From 368ab1f665ff69025f67f4d502212f118ef0eb26 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Sun, 27 Sep 2026 06:59:39 +0000 Subject: [PATCH 01/16] fix(STU-380): truthful outcomes for unreachable push/provision paths MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Devin Review on #91 flagged three places where the deploy could still misreport what FlutterFlow did: - pushCodeWithRetry flattened exhausted retries into a generic failure even when attempts ended in transport errors (the request may have been applied). Track sawTransportError/lastHttpStatus and throw an UnconfirmedDeployError when any attempt lost its response; keep a plain error only when every attempt was an HTTP refusal. An ok-but-unparseable sync response now reports unconfirmed for the same reason. - provisionMissingCodeFiles only bounded the stream read — a runner that accepts the connection but never flushes headers waited forever. Move the fetch inside the bounded wait (fetch rejection -> unconfirmed, since the POST may have landed), and stop feeding progress updates to the UI after the bound expires. - targetIdentity.projectId was only assigned after provisioning succeeded, so an unconfirmed provisioning outcome reported a null target. Assign it immediately after project validation in both executeCommit and executeBundleCommit; commitToFlutterFlow's catch now also returns unconfirmed instead of a generic failure. UnconfirmedDeployError moves to src/deployOutcome.js next to the outcome taxonomy, with exhaustedPushError encoding the transport-error rule. readProvisionResponse now converts a mid-stream read failure into the no-final-result path (unconfirmed) instead of throwing, with a comment documenting the runner contract that makes a non-2xx always definitive. Unit: exhaustedPushError covers both branches; provisionStream covers a mid-stream drop. E2e: four transport regressions drive the real fetch/ retry/timeout code against routed fixtures (stalled headers, truncated stream, all-abort push, all-500 push), each falsified against the old behaviour. Co-Authored-By: Stuart Gardoll --- app.js | 156 +++++++++++++++++++++++++++--------- e2e/stu380-deploy.spec.js | 122 +++++++++++++++++++++++++++- src/deployOutcome.js | 48 +++++++++++ src/deployOutcome.test.js | 27 +++++++ src/provisionStream.js | 52 +++++++----- src/provisionStream.test.js | 24 ++++++ 6 files changed, 370 insertions(+), 59 deletions(-) diff --git a/app.js b/app.js index 005d69b..ef2ccf9 100644 --- a/app.js +++ b/app.js @@ -65,6 +65,8 @@ import { classifyDeployResult, DeployOutcome, DEPLOY_UI_TIMEOUT_MS, + exhaustedPushError, + UnconfirmedDeployError, } from "./src/deployOutcome.js"; import { buildFlutterFlowSyncMetadata } from "./src/flutterFlowSyncMetadata.js"; import { initHeroMarkField } from "./src/heroMarkField.js"; @@ -2166,6 +2168,11 @@ class FlutterFlowApiClient { FF_API_ENDPOINTS.staging, ]; const startEndpoint = Math.max(0, endpointUrls.indexOf(this._endpoint)); + // Retried only on a lost connection or a 500, a lost response means the + // push may have been applied — exhaustion after any transport error is an + // unknown outcome, never a fabricated refusal. + let sawTransportError = false; + let lastHttpStatus = null; for (let attempt = 0; attempt < maxRetries; attempt++) { for (let ei = startEndpoint; ei < endpointUrls.length; ei++) { @@ -2198,6 +2205,7 @@ class FlutterFlowApiClient { return response; } + lastHttpStatus = response.status; const clonedForLog = response.clone(); const responseText = await clonedForLog.text(); console.log( @@ -2212,6 +2220,7 @@ class FlutterFlowApiClient { return response; } catch (error) { + sawTransportError = true; console.warn( `Push to ${baseUrl} failed: ${error.message}, trying next...`, ); @@ -2220,7 +2229,10 @@ class FlutterFlowApiClient { } } - throw new Error("All API endpoints failed after retries"); + throw exhaustedPushError({ + sawTransportError, + httpStatus: lastHttpStatus, + }); } async pushCode(pushCodeRequest) { @@ -2337,7 +2349,11 @@ async function parsePushCodeResponse(response) { }; } - throw new Error(`Invalid JSON response: ${text}`); + // HTTP ok but the body never parsed: the push request reached FlutterFlow + // and was accepted, so the remote state is unknown — not a failure. + throw new UnconfirmedDeployError( + `FlutterFlow accepted the sync but returned an unreadable response: ${text.slice(0, 200)}`, + ); } if (!response.ok) { @@ -2554,21 +2570,6 @@ function invalidateProjectSourceCache(apiClient) { projectSourceCache.delete(projectSourceCacheKey(apiClient)); } -/** - * A carve-out from the ordinary failure path: the client stopped waiting for - * (or lost the connection to) the deployment runner before it reported a - * decision, so the remote outcome is unknown. This is deliberately *not* a - * plain failure — nothing here may be reported as failed or committed when we - * cannot know what the server did. - */ -class UnconfirmedDeployError extends Error { - constructor(message) { - super(message); - this.name = "UnconfirmedDeployError"; - this.outcome = DeployOutcome.UNCONFIRMED; - } -} - /** * Bounded waiting for a remote write. The UI shows live progress only while * this promise settles; once the bound expires the waiter stops claiming @@ -2608,6 +2609,7 @@ async function provisionMissingCodeFiles( remoteFiles, commitMessage, pubspecYaml = "", + uiTimeoutMs = DEPLOY_UI_TIMEOUT_MS, ) { const missingCodeFiles = findMissingCodeFiles(fileMap, remoteFiles); if (missingCodeFiles.length === 0) { @@ -2647,34 +2649,57 @@ async function provisionMissingCodeFiles( `Provisioning ${missingCodeFiles.length} new FlutterFlow custom code file(s) before sync.`, ); commitProgress.set("provision"); - const response = await fetch(FLUTTERFLOW_CLASS_PROVISION_ENDPOINT, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ - apiKey: apiClient.apiKey, - projectId: apiClient.projectId, - baseUrl: apiClient.baseUrl, - commitMessage, - customClasses: missingCodeFiles, - verification, - stream: true, - }), - }); - + // Once the bound expires, progress updates from a late-arriving stream must + // not keep mutating a UI that already showed the terminal state. + let progressLive = true; + // The bounded wait covers the fetch itself, not just the stream body: a + // runner that accepts the connection but never flushes headers would + // otherwise hang the deploy past the UI bound. A fetch that rejects before + // any response is still an unknown outcome — the POST may have reached the + // server — so it maps to unconfirmed, not failed. const result = await withUiTimeout( - readProvisionResponse(response, { - onPhase: (message) => commitProgress.setSubstatus(message), - onLog: (message) => console.log(`[custom class deploy] ${message}`), - }), - DEPLOY_UI_TIMEOUT_MS, - (resolve, reject) => + (async () => { + let response; + try { + response = await fetch(FLUTTERFLOW_CLASS_PROVISION_ENDPOINT, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + apiKey: apiClient.apiKey, + projectId: apiClient.projectId, + baseUrl: apiClient.baseUrl, + commitMessage, + customClasses: missingCodeFiles, + verification, + stream: true, + }), + }); + } catch (fetchError) { + throw new UnconfirmedDeployError( + "The provisioning request did not return a response. The deploy may have reached the " + + "FlutterFlow server — open your FlutterFlow project to reconcile before retrying.", + ); + } + return readProvisionResponse(response, { + onPhase: (message) => { + if (progressLive) commitProgress.setSubstatus(message); + }, + onLog: (message) => { + if (progressLive) console.log(`[custom class deploy] ${message}`); + }, + }); + })(), + uiTimeoutMs, + (resolve, reject) => { + progressLive = false; reject( new UnconfirmedDeployError( "The deploy is still working on the FlutterFlow server, but this browser tab has stopped waiting. " + "Your custom classes may or may not have been written — the outcome is not yet known. " + "Open your FlutterFlow project to reconcile before retrying the deploy.", ), - ), + ); + }, ); // A stream that ended (or a body that carried) no definitive result leaves @@ -3420,6 +3445,17 @@ async function commitToFlutterFlow(dartCode, fileName, options = {}) { console.error("Commit failed:", error); commitState.setError(error); + // A lost or timed-out response after the push means the remote outcome is + // unknown — surface it as unconfirmed, never as a fabricated failure. + if (error instanceof UnconfirmedDeployError) { + return { + success: false, + unconfirmed: true, + error: error.message, + state: commitState.currentState, + }; + } + return { success: false, error: error.message, @@ -3503,6 +3539,10 @@ async function executeCommit(code, options = {}) { throw new Error("Invalid FlutterFlow Project ID format."); } + // Identity is captured as soon as the project is validated so an early + // unconfirmed outcome still names the target it was deploying to. + targetIdentity.projectId = projectId; + // Step 5: Prepare file map const fileMap = new Map(); fileMap.set(codeInfo.fileName, { @@ -3547,7 +3587,6 @@ async function executeCommit(code, options = {}) { `Provision ${artifactName} custom class`, serializedYaml, ); - targetIdentity.projectId = projectId; provisionClassesWritten = provisioning.provisionSucceeded === true; const syncMetadata = await buildApiSyncMetadata( @@ -3731,6 +3770,10 @@ async function executeBundleCommit(bundlePlan, options = {}) { throw new Error("Invalid FlutterFlow Project ID format."); } + // Identity is captured as soon as the project is validated so an early + // unconfirmed outcome still names the target it was deploying to. + targetIdentity.projectId = projectId; + commitState.setState(CommitState.PUSHING); const endpoint = getFlutterFlowEndpoint(); const apiClient = new FlutterFlowApiClient( @@ -3752,7 +3795,6 @@ async function executeBundleCommit(bundlePlan, options = {}) { `Provision ${bundlePlan.title} custom classes`, serializedYaml, ); - targetIdentity.projectId = projectId; provisionClassesWritten = provisioning.provisionSucceeded === true; const syncMetadata = await buildApiSyncMetadata( provisioning.syncFileMap, @@ -8389,6 +8431,40 @@ if (import.meta.env.DEV) { { warnings: [], ...checks }, deps || {}, ); + // Lets the browser suite drive the real provisioning transport — fetch, + // stream read and UI bound — against routed fixtures, so a stalled or + // dropped connection can be proven to resolve as unconfirmed rather than + // hanging or fabricating a failure. + window.__CCC_PROVISION_CUSTOM_CLASSES__ = ({ + fileMap, + remoteFiles, + commitMessage, + pubspecYaml, + uiTimeoutMs, + } = {}) => + provisionMissingCodeFiles( + new FlutterFlowApiClient( + "test-key", + "ff-proj-0007", + "main", + FF_API_ENDPOINTS.production, + ), + new Map(Object.entries(fileMap || {})), + new Map(Object.entries(remoteFiles || {})), + commitMessage || "Provision test class", + pubspecYaml || "", + uiTimeoutMs, + ); + // Lets the browser suite drive the real retry loop against routed endpoints, + // so transport-error exhaustion vs a definitive HTTP refusal can each be + // proven to produce their truthful outcome. + window.__CCC_PUSH_CODE_WITH_RETRY__ = (pushCodeRequest, maxRetries) => + new FlutterFlowApiClient( + "test-key", + "ff-proj-0007", + "main", + FF_API_ENDPOINTS.production, + ).pushCodeWithRetry(pushCodeRequest, maxRetries); } function copyResultsCode() { diff --git a/e2e/stu380-deploy.spec.js b/e2e/stu380-deploy.spec.js index 0b15b50..a4ae404 100644 --- a/e2e/stu380-deploy.spec.js +++ b/e2e/stu380-deploy.spec.js @@ -1,5 +1,5 @@ import { test, expect } from "@playwright/test"; -import { applyDefaultRoutes } from "./fixtures/apiFixtures.js"; +import { applyDefaultRoutes, ENDPOINTS } from "./fixtures/apiFixtures.js"; /** * STU-380 — truthful deployment terminal outcomes. @@ -289,3 +289,123 @@ test.describe("STU-380 deployment terminal outcomes", () => { ).toBeEnabled(); }); }); + +// --- Transport-level regressions (Devin Review on PR #91) ------------------- +// These drive the real provisioning exchange and push retry loop through the +// __CCC_* transport hooks against intercepted routes, so the classification of +// lost/stalled responses is exercised in the code that ships — not a mock of +// the classify step. + +async function loadDeployHooks(page) { + await page.addInitScript(() => { + localStorage.setItem("hasSeenWalkthrough", "true"); + }); + await applyDefaultRoutes(page); + await page.goto("/"); + await page.waitForFunction( + () => + typeof window.__CCC_PROVISION_CUSTOM_CLASSES__ === "function" && + typeof window.__CCC_PUSH_CODE_WITH_RETRY__ === "function", + ); +} + +const newClassFileMap = { + "gauge_model.dart": { + artifactName: "GaugeModel", + content: "class GaugeModel { final int value; GaugeModel(this.value); }", + type: "C", + path: "lib/custom_code/gauge_model.dart", + }, +}; + +async function settleAsOutcome(page, hook, args) { + return page.evaluate( + async ({ hook, args }) => { + try { + await window[hook](...args); + return { settled: "resolved" }; + } catch (error) { + return { + settled: "rejected", + name: error.name, + outcome: error.outcome, + message: error.message, + }; + } + }, + { hook, args }, + ); +} + +test.describe("STU-380 transport outcome regressions", () => { + test("a provisioning request that never gets headers hits the UI bound and reports unconfirmed", async ({ page }) => { + await loadDeployHooks(page); + // The runner accepts the connection but never flushes response headers — + // this must still resolve inside the UI bound, not hang the deploy. + await page.route(ENDPOINTS.deployCustomClasses, () => new Promise(() => {})); + + const outcome = await settleAsOutcome( + page, + "__CCC_PROVISION_CUSTOM_CLASSES__", + [{ fileMap: newClassFileMap, uiTimeoutMs: 60 }], + ); + + expect(outcome.settled).toBe("rejected"); + expect(outcome.name).toBe("UnconfirmedDeployError"); + expect(outcome.outcome).toBe("unconfirmed"); + }); + + test("a provisioning stream that ends without a result is unconfirmed, not failed", async ({ page }) => { + await loadDeployHooks(page); + await page.route(ENDPOINTS.deployCustomClasses, async (route) => { + await route.fulfill({ + status: 200, + contentType: "application/x-ndjson", + body: '{"event":"phase","phase":"deploying","message":"Deploying..."}\n', + }); + }); + + const outcome = await settleAsOutcome( + page, + "__CCC_PROVISION_CUSTOM_CLASSES__", + [{ fileMap: newClassFileMap }], + ); + + expect(outcome.name).toBe("UnconfirmedDeployError"); + expect(outcome.outcome).toBe("unconfirmed"); + }); + + test("a push that loses every response is unconfirmed, not a fabricated partial/failure", async ({ page }) => { + await loadDeployHooks(page); + // Both sync endpoints drop the request without a response — the push may + // have reached FlutterFlow, so the outcome is unknown. + await page.route("**/syncCustomCodeChanges", (route) => route.abort()); + + const outcome = await settleAsOutcome( + page, + "__CCC_PUSH_CODE_WITH_RETRY__", + [{ project_id: "ff-proj-0007", zipped_custom_code: "eA==" }, 1], + ); + + expect(outcome.settled).toBe("rejected"); + expect(outcome.name).toBe("UnconfirmedDeployError"); + expect(outcome.outcome).toBe("unconfirmed"); + }); + + test("a push refused with HTTP errors on every endpoint is a definitive failure", async ({ page }) => { + await loadDeployHooks(page); + await page.route("**/syncCustomCodeChanges", async (route) => { + await route.fulfill({ status: 500, body: "server error" }); + }); + + const outcome = await settleAsOutcome( + page, + "__CCC_PUSH_CODE_WITH_RETRY__", + [{ project_id: "ff-proj-0007", zipped_custom_code: "eA==" }, 1], + ); + + expect(outcome.settled).toBe("rejected"); + expect(outcome.name).not.toBe("UnconfirmedDeployError"); + expect(outcome.message).toContain("HTTP 500"); + }); +}); diff --git a/src/deployOutcome.js b/src/deployOutcome.js index abaa037..46386bd 100644 --- a/src/deployOutcome.js +++ b/src/deployOutcome.js @@ -63,3 +63,51 @@ export function classifyDeployResult(result) { } return DeployOutcome.FAILED; } + +/** + * A carve-out from the ordinary failure path: the client stopped waiting for + * (or lost the connection to) a remote write before a decision arrived, so the + * remote outcome is unknown. This is deliberately *not* a plain failure — + * nothing may be reported as failed or committed when we cannot know what the + * server did. Callers recognise it with `instanceof` or the `outcome` field, + * both of which `classifyDeployResult` maps to UNCONFIRMED. + */ +export class UnconfirmedDeployError extends Error { + constructor(message) { + super(message); + this.name = "UnconfirmedDeployError"; + this.outcome = DeployOutcome.UNCONFIRMED; + } +} + +/** + * Builds the error thrown when a push to FlutterFlow has retried every + * endpoint without a definitive answer. + * + * The deciding question is whether any attempt *may have reached* the server: + * a transport error — the fetch rejected before a response arrived — cannot + * prove the write did not land, because a connection can drop after the server + * accepted the request. Exhaustion is therefore UNCONFIRMED if any attempt + * ended that way; only attempts that all came back as HTTP rejections are a + * definitive refusal and may be reported as failed. + * + * @param {Object} [attempts] + * @param {boolean} [attempts.sawTransportError] - True when at least one + * attempt failed without an HTTP response + * @param {number} [attempts.httpStatus] - Last HTTP status the server + * returned, when it returned one + * @returns {Error} An UnconfirmedDeployError for a lost response, a plain + * Error for a definitive refusal + */ +export function exhaustedPushError({ sawTransportError, httpStatus } = {}) { + if (sawTransportError) { + return new UnconfirmedDeployError( + "Every FlutterFlow sync endpoint stopped answering without a definitive " + + "response. The push may still have been applied — open the FlutterFlow " + + "project to reconcile before retrying.", + ); + } + return new Error( + `FlutterFlow rejected the code sync${httpStatus ? ` (HTTP ${httpStatus})` : ""} after every retry.`, + ); +} diff --git a/src/deployOutcome.test.js b/src/deployOutcome.test.js index b9c7e2d..5ef990c 100644 --- a/src/deployOutcome.test.js +++ b/src/deployOutcome.test.js @@ -4,6 +4,8 @@ import { classifyDeployResult, DeployOutcome, DEPLOY_UI_TIMEOUT_MS, + exhaustedPushError, + UnconfirmedDeployError, } from "./deployOutcome.js"; // --- Falsification harness ------------------------------------------------- @@ -86,6 +88,31 @@ test("an unconfirmed marker beats every other signal", () => { ); }); +test("push retries exhausted by a lost response are unconfirmed, never a fabricated failure", () => { + // At least one attempt rejected without an HTTP response: the write may have + // reached FlutterFlow, so the terminal outcome must be UNCONFIRMED — a plain + // failure would lie about a deploy that might have committed. + const error = exhaustedPushError({ sawTransportError: true }); + assert.ok(error instanceof UnconfirmedDeployError); + assert.equal(error.outcome, DeployOutcome.UNCONFIRMED); + assert.equal(classifyDeployResult({ outcome: error.outcome }), DeployOutcome.UNCONFIRMED); + + // Falsification: marking the same exhaustion as a definitive refusal must + // flip the outcome it produces. + assert.equal( + exhaustedPushError({ sawTransportError: false }) instanceof UnconfirmedDeployError, + false, + ); +}); + +test("push retries refused on every endpoint are a definitive failure", () => { + const error = exhaustedPushError({ sawTransportError: false, httpStatus: 500 }); + assert.equal(error instanceof UnconfirmedDeployError, false); + assert.match(error.message, /HTTP 500/); + // And the result shape it drives classifies as FAILED, not UNCONFIRMED. + assert.equal(classifyDeployResult({ success: false, error: error.message }), DeployOutcome.FAILED); +}); + test("the UI waiting bound is finite and below the documented server deadline", () => { // Cloud Run's request timeout is 900s; the UI bound must be shorter so the // UI never out-waits a real server decision, and positive so it actually diff --git a/src/provisionStream.js b/src/provisionStream.js index 5a23fee..d5844df 100644 --- a/src/provisionStream.js +++ b/src/provisionStream.js @@ -40,26 +40,37 @@ export async function readProvisionResponse(response, handlers = {}) { finalResult = event; }; - if (response.body?.getReader) { - const reader = response.body.getReader(); - const decoder = new TextDecoder(); + // A mid-stream read failure is a dropped connection, not a decision from + // the runner: it falls through to the no-final-result return below so the + // caller reports the outcome as unknown rather than throwing a fabricated + // failure. + let readError = null; + try { + if (response.body?.getReader) { + const reader = response.body.getReader(); + const decoder = new TextDecoder(); - while (true) { - const { done, value } = await reader.read(); - if (done) break; - const parsed = readNdjsonChunk( - buffer, - decoder.decode(value, { stream: true }), - ); + while (true) { + const { done, value } = await reader.read(); + if (done) break; + const parsed = readNdjsonChunk( + buffer, + decoder.decode(value, { stream: true }), + ); + buffer = parsed.buffer; + parsed.events.forEach(handleEvent); + } + } else { + const parsed = readNdjsonChunk("", await response.text()); buffer = parsed.buffer; parsed.events.forEach(handleEvent); } - } else { - const parsed = readNdjsonChunk("", await response.text()); - buffer = parsed.buffer; - parsed.events.forEach(handleEvent); + } catch (error) { + readError = error; } + // Whatever arrived before the drop may still hold a complete trailing line — + // the result event itself — so the remainder is flushed before giving up. flushNdjsonBuffer(buffer).forEach(handleEvent); if (finalResult) { @@ -78,12 +89,17 @@ export async function readProvisionResponse(response, handlers = {}) { // An explicit non-2xx HTTP response is a definitive server refusal, not an // unknown outcome. The caller must render it as FAILED; only an ok response // whose stream dropped before a result leaves the remote state genuinely - // unknown (UNCONFIRMED). + // unknown (UNCONFIRMED). This holds for the deploy runner: once streaming + // begins it emits every post-work failure as a `result` event under the + // already-sent 200 status, so a non-2xx can only arrive before the first + // remote write. httpRejected: !response.ok, httpStatus: response.status, - error: response.ok - ? "The FlutterFlow deploy runner closed the connection before it finished." - : `FlutterFlow custom class provisioning failed (HTTP ${response.status}).`, + error: readError + ? "The connection to the FlutterFlow deploy runner dropped before it reported a result." + : response.ok + ? "The FlutterFlow deploy runner closed the connection before it finished." + : `FlutterFlow custom class provisioning failed (HTTP ${response.status}).`, }; } diff --git a/src/provisionStream.test.js b/src/provisionStream.test.js index 4b01ce0..16fb777 100644 --- a/src/provisionStream.test.js +++ b/src/provisionStream.test.js @@ -185,6 +185,30 @@ test("a dropped stream on an OK response stays UNCONFIRMED (outcome truly unknow ); }); +test("a mid-stream read failure is an unknown outcome, not a thrown error", async () => { + const encoder = new TextEncoder(); + const body = new ReadableStream({ + start(controller) { + controller.enqueue( + encoder.encode( + '{"event":"phase","phase":"deploying","message":"Deploying..."}\n', + ), + ); + controller.error(new Error("network reset")); + }, + }); + + const result = await readProvisionResponse(new Response(body, { status: 200 })); + + // The connection died mid-work: no result arrived, so the remote outcome is + // unknown — UNCONFIRMED, never a fabricated failure. + assert.equal(result.success, false); + assert.equal(result.finalResultReceived, false); + assert.equal(result.httpRejected, false); + assert.match(result.error, /dropped/); + assert.equal(deployOutcomeOfStreamResult(result), DeployOutcome.UNCONFIRMED); +}); + test("a delivered result is classified by the ordinary rule, not the rejection carve-out", async () => { const shipped = await readProvisionResponse( provisionAtStatus( From 33f5880ee48fce3336d890e12d7708b2fa9fb08a Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Sun, 27 Sep 2026 07:07:06 +0000 Subject: [PATCH 02/16] fix(STU-380): classify dropped bodies on their status, not their read error Devin Review on #99 flagged that a response body lost mid-flight shared the wrong catch in two places: - parsePushCodeResponse awaited the clone's text() unguarded, so an ok response whose body never arrived propagated a raw read error -> rendered failed/partial instead of unconfirmed. The read is now best-effort: a non-ok status still returns a definitive failure; an ok status throws UnconfirmedDeployError even when nothing of the body survived. - pushCodeWithRetry read the error body inside the same try as fetch, so a body read failure set sawTransportError and could send a non-500 refusal back through the retry loop. fetch rejections are now the only thing that marks a transport error; the logging read is best-effort and non-500 statuses return immediately. E2e: a 200/500 whose body resets mid-read classify on their status (unconfirmed vs failed), a 500 with an unreadable body is reported as the known refusal rather than an unknown outcome, and a 403 is never retried. Co-Authored-By: Stuart Gardoll --- app.js | 70 ++++++++++++++------- e2e/stu380-deploy.spec.js | 126 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 173 insertions(+), 23 deletions(-) diff --git a/app.js b/app.js index ef2ccf9..a1631e2 100644 --- a/app.js +++ b/app.js @@ -2178,6 +2178,11 @@ class FlutterFlowApiClient { for (let ei = startEndpoint; ei < endpointUrls.length; ei++) { const baseUrl = endpointUrls[ei]; + // Only a fetch rejection is a transport error: once response headers + // arrive the status is a definitive answer, and a body that fails to + // read for logging must not reclassify a known refusal as a lost + // response (or send a non-500 refusal back through the retry loop). + let response; try { console.log( `Push attempt ${attempt + 1} to ${baseUrl}syncCustomCodeChanges`, @@ -2191,7 +2196,7 @@ class FlutterFlowApiClient { file_map_length: pushCodeRequest.file_map?.length || 0, functions_map_length: pushCodeRequest.functions_map?.length || 0, }); - const response = await fetch(`${baseUrl}syncCustomCodeChanges`, { + response = await fetch(`${baseUrl}syncCustomCodeChanges`, { method: "POST", headers: { "Content-Type": "application/json", @@ -2199,33 +2204,38 @@ class FlutterFlowApiClient { }, body: JSON.stringify(pushCodeRequest), }); - - if (response.ok) { - console.log(`Push to ${baseUrl} succeeded!`); - return response; - } - - lastHttpStatus = response.status; - const clonedForLog = response.clone(); - const responseText = await clonedForLog.text(); - console.log( - `Push to ${baseUrl} returned ${response.status}: ${responseText}`, - ); - - if (response.status === 500) { - console.warn(`Endpoint ${baseUrl} returned 500, trying next...`); - await new Promise((r) => setTimeout(r, 1000 * (attempt + 1))); - continue; - } - - return response; } catch (error) { sawTransportError = true; console.warn( `Push to ${baseUrl} failed: ${error.message}, trying next...`, ); await new Promise((r) => setTimeout(r, 1000 * (attempt + 1))); + continue; + } + + if (response.ok) { + console.log(`Push to ${baseUrl} succeeded!`); + return response; + } + + lastHttpStatus = response.status; + let responseText; + try { + responseText = await response.clone().text(); + } catch (readError) { + responseText = "(unreadable response body)"; + } + console.log( + `Push to ${baseUrl} returned ${response.status}: ${responseText}`, + ); + + if (response.status === 500) { + console.warn(`Endpoint ${baseUrl} returned 500, trying next...`); + await new Promise((r) => setTimeout(r, 1000 * (attempt + 1))); + continue; } + + return response; } } @@ -2337,7 +2347,16 @@ async function parsePushCodeResponse(response) { try { jsonResult = await response.json(); } catch (error) { - const text = await originalResponse.text(); + // Both reads share the same connection: a body dropped mid-flight makes + // the clone reject too. The received status is still definitive — a non-ok + // response is a refusal, an ok one means the push may have been applied + // before the body was lost. + let text = ""; + try { + text = await originalResponse.text(); + } catch (readError) { + // The body never arrived; classify on the status alone. + } // Check if the response was an error with plain text body (common for 500s) if (!response.ok) { @@ -2352,7 +2371,7 @@ async function parsePushCodeResponse(response) { // HTTP ok but the body never parsed: the push request reached FlutterFlow // and was accepted, so the remote state is unknown — not a failure. throw new UnconfirmedDeployError( - `FlutterFlow accepted the sync but returned an unreadable response: ${text.slice(0, 200)}`, + `FlutterFlow accepted the sync but returned an unreadable response${text ? `: ${text.slice(0, 200)}` : "."}`, ); } @@ -8465,6 +8484,11 @@ if (import.meta.env.DEV) { "main", FF_API_ENDPOINTS.production, ).pushCodeWithRetry(pushCodeRequest, maxRetries); + // Lets the browser suite feed a crafted Response into the real sync-response + // parser, so a body that drops mid-read can be proven to classify on the + // received status instead of leaking the raw read error. + window.__CCC_PARSE_PUSH_RESPONSE__ = (response) => + parsePushCodeResponse(response); } function copyResultsCode() { diff --git a/e2e/stu380-deploy.spec.js b/e2e/stu380-deploy.spec.js index a4ae404..a8acc5b 100644 --- a/e2e/stu380-deploy.spec.js +++ b/e2e/stu380-deploy.spec.js @@ -408,4 +408,130 @@ test.describe("STU-380 transport outcome regressions", () => { expect(outcome.name).not.toBe("UnconfirmedDeployError"); expect(outcome.message).toContain("HTTP 500"); }); + + test("a sync response whose body drops mid-read is unconfirmed, not failed", async ({ page }) => { + await loadDeployHooks(page); + + // A 200 arrives, then the connection resets before the JSON completes: + // response.json() rejects AND the clone's text() rejects — both share the + // dead source. The accepted status means the push may have been applied. + const outcome = await page.evaluate(async () => { + const body = new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode('{"succ')); + controller.error(new Error("connection reset")); + }, + }); + try { + await window.__CCC_PARSE_PUSH_RESPONSE__( + new Response(body, { status: 200 }), + ); + return { settled: "resolved" }; + } catch (error) { + return { + settled: "rejected", + name: error.name, + outcome: error.outcome, + message: error.message, + }; + } + }); + + expect(outcome.settled).toBe("rejected"); + expect(outcome.name).toBe("UnconfirmedDeployError"); + expect(outcome.outcome).toBe("unconfirmed"); + }); + + test("a refusal whose body drops mid-read is still a definitive failure", async ({ page }) => { + await loadDeployHooks(page); + + const outcome = await page.evaluate(async () => { + const body = new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode("{")); + controller.error(new Error("connection reset")); + }, + }); + try { + const parsed = await window.__CCC_PARSE_PUSH_RESPONSE__( + new Response(body, { status: 500 }), + ); + return { settled: "resolved", parsed }; + } catch (error) { + return { settled: "rejected", name: error.name, message: error.message }; + } + }); + + expect(outcome.settled).toBe("resolved"); + expect(outcome.parsed.success).toBe(false); + expect(outcome.parsed.responseCode).toBe(500); + }); + + test("a refusal with an unreadable body is not mistaken for a lost response", async ({ page }) => { + await loadDeployHooks(page); + + // Every endpoint replies 500 but closes its body early: the statuses are + // definitive answers, so exhaustion must report the refusal — not claim + // the push outcome is unknown because a logging read failed. + const outcome = await page.evaluate(async () => { + const stubBody = () => + new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode("x")); + controller.error(new Error("connection reset")); + }, + }); + window.fetch = () => + Promise.resolve(new Response(stubBody(), { status: 500 })); + try { + await window.__CCC_PUSH_CODE_WITH_RETRY__( + { project_id: "ff-proj-0007", zipped_custom_code: "eA==" }, + 1, + ); + return { settled: "resolved" }; + } catch (error) { + return { + settled: "rejected", + name: error.name, + outcome: error.outcome, + message: error.message, + }; + } + }); + + expect(outcome.settled).toBe("rejected"); + expect(outcome.name).not.toBe("UnconfirmedDeployError"); + expect(outcome.message).toContain("HTTP 500"); + }); + + test("a non-500 refusal is never sent back through the retry loop", async ({ page }) => { + await loadDeployHooks(page); + + // A definitive 403 must not be retried — even when its body is unreadable. + const outcome = await page.evaluate(async () => { + let calls = 0; + const stubBody = () => + new ReadableStream({ + start(controller) { + controller.error(new Error("connection reset")); + }, + }); + window.fetch = () => { + calls += 1; + return Promise.resolve(new Response(stubBody(), { status: 403 })); + }; + try { + await window.__CCC_PUSH_CODE_WITH_RETRY__( + { project_id: "ff-proj-0007", zipped_custom_code: "eA==" }, + 3, + ); + return { settled: "resolved", calls }; + } catch (error) { + return { settled: "rejected", calls, name: error.name }; + } + }); + + expect(outcome.settled).toBe("resolved"); + expect(outcome.calls).toBe(1); + }); }); From eafd7ff247a7d8c29058e6a1ed5112c2d8fe2240 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Sun, 27 Sep 2026 07:19:06 +0000 Subject: [PATCH 03/16] fix(STU-380): drop the cached project snapshot on unconfirmed provisioning MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Devin Review on #99: a provisioning request that ends unconfirmed (UI bound expired, fetch rejected, stream dropped before a result) may still have written classes on the runner, but resolveProjectPubspec's cached export predates them — the next deploy would read the stale snapshot and provision the same class again. provisionMissingCodeFiles now wraps the bounded wait and result classification in a catch that invalidates the project source cache whenever the thrown error is UnconfirmedDeployError; definitive refusals (plain Error, no write happened) keep the cache. E2e: seed the cache via __CCC_RESOLVE_PROJECT_PUBSPEC__ (exportCode routed), stall provisioning past the UI bound, then resolve again — the export must run a second time. Falsified: without the invalidation the second resolve hits the cache. Co-Authored-By: Stuart Gardoll --- app.js | 148 +++++++++++++++++++++++--------------- e2e/stu380-deploy.spec.js | 44 ++++++++++++ 2 files changed, 133 insertions(+), 59 deletions(-) diff --git a/app.js b/app.js index a1631e2..67bcb9e 100644 --- a/app.js +++ b/app.js @@ -2676,70 +2676,82 @@ async function provisionMissingCodeFiles( // otherwise hang the deploy past the UI bound. A fetch that rejects before // any response is still an unknown outcome — the POST may have reached the // server — so it maps to unconfirmed, not failed. - const result = await withUiTimeout( - (async () => { - let response; - try { - response = await fetch(FLUTTERFLOW_CLASS_PROVISION_ENDPOINT, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ - apiKey: apiClient.apiKey, - projectId: apiClient.projectId, - baseUrl: apiClient.baseUrl, - commitMessage, - customClasses: missingCodeFiles, - verification, - stream: true, - }), + let result; + try { + result = await withUiTimeout( + (async () => { + let response; + try { + response = await fetch(FLUTTERFLOW_CLASS_PROVISION_ENDPOINT, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + apiKey: apiClient.apiKey, + projectId: apiClient.projectId, + baseUrl: apiClient.baseUrl, + commitMessage, + customClasses: missingCodeFiles, + verification, + stream: true, + }), + }); + } catch (fetchError) { + throw new UnconfirmedDeployError( + "The provisioning request did not return a response. The deploy may have reached the " + + "FlutterFlow server — open your FlutterFlow project to reconcile before retrying.", + ); + } + return readProvisionResponse(response, { + onPhase: (message) => { + if (progressLive) commitProgress.setSubstatus(message); + }, + onLog: (message) => { + if (progressLive) console.log(`[custom class deploy] ${message}`); + }, }); - } catch (fetchError) { - throw new UnconfirmedDeployError( - "The provisioning request did not return a response. The deploy may have reached the " + - "FlutterFlow server — open your FlutterFlow project to reconcile before retrying.", + })(), + uiTimeoutMs, + (resolve, reject) => { + progressLive = false; + reject( + new UnconfirmedDeployError( + "The deploy is still working on the FlutterFlow server, but this browser tab has stopped waiting. " + + "Your custom classes may or may not have been written — the outcome is not yet known. " + + "Open your FlutterFlow project to reconcile before retrying the deploy.", + ), ); - } - return readProvisionResponse(response, { - onPhase: (message) => { - if (progressLive) commitProgress.setSubstatus(message); - }, - onLog: (message) => { - if (progressLive) console.log(`[custom class deploy] ${message}`); - }, - }); - })(), - uiTimeoutMs, - (resolve, reject) => { - progressLive = false; - reject( - new UnconfirmedDeployError( - "The deploy is still working on the FlutterFlow server, but this browser tab has stopped waiting. " + - "Your custom classes may or may not have been written — the outcome is not yet known. " + - "Open your FlutterFlow project to reconcile before retrying the deploy.", - ), - ); - }, - ); + }, + ); - // A stream that ended (or a body that carried) no definitive result leaves - // the remote decision ambiguous. There are two distinct cases which must not - // be flattened: a server that explicitly refused the request (a 403/5xx - // `response.ok === false`) has made a definitive decision — the write did not - // happen — so that is a FAILURE, not an unknown outcome; only an ok response - // whose stream dropped before a result (or a client wait expiry) leaves the - // remote state genuinely unknown and must be reported UNCONFIRMED. - if (!result.finalResultReceived) { - if (deployOutcomeOfStreamResult(result) === DeployOutcome.FAILED) { - throw new Error( - result.error || - `FlutterFlow custom class provisioning failed (HTTP ${result.httpStatus}).`, + // A stream that ended (or a body that carried) no definitive result leaves + // the remote decision ambiguous. There are two distinct cases which must not + // be flattened: a server that explicitly refused the request (a 403/5xx + // `response.ok === false`) has made a definitive decision — the write did not + // happen — so that is a FAILURE, not an unknown outcome; only an ok response + // whose stream dropped before a result (or a client wait expiry) leaves the + // remote state genuinely unknown and must be reported UNCONFIRMED. + if (!result.finalResultReceived) { + if (deployOutcomeOfStreamResult(result) === DeployOutcome.FAILED) { + throw new Error( + result.error || + `FlutterFlow custom class provisioning failed (HTTP ${result.httpStatus}).`, + ); + } + throw new UnconfirmedDeployError( + "The connection to the FlutterFlow deploy runner dropped before it reported a result. " + + "The deploy may still be finishing on the server; open your FlutterFlow project to reconcile " + + "before retrying.", ); } - throw new UnconfirmedDeployError( - "The connection to the FlutterFlow deploy runner dropped before it reported a result. " + - "The deploy may still be finishing on the server; open your FlutterFlow project to reconcile " + - "before retrying.", - ); + } catch (error) { + // An unconfirmed provisioning may have written classes on the runner after + // the client stopped waiting, so the cached pre-write project snapshot is + // stale — a later deploy must re-read the project instead of provisioning + // the same classes a second time. + if (error instanceof UnconfirmedDeployError) { + invalidateProjectSourceCache(apiClient); + } + throw error; } if (!result.success) { @@ -8489,6 +8501,24 @@ if (import.meta.env.DEV) { // received status instead of leaking the raw read error. window.__CCC_PARSE_PUSH_RESPONSE__ = (response) => parsePushCodeResponse(response); + // Lets the browser suite seed/observe the project-source cache: a deploy + // that lost its provisioning result must leave the cache empty so the next + // one re-reads the project instead of re-provisioning written classes. + window.__CCC_RESOLVE_PROJECT_PUBSPEC__ = async (deps) => { + const result = await resolveProjectPubspec( + new FlutterFlowApiClient( + "test-key", + "ff-proj-0007", + "main", + FF_API_ENDPOINTS.production, + ), + deps || {}, + ); + return { + remoteFilePaths: [...result.remoteFiles.keys()], + added: result.added, + }; + }; } function copyResultsCode() { diff --git a/e2e/stu380-deploy.spec.js b/e2e/stu380-deploy.spec.js index a8acc5b..3ba3694 100644 --- a/e2e/stu380-deploy.spec.js +++ b/e2e/stu380-deploy.spec.js @@ -1,4 +1,5 @@ import { test, expect } from "@playwright/test"; +import JSZip from "jszip"; import { applyDefaultRoutes, ENDPOINTS } from "./fixtures/apiFixtures.js"; /** @@ -534,4 +535,47 @@ test.describe("STU-380 transport outcome regressions", () => { expect(outcome.settled).toBe("resolved"); expect(outcome.calls).toBe(1); }); + + test("an unconfirmed provisioning drops the cached project snapshot", async ({ page }) => { + await loadDeployHooks(page); + + const zip = new JSZip(); + zip.file( + "pubspec.yaml", + "name: my_app\n\ndependencies:\n flutter:\n sdk: flutter\n", + ); + const projectZip = await zip.generateAsync({ type: "base64" }); + + let exportCalls = 0; + await page.route("**/exportCode", async (route) => { + exportCalls += 1; + await route.fulfill({ + status: 200, + contentType: "application/json", + body: JSON.stringify({ value: { project_zip: projectZip } }), + }); + }); + // The runner accepts the connection but never answers — the outcome is + // unconfirmed while it may still write the class server-side. + await page.route(ENDPOINTS.deployCustomClasses, () => new Promise(() => {})); + + // Seed the project-source cache exactly like a deploy's pubspec merge does. + const seeded = await page.evaluate(() => + window.__CCC_RESOLVE_PROJECT_PUBSPEC__({}), + ); + expect(seeded.remoteFilePaths).toEqual([]); + expect(exportCalls).toBe(1); + + const outcome = await settleAsOutcome( + page, + "__CCC_PROVISION_CUSTOM_CLASSES__", + [{ fileMap: newClassFileMap, uiTimeoutMs: 60 }], + ); + expect(outcome.name).toBe("UnconfirmedDeployError"); + + // The next deploy must re-export the project — a stale snapshot would lack + // gauge_model.dart and provision it a second time. + await page.evaluate(() => window.__CCC_RESOLVE_PROJECT_PUBSPEC__({})); + expect(exportCalls).toBe(2); + }); }); From c74d7cfa2f0b465f8c9686b0982524564f14c590 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Sun, 27 Sep 2026 07:22:27 +0000 Subject: [PATCH 04/16] test(STU-380): deliver the phase chunk before the mid-stream drop MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Devin Review: erroring a stream synchronously after enqueue() discards the queued chunk (per the Streams spec, error() clears the internal queue), so the test could only exercise a pre-first-chunk failure. Error in pull() instead so the phase event is delivered, then the connection drops — and assert onPhase received it, pinning the mid-stream path. Co-Authored-By: Stuart Gardoll --- src/provisionStream.test.js | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/provisionStream.test.js b/src/provisionStream.test.js index 16fb777..734da45 100644 --- a/src/provisionStream.test.js +++ b/src/provisionStream.test.js @@ -187,6 +187,9 @@ test("a dropped stream on an OK response stays UNCONFIRMED (outcome truly unknow test("a mid-stream read failure is an unknown outcome, not a thrown error", async () => { const encoder = new TextEncoder(); + // Error in pull(), not start(): error() discards queued-but-unread chunks, + // so erroring synchronously would only exercise a drop before the first + // chunk. Pull-based erroring delivers the phase event, then drops mid-stream. const body = new ReadableStream({ start(controller) { controller.enqueue( @@ -194,12 +197,20 @@ test("a mid-stream read failure is an unknown outcome, not a thrown error", asyn '{"event":"phase","phase":"deploying","message":"Deploying..."}\n', ), ); + }, + pull(controller) { controller.error(new Error("network reset")); }, }); - const result = await readProvisionResponse(new Response(body, { status: 200 })); + const phases = []; + const result = await readProvisionResponse(new Response(body, { status: 200 }), { + onPhase: (message) => phases.push(message), + }); + // The phase event was delivered before the drop — this is the mid-stream + // case, not a connection that never produced data. + assert.deepEqual(phases, ["Deploying..."]); // The connection died mid-work: no result arrived, so the remote outcome is // unknown — UNCONFIRMED, never a fabricated failure. assert.equal(result.success, false); From 606aaa6c83df70e88a6194686352ab5b3966079d Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Sun, 27 Sep 2026 17:00:31 +0000 Subject: [PATCH 05/16] fix(STU-380): surface definitive deploy failures in the terminal modal MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit #step3-output sits inside permanently-hidden legacy containers, so showCommitFailureModal painted the refusal where no user could see it — the progress overlay closed and nothing appeared. A definitive rejection now also populates the shared commit-terminal-modal (same identity rows, per-file outcomes, and guidance as partial/unconfirmed); the hidden step3-output render stays for the regenerate wiring and legacy readers. Found while driving the real confirm flow in the browser: a provisioning HTTP 500 classified correctly as FAILED but produced zero visible UI. Co-Authored-By: Stuart Gardoll --- app.js | 29 ++-- .../{index-CUvr1G9X.js => index-DSl339_I.js} | 130 +++++++++--------- dist/index.html | 2 +- e2e/stu380-deploy.spec.js | 22 +++ 4 files changed, 109 insertions(+), 74 deletions(-) rename dist/assets/{index-CUvr1G9X.js => index-DSl339_I.js} (65%) diff --git a/app.js b/app.js index 67bcb9e..b06bdec 100644 --- a/app.js +++ b/app.js @@ -6754,20 +6754,33 @@ function showCommitSuccessModal(result) { if (modal) openModal(modal); } +// #step3-output lives inside permanently-hidden legacy containers, so writing +// the failure only there shows the user nothing — the overlay closes and no +// terminal appears. A definitive refusal therefore also populates the shared +// terminal modal; the hidden render stays for the regenerate wiring and any +// legacy surface still reading it. function showCommitFailureModal(result) { hideCommitProgress(); showCommitError(result); + populateCommitTerminalModal(result, { + heading: "Deploy failed", + title: + "FlutterFlow refused this deploy — nothing was confirmed written.", + guidance: + "Review the error and any per-file outcomes above, fix them in your code or in FlutterFlow, then deploy again. " + + "A refusal is definitive: no part of this deploy was applied, so retrying is safe once the problem is fixed.", + }); } /** - * Populates the shared terminal modal for the two outcomes that are real but - * are neither a clean success nor a clean failure: PARTIAL (some custom - * classes were written, the remaining sync failed) and UNCONFIRMED (the remote - * outcome is unknown because the client stopped waiting or the stream - * dropped). It always shows the same target identity the user confirmed, the - * per-file outcomes when the runner/push reported them, and reconciliation - * guidance that never hides the manual FlutterFlow step of checking the - * project. + * Populates the shared terminal modal for every outcome that is not a clean + * success: PARTIAL (some custom classes were written, the remaining sync + * failed), UNCONFIRMED (the remote outcome is unknown because the client + * stopped waiting or the stream dropped), and FAILED (a definitive refusal — + * nothing confirmed written). It always shows the same target identity the + * user confirmed, the per-file outcomes when the runner/push reported them, + * and reconciliation guidance that never hides the manual FlutterFlow step of + * checking the project. */ function populateCommitTerminalModal(result, { heading, title, guidance }) { const identity = result.targetIdentity || {}; diff --git a/dist/assets/index-CUvr1G9X.js b/dist/assets/index-DSl339_I.js similarity index 65% rename from dist/assets/index-CUvr1G9X.js rename to dist/assets/index-DSl339_I.js index b407a59..cdeb08e 100644 --- a/dist/assets/index-CUvr1G9X.js +++ b/dist/assets/index-DSl339_I.js @@ -1,8 +1,8 @@ -(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const s of r)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function n(r){const s={};return r.integrity&&(s.integrity=r.integrity),r.referrerPolicy&&(s.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?s.credentials="include":r.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function i(r){if(r.ep)return;r.ep=!0;const s=n(r);fetch(r.href,s)}})();var w=typeof window<"u"?window:void 0,Le=typeof globalThis<"u"?globalThis:w,Ue=Le?.navigator,F=Le?.document,me=Le?.location,Xa=Le?.fetch,zo=Le!=null&&Le.XMLHttpRequest&&"withCredentials"in new Le.XMLHttpRequest?Le.XMLHttpRequest:void 0,uc=Le?.AbortController,Tp=Le?.CompressionStream,Ge=Ue?.userAgent;function cd(){return!(!w||w.navigator.onLine===!1)}var vi=typeof globalThis<"u"?globalThis:w;vi&&typeof self>"u"&&(vi.self=vi),vi&&typeof File>"u"&&(vi.File=function(){});var B=w??{},ne={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function dc(t,e,n,i,r,s,o){try{var a=t[s](o),l=a.value}catch(u){return void n(u)}a.done?e(l):Promise.resolve(l).then(i,r)}function se(t){return function(){var e=this,n=arguments;return new Promise((function(i,r){var s=t.apply(e,n);function o(l){dc(s,i,r,o,a,"next",l)}function a(l){dc(s,i,r,o,a,"throw",l)}o(void 0)}))}}function k(){return k=Object.assign?Object.assign.bind():function(t){for(var e=1;arguments.length>e;e++){var n=arguments[e];for(var i in n)({}).hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},k.apply(null,arguments)}function ud(t,e){if(t==null)return{};var n={};for(var i in t)if({}.hasOwnProperty.call(t,i)){if(e.indexOf(i)!==-1)continue;n[i]=t[i]}return n}var fc=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function hc(t){return typeof t=="string"||t}function pc(t){return typeof t=="string"?t:void 0}var _i,$p=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],jt=(function(t){return t.AnonymousId="anonymous_id",t.DistinctId="distinct_id",t.Props="props",t.EnablePersonProcessing="enable_person_processing",t.PersonMode="person_mode",t.FeatureFlagDetails="feature_flag_details",t.FeatureFlags="feature_flags",t.FeatureFlagPayloads="feature_flag_payloads",t.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",t.BootstrapFeatureFlags="bootstrap_feature_flags",t.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",t.OverrideFeatureFlags="override_feature_flags",t.Queue="queue",t.AiQueue="ai_queue",t.LogsQueue="logs_queue",t.OptedOut="opted_out",t.SessionId="session_id",t.SessionStartTimestamp="session_start_timestamp",t.SessionLastTimestamp="session_timestamp",t.PersonProperties="person_properties",t.GroupProperties="group_properties",t.InstalledAppBuild="installed_app_build",t.InstalledAppVersion="installed_app_version",t.SessionReplay="session_replay",t.PushRegistered="push_registered",t.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",t.SurveyLastSeenDate="survey_last_seen_date",t.SurveysSeen="surveys_seen",t.Surveys="surveys",t.RemoteConfig="remote_config",t.FlagsEndpointWasHit="flags_endpoint_was_hit",t.DeviceId="device_id",t})({}),gc=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),Mp=["$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"],Lp=["token"],dd="NativeGzipValidationError",Go=t=>t.length>=2&&t[0]===31&&t[1]===139,mc=(t,e)=>t===gc.GZipJS||e===gc.GZipJS||e==="gzip",vc=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",hr=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=dd,e},Np=(function(){var t=se((function*(e,n){18>e.size&&hr("too-short");var i=new Uint8Array(yield e.slice(0,10).arrayBuffer());Go(i)&&i[2]===8||hr("invalid-header");var r=new DataView(yield e.slice(e.size-8).arrayBuffer());r.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(_i)return _i;_i=[];for(var c=0;256>c;c++){for(var d=c,f=0;8>f;f++)d=1&d?3988292384^d>>>1:d>>>1;_i[c]=d>>>0}return _i})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(n)&&hr("invalid-crc");var s=n.length>>>0;r.getUint32(4,!0)!==s&&hr("invalid-size")}));return function(e,n){return t.apply(this,arguments)}})();function Vo(){return Vo=se((function*(t,e,n){e===void 0&&(e=!0);try{var i=new TextEncoder().encode(t),r=new globalThis.CompressionStream("gzip"),s=r.writable.getWriter(),o=s.write(i).then((()=>s.close())).catch((function(){var u=se((function*(c){try{yield s.abort(c)}catch{}throw c}));return function(c){return u.apply(this,arguments)}})()),a=new Response(r.readable).blob(),l=(yield Promise.all([a,o]))[0];return yield Np(l,i),l}catch(u){if(n!=null&&n.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),Vo.apply(this,arguments)}var Op=["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"],_c=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var n=t.toLowerCase();return Op.concat(e).some((i=>{var r=i.toLowerCase();return n.indexOf(r)!==-1}))};function j(t,e){return t.indexOf(e)!==-1}var xs=function(t){return t.trim()},Ko=function(t){return t.replace(/^\$/,"")};function fd(t){var e,n=[];return(e=JSON.stringify(t,(function(i,r){if(typeof r=="bigint")return r.toString();if(typeof r!="function"&&typeof r!="symbol"){if(r instanceof Error)return{name:r.name,message:r.message,stack:r.stack};if(r&&typeof r=="object"){for(;n.length>0&&n[n.length-1]!==this;)n.pop();if(n.includes(r))return"[Circular]";n.push(r)}return r}})))!==null&&e!==void 0?e:"null"}var hd=Object.prototype,pd=hd.hasOwnProperty,Is=hd.toString,U=Array.isArray||function(t){return Is.call(t)==="[object Array]"},De=t=>typeof t=="function",he=t=>t===Object(t)&&!U(t),Vt=t=>{if(he(t)){for(var e in t)if(pd.call(t,e))return!1;return!0}return!1},C=t=>t===void 0,X=t=>Is.call(t)=="[object String]",Yo=t=>X(t)&&t.trim().length===0,Ke=t=>t===null,H=t=>C(t)||Ke(t),ke=t=>Is.call(t)=="[object Number]"&&t==t,Bt=t=>ke(t)&&t>0,gt=t=>Is.call(t)==="[object Boolean]",Bp=t=>t instanceof FormData,Dp=t=>j(Mp,t),jp=t=>j(Lp,t);function gd(t){return t===null||typeof t!="object"}function Ur(t,e){return{}.toString.call(t)==="[object "+e+"]"}function Qa(t){return typeof Event<"u"&&md(t,Event)}function md(t,e){try{return t instanceof e}catch{return!1}}var Up=[!0,"true",1,"1","yes"],fo=t=>j(Up,t),Hp=[!1,"false",0,"0","no"];function Ct(t,e,n,i,r){return e>n&&(i.warn("min cannot be greater than max."),e=n),ke(t)?t>n?(i.warn(" cannot be greater than max: "+n+". Using max value instead."),n):e>t?(i.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(i.warn(" must be a number. using max or fallback. max: "+n+", fallback: "+r),Ct(r||n,e,n,i))}class Wp{constructor(e){this.tt={},this.et=e.et,this.it=Ct(e.bucketSize,0,100,e.rt),this.nt=Ct(e.refillRate,0,this.it,e.rt),this.st=Ct(e.refillInterval,0,864e5,e.rt)}ot(e,n){var i=Math.floor((n-e.lastAccess)/this.st);i>0&&(e.tokens=Math.min(e.tokens+i*this.nt,this.it),e.lastAccess=e.lastAccess+i*this.st)}consumeRateLimit(e){var n,i=Date.now(),r=String(e),s=this.tt[r];return s?this.ot(s,i):this.tt[r]=s={tokens:this.it,lastAccess:i},s.tokens===0||(s.tokens--,s.tokens===0&&((n=this.et)==null||n.call(this,e)),s.tokens===0)}stop(){this.tt={}}}var it="Mobile",Hr="iOS",Kt="Android",ei="Tablet",vd=Kt+" "+ei,_d="iPad",yd="Apple",wd=yd+" Watch",Bi="Safari",ti="BlackBerry",bd="Samsung",Ed=bd+"Browser",Sd=bd+" Internet",Pn="Chrome",qp=Pn+" OS",xd=Pn+" "+Hr,el="Internet Explorer",Id=el+" "+it,tl="Opera",zp=tl+" Mini",nl="Edge",kd="Microsoft "+nl,Zn="Firefox",Cd=Zn+" "+Hr,Vi="Nintendo",Ki="PlayStation",Xn="Xbox",Ad=Kt+" "+it,Pd=it+" "+Bi,Pi="Windows",Jo=Pi+" Phone",yc="Nokia",Zo="Ouya",Fd="Generic",Gp=Fd+" "+it.toLowerCase(),Rd=Fd+" "+ei.toLowerCase(),Xo="Konqueror",Td="Oculus Browser",Wr="Vivaldi",$d="Yandex",qr="Whale",Qo="DuckDuckGo",Md="Pale Moon",zr="Waterfox",Di="Brave",Ld="Google Search App",we="(\\d+(\\.\\d+)?)",ho=new RegExp("Version/"+we),Vp=new RegExp(Xn,"i"),Kp=new RegExp(Ki+" \\w+","i"),Yp=new RegExp(Vi+" \\w+","i"),il=new RegExp(ti+"|PlayBook|BB10","i"),Jp={"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"},Nd=function(t,e,n,i){e=e||"";var r=(function(s){return s!=null&&s.brave?Di:null})(n);return r||(i!=null&&i.detectGoogleSearchApp&&j(t,"GSA/")?Ld:j(t," OPR/")&&j(t,"Mini")?zp:j(t," OPR/")?tl:il.test(t)?ti:j(t,"IE"+it)||j(t,"WPDesktop")?Id:j(t,"OculusBrowser")?Td:j(t,Ed)?Sd:j(t,nl)||j(t,"Edg/")?kd:j(t,Wr+"/")?Wr:j(t,"YaBrowser/")?$d:j(t,qr+"/")?qr:j(t,Qo+"/")||j(t,"Ddg/")?Qo:j(t,"FBIOS")?"Facebook "+it:j(t,"UCWEB")||j(t,"UCBrowser")?"UC Browser":j(t,"CriOS")?xd:j(t,"CrMo")||j(t,Pn)?Pn:j(t,Kt)&&j(t,Bi)?Ad:j(t,"FxiOS")?Cd:j(t.toLowerCase(),Xo.toLowerCase())?Xo:j(t,Di+"/")?Di:((s,o)=>o&&j(o,yd)||(function(a){return j(a,Bi)&&!j(a,Pn)&&!j(a,Kt)})(s))(t,e)?j(t,it)?Pd:Bi:j(t,"PaleMoon/")?Md:j(t,zr+"/")?zr:j(t,Zn)?Zn:j(t,"MSIE")||j(t,"Trident/")?el:j(t,"Gecko")?Zn:"")},Zp={[Id]:[new RegExp("rv:"+we)],[kd]:[new RegExp(nl+"?\\/"+we)],[Pn]:[new RegExp("("+Pn+"|CrMo)\\/"+we)],[xd]:[new RegExp("CriOS\\/"+we)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+we)],[Bi]:[ho],[Pd]:[ho],[tl]:[new RegExp("(Opera|OPR)\\/"+we)],[Zn]:[new RegExp(Zn+"\\/"+we)],[Cd]:[new RegExp("FxiOS\\/"+we)],[Xo]:[new RegExp("Konqueror[:/]?"+we,"i")],[ti]:[new RegExp(ti+" "+we),ho],[Ad]:[new RegExp("android\\s"+we,"i")],[Sd]:[new RegExp(Ed+"\\/"+we)],[Td]:[new RegExp("OculusBrowser\\/"+we)],[Wr]:[new RegExp(Wr+"\\/"+we)],[$d]:[new RegExp("YaBrowser\\/"+we)],[qr]:[new RegExp(qr+"\\/"+we)],[Di]:[new RegExp(Di+"\\/"+we)],[Qo]:[new RegExp("(DuckDuckGo|Ddg)\\/"+we)],[Md]:[new RegExp("PaleMoon\\/"+we)],[zr]:[new RegExp(zr+"\\/"+we)],[Ld]:[new RegExp("GSA\\/"+we)],[el]:[new RegExp("(rv:|MSIE )"+we)],Mozilla:[new RegExp("rv:"+we)]},Xp=function(t,e,n,i){var r=Nd(t,e,n,i),s=Zp[r];if(C(s))return null;for(var o=0;s.length>o;o++){var a=t.match(s[o]);if(a)return parseFloat(a[a.length-2])}return null},wc=[[new RegExp(Xn+"; "+Xn+" (.*?)[);]","i"),t=>[Xn,t&&t[1]||""]],[new RegExp(Vi,"i"),[Vi,""]],[new RegExp(Ki,"i"),[Ki,""]],[il,[ti,""]],[new RegExp(Pi,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Jo,""];if(new RegExp(it).test(e)&&!/IEMobile\b/.test(e))return[Pi+" "+it,""];var n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){var i=Jp[n[1]]||"";return/arm/i.test(e)&&(i="RT"),[Pi,i]}return[Pi,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>t&&t[3]?[Hr,[t[3],t[4],t[5]||"0"].join(".")]:[Hr,""]],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{var e="";return t&&t.length>=3&&(e=C(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+Kt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Kt+")","i"),t=>t&&t[2]?[Kt,[t[2],t[3],t[4]||"0"].join(".")]:[Kt,""]],[/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/,[qp,""]],[/Linux|debian/i,["Linux",""]]],bc=function(t){return Yp.test(t)?Vi:Kp.test(t)?Ki:Vp.test(t)?Xn:new RegExp(Zo,"i").test(t)?Zo:new RegExp("("+Jo+"|WPDesktop)","i").test(t)?Jo:/iPad/.test(t)?_d:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?wd:il.test(t)?ti:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(yc,"i").test(t)?yc:/(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(it).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)?Kt:vd:new RegExp("(pda|"+it+")","i").test(t)?Gp:new RegExp(ei,"i").test(t)&&!new RegExp(ei+" pc","i").test(t)?Rd:""},Qp=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ec(t,e){return typeof(n=t)=="string"&&Qp.test(n)?t:e();var n}function dn(t){return t&&t.split("#")[0]}function rl(t,e){var n=setTimeout(t,e);return n?.unref&&n?.unref(),n}function Sc(t,e,n){return Od.apply(this,arguments)}function Od(){return(Od=se((function*(t,e,n){var i;try{return yield Promise.race([t,new Promise(((r,s)=>{i=rl((()=>{try{n?.(),r()}catch(o){s(o)}}),e)}))])}finally{clearTimeout(i)}}))).apply(this,arguments)}var eg=t=>t instanceof Error,Bd={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}},tg=Bd.info;function Dd(t){if(gt(t))return{boolValue:t};if(typeof t=="number")return Number.isFinite(t)?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:{stringValue:String(t)};if(typeof t=="string")return{stringValue:t};if(U(t))return{arrayValue:{values:t.map((e=>Dd(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function Gr(t){var e=[];for(var n in t){var i=t[n];Ke(i)||C(i)||e.push({key:n,value:Dd(i)})}return e}function ng(t,e){var n=Bd[t.level||"info"]||tg,i=n.text,r=n.number,s=String(Date.now())+"000000",o={};e.distinctId&&(o.posthogDistinctId=e.distinctId),e.sessionId&&(o.sessionId=e.sessionId),e.windowId&&(o["window.id"]=e.windowId),H(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),H(e.lastActivityTimestamp)||(o.lastActivityTimestamp=String(e.lastActivityTimestamp)),e.currentUrl&&(o["url.full"]=e.currentUrl),e.screenName&&(o["screen.name"]=e.screenName),e.appState&&(o["app.state"]=e.appState),e.activeFeatureFlags&&e.activeFeatureFlags.length>0&&(o.feature_flags=e.activeFeatureFlags);var a=k({},o,t.attributes||{}),l={timeUnixNano:s,observedTimeUnixNano:s,severityNumber:r,severityText:i,body:{stringValue:t.body},attributes:Gr(a)};return t.trace_id&&(l.traceId=t.trace_id),t.span_id&&(l.spanId=t.span_id),C(t.trace_flags)||(l.flags=t.trace_flags),l}function jd(t,e,n){return k({},t.resourceAttributes,{"service.name":t.serviceName||"unknown_service"},t.environment&&{"deployment.environment":t.environment},t.serviceVersion&&{"service.version":t.serviceVersion},{"telemetry.sdk.name":e,"telemetry.sdk.version":n})}function Ud(t,e,n,i){return{resourceLogs:[{resource:{attributes:Gr(e)},scopeLogs:[{scope:{name:n,version:i},logRecords:t}]}]}}let ig=class{constructor(t,e,n,i,r,s,o){var a;s===void 0&&(s=()=>Promise.resolve()),this._instance=t,this.Ne=e,this.rt=n,this.ut=i,this.ht=r,this.dt=s,this.vt=o,this.ct=null,this.ft=0,this.yt=0,this.bt=0,this._t=0,this.wt=!1,this.kt=e.maxBufferSize,this.xt=Math.max((a=e.maxQueueSize)!==null&&a!==void 0?a:e.maxBufferSize,e.maxBufferSize),this.St=e.flushIntervalMs,this.Ct=e.maxBatchRecordsPerPost,this.Mt=e.rateCapWindowMs,this.Tt=e.maxLogsPerInterval}reset(){this.Et(),this.ct=null,this.bt=0,this._t=0,this.wt=!1,this.ft=0,this.yt=0,this.Ct=this.Ne.maxBatchRecordsPerPost}onReconnect(){this.yt=0,this.It()}captureLog(t){if(!this._instance.isDisabled&&!this._instance.optedOut&&t!=null&&t.body){var e=this.Pt(t);if(e!==null)if(e.body){if(this.Rt()){var n={record:ng(e,this.ut())};this.ht((()=>this.At(n)))}}else this.rt.info("Log was rejected in beforeSend function")}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Log was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for log:",o),null}return i}Rt(){if(this.Tt===void 0)return!0;var t=Date.now(),e=t-this.bt;return this.Mt>e&&e>=0||(this.bt=t,this._t=0,this.wt=!1),this.Tt>this._t?(this._t++,!0):(this.wt||(this.rt.warn("captureLog dropping logs: exceeded "+this.Tt+" logs per "+this.Mt+"ms"),this.wt=!0),!1)}flush(){var t=this;return se((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return se((function*(){var e;t.Et();var n=(e=t._instance.getPersistedProperty(jt.LogsQueue))!==null&&e!==void 0?e:[];if(n.length!==0)for(var i=n.length,r=0;n.length>0&&i>r;){var s,o;t.ft=0;var a=Math.min(n.length,t.Ct),l=n.slice(0,a),u=Ud(l.map((d=>d.record)),t.Lt(),(s=t.vt)!==null&&s!==void 0?s:t._instance.getLibraryId(),t._instance.getLibraryVersion()),c=yield t._instance.Ot(u);if(c.kind==="too-large"&&l.length>1)t.Ct=Math.max(1,Math.floor(l.length/2)),t.rt.warn("Received 413 when sending logs batch of size "+l.length+", reducing batch size to "+t.Ct);else if(c.kind==="retry-later"||(c.kind==="too-large"?t.rt.warn("Dropping a single log record after 413 with batch size 1 — the record is larger than the server cap and cannot be split further."):c.kind==="ok"&&t.Ne.maxBatchRecordsPerPost>t.Ct&&(t.Ct=Math.min(t.Ne.maxBatchRecordsPerPost,t.Ct+1)),yield t.Dt(l.length),n=(o=t._instance.getPersistedProperty(jt.LogsQueue))!==null&&o!==void 0?o:[],r+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return se((function*(){var n,i=Math.max(0,t-e.ft),r=(n=e._instance.getPersistedProperty(jt.LogsQueue))!==null&&n!==void 0?n:[];e._instance.setPersistedProperty(jt.LogsQueue,r.slice(i)),yield e.dt()}))()}Lt(){return jd(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var n=(e=this._instance.getPersistedProperty(jt.LogsQueue))!==null&&e!==void 0?e:[];this.xt>n.length||(n.shift(),this.ft++,this.rt.info("Logs queue is full, dropping oldest record.")),n.push(t),this._instance.setPersistedProperty(jt.LogsQueue,n),this.kt>n.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=rl((()=>{this.Nt=void 0,this.It()}),t))}qt(){var t=Math.min(Math.max(0,this.yt-1),6);return this.St*Math.pow(2,t)}jt(){var t=this._instance.getPersistedProperty(jt.LogsQueue);return!!t&&t.length>0}shutdown(t){var e=this;return se((function*(){e.Et();var n=e.flush().catch((()=>{}));t!==void 0?yield Sc(n,t):yield n}))()}flushWithTimeout(t){var e=this;return se((function*(){var n=e.flush();yield Sc(n,t,(()=>{n.catch((()=>{}))}))}))()}It(){this.flush().then((()=>{this.yt=0}),(t=>{this.yt++,this.rt.error("PostHog logs flush failed:",t)})).finally((()=>{!this._instance.isDisabled&&this.jt()&&this.$t(this.qt())}))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}};var po=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function xc(t){return String(t)+"000000"}function Ic(t,e,n,i){var r="";return i&&(r=Object.keys(i).sort().map((s=>JSON.stringify(s)+":"+JSON.stringify(i[s]))).join(",")),t+"\0"+e+"\0"+(n??"")+"\0"+r}let rg=class{constructor(t,e,n){this._instance=t,this.Ne=e,this.rt=n,this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Wt=0}count(t,e,n){e===void 0&&(e=1),this.Vt({name:t,type:"count",value:e,unit:n?.unit,attributes:n?.attributes})}gauge(t,e,n){this.Vt({name:t,type:"gauge",value:e,unit:n?.unit,attributes:n?.attributes})}histogram(t,e,n){this.Vt({name:t,type:"histogram",value:e,unit:n?.unit,attributes:n?.attributes})}flush(){var t=this,e=this.ct,n=(function(){var r=se((function*(){e&&(yield e.catch((()=>{}))),yield t.Zt()}));return function(){return r.apply(this,arguments)}})(),i=n().finally((()=>{this.ct===i&&(this.ct=null)}));return this.ct=i,i}drainWindow(){if(this.Bt.size===0)return null;var t=this.Bt;return this.Bt=new Map,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Gt(t)}reset(){this.Wt++,this.Et(),this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set}Vt(t){if(!this._instance.isDisabled&&!this._instance.optedOut){var e=this.Pt(t);if(e!==null)if(e.name&&typeof e.name=="string")if(typeof e.value=="number"&&Number.isFinite(e.value))if(e.type==="count"&&0>e.value)this.rt.warn("Dropping count '"+e.name+"': counters are monotonic, value must be >= 0");else{var n,i;try{n=e.attributes?k({},e.attributes):void 0,i=Ic(e.type,e.name,e.unit,n)}catch(o){return void this.rt.warn("Dropping metric '"+e.name+"': attributes could not be serialized",o)}var r=this.Bt.get(i);if(!r){if(!this.Qt())return;r={name:e.name,type:e.type,unit:e.unit,attributes:n,windowStartMs:Date.now()},this.Bt.set(i,r)}var s=this.Ut.get(e.name);s===void 0?this.Ut.set(e.name,e.type):s===e.type||this.zt.has(e.name)||(this.zt.add(e.name),this.rt.warn("Metric name '"+e.name+"' is already used as a "+s+"; recording it as a "+e.type+" too will blend both series in charts. Use a distinct name.")),this.Kt(r,e.value),this.$t()}else this.rt.warn("Dropping metric '"+e.name+"': value must be a finite number");else this.rt.warn("Dropping metric with empty name")}}Qt(){return this.Ne.maxSeriesPerFlush>this.Bt.size||(this.Ht||(this.Ht=!0,this.rt.warn("Metric series cap reached ("+this.Ne.maxSeriesPerFlush+" per flush window); dropping new series until the next flush. Reduce attribute cardinality.")),!1)}Kt(t,e){var n;switch(t.type){case"count":t.total=((n=t.total)!==null&&n!==void 0?n:0)+e;break;case"gauge":t.last=e;break;case"histogram":t.hist||(t.hist={count:0,sum:0,min:e,max:e,bucketCounts:new Array(po.length+1).fill(0)});var i=t.hist;i.count+=1,i.sum+=e,i.min=Math.min(i.min,e),i.max=Math.max(i.max,e),i.bucketCounts[(function(r,s){for(var o=0;s.length>o;o++)if(s[o]>=r)return o;return s.length})(e,po)]+=1}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Metric was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for metric:",o),null}return i}$t(){this.Nt||(this.Nt=rl((()=>{this.Nt=void 0,this.flush().catch((t=>{this.rt.error("Metrics flush failed:",t)}))}),this.Ne.flushIntervalMs))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}Zt(){var t=this;return se((function*(){if(t.Bt.size!==0){var e=t.Bt;t.Bt=new Map,t.Ht=!1,t.Ut=new Map,t.zt=new Set;var n=t.Wt,i=yield t._instance.Jt(t.Gt(e));if(n===t.Wt)switch(i.kind){case"ok":return;case"retry-later":return t.Yt(e),void t.$t();case"too-large":return void t.rt.warn("Metrics batch exceeded the server size limit and was dropped");case"fatal":return void t.rt.error("Failed to send metrics batch:",i.error)}}}))()}Gt(t){return e=this.Xt(t),n=(function(s,o,a){return k({},s.resourceAttributes,{"service.name":s.serviceName||"unknown_service"},s.environment&&{"deployment.environment":s.environment},s.serviceVersion&&{"service.version":s.serviceVersion},{"telemetry.sdk.name":o,"telemetry.sdk.version":a})})(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion()),i=this._instance.getLibraryId(),r=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:Gr(n)},scopeMetrics:[{scope:{name:i,version:r},metrics:e}]}]};var e,n,i,r}Xt(t){var e=xc(Date.now()),n=new Map;for(var i of t.values()){var r,s=Ic(i.type,i.name,i.unit,void 0),o=n.get(s);o||(o=k({name:i.name},i.unit&&{unit:i.unit}),i.type==="count"?o.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:i.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:1,dataPoints:[]},n.set(s,o));var a=Gr((r=i.attributes)!==null&&r!==void 0?r:{}),l=xc(i.windowStartMs);if(i.type==="count"){var u,c={attributes:a,startTimeUnixNano:l,timeUnixNano:e,asDouble:(u=i.total)!==null&&u!==void 0?u:0};o.sum.dataPoints.push(c)}else if(i.type==="gauge"){var d,f={attributes:a,timeUnixNano:e,asDouble:(d=i.last)!==null&&d!==void 0?d:0};o.gauge.dataPoints.push(f)}else i.hist&&o.histogram.dataPoints.push({attributes:a,startTimeUnixNano:l,timeUnixNano:e,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:po})}return Array.from(n.values())}Yt(t){var e,n;for(var i of t){var r=i[0],s=i[1],o=this.Bt.get(r);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,s.windowStartMs),o.type){case"count":o.total=((e=o.total)!==null&&e!==void 0?e:0)+((n=s.total)!==null&&n!==void 0?n:0);break;case"gauge":break;case"histogram":if(s.hist)if(o.hist){o.hist.count+=s.hist.count,o.hist.sum+=s.hist.sum,o.hist.min=Math.min(o.hist.min,s.hist.min),o.hist.max=Math.max(o.hist.max,s.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=s.hist.bucketCounts[a]}else o.hist=s.hist}else this.Qt()&&this.Bt.set(r,s)}}};var pr,kc,go;function sg(t){var e=globalThis._posthogChunkIds;if(e){var n=Object.keys(e);return go&&n.length===kc||(kc=n.length,go=n.reduce(((i,r)=>{pr||(pr={});var s=pr[r];if(s)i[s[0]]=s[1];else for(var o=t(r),a=o.length-1;a>=0;a--){var l=o[a],u=l?.filename,c=e[r];if(u&&c){i[u]=c,pr[r]=[u,c];break}}return i}),{})),go}}class og{constructor(e,n,i){i===void 0&&(i=[]),this.coercers=e,this.stackParser=n,this.modifiers=i}buildFromUnknown(e,n){n===void 0&&(n={});var i=n&&n.mechanism||{handled:!0,type:"generic"},r=this.buildCoercingContext(i,n,0).apply(e),s=this.buildParsingContext(n),o=this.parseStacktrace(r,s);return{$exception_list:this.convertToExceptionList(o,i),$exception_level:"error"}}modifyFrames(e){var n=this;return se((function*(){for(var i of e)i.stacktrace&&i.stacktrace.frames&&U(i.stacktrace.frames)&&(i.stacktrace.frames=yield n.applyModifiers(i.stacktrace.frames));return e}))()}coerceFallback(e){var n;return{type:"Error",value:"Unknown error",stack:(n=e.syntheticException)==null?void 0:n.stack,synthetic:!0}}parseStacktrace(e,n){var i,r;return e.cause!=null&&(i=this.parseStacktrace(e.cause,n)),e.stack!=""&&e.stack!=null&&(r=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?n.skipFirstLines:0),n.chunkIdMap)),k({},e,{cause:i,stack:r})}applyChunkIds(e,n){return e.map((i=>(i.filename&&n&&(i.chunk_id=n[i.filename]),i)))}applyCoercers(e,n){for(var i of this.coercers)if(i.match(e))return i.coerce(e,n);return this.coerceFallback(n)}applyModifiers(e){var n=this;return se((function*(){var i=e;for(var r of n.modifiers)i=yield r(i);return i}))()}convertToExceptionList(e,n){var i,r,s,o={type:e.type,value:e.value,mechanism:{type:(i=n.type)!==null&&i!==void 0?i:"generic",handled:(r=n.handled)===null||r===void 0||r,synthetic:(s=e.synthetic)!==null&&s!==void 0&&s}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,k({},n,{handled:!0}))),a}buildParsingContext(e){var n;return{chunkIdMap:sg(this.stackParser),skipFirstLines:(n=e.skipFirstLines)!==null&&n!==void 0?n:1}}buildCoercingContext(e,n,i){i===void 0&&(i=0);var r=(s,o)=>{if(4>=o){var a=this.buildCoercingContext(e,n,o);return this.applyCoercers(s,a)}};return k({},n,{syntheticException:i==0?n.syntheticException:void 0,mechanism:e,apply:s=>r(s,i),next:s=>r(s,i+1)})}}var ni="?";function ea(t,e,n,i,r){var s={platform:t,filename:e,function:n===""?ni:n,in_app:!0};return C(i)||(s.lineno=i),C(r)||(s.colno=r),s}var Hd=(t,e)=>{var n=t.indexOf("safari-extension")!==-1,i=t.indexOf("safari-web-extension")!==-1;return n||i?[t.indexOf("@")!==-1?t.split("@")[0]:ni,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},ag=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,lg=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,cg=/\((\S*)(?::(\d+))(?::(\d+))\)/,ug=(t,e)=>{var n=ag.exec(t);if(n)return ea(e,n[1],ni,+n[2],+n[3]);var i=lg.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var r=cg.exec(i[2]);r&&(i[2]=r[1],i[3]=r[2],i[4]=r[3])}var s=Hd(i[1]||ni,i[2]);return ea(e,s[1],s[0],i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},dg=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,fg=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,hg=(t,e)=>{var n=dg.exec(t);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){var i=fg.exec(n[3]);i&&(n[1]=n[1]||"eval",n[3]=i[1],n[4]=i[2],n[5]="")}var r=n[3],s=n[1]||ni,o=Hd(s,r);return ea(e,r=o[1],s=o[0],n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},Cc=/\(error: (.*)\)/;class pg{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,n){var i=X(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:i?e.stack:void 0,cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var n=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?n+": "+e.message:n}isDOMException(e){return Ur(e,"DOMException")}isDOMError(e){return Ur(e,"DOMError")}}class gg{match(e){return(function(n){switch({}.toString.call(n)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return md(n,Error)}})(e)}coerce(e,n){return{type:this.getType(e),value:this.getMessage(e,n),stack:this.getStack(e),cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,n){var i=e.message;return String(i.error&&typeof i.error.message=="string"?i.error.message:i)}getStack(e){return e.stacktrace||e.stack||void 0}}class mg{constructor(){}match(e){return!!Ur(e,"ErrorEvent")&&(e.error!=null||this.fe(e))}coerce(e,n){var i;if(e.error!=null)return n.apply(e.error);var r=n.apply(e.message);return k({},r,{stack:(i=this.pe(e))!==null&&i!==void 0?i:r.stack,synthetic:!0})}fe(e){return X(e.message)&&e.message.length>0}pe(e){var n=e;if(X(n.filename)&&n.filename.length>0){var i,r,s=(i=n.lineno)!==null&&i!==void 0?i:0,o=(r=n.colno)!==null&&r!==void 0?r:0;return`Error - at `+n.filename+":"+s+":"+o}}}var vg=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class _g{match(e){return typeof e=="string"}coerce(e,n){var i,r=this.getInfos(e),s=r[0],o=r[1];return{type:s??"Error",value:o??e,stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}getInfos(e){var n="Error",i=e,r=e.match(vg);return r&&(n=r[1],i=r[2]),[n,i]}}var yg=["fatal","error","warning","log","info","debug"];function Wd(t,e){e===void 0&&(e=40);var n=Object.keys(t);if(n.sort(),!n.length)return"[object has no keys]";for(var i=n.length;i>0;i--){var r=n.slice(0,i).join(", ");if(e>=r.length)return i===n.length?r:r.length>e?r.slice(0,e)+"...":r}return""}class wg{match(e){return typeof e=="object"&&e!==null}coerce(e,n){var i,r,s=this.getErrorPropertyFromObject(e);return s?n.apply(s):{type:this.getType(e),value:this.getValue(e),stack:(i=this.getStack(e))!==null&&i!==void 0?i:(r=n.syntheticException)==null?void 0:r.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return Qa(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var n="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(n+=" with message: '"+e.message+"'"),n}if("message"in e&&typeof e.message=="string")return e.message;var i=this.getObjectClassName(e);return(i&&i!=="Object"?"'"+i+"'":"Object")+" captured as exception with keys: "+Wd(e)}isSeverityLevel(e){return X(e)&&!Yo(e)&&yg.indexOf(e)>=0}getStack(e){try{return X(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:X(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(var n in e)if({}.hasOwnProperty.call(e,n)){var i=e[n];if(eg(i))return i}}getObjectClassName(e){try{var n=Object.getPrototypeOf(e);return n?n.constructor.name:void 0}catch{return}}}class bg{match(e){return Qa(e)}coerce(e,n){var i,r=e.constructor.name;return{type:r,value:r+" captured as exception with keys: "+Wd(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class Eg{match(e){return gd(e)}coerce(e,n){var i;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class Sg{match(e){return Ur(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Qa(e))return!1;try{var n=e.detail;return n!=null&&typeof n=="object"&&"reason"in n}catch{return!1}}coerce(e,n){var i,r=this.getUnhandledRejectionReason(e);return gd(r)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(r),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}:n.apply(r)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}}var Vr="$message",Kr="$timestamp",xg=new Set([Vr,Kr]),mo={enabled:!0,max_bytes:32768};function Yr(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:mo.enabled,max_bytes:kg(t.max_bytes,mo.max_bytes)}:k({},mo)}class Ig{constructor(e){this.Ke=[],this.Je=0,this.Ne=Yr(e)}setConfig(e){this.Ne=Yr(e),this.Xe()}add(e){var n=(function(r){var s;try{s=fd(r)}catch{return}try{var o=JSON.parse(s);if(!he(o))return;var a=o,l=a[Vr],u=a[Kr];return!X(l)||l.trim().length===0||!X(u)&&!ke(u)?void 0:{step:a,json:s}}catch{return}})(e);if(n){var i=(function(r){if(typeof TextEncoder<"u")return new TextEncoder().encode(r).length;for(var s=encodeURIComponent(r),o=0,a=0;s.length>a;a++)s[a]==="%"?(o+=1,a+=2):o+=1;return o})(n.json);i>this.Ne.max_bytes||(this.Ke.push({step:n.step,bytes:i}),this.Je+=i,this.Xe())}}getAttachable(){return this.Ke.map((e=>e.step))}clear(){this.Ke=[],this.Je=0}size(){return this.Ke.length}Xe(){for(;this.Je>this.Ne.max_bytes&&this.Ke.length>0;){var e=this.Ke.shift();e&&(this.Je-=e.bytes)}}}function kg(t,e){if(!ke(t)||t===1/0||t===-1/0)return e;var n=Math.floor(t);return 0>n?e:n}var qd=function(t,e){var n=(e===void 0?{}:e).debugEnabled,i={k(r){if(w&&(ne.DEBUG||w.POSTHOG_DEBUG||n)&&!C(w.console)&&w.console){for(var s=("__rrweb_original__"in w.console[r])?w.console[r].__rrweb_original__:w.console[r],o=arguments.length,a=new Array(o>1?o-1:0),l=1;o>l;l++)a[l-1]=arguments[l];s(t,...a)}},debug(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("debug",...s)},info(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("log",...s)},warn(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("warn",...s)},error(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("error",...s)},critical(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];console.error(t,...s)},uninitializedWarning(r){i.error("You must initialize PostHog before calling "+r)},createLogger:(r,s)=>qd(t+" "+r,s)};return i},A=qd("[PostHog.js]"),pe=A.createLogger,Cg=pe("[ExternalScriptsLoader]"),vo=(t,e,n)=>{if(t.config.disable_external_dependency_loading)return Cg.warn(e+" was requested but loading of external scripts is disabled."),n("Loading of external scripts is disabled");var i=F?.querySelectorAll("script");if(i){for(var r,s=function(){if(i[o].src===e){var l=i[o];return l.__posthog_loading_callback_fired?{v:n()}:(l.addEventListener("load",(u=>{l.__posthog_loading_callback_fired=!0,n(void 0,u)})),l.onerror=u=>n(u),{v:void 0})}},o=0;i.length>o;o++)if(r=s())return r.v}var a=()=>{if(!F)return n("document not found");var l=F.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=d=>{l.__posthog_loading_callback_fired=!0,n(void 0,d)},l.onerror=d=>n(d),t.config.prepare_external_dependency_script&&(l=t.config.prepare_external_dependency_script(l)),!l)return n("prepare_external_dependency_script returned null");if(t.config.external_scripts_inject_target==="head")F.head.appendChild(l);else{var u,c=F.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):F.body.appendChild(l)}};F!=null&&F.body?a():F?.addEventListener("DOMContentLoaded",a)};B.__PosthogExtensions__=B.__PosthogExtensions__||{},B.__PosthogExtensions__.loadExternalDependency=(t,e,n)=>{if(e!=="remote-config"){var i;if(t.config.strict_script_versioning)i=t.requestRouter.endpointFor("assets","/static/"+t.version+"/"+e+".js");else{var r="/static/"+e+".js?v="+t.version;if(e==="toolbar"){var s=3e5;r=r+"&t="+Math.floor(Date.now()/s)*s}i=t.requestRouter.endpointFor("assets",r)}vo(t,i,n)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");vo(t,o,n)}},B.__PosthogExtensions__.loadSiteApp=(t,e,n)=>{var i=t.requestRouter.endpointFor("api",e);vo(t,i,n)};ne.DEBUG=!1,ne.LIB_VERSION="1.415.7",ne.LIB_NAME="web";var zd="$people_distinct_id",Yi="$device_id",_o="$device_model",Fi="__alias",Ri="__timers",ta="$autocapture_disabled_server_side",na="$heatmaps_enabled_server_side",ia="$exception_capture_enabled_server_side",ra="$error_tracking_suppression_rules",sa="$error_tracking_capture_extension_exceptions",oa="$web_vitals_enabled_server_side",sl="$dead_clicks_enabled_server_side",ol="$product_tours_enabled_server_side",aa="$web_vitals_allowed_metrics",An="$session_recording_remote_config",Gd="$replay_sample_rate",Vd="$replay_override_sampling",Kd="$replay_override_linked_flag",Yd="$replay_override_url_trigger",Jd="$replay_override_event_trigger",Kn="$sesid",al="$session_is_sampled",En="$enabled_feature_flags",Ti="$active_feature_flags",Cr="$early_access_features",la="$feature_flag_details",$i="$feature_flag_payloads",Ar="$feature_flag_request_id",Jr="$minimal_flag_called_events",xt="$override_feature_flags",Sn="$override_feature_flag_payloads",Dt="$stored_person_properties",xn="$stored_group_properties",ca="$surveys",Zr="$surveys_loaded_at",ua="$surveys_activated",Pr="$surveys_activated_session",Fr="$surveys_activated_timestamps",Mi="ph_product_tours",kn="$flag_call_reported",Li="$flag_call_reported_session_id",Rr="$feature_flag_errors",ji="$feature_flag_evaluated_at",ot="$user_state",da="$client_session_props",fa="$capture_rate_limit",ha="$initial_campaign_params",pa="$initial_referrer_info",Xr="$initial_person_info",Qr="$epp",gr="$posthog_cookieless",Zd="$cookieless_mode",Xd="$sdk_debug_extensions_init_method",Qd="$sdk_debug_extensions_init_time_ms",ef="$sdk_debug_recording_script_not_loaded",ll="PostHog loadExternalDependency extension not found.",In="on_reject",Ht="always",Un="anonymous",mn="identified",ga="identified_only",es="visibilitychange",ts="beforeunload",Gn="$pageview",yo="$pageleave",wo="$identify",Ac="$groupidentify";function mr(t,e){U(t)&&t.forEach(e)}function ie(t,e){if(!H(t))if(U(t))t.forEach(e);else if(Bp(t))t.forEach(((i,r)=>e(i,r)));else for(var n in t)pd.call(t,n)&&e(t[n],n)}var fe=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;e>i;i++)n[i-1]=arguments[i];for(var r of n)for(var s in r)r[s]!==void 0&&(t[s]=r[s]);return t};function Tr(t){for(var e=Object.keys(t),n=e.length,i=new Array(n);n--;)i[n]=[e[n],t[e[n]]];return i}var Pc=function(t){try{return t()}catch{return}},Ag=function(t){return function(){try{for(var e=arguments.length,n=new Array(e),i=0;e>i;i++)n[i]=arguments[i];return t.apply(this,n)}catch(r){A.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),A.critical(r)}}},cl=function(t){var e={};return ie(t,(function(n,i){(X(n)&&n.length>0||ke(n))&&(e[i]=n)})),e},Pg=["herokuapp.com","vercel.app","netlify.app"];function Fg(t){var e=t?.hostname;if(!X(e))return!1;var n=e.split(".").slice(-2).join(".");for(var i of Pg)if(n===i)return!1;return!0}function ve(t,e,n,i){var r=i??{},s=r.capture,o=r.passive;t?.addEventListener(e,n,{capture:s!==void 0&&s,passive:o===void 0||o})}function ma(t){return t.name==="ph_toolbar_internal"}var tf=t=>{if(F){try{for(var e=t+"=",n=F.cookie.split(";").filter((s=>s.length)),i=0;n.length>i;i++){for(var r=n[i];r.charAt(0)==" ";)r=r.substring(1,r.length);if(r.indexOf(e)===0)return decodeURIComponent(r.substring(e.length,r.length))}}catch{}return null}};Math.trunc||(Math.trunc=function(t){return 0>t?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return ke(t)&&isFinite(t)&&Math.floor(t)===t});class ns{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,n,i,r){if(!Number.isInteger(e)||!Number.isInteger(n)||!Number.isInteger(i)||!Number.isInteger(r)||0>e||0>n||0>i||0>r||e>0xffffffffffff||n>4095||i>1073741823||r>4294967295)throw new RangeError("invalid field value");var s=new Uint8Array(16);return s[0]=e/Math.pow(2,40),s[1]=e/Math.pow(2,32),s[2]=e/Math.pow(2,24),s[3]=e/Math.pow(2,16),s[4]=e/256,s[5]=e,s[6]=112|n>>>8,s[7]=n,s[8]=128|i>>>24,s[9]=i>>>16,s[10]=i>>>8,s[11]=i,s[12]=r>>>24,s[13]=r>>>16,s[14]=r>>>8,s[15]=r,new ns(s)}toString(){for(var e="",n=0;this.bytes.length>n;n++)e=e+(this.bytes[n]>>>4).toString(16)+(15&this.bytes[n]).toString(16),n!==3&&n!==5&&n!==7&&n!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new ns(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var n=0;16>n;n++){var i=this.bytes[n]-e.bytes[n];if(i!==0)return Math.sign(i)}return 0}}class Rg{generate(){var e=this.generateOrAbort();if(!C(e))return e;this.S=0;var n=this.generateOrAbort();if(C(n))throw new Error("Could not generate UUID after timestamp reset");return n}generateOrAbort(){var e=Date.now();if(e>this.S)this.S=e,this.C();else{if(this.S>=e+1e4)return;this.I++,this.I>4398046511103&&(this.S++,this.C())}return ns.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 Tg}}var Fc,nf=t=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;t.length>e;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};w&&!C(w.crypto)&&crypto.getRandomValues&&(nf=t=>crypto.getRandomValues(t));class Tg{nextUint32(){return this.R.length>this.O||(nf(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var Ut=()=>$g().toString(),$g=()=>(Fc||(Fc=new Rg)).generate(),yi="",Mg=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,Wt={N:()=>!!F,j(t){A.error("cookieStore error: "+t)},P:tf,H(t){var e;try{e=JSON.parse(Wt.P(t))||{}}catch{}return e},F(t,e,n,i,r){if(!F)return!1;try{var s="",o="",a=(function(c,d){if(d){var f=(function(p,g){if(g===void 0&&(g=F),yi)return yi;if(!g||["localhost","127.0.0.1"].includes(p))return"";for(var m=p.split("."),v=Math.min(m.length,8),S="dmn_chk_"+Ut();!yi&&v--;){var b=m.slice(v).join("."),_=S+"=1;domain=."+b+";path=/";g.cookie=_+";max-age=3",g.cookie.includes(S)&&(g.cookie=_+";max-age=0",yi=b)}return yi})(c);if(!f){var h=(p=>{var g=p.match(Mg);return g?g[0]:""})(c);h!==f&&A.info("Warning: cookie subdomain discovery mismatch",h,f),f=h}return f?"; domain=."+f:""}return""})(F.location.hostname,i);if(n){var l=new Date;l.setTime(l.getTime()+864e5*n),s="; expires="+l.toUTCString()}r&&(o="; secure");var u=t+"="+encodeURIComponent(JSON.stringify(e))+s+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&A.warn("cookieStore warning: large cookie, len="+u.length),F.cookie=u,!0}catch{return!1}},q(t,e){if(F!=null&&F.cookie)try{Wt.F(t,"",-1,e)}catch{return}}},bo=null,le={N(){if(!Ke(bo))return bo;var t=!0;if(C(w))t=!1;else try{var e="__mplssupport__";le.F(e,"xyz"),le.P(e)!=='"xyz"'&&(t=!1),le.q(e)}catch{t=!1}return t||A.error("localStorage unsupported; falling back to cookie store"),bo=t,t},j(t){A.error("localStorage error: "+t)},P(t){try{return w?.localStorage.getItem(t)}catch(e){le.j(e)}return null},H(t){try{return JSON.parse(le.P(t))||{}}catch{}return null},F(t,e){try{return w?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(n){le.j(n)}return!1},q(t){try{w?.localStorage.removeItem(t)}catch(e){le.j(e)}}},Lg=[Yi,"distinct_id",Kn,al,Qr,Xr,ot],vr={},Ng={N:()=>!0,j(t){A.error("memoryStorage error: "+t)},P:t=>vr[t]||null,H:t=>vr[t]||null,F:(t,e)=>(vr[t]=e,!0),q(t){delete vr[t]}},vn=null,be={N(){if(!Ke(vn))return vn;if(vn=!0,C(w))vn=!1;else try{var t="__support__";be.F(t,"xyz"),be.P(t)!=='"xyz"'&&(vn=!1),be.q(t)}catch{vn=!1}return vn},j(t){A.error("sessionStorage error: ",t)},P(t){try{return w?.sessionStorage.getItem(t)}catch(e){be.j(e)}return null},H(t){try{return JSON.parse(be.P(t))||null}catch{}return null},F(t,e){try{return w?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(n){be.j(n)}return!1},q(t){try{w?.sessionStorage.removeItem(t)}catch(e){be.j(e)}}};class Og{constructor(e){this._instance=e}get Ne(){return this._instance.config}get consent(){return this.ti()?0:this.ei}isOptedOut(){return this.Ne.cookieless_mode===Ht||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===In}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===0}isRejected(){return this.consent===0||this.consent===-1&&this.Ne.opt_out_capturing_by_default}optInOut(e){this.ii.F(this.ri,e?1:0,this.Ne.cookie_expiration,this.Ne.cross_subdomain_cookie,this.Ne.secure_cookie)}reset(){this.ii.q(this.ri,this.Ne.cross_subdomain_cookie)}get ri(){var e=this._instance.config,n=e.token,i=e.opt_out_capturing_cookie_prefix;return e.consent_persistence_name||(i?i+n:"__ph_opt_in_out_"+n)}get ei(){var e=this.ii.P(this.ri);return fo(e)?1:j(Hp,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,n=e==="localStorage"?le:Wt;if(!this.ni||this.ni!==n){this.ni=n;var i=e==="localStorage"?Wt:le;i.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(fo(i.P(this.ri))),i.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[Ue?.doNotTrack,Ue?.msDoNotTrack,B.doNotTrack].some((e=>fo(e)))}}function rf(t,e){var n,i=t==null||(n=t.config)==null?void 0:n.get_current_url;if(!De(i))return e;try{var r=i(e);return X(r)&&r?r:e}catch(s){return A.error("Error in get_current_url, falling back to window.location.href",s),e}}var sf="__POSTHOG_TOOLBAR__",Bg=1,Dg=3,jg=11;function Rc(t){return t instanceof Element&&(t.id===sf||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function fn(t){return!!t&&t.nodeType===Bg}function Qe(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function of(t){return!!t&&t.nodeType===Dg}function af(t){return!!t&&t.nodeType===jg&&fn(t.host)}var lf=1e3;function ul(t){return t?xs(t).split(/\s+/):[]}function Tc(t,e){var n=(function(i){var r,s=w==null||(r=w.location)==null?void 0:r.href;return C(s)?void 0:rf(i,s)})(e);return!!(n&&t&&t.some((i=>n.match(i))))}function is(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 ul(e)}function cf(t){return H(t)?null:xs(t).split(/(\s+)/).filter((e=>Ui(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function Ji(t){var e="";return _a(t)&&!hf(t)&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;of(n)&&n.textContent&&(e+=(i=cf(n.textContent))!==null&&i!==void 0?i:"")})),xs(e)}function Eo(t){var e;return C(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var dl=["a","button","form","input","select","textarea","label"];function va(t,e){if(C(e))return!0;var n,i=function(s){if(e.some((o=>(function(a,l){var u=a.matches||a.matchesSelector||a.msMatchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.oMatchesSelector;try{return!!u&&u.call(a,l)}catch{return!1}})(s,o))))return{v:!0}};for(var r of t)if(n=i(r))return n.v;return!1}function uf(t){var e=t.parentNode;return!(!e||!fn(e))&&e}var Ug=[".ph-no-autocapture","[data-ph-no-autocapture]"],df=["next","previous","prev",">","<"],Hg=[...df,"+","-","−","–"],$c=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,Mc=[".ph-no-rageclick",".ph-no-capture"],Wg=["","text","search","email","password","url","tel","number"];function Lc(t,e){if(!w||fl(t))return!1;var n,i,r,s,o;if(gt(e)?(n=!!e&&Mc,i=void 0,r=!1):(n=(s=e?.css_selector_ignorelist)!==null&&s!==void 0?s:Mc,i=e?.content_ignorelist,r=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),n===!1||r&&(function(l){return!(!l||!fn(l))&&(!!Qe(l,"textarea")||(Qe(l,"input")?j(Wg,(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=ff(t,!1).targetElementList;return!(function(l,u){if(l===!1||C(l))return!1;var c;if(l===!0)c=df;else{if(!U(l))return!1;if(l.length>10)return A.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var f=d.safeText,h=d.ariaLabel;return c.some((p=>$c(f,p)||$c(h,p)))}))})(i,a.map((l=>{var u;return{safeText:Ji(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!va(a,n)}var fl=t=>!t||Qe(t,"html")||!fn(t),ff=(t,e)=>{if(!w||fl(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,i=[t],r=t;r.parentNode&&!Qe(r,"body");)if(af(r.parentNode))i.push(r.parentNode.host),r=r.parentNode.host;else{var s=uf(r);if(!s)break;if(e||dl.indexOf(s.tagName.toLowerCase())>-1)n=!0;else try{var o=w.getComputedStyle(s);o&&o.getPropertyValue("cursor")==="pointer"&&(n=!0)}catch{}i.push(s),r=s}return{parentIsUsefulElement:n,targetElementList:i}};function _a(t){for(var e=new Set,n=0,i=t;i.parentNode&&!Qe(i,"body");i=i.parentNode){if(n++>=lf||e.has(i))return!1;e.add(i);var r=is(i);if(j(r,"ph-sensitive")||j(r,"ph-no-capture"))return!1}if(j(is(t),"ph-include"))return!0;var s=t.type||"";if(X(s))switch(s.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!X(o)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(o.replace(/[^a-zA-Z0-9]/g,""))}function hf(t){return!!(Qe(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||Qe(t,"select")||Qe(t,"textarea")||t.getAttribute("contenteditable")==="true")}var Nc=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}))$"),Oc=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,qg=[16,15,14,13],zg=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),Bc=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),Dc=/[0-9A-Za-z_]/;function Gg(t){for(var e=0,n=!1,i=t.length-1;i>=0;i--){var r=t.charCodeAt(i)-48;n&&(r*=2)>9&&(r-=9),e+=r,n=!n}return e%10==0}function Ui(t,e){if(e===void 0&&(e=!0),H(t))return!1;if(X(t)){t=xs(t);var n=e?Nc.test((t||"").replace(/[- ]/g,"")):(function(r){var s;for(Oc.lastIndex=0;s=Oc.exec(r);){var o=s[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of qg){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(Nc.test(d)&&Gg(d))return!0}}}return!1})(t);if(n)return!1;var i=e?zg.test(t):(function(r){var s;for(Bc.lastIndex=0;s=Bc.exec(r);){var o=s[1],a=s[3];if(!(o&&a&&Dc.test(o)&&Dc.test(a)))return!0}return!1})(t);if(i)return!1}return!0}function jc(t){var e=Ji(t);return Ui(e=(e+" "+pf(t)).trim())?e:""}function pf(t){var e="";return t&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;if(n&&((i=n.tagName)==null?void 0:i.toLowerCase())==="span")try{var r=Ji(n);e=(e+" "+r).trim(),n.childNodes&&n.childNodes.length&&(e=(e+" "+pf(n)).trim())}catch(s){A.error("[AutoCapture]",s)}})),e}function Uc(t){return t.replace(/"|\\"/g,'\\"')}function Vg(t){var e=t.attr__class;if(e)return U(e)?e:ul(e)}var _r=pe("[Dead Clicks]"),Kg=()=>!0,Yg=t=>{var e,n=!((e=t.instance.persistence)==null||!e.get_property(sl)),i=t.instance.config.capture_dead_clicks;return gt(i)?i:!!he(i)||n};class Hc{get lazyLoadedDeadClicksAutocapture(){return this.si}constructor(e,n,i){this.instance=e,this.isEnabled=n,this.onCapture=i,this.startIfEnabledOrStop()}onRemoteConfig(e){if(e.ok){var n=e.config;"captureDeadClicks"in n&&(this.instance.persistence&&this.instance.persistence.register({[sl]:n.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var n,i;(n=B.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture?e():(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"dead-clicks-autocapture",(r=>{r?_r.error("failed to load script",r):e()}))}oi(){var e;if(F){if(!this.si&&(e=B.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var n=he(this.instance.config.capture_dead_clicks)?k({},this.instance.config.capture_dead_clicks):{};n.__onCapture=this.onCapture,this.onCapture&&(n.capture_dead_swipes=!1),this.si=B.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.si.start(F),_r.info("starting...")}}else _r.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,_r.info("stopping..."))}}var So=pe("[SegmentIntegration]"),gf="posthog-js";function mf(t,e){var n=e===void 0?{}:e,i=n.organization,r=n.projectId,s=n.prefix,o=n.severityAllowList,a=o===void 0?["error"]:o,l=n.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,f,h,p,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var v,S=((d=c.exception)==null?void 0:d.values)||[],b=S.map((x=>k({},x,{stacktrace:x.stacktrace?k({},x.stacktrace,{type:"raw",frames:(x.stacktrace.frames||[]).map((I=>k({},I,{platform:"web:javascript"})))}):void 0}))),_={$exception_message:((f=S[0])==null?void 0:f.value)||c.message,$exception_type:(h=S[0])==null?void 0:h.type,$exception_level:c.level,$exception_list:b,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((p=S[0])==null?void 0:p.value)||c.message,$sentry_exception_type:(g=S[0])==null?void 0:g.type,$sentry_tags:c.tags};return i&&r&&(_.$sentry_url=(s||"https://sentry.io/organizations/")+i+"/issues/?project="+r+"&query="+c.event_id),u&&((v=t.exceptions)==null||v.sendExceptionEvent(_)),c}}class Jg{constructor(e,n,i,r,s,o){this.name=gf,this.setupOnce=function(a){a(mf(e,{organization:n,projectId:i,prefix:r,severityAllowList:s,sendExceptionsToPostHog:o==null||o}))}}}class Wc{constructor(e){this.li=(n,i,r)=>{r&&(r.noSessionId||r.activityTimeout||r.sessionPastMaximumLength||r.crossTabAdoption)&&(A.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:n,changeReason:r}),this.ui=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.hi()}hi(){var e;this.di=(e=this._instance.sessionManager)==null?void 0:e.onSessionId(this.li)}destroy(){var e;(e=this.di)==null||e.call(this),this.di=void 0}doPageView(e,n){var i,r=this.vi(e,n);return this.ui={pathname:(i=w?.location.pathname)!==null&&i!==void 0?i:"",pageViewId:n,timestamp:e},this._instance.scrollManager.resetContext(),r}doPageLeave(e){var n;return this.vi(e,(n=this.ui)==null?void 0:n.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.ui)==null?void 0:e.pageViewId}}vi(e,n){var i=this.ui;if(!i)return{$pageview_id:n};var r={$pageview_id:n,$prev_pageview_id:i.pageViewId},s=this._instance.scrollManager.getContext();if(s&&!this._instance.config.disable_scroll_properties){var o=s.maxScrollHeight,a=s.lastScrollY,l=s.maxScrollY,u=s.maxContentHeight,c=s.lastContentY,d=s.maxContentY;if(!(C(o)||C(a)||C(l)||C(u)||C(c)||C(d))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),d=Math.ceil(d);var f=o>1?Ct(a/o,0,1,A):1,h=o>1?Ct(l/o,0,1,A):1,p=u>1?Ct(c/u,0,1,A):1,g=u>1?Ct(d/u,0,1,A):1;r=fe(r,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:f,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:h,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:p,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return i.pathname&&(r.$prev_pageview_pathname=i.pathname),i.timestamp&&(r.$prev_pageview_duration=(e.getTime()-i.timestamp.getTime())/1e3),r}}var xo=["flags","surveys"],Zg={[zd]:{exposure:"hidden"},[Fi]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[Ri]:{exposure:"hidden"},[ta]:{exposure:"event"},[na]:{exposure:"hidden"},[ia]:{exposure:"event"},[ra]:{exposure:"hidden"},[sa]:{exposure:"event"},[oa]:{exposure:"event"},[sl]:{exposure:"event"},[ol]:{exposure:"hidden"},[aa]:{exposure:"event"},[An]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[Kn]:{exposure:"hidden"},[al]:{exposure:"event"},[Gd]:{exposure:"event",shouldSkipFromEventProperties:t=>Ke(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"},[En]:{exposure:"hidden",storageGroup:"flags"},[Ti]:{exposure:"hidden",storageGroup:"flags"},[Cr]:{exposure:"hidden"},[la]:{exposure:"hidden",storageGroup:"flags"},[$i]:{exposure:"hidden",storageGroup:"flags"},[Ar]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[Jr]:{exposure:"hidden",storageGroup:"flags"},[xt]:{exposure:"hidden"},[Sn]:{exposure:"hidden"},[Dt]:{exposure:"hidden"},[xn]:{exposure:"hidden"},[ca]:{exposure:"hidden",storageGroup:"surveys"},[Zr]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[ua]:{exposure:"event"},[Pr]:{exposure:"hidden"},[Fr]:{exposure:"hidden"},[Mi]:{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"},[kn]:{exposure:"hidden"},[Li]:{exposure:"hidden"},[Rr]:{exposure:"hidden"},[ji]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[ot]:{exposure:"hidden"},[da]:{exposure:"hidden"},[fa]:{exposure:"hidden"},[ha]:{exposure:"hidden"},[pa]:{exposure:"hidden"},[Xr]:{exposure:"hidden"},[Qr]:{exposure:"hidden"},[Vd]:{exposure:"event"},[Kd]:{exposure:"event"},[Yd]:{exposure:"event"},[Jd]:{exposure:"event"},[Xd]:{exposure:"event"},[Qd]:{exposure:"event"},[ef]:{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"}},Xg=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],_n=t=>{var e=Zg[t];if(e)return e;for(var n of Xg){var i=n[1];if(t.indexOf(n[0])===0)return i}},Yn=(t,e)=>{try{return JSON.stringify(t,((n,i)=>typeof i=="bigint"?i.toString():i),e)}catch{return fd(t)}},rs=t=>{var e=F?.createElement("a");return C(e)?null:(e.href=t,e)},ii=function(t,e){for(var n,i=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),r=0;i.length>r;r++){var s=i[r].split("=");if(s[0]===e){n=s;break}}if(!U(n)||2>n.length)return"";var o=n[1];try{o=decodeURIComponent(o)}catch{A.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},Zi=function(t,e,n){if(!t||!e||!e.length)return t;for(var i=t.split("#"),r=i[1],s=(i[0]||"").split("?"),o=s[1],a=s[0],l=(o||"").split("&"),u=[],c=0;l.length>c;c++){var d=l[c].split("=");U(d)&&(e.includes(d[0])?u.push(d[0]+"="+n):u.push(l[c]))}var f=a;return o!=null&&(f+="?"+u.join("&")),r!=null&&(f+="#"+r),f},ss=function(t,e){var n=t.match(new RegExp(e+"=([^&]*)"));return n?n[1]:null},vf=(t,e)=>t>=e&&cd(),_f=(t,e,n,i)=>{if(t===0){if(cd()){var r=e+1;return r===n&&i(),r}return e}return 0},yr="https?://(.*)",ri=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Qg=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...ri],Xi="",em=["li_fat_id"];function yf(t,e,n){if(!F)return{};var i,r=e?[...ri,...n||[]]:[],s=wf(Zi(F.URL,r,Xi),t),o=(i={},ie(em,(function(a){var l=tf(a);i[a]=l||null})),i);return fe(o,s)}function wf(t,e){var n=Qg.concat(e||[]),i={};return ie(n,(function(r){var s=ii(t,r);i[r]=s||null})),i}function bf(t){var e=(function(s){return s?s.search(yr+"google.([^/?]*)")===0?"google":s.search(yr+"bing.com")===0?"bing":s.search(yr+"yahoo.com")===0?"yahoo":s.search(yr+"duckduckgo.com")===0?"duckduckgo":null:null})(t),n=e!="yahoo"?"q":"p",i={};if(!Ke(e)){i.$search_engine=e;var r=F?ii(F.referrer,n):"";r.length&&(i.ph_keyword=r)}return i}function qc(){return navigator.language||navigator.userLanguage}var os="$direct";function Ef(){return F?.referrer||os}function Sf(t,e,n){n===void 0&&(n=!1);var i=t?[...ri,...e||[]]:[],r=n?dn(me?.href):me?.href,s=r?.substring(0,1e3);return{r:Ef().substring(0,1e3),u:s?Zi(s,i,Xi):void 0}}function xf(t,e){var n;e===void 0&&(e=!1);var i=t.r,r=t.u,s=e?dn(r):r,o={$referrer:i,$referring_domain:i==null?void 0:i==os?os:(n=rs(i))==null?void 0:n.host};if(s){o.$current_url=s;var a=rs(s);o.$host=a?.host,o.$pathname=a?.pathname;var l=wf(s);fe(o,l)}if(i){var u=bf(i);fe(o,u)}return o}function If(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function tm(){try{return new Date().getTimezoneOffset()}catch{return}}var nm={flags:ji,surveys:Zr},im=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],Hn="main";class Io{constructor(e,n,i){if(i===void 0&&(i=!0),this.ci={},this.fi=!1,this.pi=!1,this.Ne=e,this.gi=i,this.props={},this.mi=void 0,this.yi=(s=>{var o="";return s.token&&(o=s.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),s.persistence_name?"ph_"+s.persistence_name:"ph_"+o+"_posthog"})(e),this.ii=this.bi(e),this.pi=this.wi(e),this.load(),e.debug&&A.info("Persistence loaded",e.persistence,k({},this.props)),this.update_config(e,e,n),this.save(),w){var r=()=>this.flush();ve(w,"beforeunload",r,{capture:!1}),ve(w,"pagehide",r,{capture:!1})}}ki(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return ke(n)&&n>0?n:0}isDisabled(){return!!this.xi}bi(e){im.indexOf(e.persistence.toLowerCase())===-1&&(A.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var n,i=(function(o,a){o===void 0&&(o=[]),a===void 0&&(a=!1);var l=[...Lg,...o];return k({},le,{H(u){try{var c={};try{c=Wt.H(u)||{}}catch{}var d,f=JSON.parse(le.P(u)||"{}");if(a){var h={};for(var p in c){var g=c[p];Ke(g)||g===""||(h[p]=g)}d=fe(f,h)}else d=fe(c,f);return le.F(u,d),d}catch{}return null},F(u,c,d,f,h,p){var g=le.F(u,c,void 0,void 0,p);try{var m={};l.forEach((v=>{c[v]&&(m[v]=c[v])})),Object.keys(m).length&&Wt.F(u,m,d,f,h,p)}catch(v){le.j(v)}return g},q(u,c){try{w?.localStorage.removeItem(u),Wt.q(u,c)}catch(d){le.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),r=!1,s=e.persistence.toLowerCase();return s==="localstorage"&&le.N()?(n=le,r=!0):s==="localstorage+cookie"&&i.N()?(n=i,r=!0):s==="sessionstorage"&&be.N()?n=be:s==="memory"?n=Ng:s==="cookie"?n=Wt:i.N()?(n=i,r=!0):n=Wt,this.fi=r,n}Si(e){return this.yi+"__"+e}wi(e){return this.fi&&!!e.split_storage}properties(){var e={};return ie(this.props,((n,i)=>{var r=_n(i);if(!r||r.exposure==="event"){if(r!=null&&r.shouldSkipFromEventProperties!=null&&r.shouldSkipFromEventProperties(n))return;e[i]=n}})),e}load(){if(!this.xi){var e=this.ii.H(this.yi);e&&(this.props=fe({},e)),this.pi&&this.Ci()}}Ci(){for(var e of xo){var n=le.H(this.Si(e));if(n&&!Vt(n)){var i=this.Mi(e);i.persisted=!0,this.Ti(e)||(i.fingerprint=this.Ei(n,e)),this.Ii(e,n)||fe(this.props,n)}}}Ti(e){return Object.keys(this.props).some((n=>{var i;return((i=_n(n))==null?void 0:i.storageGroup)===e}))}Ii(e,n){var i=nm[e];if(!i)return!1;var r=n[i],s=this.props[i];return ke(r)&&ke(s)&&s>r}refreshKey(e){var n;if(!this.xi){var i=this.pi?(n=_n(e))==null?void 0:n.storageGroup:void 0,r=i?le.H(this.Si(i)):this.ii.H(this.yi);if(r&&e in r)this.Pi(e,r[e]);else{if(i){var s=this.ii.H(this.yi);if(s&&e in s)return void this.Pi(e,s[e])}this.Ri(e)}}}save(){if(!this.xi){var e=this.ki();e>0?C(this.Ai)&&(this.Ai=setTimeout((()=>{this.Ai=void 0,this.Fi()}),e)):this.Fi()}}flush(){C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0,this.Fi())}Fi(){this.xi||(this.pi?this.Li():this.Oi(this.ii,this.yi,this.props,Hn))}Li(){var e=this.Di(),n=e.main,i=e.groups;for(var r of(this.Oi(this.ii,this.yi,n,Hn),xo)){var s,o=i[r];(!Vt(o)||(s=this.ci[r])!=null&&s.persisted)&&this.Oi(le,this.Si(r),o,r)}}Di(){var e={},n={flags:{},surveys:{}};return ie(this.props,((i,r)=>{var s,o=(s=_n(r))==null?void 0:s.storageGroup;o?n[o][r]=i:e[r]=i})),{main:e,groups:n}}Ei(e,n){if(n===Hn)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var i={};return ie(e,((r,s)=>{var o;i[s]=(o=_n(s))!=null&&o.volatile?"__volatile__":r})),JSON.stringify(i)}Oi(e,n,i,r){var s=this.Mi(r);if(r===Hn||s.dirty||C(s.fingerprint)){var o;try{if((o=this.Ei(i,r))===s.fingerprint)return void(s.dirty=!1)}catch{o=void 0}e.F(n,i,this.$i,this.Ni,this.qi,this.Ne.debug)?(s.dirty=!1,r!==Hn&&(s.persisted=!0),C(o)||(s.fingerprint=o)):this.Ne.debug&&A.warn('failed to persist storage entry "'+n+'"; will retry on next save')}}remove(e){var n=(e===void 0?{}:e).keepGroupEntries,i=n!==void 0&&n;if(C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0),this.ii.q(this.yi,!1),this.ii.q(this.yi,!0),!i&&this.gi)for(var r of xo)le.q(this.Si(r));i?delete this.ci[Hn]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,n,i){if(he(e)){C(n)&&(n="None"),this.$i=C(i)?this.ji:i;var r=!1;if(ie(e,((s,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==n||(this.Pi(o,s),r=!0)})),r)return this.save(),!0}return!1}register(e,n){if(he(e)){this.$i=C(n)?this.ji:n;var i=!1;if(ie(e,((r,s)=>{e.hasOwnProperty(s)&&(this.props[s]!==r||he(r)||U(r))&&(this.Pi(s,r),i=!0)})),i)return this.save(),!0}return!1}unregister(e){var n=typeof e=="string"?[e]:e,i=!1;for(var r of n)r in this.props&&(this.Ri(r),i=!0);i&&this.save()}update_campaign_params(){var e=F?.URL;if(e!==this.mi){var n=yf(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);Vt(cl(n))||this.register(n),this.mi=e}}update_search_keyword(){var e;this.register((e=F?.referrer)?bf(e):{})}update_referrer_info(){var e;this.register_once({$referrer:Ef(),$referring_domain:F!=null&&F.referrer&&((e=rs(F.referrer))==null?void 0:e.host)||os},void 0)}set_initial_person_info(){this.props[ha]||this.props[pa]||this.register_once({[Xr]:Sf(this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties,this.Ne.disable_capture_url_hashes)},void 0)}get_initial_props(){var e={};ie([pa,ha],(r=>{var s=this.props[r];s&&ie(s,(function(o,a){e["$initial_"+Ko(a)]=o}))}));var n=this.props[Xr];if(n){var i=(function(r,s){s===void 0&&(s=!1);var o=xf(r,s),a={};return ie(o,(function(l,u){a["$initial_"+Ko(u)]=l})),a})(n,this.Ne.disable_capture_url_hashes);fe(e,i)}return e}safe_merge(e){return ie(this.props,(function(n,i){i in e||(e[i]=n)})),e}update_config(e,n,i){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!i),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var r=e.persistence!==n.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((f,h)=>f===d[h]))})(e.cookie_persisted_properties||[],n.cookie_persisted_properties||[]),s=r?this.bi(e):this.ii,o=this.wi(e);if(r||o!==this.pi){var a=this.props;this.clear(),this.ii=s,this.pi=o,this.props=a,this.save()}}set_disabled(e){this.xi=e,this.xi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ni&&(this.Ni=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this.qi&&(this.qi=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,n){var i=this.props[Ri]||{};i[e]=n,this.Pi(Ri,i),this.save()}remove_event_timer(e){var n=this.props[Ri]||{},i=n[e];return C(i)||(delete n[e],this.Pi(Ri,n),this.save()),i}get_property(e){return this.props[e]}set_property(e,n){this.Pi(e,n),this.save()}Pi(e,n){var i;this.props[e]=n,(i=_n(e))!=null&&i.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var n,i=(n=_n(e))==null?void 0:n.storageGroup;i&&(this.Mi(i).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function wr(t){var e=!0;return{dispose(){if(e){e=!1;var n=t();n&&De(n.then)&&n.then(void 0,(()=>{}))}}}}var je={GZipJS:"gzip-js",Base64:"base64"},wi={Activation:"events",Cancellation:"cancelEvents"},ko={Popover:"popover",API:"api",Widget:"widget"},qt={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},Co={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},ya={Popover:"popover",Inline:"inline"},rm={SHOWN:"product tour shown"},zc={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},Gc=pe("[RateLimiter]");class sm{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=n=>{var i=n.text;if(i&&i.length)try{(JSON.parse(i).quota_limited||[]).forEach((r=>{Gc.info((r||"events")+" is quota limited."),this.serverLimits[r]=new Date().getTime()+6e4}))}catch(r){return void Gc.warn('could not rate limit - continuing. Error: "'+r?.message+'"',{text:i})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var n,i,r;e===void 0&&(e=!1);var s=this.captureEventsBurstLimit,o=this.captureEventsPerSecond,a=new Date().getTime(),l=(n=(i=this.instance.persistence)==null?void 0:i.get_property(fa))!==null&&n!==void 0?n:{tokens:s,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>s&&(l.tokens=s);var u=1>l.tokens;if(u||e||(l.tokens=Math.max(0,l.tokens-1)),u&&!e){var c=(ke(l.dropped)?l.dropped:0)+1;l.dropped=c,!this.lastEventRateLimited&&this.Hi(c)&&(l.dropped=0)}return this.lastEventRateLimited=u,(r=this.instance.persistence)==null||r.set_property(fa,l),{isRateLimited:u,remainingTokens:l.tokens}}Ui(e){var n=this.instance.config.property_denylist;return!U(n)||!n.includes(e)}zi(){var e;if(this.Ui("$current_url")&&this.Ui("$pathname")&&me!=null&&me.pathname)return""+((e=me.origin)!==null&&e!==void 0?e:"")+me.pathname}Hi(e){var n,i,r=this.captureEventsBurstLimit,s=this.captureEventsPerSecond,o=this.zi(),a=this.Ui("$session_id")?(n=(i=this.instance).get_session_id)==null?void 0:n.call(i):void 0,l=[e+" event(s) dropped since the last warning",o?"triggered on "+o:void 0,a?"session "+a:void 0].filter(Boolean).join(", ");return!!this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited: "+l+". Config is set to "+s+" events per second and "+r+" events burst limit."},{skip_client_rate_limiting:!0})}isServerRateLimited(e){var n=this.serverLimits[e||"events"]||!1;return n!==!1&&new Date().getTime()e(this.remoteConfig))):e()}Vi(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:e})}load(){try{if(this.remoteConfig)return on.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void on.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return on.info("No config found after loading remote JS config. Falling back to JSON."),void this.Vi((n=>{this.Zi(n.json,n),this.Gi()}));this.Zi(e),this.Gi()}))}catch(e){on.error("Error loading remote config",e),this.Zi()}}stop(){this.Ki&&(clearInterval(this.Ki),this.Ki=void 0)}refresh(){!this._instance.Qi()&&F&&F.visibilityState!=="hidden"&&this._instance.reloadFeatureFlags()}Gi(){var e;if(!this.Ki){var n=(e=this._instance.config.remote_config_refresh_interval_ms)!==null&&e!==void 0?e:3e5;n!==0&&(this.Ki=setInterval((()=>{this.refresh()}),n))}}Zi(e,n){!e&&n&&(n.statusCode===0?n.error||on.warn("Failed to fetch remote config from PostHog."):on.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(r){on.error("Error applying remote config",r)}if(e?.hasFeatureFlags!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var i;(i=this._instance.featureFlags)==null||i.ensureFlagsLoaded()}catch(r){on.error("Error loading feature flags",r)}}}var lt=Uint8Array,Ve=Uint16Array,si=Uint32Array,hl=new lt([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]),pl=new lt([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]),Vc=new lt([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Cf=function(t,e){for(var n=new Ve(31),i=0;31>i;++i)n[i]=e+=1<i;++i)for(var s=n[i];n[i+1]>s;++s)r[s]=s-n[i]<<5|i;return[n,r]},Af=Cf(hl,2),wa=Af[1];Af[0][28]=258,wa[258]=28;for(var Kc=Cf(pl,0)[1],Pf=new Ve(32768),_e=0;32768>_e;++_e){var Wn=(43690&_e)>>>1|(21845&_e)<<1;Pf[_e]=((65280&(Wn=(61680&(Wn=(52428&Wn)>>>2|(13107&Wn)<<2))>>>4|(3855&Wn)<<4))>>>8|(255&Wn)<<8)>>>1}var Hi=function(t,e,n){for(var i=t.length,r=0,s=new Ve(e);i>r;++r)++s[t[r]-1];var o,a=new Ve(e);for(r=0;e>r;++r)a[r]=a[r-1]+s[r-1]<<1;for(o=new Ve(i),r=0;i>r;++r)o[r]=Pf[a[t[r]-1]++]>>>15-t[r];return o},$n=new lt(288);for(_e=0;144>_e;++_e)$n[_e]=8;for(_e=144;256>_e;++_e)$n[_e]=9;for(_e=256;280>_e;++_e)$n[_e]=7;for(_e=280;288>_e;++_e)$n[_e]=8;var as=new lt(32);for(_e=0;32>_e;++_e)as[_e]=5;var om=Hi($n,9),am=Hi(as,5),Ff=function(t){return(t/8>>0)+(7&t&&1)},Rf=function(t,e,n){(n==null||n>t.length)&&(n=t.length);var i=new(t instanceof Ve?Ve:t instanceof si?si:lt)(n-e);return i.set(t.subarray(e,n)),i},Nt=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8},bi=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8,t[i+2]|=n>>>16},Ao=function(t,e){for(var n=[],i=0;t.length>i;++i)t[i]&&n.push({s:i,f:t[i]});var r=n.length,s=n.slice();if(!r)return[new lt(0),0];if(r==1){var o=new lt(n[0].s+1);return o[n[0].s]=1,[o,1]}n.sort((function(x,I){return x.f-I.f})),n.push({s:-1,f:25001});var a=n[0],l=n[1],u=0,c=1,d=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=r-1;)a=n[n[d].f>n[u].f?u++:d++],l=n[u!=c&&n[d].f>n[u].f?u++:d++],n[c++]={s:-1,f:a.f+l.f,l:a,r:l};var f=s[0].s;for(i=1;r>i;++i)s[i].s>f&&(f=s[i].s);var h=new Ve(f+1),p=ba(n[c-1],h,0);if(p>e){i=0;var g=0,m=p-e,v=1<i;++i){var S=s[i].s;if(e>=h[S])break;g+=v-(1<>>=m;g>0;){var b=s[i].s;e>h[b]?g-=1<=0&&g;--i){var _=s[i].s;h[_]==e&&(--h[_],++g)}p=e}return[new lt(h),p]},ba=function(t,e,n){return t.s==-1?Math.max(ba(t.l,e,n+1),ba(t.r,e,n+1)):e[t.s]=n},Yc=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new Ve(++e),i=0,r=t[0],s=1,o=function(l){n[i++]=l},a=1;e>=a;++a)if(t[a]==r&&a!=e)++s;else{if(!r&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(r),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(r);s=1,r=t[a]}return[n.subarray(0,i),e]},Ei=function(t,e){for(var n=0,i=0;e.length>i;++i)n+=t[i]*e[i];return n},Ea=function(t,e,n){var i=n.length,r=Ff(e+2);t[r]=255&i,t[r+1]=i>>>8,t[r+2]=255^t[r],t[r+3]=255^t[r+1];for(var s=0;i>s;++s)t[r+s+4]=n[s];return 8*(r+4+i)},Jc=function(t,e,n,i,r,s,o,a,l,u,c){Nt(e,c++,n),++r[256];for(var d=Ao(r,15),f=d[0],h=d[1],p=Ao(s,15),g=p[0],m=p[1],v=Yc(f),S=v[0],b=v[1],_=Yc(g),x=_[0],I=_[1],T=new Ve(19),E=0;S.length>E;++E)T[31&S[E]]++;for(E=0;x.length>E;++E)T[31&x[E]]++;for(var P=Ao(T,7),$=P[0],O=P[1],L=19;L>4&&!$[Vc[L-1]];--L);var N,V,G,M,R=u+5<<3,Z=Ei(r,$n)+Ei(s,as)+o,Ce=Ei(r,f)+Ei(s,g)+o+14+3*L+Ei(T,$)+(2*T[16]+3*T[17]+7*T[18]);if(Z>=R&&Ce>=R)return Ea(e,c,t.subarray(l,l+u));if(Nt(e,c,1+(Z>Ce)),c+=2,Z>Ce){N=Hi(f,h),V=f,G=Hi(g,m),M=g;var oe=Hi($,O);for(Nt(e,c,b-257),Nt(e,c+5,I-1),Nt(e,c+10,L-4),c+=14,E=0;L>E;++E)Nt(e,c+3*E,$[Vc[E]]);c+=3*L;for(var ye=[S,x],$e=0;2>$e;++$e){var ae=ye[$e];for(E=0;ae.length>E;++E)Nt(e,c,oe[Ie=31&ae[E]]),c+=$[Ie],Ie>15&&(Nt(e,c,ae[E]>>>5&127),c+=ae[E]>>>12)}}else N=om,V=$n,G=am,M=as;for(E=0;a>E;++E)if(i[E]>255){var Ie;bi(e,c,N[257+(Ie=i[E]>>>18&31)]),c+=V[Ie+257],Ie>7&&(Nt(e,c,i[E]>>>23&31),c+=hl[Ie]);var Se=31&i[E];bi(e,c,G[Se]),c+=M[Se],Se>3&&(bi(e,c,i[E]>>>5&8191),c+=pl[Se])}else bi(e,c,N[i[E]]),c+=V[i[E]];return bi(e,c,N[256]),c+V[256]},lm=new si([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),cm=(function(){for(var t=new si(256),e=0;256>e;++e){for(var n=e,i=9;--i;)n=(1&n&&3988292384)^n>>>1;t[e]=n}return t})(),Po=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8};function um(t,e){e===void 0&&(e={});var n=(function(){var d=4294967295;return{p(f){for(var h=d,p=0;f.length>p;++p)h=cm[255&h^f[p]]^h>>>8;d=h},d(){return 4294967295^d}}})(),i=t.length;n.p(t);var r,s,o,a,l,u=(a=10+((r=e).filename&&r.filename.length+1||0),l=8,(function(d,f,h,p,g,m){var v=d.length,S=new lt(p+v+5*(1+Math.floor(v/7e3))+g),b=S.subarray(p,S.length-g),_=0;if(!f||8>v)for(var x=0;v>=x;x+=65535){var I=x+65535;v>I?_=Ea(b,_,d.subarray(x,I)):(b[x]=!0,_=Ea(b,_,d.subarray(x,v)))}else{for(var T=lm[f-1],E=T>>>13,P=8191&T,$=(1<x;++x){var Ie=G(x),Se=32767&x,Be=L[Ie];if(O[Se]=Be,L[Ie]=Se,x>=$e){var yt=v-x;if((Ce>7e3||ye>24576)&&yt>423){_=Jc(d,b,0,M,R,Z,oe,ye,ae,x-ae,_),ye=Ce=oe=0,ae=x;for(var ge=0;286>ge;++ge)R[ge]=0;for(ge=0;30>ge;++ge)Z[ge]=0}var Ye=2,wt=0,gn=P,Re=Se-Be&32767;if(yt>2&&Ie==G(x-Re))for(var Pe=Math.min(E,yt)-1,Tt=Math.min(32767,x),Bn=Math.min(258,yt);Tt>=Re&&--gn&&Se!=Be;){if(d[x+Ye]==d[x+Ye-Re]){for(var qe=0;Bn>qe&&d[x+qe]==d[x+qe-Re];++qe);if(qe>Ye){if(Ye=qe,wt=Re,qe>Pe)break;var Dn=Math.min(Re,qe-2),$t=0;for(ge=0;Dn>ge;++ge){var Mt=x-Re+ge+32768&32767,ct=Mt-O[Mt]+32768&32767;ct>$t&&($t=ct,Be=Mt)}}}Re+=(Se=Be)-(Be=O[Se])+32768&32767}if(wt){M[ye++]=268435456|wa[Ye]<<18|Kc[wt];var rn=31&wa[Ye],gi=31&Kc[wt];oe+=hl[rn]+pl[gi],++R[257+rn],++Z[gi],$e=x+Ye,++Ce}else M[ye++]=d[x],++R[d[x]]}}_=Jc(d,b,!0,M,R,Z,oe,ye,ae,x-ae,_)}return Rf(S,0,p+Ff(_)+g)})(s=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):12+o.mem,a,l)),c=u.length;return(function(d,f){var h=f.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>f.level?4:f.level==9?2:0,d[9]=3,f.mtime!=0&&Po(d,4,Math.floor(new Date(f.mtime||Date.now())/1e3)),h){d[3]=8;for(var p=0;h.length>=p;++p)d[p+10]=h.charCodeAt(p)}})(u,e),Po(u,c-8,n.d()),Po(u,c-4,i),u}var dm=!!zo||!!Xa,Tf="text/plain",$r=!1,$f=(t,e)=>{var n=t.split("#"),i=n[1],r=n[0].split("?"),s=r[0],o=r[1];if(!o)return t;var a=o.split("&").filter((l=>l.split("=")[0]!==e)).join("&");return s+(a?"?"+a:"")+(i?"#"+i:"")},ks=function(t,e,n){var i;n===void 0&&(n=!0);var r=t.split("?"),s=r[0],o=r[1],a=k({},e),l=(i=o?.split("&").map((c=>{var d,f=c.split("="),h=f[0],p=n&&(d=a[h])!==null&&d!==void 0?d:f[1];return delete a[h],h+"="+p})))!==null&&i!==void 0?i:[],u=(function(c,d){var f,h;d===void 0&&(d="&");var p=[];return ie(c,(function(g,m){C(g)||C(m)||m==="undefined"||(f=encodeURIComponent((v=>v instanceof File)(g)?g.name:g.toString()),h=encodeURIComponent(m),p[p.length]=h+"="+f)})),p.join(d)})(a);return u&&l.push(u),l.length>0?s+"?"+l.join("&"):s},Fo=t=>{if(t.Ji)return t.Ji;var e=t.data,n=t.compression;if(e){if(n===je.GZipJS){var i=um((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new lt(a.length+(a.length>>>1)),d=0,f=function(m){c[d++]=m},h=0;u>h;++h){if(d+5>c.length){var p=new lt(d+8+(u-h<<1));p.set(c),c=p}var g=a.charCodeAt(h);128>g?f(g):2048>g?(f(192|g>>>6),f(128|63&g)):g>55295&&57344>g?(f(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++h))>>>18),f(128|g>>>12&63),f(128|g>>>6&63),f(128|63&g)):(f(224|g>>>12),f(128|g>>>6&63),f(128|63&g))}return Rf(c,0,d)})(Yn(e)),{mtime:0});return{contentType:Tf,body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),estimatedSize:i.byteLength}}if(n===je.Base64){var r=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(Yn(e)),s=(a=>"data="+encodeURIComponent(typeof a=="string"?a:Yn(a)))(r);return{contentType:"application/x-www-form-urlencoded",body:s,estimatedSize:new Blob([s]).size}}var o=Yn(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},Mf=t=>{var e,n,i=()=>t.transport==="sendBeacon"?{url:ks(t.url,{compression:je.Base64}),encodedBody:Fo(k({},t,{compression:je.Base64,Ji:void 0}))}:{url:$f(t.url,"compression"),encodedBody:Fo(k({},t,{compression:void 0,Ji:void 0}))};try{e=Fo(t)}catch(r){if(mc(t.compression,ii(t.url,"compression")))return A.error("Failed to gzip request body, sending uncompressed payload",r),i();throw r}return e&&mc(t.compression,ii(t.url,"compression"))&&!((n=e.body)instanceof ArrayBuffer?Go(new Uint8Array(n)):ArrayBuffer.isView(n)&&Go(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)))?($r=!0,i()):{url:t.url,encodedBody:e}},Lf=t=>{try{return Mf(t)}catch(e){return A.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},fm=(function(){var t=se((function*(e){var n=Yn(e.data),i=yield(function(s,o,a){return Vo.apply(this,arguments)})(n,ne.DEBUG,{rethrow:!0});if(!i)return e;var r=yield i.arrayBuffer();return k({},e,{Ji:{contentType:Tf,body:r,estimatedSize:r.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),hm=/Failed to fetch|NetworkError|Load failed/i,Nf=t=>t?.name==="TypeError"&&hm.test(t?.message||""),Of=t=>{var e=Lf(t);if(e){var n=e.url,i=e.encodedBody,r=i??{},s=r.contentType,o=r.body,a=r.estimatedSize,l=new Headers;ie(t.headers,(function(p,g){l.append(g,p)})),s&&l.append("Content-Type",s);var u=null,c=!1;if(uc){var d=new uc;u={signal:d.signal,timeout:setTimeout((()=>{var p,g;c=!0,d.abort((p=t.timeout,(g=new Error("PostHog request timed out"+(p?" after "+p+"ms":""))).name="AbortError",g))}),t.timeout)}}var f=p=>{c&&p?.name==="AbortError"||Nf(p)?A.warn(p):A.error(p),t.callback==null||t.callback({statusCode:0,error:p})};try{var h;Xa(n,k({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(h=u)==null?void 0:h.signal},t.fetchOptions)).then((p=>p.text().then((g=>{var m={statusCode:p.status,text:g};if(p.status===200)try{m.json=JSON.parse(g)}catch(v){A.error(v)}t.callback==null||t.callback(m)})))).catch(f).finally((()=>u?clearTimeout(u.timeout):null))}catch(p){u&&clearTimeout(u.timeout),f(p)}}},Sa=t=>{try{var e,n=Mf(t),i=n.url,r=n.encodedBody,s=r??{},o=s.body,a=s.estimatedSize;if(!o)return;var l=o instanceof Blob?o:new Blob([o],{type:s.contentType});if(Ue.sendBeacon(i,l))return;var u=U(t.data)?t.data:(e=t.data)==null?void 0:e.batch;if(U(u)&&u.length>1&&(a??0)>16384){var c=Math.ceil(u.length/2),d=f=>U(t.data)?f:k({},t.data,{batch:f});return Sa(k({},t,{data:d(u.slice(0,c))})),void Sa(k({},t,{data:d(u.slice(c))}))}A.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),Of(k({},t,{Yi:!0}))}catch(f){A.warn("Beacon send failed",f)}},Zc=(t,e,n,i)=>{var r=i==="query"?e==="POST"?"sent_at":"_":void 0;return ks(n===je.GZipJS?$f(t,"compression"):t,k({},r?{[r]:Date.now().toString()}:{},n===je.GZipJS?{}:{compression:n}))},Mr=[];Xa&&Mr.push({transport:"fetch",method:Of}),zo&&Mr.push({transport:"XHR",method(t){var e=Lf(t);if(e){var n=new zo,i=e.encodedBody;n.open(t.method||"GET",e.url,!0);var r=i??{},s=r.contentType,o=r.body;ie(t.headers,(function(a,l){n.setRequestHeader(l,a)})),s&&n.setRequestHeader("Content-Type",s),t.timeout&&(n.timeout=t.timeout),n.onreadystatechange=()=>{if(n.readyState===4){var a={statusCode:n.status,text:n.responseText};if(n.status===200)try{a.json=JSON.parse(n.responseText)}catch{}t.callback==null||t.callback(a)}},n.send(o)}}}),Ue!=null&&Ue.sendBeacon&&Mr.push({transport:"sendBeacon",method:Sa});var xa=3e3;class pm{constructor(e,n){this.Xi=!0,this.tr=[],this.er=Ct(n?.flush_interval_ms||xa,250,5e3,A.createLogger("flush interval"),xa),this.ir=e}enqueue(e){this.tr.push(e),this.rr||this.nr()}unload(){this.sr();var e=this.tr.length>0?this.ar():{},n=Object.values(e);[...n.filter((i=>i.url.indexOf("/e")===0)),...n.filter((i=>i.url.indexOf("/e")!==0))].map((i=>{this.lr(k({},i,{transport:"sendBeacon"}))}))}enable(){this.Xi=!1,this.nr()}nr(){var e=this;this.Xi||(this.rr=setTimeout((()=>{if(this.sr(),this.tr.length>0){var n=this.ar(),i=function(){var s=n[r],o=new Date().getTime();s.data&&U(s.data)&&ie(s.data,(a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp})),e.lr(s)};for(var r in n)i()}}),this.er))}lr(e){try{this.ir(e)}catch(n){A.error(n)}}sr(){clearTimeout(this.rr),this.rr=void 0}ar(){var e={};return ie(this.tr,(n=>{var i,r=n,s=(r?r.batchKey:null)||r.url;C(e[s])&&(e[s]=k({},r,{data:[]})),(i=e[s].data)==null||i.push(r.data)})),this.tr=[],e}}var gm=["retriesPerformedSoFar"];class mm{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!C(w)&&"onLine"in w.navigator&&(this.dr=w.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},ve(w,"online",this.vr),ve(w,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var n=e.retriesPerformedSoFar,i=ud(e,gm);Bt(n)&&(i.url=ks(i.url,{retry_count:n})),this._instance._send_request(k({},i,{callback:r=>{if(r.statusCode!==200&&(400>r.statusCode||r.statusCode>=500)){if((r.statusCode===0?3:10)>(n??0))return void this.At(k({retriesPerformedSoFar:n},i));r.statusCode===0&&A.warn("Request failed before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped retrying after "+(n??0)+" retries.")}i.callback==null||i.callback(r)}}))}At(e){var n=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=n+1;var i=(function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),c=Math.random()-.5;return Math.ceil(u+c*(u-l))})(n),r=Date.now()+i;this.tr.push({retryAt:r,requestOptions:e});var s="Enqueued failed request for retry in "+i;navigator.onLine||(s+=" (Browser is offline)"),A.warn(s),this.ur||(this.ur=!0,this.gr())}gr(){if(this.mr&&clearTimeout(this.mr),this.tr.length===0)return this.ur=!1,void(this.mr=void 0);this.mr=setTimeout((()=>{this.dr&&this.tr.length>0&&this.cr(),this.gr()}),this.hr)}cr(){var e=Date.now(),n=[],i=this.tr.filter((s=>e>s.retryAt||(n.push(s),!1)));if(this.tr=n,i.length>0)for(var r of i)this.retriableRequest(r.requestOptions)}unload(){for(var e of(this.mr&&(clearTimeout(this.mr),this.mr=void 0),this.ur=!1,C(w)||(this.vr&&(w.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(w.removeEventListener("offline",this.pr),this.pr=void 0)),this.tr)){var n=e.requestOptions;try{this._instance._send_request(k({},n,{transport:"sendBeacon"}))}catch(i){A.error(i)}}this.tr=[]}}class vm{constructor(e){this.yr=()=>{var n,i,r,s;this.br||(this.br={});var o=this.scrollElement(),a=this.scrollY(),l=o?Math.max(0,o.scrollHeight-o.clientHeight):0,u=a+(o?.clientHeight||0),c=o?.scrollHeight||0;this.br.lastScrollY=Math.ceil(a),this.br.maxScrollY=Math.max(a,(n=this.br.maxScrollY)!==null&&n!==void 0?n:0),this.br.maxScrollHeight=Math.max(l,(i=this.br.maxScrollHeight)!==null&&i!==void 0?i:0),this.br.lastContentY=u,this.br.maxContentY=Math.max(u,(r=this.br.maxContentY)!==null&&r!==void 0?r:0),this.br.maxContentHeight=Math.max(c,(s=this.br.maxContentHeight)!==null&&s!==void 0?s:0)},this._instance=e}get _r(){return this._instance.config.scroll_root_selector}getContext(){return this.br}resetContext(){var e=this.br;return setTimeout(this.yr,0),e}startMeasuringScrollPosition(){ve(w,"scroll",this.yr,{capture:!0}),ve(w,"scrollend",this.yr,{capture:!0}),ve(w,"resize",this.yr)}scrollElement(){if(!this._r)return w?.document.documentElement;var e=U(this._r)?this._r:[this._r];for(var n of e){var i=w?.document.querySelector(n);if(i)return i}}wr(e){var n=e==="y"?"scrollTop":"scrollLeft";if(this._r){var i=this.scrollElement();return i&&i[n]||0}return w?e==="y"?w.scrollY||w.pageYOffset||w.document.documentElement.scrollTop||0:w.scrollX||w.pageXOffset||w.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var _m=t=>Sf(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class Xc{constructor(e,n,i,r){this.kr=s=>{var o=this.Sr();if(!o||o.sessionId!==s){var a={sessionId:s,props:this.Cr(this._instance)};this.Mr.register({[da]:a})}},this._instance=e,this.Tr=n,this.Mr=i,this.Cr=r||_m,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[da]}getSetOnceProps(){var e,n=(e=this.Sr())==null?void 0:e.props;return n?"r"in n?xf(n,this._instance.config.disable_capture_url_hashes):{$referring_domain:n.referringDomain,$pathname:n.initialPathName,utm_source:n.utm_source,utm_campaign:n.utm_campaign,utm_medium:n.utm_medium,utm_content:n.utm_content,utm_term:n.utm_term}:{}}getSessionProps(){var e={};return ie(cl(this.getSetOnceProps()),((n,i)=>{i==="$current_url"&&(i="url"),e["$session_entry_"+Ko(i)]=n})),e}}class gl{on(e,n){return this.Er[e]||(this.Er[e]=[]),this.Er[e].push(n),()=>{this.Er[e]=this.Er[e].filter((i=>i!==n))}}emit(e,n){for(var i of this.Er[e]||[])i(n);for(var r of this.Er["*"]||[])r(e,n)}constructor(){this.Er={}}}var Si=pe("[SessionId]");class Qc{on(e,n){return this.Ir.on(e,n)}constructor(e,n,i){var r;if(this.Pr=null,this.Rr=[],this.Ar=void 0,this.Fr=!1,this.Ir=new gl,this.Lr=(u,c)=>!(!Bt(u)||!Bt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===Ht)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Ne=e.config,this.Mr=e.persistence,this.Or=void 0,this.Dr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.$r=n||Ut,this.Nr=i||Ut;var s=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*Ct(this.Ne.session_idle_timeout_seconds||1800,60,36e3,Si.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.qr(),this.jr="ph_"+s+"_window_id",this.Br="ph_"+s+"_primary_window_exists",this.Hr()){var o=be.H(this.jr),a=be.H(this.Br);o&&!a?this.Or=o:be.q(this.jr),be.F(this.Br,!0)}if((r=this.Ne.bootstrap)!=null&&r.sessionID)try{var l=(u=>{var c=this.Ne.bootstrap.sessionID.replace(/-/g,"");if(c.length!==32)throw new Error("Not a valid UUID");if(c[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(c.substring(0,12),16)})();this.Ur(this.Ne.bootstrap.sessionID,new Date().getTime(),l)}catch(u){Si.error("Invalid sessionID in bootstrap",u)}this.zr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return C(this.Rr)&&(this.Rr=[]),this.Rr.push(e),this.Dr&&e(this.Dr,this.Or),()=>{this.Rr=this.Rr.filter((n=>n!==e))}}Hr(){return this.Ne.persistence!=="memory"&&!this.Mr.xi&&be.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&be.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?be.H(this.jr):null}Zr(e){var n=this.Pr;return!Ke(n)&&!Ke(e)&&5e3>Math.abs(e-n)}Ur(e,n,i){var r=n!==this._sessionActivityTimestamp,s=!(e!==this.Dr||i!==this._sessionStartTimestamp);this._sessionStartTimestamp=i,this._sessionActivityTimestamp=n,this.Dr=e,s&&!r||s&&this.Zr(n)||(this.Pr=n,this.Mr.register({[Kn]:[n,e,i]}))}Gr(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return Bt(n)&&n>0}Qr(){this.Gr()?this.Mr.refreshKey(Kn):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!Ke(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this.Pr){this.Qr();var n=this.Jr();n[1]===this.Dr&&n[2]===this._sessionStartTimestamp&&(this.Pr=this._sessionActivityTimestamp,this.Mr.register({[Kn]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],n=Bt(e)?e:0,i=Bt(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(n,i)}Xr(e){return this.Qr(),this.Lr(e,this.Yr())}Jr(){var e=this.Mr.props[Kn];return U(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Pr=null,clearTimeout(this.tn),this.tn=void 0,this.Ur(null,null,null)}destroy(){this.Fr=!0,this.Kr(),clearTimeout(this.tn),this.tn=void 0,this.Ar&&w&&(w.removeEventListener(ts,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&be.q(this.Br)},ve(w,ts,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=null),this.Ne.cookieless_mode===Ht)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var i=n||new Date().getTime(),r=this.Jr(),s=r[1],o=r[2],a=this.Yr(),l=this.Vr(),u=Bt(o)&&Math.abs(i-o)>864e5,c=!1,d=!1,f=!s,h=s,p=!f&&!e&&this.Lr(i,a);if(p){(p=this.Xr(i))||Si.info("cross-tab refresh kept the session alive",{sessionId:s});var g=this.Jr();s=g[1],o=g[2]}f||p||u?(s=this.$r(),l=this.Nr(),Si.info("new session ID generated",{sessionId:s,windowId:l,changeReason:{noSessionId:f,activityTimeout:p,sessionPastMaximumLength:u}}),o=i,c=!0):(l||(l=this.Nr(),c=!0),(d=s!==h)&&(Si.info("adopted cross-tab session id",{sessionId:s,windowId:l}),c=!0));var m=Bt(a)&&e&&!u?a:i,v=Bt(o)?o:new Date().getTime();this.Wr(l),this.Ur(s,m,v),e||this.qr();var S={noSessionId:f,activityTimeout:p,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((b=>b(s,l,S))),{sessionId:s,windowId:l,sessionStartTimestamp:v,changeReason:c?S: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 Bf=function(t,e){if(!t)return!1;var n=t.userAgent;if(n&&_c(n,e))return!0;try{var i=t?.userAgentData;if(i!=null&&i.brands&&i.brands.some((r=>_c(r?.brand,e))))return!0}catch{}return!!t.webdriver};function Df(){return(Df=se((function*(){var t=Ue?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),n=e?.model;return X(n)&&n.length>0?n:void 0}catch(i){return void A.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",i)}}))).apply(this,arguments)}var ls=function(t,e){if(!(function(n){try{new RegExp(n)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function Ro(t,e,n){return Yn({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}var jf={exact:(t,e)=>e.some((n=>t.some((i=>n===i)))),is_not:(t,e)=>e.every((n=>t.every((i=>n!==i)))),regex:(t,e)=>e.some((n=>t.some((i=>ls(n,i))))),not_regex:(t,e)=>e.every((n=>t.every((i=>!ls(n,i))))),icontains:(t,e)=>e.map(br).some((n=>t.map(br).some((i=>n.includes(i))))),not_icontains:(t,e)=>e.map(br).every((n=>t.map(br).every((i=>!n.includes(i))))),gt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>i>parseFloat(r)))})),lt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>it.toLowerCase();function Uf(t,e){return!t||Object.entries(t).every((n=>{var i=n[1],r=e?.[n[0]];if(C(r)||Ke(r))return!1;var s=[String(r)],o=jf[i.operator];return!!o&&o(i.values,s)}))}var Ia="custom",eu="i.posthog.com",ym=/^\/static\//;class wm{constructor(e){this.en={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,n=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return n||(n=this.apiHost.replace("."+eu,".posthog.com")),n==="https://app.posthog.com"?"https://us.posthog.com":n}get region(){return this.en[this.apiHost]||(this.en[this.apiHost]=/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"us":/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"eu":Ia),this.en[this.apiHost]}rn(e){if(ym.test(e)){var n=this.instance.config.asset_host;if(typeof n=="string")return n.trim().replace(/\/$/,"")||void 0}}endpointFor(e,n){if(n===void 0&&(n=""),n&&(n=n[0]==="/"?n:"/"+n),e==="ui")return this.uiHost+n;if(e==="flags")return this.flagsApiHost+n;if(e==="assets"){var i=this.rn(n);if(i)return""+i+n}if(this.region===Ia)return this.apiHost+n;var r=eu+n;switch(e){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}}function Hf(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var Q=pe("[Surveys]"),Wf="seenSurvey_",qf=t=>{try{var e=(n=>((i,r)=>""+Wf+(function(s){return s.current_iteration&&s.current_iteration>0?s.id+"_"+s.current_iteration:s.id})(r))(0,n))(t);if(localStorage.getItem(e))return;localStorage.setItem(e,"true")}catch(n){Q.error("Failed to persist survey seen state",n)}},bm=[ko.Popover,ko.Widget,ko.API],Em={ignoreConditions:!1,ignoreDelay:!1,displayType:ya.Popover},Sm=pe("[PostHog ExternalIntegrations]"),xm={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class Im{constructor(e){this._instance=e}ai(e,n){var i;(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,e,(r=>{if(r)return Sm.error("failed to load script",r);n()}))}startIfEnabledOrStop(){var e=this,n=function(){var s,o,a,l=i[0],u=i[1];!u||(s=B.__PosthogExtensions__)!=null&&(s=s.integrations)!=null&&s[l]||e.ai(xm[l],(()=>{var c;(c=B.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=B.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=B.__PosthogExtensions__)==null||(a=a.integrations)==null||(a=a[l])==null||a.stop())};for(var i of Object.entries((r=this._instance.config.integrations)!==null&&r!==void 0?r:{})){var r;n()}}}class km{constructor(e,n){this.rt=e,this.nn=n,this.sn=new Map,this.an=!1}add(e){var n=this;return se((function*(){if(n.an)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(n.sn.has(e.name))throw new Error('Browser extension "'+e.name+'" is already registered');n.sn.set(e.name,e);try{var i=e.setup(n.nn);i&&(yield i)}catch(s){var r=n.sn.get(e.name)===e;r&&n.sn.delete(e.name),n.rt.error('Failed to set up browser extension "'+e.name+'"',s),r&&n.ln(e)}}))()}dispose(){if(!this.an){this.an=!0;var e=Array.from(this.sn.values()).reverse();for(var n of(this.sn.clear(),e))this.ln(n)}}ln(e){try{var n=e.dispose==null?void 0:e.dispose();n&&De(n.then)&&n.then(void 0,(i=>{this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}))}catch(i){this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}}}class Cm{constructor(e){this._instance=e}initialize(){}get(e){var n=this._instance.persistence;if(typeof e=="string")return n?.get_property(e);var i={};for(var r of e){var s=n?.get_property(r);C(s)||(i[r]=s)}return i}set(e,n){var i;(i=this._instance.persistence)==null||i.register(typeof e=="string"?{[e]:n}:e)}remove(e){var n;(n=this._instance.persistence)==null||n.unregister(e)}}var tu="extensionsRemoteConfig";class Am{constructor(e){this.an=!1,this.instance=e,this.rt=A,this.un=e.hn,this.kv=new Cm(e),this.onEvent=n=>wr(this.instance.on("eventCaptured",(i=>{try{n({event:i.event,properties:i.properties})}catch(r){this.rt.error("Browser extension event listener failed",r)}}))),this.onRemoteConfig=n=>{if(this.an)return wr((()=>{}));var i=s=>{try{n(s)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},r=this.instance.dn.on(tu,i);return this.un&&i(this.un),wr(r)},this.vn=new km(A.createLogger("[BrowserExtensions]"),this)}get logger(){return this.rt}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return(e=this.instance.get_property(Yi))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(Yi);return typeof e=="string"?e:void 0}get library(){return{name:ne.LIB_NAME,version:ne.LIB_VERSION}}get initialPersonProperties(){var e,n;return(e=(n=this.instance.persistence)==null?void 0:n.get_initial_props())!==null&&e!==void 0?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,n,i,r,s=(e=this.instance.sessionManager)==null?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:(n=s?.sessionId)!==null&&n!==void 0?n:"",windowId:(i=s?.windowId)!==null&&i!==void 0?i:"",sessionStartTimestamp:(r=s?.sessionStartTimestamp)!==null&&r!==void 0?r:0}}catch{return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get projectToken(){return this.instance.config.token}add(e){return this.vn.add(e)}capture(e,n,i){var r=this;return se((function*(){i?r.instance.capture(e,n,{timestamp:i.timestamp,uuid:i.uuid,$set:i.set,$set_once:i.setOnce}):r.instance.capture(e,n)}))()}registerDynamicEventProperties(e){return wr(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(tu,e))}sendRequest(e,n){var i=this;return se((function*(){var r;n===void 0&&(n={});var s=i.instance.requestRouter.endpointFor((r=n.target)!==null&&r!==void 0?r:"api",e),o={method:n.method,url:n.query?ks(s,n.query):s,data:n.body,headers:n.headers,timeout:n.timeoutMs,fireCallbackOnDrop:!0,transport:n.transport,compression:n.compression,timestampMode:n.sentAt};return n.transport==="sendBeacon"?(i.instance._send_request(o),{statusCode:202}):new Promise((a=>{o.callback=a,i.instance._send_request(o)}))}))()}dispose(){this.an||(this.an=!0,this.vn.dispose())}}var Wi={},To=0,cs=()=>{},nu='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',xi="Surveys module not available",iu="sanitize_properties is deprecated. Use before_send instead",zf="Invalid value for property_denylist config: ",Pm=["token","distinct_id",Zd],Vn="posthog",Gf=!dm&&Ge?.indexOf("MSIE")===-1&&Ge?.indexOf("Mozilla")===-1,$o=t=>{var e;return k({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:Fg(F?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:cs,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:t??"unset",__preview_deferred_init_extensions:!1,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:me&&X(me?.search)&&me.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disableDeviceModel:!1,disable_external_dependency_loading:!1,strict_script_versioning:!1,enable_recording_console_log:void 0,secure_cookie:(w==null||(e=w.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(n){A.error("Bad HTTP status: "+n.statusCode+" "+n.text)},get_device_id:n=>n,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:ga,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:xa},error_tracking:{},_onCapture:cs},(n=>({rageclick:n&&n>="2026-05-30"?{content_ignorelist:Hg,ignore_text_selection:!0}:!n||"2025-11-30">n||{content_ignorelist:!0},capture_pageview:!n||"2025-05-24">n||"history_change",session_recording:n&&n>="2026-06-25"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6},streamNetworkBody:!0}:n&&n>="2026-05-30"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6}}:n&&n>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:n&&n>="2026-01-30"?"head":"body",internal_or_test_user_hostname:n&&n>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:n&&n>="2026-05-30"?250:0,split_storage:!(!n||"2026-05-30">n),detect_google_search_app:!(!n||"2026-05-30">n),disable_capture_url_hashes:!(!n||"2026-06-25">n)}))(t))},Fm=[["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"]],ru=t=>{var e={};for(var n of Fm){var i=n[0],r=n[1];C(t[i])||(e[r]=t[i])}var s=fe({},e,t),o=t.__preview_external_dependency_versioned_paths;return C(o)||(C(t.strict_script_versioning)&&(s.strict_script_versioning=!!o),X(o)&&C(t.asset_host)&&(s.asset_host=o)),U(t.property_blacklist)&&(C(t.property_denylist)?s.property_denylist=t.property_blacklist:U(t.property_denylist)?s.property_denylist=[...t.property_blacklist,...t.property_denylist]:A.error(zf+t.property_denylist)),s};class Rm{constructor(){this.__forceAllowLocalhost=!1}get fn(){return this.__forceAllowLocalhost}set fn(e){A.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class Je{pn(e,n){if(e){var i=this.sn.indexOf(e);i!==-1&&this.sn.splice(i,1)}return this.sn.push(n),n.initialize==null||n.initialize(),n}gn(){return this.config.cookieless_mode===Ht||this.config.cookieless_mode===In&&this.consent.isRejected()}get decideEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){var e;this.webPerformance=new Rm,this.mn=!1,this.version=ne.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new gl,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=$o(),this.SentryIntegration=Jg,this.sentryIntegration=i=>(function(r,s){var o=mf(r,s);return{name:gf,processEvent:a=>o(a)}})(this,i),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.wn=!1,this.kn=null,this.xn=null,this.Sn=null,this.scrollManager=new vm(this),this.pageViewManager=new Wc(this),this.rateLimiter=new sm(this),this.requestRouter=new wm(this),this.consent=new Og(this),this.externalIntegrations=new Im(this);var n=(e=Je.__defaultExtensionClasses)!==null&&e!==void 0?e:{};this.featureFlags=n.featureFlags&&new n.featureFlags(this),this.toolbar=n.toolbar&&new n.toolbar(this),this.surveys=n.surveys&&new n.surveys(this),this.conversations=n.conversations&&new n.conversations(this),this.logs=n.logs&&new n.logs(this),this.metrics=n.metrics&&new n.metrics(this),this.experiments=n.experiments&&new n.experiments(this),this.exceptions=n.exceptions&&new n.exceptions(this),this.people={set:(i,r,s)=>{var o=X(i)?{[i]:r}:i;this.setPersonProperties(o),s?.({})},set_once:(i,r,s)=>{var o=X(i)?{[i]:r}:i;this.setPersonProperties(void 0,o),s?.({})}},this.on("eventCaptured",(i=>A.info('send "'+i?.event+'"',i)))}init(e,n,i){if(i&&i!==Vn){var r,s=(r=Wi[i])!==null&&r!==void 0?r:new Je;return s._init(e,n,i),Wi[i]=s,Wi[Vn][i]=s,s}return this._init(e,n,i)}_init(e,n,i){var r,s;n===void 0&&(n={});var o,a=X(e)?e.trim():"";if(!a)return A.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return a!==((o=this.config)==null?void 0:o.token)?console.warn("[PostHog.js]","You have already initialized PostHog with a different project token! Re-initializing is a no-op, so events will keep going to the project this instance was initialized with. To capture into a second project, load PostHog once, then initialize a named instance after the SDK has loaded, e.g. posthog.init('"+a+"', { ... }, 'project2')"):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=$o(n.defaults),n.debug=this.Cn(n.debug),this.Mn=n,this.Tn=[],n.person_profiles?this.xn=n.person_profiles:n.process_person&&(this.xn=n.process_person);var l=$o(n.defaults),u=ru(n),c=fe({},l,u,{name:i,token:a});he(l.rageclick)&&he(u.rageclick)&&(c.rageclick=fe({},l.rageclick,u.rageclick)),he(l.session_recording)&&he(u.session_recording)&&(c.session_recording=fe({},l.session_recording,u.session_recording)),this.set_config(c),this.config.on_xhr_error&&A.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=n.disable_compression?void 0:je.GZipJS;var d=this.En();if(this.persistence=new Io(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Io(k({},this.config,{persistence:"sessionStorage"}),d,!1),this.bn="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&be.N()){var f=be.H(this.bn);U(f)&&f.forEach((I=>{X(I)&&this.yn.add(I)}))}else be.q(this.bn);var h=k({},this.persistence.props),p=k({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new pm((I=>this.Pn(I)),this.config.request_queue_config),this.Rn=new mm(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new Qc(this),this.sessionPropsManager=new Xc(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((I,T,E)=>{(E!=null&&E.activityTimeout||E!=null&&E.sessionPastMaximumLength||E!=null&&E.crossTabAdoption)&&this.An()}))),this.Fn(),this.config.__preview_deferred_init_extensions?(A.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Ln(g)}),0)):(A.info("Initializing extensions synchronously"),this.Ln(g)),ne.DEBUG=ne.DEBUG||this.config.debug,ne.DEBUG&&A.info("Starting in debug mode",{this:this,config:n,thisC:k({},this.config),p:h,s:p}),!this.config.identity_distinct_id||(r=n.bootstrap)!=null&&r.distinctID||(n.bootstrap=k({},n.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((s=n.bootstrap)==null?void 0:s.distinctID)!==void 0){var m=n.bootstrap.distinctID,v=this.get_distinct_id(),S=this.persistence.get_property(ot);if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&S===Un)this.identify(m);else if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&S===mn)A.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{var b=this.config.get_device_id(Ut()),_=n.bootstrap.isIdentifiedID?b:m;this.persistence.set_property(ot,n.bootstrap.isIdentifiedID?mn:Un),this.register({distinct_id:m,$device_id:_})}}if(g)this.register_once({distinct_id:gr,$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(ot,Un)}return ve(w,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),n.segment?(function(I,T){var E=I.config.segment;if(!E)return T();(function(P,$){var O=P.config.segment;if(!O)return $();var L=V=>{var G=()=>V.anonymousId()||Ut();P.config.get_device_id=G,V.id()&&(P.register({distinct_id:V.id(),$device_id:G()}),P.persistence.set_property(ot,mn)),$()},N=O.user();"then"in N&&De(N.then)?N.then(L):L(N)})(I,(()=>{E.register((P=>{typeof Promise<"u"&&Promise.resolve||So.warn("This browser does not have Promise support, and can not use the segment integration");var $=(O,L)=>{if(!L)return O;O.event.userId||O.event.anonymousId===P.get_distinct_id()||(So.info("No userId set, resetting PostHog"),P.reset()),O.event.userId&&O.event.userId!==P.get_distinct_id()&&(So.info("UserId set, identifying with PostHog"),P.identify(O.event.userId));var N=P.calculateEventProperties(L,O.event.properties);return O.event.properties=Object.assign({},N,O.event.properties),O};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:O=>$(O,O.event.event),page:O=>$(O,Gn),identify:O=>$(O,wo),screen:O=>$(O,"$screen")}})(I)).then((()=>{T()}))}))})(this,(()=>this.On())):this.On(),De(this.config._onCapture)&&this.config._onCapture!==cs&&(A.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(I=>this.config._onCapture(I.event,I)))),this.config.ip&&A.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this.config.disableDeviceModel||(function(){return Df.apply(this,arguments)})().then((I=>{I&&this.register({[_o]:I})})).catch(cs),this}Fn(){var e,n,i,r,s,o,a=(e=(n=this.config.__extensionClasses)==null?void 0:n.featureFlags)!==null&&e!==void 0?e:(i=Je.__defaultExtensionClasses)==null?void 0:i.featureFlags;a&&(this.featureFlags&&this.featureFlags instanceof a||((r=this.Dn)==null||r.call(this),this.Dn=void 0,this.featureFlags=new a(this)),De(this.featureFlags.onReloading)&&De(this.featureFlags.setup)?this.Dn||(this.Dn=this.featureFlags.onReloading((()=>{this.dn.emit("featureFlagsReloading",!0)})),this.$n().add(this.featureFlags)):(s=(o=this.featureFlags).initialize)==null||s.call(o))}Ln(e){var n,i,r,s,o,a,l,u=performance.now(),c=k({},Je.__defaultExtensionClasses,this.config.__extensionClasses),d=[];c.exceptions&&this.sn.push(this.exceptions=(n=this.exceptions)!==null&&n!==void 0?n:new c.exceptions(this)),c.historyAutocapture&&this.sn.push(this.historyAutocapture=new c.historyAutocapture(this)),c.tracingHeaders&&this.sn.push(this.tracingHeaders=new c.tracingHeaders(this)),c.siteApps&&this.sn.push(this.siteApps=new c.siteApps(this)),c.sessionRecording&&!e&&this.sn.push(this.sessionRecording=new c.sessionRecording(this)),this.config.disable_scroll_properties||d.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),c.autocapture&&this.sn.push(this.autocapture=new c.autocapture(this)),c.surveys&&this.sn.push(this.surveys=(i=this.surveys)!==null&&i!==void 0?i:new c.surveys(this)),c.logs&&this.sn.push(this.logs=(r=this.logs)!==null&&r!==void 0?r:new c.logs(this)),c.metrics&&this.sn.push(this.metrics=(s=this.metrics)!==null&&s!==void 0?s:new c.metrics(this)),c.conversations&&this.sn.push(this.conversations=(o=this.conversations)!==null&&o!==void 0?o:new c.conversations(this)),c.productTours&&this.sn.push(this.productTours=new c.productTours(this)),c.heatmaps&&this.sn.push(this.heatmaps=new c.heatmaps(this)),c.webVitalsAutocapture&&this.sn.push(this.webVitalsAutocapture=new c.webVitalsAutocapture(this)),c.exceptionObserver&&this.sn.push(this.exceptionObserver=new c.exceptionObserver(this)),c.deadClicksAutocapture&&this.sn.push(this.deadClicksAutocapture=new c.deadClicksAutocapture(this,Yg)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((f=>{f.initialize&&d.push((()=>{f.initialize==null||f.initialize()}))})),d.push((()=>{if(this.Nn){var f=this.Nn;this.Nn=void 0,this.sn.forEach((h=>h.onRemoteConfig==null?void 0:h.onRemoteConfig(f)))}})),this.qn(d,u)}qn(e,n){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,n)}),0);var i=e.shift();if(i)try{i()}catch(s){A.error("Error initializing extension:",s)}}var r=Math.round(performance.now()-n);this.register_for_session({[Xd]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[Qd]:r}),this.config.__preview_deferred_init_extensions&&A.info("PostHog extensions initialized ("+r+"ms)")}Zi(e){var n;if(!F||!F.body)return A.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.Zi(e)}),500);if(this.config.__preview_deferred_init_extensions&&(this.Nn=e),this.hn=e,this.compression=void 0,e.ok){var i,r=e.config;r.supportedCompression&&!this.config.disable_compression&&(this.compression=j(r.supportedCompression,je.GZipJS)?je.GZipJS:j(r.supportedCompression,je.Base64)?je.Base64:void 0),(i=r.analytics)!=null&&i.endpoint&&(this.analyticsDefaultEndpoint=r.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:ga}),(n=this.jn)==null||n.handleRemoteConfig(e),this.sn.forEach((s=>s.onRemoteConfig==null?void 0:s.onRemoteConfig(e)))}On(){try{this.config.loaded(this)}catch(i){A.critical("`loaded` function failed",i)}if(this.Bn(),this.config.internal_or_test_user_hostname&&me!=null&&me.hostname){var e=me.hostname,n=this.config.internal_or_test_user_hostname;(typeof n=="string"?e===n:n.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.gn())&&this.Hn()}),1),this.Un=new kf(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()&&mr(this.__request_queue,(e=>this.Pn(e))),this.__request_queue=[],this.Bn()}_handle_unload(){var e,n,i,r,s;(e=this.surveys)==null||e.handlePageUnload==null||e.handlePageUnload(),(n=this.metrics)==null||n.flush("sendBeacon"),this.config.request_batching?(this.zn()&&this.capture(yo),(i=this.logs)==null||i.flushLogs("sendBeacon"),(r=this.In)==null||r.unload(),(s=this.Rn)==null||s.unload()):this.zn()&&this.capture(yo,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?Gf?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)?e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:429})):(e.transport=e.transport||this.config.api_transport,e.headers=k({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,(C(this.config.disable_beacon)?this.config.__preview_disable_beacon:this.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(n=>{var i,r,s,o=k({},n);o.timeout=o.timeout||6e4;var a,l,u,c,d,f=(i=o.transport)!==null&&i!==void 0?i:"fetch";f==="sendBeacon"&&C(o.compression)&&o.data&&(o.compression=je.Base64),o.method==="POST"&&o.data&&(o.timestampMode==="capture-body"?o.data={api_key:(l=(d=(c=U(a=o.data)?a:[a])[0])==null||(u=d.properties)==null?void 0:u.token)!==null&&l!==void 0?l:d?.token,batch:c,sent_at:new Date().toISOString()}:o.timestampMode==="body"&&(o.data=(function(m,v){return v===void 0&&(v=new Date().toISOString()),U(m)?m.map((S=>k({},S,{sent_at:v}))):k({},m,{sent_at:v})})(o.data))),o.url=Zc(o.url,o.method,o.compression,o.timestampMode);var h=Mr.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),p=(r=(s=(function(m,v){for(var S=0;m.length>S;S++)if(m[S].transport===f)return m[S]})(h))==null?void 0:s.method)!==null&&r!==void 0?r:h[0].method;if(!p)throw new Error("No available transport method");var g=m=>{try{p(m)}catch(v){Nf(v)?A.warn(v):A.error(v),o.callback==null||o.callback({statusCode:0,error:v})}};f!=="sendBeacon"&&o.data&&o.compression===je.GZipJS&&Tp&&typeof Promise<"u"&&!$r?fm(o).then((m=>{g(m)})).catch((m=>{if(vc(m))return $r=!0,void g(k({},o,{compression:void 0,url:Zc(n.url,n.method,void 0,n.timestampMode)}));(v=>{if(!v||typeof v!="object")return!1;var S="name"in v?String(v.name):"";return vc(v)||S===dd})(m)&&($r=!0),g(o)})):p(o)})(k({},e,{callback:n=>{var i,r;this.rateLimiter.checkForLimiting(n),400>n.statusCode||(i=(r=this.config).on_request_error)==null||i.call(r,n),e.callback==null||e.callback(n)}}))):e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:0}))}Pn(e){this.Rn?this.Rn.retriableRequest(e):this._send_request(e)}_execute_array(e){To++;try{var n,i=[],r=[],s=[];mr(e,(a=>{if(a)if(U(n=a[0]))s.push(a);else if(De(a))try{a.call(this)}catch(l){A.error("Error executing queued PostHog call",a,l)}else U(a)&&n==="alias"?i.push(a):U(a)&&n.indexOf("capture")!==-1&&De(this[n])?s.push(a):r.push(a)}));var o=function(a,l){mr(a,(function(u){try{if(U(u[0])){var c=l;ie(u,(function(d){c=c[d[0]].apply(c,d.slice(1))}))}else l[u[0]].apply(l,u.slice(1))}catch(d){A.error("Error executing queued PostHog call",u,d)}}))};o(i,this),o(r,this),o(s,this)}finally{To--}}push(e){if(To>0&&U(e)&&X(e[0])){var n=Je.prototype[e[0]];De(n)&&n.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,n,i){var r,s,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.In){if(this.is_capturing())if(!C(e)&&X(e)){var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var c=i!=null&&i.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(c==null||!c.isRateLimited){n!=null&&n.$current_url&&!X(n?.$current_url)&&(A.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),n==null||delete n.$current_url),e!=="$exception"||i!=null&&i.Wn||A.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,f=i?.timestamp||d,h=Ec(i?.uuid,Ut),p={uuid:h,event:e,properties:this.calculateEventProperties(e,n||{},f,h)};e===Gn&&this.config.__preview_capture_bot_pageviews&&u&&(p.event="$bot_pageview",p.properties.$browser_type="bot"),c&&(p.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&p.properties.$feature_flag_has_experiment===!1&&this.get_property(Jr)===!0;i?.$set&&!g&&(p.$set=i?.$set);var m=i?.$unset;m&&(p.$unset=m);var v,S,b,_=g?void 0:this.Vn(i?.$set_once,e!==Ac,e===wo);if(_&&(p.$set_once=_),i!=null&&i._noTruncate||(s=this.config.properties_string_max_length,o=p,a=L=>X(L)?L.slice(0,s):L,l=new Set,p=(function L(N,V){if(N!==Object(N))return a?a(N):N;if(!l.has(N)){var G;if(l.add(N),U(N))G=[],mr(N,(R=>{G.push(L(R))}));else{var M={};ie(N,((R,Z)=>{l.has(R)||(M[Z]=L(R))})),G=M}return G}})(o)),p.timestamp=f,C(i?.timestamp)||(p.properties.$event_time_override_provided=!0,p.properties.$event_time_override_system_time=d),g&&(p.properties=(function(L,N){N===void 0&&(N=[]);var V={},G=M=>{L[M]!==void 0&&(V[M]=L[M])};return $p.forEach(G),N.forEach(G),V})(p.properties,Pm)),e===qt.DISMISSED||e===qt.SENT){var x=n?.[Co.SURVEY_ID],I=n?.[Co.SURVEY_ITERATION];qf({id:x,current_iteration:I}),p.$set=k({},p.$set,{[(v={id:x,current_iteration:I},S=e===qt.SENT?"responded":"dismissed",b="$survey_"+S+"/"+v.id,v.current_iteration&&v.current_iteration>0&&(b="$survey_"+S+"/"+v.id+"/"+v.current_iteration),b)]:!0})}else e===qt.SHOWN&&(p.$set=k({},p.$set,{[Co.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===rm.SHOWN){var T=n?.[zc.TOUR_TYPE];T&&(p.$set=k({},p.$set,{[zc.TOUR_LAST_SEEN_DATE+"/"+T]:new Date().toISOString()}))}var E=k({},p.properties.$set,p.$set);if(Vt(E)||this.setPersonPropertiesForFlags(E),!H(this.config.before_send)){var P=this.Pt(p);if(!P)return;(p=P).uuid=Ec(p.uuid,Ut)}this.dn.emit("eventCaptured",p);var $=(r=i?._url)!==null&&r!==void 0?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),O={method:"POST",url:$,data:p,compression:"best-available",timestampMode:i?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test($)?"body":"capture-body",batchKey:i?._batchKey,transport:i?.transport};return!this.config.request_batching||i&&(i==null||!i._batchKey)||i!=null&&i.send_instantly?this.Pn(O):this.In.enqueue(O),p}A.critical("This capture call is ignored due to client rate limiting.")}}else A.error("No event name provided to posthog.capture")}else A.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(n=>e(n.event,n)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new Am(this)}cn(e){this._n.push(e);var n=!0;return()=>{if(n){n=!1;var i=this._n.indexOf(e);i!==-1&&this._n.splice(i,1)}}}calculateEventProperties(e,n,i,r,s){if(i=i||new Date,!this.persistence||!this.sessionPersistence)return n;var o=s?void 0:this.persistence.remove_event_timer(e),a=k({},n);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.gn()&&(a[Zd]=!0),e==="$snapshot"){var l=k({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!X(a.distinct_id)&&!ke(a.distinct_id)||Yo(a.distinct_id))&&A.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=(function(x,I,T,E){var P,$,O,L;if(E===void 0&&(E=!1),!Ge)return{};var N,V=x?[...ri,...I||[]]:[],G=(function(Bn){for(var qe=0;wc.length>qe;qe++){var Dn=wc[qe],$t=Dn[1],Mt=Dn[0].exec(Bn),ct=Mt&&(De($t)?$t(Mt,Bn):$t);if(ct)return ct}return["",""]})(Ge),M=G[0],R=G[1],Z=(N=typeof navigator<"u"?navigator:void 0)!=null&&N.brave?{brave:!0}:{},Ce={};C(T)||(Ce.detectGoogleSearchApp=T);var oe={},ye=(P=navigator)==null||(P=P.userAgentData)==null?void 0:P.platform,$e=($=navigator)==null?void 0:$.maxTouchPoints,ae=w==null||(O=w.screen)==null?void 0:O.width,Ie=w==null||(L=w.screen)==null?void 0:L.height,Se=w?.devicePixelRatio;C(ye)||(oe.userAgentDataPlatform=ye),C($e)||(oe.maxTouchPoints=$e),C(ae)||(oe.screenWidth=ae),C(Ie)||(oe.screenHeight=Ie),C(Se)||(oe.devicePixelRatio=Se);var Be,yt,ge,Ye,wt,gn,Re,Pe,Tt=fe(cl({$os:M,$os_version:R,$browser:Nd(Ge,navigator.vendor,Z,Ce),$device:bc(Ge),$device_type:(yt=Ge,ge=oe,Pe=bc(yt),Pe===_d||Pe===vd||Pe==="Kobo"||Pe==="Kindle Fire"||Pe===Rd?ei:Pe===Vi||Pe===Xn||Pe===Ki||Pe===Zo?"Console":Pe===wd?"Wearable":Pe?it:ge?.userAgentDataPlatform==="Android"&&((Ye=ge?.maxTouchPoints)!==null&&Ye!==void 0?Ye:0)>0?600>Math.min((wt=ge?.screenWidth)!==null&&wt!==void 0?wt:0,(gn=ge?.screenHeight)!==null&&gn!==void 0?gn:0)/((Re=ge?.devicePixelRatio)!==null&&Re!==void 0?Re:1)?it:ei:"Desktop"),$timezone:If(),$timezone_offset:tm()}),{$current_url:Zi(E?dn(me?.href):me?.href,V,Xi),$host:me?.host,$pathname:me?.pathname,$raw_user_agent:Ge.length>1e3?Ge.substring(0,997)+"...":Ge,$browser_version:Xp(Ge,navigator.vendor,Z,Ce),$browser_language:qc(),$browser_language_prefix:(Be=qc(),typeof Be=="string"?Be.split("-")[0]:void 0),$screen_height:w?.screen.height,$screen_width:w?.screen.width,$viewport_height:w?.innerHeight,$viewport_width:w?.innerWidth,$lib:ne.LIB_NAME,$lib_version:ne.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return ne.SDK_DIST_CHANNEL&&(Tt.$sdk_dist_channel=ne.SDK_DIST_CHANNEL),Tt})(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties,this.config.detect_google_search_app,this.config.disable_capture_url_hashes);if(this.sessionManager){var d=this.sessionManager.checkAndGetSessionAndWindowId(s,i.getTime()),f=d.windowId;a.$session_id=d.sessionId,a.$window_id=f}this.sessionPropsManager&&fe(a,this.sessionPropsManager.getSessionProps());try{var h;this.sessionRecording&&fe(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(h=this.Rn)==null?void 0:h.length}catch(x){a.$sdk_debug_error_capturing_properties=String(x)}if(this.requestRouter.region===Ia&&(a.$lib_custom_api_host=this.config.api_host),u=e!==Gn||s?e!==yo||s?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(i):this.pageViewManager.doPageView(i,r),a=fe(a,u),e===Gn&&F&&(a.title=F.title),!C(o)){var p=i.getTime()-o;a.$duration=parseFloat((p/1e3).toFixed(3))}Ge&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();ie(["$referrer","$referring_domain"],(x=>{x in g&&delete m[x]}));var v={};if(this._n.length>0)for(var S of this._n.slice())try{fe(v,S())}catch(x){A.error("Failed to produce browser extension event properties",x)}(a=fe({},c,g,m,k({},v,a))).$is_identified=this._isIdentified(),U(this.config.property_denylist)?ie(this.config.property_denylist,(function(x){delete a[x]})):A.error(zf+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var b=this.config.sanitize_properties;b&&(A.error(iu),a=b(a,e));var _=this.Zn();return a.$process_person_profile=_,_&&!s&&this.Gn("_calculate_event_properties"),a}Vn(e,n,i){var r;if(n===void 0&&(n=!0),i===void 0&&(i=!1),!this.persistence||!this.Zn()||this.mn&&!i)return e;var s=this.persistence.get_initial_props(),o=(r=this.sessionPropsManager)==null?void 0:r.getSetOnceProps(),a=fe({},s,o||{},e||{}),l=this.config.sanitize_properties;return l&&(A.error(iu),a=l(a,"$set_once")),n&&(this.mn=!0),Vt(a)?void 0:a}register(e,n){var i;(i=this.persistence)==null||i.register(e,n)}register_once(e,n,i){var r;(r=this.persistence)==null||r.register_once(e,n,i)}register_for_session(e){var n;(n=this.sessionPersistence)==null||n.register(e),Object.keys(e).forEach((i=>this.yn.add(i))),this.Qn()}unregister(e){var n;(n=this.persistence)==null||n.unregister(e)}unregister_for_session(e){var n;(n=this.sessionPersistence)==null||n.unregister(e),this.yn.delete(e),this.Qn()}Kn(e,n){this.register({[e]:n})}An(){this.yn.forEach((e=>{var n;(n=this.sessionPersistence)==null||n.unregister(e)})),this.yn.clear(),this.Qn()}Qn(){var e;if(this.bn)if(this.config.persistence==="memory"||(e=this.sessionPersistence)!=null&&e.xi||!be.N())be.q(this.bn);else{var n=[];this.yn.forEach((i=>n.push(i))),n.length>0?be.F(this.bn,n):be.q(this.bn)}}getFeatureFlag(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlag(e,n)}getFeatureFlagPayload(e){var n;return(n=this.featureFlags)==null?void 0:n.getFeatureFlagPayload(e)}getFeatureFlagResult(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlagResult(e,n)}getAllFeatureFlags(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.getAllFeatureFlags())!==null&&e!==void 0?e:[]}isFeatureEnabled(e,n){var i,r;return(i=(r=this.featureFlags)==null?void 0:r.isFeatureEnabled(e,n))!==null&&i!==void 0?i:n?.defaultValue}reloadFeatureFlags(){var e;(e=this.featureFlags)==null||e.reloadFeatureFlags()}updateFlags(e,n,i){var r;(r=this.featureFlags)==null||r.updateFlags(e,n,i)}updateEarlyAccessFeatureEnrollment(e,n,i){var r;(r=this.featureFlags)==null||r.updateEarlyAccessFeatureEnrollment(e,n,i)}getEarlyAccessFeatures(e,n,i){var r;return n===void 0&&(n=!1),(r=this.featureFlags)==null?void 0:r.getEarlyAccessFeatures(e,n,i)}on(e,n){return this.dn.on(e,n)}onFeatureFlags(e){return this.featureFlags?this.featureFlags.onFeatureFlags(e):(e([],{},{errorsLoading:!0}),()=>{})}onSurveysLoaded(e){return this.surveys?this.surveys.onSurveysLoaded(e):(e([],{isLoaded:!1,error:xi}),()=>{})}onSessionId(e){var n,i;return(n=(i=this.sessionManager)==null?void 0:i.onSessionId(e))!==null&&n!==void 0?n:()=>{}}getSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getSurveys(e,n):e([],{isLoaded:!1,error:xi})}getActiveMatchingSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,n):e([],{isLoaded:!1,error:xi})}renderSurvey(e,n){var i;(i=this.surveys)==null||i.renderSurvey(e,n)}displaySurvey(e,n){var i;n===void 0&&(n=Em),(i=this.surveys)==null||i.displaySurvey(e,n)}cancelPendingSurvey(e){var n;(n=this.surveys)==null||n.cancelPendingSurvey(e)}canRenderSurvey(e){var n,i;return(n=(i=this.surveys)==null?void 0:i.canRenderSurvey(e))!==null&&n!==void 0?n:{visible:!1,disabledReason:xi}}canRenderSurveyAsync(e,n){var i,r;return n===void 0&&(n=!1),(i=(r=this.surveys)==null?void 0:r.canRenderSurveyAsync(e,n))!==null&&i!==void 0?i:Promise.resolve({visible:!1,disabledReason:xi})}Jn(e){return!e||Yo(e)?(A.critical("Unique user id has not been set in posthog.identify"),!1):e===gr?(A.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.'),!1):!["distinct_id","distinctid"].includes(e.toLowerCase())&&!["undefined","null"].includes(e.toLowerCase())||(A.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.'),!1)}identify(e,n,i){if(!this.__loaded||!this.persistence)return A.uninitializedWarning("posthog.identify");if(ke(e)&&(e=e.toString(),A.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.Jn(e)&&this.Gn("posthog.identify")){var r=this.get_distinct_id();this.register({$user_id:e}),this.get_property(Yi)||this.register_once({$had_persisted_distinct_id:!0,$device_id:r},""),e!==r&&e!==this.get_property(Fi)&&(this.unregister(Fi),this.register({distinct_id:e}));var s,o=(this.persistence.get_property(ot)||Un)===Un,a=e!==r,l=!a&&o;if(a&&o)this.persistence.set_property(ot,mn),this.setPersonPropertiesForFlags({$set:n||{},$set_once:i||{}},!1),this.capture(wo,{distinct_id:e,$anon_distinct_id:r},{$set:n||{},$set_once:i||{}}),this.Sn=Ro(e,n,i),(s=this.featureFlags)==null||s.setAnonymousDistinctId(r);else if(l){this.persistence.set_property(ot,mn);var u=n||{},c=i||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=Ro(e,n,i)}else(n||i)&&this.setPersonProperties(n,i);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(kn)):l&&(n||i)&&this.reloadFeatureFlags()}}setPersonProperties(e,n){if((e||n)&&this.Gn("posthog.setPersonProperties")){var i=Ro(this.get_distinct_id(),e,n);this.Sn!==i?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:n||{}},!0),this.capture("$set",{$set:e||{},$set_once:n||{}}),this.Sn=i):A.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}unsetPersonProperties(e){var n,i=(U(e)?e:[e]).filter((r=>X(r)&&r.length>0));i.length!==0&&this.Gn("posthog.unsetPersonProperties")&&((n=this.featureFlags)==null||n.unsetPersonPropertiesForFlags(i,!0),this.capture("$set",{$unset:i}),this.Sn=null)}group(e,n,i){if(e&&n){var r=this.getGroups(),s=r[e]!==n;if(s&&this.resetGroupPropertiesForFlags(e),this.register({$groups:k({},r,{[e]:n})}),s||i){var o={$group_type:e,$group_key:n};i&&(o.$group_set=i),this.capture(Ac,o)}i&&this.setGroupPropertiesForFlags({[e]:i}),s&&!i&&this.reloadFeatureFlags()}else A.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),(i=this.featureFlags)==null||i.setPersonPropertiesForFlags(e,n)}resetPersonPropertiesForFlags(e){var n;e===void 0&&(e=!0),(n=this.featureFlags)==null||n.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((i=this.featureFlags)==null||i.setGroupPropertiesForFlags(e,n))}resetGroupPropertiesForFlags(e){var n;(n=this.featureFlags)==null||n.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,n){var i,r,s,o,a,l,u,c,d,f;if(n===void 0&&(n=!1),A.info("reset"),!this.__loaded)return A.uninitializedWarning("posthog.reset");var h,p=this.get_property(Yi),g=this.get_property(_o),m=this.get_property(An),v=this.is_capturing();if(this.consent.reset(),n||!v||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after."),(i=this.persistence)==null||i.clear(),(r=this.sessionPersistence)==null||r.clear(),this.yn.clear(),this.Qn(),C(m)||(h=this.persistence)==null||h.register({[An]:m}),(s=this.surveys)==null||s.reset(),(o=this.Un)==null||o.stop(),(a=this.featureFlags)==null||a.reset(),(l=this.conversations)==null||l.reset(),(u=this.logs)==null||u.reset(),(c=this.metrics)==null||c.reset(),(d=this.persistence)==null||d.set_property(ot,Un),(f=this.sessionManager)==null||f.resetSessionId(),this.Sn=null,this.config.cookieless_mode===Ht)this.register_once({distinct_id:gr,$device_id:null},"");else{var S=this.config.get_device_id(Ut());this.register_once({distinct_id:S,$device_id:e?S:p},""),e||C(g)||this.register({[_o]:g})}this.register({$last_posthog_reset:new Date().toISOString()},1),delete this.config.identity_distinct_id,delete this.config.identity_hash,this.reloadFeatureFlags()}shutdown(e){var n=this;return se((function*(){var i,r,s,o,a,l,u;if(n.__loaded){(i=n.Un)==null||i.stop(),(r=n.jn)==null||r.dispose(),(s=n.sessionRecording)==null||s.dispose(),(o=n.logs)==null||o.flushLogs("sendBeacon"),(a=n.metrics)==null||a.flush("sendBeacon"),(l=n.In)==null||l.unload(),(u=n.Rn)==null||u.unload();try{var c;(c=n.featureFlags)==null||c.destroy()}catch(d){A.error("Error while destroying feature flags",d)}}else A.uninitializedWarning("posthog.shutdown")}))()}setIdentity(e,n){var i;this.config.identity_distinct_id=e,this.config.identity_hash=n,this.alias(e),(i=this.conversations)==null||i.Xn()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,(e=this.conversations)==null||e.ts()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,n;return(e=(n=this.sessionManager)==null?void 0:n.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var n=this.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.sessionStartTimestamp,r=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+n.sessionId);if(e!=null&&e.withTimestamp&&i){var s,o=(s=e.timestampLookBack)!==null&&s!==void 0?s:10;if(!i)return r;r+="?t="+Math.max(Math.floor((new Date().getTime()-i)/1e3)-o,0)}return r}alias(e,n){return e===this.get_property(zd)?(A.critical("Attempting to create alias for existing People user - aborting."),-2):this.Gn("posthog.alias")?(C(n)&&(n=this.get_distinct_id()),e!==n?(this.Kn(Fi,e),this.capture("$create_alias",{alias:e,distinct_id:n})):(A.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var n=k({},this.config);if(he(e)){var i,r,s,o,a,l,u,c,d,f,h,p;fe(this.config,ru(e));var g=this.En();(i=this.persistence)==null||i.update_config(this.config,n,g),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Io(k({},this.config,{persistence:"sessionStorage"}),g,!1);var m=this.Cn(this.config.debug);gt(m)&&(this.config.debug=m),gt(this.config.debug)&&(this.config.debug?(ne.DEBUG=!0,le.N()&&le.F("ph_debug",!0),A.info("set_config",{config:e,oldConfig:n,newConfig:k({},this.config)})):(ne.DEBUG=!1,le.N()&&le.q("ph_debug"))),(r=this.featureFlags)==null||r.updateConfig==null||r.updateConfig(this.config,this.Qi()),(s=this.exceptionObserver)==null||s.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(f=this.deadClicksAutocapture)==null||f.startIfEnabledOrStop(),(h=this.surveys)==null||h.loadIfEnabled(),this.es(),(p=this.externalIntegrations)==null||p.startIfEnabledOrStop()}}_overrideSDKInfo(e,n){ne.LIB_NAME=e,ne.LIB_VERSION=n}startSessionRecording(e){var n,i,r,s,o,a=e===!0,l={sampling:a||!(e==null||!e.sampling),linked_flag:a||!(e==null||!e.linked_flag),url_trigger:a||!(e==null||!e.url_trigger),event_trigger:a||!(e==null||!e.event_trigger)};Object.values(l).some(Boolean)&&((n=this.sessionManager)==null||n.checkAndGetSessionAndWindowId(),l.sampling&&((i=this.sessionRecording)==null||i.overrideSampling()),l.linked_flag&&((r=this.sessionRecording)==null||r.overrideLinkedFlag()),l.url_trigger&&((s=this.sessionRecording)==null||s.overrideTrigger("url")),l.event_trigger&&((o=this.sessionRecording)==null||o.overrideTrigger("event"))),this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,n){if(this.exceptions){var i=new Error("PostHog syntheticException"),r=this.exceptions.buildProperties(e,{handled:!0,syntheticException:i});return this.exceptions.sendExceptionEvent(k({},r,n))}}addExceptionStep(e,n){var i;(i=this.exceptions)==null||i.addExceptionStep(e,n)}captureLog(e){var n;(n=this.logs)==null||n.captureLog(e)}get logger(){var e,n;return(e=(n=this.logs)==null?void 0:n.logger)!==null&&e!==void 0?e:Je.rs}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var n,i;return(n=(i=this.toolbar)==null?void 0:i.loadToolbar(e))!==null&&n!==void 0&&n}get_property(e){var n;return(n=this.persistence)==null?void 0:n.props[e]}getSessionProperty(e){var n;return(n=this.sessionPersistence)==null?void 0:n.props[e]}toString(){var e,n=(e=this.config.name)!==null&&e!==void 0?e:Vn;return n!==Vn&&(n=Vn+"."+n),n}_isIdentified(){var e,n;return((e=this.persistence)==null?void 0:e.get_property(ot))===mn||((n=this.sessionPersistence)==null?void 0:n.get_property(ot))===mn}Zn(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles===ga&&!this._isIdentified()&&Vt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[Fi])&&((n=this.persistence)==null||(n=n.props)==null||!n[Qr]))}zn(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Zn()||this.Gn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.Gn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}Gn(e){return this.config.person_profiles==="never"?(A.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Kn(Qr,!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!==In)}es(){var e,n,i,r,s=this.En();return((e=this.persistence)==null?void 0:e.xi)!==s&&((i=this.persistence)==null||i.set_disabled(s)),((n=this.sessionPersistence)==null?void 0:n.xi)!==s&&((r=this.sessionPersistence)==null||r.set_disabled(s)),s&&(this.yn.clear(),this.Qn()),s}opt_in_capturing(e){var n;if(this.config.cookieless_mode!==Ht){if(this.gn()){var i,r,s,o,a;this.Yn(!0,!0),(i=this.sessionManager)==null||i.destroy(),(r=this.pageViewManager)==null||r.destroy(),this.sessionManager=new Qc(this),this.pageViewManager=new Wc(this),this.persistence&&(this.sessionPropsManager=new Xc(this,this.sessionManager,this.persistence));var l,u=(s=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&s!==void 0?s:(a=Je.__defaultExtensionClasses)==null?void 0:a.sessionRecording;u&&(this.sessionRecording=this.pn(this.sessionRecording,new u(this)),this.hn&&((l=this.sessionRecording)==null||l.onRemoteConfig==null||l.onRemoteConfig(this.hn)))}var c,d;this.consent.optInOut(!0),this.es(),this.Bn(),(n=this.sessionRecording)==null||n.startIfEnabledOrStop(),this.config.cookieless_mode==In&&((c=this.surveys)==null||c.loadIfEnabled()),(C(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((d=e?.captureEventName)!==null&&d!==void 0?d:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hn()}else A.warn(nu)}opt_out_capturing(){var e,n,i;this.config.cookieless_mode!==Ht?(this.config.cookieless_mode===In&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===In&&(this.register({distinct_id:gr,$device_id:null}),(e=this.sessionRecording)==null||e.stopRecording(),this.sessionRecording=void 0,(n=this.sessionManager)==null||n.destroy(),(i=this.pageViewManager)==null||i.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.Hn(),this.Bn())):A.warn(nu)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===Ht||(this.config.cookieless_mode===In?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return Ue?Bf(Ue,this.config.custom_blocked_useragents):void 0}Hn(){F&&(F.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(Gn,{title:F.title},{send_instantly:!0}),this.kn&&(F.removeEventListener(es,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),ve(F,es,this.kn)))}debug(e){e===!1?(w?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(w?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}Qi(){var e=this.Mn||{};return"advanced_disable_flags"in e?!!e.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(A.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(function(n,i,r,s,o){var a=i in n&&!H(n[i]),l=r in n&&!H(n[r]);return a?n[i]:!!l&&(o&&o.warn("Config field '"+r+"' is deprecated. Please use '"+i+"' instead. The old field will be removed in a future major version."),n[r])})(e,"advanced_disable_flags","advanced_disable_decide",0,A)}Pt(e){var n;if(H(this.config.before_send))return e;var i=Object.keys((n=e.properties)!==null&&n!==void 0?n:{}).filter(jp),r=U(this.config.before_send)?this.config.before_send:[this.config.before_send],s=e;for(var o of r){if(s=o(s),H(s)){var a="Event '"+e.event+"' was rejected in beforeSend function";return Dp(e.event)?A.warn(a+". This can cause unexpected behavior."):A.info(a),null}s.properties&&!Vt(s.properties)||A.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}for(var l of i)if(s.properties&&H(s.properties[l]))return A.warn("Event '"+e.event+"' had its '"+l+"' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped."),null;return s}getPageViewId(){var e;return(e=this.pageViewManager.ui)==null?void 0:e.pageViewId}captureTraceFeedback(e,n){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:n})}captureTraceMetric(e,n,i){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:n,$ai_metric_value:String(i)})}Cn(e){var n=gt(e)&&!e,i=le.N()&&le.P("ph_debug")==="true";return!n&&(!!i||e)}}Je.__defaultExtensionClasses={},Je.rs=(()=>{var t=()=>{};return{trace:t,debug:t,info:t,warn:t,error:t,fatal:t}})(),(function(t,e){for(var n=0;e.length>n;n++)t.prototype[e[n]]=Ag(t.prototype[e[n]])})(Je,["identify"]);class su{constructor(e){this.disabled=e===!1;var n=he(e)?e:{};this.thresholdPx=n.threshold_px||30,this.timeoutMs=n.timeout_ms||1e3,this.clickCount=n.click_count||3,this.clicks=[]}isRageClick(e,n,i){if(this.disabled)return!1;var r=this.clicks[this.clicks.length-1];if(r&&Math.abs(e-r.x)+Math.abs(n-r.y)i-r.timestamp){if(this.clicks.push({x:e,y:n,timestamp:i}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:n,timestamp:i}];return!1}}var Mo="$copy_autocapture",Lo=pe("[AutoCapture]");function No(t,e){return e.length>t?e.slice(0,t)+"...":e}function Tm(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!fn(e));return e}function $m(t,e){var n,i,r=e.e,s=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!fn(t))return{props:{}};for(var c=[t],d=new Set([t]),f=t;f.parentNode&&!Qe(f,"body")&&lf>c.length;)if(af(f.parentNode)){var h=f.parentNode.host;if(d.has(h))break;d.add(h),c.push(h),f=h}else{if(!fn(f.parentNode)||d.has(f.parentNode))break;d.add(f.parentNode),c.push(f.parentNode),f=f.parentNode}var p,g,m=[],v={},S=!1,b=!1;if(ie(c,(E=>{var P=_a(E);if(Qe(E,"a")){var $=E.getAttribute("href");S=!!(P&&$&&Ui($))&&(u?dn($):$)}j(is(E),"ph-no-capture")&&(b=!0),m.push((function(L,N,V,G,M){M===void 0&&(M=!1);var R=L.tagName.toLowerCase(),Z={tag_name:R};dl.indexOf(R)>-1&&!V&&(Z.$el_text=R.toLowerCase()==="a"||R.toLowerCase()==="button"?No(1024,jc(L)):No(1024,Ji(L)));var Ce=is(L);Ce.length>0&&(Z.classes=Ce.filter((function(ae){return ae!==""}))),ie(L.attributes,(function(ae){var Ie;if((!hf(L)||["name","id","class","aria-label"].indexOf(ae.name)!==-1)&&(G==null||!G.includes(ae.name))&&!N&&Ui(ae.value)&&(!X(Ie=ae.name)||Ie.substring(0,10)!=="_ngcontent"&&Ie.substring(0,7)!=="_nghost")){var Se=ae.value;ae.name==="class"&&(Se=ul(Se).join(" ")),Z["attr__"+ae.name]=No(1024,ae.name==="href"&&M?dn(Se):Se)}}));for(var oe=1,ye=1,$e=L;$e=Tm($e);)oe++,$e.tagName===L.tagName&&ye++;return Z.nth_child=oe,Z.nth_of_type=ye,Z})(E,s,o,a,u));var O=(function(L){if(!_a(L))return{};var N={};return ie(L.attributes,(function(V){if(V.name&&V.name.indexOf("data-ph-capture-attribute")===0){var G=V.name.replace("data-ph-capture-attribute-",""),M=V.value;G&&M&&Ui(M)&&(N[G]=M)}})),N})(E);fe(v,O)})),b)return{props:{},explicitNoCapture:b};if(o||(m[0].$el_text=Qe(t,"a")||Qe(t,"button")?jc(t):Ji(t)),S){var _,x;m[0].attr__href=S;var I=(_=rs(S))==null?void 0:_.host,T=w==null||(x=w.location)==null?void 0:x.host;I&&T&&I!==T&&(p=S)}return{props:fe({$event_type:r.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(E){return E.map((P=>{var $,O,L="";if(P.tag_name&&(L+=P.tag_name),P.attr_class)for(var N of(P.attr_class.sort(),P.attr_class))L+="."+N.replace(/"/g,"");var V=k({},P.text?{text:P.text}:{},{"nth-child":($=P.nth_child)!==null&&$!==void 0?$:0,"nth-of-type":(O=P.nth_of_type)!==null&&O!==void 0?O:0},P.href?{href:P.href}:{},P.attr_id?{attr_id:P.attr_id}:{},P.attributes),G={};return Tr(V).sort(((M,R)=>M[0].localeCompare(R[0]))).forEach((M=>{var R=M[1];return G[Uc(M[0].toString())]=Uc(R.toString())})),(L+=":")+Tr(G).map((M=>M[0]+'="'+M[1]+'"')).join("")})).join(";")})((function(E){return E.map((P=>{var $,O,L={text:($=P.$el_text)==null?void 0:$.slice(0,400),tag_name:P.tag_name,href:(O=P.attr__href)==null?void 0:O.slice(0,2048),attr_class:Vg(P),attr_id:P.attr__id,nth_child:P.nth_child,nth_of_type:P.nth_of_type,attributes:{}};return Tr(P).filter((N=>N[0].indexOf("attr__")===0)).forEach((N=>L.attributes[N[0]]=N[1])),L}))})(g)))},(n=m[0])!=null&&n.$el_text?{$el_text:(i=m[0])==null?void 0:i.$el_text}:{},p&&r.type==="click"?{$external_click_url:p}:{},v)}}var Ii=pe("[ExceptionAutocapture]"),ou=()=>{},Mm=pe("[TracingHeaders]"),yn=pe("[Web Vitals]"),au=9e5,lu="disabled",cu="lazy_loading",ki="awaiting_config",Er="missing_config";pe("[SessionRecording]"),pe("[SessionRecording]");var ka="[SessionRecording]",Ot=pe(ka),Lm=pe("[Heatmaps]");function Oo(t){return he(t)&&"clientX"in t&&"clientY"in t&&ke(t.clientX)&&ke(t.clientY)}var Sr=pe("[Product Tours]"),Bo=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(ol))},Nm=["$set_once","$set"],bt=pe("[SiteApps]"),uu="Error while initializing PostHog app with config id ";function qn(t,e,n){if(H(t))return!1;switch(n){case"exact":return t===e;case"contains":var i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(i,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}class Om{constructor(e){this.ns=new gl,this.ss=(n,i)=>this.os(n,i)&&this.ls(n,i)&&this.us(n,i)&&this.hs(n,i),this.os=(n,i)=>i==null||!i.event||n?.event===i?.event,this._instance=e,this.ds=new Set,this.vs=new Set}init(){var e,n;C((e=this._instance)==null?void 0:e._addCaptureHook)||(n=this._instance)==null||n._addCaptureHook(((i,r)=>{this.on(i,r)}))}register(e){var n,i;if(!C((n=this._instance)==null?void 0:n._addCaptureHook)&&(e.forEach((o=>{var a,l;(a=this.vs)==null||a.add(o),(l=o.steps)==null||l.forEach((u=>{var c;(c=this.ds)==null||c.add(u?.event||"")}))})),(i=this._instance)!=null&&i.autocapture)){var r,s=new Set;e.forEach((o=>{var a;(a=o.steps)==null||a.forEach((l=>{l!=null&&l.selector&&s.add(l?.selector)}))})),(r=this._instance)==null||r.autocapture.setElementSelectors(s)}}on(e,n){var i;n!=null&&e.length!=0&&(this.ds.has(e)||this.ds.has(n.event))&&this.vs&&((i=this.vs)==null?void 0:i.size)>0&&this.vs.forEach((r=>{this.cs(n,r)&&this.ns.emit("actionCaptured",r.name)}))}fs(e){this.onAction("actionCaptured",(n=>e(n)))}cs(e,n){if(n?.steps==null)return!1;for(var i of n.steps)if(this.ss(e,i))return!0;return!1}onAction(e,n){return this.ns.on(e,n)}ls(e,n){if(n!=null&&n.url){var i,r=e==null||(i=e.properties)==null?void 0:i.$current_url;if(!r||typeof r!="string"||!qn(r,n.url,n.url_matching||"contains"))return!1}return!0}us(e,n){return!!this.ps(e,n)&&!!this.gs(e,n)&&!!this.ys(e,n)}ps(e,n){var i;if(n==null||!n.href)return!0;var r=this.bs(e);if(r.length>0)return r.some((a=>qn(a.href,n.href,n.href_matching||"exact")));var s,o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!o&&qn((s=o.match(/(?::|")href="(.*?)"/))?s[1]:"",n.href,n.href_matching||"exact")}gs(e,n){var i;if(n==null||!n.text)return!0;var r=this.bs(e);if(r.length>0)return r.some((u=>qn(u.text,n.text,n.text_matching||"exact")||qn(u.$el_text,n.text,n.text_matching||"exact")));var s,o,a,l=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!l&&(s=(function(u){for(var c,d=[],f=/(?::|")text="(.*?)"/g;!H(c=f.exec(u));)d.includes(c[1])||d.push(c[1]);return d})(l),o=n.text,a=n.text_matching||"exact",s.some((u=>qn(u,o,a))))}ys(e,n){var i,r;if(n==null||!n.selector)return!0;var s=e==null||(i=e.properties)==null?void 0:i.$element_selectors;if(s!=null&&s.includes(n.selector))return!0;var o=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";if(n.selector_regex&&o)try{return new RegExp(n.selector_regex).test(o)}catch{return!1}return!1}bs(e){var n;return(e==null||(n=e.properties)==null?void 0:n.$elements)==null?[]:e?.properties.$elements}hs(e,n){return n==null||!n.properties||n.properties.length===0||Uf(n.properties.reduce(((i,r)=>{var s=U(r.value)?r.value.map(String):r.value!=null?[String(r.value)]:[];return i[r.key]={values:s,operator:r.operator||"exact"},i}),{}),e?.properties)}}class Bm{constructor(e){var n;this._s=[],this._instance=e,this.ws=new Map,this.ks=new Map,this.xs=new Map,(n=this._instance)==null||n.onSessionId==null||n.onSessionId((i=>this.Ss(i)))}Cs(e){return!1}Ms(){return null}Ts(e){}Es(){}Is(e,n){return!!e&&Uf(e.propertyFilters,n?.properties)}Ps(e,n){var i=new Map;return e.forEach((r=>{var s;(s=r.conditions)==null||(s=s[n])==null||(s=s.values)==null||s.forEach((o=>{if(o!=null&&o.name){var a=i.get(o.name)||[];a.push(r.id),i.set(o.name,a)}}))})),i}Rs(e,n,i){var r=(i===wi.Activation?this.ws:this.ks).get(e),s=[];return this.As((o=>{s=o.filter((a=>r?.includes(a.id)))})),s.filter((o=>{var a,l=(a=o.conditions)==null||(a=a[i])==null||(a=a.values)==null?void 0:a.find((u=>u.name===e));return this.Is(l,n)}))}register(e){var n;C((n=this._instance)==null?void 0:n._addCaptureHook)||(this.Fs(e),this.Ls(e))}Ls(e){var n=e.filter((i=>{var r,s;return((r=i.conditions)==null?void 0:r.actions)&&((s=i.conditions)==null||(s=s.actions)==null||(s=s.values)==null?void 0:s.length)>0}));n.length!==0&&(this.Os==null&&(this.Os=new Om(this._instance),this.Os.init(),this.Os.fs((i=>{this.onAction(i)}))),n.forEach((i=>{var r,s,o,a,l;i.conditions&&(r=i.conditions)!=null&&r.actions&&(s=i.conditions)!=null&&(s=s.actions)!=null&&s.values&&((o=i.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.Os)==null||a.register(i.conditions.actions.values),(l=i.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var c=this.xs.get(u.name);c&&c.push(i.id),this.xs.set(u.name,c||[i.id])}})))})))}Fs(e){var n,i=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.events)&&((a=s.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0})),r=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.cancelEvents)&&((a=s.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0}));i.length===0&&r.length===0||((n=this._instance)==null||n._addCaptureHook(((s,o)=>{this.onEvent(s,o)})),this.ws=this.Ps(e,wi.Activation),this.ks=this.Ps(e,wi.Cancellation))}onEvent(e,n){var i,r,s=this.Ds(),o=(n==null||(i=n.properties)==null?void 0:i.$survey_id)||(n==null||(r=n.properties)==null?void 0:r.$product_tour_id);if(o&&this.getActivatedIds().includes(o)){var a=this.$s(e,o);if(a==="consume")return s.info("event consumed activated item, removing it",{event:e,itemId:o}),void this.Ns([o]);if(a==="persist")return s.info("shown item promoted to persisted activation",{event:e,itemId:o}),this.qs(o),void this.js([o])}if(this.ks.has(e)){var l=this.Rs(e,n,wi.Cancellation);l.length>0&&(s.info("cancel event matched, cancelling items",{event:e,itemsToCancel:l.map((c=>c.id))}),this.Ns(l.map((c=>c.id))),l.forEach((c=>this.Bs(c.id))))}if(this.ws.has(e)){s.info("event name matched",{event:e,eventPayload:n,items:this.ws.get(e)});var u=this.Rs(e,n,wi.Activation);this.Hs(u.map((c=>c.id)))}}onAction(e){this.xs.has(e)&&this.Hs(this.xs.get(e)||[])}Hs(e){var n;if(e.length!==0){var i=!((n=this._instance)==null||n.get_session_id==null||!n.get_session_id()),r=[];for(var s of e)i&&this.Cs(s)?this.qs(s)&&this.Us(s):r.push(s);r.length>0&&(this._s=[...new Set([...this._s,...r])]),this.Ds().info("updating activated items",{activatedItems:this.getActivatedIds()})}}qs(e){this._s=this._s.filter((i=>i!==e));var n=this.zs();return!n.includes(e)&&(this.Ws([...n,e]),this.Vs(),!0)}Ns(e){var n=new Set(e);this._s=this._s.filter((s=>!n.has(s)));var i=this.Zs(),r=i.filter((s=>!n.has(s)));r.length!==i.length&&(this.Ws(r),r.length===0&&this.Gs()),this.js(e)}Qs(){var e,n=this.Ms();if(!n)return{};var i=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n];return i&&typeof i=="object"?i:{}}Us(e){if(this.Ms()){var n=this.Qs();this.Ts(k({},n,{[e]:Date.now()}))}}js(e){if(this.Ms()){var n=this.Qs(),i={},r=!1;for(var s of Object.entries(n)){var o=s[0],a=s[1];e.includes(o)?r=!0:i[o]=a}r&&(Vt(i)?this.Es():this.Ts(i))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var n=this.Qs()[e];return ke(n)?n:void 0}}Zs(){var e,n=this.Js();return((e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n])||[]}zs(){var e,n,i=this.Zs();if(i.length===0)return[];var r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[this.Ys()],s=(n=this._instance)==null||n.get_session_id==null?void 0:n.get_session_id();return s&&r===s?i:[]}Vs(){var e,n=(e=this._instance)==null||e.get_session_id==null?void 0:e.get_session_id();n&&this.Xs(n)}Gs(){this.ta()}Ss(e){var n,i=(n=this._instance)==null||(n=n.persistence)==null?void 0:n.props[this.Ys()];if(i&&i!==e){var r=this.Zs(),s=this.Qs();r.length>0&&(this.Ws([]),r.filter((o=>ke(s[o]))).forEach((o=>this.Bs(o)))),this.Gs(),this.Ks()}}getActivatedIds(){return[...new Set([...this.zs(),...this._s])].filter((e=>!this.ea(e)))}reset(){this._s=[],this.Zs().length>0&&this.Ws([]),this.Gs(),this.Ks()}getEventToItemsMap(){return this.ws}ia(){return this.Os}}class Dm extends Bm{constructor(e){super(e)}Js(){return ua}Ys(){return Pr}Ms(){return Fr}Ts(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Fr]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Fr)}Cs(e){var n,i;this.As((s=>{i=s.find((o=>o.id===e))}));var r=(n=i)==null||(n=n.appearance)==null?void 0:n.surveyPopupDelaySeconds;return ke(r)&&r>0}ra(){return qt.SHOWN}As(e){var n;(n=this._instance)==null||n.getSurveys(e)}Bs(e){var n;(n=this._instance)==null||n.cancelPendingSurvey(e)}Ds(){return Q}Ws(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[ua]:e})}Xs(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Pr]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Pr)}ea(){return!1}$s(e,n){var i;this.As((s=>{i=s.find((o=>o.id===n))}));var r=!i||(function(s){var o;return Hf(s)&&!((o=s.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||s.schedule==="always"})(i);return r?e===qt.SHOWN?"consume":"ignore":e===qt.SHOWN?"persist":e===qt.DISMISSED||e===qt.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var xr="SDK is not enabled or survey functionality is not yet loaded",du="Disabled. Not loading surveys.",jm=w!=null&&w.location?ss(w.location.hash,"__posthog")||ss(location.hash,"state"):null,fu="_postHogToolbarParams",hu=pe("[Toolbar]"),pu=pe("[FeatureFlags]");class Um{constructor(e,n){n===void 0&&(n=!1),this.na=!1,this.update(e,n)}update(e,n){this.sa=((i,r)=>{var s,o,a,l;return{bootstrap:{featureFlags:(s=i.bootstrap)==null?void 0:s.featureFlags,featureFlagPayloads:(o=i.bootstrap)==null?void 0:o.featureFlagPayloads},remoteRequestsDisabled:r,featureFlagsDisabled:!!i.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!i.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!i.advanced_feature_flags_dedup_per_session,cacheTtlMs:i.feature_flag_cache_ttl_ms,requestTimeoutMs:i.feature_flag_request_timeout_ms,compression:i.disable_compression?"none":"base64",evaluationContexts:(a=(l=i.evaluation_contexts)!==null&&l!==void 0?l:i.evaluation_environments)!==null&&a!==void 0?a:[],flagKeys:U(i.flag_keys)?i.flag_keys:void 0}})(e,n),!e.evaluation_environments||e.evaluation_contexts||this.na||(pu.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.na=!0),C(e.flag_keys)||U(e.flag_keys)||pu.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var gu=pe("[FeatureFlags]"),wn=pe("[FeatureFlags]",{debugEnabled:!0}),Do=`" failed. Feature flags didn't load in time.`,mu="connection_error",vu=t=>{for(var e={},n=0;t.length>n;n++)e[t[n]]=!0;return e},_u=t=>{var e={};for(var n of Tr(t||{})){var i=n[1];i&&(e[n[0]]=i)}return e},Et=pe("[Error tracking]"),yu="Refusing to render web experiment since the viewer is a likely bot",Hm={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>ls(e,t),not_regex:(t,e)=>!ls(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class Me{get Ne(){return this._instance.config}constructor(e){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(i){i===void 0&&(i=!1),n.getWebExperiments((r=>{Me.aa("retrieved web experiments from the server"),n.oa=new Map,r.forEach((s=>{if(s.feature_flag_key){var o;n.oa&&(Me.aa("setting flag key ",s.feature_flag_key," to web experiment ",s),(o=n.oa)==null||o.set(s.feature_flag_key,s));var a=n._instance.getFeatureFlag(s.feature_flag_key);X(a)&&s.variants[a]&&n.la(s.name,a,s.variants[a].transforms)}else if(s.variants)for(var l in s.variants){var u=s.variants[l];Me.ua(u,n._instance)&&n.la(s.name,l,u.transforms)}}))}),i)},this._instance=e,this._instance.onFeatureFlags((i=>{this.onFeatureFlags(i)}))}initialize(){}onFeatureFlags(e){if(this._is_bot())Me.aa(yu);else if(!this.Ne.disable_web_experiments){if(H(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();Me.aa("applying feature flags",e),e.forEach((n=>{var i;if(this.oa&&(i=this.oa)!=null&&i.has(n)){var r,s=this._instance.getFeatureFlag(n),o=(r=this.oa)==null?void 0:r.get(n);s&&o!=null&&o.variants[s]&&this.la(o.name,s,o.variants[s].transforms)}}))}}previewWebExperiment(){var e=Me.getWindowLocation();if(e!=null&&e.search){var n=ii(e?.search,"__experiment_id"),i=ii(e?.search,"__experiment_variant");n&&i&&(Me.aa("previewing web experiments "+n+" && "+i),this.getWebExperiments((r=>{this.ha(parseInt(n),i,r)}),!1,!0))}}loadIfEnabled(){this.Ne.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,n,i){if(this.Ne.disable_web_experiments&&!i)return e([]);var r=this._instance.get_property("$web_experiments");if(r&&!n)return e(r);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this.Ne.token),method:"GET",timestampMode:"query",callback:s=>e(s.statusCode===200&&s.json&&s.json.experiments||[])})}ha(e,n,i){var r=i.filter((s=>s.id===e));r&&r.length>0&&(Me.aa("Previewing web experiment ["+r[0].name+"] with variant ["+n+"]"),this.la(r[0].name,n,r[0].variants[n].transforms))}static ua(e,n){return!H(e.conditions)&&Me.da(e,n)&&Me.va(e)}static da(e,n){var i;if(H(e.conditions)||H((i=e.conditions)==null?void 0:i.url))return!0;var r=Me.getWindowLocation();if(r){var s,o,a,l=rf(n,r.href);return(s=e.conditions)==null||!s.url||Hm[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return w?.location}static va(e){var n;if(H(e.conditions)||H((n=e.conditions)==null?void 0:n.utm))return!0;var i=yf();if(i.utm_source){var r,s,o,a,l,u,c,d,f=(r=e.conditions)==null||(r=r.utm)==null||!r.utm_campaign||((s=e.conditions)==null||(s=s.utm)==null?void 0:s.utm_campaign)==i.utm_campaign,h=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==i.utm_source,p=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==i.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==i.utm_term;return f&&p&&g&&h}return!1}static aa(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;n>r;r++)i[r-1]=arguments[r];A.info("[WebExperiments] "+e,i)}la(e,n,i){this._is_bot()?Me.aa(yu):n!=="control"?i.forEach((r=>{if(r.selector){var s;Me.aa("applying transform of variant "+n+" for experiment "+e+" ",r);var o=(s=document)==null?void 0:s.querySelectorAll(r.selector);o?.forEach((a=>{var l=a;r.html&&(l.innerHTML=r.html),r.css&&l.setAttribute("style",r.css)}))}})):Me.aa("Control variants leave the page unmodified.")}_is_bot(){return Ue&&this._instance?Bf(Ue,this.Ne.custom_blocked_useragents):void 0}}var st=pe("[Conversations]"),bn="Conversations not available yet.",wu="console",Vf="__posthogHandledLogsRequestError",jo=(t,e)=>{var n=t instanceof Error?t:new Error(e);return n[Vf]=!0,n},bu=t=>!!t&&typeof t=="object"&&t[Vf]===!0,Cs={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=gu,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 Um(t.config,t.Qi()),this.Ta=this.Ea)}updateConfig(t,e){var n;(n=this.Ea)==null||n.update(t,e)}setup(t){return this.Ia=t,this.rt=t.logger.createLogger("[FeatureFlags]"),n=()=>{this.Ia===t&&(this.Ia=void 0,this.nn=t,this.Pa(t))},(e=t.kv.initialize())!=null&&e.then?e.then(n):n();var e,n}Pa(t){if(this.nn===t)return w&&ve(w,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){w?.removeEventListener("online",this.Ca)}dispose(){var t;this.ba++,this.wa=!1,this.Ia=void 0,this.nn&&(this.La(),(t=this.Ra)==null||t.dispose(),this.Ra=void 0,this.ga=[],w?.removeEventListener("online",this.Ca),this.nn=void 0)}get Ne(){return this.Ta.get()}Oa(t){var e;return(e=this.nn)==null?void 0:e.kv.get(t)}F(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.set(t)}))}q(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.remove(t)}))}Da(t){try{t()}catch(e){this.rt.error("Failed to update feature flag persistence",e)}}Fa(){var t={};for(var e of[Ti,$i,Ar,xt]){var n=this.Oa(e);C(n)||(t[e]=n)}this.fa=t;var i=k({},t),r=this.Oa(En);if(r)for(var s of Object.entries(r))i["$feature/"+s[0]]=s[1];this.pa=i}Aa(){var t=this.Ne.cacheTtlMs;if(!t||0>=t)return!1;var e=this.Oa(ji);return typeof e!="number"||Date.now()-e>t}$a(){return!!this.Aa()&&(this.xa||this.ya||(this.xa=!0,this.rt.warn("Feature flag cache is stale, triggering refresh..."),this.reloadFeatureFlags()),!0)}Na(){var t=this.Ne.evaluationContexts;return t!=null&&t.length?t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid evaluation context found:",e,"Expected non-empty string"),n})):[]}qa(){var t=this.Ne.flagKeys;if(!C(t))return t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid flag key found:",e,"Expected non-empty string"),n}))}initialize(){var t,e,n=this.Ne,i=(t=(e=n.bootstrap)==null?void 0:e.featureFlags)!==null&&t!==void 0?t:{};if(Object.keys(i).length){var r,s,o=(r=(s=n.bootstrap)==null?void 0:s.featureFlagPayloads)!==null&&r!==void 0?r:{},a=Object.keys(i).filter((u=>!!i[u])).reduce(((u,c)=>(u[c]=i[c]||!1,u)),{}),l=Object.keys(o).filter((u=>a[u])).reduce(((u,c)=>(o[c]&&(u[c]=o[c]),u)),{});return this.ja({featureFlags:a,featureFlagPayloads:l})}}updateFlags(t,e,n){var i,r,s=n!=null&&n.merge&&(i=this.Oa(En))!==null&&i!==void 0?i:{},o=n!=null&&n.merge&&(r=this.Oa($i))!==null&&r!==void 0?r:{},a=k({},s,t),l=k({},o,e),u={};for(var c of Object.entries(a)){var d=c[0],f=c[1];u[d]={key:d,enabled:hc(f),variant:pc(f),reason:void 0,metadata:C(l?.[d])?void 0:{id:0,version:void 0,description:void 0,payload:l[d]}}}this.ja({flags:u})}get hasLoadedFlags(){return this.ma}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var t=this.Oa(la),e=this.Oa(xt),n=this.Oa(Sn);if(!n&&!e)return t||{};var i=fe({},t||{}),r=[...new Set([...Object.keys(n||{}),...Object.keys(e||{})])];for(var s of r){var o,a,l=i[s],u=e?.[s],c=C(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=C(u)?l?.variant:typeof u=="string"?u:void 0,f=n?.[s],h=k({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(h.original_enabled=l?.enabled),d!==l?.variant&&(h.original_variant=l?.variant),f&&(h.metadata=k({},l?.metadata,{payload:f,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),i[s]=h}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:n,finalDetails:i}),this.ca=!0),i}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((n=>{var i=t[n];return{key:n,enabled:hc(i),variant:pc(i),payload:fc(e[n])}}))}getFlagVariants(){var t=this.Oa(En),e=this.Oa(xt);if(!e)return t||{};for(var n=fe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:e,finalFlags:n}),this.ca=!0),n}getFlagPayloads(){var t=this.Oa($i),e=this.Oa(Sn);if(!e)return t||{};for(var n=fe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flag payloads!",{flagPayloads:t,overriddenPayloads:e,finalPayloads:n}),this.ca=!0),n}reloadFeatureFlags(){this._a||this.Ne.featureFlagsDisabled||this.Ma()||this.Ba||(this.ga.slice().forEach((t=>{try{t()}catch(e){this.rt.error("Error while running feature flags reloading callback",e)}})),this.Ba=setTimeout((()=>{this.Ha()}),5))}La(){clearTimeout(this.Ba),this.Ba=void 0}onReloading(t){return this.ga.push(t),()=>{this.ga=this.ga.filter((e=>e!==t))}}ensureFlagsLoaded(){this.ma||this.ya||this.Ba||this.reloadFeatureFlags()}setAnonymousDistinctId(t){this.$anon_distinct_id=t}setReloadingPaused(t){this._a=t}resetFlagCallReported(){this.q(kn)}Ha(t){this.La();var e=this.nn;if(e&&!this.Ne.remoteRequestsDisabled&&!this.Ma())if(this.ya)this.wa=!0;else{var n={token:e.projectToken,distinct_id:e.distinctId,groups:e.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:k({},e.initialPersonProperties,this.Oa(Dt)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(xn),timezone:If()};C(e.deviceId)||(n.$device_id=e.deviceId),(t!=null&&t.disableFlags||this.Ne.featureFlagsDisabled)&&(n.disable_flags=!0);var i=this.Na();i.length&&(n.evaluation_contexts=i);var r=this.qa();C(r)||(n.flag_keys=r);var s=this.Ne.onlyEvaluateSurveyFeatureFlags,o="/flags/?v=2"+(s?"&only_evaluate_survey_feature_flags=true":""),a=this.ba;this.ya=!0;var l=()=>{this.wa&&(this.wa=!1,this.Ha())},u=c=>{this.ya=!1,a===this.ba&&(this.F({[Rr]:[mu]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:n,compression:this.Ne.compression==="base64"?je.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,f,h=(d=c.json)!==null&&d!==void 0?d:{},p=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),p||this.wa||(this.$anon_distinct_id=void 0),!n.disable_flags||this.wa){this.ka=!p;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?mu:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),h.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((f=h.quotaLimited)==null||!f.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[Rr]:g}),m?this.rt.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more."):n.disable_flags||this.ja(h,p,{partialResponse:s}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return vf(this.Sa,3)}Ua(t){this.Sa=_f(t,this.Sa,3,(()=>this.rt.warn("Feature flag requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped refreshing feature flags; will try again when connectivity changes.")))}getFeatureFlag(t,e){var n;if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var i=this.getFeatureFlagResult(t,e);return(n=i?.variant)!==null&&n!==void 0?n:i?.enabled}}else this.rt.warn('getFeatureFlag for key "'+t+Do)}getFeatureFlagDetails(t){return this.getFlagsWithDetails()[t]}getFeatureFlagPayload(t){var e=this.getFeatureFlagResult(t,{send_event:!1});return e?.payload}getFeatureFlagResult(t,e){if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var n,i=this.getFlagVariants(),r=t in i,s=i[t],o=this.getFlagPayloads()[t],a=String(s),l=this.Oa(Ar)||void 0,u=this.Oa(ji)||void 0,c=this.Oa(kn)||{};if(this.Ne.deduplicateCallsPerSession){var d,f=(d=this.nn)==null?void 0:d.session.sessionId,h=this.Oa(Li);f&&f!==h&&(c={},n=f)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))n&&this.F({[kn]:c,[Li]:n});else{var p,g,m,v,S,b,_,x,I,T;U(c[t])?c[t].push(a):c[t]=[a],this.F(k({[kn]:c},n?{[Li]:n}:{}));var E=this.getFeatureFlagDetails(t),P=[...(p=this.Oa(Rr))!==null&&p!==void 0?p:[]];C(s)&&P.push("flag_missing");var $={$feature_flag:t,$feature_flag_response:s,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((g=this.Ne.bootstrap)==null||(g=g.featureFlags)==null?void 0:g[t])||null,$feature_flag_bootstrapped_payload:((m=this.Ne.bootstrap)==null||(m=m.featureFlagPayloads)==null?void 0:m[t])||null,$used_bootstrap_value:!this.ka};C(E==null||(v=E.metadata)==null?void 0:v.has_experiment)||($.$feature_flag_has_experiment=E.metadata.has_experiment),C(E==null||(S=E.metadata)==null?void 0:S.version)||($.$feature_flag_version=E.metadata.version);var O,L=(b=E==null||(_=E.reason)==null?void 0:_.description)!==null&&b!==void 0?b:E==null||(x=E.reason)==null?void 0:x.code;L&&($.$feature_flag_reason=L),E!=null&&(I=E.metadata)!=null&&I.id&&($.$feature_flag_id=E.metadata.id),C(E?.original_variant)&&C(E?.original_enabled)||($.$feature_flag_original_response=C(E.original_variant)?E.original_enabled:E.original_variant),E!=null&&(T=E.metadata)!=null&&T.original_payload&&($.$feature_flag_original_payload=E==null||(O=E.metadata)==null?void 0:O.original_payload),P.length&&($.$feature_flag_error=P.join(",")),this.za($)}else n&&this.F({[kn]:c,[Li]:n});if(r)return{key:t,enabled:!!s,variant:typeof s=="string"?s:void 0,payload:fc(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+Do)}za(t){try{var e;(e=this.nn)==null||e.capture("$feature_flag_called",t).catch((n=>{this.rt.error("Failed to capture feature flag call",n)}))}catch(n){this.rt.error("Failed to capture feature flag call",n)}}getRemoteConfigPayload(t,e){this.Wa(t,e)}Wa(t,e){var n=this;return se((function*(){var i=n.nn;if(i){var r={distinct_id:i.distinctId,token:i.projectToken,person_properties:{$lib:i.library.name,$lib_version:i.library.version}},s=n.Na();s.length&&(r.evaluation_contexts=s);var o,a=n.qa();C(a)||(r.flag_keys=a);try{var l,u=(l=(yield i.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:r,compression:n.Ne.compression==="base64"?je.Base64:void 0,sentAt:"body",timeoutMs:n.Ne.requestTimeoutMs})).json)==null?void 0:l.featureFlagPayloads;o=u?.[t]||void 0}catch(c){return void n.rt.error("Remote config feature flag request failed",c)}try{e(o)}catch(c){n.rt.error("Remote config feature flag callback failed",c)}}}))()}isFeatureEnabled(t,e){if(e===void 0&&(e={}),e.fresh&&!this.ka)return e.defaultValue;if(!(this.ma||this.getFlags()&&this.getFlags().length>0))return this.rt.warn('isFeatureEnabled for key "'+t+Do),e.defaultValue;var n=this.getFeatureFlag(t,e);return C(n)?e.defaultValue:!!n}addFeatureFlagsHandler(t){this.featureFlagEventHandlers.push(t)}removeFeatureFlagsHandler(t){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((e=>e!==t))}receivedFeatureFlags(t,e,n){this.ja(t,e,n)}ja(t,e,n){if(this.nn){this.ma=!0;var i=(function(r,s,o,a,l,u){s===void 0&&(s={}),o===void 0&&(o={}),a===void 0&&(a={}),u===void 0&&(u=gu);var c=((I,T)=>{var E=I.flags;return E?k({},I,{featureFlags:Object.fromEntries(Object.keys(E).map((P=>{var $;return[P,($=E[P].variant)!==null&&$!==void 0?$:E[P].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(E).filter((P=>E[P].enabled)).filter((P=>{var $;return($=E[P].metadata)==null?void 0:$.payload})).map((P=>{var $;return[P,($=E[P].metadata)==null?void 0:$.payload]})))}):(I.featureFlags&&T.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),I)})(r,u),d=c.flags,f=c.featureFlags,h=c.featureFlagPayloads;if(f){var p=r.requestId,g=r.evaluatedAt;if(U(f)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(f)for(var v=0;f.length>v;v++)m[f[v]]=!0;return{[Ti]:f,[En]:m,[Jr]:!1}}var S=f,b=h,_=d;if(l!=null&&l.partialResponse)S=k({},s,S),b=k({},o,b),_=k({},a,_);else if(r.errorsWhileComputingFlags)if(d){var x=new Set(Object.keys(d).filter((I=>{var T;return!((T=d[I])!=null&&T.failed)})));S=k({},s,Object.fromEntries(Object.entries(S).filter((I=>x.has(I[0]))))),b=k({},o,Object.fromEntries(Object.entries(b||{}).filter((I=>x.has(I[0]))))),_=k({},a,Object.fromEntries(Object.entries(_||{}).filter((I=>x.has(I[0])))))}else S=k({},s,S),b=k({},o,b),_=k({},a,_);return k({[Ti]:Object.keys(_u(S)),[En]:S||{},[$i]:b||{},[la]:_||{},[Jr]:r.minimalFlagCalledEvents===!0},p?{[Ar]:p}:{},g?{[ji]:g}:{})}})(t,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),n,this.rt);i&&this.F(i),e||(this.xa=!1),this.Va(e)}}override(t,e){e===void 0&&(e=!1),this.rt.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:t,suppressWarning:e})}overrideFeatureFlags(t){this.Za(t)}Za(t){if(this.nn){if(t===!1)return this.q([xt,Sn]),this.Va(),void wn.info("All overrides cleared");if(U(t))return this.F({[xt]:vu(t)}),this.Va(),void wn.info("Flag overrides set",{flags:t});if(t&&typeof t=="object"&&("flags"in t||"payloads"in t)){var e,n=t;this.ca=!!((e=n.suppressWarning)!==null&&e!==void 0&&e);var i={},r=n.flags,s=n.payloads;return r&&(i[xt]=U(r)?vu(r):r),s&&(i[Sn]=s),Object.keys(i).length&&this.F(i),r===!1&&s===!1?this.q([xt,Sn]):r===!1?this.q(xt):s===!1&&this.q(Sn),this.Va(),r===!1?wn.info("Flag overrides cleared"):r&&wn.info("Flag overrides set",{flags:r}),void(s===!1?wn.info("Payload overrides cleared"):s&&wn.info("Payload overrides set",{payloads:s}))}if(t&&typeof t=="object")return this.F({[xt]:t}),this.Va(),void wn.info("Flag overrides set",{flags:t});this.rt.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:t})}else this.rt.warn("posthog.featureFlags.overrideFeatureFlags called before feature flags were ready")}onFeatureFlags(t){if(this.addFeatureFlagsHandler(t),this.ma){var e=this.Ga(),n=e.flags,i=e.flagVariants;try{t(n,i)}catch(r){this.rt.error("Error while running feature flags callback",r)}}return()=>this.removeFeatureFlagsHandler(t)}updateEarlyAccessFeatureEnrollment(t,e,n){var i=(this.Oa(Cr)||[]).find((l=>l.flagKey===t)),r={["$feature_enrollment/"+t]:e},s={$feature_flag:t,$feature_enrollment:e,$set:r};i&&(s.$early_access_feature_name=i.name),n&&(s.$feature_enrollment_stage=n);var o=k({},this.getFlagVariants(),{[t]:e});this.F({[Ti]:Object.keys(_u(o)),[En]:o,[Dt]:k({},this.Oa(Dt)||{},r)}),this.Va();try{var a;(a=this.nn)==null||a.capture("$feature_enrollment_update",s).catch((l=>{this.rt.error("Failed to capture early access feature enrollment",l)}))}catch(l){this.rt.error("Failed to capture early access feature enrollment",l)}}getEarlyAccessFeatures(t,e,n){e===void 0&&(e=!1);var i=this.Oa(Cr);!i||e?this.Qa(t,n):t(i)}Qa(t,e){var n=this;return se((function*(){var i=n.nn;if(i){var r,s=e?"&"+e.map((a=>"stage="+a)).join("&"):"";try{var o=yield i.sendRequest("/api/early_access_features/?token="+i.projectToken+s,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;n.F({[Cr]:r=o.json.earlyAccessFeatures})}catch(a){return void n.rt.error("Early access feature request failed",a)}try{t(r)}catch(a){n.rt.error("Early access feature callback failed",a)}}}))()}Ga(){var t=this.getFlags(),e=this.getFlagVariants();return{flags:t.filter((n=>e[n])),flagVariants:Object.keys(e).filter((n=>e[n])).reduce(((n,i)=>(n[i]=e[i],n)),{})}}Va(t){this.Fa();var e=this.Ga(),n=e.flags,i=e.flagVariants;this.featureFlagEventHandlers.forEach((r=>{try{r(n,i,{errorsLoading:t})}catch(s){this.rt.error("Error while running feature flags callback",s)}}))}setPersonPropertiesForFlags(t,e){e===void 0&&(e=!0),this.Ka(t,e)}Ka(t,e){e===void 0&&(e=!0);var n=this.Oa(Dt)||{},i=t?.$set||(t!=null&&t.$set_once?{}:t),r=t?.$set_once,s={};if(r)for(var o in r)({}).hasOwnProperty.call(r,o)&&(o in n||(s[o]=r[o]));this.F({[Dt]:k({},n,s,i)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=k({},this.Oa(Dt)||{});t.forEach((i=>{delete n[i]})),this.F({[Dt]:n}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(Dt),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=this.Oa(xn)||{},i=k({},n);for(var r of Object.keys(t))i[r]=k({},n[r],t[r]);this.F({[xn]:i}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(xn)||{};this.F({[xn]:k({},e,{[t]:{}})})}else this.q(xn)}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}}},Wm={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===ki||this.Ya===Er?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=lu,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(F==null||!F.visibilityState||F.visibilityState==="visible")return!0;var n=w==null||(e=w.performance)==null||e.getEntriesByType==null?void 0:e.getEntriesByType("visibility-state");return!(n!=null&&n.length)||n.some((i=>i.name==="visible"))})(),this.Ie=()=>{var e;F?.visibilityState==="visible"&&(this.io=!0,(e=this.Ja)==null||e.setDocumentWasEverVisible==null||e.setDocumentWasEverVisible(!0))},this._instance=t,!this._instance.sessionManager)throw Ot.error("started without valid sessionManager"),new Error(ka+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===Ht)throw new Error(ka+' cannot be used with cookieless_mode="always"');F!=null&&F.addEventListener&&ve(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(An))==null||!t.enabled),n=!this.Ne.disable_session_recording,i=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return w&&e&&n&&!i}startIfEnabledOrStop(t){var e;if(!(this.eo||this.ro&&(e=this.Ja)!=null&&e.isStarted)){var n=!C(Object.assign)&&!C(Array.from);this.ro&&n?(this.no(t),Ot.info("starting")):(this.Ya=lu,this.stopRecording())}}no(t){var e,n,i;this.ro&&(this.Ya!==ki&&this.Ya!==Er&&(this.Ya=cu),B!=null&&(e=B.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(n=B.__PosthogExtensions__)!=null&&n.initSessionRecording?this.so(t):(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,this.ao,(r=>{if(r)return Ot.error("could not load recorder",r);this.so(t)})))}stopRecording(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.stop()}oo(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.discard()}lo(){var t,e;(t=this.Mr)==null||t.unregister(al),(e=this.Mr)==null||e.unregister(Gd)}uo(t,e){if(H(t))return null;var n,i=ke(t)?t:parseFloat(t);return typeof(n=i)!="number"||!Number.isFinite(n)||0>n||n>1?(Ot.warn(e+" must be between 0 and 1. Ignoring invalid value:",t),null):i}ho(t){if(this.Mr){var e,n,i=this.Mr,r=()=>{var s,o=t.sessionRecording===!1?void 0:t.sessionRecording,a=this.uo((s=this.Ne.session_recording)==null?void 0:s.sampleRate,"session_recording.sampleRate"),l=this.uo(o?.sampleRate,"remote config sampleRate"),u=a??l;H(u)&&this.lo();var c=o?.minimumDurationMilliseconds;i.register({[An]:k({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:k({capturePerformance:t.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:u,minimumDurationMilliseconds:C(c)?null:c,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers,version:o?.version,triggerGroups:o?.triggerGroups})})};r(),(e=this.Xa)==null||e.call(this),this.Xa=(n=this._instance.sessionManager)==null?void 0:n.onSessionId(r)}}onRemoteConfig(t){var e=t.ok?t.config:void 0;return e&&"sessionRecording"in e?e.sessionRecording===!1?(this.ho(e),void this.oo()):(this.ho(e),void this.startIfEnabledOrStop()):(this.Ya===ki&&(this.Ya=Er,Ot.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(t,e){var n;e===void 0&&(e="log"),(n=this.Ja)!=null&&n.log?this.Ja.log(t,e):Ot.warn("log called before recorder was ready")}get ao(){var t,e,n=(t=this._instance)==null||(t=t.persistence)==null?void 0:t.get_property(An);return(n==null||(e=n.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(An);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(n){return Ot.warn("persisted remote config for session recording is invalid and will be ignored",n),!1}return!H(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,n,i;if(!this.eo){if((e=B.__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({[ef]:!0});var r;if(this.Ja||(this.Ja=(r=B.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===Er||this.Ya===ki?void 0:(this.Ya=ki,Ot.info("persisted remote config is stale, requesting fresh config before starting"),void new kf(this._instance).load());this.Ya=cu,(n=(i=this.Ja).setDocumentWasEverVisible)==null||n.call(i,this.io),this.Ja.start(t)}}onRRwebEmit(t){var e;(e=this.Ja)==null||e.onRRwebEmit==null||e.onRRwebEmit(t)}overrideLinkedFlag(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Kd]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Vd]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,n;this.Ja||(n=this.Mr)==null||n.register({[t==="url"?Yd:Jd]:!0}),(e=this.Ja)==null||e.overrideTrigger(t)}get sdkDebugProperties(){var t;return((t=this.Ja)==null?void 0:t.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(t,e){var n;return!((n=this.Ja)==null||!n.tryAddCustomEvent(t,e))}}},qm={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new su(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,n=he(this.instance.config.autocapture)?this.instance.config.autocapture:{};return n.url_allowlist=(t=n.url_allowlist)==null?void 0:t.map((i=>new RegExp(i))),n.url_ignorelist=(e=n.url_ignorelist)==null?void 0:e.map((i=>new RegExp(i))),n}yo(){if(this.isBrowserSupported()){if(w&&F){var t=n=>{n=n||w?.event;try{this.bo(n)}catch(i){Lo.error("Failed to capture event",i)}};if(ve(F,"submit",t,{capture:!0}),ve(F,"change",t,{capture:!0}),ve(F,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=n=>{n=n||w?.event;try{this.bo(n,Mo)}catch(i){Lo.error("Failed to capture copy/cut event",i)}};ve(F,"copy",e,{capture:!0}),ve(F,"cut",e,{capture:!0})}}}else Lo.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.vo&&(this.yo(),this.vo=!0)}onRemoteConfig(t){if(this.fo=!0,t.ok){var e=t.config;e.elementsChainAsString&&(this.po=e.elementsChainAsString);var n=e.autocapture_opt_out;gt(n)&&(this.instance.persistence&&this.instance.persistence.register({[ta]:n}),this.co=n),this.startIfEnabled()}else this.startIfEnabled()}setElementSelectors(t){this.mo=t}getElementSelectors(t){var e,n=[];return(e=this.mo)==null||e.forEach((i=>{var r=F?.querySelectorAll(i);r?.forEach((s=>{t===s&&n.push(i)}))})),n}get isEnabled(){var t,e,n=(t=this.instance.persistence)==null?void 0:t.props[ta],i=this.co,r=this.instance.Qi()&&!this.fo;if(Ke(i)&&!gt(n)&&!r)return!1;var s=(e=this.co)!==null&&e!==void 0?e:!!n;return!!this.instance.config.autocapture&&!s}bo(t,e){if(e===void 0&&(e="$autocapture"),this.isEnabled){var n,i=Eo(t);of(i)&&(i=i.parentNode||null),e==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&this.instance.config.rageclick&&(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,t.timeStamp||new Date().getTime())&&Lc(i,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var r=e===Mo;if(i&&(function(d,f,h,p,g,m){var v;if(!w||fl(d)||h!=null&&h.url_allowlist&&!Tc(h.url_allowlist,m)||h!=null&&h.url_ignorelist&&Tc(h.url_ignorelist,m))return!1;if(h!=null&&h.dom_event_allowlist){var S=h.dom_event_allowlist;if(S&&!S.some((E=>f.type===E)))return!1}var b=ff(d,p),_=b.parentIsUsefulElement,x=b.targetElementList;if(!(function(E,P){var $=P?.element_allowlist;if(C($))return!0;var O,L=function(V){if($.some((G=>V.tagName.toLowerCase()===G)))return{v:!0}};for(var N of E)if(O=L(N))return O.v;return!1})(x,h)||!va(x,h?.css_selector_allowlist)||va(x,(v=h?.css_selector_ignorelist)!==null&&v!==void 0?v:Ug))return!1;try{var I=w.getComputedStyle(d);if(I&&I.getPropertyValue("cursor")==="pointer"&&f.type==="click")return!0}catch{}var T=d.tagName.toLowerCase();switch(T){case"html":return!1;case"form":return(g||["submit"]).indexOf(f.type)>=0;case"input":case"select":case"textarea":return(g||["change","click"]).indexOf(f.type)>=0;default:return _?(g||["click"]).indexOf(f.type)>=0:(g||["click"]).indexOf(f.type)>=0&&(dl.indexOf(T)>-1||d.getAttribute("contenteditable")==="true")}})(i,t,this.Ne,r,r?["copy","cut"]:void 0,this.instance)){var s=$m(i,{e:t,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.Ne.element_attribute_ignorelist,elementsChainAsString:this.po,disableCaptureUrlHashes:this.instance.config.disable_capture_url_hashes}),o=s.props;if(s.explicitNoCapture)return!1;var a=this.getElementSelectors(i);if(a&&a.length>0&&(o.$element_selectors=a),e===Mo){var l,u=cf(w==null||(l=w.getSelection())==null?void 0:l.toString()),c=t.type||"clipboard";if(!u)return!1;o.$selected_content=u,o.$copy_type=c}return this.instance.capture(e,o),!0}}}isBrowserSupported(){return De(F?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(w==null||(e=w.location)==null?void 0:e.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(A.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.wo&&this.wo(),this.wo=void 0,A.info("History API monitoring stopped")}monitorHistoryChanges(){w&&w.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(w&&((e=w.history[t])==null||!e.__posthog_wrapped__)){var n=this;(function(i,r,s){try{if(!(r in i))return ou;var o={next:i[r]},a=s((function(){for(var l=arguments.length,u=new Array(l),c=0;l>c;c++)u[c]=arguments[c];return o.next.apply(this,u)}));return De(a)&&(a.prototype=a.prototype||{},Object.defineProperties(a,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:o}})),i[r]=a,()=>{if(i[r]!==a)for(var l=i[r];De(l)&&l.__posthog_layer__;){var u=l.__posthog_layer__;if(u.next===a)return void(u.next=o.next);l=u.next}else i[r]=o.next}}catch{return ou}})(w.history,t,(i=>function(r,s,o){i.call(this,r,s,o),n.So(t)}))}}So(t){try{var e,n=w==null||(e=w.location)==null?void 0:e.pathname;if(!n)return;n!==this._o&&this.isEnabled&&this._instance.capture(Gn,{navigation_type:t}),this._o=n}catch(i){A.error("Error capturing "+t+" pageview",i)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};ve(w,"popstate",t),this.wo=()=>{w&&w.removeEventListener("popstate",t)}}}},heatmaps:class{get Ne(){return this.instance.config}constructor(t){var e;this.Co=!1,this.vo=!1,this.Mo=null,this.instance=t,this.Co=!((e=this.instance.persistence)==null||!e.props[na]),this.rageclicks=new su(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return he(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return H(this.Ne.capture_heatmaps)?H(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;Lm.info("starting..."),this.To(),this.Ie()}else{var t;clearInterval((t=this.Mo)!==null&&t!==void 0?t:void 0),this.Eo(),this.getAndClearBuffer()}}onRemoteConfig(t){if(t.ok){var e=t.config;if("heatmaps"in e){var n=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[na]:n}),this.Co=n,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){Oo(t.originalEvent)&&this.ke(t.originalEvent,"deadclick")}Ie(){this.Mo&&clearInterval(this.Mo),this.Mo=F?.visibilityState==="visible"?setInterval(this.cr.bind(this),this.flushIntervalMilliseconds):null}To(){w&&F&&(this.Po=this.cr.bind(this),ve(w,ts,this.Po),this.Ro=t=>this.ke(t||w?.event),ve(F,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||w?.event),ve(F,"mousemove",this.Ao,{capture:!0}),this.Lo=new Hc(this.instance,Kg,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),ve(F,es,this.Oo),this.vo=!0)}Eo(){var t;w&&F&&(this.Po&&w.removeEventListener(ts,this.Po),this.Ro&&F.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&F.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&F.removeEventListener(es,this.Oo),clearTimeout(this.Do),(t=this.Lo)==null||t.stop(),this.vo=!1)}$o(t,e){var n=this.instance.scrollManager.scrollY(),i=this.instance.scrollManager.scrollX(),r=this.instance.scrollManager.scrollElement(),s=(function(o,a,l){for(var u=o;u&&fn(u)&&!Qe(u,"body");){if(u===l)return!1;var c=void 0;try{var d,f,h;c=(d=(f=(h=u.ownerDocument)==null?void 0:h.defaultView)!==null&&f!==void 0?f:w)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(j(a,c))return!0;u=uf(u)}return!1})(Eo(t),["fixed","sticky"],r);return{x:t.clientX+(s?0:i),y:t.clientY+(s?0:n),target_fixed:s,type:e}}ke(t,e){var n;if(e===void 0&&(e="click"),!Rc(t.target)&&Oo(t)){var i=this.$o(t,e);(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,new Date().getTime())&&Lc(Eo(t),this.instance.config.rageclick)&&this.Vt(k({},i,{type:"rageclick"})),this.Vt(i)}}Fo(t){!Rc(t.target)&&Oo(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(w){var e=this.Ne.disable_capture_url_hashes?dn(w.location.href):w.location.href,n=this.Ne.custom_personal_data_properties,i=this.Ne.mask_personal_data_properties?[...ri,...n||[]]:[],r=Zi(e,i,Xi);this.R=this.R||{},this.R[r]||(this.R[r]=[]),this.R[r].push(t)}}cr(){this.R&&!Vt(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:Hc,webVitalsAutocapture:class{constructor(t){var e;this.Co=!1,this.vo=!1,this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this.No=()=>{clearTimeout(this.qo),this.qo=void 0,this.R.metrics.length!==0&&(this._instance.capture("$web_vitals",k({$current_url:this.R.url},this.R.metrics.reduce(((n,i)=>k({},n,{["$web_vitals_"+i.name+"_event"]:k({},i),["$web_vitals_"+i.name+"_value"]:i.value})),{}))),this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.jo=n=>{var i;if(this.R=this.R||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},H(n?.name)||H(n?.value))yn.error("Invalid metric received",n);else{var r=typeof n.navigationURL=="string"?n.navigationURL:void 0,s=this.Bo(r);if(!C(s)){var o=ke(n.navigationId)||typeof n.navigationId=="string"?"navigation:"+n.navigationId:"url:"+s;if(!this.Ho||this.Ho>n.value){this.R.navigationKey!==o&&(this.No(),this.qo=setTimeout(this.No,this.flushToCaptureTimeoutMs)),C(this.R.navigationKey)&&(this.R.navigationKey=o,this.R.url=s),this.R.firstMetricTimestamp=C(this.R.firstMetricTimestamp)?Date.now():this.R.firstMetricTimestamp,n.attribution&&n.attribution.interactionTargetElement&&(n.attribution.interactionTargetElement=void 0);var a=(i=this._instance.sessionManager)==null?void 0:i.checkAndGetSessionAndWindowId(!0),l=k({},n,r?{navigationURL:s}:{},{$current_url:s,timestamp:Date.now()});C(a)||(l.$session_id=a.sessionId,l.$window_id=a.windowId),this.R.metrics.push(l),this.R.metrics.length===this.allowedMetrics.length&&this.No()}else yn.error("Ignoring metric with value >= "+this.Ho,n)}}},this.Uo=()=>{if(!this.vo){var n,i,r,s,o=B.__PosthogExtensions__,a=o?.postHogWebVitalsCallbacksByFlavor,l=a?.[this.zo]||(this.zo==="web-vitals"&&C(a)?o?.postHogWebVitalsCallbacks:void 0);if(C(l)||(n=l.onLCP,i=l.onCLS,r=l.onFCP,s=l.onINP),n&&i&&r&&s){var u={reportSoftNavs:this.useSoftNavs};this.allowedMetrics.indexOf("LCP")>-1&&n(this.jo.bind(this),u),this.allowedMetrics.indexOf("CLS")>-1&&i(this.jo.bind(this),u),this.allowedMetrics.indexOf("FCP")>-1&&r(this.jo.bind(this),u),this.allowedMetrics.indexOf("INP")>-1&&s(this.jo.bind(this),u),this.vo=!0}else yn.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[oa]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,n=he(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return H(n)?((e=this._instance.persistence)==null?void 0:e.props[aa])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(he(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=he(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=he(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=he(this.Wo)&&ke(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:au;return t>0&&6e4>=t?au:t}get isEnabled(){var t=me?.protocol;if(t!=="http:"&&t!=="https:")return yn.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=he(this.Wo)?this.Wo.web_vitals:gt(this.Wo)?this.Wo:void 0;return gt(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(yn.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var n=he(e.capturePerformance)&&!!e.capturePerformance.web_vitals,i=he(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[oa]:n}),this._instance.persistence.register({[aa]:i})),this.Co=n,this.startIfEnabled()}}}get zo(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}ai(t){var e=B.__PosthogExtensions__,n=this.zo,i=e?.postHogWebVitalsCallbacksByFlavor;i!=null&&i[n]||n==="web-vitals"&&C(i)&&e!=null&&e.postHogWebVitalsCallbacks?t():e==null||e.loadExternalDependency==null||e.loadExternalDependency(this._instance,n,(r=>{r?yn.error("failed to load script",r):t()}))}Bo(t){var e=t||w?.location.href;if(e){var n=this._instance.config.disable_capture_url_hashes?dn(e):e,i=this._instance.config.custom_personal_data_properties,r=this._instance.config.mask_personal_data_properties?[...ri,...i||[]]:[];return Zi(n,r,Xi)}yn.error("Could not determine current URL")}}},zm={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var n;if(w&&this.isEnabled&&(n=B.__PosthogExtensions__)!=null&&n.errorWrappingFunctions){var i=B.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,r=B.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,s=B.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.Vo&&this.Ne.capture_unhandled_errors&&(this.Vo=i(this.captureException.bind(this))),!this.Zo&&this.Ne.capture_unhandled_rejections&&(this.Zo=r(this.captureException.bind(this))),!this.Go&&this.Ne.capture_console_errors&&(this.Go=s(this.captureException.bind(this)))}catch(o){Ii.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[ia]),this.Jo=new Wp(k({},(function(n){var i,r,s,o;return n===void 0&&(n={}),{refillRate:(i=(r=n.exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:n.__exceptionRateLimiterRefillRate)!==null&&i!==void 0?i:1,bucketSize:(s=(o=n.exceptionRateLimiterBucketSize)!==null&&o!==void 0?o:n.__exceptionRateLimiterBucketSize)!==null&&s!==void 0?s:10}})(this._instance.config.error_tracking),{refillInterval:1e4,rt:Ii})),this.Ne=this.Yo(),this.startIfEnabledOrStop()}Yo(){var t=this._instance.config.capture_exceptions,e={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return he(t)?e=k({},e,t):(C(t)?this.Ko:t)&&(e=k({},e,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),e}get isEnabled(){return this.Ne.capture_console_errors||this.Ne.capture_unhandled_errors||this.Ne.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(Ii.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",(i=>{if(i)return Ii.error("failed to load script",i);t()}))}Qo(){var t,e,n;(t=this.Vo)==null||t.call(this),this.Vo=void 0,(e=this.Zo)==null||e.call(this),this.Zo=void 0,(n=this.Go)==null||n.call(this),this.Go=void 0}onRemoteConfig(t){if(t.ok){var e=t.config;"autocaptureExceptions"in e&&(this.Ko=!!e.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[ia]:this.Ko}),this.Ne=this.Yo(),this.startIfEnabledOrStop())}}onConfigChange(){this.Ne=this.Yo()}captureException(t){var e,n,i,r=(e=t==null||(n=t.$exception_list)==null||(n=n[0])==null?void 0:n.type)!==null&&e!==void 0?e:"Exception";this.Jo.consumeRateLimit(r)?Ii.info("Skipping exception capture because of client rate limiting.",{exception:r}):(i=this._instance.exceptions)==null||i.sendExceptionEvent(t)}},exceptions:class{constructor(t){var e,n;this.Xo=[],this.tl=new og([new pg,new Sg,new mg,new gg,new bg,new wg,new _g,new Eg],(function(i){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;r>o;o++)s[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` -`),d=l;c.length>d;d++){var f=c[d];if(1024>=f.length){var h=Cc.test(f)?f.replace(Cc,"$1"):f;if(!h.match(/\S*Error: /)){for(var p of s){var g=p(h,i);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var v=Array.from(m);return v.reverse(),v.slice(0,50).map((S=>{return k({},S,{filename:S.filename||(b=v,b[b.length-1]||{}).filename,function:S.function||ni});var b}))})(u)}})("web:javascript",ug,hg)),this._instance=t,this.Xo=(e=(n=this._instance.persistence)==null?void 0:n.get_property(ra))!==null&&e!==void 0?e:[],this.el=Yr(this.il()),this.rl=new Ig(this.el)}onConfigChange(){this.el=Yr(this.il()),this.rl.setConfig(this.el)}onRemoteConfig(t){var e,n,i;if(t.ok){var r=t.config;if("errorTracking"in r){var s=(e=(n=r.errorTracking)==null?void 0:n.suppressionRules)!==null&&e!==void 0?e:[],o=(i=r.errorTracking)==null?void 0:i.captureExtensionExceptions;this.Xo=s,this._instance.persistence&&this._instance.persistence.register({[ra]:this.Xo,[sa]:o})}}}get nl(){var t,e=!!this._instance.get_property(sa),n=this._instance.config.error_tracking.captureExtensionExceptions;return(t=n??e)!==null&&t!==void 0&&t}buildProperties(t,e){return this.tl.buildFromUnknown(t,{syntheticException:e?.syntheticException,mechanism:{handled:e?.handled}})}addExceptionStep(t,e){if(this.el.enabled)try{if(!X(t)||t.trim().length===0)return void Et.warn("Ignoring exception step because message must be a non-empty string");var n=(function(s){if(!s)return{sanitizedProperties:{},droppedKeys:[]};var o=[];return{sanitizedProperties:Object.keys(s).reduce(((a,l)=>xg.has(l)?(o.push(l),a):(a[l]=s[l],a)),{}),droppedKeys:o}})(this.sl(e)),i=n.sanitizedProperties,r=n.droppedKeys;r.length>0&&Et.warn("Ignoring reserved exception step fields",{droppedKeys:r}),this.rl.add(k({[Vr]:t,[Kr]:new Date().toISOString()},i))}catch(s){Et.error("Failed to add exception step. Ignoring breadcrumb.",s)}}sendExceptionEvent(t){try{var e=t.$exception_list;if(this.al(e)){if(this.ol(e))return this.ll("Exception dropped: matched a suppression rule"),void Et.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 Et.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 Et.info("Skipping exception capture because it was thrown by the PostHog SDK")}var n=this.el.enabled&&H(t.$exception_steps)?this.dl(t):t,i=typeof(s=globalThis._posthogReleaseId)=="string"&&s.length>0?s:void 0;i&&(n.$release_id=i);try{var r=this._instance.capture("$exception",n,{_noTruncate:!0,_batchKey:"exceptionEvent",Wn:!0});return r&&this.rl.clear(),r}catch(o){return Et.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void Et.error("Failed to process exception event. Ignoring this exception.",o)}var s}dl(t){try{var e=this.rl.getAttachable();return e.length===0?t:k({},t,{$exception_steps:e})}catch(n){return Et.error("Failed to read buffered exception steps. Capturing exception without steps.",n),t}}ll(t){this.el.enabled&&this.rl.add({[Vr]:t,[Kr]:new Date().toISOString()})}sl(t){return he(t)?k({},t):{}}il(){var t,e;return(t=(e=this._instance.config.error_tracking)==null?void 0:e.exception_steps)!==null&&t!==void 0?t:{}}ol(t){if(t.length===0)return!1;try{var e=t.reduce(((n,i)=>{var r=i.type,s=i.value;return X(r)&&r.length>0&&n.$exception_types.push(r),X(s)&&s.length>0&&n.$exception_values.push(s),n}),{$exception_types:[],$exception_values:[]});return this.Xo.some((n=>{var i=n.values.map((r=>{var s=jf[r.operator],o=e[r.key];if(!s||!o)return!1;var a=U(r.value)?r.value:[r.value];return a.length>0&&s(a,o)}));return n.type==="OR"?i.some(Boolean):i.every(Boolean)}))}catch(n){return Et.warn("Failed to evaluate suppression rules. Capturing the exception.",n),!1}}ul(t){return t.flatMap((e=>{var n,i;return(n=(i=e.stacktrace)==null?void 0:i.frames)!==null&&n!==void 0?n:[]})).some((e=>e.filename&&e.filename.startsWith("chrome-extension://")))}hl(t){if(t.length>0){var e,n,i,r,s=(e=(n=t[0].stacktrace)==null?void 0:n.frames)!==null&&e!==void 0?e:[],o=s[s.length-1];return(i=o==null||(r=o.filename)==null?void 0:r.includes("posthog.com/static"))!==null&&i!==void 0&&i}return!1}al(t){return!H(t)&&U(t)}}},Gm=k({productTours:class{get Mr(){return this._instance.persistence}constructor(t){this.vl=null,this.cl=null,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(t.ok){var e=t.config;if("productTours"in e){var n,i;if(this.Mr&&this.Mr.register({[ol]:!!e.productTours}),!Bo(this._instance))return!this.vl&&H((n=this.Mr)==null?void 0:n.props[Mi])||Sr.info("product tours disabled; stopping and clearing cached tours"),(i=this.vl)==null||i.stop(),this.vl=null,void this.clearCache();this.loadIfEnabled()}}}loadIfEnabled(){!this.vl&&Bo(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.generateProductTours?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",(i=>{i?Sr.error("Could not load product tours script",i):t()}))}fl(){var t;!this.vl&&(t=B.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=B.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(t,e){if(e===void 0&&(e=!1),!U(this.cl)||e){var n=this.Mr;if(n){var i=n.props[Mi];if(U(i)&&!e)return this.cl=i,void t(i,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",timestampMode:"query",callback:r=>{if(Bo(this._instance)){var s=r.statusCode;if(s!==200||!r.json){var o="Product Tours API could not be loaded, status: "+s;return s===0?r.error||Sr.warn(o):Sr.error(o),void t([],{isLoaded:!1,error:o})}var a=U(r.json.product_tours)?r.json.product_tours:[];this.cl=a,n&&n.register({[Mi]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){H(this.vl)?t([],{isLoaded:!1,error:"Product tours not loaded"}):this.vl.getActiveProductTours(t)}showProductTour(t){var e;(e=this.vl)==null||e.showTourById(t)}previewTour(t){this.vl?this.vl.previewTour(t):this.ai((()=>{var e;this.fl(),(e=this.vl)==null||e.previewTour(t)}))}dismissProductTour(){var t;(t=this.vl)==null||t.dismissTour("user_clicked_skip")}nextStep(){var t;(t=this.vl)==null||t.nextStep()}previousStep(){var t;(t=this.vl)==null||t.previousStep()}clearCache(){var t;this.cl=null,(t=this.Mr)==null||t.unregister(Mi)}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)}}},Cs),Vm={siteApps:class{constructor(t){this.pl=0,this._instance=t,this.gl=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}ml(t,e){if(e){var n=this.globalsForEvent(e);this.gl.push(n),this.gl.length>1e3&&(this.gl=this.gl.slice(10))}}get siteAppLoaders(){var t;return(t=B._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,n,i,r,s,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var f=d[0];l[f]={id:u[f],type:f,properties:d[1]}}var h=t.$set_once,p=t.$set;return{event:k({},ud(t,Nm),{properties:k({},t.properties,p?{$set:k({},(e=(n=t.properties)==null?void 0:n.$set)!==null&&e!==void 0?e:{},p)}:{},h?{$set_once:k({},(i=(r=t.properties)==null?void 0:r.$set_once)!==null&&i!==void 0?i:{},h)}:{}),elements_chain:(s=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&s!==void 0?s:"",distinct_id:(a=t.properties)==null?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}bl(t){var e,n=(e=t.tagName)==null?void 0:e.toLowerCase();return n==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(bt.error("prepare_external_dependency_stylesheet returned null"),null):n==="script"&&this._instance.config.prepare_external_dependency_script?this._instance.config.prepare_external_dependency_script(t)||(bt.error("prepare_external_dependency_script returned null"),null):t}_l(){var t,e,n,i,r,s,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=F?.defaultView,u=l==null||(t=l.Node)==null?void 0:t.prototype;if(!l||!u)return()=>{};if(this.pl++,this.wl)return this.kl();var c=[],d=this,f=new WeakSet,h=(m,v,S)=>{if(m!=null&&m[v]){var b=m[v];m[v]=S(b),c.push((()=>{m[v]=b}))}},p=m=>{if(f.has(m))return m;var v=d.bl(m);return v&&f.add(v),v},g=m=>m.map((v=>typeof v=="string"?v:p(v))).filter((v=>!Ke(v)));return h(u,"appendChild",(m=>function(v){var S=p(v);return S?m.call(this,S):v})),h(u,"insertBefore",(m=>function(v,S){var b=p(v);return b?m.call(this,b,S):v})),h(u,"replaceChild",(m=>function(v,S){var b=p(v);return b?m.call(this,b,S):S})),[(e=l.Element)==null?void 0:e.prototype,(n=l.Document)==null?void 0:n.prototype,(i=l.DocumentFragment)==null?void 0:i.prototype].forEach((m=>{h(m,"append",(v=>function(){for(var S=arguments.length,b=new Array(S),_=0;S>_;_++)b[_]=arguments[_];return v.apply(this,g(b))})),h(m,"prepend",(v=>function(){for(var S=arguments.length,b=new Array(S),_=0;S>_;_++)b[_]=arguments[_];return v.apply(this,g(b))}))})),[(r=l.Element)==null?void 0:r.prototype,(s=l.CharacterData)==null?void 0:s.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((m=>{h(m,"before",(v=>function(){for(var S=arguments.length,b=new Array(S),_=0;S>_;_++)b[_]=arguments[_];return v.apply(this,g(b))})),h(m,"after",(v=>function(){for(var S=arguments.length,b=new Array(S),_=0;S>_;_++)b[_]=arguments[_];return v.apply(this,g(b))})),h(m,"replaceWith",(v=>function(){for(var S=arguments.length,b=new Array(S),_=0;S>_;_++)b[_]=arguments[_];var x=g(b);return b.length&&!x.length?void 0:v.apply(this,x)}))})),h((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(v,S){var b=p(S);return b?m.call(this,v,b):null})),this.wl=()=>{c.forEach((m=>m())),this.wl=void 0},this.kl()}kl(){var t=!1;return()=>{var e;t||(t=!0,this.pl--,this.pl===0&&((e=this.wl)==null||e.call(this)))}}xl(t,e){e===void 0&&(e=!0);var n=this._l();try{var i=t(n);return e&&n(),i}catch(r){throw n(),r}}setupSiteApp(t){var e=this.apps[t.id],n=()=>{var o;!e.errored&&this.gl.length&&(bt.info("Processing "+this.gl.length+" events for site app with id "+t.id),this.gl.forEach((a=>this.xl((()=>e.processEvent==null?void 0:e.processEvent(a))))),e.processedBuffer=!0),Object.values(this.apps).every((a=>a.processedBuffer||a.errored))&&((o=this.yl)==null||o.call(this))},i=!1,r=o=>{e.errored=!o,e.loaded=!0,bt.info("Site app with id "+t.id+" "+(o?"loaded":"errored")),i&&n()};try{var s=this.xl((o=>t.init({posthog:this._instance,callback(a){o(),r(a)}})),!1).processEvent;s&&(e.processEvent=s),i=!0}catch(o){bt.error(uu+t.id,o),r(!1)}if(i&&e.loaded)try{n()}catch(o){bt.error("Error while processing buffered events PostHog app with config id "+t.id,o),e.errored=!0}}Sl(){var t=this.siteAppLoaders||[];for(var e of t)this.apps[e.id]={id:e.id,loaded:!1,errored:!1,processedBuffer:!1};for(var n of t)this.setupSiteApp(n)}Cl(t){var e=this;if(Object.keys(this.apps).length!==0){var n=this.globalsForEvent(t),i=function(s){try{e.xl((()=>s.processEvent==null?void 0:s.processEvent(n)))}catch(o){bt.error("Error while processing event "+t.event+" for site app "+s.id,o)}};for(var r of Object.values(this.apps))i(r)}}onRemoteConfig(t){var e,n,i,r=this;if((e=this.siteAppLoaders)!=null&&e.length)return this.isEnabled?(this.Sl(),void this._instance.on("eventCaptured",(l=>this.Cl(l)))):void bt.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((n=this.yl)==null||n.call(this),t.ok){var s=t.config;if((i=s.siteApps)!=null&&i.length)if(this.isEnabled){var o=function(){var l,u=a.id,c=a.url;B["__$$ph_site_app_"+u]=r._instance,(l=B.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(r._instance,c,(d=>{if(d)return bt.error(uu+u,d)}))};for(var a of s.siteApps)o()}else bt.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},Km={tracingHeaders:class{constructor(t){this.Ml=void 0,this.Tl=void 0,this.El=void 0,this.Uo=()=>{var e,n,i=this.Il();i?(C(this.Ml)&&(this.Ml=(e=B.__PosthogExtensions__)==null||(e=e.tracingHeadersPatchFns)==null?void 0:e._patchXHR(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager)),C(this.Tl)&&(this.Tl=(n=B.__PosthogExtensions__)==null||(n=n.tracingHeadersPatchFns)==null?void 0:n._patchFetch(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager))):this.Qo()},this._instance=t}initialize(){this.startIfEnabledOrStop()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",(i=>{if(i)return Mm.error("failed to load script",i);t()}))}Pl(){var t,e;return(t=(e=this._instance.config.tracing_headers)!==null&&e!==void 0?e:this._instance.config.addTracingHeaders)!==null&&t!==void 0?t:this._instance.config.__add_tracing_headers}Il(){var t=this.Pl();return U(t)?(U(this.El)?this.El.splice(0,this.El.length,...t):this.El=[...t],t.length>0?this.El:void 0):(U(this.El)&&this.El.splice(0),this.El=t||void 0,this.El)}Qo(){var t,e;(t=this.Ml)==null||t.call(this),(e=this.Tl)==null||e.call(this),this.Ml=void 0,this.Tl=void 0}startIfEnabledOrStop(){this.Il()?this.ai(this.Uo):this.Qo()}}},Ym=k({surveys:class{get Ne(){return this._instance.config}constructor(t){this.Rl=void 0,this._surveyManager=null,this.Al=!1,this.Fl=[],this.Ll=null,this.Ol=null,this._instance=t,this._surveyEventReceiver=null}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this.Ne.disable_surveys){if(!t.ok)return Q.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(H(e))return Q.warn("Flags not loaded yet. Not loading surveys.");var n=U(e);this.Rl=n?e.length>0:e,Q.info("flags response received, isSurveysEnabled: "+this.Rl),this.loadIfEnabled()}}reset(){try{var t;(t=this._surveyEventReceiver)==null||t.reset(),localStorage.removeItem("lastSeenSurveyDate");for(var e=[],n=0;nlocalStorage.removeItem(r)))}catch{}}loadIfEnabled(){if(!this._surveyManager)if(this.Al)Q.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)Q.info(du);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())Q.info("Not loading surveys in cookieless mode without consent.");else{var t=B?.__PosthogExtensions__;if(t){if(!C(this.Rl)||this.Ne.advanced_enable_surveys){var e=this.Rl||this.Ne.advanced_enable_surveys;this.Al=!0;try{var n=t.generateSurveys;if(n)return void this.Dl(n,e);var i=t.loadExternalDependency;if(!i)return void this.$l(ll);i(this._instance,"surveys",(r=>{r||!t.generateSurveys?this.$l("Could not load surveys script",r):this.Dl(t.generateSurveys,e)}))}catch(r){throw this.$l("Error initializing surveys",r),r}finally{this.Al=!1}}}else Q.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new Dm(this._instance),Q.info("Surveys loaded successfully"),this.Nl({isLoaded:!0})}$l(t,e){Q.error(t,e),this.Nl({isLoaded:!1,error:t})}onSurveysLoaded(t){return this.Fl.push(t),this._surveyManager&&this.Nl({isLoaded:!0}),()=>{this.Fl=this.Fl.filter((e=>e!==t))}}getSurveys(t,e){if(e===void 0&&(e=!1),this.Ne.disable_surveys)return Q.info(du),t([]);var n,i=this._instance.get_property(ca);if(i&&!e)return t(i,{isLoaded:!0}),void(this.ql()&&this.getSurveys((()=>{}),!0));typeof Promise<"u"&&this.Ll?this.Ll.then((r=>t(r.surveys,r.context))):(typeof Promise<"u"&&(this.Ll=new Promise((r=>{n=r}))),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this.Ne.token),method:"GET",timestampMode:"query",timeout:this.Ne.surveys_request_timeout_ms,callback:r=>{var s;this.Ll=null;var o=r.statusCode;if(o!==200||!r.json){var a="Surveys API could not be loaded, status: "+o;o!==0?Q.error(a):r.error||Q.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(n==null||n({surveys:[],context:l}))}this.Ol=null;var u,c=r.json.surveys||[],d=c.filter((h=>(function(p){return!(!p.start_date||p.end_date)})(h)&&(Hf(h)||(function(p){var g;return!((g=p.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(h))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(s=this._instance.persistence)==null||s.register({[ca]:c,[Zr]:Date.now()});var f={isLoaded:!0};t(c,f),n?.({surveys:c,context:f})}}))}ql(){return this.jl()&&!this.Ll&&!this.Bl()}jl(){var t=this._instance.get_property(Zr);return ke(t)&&Date.now()-t>3e5}Bl(){return ke(this.Ol)&&3e5>Date.now()-this.Ol}markSurveyAsSeen(t,e){var n,i={id:t,current_iteration:(n=e?.iteration)!==null&&n!==void 0?n:null};qf(i);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}}Nl(t){for(var e of this.Fl)try{if(!t.isLoaded)return e([],t);this.getSurveys(e)}catch(n){Q.error("Error in survey callback",n)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!H(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);Q.warn("init was not called")}Hl(t){var e=null;return this.getSurveys((n=>{var i;e=(i=n.find((r=>r.id===t)))!==null&&i!==void 0?i:null})),e}Ul(t){if(H(this._surveyManager))return{eligible:!1,reason:xr};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyEligibility(e):{eligible:!1,reason:"Survey not found"}}zl(t){if(H(this._surveyManager))return{eligible:!1,reason:xr};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyRenderability(e):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(t){if(H(this._surveyManager))return Q.warn("init was not called"),{visible:!1,disabledReason:xr};var e=this.zl(t);return{visible:e.eligible,disabledReason:e.reason}}canRenderSurveyAsync(t,e){return H(this._surveyManager)?(Q.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:xr})):new Promise((n=>{this.getSurveys((i=>{var r,s=(r=i.find((a=>a.id===t)))!==null&&r!==void 0?r:null;if(s){var o=this.zl(s);n({visible:o.eligible,disabledReason:o.reason})}else n({visible:!1,disabledReason:"Survey not found"})}),e)}))}renderSurvey(t,e,n){var i;if(H(this._surveyManager))Q.warn("init was not called");else{var r=typeof t=="string"?this.Hl(t):t;if(r!=null&&r.id)if(bm.includes(r.type)){var s=F?.querySelector(e);if(s)return(i=r.appearance)!=null&&i.surveyPopupDelaySeconds?(Q.info("Rendering survey "+r.id+" with delay of "+r.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;Q.info("Rendering survey "+r.id+" with delay of "+((o=r.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(a=this._surveyManager)==null||a.renderSurvey(r,s,n),Q.info("Survey "+r.id+" rendered")}),1e3*r.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(r,s,n);Q.warn("Survey element not found")}else Q.warn("Surveys of type "+r.type+" cannot be rendered in the app");else Q.warn("Survey not found")}}displaySurvey(t,e){var n;if(H(this._surveyManager))Q.warn("init was not called");else{var i=this.Hl(t);if(i){var r=i;if((n=i.appearance)!=null&&n.surveyPopupDelaySeconds&&e.ignoreDelay&&(r=k({},i,{appearance:k({},i.appearance,{surveyPopupDelaySeconds:0})})),e.displayType!==ya.Popover&&e.initialResponses&&Q.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),e.ignoreConditions===!1){var s=this.Ul(i);if(!s.eligible)return void Q.warn("Survey is not eligible to be displayed: ",s.reason)}e.displayType!==ya.Inline?this._surveyManager.handlePopoverSurvey(r,e):this.renderSurvey(r,e.selector,e.properties)}else Q.warn("Survey not found")}}cancelPendingSurvey(t){H(this._surveyManager)?Q.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},Cs),Jm={toolbar:class{constructor(t){this.instance=t}Wl(t){B.ph_toolbar_state=t}Vl(){var t;return(t=B.ph_toolbar_state)!==null&&t!==void 0?t:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(t,e,n){if(t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),ma(this.instance.config)||!w||!F)return!1;t=t??w.location,n=n??w.history;try{if(!e){try{w.localStorage.setItem("test","test"),w.localStorage.removeItem("test")}catch{return!1}e=w?.localStorage}var i,r=jm||ss(t.hash,"__posthog")||ss(t.hash,"state"),s=r?Pc((()=>JSON.parse(atob(decodeURIComponent(r)))))||Pc((()=>JSON.parse(decodeURIComponent(r)))):null;return s&&s.action==="ph_authorize"?((i=s).source="url",i&&Object.keys(i).length>0&&(s.desiredHash?t.hash=s.desiredHash:n?n.replaceState(n.state,"",t.pathname+t.search):t.hash="")):((i=JSON.parse(e.getItem(fu)||"{}")).source="localstorage",delete i.userIntent),!(!i.token||this.instance.config.token!==i.token||(this.loadToolbar(i),0))}catch{return!1}}Zl(t){var e=B.ph_load_toolbar||B.ph_load_editor;!H(e)&&De(e)?e(t,this.instance):hu.warn("No toolbar load function found")}loadToolbar(t){var e=!(F==null||!F.getElementById(sf));if(!w||e)return!1;var n=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,i=k({token:this.instance.config.token},t,{apiURL:this.instance.requestRouter.endpointFor("ui")},n?{instrument:!1}:{});if(w.localStorage.setItem(fu,JSON.stringify(k({},i,{source:void 0}))),this.Vl()===2)this.Zl(i);else if(this.Vl()===0){var r;this.Wl(1),(r=B.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"toolbar",(s=>{if(s)return hu.error("[Toolbar] Failed to load",s),void this.Wl(0);this.Wl(2),this.Zl(i)})),ve(w,"turbolinks:load",(()=>{this.Wl(0),this.loadToolbar(i)}))}return!0}Gl(t){return this.loadToolbar(t)}maybeLoadEditor(t,e,n){return t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),this.maybeLoadToolbar(t,e,n)}}},Zm=k({experiments:Me},Cs),Xm={conversations:class{constructor(t){this.Ql=void 0,this._conversationsManager=null,this.Kl=!1,this.Jl=null,this.Yl=!1,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this._instance.config.disable_conversations&&(this.Xl=t.ok,t.ok)){var e=t.config.conversations;H(e)||(gt(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||ma(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=B?.__PosthogExtensions__;if(t&&!C(this.Ql)&&this.Ql)if(this.Jl&&this.Jl.token){this.Kl=!0;try{var e=t.initConversations;if(e)return this.tu(e),void(this.Kl=!1);var n=t.loadExternalDependency;if(!n)return void this.eu(ll);n(this._instance,"conversations",(i=>{i||!t.initConversations?this.eu("Could not load conversations script",i):this.tu(t.initConversations),this.Kl=!1}))}catch(i){this.eu("Error initializing conversations",i),this.Kl=!1}}else st.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,st.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else st.error("Cannot complete initialization: remote config is null")}eu(t,e){st.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():st.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!Ke(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":ma(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.Xl===!1?"remote_config_failed":C(this.Ql)?this.Xl?"disabled_in_project":"remote_config_pending":this.Ql?H(this.Jl)||!this.Jl.token?"missing_token":B!=null&&B.__PosthogExtensions__?this.Kl?"initializing":this.Yl?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.isVisible())!==null&&t!==void 0&&t}sendMessage(t,e,n){var i=this;return se((function*(){return i._conversationsManager?i._conversationsManager.sendMessage(t,e,n):(st.warn(bn),null)}))()}getMessages(t,e){var n=this;return se((function*(){return n._conversationsManager?n._conversationsManager.getMessages(t,e):(st.warn(bn),null)}))()}markAsRead(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(st.warn(bn),null)}))()}getTickets(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(st.warn(bn),null)}))()}requestRestoreLink(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(st.warn(bn),null)}))()}restoreFromToken(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(st.warn(bn),null)}))()}restoreFromUrlToken(){var t=this;return se((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(st.warn(bn),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()}}},Qm={logs:class{constructor(t){var e,n=this;this.iu=!1,this.ru=!1,this.rt=pe("[logs]"),this.nu=k({},this.rt,{error(){for(var i=arguments.length,r=new Array(i),s=0;i>s;s++)r[s]=arguments[s];r.some(bu)||n.rt.error(...r)}}),this.tr=[],this.su=[],this.Sa=0,this.au=()=>{var i,r;this.Sa=0,(i=this.ou)==null||i.onReconnect(),(r=this.lu)==null||r.onReconnect()},this._instance=t,this._instance&&(e=this._instance.config.logs)!=null&&e.captureConsoleLogs&&(this.iu=!0),w&&ve(w,"online",this.au)}uu(t,e,n,i){var r,s=(function(o,a){var l,u,c,d,f,h,p,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,v=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,S=C(v)?Math.max(m,2048):Math.max(m,v),b=o?.resourceAttributes;return{serviceName:(d=(f=b?.["service.name"])!==null&&f!==void 0?f:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(h=b?.["service.version"])!==null&&h!==void 0?h:o?.serviceVersion,environment:(p=b?.["deployment.environment"])!==null&&p!==void 0?p:o?.environment,resourceAttributes:b,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:S,maxBatchRecordsPerPost:100,rateCapWindowMs:g,maxLogsPerInterval:v,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}})((r=this._instance)==null||(r=r.config)==null?void 0:r.logs,n);return[new ig(this.hu(t,e),s,this.nu,(()=>this.du()),(o=>o()),void 0,i),s]}vu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.ou||this.cu!==e){var n;(n=this.ou)==null||n.reset(),this.cu=e;var i=this.uu((()=>this.tr),(r=>{this.tr=r}));this.ou=i[0],this.fu=i[1]}return this.ou}pu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.lu||this.gu!==e){var n;(n=this.lu)==null||n.reset(),this.gu=e;var i=this.uu((()=>this.su),(r=>{this.su=r}),{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},wu);this.lu=i[0],this.mu=i[1]}return this.lu}initialize(){this.loadIfEnabled()}onRemoteConfig(t){var e;if(t.ok){var n=(e=t.config.logs)==null?void 0:e.captureConsoleLogs;!H(n)&&n&&(this.iu=!0,this.loadIfEnabled())}}reset(){var t,e;this.tr=[],(t=this.ou)==null||t.reset(),this.su=[],(e=this.lu)==null||e.reset(),this.Sa=0}captureLog(t){this.vu().captureLog(t)}he(t){this.pu().captureLog(t)}get logger(){return this.yu||(this.yu={trace:(t,e)=>this.captureLog({body:t,level:"trace",attributes:e}),debug:(t,e)=>this.captureLog({body:t,level:"debug",attributes:e}),info:(t,e)=>this.captureLog({body:t,level:"info",attributes:e}),warn:(t,e)=>this.captureLog({body:t,level:"warn",attributes:e}),error:(t,e)=>this.captureLog({body:t,level:"error",attributes:e}),fatal:(t,e)=>this.captureLog({body:t,level:"fatal",attributes:e})}),this.yu}flushLogs(t){t?this.bu(t):(this.ou&&this.ou.flush().catch((e=>this._u(e))),this.lu&&this.lu.flush().catch((e=>this._u(e))))}_u(t){bu(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=B?.__PosthogExtensions__;if(t){var e=t.loadExternalDependency;e?e(this._instance,"logs",(n=>{var i;n||(i=t.logs)==null||!i.initializeLogs?this.rt.error("Could not load logs script",n):(t.logs.initializeLogs(this._instance),this.ru=!0)})):this.rt.error(ll)}else this.rt.error("PostHog Extensions not found.")}}hu(t,e){var n=this._instance;return{get isDisabled(){return!1},get optedOut(){return!n.is_capturing()},getPersistedProperty:i=>i===jt.LogsQueue?t():void 0,setPersistedProperty(i,r){var s;i===jt.LogsQueue&&e((s=r)!==null&&s!==void 0?s:[])},Ot:i=>this.Ot(i),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Ot(t){return new Promise((e=>{if(vf(this.Sa,3))e({kind:"fatal",error:jo(void 0,"logs endpoint is unreachable, dropping batch")});else{var n=!1,i=s=>{n||(n=!0,clearTimeout(r),e(s))},r=setTimeout((()=>{this.rt.warn("Logs request timed out before receiving a response"),i({kind:"retry-later",error:jo(void 0,"logs request timed out")})}),9e4);this._instance._send_request({method:"POST",url:this.wu(),data:t,compression:"best-available",batchKey:"logs",fireCallbackOnDrop:!0,callback:s=>{var o=s.statusCode;if(this.ku(o),o>=200&&300>o)i({kind:"ok"});else if(o===413)i({kind:"too-large"});else if(o!==0&&o!==429&&500>o)i({kind:"fatal",error:new Error("logs request failed with status "+o)});else{var a;o===0?(s.error||this.rt.warn("Logs request failed before receiving an HTTP response"),i({kind:"retry-later",error:jo(s.error,"logs request failed before receiving an HTTP response")})):i({kind:"retry-later",error:(a=s.error)!==null&&a!==void 0?a:new Error("logs request failed with status "+o)})}}})}}))}ku(t){(t!==0||this._instance.__loaded)&&(this.Sa=_f(t,this.Sa,3,(()=>this.rt.warn("Log requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped sending logs; will try again when connectivity changes."))))}bu(t){this.tr.length>0&&this.xu(t,this.tr,this.fu,ne.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,wu,(e=>{this.su=e}))}xu(t,e,n,i,r){if(e.length!==0){var s=e.map((a=>a.record));r([]);var o=Ud(s,jd(n,ne.LIB_NAME,ne.LIB_VERSION),i,ne.LIB_VERSION);this._instance._send_request({method:"POST",url:this.wu(),data:o,compression:"best-available",batchKey:"logs",transport:t})}}wu(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}du(){var t,e={};if(e.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var n=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.windowId,r=n.sessionStartTimestamp,s=n.lastActivityTimestamp;e.sessionId=n.sessionId,e.windowId=i,H(r)||(e.sessionStartTimestamp=r),H(s)||(e.lastActivityTimestamp=s)}if(B!=null&&(t=B.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?dn(B.location.href):B.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},ev={metrics:class{constructor(t){this.rt=pe("[metrics]"),this._instance=t}initialize(){}vu(){var t,e,n=(t=this._instance)==null||(t=t.config)==null?void 0:t.metrics;return this.ou&&this.cu===n||((e=this.ou)==null||e.reset(),this.cu=n,this.ou=new rg(this.hu(),(function(i){var r,s,o,a,l,u=i?.resourceAttributes;return{serviceName:(r=u?.["service.name"])!==null&&r!==void 0?r:i?.serviceName,serviceVersion:(s=u?.["service.version"])!==null&&s!==void 0?s:i?.serviceVersion,environment:(o=u?.["deployment.environment"])!==null&&o!==void 0?o:i?.environment,resourceAttributes:u,beforeSend:i?.beforeSend,flushIntervalMs:(a=i?.flushIntervalMs)!==null&&a!==void 0?a:1e4,maxSeriesPerFlush:(l=i?.maxSeriesPerFlush)!==null&&l!==void 0?l:1e3}})(n),this.rt)),this.ou}count(t,e,n){e===void 0&&(e=1),this.vu().count(t,e,n)}gauge(t,e,n){this.vu().gauge(t,e,n)}histogram(t,e,n){this.vu().histogram(t,e,n)}flush(t){if(!this.ou)return Promise.resolve();if(t){var e=this.ou.drainWindow();return e&&this.Jt(e,t),Promise.resolve()}return this.ou.flush().catch((n=>this.rt.error("PostHog metrics flush failed:",n)))}reset(){var t;(t=this.ou)==null||t.reset()}hu(){var t=this._instance,e=this;return{get isDisabled(){return!1},get optedOut(){return!t.is_capturing()},Jt:n=>e.Jt(n),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Jt(t,e){return new Promise((n=>{var i=!1,r=o=>{i||(i=!0,clearTimeout(s),n(o))},s=setTimeout((()=>r({kind:"retry-later",error:new Error("metrics request timed out")})),9e4);this._instance._send_request(k({method:"POST",url:this.Su(),data:t,compression:"best-available",batchKey:"metrics"},e&&{transport:e},{fireCallbackOnDrop:!0,callback(o){var a=o.statusCode;if(a>=200&&300>a)r({kind:"ok"});else if(a===413)r({kind:"too-large"});else if(a!==0&&a!==429&&500>a)r({kind:"fatal",error:new Error("metrics request failed with status "+a)});else{var l;r({kind:"retry-later",error:(l=o.error)!==null&&l!==void 0?l:new Error("metrics request failed with status "+a)})}}}))}))}Su(){return this._instance.requestRouter.endpointFor("api","/i/v1/metrics")+"?token="+encodeURIComponent(this._instance.config.token)}}},tv=k({},Cs,Wm,qm,zm,Gm,Vm,Ym,Km,Jm,Zm,Xm,Qm,ev);Je.__defaultExtensionClasses=k({},tv);var Kf=(function(){ne.SDK_DIST_CHANNEL="npm";var t=Wi[Vn]=new Je;return(function(){function e(){e.done||(e.done=!0,Gf=!1,ie(Wi,(function(n){n._dom_loaded()})))}F!=null&&F.addEventListener?F.readyState==="complete"?e():ve(F,"DOMContentLoaded",e,{capture:!1}):w&&A.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const nv=["a[href]","button:not([disabled])","input:not([disabled]):not([type='hidden'])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(",");let ht=null,Ca=null,Yf="";const Aa=new Map;function Jf(t){return[...t.querySelectorAll(nv)].filter(e=>!e.hidden&&e.getAttribute("aria-hidden")!=="true"&&e.getClientRects().length>0)}function iv(t){for(const e of document.body.children)e===t||e.tagName==="SCRIPT"||(Aa.set(e,{inert:e.inert,ariaHidden:e.getAttribute("aria-hidden")}),e.inert=!0,e.setAttribute("aria-hidden","true"))}function rv(){for(const[t,e]of Aa)t.inert=e.inert,e.ariaHidden===null?t.removeAttribute("aria-hidden"):t.setAttribute("aria-hidden",e.ariaHidden);Aa.clear()}function Zf(t){return t?.dataset.modalDismissible!=="false"&&t?.getAttribute("aria-busy")!=="true"}function He(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n)return!1;ht&&ht!==n&&We(ht,{restoreFocus:!1,force:!0}),Ca=e.trigger||document.activeElement,ht=n,Yf=document.body.style.overflow,iv(n),document.body.style.overflow="hidden",n.classList.add("open"),n.setAttribute("aria-hidden","false");const i=n.querySelector(".modal-content");i&&(i.style.transform="scale(1) translateY(0)");const r=()=>{if(ht!==n)return;((e.initialFocus?n.querySelector(e.initialFocus):n.querySelector("[data-modal-initial-focus]"))||Jf(n)[0]||n.querySelector(".modal-content")||n).focus({preventScroll:!0})};return requestAnimationFrame(r),setTimeout(r,260),!0}function We(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n||!e.force&&!Zf(n))return!1;n.classList.remove("open"),n.setAttribute("aria-hidden","true"),rv(),document.body.style.overflow=Yf,ht=null;const i=Ca;return Ca=null,e.restoreFocus!==!1&&i?.isConnected&&i.focus({preventScroll:!0}),!0}function Eu(t,e,n="Operation in progress"){const i=typeof t=="string"?document.getElementById(t):t;i&&(i.dataset.modalDismissible=e?"false":"true",i.setAttribute("aria-busy",String(!!e)),e?i.setAttribute("aria-label",n):i.removeAttribute("aria-label"))}function sv(t){if(!Zf(t))return;const e=t.dataset.modalCloseHandler;e&&typeof window[e]=="function"?window[e]():We(t)}document.addEventListener("keydown",t=>{if(!ht)return;if(t.key==="Escape"){t.preventDefault(),t.stopImmediatePropagation(),sv(ht);return}if(t.key!=="Tab"){t.stopPropagation();return}const e=Jf(ht);if(!e.length){t.preventDefault(),(ht.querySelector(".modal-content")||ht).focus();return}const n=e[0],i=e[e.length-1];t.shiftKey&&document.activeElement===n?(t.preventDefault(),i.focus()):!t.shiftKey&&document.activeElement===i&&(t.preventDefault(),n.focus())},!0);function ov(){document.querySelectorAll(".modal-overlay").forEach(t=>{t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-hidden",t.classList.contains("open")?"false":"true");const e=t.querySelector(".modal-content");e&&!e.hasAttribute("tabindex")&&(e.tabIndex=-1);const n=t.querySelector("h1, h2, h3");n&&(n.id||(n.id=`${t.id}-title`),t.setAttribute("aria-labelledby",n.id)),t.querySelectorAll(".modal-close").forEach(i=>{i.getAttribute("aria-label")||i.setAttribute("aria-label","Close dialog")})})}const ml=Object.freeze({free:"Free",professional:"Pro",power:"Power"}),av=Object.freeze({free:2,professional:50,power:2e3}),lv="(contact us)",cv=Object.freeze({free:Object.freeze(["2 generations/month","Gemini model only","Code Review"]),professional:Object.freeze(["50 generations/month","All models","Code Regeneration","Code Review"]),power:Object.freeze(["2000 generations/month","All models","Code Regeneration","Bring your own key (BYOK)","Code Review","All models + early access",`API & MCP access ${lv}`])}),Xf="CodeFile",Qf="GeneratedCode",uv={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function an(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Pa(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function dv(t={},e=0){const n=Pa(t.artifactType||t.type||Xf),i=Pa(t.artifactName||t.name||t.fileName||`${Qf}-${e+1}`);return`${n||"artifact"}-${i||e+1}`}function eh(t={},e=0){const n=an(t),i=n.artifactType||n.type||Xf,r=n.artifactName||n.name||Qf;let s=n.fileName||r;return s.endsWith(".dart")||(s+=".dart"),{id:Pa(n.id)||dv({...n,artifactType:i,artifactName:r,fileName:s},e),artifactType:i,artifactName:r,fileName:s,deployPath:n.deployPath||"",description:n.description||"",code:n.code||n.content||"",dependencies:th(n.dependencies),imports:Array.isArray(n.imports)?n.imports:[],publicApi:Array.isArray(n.publicApi)?n.publicApi:[],relationships:nh(n.relationships),deployStatus:n.deployStatus||"pending",review:n.review||null,metadata:an(n.metadata),codeType:n.codeType||uv[i]||"O"}}function th(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const n=an(e),i=n.name||n.package;return i?{name:i,version:n.version||null,versionRequired:!!(n.versionRequired||n.required),inferred:!!n.inferred,...n.reason?{reason:n.reason}:{}}:null}).filter(Boolean):Object.entries(an(t)).map(([e,n])=>({name:e,version:n||null,inferred:!1})):[]}function nh(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const n=an(e);return!n.from&&!n.to?null:{from:n.from||null,to:n.to||null,type:n.type||"uses",description:n.description||""}}).filter(Boolean):[]}function Fa(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;try{return JSON.parse(e)}catch{const n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(!n)return null;try{return JSON.parse(n[1].trim())}catch{return null}}}function Qi(t,e={}){const n=[],i=typeof t=="string"?Fa(t):t,s=an(i||{});!i&&typeof t=="string"&&n.push("Structured bundle parse failed; using legacy single-artifact fallback.");const o=Array.isArray(s.artifacts)?s.artifacts:[{artifactType:s.artifactType||e.artifactType,artifactName:s.artifactName||e.artifactName,fileName:s.fileName||e.fileName,description:s.description,code:s.code||e.code||(typeof t=="string"?t:""),dependencies:s.dependencies||e.dependencies,relationships:s.relationships||e.relationships}];o.forEach((d,f)=>{!d?.artifactType&&!d?.type&&n.push(`Artifact ${f+1} has no artifactType; it will deploy as a standalone code file under lib/custom_code/ root.`)});const a=o.map((d,f)=>eh(d,f)),l=new Map(o.map((d,f)=>[an(d).id,a[f]?.id]).filter(([d,f])=>d&&f)),u=d=>l.get(d)||d,c=nh(s.relationships||e.relationships).map(d=>({...d,from:d.from?u(d.from):d.from,to:d.to?u(d.to):d.to}));return{schemaVersion:s.schemaVersion||e.schemaVersion||null,id:s.id||e.id||"bundle-current",title:s.title||s.name||e.title||"Generated artifact bundle",description:s.description||e.description||"",artifacts:a,dependencies:th(s.dependencies||e.dependencies),relationships:c,deployOrder:Array.isArray(s.deployOrder)?s.deployOrder.map(u):a.map(d=>d.id),warnings:[...n,...Array.isArray(s.warnings)?s.warnings:[]],metadata:an(s.metadata)}}function oi(t){return Qi(t).artifacts[0]||eh()}function Jt(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function ai(t){return JSON.stringify(t,null,2)}function fv(t){return ai({task:"architect",userRequest:String(t??"")})}function hv(t){const e=Jt(t);return e&&typeof e=="object"&&typeof e.task=="string"?ai(e):ai({task:"generate_bundle",bundleSpec:e})}function pv(t){return ai({task:"review_bundle",generatedBundle:Jt(t),outputRequirements:{bundleReview:["status","score","summary","manualActions","findings"],scoreRange:[0,100],eachArtifact:["id","review.status","review.findings"],manualActions:{definition:"Setup the developer must perform by hand in the FlutterFlow editor that FlutterFlow will NOT do for them.",exclude:["creating the Custom Action, Widget or Code File itself - deploying the code creates it","declaring parameters or return values FlutterFlow derives from the function signature","anything that resolves as a side effect of using the action or widget in the editor","generic advice such as testing, reviewing or rebuilding the app"],preferEmpty:"Return an empty array when nothing qualifies - an empty list is the expected result for most bundles."}}})}function vl(t,e=null){const n={stage:t};return e!=null&&(n.bundle=Jt(e)),n}function gv({bundleSpec:t,artifactBundle:e,bundleReview:n,artifactId:i,userFeedback:r}){return ai({task:"regenerate_artifact",artifactId:i,bundleSpec:Jt(t),artifactBundle:Jt(e),bundleReview:Jt(n),userFeedback:String(r)})}function ih({bundleSpec:t,artifactBundle:e,bundleReview:n,userFeedback:i}){return ai({task:"regenerate_bundle",bundleSpec:Jt(t),artifactBundle:Jt(e),bundleReview:Jt(n),userFeedback:String(i??"")})}const Su={csam:"child-safety content",dangerous:"dangerous content",harassment:"harassment",hate_speech:"hate speech",maliciousUrls:"a potentially malicious URL",malicious_uris:"a potentially malicious URL",pi_and_jailbreak:"prompt-injection or jailbreak instructions",promptInjection:"prompt-injection or jailbreak instructions",rai:"restricted content",sdp:"sensitive personal data",sexually_explicit:"sexually explicit content",virus_scan:"potentially malicious file content"},mv=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function et(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function vv(t){return et(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||et(t.filterSummary)||et(t.filterResults):!1}function rh(t,e=0){if(!et(t)||e>3)return null;if(vv(t))return t;for(const n of mv){const i=t[n];if(et(i)){const r=rh(i,e+1);if(r)return r}}return null}function us(t){return Array.isArray(t)?t.some(us):et(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(us):!1}function Ra(t){return Array.isArray(t)?t.some(Ra):et(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(Ra):!1}function sh(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function _v(t,e){if(et(t))for(const[n,i]of Object.entries(t)){if(!et(i))continue;const r=et(i.categories)?i.categories:{},s=Object.entries(r).filter(([,o])=>et(o)&&o.matched===!0).map(([o])=>o);s.length>0?s.forEach(o=>e.add(o)):i.matched===!0&&e.add(sh(n))}}function yv(t,e){if(!t)return;const n=Array.isArray(t)?t.flatMap(i=>et(i)?Object.entries(i):[]):Object.entries(t);for(const[i,r]of n){if(!us(r))continue;const s=sh(i),o=r?.raiFilterResult?.raiFilterTypeResults||(s==="rai"?r?.raiFilterTypeResults:null),a=et(o)?Object.entries(o).filter(([,l])=>us(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(s)}}function wv(t){return Su[t]?Su[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function xu(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 bv(t){const e=rh(t);if(!e)return null;const n=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);_v(e.filterSummary,n),yv(e.filterResults,n);const i=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||n.size>0,r=e.invocationResult||null,s=Ra(e.filterSummary||e.filterResults);return!i&&!s&&!["PARTIAL","FAILURE"].includes(r)?null:{kind:i?"blocked":"unavailable",invocationResult:r,matchedFilters:[...n]}}function Ev(t,e){const n=bv(t);if(!n)return null;const i=[...new Set(n.matchedFilters.map(wv))],r=n.kind==="blocked",s=new Error(r?`Safety screening blocked this pipeline step for ${xu(i)}.`:"Safety screening could not be completed. Please try again.");return s.name="ModelArmorError",s.code=r?"MODEL_ARMOR_BLOCKED":"MODEL_ARMOR_UNAVAILABLE",s.isModelArmor=!0,s.pipelineStep=e,s.userTitle=r?"Request blocked for safety":"Safety check unavailable",s.userMessage=r?`The safety check detected ${xu(i)}. Edit your request to remove or rephrase the flagged content, then run the pipeline again.`:"The safety service did not finish all of its checks. Please wait a moment and run the pipeline again.",s.retryExplanation=r?"Trying another model would not change this safety decision.":"A fallback model was not attempted because safety screening must complete first.",s.matchedFilters=n.matchedFilters,s}function Sv(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function Iu(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,n=[];for(const i of Sv(t).split(` -`)){if(!/^[A-Za-z_$]/.test(i)||e.test(i))continue;const r=i.match(/^[\w$<>,?\s[\]]+?\s([a-zA-Z_$][\w$]*)\s*\(/);r&&n.push(r[1])}return n}function _l(t,e){const n=t.replace(/\.dart$/,"");if(e==="W")return n.replace(/(^|_)(\w)/g,(i,r,s)=>s.toUpperCase());if(e==="A"){const i=n.replace(/(^|_)(\w)/g,(r,s,o)=>o.toUpperCase());return i.charAt(0).toLowerCase()+i.slice(1)}return e==="F"?"CustomFunctions":e==="C"?t.endsWith(".dart")?t:`${t}.dart`:n}async function ku(t){const e=new TextEncoder().encode(String(t||"")),n=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n),i=>i.toString(16).padStart(2,"0")).join("")}async function xv(t,e=new Map){const n={},i=new Set;for(const[o,a]of t.entries()){if(a.type==="D"||a.type==="O")continue;const l=_l(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await ku(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await ku(c)),n[o]=u,a.type==="F"){const d=Iu(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(h=>i.add(h))}}const r=new Set(Iu(e.get("lib/flutter_flow/custom_functions.dart")||"")),s={functions_to_rename:[],functions_to_delete:[],functions_to_add:Array.from(i).filter(o=>!r.has(o))};return{fileMapContents:JSON.stringify(n),functionsMapContents:JSON.stringify(s)}}const Iv=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),Cu={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},kv=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),Cv=["Struct","Record"],Av=[{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=>Uo(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=>Uo(t).some(e=>{const n=/^\s*final\s+(?:double|int|String|bool|Color|num)\s+(\w+)\s*;/gm;let i;for(;(i=n.exec(e))!==null;){const r=i[1];if(!(new RegExp(`this\\.${r}\\s*=(?!=)`).test(e)||new RegExp(`[:,]\\s*${r}\\s*=(?!=)`).test(e)))return!0}return!1}),pos:`class W extends StatefulWidget { +(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const s of r)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function n(r){const s={};return r.integrity&&(s.integrity=r.integrity),r.referrerPolicy&&(s.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?s.credentials="include":r.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function i(r){if(r.ep)return;r.ep=!0;const s=n(r);fetch(r.href,s)}})();var w=typeof window<"u"?window:void 0,Le=typeof globalThis<"u"?globalThis:w,Ue=Le?.navigator,F=Le?.document,me=Le?.location,Za=Le?.fetch,qo=Le!=null&&Le.XMLHttpRequest&&"withCredentials"in new Le.XMLHttpRequest?Le.XMLHttpRequest:void 0,uc=Le?.AbortController,Fp=Le?.CompressionStream,Ve=Ue?.userAgent;function cd(){return!(!w||w.navigator.onLine===!1)}var vi=typeof globalThis<"u"?globalThis:w;vi&&typeof self>"u"&&(vi.self=vi),vi&&typeof File>"u"&&(vi.File=function(){});var B=w??{},ne={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function dc(t,e,n,i,r,s,o){try{var a=t[s](o),l=a.value}catch(u){return void n(u)}a.done?e(l):Promise.resolve(l).then(i,r)}function se(t){return function(){var e=this,n=arguments;return new Promise((function(i,r){var s=t.apply(e,n);function o(l){dc(s,i,r,o,a,"next",l)}function a(l){dc(s,i,r,o,a,"throw",l)}o(void 0)}))}}function k(){return k=Object.assign?Object.assign.bind():function(t){for(var e=1;arguments.length>e;e++){var n=arguments[e];for(var i in n)({}).hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},k.apply(null,arguments)}function ud(t,e){if(t==null)return{};var n={};for(var i in t)if({}.hasOwnProperty.call(t,i)){if(e.indexOf(i)!==-1)continue;n[i]=t[i]}return n}var fc=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function hc(t){return typeof t=="string"||t}function pc(t){return typeof t=="string"?t:void 0}var _i,Rp=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],jt=(function(t){return t.AnonymousId="anonymous_id",t.DistinctId="distinct_id",t.Props="props",t.EnablePersonProcessing="enable_person_processing",t.PersonMode="person_mode",t.FeatureFlagDetails="feature_flag_details",t.FeatureFlags="feature_flags",t.FeatureFlagPayloads="feature_flag_payloads",t.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",t.BootstrapFeatureFlags="bootstrap_feature_flags",t.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",t.OverrideFeatureFlags="override_feature_flags",t.Queue="queue",t.AiQueue="ai_queue",t.LogsQueue="logs_queue",t.OptedOut="opted_out",t.SessionId="session_id",t.SessionStartTimestamp="session_start_timestamp",t.SessionLastTimestamp="session_timestamp",t.PersonProperties="person_properties",t.GroupProperties="group_properties",t.InstalledAppBuild="installed_app_build",t.InstalledAppVersion="installed_app_version",t.SessionReplay="session_replay",t.PushRegistered="push_registered",t.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",t.SurveyLastSeenDate="survey_last_seen_date",t.SurveysSeen="surveys_seen",t.Surveys="surveys",t.RemoteConfig="remote_config",t.FlagsEndpointWasHit="flags_endpoint_was_hit",t.DeviceId="device_id",t})({}),gc=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),Tp=["$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"],$p=["token"],dd="NativeGzipValidationError",zo=t=>t.length>=2&&t[0]===31&&t[1]===139,mc=(t,e)=>t===gc.GZipJS||e===gc.GZipJS||e==="gzip",vc=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",pr=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=dd,e},Mp=(function(){var t=se((function*(e,n){18>e.size&&pr("too-short");var i=new Uint8Array(yield e.slice(0,10).arrayBuffer());zo(i)&&i[2]===8||pr("invalid-header");var r=new DataView(yield e.slice(e.size-8).arrayBuffer());r.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(_i)return _i;_i=[];for(var c=0;256>c;c++){for(var d=c,f=0;8>f;f++)d=1&d?3988292384^d>>>1:d>>>1;_i[c]=d>>>0}return _i})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(n)&&pr("invalid-crc");var s=n.length>>>0;r.getUint32(4,!0)!==s&&pr("invalid-size")}));return function(e,n){return t.apply(this,arguments)}})();function Vo(){return Vo=se((function*(t,e,n){e===void 0&&(e=!0);try{var i=new TextEncoder().encode(t),r=new globalThis.CompressionStream("gzip"),s=r.writable.getWriter(),o=s.write(i).then((()=>s.close())).catch((function(){var u=se((function*(c){try{yield s.abort(c)}catch{}throw c}));return function(c){return u.apply(this,arguments)}})()),a=new Response(r.readable).blob(),l=(yield Promise.all([a,o]))[0];return yield Mp(l,i),l}catch(u){if(n!=null&&n.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),Vo.apply(this,arguments)}var Lp=["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"],_c=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var n=t.toLowerCase();return Lp.concat(e).some((i=>{var r=i.toLowerCase();return n.indexOf(r)!==-1}))};function j(t,e){return t.indexOf(e)!==-1}var xs=function(t){return t.trim()},Go=function(t){return t.replace(/^\$/,"")};function fd(t){var e,n=[];return(e=JSON.stringify(t,(function(i,r){if(typeof r=="bigint")return r.toString();if(typeof r!="function"&&typeof r!="symbol"){if(r instanceof Error)return{name:r.name,message:r.message,stack:r.stack};if(r&&typeof r=="object"){for(;n.length>0&&n[n.length-1]!==this;)n.pop();if(n.includes(r))return"[Circular]";n.push(r)}return r}})))!==null&&e!==void 0?e:"null"}var hd=Object.prototype,pd=hd.hasOwnProperty,Is=hd.toString,U=Array.isArray||function(t){return Is.call(t)==="[object Array]"},De=t=>typeof t=="function",he=t=>t===Object(t)&&!U(t),Gt=t=>{if(he(t)){for(var e in t)if(pd.call(t,e))return!1;return!0}return!1},C=t=>t===void 0,X=t=>Is.call(t)=="[object String]",Ko=t=>X(t)&&t.trim().length===0,Ke=t=>t===null,H=t=>C(t)||Ke(t),ke=t=>Is.call(t)=="[object Number]"&&t==t,Bt=t=>ke(t)&&t>0,gt=t=>Is.call(t)==="[object Boolean]",Np=t=>t instanceof FormData,Op=t=>j(Tp,t),Bp=t=>j($p,t);function gd(t){return t===null||typeof t!="object"}function Hr(t,e){return{}.toString.call(t)==="[object "+e+"]"}function Xa(t){return typeof Event<"u"&&md(t,Event)}function md(t,e){try{return t instanceof e}catch{return!1}}var Dp=[!0,"true",1,"1","yes"],uo=t=>j(Dp,t),jp=[!1,"false",0,"0","no"];function Ct(t,e,n,i,r){return e>n&&(i.warn("min cannot be greater than max."),e=n),ke(t)?t>n?(i.warn(" cannot be greater than max: "+n+". Using max value instead."),n):e>t?(i.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(i.warn(" must be a number. using max or fallback. max: "+n+", fallback: "+r),Ct(r||n,e,n,i))}class Up{constructor(e){this.tt={},this.et=e.et,this.it=Ct(e.bucketSize,0,100,e.rt),this.nt=Ct(e.refillRate,0,this.it,e.rt),this.st=Ct(e.refillInterval,0,864e5,e.rt)}ot(e,n){var i=Math.floor((n-e.lastAccess)/this.st);i>0&&(e.tokens=Math.min(e.tokens+i*this.nt,this.it),e.lastAccess=e.lastAccess+i*this.st)}consumeRateLimit(e){var n,i=Date.now(),r=String(e),s=this.tt[r];return s?this.ot(s,i):this.tt[r]=s={tokens:this.it,lastAccess:i},s.tokens===0||(s.tokens--,s.tokens===0&&((n=this.et)==null||n.call(this,e)),s.tokens===0)}stop(){this.tt={}}}var it="Mobile",Wr="iOS",Kt="Android",ei="Tablet",vd=Kt+" "+ei,_d="iPad",yd="Apple",wd=yd+" Watch",Bi="Safari",ti="BlackBerry",bd="Samsung",Ed=bd+"Browser",Sd=bd+" Internet",Pn="Chrome",Hp=Pn+" OS",xd=Pn+" "+Wr,Qa="Internet Explorer",Id=Qa+" "+it,el="Opera",Wp=el+" Mini",tl="Edge",kd="Microsoft "+tl,Zn="Firefox",Cd=Zn+" "+Wr,Gi="Nintendo",Ki="PlayStation",Xn="Xbox",Ad=Kt+" "+it,Pd=it+" "+Bi,Pi="Windows",Yo=Pi+" Phone",yc="Nokia",Jo="Ouya",Fd="Generic",qp=Fd+" "+it.toLowerCase(),Rd=Fd+" "+ei.toLowerCase(),Zo="Konqueror",Td="Oculus Browser",qr="Vivaldi",$d="Yandex",zr="Whale",Xo="DuckDuckGo",Md="Pale Moon",Vr="Waterfox",Di="Brave",Ld="Google Search App",we="(\\d+(\\.\\d+)?)",fo=new RegExp("Version/"+we),zp=new RegExp(Xn,"i"),Vp=new RegExp(Ki+" \\w+","i"),Gp=new RegExp(Gi+" \\w+","i"),nl=new RegExp(ti+"|PlayBook|BB10","i"),Kp={"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"},Nd=function(t,e,n,i){e=e||"";var r=(function(s){return s!=null&&s.brave?Di:null})(n);return r||(i!=null&&i.detectGoogleSearchApp&&j(t,"GSA/")?Ld:j(t," OPR/")&&j(t,"Mini")?Wp:j(t," OPR/")?el:nl.test(t)?ti:j(t,"IE"+it)||j(t,"WPDesktop")?Id:j(t,"OculusBrowser")?Td:j(t,Ed)?Sd:j(t,tl)||j(t,"Edg/")?kd:j(t,qr+"/")?qr:j(t,"YaBrowser/")?$d:j(t,zr+"/")?zr:j(t,Xo+"/")||j(t,"Ddg/")?Xo:j(t,"FBIOS")?"Facebook "+it:j(t,"UCWEB")||j(t,"UCBrowser")?"UC Browser":j(t,"CriOS")?xd:j(t,"CrMo")||j(t,Pn)?Pn:j(t,Kt)&&j(t,Bi)?Ad:j(t,"FxiOS")?Cd:j(t.toLowerCase(),Zo.toLowerCase())?Zo:j(t,Di+"/")?Di:((s,o)=>o&&j(o,yd)||(function(a){return j(a,Bi)&&!j(a,Pn)&&!j(a,Kt)})(s))(t,e)?j(t,it)?Pd:Bi:j(t,"PaleMoon/")?Md:j(t,Vr+"/")?Vr:j(t,Zn)?Zn:j(t,"MSIE")||j(t,"Trident/")?Qa:j(t,"Gecko")?Zn:"")},Yp={[Id]:[new RegExp("rv:"+we)],[kd]:[new RegExp(tl+"?\\/"+we)],[Pn]:[new RegExp("("+Pn+"|CrMo)\\/"+we)],[xd]:[new RegExp("CriOS\\/"+we)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+we)],[Bi]:[fo],[Pd]:[fo],[el]:[new RegExp("(Opera|OPR)\\/"+we)],[Zn]:[new RegExp(Zn+"\\/"+we)],[Cd]:[new RegExp("FxiOS\\/"+we)],[Zo]:[new RegExp("Konqueror[:/]?"+we,"i")],[ti]:[new RegExp(ti+" "+we),fo],[Ad]:[new RegExp("android\\s"+we,"i")],[Sd]:[new RegExp(Ed+"\\/"+we)],[Td]:[new RegExp("OculusBrowser\\/"+we)],[qr]:[new RegExp(qr+"\\/"+we)],[$d]:[new RegExp("YaBrowser\\/"+we)],[zr]:[new RegExp(zr+"\\/"+we)],[Di]:[new RegExp(Di+"\\/"+we)],[Xo]:[new RegExp("(DuckDuckGo|Ddg)\\/"+we)],[Md]:[new RegExp("PaleMoon\\/"+we)],[Vr]:[new RegExp(Vr+"\\/"+we)],[Ld]:[new RegExp("GSA\\/"+we)],[Qa]:[new RegExp("(rv:|MSIE )"+we)],Mozilla:[new RegExp("rv:"+we)]},Jp=function(t,e,n,i){var r=Nd(t,e,n,i),s=Yp[r];if(C(s))return null;for(var o=0;s.length>o;o++){var a=t.match(s[o]);if(a)return parseFloat(a[a.length-2])}return null},wc=[[new RegExp(Xn+"; "+Xn+" (.*?)[);]","i"),t=>[Xn,t&&t[1]||""]],[new RegExp(Gi,"i"),[Gi,""]],[new RegExp(Ki,"i"),[Ki,""]],[nl,[ti,""]],[new RegExp(Pi,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Yo,""];if(new RegExp(it).test(e)&&!/IEMobile\b/.test(e))return[Pi+" "+it,""];var n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){var i=Kp[n[1]]||"";return/arm/i.test(e)&&(i="RT"),[Pi,i]}return[Pi,""]}],[/((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=C(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+Kt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Kt+")","i"),t=>t&&t[2]?[Kt,[t[2],t[3],t[4]||"0"].join(".")]:[Kt,""]],[/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/,[Hp,""]],[/Linux|debian/i,["Linux",""]]],bc=function(t){return Gp.test(t)?Gi:Vp.test(t)?Ki:zp.test(t)?Xn:new RegExp(Jo,"i").test(t)?Jo:new RegExp("("+Yo+"|WPDesktop)","i").test(t)?Yo:/iPad/.test(t)?_d:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?wd:nl.test(t)?ti:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(yc,"i").test(t)?yc:/(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(it).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)?Kt:vd:new RegExp("(pda|"+it+")","i").test(t)?qp:new RegExp(ei,"i").test(t)&&!new RegExp(ei+" pc","i").test(t)?Rd:""},Zp=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ec(t,e){return typeof(n=t)=="string"&&Zp.test(n)?t:e();var n}function fn(t){return t&&t.split("#")[0]}function il(t,e){var n=setTimeout(t,e);return n?.unref&&n?.unref(),n}function Sc(t,e,n){return Od.apply(this,arguments)}function Od(){return(Od=se((function*(t,e,n){var i;try{return yield Promise.race([t,new Promise(((r,s)=>{i=il((()=>{try{n?.(),r()}catch(o){s(o)}}),e)}))])}finally{clearTimeout(i)}}))).apply(this,arguments)}var Xp=t=>t instanceof Error,Bd={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},Qp=Bd.info;function Dd(t){if(gt(t))return{boolValue:t};if(typeof t=="number")return Number.isFinite(t)?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:{stringValue:String(t)};if(typeof t=="string")return{stringValue:t};if(U(t))return{arrayValue:{values:t.map((e=>Dd(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function Gr(t){var e=[];for(var n in t){var i=t[n];Ke(i)||C(i)||e.push({key:n,value:Dd(i)})}return e}function eg(t,e){var n=Bd[t.level||"info"]||Qp,i=n.text,r=n.number,s=String(Date.now())+"000000",o={};e.distinctId&&(o.posthogDistinctId=e.distinctId),e.sessionId&&(o.sessionId=e.sessionId),e.windowId&&(o["window.id"]=e.windowId),H(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),H(e.lastActivityTimestamp)||(o.lastActivityTimestamp=String(e.lastActivityTimestamp)),e.currentUrl&&(o["url.full"]=e.currentUrl),e.screenName&&(o["screen.name"]=e.screenName),e.appState&&(o["app.state"]=e.appState),e.activeFeatureFlags&&e.activeFeatureFlags.length>0&&(o.feature_flags=e.activeFeatureFlags);var a=k({},o,t.attributes||{}),l={timeUnixNano:s,observedTimeUnixNano:s,severityNumber:r,severityText:i,body:{stringValue:t.body},attributes:Gr(a)};return t.trace_id&&(l.traceId=t.trace_id),t.span_id&&(l.spanId=t.span_id),C(t.trace_flags)||(l.flags=t.trace_flags),l}function jd(t,e,n){return k({},t.resourceAttributes,{"service.name":t.serviceName||"unknown_service"},t.environment&&{"deployment.environment":t.environment},t.serviceVersion&&{"service.version":t.serviceVersion},{"telemetry.sdk.name":e,"telemetry.sdk.version":n})}function Ud(t,e,n,i){return{resourceLogs:[{resource:{attributes:Gr(e)},scopeLogs:[{scope:{name:n,version:i},logRecords:t}]}]}}let tg=class{constructor(t,e,n,i,r,s,o){var a;s===void 0&&(s=()=>Promise.resolve()),this._instance=t,this.Ne=e,this.rt=n,this.ut=i,this.ht=r,this.dt=s,this.vt=o,this.ct=null,this.ft=0,this.yt=0,this.bt=0,this._t=0,this.wt=!1,this.kt=e.maxBufferSize,this.xt=Math.max((a=e.maxQueueSize)!==null&&a!==void 0?a:e.maxBufferSize,e.maxBufferSize),this.St=e.flushIntervalMs,this.Ct=e.maxBatchRecordsPerPost,this.Mt=e.rateCapWindowMs,this.Tt=e.maxLogsPerInterval}reset(){this.Et(),this.ct=null,this.bt=0,this._t=0,this.wt=!1,this.ft=0,this.yt=0,this.Ct=this.Ne.maxBatchRecordsPerPost}onReconnect(){this.yt=0,this.It()}captureLog(t){if(!this._instance.isDisabled&&!this._instance.optedOut&&t!=null&&t.body){var e=this.Pt(t);if(e!==null)if(e.body){if(this.Rt()){var n={record:eg(e,this.ut())};this.ht((()=>this.At(n)))}}else this.rt.info("Log was rejected in beforeSend function")}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Log was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for log:",o),null}return i}Rt(){if(this.Tt===void 0)return!0;var t=Date.now(),e=t-this.bt;return this.Mt>e&&e>=0||(this.bt=t,this._t=0,this.wt=!1),this.Tt>this._t?(this._t++,!0):(this.wt||(this.rt.warn("captureLog dropping logs: exceeded "+this.Tt+" logs per "+this.Mt+"ms"),this.wt=!0),!1)}flush(){var t=this;return se((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return se((function*(){var e;t.Et();var n=(e=t._instance.getPersistedProperty(jt.LogsQueue))!==null&&e!==void 0?e:[];if(n.length!==0)for(var i=n.length,r=0;n.length>0&&i>r;){var s,o;t.ft=0;var a=Math.min(n.length,t.Ct),l=n.slice(0,a),u=Ud(l.map((d=>d.record)),t.Lt(),(s=t.vt)!==null&&s!==void 0?s:t._instance.getLibraryId(),t._instance.getLibraryVersion()),c=yield t._instance.Ot(u);if(c.kind==="too-large"&&l.length>1)t.Ct=Math.max(1,Math.floor(l.length/2)),t.rt.warn("Received 413 when sending logs batch of size "+l.length+", reducing batch size to "+t.Ct);else if(c.kind==="retry-later"||(c.kind==="too-large"?t.rt.warn("Dropping a single log record after 413 with batch size 1 — the record is larger than the server cap and cannot be split further."):c.kind==="ok"&&t.Ne.maxBatchRecordsPerPost>t.Ct&&(t.Ct=Math.min(t.Ne.maxBatchRecordsPerPost,t.Ct+1)),yield t.Dt(l.length),n=(o=t._instance.getPersistedProperty(jt.LogsQueue))!==null&&o!==void 0?o:[],r+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return se((function*(){var n,i=Math.max(0,t-e.ft),r=(n=e._instance.getPersistedProperty(jt.LogsQueue))!==null&&n!==void 0?n:[];e._instance.setPersistedProperty(jt.LogsQueue,r.slice(i)),yield e.dt()}))()}Lt(){return jd(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var n=(e=this._instance.getPersistedProperty(jt.LogsQueue))!==null&&e!==void 0?e:[];this.xt>n.length||(n.shift(),this.ft++,this.rt.info("Logs queue is full, dropping oldest record.")),n.push(t),this._instance.setPersistedProperty(jt.LogsQueue,n),this.kt>n.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=il((()=>{this.Nt=void 0,this.It()}),t))}qt(){var t=Math.min(Math.max(0,this.yt-1),6);return this.St*Math.pow(2,t)}jt(){var t=this._instance.getPersistedProperty(jt.LogsQueue);return!!t&&t.length>0}shutdown(t){var e=this;return se((function*(){e.Et();var n=e.flush().catch((()=>{}));t!==void 0?yield Sc(n,t):yield n}))()}flushWithTimeout(t){var e=this;return se((function*(){var n=e.flush();yield Sc(n,t,(()=>{n.catch((()=>{}))}))}))()}It(){this.flush().then((()=>{this.yt=0}),(t=>{this.yt++,this.rt.error("PostHog logs flush failed:",t)})).finally((()=>{!this._instance.isDisabled&&this.jt()&&this.$t(this.qt())}))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}};var ho=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function xc(t){return String(t)+"000000"}function Ic(t,e,n,i){var r="";return i&&(r=Object.keys(i).sort().map((s=>JSON.stringify(s)+":"+JSON.stringify(i[s]))).join(",")),t+"\0"+e+"\0"+(n??"")+"\0"+r}let ng=class{constructor(t,e,n){this._instance=t,this.Ne=e,this.rt=n,this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Wt=0}count(t,e,n){e===void 0&&(e=1),this.Vt({name:t,type:"count",value:e,unit:n?.unit,attributes:n?.attributes})}gauge(t,e,n){this.Vt({name:t,type:"gauge",value:e,unit:n?.unit,attributes:n?.attributes})}histogram(t,e,n){this.Vt({name:t,type:"histogram",value:e,unit:n?.unit,attributes:n?.attributes})}flush(){var t=this,e=this.ct,n=(function(){var r=se((function*(){e&&(yield e.catch((()=>{}))),yield t.Zt()}));return function(){return r.apply(this,arguments)}})(),i=n().finally((()=>{this.ct===i&&(this.ct=null)}));return this.ct=i,i}drainWindow(){if(this.Bt.size===0)return null;var t=this.Bt;return this.Bt=new Map,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Gt(t)}reset(){this.Wt++,this.Et(),this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set}Vt(t){if(!this._instance.isDisabled&&!this._instance.optedOut){var e=this.Pt(t);if(e!==null)if(e.name&&typeof e.name=="string")if(typeof e.value=="number"&&Number.isFinite(e.value))if(e.type==="count"&&0>e.value)this.rt.warn("Dropping count '"+e.name+"': counters are monotonic, value must be >= 0");else{var n,i;try{n=e.attributes?k({},e.attributes):void 0,i=Ic(e.type,e.name,e.unit,n)}catch(o){return void this.rt.warn("Dropping metric '"+e.name+"': attributes could not be serialized",o)}var r=this.Bt.get(i);if(!r){if(!this.Qt())return;r={name:e.name,type:e.type,unit:e.unit,attributes:n,windowStartMs:Date.now()},this.Bt.set(i,r)}var s=this.Ut.get(e.name);s===void 0?this.Ut.set(e.name,e.type):s===e.type||this.zt.has(e.name)||(this.zt.add(e.name),this.rt.warn("Metric name '"+e.name+"' is already used as a "+s+"; recording it as a "+e.type+" too will blend both series in charts. Use a distinct name.")),this.Kt(r,e.value),this.$t()}else this.rt.warn("Dropping metric '"+e.name+"': value must be a finite number");else this.rt.warn("Dropping metric with empty name")}}Qt(){return this.Ne.maxSeriesPerFlush>this.Bt.size||(this.Ht||(this.Ht=!0,this.rt.warn("Metric series cap reached ("+this.Ne.maxSeriesPerFlush+" per flush window); dropping new series until the next flush. Reduce attribute cardinality.")),!1)}Kt(t,e){var n;switch(t.type){case"count":t.total=((n=t.total)!==null&&n!==void 0?n:0)+e;break;case"gauge":t.last=e;break;case"histogram":t.hist||(t.hist={count:0,sum:0,min:e,max:e,bucketCounts:new Array(ho.length+1).fill(0)});var i=t.hist;i.count+=1,i.sum+=e,i.min=Math.min(i.min,e),i.max=Math.max(i.max,e),i.bucketCounts[(function(r,s){for(var o=0;s.length>o;o++)if(s[o]>=r)return o;return s.length})(e,ho)]+=1}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Metric was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for metric:",o),null}return i}$t(){this.Nt||(this.Nt=il((()=>{this.Nt=void 0,this.flush().catch((t=>{this.rt.error("Metrics flush failed:",t)}))}),this.Ne.flushIntervalMs))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}Zt(){var t=this;return se((function*(){if(t.Bt.size!==0){var e=t.Bt;t.Bt=new Map,t.Ht=!1,t.Ut=new Map,t.zt=new Set;var n=t.Wt,i=yield t._instance.Jt(t.Gt(e));if(n===t.Wt)switch(i.kind){case"ok":return;case"retry-later":return t.Yt(e),void t.$t();case"too-large":return void t.rt.warn("Metrics batch exceeded the server size limit and was dropped");case"fatal":return void t.rt.error("Failed to send metrics batch:",i.error)}}}))()}Gt(t){return e=this.Xt(t),n=(function(s,o,a){return k({},s.resourceAttributes,{"service.name":s.serviceName||"unknown_service"},s.environment&&{"deployment.environment":s.environment},s.serviceVersion&&{"service.version":s.serviceVersion},{"telemetry.sdk.name":o,"telemetry.sdk.version":a})})(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion()),i=this._instance.getLibraryId(),r=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:Gr(n)},scopeMetrics:[{scope:{name:i,version:r},metrics:e}]}]};var e,n,i,r}Xt(t){var e=xc(Date.now()),n=new Map;for(var i of t.values()){var r,s=Ic(i.type,i.name,i.unit,void 0),o=n.get(s);o||(o=k({name:i.name},i.unit&&{unit:i.unit}),i.type==="count"?o.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:i.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:1,dataPoints:[]},n.set(s,o));var a=Gr((r=i.attributes)!==null&&r!==void 0?r:{}),l=xc(i.windowStartMs);if(i.type==="count"){var u,c={attributes:a,startTimeUnixNano:l,timeUnixNano:e,asDouble:(u=i.total)!==null&&u!==void 0?u:0};o.sum.dataPoints.push(c)}else if(i.type==="gauge"){var d,f={attributes:a,timeUnixNano:e,asDouble:(d=i.last)!==null&&d!==void 0?d:0};o.gauge.dataPoints.push(f)}else i.hist&&o.histogram.dataPoints.push({attributes:a,startTimeUnixNano:l,timeUnixNano:e,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:ho})}return Array.from(n.values())}Yt(t){var e,n;for(var i of t){var r=i[0],s=i[1],o=this.Bt.get(r);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,s.windowStartMs),o.type){case"count":o.total=((e=o.total)!==null&&e!==void 0?e:0)+((n=s.total)!==null&&n!==void 0?n:0);break;case"gauge":break;case"histogram":if(s.hist)if(o.hist){o.hist.count+=s.hist.count,o.hist.sum+=s.hist.sum,o.hist.min=Math.min(o.hist.min,s.hist.min),o.hist.max=Math.max(o.hist.max,s.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=s.hist.bucketCounts[a]}else o.hist=s.hist}else this.Qt()&&this.Bt.set(r,s)}}};var gr,kc,po;function ig(t){var e=globalThis._posthogChunkIds;if(e){var n=Object.keys(e);return po&&n.length===kc||(kc=n.length,po=n.reduce(((i,r)=>{gr||(gr={});var s=gr[r];if(s)i[s[0]]=s[1];else for(var o=t(r),a=o.length-1;a>=0;a--){var l=o[a],u=l?.filename,c=e[r];if(u&&c){i[u]=c,gr[r]=[u,c];break}}return i}),{})),po}}class rg{constructor(e,n,i){i===void 0&&(i=[]),this.coercers=e,this.stackParser=n,this.modifiers=i}buildFromUnknown(e,n){n===void 0&&(n={});var i=n&&n.mechanism||{handled:!0,type:"generic"},r=this.buildCoercingContext(i,n,0).apply(e),s=this.buildParsingContext(n),o=this.parseStacktrace(r,s);return{$exception_list:this.convertToExceptionList(o,i),$exception_level:"error"}}modifyFrames(e){var n=this;return se((function*(){for(var i of e)i.stacktrace&&i.stacktrace.frames&&U(i.stacktrace.frames)&&(i.stacktrace.frames=yield n.applyModifiers(i.stacktrace.frames));return e}))()}coerceFallback(e){var n;return{type:"Error",value:"Unknown error",stack:(n=e.syntheticException)==null?void 0:n.stack,synthetic:!0}}parseStacktrace(e,n){var i,r;return e.cause!=null&&(i=this.parseStacktrace(e.cause,n)),e.stack!=""&&e.stack!=null&&(r=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?n.skipFirstLines:0),n.chunkIdMap)),k({},e,{cause:i,stack:r})}applyChunkIds(e,n){return e.map((i=>(i.filename&&n&&(i.chunk_id=n[i.filename]),i)))}applyCoercers(e,n){for(var i of this.coercers)if(i.match(e))return i.coerce(e,n);return this.coerceFallback(n)}applyModifiers(e){var n=this;return se((function*(){var i=e;for(var r of n.modifiers)i=yield r(i);return i}))()}convertToExceptionList(e,n){var i,r,s,o={type:e.type,value:e.value,mechanism:{type:(i=n.type)!==null&&i!==void 0?i:"generic",handled:(r=n.handled)===null||r===void 0||r,synthetic:(s=e.synthetic)!==null&&s!==void 0&&s}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,k({},n,{handled:!0}))),a}buildParsingContext(e){var n;return{chunkIdMap:ig(this.stackParser),skipFirstLines:(n=e.skipFirstLines)!==null&&n!==void 0?n:1}}buildCoercingContext(e,n,i){i===void 0&&(i=0);var r=(s,o)=>{if(4>=o){var a=this.buildCoercingContext(e,n,o);return this.applyCoercers(s,a)}};return k({},n,{syntheticException:i==0?n.syntheticException:void 0,mechanism:e,apply:s=>r(s,i),next:s=>r(s,i+1)})}}var ni="?";function Qo(t,e,n,i,r){var s={platform:t,filename:e,function:n===""?ni:n,in_app:!0};return C(i)||(s.lineno=i),C(r)||(s.colno=r),s}var Hd=(t,e)=>{var n=t.indexOf("safari-extension")!==-1,i=t.indexOf("safari-web-extension")!==-1;return n||i?[t.indexOf("@")!==-1?t.split("@")[0]:ni,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},sg=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,og=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,ag=/\((\S*)(?::(\d+))(?::(\d+))\)/,lg=(t,e)=>{var n=sg.exec(t);if(n)return Qo(e,n[1],ni,+n[2],+n[3]);var i=og.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var r=ag.exec(i[2]);r&&(i[2]=r[1],i[3]=r[2],i[4]=r[3])}var s=Hd(i[1]||ni,i[2]);return Qo(e,s[1],s[0],i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},cg=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,ug=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,dg=(t,e)=>{var n=cg.exec(t);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){var i=ug.exec(n[3]);i&&(n[1]=n[1]||"eval",n[3]=i[1],n[4]=i[2],n[5]="")}var r=n[3],s=n[1]||ni,o=Hd(s,r);return Qo(e,r=o[1],s=o[0],n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},Cc=/\(error: (.*)\)/;class fg{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,n){var i=X(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:i?e.stack:void 0,cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var n=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?n+": "+e.message:n}isDOMException(e){return Hr(e,"DOMException")}isDOMError(e){return Hr(e,"DOMError")}}class hg{match(e){return(function(n){switch({}.toString.call(n)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return md(n,Error)}})(e)}coerce(e,n){return{type:this.getType(e),value:this.getMessage(e,n),stack:this.getStack(e),cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,n){var i=e.message;return String(i.error&&typeof i.error.message=="string"?i.error.message:i)}getStack(e){return e.stacktrace||e.stack||void 0}}class pg{constructor(){}match(e){return!!Hr(e,"ErrorEvent")&&(e.error!=null||this.fe(e))}coerce(e,n){var i;if(e.error!=null)return n.apply(e.error);var r=n.apply(e.message);return k({},r,{stack:(i=this.pe(e))!==null&&i!==void 0?i:r.stack,synthetic:!0})}fe(e){return X(e.message)&&e.message.length>0}pe(e){var n=e;if(X(n.filename)&&n.filename.length>0){var i,r,s=(i=n.lineno)!==null&&i!==void 0?i:0,o=(r=n.colno)!==null&&r!==void 0?r:0;return`Error + at `+n.filename+":"+s+":"+o}}}var gg=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class mg{match(e){return typeof e=="string"}coerce(e,n){var i,r=this.getInfos(e),s=r[0],o=r[1];return{type:s??"Error",value:o??e,stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}getInfos(e){var n="Error",i=e,r=e.match(gg);return r&&(n=r[1],i=r[2]),[n,i]}}var vg=["fatal","error","warning","log","info","debug"];function Wd(t,e){e===void 0&&(e=40);var n=Object.keys(t);if(n.sort(),!n.length)return"[object has no keys]";for(var i=n.length;i>0;i--){var r=n.slice(0,i).join(", ");if(e>=r.length)return i===n.length?r:r.length>e?r.slice(0,e)+"...":r}return""}class _g{match(e){return typeof e=="object"&&e!==null}coerce(e,n){var i,r,s=this.getErrorPropertyFromObject(e);return s?n.apply(s):{type:this.getType(e),value:this.getValue(e),stack:(i=this.getStack(e))!==null&&i!==void 0?i:(r=n.syntheticException)==null?void 0:r.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return Xa(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var n="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(n+=" with message: '"+e.message+"'"),n}if("message"in e&&typeof e.message=="string")return e.message;var i=this.getObjectClassName(e);return(i&&i!=="Object"?"'"+i+"'":"Object")+" captured as exception with keys: "+Wd(e)}isSeverityLevel(e){return X(e)&&!Ko(e)&&vg.indexOf(e)>=0}getStack(e){try{return X(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:X(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(var n in e)if({}.hasOwnProperty.call(e,n)){var i=e[n];if(Xp(i))return i}}getObjectClassName(e){try{var n=Object.getPrototypeOf(e);return n?n.constructor.name:void 0}catch{return}}}class yg{match(e){return Xa(e)}coerce(e,n){var i,r=e.constructor.name;return{type:r,value:r+" captured as exception with keys: "+Wd(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class wg{match(e){return gd(e)}coerce(e,n){var i;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class bg{match(e){return Hr(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Xa(e))return!1;try{var n=e.detail;return n!=null&&typeof n=="object"&&"reason"in n}catch{return!1}}coerce(e,n){var i,r=this.getUnhandledRejectionReason(e);return gd(r)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(r),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}:n.apply(r)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}}var Kr="$message",Yr="$timestamp",Eg=new Set([Kr,Yr]),go={enabled:!0,max_bytes:32768};function Jr(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:go.enabled,max_bytes:xg(t.max_bytes,go.max_bytes)}:k({},go)}class Sg{constructor(e){this.Ke=[],this.Je=0,this.Ne=Jr(e)}setConfig(e){this.Ne=Jr(e),this.Xe()}add(e){var n=(function(r){var s;try{s=fd(r)}catch{return}try{var o=JSON.parse(s);if(!he(o))return;var a=o,l=a[Kr],u=a[Yr];return!X(l)||l.trim().length===0||!X(u)&&!ke(u)?void 0:{step:a,json:s}}catch{return}})(e);if(n){var i=(function(r){if(typeof TextEncoder<"u")return new TextEncoder().encode(r).length;for(var s=encodeURIComponent(r),o=0,a=0;s.length>a;a++)s[a]==="%"?(o+=1,a+=2):o+=1;return o})(n.json);i>this.Ne.max_bytes||(this.Ke.push({step:n.step,bytes:i}),this.Je+=i,this.Xe())}}getAttachable(){return this.Ke.map((e=>e.step))}clear(){this.Ke=[],this.Je=0}size(){return this.Ke.length}Xe(){for(;this.Je>this.Ne.max_bytes&&this.Ke.length>0;){var e=this.Ke.shift();e&&(this.Je-=e.bytes)}}}function xg(t,e){if(!ke(t)||t===1/0||t===-1/0)return e;var n=Math.floor(t);return 0>n?e:n}var qd=function(t,e){var n=(e===void 0?{}:e).debugEnabled,i={k(r){if(w&&(ne.DEBUG||w.POSTHOG_DEBUG||n)&&!C(w.console)&&w.console){for(var s=("__rrweb_original__"in w.console[r])?w.console[r].__rrweb_original__:w.console[r],o=arguments.length,a=new Array(o>1?o-1:0),l=1;o>l;l++)a[l-1]=arguments[l];s(t,...a)}},debug(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("debug",...s)},info(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("log",...s)},warn(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("warn",...s)},error(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("error",...s)},critical(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];console.error(t,...s)},uninitializedWarning(r){i.error("You must initialize PostHog before calling "+r)},createLogger:(r,s)=>qd(t+" "+r,s)};return i},A=qd("[PostHog.js]"),pe=A.createLogger,Ig=pe("[ExternalScriptsLoader]"),mo=(t,e,n)=>{if(t.config.disable_external_dependency_loading)return Ig.warn(e+" was requested but loading of external scripts is disabled."),n("Loading of external scripts is disabled");var i=F?.querySelectorAll("script");if(i){for(var r,s=function(){if(i[o].src===e){var l=i[o];return l.__posthog_loading_callback_fired?{v:n()}:(l.addEventListener("load",(u=>{l.__posthog_loading_callback_fired=!0,n(void 0,u)})),l.onerror=u=>n(u),{v:void 0})}},o=0;i.length>o;o++)if(r=s())return r.v}var a=()=>{if(!F)return n("document not found");var l=F.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=d=>{l.__posthog_loading_callback_fired=!0,n(void 0,d)},l.onerror=d=>n(d),t.config.prepare_external_dependency_script&&(l=t.config.prepare_external_dependency_script(l)),!l)return n("prepare_external_dependency_script returned null");if(t.config.external_scripts_inject_target==="head")F.head.appendChild(l);else{var u,c=F.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):F.body.appendChild(l)}};F!=null&&F.body?a():F?.addEventListener("DOMContentLoaded",a)};B.__PosthogExtensions__=B.__PosthogExtensions__||{},B.__PosthogExtensions__.loadExternalDependency=(t,e,n)=>{if(e!=="remote-config"){var i;if(t.config.strict_script_versioning)i=t.requestRouter.endpointFor("assets","/static/"+t.version+"/"+e+".js");else{var r="/static/"+e+".js?v="+t.version;if(e==="toolbar"){var s=3e5;r=r+"&t="+Math.floor(Date.now()/s)*s}i=t.requestRouter.endpointFor("assets",r)}mo(t,i,n)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");mo(t,o,n)}},B.__PosthogExtensions__.loadSiteApp=(t,e,n)=>{var i=t.requestRouter.endpointFor("api",e);mo(t,i,n)};ne.DEBUG=!1,ne.LIB_VERSION="1.415.7",ne.LIB_NAME="web";var zd="$people_distinct_id",Yi="$device_id",vo="$device_model",Fi="__alias",Ri="__timers",ea="$autocapture_disabled_server_side",ta="$heatmaps_enabled_server_side",na="$exception_capture_enabled_server_side",ia="$error_tracking_suppression_rules",ra="$error_tracking_capture_extension_exceptions",sa="$web_vitals_enabled_server_side",rl="$dead_clicks_enabled_server_side",sl="$product_tours_enabled_server_side",oa="$web_vitals_allowed_metrics",An="$session_recording_remote_config",Vd="$replay_sample_rate",Gd="$replay_override_sampling",Kd="$replay_override_linked_flag",Yd="$replay_override_url_trigger",Jd="$replay_override_event_trigger",Kn="$sesid",ol="$session_is_sampled",Sn="$enabled_feature_flags",Ti="$active_feature_flags",Ar="$early_access_features",aa="$feature_flag_details",$i="$feature_flag_payloads",Pr="$feature_flag_request_id",Zr="$minimal_flag_called_events",xt="$override_feature_flags",xn="$override_feature_flag_payloads",Dt="$stored_person_properties",In="$stored_group_properties",la="$surveys",Xr="$surveys_loaded_at",ca="$surveys_activated",Fr="$surveys_activated_session",Rr="$surveys_activated_timestamps",Mi="ph_product_tours",Cn="$flag_call_reported",Li="$flag_call_reported_session_id",Tr="$feature_flag_errors",ji="$feature_flag_evaluated_at",ot="$user_state",ua="$client_session_props",da="$capture_rate_limit",fa="$initial_campaign_params",ha="$initial_referrer_info",Qr="$initial_person_info",es="$epp",mr="$posthog_cookieless",Zd="$cookieless_mode",Xd="$sdk_debug_extensions_init_method",Qd="$sdk_debug_extensions_init_time_ms",ef="$sdk_debug_recording_script_not_loaded",al="PostHog loadExternalDependency extension not found.",kn="on_reject",Ht="always",Un="anonymous",vn="identified",pa="identified_only",ts="visibilitychange",ns="beforeunload",Vn="$pageview",_o="$pageleave",yo="$identify",Ac="$groupidentify";function vr(t,e){U(t)&&t.forEach(e)}function ie(t,e){if(!H(t))if(U(t))t.forEach(e);else if(Np(t))t.forEach(((i,r)=>e(i,r)));else for(var n in t)pd.call(t,n)&&e(t[n],n)}var fe=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;e>i;i++)n[i-1]=arguments[i];for(var r of n)for(var s in r)r[s]!==void 0&&(t[s]=r[s]);return t};function $r(t){for(var e=Object.keys(t),n=e.length,i=new Array(n);n--;)i[n]=[e[n],t[e[n]]];return i}var Pc=function(t){try{return t()}catch{return}},kg=function(t){return function(){try{for(var e=arguments.length,n=new Array(e),i=0;e>i;i++)n[i]=arguments[i];return t.apply(this,n)}catch(r){A.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),A.critical(r)}}},ll=function(t){var e={};return ie(t,(function(n,i){(X(n)&&n.length>0||ke(n))&&(e[i]=n)})),e},Cg=["herokuapp.com","vercel.app","netlify.app"];function Ag(t){var e=t?.hostname;if(!X(e))return!1;var n=e.split(".").slice(-2).join(".");for(var i of Cg)if(n===i)return!1;return!0}function ve(t,e,n,i){var r=i??{},s=r.capture,o=r.passive;t?.addEventListener(e,n,{capture:s!==void 0&&s,passive:o===void 0||o})}function ga(t){return t.name==="ph_toolbar_internal"}var tf=t=>{if(F){try{for(var e=t+"=",n=F.cookie.split(";").filter((s=>s.length)),i=0;n.length>i;i++){for(var r=n[i];r.charAt(0)==" ";)r=r.substring(1,r.length);if(r.indexOf(e)===0)return decodeURIComponent(r.substring(e.length,r.length))}}catch{}return null}};Math.trunc||(Math.trunc=function(t){return 0>t?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return ke(t)&&isFinite(t)&&Math.floor(t)===t});class is{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,n,i,r){if(!Number.isInteger(e)||!Number.isInteger(n)||!Number.isInteger(i)||!Number.isInteger(r)||0>e||0>n||0>i||0>r||e>0xffffffffffff||n>4095||i>1073741823||r>4294967295)throw new RangeError("invalid field value");var s=new Uint8Array(16);return s[0]=e/Math.pow(2,40),s[1]=e/Math.pow(2,32),s[2]=e/Math.pow(2,24),s[3]=e/Math.pow(2,16),s[4]=e/256,s[5]=e,s[6]=112|n>>>8,s[7]=n,s[8]=128|i>>>24,s[9]=i>>>16,s[10]=i>>>8,s[11]=i,s[12]=r>>>24,s[13]=r>>>16,s[14]=r>>>8,s[15]=r,new is(s)}toString(){for(var e="",n=0;this.bytes.length>n;n++)e=e+(this.bytes[n]>>>4).toString(16)+(15&this.bytes[n]).toString(16),n!==3&&n!==5&&n!==7&&n!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new is(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var n=0;16>n;n++){var i=this.bytes[n]-e.bytes[n];if(i!==0)return Math.sign(i)}return 0}}class Pg{generate(){var e=this.generateOrAbort();if(!C(e))return e;this.S=0;var n=this.generateOrAbort();if(C(n))throw new Error("Could not generate UUID after timestamp reset");return n}generateOrAbort(){var e=Date.now();if(e>this.S)this.S=e,this.C();else{if(this.S>=e+1e4)return;this.I++,this.I>4398046511103&&(this.S++,this.C())}return is.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 Fg}}var Fc,nf=t=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;t.length>e;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};w&&!C(w.crypto)&&crypto.getRandomValues&&(nf=t=>crypto.getRandomValues(t));class Fg{nextUint32(){return this.R.length>this.O||(nf(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var Ut=()=>Rg().toString(),Rg=()=>(Fc||(Fc=new Pg)).generate(),yi="",Tg=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,Wt={N:()=>!!F,j(t){A.error("cookieStore error: "+t)},P:tf,H(t){var e;try{e=JSON.parse(Wt.P(t))||{}}catch{}return e},F(t,e,n,i,r){if(!F)return!1;try{var s="",o="",a=(function(c,d){if(d){var f=(function(p,g){if(g===void 0&&(g=F),yi)return yi;if(!g||["localhost","127.0.0.1"].includes(p))return"";for(var m=p.split("."),v=Math.min(m.length,8),S="dmn_chk_"+Ut();!yi&&v--;){var b=m.slice(v).join("."),_=S+"=1;domain=."+b+";path=/";g.cookie=_+";max-age=3",g.cookie.includes(S)&&(g.cookie=_+";max-age=0",yi=b)}return yi})(c);if(!f){var h=(p=>{var g=p.match(Tg);return g?g[0]:""})(c);h!==f&&A.info("Warning: cookie subdomain discovery mismatch",h,f),f=h}return f?"; domain=."+f:""}return""})(F.location.hostname,i);if(n){var l=new Date;l.setTime(l.getTime()+864e5*n),s="; expires="+l.toUTCString()}r&&(o="; secure");var u=t+"="+encodeURIComponent(JSON.stringify(e))+s+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&A.warn("cookieStore warning: large cookie, len="+u.length),F.cookie=u,!0}catch{return!1}},q(t,e){if(F!=null&&F.cookie)try{Wt.F(t,"",-1,e)}catch{return}}},wo=null,le={N(){if(!Ke(wo))return wo;var t=!0;if(C(w))t=!1;else try{var e="__mplssupport__";le.F(e,"xyz"),le.P(e)!=='"xyz"'&&(t=!1),le.q(e)}catch{t=!1}return t||A.error("localStorage unsupported; falling back to cookie store"),wo=t,t},j(t){A.error("localStorage error: "+t)},P(t){try{return w?.localStorage.getItem(t)}catch(e){le.j(e)}return null},H(t){try{return JSON.parse(le.P(t))||{}}catch{}return null},F(t,e){try{return w?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(n){le.j(n)}return!1},q(t){try{w?.localStorage.removeItem(t)}catch(e){le.j(e)}}},$g=[Yi,"distinct_id",Kn,ol,es,Qr,ot],_r={},Mg={N:()=>!0,j(t){A.error("memoryStorage error: "+t)},P:t=>_r[t]||null,H:t=>_r[t]||null,F:(t,e)=>(_r[t]=e,!0),q(t){delete _r[t]}},_n=null,be={N(){if(!Ke(_n))return _n;if(_n=!0,C(w))_n=!1;else try{var t="__support__";be.F(t,"xyz"),be.P(t)!=='"xyz"'&&(_n=!1),be.q(t)}catch{_n=!1}return _n},j(t){A.error("sessionStorage error: ",t)},P(t){try{return w?.sessionStorage.getItem(t)}catch(e){be.j(e)}return null},H(t){try{return JSON.parse(be.P(t))||null}catch{}return null},F(t,e){try{return w?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(n){be.j(n)}return!1},q(t){try{w?.sessionStorage.removeItem(t)}catch(e){be.j(e)}}};class Lg{constructor(e){this._instance=e}get Ne(){return this._instance.config}get consent(){return this.ti()?0:this.ei}isOptedOut(){return this.Ne.cookieless_mode===Ht||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===kn}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===0}isRejected(){return this.consent===0||this.consent===-1&&this.Ne.opt_out_capturing_by_default}optInOut(e){this.ii.F(this.ri,e?1:0,this.Ne.cookie_expiration,this.Ne.cross_subdomain_cookie,this.Ne.secure_cookie)}reset(){this.ii.q(this.ri,this.Ne.cross_subdomain_cookie)}get ri(){var e=this._instance.config,n=e.token,i=e.opt_out_capturing_cookie_prefix;return e.consent_persistence_name||(i?i+n:"__ph_opt_in_out_"+n)}get ei(){var e=this.ii.P(this.ri);return uo(e)?1:j(jp,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,n=e==="localStorage"?le:Wt;if(!this.ni||this.ni!==n){this.ni=n;var i=e==="localStorage"?Wt:le;i.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(uo(i.P(this.ri))),i.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[Ue?.doNotTrack,Ue?.msDoNotTrack,B.doNotTrack].some((e=>uo(e)))}}function rf(t,e){var n,i=t==null||(n=t.config)==null?void 0:n.get_current_url;if(!De(i))return e;try{var r=i(e);return X(r)&&r?r:e}catch(s){return A.error("Error in get_current_url, falling back to window.location.href",s),e}}var sf="__POSTHOG_TOOLBAR__",Ng=1,Og=3,Bg=11;function Rc(t){return t instanceof Element&&(t.id===sf||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function hn(t){return!!t&&t.nodeType===Ng}function Qe(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function of(t){return!!t&&t.nodeType===Og}function af(t){return!!t&&t.nodeType===Bg&&hn(t.host)}var lf=1e3;function cl(t){return t?xs(t).split(/\s+/):[]}function Tc(t,e){var n=(function(i){var r,s=w==null||(r=w.location)==null?void 0:r.href;return C(s)?void 0:rf(i,s)})(e);return!!(n&&t&&t.some((i=>n.match(i))))}function rs(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 cl(e)}function cf(t){return H(t)?null:xs(t).split(/(\s+)/).filter((e=>Ui(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function Ji(t){var e="";return va(t)&&!hf(t)&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;of(n)&&n.textContent&&(e+=(i=cf(n.textContent))!==null&&i!==void 0?i:"")})),xs(e)}function bo(t){var e;return C(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var ul=["a","button","form","input","select","textarea","label"];function ma(t,e){if(C(e))return!0;var n,i=function(s){if(e.some((o=>(function(a,l){var u=a.matches||a.matchesSelector||a.msMatchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.oMatchesSelector;try{return!!u&&u.call(a,l)}catch{return!1}})(s,o))))return{v:!0}};for(var r of t)if(n=i(r))return n.v;return!1}function uf(t){var e=t.parentNode;return!(!e||!hn(e))&&e}var Dg=[".ph-no-autocapture","[data-ph-no-autocapture]"],df=["next","previous","prev",">","<"],jg=[...df,"+","-","−","–"],$c=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,Mc=[".ph-no-rageclick",".ph-no-capture"],Ug=["","text","search","email","password","url","tel","number"];function Lc(t,e){if(!w||dl(t))return!1;var n,i,r,s,o;if(gt(e)?(n=!!e&&Mc,i=void 0,r=!1):(n=(s=e?.css_selector_ignorelist)!==null&&s!==void 0?s:Mc,i=e?.content_ignorelist,r=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),n===!1||r&&(function(l){return!(!l||!hn(l))&&(!!Qe(l,"textarea")||(Qe(l,"input")?j(Ug,(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=ff(t,!1).targetElementList;return!(function(l,u){if(l===!1||C(l))return!1;var c;if(l===!0)c=df;else{if(!U(l))return!1;if(l.length>10)return A.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var f=d.safeText,h=d.ariaLabel;return c.some((p=>$c(f,p)||$c(h,p)))}))})(i,a.map((l=>{var u;return{safeText:Ji(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!ma(a,n)}var dl=t=>!t||Qe(t,"html")||!hn(t),ff=(t,e)=>{if(!w||dl(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,i=[t],r=t;r.parentNode&&!Qe(r,"body");)if(af(r.parentNode))i.push(r.parentNode.host),r=r.parentNode.host;else{var s=uf(r);if(!s)break;if(e||ul.indexOf(s.tagName.toLowerCase())>-1)n=!0;else try{var o=w.getComputedStyle(s);o&&o.getPropertyValue("cursor")==="pointer"&&(n=!0)}catch{}i.push(s),r=s}return{parentIsUsefulElement:n,targetElementList:i}};function va(t){for(var e=new Set,n=0,i=t;i.parentNode&&!Qe(i,"body");i=i.parentNode){if(n++>=lf||e.has(i))return!1;e.add(i);var r=rs(i);if(j(r,"ph-sensitive")||j(r,"ph-no-capture"))return!1}if(j(rs(t),"ph-include"))return!0;var s=t.type||"";if(X(s))switch(s.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!X(o)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(o.replace(/[^a-zA-Z0-9]/g,""))}function hf(t){return!!(Qe(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||Qe(t,"select")||Qe(t,"textarea")||t.getAttribute("contenteditable")==="true")}var Nc=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}))$"),Oc=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,Hg=[16,15,14,13],Wg=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),Bc=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),Dc=/[0-9A-Za-z_]/;function qg(t){for(var e=0,n=!1,i=t.length-1;i>=0;i--){var r=t.charCodeAt(i)-48;n&&(r*=2)>9&&(r-=9),e+=r,n=!n}return e%10==0}function Ui(t,e){if(e===void 0&&(e=!0),H(t))return!1;if(X(t)){t=xs(t);var n=e?Nc.test((t||"").replace(/[- ]/g,"")):(function(r){var s;for(Oc.lastIndex=0;s=Oc.exec(r);){var o=s[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of Hg){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(Nc.test(d)&&qg(d))return!0}}}return!1})(t);if(n)return!1;var i=e?Wg.test(t):(function(r){var s;for(Bc.lastIndex=0;s=Bc.exec(r);){var o=s[1],a=s[3];if(!(o&&a&&Dc.test(o)&&Dc.test(a)))return!0}return!1})(t);if(i)return!1}return!0}function jc(t){var e=Ji(t);return Ui(e=(e+" "+pf(t)).trim())?e:""}function pf(t){var e="";return t&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;if(n&&((i=n.tagName)==null?void 0:i.toLowerCase())==="span")try{var r=Ji(n);e=(e+" "+r).trim(),n.childNodes&&n.childNodes.length&&(e=(e+" "+pf(n)).trim())}catch(s){A.error("[AutoCapture]",s)}})),e}function Uc(t){return t.replace(/"|\\"/g,'\\"')}function zg(t){var e=t.attr__class;if(e)return U(e)?e:cl(e)}var yr=pe("[Dead Clicks]"),Vg=()=>!0,Gg=t=>{var e,n=!((e=t.instance.persistence)==null||!e.get_property(rl)),i=t.instance.config.capture_dead_clicks;return gt(i)?i:!!he(i)||n};class Hc{get lazyLoadedDeadClicksAutocapture(){return this.si}constructor(e,n,i){this.instance=e,this.isEnabled=n,this.onCapture=i,this.startIfEnabledOrStop()}onRemoteConfig(e){if(e.ok){var n=e.config;"captureDeadClicks"in n&&(this.instance.persistence&&this.instance.persistence.register({[rl]:n.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var n,i;(n=B.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture?e():(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"dead-clicks-autocapture",(r=>{r?yr.error("failed to load script",r):e()}))}oi(){var e;if(F){if(!this.si&&(e=B.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var n=he(this.instance.config.capture_dead_clicks)?k({},this.instance.config.capture_dead_clicks):{};n.__onCapture=this.onCapture,this.onCapture&&(n.capture_dead_swipes=!1),this.si=B.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.si.start(F),yr.info("starting...")}}else yr.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,yr.info("stopping..."))}}var Eo=pe("[SegmentIntegration]"),gf="posthog-js";function mf(t,e){var n=e===void 0?{}:e,i=n.organization,r=n.projectId,s=n.prefix,o=n.severityAllowList,a=o===void 0?["error"]:o,l=n.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,f,h,p,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var v,S=((d=c.exception)==null?void 0:d.values)||[],b=S.map((x=>k({},x,{stacktrace:x.stacktrace?k({},x.stacktrace,{type:"raw",frames:(x.stacktrace.frames||[]).map((I=>k({},I,{platform:"web:javascript"})))}):void 0}))),_={$exception_message:((f=S[0])==null?void 0:f.value)||c.message,$exception_type:(h=S[0])==null?void 0:h.type,$exception_level:c.level,$exception_list:b,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((p=S[0])==null?void 0:p.value)||c.message,$sentry_exception_type:(g=S[0])==null?void 0:g.type,$sentry_tags:c.tags};return i&&r&&(_.$sentry_url=(s||"https://sentry.io/organizations/")+i+"/issues/?project="+r+"&query="+c.event_id),u&&((v=t.exceptions)==null||v.sendExceptionEvent(_)),c}}class Kg{constructor(e,n,i,r,s,o){this.name=gf,this.setupOnce=function(a){a(mf(e,{organization:n,projectId:i,prefix:r,severityAllowList:s,sendExceptionsToPostHog:o==null||o}))}}}class Wc{constructor(e){this.li=(n,i,r)=>{r&&(r.noSessionId||r.activityTimeout||r.sessionPastMaximumLength||r.crossTabAdoption)&&(A.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:n,changeReason:r}),this.ui=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.hi()}hi(){var e;this.di=(e=this._instance.sessionManager)==null?void 0:e.onSessionId(this.li)}destroy(){var e;(e=this.di)==null||e.call(this),this.di=void 0}doPageView(e,n){var i,r=this.vi(e,n);return this.ui={pathname:(i=w?.location.pathname)!==null&&i!==void 0?i:"",pageViewId:n,timestamp:e},this._instance.scrollManager.resetContext(),r}doPageLeave(e){var n;return this.vi(e,(n=this.ui)==null?void 0:n.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.ui)==null?void 0:e.pageViewId}}vi(e,n){var i=this.ui;if(!i)return{$pageview_id:n};var r={$pageview_id:n,$prev_pageview_id:i.pageViewId},s=this._instance.scrollManager.getContext();if(s&&!this._instance.config.disable_scroll_properties){var o=s.maxScrollHeight,a=s.lastScrollY,l=s.maxScrollY,u=s.maxContentHeight,c=s.lastContentY,d=s.maxContentY;if(!(C(o)||C(a)||C(l)||C(u)||C(c)||C(d))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),d=Math.ceil(d);var f=o>1?Ct(a/o,0,1,A):1,h=o>1?Ct(l/o,0,1,A):1,p=u>1?Ct(c/u,0,1,A):1,g=u>1?Ct(d/u,0,1,A):1;r=fe(r,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:f,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:h,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:p,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return i.pathname&&(r.$prev_pageview_pathname=i.pathname),i.timestamp&&(r.$prev_pageview_duration=(e.getTime()-i.timestamp.getTime())/1e3),r}}var So=["flags","surveys"],Yg={[zd]:{exposure:"hidden"},[Fi]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[Ri]:{exposure:"hidden"},[ea]:{exposure:"event"},[ta]:{exposure:"hidden"},[na]:{exposure:"event"},[ia]:{exposure:"hidden"},[ra]:{exposure:"event"},[sa]:{exposure:"event"},[rl]:{exposure:"event"},[sl]:{exposure:"hidden"},[oa]:{exposure:"event"},[An]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[Kn]:{exposure:"hidden"},[ol]:{exposure:"event"},[Vd]:{exposure:"event",shouldSkipFromEventProperties:t=>Ke(t)},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},$sess_rec_flush_size:{exposure:"hidden"},[Sn]:{exposure:"hidden",storageGroup:"flags"},[Ti]:{exposure:"hidden",storageGroup:"flags"},[Ar]:{exposure:"hidden"},[aa]:{exposure:"hidden",storageGroup:"flags"},[$i]:{exposure:"hidden",storageGroup:"flags"},[Pr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[Zr]:{exposure:"hidden",storageGroup:"flags"},[xt]:{exposure:"hidden"},[xn]:{exposure:"hidden"},[Dt]:{exposure:"hidden"},[In]:{exposure:"hidden"},[la]:{exposure:"hidden",storageGroup:"surveys"},[Xr]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[ca]:{exposure:"event"},[Fr]:{exposure:"hidden"},[Rr]:{exposure:"hidden"},[Mi]:{exposure:"hidden"},$product_tours_activated:{exposure:"hidden"},$product_tours_activated_session:{exposure:"hidden"},$conversations_widget_session_id:{exposure:"event"},$conversations_ticket_id:{exposure:"event"},$conversations_widget_state:{exposure:"event"},$conversations_user_traits:{exposure:"event"},[Cn]:{exposure:"hidden"},[Li]:{exposure:"hidden"},[Tr]:{exposure:"hidden"},[ji]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[ot]:{exposure:"hidden"},[ua]:{exposure:"hidden"},[da]:{exposure:"hidden"},[fa]:{exposure:"hidden"},[ha]:{exposure:"hidden"},[Qr]:{exposure:"hidden"},[es]:{exposure:"hidden"},[Gd]:{exposure:"event"},[Kd]:{exposure:"event"},[Yd]:{exposure:"event"},[Jd]:{exposure:"event"},[Xd]:{exposure:"event"},[Qd]:{exposure:"event"},[ef]:{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"}},Jg=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],yn=t=>{var e=Yg[t];if(e)return e;for(var n of Jg){var i=n[1];if(t.indexOf(n[0])===0)return i}},Yn=(t,e)=>{try{return JSON.stringify(t,((n,i)=>typeof i=="bigint"?i.toString():i),e)}catch{return fd(t)}},ss=t=>{var e=F?.createElement("a");return C(e)?null:(e.href=t,e)},ii=function(t,e){for(var n,i=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),r=0;i.length>r;r++){var s=i[r].split("=");if(s[0]===e){n=s;break}}if(!U(n)||2>n.length)return"";var o=n[1];try{o=decodeURIComponent(o)}catch{A.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},Zi=function(t,e,n){if(!t||!e||!e.length)return t;for(var i=t.split("#"),r=i[1],s=(i[0]||"").split("?"),o=s[1],a=s[0],l=(o||"").split("&"),u=[],c=0;l.length>c;c++){var d=l[c].split("=");U(d)&&(e.includes(d[0])?u.push(d[0]+"="+n):u.push(l[c]))}var f=a;return o!=null&&(f+="?"+u.join("&")),r!=null&&(f+="#"+r),f},os=function(t,e){var n=t.match(new RegExp(e+"=([^&]*)"));return n?n[1]:null},vf=(t,e)=>t>=e&&cd(),_f=(t,e,n,i)=>{if(t===0){if(cd()){var r=e+1;return r===n&&i(),r}return e}return 0},wr="https?://(.*)",ri=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Zg=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...ri],Xi="",Xg=["li_fat_id"];function yf(t,e,n){if(!F)return{};var i,r=e?[...ri,...n||[]]:[],s=wf(Zi(F.URL,r,Xi),t),o=(i={},ie(Xg,(function(a){var l=tf(a);i[a]=l||null})),i);return fe(o,s)}function wf(t,e){var n=Zg.concat(e||[]),i={};return ie(n,(function(r){var s=ii(t,r);i[r]=s||null})),i}function bf(t){var e=(function(s){return s?s.search(wr+"google.([^/?]*)")===0?"google":s.search(wr+"bing.com")===0?"bing":s.search(wr+"yahoo.com")===0?"yahoo":s.search(wr+"duckduckgo.com")===0?"duckduckgo":null:null})(t),n=e!="yahoo"?"q":"p",i={};if(!Ke(e)){i.$search_engine=e;var r=F?ii(F.referrer,n):"";r.length&&(i.ph_keyword=r)}return i}function qc(){return navigator.language||navigator.userLanguage}var as="$direct";function Ef(){return F?.referrer||as}function Sf(t,e,n){n===void 0&&(n=!1);var i=t?[...ri,...e||[]]:[],r=n?fn(me?.href):me?.href,s=r?.substring(0,1e3);return{r:Ef().substring(0,1e3),u:s?Zi(s,i,Xi):void 0}}function xf(t,e){var n;e===void 0&&(e=!1);var i=t.r,r=t.u,s=e?fn(r):r,o={$referrer:i,$referring_domain:i==null?void 0:i==as?as:(n=ss(i))==null?void 0:n.host};if(s){o.$current_url=s;var a=ss(s);o.$host=a?.host,o.$pathname=a?.pathname;var l=wf(s);fe(o,l)}if(i){var u=bf(i);fe(o,u)}return o}function If(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function Qg(){try{return new Date().getTimezoneOffset()}catch{return}}var em={flags:ji,surveys:Xr},tm=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],Hn="main";class xo{constructor(e,n,i){if(i===void 0&&(i=!0),this.ci={},this.fi=!1,this.pi=!1,this.Ne=e,this.gi=i,this.props={},this.mi=void 0,this.yi=(s=>{var o="";return s.token&&(o=s.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),s.persistence_name?"ph_"+s.persistence_name:"ph_"+o+"_posthog"})(e),this.ii=this.bi(e),this.pi=this.wi(e),this.load(),e.debug&&A.info("Persistence loaded",e.persistence,k({},this.props)),this.update_config(e,e,n),this.save(),w){var r=()=>this.flush();ve(w,"beforeunload",r,{capture:!1}),ve(w,"pagehide",r,{capture:!1})}}ki(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return ke(n)&&n>0?n:0}isDisabled(){return!!this.xi}bi(e){tm.indexOf(e.persistence.toLowerCase())===-1&&(A.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var n,i=(function(o,a){o===void 0&&(o=[]),a===void 0&&(a=!1);var l=[...$g,...o];return k({},le,{H(u){try{var c={};try{c=Wt.H(u)||{}}catch{}var d,f=JSON.parse(le.P(u)||"{}");if(a){var h={};for(var p in c){var g=c[p];Ke(g)||g===""||(h[p]=g)}d=fe(f,h)}else d=fe(c,f);return le.F(u,d),d}catch{}return null},F(u,c,d,f,h,p){var g=le.F(u,c,void 0,void 0,p);try{var m={};l.forEach((v=>{c[v]&&(m[v]=c[v])})),Object.keys(m).length&&Wt.F(u,m,d,f,h,p)}catch(v){le.j(v)}return g},q(u,c){try{w?.localStorage.removeItem(u),Wt.q(u,c)}catch(d){le.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),r=!1,s=e.persistence.toLowerCase();return s==="localstorage"&&le.N()?(n=le,r=!0):s==="localstorage+cookie"&&i.N()?(n=i,r=!0):s==="sessionstorage"&&be.N()?n=be:s==="memory"?n=Mg:s==="cookie"?n=Wt:i.N()?(n=i,r=!0):n=Wt,this.fi=r,n}Si(e){return this.yi+"__"+e}wi(e){return this.fi&&!!e.split_storage}properties(){var e={};return ie(this.props,((n,i)=>{var r=yn(i);if(!r||r.exposure==="event"){if(r!=null&&r.shouldSkipFromEventProperties!=null&&r.shouldSkipFromEventProperties(n))return;e[i]=n}})),e}load(){if(!this.xi){var e=this.ii.H(this.yi);e&&(this.props=fe({},e)),this.pi&&this.Ci()}}Ci(){for(var e of So){var n=le.H(this.Si(e));if(n&&!Gt(n)){var i=this.Mi(e);i.persisted=!0,this.Ti(e)||(i.fingerprint=this.Ei(n,e)),this.Ii(e,n)||fe(this.props,n)}}}Ti(e){return Object.keys(this.props).some((n=>{var i;return((i=yn(n))==null?void 0:i.storageGroup)===e}))}Ii(e,n){var i=em[e];if(!i)return!1;var r=n[i],s=this.props[i];return ke(r)&&ke(s)&&s>r}refreshKey(e){var n;if(!this.xi){var i=this.pi?(n=yn(e))==null?void 0:n.storageGroup:void 0,r=i?le.H(this.Si(i)):this.ii.H(this.yi);if(r&&e in r)this.Pi(e,r[e]);else{if(i){var s=this.ii.H(this.yi);if(s&&e in s)return void this.Pi(e,s[e])}this.Ri(e)}}}save(){if(!this.xi){var e=this.ki();e>0?C(this.Ai)&&(this.Ai=setTimeout((()=>{this.Ai=void 0,this.Fi()}),e)):this.Fi()}}flush(){C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0,this.Fi())}Fi(){this.xi||(this.pi?this.Li():this.Oi(this.ii,this.yi,this.props,Hn))}Li(){var e=this.Di(),n=e.main,i=e.groups;for(var r of(this.Oi(this.ii,this.yi,n,Hn),So)){var s,o=i[r];(!Gt(o)||(s=this.ci[r])!=null&&s.persisted)&&this.Oi(le,this.Si(r),o,r)}}Di(){var e={},n={flags:{},surveys:{}};return ie(this.props,((i,r)=>{var s,o=(s=yn(r))==null?void 0:s.storageGroup;o?n[o][r]=i:e[r]=i})),{main:e,groups:n}}Ei(e,n){if(n===Hn)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var i={};return ie(e,((r,s)=>{var o;i[s]=(o=yn(s))!=null&&o.volatile?"__volatile__":r})),JSON.stringify(i)}Oi(e,n,i,r){var s=this.Mi(r);if(r===Hn||s.dirty||C(s.fingerprint)){var o;try{if((o=this.Ei(i,r))===s.fingerprint)return void(s.dirty=!1)}catch{o=void 0}e.F(n,i,this.$i,this.Ni,this.qi,this.Ne.debug)?(s.dirty=!1,r!==Hn&&(s.persisted=!0),C(o)||(s.fingerprint=o)):this.Ne.debug&&A.warn('failed to persist storage entry "'+n+'"; will retry on next save')}}remove(e){var n=(e===void 0?{}:e).keepGroupEntries,i=n!==void 0&&n;if(C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0),this.ii.q(this.yi,!1),this.ii.q(this.yi,!0),!i&&this.gi)for(var r of So)le.q(this.Si(r));i?delete this.ci[Hn]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,n,i){if(he(e)){C(n)&&(n="None"),this.$i=C(i)?this.ji:i;var r=!1;if(ie(e,((s,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==n||(this.Pi(o,s),r=!0)})),r)return this.save(),!0}return!1}register(e,n){if(he(e)){this.$i=C(n)?this.ji:n;var i=!1;if(ie(e,((r,s)=>{e.hasOwnProperty(s)&&(this.props[s]!==r||he(r)||U(r))&&(this.Pi(s,r),i=!0)})),i)return this.save(),!0}return!1}unregister(e){var n=typeof e=="string"?[e]:e,i=!1;for(var r of n)r in this.props&&(this.Ri(r),i=!0);i&&this.save()}update_campaign_params(){var e=F?.URL;if(e!==this.mi){var n=yf(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);Gt(ll(n))||this.register(n),this.mi=e}}update_search_keyword(){var e;this.register((e=F?.referrer)?bf(e):{})}update_referrer_info(){var e;this.register_once({$referrer:Ef(),$referring_domain:F!=null&&F.referrer&&((e=ss(F.referrer))==null?void 0:e.host)||as},void 0)}set_initial_person_info(){this.props[fa]||this.props[ha]||this.register_once({[Qr]:Sf(this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties,this.Ne.disable_capture_url_hashes)},void 0)}get_initial_props(){var e={};ie([ha,fa],(r=>{var s=this.props[r];s&&ie(s,(function(o,a){e["$initial_"+Go(a)]=o}))}));var n=this.props[Qr];if(n){var i=(function(r,s){s===void 0&&(s=!1);var o=xf(r,s),a={};return ie(o,(function(l,u){a["$initial_"+Go(u)]=l})),a})(n,this.Ne.disable_capture_url_hashes);fe(e,i)}return e}safe_merge(e){return ie(this.props,(function(n,i){i in e||(e[i]=n)})),e}update_config(e,n,i){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!i),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var r=e.persistence!==n.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((f,h)=>f===d[h]))})(e.cookie_persisted_properties||[],n.cookie_persisted_properties||[]),s=r?this.bi(e):this.ii,o=this.wi(e);if(r||o!==this.pi){var a=this.props;this.clear(),this.ii=s,this.pi=o,this.props=a,this.save()}}set_disabled(e){this.xi=e,this.xi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ni&&(this.Ni=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this.qi&&(this.qi=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,n){var i=this.props[Ri]||{};i[e]=n,this.Pi(Ri,i),this.save()}remove_event_timer(e){var n=this.props[Ri]||{},i=n[e];return C(i)||(delete n[e],this.Pi(Ri,n),this.save()),i}get_property(e){return this.props[e]}set_property(e,n){this.Pi(e,n),this.save()}Pi(e,n){var i;this.props[e]=n,(i=yn(e))!=null&&i.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var n,i=(n=yn(e))==null?void 0:n.storageGroup;i&&(this.Mi(i).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function br(t){var e=!0;return{dispose(){if(e){e=!1;var n=t();n&&De(n.then)&&n.then(void 0,(()=>{}))}}}}var je={GZipJS:"gzip-js",Base64:"base64"},wi={Activation:"events",Cancellation:"cancelEvents"},Io={Popover:"popover",API:"api",Widget:"widget"},qt={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},ko={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},_a={Popover:"popover",Inline:"inline"},nm={SHOWN:"product tour shown"},zc={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},Vc=pe("[RateLimiter]");class im{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=n=>{var i=n.text;if(i&&i.length)try{(JSON.parse(i).quota_limited||[]).forEach((r=>{Vc.info((r||"events")+" is quota limited."),this.serverLimits[r]=new Date().getTime()+6e4}))}catch(r){return void Vc.warn('could not rate limit - continuing. Error: "'+r?.message+'"',{text:i})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var n,i,r;e===void 0&&(e=!1);var s=this.captureEventsBurstLimit,o=this.captureEventsPerSecond,a=new Date().getTime(),l=(n=(i=this.instance.persistence)==null?void 0:i.get_property(da))!==null&&n!==void 0?n:{tokens:s,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>s&&(l.tokens=s);var u=1>l.tokens;if(u||e||(l.tokens=Math.max(0,l.tokens-1)),u&&!e){var c=(ke(l.dropped)?l.dropped:0)+1;l.dropped=c,!this.lastEventRateLimited&&this.Hi(c)&&(l.dropped=0)}return this.lastEventRateLimited=u,(r=this.instance.persistence)==null||r.set_property(da,l),{isRateLimited:u,remainingTokens:l.tokens}}Ui(e){var n=this.instance.config.property_denylist;return!U(n)||!n.includes(e)}zi(){var e;if(this.Ui("$current_url")&&this.Ui("$pathname")&&me!=null&&me.pathname)return""+((e=me.origin)!==null&&e!==void 0?e:"")+me.pathname}Hi(e){var n,i,r=this.captureEventsBurstLimit,s=this.captureEventsPerSecond,o=this.zi(),a=this.Ui("$session_id")?(n=(i=this.instance).get_session_id)==null?void 0:n.call(i):void 0,l=[e+" event(s) dropped since the last warning",o?"triggered on "+o:void 0,a?"session "+a:void 0].filter(Boolean).join(", ");return!!this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited: "+l+". Config is set to "+s+" events per second and "+r+" events burst limit."},{skip_client_rate_limiting:!0})}isServerRateLimited(e){var n=this.serverLimits[e||"events"]||!1;return n!==!1&&new Date().getTime()e(this.remoteConfig))):e()}Vi(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:e})}load(){try{if(this.remoteConfig)return an.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void an.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return an.info("No config found after loading remote JS config. Falling back to JSON."),void this.Vi((n=>{this.Zi(n.json,n),this.Gi()}));this.Zi(e),this.Gi()}))}catch(e){an.error("Error loading remote config",e),this.Zi()}}stop(){this.Ki&&(clearInterval(this.Ki),this.Ki=void 0)}refresh(){!this._instance.Qi()&&F&&F.visibilityState!=="hidden"&&this._instance.reloadFeatureFlags()}Gi(){var e;if(!this.Ki){var n=(e=this._instance.config.remote_config_refresh_interval_ms)!==null&&e!==void 0?e:3e5;n!==0&&(this.Ki=setInterval((()=>{this.refresh()}),n))}}Zi(e,n){!e&&n&&(n.statusCode===0?n.error||an.warn("Failed to fetch remote config from PostHog."):an.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(r){an.error("Error applying remote config",r)}if(e?.hasFeatureFlags!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var i;(i=this._instance.featureFlags)==null||i.ensureFlagsLoaded()}catch(r){an.error("Error loading feature flags",r)}}}var lt=Uint8Array,Ge=Uint16Array,si=Uint32Array,fl=new lt([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]),hl=new lt([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]),Gc=new lt([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Cf=function(t,e){for(var n=new Ge(31),i=0;31>i;++i)n[i]=e+=1<i;++i)for(var s=n[i];n[i+1]>s;++s)r[s]=s-n[i]<<5|i;return[n,r]},Af=Cf(fl,2),ya=Af[1];Af[0][28]=258,ya[258]=28;for(var Kc=Cf(hl,0)[1],Pf=new Ge(32768),_e=0;32768>_e;++_e){var Wn=(43690&_e)>>>1|(21845&_e)<<1;Pf[_e]=((65280&(Wn=(61680&(Wn=(52428&Wn)>>>2|(13107&Wn)<<2))>>>4|(3855&Wn)<<4))>>>8|(255&Wn)<<8)>>>1}var Hi=function(t,e,n){for(var i=t.length,r=0,s=new Ge(e);i>r;++r)++s[t[r]-1];var o,a=new Ge(e);for(r=0;e>r;++r)a[r]=a[r-1]+s[r-1]<<1;for(o=new Ge(i),r=0;i>r;++r)o[r]=Pf[a[t[r]-1]++]>>>15-t[r];return o},$n=new lt(288);for(_e=0;144>_e;++_e)$n[_e]=8;for(_e=144;256>_e;++_e)$n[_e]=9;for(_e=256;280>_e;++_e)$n[_e]=7;for(_e=280;288>_e;++_e)$n[_e]=8;var ls=new lt(32);for(_e=0;32>_e;++_e)ls[_e]=5;var rm=Hi($n,9),sm=Hi(ls,5),Ff=function(t){return(t/8>>0)+(7&t&&1)},Rf=function(t,e,n){(n==null||n>t.length)&&(n=t.length);var i=new(t instanceof Ge?Ge:t instanceof si?si:lt)(n-e);return i.set(t.subarray(e,n)),i},Nt=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8},bi=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8,t[i+2]|=n>>>16},Co=function(t,e){for(var n=[],i=0;t.length>i;++i)t[i]&&n.push({s:i,f:t[i]});var r=n.length,s=n.slice();if(!r)return[new lt(0),0];if(r==1){var o=new lt(n[0].s+1);return o[n[0].s]=1,[o,1]}n.sort((function(x,I){return x.f-I.f})),n.push({s:-1,f:25001});var a=n[0],l=n[1],u=0,c=1,d=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=r-1;)a=n[n[d].f>n[u].f?u++:d++],l=n[u!=c&&n[d].f>n[u].f?u++:d++],n[c++]={s:-1,f:a.f+l.f,l:a,r:l};var f=s[0].s;for(i=1;r>i;++i)s[i].s>f&&(f=s[i].s);var h=new Ge(f+1),p=wa(n[c-1],h,0);if(p>e){i=0;var g=0,m=p-e,v=1<i;++i){var S=s[i].s;if(e>=h[S])break;g+=v-(1<>>=m;g>0;){var b=s[i].s;e>h[b]?g-=1<=0&&g;--i){var _=s[i].s;h[_]==e&&(--h[_],++g)}p=e}return[new lt(h),p]},wa=function(t,e,n){return t.s==-1?Math.max(wa(t.l,e,n+1),wa(t.r,e,n+1)):e[t.s]=n},Yc=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new Ge(++e),i=0,r=t[0],s=1,o=function(l){n[i++]=l},a=1;e>=a;++a)if(t[a]==r&&a!=e)++s;else{if(!r&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(r),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(r);s=1,r=t[a]}return[n.subarray(0,i),e]},Ei=function(t,e){for(var n=0,i=0;e.length>i;++i)n+=t[i]*e[i];return n},ba=function(t,e,n){var i=n.length,r=Ff(e+2);t[r]=255&i,t[r+1]=i>>>8,t[r+2]=255^t[r],t[r+3]=255^t[r+1];for(var s=0;i>s;++s)t[r+s+4]=n[s];return 8*(r+4+i)},Jc=function(t,e,n,i,r,s,o,a,l,u,c){Nt(e,c++,n),++r[256];for(var d=Co(r,15),f=d[0],h=d[1],p=Co(s,15),g=p[0],m=p[1],v=Yc(f),S=v[0],b=v[1],_=Yc(g),x=_[0],I=_[1],T=new Ge(19),E=0;S.length>E;++E)T[31&S[E]]++;for(E=0;x.length>E;++E)T[31&x[E]]++;for(var P=Co(T,7),$=P[0],O=P[1],L=19;L>4&&!$[Gc[L-1]];--L);var N,K,V,M,R=u+5<<3,Z=Ei(r,$n)+Ei(s,ls)+o,Ce=Ei(r,f)+Ei(s,g)+o+14+3*L+Ei(T,$)+(2*T[16]+3*T[17]+7*T[18]);if(Z>=R&&Ce>=R)return ba(e,c,t.subarray(l,l+u));if(Nt(e,c,1+(Z>Ce)),c+=2,Z>Ce){N=Hi(f,h),K=f,V=Hi(g,m),M=g;var oe=Hi($,O);for(Nt(e,c,b-257),Nt(e,c+5,I-1),Nt(e,c+10,L-4),c+=14,E=0;L>E;++E)Nt(e,c+3*E,$[Gc[E]]);c+=3*L;for(var ye=[S,x],$e=0;2>$e;++$e){var ae=ye[$e];for(E=0;ae.length>E;++E)Nt(e,c,oe[Ie=31&ae[E]]),c+=$[Ie],Ie>15&&(Nt(e,c,ae[E]>>>5&127),c+=ae[E]>>>12)}}else N=rm,K=$n,V=sm,M=ls;for(E=0;a>E;++E)if(i[E]>255){var Ie;bi(e,c,N[257+(Ie=i[E]>>>18&31)]),c+=K[Ie+257],Ie>7&&(Nt(e,c,i[E]>>>23&31),c+=fl[Ie]);var Se=31&i[E];bi(e,c,V[Se]),c+=M[Se],Se>3&&(bi(e,c,i[E]>>>5&8191),c+=hl[Se])}else bi(e,c,N[i[E]]),c+=K[i[E]];return bi(e,c,N[256]),c+K[256]},om=new si([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),am=(function(){for(var t=new si(256),e=0;256>e;++e){for(var n=e,i=9;--i;)n=(1&n&&3988292384)^n>>>1;t[e]=n}return t})(),Ao=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8};function lm(t,e){e===void 0&&(e={});var n=(function(){var d=4294967295;return{p(f){for(var h=d,p=0;f.length>p;++p)h=am[255&h^f[p]]^h>>>8;d=h},d(){return 4294967295^d}}})(),i=t.length;n.p(t);var r,s,o,a,l,u=(a=10+((r=e).filename&&r.filename.length+1||0),l=8,(function(d,f,h,p,g,m){var v=d.length,S=new lt(p+v+5*(1+Math.floor(v/7e3))+g),b=S.subarray(p,S.length-g),_=0;if(!f||8>v)for(var x=0;v>=x;x+=65535){var I=x+65535;v>I?_=ba(b,_,d.subarray(x,I)):(b[x]=!0,_=ba(b,_,d.subarray(x,v)))}else{for(var T=om[f-1],E=T>>>13,P=8191&T,$=(1<x;++x){var Ie=V(x),Se=32767&x,Be=L[Ie];if(O[Se]=Be,L[Ie]=Se,x>=$e){var yt=v-x;if((Ce>7e3||ye>24576)&&yt>423){_=Jc(d,b,0,M,R,Z,oe,ye,ae,x-ae,_),ye=Ce=oe=0,ae=x;for(var ge=0;286>ge;++ge)R[ge]=0;for(ge=0;30>ge;++ge)Z[ge]=0}var Ye=2,wt=0,mn=P,Re=Se-Be&32767;if(yt>2&&Ie==V(x-Re))for(var Pe=Math.min(E,yt)-1,Tt=Math.min(32767,x),Bn=Math.min(258,yt);Tt>=Re&&--mn&&Se!=Be;){if(d[x+Ye]==d[x+Ye-Re]){for(var qe=0;Bn>qe&&d[x+qe]==d[x+qe-Re];++qe);if(qe>Ye){if(Ye=qe,wt=Re,qe>Pe)break;var Dn=Math.min(Re,qe-2),$t=0;for(ge=0;Dn>ge;++ge){var Mt=x-Re+ge+32768&32767,ct=Mt-O[Mt]+32768&32767;ct>$t&&($t=ct,Be=Mt)}}}Re+=(Se=Be)-(Be=O[Se])+32768&32767}if(wt){M[ye++]=268435456|ya[Ye]<<18|Kc[wt];var sn=31&ya[Ye],gi=31&Kc[wt];oe+=fl[sn]+hl[gi],++R[257+sn],++Z[gi],$e=x+Ye,++Ce}else M[ye++]=d[x],++R[d[x]]}}_=Jc(d,b,!0,M,R,Z,oe,ye,ae,x-ae,_)}return Rf(S,0,p+Ff(_)+g)})(s=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):12+o.mem,a,l)),c=u.length;return(function(d,f){var h=f.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>f.level?4:f.level==9?2:0,d[9]=3,f.mtime!=0&&Ao(d,4,Math.floor(new Date(f.mtime||Date.now())/1e3)),h){d[3]=8;for(var p=0;h.length>=p;++p)d[p+10]=h.charCodeAt(p)}})(u,e),Ao(u,c-8,n.d()),Ao(u,c-4,i),u}var cm=!!qo||!!Za,Tf="text/plain",Mr=!1,$f=(t,e)=>{var n=t.split("#"),i=n[1],r=n[0].split("?"),s=r[0],o=r[1];if(!o)return t;var a=o.split("&").filter((l=>l.split("=")[0]!==e)).join("&");return s+(a?"?"+a:"")+(i?"#"+i:"")},ks=function(t,e,n){var i;n===void 0&&(n=!0);var r=t.split("?"),s=r[0],o=r[1],a=k({},e),l=(i=o?.split("&").map((c=>{var d,f=c.split("="),h=f[0],p=n&&(d=a[h])!==null&&d!==void 0?d:f[1];return delete a[h],h+"="+p})))!==null&&i!==void 0?i:[],u=(function(c,d){var f,h;d===void 0&&(d="&");var p=[];return ie(c,(function(g,m){C(g)||C(m)||m==="undefined"||(f=encodeURIComponent((v=>v instanceof File)(g)?g.name:g.toString()),h=encodeURIComponent(m),p[p.length]=h+"="+f)})),p.join(d)})(a);return u&&l.push(u),l.length>0?s+"?"+l.join("&"):s},Po=t=>{if(t.Ji)return t.Ji;var e=t.data,n=t.compression;if(e){if(n===je.GZipJS){var i=lm((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new lt(a.length+(a.length>>>1)),d=0,f=function(m){c[d++]=m},h=0;u>h;++h){if(d+5>c.length){var p=new lt(d+8+(u-h<<1));p.set(c),c=p}var g=a.charCodeAt(h);128>g?f(g):2048>g?(f(192|g>>>6),f(128|63&g)):g>55295&&57344>g?(f(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++h))>>>18),f(128|g>>>12&63),f(128|g>>>6&63),f(128|63&g)):(f(224|g>>>12),f(128|g>>>6&63),f(128|63&g))}return Rf(c,0,d)})(Yn(e)),{mtime:0});return{contentType:Tf,body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),estimatedSize:i.byteLength}}if(n===je.Base64){var r=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(Yn(e)),s=(a=>"data="+encodeURIComponent(typeof a=="string"?a:Yn(a)))(r);return{contentType:"application/x-www-form-urlencoded",body:s,estimatedSize:new Blob([s]).size}}var o=Yn(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},Mf=t=>{var e,n,i=()=>t.transport==="sendBeacon"?{url:ks(t.url,{compression:je.Base64}),encodedBody:Po(k({},t,{compression:je.Base64,Ji:void 0}))}:{url:$f(t.url,"compression"),encodedBody:Po(k({},t,{compression:void 0,Ji:void 0}))};try{e=Po(t)}catch(r){if(mc(t.compression,ii(t.url,"compression")))return A.error("Failed to gzip request body, sending uncompressed payload",r),i();throw r}return e&&mc(t.compression,ii(t.url,"compression"))&&!((n=e.body)instanceof ArrayBuffer?zo(new Uint8Array(n)):ArrayBuffer.isView(n)&&zo(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)))?(Mr=!0,i()):{url:t.url,encodedBody:e}},Lf=t=>{try{return Mf(t)}catch(e){return A.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},um=(function(){var t=se((function*(e){var n=Yn(e.data),i=yield(function(s,o,a){return Vo.apply(this,arguments)})(n,ne.DEBUG,{rethrow:!0});if(!i)return e;var r=yield i.arrayBuffer();return k({},e,{Ji:{contentType:Tf,body:r,estimatedSize:r.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),dm=/Failed to fetch|NetworkError|Load failed/i,Nf=t=>t?.name==="TypeError"&&dm.test(t?.message||""),Of=t=>{var e=Lf(t);if(e){var n=e.url,i=e.encodedBody,r=i??{},s=r.contentType,o=r.body,a=r.estimatedSize,l=new Headers;ie(t.headers,(function(p,g){l.append(g,p)})),s&&l.append("Content-Type",s);var u=null,c=!1;if(uc){var d=new uc;u={signal:d.signal,timeout:setTimeout((()=>{var p,g;c=!0,d.abort((p=t.timeout,(g=new Error("PostHog request timed out"+(p?" after "+p+"ms":""))).name="AbortError",g))}),t.timeout)}}var f=p=>{c&&p?.name==="AbortError"||Nf(p)?A.warn(p):A.error(p),t.callback==null||t.callback({statusCode:0,error:p})};try{var h;Za(n,k({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(h=u)==null?void 0:h.signal},t.fetchOptions)).then((p=>p.text().then((g=>{var m={statusCode:p.status,text:g};if(p.status===200)try{m.json=JSON.parse(g)}catch(v){A.error(v)}t.callback==null||t.callback(m)})))).catch(f).finally((()=>u?clearTimeout(u.timeout):null))}catch(p){u&&clearTimeout(u.timeout),f(p)}}},Ea=t=>{try{var e,n=Mf(t),i=n.url,r=n.encodedBody,s=r??{},o=s.body,a=s.estimatedSize;if(!o)return;var l=o instanceof Blob?o:new Blob([o],{type:s.contentType});if(Ue.sendBeacon(i,l))return;var u=U(t.data)?t.data:(e=t.data)==null?void 0:e.batch;if(U(u)&&u.length>1&&(a??0)>16384){var c=Math.ceil(u.length/2),d=f=>U(t.data)?f:k({},t.data,{batch:f});return Ea(k({},t,{data:d(u.slice(0,c))})),void Ea(k({},t,{data:d(u.slice(c))}))}A.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),Of(k({},t,{Yi:!0}))}catch(f){A.warn("Beacon send failed",f)}},Zc=(t,e,n,i)=>{var r=i==="query"?e==="POST"?"sent_at":"_":void 0;return ks(n===je.GZipJS?$f(t,"compression"):t,k({},r?{[r]:Date.now().toString()}:{},n===je.GZipJS?{}:{compression:n}))},Lr=[];Za&&Lr.push({transport:"fetch",method:Of}),qo&&Lr.push({transport:"XHR",method(t){var e=Lf(t);if(e){var n=new qo,i=e.encodedBody;n.open(t.method||"GET",e.url,!0);var r=i??{},s=r.contentType,o=r.body;ie(t.headers,(function(a,l){n.setRequestHeader(l,a)})),s&&n.setRequestHeader("Content-Type",s),t.timeout&&(n.timeout=t.timeout),n.onreadystatechange=()=>{if(n.readyState===4){var a={statusCode:n.status,text:n.responseText};if(n.status===200)try{a.json=JSON.parse(n.responseText)}catch{}t.callback==null||t.callback(a)}},n.send(o)}}}),Ue!=null&&Ue.sendBeacon&&Lr.push({transport:"sendBeacon",method:Ea});var Sa=3e3;class fm{constructor(e,n){this.Xi=!0,this.tr=[],this.er=Ct(n?.flush_interval_ms||Sa,250,5e3,A.createLogger("flush interval"),Sa),this.ir=e}enqueue(e){this.tr.push(e),this.rr||this.nr()}unload(){this.sr();var e=this.tr.length>0?this.ar():{},n=Object.values(e);[...n.filter((i=>i.url.indexOf("/e")===0)),...n.filter((i=>i.url.indexOf("/e")!==0))].map((i=>{this.lr(k({},i,{transport:"sendBeacon"}))}))}enable(){this.Xi=!1,this.nr()}nr(){var e=this;this.Xi||(this.rr=setTimeout((()=>{if(this.sr(),this.tr.length>0){var n=this.ar(),i=function(){var s=n[r],o=new Date().getTime();s.data&&U(s.data)&&ie(s.data,(a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp})),e.lr(s)};for(var r in n)i()}}),this.er))}lr(e){try{this.ir(e)}catch(n){A.error(n)}}sr(){clearTimeout(this.rr),this.rr=void 0}ar(){var e={};return ie(this.tr,(n=>{var i,r=n,s=(r?r.batchKey:null)||r.url;C(e[s])&&(e[s]=k({},r,{data:[]})),(i=e[s].data)==null||i.push(r.data)})),this.tr=[],e}}var hm=["retriesPerformedSoFar"];class pm{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!C(w)&&"onLine"in w.navigator&&(this.dr=w.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},ve(w,"online",this.vr),ve(w,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var n=e.retriesPerformedSoFar,i=ud(e,hm);Bt(n)&&(i.url=ks(i.url,{retry_count:n})),this._instance._send_request(k({},i,{callback:r=>{if(r.statusCode!==200&&(400>r.statusCode||r.statusCode>=500)){if((r.statusCode===0?3:10)>(n??0))return void this.At(k({retriesPerformedSoFar:n},i));r.statusCode===0&&A.warn("Request failed before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped retrying after "+(n??0)+" retries.")}i.callback==null||i.callback(r)}}))}At(e){var n=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=n+1;var i=(function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),c=Math.random()-.5;return Math.ceil(u+c*(u-l))})(n),r=Date.now()+i;this.tr.push({retryAt:r,requestOptions:e});var s="Enqueued failed request for retry in "+i;navigator.onLine||(s+=" (Browser is offline)"),A.warn(s),this.ur||(this.ur=!0,this.gr())}gr(){if(this.mr&&clearTimeout(this.mr),this.tr.length===0)return this.ur=!1,void(this.mr=void 0);this.mr=setTimeout((()=>{this.dr&&this.tr.length>0&&this.cr(),this.gr()}),this.hr)}cr(){var e=Date.now(),n=[],i=this.tr.filter((s=>e>s.retryAt||(n.push(s),!1)));if(this.tr=n,i.length>0)for(var r of i)this.retriableRequest(r.requestOptions)}unload(){for(var e of(this.mr&&(clearTimeout(this.mr),this.mr=void 0),this.ur=!1,C(w)||(this.vr&&(w.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(w.removeEventListener("offline",this.pr),this.pr=void 0)),this.tr)){var n=e.requestOptions;try{this._instance._send_request(k({},n,{transport:"sendBeacon"}))}catch(i){A.error(i)}}this.tr=[]}}class gm{constructor(e){this.yr=()=>{var n,i,r,s;this.br||(this.br={});var o=this.scrollElement(),a=this.scrollY(),l=o?Math.max(0,o.scrollHeight-o.clientHeight):0,u=a+(o?.clientHeight||0),c=o?.scrollHeight||0;this.br.lastScrollY=Math.ceil(a),this.br.maxScrollY=Math.max(a,(n=this.br.maxScrollY)!==null&&n!==void 0?n:0),this.br.maxScrollHeight=Math.max(l,(i=this.br.maxScrollHeight)!==null&&i!==void 0?i:0),this.br.lastContentY=u,this.br.maxContentY=Math.max(u,(r=this.br.maxContentY)!==null&&r!==void 0?r:0),this.br.maxContentHeight=Math.max(c,(s=this.br.maxContentHeight)!==null&&s!==void 0?s:0)},this._instance=e}get _r(){return this._instance.config.scroll_root_selector}getContext(){return this.br}resetContext(){var e=this.br;return setTimeout(this.yr,0),e}startMeasuringScrollPosition(){ve(w,"scroll",this.yr,{capture:!0}),ve(w,"scrollend",this.yr,{capture:!0}),ve(w,"resize",this.yr)}scrollElement(){if(!this._r)return w?.document.documentElement;var e=U(this._r)?this._r:[this._r];for(var n of e){var i=w?.document.querySelector(n);if(i)return i}}wr(e){var n=e==="y"?"scrollTop":"scrollLeft";if(this._r){var i=this.scrollElement();return i&&i[n]||0}return w?e==="y"?w.scrollY||w.pageYOffset||w.document.documentElement.scrollTop||0:w.scrollX||w.pageXOffset||w.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var mm=t=>Sf(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class Xc{constructor(e,n,i,r){this.kr=s=>{var o=this.Sr();if(!o||o.sessionId!==s){var a={sessionId:s,props:this.Cr(this._instance)};this.Mr.register({[ua]:a})}},this._instance=e,this.Tr=n,this.Mr=i,this.Cr=r||mm,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[ua]}getSetOnceProps(){var e,n=(e=this.Sr())==null?void 0:e.props;return n?"r"in n?xf(n,this._instance.config.disable_capture_url_hashes):{$referring_domain:n.referringDomain,$pathname:n.initialPathName,utm_source:n.utm_source,utm_campaign:n.utm_campaign,utm_medium:n.utm_medium,utm_content:n.utm_content,utm_term:n.utm_term}:{}}getSessionProps(){var e={};return ie(ll(this.getSetOnceProps()),((n,i)=>{i==="$current_url"&&(i="url"),e["$session_entry_"+Go(i)]=n})),e}}class pl{on(e,n){return this.Er[e]||(this.Er[e]=[]),this.Er[e].push(n),()=>{this.Er[e]=this.Er[e].filter((i=>i!==n))}}emit(e,n){for(var i of this.Er[e]||[])i(n);for(var r of this.Er["*"]||[])r(e,n)}constructor(){this.Er={}}}var Si=pe("[SessionId]");class Qc{on(e,n){return this.Ir.on(e,n)}constructor(e,n,i){var r;if(this.Pr=null,this.Rr=[],this.Ar=void 0,this.Fr=!1,this.Ir=new pl,this.Lr=(u,c)=>!(!Bt(u)||!Bt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===Ht)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Ne=e.config,this.Mr=e.persistence,this.Or=void 0,this.Dr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.$r=n||Ut,this.Nr=i||Ut;var s=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*Ct(this.Ne.session_idle_timeout_seconds||1800,60,36e3,Si.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.qr(),this.jr="ph_"+s+"_window_id",this.Br="ph_"+s+"_primary_window_exists",this.Hr()){var o=be.H(this.jr),a=be.H(this.Br);o&&!a?this.Or=o:be.q(this.jr),be.F(this.Br,!0)}if((r=this.Ne.bootstrap)!=null&&r.sessionID)try{var l=(u=>{var c=this.Ne.bootstrap.sessionID.replace(/-/g,"");if(c.length!==32)throw new Error("Not a valid UUID");if(c[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(c.substring(0,12),16)})();this.Ur(this.Ne.bootstrap.sessionID,new Date().getTime(),l)}catch(u){Si.error("Invalid sessionID in bootstrap",u)}this.zr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return C(this.Rr)&&(this.Rr=[]),this.Rr.push(e),this.Dr&&e(this.Dr,this.Or),()=>{this.Rr=this.Rr.filter((n=>n!==e))}}Hr(){return this.Ne.persistence!=="memory"&&!this.Mr.xi&&be.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&be.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?be.H(this.jr):null}Zr(e){var n=this.Pr;return!Ke(n)&&!Ke(e)&&5e3>Math.abs(e-n)}Ur(e,n,i){var r=n!==this._sessionActivityTimestamp,s=!(e!==this.Dr||i!==this._sessionStartTimestamp);this._sessionStartTimestamp=i,this._sessionActivityTimestamp=n,this.Dr=e,s&&!r||s&&this.Zr(n)||(this.Pr=n,this.Mr.register({[Kn]:[n,e,i]}))}Gr(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return Bt(n)&&n>0}Qr(){this.Gr()?this.Mr.refreshKey(Kn):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!Ke(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this.Pr){this.Qr();var n=this.Jr();n[1]===this.Dr&&n[2]===this._sessionStartTimestamp&&(this.Pr=this._sessionActivityTimestamp,this.Mr.register({[Kn]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],n=Bt(e)?e:0,i=Bt(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(n,i)}Xr(e){return this.Qr(),this.Lr(e,this.Yr())}Jr(){var e=this.Mr.props[Kn];return U(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Pr=null,clearTimeout(this.tn),this.tn=void 0,this.Ur(null,null,null)}destroy(){this.Fr=!0,this.Kr(),clearTimeout(this.tn),this.tn=void 0,this.Ar&&w&&(w.removeEventListener(ns,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&be.q(this.Br)},ve(w,ns,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=null),this.Ne.cookieless_mode===Ht)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var i=n||new Date().getTime(),r=this.Jr(),s=r[1],o=r[2],a=this.Yr(),l=this.Vr(),u=Bt(o)&&Math.abs(i-o)>864e5,c=!1,d=!1,f=!s,h=s,p=!f&&!e&&this.Lr(i,a);if(p){(p=this.Xr(i))||Si.info("cross-tab refresh kept the session alive",{sessionId:s});var g=this.Jr();s=g[1],o=g[2]}f||p||u?(s=this.$r(),l=this.Nr(),Si.info("new session ID generated",{sessionId:s,windowId:l,changeReason:{noSessionId:f,activityTimeout:p,sessionPastMaximumLength:u}}),o=i,c=!0):(l||(l=this.Nr(),c=!0),(d=s!==h)&&(Si.info("adopted cross-tab session id",{sessionId:s,windowId:l}),c=!0));var m=Bt(a)&&e&&!u?a:i,v=Bt(o)?o:new Date().getTime();this.Wr(l),this.Ur(s,m,v),e||this.qr();var S={noSessionId:f,activityTimeout:p,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((b=>b(s,l,S))),{sessionId:s,windowId:l,sessionStartTimestamp:v,changeReason:c?S: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 Bf=function(t,e){if(!t)return!1;var n=t.userAgent;if(n&&_c(n,e))return!0;try{var i=t?.userAgentData;if(i!=null&&i.brands&&i.brands.some((r=>_c(r?.brand,e))))return!0}catch{}return!!t.webdriver};function Df(){return(Df=se((function*(){var t=Ue?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),n=e?.model;return X(n)&&n.length>0?n:void 0}catch(i){return void A.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",i)}}))).apply(this,arguments)}var cs=function(t,e){if(!(function(n){try{new RegExp(n)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function Fo(t,e,n){return Yn({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}var jf={exact:(t,e)=>e.some((n=>t.some((i=>n===i)))),is_not:(t,e)=>e.every((n=>t.every((i=>n!==i)))),regex:(t,e)=>e.some((n=>t.some((i=>cs(n,i))))),not_regex:(t,e)=>e.every((n=>t.every((i=>!cs(n,i))))),icontains:(t,e)=>e.map(Er).some((n=>t.map(Er).some((i=>n.includes(i))))),not_icontains:(t,e)=>e.map(Er).every((n=>t.map(Er).every((i=>!n.includes(i))))),gt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>i>parseFloat(r)))})),lt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>it.toLowerCase();function Uf(t,e){return!t||Object.entries(t).every((n=>{var i=n[1],r=e?.[n[0]];if(C(r)||Ke(r))return!1;var s=[String(r)],o=jf[i.operator];return!!o&&o(i.values,s)}))}var xa="custom",eu="i.posthog.com",vm=/^\/static\//;class _m{constructor(e){this.en={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,n=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return n||(n=this.apiHost.replace("."+eu,".posthog.com")),n==="https://app.posthog.com"?"https://us.posthog.com":n}get region(){return this.en[this.apiHost]||(this.en[this.apiHost]=/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"us":/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"eu":xa),this.en[this.apiHost]}rn(e){if(vm.test(e)){var n=this.instance.config.asset_host;if(typeof n=="string")return n.trim().replace(/\/$/,"")||void 0}}endpointFor(e,n){if(n===void 0&&(n=""),n&&(n=n[0]==="/"?n:"/"+n),e==="ui")return this.uiHost+n;if(e==="flags")return this.flagsApiHost+n;if(e==="assets"){var i=this.rn(n);if(i)return""+i+n}if(this.region===xa)return this.apiHost+n;var r=eu+n;switch(e){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}}function Hf(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var Q=pe("[Surveys]"),Wf="seenSurvey_",qf=t=>{try{var e=(n=>((i,r)=>""+Wf+(function(s){return s.current_iteration&&s.current_iteration>0?s.id+"_"+s.current_iteration:s.id})(r))(0,n))(t);if(localStorage.getItem(e))return;localStorage.setItem(e,"true")}catch(n){Q.error("Failed to persist survey seen state",n)}},ym=[Io.Popover,Io.Widget,Io.API],wm={ignoreConditions:!1,ignoreDelay:!1,displayType:_a.Popover},bm=pe("[PostHog ExternalIntegrations]"),Em={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class Sm{constructor(e){this._instance=e}ai(e,n){var i;(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,e,(r=>{if(r)return bm.error("failed to load script",r);n()}))}startIfEnabledOrStop(){var e=this,n=function(){var s,o,a,l=i[0],u=i[1];!u||(s=B.__PosthogExtensions__)!=null&&(s=s.integrations)!=null&&s[l]||e.ai(Em[l],(()=>{var c;(c=B.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=B.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=B.__PosthogExtensions__)==null||(a=a.integrations)==null||(a=a[l])==null||a.stop())};for(var i of Object.entries((r=this._instance.config.integrations)!==null&&r!==void 0?r:{})){var r;n()}}}class xm{constructor(e,n){this.rt=e,this.nn=n,this.sn=new Map,this.an=!1}add(e){var n=this;return se((function*(){if(n.an)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(n.sn.has(e.name))throw new Error('Browser extension "'+e.name+'" is already registered');n.sn.set(e.name,e);try{var i=e.setup(n.nn);i&&(yield i)}catch(s){var r=n.sn.get(e.name)===e;r&&n.sn.delete(e.name),n.rt.error('Failed to set up browser extension "'+e.name+'"',s),r&&n.ln(e)}}))()}dispose(){if(!this.an){this.an=!0;var e=Array.from(this.sn.values()).reverse();for(var n of(this.sn.clear(),e))this.ln(n)}}ln(e){try{var n=e.dispose==null?void 0:e.dispose();n&&De(n.then)&&n.then(void 0,(i=>{this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}))}catch(i){this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}}}class Im{constructor(e){this._instance=e}initialize(){}get(e){var n=this._instance.persistence;if(typeof e=="string")return n?.get_property(e);var i={};for(var r of e){var s=n?.get_property(r);C(s)||(i[r]=s)}return i}set(e,n){var i;(i=this._instance.persistence)==null||i.register(typeof e=="string"?{[e]:n}:e)}remove(e){var n;(n=this._instance.persistence)==null||n.unregister(e)}}var tu="extensionsRemoteConfig";class km{constructor(e){this.an=!1,this.instance=e,this.rt=A,this.un=e.hn,this.kv=new Im(e),this.onEvent=n=>br(this.instance.on("eventCaptured",(i=>{try{n({event:i.event,properties:i.properties})}catch(r){this.rt.error("Browser extension event listener failed",r)}}))),this.onRemoteConfig=n=>{if(this.an)return br((()=>{}));var i=s=>{try{n(s)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},r=this.instance.dn.on(tu,i);return this.un&&i(this.un),br(r)},this.vn=new xm(A.createLogger("[BrowserExtensions]"),this)}get logger(){return this.rt}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return(e=this.instance.get_property(Yi))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(Yi);return typeof e=="string"?e:void 0}get library(){return{name:ne.LIB_NAME,version:ne.LIB_VERSION}}get initialPersonProperties(){var e,n;return(e=(n=this.instance.persistence)==null?void 0:n.get_initial_props())!==null&&e!==void 0?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,n,i,r,s=(e=this.instance.sessionManager)==null?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:(n=s?.sessionId)!==null&&n!==void 0?n:"",windowId:(i=s?.windowId)!==null&&i!==void 0?i:"",sessionStartTimestamp:(r=s?.sessionStartTimestamp)!==null&&r!==void 0?r:0}}catch{return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get projectToken(){return this.instance.config.token}add(e){return this.vn.add(e)}capture(e,n,i){var r=this;return se((function*(){i?r.instance.capture(e,n,{timestamp:i.timestamp,uuid:i.uuid,$set:i.set,$set_once:i.setOnce}):r.instance.capture(e,n)}))()}registerDynamicEventProperties(e){return br(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(tu,e))}sendRequest(e,n){var i=this;return se((function*(){var r;n===void 0&&(n={});var s=i.instance.requestRouter.endpointFor((r=n.target)!==null&&r!==void 0?r:"api",e),o={method:n.method,url:n.query?ks(s,n.query):s,data:n.body,headers:n.headers,timeout:n.timeoutMs,fireCallbackOnDrop:!0,transport:n.transport,compression:n.compression,timestampMode:n.sentAt};return n.transport==="sendBeacon"?(i.instance._send_request(o),{statusCode:202}):new Promise((a=>{o.callback=a,i.instance._send_request(o)}))}))()}dispose(){this.an||(this.an=!0,this.vn.dispose())}}var Wi={},Ro=0,us=()=>{},nu='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',xi="Surveys module not available",iu="sanitize_properties is deprecated. Use before_send instead",zf="Invalid value for property_denylist config: ",Cm=["token","distinct_id",Zd],Gn="posthog",Vf=!cm&&Ve?.indexOf("MSIE")===-1&&Ve?.indexOf("Mozilla")===-1,To=t=>{var e;return k({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:Ag(F?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:us,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:t??"unset",__preview_deferred_init_extensions:!1,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:me&&X(me?.search)&&me.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disableDeviceModel:!1,disable_external_dependency_loading:!1,strict_script_versioning:!1,enable_recording_console_log:void 0,secure_cookie:(w==null||(e=w.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(n){A.error("Bad HTTP status: "+n.statusCode+" "+n.text)},get_device_id:n=>n,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:pa,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:Sa},error_tracking:{},_onCapture:us},(n=>({rageclick:n&&n>="2026-05-30"?{content_ignorelist:jg,ignore_text_selection:!0}:!n||"2025-11-30">n||{content_ignorelist:!0},capture_pageview:!n||"2025-05-24">n||"history_change",session_recording:n&&n>="2026-06-25"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6},streamNetworkBody:!0}:n&&n>="2026-05-30"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6}}:n&&n>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:n&&n>="2026-01-30"?"head":"body",internal_or_test_user_hostname:n&&n>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:n&&n>="2026-05-30"?250:0,split_storage:!(!n||"2026-05-30">n),detect_google_search_app:!(!n||"2026-05-30">n),disable_capture_url_hashes:!(!n||"2026-06-25">n)}))(t))},Am=[["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"]],ru=t=>{var e={};for(var n of Am){var i=n[0],r=n[1];C(t[i])||(e[r]=t[i])}var s=fe({},e,t),o=t.__preview_external_dependency_versioned_paths;return C(o)||(C(t.strict_script_versioning)&&(s.strict_script_versioning=!!o),X(o)&&C(t.asset_host)&&(s.asset_host=o)),U(t.property_blacklist)&&(C(t.property_denylist)?s.property_denylist=t.property_blacklist:U(t.property_denylist)?s.property_denylist=[...t.property_blacklist,...t.property_denylist]:A.error(zf+t.property_denylist)),s};class Pm{constructor(){this.__forceAllowLocalhost=!1}get fn(){return this.__forceAllowLocalhost}set fn(e){A.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class Je{pn(e,n){if(e){var i=this.sn.indexOf(e);i!==-1&&this.sn.splice(i,1)}return this.sn.push(n),n.initialize==null||n.initialize(),n}gn(){return this.config.cookieless_mode===Ht||this.config.cookieless_mode===kn&&this.consent.isRejected()}get decideEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){var e;this.webPerformance=new Pm,this.mn=!1,this.version=ne.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new pl,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=To(),this.SentryIntegration=Kg,this.sentryIntegration=i=>(function(r,s){var o=mf(r,s);return{name:gf,processEvent:a=>o(a)}})(this,i),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.wn=!1,this.kn=null,this.xn=null,this.Sn=null,this.scrollManager=new gm(this),this.pageViewManager=new Wc(this),this.rateLimiter=new im(this),this.requestRouter=new _m(this),this.consent=new Lg(this),this.externalIntegrations=new Sm(this);var n=(e=Je.__defaultExtensionClasses)!==null&&e!==void 0?e:{};this.featureFlags=n.featureFlags&&new n.featureFlags(this),this.toolbar=n.toolbar&&new n.toolbar(this),this.surveys=n.surveys&&new n.surveys(this),this.conversations=n.conversations&&new n.conversations(this),this.logs=n.logs&&new n.logs(this),this.metrics=n.metrics&&new n.metrics(this),this.experiments=n.experiments&&new n.experiments(this),this.exceptions=n.exceptions&&new n.exceptions(this),this.people={set:(i,r,s)=>{var o=X(i)?{[i]:r}:i;this.setPersonProperties(o),s?.({})},set_once:(i,r,s)=>{var o=X(i)?{[i]:r}:i;this.setPersonProperties(void 0,o),s?.({})}},this.on("eventCaptured",(i=>A.info('send "'+i?.event+'"',i)))}init(e,n,i){if(i&&i!==Gn){var r,s=(r=Wi[i])!==null&&r!==void 0?r:new Je;return s._init(e,n,i),Wi[i]=s,Wi[Gn][i]=s,s}return this._init(e,n,i)}_init(e,n,i){var r,s;n===void 0&&(n={});var o,a=X(e)?e.trim():"";if(!a)return A.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return a!==((o=this.config)==null?void 0:o.token)?console.warn("[PostHog.js]","You have already initialized PostHog with a different project token! Re-initializing is a no-op, so events will keep going to the project this instance was initialized with. To capture into a second project, load PostHog once, then initialize a named instance after the SDK has loaded, e.g. posthog.init('"+a+"', { ... }, 'project2')"):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=To(n.defaults),n.debug=this.Cn(n.debug),this.Mn=n,this.Tn=[],n.person_profiles?this.xn=n.person_profiles:n.process_person&&(this.xn=n.process_person);var l=To(n.defaults),u=ru(n),c=fe({},l,u,{name:i,token:a});he(l.rageclick)&&he(u.rageclick)&&(c.rageclick=fe({},l.rageclick,u.rageclick)),he(l.session_recording)&&he(u.session_recording)&&(c.session_recording=fe({},l.session_recording,u.session_recording)),this.set_config(c),this.config.on_xhr_error&&A.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=n.disable_compression?void 0:je.GZipJS;var d=this.En();if(this.persistence=new xo(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new xo(k({},this.config,{persistence:"sessionStorage"}),d,!1),this.bn="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&be.N()){var f=be.H(this.bn);U(f)&&f.forEach((I=>{X(I)&&this.yn.add(I)}))}else be.q(this.bn);var h=k({},this.persistence.props),p=k({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new fm((I=>this.Pn(I)),this.config.request_queue_config),this.Rn=new pm(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new Qc(this),this.sessionPropsManager=new Xc(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((I,T,E)=>{(E!=null&&E.activityTimeout||E!=null&&E.sessionPastMaximumLength||E!=null&&E.crossTabAdoption)&&this.An()}))),this.Fn(),this.config.__preview_deferred_init_extensions?(A.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Ln(g)}),0)):(A.info("Initializing extensions synchronously"),this.Ln(g)),ne.DEBUG=ne.DEBUG||this.config.debug,ne.DEBUG&&A.info("Starting in debug mode",{this:this,config:n,thisC:k({},this.config),p:h,s:p}),!this.config.identity_distinct_id||(r=n.bootstrap)!=null&&r.distinctID||(n.bootstrap=k({},n.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((s=n.bootstrap)==null?void 0:s.distinctID)!==void 0){var m=n.bootstrap.distinctID,v=this.get_distinct_id(),S=this.persistence.get_property(ot);if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&S===Un)this.identify(m);else if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&S===vn)A.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{var b=this.config.get_device_id(Ut()),_=n.bootstrap.isIdentifiedID?b:m;this.persistence.set_property(ot,n.bootstrap.isIdentifiedID?vn:Un),this.register({distinct_id:m,$device_id:_})}}if(g)this.register_once({distinct_id:mr,$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(ot,Un)}return ve(w,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),n.segment?(function(I,T){var E=I.config.segment;if(!E)return T();(function(P,$){var O=P.config.segment;if(!O)return $();var L=K=>{var V=()=>K.anonymousId()||Ut();P.config.get_device_id=V,K.id()&&(P.register({distinct_id:K.id(),$device_id:V()}),P.persistence.set_property(ot,vn)),$()},N=O.user();"then"in N&&De(N.then)?N.then(L):L(N)})(I,(()=>{E.register((P=>{typeof Promise<"u"&&Promise.resolve||Eo.warn("This browser does not have Promise support, and can not use the segment integration");var $=(O,L)=>{if(!L)return O;O.event.userId||O.event.anonymousId===P.get_distinct_id()||(Eo.info("No userId set, resetting PostHog"),P.reset()),O.event.userId&&O.event.userId!==P.get_distinct_id()&&(Eo.info("UserId set, identifying with PostHog"),P.identify(O.event.userId));var N=P.calculateEventProperties(L,O.event.properties);return O.event.properties=Object.assign({},N,O.event.properties),O};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:O=>$(O,O.event.event),page:O=>$(O,Vn),identify:O=>$(O,yo),screen:O=>$(O,"$screen")}})(I)).then((()=>{T()}))}))})(this,(()=>this.On())):this.On(),De(this.config._onCapture)&&this.config._onCapture!==us&&(A.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(I=>this.config._onCapture(I.event,I)))),this.config.ip&&A.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this.config.disableDeviceModel||(function(){return Df.apply(this,arguments)})().then((I=>{I&&this.register({[vo]:I})})).catch(us),this}Fn(){var e,n,i,r,s,o,a=(e=(n=this.config.__extensionClasses)==null?void 0:n.featureFlags)!==null&&e!==void 0?e:(i=Je.__defaultExtensionClasses)==null?void 0:i.featureFlags;a&&(this.featureFlags&&this.featureFlags instanceof a||((r=this.Dn)==null||r.call(this),this.Dn=void 0,this.featureFlags=new a(this)),De(this.featureFlags.onReloading)&&De(this.featureFlags.setup)?this.Dn||(this.Dn=this.featureFlags.onReloading((()=>{this.dn.emit("featureFlagsReloading",!0)})),this.$n().add(this.featureFlags)):(s=(o=this.featureFlags).initialize)==null||s.call(o))}Ln(e){var n,i,r,s,o,a,l,u=performance.now(),c=k({},Je.__defaultExtensionClasses,this.config.__extensionClasses),d=[];c.exceptions&&this.sn.push(this.exceptions=(n=this.exceptions)!==null&&n!==void 0?n:new c.exceptions(this)),c.historyAutocapture&&this.sn.push(this.historyAutocapture=new c.historyAutocapture(this)),c.tracingHeaders&&this.sn.push(this.tracingHeaders=new c.tracingHeaders(this)),c.siteApps&&this.sn.push(this.siteApps=new c.siteApps(this)),c.sessionRecording&&!e&&this.sn.push(this.sessionRecording=new c.sessionRecording(this)),this.config.disable_scroll_properties||d.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),c.autocapture&&this.sn.push(this.autocapture=new c.autocapture(this)),c.surveys&&this.sn.push(this.surveys=(i=this.surveys)!==null&&i!==void 0?i:new c.surveys(this)),c.logs&&this.sn.push(this.logs=(r=this.logs)!==null&&r!==void 0?r:new c.logs(this)),c.metrics&&this.sn.push(this.metrics=(s=this.metrics)!==null&&s!==void 0?s:new c.metrics(this)),c.conversations&&this.sn.push(this.conversations=(o=this.conversations)!==null&&o!==void 0?o:new c.conversations(this)),c.productTours&&this.sn.push(this.productTours=new c.productTours(this)),c.heatmaps&&this.sn.push(this.heatmaps=new c.heatmaps(this)),c.webVitalsAutocapture&&this.sn.push(this.webVitalsAutocapture=new c.webVitalsAutocapture(this)),c.exceptionObserver&&this.sn.push(this.exceptionObserver=new c.exceptionObserver(this)),c.deadClicksAutocapture&&this.sn.push(this.deadClicksAutocapture=new c.deadClicksAutocapture(this,Gg)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((f=>{f.initialize&&d.push((()=>{f.initialize==null||f.initialize()}))})),d.push((()=>{if(this.Nn){var f=this.Nn;this.Nn=void 0,this.sn.forEach((h=>h.onRemoteConfig==null?void 0:h.onRemoteConfig(f)))}})),this.qn(d,u)}qn(e,n){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,n)}),0);var i=e.shift();if(i)try{i()}catch(s){A.error("Error initializing extension:",s)}}var r=Math.round(performance.now()-n);this.register_for_session({[Xd]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[Qd]:r}),this.config.__preview_deferred_init_extensions&&A.info("PostHog extensions initialized ("+r+"ms)")}Zi(e){var n;if(!F||!F.body)return A.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.Zi(e)}),500);if(this.config.__preview_deferred_init_extensions&&(this.Nn=e),this.hn=e,this.compression=void 0,e.ok){var i,r=e.config;r.supportedCompression&&!this.config.disable_compression&&(this.compression=j(r.supportedCompression,je.GZipJS)?je.GZipJS:j(r.supportedCompression,je.Base64)?je.Base64:void 0),(i=r.analytics)!=null&&i.endpoint&&(this.analyticsDefaultEndpoint=r.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:pa}),(n=this.jn)==null||n.handleRemoteConfig(e),this.sn.forEach((s=>s.onRemoteConfig==null?void 0:s.onRemoteConfig(e)))}On(){try{this.config.loaded(this)}catch(i){A.critical("`loaded` function failed",i)}if(this.Bn(),this.config.internal_or_test_user_hostname&&me!=null&&me.hostname){var e=me.hostname,n=this.config.internal_or_test_user_hostname;(typeof n=="string"?e===n:n.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.gn())&&this.Hn()}),1),this.Un=new kf(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()&&vr(this.__request_queue,(e=>this.Pn(e))),this.__request_queue=[],this.Bn()}_handle_unload(){var e,n,i,r,s;(e=this.surveys)==null||e.handlePageUnload==null||e.handlePageUnload(),(n=this.metrics)==null||n.flush("sendBeacon"),this.config.request_batching?(this.zn()&&this.capture(_o),(i=this.logs)==null||i.flushLogs("sendBeacon"),(r=this.In)==null||r.unload(),(s=this.Rn)==null||s.unload()):this.zn()&&this.capture(_o,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?Vf?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)?e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:429})):(e.transport=e.transport||this.config.api_transport,e.headers=k({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,(C(this.config.disable_beacon)?this.config.__preview_disable_beacon:this.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(n=>{var i,r,s,o=k({},n);o.timeout=o.timeout||6e4;var a,l,u,c,d,f=(i=o.transport)!==null&&i!==void 0?i:"fetch";f==="sendBeacon"&&C(o.compression)&&o.data&&(o.compression=je.Base64),o.method==="POST"&&o.data&&(o.timestampMode==="capture-body"?o.data={api_key:(l=(d=(c=U(a=o.data)?a:[a])[0])==null||(u=d.properties)==null?void 0:u.token)!==null&&l!==void 0?l:d?.token,batch:c,sent_at:new Date().toISOString()}:o.timestampMode==="body"&&(o.data=(function(m,v){return v===void 0&&(v=new Date().toISOString()),U(m)?m.map((S=>k({},S,{sent_at:v}))):k({},m,{sent_at:v})})(o.data))),o.url=Zc(o.url,o.method,o.compression,o.timestampMode);var h=Lr.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),p=(r=(s=(function(m,v){for(var S=0;m.length>S;S++)if(m[S].transport===f)return m[S]})(h))==null?void 0:s.method)!==null&&r!==void 0?r:h[0].method;if(!p)throw new Error("No available transport method");var g=m=>{try{p(m)}catch(v){Nf(v)?A.warn(v):A.error(v),o.callback==null||o.callback({statusCode:0,error:v})}};f!=="sendBeacon"&&o.data&&o.compression===je.GZipJS&&Fp&&typeof Promise<"u"&&!Mr?um(o).then((m=>{g(m)})).catch((m=>{if(vc(m))return Mr=!0,void g(k({},o,{compression:void 0,url:Zc(n.url,n.method,void 0,n.timestampMode)}));(v=>{if(!v||typeof v!="object")return!1;var S="name"in v?String(v.name):"";return vc(v)||S===dd})(m)&&(Mr=!0),g(o)})):p(o)})(k({},e,{callback:n=>{var i,r;this.rateLimiter.checkForLimiting(n),400>n.statusCode||(i=(r=this.config).on_request_error)==null||i.call(r,n),e.callback==null||e.callback(n)}}))):e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:0}))}Pn(e){this.Rn?this.Rn.retriableRequest(e):this._send_request(e)}_execute_array(e){Ro++;try{var n,i=[],r=[],s=[];vr(e,(a=>{if(a)if(U(n=a[0]))s.push(a);else if(De(a))try{a.call(this)}catch(l){A.error("Error executing queued PostHog call",a,l)}else U(a)&&n==="alias"?i.push(a):U(a)&&n.indexOf("capture")!==-1&&De(this[n])?s.push(a):r.push(a)}));var o=function(a,l){vr(a,(function(u){try{if(U(u[0])){var c=l;ie(u,(function(d){c=c[d[0]].apply(c,d.slice(1))}))}else l[u[0]].apply(l,u.slice(1))}catch(d){A.error("Error executing queued PostHog call",u,d)}}))};o(i,this),o(r,this),o(s,this)}finally{Ro--}}push(e){if(Ro>0&&U(e)&&X(e[0])){var n=Je.prototype[e[0]];De(n)&&n.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,n,i){var r,s,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.In){if(this.is_capturing())if(!C(e)&&X(e)){var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var c=i!=null&&i.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(c==null||!c.isRateLimited){n!=null&&n.$current_url&&!X(n?.$current_url)&&(A.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),n==null||delete n.$current_url),e!=="$exception"||i!=null&&i.Wn||A.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,f=i?.timestamp||d,h=Ec(i?.uuid,Ut),p={uuid:h,event:e,properties:this.calculateEventProperties(e,n||{},f,h)};e===Vn&&this.config.__preview_capture_bot_pageviews&&u&&(p.event="$bot_pageview",p.properties.$browser_type="bot"),c&&(p.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&p.properties.$feature_flag_has_experiment===!1&&this.get_property(Zr)===!0;i?.$set&&!g&&(p.$set=i?.$set);var m=i?.$unset;m&&(p.$unset=m);var v,S,b,_=g?void 0:this.Vn(i?.$set_once,e!==Ac,e===yo);if(_&&(p.$set_once=_),i!=null&&i._noTruncate||(s=this.config.properties_string_max_length,o=p,a=L=>X(L)?L.slice(0,s):L,l=new Set,p=(function L(N,K){if(N!==Object(N))return a?a(N):N;if(!l.has(N)){var V;if(l.add(N),U(N))V=[],vr(N,(R=>{V.push(L(R))}));else{var M={};ie(N,((R,Z)=>{l.has(R)||(M[Z]=L(R))})),V=M}return V}})(o)),p.timestamp=f,C(i?.timestamp)||(p.properties.$event_time_override_provided=!0,p.properties.$event_time_override_system_time=d),g&&(p.properties=(function(L,N){N===void 0&&(N=[]);var K={},V=M=>{L[M]!==void 0&&(K[M]=L[M])};return Rp.forEach(V),N.forEach(V),K})(p.properties,Cm)),e===qt.DISMISSED||e===qt.SENT){var x=n?.[ko.SURVEY_ID],I=n?.[ko.SURVEY_ITERATION];qf({id:x,current_iteration:I}),p.$set=k({},p.$set,{[(v={id:x,current_iteration:I},S=e===qt.SENT?"responded":"dismissed",b="$survey_"+S+"/"+v.id,v.current_iteration&&v.current_iteration>0&&(b="$survey_"+S+"/"+v.id+"/"+v.current_iteration),b)]:!0})}else e===qt.SHOWN&&(p.$set=k({},p.$set,{[ko.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===nm.SHOWN){var T=n?.[zc.TOUR_TYPE];T&&(p.$set=k({},p.$set,{[zc.TOUR_LAST_SEEN_DATE+"/"+T]:new Date().toISOString()}))}var E=k({},p.properties.$set,p.$set);if(Gt(E)||this.setPersonPropertiesForFlags(E),!H(this.config.before_send)){var P=this.Pt(p);if(!P)return;(p=P).uuid=Ec(p.uuid,Ut)}this.dn.emit("eventCaptured",p);var $=(r=i?._url)!==null&&r!==void 0?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),O={method:"POST",url:$,data:p,compression:"best-available",timestampMode:i?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test($)?"body":"capture-body",batchKey:i?._batchKey,transport:i?.transport};return!this.config.request_batching||i&&(i==null||!i._batchKey)||i!=null&&i.send_instantly?this.Pn(O):this.In.enqueue(O),p}A.critical("This capture call is ignored due to client rate limiting.")}}else A.error("No event name provided to posthog.capture")}else A.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(n=>e(n.event,n)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new km(this)}cn(e){this._n.push(e);var n=!0;return()=>{if(n){n=!1;var i=this._n.indexOf(e);i!==-1&&this._n.splice(i,1)}}}calculateEventProperties(e,n,i,r,s){if(i=i||new Date,!this.persistence||!this.sessionPersistence)return n;var o=s?void 0:this.persistence.remove_event_timer(e),a=k({},n);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.gn()&&(a[Zd]=!0),e==="$snapshot"){var l=k({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!X(a.distinct_id)&&!ke(a.distinct_id)||Ko(a.distinct_id))&&A.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=(function(x,I,T,E){var P,$,O,L;if(E===void 0&&(E=!1),!Ve)return{};var N,K=x?[...ri,...I||[]]:[],V=(function(Bn){for(var qe=0;wc.length>qe;qe++){var Dn=wc[qe],$t=Dn[1],Mt=Dn[0].exec(Bn),ct=Mt&&(De($t)?$t(Mt,Bn):$t);if(ct)return ct}return["",""]})(Ve),M=V[0],R=V[1],Z=(N=typeof navigator<"u"?navigator:void 0)!=null&&N.brave?{brave:!0}:{},Ce={};C(T)||(Ce.detectGoogleSearchApp=T);var oe={},ye=(P=navigator)==null||(P=P.userAgentData)==null?void 0:P.platform,$e=($=navigator)==null?void 0:$.maxTouchPoints,ae=w==null||(O=w.screen)==null?void 0:O.width,Ie=w==null||(L=w.screen)==null?void 0:L.height,Se=w?.devicePixelRatio;C(ye)||(oe.userAgentDataPlatform=ye),C($e)||(oe.maxTouchPoints=$e),C(ae)||(oe.screenWidth=ae),C(Ie)||(oe.screenHeight=Ie),C(Se)||(oe.devicePixelRatio=Se);var Be,yt,ge,Ye,wt,mn,Re,Pe,Tt=fe(ll({$os:M,$os_version:R,$browser:Nd(Ve,navigator.vendor,Z,Ce),$device:bc(Ve),$device_type:(yt=Ve,ge=oe,Pe=bc(yt),Pe===_d||Pe===vd||Pe==="Kobo"||Pe==="Kindle Fire"||Pe===Rd?ei:Pe===Gi||Pe===Xn||Pe===Ki||Pe===Jo?"Console":Pe===wd?"Wearable":Pe?it:ge?.userAgentDataPlatform==="Android"&&((Ye=ge?.maxTouchPoints)!==null&&Ye!==void 0?Ye:0)>0?600>Math.min((wt=ge?.screenWidth)!==null&&wt!==void 0?wt:0,(mn=ge?.screenHeight)!==null&&mn!==void 0?mn:0)/((Re=ge?.devicePixelRatio)!==null&&Re!==void 0?Re:1)?it:ei:"Desktop"),$timezone:If(),$timezone_offset:Qg()}),{$current_url:Zi(E?fn(me?.href):me?.href,K,Xi),$host:me?.host,$pathname:me?.pathname,$raw_user_agent:Ve.length>1e3?Ve.substring(0,997)+"...":Ve,$browser_version:Jp(Ve,navigator.vendor,Z,Ce),$browser_language:qc(),$browser_language_prefix:(Be=qc(),typeof Be=="string"?Be.split("-")[0]:void 0),$screen_height:w?.screen.height,$screen_width:w?.screen.width,$viewport_height:w?.innerHeight,$viewport_width:w?.innerWidth,$lib:ne.LIB_NAME,$lib_version:ne.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return ne.SDK_DIST_CHANNEL&&(Tt.$sdk_dist_channel=ne.SDK_DIST_CHANNEL),Tt})(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties,this.config.detect_google_search_app,this.config.disable_capture_url_hashes);if(this.sessionManager){var d=this.sessionManager.checkAndGetSessionAndWindowId(s,i.getTime()),f=d.windowId;a.$session_id=d.sessionId,a.$window_id=f}this.sessionPropsManager&&fe(a,this.sessionPropsManager.getSessionProps());try{var h;this.sessionRecording&&fe(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(h=this.Rn)==null?void 0:h.length}catch(x){a.$sdk_debug_error_capturing_properties=String(x)}if(this.requestRouter.region===xa&&(a.$lib_custom_api_host=this.config.api_host),u=e!==Vn||s?e!==_o||s?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(i):this.pageViewManager.doPageView(i,r),a=fe(a,u),e===Vn&&F&&(a.title=F.title),!C(o)){var p=i.getTime()-o;a.$duration=parseFloat((p/1e3).toFixed(3))}Ve&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();ie(["$referrer","$referring_domain"],(x=>{x in g&&delete m[x]}));var v={};if(this._n.length>0)for(var S of this._n.slice())try{fe(v,S())}catch(x){A.error("Failed to produce browser extension event properties",x)}(a=fe({},c,g,m,k({},v,a))).$is_identified=this._isIdentified(),U(this.config.property_denylist)?ie(this.config.property_denylist,(function(x){delete a[x]})):A.error(zf+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var b=this.config.sanitize_properties;b&&(A.error(iu),a=b(a,e));var _=this.Zn();return a.$process_person_profile=_,_&&!s&&this.Gn("_calculate_event_properties"),a}Vn(e,n,i){var r;if(n===void 0&&(n=!0),i===void 0&&(i=!1),!this.persistence||!this.Zn()||this.mn&&!i)return e;var s=this.persistence.get_initial_props(),o=(r=this.sessionPropsManager)==null?void 0:r.getSetOnceProps(),a=fe({},s,o||{},e||{}),l=this.config.sanitize_properties;return l&&(A.error(iu),a=l(a,"$set_once")),n&&(this.mn=!0),Gt(a)?void 0:a}register(e,n){var i;(i=this.persistence)==null||i.register(e,n)}register_once(e,n,i){var r;(r=this.persistence)==null||r.register_once(e,n,i)}register_for_session(e){var n;(n=this.sessionPersistence)==null||n.register(e),Object.keys(e).forEach((i=>this.yn.add(i))),this.Qn()}unregister(e){var n;(n=this.persistence)==null||n.unregister(e)}unregister_for_session(e){var n;(n=this.sessionPersistence)==null||n.unregister(e),this.yn.delete(e),this.Qn()}Kn(e,n){this.register({[e]:n})}An(){this.yn.forEach((e=>{var n;(n=this.sessionPersistence)==null||n.unregister(e)})),this.yn.clear(),this.Qn()}Qn(){var e;if(this.bn)if(this.config.persistence==="memory"||(e=this.sessionPersistence)!=null&&e.xi||!be.N())be.q(this.bn);else{var n=[];this.yn.forEach((i=>n.push(i))),n.length>0?be.F(this.bn,n):be.q(this.bn)}}getFeatureFlag(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlag(e,n)}getFeatureFlagPayload(e){var n;return(n=this.featureFlags)==null?void 0:n.getFeatureFlagPayload(e)}getFeatureFlagResult(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlagResult(e,n)}getAllFeatureFlags(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.getAllFeatureFlags())!==null&&e!==void 0?e:[]}isFeatureEnabled(e,n){var i,r;return(i=(r=this.featureFlags)==null?void 0:r.isFeatureEnabled(e,n))!==null&&i!==void 0?i:n?.defaultValue}reloadFeatureFlags(){var e;(e=this.featureFlags)==null||e.reloadFeatureFlags()}updateFlags(e,n,i){var r;(r=this.featureFlags)==null||r.updateFlags(e,n,i)}updateEarlyAccessFeatureEnrollment(e,n,i){var r;(r=this.featureFlags)==null||r.updateEarlyAccessFeatureEnrollment(e,n,i)}getEarlyAccessFeatures(e,n,i){var r;return n===void 0&&(n=!1),(r=this.featureFlags)==null?void 0:r.getEarlyAccessFeatures(e,n,i)}on(e,n){return this.dn.on(e,n)}onFeatureFlags(e){return this.featureFlags?this.featureFlags.onFeatureFlags(e):(e([],{},{errorsLoading:!0}),()=>{})}onSurveysLoaded(e){return this.surveys?this.surveys.onSurveysLoaded(e):(e([],{isLoaded:!1,error:xi}),()=>{})}onSessionId(e){var n,i;return(n=(i=this.sessionManager)==null?void 0:i.onSessionId(e))!==null&&n!==void 0?n:()=>{}}getSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getSurveys(e,n):e([],{isLoaded:!1,error:xi})}getActiveMatchingSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,n):e([],{isLoaded:!1,error:xi})}renderSurvey(e,n){var i;(i=this.surveys)==null||i.renderSurvey(e,n)}displaySurvey(e,n){var i;n===void 0&&(n=wm),(i=this.surveys)==null||i.displaySurvey(e,n)}cancelPendingSurvey(e){var n;(n=this.surveys)==null||n.cancelPendingSurvey(e)}canRenderSurvey(e){var n,i;return(n=(i=this.surveys)==null?void 0:i.canRenderSurvey(e))!==null&&n!==void 0?n:{visible:!1,disabledReason:xi}}canRenderSurveyAsync(e,n){var i,r;return n===void 0&&(n=!1),(i=(r=this.surveys)==null?void 0:r.canRenderSurveyAsync(e,n))!==null&&i!==void 0?i:Promise.resolve({visible:!1,disabledReason:xi})}Jn(e){return!e||Ko(e)?(A.critical("Unique user id has not been set in posthog.identify"),!1):e===mr?(A.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.'),!1):!["distinct_id","distinctid"].includes(e.toLowerCase())&&!["undefined","null"].includes(e.toLowerCase())||(A.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.'),!1)}identify(e,n,i){if(!this.__loaded||!this.persistence)return A.uninitializedWarning("posthog.identify");if(ke(e)&&(e=e.toString(),A.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.Jn(e)&&this.Gn("posthog.identify")){var r=this.get_distinct_id();this.register({$user_id:e}),this.get_property(Yi)||this.register_once({$had_persisted_distinct_id:!0,$device_id:r},""),e!==r&&e!==this.get_property(Fi)&&(this.unregister(Fi),this.register({distinct_id:e}));var s,o=(this.persistence.get_property(ot)||Un)===Un,a=e!==r,l=!a&&o;if(a&&o)this.persistence.set_property(ot,vn),this.setPersonPropertiesForFlags({$set:n||{},$set_once:i||{}},!1),this.capture(yo,{distinct_id:e,$anon_distinct_id:r},{$set:n||{},$set_once:i||{}}),this.Sn=Fo(e,n,i),(s=this.featureFlags)==null||s.setAnonymousDistinctId(r);else if(l){this.persistence.set_property(ot,vn);var u=n||{},c=i||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=Fo(e,n,i)}else(n||i)&&this.setPersonProperties(n,i);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Cn)):l&&(n||i)&&this.reloadFeatureFlags()}}setPersonProperties(e,n){if((e||n)&&this.Gn("posthog.setPersonProperties")){var i=Fo(this.get_distinct_id(),e,n);this.Sn!==i?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:n||{}},!0),this.capture("$set",{$set:e||{},$set_once:n||{}}),this.Sn=i):A.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}unsetPersonProperties(e){var n,i=(U(e)?e:[e]).filter((r=>X(r)&&r.length>0));i.length!==0&&this.Gn("posthog.unsetPersonProperties")&&((n=this.featureFlags)==null||n.unsetPersonPropertiesForFlags(i,!0),this.capture("$set",{$unset:i}),this.Sn=null)}group(e,n,i){if(e&&n){var r=this.getGroups(),s=r[e]!==n;if(s&&this.resetGroupPropertiesForFlags(e),this.register({$groups:k({},r,{[e]:n})}),s||i){var o={$group_type:e,$group_key:n};i&&(o.$group_set=i),this.capture(Ac,o)}i&&this.setGroupPropertiesForFlags({[e]:i}),s&&!i&&this.reloadFeatureFlags()}else A.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),(i=this.featureFlags)==null||i.setPersonPropertiesForFlags(e,n)}resetPersonPropertiesForFlags(e){var n;e===void 0&&(e=!0),(n=this.featureFlags)==null||n.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((i=this.featureFlags)==null||i.setGroupPropertiesForFlags(e,n))}resetGroupPropertiesForFlags(e){var n;(n=this.featureFlags)==null||n.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,n){var i,r,s,o,a,l,u,c,d,f;if(n===void 0&&(n=!1),A.info("reset"),!this.__loaded)return A.uninitializedWarning("posthog.reset");var h,p=this.get_property(Yi),g=this.get_property(vo),m=this.get_property(An),v=this.is_capturing();if(this.consent.reset(),n||!v||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after."),(i=this.persistence)==null||i.clear(),(r=this.sessionPersistence)==null||r.clear(),this.yn.clear(),this.Qn(),C(m)||(h=this.persistence)==null||h.register({[An]:m}),(s=this.surveys)==null||s.reset(),(o=this.Un)==null||o.stop(),(a=this.featureFlags)==null||a.reset(),(l=this.conversations)==null||l.reset(),(u=this.logs)==null||u.reset(),(c=this.metrics)==null||c.reset(),(d=this.persistence)==null||d.set_property(ot,Un),(f=this.sessionManager)==null||f.resetSessionId(),this.Sn=null,this.config.cookieless_mode===Ht)this.register_once({distinct_id:mr,$device_id:null},"");else{var S=this.config.get_device_id(Ut());this.register_once({distinct_id:S,$device_id:e?S:p},""),e||C(g)||this.register({[vo]:g})}this.register({$last_posthog_reset:new Date().toISOString()},1),delete this.config.identity_distinct_id,delete this.config.identity_hash,this.reloadFeatureFlags()}shutdown(e){var n=this;return se((function*(){var i,r,s,o,a,l,u;if(n.__loaded){(i=n.Un)==null||i.stop(),(r=n.jn)==null||r.dispose(),(s=n.sessionRecording)==null||s.dispose(),(o=n.logs)==null||o.flushLogs("sendBeacon"),(a=n.metrics)==null||a.flush("sendBeacon"),(l=n.In)==null||l.unload(),(u=n.Rn)==null||u.unload();try{var c;(c=n.featureFlags)==null||c.destroy()}catch(d){A.error("Error while destroying feature flags",d)}}else A.uninitializedWarning("posthog.shutdown")}))()}setIdentity(e,n){var i;this.config.identity_distinct_id=e,this.config.identity_hash=n,this.alias(e),(i=this.conversations)==null||i.Xn()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,(e=this.conversations)==null||e.ts()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,n;return(e=(n=this.sessionManager)==null?void 0:n.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var n=this.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.sessionStartTimestamp,r=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+n.sessionId);if(e!=null&&e.withTimestamp&&i){var s,o=(s=e.timestampLookBack)!==null&&s!==void 0?s:10;if(!i)return r;r+="?t="+Math.max(Math.floor((new Date().getTime()-i)/1e3)-o,0)}return r}alias(e,n){return e===this.get_property(zd)?(A.critical("Attempting to create alias for existing People user - aborting."),-2):this.Gn("posthog.alias")?(C(n)&&(n=this.get_distinct_id()),e!==n?(this.Kn(Fi,e),this.capture("$create_alias",{alias:e,distinct_id:n})):(A.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var n=k({},this.config);if(he(e)){var i,r,s,o,a,l,u,c,d,f,h,p;fe(this.config,ru(e));var g=this.En();(i=this.persistence)==null||i.update_config(this.config,n,g),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new xo(k({},this.config,{persistence:"sessionStorage"}),g,!1);var m=this.Cn(this.config.debug);gt(m)&&(this.config.debug=m),gt(this.config.debug)&&(this.config.debug?(ne.DEBUG=!0,le.N()&&le.F("ph_debug",!0),A.info("set_config",{config:e,oldConfig:n,newConfig:k({},this.config)})):(ne.DEBUG=!1,le.N()&&le.q("ph_debug"))),(r=this.featureFlags)==null||r.updateConfig==null||r.updateConfig(this.config,this.Qi()),(s=this.exceptionObserver)==null||s.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(f=this.deadClicksAutocapture)==null||f.startIfEnabledOrStop(),(h=this.surveys)==null||h.loadIfEnabled(),this.es(),(p=this.externalIntegrations)==null||p.startIfEnabledOrStop()}}_overrideSDKInfo(e,n){ne.LIB_NAME=e,ne.LIB_VERSION=n}startSessionRecording(e){var n,i,r,s,o,a=e===!0,l={sampling:a||!(e==null||!e.sampling),linked_flag:a||!(e==null||!e.linked_flag),url_trigger:a||!(e==null||!e.url_trigger),event_trigger:a||!(e==null||!e.event_trigger)};Object.values(l).some(Boolean)&&((n=this.sessionManager)==null||n.checkAndGetSessionAndWindowId(),l.sampling&&((i=this.sessionRecording)==null||i.overrideSampling()),l.linked_flag&&((r=this.sessionRecording)==null||r.overrideLinkedFlag()),l.url_trigger&&((s=this.sessionRecording)==null||s.overrideTrigger("url")),l.event_trigger&&((o=this.sessionRecording)==null||o.overrideTrigger("event"))),this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,n){if(this.exceptions){var i=new Error("PostHog syntheticException"),r=this.exceptions.buildProperties(e,{handled:!0,syntheticException:i});return this.exceptions.sendExceptionEvent(k({},r,n))}}addExceptionStep(e,n){var i;(i=this.exceptions)==null||i.addExceptionStep(e,n)}captureLog(e){var n;(n=this.logs)==null||n.captureLog(e)}get logger(){var e,n;return(e=(n=this.logs)==null?void 0:n.logger)!==null&&e!==void 0?e:Je.rs}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var n,i;return(n=(i=this.toolbar)==null?void 0:i.loadToolbar(e))!==null&&n!==void 0&&n}get_property(e){var n;return(n=this.persistence)==null?void 0:n.props[e]}getSessionProperty(e){var n;return(n=this.sessionPersistence)==null?void 0:n.props[e]}toString(){var e,n=(e=this.config.name)!==null&&e!==void 0?e:Gn;return n!==Gn&&(n=Gn+"."+n),n}_isIdentified(){var e,n;return((e=this.persistence)==null?void 0:e.get_property(ot))===vn||((n=this.sessionPersistence)==null?void 0:n.get_property(ot))===vn}Zn(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles===pa&&!this._isIdentified()&&Gt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[Fi])&&((n=this.persistence)==null||(n=n.props)==null||!n[es]))}zn(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Zn()||this.Gn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.Gn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}Gn(e){return this.config.person_profiles==="never"?(A.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Kn(es,!0),!0)}En(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut();return this.config.disable_persistence||e&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!==kn)}es(){var e,n,i,r,s=this.En();return((e=this.persistence)==null?void 0:e.xi)!==s&&((i=this.persistence)==null||i.set_disabled(s)),((n=this.sessionPersistence)==null?void 0:n.xi)!==s&&((r=this.sessionPersistence)==null||r.set_disabled(s)),s&&(this.yn.clear(),this.Qn()),s}opt_in_capturing(e){var n;if(this.config.cookieless_mode!==Ht){if(this.gn()){var i,r,s,o,a;this.Yn(!0,!0),(i=this.sessionManager)==null||i.destroy(),(r=this.pageViewManager)==null||r.destroy(),this.sessionManager=new Qc(this),this.pageViewManager=new Wc(this),this.persistence&&(this.sessionPropsManager=new Xc(this,this.sessionManager,this.persistence));var l,u=(s=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&s!==void 0?s:(a=Je.__defaultExtensionClasses)==null?void 0:a.sessionRecording;u&&(this.sessionRecording=this.pn(this.sessionRecording,new u(this)),this.hn&&((l=this.sessionRecording)==null||l.onRemoteConfig==null||l.onRemoteConfig(this.hn)))}var c,d;this.consent.optInOut(!0),this.es(),this.Bn(),(n=this.sessionRecording)==null||n.startIfEnabledOrStop(),this.config.cookieless_mode==kn&&((c=this.surveys)==null||c.loadIfEnabled()),(C(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((d=e?.captureEventName)!==null&&d!==void 0?d:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hn()}else A.warn(nu)}opt_out_capturing(){var e,n,i;this.config.cookieless_mode!==Ht?(this.config.cookieless_mode===kn&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===kn&&(this.register({distinct_id:mr,$device_id:null}),(e=this.sessionRecording)==null||e.stopRecording(),this.sessionRecording=void 0,(n=this.sessionManager)==null||n.destroy(),(i=this.pageViewManager)==null||i.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.Hn(),this.Bn())):A.warn(nu)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===Ht||(this.config.cookieless_mode===kn?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return Ue?Bf(Ue,this.config.custom_blocked_useragents):void 0}Hn(){F&&(F.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(Vn,{title:F.title},{send_instantly:!0}),this.kn&&(F.removeEventListener(ts,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),ve(F,ts,this.kn)))}debug(e){e===!1?(w?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(w?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}Qi(){var e=this.Mn||{};return"advanced_disable_flags"in e?!!e.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(A.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(function(n,i,r,s,o){var a=i in n&&!H(n[i]),l=r in n&&!H(n[r]);return a?n[i]:!!l&&(o&&o.warn("Config field '"+r+"' is deprecated. Please use '"+i+"' instead. The old field will be removed in a future major version."),n[r])})(e,"advanced_disable_flags","advanced_disable_decide",0,A)}Pt(e){var n;if(H(this.config.before_send))return e;var i=Object.keys((n=e.properties)!==null&&n!==void 0?n:{}).filter(Bp),r=U(this.config.before_send)?this.config.before_send:[this.config.before_send],s=e;for(var o of r){if(s=o(s),H(s)){var a="Event '"+e.event+"' was rejected in beforeSend function";return Op(e.event)?A.warn(a+". This can cause unexpected behavior."):A.info(a),null}s.properties&&!Gt(s.properties)||A.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}for(var l of i)if(s.properties&&H(s.properties[l]))return A.warn("Event '"+e.event+"' had its '"+l+"' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped."),null;return s}getPageViewId(){var e;return(e=this.pageViewManager.ui)==null?void 0:e.pageViewId}captureTraceFeedback(e,n){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:n})}captureTraceMetric(e,n,i){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:n,$ai_metric_value:String(i)})}Cn(e){var n=gt(e)&&!e,i=le.N()&&le.P("ph_debug")==="true";return!n&&(!!i||e)}}Je.__defaultExtensionClasses={},Je.rs=(()=>{var t=()=>{};return{trace:t,debug:t,info:t,warn:t,error:t,fatal:t}})(),(function(t,e){for(var n=0;e.length>n;n++)t.prototype[e[n]]=kg(t.prototype[e[n]])})(Je,["identify"]);class su{constructor(e){this.disabled=e===!1;var n=he(e)?e:{};this.thresholdPx=n.threshold_px||30,this.timeoutMs=n.timeout_ms||1e3,this.clickCount=n.click_count||3,this.clicks=[]}isRageClick(e,n,i){if(this.disabled)return!1;var r=this.clicks[this.clicks.length-1];if(r&&Math.abs(e-r.x)+Math.abs(n-r.y)i-r.timestamp){if(this.clicks.push({x:e,y:n,timestamp:i}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:n,timestamp:i}];return!1}}var $o="$copy_autocapture",Mo=pe("[AutoCapture]");function Lo(t,e){return e.length>t?e.slice(0,t)+"...":e}function Fm(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!hn(e));return e}function Rm(t,e){var n,i,r=e.e,s=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!hn(t))return{props:{}};for(var c=[t],d=new Set([t]),f=t;f.parentNode&&!Qe(f,"body")&&lf>c.length;)if(af(f.parentNode)){var h=f.parentNode.host;if(d.has(h))break;d.add(h),c.push(h),f=h}else{if(!hn(f.parentNode)||d.has(f.parentNode))break;d.add(f.parentNode),c.push(f.parentNode),f=f.parentNode}var p,g,m=[],v={},S=!1,b=!1;if(ie(c,(E=>{var P=va(E);if(Qe(E,"a")){var $=E.getAttribute("href");S=!!(P&&$&&Ui($))&&(u?fn($):$)}j(rs(E),"ph-no-capture")&&(b=!0),m.push((function(L,N,K,V,M){M===void 0&&(M=!1);var R=L.tagName.toLowerCase(),Z={tag_name:R};ul.indexOf(R)>-1&&!K&&(Z.$el_text=R.toLowerCase()==="a"||R.toLowerCase()==="button"?Lo(1024,jc(L)):Lo(1024,Ji(L)));var Ce=rs(L);Ce.length>0&&(Z.classes=Ce.filter((function(ae){return ae!==""}))),ie(L.attributes,(function(ae){var Ie;if((!hf(L)||["name","id","class","aria-label"].indexOf(ae.name)!==-1)&&(V==null||!V.includes(ae.name))&&!N&&Ui(ae.value)&&(!X(Ie=ae.name)||Ie.substring(0,10)!=="_ngcontent"&&Ie.substring(0,7)!=="_nghost")){var Se=ae.value;ae.name==="class"&&(Se=cl(Se).join(" ")),Z["attr__"+ae.name]=Lo(1024,ae.name==="href"&&M?fn(Se):Se)}}));for(var oe=1,ye=1,$e=L;$e=Fm($e);)oe++,$e.tagName===L.tagName&&ye++;return Z.nth_child=oe,Z.nth_of_type=ye,Z})(E,s,o,a,u));var O=(function(L){if(!va(L))return{};var N={};return ie(L.attributes,(function(K){if(K.name&&K.name.indexOf("data-ph-capture-attribute")===0){var V=K.name.replace("data-ph-capture-attribute-",""),M=K.value;V&&M&&Ui(M)&&(N[V]=M)}})),N})(E);fe(v,O)})),b)return{props:{},explicitNoCapture:b};if(o||(m[0].$el_text=Qe(t,"a")||Qe(t,"button")?jc(t):Ji(t)),S){var _,x;m[0].attr__href=S;var I=(_=ss(S))==null?void 0:_.host,T=w==null||(x=w.location)==null?void 0:x.host;I&&T&&I!==T&&(p=S)}return{props:fe({$event_type:r.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(E){return E.map((P=>{var $,O,L="";if(P.tag_name&&(L+=P.tag_name),P.attr_class)for(var N of(P.attr_class.sort(),P.attr_class))L+="."+N.replace(/"/g,"");var K=k({},P.text?{text:P.text}:{},{"nth-child":($=P.nth_child)!==null&&$!==void 0?$:0,"nth-of-type":(O=P.nth_of_type)!==null&&O!==void 0?O:0},P.href?{href:P.href}:{},P.attr_id?{attr_id:P.attr_id}:{},P.attributes),V={};return $r(K).sort(((M,R)=>M[0].localeCompare(R[0]))).forEach((M=>{var R=M[1];return V[Uc(M[0].toString())]=Uc(R.toString())})),(L+=":")+$r(V).map((M=>M[0]+'="'+M[1]+'"')).join("")})).join(";")})((function(E){return E.map((P=>{var $,O,L={text:($=P.$el_text)==null?void 0:$.slice(0,400),tag_name:P.tag_name,href:(O=P.attr__href)==null?void 0:O.slice(0,2048),attr_class:zg(P),attr_id:P.attr__id,nth_child:P.nth_child,nth_of_type:P.nth_of_type,attributes:{}};return $r(P).filter((N=>N[0].indexOf("attr__")===0)).forEach((N=>L.attributes[N[0]]=N[1])),L}))})(g)))},(n=m[0])!=null&&n.$el_text?{$el_text:(i=m[0])==null?void 0:i.$el_text}:{},p&&r.type==="click"?{$external_click_url:p}:{},v)}}var Ii=pe("[ExceptionAutocapture]"),ou=()=>{},Tm=pe("[TracingHeaders]"),wn=pe("[Web Vitals]"),au=9e5,lu="disabled",cu="lazy_loading",ki="awaiting_config",Sr="missing_config";pe("[SessionRecording]"),pe("[SessionRecording]");var Ia="[SessionRecording]",Ot=pe(Ia),$m=pe("[Heatmaps]");function No(t){return he(t)&&"clientX"in t&&"clientY"in t&&ke(t.clientX)&&ke(t.clientY)}var xr=pe("[Product Tours]"),Oo=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(sl))},Mm=["$set_once","$set"],bt=pe("[SiteApps]"),uu="Error while initializing PostHog app with config id ";function qn(t,e,n){if(H(t))return!1;switch(n){case"exact":return t===e;case"contains":var i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(i,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}class Lm{constructor(e){this.ns=new pl,this.ss=(n,i)=>this.os(n,i)&&this.ls(n,i)&&this.us(n,i)&&this.hs(n,i),this.os=(n,i)=>i==null||!i.event||n?.event===i?.event,this._instance=e,this.ds=new Set,this.vs=new Set}init(){var e,n;C((e=this._instance)==null?void 0:e._addCaptureHook)||(n=this._instance)==null||n._addCaptureHook(((i,r)=>{this.on(i,r)}))}register(e){var n,i;if(!C((n=this._instance)==null?void 0:n._addCaptureHook)&&(e.forEach((o=>{var a,l;(a=this.vs)==null||a.add(o),(l=o.steps)==null||l.forEach((u=>{var c;(c=this.ds)==null||c.add(u?.event||"")}))})),(i=this._instance)!=null&&i.autocapture)){var r,s=new Set;e.forEach((o=>{var a;(a=o.steps)==null||a.forEach((l=>{l!=null&&l.selector&&s.add(l?.selector)}))})),(r=this._instance)==null||r.autocapture.setElementSelectors(s)}}on(e,n){var i;n!=null&&e.length!=0&&(this.ds.has(e)||this.ds.has(n.event))&&this.vs&&((i=this.vs)==null?void 0:i.size)>0&&this.vs.forEach((r=>{this.cs(n,r)&&this.ns.emit("actionCaptured",r.name)}))}fs(e){this.onAction("actionCaptured",(n=>e(n)))}cs(e,n){if(n?.steps==null)return!1;for(var i of n.steps)if(this.ss(e,i))return!0;return!1}onAction(e,n){return this.ns.on(e,n)}ls(e,n){if(n!=null&&n.url){var i,r=e==null||(i=e.properties)==null?void 0:i.$current_url;if(!r||typeof r!="string"||!qn(r,n.url,n.url_matching||"contains"))return!1}return!0}us(e,n){return!!this.ps(e,n)&&!!this.gs(e,n)&&!!this.ys(e,n)}ps(e,n){var i;if(n==null||!n.href)return!0;var r=this.bs(e);if(r.length>0)return r.some((a=>qn(a.href,n.href,n.href_matching||"exact")));var s,o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!o&&qn((s=o.match(/(?::|")href="(.*?)"/))?s[1]:"",n.href,n.href_matching||"exact")}gs(e,n){var i;if(n==null||!n.text)return!0;var r=this.bs(e);if(r.length>0)return r.some((u=>qn(u.text,n.text,n.text_matching||"exact")||qn(u.$el_text,n.text,n.text_matching||"exact")));var s,o,a,l=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!l&&(s=(function(u){for(var c,d=[],f=/(?::|")text="(.*?)"/g;!H(c=f.exec(u));)d.includes(c[1])||d.push(c[1]);return d})(l),o=n.text,a=n.text_matching||"exact",s.some((u=>qn(u,o,a))))}ys(e,n){var i,r;if(n==null||!n.selector)return!0;var s=e==null||(i=e.properties)==null?void 0:i.$element_selectors;if(s!=null&&s.includes(n.selector))return!0;var o=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";if(n.selector_regex&&o)try{return new RegExp(n.selector_regex).test(o)}catch{return!1}return!1}bs(e){var n;return(e==null||(n=e.properties)==null?void 0:n.$elements)==null?[]:e?.properties.$elements}hs(e,n){return n==null||!n.properties||n.properties.length===0||Uf(n.properties.reduce(((i,r)=>{var s=U(r.value)?r.value.map(String):r.value!=null?[String(r.value)]:[];return i[r.key]={values:s,operator:r.operator||"exact"},i}),{}),e?.properties)}}class Nm{constructor(e){var n;this._s=[],this._instance=e,this.ws=new Map,this.ks=new Map,this.xs=new Map,(n=this._instance)==null||n.onSessionId==null||n.onSessionId((i=>this.Ss(i)))}Cs(e){return!1}Ms(){return null}Ts(e){}Es(){}Is(e,n){return!!e&&Uf(e.propertyFilters,n?.properties)}Ps(e,n){var i=new Map;return e.forEach((r=>{var s;(s=r.conditions)==null||(s=s[n])==null||(s=s.values)==null||s.forEach((o=>{if(o!=null&&o.name){var a=i.get(o.name)||[];a.push(r.id),i.set(o.name,a)}}))})),i}Rs(e,n,i){var r=(i===wi.Activation?this.ws:this.ks).get(e),s=[];return this.As((o=>{s=o.filter((a=>r?.includes(a.id)))})),s.filter((o=>{var a,l=(a=o.conditions)==null||(a=a[i])==null||(a=a.values)==null?void 0:a.find((u=>u.name===e));return this.Is(l,n)}))}register(e){var n;C((n=this._instance)==null?void 0:n._addCaptureHook)||(this.Fs(e),this.Ls(e))}Ls(e){var n=e.filter((i=>{var r,s;return((r=i.conditions)==null?void 0:r.actions)&&((s=i.conditions)==null||(s=s.actions)==null||(s=s.values)==null?void 0:s.length)>0}));n.length!==0&&(this.Os==null&&(this.Os=new Lm(this._instance),this.Os.init(),this.Os.fs((i=>{this.onAction(i)}))),n.forEach((i=>{var r,s,o,a,l;i.conditions&&(r=i.conditions)!=null&&r.actions&&(s=i.conditions)!=null&&(s=s.actions)!=null&&s.values&&((o=i.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.Os)==null||a.register(i.conditions.actions.values),(l=i.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var c=this.xs.get(u.name);c&&c.push(i.id),this.xs.set(u.name,c||[i.id])}})))})))}Fs(e){var n,i=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.events)&&((a=s.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0})),r=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.cancelEvents)&&((a=s.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0}));i.length===0&&r.length===0||((n=this._instance)==null||n._addCaptureHook(((s,o)=>{this.onEvent(s,o)})),this.ws=this.Ps(e,wi.Activation),this.ks=this.Ps(e,wi.Cancellation))}onEvent(e,n){var i,r,s=this.Ds(),o=(n==null||(i=n.properties)==null?void 0:i.$survey_id)||(n==null||(r=n.properties)==null?void 0:r.$product_tour_id);if(o&&this.getActivatedIds().includes(o)){var a=this.$s(e,o);if(a==="consume")return s.info("event consumed activated item, removing it",{event:e,itemId:o}),void this.Ns([o]);if(a==="persist")return s.info("shown item promoted to persisted activation",{event:e,itemId:o}),this.qs(o),void this.js([o])}if(this.ks.has(e)){var l=this.Rs(e,n,wi.Cancellation);l.length>0&&(s.info("cancel event matched, cancelling items",{event:e,itemsToCancel:l.map((c=>c.id))}),this.Ns(l.map((c=>c.id))),l.forEach((c=>this.Bs(c.id))))}if(this.ws.has(e)){s.info("event name matched",{event:e,eventPayload:n,items:this.ws.get(e)});var u=this.Rs(e,n,wi.Activation);this.Hs(u.map((c=>c.id)))}}onAction(e){this.xs.has(e)&&this.Hs(this.xs.get(e)||[])}Hs(e){var n;if(e.length!==0){var i=!((n=this._instance)==null||n.get_session_id==null||!n.get_session_id()),r=[];for(var s of e)i&&this.Cs(s)?this.qs(s)&&this.Us(s):r.push(s);r.length>0&&(this._s=[...new Set([...this._s,...r])]),this.Ds().info("updating activated items",{activatedItems:this.getActivatedIds()})}}qs(e){this._s=this._s.filter((i=>i!==e));var n=this.zs();return!n.includes(e)&&(this.Ws([...n,e]),this.Vs(),!0)}Ns(e){var n=new Set(e);this._s=this._s.filter((s=>!n.has(s)));var i=this.Zs(),r=i.filter((s=>!n.has(s)));r.length!==i.length&&(this.Ws(r),r.length===0&&this.Gs()),this.js(e)}Qs(){var e,n=this.Ms();if(!n)return{};var i=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n];return i&&typeof i=="object"?i:{}}Us(e){if(this.Ms()){var n=this.Qs();this.Ts(k({},n,{[e]:Date.now()}))}}js(e){if(this.Ms()){var n=this.Qs(),i={},r=!1;for(var s of Object.entries(n)){var o=s[0],a=s[1];e.includes(o)?r=!0:i[o]=a}r&&(Gt(i)?this.Es():this.Ts(i))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var n=this.Qs()[e];return ke(n)?n:void 0}}Zs(){var e,n=this.Js();return((e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n])||[]}zs(){var e,n,i=this.Zs();if(i.length===0)return[];var r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[this.Ys()],s=(n=this._instance)==null||n.get_session_id==null?void 0:n.get_session_id();return s&&r===s?i:[]}Vs(){var e,n=(e=this._instance)==null||e.get_session_id==null?void 0:e.get_session_id();n&&this.Xs(n)}Gs(){this.ta()}Ss(e){var n,i=(n=this._instance)==null||(n=n.persistence)==null?void 0:n.props[this.Ys()];if(i&&i!==e){var r=this.Zs(),s=this.Qs();r.length>0&&(this.Ws([]),r.filter((o=>ke(s[o]))).forEach((o=>this.Bs(o)))),this.Gs(),this.Ks()}}getActivatedIds(){return[...new Set([...this.zs(),...this._s])].filter((e=>!this.ea(e)))}reset(){this._s=[],this.Zs().length>0&&this.Ws([]),this.Gs(),this.Ks()}getEventToItemsMap(){return this.ws}ia(){return this.Os}}class Om extends Nm{constructor(e){super(e)}Js(){return ca}Ys(){return Fr}Ms(){return Rr}Ts(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Rr]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Rr)}Cs(e){var n,i;this.As((s=>{i=s.find((o=>o.id===e))}));var r=(n=i)==null||(n=n.appearance)==null?void 0:n.surveyPopupDelaySeconds;return ke(r)&&r>0}ra(){return qt.SHOWN}As(e){var n;(n=this._instance)==null||n.getSurveys(e)}Bs(e){var n;(n=this._instance)==null||n.cancelPendingSurvey(e)}Ds(){return Q}Ws(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[ca]:e})}Xs(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Fr]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Fr)}ea(){return!1}$s(e,n){var i;this.As((s=>{i=s.find((o=>o.id===n))}));var r=!i||(function(s){var o;return Hf(s)&&!((o=s.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||s.schedule==="always"})(i);return r?e===qt.SHOWN?"consume":"ignore":e===qt.SHOWN?"persist":e===qt.DISMISSED||e===qt.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var Ir="SDK is not enabled or survey functionality is not yet loaded",du="Disabled. Not loading surveys.",Bm=w!=null&&w.location?os(w.location.hash,"__posthog")||os(location.hash,"state"):null,fu="_postHogToolbarParams",hu=pe("[Toolbar]"),pu=pe("[FeatureFlags]");class Dm{constructor(e,n){n===void 0&&(n=!1),this.na=!1,this.update(e,n)}update(e,n){this.sa=((i,r)=>{var s,o,a,l;return{bootstrap:{featureFlags:(s=i.bootstrap)==null?void 0:s.featureFlags,featureFlagPayloads:(o=i.bootstrap)==null?void 0:o.featureFlagPayloads},remoteRequestsDisabled:r,featureFlagsDisabled:!!i.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!i.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!i.advanced_feature_flags_dedup_per_session,cacheTtlMs:i.feature_flag_cache_ttl_ms,requestTimeoutMs:i.feature_flag_request_timeout_ms,compression:i.disable_compression?"none":"base64",evaluationContexts:(a=(l=i.evaluation_contexts)!==null&&l!==void 0?l:i.evaluation_environments)!==null&&a!==void 0?a:[],flagKeys:U(i.flag_keys)?i.flag_keys:void 0}})(e,n),!e.evaluation_environments||e.evaluation_contexts||this.na||(pu.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.na=!0),C(e.flag_keys)||U(e.flag_keys)||pu.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var gu=pe("[FeatureFlags]"),bn=pe("[FeatureFlags]",{debugEnabled:!0}),Bo=`" failed. Feature flags didn't load in time.`,mu="connection_error",vu=t=>{for(var e={},n=0;t.length>n;n++)e[t[n]]=!0;return e},_u=t=>{var e={};for(var n of $r(t||{})){var i=n[1];i&&(e[n[0]]=i)}return e},Et=pe("[Error tracking]"),yu="Refusing to render web experiment since the viewer is a likely bot",jm={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>cs(e,t),not_regex:(t,e)=>!cs(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class Me{get Ne(){return this._instance.config}constructor(e){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(i){i===void 0&&(i=!1),n.getWebExperiments((r=>{Me.aa("retrieved web experiments from the server"),n.oa=new Map,r.forEach((s=>{if(s.feature_flag_key){var o;n.oa&&(Me.aa("setting flag key ",s.feature_flag_key," to web experiment ",s),(o=n.oa)==null||o.set(s.feature_flag_key,s));var a=n._instance.getFeatureFlag(s.feature_flag_key);X(a)&&s.variants[a]&&n.la(s.name,a,s.variants[a].transforms)}else if(s.variants)for(var l in s.variants){var u=s.variants[l];Me.ua(u,n._instance)&&n.la(s.name,l,u.transforms)}}))}),i)},this._instance=e,this._instance.onFeatureFlags((i=>{this.onFeatureFlags(i)}))}initialize(){}onFeatureFlags(e){if(this._is_bot())Me.aa(yu);else if(!this.Ne.disable_web_experiments){if(H(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();Me.aa("applying feature flags",e),e.forEach((n=>{var i;if(this.oa&&(i=this.oa)!=null&&i.has(n)){var r,s=this._instance.getFeatureFlag(n),o=(r=this.oa)==null?void 0:r.get(n);s&&o!=null&&o.variants[s]&&this.la(o.name,s,o.variants[s].transforms)}}))}}previewWebExperiment(){var e=Me.getWindowLocation();if(e!=null&&e.search){var n=ii(e?.search,"__experiment_id"),i=ii(e?.search,"__experiment_variant");n&&i&&(Me.aa("previewing web experiments "+n+" && "+i),this.getWebExperiments((r=>{this.ha(parseInt(n),i,r)}),!1,!0))}}loadIfEnabled(){this.Ne.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,n,i){if(this.Ne.disable_web_experiments&&!i)return e([]);var r=this._instance.get_property("$web_experiments");if(r&&!n)return e(r);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this.Ne.token),method:"GET",timestampMode:"query",callback:s=>e(s.statusCode===200&&s.json&&s.json.experiments||[])})}ha(e,n,i){var r=i.filter((s=>s.id===e));r&&r.length>0&&(Me.aa("Previewing web experiment ["+r[0].name+"] with variant ["+n+"]"),this.la(r[0].name,n,r[0].variants[n].transforms))}static ua(e,n){return!H(e.conditions)&&Me.da(e,n)&&Me.va(e)}static da(e,n){var i;if(H(e.conditions)||H((i=e.conditions)==null?void 0:i.url))return!0;var r=Me.getWindowLocation();if(r){var s,o,a,l=rf(n,r.href);return(s=e.conditions)==null||!s.url||jm[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return w?.location}static va(e){var n;if(H(e.conditions)||H((n=e.conditions)==null?void 0:n.utm))return!0;var i=yf();if(i.utm_source){var r,s,o,a,l,u,c,d,f=(r=e.conditions)==null||(r=r.utm)==null||!r.utm_campaign||((s=e.conditions)==null||(s=s.utm)==null?void 0:s.utm_campaign)==i.utm_campaign,h=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==i.utm_source,p=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==i.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==i.utm_term;return f&&p&&g&&h}return!1}static aa(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;n>r;r++)i[r-1]=arguments[r];A.info("[WebExperiments] "+e,i)}la(e,n,i){this._is_bot()?Me.aa(yu):n!=="control"?i.forEach((r=>{if(r.selector){var s;Me.aa("applying transform of variant "+n+" for experiment "+e+" ",r);var o=(s=document)==null?void 0:s.querySelectorAll(r.selector);o?.forEach((a=>{var l=a;r.html&&(l.innerHTML=r.html),r.css&&l.setAttribute("style",r.css)}))}})):Me.aa("Control variants leave the page unmodified.")}_is_bot(){return Ue&&this._instance?Bf(Ue,this.Ne.custom_blocked_useragents):void 0}}var st=pe("[Conversations]"),En="Conversations not available yet.",wu="console",Gf="__posthogHandledLogsRequestError",Do=(t,e)=>{var n=t instanceof Error?t:new Error(e);return n[Gf]=!0,n},bu=t=>!!t&&typeof t=="object"&&t[Gf]===!0,Cs={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=gu,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 Dm(t.config,t.Qi()),this.Ta=this.Ea)}updateConfig(t,e){var n;(n=this.Ea)==null||n.update(t,e)}setup(t){return this.Ia=t,this.rt=t.logger.createLogger("[FeatureFlags]"),n=()=>{this.Ia===t&&(this.Ia=void 0,this.nn=t,this.Pa(t))},(e=t.kv.initialize())!=null&&e.then?e.then(n):n();var e,n}Pa(t){if(this.nn===t)return w&&ve(w,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){w?.removeEventListener("online",this.Ca)}dispose(){var t;this.ba++,this.wa=!1,this.Ia=void 0,this.nn&&(this.La(),(t=this.Ra)==null||t.dispose(),this.Ra=void 0,this.ga=[],w?.removeEventListener("online",this.Ca),this.nn=void 0)}get Ne(){return this.Ta.get()}Oa(t){var e;return(e=this.nn)==null?void 0:e.kv.get(t)}F(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.set(t)}))}q(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.remove(t)}))}Da(t){try{t()}catch(e){this.rt.error("Failed to update feature flag persistence",e)}}Fa(){var t={};for(var e of[Ti,$i,Pr,xt]){var n=this.Oa(e);C(n)||(t[e]=n)}this.fa=t;var i=k({},t),r=this.Oa(Sn);if(r)for(var s of Object.entries(r))i["$feature/"+s[0]]=s[1];this.pa=i}Aa(){var t=this.Ne.cacheTtlMs;if(!t||0>=t)return!1;var e=this.Oa(ji);return typeof e!="number"||Date.now()-e>t}$a(){return!!this.Aa()&&(this.xa||this.ya||(this.xa=!0,this.rt.warn("Feature flag cache is stale, triggering refresh..."),this.reloadFeatureFlags()),!0)}Na(){var t=this.Ne.evaluationContexts;return t!=null&&t.length?t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid evaluation context found:",e,"Expected non-empty string"),n})):[]}qa(){var t=this.Ne.flagKeys;if(!C(t))return t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid flag key found:",e,"Expected non-empty string"),n}))}initialize(){var t,e,n=this.Ne,i=(t=(e=n.bootstrap)==null?void 0:e.featureFlags)!==null&&t!==void 0?t:{};if(Object.keys(i).length){var r,s,o=(r=(s=n.bootstrap)==null?void 0:s.featureFlagPayloads)!==null&&r!==void 0?r:{},a=Object.keys(i).filter((u=>!!i[u])).reduce(((u,c)=>(u[c]=i[c]||!1,u)),{}),l=Object.keys(o).filter((u=>a[u])).reduce(((u,c)=>(o[c]&&(u[c]=o[c]),u)),{});return this.ja({featureFlags:a,featureFlagPayloads:l})}}updateFlags(t,e,n){var i,r,s=n!=null&&n.merge&&(i=this.Oa(Sn))!==null&&i!==void 0?i:{},o=n!=null&&n.merge&&(r=this.Oa($i))!==null&&r!==void 0?r:{},a=k({},s,t),l=k({},o,e),u={};for(var c of Object.entries(a)){var d=c[0],f=c[1];u[d]={key:d,enabled:hc(f),variant:pc(f),reason:void 0,metadata:C(l?.[d])?void 0:{id:0,version:void 0,description:void 0,payload:l[d]}}}this.ja({flags:u})}get hasLoadedFlags(){return this.ma}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var t=this.Oa(aa),e=this.Oa(xt),n=this.Oa(xn);if(!n&&!e)return t||{};var i=fe({},t||{}),r=[...new Set([...Object.keys(n||{}),...Object.keys(e||{})])];for(var s of r){var o,a,l=i[s],u=e?.[s],c=C(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=C(u)?l?.variant:typeof u=="string"?u:void 0,f=n?.[s],h=k({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(h.original_enabled=l?.enabled),d!==l?.variant&&(h.original_variant=l?.variant),f&&(h.metadata=k({},l?.metadata,{payload:f,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),i[s]=h}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:n,finalDetails:i}),this.ca=!0),i}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((n=>{var i=t[n];return{key:n,enabled:hc(i),variant:pc(i),payload:fc(e[n])}}))}getFlagVariants(){var t=this.Oa(Sn),e=this.Oa(xt);if(!e)return t||{};for(var n=fe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:e,finalFlags:n}),this.ca=!0),n}getFlagPayloads(){var t=this.Oa($i),e=this.Oa(xn);if(!e)return t||{};for(var n=fe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flag payloads!",{flagPayloads:t,overriddenPayloads:e,finalPayloads:n}),this.ca=!0),n}reloadFeatureFlags(){this._a||this.Ne.featureFlagsDisabled||this.Ma()||this.Ba||(this.ga.slice().forEach((t=>{try{t()}catch(e){this.rt.error("Error while running feature flags reloading callback",e)}})),this.Ba=setTimeout((()=>{this.Ha()}),5))}La(){clearTimeout(this.Ba),this.Ba=void 0}onReloading(t){return this.ga.push(t),()=>{this.ga=this.ga.filter((e=>e!==t))}}ensureFlagsLoaded(){this.ma||this.ya||this.Ba||this.reloadFeatureFlags()}setAnonymousDistinctId(t){this.$anon_distinct_id=t}setReloadingPaused(t){this._a=t}resetFlagCallReported(){this.q(Cn)}Ha(t){this.La();var e=this.nn;if(e&&!this.Ne.remoteRequestsDisabled&&!this.Ma())if(this.ya)this.wa=!0;else{var n={token:e.projectToken,distinct_id:e.distinctId,groups:e.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:k({},e.initialPersonProperties,this.Oa(Dt)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(In),timezone:If()};C(e.deviceId)||(n.$device_id=e.deviceId),(t!=null&&t.disableFlags||this.Ne.featureFlagsDisabled)&&(n.disable_flags=!0);var i=this.Na();i.length&&(n.evaluation_contexts=i);var r=this.qa();C(r)||(n.flag_keys=r);var s=this.Ne.onlyEvaluateSurveyFeatureFlags,o="/flags/?v=2"+(s?"&only_evaluate_survey_feature_flags=true":""),a=this.ba;this.ya=!0;var l=()=>{this.wa&&(this.wa=!1,this.Ha())},u=c=>{this.ya=!1,a===this.ba&&(this.F({[Tr]:[mu]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:n,compression:this.Ne.compression==="base64"?je.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,f,h=(d=c.json)!==null&&d!==void 0?d:{},p=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),p||this.wa||(this.$anon_distinct_id=void 0),!n.disable_flags||this.wa){this.ka=!p;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?mu:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),h.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((f=h.quotaLimited)==null||!f.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[Tr]:g}),m?this.rt.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more."):n.disable_flags||this.ja(h,p,{partialResponse:s}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return vf(this.Sa,3)}Ua(t){this.Sa=_f(t,this.Sa,3,(()=>this.rt.warn("Feature flag requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped refreshing feature flags; will try again when connectivity changes.")))}getFeatureFlag(t,e){var n;if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var i=this.getFeatureFlagResult(t,e);return(n=i?.variant)!==null&&n!==void 0?n:i?.enabled}}else this.rt.warn('getFeatureFlag for key "'+t+Bo)}getFeatureFlagDetails(t){return this.getFlagsWithDetails()[t]}getFeatureFlagPayload(t){var e=this.getFeatureFlagResult(t,{send_event:!1});return e?.payload}getFeatureFlagResult(t,e){if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var n,i=this.getFlagVariants(),r=t in i,s=i[t],o=this.getFlagPayloads()[t],a=String(s),l=this.Oa(Pr)||void 0,u=this.Oa(ji)||void 0,c=this.Oa(Cn)||{};if(this.Ne.deduplicateCallsPerSession){var d,f=(d=this.nn)==null?void 0:d.session.sessionId,h=this.Oa(Li);f&&f!==h&&(c={},n=f)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))n&&this.F({[Cn]:c,[Li]:n});else{var p,g,m,v,S,b,_,x,I,T;U(c[t])?c[t].push(a):c[t]=[a],this.F(k({[Cn]:c},n?{[Li]:n}:{}));var E=this.getFeatureFlagDetails(t),P=[...(p=this.Oa(Tr))!==null&&p!==void 0?p:[]];C(s)&&P.push("flag_missing");var $={$feature_flag:t,$feature_flag_response:s,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((g=this.Ne.bootstrap)==null||(g=g.featureFlags)==null?void 0:g[t])||null,$feature_flag_bootstrapped_payload:((m=this.Ne.bootstrap)==null||(m=m.featureFlagPayloads)==null?void 0:m[t])||null,$used_bootstrap_value:!this.ka};C(E==null||(v=E.metadata)==null?void 0:v.has_experiment)||($.$feature_flag_has_experiment=E.metadata.has_experiment),C(E==null||(S=E.metadata)==null?void 0:S.version)||($.$feature_flag_version=E.metadata.version);var O,L=(b=E==null||(_=E.reason)==null?void 0:_.description)!==null&&b!==void 0?b:E==null||(x=E.reason)==null?void 0:x.code;L&&($.$feature_flag_reason=L),E!=null&&(I=E.metadata)!=null&&I.id&&($.$feature_flag_id=E.metadata.id),C(E?.original_variant)&&C(E?.original_enabled)||($.$feature_flag_original_response=C(E.original_variant)?E.original_enabled:E.original_variant),E!=null&&(T=E.metadata)!=null&&T.original_payload&&($.$feature_flag_original_payload=E==null||(O=E.metadata)==null?void 0:O.original_payload),P.length&&($.$feature_flag_error=P.join(",")),this.za($)}else n&&this.F({[Cn]:c,[Li]:n});if(r)return{key:t,enabled:!!s,variant:typeof s=="string"?s:void 0,payload:fc(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+Bo)}za(t){try{var e;(e=this.nn)==null||e.capture("$feature_flag_called",t).catch((n=>{this.rt.error("Failed to capture feature flag call",n)}))}catch(n){this.rt.error("Failed to capture feature flag call",n)}}getRemoteConfigPayload(t,e){this.Wa(t,e)}Wa(t,e){var n=this;return se((function*(){var i=n.nn;if(i){var r={distinct_id:i.distinctId,token:i.projectToken,person_properties:{$lib:i.library.name,$lib_version:i.library.version}},s=n.Na();s.length&&(r.evaluation_contexts=s);var o,a=n.qa();C(a)||(r.flag_keys=a);try{var l,u=(l=(yield i.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:r,compression:n.Ne.compression==="base64"?je.Base64:void 0,sentAt:"body",timeoutMs:n.Ne.requestTimeoutMs})).json)==null?void 0:l.featureFlagPayloads;o=u?.[t]||void 0}catch(c){return void n.rt.error("Remote config feature flag request failed",c)}try{e(o)}catch(c){n.rt.error("Remote config feature flag callback failed",c)}}}))()}isFeatureEnabled(t,e){if(e===void 0&&(e={}),e.fresh&&!this.ka)return e.defaultValue;if(!(this.ma||this.getFlags()&&this.getFlags().length>0))return this.rt.warn('isFeatureEnabled for key "'+t+Bo),e.defaultValue;var n=this.getFeatureFlag(t,e);return C(n)?e.defaultValue:!!n}addFeatureFlagsHandler(t){this.featureFlagEventHandlers.push(t)}removeFeatureFlagsHandler(t){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((e=>e!==t))}receivedFeatureFlags(t,e,n){this.ja(t,e,n)}ja(t,e,n){if(this.nn){this.ma=!0;var i=(function(r,s,o,a,l,u){s===void 0&&(s={}),o===void 0&&(o={}),a===void 0&&(a={}),u===void 0&&(u=gu);var c=((I,T)=>{var E=I.flags;return E?k({},I,{featureFlags:Object.fromEntries(Object.keys(E).map((P=>{var $;return[P,($=E[P].variant)!==null&&$!==void 0?$:E[P].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(E).filter((P=>E[P].enabled)).filter((P=>{var $;return($=E[P].metadata)==null?void 0:$.payload})).map((P=>{var $;return[P,($=E[P].metadata)==null?void 0:$.payload]})))}):(I.featureFlags&&T.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),I)})(r,u),d=c.flags,f=c.featureFlags,h=c.featureFlagPayloads;if(f){var p=r.requestId,g=r.evaluatedAt;if(U(f)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(f)for(var v=0;f.length>v;v++)m[f[v]]=!0;return{[Ti]:f,[Sn]:m,[Zr]:!1}}var S=f,b=h,_=d;if(l!=null&&l.partialResponse)S=k({},s,S),b=k({},o,b),_=k({},a,_);else if(r.errorsWhileComputingFlags)if(d){var x=new Set(Object.keys(d).filter((I=>{var T;return!((T=d[I])!=null&&T.failed)})));S=k({},s,Object.fromEntries(Object.entries(S).filter((I=>x.has(I[0]))))),b=k({},o,Object.fromEntries(Object.entries(b||{}).filter((I=>x.has(I[0]))))),_=k({},a,Object.fromEntries(Object.entries(_||{}).filter((I=>x.has(I[0])))))}else S=k({},s,S),b=k({},o,b),_=k({},a,_);return k({[Ti]:Object.keys(_u(S)),[Sn]:S||{},[$i]:b||{},[aa]:_||{},[Zr]:r.minimalFlagCalledEvents===!0},p?{[Pr]:p}:{},g?{[ji]:g}:{})}})(t,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),n,this.rt);i&&this.F(i),e||(this.xa=!1),this.Va(e)}}override(t,e){e===void 0&&(e=!1),this.rt.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:t,suppressWarning:e})}overrideFeatureFlags(t){this.Za(t)}Za(t){if(this.nn){if(t===!1)return this.q([xt,xn]),this.Va(),void bn.info("All overrides cleared");if(U(t))return this.F({[xt]:vu(t)}),this.Va(),void bn.info("Flag overrides set",{flags:t});if(t&&typeof t=="object"&&("flags"in t||"payloads"in t)){var e,n=t;this.ca=!!((e=n.suppressWarning)!==null&&e!==void 0&&e);var i={},r=n.flags,s=n.payloads;return r&&(i[xt]=U(r)?vu(r):r),s&&(i[xn]=s),Object.keys(i).length&&this.F(i),r===!1&&s===!1?this.q([xt,xn]):r===!1?this.q(xt):s===!1&&this.q(xn),this.Va(),r===!1?bn.info("Flag overrides cleared"):r&&bn.info("Flag overrides set",{flags:r}),void(s===!1?bn.info("Payload overrides cleared"):s&&bn.info("Payload overrides set",{payloads:s}))}if(t&&typeof t=="object")return this.F({[xt]:t}),this.Va(),void bn.info("Flag overrides set",{flags:t});this.rt.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:t})}else this.rt.warn("posthog.featureFlags.overrideFeatureFlags called before feature flags were ready")}onFeatureFlags(t){if(this.addFeatureFlagsHandler(t),this.ma){var e=this.Ga(),n=e.flags,i=e.flagVariants;try{t(n,i)}catch(r){this.rt.error("Error while running feature flags callback",r)}}return()=>this.removeFeatureFlagsHandler(t)}updateEarlyAccessFeatureEnrollment(t,e,n){var i=(this.Oa(Ar)||[]).find((l=>l.flagKey===t)),r={["$feature_enrollment/"+t]:e},s={$feature_flag:t,$feature_enrollment:e,$set:r};i&&(s.$early_access_feature_name=i.name),n&&(s.$feature_enrollment_stage=n);var o=k({},this.getFlagVariants(),{[t]:e});this.F({[Ti]:Object.keys(_u(o)),[Sn]:o,[Dt]:k({},this.Oa(Dt)||{},r)}),this.Va();try{var a;(a=this.nn)==null||a.capture("$feature_enrollment_update",s).catch((l=>{this.rt.error("Failed to capture early access feature enrollment",l)}))}catch(l){this.rt.error("Failed to capture early access feature enrollment",l)}}getEarlyAccessFeatures(t,e,n){e===void 0&&(e=!1);var i=this.Oa(Ar);!i||e?this.Qa(t,n):t(i)}Qa(t,e){var n=this;return se((function*(){var i=n.nn;if(i){var r,s=e?"&"+e.map((a=>"stage="+a)).join("&"):"";try{var o=yield i.sendRequest("/api/early_access_features/?token="+i.projectToken+s,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;n.F({[Ar]:r=o.json.earlyAccessFeatures})}catch(a){return void n.rt.error("Early access feature request failed",a)}try{t(r)}catch(a){n.rt.error("Early access feature callback failed",a)}}}))()}Ga(){var t=this.getFlags(),e=this.getFlagVariants();return{flags:t.filter((n=>e[n])),flagVariants:Object.keys(e).filter((n=>e[n])).reduce(((n,i)=>(n[i]=e[i],n)),{})}}Va(t){this.Fa();var e=this.Ga(),n=e.flags,i=e.flagVariants;this.featureFlagEventHandlers.forEach((r=>{try{r(n,i,{errorsLoading:t})}catch(s){this.rt.error("Error while running feature flags callback",s)}}))}setPersonPropertiesForFlags(t,e){e===void 0&&(e=!0),this.Ka(t,e)}Ka(t,e){e===void 0&&(e=!0);var n=this.Oa(Dt)||{},i=t?.$set||(t!=null&&t.$set_once?{}:t),r=t?.$set_once,s={};if(r)for(var o in r)({}).hasOwnProperty.call(r,o)&&(o in n||(s[o]=r[o]));this.F({[Dt]:k({},n,s,i)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=k({},this.Oa(Dt)||{});t.forEach((i=>{delete n[i]})),this.F({[Dt]:n}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(Dt),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=this.Oa(In)||{},i=k({},n);for(var r of Object.keys(t))i[r]=k({},n[r],t[r]);this.F({[In]:i}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(In)||{};this.F({[In]:k({},e,{[t]:{}})})}else this.q(In)}reset(){this.ba++,this.wa=!1,this.Fa(),this.ma=!1,this._a=!1,this.ka=!1,this.$anon_distinct_id=void 0,this.La(),this.ca=!1,this.Sa=0}}},Um={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===ki||this.Ya===Sr?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=lu,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(F==null||!F.visibilityState||F.visibilityState==="visible")return!0;var n=w==null||(e=w.performance)==null||e.getEntriesByType==null?void 0:e.getEntriesByType("visibility-state");return!(n!=null&&n.length)||n.some((i=>i.name==="visible"))})(),this.Ie=()=>{var e;F?.visibilityState==="visible"&&(this.io=!0,(e=this.Ja)==null||e.setDocumentWasEverVisible==null||e.setDocumentWasEverVisible(!0))},this._instance=t,!this._instance.sessionManager)throw Ot.error("started without valid sessionManager"),new Error(Ia+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===Ht)throw new Error(Ia+' cannot be used with cookieless_mode="always"');F!=null&&F.addEventListener&&ve(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(An))==null||!t.enabled),n=!this.Ne.disable_session_recording,i=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return w&&e&&n&&!i}startIfEnabledOrStop(t){var e;if(!(this.eo||this.ro&&(e=this.Ja)!=null&&e.isStarted)){var n=!C(Object.assign)&&!C(Array.from);this.ro&&n?(this.no(t),Ot.info("starting")):(this.Ya=lu,this.stopRecording())}}no(t){var e,n,i;this.ro&&(this.Ya!==ki&&this.Ya!==Sr&&(this.Ya=cu),B!=null&&(e=B.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(n=B.__PosthogExtensions__)!=null&&n.initSessionRecording?this.so(t):(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,this.ao,(r=>{if(r)return Ot.error("could not load recorder",r);this.so(t)})))}stopRecording(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.stop()}oo(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.discard()}lo(){var t,e;(t=this.Mr)==null||t.unregister(ol),(e=this.Mr)==null||e.unregister(Vd)}uo(t,e){if(H(t))return null;var n,i=ke(t)?t:parseFloat(t);return typeof(n=i)!="number"||!Number.isFinite(n)||0>n||n>1?(Ot.warn(e+" must be between 0 and 1. Ignoring invalid value:",t),null):i}ho(t){if(this.Mr){var e,n,i=this.Mr,r=()=>{var s,o=t.sessionRecording===!1?void 0:t.sessionRecording,a=this.uo((s=this.Ne.session_recording)==null?void 0:s.sampleRate,"session_recording.sampleRate"),l=this.uo(o?.sampleRate,"remote config sampleRate"),u=a??l;H(u)&&this.lo();var c=o?.minimumDurationMilliseconds;i.register({[An]:k({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:k({capturePerformance:t.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:u,minimumDurationMilliseconds:C(c)?null:c,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers,version:o?.version,triggerGroups:o?.triggerGroups})})};r(),(e=this.Xa)==null||e.call(this),this.Xa=(n=this._instance.sessionManager)==null?void 0:n.onSessionId(r)}}onRemoteConfig(t){var e=t.ok?t.config:void 0;return e&&"sessionRecording"in e?e.sessionRecording===!1?(this.ho(e),void this.oo()):(this.ho(e),void this.startIfEnabledOrStop()):(this.Ya===ki&&(this.Ya=Sr,Ot.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(t,e){var n;e===void 0&&(e="log"),(n=this.Ja)!=null&&n.log?this.Ja.log(t,e):Ot.warn("log called before recorder was ready")}get ao(){var t,e,n=(t=this._instance)==null||(t=t.persistence)==null?void 0:t.get_property(An);return(n==null||(e=n.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(An);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(n){return Ot.warn("persisted remote config for session recording is invalid and will be ignored",n),!1}return!H(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,n,i;if(!this.eo){if((e=B.__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({[ef]:!0});var r;if(this.Ja||(this.Ja=(r=B.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===Sr||this.Ya===ki?void 0:(this.Ya=ki,Ot.info("persisted remote config is stale, requesting fresh config before starting"),void new kf(this._instance).load());this.Ya=cu,(n=(i=this.Ja).setDocumentWasEverVisible)==null||n.call(i,this.io),this.Ja.start(t)}}onRRwebEmit(t){var e;(e=this.Ja)==null||e.onRRwebEmit==null||e.onRRwebEmit(t)}overrideLinkedFlag(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Kd]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Gd]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,n;this.Ja||(n=this.Mr)==null||n.register({[t==="url"?Yd:Jd]:!0}),(e=this.Ja)==null||e.overrideTrigger(t)}get sdkDebugProperties(){var t;return((t=this.Ja)==null?void 0:t.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(t,e){var n;return!((n=this.Ja)==null||!n.tryAddCustomEvent(t,e))}}},Hm={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new su(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,n=he(this.instance.config.autocapture)?this.instance.config.autocapture:{};return n.url_allowlist=(t=n.url_allowlist)==null?void 0:t.map((i=>new RegExp(i))),n.url_ignorelist=(e=n.url_ignorelist)==null?void 0:e.map((i=>new RegExp(i))),n}yo(){if(this.isBrowserSupported()){if(w&&F){var t=n=>{n=n||w?.event;try{this.bo(n)}catch(i){Mo.error("Failed to capture event",i)}};if(ve(F,"submit",t,{capture:!0}),ve(F,"change",t,{capture:!0}),ve(F,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=n=>{n=n||w?.event;try{this.bo(n,$o)}catch(i){Mo.error("Failed to capture copy/cut event",i)}};ve(F,"copy",e,{capture:!0}),ve(F,"cut",e,{capture:!0})}}}else Mo.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.vo&&(this.yo(),this.vo=!0)}onRemoteConfig(t){if(this.fo=!0,t.ok){var e=t.config;e.elementsChainAsString&&(this.po=e.elementsChainAsString);var n=e.autocapture_opt_out;gt(n)&&(this.instance.persistence&&this.instance.persistence.register({[ea]:n}),this.co=n),this.startIfEnabled()}else this.startIfEnabled()}setElementSelectors(t){this.mo=t}getElementSelectors(t){var e,n=[];return(e=this.mo)==null||e.forEach((i=>{var r=F?.querySelectorAll(i);r?.forEach((s=>{t===s&&n.push(i)}))})),n}get isEnabled(){var t,e,n=(t=this.instance.persistence)==null?void 0:t.props[ea],i=this.co,r=this.instance.Qi()&&!this.fo;if(Ke(i)&&!gt(n)&&!r)return!1;var s=(e=this.co)!==null&&e!==void 0?e:!!n;return!!this.instance.config.autocapture&&!s}bo(t,e){if(e===void 0&&(e="$autocapture"),this.isEnabled){var n,i=bo(t);of(i)&&(i=i.parentNode||null),e==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&this.instance.config.rageclick&&(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,t.timeStamp||new Date().getTime())&&Lc(i,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var r=e===$o;if(i&&(function(d,f,h,p,g,m){var v;if(!w||dl(d)||h!=null&&h.url_allowlist&&!Tc(h.url_allowlist,m)||h!=null&&h.url_ignorelist&&Tc(h.url_ignorelist,m))return!1;if(h!=null&&h.dom_event_allowlist){var S=h.dom_event_allowlist;if(S&&!S.some((E=>f.type===E)))return!1}var b=ff(d,p),_=b.parentIsUsefulElement,x=b.targetElementList;if(!(function(E,P){var $=P?.element_allowlist;if(C($))return!0;var O,L=function(K){if($.some((V=>K.tagName.toLowerCase()===V)))return{v:!0}};for(var N of E)if(O=L(N))return O.v;return!1})(x,h)||!ma(x,h?.css_selector_allowlist)||ma(x,(v=h?.css_selector_ignorelist)!==null&&v!==void 0?v:Dg))return!1;try{var I=w.getComputedStyle(d);if(I&&I.getPropertyValue("cursor")==="pointer"&&f.type==="click")return!0}catch{}var T=d.tagName.toLowerCase();switch(T){case"html":return!1;case"form":return(g||["submit"]).indexOf(f.type)>=0;case"input":case"select":case"textarea":return(g||["change","click"]).indexOf(f.type)>=0;default:return _?(g||["click"]).indexOf(f.type)>=0:(g||["click"]).indexOf(f.type)>=0&&(ul.indexOf(T)>-1||d.getAttribute("contenteditable")==="true")}})(i,t,this.Ne,r,r?["copy","cut"]:void 0,this.instance)){var s=Rm(i,{e:t,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.Ne.element_attribute_ignorelist,elementsChainAsString:this.po,disableCaptureUrlHashes:this.instance.config.disable_capture_url_hashes}),o=s.props;if(s.explicitNoCapture)return!1;var a=this.getElementSelectors(i);if(a&&a.length>0&&(o.$element_selectors=a),e===$o){var l,u=cf(w==null||(l=w.getSelection())==null?void 0:l.toString()),c=t.type||"clipboard";if(!u)return!1;o.$selected_content=u,o.$copy_type=c}return this.instance.capture(e,o),!0}}}isBrowserSupported(){return De(F?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(w==null||(e=w.location)==null?void 0:e.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(A.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.wo&&this.wo(),this.wo=void 0,A.info("History API monitoring stopped")}monitorHistoryChanges(){w&&w.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(w&&((e=w.history[t])==null||!e.__posthog_wrapped__)){var n=this;(function(i,r,s){try{if(!(r in i))return ou;var o={next:i[r]},a=s((function(){for(var l=arguments.length,u=new Array(l),c=0;l>c;c++)u[c]=arguments[c];return o.next.apply(this,u)}));return De(a)&&(a.prototype=a.prototype||{},Object.defineProperties(a,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:o}})),i[r]=a,()=>{if(i[r]!==a)for(var l=i[r];De(l)&&l.__posthog_layer__;){var u=l.__posthog_layer__;if(u.next===a)return void(u.next=o.next);l=u.next}else i[r]=o.next}}catch{return ou}})(w.history,t,(i=>function(r,s,o){i.call(this,r,s,o),n.So(t)}))}}So(t){try{var e,n=w==null||(e=w.location)==null?void 0:e.pathname;if(!n)return;n!==this._o&&this.isEnabled&&this._instance.capture(Vn,{navigation_type:t}),this._o=n}catch(i){A.error("Error capturing "+t+" pageview",i)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};ve(w,"popstate",t),this.wo=()=>{w&&w.removeEventListener("popstate",t)}}}},heatmaps:class{get Ne(){return this.instance.config}constructor(t){var e;this.Co=!1,this.vo=!1,this.Mo=null,this.instance=t,this.Co=!((e=this.instance.persistence)==null||!e.props[ta]),this.rageclicks=new su(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return he(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return H(this.Ne.capture_heatmaps)?H(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;$m.info("starting..."),this.To(),this.Ie()}else{var t;clearInterval((t=this.Mo)!==null&&t!==void 0?t:void 0),this.Eo(),this.getAndClearBuffer()}}onRemoteConfig(t){if(t.ok){var e=t.config;if("heatmaps"in e){var n=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[ta]:n}),this.Co=n,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){No(t.originalEvent)&&this.ke(t.originalEvent,"deadclick")}Ie(){this.Mo&&clearInterval(this.Mo),this.Mo=F?.visibilityState==="visible"?setInterval(this.cr.bind(this),this.flushIntervalMilliseconds):null}To(){w&&F&&(this.Po=this.cr.bind(this),ve(w,ns,this.Po),this.Ro=t=>this.ke(t||w?.event),ve(F,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||w?.event),ve(F,"mousemove",this.Ao,{capture:!0}),this.Lo=new Hc(this.instance,Vg,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),ve(F,ts,this.Oo),this.vo=!0)}Eo(){var t;w&&F&&(this.Po&&w.removeEventListener(ns,this.Po),this.Ro&&F.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&F.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&F.removeEventListener(ts,this.Oo),clearTimeout(this.Do),(t=this.Lo)==null||t.stop(),this.vo=!1)}$o(t,e){var n=this.instance.scrollManager.scrollY(),i=this.instance.scrollManager.scrollX(),r=this.instance.scrollManager.scrollElement(),s=(function(o,a,l){for(var u=o;u&&hn(u)&&!Qe(u,"body");){if(u===l)return!1;var c=void 0;try{var d,f,h;c=(d=(f=(h=u.ownerDocument)==null?void 0:h.defaultView)!==null&&f!==void 0?f:w)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(j(a,c))return!0;u=uf(u)}return!1})(bo(t),["fixed","sticky"],r);return{x:t.clientX+(s?0:i),y:t.clientY+(s?0:n),target_fixed:s,type:e}}ke(t,e){var n;if(e===void 0&&(e="click"),!Rc(t.target)&&No(t)){var i=this.$o(t,e);(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,new Date().getTime())&&Lc(bo(t),this.instance.config.rageclick)&&this.Vt(k({},i,{type:"rageclick"})),this.Vt(i)}}Fo(t){!Rc(t.target)&&No(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(w){var e=this.Ne.disable_capture_url_hashes?fn(w.location.href):w.location.href,n=this.Ne.custom_personal_data_properties,i=this.Ne.mask_personal_data_properties?[...ri,...n||[]]:[],r=Zi(e,i,Xi);this.R=this.R||{},this.R[r]||(this.R[r]=[]),this.R[r].push(t)}}cr(){this.R&&!Gt(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:Hc,webVitalsAutocapture:class{constructor(t){var e;this.Co=!1,this.vo=!1,this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this.No=()=>{clearTimeout(this.qo),this.qo=void 0,this.R.metrics.length!==0&&(this._instance.capture("$web_vitals",k({$current_url:this.R.url},this.R.metrics.reduce(((n,i)=>k({},n,{["$web_vitals_"+i.name+"_event"]:k({},i),["$web_vitals_"+i.name+"_value"]:i.value})),{}))),this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.jo=n=>{var i;if(this.R=this.R||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},H(n?.name)||H(n?.value))wn.error("Invalid metric received",n);else{var r=typeof n.navigationURL=="string"?n.navigationURL:void 0,s=this.Bo(r);if(!C(s)){var o=ke(n.navigationId)||typeof n.navigationId=="string"?"navigation:"+n.navigationId:"url:"+s;if(!this.Ho||this.Ho>n.value){this.R.navigationKey!==o&&(this.No(),this.qo=setTimeout(this.No,this.flushToCaptureTimeoutMs)),C(this.R.navigationKey)&&(this.R.navigationKey=o,this.R.url=s),this.R.firstMetricTimestamp=C(this.R.firstMetricTimestamp)?Date.now():this.R.firstMetricTimestamp,n.attribution&&n.attribution.interactionTargetElement&&(n.attribution.interactionTargetElement=void 0);var a=(i=this._instance.sessionManager)==null?void 0:i.checkAndGetSessionAndWindowId(!0),l=k({},n,r?{navigationURL:s}:{},{$current_url:s,timestamp:Date.now()});C(a)||(l.$session_id=a.sessionId,l.$window_id=a.windowId),this.R.metrics.push(l),this.R.metrics.length===this.allowedMetrics.length&&this.No()}else wn.error("Ignoring metric with value >= "+this.Ho,n)}}},this.Uo=()=>{if(!this.vo){var n,i,r,s,o=B.__PosthogExtensions__,a=o?.postHogWebVitalsCallbacksByFlavor,l=a?.[this.zo]||(this.zo==="web-vitals"&&C(a)?o?.postHogWebVitalsCallbacks:void 0);if(C(l)||(n=l.onLCP,i=l.onCLS,r=l.onFCP,s=l.onINP),n&&i&&r&&s){var u={reportSoftNavs:this.useSoftNavs};this.allowedMetrics.indexOf("LCP")>-1&&n(this.jo.bind(this),u),this.allowedMetrics.indexOf("CLS")>-1&&i(this.jo.bind(this),u),this.allowedMetrics.indexOf("FCP")>-1&&r(this.jo.bind(this),u),this.allowedMetrics.indexOf("INP")>-1&&s(this.jo.bind(this),u),this.vo=!0}else wn.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[sa]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,n=he(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return H(n)?((e=this._instance.persistence)==null?void 0:e.props[oa])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(he(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=he(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=he(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=he(this.Wo)&&ke(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:au;return t>0&&6e4>=t?au:t}get isEnabled(){var t=me?.protocol;if(t!=="http:"&&t!=="https:")return wn.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=he(this.Wo)?this.Wo.web_vitals:gt(this.Wo)?this.Wo:void 0;return gt(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(wn.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var n=he(e.capturePerformance)&&!!e.capturePerformance.web_vitals,i=he(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[sa]:n}),this._instance.persistence.register({[oa]:i})),this.Co=n,this.startIfEnabled()}}}get zo(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}ai(t){var e=B.__PosthogExtensions__,n=this.zo,i=e?.postHogWebVitalsCallbacksByFlavor;i!=null&&i[n]||n==="web-vitals"&&C(i)&&e!=null&&e.postHogWebVitalsCallbacks?t():e==null||e.loadExternalDependency==null||e.loadExternalDependency(this._instance,n,(r=>{r?wn.error("failed to load script",r):t()}))}Bo(t){var e=t||w?.location.href;if(e){var n=this._instance.config.disable_capture_url_hashes?fn(e):e,i=this._instance.config.custom_personal_data_properties,r=this._instance.config.mask_personal_data_properties?[...ri,...i||[]]:[];return Zi(n,r,Xi)}wn.error("Could not determine current URL")}}},Wm={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var n;if(w&&this.isEnabled&&(n=B.__PosthogExtensions__)!=null&&n.errorWrappingFunctions){var i=B.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,r=B.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,s=B.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.Vo&&this.Ne.capture_unhandled_errors&&(this.Vo=i(this.captureException.bind(this))),!this.Zo&&this.Ne.capture_unhandled_rejections&&(this.Zo=r(this.captureException.bind(this))),!this.Go&&this.Ne.capture_console_errors&&(this.Go=s(this.captureException.bind(this)))}catch(o){Ii.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[na]),this.Jo=new Up(k({},(function(n){var i,r,s,o;return n===void 0&&(n={}),{refillRate:(i=(r=n.exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:n.__exceptionRateLimiterRefillRate)!==null&&i!==void 0?i:1,bucketSize:(s=(o=n.exceptionRateLimiterBucketSize)!==null&&o!==void 0?o:n.__exceptionRateLimiterBucketSize)!==null&&s!==void 0?s:10}})(this._instance.config.error_tracking),{refillInterval:1e4,rt:Ii})),this.Ne=this.Yo(),this.startIfEnabledOrStop()}Yo(){var t=this._instance.config.capture_exceptions,e={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return he(t)?e=k({},e,t):(C(t)?this.Ko:t)&&(e=k({},e,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),e}get isEnabled(){return this.Ne.capture_console_errors||this.Ne.capture_unhandled_errors||this.Ne.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(Ii.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",(i=>{if(i)return Ii.error("failed to load script",i);t()}))}Qo(){var t,e,n;(t=this.Vo)==null||t.call(this),this.Vo=void 0,(e=this.Zo)==null||e.call(this),this.Zo=void 0,(n=this.Go)==null||n.call(this),this.Go=void 0}onRemoteConfig(t){if(t.ok){var e=t.config;"autocaptureExceptions"in e&&(this.Ko=!!e.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[na]:this.Ko}),this.Ne=this.Yo(),this.startIfEnabledOrStop())}}onConfigChange(){this.Ne=this.Yo()}captureException(t){var e,n,i,r=(e=t==null||(n=t.$exception_list)==null||(n=n[0])==null?void 0:n.type)!==null&&e!==void 0?e:"Exception";this.Jo.consumeRateLimit(r)?Ii.info("Skipping exception capture because of client rate limiting.",{exception:r}):(i=this._instance.exceptions)==null||i.sendExceptionEvent(t)}},exceptions:class{constructor(t){var e,n;this.Xo=[],this.tl=new rg([new fg,new bg,new pg,new hg,new yg,new _g,new mg,new wg],(function(i){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;r>o;o++)s[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` +`),d=l;c.length>d;d++){var f=c[d];if(1024>=f.length){var h=Cc.test(f)?f.replace(Cc,"$1"):f;if(!h.match(/\S*Error: /)){for(var p of s){var g=p(h,i);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var v=Array.from(m);return v.reverse(),v.slice(0,50).map((S=>{return k({},S,{filename:S.filename||(b=v,b[b.length-1]||{}).filename,function:S.function||ni});var b}))})(u)}})("web:javascript",lg,dg)),this._instance=t,this.Xo=(e=(n=this._instance.persistence)==null?void 0:n.get_property(ia))!==null&&e!==void 0?e:[],this.el=Jr(this.il()),this.rl=new Sg(this.el)}onConfigChange(){this.el=Jr(this.il()),this.rl.setConfig(this.el)}onRemoteConfig(t){var e,n,i;if(t.ok){var r=t.config;if("errorTracking"in r){var s=(e=(n=r.errorTracking)==null?void 0:n.suppressionRules)!==null&&e!==void 0?e:[],o=(i=r.errorTracking)==null?void 0:i.captureExtensionExceptions;this.Xo=s,this._instance.persistence&&this._instance.persistence.register({[ia]:this.Xo,[ra]:o})}}}get nl(){var t,e=!!this._instance.get_property(ra),n=this._instance.config.error_tracking.captureExtensionExceptions;return(t=n??e)!==null&&t!==void 0&&t}buildProperties(t,e){return this.tl.buildFromUnknown(t,{syntheticException:e?.syntheticException,mechanism:{handled:e?.handled}})}addExceptionStep(t,e){if(this.el.enabled)try{if(!X(t)||t.trim().length===0)return void Et.warn("Ignoring exception step because message must be a non-empty string");var n=(function(s){if(!s)return{sanitizedProperties:{},droppedKeys:[]};var o=[];return{sanitizedProperties:Object.keys(s).reduce(((a,l)=>Eg.has(l)?(o.push(l),a):(a[l]=s[l],a)),{}),droppedKeys:o}})(this.sl(e)),i=n.sanitizedProperties,r=n.droppedKeys;r.length>0&&Et.warn("Ignoring reserved exception step fields",{droppedKeys:r}),this.rl.add(k({[Kr]:t,[Yr]:new Date().toISOString()},i))}catch(s){Et.error("Failed to add exception step. Ignoring breadcrumb.",s)}}sendExceptionEvent(t){try{var e=t.$exception_list;if(this.al(e)){if(this.ol(e))return this.ll("Exception dropped: matched a suppression rule"),void Et.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 Et.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 Et.info("Skipping exception capture because it was thrown by the PostHog SDK")}var n=this.el.enabled&&H(t.$exception_steps)?this.dl(t):t,i=typeof(s=globalThis._posthogReleaseId)=="string"&&s.length>0?s:void 0;i&&(n.$release_id=i);try{var r=this._instance.capture("$exception",n,{_noTruncate:!0,_batchKey:"exceptionEvent",Wn:!0});return r&&this.rl.clear(),r}catch(o){return Et.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void Et.error("Failed to process exception event. Ignoring this exception.",o)}var s}dl(t){try{var e=this.rl.getAttachable();return e.length===0?t:k({},t,{$exception_steps:e})}catch(n){return Et.error("Failed to read buffered exception steps. Capturing exception without steps.",n),t}}ll(t){this.el.enabled&&this.rl.add({[Kr]:t,[Yr]:new Date().toISOString()})}sl(t){return he(t)?k({},t):{}}il(){var t,e;return(t=(e=this._instance.config.error_tracking)==null?void 0:e.exception_steps)!==null&&t!==void 0?t:{}}ol(t){if(t.length===0)return!1;try{var e=t.reduce(((n,i)=>{var r=i.type,s=i.value;return X(r)&&r.length>0&&n.$exception_types.push(r),X(s)&&s.length>0&&n.$exception_values.push(s),n}),{$exception_types:[],$exception_values:[]});return this.Xo.some((n=>{var i=n.values.map((r=>{var s=jf[r.operator],o=e[r.key];if(!s||!o)return!1;var a=U(r.value)?r.value:[r.value];return a.length>0&&s(a,o)}));return n.type==="OR"?i.some(Boolean):i.every(Boolean)}))}catch(n){return Et.warn("Failed to evaluate suppression rules. Capturing the exception.",n),!1}}ul(t){return t.flatMap((e=>{var n,i;return(n=(i=e.stacktrace)==null?void 0:i.frames)!==null&&n!==void 0?n:[]})).some((e=>e.filename&&e.filename.startsWith("chrome-extension://")))}hl(t){if(t.length>0){var e,n,i,r,s=(e=(n=t[0].stacktrace)==null?void 0:n.frames)!==null&&e!==void 0?e:[],o=s[s.length-1];return(i=o==null||(r=o.filename)==null?void 0:r.includes("posthog.com/static"))!==null&&i!==void 0&&i}return!1}al(t){return!H(t)&&U(t)}}},qm=k({productTours:class{get Mr(){return this._instance.persistence}constructor(t){this.vl=null,this.cl=null,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(t.ok){var e=t.config;if("productTours"in e){var n,i;if(this.Mr&&this.Mr.register({[sl]:!!e.productTours}),!Oo(this._instance))return!this.vl&&H((n=this.Mr)==null?void 0:n.props[Mi])||xr.info("product tours disabled; stopping and clearing cached tours"),(i=this.vl)==null||i.stop(),this.vl=null,void this.clearCache();this.loadIfEnabled()}}}loadIfEnabled(){!this.vl&&Oo(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.generateProductTours?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",(i=>{i?xr.error("Could not load product tours script",i):t()}))}fl(){var t;!this.vl&&(t=B.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=B.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(t,e){if(e===void 0&&(e=!1),!U(this.cl)||e){var n=this.Mr;if(n){var i=n.props[Mi];if(U(i)&&!e)return this.cl=i,void t(i,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",timestampMode:"query",callback:r=>{if(Oo(this._instance)){var s=r.statusCode;if(s!==200||!r.json){var o="Product Tours API could not be loaded, status: "+s;return s===0?r.error||xr.warn(o):xr.error(o),void t([],{isLoaded:!1,error:o})}var a=U(r.json.product_tours)?r.json.product_tours:[];this.cl=a,n&&n.register({[Mi]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){H(this.vl)?t([],{isLoaded:!1,error:"Product tours not loaded"}):this.vl.getActiveProductTours(t)}showProductTour(t){var e;(e=this.vl)==null||e.showTourById(t)}previewTour(t){this.vl?this.vl.previewTour(t):this.ai((()=>{var e;this.fl(),(e=this.vl)==null||e.previewTour(t)}))}dismissProductTour(){var t;(t=this.vl)==null||t.dismissTour("user_clicked_skip")}nextStep(){var t;(t=this.vl)==null||t.nextStep()}previousStep(){var t;(t=this.vl)==null||t.previousStep()}clearCache(){var t;this.cl=null,(t=this.Mr)==null||t.unregister(Mi)}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)}}},Cs),zm={siteApps:class{constructor(t){this.pl=0,this._instance=t,this.gl=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}ml(t,e){if(e){var n=this.globalsForEvent(e);this.gl.push(n),this.gl.length>1e3&&(this.gl=this.gl.slice(10))}}get siteAppLoaders(){var t;return(t=B._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,n,i,r,s,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var f=d[0];l[f]={id:u[f],type:f,properties:d[1]}}var h=t.$set_once,p=t.$set;return{event:k({},ud(t,Mm),{properties:k({},t.properties,p?{$set:k({},(e=(n=t.properties)==null?void 0:n.$set)!==null&&e!==void 0?e:{},p)}:{},h?{$set_once:k({},(i=(r=t.properties)==null?void 0:r.$set_once)!==null&&i!==void 0?i:{},h)}:{}),elements_chain:(s=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&s!==void 0?s:"",distinct_id:(a=t.properties)==null?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}bl(t){var e,n=(e=t.tagName)==null?void 0:e.toLowerCase();return n==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(bt.error("prepare_external_dependency_stylesheet returned null"),null):n==="script"&&this._instance.config.prepare_external_dependency_script?this._instance.config.prepare_external_dependency_script(t)||(bt.error("prepare_external_dependency_script returned null"),null):t}_l(){var t,e,n,i,r,s,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=F?.defaultView,u=l==null||(t=l.Node)==null?void 0:t.prototype;if(!l||!u)return()=>{};if(this.pl++,this.wl)return this.kl();var c=[],d=this,f=new WeakSet,h=(m,v,S)=>{if(m!=null&&m[v]){var b=m[v];m[v]=S(b),c.push((()=>{m[v]=b}))}},p=m=>{if(f.has(m))return m;var v=d.bl(m);return v&&f.add(v),v},g=m=>m.map((v=>typeof v=="string"?v:p(v))).filter((v=>!Ke(v)));return h(u,"appendChild",(m=>function(v){var S=p(v);return S?m.call(this,S):v})),h(u,"insertBefore",(m=>function(v,S){var b=p(v);return b?m.call(this,b,S):v})),h(u,"replaceChild",(m=>function(v,S){var b=p(v);return b?m.call(this,b,S):S})),[(e=l.Element)==null?void 0:e.prototype,(n=l.Document)==null?void 0:n.prototype,(i=l.DocumentFragment)==null?void 0:i.prototype].forEach((m=>{h(m,"append",(v=>function(){for(var S=arguments.length,b=new Array(S),_=0;S>_;_++)b[_]=arguments[_];return v.apply(this,g(b))})),h(m,"prepend",(v=>function(){for(var S=arguments.length,b=new Array(S),_=0;S>_;_++)b[_]=arguments[_];return v.apply(this,g(b))}))})),[(r=l.Element)==null?void 0:r.prototype,(s=l.CharacterData)==null?void 0:s.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((m=>{h(m,"before",(v=>function(){for(var S=arguments.length,b=new Array(S),_=0;S>_;_++)b[_]=arguments[_];return v.apply(this,g(b))})),h(m,"after",(v=>function(){for(var S=arguments.length,b=new Array(S),_=0;S>_;_++)b[_]=arguments[_];return v.apply(this,g(b))})),h(m,"replaceWith",(v=>function(){for(var S=arguments.length,b=new Array(S),_=0;S>_;_++)b[_]=arguments[_];var x=g(b);return b.length&&!x.length?void 0:v.apply(this,x)}))})),h((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(v,S){var b=p(S);return b?m.call(this,v,b):null})),this.wl=()=>{c.forEach((m=>m())),this.wl=void 0},this.kl()}kl(){var t=!1;return()=>{var e;t||(t=!0,this.pl--,this.pl===0&&((e=this.wl)==null||e.call(this)))}}xl(t,e){e===void 0&&(e=!0);var n=this._l();try{var i=t(n);return e&&n(),i}catch(r){throw n(),r}}setupSiteApp(t){var e=this.apps[t.id],n=()=>{var o;!e.errored&&this.gl.length&&(bt.info("Processing "+this.gl.length+" events for site app with id "+t.id),this.gl.forEach((a=>this.xl((()=>e.processEvent==null?void 0:e.processEvent(a))))),e.processedBuffer=!0),Object.values(this.apps).every((a=>a.processedBuffer||a.errored))&&((o=this.yl)==null||o.call(this))},i=!1,r=o=>{e.errored=!o,e.loaded=!0,bt.info("Site app with id "+t.id+" "+(o?"loaded":"errored")),i&&n()};try{var s=this.xl((o=>t.init({posthog:this._instance,callback(a){o(),r(a)}})),!1).processEvent;s&&(e.processEvent=s),i=!0}catch(o){bt.error(uu+t.id,o),r(!1)}if(i&&e.loaded)try{n()}catch(o){bt.error("Error while processing buffered events PostHog app with config id "+t.id,o),e.errored=!0}}Sl(){var t=this.siteAppLoaders||[];for(var e of t)this.apps[e.id]={id:e.id,loaded:!1,errored:!1,processedBuffer:!1};for(var n of t)this.setupSiteApp(n)}Cl(t){var e=this;if(Object.keys(this.apps).length!==0){var n=this.globalsForEvent(t),i=function(s){try{e.xl((()=>s.processEvent==null?void 0:s.processEvent(n)))}catch(o){bt.error("Error while processing event "+t.event+" for site app "+s.id,o)}};for(var r of Object.values(this.apps))i(r)}}onRemoteConfig(t){var e,n,i,r=this;if((e=this.siteAppLoaders)!=null&&e.length)return this.isEnabled?(this.Sl(),void this._instance.on("eventCaptured",(l=>this.Cl(l)))):void bt.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((n=this.yl)==null||n.call(this),t.ok){var s=t.config;if((i=s.siteApps)!=null&&i.length)if(this.isEnabled){var o=function(){var l,u=a.id,c=a.url;B["__$$ph_site_app_"+u]=r._instance,(l=B.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(r._instance,c,(d=>{if(d)return bt.error(uu+u,d)}))};for(var a of s.siteApps)o()}else bt.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},Vm={tracingHeaders:class{constructor(t){this.Ml=void 0,this.Tl=void 0,this.El=void 0,this.Uo=()=>{var e,n,i=this.Il();i?(C(this.Ml)&&(this.Ml=(e=B.__PosthogExtensions__)==null||(e=e.tracingHeadersPatchFns)==null?void 0:e._patchXHR(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager)),C(this.Tl)&&(this.Tl=(n=B.__PosthogExtensions__)==null||(n=n.tracingHeadersPatchFns)==null?void 0:n._patchFetch(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager))):this.Qo()},this._instance=t}initialize(){this.startIfEnabledOrStop()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",(i=>{if(i)return Tm.error("failed to load script",i);t()}))}Pl(){var t,e;return(t=(e=this._instance.config.tracing_headers)!==null&&e!==void 0?e:this._instance.config.addTracingHeaders)!==null&&t!==void 0?t:this._instance.config.__add_tracing_headers}Il(){var t=this.Pl();return U(t)?(U(this.El)?this.El.splice(0,this.El.length,...t):this.El=[...t],t.length>0?this.El:void 0):(U(this.El)&&this.El.splice(0),this.El=t||void 0,this.El)}Qo(){var t,e;(t=this.Ml)==null||t.call(this),(e=this.Tl)==null||e.call(this),this.Ml=void 0,this.Tl=void 0}startIfEnabledOrStop(){this.Il()?this.ai(this.Uo):this.Qo()}}},Gm=k({surveys:class{get Ne(){return this._instance.config}constructor(t){this.Rl=void 0,this._surveyManager=null,this.Al=!1,this.Fl=[],this.Ll=null,this.Ol=null,this._instance=t,this._surveyEventReceiver=null}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this.Ne.disable_surveys){if(!t.ok)return Q.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(H(e))return Q.warn("Flags not loaded yet. Not loading surveys.");var n=U(e);this.Rl=n?e.length>0:e,Q.info("flags response received, isSurveysEnabled: "+this.Rl),this.loadIfEnabled()}}reset(){try{var t;(t=this._surveyEventReceiver)==null||t.reset(),localStorage.removeItem("lastSeenSurveyDate");for(var e=[],n=0;nlocalStorage.removeItem(r)))}catch{}}loadIfEnabled(){if(!this._surveyManager)if(this.Al)Q.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)Q.info(du);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())Q.info("Not loading surveys in cookieless mode without consent.");else{var t=B?.__PosthogExtensions__;if(t){if(!C(this.Rl)||this.Ne.advanced_enable_surveys){var e=this.Rl||this.Ne.advanced_enable_surveys;this.Al=!0;try{var n=t.generateSurveys;if(n)return void this.Dl(n,e);var i=t.loadExternalDependency;if(!i)return void this.$l(al);i(this._instance,"surveys",(r=>{r||!t.generateSurveys?this.$l("Could not load surveys script",r):this.Dl(t.generateSurveys,e)}))}catch(r){throw this.$l("Error initializing surveys",r),r}finally{this.Al=!1}}}else Q.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new Om(this._instance),Q.info("Surveys loaded successfully"),this.Nl({isLoaded:!0})}$l(t,e){Q.error(t,e),this.Nl({isLoaded:!1,error:t})}onSurveysLoaded(t){return this.Fl.push(t),this._surveyManager&&this.Nl({isLoaded:!0}),()=>{this.Fl=this.Fl.filter((e=>e!==t))}}getSurveys(t,e){if(e===void 0&&(e=!1),this.Ne.disable_surveys)return Q.info(du),t([]);var n,i=this._instance.get_property(la);if(i&&!e)return t(i,{isLoaded:!0}),void(this.ql()&&this.getSurveys((()=>{}),!0));typeof Promise<"u"&&this.Ll?this.Ll.then((r=>t(r.surveys,r.context))):(typeof Promise<"u"&&(this.Ll=new Promise((r=>{n=r}))),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this.Ne.token),method:"GET",timestampMode:"query",timeout:this.Ne.surveys_request_timeout_ms,callback:r=>{var s;this.Ll=null;var o=r.statusCode;if(o!==200||!r.json){var a="Surveys API could not be loaded, status: "+o;o!==0?Q.error(a):r.error||Q.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(n==null||n({surveys:[],context:l}))}this.Ol=null;var u,c=r.json.surveys||[],d=c.filter((h=>(function(p){return!(!p.start_date||p.end_date)})(h)&&(Hf(h)||(function(p){var g;return!((g=p.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(h))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(s=this._instance.persistence)==null||s.register({[la]:c,[Xr]:Date.now()});var f={isLoaded:!0};t(c,f),n?.({surveys:c,context:f})}}))}ql(){return this.jl()&&!this.Ll&&!this.Bl()}jl(){var t=this._instance.get_property(Xr);return ke(t)&&Date.now()-t>3e5}Bl(){return ke(this.Ol)&&3e5>Date.now()-this.Ol}markSurveyAsSeen(t,e){var n,i={id:t,current_iteration:(n=e?.iteration)!==null&&n!==void 0?n:null};qf(i);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}}Nl(t){for(var e of this.Fl)try{if(!t.isLoaded)return e([],t);this.getSurveys(e)}catch(n){Q.error("Error in survey callback",n)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!H(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);Q.warn("init was not called")}Hl(t){var e=null;return this.getSurveys((n=>{var i;e=(i=n.find((r=>r.id===t)))!==null&&i!==void 0?i:null})),e}Ul(t){if(H(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(H(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(H(this._surveyManager))return Q.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 H(this._surveyManager)?(Q.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Ir})):new Promise((n=>{this.getSurveys((i=>{var r,s=(r=i.find((a=>a.id===t)))!==null&&r!==void 0?r:null;if(s){var o=this.zl(s);n({visible:o.eligible,disabledReason:o.reason})}else n({visible:!1,disabledReason:"Survey not found"})}),e)}))}renderSurvey(t,e,n){var i;if(H(this._surveyManager))Q.warn("init was not called");else{var r=typeof t=="string"?this.Hl(t):t;if(r!=null&&r.id)if(ym.includes(r.type)){var s=F?.querySelector(e);if(s)return(i=r.appearance)!=null&&i.surveyPopupDelaySeconds?(Q.info("Rendering survey "+r.id+" with delay of "+r.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;Q.info("Rendering survey "+r.id+" with delay of "+((o=r.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(a=this._surveyManager)==null||a.renderSurvey(r,s,n),Q.info("Survey "+r.id+" rendered")}),1e3*r.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(r,s,n);Q.warn("Survey element not found")}else Q.warn("Surveys of type "+r.type+" cannot be rendered in the app");else Q.warn("Survey not found")}}displaySurvey(t,e){var n;if(H(this._surveyManager))Q.warn("init was not called");else{var i=this.Hl(t);if(i){var r=i;if((n=i.appearance)!=null&&n.surveyPopupDelaySeconds&&e.ignoreDelay&&(r=k({},i,{appearance:k({},i.appearance,{surveyPopupDelaySeconds:0})})),e.displayType!==_a.Popover&&e.initialResponses&&Q.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),e.ignoreConditions===!1){var s=this.Ul(i);if(!s.eligible)return void Q.warn("Survey is not eligible to be displayed: ",s.reason)}e.displayType!==_a.Inline?this._surveyManager.handlePopoverSurvey(r,e):this.renderSurvey(r,e.selector,e.properties)}else Q.warn("Survey not found")}}cancelPendingSurvey(t){H(this._surveyManager)?Q.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},Cs),Km={toolbar:class{constructor(t){this.instance=t}Wl(t){B.ph_toolbar_state=t}Vl(){var t;return(t=B.ph_toolbar_state)!==null&&t!==void 0?t:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(t,e,n){if(t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),ga(this.instance.config)||!w||!F)return!1;t=t??w.location,n=n??w.history;try{if(!e){try{w.localStorage.setItem("test","test"),w.localStorage.removeItem("test")}catch{return!1}e=w?.localStorage}var i,r=Bm||os(t.hash,"__posthog")||os(t.hash,"state"),s=r?Pc((()=>JSON.parse(atob(decodeURIComponent(r)))))||Pc((()=>JSON.parse(decodeURIComponent(r)))):null;return s&&s.action==="ph_authorize"?((i=s).source="url",i&&Object.keys(i).length>0&&(s.desiredHash?t.hash=s.desiredHash:n?n.replaceState(n.state,"",t.pathname+t.search):t.hash="")):((i=JSON.parse(e.getItem(fu)||"{}")).source="localstorage",delete i.userIntent),!(!i.token||this.instance.config.token!==i.token||(this.loadToolbar(i),0))}catch{return!1}}Zl(t){var e=B.ph_load_toolbar||B.ph_load_editor;!H(e)&&De(e)?e(t,this.instance):hu.warn("No toolbar load function found")}loadToolbar(t){var e=!(F==null||!F.getElementById(sf));if(!w||e)return!1;var n=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,i=k({token:this.instance.config.token},t,{apiURL:this.instance.requestRouter.endpointFor("ui")},n?{instrument:!1}:{});if(w.localStorage.setItem(fu,JSON.stringify(k({},i,{source:void 0}))),this.Vl()===2)this.Zl(i);else if(this.Vl()===0){var r;this.Wl(1),(r=B.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"toolbar",(s=>{if(s)return hu.error("[Toolbar] Failed to load",s),void this.Wl(0);this.Wl(2),this.Zl(i)})),ve(w,"turbolinks:load",(()=>{this.Wl(0),this.loadToolbar(i)}))}return!0}Gl(t){return this.loadToolbar(t)}maybeLoadEditor(t,e,n){return t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),this.maybeLoadToolbar(t,e,n)}}},Ym=k({experiments:Me},Cs),Jm={conversations:class{constructor(t){this.Ql=void 0,this._conversationsManager=null,this.Kl=!1,this.Jl=null,this.Yl=!1,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this._instance.config.disable_conversations&&(this.Xl=t.ok,t.ok)){var e=t.config.conversations;H(e)||(gt(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||ga(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=B?.__PosthogExtensions__;if(t&&!C(this.Ql)&&this.Ql)if(this.Jl&&this.Jl.token){this.Kl=!0;try{var e=t.initConversations;if(e)return this.tu(e),void(this.Kl=!1);var n=t.loadExternalDependency;if(!n)return void this.eu(al);n(this._instance,"conversations",(i=>{i||!t.initConversations?this.eu("Could not load conversations script",i):this.tu(t.initConversations),this.Kl=!1}))}catch(i){this.eu("Error initializing conversations",i),this.Kl=!1}}else st.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,st.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else st.error("Cannot complete initialization: remote config is null")}eu(t,e){st.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():st.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!Ke(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":ga(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.Xl===!1?"remote_config_failed":C(this.Ql)?this.Xl?"disabled_in_project":"remote_config_pending":this.Ql?H(this.Jl)||!this.Jl.token?"missing_token":B!=null&&B.__PosthogExtensions__?this.Kl?"initializing":this.Yl?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.isVisible())!==null&&t!==void 0&&t}sendMessage(t,e,n){var i=this;return se((function*(){return i._conversationsManager?i._conversationsManager.sendMessage(t,e,n):(st.warn(En),null)}))()}getMessages(t,e){var n=this;return se((function*(){return n._conversationsManager?n._conversationsManager.getMessages(t,e):(st.warn(En),null)}))()}markAsRead(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(st.warn(En),null)}))()}getTickets(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(st.warn(En),null)}))()}requestRestoreLink(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(st.warn(En),null)}))()}restoreFromToken(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(st.warn(En),null)}))()}restoreFromUrlToken(){var t=this;return se((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(st.warn(En),null)}))()}getCurrentTicketId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getCurrentTicketId())!==null&&t!==void 0?t:null}getWidgetSessionId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getWidgetSessionId())!==null&&t!==void 0?t:null}Xn(){var t;(t=this._conversationsManager)==null||t.setIdentity()}ts(){var t;(t=this._conversationsManager)==null||t.clearIdentity()}}},Zm={logs:class{constructor(t){var e,n=this;this.iu=!1,this.ru=!1,this.rt=pe("[logs]"),this.nu=k({},this.rt,{error(){for(var i=arguments.length,r=new Array(i),s=0;i>s;s++)r[s]=arguments[s];r.some(bu)||n.rt.error(...r)}}),this.tr=[],this.su=[],this.Sa=0,this.au=()=>{var i,r;this.Sa=0,(i=this.ou)==null||i.onReconnect(),(r=this.lu)==null||r.onReconnect()},this._instance=t,this._instance&&(e=this._instance.config.logs)!=null&&e.captureConsoleLogs&&(this.iu=!0),w&&ve(w,"online",this.au)}uu(t,e,n,i){var r,s=(function(o,a){var l,u,c,d,f,h,p,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,v=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,S=C(v)?Math.max(m,2048):Math.max(m,v),b=o?.resourceAttributes;return{serviceName:(d=(f=b?.["service.name"])!==null&&f!==void 0?f:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(h=b?.["service.version"])!==null&&h!==void 0?h:o?.serviceVersion,environment:(p=b?.["deployment.environment"])!==null&&p!==void 0?p:o?.environment,resourceAttributes:b,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:S,maxBatchRecordsPerPost:100,rateCapWindowMs:g,maxLogsPerInterval:v,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}})((r=this._instance)==null||(r=r.config)==null?void 0:r.logs,n);return[new tg(this.hu(t,e),s,this.nu,(()=>this.du()),(o=>o()),void 0,i),s]}vu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.ou||this.cu!==e){var n;(n=this.ou)==null||n.reset(),this.cu=e;var i=this.uu((()=>this.tr),(r=>{this.tr=r}));this.ou=i[0],this.fu=i[1]}return this.ou}pu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.lu||this.gu!==e){var n;(n=this.lu)==null||n.reset(),this.gu=e;var i=this.uu((()=>this.su),(r=>{this.su=r}),{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},wu);this.lu=i[0],this.mu=i[1]}return this.lu}initialize(){this.loadIfEnabled()}onRemoteConfig(t){var e;if(t.ok){var n=(e=t.config.logs)==null?void 0:e.captureConsoleLogs;!H(n)&&n&&(this.iu=!0,this.loadIfEnabled())}}reset(){var t,e;this.tr=[],(t=this.ou)==null||t.reset(),this.su=[],(e=this.lu)==null||e.reset(),this.Sa=0}captureLog(t){this.vu().captureLog(t)}he(t){this.pu().captureLog(t)}get logger(){return this.yu||(this.yu={trace:(t,e)=>this.captureLog({body:t,level:"trace",attributes:e}),debug:(t,e)=>this.captureLog({body:t,level:"debug",attributes:e}),info:(t,e)=>this.captureLog({body:t,level:"info",attributes:e}),warn:(t,e)=>this.captureLog({body:t,level:"warn",attributes:e}),error:(t,e)=>this.captureLog({body:t,level:"error",attributes:e}),fatal:(t,e)=>this.captureLog({body:t,level:"fatal",attributes:e})}),this.yu}flushLogs(t){t?this.bu(t):(this.ou&&this.ou.flush().catch((e=>this._u(e))),this.lu&&this.lu.flush().catch((e=>this._u(e))))}_u(t){bu(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=B?.__PosthogExtensions__;if(t){var e=t.loadExternalDependency;e?e(this._instance,"logs",(n=>{var i;n||(i=t.logs)==null||!i.initializeLogs?this.rt.error("Could not load logs script",n):(t.logs.initializeLogs(this._instance),this.ru=!0)})):this.rt.error(al)}else this.rt.error("PostHog Extensions not found.")}}hu(t,e){var n=this._instance;return{get isDisabled(){return!1},get optedOut(){return!n.is_capturing()},getPersistedProperty:i=>i===jt.LogsQueue?t():void 0,setPersistedProperty(i,r){var s;i===jt.LogsQueue&&e((s=r)!==null&&s!==void 0?s:[])},Ot:i=>this.Ot(i),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Ot(t){return new Promise((e=>{if(vf(this.Sa,3))e({kind:"fatal",error:Do(void 0,"logs endpoint is unreachable, dropping batch")});else{var n=!1,i=s=>{n||(n=!0,clearTimeout(r),e(s))},r=setTimeout((()=>{this.rt.warn("Logs request timed out before receiving a response"),i({kind:"retry-later",error:Do(void 0,"logs request timed out")})}),9e4);this._instance._send_request({method:"POST",url:this.wu(),data:t,compression:"best-available",batchKey:"logs",fireCallbackOnDrop:!0,callback:s=>{var o=s.statusCode;if(this.ku(o),o>=200&&300>o)i({kind:"ok"});else if(o===413)i({kind:"too-large"});else if(o!==0&&o!==429&&500>o)i({kind:"fatal",error:new Error("logs request failed with status "+o)});else{var a;o===0?(s.error||this.rt.warn("Logs request failed before receiving an HTTP response"),i({kind:"retry-later",error:Do(s.error,"logs request failed before receiving an HTTP response")})):i({kind:"retry-later",error:(a=s.error)!==null&&a!==void 0?a:new Error("logs request failed with status "+o)})}}})}}))}ku(t){(t!==0||this._instance.__loaded)&&(this.Sa=_f(t,this.Sa,3,(()=>this.rt.warn("Log requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped sending logs; will try again when connectivity changes."))))}bu(t){this.tr.length>0&&this.xu(t,this.tr,this.fu,ne.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,wu,(e=>{this.su=e}))}xu(t,e,n,i,r){if(e.length!==0){var s=e.map((a=>a.record));r([]);var o=Ud(s,jd(n,ne.LIB_NAME,ne.LIB_VERSION),i,ne.LIB_VERSION);this._instance._send_request({method:"POST",url:this.wu(),data:o,compression:"best-available",batchKey:"logs",transport:t})}}wu(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}du(){var t,e={};if(e.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var n=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.windowId,r=n.sessionStartTimestamp,s=n.lastActivityTimestamp;e.sessionId=n.sessionId,e.windowId=i,H(r)||(e.sessionStartTimestamp=r),H(s)||(e.lastActivityTimestamp=s)}if(B!=null&&(t=B.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?fn(B.location.href):B.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},Xm={metrics:class{constructor(t){this.rt=pe("[metrics]"),this._instance=t}initialize(){}vu(){var t,e,n=(t=this._instance)==null||(t=t.config)==null?void 0:t.metrics;return this.ou&&this.cu===n||((e=this.ou)==null||e.reset(),this.cu=n,this.ou=new ng(this.hu(),(function(i){var r,s,o,a,l,u=i?.resourceAttributes;return{serviceName:(r=u?.["service.name"])!==null&&r!==void 0?r:i?.serviceName,serviceVersion:(s=u?.["service.version"])!==null&&s!==void 0?s:i?.serviceVersion,environment:(o=u?.["deployment.environment"])!==null&&o!==void 0?o:i?.environment,resourceAttributes:u,beforeSend:i?.beforeSend,flushIntervalMs:(a=i?.flushIntervalMs)!==null&&a!==void 0?a:1e4,maxSeriesPerFlush:(l=i?.maxSeriesPerFlush)!==null&&l!==void 0?l:1e3}})(n),this.rt)),this.ou}count(t,e,n){e===void 0&&(e=1),this.vu().count(t,e,n)}gauge(t,e,n){this.vu().gauge(t,e,n)}histogram(t,e,n){this.vu().histogram(t,e,n)}flush(t){if(!this.ou)return Promise.resolve();if(t){var e=this.ou.drainWindow();return e&&this.Jt(e,t),Promise.resolve()}return this.ou.flush().catch((n=>this.rt.error("PostHog metrics flush failed:",n)))}reset(){var t;(t=this.ou)==null||t.reset()}hu(){var t=this._instance,e=this;return{get isDisabled(){return!1},get optedOut(){return!t.is_capturing()},Jt:n=>e.Jt(n),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Jt(t,e){return new Promise((n=>{var i=!1,r=o=>{i||(i=!0,clearTimeout(s),n(o))},s=setTimeout((()=>r({kind:"retry-later",error:new Error("metrics request timed out")})),9e4);this._instance._send_request(k({method:"POST",url:this.Su(),data:t,compression:"best-available",batchKey:"metrics"},e&&{transport:e},{fireCallbackOnDrop:!0,callback(o){var a=o.statusCode;if(a>=200&&300>a)r({kind:"ok"});else if(a===413)r({kind:"too-large"});else if(a!==0&&a!==429&&500>a)r({kind:"fatal",error:new Error("metrics request failed with status "+a)});else{var l;r({kind:"retry-later",error:(l=o.error)!==null&&l!==void 0?l:new Error("metrics request failed with status "+a)})}}}))}))}Su(){return this._instance.requestRouter.endpointFor("api","/i/v1/metrics")+"?token="+encodeURIComponent(this._instance.config.token)}}},Qm=k({},Cs,Um,Hm,Wm,qm,zm,Gm,Vm,Km,Ym,Jm,Zm,Xm);Je.__defaultExtensionClasses=k({},Qm);(function(){ne.SDK_DIST_CHANNEL="npm";var t=Wi[Gn]=new Je;return(function(){function e(){e.done||(e.done=!0,Vf=!1,ie(Wi,(function(n){n._dom_loaded()})))}F!=null&&F.addEventListener?F.readyState==="complete"?e():ve(F,"DOMContentLoaded",e,{capture:!1}):w&&A.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const ev=["a[href]","button:not([disabled])","input:not([disabled]):not([type='hidden'])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(",");let ht=null,ka=null,Kf="";const Ca=new Map;function Yf(t){return[...t.querySelectorAll(ev)].filter(e=>!e.hidden&&e.getAttribute("aria-hidden")!=="true"&&e.getClientRects().length>0)}function tv(t){for(const e of document.body.children)e===t||e.tagName==="SCRIPT"||(Ca.set(e,{inert:e.inert,ariaHidden:e.getAttribute("aria-hidden")}),e.inert=!0,e.setAttribute("aria-hidden","true"))}function nv(){for(const[t,e]of Ca)t.inert=e.inert,e.ariaHidden===null?t.removeAttribute("aria-hidden"):t.setAttribute("aria-hidden",e.ariaHidden);Ca.clear()}function Jf(t){return t?.dataset.modalDismissible!=="false"&&t?.getAttribute("aria-busy")!=="true"}function He(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n)return!1;ht&&ht!==n&&We(ht,{restoreFocus:!1,force:!0}),ka=e.trigger||document.activeElement,ht=n,Kf=document.body.style.overflow,tv(n),document.body.style.overflow="hidden",n.classList.add("open"),n.setAttribute("aria-hidden","false");const i=n.querySelector(".modal-content");i&&(i.style.transform="scale(1) translateY(0)");const r=()=>{if(ht!==n)return;((e.initialFocus?n.querySelector(e.initialFocus):n.querySelector("[data-modal-initial-focus]"))||Yf(n)[0]||n.querySelector(".modal-content")||n).focus({preventScroll:!0})};return requestAnimationFrame(r),setTimeout(r,260),!0}function We(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n||!e.force&&!Jf(n))return!1;n.classList.remove("open"),n.setAttribute("aria-hidden","true"),nv(),document.body.style.overflow=Kf,ht=null;const i=ka;return ka=null,e.restoreFocus!==!1&&i?.isConnected&&i.focus({preventScroll:!0}),!0}function Eu(t,e,n="Operation in progress"){const i=typeof t=="string"?document.getElementById(t):t;i&&(i.dataset.modalDismissible=e?"false":"true",i.setAttribute("aria-busy",String(!!e)),e?i.setAttribute("aria-label",n):i.removeAttribute("aria-label"))}function iv(t){if(!Jf(t))return;const e=t.dataset.modalCloseHandler;e&&typeof window[e]=="function"?window[e]():We(t)}document.addEventListener("keydown",t=>{if(!ht)return;if(t.key==="Escape"){t.preventDefault(),t.stopImmediatePropagation(),iv(ht);return}if(t.key!=="Tab"){t.stopPropagation();return}const e=Yf(ht);if(!e.length){t.preventDefault(),(ht.querySelector(".modal-content")||ht).focus();return}const n=e[0],i=e[e.length-1];t.shiftKey&&document.activeElement===n?(t.preventDefault(),i.focus()):!t.shiftKey&&document.activeElement===i&&(t.preventDefault(),n.focus())},!0);function rv(){document.querySelectorAll(".modal-overlay").forEach(t=>{t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-hidden",t.classList.contains("open")?"false":"true");const e=t.querySelector(".modal-content");e&&!e.hasAttribute("tabindex")&&(e.tabIndex=-1);const n=t.querySelector("h1, h2, h3");n&&(n.id||(n.id=`${t.id}-title`),t.setAttribute("aria-labelledby",n.id)),t.querySelectorAll(".modal-close").forEach(i=>{i.getAttribute("aria-label")||i.setAttribute("aria-label","Close dialog")})})}const gl=Object.freeze({free:"Free",professional:"Pro",power:"Power"}),sv=Object.freeze({free:2,professional:50,power:2e3}),ov="(contact us)",av=Object.freeze({free:Object.freeze(["2 generations/month","Gemini model only","Code Review"]),professional:Object.freeze(["50 generations/month","All models","Code Regeneration","Code Review"]),power:Object.freeze(["2000 generations/month","All models","Code Regeneration","Bring your own key (BYOK)","Code Review","All models + early access",`API & MCP access ${ov}`])}),Zf="CodeFile",Xf="GeneratedCode",lv={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function ln(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Aa(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function cv(t={},e=0){const n=Aa(t.artifactType||t.type||Zf),i=Aa(t.artifactName||t.name||t.fileName||`${Xf}-${e+1}`);return`${n||"artifact"}-${i||e+1}`}function Qf(t={},e=0){const n=ln(t),i=n.artifactType||n.type||Zf,r=n.artifactName||n.name||Xf;let s=n.fileName||r;return s.endsWith(".dart")||(s+=".dart"),{id:Aa(n.id)||cv({...n,artifactType:i,artifactName:r,fileName:s},e),artifactType:i,artifactName:r,fileName:s,deployPath:n.deployPath||"",description:n.description||"",code:n.code||n.content||"",dependencies:eh(n.dependencies),imports:Array.isArray(n.imports)?n.imports:[],publicApi:Array.isArray(n.publicApi)?n.publicApi:[],relationships:th(n.relationships),deployStatus:n.deployStatus||"pending",review:n.review||null,metadata:ln(n.metadata),codeType:n.codeType||lv[i]||"O"}}function eh(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const n=ln(e),i=n.name||n.package;return i?{name:i,version:n.version||null,versionRequired:!!(n.versionRequired||n.required),inferred:!!n.inferred,...n.reason?{reason:n.reason}:{}}:null}).filter(Boolean):Object.entries(ln(t)).map(([e,n])=>({name:e,version:n||null,inferred:!1})):[]}function th(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const n=ln(e);return!n.from&&!n.to?null:{from:n.from||null,to:n.to||null,type:n.type||"uses",description:n.description||""}}).filter(Boolean):[]}function Pa(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;try{return JSON.parse(e)}catch{const n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(!n)return null;try{return JSON.parse(n[1].trim())}catch{return null}}}function Qi(t,e={}){const n=[],i=typeof t=="string"?Pa(t):t,s=ln(i||{});!i&&typeof t=="string"&&n.push("Structured bundle parse failed; using legacy single-artifact fallback.");const o=Array.isArray(s.artifacts)?s.artifacts:[{artifactType:s.artifactType||e.artifactType,artifactName:s.artifactName||e.artifactName,fileName:s.fileName||e.fileName,description:s.description,code:s.code||e.code||(typeof t=="string"?t:""),dependencies:s.dependencies||e.dependencies,relationships:s.relationships||e.relationships}];o.forEach((d,f)=>{!d?.artifactType&&!d?.type&&n.push(`Artifact ${f+1} has no artifactType; it will deploy as a standalone code file under lib/custom_code/ root.`)});const a=o.map((d,f)=>Qf(d,f)),l=new Map(o.map((d,f)=>[ln(d).id,a[f]?.id]).filter(([d,f])=>d&&f)),u=d=>l.get(d)||d,c=th(s.relationships||e.relationships).map(d=>({...d,from:d.from?u(d.from):d.from,to:d.to?u(d.to):d.to}));return{schemaVersion:s.schemaVersion||e.schemaVersion||null,id:s.id||e.id||"bundle-current",title:s.title||s.name||e.title||"Generated artifact bundle",description:s.description||e.description||"",artifacts:a,dependencies:eh(s.dependencies||e.dependencies),relationships:c,deployOrder:Array.isArray(s.deployOrder)?s.deployOrder.map(u):a.map(d=>d.id),warnings:[...n,...Array.isArray(s.warnings)?s.warnings:[]],metadata:ln(s.metadata)}}function oi(t){return Qi(t).artifacts[0]||Qf()}function Zt(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function ai(t){return JSON.stringify(t,null,2)}function uv(t){return ai({task:"architect",userRequest:String(t??"")})}function dv(t){const e=Zt(t);return e&&typeof e=="object"&&typeof e.task=="string"?ai(e):ai({task:"generate_bundle",bundleSpec:e})}function fv(t){return ai({task:"review_bundle",generatedBundle:Zt(t),outputRequirements:{bundleReview:["status","score","summary","manualActions","findings"],scoreRange:[0,100],eachArtifact:["id","review.status","review.findings"],manualActions:{definition:"Setup the developer must perform by hand in the FlutterFlow editor that FlutterFlow will NOT do for them.",exclude:["creating the Custom Action, Widget or Code File itself - deploying the code creates it","declaring parameters or return values FlutterFlow derives from the function signature","anything that resolves as a side effect of using the action or widget in the editor","generic advice such as testing, reviewing or rebuilding the app"],preferEmpty:"Return an empty array when nothing qualifies - an empty list is the expected result for most bundles."}}})}function ml(t,e=null){const n={stage:t};return e!=null&&(n.bundle=Zt(e)),n}function hv({bundleSpec:t,artifactBundle:e,bundleReview:n,artifactId:i,userFeedback:r}){return ai({task:"regenerate_artifact",artifactId:i,bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(r)})}function nh({bundleSpec:t,artifactBundle:e,bundleReview:n,userFeedback:i}){return ai({task:"regenerate_bundle",bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(i??"")})}const Su={csam:"child-safety content",dangerous:"dangerous content",harassment:"harassment",hate_speech:"hate speech",maliciousUrls:"a potentially malicious URL",malicious_uris:"a potentially malicious URL",pi_and_jailbreak:"prompt-injection or jailbreak instructions",promptInjection:"prompt-injection or jailbreak instructions",rai:"restricted content",sdp:"sensitive personal data",sexually_explicit:"sexually explicit content",virus_scan:"potentially malicious file content"},pv=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function et(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function gv(t){return et(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||et(t.filterSummary)||et(t.filterResults):!1}function ih(t,e=0){if(!et(t)||e>3)return null;if(gv(t))return t;for(const n of pv){const i=t[n];if(et(i)){const r=ih(i,e+1);if(r)return r}}return null}function ds(t){return Array.isArray(t)?t.some(ds):et(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(ds):!1}function Fa(t){return Array.isArray(t)?t.some(Fa):et(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(Fa):!1}function rh(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function mv(t,e){if(et(t))for(const[n,i]of Object.entries(t)){if(!et(i))continue;const r=et(i.categories)?i.categories:{},s=Object.entries(r).filter(([,o])=>et(o)&&o.matched===!0).map(([o])=>o);s.length>0?s.forEach(o=>e.add(o)):i.matched===!0&&e.add(rh(n))}}function vv(t,e){if(!t)return;const n=Array.isArray(t)?t.flatMap(i=>et(i)?Object.entries(i):[]):Object.entries(t);for(const[i,r]of n){if(!ds(r))continue;const s=rh(i),o=r?.raiFilterResult?.raiFilterTypeResults||(s==="rai"?r?.raiFilterTypeResults:null),a=et(o)?Object.entries(o).filter(([,l])=>ds(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(s)}}function _v(t){return Su[t]?Su[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function xu(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 yv(t){const e=ih(t);if(!e)return null;const n=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);mv(e.filterSummary,n),vv(e.filterResults,n);const i=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||n.size>0,r=e.invocationResult||null,s=Fa(e.filterSummary||e.filterResults);return!i&&!s&&!["PARTIAL","FAILURE"].includes(r)?null:{kind:i?"blocked":"unavailable",invocationResult:r,matchedFilters:[...n]}}function wv(t,e){const n=yv(t);if(!n)return null;const i=[...new Set(n.matchedFilters.map(_v))],r=n.kind==="blocked",s=new Error(r?`Safety screening blocked this pipeline step for ${xu(i)}.`:"Safety screening could not be completed. Please try again.");return s.name="ModelArmorError",s.code=r?"MODEL_ARMOR_BLOCKED":"MODEL_ARMOR_UNAVAILABLE",s.isModelArmor=!0,s.pipelineStep=e,s.userTitle=r?"Request blocked for safety":"Safety check unavailable",s.userMessage=r?`The safety check detected ${xu(i)}. Edit your request to remove or rephrase the flagged content, then run the pipeline again.`:"The safety service did not finish all of its checks. Please wait a moment and run the pipeline again.",s.retryExplanation=r?"Trying another model would not change this safety decision.":"A fallback model was not attempted because safety screening must complete first.",s.matchedFilters=n.matchedFilters,s}function bv(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function Iu(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,n=[];for(const i of bv(t).split(` +`)){if(!/^[A-Za-z_$]/.test(i)||e.test(i))continue;const r=i.match(/^[\w$<>,?\s[\]]+?\s([a-zA-Z_$][\w$]*)\s*\(/);r&&n.push(r[1])}return n}function vl(t,e){const n=t.replace(/\.dart$/,"");if(e==="W")return n.replace(/(^|_)(\w)/g,(i,r,s)=>s.toUpperCase());if(e==="A"){const i=n.replace(/(^|_)(\w)/g,(r,s,o)=>o.toUpperCase());return i.charAt(0).toLowerCase()+i.slice(1)}return e==="F"?"CustomFunctions":e==="C"?t.endsWith(".dart")?t:`${t}.dart`:n}async function ku(t){const e=new TextEncoder().encode(String(t||"")),n=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n),i=>i.toString(16).padStart(2,"0")).join("")}async function Ev(t,e=new Map){const n={},i=new Set;for(const[o,a]of t.entries()){if(a.type==="D"||a.type==="O")continue;const l=vl(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await ku(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await ku(c)),n[o]=u,a.type==="F"){const d=Iu(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(h=>i.add(h))}}const r=new Set(Iu(e.get("lib/flutter_flow/custom_functions.dart")||"")),s={functions_to_rename:[],functions_to_delete:[],functions_to_add:Array.from(i).filter(o=>!r.has(o))};return{fileMapContents:JSON.stringify(n),functionsMapContents:JSON.stringify(s)}}const Sv=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),Cu={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},xv=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),Iv=["Struct","Record"],kv=[{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=>jo(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=>jo(t).some(e=>{const n=/^\s*final\s+(?:double|int|String|bool|Color|num)\s+(\w+)\s*;/gm;let i;for(;(i=n.exec(e))!==null;){const r=i[1];if(!(new RegExp(`this\\.${r}\\s*=(?!=)`).test(e)||new RegExp(`[:,]\\s*${r}\\s*=(?!=)`).test(e)))return!0}return!1}),pos:`class W extends StatefulWidget { const W({required this.value}); final double value; }`,neg:`class _P { @@ -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=>Uo(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=>jo(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,47 +25,47 @@ 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 St(t,e,n){return{artifactId:t.id,artifactName:t.artifactName,artifactType:t.artifactType,severity:e,message:n}}function er(t){let e="",n=0;for(;n"&&(n--,n===0))return{inner:t.slice(e+1,i),end:i+1};return null}function Fv(t,e){const n=new RegExp(`class\\s+${e}\\b[^{]*\\{`).exec(t);if(!n)return null;let i=0;for(let r=n.index+n[0].length-1;rRv(t).usable);function $v(t=""){const e=er(t);return Tv.filter(n=>n.detect(e)).map(({id:n,severity:i,message:r})=>({id:n,severity:i,message:r}))}function Mv(t){const e=[],n=t.matchAll(/\bFuture\b/g);for(const i of n){let r=i.index+6,s=null;const o=r;for(;ro;if(t[r]==="<"){const u=Pv(t,r);if(!u||(s=u.inner.replace(/\s+/g," ").trim(),r=u.end,!/\s/.test(t[r]||"")))continue;for(;rAu(o.functionName)===i);if(r)return r;const s=o=>!o.functionName.startsWith("_");return n.find(s)||n[0]}function As(t=""){return Array.from(er(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function Lv(t="",e=""){return yl(t,e)?.returnType||null}function Pu(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 Nv(t,e){const n=As(e);if(n.length===0)return null;const r=String(t||"").split("/").pop().replace(/\.dart$/,"");if(n.some(l=>Pu(l)===r)||n.length>1)return null;const[o]=n,a=`${Pu(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 wl(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function Ov(t,e,n=""){const i=yl(e,n)?.functionName;if(!i)return null;const r=String(t||"").split("/").pop(),s=_l(r,"A");if(s===i)return null;const o=`${wl(i)}.dart`;return`File name "${r}" does not match Action "${i}". FlutterFlow derives the action from the file name, so it looks for "${s}" and reports Action "${s}" declaration not found. Rename the file to "${o}" - FlutterFlow puts an underscore before every capital - or rename the function to "${s}".`}function Bv(t="",e=""){return yl(t,e)!==null}function Dv(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(i=>kv.has(i)?!1:!Cv.some(s=>i.endsWith(s))||e.has(i))}function jv(t,{functionName:e="",declaredTypes:n=new Set}={}){const i=Lv(t,e),r=Dv(i,n);if(r.length===0)return null;const[s]=r;let o;return n.has(s)?o=`uses Code File type "${s}", which FlutterFlow cannot process as an Action Return Value`:i===s?o="is not a FlutterFlow Action Return Value":o=`uses type "${s}", which is not a FlutterFlow Action Return Value`,`CustomAction return type "${i}" ${o}. Return JSON (Future) or an existing FlutterFlow Data Type (*Struct) instead.`}function Uv(t,e={}){const n=[],i=t.fileName||"",r=t.code||"";if(Iv.has(t.artifactType)||n.push(St(t,"error",`Unsupported artifact type "${t.artifactType}".`)),i.endsWith(".dart")||n.push(St(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!r.trim())return n.push(St(t,"warning","Generated artifact has no Dart code yet.")),n;if(t.artifactType==="CustomWidget"){/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)||n.push(St(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const s of $v(r))n.push(St(t,s.severity,s.message))}if(t.artifactType==="CustomAction"&&!Bv(r,t.artifactName)&&n.push(St(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const s=e.declaredTypes||new Set(As(r)),o=jv(r,{functionName:t.artifactName,declaredTypes:s});o&&n.push(St(t,"error",o));const a=Ov(i,r,t.artifactName);a&&n.push(St(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)&&n.push(St(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const s=Nv(i,r);s&&n.push(St(t,"info",s))}return n}function Hv(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],n=new Set(e.flatMap(s=>As(s.code||""))),i=e.flatMap(s=>Uv(s,{declaredTypes:n})),r=e.map(s=>({artifactId:s.id,fileName:s.fileName,pathHint:Cu[s.artifactType]||Cu.CodeFile}));return{valid:i.every(s=>s.severity!=="error"),findings:i,deployHints:r}}const Fu="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function Ru(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function Wv(t=""){const e=t.indexOf(Fu);return e===-1?t:t.slice(e+Fu.length).replace(/^\s*\n/,"")}const qv=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function zv(t="",e=""){const n=Wv(t),i=new Set((e.match(/^\s*import .*$/gm)||[]).map(Ru).filter(Boolean)),r=n.split(` -`).filter(s=>{const o=Ru(s);return o===null||!i.has(o)?!0:!qv.test(s)}).join(` -`).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+r}const Gv=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations"]);function oh(t){let e="",n=0;for(;n{const i=n.name||n.package;if(!i||i==="flutter")return e;const r=n.versionRequired||n.required;return e[i]=r&&n.version||"",e},{})}function Zv(t){const e=new Map,n=new Map,i=[];for(const r of t)e.has(r.fileName)?i.push(`Duplicate deploy file name "${r.fileName}" for artifacts "${e.get(r.fileName)}" and "${r.artifactId}".`):e.set(r.fileName,r.artifactId),n.has(r.path)?i.push(`Duplicate deploy path "${r.path}" for artifacts "${n.get(r.path)}" and "${r.artifactId}".`):n.set(r.path,r.artifactId);return i}function Xv(t,e={}){const n=Array.isArray(t?.artifacts)?t.artifacts:[],r=(e.selectedArtifactIds||t?.deployOrder||n.map(h=>h.id)).map(h=>n.find(p=>p.id===h)).filter(Boolean),s=[...t?.warnings||[]];let o=[];r.forEach(h=>{const p=Jv(h),g=h.fixedCode||h.code||"",m=h.codeType||Kv[h.artifactType]||Ze.OTHER;g.trim()||s.push(`${h.artifactName||h.id} has no generated code.`),o.push({artifactId:h.id,artifactName:h.artifactName,artifactType:h.artifactType,fileName:p,content:g,type:m,path:h.deployPath||Yv(p,m),deployPath:h.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((h,p)=>({entry:h,index:p})).filter(({entry:h})=>h.type===Ze.FUNCTION&&h.path===a);if(l.length>1){const h=l[0],p={...h.entry,artifactId:l.map(({entry:m})=>m.artifactId).join("+"),artifactName:h.entry.artifactName,content:l.map(({entry:m})=>`// ${m.artifactId} +`;)n++;e+=" "}else if(i==="/*"){for(n+=2;n"&&(n--,n===0))return{inner:t.slice(e+1,i),end:i+1};return null}function Av(t,e){const n=new RegExp(`class\\s+${e}\\b[^{]*\\{`).exec(t);if(!n)return null;let i=0;for(let r=n.index+n[0].length-1;rPv(t).usable);function Rv(t=""){const e=er(t);return Fv.filter(n=>n.detect(e)).map(({id:n,severity:i,message:r})=>({id:n,severity:i,message:r}))}function Tv(t){const e=[],n=t.matchAll(/\bFuture\b/g);for(const i of n){let r=i.index+6,s=null;const o=r;for(;ro;if(t[r]==="<"){const u=Cv(t,r);if(!u||(s=u.inner.replace(/\s+/g," ").trim(),r=u.end,!/\s/.test(t[r]||"")))continue;for(;rAu(o.functionName)===i);if(r)return r;const s=o=>!o.functionName.startsWith("_");return n.find(s)||n[0]}function As(t=""){return Array.from(er(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function $v(t="",e=""){return _l(t,e)?.returnType||null}function Pu(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 Mv(t,e){const n=As(e);if(n.length===0)return null;const r=String(t||"").split("/").pop().replace(/\.dart$/,"");if(n.some(l=>Pu(l)===r)||n.length>1)return null;const[o]=n,a=`${Pu(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 yl(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function Lv(t,e,n=""){const i=_l(e,n)?.functionName;if(!i)return null;const r=String(t||"").split("/").pop(),s=vl(r,"A");if(s===i)return null;const o=`${yl(i)}.dart`;return`File name "${r}" does not match Action "${i}". FlutterFlow derives the action from the file name, so it looks for "${s}" and reports Action "${s}" declaration not found. Rename the file to "${o}" - FlutterFlow puts an underscore before every capital - or rename the function to "${s}".`}function Nv(t="",e=""){return _l(t,e)!==null}function Ov(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(i=>xv.has(i)?!1:!Iv.some(s=>i.endsWith(s))||e.has(i))}function Bv(t,{functionName:e="",declaredTypes:n=new Set}={}){const i=$v(t,e),r=Ov(i,n);if(r.length===0)return null;const[s]=r;let o;return n.has(s)?o=`uses Code File type "${s}", which FlutterFlow cannot process as an Action Return Value`:i===s?o="is not a FlutterFlow Action Return Value":o=`uses type "${s}", which is not a FlutterFlow Action Return Value`,`CustomAction return type "${i}" ${o}. Return JSON (Future) or an existing FlutterFlow Data Type (*Struct) instead.`}function Dv(t,e={}){const n=[],i=t.fileName||"",r=t.code||"";if(Sv.has(t.artifactType)||n.push(St(t,"error",`Unsupported artifact type "${t.artifactType}".`)),i.endsWith(".dart")||n.push(St(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!r.trim())return n.push(St(t,"warning","Generated artifact has no Dart code yet.")),n;if(t.artifactType==="CustomWidget"){/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)||n.push(St(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const s of Rv(r))n.push(St(t,s.severity,s.message))}if(t.artifactType==="CustomAction"&&!Nv(r,t.artifactName)&&n.push(St(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const s=e.declaredTypes||new Set(As(r)),o=Bv(r,{functionName:t.artifactName,declaredTypes:s});o&&n.push(St(t,"error",o));const a=Lv(i,r,t.artifactName);a&&n.push(St(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)&&n.push(St(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const s=Mv(i,r);s&&n.push(St(t,"info",s))}return n}function jv(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],n=new Set(e.flatMap(s=>As(s.code||""))),i=e.flatMap(s=>Dv(s,{declaredTypes:n})),r=e.map(s=>({artifactId:s.id,fileName:s.fileName,pathHint:Cu[s.artifactType]||Cu.CodeFile}));return{valid:i.every(s=>s.severity!=="error"),findings:i,deployHints:r}}const Fu="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function Ru(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function Uv(t=""){const e=t.indexOf(Fu);return e===-1?t:t.slice(e+Fu.length).replace(/^\s*\n/,"")}const Hv=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function Wv(t="",e=""){const n=Uv(t),i=new Set((e.match(/^\s*import .*$/gm)||[]).map(Ru).filter(Boolean)),r=n.split(` +`).filter(s=>{const o=Ru(s);return o===null||!i.has(o)?!0:!Hv.test(s)}).join(` +`).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+r}const qv=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations"]);function sh(t){let e="",n=0;for(;n{const i=n.name||n.package;if(!i||i==="flutter")return e;const r=n.versionRequired||n.required;return e[i]=r&&n.version||"",e},{})}function Yv(t){const e=new Map,n=new Map,i=[];for(const r of t)e.has(r.fileName)?i.push(`Duplicate deploy file name "${r.fileName}" for artifacts "${e.get(r.fileName)}" and "${r.artifactId}".`):e.set(r.fileName,r.artifactId),n.has(r.path)?i.push(`Duplicate deploy path "${r.path}" for artifacts "${n.get(r.path)}" and "${r.artifactId}".`):n.set(r.path,r.artifactId);return i}function Jv(t,e={}){const n=Array.isArray(t?.artifacts)?t.artifacts:[],r=(e.selectedArtifactIds||t?.deployOrder||n.map(h=>h.id)).map(h=>n.find(p=>p.id===h)).filter(Boolean),s=[...t?.warnings||[]];let o=[];r.forEach(h=>{const p=Kv(h),g=h.fixedCode||h.code||"",m=h.codeType||Vv[h.artifactType]||Ze.OTHER;g.trim()||s.push(`${h.artifactName||h.id} has no generated code.`),o.push({artifactId:h.id,artifactName:h.artifactName,artifactType:h.artifactType,fileName:p,content:g,type:m,path:h.deployPath||Gv(p,m),deployPath:h.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((h,p)=>({entry:h,index:p})).filter(({entry:h})=>h.type===Ze.FUNCTION&&h.path===a);if(l.length>1){const h=l[0],p={...h.entry,artifactId:l.map(({entry:m})=>m.artifactId).join("+"),artifactName:h.entry.artifactName,content:l.map(({entry:m})=>`// ${m.artifactId} ${m.content}`).join(` -`)},g=new Set(l.slice(1).map(({index:m})=>m));o=o.filter((m,v)=>!g.has(v)),o[h.index]=p}const u={...Tu(t?.dependencies),...r.reduce((h,p)=>({...h,...Tu(p.dependencies)}),{})},c={};r.forEach(h=>{bl(h.code||"").forEach(p=>{p in u||(c[p]="")})});const d={...c,...u},f=Zv(o);return{bundleId:t?.id||"bundle-current",title:t?.title||"Generated artifact bundle",fileEntries:o,dependencies:d,relationships:t?.relationships||[],warnings:s,errors:f}}function Qv(t){return String(t||"").match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/)?.[1]}function e_(t){return String(t||"").split("/").pop().replace(/\.dart$/,"").split(/[^A-Za-z0-9]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function t_(t,e){const i=[e_(t),Qv(e.content),e.artifactName].find(r=>/^[A-Z][A-Za-z0-9_]*$/.test(String(r||"")));if(!i)throw new Error(`Cannot derive a FlutterFlow custom class name for ${t}.`);return i}function n_(t,e=new Map){const n=[];for(const[i,r]of t.entries())r.type!=="C"||e.has(r.path)||n.push({artifactId:r.artifactId||i,className:t_(i,r),content:r.content,fileName:i,path:r.path});return n}function i_(t,e){const n=new Set(e.map(i=>i.path));return new Map(Array.from(t.entries()).filter(([,i])=>!n.has(i.path)))}const $u={pass:0,warning:1,fail:2},r_=["manualActions"];function rt(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function zt(...t){for(const e of t){if(typeof e=="string"&&e.trim())return e.trim();if(Array.isArray(e)&&e.length>0){const n=e.filter(i=>typeof i=="string").join(` -`);if(n)return n}}return""}function It(t){return t==null?[]:Array.isArray(t)?t:[t]}function s_(t){const e=rt(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const n=Number(e);if(Number.isFinite(n))return Mu(n);const i=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return i?Mu(Number(i[1])):null}function Mu(t){return t>=0&&t<=100?t:null}function at(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function El(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 Ta(...t){return t.filter(Boolean).reduce((e,n)=>$u[n]>$u[e]?n:e,"pass")}function ah(t,e="warning",n="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:n};const i=rt(t),r=zt(i.message,i.title,i.issue,i.description,i.summary);return r?{severity:El(i.severity||i.status||i.level)||e,message:r,suggestion:zt(i.suggestion,i.fix,i.recommendation,i.action),source:i.source||n}:null}function $a(t,e="review"){const n=rt(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([r,s])=>It(n[r]).map(o=>ah(o,s,e)).filter(Boolean))}function o_(t,e,n=null){if(typeof t=="string")return{id:`${n||"bundle"}-manual-${e+1}`,title:t,detail:"",location:"",timing:"unspecified",artifactId:n,source:"Code Review"};const i=rt(t),r=zt(i.title,i.action,i.step,i.message,i.name,i.description);return r?{id:i.id||`${n||"bundle"}-manual-${e+1}`,title:r,detail:zt(i.detail,i.instructions,i.description),location:zt(i.location,i.flutterFlowPath,i.path),timing:zt(i.timing,i.phase)||"unspecified",artifactId:n,source:zt(i.source)||"Code Review"}:null}function Ma(t,e=null){const n=rt(t);return r_.flatMap(i=>It(n[i])).map((i,r)=>o_(i,r,e)).filter(Boolean)}function a_(t){let e=typeof t=="string"?Fa(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const n=rt(e);typeof n.content=="string"&&(e=Fa(n.content)||e);const i=rt(e),r=rt(i.reviewResult||i.codeReview||i.result);return{rawText:"",root:Object.keys(r).length?r:i}}function l_(t,e){const n=[e.id,e.fileName,e.artifactName].map(at);return t.find(i=>{const r=rt(i);return[r.id,r.fileName,r.artifactName,r.name].map(at).some(s=>s&&n.includes(s))})||null}function c_(t,e){return It(t?.metadata?.compatibility?.deployHints).find(r=>at(r?.artifactId)===at(e.id)||at(r?.fileName)===at(e.fileName))?.pathHint||""}function u_(t,e){return It(t?.relationships).filter(n=>at(n?.from)===at(e.id)||at(n?.to)===at(e.id))}function d_(t,e){return It(t?.metadata?.compatibility?.findings).filter(n=>!n?.artifactId||at(n.artifactId)===at(e.id)).map(n=>ah(n,"warning","Compatibility check")).filter(Boolean)}function f_(t,e,n,i){const r=l_(e,n),s=rt(r?.review||r||n.review),o=Object.keys(s).length>0,a=[...$a(s),...d_(t,n)],l=Ma(s,n.id),u=El(s.status||s.verdict||s.outcome||s.result),c=a.length?Ta(...a.map(f=>f.severity)):null,d=Ta(u,c,o?null:"warning");return{...n,index:i,status:d,statusReason:o?zt(s.summary,s.overview,s.assessment,s.conclusion)||(a.length?`${a.length} review finding${a.length===1?"":"s"}`:"No file-level findings"):"No file-level verdict was returned",reviewComplete:o,findings:a,manualSteps:l,fixedSource:typeof s.fixedSource=="string"&&s.fixedSource.trim()?s.fixedSource.trim():null,pathHint:c_(t,n),relationships:u_(t,n)}}function h_({status:t,score:e,artifactPresentations:n,manualSteps:i}){const r=n.length;if(r===0&&i.length===0)return e==null?"Code review returned no overall summary and no score.":`Reviewed bundle with score ${e}/100.`;const s=n.reduce((a,l)=>(a[l.status]+=1,a),{pass:0,warning:0,fail:0}),o=[];return t&&o.push(`Overall verdict: ${t}.`),r&&o.push(`${r} artifact${r===1?"":"s"}: ${s.pass} pass, ${s.warning} warn, ${s.fail} fail.`),i.length&&o.push(`Do before deploy: ${i.map(a=>a.title).join("; ")}.`),e==null&&o.push("No numeric score (0-100) was returned."),o.join(" ")}function p_({bundle:t,reviewResult:e}){const n=rt(t),i=It(n.artifacts),{root:r,rawText:s}=a_(e),o=[r.bundleReview,r.overallReview,r.overall,r.bundleSummary,r.summaryReview,r.review].map(rt).find(b=>Object.keys(b).length)||{},a=It(r.artifacts||r.files||r.reviews),l=i.map((b,_)=>f_(n,a,b,_)),u=$a(r),d=[...$a(o),...u],f=[...Ma(o),...Ma(r),...l.flatMap(b=>b.manualSteps)].filter((b,_,x)=>x.findIndex(I=>I.title===b.title&&I.artifactId===b.artifactId)===_),h=El(o.status||o.verdict||o.overallStatus||r.status||r.verdict||r.overallStatus||r.outcome),p=Ta(h,...d.map(b=>b.severity),...l.map(b=>b.status)),g=o.score??r.score??r.overallScore??s,m=s_(g),v=zt(o.headline,o.summary,o.executiveSummary,o.overview,o.assessment,o.conclusion,r.overallSummary,r.headline,r.summary,r.executiveSummary,r.overview,r.assessment,r.conclusion,s)||h_({status:p,score:m,artifactPresentations:l,manualSteps:f}),S=l.reduce((b,_)=>(b[_.status]+=1,b),{pass:0,warning:0,fail:0});return{title:n.title||"Generated artifact bundle",description:n.description||"",status:p,score:m,summary:v,findings:d,manualSteps:f,artifacts:l,counts:S,reviewCoverage:{reviewed:l.filter(b=>b.reviewComplete).length,total:l.length},deployOrder:It(n.deployOrder),relationships:It(n.relationships),warnings:It(n.warnings),compatibility:rt(n.metadata?.compatibility)}}const g_=/^\uFEFF/;function Ci(t){let e=0,n=t.length;for(;ee&&!t[n-1].trim();)n--;return t.slice(e,n).join(` -`)}function m_(t){const e=String(t??"").replace(g_,"");if(!e.trim())return"";const n=e.split(` -`),i=c=>{const d=c.trim();return/^`{3,}[A-Za-z0-9+#_.-]*$/.test(d)?c.length-c.trimStart().length:-1};let r=0,s=-1;const o=[];{let c=0;for(let d=0;d=0&&(r++,s<0&&(s=d),o.push(c+f)),c+=n[d].length+1}}if(r===0)return Ci(n);{const c=La(e);if(!c.error&&o.every(f=>Nu(f,c.commentAndStringRanges)))return Ci(n)}if(r===1){const c=Ci(n.slice(0,s)),d=Ci(n.slice(s+1));return d.length>=c.length?d:c}const a=[];let l=null;for(let c=0;cm));o=o.filter((m,v)=>!g.has(v)),o[h.index]=p}const u={...Tu(t?.dependencies),...r.reduce((h,p)=>({...h,...Tu(p.dependencies)}),{})},c={};r.forEach(h=>{wl(h.code||"").forEach(p=>{p in u||(c[p]="")})});const d={...c,...u},f=Yv(o);return{bundleId:t?.id||"bundle-current",title:t?.title||"Generated artifact bundle",fileEntries:o,dependencies:d,relationships:t?.relationships||[],warnings:s,errors:f}}function Zv(t){return String(t||"").match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/)?.[1]}function Xv(t){return String(t||"").split("/").pop().replace(/\.dart$/,"").split(/[^A-Za-z0-9]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function Qv(t,e){const i=[Xv(t),Zv(e.content),e.artifactName].find(r=>/^[A-Z][A-Za-z0-9_]*$/.test(String(r||"")));if(!i)throw new Error(`Cannot derive a FlutterFlow custom class name for ${t}.`);return i}function e_(t,e=new Map){const n=[];for(const[i,r]of t.entries())r.type!=="C"||e.has(r.path)||n.push({artifactId:r.artifactId||i,className:Qv(i,r),content:r.content,fileName:i,path:r.path});return n}function t_(t,e){const n=new Set(e.map(i=>i.path));return new Map(Array.from(t.entries()).filter(([,i])=>!n.has(i.path)))}const $u={pass:0,warning:1,fail:2},n_=["manualActions"];function rt(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function zt(...t){for(const e of t){if(typeof e=="string"&&e.trim())return e.trim();if(Array.isArray(e)&&e.length>0){const n=e.filter(i=>typeof i=="string").join(` +`);if(n)return n}}return""}function It(t){return t==null?[]:Array.isArray(t)?t:[t]}function i_(t){const e=rt(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const n=Number(e);if(Number.isFinite(n))return Mu(n);const i=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return i?Mu(Number(i[1])):null}function Mu(t){return t>=0&&t<=100?t:null}function at(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function bl(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 Ra(...t){return t.filter(Boolean).reduce((e,n)=>$u[n]>$u[e]?n:e,"pass")}function oh(t,e="warning",n="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:n};const i=rt(t),r=zt(i.message,i.title,i.issue,i.description,i.summary);return r?{severity:bl(i.severity||i.status||i.level)||e,message:r,suggestion:zt(i.suggestion,i.fix,i.recommendation,i.action),source:i.source||n}:null}function Ta(t,e="review"){const n=rt(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([r,s])=>It(n[r]).map(o=>oh(o,s,e)).filter(Boolean))}function r_(t,e,n=null){if(typeof t=="string")return{id:`${n||"bundle"}-manual-${e+1}`,title:t,detail:"",location:"",timing:"unspecified",artifactId:n,source:"Code Review"};const i=rt(t),r=zt(i.title,i.action,i.step,i.message,i.name,i.description);return r?{id:i.id||`${n||"bundle"}-manual-${e+1}`,title:r,detail:zt(i.detail,i.instructions,i.description),location:zt(i.location,i.flutterFlowPath,i.path),timing:zt(i.timing,i.phase)||"unspecified",artifactId:n,source:zt(i.source)||"Code Review"}:null}function $a(t,e=null){const n=rt(t);return n_.flatMap(i=>It(n[i])).map((i,r)=>r_(i,r,e)).filter(Boolean)}function s_(t){let e=typeof t=="string"?Pa(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const n=rt(e);typeof n.content=="string"&&(e=Pa(n.content)||e);const i=rt(e),r=rt(i.reviewResult||i.codeReview||i.result);return{rawText:"",root:Object.keys(r).length?r:i}}function o_(t,e){const n=[e.id,e.fileName,e.artifactName].map(at);return t.find(i=>{const r=rt(i);return[r.id,r.fileName,r.artifactName,r.name].map(at).some(s=>s&&n.includes(s))})||null}function a_(t,e){return It(t?.metadata?.compatibility?.deployHints).find(r=>at(r?.artifactId)===at(e.id)||at(r?.fileName)===at(e.fileName))?.pathHint||""}function l_(t,e){return It(t?.relationships).filter(n=>at(n?.from)===at(e.id)||at(n?.to)===at(e.id))}function c_(t,e){return It(t?.metadata?.compatibility?.findings).filter(n=>!n?.artifactId||at(n.artifactId)===at(e.id)).map(n=>oh(n,"warning","Compatibility check")).filter(Boolean)}function u_(t,e,n,i){const r=o_(e,n),s=rt(r?.review||r||n.review),o=Object.keys(s).length>0,a=[...Ta(s),...c_(t,n)],l=$a(s,n.id),u=bl(s.status||s.verdict||s.outcome||s.result),c=a.length?Ra(...a.map(f=>f.severity)):null,d=Ra(u,c,o?null:"warning");return{...n,index:i,status:d,statusReason:o?zt(s.summary,s.overview,s.assessment,s.conclusion)||(a.length?`${a.length} review finding${a.length===1?"":"s"}`:"No file-level findings"):"No file-level verdict was returned",reviewComplete:o,findings:a,manualSteps:l,fixedSource:typeof s.fixedSource=="string"&&s.fixedSource.trim()?s.fixedSource.trim():null,pathHint:a_(t,n),relationships:l_(t,n)}}function d_({status:t,score:e,artifactPresentations:n,manualSteps:i}){const r=n.length;if(r===0&&i.length===0)return e==null?"Code review returned no overall summary and no score.":`Reviewed bundle with score ${e}/100.`;const s=n.reduce((a,l)=>(a[l.status]+=1,a),{pass:0,warning:0,fail:0}),o=[];return t&&o.push(`Overall verdict: ${t}.`),r&&o.push(`${r} artifact${r===1?"":"s"}: ${s.pass} pass, ${s.warning} warn, ${s.fail} fail.`),i.length&&o.push(`Do before deploy: ${i.map(a=>a.title).join("; ")}.`),e==null&&o.push("No numeric score (0-100) was returned."),o.join(" ")}function f_({bundle:t,reviewResult:e}){const n=rt(t),i=It(n.artifacts),{root:r,rawText:s}=s_(e),o=[r.bundleReview,r.overallReview,r.overall,r.bundleSummary,r.summaryReview,r.review].map(rt).find(b=>Object.keys(b).length)||{},a=It(r.artifacts||r.files||r.reviews),l=i.map((b,_)=>u_(n,a,b,_)),u=Ta(r),d=[...Ta(o),...u],f=[...$a(o),...$a(r),...l.flatMap(b=>b.manualSteps)].filter((b,_,x)=>x.findIndex(I=>I.title===b.title&&I.artifactId===b.artifactId)===_),h=bl(o.status||o.verdict||o.overallStatus||r.status||r.verdict||r.overallStatus||r.outcome),p=Ra(h,...d.map(b=>b.severity),...l.map(b=>b.status)),g=o.score??r.score??r.overallScore??s,m=i_(g),v=zt(o.headline,o.summary,o.executiveSummary,o.overview,o.assessment,o.conclusion,r.overallSummary,r.headline,r.summary,r.executiveSummary,r.overview,r.assessment,r.conclusion,s)||d_({status:p,score:m,artifactPresentations:l,manualSteps:f}),S=l.reduce((b,_)=>(b[_.status]+=1,b),{pass:0,warning:0,fail:0});return{title:n.title||"Generated artifact bundle",description:n.description||"",status:p,score:m,summary:v,findings:d,manualSteps:f,artifacts:l,counts:S,reviewCoverage:{reviewed:l.filter(b=>b.reviewComplete).length,total:l.length},deployOrder:It(n.deployOrder),relationships:It(n.relationships),warnings:It(n.warnings),compatibility:rt(n.metadata?.compatibility)}}const h_=/^\uFEFF/;function Ci(t){let e=0,n=t.length;for(;ee&&!t[n-1].trim();)n--;return t.slice(e,n).join(` +`)}function p_(t){const e=String(t??"").replace(h_,"");if(!e.trim())return"";const n=e.split(` +`),i=c=>{const d=c.trim();return/^`{3,}[A-Za-z0-9+#_.-]*$/.test(d)?c.length-c.trimStart().length:-1};let r=0,s=-1;const o=[];{let c=0;for(let d=0;d=0&&(r++,s<0&&(s=d),o.push(c+f)),c+=n[d].length+1}}if(r===0)return Ci(n);{const c=Ma(e);if(!c.error&&o.every(f=>Nu(f,c.commentAndStringRanges)))return Ci(n)}if(r===1){const c=Ci(n.slice(0,s)),d=Ci(n.slice(s+1));return d.length>=c.length?d:c}const a=[];let l=null;for(let c=0;cc.length>0);return u.length===0?"":u.join(` +${d}`,{commentAndStringRanges:g}=Ma(p),m=h.length+1+f;if(Nu(m,g)){l.push(d);continue}a.push(Ci(l)),l=null}const u=a.filter(c=>c.length>0);return u.length===0?"":u.join(` -`)}function v_(t){return String(t??"").replace(/\/\*[\s\S]*?\*\//g," ").replace(/\/\/[^\n]*/g,"").replace(/'''[\s\S]*?'''/g,'""').replace(/"""[\s\S]*?"""/g,'""').replace(/'(?:\\.|[^'\\\n])*'/g,'""').replace(/"(?:\\.|[^"\\\n])*"/g,'""')}function lh(t){const e=v_(t);return Array.from(e.matchAll(/class\s+([A-Z]\w*)\s+extends\s+[A-Za-z_]\w*Widget\b/g),n=>n[1])}function ch(t){return`${wl(t)}.dart`}function __(t){return _l(t,"W")}const Lu={"(":")","[":"]","{":"}"},y_={")":"(","]":"[","}":"{"},w_=/[A-Za-z0-9_]/;function La(t){const e=[{kind:"code",opener:null,openedLine:0}],n=[];let i=1,r=0;const s=(c,d)=>{(c===` +`)}function g_(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 ah(t){const e=g_(t);return Array.from(e.matchAll(/class\s+([A-Z]\w*)\s+extends\s+[A-Za-z_]\w*Widget\b/g),n=>n[1])}function lh(t){return`${yl(t)}.dart`}function m_(t){return vl(t,"W")}const Lu={"(":")","[":"]","{":"}"},v_={")":"(","]":"[","}":"{"},__=/[A-Za-z0-9_]/;function Ma(t){const e=[{kind:"code",opener:null,openedLine:0}],n=[];let i=1,r=0;const s=(c,d)=>{(c===` `||c==="\r"&&d!==` `)&&i++};let o=null;const a=()=>{for(const c of e)(c.kind==="string"||c.kind==="block-comment"||c.kind==="line-comment")&&n.push({start:c.startIndex,end:t.length})};for(;r0?t[r-1]:"",p=r>1?t[r-2]:"",g=(h==="r"||h==="R")&&!w_.test(p);e.push({kind:"string",quote:c,triple:f,raw:g,startIndex:r,openedLine:i}),r+=f?3:1;continue}if(Lu[c]){e.push({kind:"code",opener:c,openedLine:i}),r++;continue}if(y_[c]){if(d.interpolation&&c==="}"){e.pop(),r++;continue}if(d.opener&&Lu[d.opener]===c){e.pop(),r++;continue}return d.opener?(a(),{error:o??`line ${i}: "${c}" closes nothing - "${d.opener}" opened on line ${d.openedLine} is still open`,commentAndStringRanges:n}):(a(),{error:o??`line ${i}: unexpected "${c}" with no matching opener`,commentAndStringRanges:n})}s(c,t[r+1]),r++}a();let l=e.length-1;for(;l>0&&e[l].kind==="line-comment";)l--;let u=o;if(!u){const c=e[l];if(!(c.kind==="code"&&!c.opener&&!c.interpolation))if(c.kind==="string")u=`unclosed ${c.triple?"triple-quoted ":""}string starting on line ${c.openedLine} was never closed`;else if(c.kind==="block-comment")u=`unterminated /* comment starting on line ${c.openedLine}`;else if(c.interpolation){const d=e.findLast(h=>h.opener);u=`unclosed "\${" expression${d?` opened on line ${d.openedLine}`:""} was never closed`}else u=`"${c.opener}" opened on line ${c.openedLine} is never closed`}return{error:u,commentAndStringRanges:n}}function b_(t){return La(String(t??"")).error}function Nu(t,e){return e.some(({start:n,end:i})=>t>=n&&ttypeof n=="string"?n:n?.errorMessage).filter(Boolean);return e.length>0?e.join("; "):JSON.stringify(t)}return t&&typeof t=="object"?t.errorMessage||JSON.stringify(t):String(t??"")}const E_=["gmail.com","googlemail.com","outlook.com","hotmail.com","live.com","msn.com"],S_="MAGIC_LINK_SENT",x_="PLUS_ALIAS_REJECTED",I_="Please enter your primary email address. Plus aliases (such as {email}) are not allowed for {domain} accounts.",Ps={allowlistedDomains:E_,successCode:S_,validationCode:x_,messageTemplate:I_},k_=new Set(Ps.allowlistedDomains),C_=Ps.successCode,uh=Ps.validationCode;function Fs(t){return typeof t=="string"?t.trim():""}function A_(t){const e=Fs(t),n=e.lastIndexOf("@");if(n<=0||n===e.length-1)return!1;const i=e.slice(0,n),r=e.slice(n+1).toLowerCase();return k_.has(r)?i.includes("+"):!1}function P_(t,e){return Ps.messageTemplate.replaceAll("{email}",t).replaceAll("{domain}",e)}function dh(t){if(!A_(t))return null;const e=Fs(t),n=e.lastIndexOf("@"),i=e.slice(n+1).toLowerCase();return P_(e,i)}function fh(t,e){return t?.code===uh?t.message||dh(e)||"Please enter your primary email address.":t?.code===C_||!t?.code?`Check your email — we sent a link to ${Fs(e)}`:t.message||"Something went wrong. Please try again."}const F_="ccc_auth_session",R_="ccc_subscription",T_=Object.freeze(["hasSeenWalkthrough"]);function $_(t){const e=[];for(const n of T_)t.getItem(n)!==null&&(t.removeItem(n),e.push(n));return e}function M_(){return[F_,R_]}function L_({storage:t,onIdentityChanged:e,onPlanChanged:n}){for(const i of M_())t.removeItem(i);typeof e=="function"&&e(),typeof n=="function"&&n()}function N_({sendLink:t,getEmail:e,onState:n}){let i=!1;return async function(){if(i)return{status:"busy"};i=!0;let s;try{n({status:"pending",error:null});const o=await t(e());return s={status:"sent",data:o},n({status:"sent",data:o}),s}catch(o){return s={status:"error",error:o},n({status:"error",error:o}),s}finally{i=!1}}}const O_=/^dependencies\s*:\s*(?:#.*)?$/,B_=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function Rs(t){const e=t.match(B_);return e?e[1]??e[2]??e[3]:null}function or(t){const e=t.trim();return e===""||e.startsWith("#")}function fi(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function xl(t,e){const n=t.findIndex(s=>e.test(s));if(n===-1)return null;let i=n,r=null;for(let s=n+1;s=0.0.0"}`}function H_(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([u])=>u&&u!=="flutter");if(i.length===0)return{yaml:n,added:[],alreadyPresent:[]};const r=n.split(` -`),s=new Set(ph(n)),o=[],a=[];for(const[u,c]of i)s.has(u)?a.push(u):(o.push([u,c]),s.add(u));if(o.length===0)return{yaml:n,added:[],alreadyPresent:a};const l=Il(r);if(l){const u=o.map(([c,d])=>Ou(l.childIndent,c,d));r.splice(l.endIndex,0,...u)}else r.length>0&&r[r.length-1].trim()!==""&&r.push(""),r.push("dependencies:"),o.forEach(([u,c])=>{r.push(Ou(" ",u,c))});return{yaml:r.join(` -`),added:o.map(([u])=>u),alreadyPresent:a}}function W_(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([l])=>l&&l!=="flutter");if(i.length===0)return{yaml:n,overridden:[],skipped:[]};const r=n.split(` -`),s=$s(n),o=[],a=[];for(const[l,u]of i){const c=s.get(l);if(!c||!c.isScalar||!String(u||"").trim()){a.push(l);continue}const d=" ".repeat(fi(r[c.lineIndex]));r[c.lineIndex]=`${d}${l}: ${mh(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:r.join(` -`),overridden:o,skipped:a}}function vh(t){const e=String(t||""),n=[];return e.trim()?(/^name:\s*\S+/m.test(e)||n.push("pubspec.yaml missing name field"),Il(e.split(` -`))||n.push("pubspec.yaml missing dependencies section"),ph(e).includes("flutter")||n.push("pubspec.yaml missing Flutter SDK dependency"),{valid:n.length===0,errors:n}):(n.push("pubspec.yaml is empty"),{valid:!1,errors:n})}const q_=">=3.0.0 <4.0.0";function Na(t){const e=String(t||"").trim(),n=e[0];return n!=="'"&&n!=='"'||e[e.length-1]!==n?e:e.slice(1,-1).replaceAll(`${n}${n}`,n)}function z_(t=""){const e=Vv(t).filter(n=>!n.startsWith("dart:")&&!n.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function Bu(t,e,n){const i=[];for(const[r,s]of t){if(s.isScalar){e[r]=Na(s.constraint);continue}if(s.sourceKey==="sdk"){n.add(r);continue}if(s.sourceKey===null&&s.version){e[r]=Na(s.version);continue}i.push(r)}return i}function G_(t){const e=new Set,n={},i={},r=Bu($s(t),n,e);r.push(...Bu(j_(t,"dependency_overrides"),i,e));const s=new Set([...Object.keys(n),...e]),{sdk:o}=gh(t);return{sdkConstraint:Na(o)||q_,dependencies:n,overrides:i,sdkPackages:[...e].sort(),availablePackages:s,unrepresentable:r}}function V_(t,e,n){return e.length>0?`${t} imports ${e.join(", ")}, which FlutterFlow only generates once the app is built, so it could not be compiled before the deploy.`:`${t} imports ${n.join(", ")}, which your project's pubspec.yaml does not declare with a version constraint, so it could not be compiled before the deploy.`}function K_(t,e){const{sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s,availablePackages:o,unrepresentable:a}=G_(e),l={sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s},u=[],c=[],d=a.map(f=>`Your project declares ${f} from a source that cannot be reproduced outside it, so the pre-deploy compile check runs against a scratch package graph that omits ${f}. Classes that do not import ${f} directly are still checked, but against that reduced graph, so their transitive package resolution may differ from your project's and the check is approximate for them.`);for(const f of t){const{className:h,content:p}=f,g=bl(p),m=g.filter(b=>a.includes(b));if(m.length>0){c.push({className:h,reason:`${h} was not compiled before deploying: it imports ${m.join(", ")}, which your project declares from a source that cannot be reproduced outside it, so package resolution could not be matched exactly.`});continue}const{unresolvableImports:v}=z_(p),S=g.filter(b=>!o.has(b));if(v.length>0||S.length>0){c.push({className:h,reason:V_(h,v,S)});continue}u.push({fileName:`${wl(h)}.dart`,content:p})}return{manifest:l,sources:u,skipped:c,approximate:d}}function Du(t,e){const n=`${t}${e}`.split(` -`),i=n.pop()??"",r=[];for(const s of n){const o=_h(s);o&&r.push(o)}return{events:r,buffer:i}}function Y_(t){const e=_h(t);return e?[e]:[]}function _h(t){const e=t.trim();if(!e)return null;try{const n=JSON.parse(e);return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}const Xe=Object.freeze({COMMITTED:"committed",PARTIAL:"partial",FAILED:"failed",UNCONFIRMED:"unconfirmed"}),J_=12e4;function yh(t){return t?.unconfirmed===!0||t?.outcome===Xe.UNCONFIRMED?Xe.UNCONFIRMED:t?.partial===!0||t?.outcome===Xe.PARTIAL?Xe.PARTIAL:t?.success===!0?Xe.COMMITTED:Xe.FAILED}async function Z_(t,e={}){const{onPhase:n,onLog:i}=e;let r=null,s="";const o=a=>{if(a.event==="phase"){a.message&&n&&n(a.message);return}if(a.event==="log"){a.message&&i&&i(a.message);return}r=a};if(t.body?.getReader){const a=t.body.getReader(),l=new TextDecoder;for(;;){const{done:u,value:c}=await a.read();if(u)break;const d=Du(s,l.decode(c,{stream:!0}));s=d.buffer,d.events.forEach(o)}}else{const a=Du("",await t.text());s=a.buffer,a.events.forEach(o)}return Y_(s).forEach(o),r?{...r,success:r.success===!0||r.success===void 0&&t.ok,finalResultReceived:!0}:{success:!1,finalResultReceived:!1,httpRejected:!t.ok,httpStatus:t.status,error:t.ok?"The FlutterFlow deploy runner closed the connection before it finished.":`FlutterFlow custom class provisioning failed (HTTP ${t.status}).`}}function X_(t){return t?.finalResultReceived?yh(t):t?.httpRejected?Xe.FAILED:Xe.UNCONFIRMED}function Q_(){let t=document.getElementById("fx-grid");if(!t)return null;const e=window.matchMedia("(prefers-reduced-motion: reduce)"),n=window.matchMedia("(pointer: none)");let i=t.getContext("webgl2",{alpha:!0,antialias:!1,depth:!1,stencil:!1,premultipliedAlpha:!0,powerPreference:"low-power"}),r=i?null:t.getContext("2d");if(!i&&!r)return null;const s='',o=`#version 300 es +`){n.push({start:d.startIndex,end:r}),o??=`line ${i}: string starting on line ${d.openedLine} is never closed`,e.pop();continue}if(!d.raw&&c==="\\"){s(t[r+1]??"",t[r+2]??""),r+=2;continue}if(!d.raw&&c==="$"&&t[r+1]==="{"){e.push({kind:"code",opener:null,interpolation:!0}),r+=2;continue}const f=d.triple?3:1;if(c===d.quote&&t.slice(r,r+f)===d.quote.repeat(f)){n.push({start:d.startIndex,end:r+f}),e.pop(),r+=f;continue}s(c,t[r+1]),r++;continue}if(c==="/"&&t[r+1]==="/"){e.push({kind:"line-comment",startIndex:r}),r+=2;continue}if(c==="/"&&t[r+1]==="*"){e.push({kind:"block-comment",startIndex:r,openedLine:i,depth:1}),r+=2;continue}if(c==="'"||c==='"'){const f=t.slice(r,r+3)===c.repeat(3),h=r>0?t[r-1]:"",p=r>1?t[r-2]:"",g=(h==="r"||h==="R")&&!__.test(p);e.push({kind:"string",quote:c,triple:f,raw:g,startIndex:r,openedLine:i}),r+=f?3:1;continue}if(Lu[c]){e.push({kind:"code",opener:c,openedLine:i}),r++;continue}if(v_[c]){if(d.interpolation&&c==="}"){e.pop(),r++;continue}if(d.opener&&Lu[d.opener]===c){e.pop(),r++;continue}return d.opener?(a(),{error:o??`line ${i}: "${c}" closes nothing - "${d.opener}" opened on line ${d.openedLine} is still open`,commentAndStringRanges:n}):(a(),{error:o??`line ${i}: unexpected "${c}" with no matching opener`,commentAndStringRanges:n})}s(c,t[r+1]),r++}a();let l=e.length-1;for(;l>0&&e[l].kind==="line-comment";)l--;let u=o;if(!u){const c=e[l];if(!(c.kind==="code"&&!c.opener&&!c.interpolation))if(c.kind==="string")u=`unclosed ${c.triple?"triple-quoted ":""}string starting on line ${c.openedLine} was never closed`;else if(c.kind==="block-comment")u=`unterminated /* comment starting on line ${c.openedLine}`;else if(c.interpolation){const d=e.findLast(h=>h.opener);u=`unclosed "\${" expression${d?` opened on line ${d.openedLine}`:""} was never closed`}else u=`"${c.opener}" opened on line ${c.openedLine} is never closed`}return{error:u,commentAndStringRanges:n}}function y_(t){return Ma(String(t??"")).error}function Nu(t,e){return e.some(({start:n,end:i})=>t>=n&&ttypeof n=="string"?n:n?.errorMessage).filter(Boolean);return e.length>0?e.join("; "):JSON.stringify(t)}return t&&typeof t=="object"?t.errorMessage||JSON.stringify(t):String(t??"")}const w_=["gmail.com","googlemail.com","outlook.com","hotmail.com","live.com","msn.com"],b_="MAGIC_LINK_SENT",E_="PLUS_ALIAS_REJECTED",S_="Please enter your primary email address. Plus aliases (such as {email}) are not allowed for {domain} accounts.",Ps={allowlistedDomains:w_,successCode:b_,validationCode:E_,messageTemplate:S_},x_=new Set(Ps.allowlistedDomains),I_=Ps.successCode,ch=Ps.validationCode;function Fs(t){return typeof t=="string"?t.trim():""}function k_(t){const e=Fs(t),n=e.lastIndexOf("@");if(n<=0||n===e.length-1)return!1;const i=e.slice(0,n),r=e.slice(n+1).toLowerCase();return x_.has(r)?i.includes("+"):!1}function C_(t,e){return Ps.messageTemplate.replaceAll("{email}",t).replaceAll("{domain}",e)}function uh(t){if(!k_(t))return null;const e=Fs(t),n=e.lastIndexOf("@"),i=e.slice(n+1).toLowerCase();return C_(e,i)}function dh(t,e){return t?.code===ch?t.message||uh(e)||"Please enter your primary email address.":t?.code===I_||!t?.code?`Check your email — we sent a link to ${Fs(e)}`:t.message||"Something went wrong. Please try again."}const A_="ccc_auth_session",P_="ccc_subscription",F_=Object.freeze(["hasSeenWalkthrough"]);function R_(t){const e=[];for(const n of F_)t.getItem(n)!==null&&(t.removeItem(n),e.push(n));return e}function T_(){return[A_,P_]}function $_({storage:t,onIdentityChanged:e,onPlanChanged:n}){for(const i of T_())t.removeItem(i);typeof e=="function"&&e(),typeof n=="function"&&n()}function M_({sendLink:t,getEmail:e,onState:n}){let i=!1;return async function(){if(i)return{status:"busy"};i=!0;let s;try{n({status:"pending",error:null});const o=await t(e());return s={status:"sent",data:o},n({status:"sent",data:o}),s}catch(o){return s={status:"error",error:o},n({status:"error",error:o}),s}finally{i=!1}}}const L_=/^dependencies\s*:\s*(?:#.*)?$/,N_=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function Rs(t){const e=t.match(N_);return e?e[1]??e[2]??e[3]:null}function ar(t){const e=t.trim();return e===""||e.startsWith("#")}function fi(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function Sl(t,e){const n=t.findIndex(s=>e.test(s));if(n===-1)return null;let i=n,r=null;for(let s=n+1;s=0.0.0"}`}function j_(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([u])=>u&&u!=="flutter");if(i.length===0)return{yaml:n,added:[],alreadyPresent:[]};const r=n.split(` +`),s=new Set(hh(n)),o=[],a=[];for(const[u,c]of i)s.has(u)?a.push(u):(o.push([u,c]),s.add(u));if(o.length===0)return{yaml:n,added:[],alreadyPresent:a};const l=xl(r);if(l){const u=o.map(([c,d])=>Ou(l.childIndent,c,d));r.splice(l.endIndex,0,...u)}else r.length>0&&r[r.length-1].trim()!==""&&r.push(""),r.push("dependencies:"),o.forEach(([u,c])=>{r.push(Ou(" ",u,c))});return{yaml:r.join(` +`),added:o.map(([u])=>u),alreadyPresent:a}}function U_(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([l])=>l&&l!=="flutter");if(i.length===0)return{yaml:n,overridden:[],skipped:[]};const r=n.split(` +`),s=$s(n),o=[],a=[];for(const[l,u]of i){const c=s.get(l);if(!c||!c.isScalar||!String(u||"").trim()){a.push(l);continue}const d=" ".repeat(fi(r[c.lineIndex]));r[c.lineIndex]=`${d}${l}: ${gh(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:r.join(` +`),overridden:o,skipped:a}}function mh(t){const e=String(t||""),n=[];return e.trim()?(/^name:\s*\S+/m.test(e)||n.push("pubspec.yaml missing name field"),xl(e.split(` +`))||n.push("pubspec.yaml missing dependencies section"),hh(e).includes("flutter")||n.push("pubspec.yaml missing Flutter SDK dependency"),{valid:n.length===0,errors:n}):(n.push("pubspec.yaml is empty"),{valid:!1,errors:n})}const H_=">=3.0.0 <4.0.0";function La(t){const e=String(t||"").trim(),n=e[0];return n!=="'"&&n!=='"'||e[e.length-1]!==n?e:e.slice(1,-1).replaceAll(`${n}${n}`,n)}function W_(t=""){const e=zv(t).filter(n=>!n.startsWith("dart:")&&!n.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function Bu(t,e,n){const i=[];for(const[r,s]of t){if(s.isScalar){e[r]=La(s.constraint);continue}if(s.sourceKey==="sdk"){n.add(r);continue}if(s.sourceKey===null&&s.version){e[r]=La(s.version);continue}i.push(r)}return i}function q_(t){const e=new Set,n={},i={},r=Bu($s(t),n,e);r.push(...Bu(B_(t,"dependency_overrides"),i,e));const s=new Set([...Object.keys(n),...e]),{sdk:o}=ph(t);return{sdkConstraint:La(o)||H_,dependencies:n,overrides:i,sdkPackages:[...e].sort(),availablePackages:s,unrepresentable:r}}function z_(t,e,n){return e.length>0?`${t} imports ${e.join(", ")}, which FlutterFlow only generates once the app is built, so it could not be compiled before the deploy.`:`${t} imports ${n.join(", ")}, which your project's pubspec.yaml does not declare with a version constraint, so it could not be compiled before the deploy.`}function V_(t,e){const{sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s,availablePackages:o,unrepresentable:a}=q_(e),l={sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s},u=[],c=[],d=a.map(f=>`Your project declares ${f} from a source that cannot be reproduced outside it, so the pre-deploy compile check runs against a scratch package graph that omits ${f}. Classes that do not import ${f} directly are still checked, but against that reduced graph, so their transitive package resolution may differ from your project's and the check is approximate for them.`);for(const f of t){const{className:h,content:p}=f,g=wl(p),m=g.filter(b=>a.includes(b));if(m.length>0){c.push({className:h,reason:`${h} was not compiled before deploying: it imports ${m.join(", ")}, which your project declares from a source that cannot be reproduced outside it, so package resolution could not be matched exactly.`});continue}const{unresolvableImports:v}=W_(p),S=g.filter(b=>!o.has(b));if(v.length>0||S.length>0){c.push({className:h,reason:z_(h,v,S)});continue}u.push({fileName:`${yl(h)}.dart`,content:p})}return{manifest:l,sources:u,skipped:c,approximate:d}}function Du(t,e){const n=`${t}${e}`.split(` +`),i=n.pop()??"",r=[];for(const s of n){const o=vh(s);o&&r.push(o)}return{events:r,buffer:i}}function G_(t){const e=vh(t);return e?[e]:[]}function vh(t){const e=t.trim();if(!e)return null;try{const n=JSON.parse(e);return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}const Xe=Object.freeze({COMMITTED:"committed",PARTIAL:"partial",FAILED:"failed",UNCONFIRMED:"unconfirmed"}),K_=12e4;function _h(t){return t?.unconfirmed===!0||t?.outcome===Xe.UNCONFIRMED?Xe.UNCONFIRMED:t?.partial===!0||t?.outcome===Xe.PARTIAL?Xe.PARTIAL:t?.success===!0?Xe.COMMITTED:Xe.FAILED}class Yt extends Error{constructor(e){super(e),this.name="UnconfirmedDeployError",this.outcome=Xe.UNCONFIRMED}}function Y_({sawTransportError:t,httpStatus:e}={}){return t?new Yt("Every FlutterFlow sync endpoint stopped answering without a definitive response. The push may still have been applied — open the FlutterFlow project to reconcile before retrying."):new Error(`FlutterFlow rejected the code sync${e?` (HTTP ${e})`:""} after every retry.`)}async function J_(t,e={}){const{onPhase:n,onLog:i}=e;let r=null,s="";const o=l=>{if(l.event==="phase"){l.message&&n&&n(l.message);return}if(l.event==="log"){l.message&&i&&i(l.message);return}r=l};let a=null;try{if(t.body?.getReader){const l=t.body.getReader(),u=new TextDecoder;for(;;){const{done:c,value:d}=await l.read();if(c)break;const f=Du(s,u.decode(d,{stream:!0}));s=f.buffer,f.events.forEach(o)}}else{const l=Du("",await t.text());s=l.buffer,l.events.forEach(o)}}catch(l){a=l}return G_(s).forEach(o),r?{...r,success:r.success===!0||r.success===void 0&&t.ok,finalResultReceived:!0}:{success:!1,finalResultReceived:!1,httpRejected:!t.ok,httpStatus:t.status,error:a?"The connection to the FlutterFlow deploy runner dropped before it reported a result.":t.ok?"The FlutterFlow deploy runner closed the connection before it finished.":`FlutterFlow custom class provisioning failed (HTTP ${t.status}).`}}function Z_(t){return t?.finalResultReceived?_h(t):t?.httpRejected?Xe.FAILED:Xe.UNCONFIRMED}function X_(){let t=document.getElementById("fx-grid");if(!t)return null;const e=window.matchMedia("(prefers-reduced-motion: reduce)"),n=window.matchMedia("(pointer: none)");let i=t.getContext("webgl2",{alpha:!0,antialias:!1,depth:!1,stencil:!1,premultipliedAlpha:!0,powerPreference:"low-power"}),r=i?null:t.getContext("2d");if(!i&&!r)return null;const s='',o=`#version 300 es in vec2 p; void main(){ gl_Position = vec4(p, 0.0, 1.0); }`;function a(){return["#version 300 es","precision highp float;","out vec4 o;","uniform vec2 res;","uniform vec2 design;","uniform vec2 mouse;","uniform float energy;","uniform float parallax;","uniform float t;","uniform vec3 ink;","uniform sampler2D mark;","uniform vec2 rot;","const float WARP_A = 0.0032;","void main(){"," vec2 px = gl_FragCoord.xy * (design / res);"," vec2 p = vec2(px.x, design.y - px.y);"," vec2 off = vec2(0.0, -parallax) + vec2(sin(t * 0.11), cos(t * 0.09)) * 7.0;"," vec2 g = p + off;"," vec2 gm = mouse + off;"," float base = min(design.x, design.y);"," float spacing = clamp(base / 10.0, 64.0, 118.0);"," vec2 rel = g - gm;"," float rho = length(rel) + 1e-5;"," vec2 dir = rel / rho;"," vec2 pw = gm + dir * (rho + WARP_A * rho * rho);"," vec2 cell = floor(pw / spacing);"," vec2 cw = (cell + 0.5) * spacing - gm;"," float Rc = length(cw) + 1e-5;"," float rhoC = (-1.0 + sqrt(1.0 + 4.0 * WARP_A * Rc)) / (2.0 * WARP_A);"," vec2 c = gm + (cw / Rc) * rhoC;"," float cellSize = spacing / (1.0 + 2.0 * WARP_A * rhoC);"," float sigma = spacing * 2.9;"," float f = exp(-(rhoC * rhoC) / (2.0 * sigma * sigma));"," float scale = mix(0.32, 1.42, f);"," float weight = smoothstep(0.06, 0.80, f);"," float hs = cellSize * 0.26 * scale;"," vec2 uv = (g - c) / hs;"," vec2 ruv = mat2(rot.x, rot.y, -rot.y, rot.x) * uv;"," float cov = 0.0;"," if (abs(ruv.x) <= 1.0 && abs(ruv.y) <= 1.0) cov = texture(mark, ruv * 0.5 + 0.5).a;"," float s = cov * weight * energy * 0.26;"," o = vec4(ink * s, s);","}"].join(` -`)}let l=null,u,c,d,f,h,p,g,m,v;function S(K,W){if(!i)return null;const D=i.createShader(K);return i.shaderSource(D,W),i.compileShader(D),i.getShaderParameter(D,i.COMPILE_STATUS)?D:(window.console&&console.warn("fx-grid shader: "+i.getShaderInfoLog(D)),null)}if(i){const K=S(i.VERTEX_SHADER,o),W=S(i.FRAGMENT_SHADER,a());if(K&&W&&(l=i.createProgram(),i.attachShader(l,K),i.attachShader(l,W),i.linkProgram(l),i.getProgramParameter(l,i.LINK_STATUS)||(window.console&&console.warn("fx-grid link: "+i.getProgramInfoLog(l)),l=null)),l){i.useProgram(l),i.bindBuffer(i.ARRAY_BUFFER,i.createBuffer()),i.bufferData(i.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),i.STATIC_DRAW);const D=i.getAttribLocation(l,"p");i.enableVertexAttribArray(D),i.vertexAttribPointer(D,2,i.FLOAT,!1,0,0),u=i.getUniformLocation(l,"res"),c=i.getUniformLocation(l,"design"),d=i.getUniformLocation(l,"mouse"),f=i.getUniformLocation(l,"energy"),h=i.getUniformLocation(l,"parallax"),p=i.getUniformLocation(l,"t"),g=i.getUniformLocation(l,"ink"),m=i.getUniformLocation(l,"mark"),v=i.getUniformLocation(l,"rot"),i.enable(i.BLEND),i.blendFunc(i.ONE,i.ONE_MINUS_SRC_ALPHA),i.clearColor(0,0,0,0)}else{i=null;const D=t.cloneNode(!1);if(t.parentNode.replaceChild(D,t),t=D,r=t.getContext("2d"),!r)return null}}function b(K){if(!K)return null;const W=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(K);if(W){let D=W[1];return D.length===3&&(D=D[0]+D[0]+D[1]+D[1]+D[2]+D[2]),[parseInt(D.slice(0,2),16)/255,parseInt(D.slice(2,4),16)/255,parseInt(D.slice(4,6),16)/255]}try{const D=document.createElement("canvas");D.width=1,D.height=1;const ue=D.getContext("2d");ue.fillStyle="rgb(9, 8, 7)";const xe=String(ue.fillStyle);ue.fillStyle=K;const Fe=String(ue.fillStyle);if(Fe===xe)return null;const ut=/^#([0-9a-f]{6})$/i.exec(Fe);if(ut){const dt=ut[1];return[parseInt(dt.slice(0,2),16)/255,parseInt(dt.slice(2,4),16)/255,parseInt(dt.slice(4,6),16)/255]}const Lt=/rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i.exec(Fe);if(Lt)return[Number(Lt[1])/255,Number(Lt[2])/255,Number(Lt[3])/255]}catch{}return null}function _(){let K="";try{const W=getComputedStyle(document.documentElement);K=(W.getPropertyValue("--fx-ink")||"").trim()||(W.getPropertyValue("--fg")||"").trim()}catch{}return b(K)||[.56,.68,.88]}const x=_();let I=1920,T=1080,E=960,P=540,$=960,O=540,L=.66,N=0,V=-1e9,G=!1,M=0,R=0,Z=null,Ce=!1,oe=!1,ye=!1;const $e=64,ae=15.2;let Ie=0,Se=0;const Be=.0032,yt=0,ge=.56,Ye=.26,wt=.32,gn=.16,Re=.349;let Pe=yt;function Tt(){const K=t.getBoundingClientRect(),W=t.clientWidth,D=t.clientHeight;if(!K.width||!W||!D)return;const ue=Math.min(window.devicePixelRatio||1,2),xe=Math.max(.2,Math.min(2,K.width/W*ue)),Fe=Math.max(2,Math.round(W*xe)),ut=Math.max(2,Math.round(D*xe));(Fe!==t.width||ut!==t.height)&&(t.width=Fe,t.height=ut,i&&i.viewport(0,0,Fe,ut)),I=W,T=D,G||(E=$=I/2,P=O=T/2,G=!0)}function Bn(K){!l||!Ce||!i||(i.uniform2f(u,t.width,t.height),i.uniform2f(c,I,T),i.uniform2f(d,E,P),i.uniform1f(f,L),i.uniform1f(h,N),i.uniform2f(v,Math.cos(Pe),Math.sin(Pe)),i.uniform1f(p,K),i.uniform3f(g,x[0],x[1],x[2]),i.clear(i.COLOR_BUFFER_BIT),i.drawArrays(i.TRIANGLES,0,3))}function qe(K,W,D){const ue=Math.max(0,Math.min(1,(D-K)/(W-K)));return ue*ue*(3-2*ue)}function Dn(K){if(!Z||!r)return;const W=r;W.setTransform(1,0,0,1,0,0),W.clearRect(0,0,t.width,t.height);const D=t.width/I;W.setTransform(D,0,0,D,0,0),W.globalAlpha=1;const ue=Math.min(I,T),xe=Math.max(64,Math.min(118,ue/10)),Fe=xe*2.9,ut=2*Fe*Fe,Lt=Math.sin(K*.11)*7,dt=Math.cos(K*.09)*7-N,ur=E+Lt,dr=P+dt,io=Fe*Math.sqrt(2*Math.log(1/.06)),mi=io+Be*io*io+xe,Cp=Math.floor((ur-mi)/xe)-1,Ap=Math.ceil((ur+mi)/xe)+1,Pp=Math.floor((dr-mi)/xe)-1,Fp=Math.ceil((dr+mi)/xe)+1;for(let ro=Pp;ro<=Fp;ro++){const Rp=(ro+.5)*xe;for(let so=Cp;so<=Ap;so++){const oo=(so+.5)*xe-ur,ao=Rp-dr,lo=Math.sqrt(oo*oo+ao*ao)+1e-5;if(lo>mi)continue;const fr=(-1+Math.sqrt(1+4*Be*lo))/(2*Be),ac=Math.exp(-(fr*fr)/ut),lc=qe(.06,.8,ac)*L*.26;if(lc<.004)continue;const sn=xe/(1+2*Be*fr)*.26*(.32+1.1*ac),cc=fr/lo,co=ur+oo*cc,uo=dr+ao*cc;co<-sn*1.6||co>I+sn*1.6||uo<-sn*1.6||uo>T+sn*1.6||(W.globalAlpha=lc,W.save(),W.translate(co,uo),W.rotate(Pe),W.drawImage(Z,-sn,-sn,sn*2,sn*2),W.restore())}}W.globalAlpha=1}function $t(K){if(!oe)return;const W=R?Math.min(.05,(K-R)/1e3):.016;R=K;const ue=K-V>2400?.6:1;L+=(ue-L)*Math.min(1,W*3.2);const xe=Math.min(.05,W);Ie+=(($-E)*$e-Ie*ae)*xe,Se+=((O-P)*$e-Se*ae)*xe,E+=Ie*xe,P+=Se*xe,N=(window.scrollY||window.pageYOffset||0)*.55;const Fe=K/1e3,ut=E/(I||1)-.5,Lt=P/(T||1)-.5;let dt=ut*(ut>=0?ge:Ye)+Lt*(Lt>=0?wt:gn);dt>Re?dt=Re:dt<-Re&&(dt=-Re),Pe=yt+dt-N*6e-4,Tt(),i?Bn(Fe):Dn(Fe),M=requestAnimationFrame($t)}function Mt(K){if(!oe)return;const W=t.getBoundingClientRect();!W.width||!I||!T||($=(K.clientX-W.left)/W.width*I,O=(K.clientY-W.top)/W.height*T,V=performance.now())}function ct(){oe||no||e.matches||n.matches||!ye||document.hidden||(oe=!0,R=0,M=requestAnimationFrame($t))}function rn(){oe=!1,M&&(cancelAnimationFrame(M),M=0),R=0}function gi(){e.matches?(rn(),t.classList.remove("is-ready")):ye&&ct()}function jn(){n.matches?rn():ye&&ct()}function rc(){document.hidden?rn():ye&&ct()}const sc=new IntersectionObserver(K=>{ye=K[0]?.isIntersecting||!1,ye?ct():rn()},{threshold:0});sc.observe(t),window.addEventListener("pointermove",Mt,{passive:!0,capture:!0}),window.addEventListener("resize",Tt),e.addEventListener("change",gi),n.addEventListener("change",jn),document.addEventListener("visibilitychange",rc);function kp(){const K=(s.match(/\sd="([^"]+)"/)||[])[1],W=document.createElement("canvas");W.width=256,W.height=256;const D=W.getContext("2d");if(K&&window.Path2D){const ue=Math.min(8.533333333333333,8.421052631578947);D.setTransform(ue,0,0,ue,ue+(256-30*ue)/2,-6.4*ue),D.fillStyle="rgb(255,255,255)",D.fill(new Path2D(K),"evenodd"),D.setTransform(1,0,0,1,0,0)}try{const ue=D.getImageData(0,0,256,256),xe=ue.data;for(let Fe=3;Feoe}}const ey=120;function ty(t,e,n){return tn?n:t}function de(t,e,n){return ty((t-e)/(n-e),0,1)}function ny(t){return t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2}function Ho(t){return 1-Math.pow(1-t,3)}function ze(t,e){return e=e===void 0?1.7:e,1+(e+1)*Math.pow(t-1,3)+e*Math.pow(t-1,2)}function ju(t){return 1-Math.pow(2,-9*t)*Math.cos(t*15)}function te(t,e){if(t<=e[0].t)return e[0].v;for(let n=1;n8.2&&_<9.4&&(s*=1-.07*Math.sin(de(_,8.2,9.4)*Math.PI))}else if(t<53){const _=t-42;g=te(_,[{t:0,v:1},{t:2,v:0},{t:4.2,v:0},{t:4.6,v:1},{t:6.8,v:1},{t:7.4,v:0},{t:9.4,v:0},{t:10.6,v:1}]),p=te(_,[{t:0,v:1},{t:2,v:.3},{t:4.6,v:1,e:ze}]),d=te(_,[{t:0,v:0},{t:2,v:.3},{t:4.6,v:.16,e:ze},{t:10.6,v:0}]),h=te(_,[{t:0,v:0},{t:2,v:-40},{t:4.6,v:0,e:ze}]),o=te(_,[{t:0,v:0},{t:4.6,v:-.12},{t:10.6,v:0}])}else if(t<60){const _=t-53;c=te(_,[{t:0,v:1},{t:.35,v:0},{t:.45,v:0},{t:.7,v:1}]);const x=de(_,.45,2.2);a=x>0?-2.6*(1-ju(x)):0,g=te(_,[{t:0,v:1},{t:.57,v:0},{t:.67,v:0},{t:.92,v:1}]);const I=de(_,.67,2.42);f=I>0?-2.6*(1-ju(I)):0,s=1-.05*(Math.sin(de(_,1.9,2.5)*Math.PI)+Math.sin(de(_,2.5,3.1)*Math.PI))}else if(t<74){let x=function(P){return[te(P,[{t:0,v:0},{t:.25,v:1},{t:.5,v:1},{t:.72,v:.14},{t:.82,v:.14},{t:1,v:0}]),te(P,[{t:0,v:0},{t:.08,v:-.62},{t:.25,v:-.62},{t:.33,v:.62},{t:.7,v:.62},{t:.82,v:-.62},{t:1,v:-.62}])]};var b=x;const _=t-60,I=1-de(_,12,14),T=x(de(_,0,12)),E=x(de(_-.5,0,12));n=T[0]*I,i=(T[1]+.05*Math.sin(_*7))*I,o=(E[0]-T[0])*.6*I,a=(E[1]-T[1])*.6*I,h=(E[0]-T[0])*30*I,S=de(_,0,.4)*I}else if(t<85.4){const _=t-74,x=te(_,[{t:0,v:0},{t:4,v:1},{t:8,v:.24},{t:9.6,v:1,e:ze},{t:11.4,v:0}]);o=x*.5,d=-x*.5,l=te(_,[{t:0,v:0},{t:4,v:6},{t:8,v:20},{t:9.6,v:38,e:ze},{t:11.4,v:0}]),h=-l*.7,a=te(_,[{t:0,v:0},{t:8,v:0},{t:9.6,v:.4},{t:11.4,v:0}])}else if(t<96.4){const _=t-85.4,x=de(_,0,5.6),I=de(_,5.6,7.6),T=.72*Math.min(1,_/.6)*(1-I);d=Math.cos(x*Math.PI*2)*T,f=Math.sin(x*Math.PI*2)*T*.55,h=x*360*(1-I);const E=te(_,[{t:0,v:0},{t:7.6,v:0},{t:8.2,v:1,e:Ho},{t:8.6,v:.55},{t:9.4,v:0}]);o=-.16*E,d+=.16*E,l=-6*E,h+=6*E,s=1+.05*E,m=1+.9*E}else if(t<108.6){const _=t-96.4,x=de(_,9.6,12.2);n=te(_,[{t:0,v:0},{t:2.1,v:1},{t:4.8,v:.08},{t:7.5,v:1},{t:9.6,v:0}])*(1-x),i=-.35*Math.abs(Math.sin(de(_,0,9.6)*Math.PI*3))*(1-x);const I=Math.sin(_*6.2)*(1-x);u=1+.12*I,p=1-.12*I,l=I*8,h=-I*8,o=.06*I,d=-.06*I,S=de(_,0,.4)*(1-x)}else{const _=t-108.6,x=Math.sin(de(_,0,8)*Math.PI),I=1-de(_,8,11.4);s=1+.04*x*I,i=-.1*x*I,r=2*x*I,m=1+.5*Math.sin(de(_,0,6)*Math.PI),v=1+.1*Math.sin(de(_,0,6)*Math.PI)}return e.x=n,e.y=i,e.rot=r,e.scale=s,e.ax=o,e.ay=a,e.ar=l,e.asc=u,e.afade=c,e.bx=d,e.by=f,e.br=h,e.bsc=p,e.bfade=g,e.hfade=m,e.hsc=v,e.shd=S,e}function iy(t={}){const e=t.arena||document.querySelector(".pipeline-glyph.logo-loop");if(!e)return null;const n=e.querySelector(".loop-mark"),i=e.querySelector(".loop-piece-a"),r=e.querySelector(".loop-piece-b"),s=e.querySelector(".loop-halo"),o=e.querySelector(".loop-shadow");if(!n||!i||!r||!s||!o)return null;const a=t.reducedMotion||window.matchMedia("(prefers-reduced-motion: reduce)"),l=ey;let u=34,c=0,d=0;function f(){u=n.offsetWidth||34,c=Math.max(0,e.offsetWidth-u-4),d=Math.max(0,(e.offsetHeight-u)/2-2),e.style.setProperty("--mark-c",u/2+"px")}function h(M){const R=Math.min(1,Math.max(0,M.x))*c,Z=M.y*d;n.style.transform="translate3d("+R.toFixed(2)+"px,"+Z.toFixed(2)+"px,0) rotate("+M.rot.toFixed(2)+"deg) scale("+M.scale.toFixed(3)+")",i.style.transform="translate3d("+(M.ax*u).toFixed(2)+"px,"+(M.ay*u).toFixed(2)+"px,0) rotate("+M.ar.toFixed(2)+"deg) scale("+M.asc.toFixed(3)+")",i.style.opacity=M.afade.toFixed(3),r.style.transform="translate3d("+(M.bx*u).toFixed(2)+"px,"+(M.by*u).toFixed(2)+"px,0) rotate("+M.br.toFixed(2)+"deg) scale("+M.bsc.toFixed(3)+")",r.style.opacity=M.bfade.toFixed(3),s.style.transform="scale("+M.hsc.toFixed(3)+")",s.style.opacity=(.09*M.hfade).toFixed(3),o.style.transform="translateX("+R.toFixed(2)+"px) scaleX("+(.75+.4*Math.abs(M.x)).toFixed(3)+")",o.style.opacity=(M.shd*.5).toFixed(3)}let p=0,g=0,m=0,v=!1,S=!1,b=!1,_=0;function x(){return b||a.matches||document.hidden||!e.offsetParent?!1:S}function I(M){if(!v)return;if(m=requestAnimationFrame(I),!x()){E();return}const R=g?(M-g)/1e3:0;g=M,p=(p+Math.min(R,.1))%l,_+=1,h(Ai(p))}function T(){v||b||x()&&(v=!0,g=0,m=requestAnimationFrame(I))}function E(){v=!1,m&&(cancelAnimationFrame(m),m=0),g=0}function P(){x()?T():E()}function $(){a.matches?(E(),h(Ai(0))):P()}function O(){f(),v&&h(Ai(p))}function L(){g=0,P()}const N=new IntersectionObserver(M=>{S=M[0]?M[0].isIntersecting:!1,P()},{threshold:0});N.observe(e),window.addEventListener("resize",O),a.addEventListener("change",$),document.addEventListener("visibilitychange",L);function V(){b||(b=!0,E(),N.disconnect(),window.removeEventListener("resize",O),a.removeEventListener("change",$),document.removeEventListener("visibilitychange",L))}window.addEventListener("pagehide",V);function G(M){p=(M%l+l)%l,h(Ai(p))}return f(),h(Ai(0)),P(),{isRunning:()=>v,currentTime:()=>p,frameCount:()=>_,seek:G,dispose:V}}const ry=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function Zt(t){const e=String(t||"").trim().match(ry);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function sy(t,e){if(t.length===0&&e.length===0)return 0;if(t.length===0)return 1;if(e.length===0)return-1;for(let n=0;n0)}function ay(t){const e=Zt(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function kl(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 Zt(o)?{min:o,minInclusive:!0,max:ay(o),maxInclusive:!1}:null}if(Zt(e))return{min:e,minInclusive:!0,max:e,maxInclusive:!0};const n={min:null,minInclusive:!1,max:null,maxInclusive:!1},i=/(>=|<=|>|<)\s*([0-9][0-9A-Za-z.+-]*)/g;let r=!1,s;for(;(s=i.exec(e))!==null;){const[,o,a]=s;if(!Zt(a))return null;r=!0,o===">="||o===">"?(n.min=a,n.minInclusive=o===">="):(n.max=a,n.maxInclusive=o==="<=")}return r?n:null}function Uu(t,e){const n=kl(t);if(!n||!Zt(e))return!1;if(n.min!==null){const i=ds(e,n.min);if(i<0||i===0&&!n.minInclusive)return!1}if(n.max!==null){const i=ds(e,n.max);if(i>0||i===0&&!n.maxInclusive)return!1}return!0}function ly(t,e){const n=kl(t);if(!n||!Zt(e))return!1;if(n.max===null)return!0;const i=ds(n.max,e);return i>0?!0:i===0&&n.maxInclusive}function zn(t){const e=kl(t);return e?e.min:null}const cy="https://pub.dev/api/packages/",uy=8e3;function dy(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null}=e,r=Array.isArray(t?.versions)?t.versions:[];let s=null;for(const o of r){const a=o?.version;if(!a||o.retracted||oy(a))continue;const l=o.pubspec?.environment||{};n&&l.sdk&&!Uu(l.sdk,n)||i&&l.flutter&&!Uu(l.flutter,i)||(!s||ds(a,s)>0)&&(s=a)}return s?{version:s,constraint:`^${s}`}:null}async function fy(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null,fetchImpl:r=fetch}=e;let s;try{const a=await r(`${cy}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(uy)});if(!a.ok)return{name:t,constraint:null,version:null,error:a.status===404?`"${t}" was not found on pub.dev`:`pub.dev returned ${a.status} for "${t}"`};s=await a.json()}catch(a){return{name:t,constraint:null,version:null,error:`could not reach pub.dev for "${t}" (${a.message})`}}const o=dy(s,{dartSdkFloor:n,flutterSdkFloor:i});return o?{name:t,...o,error:null}:{name:t,constraint:null,version:null,error:n?`no published "${t}" release supports Dart ${n}`:`no published "${t}" release could be read`}}async function hy(t,e={}){const n=await Promise.all(t.map(i=>fy(i,e)));return new Map(n.map(({name:i,...r})=>[i,r]))}async function py(t,e={},n={}){const{resolveVersions:i=hy}=n,r=Object.entries(e).filter(([c])=>c&&c!=="flutter"),s=gh(t),o={dartSdkFloor:zn(s.sdk),flutterSdkFloor:zn(s.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(r.length===0)return a;const l=$s(t),u=[];for(const[c,d]of r){const f=l.get(c);if(!f){u.push(c);continue}const h=zn(d);if(!h){a.kept.push({name:c,constraint:f.constraint});continue}if(!f.isScalar){a.warnings.push(`"${c}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${h}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:c,constraint:f.constraint});continue}if(ly(f.constraint,h)){a.kept.push({name:c,constraint:f.constraint});continue}a.overrides[c]=`^${h}`,a.warnings.push(`"${c}" was pinned to ${f.constraint} in your project, which cannot resolve the ${h} the generated code needs. Raising it to ^${h} — this changes a dependency the rest of your app also uses.`)}if(u.length>0){const c=await i(u,o);for(const d of u){const f=c.get(d);if(f?.constraint){a.additions[d]=f.constraint;continue}const h=e[d]||"";if(zn(h)){a.additions[d]=`^${zn(h)}`,a.warnings.push(`Could not confirm "${d}" version on pub.dev (${f?.error||"lookup failed"}). Using ^${zn(h)} from the AI's recommendation — verify this is current.`);continue}a.additions[d]=">=0.0.0",a.warnings.push(`Could not determine a version for "${d}" (${f?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const gy={"&":"&","<":"<",">":">",'"':""","'":"'"};function Xt(t){return String(t??"").replace(/[&<>"']/g,e=>gy[e])}function q(t){return t?Xt(t).replace(/\n/g,"
"):""}function Yt(t){return Xt(t).replace(/\r?\n/g," ")}function Ms(t,e={}){const n=t?.pipelineStep;if(n!=null&&e[n]!=null)return e[n];const i=t?.message||"";return i.includes("Code Generator")?2:i.includes("Code Review")?3:1}function bh(t){if(!t)return{kind:"generic",title:"Generation failed",message:"An unknown error occurred. Please try again.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1};if(t.isModelArmor){const n=t.code==="MODEL_ARMOR_BLOCKED";return{kind:"safety",title:t.userTitle||"Request blocked for safety",message:t.userMessage||t.message,detail:t.retryExplanation||"",canRetry:!n,canEdit:!0,canUpgrade:!1}}if(t.isUsageLimit)return{kind:"quota",title:"Monthly limit reached",message:t.message||"You've used all your generations for this period.",detail:"",canRetry:!1,canEdit:!1,canUpgrade:!0};const e=t.message||"";return/timed out after/i.test(e)?{kind:"timeout",title:"Request timed out",message:"The generation service took too long to respond.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:/unreachable|failed to fetch|load failed|cors/i.test(e)?{kind:"network",title:"Connection problem",message:"We couldn't reach the generation service. Check your connection and try again.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:{kind:"generic",title:"Generation failed",message:e||"An unexpected error occurred.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1}}function my(t){const e={"Integration Audit Report":"📋","Critical Issues":"❌",Warnings:"⚠️",Recommendations:"✅","Overall Score":"📊"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📄"}function vy(t){const e={critical:"❌",warning:"⚠️",recommendation:"✅",score:"📊",issue:"🔍",fix:"🔧"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📝"}function _y(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 li(t){if(!t)return"";if(typeof t!="string")return String(t);const e=/```(?:\w+)?\n?([\s\S]*?)```/,n=t.match(e);return n?n[1].trim():t.trim()}function Hu(t){return t=Xt(t),t=t.replace(/\*\*(.*?)\*\*/g,'$1'),t=t.replace(/\*(.*?)\*/g,'$1'),t=t.replace(/`(.*?)`/g,'$1'),t=t.replace(/\b(FAIL|ERROR|CRITICAL)\b/g,'$1'),t=t.replace(/\b(WARN|WARNING)\b/g,'$1'),t=t.replace(/\b(PASS|SUCCESS|OK)\b/g,'$1'),t}function Eh(t,e="dart",n=globalThis.hljs){if(!t)return"";const i=li(t);try{return n.highlight(i,{language:e}).value}catch(r){console.warn("Syntax highlighting failed:",r);try{return n.highlight(i,{language:"json"}).value}catch{return Xt(i)}}}function Ls(t,e={}){const{highlighter:n=globalThis.hljs}=e;let i='
';const r=String(t??"").split(` -`);let s=!1,o="";for(const a of r){if(a.startsWith("```")){if(s){const l=_y(o),u=Eh(o.trim(),l,n);i+=`
+`)}let l=null,u,c,d,f,h,p,g,m,v;function S(Y,W){if(!i)return null;const D=i.createShader(Y);return i.shaderSource(D,W),i.compileShader(D),i.getShaderParameter(D,i.COMPILE_STATUS)?D:(window.console&&console.warn("fx-grid shader: "+i.getShaderInfoLog(D)),null)}if(i){const Y=S(i.VERTEX_SHADER,o),W=S(i.FRAGMENT_SHADER,a());if(Y&&W&&(l=i.createProgram(),i.attachShader(l,Y),i.attachShader(l,W),i.linkProgram(l),i.getProgramParameter(l,i.LINK_STATUS)||(window.console&&console.warn("fx-grid link: "+i.getProgramInfoLog(l)),l=null)),l){i.useProgram(l),i.bindBuffer(i.ARRAY_BUFFER,i.createBuffer()),i.bufferData(i.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),i.STATIC_DRAW);const D=i.getAttribLocation(l,"p");i.enableVertexAttribArray(D),i.vertexAttribPointer(D,2,i.FLOAT,!1,0,0),u=i.getUniformLocation(l,"res"),c=i.getUniformLocation(l,"design"),d=i.getUniformLocation(l,"mouse"),f=i.getUniformLocation(l,"energy"),h=i.getUniformLocation(l,"parallax"),p=i.getUniformLocation(l,"t"),g=i.getUniformLocation(l,"ink"),m=i.getUniformLocation(l,"mark"),v=i.getUniformLocation(l,"rot"),i.enable(i.BLEND),i.blendFunc(i.ONE,i.ONE_MINUS_SRC_ALPHA),i.clearColor(0,0,0,0)}else{i=null;const D=t.cloneNode(!1);if(t.parentNode.replaceChild(D,t),t=D,r=t.getContext("2d"),!r)return null}}function b(Y){if(!Y)return null;const W=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(Y);if(W){let D=W[1];return D.length===3&&(D=D[0]+D[0]+D[1]+D[1]+D[2]+D[2]),[parseInt(D.slice(0,2),16)/255,parseInt(D.slice(2,4),16)/255,parseInt(D.slice(4,6),16)/255]}try{const D=document.createElement("canvas");D.width=1,D.height=1;const ue=D.getContext("2d");ue.fillStyle="rgb(9, 8, 7)";const xe=String(ue.fillStyle);ue.fillStyle=Y;const Fe=String(ue.fillStyle);if(Fe===xe)return null;const ut=/^#([0-9a-f]{6})$/i.exec(Fe);if(ut){const dt=ut[1];return[parseInt(dt.slice(0,2),16)/255,parseInt(dt.slice(2,4),16)/255,parseInt(dt.slice(4,6),16)/255]}const Lt=/rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i.exec(Fe);if(Lt)return[Number(Lt[1])/255,Number(Lt[2])/255,Number(Lt[3])/255]}catch{}return null}function _(){let Y="";try{const W=getComputedStyle(document.documentElement);Y=(W.getPropertyValue("--fx-ink")||"").trim()||(W.getPropertyValue("--fg")||"").trim()}catch{}return b(Y)||[.56,.68,.88]}const x=_();let I=1920,T=1080,E=960,P=540,$=960,O=540,L=.66,N=0,K=-1e9,V=!1,M=0,R=0,Z=null,Ce=!1,oe=!1,ye=!1;const $e=64,ae=15.2;let Ie=0,Se=0;const Be=.0032,yt=0,ge=.56,Ye=.26,wt=.32,mn=.16,Re=.349;let Pe=yt;function Tt(){const Y=t.getBoundingClientRect(),W=t.clientWidth,D=t.clientHeight;if(!Y.width||!W||!D)return;const ue=Math.min(window.devicePixelRatio||1,2),xe=Math.max(.2,Math.min(2,Y.width/W*ue)),Fe=Math.max(2,Math.round(W*xe)),ut=Math.max(2,Math.round(D*xe));(Fe!==t.width||ut!==t.height)&&(t.width=Fe,t.height=ut,i&&i.viewport(0,0,Fe,ut)),I=W,T=D,V||(E=$=I/2,P=O=T/2,V=!0)}function Bn(Y){!l||!Ce||!i||(i.uniform2f(u,t.width,t.height),i.uniform2f(c,I,T),i.uniform2f(d,E,P),i.uniform1f(f,L),i.uniform1f(h,N),i.uniform2f(v,Math.cos(Pe),Math.sin(Pe)),i.uniform1f(p,Y),i.uniform3f(g,x[0],x[1],x[2]),i.clear(i.COLOR_BUFFER_BIT),i.drawArrays(i.TRIANGLES,0,3))}function qe(Y,W,D){const ue=Math.max(0,Math.min(1,(D-Y)/(W-Y)));return ue*ue*(3-2*ue)}function Dn(Y){if(!Z||!r)return;const W=r;W.setTransform(1,0,0,1,0,0),W.clearRect(0,0,t.width,t.height);const D=t.width/I;W.setTransform(D,0,0,D,0,0),W.globalAlpha=1;const ue=Math.min(I,T),xe=Math.max(64,Math.min(118,ue/10)),Fe=xe*2.9,ut=2*Fe*Fe,Lt=Math.sin(Y*.11)*7,dt=Math.cos(Y*.09)*7-N,dr=E+Lt,fr=P+dt,no=Fe*Math.sqrt(2*Math.log(1/.06)),mi=no+Be*no*no+xe,Ip=Math.floor((dr-mi)/xe)-1,kp=Math.ceil((dr+mi)/xe)+1,Cp=Math.floor((fr-mi)/xe)-1,Ap=Math.ceil((fr+mi)/xe)+1;for(let io=Cp;io<=Ap;io++){const Pp=(io+.5)*xe;for(let ro=Ip;ro<=kp;ro++){const so=(ro+.5)*xe-dr,oo=Pp-fr,ao=Math.sqrt(so*so+oo*oo)+1e-5;if(ao>mi)continue;const hr=(-1+Math.sqrt(1+4*Be*ao))/(2*Be),ac=Math.exp(-(hr*hr)/ut),lc=qe(.06,.8,ac)*L*.26;if(lc<.004)continue;const on=xe/(1+2*Be*hr)*.26*(.32+1.1*ac),cc=hr/ao,lo=dr+so*cc,co=fr+oo*cc;lo<-on*1.6||lo>I+on*1.6||co<-on*1.6||co>T+on*1.6||(W.globalAlpha=lc,W.save(),W.translate(lo,co),W.rotate(Pe),W.drawImage(Z,-on,-on,on*2,on*2),W.restore())}}W.globalAlpha=1}function $t(Y){if(!oe)return;const W=R?Math.min(.05,(Y-R)/1e3):.016;R=Y;const ue=Y-K>2400?.6:1;L+=(ue-L)*Math.min(1,W*3.2);const xe=Math.min(.05,W);Ie+=(($-E)*$e-Ie*ae)*xe,Se+=((O-P)*$e-Se*ae)*xe,E+=Ie*xe,P+=Se*xe,N=(window.scrollY||window.pageYOffset||0)*.55;const Fe=Y/1e3,ut=E/(I||1)-.5,Lt=P/(T||1)-.5;let dt=ut*(ut>=0?ge:Ye)+Lt*(Lt>=0?wt:mn);dt>Re?dt=Re:dt<-Re&&(dt=-Re),Pe=yt+dt-N*6e-4,Tt(),i?Bn(Fe):Dn(Fe),M=requestAnimationFrame($t)}function Mt(Y){if(!oe)return;const W=t.getBoundingClientRect();!W.width||!I||!T||($=(Y.clientX-W.left)/W.width*I,O=(Y.clientY-W.top)/W.height*T,K=performance.now())}function ct(){oe||to||e.matches||n.matches||!ye||document.hidden||(oe=!0,R=0,M=requestAnimationFrame($t))}function sn(){oe=!1,M&&(cancelAnimationFrame(M),M=0),R=0}function gi(){e.matches?(sn(),t.classList.remove("is-ready")):ye&&ct()}function jn(){n.matches?sn():ye&&ct()}function rc(){document.hidden?sn():ye&&ct()}const sc=new IntersectionObserver(Y=>{ye=Y[0]?.isIntersecting||!1,ye?ct():sn()},{threshold:0});sc.observe(t),window.addEventListener("pointermove",Mt,{passive:!0,capture:!0}),window.addEventListener("resize",Tt),e.addEventListener("change",gi),n.addEventListener("change",jn),document.addEventListener("visibilitychange",rc);function xp(){const Y=(s.match(/\sd="([^"]+)"/)||[])[1],W=document.createElement("canvas");W.width=256,W.height=256;const D=W.getContext("2d");if(Y&&window.Path2D){const ue=Math.min(8.533333333333333,8.421052631578947);D.setTransform(ue,0,0,ue,ue+(256-30*ue)/2,-6.4*ue),D.fillStyle="rgb(255,255,255)",D.fill(new Path2D(Y),"evenodd"),D.setTransform(1,0,0,1,0,0)}try{const ue=D.getImageData(0,0,256,256),xe=ue.data;for(let Fe=3;Feoe}}const Q_=120;function ey(t,e,n){return tn?n:t}function de(t,e,n){return ey((t-e)/(n-e),0,1)}function ty(t){return t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2}function Uo(t){return 1-Math.pow(1-t,3)}function ze(t,e){return e=e===void 0?1.7:e,1+(e+1)*Math.pow(t-1,3)+e*Math.pow(t-1,2)}function ju(t){return 1-Math.pow(2,-9*t)*Math.cos(t*15)}function te(t,e){if(t<=e[0].t)return e[0].v;for(let n=1;n8.2&&_<9.4&&(s*=1-.07*Math.sin(de(_,8.2,9.4)*Math.PI))}else if(t<53){const _=t-42;g=te(_,[{t:0,v:1},{t:2,v:0},{t:4.2,v:0},{t:4.6,v:1},{t:6.8,v:1},{t:7.4,v:0},{t:9.4,v:0},{t:10.6,v:1}]),p=te(_,[{t:0,v:1},{t:2,v:.3},{t:4.6,v:1,e:ze}]),d=te(_,[{t:0,v:0},{t:2,v:.3},{t:4.6,v:.16,e:ze},{t:10.6,v:0}]),h=te(_,[{t:0,v:0},{t:2,v:-40},{t:4.6,v:0,e:ze}]),o=te(_,[{t:0,v:0},{t:4.6,v:-.12},{t:10.6,v:0}])}else if(t<60){const _=t-53;c=te(_,[{t:0,v:1},{t:.35,v:0},{t:.45,v:0},{t:.7,v:1}]);const x=de(_,.45,2.2);a=x>0?-2.6*(1-ju(x)):0,g=te(_,[{t:0,v:1},{t:.57,v:0},{t:.67,v:0},{t:.92,v:1}]);const I=de(_,.67,2.42);f=I>0?-2.6*(1-ju(I)):0,s=1-.05*(Math.sin(de(_,1.9,2.5)*Math.PI)+Math.sin(de(_,2.5,3.1)*Math.PI))}else if(t<74){let x=function(P){return[te(P,[{t:0,v:0},{t:.25,v:1},{t:.5,v:1},{t:.72,v:.14},{t:.82,v:.14},{t:1,v:0}]),te(P,[{t:0,v:0},{t:.08,v:-.62},{t:.25,v:-.62},{t:.33,v:.62},{t:.7,v:.62},{t:.82,v:-.62},{t:1,v:-.62}])]};var b=x;const _=t-60,I=1-de(_,12,14),T=x(de(_,0,12)),E=x(de(_-.5,0,12));n=T[0]*I,i=(T[1]+.05*Math.sin(_*7))*I,o=(E[0]-T[0])*.6*I,a=(E[1]-T[1])*.6*I,h=(E[0]-T[0])*30*I,S=de(_,0,.4)*I}else if(t<85.4){const _=t-74,x=te(_,[{t:0,v:0},{t:4,v:1},{t:8,v:.24},{t:9.6,v:1,e:ze},{t:11.4,v:0}]);o=x*.5,d=-x*.5,l=te(_,[{t:0,v:0},{t:4,v:6},{t:8,v:20},{t:9.6,v:38,e:ze},{t:11.4,v:0}]),h=-l*.7,a=te(_,[{t:0,v:0},{t:8,v:0},{t:9.6,v:.4},{t:11.4,v:0}])}else if(t<96.4){const _=t-85.4,x=de(_,0,5.6),I=de(_,5.6,7.6),T=.72*Math.min(1,_/.6)*(1-I);d=Math.cos(x*Math.PI*2)*T,f=Math.sin(x*Math.PI*2)*T*.55,h=x*360*(1-I);const E=te(_,[{t:0,v:0},{t:7.6,v:0},{t:8.2,v:1,e:Uo},{t:8.6,v:.55},{t:9.4,v:0}]);o=-.16*E,d+=.16*E,l=-6*E,h+=6*E,s=1+.05*E,m=1+.9*E}else if(t<108.6){const _=t-96.4,x=de(_,9.6,12.2);n=te(_,[{t:0,v:0},{t:2.1,v:1},{t:4.8,v:.08},{t:7.5,v:1},{t:9.6,v:0}])*(1-x),i=-.35*Math.abs(Math.sin(de(_,0,9.6)*Math.PI*3))*(1-x);const I=Math.sin(_*6.2)*(1-x);u=1+.12*I,p=1-.12*I,l=I*8,h=-I*8,o=.06*I,d=-.06*I,S=de(_,0,.4)*(1-x)}else{const _=t-108.6,x=Math.sin(de(_,0,8)*Math.PI),I=1-de(_,8,11.4);s=1+.04*x*I,i=-.1*x*I,r=2*x*I,m=1+.5*Math.sin(de(_,0,6)*Math.PI),v=1+.1*Math.sin(de(_,0,6)*Math.PI)}return e.x=n,e.y=i,e.rot=r,e.scale=s,e.ax=o,e.ay=a,e.ar=l,e.asc=u,e.afade=c,e.bx=d,e.by=f,e.br=h,e.bsc=p,e.bfade=g,e.hfade=m,e.hsc=v,e.shd=S,e}function ny(t={}){const e=t.arena||document.querySelector(".pipeline-glyph.logo-loop");if(!e)return null;const n=e.querySelector(".loop-mark"),i=e.querySelector(".loop-piece-a"),r=e.querySelector(".loop-piece-b"),s=e.querySelector(".loop-halo"),o=e.querySelector(".loop-shadow");if(!n||!i||!r||!s||!o)return null;const a=t.reducedMotion||window.matchMedia("(prefers-reduced-motion: reduce)"),l=Q_;let u=34,c=0,d=0;function f(){u=n.offsetWidth||34,c=Math.max(0,e.offsetWidth-u-4),d=Math.max(0,(e.offsetHeight-u)/2-2),e.style.setProperty("--mark-c",u/2+"px")}function h(M){const R=Math.min(1,Math.max(0,M.x))*c,Z=M.y*d;n.style.transform="translate3d("+R.toFixed(2)+"px,"+Z.toFixed(2)+"px,0) rotate("+M.rot.toFixed(2)+"deg) scale("+M.scale.toFixed(3)+")",i.style.transform="translate3d("+(M.ax*u).toFixed(2)+"px,"+(M.ay*u).toFixed(2)+"px,0) rotate("+M.ar.toFixed(2)+"deg) scale("+M.asc.toFixed(3)+")",i.style.opacity=M.afade.toFixed(3),r.style.transform="translate3d("+(M.bx*u).toFixed(2)+"px,"+(M.by*u).toFixed(2)+"px,0) rotate("+M.br.toFixed(2)+"deg) scale("+M.bsc.toFixed(3)+")",r.style.opacity=M.bfade.toFixed(3),s.style.transform="scale("+M.hsc.toFixed(3)+")",s.style.opacity=(.09*M.hfade).toFixed(3),o.style.transform="translateX("+R.toFixed(2)+"px) scaleX("+(.75+.4*Math.abs(M.x)).toFixed(3)+")",o.style.opacity=(M.shd*.5).toFixed(3)}let p=0,g=0,m=0,v=!1,S=!1,b=!1,_=0;function x(){return b||a.matches||document.hidden||!e.offsetParent?!1:S}function I(M){if(!v)return;if(m=requestAnimationFrame(I),!x()){E();return}const R=g?(M-g)/1e3:0;g=M,p=(p+Math.min(R,.1))%l,_+=1,h(Ai(p))}function T(){v||b||x()&&(v=!0,g=0,m=requestAnimationFrame(I))}function E(){v=!1,m&&(cancelAnimationFrame(m),m=0),g=0}function P(){x()?T():E()}function $(){a.matches?(E(),h(Ai(0))):P()}function O(){f(),v&&h(Ai(p))}function L(){g=0,P()}const N=new IntersectionObserver(M=>{S=M[0]?M[0].isIntersecting:!1,P()},{threshold:0});N.observe(e),window.addEventListener("resize",O),a.addEventListener("change",$),document.addEventListener("visibilitychange",L);function K(){b||(b=!0,E(),N.disconnect(),window.removeEventListener("resize",O),a.removeEventListener("change",$),document.removeEventListener("visibilitychange",L))}window.addEventListener("pagehide",K);function V(M){p=(M%l+l)%l,h(Ai(p))}return f(),h(Ai(0)),P(),{isRunning:()=>v,currentTime:()=>p,frameCount:()=>_,seek:V,dispose:K}}const iy=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function Xt(t){const e=String(t||"").trim().match(iy);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function ry(t,e){if(t.length===0&&e.length===0)return 0;if(t.length===0)return 1;if(e.length===0)return-1;for(let n=0;n0)}function oy(t){const e=Xt(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function Il(t){let e=String(t??"").trim();if((e.startsWith("'")||e.startsWith('"'))&&(e=e.slice(1,-1).trim()),e===""||e==="any"||e==="*")return{min:null,minInclusive:!1,max:null,maxInclusive:!1};if(e.startsWith("^")){const o=e.slice(1).trim();return Xt(o)?{min:o,minInclusive:!0,max:oy(o),maxInclusive:!1}:null}if(Xt(e))return{min:e,minInclusive:!0,max:e,maxInclusive:!0};const n={min:null,minInclusive:!1,max:null,maxInclusive:!1},i=/(>=|<=|>|<)\s*([0-9][0-9A-Za-z.+-]*)/g;let r=!1,s;for(;(s=i.exec(e))!==null;){const[,o,a]=s;if(!Xt(a))return null;r=!0,o===">="||o===">"?(n.min=a,n.minInclusive=o===">="):(n.max=a,n.maxInclusive=o==="<=")}return r?n:null}function Uu(t,e){const n=Il(t);if(!n||!Xt(e))return!1;if(n.min!==null){const i=fs(e,n.min);if(i<0||i===0&&!n.minInclusive)return!1}if(n.max!==null){const i=fs(e,n.max);if(i>0||i===0&&!n.maxInclusive)return!1}return!0}function ay(t,e){const n=Il(t);if(!n||!Xt(e))return!1;if(n.max===null)return!0;const i=fs(n.max,e);return i>0?!0:i===0&&n.maxInclusive}function zn(t){const e=Il(t);return e?e.min:null}const ly="https://pub.dev/api/packages/",cy=8e3;function uy(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null}=e,r=Array.isArray(t?.versions)?t.versions:[];let s=null;for(const o of r){const a=o?.version;if(!a||o.retracted||sy(a))continue;const l=o.pubspec?.environment||{};n&&l.sdk&&!Uu(l.sdk,n)||i&&l.flutter&&!Uu(l.flutter,i)||(!s||fs(a,s)>0)&&(s=a)}return s?{version:s,constraint:`^${s}`}:null}async function dy(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null,fetchImpl:r=fetch}=e;let s;try{const a=await r(`${ly}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(cy)});if(!a.ok)return{name:t,constraint:null,version:null,error:a.status===404?`"${t}" was not found on pub.dev`:`pub.dev returned ${a.status} for "${t}"`};s=await a.json()}catch(a){return{name:t,constraint:null,version:null,error:`could not reach pub.dev for "${t}" (${a.message})`}}const o=uy(s,{dartSdkFloor:n,flutterSdkFloor:i});return o?{name:t,...o,error:null}:{name:t,constraint:null,version:null,error:n?`no published "${t}" release supports Dart ${n}`:`no published "${t}" release could be read`}}async function fy(t,e={}){const n=await Promise.all(t.map(i=>dy(i,e)));return new Map(n.map(({name:i,...r})=>[i,r]))}async function hy(t,e={},n={}){const{resolveVersions:i=fy}=n,r=Object.entries(e).filter(([c])=>c&&c!=="flutter"),s=ph(t),o={dartSdkFloor:zn(s.sdk),flutterSdkFloor:zn(s.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(r.length===0)return a;const l=$s(t),u=[];for(const[c,d]of r){const f=l.get(c);if(!f){u.push(c);continue}const h=zn(d);if(!h){a.kept.push({name:c,constraint:f.constraint});continue}if(!f.isScalar){a.warnings.push(`"${c}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${h}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:c,constraint:f.constraint});continue}if(ay(f.constraint,h)){a.kept.push({name:c,constraint:f.constraint});continue}a.overrides[c]=`^${h}`,a.warnings.push(`"${c}" was pinned to ${f.constraint} in your project, which cannot resolve the ${h} the generated code needs. Raising it to ^${h} — this changes a dependency the rest of your app also uses.`)}if(u.length>0){const c=await i(u,o);for(const d of u){const f=c.get(d);if(f?.constraint){a.additions[d]=f.constraint;continue}const h=e[d]||"";if(zn(h)){a.additions[d]=`^${zn(h)}`,a.warnings.push(`Could not confirm "${d}" version on pub.dev (${f?.error||"lookup failed"}). Using ^${zn(h)} from the AI's recommendation — verify this is current.`);continue}a.additions[d]=">=0.0.0",a.warnings.push(`Could not determine a version for "${d}" (${f?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const py={"&":"&","<":"<",">":">",'"':""","'":"'"};function Qt(t){return String(t??"").replace(/[&<>"']/g,e=>py[e])}function q(t){return t?Qt(t).replace(/\n/g,"
"):""}function Jt(t){return Qt(t).replace(/\r?\n/g," ")}function Ms(t,e={}){const n=t?.pipelineStep;if(n!=null&&e[n]!=null)return e[n];const i=t?.message||"";return i.includes("Code Generator")?2:i.includes("Code Review")?3:1}function wh(t){if(!t)return{kind:"generic",title:"Generation failed",message:"An unknown error occurred. Please try again.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1};if(t.isModelArmor){const n=t.code==="MODEL_ARMOR_BLOCKED";return{kind:"safety",title:t.userTitle||"Request blocked for safety",message:t.userMessage||t.message,detail:t.retryExplanation||"",canRetry:!n,canEdit:!0,canUpgrade:!1}}if(t.isUsageLimit)return{kind:"quota",title:"Monthly limit reached",message:t.message||"You've used all your generations for this period.",detail:"",canRetry:!1,canEdit:!1,canUpgrade:!0};const e=t.message||"";return/timed out after/i.test(e)?{kind:"timeout",title:"Request timed out",message:"The generation service took too long to respond.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:/unreachable|failed to fetch|load failed|cors/i.test(e)?{kind:"network",title:"Connection problem",message:"We couldn't reach the generation service. Check your connection and try again.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:{kind:"generic",title:"Generation failed",message:e||"An unexpected error occurred.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1}}function gy(t){const e={"Integration Audit Report":"📋","Critical Issues":"❌",Warnings:"⚠️",Recommendations:"✅","Overall Score":"📊"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📄"}function my(t){const e={critical:"❌",warning:"⚠️",recommendation:"✅",score:"📊",issue:"🔍",fix:"🔧"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📝"}function vy(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 li(t){if(!t)return"";if(typeof t!="string")return String(t);const e=/```(?:\w+)?\n?([\s\S]*?)```/,n=t.match(e);return n?n[1].trim():t.trim()}function Hu(t){return t=Qt(t),t=t.replace(/\*\*(.*?)\*\*/g,'$1'),t=t.replace(/\*(.*?)\*/g,'$1'),t=t.replace(/`(.*?)`/g,'$1'),t=t.replace(/\b(FAIL|ERROR|CRITICAL)\b/g,'$1'),t=t.replace(/\b(WARN|WARNING)\b/g,'$1'),t=t.replace(/\b(PASS|SUCCESS|OK)\b/g,'$1'),t}function bh(t,e="dart",n=globalThis.hljs){if(!t)return"";const i=li(t);try{return n.highlight(i,{language:e}).value}catch(r){console.warn("Syntax highlighting failed:",r);try{return n.highlight(i,{language:"json"}).value}catch{return Qt(i)}}}function Ls(t,e={}){const{highlighter:n=globalThis.hljs}=e;let i='
';const r=String(t??"").split(` +`);let s=!1,o="";for(const a of r){if(a.startsWith("```")){if(s){const l=vy(o),u=bh(o.trim(),l,n);i+=`
${u}
`,o="",s=!1}else s=!0;continue}if(s){o+=a+` `;continue}if(a.startsWith("# ")){const l=a.substring(2).trim();i+=`

- ${my(l)} - ${Xt(l)} + ${gy(l)} + ${Qt(l)}

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

- ${vy(l)} - ${Xt(l)} + ${my(l)} + ${Qt(l)}

`;continue}if(/^[-*+]\s+/.test(a)||/^\d+\.\s+/.test(a)){const l=a.replace(/^([-*+]|\d+\.)\s+/,"").trim();i+=`
• @@ -78,14 +78,14 @@ in vec2 p; void main(){ gl_Position = vec4(p, 0.0, 1.0); }`;function a(){return[
${i}
- `}const yy=[[/gradient stroke\s*$/i," and an animated percentage label"],[/gauge\s*$/i," with a gradient stroke and animated fill"],[/rating\s*(bar|widget)?\s*$/i," with half-star support and haptic feedback"],[/list\s*$/i," with swipe-to-delete and an undo snackbar"],[/pad\s*$/i," that exports a transparent PNG"],[/carousel\s*$/i," with parallax cards and page indicators"],[/(button|cta)\s*$/i," with a loading spinner and success state"],[/(chart|graph)\s*$/i," that animates from a Firestore stream"],[/action\s*(that|to)?\s*$/i," uploads an image to Firebase Storage and returns the URL"],[/timer\s*$/i," with pause, resume and a completion callback"],[/map\s*$/i," with clustered markers and a custom info window"],[/^a\s+\w*$/i," widget that"],[/(picker|selector)\s*$/i," with search and multi-select"]],wy=220,by=6;function Wu(t,e){return!!(t&&t.trim())&&!e}function Ey(t,e=""){if(typeof t!="string"||!t||t===e||t.trim().lengthi.test(t));return n?n[1]:null}function Sy(){let t="",e="";return{get active(){return t},resolve(n){return t=Ey(n,e)??"",t},dismiss(){t=""},accept(n){if(!t)return null;const i=n+t;return e=i,t="",i}}}function xy({onSubmit:t}){const e=document.getElementById("composer"),n=document.getElementById("pipeline-input"),i=document.getElementById("hero-send");if(!e||!n||!i||typeof t!="function")return;const r=e.querySelector(".ghost .typed"),s=e.querySelector(".ghost .suggest"),o=document.getElementById("tab-hint"),a=document.getElementById("suggest-status"),l=Array.from(document.querySelectorAll("#example-chips .chip")),u=document.getElementById("btn-add-images"),c=document.getElementById("prompt-image-input"),d=window.matchMedia("(prefers-reduced-motion: reduce)"),f=Sy();let h=!1,p=!1,g=!1,m=!1,v=null,S=null;function b(){i.disabled=!Wu(n.value,p||g||m)}function _(){r&&(r.textContent=n.value)}function x(){s&&(s.textContent=""),_(),e.classList.remove("has-suggest"),o&&(o.hidden=!0,o.tabIndex=-1),a&&(a.textContent="")}function I(R){s&&(s.textContent=R),_(),e.classList.add("has-suggest"),o&&(o.hidden=!1,o.tabIndex=0,o.setAttribute("aria-label","Accept suggestion: "+R.trim())),a&&(a.textContent="Suggestion: "+R+". Press Tab to accept.")}function T(){f.dismiss(),x()}function E(){if(h||p)return;const R=f.resolve(n.value);R&&I(R)}function P(){clearTimeout(v),!h&&(v=setTimeout(E,wy))}function $(){const R=f.accept(n.value);return R===null?!1:(n.value=R,x(),b(),!0)}function O(R){p=R,e.classList.toggle("is-busy",R),i.classList.toggle("is-busy",R),i.setAttribute("aria-label",R?"Generating":"Generate"),n.readOnly=R,l.forEach(Z=>{Z.disabled=R}),u&&(u.disabled=R),c&&(c.disabled=R),b()}async function L(){if(Wu(n.value,p||g||m)){T(),O(!0);try{await t()}finally{O(!1)}}}function N(){g=!1,S&&(clearInterval(S),S=null),e.classList.remove("is-demo-typing"),b()}function V(){l.forEach(R=>{R.classList.remove("is-active"),R.setAttribute("aria-pressed","false")})}function G(){try{n.focus({preventScroll:!0}),n.setSelectionRange(n.value.length,n.value.length)}catch{}}function M(R){const Z=R.dataset.prompt||"";if(N(),clearTimeout(v),v=null,T(),l.forEach(oe=>{const ye=oe===R;oe.classList.toggle("is-active",ye),oe.setAttribute("aria-pressed",String(ye))}),d.matches||!Z){n.value=Z,_(),b(),G();return}n.value="",_(),g=!0,b(),e.classList.add("is-demo-typing");let Ce=0;S=setInterval(()=>{Ce+=1,n.value=Z.slice(0,Ce),_(),Ce>=Z.length?(N(),G()):b()},22)}return l.forEach(R=>{R.setAttribute("aria-pressed","false"),R.addEventListener("click",()=>M(R))}),n.addEventListener("keydown",R=>{if(g&&R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!h){R.preventDefault();return}N(),R.key==="Tab"&&!R.shiftKey&&f.active?(R.preventDefault(),$()):R.key==="Escape"?(clearTimeout(v),v=null,T()):R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!h&&(R.preventDefault(),L())}),n.addEventListener("input",()=>{N(),V(),T(),b(),P()}),n.addEventListener("compositionstart",()=>{h=!0}),n.addEventListener("compositionend",()=>{h=!1,T(),b(),P()}),n.addEventListener("scroll",()=>{r&&r.parentNode&&(r.parentNode.scrollTop=n.scrollTop)}),o&&o.addEventListener("click",()=>{$(),n.focus({preventScroll:!0})}),i.addEventListener("click",L),n.addEventListener("pointerdown",()=>{N(),V()}),_(),b(),{setAttachmentsPending(R){m=!!R,b()}}}const Iy="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses",ky="phc_KoqpBJCIiWMW5I6HKBM092DVXZbMmE4KkPHqI518pF3",Cy="https://us.i.posthog.com";Kf.init(ky,{api_host:Cy,person_profiles:"identified_only"});function Cn(t,e={}){try{Kf.capture(t,e)}catch(n){console.error("PostHog tracking failed",n)}}const vt="https://4tgke4.buildship.run",Sh={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},fs="ccc_auth_session",Oa="ccc_signin_return",Ay=1800*1e3,qu=new WeakSet;let z={email:null,sessionToken:null,isVerified:!1};function Mn(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let ce=Mn({isResolved:!0}),Ba=Promise.resolve();const Py=`${vt}/service/runpipeline`,Fy="bs_user_id",Ry="bs_identity_token",Ty=`${vt}/authUserCheck`;let ft={userId:null,token:null,status:null,resolved:!1};const hs=av,ps="ccc_subscription",zu=3,$y=new Set(["active","trialing","paid"]),gs="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"],My={"google/gemini-3.7-flash":"Gemini 3.7 Flash","anthropic/claude-opus-5":"Claude Opus 5","openai/gpt-5.6-sol":"GPT-5.6 Sol","z-ai/glm-5.2":"GLM 5.2","moonshotai/kimi-k3":"Kimi K3","openrouter/auto-beta":"OpenRouter: Auto Router","openrouter/free":"OpenRouter: Free Models","openrouter/deepseek/deepseek-v4-pro":"DeepSeek v4 Pro"};function Gt(t){return My[t]||t}const Ly=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 xh(t){return Ly.has(t)}const Da=4,Wo=8*1024*1024,Ny="https://4tgke4.buildship.run/service/runpipeline-image";let Ne=[];const hn=[],Oy=3e4;let Ih=null;function By(t){return new Promise(e=>{const n=new FileReader;n.onload=()=>e(n.result),n.onerror=()=>e(null),n.readAsDataURL(t)})}async function Dy(t,e){const n=new FormData;return n.append("file",t),(await fetch(Ny,{method:"POST",body:n,signal:e})).json()}function jy(t){if(Array.isArray(t)){const e=t[0];if(e&&typeof e=="object")for(const n of Object.keys(e)){if(n==="item"||n==="index")continue;const i=e[n];if(i&&typeof i=="object"){if(typeof i.file=="string")return i.file;if(typeof i.url=="string")return i.url}if(typeof i=="string")return i}return""}return typeof t=="string"?t:t&&typeof t=="object"&&(t.url||t.fileUrl||t.file_url||t.downloadUrl||t.imageUrl||t.image_url||t.file)||""}async function Uy(t,e,n){const i=await By(t);i&&Ne.includes(e)&&(e.dataUrl=i,ln());let r="";if(i)try{r=jy(await Dy(t,n))}catch{r=""}return Ne.includes(e)?!i||!r?(Ne.splice(Ne.indexOf(e),1),ln(),"failed"):(e.url=r,ln(),"added"):"dropped"}function kh(t){const e=hn.indexOf(t);e>=0&&hn.splice(e,1),Ah()}function Ch(t){t.controller.abort(),kh(t);const e=Ne.indexOf(t.slot);e>=0&&(Ne.splice(e,1),ln())}function Ah(){Ih?.setAttachmentsPending(hn.length>0)}async function Hy(t){const e=Array.from(t.target.files||[]);if(!e.length)return;if(t.target.value="",y.isRunning){Ee("Wait for the current generation to finish before attaching images.","info");return}const n=e.filter(u=>u.size>Wo);n.length&&Ee(`Skipped ${n.length} image(s) over the ${(Wo/1024/1024).toFixed(0)} MB limit.`,"warning");const i=e.filter(u=>u.size<=Wo);if(!i.length)return;const r=Da-Ne.length,s=i.slice(0,r);if(i.length>r&&Ee(`You can attach up to ${Da} images.`,"info"),!s.length)return;const o=s.map(u=>{const c={dataUrl:null,name:u.name,url:null};Ne.push(c);const d={slot:c,controller:new AbortController},f=setTimeout(()=>d.controller.abort(),Oy);return d.job=Uy(u,c,d.controller.signal),hn.push(d),d.job.finally(()=>{clearTimeout(f),kh(d)}),d.job});ln(),Ah();const l=(await Promise.all(o)).filter(u=>u==="failed").length;l&&Ee(`${l} image(s) could not be uploaded and were not attached.`,"error")}function Wy(t){const e=Ne[t],n=hn.find(i=>i.slot===e);if(n){Ch(n);return}Ne.splice(t,1),ln()}function ln(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",Ne.forEach((n,i)=>{const r=document.createElement("div");r.className="prompt-img-thumb"+(n.url?"":" is-pending"),r.innerHTML=(n.dataUrl?`Prompt image`:"")+``,t.appendChild(r)}),e&&(e.textContent=Ne.length>=Da?"Image limit reached":"Add images"))}function Cl(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),n=xh(e?.value);t.classList.toggle("hidden",!n),!n&&Ne.length&&(hn.slice().forEach(Ch),Ne=[],ln())}const Fn="ccc_usage",Ph="google/gemini-3.7-flash",Fh="google/gemini-3.7-flash",Ir="google/gemini-3.7-flash",Ni={professional:11,power:49},ja={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"},Nr={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 Or={...Nr};async function qy(){const t=new AbortController,e=setTimeout(()=>t.abort(),5e3);try{const n=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:t.signal});if(!n.ok)return;const i=await n.json();if(i.result!=="success"||!i.rates)return;const r=i.rates,s={AUD:1},o=new Set([...Object.keys(Nr),...Object.values(Ua),...Object.values(ja)]);for(const a of o)a!=="AUD"&&(typeof r[a]=="number"&&r[a]>0?s[a]=r[a]:Nr[a]&&(s[a]=Nr[a]));Or=s}catch{}finally{clearTimeout(e)}}const Ua={"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 Al(){try{const s=Intl.DateTimeFormat().resolvedOptions().timeZone;if(s&&Ua[s])return Ua[s]}catch{}const e=(navigator.language||"en-US").replace("-","_"),n=ja[e];if(n)return n;const i=e.split("_")[0],r=ja[i];return r||"USD"}function Oi(t,e){const n=Or[e]??Or.USD,i=t*n,r=Math.round(i*100)/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:r>=100||r%1===0?0:2}).format(r)}catch{return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(t*Or.USD)}}const pt="ccc_api_key_",At="ccc_session_api_key_",Ft="ccc_encryption_key",tr="ccc_encryption_key_scope",zy="ccc_keystore",ms="keys",nr="ccc_encryption_key_version";let Ha=null,vs=null,ir=!1,_s=!1,Gu=!1;class ys extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function Vu(){if(Gu)return;Gu=!0;const t="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(t),document.body&&Ee(t,"warning")}function Rh(){return localStorage.getItem(nr)||""}function Wa(){return crypto.randomUUID?.()||$h(crypto.getRandomValues(new Uint8Array(16)))}function Gy(){const t=Rh();if(t)return t;const e=Wa();return localStorage.setItem(nr,e),e}function ci(){Ha=null,vs=null,ir=!1,_s=!1}window.addEventListener("storage",t=>{t.key===nr&&ci()});function Vy(){return new Promise((t,e)=>{const n=indexedDB.open(zy,1);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(ms)||i.createObjectStore(ms)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function Pl(t,e){const n=await Vy();return new Promise((i,r)=>{const s=n.transaction(ms,t);let o;try{o=e(s.objectStore(ms))}catch(l){n.close(),r(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>r(o.error),s.oncomplete=()=>{n.close(),i(a)},s.onerror=()=>{n.close(),r(s.error||new Error("Encryption key transaction failed."))},s.onabort=()=>{n.close(),r(s.error||new Error("Encryption key transaction aborted."))}})}function Ky(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function Yy(){const t=await Pl("readonly",e=>e.get(Ft));return Ky(t)?t:null}async function Th(t){await Pl("readwrite",e=>e.put(t,Ft))}async function Jy(){ci();try{await Pl("readwrite",t=>t.delete(Ft))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function Zy(){const t=sessionStorage.getItem(Ft);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Th(e),sessionStorage.removeItem(Ft),sessionStorage.removeItem(tr),localStorage.removeItem(pt+"salt"),e}async function Ku(t){const e=sessionStorage.getItem(Ft);if(e)return _s=sessionStorage.getItem(tr)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new ys;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),i=await crypto.subtle.exportKey("jwk",n);return sessionStorage.setItem(Ft,JSON.stringify(i)),sessionStorage.setItem(tr,"session"),_s=!1,crypto.subtle.importKey("jwk",i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function Xy(t){if(sessionStorage.getItem(tr)==="session"&&sessionStorage.getItem(Ft))return Vu(),ir=!0,Ku(t);try{const e=await Yy();if(e)return e;const n=await Zy();if(n)return n;const i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Th(i),i}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),Vu(),ir=!0,Ku(t)}}async function Fl(t={}){const{allowSessionFallbackCreation:e=!0}=t,n=Gy();vs!==n&&ci();const i=Ha||Xy(e);Ha=i,vs=n;try{return await i}catch(r){throw ci(),r}}async function Qy(t){const e=await Fl(),n=vs,i=new TextEncoder,r=crypto.getRandomValues(new Uint8Array(12)),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},e,i.encode(t)),o=new Uint8Array(r.length+s.byteLength);return o.set(r),o.set(new Uint8Array(s),r.length),{ciphertext:$h(o),keyVersion:n,sessionFallback:ir}}async function e0(t,e={}){const{isSessionCredential:n=!1}=e;try{const i=await Fl({allowSessionFallbackCreation:!1});if(ir&&!n&&!_s)throw new ys;const r=t0(t),s=r.slice(0,12),o=r.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},i,o);return new TextDecoder().decode(a)}catch(i){if(i instanceof ys)throw i;return console.error("Decryption failed:",i),null}}function $h(t){const e=new Uint8Array(t);let n="";for(let i=0;i0}let Ln="",ui="",qi=null,Ju=0,tt="not-configured";async function Rl(){sessionStorage.getItem(Ft)&&await Fl(),Ln=await Te("flutterflow"),ui=await Te("flutterflow_project_id"),c0(),nn(),Ln?Ll():(tt="not-configured",mt())}let rr=!1;function Mh(){const t=document.getElementById("api-keys-modal");He(t),Ml(),Ln&&Nl(Ln)}function Tl(){rr=!1,Mh()}function i0(){rr=!0;const t=document.getElementById("walkthrough-modal");t&&We(t),Mh()}let Zu=!1;function Xu(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-settings-model");if(!t||!e)return;e.value=t.value;const n=Array.from(t.options);Array.from(e.options).forEach((r,s)=>{const o=n[s];o&&(r.textContent=o.textContent)});const i=document.getElementById("composer-settings-free-notice");i&&(document.getElementById("model-selector-free-notice")?(i.hidden=!1,i.innerHTML='Free plan — Gemini only. '):i.hidden=!0)}function Qu(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-image-capability"),n=document.getElementById("composer-image-capability-note");if(!t)return;const i=Gt(t.value),r=xh(t.value);e&&(e.textContent=r?"Supported":"Not supported"),n&&(n.textContent=r?`${i} accepts reference images you attach to the prompt.`:`Images can't be attached with ${i}. Attached images are removed when you switch to it.`),Cl()}function r0(){if(rr=!1,Xu(),Qu(),!Zu){const e=document.getElementById("composer-settings-model");e&&e.addEventListener("change",()=>{const n=document.getElementById("code-generator-model");n.value=e.value,n.dispatchEvent(new Event("change")),Xu(),Qu()}),Zu=!0}const t=document.querySelector('.composer [aria-label="Generation settings"]');He("composer-settings-modal",{trigger:t})}function s0(t){t&&t.target!==t.currentTarget||We("composer-settings-modal")}function Lh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&We(e);const n=rr;if(rr=!1,n){const i=document.getElementById("walkthrough-modal");i&&(tt==="connected"&&$l(),He(i))}}let Qt=1;function Nh(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function Ns(){const t=Nh();t.length&&t.forEach((e,n)=>{const i=n+1;e.classList.remove("wt-current","wt-done","wt-pending");const r=e.querySelector(".wt-step-num");i===Qt?(e.classList.add("wt-current"),r&&(r.textContent=i)):i0&&Qt<=t&&(Qt++,Ns())}function o0(){const t=document.getElementById("walkthrough-modal");t&&(Qt=1,Ns(),He(t))}function a0(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&We(e);const n=document.getElementById("walkthrough-dont-show");n&&n.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function Oh(){if(z.isVerified&&Rt()&&ce.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(Qt=1,Ns(),He(e))}}async function Ml(){const t=document.getElementById("flutterflow-api-key-input");Ln?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",l0()}function l0(){ed("flutterflow","flutterflow-key-status"),ed("flutterflow_project_id","flutterflow-project-status")}function ed(t,e){const n=document.getElementById(e);if(!n)return;const i=n.querySelector(".key-status-dot"),r=n.querySelector("span");kt(t)?(i.className="key-status-dot configured",r.className="text-green-600",r.textContent="User key configured"):(i.className="key-status-dot missing",r.className="text-gray-500",r.textContent="Not configured")}function nn(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff");e&&e.classList.toggle("hidden",!t)}function c0(){const t=document.getElementById("api-keys-status");if(!t)return;const e=t.querySelectorAll(".key-status-dot"),n=["flutterflow"];e.forEach((i,r)=>{const s=n[r];s==="flutterflow"?kt("flutterflow")&&kt("flutterflow_project_id")?(i.className="key-status-dot configured",i.title="FlutterFlow (Fully configured)"):kt("flutterflow")||kt("flutterflow_project_id")?(i.className="key-status-dot env",i.title="FlutterFlow (Partially configured)"):(i.className="key-status-dot missing",i.title="FlutterFlow (Not configured)"):kt(s)?(i.className="key-status-dot configured",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (User key)"):(i.className="key-status-dot missing",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (Not configured)")}),nn()}async function u0(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select"),n=t.value.trim();n&&await Yu("flutterflow",n);const i=e?.value.trim()||"";if(i){if(!Os(i)){Ee("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await Yu("flutterflow_project_id",i)}await Rl(),n&&await Ll(),Ml();const r=document.querySelector("#api-keys-modal .bg-blue-500"),s=r.textContent;r.textContent="Saved!",r.classList.remove("bg-blue-500","hover:bg-blue-600"),r.classList.add("bg-green-500"),setTimeout(()=>{r.textContent=s,r.classList.remove("bg-green-500"),r.classList.add("bg-blue-500","hover:bg-blue-600"),Lh()},1e3)}async function d0(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(nr,Wa()),ci(),localStorage.removeItem(pt+"flutterflow"),localStorage.removeItem(pt+"flutterflow_project_id"),sessionStorage.removeItem(At+"flutterflow"),sessionStorage.removeItem(At+"flutterflow_project_id"),sessionStorage.removeItem(Ft),sessionStorage.removeItem(tr),localStorage.removeItem(pt+"salt"),await Jy(),localStorage.setItem(nr,Wa()),localStorage.removeItem(pt+"flutterflow"),localStorage.removeItem(pt+"flutterflow_project_id"),sessionStorage.removeItem(At+"flutterflow"),sessionStorage.removeItem(At+"flutterflow_project_id"),await Rl();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),Ml()}function Os(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function mt(){const t=document.getElementById("acct-ff-dot"),e=document.getElementById("acct-ff-status"),n=document.getElementById("acct-ff-endpoint"),i=document.getElementById("acct-ff-project");if(n){const o=_t();n.textContent=o.includes("staging")?"Staging":"Production"}if(i&&(i.textContent=ui||"—"),!e)return;let r,s;if(!kt("flutterflow"))r="Not connected — add your FlutterFlow API key",s="";else switch(tt){case"connected":r="Connected to FlutterFlow",s="ok";break;case"no-projects":r="Key accepted — no projects found",s="warn";break;case"unauthorized":r="API key rejected (401/403) — re-enter your key",s="bad";break;case"network-error":r="Could not reach FlutterFlow — check your network",s="bad";break;default:r="Checking connection…",s="warn";break}e.textContent=r,t&&(t.className=`acct-dot${s?" "+s:""}`)}async function Ll(){const t=await Te("flutterflow");if(!t||!kt("flutterflow"))return tt="not-configured",mt(),null;tt="validating",mt();try{const n=await new hi(t,"","main",_t()).listProjects();return tt=n&&n.length>0?"connected":"no-projects",mt(),n}catch(e){const n=String(e&&e.message||"");return tt=/(401|403)|denied|unauthorized|scoped|list permission/i.test(n)?"unauthorized":"network-error",mt(),null}}function f0(){ui="",localStorage.removeItem(pt+"flutterflow_project_id"),sessionStorage.removeItem(At+"flutterflow_project_id")}function h0(){f0();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML='',t.value=""),kt("flutterflow")?(tt="validating",Nl(Ln)):tt="not-configured",mt()}function p0(t,e){const n=document.getElementById(t);n&&(n.value?e?n.style.borderColor="#22c55e":n.style.borderColor="#ef4444":n.style.borderColor="")}function g0(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const n=e.target.value.trim().length>0;p0("flutterflow-api-key-input",n)}),t.addEventListener("blur",m0(async e=>{const n=e.target.value.trim();n&&await Nl(n)},500)))}function m0(t,e){let n;return function(...r){const s=()=>{clearTimeout(n),t(...r)};clearTimeout(n),n=setTimeout(s,e)}}async function Nl(t){const e=document.getElementById("flutterflow-projects-select"),n=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',n&&n.classList.add("hidden"),(kt("flutterflow")||t)&&(tt="validating"),mt();try{const r=await new hi(t,"","main",_t()).listProjects();if(!r||r.length===0){tt="no-projects",mt(),e.innerHTML='';return}tt="connected",mt(),e.innerHTML='',r.forEach(s=>{const o=document.createElement("option");o.value=s.id||s.projectId||"",o.textContent=s.name||s.projectName||`Project ${s.id}`,e.appendChild(o)}),ui&&(e.value=ui)}catch(i){console.error("Failed to fetch projects:",i);const r=String(i&&i.message||"");tt=/(401|403)|denied|unauthorized|scoped|list permission/i.test(r)?"unauthorized":"network-error",mt(),e.innerHTML='',n&&(n.textContent=`Failed to load projects: ${i.message}`,n.classList.remove("hidden"))}}function v0(t){const e=document.getElementById(t),i=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",i.innerHTML=` + `}const _y=[[/gradient stroke\s*$/i," and an animated percentage label"],[/gauge\s*$/i," with a gradient stroke and animated fill"],[/rating\s*(bar|widget)?\s*$/i," with half-star support and haptic feedback"],[/list\s*$/i," with swipe-to-delete and an undo snackbar"],[/pad\s*$/i," that exports a transparent PNG"],[/carousel\s*$/i," with parallax cards and page indicators"],[/(button|cta)\s*$/i," with a loading spinner and success state"],[/(chart|graph)\s*$/i," that animates from a Firestore stream"],[/action\s*(that|to)?\s*$/i," uploads an image to Firebase Storage and returns the URL"],[/timer\s*$/i," with pause, resume and a completion callback"],[/map\s*$/i," with clustered markers and a custom info window"],[/^a\s+\w*$/i," widget that"],[/(picker|selector)\s*$/i," with search and multi-select"]],yy=220,wy=6;function Wu(t,e){return!!(t&&t.trim())&&!e}function by(t,e=""){if(typeof t!="string"||!t||t===e||t.trim().lengthi.test(t));return n?n[1]:null}function Ey(){let t="",e="";return{get active(){return t},resolve(n){return t=by(n,e)??"",t},dismiss(){t=""},accept(n){if(!t)return null;const i=n+t;return e=i,t="",i}}}function Sy({onSubmit:t}){const e=document.getElementById("composer"),n=document.getElementById("pipeline-input"),i=document.getElementById("hero-send");if(!e||!n||!i||typeof t!="function")return;const r=e.querySelector(".ghost .typed"),s=e.querySelector(".ghost .suggest"),o=document.getElementById("tab-hint"),a=document.getElementById("suggest-status"),l=Array.from(document.querySelectorAll("#example-chips .chip")),u=document.getElementById("btn-add-images"),c=document.getElementById("prompt-image-input"),d=window.matchMedia("(prefers-reduced-motion: reduce)"),f=Ey();let h=!1,p=!1,g=!1,m=!1,v=null,S=null;function b(){i.disabled=!Wu(n.value,p||g||m)}function _(){r&&(r.textContent=n.value)}function x(){s&&(s.textContent=""),_(),e.classList.remove("has-suggest"),o&&(o.hidden=!0,o.tabIndex=-1),a&&(a.textContent="")}function I(R){s&&(s.textContent=R),_(),e.classList.add("has-suggest"),o&&(o.hidden=!1,o.tabIndex=0,o.setAttribute("aria-label","Accept suggestion: "+R.trim())),a&&(a.textContent="Suggestion: "+R+". Press Tab to accept.")}function T(){f.dismiss(),x()}function E(){if(h||p)return;const R=f.resolve(n.value);R&&I(R)}function P(){clearTimeout(v),!h&&(v=setTimeout(E,yy))}function $(){const R=f.accept(n.value);return R===null?!1:(n.value=R,x(),b(),!0)}function O(R){p=R,e.classList.toggle("is-busy",R),i.classList.toggle("is-busy",R),i.setAttribute("aria-label",R?"Generating":"Generate"),n.readOnly=R,l.forEach(Z=>{Z.disabled=R}),u&&(u.disabled=R),c&&(c.disabled=R),b()}async function L(){if(Wu(n.value,p||g||m)){T(),O(!0);try{await t()}finally{O(!1)}}}function N(){g=!1,S&&(clearInterval(S),S=null),e.classList.remove("is-demo-typing"),b()}function K(){l.forEach(R=>{R.classList.remove("is-active"),R.setAttribute("aria-pressed","false")})}function V(){try{n.focus({preventScroll:!0}),n.setSelectionRange(n.value.length,n.value.length)}catch{}}function M(R){const Z=R.dataset.prompt||"";if(N(),clearTimeout(v),v=null,T(),l.forEach(oe=>{const ye=oe===R;oe.classList.toggle("is-active",ye),oe.setAttribute("aria-pressed",String(ye))}),d.matches||!Z){n.value=Z,_(),b(),V();return}n.value="",_(),g=!0,b(),e.classList.add("is-demo-typing");let Ce=0;S=setInterval(()=>{Ce+=1,n.value=Z.slice(0,Ce),_(),Ce>=Z.length?(N(),V()):b()},22)}return l.forEach(R=>{R.setAttribute("aria-pressed","false"),R.addEventListener("click",()=>M(R))}),n.addEventListener("keydown",R=>{if(g&&R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!h){R.preventDefault();return}N(),R.key==="Tab"&&!R.shiftKey&&f.active?(R.preventDefault(),$()):R.key==="Escape"?(clearTimeout(v),v=null,T()):R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!h&&(R.preventDefault(),L())}),n.addEventListener("input",()=>{N(),K(),T(),b(),P()}),n.addEventListener("compositionstart",()=>{h=!0}),n.addEventListener("compositionend",()=>{h=!1,T(),b(),P()}),n.addEventListener("scroll",()=>{r&&r.parentNode&&(r.parentNode.scrollTop=n.scrollTop)}),o&&o.addEventListener("click",()=>{$(),n.focus({preventScroll:!0})}),i.addEventListener("click",L),n.addEventListener("pointerdown",()=>{N(),K()}),_(),b(),{setAttachmentsPending(R){m=!!R,b()}}}const xy="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses";const vt="https://4tgke4.buildship.run",Eh={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},hs="ccc_auth_session",Na="ccc_signin_return",Iy=1800*1e3,qu=new WeakSet;let z={email:null,sessionToken:null,isVerified:!1};function Mn(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let ce=Mn({isResolved:!0}),Oa=Promise.resolve();const ky=`${vt}/service/runpipeline`,Cy="bs_user_id",Ay="bs_identity_token",Py=`${vt}/authUserCheck`;let ft={userId:null,token:null,status:null,resolved:!1};const ps=sv,gs="ccc_subscription",zu=3,Fy=new Set(["active","trialing","paid"]),ms="google/gemini-3.7-flash",Nr=["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"],Ry={"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 Vt(t){return Ry[t]||t}const Ty=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 Sh(t){return Ty.has(t)}const Ba=4,Ho=8*1024*1024,$y="https://4tgke4.buildship.run/service/runpipeline-image";let Ne=[];const pn=[],My=3e4;let xh=null;function Ly(t){return new Promise(e=>{const n=new FileReader;n.onload=()=>e(n.result),n.onerror=()=>e(null),n.readAsDataURL(t)})}async function Ny(t,e){const n=new FormData;return n.append("file",t),(await fetch($y,{method:"POST",body:n,signal:e})).json()}function Oy(t){if(Array.isArray(t)){const e=t[0];if(e&&typeof e=="object")for(const n of Object.keys(e)){if(n==="item"||n==="index")continue;const i=e[n];if(i&&typeof i=="object"){if(typeof i.file=="string")return i.file;if(typeof i.url=="string")return i.url}if(typeof i=="string")return i}return""}return typeof t=="string"?t:t&&typeof t=="object"&&(t.url||t.fileUrl||t.file_url||t.downloadUrl||t.imageUrl||t.image_url||t.file)||""}async function By(t,e,n){const i=await Ly(t);i&&Ne.includes(e)&&(e.dataUrl=i,cn());let r="";if(i)try{r=Oy(await Ny(t,n))}catch{r=""}return Ne.includes(e)?!i||!r?(Ne.splice(Ne.indexOf(e),1),cn(),"failed"):(e.url=r,cn(),"added"):"dropped"}function Ih(t){const e=pn.indexOf(t);e>=0&&pn.splice(e,1),Ch()}function kh(t){t.controller.abort(),Ih(t);const e=Ne.indexOf(t.slot);e>=0&&(Ne.splice(e,1),cn())}function Ch(){xh?.setAttachmentsPending(pn.length>0)}async function Dy(t){const e=Array.from(t.target.files||[]);if(!e.length)return;if(t.target.value="",y.isRunning){Ee("Wait for the current generation to finish before attaching images.","info");return}const n=e.filter(u=>u.size>Ho);n.length&&Ee(`Skipped ${n.length} image(s) over the ${(Ho/1024/1024).toFixed(0)} MB limit.`,"warning");const i=e.filter(u=>u.size<=Ho);if(!i.length)return;const r=Ba-Ne.length,s=i.slice(0,r);if(i.length>r&&Ee(`You can attach up to ${Ba} images.`,"info"),!s.length)return;const o=s.map(u=>{const c={dataUrl:null,name:u.name,url:null};Ne.push(c);const d={slot:c,controller:new AbortController},f=setTimeout(()=>d.controller.abort(),My);return d.job=By(u,c,d.controller.signal),pn.push(d),d.job.finally(()=>{clearTimeout(f),Ih(d)}),d.job});cn(),Ch();const l=(await Promise.all(o)).filter(u=>u==="failed").length;l&&Ee(`${l} image(s) could not be uploaded and were not attached.`,"error")}function jy(t){const e=Ne[t],n=pn.find(i=>i.slot===e);if(n){kh(n);return}Ne.splice(t,1),cn()}function cn(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",Ne.forEach((n,i)=>{const r=document.createElement("div");r.className="prompt-img-thumb"+(n.url?"":" is-pending"),r.innerHTML=(n.dataUrl?`Prompt image`:"")+``,t.appendChild(r)}),e&&(e.textContent=Ne.length>=Ba?"Image limit reached":"Add images"))}function kl(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),n=Sh(e?.value);t.classList.toggle("hidden",!n),!n&&Ne.length&&(pn.slice().forEach(kh),Ne=[],cn())}const Fn="ccc_usage",Ah="google/gemini-3.7-flash",Ph="google/gemini-3.7-flash",kr="google/gemini-3.7-flash",Ni={professional:11,power:49},Da={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"},Or={AUD:1,USD:.65,EUR:.6,GBP:.52,CAD:.88,NZD:1.08,JPY:97,KRW:870,INR:54,SGD:.87,HKD:5.08,BRL:3.18,CNY:4.7,TWD:20.5,THB:22.5,VND:16200,IDR:10200,MYR:2.88,SEK:6.8,NOK:6.95,DKK:4.48,PLN:2.6,CZK:15.2,HUF:238,RON:2.98,TRY:20.9,AED:2.39,ILS:2.38,PHP:36.4,ZAR:11.8,RUB:58,UAH:26.8,CHF:.57,MXN:11.1,ARS:580,CLP:610,COP:2700,PEN:2.44};let Br={...Or};async function Uy(){const t=new AbortController,e=setTimeout(()=>t.abort(),5e3);try{const n=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:t.signal});if(!n.ok)return;const i=await n.json();if(i.result!=="success"||!i.rates)return;const r=i.rates,s={AUD:1},o=new Set([...Object.keys(Or),...Object.values(ja),...Object.values(Da)]);for(const a of o)a!=="AUD"&&(typeof r[a]=="number"&&r[a]>0?s[a]=r[a]:Or[a]&&(s[a]=Or[a]));Br=s}catch{}finally{clearTimeout(e)}}const ja={"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 Cl(){try{const s=Intl.DateTimeFormat().resolvedOptions().timeZone;if(s&&ja[s])return ja[s]}catch{}const e=(navigator.language||"en-US").replace("-","_"),n=Da[e];if(n)return n;const i=e.split("_")[0],r=Da[i];return r||"USD"}function Oi(t,e){const n=Br[e]??Br.USD,i=t*n,r=Math.round(i*100)/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:r>=100||r%1===0?0:2}).format(r)}catch{return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(t*Br.USD)}}const pt="ccc_api_key_",At="ccc_session_api_key_",Ft="ccc_encryption_key",tr="ccc_encryption_key_scope",Hy="ccc_keystore",vs="keys",nr="ccc_encryption_key_version";let Ua=null,_s=null,ir=!1,ys=!1,Vu=!1;class ws extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function Gu(){if(Vu)return;Vu=!0;const t="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(t),document.body&&Ee(t,"warning")}function Fh(){return localStorage.getItem(nr)||""}function Ha(){return crypto.randomUUID?.()||Th(crypto.getRandomValues(new Uint8Array(16)))}function Wy(){const t=Fh();if(t)return t;const e=Ha();return localStorage.setItem(nr,e),e}function ci(){Ua=null,_s=null,ir=!1,ys=!1}window.addEventListener("storage",t=>{t.key===nr&&ci()});function qy(){return new Promise((t,e)=>{const n=indexedDB.open(Hy,1);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(vs)||i.createObjectStore(vs)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function Al(t,e){const n=await qy();return new Promise((i,r)=>{const s=n.transaction(vs,t);let o;try{o=e(s.objectStore(vs))}catch(l){n.close(),r(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>r(o.error),s.oncomplete=()=>{n.close(),i(a)},s.onerror=()=>{n.close(),r(s.error||new Error("Encryption key transaction failed."))},s.onabort=()=>{n.close(),r(s.error||new Error("Encryption key transaction aborted."))}})}function zy(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function Vy(){const t=await Al("readonly",e=>e.get(Ft));return zy(t)?t:null}async function Rh(t){await Al("readwrite",e=>e.put(t,Ft))}async function Gy(){ci();try{await Al("readwrite",t=>t.delete(Ft))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function Ky(){const t=sessionStorage.getItem(Ft);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Rh(e),sessionStorage.removeItem(Ft),sessionStorage.removeItem(tr),localStorage.removeItem(pt+"salt"),e}async function Ku(t){const e=sessionStorage.getItem(Ft);if(e)return ys=sessionStorage.getItem(tr)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new ws;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),i=await crypto.subtle.exportKey("jwk",n);return sessionStorage.setItem(Ft,JSON.stringify(i)),sessionStorage.setItem(tr,"session"),ys=!1,crypto.subtle.importKey("jwk",i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function Yy(t){if(sessionStorage.getItem(tr)==="session"&&sessionStorage.getItem(Ft))return Gu(),ir=!0,Ku(t);try{const e=await Vy();if(e)return e;const n=await Ky();if(n)return n;const i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Rh(i),i}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),Gu(),ir=!0,Ku(t)}}async function Pl(t={}){const{allowSessionFallbackCreation:e=!0}=t,n=Wy();_s!==n&&ci();const i=Ua||Yy(e);Ua=i,_s=n;try{return await i}catch(r){throw ci(),r}}async function Jy(t){const e=await Pl(),n=_s,i=new TextEncoder,r=crypto.getRandomValues(new Uint8Array(12)),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},e,i.encode(t)),o=new Uint8Array(r.length+s.byteLength);return o.set(r),o.set(new Uint8Array(s),r.length),{ciphertext:Th(o),keyVersion:n,sessionFallback:ir}}async function Zy(t,e={}){const{isSessionCredential:n=!1}=e;try{const i=await Pl({allowSessionFallbackCreation:!1});if(ir&&!n&&!ys)throw new ws;const r=Xy(t),s=r.slice(0,12),o=r.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},i,o);return new TextDecoder().decode(a)}catch(i){if(i instanceof ws)throw i;return console.error("Decryption failed:",i),null}}function Th(t){const e=new Uint8Array(t);let n="";for(let i=0;i0}let Ln="",ui="",qi=null,Ju=0,tt="not-configured";async function Fl(){sessionStorage.getItem(Ft)&&await Pl(),Ln=await Te("flutterflow"),ui=await Te("flutterflow_project_id"),o0(),rn(),Ln?Ml():(tt="not-configured",mt())}let rr=!1;function $h(){const t=document.getElementById("api-keys-modal");He(t),$l(),Ln&&Ll(Ln)}function Rl(){rr=!1,$h()}function e0(){rr=!0;const t=document.getElementById("walkthrough-modal");t&&We(t),$h()}let Zu=!1;function Xu(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-settings-model");if(!t||!e)return;e.value=t.value;const n=Array.from(t.options);Array.from(e.options).forEach((r,s)=>{const o=n[s];o&&(r.textContent=o.textContent)});const i=document.getElementById("composer-settings-free-notice");i&&(document.getElementById("model-selector-free-notice")?(i.hidden=!1,i.innerHTML='Free plan — Gemini only. '):i.hidden=!0)}function Qu(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-image-capability"),n=document.getElementById("composer-image-capability-note");if(!t)return;const i=Vt(t.value),r=Sh(t.value);e&&(e.textContent=r?"Supported":"Not supported"),n&&(n.textContent=r?`${i} accepts reference images you attach to the prompt.`:`Images can't be attached with ${i}. Attached images are removed when you switch to it.`),kl()}function t0(){if(rr=!1,Xu(),Qu(),!Zu){const e=document.getElementById("composer-settings-model");e&&e.addEventListener("change",()=>{const n=document.getElementById("code-generator-model");n.value=e.value,n.dispatchEvent(new Event("change")),Xu(),Qu()}),Zu=!0}const t=document.querySelector('.composer [aria-label="Generation settings"]');He("composer-settings-modal",{trigger:t})}function n0(t){t&&t.target!==t.currentTarget||We("composer-settings-modal")}function Mh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&We(e);const n=rr;if(rr=!1,n){const i=document.getElementById("walkthrough-modal");i&&(tt==="connected"&&Tl(),He(i))}}let en=1;function Lh(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function Ns(){const t=Lh();t.length&&t.forEach((e,n)=>{const i=n+1;e.classList.remove("wt-current","wt-done","wt-pending");const r=e.querySelector(".wt-step-num");i===en?(e.classList.add("wt-current"),r&&(r.textContent=i)):i0&&en<=t&&(en++,Ns())}function i0(){const t=document.getElementById("walkthrough-modal");t&&(en=1,Ns(),He(t))}function r0(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&We(e);const n=document.getElementById("walkthrough-dont-show");n&&n.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function Nh(){if(z.isVerified&&Rt()&&ce.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(en=1,Ns(),He(e))}}async function $l(){const t=document.getElementById("flutterflow-api-key-input");Ln?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",s0()}function s0(){ed("flutterflow","flutterflow-key-status"),ed("flutterflow_project_id","flutterflow-project-status")}function ed(t,e){const n=document.getElementById(e);if(!n)return;const i=n.querySelector(".key-status-dot"),r=n.querySelector("span");kt(t)?(i.className="key-status-dot configured",r.className="text-green-600",r.textContent="User key configured"):(i.className="key-status-dot missing",r.className="text-gray-500",r.textContent="Not configured")}function rn(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff");e&&e.classList.toggle("hidden",!t)}function o0(){const t=document.getElementById("api-keys-status");if(!t)return;const e=t.querySelectorAll(".key-status-dot"),n=["flutterflow"];e.forEach((i,r)=>{const s=n[r];s==="flutterflow"?kt("flutterflow")&&kt("flutterflow_project_id")?(i.className="key-status-dot configured",i.title="FlutterFlow (Fully configured)"):kt("flutterflow")||kt("flutterflow_project_id")?(i.className="key-status-dot env",i.title="FlutterFlow (Partially configured)"):(i.className="key-status-dot missing",i.title="FlutterFlow (Not configured)"):kt(s)?(i.className="key-status-dot configured",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (User key)"):(i.className="key-status-dot missing",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (Not configured)")}),rn()}async function a0(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select"),n=t.value.trim();n&&await Yu("flutterflow",n);const i=e?.value.trim()||"";if(i){if(!Os(i)){Ee("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await Yu("flutterflow_project_id",i)}await Fl(),n&&await Ml(),$l();const r=document.querySelector("#api-keys-modal .bg-blue-500"),s=r.textContent;r.textContent="Saved!",r.classList.remove("bg-blue-500","hover:bg-blue-600"),r.classList.add("bg-green-500"),setTimeout(()=>{r.textContent=s,r.classList.remove("bg-green-500"),r.classList.add("bg-blue-500","hover:bg-blue-600"),Mh()},1e3)}async function l0(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(nr,Ha()),ci(),localStorage.removeItem(pt+"flutterflow"),localStorage.removeItem(pt+"flutterflow_project_id"),sessionStorage.removeItem(At+"flutterflow"),sessionStorage.removeItem(At+"flutterflow_project_id"),sessionStorage.removeItem(Ft),sessionStorage.removeItem(tr),localStorage.removeItem(pt+"salt"),await Gy(),localStorage.setItem(nr,Ha()),localStorage.removeItem(pt+"flutterflow"),localStorage.removeItem(pt+"flutterflow_project_id"),sessionStorage.removeItem(At+"flutterflow"),sessionStorage.removeItem(At+"flutterflow_project_id"),await Fl();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),$l()}function Os(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function mt(){const t=document.getElementById("acct-ff-dot"),e=document.getElementById("acct-ff-status"),n=document.getElementById("acct-ff-endpoint"),i=document.getElementById("acct-ff-project");if(n){const o=_t();n.textContent=o.includes("staging")?"Staging":"Production"}if(i&&(i.textContent=ui||"—"),!e)return;let r,s;if(!kt("flutterflow"))r="Not connected — add your FlutterFlow API key",s="";else switch(tt){case"connected":r="Connected to FlutterFlow",s="ok";break;case"no-projects":r="Key accepted — no projects found",s="warn";break;case"unauthorized":r="API key rejected (401/403) — re-enter your key",s="bad";break;case"network-error":r="Could not reach FlutterFlow — check your network",s="bad";break;default:r="Checking connection…",s="warn";break}e.textContent=r,t&&(t.className=`acct-dot${s?" "+s:""}`)}async function Ml(){const t=await Te("flutterflow");if(!t||!kt("flutterflow"))return tt="not-configured",mt(),null;tt="validating",mt();try{const n=await new hi(t,"","main",_t()).listProjects();return tt=n&&n.length>0?"connected":"no-projects",mt(),n}catch(e){const n=String(e&&e.message||"");return tt=/(401|403)|denied|unauthorized|scoped|list permission/i.test(n)?"unauthorized":"network-error",mt(),null}}function c0(){ui="",localStorage.removeItem(pt+"flutterflow_project_id"),sessionStorage.removeItem(At+"flutterflow_project_id")}function u0(){c0();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML='',t.value=""),kt("flutterflow")?(tt="validating",Ll(Ln)):tt="not-configured",mt()}function d0(t,e){const n=document.getElementById(t);n&&(n.value?e?n.style.borderColor="#22c55e":n.style.borderColor="#ef4444":n.style.borderColor="")}function f0(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const n=e.target.value.trim().length>0;d0("flutterflow-api-key-input",n)}),t.addEventListener("blur",h0(async e=>{const n=e.target.value.trim();n&&await Ll(n)},500)))}function h0(t,e){let n;return function(...r){const s=()=>{clearTimeout(n),t(...r)};clearTimeout(n),n=setTimeout(s,e)}}async function Ll(t){const e=document.getElementById("flutterflow-projects-select"),n=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',n&&n.classList.add("hidden"),(kt("flutterflow")||t)&&(tt="validating"),mt();try{const r=await new hi(t,"","main",_t()).listProjects();if(!r||r.length===0){tt="no-projects",mt(),e.innerHTML='';return}tt="connected",mt(),e.innerHTML='',r.forEach(s=>{const o=document.createElement("option");o.value=s.id||s.projectId||"",o.textContent=s.name||s.projectName||`Project ${s.id}`,e.appendChild(o)}),ui&&(e.value=ui)}catch(i){console.error("Failed to fetch projects:",i);const r=String(i&&i.message||"");tt=/(401|403)|denied|unauthorized|scoped|list permission/i.test(r)?"unauthorized":"network-error",mt(),e.innerHTML='',n&&(n.textContent=`Failed to load projects: ${i.message}`,n.classList.remove("hidden"))}}function p0(t){const e=document.getElementById(t),i=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",i.innerHTML=` `):(e.type="password",i.innerHTML=` - `)}let y={step1Result:null,step2Result:null,step3Result:null,bundleSpec:null,artifactBundle:null,bundleReview:null,selectedArtifactId:null,resultsViewMode:"summary",currentStep:0,isRunning:!1,runId:0,submittedPrompt:"",submittedImages:[]};function _0(){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 y0(){y.bundleSpec=Qi(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function Bs(){const t=oi(y.bundleSpec);y.artifactBundle=Qi(y.step2Result,{id:y.bundleSpec?.id,title:y.bundleSpec?.title,description:y.bundleSpec?.description,artifactType:t.artifactType,artifactName:t.artifactName,fileName:t.fileName,dependencies:t.dependencies,relationships:y.bundleSpec?.relationships,code:y.step2Result||""});const e=Hv(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(n=>n.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=oi(y.artifactBundle).id}function Ds(){const t=Qi(y.step3Result,{id:y.artifactBundle?.id,title:y.artifactBundle?.title}),e=new Map(t.artifacts.map(i=>[i.id,i.review])),n=new Map(t.artifacts.filter(i=>{const r=i.review;return r&&typeof r.fixedSource=="string"&&r.fixedSource.trim()}).map(i=>[i.id,i.review.fixedSource.trim()]));y.bundleReview=Qi({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(i=>{const r=n.get(i.id)||null;return{...i,review:e.get(i.id)||i.review||y.step3Result||null,...r?{fixedCode:r}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function Bh(){const t=Ol();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function Ol(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(n=>n.id===y.selectedArtifactId)||oi(t)}function Bl(){return Ol().code||y.step2Result||""}async function w0(){try{await Rl()}catch(t){return console.error("checkConnection: initializeApiKeys failed:",t),!1}return!0}const Br={production:"https://api.flutterflow.io/v2/",staging:"https://api.flutterflow.io/v2-staging/"};function b0(t,e){const n=e?.trim()?` (${e.trim().slice(0,200)})`:"";return t===401?`Your FlutterFlow API key was rejected (401 Unauthorized)${n}. Re-enter a current key under API Keys settings, then try again.`:`Listing FlutterFlow projects was denied (403)${n}. The key may be scoped to sync a single project without list permission - verify the key's access in FlutterFlow, re-enter it under API Keys settings, then retry.`}class hi{constructor(e,n,i="main",r=Br.production){this.apiKey=e,this.baseUrl=r,this._projectId=n,this._branchName=i,this._endpoint=r}get projectId(){return this._projectId}get branchName(){return this._branchName==="main"?"":this._branchName}async exportProjectZip(){console.log(`Exporting code from FlutterFlow project: ${this.projectId}, branch: ${this.branchName||"main"}`);const e=[{project:{path:`projects/${this.projectId}`},...this.branchName?{branch_name:this.branchName}:{},export_as_module:!1,include_assets_map:!1,format:!1,export_as_debug:!1},{project_id:this.projectId,branch_name:this.branchName,include_assets:!1,export_as_module:!1}];let n=null;for(const i of e)try{const r=await fetch(`${this.baseUrl}exportCode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(i)});if(!r.ok){const a=await r.text();n=new Error(`Export failed: ${r.status} - ${a}`);continue}const s=await r.json(),o=s?.value?.project_zip||s?.project_zip;if(!o){n=new Error("Export response did not include project source.");continue}return o}catch(r){n=r}throw n||new Error("Export failed for an unknown reason.")}async fetchProjectSource(){const e=await this.exportProjectZip(),n=await JSZip.loadAsync(e,{base64:!0}),i=Object.keys(n.files).filter(a=>!n.files[a].dir&&(a==="pubspec.yaml"||a.endsWith("/pubspec.yaml"))).sort((a,l)=>a.split("/").length-l.split("/").length)[0];if(!i)throw new Error("Export did not contain a pubspec.yaml.");const r=i.slice(0,i.length-12),s=new Map,o=Object.keys(n.files).filter(a=>{if(n.files[a].dir||!a.startsWith(r))return!1;const l=a.slice(r.length);return l==="lib/flutter_flow/custom_functions.dart"||l.startsWith("lib/custom_code/")&&l.endsWith(".dart")});return await Promise.all(o.map(async a=>{s.set(a.slice(r.length),await n.files[a].async("string"))})),{pubspecYaml:await n.files[i].async("string"),files:s}}async pushCodeWithRetry(e,n=3){const i=[Br.production,Br.staging],r=Math.max(0,i.indexOf(this._endpoint));for(let s=0;ssetTimeout(d,1e3*(s+1)));continue}return l}catch(l){console.warn(`Push to ${a} failed: ${l.message}, trying next...`),await new Promise(u=>setTimeout(u,1e3*(s+1)))}}throw new Error("All API endpoints failed after retries")}async pushCode(e){return this.pushCodeWithRetry(e)}parseProjectsResponse(e){if(e?.success&&typeof e.value=="string")try{const i=JSON.parse(e.value);if(i&&Array.isArray(i.entries))return i.entries.map(r=>({id:r.id,name:r.project?.name||r.id}))}catch(i){console.error("Failed to parse stringified project value:",i)}const n=e?.projects||e?.items||e?.entries||(Array.isArray(e)?e:[]);return Array.isArray(n)?n:[]}async listProjects(){console.log("Listing projects for API key");const e=[`${this.baseUrl}listProjects`,"https://api.flutterflow.io/v2/l/listProjects"];let n=0,i="";for(const r of e){const s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({project_type:"ALL",deserialize_response:!0})});if(s.ok)return r!==e[0]&&console.log(`listProjects answered on legacy path ${r}`),this.parseProjectsResponse(await s.json());if(n=s.status,i=await s.text(),console.warn(`listProjects via ${r} returned ${n}: ${i}`),s.status===401||s.status===403)throw new Error(b0(s.status,i));if(s.status!==404)throw new Error(`List projects failed: ${s.status} - ${i}`)}throw new Error(`List projects failed: ${n} - ${i}`)}}async function Dl(t){const e=t.clone();let n;try{n=await t.json()}catch{const s=await e.text();if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:s||`HTTP ${t.status}`,errorMap:new Map};throw new Error(`Invalid JSON response: ${s}`)}if(!t.ok){let r=n.message||`HTTP ${t.status}`,s=new Map;if(n.errors)s=new Map(Object.entries(n.errors));else if(!n.message&&typeof n=="object"){const o=Object.keys(n).filter(a=>a.endsWith(".dart")&&Array.isArray(n[a]));o.length>0&&(s=new Map(Object.entries(n)),r=o.flatMap(l=>n[l].map(u=>`${l}: ${u.errorMessage}`)).join(` -`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:r,errorMap:s}}let i={};if(n.value)try{i=typeof n.value=="string"?JSON.parse(n.value):n.value}catch(r){console.warn("Ignoring malformed push response value:",r)}return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(i))}}function jl(t,e){return{401:"Authentication failed. Please check your FlutterFlow API key.",403:"Access denied. You may not have permission to modify this project.",404:"Project not found. Please check your Project ID.",409:"Conflict detected. The project may have been modified elsewhere.",422:"Validation failed: Invalid request format",429:"Rate limit exceeded. Please try again in a few minutes.",500:"FlutterFlow server error. Please try again later.",503:"FlutterFlow service temporarily unavailable."}[t]||`FlutterFlow API error: ${`HTTP ${t}`}`}const J={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},Dh=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,jh=/extends\s+State<\w+>/;function E0(t,e=""){if(t==="pubspec.yaml")return J.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return J.OTHER;if(t==="custom_functions.dart")return J.FUNCTION;if(e){const n=Dh.test(e),i=jh.test(e);if(n||i)return J.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return J.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return J.FUNCTION}return J.CODE_FILE}function Uh(t,e){switch(e){case J.ACTION:return`lib/custom_code/actions/${t}`;case J.WIDGET:return`lib/custom_code/widgets/${t}`;case J.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case J.CODE_FILE:return`lib/custom_code/${t}`;case J.DEPENDENCIES:return"pubspec.yaml";case J.OTHER:return`lib/custom_code/${t}`;default:return t}}async function Ul(t,e=new Map){return xv(t,e)}const qa=new Map;function Hh(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function js(t){qa.delete(Hh(t))}class ws extends Error{constructor(e){super(e),this.name="UnconfirmedDeployError",this.outcome=Xe.UNCONFIRMED}}function S0(t,e,n){return new Promise((i,r)=>{let s=!1;const o=(l,u,c)=>{s||(s=!0,c==="resolve"?i(u):r(u))},a=setTimeout(()=>{s||(s=!0,n(i,r))},e);t.then(l=>{clearTimeout(a),o(i,l,"resolve")},l=>{clearTimeout(a),o(r,l,"reject")})})}async function Hl(t,e,n,i,r=""){const s=n_(e,n);if(s.length===0)return{remoteFiles:n,syncFileMap:e,unverified:[],approximate:[]};const o=K_(s,r),a={...o.manifest,sources:o.sources},l=o.skipped.map(f=>f.reason);l.forEach(f=>console.warn(`[custom class deploy] ${f}`));const u=o.approximate;u.forEach(f=>console.warn(`[custom class deploy] ${f}`)),console.log(`Provisioning ${s.length} new FlutterFlow custom code file(s) before sync.`),Oe.set("provision");const c=await fetch(Iy,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:i,customClasses:s,verification:a,stream:!0})}),d=await S0(Z_(c,{onPhase:f=>Oe.setSubstatus(f),onLog:f=>console.log(`[custom class deploy] ${f}`)}),J_,(f,h)=>h(new ws("The deploy is still working on the FlutterFlow server, but this browser tab has stopped waiting. Your custom classes may or may not have been written — the outcome is not yet known. Open your FlutterFlow project to reconcile before retrying the deploy.")));if(!d.finalResultReceived)throw X_(d)===Xe.FAILED?new Error(d.error||`FlutterFlow custom class provisioning failed (HTTP ${d.httpStatus}).`):new ws("The connection to the FlutterFlow deploy runner dropped before it reported a result. The deploy may still be finishing on the server; open your FlutterFlow project to reconcile before retrying.");if(!d.success){const f=d.details?` ${d.details}`:"";throw new Error(`${d.error||"FlutterFlow custom class provisioning failed."}${f}`)}return js(t),d.verificationSkipped&&(console.warn(`[custom class deploy] ${d.verificationSkipped}`),l.push(d.verificationSkipped)),{remoteFiles:n,syncFileMap:i_(e,s),unverified:l,approximate:u,provisionSucceeded:!0}}async function Wl(t,e={}){const n=Hh(t);let i=qa.get(n);if(i===void 0){try{i=await t.fetchProjectSource()}catch(l){throw new Error(`Could not read your project's pubspec.yaml (${l.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=vh(i.pubspecYaml);if(!a.valid)throw new Error(`Your project's pubspec.yaml could not be read reliably (${a.errors.join("; ")}). Deploy was stopped so your existing package dependencies aren't overwritten.`);qa.set(n,i)}const r=await py(i.pubspecYaml,e),s=W_(i.pubspecYaml,r.overrides),o=H_(s.yaml,r.additions);return r.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>`${a}: ${r.additions[a]||"any"}`).join(", "),r.sdk.dartSdkFloor?`(resolved for Dart ${r.sdk.dartSdkFloor})`:""),r.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:s.overridden,warnings:r.warnings,remoteFiles:i.files}}function x0(t){const e=[],n=[];t.content.length>5e4&&n.push("Code file is large (>50KB). This may take longer to commit."),t.content.length>1e5&&e.push("Code file is too large (>100KB). Consider splitting into smaller components.");const i=t.content.split(` -`).length;i>500&&n.push(`Code has ${i} lines. Consider breaking it into smaller widgets.`),t.content.includes("setState")&&t.codeType===J.ACTION&&n.push("Using setState in a Custom Action may not work as expected. Consider using a Custom Widget."),t.content.includes("dynamic")&&!t.content.includes("?")&&n.push('Code uses "dynamic" types. Consider adding explicit types for better null safety.'),t.content.match(/Color\(0xFF[0-9A-Fa-f]{6}\)/)&&n.push("Code contains hardcoded colors. Consider using FlutterFlowTheme.of(context) for theme consistency.");const r=t.content.match(/print\s*\(/g);r&&r.length>3&&n.push(`Code contains ${r.length} print statements. Consider removing debug prints before committing.`);const s=b_(t.content);if(s&&e.push(`FlutterFlow cannot format this code - ${s}. Fix or regenerate before committing.`),t.codeType===J.WIDGET){const o=lh(t.content),a=__(t.fileName);if(o.length===0)e.push("No public widget class found (must extend StatelessWidget or StatefulWidget).");else if(!o.includes(a)){const l=`${ch(o[0])}`;e.push(`Widget class name "${o[0]}" does not match the file name "${t.fileName}". FlutterFlow derives the widget from the file name, so it will report "No widget ${a} found". Rename the file to "${l}" or the class to match before committing.`)}}return{canProceed:e.length===0,issues:e,warnings:n}}function Wh(t,e={}){const{artifactType:n="CustomWidget",artifactName:i="GeneratedCode",fileName:r}=e,s=m_(t);let o=r||i;if(n==="CustomFunction")o="custom_functions.dart";else if(n==="CustomWidget"){const u=lh(s)[0],c=u?ch(u):null;c&&o!==c?(console.warn(`Commit file name "${o}" does not match declared widget class "${u}"; renaming to "${c}" so FlutterFlow can find the widget.`),o=c):o.endsWith(".dart")||(o+=".dart")}else o.endsWith(".dart")||(o+=".dart");let a=J.CODE_FILE;switch(n){case"CustomAction":a=J.ACTION;break;case"CustomWidget":a=J.WIDGET;break;case"CustomFunction":a=J.FUNCTION;break;case"CustomClass":case"CodeFile":a=J.CODE_FILE;break}let l="";return a===J.WIDGET?l=`// Automatic FlutterFlow imports + `)}let y={step1Result:null,step2Result:null,step3Result:null,bundleSpec:null,artifactBundle:null,bundleReview:null,selectedArtifactId:null,resultsViewMode:"summary",currentStep:0,isRunning:!1,runId:0,submittedPrompt:"",submittedImages:[]};function g0(){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 m0(){y.bundleSpec=Qi(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function Bs(){const t=oi(y.bundleSpec);y.artifactBundle=Qi(y.step2Result,{id:y.bundleSpec?.id,title:y.bundleSpec?.title,description:y.bundleSpec?.description,artifactType:t.artifactType,artifactName:t.artifactName,fileName:t.fileName,dependencies:t.dependencies,relationships:y.bundleSpec?.relationships,code:y.step2Result||""});const e=jv(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(n=>n.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=oi(y.artifactBundle).id}function Ds(){const t=Qi(y.step3Result,{id:y.artifactBundle?.id,title:y.artifactBundle?.title}),e=new Map(t.artifacts.map(i=>[i.id,i.review])),n=new Map(t.artifacts.filter(i=>{const r=i.review;return r&&typeof r.fixedSource=="string"&&r.fixedSource.trim()}).map(i=>[i.id,i.review.fixedSource.trim()]));y.bundleReview=Qi({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(i=>{const r=n.get(i.id)||null;return{...i,review:e.get(i.id)||i.review||y.step3Result||null,...r?{fixedCode:r}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function Oh(){const t=Nl();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function Nl(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(n=>n.id===y.selectedArtifactId)||oi(t)}function Ol(){return Nl().code||y.step2Result||""}async function v0(){try{await Fl()}catch(t){return console.error("checkConnection: initializeApiKeys failed:",t),!1}return!0}const Dr={production:"https://api.flutterflow.io/v2/",staging:"https://api.flutterflow.io/v2-staging/"};function _0(t,e){const n=e?.trim()?` (${e.trim().slice(0,200)})`:"";return t===401?`Your FlutterFlow API key was rejected (401 Unauthorized)${n}. Re-enter a current key under API Keys settings, then try again.`:`Listing FlutterFlow projects was denied (403)${n}. The key may be scoped to sync a single project without list permission - verify the key's access in FlutterFlow, re-enter it under API Keys settings, then retry.`}class hi{constructor(e,n,i="main",r=Dr.production){this.apiKey=e,this.baseUrl=r,this._projectId=n,this._branchName=i,this._endpoint=r}get projectId(){return this._projectId}get branchName(){return this._branchName==="main"?"":this._branchName}async exportProjectZip(){console.log(`Exporting code from FlutterFlow project: ${this.projectId}, branch: ${this.branchName||"main"}`);const e=[{project:{path:`projects/${this.projectId}`},...this.branchName?{branch_name:this.branchName}:{},export_as_module:!1,include_assets_map:!1,format:!1,export_as_debug:!1},{project_id:this.projectId,branch_name:this.branchName,include_assets:!1,export_as_module:!1}];let n=null;for(const i of e)try{const r=await fetch(`${this.baseUrl}exportCode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(i)});if(!r.ok){const a=await r.text();n=new Error(`Export failed: ${r.status} - ${a}`);continue}const s=await r.json(),o=s?.value?.project_zip||s?.project_zip;if(!o){n=new Error("Export response did not include project source.");continue}return o}catch(r){n=r}throw n||new Error("Export failed for an unknown reason.")}async fetchProjectSource(){const e=await this.exportProjectZip(),n=await JSZip.loadAsync(e,{base64:!0}),i=Object.keys(n.files).filter(a=>!n.files[a].dir&&(a==="pubspec.yaml"||a.endsWith("/pubspec.yaml"))).sort((a,l)=>a.split("/").length-l.split("/").length)[0];if(!i)throw new Error("Export did not contain a pubspec.yaml.");const r=i.slice(0,i.length-12),s=new Map,o=Object.keys(n.files).filter(a=>{if(n.files[a].dir||!a.startsWith(r))return!1;const l=a.slice(r.length);return l==="lib/flutter_flow/custom_functions.dart"||l.startsWith("lib/custom_code/")&&l.endsWith(".dart")});return await Promise.all(o.map(async a=>{s.set(a.slice(r.length),await n.files[a].async("string"))})),{pubspecYaml:await n.files[i].async("string"),files:s}}async pushCodeWithRetry(e,n=3){const i=[Dr.production,Dr.staging],r=Math.max(0,i.indexOf(this._endpoint));let s=!1,o=null;for(let a=0;asetTimeout(h,1e3*(a+1)));continue}if(c.ok)return console.log(`Push to ${u} succeeded!`),c;o=c.status;let d;try{d=await c.clone().text()}catch{d="(unreadable response body)"}if(console.log(`Push to ${u} returned ${c.status}: ${d}`),c.status===500){console.warn(`Endpoint ${u} returned 500, trying next...`),await new Promise(f=>setTimeout(f,1e3*(a+1)));continue}return c}throw Y_({sawTransportError:s,httpStatus:o})}async pushCode(e){return this.pushCodeWithRetry(e)}parseProjectsResponse(e){if(e?.success&&typeof e.value=="string")try{const i=JSON.parse(e.value);if(i&&Array.isArray(i.entries))return i.entries.map(r=>({id:r.id,name:r.project?.name||r.id}))}catch(i){console.error("Failed to parse stringified project value:",i)}const n=e?.projects||e?.items||e?.entries||(Array.isArray(e)?e:[]);return Array.isArray(n)?n:[]}async listProjects(){console.log("Listing projects for API key");const e=[`${this.baseUrl}listProjects`,"https://api.flutterflow.io/v2/l/listProjects"];let n=0,i="";for(const r of e){const s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({project_type:"ALL",deserialize_response:!0})});if(s.ok)return r!==e[0]&&console.log(`listProjects answered on legacy path ${r}`),this.parseProjectsResponse(await s.json());if(n=s.status,i=await s.text(),console.warn(`listProjects via ${r} returned ${n}: ${i}`),s.status===401||s.status===403)throw new Error(_0(s.status,i));if(s.status!==404)throw new Error(`List projects failed: ${s.status} - ${i}`)}throw new Error(`List projects failed: ${n} - ${i}`)}}async function Bl(t){const e=t.clone();let n;try{n=await t.json()}catch{let s="";try{s=await e.text()}catch{}if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:s||`HTTP ${t.status}`,errorMap:new Map};throw new Yt(`FlutterFlow accepted the sync but returned an unreadable response${s?`: ${s.slice(0,200)}`:"."}`)}if(!t.ok){let r=n.message||`HTTP ${t.status}`,s=new Map;if(n.errors)s=new Map(Object.entries(n.errors));else if(!n.message&&typeof n=="object"){const o=Object.keys(n).filter(a=>a.endsWith(".dart")&&Array.isArray(n[a]));o.length>0&&(s=new Map(Object.entries(n)),r=o.flatMap(l=>n[l].map(u=>`${l}: ${u.errorMessage}`)).join(` +`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:r,errorMap:s}}let i={};if(n.value)try{i=typeof n.value=="string"?JSON.parse(n.value):n.value}catch(r){console.warn("Ignoring malformed push response value:",r)}return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(i))}}function Dl(t,e){return{401:"Authentication failed. Please check your FlutterFlow API key.",403:"Access denied. You may not have permission to modify this project.",404:"Project not found. Please check your Project ID.",409:"Conflict detected. The project may have been modified elsewhere.",422:"Validation failed: Invalid request format",429:"Rate limit exceeded. Please try again in a few minutes.",500:"FlutterFlow server error. Please try again later.",503:"FlutterFlow service temporarily unavailable."}[t]||`FlutterFlow API error: ${`HTTP ${t}`}`}const J={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},Bh=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,Dh=/extends\s+State<\w+>/;function y0(t,e=""){if(t==="pubspec.yaml")return J.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return J.OTHER;if(t==="custom_functions.dart")return J.FUNCTION;if(e){const n=Bh.test(e),i=Dh.test(e);if(n||i)return J.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return J.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return J.FUNCTION}return J.CODE_FILE}function jh(t,e){switch(e){case J.ACTION:return`lib/custom_code/actions/${t}`;case J.WIDGET:return`lib/custom_code/widgets/${t}`;case J.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case J.CODE_FILE:return`lib/custom_code/${t}`;case J.DEPENDENCIES:return"pubspec.yaml";case J.OTHER:return`lib/custom_code/${t}`;default:return t}}async function jl(t,e=new Map){return Ev(t,e)}const Wa=new Map;function Uh(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function sr(t){Wa.delete(Uh(t))}function w0(t,e,n){return new Promise((i,r)=>{let s=!1;const o=(l,u,c)=>{s||(s=!0,c==="resolve"?i(u):r(u))},a=setTimeout(()=>{s||(s=!0,n(i,r))},e);t.then(l=>{clearTimeout(a),o(i,l,"resolve")},l=>{clearTimeout(a),o(r,l,"reject")})})}async function Ul(t,e,n,i,r="",s=K_){const o=e_(e,n);if(o.length===0)return{remoteFiles:n,syncFileMap:e,unverified:[],approximate:[]};const a=V_(o,r),l={...a.manifest,sources:a.sources},u=a.skipped.map(h=>h.reason);u.forEach(h=>console.warn(`[custom class deploy] ${h}`));const c=a.approximate;c.forEach(h=>console.warn(`[custom class deploy] ${h}`)),console.log(`Provisioning ${o.length} new FlutterFlow custom code file(s) before sync.`),Oe.set("provision");let d=!0,f;try{if(f=await w0((async()=>{let h;try{h=await fetch(xy,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:i,customClasses:o,verification:l,stream:!0})})}catch{throw new Yt("The provisioning request did not return a response. The deploy may have reached the FlutterFlow server — open your FlutterFlow project to reconcile before retrying.")}return J_(h,{onPhase:p=>{d&&Oe.setSubstatus(p)},onLog:p=>{d&&console.log(`[custom class deploy] ${p}`)}})})(),s,(h,p)=>{d=!1,p(new Yt("The deploy is still working on the FlutterFlow server, but this browser tab has stopped waiting. Your custom classes may or may not have been written — the outcome is not yet known. Open your FlutterFlow project to reconcile before retrying the deploy."))}),!f.finalResultReceived)throw Z_(f)===Xe.FAILED?new Error(f.error||`FlutterFlow custom class provisioning failed (HTTP ${f.httpStatus}).`):new Yt("The connection to the FlutterFlow deploy runner dropped before it reported a result. The deploy may still be finishing on the server; open your FlutterFlow project to reconcile before retrying.")}catch(h){throw h instanceof Yt&&sr(t),h}if(!f.success){const h=f.details?` ${f.details}`:"";throw new Error(`${f.error||"FlutterFlow custom class provisioning failed."}${h}`)}return sr(t),f.verificationSkipped&&(console.warn(`[custom class deploy] ${f.verificationSkipped}`),u.push(f.verificationSkipped)),{remoteFiles:n,syncFileMap:t_(e,o),unverified:u,approximate:c,provisionSucceeded:!0}}async function Hl(t,e={}){const n=Uh(t);let i=Wa.get(n);if(i===void 0){try{i=await t.fetchProjectSource()}catch(l){throw new Error(`Could not read your project's pubspec.yaml (${l.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=mh(i.pubspecYaml);if(!a.valid)throw new Error(`Your project's pubspec.yaml could not be read reliably (${a.errors.join("; ")}). Deploy was stopped so your existing package dependencies aren't overwritten.`);Wa.set(n,i)}const r=await hy(i.pubspecYaml,e),s=U_(i.pubspecYaml,r.overrides),o=j_(s.yaml,r.additions);return r.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>`${a}: ${r.additions[a]||"any"}`).join(", "),r.sdk.dartSdkFloor?`(resolved for Dart ${r.sdk.dartSdkFloor})`:""),r.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:s.overridden,warnings:r.warnings,remoteFiles:i.files}}function b0(t){const e=[],n=[];t.content.length>5e4&&n.push("Code file is large (>50KB). This may take longer to commit."),t.content.length>1e5&&e.push("Code file is too large (>100KB). Consider splitting into smaller components.");const i=t.content.split(` +`).length;i>500&&n.push(`Code has ${i} lines. Consider breaking it into smaller widgets.`),t.content.includes("setState")&&t.codeType===J.ACTION&&n.push("Using setState in a Custom Action may not work as expected. Consider using a Custom Widget."),t.content.includes("dynamic")&&!t.content.includes("?")&&n.push('Code uses "dynamic" types. Consider adding explicit types for better null safety.'),t.content.match(/Color\(0xFF[0-9A-Fa-f]{6}\)/)&&n.push("Code contains hardcoded colors. Consider using FlutterFlowTheme.of(context) for theme consistency.");const r=t.content.match(/print\s*\(/g);r&&r.length>3&&n.push(`Code contains ${r.length} print statements. Consider removing debug prints before committing.`);const s=y_(t.content);if(s&&e.push(`FlutterFlow cannot format this code - ${s}. Fix or regenerate before committing.`),t.codeType===J.WIDGET){const o=ah(t.content),a=m_(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=`${lh(o[0])}`;e.push(`Widget class name "${o[0]}" does not match the file name "${t.fileName}". FlutterFlow derives the widget from the file name, so it will report "No widget ${a} found". Rename the file to "${l}" or the class to match before committing.`)}}return{canProceed:e.length===0,issues:e,warnings:n}}function Hh(t,e={}){const{artifactType:n="CustomWidget",artifactName:i="GeneratedCode",fileName:r}=e,s=p_(t);let o=r||i;if(n==="CustomFunction")o="custom_functions.dart";else if(n==="CustomWidget"){const u=ah(s)[0],c=u?lh(u):null;c&&o!==c?(console.warn(`Commit file name "${o}" does not match declared widget class "${u}"; renaming to "${c}" so FlutterFlow can find the widget.`),o=c):o.endsWith(".dart")||(o+=".dart")}else o.endsWith(".dart")||(o+=".dart");let a=J.CODE_FILE;switch(n){case"CustomAction":a=J.ACTION;break;case"CustomWidget":a=J.WIDGET;break;case"CustomFunction":a=J.FUNCTION;break;case"CustomClass":case"CodeFile":a=J.CODE_FILE;break}let l="";return a===J.WIDGET?l=`// Automatic FlutterFlow imports import '/flutter_flow/flutter_flow_theme.dart'; import '/flutter_flow/flutter_flow_util.dart'; import 'package:flutter/material.dart'; @@ -111,15 +111,15 @@ import '/flutter_flow/lat_lng.dart'; import '/flutter_flow/place.dart'; import '/flutter_flow/uploaded_file.dart'; -`),{content:zv(s,l),fileName:o,codeType:a,artifactType:n,artifactName:i}}function I0(t){const e={};for(const n of bl(t))e[n]="";return e}function k0(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 C0(t,e,n,i=new Set,r=""){const s=[],o=Dh.test(e),a=jh.test(e);return n===J.WIDGET&&!o&&!a&&s.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:s.length===0,errors:s}}function Us(t){const e=[],n=[];if(!t||t.size===0)return e.push("No files to commit"),{valid:!1,errors:e,warnings:n};const i=new Set(Array.from(t.values()).flatMap(r=>As(r.content||"")));for(const[r,s]of t.entries()){if((!s.content||s.content.trim().length===0)&&e.push(`File ${r} is empty`),s.content&&s.content.length>1e5&&n.push(`File ${r} is very large (>100KB)`),r.endsWith(".dart")){const o=C0(r,s.content,s.type,i,s.artifactName);o.valid||e.push(...o.errors.map(a=>`${r}: ${a}`))}if(r==="pubspec.yaml"){const o=vh(s.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:n}}const ee={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},Y={currentState:ee.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=ee.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(ee).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===ee.PREPARING&&(this.startTime=Date.now()),(t===ee.SUCCESS||t===ee.ERROR)&&(this.endTime=Date.now()),typeof window<"u"&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("commitStateChange",{detail:{state:t,commitState:this}})),console.log(`Commit state changed to: ${t}`)},setError(t){this.error=t,this.setState(ee.ERROR)},setSuccess(t){this.result=t,this.setState(ee.SUCCESS)},setProgress(t,e){this.filesProcessed=t,this.totalFiles=e},getElapsedTime(){return this.startTime?(this.endTime||Date.now())-this.startTime:null},isInProgress(){return this.currentState===ee.PREPARING||this.currentState===ee.VALIDATING||this.currentState===ee.PUSHING}};async function A0(t,e,n={}){let{codeType:i="W"}=n;const{pubspecDeps:r={},artifactName:s=e}=n;i==="CustomWidget"&&(i=J.WIDGET),i==="CustomAction"&&(i=J.ACTION),i==="CustomFunction"&&(i=J.FUNCTION),i==="CustomClass"&&(i=J.CODE_FILE),i==="CodeFile"&&(i=J.CODE_FILE),Y.reset(),Y.setState(ee.PREPARING);try{const o=await Te("flutterflow"),a=await Te("flutterflow_project_id");if(!o||!a)throw new Error("FlutterFlow credentials not configured. Please set your API key and Project ID in the API Keys settings.");if(!Os(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=_t(),u=new hi(o,a,"main",l);Y.setState(ee.VALIDATING);const c=new Map,d=i||E0(e,t),f=Uh(e,d);c.set(e,{artifactName:s,content:t,type:d,path:f}),Y.setProgress(0,c.size);const h=Us(c);if(!h.valid)throw new Error(`Validation failed: +`),{content:Wv(s,l),fileName:o,codeType:a,artifactType:n,artifactName:i}}function E0(t){const e={};for(const n of wl(t))e[n]="";return e}function S0(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 x0(t,e,n,i=new Set,r=""){const s=[],o=Bh.test(e),a=Dh.test(e);return n===J.WIDGET&&!o&&!a&&s.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:s.length===0,errors:s}}function js(t){const e=[],n=[];if(!t||t.size===0)return e.push("No files to commit"),{valid:!1,errors:e,warnings:n};const i=new Set(Array.from(t.values()).flatMap(r=>As(r.content||"")));for(const[r,s]of t.entries()){if((!s.content||s.content.trim().length===0)&&e.push(`File ${r} is empty`),s.content&&s.content.length>1e5&&n.push(`File ${r} is very large (>100KB)`),r.endsWith(".dart")){const o=x0(r,s.content,s.type,i,s.artifactName);o.valid||e.push(...o.errors.map(a=>`${r}: ${a}`))}if(r==="pubspec.yaml"){const o=mh(s.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:n}}const ee={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},G={currentState:ee.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=ee.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(ee).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===ee.PREPARING&&(this.startTime=Date.now()),(t===ee.SUCCESS||t===ee.ERROR)&&(this.endTime=Date.now()),typeof window<"u"&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("commitStateChange",{detail:{state:t,commitState:this}})),console.log(`Commit state changed to: ${t}`)},setError(t){this.error=t,this.setState(ee.ERROR)},setSuccess(t){this.result=t,this.setState(ee.SUCCESS)},setProgress(t,e){this.filesProcessed=t,this.totalFiles=e},getElapsedTime(){return this.startTime?(this.endTime||Date.now())-this.startTime:null},isInProgress(){return this.currentState===ee.PREPARING||this.currentState===ee.VALIDATING||this.currentState===ee.PUSHING}};async function I0(t,e,n={}){let{codeType:i="W"}=n;const{pubspecDeps:r={},artifactName:s=e}=n;i==="CustomWidget"&&(i=J.WIDGET),i==="CustomAction"&&(i=J.ACTION),i==="CustomFunction"&&(i=J.FUNCTION),i==="CustomClass"&&(i=J.CODE_FILE),i==="CodeFile"&&(i=J.CODE_FILE),G.reset(),G.setState(ee.PREPARING);try{const o=await Te("flutterflow"),a=await Te("flutterflow_project_id");if(!o||!a)throw new Error("FlutterFlow credentials not configured. Please set your API key and Project ID in the API Keys settings.");if(!Os(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=_t(),u=new hi(o,a,"main",l);G.setState(ee.VALIDATING);const c=new Map,d=i||y0(e,t),f=jh(e,d);c.set(e,{artifactName:s,content:t,type:d,path:f}),G.setProgress(0,c.size);const h=js(c);if(!h.valid)throw new Error(`Validation failed: ${h.errors.join(` -`)}`);const p=await Wl(u,r),g=p.yaml,m=await Hl(u,c,p.remoteFiles,`Provision ${s} custom class`,g),v=await Ul(m.syncFileMap,m.remoteFiles),S=new Map(m.syncFileMap);S.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),Oe.set("package");const b=await ql(S),_={project_id:a,zipped_custom_code:b,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};Y.setState(ee.PUSHING),Y.setProgress(1,c.size),js(u),Oe.set("push");const x=await u.pushCode(_),I=await Dl(x);if(I.success)Y.setSuccess({fileCount:c.size,projectId:a,warnings:I.errorMap&&I.errorMap.size>0?Array.from(I.errorMap.entries()):[]});else{const T=I.errorMessage||jl(I.responseCode);throw new Error(T)}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:p.added,unverified:m.unverified,approximate:m.approximate,warnings:I.errorMap?Array.from(I.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),Y.setError(o),{success:!1,error:o.message,state:Y.currentState}}}async function ql(t){const e=new JSZip;for(const[n,i]of t.entries())e.file(n,i.content);return e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}async function P0(t,e={}){const{artifactType:n,artifactName:i,fileName:r,pipelineResult:s}=e;console.log(`Starting commit for ${i} (${n})`);let o=!1;const a={projectId:null,endpoint:_t(),artifactType:n,artifactName:i,fileName:r};try{Y.setState(ee.PREPARING);const l=Wh(t,{artifactType:n,artifactName:i,fileName:r}),u=I0(l.content);console.log("Detected dependencies:",u),Y.setState(ee.VALIDATING);const c=await Te("flutterflow"),d=qi||await Te("flutterflow_project_id");if(!c)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!d)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Os(d))throw new Error("Invalid FlutterFlow Project ID format.");const f=new Map;f.set(l.fileName,{artifactName:i,content:l.content,type:l.codeType,path:Uh(l.fileName,l.codeType),functionName:l.codeType===J.FUNCTION?i:void 0}),Y.setProgress(0,f.size);const h=Us(f);if(!h.valid)throw new Error(`File validation failed: +`)}`);const p=await Hl(u,r),g=p.yaml,m=await Ul(u,c,p.remoteFiles,`Provision ${s} custom class`,g),v=await jl(m.syncFileMap,m.remoteFiles),S=new Map(m.syncFileMap);S.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),Oe.set("package");const b=await Wl(S),_={project_id:a,zipped_custom_code:b,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};G.setState(ee.PUSHING),G.setProgress(1,c.size),sr(u),Oe.set("push");const x=await u.pushCode(_),I=await Bl(x);if(I.success)G.setSuccess({fileCount:c.size,projectId:a,warnings:I.errorMap&&I.errorMap.size>0?Array.from(I.errorMap.entries()):[]});else{const T=I.errorMessage||Dl(I.responseCode);throw new Error(T)}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:p.added,unverified:m.unverified,approximate:m.approximate,warnings:I.errorMap?Array.from(I.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),G.setError(o),o instanceof Yt?{success:!1,unconfirmed:!0,error:o.message,state:G.currentState}:{success:!1,error:o.message,state:G.currentState}}}async function Wl(t){const e=new JSZip;for(const[n,i]of t.entries())e.file(n,i.content);return e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}async function k0(t,e={}){const{artifactType:n,artifactName:i,fileName:r,pipelineResult:s}=e;console.log(`Starting commit for ${i} (${n})`);let o=!1;const a={projectId:null,endpoint:_t(),artifactType:n,artifactName:i,fileName:r};try{G.setState(ee.PREPARING);const l=Hh(t,{artifactType:n,artifactName:i,fileName:r}),u=E0(l.content);console.log("Detected dependencies:",u),G.setState(ee.VALIDATING);const c=await Te("flutterflow"),d=qi||await Te("flutterflow_project_id");if(!c)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!d)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Os(d))throw new Error("Invalid FlutterFlow Project ID format.");a.projectId=d;const f=new Map;f.set(l.fileName,{artifactName:i,content:l.content,type:l.codeType,path:jh(l.fileName,l.codeType),functionName:l.codeType===J.FUNCTION?i:void 0}),G.setProgress(0,f.size);const h=js(f);if(!h.valid)throw new Error(`File validation failed: ${h.errors.join(` -`)}`);h.warnings.length>0&&console.warn("Validation warnings:",h.warnings),Y.setState(ee.PUSHING);const p=_t(),g=new hi(c,d,"main",p),m=await Wl(g,u),v=m.yaml,S=await Hl(g,f,m.remoteFiles,`Provision ${i} custom class`,v);a.projectId=d,o=S.provisionSucceeded===!0;const b=await Ul(S.syncFileMap,S.remoteFiles),_=new Map(S.syncFileMap);_.set("pubspec.yaml",{content:v,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Oe.set("package");const x=await ql(_),I={project_id:d,zipped_custom_code:x,uid:`web_${Date.now()}`,branch_name:g.branchName,serialized_yaml:v,file_map:b.fileMapContents,functions_map:b.functionsMapContents};Y.setProgress(1,f.size),js(g),Oe.set("push");const T=await g.pushCode(I),E=await Dl(T);if(E.success){const P={...k0(l,s),projectId:d};return Y.setSuccess({...P,fileCount:f.size,warnings:E.errorMap?Array.from(E.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${l.fileName} to FlutterFlow`,metadata:P,targetIdentity:a,addedDependencies:m.added,unverified:S.unverified,approximate:S.approximate,warnings:E.errorMap?Array.from(E.errorMap.entries()):[],elapsedTime:Y.getElapsedTime()}}else{const P=E.errorMessage||jl(E.responseCode),$=new Error(P);throw $.errorMap=E.errorMap,$}}catch(l){console.error("Commit execution failed:",l),Y.setError(l);let u=new Map;if(l.errorMap)u=l.errorMap;else if(l.message&&l.message.includes("{"))try{const c=l.message.match(/\{[\s\S]*\}/);if(c){const d=JSON.parse(c[0]);u=new Map(Object.entries(d))}}catch(c){console.warn("Failed to parse error map from commit response:",c)}return l instanceof ws?{success:!1,unconfirmed:!0,error:l.message,errorMap:u,targetIdentity:a,state:Y.currentState,elapsedTime:Y.getElapsedTime()}:o?{success:!1,partial:!0,error:l.message,errorMap:u,targetIdentity:a,state:Y.currentState,elapsedTime:Y.getElapsedTime()}:{success:!1,error:l.message,errorMap:u,targetIdentity:a,state:Y.currentState,elapsedTime:Y.getElapsedTime()}}}async function F0(t,e={}){const{pipelineResult:n}=e;let i=!1;const r={projectId:null,endpoint:_t(),artifactType:"Bundle",artifactName:t?.title,fileName:t?.fileEntries?`${t.fileEntries.length} artifacts`:"bundle"};try{if(Y.setState(ee.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: +`)}`);h.warnings.length>0&&console.warn("Validation warnings:",h.warnings),G.setState(ee.PUSHING);const p=_t(),g=new hi(c,d,"main",p),m=await Hl(g,u),v=m.yaml,S=await Ul(g,f,m.remoteFiles,`Provision ${i} custom class`,v);o=S.provisionSucceeded===!0;const b=await jl(S.syncFileMap,S.remoteFiles),_=new Map(S.syncFileMap);_.set("pubspec.yaml",{content:v,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Oe.set("package");const x=await Wl(_),I={project_id:d,zipped_custom_code:x,uid:`web_${Date.now()}`,branch_name:g.branchName,serialized_yaml:v,file_map:b.fileMapContents,functions_map:b.functionsMapContents};G.setProgress(1,f.size),sr(g),Oe.set("push");const T=await g.pushCode(I),E=await Bl(T);if(E.success){const P={...S0(l,s),projectId:d};return G.setSuccess({...P,fileCount:f.size,warnings:E.errorMap?Array.from(E.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${l.fileName} to FlutterFlow`,metadata:P,targetIdentity:a,addedDependencies:m.added,unverified:S.unverified,approximate:S.approximate,warnings:E.errorMap?Array.from(E.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}else{const P=E.errorMessage||Dl(E.responseCode),$=new Error(P);throw $.errorMap=E.errorMap,$}}catch(l){console.error("Commit execution failed:",l),G.setError(l);let u=new Map;if(l.errorMap)u=l.errorMap;else if(l.message&&l.message.includes("{"))try{const c=l.message.match(/\{[\s\S]*\}/);if(c){const d=JSON.parse(c[0]);u=new Map(Object.entries(d))}}catch(c){console.warn("Failed to parse error map from commit response:",c)}return l instanceof Yt?{success:!1,unconfirmed:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:o?{success:!1,partial:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function C0(t,e={}){const{pipelineResult:n}=e;let i=!1;const r={projectId:null,endpoint:_t(),artifactType:"Bundle",artifactName:t?.title,fileName:t?.fileEntries?`${t.fileEntries.length} artifacts`:"bundle"};try{if(G.setState(ee.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: ${t.errors.join(` -`)}`);const s=new Map(t.fileEntries.map(I=>[I.fileName,{artifactId:I.artifactId,artifactName:I.artifactName,content:I.content,type:I.type,path:I.path,functionName:I.type===J.FUNCTION?I.artifactName:void 0}]));Y.setProgress(0,s.size);const o=Us(s);if(!o.valid)throw new Error(`File validation failed: +`)}`);const s=new Map(t.fileEntries.map(I=>[I.fileName,{artifactId:I.artifactId,artifactName:I.artifactName,content:I.content,type:I.type,path:I.path,functionName:I.type===J.FUNCTION?I.artifactName:void 0}]));G.setProgress(0,s.size);const o=js(s);if(!o.valid)throw new Error(`File validation failed: ${o.errors.join(` -`)}`);Y.setState(ee.VALIDATING);const a=await Te("flutterflow"),l=qi||await Te("flutterflow_project_id");if(!a)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!l)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Os(l))throw new Error("Invalid FlutterFlow Project ID format.");Y.setState(ee.PUSHING);const u=_t(),c=new hi(a,l,"main",u),d=await Wl(c,t.dependencies),f=d.yaml,h=await Hl(c,s,d.remoteFiles,`Provision ${t.title} custom classes`,f);r.projectId=l,i=h.provisionSucceeded===!0;const p=await Ul(h.syncFileMap,h.remoteFiles),g=new Map(h.syncFileMap);g.set("pubspec.yaml",{content:f,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Oe.set("package");const m=await ql(g),v={project_id:l,zipped_custom_code:m,uid:`web_${Date.now()}`,branch_name:c.branchName,serialized_yaml:f,file_map:p.fileMapContents,functions_map:p.functionsMapContents};Y.setProgress(1,s.size),js(c),Oe.set("push");const S=await c.pushCode(v),b=await Dl(S);if(b.success){const I={...n,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((T,E)=>T+E.content.length,0),projectId:l};return Y.setSuccess({...I,fileCount:s.size,warnings:b.errorMap?Array.from(b.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:I,targetIdentity:r,addedDependencies:d.added,unverified:h.unverified,approximate:h.approximate,warnings:b.errorMap?Array.from(b.errorMap.entries()):[],elapsedTime:Y.getElapsedTime()}}const _=b.errorMessage||jl(b.responseCode),x=new Error(_);throw x.errorMap=b.errorMap,x}catch(s){console.error("Bundle commit execution failed:",s),Y.setError(s);const o=s.errorMap||new Map;return s instanceof ws?{success:!1,unconfirmed:!0,error:s.message,errorMap:o,targetIdentity:r,state:Y.currentState,elapsedTime:Y.getElapsedTime()}:i?{success:!1,partial:!0,error:s.message,errorMap:o,targetIdentity:r,state:Y.currentState,elapsedTime:Y.getElapsedTime()}:{success:!1,error:s.message,errorMap:o,targetIdentity:r,state:Y.currentState,elapsedTime:Y.getElapsedTime()}}}async function R0(t,e=[]){const n=vl("architect");try{return await Ss("architect",Ph,fv(t),n,e)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Prompt Architect failed: ${i.message}`)}}async function Hs(t,e,n=[],i){const r=hv(t),s=vl("generator",y.bundleSpec);try{return await Ss("generator",e,r,s,n)}catch(o){if(o.isModelArmor||o.isUsageLimit||o.isPipelineCancel)throw o;if(e!==Ir){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,o.message),Nw(e,Ir,i);try{return await Ss("generator",Ir,r,s,n)}catch(a){throw a.isModelArmor||a.isUsageLimit||a.isPipelineCancel?a:new Error(`Code Generator failed: primary (${e}): ${o.message} | fallback (${Ir}): ${a.message}`)}}throw new Error(`Code Generator failed: ${o.message}`)}}async function Ws(t,e=null){const n={...vl("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await Ss("review",Fh,pv(t),n)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Code Review failed: ${i.message}`)}}function bs(t,e){const n=document.getElementById(`step${t}-item`),i=document.getElementById(`step${t}-status`);!n||!i||(n.classList.remove("active","completed","error"),i.classList.remove("running","completed","error"),e==="active"?(n.classList.add("active"),i.classList.add("running"),i.innerHTML=` +`)}`);G.setState(ee.VALIDATING);const a=await Te("flutterflow"),l=qi||await Te("flutterflow_project_id");if(!a)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!l)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Os(l))throw new Error("Invalid FlutterFlow Project ID format.");r.projectId=l,G.setState(ee.PUSHING);const u=_t(),c=new hi(a,l,"main",u),d=await Hl(c,t.dependencies),f=d.yaml,h=await Ul(c,s,d.remoteFiles,`Provision ${t.title} custom classes`,f);i=h.provisionSucceeded===!0;const p=await jl(h.syncFileMap,h.remoteFiles),g=new Map(h.syncFileMap);g.set("pubspec.yaml",{content:f,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Oe.set("package");const m=await Wl(g),v={project_id:l,zipped_custom_code:m,uid:`web_${Date.now()}`,branch_name:c.branchName,serialized_yaml:f,file_map:p.fileMapContents,functions_map:p.functionsMapContents};G.setProgress(1,s.size),sr(c),Oe.set("push");const S=await c.pushCode(v),b=await Bl(S);if(b.success){const I={...n,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((T,E)=>T+E.content.length,0),projectId:l};return G.setSuccess({...I,fileCount:s.size,warnings:b.errorMap?Array.from(b.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:I,targetIdentity:r,addedDependencies:d.added,unverified:h.unverified,approximate:h.approximate,warnings:b.errorMap?Array.from(b.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}const _=b.errorMessage||Dl(b.responseCode),x=new Error(_);throw x.errorMap=b.errorMap,x}catch(s){console.error("Bundle commit execution failed:",s),G.setError(s);const o=s.errorMap||new Map;return s instanceof Yt?{success:!1,unconfirmed:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:i?{success:!1,partial:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function A0(t,e=[]){const n=ml("architect");try{return await Ss("architect",Ah,uv(t),n,e)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Prompt Architect failed: ${i.message}`)}}async function Us(t,e,n=[],i){const r=dv(t),s=ml("generator",y.bundleSpec);try{return await Ss("generator",e,r,s,n)}catch(o){if(o.isModelArmor||o.isUsageLimit||o.isPipelineCancel)throw o;if(e!==kr){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,o.message),$w(e,kr,i);try{return await Ss("generator",kr,r,s,n)}catch(a){throw a.isModelArmor||a.isUsageLimit||a.isPipelineCancel?a:new Error(`Code Generator failed: primary (${e}): ${o.message} | fallback (${kr}): ${a.message}`)}}throw new Error(`Code Generator failed: ${o.message}`)}}async function Hs(t,e=null){const n={...ml("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await Ss("review",Ph,fv(t),n)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Code Review failed: ${i.message}`)}}function bs(t,e){const n=document.getElementById(`step${t}-item`),i=document.getElementById(`step${t}-status`);!n||!i||(n.classList.remove("active","completed","error"),i.classList.remove("running","completed","error"),e==="active"?(n.classList.add("active"),i.classList.add("running"),i.innerHTML=` `):e==="completed"?(n.classList.add("completed"),i.classList.add("completed"),i.innerHTML=` @@ -127,12 +127,12 @@ ${o.errors.join(` `):i.innerHTML=` - `)}function Ae(t,e){const n=document.getElementById(`step${t}-loading`),i=document.getElementById(`step${t}-result`);e?(n.classList.remove("hidden"),i.classList.add("hidden"),bs(t,"active")):(n.classList.add("hidden"),i.classList.remove("hidden"),bs(t,"completed"))}function T0(t){const e=document.getElementById(`${t}-content`),n=document.getElementById(`${t}-chevron`);e.classList.contains("open")?(e.classList.remove("open"),n&&(n.style.transform="rotate(0deg)")):(e.classList.add("open"),n&&(n.style.transform="rotate(180deg)"))}function $0(t){nt(parseInt(t.replace("step","")))}function nt(t){for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-item`);a&&a.classList.remove("active")}const e=document.getElementById(`step${t}-item`);e&&e.classList.add("active"),Nn();const n=document.getElementById("ready-state");n&&n.classList.add("hidden");for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-content`);a&&a.classList.add("hidden")}const i=document.getElementById(`step${t}-content`);i&&i.classList.remove("hidden");const r=document.getElementById("stage-title"),s={1:"Prompt Architect",2:"Code Generator",3:"Code Review"};r&&(r.textContent=s[t]||"Active Workflow Stage")}function M0(t){const e=document.getElementById(t);if(!e)return;const n=e.dataset.raw||e.textContent;navigator.clipboard.writeText(n).then(()=>{Cn("Code Copied",{elementId:t});const r=e.closest(".code-container")?.querySelector(".copy-btn");r&&(r.classList.add("copied"),r.innerHTML=' Copied!',setTimeout(()=>{r.classList.remove("copied"),r.innerHTML=' Copy'},2e3))}).catch(i=>{console.warn("Failed to copy to clipboard:",i)})}function za(t){const e=Ga(t);console.log(`Step 1 (Prompt Architect): ${Gt(Ph)}`),console.log(e!==t?`Step 2 (Code Generator): ${Gt(t)} → ${Gt(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${Gt(t)}`),console.log(`Step 3 (Code Review): ${Gt(Fh)}`)}function qh(){return{step1Result:y.step1Result,step2Result:y.step2Result,step3Result:y.step3Result,artifactBundle:y.artifactBundle,bundleReview:y.bundleReview,selectedArtifactId:y.selectedArtifactId}}function L0(t){if(!t)return;Object.assign(y,t),new Set((y.artifactBundle?.artifacts||[]).map(n=>n.id)).has(y.selectedArtifactId)||(y.selectedArtifactId=oi(y.artifactBundle)?.id||null)}const zh="results-replacement-error";function N0(t,{stage:e=2,runId:n,retry:i}){if(!re(n))return;const r=document.getElementById(zh);if(!r)return;const s=bh(t),o=document.getElementById("results-replacement-error-title"),a=document.getElementById("results-replacement-error-message"),l=document.getElementById("results-replacement-error-retry"),u=document.getElementById("results-replacement-error-upgrade");o&&(o.textContent=`${Vs[e]||"Regeneration"}: ${s.title}`),a&&(a.textContent=s.message),r.hidden=!1;let c=null;u&&(u.hidden=!s.canUpgrade,s.canUpgrade&&(u.textContent="View plans",u.onclick=()=>di(),c=u)),l&&(l.hidden=s.canUpgrade,s.canUpgrade||(l.onclick=()=>{zl(),typeof i=="function"&&i()},l.textContent="Retry",c=l)),(c||r).focus({preventScroll:!0})}function zl(){const t=document.getElementById(zh);t&&(t.hidden=!0)}function Gh(t,{previous:e,stage:n,runId:i,retry:r}){re(i)&&(t.isUsageLimit&&cn(),L0(e),lr(),tn(!0),cr(),to(),N0(t,{stage:n,runId:i,retry:r}),nn())}async function Vh(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0;const e=Ks();Gl("standardRegenerate",y.step2Result,y.step1Result);const n=document.querySelectorAll(".btn-refine-action"),i=qh();n.forEach(r=>{r.disabled=!0,r.innerHTML=` + `)}function Ae(t,e){const n=document.getElementById(`step${t}-loading`),i=document.getElementById(`step${t}-result`);e?(n.classList.remove("hidden"),i.classList.add("hidden"),bs(t,"active")):(n.classList.add("hidden"),i.classList.remove("hidden"),bs(t,"completed"))}function P0(t){const e=document.getElementById(`${t}-content`),n=document.getElementById(`${t}-chevron`);e.classList.contains("open")?(e.classList.remove("open"),n&&(n.style.transform="rotate(0deg)")):(e.classList.add("open"),n&&(n.style.transform="rotate(180deg)"))}function F0(t){nt(parseInt(t.replace("step","")))}function nt(t){for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-item`);a&&a.classList.remove("active")}const e=document.getElementById(`step${t}-item`);e&&e.classList.add("active"),Nn();const n=document.getElementById("ready-state");n&&n.classList.add("hidden");for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-content`);a&&a.classList.add("hidden")}const i=document.getElementById(`step${t}-content`);i&&i.classList.remove("hidden");const r=document.getElementById("stage-title"),s={1:"Prompt Architect",2:"Code Generator",3:"Code Review"};r&&(r.textContent=s[t]||"Active Workflow Stage")}function R0(t){const e=document.getElementById(t);if(!e)return;const n=e.dataset.raw||e.textContent;navigator.clipboard.writeText(n).then(()=>{const r=e.closest(".code-container")?.querySelector(".copy-btn");r&&(r.classList.add("copied"),r.innerHTML=' Copied!',setTimeout(()=>{r.classList.remove("copied"),r.innerHTML=' Copy'},2e3))}).catch(i=>{console.warn("Failed to copy to clipboard:",i)})}function qa(t){const e=za(t);console.log(`Step 1 (Prompt Architect): ${Vt(Ah)}`),console.log(e!==t?`Step 2 (Code Generator): ${Vt(t)} → ${Vt(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${Vt(t)}`),console.log(`Step 3 (Code Review): ${Vt(Ph)}`)}function Wh(){return{step1Result:y.step1Result,step2Result:y.step2Result,step3Result:y.step3Result,artifactBundle:y.artifactBundle,bundleReview:y.bundleReview,selectedArtifactId:y.selectedArtifactId}}function T0(t){if(!t)return;Object.assign(y,t),new Set((y.artifactBundle?.artifacts||[]).map(n=>n.id)).has(y.selectedArtifactId)||(y.selectedArtifactId=oi(y.artifactBundle)?.id||null)}const qh="results-replacement-error";function $0(t,{stage:e=2,runId:n,retry:i}){if(!re(n))return;const r=document.getElementById(qh);if(!r)return;const s=wh(t),o=document.getElementById("results-replacement-error-title"),a=document.getElementById("results-replacement-error-message"),l=document.getElementById("results-replacement-error-retry"),u=document.getElementById("results-replacement-error-upgrade");o&&(o.textContent=`${Vs[e]||"Regeneration"}: ${s.title}`),a&&(a.textContent=s.message),r.hidden=!1;let c=null;u&&(u.hidden=!s.canUpgrade,s.canUpgrade&&(u.textContent="View plans",u.onclick=()=>di(),c=u)),l&&(l.hidden=s.canUpgrade,s.canUpgrade||(l.onclick=()=>{ql(),typeof i=="function"&&i()},l.textContent="Retry",c=l)),(c||r).focus({preventScroll:!0})}function ql(){const t=document.getElementById(qh);t&&(t.hidden=!0)}function zh(t,{previous:e,stage:n,runId:i,retry:r}){re(i)&&(t.isUsageLimit&&un(),T0(e),cr(),nn(!0),ur(),eo(),$0(t,{stage:n,runId:i,retry:r}),rn())}async function Vh(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0;const e=Gs();zl("standardRegenerate",y.step2Result,y.step1Result);const n=document.querySelectorAll(".btn-refine-action"),i=Wh();n.forEach(r=>{r.disabled=!0,r.innerHTML=` - Refining...`});try{zl();const r=Ol(),s=r.id,o=gv({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,artifactId:r.id,userFeedback:"Fix the issues listed in the audit report."});Xs({runId:e}),Pt(2,e),nt(2),Ae(2,!0);const a=await Hs(o,t,[],e);if(!re(e))return;y.step2Result=a,Bs(),en(2,e);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),nt(3),Pt(3,e),Ae(3,!0);const c=await Ws(y.step2Result,y.step1Result);if(!re(e))return;y.step3Result=c,Ds(),en(3,e),y.artifactBundle?.artifacts?.some(h=>h.id===s)?y.selectedArtifactId=s:y.selectedArtifactId=oi(y.artifactBundle)?.id||null;const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),lr();const f=Ls(y.step3Result);cr(u,f)}catch(r){if(console.error("Refinement failed:",r),!re(e))return;const s=Ms(r,{architect:2,generator:2,review:3});Gh(r,{previous:i,stage:s,runId:e,retry:Vh})}finally{n.forEach(r=>{r.disabled=!1,r.textContent="Refine & Regenerate"}),re(e)&&(y.isRunning=!1,nn())}}async function Gl(t,e,n){const i=`${vt}/connectFeedback`,r={type:t,code:e,input:n};try{const s=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok){const a=await s.text();return console.error(`callEndpoint failed: ${s.status} ${s.statusText}`,a),{success:!1,status:s.status,error:a}}const o=await s.json();return console.log("Telemetry success:",o),o}catch(s){return console.error("callEndpoint failed:",s),{success:!1,error:s.message}}}function O0(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function Kh(){const t=document.getElementById("ff-error-paste-input"),e=t?.value?.trim();if(!e){t?.focus(),t?.classList.add("ring-2","ring-red-400","border-red-300"),setTimeout(()=>t?.classList.remove("ring-2","ring-red-400","border-red-300"),2e3);return}if(!y.step2Result){Ee("No generated code found. Please run the full pipeline first.","warning");return}if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=Ks();Gl("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` + Refining...`});try{ql();const r=Nl(),s=r.id,o=hv({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,artifactId:r.id,userFeedback:"Fix the issues listed in the audit report."});Zs({runId:e}),Pt(2,e),nt(2),Ae(2,!0);const a=await Us(o,t,[],e);if(!re(e))return;y.step2Result=a,Bs(),tn(2,e);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),nt(3),Pt(3,e),Ae(3,!0);const c=await Hs(y.step2Result,y.step1Result);if(!re(e))return;y.step3Result=c,Ds(),tn(3,e),y.artifactBundle?.artifacts?.some(h=>h.id===s)?y.selectedArtifactId=s:y.selectedArtifactId=oi(y.artifactBundle)?.id||null;const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const f=Ls(y.step3Result);ur(u,f)}catch(r){if(console.error("Refinement failed:",r),!re(e))return;const s=Ms(r,{architect:2,generator:2,review:3});zh(r,{previous:i,stage:s,runId:e,retry:Vh})}finally{n.forEach(r=>{r.disabled=!1,r.textContent="Refine & Regenerate"}),re(e)&&(y.isRunning=!1,rn())}}async function zl(t,e,n){const i=`${vt}/connectFeedback`,r={type:t,code:e,input:n};try{const s=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok){const a=await s.text();return console.error(`callEndpoint failed: ${s.status} ${s.statusText}`,a),{success:!1,status:s.status,error:a}}const o=await s.json();return console.log("Telemetry success:",o),o}catch(s){return console.error("callEndpoint failed:",s),{success:!1,error:s.message}}}function M0(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function Gh(){const t=document.getElementById("ff-error-paste-input"),e=t?.value?.trim();if(!e){t?.focus(),t?.classList.add("ring-2","ring-red-400","border-red-300"),setTimeout(()=>t?.classList.remove("ring-2","ring-red-400","border-red-300"),2e3);return}if(!y.step2Result){Ee("No generated code found. Please run the full pipeline first.","warning");return}if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=Gs();zl("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` - Fixing…`);const s=qh();try{zl();const o=ih({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});Sp(),Xs({runId:i}),Pt(2,i),nt(2),Ae(2,!0);const a=await Hs(o,n,[],i);if(!re(i))return;y.step2Result=a,Bs(),en(2,i);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),nt(3),Pt(3,i),Ae(3,!0);const c=await Ws(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,Ds(),en(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),lr();const f=Ls(y.step3Result);cr(u,f),t&&(t.value="")}catch(o){if(console.error("Fix from errors failed:",o),!re(i))return;const a=Ms(o,{architect:2,generator:2,review:3});Gh(o,{previous:s,stage:a,runId:i,retry:Kh})}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,nn())}}async function sr(){if(console.log("runThinkingPipeline called"),y.isRunning)return;localStorage.setItem("hasSeenWalkthrough","true");const t=document.getElementById("pipeline-input").value,e=document.getElementById("code-generator-model").value,n=Ne.slice();if(!t.trim()){Ee("Please describe your FlutterFlow widget first.","warning");return}y.isRunning=!0;const i=Ks();try{if(await Ba,!re(i)||(hn.length&&await Promise.allSettled(hn.map(v=>v.job)),!re(i))||!await aw()||!re(i)||(await tw(),!re(i)))return;const r=Ga(e);Cn("Pipeline Started",{selectedModel:e,effectiveModel:r,inputLength:t.length}),_0(),y.submittedPrompt=t,y.submittedImages=n.filter(v=>v.url),Ya(!0),za(r),Nn();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const o=document.getElementById("paywall-exhausted");o&&o.classList.add("hidden"),Xs({prompt:t,runId:i}),jw(),nt(1),Pt(1,i),Ae(1,!0);const a=y.submittedImages.map(v=>({url:v.url})),l=await R0(t,a);if(!re(i))return;y.step1Result=l,y0(),en(1,i),Cn("Prompt Architect Completed");const u=document.getElementById("step1-output"),c=li(y.step1Result);u.textContent=c,u.dataset.raw=c,Ae(1,!1),nt(2),Pt(2,i),Ae(2,!0);const d=await Hs(y.step1Result,r,a,i);if(!re(i))return;y.step2Result=d,Bs(),en(2,i),Cn("Code Generator Completed");const f=document.getElementById("step2-output"),h=li(y.step2Result);f.textContent=h,f.dataset.raw=h,Ae(2,!1),nt(3),Pt(3,i),Ae(3,!0);const p=await Ws(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=p,Ds(),en(3,i),Cn("Code Review Completed");const g=document.getElementById("step3-output");g.textContent=y.step3Result,Ae(3,!1),lr();const m=Ls(y.step3Result);Uw(),cr(h,m)}catch(r){if(r.isPipelineCancel||console.error("Pipeline failed:",r),!re(i))return;const s=Ms(r,{architect:1,generator:2,review:3});r.isUsageLimit?cn():Cn("Pipeline Failed",{error:r.message,effectiveModel:Ga(document.getElementById("code-generator-model").value)}),nt(s),Ae(s,!1),yp(r,{stage:s,runId:i}),bs(s,"error")}finally{re(i)&&(y.isRunning=!1,Ya(!1),nn())}}function B0(){const t=document.getElementById("code-generator-model").value,e=[gs,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(i=>i!==t),n=prompt(`Retry with different model? + Fixing…`);const s=Wh();try{ql();const o=nh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});bp(),Zs({runId:i}),Pt(2,i),nt(2),Ae(2,!0);const a=await Us(o,n,[],i);if(!re(i))return;y.step2Result=a,Bs(),tn(2,i);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),nt(3),Pt(3,i),Ae(3,!0);const c=await Hs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,Ds(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const f=Ls(y.step3Result);ur(u,f),t&&(t.value="")}catch(o){if(console.error("Fix from errors failed:",o),!re(i))return;const a=Ms(o,{architect:2,generator:2,review:3});zh(o,{previous:s,stage:a,runId:i,retry:Gh})}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function or(){if(console.log("runThinkingPipeline called"),y.isRunning)return;localStorage.setItem("hasSeenWalkthrough","true");const t=document.getElementById("pipeline-input").value,e=document.getElementById("code-generator-model").value,n=Ne.slice();if(!t.trim()){Ee("Please describe your FlutterFlow widget first.","warning");return}y.isRunning=!0;const i=Gs();try{if(await Oa,!re(i)||(pn.length&&await Promise.allSettled(pn.map(v=>v.job)),!re(i))||!await rw()||!re(i)||(await X0(),!re(i)))return;const r=za(e);t.length,g0(),y.submittedPrompt=t,y.submittedImages=n.filter(v=>v.url),Ka(!0),qa(r),Nn();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const o=document.getElementById("paywall-exhausted");o&&o.classList.add("hidden"),Zs({prompt:t,runId:i}),Ow(),nt(1),Pt(1,i),Ae(1,!0);const a=y.submittedImages.map(v=>({url:v.url})),l=await A0(t,a);if(!re(i))return;y.step1Result=l,m0(),tn(1,i);const u=document.getElementById("step1-output"),c=li(y.step1Result);u.textContent=c,u.dataset.raw=c,Ae(1,!1),nt(2),Pt(2,i),Ae(2,!0);const d=await Us(y.step1Result,r,a,i);if(!re(i))return;y.step2Result=d,Bs(),tn(2,i);const f=document.getElementById("step2-output"),h=li(y.step2Result);f.textContent=h,f.dataset.raw=h,Ae(2,!1),nt(3),Pt(3,i),Ae(3,!0);const p=await Hs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=p,Ds(),tn(3,i);const g=document.getElementById("step3-output");g.textContent=y.step3Result,Ae(3,!1),cr();const m=Ls(y.step3Result);Bw(),ur(h,m)}catch(r){if(r.isPipelineCancel||console.error("Pipeline failed:",r),!re(i))return;const s=Ms(r,{architect:1,generator:2,review:3});r.isUsageLimit?un():(r.message,za(document.getElementById("code-generator-model").value),void 0),nt(s),Ae(s,!1),vp(r,{stage:s,runId:i}),bs(s,"error")}finally{re(i)&&(y.isRunning=!1,Ka(!1),rn())}}function L0(){const t=document.getElementById("code-generator-model").value,e=[ms,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(i=>i!==t),n=prompt(`Retry with different model? Current: ${t} @@ -140,14 +140,14 @@ Options: 1. ${e[0]} 2. ${e[1]} -Enter 1 or 2:`);n==="1"?(document.getElementById("code-generator-model").value=e[0],sr()):n==="2"&&(document.getElementById("code-generator-model").value=e[1],sr())}async function D0(){const t=Bl();if(!t){Ee("No code to commit. Please run the pipeline first.","warning");return}const e=await Te("flutterflow"),n=await Te("flutterflow_project_id");if(!e||!n){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),Tl();return}if(y.artifactBundle?.artifacts?.length>1){await j0();return}const{artifactType:i,artifactName:r,fileName:s}=Bh(),o=Wh(t,{artifactType:i,artifactName:r,fileName:s}),a=x0(o);if(!a.canProceed){Ee(`Pre-commit checks failed: ${a.issues.join("; ")}`,"error");return}Yl(o,a,null,null)}async function j0(){const t=await Te("flutterflow"),e=await Te("flutterflow_project_id");if(!t||!e){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),Tl();return}const n=Xv(y.artifactBundle);if(n.errors.length>0){Ee(`Bundle validation failed: ${n.errors.join("; ")}`,"error");return}const i=new Map(n.fileEntries.map(a=>[a.fileName,{content:a.content,type:a.type,path:a.path}])),r=Us(i),s={canProceed:r.valid&&n.errors.length===0,issues:[...n.errors,...r.errors],warnings:[...n.warnings,...r.warnings]};if(!s.canProceed){Ee(`Bundle validation failed: ${s.issues.join("; ")}`,"error");return}const o={content:n.fileEntries.map(a=>`// ${a.fileName} +Enter 1 or 2:`);n==="1"?(document.getElementById("code-generator-model").value=e[0],or()):n==="2"&&(document.getElementById("code-generator-model").value=e[1],or())}async function N0(){const t=Ol();if(!t){Ee("No code to commit. Please run the pipeline first.","warning");return}const e=await Te("flutterflow"),n=await Te("flutterflow_project_id");if(!e||!n){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),Rl();return}if(y.artifactBundle?.artifacts?.length>1){await O0();return}const{artifactType:i,artifactName:r,fileName:s}=Oh(),o=Hh(t,{artifactType:i,artifactName:r,fileName:s}),a=b0(o);if(!a.canProceed){Ee(`Pre-commit checks failed: ${a.issues.join("; ")}`,"error");return}Kl(o,a,null,null)}async function O0(){const t=await Te("flutterflow"),e=await Te("flutterflow_project_id");if(!t||!e){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),Rl();return}const n=Jv(y.artifactBundle);if(n.errors.length>0){Ee(`Bundle validation failed: ${n.errors.join("; ")}`,"error");return}const i=new Map(n.fileEntries.map(a=>[a.fileName,{content:a.content,type:a.type,path:a.path}])),r=js(i),s={canProceed:r.valid&&n.errors.length===0,issues:[...n.errors,...r.errors],warnings:[...n.warnings,...r.warnings]};if(!s.canProceed){Ee(`Bundle validation failed: ${s.issues.join("; ")}`,"error");return}const o={content:n.fileEntries.map(a=>`// ${a.fileName} ${a.content}`).join(` -`),fileName:`${n.fileEntries.length} files`,codeType:"bundle",artifactType:"Bundle",artifactName:n.title};Yl(o,s,n.dependencies,n)}function U0(t){let e=t.errorMap||new Map;!(e instanceof Map)&&typeof e=="object"&&(e=new Map(Object.entries(e)));let n=`
+`),fileName:`${n.fileEntries.length} files`,codeType:"bundle",artifactType:"Bundle",artifactName:n.title};Kl(o,s,n.dependencies,n)}function B0(t){let e=t.errorMap||new Map;!(e instanceof Map)&&typeof e=="object"&&(e=new Map(Object.entries(e)));let n=`

FlutterFlow Commit Failed

${q(t.error)}

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

Errors:

-
    `;for(const[r,s]of e.entries()){const o=Sl(s);n+=`
  • +
      `;for(const[r,s]of e.entries()){const o=El(s);n+=`
    • ${q(r)}: ${q(o)}
    • `}n+="
"}n+="
",n+=`
-
`;const i=document.getElementById("step3-output");i&&(i.innerHTML=n,document.getElementById("btn-regenerate-from-error")?.addEventListener("click",()=>{Yh(t.error,e)}))}async function Yh(t,e){if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=Ks(),r=document.getElementById("btn-regenerate-from-error");r&&(r.disabled=!0,r.innerHTML=` +
`;const i=document.getElementById("step3-output");i&&(i.innerHTML=n,document.getElementById("btn-regenerate-from-error")?.addEventListener("click",()=>{Kh(t.error,e)}))}async function Kh(t,e){if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=Gs(),r=document.getElementById("btn-regenerate-from-error");r&&(r.disabled=!0,r.innerHTML=` Fixing...`);try{let s=`The previous code had the following errors when committing to FlutterFlow: -`;if(e&&e.size>0)for(const[h,p]of e.entries()){const g=Sl(p);s+=`File: ${h} +`;if(e&&e.size>0)for(const[h,p]of e.entries()){const g=El(p);s+=`File: ${h} Error: ${g} `}else s+=`${t} -`;const o=ih({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:s});Xs({runId:i}),Pt(2,i),nt(2),Ae(2,!0);const a=await Hs(o,n,[],i);if(!re(i))return;y.step2Result=a,Bs(),en(2,i);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),nt(3),Pt(3,i),Ae(3,!0);const c=await Ws(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,Ds(),en(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),lr();const f=Ls(y.step3Result);cr(u,f)}catch(s){if(console.error("Regeneration failed:",s),!re(i))return;const o=Ms(s,{architect:2,generator:2,review:3});s.isUsageLimit&&cn(),nt(o),Ae(o,!1),yp(s,{stage:o,runId:i,retry:()=>Yh(t,e)}),bs(o,"error")}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,nn())}}async function H0(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const n=await Te("flutterflow"),i=await Te("flutterflow_project_id");n&&i?(t.className="w-2 h-2 rounded-full bg-green-500",e.textContent="FlutterFlow credentials configured",e.className="text-green-600"):n||i?(t.className="w-2 h-2 rounded-full bg-yellow-500",e.textContent="FlutterFlow credentials incomplete",e.className="text-yellow-600"):(t.className="w-2 h-2 rounded-full bg-red-500",e.textContent="FlutterFlow credentials not configured",e.className="text-red-600")}async function Jh(t){try{const e=await fetch(`${vt}/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 W0(t){try{const n=await(await fetch(`${vt}/auth/verify-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})})).json();if(n.error||!n.email||!n.sessionToken)throw new Error(n.error||"Invalid or expired link");return n}catch(e){throw console.error("verifyMagicLink failed:",{message:e.message,stack:e.stack}),e}}async function q0(t){try{const e=await fetch(`${vt}/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:`${vt}/auth/refresh-session`,status:e.status}),null;const n=await e.json();return n.error||!n.email||!n.sessionToken?(console.warn("refreshSession: validation failed",{error:n.error,hasEmail:!!n.email,hasToken:!!n.sessionToken}),null):n}catch(e){return console.error("refreshSession: fetch failed",{url:`${vt}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function td(t,e){const n=Xh(),i=(z.email||n.email)!==t;z.email=t,z.sessionToken=e,z.isVerified=!0,ce=Mn({isLoading:!0}),localStorage.setItem(fs,JSON.stringify({email:t,sessionToken:e})),i&&rp()}function Zh(){z.email=null,z.sessionToken=null,z.isVerified=!1,ce=Mn({isResolved:!0}),localStorage.removeItem(fs),localStorage.removeItem(ps)}function Xh(){try{const t=localStorage.getItem(fs);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(fs),{email:null,sessionToken:null}}}async function z0(){const e=new URLSearchParams(window.location.search).get("token");if(e){window.history.replaceState({},"",window.location.pathname+window.location.hash);try{const{email:n,sessionToken:i}=await W0(e);td(n,i),Qh();const r=nd();r&&!window.location.hash&&(window.location.hash=r)}catch(n){nd();const i=n.message||"Sign-in link invalid or expired.";Ee(i,"error"),qs(),Jn(i,"error")}}else{const{email:n,sessionToken:i}=Xh();if(n&&i){const r=await q0(i);r?td(r.email,r.sessionToken):Zh()}}Vl()}function G0(){try{localStorage.setItem(Oa,JSON.stringify({hash:window.location.hash||"#home",ts:Date.now()}))}catch(t){console.warn("rememberSignInReturnSurface: failed to persist return surface:",t)}}function nd(){try{const t=localStorage.getItem(Oa);if(localStorage.removeItem(Oa),!t)return null;const{hash:e,ts:n}=JSON.parse(t);return!e||typeof n!="number"||Date.now()-n>Ay?null:e}catch(t){return console.warn("consumeSignInReturnSurface: failed to read return surface:",t),null}}function qs(){const t=document.getElementById("signin-modal");if(!t)return;G0(),document.getElementById("signin-email-input")?.removeAttribute("aria-invalid"),Jn(""),He(t)}function Qh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&We(e)}function Jn(t,e){const n=document.getElementById("signin-message");n&&(n.textContent=t||"",n.classList.remove("signin-message-success","signin-message-error"),e&&n.classList.add(`signin-message-${e}`))}async function V0(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),n=Fs(t?.value);if(!n||!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(n)||n.length>254){t?.setAttribute("aria-invalid","true"),Jn("Please enter a valid email address.","error");return}t?.removeAttribute("aria-invalid"),e&&(e.disabled=!0,e.textContent="Sending…");const r=dh(n);r&&Jn(r,"error");try{const s=await Jh(n),o=s?.code===uh;t&&!o&&(t.value=""),t?.setAttribute("aria-invalid",String(o)),Jn(fh(s,n),o?"error":"success"),e&&(e.disabled=!1,e.textContent=o?"Send Sign-in Link":"Sent!",o||setTimeout(()=>{e.textContent==="Sent!"&&(e.textContent="Send Sign-in Link")},2500))}catch(s){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:n,err:s}),Jn("Something went wrong. Please try again.","error"),e&&(e.disabled=!1,e.textContent="Send Sign-in Link")}}function K0(){z.email=null,z.sessionToken=null,z.isVerified=!1,ce=Mn({isResolved:!0}),L_({storage:window.localStorage,onIdentityChanged:Vl,onPlanChanged:Gs})}const Y0=N_({sendLink:Jh,getEmail:()=>z.email||"",onState:J0});function J0(t){const e=document.getElementById("send-new-link-btn"),n=document.getElementById("send-new-link-msg");if(!e||!n)return;if(t.status==="pending"){e.disabled=!0,e.textContent="Sending…",n.className="acct-access-msg",n.textContent="Sending a fresh sign-in link…";return}if(t.status==="sent"){e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg",n.textContent=fh(t.data,z.email||"")||"Link sent — check your email.";return}e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg error";const i=t.error?.message?`Couldn't send a link right now. ${t.error.message}`:"Couldn't send a link right now. Please try again.";n.textContent=i}async function Z0(){await Y0()}function X0(){const t=$_(window.localStorage),e=t.length?`Cleared disposable UI caches: ${t.join(", ")}.`:"Nothing disposable to clear.";Ee(`${e} Your run count, identity and stored keys are kept.`,"info")}function Q0(){const t=document.getElementById("delete-unavailable-modal");t&&He(t,{trigger:document.activeElement})}function ew(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("delete-unavailable-modal");e&&We(e)}function Vl(){const t=z.isVerified&&!!z.email,e=document.getElementById("auth-signedout"),n=document.getElementById("auth-signedin"),i=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),n&&n.classList.toggle("hidden",!t),i&&i.classList.toggle("hidden",t);const r=document.getElementById("auth-user-email");r&&(r.textContent=z.email||"");const s=document.getElementById("access-signed-email");s&&(s.textContent=z.email||""),uw(),Gs()}async function ep(){try{if(typeof FingerprintJS>"u"){console.warn("resolveIdentity: FingerprintJS not loaded, skipping");return}const e=await(await FingerprintJS.load()).get(),n=e.visitorId,i=await fetch(Ty,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fingerprint:e.visitorId,cookie_id:n})});if(!i.ok)throw new Error(`Identity check HTTP ${i.status}`);const r=await i.json();if(ft.userId=r.user_id,ft.token=r.identity_token||null,ft.status=r.status,ft.resolved=!0,sessionStorage.setItem(Fy,r.user_id),ft.token&&sessionStorage.setItem(Ry,ft.token),r.usage_count!==void 0){const s=pn(),a=(r.usage_month||s)===s?r.usage_count:0;localStorage.setItem(Fn,JSON.stringify({count:a,month:s})),cn()}console.log(`Identity resolved: ${r.status} (${r.user_id.slice(0,8)}...) usage: ${r.usage_count??"n/a"}`)}catch(t){console.error("resolveIdentity failed:",t)}}let qo=null;function tw(t=5e3){return ft.resolved?Promise.resolve():(qo||(qo=ep().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([qo,new Promise(e=>setTimeout(e,t))]))}function tp(){const t=pn();try{const e=localStorage.getItem(Fn);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Fn,month:t,err:e}),localStorage.removeItem(Fn),{count:0,month:t}}}function pn(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function ar(){const t=tp();return t.month!==pn()?{count:0,month:pn()}:t}function nw(){const e={count:ar().count+1,month:pn()};return localStorage.setItem(Fn,JSON.stringify(e)),e}function pi(){return!!ce.isLoading}function Rt(){return!!ce.isResolved}function iw(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(hs,e)?e:null}function rw(t){return t&&Object.entries(Sh).find(([,e])=>e===t)?.[0]||null}function kr(...t){return t.find(e=>e!=null&&e!=="")}function sw(...t){return t.find(e=>e&&typeof e=="object")||{}}function ow(t){const e=t.data&&typeof t.data=="object"?t.data:t,n=sw(e.subscription,e.stripeSubscription,e.currentSubscription,e.customer?.subscriptions?.data?.[0],e.subscriptions?.data?.[0],e.subscriptions?.[0]),i=e.metadata||n.metadata||e.customer?.metadata||{},r=kr(e.priceId,e.price_id,e.stripePriceId,e.stripe_price_id,n.priceId,n.price_id,n.plan?.id,n.price?.id,n.items?.data?.[0]?.price?.id,n.items?.[0]?.price?.id,n.lines?.data?.[0]?.price?.id),s=kr(e.status,e.subscriptionStatus,e.subscription_status,n.status,"none"),o=iw(kr(e.tier,e.plan,e.planId,e.plan_id,e.subscriptionTier,e.subscription_tier,e.product,e.productName,n.tier,n.plan,i.tier,i.plan)),a=$y.has(String(s).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||rw(r)||(a||l?"professional":"free");return Mn({tier:u,status:s,periodEnd:kr(e.periodEnd,e.currentPeriodEnd,e.current_period_end,n.current_period_end,n.periodEnd,null),isResolved:!0})}function zs(){return hs[ce.tier]??hs.free}async function aw(){if(z.isVerified&&(!Rt()||pi())&&(await ip({force:!0}),Gs()),z.isVerified&&!Rt())return Ee("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=ar(),e=zs();if(t>=e)return np(t,e,{openModal:!0}),!1;const n=Math.floor(e*.8);if(t>=n){const i=e-t;Ee(`${i} run${i===1?"":"s"} remaining this month.`,"warning")}return!0}function id(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function np(t,e,n={}){tn(!0);const i=document.getElementById("walkthrough-modal");i&&We(i,{restoreFocus:!1});const r=document.getElementById("ready-state");r&&r.classList.add("hidden");const s=document.getElementById("preview-frame-container");s&&(s.style.display="none");const o=document.getElementById("main-stage-container");o&&o.classList.add("visible");const a=document.getElementById("results-view");a&&a.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar");const l=document.getElementById("pipeline-progress");l&&l.classList.remove("visible");const u=document.getElementById("paywall-exhausted");if(!u){Ee(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),di();return}const c=document.getElementById("paywall-exhausted-text");if(c){const f=ce.tier;f==="free"?c.textContent=`You've used all ${e} free generations this month. Upgrade to Pro for 50 generations/month and access to all AI models.`:c.textContent=`You've used all ${e} generations this month on your ${f} plan. Your limit resets next month.`}const d=document.getElementById("paywall-signin-btn");d&&d.classList.toggle("hidden",z.isVerified),u.classList.remove("hidden"),n.openModal&&di()}function Ga(t){return ce.tier==="free"&&Lr.includes(t)?gs:t}function lw(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const n=ce.tier,r=!(z.isVerified&&!Rt())&&n==="free";Array.from(e.options).forEach(o=>{const a=Gt(o.value),l=Lr.includes(o.value);o.textContent=l&&r?`${a} (PRO)`:a,o.disabled=!1}),r&&Lr.includes(e.value)&&(e.value=gs),e.disabled=!1,qu.has(e)||(e.addEventListener("change",()=>{Rt()&&ce.tier==="free"&&Lr.includes(e.value)&&(e.value=gs,di()),za(e.value),Cl()}),qu.add(e));let s=document.getElementById("model-selector-free-notice");r?(s||(s=document.createElement("p"),s.id="model-selector-free-notice",s.className="text-xs text-gray-400 mt-1",t.appendChild(s)),s.innerHTML='Free plan — Gemini only. '):s&&s.remove(),za(e.value)}function Kl(){const t=z.isVerified&&!!z.email,e=t&&pi(),n=!t||Rt(),i=ar(),r=n?i.count:0,s=n?zs():0,o=Math.max(0,s-r),a=`${r} / ${s} runs this month`,l=ml,u=n?ce.tier||"free":null,c=document.getElementById("topbar-credits-count");c&&(e?c.textContent="…":n?c.textContent=String(o):c.textContent="—");const d=document.getElementById("credits-balance");d&&(e?d.textContent="Checking plan…":n?d.textContent=a:d.textContent="Plan check failed");const f=document.getElementById("usage-dialog-tier");f&&(e?f.textContent="Checking…":n?f.textContent=l[u]||"Free":f.textContent="Unavailable");const h=document.getElementById("usage-dialog-status");h&&(e?h.textContent="Verifying your subscription…":n?h.textContent="Runs reset at the start of each month.":h.textContent="Could not verify your subscription. Try again or sign out.");const p=document.getElementById("usage-counter");if(p)if(e&&t)p.textContent="Checking plan…",p.className="text-xs text-gray-500";else if(!n&&t)p.textContent="Plan check failed",p.className="text-xs text-red-600 font-medium";else{p.textContent=a;const g=s>0?r/s:0;p.className=g>=1?"text-xs text-red-600 font-medium":g>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500"}if(!t){const g=document.getElementById("guest-usage-text");if(g){const m=tp(),v=m.month===pn()?m.count??0:0;g.textContent=`${v} / ${hs.free} generations used`}}cw()}function cw(){if(!(z.isVerified&&!!z.email))return;const e=pi(),n=Rt(),i=ar(),r=n?i.count:0,s=n?zs():0,o=Math.max(0,s-r),a=n?ce.tier||"free":null,l={free:"Free",professional:"Pro",power:"Power"}[a]||"Free",u=z.email||"",c=u.split("@")[0]||u,d=document.getElementById("acct-avatar");d&&(d.textContent=(u[0]||"?").toUpperCase());const f=document.getElementById("acct-name");f&&(f.textContent=c||"—");const h=document.getElementById("acct-plan-tier"),p=document.getElementById("acct-plan-price"),g=document.getElementById("acct-plan-note"),m=document.getElementById("acct-renewal");if(h&&(h.textContent=e?"Checking…":n?l:"Plan unavailable"),p)if(e)p.textContent="—";else if(!n)p.textContent="—";else if(a==="free")p.textContent="$0 / month";else{const E=Oi(Ni[a]??0,Al());p.textContent=`${E} / month`}if(g&&(e?g.textContent="Verifying your subscription…":n?a==="free"?g.textContent="No subscription. Upgrade for more generations.":g.textContent="billed monthly through Stripe":g.textContent="Could not verify your subscription. Check billing or sign out."),m){const E=Date.parse(ce.periodEnd||""),P=n&&a!=="free"&&!!ce.periodEnd&&!Number.isNaN(E);if(e)m.textContent="";else if(!n)m.textContent="";else if(a==="free")m.textContent="";else if(P){const $=new Date(E).toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"});m.textContent=`Renews ${$} · reset at the start of each month.`}else m.textContent="Renewal date is not available for this period."}const v=document.getElementById("acct-left-count"),S=document.getElementById("acct-left-limit"),b=document.getElementById("acct-reset-note");v&&(v.textContent=e?"…":n?String(o):"—"),S&&(S.textContent=e?"…":n?String(s):"—"),b&&(e?b.textContent="Checking plan…":n?b.textContent="Runs reset at the start of each month.":b.textContent="Plan check failed. Refresh or manage billing.");const _=document.getElementById("acct-used-count"),x=document.getElementById("acct-meter-fill"),I=document.getElementById("acct-meter-meta"),T=document.getElementById("acct-meter-track");if(_&&(_.textContent=e?"…":n?String(r):"—"),x){const E=n&&s>0?Math.min(100,Math.round(r/s*100)):0;x.style.width=`${E}%`}if(I)if(e)I.textContent="Checking…";else if(!n)I.textContent="Plan check failed";else if(s===0)I.textContent=`${r} of ${s}`;else{const E=Math.round(r/s*100);I.textContent=`${r} of ${s} · ${E}%`}T&&(e?T.setAttribute("aria-label","Checking usage…"):n?T.setAttribute("aria-label",`${r} of ${s} generations used`):T.setAttribute("aria-label","Usage unavailable")),mt()}function cn(){if(Kl(),z.isVerified&&(pi()||!Rt())){id();return}const{count:t}=ar(),e=zs();t>=e&&!y.isRunning?np(t,e):id()}function uw(){Kl()}async function ip(t={}){const e=t.force===!0;if(!z.isVerified||!z.sessionToken){ce=Mn({isResolved:!0});return}ce={...ce,isLoading:!0,error:null};const n=localStorage.getItem(ps);if(!e&&n)try{const{data:i,email:r,ts:s,version:o}=JSON.parse(n);if(o===zu&&r===z.email&&Date.now()-s<300*1e3){ce={...i,isLoading:!1,isResolved:i.isResolved!==!1};return}}catch(i){console.warn("Failed to parse subscription cache:",i,"| raw value:",n)}try{const r=await(await fetch(`${vt}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:z.sessionToken,user_id:ft.userId})})).json();if(r.error){if(["unauthorized","invalid session","expired session"].some(o=>String(r.error).toLowerCase().includes(o))){Zh(),Vl();return}ce=Mn({isResolved:!1,error:r.error});return}ce=ow(r),localStorage.setItem(ps,JSON.stringify({version:zu,data:ce,email:z.email,ts:Date.now()}))}catch(i){console.error("fetchSubscription failed:",i),ce={...ce,isLoading:!1,isResolved:!1,error:i.message}}}function rp(){localStorage.removeItem(ps)}async function dw(t){if(!z.isVerified||!z.sessionToken){sp(),qs();return}if(!Sh[t]){Ee("Invalid plan selected.","error");return}const e=document.getElementById(`checkout-btn-${t}`);e&&(e.disabled=!0,e.textContent="Redirecting…");try{const i=await(await fetch(`${vt}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:z.sessionToken,currency:Al()})})).json();if(i.error||!i.url)throw new Error(i.error||"Failed to create checkout session");const{url:r}=i;window.location.href=r}catch(n){console.error("startCheckout failed:",n),e&&(e.disabled=!1,e.textContent="Subscribe"),Ee("Could not start checkout. Please try again.","error")}}async function fw(t){if(!z.isVerified||!z.sessionToken){qs();return}const e=t||document.getElementById("manage-billing-btn"),n=e?e.textContent:"";e&&(e.disabled=!0,e.textContent="Loading…");try{const r=await(await fetch(`${vt}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:z.sessionToken})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to open billing portal");const{url:s}=r;window.location.href=s}catch(i){console.error("openCustomerPortal failed:",i),e&&(e.disabled=!1,e.textContent=n),Ee("Could not open billing portal. Please try again.","error")}}const Es=new Set;function hw(){Es.forEach(t=>t.abort()),Es.clear()}async function Ss(t,e,n,i={},r=[]){const o=new AbortController;Es.add(o);let a=!1;const l=setTimeout(()=>{a=!0,o.abort()},12e4);try{const u=await fetch(Py,{method:"POST",headers:{"Content-Type":"application/json",...ft.token?{Authorization:`Bearer ${ft.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:ft.userId,step:t,model:e,prompt:n,images:r,context:i})}),c=await u.text();let d={};try{d=c?JSON.parse(c):{}}catch{d={}}if(u.status===429){d.serverCount!==void 0&&(localStorage.setItem(Fn,JSON.stringify({count:d.serverCount,month:pn()})),cn());const p=new Error(d.message||"Monthly usage limit reached. Upgrade to continue.");throw p.isUsageLimit=!0,p.pipelineStep=t,p}const f=Ev(d,t);if(f)throw f;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(d),"content type:",typeof d.content),!u.ok)throw new Error(`${d.message||d.error||"BuildShip pipeline error"} (HTTP ${u.status})`);if(t==="generator")if(d.usage_status==="success"&&Number.isFinite(d.usage_count)){const p=pn();(d.usage_month||p)===p&&(localStorage.setItem(Fn,JSON.stringify({count:d.usage_count,month:p})),cn())}else nw(),cn();let h=d.output||d.content;if(!h){const p=c?` (body: ${c.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${p}`)}return Array.isArray(h)&&(h=h.map(p=>typeof p=="string"?p:p.text||"").join("")),typeof h!="string"&&(h=JSON.stringify(h)),h}catch(u){if(u.name==="AbortError"){if(a)throw new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`);const c=new Error(`BuildShip ${t} request cancelled`);throw c.isPipelineCancel=!0,c}throw u instanceof TypeError?new Error(`BuildShip unreachable: ${u.message}`):u}finally{clearTimeout(l),Es.delete(o)}}let Va=!1;function pw(){const e=new URLSearchParams(window.location.search).get("checkout");return e==="success"?(window.history.replaceState({},"",window.location.pathname+window.location.hash),rp(),Va=!0):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname+window.location.hash),Ee("Checkout cancelled.","info")),e}function gw(){if(!Va)return;Va=!1;const t=ce.tier!=="free";Ee(t?"Subscription active! Your plan is live.":"Checkout complete — confirming your subscription. Check Manage billing if it does not update.",t?"success":"info")}function Gs(){const t=z.isVerified&&!!z.email,e=ce.tier,n=t&&pi(),i=!t||Rt(),r=document.getElementById("subscription-tier-badge");if(r){const a=ml,l={free:"bg-gray-100 text-gray-600",professional:"bg-indigo-100 text-indigo-700",power:"bg-purple-100 text-purple-700",unresolved:"bg-red-50 text-red-600"};r.textContent=n?"Checking…":i?a[e]||"Free":"Plan unavailable",r.className=`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${i?l[e]||l.free:l.unresolved}`}const s=document.getElementById("upgrade-prompt");s&&s.classList.toggle("hidden",!t||n||!i||e!=="free");const o=document.getElementById("manage-billing-btn");o&&o.classList.toggle("hidden",!t||n||i&&e==="free"),mw(i?e:null),lw(),Cl(),cn(),xp()}function mw(t){const e=["bg-gray-100","text-gray-500","cursor-default"];Object.entries({professional:{btnId:"checkout-btn-professional",defaultText:"Subscribe"},power:{btnId:"checkout-btn-power",defaultText:"Subscribe"}}).forEach(([r,{btnId:s,defaultText:o}])=>{const a=document.getElementById(s);a&&(r===t?(a.disabled=!0,a.textContent="Current plan",a.classList.add(...e)):(a.disabled=!1,a.textContent=o,a.classList.remove(...e)))});const i=document.getElementById("free-tier-current");i&&i.classList.toggle("hidden",t!=="free")}function vw(){document.querySelectorAll(".pm-card[data-tier]").forEach(t=>{const e=t.dataset.tier,n=cv[e];if(!n)return;const i=t.querySelector("ul.pm-features");if(i){i.innerHTML="";for(const r of n){const s=document.createElement("li");s.textContent=r,i.appendChild(s)}}})}function Ka(){const t=Al(),e=document.getElementById("pro-price"),n=document.getElementById("power-price"),i=document.getElementById("plans-pro-price"),r=document.getElementById("plans-power-price"),s=document.getElementById("pro-price-note"),o=document.getElementById("power-price-note"),a=document.getElementById("plans-pro-price-note"),l=document.getElementById("plans-power-price-note");e&&(e.textContent=Oi(Ni.professional,t)),n&&(n.textContent=Oi(Ni.power,t)),i&&(i.textContent=Oi(Ni.professional,t)),r&&(r.textContent=Oi(Ni.power,t));const u="billed monthly";s&&(s.textContent=u),o&&(o.textContent=u),a&&(a.textContent=u),l&&(l.textContent=u)}function di(){Ka();const t=document.getElementById("pricing-modal");t&&He(t),qy().then(()=>Ka())}function sp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&We(e)}function Ee(t,e="info"){const n={success:"bg-green-600 text-white",error:"bg-red-600 text-white",warning:"bg-amber-500 text-white",info:"bg-gray-800 text-white"},i=document.createElement("div");i.className=`fixed bottom-6 left-1/2 -translate-x-1/2 px-5 py-3 rounded-lg text-sm font-medium shadow-lg z-50 transition-opacity duration-300 ${n[e]||n.info}`,i.textContent=t,document.body.appendChild(i),setTimeout(()=>{i.style.opacity="0",setTimeout(()=>i.remove(),300)},3500)}document.addEventListener("DOMContentLoaded",async()=>{ov(),hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),_w(),window.__heroField=Q_(),window.__pipelineLogo=iy(),Ih=xy({onSubmit:sr}),Ba=(async()=>{try{await z0(),pw(),await ip()}catch(n){console.warn("Startup auth/subscription initialization failed:",n)}})(),await Ba,gw(),Gs(),Ka(),vw(),await w0(),g0();const t=document.getElementById("flutterflow-endpoint-select");if(t){const n=_t();t.value=n}Oh(),ep();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{Qt===2&&e.value.trim().length>0&&($l(),Ns())}),e.addEventListener("blur",()=>{const n=document.getElementById("walkthrough-modal");Qt===2&&n&&He(n)}),e.addEventListener("keydown",n=>{if(n.key==="Tab"){const i=document.getElementById("walkthrough-modal");Qt===2&&i&&setTimeout(()=>{He(i)},100)}})),window.addEventListener("commitStateChange",n=>{const{state:i}=n.detail;i===ee.PREPARING||i===ee.VALIDATING||i===ee.PUSHING?(Oe.phaseId||fp(),sd(i)):(i===ee.SUCCESS||i===ee.ERROR)&&(sd(i),setTimeout(Jl,1e3))}),ic()});function _w(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function yw(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Nn),document.addEventListener("keydown",Nn))}function Nn(){const t=document.getElementById("preview-frame-container"),e=document.getElementById("main-stage-container"),n=document.getElementById("ready-state");t&&(t.style.display="none"),e&&e.classList.add("visible"),n&&n.classList.remove("hidden");const i=document.getElementById("welcome-video-player");i&&i.removeEventListener("click",Nn),document.removeEventListener("keydown",Nn),Oh()}let zi=null;async function ww(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++Ju,n=()=>e===Ju,i=await Te("flutterflow"),r=await Te("flutterflow_project_id");if(n()){if(!i){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const o=await new hi(i,"","main",_t()).listProjects();if(!n())return;if(!o||o.length===0){t.innerHTML='';return}t.innerHTML='',o.forEach(a=>{const l=document.createElement("option");l.value=a.id||a.projectId||"",l.textContent=a.name||a.projectName||`Project ${a.id}`,t.appendChild(l)}),r&&(t.value=r)}catch(s){if(!n())return;console.error("Failed to load projects for deploy:",s),t.innerHTML=''}}}function bw(){return document.getElementById("confirm-project-select")?.value?.trim()||null}function Yl(t,e,n,i=null){zi={codeInfo:t,checks:e,deps:n,bundlePlan:i},document.getElementById("confirm-file-name").textContent=t.fileName,document.getElementById("confirm-artifact-type").textContent=t.artifactType,document.getElementById("confirm-file-size").textContent=`${(t.content.length/1024).toFixed(1)} KB`,document.getElementById("confirm-line-count").textContent=i?`${i.fileEntries.length} files`:t.content.split(` -`).length,ww();const r=document.getElementById("confirm-deps-list"),s=document.getElementById("confirm-deps-section");n&&Object.keys(n).length>0?(r.innerHTML=Object.entries(n).map(([u,c])=>{const d=c?`at least ${Xt(c)}`:"version resolved from your project";return`
  • • ${Xt(u)}: ${d}
  • `}).join(""),s.classList.remove("hidden")):s.classList.add("hidden");const o=document.getElementById("confirm-warnings-list"),a=document.getElementById("confirm-warnings-section");e.warnings&&e.warnings.length>0?(o.innerHTML=e.warnings.map(u=>`
  • • ${Xt(u)}
  • `).join(""),a.classList.remove("hidden")):a.classList.add("hidden"),document.getElementById("confirm-code-preview").textContent=t.content,document.getElementById("code-preview-content").classList.add("hidden"),document.getElementById("code-preview-chevron").style.transform="rotate(0deg)";const l=document.getElementById("commit-confirm-modal");l&&He(l)}function op(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&We(e),zi=null}function Ew(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&We(e);const n=["success-message","success-project-id","success-file-name","success-artifact-type","success-time","success-size"];for(const s of n){const o=document.getElementById(s);o&&(o.textContent="")}const i=document.getElementById("success-warnings-section");i&&i.classList.add("hidden");const r=document.getElementById("success-warnings-list");r&&(r.innerHTML="")}function ap(t){const e=(m,v)=>{const S=document.getElementById(m);S&&(S.textContent=v||"")},n=t.metadata?.fileName||"",i=t.metadata?.projectId||"",r=t.metadata?.artifactType||"",s=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",i),e("success-file-name",n),e("success-artifact-type",r),e("success-time",s),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&i&&(u.href=`https://app.flutterflow.io/project/${i}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),f=t.unverified||[],h=t.approximate||[],p=t.warnings||[];(p.length>0||f.length>0||h.length>0)&&c&&d&&(d.innerHTML=[...f.map(m=>`
  • Not verified before deploying: ${q(String(m))}
  • `),...h.map(m=>`
  • Verified approximately: ${q(String(m))}
  • `),...p.map(([m,v])=>`
  • ${q(m)}: ${q(String(v))}
  • `)].join(""),c.classList.remove("hidden"));const g=document.getElementById("commit-success-modal");g&&He(g)}function lp(t){Jl(),U0(t)}function cp(t,{heading:e,title:n,guidance:i}){const r=t.targetIdentity||{},s=document.getElementById("commit-terminal-modal");if(!s)return!1;const o=(h,p)=>{const g=document.getElementById(h);g&&(g.textContent=p||"")};o("terminal-heading",e),o("terminal-title",n),o("terminal-message",t.error||t.message||"");const a=document.getElementById("terminal-identity-list");if(a){const h=[["Project",r.projectId||t.metadata?.projectId],["Endpoint",r.endpoint],["File",r.fileName||t.metadata?.fileName],["Artifact",r.artifactType||t.metadata?.artifactType]];a.innerHTML=h.map(([p,g])=>`
    ${q(p)}:${q(String(g??"—"))}
    `).join("")}const l=document.getElementById("terminal-file-outcomes");let u=t.errorMap;u&&!(u instanceof Map)&&(u=new Map(Object.entries(u))),l&&u&&u.size>0?(l.innerHTML=[...u.entries()].map(([h,p])=>`
  • ${q(h)}: ${q(Sl(p))}
  • `).join(""),l.classList.remove("hidden")):l&&l.classList.add("hidden");const c=document.getElementById("terminal-guidance");c&&(c.innerHTML=i);const d=document.getElementById("terminal-open-ff-link"),f=r.projectId||t.metadata?.projectId;return d&&(d.href=f?`https://app.flutterflow.io/project/${f}`:"https://app.flutterflow.io/"),He(s),!0}function up(t){cp(t,{heading:"Deploy partially applied",title:"Some custom classes reached FlutterFlow, but the deploy did not fully complete.",guidance:"The custom classes the runner confirmed are already in your project and are not lost. Review the per-file errors above, fix them in FlutterFlow or regenerate, then deploy again. Open the project to see exactly what landed."})}function dp(t){cp(t,{heading:"Deploy outcome not yet known",title:"This browser stopped waiting before the FlutterFlow server reported a result.",guidance:"The deploy may still be finishing on the server — it was not cancelled. Open your FlutterFlow project and confirm whether the class landed before retrying, so you do not push a duplicate or build on top of an unknown state."})}function Sw(t){t&&t.target!==t.currentTarget||We(document.getElementById("commit-terminal-modal"))}function xw(){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 rd={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}},Iw=[{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..."}],Oe={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&&(Eu(e,!0,"Deploying to FlutterFlow"),He(e)),this.set("prepare")},set(t,e=null){if(!(!rd[t]||t===this.phaseId)){if(!this.sequence.includes(t)){const n=this.sequence.indexOf("package");this.sequence.splice(n===-1?this.sequence.length:n,0,t)}this.phaseId=t,this.phaseStartedAt=Date.now(),this.substatus=e,this.liveSubstatus=!1,this.render(),this.timer&&clearInterval(this.timer),t!=="done"&&(this.timer=setInterval(()=>this.render(),500))}},setSubstatus(t){t&&(this.liveSubstatus=!0,this.substatus=t,this.render())},render(){const t=rd[this.phaseId];if(!t)return;const e=(Date.now()-this.phaseStartedAt)/1e3,n=t.start+(t.end-t.start)*(1-Math.exp(-e/25));if(this.phaseId==="provision"&&!this.liveSubstatus){const o=Iw.filter(a=>e>=a.after).pop();o&&(this.substatus=o.text)}const i=this.sequence.indexOf(this.phaseId),s=[`Step ${i===-1?1:i+1} of ${this.sequence.length}`];e>=5&&s.push(kw(e)),hp(this.phaseId==="done"?100:n,t.message,s.join(" · "),this.substatus)},stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.phaseId=null;const t=document.getElementById("commit-progress-overlay");t&&(Eu(t,!1),We(t,{force:!0,restoreFocus:!1}))}};function kw(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 fp(t){Oe.start(t)}function Jl(){Oe.stop()}function hp(t,e,n,i=null){const r=document.getElementById("commit-progress-bar"),s=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");r&&(r.style.width=`${Math.round(t*10)/10}%`),s&&(s.textContent=e),o&&(o.textContent=n),a&&(a.textContent=i||"",a.classList.toggle("hidden",!i))}function sd(t){const e={[ee.PREPARING]:"prepare",[ee.VALIDATING]:"validate",[ee.PUSHING]:"project",[ee.SUCCESS]:"done"};if(t===ee.ERROR){Oe.timer&&clearInterval(Oe.timer),Oe.timer=null,hp(100,"Failed","Error occurred");return}const n=e[t];n&&Oe.set(n)}function Cw(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===J.CODE_FILE):t.codeInfo?.codeType===J.CODE_FILE}let pp=!1;function gp(t){pp=t;const e=document.querySelector("#commit-confirm-modal button[data-deploy-confirm]");e&&(e.disabled=t),[...document.querySelectorAll("[data-deploy-start]"),...document.querySelectorAll("#btn-deploy-to-ff")].forEach(i=>{i.disabled=t})}function od(t){Jl(),gp(!1);const e=yh(t);e===Xe.COMMITTED?ap(t):e===Xe.PARTIAL?up(t):e===Xe.UNCONFIRMED?dp(t):lp(t)}async function Aw(){if(!zi){console.error("No pending commit data");return}if(pp){console.warn("Deploy already in flight; ignoring duplicate confirm.");return}const t=zi;if(zi=null,qi=bw(),op(),gp(!0),fp({withProvisioning:Cw(t)}),t.bundlePlan){const o=await F0(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});qi=null,od(o);return}const{codeInfo:e}=t,{artifactType:n,artifactName:i,fileName:r}=Bh(),s=await P0(e.content,{artifactType:n,artifactName:i,fileName:r,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});qi=null,od(s)}window.runThinkingPipeline=sr;window.toggleStep=$0;window.toggleSection=T0;window.selectWorkflowStep=nt;window.copyCode=M0;window.retryWithDifferentModel=B0;window.openApiKeysModal=Tl;window.closeApiKeysModal=Lh;window.openComposerSettings=r0;window.closeComposerSettings=s0;window.walkthroughConnectAccount=i0;window.closeWalkthroughModal=a0;window.openWalkthroughModal=o0;window.advanceWalkthrough=$l;window.commitToFlutterFlow=A0;function Pw(){const t=document.getElementById("pipeline-input");t&&t.focus()}function Fw(){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=Pw;window.openModelSelector=Fw;window.handlePromptImageSelect=Hy;window.removePromptImage=Wy;window.saveApiKeys=u0;window.validateFlutterFlowConnection=Ll;window.clearAllApiKeys=d0;window.toggleKeyVisibility=v0;window.handleWelcomeVideoEnd=yw;window.dismissWelcomeVideo=Nn;window.initiateCommitToFlutterFlow=D0;window.updateFlutterFlowCredentialStatus=H0;window.openCommitConfirmModal=Yl;window.closeCommitConfirmModal=op;window.closeCommitSuccessModal=Ew;window.closeCommitTerminalModal=Sw;window.showCommitPartialModal=up;window.showCommitUnconfirmedModal=dp;window.showCommitSuccessModal=ap;window.showCommitFailureModal=lp;window.toggleCodePreview=xw;window.confirmCommitToFlutterFlow=Aw;window.runRefinement=Vh;window.regenerateFromPastedErrors=Kh;window.clearErrorInput=O0;window.setFlutterFlowEndpoint=n0;window.getFlutterFlowEndpoint=_t;window.commitProgress=Oe;window.openSignInModal=qs;window.closeSignInModal=Qh;window.handleMagicLinkRequest=V0;window.handleSignOut=K0;window.handleSendNewLink=Z0;window.handleClearCache=X0;window.handleDeleteAccount=Q0;window.closeDeleteUnavailableModal=ew;window.startCheckout=dw;window.openCustomerPortal=fw;window.openPricingModal=di;window.closePricingModal=sp;let Dr=null,mp=null,On={1:"pending",2:"pending",3:"pending"},Zl=1,Xl=null;const Vs={1:"Prompt Architect",2:"Code Generator",3:"Code Review"},Rw={1:"Understanding your prompt",2:"Generating Dart code",3:"Running the code audit"},Tw={1:"Prompt understood",2:"Dart code generated",3:"Code audit complete"};function Ks(){return y.runId+=1,y.runId}function re(t){return t===void 0||t===y.runId}function $w(){y.runId+=1}function Ql(t){return document.getElementById(`pdot-${t}`)}function Ya(t){const e=document.getElementById("btn-run-pipeline")||document.getElementById("hero-send");e&&(e.disabled=t,e.classList.toggle("is-busy",t),t?e.setAttribute("aria-busy","true"):e.removeAttribute("aria-busy"))}function Ys(t){const e=document.getElementById("pipeline-progress");e&&(e.dataset.runState=t)}function Rn(t,e){On[t]=e;const n=Ql(t);if(!n)return;n.dataset.state=e,n.disabled=e==="pending"||e==="skipped";const i=Vs[t],r={pending:"not started",active:"in progress",done:"complete",failed:"failed",skipped:"not run"};n.setAttribute("aria-label",`Step ${t} of 3, ${i}: ${r[e]||e}`),e==="active"?n.setAttribute("aria-current","step"):n.removeAttribute("aria-current")}function Mw(){return[1,2,3].filter(t=>On[t]==="done").length}function Js(){const t=document.getElementById("pipeline-progress-fill");t&&(t.style.width=`${Mw()/3*100}%`);const e=document.getElementById("progress-stage-count");e&&(e.textContent=`Step ${Zl} of 3`)}function Zs(t,{done:e=!1}={}){const n=document.getElementById("progress-title-text"),i=document.getElementById("progress-substep-text"),r=On[t],s=e||r==="done";if(n&&(n.textContent=s?Tw[t]:Rw[t]),i){const o=s?" — complete":r==="failed"?" — stopped":"";i.textContent=`Step ${t} of 3 — ${Vs[t]}${o}`}}function Lw(t){On[t]==="pending"||On[t]==="skipped"||(Xl=t,[1,2,3].forEach(e=>{const n=Ql(e);n&&n.setAttribute("aria-pressed",String(e===t))}),Zs(t))}function ec(){Xl=null,[1,2,3].forEach(t=>{const e=Ql(t);e&&e.removeAttribute("aria-pressed")})}function vp(t){const e=document.getElementById("pipeline-note");e&&(e.textContent=t||"",e.hidden=!t)}function Nw(t,e,n){re(n)&&vp(`${Gt(t)} did not answer. Continuing on ${Gt(e)}.`)}function tc(){const t=document.getElementById("pipeline-failure");if(!t)return;t.hidden=!0;const e=document.getElementById("pipeline-failure-actions");e&&e.replaceChildren()}const Ow=1120;function Bw(){const t=getComputedStyle(document.documentElement).getPropertyValue("--t-morph").trim(),e=Number.parseFloat(t);return Number.isFinite(e)&&e>0?e:Ow}let Qn=null,jr=null;function Dw(){return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0}function un(){if(jr){try{jr.cancel()}catch{}jr=null}Qn&&(Qn.remove(),Qn=null),window.removeEventListener("resize",un)}function _p(t,e){if(un(),Dw()||!t||!e||!document.body||typeof Element.prototype.animate!="function")return;const n=t.getBoundingClientRect(),i=e.getBoundingClientRect();if(!n.width||!n.height||!i.width||!i.height)return;const r=document.createElement("div");r.className="composer-morph",r.setAttribute("aria-hidden","true"),r.style.cssText=`left:${i.left}px;top:${i.top}px;width:${i.width}px;height:${i.height}px;opacity:0;`,document.body.appendChild(r);const s=n.left+n.width/2-(i.left+i.width/2),o=n.top+n.height/2-(i.top+i.height/2),a=n.width/i.width,l=n.height/i.height,u=`translate(${s}px,${o}px) scale(${a},${l})`,c=r.animate([{transform:u,opacity:0,offset:0,easing:"cubic-bezier(.2,0,0,1)"},{transform:u,opacity:1,offset:.14,easing:"cubic-bezier(.4,0,.2,1)"},{transform:`translate(${s}px,${o}px) scale(${a*.93},${l*.93})`,opacity:1,offset:.28,easing:"cubic-bezier(.32,1.38,.5,1)"},{transform:"translate(0px,0px) scale(1,1)",opacity:1,offset:1}],{duration:Bw(),fill:"both"});Qn=r,jr=c,window.addEventListener("resize",un),c.onfinish=()=>{if(Qn!==r)return;const d=r.animate([{opacity:1},{opacity:0}],{duration:260,fill:"forwards"});d.onfinish=()=>{Qn===r&&un()}}}function jw(){const e=document.getElementById("composer")?.getBoundingClientRect();e&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{_p({getBoundingClientRect:()=>e},document.getElementById("main-stage-container"))})})}function Uw(){_p(document.getElementById("pipeline-progress"),document.getElementById("main-stage-container"))}window.addEventListener("hashchange",un);window.addEventListener("popstate",un);function Xs(t={}){const{prompt:e=null,runId:n}=t;if(!re(n))return;eo(),tn(!0);const i=document.getElementById("pipeline-progress"),r=document.getElementById("results-view"),s=document.getElementById("ready-state");if(s&&s.classList.add("hidden"),r&&r.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),i&&i.classList.add("visible"),Ys("running"),e!==null){const a=document.getElementById("pipeline-submitted-prompt");a&&(a.textContent=e)}mp=Date.now();const o=document.getElementById("progress-elapsed");o&&(o.textContent="0s"),On={1:"pending",2:"pending",3:"pending"},ec(),tc(),vp(""),[1,2,3].forEach(a=>Rn(a,"pending")),Pt(1,n),Hw()}function Pt(t,e){re(e)&&(Zl=t,ec(),[1,2,3].forEach(n=>{n===t?Rn(n,"active"):nt&&Rn(n,"pending")}),Zs(t),Js())}function en(t,e){re(e)&&(Rn(t,"done"),Xl===null&&Zs(t,{done:!0}),Js())}function yp(t,{stage:e=1,runId:n,retry:i=wp}={}){if(!re(n))return;Qs(),eo(),un(),Ys("failed"),tn(!0);const r=document.getElementById("pipeline-progress");r&&r.classList.add("visible");const s=document.getElementById("results-view");s&&s.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),Rn(e,"failed"),[1,2,3].forEach(p=>{p>e&&Rn(p,"pending")}),Zl=e,ec(),Zs(e),Js();const o=bh(t),a=document.getElementById("pipeline-failure"),l=document.getElementById("pipeline-failure-title"),u=document.getElementById("pipeline-failure-message"),c=document.getElementById("pipeline-failure-hint"),d=document.getElementById("pipeline-failure-actions");if(!a||!l||!u||!d)return;if(a.dataset.kind=o.kind,l.textContent=`${Vs[e]}: ${o.title}`,u.textContent=o.message,c){const p=o.detail&&o.detail!==o.message?o.detail:"";c.textContent=p,c.hidden=!p}d.replaceChildren();const f=[o.canUpgrade&&{id:"upgrade",label:"View plans",variant:"primary",onClick:()=>di()},o.canRetry&&{id:"retry",label:"Retry",variant:o.canUpgrade?"secondary":"primary",onClick:i},o.canEdit&&{id:"edit",label:"Edit prompt",variant:"secondary",onClick:Ja}].filter(Boolean);!o.canEdit&&!o.canRetry&&f.push({id:"edit",label:"Back to prompt",variant:"secondary",onClick:Ja}),f.forEach(p=>{const g=document.createElement("button");g.type="button",g.textContent=p.label,g.dataset.action=p.id,g.dataset.variant=p.variant,g.addEventListener("click",p.onClick),d.appendChild(g)}),a.hidden=!1;const h=d.querySelector("button");h&&h.focus({preventScroll:!0})}function Ja(){$w(),hw(),y.isRunning=!1,Ya(!1),nn(),Ys("settled"),un(),Qs(),eo(),tc();const t=document.getElementById("pipeline-progress");t&&t.classList.remove("visible"),tn(!1);const e=document.getElementById("pipeline-input");e&&(y.submittedPrompt&&(e.value=y.submittedPrompt,e.dispatchEvent(new Event("input",{bubbles:!0}))),e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length))}function wp(){const t=document.getElementById("pipeline-input");t&&y.submittedPrompt&&(t.value=y.submittedPrompt,t.dispatchEvent(new Event("input",{bubbles:!0}))),Ne=y.submittedImages.slice(),ln(),tc(),sr()}function Hw(){Qs(),Dr=setInterval(()=>{const t=(Date.now()-mp)/1e3,e=document.getElementById("progress-elapsed");e&&(e.textContent=`${Math.floor(t)}s`)},250)}function Qs(){Dr&&(clearInterval(Dr),Dr=null)}let Gi=null;function eo(){Gi&&(clearTimeout(Gi),Gi=null)}function lr(){Qs(),eo(),Ys("settled"),Js();const t=document.getElementById("pipeline-progress-fill");Gi=setTimeout(()=>{Gi=null;const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function Tn(t,e=""){const n={pass:'',warning:'',fail:'',info:''};return``}function bp(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function Ww(){return p_({bundle:y.artifactBundle,reviewResult:y.step3Result})}function qw(t){return` -
    +`;const o=nh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:s});Zs({runId:i}),Pt(2,i),nt(2),Ae(2,!0);const a=await Us(o,n,[],i);if(!re(i))return;y.step2Result=a,Bs(),tn(2,i);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),nt(3),Pt(3,i),Ae(3,!0);const c=await Hs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,Ds(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const f=Ls(y.step3Result);ur(u,f)}catch(s){if(console.error("Regeneration failed:",s),!re(i))return;const o=Ms(s,{architect:2,generator:2,review:3});s.isUsageLimit&&un(),nt(o),Ae(o,!1),vp(s,{stage:o,runId:i,retry:()=>Kh(t,e)}),bs(o,"error")}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function D0(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const n=await Te("flutterflow"),i=await Te("flutterflow_project_id");n&&i?(t.className="w-2 h-2 rounded-full bg-green-500",e.textContent="FlutterFlow credentials configured",e.className="text-green-600"):n||i?(t.className="w-2 h-2 rounded-full bg-yellow-500",e.textContent="FlutterFlow credentials incomplete",e.className="text-yellow-600"):(t.className="w-2 h-2 rounded-full bg-red-500",e.textContent="FlutterFlow credentials not configured",e.className="text-red-600")}async function Yh(t){try{const e=await fetch(`${vt}/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 j0(t){try{const n=await(await fetch(`${vt}/auth/verify-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})})).json();if(n.error||!n.email||!n.sessionToken)throw new Error(n.error||"Invalid or expired link");return n}catch(e){throw console.error("verifyMagicLink failed:",{message:e.message,stack:e.stack}),e}}async function U0(t){try{const e=await fetch(`${vt}/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:`${vt}/auth/refresh-session`,status:e.status}),null;const n=await e.json();return n.error||!n.email||!n.sessionToken?(console.warn("refreshSession: validation failed",{error:n.error,hasEmail:!!n.email,hasToken:!!n.sessionToken}),null):n}catch(e){return console.error("refreshSession: fetch failed",{url:`${vt}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function td(t,e){const n=Zh(),i=(z.email||n.email)!==t;z.email=t,z.sessionToken=e,z.isVerified=!0,ce=Mn({isLoading:!0}),localStorage.setItem(hs,JSON.stringify({email:t,sessionToken:e})),i&&ip()}function Jh(){z.email=null,z.sessionToken=null,z.isVerified=!1,ce=Mn({isResolved:!0}),localStorage.removeItem(hs),localStorage.removeItem(gs)}function Zh(){try{const t=localStorage.getItem(hs);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(hs),{email:null,sessionToken:null}}}async function H0(){const e=new URLSearchParams(window.location.search).get("token");if(e){window.history.replaceState({},"",window.location.pathname+window.location.hash);try{const{email:n,sessionToken:i}=await j0(e);td(n,i),Xh();const r=nd();r&&!window.location.hash&&(window.location.hash=r)}catch(n){nd();const i=n.message||"Sign-in link invalid or expired.";Ee(i,"error"),Ws(),Jn(i,"error")}}else{const{email:n,sessionToken:i}=Zh();if(n&&i){const r=await U0(i);r?td(r.email,r.sessionToken):Jh()}}Vl()}function W0(){try{localStorage.setItem(Na,JSON.stringify({hash:window.location.hash||"#home",ts:Date.now()}))}catch(t){console.warn("rememberSignInReturnSurface: failed to persist return surface:",t)}}function nd(){try{const t=localStorage.getItem(Na);if(localStorage.removeItem(Na),!t)return null;const{hash:e,ts:n}=JSON.parse(t);return!e||typeof n!="number"||Date.now()-n>Iy?null:e}catch(t){return console.warn("consumeSignInReturnSurface: failed to read return surface:",t),null}}function Ws(){const t=document.getElementById("signin-modal");if(!t)return;W0(),document.getElementById("signin-email-input")?.removeAttribute("aria-invalid"),Jn(""),He(t)}function Xh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&We(e)}function Jn(t,e){const n=document.getElementById("signin-message");n&&(n.textContent=t||"",n.classList.remove("signin-message-success","signin-message-error"),e&&n.classList.add(`signin-message-${e}`))}async function q0(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),n=Fs(t?.value);if(!n||!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(n)||n.length>254){t?.setAttribute("aria-invalid","true"),Jn("Please enter a valid email address.","error");return}t?.removeAttribute("aria-invalid"),e&&(e.disabled=!0,e.textContent="Sending…");const r=uh(n);r&&Jn(r,"error");try{const s=await Yh(n),o=s?.code===ch;t&&!o&&(t.value=""),t?.setAttribute("aria-invalid",String(o)),Jn(dh(s,n),o?"error":"success"),e&&(e.disabled=!1,e.textContent=o?"Send Sign-in Link":"Sent!",o||setTimeout(()=>{e.textContent==="Sent!"&&(e.textContent="Send Sign-in Link")},2500))}catch(s){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:n,err:s}),Jn("Something went wrong. Please try again.","error"),e&&(e.disabled=!1,e.textContent="Send Sign-in Link")}}function z0(){z.email=null,z.sessionToken=null,z.isVerified=!1,ce=Mn({isResolved:!0}),$_({storage:window.localStorage,onIdentityChanged:Vl,onPlanChanged:zs})}const V0=M_({sendLink:Yh,getEmail:()=>z.email||"",onState:G0});function G0(t){const e=document.getElementById("send-new-link-btn"),n=document.getElementById("send-new-link-msg");if(!e||!n)return;if(t.status==="pending"){e.disabled=!0,e.textContent="Sending…",n.className="acct-access-msg",n.textContent="Sending a fresh sign-in link…";return}if(t.status==="sent"){e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg",n.textContent=dh(t.data,z.email||"")||"Link sent — check your email.";return}e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg error";const i=t.error?.message?`Couldn't send a link right now. ${t.error.message}`:"Couldn't send a link right now. Please try again.";n.textContent=i}async function K0(){await V0()}function Y0(){const t=R_(window.localStorage),e=t.length?`Cleared disposable UI caches: ${t.join(", ")}.`:"Nothing disposable to clear.";Ee(`${e} Your run count, identity and stored keys are kept.`,"info")}function J0(){const t=document.getElementById("delete-unavailable-modal");t&&He(t,{trigger:document.activeElement})}function Z0(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("delete-unavailable-modal");e&&We(e)}function Vl(){const t=z.isVerified&&!!z.email,e=document.getElementById("auth-signedout"),n=document.getElementById("auth-signedin"),i=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),n&&n.classList.toggle("hidden",!t),i&&i.classList.toggle("hidden",t);const r=document.getElementById("auth-user-email");r&&(r.textContent=z.email||"");const s=document.getElementById("access-signed-email");s&&(s.textContent=z.email||""),aw(),zs()}async function Qh(){try{if(typeof FingerprintJS>"u"){console.warn("resolveIdentity: FingerprintJS not loaded, skipping");return}const e=await(await FingerprintJS.load()).get(),n=e.visitorId,i=await fetch(Py,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fingerprint:e.visitorId,cookie_id:n})});if(!i.ok)throw new Error(`Identity check HTTP ${i.status}`);const r=await i.json();if(ft.userId=r.user_id,ft.token=r.identity_token||null,ft.status=r.status,ft.resolved=!0,sessionStorage.setItem(Cy,r.user_id),ft.token&&sessionStorage.setItem(Ay,ft.token),r.usage_count!==void 0){const s=gn(),a=(r.usage_month||s)===s?r.usage_count:0;localStorage.setItem(Fn,JSON.stringify({count:a,month:s})),un()}console.log(`Identity resolved: ${r.status} (${r.user_id.slice(0,8)}...) usage: ${r.usage_count??"n/a"}`)}catch(t){console.error("resolveIdentity failed:",t)}}let Wo=null;function X0(t=5e3){return ft.resolved?Promise.resolve():(Wo||(Wo=Qh().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([Wo,new Promise(e=>setTimeout(e,t))]))}function ep(){const t=gn();try{const e=localStorage.getItem(Fn);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Fn,month:t,err:e}),localStorage.removeItem(Fn),{count:0,month:t}}}function gn(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function lr(){const t=ep();return t.month!==gn()?{count:0,month:gn()}:t}function Q0(){const e={count:lr().count+1,month:gn()};return localStorage.setItem(Fn,JSON.stringify(e)),e}function pi(){return!!ce.isLoading}function Rt(){return!!ce.isResolved}function ew(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(ps,e)?e:null}function tw(t){return t&&Object.entries(Eh).find(([,e])=>e===t)?.[0]||null}function Cr(...t){return t.find(e=>e!=null&&e!=="")}function nw(...t){return t.find(e=>e&&typeof e=="object")||{}}function iw(t){const e=t.data&&typeof t.data=="object"?t.data:t,n=nw(e.subscription,e.stripeSubscription,e.currentSubscription,e.customer?.subscriptions?.data?.[0],e.subscriptions?.data?.[0],e.subscriptions?.[0]),i=e.metadata||n.metadata||e.customer?.metadata||{},r=Cr(e.priceId,e.price_id,e.stripePriceId,e.stripe_price_id,n.priceId,n.price_id,n.plan?.id,n.price?.id,n.items?.data?.[0]?.price?.id,n.items?.[0]?.price?.id,n.lines?.data?.[0]?.price?.id),s=Cr(e.status,e.subscriptionStatus,e.subscription_status,n.status,"none"),o=ew(Cr(e.tier,e.plan,e.planId,e.plan_id,e.subscriptionTier,e.subscription_tier,e.product,e.productName,n.tier,n.plan,i.tier,i.plan)),a=Fy.has(String(s).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||tw(r)||(a||l?"professional":"free");return Mn({tier:u,status:s,periodEnd:Cr(e.periodEnd,e.currentPeriodEnd,e.current_period_end,n.current_period_end,n.periodEnd,null),isResolved:!0})}function qs(){return ps[ce.tier]??ps.free}async function rw(){if(z.isVerified&&(!Rt()||pi())&&(await np({force:!0}),zs()),z.isVerified&&!Rt())return Ee("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=lr(),e=qs();if(t>=e)return tp(t,e,{openModal:!0}),!1;const n=Math.floor(e*.8);if(t>=n){const i=e-t;Ee(`${i} run${i===1?"":"s"} remaining this month.`,"warning")}return!0}function id(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function tp(t,e,n={}){nn(!0);const i=document.getElementById("walkthrough-modal");i&&We(i,{restoreFocus:!1});const r=document.getElementById("ready-state");r&&r.classList.add("hidden");const s=document.getElementById("preview-frame-container");s&&(s.style.display="none");const o=document.getElementById("main-stage-container");o&&o.classList.add("visible");const a=document.getElementById("results-view");a&&a.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar");const l=document.getElementById("pipeline-progress");l&&l.classList.remove("visible");const u=document.getElementById("paywall-exhausted");if(!u){Ee(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),di();return}const c=document.getElementById("paywall-exhausted-text");if(c){const f=ce.tier;f==="free"?c.textContent=`You've used all ${e} free generations this month. Upgrade to Pro for 50 generations/month and access to all AI models.`:c.textContent=`You've used all ${e} generations this month on your ${f} plan. Your limit resets next month.`}const d=document.getElementById("paywall-signin-btn");d&&d.classList.toggle("hidden",z.isVerified),u.classList.remove("hidden"),n.openModal&&di()}function za(t){return ce.tier==="free"&&Nr.includes(t)?ms:t}function sw(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const n=ce.tier,r=!(z.isVerified&&!Rt())&&n==="free";Array.from(e.options).forEach(o=>{const a=Vt(o.value),l=Nr.includes(o.value);o.textContent=l&&r?`${a} (PRO)`:a,o.disabled=!1}),r&&Nr.includes(e.value)&&(e.value=ms),e.disabled=!1,qu.has(e)||(e.addEventListener("change",()=>{Rt()&&ce.tier==="free"&&Nr.includes(e.value)&&(e.value=ms,di()),qa(e.value),kl()}),qu.add(e));let s=document.getElementById("model-selector-free-notice");r?(s||(s=document.createElement("p"),s.id="model-selector-free-notice",s.className="text-xs text-gray-400 mt-1",t.appendChild(s)),s.innerHTML='Free plan — Gemini only. '):s&&s.remove(),qa(e.value)}function Gl(){const t=z.isVerified&&!!z.email,e=t&&pi(),n=!t||Rt(),i=lr(),r=n?i.count:0,s=n?qs():0,o=Math.max(0,s-r),a=`${r} / ${s} runs this month`,l=gl,u=n?ce.tier||"free":null,c=document.getElementById("topbar-credits-count");c&&(e?c.textContent="…":n?c.textContent=String(o):c.textContent="—");const d=document.getElementById("credits-balance");d&&(e?d.textContent="Checking plan…":n?d.textContent=a:d.textContent="Plan check failed");const f=document.getElementById("usage-dialog-tier");f&&(e?f.textContent="Checking…":n?f.textContent=l[u]||"Free":f.textContent="Unavailable");const h=document.getElementById("usage-dialog-status");h&&(e?h.textContent="Verifying your subscription…":n?h.textContent="Runs reset at the start of each month.":h.textContent="Could not verify your subscription. Try again or sign out.");const p=document.getElementById("usage-counter");if(p)if(e&&t)p.textContent="Checking plan…",p.className="text-xs text-gray-500";else if(!n&&t)p.textContent="Plan check failed",p.className="text-xs text-red-600 font-medium";else{p.textContent=a;const g=s>0?r/s:0;p.className=g>=1?"text-xs text-red-600 font-medium":g>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500"}if(!t){const g=document.getElementById("guest-usage-text");if(g){const m=ep(),v=m.month===gn()?m.count??0:0;g.textContent=`${v} / ${ps.free} generations used`}}ow()}function ow(){if(!(z.isVerified&&!!z.email))return;const e=pi(),n=Rt(),i=lr(),r=n?i.count:0,s=n?qs():0,o=Math.max(0,s-r),a=n?ce.tier||"free":null,l={free:"Free",professional:"Pro",power:"Power"}[a]||"Free",u=z.email||"",c=u.split("@")[0]||u,d=document.getElementById("acct-avatar");d&&(d.textContent=(u[0]||"?").toUpperCase());const f=document.getElementById("acct-name");f&&(f.textContent=c||"—");const h=document.getElementById("acct-plan-tier"),p=document.getElementById("acct-plan-price"),g=document.getElementById("acct-plan-note"),m=document.getElementById("acct-renewal");if(h&&(h.textContent=e?"Checking…":n?l:"Plan unavailable"),p)if(e)p.textContent="—";else if(!n)p.textContent="—";else if(a==="free")p.textContent="$0 / month";else{const E=Oi(Ni[a]??0,Cl());p.textContent=`${E} / month`}if(g&&(e?g.textContent="Verifying your subscription…":n?a==="free"?g.textContent="No subscription. Upgrade for more generations.":g.textContent="billed monthly through Stripe":g.textContent="Could not verify your subscription. Check billing or sign out."),m){const E=Date.parse(ce.periodEnd||""),P=n&&a!=="free"&&!!ce.periodEnd&&!Number.isNaN(E);if(e)m.textContent="";else if(!n)m.textContent="";else if(a==="free")m.textContent="";else if(P){const $=new Date(E).toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"});m.textContent=`Renews ${$} · reset at the start of each month.`}else m.textContent="Renewal date is not available for this period."}const v=document.getElementById("acct-left-count"),S=document.getElementById("acct-left-limit"),b=document.getElementById("acct-reset-note");v&&(v.textContent=e?"…":n?String(o):"—"),S&&(S.textContent=e?"…":n?String(s):"—"),b&&(e?b.textContent="Checking plan…":n?b.textContent="Runs reset at the start of each month.":b.textContent="Plan check failed. Refresh or manage billing.");const _=document.getElementById("acct-used-count"),x=document.getElementById("acct-meter-fill"),I=document.getElementById("acct-meter-meta"),T=document.getElementById("acct-meter-track");if(_&&(_.textContent=e?"…":n?String(r):"—"),x){const E=n&&s>0?Math.min(100,Math.round(r/s*100)):0;x.style.width=`${E}%`}if(I)if(e)I.textContent="Checking…";else if(!n)I.textContent="Plan check failed";else if(s===0)I.textContent=`${r} of ${s}`;else{const E=Math.round(r/s*100);I.textContent=`${r} of ${s} · ${E}%`}T&&(e?T.setAttribute("aria-label","Checking usage…"):n?T.setAttribute("aria-label",`${r} of ${s} generations used`):T.setAttribute("aria-label","Usage unavailable")),mt()}function un(){if(Gl(),z.isVerified&&(pi()||!Rt())){id();return}const{count:t}=lr(),e=qs();t>=e&&!y.isRunning?tp(t,e):id()}function aw(){Gl()}async function np(t={}){const e=t.force===!0;if(!z.isVerified||!z.sessionToken){ce=Mn({isResolved:!0});return}ce={...ce,isLoading:!0,error:null};const n=localStorage.getItem(gs);if(!e&&n)try{const{data:i,email:r,ts:s,version:o}=JSON.parse(n);if(o===zu&&r===z.email&&Date.now()-s<300*1e3){ce={...i,isLoading:!1,isResolved:i.isResolved!==!1};return}}catch(i){console.warn("Failed to parse subscription cache:",i,"| raw value:",n)}try{const r=await(await fetch(`${vt}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:z.sessionToken,user_id:ft.userId})})).json();if(r.error){if(["unauthorized","invalid session","expired session"].some(o=>String(r.error).toLowerCase().includes(o))){Jh(),Vl();return}ce=Mn({isResolved:!1,error:r.error});return}ce=iw(r),localStorage.setItem(gs,JSON.stringify({version:zu,data:ce,email:z.email,ts:Date.now()}))}catch(i){console.error("fetchSubscription failed:",i),ce={...ce,isLoading:!1,isResolved:!1,error:i.message}}}function ip(){localStorage.removeItem(gs)}async function lw(t){if(!z.isVerified||!z.sessionToken){rp(),Ws();return}if(!Eh[t]){Ee("Invalid plan selected.","error");return}const e=document.getElementById(`checkout-btn-${t}`);e&&(e.disabled=!0,e.textContent="Redirecting…");try{const i=await(await fetch(`${vt}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:z.sessionToken,currency:Cl()})})).json();if(i.error||!i.url)throw new Error(i.error||"Failed to create checkout session");const{url:r}=i;window.location.href=r}catch(n){console.error("startCheckout failed:",n),e&&(e.disabled=!1,e.textContent="Subscribe"),Ee("Could not start checkout. Please try again.","error")}}async function cw(t){if(!z.isVerified||!z.sessionToken){Ws();return}const e=t||document.getElementById("manage-billing-btn"),n=e?e.textContent:"";e&&(e.disabled=!0,e.textContent="Loading…");try{const r=await(await fetch(`${vt}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:z.sessionToken})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to open billing portal");const{url:s}=r;window.location.href=s}catch(i){console.error("openCustomerPortal failed:",i),e&&(e.disabled=!1,e.textContent=n),Ee("Could not open billing portal. Please try again.","error")}}const Es=new Set;function uw(){Es.forEach(t=>t.abort()),Es.clear()}async function Ss(t,e,n,i={},r=[]){const o=new AbortController;Es.add(o);let a=!1;const l=setTimeout(()=>{a=!0,o.abort()},12e4);try{const u=await fetch(ky,{method:"POST",headers:{"Content-Type":"application/json",...ft.token?{Authorization:`Bearer ${ft.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:ft.userId,step:t,model:e,prompt:n,images:r,context:i})}),c=await u.text();let d={};try{d=c?JSON.parse(c):{}}catch{d={}}if(u.status===429){d.serverCount!==void 0&&(localStorage.setItem(Fn,JSON.stringify({count:d.serverCount,month:gn()})),un());const p=new Error(d.message||"Monthly usage limit reached. Upgrade to continue.");throw p.isUsageLimit=!0,p.pipelineStep=t,p}const f=wv(d,t);if(f)throw f;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(d),"content type:",typeof d.content),!u.ok)throw new Error(`${d.message||d.error||"BuildShip pipeline error"} (HTTP ${u.status})`);if(t==="generator")if(d.usage_status==="success"&&Number.isFinite(d.usage_count)){const p=gn();(d.usage_month||p)===p&&(localStorage.setItem(Fn,JSON.stringify({count:d.usage_count,month:p})),un())}else Q0(),un();let h=d.output||d.content;if(!h){const p=c?` (body: ${c.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${p}`)}return Array.isArray(h)&&(h=h.map(p=>typeof p=="string"?p:p.text||"").join("")),typeof h!="string"&&(h=JSON.stringify(h)),h}catch(u){if(u.name==="AbortError"){if(a)throw new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`);const c=new Error(`BuildShip ${t} request cancelled`);throw c.isPipelineCancel=!0,c}throw u instanceof TypeError?new Error(`BuildShip unreachable: ${u.message}`):u}finally{clearTimeout(l),Es.delete(o)}}let Va=!1;function dw(){const e=new URLSearchParams(window.location.search).get("checkout");return e==="success"?(window.history.replaceState({},"",window.location.pathname+window.location.hash),ip(),Va=!0):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname+window.location.hash),Ee("Checkout cancelled.","info")),e}function fw(){if(!Va)return;Va=!1;const t=ce.tier!=="free";Ee(t?"Subscription active! Your plan is live.":"Checkout complete — confirming your subscription. Check Manage billing if it does not update.",t?"success":"info")}function zs(){const t=z.isVerified&&!!z.email,e=ce.tier,n=t&&pi(),i=!t||Rt(),r=document.getElementById("subscription-tier-badge");if(r){const a=gl,l={free:"bg-gray-100 text-gray-600",professional:"bg-indigo-100 text-indigo-700",power:"bg-purple-100 text-purple-700",unresolved:"bg-red-50 text-red-600"};r.textContent=n?"Checking…":i?a[e]||"Free":"Plan unavailable",r.className=`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${i?l[e]||l.free:l.unresolved}`}const s=document.getElementById("upgrade-prompt");s&&s.classList.toggle("hidden",!t||n||!i||e!=="free");const o=document.getElementById("manage-billing-btn");o&&o.classList.toggle("hidden",!t||n||i&&e==="free"),hw(i?e:null),sw(),kl(),un(),Ep()}function hw(t){const e=["bg-gray-100","text-gray-500","cursor-default"];Object.entries({professional:{btnId:"checkout-btn-professional",defaultText:"Subscribe"},power:{btnId:"checkout-btn-power",defaultText:"Subscribe"}}).forEach(([r,{btnId:s,defaultText:o}])=>{const a=document.getElementById(s);a&&(r===t?(a.disabled=!0,a.textContent="Current plan",a.classList.add(...e)):(a.disabled=!1,a.textContent=o,a.classList.remove(...e)))});const i=document.getElementById("free-tier-current");i&&i.classList.toggle("hidden",t!=="free")}function pw(){document.querySelectorAll(".pm-card[data-tier]").forEach(t=>{const e=t.dataset.tier,n=av[e];if(!n)return;const i=t.querySelector("ul.pm-features");if(i){i.innerHTML="";for(const r of n){const s=document.createElement("li");s.textContent=r,i.appendChild(s)}}})}function Ga(){const t=Cl(),e=document.getElementById("pro-price"),n=document.getElementById("power-price"),i=document.getElementById("plans-pro-price"),r=document.getElementById("plans-power-price"),s=document.getElementById("pro-price-note"),o=document.getElementById("power-price-note"),a=document.getElementById("plans-pro-price-note"),l=document.getElementById("plans-power-price-note");e&&(e.textContent=Oi(Ni.professional,t)),n&&(n.textContent=Oi(Ni.power,t)),i&&(i.textContent=Oi(Ni.professional,t)),r&&(r.textContent=Oi(Ni.power,t));const u="billed monthly";s&&(s.textContent=u),o&&(o.textContent=u),a&&(a.textContent=u),l&&(l.textContent=u)}function di(){Ga();const t=document.getElementById("pricing-modal");t&&He(t),Uy().then(()=>Ga())}function rp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&We(e)}function Ee(t,e="info"){const n={success:"bg-green-600 text-white",error:"bg-red-600 text-white",warning:"bg-amber-500 text-white",info:"bg-gray-800 text-white"},i=document.createElement("div");i.className=`fixed bottom-6 left-1/2 -translate-x-1/2 px-5 py-3 rounded-lg text-sm font-medium shadow-lg z-50 transition-opacity duration-300 ${n[e]||n.info}`,i.textContent=t,document.body.appendChild(i),setTimeout(()=>{i.style.opacity="0",setTimeout(()=>i.remove(),300)},3500)}document.addEventListener("DOMContentLoaded",async()=>{rv(),hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),gw(),window.__heroField=X_(),window.__pipelineLogo=ny(),xh=Sy({onSubmit:or}),Oa=(async()=>{try{await H0(),dw(),await np()}catch(n){console.warn("Startup auth/subscription initialization failed:",n)}})(),await Oa,fw(),zs(),Ga(),pw(),await v0(),f0();const t=document.getElementById("flutterflow-endpoint-select");if(t){const n=_t();t.value=n}Nh(),Qh();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{en===2&&e.value.trim().length>0&&(Tl(),Ns())}),e.addEventListener("blur",()=>{const n=document.getElementById("walkthrough-modal");en===2&&n&&He(n)}),e.addEventListener("keydown",n=>{if(n.key==="Tab"){const i=document.getElementById("walkthrough-modal");en===2&&i&&setTimeout(()=>{He(i)},100)}})),window.addEventListener("commitStateChange",n=>{const{state:i}=n.detail;i===ee.PREPARING||i===ee.VALIDATING||i===ee.PUSHING?(Oe.phaseId||up(),sd(i)):(i===ee.SUCCESS||i===ee.ERROR)&&(sd(i),setTimeout(Jl,1e3))}),ic()});function gw(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function mw(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Nn),document.addEventListener("keydown",Nn))}function Nn(){const t=document.getElementById("preview-frame-container"),e=document.getElementById("main-stage-container"),n=document.getElementById("ready-state");t&&(t.style.display="none"),e&&e.classList.add("visible"),n&&n.classList.remove("hidden");const i=document.getElementById("welcome-video-player");i&&i.removeEventListener("click",Nn),document.removeEventListener("keydown",Nn),Nh()}let zi=null;async function vw(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++Ju,n=()=>e===Ju,i=await Te("flutterflow"),r=await Te("flutterflow_project_id");if(n()){if(!i){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const o=await new hi(i,"","main",_t()).listProjects();if(!n())return;if(!o||o.length===0){t.innerHTML='';return}t.innerHTML='',o.forEach(a=>{const l=document.createElement("option");l.value=a.id||a.projectId||"",l.textContent=a.name||a.projectName||`Project ${a.id}`,t.appendChild(l)}),r&&(t.value=r)}catch(s){if(!n())return;console.error("Failed to load projects for deploy:",s),t.innerHTML=''}}}function _w(){return document.getElementById("confirm-project-select")?.value?.trim()||null}function Kl(t,e,n,i=null){zi={codeInfo:t,checks:e,deps:n,bundlePlan:i},document.getElementById("confirm-file-name").textContent=t.fileName,document.getElementById("confirm-artifact-type").textContent=t.artifactType,document.getElementById("confirm-file-size").textContent=`${(t.content.length/1024).toFixed(1)} KB`,document.getElementById("confirm-line-count").textContent=i?`${i.fileEntries.length} files`:t.content.split(` +`).length,vw();const r=document.getElementById("confirm-deps-list"),s=document.getElementById("confirm-deps-section");n&&Object.keys(n).length>0?(r.innerHTML=Object.entries(n).map(([u,c])=>{const d=c?`at least ${Qt(c)}`:"version resolved from your project";return`
  • • ${Qt(u)}: ${d}
  • `}).join(""),s.classList.remove("hidden")):s.classList.add("hidden");const o=document.getElementById("confirm-warnings-list"),a=document.getElementById("confirm-warnings-section");e.warnings&&e.warnings.length>0?(o.innerHTML=e.warnings.map(u=>`
  • • ${Qt(u)}
  • `).join(""),a.classList.remove("hidden")):a.classList.add("hidden"),document.getElementById("confirm-code-preview").textContent=t.content,document.getElementById("code-preview-content").classList.add("hidden"),document.getElementById("code-preview-chevron").style.transform="rotate(0deg)";const l=document.getElementById("commit-confirm-modal");l&&He(l)}function sp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&We(e),zi=null}function yw(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&We(e);const n=["success-message","success-project-id","success-file-name","success-artifact-type","success-time","success-size"];for(const s of n){const o=document.getElementById(s);o&&(o.textContent="")}const i=document.getElementById("success-warnings-section");i&&i.classList.add("hidden");const r=document.getElementById("success-warnings-list");r&&(r.innerHTML="")}function op(t){const e=(m,v)=>{const S=document.getElementById(m);S&&(S.textContent=v||"")},n=t.metadata?.fileName||"",i=t.metadata?.projectId||"",r=t.metadata?.artifactType||"",s=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",i),e("success-file-name",n),e("success-artifact-type",r),e("success-time",s),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&i&&(u.href=`https://app.flutterflow.io/project/${i}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),f=t.unverified||[],h=t.approximate||[],p=t.warnings||[];(p.length>0||f.length>0||h.length>0)&&c&&d&&(d.innerHTML=[...f.map(m=>`
  • Not verified before deploying: ${q(String(m))}
  • `),...h.map(m=>`
  • Verified approximately: ${q(String(m))}
  • `),...p.map(([m,v])=>`
  • ${q(m)}: ${q(String(v))}
  • `)].join(""),c.classList.remove("hidden"));const g=document.getElementById("commit-success-modal");g&&He(g)}function ap(t){Jl(),B0(t),Yl(t,{heading:"Deploy failed",title:"FlutterFlow refused this deploy — nothing was confirmed written.",guidance:"Review the error and any per-file outcomes above, fix them in your code or in FlutterFlow, then deploy again. A refusal is definitive: no part of this deploy was applied, so retrying is safe once the problem is fixed."})}function Yl(t,{heading:e,title:n,guidance:i}){const r=t.targetIdentity||{},s=document.getElementById("commit-terminal-modal");if(!s)return!1;const o=(h,p)=>{const g=document.getElementById(h);g&&(g.textContent=p||"")};o("terminal-heading",e),o("terminal-title",n),o("terminal-message",t.error||t.message||"");const a=document.getElementById("terminal-identity-list");if(a){const h=[["Project",r.projectId||t.metadata?.projectId],["Endpoint",r.endpoint],["File",r.fileName||t.metadata?.fileName],["Artifact",r.artifactType||t.metadata?.artifactType]];a.innerHTML=h.map(([p,g])=>`
    ${q(p)}:${q(String(g??"—"))}
    `).join("")}const l=document.getElementById("terminal-file-outcomes");let u=t.errorMap;u&&!(u instanceof Map)&&(u=new Map(Object.entries(u))),l&&u&&u.size>0?(l.innerHTML=[...u.entries()].map(([h,p])=>`
  • ${q(h)}: ${q(El(p))}
  • `).join(""),l.classList.remove("hidden")):l&&l.classList.add("hidden");const c=document.getElementById("terminal-guidance");c&&(c.innerHTML=i);const d=document.getElementById("terminal-open-ff-link"),f=r.projectId||t.metadata?.projectId;return d&&(d.href=f?`https://app.flutterflow.io/project/${f}`:"https://app.flutterflow.io/"),He(s),!0}function lp(t){Yl(t,{heading:"Deploy partially applied",title:"Some custom classes reached FlutterFlow, but the deploy did not fully complete.",guidance:"The custom classes the runner confirmed are already in your project and are not lost. Review the per-file errors above, fix them in FlutterFlow or regenerate, then deploy again. Open the project to see exactly what landed."})}function cp(t){Yl(t,{heading:"Deploy outcome not yet known",title:"This browser stopped waiting before the FlutterFlow server reported a result.",guidance:"The deploy may still be finishing on the server — it was not cancelled. Open your FlutterFlow project and confirm whether the class landed before retrying, so you do not push a duplicate or build on top of an unknown state."})}function ww(t){t&&t.target!==t.currentTarget||We(document.getElementById("commit-terminal-modal"))}function bw(){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 rd={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}},Ew=[{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..."}],Oe={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&&(Eu(e,!0,"Deploying to FlutterFlow"),He(e)),this.set("prepare")},set(t,e=null){if(!(!rd[t]||t===this.phaseId)){if(!this.sequence.includes(t)){const n=this.sequence.indexOf("package");this.sequence.splice(n===-1?this.sequence.length:n,0,t)}this.phaseId=t,this.phaseStartedAt=Date.now(),this.substatus=e,this.liveSubstatus=!1,this.render(),this.timer&&clearInterval(this.timer),t!=="done"&&(this.timer=setInterval(()=>this.render(),500))}},setSubstatus(t){t&&(this.liveSubstatus=!0,this.substatus=t,this.render())},render(){const t=rd[this.phaseId];if(!t)return;const e=(Date.now()-this.phaseStartedAt)/1e3,n=t.start+(t.end-t.start)*(1-Math.exp(-e/25));if(this.phaseId==="provision"&&!this.liveSubstatus){const o=Ew.filter(a=>e>=a.after).pop();o&&(this.substatus=o.text)}const i=this.sequence.indexOf(this.phaseId),s=[`Step ${i===-1?1:i+1} of ${this.sequence.length}`];e>=5&&s.push(Sw(e)),dp(this.phaseId==="done"?100:n,t.message,s.join(" · "),this.substatus)},stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.phaseId=null;const t=document.getElementById("commit-progress-overlay");t&&(Eu(t,!1),We(t,{force:!0,restoreFocus:!1}))}};function Sw(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 up(t){Oe.start(t)}function Jl(){Oe.stop()}function dp(t,e,n,i=null){const r=document.getElementById("commit-progress-bar"),s=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");r&&(r.style.width=`${Math.round(t*10)/10}%`),s&&(s.textContent=e),o&&(o.textContent=n),a&&(a.textContent=i||"",a.classList.toggle("hidden",!i))}function sd(t){const e={[ee.PREPARING]:"prepare",[ee.VALIDATING]:"validate",[ee.PUSHING]:"project",[ee.SUCCESS]:"done"};if(t===ee.ERROR){Oe.timer&&clearInterval(Oe.timer),Oe.timer=null,dp(100,"Failed","Error occurred");return}const n=e[t];n&&Oe.set(n)}function xw(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===J.CODE_FILE):t.codeInfo?.codeType===J.CODE_FILE}let fp=!1;function hp(t){fp=t;const e=document.querySelector("#commit-confirm-modal button[data-deploy-confirm]");e&&(e.disabled=t),[...document.querySelectorAll("[data-deploy-start]"),...document.querySelectorAll("#btn-deploy-to-ff")].forEach(i=>{i.disabled=t})}function od(t){Jl(),hp(!1);const e=_h(t);e===Xe.COMMITTED?op(t):e===Xe.PARTIAL?lp(t):e===Xe.UNCONFIRMED?cp(t):ap(t)}async function Iw(){if(!zi){console.error("No pending commit data");return}if(fp){console.warn("Deploy already in flight; ignoring duplicate confirm.");return}const t=zi;if(zi=null,qi=_w(),sp(),hp(!0),up({withProvisioning:xw(t)}),t.bundlePlan){const o=await C0(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});qi=null,od(o);return}const{codeInfo:e}=t,{artifactType:n,artifactName:i,fileName:r}=Oh(),s=await k0(e.content,{artifactType:n,artifactName:i,fileName:r,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});qi=null,od(s)}window.runThinkingPipeline=or;window.toggleStep=F0;window.toggleSection=P0;window.selectWorkflowStep=nt;window.copyCode=R0;window.retryWithDifferentModel=L0;window.openApiKeysModal=Rl;window.closeApiKeysModal=Mh;window.openComposerSettings=t0;window.closeComposerSettings=n0;window.walkthroughConnectAccount=e0;window.closeWalkthroughModal=r0;window.openWalkthroughModal=i0;window.advanceWalkthrough=Tl;window.commitToFlutterFlow=I0;function kw(){const t=document.getElementById("pipeline-input");t&&t.focus()}function Cw(){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=kw;window.openModelSelector=Cw;window.handlePromptImageSelect=Dy;window.removePromptImage=jy;window.saveApiKeys=a0;window.validateFlutterFlowConnection=Ml;window.clearAllApiKeys=l0;window.toggleKeyVisibility=p0;window.handleWelcomeVideoEnd=mw;window.dismissWelcomeVideo=Nn;window.initiateCommitToFlutterFlow=N0;window.updateFlutterFlowCredentialStatus=D0;window.openCommitConfirmModal=Kl;window.closeCommitConfirmModal=sp;window.closeCommitSuccessModal=yw;window.closeCommitTerminalModal=ww;window.showCommitPartialModal=lp;window.showCommitUnconfirmedModal=cp;window.showCommitSuccessModal=op;window.showCommitFailureModal=ap;window.toggleCodePreview=bw;window.confirmCommitToFlutterFlow=Iw;window.runRefinement=Vh;window.regenerateFromPastedErrors=Gh;window.clearErrorInput=M0;window.setFlutterFlowEndpoint=Qy;window.getFlutterFlowEndpoint=_t;window.commitProgress=Oe;window.openSignInModal=Ws;window.closeSignInModal=Xh;window.handleMagicLinkRequest=q0;window.handleSignOut=z0;window.handleSendNewLink=K0;window.handleClearCache=Y0;window.handleDeleteAccount=J0;window.closeDeleteUnavailableModal=Z0;window.startCheckout=lw;window.openCustomerPortal=cw;window.openPricingModal=di;window.closePricingModal=rp;let jr=null,pp=null,On={1:"pending",2:"pending",3:"pending"},Zl=1,Xl=null;const Vs={1:"Prompt Architect",2:"Code Generator",3:"Code Review"},Aw={1:"Understanding your prompt",2:"Generating Dart code",3:"Running the code audit"},Pw={1:"Prompt understood",2:"Dart code generated",3:"Code audit complete"};function Gs(){return y.runId+=1,y.runId}function re(t){return t===void 0||t===y.runId}function Fw(){y.runId+=1}function Ql(t){return document.getElementById(`pdot-${t}`)}function Ka(t){const e=document.getElementById("btn-run-pipeline")||document.getElementById("hero-send");e&&(e.disabled=t,e.classList.toggle("is-busy",t),t?e.setAttribute("aria-busy","true"):e.removeAttribute("aria-busy"))}function Ks(t){const e=document.getElementById("pipeline-progress");e&&(e.dataset.runState=t)}function Rn(t,e){On[t]=e;const n=Ql(t);if(!n)return;n.dataset.state=e,n.disabled=e==="pending"||e==="skipped";const i=Vs[t],r={pending:"not started",active:"in progress",done:"complete",failed:"failed",skipped:"not run"};n.setAttribute("aria-label",`Step ${t} of 3, ${i}: ${r[e]||e}`),e==="active"?n.setAttribute("aria-current","step"):n.removeAttribute("aria-current")}function Rw(){return[1,2,3].filter(t=>On[t]==="done").length}function Ys(){const t=document.getElementById("pipeline-progress-fill");t&&(t.style.width=`${Rw()/3*100}%`);const e=document.getElementById("progress-stage-count");e&&(e.textContent=`Step ${Zl} of 3`)}function Js(t,{done:e=!1}={}){const n=document.getElementById("progress-title-text"),i=document.getElementById("progress-substep-text"),r=On[t],s=e||r==="done";if(n&&(n.textContent=s?Pw[t]:Aw[t]),i){const o=s?" — complete":r==="failed"?" — stopped":"";i.textContent=`Step ${t} of 3 — ${Vs[t]}${o}`}}function Tw(t){On[t]==="pending"||On[t]==="skipped"||(Xl=t,[1,2,3].forEach(e=>{const n=Ql(e);n&&n.setAttribute("aria-pressed",String(e===t))}),Js(t))}function ec(){Xl=null,[1,2,3].forEach(t=>{const e=Ql(t);e&&e.removeAttribute("aria-pressed")})}function gp(t){const e=document.getElementById("pipeline-note");e&&(e.textContent=t||"",e.hidden=!t)}function $w(t,e,n){re(n)&&gp(`${Vt(t)} did not answer. Continuing on ${Vt(e)}.`)}function tc(){const t=document.getElementById("pipeline-failure");if(!t)return;t.hidden=!0;const e=document.getElementById("pipeline-failure-actions");e&&e.replaceChildren()}const Mw=1120;function Lw(){const t=getComputedStyle(document.documentElement).getPropertyValue("--t-morph").trim(),e=Number.parseFloat(t);return Number.isFinite(e)&&e>0?e:Mw}let Qn=null,Ur=null;function Nw(){return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0}function dn(){if(Ur){try{Ur.cancel()}catch{}Ur=null}Qn&&(Qn.remove(),Qn=null),window.removeEventListener("resize",dn)}function mp(t,e){if(dn(),Nw()||!t||!e||!document.body||typeof Element.prototype.animate!="function")return;const n=t.getBoundingClientRect(),i=e.getBoundingClientRect();if(!n.width||!n.height||!i.width||!i.height)return;const r=document.createElement("div");r.className="composer-morph",r.setAttribute("aria-hidden","true"),r.style.cssText=`left:${i.left}px;top:${i.top}px;width:${i.width}px;height:${i.height}px;opacity:0;`,document.body.appendChild(r);const s=n.left+n.width/2-(i.left+i.width/2),o=n.top+n.height/2-(i.top+i.height/2),a=n.width/i.width,l=n.height/i.height,u=`translate(${s}px,${o}px) scale(${a},${l})`,c=r.animate([{transform:u,opacity:0,offset:0,easing:"cubic-bezier(.2,0,0,1)"},{transform:u,opacity:1,offset:.14,easing:"cubic-bezier(.4,0,.2,1)"},{transform:`translate(${s}px,${o}px) scale(${a*.93},${l*.93})`,opacity:1,offset:.28,easing:"cubic-bezier(.32,1.38,.5,1)"},{transform:"translate(0px,0px) scale(1,1)",opacity:1,offset:1}],{duration:Lw(),fill:"both"});Qn=r,Ur=c,window.addEventListener("resize",dn),c.onfinish=()=>{if(Qn!==r)return;const d=r.animate([{opacity:1},{opacity:0}],{duration:260,fill:"forwards"});d.onfinish=()=>{Qn===r&&dn()}}}function Ow(){const e=document.getElementById("composer")?.getBoundingClientRect();e&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{mp({getBoundingClientRect:()=>e},document.getElementById("main-stage-container"))})})}function Bw(){mp(document.getElementById("pipeline-progress"),document.getElementById("main-stage-container"))}window.addEventListener("hashchange",dn);window.addEventListener("popstate",dn);function Zs(t={}){const{prompt:e=null,runId:n}=t;if(!re(n))return;Qs(),nn(!0);const i=document.getElementById("pipeline-progress"),r=document.getElementById("results-view"),s=document.getElementById("ready-state");if(s&&s.classList.add("hidden"),r&&r.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),i&&i.classList.add("visible"),Ks("running"),e!==null){const a=document.getElementById("pipeline-submitted-prompt");a&&(a.textContent=e)}pp=Date.now();const o=document.getElementById("progress-elapsed");o&&(o.textContent="0s"),On={1:"pending",2:"pending",3:"pending"},ec(),tc(),gp(""),[1,2,3].forEach(a=>Rn(a,"pending")),Pt(1,n),Dw()}function Pt(t,e){re(e)&&(Zl=t,ec(),[1,2,3].forEach(n=>{n===t?Rn(n,"active"):nt&&Rn(n,"pending")}),Js(t),Ys())}function tn(t,e){re(e)&&(Rn(t,"done"),Xl===null&&Js(t,{done:!0}),Ys())}function vp(t,{stage:e=1,runId:n,retry:i=_p}={}){if(!re(n))return;Xs(),Qs(),dn(),Ks("failed"),nn(!0);const r=document.getElementById("pipeline-progress");r&&r.classList.add("visible");const s=document.getElementById("results-view");s&&s.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),Rn(e,"failed"),[1,2,3].forEach(p=>{p>e&&Rn(p,"pending")}),Zl=e,ec(),Js(e),Ys();const o=wh(t),a=document.getElementById("pipeline-failure"),l=document.getElementById("pipeline-failure-title"),u=document.getElementById("pipeline-failure-message"),c=document.getElementById("pipeline-failure-hint"),d=document.getElementById("pipeline-failure-actions");if(!a||!l||!u||!d)return;if(a.dataset.kind=o.kind,l.textContent=`${Vs[e]}: ${o.title}`,u.textContent=o.message,c){const p=o.detail&&o.detail!==o.message?o.detail:"";c.textContent=p,c.hidden=!p}d.replaceChildren();const f=[o.canUpgrade&&{id:"upgrade",label:"View plans",variant:"primary",onClick:()=>di()},o.canRetry&&{id:"retry",label:"Retry",variant:o.canUpgrade?"secondary":"primary",onClick:i},o.canEdit&&{id:"edit",label:"Edit prompt",variant:"secondary",onClick:Ya}].filter(Boolean);!o.canEdit&&!o.canRetry&&f.push({id:"edit",label:"Back to prompt",variant:"secondary",onClick:Ya}),f.forEach(p=>{const g=document.createElement("button");g.type="button",g.textContent=p.label,g.dataset.action=p.id,g.dataset.variant=p.variant,g.addEventListener("click",p.onClick),d.appendChild(g)}),a.hidden=!1;const h=d.querySelector("button");h&&h.focus({preventScroll:!0})}function Ya(){Fw(),uw(),y.isRunning=!1,Ka(!1),rn(),Ks("settled"),dn(),Xs(),Qs(),tc();const t=document.getElementById("pipeline-progress");t&&t.classList.remove("visible"),nn(!1);const e=document.getElementById("pipeline-input");e&&(y.submittedPrompt&&(e.value=y.submittedPrompt,e.dispatchEvent(new Event("input",{bubbles:!0}))),e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length))}function _p(){const t=document.getElementById("pipeline-input");t&&y.submittedPrompt&&(t.value=y.submittedPrompt,t.dispatchEvent(new Event("input",{bubbles:!0}))),Ne=y.submittedImages.slice(),cn(),tc(),or()}function Dw(){Xs(),jr=setInterval(()=>{const t=(Date.now()-pp)/1e3,e=document.getElementById("progress-elapsed");e&&(e.textContent=`${Math.floor(t)}s`)},250)}function Xs(){jr&&(clearInterval(jr),jr=null)}let Vi=null;function Qs(){Vi&&(clearTimeout(Vi),Vi=null)}function cr(){Xs(),Qs(),Ks("settled"),Ys();const t=document.getElementById("pipeline-progress-fill");Vi=setTimeout(()=>{Vi=null;const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function Tn(t,e=""){const n={pass:'',warning:'',fail:'',info:''};return``}function yp(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function jw(){return f_({bundle:y.artifactBundle,reviewResult:y.step3Result})}function Uw(t){return` +
    ${Tn(t.severity)}
    ${q(t.message)}
    @@ -174,17 +174,17 @@ Error: ${g} ${q(t.source)}
    - `}function zw(t){return` + `}function Hw(t){return`
  • ${q(t.title)} ${t.detail&&t.detail!==t.title?`

    ${q(t.detail)}

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

    ${q(l.reason)}

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

    ${q(l.description)}

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

    ${q(e.artifactName)}

    ${e.description?`

    ${q(e.description)}

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

    Manual FlutterFlow steps for this file

    -
      ${e.manualSteps.map(zw).join("")}
    +
      ${e.manualSteps.map(Hw).join("")}
    `:""}
    @@ -297,22 +297,22 @@ Error: ${g}
      ${a}
    - `}function Kw(t){const e=document.getElementById("bundle-strip"),n=document.getElementById("results-summary-tab"),i=document.getElementById("artifact-tabs"),r=document.getElementById("results-file-count");if(n){const s=y.resultsViewMode==="summary";n.classList.toggle("active",s),n.setAttribute("role","tab"),n.setAttribute("aria-selected",String(s)),n.setAttribute("aria-controls","results-summary-detail"),n.tabIndex=s?0:-1}if(i&&(i.setAttribute("role","tablist"),i.setAttribute("aria-label","Artifacts in this bundle")),!t.artifacts.length){r&&(r.textContent="0 files"),e&&e.classList.remove("visible"),i&&(i.innerHTML=""),ad();return}if(r){const s=t.artifacts.length;r.textContent=`${s} ${s===1?"file":"files"}`}i&&(i.innerHTML=t.artifacts.map(s=>{const o=y.resultsViewMode==="file"&&s.id===y.selectedArtifactId;return` + `}function zw(t){const e=document.getElementById("bundle-strip"),n=document.getElementById("results-summary-tab"),i=document.getElementById("artifact-tabs"),r=document.getElementById("results-file-count");if(n){const s=y.resultsViewMode==="summary";n.classList.toggle("active",s),n.setAttribute("role","tab"),n.setAttribute("aria-selected",String(s)),n.setAttribute("aria-controls","results-summary-detail"),n.tabIndex=s?0:-1}if(i&&(i.setAttribute("role","tablist"),i.setAttribute("aria-label","Artifacts in this bundle")),!t.artifacts.length){r&&(r.textContent="0 files"),e&&e.classList.remove("visible"),i&&(i.innerHTML=""),ad();return}if(r){const s=t.artifacts.length;r.textContent=`${s} ${s===1?"file":"files"}`}i&&(i.innerHTML=t.artifacts.map(s=>{const o=y.resultsViewMode==="file"&&s.id===y.selectedArtifactId;return` - `}).join(""),i.onclick=s=>{const o=s.target.closest(".artifact-tab");o?.dataset?.artifactId&&nc(o.dataset.artifactId)},ad()),e&&e.classList.add("visible")}function ad(){const t=document.getElementById("bundle-strip");!t||t.dataset.tabKeyboard==="bound"||(t.dataset.tabKeyboard="bound",t.addEventListener("keydown",e=>{if(e.defaultPrevented)return;const n=[document.getElementById("results-summary-tab"),...Array.from(document.querySelectorAll("#artifact-tabs .artifact-tab"))].filter(Boolean);if(!n.length||!n.includes(document.activeElement))return;let i=-1;const r=n.indexOf(document.activeElement);if(e.key==="ArrowRight")i=(r+1)%n.length;else if(e.key==="ArrowLeft")i=(r-1+n.length)%n.length;else if(e.key==="Home")i=0;else if(e.key==="End")i=n.length-1;else return;e.preventDefault();const s=n[i];if(!s)return;if(s.id==="results-summary-tab")Ep();else{const a=s.dataset.artifactId;a&&nc(a)}const o=s.id==="results-summary-tab"?document.getElementById("results-summary-tab"):document.querySelector(`#artifact-tabs .artifact-tab[data-artifact-id="${s.dataset.artifactId}"]`);o&&o.focus()}))}function to(){document.body.classList.add("results-fullscreen"),document.body.classList.add("results-with-sidebar");const t=document.getElementById("results-view"),e=document.getElementById("results-code-output"),n=document.getElementById("results-audit-output"),i=document.getElementById("results-summary-detail"),r=document.getElementById("artifact-results-split"),s=Ww(),o=Bl();if(i&&(i.setAttribute("role","tabpanel"),i.setAttribute("aria-labelledby","results-summary-tab")),r){r.setAttribute("role","tabpanel");const a=s?.artifacts?.find(l=>l.id===y.selectedArtifactId);r.setAttribute("aria-labelledby",a?`artifact-tab-${a.id}`:"results-summary-tab")}if(Gw(s),Kw(s),e&&(e.textContent=""),e){const a=Eh(o);e.innerHTML=a}n&&(n.innerHTML=Vw(s)),i&&i.classList.toggle("hidden",y.resultsViewMode!=="summary"),r&&r.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function cr(t,e){tn(!0),y.selectedArtifactId||(y.selectedArtifactId=oi(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const n=document.getElementById("step3-output");n&&(n.textContent=""),to(),nn(),Yw()}function Yw(){const t=document.getElementById("btn-feedback-up"),e=document.getElementById("btn-feedback-down"),n=document.getElementById("results-feedback-status");t&&(t.className="feedback-btn",t.setAttribute("aria-pressed","false"),t.disabled=!1,t.removeAttribute("aria-disabled")),e&&(e.className="feedback-btn",e.setAttribute("aria-pressed","false"),e.disabled=!1,e.removeAttribute("aria-disabled")),n&&(n.textContent=""),Za=!1}function nc(t){y.selectedArtifactId=t,y.resultsViewMode="file",to()}function Ep(){y.resultsViewMode="summary",to()}function Jw(){const t=document.getElementById("btn-copy-results"),e=document.getElementById("results-copy-status"),n=Bl(),i=(r,s)=>{e&&(e.textContent=r,e.classList.toggle("ok",!!s),e.classList.toggle("fail",!s))};if(!navigator.clipboard?.writeText){i("Copying isn't supported in this browser.",!1);return}navigator.clipboard.writeText(n).then(()=>{if(i("Copied to clipboard",!0),t){t.classList.add("copied");const r=t.querySelector("span");if(r){const s=r.textContent;r.textContent="Copied!",setTimeout(()=>{t.classList.remove("copied"),r.textContent=s},2e3)}}}).catch(()=>{i("Clipboard permission was denied. Select the code to copy it manually.",!1)})}let Za=!1;async function Zw(t){const e=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down"),i=document.getElementById("results-feedback-status");if(!e||!n||Za)return;const r=l=>{i&&(i.textContent="",i.offsetWidth,i.textContent=l)},s=l=>{Za=l,[e,n].forEach(u=>{u.disabled=l,u.setAttribute("aria-disabled",String(l))})},o=t==="up"?"thumbsUp":"thumbsDown";s(!0),r("Submitting review feedback…");const a={type:o,code:y.step2Result,input:y.step1Result};try{const l=await Gl(a.type,a.code,a.input);if(!l||l.success!==!0){s(!1),r("Review feedback could not be sent. Tap again to retry.");return}e.classList.toggle("active-up",t==="up"),n.classList.toggle("active-down",t==="down"),e.setAttribute("aria-pressed",String(t==="up")),n.setAttribute("aria-pressed",String(t==="down")),s(!1),r("Review feedback saved."),Cn("Generation Feedback",{feedback:o})}catch{s(!1),r("Review feedback could not be sent. Tap again to retry.")}}function Xw(){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 Sp(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}function tn(t){const e=document.getElementById("generation-stage");e&&(t?(e.hidden=!1,e.inert=!1,requestAnimationFrame(()=>e.classList.add("is-active"))):(e.classList.remove("is-active"),e.inert=!0,setTimeout(()=>{e.classList.contains("is-active")||(e.hidden=!0)},260)))}function xp(){const t=z.isVerified&&!!z.email,e=ce.tier||"free",n=t&&pi(),i=!t||Rt(),s=n?"Checking…":i?ml[e]||"Free":"—",o=document.getElementById("topbar-plan");o&&(o.textContent=s);const a=document.getElementById("topbar-avatar");a&&(a.textContent=(z.email||"?")[0].toUpperCase()),Kl();const l=document.getElementById("plans-free-current");l&&l.classList.toggle("hidden",e!=="free"||!i);const u=document.getElementById("plans-checkout-btn-professional");if(u){const d=e==="professional"&&i;u.disabled=d,u.textContent=d?"Current plan":"Subscribe"}const c=document.getElementById("plans-checkout-btn-power");if(c){const d=e==="power"&&i;c.disabled=d,c.textContent=d?"Current plan":"Subscribe"}}function Qw(){xp();const t=document.getElementById("credits-modal");t&&He(t)}function eb(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("credits-modal");e&&We(e)}function Ip(t,e=!0,n=!0){if(t=["home","account","plans"].includes(t)?t:"home",document.querySelectorAll(".view[data-view]").forEach(r=>{r.dataset.view===t?(r.hidden=!1,r.removeAttribute("inert"),requestAnimationFrame(()=>{r.classList.add("is-active"),n&&r.focus({preventScroll:!0})})):(r.classList.remove("is-active"),r.setAttribute("inert","true"),setTimeout(()=>{r.classList.contains("is-active")||(r.hidden=!0)},260))}),t!=="home")tn(!1);else{const r=document.getElementById("main-stage-container");r&&r.classList.contains("visible")&&tn(!0)}if(document.querySelectorAll(".nav-link[data-view]").forEach(r=>{const s=r.dataset.view===t;r.setAttribute("aria-current",s?"page":null),s||r.removeAttribute("aria-current")}),e){const r=t==="home"?"":`#${t}`;window.location.hash!==r&&window.history.pushState({view:t},"",r||"#")}}let ld=!1;function ic(){const t=window.location.hash.replace(/^#/,"");Ip(t||"home",!1,ld),ld=!0}window.addEventListener("popstate",t=>{ic()});window.addEventListener("hashchange",()=>{ic()});window.copyResultsCode=Jw;window.selectArtifact=nc;window.selectResultsSummary=Ep;window.submitResultsFeedback=Zw;window.showErrorInputPanel=Xw;window.hideErrorInputPanel=Sp;window.setGenerationStageVisible=tn;window.switchView=Ip;window.selectPipelineStage=Lw;window.editPipelinePrompt=Ja;window.retryPipelineRun=wp;window.openCreditsModal=Qw;window.closeCreditsModal=eb; + `}).join(""),i.onclick=s=>{const o=s.target.closest(".artifact-tab");o?.dataset?.artifactId&&nc(o.dataset.artifactId)},ad()),e&&e.classList.add("visible")}function ad(){const t=document.getElementById("bundle-strip");!t||t.dataset.tabKeyboard==="bound"||(t.dataset.tabKeyboard="bound",t.addEventListener("keydown",e=>{if(e.defaultPrevented)return;const n=[document.getElementById("results-summary-tab"),...Array.from(document.querySelectorAll("#artifact-tabs .artifact-tab"))].filter(Boolean);if(!n.length||!n.includes(document.activeElement))return;let i=-1;const r=n.indexOf(document.activeElement);if(e.key==="ArrowRight")i=(r+1)%n.length;else if(e.key==="ArrowLeft")i=(r-1+n.length)%n.length;else if(e.key==="Home")i=0;else if(e.key==="End")i=n.length-1;else return;e.preventDefault();const s=n[i];if(!s)return;if(s.id==="results-summary-tab")wp();else{const a=s.dataset.artifactId;a&&nc(a)}const o=s.id==="results-summary-tab"?document.getElementById("results-summary-tab"):document.querySelector(`#artifact-tabs .artifact-tab[data-artifact-id="${s.dataset.artifactId}"]`);o&&o.focus()}))}function eo(){document.body.classList.add("results-fullscreen"),document.body.classList.add("results-with-sidebar");const t=document.getElementById("results-view"),e=document.getElementById("results-code-output"),n=document.getElementById("results-audit-output"),i=document.getElementById("results-summary-detail"),r=document.getElementById("artifact-results-split"),s=jw(),o=Ol();if(i&&(i.setAttribute("role","tabpanel"),i.setAttribute("aria-labelledby","results-summary-tab")),r){r.setAttribute("role","tabpanel");const a=s?.artifacts?.find(l=>l.id===y.selectedArtifactId);r.setAttribute("aria-labelledby",a?`artifact-tab-${a.id}`:"results-summary-tab")}if(Ww(s),zw(s),e&&(e.textContent=""),e){const a=bh(o);e.innerHTML=a}n&&(n.innerHTML=qw(s)),i&&i.classList.toggle("hidden",y.resultsViewMode!=="summary"),r&&r.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function ur(t,e){nn(!0),y.selectedArtifactId||(y.selectedArtifactId=oi(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const n=document.getElementById("step3-output");n&&(n.textContent=""),eo(),rn(),Vw()}function Vw(){const t=document.getElementById("btn-feedback-up"),e=document.getElementById("btn-feedback-down"),n=document.getElementById("results-feedback-status");t&&(t.className="feedback-btn",t.setAttribute("aria-pressed","false"),t.disabled=!1,t.removeAttribute("aria-disabled")),e&&(e.className="feedback-btn",e.setAttribute("aria-pressed","false"),e.disabled=!1,e.removeAttribute("aria-disabled")),n&&(n.textContent=""),Ja=!1}function nc(t){y.selectedArtifactId=t,y.resultsViewMode="file",eo()}function wp(){y.resultsViewMode="summary",eo()}function Gw(){const t=document.getElementById("btn-copy-results"),e=document.getElementById("results-copy-status"),n=Ol(),i=(r,s)=>{e&&(e.textContent=r,e.classList.toggle("ok",!!s),e.classList.toggle("fail",!s))};if(!navigator.clipboard?.writeText){i("Copying isn't supported in this browser.",!1);return}navigator.clipboard.writeText(n).then(()=>{if(i("Copied to clipboard",!0),t){t.classList.add("copied");const r=t.querySelector("span");if(r){const s=r.textContent;r.textContent="Copied!",setTimeout(()=>{t.classList.remove("copied"),r.textContent=s},2e3)}}}).catch(()=>{i("Clipboard permission was denied. Select the code to copy it manually.",!1)})}let Ja=!1;async function Kw(t){const e=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down"),i=document.getElementById("results-feedback-status");if(!e||!n||Ja)return;const r=l=>{i&&(i.textContent="",i.offsetWidth,i.textContent=l)},s=l=>{Ja=l,[e,n].forEach(u=>{u.disabled=l,u.setAttribute("aria-disabled",String(l))})},o=t==="up"?"thumbsUp":"thumbsDown";s(!0),r("Submitting review feedback…");const a={type:o,code:y.step2Result,input:y.step1Result};try{const l=await zl(a.type,a.code,a.input);if(!l||l.success!==!0){s(!1),r("Review feedback could not be sent. Tap again to retry.");return}e.classList.toggle("active-up",t==="up"),n.classList.toggle("active-down",t==="down"),e.setAttribute("aria-pressed",String(t==="up")),n.setAttribute("aria-pressed",String(t==="down")),s(!1),r("Review feedback saved.")}catch{s(!1),r("Review feedback could not be sent. Tap again to retry.")}}function Yw(){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 bp(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}function nn(t){const e=document.getElementById("generation-stage");e&&(t?(e.hidden=!1,e.inert=!1,requestAnimationFrame(()=>e.classList.add("is-active"))):(e.classList.remove("is-active"),e.inert=!0,setTimeout(()=>{e.classList.contains("is-active")||(e.hidden=!0)},260)))}function Ep(){const t=z.isVerified&&!!z.email,e=ce.tier||"free",n=t&&pi(),i=!t||Rt(),s=n?"Checking…":i?gl[e]||"Free":"—",o=document.getElementById("topbar-plan");o&&(o.textContent=s);const a=document.getElementById("topbar-avatar");a&&(a.textContent=(z.email||"?")[0].toUpperCase()),Gl();const l=document.getElementById("plans-free-current");l&&l.classList.toggle("hidden",e!=="free"||!i);const u=document.getElementById("plans-checkout-btn-professional");if(u){const d=e==="professional"&&i;u.disabled=d,u.textContent=d?"Current plan":"Subscribe"}const c=document.getElementById("plans-checkout-btn-power");if(c){const d=e==="power"&&i;c.disabled=d,c.textContent=d?"Current plan":"Subscribe"}}function Jw(){Ep();const t=document.getElementById("credits-modal");t&&He(t)}function Zw(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("credits-modal");e&&We(e)}function Sp(t,e=!0,n=!0){if(t=["home","account","plans"].includes(t)?t:"home",document.querySelectorAll(".view[data-view]").forEach(r=>{r.dataset.view===t?(r.hidden=!1,r.removeAttribute("inert"),requestAnimationFrame(()=>{r.classList.add("is-active"),n&&r.focus({preventScroll:!0})})):(r.classList.remove("is-active"),r.setAttribute("inert","true"),setTimeout(()=>{r.classList.contains("is-active")||(r.hidden=!0)},260))}),t!=="home")nn(!1);else{const r=document.getElementById("main-stage-container");r&&r.classList.contains("visible")&&nn(!0)}if(document.querySelectorAll(".nav-link[data-view]").forEach(r=>{const s=r.dataset.view===t;r.setAttribute("aria-current",s?"page":null),s||r.removeAttribute("aria-current")}),e){const r=t==="home"?"":`#${t}`;window.location.hash!==r&&window.history.pushState({view:t},"",r||"#")}}let ld=!1;function ic(){const t=window.location.hash.replace(/^#/,"");Sp(t||"home",!1,ld),ld=!0}window.addEventListener("popstate",t=>{ic()});window.addEventListener("hashchange",()=>{ic()});window.copyResultsCode=Gw;window.selectArtifact=nc;window.selectResultsSummary=wp;window.submitResultsFeedback=Kw;window.showErrorInputPanel=Yw;window.hideErrorInputPanel=bp;window.setGenerationStageVisible=nn;window.switchView=Sp;window.selectPipelineStage=Tw;window.editPipelinePrompt=Ya;window.retryPipelineRun=_p;window.openCreditsModal=Jw;window.closeCreditsModal=Zw; diff --git a/dist/index.html b/dist/index.html index d21f63d..62c098d 100644 --- a/dist/index.html +++ b/dist/index.html @@ -3313,7 +3313,7 @@ .send.is-busy .send-spin { animation: none; opacity: 0.6; } } - + diff --git a/e2e/stu380-deploy.spec.js b/e2e/stu380-deploy.spec.js index 3ba3694..8e96e7b 100644 --- a/e2e/stu380-deploy.spec.js +++ b/e2e/stu380-deploy.spec.js @@ -83,6 +83,15 @@ test.describe("STU-380 deployment terminal outcomes", () => { // A definitive rejection must not read as committed. await expect(output).not.toContainText("committed"); await expect(output).not.toContainText("Committed"); + + // #step3-output sits in permanently-hidden legacy containers, so the + // refusal must also reach the shared terminal modal to be visible at all. + const terminal = page.locator("#commit-terminal-modal"); + await expect(terminal).toBeVisible(); + await expect(terminal).toContainText("Deploy failed"); + await expect(terminal).toContainText("403"); + await expect(terminal).toContainText(identity.projectId); + await expect(terminal).not.toContainText("Committed"); }); test("a per-file rejection surfaces each file's error, not a blanket success", async ({ page }) => { @@ -99,6 +108,13 @@ test.describe("STU-380 deployment terminal outcomes", () => { await expect(output).toContainText("gauge_widget.dart"); await expect(output).toContainText("Duplicate class GaugeWidget"); await expect(output).not.toContainText("committed"); + + // The same per-file outcomes are visible in the shared terminal modal. + const terminal = page.locator("#commit-terminal-modal"); + await expect(terminal).toBeVisible(); + await expect(terminal).toContainText("Deploy failed"); + await expect(terminal).toContainText("gauge_widget.dart"); + await expect(terminal).toContainText("Duplicate class GaugeWidget"); }); test("a compile gate failure shows the analyzer rejection, never committed", async ({ page }) => { @@ -112,6 +128,12 @@ test.describe("STU-380 deployment terminal outcomes", () => { const output = page.locator("#step3-output"); await expect(output).toContainText("does not compile"); await expect(output).not.toContainText("committed"); + + // The analyzer refusal reaches the visible terminal too. + const terminal = page.locator("#commit-terminal-modal"); + await expect(terminal).toBeVisible(); + await expect(terminal).toContainText("Deploy failed"); + await expect(terminal).toContainText("does not compile"); }); test("a partial outcome opens the terminal modal with per-file outcomes and does not claim committed", async ({ page }) => { From a2a5dbd6da18cad116e702b403a46300997d26ca Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Sun, 27 Sep 2026 17:15:52 +0000 Subject: [PATCH 06/16] fix(STU-380): treat push 5xx as uncertain; refusal after an uncertain attempt is unconfirmed MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A definitive refusal only makes the deploy definitively failed if no earlier attempt was uncertain. Any 5xx from the sync endpoint — or a lost response — may have landed the write, so: - non-500 5xx throws UnconfirmedDeployError immediately - a later definitive refusal after any uncertain attempt stays unconfirmed - retry-exhaustion always returns UnconfirmedDeployError FAILED therefore only covers provably pre-write refusals, keeping the failure modal's 'nothing applied, retry is safe' copy accurate. Co-Authored-By: Stuart Gardoll --- app.js | 50 +++++-- .../{index-DSl339_I.js => index-DBkaFUBQ.js} | 44 +++--- dist/index.html | 2 +- e2e/stu380-deploy.spec.js | 134 ++++++++++++++++-- src/deployOutcome.js | 36 ++--- src/deployOutcome.test.js | 30 ++-- 6 files changed, 211 insertions(+), 85 deletions(-) rename dist/assets/{index-DSl339_I.js => index-DBkaFUBQ.js} (94%) diff --git a/app.js b/app.js index b06bdec..46641d9 100644 --- a/app.js +++ b/app.js @@ -2168,19 +2168,20 @@ class FlutterFlowApiClient { FF_API_ENDPOINTS.staging, ]; const startEndpoint = Math.max(0, endpointUrls.indexOf(this._endpoint)); - // Retried only on a lost connection or a 500, a lost response means the - // push may have been applied — exhaustion after any transport error is an - // unknown outcome, never a fabricated refusal. - let sawTransportError = false; + // An attempt is uncertain when its outcome cannot prove the push was + // refused: a dropped response (the request may have landed) or a 5xx (the + // server's own failure report can follow a write). Once any attempt is + // uncertain, no later refusal can undo it — the outcome stays unknown. + let sawUncertainAttempt = false; let lastHttpStatus = null; for (let attempt = 0; attempt < maxRetries; attempt++) { for (let ei = startEndpoint; ei < endpointUrls.length; ei++) { const baseUrl = endpointUrls[ei]; - // Only a fetch rejection is a transport error: once response headers - // arrive the status is a definitive answer, and a body that fails to - // read for logging must not reclassify a known refusal as a lost + // Only a fetch rejection is a lost response: once headers arrive, a + // refusal status is a definitive answer for this endpoint — and a body + // that fails to read for logging must not reclassify one as a lost // response (or send a non-500 refusal back through the retry loop). let response; try { @@ -2205,7 +2206,7 @@ class FlutterFlowApiClient { body: JSON.stringify(pushCodeRequest), }); } catch (error) { - sawTransportError = true; + sawUncertainAttempt = true; console.warn( `Push to ${baseUrl} failed: ${error.message}, trying next...`, ); @@ -2229,20 +2230,45 @@ class FlutterFlowApiClient { `Push to ${baseUrl} returned ${response.status}: ${responseText}`, ); + // A 5xx is the server's own failure report: it can be raised after + // the write was applied, so it can never prove a refusal. + if (response.status >= 500) { + sawUncertainAttempt = true; + } if (response.status === 500) { console.warn(`Endpoint ${baseUrl} returned 500, trying next...`); await new Promise((r) => setTimeout(r, 1000 * (attempt + 1))); continue; } + // Any other server error is already an unknown outcome for this + // endpoint — the write may have been applied before the failure. + if (response.status >= 500) { + throw new UnconfirmedDeployError( + `FlutterFlow reported a server error (HTTP ${response.status}), ` + + "which cannot prove the push was refused — the write may have " + + "been applied before the failure. Open your FlutterFlow project " + + "to reconcile before retrying.", + ); + } + + // A refusal is definitive for this endpoint, but it cannot prove that + // an earlier attempt whose outcome was lost did not apply the push. + if (sawUncertainAttempt) { + throw new UnconfirmedDeployError( + `The push was refused (HTTP ${response.status}), but an earlier ` + + "sync attempt may already have applied it — server errors and " + + "dropped responses cannot prove a refusal. Open your FlutterFlow " + + "project to reconcile before retrying.", + ); + } return response; } } - throw exhaustedPushError({ - sawTransportError, - httpStatus: lastHttpStatus, - }); + // Every retry path left the outcome unknown: each attempt either lost its + // response or hit a server error, so the push may have been applied. + throw exhaustedPushError({ httpStatus: lastHttpStatus }); } async pushCode(pushCodeRequest) { diff --git a/dist/assets/index-DSl339_I.js b/dist/assets/index-DBkaFUBQ.js similarity index 94% rename from dist/assets/index-DSl339_I.js rename to dist/assets/index-DBkaFUBQ.js index cdeb08e..8cf3eb4 100644 --- a/dist/assets/index-DSl339_I.js +++ b/dist/assets/index-DBkaFUBQ.js @@ -1,6 +1,6 @@ -(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const s of r)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function n(r){const s={};return r.integrity&&(s.integrity=r.integrity),r.referrerPolicy&&(s.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?s.credentials="include":r.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function i(r){if(r.ep)return;r.ep=!0;const s=n(r);fetch(r.href,s)}})();var w=typeof window<"u"?window:void 0,Le=typeof globalThis<"u"?globalThis:w,Ue=Le?.navigator,F=Le?.document,me=Le?.location,Za=Le?.fetch,qo=Le!=null&&Le.XMLHttpRequest&&"withCredentials"in new Le.XMLHttpRequest?Le.XMLHttpRequest:void 0,uc=Le?.AbortController,Fp=Le?.CompressionStream,Ve=Ue?.userAgent;function cd(){return!(!w||w.navigator.onLine===!1)}var vi=typeof globalThis<"u"?globalThis:w;vi&&typeof self>"u"&&(vi.self=vi),vi&&typeof File>"u"&&(vi.File=function(){});var B=w??{},ne={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function dc(t,e,n,i,r,s,o){try{var a=t[s](o),l=a.value}catch(u){return void n(u)}a.done?e(l):Promise.resolve(l).then(i,r)}function se(t){return function(){var e=this,n=arguments;return new Promise((function(i,r){var s=t.apply(e,n);function o(l){dc(s,i,r,o,a,"next",l)}function a(l){dc(s,i,r,o,a,"throw",l)}o(void 0)}))}}function k(){return k=Object.assign?Object.assign.bind():function(t){for(var e=1;arguments.length>e;e++){var n=arguments[e];for(var i in n)({}).hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},k.apply(null,arguments)}function ud(t,e){if(t==null)return{};var n={};for(var i in t)if({}.hasOwnProperty.call(t,i)){if(e.indexOf(i)!==-1)continue;n[i]=t[i]}return n}var fc=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function hc(t){return typeof t=="string"||t}function pc(t){return typeof t=="string"?t:void 0}var _i,Rp=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],jt=(function(t){return t.AnonymousId="anonymous_id",t.DistinctId="distinct_id",t.Props="props",t.EnablePersonProcessing="enable_person_processing",t.PersonMode="person_mode",t.FeatureFlagDetails="feature_flag_details",t.FeatureFlags="feature_flags",t.FeatureFlagPayloads="feature_flag_payloads",t.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",t.BootstrapFeatureFlags="bootstrap_feature_flags",t.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",t.OverrideFeatureFlags="override_feature_flags",t.Queue="queue",t.AiQueue="ai_queue",t.LogsQueue="logs_queue",t.OptedOut="opted_out",t.SessionId="session_id",t.SessionStartTimestamp="session_start_timestamp",t.SessionLastTimestamp="session_timestamp",t.PersonProperties="person_properties",t.GroupProperties="group_properties",t.InstalledAppBuild="installed_app_build",t.InstalledAppVersion="installed_app_version",t.SessionReplay="session_replay",t.PushRegistered="push_registered",t.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",t.SurveyLastSeenDate="survey_last_seen_date",t.SurveysSeen="surveys_seen",t.Surveys="surveys",t.RemoteConfig="remote_config",t.FlagsEndpointWasHit="flags_endpoint_was_hit",t.DeviceId="device_id",t})({}),gc=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),Tp=["$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"],$p=["token"],dd="NativeGzipValidationError",zo=t=>t.length>=2&&t[0]===31&&t[1]===139,mc=(t,e)=>t===gc.GZipJS||e===gc.GZipJS||e==="gzip",vc=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",pr=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=dd,e},Mp=(function(){var t=se((function*(e,n){18>e.size&&pr("too-short");var i=new Uint8Array(yield e.slice(0,10).arrayBuffer());zo(i)&&i[2]===8||pr("invalid-header");var r=new DataView(yield e.slice(e.size-8).arrayBuffer());r.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(_i)return _i;_i=[];for(var c=0;256>c;c++){for(var d=c,f=0;8>f;f++)d=1&d?3988292384^d>>>1:d>>>1;_i[c]=d>>>0}return _i})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(n)&&pr("invalid-crc");var s=n.length>>>0;r.getUint32(4,!0)!==s&&pr("invalid-size")}));return function(e,n){return t.apply(this,arguments)}})();function Vo(){return Vo=se((function*(t,e,n){e===void 0&&(e=!0);try{var i=new TextEncoder().encode(t),r=new globalThis.CompressionStream("gzip"),s=r.writable.getWriter(),o=s.write(i).then((()=>s.close())).catch((function(){var u=se((function*(c){try{yield s.abort(c)}catch{}throw c}));return function(c){return u.apply(this,arguments)}})()),a=new Response(r.readable).blob(),l=(yield Promise.all([a,o]))[0];return yield Mp(l,i),l}catch(u){if(n!=null&&n.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),Vo.apply(this,arguments)}var Lp=["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"],_c=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var n=t.toLowerCase();return Lp.concat(e).some((i=>{var r=i.toLowerCase();return n.indexOf(r)!==-1}))};function j(t,e){return t.indexOf(e)!==-1}var xs=function(t){return t.trim()},Go=function(t){return t.replace(/^\$/,"")};function fd(t){var e,n=[];return(e=JSON.stringify(t,(function(i,r){if(typeof r=="bigint")return r.toString();if(typeof r!="function"&&typeof r!="symbol"){if(r instanceof Error)return{name:r.name,message:r.message,stack:r.stack};if(r&&typeof r=="object"){for(;n.length>0&&n[n.length-1]!==this;)n.pop();if(n.includes(r))return"[Circular]";n.push(r)}return r}})))!==null&&e!==void 0?e:"null"}var hd=Object.prototype,pd=hd.hasOwnProperty,Is=hd.toString,U=Array.isArray||function(t){return Is.call(t)==="[object Array]"},De=t=>typeof t=="function",he=t=>t===Object(t)&&!U(t),Gt=t=>{if(he(t)){for(var e in t)if(pd.call(t,e))return!1;return!0}return!1},C=t=>t===void 0,X=t=>Is.call(t)=="[object String]",Ko=t=>X(t)&&t.trim().length===0,Ke=t=>t===null,H=t=>C(t)||Ke(t),ke=t=>Is.call(t)=="[object Number]"&&t==t,Bt=t=>ke(t)&&t>0,gt=t=>Is.call(t)==="[object Boolean]",Np=t=>t instanceof FormData,Op=t=>j(Tp,t),Bp=t=>j($p,t);function gd(t){return t===null||typeof t!="object"}function Hr(t,e){return{}.toString.call(t)==="[object "+e+"]"}function Xa(t){return typeof Event<"u"&&md(t,Event)}function md(t,e){try{return t instanceof e}catch{return!1}}var Dp=[!0,"true",1,"1","yes"],uo=t=>j(Dp,t),jp=[!1,"false",0,"0","no"];function Ct(t,e,n,i,r){return e>n&&(i.warn("min cannot be greater than max."),e=n),ke(t)?t>n?(i.warn(" cannot be greater than max: "+n+". Using max value instead."),n):e>t?(i.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(i.warn(" must be a number. using max or fallback. max: "+n+", fallback: "+r),Ct(r||n,e,n,i))}class Up{constructor(e){this.tt={},this.et=e.et,this.it=Ct(e.bucketSize,0,100,e.rt),this.nt=Ct(e.refillRate,0,this.it,e.rt),this.st=Ct(e.refillInterval,0,864e5,e.rt)}ot(e,n){var i=Math.floor((n-e.lastAccess)/this.st);i>0&&(e.tokens=Math.min(e.tokens+i*this.nt,this.it),e.lastAccess=e.lastAccess+i*this.st)}consumeRateLimit(e){var n,i=Date.now(),r=String(e),s=this.tt[r];return s?this.ot(s,i):this.tt[r]=s={tokens:this.it,lastAccess:i},s.tokens===0||(s.tokens--,s.tokens===0&&((n=this.et)==null||n.call(this,e)),s.tokens===0)}stop(){this.tt={}}}var it="Mobile",Wr="iOS",Kt="Android",ei="Tablet",vd=Kt+" "+ei,_d="iPad",yd="Apple",wd=yd+" Watch",Bi="Safari",ti="BlackBerry",bd="Samsung",Ed=bd+"Browser",Sd=bd+" Internet",Pn="Chrome",Hp=Pn+" OS",xd=Pn+" "+Wr,Qa="Internet Explorer",Id=Qa+" "+it,el="Opera",Wp=el+" Mini",tl="Edge",kd="Microsoft "+tl,Zn="Firefox",Cd=Zn+" "+Wr,Gi="Nintendo",Ki="PlayStation",Xn="Xbox",Ad=Kt+" "+it,Pd=it+" "+Bi,Pi="Windows",Yo=Pi+" Phone",yc="Nokia",Jo="Ouya",Fd="Generic",qp=Fd+" "+it.toLowerCase(),Rd=Fd+" "+ei.toLowerCase(),Zo="Konqueror",Td="Oculus Browser",qr="Vivaldi",$d="Yandex",zr="Whale",Xo="DuckDuckGo",Md="Pale Moon",Vr="Waterfox",Di="Brave",Ld="Google Search App",we="(\\d+(\\.\\d+)?)",fo=new RegExp("Version/"+we),zp=new RegExp(Xn,"i"),Vp=new RegExp(Ki+" \\w+","i"),Gp=new RegExp(Gi+" \\w+","i"),nl=new RegExp(ti+"|PlayBook|BB10","i"),Kp={"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"},Nd=function(t,e,n,i){e=e||"";var r=(function(s){return s!=null&&s.brave?Di:null})(n);return r||(i!=null&&i.detectGoogleSearchApp&&j(t,"GSA/")?Ld:j(t," OPR/")&&j(t,"Mini")?Wp:j(t," OPR/")?el:nl.test(t)?ti:j(t,"IE"+it)||j(t,"WPDesktop")?Id:j(t,"OculusBrowser")?Td:j(t,Ed)?Sd:j(t,tl)||j(t,"Edg/")?kd:j(t,qr+"/")?qr:j(t,"YaBrowser/")?$d:j(t,zr+"/")?zr:j(t,Xo+"/")||j(t,"Ddg/")?Xo:j(t,"FBIOS")?"Facebook "+it:j(t,"UCWEB")||j(t,"UCBrowser")?"UC Browser":j(t,"CriOS")?xd:j(t,"CrMo")||j(t,Pn)?Pn:j(t,Kt)&&j(t,Bi)?Ad:j(t,"FxiOS")?Cd:j(t.toLowerCase(),Zo.toLowerCase())?Zo:j(t,Di+"/")?Di:((s,o)=>o&&j(o,yd)||(function(a){return j(a,Bi)&&!j(a,Pn)&&!j(a,Kt)})(s))(t,e)?j(t,it)?Pd:Bi:j(t,"PaleMoon/")?Md:j(t,Vr+"/")?Vr:j(t,Zn)?Zn:j(t,"MSIE")||j(t,"Trident/")?Qa:j(t,"Gecko")?Zn:"")},Yp={[Id]:[new RegExp("rv:"+we)],[kd]:[new RegExp(tl+"?\\/"+we)],[Pn]:[new RegExp("("+Pn+"|CrMo)\\/"+we)],[xd]:[new RegExp("CriOS\\/"+we)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+we)],[Bi]:[fo],[Pd]:[fo],[el]:[new RegExp("(Opera|OPR)\\/"+we)],[Zn]:[new RegExp(Zn+"\\/"+we)],[Cd]:[new RegExp("FxiOS\\/"+we)],[Zo]:[new RegExp("Konqueror[:/]?"+we,"i")],[ti]:[new RegExp(ti+" "+we),fo],[Ad]:[new RegExp("android\\s"+we,"i")],[Sd]:[new RegExp(Ed+"\\/"+we)],[Td]:[new RegExp("OculusBrowser\\/"+we)],[qr]:[new RegExp(qr+"\\/"+we)],[$d]:[new RegExp("YaBrowser\\/"+we)],[zr]:[new RegExp(zr+"\\/"+we)],[Di]:[new RegExp(Di+"\\/"+we)],[Xo]:[new RegExp("(DuckDuckGo|Ddg)\\/"+we)],[Md]:[new RegExp("PaleMoon\\/"+we)],[Vr]:[new RegExp(Vr+"\\/"+we)],[Ld]:[new RegExp("GSA\\/"+we)],[Qa]:[new RegExp("(rv:|MSIE )"+we)],Mozilla:[new RegExp("rv:"+we)]},Jp=function(t,e,n,i){var r=Nd(t,e,n,i),s=Yp[r];if(C(s))return null;for(var o=0;s.length>o;o++){var a=t.match(s[o]);if(a)return parseFloat(a[a.length-2])}return null},wc=[[new RegExp(Xn+"; "+Xn+" (.*?)[);]","i"),t=>[Xn,t&&t[1]||""]],[new RegExp(Gi,"i"),[Gi,""]],[new RegExp(Ki,"i"),[Ki,""]],[nl,[ti,""]],[new RegExp(Pi,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Yo,""];if(new RegExp(it).test(e)&&!/IEMobile\b/.test(e))return[Pi+" "+it,""];var n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){var i=Kp[n[1]]||"";return/arm/i.test(e)&&(i="RT"),[Pi,i]}return[Pi,""]}],[/((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=C(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+Kt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Kt+")","i"),t=>t&&t[2]?[Kt,[t[2],t[3],t[4]||"0"].join(".")]:[Kt,""]],[/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/,[Hp,""]],[/Linux|debian/i,["Linux",""]]],bc=function(t){return Gp.test(t)?Gi:Vp.test(t)?Ki:zp.test(t)?Xn:new RegExp(Jo,"i").test(t)?Jo:new RegExp("("+Yo+"|WPDesktop)","i").test(t)?Yo:/iPad/.test(t)?_d:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?wd:nl.test(t)?ti:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(yc,"i").test(t)?yc:/(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(it).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)?Kt:vd:new RegExp("(pda|"+it+")","i").test(t)?qp:new RegExp(ei,"i").test(t)&&!new RegExp(ei+" pc","i").test(t)?Rd:""},Zp=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ec(t,e){return typeof(n=t)=="string"&&Zp.test(n)?t:e();var n}function fn(t){return t&&t.split("#")[0]}function il(t,e){var n=setTimeout(t,e);return n?.unref&&n?.unref(),n}function Sc(t,e,n){return Od.apply(this,arguments)}function Od(){return(Od=se((function*(t,e,n){var i;try{return yield Promise.race([t,new Promise(((r,s)=>{i=il((()=>{try{n?.(),r()}catch(o){s(o)}}),e)}))])}finally{clearTimeout(i)}}))).apply(this,arguments)}var Xp=t=>t instanceof Error,Bd={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},Qp=Bd.info;function Dd(t){if(gt(t))return{boolValue:t};if(typeof t=="number")return Number.isFinite(t)?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:{stringValue:String(t)};if(typeof t=="string")return{stringValue:t};if(U(t))return{arrayValue:{values:t.map((e=>Dd(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function Gr(t){var e=[];for(var n in t){var i=t[n];Ke(i)||C(i)||e.push({key:n,value:Dd(i)})}return e}function eg(t,e){var n=Bd[t.level||"info"]||Qp,i=n.text,r=n.number,s=String(Date.now())+"000000",o={};e.distinctId&&(o.posthogDistinctId=e.distinctId),e.sessionId&&(o.sessionId=e.sessionId),e.windowId&&(o["window.id"]=e.windowId),H(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),H(e.lastActivityTimestamp)||(o.lastActivityTimestamp=String(e.lastActivityTimestamp)),e.currentUrl&&(o["url.full"]=e.currentUrl),e.screenName&&(o["screen.name"]=e.screenName),e.appState&&(o["app.state"]=e.appState),e.activeFeatureFlags&&e.activeFeatureFlags.length>0&&(o.feature_flags=e.activeFeatureFlags);var a=k({},o,t.attributes||{}),l={timeUnixNano:s,observedTimeUnixNano:s,severityNumber:r,severityText:i,body:{stringValue:t.body},attributes:Gr(a)};return t.trace_id&&(l.traceId=t.trace_id),t.span_id&&(l.spanId=t.span_id),C(t.trace_flags)||(l.flags=t.trace_flags),l}function jd(t,e,n){return k({},t.resourceAttributes,{"service.name":t.serviceName||"unknown_service"},t.environment&&{"deployment.environment":t.environment},t.serviceVersion&&{"service.version":t.serviceVersion},{"telemetry.sdk.name":e,"telemetry.sdk.version":n})}function Ud(t,e,n,i){return{resourceLogs:[{resource:{attributes:Gr(e)},scopeLogs:[{scope:{name:n,version:i},logRecords:t}]}]}}let tg=class{constructor(t,e,n,i,r,s,o){var a;s===void 0&&(s=()=>Promise.resolve()),this._instance=t,this.Ne=e,this.rt=n,this.ut=i,this.ht=r,this.dt=s,this.vt=o,this.ct=null,this.ft=0,this.yt=0,this.bt=0,this._t=0,this.wt=!1,this.kt=e.maxBufferSize,this.xt=Math.max((a=e.maxQueueSize)!==null&&a!==void 0?a:e.maxBufferSize,e.maxBufferSize),this.St=e.flushIntervalMs,this.Ct=e.maxBatchRecordsPerPost,this.Mt=e.rateCapWindowMs,this.Tt=e.maxLogsPerInterval}reset(){this.Et(),this.ct=null,this.bt=0,this._t=0,this.wt=!1,this.ft=0,this.yt=0,this.Ct=this.Ne.maxBatchRecordsPerPost}onReconnect(){this.yt=0,this.It()}captureLog(t){if(!this._instance.isDisabled&&!this._instance.optedOut&&t!=null&&t.body){var e=this.Pt(t);if(e!==null)if(e.body){if(this.Rt()){var n={record:eg(e,this.ut())};this.ht((()=>this.At(n)))}}else this.rt.info("Log was rejected in beforeSend function")}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Log was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for log:",o),null}return i}Rt(){if(this.Tt===void 0)return!0;var t=Date.now(),e=t-this.bt;return this.Mt>e&&e>=0||(this.bt=t,this._t=0,this.wt=!1),this.Tt>this._t?(this._t++,!0):(this.wt||(this.rt.warn("captureLog dropping logs: exceeded "+this.Tt+" logs per "+this.Mt+"ms"),this.wt=!0),!1)}flush(){var t=this;return se((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return se((function*(){var e;t.Et();var n=(e=t._instance.getPersistedProperty(jt.LogsQueue))!==null&&e!==void 0?e:[];if(n.length!==0)for(var i=n.length,r=0;n.length>0&&i>r;){var s,o;t.ft=0;var a=Math.min(n.length,t.Ct),l=n.slice(0,a),u=Ud(l.map((d=>d.record)),t.Lt(),(s=t.vt)!==null&&s!==void 0?s:t._instance.getLibraryId(),t._instance.getLibraryVersion()),c=yield t._instance.Ot(u);if(c.kind==="too-large"&&l.length>1)t.Ct=Math.max(1,Math.floor(l.length/2)),t.rt.warn("Received 413 when sending logs batch of size "+l.length+", reducing batch size to "+t.Ct);else if(c.kind==="retry-later"||(c.kind==="too-large"?t.rt.warn("Dropping a single log record after 413 with batch size 1 — the record is larger than the server cap and cannot be split further."):c.kind==="ok"&&t.Ne.maxBatchRecordsPerPost>t.Ct&&(t.Ct=Math.min(t.Ne.maxBatchRecordsPerPost,t.Ct+1)),yield t.Dt(l.length),n=(o=t._instance.getPersistedProperty(jt.LogsQueue))!==null&&o!==void 0?o:[],r+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return se((function*(){var n,i=Math.max(0,t-e.ft),r=(n=e._instance.getPersistedProperty(jt.LogsQueue))!==null&&n!==void 0?n:[];e._instance.setPersistedProperty(jt.LogsQueue,r.slice(i)),yield e.dt()}))()}Lt(){return jd(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var n=(e=this._instance.getPersistedProperty(jt.LogsQueue))!==null&&e!==void 0?e:[];this.xt>n.length||(n.shift(),this.ft++,this.rt.info("Logs queue is full, dropping oldest record.")),n.push(t),this._instance.setPersistedProperty(jt.LogsQueue,n),this.kt>n.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=il((()=>{this.Nt=void 0,this.It()}),t))}qt(){var t=Math.min(Math.max(0,this.yt-1),6);return this.St*Math.pow(2,t)}jt(){var t=this._instance.getPersistedProperty(jt.LogsQueue);return!!t&&t.length>0}shutdown(t){var e=this;return se((function*(){e.Et();var n=e.flush().catch((()=>{}));t!==void 0?yield Sc(n,t):yield n}))()}flushWithTimeout(t){var e=this;return se((function*(){var n=e.flush();yield Sc(n,t,(()=>{n.catch((()=>{}))}))}))()}It(){this.flush().then((()=>{this.yt=0}),(t=>{this.yt++,this.rt.error("PostHog logs flush failed:",t)})).finally((()=>{!this._instance.isDisabled&&this.jt()&&this.$t(this.qt())}))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}};var ho=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function xc(t){return String(t)+"000000"}function Ic(t,e,n,i){var r="";return i&&(r=Object.keys(i).sort().map((s=>JSON.stringify(s)+":"+JSON.stringify(i[s]))).join(",")),t+"\0"+e+"\0"+(n??"")+"\0"+r}let ng=class{constructor(t,e,n){this._instance=t,this.Ne=e,this.rt=n,this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Wt=0}count(t,e,n){e===void 0&&(e=1),this.Vt({name:t,type:"count",value:e,unit:n?.unit,attributes:n?.attributes})}gauge(t,e,n){this.Vt({name:t,type:"gauge",value:e,unit:n?.unit,attributes:n?.attributes})}histogram(t,e,n){this.Vt({name:t,type:"histogram",value:e,unit:n?.unit,attributes:n?.attributes})}flush(){var t=this,e=this.ct,n=(function(){var r=se((function*(){e&&(yield e.catch((()=>{}))),yield t.Zt()}));return function(){return r.apply(this,arguments)}})(),i=n().finally((()=>{this.ct===i&&(this.ct=null)}));return this.ct=i,i}drainWindow(){if(this.Bt.size===0)return null;var t=this.Bt;return this.Bt=new Map,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Gt(t)}reset(){this.Wt++,this.Et(),this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set}Vt(t){if(!this._instance.isDisabled&&!this._instance.optedOut){var e=this.Pt(t);if(e!==null)if(e.name&&typeof e.name=="string")if(typeof e.value=="number"&&Number.isFinite(e.value))if(e.type==="count"&&0>e.value)this.rt.warn("Dropping count '"+e.name+"': counters are monotonic, value must be >= 0");else{var n,i;try{n=e.attributes?k({},e.attributes):void 0,i=Ic(e.type,e.name,e.unit,n)}catch(o){return void this.rt.warn("Dropping metric '"+e.name+"': attributes could not be serialized",o)}var r=this.Bt.get(i);if(!r){if(!this.Qt())return;r={name:e.name,type:e.type,unit:e.unit,attributes:n,windowStartMs:Date.now()},this.Bt.set(i,r)}var s=this.Ut.get(e.name);s===void 0?this.Ut.set(e.name,e.type):s===e.type||this.zt.has(e.name)||(this.zt.add(e.name),this.rt.warn("Metric name '"+e.name+"' is already used as a "+s+"; recording it as a "+e.type+" too will blend both series in charts. Use a distinct name.")),this.Kt(r,e.value),this.$t()}else this.rt.warn("Dropping metric '"+e.name+"': value must be a finite number");else this.rt.warn("Dropping metric with empty name")}}Qt(){return this.Ne.maxSeriesPerFlush>this.Bt.size||(this.Ht||(this.Ht=!0,this.rt.warn("Metric series cap reached ("+this.Ne.maxSeriesPerFlush+" per flush window); dropping new series until the next flush. Reduce attribute cardinality.")),!1)}Kt(t,e){var n;switch(t.type){case"count":t.total=((n=t.total)!==null&&n!==void 0?n:0)+e;break;case"gauge":t.last=e;break;case"histogram":t.hist||(t.hist={count:0,sum:0,min:e,max:e,bucketCounts:new Array(ho.length+1).fill(0)});var i=t.hist;i.count+=1,i.sum+=e,i.min=Math.min(i.min,e),i.max=Math.max(i.max,e),i.bucketCounts[(function(r,s){for(var o=0;s.length>o;o++)if(s[o]>=r)return o;return s.length})(e,ho)]+=1}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Metric was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for metric:",o),null}return i}$t(){this.Nt||(this.Nt=il((()=>{this.Nt=void 0,this.flush().catch((t=>{this.rt.error("Metrics flush failed:",t)}))}),this.Ne.flushIntervalMs))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}Zt(){var t=this;return se((function*(){if(t.Bt.size!==0){var e=t.Bt;t.Bt=new Map,t.Ht=!1,t.Ut=new Map,t.zt=new Set;var n=t.Wt,i=yield t._instance.Jt(t.Gt(e));if(n===t.Wt)switch(i.kind){case"ok":return;case"retry-later":return t.Yt(e),void t.$t();case"too-large":return void t.rt.warn("Metrics batch exceeded the server size limit and was dropped");case"fatal":return void t.rt.error("Failed to send metrics batch:",i.error)}}}))()}Gt(t){return e=this.Xt(t),n=(function(s,o,a){return k({},s.resourceAttributes,{"service.name":s.serviceName||"unknown_service"},s.environment&&{"deployment.environment":s.environment},s.serviceVersion&&{"service.version":s.serviceVersion},{"telemetry.sdk.name":o,"telemetry.sdk.version":a})})(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion()),i=this._instance.getLibraryId(),r=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:Gr(n)},scopeMetrics:[{scope:{name:i,version:r},metrics:e}]}]};var e,n,i,r}Xt(t){var e=xc(Date.now()),n=new Map;for(var i of t.values()){var r,s=Ic(i.type,i.name,i.unit,void 0),o=n.get(s);o||(o=k({name:i.name},i.unit&&{unit:i.unit}),i.type==="count"?o.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:i.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:1,dataPoints:[]},n.set(s,o));var a=Gr((r=i.attributes)!==null&&r!==void 0?r:{}),l=xc(i.windowStartMs);if(i.type==="count"){var u,c={attributes:a,startTimeUnixNano:l,timeUnixNano:e,asDouble:(u=i.total)!==null&&u!==void 0?u:0};o.sum.dataPoints.push(c)}else if(i.type==="gauge"){var d,f={attributes:a,timeUnixNano:e,asDouble:(d=i.last)!==null&&d!==void 0?d:0};o.gauge.dataPoints.push(f)}else i.hist&&o.histogram.dataPoints.push({attributes:a,startTimeUnixNano:l,timeUnixNano:e,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:ho})}return Array.from(n.values())}Yt(t){var e,n;for(var i of t){var r=i[0],s=i[1],o=this.Bt.get(r);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,s.windowStartMs),o.type){case"count":o.total=((e=o.total)!==null&&e!==void 0?e:0)+((n=s.total)!==null&&n!==void 0?n:0);break;case"gauge":break;case"histogram":if(s.hist)if(o.hist){o.hist.count+=s.hist.count,o.hist.sum+=s.hist.sum,o.hist.min=Math.min(o.hist.min,s.hist.min),o.hist.max=Math.max(o.hist.max,s.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=s.hist.bucketCounts[a]}else o.hist=s.hist}else this.Qt()&&this.Bt.set(r,s)}}};var gr,kc,po;function ig(t){var e=globalThis._posthogChunkIds;if(e){var n=Object.keys(e);return po&&n.length===kc||(kc=n.length,po=n.reduce(((i,r)=>{gr||(gr={});var s=gr[r];if(s)i[s[0]]=s[1];else for(var o=t(r),a=o.length-1;a>=0;a--){var l=o[a],u=l?.filename,c=e[r];if(u&&c){i[u]=c,gr[r]=[u,c];break}}return i}),{})),po}}class rg{constructor(e,n,i){i===void 0&&(i=[]),this.coercers=e,this.stackParser=n,this.modifiers=i}buildFromUnknown(e,n){n===void 0&&(n={});var i=n&&n.mechanism||{handled:!0,type:"generic"},r=this.buildCoercingContext(i,n,0).apply(e),s=this.buildParsingContext(n),o=this.parseStacktrace(r,s);return{$exception_list:this.convertToExceptionList(o,i),$exception_level:"error"}}modifyFrames(e){var n=this;return se((function*(){for(var i of e)i.stacktrace&&i.stacktrace.frames&&U(i.stacktrace.frames)&&(i.stacktrace.frames=yield n.applyModifiers(i.stacktrace.frames));return e}))()}coerceFallback(e){var n;return{type:"Error",value:"Unknown error",stack:(n=e.syntheticException)==null?void 0:n.stack,synthetic:!0}}parseStacktrace(e,n){var i,r;return e.cause!=null&&(i=this.parseStacktrace(e.cause,n)),e.stack!=""&&e.stack!=null&&(r=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?n.skipFirstLines:0),n.chunkIdMap)),k({},e,{cause:i,stack:r})}applyChunkIds(e,n){return e.map((i=>(i.filename&&n&&(i.chunk_id=n[i.filename]),i)))}applyCoercers(e,n){for(var i of this.coercers)if(i.match(e))return i.coerce(e,n);return this.coerceFallback(n)}applyModifiers(e){var n=this;return se((function*(){var i=e;for(var r of n.modifiers)i=yield r(i);return i}))()}convertToExceptionList(e,n){var i,r,s,o={type:e.type,value:e.value,mechanism:{type:(i=n.type)!==null&&i!==void 0?i:"generic",handled:(r=n.handled)===null||r===void 0||r,synthetic:(s=e.synthetic)!==null&&s!==void 0&&s}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,k({},n,{handled:!0}))),a}buildParsingContext(e){var n;return{chunkIdMap:ig(this.stackParser),skipFirstLines:(n=e.skipFirstLines)!==null&&n!==void 0?n:1}}buildCoercingContext(e,n,i){i===void 0&&(i=0);var r=(s,o)=>{if(4>=o){var a=this.buildCoercingContext(e,n,o);return this.applyCoercers(s,a)}};return k({},n,{syntheticException:i==0?n.syntheticException:void 0,mechanism:e,apply:s=>r(s,i),next:s=>r(s,i+1)})}}var ni="?";function Qo(t,e,n,i,r){var s={platform:t,filename:e,function:n===""?ni:n,in_app:!0};return C(i)||(s.lineno=i),C(r)||(s.colno=r),s}var Hd=(t,e)=>{var n=t.indexOf("safari-extension")!==-1,i=t.indexOf("safari-web-extension")!==-1;return n||i?[t.indexOf("@")!==-1?t.split("@")[0]:ni,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},sg=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,og=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,ag=/\((\S*)(?::(\d+))(?::(\d+))\)/,lg=(t,e)=>{var n=sg.exec(t);if(n)return Qo(e,n[1],ni,+n[2],+n[3]);var i=og.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var r=ag.exec(i[2]);r&&(i[2]=r[1],i[3]=r[2],i[4]=r[3])}var s=Hd(i[1]||ni,i[2]);return Qo(e,s[1],s[0],i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},cg=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,ug=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,dg=(t,e)=>{var n=cg.exec(t);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){var i=ug.exec(n[3]);i&&(n[1]=n[1]||"eval",n[3]=i[1],n[4]=i[2],n[5]="")}var r=n[3],s=n[1]||ni,o=Hd(s,r);return Qo(e,r=o[1],s=o[0],n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},Cc=/\(error: (.*)\)/;class fg{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,n){var i=X(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:i?e.stack:void 0,cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var n=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?n+": "+e.message:n}isDOMException(e){return Hr(e,"DOMException")}isDOMError(e){return Hr(e,"DOMError")}}class hg{match(e){return(function(n){switch({}.toString.call(n)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return md(n,Error)}})(e)}coerce(e,n){return{type:this.getType(e),value:this.getMessage(e,n),stack:this.getStack(e),cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,n){var i=e.message;return String(i.error&&typeof i.error.message=="string"?i.error.message:i)}getStack(e){return e.stacktrace||e.stack||void 0}}class pg{constructor(){}match(e){return!!Hr(e,"ErrorEvent")&&(e.error!=null||this.fe(e))}coerce(e,n){var i;if(e.error!=null)return n.apply(e.error);var r=n.apply(e.message);return k({},r,{stack:(i=this.pe(e))!==null&&i!==void 0?i:r.stack,synthetic:!0})}fe(e){return X(e.message)&&e.message.length>0}pe(e){var n=e;if(X(n.filename)&&n.filename.length>0){var i,r,s=(i=n.lineno)!==null&&i!==void 0?i:0,o=(r=n.colno)!==null&&r!==void 0?r:0;return`Error - at `+n.filename+":"+s+":"+o}}}var gg=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class mg{match(e){return typeof e=="string"}coerce(e,n){var i,r=this.getInfos(e),s=r[0],o=r[1];return{type:s??"Error",value:o??e,stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}getInfos(e){var n="Error",i=e,r=e.match(gg);return r&&(n=r[1],i=r[2]),[n,i]}}var vg=["fatal","error","warning","log","info","debug"];function Wd(t,e){e===void 0&&(e=40);var n=Object.keys(t);if(n.sort(),!n.length)return"[object has no keys]";for(var i=n.length;i>0;i--){var r=n.slice(0,i).join(", ");if(e>=r.length)return i===n.length?r:r.length>e?r.slice(0,e)+"...":r}return""}class _g{match(e){return typeof e=="object"&&e!==null}coerce(e,n){var i,r,s=this.getErrorPropertyFromObject(e);return s?n.apply(s):{type:this.getType(e),value:this.getValue(e),stack:(i=this.getStack(e))!==null&&i!==void 0?i:(r=n.syntheticException)==null?void 0:r.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return Xa(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var n="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(n+=" with message: '"+e.message+"'"),n}if("message"in e&&typeof e.message=="string")return e.message;var i=this.getObjectClassName(e);return(i&&i!=="Object"?"'"+i+"'":"Object")+" captured as exception with keys: "+Wd(e)}isSeverityLevel(e){return X(e)&&!Ko(e)&&vg.indexOf(e)>=0}getStack(e){try{return X(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:X(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(var n in e)if({}.hasOwnProperty.call(e,n)){var i=e[n];if(Xp(i))return i}}getObjectClassName(e){try{var n=Object.getPrototypeOf(e);return n?n.constructor.name:void 0}catch{return}}}class yg{match(e){return Xa(e)}coerce(e,n){var i,r=e.constructor.name;return{type:r,value:r+" captured as exception with keys: "+Wd(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class wg{match(e){return gd(e)}coerce(e,n){var i;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class bg{match(e){return Hr(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Xa(e))return!1;try{var n=e.detail;return n!=null&&typeof n=="object"&&"reason"in n}catch{return!1}}coerce(e,n){var i,r=this.getUnhandledRejectionReason(e);return gd(r)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(r),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}:n.apply(r)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}}var Kr="$message",Yr="$timestamp",Eg=new Set([Kr,Yr]),go={enabled:!0,max_bytes:32768};function Jr(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:go.enabled,max_bytes:xg(t.max_bytes,go.max_bytes)}:k({},go)}class Sg{constructor(e){this.Ke=[],this.Je=0,this.Ne=Jr(e)}setConfig(e){this.Ne=Jr(e),this.Xe()}add(e){var n=(function(r){var s;try{s=fd(r)}catch{return}try{var o=JSON.parse(s);if(!he(o))return;var a=o,l=a[Kr],u=a[Yr];return!X(l)||l.trim().length===0||!X(u)&&!ke(u)?void 0:{step:a,json:s}}catch{return}})(e);if(n){var i=(function(r){if(typeof TextEncoder<"u")return new TextEncoder().encode(r).length;for(var s=encodeURIComponent(r),o=0,a=0;s.length>a;a++)s[a]==="%"?(o+=1,a+=2):o+=1;return o})(n.json);i>this.Ne.max_bytes||(this.Ke.push({step:n.step,bytes:i}),this.Je+=i,this.Xe())}}getAttachable(){return this.Ke.map((e=>e.step))}clear(){this.Ke=[],this.Je=0}size(){return this.Ke.length}Xe(){for(;this.Je>this.Ne.max_bytes&&this.Ke.length>0;){var e=this.Ke.shift();e&&(this.Je-=e.bytes)}}}function xg(t,e){if(!ke(t)||t===1/0||t===-1/0)return e;var n=Math.floor(t);return 0>n?e:n}var qd=function(t,e){var n=(e===void 0?{}:e).debugEnabled,i={k(r){if(w&&(ne.DEBUG||w.POSTHOG_DEBUG||n)&&!C(w.console)&&w.console){for(var s=("__rrweb_original__"in w.console[r])?w.console[r].__rrweb_original__:w.console[r],o=arguments.length,a=new Array(o>1?o-1:0),l=1;o>l;l++)a[l-1]=arguments[l];s(t,...a)}},debug(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("debug",...s)},info(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("log",...s)},warn(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("warn",...s)},error(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("error",...s)},critical(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];console.error(t,...s)},uninitializedWarning(r){i.error("You must initialize PostHog before calling "+r)},createLogger:(r,s)=>qd(t+" "+r,s)};return i},A=qd("[PostHog.js]"),pe=A.createLogger,Ig=pe("[ExternalScriptsLoader]"),mo=(t,e,n)=>{if(t.config.disable_external_dependency_loading)return Ig.warn(e+" was requested but loading of external scripts is disabled."),n("Loading of external scripts is disabled");var i=F?.querySelectorAll("script");if(i){for(var r,s=function(){if(i[o].src===e){var l=i[o];return l.__posthog_loading_callback_fired?{v:n()}:(l.addEventListener("load",(u=>{l.__posthog_loading_callback_fired=!0,n(void 0,u)})),l.onerror=u=>n(u),{v:void 0})}},o=0;i.length>o;o++)if(r=s())return r.v}var a=()=>{if(!F)return n("document not found");var l=F.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=d=>{l.__posthog_loading_callback_fired=!0,n(void 0,d)},l.onerror=d=>n(d),t.config.prepare_external_dependency_script&&(l=t.config.prepare_external_dependency_script(l)),!l)return n("prepare_external_dependency_script returned null");if(t.config.external_scripts_inject_target==="head")F.head.appendChild(l);else{var u,c=F.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):F.body.appendChild(l)}};F!=null&&F.body?a():F?.addEventListener("DOMContentLoaded",a)};B.__PosthogExtensions__=B.__PosthogExtensions__||{},B.__PosthogExtensions__.loadExternalDependency=(t,e,n)=>{if(e!=="remote-config"){var i;if(t.config.strict_script_versioning)i=t.requestRouter.endpointFor("assets","/static/"+t.version+"/"+e+".js");else{var r="/static/"+e+".js?v="+t.version;if(e==="toolbar"){var s=3e5;r=r+"&t="+Math.floor(Date.now()/s)*s}i=t.requestRouter.endpointFor("assets",r)}mo(t,i,n)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");mo(t,o,n)}},B.__PosthogExtensions__.loadSiteApp=(t,e,n)=>{var i=t.requestRouter.endpointFor("api",e);mo(t,i,n)};ne.DEBUG=!1,ne.LIB_VERSION="1.415.7",ne.LIB_NAME="web";var zd="$people_distinct_id",Yi="$device_id",vo="$device_model",Fi="__alias",Ri="__timers",ea="$autocapture_disabled_server_side",ta="$heatmaps_enabled_server_side",na="$exception_capture_enabled_server_side",ia="$error_tracking_suppression_rules",ra="$error_tracking_capture_extension_exceptions",sa="$web_vitals_enabled_server_side",rl="$dead_clicks_enabled_server_side",sl="$product_tours_enabled_server_side",oa="$web_vitals_allowed_metrics",An="$session_recording_remote_config",Vd="$replay_sample_rate",Gd="$replay_override_sampling",Kd="$replay_override_linked_flag",Yd="$replay_override_url_trigger",Jd="$replay_override_event_trigger",Kn="$sesid",ol="$session_is_sampled",Sn="$enabled_feature_flags",Ti="$active_feature_flags",Ar="$early_access_features",aa="$feature_flag_details",$i="$feature_flag_payloads",Pr="$feature_flag_request_id",Zr="$minimal_flag_called_events",xt="$override_feature_flags",xn="$override_feature_flag_payloads",Dt="$stored_person_properties",In="$stored_group_properties",la="$surveys",Xr="$surveys_loaded_at",ca="$surveys_activated",Fr="$surveys_activated_session",Rr="$surveys_activated_timestamps",Mi="ph_product_tours",Cn="$flag_call_reported",Li="$flag_call_reported_session_id",Tr="$feature_flag_errors",ji="$feature_flag_evaluated_at",ot="$user_state",ua="$client_session_props",da="$capture_rate_limit",fa="$initial_campaign_params",ha="$initial_referrer_info",Qr="$initial_person_info",es="$epp",mr="$posthog_cookieless",Zd="$cookieless_mode",Xd="$sdk_debug_extensions_init_method",Qd="$sdk_debug_extensions_init_time_ms",ef="$sdk_debug_recording_script_not_loaded",al="PostHog loadExternalDependency extension not found.",kn="on_reject",Ht="always",Un="anonymous",vn="identified",pa="identified_only",ts="visibilitychange",ns="beforeunload",Vn="$pageview",_o="$pageleave",yo="$identify",Ac="$groupidentify";function vr(t,e){U(t)&&t.forEach(e)}function ie(t,e){if(!H(t))if(U(t))t.forEach(e);else if(Np(t))t.forEach(((i,r)=>e(i,r)));else for(var n in t)pd.call(t,n)&&e(t[n],n)}var fe=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;e>i;i++)n[i-1]=arguments[i];for(var r of n)for(var s in r)r[s]!==void 0&&(t[s]=r[s]);return t};function $r(t){for(var e=Object.keys(t),n=e.length,i=new Array(n);n--;)i[n]=[e[n],t[e[n]]];return i}var Pc=function(t){try{return t()}catch{return}},kg=function(t){return function(){try{for(var e=arguments.length,n=new Array(e),i=0;e>i;i++)n[i]=arguments[i];return t.apply(this,n)}catch(r){A.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),A.critical(r)}}},ll=function(t){var e={};return ie(t,(function(n,i){(X(n)&&n.length>0||ke(n))&&(e[i]=n)})),e},Cg=["herokuapp.com","vercel.app","netlify.app"];function Ag(t){var e=t?.hostname;if(!X(e))return!1;var n=e.split(".").slice(-2).join(".");for(var i of Cg)if(n===i)return!1;return!0}function ve(t,e,n,i){var r=i??{},s=r.capture,o=r.passive;t?.addEventListener(e,n,{capture:s!==void 0&&s,passive:o===void 0||o})}function ga(t){return t.name==="ph_toolbar_internal"}var tf=t=>{if(F){try{for(var e=t+"=",n=F.cookie.split(";").filter((s=>s.length)),i=0;n.length>i;i++){for(var r=n[i];r.charAt(0)==" ";)r=r.substring(1,r.length);if(r.indexOf(e)===0)return decodeURIComponent(r.substring(e.length,r.length))}}catch{}return null}};Math.trunc||(Math.trunc=function(t){return 0>t?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return ke(t)&&isFinite(t)&&Math.floor(t)===t});class is{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,n,i,r){if(!Number.isInteger(e)||!Number.isInteger(n)||!Number.isInteger(i)||!Number.isInteger(r)||0>e||0>n||0>i||0>r||e>0xffffffffffff||n>4095||i>1073741823||r>4294967295)throw new RangeError("invalid field value");var s=new Uint8Array(16);return s[0]=e/Math.pow(2,40),s[1]=e/Math.pow(2,32),s[2]=e/Math.pow(2,24),s[3]=e/Math.pow(2,16),s[4]=e/256,s[5]=e,s[6]=112|n>>>8,s[7]=n,s[8]=128|i>>>24,s[9]=i>>>16,s[10]=i>>>8,s[11]=i,s[12]=r>>>24,s[13]=r>>>16,s[14]=r>>>8,s[15]=r,new is(s)}toString(){for(var e="",n=0;this.bytes.length>n;n++)e=e+(this.bytes[n]>>>4).toString(16)+(15&this.bytes[n]).toString(16),n!==3&&n!==5&&n!==7&&n!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new is(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var n=0;16>n;n++){var i=this.bytes[n]-e.bytes[n];if(i!==0)return Math.sign(i)}return 0}}class Pg{generate(){var e=this.generateOrAbort();if(!C(e))return e;this.S=0;var n=this.generateOrAbort();if(C(n))throw new Error("Could not generate UUID after timestamp reset");return n}generateOrAbort(){var e=Date.now();if(e>this.S)this.S=e,this.C();else{if(this.S>=e+1e4)return;this.I++,this.I>4398046511103&&(this.S++,this.C())}return is.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 Fg}}var Fc,nf=t=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;t.length>e;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};w&&!C(w.crypto)&&crypto.getRandomValues&&(nf=t=>crypto.getRandomValues(t));class Fg{nextUint32(){return this.R.length>this.O||(nf(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var Ut=()=>Rg().toString(),Rg=()=>(Fc||(Fc=new Pg)).generate(),yi="",Tg=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,Wt={N:()=>!!F,j(t){A.error("cookieStore error: "+t)},P:tf,H(t){var e;try{e=JSON.parse(Wt.P(t))||{}}catch{}return e},F(t,e,n,i,r){if(!F)return!1;try{var s="",o="",a=(function(c,d){if(d){var f=(function(p,g){if(g===void 0&&(g=F),yi)return yi;if(!g||["localhost","127.0.0.1"].includes(p))return"";for(var m=p.split("."),v=Math.min(m.length,8),S="dmn_chk_"+Ut();!yi&&v--;){var b=m.slice(v).join("."),_=S+"=1;domain=."+b+";path=/";g.cookie=_+";max-age=3",g.cookie.includes(S)&&(g.cookie=_+";max-age=0",yi=b)}return yi})(c);if(!f){var h=(p=>{var g=p.match(Tg);return g?g[0]:""})(c);h!==f&&A.info("Warning: cookie subdomain discovery mismatch",h,f),f=h}return f?"; domain=."+f:""}return""})(F.location.hostname,i);if(n){var l=new Date;l.setTime(l.getTime()+864e5*n),s="; expires="+l.toUTCString()}r&&(o="; secure");var u=t+"="+encodeURIComponent(JSON.stringify(e))+s+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&A.warn("cookieStore warning: large cookie, len="+u.length),F.cookie=u,!0}catch{return!1}},q(t,e){if(F!=null&&F.cookie)try{Wt.F(t,"",-1,e)}catch{return}}},wo=null,le={N(){if(!Ke(wo))return wo;var t=!0;if(C(w))t=!1;else try{var e="__mplssupport__";le.F(e,"xyz"),le.P(e)!=='"xyz"'&&(t=!1),le.q(e)}catch{t=!1}return t||A.error("localStorage unsupported; falling back to cookie store"),wo=t,t},j(t){A.error("localStorage error: "+t)},P(t){try{return w?.localStorage.getItem(t)}catch(e){le.j(e)}return null},H(t){try{return JSON.parse(le.P(t))||{}}catch{}return null},F(t,e){try{return w?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(n){le.j(n)}return!1},q(t){try{w?.localStorage.removeItem(t)}catch(e){le.j(e)}}},$g=[Yi,"distinct_id",Kn,ol,es,Qr,ot],_r={},Mg={N:()=>!0,j(t){A.error("memoryStorage error: "+t)},P:t=>_r[t]||null,H:t=>_r[t]||null,F:(t,e)=>(_r[t]=e,!0),q(t){delete _r[t]}},_n=null,be={N(){if(!Ke(_n))return _n;if(_n=!0,C(w))_n=!1;else try{var t="__support__";be.F(t,"xyz"),be.P(t)!=='"xyz"'&&(_n=!1),be.q(t)}catch{_n=!1}return _n},j(t){A.error("sessionStorage error: ",t)},P(t){try{return w?.sessionStorage.getItem(t)}catch(e){be.j(e)}return null},H(t){try{return JSON.parse(be.P(t))||null}catch{}return null},F(t,e){try{return w?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(n){be.j(n)}return!1},q(t){try{w?.sessionStorage.removeItem(t)}catch(e){be.j(e)}}};class Lg{constructor(e){this._instance=e}get Ne(){return this._instance.config}get consent(){return this.ti()?0:this.ei}isOptedOut(){return this.Ne.cookieless_mode===Ht||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===kn}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===0}isRejected(){return this.consent===0||this.consent===-1&&this.Ne.opt_out_capturing_by_default}optInOut(e){this.ii.F(this.ri,e?1:0,this.Ne.cookie_expiration,this.Ne.cross_subdomain_cookie,this.Ne.secure_cookie)}reset(){this.ii.q(this.ri,this.Ne.cross_subdomain_cookie)}get ri(){var e=this._instance.config,n=e.token,i=e.opt_out_capturing_cookie_prefix;return e.consent_persistence_name||(i?i+n:"__ph_opt_in_out_"+n)}get ei(){var e=this.ii.P(this.ri);return uo(e)?1:j(jp,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,n=e==="localStorage"?le:Wt;if(!this.ni||this.ni!==n){this.ni=n;var i=e==="localStorage"?Wt:le;i.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(uo(i.P(this.ri))),i.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[Ue?.doNotTrack,Ue?.msDoNotTrack,B.doNotTrack].some((e=>uo(e)))}}function rf(t,e){var n,i=t==null||(n=t.config)==null?void 0:n.get_current_url;if(!De(i))return e;try{var r=i(e);return X(r)&&r?r:e}catch(s){return A.error("Error in get_current_url, falling back to window.location.href",s),e}}var sf="__POSTHOG_TOOLBAR__",Ng=1,Og=3,Bg=11;function Rc(t){return t instanceof Element&&(t.id===sf||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function hn(t){return!!t&&t.nodeType===Ng}function Qe(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function of(t){return!!t&&t.nodeType===Og}function af(t){return!!t&&t.nodeType===Bg&&hn(t.host)}var lf=1e3;function cl(t){return t?xs(t).split(/\s+/):[]}function Tc(t,e){var n=(function(i){var r,s=w==null||(r=w.location)==null?void 0:r.href;return C(s)?void 0:rf(i,s)})(e);return!!(n&&t&&t.some((i=>n.match(i))))}function rs(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 cl(e)}function cf(t){return H(t)?null:xs(t).split(/(\s+)/).filter((e=>Ui(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function Ji(t){var e="";return va(t)&&!hf(t)&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;of(n)&&n.textContent&&(e+=(i=cf(n.textContent))!==null&&i!==void 0?i:"")})),xs(e)}function bo(t){var e;return C(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var ul=["a","button","form","input","select","textarea","label"];function ma(t,e){if(C(e))return!0;var n,i=function(s){if(e.some((o=>(function(a,l){var u=a.matches||a.matchesSelector||a.msMatchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.oMatchesSelector;try{return!!u&&u.call(a,l)}catch{return!1}})(s,o))))return{v:!0}};for(var r of t)if(n=i(r))return n.v;return!1}function uf(t){var e=t.parentNode;return!(!e||!hn(e))&&e}var Dg=[".ph-no-autocapture","[data-ph-no-autocapture]"],df=["next","previous","prev",">","<"],jg=[...df,"+","-","−","–"],$c=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,Mc=[".ph-no-rageclick",".ph-no-capture"],Ug=["","text","search","email","password","url","tel","number"];function Lc(t,e){if(!w||dl(t))return!1;var n,i,r,s,o;if(gt(e)?(n=!!e&&Mc,i=void 0,r=!1):(n=(s=e?.css_selector_ignorelist)!==null&&s!==void 0?s:Mc,i=e?.content_ignorelist,r=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),n===!1||r&&(function(l){return!(!l||!hn(l))&&(!!Qe(l,"textarea")||(Qe(l,"input")?j(Ug,(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=ff(t,!1).targetElementList;return!(function(l,u){if(l===!1||C(l))return!1;var c;if(l===!0)c=df;else{if(!U(l))return!1;if(l.length>10)return A.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var f=d.safeText,h=d.ariaLabel;return c.some((p=>$c(f,p)||$c(h,p)))}))})(i,a.map((l=>{var u;return{safeText:Ji(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!ma(a,n)}var dl=t=>!t||Qe(t,"html")||!hn(t),ff=(t,e)=>{if(!w||dl(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,i=[t],r=t;r.parentNode&&!Qe(r,"body");)if(af(r.parentNode))i.push(r.parentNode.host),r=r.parentNode.host;else{var s=uf(r);if(!s)break;if(e||ul.indexOf(s.tagName.toLowerCase())>-1)n=!0;else try{var o=w.getComputedStyle(s);o&&o.getPropertyValue("cursor")==="pointer"&&(n=!0)}catch{}i.push(s),r=s}return{parentIsUsefulElement:n,targetElementList:i}};function va(t){for(var e=new Set,n=0,i=t;i.parentNode&&!Qe(i,"body");i=i.parentNode){if(n++>=lf||e.has(i))return!1;e.add(i);var r=rs(i);if(j(r,"ph-sensitive")||j(r,"ph-no-capture"))return!1}if(j(rs(t),"ph-include"))return!0;var s=t.type||"";if(X(s))switch(s.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!X(o)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(o.replace(/[^a-zA-Z0-9]/g,""))}function hf(t){return!!(Qe(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||Qe(t,"select")||Qe(t,"textarea")||t.getAttribute("contenteditable")==="true")}var Nc=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}))$"),Oc=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,Hg=[16,15,14,13],Wg=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),Bc=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),Dc=/[0-9A-Za-z_]/;function qg(t){for(var e=0,n=!1,i=t.length-1;i>=0;i--){var r=t.charCodeAt(i)-48;n&&(r*=2)>9&&(r-=9),e+=r,n=!n}return e%10==0}function Ui(t,e){if(e===void 0&&(e=!0),H(t))return!1;if(X(t)){t=xs(t);var n=e?Nc.test((t||"").replace(/[- ]/g,"")):(function(r){var s;for(Oc.lastIndex=0;s=Oc.exec(r);){var o=s[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of Hg){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(Nc.test(d)&&qg(d))return!0}}}return!1})(t);if(n)return!1;var i=e?Wg.test(t):(function(r){var s;for(Bc.lastIndex=0;s=Bc.exec(r);){var o=s[1],a=s[3];if(!(o&&a&&Dc.test(o)&&Dc.test(a)))return!0}return!1})(t);if(i)return!1}return!0}function jc(t){var e=Ji(t);return Ui(e=(e+" "+pf(t)).trim())?e:""}function pf(t){var e="";return t&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;if(n&&((i=n.tagName)==null?void 0:i.toLowerCase())==="span")try{var r=Ji(n);e=(e+" "+r).trim(),n.childNodes&&n.childNodes.length&&(e=(e+" "+pf(n)).trim())}catch(s){A.error("[AutoCapture]",s)}})),e}function Uc(t){return t.replace(/"|\\"/g,'\\"')}function zg(t){var e=t.attr__class;if(e)return U(e)?e:cl(e)}var yr=pe("[Dead Clicks]"),Vg=()=>!0,Gg=t=>{var e,n=!((e=t.instance.persistence)==null||!e.get_property(rl)),i=t.instance.config.capture_dead_clicks;return gt(i)?i:!!he(i)||n};class Hc{get lazyLoadedDeadClicksAutocapture(){return this.si}constructor(e,n,i){this.instance=e,this.isEnabled=n,this.onCapture=i,this.startIfEnabledOrStop()}onRemoteConfig(e){if(e.ok){var n=e.config;"captureDeadClicks"in n&&(this.instance.persistence&&this.instance.persistence.register({[rl]:n.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var n,i;(n=B.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture?e():(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"dead-clicks-autocapture",(r=>{r?yr.error("failed to load script",r):e()}))}oi(){var e;if(F){if(!this.si&&(e=B.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var n=he(this.instance.config.capture_dead_clicks)?k({},this.instance.config.capture_dead_clicks):{};n.__onCapture=this.onCapture,this.onCapture&&(n.capture_dead_swipes=!1),this.si=B.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.si.start(F),yr.info("starting...")}}else yr.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,yr.info("stopping..."))}}var Eo=pe("[SegmentIntegration]"),gf="posthog-js";function mf(t,e){var n=e===void 0?{}:e,i=n.organization,r=n.projectId,s=n.prefix,o=n.severityAllowList,a=o===void 0?["error"]:o,l=n.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,f,h,p,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var v,S=((d=c.exception)==null?void 0:d.values)||[],b=S.map((x=>k({},x,{stacktrace:x.stacktrace?k({},x.stacktrace,{type:"raw",frames:(x.stacktrace.frames||[]).map((I=>k({},I,{platform:"web:javascript"})))}):void 0}))),_={$exception_message:((f=S[0])==null?void 0:f.value)||c.message,$exception_type:(h=S[0])==null?void 0:h.type,$exception_level:c.level,$exception_list:b,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((p=S[0])==null?void 0:p.value)||c.message,$sentry_exception_type:(g=S[0])==null?void 0:g.type,$sentry_tags:c.tags};return i&&r&&(_.$sentry_url=(s||"https://sentry.io/organizations/")+i+"/issues/?project="+r+"&query="+c.event_id),u&&((v=t.exceptions)==null||v.sendExceptionEvent(_)),c}}class Kg{constructor(e,n,i,r,s,o){this.name=gf,this.setupOnce=function(a){a(mf(e,{organization:n,projectId:i,prefix:r,severityAllowList:s,sendExceptionsToPostHog:o==null||o}))}}}class Wc{constructor(e){this.li=(n,i,r)=>{r&&(r.noSessionId||r.activityTimeout||r.sessionPastMaximumLength||r.crossTabAdoption)&&(A.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:n,changeReason:r}),this.ui=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.hi()}hi(){var e;this.di=(e=this._instance.sessionManager)==null?void 0:e.onSessionId(this.li)}destroy(){var e;(e=this.di)==null||e.call(this),this.di=void 0}doPageView(e,n){var i,r=this.vi(e,n);return this.ui={pathname:(i=w?.location.pathname)!==null&&i!==void 0?i:"",pageViewId:n,timestamp:e},this._instance.scrollManager.resetContext(),r}doPageLeave(e){var n;return this.vi(e,(n=this.ui)==null?void 0:n.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.ui)==null?void 0:e.pageViewId}}vi(e,n){var i=this.ui;if(!i)return{$pageview_id:n};var r={$pageview_id:n,$prev_pageview_id:i.pageViewId},s=this._instance.scrollManager.getContext();if(s&&!this._instance.config.disable_scroll_properties){var o=s.maxScrollHeight,a=s.lastScrollY,l=s.maxScrollY,u=s.maxContentHeight,c=s.lastContentY,d=s.maxContentY;if(!(C(o)||C(a)||C(l)||C(u)||C(c)||C(d))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),d=Math.ceil(d);var f=o>1?Ct(a/o,0,1,A):1,h=o>1?Ct(l/o,0,1,A):1,p=u>1?Ct(c/u,0,1,A):1,g=u>1?Ct(d/u,0,1,A):1;r=fe(r,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:f,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:h,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:p,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return i.pathname&&(r.$prev_pageview_pathname=i.pathname),i.timestamp&&(r.$prev_pageview_duration=(e.getTime()-i.timestamp.getTime())/1e3),r}}var So=["flags","surveys"],Yg={[zd]:{exposure:"hidden"},[Fi]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[Ri]:{exposure:"hidden"},[ea]:{exposure:"event"},[ta]:{exposure:"hidden"},[na]:{exposure:"event"},[ia]:{exposure:"hidden"},[ra]:{exposure:"event"},[sa]:{exposure:"event"},[rl]:{exposure:"event"},[sl]:{exposure:"hidden"},[oa]:{exposure:"event"},[An]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[Kn]:{exposure:"hidden"},[ol]:{exposure:"event"},[Vd]:{exposure:"event",shouldSkipFromEventProperties:t=>Ke(t)},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},$sess_rec_flush_size:{exposure:"hidden"},[Sn]:{exposure:"hidden",storageGroup:"flags"},[Ti]:{exposure:"hidden",storageGroup:"flags"},[Ar]:{exposure:"hidden"},[aa]:{exposure:"hidden",storageGroup:"flags"},[$i]:{exposure:"hidden",storageGroup:"flags"},[Pr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[Zr]:{exposure:"hidden",storageGroup:"flags"},[xt]:{exposure:"hidden"},[xn]:{exposure:"hidden"},[Dt]:{exposure:"hidden"},[In]:{exposure:"hidden"},[la]:{exposure:"hidden",storageGroup:"surveys"},[Xr]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[ca]:{exposure:"event"},[Fr]:{exposure:"hidden"},[Rr]:{exposure:"hidden"},[Mi]:{exposure:"hidden"},$product_tours_activated:{exposure:"hidden"},$product_tours_activated_session:{exposure:"hidden"},$conversations_widget_session_id:{exposure:"event"},$conversations_ticket_id:{exposure:"event"},$conversations_widget_state:{exposure:"event"},$conversations_user_traits:{exposure:"event"},[Cn]:{exposure:"hidden"},[Li]:{exposure:"hidden"},[Tr]:{exposure:"hidden"},[ji]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[ot]:{exposure:"hidden"},[ua]:{exposure:"hidden"},[da]:{exposure:"hidden"},[fa]:{exposure:"hidden"},[ha]:{exposure:"hidden"},[Qr]:{exposure:"hidden"},[es]:{exposure:"hidden"},[Gd]:{exposure:"event"},[Kd]:{exposure:"event"},[Yd]:{exposure:"event"},[Jd]:{exposure:"event"},[Xd]:{exposure:"event"},[Qd]:{exposure:"event"},[ef]:{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"}},Jg=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],yn=t=>{var e=Yg[t];if(e)return e;for(var n of Jg){var i=n[1];if(t.indexOf(n[0])===0)return i}},Yn=(t,e)=>{try{return JSON.stringify(t,((n,i)=>typeof i=="bigint"?i.toString():i),e)}catch{return fd(t)}},ss=t=>{var e=F?.createElement("a");return C(e)?null:(e.href=t,e)},ii=function(t,e){for(var n,i=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),r=0;i.length>r;r++){var s=i[r].split("=");if(s[0]===e){n=s;break}}if(!U(n)||2>n.length)return"";var o=n[1];try{o=decodeURIComponent(o)}catch{A.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},Zi=function(t,e,n){if(!t||!e||!e.length)return t;for(var i=t.split("#"),r=i[1],s=(i[0]||"").split("?"),o=s[1],a=s[0],l=(o||"").split("&"),u=[],c=0;l.length>c;c++){var d=l[c].split("=");U(d)&&(e.includes(d[0])?u.push(d[0]+"="+n):u.push(l[c]))}var f=a;return o!=null&&(f+="?"+u.join("&")),r!=null&&(f+="#"+r),f},os=function(t,e){var n=t.match(new RegExp(e+"=([^&]*)"));return n?n[1]:null},vf=(t,e)=>t>=e&&cd(),_f=(t,e,n,i)=>{if(t===0){if(cd()){var r=e+1;return r===n&&i(),r}return e}return 0},wr="https?://(.*)",ri=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Zg=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...ri],Xi="",Xg=["li_fat_id"];function yf(t,e,n){if(!F)return{};var i,r=e?[...ri,...n||[]]:[],s=wf(Zi(F.URL,r,Xi),t),o=(i={},ie(Xg,(function(a){var l=tf(a);i[a]=l||null})),i);return fe(o,s)}function wf(t,e){var n=Zg.concat(e||[]),i={};return ie(n,(function(r){var s=ii(t,r);i[r]=s||null})),i}function bf(t){var e=(function(s){return s?s.search(wr+"google.([^/?]*)")===0?"google":s.search(wr+"bing.com")===0?"bing":s.search(wr+"yahoo.com")===0?"yahoo":s.search(wr+"duckduckgo.com")===0?"duckduckgo":null:null})(t),n=e!="yahoo"?"q":"p",i={};if(!Ke(e)){i.$search_engine=e;var r=F?ii(F.referrer,n):"";r.length&&(i.ph_keyword=r)}return i}function qc(){return navigator.language||navigator.userLanguage}var as="$direct";function Ef(){return F?.referrer||as}function Sf(t,e,n){n===void 0&&(n=!1);var i=t?[...ri,...e||[]]:[],r=n?fn(me?.href):me?.href,s=r?.substring(0,1e3);return{r:Ef().substring(0,1e3),u:s?Zi(s,i,Xi):void 0}}function xf(t,e){var n;e===void 0&&(e=!1);var i=t.r,r=t.u,s=e?fn(r):r,o={$referrer:i,$referring_domain:i==null?void 0:i==as?as:(n=ss(i))==null?void 0:n.host};if(s){o.$current_url=s;var a=ss(s);o.$host=a?.host,o.$pathname=a?.pathname;var l=wf(s);fe(o,l)}if(i){var u=bf(i);fe(o,u)}return o}function If(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function Qg(){try{return new Date().getTimezoneOffset()}catch{return}}var em={flags:ji,surveys:Xr},tm=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],Hn="main";class xo{constructor(e,n,i){if(i===void 0&&(i=!0),this.ci={},this.fi=!1,this.pi=!1,this.Ne=e,this.gi=i,this.props={},this.mi=void 0,this.yi=(s=>{var o="";return s.token&&(o=s.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),s.persistence_name?"ph_"+s.persistence_name:"ph_"+o+"_posthog"})(e),this.ii=this.bi(e),this.pi=this.wi(e),this.load(),e.debug&&A.info("Persistence loaded",e.persistence,k({},this.props)),this.update_config(e,e,n),this.save(),w){var r=()=>this.flush();ve(w,"beforeunload",r,{capture:!1}),ve(w,"pagehide",r,{capture:!1})}}ki(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return ke(n)&&n>0?n:0}isDisabled(){return!!this.xi}bi(e){tm.indexOf(e.persistence.toLowerCase())===-1&&(A.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var n,i=(function(o,a){o===void 0&&(o=[]),a===void 0&&(a=!1);var l=[...$g,...o];return k({},le,{H(u){try{var c={};try{c=Wt.H(u)||{}}catch{}var d,f=JSON.parse(le.P(u)||"{}");if(a){var h={};for(var p in c){var g=c[p];Ke(g)||g===""||(h[p]=g)}d=fe(f,h)}else d=fe(c,f);return le.F(u,d),d}catch{}return null},F(u,c,d,f,h,p){var g=le.F(u,c,void 0,void 0,p);try{var m={};l.forEach((v=>{c[v]&&(m[v]=c[v])})),Object.keys(m).length&&Wt.F(u,m,d,f,h,p)}catch(v){le.j(v)}return g},q(u,c){try{w?.localStorage.removeItem(u),Wt.q(u,c)}catch(d){le.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),r=!1,s=e.persistence.toLowerCase();return s==="localstorage"&&le.N()?(n=le,r=!0):s==="localstorage+cookie"&&i.N()?(n=i,r=!0):s==="sessionstorage"&&be.N()?n=be:s==="memory"?n=Mg:s==="cookie"?n=Wt:i.N()?(n=i,r=!0):n=Wt,this.fi=r,n}Si(e){return this.yi+"__"+e}wi(e){return this.fi&&!!e.split_storage}properties(){var e={};return ie(this.props,((n,i)=>{var r=yn(i);if(!r||r.exposure==="event"){if(r!=null&&r.shouldSkipFromEventProperties!=null&&r.shouldSkipFromEventProperties(n))return;e[i]=n}})),e}load(){if(!this.xi){var e=this.ii.H(this.yi);e&&(this.props=fe({},e)),this.pi&&this.Ci()}}Ci(){for(var e of So){var n=le.H(this.Si(e));if(n&&!Gt(n)){var i=this.Mi(e);i.persisted=!0,this.Ti(e)||(i.fingerprint=this.Ei(n,e)),this.Ii(e,n)||fe(this.props,n)}}}Ti(e){return Object.keys(this.props).some((n=>{var i;return((i=yn(n))==null?void 0:i.storageGroup)===e}))}Ii(e,n){var i=em[e];if(!i)return!1;var r=n[i],s=this.props[i];return ke(r)&&ke(s)&&s>r}refreshKey(e){var n;if(!this.xi){var i=this.pi?(n=yn(e))==null?void 0:n.storageGroup:void 0,r=i?le.H(this.Si(i)):this.ii.H(this.yi);if(r&&e in r)this.Pi(e,r[e]);else{if(i){var s=this.ii.H(this.yi);if(s&&e in s)return void this.Pi(e,s[e])}this.Ri(e)}}}save(){if(!this.xi){var e=this.ki();e>0?C(this.Ai)&&(this.Ai=setTimeout((()=>{this.Ai=void 0,this.Fi()}),e)):this.Fi()}}flush(){C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0,this.Fi())}Fi(){this.xi||(this.pi?this.Li():this.Oi(this.ii,this.yi,this.props,Hn))}Li(){var e=this.Di(),n=e.main,i=e.groups;for(var r of(this.Oi(this.ii,this.yi,n,Hn),So)){var s,o=i[r];(!Gt(o)||(s=this.ci[r])!=null&&s.persisted)&&this.Oi(le,this.Si(r),o,r)}}Di(){var e={},n={flags:{},surveys:{}};return ie(this.props,((i,r)=>{var s,o=(s=yn(r))==null?void 0:s.storageGroup;o?n[o][r]=i:e[r]=i})),{main:e,groups:n}}Ei(e,n){if(n===Hn)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var i={};return ie(e,((r,s)=>{var o;i[s]=(o=yn(s))!=null&&o.volatile?"__volatile__":r})),JSON.stringify(i)}Oi(e,n,i,r){var s=this.Mi(r);if(r===Hn||s.dirty||C(s.fingerprint)){var o;try{if((o=this.Ei(i,r))===s.fingerprint)return void(s.dirty=!1)}catch{o=void 0}e.F(n,i,this.$i,this.Ni,this.qi,this.Ne.debug)?(s.dirty=!1,r!==Hn&&(s.persisted=!0),C(o)||(s.fingerprint=o)):this.Ne.debug&&A.warn('failed to persist storage entry "'+n+'"; will retry on next save')}}remove(e){var n=(e===void 0?{}:e).keepGroupEntries,i=n!==void 0&&n;if(C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0),this.ii.q(this.yi,!1),this.ii.q(this.yi,!0),!i&&this.gi)for(var r of So)le.q(this.Si(r));i?delete this.ci[Hn]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,n,i){if(he(e)){C(n)&&(n="None"),this.$i=C(i)?this.ji:i;var r=!1;if(ie(e,((s,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==n||(this.Pi(o,s),r=!0)})),r)return this.save(),!0}return!1}register(e,n){if(he(e)){this.$i=C(n)?this.ji:n;var i=!1;if(ie(e,((r,s)=>{e.hasOwnProperty(s)&&(this.props[s]!==r||he(r)||U(r))&&(this.Pi(s,r),i=!0)})),i)return this.save(),!0}return!1}unregister(e){var n=typeof e=="string"?[e]:e,i=!1;for(var r of n)r in this.props&&(this.Ri(r),i=!0);i&&this.save()}update_campaign_params(){var e=F?.URL;if(e!==this.mi){var n=yf(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);Gt(ll(n))||this.register(n),this.mi=e}}update_search_keyword(){var e;this.register((e=F?.referrer)?bf(e):{})}update_referrer_info(){var e;this.register_once({$referrer:Ef(),$referring_domain:F!=null&&F.referrer&&((e=ss(F.referrer))==null?void 0:e.host)||as},void 0)}set_initial_person_info(){this.props[fa]||this.props[ha]||this.register_once({[Qr]:Sf(this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties,this.Ne.disable_capture_url_hashes)},void 0)}get_initial_props(){var e={};ie([ha,fa],(r=>{var s=this.props[r];s&&ie(s,(function(o,a){e["$initial_"+Go(a)]=o}))}));var n=this.props[Qr];if(n){var i=(function(r,s){s===void 0&&(s=!1);var o=xf(r,s),a={};return ie(o,(function(l,u){a["$initial_"+Go(u)]=l})),a})(n,this.Ne.disable_capture_url_hashes);fe(e,i)}return e}safe_merge(e){return ie(this.props,(function(n,i){i in e||(e[i]=n)})),e}update_config(e,n,i){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!i),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var r=e.persistence!==n.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((f,h)=>f===d[h]))})(e.cookie_persisted_properties||[],n.cookie_persisted_properties||[]),s=r?this.bi(e):this.ii,o=this.wi(e);if(r||o!==this.pi){var a=this.props;this.clear(),this.ii=s,this.pi=o,this.props=a,this.save()}}set_disabled(e){this.xi=e,this.xi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ni&&(this.Ni=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this.qi&&(this.qi=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,n){var i=this.props[Ri]||{};i[e]=n,this.Pi(Ri,i),this.save()}remove_event_timer(e){var n=this.props[Ri]||{},i=n[e];return C(i)||(delete n[e],this.Pi(Ri,n),this.save()),i}get_property(e){return this.props[e]}set_property(e,n){this.Pi(e,n),this.save()}Pi(e,n){var i;this.props[e]=n,(i=yn(e))!=null&&i.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var n,i=(n=yn(e))==null?void 0:n.storageGroup;i&&(this.Mi(i).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function br(t){var e=!0;return{dispose(){if(e){e=!1;var n=t();n&&De(n.then)&&n.then(void 0,(()=>{}))}}}}var je={GZipJS:"gzip-js",Base64:"base64"},wi={Activation:"events",Cancellation:"cancelEvents"},Io={Popover:"popover",API:"api",Widget:"widget"},qt={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},ko={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},_a={Popover:"popover",Inline:"inline"},nm={SHOWN:"product tour shown"},zc={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},Vc=pe("[RateLimiter]");class im{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=n=>{var i=n.text;if(i&&i.length)try{(JSON.parse(i).quota_limited||[]).forEach((r=>{Vc.info((r||"events")+" is quota limited."),this.serverLimits[r]=new Date().getTime()+6e4}))}catch(r){return void Vc.warn('could not rate limit - continuing. Error: "'+r?.message+'"',{text:i})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var n,i,r;e===void 0&&(e=!1);var s=this.captureEventsBurstLimit,o=this.captureEventsPerSecond,a=new Date().getTime(),l=(n=(i=this.instance.persistence)==null?void 0:i.get_property(da))!==null&&n!==void 0?n:{tokens:s,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>s&&(l.tokens=s);var u=1>l.tokens;if(u||e||(l.tokens=Math.max(0,l.tokens-1)),u&&!e){var c=(ke(l.dropped)?l.dropped:0)+1;l.dropped=c,!this.lastEventRateLimited&&this.Hi(c)&&(l.dropped=0)}return this.lastEventRateLimited=u,(r=this.instance.persistence)==null||r.set_property(da,l),{isRateLimited:u,remainingTokens:l.tokens}}Ui(e){var n=this.instance.config.property_denylist;return!U(n)||!n.includes(e)}zi(){var e;if(this.Ui("$current_url")&&this.Ui("$pathname")&&me!=null&&me.pathname)return""+((e=me.origin)!==null&&e!==void 0?e:"")+me.pathname}Hi(e){var n,i,r=this.captureEventsBurstLimit,s=this.captureEventsPerSecond,o=this.zi(),a=this.Ui("$session_id")?(n=(i=this.instance).get_session_id)==null?void 0:n.call(i):void 0,l=[e+" event(s) dropped since the last warning",o?"triggered on "+o:void 0,a?"session "+a:void 0].filter(Boolean).join(", ");return!!this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited: "+l+". Config is set to "+s+" events per second and "+r+" events burst limit."},{skip_client_rate_limiting:!0})}isServerRateLimited(e){var n=this.serverLimits[e||"events"]||!1;return n!==!1&&new Date().getTime()e(this.remoteConfig))):e()}Vi(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:e})}load(){try{if(this.remoteConfig)return an.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void an.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return an.info("No config found after loading remote JS config. Falling back to JSON."),void this.Vi((n=>{this.Zi(n.json,n),this.Gi()}));this.Zi(e),this.Gi()}))}catch(e){an.error("Error loading remote config",e),this.Zi()}}stop(){this.Ki&&(clearInterval(this.Ki),this.Ki=void 0)}refresh(){!this._instance.Qi()&&F&&F.visibilityState!=="hidden"&&this._instance.reloadFeatureFlags()}Gi(){var e;if(!this.Ki){var n=(e=this._instance.config.remote_config_refresh_interval_ms)!==null&&e!==void 0?e:3e5;n!==0&&(this.Ki=setInterval((()=>{this.refresh()}),n))}}Zi(e,n){!e&&n&&(n.statusCode===0?n.error||an.warn("Failed to fetch remote config from PostHog."):an.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(r){an.error("Error applying remote config",r)}if(e?.hasFeatureFlags!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var i;(i=this._instance.featureFlags)==null||i.ensureFlagsLoaded()}catch(r){an.error("Error loading feature flags",r)}}}var lt=Uint8Array,Ge=Uint16Array,si=Uint32Array,fl=new lt([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]),hl=new lt([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]),Gc=new lt([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Cf=function(t,e){for(var n=new Ge(31),i=0;31>i;++i)n[i]=e+=1<i;++i)for(var s=n[i];n[i+1]>s;++s)r[s]=s-n[i]<<5|i;return[n,r]},Af=Cf(fl,2),ya=Af[1];Af[0][28]=258,ya[258]=28;for(var Kc=Cf(hl,0)[1],Pf=new Ge(32768),_e=0;32768>_e;++_e){var Wn=(43690&_e)>>>1|(21845&_e)<<1;Pf[_e]=((65280&(Wn=(61680&(Wn=(52428&Wn)>>>2|(13107&Wn)<<2))>>>4|(3855&Wn)<<4))>>>8|(255&Wn)<<8)>>>1}var Hi=function(t,e,n){for(var i=t.length,r=0,s=new Ge(e);i>r;++r)++s[t[r]-1];var o,a=new Ge(e);for(r=0;e>r;++r)a[r]=a[r-1]+s[r-1]<<1;for(o=new Ge(i),r=0;i>r;++r)o[r]=Pf[a[t[r]-1]++]>>>15-t[r];return o},$n=new lt(288);for(_e=0;144>_e;++_e)$n[_e]=8;for(_e=144;256>_e;++_e)$n[_e]=9;for(_e=256;280>_e;++_e)$n[_e]=7;for(_e=280;288>_e;++_e)$n[_e]=8;var ls=new lt(32);for(_e=0;32>_e;++_e)ls[_e]=5;var rm=Hi($n,9),sm=Hi(ls,5),Ff=function(t){return(t/8>>0)+(7&t&&1)},Rf=function(t,e,n){(n==null||n>t.length)&&(n=t.length);var i=new(t instanceof Ge?Ge:t instanceof si?si:lt)(n-e);return i.set(t.subarray(e,n)),i},Nt=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8},bi=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8,t[i+2]|=n>>>16},Co=function(t,e){for(var n=[],i=0;t.length>i;++i)t[i]&&n.push({s:i,f:t[i]});var r=n.length,s=n.slice();if(!r)return[new lt(0),0];if(r==1){var o=new lt(n[0].s+1);return o[n[0].s]=1,[o,1]}n.sort((function(x,I){return x.f-I.f})),n.push({s:-1,f:25001});var a=n[0],l=n[1],u=0,c=1,d=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=r-1;)a=n[n[d].f>n[u].f?u++:d++],l=n[u!=c&&n[d].f>n[u].f?u++:d++],n[c++]={s:-1,f:a.f+l.f,l:a,r:l};var f=s[0].s;for(i=1;r>i;++i)s[i].s>f&&(f=s[i].s);var h=new Ge(f+1),p=wa(n[c-1],h,0);if(p>e){i=0;var g=0,m=p-e,v=1<i;++i){var S=s[i].s;if(e>=h[S])break;g+=v-(1<>>=m;g>0;){var b=s[i].s;e>h[b]?g-=1<=0&&g;--i){var _=s[i].s;h[_]==e&&(--h[_],++g)}p=e}return[new lt(h),p]},wa=function(t,e,n){return t.s==-1?Math.max(wa(t.l,e,n+1),wa(t.r,e,n+1)):e[t.s]=n},Yc=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new Ge(++e),i=0,r=t[0],s=1,o=function(l){n[i++]=l},a=1;e>=a;++a)if(t[a]==r&&a!=e)++s;else{if(!r&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(r),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(r);s=1,r=t[a]}return[n.subarray(0,i),e]},Ei=function(t,e){for(var n=0,i=0;e.length>i;++i)n+=t[i]*e[i];return n},ba=function(t,e,n){var i=n.length,r=Ff(e+2);t[r]=255&i,t[r+1]=i>>>8,t[r+2]=255^t[r],t[r+3]=255^t[r+1];for(var s=0;i>s;++s)t[r+s+4]=n[s];return 8*(r+4+i)},Jc=function(t,e,n,i,r,s,o,a,l,u,c){Nt(e,c++,n),++r[256];for(var d=Co(r,15),f=d[0],h=d[1],p=Co(s,15),g=p[0],m=p[1],v=Yc(f),S=v[0],b=v[1],_=Yc(g),x=_[0],I=_[1],T=new Ge(19),E=0;S.length>E;++E)T[31&S[E]]++;for(E=0;x.length>E;++E)T[31&x[E]]++;for(var P=Co(T,7),$=P[0],O=P[1],L=19;L>4&&!$[Gc[L-1]];--L);var N,K,V,M,R=u+5<<3,Z=Ei(r,$n)+Ei(s,ls)+o,Ce=Ei(r,f)+Ei(s,g)+o+14+3*L+Ei(T,$)+(2*T[16]+3*T[17]+7*T[18]);if(Z>=R&&Ce>=R)return ba(e,c,t.subarray(l,l+u));if(Nt(e,c,1+(Z>Ce)),c+=2,Z>Ce){N=Hi(f,h),K=f,V=Hi(g,m),M=g;var oe=Hi($,O);for(Nt(e,c,b-257),Nt(e,c+5,I-1),Nt(e,c+10,L-4),c+=14,E=0;L>E;++E)Nt(e,c+3*E,$[Gc[E]]);c+=3*L;for(var ye=[S,x],$e=0;2>$e;++$e){var ae=ye[$e];for(E=0;ae.length>E;++E)Nt(e,c,oe[Ie=31&ae[E]]),c+=$[Ie],Ie>15&&(Nt(e,c,ae[E]>>>5&127),c+=ae[E]>>>12)}}else N=rm,K=$n,V=sm,M=ls;for(E=0;a>E;++E)if(i[E]>255){var Ie;bi(e,c,N[257+(Ie=i[E]>>>18&31)]),c+=K[Ie+257],Ie>7&&(Nt(e,c,i[E]>>>23&31),c+=fl[Ie]);var Se=31&i[E];bi(e,c,V[Se]),c+=M[Se],Se>3&&(bi(e,c,i[E]>>>5&8191),c+=hl[Se])}else bi(e,c,N[i[E]]),c+=K[i[E]];return bi(e,c,N[256]),c+K[256]},om=new si([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),am=(function(){for(var t=new si(256),e=0;256>e;++e){for(var n=e,i=9;--i;)n=(1&n&&3988292384)^n>>>1;t[e]=n}return t})(),Ao=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8};function lm(t,e){e===void 0&&(e={});var n=(function(){var d=4294967295;return{p(f){for(var h=d,p=0;f.length>p;++p)h=am[255&h^f[p]]^h>>>8;d=h},d(){return 4294967295^d}}})(),i=t.length;n.p(t);var r,s,o,a,l,u=(a=10+((r=e).filename&&r.filename.length+1||0),l=8,(function(d,f,h,p,g,m){var v=d.length,S=new lt(p+v+5*(1+Math.floor(v/7e3))+g),b=S.subarray(p,S.length-g),_=0;if(!f||8>v)for(var x=0;v>=x;x+=65535){var I=x+65535;v>I?_=ba(b,_,d.subarray(x,I)):(b[x]=!0,_=ba(b,_,d.subarray(x,v)))}else{for(var T=om[f-1],E=T>>>13,P=8191&T,$=(1<x;++x){var Ie=V(x),Se=32767&x,Be=L[Ie];if(O[Se]=Be,L[Ie]=Se,x>=$e){var yt=v-x;if((Ce>7e3||ye>24576)&&yt>423){_=Jc(d,b,0,M,R,Z,oe,ye,ae,x-ae,_),ye=Ce=oe=0,ae=x;for(var ge=0;286>ge;++ge)R[ge]=0;for(ge=0;30>ge;++ge)Z[ge]=0}var Ye=2,wt=0,mn=P,Re=Se-Be&32767;if(yt>2&&Ie==V(x-Re))for(var Pe=Math.min(E,yt)-1,Tt=Math.min(32767,x),Bn=Math.min(258,yt);Tt>=Re&&--mn&&Se!=Be;){if(d[x+Ye]==d[x+Ye-Re]){for(var qe=0;Bn>qe&&d[x+qe]==d[x+qe-Re];++qe);if(qe>Ye){if(Ye=qe,wt=Re,qe>Pe)break;var Dn=Math.min(Re,qe-2),$t=0;for(ge=0;Dn>ge;++ge){var Mt=x-Re+ge+32768&32767,ct=Mt-O[Mt]+32768&32767;ct>$t&&($t=ct,Be=Mt)}}}Re+=(Se=Be)-(Be=O[Se])+32768&32767}if(wt){M[ye++]=268435456|ya[Ye]<<18|Kc[wt];var sn=31&ya[Ye],gi=31&Kc[wt];oe+=fl[sn]+hl[gi],++R[257+sn],++Z[gi],$e=x+Ye,++Ce}else M[ye++]=d[x],++R[d[x]]}}_=Jc(d,b,!0,M,R,Z,oe,ye,ae,x-ae,_)}return Rf(S,0,p+Ff(_)+g)})(s=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):12+o.mem,a,l)),c=u.length;return(function(d,f){var h=f.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>f.level?4:f.level==9?2:0,d[9]=3,f.mtime!=0&&Ao(d,4,Math.floor(new Date(f.mtime||Date.now())/1e3)),h){d[3]=8;for(var p=0;h.length>=p;++p)d[p+10]=h.charCodeAt(p)}})(u,e),Ao(u,c-8,n.d()),Ao(u,c-4,i),u}var cm=!!qo||!!Za,Tf="text/plain",Mr=!1,$f=(t,e)=>{var n=t.split("#"),i=n[1],r=n[0].split("?"),s=r[0],o=r[1];if(!o)return t;var a=o.split("&").filter((l=>l.split("=")[0]!==e)).join("&");return s+(a?"?"+a:"")+(i?"#"+i:"")},ks=function(t,e,n){var i;n===void 0&&(n=!0);var r=t.split("?"),s=r[0],o=r[1],a=k({},e),l=(i=o?.split("&").map((c=>{var d,f=c.split("="),h=f[0],p=n&&(d=a[h])!==null&&d!==void 0?d:f[1];return delete a[h],h+"="+p})))!==null&&i!==void 0?i:[],u=(function(c,d){var f,h;d===void 0&&(d="&");var p=[];return ie(c,(function(g,m){C(g)||C(m)||m==="undefined"||(f=encodeURIComponent((v=>v instanceof File)(g)?g.name:g.toString()),h=encodeURIComponent(m),p[p.length]=h+"="+f)})),p.join(d)})(a);return u&&l.push(u),l.length>0?s+"?"+l.join("&"):s},Po=t=>{if(t.Ji)return t.Ji;var e=t.data,n=t.compression;if(e){if(n===je.GZipJS){var i=lm((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new lt(a.length+(a.length>>>1)),d=0,f=function(m){c[d++]=m},h=0;u>h;++h){if(d+5>c.length){var p=new lt(d+8+(u-h<<1));p.set(c),c=p}var g=a.charCodeAt(h);128>g?f(g):2048>g?(f(192|g>>>6),f(128|63&g)):g>55295&&57344>g?(f(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++h))>>>18),f(128|g>>>12&63),f(128|g>>>6&63),f(128|63&g)):(f(224|g>>>12),f(128|g>>>6&63),f(128|63&g))}return Rf(c,0,d)})(Yn(e)),{mtime:0});return{contentType:Tf,body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),estimatedSize:i.byteLength}}if(n===je.Base64){var r=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(Yn(e)),s=(a=>"data="+encodeURIComponent(typeof a=="string"?a:Yn(a)))(r);return{contentType:"application/x-www-form-urlencoded",body:s,estimatedSize:new Blob([s]).size}}var o=Yn(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},Mf=t=>{var e,n,i=()=>t.transport==="sendBeacon"?{url:ks(t.url,{compression:je.Base64}),encodedBody:Po(k({},t,{compression:je.Base64,Ji:void 0}))}:{url:$f(t.url,"compression"),encodedBody:Po(k({},t,{compression:void 0,Ji:void 0}))};try{e=Po(t)}catch(r){if(mc(t.compression,ii(t.url,"compression")))return A.error("Failed to gzip request body, sending uncompressed payload",r),i();throw r}return e&&mc(t.compression,ii(t.url,"compression"))&&!((n=e.body)instanceof ArrayBuffer?zo(new Uint8Array(n)):ArrayBuffer.isView(n)&&zo(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)))?(Mr=!0,i()):{url:t.url,encodedBody:e}},Lf=t=>{try{return Mf(t)}catch(e){return A.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},um=(function(){var t=se((function*(e){var n=Yn(e.data),i=yield(function(s,o,a){return Vo.apply(this,arguments)})(n,ne.DEBUG,{rethrow:!0});if(!i)return e;var r=yield i.arrayBuffer();return k({},e,{Ji:{contentType:Tf,body:r,estimatedSize:r.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),dm=/Failed to fetch|NetworkError|Load failed/i,Nf=t=>t?.name==="TypeError"&&dm.test(t?.message||""),Of=t=>{var e=Lf(t);if(e){var n=e.url,i=e.encodedBody,r=i??{},s=r.contentType,o=r.body,a=r.estimatedSize,l=new Headers;ie(t.headers,(function(p,g){l.append(g,p)})),s&&l.append("Content-Type",s);var u=null,c=!1;if(uc){var d=new uc;u={signal:d.signal,timeout:setTimeout((()=>{var p,g;c=!0,d.abort((p=t.timeout,(g=new Error("PostHog request timed out"+(p?" after "+p+"ms":""))).name="AbortError",g))}),t.timeout)}}var f=p=>{c&&p?.name==="AbortError"||Nf(p)?A.warn(p):A.error(p),t.callback==null||t.callback({statusCode:0,error:p})};try{var h;Za(n,k({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(h=u)==null?void 0:h.signal},t.fetchOptions)).then((p=>p.text().then((g=>{var m={statusCode:p.status,text:g};if(p.status===200)try{m.json=JSON.parse(g)}catch(v){A.error(v)}t.callback==null||t.callback(m)})))).catch(f).finally((()=>u?clearTimeout(u.timeout):null))}catch(p){u&&clearTimeout(u.timeout),f(p)}}},Ea=t=>{try{var e,n=Mf(t),i=n.url,r=n.encodedBody,s=r??{},o=s.body,a=s.estimatedSize;if(!o)return;var l=o instanceof Blob?o:new Blob([o],{type:s.contentType});if(Ue.sendBeacon(i,l))return;var u=U(t.data)?t.data:(e=t.data)==null?void 0:e.batch;if(U(u)&&u.length>1&&(a??0)>16384){var c=Math.ceil(u.length/2),d=f=>U(t.data)?f:k({},t.data,{batch:f});return Ea(k({},t,{data:d(u.slice(0,c))})),void Ea(k({},t,{data:d(u.slice(c))}))}A.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),Of(k({},t,{Yi:!0}))}catch(f){A.warn("Beacon send failed",f)}},Zc=(t,e,n,i)=>{var r=i==="query"?e==="POST"?"sent_at":"_":void 0;return ks(n===je.GZipJS?$f(t,"compression"):t,k({},r?{[r]:Date.now().toString()}:{},n===je.GZipJS?{}:{compression:n}))},Lr=[];Za&&Lr.push({transport:"fetch",method:Of}),qo&&Lr.push({transport:"XHR",method(t){var e=Lf(t);if(e){var n=new qo,i=e.encodedBody;n.open(t.method||"GET",e.url,!0);var r=i??{},s=r.contentType,o=r.body;ie(t.headers,(function(a,l){n.setRequestHeader(l,a)})),s&&n.setRequestHeader("Content-Type",s),t.timeout&&(n.timeout=t.timeout),n.onreadystatechange=()=>{if(n.readyState===4){var a={statusCode:n.status,text:n.responseText};if(n.status===200)try{a.json=JSON.parse(n.responseText)}catch{}t.callback==null||t.callback(a)}},n.send(o)}}}),Ue!=null&&Ue.sendBeacon&&Lr.push({transport:"sendBeacon",method:Ea});var Sa=3e3;class fm{constructor(e,n){this.Xi=!0,this.tr=[],this.er=Ct(n?.flush_interval_ms||Sa,250,5e3,A.createLogger("flush interval"),Sa),this.ir=e}enqueue(e){this.tr.push(e),this.rr||this.nr()}unload(){this.sr();var e=this.tr.length>0?this.ar():{},n=Object.values(e);[...n.filter((i=>i.url.indexOf("/e")===0)),...n.filter((i=>i.url.indexOf("/e")!==0))].map((i=>{this.lr(k({},i,{transport:"sendBeacon"}))}))}enable(){this.Xi=!1,this.nr()}nr(){var e=this;this.Xi||(this.rr=setTimeout((()=>{if(this.sr(),this.tr.length>0){var n=this.ar(),i=function(){var s=n[r],o=new Date().getTime();s.data&&U(s.data)&&ie(s.data,(a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp})),e.lr(s)};for(var r in n)i()}}),this.er))}lr(e){try{this.ir(e)}catch(n){A.error(n)}}sr(){clearTimeout(this.rr),this.rr=void 0}ar(){var e={};return ie(this.tr,(n=>{var i,r=n,s=(r?r.batchKey:null)||r.url;C(e[s])&&(e[s]=k({},r,{data:[]})),(i=e[s].data)==null||i.push(r.data)})),this.tr=[],e}}var hm=["retriesPerformedSoFar"];class pm{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!C(w)&&"onLine"in w.navigator&&(this.dr=w.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},ve(w,"online",this.vr),ve(w,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var n=e.retriesPerformedSoFar,i=ud(e,hm);Bt(n)&&(i.url=ks(i.url,{retry_count:n})),this._instance._send_request(k({},i,{callback:r=>{if(r.statusCode!==200&&(400>r.statusCode||r.statusCode>=500)){if((r.statusCode===0?3:10)>(n??0))return void this.At(k({retriesPerformedSoFar:n},i));r.statusCode===0&&A.warn("Request failed before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped retrying after "+(n??0)+" retries.")}i.callback==null||i.callback(r)}}))}At(e){var n=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=n+1;var i=(function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),c=Math.random()-.5;return Math.ceil(u+c*(u-l))})(n),r=Date.now()+i;this.tr.push({retryAt:r,requestOptions:e});var s="Enqueued failed request for retry in "+i;navigator.onLine||(s+=" (Browser is offline)"),A.warn(s),this.ur||(this.ur=!0,this.gr())}gr(){if(this.mr&&clearTimeout(this.mr),this.tr.length===0)return this.ur=!1,void(this.mr=void 0);this.mr=setTimeout((()=>{this.dr&&this.tr.length>0&&this.cr(),this.gr()}),this.hr)}cr(){var e=Date.now(),n=[],i=this.tr.filter((s=>e>s.retryAt||(n.push(s),!1)));if(this.tr=n,i.length>0)for(var r of i)this.retriableRequest(r.requestOptions)}unload(){for(var e of(this.mr&&(clearTimeout(this.mr),this.mr=void 0),this.ur=!1,C(w)||(this.vr&&(w.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(w.removeEventListener("offline",this.pr),this.pr=void 0)),this.tr)){var n=e.requestOptions;try{this._instance._send_request(k({},n,{transport:"sendBeacon"}))}catch(i){A.error(i)}}this.tr=[]}}class gm{constructor(e){this.yr=()=>{var n,i,r,s;this.br||(this.br={});var o=this.scrollElement(),a=this.scrollY(),l=o?Math.max(0,o.scrollHeight-o.clientHeight):0,u=a+(o?.clientHeight||0),c=o?.scrollHeight||0;this.br.lastScrollY=Math.ceil(a),this.br.maxScrollY=Math.max(a,(n=this.br.maxScrollY)!==null&&n!==void 0?n:0),this.br.maxScrollHeight=Math.max(l,(i=this.br.maxScrollHeight)!==null&&i!==void 0?i:0),this.br.lastContentY=u,this.br.maxContentY=Math.max(u,(r=this.br.maxContentY)!==null&&r!==void 0?r:0),this.br.maxContentHeight=Math.max(c,(s=this.br.maxContentHeight)!==null&&s!==void 0?s:0)},this._instance=e}get _r(){return this._instance.config.scroll_root_selector}getContext(){return this.br}resetContext(){var e=this.br;return setTimeout(this.yr,0),e}startMeasuringScrollPosition(){ve(w,"scroll",this.yr,{capture:!0}),ve(w,"scrollend",this.yr,{capture:!0}),ve(w,"resize",this.yr)}scrollElement(){if(!this._r)return w?.document.documentElement;var e=U(this._r)?this._r:[this._r];for(var n of e){var i=w?.document.querySelector(n);if(i)return i}}wr(e){var n=e==="y"?"scrollTop":"scrollLeft";if(this._r){var i=this.scrollElement();return i&&i[n]||0}return w?e==="y"?w.scrollY||w.pageYOffset||w.document.documentElement.scrollTop||0:w.scrollX||w.pageXOffset||w.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var mm=t=>Sf(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class Xc{constructor(e,n,i,r){this.kr=s=>{var o=this.Sr();if(!o||o.sessionId!==s){var a={sessionId:s,props:this.Cr(this._instance)};this.Mr.register({[ua]:a})}},this._instance=e,this.Tr=n,this.Mr=i,this.Cr=r||mm,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[ua]}getSetOnceProps(){var e,n=(e=this.Sr())==null?void 0:e.props;return n?"r"in n?xf(n,this._instance.config.disable_capture_url_hashes):{$referring_domain:n.referringDomain,$pathname:n.initialPathName,utm_source:n.utm_source,utm_campaign:n.utm_campaign,utm_medium:n.utm_medium,utm_content:n.utm_content,utm_term:n.utm_term}:{}}getSessionProps(){var e={};return ie(ll(this.getSetOnceProps()),((n,i)=>{i==="$current_url"&&(i="url"),e["$session_entry_"+Go(i)]=n})),e}}class pl{on(e,n){return this.Er[e]||(this.Er[e]=[]),this.Er[e].push(n),()=>{this.Er[e]=this.Er[e].filter((i=>i!==n))}}emit(e,n){for(var i of this.Er[e]||[])i(n);for(var r of this.Er["*"]||[])r(e,n)}constructor(){this.Er={}}}var Si=pe("[SessionId]");class Qc{on(e,n){return this.Ir.on(e,n)}constructor(e,n,i){var r;if(this.Pr=null,this.Rr=[],this.Ar=void 0,this.Fr=!1,this.Ir=new pl,this.Lr=(u,c)=>!(!Bt(u)||!Bt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===Ht)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Ne=e.config,this.Mr=e.persistence,this.Or=void 0,this.Dr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.$r=n||Ut,this.Nr=i||Ut;var s=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*Ct(this.Ne.session_idle_timeout_seconds||1800,60,36e3,Si.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.qr(),this.jr="ph_"+s+"_window_id",this.Br="ph_"+s+"_primary_window_exists",this.Hr()){var o=be.H(this.jr),a=be.H(this.Br);o&&!a?this.Or=o:be.q(this.jr),be.F(this.Br,!0)}if((r=this.Ne.bootstrap)!=null&&r.sessionID)try{var l=(u=>{var c=this.Ne.bootstrap.sessionID.replace(/-/g,"");if(c.length!==32)throw new Error("Not a valid UUID");if(c[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(c.substring(0,12),16)})();this.Ur(this.Ne.bootstrap.sessionID,new Date().getTime(),l)}catch(u){Si.error("Invalid sessionID in bootstrap",u)}this.zr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return C(this.Rr)&&(this.Rr=[]),this.Rr.push(e),this.Dr&&e(this.Dr,this.Or),()=>{this.Rr=this.Rr.filter((n=>n!==e))}}Hr(){return this.Ne.persistence!=="memory"&&!this.Mr.xi&&be.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&be.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?be.H(this.jr):null}Zr(e){var n=this.Pr;return!Ke(n)&&!Ke(e)&&5e3>Math.abs(e-n)}Ur(e,n,i){var r=n!==this._sessionActivityTimestamp,s=!(e!==this.Dr||i!==this._sessionStartTimestamp);this._sessionStartTimestamp=i,this._sessionActivityTimestamp=n,this.Dr=e,s&&!r||s&&this.Zr(n)||(this.Pr=n,this.Mr.register({[Kn]:[n,e,i]}))}Gr(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return Bt(n)&&n>0}Qr(){this.Gr()?this.Mr.refreshKey(Kn):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!Ke(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this.Pr){this.Qr();var n=this.Jr();n[1]===this.Dr&&n[2]===this._sessionStartTimestamp&&(this.Pr=this._sessionActivityTimestamp,this.Mr.register({[Kn]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],n=Bt(e)?e:0,i=Bt(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(n,i)}Xr(e){return this.Qr(),this.Lr(e,this.Yr())}Jr(){var e=this.Mr.props[Kn];return U(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Pr=null,clearTimeout(this.tn),this.tn=void 0,this.Ur(null,null,null)}destroy(){this.Fr=!0,this.Kr(),clearTimeout(this.tn),this.tn=void 0,this.Ar&&w&&(w.removeEventListener(ns,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&be.q(this.Br)},ve(w,ns,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=null),this.Ne.cookieless_mode===Ht)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var i=n||new Date().getTime(),r=this.Jr(),s=r[1],o=r[2],a=this.Yr(),l=this.Vr(),u=Bt(o)&&Math.abs(i-o)>864e5,c=!1,d=!1,f=!s,h=s,p=!f&&!e&&this.Lr(i,a);if(p){(p=this.Xr(i))||Si.info("cross-tab refresh kept the session alive",{sessionId:s});var g=this.Jr();s=g[1],o=g[2]}f||p||u?(s=this.$r(),l=this.Nr(),Si.info("new session ID generated",{sessionId:s,windowId:l,changeReason:{noSessionId:f,activityTimeout:p,sessionPastMaximumLength:u}}),o=i,c=!0):(l||(l=this.Nr(),c=!0),(d=s!==h)&&(Si.info("adopted cross-tab session id",{sessionId:s,windowId:l}),c=!0));var m=Bt(a)&&e&&!u?a:i,v=Bt(o)?o:new Date().getTime();this.Wr(l),this.Ur(s,m,v),e||this.qr();var S={noSessionId:f,activityTimeout:p,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((b=>b(s,l,S))),{sessionId:s,windowId:l,sessionStartTimestamp:v,changeReason:c?S: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 Bf=function(t,e){if(!t)return!1;var n=t.userAgent;if(n&&_c(n,e))return!0;try{var i=t?.userAgentData;if(i!=null&&i.brands&&i.brands.some((r=>_c(r?.brand,e))))return!0}catch{}return!!t.webdriver};function Df(){return(Df=se((function*(){var t=Ue?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),n=e?.model;return X(n)&&n.length>0?n:void 0}catch(i){return void A.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",i)}}))).apply(this,arguments)}var cs=function(t,e){if(!(function(n){try{new RegExp(n)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function Fo(t,e,n){return Yn({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}var jf={exact:(t,e)=>e.some((n=>t.some((i=>n===i)))),is_not:(t,e)=>e.every((n=>t.every((i=>n!==i)))),regex:(t,e)=>e.some((n=>t.some((i=>cs(n,i))))),not_regex:(t,e)=>e.every((n=>t.every((i=>!cs(n,i))))),icontains:(t,e)=>e.map(Er).some((n=>t.map(Er).some((i=>n.includes(i))))),not_icontains:(t,e)=>e.map(Er).every((n=>t.map(Er).every((i=>!n.includes(i))))),gt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>i>parseFloat(r)))})),lt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>it.toLowerCase();function Uf(t,e){return!t||Object.entries(t).every((n=>{var i=n[1],r=e?.[n[0]];if(C(r)||Ke(r))return!1;var s=[String(r)],o=jf[i.operator];return!!o&&o(i.values,s)}))}var xa="custom",eu="i.posthog.com",vm=/^\/static\//;class _m{constructor(e){this.en={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,n=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return n||(n=this.apiHost.replace("."+eu,".posthog.com")),n==="https://app.posthog.com"?"https://us.posthog.com":n}get region(){return this.en[this.apiHost]||(this.en[this.apiHost]=/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"us":/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"eu":xa),this.en[this.apiHost]}rn(e){if(vm.test(e)){var n=this.instance.config.asset_host;if(typeof n=="string")return n.trim().replace(/\/$/,"")||void 0}}endpointFor(e,n){if(n===void 0&&(n=""),n&&(n=n[0]==="/"?n:"/"+n),e==="ui")return this.uiHost+n;if(e==="flags")return this.flagsApiHost+n;if(e==="assets"){var i=this.rn(n);if(i)return""+i+n}if(this.region===xa)return this.apiHost+n;var r=eu+n;switch(e){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}}function Hf(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var Q=pe("[Surveys]"),Wf="seenSurvey_",qf=t=>{try{var e=(n=>((i,r)=>""+Wf+(function(s){return s.current_iteration&&s.current_iteration>0?s.id+"_"+s.current_iteration:s.id})(r))(0,n))(t);if(localStorage.getItem(e))return;localStorage.setItem(e,"true")}catch(n){Q.error("Failed to persist survey seen state",n)}},ym=[Io.Popover,Io.Widget,Io.API],wm={ignoreConditions:!1,ignoreDelay:!1,displayType:_a.Popover},bm=pe("[PostHog ExternalIntegrations]"),Em={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class Sm{constructor(e){this._instance=e}ai(e,n){var i;(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,e,(r=>{if(r)return bm.error("failed to load script",r);n()}))}startIfEnabledOrStop(){var e=this,n=function(){var s,o,a,l=i[0],u=i[1];!u||(s=B.__PosthogExtensions__)!=null&&(s=s.integrations)!=null&&s[l]||e.ai(Em[l],(()=>{var c;(c=B.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=B.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=B.__PosthogExtensions__)==null||(a=a.integrations)==null||(a=a[l])==null||a.stop())};for(var i of Object.entries((r=this._instance.config.integrations)!==null&&r!==void 0?r:{})){var r;n()}}}class xm{constructor(e,n){this.rt=e,this.nn=n,this.sn=new Map,this.an=!1}add(e){var n=this;return se((function*(){if(n.an)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(n.sn.has(e.name))throw new Error('Browser extension "'+e.name+'" is already registered');n.sn.set(e.name,e);try{var i=e.setup(n.nn);i&&(yield i)}catch(s){var r=n.sn.get(e.name)===e;r&&n.sn.delete(e.name),n.rt.error('Failed to set up browser extension "'+e.name+'"',s),r&&n.ln(e)}}))()}dispose(){if(!this.an){this.an=!0;var e=Array.from(this.sn.values()).reverse();for(var n of(this.sn.clear(),e))this.ln(n)}}ln(e){try{var n=e.dispose==null?void 0:e.dispose();n&&De(n.then)&&n.then(void 0,(i=>{this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}))}catch(i){this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}}}class Im{constructor(e){this._instance=e}initialize(){}get(e){var n=this._instance.persistence;if(typeof e=="string")return n?.get_property(e);var i={};for(var r of e){var s=n?.get_property(r);C(s)||(i[r]=s)}return i}set(e,n){var i;(i=this._instance.persistence)==null||i.register(typeof e=="string"?{[e]:n}:e)}remove(e){var n;(n=this._instance.persistence)==null||n.unregister(e)}}var tu="extensionsRemoteConfig";class km{constructor(e){this.an=!1,this.instance=e,this.rt=A,this.un=e.hn,this.kv=new Im(e),this.onEvent=n=>br(this.instance.on("eventCaptured",(i=>{try{n({event:i.event,properties:i.properties})}catch(r){this.rt.error("Browser extension event listener failed",r)}}))),this.onRemoteConfig=n=>{if(this.an)return br((()=>{}));var i=s=>{try{n(s)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},r=this.instance.dn.on(tu,i);return this.un&&i(this.un),br(r)},this.vn=new xm(A.createLogger("[BrowserExtensions]"),this)}get logger(){return this.rt}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return(e=this.instance.get_property(Yi))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(Yi);return typeof e=="string"?e:void 0}get library(){return{name:ne.LIB_NAME,version:ne.LIB_VERSION}}get initialPersonProperties(){var e,n;return(e=(n=this.instance.persistence)==null?void 0:n.get_initial_props())!==null&&e!==void 0?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,n,i,r,s=(e=this.instance.sessionManager)==null?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:(n=s?.sessionId)!==null&&n!==void 0?n:"",windowId:(i=s?.windowId)!==null&&i!==void 0?i:"",sessionStartTimestamp:(r=s?.sessionStartTimestamp)!==null&&r!==void 0?r:0}}catch{return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get projectToken(){return this.instance.config.token}add(e){return this.vn.add(e)}capture(e,n,i){var r=this;return se((function*(){i?r.instance.capture(e,n,{timestamp:i.timestamp,uuid:i.uuid,$set:i.set,$set_once:i.setOnce}):r.instance.capture(e,n)}))()}registerDynamicEventProperties(e){return br(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(tu,e))}sendRequest(e,n){var i=this;return se((function*(){var r;n===void 0&&(n={});var s=i.instance.requestRouter.endpointFor((r=n.target)!==null&&r!==void 0?r:"api",e),o={method:n.method,url:n.query?ks(s,n.query):s,data:n.body,headers:n.headers,timeout:n.timeoutMs,fireCallbackOnDrop:!0,transport:n.transport,compression:n.compression,timestampMode:n.sentAt};return n.transport==="sendBeacon"?(i.instance._send_request(o),{statusCode:202}):new Promise((a=>{o.callback=a,i.instance._send_request(o)}))}))()}dispose(){this.an||(this.an=!0,this.vn.dispose())}}var Wi={},Ro=0,us=()=>{},nu='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',xi="Surveys module not available",iu="sanitize_properties is deprecated. Use before_send instead",zf="Invalid value for property_denylist config: ",Cm=["token","distinct_id",Zd],Gn="posthog",Vf=!cm&&Ve?.indexOf("MSIE")===-1&&Ve?.indexOf("Mozilla")===-1,To=t=>{var e;return k({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:Ag(F?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:us,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:t??"unset",__preview_deferred_init_extensions:!1,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:me&&X(me?.search)&&me.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disableDeviceModel:!1,disable_external_dependency_loading:!1,strict_script_versioning:!1,enable_recording_console_log:void 0,secure_cookie:(w==null||(e=w.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(n){A.error("Bad HTTP status: "+n.statusCode+" "+n.text)},get_device_id:n=>n,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:pa,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:Sa},error_tracking:{},_onCapture:us},(n=>({rageclick:n&&n>="2026-05-30"?{content_ignorelist:jg,ignore_text_selection:!0}:!n||"2025-11-30">n||{content_ignorelist:!0},capture_pageview:!n||"2025-05-24">n||"history_change",session_recording:n&&n>="2026-06-25"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6},streamNetworkBody:!0}:n&&n>="2026-05-30"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6}}:n&&n>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:n&&n>="2026-01-30"?"head":"body",internal_or_test_user_hostname:n&&n>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:n&&n>="2026-05-30"?250:0,split_storage:!(!n||"2026-05-30">n),detect_google_search_app:!(!n||"2026-05-30">n),disable_capture_url_hashes:!(!n||"2026-06-25">n)}))(t))},Am=[["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"]],ru=t=>{var e={};for(var n of Am){var i=n[0],r=n[1];C(t[i])||(e[r]=t[i])}var s=fe({},e,t),o=t.__preview_external_dependency_versioned_paths;return C(o)||(C(t.strict_script_versioning)&&(s.strict_script_versioning=!!o),X(o)&&C(t.asset_host)&&(s.asset_host=o)),U(t.property_blacklist)&&(C(t.property_denylist)?s.property_denylist=t.property_blacklist:U(t.property_denylist)?s.property_denylist=[...t.property_blacklist,...t.property_denylist]:A.error(zf+t.property_denylist)),s};class Pm{constructor(){this.__forceAllowLocalhost=!1}get fn(){return this.__forceAllowLocalhost}set fn(e){A.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class Je{pn(e,n){if(e){var i=this.sn.indexOf(e);i!==-1&&this.sn.splice(i,1)}return this.sn.push(n),n.initialize==null||n.initialize(),n}gn(){return this.config.cookieless_mode===Ht||this.config.cookieless_mode===kn&&this.consent.isRejected()}get decideEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){var e;this.webPerformance=new Pm,this.mn=!1,this.version=ne.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new pl,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=To(),this.SentryIntegration=Kg,this.sentryIntegration=i=>(function(r,s){var o=mf(r,s);return{name:gf,processEvent:a=>o(a)}})(this,i),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.wn=!1,this.kn=null,this.xn=null,this.Sn=null,this.scrollManager=new gm(this),this.pageViewManager=new Wc(this),this.rateLimiter=new im(this),this.requestRouter=new _m(this),this.consent=new Lg(this),this.externalIntegrations=new Sm(this);var n=(e=Je.__defaultExtensionClasses)!==null&&e!==void 0?e:{};this.featureFlags=n.featureFlags&&new n.featureFlags(this),this.toolbar=n.toolbar&&new n.toolbar(this),this.surveys=n.surveys&&new n.surveys(this),this.conversations=n.conversations&&new n.conversations(this),this.logs=n.logs&&new n.logs(this),this.metrics=n.metrics&&new n.metrics(this),this.experiments=n.experiments&&new n.experiments(this),this.exceptions=n.exceptions&&new n.exceptions(this),this.people={set:(i,r,s)=>{var o=X(i)?{[i]:r}:i;this.setPersonProperties(o),s?.({})},set_once:(i,r,s)=>{var o=X(i)?{[i]:r}:i;this.setPersonProperties(void 0,o),s?.({})}},this.on("eventCaptured",(i=>A.info('send "'+i?.event+'"',i)))}init(e,n,i){if(i&&i!==Gn){var r,s=(r=Wi[i])!==null&&r!==void 0?r:new Je;return s._init(e,n,i),Wi[i]=s,Wi[Gn][i]=s,s}return this._init(e,n,i)}_init(e,n,i){var r,s;n===void 0&&(n={});var o,a=X(e)?e.trim():"";if(!a)return A.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return a!==((o=this.config)==null?void 0:o.token)?console.warn("[PostHog.js]","You have already initialized PostHog with a different project token! Re-initializing is a no-op, so events will keep going to the project this instance was initialized with. To capture into a second project, load PostHog once, then initialize a named instance after the SDK has loaded, e.g. posthog.init('"+a+"', { ... }, 'project2')"):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=To(n.defaults),n.debug=this.Cn(n.debug),this.Mn=n,this.Tn=[],n.person_profiles?this.xn=n.person_profiles:n.process_person&&(this.xn=n.process_person);var l=To(n.defaults),u=ru(n),c=fe({},l,u,{name:i,token:a});he(l.rageclick)&&he(u.rageclick)&&(c.rageclick=fe({},l.rageclick,u.rageclick)),he(l.session_recording)&&he(u.session_recording)&&(c.session_recording=fe({},l.session_recording,u.session_recording)),this.set_config(c),this.config.on_xhr_error&&A.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=n.disable_compression?void 0:je.GZipJS;var d=this.En();if(this.persistence=new xo(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new xo(k({},this.config,{persistence:"sessionStorage"}),d,!1),this.bn="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&be.N()){var f=be.H(this.bn);U(f)&&f.forEach((I=>{X(I)&&this.yn.add(I)}))}else be.q(this.bn);var h=k({},this.persistence.props),p=k({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new fm((I=>this.Pn(I)),this.config.request_queue_config),this.Rn=new pm(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new Qc(this),this.sessionPropsManager=new Xc(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((I,T,E)=>{(E!=null&&E.activityTimeout||E!=null&&E.sessionPastMaximumLength||E!=null&&E.crossTabAdoption)&&this.An()}))),this.Fn(),this.config.__preview_deferred_init_extensions?(A.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Ln(g)}),0)):(A.info("Initializing extensions synchronously"),this.Ln(g)),ne.DEBUG=ne.DEBUG||this.config.debug,ne.DEBUG&&A.info("Starting in debug mode",{this:this,config:n,thisC:k({},this.config),p:h,s:p}),!this.config.identity_distinct_id||(r=n.bootstrap)!=null&&r.distinctID||(n.bootstrap=k({},n.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((s=n.bootstrap)==null?void 0:s.distinctID)!==void 0){var m=n.bootstrap.distinctID,v=this.get_distinct_id(),S=this.persistence.get_property(ot);if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&S===Un)this.identify(m);else if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&S===vn)A.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{var b=this.config.get_device_id(Ut()),_=n.bootstrap.isIdentifiedID?b:m;this.persistence.set_property(ot,n.bootstrap.isIdentifiedID?vn:Un),this.register({distinct_id:m,$device_id:_})}}if(g)this.register_once({distinct_id:mr,$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(ot,Un)}return ve(w,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),n.segment?(function(I,T){var E=I.config.segment;if(!E)return T();(function(P,$){var O=P.config.segment;if(!O)return $();var L=K=>{var V=()=>K.anonymousId()||Ut();P.config.get_device_id=V,K.id()&&(P.register({distinct_id:K.id(),$device_id:V()}),P.persistence.set_property(ot,vn)),$()},N=O.user();"then"in N&&De(N.then)?N.then(L):L(N)})(I,(()=>{E.register((P=>{typeof Promise<"u"&&Promise.resolve||Eo.warn("This browser does not have Promise support, and can not use the segment integration");var $=(O,L)=>{if(!L)return O;O.event.userId||O.event.anonymousId===P.get_distinct_id()||(Eo.info("No userId set, resetting PostHog"),P.reset()),O.event.userId&&O.event.userId!==P.get_distinct_id()&&(Eo.info("UserId set, identifying with PostHog"),P.identify(O.event.userId));var N=P.calculateEventProperties(L,O.event.properties);return O.event.properties=Object.assign({},N,O.event.properties),O};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:O=>$(O,O.event.event),page:O=>$(O,Vn),identify:O=>$(O,yo),screen:O=>$(O,"$screen")}})(I)).then((()=>{T()}))}))})(this,(()=>this.On())):this.On(),De(this.config._onCapture)&&this.config._onCapture!==us&&(A.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(I=>this.config._onCapture(I.event,I)))),this.config.ip&&A.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this.config.disableDeviceModel||(function(){return Df.apply(this,arguments)})().then((I=>{I&&this.register({[vo]:I})})).catch(us),this}Fn(){var e,n,i,r,s,o,a=(e=(n=this.config.__extensionClasses)==null?void 0:n.featureFlags)!==null&&e!==void 0?e:(i=Je.__defaultExtensionClasses)==null?void 0:i.featureFlags;a&&(this.featureFlags&&this.featureFlags instanceof a||((r=this.Dn)==null||r.call(this),this.Dn=void 0,this.featureFlags=new a(this)),De(this.featureFlags.onReloading)&&De(this.featureFlags.setup)?this.Dn||(this.Dn=this.featureFlags.onReloading((()=>{this.dn.emit("featureFlagsReloading",!0)})),this.$n().add(this.featureFlags)):(s=(o=this.featureFlags).initialize)==null||s.call(o))}Ln(e){var n,i,r,s,o,a,l,u=performance.now(),c=k({},Je.__defaultExtensionClasses,this.config.__extensionClasses),d=[];c.exceptions&&this.sn.push(this.exceptions=(n=this.exceptions)!==null&&n!==void 0?n:new c.exceptions(this)),c.historyAutocapture&&this.sn.push(this.historyAutocapture=new c.historyAutocapture(this)),c.tracingHeaders&&this.sn.push(this.tracingHeaders=new c.tracingHeaders(this)),c.siteApps&&this.sn.push(this.siteApps=new c.siteApps(this)),c.sessionRecording&&!e&&this.sn.push(this.sessionRecording=new c.sessionRecording(this)),this.config.disable_scroll_properties||d.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),c.autocapture&&this.sn.push(this.autocapture=new c.autocapture(this)),c.surveys&&this.sn.push(this.surveys=(i=this.surveys)!==null&&i!==void 0?i:new c.surveys(this)),c.logs&&this.sn.push(this.logs=(r=this.logs)!==null&&r!==void 0?r:new c.logs(this)),c.metrics&&this.sn.push(this.metrics=(s=this.metrics)!==null&&s!==void 0?s:new c.metrics(this)),c.conversations&&this.sn.push(this.conversations=(o=this.conversations)!==null&&o!==void 0?o:new c.conversations(this)),c.productTours&&this.sn.push(this.productTours=new c.productTours(this)),c.heatmaps&&this.sn.push(this.heatmaps=new c.heatmaps(this)),c.webVitalsAutocapture&&this.sn.push(this.webVitalsAutocapture=new c.webVitalsAutocapture(this)),c.exceptionObserver&&this.sn.push(this.exceptionObserver=new c.exceptionObserver(this)),c.deadClicksAutocapture&&this.sn.push(this.deadClicksAutocapture=new c.deadClicksAutocapture(this,Gg)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((f=>{f.initialize&&d.push((()=>{f.initialize==null||f.initialize()}))})),d.push((()=>{if(this.Nn){var f=this.Nn;this.Nn=void 0,this.sn.forEach((h=>h.onRemoteConfig==null?void 0:h.onRemoteConfig(f)))}})),this.qn(d,u)}qn(e,n){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,n)}),0);var i=e.shift();if(i)try{i()}catch(s){A.error("Error initializing extension:",s)}}var r=Math.round(performance.now()-n);this.register_for_session({[Xd]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[Qd]:r}),this.config.__preview_deferred_init_extensions&&A.info("PostHog extensions initialized ("+r+"ms)")}Zi(e){var n;if(!F||!F.body)return A.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.Zi(e)}),500);if(this.config.__preview_deferred_init_extensions&&(this.Nn=e),this.hn=e,this.compression=void 0,e.ok){var i,r=e.config;r.supportedCompression&&!this.config.disable_compression&&(this.compression=j(r.supportedCompression,je.GZipJS)?je.GZipJS:j(r.supportedCompression,je.Base64)?je.Base64:void 0),(i=r.analytics)!=null&&i.endpoint&&(this.analyticsDefaultEndpoint=r.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:pa}),(n=this.jn)==null||n.handleRemoteConfig(e),this.sn.forEach((s=>s.onRemoteConfig==null?void 0:s.onRemoteConfig(e)))}On(){try{this.config.loaded(this)}catch(i){A.critical("`loaded` function failed",i)}if(this.Bn(),this.config.internal_or_test_user_hostname&&me!=null&&me.hostname){var e=me.hostname,n=this.config.internal_or_test_user_hostname;(typeof n=="string"?e===n:n.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.gn())&&this.Hn()}),1),this.Un=new kf(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()&&vr(this.__request_queue,(e=>this.Pn(e))),this.__request_queue=[],this.Bn()}_handle_unload(){var e,n,i,r,s;(e=this.surveys)==null||e.handlePageUnload==null||e.handlePageUnload(),(n=this.metrics)==null||n.flush("sendBeacon"),this.config.request_batching?(this.zn()&&this.capture(_o),(i=this.logs)==null||i.flushLogs("sendBeacon"),(r=this.In)==null||r.unload(),(s=this.Rn)==null||s.unload()):this.zn()&&this.capture(_o,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?Vf?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)?e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:429})):(e.transport=e.transport||this.config.api_transport,e.headers=k({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,(C(this.config.disable_beacon)?this.config.__preview_disable_beacon:this.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(n=>{var i,r,s,o=k({},n);o.timeout=o.timeout||6e4;var a,l,u,c,d,f=(i=o.transport)!==null&&i!==void 0?i:"fetch";f==="sendBeacon"&&C(o.compression)&&o.data&&(o.compression=je.Base64),o.method==="POST"&&o.data&&(o.timestampMode==="capture-body"?o.data={api_key:(l=(d=(c=U(a=o.data)?a:[a])[0])==null||(u=d.properties)==null?void 0:u.token)!==null&&l!==void 0?l:d?.token,batch:c,sent_at:new Date().toISOString()}:o.timestampMode==="body"&&(o.data=(function(m,v){return v===void 0&&(v=new Date().toISOString()),U(m)?m.map((S=>k({},S,{sent_at:v}))):k({},m,{sent_at:v})})(o.data))),o.url=Zc(o.url,o.method,o.compression,o.timestampMode);var h=Lr.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),p=(r=(s=(function(m,v){for(var S=0;m.length>S;S++)if(m[S].transport===f)return m[S]})(h))==null?void 0:s.method)!==null&&r!==void 0?r:h[0].method;if(!p)throw new Error("No available transport method");var g=m=>{try{p(m)}catch(v){Nf(v)?A.warn(v):A.error(v),o.callback==null||o.callback({statusCode:0,error:v})}};f!=="sendBeacon"&&o.data&&o.compression===je.GZipJS&&Fp&&typeof Promise<"u"&&!Mr?um(o).then((m=>{g(m)})).catch((m=>{if(vc(m))return Mr=!0,void g(k({},o,{compression:void 0,url:Zc(n.url,n.method,void 0,n.timestampMode)}));(v=>{if(!v||typeof v!="object")return!1;var S="name"in v?String(v.name):"";return vc(v)||S===dd})(m)&&(Mr=!0),g(o)})):p(o)})(k({},e,{callback:n=>{var i,r;this.rateLimiter.checkForLimiting(n),400>n.statusCode||(i=(r=this.config).on_request_error)==null||i.call(r,n),e.callback==null||e.callback(n)}}))):e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:0}))}Pn(e){this.Rn?this.Rn.retriableRequest(e):this._send_request(e)}_execute_array(e){Ro++;try{var n,i=[],r=[],s=[];vr(e,(a=>{if(a)if(U(n=a[0]))s.push(a);else if(De(a))try{a.call(this)}catch(l){A.error("Error executing queued PostHog call",a,l)}else U(a)&&n==="alias"?i.push(a):U(a)&&n.indexOf("capture")!==-1&&De(this[n])?s.push(a):r.push(a)}));var o=function(a,l){vr(a,(function(u){try{if(U(u[0])){var c=l;ie(u,(function(d){c=c[d[0]].apply(c,d.slice(1))}))}else l[u[0]].apply(l,u.slice(1))}catch(d){A.error("Error executing queued PostHog call",u,d)}}))};o(i,this),o(r,this),o(s,this)}finally{Ro--}}push(e){if(Ro>0&&U(e)&&X(e[0])){var n=Je.prototype[e[0]];De(n)&&n.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,n,i){var r,s,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.In){if(this.is_capturing())if(!C(e)&&X(e)){var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var c=i!=null&&i.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(c==null||!c.isRateLimited){n!=null&&n.$current_url&&!X(n?.$current_url)&&(A.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),n==null||delete n.$current_url),e!=="$exception"||i!=null&&i.Wn||A.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,f=i?.timestamp||d,h=Ec(i?.uuid,Ut),p={uuid:h,event:e,properties:this.calculateEventProperties(e,n||{},f,h)};e===Vn&&this.config.__preview_capture_bot_pageviews&&u&&(p.event="$bot_pageview",p.properties.$browser_type="bot"),c&&(p.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&p.properties.$feature_flag_has_experiment===!1&&this.get_property(Zr)===!0;i?.$set&&!g&&(p.$set=i?.$set);var m=i?.$unset;m&&(p.$unset=m);var v,S,b,_=g?void 0:this.Vn(i?.$set_once,e!==Ac,e===yo);if(_&&(p.$set_once=_),i!=null&&i._noTruncate||(s=this.config.properties_string_max_length,o=p,a=L=>X(L)?L.slice(0,s):L,l=new Set,p=(function L(N,K){if(N!==Object(N))return a?a(N):N;if(!l.has(N)){var V;if(l.add(N),U(N))V=[],vr(N,(R=>{V.push(L(R))}));else{var M={};ie(N,((R,Z)=>{l.has(R)||(M[Z]=L(R))})),V=M}return V}})(o)),p.timestamp=f,C(i?.timestamp)||(p.properties.$event_time_override_provided=!0,p.properties.$event_time_override_system_time=d),g&&(p.properties=(function(L,N){N===void 0&&(N=[]);var K={},V=M=>{L[M]!==void 0&&(K[M]=L[M])};return Rp.forEach(V),N.forEach(V),K})(p.properties,Cm)),e===qt.DISMISSED||e===qt.SENT){var x=n?.[ko.SURVEY_ID],I=n?.[ko.SURVEY_ITERATION];qf({id:x,current_iteration:I}),p.$set=k({},p.$set,{[(v={id:x,current_iteration:I},S=e===qt.SENT?"responded":"dismissed",b="$survey_"+S+"/"+v.id,v.current_iteration&&v.current_iteration>0&&(b="$survey_"+S+"/"+v.id+"/"+v.current_iteration),b)]:!0})}else e===qt.SHOWN&&(p.$set=k({},p.$set,{[ko.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===nm.SHOWN){var T=n?.[zc.TOUR_TYPE];T&&(p.$set=k({},p.$set,{[zc.TOUR_LAST_SEEN_DATE+"/"+T]:new Date().toISOString()}))}var E=k({},p.properties.$set,p.$set);if(Gt(E)||this.setPersonPropertiesForFlags(E),!H(this.config.before_send)){var P=this.Pt(p);if(!P)return;(p=P).uuid=Ec(p.uuid,Ut)}this.dn.emit("eventCaptured",p);var $=(r=i?._url)!==null&&r!==void 0?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),O={method:"POST",url:$,data:p,compression:"best-available",timestampMode:i?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test($)?"body":"capture-body",batchKey:i?._batchKey,transport:i?.transport};return!this.config.request_batching||i&&(i==null||!i._batchKey)||i!=null&&i.send_instantly?this.Pn(O):this.In.enqueue(O),p}A.critical("This capture call is ignored due to client rate limiting.")}}else A.error("No event name provided to posthog.capture")}else A.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(n=>e(n.event,n)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new km(this)}cn(e){this._n.push(e);var n=!0;return()=>{if(n){n=!1;var i=this._n.indexOf(e);i!==-1&&this._n.splice(i,1)}}}calculateEventProperties(e,n,i,r,s){if(i=i||new Date,!this.persistence||!this.sessionPersistence)return n;var o=s?void 0:this.persistence.remove_event_timer(e),a=k({},n);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.gn()&&(a[Zd]=!0),e==="$snapshot"){var l=k({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!X(a.distinct_id)&&!ke(a.distinct_id)||Ko(a.distinct_id))&&A.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=(function(x,I,T,E){var P,$,O,L;if(E===void 0&&(E=!1),!Ve)return{};var N,K=x?[...ri,...I||[]]:[],V=(function(Bn){for(var qe=0;wc.length>qe;qe++){var Dn=wc[qe],$t=Dn[1],Mt=Dn[0].exec(Bn),ct=Mt&&(De($t)?$t(Mt,Bn):$t);if(ct)return ct}return["",""]})(Ve),M=V[0],R=V[1],Z=(N=typeof navigator<"u"?navigator:void 0)!=null&&N.brave?{brave:!0}:{},Ce={};C(T)||(Ce.detectGoogleSearchApp=T);var oe={},ye=(P=navigator)==null||(P=P.userAgentData)==null?void 0:P.platform,$e=($=navigator)==null?void 0:$.maxTouchPoints,ae=w==null||(O=w.screen)==null?void 0:O.width,Ie=w==null||(L=w.screen)==null?void 0:L.height,Se=w?.devicePixelRatio;C(ye)||(oe.userAgentDataPlatform=ye),C($e)||(oe.maxTouchPoints=$e),C(ae)||(oe.screenWidth=ae),C(Ie)||(oe.screenHeight=Ie),C(Se)||(oe.devicePixelRatio=Se);var Be,yt,ge,Ye,wt,mn,Re,Pe,Tt=fe(ll({$os:M,$os_version:R,$browser:Nd(Ve,navigator.vendor,Z,Ce),$device:bc(Ve),$device_type:(yt=Ve,ge=oe,Pe=bc(yt),Pe===_d||Pe===vd||Pe==="Kobo"||Pe==="Kindle Fire"||Pe===Rd?ei:Pe===Gi||Pe===Xn||Pe===Ki||Pe===Jo?"Console":Pe===wd?"Wearable":Pe?it:ge?.userAgentDataPlatform==="Android"&&((Ye=ge?.maxTouchPoints)!==null&&Ye!==void 0?Ye:0)>0?600>Math.min((wt=ge?.screenWidth)!==null&&wt!==void 0?wt:0,(mn=ge?.screenHeight)!==null&&mn!==void 0?mn:0)/((Re=ge?.devicePixelRatio)!==null&&Re!==void 0?Re:1)?it:ei:"Desktop"),$timezone:If(),$timezone_offset:Qg()}),{$current_url:Zi(E?fn(me?.href):me?.href,K,Xi),$host:me?.host,$pathname:me?.pathname,$raw_user_agent:Ve.length>1e3?Ve.substring(0,997)+"...":Ve,$browser_version:Jp(Ve,navigator.vendor,Z,Ce),$browser_language:qc(),$browser_language_prefix:(Be=qc(),typeof Be=="string"?Be.split("-")[0]:void 0),$screen_height:w?.screen.height,$screen_width:w?.screen.width,$viewport_height:w?.innerHeight,$viewport_width:w?.innerWidth,$lib:ne.LIB_NAME,$lib_version:ne.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return ne.SDK_DIST_CHANNEL&&(Tt.$sdk_dist_channel=ne.SDK_DIST_CHANNEL),Tt})(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties,this.config.detect_google_search_app,this.config.disable_capture_url_hashes);if(this.sessionManager){var d=this.sessionManager.checkAndGetSessionAndWindowId(s,i.getTime()),f=d.windowId;a.$session_id=d.sessionId,a.$window_id=f}this.sessionPropsManager&&fe(a,this.sessionPropsManager.getSessionProps());try{var h;this.sessionRecording&&fe(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(h=this.Rn)==null?void 0:h.length}catch(x){a.$sdk_debug_error_capturing_properties=String(x)}if(this.requestRouter.region===xa&&(a.$lib_custom_api_host=this.config.api_host),u=e!==Vn||s?e!==_o||s?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(i):this.pageViewManager.doPageView(i,r),a=fe(a,u),e===Vn&&F&&(a.title=F.title),!C(o)){var p=i.getTime()-o;a.$duration=parseFloat((p/1e3).toFixed(3))}Ve&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();ie(["$referrer","$referring_domain"],(x=>{x in g&&delete m[x]}));var v={};if(this._n.length>0)for(var S of this._n.slice())try{fe(v,S())}catch(x){A.error("Failed to produce browser extension event properties",x)}(a=fe({},c,g,m,k({},v,a))).$is_identified=this._isIdentified(),U(this.config.property_denylist)?ie(this.config.property_denylist,(function(x){delete a[x]})):A.error(zf+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var b=this.config.sanitize_properties;b&&(A.error(iu),a=b(a,e));var _=this.Zn();return a.$process_person_profile=_,_&&!s&&this.Gn("_calculate_event_properties"),a}Vn(e,n,i){var r;if(n===void 0&&(n=!0),i===void 0&&(i=!1),!this.persistence||!this.Zn()||this.mn&&!i)return e;var s=this.persistence.get_initial_props(),o=(r=this.sessionPropsManager)==null?void 0:r.getSetOnceProps(),a=fe({},s,o||{},e||{}),l=this.config.sanitize_properties;return l&&(A.error(iu),a=l(a,"$set_once")),n&&(this.mn=!0),Gt(a)?void 0:a}register(e,n){var i;(i=this.persistence)==null||i.register(e,n)}register_once(e,n,i){var r;(r=this.persistence)==null||r.register_once(e,n,i)}register_for_session(e){var n;(n=this.sessionPersistence)==null||n.register(e),Object.keys(e).forEach((i=>this.yn.add(i))),this.Qn()}unregister(e){var n;(n=this.persistence)==null||n.unregister(e)}unregister_for_session(e){var n;(n=this.sessionPersistence)==null||n.unregister(e),this.yn.delete(e),this.Qn()}Kn(e,n){this.register({[e]:n})}An(){this.yn.forEach((e=>{var n;(n=this.sessionPersistence)==null||n.unregister(e)})),this.yn.clear(),this.Qn()}Qn(){var e;if(this.bn)if(this.config.persistence==="memory"||(e=this.sessionPersistence)!=null&&e.xi||!be.N())be.q(this.bn);else{var n=[];this.yn.forEach((i=>n.push(i))),n.length>0?be.F(this.bn,n):be.q(this.bn)}}getFeatureFlag(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlag(e,n)}getFeatureFlagPayload(e){var n;return(n=this.featureFlags)==null?void 0:n.getFeatureFlagPayload(e)}getFeatureFlagResult(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlagResult(e,n)}getAllFeatureFlags(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.getAllFeatureFlags())!==null&&e!==void 0?e:[]}isFeatureEnabled(e,n){var i,r;return(i=(r=this.featureFlags)==null?void 0:r.isFeatureEnabled(e,n))!==null&&i!==void 0?i:n?.defaultValue}reloadFeatureFlags(){var e;(e=this.featureFlags)==null||e.reloadFeatureFlags()}updateFlags(e,n,i){var r;(r=this.featureFlags)==null||r.updateFlags(e,n,i)}updateEarlyAccessFeatureEnrollment(e,n,i){var r;(r=this.featureFlags)==null||r.updateEarlyAccessFeatureEnrollment(e,n,i)}getEarlyAccessFeatures(e,n,i){var r;return n===void 0&&(n=!1),(r=this.featureFlags)==null?void 0:r.getEarlyAccessFeatures(e,n,i)}on(e,n){return this.dn.on(e,n)}onFeatureFlags(e){return this.featureFlags?this.featureFlags.onFeatureFlags(e):(e([],{},{errorsLoading:!0}),()=>{})}onSurveysLoaded(e){return this.surveys?this.surveys.onSurveysLoaded(e):(e([],{isLoaded:!1,error:xi}),()=>{})}onSessionId(e){var n,i;return(n=(i=this.sessionManager)==null?void 0:i.onSessionId(e))!==null&&n!==void 0?n:()=>{}}getSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getSurveys(e,n):e([],{isLoaded:!1,error:xi})}getActiveMatchingSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,n):e([],{isLoaded:!1,error:xi})}renderSurvey(e,n){var i;(i=this.surveys)==null||i.renderSurvey(e,n)}displaySurvey(e,n){var i;n===void 0&&(n=wm),(i=this.surveys)==null||i.displaySurvey(e,n)}cancelPendingSurvey(e){var n;(n=this.surveys)==null||n.cancelPendingSurvey(e)}canRenderSurvey(e){var n,i;return(n=(i=this.surveys)==null?void 0:i.canRenderSurvey(e))!==null&&n!==void 0?n:{visible:!1,disabledReason:xi}}canRenderSurveyAsync(e,n){var i,r;return n===void 0&&(n=!1),(i=(r=this.surveys)==null?void 0:r.canRenderSurveyAsync(e,n))!==null&&i!==void 0?i:Promise.resolve({visible:!1,disabledReason:xi})}Jn(e){return!e||Ko(e)?(A.critical("Unique user id has not been set in posthog.identify"),!1):e===mr?(A.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.'),!1):!["distinct_id","distinctid"].includes(e.toLowerCase())&&!["undefined","null"].includes(e.toLowerCase())||(A.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.'),!1)}identify(e,n,i){if(!this.__loaded||!this.persistence)return A.uninitializedWarning("posthog.identify");if(ke(e)&&(e=e.toString(),A.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.Jn(e)&&this.Gn("posthog.identify")){var r=this.get_distinct_id();this.register({$user_id:e}),this.get_property(Yi)||this.register_once({$had_persisted_distinct_id:!0,$device_id:r},""),e!==r&&e!==this.get_property(Fi)&&(this.unregister(Fi),this.register({distinct_id:e}));var s,o=(this.persistence.get_property(ot)||Un)===Un,a=e!==r,l=!a&&o;if(a&&o)this.persistence.set_property(ot,vn),this.setPersonPropertiesForFlags({$set:n||{},$set_once:i||{}},!1),this.capture(yo,{distinct_id:e,$anon_distinct_id:r},{$set:n||{},$set_once:i||{}}),this.Sn=Fo(e,n,i),(s=this.featureFlags)==null||s.setAnonymousDistinctId(r);else if(l){this.persistence.set_property(ot,vn);var u=n||{},c=i||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=Fo(e,n,i)}else(n||i)&&this.setPersonProperties(n,i);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Cn)):l&&(n||i)&&this.reloadFeatureFlags()}}setPersonProperties(e,n){if((e||n)&&this.Gn("posthog.setPersonProperties")){var i=Fo(this.get_distinct_id(),e,n);this.Sn!==i?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:n||{}},!0),this.capture("$set",{$set:e||{},$set_once:n||{}}),this.Sn=i):A.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}unsetPersonProperties(e){var n,i=(U(e)?e:[e]).filter((r=>X(r)&&r.length>0));i.length!==0&&this.Gn("posthog.unsetPersonProperties")&&((n=this.featureFlags)==null||n.unsetPersonPropertiesForFlags(i,!0),this.capture("$set",{$unset:i}),this.Sn=null)}group(e,n,i){if(e&&n){var r=this.getGroups(),s=r[e]!==n;if(s&&this.resetGroupPropertiesForFlags(e),this.register({$groups:k({},r,{[e]:n})}),s||i){var o={$group_type:e,$group_key:n};i&&(o.$group_set=i),this.capture(Ac,o)}i&&this.setGroupPropertiesForFlags({[e]:i}),s&&!i&&this.reloadFeatureFlags()}else A.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),(i=this.featureFlags)==null||i.setPersonPropertiesForFlags(e,n)}resetPersonPropertiesForFlags(e){var n;e===void 0&&(e=!0),(n=this.featureFlags)==null||n.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((i=this.featureFlags)==null||i.setGroupPropertiesForFlags(e,n))}resetGroupPropertiesForFlags(e){var n;(n=this.featureFlags)==null||n.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,n){var i,r,s,o,a,l,u,c,d,f;if(n===void 0&&(n=!1),A.info("reset"),!this.__loaded)return A.uninitializedWarning("posthog.reset");var h,p=this.get_property(Yi),g=this.get_property(vo),m=this.get_property(An),v=this.is_capturing();if(this.consent.reset(),n||!v||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after."),(i=this.persistence)==null||i.clear(),(r=this.sessionPersistence)==null||r.clear(),this.yn.clear(),this.Qn(),C(m)||(h=this.persistence)==null||h.register({[An]:m}),(s=this.surveys)==null||s.reset(),(o=this.Un)==null||o.stop(),(a=this.featureFlags)==null||a.reset(),(l=this.conversations)==null||l.reset(),(u=this.logs)==null||u.reset(),(c=this.metrics)==null||c.reset(),(d=this.persistence)==null||d.set_property(ot,Un),(f=this.sessionManager)==null||f.resetSessionId(),this.Sn=null,this.config.cookieless_mode===Ht)this.register_once({distinct_id:mr,$device_id:null},"");else{var S=this.config.get_device_id(Ut());this.register_once({distinct_id:S,$device_id:e?S:p},""),e||C(g)||this.register({[vo]:g})}this.register({$last_posthog_reset:new Date().toISOString()},1),delete this.config.identity_distinct_id,delete this.config.identity_hash,this.reloadFeatureFlags()}shutdown(e){var n=this;return se((function*(){var i,r,s,o,a,l,u;if(n.__loaded){(i=n.Un)==null||i.stop(),(r=n.jn)==null||r.dispose(),(s=n.sessionRecording)==null||s.dispose(),(o=n.logs)==null||o.flushLogs("sendBeacon"),(a=n.metrics)==null||a.flush("sendBeacon"),(l=n.In)==null||l.unload(),(u=n.Rn)==null||u.unload();try{var c;(c=n.featureFlags)==null||c.destroy()}catch(d){A.error("Error while destroying feature flags",d)}}else A.uninitializedWarning("posthog.shutdown")}))()}setIdentity(e,n){var i;this.config.identity_distinct_id=e,this.config.identity_hash=n,this.alias(e),(i=this.conversations)==null||i.Xn()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,(e=this.conversations)==null||e.ts()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,n;return(e=(n=this.sessionManager)==null?void 0:n.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var n=this.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.sessionStartTimestamp,r=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+n.sessionId);if(e!=null&&e.withTimestamp&&i){var s,o=(s=e.timestampLookBack)!==null&&s!==void 0?s:10;if(!i)return r;r+="?t="+Math.max(Math.floor((new Date().getTime()-i)/1e3)-o,0)}return r}alias(e,n){return e===this.get_property(zd)?(A.critical("Attempting to create alias for existing People user - aborting."),-2):this.Gn("posthog.alias")?(C(n)&&(n=this.get_distinct_id()),e!==n?(this.Kn(Fi,e),this.capture("$create_alias",{alias:e,distinct_id:n})):(A.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var n=k({},this.config);if(he(e)){var i,r,s,o,a,l,u,c,d,f,h,p;fe(this.config,ru(e));var g=this.En();(i=this.persistence)==null||i.update_config(this.config,n,g),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new xo(k({},this.config,{persistence:"sessionStorage"}),g,!1);var m=this.Cn(this.config.debug);gt(m)&&(this.config.debug=m),gt(this.config.debug)&&(this.config.debug?(ne.DEBUG=!0,le.N()&&le.F("ph_debug",!0),A.info("set_config",{config:e,oldConfig:n,newConfig:k({},this.config)})):(ne.DEBUG=!1,le.N()&&le.q("ph_debug"))),(r=this.featureFlags)==null||r.updateConfig==null||r.updateConfig(this.config,this.Qi()),(s=this.exceptionObserver)==null||s.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(f=this.deadClicksAutocapture)==null||f.startIfEnabledOrStop(),(h=this.surveys)==null||h.loadIfEnabled(),this.es(),(p=this.externalIntegrations)==null||p.startIfEnabledOrStop()}}_overrideSDKInfo(e,n){ne.LIB_NAME=e,ne.LIB_VERSION=n}startSessionRecording(e){var n,i,r,s,o,a=e===!0,l={sampling:a||!(e==null||!e.sampling),linked_flag:a||!(e==null||!e.linked_flag),url_trigger:a||!(e==null||!e.url_trigger),event_trigger:a||!(e==null||!e.event_trigger)};Object.values(l).some(Boolean)&&((n=this.sessionManager)==null||n.checkAndGetSessionAndWindowId(),l.sampling&&((i=this.sessionRecording)==null||i.overrideSampling()),l.linked_flag&&((r=this.sessionRecording)==null||r.overrideLinkedFlag()),l.url_trigger&&((s=this.sessionRecording)==null||s.overrideTrigger("url")),l.event_trigger&&((o=this.sessionRecording)==null||o.overrideTrigger("event"))),this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,n){if(this.exceptions){var i=new Error("PostHog syntheticException"),r=this.exceptions.buildProperties(e,{handled:!0,syntheticException:i});return this.exceptions.sendExceptionEvent(k({},r,n))}}addExceptionStep(e,n){var i;(i=this.exceptions)==null||i.addExceptionStep(e,n)}captureLog(e){var n;(n=this.logs)==null||n.captureLog(e)}get logger(){var e,n;return(e=(n=this.logs)==null?void 0:n.logger)!==null&&e!==void 0?e:Je.rs}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var n,i;return(n=(i=this.toolbar)==null?void 0:i.loadToolbar(e))!==null&&n!==void 0&&n}get_property(e){var n;return(n=this.persistence)==null?void 0:n.props[e]}getSessionProperty(e){var n;return(n=this.sessionPersistence)==null?void 0:n.props[e]}toString(){var e,n=(e=this.config.name)!==null&&e!==void 0?e:Gn;return n!==Gn&&(n=Gn+"."+n),n}_isIdentified(){var e,n;return((e=this.persistence)==null?void 0:e.get_property(ot))===vn||((n=this.sessionPersistence)==null?void 0:n.get_property(ot))===vn}Zn(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles===pa&&!this._isIdentified()&&Gt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[Fi])&&((n=this.persistence)==null||(n=n.props)==null||!n[es]))}zn(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Zn()||this.Gn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.Gn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}Gn(e){return this.config.person_profiles==="never"?(A.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Kn(es,!0),!0)}En(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut();return this.config.disable_persistence||e&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!==kn)}es(){var e,n,i,r,s=this.En();return((e=this.persistence)==null?void 0:e.xi)!==s&&((i=this.persistence)==null||i.set_disabled(s)),((n=this.sessionPersistence)==null?void 0:n.xi)!==s&&((r=this.sessionPersistence)==null||r.set_disabled(s)),s&&(this.yn.clear(),this.Qn()),s}opt_in_capturing(e){var n;if(this.config.cookieless_mode!==Ht){if(this.gn()){var i,r,s,o,a;this.Yn(!0,!0),(i=this.sessionManager)==null||i.destroy(),(r=this.pageViewManager)==null||r.destroy(),this.sessionManager=new Qc(this),this.pageViewManager=new Wc(this),this.persistence&&(this.sessionPropsManager=new Xc(this,this.sessionManager,this.persistence));var l,u=(s=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&s!==void 0?s:(a=Je.__defaultExtensionClasses)==null?void 0:a.sessionRecording;u&&(this.sessionRecording=this.pn(this.sessionRecording,new u(this)),this.hn&&((l=this.sessionRecording)==null||l.onRemoteConfig==null||l.onRemoteConfig(this.hn)))}var c,d;this.consent.optInOut(!0),this.es(),this.Bn(),(n=this.sessionRecording)==null||n.startIfEnabledOrStop(),this.config.cookieless_mode==kn&&((c=this.surveys)==null||c.loadIfEnabled()),(C(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((d=e?.captureEventName)!==null&&d!==void 0?d:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hn()}else A.warn(nu)}opt_out_capturing(){var e,n,i;this.config.cookieless_mode!==Ht?(this.config.cookieless_mode===kn&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===kn&&(this.register({distinct_id:mr,$device_id:null}),(e=this.sessionRecording)==null||e.stopRecording(),this.sessionRecording=void 0,(n=this.sessionManager)==null||n.destroy(),(i=this.pageViewManager)==null||i.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.Hn(),this.Bn())):A.warn(nu)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===Ht||(this.config.cookieless_mode===kn?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return Ue?Bf(Ue,this.config.custom_blocked_useragents):void 0}Hn(){F&&(F.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(Vn,{title:F.title},{send_instantly:!0}),this.kn&&(F.removeEventListener(ts,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),ve(F,ts,this.kn)))}debug(e){e===!1?(w?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(w?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}Qi(){var e=this.Mn||{};return"advanced_disable_flags"in e?!!e.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(A.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(function(n,i,r,s,o){var a=i in n&&!H(n[i]),l=r in n&&!H(n[r]);return a?n[i]:!!l&&(o&&o.warn("Config field '"+r+"' is deprecated. Please use '"+i+"' instead. The old field will be removed in a future major version."),n[r])})(e,"advanced_disable_flags","advanced_disable_decide",0,A)}Pt(e){var n;if(H(this.config.before_send))return e;var i=Object.keys((n=e.properties)!==null&&n!==void 0?n:{}).filter(Bp),r=U(this.config.before_send)?this.config.before_send:[this.config.before_send],s=e;for(var o of r){if(s=o(s),H(s)){var a="Event '"+e.event+"' was rejected in beforeSend function";return Op(e.event)?A.warn(a+". This can cause unexpected behavior."):A.info(a),null}s.properties&&!Gt(s.properties)||A.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}for(var l of i)if(s.properties&&H(s.properties[l]))return A.warn("Event '"+e.event+"' had its '"+l+"' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped."),null;return s}getPageViewId(){var e;return(e=this.pageViewManager.ui)==null?void 0:e.pageViewId}captureTraceFeedback(e,n){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:n})}captureTraceMetric(e,n,i){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:n,$ai_metric_value:String(i)})}Cn(e){var n=gt(e)&&!e,i=le.N()&&le.P("ph_debug")==="true";return!n&&(!!i||e)}}Je.__defaultExtensionClasses={},Je.rs=(()=>{var t=()=>{};return{trace:t,debug:t,info:t,warn:t,error:t,fatal:t}})(),(function(t,e){for(var n=0;e.length>n;n++)t.prototype[e[n]]=kg(t.prototype[e[n]])})(Je,["identify"]);class su{constructor(e){this.disabled=e===!1;var n=he(e)?e:{};this.thresholdPx=n.threshold_px||30,this.timeoutMs=n.timeout_ms||1e3,this.clickCount=n.click_count||3,this.clicks=[]}isRageClick(e,n,i){if(this.disabled)return!1;var r=this.clicks[this.clicks.length-1];if(r&&Math.abs(e-r.x)+Math.abs(n-r.y)i-r.timestamp){if(this.clicks.push({x:e,y:n,timestamp:i}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:n,timestamp:i}];return!1}}var $o="$copy_autocapture",Mo=pe("[AutoCapture]");function Lo(t,e){return e.length>t?e.slice(0,t)+"...":e}function Fm(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!hn(e));return e}function Rm(t,e){var n,i,r=e.e,s=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!hn(t))return{props:{}};for(var c=[t],d=new Set([t]),f=t;f.parentNode&&!Qe(f,"body")&&lf>c.length;)if(af(f.parentNode)){var h=f.parentNode.host;if(d.has(h))break;d.add(h),c.push(h),f=h}else{if(!hn(f.parentNode)||d.has(f.parentNode))break;d.add(f.parentNode),c.push(f.parentNode),f=f.parentNode}var p,g,m=[],v={},S=!1,b=!1;if(ie(c,(E=>{var P=va(E);if(Qe(E,"a")){var $=E.getAttribute("href");S=!!(P&&$&&Ui($))&&(u?fn($):$)}j(rs(E),"ph-no-capture")&&(b=!0),m.push((function(L,N,K,V,M){M===void 0&&(M=!1);var R=L.tagName.toLowerCase(),Z={tag_name:R};ul.indexOf(R)>-1&&!K&&(Z.$el_text=R.toLowerCase()==="a"||R.toLowerCase()==="button"?Lo(1024,jc(L)):Lo(1024,Ji(L)));var Ce=rs(L);Ce.length>0&&(Z.classes=Ce.filter((function(ae){return ae!==""}))),ie(L.attributes,(function(ae){var Ie;if((!hf(L)||["name","id","class","aria-label"].indexOf(ae.name)!==-1)&&(V==null||!V.includes(ae.name))&&!N&&Ui(ae.value)&&(!X(Ie=ae.name)||Ie.substring(0,10)!=="_ngcontent"&&Ie.substring(0,7)!=="_nghost")){var Se=ae.value;ae.name==="class"&&(Se=cl(Se).join(" ")),Z["attr__"+ae.name]=Lo(1024,ae.name==="href"&&M?fn(Se):Se)}}));for(var oe=1,ye=1,$e=L;$e=Fm($e);)oe++,$e.tagName===L.tagName&&ye++;return Z.nth_child=oe,Z.nth_of_type=ye,Z})(E,s,o,a,u));var O=(function(L){if(!va(L))return{};var N={};return ie(L.attributes,(function(K){if(K.name&&K.name.indexOf("data-ph-capture-attribute")===0){var V=K.name.replace("data-ph-capture-attribute-",""),M=K.value;V&&M&&Ui(M)&&(N[V]=M)}})),N})(E);fe(v,O)})),b)return{props:{},explicitNoCapture:b};if(o||(m[0].$el_text=Qe(t,"a")||Qe(t,"button")?jc(t):Ji(t)),S){var _,x;m[0].attr__href=S;var I=(_=ss(S))==null?void 0:_.host,T=w==null||(x=w.location)==null?void 0:x.host;I&&T&&I!==T&&(p=S)}return{props:fe({$event_type:r.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(E){return E.map((P=>{var $,O,L="";if(P.tag_name&&(L+=P.tag_name),P.attr_class)for(var N of(P.attr_class.sort(),P.attr_class))L+="."+N.replace(/"/g,"");var K=k({},P.text?{text:P.text}:{},{"nth-child":($=P.nth_child)!==null&&$!==void 0?$:0,"nth-of-type":(O=P.nth_of_type)!==null&&O!==void 0?O:0},P.href?{href:P.href}:{},P.attr_id?{attr_id:P.attr_id}:{},P.attributes),V={};return $r(K).sort(((M,R)=>M[0].localeCompare(R[0]))).forEach((M=>{var R=M[1];return V[Uc(M[0].toString())]=Uc(R.toString())})),(L+=":")+$r(V).map((M=>M[0]+'="'+M[1]+'"')).join("")})).join(";")})((function(E){return E.map((P=>{var $,O,L={text:($=P.$el_text)==null?void 0:$.slice(0,400),tag_name:P.tag_name,href:(O=P.attr__href)==null?void 0:O.slice(0,2048),attr_class:zg(P),attr_id:P.attr__id,nth_child:P.nth_child,nth_of_type:P.nth_of_type,attributes:{}};return $r(P).filter((N=>N[0].indexOf("attr__")===0)).forEach((N=>L.attributes[N[0]]=N[1])),L}))})(g)))},(n=m[0])!=null&&n.$el_text?{$el_text:(i=m[0])==null?void 0:i.$el_text}:{},p&&r.type==="click"?{$external_click_url:p}:{},v)}}var Ii=pe("[ExceptionAutocapture]"),ou=()=>{},Tm=pe("[TracingHeaders]"),wn=pe("[Web Vitals]"),au=9e5,lu="disabled",cu="lazy_loading",ki="awaiting_config",Sr="missing_config";pe("[SessionRecording]"),pe("[SessionRecording]");var Ia="[SessionRecording]",Ot=pe(Ia),$m=pe("[Heatmaps]");function No(t){return he(t)&&"clientX"in t&&"clientY"in t&&ke(t.clientX)&&ke(t.clientY)}var xr=pe("[Product Tours]"),Oo=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(sl))},Mm=["$set_once","$set"],bt=pe("[SiteApps]"),uu="Error while initializing PostHog app with config id ";function qn(t,e,n){if(H(t))return!1;switch(n){case"exact":return t===e;case"contains":var i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(i,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}class Lm{constructor(e){this.ns=new pl,this.ss=(n,i)=>this.os(n,i)&&this.ls(n,i)&&this.us(n,i)&&this.hs(n,i),this.os=(n,i)=>i==null||!i.event||n?.event===i?.event,this._instance=e,this.ds=new Set,this.vs=new Set}init(){var e,n;C((e=this._instance)==null?void 0:e._addCaptureHook)||(n=this._instance)==null||n._addCaptureHook(((i,r)=>{this.on(i,r)}))}register(e){var n,i;if(!C((n=this._instance)==null?void 0:n._addCaptureHook)&&(e.forEach((o=>{var a,l;(a=this.vs)==null||a.add(o),(l=o.steps)==null||l.forEach((u=>{var c;(c=this.ds)==null||c.add(u?.event||"")}))})),(i=this._instance)!=null&&i.autocapture)){var r,s=new Set;e.forEach((o=>{var a;(a=o.steps)==null||a.forEach((l=>{l!=null&&l.selector&&s.add(l?.selector)}))})),(r=this._instance)==null||r.autocapture.setElementSelectors(s)}}on(e,n){var i;n!=null&&e.length!=0&&(this.ds.has(e)||this.ds.has(n.event))&&this.vs&&((i=this.vs)==null?void 0:i.size)>0&&this.vs.forEach((r=>{this.cs(n,r)&&this.ns.emit("actionCaptured",r.name)}))}fs(e){this.onAction("actionCaptured",(n=>e(n)))}cs(e,n){if(n?.steps==null)return!1;for(var i of n.steps)if(this.ss(e,i))return!0;return!1}onAction(e,n){return this.ns.on(e,n)}ls(e,n){if(n!=null&&n.url){var i,r=e==null||(i=e.properties)==null?void 0:i.$current_url;if(!r||typeof r!="string"||!qn(r,n.url,n.url_matching||"contains"))return!1}return!0}us(e,n){return!!this.ps(e,n)&&!!this.gs(e,n)&&!!this.ys(e,n)}ps(e,n){var i;if(n==null||!n.href)return!0;var r=this.bs(e);if(r.length>0)return r.some((a=>qn(a.href,n.href,n.href_matching||"exact")));var s,o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!o&&qn((s=o.match(/(?::|")href="(.*?)"/))?s[1]:"",n.href,n.href_matching||"exact")}gs(e,n){var i;if(n==null||!n.text)return!0;var r=this.bs(e);if(r.length>0)return r.some((u=>qn(u.text,n.text,n.text_matching||"exact")||qn(u.$el_text,n.text,n.text_matching||"exact")));var s,o,a,l=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!l&&(s=(function(u){for(var c,d=[],f=/(?::|")text="(.*?)"/g;!H(c=f.exec(u));)d.includes(c[1])||d.push(c[1]);return d})(l),o=n.text,a=n.text_matching||"exact",s.some((u=>qn(u,o,a))))}ys(e,n){var i,r;if(n==null||!n.selector)return!0;var s=e==null||(i=e.properties)==null?void 0:i.$element_selectors;if(s!=null&&s.includes(n.selector))return!0;var o=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";if(n.selector_regex&&o)try{return new RegExp(n.selector_regex).test(o)}catch{return!1}return!1}bs(e){var n;return(e==null||(n=e.properties)==null?void 0:n.$elements)==null?[]:e?.properties.$elements}hs(e,n){return n==null||!n.properties||n.properties.length===0||Uf(n.properties.reduce(((i,r)=>{var s=U(r.value)?r.value.map(String):r.value!=null?[String(r.value)]:[];return i[r.key]={values:s,operator:r.operator||"exact"},i}),{}),e?.properties)}}class Nm{constructor(e){var n;this._s=[],this._instance=e,this.ws=new Map,this.ks=new Map,this.xs=new Map,(n=this._instance)==null||n.onSessionId==null||n.onSessionId((i=>this.Ss(i)))}Cs(e){return!1}Ms(){return null}Ts(e){}Es(){}Is(e,n){return!!e&&Uf(e.propertyFilters,n?.properties)}Ps(e,n){var i=new Map;return e.forEach((r=>{var s;(s=r.conditions)==null||(s=s[n])==null||(s=s.values)==null||s.forEach((o=>{if(o!=null&&o.name){var a=i.get(o.name)||[];a.push(r.id),i.set(o.name,a)}}))})),i}Rs(e,n,i){var r=(i===wi.Activation?this.ws:this.ks).get(e),s=[];return this.As((o=>{s=o.filter((a=>r?.includes(a.id)))})),s.filter((o=>{var a,l=(a=o.conditions)==null||(a=a[i])==null||(a=a.values)==null?void 0:a.find((u=>u.name===e));return this.Is(l,n)}))}register(e){var n;C((n=this._instance)==null?void 0:n._addCaptureHook)||(this.Fs(e),this.Ls(e))}Ls(e){var n=e.filter((i=>{var r,s;return((r=i.conditions)==null?void 0:r.actions)&&((s=i.conditions)==null||(s=s.actions)==null||(s=s.values)==null?void 0:s.length)>0}));n.length!==0&&(this.Os==null&&(this.Os=new Lm(this._instance),this.Os.init(),this.Os.fs((i=>{this.onAction(i)}))),n.forEach((i=>{var r,s,o,a,l;i.conditions&&(r=i.conditions)!=null&&r.actions&&(s=i.conditions)!=null&&(s=s.actions)!=null&&s.values&&((o=i.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.Os)==null||a.register(i.conditions.actions.values),(l=i.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var c=this.xs.get(u.name);c&&c.push(i.id),this.xs.set(u.name,c||[i.id])}})))})))}Fs(e){var n,i=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.events)&&((a=s.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0})),r=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.cancelEvents)&&((a=s.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0}));i.length===0&&r.length===0||((n=this._instance)==null||n._addCaptureHook(((s,o)=>{this.onEvent(s,o)})),this.ws=this.Ps(e,wi.Activation),this.ks=this.Ps(e,wi.Cancellation))}onEvent(e,n){var i,r,s=this.Ds(),o=(n==null||(i=n.properties)==null?void 0:i.$survey_id)||(n==null||(r=n.properties)==null?void 0:r.$product_tour_id);if(o&&this.getActivatedIds().includes(o)){var a=this.$s(e,o);if(a==="consume")return s.info("event consumed activated item, removing it",{event:e,itemId:o}),void this.Ns([o]);if(a==="persist")return s.info("shown item promoted to persisted activation",{event:e,itemId:o}),this.qs(o),void this.js([o])}if(this.ks.has(e)){var l=this.Rs(e,n,wi.Cancellation);l.length>0&&(s.info("cancel event matched, cancelling items",{event:e,itemsToCancel:l.map((c=>c.id))}),this.Ns(l.map((c=>c.id))),l.forEach((c=>this.Bs(c.id))))}if(this.ws.has(e)){s.info("event name matched",{event:e,eventPayload:n,items:this.ws.get(e)});var u=this.Rs(e,n,wi.Activation);this.Hs(u.map((c=>c.id)))}}onAction(e){this.xs.has(e)&&this.Hs(this.xs.get(e)||[])}Hs(e){var n;if(e.length!==0){var i=!((n=this._instance)==null||n.get_session_id==null||!n.get_session_id()),r=[];for(var s of e)i&&this.Cs(s)?this.qs(s)&&this.Us(s):r.push(s);r.length>0&&(this._s=[...new Set([...this._s,...r])]),this.Ds().info("updating activated items",{activatedItems:this.getActivatedIds()})}}qs(e){this._s=this._s.filter((i=>i!==e));var n=this.zs();return!n.includes(e)&&(this.Ws([...n,e]),this.Vs(),!0)}Ns(e){var n=new Set(e);this._s=this._s.filter((s=>!n.has(s)));var i=this.Zs(),r=i.filter((s=>!n.has(s)));r.length!==i.length&&(this.Ws(r),r.length===0&&this.Gs()),this.js(e)}Qs(){var e,n=this.Ms();if(!n)return{};var i=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n];return i&&typeof i=="object"?i:{}}Us(e){if(this.Ms()){var n=this.Qs();this.Ts(k({},n,{[e]:Date.now()}))}}js(e){if(this.Ms()){var n=this.Qs(),i={},r=!1;for(var s of Object.entries(n)){var o=s[0],a=s[1];e.includes(o)?r=!0:i[o]=a}r&&(Gt(i)?this.Es():this.Ts(i))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var n=this.Qs()[e];return ke(n)?n:void 0}}Zs(){var e,n=this.Js();return((e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n])||[]}zs(){var e,n,i=this.Zs();if(i.length===0)return[];var r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[this.Ys()],s=(n=this._instance)==null||n.get_session_id==null?void 0:n.get_session_id();return s&&r===s?i:[]}Vs(){var e,n=(e=this._instance)==null||e.get_session_id==null?void 0:e.get_session_id();n&&this.Xs(n)}Gs(){this.ta()}Ss(e){var n,i=(n=this._instance)==null||(n=n.persistence)==null?void 0:n.props[this.Ys()];if(i&&i!==e){var r=this.Zs(),s=this.Qs();r.length>0&&(this.Ws([]),r.filter((o=>ke(s[o]))).forEach((o=>this.Bs(o)))),this.Gs(),this.Ks()}}getActivatedIds(){return[...new Set([...this.zs(),...this._s])].filter((e=>!this.ea(e)))}reset(){this._s=[],this.Zs().length>0&&this.Ws([]),this.Gs(),this.Ks()}getEventToItemsMap(){return this.ws}ia(){return this.Os}}class Om extends Nm{constructor(e){super(e)}Js(){return ca}Ys(){return Fr}Ms(){return Rr}Ts(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Rr]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Rr)}Cs(e){var n,i;this.As((s=>{i=s.find((o=>o.id===e))}));var r=(n=i)==null||(n=n.appearance)==null?void 0:n.surveyPopupDelaySeconds;return ke(r)&&r>0}ra(){return qt.SHOWN}As(e){var n;(n=this._instance)==null||n.getSurveys(e)}Bs(e){var n;(n=this._instance)==null||n.cancelPendingSurvey(e)}Ds(){return Q}Ws(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[ca]:e})}Xs(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Fr]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Fr)}ea(){return!1}$s(e,n){var i;this.As((s=>{i=s.find((o=>o.id===n))}));var r=!i||(function(s){var o;return Hf(s)&&!((o=s.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||s.schedule==="always"})(i);return r?e===qt.SHOWN?"consume":"ignore":e===qt.SHOWN?"persist":e===qt.DISMISSED||e===qt.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var Ir="SDK is not enabled or survey functionality is not yet loaded",du="Disabled. Not loading surveys.",Bm=w!=null&&w.location?os(w.location.hash,"__posthog")||os(location.hash,"state"):null,fu="_postHogToolbarParams",hu=pe("[Toolbar]"),pu=pe("[FeatureFlags]");class Dm{constructor(e,n){n===void 0&&(n=!1),this.na=!1,this.update(e,n)}update(e,n){this.sa=((i,r)=>{var s,o,a,l;return{bootstrap:{featureFlags:(s=i.bootstrap)==null?void 0:s.featureFlags,featureFlagPayloads:(o=i.bootstrap)==null?void 0:o.featureFlagPayloads},remoteRequestsDisabled:r,featureFlagsDisabled:!!i.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!i.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!i.advanced_feature_flags_dedup_per_session,cacheTtlMs:i.feature_flag_cache_ttl_ms,requestTimeoutMs:i.feature_flag_request_timeout_ms,compression:i.disable_compression?"none":"base64",evaluationContexts:(a=(l=i.evaluation_contexts)!==null&&l!==void 0?l:i.evaluation_environments)!==null&&a!==void 0?a:[],flagKeys:U(i.flag_keys)?i.flag_keys:void 0}})(e,n),!e.evaluation_environments||e.evaluation_contexts||this.na||(pu.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.na=!0),C(e.flag_keys)||U(e.flag_keys)||pu.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var gu=pe("[FeatureFlags]"),bn=pe("[FeatureFlags]",{debugEnabled:!0}),Bo=`" failed. Feature flags didn't load in time.`,mu="connection_error",vu=t=>{for(var e={},n=0;t.length>n;n++)e[t[n]]=!0;return e},_u=t=>{var e={};for(var n of $r(t||{})){var i=n[1];i&&(e[n[0]]=i)}return e},Et=pe("[Error tracking]"),yu="Refusing to render web experiment since the viewer is a likely bot",jm={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>cs(e,t),not_regex:(t,e)=>!cs(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class Me{get Ne(){return this._instance.config}constructor(e){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(i){i===void 0&&(i=!1),n.getWebExperiments((r=>{Me.aa("retrieved web experiments from the server"),n.oa=new Map,r.forEach((s=>{if(s.feature_flag_key){var o;n.oa&&(Me.aa("setting flag key ",s.feature_flag_key," to web experiment ",s),(o=n.oa)==null||o.set(s.feature_flag_key,s));var a=n._instance.getFeatureFlag(s.feature_flag_key);X(a)&&s.variants[a]&&n.la(s.name,a,s.variants[a].transforms)}else if(s.variants)for(var l in s.variants){var u=s.variants[l];Me.ua(u,n._instance)&&n.la(s.name,l,u.transforms)}}))}),i)},this._instance=e,this._instance.onFeatureFlags((i=>{this.onFeatureFlags(i)}))}initialize(){}onFeatureFlags(e){if(this._is_bot())Me.aa(yu);else if(!this.Ne.disable_web_experiments){if(H(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();Me.aa("applying feature flags",e),e.forEach((n=>{var i;if(this.oa&&(i=this.oa)!=null&&i.has(n)){var r,s=this._instance.getFeatureFlag(n),o=(r=this.oa)==null?void 0:r.get(n);s&&o!=null&&o.variants[s]&&this.la(o.name,s,o.variants[s].transforms)}}))}}previewWebExperiment(){var e=Me.getWindowLocation();if(e!=null&&e.search){var n=ii(e?.search,"__experiment_id"),i=ii(e?.search,"__experiment_variant");n&&i&&(Me.aa("previewing web experiments "+n+" && "+i),this.getWebExperiments((r=>{this.ha(parseInt(n),i,r)}),!1,!0))}}loadIfEnabled(){this.Ne.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,n,i){if(this.Ne.disable_web_experiments&&!i)return e([]);var r=this._instance.get_property("$web_experiments");if(r&&!n)return e(r);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this.Ne.token),method:"GET",timestampMode:"query",callback:s=>e(s.statusCode===200&&s.json&&s.json.experiments||[])})}ha(e,n,i){var r=i.filter((s=>s.id===e));r&&r.length>0&&(Me.aa("Previewing web experiment ["+r[0].name+"] with variant ["+n+"]"),this.la(r[0].name,n,r[0].variants[n].transforms))}static ua(e,n){return!H(e.conditions)&&Me.da(e,n)&&Me.va(e)}static da(e,n){var i;if(H(e.conditions)||H((i=e.conditions)==null?void 0:i.url))return!0;var r=Me.getWindowLocation();if(r){var s,o,a,l=rf(n,r.href);return(s=e.conditions)==null||!s.url||jm[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return w?.location}static va(e){var n;if(H(e.conditions)||H((n=e.conditions)==null?void 0:n.utm))return!0;var i=yf();if(i.utm_source){var r,s,o,a,l,u,c,d,f=(r=e.conditions)==null||(r=r.utm)==null||!r.utm_campaign||((s=e.conditions)==null||(s=s.utm)==null?void 0:s.utm_campaign)==i.utm_campaign,h=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==i.utm_source,p=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==i.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==i.utm_term;return f&&p&&g&&h}return!1}static aa(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;n>r;r++)i[r-1]=arguments[r];A.info("[WebExperiments] "+e,i)}la(e,n,i){this._is_bot()?Me.aa(yu):n!=="control"?i.forEach((r=>{if(r.selector){var s;Me.aa("applying transform of variant "+n+" for experiment "+e+" ",r);var o=(s=document)==null?void 0:s.querySelectorAll(r.selector);o?.forEach((a=>{var l=a;r.html&&(l.innerHTML=r.html),r.css&&l.setAttribute("style",r.css)}))}})):Me.aa("Control variants leave the page unmodified.")}_is_bot(){return Ue&&this._instance?Bf(Ue,this.Ne.custom_blocked_useragents):void 0}}var st=pe("[Conversations]"),En="Conversations not available yet.",wu="console",Gf="__posthogHandledLogsRequestError",Do=(t,e)=>{var n=t instanceof Error?t:new Error(e);return n[Gf]=!0,n},bu=t=>!!t&&typeof t=="object"&&t[Gf]===!0,Cs={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=gu,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 Dm(t.config,t.Qi()),this.Ta=this.Ea)}updateConfig(t,e){var n;(n=this.Ea)==null||n.update(t,e)}setup(t){return this.Ia=t,this.rt=t.logger.createLogger("[FeatureFlags]"),n=()=>{this.Ia===t&&(this.Ia=void 0,this.nn=t,this.Pa(t))},(e=t.kv.initialize())!=null&&e.then?e.then(n):n();var e,n}Pa(t){if(this.nn===t)return w&&ve(w,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){w?.removeEventListener("online",this.Ca)}dispose(){var t;this.ba++,this.wa=!1,this.Ia=void 0,this.nn&&(this.La(),(t=this.Ra)==null||t.dispose(),this.Ra=void 0,this.ga=[],w?.removeEventListener("online",this.Ca),this.nn=void 0)}get Ne(){return this.Ta.get()}Oa(t){var e;return(e=this.nn)==null?void 0:e.kv.get(t)}F(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.set(t)}))}q(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.remove(t)}))}Da(t){try{t()}catch(e){this.rt.error("Failed to update feature flag persistence",e)}}Fa(){var t={};for(var e of[Ti,$i,Pr,xt]){var n=this.Oa(e);C(n)||(t[e]=n)}this.fa=t;var i=k({},t),r=this.Oa(Sn);if(r)for(var s of Object.entries(r))i["$feature/"+s[0]]=s[1];this.pa=i}Aa(){var t=this.Ne.cacheTtlMs;if(!t||0>=t)return!1;var e=this.Oa(ji);return typeof e!="number"||Date.now()-e>t}$a(){return!!this.Aa()&&(this.xa||this.ya||(this.xa=!0,this.rt.warn("Feature flag cache is stale, triggering refresh..."),this.reloadFeatureFlags()),!0)}Na(){var t=this.Ne.evaluationContexts;return t!=null&&t.length?t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid evaluation context found:",e,"Expected non-empty string"),n})):[]}qa(){var t=this.Ne.flagKeys;if(!C(t))return t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid flag key found:",e,"Expected non-empty string"),n}))}initialize(){var t,e,n=this.Ne,i=(t=(e=n.bootstrap)==null?void 0:e.featureFlags)!==null&&t!==void 0?t:{};if(Object.keys(i).length){var r,s,o=(r=(s=n.bootstrap)==null?void 0:s.featureFlagPayloads)!==null&&r!==void 0?r:{},a=Object.keys(i).filter((u=>!!i[u])).reduce(((u,c)=>(u[c]=i[c]||!1,u)),{}),l=Object.keys(o).filter((u=>a[u])).reduce(((u,c)=>(o[c]&&(u[c]=o[c]),u)),{});return this.ja({featureFlags:a,featureFlagPayloads:l})}}updateFlags(t,e,n){var i,r,s=n!=null&&n.merge&&(i=this.Oa(Sn))!==null&&i!==void 0?i:{},o=n!=null&&n.merge&&(r=this.Oa($i))!==null&&r!==void 0?r:{},a=k({},s,t),l=k({},o,e),u={};for(var c of Object.entries(a)){var d=c[0],f=c[1];u[d]={key:d,enabled:hc(f),variant:pc(f),reason:void 0,metadata:C(l?.[d])?void 0:{id:0,version:void 0,description:void 0,payload:l[d]}}}this.ja({flags:u})}get hasLoadedFlags(){return this.ma}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var t=this.Oa(aa),e=this.Oa(xt),n=this.Oa(xn);if(!n&&!e)return t||{};var i=fe({},t||{}),r=[...new Set([...Object.keys(n||{}),...Object.keys(e||{})])];for(var s of r){var o,a,l=i[s],u=e?.[s],c=C(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=C(u)?l?.variant:typeof u=="string"?u:void 0,f=n?.[s],h=k({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(h.original_enabled=l?.enabled),d!==l?.variant&&(h.original_variant=l?.variant),f&&(h.metadata=k({},l?.metadata,{payload:f,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),i[s]=h}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:n,finalDetails:i}),this.ca=!0),i}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((n=>{var i=t[n];return{key:n,enabled:hc(i),variant:pc(i),payload:fc(e[n])}}))}getFlagVariants(){var t=this.Oa(Sn),e=this.Oa(xt);if(!e)return t||{};for(var n=fe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:e,finalFlags:n}),this.ca=!0),n}getFlagPayloads(){var t=this.Oa($i),e=this.Oa(xn);if(!e)return t||{};for(var n=fe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flag payloads!",{flagPayloads:t,overriddenPayloads:e,finalPayloads:n}),this.ca=!0),n}reloadFeatureFlags(){this._a||this.Ne.featureFlagsDisabled||this.Ma()||this.Ba||(this.ga.slice().forEach((t=>{try{t()}catch(e){this.rt.error("Error while running feature flags reloading callback",e)}})),this.Ba=setTimeout((()=>{this.Ha()}),5))}La(){clearTimeout(this.Ba),this.Ba=void 0}onReloading(t){return this.ga.push(t),()=>{this.ga=this.ga.filter((e=>e!==t))}}ensureFlagsLoaded(){this.ma||this.ya||this.Ba||this.reloadFeatureFlags()}setAnonymousDistinctId(t){this.$anon_distinct_id=t}setReloadingPaused(t){this._a=t}resetFlagCallReported(){this.q(Cn)}Ha(t){this.La();var e=this.nn;if(e&&!this.Ne.remoteRequestsDisabled&&!this.Ma())if(this.ya)this.wa=!0;else{var n={token:e.projectToken,distinct_id:e.distinctId,groups:e.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:k({},e.initialPersonProperties,this.Oa(Dt)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(In),timezone:If()};C(e.deviceId)||(n.$device_id=e.deviceId),(t!=null&&t.disableFlags||this.Ne.featureFlagsDisabled)&&(n.disable_flags=!0);var i=this.Na();i.length&&(n.evaluation_contexts=i);var r=this.qa();C(r)||(n.flag_keys=r);var s=this.Ne.onlyEvaluateSurveyFeatureFlags,o="/flags/?v=2"+(s?"&only_evaluate_survey_feature_flags=true":""),a=this.ba;this.ya=!0;var l=()=>{this.wa&&(this.wa=!1,this.Ha())},u=c=>{this.ya=!1,a===this.ba&&(this.F({[Tr]:[mu]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:n,compression:this.Ne.compression==="base64"?je.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,f,h=(d=c.json)!==null&&d!==void 0?d:{},p=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),p||this.wa||(this.$anon_distinct_id=void 0),!n.disable_flags||this.wa){this.ka=!p;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?mu:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),h.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((f=h.quotaLimited)==null||!f.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[Tr]:g}),m?this.rt.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more."):n.disable_flags||this.ja(h,p,{partialResponse:s}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return vf(this.Sa,3)}Ua(t){this.Sa=_f(t,this.Sa,3,(()=>this.rt.warn("Feature flag requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped refreshing feature flags; will try again when connectivity changes.")))}getFeatureFlag(t,e){var n;if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var i=this.getFeatureFlagResult(t,e);return(n=i?.variant)!==null&&n!==void 0?n:i?.enabled}}else this.rt.warn('getFeatureFlag for key "'+t+Bo)}getFeatureFlagDetails(t){return this.getFlagsWithDetails()[t]}getFeatureFlagPayload(t){var e=this.getFeatureFlagResult(t,{send_event:!1});return e?.payload}getFeatureFlagResult(t,e){if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var n,i=this.getFlagVariants(),r=t in i,s=i[t],o=this.getFlagPayloads()[t],a=String(s),l=this.Oa(Pr)||void 0,u=this.Oa(ji)||void 0,c=this.Oa(Cn)||{};if(this.Ne.deduplicateCallsPerSession){var d,f=(d=this.nn)==null?void 0:d.session.sessionId,h=this.Oa(Li);f&&f!==h&&(c={},n=f)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))n&&this.F({[Cn]:c,[Li]:n});else{var p,g,m,v,S,b,_,x,I,T;U(c[t])?c[t].push(a):c[t]=[a],this.F(k({[Cn]:c},n?{[Li]:n}:{}));var E=this.getFeatureFlagDetails(t),P=[...(p=this.Oa(Tr))!==null&&p!==void 0?p:[]];C(s)&&P.push("flag_missing");var $={$feature_flag:t,$feature_flag_response:s,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((g=this.Ne.bootstrap)==null||(g=g.featureFlags)==null?void 0:g[t])||null,$feature_flag_bootstrapped_payload:((m=this.Ne.bootstrap)==null||(m=m.featureFlagPayloads)==null?void 0:m[t])||null,$used_bootstrap_value:!this.ka};C(E==null||(v=E.metadata)==null?void 0:v.has_experiment)||($.$feature_flag_has_experiment=E.metadata.has_experiment),C(E==null||(S=E.metadata)==null?void 0:S.version)||($.$feature_flag_version=E.metadata.version);var O,L=(b=E==null||(_=E.reason)==null?void 0:_.description)!==null&&b!==void 0?b:E==null||(x=E.reason)==null?void 0:x.code;L&&($.$feature_flag_reason=L),E!=null&&(I=E.metadata)!=null&&I.id&&($.$feature_flag_id=E.metadata.id),C(E?.original_variant)&&C(E?.original_enabled)||($.$feature_flag_original_response=C(E.original_variant)?E.original_enabled:E.original_variant),E!=null&&(T=E.metadata)!=null&&T.original_payload&&($.$feature_flag_original_payload=E==null||(O=E.metadata)==null?void 0:O.original_payload),P.length&&($.$feature_flag_error=P.join(",")),this.za($)}else n&&this.F({[Cn]:c,[Li]:n});if(r)return{key:t,enabled:!!s,variant:typeof s=="string"?s:void 0,payload:fc(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+Bo)}za(t){try{var e;(e=this.nn)==null||e.capture("$feature_flag_called",t).catch((n=>{this.rt.error("Failed to capture feature flag call",n)}))}catch(n){this.rt.error("Failed to capture feature flag call",n)}}getRemoteConfigPayload(t,e){this.Wa(t,e)}Wa(t,e){var n=this;return se((function*(){var i=n.nn;if(i){var r={distinct_id:i.distinctId,token:i.projectToken,person_properties:{$lib:i.library.name,$lib_version:i.library.version}},s=n.Na();s.length&&(r.evaluation_contexts=s);var o,a=n.qa();C(a)||(r.flag_keys=a);try{var l,u=(l=(yield i.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:r,compression:n.Ne.compression==="base64"?je.Base64:void 0,sentAt:"body",timeoutMs:n.Ne.requestTimeoutMs})).json)==null?void 0:l.featureFlagPayloads;o=u?.[t]||void 0}catch(c){return void n.rt.error("Remote config feature flag request failed",c)}try{e(o)}catch(c){n.rt.error("Remote config feature flag callback failed",c)}}}))()}isFeatureEnabled(t,e){if(e===void 0&&(e={}),e.fresh&&!this.ka)return e.defaultValue;if(!(this.ma||this.getFlags()&&this.getFlags().length>0))return this.rt.warn('isFeatureEnabled for key "'+t+Bo),e.defaultValue;var n=this.getFeatureFlag(t,e);return C(n)?e.defaultValue:!!n}addFeatureFlagsHandler(t){this.featureFlagEventHandlers.push(t)}removeFeatureFlagsHandler(t){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((e=>e!==t))}receivedFeatureFlags(t,e,n){this.ja(t,e,n)}ja(t,e,n){if(this.nn){this.ma=!0;var i=(function(r,s,o,a,l,u){s===void 0&&(s={}),o===void 0&&(o={}),a===void 0&&(a={}),u===void 0&&(u=gu);var c=((I,T)=>{var E=I.flags;return E?k({},I,{featureFlags:Object.fromEntries(Object.keys(E).map((P=>{var $;return[P,($=E[P].variant)!==null&&$!==void 0?$:E[P].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(E).filter((P=>E[P].enabled)).filter((P=>{var $;return($=E[P].metadata)==null?void 0:$.payload})).map((P=>{var $;return[P,($=E[P].metadata)==null?void 0:$.payload]})))}):(I.featureFlags&&T.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),I)})(r,u),d=c.flags,f=c.featureFlags,h=c.featureFlagPayloads;if(f){var p=r.requestId,g=r.evaluatedAt;if(U(f)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(f)for(var v=0;f.length>v;v++)m[f[v]]=!0;return{[Ti]:f,[Sn]:m,[Zr]:!1}}var S=f,b=h,_=d;if(l!=null&&l.partialResponse)S=k({},s,S),b=k({},o,b),_=k({},a,_);else if(r.errorsWhileComputingFlags)if(d){var x=new Set(Object.keys(d).filter((I=>{var T;return!((T=d[I])!=null&&T.failed)})));S=k({},s,Object.fromEntries(Object.entries(S).filter((I=>x.has(I[0]))))),b=k({},o,Object.fromEntries(Object.entries(b||{}).filter((I=>x.has(I[0]))))),_=k({},a,Object.fromEntries(Object.entries(_||{}).filter((I=>x.has(I[0])))))}else S=k({},s,S),b=k({},o,b),_=k({},a,_);return k({[Ti]:Object.keys(_u(S)),[Sn]:S||{},[$i]:b||{},[aa]:_||{},[Zr]:r.minimalFlagCalledEvents===!0},p?{[Pr]:p}:{},g?{[ji]:g}:{})}})(t,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),n,this.rt);i&&this.F(i),e||(this.xa=!1),this.Va(e)}}override(t,e){e===void 0&&(e=!1),this.rt.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:t,suppressWarning:e})}overrideFeatureFlags(t){this.Za(t)}Za(t){if(this.nn){if(t===!1)return this.q([xt,xn]),this.Va(),void bn.info("All overrides cleared");if(U(t))return this.F({[xt]:vu(t)}),this.Va(),void bn.info("Flag overrides set",{flags:t});if(t&&typeof t=="object"&&("flags"in t||"payloads"in t)){var e,n=t;this.ca=!!((e=n.suppressWarning)!==null&&e!==void 0&&e);var i={},r=n.flags,s=n.payloads;return r&&(i[xt]=U(r)?vu(r):r),s&&(i[xn]=s),Object.keys(i).length&&this.F(i),r===!1&&s===!1?this.q([xt,xn]):r===!1?this.q(xt):s===!1&&this.q(xn),this.Va(),r===!1?bn.info("Flag overrides cleared"):r&&bn.info("Flag overrides set",{flags:r}),void(s===!1?bn.info("Payload overrides cleared"):s&&bn.info("Payload overrides set",{payloads:s}))}if(t&&typeof t=="object")return this.F({[xt]:t}),this.Va(),void bn.info("Flag overrides set",{flags:t});this.rt.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:t})}else this.rt.warn("posthog.featureFlags.overrideFeatureFlags called before feature flags were ready")}onFeatureFlags(t){if(this.addFeatureFlagsHandler(t),this.ma){var e=this.Ga(),n=e.flags,i=e.flagVariants;try{t(n,i)}catch(r){this.rt.error("Error while running feature flags callback",r)}}return()=>this.removeFeatureFlagsHandler(t)}updateEarlyAccessFeatureEnrollment(t,e,n){var i=(this.Oa(Ar)||[]).find((l=>l.flagKey===t)),r={["$feature_enrollment/"+t]:e},s={$feature_flag:t,$feature_enrollment:e,$set:r};i&&(s.$early_access_feature_name=i.name),n&&(s.$feature_enrollment_stage=n);var o=k({},this.getFlagVariants(),{[t]:e});this.F({[Ti]:Object.keys(_u(o)),[Sn]:o,[Dt]:k({},this.Oa(Dt)||{},r)}),this.Va();try{var a;(a=this.nn)==null||a.capture("$feature_enrollment_update",s).catch((l=>{this.rt.error("Failed to capture early access feature enrollment",l)}))}catch(l){this.rt.error("Failed to capture early access feature enrollment",l)}}getEarlyAccessFeatures(t,e,n){e===void 0&&(e=!1);var i=this.Oa(Ar);!i||e?this.Qa(t,n):t(i)}Qa(t,e){var n=this;return se((function*(){var i=n.nn;if(i){var r,s=e?"&"+e.map((a=>"stage="+a)).join("&"):"";try{var o=yield i.sendRequest("/api/early_access_features/?token="+i.projectToken+s,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;n.F({[Ar]:r=o.json.earlyAccessFeatures})}catch(a){return void n.rt.error("Early access feature request failed",a)}try{t(r)}catch(a){n.rt.error("Early access feature callback failed",a)}}}))()}Ga(){var t=this.getFlags(),e=this.getFlagVariants();return{flags:t.filter((n=>e[n])),flagVariants:Object.keys(e).filter((n=>e[n])).reduce(((n,i)=>(n[i]=e[i],n)),{})}}Va(t){this.Fa();var e=this.Ga(),n=e.flags,i=e.flagVariants;this.featureFlagEventHandlers.forEach((r=>{try{r(n,i,{errorsLoading:t})}catch(s){this.rt.error("Error while running feature flags callback",s)}}))}setPersonPropertiesForFlags(t,e){e===void 0&&(e=!0),this.Ka(t,e)}Ka(t,e){e===void 0&&(e=!0);var n=this.Oa(Dt)||{},i=t?.$set||(t!=null&&t.$set_once?{}:t),r=t?.$set_once,s={};if(r)for(var o in r)({}).hasOwnProperty.call(r,o)&&(o in n||(s[o]=r[o]));this.F({[Dt]:k({},n,s,i)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=k({},this.Oa(Dt)||{});t.forEach((i=>{delete n[i]})),this.F({[Dt]:n}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(Dt),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=this.Oa(In)||{},i=k({},n);for(var r of Object.keys(t))i[r]=k({},n[r],t[r]);this.F({[In]:i}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(In)||{};this.F({[In]:k({},e,{[t]:{}})})}else this.q(In)}reset(){this.ba++,this.wa=!1,this.Fa(),this.ma=!1,this._a=!1,this.ka=!1,this.$anon_distinct_id=void 0,this.La(),this.ca=!1,this.Sa=0}}},Um={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===ki||this.Ya===Sr?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=lu,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(F==null||!F.visibilityState||F.visibilityState==="visible")return!0;var n=w==null||(e=w.performance)==null||e.getEntriesByType==null?void 0:e.getEntriesByType("visibility-state");return!(n!=null&&n.length)||n.some((i=>i.name==="visible"))})(),this.Ie=()=>{var e;F?.visibilityState==="visible"&&(this.io=!0,(e=this.Ja)==null||e.setDocumentWasEverVisible==null||e.setDocumentWasEverVisible(!0))},this._instance=t,!this._instance.sessionManager)throw Ot.error("started without valid sessionManager"),new Error(Ia+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===Ht)throw new Error(Ia+' cannot be used with cookieless_mode="always"');F!=null&&F.addEventListener&&ve(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(An))==null||!t.enabled),n=!this.Ne.disable_session_recording,i=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return w&&e&&n&&!i}startIfEnabledOrStop(t){var e;if(!(this.eo||this.ro&&(e=this.Ja)!=null&&e.isStarted)){var n=!C(Object.assign)&&!C(Array.from);this.ro&&n?(this.no(t),Ot.info("starting")):(this.Ya=lu,this.stopRecording())}}no(t){var e,n,i;this.ro&&(this.Ya!==ki&&this.Ya!==Sr&&(this.Ya=cu),B!=null&&(e=B.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(n=B.__PosthogExtensions__)!=null&&n.initSessionRecording?this.so(t):(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,this.ao,(r=>{if(r)return Ot.error("could not load recorder",r);this.so(t)})))}stopRecording(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.stop()}oo(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.discard()}lo(){var t,e;(t=this.Mr)==null||t.unregister(ol),(e=this.Mr)==null||e.unregister(Vd)}uo(t,e){if(H(t))return null;var n,i=ke(t)?t:parseFloat(t);return typeof(n=i)!="number"||!Number.isFinite(n)||0>n||n>1?(Ot.warn(e+" must be between 0 and 1. Ignoring invalid value:",t),null):i}ho(t){if(this.Mr){var e,n,i=this.Mr,r=()=>{var s,o=t.sessionRecording===!1?void 0:t.sessionRecording,a=this.uo((s=this.Ne.session_recording)==null?void 0:s.sampleRate,"session_recording.sampleRate"),l=this.uo(o?.sampleRate,"remote config sampleRate"),u=a??l;H(u)&&this.lo();var c=o?.minimumDurationMilliseconds;i.register({[An]:k({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:k({capturePerformance:t.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:u,minimumDurationMilliseconds:C(c)?null:c,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers,version:o?.version,triggerGroups:o?.triggerGroups})})};r(),(e=this.Xa)==null||e.call(this),this.Xa=(n=this._instance.sessionManager)==null?void 0:n.onSessionId(r)}}onRemoteConfig(t){var e=t.ok?t.config:void 0;return e&&"sessionRecording"in e?e.sessionRecording===!1?(this.ho(e),void this.oo()):(this.ho(e),void this.startIfEnabledOrStop()):(this.Ya===ki&&(this.Ya=Sr,Ot.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(t,e){var n;e===void 0&&(e="log"),(n=this.Ja)!=null&&n.log?this.Ja.log(t,e):Ot.warn("log called before recorder was ready")}get ao(){var t,e,n=(t=this._instance)==null||(t=t.persistence)==null?void 0:t.get_property(An);return(n==null||(e=n.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(An);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(n){return Ot.warn("persisted remote config for session recording is invalid and will be ignored",n),!1}return!H(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,n,i;if(!this.eo){if((e=B.__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({[ef]:!0});var r;if(this.Ja||(this.Ja=(r=B.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===Sr||this.Ya===ki?void 0:(this.Ya=ki,Ot.info("persisted remote config is stale, requesting fresh config before starting"),void new kf(this._instance).load());this.Ya=cu,(n=(i=this.Ja).setDocumentWasEverVisible)==null||n.call(i,this.io),this.Ja.start(t)}}onRRwebEmit(t){var e;(e=this.Ja)==null||e.onRRwebEmit==null||e.onRRwebEmit(t)}overrideLinkedFlag(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Kd]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Gd]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,n;this.Ja||(n=this.Mr)==null||n.register({[t==="url"?Yd:Jd]:!0}),(e=this.Ja)==null||e.overrideTrigger(t)}get sdkDebugProperties(){var t;return((t=this.Ja)==null?void 0:t.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(t,e){var n;return!((n=this.Ja)==null||!n.tryAddCustomEvent(t,e))}}},Hm={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new su(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,n=he(this.instance.config.autocapture)?this.instance.config.autocapture:{};return n.url_allowlist=(t=n.url_allowlist)==null?void 0:t.map((i=>new RegExp(i))),n.url_ignorelist=(e=n.url_ignorelist)==null?void 0:e.map((i=>new RegExp(i))),n}yo(){if(this.isBrowserSupported()){if(w&&F){var t=n=>{n=n||w?.event;try{this.bo(n)}catch(i){Mo.error("Failed to capture event",i)}};if(ve(F,"submit",t,{capture:!0}),ve(F,"change",t,{capture:!0}),ve(F,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=n=>{n=n||w?.event;try{this.bo(n,$o)}catch(i){Mo.error("Failed to capture copy/cut event",i)}};ve(F,"copy",e,{capture:!0}),ve(F,"cut",e,{capture:!0})}}}else Mo.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.vo&&(this.yo(),this.vo=!0)}onRemoteConfig(t){if(this.fo=!0,t.ok){var e=t.config;e.elementsChainAsString&&(this.po=e.elementsChainAsString);var n=e.autocapture_opt_out;gt(n)&&(this.instance.persistence&&this.instance.persistence.register({[ea]:n}),this.co=n),this.startIfEnabled()}else this.startIfEnabled()}setElementSelectors(t){this.mo=t}getElementSelectors(t){var e,n=[];return(e=this.mo)==null||e.forEach((i=>{var r=F?.querySelectorAll(i);r?.forEach((s=>{t===s&&n.push(i)}))})),n}get isEnabled(){var t,e,n=(t=this.instance.persistence)==null?void 0:t.props[ea],i=this.co,r=this.instance.Qi()&&!this.fo;if(Ke(i)&&!gt(n)&&!r)return!1;var s=(e=this.co)!==null&&e!==void 0?e:!!n;return!!this.instance.config.autocapture&&!s}bo(t,e){if(e===void 0&&(e="$autocapture"),this.isEnabled){var n,i=bo(t);of(i)&&(i=i.parentNode||null),e==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&this.instance.config.rageclick&&(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,t.timeStamp||new Date().getTime())&&Lc(i,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var r=e===$o;if(i&&(function(d,f,h,p,g,m){var v;if(!w||dl(d)||h!=null&&h.url_allowlist&&!Tc(h.url_allowlist,m)||h!=null&&h.url_ignorelist&&Tc(h.url_ignorelist,m))return!1;if(h!=null&&h.dom_event_allowlist){var S=h.dom_event_allowlist;if(S&&!S.some((E=>f.type===E)))return!1}var b=ff(d,p),_=b.parentIsUsefulElement,x=b.targetElementList;if(!(function(E,P){var $=P?.element_allowlist;if(C($))return!0;var O,L=function(K){if($.some((V=>K.tagName.toLowerCase()===V)))return{v:!0}};for(var N of E)if(O=L(N))return O.v;return!1})(x,h)||!ma(x,h?.css_selector_allowlist)||ma(x,(v=h?.css_selector_ignorelist)!==null&&v!==void 0?v:Dg))return!1;try{var I=w.getComputedStyle(d);if(I&&I.getPropertyValue("cursor")==="pointer"&&f.type==="click")return!0}catch{}var T=d.tagName.toLowerCase();switch(T){case"html":return!1;case"form":return(g||["submit"]).indexOf(f.type)>=0;case"input":case"select":case"textarea":return(g||["change","click"]).indexOf(f.type)>=0;default:return _?(g||["click"]).indexOf(f.type)>=0:(g||["click"]).indexOf(f.type)>=0&&(ul.indexOf(T)>-1||d.getAttribute("contenteditable")==="true")}})(i,t,this.Ne,r,r?["copy","cut"]:void 0,this.instance)){var s=Rm(i,{e:t,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.Ne.element_attribute_ignorelist,elementsChainAsString:this.po,disableCaptureUrlHashes:this.instance.config.disable_capture_url_hashes}),o=s.props;if(s.explicitNoCapture)return!1;var a=this.getElementSelectors(i);if(a&&a.length>0&&(o.$element_selectors=a),e===$o){var l,u=cf(w==null||(l=w.getSelection())==null?void 0:l.toString()),c=t.type||"clipboard";if(!u)return!1;o.$selected_content=u,o.$copy_type=c}return this.instance.capture(e,o),!0}}}isBrowserSupported(){return De(F?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(w==null||(e=w.location)==null?void 0:e.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(A.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.wo&&this.wo(),this.wo=void 0,A.info("History API monitoring stopped")}monitorHistoryChanges(){w&&w.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(w&&((e=w.history[t])==null||!e.__posthog_wrapped__)){var n=this;(function(i,r,s){try{if(!(r in i))return ou;var o={next:i[r]},a=s((function(){for(var l=arguments.length,u=new Array(l),c=0;l>c;c++)u[c]=arguments[c];return o.next.apply(this,u)}));return De(a)&&(a.prototype=a.prototype||{},Object.defineProperties(a,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:o}})),i[r]=a,()=>{if(i[r]!==a)for(var l=i[r];De(l)&&l.__posthog_layer__;){var u=l.__posthog_layer__;if(u.next===a)return void(u.next=o.next);l=u.next}else i[r]=o.next}}catch{return ou}})(w.history,t,(i=>function(r,s,o){i.call(this,r,s,o),n.So(t)}))}}So(t){try{var e,n=w==null||(e=w.location)==null?void 0:e.pathname;if(!n)return;n!==this._o&&this.isEnabled&&this._instance.capture(Vn,{navigation_type:t}),this._o=n}catch(i){A.error("Error capturing "+t+" pageview",i)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};ve(w,"popstate",t),this.wo=()=>{w&&w.removeEventListener("popstate",t)}}}},heatmaps:class{get Ne(){return this.instance.config}constructor(t){var e;this.Co=!1,this.vo=!1,this.Mo=null,this.instance=t,this.Co=!((e=this.instance.persistence)==null||!e.props[ta]),this.rageclicks=new su(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return he(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return H(this.Ne.capture_heatmaps)?H(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;$m.info("starting..."),this.To(),this.Ie()}else{var t;clearInterval((t=this.Mo)!==null&&t!==void 0?t:void 0),this.Eo(),this.getAndClearBuffer()}}onRemoteConfig(t){if(t.ok){var e=t.config;if("heatmaps"in e){var n=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[ta]:n}),this.Co=n,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){No(t.originalEvent)&&this.ke(t.originalEvent,"deadclick")}Ie(){this.Mo&&clearInterval(this.Mo),this.Mo=F?.visibilityState==="visible"?setInterval(this.cr.bind(this),this.flushIntervalMilliseconds):null}To(){w&&F&&(this.Po=this.cr.bind(this),ve(w,ns,this.Po),this.Ro=t=>this.ke(t||w?.event),ve(F,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||w?.event),ve(F,"mousemove",this.Ao,{capture:!0}),this.Lo=new Hc(this.instance,Vg,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),ve(F,ts,this.Oo),this.vo=!0)}Eo(){var t;w&&F&&(this.Po&&w.removeEventListener(ns,this.Po),this.Ro&&F.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&F.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&F.removeEventListener(ts,this.Oo),clearTimeout(this.Do),(t=this.Lo)==null||t.stop(),this.vo=!1)}$o(t,e){var n=this.instance.scrollManager.scrollY(),i=this.instance.scrollManager.scrollX(),r=this.instance.scrollManager.scrollElement(),s=(function(o,a,l){for(var u=o;u&&hn(u)&&!Qe(u,"body");){if(u===l)return!1;var c=void 0;try{var d,f,h;c=(d=(f=(h=u.ownerDocument)==null?void 0:h.defaultView)!==null&&f!==void 0?f:w)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(j(a,c))return!0;u=uf(u)}return!1})(bo(t),["fixed","sticky"],r);return{x:t.clientX+(s?0:i),y:t.clientY+(s?0:n),target_fixed:s,type:e}}ke(t,e){var n;if(e===void 0&&(e="click"),!Rc(t.target)&&No(t)){var i=this.$o(t,e);(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,new Date().getTime())&&Lc(bo(t),this.instance.config.rageclick)&&this.Vt(k({},i,{type:"rageclick"})),this.Vt(i)}}Fo(t){!Rc(t.target)&&No(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(w){var e=this.Ne.disable_capture_url_hashes?fn(w.location.href):w.location.href,n=this.Ne.custom_personal_data_properties,i=this.Ne.mask_personal_data_properties?[...ri,...n||[]]:[],r=Zi(e,i,Xi);this.R=this.R||{},this.R[r]||(this.R[r]=[]),this.R[r].push(t)}}cr(){this.R&&!Gt(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:Hc,webVitalsAutocapture:class{constructor(t){var e;this.Co=!1,this.vo=!1,this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this.No=()=>{clearTimeout(this.qo),this.qo=void 0,this.R.metrics.length!==0&&(this._instance.capture("$web_vitals",k({$current_url:this.R.url},this.R.metrics.reduce(((n,i)=>k({},n,{["$web_vitals_"+i.name+"_event"]:k({},i),["$web_vitals_"+i.name+"_value"]:i.value})),{}))),this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.jo=n=>{var i;if(this.R=this.R||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},H(n?.name)||H(n?.value))wn.error("Invalid metric received",n);else{var r=typeof n.navigationURL=="string"?n.navigationURL:void 0,s=this.Bo(r);if(!C(s)){var o=ke(n.navigationId)||typeof n.navigationId=="string"?"navigation:"+n.navigationId:"url:"+s;if(!this.Ho||this.Ho>n.value){this.R.navigationKey!==o&&(this.No(),this.qo=setTimeout(this.No,this.flushToCaptureTimeoutMs)),C(this.R.navigationKey)&&(this.R.navigationKey=o,this.R.url=s),this.R.firstMetricTimestamp=C(this.R.firstMetricTimestamp)?Date.now():this.R.firstMetricTimestamp,n.attribution&&n.attribution.interactionTargetElement&&(n.attribution.interactionTargetElement=void 0);var a=(i=this._instance.sessionManager)==null?void 0:i.checkAndGetSessionAndWindowId(!0),l=k({},n,r?{navigationURL:s}:{},{$current_url:s,timestamp:Date.now()});C(a)||(l.$session_id=a.sessionId,l.$window_id=a.windowId),this.R.metrics.push(l),this.R.metrics.length===this.allowedMetrics.length&&this.No()}else wn.error("Ignoring metric with value >= "+this.Ho,n)}}},this.Uo=()=>{if(!this.vo){var n,i,r,s,o=B.__PosthogExtensions__,a=o?.postHogWebVitalsCallbacksByFlavor,l=a?.[this.zo]||(this.zo==="web-vitals"&&C(a)?o?.postHogWebVitalsCallbacks:void 0);if(C(l)||(n=l.onLCP,i=l.onCLS,r=l.onFCP,s=l.onINP),n&&i&&r&&s){var u={reportSoftNavs:this.useSoftNavs};this.allowedMetrics.indexOf("LCP")>-1&&n(this.jo.bind(this),u),this.allowedMetrics.indexOf("CLS")>-1&&i(this.jo.bind(this),u),this.allowedMetrics.indexOf("FCP")>-1&&r(this.jo.bind(this),u),this.allowedMetrics.indexOf("INP")>-1&&s(this.jo.bind(this),u),this.vo=!0}else wn.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[sa]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,n=he(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return H(n)?((e=this._instance.persistence)==null?void 0:e.props[oa])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(he(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=he(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=he(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=he(this.Wo)&&ke(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:au;return t>0&&6e4>=t?au:t}get isEnabled(){var t=me?.protocol;if(t!=="http:"&&t!=="https:")return wn.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=he(this.Wo)?this.Wo.web_vitals:gt(this.Wo)?this.Wo:void 0;return gt(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(wn.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var n=he(e.capturePerformance)&&!!e.capturePerformance.web_vitals,i=he(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[sa]:n}),this._instance.persistence.register({[oa]:i})),this.Co=n,this.startIfEnabled()}}}get zo(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}ai(t){var e=B.__PosthogExtensions__,n=this.zo,i=e?.postHogWebVitalsCallbacksByFlavor;i!=null&&i[n]||n==="web-vitals"&&C(i)&&e!=null&&e.postHogWebVitalsCallbacks?t():e==null||e.loadExternalDependency==null||e.loadExternalDependency(this._instance,n,(r=>{r?wn.error("failed to load script",r):t()}))}Bo(t){var e=t||w?.location.href;if(e){var n=this._instance.config.disable_capture_url_hashes?fn(e):e,i=this._instance.config.custom_personal_data_properties,r=this._instance.config.mask_personal_data_properties?[...ri,...i||[]]:[];return Zi(n,r,Xi)}wn.error("Could not determine current URL")}}},Wm={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var n;if(w&&this.isEnabled&&(n=B.__PosthogExtensions__)!=null&&n.errorWrappingFunctions){var i=B.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,r=B.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,s=B.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.Vo&&this.Ne.capture_unhandled_errors&&(this.Vo=i(this.captureException.bind(this))),!this.Zo&&this.Ne.capture_unhandled_rejections&&(this.Zo=r(this.captureException.bind(this))),!this.Go&&this.Ne.capture_console_errors&&(this.Go=s(this.captureException.bind(this)))}catch(o){Ii.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[na]),this.Jo=new Up(k({},(function(n){var i,r,s,o;return n===void 0&&(n={}),{refillRate:(i=(r=n.exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:n.__exceptionRateLimiterRefillRate)!==null&&i!==void 0?i:1,bucketSize:(s=(o=n.exceptionRateLimiterBucketSize)!==null&&o!==void 0?o:n.__exceptionRateLimiterBucketSize)!==null&&s!==void 0?s:10}})(this._instance.config.error_tracking),{refillInterval:1e4,rt:Ii})),this.Ne=this.Yo(),this.startIfEnabledOrStop()}Yo(){var t=this._instance.config.capture_exceptions,e={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return he(t)?e=k({},e,t):(C(t)?this.Ko:t)&&(e=k({},e,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),e}get isEnabled(){return this.Ne.capture_console_errors||this.Ne.capture_unhandled_errors||this.Ne.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(Ii.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",(i=>{if(i)return Ii.error("failed to load script",i);t()}))}Qo(){var t,e,n;(t=this.Vo)==null||t.call(this),this.Vo=void 0,(e=this.Zo)==null||e.call(this),this.Zo=void 0,(n=this.Go)==null||n.call(this),this.Go=void 0}onRemoteConfig(t){if(t.ok){var e=t.config;"autocaptureExceptions"in e&&(this.Ko=!!e.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[na]:this.Ko}),this.Ne=this.Yo(),this.startIfEnabledOrStop())}}onConfigChange(){this.Ne=this.Yo()}captureException(t){var e,n,i,r=(e=t==null||(n=t.$exception_list)==null||(n=n[0])==null?void 0:n.type)!==null&&e!==void 0?e:"Exception";this.Jo.consumeRateLimit(r)?Ii.info("Skipping exception capture because of client rate limiting.",{exception:r}):(i=this._instance.exceptions)==null||i.sendExceptionEvent(t)}},exceptions:class{constructor(t){var e,n;this.Xo=[],this.tl=new rg([new fg,new bg,new pg,new hg,new yg,new _g,new mg,new wg],(function(i){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;r>o;o++)s[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` -`),d=l;c.length>d;d++){var f=c[d];if(1024>=f.length){var h=Cc.test(f)?f.replace(Cc,"$1"):f;if(!h.match(/\S*Error: /)){for(var p of s){var g=p(h,i);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var v=Array.from(m);return v.reverse(),v.slice(0,50).map((S=>{return k({},S,{filename:S.filename||(b=v,b[b.length-1]||{}).filename,function:S.function||ni});var b}))})(u)}})("web:javascript",lg,dg)),this._instance=t,this.Xo=(e=(n=this._instance.persistence)==null?void 0:n.get_property(ia))!==null&&e!==void 0?e:[],this.el=Jr(this.il()),this.rl=new Sg(this.el)}onConfigChange(){this.el=Jr(this.il()),this.rl.setConfig(this.el)}onRemoteConfig(t){var e,n,i;if(t.ok){var r=t.config;if("errorTracking"in r){var s=(e=(n=r.errorTracking)==null?void 0:n.suppressionRules)!==null&&e!==void 0?e:[],o=(i=r.errorTracking)==null?void 0:i.captureExtensionExceptions;this.Xo=s,this._instance.persistence&&this._instance.persistence.register({[ia]:this.Xo,[ra]:o})}}}get nl(){var t,e=!!this._instance.get_property(ra),n=this._instance.config.error_tracking.captureExtensionExceptions;return(t=n??e)!==null&&t!==void 0&&t}buildProperties(t,e){return this.tl.buildFromUnknown(t,{syntheticException:e?.syntheticException,mechanism:{handled:e?.handled}})}addExceptionStep(t,e){if(this.el.enabled)try{if(!X(t)||t.trim().length===0)return void Et.warn("Ignoring exception step because message must be a non-empty string");var n=(function(s){if(!s)return{sanitizedProperties:{},droppedKeys:[]};var o=[];return{sanitizedProperties:Object.keys(s).reduce(((a,l)=>Eg.has(l)?(o.push(l),a):(a[l]=s[l],a)),{}),droppedKeys:o}})(this.sl(e)),i=n.sanitizedProperties,r=n.droppedKeys;r.length>0&&Et.warn("Ignoring reserved exception step fields",{droppedKeys:r}),this.rl.add(k({[Kr]:t,[Yr]:new Date().toISOString()},i))}catch(s){Et.error("Failed to add exception step. Ignoring breadcrumb.",s)}}sendExceptionEvent(t){try{var e=t.$exception_list;if(this.al(e)){if(this.ol(e))return this.ll("Exception dropped: matched a suppression rule"),void Et.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 Et.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 Et.info("Skipping exception capture because it was thrown by the PostHog SDK")}var n=this.el.enabled&&H(t.$exception_steps)?this.dl(t):t,i=typeof(s=globalThis._posthogReleaseId)=="string"&&s.length>0?s:void 0;i&&(n.$release_id=i);try{var r=this._instance.capture("$exception",n,{_noTruncate:!0,_batchKey:"exceptionEvent",Wn:!0});return r&&this.rl.clear(),r}catch(o){return Et.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void Et.error("Failed to process exception event. Ignoring this exception.",o)}var s}dl(t){try{var e=this.rl.getAttachable();return e.length===0?t:k({},t,{$exception_steps:e})}catch(n){return Et.error("Failed to read buffered exception steps. Capturing exception without steps.",n),t}}ll(t){this.el.enabled&&this.rl.add({[Kr]:t,[Yr]:new Date().toISOString()})}sl(t){return he(t)?k({},t):{}}il(){var t,e;return(t=(e=this._instance.config.error_tracking)==null?void 0:e.exception_steps)!==null&&t!==void 0?t:{}}ol(t){if(t.length===0)return!1;try{var e=t.reduce(((n,i)=>{var r=i.type,s=i.value;return X(r)&&r.length>0&&n.$exception_types.push(r),X(s)&&s.length>0&&n.$exception_values.push(s),n}),{$exception_types:[],$exception_values:[]});return this.Xo.some((n=>{var i=n.values.map((r=>{var s=jf[r.operator],o=e[r.key];if(!s||!o)return!1;var a=U(r.value)?r.value:[r.value];return a.length>0&&s(a,o)}));return n.type==="OR"?i.some(Boolean):i.every(Boolean)}))}catch(n){return Et.warn("Failed to evaluate suppression rules. Capturing the exception.",n),!1}}ul(t){return t.flatMap((e=>{var n,i;return(n=(i=e.stacktrace)==null?void 0:i.frames)!==null&&n!==void 0?n:[]})).some((e=>e.filename&&e.filename.startsWith("chrome-extension://")))}hl(t){if(t.length>0){var e,n,i,r,s=(e=(n=t[0].stacktrace)==null?void 0:n.frames)!==null&&e!==void 0?e:[],o=s[s.length-1];return(i=o==null||(r=o.filename)==null?void 0:r.includes("posthog.com/static"))!==null&&i!==void 0&&i}return!1}al(t){return!H(t)&&U(t)}}},qm=k({productTours:class{get Mr(){return this._instance.persistence}constructor(t){this.vl=null,this.cl=null,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(t.ok){var e=t.config;if("productTours"in e){var n,i;if(this.Mr&&this.Mr.register({[sl]:!!e.productTours}),!Oo(this._instance))return!this.vl&&H((n=this.Mr)==null?void 0:n.props[Mi])||xr.info("product tours disabled; stopping and clearing cached tours"),(i=this.vl)==null||i.stop(),this.vl=null,void this.clearCache();this.loadIfEnabled()}}}loadIfEnabled(){!this.vl&&Oo(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.generateProductTours?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",(i=>{i?xr.error("Could not load product tours script",i):t()}))}fl(){var t;!this.vl&&(t=B.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=B.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(t,e){if(e===void 0&&(e=!1),!U(this.cl)||e){var n=this.Mr;if(n){var i=n.props[Mi];if(U(i)&&!e)return this.cl=i,void t(i,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",timestampMode:"query",callback:r=>{if(Oo(this._instance)){var s=r.statusCode;if(s!==200||!r.json){var o="Product Tours API could not be loaded, status: "+s;return s===0?r.error||xr.warn(o):xr.error(o),void t([],{isLoaded:!1,error:o})}var a=U(r.json.product_tours)?r.json.product_tours:[];this.cl=a,n&&n.register({[Mi]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){H(this.vl)?t([],{isLoaded:!1,error:"Product tours not loaded"}):this.vl.getActiveProductTours(t)}showProductTour(t){var e;(e=this.vl)==null||e.showTourById(t)}previewTour(t){this.vl?this.vl.previewTour(t):this.ai((()=>{var e;this.fl(),(e=this.vl)==null||e.previewTour(t)}))}dismissProductTour(){var t;(t=this.vl)==null||t.dismissTour("user_clicked_skip")}nextStep(){var t;(t=this.vl)==null||t.nextStep()}previousStep(){var t;(t=this.vl)==null||t.previousStep()}clearCache(){var t;this.cl=null,(t=this.Mr)==null||t.unregister(Mi)}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)}}},Cs),zm={siteApps:class{constructor(t){this.pl=0,this._instance=t,this.gl=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}ml(t,e){if(e){var n=this.globalsForEvent(e);this.gl.push(n),this.gl.length>1e3&&(this.gl=this.gl.slice(10))}}get siteAppLoaders(){var t;return(t=B._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,n,i,r,s,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var f=d[0];l[f]={id:u[f],type:f,properties:d[1]}}var h=t.$set_once,p=t.$set;return{event:k({},ud(t,Mm),{properties:k({},t.properties,p?{$set:k({},(e=(n=t.properties)==null?void 0:n.$set)!==null&&e!==void 0?e:{},p)}:{},h?{$set_once:k({},(i=(r=t.properties)==null?void 0:r.$set_once)!==null&&i!==void 0?i:{},h)}:{}),elements_chain:(s=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&s!==void 0?s:"",distinct_id:(a=t.properties)==null?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}bl(t){var e,n=(e=t.tagName)==null?void 0:e.toLowerCase();return n==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(bt.error("prepare_external_dependency_stylesheet returned null"),null):n==="script"&&this._instance.config.prepare_external_dependency_script?this._instance.config.prepare_external_dependency_script(t)||(bt.error("prepare_external_dependency_script returned null"),null):t}_l(){var t,e,n,i,r,s,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=F?.defaultView,u=l==null||(t=l.Node)==null?void 0:t.prototype;if(!l||!u)return()=>{};if(this.pl++,this.wl)return this.kl();var c=[],d=this,f=new WeakSet,h=(m,v,S)=>{if(m!=null&&m[v]){var b=m[v];m[v]=S(b),c.push((()=>{m[v]=b}))}},p=m=>{if(f.has(m))return m;var v=d.bl(m);return v&&f.add(v),v},g=m=>m.map((v=>typeof v=="string"?v:p(v))).filter((v=>!Ke(v)));return h(u,"appendChild",(m=>function(v){var S=p(v);return S?m.call(this,S):v})),h(u,"insertBefore",(m=>function(v,S){var b=p(v);return b?m.call(this,b,S):v})),h(u,"replaceChild",(m=>function(v,S){var b=p(v);return b?m.call(this,b,S):S})),[(e=l.Element)==null?void 0:e.prototype,(n=l.Document)==null?void 0:n.prototype,(i=l.DocumentFragment)==null?void 0:i.prototype].forEach((m=>{h(m,"append",(v=>function(){for(var S=arguments.length,b=new Array(S),_=0;S>_;_++)b[_]=arguments[_];return v.apply(this,g(b))})),h(m,"prepend",(v=>function(){for(var S=arguments.length,b=new Array(S),_=0;S>_;_++)b[_]=arguments[_];return v.apply(this,g(b))}))})),[(r=l.Element)==null?void 0:r.prototype,(s=l.CharacterData)==null?void 0:s.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((m=>{h(m,"before",(v=>function(){for(var S=arguments.length,b=new Array(S),_=0;S>_;_++)b[_]=arguments[_];return v.apply(this,g(b))})),h(m,"after",(v=>function(){for(var S=arguments.length,b=new Array(S),_=0;S>_;_++)b[_]=arguments[_];return v.apply(this,g(b))})),h(m,"replaceWith",(v=>function(){for(var S=arguments.length,b=new Array(S),_=0;S>_;_++)b[_]=arguments[_];var x=g(b);return b.length&&!x.length?void 0:v.apply(this,x)}))})),h((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(v,S){var b=p(S);return b?m.call(this,v,b):null})),this.wl=()=>{c.forEach((m=>m())),this.wl=void 0},this.kl()}kl(){var t=!1;return()=>{var e;t||(t=!0,this.pl--,this.pl===0&&((e=this.wl)==null||e.call(this)))}}xl(t,e){e===void 0&&(e=!0);var n=this._l();try{var i=t(n);return e&&n(),i}catch(r){throw n(),r}}setupSiteApp(t){var e=this.apps[t.id],n=()=>{var o;!e.errored&&this.gl.length&&(bt.info("Processing "+this.gl.length+" events for site app with id "+t.id),this.gl.forEach((a=>this.xl((()=>e.processEvent==null?void 0:e.processEvent(a))))),e.processedBuffer=!0),Object.values(this.apps).every((a=>a.processedBuffer||a.errored))&&((o=this.yl)==null||o.call(this))},i=!1,r=o=>{e.errored=!o,e.loaded=!0,bt.info("Site app with id "+t.id+" "+(o?"loaded":"errored")),i&&n()};try{var s=this.xl((o=>t.init({posthog:this._instance,callback(a){o(),r(a)}})),!1).processEvent;s&&(e.processEvent=s),i=!0}catch(o){bt.error(uu+t.id,o),r(!1)}if(i&&e.loaded)try{n()}catch(o){bt.error("Error while processing buffered events PostHog app with config id "+t.id,o),e.errored=!0}}Sl(){var t=this.siteAppLoaders||[];for(var e of t)this.apps[e.id]={id:e.id,loaded:!1,errored:!1,processedBuffer:!1};for(var n of t)this.setupSiteApp(n)}Cl(t){var e=this;if(Object.keys(this.apps).length!==0){var n=this.globalsForEvent(t),i=function(s){try{e.xl((()=>s.processEvent==null?void 0:s.processEvent(n)))}catch(o){bt.error("Error while processing event "+t.event+" for site app "+s.id,o)}};for(var r of Object.values(this.apps))i(r)}}onRemoteConfig(t){var e,n,i,r=this;if((e=this.siteAppLoaders)!=null&&e.length)return this.isEnabled?(this.Sl(),void this._instance.on("eventCaptured",(l=>this.Cl(l)))):void bt.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((n=this.yl)==null||n.call(this),t.ok){var s=t.config;if((i=s.siteApps)!=null&&i.length)if(this.isEnabled){var o=function(){var l,u=a.id,c=a.url;B["__$$ph_site_app_"+u]=r._instance,(l=B.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(r._instance,c,(d=>{if(d)return bt.error(uu+u,d)}))};for(var a of s.siteApps)o()}else bt.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},Vm={tracingHeaders:class{constructor(t){this.Ml=void 0,this.Tl=void 0,this.El=void 0,this.Uo=()=>{var e,n,i=this.Il();i?(C(this.Ml)&&(this.Ml=(e=B.__PosthogExtensions__)==null||(e=e.tracingHeadersPatchFns)==null?void 0:e._patchXHR(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager)),C(this.Tl)&&(this.Tl=(n=B.__PosthogExtensions__)==null||(n=n.tracingHeadersPatchFns)==null?void 0:n._patchFetch(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager))):this.Qo()},this._instance=t}initialize(){this.startIfEnabledOrStop()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",(i=>{if(i)return Tm.error("failed to load script",i);t()}))}Pl(){var t,e;return(t=(e=this._instance.config.tracing_headers)!==null&&e!==void 0?e:this._instance.config.addTracingHeaders)!==null&&t!==void 0?t:this._instance.config.__add_tracing_headers}Il(){var t=this.Pl();return U(t)?(U(this.El)?this.El.splice(0,this.El.length,...t):this.El=[...t],t.length>0?this.El:void 0):(U(this.El)&&this.El.splice(0),this.El=t||void 0,this.El)}Qo(){var t,e;(t=this.Ml)==null||t.call(this),(e=this.Tl)==null||e.call(this),this.Ml=void 0,this.Tl=void 0}startIfEnabledOrStop(){this.Il()?this.ai(this.Uo):this.Qo()}}},Gm=k({surveys:class{get Ne(){return this._instance.config}constructor(t){this.Rl=void 0,this._surveyManager=null,this.Al=!1,this.Fl=[],this.Ll=null,this.Ol=null,this._instance=t,this._surveyEventReceiver=null}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this.Ne.disable_surveys){if(!t.ok)return Q.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(H(e))return Q.warn("Flags not loaded yet. Not loading surveys.");var n=U(e);this.Rl=n?e.length>0:e,Q.info("flags response received, isSurveysEnabled: "+this.Rl),this.loadIfEnabled()}}reset(){try{var t;(t=this._surveyEventReceiver)==null||t.reset(),localStorage.removeItem("lastSeenSurveyDate");for(var e=[],n=0;nlocalStorage.removeItem(r)))}catch{}}loadIfEnabled(){if(!this._surveyManager)if(this.Al)Q.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)Q.info(du);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())Q.info("Not loading surveys in cookieless mode without consent.");else{var t=B?.__PosthogExtensions__;if(t){if(!C(this.Rl)||this.Ne.advanced_enable_surveys){var e=this.Rl||this.Ne.advanced_enable_surveys;this.Al=!0;try{var n=t.generateSurveys;if(n)return void this.Dl(n,e);var i=t.loadExternalDependency;if(!i)return void this.$l(al);i(this._instance,"surveys",(r=>{r||!t.generateSurveys?this.$l("Could not load surveys script",r):this.Dl(t.generateSurveys,e)}))}catch(r){throw this.$l("Error initializing surveys",r),r}finally{this.Al=!1}}}else Q.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new Om(this._instance),Q.info("Surveys loaded successfully"),this.Nl({isLoaded:!0})}$l(t,e){Q.error(t,e),this.Nl({isLoaded:!1,error:t})}onSurveysLoaded(t){return this.Fl.push(t),this._surveyManager&&this.Nl({isLoaded:!0}),()=>{this.Fl=this.Fl.filter((e=>e!==t))}}getSurveys(t,e){if(e===void 0&&(e=!1),this.Ne.disable_surveys)return Q.info(du),t([]);var n,i=this._instance.get_property(la);if(i&&!e)return t(i,{isLoaded:!0}),void(this.ql()&&this.getSurveys((()=>{}),!0));typeof Promise<"u"&&this.Ll?this.Ll.then((r=>t(r.surveys,r.context))):(typeof Promise<"u"&&(this.Ll=new Promise((r=>{n=r}))),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this.Ne.token),method:"GET",timestampMode:"query",timeout:this.Ne.surveys_request_timeout_ms,callback:r=>{var s;this.Ll=null;var o=r.statusCode;if(o!==200||!r.json){var a="Surveys API could not be loaded, status: "+o;o!==0?Q.error(a):r.error||Q.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(n==null||n({surveys:[],context:l}))}this.Ol=null;var u,c=r.json.surveys||[],d=c.filter((h=>(function(p){return!(!p.start_date||p.end_date)})(h)&&(Hf(h)||(function(p){var g;return!((g=p.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(h))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(s=this._instance.persistence)==null||s.register({[la]:c,[Xr]:Date.now()});var f={isLoaded:!0};t(c,f),n?.({surveys:c,context:f})}}))}ql(){return this.jl()&&!this.Ll&&!this.Bl()}jl(){var t=this._instance.get_property(Xr);return ke(t)&&Date.now()-t>3e5}Bl(){return ke(this.Ol)&&3e5>Date.now()-this.Ol}markSurveyAsSeen(t,e){var n,i={id:t,current_iteration:(n=e?.iteration)!==null&&n!==void 0?n:null};qf(i);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}}Nl(t){for(var e of this.Fl)try{if(!t.isLoaded)return e([],t);this.getSurveys(e)}catch(n){Q.error("Error in survey callback",n)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!H(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);Q.warn("init was not called")}Hl(t){var e=null;return this.getSurveys((n=>{var i;e=(i=n.find((r=>r.id===t)))!==null&&i!==void 0?i:null})),e}Ul(t){if(H(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(H(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(H(this._surveyManager))return Q.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 H(this._surveyManager)?(Q.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Ir})):new Promise((n=>{this.getSurveys((i=>{var r,s=(r=i.find((a=>a.id===t)))!==null&&r!==void 0?r:null;if(s){var o=this.zl(s);n({visible:o.eligible,disabledReason:o.reason})}else n({visible:!1,disabledReason:"Survey not found"})}),e)}))}renderSurvey(t,e,n){var i;if(H(this._surveyManager))Q.warn("init was not called");else{var r=typeof t=="string"?this.Hl(t):t;if(r!=null&&r.id)if(ym.includes(r.type)){var s=F?.querySelector(e);if(s)return(i=r.appearance)!=null&&i.surveyPopupDelaySeconds?(Q.info("Rendering survey "+r.id+" with delay of "+r.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;Q.info("Rendering survey "+r.id+" with delay of "+((o=r.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(a=this._surveyManager)==null||a.renderSurvey(r,s,n),Q.info("Survey "+r.id+" rendered")}),1e3*r.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(r,s,n);Q.warn("Survey element not found")}else Q.warn("Surveys of type "+r.type+" cannot be rendered in the app");else Q.warn("Survey not found")}}displaySurvey(t,e){var n;if(H(this._surveyManager))Q.warn("init was not called");else{var i=this.Hl(t);if(i){var r=i;if((n=i.appearance)!=null&&n.surveyPopupDelaySeconds&&e.ignoreDelay&&(r=k({},i,{appearance:k({},i.appearance,{surveyPopupDelaySeconds:0})})),e.displayType!==_a.Popover&&e.initialResponses&&Q.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),e.ignoreConditions===!1){var s=this.Ul(i);if(!s.eligible)return void Q.warn("Survey is not eligible to be displayed: ",s.reason)}e.displayType!==_a.Inline?this._surveyManager.handlePopoverSurvey(r,e):this.renderSurvey(r,e.selector,e.properties)}else Q.warn("Survey not found")}}cancelPendingSurvey(t){H(this._surveyManager)?Q.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},Cs),Km={toolbar:class{constructor(t){this.instance=t}Wl(t){B.ph_toolbar_state=t}Vl(){var t;return(t=B.ph_toolbar_state)!==null&&t!==void 0?t:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(t,e,n){if(t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),ga(this.instance.config)||!w||!F)return!1;t=t??w.location,n=n??w.history;try{if(!e){try{w.localStorage.setItem("test","test"),w.localStorage.removeItem("test")}catch{return!1}e=w?.localStorage}var i,r=Bm||os(t.hash,"__posthog")||os(t.hash,"state"),s=r?Pc((()=>JSON.parse(atob(decodeURIComponent(r)))))||Pc((()=>JSON.parse(decodeURIComponent(r)))):null;return s&&s.action==="ph_authorize"?((i=s).source="url",i&&Object.keys(i).length>0&&(s.desiredHash?t.hash=s.desiredHash:n?n.replaceState(n.state,"",t.pathname+t.search):t.hash="")):((i=JSON.parse(e.getItem(fu)||"{}")).source="localstorage",delete i.userIntent),!(!i.token||this.instance.config.token!==i.token||(this.loadToolbar(i),0))}catch{return!1}}Zl(t){var e=B.ph_load_toolbar||B.ph_load_editor;!H(e)&&De(e)?e(t,this.instance):hu.warn("No toolbar load function found")}loadToolbar(t){var e=!(F==null||!F.getElementById(sf));if(!w||e)return!1;var n=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,i=k({token:this.instance.config.token},t,{apiURL:this.instance.requestRouter.endpointFor("ui")},n?{instrument:!1}:{});if(w.localStorage.setItem(fu,JSON.stringify(k({},i,{source:void 0}))),this.Vl()===2)this.Zl(i);else if(this.Vl()===0){var r;this.Wl(1),(r=B.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"toolbar",(s=>{if(s)return hu.error("[Toolbar] Failed to load",s),void this.Wl(0);this.Wl(2),this.Zl(i)})),ve(w,"turbolinks:load",(()=>{this.Wl(0),this.loadToolbar(i)}))}return!0}Gl(t){return this.loadToolbar(t)}maybeLoadEditor(t,e,n){return t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),this.maybeLoadToolbar(t,e,n)}}},Ym=k({experiments:Me},Cs),Jm={conversations:class{constructor(t){this.Ql=void 0,this._conversationsManager=null,this.Kl=!1,this.Jl=null,this.Yl=!1,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this._instance.config.disable_conversations&&(this.Xl=t.ok,t.ok)){var e=t.config.conversations;H(e)||(gt(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||ga(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=B?.__PosthogExtensions__;if(t&&!C(this.Ql)&&this.Ql)if(this.Jl&&this.Jl.token){this.Kl=!0;try{var e=t.initConversations;if(e)return this.tu(e),void(this.Kl=!1);var n=t.loadExternalDependency;if(!n)return void this.eu(al);n(this._instance,"conversations",(i=>{i||!t.initConversations?this.eu("Could not load conversations script",i):this.tu(t.initConversations),this.Kl=!1}))}catch(i){this.eu("Error initializing conversations",i),this.Kl=!1}}else st.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,st.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else st.error("Cannot complete initialization: remote config is null")}eu(t,e){st.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():st.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!Ke(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":ga(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.Xl===!1?"remote_config_failed":C(this.Ql)?this.Xl?"disabled_in_project":"remote_config_pending":this.Ql?H(this.Jl)||!this.Jl.token?"missing_token":B!=null&&B.__PosthogExtensions__?this.Kl?"initializing":this.Yl?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.isVisible())!==null&&t!==void 0&&t}sendMessage(t,e,n){var i=this;return se((function*(){return i._conversationsManager?i._conversationsManager.sendMessage(t,e,n):(st.warn(En),null)}))()}getMessages(t,e){var n=this;return se((function*(){return n._conversationsManager?n._conversationsManager.getMessages(t,e):(st.warn(En),null)}))()}markAsRead(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(st.warn(En),null)}))()}getTickets(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(st.warn(En),null)}))()}requestRestoreLink(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(st.warn(En),null)}))()}restoreFromToken(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(st.warn(En),null)}))()}restoreFromUrlToken(){var t=this;return se((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(st.warn(En),null)}))()}getCurrentTicketId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getCurrentTicketId())!==null&&t!==void 0?t:null}getWidgetSessionId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getWidgetSessionId())!==null&&t!==void 0?t:null}Xn(){var t;(t=this._conversationsManager)==null||t.setIdentity()}ts(){var t;(t=this._conversationsManager)==null||t.clearIdentity()}}},Zm={logs:class{constructor(t){var e,n=this;this.iu=!1,this.ru=!1,this.rt=pe("[logs]"),this.nu=k({},this.rt,{error(){for(var i=arguments.length,r=new Array(i),s=0;i>s;s++)r[s]=arguments[s];r.some(bu)||n.rt.error(...r)}}),this.tr=[],this.su=[],this.Sa=0,this.au=()=>{var i,r;this.Sa=0,(i=this.ou)==null||i.onReconnect(),(r=this.lu)==null||r.onReconnect()},this._instance=t,this._instance&&(e=this._instance.config.logs)!=null&&e.captureConsoleLogs&&(this.iu=!0),w&&ve(w,"online",this.au)}uu(t,e,n,i){var r,s=(function(o,a){var l,u,c,d,f,h,p,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,v=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,S=C(v)?Math.max(m,2048):Math.max(m,v),b=o?.resourceAttributes;return{serviceName:(d=(f=b?.["service.name"])!==null&&f!==void 0?f:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(h=b?.["service.version"])!==null&&h!==void 0?h:o?.serviceVersion,environment:(p=b?.["deployment.environment"])!==null&&p!==void 0?p:o?.environment,resourceAttributes:b,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:S,maxBatchRecordsPerPost:100,rateCapWindowMs:g,maxLogsPerInterval:v,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}})((r=this._instance)==null||(r=r.config)==null?void 0:r.logs,n);return[new tg(this.hu(t,e),s,this.nu,(()=>this.du()),(o=>o()),void 0,i),s]}vu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.ou||this.cu!==e){var n;(n=this.ou)==null||n.reset(),this.cu=e;var i=this.uu((()=>this.tr),(r=>{this.tr=r}));this.ou=i[0],this.fu=i[1]}return this.ou}pu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.lu||this.gu!==e){var n;(n=this.lu)==null||n.reset(),this.gu=e;var i=this.uu((()=>this.su),(r=>{this.su=r}),{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},wu);this.lu=i[0],this.mu=i[1]}return this.lu}initialize(){this.loadIfEnabled()}onRemoteConfig(t){var e;if(t.ok){var n=(e=t.config.logs)==null?void 0:e.captureConsoleLogs;!H(n)&&n&&(this.iu=!0,this.loadIfEnabled())}}reset(){var t,e;this.tr=[],(t=this.ou)==null||t.reset(),this.su=[],(e=this.lu)==null||e.reset(),this.Sa=0}captureLog(t){this.vu().captureLog(t)}he(t){this.pu().captureLog(t)}get logger(){return this.yu||(this.yu={trace:(t,e)=>this.captureLog({body:t,level:"trace",attributes:e}),debug:(t,e)=>this.captureLog({body:t,level:"debug",attributes:e}),info:(t,e)=>this.captureLog({body:t,level:"info",attributes:e}),warn:(t,e)=>this.captureLog({body:t,level:"warn",attributes:e}),error:(t,e)=>this.captureLog({body:t,level:"error",attributes:e}),fatal:(t,e)=>this.captureLog({body:t,level:"fatal",attributes:e})}),this.yu}flushLogs(t){t?this.bu(t):(this.ou&&this.ou.flush().catch((e=>this._u(e))),this.lu&&this.lu.flush().catch((e=>this._u(e))))}_u(t){bu(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=B?.__PosthogExtensions__;if(t){var e=t.loadExternalDependency;e?e(this._instance,"logs",(n=>{var i;n||(i=t.logs)==null||!i.initializeLogs?this.rt.error("Could not load logs script",n):(t.logs.initializeLogs(this._instance),this.ru=!0)})):this.rt.error(al)}else this.rt.error("PostHog Extensions not found.")}}hu(t,e){var n=this._instance;return{get isDisabled(){return!1},get optedOut(){return!n.is_capturing()},getPersistedProperty:i=>i===jt.LogsQueue?t():void 0,setPersistedProperty(i,r){var s;i===jt.LogsQueue&&e((s=r)!==null&&s!==void 0?s:[])},Ot:i=>this.Ot(i),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Ot(t){return new Promise((e=>{if(vf(this.Sa,3))e({kind:"fatal",error:Do(void 0,"logs endpoint is unreachable, dropping batch")});else{var n=!1,i=s=>{n||(n=!0,clearTimeout(r),e(s))},r=setTimeout((()=>{this.rt.warn("Logs request timed out before receiving a response"),i({kind:"retry-later",error:Do(void 0,"logs request timed out")})}),9e4);this._instance._send_request({method:"POST",url:this.wu(),data:t,compression:"best-available",batchKey:"logs",fireCallbackOnDrop:!0,callback:s=>{var o=s.statusCode;if(this.ku(o),o>=200&&300>o)i({kind:"ok"});else if(o===413)i({kind:"too-large"});else if(o!==0&&o!==429&&500>o)i({kind:"fatal",error:new Error("logs request failed with status "+o)});else{var a;o===0?(s.error||this.rt.warn("Logs request failed before receiving an HTTP response"),i({kind:"retry-later",error:Do(s.error,"logs request failed before receiving an HTTP response")})):i({kind:"retry-later",error:(a=s.error)!==null&&a!==void 0?a:new Error("logs request failed with status "+o)})}}})}}))}ku(t){(t!==0||this._instance.__loaded)&&(this.Sa=_f(t,this.Sa,3,(()=>this.rt.warn("Log requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped sending logs; will try again when connectivity changes."))))}bu(t){this.tr.length>0&&this.xu(t,this.tr,this.fu,ne.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,wu,(e=>{this.su=e}))}xu(t,e,n,i,r){if(e.length!==0){var s=e.map((a=>a.record));r([]);var o=Ud(s,jd(n,ne.LIB_NAME,ne.LIB_VERSION),i,ne.LIB_VERSION);this._instance._send_request({method:"POST",url:this.wu(),data:o,compression:"best-available",batchKey:"logs",transport:t})}}wu(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}du(){var t,e={};if(e.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var n=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.windowId,r=n.sessionStartTimestamp,s=n.lastActivityTimestamp;e.sessionId=n.sessionId,e.windowId=i,H(r)||(e.sessionStartTimestamp=r),H(s)||(e.lastActivityTimestamp=s)}if(B!=null&&(t=B.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?fn(B.location.href):B.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},Xm={metrics:class{constructor(t){this.rt=pe("[metrics]"),this._instance=t}initialize(){}vu(){var t,e,n=(t=this._instance)==null||(t=t.config)==null?void 0:t.metrics;return this.ou&&this.cu===n||((e=this.ou)==null||e.reset(),this.cu=n,this.ou=new ng(this.hu(),(function(i){var r,s,o,a,l,u=i?.resourceAttributes;return{serviceName:(r=u?.["service.name"])!==null&&r!==void 0?r:i?.serviceName,serviceVersion:(s=u?.["service.version"])!==null&&s!==void 0?s:i?.serviceVersion,environment:(o=u?.["deployment.environment"])!==null&&o!==void 0?o:i?.environment,resourceAttributes:u,beforeSend:i?.beforeSend,flushIntervalMs:(a=i?.flushIntervalMs)!==null&&a!==void 0?a:1e4,maxSeriesPerFlush:(l=i?.maxSeriesPerFlush)!==null&&l!==void 0?l:1e3}})(n),this.rt)),this.ou}count(t,e,n){e===void 0&&(e=1),this.vu().count(t,e,n)}gauge(t,e,n){this.vu().gauge(t,e,n)}histogram(t,e,n){this.vu().histogram(t,e,n)}flush(t){if(!this.ou)return Promise.resolve();if(t){var e=this.ou.drainWindow();return e&&this.Jt(e,t),Promise.resolve()}return this.ou.flush().catch((n=>this.rt.error("PostHog metrics flush failed:",n)))}reset(){var t;(t=this.ou)==null||t.reset()}hu(){var t=this._instance,e=this;return{get isDisabled(){return!1},get optedOut(){return!t.is_capturing()},Jt:n=>e.Jt(n),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Jt(t,e){return new Promise((n=>{var i=!1,r=o=>{i||(i=!0,clearTimeout(s),n(o))},s=setTimeout((()=>r({kind:"retry-later",error:new Error("metrics request timed out")})),9e4);this._instance._send_request(k({method:"POST",url:this.Su(),data:t,compression:"best-available",batchKey:"metrics"},e&&{transport:e},{fireCallbackOnDrop:!0,callback(o){var a=o.statusCode;if(a>=200&&300>a)r({kind:"ok"});else if(a===413)r({kind:"too-large"});else if(a!==0&&a!==429&&500>a)r({kind:"fatal",error:new Error("metrics request failed with status "+a)});else{var l;r({kind:"retry-later",error:(l=o.error)!==null&&l!==void 0?l:new Error("metrics request failed with status "+a)})}}}))}))}Su(){return this._instance.requestRouter.endpointFor("api","/i/v1/metrics")+"?token="+encodeURIComponent(this._instance.config.token)}}},Qm=k({},Cs,Um,Hm,Wm,qm,zm,Gm,Vm,Km,Ym,Jm,Zm,Xm);Je.__defaultExtensionClasses=k({},Qm);(function(){ne.SDK_DIST_CHANNEL="npm";var t=Wi[Gn]=new Je;return(function(){function e(){e.done||(e.done=!0,Vf=!1,ie(Wi,(function(n){n._dom_loaded()})))}F!=null&&F.addEventListener?F.readyState==="complete"?e():ve(F,"DOMContentLoaded",e,{capture:!1}):w&&A.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const ev=["a[href]","button:not([disabled])","input:not([disabled]):not([type='hidden'])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(",");let ht=null,ka=null,Kf="";const Ca=new Map;function Yf(t){return[...t.querySelectorAll(ev)].filter(e=>!e.hidden&&e.getAttribute("aria-hidden")!=="true"&&e.getClientRects().length>0)}function tv(t){for(const e of document.body.children)e===t||e.tagName==="SCRIPT"||(Ca.set(e,{inert:e.inert,ariaHidden:e.getAttribute("aria-hidden")}),e.inert=!0,e.setAttribute("aria-hidden","true"))}function nv(){for(const[t,e]of Ca)t.inert=e.inert,e.ariaHidden===null?t.removeAttribute("aria-hidden"):t.setAttribute("aria-hidden",e.ariaHidden);Ca.clear()}function Jf(t){return t?.dataset.modalDismissible!=="false"&&t?.getAttribute("aria-busy")!=="true"}function He(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n)return!1;ht&&ht!==n&&We(ht,{restoreFocus:!1,force:!0}),ka=e.trigger||document.activeElement,ht=n,Kf=document.body.style.overflow,tv(n),document.body.style.overflow="hidden",n.classList.add("open"),n.setAttribute("aria-hidden","false");const i=n.querySelector(".modal-content");i&&(i.style.transform="scale(1) translateY(0)");const r=()=>{if(ht!==n)return;((e.initialFocus?n.querySelector(e.initialFocus):n.querySelector("[data-modal-initial-focus]"))||Yf(n)[0]||n.querySelector(".modal-content")||n).focus({preventScroll:!0})};return requestAnimationFrame(r),setTimeout(r,260),!0}function We(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n||!e.force&&!Jf(n))return!1;n.classList.remove("open"),n.setAttribute("aria-hidden","true"),nv(),document.body.style.overflow=Kf,ht=null;const i=ka;return ka=null,e.restoreFocus!==!1&&i?.isConnected&&i.focus({preventScroll:!0}),!0}function Eu(t,e,n="Operation in progress"){const i=typeof t=="string"?document.getElementById(t):t;i&&(i.dataset.modalDismissible=e?"false":"true",i.setAttribute("aria-busy",String(!!e)),e?i.setAttribute("aria-label",n):i.removeAttribute("aria-label"))}function iv(t){if(!Jf(t))return;const e=t.dataset.modalCloseHandler;e&&typeof window[e]=="function"?window[e]():We(t)}document.addEventListener("keydown",t=>{if(!ht)return;if(t.key==="Escape"){t.preventDefault(),t.stopImmediatePropagation(),iv(ht);return}if(t.key!=="Tab"){t.stopPropagation();return}const e=Yf(ht);if(!e.length){t.preventDefault(),(ht.querySelector(".modal-content")||ht).focus();return}const n=e[0],i=e[e.length-1];t.shiftKey&&document.activeElement===n?(t.preventDefault(),i.focus()):!t.shiftKey&&document.activeElement===i&&(t.preventDefault(),n.focus())},!0);function rv(){document.querySelectorAll(".modal-overlay").forEach(t=>{t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-hidden",t.classList.contains("open")?"false":"true");const e=t.querySelector(".modal-content");e&&!e.hasAttribute("tabindex")&&(e.tabIndex=-1);const n=t.querySelector("h1, h2, h3");n&&(n.id||(n.id=`${t.id}-title`),t.setAttribute("aria-labelledby",n.id)),t.querySelectorAll(".modal-close").forEach(i=>{i.getAttribute("aria-label")||i.setAttribute("aria-label","Close dialog")})})}const gl=Object.freeze({free:"Free",professional:"Pro",power:"Power"}),sv=Object.freeze({free:2,professional:50,power:2e3}),ov="(contact us)",av=Object.freeze({free:Object.freeze(["2 generations/month","Gemini model only","Code Review"]),professional:Object.freeze(["50 generations/month","All models","Code Regeneration","Code Review"]),power:Object.freeze(["2000 generations/month","All models","Code Regeneration","Bring your own key (BYOK)","Code Review","All models + early access",`API & MCP access ${ov}`])}),Zf="CodeFile",Xf="GeneratedCode",lv={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function ln(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Aa(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function cv(t={},e=0){const n=Aa(t.artifactType||t.type||Zf),i=Aa(t.artifactName||t.name||t.fileName||`${Xf}-${e+1}`);return`${n||"artifact"}-${i||e+1}`}function Qf(t={},e=0){const n=ln(t),i=n.artifactType||n.type||Zf,r=n.artifactName||n.name||Xf;let s=n.fileName||r;return s.endsWith(".dart")||(s+=".dart"),{id:Aa(n.id)||cv({...n,artifactType:i,artifactName:r,fileName:s},e),artifactType:i,artifactName:r,fileName:s,deployPath:n.deployPath||"",description:n.description||"",code:n.code||n.content||"",dependencies:eh(n.dependencies),imports:Array.isArray(n.imports)?n.imports:[],publicApi:Array.isArray(n.publicApi)?n.publicApi:[],relationships:th(n.relationships),deployStatus:n.deployStatus||"pending",review:n.review||null,metadata:ln(n.metadata),codeType:n.codeType||lv[i]||"O"}}function eh(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const n=ln(e),i=n.name||n.package;return i?{name:i,version:n.version||null,versionRequired:!!(n.versionRequired||n.required),inferred:!!n.inferred,...n.reason?{reason:n.reason}:{}}:null}).filter(Boolean):Object.entries(ln(t)).map(([e,n])=>({name:e,version:n||null,inferred:!1})):[]}function th(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const n=ln(e);return!n.from&&!n.to?null:{from:n.from||null,to:n.to||null,type:n.type||"uses",description:n.description||""}}).filter(Boolean):[]}function Pa(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;try{return JSON.parse(e)}catch{const n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(!n)return null;try{return JSON.parse(n[1].trim())}catch{return null}}}function Qi(t,e={}){const n=[],i=typeof t=="string"?Pa(t):t,s=ln(i||{});!i&&typeof t=="string"&&n.push("Structured bundle parse failed; using legacy single-artifact fallback.");const o=Array.isArray(s.artifacts)?s.artifacts:[{artifactType:s.artifactType||e.artifactType,artifactName:s.artifactName||e.artifactName,fileName:s.fileName||e.fileName,description:s.description,code:s.code||e.code||(typeof t=="string"?t:""),dependencies:s.dependencies||e.dependencies,relationships:s.relationships||e.relationships}];o.forEach((d,f)=>{!d?.artifactType&&!d?.type&&n.push(`Artifact ${f+1} has no artifactType; it will deploy as a standalone code file under lib/custom_code/ root.`)});const a=o.map((d,f)=>Qf(d,f)),l=new Map(o.map((d,f)=>[ln(d).id,a[f]?.id]).filter(([d,f])=>d&&f)),u=d=>l.get(d)||d,c=th(s.relationships||e.relationships).map(d=>({...d,from:d.from?u(d.from):d.from,to:d.to?u(d.to):d.to}));return{schemaVersion:s.schemaVersion||e.schemaVersion||null,id:s.id||e.id||"bundle-current",title:s.title||s.name||e.title||"Generated artifact bundle",description:s.description||e.description||"",artifacts:a,dependencies:eh(s.dependencies||e.dependencies),relationships:c,deployOrder:Array.isArray(s.deployOrder)?s.deployOrder.map(u):a.map(d=>d.id),warnings:[...n,...Array.isArray(s.warnings)?s.warnings:[]],metadata:ln(s.metadata)}}function oi(t){return Qi(t).artifacts[0]||Qf()}function Zt(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function ai(t){return JSON.stringify(t,null,2)}function uv(t){return ai({task:"architect",userRequest:String(t??"")})}function dv(t){const e=Zt(t);return e&&typeof e=="object"&&typeof e.task=="string"?ai(e):ai({task:"generate_bundle",bundleSpec:e})}function fv(t){return ai({task:"review_bundle",generatedBundle:Zt(t),outputRequirements:{bundleReview:["status","score","summary","manualActions","findings"],scoreRange:[0,100],eachArtifact:["id","review.status","review.findings"],manualActions:{definition:"Setup the developer must perform by hand in the FlutterFlow editor that FlutterFlow will NOT do for them.",exclude:["creating the Custom Action, Widget or Code File itself - deploying the code creates it","declaring parameters or return values FlutterFlow derives from the function signature","anything that resolves as a side effect of using the action or widget in the editor","generic advice such as testing, reviewing or rebuilding the app"],preferEmpty:"Return an empty array when nothing qualifies - an empty list is the expected result for most bundles."}}})}function ml(t,e=null){const n={stage:t};return e!=null&&(n.bundle=Zt(e)),n}function hv({bundleSpec:t,artifactBundle:e,bundleReview:n,artifactId:i,userFeedback:r}){return ai({task:"regenerate_artifact",artifactId:i,bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(r)})}function nh({bundleSpec:t,artifactBundle:e,bundleReview:n,userFeedback:i}){return ai({task:"regenerate_bundle",bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(i??"")})}const Su={csam:"child-safety content",dangerous:"dangerous content",harassment:"harassment",hate_speech:"hate speech",maliciousUrls:"a potentially malicious URL",malicious_uris:"a potentially malicious URL",pi_and_jailbreak:"prompt-injection or jailbreak instructions",promptInjection:"prompt-injection or jailbreak instructions",rai:"restricted content",sdp:"sensitive personal data",sexually_explicit:"sexually explicit content",virus_scan:"potentially malicious file content"},pv=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function et(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function gv(t){return et(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||et(t.filterSummary)||et(t.filterResults):!1}function ih(t,e=0){if(!et(t)||e>3)return null;if(gv(t))return t;for(const n of pv){const i=t[n];if(et(i)){const r=ih(i,e+1);if(r)return r}}return null}function ds(t){return Array.isArray(t)?t.some(ds):et(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(ds):!1}function Fa(t){return Array.isArray(t)?t.some(Fa):et(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(Fa):!1}function rh(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function mv(t,e){if(et(t))for(const[n,i]of Object.entries(t)){if(!et(i))continue;const r=et(i.categories)?i.categories:{},s=Object.entries(r).filter(([,o])=>et(o)&&o.matched===!0).map(([o])=>o);s.length>0?s.forEach(o=>e.add(o)):i.matched===!0&&e.add(rh(n))}}function vv(t,e){if(!t)return;const n=Array.isArray(t)?t.flatMap(i=>et(i)?Object.entries(i):[]):Object.entries(t);for(const[i,r]of n){if(!ds(r))continue;const s=rh(i),o=r?.raiFilterResult?.raiFilterTypeResults||(s==="rai"?r?.raiFilterTypeResults:null),a=et(o)?Object.entries(o).filter(([,l])=>ds(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(s)}}function _v(t){return Su[t]?Su[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function xu(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 yv(t){const e=ih(t);if(!e)return null;const n=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);mv(e.filterSummary,n),vv(e.filterResults,n);const i=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||n.size>0,r=e.invocationResult||null,s=Fa(e.filterSummary||e.filterResults);return!i&&!s&&!["PARTIAL","FAILURE"].includes(r)?null:{kind:i?"blocked":"unavailable",invocationResult:r,matchedFilters:[...n]}}function wv(t,e){const n=yv(t);if(!n)return null;const i=[...new Set(n.matchedFilters.map(_v))],r=n.kind==="blocked",s=new Error(r?`Safety screening blocked this pipeline step for ${xu(i)}.`:"Safety screening could not be completed. Please try again.");return s.name="ModelArmorError",s.code=r?"MODEL_ARMOR_BLOCKED":"MODEL_ARMOR_UNAVAILABLE",s.isModelArmor=!0,s.pipelineStep=e,s.userTitle=r?"Request blocked for safety":"Safety check unavailable",s.userMessage=r?`The safety check detected ${xu(i)}. Edit your request to remove or rephrase the flagged content, then run the pipeline again.`:"The safety service did not finish all of its checks. Please wait a moment and run the pipeline again.",s.retryExplanation=r?"Trying another model would not change this safety decision.":"A fallback model was not attempted because safety screening must complete first.",s.matchedFilters=n.matchedFilters,s}function bv(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function Iu(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,n=[];for(const i of bv(t).split(` +(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const s of r)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function n(r){const s={};return r.integrity&&(s.integrity=r.integrity),r.referrerPolicy&&(s.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?s.credentials="include":r.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function i(r){if(r.ep)return;r.ep=!0;const s=n(r);fetch(r.href,s)}})();var w=typeof window<"u"?window:void 0,Le=typeof globalThis<"u"?globalThis:w,Ue=Le?.navigator,F=Le?.document,me=Le?.location,Za=Le?.fetch,qo=Le!=null&&Le.XMLHttpRequest&&"withCredentials"in new Le.XMLHttpRequest?Le.XMLHttpRequest:void 0,uc=Le?.AbortController,Fp=Le?.CompressionStream,Ve=Ue?.userAgent;function cd(){return!(!w||w.navigator.onLine===!1)}var vi=typeof globalThis<"u"?globalThis:w;vi&&typeof self>"u"&&(vi.self=vi),vi&&typeof File>"u"&&(vi.File=function(){});var B=w??{},ne={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function dc(t,e,n,i,r,s,o){try{var a=t[s](o),l=a.value}catch(u){return void n(u)}a.done?e(l):Promise.resolve(l).then(i,r)}function se(t){return function(){var e=this,n=arguments;return new Promise((function(i,r){var s=t.apply(e,n);function o(l){dc(s,i,r,o,a,"next",l)}function a(l){dc(s,i,r,o,a,"throw",l)}o(void 0)}))}}function k(){return k=Object.assign?Object.assign.bind():function(t){for(var e=1;arguments.length>e;e++){var n=arguments[e];for(var i in n)({}).hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},k.apply(null,arguments)}function ud(t,e){if(t==null)return{};var n={};for(var i in t)if({}.hasOwnProperty.call(t,i)){if(e.indexOf(i)!==-1)continue;n[i]=t[i]}return n}var fc=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function hc(t){return typeof t=="string"||t}function pc(t){return typeof t=="string"?t:void 0}var _i,Rp=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],Ut=(function(t){return t.AnonymousId="anonymous_id",t.DistinctId="distinct_id",t.Props="props",t.EnablePersonProcessing="enable_person_processing",t.PersonMode="person_mode",t.FeatureFlagDetails="feature_flag_details",t.FeatureFlags="feature_flags",t.FeatureFlagPayloads="feature_flag_payloads",t.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",t.BootstrapFeatureFlags="bootstrap_feature_flags",t.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",t.OverrideFeatureFlags="override_feature_flags",t.Queue="queue",t.AiQueue="ai_queue",t.LogsQueue="logs_queue",t.OptedOut="opted_out",t.SessionId="session_id",t.SessionStartTimestamp="session_start_timestamp",t.SessionLastTimestamp="session_timestamp",t.PersonProperties="person_properties",t.GroupProperties="group_properties",t.InstalledAppBuild="installed_app_build",t.InstalledAppVersion="installed_app_version",t.SessionReplay="session_replay",t.PushRegistered="push_registered",t.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",t.SurveyLastSeenDate="survey_last_seen_date",t.SurveysSeen="surveys_seen",t.Surveys="surveys",t.RemoteConfig="remote_config",t.FlagsEndpointWasHit="flags_endpoint_was_hit",t.DeviceId="device_id",t})({}),gc=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),Tp=["$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"],$p=["token"],dd="NativeGzipValidationError",zo=t=>t.length>=2&&t[0]===31&&t[1]===139,mc=(t,e)=>t===gc.GZipJS||e===gc.GZipJS||e==="gzip",vc=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",pr=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=dd,e},Mp=(function(){var t=se((function*(e,n){18>e.size&&pr("too-short");var i=new Uint8Array(yield e.slice(0,10).arrayBuffer());zo(i)&&i[2]===8||pr("invalid-header");var r=new DataView(yield e.slice(e.size-8).arrayBuffer());r.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(_i)return _i;_i=[];for(var c=0;256>c;c++){for(var d=c,f=0;8>f;f++)d=1&d?3988292384^d>>>1:d>>>1;_i[c]=d>>>0}return _i})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(n)&&pr("invalid-crc");var s=n.length>>>0;r.getUint32(4,!0)!==s&&pr("invalid-size")}));return function(e,n){return t.apply(this,arguments)}})();function Vo(){return Vo=se((function*(t,e,n){e===void 0&&(e=!0);try{var i=new TextEncoder().encode(t),r=new globalThis.CompressionStream("gzip"),s=r.writable.getWriter(),o=s.write(i).then((()=>s.close())).catch((function(){var u=se((function*(c){try{yield s.abort(c)}catch{}throw c}));return function(c){return u.apply(this,arguments)}})()),a=new Response(r.readable).blob(),l=(yield Promise.all([a,o]))[0];return yield Mp(l,i),l}catch(u){if(n!=null&&n.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),Vo.apply(this,arguments)}var Lp=["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"],_c=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var n=t.toLowerCase();return Lp.concat(e).some((i=>{var r=i.toLowerCase();return n.indexOf(r)!==-1}))};function j(t,e){return t.indexOf(e)!==-1}var xs=function(t){return t.trim()},Go=function(t){return t.replace(/^\$/,"")};function fd(t){var e,n=[];return(e=JSON.stringify(t,(function(i,r){if(typeof r=="bigint")return r.toString();if(typeof r!="function"&&typeof r!="symbol"){if(r instanceof Error)return{name:r.name,message:r.message,stack:r.stack};if(r&&typeof r=="object"){for(;n.length>0&&n[n.length-1]!==this;)n.pop();if(n.includes(r))return"[Circular]";n.push(r)}return r}})))!==null&&e!==void 0?e:"null"}var hd=Object.prototype,pd=hd.hasOwnProperty,Is=hd.toString,U=Array.isArray||function(t){return Is.call(t)==="[object Array]"},De=t=>typeof t=="function",he=t=>t===Object(t)&&!U(t),Kt=t=>{if(he(t)){for(var e in t)if(pd.call(t,e))return!1;return!0}return!1},C=t=>t===void 0,X=t=>Is.call(t)=="[object String]",Ko=t=>X(t)&&t.trim().length===0,Ke=t=>t===null,H=t=>C(t)||Ke(t),ke=t=>Is.call(t)=="[object Number]"&&t==t,Dt=t=>ke(t)&&t>0,gt=t=>Is.call(t)==="[object Boolean]",Np=t=>t instanceof FormData,Op=t=>j(Tp,t),Bp=t=>j($p,t);function gd(t){return t===null||typeof t!="object"}function Hr(t,e){return{}.toString.call(t)==="[object "+e+"]"}function Xa(t){return typeof Event<"u"&&md(t,Event)}function md(t,e){try{return t instanceof e}catch{return!1}}var Dp=[!0,"true",1,"1","yes"],uo=t=>j(Dp,t),jp=[!1,"false",0,"0","no"];function At(t,e,n,i,r){return e>n&&(i.warn("min cannot be greater than max."),e=n),ke(t)?t>n?(i.warn(" cannot be greater than max: "+n+". Using max value instead."),n):e>t?(i.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(i.warn(" must be a number. using max or fallback. max: "+n+", fallback: "+r),At(r||n,e,n,i))}class Up{constructor(e){this.tt={},this.et=e.et,this.it=At(e.bucketSize,0,100,e.rt),this.nt=At(e.refillRate,0,this.it,e.rt),this.st=At(e.refillInterval,0,864e5,e.rt)}ot(e,n){var i=Math.floor((n-e.lastAccess)/this.st);i>0&&(e.tokens=Math.min(e.tokens+i*this.nt,this.it),e.lastAccess=e.lastAccess+i*this.st)}consumeRateLimit(e){var n,i=Date.now(),r=String(e),s=this.tt[r];return s?this.ot(s,i):this.tt[r]=s={tokens:this.it,lastAccess:i},s.tokens===0||(s.tokens--,s.tokens===0&&((n=this.et)==null||n.call(this,e)),s.tokens===0)}stop(){this.tt={}}}var it="Mobile",Wr="iOS",Yt="Android",ei="Tablet",vd=Yt+" "+ei,_d="iPad",yd="Apple",wd=yd+" Watch",Bi="Safari",ti="BlackBerry",bd="Samsung",Ed=bd+"Browser",Sd=bd+" Internet",Pn="Chrome",Hp=Pn+" OS",xd=Pn+" "+Wr,Qa="Internet Explorer",Id=Qa+" "+it,el="Opera",Wp=el+" Mini",tl="Edge",kd="Microsoft "+tl,Zn="Firefox",Cd=Zn+" "+Wr,Gi="Nintendo",Ki="PlayStation",Xn="Xbox",Ad=Yt+" "+it,Pd=it+" "+Bi,Pi="Windows",Yo=Pi+" Phone",yc="Nokia",Jo="Ouya",Fd="Generic",qp=Fd+" "+it.toLowerCase(),Rd=Fd+" "+ei.toLowerCase(),Zo="Konqueror",Td="Oculus Browser",qr="Vivaldi",$d="Yandex",zr="Whale",Xo="DuckDuckGo",Md="Pale Moon",Vr="Waterfox",Di="Brave",Ld="Google Search App",we="(\\d+(\\.\\d+)?)",fo=new RegExp("Version/"+we),zp=new RegExp(Xn,"i"),Vp=new RegExp(Ki+" \\w+","i"),Gp=new RegExp(Gi+" \\w+","i"),nl=new RegExp(ti+"|PlayBook|BB10","i"),Kp={"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"},Nd=function(t,e,n,i){e=e||"";var r=(function(s){return s!=null&&s.brave?Di:null})(n);return r||(i!=null&&i.detectGoogleSearchApp&&j(t,"GSA/")?Ld:j(t," OPR/")&&j(t,"Mini")?Wp:j(t," OPR/")?el:nl.test(t)?ti:j(t,"IE"+it)||j(t,"WPDesktop")?Id:j(t,"OculusBrowser")?Td:j(t,Ed)?Sd:j(t,tl)||j(t,"Edg/")?kd:j(t,qr+"/")?qr:j(t,"YaBrowser/")?$d:j(t,zr+"/")?zr:j(t,Xo+"/")||j(t,"Ddg/")?Xo:j(t,"FBIOS")?"Facebook "+it:j(t,"UCWEB")||j(t,"UCBrowser")?"UC Browser":j(t,"CriOS")?xd:j(t,"CrMo")||j(t,Pn)?Pn:j(t,Yt)&&j(t,Bi)?Ad:j(t,"FxiOS")?Cd:j(t.toLowerCase(),Zo.toLowerCase())?Zo:j(t,Di+"/")?Di:((s,o)=>o&&j(o,yd)||(function(a){return j(a,Bi)&&!j(a,Pn)&&!j(a,Yt)})(s))(t,e)?j(t,it)?Pd:Bi:j(t,"PaleMoon/")?Md:j(t,Vr+"/")?Vr:j(t,Zn)?Zn:j(t,"MSIE")||j(t,"Trident/")?Qa:j(t,"Gecko")?Zn:"")},Yp={[Id]:[new RegExp("rv:"+we)],[kd]:[new RegExp(tl+"?\\/"+we)],[Pn]:[new RegExp("("+Pn+"|CrMo)\\/"+we)],[xd]:[new RegExp("CriOS\\/"+we)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+we)],[Bi]:[fo],[Pd]:[fo],[el]:[new RegExp("(Opera|OPR)\\/"+we)],[Zn]:[new RegExp(Zn+"\\/"+we)],[Cd]:[new RegExp("FxiOS\\/"+we)],[Zo]:[new RegExp("Konqueror[:/]?"+we,"i")],[ti]:[new RegExp(ti+" "+we),fo],[Ad]:[new RegExp("android\\s"+we,"i")],[Sd]:[new RegExp(Ed+"\\/"+we)],[Td]:[new RegExp("OculusBrowser\\/"+we)],[qr]:[new RegExp(qr+"\\/"+we)],[$d]:[new RegExp("YaBrowser\\/"+we)],[zr]:[new RegExp(zr+"\\/"+we)],[Di]:[new RegExp(Di+"\\/"+we)],[Xo]:[new RegExp("(DuckDuckGo|Ddg)\\/"+we)],[Md]:[new RegExp("PaleMoon\\/"+we)],[Vr]:[new RegExp(Vr+"\\/"+we)],[Ld]:[new RegExp("GSA\\/"+we)],[Qa]:[new RegExp("(rv:|MSIE )"+we)],Mozilla:[new RegExp("rv:"+we)]},Jp=function(t,e,n,i){var r=Nd(t,e,n,i),s=Yp[r];if(C(s))return null;for(var o=0;s.length>o;o++){var a=t.match(s[o]);if(a)return parseFloat(a[a.length-2])}return null},wc=[[new RegExp(Xn+"; "+Xn+" (.*?)[);]","i"),t=>[Xn,t&&t[1]||""]],[new RegExp(Gi,"i"),[Gi,""]],[new RegExp(Ki,"i"),[Ki,""]],[nl,[ti,""]],[new RegExp(Pi,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Yo,""];if(new RegExp(it).test(e)&&!/IEMobile\b/.test(e))return[Pi+" "+it,""];var n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){var i=Kp[n[1]]||"";return/arm/i.test(e)&&(i="RT"),[Pi,i]}return[Pi,""]}],[/((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=C(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+Yt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Yt+")","i"),t=>t&&t[2]?[Yt,[t[2],t[3],t[4]||"0"].join(".")]:[Yt,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{var e=["Mac OS X",""];return t&&t[1]&&(e[1]=[t[1],t[2],t[3]||"0"].join(".")),e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[Hp,""]],[/Linux|debian/i,["Linux",""]]],bc=function(t){return Gp.test(t)?Gi:Vp.test(t)?Ki:zp.test(t)?Xn:new RegExp(Jo,"i").test(t)?Jo:new RegExp("("+Yo+"|WPDesktop)","i").test(t)?Yo:/iPad/.test(t)?_d:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?wd:nl.test(t)?ti:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(yc,"i").test(t)?yc:/(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(it).test(t)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(t)||/pixel[\daxl ]{1,6}/i.test(t)&&!/pixel c/i.test(t)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(t)||/lmy47v/i.test(t)&&!/QTAQZ3/i.test(t)?Yt:vd:new RegExp("(pda|"+it+")","i").test(t)?qp:new RegExp(ei,"i").test(t)&&!new RegExp(ei+" pc","i").test(t)?Rd:""},Zp=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ec(t,e){return typeof(n=t)=="string"&&Zp.test(n)?t:e();var n}function fn(t){return t&&t.split("#")[0]}function il(t,e){var n=setTimeout(t,e);return n?.unref&&n?.unref(),n}function Sc(t,e,n){return Od.apply(this,arguments)}function Od(){return(Od=se((function*(t,e,n){var i;try{return yield Promise.race([t,new Promise(((r,s)=>{i=il((()=>{try{n?.(),r()}catch(o){s(o)}}),e)}))])}finally{clearTimeout(i)}}))).apply(this,arguments)}var Xp=t=>t instanceof Error,Bd={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},Qp=Bd.info;function Dd(t){if(gt(t))return{boolValue:t};if(typeof t=="number")return Number.isFinite(t)?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:{stringValue:String(t)};if(typeof t=="string")return{stringValue:t};if(U(t))return{arrayValue:{values:t.map((e=>Dd(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function Gr(t){var e=[];for(var n in t){var i=t[n];Ke(i)||C(i)||e.push({key:n,value:Dd(i)})}return e}function eg(t,e){var n=Bd[t.level||"info"]||Qp,i=n.text,r=n.number,s=String(Date.now())+"000000",o={};e.distinctId&&(o.posthogDistinctId=e.distinctId),e.sessionId&&(o.sessionId=e.sessionId),e.windowId&&(o["window.id"]=e.windowId),H(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),H(e.lastActivityTimestamp)||(o.lastActivityTimestamp=String(e.lastActivityTimestamp)),e.currentUrl&&(o["url.full"]=e.currentUrl),e.screenName&&(o["screen.name"]=e.screenName),e.appState&&(o["app.state"]=e.appState),e.activeFeatureFlags&&e.activeFeatureFlags.length>0&&(o.feature_flags=e.activeFeatureFlags);var a=k({},o,t.attributes||{}),l={timeUnixNano:s,observedTimeUnixNano:s,severityNumber:r,severityText:i,body:{stringValue:t.body},attributes:Gr(a)};return t.trace_id&&(l.traceId=t.trace_id),t.span_id&&(l.spanId=t.span_id),C(t.trace_flags)||(l.flags=t.trace_flags),l}function jd(t,e,n){return k({},t.resourceAttributes,{"service.name":t.serviceName||"unknown_service"},t.environment&&{"deployment.environment":t.environment},t.serviceVersion&&{"service.version":t.serviceVersion},{"telemetry.sdk.name":e,"telemetry.sdk.version":n})}function Ud(t,e,n,i){return{resourceLogs:[{resource:{attributes:Gr(e)},scopeLogs:[{scope:{name:n,version:i},logRecords:t}]}]}}let tg=class{constructor(t,e,n,i,r,s,o){var a;s===void 0&&(s=()=>Promise.resolve()),this._instance=t,this.Ne=e,this.rt=n,this.ut=i,this.ht=r,this.dt=s,this.vt=o,this.ct=null,this.ft=0,this.yt=0,this.bt=0,this._t=0,this.wt=!1,this.kt=e.maxBufferSize,this.xt=Math.max((a=e.maxQueueSize)!==null&&a!==void 0?a:e.maxBufferSize,e.maxBufferSize),this.St=e.flushIntervalMs,this.Ct=e.maxBatchRecordsPerPost,this.Mt=e.rateCapWindowMs,this.Tt=e.maxLogsPerInterval}reset(){this.Et(),this.ct=null,this.bt=0,this._t=0,this.wt=!1,this.ft=0,this.yt=0,this.Ct=this.Ne.maxBatchRecordsPerPost}onReconnect(){this.yt=0,this.It()}captureLog(t){if(!this._instance.isDisabled&&!this._instance.optedOut&&t!=null&&t.body){var e=this.Pt(t);if(e!==null)if(e.body){if(this.Rt()){var n={record:eg(e,this.ut())};this.ht((()=>this.At(n)))}}else this.rt.info("Log was rejected in beforeSend function")}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Log was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for log:",o),null}return i}Rt(){if(this.Tt===void 0)return!0;var t=Date.now(),e=t-this.bt;return this.Mt>e&&e>=0||(this.bt=t,this._t=0,this.wt=!1),this.Tt>this._t?(this._t++,!0):(this.wt||(this.rt.warn("captureLog dropping logs: exceeded "+this.Tt+" logs per "+this.Mt+"ms"),this.wt=!0),!1)}flush(){var t=this;return se((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return se((function*(){var e;t.Et();var n=(e=t._instance.getPersistedProperty(Ut.LogsQueue))!==null&&e!==void 0?e:[];if(n.length!==0)for(var i=n.length,r=0;n.length>0&&i>r;){var s,o;t.ft=0;var a=Math.min(n.length,t.Ct),l=n.slice(0,a),u=Ud(l.map((d=>d.record)),t.Lt(),(s=t.vt)!==null&&s!==void 0?s:t._instance.getLibraryId(),t._instance.getLibraryVersion()),c=yield t._instance.Ot(u);if(c.kind==="too-large"&&l.length>1)t.Ct=Math.max(1,Math.floor(l.length/2)),t.rt.warn("Received 413 when sending logs batch of size "+l.length+", reducing batch size to "+t.Ct);else if(c.kind==="retry-later"||(c.kind==="too-large"?t.rt.warn("Dropping a single log record after 413 with batch size 1 — the record is larger than the server cap and cannot be split further."):c.kind==="ok"&&t.Ne.maxBatchRecordsPerPost>t.Ct&&(t.Ct=Math.min(t.Ne.maxBatchRecordsPerPost,t.Ct+1)),yield t.Dt(l.length),n=(o=t._instance.getPersistedProperty(Ut.LogsQueue))!==null&&o!==void 0?o:[],r+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return se((function*(){var n,i=Math.max(0,t-e.ft),r=(n=e._instance.getPersistedProperty(Ut.LogsQueue))!==null&&n!==void 0?n:[];e._instance.setPersistedProperty(Ut.LogsQueue,r.slice(i)),yield e.dt()}))()}Lt(){return jd(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var n=(e=this._instance.getPersistedProperty(Ut.LogsQueue))!==null&&e!==void 0?e:[];this.xt>n.length||(n.shift(),this.ft++,this.rt.info("Logs queue is full, dropping oldest record.")),n.push(t),this._instance.setPersistedProperty(Ut.LogsQueue,n),this.kt>n.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=il((()=>{this.Nt=void 0,this.It()}),t))}qt(){var t=Math.min(Math.max(0,this.yt-1),6);return this.St*Math.pow(2,t)}jt(){var t=this._instance.getPersistedProperty(Ut.LogsQueue);return!!t&&t.length>0}shutdown(t){var e=this;return se((function*(){e.Et();var n=e.flush().catch((()=>{}));t!==void 0?yield Sc(n,t):yield n}))()}flushWithTimeout(t){var e=this;return se((function*(){var n=e.flush();yield Sc(n,t,(()=>{n.catch((()=>{}))}))}))()}It(){this.flush().then((()=>{this.yt=0}),(t=>{this.yt++,this.rt.error("PostHog logs flush failed:",t)})).finally((()=>{!this._instance.isDisabled&&this.jt()&&this.$t(this.qt())}))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}};var ho=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function xc(t){return String(t)+"000000"}function Ic(t,e,n,i){var r="";return i&&(r=Object.keys(i).sort().map((s=>JSON.stringify(s)+":"+JSON.stringify(i[s]))).join(",")),t+"\0"+e+"\0"+(n??"")+"\0"+r}let ng=class{constructor(t,e,n){this._instance=t,this.Ne=e,this.rt=n,this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Wt=0}count(t,e,n){e===void 0&&(e=1),this.Vt({name:t,type:"count",value:e,unit:n?.unit,attributes:n?.attributes})}gauge(t,e,n){this.Vt({name:t,type:"gauge",value:e,unit:n?.unit,attributes:n?.attributes})}histogram(t,e,n){this.Vt({name:t,type:"histogram",value:e,unit:n?.unit,attributes:n?.attributes})}flush(){var t=this,e=this.ct,n=(function(){var r=se((function*(){e&&(yield e.catch((()=>{}))),yield t.Zt()}));return function(){return r.apply(this,arguments)}})(),i=n().finally((()=>{this.ct===i&&(this.ct=null)}));return this.ct=i,i}drainWindow(){if(this.Bt.size===0)return null;var t=this.Bt;return this.Bt=new Map,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Gt(t)}reset(){this.Wt++,this.Et(),this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set}Vt(t){if(!this._instance.isDisabled&&!this._instance.optedOut){var e=this.Pt(t);if(e!==null)if(e.name&&typeof e.name=="string")if(typeof e.value=="number"&&Number.isFinite(e.value))if(e.type==="count"&&0>e.value)this.rt.warn("Dropping count '"+e.name+"': counters are monotonic, value must be >= 0");else{var n,i;try{n=e.attributes?k({},e.attributes):void 0,i=Ic(e.type,e.name,e.unit,n)}catch(o){return void this.rt.warn("Dropping metric '"+e.name+"': attributes could not be serialized",o)}var r=this.Bt.get(i);if(!r){if(!this.Qt())return;r={name:e.name,type:e.type,unit:e.unit,attributes:n,windowStartMs:Date.now()},this.Bt.set(i,r)}var s=this.Ut.get(e.name);s===void 0?this.Ut.set(e.name,e.type):s===e.type||this.zt.has(e.name)||(this.zt.add(e.name),this.rt.warn("Metric name '"+e.name+"' is already used as a "+s+"; recording it as a "+e.type+" too will blend both series in charts. Use a distinct name.")),this.Kt(r,e.value),this.$t()}else this.rt.warn("Dropping metric '"+e.name+"': value must be a finite number");else this.rt.warn("Dropping metric with empty name")}}Qt(){return this.Ne.maxSeriesPerFlush>this.Bt.size||(this.Ht||(this.Ht=!0,this.rt.warn("Metric series cap reached ("+this.Ne.maxSeriesPerFlush+" per flush window); dropping new series until the next flush. Reduce attribute cardinality.")),!1)}Kt(t,e){var n;switch(t.type){case"count":t.total=((n=t.total)!==null&&n!==void 0?n:0)+e;break;case"gauge":t.last=e;break;case"histogram":t.hist||(t.hist={count:0,sum:0,min:e,max:e,bucketCounts:new Array(ho.length+1).fill(0)});var i=t.hist;i.count+=1,i.sum+=e,i.min=Math.min(i.min,e),i.max=Math.max(i.max,e),i.bucketCounts[(function(r,s){for(var o=0;s.length>o;o++)if(s[o]>=r)return o;return s.length})(e,ho)]+=1}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Metric was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for metric:",o),null}return i}$t(){this.Nt||(this.Nt=il((()=>{this.Nt=void 0,this.flush().catch((t=>{this.rt.error("Metrics flush failed:",t)}))}),this.Ne.flushIntervalMs))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}Zt(){var t=this;return se((function*(){if(t.Bt.size!==0){var e=t.Bt;t.Bt=new Map,t.Ht=!1,t.Ut=new Map,t.zt=new Set;var n=t.Wt,i=yield t._instance.Jt(t.Gt(e));if(n===t.Wt)switch(i.kind){case"ok":return;case"retry-later":return t.Yt(e),void t.$t();case"too-large":return void t.rt.warn("Metrics batch exceeded the server size limit and was dropped");case"fatal":return void t.rt.error("Failed to send metrics batch:",i.error)}}}))()}Gt(t){return e=this.Xt(t),n=(function(s,o,a){return k({},s.resourceAttributes,{"service.name":s.serviceName||"unknown_service"},s.environment&&{"deployment.environment":s.environment},s.serviceVersion&&{"service.version":s.serviceVersion},{"telemetry.sdk.name":o,"telemetry.sdk.version":a})})(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion()),i=this._instance.getLibraryId(),r=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:Gr(n)},scopeMetrics:[{scope:{name:i,version:r},metrics:e}]}]};var e,n,i,r}Xt(t){var e=xc(Date.now()),n=new Map;for(var i of t.values()){var r,s=Ic(i.type,i.name,i.unit,void 0),o=n.get(s);o||(o=k({name:i.name},i.unit&&{unit:i.unit}),i.type==="count"?o.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:i.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:1,dataPoints:[]},n.set(s,o));var a=Gr((r=i.attributes)!==null&&r!==void 0?r:{}),l=xc(i.windowStartMs);if(i.type==="count"){var u,c={attributes:a,startTimeUnixNano:l,timeUnixNano:e,asDouble:(u=i.total)!==null&&u!==void 0?u:0};o.sum.dataPoints.push(c)}else if(i.type==="gauge"){var d,f={attributes:a,timeUnixNano:e,asDouble:(d=i.last)!==null&&d!==void 0?d:0};o.gauge.dataPoints.push(f)}else i.hist&&o.histogram.dataPoints.push({attributes:a,startTimeUnixNano:l,timeUnixNano:e,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:ho})}return Array.from(n.values())}Yt(t){var e,n;for(var i of t){var r=i[0],s=i[1],o=this.Bt.get(r);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,s.windowStartMs),o.type){case"count":o.total=((e=o.total)!==null&&e!==void 0?e:0)+((n=s.total)!==null&&n!==void 0?n:0);break;case"gauge":break;case"histogram":if(s.hist)if(o.hist){o.hist.count+=s.hist.count,o.hist.sum+=s.hist.sum,o.hist.min=Math.min(o.hist.min,s.hist.min),o.hist.max=Math.max(o.hist.max,s.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=s.hist.bucketCounts[a]}else o.hist=s.hist}else this.Qt()&&this.Bt.set(r,s)}}};var gr,kc,po;function ig(t){var e=globalThis._posthogChunkIds;if(e){var n=Object.keys(e);return po&&n.length===kc||(kc=n.length,po=n.reduce(((i,r)=>{gr||(gr={});var s=gr[r];if(s)i[s[0]]=s[1];else for(var o=t(r),a=o.length-1;a>=0;a--){var l=o[a],u=l?.filename,c=e[r];if(u&&c){i[u]=c,gr[r]=[u,c];break}}return i}),{})),po}}class rg{constructor(e,n,i){i===void 0&&(i=[]),this.coercers=e,this.stackParser=n,this.modifiers=i}buildFromUnknown(e,n){n===void 0&&(n={});var i=n&&n.mechanism||{handled:!0,type:"generic"},r=this.buildCoercingContext(i,n,0).apply(e),s=this.buildParsingContext(n),o=this.parseStacktrace(r,s);return{$exception_list:this.convertToExceptionList(o,i),$exception_level:"error"}}modifyFrames(e){var n=this;return se((function*(){for(var i of e)i.stacktrace&&i.stacktrace.frames&&U(i.stacktrace.frames)&&(i.stacktrace.frames=yield n.applyModifiers(i.stacktrace.frames));return e}))()}coerceFallback(e){var n;return{type:"Error",value:"Unknown error",stack:(n=e.syntheticException)==null?void 0:n.stack,synthetic:!0}}parseStacktrace(e,n){var i,r;return e.cause!=null&&(i=this.parseStacktrace(e.cause,n)),e.stack!=""&&e.stack!=null&&(r=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?n.skipFirstLines:0),n.chunkIdMap)),k({},e,{cause:i,stack:r})}applyChunkIds(e,n){return e.map((i=>(i.filename&&n&&(i.chunk_id=n[i.filename]),i)))}applyCoercers(e,n){for(var i of this.coercers)if(i.match(e))return i.coerce(e,n);return this.coerceFallback(n)}applyModifiers(e){var n=this;return se((function*(){var i=e;for(var r of n.modifiers)i=yield r(i);return i}))()}convertToExceptionList(e,n){var i,r,s,o={type:e.type,value:e.value,mechanism:{type:(i=n.type)!==null&&i!==void 0?i:"generic",handled:(r=n.handled)===null||r===void 0||r,synthetic:(s=e.synthetic)!==null&&s!==void 0&&s}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,k({},n,{handled:!0}))),a}buildParsingContext(e){var n;return{chunkIdMap:ig(this.stackParser),skipFirstLines:(n=e.skipFirstLines)!==null&&n!==void 0?n:1}}buildCoercingContext(e,n,i){i===void 0&&(i=0);var r=(s,o)=>{if(4>=o){var a=this.buildCoercingContext(e,n,o);return this.applyCoercers(s,a)}};return k({},n,{syntheticException:i==0?n.syntheticException:void 0,mechanism:e,apply:s=>r(s,i),next:s=>r(s,i+1)})}}var ni="?";function Qo(t,e,n,i,r){var s={platform:t,filename:e,function:n===""?ni:n,in_app:!0};return C(i)||(s.lineno=i),C(r)||(s.colno=r),s}var Hd=(t,e)=>{var n=t.indexOf("safari-extension")!==-1,i=t.indexOf("safari-web-extension")!==-1;return n||i?[t.indexOf("@")!==-1?t.split("@")[0]:ni,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},sg=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,og=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,ag=/\((\S*)(?::(\d+))(?::(\d+))\)/,lg=(t,e)=>{var n=sg.exec(t);if(n)return Qo(e,n[1],ni,+n[2],+n[3]);var i=og.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var r=ag.exec(i[2]);r&&(i[2]=r[1],i[3]=r[2],i[4]=r[3])}var s=Hd(i[1]||ni,i[2]);return Qo(e,s[1],s[0],i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},cg=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,ug=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,dg=(t,e)=>{var n=cg.exec(t);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){var i=ug.exec(n[3]);i&&(n[1]=n[1]||"eval",n[3]=i[1],n[4]=i[2],n[5]="")}var r=n[3],s=n[1]||ni,o=Hd(s,r);return Qo(e,r=o[1],s=o[0],n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},Cc=/\(error: (.*)\)/;class fg{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,n){var i=X(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:i?e.stack:void 0,cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var n=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?n+": "+e.message:n}isDOMException(e){return Hr(e,"DOMException")}isDOMError(e){return Hr(e,"DOMError")}}class hg{match(e){return(function(n){switch({}.toString.call(n)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return md(n,Error)}})(e)}coerce(e,n){return{type:this.getType(e),value:this.getMessage(e,n),stack:this.getStack(e),cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,n){var i=e.message;return String(i.error&&typeof i.error.message=="string"?i.error.message:i)}getStack(e){return e.stacktrace||e.stack||void 0}}class pg{constructor(){}match(e){return!!Hr(e,"ErrorEvent")&&(e.error!=null||this.fe(e))}coerce(e,n){var i;if(e.error!=null)return n.apply(e.error);var r=n.apply(e.message);return k({},r,{stack:(i=this.pe(e))!==null&&i!==void 0?i:r.stack,synthetic:!0})}fe(e){return X(e.message)&&e.message.length>0}pe(e){var n=e;if(X(n.filename)&&n.filename.length>0){var i,r,s=(i=n.lineno)!==null&&i!==void 0?i:0,o=(r=n.colno)!==null&&r!==void 0?r:0;return`Error + at `+n.filename+":"+s+":"+o}}}var gg=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class mg{match(e){return typeof e=="string"}coerce(e,n){var i,r=this.getInfos(e),s=r[0],o=r[1];return{type:s??"Error",value:o??e,stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}getInfos(e){var n="Error",i=e,r=e.match(gg);return r&&(n=r[1],i=r[2]),[n,i]}}var vg=["fatal","error","warning","log","info","debug"];function Wd(t,e){e===void 0&&(e=40);var n=Object.keys(t);if(n.sort(),!n.length)return"[object has no keys]";for(var i=n.length;i>0;i--){var r=n.slice(0,i).join(", ");if(e>=r.length)return i===n.length?r:r.length>e?r.slice(0,e)+"...":r}return""}class _g{match(e){return typeof e=="object"&&e!==null}coerce(e,n){var i,r,s=this.getErrorPropertyFromObject(e);return s?n.apply(s):{type:this.getType(e),value:this.getValue(e),stack:(i=this.getStack(e))!==null&&i!==void 0?i:(r=n.syntheticException)==null?void 0:r.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return Xa(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var n="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(n+=" with message: '"+e.message+"'"),n}if("message"in e&&typeof e.message=="string")return e.message;var i=this.getObjectClassName(e);return(i&&i!=="Object"?"'"+i+"'":"Object")+" captured as exception with keys: "+Wd(e)}isSeverityLevel(e){return X(e)&&!Ko(e)&&vg.indexOf(e)>=0}getStack(e){try{return X(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:X(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(var n in e)if({}.hasOwnProperty.call(e,n)){var i=e[n];if(Xp(i))return i}}getObjectClassName(e){try{var n=Object.getPrototypeOf(e);return n?n.constructor.name:void 0}catch{return}}}class yg{match(e){return Xa(e)}coerce(e,n){var i,r=e.constructor.name;return{type:r,value:r+" captured as exception with keys: "+Wd(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class wg{match(e){return gd(e)}coerce(e,n){var i;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class bg{match(e){return Hr(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Xa(e))return!1;try{var n=e.detail;return n!=null&&typeof n=="object"&&"reason"in n}catch{return!1}}coerce(e,n){var i,r=this.getUnhandledRejectionReason(e);return gd(r)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(r),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}:n.apply(r)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}}var Kr="$message",Yr="$timestamp",Eg=new Set([Kr,Yr]),go={enabled:!0,max_bytes:32768};function Jr(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:go.enabled,max_bytes:xg(t.max_bytes,go.max_bytes)}:k({},go)}class Sg{constructor(e){this.Ke=[],this.Je=0,this.Ne=Jr(e)}setConfig(e){this.Ne=Jr(e),this.Xe()}add(e){var n=(function(r){var s;try{s=fd(r)}catch{return}try{var o=JSON.parse(s);if(!he(o))return;var a=o,l=a[Kr],u=a[Yr];return!X(l)||l.trim().length===0||!X(u)&&!ke(u)?void 0:{step:a,json:s}}catch{return}})(e);if(n){var i=(function(r){if(typeof TextEncoder<"u")return new TextEncoder().encode(r).length;for(var s=encodeURIComponent(r),o=0,a=0;s.length>a;a++)s[a]==="%"?(o+=1,a+=2):o+=1;return o})(n.json);i>this.Ne.max_bytes||(this.Ke.push({step:n.step,bytes:i}),this.Je+=i,this.Xe())}}getAttachable(){return this.Ke.map((e=>e.step))}clear(){this.Ke=[],this.Je=0}size(){return this.Ke.length}Xe(){for(;this.Je>this.Ne.max_bytes&&this.Ke.length>0;){var e=this.Ke.shift();e&&(this.Je-=e.bytes)}}}function xg(t,e){if(!ke(t)||t===1/0||t===-1/0)return e;var n=Math.floor(t);return 0>n?e:n}var qd=function(t,e){var n=(e===void 0?{}:e).debugEnabled,i={k(r){if(w&&(ne.DEBUG||w.POSTHOG_DEBUG||n)&&!C(w.console)&&w.console){for(var s=("__rrweb_original__"in w.console[r])?w.console[r].__rrweb_original__:w.console[r],o=arguments.length,a=new Array(o>1?o-1:0),l=1;o>l;l++)a[l-1]=arguments[l];s(t,...a)}},debug(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("debug",...s)},info(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("log",...s)},warn(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("warn",...s)},error(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("error",...s)},critical(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];console.error(t,...s)},uninitializedWarning(r){i.error("You must initialize PostHog before calling "+r)},createLogger:(r,s)=>qd(t+" "+r,s)};return i},A=qd("[PostHog.js]"),pe=A.createLogger,Ig=pe("[ExternalScriptsLoader]"),mo=(t,e,n)=>{if(t.config.disable_external_dependency_loading)return Ig.warn(e+" was requested but loading of external scripts is disabled."),n("Loading of external scripts is disabled");var i=F?.querySelectorAll("script");if(i){for(var r,s=function(){if(i[o].src===e){var l=i[o];return l.__posthog_loading_callback_fired?{v:n()}:(l.addEventListener("load",(u=>{l.__posthog_loading_callback_fired=!0,n(void 0,u)})),l.onerror=u=>n(u),{v:void 0})}},o=0;i.length>o;o++)if(r=s())return r.v}var a=()=>{if(!F)return n("document not found");var l=F.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=d=>{l.__posthog_loading_callback_fired=!0,n(void 0,d)},l.onerror=d=>n(d),t.config.prepare_external_dependency_script&&(l=t.config.prepare_external_dependency_script(l)),!l)return n("prepare_external_dependency_script returned null");if(t.config.external_scripts_inject_target==="head")F.head.appendChild(l);else{var u,c=F.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):F.body.appendChild(l)}};F!=null&&F.body?a():F?.addEventListener("DOMContentLoaded",a)};B.__PosthogExtensions__=B.__PosthogExtensions__||{},B.__PosthogExtensions__.loadExternalDependency=(t,e,n)=>{if(e!=="remote-config"){var i;if(t.config.strict_script_versioning)i=t.requestRouter.endpointFor("assets","/static/"+t.version+"/"+e+".js");else{var r="/static/"+e+".js?v="+t.version;if(e==="toolbar"){var s=3e5;r=r+"&t="+Math.floor(Date.now()/s)*s}i=t.requestRouter.endpointFor("assets",r)}mo(t,i,n)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");mo(t,o,n)}},B.__PosthogExtensions__.loadSiteApp=(t,e,n)=>{var i=t.requestRouter.endpointFor("api",e);mo(t,i,n)};ne.DEBUG=!1,ne.LIB_VERSION="1.415.7",ne.LIB_NAME="web";var zd="$people_distinct_id",Yi="$device_id",vo="$device_model",Fi="__alias",Ri="__timers",ea="$autocapture_disabled_server_side",ta="$heatmaps_enabled_server_side",na="$exception_capture_enabled_server_side",ia="$error_tracking_suppression_rules",ra="$error_tracking_capture_extension_exceptions",sa="$web_vitals_enabled_server_side",rl="$dead_clicks_enabled_server_side",sl="$product_tours_enabled_server_side",oa="$web_vitals_allowed_metrics",An="$session_recording_remote_config",Vd="$replay_sample_rate",Gd="$replay_override_sampling",Kd="$replay_override_linked_flag",Yd="$replay_override_url_trigger",Jd="$replay_override_event_trigger",Kn="$sesid",ol="$session_is_sampled",Sn="$enabled_feature_flags",Ti="$active_feature_flags",Ar="$early_access_features",aa="$feature_flag_details",$i="$feature_flag_payloads",Pr="$feature_flag_request_id",Zr="$minimal_flag_called_events",It="$override_feature_flags",xn="$override_feature_flag_payloads",jt="$stored_person_properties",In="$stored_group_properties",la="$surveys",Xr="$surveys_loaded_at",ca="$surveys_activated",Fr="$surveys_activated_session",Rr="$surveys_activated_timestamps",Mi="ph_product_tours",Cn="$flag_call_reported",Li="$flag_call_reported_session_id",Tr="$feature_flag_errors",ji="$feature_flag_evaluated_at",ot="$user_state",ua="$client_session_props",da="$capture_rate_limit",fa="$initial_campaign_params",ha="$initial_referrer_info",Qr="$initial_person_info",es="$epp",mr="$posthog_cookieless",Zd="$cookieless_mode",Xd="$sdk_debug_extensions_init_method",Qd="$sdk_debug_extensions_init_time_ms",ef="$sdk_debug_recording_script_not_loaded",al="PostHog loadExternalDependency extension not found.",kn="on_reject",Wt="always",Un="anonymous",vn="identified",pa="identified_only",ts="visibilitychange",ns="beforeunload",Vn="$pageview",_o="$pageleave",yo="$identify",Ac="$groupidentify";function vr(t,e){U(t)&&t.forEach(e)}function ie(t,e){if(!H(t))if(U(t))t.forEach(e);else if(Np(t))t.forEach(((i,r)=>e(i,r)));else for(var n in t)pd.call(t,n)&&e(t[n],n)}var fe=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;e>i;i++)n[i-1]=arguments[i];for(var r of n)for(var s in r)r[s]!==void 0&&(t[s]=r[s]);return t};function $r(t){for(var e=Object.keys(t),n=e.length,i=new Array(n);n--;)i[n]=[e[n],t[e[n]]];return i}var Pc=function(t){try{return t()}catch{return}},kg=function(t){return function(){try{for(var e=arguments.length,n=new Array(e),i=0;e>i;i++)n[i]=arguments[i];return t.apply(this,n)}catch(r){A.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),A.critical(r)}}},ll=function(t){var e={};return ie(t,(function(n,i){(X(n)&&n.length>0||ke(n))&&(e[i]=n)})),e},Cg=["herokuapp.com","vercel.app","netlify.app"];function Ag(t){var e=t?.hostname;if(!X(e))return!1;var n=e.split(".").slice(-2).join(".");for(var i of Cg)if(n===i)return!1;return!0}function ve(t,e,n,i){var r=i??{},s=r.capture,o=r.passive;t?.addEventListener(e,n,{capture:s!==void 0&&s,passive:o===void 0||o})}function ga(t){return t.name==="ph_toolbar_internal"}var tf=t=>{if(F){try{for(var e=t+"=",n=F.cookie.split(";").filter((s=>s.length)),i=0;n.length>i;i++){for(var r=n[i];r.charAt(0)==" ";)r=r.substring(1,r.length);if(r.indexOf(e)===0)return decodeURIComponent(r.substring(e.length,r.length))}}catch{}return null}};Math.trunc||(Math.trunc=function(t){return 0>t?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return ke(t)&&isFinite(t)&&Math.floor(t)===t});class is{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,n,i,r){if(!Number.isInteger(e)||!Number.isInteger(n)||!Number.isInteger(i)||!Number.isInteger(r)||0>e||0>n||0>i||0>r||e>0xffffffffffff||n>4095||i>1073741823||r>4294967295)throw new RangeError("invalid field value");var s=new Uint8Array(16);return s[0]=e/Math.pow(2,40),s[1]=e/Math.pow(2,32),s[2]=e/Math.pow(2,24),s[3]=e/Math.pow(2,16),s[4]=e/256,s[5]=e,s[6]=112|n>>>8,s[7]=n,s[8]=128|i>>>24,s[9]=i>>>16,s[10]=i>>>8,s[11]=i,s[12]=r>>>24,s[13]=r>>>16,s[14]=r>>>8,s[15]=r,new is(s)}toString(){for(var e="",n=0;this.bytes.length>n;n++)e=e+(this.bytes[n]>>>4).toString(16)+(15&this.bytes[n]).toString(16),n!==3&&n!==5&&n!==7&&n!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new is(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var n=0;16>n;n++){var i=this.bytes[n]-e.bytes[n];if(i!==0)return Math.sign(i)}return 0}}class Pg{generate(){var e=this.generateOrAbort();if(!C(e))return e;this.S=0;var n=this.generateOrAbort();if(C(n))throw new Error("Could not generate UUID after timestamp reset");return n}generateOrAbort(){var e=Date.now();if(e>this.S)this.S=e,this.C();else{if(this.S>=e+1e4)return;this.I++,this.I>4398046511103&&(this.S++,this.C())}return is.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 Fg}}var Fc,nf=t=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;t.length>e;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};w&&!C(w.crypto)&&crypto.getRandomValues&&(nf=t=>crypto.getRandomValues(t));class Fg{nextUint32(){return this.R.length>this.O||(nf(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var Ht=()=>Rg().toString(),Rg=()=>(Fc||(Fc=new Pg)).generate(),yi="",Tg=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,qt={N:()=>!!F,j(t){A.error("cookieStore error: "+t)},P:tf,H(t){var e;try{e=JSON.parse(qt.P(t))||{}}catch{}return e},F(t,e,n,i,r){if(!F)return!1;try{var s="",o="",a=(function(c,d){if(d){var f=(function(p,g){if(g===void 0&&(g=F),yi)return yi;if(!g||["localhost","127.0.0.1"].includes(p))return"";for(var m=p.split("."),v=Math.min(m.length,8),S="dmn_chk_"+Ht();!yi&&v--;){var b=m.slice(v).join("."),_=S+"=1;domain=."+b+";path=/";g.cookie=_+";max-age=3",g.cookie.includes(S)&&(g.cookie=_+";max-age=0",yi=b)}return yi})(c);if(!f){var h=(p=>{var g=p.match(Tg);return g?g[0]:""})(c);h!==f&&A.info("Warning: cookie subdomain discovery mismatch",h,f),f=h}return f?"; domain=."+f:""}return""})(F.location.hostname,i);if(n){var l=new Date;l.setTime(l.getTime()+864e5*n),s="; expires="+l.toUTCString()}r&&(o="; secure");var u=t+"="+encodeURIComponent(JSON.stringify(e))+s+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&A.warn("cookieStore warning: large cookie, len="+u.length),F.cookie=u,!0}catch{return!1}},q(t,e){if(F!=null&&F.cookie)try{qt.F(t,"",-1,e)}catch{return}}},wo=null,le={N(){if(!Ke(wo))return wo;var t=!0;if(C(w))t=!1;else try{var e="__mplssupport__";le.F(e,"xyz"),le.P(e)!=='"xyz"'&&(t=!1),le.q(e)}catch{t=!1}return t||A.error("localStorage unsupported; falling back to cookie store"),wo=t,t},j(t){A.error("localStorage error: "+t)},P(t){try{return w?.localStorage.getItem(t)}catch(e){le.j(e)}return null},H(t){try{return JSON.parse(le.P(t))||{}}catch{}return null},F(t,e){try{return w?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(n){le.j(n)}return!1},q(t){try{w?.localStorage.removeItem(t)}catch(e){le.j(e)}}},$g=[Yi,"distinct_id",Kn,ol,es,Qr,ot],_r={},Mg={N:()=>!0,j(t){A.error("memoryStorage error: "+t)},P:t=>_r[t]||null,H:t=>_r[t]||null,F:(t,e)=>(_r[t]=e,!0),q(t){delete _r[t]}},_n=null,be={N(){if(!Ke(_n))return _n;if(_n=!0,C(w))_n=!1;else try{var t="__support__";be.F(t,"xyz"),be.P(t)!=='"xyz"'&&(_n=!1),be.q(t)}catch{_n=!1}return _n},j(t){A.error("sessionStorage error: ",t)},P(t){try{return w?.sessionStorage.getItem(t)}catch(e){be.j(e)}return null},H(t){try{return JSON.parse(be.P(t))||null}catch{}return null},F(t,e){try{return w?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(n){be.j(n)}return!1},q(t){try{w?.sessionStorage.removeItem(t)}catch(e){be.j(e)}}};class Lg{constructor(e){this._instance=e}get Ne(){return this._instance.config}get consent(){return this.ti()?0:this.ei}isOptedOut(){return this.Ne.cookieless_mode===Wt||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===kn}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===0}isRejected(){return this.consent===0||this.consent===-1&&this.Ne.opt_out_capturing_by_default}optInOut(e){this.ii.F(this.ri,e?1:0,this.Ne.cookie_expiration,this.Ne.cross_subdomain_cookie,this.Ne.secure_cookie)}reset(){this.ii.q(this.ri,this.Ne.cross_subdomain_cookie)}get ri(){var e=this._instance.config,n=e.token,i=e.opt_out_capturing_cookie_prefix;return e.consent_persistence_name||(i?i+n:"__ph_opt_in_out_"+n)}get ei(){var e=this.ii.P(this.ri);return uo(e)?1:j(jp,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,n=e==="localStorage"?le:qt;if(!this.ni||this.ni!==n){this.ni=n;var i=e==="localStorage"?qt:le;i.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(uo(i.P(this.ri))),i.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[Ue?.doNotTrack,Ue?.msDoNotTrack,B.doNotTrack].some((e=>uo(e)))}}function rf(t,e){var n,i=t==null||(n=t.config)==null?void 0:n.get_current_url;if(!De(i))return e;try{var r=i(e);return X(r)&&r?r:e}catch(s){return A.error("Error in get_current_url, falling back to window.location.href",s),e}}var sf="__POSTHOG_TOOLBAR__",Ng=1,Og=3,Bg=11;function Rc(t){return t instanceof Element&&(t.id===sf||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function hn(t){return!!t&&t.nodeType===Ng}function Qe(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function of(t){return!!t&&t.nodeType===Og}function af(t){return!!t&&t.nodeType===Bg&&hn(t.host)}var lf=1e3;function cl(t){return t?xs(t).split(/\s+/):[]}function Tc(t,e){var n=(function(i){var r,s=w==null||(r=w.location)==null?void 0:r.href;return C(s)?void 0:rf(i,s)})(e);return!!(n&&t&&t.some((i=>n.match(i))))}function rs(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 cl(e)}function cf(t){return H(t)?null:xs(t).split(/(\s+)/).filter((e=>Ui(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function Ji(t){var e="";return va(t)&&!hf(t)&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;of(n)&&n.textContent&&(e+=(i=cf(n.textContent))!==null&&i!==void 0?i:"")})),xs(e)}function bo(t){var e;return C(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var ul=["a","button","form","input","select","textarea","label"];function ma(t,e){if(C(e))return!0;var n,i=function(s){if(e.some((o=>(function(a,l){var u=a.matches||a.matchesSelector||a.msMatchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.oMatchesSelector;try{return!!u&&u.call(a,l)}catch{return!1}})(s,o))))return{v:!0}};for(var r of t)if(n=i(r))return n.v;return!1}function uf(t){var e=t.parentNode;return!(!e||!hn(e))&&e}var Dg=[".ph-no-autocapture","[data-ph-no-autocapture]"],df=["next","previous","prev",">","<"],jg=[...df,"+","-","−","–"],$c=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,Mc=[".ph-no-rageclick",".ph-no-capture"],Ug=["","text","search","email","password","url","tel","number"];function Lc(t,e){if(!w||dl(t))return!1;var n,i,r,s,o;if(gt(e)?(n=!!e&&Mc,i=void 0,r=!1):(n=(s=e?.css_selector_ignorelist)!==null&&s!==void 0?s:Mc,i=e?.content_ignorelist,r=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),n===!1||r&&(function(l){return!(!l||!hn(l))&&(!!Qe(l,"textarea")||(Qe(l,"input")?j(Ug,(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=ff(t,!1).targetElementList;return!(function(l,u){if(l===!1||C(l))return!1;var c;if(l===!0)c=df;else{if(!U(l))return!1;if(l.length>10)return A.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var f=d.safeText,h=d.ariaLabel;return c.some((p=>$c(f,p)||$c(h,p)))}))})(i,a.map((l=>{var u;return{safeText:Ji(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!ma(a,n)}var dl=t=>!t||Qe(t,"html")||!hn(t),ff=(t,e)=>{if(!w||dl(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,i=[t],r=t;r.parentNode&&!Qe(r,"body");)if(af(r.parentNode))i.push(r.parentNode.host),r=r.parentNode.host;else{var s=uf(r);if(!s)break;if(e||ul.indexOf(s.tagName.toLowerCase())>-1)n=!0;else try{var o=w.getComputedStyle(s);o&&o.getPropertyValue("cursor")==="pointer"&&(n=!0)}catch{}i.push(s),r=s}return{parentIsUsefulElement:n,targetElementList:i}};function va(t){for(var e=new Set,n=0,i=t;i.parentNode&&!Qe(i,"body");i=i.parentNode){if(n++>=lf||e.has(i))return!1;e.add(i);var r=rs(i);if(j(r,"ph-sensitive")||j(r,"ph-no-capture"))return!1}if(j(rs(t),"ph-include"))return!0;var s=t.type||"";if(X(s))switch(s.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!X(o)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(o.replace(/[^a-zA-Z0-9]/g,""))}function hf(t){return!!(Qe(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||Qe(t,"select")||Qe(t,"textarea")||t.getAttribute("contenteditable")==="true")}var Nc=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}))$"),Oc=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,Hg=[16,15,14,13],Wg=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),Bc=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),Dc=/[0-9A-Za-z_]/;function qg(t){for(var e=0,n=!1,i=t.length-1;i>=0;i--){var r=t.charCodeAt(i)-48;n&&(r*=2)>9&&(r-=9),e+=r,n=!n}return e%10==0}function Ui(t,e){if(e===void 0&&(e=!0),H(t))return!1;if(X(t)){t=xs(t);var n=e?Nc.test((t||"").replace(/[- ]/g,"")):(function(r){var s;for(Oc.lastIndex=0;s=Oc.exec(r);){var o=s[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of Hg){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(Nc.test(d)&&qg(d))return!0}}}return!1})(t);if(n)return!1;var i=e?Wg.test(t):(function(r){var s;for(Bc.lastIndex=0;s=Bc.exec(r);){var o=s[1],a=s[3];if(!(o&&a&&Dc.test(o)&&Dc.test(a)))return!0}return!1})(t);if(i)return!1}return!0}function jc(t){var e=Ji(t);return Ui(e=(e+" "+pf(t)).trim())?e:""}function pf(t){var e="";return t&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;if(n&&((i=n.tagName)==null?void 0:i.toLowerCase())==="span")try{var r=Ji(n);e=(e+" "+r).trim(),n.childNodes&&n.childNodes.length&&(e=(e+" "+pf(n)).trim())}catch(s){A.error("[AutoCapture]",s)}})),e}function Uc(t){return t.replace(/"|\\"/g,'\\"')}function zg(t){var e=t.attr__class;if(e)return U(e)?e:cl(e)}var yr=pe("[Dead Clicks]"),Vg=()=>!0,Gg=t=>{var e,n=!((e=t.instance.persistence)==null||!e.get_property(rl)),i=t.instance.config.capture_dead_clicks;return gt(i)?i:!!he(i)||n};class Hc{get lazyLoadedDeadClicksAutocapture(){return this.si}constructor(e,n,i){this.instance=e,this.isEnabled=n,this.onCapture=i,this.startIfEnabledOrStop()}onRemoteConfig(e){if(e.ok){var n=e.config;"captureDeadClicks"in n&&(this.instance.persistence&&this.instance.persistence.register({[rl]:n.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var n,i;(n=B.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture?e():(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"dead-clicks-autocapture",(r=>{r?yr.error("failed to load script",r):e()}))}oi(){var e;if(F){if(!this.si&&(e=B.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var n=he(this.instance.config.capture_dead_clicks)?k({},this.instance.config.capture_dead_clicks):{};n.__onCapture=this.onCapture,this.onCapture&&(n.capture_dead_swipes=!1),this.si=B.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.si.start(F),yr.info("starting...")}}else yr.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,yr.info("stopping..."))}}var Eo=pe("[SegmentIntegration]"),gf="posthog-js";function mf(t,e){var n=e===void 0?{}:e,i=n.organization,r=n.projectId,s=n.prefix,o=n.severityAllowList,a=o===void 0?["error"]:o,l=n.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,f,h,p,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var v,S=((d=c.exception)==null?void 0:d.values)||[],b=S.map((x=>k({},x,{stacktrace:x.stacktrace?k({},x.stacktrace,{type:"raw",frames:(x.stacktrace.frames||[]).map((I=>k({},I,{platform:"web:javascript"})))}):void 0}))),_={$exception_message:((f=S[0])==null?void 0:f.value)||c.message,$exception_type:(h=S[0])==null?void 0:h.type,$exception_level:c.level,$exception_list:b,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((p=S[0])==null?void 0:p.value)||c.message,$sentry_exception_type:(g=S[0])==null?void 0:g.type,$sentry_tags:c.tags};return i&&r&&(_.$sentry_url=(s||"https://sentry.io/organizations/")+i+"/issues/?project="+r+"&query="+c.event_id),u&&((v=t.exceptions)==null||v.sendExceptionEvent(_)),c}}class Kg{constructor(e,n,i,r,s,o){this.name=gf,this.setupOnce=function(a){a(mf(e,{organization:n,projectId:i,prefix:r,severityAllowList:s,sendExceptionsToPostHog:o==null||o}))}}}class Wc{constructor(e){this.li=(n,i,r)=>{r&&(r.noSessionId||r.activityTimeout||r.sessionPastMaximumLength||r.crossTabAdoption)&&(A.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:n,changeReason:r}),this.ui=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.hi()}hi(){var e;this.di=(e=this._instance.sessionManager)==null?void 0:e.onSessionId(this.li)}destroy(){var e;(e=this.di)==null||e.call(this),this.di=void 0}doPageView(e,n){var i,r=this.vi(e,n);return this.ui={pathname:(i=w?.location.pathname)!==null&&i!==void 0?i:"",pageViewId:n,timestamp:e},this._instance.scrollManager.resetContext(),r}doPageLeave(e){var n;return this.vi(e,(n=this.ui)==null?void 0:n.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.ui)==null?void 0:e.pageViewId}}vi(e,n){var i=this.ui;if(!i)return{$pageview_id:n};var r={$pageview_id:n,$prev_pageview_id:i.pageViewId},s=this._instance.scrollManager.getContext();if(s&&!this._instance.config.disable_scroll_properties){var o=s.maxScrollHeight,a=s.lastScrollY,l=s.maxScrollY,u=s.maxContentHeight,c=s.lastContentY,d=s.maxContentY;if(!(C(o)||C(a)||C(l)||C(u)||C(c)||C(d))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),d=Math.ceil(d);var f=o>1?At(a/o,0,1,A):1,h=o>1?At(l/o,0,1,A):1,p=u>1?At(c/u,0,1,A):1,g=u>1?At(d/u,0,1,A):1;r=fe(r,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:f,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:h,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:p,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return i.pathname&&(r.$prev_pageview_pathname=i.pathname),i.timestamp&&(r.$prev_pageview_duration=(e.getTime()-i.timestamp.getTime())/1e3),r}}var So=["flags","surveys"],Yg={[zd]:{exposure:"hidden"},[Fi]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[Ri]:{exposure:"hidden"},[ea]:{exposure:"event"},[ta]:{exposure:"hidden"},[na]:{exposure:"event"},[ia]:{exposure:"hidden"},[ra]:{exposure:"event"},[sa]:{exposure:"event"},[rl]:{exposure:"event"},[sl]:{exposure:"hidden"},[oa]:{exposure:"event"},[An]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[Kn]:{exposure:"hidden"},[ol]:{exposure:"event"},[Vd]:{exposure:"event",shouldSkipFromEventProperties:t=>Ke(t)},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},$sess_rec_flush_size:{exposure:"hidden"},[Sn]:{exposure:"hidden",storageGroup:"flags"},[Ti]:{exposure:"hidden",storageGroup:"flags"},[Ar]:{exposure:"hidden"},[aa]:{exposure:"hidden",storageGroup:"flags"},[$i]:{exposure:"hidden",storageGroup:"flags"},[Pr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[Zr]:{exposure:"hidden",storageGroup:"flags"},[It]:{exposure:"hidden"},[xn]:{exposure:"hidden"},[jt]:{exposure:"hidden"},[In]:{exposure:"hidden"},[la]:{exposure:"hidden",storageGroup:"surveys"},[Xr]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[ca]:{exposure:"event"},[Fr]:{exposure:"hidden"},[Rr]:{exposure:"hidden"},[Mi]:{exposure:"hidden"},$product_tours_activated:{exposure:"hidden"},$product_tours_activated_session:{exposure:"hidden"},$conversations_widget_session_id:{exposure:"event"},$conversations_ticket_id:{exposure:"event"},$conversations_widget_state:{exposure:"event"},$conversations_user_traits:{exposure:"event"},[Cn]:{exposure:"hidden"},[Li]:{exposure:"hidden"},[Tr]:{exposure:"hidden"},[ji]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[ot]:{exposure:"hidden"},[ua]:{exposure:"hidden"},[da]:{exposure:"hidden"},[fa]:{exposure:"hidden"},[ha]:{exposure:"hidden"},[Qr]:{exposure:"hidden"},[es]:{exposure:"hidden"},[Gd]:{exposure:"event"},[Kd]:{exposure:"event"},[Yd]:{exposure:"event"},[Jd]:{exposure:"event"},[Xd]:{exposure:"event"},[Qd]:{exposure:"event"},[ef]:{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"}},Jg=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],yn=t=>{var e=Yg[t];if(e)return e;for(var n of Jg){var i=n[1];if(t.indexOf(n[0])===0)return i}},Yn=(t,e)=>{try{return JSON.stringify(t,((n,i)=>typeof i=="bigint"?i.toString():i),e)}catch{return fd(t)}},ss=t=>{var e=F?.createElement("a");return C(e)?null:(e.href=t,e)},ii=function(t,e){for(var n,i=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),r=0;i.length>r;r++){var s=i[r].split("=");if(s[0]===e){n=s;break}}if(!U(n)||2>n.length)return"";var o=n[1];try{o=decodeURIComponent(o)}catch{A.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},Zi=function(t,e,n){if(!t||!e||!e.length)return t;for(var i=t.split("#"),r=i[1],s=(i[0]||"").split("?"),o=s[1],a=s[0],l=(o||"").split("&"),u=[],c=0;l.length>c;c++){var d=l[c].split("=");U(d)&&(e.includes(d[0])?u.push(d[0]+"="+n):u.push(l[c]))}var f=a;return o!=null&&(f+="?"+u.join("&")),r!=null&&(f+="#"+r),f},os=function(t,e){var n=t.match(new RegExp(e+"=([^&]*)"));return n?n[1]:null},vf=(t,e)=>t>=e&&cd(),_f=(t,e,n,i)=>{if(t===0){if(cd()){var r=e+1;return r===n&&i(),r}return e}return 0},wr="https?://(.*)",ri=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Zg=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...ri],Xi="",Xg=["li_fat_id"];function yf(t,e,n){if(!F)return{};var i,r=e?[...ri,...n||[]]:[],s=wf(Zi(F.URL,r,Xi),t),o=(i={},ie(Xg,(function(a){var l=tf(a);i[a]=l||null})),i);return fe(o,s)}function wf(t,e){var n=Zg.concat(e||[]),i={};return ie(n,(function(r){var s=ii(t,r);i[r]=s||null})),i}function bf(t){var e=(function(s){return s?s.search(wr+"google.([^/?]*)")===0?"google":s.search(wr+"bing.com")===0?"bing":s.search(wr+"yahoo.com")===0?"yahoo":s.search(wr+"duckduckgo.com")===0?"duckduckgo":null:null})(t),n=e!="yahoo"?"q":"p",i={};if(!Ke(e)){i.$search_engine=e;var r=F?ii(F.referrer,n):"";r.length&&(i.ph_keyword=r)}return i}function qc(){return navigator.language||navigator.userLanguage}var as="$direct";function Ef(){return F?.referrer||as}function Sf(t,e,n){n===void 0&&(n=!1);var i=t?[...ri,...e||[]]:[],r=n?fn(me?.href):me?.href,s=r?.substring(0,1e3);return{r:Ef().substring(0,1e3),u:s?Zi(s,i,Xi):void 0}}function xf(t,e){var n;e===void 0&&(e=!1);var i=t.r,r=t.u,s=e?fn(r):r,o={$referrer:i,$referring_domain:i==null?void 0:i==as?as:(n=ss(i))==null?void 0:n.host};if(s){o.$current_url=s;var a=ss(s);o.$host=a?.host,o.$pathname=a?.pathname;var l=wf(s);fe(o,l)}if(i){var u=bf(i);fe(o,u)}return o}function If(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function Qg(){try{return new Date().getTimezoneOffset()}catch{return}}var em={flags:ji,surveys:Xr},tm=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],Hn="main";class xo{constructor(e,n,i){if(i===void 0&&(i=!0),this.ci={},this.fi=!1,this.pi=!1,this.Ne=e,this.gi=i,this.props={},this.mi=void 0,this.yi=(s=>{var o="";return s.token&&(o=s.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),s.persistence_name?"ph_"+s.persistence_name:"ph_"+o+"_posthog"})(e),this.ii=this.bi(e),this.pi=this.wi(e),this.load(),e.debug&&A.info("Persistence loaded",e.persistence,k({},this.props)),this.update_config(e,e,n),this.save(),w){var r=()=>this.flush();ve(w,"beforeunload",r,{capture:!1}),ve(w,"pagehide",r,{capture:!1})}}ki(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return ke(n)&&n>0?n:0}isDisabled(){return!!this.xi}bi(e){tm.indexOf(e.persistence.toLowerCase())===-1&&(A.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var n,i=(function(o,a){o===void 0&&(o=[]),a===void 0&&(a=!1);var l=[...$g,...o];return k({},le,{H(u){try{var c={};try{c=qt.H(u)||{}}catch{}var d,f=JSON.parse(le.P(u)||"{}");if(a){var h={};for(var p in c){var g=c[p];Ke(g)||g===""||(h[p]=g)}d=fe(f,h)}else d=fe(c,f);return le.F(u,d),d}catch{}return null},F(u,c,d,f,h,p){var g=le.F(u,c,void 0,void 0,p);try{var m={};l.forEach((v=>{c[v]&&(m[v]=c[v])})),Object.keys(m).length&&qt.F(u,m,d,f,h,p)}catch(v){le.j(v)}return g},q(u,c){try{w?.localStorage.removeItem(u),qt.q(u,c)}catch(d){le.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),r=!1,s=e.persistence.toLowerCase();return s==="localstorage"&&le.N()?(n=le,r=!0):s==="localstorage+cookie"&&i.N()?(n=i,r=!0):s==="sessionstorage"&&be.N()?n=be:s==="memory"?n=Mg:s==="cookie"?n=qt:i.N()?(n=i,r=!0):n=qt,this.fi=r,n}Si(e){return this.yi+"__"+e}wi(e){return this.fi&&!!e.split_storage}properties(){var e={};return ie(this.props,((n,i)=>{var r=yn(i);if(!r||r.exposure==="event"){if(r!=null&&r.shouldSkipFromEventProperties!=null&&r.shouldSkipFromEventProperties(n))return;e[i]=n}})),e}load(){if(!this.xi){var e=this.ii.H(this.yi);e&&(this.props=fe({},e)),this.pi&&this.Ci()}}Ci(){for(var e of So){var n=le.H(this.Si(e));if(n&&!Kt(n)){var i=this.Mi(e);i.persisted=!0,this.Ti(e)||(i.fingerprint=this.Ei(n,e)),this.Ii(e,n)||fe(this.props,n)}}}Ti(e){return Object.keys(this.props).some((n=>{var i;return((i=yn(n))==null?void 0:i.storageGroup)===e}))}Ii(e,n){var i=em[e];if(!i)return!1;var r=n[i],s=this.props[i];return ke(r)&&ke(s)&&s>r}refreshKey(e){var n;if(!this.xi){var i=this.pi?(n=yn(e))==null?void 0:n.storageGroup:void 0,r=i?le.H(this.Si(i)):this.ii.H(this.yi);if(r&&e in r)this.Pi(e,r[e]);else{if(i){var s=this.ii.H(this.yi);if(s&&e in s)return void this.Pi(e,s[e])}this.Ri(e)}}}save(){if(!this.xi){var e=this.ki();e>0?C(this.Ai)&&(this.Ai=setTimeout((()=>{this.Ai=void 0,this.Fi()}),e)):this.Fi()}}flush(){C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0,this.Fi())}Fi(){this.xi||(this.pi?this.Li():this.Oi(this.ii,this.yi,this.props,Hn))}Li(){var e=this.Di(),n=e.main,i=e.groups;for(var r of(this.Oi(this.ii,this.yi,n,Hn),So)){var s,o=i[r];(!Kt(o)||(s=this.ci[r])!=null&&s.persisted)&&this.Oi(le,this.Si(r),o,r)}}Di(){var e={},n={flags:{},surveys:{}};return ie(this.props,((i,r)=>{var s,o=(s=yn(r))==null?void 0:s.storageGroup;o?n[o][r]=i:e[r]=i})),{main:e,groups:n}}Ei(e,n){if(n===Hn)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var i={};return ie(e,((r,s)=>{var o;i[s]=(o=yn(s))!=null&&o.volatile?"__volatile__":r})),JSON.stringify(i)}Oi(e,n,i,r){var s=this.Mi(r);if(r===Hn||s.dirty||C(s.fingerprint)){var o;try{if((o=this.Ei(i,r))===s.fingerprint)return void(s.dirty=!1)}catch{o=void 0}e.F(n,i,this.$i,this.Ni,this.qi,this.Ne.debug)?(s.dirty=!1,r!==Hn&&(s.persisted=!0),C(o)||(s.fingerprint=o)):this.Ne.debug&&A.warn('failed to persist storage entry "'+n+'"; will retry on next save')}}remove(e){var n=(e===void 0?{}:e).keepGroupEntries,i=n!==void 0&&n;if(C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0),this.ii.q(this.yi,!1),this.ii.q(this.yi,!0),!i&&this.gi)for(var r of So)le.q(this.Si(r));i?delete this.ci[Hn]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,n,i){if(he(e)){C(n)&&(n="None"),this.$i=C(i)?this.ji:i;var r=!1;if(ie(e,((s,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==n||(this.Pi(o,s),r=!0)})),r)return this.save(),!0}return!1}register(e,n){if(he(e)){this.$i=C(n)?this.ji:n;var i=!1;if(ie(e,((r,s)=>{e.hasOwnProperty(s)&&(this.props[s]!==r||he(r)||U(r))&&(this.Pi(s,r),i=!0)})),i)return this.save(),!0}return!1}unregister(e){var n=typeof e=="string"?[e]:e,i=!1;for(var r of n)r in this.props&&(this.Ri(r),i=!0);i&&this.save()}update_campaign_params(){var e=F?.URL;if(e!==this.mi){var n=yf(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);Kt(ll(n))||this.register(n),this.mi=e}}update_search_keyword(){var e;this.register((e=F?.referrer)?bf(e):{})}update_referrer_info(){var e;this.register_once({$referrer:Ef(),$referring_domain:F!=null&&F.referrer&&((e=ss(F.referrer))==null?void 0:e.host)||as},void 0)}set_initial_person_info(){this.props[fa]||this.props[ha]||this.register_once({[Qr]:Sf(this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties,this.Ne.disable_capture_url_hashes)},void 0)}get_initial_props(){var e={};ie([ha,fa],(r=>{var s=this.props[r];s&&ie(s,(function(o,a){e["$initial_"+Go(a)]=o}))}));var n=this.props[Qr];if(n){var i=(function(r,s){s===void 0&&(s=!1);var o=xf(r,s),a={};return ie(o,(function(l,u){a["$initial_"+Go(u)]=l})),a})(n,this.Ne.disable_capture_url_hashes);fe(e,i)}return e}safe_merge(e){return ie(this.props,(function(n,i){i in e||(e[i]=n)})),e}update_config(e,n,i){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!i),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var r=e.persistence!==n.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((f,h)=>f===d[h]))})(e.cookie_persisted_properties||[],n.cookie_persisted_properties||[]),s=r?this.bi(e):this.ii,o=this.wi(e);if(r||o!==this.pi){var a=this.props;this.clear(),this.ii=s,this.pi=o,this.props=a,this.save()}}set_disabled(e){this.xi=e,this.xi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ni&&(this.Ni=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this.qi&&(this.qi=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,n){var i=this.props[Ri]||{};i[e]=n,this.Pi(Ri,i),this.save()}remove_event_timer(e){var n=this.props[Ri]||{},i=n[e];return C(i)||(delete n[e],this.Pi(Ri,n),this.save()),i}get_property(e){return this.props[e]}set_property(e,n){this.Pi(e,n),this.save()}Pi(e,n){var i;this.props[e]=n,(i=yn(e))!=null&&i.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var n,i=(n=yn(e))==null?void 0:n.storageGroup;i&&(this.Mi(i).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function br(t){var e=!0;return{dispose(){if(e){e=!1;var n=t();n&&De(n.then)&&n.then(void 0,(()=>{}))}}}}var je={GZipJS:"gzip-js",Base64:"base64"},wi={Activation:"events",Cancellation:"cancelEvents"},Io={Popover:"popover",API:"api",Widget:"widget"},zt={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},ko={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},_a={Popover:"popover",Inline:"inline"},nm={SHOWN:"product tour shown"},zc={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},Vc=pe("[RateLimiter]");class im{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=n=>{var i=n.text;if(i&&i.length)try{(JSON.parse(i).quota_limited||[]).forEach((r=>{Vc.info((r||"events")+" is quota limited."),this.serverLimits[r]=new Date().getTime()+6e4}))}catch(r){return void Vc.warn('could not rate limit - continuing. Error: "'+r?.message+'"',{text:i})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var n,i,r;e===void 0&&(e=!1);var s=this.captureEventsBurstLimit,o=this.captureEventsPerSecond,a=new Date().getTime(),l=(n=(i=this.instance.persistence)==null?void 0:i.get_property(da))!==null&&n!==void 0?n:{tokens:s,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>s&&(l.tokens=s);var u=1>l.tokens;if(u||e||(l.tokens=Math.max(0,l.tokens-1)),u&&!e){var c=(ke(l.dropped)?l.dropped:0)+1;l.dropped=c,!this.lastEventRateLimited&&this.Hi(c)&&(l.dropped=0)}return this.lastEventRateLimited=u,(r=this.instance.persistence)==null||r.set_property(da,l),{isRateLimited:u,remainingTokens:l.tokens}}Ui(e){var n=this.instance.config.property_denylist;return!U(n)||!n.includes(e)}zi(){var e;if(this.Ui("$current_url")&&this.Ui("$pathname")&&me!=null&&me.pathname)return""+((e=me.origin)!==null&&e!==void 0?e:"")+me.pathname}Hi(e){var n,i,r=this.captureEventsBurstLimit,s=this.captureEventsPerSecond,o=this.zi(),a=this.Ui("$session_id")?(n=(i=this.instance).get_session_id)==null?void 0:n.call(i):void 0,l=[e+" event(s) dropped since the last warning",o?"triggered on "+o:void 0,a?"session "+a:void 0].filter(Boolean).join(", ");return!!this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited: "+l+". Config is set to "+s+" events per second and "+r+" events burst limit."},{skip_client_rate_limiting:!0})}isServerRateLimited(e){var n=this.serverLimits[e||"events"]||!1;return n!==!1&&new Date().getTime()e(this.remoteConfig))):e()}Vi(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:e})}load(){try{if(this.remoteConfig)return an.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void an.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return an.info("No config found after loading remote JS config. Falling back to JSON."),void this.Vi((n=>{this.Zi(n.json,n),this.Gi()}));this.Zi(e),this.Gi()}))}catch(e){an.error("Error loading remote config",e),this.Zi()}}stop(){this.Ki&&(clearInterval(this.Ki),this.Ki=void 0)}refresh(){!this._instance.Qi()&&F&&F.visibilityState!=="hidden"&&this._instance.reloadFeatureFlags()}Gi(){var e;if(!this.Ki){var n=(e=this._instance.config.remote_config_refresh_interval_ms)!==null&&e!==void 0?e:3e5;n!==0&&(this.Ki=setInterval((()=>{this.refresh()}),n))}}Zi(e,n){!e&&n&&(n.statusCode===0?n.error||an.warn("Failed to fetch remote config from PostHog."):an.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(r){an.error("Error applying remote config",r)}if(e?.hasFeatureFlags!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var i;(i=this._instance.featureFlags)==null||i.ensureFlagsLoaded()}catch(r){an.error("Error loading feature flags",r)}}}var lt=Uint8Array,Ge=Uint16Array,si=Uint32Array,fl=new lt([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]),hl=new lt([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]),Gc=new lt([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Cf=function(t,e){for(var n=new Ge(31),i=0;31>i;++i)n[i]=e+=1<i;++i)for(var s=n[i];n[i+1]>s;++s)r[s]=s-n[i]<<5|i;return[n,r]},Af=Cf(fl,2),ya=Af[1];Af[0][28]=258,ya[258]=28;for(var Kc=Cf(hl,0)[1],Pf=new Ge(32768),_e=0;32768>_e;++_e){var Wn=(43690&_e)>>>1|(21845&_e)<<1;Pf[_e]=((65280&(Wn=(61680&(Wn=(52428&Wn)>>>2|(13107&Wn)<<2))>>>4|(3855&Wn)<<4))>>>8|(255&Wn)<<8)>>>1}var Hi=function(t,e,n){for(var i=t.length,r=0,s=new Ge(e);i>r;++r)++s[t[r]-1];var o,a=new Ge(e);for(r=0;e>r;++r)a[r]=a[r-1]+s[r-1]<<1;for(o=new Ge(i),r=0;i>r;++r)o[r]=Pf[a[t[r]-1]++]>>>15-t[r];return o},$n=new lt(288);for(_e=0;144>_e;++_e)$n[_e]=8;for(_e=144;256>_e;++_e)$n[_e]=9;for(_e=256;280>_e;++_e)$n[_e]=7;for(_e=280;288>_e;++_e)$n[_e]=8;var ls=new lt(32);for(_e=0;32>_e;++_e)ls[_e]=5;var rm=Hi($n,9),sm=Hi(ls,5),Ff=function(t){return(t/8>>0)+(7&t&&1)},Rf=function(t,e,n){(n==null||n>t.length)&&(n=t.length);var i=new(t instanceof Ge?Ge:t instanceof si?si:lt)(n-e);return i.set(t.subarray(e,n)),i},Ot=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8},bi=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8,t[i+2]|=n>>>16},Co=function(t,e){for(var n=[],i=0;t.length>i;++i)t[i]&&n.push({s:i,f:t[i]});var r=n.length,s=n.slice();if(!r)return[new lt(0),0];if(r==1){var o=new lt(n[0].s+1);return o[n[0].s]=1,[o,1]}n.sort((function(x,I){return x.f-I.f})),n.push({s:-1,f:25001});var a=n[0],l=n[1],u=0,c=1,d=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=r-1;)a=n[n[d].f>n[u].f?u++:d++],l=n[u!=c&&n[d].f>n[u].f?u++:d++],n[c++]={s:-1,f:a.f+l.f,l:a,r:l};var f=s[0].s;for(i=1;r>i;++i)s[i].s>f&&(f=s[i].s);var h=new Ge(f+1),p=wa(n[c-1],h,0);if(p>e){i=0;var g=0,m=p-e,v=1<i;++i){var S=s[i].s;if(e>=h[S])break;g+=v-(1<>>=m;g>0;){var b=s[i].s;e>h[b]?g-=1<=0&&g;--i){var _=s[i].s;h[_]==e&&(--h[_],++g)}p=e}return[new lt(h),p]},wa=function(t,e,n){return t.s==-1?Math.max(wa(t.l,e,n+1),wa(t.r,e,n+1)):e[t.s]=n},Yc=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new Ge(++e),i=0,r=t[0],s=1,o=function(l){n[i++]=l},a=1;e>=a;++a)if(t[a]==r&&a!=e)++s;else{if(!r&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(r),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(r);s=1,r=t[a]}return[n.subarray(0,i),e]},Ei=function(t,e){for(var n=0,i=0;e.length>i;++i)n+=t[i]*e[i];return n},ba=function(t,e,n){var i=n.length,r=Ff(e+2);t[r]=255&i,t[r+1]=i>>>8,t[r+2]=255^t[r],t[r+3]=255^t[r+1];for(var s=0;i>s;++s)t[r+s+4]=n[s];return 8*(r+4+i)},Jc=function(t,e,n,i,r,s,o,a,l,u,c){Ot(e,c++,n),++r[256];for(var d=Co(r,15),f=d[0],h=d[1],p=Co(s,15),g=p[0],m=p[1],v=Yc(f),S=v[0],b=v[1],_=Yc(g),x=_[0],I=_[1],T=new Ge(19),E=0;S.length>E;++E)T[31&S[E]]++;for(E=0;x.length>E;++E)T[31&x[E]]++;for(var P=Co(T,7),$=P[0],O=P[1],L=19;L>4&&!$[Gc[L-1]];--L);var N,K,V,M,R=u+5<<3,Z=Ei(r,$n)+Ei(s,ls)+o,Ce=Ei(r,f)+Ei(s,g)+o+14+3*L+Ei(T,$)+(2*T[16]+3*T[17]+7*T[18]);if(Z>=R&&Ce>=R)return ba(e,c,t.subarray(l,l+u));if(Ot(e,c,1+(Z>Ce)),c+=2,Z>Ce){N=Hi(f,h),K=f,V=Hi(g,m),M=g;var oe=Hi($,O);for(Ot(e,c,b-257),Ot(e,c+5,I-1),Ot(e,c+10,L-4),c+=14,E=0;L>E;++E)Ot(e,c+3*E,$[Gc[E]]);c+=3*L;for(var ye=[S,x],$e=0;2>$e;++$e){var ae=ye[$e];for(E=0;ae.length>E;++E)Ot(e,c,oe[Ie=31&ae[E]]),c+=$[Ie],Ie>15&&(Ot(e,c,ae[E]>>>5&127),c+=ae[E]>>>12)}}else N=rm,K=$n,V=sm,M=ls;for(E=0;a>E;++E)if(i[E]>255){var Ie;bi(e,c,N[257+(Ie=i[E]>>>18&31)]),c+=K[Ie+257],Ie>7&&(Ot(e,c,i[E]>>>23&31),c+=fl[Ie]);var Se=31&i[E];bi(e,c,V[Se]),c+=M[Se],Se>3&&(bi(e,c,i[E]>>>5&8191),c+=hl[Se])}else bi(e,c,N[i[E]]),c+=K[i[E]];return bi(e,c,N[256]),c+K[256]},om=new si([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),am=(function(){for(var t=new si(256),e=0;256>e;++e){for(var n=e,i=9;--i;)n=(1&n&&3988292384)^n>>>1;t[e]=n}return t})(),Ao=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8};function lm(t,e){e===void 0&&(e={});var n=(function(){var d=4294967295;return{p(f){for(var h=d,p=0;f.length>p;++p)h=am[255&h^f[p]]^h>>>8;d=h},d(){return 4294967295^d}}})(),i=t.length;n.p(t);var r,s,o,a,l,u=(a=10+((r=e).filename&&r.filename.length+1||0),l=8,(function(d,f,h,p,g,m){var v=d.length,S=new lt(p+v+5*(1+Math.floor(v/7e3))+g),b=S.subarray(p,S.length-g),_=0;if(!f||8>v)for(var x=0;v>=x;x+=65535){var I=x+65535;v>I?_=ba(b,_,d.subarray(x,I)):(b[x]=!0,_=ba(b,_,d.subarray(x,v)))}else{for(var T=om[f-1],E=T>>>13,P=8191&T,$=(1<x;++x){var Ie=V(x),Se=32767&x,Be=L[Ie];if(O[Se]=Be,L[Ie]=Se,x>=$e){var wt=v-x;if((Ce>7e3||ye>24576)&&wt>423){_=Jc(d,b,0,M,R,Z,oe,ye,ae,x-ae,_),ye=Ce=oe=0,ae=x;for(var ge=0;286>ge;++ge)R[ge]=0;for(ge=0;30>ge;++ge)Z[ge]=0}var Ye=2,bt=0,mn=P,Re=Se-Be&32767;if(wt>2&&Ie==V(x-Re))for(var Pe=Math.min(E,wt)-1,$t=Math.min(32767,x),Bn=Math.min(258,wt);$t>=Re&&--mn&&Se!=Be;){if(d[x+Ye]==d[x+Ye-Re]){for(var qe=0;Bn>qe&&d[x+qe]==d[x+qe-Re];++qe);if(qe>Ye){if(Ye=qe,bt=Re,qe>Pe)break;var Dn=Math.min(Re,qe-2),Mt=0;for(ge=0;Dn>ge;++ge){var Lt=x-Re+ge+32768&32767,ct=Lt-O[Lt]+32768&32767;ct>Mt&&(Mt=ct,Be=Lt)}}}Re+=(Se=Be)-(Be=O[Se])+32768&32767}if(bt){M[ye++]=268435456|ya[Ye]<<18|Kc[bt];var sn=31&ya[Ye],gi=31&Kc[bt];oe+=fl[sn]+hl[gi],++R[257+sn],++Z[gi],$e=x+Ye,++Ce}else M[ye++]=d[x],++R[d[x]]}}_=Jc(d,b,!0,M,R,Z,oe,ye,ae,x-ae,_)}return Rf(S,0,p+Ff(_)+g)})(s=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):12+o.mem,a,l)),c=u.length;return(function(d,f){var h=f.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>f.level?4:f.level==9?2:0,d[9]=3,f.mtime!=0&&Ao(d,4,Math.floor(new Date(f.mtime||Date.now())/1e3)),h){d[3]=8;for(var p=0;h.length>=p;++p)d[p+10]=h.charCodeAt(p)}})(u,e),Ao(u,c-8,n.d()),Ao(u,c-4,i),u}var cm=!!qo||!!Za,Tf="text/plain",Mr=!1,$f=(t,e)=>{var n=t.split("#"),i=n[1],r=n[0].split("?"),s=r[0],o=r[1];if(!o)return t;var a=o.split("&").filter((l=>l.split("=")[0]!==e)).join("&");return s+(a?"?"+a:"")+(i?"#"+i:"")},ks=function(t,e,n){var i;n===void 0&&(n=!0);var r=t.split("?"),s=r[0],o=r[1],a=k({},e),l=(i=o?.split("&").map((c=>{var d,f=c.split("="),h=f[0],p=n&&(d=a[h])!==null&&d!==void 0?d:f[1];return delete a[h],h+"="+p})))!==null&&i!==void 0?i:[],u=(function(c,d){var f,h;d===void 0&&(d="&");var p=[];return ie(c,(function(g,m){C(g)||C(m)||m==="undefined"||(f=encodeURIComponent((v=>v instanceof File)(g)?g.name:g.toString()),h=encodeURIComponent(m),p[p.length]=h+"="+f)})),p.join(d)})(a);return u&&l.push(u),l.length>0?s+"?"+l.join("&"):s},Po=t=>{if(t.Ji)return t.Ji;var e=t.data,n=t.compression;if(e){if(n===je.GZipJS){var i=lm((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new lt(a.length+(a.length>>>1)),d=0,f=function(m){c[d++]=m},h=0;u>h;++h){if(d+5>c.length){var p=new lt(d+8+(u-h<<1));p.set(c),c=p}var g=a.charCodeAt(h);128>g?f(g):2048>g?(f(192|g>>>6),f(128|63&g)):g>55295&&57344>g?(f(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++h))>>>18),f(128|g>>>12&63),f(128|g>>>6&63),f(128|63&g)):(f(224|g>>>12),f(128|g>>>6&63),f(128|63&g))}return Rf(c,0,d)})(Yn(e)),{mtime:0});return{contentType:Tf,body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),estimatedSize:i.byteLength}}if(n===je.Base64){var r=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(Yn(e)),s=(a=>"data="+encodeURIComponent(typeof a=="string"?a:Yn(a)))(r);return{contentType:"application/x-www-form-urlencoded",body:s,estimatedSize:new Blob([s]).size}}var o=Yn(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},Mf=t=>{var e,n,i=()=>t.transport==="sendBeacon"?{url:ks(t.url,{compression:je.Base64}),encodedBody:Po(k({},t,{compression:je.Base64,Ji:void 0}))}:{url:$f(t.url,"compression"),encodedBody:Po(k({},t,{compression:void 0,Ji:void 0}))};try{e=Po(t)}catch(r){if(mc(t.compression,ii(t.url,"compression")))return A.error("Failed to gzip request body, sending uncompressed payload",r),i();throw r}return e&&mc(t.compression,ii(t.url,"compression"))&&!((n=e.body)instanceof ArrayBuffer?zo(new Uint8Array(n)):ArrayBuffer.isView(n)&&zo(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)))?(Mr=!0,i()):{url:t.url,encodedBody:e}},Lf=t=>{try{return Mf(t)}catch(e){return A.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},um=(function(){var t=se((function*(e){var n=Yn(e.data),i=yield(function(s,o,a){return Vo.apply(this,arguments)})(n,ne.DEBUG,{rethrow:!0});if(!i)return e;var r=yield i.arrayBuffer();return k({},e,{Ji:{contentType:Tf,body:r,estimatedSize:r.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),dm=/Failed to fetch|NetworkError|Load failed/i,Nf=t=>t?.name==="TypeError"&&dm.test(t?.message||""),Of=t=>{var e=Lf(t);if(e){var n=e.url,i=e.encodedBody,r=i??{},s=r.contentType,o=r.body,a=r.estimatedSize,l=new Headers;ie(t.headers,(function(p,g){l.append(g,p)})),s&&l.append("Content-Type",s);var u=null,c=!1;if(uc){var d=new uc;u={signal:d.signal,timeout:setTimeout((()=>{var p,g;c=!0,d.abort((p=t.timeout,(g=new Error("PostHog request timed out"+(p?" after "+p+"ms":""))).name="AbortError",g))}),t.timeout)}}var f=p=>{c&&p?.name==="AbortError"||Nf(p)?A.warn(p):A.error(p),t.callback==null||t.callback({statusCode:0,error:p})};try{var h;Za(n,k({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(h=u)==null?void 0:h.signal},t.fetchOptions)).then((p=>p.text().then((g=>{var m={statusCode:p.status,text:g};if(p.status===200)try{m.json=JSON.parse(g)}catch(v){A.error(v)}t.callback==null||t.callback(m)})))).catch(f).finally((()=>u?clearTimeout(u.timeout):null))}catch(p){u&&clearTimeout(u.timeout),f(p)}}},Ea=t=>{try{var e,n=Mf(t),i=n.url,r=n.encodedBody,s=r??{},o=s.body,a=s.estimatedSize;if(!o)return;var l=o instanceof Blob?o:new Blob([o],{type:s.contentType});if(Ue.sendBeacon(i,l))return;var u=U(t.data)?t.data:(e=t.data)==null?void 0:e.batch;if(U(u)&&u.length>1&&(a??0)>16384){var c=Math.ceil(u.length/2),d=f=>U(t.data)?f:k({},t.data,{batch:f});return Ea(k({},t,{data:d(u.slice(0,c))})),void Ea(k({},t,{data:d(u.slice(c))}))}A.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),Of(k({},t,{Yi:!0}))}catch(f){A.warn("Beacon send failed",f)}},Zc=(t,e,n,i)=>{var r=i==="query"?e==="POST"?"sent_at":"_":void 0;return ks(n===je.GZipJS?$f(t,"compression"):t,k({},r?{[r]:Date.now().toString()}:{},n===je.GZipJS?{}:{compression:n}))},Lr=[];Za&&Lr.push({transport:"fetch",method:Of}),qo&&Lr.push({transport:"XHR",method(t){var e=Lf(t);if(e){var n=new qo,i=e.encodedBody;n.open(t.method||"GET",e.url,!0);var r=i??{},s=r.contentType,o=r.body;ie(t.headers,(function(a,l){n.setRequestHeader(l,a)})),s&&n.setRequestHeader("Content-Type",s),t.timeout&&(n.timeout=t.timeout),n.onreadystatechange=()=>{if(n.readyState===4){var a={statusCode:n.status,text:n.responseText};if(n.status===200)try{a.json=JSON.parse(n.responseText)}catch{}t.callback==null||t.callback(a)}},n.send(o)}}}),Ue!=null&&Ue.sendBeacon&&Lr.push({transport:"sendBeacon",method:Ea});var Sa=3e3;class fm{constructor(e,n){this.Xi=!0,this.tr=[],this.er=At(n?.flush_interval_ms||Sa,250,5e3,A.createLogger("flush interval"),Sa),this.ir=e}enqueue(e){this.tr.push(e),this.rr||this.nr()}unload(){this.sr();var e=this.tr.length>0?this.ar():{},n=Object.values(e);[...n.filter((i=>i.url.indexOf("/e")===0)),...n.filter((i=>i.url.indexOf("/e")!==0))].map((i=>{this.lr(k({},i,{transport:"sendBeacon"}))}))}enable(){this.Xi=!1,this.nr()}nr(){var e=this;this.Xi||(this.rr=setTimeout((()=>{if(this.sr(),this.tr.length>0){var n=this.ar(),i=function(){var s=n[r],o=new Date().getTime();s.data&&U(s.data)&&ie(s.data,(a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp})),e.lr(s)};for(var r in n)i()}}),this.er))}lr(e){try{this.ir(e)}catch(n){A.error(n)}}sr(){clearTimeout(this.rr),this.rr=void 0}ar(){var e={};return ie(this.tr,(n=>{var i,r=n,s=(r?r.batchKey:null)||r.url;C(e[s])&&(e[s]=k({},r,{data:[]})),(i=e[s].data)==null||i.push(r.data)})),this.tr=[],e}}var hm=["retriesPerformedSoFar"];class pm{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!C(w)&&"onLine"in w.navigator&&(this.dr=w.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},ve(w,"online",this.vr),ve(w,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var n=e.retriesPerformedSoFar,i=ud(e,hm);Dt(n)&&(i.url=ks(i.url,{retry_count:n})),this._instance._send_request(k({},i,{callback:r=>{if(r.statusCode!==200&&(400>r.statusCode||r.statusCode>=500)){if((r.statusCode===0?3:10)>(n??0))return void this.At(k({retriesPerformedSoFar:n},i));r.statusCode===0&&A.warn("Request failed before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped retrying after "+(n??0)+" retries.")}i.callback==null||i.callback(r)}}))}At(e){var n=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=n+1;var i=(function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),c=Math.random()-.5;return Math.ceil(u+c*(u-l))})(n),r=Date.now()+i;this.tr.push({retryAt:r,requestOptions:e});var s="Enqueued failed request for retry in "+i;navigator.onLine||(s+=" (Browser is offline)"),A.warn(s),this.ur||(this.ur=!0,this.gr())}gr(){if(this.mr&&clearTimeout(this.mr),this.tr.length===0)return this.ur=!1,void(this.mr=void 0);this.mr=setTimeout((()=>{this.dr&&this.tr.length>0&&this.cr(),this.gr()}),this.hr)}cr(){var e=Date.now(),n=[],i=this.tr.filter((s=>e>s.retryAt||(n.push(s),!1)));if(this.tr=n,i.length>0)for(var r of i)this.retriableRequest(r.requestOptions)}unload(){for(var e of(this.mr&&(clearTimeout(this.mr),this.mr=void 0),this.ur=!1,C(w)||(this.vr&&(w.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(w.removeEventListener("offline",this.pr),this.pr=void 0)),this.tr)){var n=e.requestOptions;try{this._instance._send_request(k({},n,{transport:"sendBeacon"}))}catch(i){A.error(i)}}this.tr=[]}}class gm{constructor(e){this.yr=()=>{var n,i,r,s;this.br||(this.br={});var o=this.scrollElement(),a=this.scrollY(),l=o?Math.max(0,o.scrollHeight-o.clientHeight):0,u=a+(o?.clientHeight||0),c=o?.scrollHeight||0;this.br.lastScrollY=Math.ceil(a),this.br.maxScrollY=Math.max(a,(n=this.br.maxScrollY)!==null&&n!==void 0?n:0),this.br.maxScrollHeight=Math.max(l,(i=this.br.maxScrollHeight)!==null&&i!==void 0?i:0),this.br.lastContentY=u,this.br.maxContentY=Math.max(u,(r=this.br.maxContentY)!==null&&r!==void 0?r:0),this.br.maxContentHeight=Math.max(c,(s=this.br.maxContentHeight)!==null&&s!==void 0?s:0)},this._instance=e}get _r(){return this._instance.config.scroll_root_selector}getContext(){return this.br}resetContext(){var e=this.br;return setTimeout(this.yr,0),e}startMeasuringScrollPosition(){ve(w,"scroll",this.yr,{capture:!0}),ve(w,"scrollend",this.yr,{capture:!0}),ve(w,"resize",this.yr)}scrollElement(){if(!this._r)return w?.document.documentElement;var e=U(this._r)?this._r:[this._r];for(var n of e){var i=w?.document.querySelector(n);if(i)return i}}wr(e){var n=e==="y"?"scrollTop":"scrollLeft";if(this._r){var i=this.scrollElement();return i&&i[n]||0}return w?e==="y"?w.scrollY||w.pageYOffset||w.document.documentElement.scrollTop||0:w.scrollX||w.pageXOffset||w.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var mm=t=>Sf(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class Xc{constructor(e,n,i,r){this.kr=s=>{var o=this.Sr();if(!o||o.sessionId!==s){var a={sessionId:s,props:this.Cr(this._instance)};this.Mr.register({[ua]:a})}},this._instance=e,this.Tr=n,this.Mr=i,this.Cr=r||mm,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[ua]}getSetOnceProps(){var e,n=(e=this.Sr())==null?void 0:e.props;return n?"r"in n?xf(n,this._instance.config.disable_capture_url_hashes):{$referring_domain:n.referringDomain,$pathname:n.initialPathName,utm_source:n.utm_source,utm_campaign:n.utm_campaign,utm_medium:n.utm_medium,utm_content:n.utm_content,utm_term:n.utm_term}:{}}getSessionProps(){var e={};return ie(ll(this.getSetOnceProps()),((n,i)=>{i==="$current_url"&&(i="url"),e["$session_entry_"+Go(i)]=n})),e}}class pl{on(e,n){return this.Er[e]||(this.Er[e]=[]),this.Er[e].push(n),()=>{this.Er[e]=this.Er[e].filter((i=>i!==n))}}emit(e,n){for(var i of this.Er[e]||[])i(n);for(var r of this.Er["*"]||[])r(e,n)}constructor(){this.Er={}}}var Si=pe("[SessionId]");class Qc{on(e,n){return this.Ir.on(e,n)}constructor(e,n,i){var r;if(this.Pr=null,this.Rr=[],this.Ar=void 0,this.Fr=!1,this.Ir=new pl,this.Lr=(u,c)=>!(!Dt(u)||!Dt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===Wt)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Ne=e.config,this.Mr=e.persistence,this.Or=void 0,this.Dr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.$r=n||Ht,this.Nr=i||Ht;var s=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*At(this.Ne.session_idle_timeout_seconds||1800,60,36e3,Si.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.qr(),this.jr="ph_"+s+"_window_id",this.Br="ph_"+s+"_primary_window_exists",this.Hr()){var o=be.H(this.jr),a=be.H(this.Br);o&&!a?this.Or=o:be.q(this.jr),be.F(this.Br,!0)}if((r=this.Ne.bootstrap)!=null&&r.sessionID)try{var l=(u=>{var c=this.Ne.bootstrap.sessionID.replace(/-/g,"");if(c.length!==32)throw new Error("Not a valid UUID");if(c[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(c.substring(0,12),16)})();this.Ur(this.Ne.bootstrap.sessionID,new Date().getTime(),l)}catch(u){Si.error("Invalid sessionID in bootstrap",u)}this.zr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return C(this.Rr)&&(this.Rr=[]),this.Rr.push(e),this.Dr&&e(this.Dr,this.Or),()=>{this.Rr=this.Rr.filter((n=>n!==e))}}Hr(){return this.Ne.persistence!=="memory"&&!this.Mr.xi&&be.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&be.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?be.H(this.jr):null}Zr(e){var n=this.Pr;return!Ke(n)&&!Ke(e)&&5e3>Math.abs(e-n)}Ur(e,n,i){var r=n!==this._sessionActivityTimestamp,s=!(e!==this.Dr||i!==this._sessionStartTimestamp);this._sessionStartTimestamp=i,this._sessionActivityTimestamp=n,this.Dr=e,s&&!r||s&&this.Zr(n)||(this.Pr=n,this.Mr.register({[Kn]:[n,e,i]}))}Gr(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return Dt(n)&&n>0}Qr(){this.Gr()?this.Mr.refreshKey(Kn):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!Ke(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this.Pr){this.Qr();var n=this.Jr();n[1]===this.Dr&&n[2]===this._sessionStartTimestamp&&(this.Pr=this._sessionActivityTimestamp,this.Mr.register({[Kn]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],n=Dt(e)?e:0,i=Dt(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(n,i)}Xr(e){return this.Qr(),this.Lr(e,this.Yr())}Jr(){var e=this.Mr.props[Kn];return U(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Pr=null,clearTimeout(this.tn),this.tn=void 0,this.Ur(null,null,null)}destroy(){this.Fr=!0,this.Kr(),clearTimeout(this.tn),this.tn=void 0,this.Ar&&w&&(w.removeEventListener(ns,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&be.q(this.Br)},ve(w,ns,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=null),this.Ne.cookieless_mode===Wt)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var i=n||new Date().getTime(),r=this.Jr(),s=r[1],o=r[2],a=this.Yr(),l=this.Vr(),u=Dt(o)&&Math.abs(i-o)>864e5,c=!1,d=!1,f=!s,h=s,p=!f&&!e&&this.Lr(i,a);if(p){(p=this.Xr(i))||Si.info("cross-tab refresh kept the session alive",{sessionId:s});var g=this.Jr();s=g[1],o=g[2]}f||p||u?(s=this.$r(),l=this.Nr(),Si.info("new session ID generated",{sessionId:s,windowId:l,changeReason:{noSessionId:f,activityTimeout:p,sessionPastMaximumLength:u}}),o=i,c=!0):(l||(l=this.Nr(),c=!0),(d=s!==h)&&(Si.info("adopted cross-tab session id",{sessionId:s,windowId:l}),c=!0));var m=Dt(a)&&e&&!u?a:i,v=Dt(o)?o:new Date().getTime();this.Wr(l),this.Ur(s,m,v),e||this.qr();var S={noSessionId:f,activityTimeout:p,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((b=>b(s,l,S))),{sessionId:s,windowId:l,sessionStartTimestamp:v,changeReason:c?S: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 Bf=function(t,e){if(!t)return!1;var n=t.userAgent;if(n&&_c(n,e))return!0;try{var i=t?.userAgentData;if(i!=null&&i.brands&&i.brands.some((r=>_c(r?.brand,e))))return!0}catch{}return!!t.webdriver};function Df(){return(Df=se((function*(){var t=Ue?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),n=e?.model;return X(n)&&n.length>0?n:void 0}catch(i){return void A.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",i)}}))).apply(this,arguments)}var cs=function(t,e){if(!(function(n){try{new RegExp(n)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function Fo(t,e,n){return Yn({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}var jf={exact:(t,e)=>e.some((n=>t.some((i=>n===i)))),is_not:(t,e)=>e.every((n=>t.every((i=>n!==i)))),regex:(t,e)=>e.some((n=>t.some((i=>cs(n,i))))),not_regex:(t,e)=>e.every((n=>t.every((i=>!cs(n,i))))),icontains:(t,e)=>e.map(Er).some((n=>t.map(Er).some((i=>n.includes(i))))),not_icontains:(t,e)=>e.map(Er).every((n=>t.map(Er).every((i=>!n.includes(i))))),gt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>i>parseFloat(r)))})),lt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>it.toLowerCase();function Uf(t,e){return!t||Object.entries(t).every((n=>{var i=n[1],r=e?.[n[0]];if(C(r)||Ke(r))return!1;var s=[String(r)],o=jf[i.operator];return!!o&&o(i.values,s)}))}var xa="custom",eu="i.posthog.com",vm=/^\/static\//;class _m{constructor(e){this.en={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,n=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return n||(n=this.apiHost.replace("."+eu,".posthog.com")),n==="https://app.posthog.com"?"https://us.posthog.com":n}get region(){return this.en[this.apiHost]||(this.en[this.apiHost]=/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"us":/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"eu":xa),this.en[this.apiHost]}rn(e){if(vm.test(e)){var n=this.instance.config.asset_host;if(typeof n=="string")return n.trim().replace(/\/$/,"")||void 0}}endpointFor(e,n){if(n===void 0&&(n=""),n&&(n=n[0]==="/"?n:"/"+n),e==="ui")return this.uiHost+n;if(e==="flags")return this.flagsApiHost+n;if(e==="assets"){var i=this.rn(n);if(i)return""+i+n}if(this.region===xa)return this.apiHost+n;var r=eu+n;switch(e){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}}function Hf(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var Q=pe("[Surveys]"),Wf="seenSurvey_",qf=t=>{try{var e=(n=>((i,r)=>""+Wf+(function(s){return s.current_iteration&&s.current_iteration>0?s.id+"_"+s.current_iteration:s.id})(r))(0,n))(t);if(localStorage.getItem(e))return;localStorage.setItem(e,"true")}catch(n){Q.error("Failed to persist survey seen state",n)}},ym=[Io.Popover,Io.Widget,Io.API],wm={ignoreConditions:!1,ignoreDelay:!1,displayType:_a.Popover},bm=pe("[PostHog ExternalIntegrations]"),Em={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class Sm{constructor(e){this._instance=e}ai(e,n){var i;(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,e,(r=>{if(r)return bm.error("failed to load script",r);n()}))}startIfEnabledOrStop(){var e=this,n=function(){var s,o,a,l=i[0],u=i[1];!u||(s=B.__PosthogExtensions__)!=null&&(s=s.integrations)!=null&&s[l]||e.ai(Em[l],(()=>{var c;(c=B.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=B.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=B.__PosthogExtensions__)==null||(a=a.integrations)==null||(a=a[l])==null||a.stop())};for(var i of Object.entries((r=this._instance.config.integrations)!==null&&r!==void 0?r:{})){var r;n()}}}class xm{constructor(e,n){this.rt=e,this.nn=n,this.sn=new Map,this.an=!1}add(e){var n=this;return se((function*(){if(n.an)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(n.sn.has(e.name))throw new Error('Browser extension "'+e.name+'" is already registered');n.sn.set(e.name,e);try{var i=e.setup(n.nn);i&&(yield i)}catch(s){var r=n.sn.get(e.name)===e;r&&n.sn.delete(e.name),n.rt.error('Failed to set up browser extension "'+e.name+'"',s),r&&n.ln(e)}}))()}dispose(){if(!this.an){this.an=!0;var e=Array.from(this.sn.values()).reverse();for(var n of(this.sn.clear(),e))this.ln(n)}}ln(e){try{var n=e.dispose==null?void 0:e.dispose();n&&De(n.then)&&n.then(void 0,(i=>{this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}))}catch(i){this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}}}class Im{constructor(e){this._instance=e}initialize(){}get(e){var n=this._instance.persistence;if(typeof e=="string")return n?.get_property(e);var i={};for(var r of e){var s=n?.get_property(r);C(s)||(i[r]=s)}return i}set(e,n){var i;(i=this._instance.persistence)==null||i.register(typeof e=="string"?{[e]:n}:e)}remove(e){var n;(n=this._instance.persistence)==null||n.unregister(e)}}var tu="extensionsRemoteConfig";class km{constructor(e){this.an=!1,this.instance=e,this.rt=A,this.un=e.hn,this.kv=new Im(e),this.onEvent=n=>br(this.instance.on("eventCaptured",(i=>{try{n({event:i.event,properties:i.properties})}catch(r){this.rt.error("Browser extension event listener failed",r)}}))),this.onRemoteConfig=n=>{if(this.an)return br((()=>{}));var i=s=>{try{n(s)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},r=this.instance.dn.on(tu,i);return this.un&&i(this.un),br(r)},this.vn=new xm(A.createLogger("[BrowserExtensions]"),this)}get logger(){return this.rt}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return(e=this.instance.get_property(Yi))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(Yi);return typeof e=="string"?e:void 0}get library(){return{name:ne.LIB_NAME,version:ne.LIB_VERSION}}get initialPersonProperties(){var e,n;return(e=(n=this.instance.persistence)==null?void 0:n.get_initial_props())!==null&&e!==void 0?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,n,i,r,s=(e=this.instance.sessionManager)==null?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:(n=s?.sessionId)!==null&&n!==void 0?n:"",windowId:(i=s?.windowId)!==null&&i!==void 0?i:"",sessionStartTimestamp:(r=s?.sessionStartTimestamp)!==null&&r!==void 0?r:0}}catch{return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get projectToken(){return this.instance.config.token}add(e){return this.vn.add(e)}capture(e,n,i){var r=this;return se((function*(){i?r.instance.capture(e,n,{timestamp:i.timestamp,uuid:i.uuid,$set:i.set,$set_once:i.setOnce}):r.instance.capture(e,n)}))()}registerDynamicEventProperties(e){return br(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(tu,e))}sendRequest(e,n){var i=this;return se((function*(){var r;n===void 0&&(n={});var s=i.instance.requestRouter.endpointFor((r=n.target)!==null&&r!==void 0?r:"api",e),o={method:n.method,url:n.query?ks(s,n.query):s,data:n.body,headers:n.headers,timeout:n.timeoutMs,fireCallbackOnDrop:!0,transport:n.transport,compression:n.compression,timestampMode:n.sentAt};return n.transport==="sendBeacon"?(i.instance._send_request(o),{statusCode:202}):new Promise((a=>{o.callback=a,i.instance._send_request(o)}))}))()}dispose(){this.an||(this.an=!0,this.vn.dispose())}}var Wi={},Ro=0,us=()=>{},nu='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',xi="Surveys module not available",iu="sanitize_properties is deprecated. Use before_send instead",zf="Invalid value for property_denylist config: ",Cm=["token","distinct_id",Zd],Gn="posthog",Vf=!cm&&Ve?.indexOf("MSIE")===-1&&Ve?.indexOf("Mozilla")===-1,To=t=>{var e;return k({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:Ag(F?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:us,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:t??"unset",__preview_deferred_init_extensions:!1,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:me&&X(me?.search)&&me.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disableDeviceModel:!1,disable_external_dependency_loading:!1,strict_script_versioning:!1,enable_recording_console_log:void 0,secure_cookie:(w==null||(e=w.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(n){A.error("Bad HTTP status: "+n.statusCode+" "+n.text)},get_device_id:n=>n,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:pa,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:Sa},error_tracking:{},_onCapture:us},(n=>({rageclick:n&&n>="2026-05-30"?{content_ignorelist:jg,ignore_text_selection:!0}:!n||"2025-11-30">n||{content_ignorelist:!0},capture_pageview:!n||"2025-05-24">n||"history_change",session_recording:n&&n>="2026-06-25"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6},streamNetworkBody:!0}:n&&n>="2026-05-30"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6}}:n&&n>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:n&&n>="2026-01-30"?"head":"body",internal_or_test_user_hostname:n&&n>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:n&&n>="2026-05-30"?250:0,split_storage:!(!n||"2026-05-30">n),detect_google_search_app:!(!n||"2026-05-30">n),disable_capture_url_hashes:!(!n||"2026-06-25">n)}))(t))},Am=[["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"]],ru=t=>{var e={};for(var n of Am){var i=n[0],r=n[1];C(t[i])||(e[r]=t[i])}var s=fe({},e,t),o=t.__preview_external_dependency_versioned_paths;return C(o)||(C(t.strict_script_versioning)&&(s.strict_script_versioning=!!o),X(o)&&C(t.asset_host)&&(s.asset_host=o)),U(t.property_blacklist)&&(C(t.property_denylist)?s.property_denylist=t.property_blacklist:U(t.property_denylist)?s.property_denylist=[...t.property_blacklist,...t.property_denylist]:A.error(zf+t.property_denylist)),s};class Pm{constructor(){this.__forceAllowLocalhost=!1}get fn(){return this.__forceAllowLocalhost}set fn(e){A.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class Je{pn(e,n){if(e){var i=this.sn.indexOf(e);i!==-1&&this.sn.splice(i,1)}return this.sn.push(n),n.initialize==null||n.initialize(),n}gn(){return this.config.cookieless_mode===Wt||this.config.cookieless_mode===kn&&this.consent.isRejected()}get decideEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){var e;this.webPerformance=new Pm,this.mn=!1,this.version=ne.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new pl,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=To(),this.SentryIntegration=Kg,this.sentryIntegration=i=>(function(r,s){var o=mf(r,s);return{name:gf,processEvent:a=>o(a)}})(this,i),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.wn=!1,this.kn=null,this.xn=null,this.Sn=null,this.scrollManager=new gm(this),this.pageViewManager=new Wc(this),this.rateLimiter=new im(this),this.requestRouter=new _m(this),this.consent=new Lg(this),this.externalIntegrations=new Sm(this);var n=(e=Je.__defaultExtensionClasses)!==null&&e!==void 0?e:{};this.featureFlags=n.featureFlags&&new n.featureFlags(this),this.toolbar=n.toolbar&&new n.toolbar(this),this.surveys=n.surveys&&new n.surveys(this),this.conversations=n.conversations&&new n.conversations(this),this.logs=n.logs&&new n.logs(this),this.metrics=n.metrics&&new n.metrics(this),this.experiments=n.experiments&&new n.experiments(this),this.exceptions=n.exceptions&&new n.exceptions(this),this.people={set:(i,r,s)=>{var o=X(i)?{[i]:r}:i;this.setPersonProperties(o),s?.({})},set_once:(i,r,s)=>{var o=X(i)?{[i]:r}:i;this.setPersonProperties(void 0,o),s?.({})}},this.on("eventCaptured",(i=>A.info('send "'+i?.event+'"',i)))}init(e,n,i){if(i&&i!==Gn){var r,s=(r=Wi[i])!==null&&r!==void 0?r:new Je;return s._init(e,n,i),Wi[i]=s,Wi[Gn][i]=s,s}return this._init(e,n,i)}_init(e,n,i){var r,s;n===void 0&&(n={});var o,a=X(e)?e.trim():"";if(!a)return A.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return a!==((o=this.config)==null?void 0:o.token)?console.warn("[PostHog.js]","You have already initialized PostHog with a different project token! Re-initializing is a no-op, so events will keep going to the project this instance was initialized with. To capture into a second project, load PostHog once, then initialize a named instance after the SDK has loaded, e.g. posthog.init('"+a+"', { ... }, 'project2')"):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=To(n.defaults),n.debug=this.Cn(n.debug),this.Mn=n,this.Tn=[],n.person_profiles?this.xn=n.person_profiles:n.process_person&&(this.xn=n.process_person);var l=To(n.defaults),u=ru(n),c=fe({},l,u,{name:i,token:a});he(l.rageclick)&&he(u.rageclick)&&(c.rageclick=fe({},l.rageclick,u.rageclick)),he(l.session_recording)&&he(u.session_recording)&&(c.session_recording=fe({},l.session_recording,u.session_recording)),this.set_config(c),this.config.on_xhr_error&&A.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=n.disable_compression?void 0:je.GZipJS;var d=this.En();if(this.persistence=new xo(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new xo(k({},this.config,{persistence:"sessionStorage"}),d,!1),this.bn="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&be.N()){var f=be.H(this.bn);U(f)&&f.forEach((I=>{X(I)&&this.yn.add(I)}))}else be.q(this.bn);var h=k({},this.persistence.props),p=k({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new fm((I=>this.Pn(I)),this.config.request_queue_config),this.Rn=new pm(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new Qc(this),this.sessionPropsManager=new Xc(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((I,T,E)=>{(E!=null&&E.activityTimeout||E!=null&&E.sessionPastMaximumLength||E!=null&&E.crossTabAdoption)&&this.An()}))),this.Fn(),this.config.__preview_deferred_init_extensions?(A.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Ln(g)}),0)):(A.info("Initializing extensions synchronously"),this.Ln(g)),ne.DEBUG=ne.DEBUG||this.config.debug,ne.DEBUG&&A.info("Starting in debug mode",{this:this,config:n,thisC:k({},this.config),p:h,s:p}),!this.config.identity_distinct_id||(r=n.bootstrap)!=null&&r.distinctID||(n.bootstrap=k({},n.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((s=n.bootstrap)==null?void 0:s.distinctID)!==void 0){var m=n.bootstrap.distinctID,v=this.get_distinct_id(),S=this.persistence.get_property(ot);if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&S===Un)this.identify(m);else if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&S===vn)A.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{var b=this.config.get_device_id(Ht()),_=n.bootstrap.isIdentifiedID?b:m;this.persistence.set_property(ot,n.bootstrap.isIdentifiedID?vn:Un),this.register({distinct_id:m,$device_id:_})}}if(g)this.register_once({distinct_id:mr,$device_id:null},"");else if(!this.get_distinct_id()){var x=this.config.get_device_id(Ht());this.register_once({distinct_id:x,$device_id:x},""),this.persistence.set_property(ot,Un)}return ve(w,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),n.segment?(function(I,T){var E=I.config.segment;if(!E)return T();(function(P,$){var O=P.config.segment;if(!O)return $();var L=K=>{var V=()=>K.anonymousId()||Ht();P.config.get_device_id=V,K.id()&&(P.register({distinct_id:K.id(),$device_id:V()}),P.persistence.set_property(ot,vn)),$()},N=O.user();"then"in N&&De(N.then)?N.then(L):L(N)})(I,(()=>{E.register((P=>{typeof Promise<"u"&&Promise.resolve||Eo.warn("This browser does not have Promise support, and can not use the segment integration");var $=(O,L)=>{if(!L)return O;O.event.userId||O.event.anonymousId===P.get_distinct_id()||(Eo.info("No userId set, resetting PostHog"),P.reset()),O.event.userId&&O.event.userId!==P.get_distinct_id()&&(Eo.info("UserId set, identifying with PostHog"),P.identify(O.event.userId));var N=P.calculateEventProperties(L,O.event.properties);return O.event.properties=Object.assign({},N,O.event.properties),O};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:O=>$(O,O.event.event),page:O=>$(O,Vn),identify:O=>$(O,yo),screen:O=>$(O,"$screen")}})(I)).then((()=>{T()}))}))})(this,(()=>this.On())):this.On(),De(this.config._onCapture)&&this.config._onCapture!==us&&(A.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(I=>this.config._onCapture(I.event,I)))),this.config.ip&&A.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this.config.disableDeviceModel||(function(){return Df.apply(this,arguments)})().then((I=>{I&&this.register({[vo]:I})})).catch(us),this}Fn(){var e,n,i,r,s,o,a=(e=(n=this.config.__extensionClasses)==null?void 0:n.featureFlags)!==null&&e!==void 0?e:(i=Je.__defaultExtensionClasses)==null?void 0:i.featureFlags;a&&(this.featureFlags&&this.featureFlags instanceof a||((r=this.Dn)==null||r.call(this),this.Dn=void 0,this.featureFlags=new a(this)),De(this.featureFlags.onReloading)&&De(this.featureFlags.setup)?this.Dn||(this.Dn=this.featureFlags.onReloading((()=>{this.dn.emit("featureFlagsReloading",!0)})),this.$n().add(this.featureFlags)):(s=(o=this.featureFlags).initialize)==null||s.call(o))}Ln(e){var n,i,r,s,o,a,l,u=performance.now(),c=k({},Je.__defaultExtensionClasses,this.config.__extensionClasses),d=[];c.exceptions&&this.sn.push(this.exceptions=(n=this.exceptions)!==null&&n!==void 0?n:new c.exceptions(this)),c.historyAutocapture&&this.sn.push(this.historyAutocapture=new c.historyAutocapture(this)),c.tracingHeaders&&this.sn.push(this.tracingHeaders=new c.tracingHeaders(this)),c.siteApps&&this.sn.push(this.siteApps=new c.siteApps(this)),c.sessionRecording&&!e&&this.sn.push(this.sessionRecording=new c.sessionRecording(this)),this.config.disable_scroll_properties||d.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),c.autocapture&&this.sn.push(this.autocapture=new c.autocapture(this)),c.surveys&&this.sn.push(this.surveys=(i=this.surveys)!==null&&i!==void 0?i:new c.surveys(this)),c.logs&&this.sn.push(this.logs=(r=this.logs)!==null&&r!==void 0?r:new c.logs(this)),c.metrics&&this.sn.push(this.metrics=(s=this.metrics)!==null&&s!==void 0?s:new c.metrics(this)),c.conversations&&this.sn.push(this.conversations=(o=this.conversations)!==null&&o!==void 0?o:new c.conversations(this)),c.productTours&&this.sn.push(this.productTours=new c.productTours(this)),c.heatmaps&&this.sn.push(this.heatmaps=new c.heatmaps(this)),c.webVitalsAutocapture&&this.sn.push(this.webVitalsAutocapture=new c.webVitalsAutocapture(this)),c.exceptionObserver&&this.sn.push(this.exceptionObserver=new c.exceptionObserver(this)),c.deadClicksAutocapture&&this.sn.push(this.deadClicksAutocapture=new c.deadClicksAutocapture(this,Gg)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((f=>{f.initialize&&d.push((()=>{f.initialize==null||f.initialize()}))})),d.push((()=>{if(this.Nn){var f=this.Nn;this.Nn=void 0,this.sn.forEach((h=>h.onRemoteConfig==null?void 0:h.onRemoteConfig(f)))}})),this.qn(d,u)}qn(e,n){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,n)}),0);var i=e.shift();if(i)try{i()}catch(s){A.error("Error initializing extension:",s)}}var r=Math.round(performance.now()-n);this.register_for_session({[Xd]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[Qd]:r}),this.config.__preview_deferred_init_extensions&&A.info("PostHog extensions initialized ("+r+"ms)")}Zi(e){var n;if(!F||!F.body)return A.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.Zi(e)}),500);if(this.config.__preview_deferred_init_extensions&&(this.Nn=e),this.hn=e,this.compression=void 0,e.ok){var i,r=e.config;r.supportedCompression&&!this.config.disable_compression&&(this.compression=j(r.supportedCompression,je.GZipJS)?je.GZipJS:j(r.supportedCompression,je.Base64)?je.Base64:void 0),(i=r.analytics)!=null&&i.endpoint&&(this.analyticsDefaultEndpoint=r.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:pa}),(n=this.jn)==null||n.handleRemoteConfig(e),this.sn.forEach((s=>s.onRemoteConfig==null?void 0:s.onRemoteConfig(e)))}On(){try{this.config.loaded(this)}catch(i){A.critical("`loaded` function failed",i)}if(this.Bn(),this.config.internal_or_test_user_hostname&&me!=null&&me.hostname){var e=me.hostname,n=this.config.internal_or_test_user_hostname;(typeof n=="string"?e===n:n.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.gn())&&this.Hn()}),1),this.Un=new kf(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()&&vr(this.__request_queue,(e=>this.Pn(e))),this.__request_queue=[],this.Bn()}_handle_unload(){var e,n,i,r,s;(e=this.surveys)==null||e.handlePageUnload==null||e.handlePageUnload(),(n=this.metrics)==null||n.flush("sendBeacon"),this.config.request_batching?(this.zn()&&this.capture(_o),(i=this.logs)==null||i.flushLogs("sendBeacon"),(r=this.In)==null||r.unload(),(s=this.Rn)==null||s.unload()):this.zn()&&this.capture(_o,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?Vf?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)?e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:429})):(e.transport=e.transport||this.config.api_transport,e.headers=k({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,(C(this.config.disable_beacon)?this.config.__preview_disable_beacon:this.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(n=>{var i,r,s,o=k({},n);o.timeout=o.timeout||6e4;var a,l,u,c,d,f=(i=o.transport)!==null&&i!==void 0?i:"fetch";f==="sendBeacon"&&C(o.compression)&&o.data&&(o.compression=je.Base64),o.method==="POST"&&o.data&&(o.timestampMode==="capture-body"?o.data={api_key:(l=(d=(c=U(a=o.data)?a:[a])[0])==null||(u=d.properties)==null?void 0:u.token)!==null&&l!==void 0?l:d?.token,batch:c,sent_at:new Date().toISOString()}:o.timestampMode==="body"&&(o.data=(function(m,v){return v===void 0&&(v=new Date().toISOString()),U(m)?m.map((S=>k({},S,{sent_at:v}))):k({},m,{sent_at:v})})(o.data))),o.url=Zc(o.url,o.method,o.compression,o.timestampMode);var h=Lr.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),p=(r=(s=(function(m,v){for(var S=0;m.length>S;S++)if(m[S].transport===f)return m[S]})(h))==null?void 0:s.method)!==null&&r!==void 0?r:h[0].method;if(!p)throw new Error("No available transport method");var g=m=>{try{p(m)}catch(v){Nf(v)?A.warn(v):A.error(v),o.callback==null||o.callback({statusCode:0,error:v})}};f!=="sendBeacon"&&o.data&&o.compression===je.GZipJS&&Fp&&typeof Promise<"u"&&!Mr?um(o).then((m=>{g(m)})).catch((m=>{if(vc(m))return Mr=!0,void g(k({},o,{compression:void 0,url:Zc(n.url,n.method,void 0,n.timestampMode)}));(v=>{if(!v||typeof v!="object")return!1;var S="name"in v?String(v.name):"";return vc(v)||S===dd})(m)&&(Mr=!0),g(o)})):p(o)})(k({},e,{callback:n=>{var i,r;this.rateLimiter.checkForLimiting(n),400>n.statusCode||(i=(r=this.config).on_request_error)==null||i.call(r,n),e.callback==null||e.callback(n)}}))):e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:0}))}Pn(e){this.Rn?this.Rn.retriableRequest(e):this._send_request(e)}_execute_array(e){Ro++;try{var n,i=[],r=[],s=[];vr(e,(a=>{if(a)if(U(n=a[0]))s.push(a);else if(De(a))try{a.call(this)}catch(l){A.error("Error executing queued PostHog call",a,l)}else U(a)&&n==="alias"?i.push(a):U(a)&&n.indexOf("capture")!==-1&&De(this[n])?s.push(a):r.push(a)}));var o=function(a,l){vr(a,(function(u){try{if(U(u[0])){var c=l;ie(u,(function(d){c=c[d[0]].apply(c,d.slice(1))}))}else l[u[0]].apply(l,u.slice(1))}catch(d){A.error("Error executing queued PostHog call",u,d)}}))};o(i,this),o(r,this),o(s,this)}finally{Ro--}}push(e){if(Ro>0&&U(e)&&X(e[0])){var n=Je.prototype[e[0]];De(n)&&n.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,n,i){var r,s,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.In){if(this.is_capturing())if(!C(e)&&X(e)){var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var c=i!=null&&i.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(c==null||!c.isRateLimited){n!=null&&n.$current_url&&!X(n?.$current_url)&&(A.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),n==null||delete n.$current_url),e!=="$exception"||i!=null&&i.Wn||A.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,f=i?.timestamp||d,h=Ec(i?.uuid,Ht),p={uuid:h,event:e,properties:this.calculateEventProperties(e,n||{},f,h)};e===Vn&&this.config.__preview_capture_bot_pageviews&&u&&(p.event="$bot_pageview",p.properties.$browser_type="bot"),c&&(p.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&p.properties.$feature_flag_has_experiment===!1&&this.get_property(Zr)===!0;i?.$set&&!g&&(p.$set=i?.$set);var m=i?.$unset;m&&(p.$unset=m);var v,S,b,_=g?void 0:this.Vn(i?.$set_once,e!==Ac,e===yo);if(_&&(p.$set_once=_),i!=null&&i._noTruncate||(s=this.config.properties_string_max_length,o=p,a=L=>X(L)?L.slice(0,s):L,l=new Set,p=(function L(N,K){if(N!==Object(N))return a?a(N):N;if(!l.has(N)){var V;if(l.add(N),U(N))V=[],vr(N,(R=>{V.push(L(R))}));else{var M={};ie(N,((R,Z)=>{l.has(R)||(M[Z]=L(R))})),V=M}return V}})(o)),p.timestamp=f,C(i?.timestamp)||(p.properties.$event_time_override_provided=!0,p.properties.$event_time_override_system_time=d),g&&(p.properties=(function(L,N){N===void 0&&(N=[]);var K={},V=M=>{L[M]!==void 0&&(K[M]=L[M])};return Rp.forEach(V),N.forEach(V),K})(p.properties,Cm)),e===zt.DISMISSED||e===zt.SENT){var x=n?.[ko.SURVEY_ID],I=n?.[ko.SURVEY_ITERATION];qf({id:x,current_iteration:I}),p.$set=k({},p.$set,{[(v={id:x,current_iteration:I},S=e===zt.SENT?"responded":"dismissed",b="$survey_"+S+"/"+v.id,v.current_iteration&&v.current_iteration>0&&(b="$survey_"+S+"/"+v.id+"/"+v.current_iteration),b)]:!0})}else e===zt.SHOWN&&(p.$set=k({},p.$set,{[ko.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===nm.SHOWN){var T=n?.[zc.TOUR_TYPE];T&&(p.$set=k({},p.$set,{[zc.TOUR_LAST_SEEN_DATE+"/"+T]:new Date().toISOString()}))}var E=k({},p.properties.$set,p.$set);if(Kt(E)||this.setPersonPropertiesForFlags(E),!H(this.config.before_send)){var P=this.Pt(p);if(!P)return;(p=P).uuid=Ec(p.uuid,Ht)}this.dn.emit("eventCaptured",p);var $=(r=i?._url)!==null&&r!==void 0?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),O={method:"POST",url:$,data:p,compression:"best-available",timestampMode:i?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test($)?"body":"capture-body",batchKey:i?._batchKey,transport:i?.transport};return!this.config.request_batching||i&&(i==null||!i._batchKey)||i!=null&&i.send_instantly?this.Pn(O):this.In.enqueue(O),p}A.critical("This capture call is ignored due to client rate limiting.")}}else A.error("No event name provided to posthog.capture")}else A.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(n=>e(n.event,n)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new km(this)}cn(e){this._n.push(e);var n=!0;return()=>{if(n){n=!1;var i=this._n.indexOf(e);i!==-1&&this._n.splice(i,1)}}}calculateEventProperties(e,n,i,r,s){if(i=i||new Date,!this.persistence||!this.sessionPersistence)return n;var o=s?void 0:this.persistence.remove_event_timer(e),a=k({},n);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.gn()&&(a[Zd]=!0),e==="$snapshot"){var l=k({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!X(a.distinct_id)&&!ke(a.distinct_id)||Ko(a.distinct_id))&&A.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=(function(x,I,T,E){var P,$,O,L;if(E===void 0&&(E=!1),!Ve)return{};var N,K=x?[...ri,...I||[]]:[],V=(function(Bn){for(var qe=0;wc.length>qe;qe++){var Dn=wc[qe],Mt=Dn[1],Lt=Dn[0].exec(Bn),ct=Lt&&(De(Mt)?Mt(Lt,Bn):Mt);if(ct)return ct}return["",""]})(Ve),M=V[0],R=V[1],Z=(N=typeof navigator<"u"?navigator:void 0)!=null&&N.brave?{brave:!0}:{},Ce={};C(T)||(Ce.detectGoogleSearchApp=T);var oe={},ye=(P=navigator)==null||(P=P.userAgentData)==null?void 0:P.platform,$e=($=navigator)==null?void 0:$.maxTouchPoints,ae=w==null||(O=w.screen)==null?void 0:O.width,Ie=w==null||(L=w.screen)==null?void 0:L.height,Se=w?.devicePixelRatio;C(ye)||(oe.userAgentDataPlatform=ye),C($e)||(oe.maxTouchPoints=$e),C(ae)||(oe.screenWidth=ae),C(Ie)||(oe.screenHeight=Ie),C(Se)||(oe.devicePixelRatio=Se);var Be,wt,ge,Ye,bt,mn,Re,Pe,$t=fe(ll({$os:M,$os_version:R,$browser:Nd(Ve,navigator.vendor,Z,Ce),$device:bc(Ve),$device_type:(wt=Ve,ge=oe,Pe=bc(wt),Pe===_d||Pe===vd||Pe==="Kobo"||Pe==="Kindle Fire"||Pe===Rd?ei:Pe===Gi||Pe===Xn||Pe===Ki||Pe===Jo?"Console":Pe===wd?"Wearable":Pe?it:ge?.userAgentDataPlatform==="Android"&&((Ye=ge?.maxTouchPoints)!==null&&Ye!==void 0?Ye:0)>0?600>Math.min((bt=ge?.screenWidth)!==null&&bt!==void 0?bt:0,(mn=ge?.screenHeight)!==null&&mn!==void 0?mn:0)/((Re=ge?.devicePixelRatio)!==null&&Re!==void 0?Re:1)?it:ei:"Desktop"),$timezone:If(),$timezone_offset:Qg()}),{$current_url:Zi(E?fn(me?.href):me?.href,K,Xi),$host:me?.host,$pathname:me?.pathname,$raw_user_agent:Ve.length>1e3?Ve.substring(0,997)+"...":Ve,$browser_version:Jp(Ve,navigator.vendor,Z,Ce),$browser_language:qc(),$browser_language_prefix:(Be=qc(),typeof Be=="string"?Be.split("-")[0]:void 0),$screen_height:w?.screen.height,$screen_width:w?.screen.width,$viewport_height:w?.innerHeight,$viewport_width:w?.innerWidth,$lib:ne.LIB_NAME,$lib_version:ne.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return ne.SDK_DIST_CHANNEL&&($t.$sdk_dist_channel=ne.SDK_DIST_CHANNEL),$t})(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties,this.config.detect_google_search_app,this.config.disable_capture_url_hashes);if(this.sessionManager){var d=this.sessionManager.checkAndGetSessionAndWindowId(s,i.getTime()),f=d.windowId;a.$session_id=d.sessionId,a.$window_id=f}this.sessionPropsManager&&fe(a,this.sessionPropsManager.getSessionProps());try{var h;this.sessionRecording&&fe(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(h=this.Rn)==null?void 0:h.length}catch(x){a.$sdk_debug_error_capturing_properties=String(x)}if(this.requestRouter.region===xa&&(a.$lib_custom_api_host=this.config.api_host),u=e!==Vn||s?e!==_o||s?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(i):this.pageViewManager.doPageView(i,r),a=fe(a,u),e===Vn&&F&&(a.title=F.title),!C(o)){var p=i.getTime()-o;a.$duration=parseFloat((p/1e3).toFixed(3))}Ve&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();ie(["$referrer","$referring_domain"],(x=>{x in g&&delete m[x]}));var v={};if(this._n.length>0)for(var S of this._n.slice())try{fe(v,S())}catch(x){A.error("Failed to produce browser extension event properties",x)}(a=fe({},c,g,m,k({},v,a))).$is_identified=this._isIdentified(),U(this.config.property_denylist)?ie(this.config.property_denylist,(function(x){delete a[x]})):A.error(zf+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var b=this.config.sanitize_properties;b&&(A.error(iu),a=b(a,e));var _=this.Zn();return a.$process_person_profile=_,_&&!s&&this.Gn("_calculate_event_properties"),a}Vn(e,n,i){var r;if(n===void 0&&(n=!0),i===void 0&&(i=!1),!this.persistence||!this.Zn()||this.mn&&!i)return e;var s=this.persistence.get_initial_props(),o=(r=this.sessionPropsManager)==null?void 0:r.getSetOnceProps(),a=fe({},s,o||{},e||{}),l=this.config.sanitize_properties;return l&&(A.error(iu),a=l(a,"$set_once")),n&&(this.mn=!0),Kt(a)?void 0:a}register(e,n){var i;(i=this.persistence)==null||i.register(e,n)}register_once(e,n,i){var r;(r=this.persistence)==null||r.register_once(e,n,i)}register_for_session(e){var n;(n=this.sessionPersistence)==null||n.register(e),Object.keys(e).forEach((i=>this.yn.add(i))),this.Qn()}unregister(e){var n;(n=this.persistence)==null||n.unregister(e)}unregister_for_session(e){var n;(n=this.sessionPersistence)==null||n.unregister(e),this.yn.delete(e),this.Qn()}Kn(e,n){this.register({[e]:n})}An(){this.yn.forEach((e=>{var n;(n=this.sessionPersistence)==null||n.unregister(e)})),this.yn.clear(),this.Qn()}Qn(){var e;if(this.bn)if(this.config.persistence==="memory"||(e=this.sessionPersistence)!=null&&e.xi||!be.N())be.q(this.bn);else{var n=[];this.yn.forEach((i=>n.push(i))),n.length>0?be.F(this.bn,n):be.q(this.bn)}}getFeatureFlag(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlag(e,n)}getFeatureFlagPayload(e){var n;return(n=this.featureFlags)==null?void 0:n.getFeatureFlagPayload(e)}getFeatureFlagResult(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlagResult(e,n)}getAllFeatureFlags(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.getAllFeatureFlags())!==null&&e!==void 0?e:[]}isFeatureEnabled(e,n){var i,r;return(i=(r=this.featureFlags)==null?void 0:r.isFeatureEnabled(e,n))!==null&&i!==void 0?i:n?.defaultValue}reloadFeatureFlags(){var e;(e=this.featureFlags)==null||e.reloadFeatureFlags()}updateFlags(e,n,i){var r;(r=this.featureFlags)==null||r.updateFlags(e,n,i)}updateEarlyAccessFeatureEnrollment(e,n,i){var r;(r=this.featureFlags)==null||r.updateEarlyAccessFeatureEnrollment(e,n,i)}getEarlyAccessFeatures(e,n,i){var r;return n===void 0&&(n=!1),(r=this.featureFlags)==null?void 0:r.getEarlyAccessFeatures(e,n,i)}on(e,n){return this.dn.on(e,n)}onFeatureFlags(e){return this.featureFlags?this.featureFlags.onFeatureFlags(e):(e([],{},{errorsLoading:!0}),()=>{})}onSurveysLoaded(e){return this.surveys?this.surveys.onSurveysLoaded(e):(e([],{isLoaded:!1,error:xi}),()=>{})}onSessionId(e){var n,i;return(n=(i=this.sessionManager)==null?void 0:i.onSessionId(e))!==null&&n!==void 0?n:()=>{}}getSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getSurveys(e,n):e([],{isLoaded:!1,error:xi})}getActiveMatchingSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,n):e([],{isLoaded:!1,error:xi})}renderSurvey(e,n){var i;(i=this.surveys)==null||i.renderSurvey(e,n)}displaySurvey(e,n){var i;n===void 0&&(n=wm),(i=this.surveys)==null||i.displaySurvey(e,n)}cancelPendingSurvey(e){var n;(n=this.surveys)==null||n.cancelPendingSurvey(e)}canRenderSurvey(e){var n,i;return(n=(i=this.surveys)==null?void 0:i.canRenderSurvey(e))!==null&&n!==void 0?n:{visible:!1,disabledReason:xi}}canRenderSurveyAsync(e,n){var i,r;return n===void 0&&(n=!1),(i=(r=this.surveys)==null?void 0:r.canRenderSurveyAsync(e,n))!==null&&i!==void 0?i:Promise.resolve({visible:!1,disabledReason:xi})}Jn(e){return!e||Ko(e)?(A.critical("Unique user id has not been set in posthog.identify"),!1):e===mr?(A.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.'),!1):!["distinct_id","distinctid"].includes(e.toLowerCase())&&!["undefined","null"].includes(e.toLowerCase())||(A.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.'),!1)}identify(e,n,i){if(!this.__loaded||!this.persistence)return A.uninitializedWarning("posthog.identify");if(ke(e)&&(e=e.toString(),A.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.Jn(e)&&this.Gn("posthog.identify")){var r=this.get_distinct_id();this.register({$user_id:e}),this.get_property(Yi)||this.register_once({$had_persisted_distinct_id:!0,$device_id:r},""),e!==r&&e!==this.get_property(Fi)&&(this.unregister(Fi),this.register({distinct_id:e}));var s,o=(this.persistence.get_property(ot)||Un)===Un,a=e!==r,l=!a&&o;if(a&&o)this.persistence.set_property(ot,vn),this.setPersonPropertiesForFlags({$set:n||{},$set_once:i||{}},!1),this.capture(yo,{distinct_id:e,$anon_distinct_id:r},{$set:n||{},$set_once:i||{}}),this.Sn=Fo(e,n,i),(s=this.featureFlags)==null||s.setAnonymousDistinctId(r);else if(l){this.persistence.set_property(ot,vn);var u=n||{},c=i||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=Fo(e,n,i)}else(n||i)&&this.setPersonProperties(n,i);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Cn)):l&&(n||i)&&this.reloadFeatureFlags()}}setPersonProperties(e,n){if((e||n)&&this.Gn("posthog.setPersonProperties")){var i=Fo(this.get_distinct_id(),e,n);this.Sn!==i?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:n||{}},!0),this.capture("$set",{$set:e||{},$set_once:n||{}}),this.Sn=i):A.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}unsetPersonProperties(e){var n,i=(U(e)?e:[e]).filter((r=>X(r)&&r.length>0));i.length!==0&&this.Gn("posthog.unsetPersonProperties")&&((n=this.featureFlags)==null||n.unsetPersonPropertiesForFlags(i,!0),this.capture("$set",{$unset:i}),this.Sn=null)}group(e,n,i){if(e&&n){var r=this.getGroups(),s=r[e]!==n;if(s&&this.resetGroupPropertiesForFlags(e),this.register({$groups:k({},r,{[e]:n})}),s||i){var o={$group_type:e,$group_key:n};i&&(o.$group_set=i),this.capture(Ac,o)}i&&this.setGroupPropertiesForFlags({[e]:i}),s&&!i&&this.reloadFeatureFlags()}else A.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),(i=this.featureFlags)==null||i.setPersonPropertiesForFlags(e,n)}resetPersonPropertiesForFlags(e){var n;e===void 0&&(e=!0),(n=this.featureFlags)==null||n.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((i=this.featureFlags)==null||i.setGroupPropertiesForFlags(e,n))}resetGroupPropertiesForFlags(e){var n;(n=this.featureFlags)==null||n.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,n){var i,r,s,o,a,l,u,c,d,f;if(n===void 0&&(n=!1),A.info("reset"),!this.__loaded)return A.uninitializedWarning("posthog.reset");var h,p=this.get_property(Yi),g=this.get_property(vo),m=this.get_property(An),v=this.is_capturing();if(this.consent.reset(),n||!v||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after."),(i=this.persistence)==null||i.clear(),(r=this.sessionPersistence)==null||r.clear(),this.yn.clear(),this.Qn(),C(m)||(h=this.persistence)==null||h.register({[An]:m}),(s=this.surveys)==null||s.reset(),(o=this.Un)==null||o.stop(),(a=this.featureFlags)==null||a.reset(),(l=this.conversations)==null||l.reset(),(u=this.logs)==null||u.reset(),(c=this.metrics)==null||c.reset(),(d=this.persistence)==null||d.set_property(ot,Un),(f=this.sessionManager)==null||f.resetSessionId(),this.Sn=null,this.config.cookieless_mode===Wt)this.register_once({distinct_id:mr,$device_id:null},"");else{var S=this.config.get_device_id(Ht());this.register_once({distinct_id:S,$device_id:e?S:p},""),e||C(g)||this.register({[vo]:g})}this.register({$last_posthog_reset:new Date().toISOString()},1),delete this.config.identity_distinct_id,delete this.config.identity_hash,this.reloadFeatureFlags()}shutdown(e){var n=this;return se((function*(){var i,r,s,o,a,l,u;if(n.__loaded){(i=n.Un)==null||i.stop(),(r=n.jn)==null||r.dispose(),(s=n.sessionRecording)==null||s.dispose(),(o=n.logs)==null||o.flushLogs("sendBeacon"),(a=n.metrics)==null||a.flush("sendBeacon"),(l=n.In)==null||l.unload(),(u=n.Rn)==null||u.unload();try{var c;(c=n.featureFlags)==null||c.destroy()}catch(d){A.error("Error while destroying feature flags",d)}}else A.uninitializedWarning("posthog.shutdown")}))()}setIdentity(e,n){var i;this.config.identity_distinct_id=e,this.config.identity_hash=n,this.alias(e),(i=this.conversations)==null||i.Xn()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,(e=this.conversations)==null||e.ts()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,n;return(e=(n=this.sessionManager)==null?void 0:n.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var n=this.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.sessionStartTimestamp,r=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+n.sessionId);if(e!=null&&e.withTimestamp&&i){var s,o=(s=e.timestampLookBack)!==null&&s!==void 0?s:10;if(!i)return r;r+="?t="+Math.max(Math.floor((new Date().getTime()-i)/1e3)-o,0)}return r}alias(e,n){return e===this.get_property(zd)?(A.critical("Attempting to create alias for existing People user - aborting."),-2):this.Gn("posthog.alias")?(C(n)&&(n=this.get_distinct_id()),e!==n?(this.Kn(Fi,e),this.capture("$create_alias",{alias:e,distinct_id:n})):(A.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var n=k({},this.config);if(he(e)){var i,r,s,o,a,l,u,c,d,f,h,p;fe(this.config,ru(e));var g=this.En();(i=this.persistence)==null||i.update_config(this.config,n,g),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new xo(k({},this.config,{persistence:"sessionStorage"}),g,!1);var m=this.Cn(this.config.debug);gt(m)&&(this.config.debug=m),gt(this.config.debug)&&(this.config.debug?(ne.DEBUG=!0,le.N()&&le.F("ph_debug",!0),A.info("set_config",{config:e,oldConfig:n,newConfig:k({},this.config)})):(ne.DEBUG=!1,le.N()&&le.q("ph_debug"))),(r=this.featureFlags)==null||r.updateConfig==null||r.updateConfig(this.config,this.Qi()),(s=this.exceptionObserver)==null||s.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(f=this.deadClicksAutocapture)==null||f.startIfEnabledOrStop(),(h=this.surveys)==null||h.loadIfEnabled(),this.es(),(p=this.externalIntegrations)==null||p.startIfEnabledOrStop()}}_overrideSDKInfo(e,n){ne.LIB_NAME=e,ne.LIB_VERSION=n}startSessionRecording(e){var n,i,r,s,o,a=e===!0,l={sampling:a||!(e==null||!e.sampling),linked_flag:a||!(e==null||!e.linked_flag),url_trigger:a||!(e==null||!e.url_trigger),event_trigger:a||!(e==null||!e.event_trigger)};Object.values(l).some(Boolean)&&((n=this.sessionManager)==null||n.checkAndGetSessionAndWindowId(),l.sampling&&((i=this.sessionRecording)==null||i.overrideSampling()),l.linked_flag&&((r=this.sessionRecording)==null||r.overrideLinkedFlag()),l.url_trigger&&((s=this.sessionRecording)==null||s.overrideTrigger("url")),l.event_trigger&&((o=this.sessionRecording)==null||o.overrideTrigger("event"))),this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,n){if(this.exceptions){var i=new Error("PostHog syntheticException"),r=this.exceptions.buildProperties(e,{handled:!0,syntheticException:i});return this.exceptions.sendExceptionEvent(k({},r,n))}}addExceptionStep(e,n){var i;(i=this.exceptions)==null||i.addExceptionStep(e,n)}captureLog(e){var n;(n=this.logs)==null||n.captureLog(e)}get logger(){var e,n;return(e=(n=this.logs)==null?void 0:n.logger)!==null&&e!==void 0?e:Je.rs}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var n,i;return(n=(i=this.toolbar)==null?void 0:i.loadToolbar(e))!==null&&n!==void 0&&n}get_property(e){var n;return(n=this.persistence)==null?void 0:n.props[e]}getSessionProperty(e){var n;return(n=this.sessionPersistence)==null?void 0:n.props[e]}toString(){var e,n=(e=this.config.name)!==null&&e!==void 0?e:Gn;return n!==Gn&&(n=Gn+"."+n),n}_isIdentified(){var e,n;return((e=this.persistence)==null?void 0:e.get_property(ot))===vn||((n=this.sessionPersistence)==null?void 0:n.get_property(ot))===vn}Zn(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles===pa&&!this._isIdentified()&&Kt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[Fi])&&((n=this.persistence)==null||(n=n.props)==null||!n[es]))}zn(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Zn()||this.Gn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.Gn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}Gn(e){return this.config.person_profiles==="never"?(A.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Kn(es,!0),!0)}En(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut();return this.config.disable_persistence||e&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!==kn)}es(){var e,n,i,r,s=this.En();return((e=this.persistence)==null?void 0:e.xi)!==s&&((i=this.persistence)==null||i.set_disabled(s)),((n=this.sessionPersistence)==null?void 0:n.xi)!==s&&((r=this.sessionPersistence)==null||r.set_disabled(s)),s&&(this.yn.clear(),this.Qn()),s}opt_in_capturing(e){var n;if(this.config.cookieless_mode!==Wt){if(this.gn()){var i,r,s,o,a;this.Yn(!0,!0),(i=this.sessionManager)==null||i.destroy(),(r=this.pageViewManager)==null||r.destroy(),this.sessionManager=new Qc(this),this.pageViewManager=new Wc(this),this.persistence&&(this.sessionPropsManager=new Xc(this,this.sessionManager,this.persistence));var l,u=(s=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&s!==void 0?s:(a=Je.__defaultExtensionClasses)==null?void 0:a.sessionRecording;u&&(this.sessionRecording=this.pn(this.sessionRecording,new u(this)),this.hn&&((l=this.sessionRecording)==null||l.onRemoteConfig==null||l.onRemoteConfig(this.hn)))}var c,d;this.consent.optInOut(!0),this.es(),this.Bn(),(n=this.sessionRecording)==null||n.startIfEnabledOrStop(),this.config.cookieless_mode==kn&&((c=this.surveys)==null||c.loadIfEnabled()),(C(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((d=e?.captureEventName)!==null&&d!==void 0?d:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hn()}else A.warn(nu)}opt_out_capturing(){var e,n,i;this.config.cookieless_mode!==Wt?(this.config.cookieless_mode===kn&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===kn&&(this.register({distinct_id:mr,$device_id:null}),(e=this.sessionRecording)==null||e.stopRecording(),this.sessionRecording=void 0,(n=this.sessionManager)==null||n.destroy(),(i=this.pageViewManager)==null||i.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.Hn(),this.Bn())):A.warn(nu)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===Wt||(this.config.cookieless_mode===kn?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return Ue?Bf(Ue,this.config.custom_blocked_useragents):void 0}Hn(){F&&(F.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(Vn,{title:F.title},{send_instantly:!0}),this.kn&&(F.removeEventListener(ts,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),ve(F,ts,this.kn)))}debug(e){e===!1?(w?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(w?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}Qi(){var e=this.Mn||{};return"advanced_disable_flags"in e?!!e.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(A.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(function(n,i,r,s,o){var a=i in n&&!H(n[i]),l=r in n&&!H(n[r]);return a?n[i]:!!l&&(o&&o.warn("Config field '"+r+"' is deprecated. Please use '"+i+"' instead. The old field will be removed in a future major version."),n[r])})(e,"advanced_disable_flags","advanced_disable_decide",0,A)}Pt(e){var n;if(H(this.config.before_send))return e;var i=Object.keys((n=e.properties)!==null&&n!==void 0?n:{}).filter(Bp),r=U(this.config.before_send)?this.config.before_send:[this.config.before_send],s=e;for(var o of r){if(s=o(s),H(s)){var a="Event '"+e.event+"' was rejected in beforeSend function";return Op(e.event)?A.warn(a+". This can cause unexpected behavior."):A.info(a),null}s.properties&&!Kt(s.properties)||A.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}for(var l of i)if(s.properties&&H(s.properties[l]))return A.warn("Event '"+e.event+"' had its '"+l+"' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped."),null;return s}getPageViewId(){var e;return(e=this.pageViewManager.ui)==null?void 0:e.pageViewId}captureTraceFeedback(e,n){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:n})}captureTraceMetric(e,n,i){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:n,$ai_metric_value:String(i)})}Cn(e){var n=gt(e)&&!e,i=le.N()&&le.P("ph_debug")==="true";return!n&&(!!i||e)}}Je.__defaultExtensionClasses={},Je.rs=(()=>{var t=()=>{};return{trace:t,debug:t,info:t,warn:t,error:t,fatal:t}})(),(function(t,e){for(var n=0;e.length>n;n++)t.prototype[e[n]]=kg(t.prototype[e[n]])})(Je,["identify"]);class su{constructor(e){this.disabled=e===!1;var n=he(e)?e:{};this.thresholdPx=n.threshold_px||30,this.timeoutMs=n.timeout_ms||1e3,this.clickCount=n.click_count||3,this.clicks=[]}isRageClick(e,n,i){if(this.disabled)return!1;var r=this.clicks[this.clicks.length-1];if(r&&Math.abs(e-r.x)+Math.abs(n-r.y)i-r.timestamp){if(this.clicks.push({x:e,y:n,timestamp:i}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:n,timestamp:i}];return!1}}var $o="$copy_autocapture",Mo=pe("[AutoCapture]");function Lo(t,e){return e.length>t?e.slice(0,t)+"...":e}function Fm(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!hn(e));return e}function Rm(t,e){var n,i,r=e.e,s=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!hn(t))return{props:{}};for(var c=[t],d=new Set([t]),f=t;f.parentNode&&!Qe(f,"body")&&lf>c.length;)if(af(f.parentNode)){var h=f.parentNode.host;if(d.has(h))break;d.add(h),c.push(h),f=h}else{if(!hn(f.parentNode)||d.has(f.parentNode))break;d.add(f.parentNode),c.push(f.parentNode),f=f.parentNode}var p,g,m=[],v={},S=!1,b=!1;if(ie(c,(E=>{var P=va(E);if(Qe(E,"a")){var $=E.getAttribute("href");S=!!(P&&$&&Ui($))&&(u?fn($):$)}j(rs(E),"ph-no-capture")&&(b=!0),m.push((function(L,N,K,V,M){M===void 0&&(M=!1);var R=L.tagName.toLowerCase(),Z={tag_name:R};ul.indexOf(R)>-1&&!K&&(Z.$el_text=R.toLowerCase()==="a"||R.toLowerCase()==="button"?Lo(1024,jc(L)):Lo(1024,Ji(L)));var Ce=rs(L);Ce.length>0&&(Z.classes=Ce.filter((function(ae){return ae!==""}))),ie(L.attributes,(function(ae){var Ie;if((!hf(L)||["name","id","class","aria-label"].indexOf(ae.name)!==-1)&&(V==null||!V.includes(ae.name))&&!N&&Ui(ae.value)&&(!X(Ie=ae.name)||Ie.substring(0,10)!=="_ngcontent"&&Ie.substring(0,7)!=="_nghost")){var Se=ae.value;ae.name==="class"&&(Se=cl(Se).join(" ")),Z["attr__"+ae.name]=Lo(1024,ae.name==="href"&&M?fn(Se):Se)}}));for(var oe=1,ye=1,$e=L;$e=Fm($e);)oe++,$e.tagName===L.tagName&&ye++;return Z.nth_child=oe,Z.nth_of_type=ye,Z})(E,s,o,a,u));var O=(function(L){if(!va(L))return{};var N={};return ie(L.attributes,(function(K){if(K.name&&K.name.indexOf("data-ph-capture-attribute")===0){var V=K.name.replace("data-ph-capture-attribute-",""),M=K.value;V&&M&&Ui(M)&&(N[V]=M)}})),N})(E);fe(v,O)})),b)return{props:{},explicitNoCapture:b};if(o||(m[0].$el_text=Qe(t,"a")||Qe(t,"button")?jc(t):Ji(t)),S){var _,x;m[0].attr__href=S;var I=(_=ss(S))==null?void 0:_.host,T=w==null||(x=w.location)==null?void 0:x.host;I&&T&&I!==T&&(p=S)}return{props:fe({$event_type:r.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(E){return E.map((P=>{var $,O,L="";if(P.tag_name&&(L+=P.tag_name),P.attr_class)for(var N of(P.attr_class.sort(),P.attr_class))L+="."+N.replace(/"/g,"");var K=k({},P.text?{text:P.text}:{},{"nth-child":($=P.nth_child)!==null&&$!==void 0?$:0,"nth-of-type":(O=P.nth_of_type)!==null&&O!==void 0?O:0},P.href?{href:P.href}:{},P.attr_id?{attr_id:P.attr_id}:{},P.attributes),V={};return $r(K).sort(((M,R)=>M[0].localeCompare(R[0]))).forEach((M=>{var R=M[1];return V[Uc(M[0].toString())]=Uc(R.toString())})),(L+=":")+$r(V).map((M=>M[0]+'="'+M[1]+'"')).join("")})).join(";")})((function(E){return E.map((P=>{var $,O,L={text:($=P.$el_text)==null?void 0:$.slice(0,400),tag_name:P.tag_name,href:(O=P.attr__href)==null?void 0:O.slice(0,2048),attr_class:zg(P),attr_id:P.attr__id,nth_child:P.nth_child,nth_of_type:P.nth_of_type,attributes:{}};return $r(P).filter((N=>N[0].indexOf("attr__")===0)).forEach((N=>L.attributes[N[0]]=N[1])),L}))})(g)))},(n=m[0])!=null&&n.$el_text?{$el_text:(i=m[0])==null?void 0:i.$el_text}:{},p&&r.type==="click"?{$external_click_url:p}:{},v)}}var Ii=pe("[ExceptionAutocapture]"),ou=()=>{},Tm=pe("[TracingHeaders]"),wn=pe("[Web Vitals]"),au=9e5,lu="disabled",cu="lazy_loading",ki="awaiting_config",Sr="missing_config";pe("[SessionRecording]"),pe("[SessionRecording]");var Ia="[SessionRecording]",Bt=pe(Ia),$m=pe("[Heatmaps]");function No(t){return he(t)&&"clientX"in t&&"clientY"in t&&ke(t.clientX)&&ke(t.clientY)}var xr=pe("[Product Tours]"),Oo=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(sl))},Mm=["$set_once","$set"],Et=pe("[SiteApps]"),uu="Error while initializing PostHog app with config id ";function qn(t,e,n){if(H(t))return!1;switch(n){case"exact":return t===e;case"contains":var i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(i,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}class Lm{constructor(e){this.ns=new pl,this.ss=(n,i)=>this.os(n,i)&&this.ls(n,i)&&this.us(n,i)&&this.hs(n,i),this.os=(n,i)=>i==null||!i.event||n?.event===i?.event,this._instance=e,this.ds=new Set,this.vs=new Set}init(){var e,n;C((e=this._instance)==null?void 0:e._addCaptureHook)||(n=this._instance)==null||n._addCaptureHook(((i,r)=>{this.on(i,r)}))}register(e){var n,i;if(!C((n=this._instance)==null?void 0:n._addCaptureHook)&&(e.forEach((o=>{var a,l;(a=this.vs)==null||a.add(o),(l=o.steps)==null||l.forEach((u=>{var c;(c=this.ds)==null||c.add(u?.event||"")}))})),(i=this._instance)!=null&&i.autocapture)){var r,s=new Set;e.forEach((o=>{var a;(a=o.steps)==null||a.forEach((l=>{l!=null&&l.selector&&s.add(l?.selector)}))})),(r=this._instance)==null||r.autocapture.setElementSelectors(s)}}on(e,n){var i;n!=null&&e.length!=0&&(this.ds.has(e)||this.ds.has(n.event))&&this.vs&&((i=this.vs)==null?void 0:i.size)>0&&this.vs.forEach((r=>{this.cs(n,r)&&this.ns.emit("actionCaptured",r.name)}))}fs(e){this.onAction("actionCaptured",(n=>e(n)))}cs(e,n){if(n?.steps==null)return!1;for(var i of n.steps)if(this.ss(e,i))return!0;return!1}onAction(e,n){return this.ns.on(e,n)}ls(e,n){if(n!=null&&n.url){var i,r=e==null||(i=e.properties)==null?void 0:i.$current_url;if(!r||typeof r!="string"||!qn(r,n.url,n.url_matching||"contains"))return!1}return!0}us(e,n){return!!this.ps(e,n)&&!!this.gs(e,n)&&!!this.ys(e,n)}ps(e,n){var i;if(n==null||!n.href)return!0;var r=this.bs(e);if(r.length>0)return r.some((a=>qn(a.href,n.href,n.href_matching||"exact")));var s,o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!o&&qn((s=o.match(/(?::|")href="(.*?)"/))?s[1]:"",n.href,n.href_matching||"exact")}gs(e,n){var i;if(n==null||!n.text)return!0;var r=this.bs(e);if(r.length>0)return r.some((u=>qn(u.text,n.text,n.text_matching||"exact")||qn(u.$el_text,n.text,n.text_matching||"exact")));var s,o,a,l=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!l&&(s=(function(u){for(var c,d=[],f=/(?::|")text="(.*?)"/g;!H(c=f.exec(u));)d.includes(c[1])||d.push(c[1]);return d})(l),o=n.text,a=n.text_matching||"exact",s.some((u=>qn(u,o,a))))}ys(e,n){var i,r;if(n==null||!n.selector)return!0;var s=e==null||(i=e.properties)==null?void 0:i.$element_selectors;if(s!=null&&s.includes(n.selector))return!0;var o=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";if(n.selector_regex&&o)try{return new RegExp(n.selector_regex).test(o)}catch{return!1}return!1}bs(e){var n;return(e==null||(n=e.properties)==null?void 0:n.$elements)==null?[]:e?.properties.$elements}hs(e,n){return n==null||!n.properties||n.properties.length===0||Uf(n.properties.reduce(((i,r)=>{var s=U(r.value)?r.value.map(String):r.value!=null?[String(r.value)]:[];return i[r.key]={values:s,operator:r.operator||"exact"},i}),{}),e?.properties)}}class Nm{constructor(e){var n;this._s=[],this._instance=e,this.ws=new Map,this.ks=new Map,this.xs=new Map,(n=this._instance)==null||n.onSessionId==null||n.onSessionId((i=>this.Ss(i)))}Cs(e){return!1}Ms(){return null}Ts(e){}Es(){}Is(e,n){return!!e&&Uf(e.propertyFilters,n?.properties)}Ps(e,n){var i=new Map;return e.forEach((r=>{var s;(s=r.conditions)==null||(s=s[n])==null||(s=s.values)==null||s.forEach((o=>{if(o!=null&&o.name){var a=i.get(o.name)||[];a.push(r.id),i.set(o.name,a)}}))})),i}Rs(e,n,i){var r=(i===wi.Activation?this.ws:this.ks).get(e),s=[];return this.As((o=>{s=o.filter((a=>r?.includes(a.id)))})),s.filter((o=>{var a,l=(a=o.conditions)==null||(a=a[i])==null||(a=a.values)==null?void 0:a.find((u=>u.name===e));return this.Is(l,n)}))}register(e){var n;C((n=this._instance)==null?void 0:n._addCaptureHook)||(this.Fs(e),this.Ls(e))}Ls(e){var n=e.filter((i=>{var r,s;return((r=i.conditions)==null?void 0:r.actions)&&((s=i.conditions)==null||(s=s.actions)==null||(s=s.values)==null?void 0:s.length)>0}));n.length!==0&&(this.Os==null&&(this.Os=new Lm(this._instance),this.Os.init(),this.Os.fs((i=>{this.onAction(i)}))),n.forEach((i=>{var r,s,o,a,l;i.conditions&&(r=i.conditions)!=null&&r.actions&&(s=i.conditions)!=null&&(s=s.actions)!=null&&s.values&&((o=i.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.Os)==null||a.register(i.conditions.actions.values),(l=i.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var c=this.xs.get(u.name);c&&c.push(i.id),this.xs.set(u.name,c||[i.id])}})))})))}Fs(e){var n,i=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.events)&&((a=s.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0})),r=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.cancelEvents)&&((a=s.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0}));i.length===0&&r.length===0||((n=this._instance)==null||n._addCaptureHook(((s,o)=>{this.onEvent(s,o)})),this.ws=this.Ps(e,wi.Activation),this.ks=this.Ps(e,wi.Cancellation))}onEvent(e,n){var i,r,s=this.Ds(),o=(n==null||(i=n.properties)==null?void 0:i.$survey_id)||(n==null||(r=n.properties)==null?void 0:r.$product_tour_id);if(o&&this.getActivatedIds().includes(o)){var a=this.$s(e,o);if(a==="consume")return s.info("event consumed activated item, removing it",{event:e,itemId:o}),void this.Ns([o]);if(a==="persist")return s.info("shown item promoted to persisted activation",{event:e,itemId:o}),this.qs(o),void this.js([o])}if(this.ks.has(e)){var l=this.Rs(e,n,wi.Cancellation);l.length>0&&(s.info("cancel event matched, cancelling items",{event:e,itemsToCancel:l.map((c=>c.id))}),this.Ns(l.map((c=>c.id))),l.forEach((c=>this.Bs(c.id))))}if(this.ws.has(e)){s.info("event name matched",{event:e,eventPayload:n,items:this.ws.get(e)});var u=this.Rs(e,n,wi.Activation);this.Hs(u.map((c=>c.id)))}}onAction(e){this.xs.has(e)&&this.Hs(this.xs.get(e)||[])}Hs(e){var n;if(e.length!==0){var i=!((n=this._instance)==null||n.get_session_id==null||!n.get_session_id()),r=[];for(var s of e)i&&this.Cs(s)?this.qs(s)&&this.Us(s):r.push(s);r.length>0&&(this._s=[...new Set([...this._s,...r])]),this.Ds().info("updating activated items",{activatedItems:this.getActivatedIds()})}}qs(e){this._s=this._s.filter((i=>i!==e));var n=this.zs();return!n.includes(e)&&(this.Ws([...n,e]),this.Vs(),!0)}Ns(e){var n=new Set(e);this._s=this._s.filter((s=>!n.has(s)));var i=this.Zs(),r=i.filter((s=>!n.has(s)));r.length!==i.length&&(this.Ws(r),r.length===0&&this.Gs()),this.js(e)}Qs(){var e,n=this.Ms();if(!n)return{};var i=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n];return i&&typeof i=="object"?i:{}}Us(e){if(this.Ms()){var n=this.Qs();this.Ts(k({},n,{[e]:Date.now()}))}}js(e){if(this.Ms()){var n=this.Qs(),i={},r=!1;for(var s of Object.entries(n)){var o=s[0],a=s[1];e.includes(o)?r=!0:i[o]=a}r&&(Kt(i)?this.Es():this.Ts(i))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var n=this.Qs()[e];return ke(n)?n:void 0}}Zs(){var e,n=this.Js();return((e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n])||[]}zs(){var e,n,i=this.Zs();if(i.length===0)return[];var r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[this.Ys()],s=(n=this._instance)==null||n.get_session_id==null?void 0:n.get_session_id();return s&&r===s?i:[]}Vs(){var e,n=(e=this._instance)==null||e.get_session_id==null?void 0:e.get_session_id();n&&this.Xs(n)}Gs(){this.ta()}Ss(e){var n,i=(n=this._instance)==null||(n=n.persistence)==null?void 0:n.props[this.Ys()];if(i&&i!==e){var r=this.Zs(),s=this.Qs();r.length>0&&(this.Ws([]),r.filter((o=>ke(s[o]))).forEach((o=>this.Bs(o)))),this.Gs(),this.Ks()}}getActivatedIds(){return[...new Set([...this.zs(),...this._s])].filter((e=>!this.ea(e)))}reset(){this._s=[],this.Zs().length>0&&this.Ws([]),this.Gs(),this.Ks()}getEventToItemsMap(){return this.ws}ia(){return this.Os}}class Om extends Nm{constructor(e){super(e)}Js(){return ca}Ys(){return Fr}Ms(){return Rr}Ts(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Rr]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Rr)}Cs(e){var n,i;this.As((s=>{i=s.find((o=>o.id===e))}));var r=(n=i)==null||(n=n.appearance)==null?void 0:n.surveyPopupDelaySeconds;return ke(r)&&r>0}ra(){return zt.SHOWN}As(e){var n;(n=this._instance)==null||n.getSurveys(e)}Bs(e){var n;(n=this._instance)==null||n.cancelPendingSurvey(e)}Ds(){return Q}Ws(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[ca]:e})}Xs(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Fr]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Fr)}ea(){return!1}$s(e,n){var i;this.As((s=>{i=s.find((o=>o.id===n))}));var r=!i||(function(s){var o;return Hf(s)&&!((o=s.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||s.schedule==="always"})(i);return r?e===zt.SHOWN?"consume":"ignore":e===zt.SHOWN?"persist":e===zt.DISMISSED||e===zt.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var Ir="SDK is not enabled or survey functionality is not yet loaded",du="Disabled. Not loading surveys.",Bm=w!=null&&w.location?os(w.location.hash,"__posthog")||os(location.hash,"state"):null,fu="_postHogToolbarParams",hu=pe("[Toolbar]"),pu=pe("[FeatureFlags]");class Dm{constructor(e,n){n===void 0&&(n=!1),this.na=!1,this.update(e,n)}update(e,n){this.sa=((i,r)=>{var s,o,a,l;return{bootstrap:{featureFlags:(s=i.bootstrap)==null?void 0:s.featureFlags,featureFlagPayloads:(o=i.bootstrap)==null?void 0:o.featureFlagPayloads},remoteRequestsDisabled:r,featureFlagsDisabled:!!i.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!i.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!i.advanced_feature_flags_dedup_per_session,cacheTtlMs:i.feature_flag_cache_ttl_ms,requestTimeoutMs:i.feature_flag_request_timeout_ms,compression:i.disable_compression?"none":"base64",evaluationContexts:(a=(l=i.evaluation_contexts)!==null&&l!==void 0?l:i.evaluation_environments)!==null&&a!==void 0?a:[],flagKeys:U(i.flag_keys)?i.flag_keys:void 0}})(e,n),!e.evaluation_environments||e.evaluation_contexts||this.na||(pu.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.na=!0),C(e.flag_keys)||U(e.flag_keys)||pu.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var gu=pe("[FeatureFlags]"),bn=pe("[FeatureFlags]",{debugEnabled:!0}),Bo=`" failed. Feature flags didn't load in time.`,mu="connection_error",vu=t=>{for(var e={},n=0;t.length>n;n++)e[t[n]]=!0;return e},_u=t=>{var e={};for(var n of $r(t||{})){var i=n[1];i&&(e[n[0]]=i)}return e},St=pe("[Error tracking]"),yu="Refusing to render web experiment since the viewer is a likely bot",jm={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>cs(e,t),not_regex:(t,e)=>!cs(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class Me{get Ne(){return this._instance.config}constructor(e){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(i){i===void 0&&(i=!1),n.getWebExperiments((r=>{Me.aa("retrieved web experiments from the server"),n.oa=new Map,r.forEach((s=>{if(s.feature_flag_key){var o;n.oa&&(Me.aa("setting flag key ",s.feature_flag_key," to web experiment ",s),(o=n.oa)==null||o.set(s.feature_flag_key,s));var a=n._instance.getFeatureFlag(s.feature_flag_key);X(a)&&s.variants[a]&&n.la(s.name,a,s.variants[a].transforms)}else if(s.variants)for(var l in s.variants){var u=s.variants[l];Me.ua(u,n._instance)&&n.la(s.name,l,u.transforms)}}))}),i)},this._instance=e,this._instance.onFeatureFlags((i=>{this.onFeatureFlags(i)}))}initialize(){}onFeatureFlags(e){if(this._is_bot())Me.aa(yu);else if(!this.Ne.disable_web_experiments){if(H(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();Me.aa("applying feature flags",e),e.forEach((n=>{var i;if(this.oa&&(i=this.oa)!=null&&i.has(n)){var r,s=this._instance.getFeatureFlag(n),o=(r=this.oa)==null?void 0:r.get(n);s&&o!=null&&o.variants[s]&&this.la(o.name,s,o.variants[s].transforms)}}))}}previewWebExperiment(){var e=Me.getWindowLocation();if(e!=null&&e.search){var n=ii(e?.search,"__experiment_id"),i=ii(e?.search,"__experiment_variant");n&&i&&(Me.aa("previewing web experiments "+n+" && "+i),this.getWebExperiments((r=>{this.ha(parseInt(n),i,r)}),!1,!0))}}loadIfEnabled(){this.Ne.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,n,i){if(this.Ne.disable_web_experiments&&!i)return e([]);var r=this._instance.get_property("$web_experiments");if(r&&!n)return e(r);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this.Ne.token),method:"GET",timestampMode:"query",callback:s=>e(s.statusCode===200&&s.json&&s.json.experiments||[])})}ha(e,n,i){var r=i.filter((s=>s.id===e));r&&r.length>0&&(Me.aa("Previewing web experiment ["+r[0].name+"] with variant ["+n+"]"),this.la(r[0].name,n,r[0].variants[n].transforms))}static ua(e,n){return!H(e.conditions)&&Me.da(e,n)&&Me.va(e)}static da(e,n){var i;if(H(e.conditions)||H((i=e.conditions)==null?void 0:i.url))return!0;var r=Me.getWindowLocation();if(r){var s,o,a,l=rf(n,r.href);return(s=e.conditions)==null||!s.url||jm[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return w?.location}static va(e){var n;if(H(e.conditions)||H((n=e.conditions)==null?void 0:n.utm))return!0;var i=yf();if(i.utm_source){var r,s,o,a,l,u,c,d,f=(r=e.conditions)==null||(r=r.utm)==null||!r.utm_campaign||((s=e.conditions)==null||(s=s.utm)==null?void 0:s.utm_campaign)==i.utm_campaign,h=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==i.utm_source,p=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==i.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==i.utm_term;return f&&p&&g&&h}return!1}static aa(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;n>r;r++)i[r-1]=arguments[r];A.info("[WebExperiments] "+e,i)}la(e,n,i){this._is_bot()?Me.aa(yu):n!=="control"?i.forEach((r=>{if(r.selector){var s;Me.aa("applying transform of variant "+n+" for experiment "+e+" ",r);var o=(s=document)==null?void 0:s.querySelectorAll(r.selector);o?.forEach((a=>{var l=a;r.html&&(l.innerHTML=r.html),r.css&&l.setAttribute("style",r.css)}))}})):Me.aa("Control variants leave the page unmodified.")}_is_bot(){return Ue&&this._instance?Bf(Ue,this.Ne.custom_blocked_useragents):void 0}}var st=pe("[Conversations]"),En="Conversations not available yet.",wu="console",Gf="__posthogHandledLogsRequestError",Do=(t,e)=>{var n=t instanceof Error?t:new Error(e);return n[Gf]=!0,n},bu=t=>!!t&&typeof t=="object"&&t[Gf]===!0,Cs={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=gu,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 Dm(t.config,t.Qi()),this.Ta=this.Ea)}updateConfig(t,e){var n;(n=this.Ea)==null||n.update(t,e)}setup(t){return this.Ia=t,this.rt=t.logger.createLogger("[FeatureFlags]"),n=()=>{this.Ia===t&&(this.Ia=void 0,this.nn=t,this.Pa(t))},(e=t.kv.initialize())!=null&&e.then?e.then(n):n();var e,n}Pa(t){if(this.nn===t)return w&&ve(w,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){w?.removeEventListener("online",this.Ca)}dispose(){var t;this.ba++,this.wa=!1,this.Ia=void 0,this.nn&&(this.La(),(t=this.Ra)==null||t.dispose(),this.Ra=void 0,this.ga=[],w?.removeEventListener("online",this.Ca),this.nn=void 0)}get Ne(){return this.Ta.get()}Oa(t){var e;return(e=this.nn)==null?void 0:e.kv.get(t)}F(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.set(t)}))}q(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.remove(t)}))}Da(t){try{t()}catch(e){this.rt.error("Failed to update feature flag persistence",e)}}Fa(){var t={};for(var e of[Ti,$i,Pr,It]){var n=this.Oa(e);C(n)||(t[e]=n)}this.fa=t;var i=k({},t),r=this.Oa(Sn);if(r)for(var s of Object.entries(r))i["$feature/"+s[0]]=s[1];this.pa=i}Aa(){var t=this.Ne.cacheTtlMs;if(!t||0>=t)return!1;var e=this.Oa(ji);return typeof e!="number"||Date.now()-e>t}$a(){return!!this.Aa()&&(this.xa||this.ya||(this.xa=!0,this.rt.warn("Feature flag cache is stale, triggering refresh..."),this.reloadFeatureFlags()),!0)}Na(){var t=this.Ne.evaluationContexts;return t!=null&&t.length?t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid evaluation context found:",e,"Expected non-empty string"),n})):[]}qa(){var t=this.Ne.flagKeys;if(!C(t))return t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid flag key found:",e,"Expected non-empty string"),n}))}initialize(){var t,e,n=this.Ne,i=(t=(e=n.bootstrap)==null?void 0:e.featureFlags)!==null&&t!==void 0?t:{};if(Object.keys(i).length){var r,s,o=(r=(s=n.bootstrap)==null?void 0:s.featureFlagPayloads)!==null&&r!==void 0?r:{},a=Object.keys(i).filter((u=>!!i[u])).reduce(((u,c)=>(u[c]=i[c]||!1,u)),{}),l=Object.keys(o).filter((u=>a[u])).reduce(((u,c)=>(o[c]&&(u[c]=o[c]),u)),{});return this.ja({featureFlags:a,featureFlagPayloads:l})}}updateFlags(t,e,n){var i,r,s=n!=null&&n.merge&&(i=this.Oa(Sn))!==null&&i!==void 0?i:{},o=n!=null&&n.merge&&(r=this.Oa($i))!==null&&r!==void 0?r:{},a=k({},s,t),l=k({},o,e),u={};for(var c of Object.entries(a)){var d=c[0],f=c[1];u[d]={key:d,enabled:hc(f),variant:pc(f),reason:void 0,metadata:C(l?.[d])?void 0:{id:0,version:void 0,description:void 0,payload:l[d]}}}this.ja({flags:u})}get hasLoadedFlags(){return this.ma}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var t=this.Oa(aa),e=this.Oa(It),n=this.Oa(xn);if(!n&&!e)return t||{};var i=fe({},t||{}),r=[...new Set([...Object.keys(n||{}),...Object.keys(e||{})])];for(var s of r){var o,a,l=i[s],u=e?.[s],c=C(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=C(u)?l?.variant:typeof u=="string"?u:void 0,f=n?.[s],h=k({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(h.original_enabled=l?.enabled),d!==l?.variant&&(h.original_variant=l?.variant),f&&(h.metadata=k({},l?.metadata,{payload:f,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),i[s]=h}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:n,finalDetails:i}),this.ca=!0),i}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((n=>{var i=t[n];return{key:n,enabled:hc(i),variant:pc(i),payload:fc(e[n])}}))}getFlagVariants(){var t=this.Oa(Sn),e=this.Oa(It);if(!e)return t||{};for(var n=fe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:e,finalFlags:n}),this.ca=!0),n}getFlagPayloads(){var t=this.Oa($i),e=this.Oa(xn);if(!e)return t||{};for(var n=fe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flag payloads!",{flagPayloads:t,overriddenPayloads:e,finalPayloads:n}),this.ca=!0),n}reloadFeatureFlags(){this._a||this.Ne.featureFlagsDisabled||this.Ma()||this.Ba||(this.ga.slice().forEach((t=>{try{t()}catch(e){this.rt.error("Error while running feature flags reloading callback",e)}})),this.Ba=setTimeout((()=>{this.Ha()}),5))}La(){clearTimeout(this.Ba),this.Ba=void 0}onReloading(t){return this.ga.push(t),()=>{this.ga=this.ga.filter((e=>e!==t))}}ensureFlagsLoaded(){this.ma||this.ya||this.Ba||this.reloadFeatureFlags()}setAnonymousDistinctId(t){this.$anon_distinct_id=t}setReloadingPaused(t){this._a=t}resetFlagCallReported(){this.q(Cn)}Ha(t){this.La();var e=this.nn;if(e&&!this.Ne.remoteRequestsDisabled&&!this.Ma())if(this.ya)this.wa=!0;else{var n={token:e.projectToken,distinct_id:e.distinctId,groups:e.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:k({},e.initialPersonProperties,this.Oa(jt)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(In),timezone:If()};C(e.deviceId)||(n.$device_id=e.deviceId),(t!=null&&t.disableFlags||this.Ne.featureFlagsDisabled)&&(n.disable_flags=!0);var i=this.Na();i.length&&(n.evaluation_contexts=i);var r=this.qa();C(r)||(n.flag_keys=r);var s=this.Ne.onlyEvaluateSurveyFeatureFlags,o="/flags/?v=2"+(s?"&only_evaluate_survey_feature_flags=true":""),a=this.ba;this.ya=!0;var l=()=>{this.wa&&(this.wa=!1,this.Ha())},u=c=>{this.ya=!1,a===this.ba&&(this.F({[Tr]:[mu]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:n,compression:this.Ne.compression==="base64"?je.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,f,h=(d=c.json)!==null&&d!==void 0?d:{},p=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),p||this.wa||(this.$anon_distinct_id=void 0),!n.disable_flags||this.wa){this.ka=!p;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?mu:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),h.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((f=h.quotaLimited)==null||!f.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[Tr]:g}),m?this.rt.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more."):n.disable_flags||this.ja(h,p,{partialResponse:s}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return vf(this.Sa,3)}Ua(t){this.Sa=_f(t,this.Sa,3,(()=>this.rt.warn("Feature flag requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped refreshing feature flags; will try again when connectivity changes.")))}getFeatureFlag(t,e){var n;if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var i=this.getFeatureFlagResult(t,e);return(n=i?.variant)!==null&&n!==void 0?n:i?.enabled}}else this.rt.warn('getFeatureFlag for key "'+t+Bo)}getFeatureFlagDetails(t){return this.getFlagsWithDetails()[t]}getFeatureFlagPayload(t){var e=this.getFeatureFlagResult(t,{send_event:!1});return e?.payload}getFeatureFlagResult(t,e){if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var n,i=this.getFlagVariants(),r=t in i,s=i[t],o=this.getFlagPayloads()[t],a=String(s),l=this.Oa(Pr)||void 0,u=this.Oa(ji)||void 0,c=this.Oa(Cn)||{};if(this.Ne.deduplicateCallsPerSession){var d,f=(d=this.nn)==null?void 0:d.session.sessionId,h=this.Oa(Li);f&&f!==h&&(c={},n=f)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))n&&this.F({[Cn]:c,[Li]:n});else{var p,g,m,v,S,b,_,x,I,T;U(c[t])?c[t].push(a):c[t]=[a],this.F(k({[Cn]:c},n?{[Li]:n}:{}));var E=this.getFeatureFlagDetails(t),P=[...(p=this.Oa(Tr))!==null&&p!==void 0?p:[]];C(s)&&P.push("flag_missing");var $={$feature_flag:t,$feature_flag_response:s,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((g=this.Ne.bootstrap)==null||(g=g.featureFlags)==null?void 0:g[t])||null,$feature_flag_bootstrapped_payload:((m=this.Ne.bootstrap)==null||(m=m.featureFlagPayloads)==null?void 0:m[t])||null,$used_bootstrap_value:!this.ka};C(E==null||(v=E.metadata)==null?void 0:v.has_experiment)||($.$feature_flag_has_experiment=E.metadata.has_experiment),C(E==null||(S=E.metadata)==null?void 0:S.version)||($.$feature_flag_version=E.metadata.version);var O,L=(b=E==null||(_=E.reason)==null?void 0:_.description)!==null&&b!==void 0?b:E==null||(x=E.reason)==null?void 0:x.code;L&&($.$feature_flag_reason=L),E!=null&&(I=E.metadata)!=null&&I.id&&($.$feature_flag_id=E.metadata.id),C(E?.original_variant)&&C(E?.original_enabled)||($.$feature_flag_original_response=C(E.original_variant)?E.original_enabled:E.original_variant),E!=null&&(T=E.metadata)!=null&&T.original_payload&&($.$feature_flag_original_payload=E==null||(O=E.metadata)==null?void 0:O.original_payload),P.length&&($.$feature_flag_error=P.join(",")),this.za($)}else n&&this.F({[Cn]:c,[Li]:n});if(r)return{key:t,enabled:!!s,variant:typeof s=="string"?s:void 0,payload:fc(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+Bo)}za(t){try{var e;(e=this.nn)==null||e.capture("$feature_flag_called",t).catch((n=>{this.rt.error("Failed to capture feature flag call",n)}))}catch(n){this.rt.error("Failed to capture feature flag call",n)}}getRemoteConfigPayload(t,e){this.Wa(t,e)}Wa(t,e){var n=this;return se((function*(){var i=n.nn;if(i){var r={distinct_id:i.distinctId,token:i.projectToken,person_properties:{$lib:i.library.name,$lib_version:i.library.version}},s=n.Na();s.length&&(r.evaluation_contexts=s);var o,a=n.qa();C(a)||(r.flag_keys=a);try{var l,u=(l=(yield i.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:r,compression:n.Ne.compression==="base64"?je.Base64:void 0,sentAt:"body",timeoutMs:n.Ne.requestTimeoutMs})).json)==null?void 0:l.featureFlagPayloads;o=u?.[t]||void 0}catch(c){return void n.rt.error("Remote config feature flag request failed",c)}try{e(o)}catch(c){n.rt.error("Remote config feature flag callback failed",c)}}}))()}isFeatureEnabled(t,e){if(e===void 0&&(e={}),e.fresh&&!this.ka)return e.defaultValue;if(!(this.ma||this.getFlags()&&this.getFlags().length>0))return this.rt.warn('isFeatureEnabled for key "'+t+Bo),e.defaultValue;var n=this.getFeatureFlag(t,e);return C(n)?e.defaultValue:!!n}addFeatureFlagsHandler(t){this.featureFlagEventHandlers.push(t)}removeFeatureFlagsHandler(t){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((e=>e!==t))}receivedFeatureFlags(t,e,n){this.ja(t,e,n)}ja(t,e,n){if(this.nn){this.ma=!0;var i=(function(r,s,o,a,l,u){s===void 0&&(s={}),o===void 0&&(o={}),a===void 0&&(a={}),u===void 0&&(u=gu);var c=((I,T)=>{var E=I.flags;return E?k({},I,{featureFlags:Object.fromEntries(Object.keys(E).map((P=>{var $;return[P,($=E[P].variant)!==null&&$!==void 0?$:E[P].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(E).filter((P=>E[P].enabled)).filter((P=>{var $;return($=E[P].metadata)==null?void 0:$.payload})).map((P=>{var $;return[P,($=E[P].metadata)==null?void 0:$.payload]})))}):(I.featureFlags&&T.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),I)})(r,u),d=c.flags,f=c.featureFlags,h=c.featureFlagPayloads;if(f){var p=r.requestId,g=r.evaluatedAt;if(U(f)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(f)for(var v=0;f.length>v;v++)m[f[v]]=!0;return{[Ti]:f,[Sn]:m,[Zr]:!1}}var S=f,b=h,_=d;if(l!=null&&l.partialResponse)S=k({},s,S),b=k({},o,b),_=k({},a,_);else if(r.errorsWhileComputingFlags)if(d){var x=new Set(Object.keys(d).filter((I=>{var T;return!((T=d[I])!=null&&T.failed)})));S=k({},s,Object.fromEntries(Object.entries(S).filter((I=>x.has(I[0]))))),b=k({},o,Object.fromEntries(Object.entries(b||{}).filter((I=>x.has(I[0]))))),_=k({},a,Object.fromEntries(Object.entries(_||{}).filter((I=>x.has(I[0])))))}else S=k({},s,S),b=k({},o,b),_=k({},a,_);return k({[Ti]:Object.keys(_u(S)),[Sn]:S||{},[$i]:b||{},[aa]:_||{},[Zr]:r.minimalFlagCalledEvents===!0},p?{[Pr]:p}:{},g?{[ji]:g}:{})}})(t,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),n,this.rt);i&&this.F(i),e||(this.xa=!1),this.Va(e)}}override(t,e){e===void 0&&(e=!1),this.rt.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:t,suppressWarning:e})}overrideFeatureFlags(t){this.Za(t)}Za(t){if(this.nn){if(t===!1)return this.q([It,xn]),this.Va(),void bn.info("All overrides cleared");if(U(t))return this.F({[It]:vu(t)}),this.Va(),void bn.info("Flag overrides set",{flags:t});if(t&&typeof t=="object"&&("flags"in t||"payloads"in t)){var e,n=t;this.ca=!!((e=n.suppressWarning)!==null&&e!==void 0&&e);var i={},r=n.flags,s=n.payloads;return r&&(i[It]=U(r)?vu(r):r),s&&(i[xn]=s),Object.keys(i).length&&this.F(i),r===!1&&s===!1?this.q([It,xn]):r===!1?this.q(It):s===!1&&this.q(xn),this.Va(),r===!1?bn.info("Flag overrides cleared"):r&&bn.info("Flag overrides set",{flags:r}),void(s===!1?bn.info("Payload overrides cleared"):s&&bn.info("Payload overrides set",{payloads:s}))}if(t&&typeof t=="object")return this.F({[It]:t}),this.Va(),void bn.info("Flag overrides set",{flags:t});this.rt.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:t})}else this.rt.warn("posthog.featureFlags.overrideFeatureFlags called before feature flags were ready")}onFeatureFlags(t){if(this.addFeatureFlagsHandler(t),this.ma){var e=this.Ga(),n=e.flags,i=e.flagVariants;try{t(n,i)}catch(r){this.rt.error("Error while running feature flags callback",r)}}return()=>this.removeFeatureFlagsHandler(t)}updateEarlyAccessFeatureEnrollment(t,e,n){var i=(this.Oa(Ar)||[]).find((l=>l.flagKey===t)),r={["$feature_enrollment/"+t]:e},s={$feature_flag:t,$feature_enrollment:e,$set:r};i&&(s.$early_access_feature_name=i.name),n&&(s.$feature_enrollment_stage=n);var o=k({},this.getFlagVariants(),{[t]:e});this.F({[Ti]:Object.keys(_u(o)),[Sn]:o,[jt]:k({},this.Oa(jt)||{},r)}),this.Va();try{var a;(a=this.nn)==null||a.capture("$feature_enrollment_update",s).catch((l=>{this.rt.error("Failed to capture early access feature enrollment",l)}))}catch(l){this.rt.error("Failed to capture early access feature enrollment",l)}}getEarlyAccessFeatures(t,e,n){e===void 0&&(e=!1);var i=this.Oa(Ar);!i||e?this.Qa(t,n):t(i)}Qa(t,e){var n=this;return se((function*(){var i=n.nn;if(i){var r,s=e?"&"+e.map((a=>"stage="+a)).join("&"):"";try{var o=yield i.sendRequest("/api/early_access_features/?token="+i.projectToken+s,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;n.F({[Ar]:r=o.json.earlyAccessFeatures})}catch(a){return void n.rt.error("Early access feature request failed",a)}try{t(r)}catch(a){n.rt.error("Early access feature callback failed",a)}}}))()}Ga(){var t=this.getFlags(),e=this.getFlagVariants();return{flags:t.filter((n=>e[n])),flagVariants:Object.keys(e).filter((n=>e[n])).reduce(((n,i)=>(n[i]=e[i],n)),{})}}Va(t){this.Fa();var e=this.Ga(),n=e.flags,i=e.flagVariants;this.featureFlagEventHandlers.forEach((r=>{try{r(n,i,{errorsLoading:t})}catch(s){this.rt.error("Error while running feature flags callback",s)}}))}setPersonPropertiesForFlags(t,e){e===void 0&&(e=!0),this.Ka(t,e)}Ka(t,e){e===void 0&&(e=!0);var n=this.Oa(jt)||{},i=t?.$set||(t!=null&&t.$set_once?{}:t),r=t?.$set_once,s={};if(r)for(var o in r)({}).hasOwnProperty.call(r,o)&&(o in n||(s[o]=r[o]));this.F({[jt]:k({},n,s,i)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=k({},this.Oa(jt)||{});t.forEach((i=>{delete n[i]})),this.F({[jt]:n}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(jt),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=this.Oa(In)||{},i=k({},n);for(var r of Object.keys(t))i[r]=k({},n[r],t[r]);this.F({[In]:i}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(In)||{};this.F({[In]:k({},e,{[t]:{}})})}else this.q(In)}reset(){this.ba++,this.wa=!1,this.Fa(),this.ma=!1,this._a=!1,this.ka=!1,this.$anon_distinct_id=void 0,this.La(),this.ca=!1,this.Sa=0}}},Um={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===ki||this.Ya===Sr?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=lu,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(F==null||!F.visibilityState||F.visibilityState==="visible")return!0;var n=w==null||(e=w.performance)==null||e.getEntriesByType==null?void 0:e.getEntriesByType("visibility-state");return!(n!=null&&n.length)||n.some((i=>i.name==="visible"))})(),this.Ie=()=>{var e;F?.visibilityState==="visible"&&(this.io=!0,(e=this.Ja)==null||e.setDocumentWasEverVisible==null||e.setDocumentWasEverVisible(!0))},this._instance=t,!this._instance.sessionManager)throw Bt.error("started without valid sessionManager"),new Error(Ia+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===Wt)throw new Error(Ia+' cannot be used with cookieless_mode="always"');F!=null&&F.addEventListener&&ve(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(An))==null||!t.enabled),n=!this.Ne.disable_session_recording,i=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return w&&e&&n&&!i}startIfEnabledOrStop(t){var e;if(!(this.eo||this.ro&&(e=this.Ja)!=null&&e.isStarted)){var n=!C(Object.assign)&&!C(Array.from);this.ro&&n?(this.no(t),Bt.info("starting")):(this.Ya=lu,this.stopRecording())}}no(t){var e,n,i;this.ro&&(this.Ya!==ki&&this.Ya!==Sr&&(this.Ya=cu),B!=null&&(e=B.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(n=B.__PosthogExtensions__)!=null&&n.initSessionRecording?this.so(t):(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,this.ao,(r=>{if(r)return Bt.error("could not load recorder",r);this.so(t)})))}stopRecording(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.stop()}oo(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.discard()}lo(){var t,e;(t=this.Mr)==null||t.unregister(ol),(e=this.Mr)==null||e.unregister(Vd)}uo(t,e){if(H(t))return null;var n,i=ke(t)?t:parseFloat(t);return typeof(n=i)!="number"||!Number.isFinite(n)||0>n||n>1?(Bt.warn(e+" must be between 0 and 1. Ignoring invalid value:",t),null):i}ho(t){if(this.Mr){var e,n,i=this.Mr,r=()=>{var s,o=t.sessionRecording===!1?void 0:t.sessionRecording,a=this.uo((s=this.Ne.session_recording)==null?void 0:s.sampleRate,"session_recording.sampleRate"),l=this.uo(o?.sampleRate,"remote config sampleRate"),u=a??l;H(u)&&this.lo();var c=o?.minimumDurationMilliseconds;i.register({[An]:k({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:k({capturePerformance:t.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:u,minimumDurationMilliseconds:C(c)?null:c,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers,version:o?.version,triggerGroups:o?.triggerGroups})})};r(),(e=this.Xa)==null||e.call(this),this.Xa=(n=this._instance.sessionManager)==null?void 0:n.onSessionId(r)}}onRemoteConfig(t){var e=t.ok?t.config:void 0;return e&&"sessionRecording"in e?e.sessionRecording===!1?(this.ho(e),void this.oo()):(this.ho(e),void this.startIfEnabledOrStop()):(this.Ya===ki&&(this.Ya=Sr,Bt.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(t,e){var n;e===void 0&&(e="log"),(n=this.Ja)!=null&&n.log?this.Ja.log(t,e):Bt.warn("log called before recorder was ready")}get ao(){var t,e,n=(t=this._instance)==null||(t=t.persistence)==null?void 0:t.get_property(An);return(n==null||(e=n.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(An);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(n){return Bt.warn("persisted remote config for session recording is invalid and will be ignored",n),!1}return!H(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,n,i;if(!this.eo){if((e=B.__PosthogExtensions__)==null||!e.initSessionRecording)return Bt.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[ef]:!0});var r;if(this.Ja||(this.Ja=(r=B.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===Sr||this.Ya===ki?void 0:(this.Ya=ki,Bt.info("persisted remote config is stale, requesting fresh config before starting"),void new kf(this._instance).load());this.Ya=cu,(n=(i=this.Ja).setDocumentWasEverVisible)==null||n.call(i,this.io),this.Ja.start(t)}}onRRwebEmit(t){var e;(e=this.Ja)==null||e.onRRwebEmit==null||e.onRRwebEmit(t)}overrideLinkedFlag(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Kd]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Gd]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,n;this.Ja||(n=this.Mr)==null||n.register({[t==="url"?Yd:Jd]:!0}),(e=this.Ja)==null||e.overrideTrigger(t)}get sdkDebugProperties(){var t;return((t=this.Ja)==null?void 0:t.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(t,e){var n;return!((n=this.Ja)==null||!n.tryAddCustomEvent(t,e))}}},Hm={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new su(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,n=he(this.instance.config.autocapture)?this.instance.config.autocapture:{};return n.url_allowlist=(t=n.url_allowlist)==null?void 0:t.map((i=>new RegExp(i))),n.url_ignorelist=(e=n.url_ignorelist)==null?void 0:e.map((i=>new RegExp(i))),n}yo(){if(this.isBrowserSupported()){if(w&&F){var t=n=>{n=n||w?.event;try{this.bo(n)}catch(i){Mo.error("Failed to capture event",i)}};if(ve(F,"submit",t,{capture:!0}),ve(F,"change",t,{capture:!0}),ve(F,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=n=>{n=n||w?.event;try{this.bo(n,$o)}catch(i){Mo.error("Failed to capture copy/cut event",i)}};ve(F,"copy",e,{capture:!0}),ve(F,"cut",e,{capture:!0})}}}else Mo.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.vo&&(this.yo(),this.vo=!0)}onRemoteConfig(t){if(this.fo=!0,t.ok){var e=t.config;e.elementsChainAsString&&(this.po=e.elementsChainAsString);var n=e.autocapture_opt_out;gt(n)&&(this.instance.persistence&&this.instance.persistence.register({[ea]:n}),this.co=n),this.startIfEnabled()}else this.startIfEnabled()}setElementSelectors(t){this.mo=t}getElementSelectors(t){var e,n=[];return(e=this.mo)==null||e.forEach((i=>{var r=F?.querySelectorAll(i);r?.forEach((s=>{t===s&&n.push(i)}))})),n}get isEnabled(){var t,e,n=(t=this.instance.persistence)==null?void 0:t.props[ea],i=this.co,r=this.instance.Qi()&&!this.fo;if(Ke(i)&&!gt(n)&&!r)return!1;var s=(e=this.co)!==null&&e!==void 0?e:!!n;return!!this.instance.config.autocapture&&!s}bo(t,e){if(e===void 0&&(e="$autocapture"),this.isEnabled){var n,i=bo(t);of(i)&&(i=i.parentNode||null),e==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&this.instance.config.rageclick&&(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,t.timeStamp||new Date().getTime())&&Lc(i,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var r=e===$o;if(i&&(function(d,f,h,p,g,m){var v;if(!w||dl(d)||h!=null&&h.url_allowlist&&!Tc(h.url_allowlist,m)||h!=null&&h.url_ignorelist&&Tc(h.url_ignorelist,m))return!1;if(h!=null&&h.dom_event_allowlist){var S=h.dom_event_allowlist;if(S&&!S.some((E=>f.type===E)))return!1}var b=ff(d,p),_=b.parentIsUsefulElement,x=b.targetElementList;if(!(function(E,P){var $=P?.element_allowlist;if(C($))return!0;var O,L=function(K){if($.some((V=>K.tagName.toLowerCase()===V)))return{v:!0}};for(var N of E)if(O=L(N))return O.v;return!1})(x,h)||!ma(x,h?.css_selector_allowlist)||ma(x,(v=h?.css_selector_ignorelist)!==null&&v!==void 0?v:Dg))return!1;try{var I=w.getComputedStyle(d);if(I&&I.getPropertyValue("cursor")==="pointer"&&f.type==="click")return!0}catch{}var T=d.tagName.toLowerCase();switch(T){case"html":return!1;case"form":return(g||["submit"]).indexOf(f.type)>=0;case"input":case"select":case"textarea":return(g||["change","click"]).indexOf(f.type)>=0;default:return _?(g||["click"]).indexOf(f.type)>=0:(g||["click"]).indexOf(f.type)>=0&&(ul.indexOf(T)>-1||d.getAttribute("contenteditable")==="true")}})(i,t,this.Ne,r,r?["copy","cut"]:void 0,this.instance)){var s=Rm(i,{e:t,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.Ne.element_attribute_ignorelist,elementsChainAsString:this.po,disableCaptureUrlHashes:this.instance.config.disable_capture_url_hashes}),o=s.props;if(s.explicitNoCapture)return!1;var a=this.getElementSelectors(i);if(a&&a.length>0&&(o.$element_selectors=a),e===$o){var l,u=cf(w==null||(l=w.getSelection())==null?void 0:l.toString()),c=t.type||"clipboard";if(!u)return!1;o.$selected_content=u,o.$copy_type=c}return this.instance.capture(e,o),!0}}}isBrowserSupported(){return De(F?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(w==null||(e=w.location)==null?void 0:e.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(A.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.wo&&this.wo(),this.wo=void 0,A.info("History API monitoring stopped")}monitorHistoryChanges(){w&&w.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(w&&((e=w.history[t])==null||!e.__posthog_wrapped__)){var n=this;(function(i,r,s){try{if(!(r in i))return ou;var o={next:i[r]},a=s((function(){for(var l=arguments.length,u=new Array(l),c=0;l>c;c++)u[c]=arguments[c];return o.next.apply(this,u)}));return De(a)&&(a.prototype=a.prototype||{},Object.defineProperties(a,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:o}})),i[r]=a,()=>{if(i[r]!==a)for(var l=i[r];De(l)&&l.__posthog_layer__;){var u=l.__posthog_layer__;if(u.next===a)return void(u.next=o.next);l=u.next}else i[r]=o.next}}catch{return ou}})(w.history,t,(i=>function(r,s,o){i.call(this,r,s,o),n.So(t)}))}}So(t){try{var e,n=w==null||(e=w.location)==null?void 0:e.pathname;if(!n)return;n!==this._o&&this.isEnabled&&this._instance.capture(Vn,{navigation_type:t}),this._o=n}catch(i){A.error("Error capturing "+t+" pageview",i)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};ve(w,"popstate",t),this.wo=()=>{w&&w.removeEventListener("popstate",t)}}}},heatmaps:class{get Ne(){return this.instance.config}constructor(t){var e;this.Co=!1,this.vo=!1,this.Mo=null,this.instance=t,this.Co=!((e=this.instance.persistence)==null||!e.props[ta]),this.rageclicks=new su(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return he(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return H(this.Ne.capture_heatmaps)?H(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;$m.info("starting..."),this.To(),this.Ie()}else{var t;clearInterval((t=this.Mo)!==null&&t!==void 0?t:void 0),this.Eo(),this.getAndClearBuffer()}}onRemoteConfig(t){if(t.ok){var e=t.config;if("heatmaps"in e){var n=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[ta]:n}),this.Co=n,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){No(t.originalEvent)&&this.ke(t.originalEvent,"deadclick")}Ie(){this.Mo&&clearInterval(this.Mo),this.Mo=F?.visibilityState==="visible"?setInterval(this.cr.bind(this),this.flushIntervalMilliseconds):null}To(){w&&F&&(this.Po=this.cr.bind(this),ve(w,ns,this.Po),this.Ro=t=>this.ke(t||w?.event),ve(F,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||w?.event),ve(F,"mousemove",this.Ao,{capture:!0}),this.Lo=new Hc(this.instance,Vg,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),ve(F,ts,this.Oo),this.vo=!0)}Eo(){var t;w&&F&&(this.Po&&w.removeEventListener(ns,this.Po),this.Ro&&F.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&F.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&F.removeEventListener(ts,this.Oo),clearTimeout(this.Do),(t=this.Lo)==null||t.stop(),this.vo=!1)}$o(t,e){var n=this.instance.scrollManager.scrollY(),i=this.instance.scrollManager.scrollX(),r=this.instance.scrollManager.scrollElement(),s=(function(o,a,l){for(var u=o;u&&hn(u)&&!Qe(u,"body");){if(u===l)return!1;var c=void 0;try{var d,f,h;c=(d=(f=(h=u.ownerDocument)==null?void 0:h.defaultView)!==null&&f!==void 0?f:w)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(j(a,c))return!0;u=uf(u)}return!1})(bo(t),["fixed","sticky"],r);return{x:t.clientX+(s?0:i),y:t.clientY+(s?0:n),target_fixed:s,type:e}}ke(t,e){var n;if(e===void 0&&(e="click"),!Rc(t.target)&&No(t)){var i=this.$o(t,e);(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,new Date().getTime())&&Lc(bo(t),this.instance.config.rageclick)&&this.Vt(k({},i,{type:"rageclick"})),this.Vt(i)}}Fo(t){!Rc(t.target)&&No(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(w){var e=this.Ne.disable_capture_url_hashes?fn(w.location.href):w.location.href,n=this.Ne.custom_personal_data_properties,i=this.Ne.mask_personal_data_properties?[...ri,...n||[]]:[],r=Zi(e,i,Xi);this.R=this.R||{},this.R[r]||(this.R[r]=[]),this.R[r].push(t)}}cr(){this.R&&!Kt(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:Hc,webVitalsAutocapture:class{constructor(t){var e;this.Co=!1,this.vo=!1,this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this.No=()=>{clearTimeout(this.qo),this.qo=void 0,this.R.metrics.length!==0&&(this._instance.capture("$web_vitals",k({$current_url:this.R.url},this.R.metrics.reduce(((n,i)=>k({},n,{["$web_vitals_"+i.name+"_event"]:k({},i),["$web_vitals_"+i.name+"_value"]:i.value})),{}))),this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.jo=n=>{var i;if(this.R=this.R||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},H(n?.name)||H(n?.value))wn.error("Invalid metric received",n);else{var r=typeof n.navigationURL=="string"?n.navigationURL:void 0,s=this.Bo(r);if(!C(s)){var o=ke(n.navigationId)||typeof n.navigationId=="string"?"navigation:"+n.navigationId:"url:"+s;if(!this.Ho||this.Ho>n.value){this.R.navigationKey!==o&&(this.No(),this.qo=setTimeout(this.No,this.flushToCaptureTimeoutMs)),C(this.R.navigationKey)&&(this.R.navigationKey=o,this.R.url=s),this.R.firstMetricTimestamp=C(this.R.firstMetricTimestamp)?Date.now():this.R.firstMetricTimestamp,n.attribution&&n.attribution.interactionTargetElement&&(n.attribution.interactionTargetElement=void 0);var a=(i=this._instance.sessionManager)==null?void 0:i.checkAndGetSessionAndWindowId(!0),l=k({},n,r?{navigationURL:s}:{},{$current_url:s,timestamp:Date.now()});C(a)||(l.$session_id=a.sessionId,l.$window_id=a.windowId),this.R.metrics.push(l),this.R.metrics.length===this.allowedMetrics.length&&this.No()}else wn.error("Ignoring metric with value >= "+this.Ho,n)}}},this.Uo=()=>{if(!this.vo){var n,i,r,s,o=B.__PosthogExtensions__,a=o?.postHogWebVitalsCallbacksByFlavor,l=a?.[this.zo]||(this.zo==="web-vitals"&&C(a)?o?.postHogWebVitalsCallbacks:void 0);if(C(l)||(n=l.onLCP,i=l.onCLS,r=l.onFCP,s=l.onINP),n&&i&&r&&s){var u={reportSoftNavs:this.useSoftNavs};this.allowedMetrics.indexOf("LCP")>-1&&n(this.jo.bind(this),u),this.allowedMetrics.indexOf("CLS")>-1&&i(this.jo.bind(this),u),this.allowedMetrics.indexOf("FCP")>-1&&r(this.jo.bind(this),u),this.allowedMetrics.indexOf("INP")>-1&&s(this.jo.bind(this),u),this.vo=!0}else wn.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[sa]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,n=he(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return H(n)?((e=this._instance.persistence)==null?void 0:e.props[oa])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(he(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=he(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=he(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=he(this.Wo)&&ke(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:au;return t>0&&6e4>=t?au:t}get isEnabled(){var t=me?.protocol;if(t!=="http:"&&t!=="https:")return wn.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=he(this.Wo)?this.Wo.web_vitals:gt(this.Wo)?this.Wo:void 0;return gt(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(wn.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var n=he(e.capturePerformance)&&!!e.capturePerformance.web_vitals,i=he(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[sa]:n}),this._instance.persistence.register({[oa]:i})),this.Co=n,this.startIfEnabled()}}}get zo(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}ai(t){var e=B.__PosthogExtensions__,n=this.zo,i=e?.postHogWebVitalsCallbacksByFlavor;i!=null&&i[n]||n==="web-vitals"&&C(i)&&e!=null&&e.postHogWebVitalsCallbacks?t():e==null||e.loadExternalDependency==null||e.loadExternalDependency(this._instance,n,(r=>{r?wn.error("failed to load script",r):t()}))}Bo(t){var e=t||w?.location.href;if(e){var n=this._instance.config.disable_capture_url_hashes?fn(e):e,i=this._instance.config.custom_personal_data_properties,r=this._instance.config.mask_personal_data_properties?[...ri,...i||[]]:[];return Zi(n,r,Xi)}wn.error("Could not determine current URL")}}},Wm={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var n;if(w&&this.isEnabled&&(n=B.__PosthogExtensions__)!=null&&n.errorWrappingFunctions){var i=B.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,r=B.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,s=B.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.Vo&&this.Ne.capture_unhandled_errors&&(this.Vo=i(this.captureException.bind(this))),!this.Zo&&this.Ne.capture_unhandled_rejections&&(this.Zo=r(this.captureException.bind(this))),!this.Go&&this.Ne.capture_console_errors&&(this.Go=s(this.captureException.bind(this)))}catch(o){Ii.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[na]),this.Jo=new Up(k({},(function(n){var i,r,s,o;return n===void 0&&(n={}),{refillRate:(i=(r=n.exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:n.__exceptionRateLimiterRefillRate)!==null&&i!==void 0?i:1,bucketSize:(s=(o=n.exceptionRateLimiterBucketSize)!==null&&o!==void 0?o:n.__exceptionRateLimiterBucketSize)!==null&&s!==void 0?s:10}})(this._instance.config.error_tracking),{refillInterval:1e4,rt:Ii})),this.Ne=this.Yo(),this.startIfEnabledOrStop()}Yo(){var t=this._instance.config.capture_exceptions,e={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return he(t)?e=k({},e,t):(C(t)?this.Ko:t)&&(e=k({},e,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),e}get isEnabled(){return this.Ne.capture_console_errors||this.Ne.capture_unhandled_errors||this.Ne.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(Ii.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",(i=>{if(i)return Ii.error("failed to load script",i);t()}))}Qo(){var t,e,n;(t=this.Vo)==null||t.call(this),this.Vo=void 0,(e=this.Zo)==null||e.call(this),this.Zo=void 0,(n=this.Go)==null||n.call(this),this.Go=void 0}onRemoteConfig(t){if(t.ok){var e=t.config;"autocaptureExceptions"in e&&(this.Ko=!!e.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[na]:this.Ko}),this.Ne=this.Yo(),this.startIfEnabledOrStop())}}onConfigChange(){this.Ne=this.Yo()}captureException(t){var e,n,i,r=(e=t==null||(n=t.$exception_list)==null||(n=n[0])==null?void 0:n.type)!==null&&e!==void 0?e:"Exception";this.Jo.consumeRateLimit(r)?Ii.info("Skipping exception capture because of client rate limiting.",{exception:r}):(i=this._instance.exceptions)==null||i.sendExceptionEvent(t)}},exceptions:class{constructor(t){var e,n;this.Xo=[],this.tl=new rg([new fg,new bg,new pg,new hg,new yg,new _g,new mg,new wg],(function(i){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;r>o;o++)s[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` +`),d=l;c.length>d;d++){var f=c[d];if(1024>=f.length){var h=Cc.test(f)?f.replace(Cc,"$1"):f;if(!h.match(/\S*Error: /)){for(var p of s){var g=p(h,i);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var v=Array.from(m);return v.reverse(),v.slice(0,50).map((S=>{return k({},S,{filename:S.filename||(b=v,b[b.length-1]||{}).filename,function:S.function||ni});var b}))})(u)}})("web:javascript",lg,dg)),this._instance=t,this.Xo=(e=(n=this._instance.persistence)==null?void 0:n.get_property(ia))!==null&&e!==void 0?e:[],this.el=Jr(this.il()),this.rl=new Sg(this.el)}onConfigChange(){this.el=Jr(this.il()),this.rl.setConfig(this.el)}onRemoteConfig(t){var e,n,i;if(t.ok){var r=t.config;if("errorTracking"in r){var s=(e=(n=r.errorTracking)==null?void 0:n.suppressionRules)!==null&&e!==void 0?e:[],o=(i=r.errorTracking)==null?void 0:i.captureExtensionExceptions;this.Xo=s,this._instance.persistence&&this._instance.persistence.register({[ia]:this.Xo,[ra]:o})}}}get nl(){var t,e=!!this._instance.get_property(ra),n=this._instance.config.error_tracking.captureExtensionExceptions;return(t=n??e)!==null&&t!==void 0&&t}buildProperties(t,e){return this.tl.buildFromUnknown(t,{syntheticException:e?.syntheticException,mechanism:{handled:e?.handled}})}addExceptionStep(t,e){if(this.el.enabled)try{if(!X(t)||t.trim().length===0)return void St.warn("Ignoring exception step because message must be a non-empty string");var n=(function(s){if(!s)return{sanitizedProperties:{},droppedKeys:[]};var o=[];return{sanitizedProperties:Object.keys(s).reduce(((a,l)=>Eg.has(l)?(o.push(l),a):(a[l]=s[l],a)),{}),droppedKeys:o}})(this.sl(e)),i=n.sanitizedProperties,r=n.droppedKeys;r.length>0&&St.warn("Ignoring reserved exception step fields",{droppedKeys:r}),this.rl.add(k({[Kr]:t,[Yr]:new Date().toISOString()},i))}catch(s){St.error("Failed to add exception step. Ignoring breadcrumb.",s)}}sendExceptionEvent(t){try{var e=t.$exception_list;if(this.al(e)){if(this.ol(e))return this.ll("Exception dropped: matched a suppression rule"),void St.info("Skipping exception capture because a suppression rule matched");if(!this.nl&&this.ul(e))return this.ll("Exception dropped: thrown by a browser extension"),void St.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.hl(e))return this.ll("Exception dropped: thrown by the PostHog SDK"),void St.info("Skipping exception capture because it was thrown by the PostHog SDK")}var n=this.el.enabled&&H(t.$exception_steps)?this.dl(t):t,i=typeof(s=globalThis._posthogReleaseId)=="string"&&s.length>0?s:void 0;i&&(n.$release_id=i);try{var r=this._instance.capture("$exception",n,{_noTruncate:!0,_batchKey:"exceptionEvent",Wn:!0});return r&&this.rl.clear(),r}catch(o){return St.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void St.error("Failed to process exception event. Ignoring this exception.",o)}var s}dl(t){try{var e=this.rl.getAttachable();return e.length===0?t:k({},t,{$exception_steps:e})}catch(n){return St.error("Failed to read buffered exception steps. Capturing exception without steps.",n),t}}ll(t){this.el.enabled&&this.rl.add({[Kr]:t,[Yr]:new Date().toISOString()})}sl(t){return he(t)?k({},t):{}}il(){var t,e;return(t=(e=this._instance.config.error_tracking)==null?void 0:e.exception_steps)!==null&&t!==void 0?t:{}}ol(t){if(t.length===0)return!1;try{var e=t.reduce(((n,i)=>{var r=i.type,s=i.value;return X(r)&&r.length>0&&n.$exception_types.push(r),X(s)&&s.length>0&&n.$exception_values.push(s),n}),{$exception_types:[],$exception_values:[]});return this.Xo.some((n=>{var i=n.values.map((r=>{var s=jf[r.operator],o=e[r.key];if(!s||!o)return!1;var a=U(r.value)?r.value:[r.value];return a.length>0&&s(a,o)}));return n.type==="OR"?i.some(Boolean):i.every(Boolean)}))}catch(n){return St.warn("Failed to evaluate suppression rules. Capturing the exception.",n),!1}}ul(t){return t.flatMap((e=>{var n,i;return(n=(i=e.stacktrace)==null?void 0:i.frames)!==null&&n!==void 0?n:[]})).some((e=>e.filename&&e.filename.startsWith("chrome-extension://")))}hl(t){if(t.length>0){var e,n,i,r,s=(e=(n=t[0].stacktrace)==null?void 0:n.frames)!==null&&e!==void 0?e:[],o=s[s.length-1];return(i=o==null||(r=o.filename)==null?void 0:r.includes("posthog.com/static"))!==null&&i!==void 0&&i}return!1}al(t){return!H(t)&&U(t)}}},qm=k({productTours:class{get Mr(){return this._instance.persistence}constructor(t){this.vl=null,this.cl=null,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(t.ok){var e=t.config;if("productTours"in e){var n,i;if(this.Mr&&this.Mr.register({[sl]:!!e.productTours}),!Oo(this._instance))return!this.vl&&H((n=this.Mr)==null?void 0:n.props[Mi])||xr.info("product tours disabled; stopping and clearing cached tours"),(i=this.vl)==null||i.stop(),this.vl=null,void this.clearCache();this.loadIfEnabled()}}}loadIfEnabled(){!this.vl&&Oo(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.generateProductTours?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",(i=>{i?xr.error("Could not load product tours script",i):t()}))}fl(){var t;!this.vl&&(t=B.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=B.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(t,e){if(e===void 0&&(e=!1),!U(this.cl)||e){var n=this.Mr;if(n){var i=n.props[Mi];if(U(i)&&!e)return this.cl=i,void t(i,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",timestampMode:"query",callback:r=>{if(Oo(this._instance)){var s=r.statusCode;if(s!==200||!r.json){var o="Product Tours API could not be loaded, status: "+s;return s===0?r.error||xr.warn(o):xr.error(o),void t([],{isLoaded:!1,error:o})}var a=U(r.json.product_tours)?r.json.product_tours:[];this.cl=a,n&&n.register({[Mi]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){H(this.vl)?t([],{isLoaded:!1,error:"Product tours not loaded"}):this.vl.getActiveProductTours(t)}showProductTour(t){var e;(e=this.vl)==null||e.showTourById(t)}previewTour(t){this.vl?this.vl.previewTour(t):this.ai((()=>{var e;this.fl(),(e=this.vl)==null||e.previewTour(t)}))}dismissProductTour(){var t;(t=this.vl)==null||t.dismissTour("user_clicked_skip")}nextStep(){var t;(t=this.vl)==null||t.nextStep()}previousStep(){var t;(t=this.vl)==null||t.previousStep()}clearCache(){var t;this.cl=null,(t=this.Mr)==null||t.unregister(Mi)}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)}}},Cs),zm={siteApps:class{constructor(t){this.pl=0,this._instance=t,this.gl=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}ml(t,e){if(e){var n=this.globalsForEvent(e);this.gl.push(n),this.gl.length>1e3&&(this.gl=this.gl.slice(10))}}get siteAppLoaders(){var t;return(t=B._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,n,i,r,s,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var f=d[0];l[f]={id:u[f],type:f,properties:d[1]}}var h=t.$set_once,p=t.$set;return{event:k({},ud(t,Mm),{properties:k({},t.properties,p?{$set:k({},(e=(n=t.properties)==null?void 0:n.$set)!==null&&e!==void 0?e:{},p)}:{},h?{$set_once:k({},(i=(r=t.properties)==null?void 0:r.$set_once)!==null&&i!==void 0?i:{},h)}:{}),elements_chain:(s=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&s!==void 0?s:"",distinct_id:(a=t.properties)==null?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}bl(t){var e,n=(e=t.tagName)==null?void 0:e.toLowerCase();return n==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(Et.error("prepare_external_dependency_stylesheet returned null"),null):n==="script"&&this._instance.config.prepare_external_dependency_script?this._instance.config.prepare_external_dependency_script(t)||(Et.error("prepare_external_dependency_script returned null"),null):t}_l(){var t,e,n,i,r,s,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=F?.defaultView,u=l==null||(t=l.Node)==null?void 0:t.prototype;if(!l||!u)return()=>{};if(this.pl++,this.wl)return this.kl();var c=[],d=this,f=new WeakSet,h=(m,v,S)=>{if(m!=null&&m[v]){var b=m[v];m[v]=S(b),c.push((()=>{m[v]=b}))}},p=m=>{if(f.has(m))return m;var v=d.bl(m);return v&&f.add(v),v},g=m=>m.map((v=>typeof v=="string"?v:p(v))).filter((v=>!Ke(v)));return h(u,"appendChild",(m=>function(v){var S=p(v);return S?m.call(this,S):v})),h(u,"insertBefore",(m=>function(v,S){var b=p(v);return b?m.call(this,b,S):v})),h(u,"replaceChild",(m=>function(v,S){var b=p(v);return b?m.call(this,b,S):S})),[(e=l.Element)==null?void 0:e.prototype,(n=l.Document)==null?void 0:n.prototype,(i=l.DocumentFragment)==null?void 0:i.prototype].forEach((m=>{h(m,"append",(v=>function(){for(var S=arguments.length,b=new Array(S),_=0;S>_;_++)b[_]=arguments[_];return v.apply(this,g(b))})),h(m,"prepend",(v=>function(){for(var S=arguments.length,b=new Array(S),_=0;S>_;_++)b[_]=arguments[_];return v.apply(this,g(b))}))})),[(r=l.Element)==null?void 0:r.prototype,(s=l.CharacterData)==null?void 0:s.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((m=>{h(m,"before",(v=>function(){for(var S=arguments.length,b=new Array(S),_=0;S>_;_++)b[_]=arguments[_];return v.apply(this,g(b))})),h(m,"after",(v=>function(){for(var S=arguments.length,b=new Array(S),_=0;S>_;_++)b[_]=arguments[_];return v.apply(this,g(b))})),h(m,"replaceWith",(v=>function(){for(var S=arguments.length,b=new Array(S),_=0;S>_;_++)b[_]=arguments[_];var x=g(b);return b.length&&!x.length?void 0:v.apply(this,x)}))})),h((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(v,S){var b=p(S);return b?m.call(this,v,b):null})),this.wl=()=>{c.forEach((m=>m())),this.wl=void 0},this.kl()}kl(){var t=!1;return()=>{var e;t||(t=!0,this.pl--,this.pl===0&&((e=this.wl)==null||e.call(this)))}}xl(t,e){e===void 0&&(e=!0);var n=this._l();try{var i=t(n);return e&&n(),i}catch(r){throw n(),r}}setupSiteApp(t){var e=this.apps[t.id],n=()=>{var o;!e.errored&&this.gl.length&&(Et.info("Processing "+this.gl.length+" events for site app with id "+t.id),this.gl.forEach((a=>this.xl((()=>e.processEvent==null?void 0:e.processEvent(a))))),e.processedBuffer=!0),Object.values(this.apps).every((a=>a.processedBuffer||a.errored))&&((o=this.yl)==null||o.call(this))},i=!1,r=o=>{e.errored=!o,e.loaded=!0,Et.info("Site app with id "+t.id+" "+(o?"loaded":"errored")),i&&n()};try{var s=this.xl((o=>t.init({posthog:this._instance,callback(a){o(),r(a)}})),!1).processEvent;s&&(e.processEvent=s),i=!0}catch(o){Et.error(uu+t.id,o),r(!1)}if(i&&e.loaded)try{n()}catch(o){Et.error("Error while processing buffered events PostHog app with config id "+t.id,o),e.errored=!0}}Sl(){var t=this.siteAppLoaders||[];for(var e of t)this.apps[e.id]={id:e.id,loaded:!1,errored:!1,processedBuffer:!1};for(var n of t)this.setupSiteApp(n)}Cl(t){var e=this;if(Object.keys(this.apps).length!==0){var n=this.globalsForEvent(t),i=function(s){try{e.xl((()=>s.processEvent==null?void 0:s.processEvent(n)))}catch(o){Et.error("Error while processing event "+t.event+" for site app "+s.id,o)}};for(var r of Object.values(this.apps))i(r)}}onRemoteConfig(t){var e,n,i,r=this;if((e=this.siteAppLoaders)!=null&&e.length)return this.isEnabled?(this.Sl(),void this._instance.on("eventCaptured",(l=>this.Cl(l)))):void Et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((n=this.yl)==null||n.call(this),t.ok){var s=t.config;if((i=s.siteApps)!=null&&i.length)if(this.isEnabled){var o=function(){var l,u=a.id,c=a.url;B["__$$ph_site_app_"+u]=r._instance,(l=B.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(r._instance,c,(d=>{if(d)return Et.error(uu+u,d)}))};for(var a of s.siteApps)o()}else Et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},Vm={tracingHeaders:class{constructor(t){this.Ml=void 0,this.Tl=void 0,this.El=void 0,this.Uo=()=>{var e,n,i=this.Il();i?(C(this.Ml)&&(this.Ml=(e=B.__PosthogExtensions__)==null||(e=e.tracingHeadersPatchFns)==null?void 0:e._patchXHR(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager)),C(this.Tl)&&(this.Tl=(n=B.__PosthogExtensions__)==null||(n=n.tracingHeadersPatchFns)==null?void 0:n._patchFetch(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager))):this.Qo()},this._instance=t}initialize(){this.startIfEnabledOrStop()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",(i=>{if(i)return Tm.error("failed to load script",i);t()}))}Pl(){var t,e;return(t=(e=this._instance.config.tracing_headers)!==null&&e!==void 0?e:this._instance.config.addTracingHeaders)!==null&&t!==void 0?t:this._instance.config.__add_tracing_headers}Il(){var t=this.Pl();return U(t)?(U(this.El)?this.El.splice(0,this.El.length,...t):this.El=[...t],t.length>0?this.El:void 0):(U(this.El)&&this.El.splice(0),this.El=t||void 0,this.El)}Qo(){var t,e;(t=this.Ml)==null||t.call(this),(e=this.Tl)==null||e.call(this),this.Ml=void 0,this.Tl=void 0}startIfEnabledOrStop(){this.Il()?this.ai(this.Uo):this.Qo()}}},Gm=k({surveys:class{get Ne(){return this._instance.config}constructor(t){this.Rl=void 0,this._surveyManager=null,this.Al=!1,this.Fl=[],this.Ll=null,this.Ol=null,this._instance=t,this._surveyEventReceiver=null}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this.Ne.disable_surveys){if(!t.ok)return Q.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(H(e))return Q.warn("Flags not loaded yet. Not loading surveys.");var n=U(e);this.Rl=n?e.length>0:e,Q.info("flags response received, isSurveysEnabled: "+this.Rl),this.loadIfEnabled()}}reset(){try{var t;(t=this._surveyEventReceiver)==null||t.reset(),localStorage.removeItem("lastSeenSurveyDate");for(var e=[],n=0;nlocalStorage.removeItem(r)))}catch{}}loadIfEnabled(){if(!this._surveyManager)if(this.Al)Q.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)Q.info(du);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())Q.info("Not loading surveys in cookieless mode without consent.");else{var t=B?.__PosthogExtensions__;if(t){if(!C(this.Rl)||this.Ne.advanced_enable_surveys){var e=this.Rl||this.Ne.advanced_enable_surveys;this.Al=!0;try{var n=t.generateSurveys;if(n)return void this.Dl(n,e);var i=t.loadExternalDependency;if(!i)return void this.$l(al);i(this._instance,"surveys",(r=>{r||!t.generateSurveys?this.$l("Could not load surveys script",r):this.Dl(t.generateSurveys,e)}))}catch(r){throw this.$l("Error initializing surveys",r),r}finally{this.Al=!1}}}else Q.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new Om(this._instance),Q.info("Surveys loaded successfully"),this.Nl({isLoaded:!0})}$l(t,e){Q.error(t,e),this.Nl({isLoaded:!1,error:t})}onSurveysLoaded(t){return this.Fl.push(t),this._surveyManager&&this.Nl({isLoaded:!0}),()=>{this.Fl=this.Fl.filter((e=>e!==t))}}getSurveys(t,e){if(e===void 0&&(e=!1),this.Ne.disable_surveys)return Q.info(du),t([]);var n,i=this._instance.get_property(la);if(i&&!e)return t(i,{isLoaded:!0}),void(this.ql()&&this.getSurveys((()=>{}),!0));typeof Promise<"u"&&this.Ll?this.Ll.then((r=>t(r.surveys,r.context))):(typeof Promise<"u"&&(this.Ll=new Promise((r=>{n=r}))),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this.Ne.token),method:"GET",timestampMode:"query",timeout:this.Ne.surveys_request_timeout_ms,callback:r=>{var s;this.Ll=null;var o=r.statusCode;if(o!==200||!r.json){var a="Surveys API could not be loaded, status: "+o;o!==0?Q.error(a):r.error||Q.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(n==null||n({surveys:[],context:l}))}this.Ol=null;var u,c=r.json.surveys||[],d=c.filter((h=>(function(p){return!(!p.start_date||p.end_date)})(h)&&(Hf(h)||(function(p){var g;return!((g=p.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(h))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(s=this._instance.persistence)==null||s.register({[la]:c,[Xr]:Date.now()});var f={isLoaded:!0};t(c,f),n?.({surveys:c,context:f})}}))}ql(){return this.jl()&&!this.Ll&&!this.Bl()}jl(){var t=this._instance.get_property(Xr);return ke(t)&&Date.now()-t>3e5}Bl(){return ke(this.Ol)&&3e5>Date.now()-this.Ol}markSurveyAsSeen(t,e){var n,i={id:t,current_iteration:(n=e?.iteration)!==null&&n!==void 0?n:null};qf(i);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}}Nl(t){for(var e of this.Fl)try{if(!t.isLoaded)return e([],t);this.getSurveys(e)}catch(n){Q.error("Error in survey callback",n)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!H(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);Q.warn("init was not called")}Hl(t){var e=null;return this.getSurveys((n=>{var i;e=(i=n.find((r=>r.id===t)))!==null&&i!==void 0?i:null})),e}Ul(t){if(H(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(H(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(H(this._surveyManager))return Q.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 H(this._surveyManager)?(Q.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Ir})):new Promise((n=>{this.getSurveys((i=>{var r,s=(r=i.find((a=>a.id===t)))!==null&&r!==void 0?r:null;if(s){var o=this.zl(s);n({visible:o.eligible,disabledReason:o.reason})}else n({visible:!1,disabledReason:"Survey not found"})}),e)}))}renderSurvey(t,e,n){var i;if(H(this._surveyManager))Q.warn("init was not called");else{var r=typeof t=="string"?this.Hl(t):t;if(r!=null&&r.id)if(ym.includes(r.type)){var s=F?.querySelector(e);if(s)return(i=r.appearance)!=null&&i.surveyPopupDelaySeconds?(Q.info("Rendering survey "+r.id+" with delay of "+r.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;Q.info("Rendering survey "+r.id+" with delay of "+((o=r.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(a=this._surveyManager)==null||a.renderSurvey(r,s,n),Q.info("Survey "+r.id+" rendered")}),1e3*r.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(r,s,n);Q.warn("Survey element not found")}else Q.warn("Surveys of type "+r.type+" cannot be rendered in the app");else Q.warn("Survey not found")}}displaySurvey(t,e){var n;if(H(this._surveyManager))Q.warn("init was not called");else{var i=this.Hl(t);if(i){var r=i;if((n=i.appearance)!=null&&n.surveyPopupDelaySeconds&&e.ignoreDelay&&(r=k({},i,{appearance:k({},i.appearance,{surveyPopupDelaySeconds:0})})),e.displayType!==_a.Popover&&e.initialResponses&&Q.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),e.ignoreConditions===!1){var s=this.Ul(i);if(!s.eligible)return void Q.warn("Survey is not eligible to be displayed: ",s.reason)}e.displayType!==_a.Inline?this._surveyManager.handlePopoverSurvey(r,e):this.renderSurvey(r,e.selector,e.properties)}else Q.warn("Survey not found")}}cancelPendingSurvey(t){H(this._surveyManager)?Q.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},Cs),Km={toolbar:class{constructor(t){this.instance=t}Wl(t){B.ph_toolbar_state=t}Vl(){var t;return(t=B.ph_toolbar_state)!==null&&t!==void 0?t:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(t,e,n){if(t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),ga(this.instance.config)||!w||!F)return!1;t=t??w.location,n=n??w.history;try{if(!e){try{w.localStorage.setItem("test","test"),w.localStorage.removeItem("test")}catch{return!1}e=w?.localStorage}var i,r=Bm||os(t.hash,"__posthog")||os(t.hash,"state"),s=r?Pc((()=>JSON.parse(atob(decodeURIComponent(r)))))||Pc((()=>JSON.parse(decodeURIComponent(r)))):null;return s&&s.action==="ph_authorize"?((i=s).source="url",i&&Object.keys(i).length>0&&(s.desiredHash?t.hash=s.desiredHash:n?n.replaceState(n.state,"",t.pathname+t.search):t.hash="")):((i=JSON.parse(e.getItem(fu)||"{}")).source="localstorage",delete i.userIntent),!(!i.token||this.instance.config.token!==i.token||(this.loadToolbar(i),0))}catch{return!1}}Zl(t){var e=B.ph_load_toolbar||B.ph_load_editor;!H(e)&&De(e)?e(t,this.instance):hu.warn("No toolbar load function found")}loadToolbar(t){var e=!(F==null||!F.getElementById(sf));if(!w||e)return!1;var n=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,i=k({token:this.instance.config.token},t,{apiURL:this.instance.requestRouter.endpointFor("ui")},n?{instrument:!1}:{});if(w.localStorage.setItem(fu,JSON.stringify(k({},i,{source:void 0}))),this.Vl()===2)this.Zl(i);else if(this.Vl()===0){var r;this.Wl(1),(r=B.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"toolbar",(s=>{if(s)return hu.error("[Toolbar] Failed to load",s),void this.Wl(0);this.Wl(2),this.Zl(i)})),ve(w,"turbolinks:load",(()=>{this.Wl(0),this.loadToolbar(i)}))}return!0}Gl(t){return this.loadToolbar(t)}maybeLoadEditor(t,e,n){return t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),this.maybeLoadToolbar(t,e,n)}}},Ym=k({experiments:Me},Cs),Jm={conversations:class{constructor(t){this.Ql=void 0,this._conversationsManager=null,this.Kl=!1,this.Jl=null,this.Yl=!1,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this._instance.config.disable_conversations&&(this.Xl=t.ok,t.ok)){var e=t.config.conversations;H(e)||(gt(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||ga(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=B?.__PosthogExtensions__;if(t&&!C(this.Ql)&&this.Ql)if(this.Jl&&this.Jl.token){this.Kl=!0;try{var e=t.initConversations;if(e)return this.tu(e),void(this.Kl=!1);var n=t.loadExternalDependency;if(!n)return void this.eu(al);n(this._instance,"conversations",(i=>{i||!t.initConversations?this.eu("Could not load conversations script",i):this.tu(t.initConversations),this.Kl=!1}))}catch(i){this.eu("Error initializing conversations",i),this.Kl=!1}}else st.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,st.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else st.error("Cannot complete initialization: remote config is null")}eu(t,e){st.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():st.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!Ke(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":ga(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.Xl===!1?"remote_config_failed":C(this.Ql)?this.Xl?"disabled_in_project":"remote_config_pending":this.Ql?H(this.Jl)||!this.Jl.token?"missing_token":B!=null&&B.__PosthogExtensions__?this.Kl?"initializing":this.Yl?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.isVisible())!==null&&t!==void 0&&t}sendMessage(t,e,n){var i=this;return se((function*(){return i._conversationsManager?i._conversationsManager.sendMessage(t,e,n):(st.warn(En),null)}))()}getMessages(t,e){var n=this;return se((function*(){return n._conversationsManager?n._conversationsManager.getMessages(t,e):(st.warn(En),null)}))()}markAsRead(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(st.warn(En),null)}))()}getTickets(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(st.warn(En),null)}))()}requestRestoreLink(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(st.warn(En),null)}))()}restoreFromToken(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(st.warn(En),null)}))()}restoreFromUrlToken(){var t=this;return se((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(st.warn(En),null)}))()}getCurrentTicketId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getCurrentTicketId())!==null&&t!==void 0?t:null}getWidgetSessionId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getWidgetSessionId())!==null&&t!==void 0?t:null}Xn(){var t;(t=this._conversationsManager)==null||t.setIdentity()}ts(){var t;(t=this._conversationsManager)==null||t.clearIdentity()}}},Zm={logs:class{constructor(t){var e,n=this;this.iu=!1,this.ru=!1,this.rt=pe("[logs]"),this.nu=k({},this.rt,{error(){for(var i=arguments.length,r=new Array(i),s=0;i>s;s++)r[s]=arguments[s];r.some(bu)||n.rt.error(...r)}}),this.tr=[],this.su=[],this.Sa=0,this.au=()=>{var i,r;this.Sa=0,(i=this.ou)==null||i.onReconnect(),(r=this.lu)==null||r.onReconnect()},this._instance=t,this._instance&&(e=this._instance.config.logs)!=null&&e.captureConsoleLogs&&(this.iu=!0),w&&ve(w,"online",this.au)}uu(t,e,n,i){var r,s=(function(o,a){var l,u,c,d,f,h,p,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,v=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,S=C(v)?Math.max(m,2048):Math.max(m,v),b=o?.resourceAttributes;return{serviceName:(d=(f=b?.["service.name"])!==null&&f!==void 0?f:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(h=b?.["service.version"])!==null&&h!==void 0?h:o?.serviceVersion,environment:(p=b?.["deployment.environment"])!==null&&p!==void 0?p:o?.environment,resourceAttributes:b,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:S,maxBatchRecordsPerPost:100,rateCapWindowMs:g,maxLogsPerInterval:v,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}})((r=this._instance)==null||(r=r.config)==null?void 0:r.logs,n);return[new tg(this.hu(t,e),s,this.nu,(()=>this.du()),(o=>o()),void 0,i),s]}vu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.ou||this.cu!==e){var n;(n=this.ou)==null||n.reset(),this.cu=e;var i=this.uu((()=>this.tr),(r=>{this.tr=r}));this.ou=i[0],this.fu=i[1]}return this.ou}pu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.lu||this.gu!==e){var n;(n=this.lu)==null||n.reset(),this.gu=e;var i=this.uu((()=>this.su),(r=>{this.su=r}),{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},wu);this.lu=i[0],this.mu=i[1]}return this.lu}initialize(){this.loadIfEnabled()}onRemoteConfig(t){var e;if(t.ok){var n=(e=t.config.logs)==null?void 0:e.captureConsoleLogs;!H(n)&&n&&(this.iu=!0,this.loadIfEnabled())}}reset(){var t,e;this.tr=[],(t=this.ou)==null||t.reset(),this.su=[],(e=this.lu)==null||e.reset(),this.Sa=0}captureLog(t){this.vu().captureLog(t)}he(t){this.pu().captureLog(t)}get logger(){return this.yu||(this.yu={trace:(t,e)=>this.captureLog({body:t,level:"trace",attributes:e}),debug:(t,e)=>this.captureLog({body:t,level:"debug",attributes:e}),info:(t,e)=>this.captureLog({body:t,level:"info",attributes:e}),warn:(t,e)=>this.captureLog({body:t,level:"warn",attributes:e}),error:(t,e)=>this.captureLog({body:t,level:"error",attributes:e}),fatal:(t,e)=>this.captureLog({body:t,level:"fatal",attributes:e})}),this.yu}flushLogs(t){t?this.bu(t):(this.ou&&this.ou.flush().catch((e=>this._u(e))),this.lu&&this.lu.flush().catch((e=>this._u(e))))}_u(t){bu(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=B?.__PosthogExtensions__;if(t){var e=t.loadExternalDependency;e?e(this._instance,"logs",(n=>{var i;n||(i=t.logs)==null||!i.initializeLogs?this.rt.error("Could not load logs script",n):(t.logs.initializeLogs(this._instance),this.ru=!0)})):this.rt.error(al)}else this.rt.error("PostHog Extensions not found.")}}hu(t,e){var n=this._instance;return{get isDisabled(){return!1},get optedOut(){return!n.is_capturing()},getPersistedProperty:i=>i===Ut.LogsQueue?t():void 0,setPersistedProperty(i,r){var s;i===Ut.LogsQueue&&e((s=r)!==null&&s!==void 0?s:[])},Ot:i=>this.Ot(i),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Ot(t){return new Promise((e=>{if(vf(this.Sa,3))e({kind:"fatal",error:Do(void 0,"logs endpoint is unreachable, dropping batch")});else{var n=!1,i=s=>{n||(n=!0,clearTimeout(r),e(s))},r=setTimeout((()=>{this.rt.warn("Logs request timed out before receiving a response"),i({kind:"retry-later",error:Do(void 0,"logs request timed out")})}),9e4);this._instance._send_request({method:"POST",url:this.wu(),data:t,compression:"best-available",batchKey:"logs",fireCallbackOnDrop:!0,callback:s=>{var o=s.statusCode;if(this.ku(o),o>=200&&300>o)i({kind:"ok"});else if(o===413)i({kind:"too-large"});else if(o!==0&&o!==429&&500>o)i({kind:"fatal",error:new Error("logs request failed with status "+o)});else{var a;o===0?(s.error||this.rt.warn("Logs request failed before receiving an HTTP response"),i({kind:"retry-later",error:Do(s.error,"logs request failed before receiving an HTTP response")})):i({kind:"retry-later",error:(a=s.error)!==null&&a!==void 0?a:new Error("logs request failed with status "+o)})}}})}}))}ku(t){(t!==0||this._instance.__loaded)&&(this.Sa=_f(t,this.Sa,3,(()=>this.rt.warn("Log requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped sending logs; will try again when connectivity changes."))))}bu(t){this.tr.length>0&&this.xu(t,this.tr,this.fu,ne.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,wu,(e=>{this.su=e}))}xu(t,e,n,i,r){if(e.length!==0){var s=e.map((a=>a.record));r([]);var o=Ud(s,jd(n,ne.LIB_NAME,ne.LIB_VERSION),i,ne.LIB_VERSION);this._instance._send_request({method:"POST",url:this.wu(),data:o,compression:"best-available",batchKey:"logs",transport:t})}}wu(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}du(){var t,e={};if(e.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var n=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.windowId,r=n.sessionStartTimestamp,s=n.lastActivityTimestamp;e.sessionId=n.sessionId,e.windowId=i,H(r)||(e.sessionStartTimestamp=r),H(s)||(e.lastActivityTimestamp=s)}if(B!=null&&(t=B.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?fn(B.location.href):B.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},Xm={metrics:class{constructor(t){this.rt=pe("[metrics]"),this._instance=t}initialize(){}vu(){var t,e,n=(t=this._instance)==null||(t=t.config)==null?void 0:t.metrics;return this.ou&&this.cu===n||((e=this.ou)==null||e.reset(),this.cu=n,this.ou=new ng(this.hu(),(function(i){var r,s,o,a,l,u=i?.resourceAttributes;return{serviceName:(r=u?.["service.name"])!==null&&r!==void 0?r:i?.serviceName,serviceVersion:(s=u?.["service.version"])!==null&&s!==void 0?s:i?.serviceVersion,environment:(o=u?.["deployment.environment"])!==null&&o!==void 0?o:i?.environment,resourceAttributes:u,beforeSend:i?.beforeSend,flushIntervalMs:(a=i?.flushIntervalMs)!==null&&a!==void 0?a:1e4,maxSeriesPerFlush:(l=i?.maxSeriesPerFlush)!==null&&l!==void 0?l:1e3}})(n),this.rt)),this.ou}count(t,e,n){e===void 0&&(e=1),this.vu().count(t,e,n)}gauge(t,e,n){this.vu().gauge(t,e,n)}histogram(t,e,n){this.vu().histogram(t,e,n)}flush(t){if(!this.ou)return Promise.resolve();if(t){var e=this.ou.drainWindow();return e&&this.Jt(e,t),Promise.resolve()}return this.ou.flush().catch((n=>this.rt.error("PostHog metrics flush failed:",n)))}reset(){var t;(t=this.ou)==null||t.reset()}hu(){var t=this._instance,e=this;return{get isDisabled(){return!1},get optedOut(){return!t.is_capturing()},Jt:n=>e.Jt(n),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Jt(t,e){return new Promise((n=>{var i=!1,r=o=>{i||(i=!0,clearTimeout(s),n(o))},s=setTimeout((()=>r({kind:"retry-later",error:new Error("metrics request timed out")})),9e4);this._instance._send_request(k({method:"POST",url:this.Su(),data:t,compression:"best-available",batchKey:"metrics"},e&&{transport:e},{fireCallbackOnDrop:!0,callback(o){var a=o.statusCode;if(a>=200&&300>a)r({kind:"ok"});else if(a===413)r({kind:"too-large"});else if(a!==0&&a!==429&&500>a)r({kind:"fatal",error:new Error("metrics request failed with status "+a)});else{var l;r({kind:"retry-later",error:(l=o.error)!==null&&l!==void 0?l:new Error("metrics request failed with status "+a)})}}}))}))}Su(){return this._instance.requestRouter.endpointFor("api","/i/v1/metrics")+"?token="+encodeURIComponent(this._instance.config.token)}}},Qm=k({},Cs,Um,Hm,Wm,qm,zm,Gm,Vm,Km,Ym,Jm,Zm,Xm);Je.__defaultExtensionClasses=k({},Qm);(function(){ne.SDK_DIST_CHANNEL="npm";var t=Wi[Gn]=new Je;return(function(){function e(){e.done||(e.done=!0,Vf=!1,ie(Wi,(function(n){n._dom_loaded()})))}F!=null&&F.addEventListener?F.readyState==="complete"?e():ve(F,"DOMContentLoaded",e,{capture:!1}):w&&A.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const ev=["a[href]","button:not([disabled])","input:not([disabled]):not([type='hidden'])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(",");let ht=null,ka=null,Kf="";const Ca=new Map;function Yf(t){return[...t.querySelectorAll(ev)].filter(e=>!e.hidden&&e.getAttribute("aria-hidden")!=="true"&&e.getClientRects().length>0)}function tv(t){for(const e of document.body.children)e===t||e.tagName==="SCRIPT"||(Ca.set(e,{inert:e.inert,ariaHidden:e.getAttribute("aria-hidden")}),e.inert=!0,e.setAttribute("aria-hidden","true"))}function nv(){for(const[t,e]of Ca)t.inert=e.inert,e.ariaHidden===null?t.removeAttribute("aria-hidden"):t.setAttribute("aria-hidden",e.ariaHidden);Ca.clear()}function Jf(t){return t?.dataset.modalDismissible!=="false"&&t?.getAttribute("aria-busy")!=="true"}function He(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n)return!1;ht&&ht!==n&&We(ht,{restoreFocus:!1,force:!0}),ka=e.trigger||document.activeElement,ht=n,Kf=document.body.style.overflow,tv(n),document.body.style.overflow="hidden",n.classList.add("open"),n.setAttribute("aria-hidden","false");const i=n.querySelector(".modal-content");i&&(i.style.transform="scale(1) translateY(0)");const r=()=>{if(ht!==n)return;((e.initialFocus?n.querySelector(e.initialFocus):n.querySelector("[data-modal-initial-focus]"))||Yf(n)[0]||n.querySelector(".modal-content")||n).focus({preventScroll:!0})};return requestAnimationFrame(r),setTimeout(r,260),!0}function We(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n||!e.force&&!Jf(n))return!1;n.classList.remove("open"),n.setAttribute("aria-hidden","true"),nv(),document.body.style.overflow=Kf,ht=null;const i=ka;return ka=null,e.restoreFocus!==!1&&i?.isConnected&&i.focus({preventScroll:!0}),!0}function Eu(t,e,n="Operation in progress"){const i=typeof t=="string"?document.getElementById(t):t;i&&(i.dataset.modalDismissible=e?"false":"true",i.setAttribute("aria-busy",String(!!e)),e?i.setAttribute("aria-label",n):i.removeAttribute("aria-label"))}function iv(t){if(!Jf(t))return;const e=t.dataset.modalCloseHandler;e&&typeof window[e]=="function"?window[e]():We(t)}document.addEventListener("keydown",t=>{if(!ht)return;if(t.key==="Escape"){t.preventDefault(),t.stopImmediatePropagation(),iv(ht);return}if(t.key!=="Tab"){t.stopPropagation();return}const e=Yf(ht);if(!e.length){t.preventDefault(),(ht.querySelector(".modal-content")||ht).focus();return}const n=e[0],i=e[e.length-1];t.shiftKey&&document.activeElement===n?(t.preventDefault(),i.focus()):!t.shiftKey&&document.activeElement===i&&(t.preventDefault(),n.focus())},!0);function rv(){document.querySelectorAll(".modal-overlay").forEach(t=>{t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-hidden",t.classList.contains("open")?"false":"true");const e=t.querySelector(".modal-content");e&&!e.hasAttribute("tabindex")&&(e.tabIndex=-1);const n=t.querySelector("h1, h2, h3");n&&(n.id||(n.id=`${t.id}-title`),t.setAttribute("aria-labelledby",n.id)),t.querySelectorAll(".modal-close").forEach(i=>{i.getAttribute("aria-label")||i.setAttribute("aria-label","Close dialog")})})}const gl=Object.freeze({free:"Free",professional:"Pro",power:"Power"}),sv=Object.freeze({free:2,professional:50,power:2e3}),ov="(contact us)",av=Object.freeze({free:Object.freeze(["2 generations/month","Gemini model only","Code Review"]),professional:Object.freeze(["50 generations/month","All models","Code Regeneration","Code Review"]),power:Object.freeze(["2000 generations/month","All models","Code Regeneration","Bring your own key (BYOK)","Code Review","All models + early access",`API & MCP access ${ov}`])}),Zf="CodeFile",Xf="GeneratedCode",lv={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function ln(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Aa(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function cv(t={},e=0){const n=Aa(t.artifactType||t.type||Zf),i=Aa(t.artifactName||t.name||t.fileName||`${Xf}-${e+1}`);return`${n||"artifact"}-${i||e+1}`}function Qf(t={},e=0){const n=ln(t),i=n.artifactType||n.type||Zf,r=n.artifactName||n.name||Xf;let s=n.fileName||r;return s.endsWith(".dart")||(s+=".dart"),{id:Aa(n.id)||cv({...n,artifactType:i,artifactName:r,fileName:s},e),artifactType:i,artifactName:r,fileName:s,deployPath:n.deployPath||"",description:n.description||"",code:n.code||n.content||"",dependencies:eh(n.dependencies),imports:Array.isArray(n.imports)?n.imports:[],publicApi:Array.isArray(n.publicApi)?n.publicApi:[],relationships:th(n.relationships),deployStatus:n.deployStatus||"pending",review:n.review||null,metadata:ln(n.metadata),codeType:n.codeType||lv[i]||"O"}}function eh(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const n=ln(e),i=n.name||n.package;return i?{name:i,version:n.version||null,versionRequired:!!(n.versionRequired||n.required),inferred:!!n.inferred,...n.reason?{reason:n.reason}:{}}:null}).filter(Boolean):Object.entries(ln(t)).map(([e,n])=>({name:e,version:n||null,inferred:!1})):[]}function th(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const n=ln(e);return!n.from&&!n.to?null:{from:n.from||null,to:n.to||null,type:n.type||"uses",description:n.description||""}}).filter(Boolean):[]}function Pa(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;try{return JSON.parse(e)}catch{const n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(!n)return null;try{return JSON.parse(n[1].trim())}catch{return null}}}function Qi(t,e={}){const n=[],i=typeof t=="string"?Pa(t):t,s=ln(i||{});!i&&typeof t=="string"&&n.push("Structured bundle parse failed; using legacy single-artifact fallback.");const o=Array.isArray(s.artifacts)?s.artifacts:[{artifactType:s.artifactType||e.artifactType,artifactName:s.artifactName||e.artifactName,fileName:s.fileName||e.fileName,description:s.description,code:s.code||e.code||(typeof t=="string"?t:""),dependencies:s.dependencies||e.dependencies,relationships:s.relationships||e.relationships}];o.forEach((d,f)=>{!d?.artifactType&&!d?.type&&n.push(`Artifact ${f+1} has no artifactType; it will deploy as a standalone code file under lib/custom_code/ root.`)});const a=o.map((d,f)=>Qf(d,f)),l=new Map(o.map((d,f)=>[ln(d).id,a[f]?.id]).filter(([d,f])=>d&&f)),u=d=>l.get(d)||d,c=th(s.relationships||e.relationships).map(d=>({...d,from:d.from?u(d.from):d.from,to:d.to?u(d.to):d.to}));return{schemaVersion:s.schemaVersion||e.schemaVersion||null,id:s.id||e.id||"bundle-current",title:s.title||s.name||e.title||"Generated artifact bundle",description:s.description||e.description||"",artifacts:a,dependencies:eh(s.dependencies||e.dependencies),relationships:c,deployOrder:Array.isArray(s.deployOrder)?s.deployOrder.map(u):a.map(d=>d.id),warnings:[...n,...Array.isArray(s.warnings)?s.warnings:[]],metadata:ln(s.metadata)}}function oi(t){return Qi(t).artifacts[0]||Qf()}function Zt(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function ai(t){return JSON.stringify(t,null,2)}function uv(t){return ai({task:"architect",userRequest:String(t??"")})}function dv(t){const e=Zt(t);return e&&typeof e=="object"&&typeof e.task=="string"?ai(e):ai({task:"generate_bundle",bundleSpec:e})}function fv(t){return ai({task:"review_bundle",generatedBundle:Zt(t),outputRequirements:{bundleReview:["status","score","summary","manualActions","findings"],scoreRange:[0,100],eachArtifact:["id","review.status","review.findings"],manualActions:{definition:"Setup the developer must perform by hand in the FlutterFlow editor that FlutterFlow will NOT do for them.",exclude:["creating the Custom Action, Widget or Code File itself - deploying the code creates it","declaring parameters or return values FlutterFlow derives from the function signature","anything that resolves as a side effect of using the action or widget in the editor","generic advice such as testing, reviewing or rebuilding the app"],preferEmpty:"Return an empty array when nothing qualifies - an empty list is the expected result for most bundles."}}})}function ml(t,e=null){const n={stage:t};return e!=null&&(n.bundle=Zt(e)),n}function hv({bundleSpec:t,artifactBundle:e,bundleReview:n,artifactId:i,userFeedback:r}){return ai({task:"regenerate_artifact",artifactId:i,bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(r)})}function nh({bundleSpec:t,artifactBundle:e,bundleReview:n,userFeedback:i}){return ai({task:"regenerate_bundle",bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(i??"")})}const Su={csam:"child-safety content",dangerous:"dangerous content",harassment:"harassment",hate_speech:"hate speech",maliciousUrls:"a potentially malicious URL",malicious_uris:"a potentially malicious URL",pi_and_jailbreak:"prompt-injection or jailbreak instructions",promptInjection:"prompt-injection or jailbreak instructions",rai:"restricted content",sdp:"sensitive personal data",sexually_explicit:"sexually explicit content",virus_scan:"potentially malicious file content"},pv=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function et(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function gv(t){return et(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||et(t.filterSummary)||et(t.filterResults):!1}function ih(t,e=0){if(!et(t)||e>3)return null;if(gv(t))return t;for(const n of pv){const i=t[n];if(et(i)){const r=ih(i,e+1);if(r)return r}}return null}function ds(t){return Array.isArray(t)?t.some(ds):et(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(ds):!1}function Fa(t){return Array.isArray(t)?t.some(Fa):et(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(Fa):!1}function rh(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function mv(t,e){if(et(t))for(const[n,i]of Object.entries(t)){if(!et(i))continue;const r=et(i.categories)?i.categories:{},s=Object.entries(r).filter(([,o])=>et(o)&&o.matched===!0).map(([o])=>o);s.length>0?s.forEach(o=>e.add(o)):i.matched===!0&&e.add(rh(n))}}function vv(t,e){if(!t)return;const n=Array.isArray(t)?t.flatMap(i=>et(i)?Object.entries(i):[]):Object.entries(t);for(const[i,r]of n){if(!ds(r))continue;const s=rh(i),o=r?.raiFilterResult?.raiFilterTypeResults||(s==="rai"?r?.raiFilterTypeResults:null),a=et(o)?Object.entries(o).filter(([,l])=>ds(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(s)}}function _v(t){return Su[t]?Su[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function xu(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 yv(t){const e=ih(t);if(!e)return null;const n=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);mv(e.filterSummary,n),vv(e.filterResults,n);const i=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||n.size>0,r=e.invocationResult||null,s=Fa(e.filterSummary||e.filterResults);return!i&&!s&&!["PARTIAL","FAILURE"].includes(r)?null:{kind:i?"blocked":"unavailable",invocationResult:r,matchedFilters:[...n]}}function wv(t,e){const n=yv(t);if(!n)return null;const i=[...new Set(n.matchedFilters.map(_v))],r=n.kind==="blocked",s=new Error(r?`Safety screening blocked this pipeline step for ${xu(i)}.`:"Safety screening could not be completed. Please try again.");return s.name="ModelArmorError",s.code=r?"MODEL_ARMOR_BLOCKED":"MODEL_ARMOR_UNAVAILABLE",s.isModelArmor=!0,s.pipelineStep=e,s.userTitle=r?"Request blocked for safety":"Safety check unavailable",s.userMessage=r?`The safety check detected ${xu(i)}. Edit your request to remove or rephrase the flagged content, then run the pipeline again.`:"The safety service did not finish all of its checks. Please wait a moment and run the pipeline again.",s.retryExplanation=r?"Trying another model would not change this safety decision.":"A fallback model was not attempted because safety screening must complete first.",s.matchedFilters=n.matchedFilters,s}function bv(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function Iu(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,n=[];for(const i of bv(t).split(` `)){if(!/^[A-Za-z_$]/.test(i)||e.test(i))continue;const r=i.match(/^[\w$<>,?\s[\]]+?\s([a-zA-Z_$][\w$]*)\s*\(/);r&&n.push(r[1])}return n}function vl(t,e){const n=t.replace(/\.dart$/,"");if(e==="W")return n.replace(/(^|_)(\w)/g,(i,r,s)=>s.toUpperCase());if(e==="A"){const i=n.replace(/(^|_)(\w)/g,(r,s,o)=>o.toUpperCase());return i.charAt(0).toLowerCase()+i.slice(1)}return e==="F"?"CustomFunctions":e==="C"?t.endsWith(".dart")?t:`${t}.dart`:n}async function ku(t){const e=new TextEncoder().encode(String(t||"")),n=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n),i=>i.toString(16).padStart(2,"0")).join("")}async function Ev(t,e=new Map){const n={},i=new Set;for(const[o,a]of t.entries()){if(a.type==="D"||a.type==="O")continue;const l=vl(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await ku(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await ku(c)),n[o]=u,a.type==="F"){const d=Iu(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(h=>i.add(h))}}const r=new Set(Iu(e.get("lib/flutter_flow/custom_functions.dart")||"")),s={functions_to_rename:[],functions_to_delete:[],functions_to_add:Array.from(i).filter(o=>!r.has(o))};return{fileMapContents:JSON.stringify(n),functionsMapContents:JSON.stringify(s)}}const Sv=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),Cu={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},xv=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),Iv=["Struct","Record"],kv=[{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=>jo(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=>jo(t).some(e=>{const n=/^\s*final\s+(?:double|int|String|bool|Color|num)\s+(\w+)\s*;/gm;let i;for(;(i=n.exec(e))!==null;){const r=i[1];if(!(new RegExp(`this\\.${r}\\s*=(?!=)`).test(e)||new RegExp(`[:,]\\s*${r}\\s*=(?!=)`).test(e)))return!0}return!1}),pos:`class W extends StatefulWidget { const W({required this.value}); @@ -24,15 +24,15 @@ class _S extends State { @override Widget build(BuildContext c) => const Size final double? width; @override _S createState() => _S(); } -class _S extends State { @override Widget build(BuildContext c) => Padding(padding: const EdgeInsets.all(8), child: const SizedBox()); }`}];function St(t,e,n){return{artifactId:t.id,artifactName:t.artifactName,artifactType:t.artifactType,severity:e,message:n}}function er(t){let e="",n=0;for(;n"&&(n--,n===0))return{inner:t.slice(e+1,i),end:i+1};return null}function Av(t,e){const n=new RegExp(`class\\s+${e}\\b[^{]*\\{`).exec(t);if(!n)return null;let i=0;for(let r=n.index+n[0].length-1;rPv(t).usable);function Rv(t=""){const e=er(t);return Fv.filter(n=>n.detect(e)).map(({id:n,severity:i,message:r})=>({id:n,severity:i,message:r}))}function Tv(t){const e=[],n=t.matchAll(/\bFuture\b/g);for(const i of n){let r=i.index+6,s=null;const o=r;for(;ro;if(t[r]==="<"){const u=Cv(t,r);if(!u||(s=u.inner.replace(/\s+/g," ").trim(),r=u.end,!/\s/.test(t[r]||"")))continue;for(;rAu(o.functionName)===i);if(r)return r;const s=o=>!o.functionName.startsWith("_");return n.find(s)||n[0]}function As(t=""){return Array.from(er(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function $v(t="",e=""){return _l(t,e)?.returnType||null}function Pu(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 Mv(t,e){const n=As(e);if(n.length===0)return null;const r=String(t||"").split("/").pop().replace(/\.dart$/,"");if(n.some(l=>Pu(l)===r)||n.length>1)return null;const[o]=n,a=`${Pu(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 yl(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function Lv(t,e,n=""){const i=_l(e,n)?.functionName;if(!i)return null;const r=String(t||"").split("/").pop(),s=vl(r,"A");if(s===i)return null;const o=`${yl(i)}.dart`;return`File name "${r}" does not match Action "${i}". FlutterFlow derives the action from the file name, so it looks for "${s}" and reports Action "${s}" declaration not found. Rename the file to "${o}" - FlutterFlow puts an underscore before every capital - or rename the function to "${s}".`}function Nv(t="",e=""){return _l(t,e)!==null}function Ov(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(i=>xv.has(i)?!1:!Iv.some(s=>i.endsWith(s))||e.has(i))}function Bv(t,{functionName:e="",declaredTypes:n=new Set}={}){const i=$v(t,e),r=Ov(i,n);if(r.length===0)return null;const[s]=r;let o;return n.has(s)?o=`uses Code File type "${s}", which FlutterFlow cannot process as an Action Return Value`:i===s?o="is not a FlutterFlow Action Return Value":o=`uses type "${s}", which is not a FlutterFlow Action Return Value`,`CustomAction return type "${i}" ${o}. Return JSON (Future) or an existing FlutterFlow Data Type (*Struct) instead.`}function Dv(t,e={}){const n=[],i=t.fileName||"",r=t.code||"";if(Sv.has(t.artifactType)||n.push(St(t,"error",`Unsupported artifact type "${t.artifactType}".`)),i.endsWith(".dart")||n.push(St(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!r.trim())return n.push(St(t,"warning","Generated artifact has no Dart code yet.")),n;if(t.artifactType==="CustomWidget"){/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)||n.push(St(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const s of Rv(r))n.push(St(t,s.severity,s.message))}if(t.artifactType==="CustomAction"&&!Nv(r,t.artifactName)&&n.push(St(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const s=e.declaredTypes||new Set(As(r)),o=Bv(r,{functionName:t.artifactName,declaredTypes:s});o&&n.push(St(t,"error",o));const a=Lv(i,r,t.artifactName);a&&n.push(St(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)&&n.push(St(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const s=Mv(i,r);s&&n.push(St(t,"info",s))}return n}function jv(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],n=new Set(e.flatMap(s=>As(s.code||""))),i=e.flatMap(s=>Dv(s,{declaredTypes:n})),r=e.map(s=>({artifactId:s.id,fileName:s.fileName,pathHint:Cu[s.artifactType]||Cu.CodeFile}));return{valid:i.every(s=>s.severity!=="error"),findings:i,deployHints:r}}const Fu="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function Ru(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function Uv(t=""){const e=t.indexOf(Fu);return e===-1?t:t.slice(e+Fu.length).replace(/^\s*\n/,"")}const Hv=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function Wv(t="",e=""){const n=Uv(t),i=new Set((e.match(/^\s*import .*$/gm)||[]).map(Ru).filter(Boolean)),r=n.split(` +class _S extends State { @override Widget build(BuildContext c) => Padding(padding: const EdgeInsets.all(8), child: const SizedBox()); }`}];function xt(t,e,n){return{artifactId:t.id,artifactName:t.artifactName,artifactType:t.artifactType,severity:e,message:n}}function er(t){let e="",n=0;for(;n"&&(n--,n===0))return{inner:t.slice(e+1,i),end:i+1};return null}function Av(t,e){const n=new RegExp(`class\\s+${e}\\b[^{]*\\{`).exec(t);if(!n)return null;let i=0;for(let r=n.index+n[0].length-1;rPv(t).usable);function Rv(t=""){const e=er(t);return Fv.filter(n=>n.detect(e)).map(({id:n,severity:i,message:r})=>({id:n,severity:i,message:r}))}function Tv(t){const e=[],n=t.matchAll(/\bFuture\b/g);for(const i of n){let r=i.index+6,s=null;const o=r;for(;ro;if(t[r]==="<"){const u=Cv(t,r);if(!u||(s=u.inner.replace(/\s+/g," ").trim(),r=u.end,!/\s/.test(t[r]||"")))continue;for(;rAu(o.functionName)===i);if(r)return r;const s=o=>!o.functionName.startsWith("_");return n.find(s)||n[0]}function As(t=""){return Array.from(er(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function $v(t="",e=""){return _l(t,e)?.returnType||null}function Pu(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 Mv(t,e){const n=As(e);if(n.length===0)return null;const r=String(t||"").split("/").pop().replace(/\.dart$/,"");if(n.some(l=>Pu(l)===r)||n.length>1)return null;const[o]=n,a=`${Pu(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 yl(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function Lv(t,e,n=""){const i=_l(e,n)?.functionName;if(!i)return null;const r=String(t||"").split("/").pop(),s=vl(r,"A");if(s===i)return null;const o=`${yl(i)}.dart`;return`File name "${r}" does not match Action "${i}". FlutterFlow derives the action from the file name, so it looks for "${s}" and reports Action "${s}" declaration not found. Rename the file to "${o}" - FlutterFlow puts an underscore before every capital - or rename the function to "${s}".`}function Nv(t="",e=""){return _l(t,e)!==null}function Ov(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(i=>xv.has(i)?!1:!Iv.some(s=>i.endsWith(s))||e.has(i))}function Bv(t,{functionName:e="",declaredTypes:n=new Set}={}){const i=$v(t,e),r=Ov(i,n);if(r.length===0)return null;const[s]=r;let o;return n.has(s)?o=`uses Code File type "${s}", which FlutterFlow cannot process as an Action Return Value`:i===s?o="is not a FlutterFlow Action Return Value":o=`uses type "${s}", which is not a FlutterFlow Action Return Value`,`CustomAction return type "${i}" ${o}. Return JSON (Future) or an existing FlutterFlow Data Type (*Struct) instead.`}function Dv(t,e={}){const n=[],i=t.fileName||"",r=t.code||"";if(Sv.has(t.artifactType)||n.push(xt(t,"error",`Unsupported artifact type "${t.artifactType}".`)),i.endsWith(".dart")||n.push(xt(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!r.trim())return n.push(xt(t,"warning","Generated artifact has no Dart code yet.")),n;if(t.artifactType==="CustomWidget"){/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)||n.push(xt(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const s of Rv(r))n.push(xt(t,s.severity,s.message))}if(t.artifactType==="CustomAction"&&!Nv(r,t.artifactName)&&n.push(xt(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const s=e.declaredTypes||new Set(As(r)),o=Bv(r,{functionName:t.artifactName,declaredTypes:s});o&&n.push(xt(t,"error",o));const a=Lv(i,r,t.artifactName);a&&n.push(xt(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)&&n.push(xt(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const s=Mv(i,r);s&&n.push(xt(t,"info",s))}return n}function jv(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],n=new Set(e.flatMap(s=>As(s.code||""))),i=e.flatMap(s=>Dv(s,{declaredTypes:n})),r=e.map(s=>({artifactId:s.id,fileName:s.fileName,pathHint:Cu[s.artifactType]||Cu.CodeFile}));return{valid:i.every(s=>s.severity!=="error"),findings:i,deployHints:r}}const Fu="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function Ru(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function Uv(t=""){const e=t.indexOf(Fu);return e===-1?t:t.slice(e+Fu.length).replace(/^\s*\n/,"")}const Hv=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function Wv(t="",e=""){const n=Uv(t),i=new Set((e.match(/^\s*import .*$/gm)||[]).map(Ru).filter(Boolean)),r=n.split(` `).filter(s=>{const o=Ru(s);return o===null||!i.has(o)?!0:!Hv.test(s)}).join(` `).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+r}const qv=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations"]);function sh(t){let e="",n=0;for(;n{const i=n.name||n.package;if(!i||i==="flutter")return e;const r=n.versionRequired||n.required;return e[i]=r&&n.version||"",e},{})}function Yv(t){const e=new Map,n=new Map,i=[];for(const r of t)e.has(r.fileName)?i.push(`Duplicate deploy file name "${r.fileName}" for artifacts "${e.get(r.fileName)}" and "${r.artifactId}".`):e.set(r.fileName,r.artifactId),n.has(r.path)?i.push(`Duplicate deploy path "${r.path}" for artifacts "${n.get(r.path)}" and "${r.artifactId}".`):n.set(r.path,r.artifactId);return i}function Jv(t,e={}){const n=Array.isArray(t?.artifacts)?t.artifacts:[],r=(e.selectedArtifactIds||t?.deployOrder||n.map(h=>h.id)).map(h=>n.find(p=>p.id===h)).filter(Boolean),s=[...t?.warnings||[]];let o=[];r.forEach(h=>{const p=Kv(h),g=h.fixedCode||h.code||"",m=h.codeType||Vv[h.artifactType]||Ze.OTHER;g.trim()||s.push(`${h.artifactName||h.id} has no generated code.`),o.push({artifactId:h.id,artifactName:h.artifactName,artifactType:h.artifactType,fileName:p,content:g,type:m,path:h.deployPath||Gv(p,m),deployPath:h.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((h,p)=>({entry:h,index:p})).filter(({entry:h})=>h.type===Ze.FUNCTION&&h.path===a);if(l.length>1){const h=l[0],p={...h.entry,artifactId:l.map(({entry:m})=>m.artifactId).join("+"),artifactName:h.entry.artifactName,content:l.map(({entry:m})=>`// ${m.artifactId} ${m.content}`).join(` -`)},g=new Set(l.slice(1).map(({index:m})=>m));o=o.filter((m,v)=>!g.has(v)),o[h.index]=p}const u={...Tu(t?.dependencies),...r.reduce((h,p)=>({...h,...Tu(p.dependencies)}),{})},c={};r.forEach(h=>{wl(h.code||"").forEach(p=>{p in u||(c[p]="")})});const d={...c,...u},f=Yv(o);return{bundleId:t?.id||"bundle-current",title:t?.title||"Generated artifact bundle",fileEntries:o,dependencies:d,relationships:t?.relationships||[],warnings:s,errors:f}}function Zv(t){return String(t||"").match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/)?.[1]}function Xv(t){return String(t||"").split("/").pop().replace(/\.dart$/,"").split(/[^A-Za-z0-9]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function Qv(t,e){const i=[Xv(t),Zv(e.content),e.artifactName].find(r=>/^[A-Z][A-Za-z0-9_]*$/.test(String(r||"")));if(!i)throw new Error(`Cannot derive a FlutterFlow custom class name for ${t}.`);return i}function e_(t,e=new Map){const n=[];for(const[i,r]of t.entries())r.type!=="C"||e.has(r.path)||n.push({artifactId:r.artifactId||i,className:Qv(i,r),content:r.content,fileName:i,path:r.path});return n}function t_(t,e){const n=new Set(e.map(i=>i.path));return new Map(Array.from(t.entries()).filter(([,i])=>!n.has(i.path)))}const $u={pass:0,warning:1,fail:2},n_=["manualActions"];function rt(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function zt(...t){for(const e of t){if(typeof e=="string"&&e.trim())return e.trim();if(Array.isArray(e)&&e.length>0){const n=e.filter(i=>typeof i=="string").join(` -`);if(n)return n}}return""}function It(t){return t==null?[]:Array.isArray(t)?t:[t]}function i_(t){const e=rt(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const n=Number(e);if(Number.isFinite(n))return Mu(n);const i=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return i?Mu(Number(i[1])):null}function Mu(t){return t>=0&&t<=100?t:null}function at(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function bl(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 Ra(...t){return t.filter(Boolean).reduce((e,n)=>$u[n]>$u[e]?n:e,"pass")}function oh(t,e="warning",n="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:n};const i=rt(t),r=zt(i.message,i.title,i.issue,i.description,i.summary);return r?{severity:bl(i.severity||i.status||i.level)||e,message:r,suggestion:zt(i.suggestion,i.fix,i.recommendation,i.action),source:i.source||n}:null}function Ta(t,e="review"){const n=rt(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([r,s])=>It(n[r]).map(o=>oh(o,s,e)).filter(Boolean))}function r_(t,e,n=null){if(typeof t=="string")return{id:`${n||"bundle"}-manual-${e+1}`,title:t,detail:"",location:"",timing:"unspecified",artifactId:n,source:"Code Review"};const i=rt(t),r=zt(i.title,i.action,i.step,i.message,i.name,i.description);return r?{id:i.id||`${n||"bundle"}-manual-${e+1}`,title:r,detail:zt(i.detail,i.instructions,i.description),location:zt(i.location,i.flutterFlowPath,i.path),timing:zt(i.timing,i.phase)||"unspecified",artifactId:n,source:zt(i.source)||"Code Review"}:null}function $a(t,e=null){const n=rt(t);return n_.flatMap(i=>It(n[i])).map((i,r)=>r_(i,r,e)).filter(Boolean)}function s_(t){let e=typeof t=="string"?Pa(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const n=rt(e);typeof n.content=="string"&&(e=Pa(n.content)||e);const i=rt(e),r=rt(i.reviewResult||i.codeReview||i.result);return{rawText:"",root:Object.keys(r).length?r:i}}function o_(t,e){const n=[e.id,e.fileName,e.artifactName].map(at);return t.find(i=>{const r=rt(i);return[r.id,r.fileName,r.artifactName,r.name].map(at).some(s=>s&&n.includes(s))})||null}function a_(t,e){return It(t?.metadata?.compatibility?.deployHints).find(r=>at(r?.artifactId)===at(e.id)||at(r?.fileName)===at(e.fileName))?.pathHint||""}function l_(t,e){return It(t?.relationships).filter(n=>at(n?.from)===at(e.id)||at(n?.to)===at(e.id))}function c_(t,e){return It(t?.metadata?.compatibility?.findings).filter(n=>!n?.artifactId||at(n.artifactId)===at(e.id)).map(n=>oh(n,"warning","Compatibility check")).filter(Boolean)}function u_(t,e,n,i){const r=o_(e,n),s=rt(r?.review||r||n.review),o=Object.keys(s).length>0,a=[...Ta(s),...c_(t,n)],l=$a(s,n.id),u=bl(s.status||s.verdict||s.outcome||s.result),c=a.length?Ra(...a.map(f=>f.severity)):null,d=Ra(u,c,o?null:"warning");return{...n,index:i,status:d,statusReason:o?zt(s.summary,s.overview,s.assessment,s.conclusion)||(a.length?`${a.length} review finding${a.length===1?"":"s"}`:"No file-level findings"):"No file-level verdict was returned",reviewComplete:o,findings:a,manualSteps:l,fixedSource:typeof s.fixedSource=="string"&&s.fixedSource.trim()?s.fixedSource.trim():null,pathHint:a_(t,n),relationships:l_(t,n)}}function d_({status:t,score:e,artifactPresentations:n,manualSteps:i}){const r=n.length;if(r===0&&i.length===0)return e==null?"Code review returned no overall summary and no score.":`Reviewed bundle with score ${e}/100.`;const s=n.reduce((a,l)=>(a[l.status]+=1,a),{pass:0,warning:0,fail:0}),o=[];return t&&o.push(`Overall verdict: ${t}.`),r&&o.push(`${r} artifact${r===1?"":"s"}: ${s.pass} pass, ${s.warning} warn, ${s.fail} fail.`),i.length&&o.push(`Do before deploy: ${i.map(a=>a.title).join("; ")}.`),e==null&&o.push("No numeric score (0-100) was returned."),o.join(" ")}function f_({bundle:t,reviewResult:e}){const n=rt(t),i=It(n.artifacts),{root:r,rawText:s}=s_(e),o=[r.bundleReview,r.overallReview,r.overall,r.bundleSummary,r.summaryReview,r.review].map(rt).find(b=>Object.keys(b).length)||{},a=It(r.artifacts||r.files||r.reviews),l=i.map((b,_)=>u_(n,a,b,_)),u=Ta(r),d=[...Ta(o),...u],f=[...$a(o),...$a(r),...l.flatMap(b=>b.manualSteps)].filter((b,_,x)=>x.findIndex(I=>I.title===b.title&&I.artifactId===b.artifactId)===_),h=bl(o.status||o.verdict||o.overallStatus||r.status||r.verdict||r.overallStatus||r.outcome),p=Ra(h,...d.map(b=>b.severity),...l.map(b=>b.status)),g=o.score??r.score??r.overallScore??s,m=i_(g),v=zt(o.headline,o.summary,o.executiveSummary,o.overview,o.assessment,o.conclusion,r.overallSummary,r.headline,r.summary,r.executiveSummary,r.overview,r.assessment,r.conclusion,s)||d_({status:p,score:m,artifactPresentations:l,manualSteps:f}),S=l.reduce((b,_)=>(b[_.status]+=1,b),{pass:0,warning:0,fail:0});return{title:n.title||"Generated artifact bundle",description:n.description||"",status:p,score:m,summary:v,findings:d,manualSteps:f,artifacts:l,counts:S,reviewCoverage:{reviewed:l.filter(b=>b.reviewComplete).length,total:l.length},deployOrder:It(n.deployOrder),relationships:It(n.relationships),warnings:It(n.warnings),compatibility:rt(n.metadata?.compatibility)}}const h_=/^\uFEFF/;function Ci(t){let e=0,n=t.length;for(;ee&&!t[n-1].trim();)n--;return t.slice(e,n).join(` +`)},g=new Set(l.slice(1).map(({index:m})=>m));o=o.filter((m,v)=>!g.has(v)),o[h.index]=p}const u={...Tu(t?.dependencies),...r.reduce((h,p)=>({...h,...Tu(p.dependencies)}),{})},c={};r.forEach(h=>{wl(h.code||"").forEach(p=>{p in u||(c[p]="")})});const d={...c,...u},f=Yv(o);return{bundleId:t?.id||"bundle-current",title:t?.title||"Generated artifact bundle",fileEntries:o,dependencies:d,relationships:t?.relationships||[],warnings:s,errors:f}}function Zv(t){return String(t||"").match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/)?.[1]}function Xv(t){return String(t||"").split("/").pop().replace(/\.dart$/,"").split(/[^A-Za-z0-9]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function Qv(t,e){const i=[Xv(t),Zv(e.content),e.artifactName].find(r=>/^[A-Z][A-Za-z0-9_]*$/.test(String(r||"")));if(!i)throw new Error(`Cannot derive a FlutterFlow custom class name for ${t}.`);return i}function e_(t,e=new Map){const n=[];for(const[i,r]of t.entries())r.type!=="C"||e.has(r.path)||n.push({artifactId:r.artifactId||i,className:Qv(i,r),content:r.content,fileName:i,path:r.path});return n}function t_(t,e){const n=new Set(e.map(i=>i.path));return new Map(Array.from(t.entries()).filter(([,i])=>!n.has(i.path)))}const $u={pass:0,warning:1,fail:2},n_=["manualActions"];function rt(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Vt(...t){for(const e of t){if(typeof e=="string"&&e.trim())return e.trim();if(Array.isArray(e)&&e.length>0){const n=e.filter(i=>typeof i=="string").join(` +`);if(n)return n}}return""}function kt(t){return t==null?[]:Array.isArray(t)?t:[t]}function i_(t){const e=rt(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const n=Number(e);if(Number.isFinite(n))return Mu(n);const i=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return i?Mu(Number(i[1])):null}function Mu(t){return t>=0&&t<=100?t:null}function at(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function bl(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 Ra(...t){return t.filter(Boolean).reduce((e,n)=>$u[n]>$u[e]?n:e,"pass")}function oh(t,e="warning",n="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:n};const i=rt(t),r=Vt(i.message,i.title,i.issue,i.description,i.summary);return r?{severity:bl(i.severity||i.status||i.level)||e,message:r,suggestion:Vt(i.suggestion,i.fix,i.recommendation,i.action),source:i.source||n}:null}function Ta(t,e="review"){const n=rt(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([r,s])=>kt(n[r]).map(o=>oh(o,s,e)).filter(Boolean))}function r_(t,e,n=null){if(typeof t=="string")return{id:`${n||"bundle"}-manual-${e+1}`,title:t,detail:"",location:"",timing:"unspecified",artifactId:n,source:"Code Review"};const i=rt(t),r=Vt(i.title,i.action,i.step,i.message,i.name,i.description);return r?{id:i.id||`${n||"bundle"}-manual-${e+1}`,title:r,detail:Vt(i.detail,i.instructions,i.description),location:Vt(i.location,i.flutterFlowPath,i.path),timing:Vt(i.timing,i.phase)||"unspecified",artifactId:n,source:Vt(i.source)||"Code Review"}:null}function $a(t,e=null){const n=rt(t);return n_.flatMap(i=>kt(n[i])).map((i,r)=>r_(i,r,e)).filter(Boolean)}function s_(t){let e=typeof t=="string"?Pa(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const n=rt(e);typeof n.content=="string"&&(e=Pa(n.content)||e);const i=rt(e),r=rt(i.reviewResult||i.codeReview||i.result);return{rawText:"",root:Object.keys(r).length?r:i}}function o_(t,e){const n=[e.id,e.fileName,e.artifactName].map(at);return t.find(i=>{const r=rt(i);return[r.id,r.fileName,r.artifactName,r.name].map(at).some(s=>s&&n.includes(s))})||null}function a_(t,e){return kt(t?.metadata?.compatibility?.deployHints).find(r=>at(r?.artifactId)===at(e.id)||at(r?.fileName)===at(e.fileName))?.pathHint||""}function l_(t,e){return kt(t?.relationships).filter(n=>at(n?.from)===at(e.id)||at(n?.to)===at(e.id))}function c_(t,e){return kt(t?.metadata?.compatibility?.findings).filter(n=>!n?.artifactId||at(n.artifactId)===at(e.id)).map(n=>oh(n,"warning","Compatibility check")).filter(Boolean)}function u_(t,e,n,i){const r=o_(e,n),s=rt(r?.review||r||n.review),o=Object.keys(s).length>0,a=[...Ta(s),...c_(t,n)],l=$a(s,n.id),u=bl(s.status||s.verdict||s.outcome||s.result),c=a.length?Ra(...a.map(f=>f.severity)):null,d=Ra(u,c,o?null:"warning");return{...n,index:i,status:d,statusReason:o?Vt(s.summary,s.overview,s.assessment,s.conclusion)||(a.length?`${a.length} review finding${a.length===1?"":"s"}`:"No file-level findings"):"No file-level verdict was returned",reviewComplete:o,findings:a,manualSteps:l,fixedSource:typeof s.fixedSource=="string"&&s.fixedSource.trim()?s.fixedSource.trim():null,pathHint:a_(t,n),relationships:l_(t,n)}}function d_({status:t,score:e,artifactPresentations:n,manualSteps:i}){const r=n.length;if(r===0&&i.length===0)return e==null?"Code review returned no overall summary and no score.":`Reviewed bundle with score ${e}/100.`;const s=n.reduce((a,l)=>(a[l.status]+=1,a),{pass:0,warning:0,fail:0}),o=[];return t&&o.push(`Overall verdict: ${t}.`),r&&o.push(`${r} artifact${r===1?"":"s"}: ${s.pass} pass, ${s.warning} warn, ${s.fail} fail.`),i.length&&o.push(`Do before deploy: ${i.map(a=>a.title).join("; ")}.`),e==null&&o.push("No numeric score (0-100) was returned."),o.join(" ")}function f_({bundle:t,reviewResult:e}){const n=rt(t),i=kt(n.artifacts),{root:r,rawText:s}=s_(e),o=[r.bundleReview,r.overallReview,r.overall,r.bundleSummary,r.summaryReview,r.review].map(rt).find(b=>Object.keys(b).length)||{},a=kt(r.artifacts||r.files||r.reviews),l=i.map((b,_)=>u_(n,a,b,_)),u=Ta(r),d=[...Ta(o),...u],f=[...$a(o),...$a(r),...l.flatMap(b=>b.manualSteps)].filter((b,_,x)=>x.findIndex(I=>I.title===b.title&&I.artifactId===b.artifactId)===_),h=bl(o.status||o.verdict||o.overallStatus||r.status||r.verdict||r.overallStatus||r.outcome),p=Ra(h,...d.map(b=>b.severity),...l.map(b=>b.status)),g=o.score??r.score??r.overallScore??s,m=i_(g),v=Vt(o.headline,o.summary,o.executiveSummary,o.overview,o.assessment,o.conclusion,r.overallSummary,r.headline,r.summary,r.executiveSummary,r.overview,r.assessment,r.conclusion,s)||d_({status:p,score:m,artifactPresentations:l,manualSteps:f}),S=l.reduce((b,_)=>(b[_.status]+=1,b),{pass:0,warning:0,fail:0});return{title:n.title||"Generated artifact bundle",description:n.description||"",status:p,score:m,summary:v,findings:d,manualSteps:f,artifacts:l,counts:S,reviewCoverage:{reviewed:l.filter(b=>b.reviewComplete).length,total:l.length},deployOrder:kt(n.deployOrder),relationships:kt(n.relationships),warnings:kt(n.warnings),compatibility:rt(n.metadata?.compatibility)}}const h_=/^\uFEFF/;function Ci(t){let e=0,n=t.length;for(;ee&&!t[n-1].trim();)n--;return t.slice(e,n).join(` `)}function p_(t){const e=String(t??"").replace(h_,"");if(!e.trim())return"";const n=e.split(` `),i=c=>{const d=c.trim();return/^`{3,}[A-Za-z0-9+#_.-]*$/.test(d)?c.length-c.trimStart().length:-1};let r=0,s=-1;const o=[];{let c=0;for(let d=0;d=0&&(r++,s<0&&(s=d),o.push(c+f)),c+=n[d].length+1}}if(r===0)return Ci(n);{const c=Ma(e);if(!c.error&&o.every(f=>Nu(f,c.commentAndStringRanges)))return Ci(n)}if(r===1){const c=Ci(n.slice(0,s)),d=Ci(n.slice(s+1));return d.length>=c.length?d:c}const a=[];let l=null;for(let c=0;c!n.startsWith("dart:")&&!n.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function Bu(t,e,n){const i=[];for(const[r,s]of t){if(s.isScalar){e[r]=La(s.constraint);continue}if(s.sourceKey==="sdk"){n.add(r);continue}if(s.sourceKey===null&&s.version){e[r]=La(s.version);continue}i.push(r)}return i}function q_(t){const e=new Set,n={},i={},r=Bu($s(t),n,e);r.push(...Bu(B_(t,"dependency_overrides"),i,e));const s=new Set([...Object.keys(n),...e]),{sdk:o}=ph(t);return{sdkConstraint:La(o)||H_,dependencies:n,overrides:i,sdkPackages:[...e].sort(),availablePackages:s,unrepresentable:r}}function z_(t,e,n){return e.length>0?`${t} imports ${e.join(", ")}, which FlutterFlow only generates once the app is built, so it could not be compiled before the deploy.`:`${t} imports ${n.join(", ")}, which your project's pubspec.yaml does not declare with a version constraint, so it could not be compiled before the deploy.`}function V_(t,e){const{sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s,availablePackages:o,unrepresentable:a}=q_(e),l={sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s},u=[],c=[],d=a.map(f=>`Your project declares ${f} from a source that cannot be reproduced outside it, so the pre-deploy compile check runs against a scratch package graph that omits ${f}. Classes that do not import ${f} directly are still checked, but against that reduced graph, so their transitive package resolution may differ from your project's and the check is approximate for them.`);for(const f of t){const{className:h,content:p}=f,g=wl(p),m=g.filter(b=>a.includes(b));if(m.length>0){c.push({className:h,reason:`${h} was not compiled before deploying: it imports ${m.join(", ")}, which your project declares from a source that cannot be reproduced outside it, so package resolution could not be matched exactly.`});continue}const{unresolvableImports:v}=W_(p),S=g.filter(b=>!o.has(b));if(v.length>0||S.length>0){c.push({className:h,reason:z_(h,v,S)});continue}u.push({fileName:`${yl(h)}.dart`,content:p})}return{manifest:l,sources:u,skipped:c,approximate:d}}function Du(t,e){const n=`${t}${e}`.split(` -`),i=n.pop()??"",r=[];for(const s of n){const o=vh(s);o&&r.push(o)}return{events:r,buffer:i}}function G_(t){const e=vh(t);return e?[e]:[]}function vh(t){const e=t.trim();if(!e)return null;try{const n=JSON.parse(e);return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}const Xe=Object.freeze({COMMITTED:"committed",PARTIAL:"partial",FAILED:"failed",UNCONFIRMED:"unconfirmed"}),K_=12e4;function _h(t){return t?.unconfirmed===!0||t?.outcome===Xe.UNCONFIRMED?Xe.UNCONFIRMED:t?.partial===!0||t?.outcome===Xe.PARTIAL?Xe.PARTIAL:t?.success===!0?Xe.COMMITTED:Xe.FAILED}class Yt extends Error{constructor(e){super(e),this.name="UnconfirmedDeployError",this.outcome=Xe.UNCONFIRMED}}function Y_({sawTransportError:t,httpStatus:e}={}){return t?new Yt("Every FlutterFlow sync endpoint stopped answering without a definitive response. The push may still have been applied — open the FlutterFlow project to reconcile before retrying."):new Error(`FlutterFlow rejected the code sync${e?` (HTTP ${e})`:""} after every retry.`)}async function J_(t,e={}){const{onPhase:n,onLog:i}=e;let r=null,s="";const o=l=>{if(l.event==="phase"){l.message&&n&&n(l.message);return}if(l.event==="log"){l.message&&i&&i(l.message);return}r=l};let a=null;try{if(t.body?.getReader){const l=t.body.getReader(),u=new TextDecoder;for(;;){const{done:c,value:d}=await l.read();if(c)break;const f=Du(s,u.decode(d,{stream:!0}));s=f.buffer,f.events.forEach(o)}}else{const l=Du("",await t.text());s=l.buffer,l.events.forEach(o)}}catch(l){a=l}return G_(s).forEach(o),r?{...r,success:r.success===!0||r.success===void 0&&t.ok,finalResultReceived:!0}:{success:!1,finalResultReceived:!1,httpRejected:!t.ok,httpStatus:t.status,error:a?"The connection to the FlutterFlow deploy runner dropped before it reported a result.":t.ok?"The FlutterFlow deploy runner closed the connection before it finished.":`FlutterFlow custom class provisioning failed (HTTP ${t.status}).`}}function Z_(t){return t?.finalResultReceived?_h(t):t?.httpRejected?Xe.FAILED:Xe.UNCONFIRMED}function X_(){let t=document.getElementById("fx-grid");if(!t)return null;const e=window.matchMedia("(prefers-reduced-motion: reduce)"),n=window.matchMedia("(pointer: none)");let i=t.getContext("webgl2",{alpha:!0,antialias:!1,depth:!1,stencil:!1,premultipliedAlpha:!0,powerPreference:"low-power"}),r=i?null:t.getContext("2d");if(!i&&!r)return null;const s='',o=`#version 300 es +`),i=n.pop()??"",r=[];for(const s of n){const o=vh(s);o&&r.push(o)}return{events:r,buffer:i}}function G_(t){const e=vh(t);return e?[e]:[]}function vh(t){const e=t.trim();if(!e)return null;try{const n=JSON.parse(e);return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}const Xe=Object.freeze({COMMITTED:"committed",PARTIAL:"partial",FAILED:"failed",UNCONFIRMED:"unconfirmed"}),K_=12e4;function _h(t){return t?.unconfirmed===!0||t?.outcome===Xe.UNCONFIRMED?Xe.UNCONFIRMED:t?.partial===!0||t?.outcome===Xe.PARTIAL?Xe.PARTIAL:t?.success===!0?Xe.COMMITTED:Xe.FAILED}class mt extends Error{constructor(e){super(e),this.name="UnconfirmedDeployError",this.outcome=Xe.UNCONFIRMED}}function Y_({httpStatus:t}={}){return new mt(`Every FlutterFlow sync endpoint lost its response or ended in a server error${t?` (last: HTTP ${t})`:""} — neither can prove the push was refused, so it may already have been applied. Open the FlutterFlow project to reconcile before retrying.`)}async function J_(t,e={}){const{onPhase:n,onLog:i}=e;let r=null,s="";const o=l=>{if(l.event==="phase"){l.message&&n&&n(l.message);return}if(l.event==="log"){l.message&&i&&i(l.message);return}r=l};let a=null;try{if(t.body?.getReader){const l=t.body.getReader(),u=new TextDecoder;for(;;){const{done:c,value:d}=await l.read();if(c)break;const f=Du(s,u.decode(d,{stream:!0}));s=f.buffer,f.events.forEach(o)}}else{const l=Du("",await t.text());s=l.buffer,l.events.forEach(o)}}catch(l){a=l}return G_(s).forEach(o),r?{...r,success:r.success===!0||r.success===void 0&&t.ok,finalResultReceived:!0}:{success:!1,finalResultReceived:!1,httpRejected:!t.ok,httpStatus:t.status,error:a?"The connection to the FlutterFlow deploy runner dropped before it reported a result.":t.ok?"The FlutterFlow deploy runner closed the connection before it finished.":`FlutterFlow custom class provisioning failed (HTTP ${t.status}).`}}function Z_(t){return t?.finalResultReceived?_h(t):t?.httpRejected?Xe.FAILED:Xe.UNCONFIRMED}function X_(){let t=document.getElementById("fx-grid");if(!t)return null;const e=window.matchMedia("(prefers-reduced-motion: reduce)"),n=window.matchMedia("(pointer: none)");let i=t.getContext("webgl2",{alpha:!0,antialias:!1,depth:!1,stencil:!1,premultipliedAlpha:!0,powerPreference:"low-power"}),r=i?null:t.getContext("2d");if(!i&&!r)return null;const s='',o=`#version 300 es in vec2 p; void main(){ gl_Position = vec4(p, 0.0, 1.0); }`;function a(){return["#version 300 es","precision highp float;","out vec4 o;","uniform vec2 res;","uniform vec2 design;","uniform vec2 mouse;","uniform float energy;","uniform float parallax;","uniform float t;","uniform vec3 ink;","uniform sampler2D mark;","uniform vec2 rot;","const float WARP_A = 0.0032;","void main(){"," vec2 px = gl_FragCoord.xy * (design / res);"," vec2 p = vec2(px.x, design.y - px.y);"," vec2 off = vec2(0.0, -parallax) + vec2(sin(t * 0.11), cos(t * 0.09)) * 7.0;"," vec2 g = p + off;"," vec2 gm = mouse + off;"," float base = min(design.x, design.y);"," float spacing = clamp(base / 10.0, 64.0, 118.0);"," vec2 rel = g - gm;"," float rho = length(rel) + 1e-5;"," vec2 dir = rel / rho;"," vec2 pw = gm + dir * (rho + WARP_A * rho * rho);"," vec2 cell = floor(pw / spacing);"," vec2 cw = (cell + 0.5) * spacing - gm;"," float Rc = length(cw) + 1e-5;"," float rhoC = (-1.0 + sqrt(1.0 + 4.0 * WARP_A * Rc)) / (2.0 * WARP_A);"," vec2 c = gm + (cw / Rc) * rhoC;"," float cellSize = spacing / (1.0 + 2.0 * WARP_A * rhoC);"," float sigma = spacing * 2.9;"," float f = exp(-(rhoC * rhoC) / (2.0 * sigma * sigma));"," float scale = mix(0.32, 1.42, f);"," float weight = smoothstep(0.06, 0.80, f);"," float hs = cellSize * 0.26 * scale;"," vec2 uv = (g - c) / hs;"," vec2 ruv = mat2(rot.x, rot.y, -rot.y, rot.x) * uv;"," float cov = 0.0;"," if (abs(ruv.x) <= 1.0 && abs(ruv.y) <= 1.0) cov = texture(mark, ruv * 0.5 + 0.5).a;"," float s = cov * weight * energy * 0.26;"," o = vec4(ink * s, s);","}"].join(` -`)}let l=null,u,c,d,f,h,p,g,m,v;function S(Y,W){if(!i)return null;const D=i.createShader(Y);return i.shaderSource(D,W),i.compileShader(D),i.getShaderParameter(D,i.COMPILE_STATUS)?D:(window.console&&console.warn("fx-grid shader: "+i.getShaderInfoLog(D)),null)}if(i){const Y=S(i.VERTEX_SHADER,o),W=S(i.FRAGMENT_SHADER,a());if(Y&&W&&(l=i.createProgram(),i.attachShader(l,Y),i.attachShader(l,W),i.linkProgram(l),i.getProgramParameter(l,i.LINK_STATUS)||(window.console&&console.warn("fx-grid link: "+i.getProgramInfoLog(l)),l=null)),l){i.useProgram(l),i.bindBuffer(i.ARRAY_BUFFER,i.createBuffer()),i.bufferData(i.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),i.STATIC_DRAW);const D=i.getAttribLocation(l,"p");i.enableVertexAttribArray(D),i.vertexAttribPointer(D,2,i.FLOAT,!1,0,0),u=i.getUniformLocation(l,"res"),c=i.getUniformLocation(l,"design"),d=i.getUniformLocation(l,"mouse"),f=i.getUniformLocation(l,"energy"),h=i.getUniformLocation(l,"parallax"),p=i.getUniformLocation(l,"t"),g=i.getUniformLocation(l,"ink"),m=i.getUniformLocation(l,"mark"),v=i.getUniformLocation(l,"rot"),i.enable(i.BLEND),i.blendFunc(i.ONE,i.ONE_MINUS_SRC_ALPHA),i.clearColor(0,0,0,0)}else{i=null;const D=t.cloneNode(!1);if(t.parentNode.replaceChild(D,t),t=D,r=t.getContext("2d"),!r)return null}}function b(Y){if(!Y)return null;const W=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(Y);if(W){let D=W[1];return D.length===3&&(D=D[0]+D[0]+D[1]+D[1]+D[2]+D[2]),[parseInt(D.slice(0,2),16)/255,parseInt(D.slice(2,4),16)/255,parseInt(D.slice(4,6),16)/255]}try{const D=document.createElement("canvas");D.width=1,D.height=1;const ue=D.getContext("2d");ue.fillStyle="rgb(9, 8, 7)";const xe=String(ue.fillStyle);ue.fillStyle=Y;const Fe=String(ue.fillStyle);if(Fe===xe)return null;const ut=/^#([0-9a-f]{6})$/i.exec(Fe);if(ut){const dt=ut[1];return[parseInt(dt.slice(0,2),16)/255,parseInt(dt.slice(2,4),16)/255,parseInt(dt.slice(4,6),16)/255]}const Lt=/rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i.exec(Fe);if(Lt)return[Number(Lt[1])/255,Number(Lt[2])/255,Number(Lt[3])/255]}catch{}return null}function _(){let Y="";try{const W=getComputedStyle(document.documentElement);Y=(W.getPropertyValue("--fx-ink")||"").trim()||(W.getPropertyValue("--fg")||"").trim()}catch{}return b(Y)||[.56,.68,.88]}const x=_();let I=1920,T=1080,E=960,P=540,$=960,O=540,L=.66,N=0,K=-1e9,V=!1,M=0,R=0,Z=null,Ce=!1,oe=!1,ye=!1;const $e=64,ae=15.2;let Ie=0,Se=0;const Be=.0032,yt=0,ge=.56,Ye=.26,wt=.32,mn=.16,Re=.349;let Pe=yt;function Tt(){const Y=t.getBoundingClientRect(),W=t.clientWidth,D=t.clientHeight;if(!Y.width||!W||!D)return;const ue=Math.min(window.devicePixelRatio||1,2),xe=Math.max(.2,Math.min(2,Y.width/W*ue)),Fe=Math.max(2,Math.round(W*xe)),ut=Math.max(2,Math.round(D*xe));(Fe!==t.width||ut!==t.height)&&(t.width=Fe,t.height=ut,i&&i.viewport(0,0,Fe,ut)),I=W,T=D,V||(E=$=I/2,P=O=T/2,V=!0)}function Bn(Y){!l||!Ce||!i||(i.uniform2f(u,t.width,t.height),i.uniform2f(c,I,T),i.uniform2f(d,E,P),i.uniform1f(f,L),i.uniform1f(h,N),i.uniform2f(v,Math.cos(Pe),Math.sin(Pe)),i.uniform1f(p,Y),i.uniform3f(g,x[0],x[1],x[2]),i.clear(i.COLOR_BUFFER_BIT),i.drawArrays(i.TRIANGLES,0,3))}function qe(Y,W,D){const ue=Math.max(0,Math.min(1,(D-Y)/(W-Y)));return ue*ue*(3-2*ue)}function Dn(Y){if(!Z||!r)return;const W=r;W.setTransform(1,0,0,1,0,0),W.clearRect(0,0,t.width,t.height);const D=t.width/I;W.setTransform(D,0,0,D,0,0),W.globalAlpha=1;const ue=Math.min(I,T),xe=Math.max(64,Math.min(118,ue/10)),Fe=xe*2.9,ut=2*Fe*Fe,Lt=Math.sin(Y*.11)*7,dt=Math.cos(Y*.09)*7-N,dr=E+Lt,fr=P+dt,no=Fe*Math.sqrt(2*Math.log(1/.06)),mi=no+Be*no*no+xe,Ip=Math.floor((dr-mi)/xe)-1,kp=Math.ceil((dr+mi)/xe)+1,Cp=Math.floor((fr-mi)/xe)-1,Ap=Math.ceil((fr+mi)/xe)+1;for(let io=Cp;io<=Ap;io++){const Pp=(io+.5)*xe;for(let ro=Ip;ro<=kp;ro++){const so=(ro+.5)*xe-dr,oo=Pp-fr,ao=Math.sqrt(so*so+oo*oo)+1e-5;if(ao>mi)continue;const hr=(-1+Math.sqrt(1+4*Be*ao))/(2*Be),ac=Math.exp(-(hr*hr)/ut),lc=qe(.06,.8,ac)*L*.26;if(lc<.004)continue;const on=xe/(1+2*Be*hr)*.26*(.32+1.1*ac),cc=hr/ao,lo=dr+so*cc,co=fr+oo*cc;lo<-on*1.6||lo>I+on*1.6||co<-on*1.6||co>T+on*1.6||(W.globalAlpha=lc,W.save(),W.translate(lo,co),W.rotate(Pe),W.drawImage(Z,-on,-on,on*2,on*2),W.restore())}}W.globalAlpha=1}function $t(Y){if(!oe)return;const W=R?Math.min(.05,(Y-R)/1e3):.016;R=Y;const ue=Y-K>2400?.6:1;L+=(ue-L)*Math.min(1,W*3.2);const xe=Math.min(.05,W);Ie+=(($-E)*$e-Ie*ae)*xe,Se+=((O-P)*$e-Se*ae)*xe,E+=Ie*xe,P+=Se*xe,N=(window.scrollY||window.pageYOffset||0)*.55;const Fe=Y/1e3,ut=E/(I||1)-.5,Lt=P/(T||1)-.5;let dt=ut*(ut>=0?ge:Ye)+Lt*(Lt>=0?wt:mn);dt>Re?dt=Re:dt<-Re&&(dt=-Re),Pe=yt+dt-N*6e-4,Tt(),i?Bn(Fe):Dn(Fe),M=requestAnimationFrame($t)}function Mt(Y){if(!oe)return;const W=t.getBoundingClientRect();!W.width||!I||!T||($=(Y.clientX-W.left)/W.width*I,O=(Y.clientY-W.top)/W.height*T,K=performance.now())}function ct(){oe||to||e.matches||n.matches||!ye||document.hidden||(oe=!0,R=0,M=requestAnimationFrame($t))}function sn(){oe=!1,M&&(cancelAnimationFrame(M),M=0),R=0}function gi(){e.matches?(sn(),t.classList.remove("is-ready")):ye&&ct()}function jn(){n.matches?sn():ye&&ct()}function rc(){document.hidden?sn():ye&&ct()}const sc=new IntersectionObserver(Y=>{ye=Y[0]?.isIntersecting||!1,ye?ct():sn()},{threshold:0});sc.observe(t),window.addEventListener("pointermove",Mt,{passive:!0,capture:!0}),window.addEventListener("resize",Tt),e.addEventListener("change",gi),n.addEventListener("change",jn),document.addEventListener("visibilitychange",rc);function xp(){const Y=(s.match(/\sd="([^"]+)"/)||[])[1],W=document.createElement("canvas");W.width=256,W.height=256;const D=W.getContext("2d");if(Y&&window.Path2D){const ue=Math.min(8.533333333333333,8.421052631578947);D.setTransform(ue,0,0,ue,ue+(256-30*ue)/2,-6.4*ue),D.fillStyle="rgb(255,255,255)",D.fill(new Path2D(Y),"evenodd"),D.setTransform(1,0,0,1,0,0)}try{const ue=D.getImageData(0,0,256,256),xe=ue.data;for(let Fe=3;Feoe}}const Q_=120;function ey(t,e,n){return tn?n:t}function de(t,e,n){return ey((t-e)/(n-e),0,1)}function ty(t){return t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2}function Uo(t){return 1-Math.pow(1-t,3)}function ze(t,e){return e=e===void 0?1.7:e,1+(e+1)*Math.pow(t-1,3)+e*Math.pow(t-1,2)}function ju(t){return 1-Math.pow(2,-9*t)*Math.cos(t*15)}function te(t,e){if(t<=e[0].t)return e[0].v;for(let n=1;n8.2&&_<9.4&&(s*=1-.07*Math.sin(de(_,8.2,9.4)*Math.PI))}else if(t<53){const _=t-42;g=te(_,[{t:0,v:1},{t:2,v:0},{t:4.2,v:0},{t:4.6,v:1},{t:6.8,v:1},{t:7.4,v:0},{t:9.4,v:0},{t:10.6,v:1}]),p=te(_,[{t:0,v:1},{t:2,v:.3},{t:4.6,v:1,e:ze}]),d=te(_,[{t:0,v:0},{t:2,v:.3},{t:4.6,v:.16,e:ze},{t:10.6,v:0}]),h=te(_,[{t:0,v:0},{t:2,v:-40},{t:4.6,v:0,e:ze}]),o=te(_,[{t:0,v:0},{t:4.6,v:-.12},{t:10.6,v:0}])}else if(t<60){const _=t-53;c=te(_,[{t:0,v:1},{t:.35,v:0},{t:.45,v:0},{t:.7,v:1}]);const x=de(_,.45,2.2);a=x>0?-2.6*(1-ju(x)):0,g=te(_,[{t:0,v:1},{t:.57,v:0},{t:.67,v:0},{t:.92,v:1}]);const I=de(_,.67,2.42);f=I>0?-2.6*(1-ju(I)):0,s=1-.05*(Math.sin(de(_,1.9,2.5)*Math.PI)+Math.sin(de(_,2.5,3.1)*Math.PI))}else if(t<74){let x=function(P){return[te(P,[{t:0,v:0},{t:.25,v:1},{t:.5,v:1},{t:.72,v:.14},{t:.82,v:.14},{t:1,v:0}]),te(P,[{t:0,v:0},{t:.08,v:-.62},{t:.25,v:-.62},{t:.33,v:.62},{t:.7,v:.62},{t:.82,v:-.62},{t:1,v:-.62}])]};var b=x;const _=t-60,I=1-de(_,12,14),T=x(de(_,0,12)),E=x(de(_-.5,0,12));n=T[0]*I,i=(T[1]+.05*Math.sin(_*7))*I,o=(E[0]-T[0])*.6*I,a=(E[1]-T[1])*.6*I,h=(E[0]-T[0])*30*I,S=de(_,0,.4)*I}else if(t<85.4){const _=t-74,x=te(_,[{t:0,v:0},{t:4,v:1},{t:8,v:.24},{t:9.6,v:1,e:ze},{t:11.4,v:0}]);o=x*.5,d=-x*.5,l=te(_,[{t:0,v:0},{t:4,v:6},{t:8,v:20},{t:9.6,v:38,e:ze},{t:11.4,v:0}]),h=-l*.7,a=te(_,[{t:0,v:0},{t:8,v:0},{t:9.6,v:.4},{t:11.4,v:0}])}else if(t<96.4){const _=t-85.4,x=de(_,0,5.6),I=de(_,5.6,7.6),T=.72*Math.min(1,_/.6)*(1-I);d=Math.cos(x*Math.PI*2)*T,f=Math.sin(x*Math.PI*2)*T*.55,h=x*360*(1-I);const E=te(_,[{t:0,v:0},{t:7.6,v:0},{t:8.2,v:1,e:Uo},{t:8.6,v:.55},{t:9.4,v:0}]);o=-.16*E,d+=.16*E,l=-6*E,h+=6*E,s=1+.05*E,m=1+.9*E}else if(t<108.6){const _=t-96.4,x=de(_,9.6,12.2);n=te(_,[{t:0,v:0},{t:2.1,v:1},{t:4.8,v:.08},{t:7.5,v:1},{t:9.6,v:0}])*(1-x),i=-.35*Math.abs(Math.sin(de(_,0,9.6)*Math.PI*3))*(1-x);const I=Math.sin(_*6.2)*(1-x);u=1+.12*I,p=1-.12*I,l=I*8,h=-I*8,o=.06*I,d=-.06*I,S=de(_,0,.4)*(1-x)}else{const _=t-108.6,x=Math.sin(de(_,0,8)*Math.PI),I=1-de(_,8,11.4);s=1+.04*x*I,i=-.1*x*I,r=2*x*I,m=1+.5*Math.sin(de(_,0,6)*Math.PI),v=1+.1*Math.sin(de(_,0,6)*Math.PI)}return e.x=n,e.y=i,e.rot=r,e.scale=s,e.ax=o,e.ay=a,e.ar=l,e.asc=u,e.afade=c,e.bx=d,e.by=f,e.br=h,e.bsc=p,e.bfade=g,e.hfade=m,e.hsc=v,e.shd=S,e}function ny(t={}){const e=t.arena||document.querySelector(".pipeline-glyph.logo-loop");if(!e)return null;const n=e.querySelector(".loop-mark"),i=e.querySelector(".loop-piece-a"),r=e.querySelector(".loop-piece-b"),s=e.querySelector(".loop-halo"),o=e.querySelector(".loop-shadow");if(!n||!i||!r||!s||!o)return null;const a=t.reducedMotion||window.matchMedia("(prefers-reduced-motion: reduce)"),l=Q_;let u=34,c=0,d=0;function f(){u=n.offsetWidth||34,c=Math.max(0,e.offsetWidth-u-4),d=Math.max(0,(e.offsetHeight-u)/2-2),e.style.setProperty("--mark-c",u/2+"px")}function h(M){const R=Math.min(1,Math.max(0,M.x))*c,Z=M.y*d;n.style.transform="translate3d("+R.toFixed(2)+"px,"+Z.toFixed(2)+"px,0) rotate("+M.rot.toFixed(2)+"deg) scale("+M.scale.toFixed(3)+")",i.style.transform="translate3d("+(M.ax*u).toFixed(2)+"px,"+(M.ay*u).toFixed(2)+"px,0) rotate("+M.ar.toFixed(2)+"deg) scale("+M.asc.toFixed(3)+")",i.style.opacity=M.afade.toFixed(3),r.style.transform="translate3d("+(M.bx*u).toFixed(2)+"px,"+(M.by*u).toFixed(2)+"px,0) rotate("+M.br.toFixed(2)+"deg) scale("+M.bsc.toFixed(3)+")",r.style.opacity=M.bfade.toFixed(3),s.style.transform="scale("+M.hsc.toFixed(3)+")",s.style.opacity=(.09*M.hfade).toFixed(3),o.style.transform="translateX("+R.toFixed(2)+"px) scaleX("+(.75+.4*Math.abs(M.x)).toFixed(3)+")",o.style.opacity=(M.shd*.5).toFixed(3)}let p=0,g=0,m=0,v=!1,S=!1,b=!1,_=0;function x(){return b||a.matches||document.hidden||!e.offsetParent?!1:S}function I(M){if(!v)return;if(m=requestAnimationFrame(I),!x()){E();return}const R=g?(M-g)/1e3:0;g=M,p=(p+Math.min(R,.1))%l,_+=1,h(Ai(p))}function T(){v||b||x()&&(v=!0,g=0,m=requestAnimationFrame(I))}function E(){v=!1,m&&(cancelAnimationFrame(m),m=0),g=0}function P(){x()?T():E()}function $(){a.matches?(E(),h(Ai(0))):P()}function O(){f(),v&&h(Ai(p))}function L(){g=0,P()}const N=new IntersectionObserver(M=>{S=M[0]?M[0].isIntersecting:!1,P()},{threshold:0});N.observe(e),window.addEventListener("resize",O),a.addEventListener("change",$),document.addEventListener("visibilitychange",L);function K(){b||(b=!0,E(),N.disconnect(),window.removeEventListener("resize",O),a.removeEventListener("change",$),document.removeEventListener("visibilitychange",L))}window.addEventListener("pagehide",K);function V(M){p=(M%l+l)%l,h(Ai(p))}return f(),h(Ai(0)),P(),{isRunning:()=>v,currentTime:()=>p,frameCount:()=>_,seek:V,dispose:K}}const iy=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function Xt(t){const e=String(t||"").trim().match(iy);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function ry(t,e){if(t.length===0&&e.length===0)return 0;if(t.length===0)return 1;if(e.length===0)return-1;for(let n=0;n0)}function oy(t){const e=Xt(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function Il(t){let e=String(t??"").trim();if((e.startsWith("'")||e.startsWith('"'))&&(e=e.slice(1,-1).trim()),e===""||e==="any"||e==="*")return{min:null,minInclusive:!1,max:null,maxInclusive:!1};if(e.startsWith("^")){const o=e.slice(1).trim();return Xt(o)?{min:o,minInclusive:!0,max:oy(o),maxInclusive:!1}:null}if(Xt(e))return{min:e,minInclusive:!0,max:e,maxInclusive:!0};const n={min:null,minInclusive:!1,max:null,maxInclusive:!1},i=/(>=|<=|>|<)\s*([0-9][0-9A-Za-z.+-]*)/g;let r=!1,s;for(;(s=i.exec(e))!==null;){const[,o,a]=s;if(!Xt(a))return null;r=!0,o===">="||o===">"?(n.min=a,n.minInclusive=o===">="):(n.max=a,n.maxInclusive=o==="<=")}return r?n:null}function Uu(t,e){const n=Il(t);if(!n||!Xt(e))return!1;if(n.min!==null){const i=fs(e,n.min);if(i<0||i===0&&!n.minInclusive)return!1}if(n.max!==null){const i=fs(e,n.max);if(i>0||i===0&&!n.maxInclusive)return!1}return!0}function ay(t,e){const n=Il(t);if(!n||!Xt(e))return!1;if(n.max===null)return!0;const i=fs(n.max,e);return i>0?!0:i===0&&n.maxInclusive}function zn(t){const e=Il(t);return e?e.min:null}const ly="https://pub.dev/api/packages/",cy=8e3;function uy(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null}=e,r=Array.isArray(t?.versions)?t.versions:[];let s=null;for(const o of r){const a=o?.version;if(!a||o.retracted||sy(a))continue;const l=o.pubspec?.environment||{};n&&l.sdk&&!Uu(l.sdk,n)||i&&l.flutter&&!Uu(l.flutter,i)||(!s||fs(a,s)>0)&&(s=a)}return s?{version:s,constraint:`^${s}`}:null}async function dy(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null,fetchImpl:r=fetch}=e;let s;try{const a=await r(`${ly}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(cy)});if(!a.ok)return{name:t,constraint:null,version:null,error:a.status===404?`"${t}" was not found on pub.dev`:`pub.dev returned ${a.status} for "${t}"`};s=await a.json()}catch(a){return{name:t,constraint:null,version:null,error:`could not reach pub.dev for "${t}" (${a.message})`}}const o=uy(s,{dartSdkFloor:n,flutterSdkFloor:i});return o?{name:t,...o,error:null}:{name:t,constraint:null,version:null,error:n?`no published "${t}" release supports Dart ${n}`:`no published "${t}" release could be read`}}async function fy(t,e={}){const n=await Promise.all(t.map(i=>dy(i,e)));return new Map(n.map(({name:i,...r})=>[i,r]))}async function hy(t,e={},n={}){const{resolveVersions:i=fy}=n,r=Object.entries(e).filter(([c])=>c&&c!=="flutter"),s=ph(t),o={dartSdkFloor:zn(s.sdk),flutterSdkFloor:zn(s.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(r.length===0)return a;const l=$s(t),u=[];for(const[c,d]of r){const f=l.get(c);if(!f){u.push(c);continue}const h=zn(d);if(!h){a.kept.push({name:c,constraint:f.constraint});continue}if(!f.isScalar){a.warnings.push(`"${c}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${h}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:c,constraint:f.constraint});continue}if(ay(f.constraint,h)){a.kept.push({name:c,constraint:f.constraint});continue}a.overrides[c]=`^${h}`,a.warnings.push(`"${c}" was pinned to ${f.constraint} in your project, which cannot resolve the ${h} the generated code needs. Raising it to ^${h} — this changes a dependency the rest of your app also uses.`)}if(u.length>0){const c=await i(u,o);for(const d of u){const f=c.get(d);if(f?.constraint){a.additions[d]=f.constraint;continue}const h=e[d]||"";if(zn(h)){a.additions[d]=`^${zn(h)}`,a.warnings.push(`Could not confirm "${d}" version on pub.dev (${f?.error||"lookup failed"}). Using ^${zn(h)} from the AI's recommendation — verify this is current.`);continue}a.additions[d]=">=0.0.0",a.warnings.push(`Could not determine a version for "${d}" (${f?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const py={"&":"&","<":"<",">":">",'"':""","'":"'"};function Qt(t){return String(t??"").replace(/[&<>"']/g,e=>py[e])}function q(t){return t?Qt(t).replace(/\n/g,"
    "):""}function Jt(t){return Qt(t).replace(/\r?\n/g," ")}function Ms(t,e={}){const n=t?.pipelineStep;if(n!=null&&e[n]!=null)return e[n];const i=t?.message||"";return i.includes("Code Generator")?2:i.includes("Code Review")?3:1}function wh(t){if(!t)return{kind:"generic",title:"Generation failed",message:"An unknown error occurred. Please try again.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1};if(t.isModelArmor){const n=t.code==="MODEL_ARMOR_BLOCKED";return{kind:"safety",title:t.userTitle||"Request blocked for safety",message:t.userMessage||t.message,detail:t.retryExplanation||"",canRetry:!n,canEdit:!0,canUpgrade:!1}}if(t.isUsageLimit)return{kind:"quota",title:"Monthly limit reached",message:t.message||"You've used all your generations for this period.",detail:"",canRetry:!1,canEdit:!1,canUpgrade:!0};const e=t.message||"";return/timed out after/i.test(e)?{kind:"timeout",title:"Request timed out",message:"The generation service took too long to respond.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:/unreachable|failed to fetch|load failed|cors/i.test(e)?{kind:"network",title:"Connection problem",message:"We couldn't reach the generation service. Check your connection and try again.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:{kind:"generic",title:"Generation failed",message:e||"An unexpected error occurred.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1}}function gy(t){const e={"Integration Audit Report":"📋","Critical Issues":"❌",Warnings:"⚠️",Recommendations:"✅","Overall Score":"📊"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📄"}function my(t){const e={critical:"❌",warning:"⚠️",recommendation:"✅",score:"📊",issue:"🔍",fix:"🔧"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📝"}function vy(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 li(t){if(!t)return"";if(typeof t!="string")return String(t);const e=/```(?:\w+)?\n?([\s\S]*?)```/,n=t.match(e);return n?n[1].trim():t.trim()}function Hu(t){return t=Qt(t),t=t.replace(/\*\*(.*?)\*\*/g,'$1'),t=t.replace(/\*(.*?)\*/g,'$1'),t=t.replace(/`(.*?)`/g,'$1'),t=t.replace(/\b(FAIL|ERROR|CRITICAL)\b/g,'$1'),t=t.replace(/\b(WARN|WARNING)\b/g,'$1'),t=t.replace(/\b(PASS|SUCCESS|OK)\b/g,'$1'),t}function bh(t,e="dart",n=globalThis.hljs){if(!t)return"";const i=li(t);try{return n.highlight(i,{language:e}).value}catch(r){console.warn("Syntax highlighting failed:",r);try{return n.highlight(i,{language:"json"}).value}catch{return Qt(i)}}}function Ls(t,e={}){const{highlighter:n=globalThis.hljs}=e;let i='
    ';const r=String(t??"").split(` +`)}let l=null,u,c,d,f,h,p,g,m,v;function S(Y,W){if(!i)return null;const D=i.createShader(Y);return i.shaderSource(D,W),i.compileShader(D),i.getShaderParameter(D,i.COMPILE_STATUS)?D:(window.console&&console.warn("fx-grid shader: "+i.getShaderInfoLog(D)),null)}if(i){const Y=S(i.VERTEX_SHADER,o),W=S(i.FRAGMENT_SHADER,a());if(Y&&W&&(l=i.createProgram(),i.attachShader(l,Y),i.attachShader(l,W),i.linkProgram(l),i.getProgramParameter(l,i.LINK_STATUS)||(window.console&&console.warn("fx-grid link: "+i.getProgramInfoLog(l)),l=null)),l){i.useProgram(l),i.bindBuffer(i.ARRAY_BUFFER,i.createBuffer()),i.bufferData(i.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),i.STATIC_DRAW);const D=i.getAttribLocation(l,"p");i.enableVertexAttribArray(D),i.vertexAttribPointer(D,2,i.FLOAT,!1,0,0),u=i.getUniformLocation(l,"res"),c=i.getUniformLocation(l,"design"),d=i.getUniformLocation(l,"mouse"),f=i.getUniformLocation(l,"energy"),h=i.getUniformLocation(l,"parallax"),p=i.getUniformLocation(l,"t"),g=i.getUniformLocation(l,"ink"),m=i.getUniformLocation(l,"mark"),v=i.getUniformLocation(l,"rot"),i.enable(i.BLEND),i.blendFunc(i.ONE,i.ONE_MINUS_SRC_ALPHA),i.clearColor(0,0,0,0)}else{i=null;const D=t.cloneNode(!1);if(t.parentNode.replaceChild(D,t),t=D,r=t.getContext("2d"),!r)return null}}function b(Y){if(!Y)return null;const W=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(Y);if(W){let D=W[1];return D.length===3&&(D=D[0]+D[0]+D[1]+D[1]+D[2]+D[2]),[parseInt(D.slice(0,2),16)/255,parseInt(D.slice(2,4),16)/255,parseInt(D.slice(4,6),16)/255]}try{const D=document.createElement("canvas");D.width=1,D.height=1;const ue=D.getContext("2d");ue.fillStyle="rgb(9, 8, 7)";const xe=String(ue.fillStyle);ue.fillStyle=Y;const Fe=String(ue.fillStyle);if(Fe===xe)return null;const ut=/^#([0-9a-f]{6})$/i.exec(Fe);if(ut){const dt=ut[1];return[parseInt(dt.slice(0,2),16)/255,parseInt(dt.slice(2,4),16)/255,parseInt(dt.slice(4,6),16)/255]}const Nt=/rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i.exec(Fe);if(Nt)return[Number(Nt[1])/255,Number(Nt[2])/255,Number(Nt[3])/255]}catch{}return null}function _(){let Y="";try{const W=getComputedStyle(document.documentElement);Y=(W.getPropertyValue("--fx-ink")||"").trim()||(W.getPropertyValue("--fg")||"").trim()}catch{}return b(Y)||[.56,.68,.88]}const x=_();let I=1920,T=1080,E=960,P=540,$=960,O=540,L=.66,N=0,K=-1e9,V=!1,M=0,R=0,Z=null,Ce=!1,oe=!1,ye=!1;const $e=64,ae=15.2;let Ie=0,Se=0;const Be=.0032,wt=0,ge=.56,Ye=.26,bt=.32,mn=.16,Re=.349;let Pe=wt;function $t(){const Y=t.getBoundingClientRect(),W=t.clientWidth,D=t.clientHeight;if(!Y.width||!W||!D)return;const ue=Math.min(window.devicePixelRatio||1,2),xe=Math.max(.2,Math.min(2,Y.width/W*ue)),Fe=Math.max(2,Math.round(W*xe)),ut=Math.max(2,Math.round(D*xe));(Fe!==t.width||ut!==t.height)&&(t.width=Fe,t.height=ut,i&&i.viewport(0,0,Fe,ut)),I=W,T=D,V||(E=$=I/2,P=O=T/2,V=!0)}function Bn(Y){!l||!Ce||!i||(i.uniform2f(u,t.width,t.height),i.uniform2f(c,I,T),i.uniform2f(d,E,P),i.uniform1f(f,L),i.uniform1f(h,N),i.uniform2f(v,Math.cos(Pe),Math.sin(Pe)),i.uniform1f(p,Y),i.uniform3f(g,x[0],x[1],x[2]),i.clear(i.COLOR_BUFFER_BIT),i.drawArrays(i.TRIANGLES,0,3))}function qe(Y,W,D){const ue=Math.max(0,Math.min(1,(D-Y)/(W-Y)));return ue*ue*(3-2*ue)}function Dn(Y){if(!Z||!r)return;const W=r;W.setTransform(1,0,0,1,0,0),W.clearRect(0,0,t.width,t.height);const D=t.width/I;W.setTransform(D,0,0,D,0,0),W.globalAlpha=1;const ue=Math.min(I,T),xe=Math.max(64,Math.min(118,ue/10)),Fe=xe*2.9,ut=2*Fe*Fe,Nt=Math.sin(Y*.11)*7,dt=Math.cos(Y*.09)*7-N,dr=E+Nt,fr=P+dt,no=Fe*Math.sqrt(2*Math.log(1/.06)),mi=no+Be*no*no+xe,Ip=Math.floor((dr-mi)/xe)-1,kp=Math.ceil((dr+mi)/xe)+1,Cp=Math.floor((fr-mi)/xe)-1,Ap=Math.ceil((fr+mi)/xe)+1;for(let io=Cp;io<=Ap;io++){const Pp=(io+.5)*xe;for(let ro=Ip;ro<=kp;ro++){const so=(ro+.5)*xe-dr,oo=Pp-fr,ao=Math.sqrt(so*so+oo*oo)+1e-5;if(ao>mi)continue;const hr=(-1+Math.sqrt(1+4*Be*ao))/(2*Be),ac=Math.exp(-(hr*hr)/ut),lc=qe(.06,.8,ac)*L*.26;if(lc<.004)continue;const on=xe/(1+2*Be*hr)*.26*(.32+1.1*ac),cc=hr/ao,lo=dr+so*cc,co=fr+oo*cc;lo<-on*1.6||lo>I+on*1.6||co<-on*1.6||co>T+on*1.6||(W.globalAlpha=lc,W.save(),W.translate(lo,co),W.rotate(Pe),W.drawImage(Z,-on,-on,on*2,on*2),W.restore())}}W.globalAlpha=1}function Mt(Y){if(!oe)return;const W=R?Math.min(.05,(Y-R)/1e3):.016;R=Y;const ue=Y-K>2400?.6:1;L+=(ue-L)*Math.min(1,W*3.2);const xe=Math.min(.05,W);Ie+=(($-E)*$e-Ie*ae)*xe,Se+=((O-P)*$e-Se*ae)*xe,E+=Ie*xe,P+=Se*xe,N=(window.scrollY||window.pageYOffset||0)*.55;const Fe=Y/1e3,ut=E/(I||1)-.5,Nt=P/(T||1)-.5;let dt=ut*(ut>=0?ge:Ye)+Nt*(Nt>=0?bt:mn);dt>Re?dt=Re:dt<-Re&&(dt=-Re),Pe=wt+dt-N*6e-4,$t(),i?Bn(Fe):Dn(Fe),M=requestAnimationFrame(Mt)}function Lt(Y){if(!oe)return;const W=t.getBoundingClientRect();!W.width||!I||!T||($=(Y.clientX-W.left)/W.width*I,O=(Y.clientY-W.top)/W.height*T,K=performance.now())}function ct(){oe||to||e.matches||n.matches||!ye||document.hidden||(oe=!0,R=0,M=requestAnimationFrame(Mt))}function sn(){oe=!1,M&&(cancelAnimationFrame(M),M=0),R=0}function gi(){e.matches?(sn(),t.classList.remove("is-ready")):ye&&ct()}function jn(){n.matches?sn():ye&&ct()}function rc(){document.hidden?sn():ye&&ct()}const sc=new IntersectionObserver(Y=>{ye=Y[0]?.isIntersecting||!1,ye?ct():sn()},{threshold:0});sc.observe(t),window.addEventListener("pointermove",Lt,{passive:!0,capture:!0}),window.addEventListener("resize",$t),e.addEventListener("change",gi),n.addEventListener("change",jn),document.addEventListener("visibilitychange",rc);function xp(){const Y=(s.match(/\sd="([^"]+)"/)||[])[1],W=document.createElement("canvas");W.width=256,W.height=256;const D=W.getContext("2d");if(Y&&window.Path2D){const ue=Math.min(8.533333333333333,8.421052631578947);D.setTransform(ue,0,0,ue,ue+(256-30*ue)/2,-6.4*ue),D.fillStyle="rgb(255,255,255)",D.fill(new Path2D(Y),"evenodd"),D.setTransform(1,0,0,1,0,0)}try{const ue=D.getImageData(0,0,256,256),xe=ue.data;for(let Fe=3;Feoe}}const Q_=120;function ey(t,e,n){return tn?n:t}function de(t,e,n){return ey((t-e)/(n-e),0,1)}function ty(t){return t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2}function Uo(t){return 1-Math.pow(1-t,3)}function ze(t,e){return e=e===void 0?1.7:e,1+(e+1)*Math.pow(t-1,3)+e*Math.pow(t-1,2)}function ju(t){return 1-Math.pow(2,-9*t)*Math.cos(t*15)}function te(t,e){if(t<=e[0].t)return e[0].v;for(let n=1;n8.2&&_<9.4&&(s*=1-.07*Math.sin(de(_,8.2,9.4)*Math.PI))}else if(t<53){const _=t-42;g=te(_,[{t:0,v:1},{t:2,v:0},{t:4.2,v:0},{t:4.6,v:1},{t:6.8,v:1},{t:7.4,v:0},{t:9.4,v:0},{t:10.6,v:1}]),p=te(_,[{t:0,v:1},{t:2,v:.3},{t:4.6,v:1,e:ze}]),d=te(_,[{t:0,v:0},{t:2,v:.3},{t:4.6,v:.16,e:ze},{t:10.6,v:0}]),h=te(_,[{t:0,v:0},{t:2,v:-40},{t:4.6,v:0,e:ze}]),o=te(_,[{t:0,v:0},{t:4.6,v:-.12},{t:10.6,v:0}])}else if(t<60){const _=t-53;c=te(_,[{t:0,v:1},{t:.35,v:0},{t:.45,v:0},{t:.7,v:1}]);const x=de(_,.45,2.2);a=x>0?-2.6*(1-ju(x)):0,g=te(_,[{t:0,v:1},{t:.57,v:0},{t:.67,v:0},{t:.92,v:1}]);const I=de(_,.67,2.42);f=I>0?-2.6*(1-ju(I)):0,s=1-.05*(Math.sin(de(_,1.9,2.5)*Math.PI)+Math.sin(de(_,2.5,3.1)*Math.PI))}else if(t<74){let x=function(P){return[te(P,[{t:0,v:0},{t:.25,v:1},{t:.5,v:1},{t:.72,v:.14},{t:.82,v:.14},{t:1,v:0}]),te(P,[{t:0,v:0},{t:.08,v:-.62},{t:.25,v:-.62},{t:.33,v:.62},{t:.7,v:.62},{t:.82,v:-.62},{t:1,v:-.62}])]};var b=x;const _=t-60,I=1-de(_,12,14),T=x(de(_,0,12)),E=x(de(_-.5,0,12));n=T[0]*I,i=(T[1]+.05*Math.sin(_*7))*I,o=(E[0]-T[0])*.6*I,a=(E[1]-T[1])*.6*I,h=(E[0]-T[0])*30*I,S=de(_,0,.4)*I}else if(t<85.4){const _=t-74,x=te(_,[{t:0,v:0},{t:4,v:1},{t:8,v:.24},{t:9.6,v:1,e:ze},{t:11.4,v:0}]);o=x*.5,d=-x*.5,l=te(_,[{t:0,v:0},{t:4,v:6},{t:8,v:20},{t:9.6,v:38,e:ze},{t:11.4,v:0}]),h=-l*.7,a=te(_,[{t:0,v:0},{t:8,v:0},{t:9.6,v:.4},{t:11.4,v:0}])}else if(t<96.4){const _=t-85.4,x=de(_,0,5.6),I=de(_,5.6,7.6),T=.72*Math.min(1,_/.6)*(1-I);d=Math.cos(x*Math.PI*2)*T,f=Math.sin(x*Math.PI*2)*T*.55,h=x*360*(1-I);const E=te(_,[{t:0,v:0},{t:7.6,v:0},{t:8.2,v:1,e:Uo},{t:8.6,v:.55},{t:9.4,v:0}]);o=-.16*E,d+=.16*E,l=-6*E,h+=6*E,s=1+.05*E,m=1+.9*E}else if(t<108.6){const _=t-96.4,x=de(_,9.6,12.2);n=te(_,[{t:0,v:0},{t:2.1,v:1},{t:4.8,v:.08},{t:7.5,v:1},{t:9.6,v:0}])*(1-x),i=-.35*Math.abs(Math.sin(de(_,0,9.6)*Math.PI*3))*(1-x);const I=Math.sin(_*6.2)*(1-x);u=1+.12*I,p=1-.12*I,l=I*8,h=-I*8,o=.06*I,d=-.06*I,S=de(_,0,.4)*(1-x)}else{const _=t-108.6,x=Math.sin(de(_,0,8)*Math.PI),I=1-de(_,8,11.4);s=1+.04*x*I,i=-.1*x*I,r=2*x*I,m=1+.5*Math.sin(de(_,0,6)*Math.PI),v=1+.1*Math.sin(de(_,0,6)*Math.PI)}return e.x=n,e.y=i,e.rot=r,e.scale=s,e.ax=o,e.ay=a,e.ar=l,e.asc=u,e.afade=c,e.bx=d,e.by=f,e.br=h,e.bsc=p,e.bfade=g,e.hfade=m,e.hsc=v,e.shd=S,e}function ny(t={}){const e=t.arena||document.querySelector(".pipeline-glyph.logo-loop");if(!e)return null;const n=e.querySelector(".loop-mark"),i=e.querySelector(".loop-piece-a"),r=e.querySelector(".loop-piece-b"),s=e.querySelector(".loop-halo"),o=e.querySelector(".loop-shadow");if(!n||!i||!r||!s||!o)return null;const a=t.reducedMotion||window.matchMedia("(prefers-reduced-motion: reduce)"),l=Q_;let u=34,c=0,d=0;function f(){u=n.offsetWidth||34,c=Math.max(0,e.offsetWidth-u-4),d=Math.max(0,(e.offsetHeight-u)/2-2),e.style.setProperty("--mark-c",u/2+"px")}function h(M){const R=Math.min(1,Math.max(0,M.x))*c,Z=M.y*d;n.style.transform="translate3d("+R.toFixed(2)+"px,"+Z.toFixed(2)+"px,0) rotate("+M.rot.toFixed(2)+"deg) scale("+M.scale.toFixed(3)+")",i.style.transform="translate3d("+(M.ax*u).toFixed(2)+"px,"+(M.ay*u).toFixed(2)+"px,0) rotate("+M.ar.toFixed(2)+"deg) scale("+M.asc.toFixed(3)+")",i.style.opacity=M.afade.toFixed(3),r.style.transform="translate3d("+(M.bx*u).toFixed(2)+"px,"+(M.by*u).toFixed(2)+"px,0) rotate("+M.br.toFixed(2)+"deg) scale("+M.bsc.toFixed(3)+")",r.style.opacity=M.bfade.toFixed(3),s.style.transform="scale("+M.hsc.toFixed(3)+")",s.style.opacity=(.09*M.hfade).toFixed(3),o.style.transform="translateX("+R.toFixed(2)+"px) scaleX("+(.75+.4*Math.abs(M.x)).toFixed(3)+")",o.style.opacity=(M.shd*.5).toFixed(3)}let p=0,g=0,m=0,v=!1,S=!1,b=!1,_=0;function x(){return b||a.matches||document.hidden||!e.offsetParent?!1:S}function I(M){if(!v)return;if(m=requestAnimationFrame(I),!x()){E();return}const R=g?(M-g)/1e3:0;g=M,p=(p+Math.min(R,.1))%l,_+=1,h(Ai(p))}function T(){v||b||x()&&(v=!0,g=0,m=requestAnimationFrame(I))}function E(){v=!1,m&&(cancelAnimationFrame(m),m=0),g=0}function P(){x()?T():E()}function $(){a.matches?(E(),h(Ai(0))):P()}function O(){f(),v&&h(Ai(p))}function L(){g=0,P()}const N=new IntersectionObserver(M=>{S=M[0]?M[0].isIntersecting:!1,P()},{threshold:0});N.observe(e),window.addEventListener("resize",O),a.addEventListener("change",$),document.addEventListener("visibilitychange",L);function K(){b||(b=!0,E(),N.disconnect(),window.removeEventListener("resize",O),a.removeEventListener("change",$),document.removeEventListener("visibilitychange",L))}window.addEventListener("pagehide",K);function V(M){p=(M%l+l)%l,h(Ai(p))}return f(),h(Ai(0)),P(),{isRunning:()=>v,currentTime:()=>p,frameCount:()=>_,seek:V,dispose:K}}const iy=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function Xt(t){const e=String(t||"").trim().match(iy);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function ry(t,e){if(t.length===0&&e.length===0)return 0;if(t.length===0)return 1;if(e.length===0)return-1;for(let n=0;n0)}function oy(t){const e=Xt(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function Il(t){let e=String(t??"").trim();if((e.startsWith("'")||e.startsWith('"'))&&(e=e.slice(1,-1).trim()),e===""||e==="any"||e==="*")return{min:null,minInclusive:!1,max:null,maxInclusive:!1};if(e.startsWith("^")){const o=e.slice(1).trim();return Xt(o)?{min:o,minInclusive:!0,max:oy(o),maxInclusive:!1}:null}if(Xt(e))return{min:e,minInclusive:!0,max:e,maxInclusive:!0};const n={min:null,minInclusive:!1,max:null,maxInclusive:!1},i=/(>=|<=|>|<)\s*([0-9][0-9A-Za-z.+-]*)/g;let r=!1,s;for(;(s=i.exec(e))!==null;){const[,o,a]=s;if(!Xt(a))return null;r=!0,o===">="||o===">"?(n.min=a,n.minInclusive=o===">="):(n.max=a,n.maxInclusive=o==="<=")}return r?n:null}function Uu(t,e){const n=Il(t);if(!n||!Xt(e))return!1;if(n.min!==null){const i=fs(e,n.min);if(i<0||i===0&&!n.minInclusive)return!1}if(n.max!==null){const i=fs(e,n.max);if(i>0||i===0&&!n.maxInclusive)return!1}return!0}function ay(t,e){const n=Il(t);if(!n||!Xt(e))return!1;if(n.max===null)return!0;const i=fs(n.max,e);return i>0?!0:i===0&&n.maxInclusive}function zn(t){const e=Il(t);return e?e.min:null}const ly="https://pub.dev/api/packages/",cy=8e3;function uy(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null}=e,r=Array.isArray(t?.versions)?t.versions:[];let s=null;for(const o of r){const a=o?.version;if(!a||o.retracted||sy(a))continue;const l=o.pubspec?.environment||{};n&&l.sdk&&!Uu(l.sdk,n)||i&&l.flutter&&!Uu(l.flutter,i)||(!s||fs(a,s)>0)&&(s=a)}return s?{version:s,constraint:`^${s}`}:null}async function dy(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null,fetchImpl:r=fetch}=e;let s;try{const a=await r(`${ly}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(cy)});if(!a.ok)return{name:t,constraint:null,version:null,error:a.status===404?`"${t}" was not found on pub.dev`:`pub.dev returned ${a.status} for "${t}"`};s=await a.json()}catch(a){return{name:t,constraint:null,version:null,error:`could not reach pub.dev for "${t}" (${a.message})`}}const o=uy(s,{dartSdkFloor:n,flutterSdkFloor:i});return o?{name:t,...o,error:null}:{name:t,constraint:null,version:null,error:n?`no published "${t}" release supports Dart ${n}`:`no published "${t}" release could be read`}}async function fy(t,e={}){const n=await Promise.all(t.map(i=>dy(i,e)));return new Map(n.map(({name:i,...r})=>[i,r]))}async function hy(t,e={},n={}){const{resolveVersions:i=fy}=n,r=Object.entries(e).filter(([c])=>c&&c!=="flutter"),s=ph(t),o={dartSdkFloor:zn(s.sdk),flutterSdkFloor:zn(s.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(r.length===0)return a;const l=$s(t),u=[];for(const[c,d]of r){const f=l.get(c);if(!f){u.push(c);continue}const h=zn(d);if(!h){a.kept.push({name:c,constraint:f.constraint});continue}if(!f.isScalar){a.warnings.push(`"${c}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${h}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:c,constraint:f.constraint});continue}if(ay(f.constraint,h)){a.kept.push({name:c,constraint:f.constraint});continue}a.overrides[c]=`^${h}`,a.warnings.push(`"${c}" was pinned to ${f.constraint} in your project, which cannot resolve the ${h} the generated code needs. Raising it to ^${h} — this changes a dependency the rest of your app also uses.`)}if(u.length>0){const c=await i(u,o);for(const d of u){const f=c.get(d);if(f?.constraint){a.additions[d]=f.constraint;continue}const h=e[d]||"";if(zn(h)){a.additions[d]=`^${zn(h)}`,a.warnings.push(`Could not confirm "${d}" version on pub.dev (${f?.error||"lookup failed"}). Using ^${zn(h)} from the AI's recommendation — verify this is current.`);continue}a.additions[d]=">=0.0.0",a.warnings.push(`Could not determine a version for "${d}" (${f?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const py={"&":"&","<":"<",">":">",'"':""","'":"'"};function Qt(t){return String(t??"").replace(/[&<>"']/g,e=>py[e])}function q(t){return t?Qt(t).replace(/\n/g,"
    "):""}function Jt(t){return Qt(t).replace(/\r?\n/g," ")}function Ms(t,e={}){const n=t?.pipelineStep;if(n!=null&&e[n]!=null)return e[n];const i=t?.message||"";return i.includes("Code Generator")?2:i.includes("Code Review")?3:1}function wh(t){if(!t)return{kind:"generic",title:"Generation failed",message:"An unknown error occurred. Please try again.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1};if(t.isModelArmor){const n=t.code==="MODEL_ARMOR_BLOCKED";return{kind:"safety",title:t.userTitle||"Request blocked for safety",message:t.userMessage||t.message,detail:t.retryExplanation||"",canRetry:!n,canEdit:!0,canUpgrade:!1}}if(t.isUsageLimit)return{kind:"quota",title:"Monthly limit reached",message:t.message||"You've used all your generations for this period.",detail:"",canRetry:!1,canEdit:!1,canUpgrade:!0};const e=t.message||"";return/timed out after/i.test(e)?{kind:"timeout",title:"Request timed out",message:"The generation service took too long to respond.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:/unreachable|failed to fetch|load failed|cors/i.test(e)?{kind:"network",title:"Connection problem",message:"We couldn't reach the generation service. Check your connection and try again.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:{kind:"generic",title:"Generation failed",message:e||"An unexpected error occurred.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1}}function gy(t){const e={"Integration Audit Report":"📋","Critical Issues":"❌",Warnings:"⚠️",Recommendations:"✅","Overall Score":"📊"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📄"}function my(t){const e={critical:"❌",warning:"⚠️",recommendation:"✅",score:"📊",issue:"🔍",fix:"🔧"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📝"}function vy(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 li(t){if(!t)return"";if(typeof t!="string")return String(t);const e=/```(?:\w+)?\n?([\s\S]*?)```/,n=t.match(e);return n?n[1].trim():t.trim()}function Hu(t){return t=Qt(t),t=t.replace(/\*\*(.*?)\*\*/g,'$1'),t=t.replace(/\*(.*?)\*/g,'$1'),t=t.replace(/`(.*?)`/g,'$1'),t=t.replace(/\b(FAIL|ERROR|CRITICAL)\b/g,'$1'),t=t.replace(/\b(WARN|WARNING)\b/g,'$1'),t=t.replace(/\b(PASS|SUCCESS|OK)\b/g,'$1'),t}function bh(t,e="dart",n=globalThis.hljs){if(!t)return"";const i=li(t);try{return n.highlight(i,{language:e}).value}catch(r){console.warn("Syntax highlighting failed:",r);try{return n.highlight(i,{language:"json"}).value}catch{return Qt(i)}}}function Ls(t,e={}){const{highlighter:n=globalThis.hljs}=e;let i='
    ';const r=String(t??"").split(` `);let s=!1,o="";for(const a of r){if(a.startsWith("```")){if(s){const l=vy(o),u=bh(o.trim(),l,n);i+=`
    ${u}
    `,o="",s=!1}else s=!0;continue}if(s){o+=a+` @@ -78,13 +78,13 @@ in vec2 p; void main(){ gl_Position = vec4(p, 0.0, 1.0); }`;function a(){return[
    ${i}
    - `}const _y=[[/gradient stroke\s*$/i," and an animated percentage label"],[/gauge\s*$/i," with a gradient stroke and animated fill"],[/rating\s*(bar|widget)?\s*$/i," with half-star support and haptic feedback"],[/list\s*$/i," with swipe-to-delete and an undo snackbar"],[/pad\s*$/i," that exports a transparent PNG"],[/carousel\s*$/i," with parallax cards and page indicators"],[/(button|cta)\s*$/i," with a loading spinner and success state"],[/(chart|graph)\s*$/i," that animates from a Firestore stream"],[/action\s*(that|to)?\s*$/i," uploads an image to Firebase Storage and returns the URL"],[/timer\s*$/i," with pause, resume and a completion callback"],[/map\s*$/i," with clustered markers and a custom info window"],[/^a\s+\w*$/i," widget that"],[/(picker|selector)\s*$/i," with search and multi-select"]],yy=220,wy=6;function Wu(t,e){return!!(t&&t.trim())&&!e}function by(t,e=""){if(typeof t!="string"||!t||t===e||t.trim().lengthi.test(t));return n?n[1]:null}function Ey(){let t="",e="";return{get active(){return t},resolve(n){return t=by(n,e)??"",t},dismiss(){t=""},accept(n){if(!t)return null;const i=n+t;return e=i,t="",i}}}function Sy({onSubmit:t}){const e=document.getElementById("composer"),n=document.getElementById("pipeline-input"),i=document.getElementById("hero-send");if(!e||!n||!i||typeof t!="function")return;const r=e.querySelector(".ghost .typed"),s=e.querySelector(".ghost .suggest"),o=document.getElementById("tab-hint"),a=document.getElementById("suggest-status"),l=Array.from(document.querySelectorAll("#example-chips .chip")),u=document.getElementById("btn-add-images"),c=document.getElementById("prompt-image-input"),d=window.matchMedia("(prefers-reduced-motion: reduce)"),f=Ey();let h=!1,p=!1,g=!1,m=!1,v=null,S=null;function b(){i.disabled=!Wu(n.value,p||g||m)}function _(){r&&(r.textContent=n.value)}function x(){s&&(s.textContent=""),_(),e.classList.remove("has-suggest"),o&&(o.hidden=!0,o.tabIndex=-1),a&&(a.textContent="")}function I(R){s&&(s.textContent=R),_(),e.classList.add("has-suggest"),o&&(o.hidden=!1,o.tabIndex=0,o.setAttribute("aria-label","Accept suggestion: "+R.trim())),a&&(a.textContent="Suggestion: "+R+". Press Tab to accept.")}function T(){f.dismiss(),x()}function E(){if(h||p)return;const R=f.resolve(n.value);R&&I(R)}function P(){clearTimeout(v),!h&&(v=setTimeout(E,yy))}function $(){const R=f.accept(n.value);return R===null?!1:(n.value=R,x(),b(),!0)}function O(R){p=R,e.classList.toggle("is-busy",R),i.classList.toggle("is-busy",R),i.setAttribute("aria-label",R?"Generating":"Generate"),n.readOnly=R,l.forEach(Z=>{Z.disabled=R}),u&&(u.disabled=R),c&&(c.disabled=R),b()}async function L(){if(Wu(n.value,p||g||m)){T(),O(!0);try{await t()}finally{O(!1)}}}function N(){g=!1,S&&(clearInterval(S),S=null),e.classList.remove("is-demo-typing"),b()}function K(){l.forEach(R=>{R.classList.remove("is-active"),R.setAttribute("aria-pressed","false")})}function V(){try{n.focus({preventScroll:!0}),n.setSelectionRange(n.value.length,n.value.length)}catch{}}function M(R){const Z=R.dataset.prompt||"";if(N(),clearTimeout(v),v=null,T(),l.forEach(oe=>{const ye=oe===R;oe.classList.toggle("is-active",ye),oe.setAttribute("aria-pressed",String(ye))}),d.matches||!Z){n.value=Z,_(),b(),V();return}n.value="",_(),g=!0,b(),e.classList.add("is-demo-typing");let Ce=0;S=setInterval(()=>{Ce+=1,n.value=Z.slice(0,Ce),_(),Ce>=Z.length?(N(),V()):b()},22)}return l.forEach(R=>{R.setAttribute("aria-pressed","false"),R.addEventListener("click",()=>M(R))}),n.addEventListener("keydown",R=>{if(g&&R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!h){R.preventDefault();return}N(),R.key==="Tab"&&!R.shiftKey&&f.active?(R.preventDefault(),$()):R.key==="Escape"?(clearTimeout(v),v=null,T()):R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!h&&(R.preventDefault(),L())}),n.addEventListener("input",()=>{N(),K(),T(),b(),P()}),n.addEventListener("compositionstart",()=>{h=!0}),n.addEventListener("compositionend",()=>{h=!1,T(),b(),P()}),n.addEventListener("scroll",()=>{r&&r.parentNode&&(r.parentNode.scrollTop=n.scrollTop)}),o&&o.addEventListener("click",()=>{$(),n.focus({preventScroll:!0})}),i.addEventListener("click",L),n.addEventListener("pointerdown",()=>{N(),K()}),_(),b(),{setAttachmentsPending(R){m=!!R,b()}}}const xy="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses";const vt="https://4tgke4.buildship.run",Eh={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},hs="ccc_auth_session",Na="ccc_signin_return",Iy=1800*1e3,qu=new WeakSet;let z={email:null,sessionToken:null,isVerified:!1};function Mn(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let ce=Mn({isResolved:!0}),Oa=Promise.resolve();const ky=`${vt}/service/runpipeline`,Cy="bs_user_id",Ay="bs_identity_token",Py=`${vt}/authUserCheck`;let ft={userId:null,token:null,status:null,resolved:!1};const ps=sv,gs="ccc_subscription",zu=3,Fy=new Set(["active","trialing","paid"]),ms="google/gemini-3.7-flash",Nr=["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"],Ry={"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 Vt(t){return Ry[t]||t}const Ty=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 Sh(t){return Ty.has(t)}const Ba=4,Ho=8*1024*1024,$y="https://4tgke4.buildship.run/service/runpipeline-image";let Ne=[];const pn=[],My=3e4;let xh=null;function Ly(t){return new Promise(e=>{const n=new FileReader;n.onload=()=>e(n.result),n.onerror=()=>e(null),n.readAsDataURL(t)})}async function Ny(t,e){const n=new FormData;return n.append("file",t),(await fetch($y,{method:"POST",body:n,signal:e})).json()}function Oy(t){if(Array.isArray(t)){const e=t[0];if(e&&typeof e=="object")for(const n of Object.keys(e)){if(n==="item"||n==="index")continue;const i=e[n];if(i&&typeof i=="object"){if(typeof i.file=="string")return i.file;if(typeof i.url=="string")return i.url}if(typeof i=="string")return i}return""}return typeof t=="string"?t:t&&typeof t=="object"&&(t.url||t.fileUrl||t.file_url||t.downloadUrl||t.imageUrl||t.image_url||t.file)||""}async function By(t,e,n){const i=await Ly(t);i&&Ne.includes(e)&&(e.dataUrl=i,cn());let r="";if(i)try{r=Oy(await Ny(t,n))}catch{r=""}return Ne.includes(e)?!i||!r?(Ne.splice(Ne.indexOf(e),1),cn(),"failed"):(e.url=r,cn(),"added"):"dropped"}function Ih(t){const e=pn.indexOf(t);e>=0&&pn.splice(e,1),Ch()}function kh(t){t.controller.abort(),Ih(t);const e=Ne.indexOf(t.slot);e>=0&&(Ne.splice(e,1),cn())}function Ch(){xh?.setAttachmentsPending(pn.length>0)}async function Dy(t){const e=Array.from(t.target.files||[]);if(!e.length)return;if(t.target.value="",y.isRunning){Ee("Wait for the current generation to finish before attaching images.","info");return}const n=e.filter(u=>u.size>Ho);n.length&&Ee(`Skipped ${n.length} image(s) over the ${(Ho/1024/1024).toFixed(0)} MB limit.`,"warning");const i=e.filter(u=>u.size<=Ho);if(!i.length)return;const r=Ba-Ne.length,s=i.slice(0,r);if(i.length>r&&Ee(`You can attach up to ${Ba} images.`,"info"),!s.length)return;const o=s.map(u=>{const c={dataUrl:null,name:u.name,url:null};Ne.push(c);const d={slot:c,controller:new AbortController},f=setTimeout(()=>d.controller.abort(),My);return d.job=By(u,c,d.controller.signal),pn.push(d),d.job.finally(()=>{clearTimeout(f),Ih(d)}),d.job});cn(),Ch();const l=(await Promise.all(o)).filter(u=>u==="failed").length;l&&Ee(`${l} image(s) could not be uploaded and were not attached.`,"error")}function jy(t){const e=Ne[t],n=pn.find(i=>i.slot===e);if(n){kh(n);return}Ne.splice(t,1),cn()}function cn(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",Ne.forEach((n,i)=>{const r=document.createElement("div");r.className="prompt-img-thumb"+(n.url?"":" is-pending"),r.innerHTML=(n.dataUrl?`Prompt image`:"")+``,t.appendChild(r)}),e&&(e.textContent=Ne.length>=Ba?"Image limit reached":"Add images"))}function kl(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),n=Sh(e?.value);t.classList.toggle("hidden",!n),!n&&Ne.length&&(pn.slice().forEach(kh),Ne=[],cn())}const Fn="ccc_usage",Ah="google/gemini-3.7-flash",Ph="google/gemini-3.7-flash",kr="google/gemini-3.7-flash",Ni={professional:11,power:49},Da={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"},Or={AUD:1,USD:.65,EUR:.6,GBP:.52,CAD:.88,NZD:1.08,JPY:97,KRW:870,INR:54,SGD:.87,HKD:5.08,BRL:3.18,CNY:4.7,TWD:20.5,THB:22.5,VND:16200,IDR:10200,MYR:2.88,SEK:6.8,NOK:6.95,DKK:4.48,PLN:2.6,CZK:15.2,HUF:238,RON:2.98,TRY:20.9,AED:2.39,ILS:2.38,PHP:36.4,ZAR:11.8,RUB:58,UAH:26.8,CHF:.57,MXN:11.1,ARS:580,CLP:610,COP:2700,PEN:2.44};let Br={...Or};async function Uy(){const t=new AbortController,e=setTimeout(()=>t.abort(),5e3);try{const n=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:t.signal});if(!n.ok)return;const i=await n.json();if(i.result!=="success"||!i.rates)return;const r=i.rates,s={AUD:1},o=new Set([...Object.keys(Or),...Object.values(ja),...Object.values(Da)]);for(const a of o)a!=="AUD"&&(typeof r[a]=="number"&&r[a]>0?s[a]=r[a]:Or[a]&&(s[a]=Or[a]));Br=s}catch{}finally{clearTimeout(e)}}const ja={"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 Cl(){try{const s=Intl.DateTimeFormat().resolvedOptions().timeZone;if(s&&ja[s])return ja[s]}catch{}const e=(navigator.language||"en-US").replace("-","_"),n=Da[e];if(n)return n;const i=e.split("_")[0],r=Da[i];return r||"USD"}function Oi(t,e){const n=Br[e]??Br.USD,i=t*n,r=Math.round(i*100)/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:r>=100||r%1===0?0:2}).format(r)}catch{return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(t*Br.USD)}}const pt="ccc_api_key_",At="ccc_session_api_key_",Ft="ccc_encryption_key",tr="ccc_encryption_key_scope",Hy="ccc_keystore",vs="keys",nr="ccc_encryption_key_version";let Ua=null,_s=null,ir=!1,ys=!1,Vu=!1;class ws extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function Gu(){if(Vu)return;Vu=!0;const t="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(t),document.body&&Ee(t,"warning")}function Fh(){return localStorage.getItem(nr)||""}function Ha(){return crypto.randomUUID?.()||Th(crypto.getRandomValues(new Uint8Array(16)))}function Wy(){const t=Fh();if(t)return t;const e=Ha();return localStorage.setItem(nr,e),e}function ci(){Ua=null,_s=null,ir=!1,ys=!1}window.addEventListener("storage",t=>{t.key===nr&&ci()});function qy(){return new Promise((t,e)=>{const n=indexedDB.open(Hy,1);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(vs)||i.createObjectStore(vs)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function Al(t,e){const n=await qy();return new Promise((i,r)=>{const s=n.transaction(vs,t);let o;try{o=e(s.objectStore(vs))}catch(l){n.close(),r(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>r(o.error),s.oncomplete=()=>{n.close(),i(a)},s.onerror=()=>{n.close(),r(s.error||new Error("Encryption key transaction failed."))},s.onabort=()=>{n.close(),r(s.error||new Error("Encryption key transaction aborted."))}})}function zy(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function Vy(){const t=await Al("readonly",e=>e.get(Ft));return zy(t)?t:null}async function Rh(t){await Al("readwrite",e=>e.put(t,Ft))}async function Gy(){ci();try{await Al("readwrite",t=>t.delete(Ft))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function Ky(){const t=sessionStorage.getItem(Ft);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Rh(e),sessionStorage.removeItem(Ft),sessionStorage.removeItem(tr),localStorage.removeItem(pt+"salt"),e}async function Ku(t){const e=sessionStorage.getItem(Ft);if(e)return ys=sessionStorage.getItem(tr)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new ws;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),i=await crypto.subtle.exportKey("jwk",n);return sessionStorage.setItem(Ft,JSON.stringify(i)),sessionStorage.setItem(tr,"session"),ys=!1,crypto.subtle.importKey("jwk",i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function Yy(t){if(sessionStorage.getItem(tr)==="session"&&sessionStorage.getItem(Ft))return Gu(),ir=!0,Ku(t);try{const e=await Vy();if(e)return e;const n=await Ky();if(n)return n;const i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Rh(i),i}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),Gu(),ir=!0,Ku(t)}}async function Pl(t={}){const{allowSessionFallbackCreation:e=!0}=t,n=Wy();_s!==n&&ci();const i=Ua||Yy(e);Ua=i,_s=n;try{return await i}catch(r){throw ci(),r}}async function Jy(t){const e=await Pl(),n=_s,i=new TextEncoder,r=crypto.getRandomValues(new Uint8Array(12)),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},e,i.encode(t)),o=new Uint8Array(r.length+s.byteLength);return o.set(r),o.set(new Uint8Array(s),r.length),{ciphertext:Th(o),keyVersion:n,sessionFallback:ir}}async function Zy(t,e={}){const{isSessionCredential:n=!1}=e;try{const i=await Pl({allowSessionFallbackCreation:!1});if(ir&&!n&&!ys)throw new ws;const r=Xy(t),s=r.slice(0,12),o=r.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},i,o);return new TextDecoder().decode(a)}catch(i){if(i instanceof ws)throw i;return console.error("Decryption failed:",i),null}}function Th(t){const e=new Uint8Array(t);let n="";for(let i=0;i0}let Ln="",ui="",qi=null,Ju=0,tt="not-configured";async function Fl(){sessionStorage.getItem(Ft)&&await Pl(),Ln=await Te("flutterflow"),ui=await Te("flutterflow_project_id"),o0(),rn(),Ln?Ml():(tt="not-configured",mt())}let rr=!1;function $h(){const t=document.getElementById("api-keys-modal");He(t),$l(),Ln&&Ll(Ln)}function Rl(){rr=!1,$h()}function e0(){rr=!0;const t=document.getElementById("walkthrough-modal");t&&We(t),$h()}let Zu=!1;function Xu(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-settings-model");if(!t||!e)return;e.value=t.value;const n=Array.from(t.options);Array.from(e.options).forEach((r,s)=>{const o=n[s];o&&(r.textContent=o.textContent)});const i=document.getElementById("composer-settings-free-notice");i&&(document.getElementById("model-selector-free-notice")?(i.hidden=!1,i.innerHTML='Free plan — Gemini only. '):i.hidden=!0)}function Qu(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-image-capability"),n=document.getElementById("composer-image-capability-note");if(!t)return;const i=Vt(t.value),r=Sh(t.value);e&&(e.textContent=r?"Supported":"Not supported"),n&&(n.textContent=r?`${i} accepts reference images you attach to the prompt.`:`Images can't be attached with ${i}. Attached images are removed when you switch to it.`),kl()}function t0(){if(rr=!1,Xu(),Qu(),!Zu){const e=document.getElementById("composer-settings-model");e&&e.addEventListener("change",()=>{const n=document.getElementById("code-generator-model");n.value=e.value,n.dispatchEvent(new Event("change")),Xu(),Qu()}),Zu=!0}const t=document.querySelector('.composer [aria-label="Generation settings"]');He("composer-settings-modal",{trigger:t})}function n0(t){t&&t.target!==t.currentTarget||We("composer-settings-modal")}function Mh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&We(e);const n=rr;if(rr=!1,n){const i=document.getElementById("walkthrough-modal");i&&(tt==="connected"&&Tl(),He(i))}}let en=1;function Lh(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function Ns(){const t=Lh();t.length&&t.forEach((e,n)=>{const i=n+1;e.classList.remove("wt-current","wt-done","wt-pending");const r=e.querySelector(".wt-step-num");i===en?(e.classList.add("wt-current"),r&&(r.textContent=i)):i0&&en<=t&&(en++,Ns())}function i0(){const t=document.getElementById("walkthrough-modal");t&&(en=1,Ns(),He(t))}function r0(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&We(e);const n=document.getElementById("walkthrough-dont-show");n&&n.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function Nh(){if(z.isVerified&&Rt()&&ce.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(en=1,Ns(),He(e))}}async function $l(){const t=document.getElementById("flutterflow-api-key-input");Ln?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",s0()}function s0(){ed("flutterflow","flutterflow-key-status"),ed("flutterflow_project_id","flutterflow-project-status")}function ed(t,e){const n=document.getElementById(e);if(!n)return;const i=n.querySelector(".key-status-dot"),r=n.querySelector("span");kt(t)?(i.className="key-status-dot configured",r.className="text-green-600",r.textContent="User key configured"):(i.className="key-status-dot missing",r.className="text-gray-500",r.textContent="Not configured")}function rn(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff");e&&e.classList.toggle("hidden",!t)}function o0(){const t=document.getElementById("api-keys-status");if(!t)return;const e=t.querySelectorAll(".key-status-dot"),n=["flutterflow"];e.forEach((i,r)=>{const s=n[r];s==="flutterflow"?kt("flutterflow")&&kt("flutterflow_project_id")?(i.className="key-status-dot configured",i.title="FlutterFlow (Fully configured)"):kt("flutterflow")||kt("flutterflow_project_id")?(i.className="key-status-dot env",i.title="FlutterFlow (Partially configured)"):(i.className="key-status-dot missing",i.title="FlutterFlow (Not configured)"):kt(s)?(i.className="key-status-dot configured",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (User key)"):(i.className="key-status-dot missing",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (Not configured)")}),rn()}async function a0(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select"),n=t.value.trim();n&&await Yu("flutterflow",n);const i=e?.value.trim()||"";if(i){if(!Os(i)){Ee("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await Yu("flutterflow_project_id",i)}await Fl(),n&&await Ml(),$l();const r=document.querySelector("#api-keys-modal .bg-blue-500"),s=r.textContent;r.textContent="Saved!",r.classList.remove("bg-blue-500","hover:bg-blue-600"),r.classList.add("bg-green-500"),setTimeout(()=>{r.textContent=s,r.classList.remove("bg-green-500"),r.classList.add("bg-blue-500","hover:bg-blue-600"),Mh()},1e3)}async function l0(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(nr,Ha()),ci(),localStorage.removeItem(pt+"flutterflow"),localStorage.removeItem(pt+"flutterflow_project_id"),sessionStorage.removeItem(At+"flutterflow"),sessionStorage.removeItem(At+"flutterflow_project_id"),sessionStorage.removeItem(Ft),sessionStorage.removeItem(tr),localStorage.removeItem(pt+"salt"),await Gy(),localStorage.setItem(nr,Ha()),localStorage.removeItem(pt+"flutterflow"),localStorage.removeItem(pt+"flutterflow_project_id"),sessionStorage.removeItem(At+"flutterflow"),sessionStorage.removeItem(At+"flutterflow_project_id"),await Fl();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),$l()}function Os(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function mt(){const t=document.getElementById("acct-ff-dot"),e=document.getElementById("acct-ff-status"),n=document.getElementById("acct-ff-endpoint"),i=document.getElementById("acct-ff-project");if(n){const o=_t();n.textContent=o.includes("staging")?"Staging":"Production"}if(i&&(i.textContent=ui||"—"),!e)return;let r,s;if(!kt("flutterflow"))r="Not connected — add your FlutterFlow API key",s="";else switch(tt){case"connected":r="Connected to FlutterFlow",s="ok";break;case"no-projects":r="Key accepted — no projects found",s="warn";break;case"unauthorized":r="API key rejected (401/403) — re-enter your key",s="bad";break;case"network-error":r="Could not reach FlutterFlow — check your network",s="bad";break;default:r="Checking connection…",s="warn";break}e.textContent=r,t&&(t.className=`acct-dot${s?" "+s:""}`)}async function Ml(){const t=await Te("flutterflow");if(!t||!kt("flutterflow"))return tt="not-configured",mt(),null;tt="validating",mt();try{const n=await new hi(t,"","main",_t()).listProjects();return tt=n&&n.length>0?"connected":"no-projects",mt(),n}catch(e){const n=String(e&&e.message||"");return tt=/(401|403)|denied|unauthorized|scoped|list permission/i.test(n)?"unauthorized":"network-error",mt(),null}}function c0(){ui="",localStorage.removeItem(pt+"flutterflow_project_id"),sessionStorage.removeItem(At+"flutterflow_project_id")}function u0(){c0();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML='',t.value=""),kt("flutterflow")?(tt="validating",Ll(Ln)):tt="not-configured",mt()}function d0(t,e){const n=document.getElementById(t);n&&(n.value?e?n.style.borderColor="#22c55e":n.style.borderColor="#ef4444":n.style.borderColor="")}function f0(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const n=e.target.value.trim().length>0;d0("flutterflow-api-key-input",n)}),t.addEventListener("blur",h0(async e=>{const n=e.target.value.trim();n&&await Ll(n)},500)))}function h0(t,e){let n;return function(...r){const s=()=>{clearTimeout(n),t(...r)};clearTimeout(n),n=setTimeout(s,e)}}async function Ll(t){const e=document.getElementById("flutterflow-projects-select"),n=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',n&&n.classList.add("hidden"),(kt("flutterflow")||t)&&(tt="validating"),mt();try{const r=await new hi(t,"","main",_t()).listProjects();if(!r||r.length===0){tt="no-projects",mt(),e.innerHTML='';return}tt="connected",mt(),e.innerHTML='',r.forEach(s=>{const o=document.createElement("option");o.value=s.id||s.projectId||"",o.textContent=s.name||s.projectName||`Project ${s.id}`,e.appendChild(o)}),ui&&(e.value=ui)}catch(i){console.error("Failed to fetch projects:",i);const r=String(i&&i.message||"");tt=/(401|403)|denied|unauthorized|scoped|list permission/i.test(r)?"unauthorized":"network-error",mt(),e.innerHTML='',n&&(n.textContent=`Failed to load projects: ${i.message}`,n.classList.remove("hidden"))}}function p0(t){const e=document.getElementById(t),i=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",i.innerHTML=` + `}const _y=[[/gradient stroke\s*$/i," and an animated percentage label"],[/gauge\s*$/i," with a gradient stroke and animated fill"],[/rating\s*(bar|widget)?\s*$/i," with half-star support and haptic feedback"],[/list\s*$/i," with swipe-to-delete and an undo snackbar"],[/pad\s*$/i," that exports a transparent PNG"],[/carousel\s*$/i," with parallax cards and page indicators"],[/(button|cta)\s*$/i," with a loading spinner and success state"],[/(chart|graph)\s*$/i," that animates from a Firestore stream"],[/action\s*(that|to)?\s*$/i," uploads an image to Firebase Storage and returns the URL"],[/timer\s*$/i," with pause, resume and a completion callback"],[/map\s*$/i," with clustered markers and a custom info window"],[/^a\s+\w*$/i," widget that"],[/(picker|selector)\s*$/i," with search and multi-select"]],yy=220,wy=6;function Wu(t,e){return!!(t&&t.trim())&&!e}function by(t,e=""){if(typeof t!="string"||!t||t===e||t.trim().lengthi.test(t));return n?n[1]:null}function Ey(){let t="",e="";return{get active(){return t},resolve(n){return t=by(n,e)??"",t},dismiss(){t=""},accept(n){if(!t)return null;const i=n+t;return e=i,t="",i}}}function Sy({onSubmit:t}){const e=document.getElementById("composer"),n=document.getElementById("pipeline-input"),i=document.getElementById("hero-send");if(!e||!n||!i||typeof t!="function")return;const r=e.querySelector(".ghost .typed"),s=e.querySelector(".ghost .suggest"),o=document.getElementById("tab-hint"),a=document.getElementById("suggest-status"),l=Array.from(document.querySelectorAll("#example-chips .chip")),u=document.getElementById("btn-add-images"),c=document.getElementById("prompt-image-input"),d=window.matchMedia("(prefers-reduced-motion: reduce)"),f=Ey();let h=!1,p=!1,g=!1,m=!1,v=null,S=null;function b(){i.disabled=!Wu(n.value,p||g||m)}function _(){r&&(r.textContent=n.value)}function x(){s&&(s.textContent=""),_(),e.classList.remove("has-suggest"),o&&(o.hidden=!0,o.tabIndex=-1),a&&(a.textContent="")}function I(R){s&&(s.textContent=R),_(),e.classList.add("has-suggest"),o&&(o.hidden=!1,o.tabIndex=0,o.setAttribute("aria-label","Accept suggestion: "+R.trim())),a&&(a.textContent="Suggestion: "+R+". Press Tab to accept.")}function T(){f.dismiss(),x()}function E(){if(h||p)return;const R=f.resolve(n.value);R&&I(R)}function P(){clearTimeout(v),!h&&(v=setTimeout(E,yy))}function $(){const R=f.accept(n.value);return R===null?!1:(n.value=R,x(),b(),!0)}function O(R){p=R,e.classList.toggle("is-busy",R),i.classList.toggle("is-busy",R),i.setAttribute("aria-label",R?"Generating":"Generate"),n.readOnly=R,l.forEach(Z=>{Z.disabled=R}),u&&(u.disabled=R),c&&(c.disabled=R),b()}async function L(){if(Wu(n.value,p||g||m)){T(),O(!0);try{await t()}finally{O(!1)}}}function N(){g=!1,S&&(clearInterval(S),S=null),e.classList.remove("is-demo-typing"),b()}function K(){l.forEach(R=>{R.classList.remove("is-active"),R.setAttribute("aria-pressed","false")})}function V(){try{n.focus({preventScroll:!0}),n.setSelectionRange(n.value.length,n.value.length)}catch{}}function M(R){const Z=R.dataset.prompt||"";if(N(),clearTimeout(v),v=null,T(),l.forEach(oe=>{const ye=oe===R;oe.classList.toggle("is-active",ye),oe.setAttribute("aria-pressed",String(ye))}),d.matches||!Z){n.value=Z,_(),b(),V();return}n.value="",_(),g=!0,b(),e.classList.add("is-demo-typing");let Ce=0;S=setInterval(()=>{Ce+=1,n.value=Z.slice(0,Ce),_(),Ce>=Z.length?(N(),V()):b()},22)}return l.forEach(R=>{R.setAttribute("aria-pressed","false"),R.addEventListener("click",()=>M(R))}),n.addEventListener("keydown",R=>{if(g&&R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!h){R.preventDefault();return}N(),R.key==="Tab"&&!R.shiftKey&&f.active?(R.preventDefault(),$()):R.key==="Escape"?(clearTimeout(v),v=null,T()):R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!h&&(R.preventDefault(),L())}),n.addEventListener("input",()=>{N(),K(),T(),b(),P()}),n.addEventListener("compositionstart",()=>{h=!0}),n.addEventListener("compositionend",()=>{h=!1,T(),b(),P()}),n.addEventListener("scroll",()=>{r&&r.parentNode&&(r.parentNode.scrollTop=n.scrollTop)}),o&&o.addEventListener("click",()=>{$(),n.focus({preventScroll:!0})}),i.addEventListener("click",L),n.addEventListener("pointerdown",()=>{N(),K()}),_(),b(),{setAttachmentsPending(R){m=!!R,b()}}}const xy="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses";const _t="https://4tgke4.buildship.run",Eh={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},hs="ccc_auth_session",Na="ccc_signin_return",Iy=1800*1e3,qu=new WeakSet;let z={email:null,sessionToken:null,isVerified:!1};function Mn(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let ce=Mn({isResolved:!0}),Oa=Promise.resolve();const ky=`${_t}/service/runpipeline`,Cy="bs_user_id",Ay="bs_identity_token",Py=`${_t}/authUserCheck`;let ft={userId:null,token:null,status:null,resolved:!1};const ps=sv,gs="ccc_subscription",zu=3,Fy=new Set(["active","trialing","paid"]),ms="google/gemini-3.7-flash",Nr=["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"],Ry={"google/gemini-3.7-flash":"Gemini 3.7 Flash","anthropic/claude-opus-5":"Claude Opus 5","openai/gpt-5.6-sol":"GPT-5.6 Sol","z-ai/glm-5.2":"GLM 5.2","moonshotai/kimi-k3":"Kimi K3","openrouter/auto-beta":"OpenRouter: Auto Router","openrouter/free":"OpenRouter: Free Models","openrouter/deepseek/deepseek-v4-pro":"DeepSeek v4 Pro"};function Gt(t){return Ry[t]||t}const Ty=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 Sh(t){return Ty.has(t)}const Ba=4,Ho=8*1024*1024,$y="https://4tgke4.buildship.run/service/runpipeline-image";let Ne=[];const pn=[],My=3e4;let xh=null;function Ly(t){return new Promise(e=>{const n=new FileReader;n.onload=()=>e(n.result),n.onerror=()=>e(null),n.readAsDataURL(t)})}async function Ny(t,e){const n=new FormData;return n.append("file",t),(await fetch($y,{method:"POST",body:n,signal:e})).json()}function Oy(t){if(Array.isArray(t)){const e=t[0];if(e&&typeof e=="object")for(const n of Object.keys(e)){if(n==="item"||n==="index")continue;const i=e[n];if(i&&typeof i=="object"){if(typeof i.file=="string")return i.file;if(typeof i.url=="string")return i.url}if(typeof i=="string")return i}return""}return typeof t=="string"?t:t&&typeof t=="object"&&(t.url||t.fileUrl||t.file_url||t.downloadUrl||t.imageUrl||t.image_url||t.file)||""}async function By(t,e,n){const i=await Ly(t);i&&Ne.includes(e)&&(e.dataUrl=i,cn());let r="";if(i)try{r=Oy(await Ny(t,n))}catch{r=""}return Ne.includes(e)?!i||!r?(Ne.splice(Ne.indexOf(e),1),cn(),"failed"):(e.url=r,cn(),"added"):"dropped"}function Ih(t){const e=pn.indexOf(t);e>=0&&pn.splice(e,1),Ch()}function kh(t){t.controller.abort(),Ih(t);const e=Ne.indexOf(t.slot);e>=0&&(Ne.splice(e,1),cn())}function Ch(){xh?.setAttachmentsPending(pn.length>0)}async function Dy(t){const e=Array.from(t.target.files||[]);if(!e.length)return;if(t.target.value="",y.isRunning){Ee("Wait for the current generation to finish before attaching images.","info");return}const n=e.filter(u=>u.size>Ho);n.length&&Ee(`Skipped ${n.length} image(s) over the ${(Ho/1024/1024).toFixed(0)} MB limit.`,"warning");const i=e.filter(u=>u.size<=Ho);if(!i.length)return;const r=Ba-Ne.length,s=i.slice(0,r);if(i.length>r&&Ee(`You can attach up to ${Ba} images.`,"info"),!s.length)return;const o=s.map(u=>{const c={dataUrl:null,name:u.name,url:null};Ne.push(c);const d={slot:c,controller:new AbortController},f=setTimeout(()=>d.controller.abort(),My);return d.job=By(u,c,d.controller.signal),pn.push(d),d.job.finally(()=>{clearTimeout(f),Ih(d)}),d.job});cn(),Ch();const l=(await Promise.all(o)).filter(u=>u==="failed").length;l&&Ee(`${l} image(s) could not be uploaded and were not attached.`,"error")}function jy(t){const e=Ne[t],n=pn.find(i=>i.slot===e);if(n){kh(n);return}Ne.splice(t,1),cn()}function cn(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",Ne.forEach((n,i)=>{const r=document.createElement("div");r.className="prompt-img-thumb"+(n.url?"":" is-pending"),r.innerHTML=(n.dataUrl?`Prompt image`:"")+``,t.appendChild(r)}),e&&(e.textContent=Ne.length>=Ba?"Image limit reached":"Add images"))}function kl(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),n=Sh(e?.value);t.classList.toggle("hidden",!n),!n&&Ne.length&&(pn.slice().forEach(kh),Ne=[],cn())}const Fn="ccc_usage",Ah="google/gemini-3.7-flash",Ph="google/gemini-3.7-flash",kr="google/gemini-3.7-flash",Ni={professional:11,power:49},Da={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"},Or={AUD:1,USD:.65,EUR:.6,GBP:.52,CAD:.88,NZD:1.08,JPY:97,KRW:870,INR:54,SGD:.87,HKD:5.08,BRL:3.18,CNY:4.7,TWD:20.5,THB:22.5,VND:16200,IDR:10200,MYR:2.88,SEK:6.8,NOK:6.95,DKK:4.48,PLN:2.6,CZK:15.2,HUF:238,RON:2.98,TRY:20.9,AED:2.39,ILS:2.38,PHP:36.4,ZAR:11.8,RUB:58,UAH:26.8,CHF:.57,MXN:11.1,ARS:580,CLP:610,COP:2700,PEN:2.44};let Br={...Or};async function Uy(){const t=new AbortController,e=setTimeout(()=>t.abort(),5e3);try{const n=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:t.signal});if(!n.ok)return;const i=await n.json();if(i.result!=="success"||!i.rates)return;const r=i.rates,s={AUD:1},o=new Set([...Object.keys(Or),...Object.values(ja),...Object.values(Da)]);for(const a of o)a!=="AUD"&&(typeof r[a]=="number"&&r[a]>0?s[a]=r[a]:Or[a]&&(s[a]=Or[a]));Br=s}catch{}finally{clearTimeout(e)}}const ja={"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 Cl(){try{const s=Intl.DateTimeFormat().resolvedOptions().timeZone;if(s&&ja[s])return ja[s]}catch{}const e=(navigator.language||"en-US").replace("-","_"),n=Da[e];if(n)return n;const i=e.split("_")[0],r=Da[i];return r||"USD"}function Oi(t,e){const n=Br[e]??Br.USD,i=t*n,r=Math.round(i*100)/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:r>=100||r%1===0?0:2}).format(r)}catch{return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(t*Br.USD)}}const pt="ccc_api_key_",Pt="ccc_session_api_key_",Rt="ccc_encryption_key",tr="ccc_encryption_key_scope",Hy="ccc_keystore",vs="keys",nr="ccc_encryption_key_version";let Ua=null,_s=null,ir=!1,ys=!1,Vu=!1;class ws extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function Gu(){if(Vu)return;Vu=!0;const t="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(t),document.body&&Ee(t,"warning")}function Fh(){return localStorage.getItem(nr)||""}function Ha(){return crypto.randomUUID?.()||Th(crypto.getRandomValues(new Uint8Array(16)))}function Wy(){const t=Fh();if(t)return t;const e=Ha();return localStorage.setItem(nr,e),e}function ci(){Ua=null,_s=null,ir=!1,ys=!1}window.addEventListener("storage",t=>{t.key===nr&&ci()});function qy(){return new Promise((t,e)=>{const n=indexedDB.open(Hy,1);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(vs)||i.createObjectStore(vs)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function Al(t,e){const n=await qy();return new Promise((i,r)=>{const s=n.transaction(vs,t);let o;try{o=e(s.objectStore(vs))}catch(l){n.close(),r(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>r(o.error),s.oncomplete=()=>{n.close(),i(a)},s.onerror=()=>{n.close(),r(s.error||new Error("Encryption key transaction failed."))},s.onabort=()=>{n.close(),r(s.error||new Error("Encryption key transaction aborted."))}})}function zy(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function Vy(){const t=await Al("readonly",e=>e.get(Rt));return zy(t)?t:null}async function Rh(t){await Al("readwrite",e=>e.put(t,Rt))}async function Gy(){ci();try{await Al("readwrite",t=>t.delete(Rt))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function Ky(){const t=sessionStorage.getItem(Rt);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Rh(e),sessionStorage.removeItem(Rt),sessionStorage.removeItem(tr),localStorage.removeItem(pt+"salt"),e}async function Ku(t){const e=sessionStorage.getItem(Rt);if(e)return ys=sessionStorage.getItem(tr)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new ws;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),i=await crypto.subtle.exportKey("jwk",n);return sessionStorage.setItem(Rt,JSON.stringify(i)),sessionStorage.setItem(tr,"session"),ys=!1,crypto.subtle.importKey("jwk",i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function Yy(t){if(sessionStorage.getItem(tr)==="session"&&sessionStorage.getItem(Rt))return Gu(),ir=!0,Ku(t);try{const e=await Vy();if(e)return e;const n=await Ky();if(n)return n;const i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Rh(i),i}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),Gu(),ir=!0,Ku(t)}}async function Pl(t={}){const{allowSessionFallbackCreation:e=!0}=t,n=Wy();_s!==n&&ci();const i=Ua||Yy(e);Ua=i,_s=n;try{return await i}catch(r){throw ci(),r}}async function Jy(t){const e=await Pl(),n=_s,i=new TextEncoder,r=crypto.getRandomValues(new Uint8Array(12)),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},e,i.encode(t)),o=new Uint8Array(r.length+s.byteLength);return o.set(r),o.set(new Uint8Array(s),r.length),{ciphertext:Th(o),keyVersion:n,sessionFallback:ir}}async function Zy(t,e={}){const{isSessionCredential:n=!1}=e;try{const i=await Pl({allowSessionFallbackCreation:!1});if(ir&&!n&&!ys)throw new ws;const r=Xy(t),s=r.slice(0,12),o=r.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},i,o);return new TextDecoder().decode(a)}catch(i){if(i instanceof ws)throw i;return console.error("Decryption failed:",i),null}}function Th(t){const e=new Uint8Array(t);let n="";for(let i=0;i0}let Ln="",ui="",qi=null,Ju=0,tt="not-configured";async function Fl(){sessionStorage.getItem(Rt)&&await Pl(),Ln=await Te("flutterflow"),ui=await Te("flutterflow_project_id"),o0(),rn(),Ln?Ml():(tt="not-configured",vt())}let rr=!1;function $h(){const t=document.getElementById("api-keys-modal");He(t),$l(),Ln&&Ll(Ln)}function Rl(){rr=!1,$h()}function e0(){rr=!0;const t=document.getElementById("walkthrough-modal");t&&We(t),$h()}let Zu=!1;function Xu(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-settings-model");if(!t||!e)return;e.value=t.value;const n=Array.from(t.options);Array.from(e.options).forEach((r,s)=>{const o=n[s];o&&(r.textContent=o.textContent)});const i=document.getElementById("composer-settings-free-notice");i&&(document.getElementById("model-selector-free-notice")?(i.hidden=!1,i.innerHTML='Free plan — Gemini only. '):i.hidden=!0)}function Qu(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-image-capability"),n=document.getElementById("composer-image-capability-note");if(!t)return;const i=Gt(t.value),r=Sh(t.value);e&&(e.textContent=r?"Supported":"Not supported"),n&&(n.textContent=r?`${i} accepts reference images you attach to the prompt.`:`Images can't be attached with ${i}. Attached images are removed when you switch to it.`),kl()}function t0(){if(rr=!1,Xu(),Qu(),!Zu){const e=document.getElementById("composer-settings-model");e&&e.addEventListener("change",()=>{const n=document.getElementById("code-generator-model");n.value=e.value,n.dispatchEvent(new Event("change")),Xu(),Qu()}),Zu=!0}const t=document.querySelector('.composer [aria-label="Generation settings"]');He("composer-settings-modal",{trigger:t})}function n0(t){t&&t.target!==t.currentTarget||We("composer-settings-modal")}function Mh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&We(e);const n=rr;if(rr=!1,n){const i=document.getElementById("walkthrough-modal");i&&(tt==="connected"&&Tl(),He(i))}}let en=1;function Lh(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function Ns(){const t=Lh();t.length&&t.forEach((e,n)=>{const i=n+1;e.classList.remove("wt-current","wt-done","wt-pending");const r=e.querySelector(".wt-step-num");i===en?(e.classList.add("wt-current"),r&&(r.textContent=i)):i0&&en<=t&&(en++,Ns())}function i0(){const t=document.getElementById("walkthrough-modal");t&&(en=1,Ns(),He(t))}function r0(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&We(e);const n=document.getElementById("walkthrough-dont-show");n&&n.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function Nh(){if(z.isVerified&&Tt()&&ce.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(en=1,Ns(),He(e))}}async function $l(){const t=document.getElementById("flutterflow-api-key-input");Ln?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",s0()}function s0(){ed("flutterflow","flutterflow-key-status"),ed("flutterflow_project_id","flutterflow-project-status")}function ed(t,e){const n=document.getElementById(e);if(!n)return;const i=n.querySelector(".key-status-dot"),r=n.querySelector("span");Ct(t)?(i.className="key-status-dot configured",r.className="text-green-600",r.textContent="User key configured"):(i.className="key-status-dot missing",r.className="text-gray-500",r.textContent="Not configured")}function rn(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff");e&&e.classList.toggle("hidden",!t)}function o0(){const t=document.getElementById("api-keys-status");if(!t)return;const e=t.querySelectorAll(".key-status-dot"),n=["flutterflow"];e.forEach((i,r)=>{const s=n[r];s==="flutterflow"?Ct("flutterflow")&&Ct("flutterflow_project_id")?(i.className="key-status-dot configured",i.title="FlutterFlow (Fully configured)"):Ct("flutterflow")||Ct("flutterflow_project_id")?(i.className="key-status-dot env",i.title="FlutterFlow (Partially configured)"):(i.className="key-status-dot missing",i.title="FlutterFlow (Not configured)"):Ct(s)?(i.className="key-status-dot configured",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (User key)"):(i.className="key-status-dot missing",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (Not configured)")}),rn()}async function a0(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select"),n=t.value.trim();n&&await Yu("flutterflow",n);const i=e?.value.trim()||"";if(i){if(!Os(i)){Ee("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await Yu("flutterflow_project_id",i)}await Fl(),n&&await Ml(),$l();const r=document.querySelector("#api-keys-modal .bg-blue-500"),s=r.textContent;r.textContent="Saved!",r.classList.remove("bg-blue-500","hover:bg-blue-600"),r.classList.add("bg-green-500"),setTimeout(()=>{r.textContent=s,r.classList.remove("bg-green-500"),r.classList.add("bg-blue-500","hover:bg-blue-600"),Mh()},1e3)}async function l0(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(nr,Ha()),ci(),localStorage.removeItem(pt+"flutterflow"),localStorage.removeItem(pt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow"),sessionStorage.removeItem(Pt+"flutterflow_project_id"),sessionStorage.removeItem(Rt),sessionStorage.removeItem(tr),localStorage.removeItem(pt+"salt"),await Gy(),localStorage.setItem(nr,Ha()),localStorage.removeItem(pt+"flutterflow"),localStorage.removeItem(pt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow"),sessionStorage.removeItem(Pt+"flutterflow_project_id"),await Fl();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),$l()}function Os(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function vt(){const t=document.getElementById("acct-ff-dot"),e=document.getElementById("acct-ff-status"),n=document.getElementById("acct-ff-endpoint"),i=document.getElementById("acct-ff-project");if(n){const o=yt();n.textContent=o.includes("staging")?"Staging":"Production"}if(i&&(i.textContent=ui||"—"),!e)return;let r,s;if(!Ct("flutterflow"))r="Not connected — add your FlutterFlow API key",s="";else switch(tt){case"connected":r="Connected to FlutterFlow",s="ok";break;case"no-projects":r="Key accepted — no projects found",s="warn";break;case"unauthorized":r="API key rejected (401/403) — re-enter your key",s="bad";break;case"network-error":r="Could not reach FlutterFlow — check your network",s="bad";break;default:r="Checking connection…",s="warn";break}e.textContent=r,t&&(t.className=`acct-dot${s?" "+s:""}`)}async function Ml(){const t=await Te("flutterflow");if(!t||!Ct("flutterflow"))return tt="not-configured",vt(),null;tt="validating",vt();try{const n=await new hi(t,"","main",yt()).listProjects();return tt=n&&n.length>0?"connected":"no-projects",vt(),n}catch(e){const n=String(e&&e.message||"");return tt=/(401|403)|denied|unauthorized|scoped|list permission/i.test(n)?"unauthorized":"network-error",vt(),null}}function c0(){ui="",localStorage.removeItem(pt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow_project_id")}function u0(){c0();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML='',t.value=""),Ct("flutterflow")?(tt="validating",Ll(Ln)):tt="not-configured",vt()}function d0(t,e){const n=document.getElementById(t);n&&(n.value?e?n.style.borderColor="#22c55e":n.style.borderColor="#ef4444":n.style.borderColor="")}function f0(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const n=e.target.value.trim().length>0;d0("flutterflow-api-key-input",n)}),t.addEventListener("blur",h0(async e=>{const n=e.target.value.trim();n&&await Ll(n)},500)))}function h0(t,e){let n;return function(...r){const s=()=>{clearTimeout(n),t(...r)};clearTimeout(n),n=setTimeout(s,e)}}async function Ll(t){const e=document.getElementById("flutterflow-projects-select"),n=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',n&&n.classList.add("hidden"),(Ct("flutterflow")||t)&&(tt="validating"),vt();try{const r=await new hi(t,"","main",yt()).listProjects();if(!r||r.length===0){tt="no-projects",vt(),e.innerHTML='';return}tt="connected",vt(),e.innerHTML='',r.forEach(s=>{const o=document.createElement("option");o.value=s.id||s.projectId||"",o.textContent=s.name||s.projectName||`Project ${s.id}`,e.appendChild(o)}),ui&&(e.value=ui)}catch(i){console.error("Failed to fetch projects:",i);const r=String(i&&i.message||"");tt=/(401|403)|denied|unauthorized|scoped|list permission/i.test(r)?"unauthorized":"network-error",vt(),e.innerHTML='',n&&(n.textContent=`Failed to load projects: ${i.message}`,n.classList.remove("hidden"))}}function p0(t){const e=document.getElementById(t),i=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",i.innerHTML=` `):(e.type="password",i.innerHTML=` - `)}let y={step1Result:null,step2Result:null,step3Result:null,bundleSpec:null,artifactBundle:null,bundleReview:null,selectedArtifactId:null,resultsViewMode:"summary",currentStep:0,isRunning:!1,runId:0,submittedPrompt:"",submittedImages:[]};function g0(){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 m0(){y.bundleSpec=Qi(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function Bs(){const t=oi(y.bundleSpec);y.artifactBundle=Qi(y.step2Result,{id:y.bundleSpec?.id,title:y.bundleSpec?.title,description:y.bundleSpec?.description,artifactType:t.artifactType,artifactName:t.artifactName,fileName:t.fileName,dependencies:t.dependencies,relationships:y.bundleSpec?.relationships,code:y.step2Result||""});const e=jv(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(n=>n.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=oi(y.artifactBundle).id}function Ds(){const t=Qi(y.step3Result,{id:y.artifactBundle?.id,title:y.artifactBundle?.title}),e=new Map(t.artifacts.map(i=>[i.id,i.review])),n=new Map(t.artifacts.filter(i=>{const r=i.review;return r&&typeof r.fixedSource=="string"&&r.fixedSource.trim()}).map(i=>[i.id,i.review.fixedSource.trim()]));y.bundleReview=Qi({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(i=>{const r=n.get(i.id)||null;return{...i,review:e.get(i.id)||i.review||y.step3Result||null,...r?{fixedCode:r}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function Oh(){const t=Nl();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function Nl(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(n=>n.id===y.selectedArtifactId)||oi(t)}function Ol(){return Nl().code||y.step2Result||""}async function v0(){try{await Fl()}catch(t){return console.error("checkConnection: initializeApiKeys failed:",t),!1}return!0}const Dr={production:"https://api.flutterflow.io/v2/",staging:"https://api.flutterflow.io/v2-staging/"};function _0(t,e){const n=e?.trim()?` (${e.trim().slice(0,200)})`:"";return t===401?`Your FlutterFlow API key was rejected (401 Unauthorized)${n}. Re-enter a current key under API Keys settings, then try again.`:`Listing FlutterFlow projects was denied (403)${n}. The key may be scoped to sync a single project without list permission - verify the key's access in FlutterFlow, re-enter it under API Keys settings, then retry.`}class hi{constructor(e,n,i="main",r=Dr.production){this.apiKey=e,this.baseUrl=r,this._projectId=n,this._branchName=i,this._endpoint=r}get projectId(){return this._projectId}get branchName(){return this._branchName==="main"?"":this._branchName}async exportProjectZip(){console.log(`Exporting code from FlutterFlow project: ${this.projectId}, branch: ${this.branchName||"main"}`);const e=[{project:{path:`projects/${this.projectId}`},...this.branchName?{branch_name:this.branchName}:{},export_as_module:!1,include_assets_map:!1,format:!1,export_as_debug:!1},{project_id:this.projectId,branch_name:this.branchName,include_assets:!1,export_as_module:!1}];let n=null;for(const i of e)try{const r=await fetch(`${this.baseUrl}exportCode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(i)});if(!r.ok){const a=await r.text();n=new Error(`Export failed: ${r.status} - ${a}`);continue}const s=await r.json(),o=s?.value?.project_zip||s?.project_zip;if(!o){n=new Error("Export response did not include project source.");continue}return o}catch(r){n=r}throw n||new Error("Export failed for an unknown reason.")}async fetchProjectSource(){const e=await this.exportProjectZip(),n=await JSZip.loadAsync(e,{base64:!0}),i=Object.keys(n.files).filter(a=>!n.files[a].dir&&(a==="pubspec.yaml"||a.endsWith("/pubspec.yaml"))).sort((a,l)=>a.split("/").length-l.split("/").length)[0];if(!i)throw new Error("Export did not contain a pubspec.yaml.");const r=i.slice(0,i.length-12),s=new Map,o=Object.keys(n.files).filter(a=>{if(n.files[a].dir||!a.startsWith(r))return!1;const l=a.slice(r.length);return l==="lib/flutter_flow/custom_functions.dart"||l.startsWith("lib/custom_code/")&&l.endsWith(".dart")});return await Promise.all(o.map(async a=>{s.set(a.slice(r.length),await n.files[a].async("string"))})),{pubspecYaml:await n.files[i].async("string"),files:s}}async pushCodeWithRetry(e,n=3){const i=[Dr.production,Dr.staging],r=Math.max(0,i.indexOf(this._endpoint));let s=!1,o=null;for(let a=0;asetTimeout(h,1e3*(a+1)));continue}if(c.ok)return console.log(`Push to ${u} succeeded!`),c;o=c.status;let d;try{d=await c.clone().text()}catch{d="(unreadable response body)"}if(console.log(`Push to ${u} returned ${c.status}: ${d}`),c.status===500){console.warn(`Endpoint ${u} returned 500, trying next...`),await new Promise(f=>setTimeout(f,1e3*(a+1)));continue}return c}throw Y_({sawTransportError:s,httpStatus:o})}async pushCode(e){return this.pushCodeWithRetry(e)}parseProjectsResponse(e){if(e?.success&&typeof e.value=="string")try{const i=JSON.parse(e.value);if(i&&Array.isArray(i.entries))return i.entries.map(r=>({id:r.id,name:r.project?.name||r.id}))}catch(i){console.error("Failed to parse stringified project value:",i)}const n=e?.projects||e?.items||e?.entries||(Array.isArray(e)?e:[]);return Array.isArray(n)?n:[]}async listProjects(){console.log("Listing projects for API key");const e=[`${this.baseUrl}listProjects`,"https://api.flutterflow.io/v2/l/listProjects"];let n=0,i="";for(const r of e){const s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({project_type:"ALL",deserialize_response:!0})});if(s.ok)return r!==e[0]&&console.log(`listProjects answered on legacy path ${r}`),this.parseProjectsResponse(await s.json());if(n=s.status,i=await s.text(),console.warn(`listProjects via ${r} returned ${n}: ${i}`),s.status===401||s.status===403)throw new Error(_0(s.status,i));if(s.status!==404)throw new Error(`List projects failed: ${s.status} - ${i}`)}throw new Error(`List projects failed: ${n} - ${i}`)}}async function Bl(t){const e=t.clone();let n;try{n=await t.json()}catch{let s="";try{s=await e.text()}catch{}if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:s||`HTTP ${t.status}`,errorMap:new Map};throw new Yt(`FlutterFlow accepted the sync but returned an unreadable response${s?`: ${s.slice(0,200)}`:"."}`)}if(!t.ok){let r=n.message||`HTTP ${t.status}`,s=new Map;if(n.errors)s=new Map(Object.entries(n.errors));else if(!n.message&&typeof n=="object"){const o=Object.keys(n).filter(a=>a.endsWith(".dart")&&Array.isArray(n[a]));o.length>0&&(s=new Map(Object.entries(n)),r=o.flatMap(l=>n[l].map(u=>`${l}: ${u.errorMessage}`)).join(` -`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:r,errorMap:s}}let i={};if(n.value)try{i=typeof n.value=="string"?JSON.parse(n.value):n.value}catch(r){console.warn("Ignoring malformed push response value:",r)}return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(i))}}function Dl(t,e){return{401:"Authentication failed. Please check your FlutterFlow API key.",403:"Access denied. You may not have permission to modify this project.",404:"Project not found. Please check your Project ID.",409:"Conflict detected. The project may have been modified elsewhere.",422:"Validation failed: Invalid request format",429:"Rate limit exceeded. Please try again in a few minutes.",500:"FlutterFlow server error. Please try again later.",503:"FlutterFlow service temporarily unavailable."}[t]||`FlutterFlow API error: ${`HTTP ${t}`}`}const J={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},Bh=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,Dh=/extends\s+State<\w+>/;function y0(t,e=""){if(t==="pubspec.yaml")return J.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return J.OTHER;if(t==="custom_functions.dart")return J.FUNCTION;if(e){const n=Bh.test(e),i=Dh.test(e);if(n||i)return J.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return J.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return J.FUNCTION}return J.CODE_FILE}function jh(t,e){switch(e){case J.ACTION:return`lib/custom_code/actions/${t}`;case J.WIDGET:return`lib/custom_code/widgets/${t}`;case J.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case J.CODE_FILE:return`lib/custom_code/${t}`;case J.DEPENDENCIES:return"pubspec.yaml";case J.OTHER:return`lib/custom_code/${t}`;default:return t}}async function jl(t,e=new Map){return Ev(t,e)}const Wa=new Map;function Uh(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function sr(t){Wa.delete(Uh(t))}function w0(t,e,n){return new Promise((i,r)=>{let s=!1;const o=(l,u,c)=>{s||(s=!0,c==="resolve"?i(u):r(u))},a=setTimeout(()=>{s||(s=!0,n(i,r))},e);t.then(l=>{clearTimeout(a),o(i,l,"resolve")},l=>{clearTimeout(a),o(r,l,"reject")})})}async function Ul(t,e,n,i,r="",s=K_){const o=e_(e,n);if(o.length===0)return{remoteFiles:n,syncFileMap:e,unverified:[],approximate:[]};const a=V_(o,r),l={...a.manifest,sources:a.sources},u=a.skipped.map(h=>h.reason);u.forEach(h=>console.warn(`[custom class deploy] ${h}`));const c=a.approximate;c.forEach(h=>console.warn(`[custom class deploy] ${h}`)),console.log(`Provisioning ${o.length} new FlutterFlow custom code file(s) before sync.`),Oe.set("provision");let d=!0,f;try{if(f=await w0((async()=>{let h;try{h=await fetch(xy,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:i,customClasses:o,verification:l,stream:!0})})}catch{throw new Yt("The provisioning request did not return a response. The deploy may have reached the FlutterFlow server — open your FlutterFlow project to reconcile before retrying.")}return J_(h,{onPhase:p=>{d&&Oe.setSubstatus(p)},onLog:p=>{d&&console.log(`[custom class deploy] ${p}`)}})})(),s,(h,p)=>{d=!1,p(new Yt("The deploy is still working on the FlutterFlow server, but this browser tab has stopped waiting. Your custom classes may or may not have been written — the outcome is not yet known. Open your FlutterFlow project to reconcile before retrying the deploy."))}),!f.finalResultReceived)throw Z_(f)===Xe.FAILED?new Error(f.error||`FlutterFlow custom class provisioning failed (HTTP ${f.httpStatus}).`):new Yt("The connection to the FlutterFlow deploy runner dropped before it reported a result. The deploy may still be finishing on the server; open your FlutterFlow project to reconcile before retrying.")}catch(h){throw h instanceof Yt&&sr(t),h}if(!f.success){const h=f.details?` ${f.details}`:"";throw new Error(`${f.error||"FlutterFlow custom class provisioning failed."}${h}`)}return sr(t),f.verificationSkipped&&(console.warn(`[custom class deploy] ${f.verificationSkipped}`),u.push(f.verificationSkipped)),{remoteFiles:n,syncFileMap:t_(e,o),unverified:u,approximate:c,provisionSucceeded:!0}}async function Hl(t,e={}){const n=Uh(t);let i=Wa.get(n);if(i===void 0){try{i=await t.fetchProjectSource()}catch(l){throw new Error(`Could not read your project's pubspec.yaml (${l.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=mh(i.pubspecYaml);if(!a.valid)throw new Error(`Your project's pubspec.yaml could not be read reliably (${a.errors.join("; ")}). Deploy was stopped so your existing package dependencies aren't overwritten.`);Wa.set(n,i)}const r=await hy(i.pubspecYaml,e),s=U_(i.pubspecYaml,r.overrides),o=j_(s.yaml,r.additions);return r.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>`${a}: ${r.additions[a]||"any"}`).join(", "),r.sdk.dartSdkFloor?`(resolved for Dart ${r.sdk.dartSdkFloor})`:""),r.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:s.overridden,warnings:r.warnings,remoteFiles:i.files}}function b0(t){const e=[],n=[];t.content.length>5e4&&n.push("Code file is large (>50KB). This may take longer to commit."),t.content.length>1e5&&e.push("Code file is too large (>100KB). Consider splitting into smaller components.");const i=t.content.split(` + `)}let y={step1Result:null,step2Result:null,step3Result:null,bundleSpec:null,artifactBundle:null,bundleReview:null,selectedArtifactId:null,resultsViewMode:"summary",currentStep:0,isRunning:!1,runId:0,submittedPrompt:"",submittedImages:[]};function g0(){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 m0(){y.bundleSpec=Qi(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function Bs(){const t=oi(y.bundleSpec);y.artifactBundle=Qi(y.step2Result,{id:y.bundleSpec?.id,title:y.bundleSpec?.title,description:y.bundleSpec?.description,artifactType:t.artifactType,artifactName:t.artifactName,fileName:t.fileName,dependencies:t.dependencies,relationships:y.bundleSpec?.relationships,code:y.step2Result||""});const e=jv(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(n=>n.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=oi(y.artifactBundle).id}function Ds(){const t=Qi(y.step3Result,{id:y.artifactBundle?.id,title:y.artifactBundle?.title}),e=new Map(t.artifacts.map(i=>[i.id,i.review])),n=new Map(t.artifacts.filter(i=>{const r=i.review;return r&&typeof r.fixedSource=="string"&&r.fixedSource.trim()}).map(i=>[i.id,i.review.fixedSource.trim()]));y.bundleReview=Qi({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(i=>{const r=n.get(i.id)||null;return{...i,review:e.get(i.id)||i.review||y.step3Result||null,...r?{fixedCode:r}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function Oh(){const t=Nl();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function Nl(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(n=>n.id===y.selectedArtifactId)||oi(t)}function Ol(){return Nl().code||y.step2Result||""}async function v0(){try{await Fl()}catch(t){return console.error("checkConnection: initializeApiKeys failed:",t),!1}return!0}const Dr={production:"https://api.flutterflow.io/v2/",staging:"https://api.flutterflow.io/v2-staging/"};function _0(t,e){const n=e?.trim()?` (${e.trim().slice(0,200)})`:"";return t===401?`Your FlutterFlow API key was rejected (401 Unauthorized)${n}. Re-enter a current key under API Keys settings, then try again.`:`Listing FlutterFlow projects was denied (403)${n}. The key may be scoped to sync a single project without list permission - verify the key's access in FlutterFlow, re-enter it under API Keys settings, then retry.`}class hi{constructor(e,n,i="main",r=Dr.production){this.apiKey=e,this.baseUrl=r,this._projectId=n,this._branchName=i,this._endpoint=r}get projectId(){return this._projectId}get branchName(){return this._branchName==="main"?"":this._branchName}async exportProjectZip(){console.log(`Exporting code from FlutterFlow project: ${this.projectId}, branch: ${this.branchName||"main"}`);const e=[{project:{path:`projects/${this.projectId}`},...this.branchName?{branch_name:this.branchName}:{},export_as_module:!1,include_assets_map:!1,format:!1,export_as_debug:!1},{project_id:this.projectId,branch_name:this.branchName,include_assets:!1,export_as_module:!1}];let n=null;for(const i of e)try{const r=await fetch(`${this.baseUrl}exportCode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(i)});if(!r.ok){const a=await r.text();n=new Error(`Export failed: ${r.status} - ${a}`);continue}const s=await r.json(),o=s?.value?.project_zip||s?.project_zip;if(!o){n=new Error("Export response did not include project source.");continue}return o}catch(r){n=r}throw n||new Error("Export failed for an unknown reason.")}async fetchProjectSource(){const e=await this.exportProjectZip(),n=await JSZip.loadAsync(e,{base64:!0}),i=Object.keys(n.files).filter(a=>!n.files[a].dir&&(a==="pubspec.yaml"||a.endsWith("/pubspec.yaml"))).sort((a,l)=>a.split("/").length-l.split("/").length)[0];if(!i)throw new Error("Export did not contain a pubspec.yaml.");const r=i.slice(0,i.length-12),s=new Map,o=Object.keys(n.files).filter(a=>{if(n.files[a].dir||!a.startsWith(r))return!1;const l=a.slice(r.length);return l==="lib/flutter_flow/custom_functions.dart"||l.startsWith("lib/custom_code/")&&l.endsWith(".dart")});return await Promise.all(o.map(async a=>{s.set(a.slice(r.length),await n.files[a].async("string"))})),{pubspecYaml:await n.files[i].async("string"),files:s}}async pushCodeWithRetry(e,n=3){const i=[Dr.production,Dr.staging],r=Math.max(0,i.indexOf(this._endpoint));let s=!1,o=null;for(let a=0;asetTimeout(h,1e3*(a+1)));continue}if(c.ok)return console.log(`Push to ${u} succeeded!`),c;o=c.status;let d;try{d=await c.clone().text()}catch{d="(unreadable response body)"}if(console.log(`Push to ${u} returned ${c.status}: ${d}`),c.status>=500&&(s=!0),c.status===500){console.warn(`Endpoint ${u} returned 500, trying next...`),await new Promise(f=>setTimeout(f,1e3*(a+1)));continue}if(c.status>=500)throw new mt(`FlutterFlow reported a server error (HTTP ${c.status}), which cannot prove the push was refused — the write may have been applied before the failure. Open your FlutterFlow project to reconcile before retrying.`);if(s)throw new mt(`The push was refused (HTTP ${c.status}), but an earlier sync attempt may already have applied it — server errors and dropped responses cannot prove a refusal. Open your FlutterFlow project to reconcile before retrying.`);return c}throw Y_({httpStatus:o})}async pushCode(e){return this.pushCodeWithRetry(e)}parseProjectsResponse(e){if(e?.success&&typeof e.value=="string")try{const i=JSON.parse(e.value);if(i&&Array.isArray(i.entries))return i.entries.map(r=>({id:r.id,name:r.project?.name||r.id}))}catch(i){console.error("Failed to parse stringified project value:",i)}const n=e?.projects||e?.items||e?.entries||(Array.isArray(e)?e:[]);return Array.isArray(n)?n:[]}async listProjects(){console.log("Listing projects for API key");const e=[`${this.baseUrl}listProjects`,"https://api.flutterflow.io/v2/l/listProjects"];let n=0,i="";for(const r of e){const s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({project_type:"ALL",deserialize_response:!0})});if(s.ok)return r!==e[0]&&console.log(`listProjects answered on legacy path ${r}`),this.parseProjectsResponse(await s.json());if(n=s.status,i=await s.text(),console.warn(`listProjects via ${r} returned ${n}: ${i}`),s.status===401||s.status===403)throw new Error(_0(s.status,i));if(s.status!==404)throw new Error(`List projects failed: ${s.status} - ${i}`)}throw new Error(`List projects failed: ${n} - ${i}`)}}async function Bl(t){const e=t.clone();let n;try{n=await t.json()}catch{let s="";try{s=await e.text()}catch{}if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:s||`HTTP ${t.status}`,errorMap:new Map};throw new mt(`FlutterFlow accepted the sync but returned an unreadable response${s?`: ${s.slice(0,200)}`:"."}`)}if(!t.ok){let r=n.message||`HTTP ${t.status}`,s=new Map;if(n.errors)s=new Map(Object.entries(n.errors));else if(!n.message&&typeof n=="object"){const o=Object.keys(n).filter(a=>a.endsWith(".dart")&&Array.isArray(n[a]));o.length>0&&(s=new Map(Object.entries(n)),r=o.flatMap(l=>n[l].map(u=>`${l}: ${u.errorMessage}`)).join(` +`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:r,errorMap:s}}let i={};if(n.value)try{i=typeof n.value=="string"?JSON.parse(n.value):n.value}catch(r){console.warn("Ignoring malformed push response value:",r)}return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(i))}}function Dl(t,e){return{401:"Authentication failed. Please check your FlutterFlow API key.",403:"Access denied. You may not have permission to modify this project.",404:"Project not found. Please check your Project ID.",409:"Conflict detected. The project may have been modified elsewhere.",422:"Validation failed: Invalid request format",429:"Rate limit exceeded. Please try again in a few minutes.",500:"FlutterFlow server error. Please try again later.",503:"FlutterFlow service temporarily unavailable."}[t]||`FlutterFlow API error: ${`HTTP ${t}`}`}const J={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},Bh=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,Dh=/extends\s+State<\w+>/;function y0(t,e=""){if(t==="pubspec.yaml")return J.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return J.OTHER;if(t==="custom_functions.dart")return J.FUNCTION;if(e){const n=Bh.test(e),i=Dh.test(e);if(n||i)return J.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return J.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return J.FUNCTION}return J.CODE_FILE}function jh(t,e){switch(e){case J.ACTION:return`lib/custom_code/actions/${t}`;case J.WIDGET:return`lib/custom_code/widgets/${t}`;case J.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case J.CODE_FILE:return`lib/custom_code/${t}`;case J.DEPENDENCIES:return"pubspec.yaml";case J.OTHER:return`lib/custom_code/${t}`;default:return t}}async function jl(t,e=new Map){return Ev(t,e)}const Wa=new Map;function Uh(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function sr(t){Wa.delete(Uh(t))}function w0(t,e,n){return new Promise((i,r)=>{let s=!1;const o=(l,u,c)=>{s||(s=!0,c==="resolve"?i(u):r(u))},a=setTimeout(()=>{s||(s=!0,n(i,r))},e);t.then(l=>{clearTimeout(a),o(i,l,"resolve")},l=>{clearTimeout(a),o(r,l,"reject")})})}async function Ul(t,e,n,i,r="",s=K_){const o=e_(e,n);if(o.length===0)return{remoteFiles:n,syncFileMap:e,unverified:[],approximate:[]};const a=V_(o,r),l={...a.manifest,sources:a.sources},u=a.skipped.map(h=>h.reason);u.forEach(h=>console.warn(`[custom class deploy] ${h}`));const c=a.approximate;c.forEach(h=>console.warn(`[custom class deploy] ${h}`)),console.log(`Provisioning ${o.length} new FlutterFlow custom code file(s) before sync.`),Oe.set("provision");let d=!0,f;try{if(f=await w0((async()=>{let h;try{h=await fetch(xy,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:i,customClasses:o,verification:l,stream:!0})})}catch{throw new mt("The provisioning request did not return a response. The deploy may have reached the FlutterFlow server — open your FlutterFlow project to reconcile before retrying.")}return J_(h,{onPhase:p=>{d&&Oe.setSubstatus(p)},onLog:p=>{d&&console.log(`[custom class deploy] ${p}`)}})})(),s,(h,p)=>{d=!1,p(new mt("The deploy is still working on the FlutterFlow server, but this browser tab has stopped waiting. Your custom classes may or may not have been written — the outcome is not yet known. Open your FlutterFlow project to reconcile before retrying the deploy."))}),!f.finalResultReceived)throw Z_(f)===Xe.FAILED?new Error(f.error||`FlutterFlow custom class provisioning failed (HTTP ${f.httpStatus}).`):new mt("The connection to the FlutterFlow deploy runner dropped before it reported a result. The deploy may still be finishing on the server; open your FlutterFlow project to reconcile before retrying.")}catch(h){throw h instanceof mt&&sr(t),h}if(!f.success){const h=f.details?` ${f.details}`:"";throw new Error(`${f.error||"FlutterFlow custom class provisioning failed."}${h}`)}return sr(t),f.verificationSkipped&&(console.warn(`[custom class deploy] ${f.verificationSkipped}`),u.push(f.verificationSkipped)),{remoteFiles:n,syncFileMap:t_(e,o),unverified:u,approximate:c,provisionSucceeded:!0}}async function Hl(t,e={}){const n=Uh(t);let i=Wa.get(n);if(i===void 0){try{i=await t.fetchProjectSource()}catch(l){throw new Error(`Could not read your project's pubspec.yaml (${l.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=mh(i.pubspecYaml);if(!a.valid)throw new Error(`Your project's pubspec.yaml could not be read reliably (${a.errors.join("; ")}). Deploy was stopped so your existing package dependencies aren't overwritten.`);Wa.set(n,i)}const r=await hy(i.pubspecYaml,e),s=U_(i.pubspecYaml,r.overrides),o=j_(s.yaml,r.additions);return r.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>`${a}: ${r.additions[a]||"any"}`).join(", "),r.sdk.dartSdkFloor?`(resolved for Dart ${r.sdk.dartSdkFloor})`:""),r.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:s.overridden,warnings:r.warnings,remoteFiles:i.files}}function b0(t){const e=[],n=[];t.content.length>5e4&&n.push("Code file is large (>50KB). This may take longer to commit."),t.content.length>1e5&&e.push("Code file is too large (>100KB). Consider splitting into smaller components.");const i=t.content.split(` `).length;i>500&&n.push(`Code has ${i} lines. Consider breaking it into smaller widgets.`),t.content.includes("setState")&&t.codeType===J.ACTION&&n.push("Using setState in a Custom Action may not work as expected. Consider using a Custom Widget."),t.content.includes("dynamic")&&!t.content.includes("?")&&n.push('Code uses "dynamic" types. Consider adding explicit types for better null safety.'),t.content.match(/Color\(0xFF[0-9A-Fa-f]{6}\)/)&&n.push("Code contains hardcoded colors. Consider using FlutterFlowTheme.of(context) for theme consistency.");const r=t.content.match(/print\s*\(/g);r&&r.length>3&&n.push(`Code contains ${r.length} print statements. Consider removing debug prints before committing.`);const s=y_(t.content);if(s&&e.push(`FlutterFlow cannot format this code - ${s}. Fix or regenerate before committing.`),t.codeType===J.WIDGET){const o=ah(t.content),a=m_(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=`${lh(o[0])}`;e.push(`Widget class name "${o[0]}" does not match the file name "${t.fileName}". FlutterFlow derives the widget from the file name, so it will report "No widget ${a} found". Rename the file to "${l}" or the class to match before committing.`)}}return{canProceed:e.length===0,issues:e,warnings:n}}function Hh(t,e={}){const{artifactType:n="CustomWidget",artifactName:i="GeneratedCode",fileName:r}=e,s=p_(t);let o=r||i;if(n==="CustomFunction")o="custom_functions.dart";else if(n==="CustomWidget"){const u=ah(s)[0],c=u?lh(u):null;c&&o!==c?(console.warn(`Commit file name "${o}" does not match declared widget class "${u}"; renaming to "${c}" so FlutterFlow can find the widget.`),o=c):o.endsWith(".dart")||(o+=".dart")}else o.endsWith(".dart")||(o+=".dart");let a=J.CODE_FILE;switch(n){case"CustomAction":a=J.ACTION;break;case"CustomWidget":a=J.WIDGET;break;case"CustomFunction":a=J.FUNCTION;break;case"CustomClass":case"CodeFile":a=J.CODE_FILE;break}let l="";return a===J.WIDGET?l=`// Automatic FlutterFlow imports import '/flutter_flow/flutter_flow_theme.dart'; import '/flutter_flow/flutter_flow_util.dart'; @@ -111,15 +111,15 @@ import '/flutter_flow/lat_lng.dart'; import '/flutter_flow/place.dart'; import '/flutter_flow/uploaded_file.dart'; -`),{content:Wv(s,l),fileName:o,codeType:a,artifactType:n,artifactName:i}}function E0(t){const e={};for(const n of wl(t))e[n]="";return e}function S0(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 x0(t,e,n,i=new Set,r=""){const s=[],o=Bh.test(e),a=Dh.test(e);return n===J.WIDGET&&!o&&!a&&s.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:s.length===0,errors:s}}function js(t){const e=[],n=[];if(!t||t.size===0)return e.push("No files to commit"),{valid:!1,errors:e,warnings:n};const i=new Set(Array.from(t.values()).flatMap(r=>As(r.content||"")));for(const[r,s]of t.entries()){if((!s.content||s.content.trim().length===0)&&e.push(`File ${r} is empty`),s.content&&s.content.length>1e5&&n.push(`File ${r} is very large (>100KB)`),r.endsWith(".dart")){const o=x0(r,s.content,s.type,i,s.artifactName);o.valid||e.push(...o.errors.map(a=>`${r}: ${a}`))}if(r==="pubspec.yaml"){const o=mh(s.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:n}}const ee={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},G={currentState:ee.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=ee.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(ee).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===ee.PREPARING&&(this.startTime=Date.now()),(t===ee.SUCCESS||t===ee.ERROR)&&(this.endTime=Date.now()),typeof window<"u"&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("commitStateChange",{detail:{state:t,commitState:this}})),console.log(`Commit state changed to: ${t}`)},setError(t){this.error=t,this.setState(ee.ERROR)},setSuccess(t){this.result=t,this.setState(ee.SUCCESS)},setProgress(t,e){this.filesProcessed=t,this.totalFiles=e},getElapsedTime(){return this.startTime?(this.endTime||Date.now())-this.startTime:null},isInProgress(){return this.currentState===ee.PREPARING||this.currentState===ee.VALIDATING||this.currentState===ee.PUSHING}};async function I0(t,e,n={}){let{codeType:i="W"}=n;const{pubspecDeps:r={},artifactName:s=e}=n;i==="CustomWidget"&&(i=J.WIDGET),i==="CustomAction"&&(i=J.ACTION),i==="CustomFunction"&&(i=J.FUNCTION),i==="CustomClass"&&(i=J.CODE_FILE),i==="CodeFile"&&(i=J.CODE_FILE),G.reset(),G.setState(ee.PREPARING);try{const o=await Te("flutterflow"),a=await Te("flutterflow_project_id");if(!o||!a)throw new Error("FlutterFlow credentials not configured. Please set your API key and Project ID in the API Keys settings.");if(!Os(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=_t(),u=new hi(o,a,"main",l);G.setState(ee.VALIDATING);const c=new Map,d=i||y0(e,t),f=jh(e,d);c.set(e,{artifactName:s,content:t,type:d,path:f}),G.setProgress(0,c.size);const h=js(c);if(!h.valid)throw new Error(`Validation failed: +`),{content:Wv(s,l),fileName:o,codeType:a,artifactType:n,artifactName:i}}function E0(t){const e={};for(const n of wl(t))e[n]="";return e}function S0(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 x0(t,e,n,i=new Set,r=""){const s=[],o=Bh.test(e),a=Dh.test(e);return n===J.WIDGET&&!o&&!a&&s.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:s.length===0,errors:s}}function js(t){const e=[],n=[];if(!t||t.size===0)return e.push("No files to commit"),{valid:!1,errors:e,warnings:n};const i=new Set(Array.from(t.values()).flatMap(r=>As(r.content||"")));for(const[r,s]of t.entries()){if((!s.content||s.content.trim().length===0)&&e.push(`File ${r} is empty`),s.content&&s.content.length>1e5&&n.push(`File ${r} is very large (>100KB)`),r.endsWith(".dart")){const o=x0(r,s.content,s.type,i,s.artifactName);o.valid||e.push(...o.errors.map(a=>`${r}: ${a}`))}if(r==="pubspec.yaml"){const o=mh(s.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:n}}const ee={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},G={currentState:ee.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=ee.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(ee).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===ee.PREPARING&&(this.startTime=Date.now()),(t===ee.SUCCESS||t===ee.ERROR)&&(this.endTime=Date.now()),typeof window<"u"&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("commitStateChange",{detail:{state:t,commitState:this}})),console.log(`Commit state changed to: ${t}`)},setError(t){this.error=t,this.setState(ee.ERROR)},setSuccess(t){this.result=t,this.setState(ee.SUCCESS)},setProgress(t,e){this.filesProcessed=t,this.totalFiles=e},getElapsedTime(){return this.startTime?(this.endTime||Date.now())-this.startTime:null},isInProgress(){return this.currentState===ee.PREPARING||this.currentState===ee.VALIDATING||this.currentState===ee.PUSHING}};async function I0(t,e,n={}){let{codeType:i="W"}=n;const{pubspecDeps:r={},artifactName:s=e}=n;i==="CustomWidget"&&(i=J.WIDGET),i==="CustomAction"&&(i=J.ACTION),i==="CustomFunction"&&(i=J.FUNCTION),i==="CustomClass"&&(i=J.CODE_FILE),i==="CodeFile"&&(i=J.CODE_FILE),G.reset(),G.setState(ee.PREPARING);try{const o=await Te("flutterflow"),a=await Te("flutterflow_project_id");if(!o||!a)throw new Error("FlutterFlow credentials not configured. Please set your API key and Project ID in the API Keys settings.");if(!Os(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=yt(),u=new hi(o,a,"main",l);G.setState(ee.VALIDATING);const c=new Map,d=i||y0(e,t),f=jh(e,d);c.set(e,{artifactName:s,content:t,type:d,path:f}),G.setProgress(0,c.size);const h=js(c);if(!h.valid)throw new Error(`Validation failed: ${h.errors.join(` -`)}`);const p=await Hl(u,r),g=p.yaml,m=await Ul(u,c,p.remoteFiles,`Provision ${s} custom class`,g),v=await jl(m.syncFileMap,m.remoteFiles),S=new Map(m.syncFileMap);S.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),Oe.set("package");const b=await Wl(S),_={project_id:a,zipped_custom_code:b,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};G.setState(ee.PUSHING),G.setProgress(1,c.size),sr(u),Oe.set("push");const x=await u.pushCode(_),I=await Bl(x);if(I.success)G.setSuccess({fileCount:c.size,projectId:a,warnings:I.errorMap&&I.errorMap.size>0?Array.from(I.errorMap.entries()):[]});else{const T=I.errorMessage||Dl(I.responseCode);throw new Error(T)}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:p.added,unverified:m.unverified,approximate:m.approximate,warnings:I.errorMap?Array.from(I.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),G.setError(o),o instanceof Yt?{success:!1,unconfirmed:!0,error:o.message,state:G.currentState}:{success:!1,error:o.message,state:G.currentState}}}async function Wl(t){const e=new JSZip;for(const[n,i]of t.entries())e.file(n,i.content);return e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}async function k0(t,e={}){const{artifactType:n,artifactName:i,fileName:r,pipelineResult:s}=e;console.log(`Starting commit for ${i} (${n})`);let o=!1;const a={projectId:null,endpoint:_t(),artifactType:n,artifactName:i,fileName:r};try{G.setState(ee.PREPARING);const l=Hh(t,{artifactType:n,artifactName:i,fileName:r}),u=E0(l.content);console.log("Detected dependencies:",u),G.setState(ee.VALIDATING);const c=await Te("flutterflow"),d=qi||await Te("flutterflow_project_id");if(!c)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!d)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Os(d))throw new Error("Invalid FlutterFlow Project ID format.");a.projectId=d;const f=new Map;f.set(l.fileName,{artifactName:i,content:l.content,type:l.codeType,path:jh(l.fileName,l.codeType),functionName:l.codeType===J.FUNCTION?i:void 0}),G.setProgress(0,f.size);const h=js(f);if(!h.valid)throw new Error(`File validation failed: +`)}`);const p=await Hl(u,r),g=p.yaml,m=await Ul(u,c,p.remoteFiles,`Provision ${s} custom class`,g),v=await jl(m.syncFileMap,m.remoteFiles),S=new Map(m.syncFileMap);S.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),Oe.set("package");const b=await Wl(S),_={project_id:a,zipped_custom_code:b,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};G.setState(ee.PUSHING),G.setProgress(1,c.size),sr(u),Oe.set("push");const x=await u.pushCode(_),I=await Bl(x);if(I.success)G.setSuccess({fileCount:c.size,projectId:a,warnings:I.errorMap&&I.errorMap.size>0?Array.from(I.errorMap.entries()):[]});else{const T=I.errorMessage||Dl(I.responseCode);throw new Error(T)}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:p.added,unverified:m.unverified,approximate:m.approximate,warnings:I.errorMap?Array.from(I.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),G.setError(o),o instanceof mt?{success:!1,unconfirmed:!0,error:o.message,state:G.currentState}:{success:!1,error:o.message,state:G.currentState}}}async function Wl(t){const e=new JSZip;for(const[n,i]of t.entries())e.file(n,i.content);return e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}async function k0(t,e={}){const{artifactType:n,artifactName:i,fileName:r,pipelineResult:s}=e;console.log(`Starting commit for ${i} (${n})`);let o=!1;const a={projectId:null,endpoint:yt(),artifactType:n,artifactName:i,fileName:r};try{G.setState(ee.PREPARING);const l=Hh(t,{artifactType:n,artifactName:i,fileName:r}),u=E0(l.content);console.log("Detected dependencies:",u),G.setState(ee.VALIDATING);const c=await Te("flutterflow"),d=qi||await Te("flutterflow_project_id");if(!c)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!d)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Os(d))throw new Error("Invalid FlutterFlow Project ID format.");a.projectId=d;const f=new Map;f.set(l.fileName,{artifactName:i,content:l.content,type:l.codeType,path:jh(l.fileName,l.codeType),functionName:l.codeType===J.FUNCTION?i:void 0}),G.setProgress(0,f.size);const h=js(f);if(!h.valid)throw new Error(`File validation failed: ${h.errors.join(` -`)}`);h.warnings.length>0&&console.warn("Validation warnings:",h.warnings),G.setState(ee.PUSHING);const p=_t(),g=new hi(c,d,"main",p),m=await Hl(g,u),v=m.yaml,S=await Ul(g,f,m.remoteFiles,`Provision ${i} custom class`,v);o=S.provisionSucceeded===!0;const b=await jl(S.syncFileMap,S.remoteFiles),_=new Map(S.syncFileMap);_.set("pubspec.yaml",{content:v,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Oe.set("package");const x=await Wl(_),I={project_id:d,zipped_custom_code:x,uid:`web_${Date.now()}`,branch_name:g.branchName,serialized_yaml:v,file_map:b.fileMapContents,functions_map:b.functionsMapContents};G.setProgress(1,f.size),sr(g),Oe.set("push");const T=await g.pushCode(I),E=await Bl(T);if(E.success){const P={...S0(l,s),projectId:d};return G.setSuccess({...P,fileCount:f.size,warnings:E.errorMap?Array.from(E.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${l.fileName} to FlutterFlow`,metadata:P,targetIdentity:a,addedDependencies:m.added,unverified:S.unverified,approximate:S.approximate,warnings:E.errorMap?Array.from(E.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}else{const P=E.errorMessage||Dl(E.responseCode),$=new Error(P);throw $.errorMap=E.errorMap,$}}catch(l){console.error("Commit execution failed:",l),G.setError(l);let u=new Map;if(l.errorMap)u=l.errorMap;else if(l.message&&l.message.includes("{"))try{const c=l.message.match(/\{[\s\S]*\}/);if(c){const d=JSON.parse(c[0]);u=new Map(Object.entries(d))}}catch(c){console.warn("Failed to parse error map from commit response:",c)}return l instanceof Yt?{success:!1,unconfirmed:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:o?{success:!1,partial:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function C0(t,e={}){const{pipelineResult:n}=e;let i=!1;const r={projectId:null,endpoint:_t(),artifactType:"Bundle",artifactName:t?.title,fileName:t?.fileEntries?`${t.fileEntries.length} artifacts`:"bundle"};try{if(G.setState(ee.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: +`)}`);h.warnings.length>0&&console.warn("Validation warnings:",h.warnings),G.setState(ee.PUSHING);const p=yt(),g=new hi(c,d,"main",p),m=await Hl(g,u),v=m.yaml,S=await Ul(g,f,m.remoteFiles,`Provision ${i} custom class`,v);o=S.provisionSucceeded===!0;const b=await jl(S.syncFileMap,S.remoteFiles),_=new Map(S.syncFileMap);_.set("pubspec.yaml",{content:v,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Oe.set("package");const x=await Wl(_),I={project_id:d,zipped_custom_code:x,uid:`web_${Date.now()}`,branch_name:g.branchName,serialized_yaml:v,file_map:b.fileMapContents,functions_map:b.functionsMapContents};G.setProgress(1,f.size),sr(g),Oe.set("push");const T=await g.pushCode(I),E=await Bl(T);if(E.success){const P={...S0(l,s),projectId:d};return G.setSuccess({...P,fileCount:f.size,warnings:E.errorMap?Array.from(E.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${l.fileName} to FlutterFlow`,metadata:P,targetIdentity:a,addedDependencies:m.added,unverified:S.unverified,approximate:S.approximate,warnings:E.errorMap?Array.from(E.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}else{const P=E.errorMessage||Dl(E.responseCode),$=new Error(P);throw $.errorMap=E.errorMap,$}}catch(l){console.error("Commit execution failed:",l),G.setError(l);let u=new Map;if(l.errorMap)u=l.errorMap;else if(l.message&&l.message.includes("{"))try{const c=l.message.match(/\{[\s\S]*\}/);if(c){const d=JSON.parse(c[0]);u=new Map(Object.entries(d))}}catch(c){console.warn("Failed to parse error map from commit response:",c)}return l instanceof mt?{success:!1,unconfirmed:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:o?{success:!1,partial:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function C0(t,e={}){const{pipelineResult:n}=e;let i=!1;const r={projectId:null,endpoint:yt(),artifactType:"Bundle",artifactName:t?.title,fileName:t?.fileEntries?`${t.fileEntries.length} artifacts`:"bundle"};try{if(G.setState(ee.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: ${t.errors.join(` `)}`);const s=new Map(t.fileEntries.map(I=>[I.fileName,{artifactId:I.artifactId,artifactName:I.artifactName,content:I.content,type:I.type,path:I.path,functionName:I.type===J.FUNCTION?I.artifactName:void 0}]));G.setProgress(0,s.size);const o=js(s);if(!o.valid)throw new Error(`File validation failed: ${o.errors.join(` -`)}`);G.setState(ee.VALIDATING);const a=await Te("flutterflow"),l=qi||await Te("flutterflow_project_id");if(!a)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!l)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Os(l))throw new Error("Invalid FlutterFlow Project ID format.");r.projectId=l,G.setState(ee.PUSHING);const u=_t(),c=new hi(a,l,"main",u),d=await Hl(c,t.dependencies),f=d.yaml,h=await Ul(c,s,d.remoteFiles,`Provision ${t.title} custom classes`,f);i=h.provisionSucceeded===!0;const p=await jl(h.syncFileMap,h.remoteFiles),g=new Map(h.syncFileMap);g.set("pubspec.yaml",{content:f,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Oe.set("package");const m=await Wl(g),v={project_id:l,zipped_custom_code:m,uid:`web_${Date.now()}`,branch_name:c.branchName,serialized_yaml:f,file_map:p.fileMapContents,functions_map:p.functionsMapContents};G.setProgress(1,s.size),sr(c),Oe.set("push");const S=await c.pushCode(v),b=await Bl(S);if(b.success){const I={...n,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((T,E)=>T+E.content.length,0),projectId:l};return G.setSuccess({...I,fileCount:s.size,warnings:b.errorMap?Array.from(b.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:I,targetIdentity:r,addedDependencies:d.added,unverified:h.unverified,approximate:h.approximate,warnings:b.errorMap?Array.from(b.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}const _=b.errorMessage||Dl(b.responseCode),x=new Error(_);throw x.errorMap=b.errorMap,x}catch(s){console.error("Bundle commit execution failed:",s),G.setError(s);const o=s.errorMap||new Map;return s instanceof Yt?{success:!1,unconfirmed:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:i?{success:!1,partial:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function A0(t,e=[]){const n=ml("architect");try{return await Ss("architect",Ah,uv(t),n,e)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Prompt Architect failed: ${i.message}`)}}async function Us(t,e,n=[],i){const r=dv(t),s=ml("generator",y.bundleSpec);try{return await Ss("generator",e,r,s,n)}catch(o){if(o.isModelArmor||o.isUsageLimit||o.isPipelineCancel)throw o;if(e!==kr){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,o.message),$w(e,kr,i);try{return await Ss("generator",kr,r,s,n)}catch(a){throw a.isModelArmor||a.isUsageLimit||a.isPipelineCancel?a:new Error(`Code Generator failed: primary (${e}): ${o.message} | fallback (${kr}): ${a.message}`)}}throw new Error(`Code Generator failed: ${o.message}`)}}async function Hs(t,e=null){const n={...ml("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await Ss("review",Ph,fv(t),n)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Code Review failed: ${i.message}`)}}function bs(t,e){const n=document.getElementById(`step${t}-item`),i=document.getElementById(`step${t}-status`);!n||!i||(n.classList.remove("active","completed","error"),i.classList.remove("running","completed","error"),e==="active"?(n.classList.add("active"),i.classList.add("running"),i.innerHTML=` +`)}`);G.setState(ee.VALIDATING);const a=await Te("flutterflow"),l=qi||await Te("flutterflow_project_id");if(!a)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!l)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Os(l))throw new Error("Invalid FlutterFlow Project ID format.");r.projectId=l,G.setState(ee.PUSHING);const u=yt(),c=new hi(a,l,"main",u),d=await Hl(c,t.dependencies),f=d.yaml,h=await Ul(c,s,d.remoteFiles,`Provision ${t.title} custom classes`,f);i=h.provisionSucceeded===!0;const p=await jl(h.syncFileMap,h.remoteFiles),g=new Map(h.syncFileMap);g.set("pubspec.yaml",{content:f,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Oe.set("package");const m=await Wl(g),v={project_id:l,zipped_custom_code:m,uid:`web_${Date.now()}`,branch_name:c.branchName,serialized_yaml:f,file_map:p.fileMapContents,functions_map:p.functionsMapContents};G.setProgress(1,s.size),sr(c),Oe.set("push");const S=await c.pushCode(v),b=await Bl(S);if(b.success){const I={...n,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((T,E)=>T+E.content.length,0),projectId:l};return G.setSuccess({...I,fileCount:s.size,warnings:b.errorMap?Array.from(b.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:I,targetIdentity:r,addedDependencies:d.added,unverified:h.unverified,approximate:h.approximate,warnings:b.errorMap?Array.from(b.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}const _=b.errorMessage||Dl(b.responseCode),x=new Error(_);throw x.errorMap=b.errorMap,x}catch(s){console.error("Bundle commit execution failed:",s),G.setError(s);const o=s.errorMap||new Map;return s instanceof mt?{success:!1,unconfirmed:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:i?{success:!1,partial:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function A0(t,e=[]){const n=ml("architect");try{return await Ss("architect",Ah,uv(t),n,e)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Prompt Architect failed: ${i.message}`)}}async function Us(t,e,n=[],i){const r=dv(t),s=ml("generator",y.bundleSpec);try{return await Ss("generator",e,r,s,n)}catch(o){if(o.isModelArmor||o.isUsageLimit||o.isPipelineCancel)throw o;if(e!==kr){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,o.message),$w(e,kr,i);try{return await Ss("generator",kr,r,s,n)}catch(a){throw a.isModelArmor||a.isUsageLimit||a.isPipelineCancel?a:new Error(`Code Generator failed: primary (${e}): ${o.message} | fallback (${kr}): ${a.message}`)}}throw new Error(`Code Generator failed: ${o.message}`)}}async function Hs(t,e=null){const n={...ml("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await Ss("review",Ph,fv(t),n)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Code Review failed: ${i.message}`)}}function bs(t,e){const n=document.getElementById(`step${t}-item`),i=document.getElementById(`step${t}-status`);!n||!i||(n.classList.remove("active","completed","error"),i.classList.remove("running","completed","error"),e==="active"?(n.classList.add("active"),i.classList.add("running"),i.innerHTML=` `):e==="completed"?(n.classList.add("completed"),i.classList.add("completed"),i.innerHTML=` @@ -127,12 +127,12 @@ ${o.errors.join(` `):i.innerHTML=` - `)}function Ae(t,e){const n=document.getElementById(`step${t}-loading`),i=document.getElementById(`step${t}-result`);e?(n.classList.remove("hidden"),i.classList.add("hidden"),bs(t,"active")):(n.classList.add("hidden"),i.classList.remove("hidden"),bs(t,"completed"))}function P0(t){const e=document.getElementById(`${t}-content`),n=document.getElementById(`${t}-chevron`);e.classList.contains("open")?(e.classList.remove("open"),n&&(n.style.transform="rotate(0deg)")):(e.classList.add("open"),n&&(n.style.transform="rotate(180deg)"))}function F0(t){nt(parseInt(t.replace("step","")))}function nt(t){for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-item`);a&&a.classList.remove("active")}const e=document.getElementById(`step${t}-item`);e&&e.classList.add("active"),Nn();const n=document.getElementById("ready-state");n&&n.classList.add("hidden");for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-content`);a&&a.classList.add("hidden")}const i=document.getElementById(`step${t}-content`);i&&i.classList.remove("hidden");const r=document.getElementById("stage-title"),s={1:"Prompt Architect",2:"Code Generator",3:"Code Review"};r&&(r.textContent=s[t]||"Active Workflow Stage")}function R0(t){const e=document.getElementById(t);if(!e)return;const n=e.dataset.raw||e.textContent;navigator.clipboard.writeText(n).then(()=>{const r=e.closest(".code-container")?.querySelector(".copy-btn");r&&(r.classList.add("copied"),r.innerHTML=' Copied!',setTimeout(()=>{r.classList.remove("copied"),r.innerHTML=' Copy'},2e3))}).catch(i=>{console.warn("Failed to copy to clipboard:",i)})}function qa(t){const e=za(t);console.log(`Step 1 (Prompt Architect): ${Vt(Ah)}`),console.log(e!==t?`Step 2 (Code Generator): ${Vt(t)} → ${Vt(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${Vt(t)}`),console.log(`Step 3 (Code Review): ${Vt(Ph)}`)}function Wh(){return{step1Result:y.step1Result,step2Result:y.step2Result,step3Result:y.step3Result,artifactBundle:y.artifactBundle,bundleReview:y.bundleReview,selectedArtifactId:y.selectedArtifactId}}function T0(t){if(!t)return;Object.assign(y,t),new Set((y.artifactBundle?.artifacts||[]).map(n=>n.id)).has(y.selectedArtifactId)||(y.selectedArtifactId=oi(y.artifactBundle)?.id||null)}const qh="results-replacement-error";function $0(t,{stage:e=2,runId:n,retry:i}){if(!re(n))return;const r=document.getElementById(qh);if(!r)return;const s=wh(t),o=document.getElementById("results-replacement-error-title"),a=document.getElementById("results-replacement-error-message"),l=document.getElementById("results-replacement-error-retry"),u=document.getElementById("results-replacement-error-upgrade");o&&(o.textContent=`${Vs[e]||"Regeneration"}: ${s.title}`),a&&(a.textContent=s.message),r.hidden=!1;let c=null;u&&(u.hidden=!s.canUpgrade,s.canUpgrade&&(u.textContent="View plans",u.onclick=()=>di(),c=u)),l&&(l.hidden=s.canUpgrade,s.canUpgrade||(l.onclick=()=>{ql(),typeof i=="function"&&i()},l.textContent="Retry",c=l)),(c||r).focus({preventScroll:!0})}function ql(){const t=document.getElementById(qh);t&&(t.hidden=!0)}function zh(t,{previous:e,stage:n,runId:i,retry:r}){re(i)&&(t.isUsageLimit&&un(),T0(e),cr(),nn(!0),ur(),eo(),$0(t,{stage:n,runId:i,retry:r}),rn())}async function Vh(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0;const e=Gs();zl("standardRegenerate",y.step2Result,y.step1Result);const n=document.querySelectorAll(".btn-refine-action"),i=Wh();n.forEach(r=>{r.disabled=!0,r.innerHTML=` + `)}function Ae(t,e){const n=document.getElementById(`step${t}-loading`),i=document.getElementById(`step${t}-result`);e?(n.classList.remove("hidden"),i.classList.add("hidden"),bs(t,"active")):(n.classList.add("hidden"),i.classList.remove("hidden"),bs(t,"completed"))}function P0(t){const e=document.getElementById(`${t}-content`),n=document.getElementById(`${t}-chevron`);e.classList.contains("open")?(e.classList.remove("open"),n&&(n.style.transform="rotate(0deg)")):(e.classList.add("open"),n&&(n.style.transform="rotate(180deg)"))}function F0(t){nt(parseInt(t.replace("step","")))}function nt(t){for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-item`);a&&a.classList.remove("active")}const e=document.getElementById(`step${t}-item`);e&&e.classList.add("active"),Nn();const n=document.getElementById("ready-state");n&&n.classList.add("hidden");for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-content`);a&&a.classList.add("hidden")}const i=document.getElementById(`step${t}-content`);i&&i.classList.remove("hidden");const r=document.getElementById("stage-title"),s={1:"Prompt Architect",2:"Code Generator",3:"Code Review"};r&&(r.textContent=s[t]||"Active Workflow Stage")}function R0(t){const e=document.getElementById(t);if(!e)return;const n=e.dataset.raw||e.textContent;navigator.clipboard.writeText(n).then(()=>{const r=e.closest(".code-container")?.querySelector(".copy-btn");r&&(r.classList.add("copied"),r.innerHTML=' Copied!',setTimeout(()=>{r.classList.remove("copied"),r.innerHTML=' Copy'},2e3))}).catch(i=>{console.warn("Failed to copy to clipboard:",i)})}function qa(t){const e=za(t);console.log(`Step 1 (Prompt Architect): ${Gt(Ah)}`),console.log(e!==t?`Step 2 (Code Generator): ${Gt(t)} → ${Gt(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${Gt(t)}`),console.log(`Step 3 (Code Review): ${Gt(Ph)}`)}function Wh(){return{step1Result:y.step1Result,step2Result:y.step2Result,step3Result:y.step3Result,artifactBundle:y.artifactBundle,bundleReview:y.bundleReview,selectedArtifactId:y.selectedArtifactId}}function T0(t){if(!t)return;Object.assign(y,t),new Set((y.artifactBundle?.artifacts||[]).map(n=>n.id)).has(y.selectedArtifactId)||(y.selectedArtifactId=oi(y.artifactBundle)?.id||null)}const qh="results-replacement-error";function $0(t,{stage:e=2,runId:n,retry:i}){if(!re(n))return;const r=document.getElementById(qh);if(!r)return;const s=wh(t),o=document.getElementById("results-replacement-error-title"),a=document.getElementById("results-replacement-error-message"),l=document.getElementById("results-replacement-error-retry"),u=document.getElementById("results-replacement-error-upgrade");o&&(o.textContent=`${Vs[e]||"Regeneration"}: ${s.title}`),a&&(a.textContent=s.message),r.hidden=!1;let c=null;u&&(u.hidden=!s.canUpgrade,s.canUpgrade&&(u.textContent="View plans",u.onclick=()=>di(),c=u)),l&&(l.hidden=s.canUpgrade,s.canUpgrade||(l.onclick=()=>{ql(),typeof i=="function"&&i()},l.textContent="Retry",c=l)),(c||r).focus({preventScroll:!0})}function ql(){const t=document.getElementById(qh);t&&(t.hidden=!0)}function zh(t,{previous:e,stage:n,runId:i,retry:r}){re(i)&&(t.isUsageLimit&&un(),T0(e),cr(),nn(!0),ur(),eo(),$0(t,{stage:n,runId:i,retry:r}),rn())}async function Vh(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0;const e=Gs();zl("standardRegenerate",y.step2Result,y.step1Result);const n=document.querySelectorAll(".btn-refine-action"),i=Wh();n.forEach(r=>{r.disabled=!0,r.innerHTML=` - Refining...`});try{ql();const r=Nl(),s=r.id,o=hv({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,artifactId:r.id,userFeedback:"Fix the issues listed in the audit report."});Zs({runId:e}),Pt(2,e),nt(2),Ae(2,!0);const a=await Us(o,t,[],e);if(!re(e))return;y.step2Result=a,Bs(),tn(2,e);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),nt(3),Pt(3,e),Ae(3,!0);const c=await Hs(y.step2Result,y.step1Result);if(!re(e))return;y.step3Result=c,Ds(),tn(3,e),y.artifactBundle?.artifacts?.some(h=>h.id===s)?y.selectedArtifactId=s:y.selectedArtifactId=oi(y.artifactBundle)?.id||null;const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const f=Ls(y.step3Result);ur(u,f)}catch(r){if(console.error("Refinement failed:",r),!re(e))return;const s=Ms(r,{architect:2,generator:2,review:3});zh(r,{previous:i,stage:s,runId:e,retry:Vh})}finally{n.forEach(r=>{r.disabled=!1,r.textContent="Refine & Regenerate"}),re(e)&&(y.isRunning=!1,rn())}}async function zl(t,e,n){const i=`${vt}/connectFeedback`,r={type:t,code:e,input:n};try{const s=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok){const a=await s.text();return console.error(`callEndpoint failed: ${s.status} ${s.statusText}`,a),{success:!1,status:s.status,error:a}}const o=await s.json();return console.log("Telemetry success:",o),o}catch(s){return console.error("callEndpoint failed:",s),{success:!1,error:s.message}}}function M0(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function Gh(){const t=document.getElementById("ff-error-paste-input"),e=t?.value?.trim();if(!e){t?.focus(),t?.classList.add("ring-2","ring-red-400","border-red-300"),setTimeout(()=>t?.classList.remove("ring-2","ring-red-400","border-red-300"),2e3);return}if(!y.step2Result){Ee("No generated code found. Please run the full pipeline first.","warning");return}if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=Gs();zl("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` + Refining...`});try{ql();const r=Nl(),s=r.id,o=hv({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,artifactId:r.id,userFeedback:"Fix the issues listed in the audit report."});Zs({runId:e}),Ft(2,e),nt(2),Ae(2,!0);const a=await Us(o,t,[],e);if(!re(e))return;y.step2Result=a,Bs(),tn(2,e);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),nt(3),Ft(3,e),Ae(3,!0);const c=await Hs(y.step2Result,y.step1Result);if(!re(e))return;y.step3Result=c,Ds(),tn(3,e),y.artifactBundle?.artifacts?.some(h=>h.id===s)?y.selectedArtifactId=s:y.selectedArtifactId=oi(y.artifactBundle)?.id||null;const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const f=Ls(y.step3Result);ur(u,f)}catch(r){if(console.error("Refinement failed:",r),!re(e))return;const s=Ms(r,{architect:2,generator:2,review:3});zh(r,{previous:i,stage:s,runId:e,retry:Vh})}finally{n.forEach(r=>{r.disabled=!1,r.textContent="Refine & Regenerate"}),re(e)&&(y.isRunning=!1,rn())}}async function zl(t,e,n){const i=`${_t}/connectFeedback`,r={type:t,code:e,input:n};try{const s=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok){const a=await s.text();return console.error(`callEndpoint failed: ${s.status} ${s.statusText}`,a),{success:!1,status:s.status,error:a}}const o=await s.json();return console.log("Telemetry success:",o),o}catch(s){return console.error("callEndpoint failed:",s),{success:!1,error:s.message}}}function M0(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function Gh(){const t=document.getElementById("ff-error-paste-input"),e=t?.value?.trim();if(!e){t?.focus(),t?.classList.add("ring-2","ring-red-400","border-red-300"),setTimeout(()=>t?.classList.remove("ring-2","ring-red-400","border-red-300"),2e3);return}if(!y.step2Result){Ee("No generated code found. Please run the full pipeline first.","warning");return}if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=Gs();zl("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` - Fixing…`);const s=Wh();try{ql();const o=nh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});bp(),Zs({runId:i}),Pt(2,i),nt(2),Ae(2,!0);const a=await Us(o,n,[],i);if(!re(i))return;y.step2Result=a,Bs(),tn(2,i);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),nt(3),Pt(3,i),Ae(3,!0);const c=await Hs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,Ds(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const f=Ls(y.step3Result);ur(u,f),t&&(t.value="")}catch(o){if(console.error("Fix from errors failed:",o),!re(i))return;const a=Ms(o,{architect:2,generator:2,review:3});zh(o,{previous:s,stage:a,runId:i,retry:Gh})}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function or(){if(console.log("runThinkingPipeline called"),y.isRunning)return;localStorage.setItem("hasSeenWalkthrough","true");const t=document.getElementById("pipeline-input").value,e=document.getElementById("code-generator-model").value,n=Ne.slice();if(!t.trim()){Ee("Please describe your FlutterFlow widget first.","warning");return}y.isRunning=!0;const i=Gs();try{if(await Oa,!re(i)||(pn.length&&await Promise.allSettled(pn.map(v=>v.job)),!re(i))||!await rw()||!re(i)||(await X0(),!re(i)))return;const r=za(e);t.length,g0(),y.submittedPrompt=t,y.submittedImages=n.filter(v=>v.url),Ka(!0),qa(r),Nn();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const o=document.getElementById("paywall-exhausted");o&&o.classList.add("hidden"),Zs({prompt:t,runId:i}),Ow(),nt(1),Pt(1,i),Ae(1,!0);const a=y.submittedImages.map(v=>({url:v.url})),l=await A0(t,a);if(!re(i))return;y.step1Result=l,m0(),tn(1,i);const u=document.getElementById("step1-output"),c=li(y.step1Result);u.textContent=c,u.dataset.raw=c,Ae(1,!1),nt(2),Pt(2,i),Ae(2,!0);const d=await Us(y.step1Result,r,a,i);if(!re(i))return;y.step2Result=d,Bs(),tn(2,i);const f=document.getElementById("step2-output"),h=li(y.step2Result);f.textContent=h,f.dataset.raw=h,Ae(2,!1),nt(3),Pt(3,i),Ae(3,!0);const p=await Hs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=p,Ds(),tn(3,i);const g=document.getElementById("step3-output");g.textContent=y.step3Result,Ae(3,!1),cr();const m=Ls(y.step3Result);Bw(),ur(h,m)}catch(r){if(r.isPipelineCancel||console.error("Pipeline failed:",r),!re(i))return;const s=Ms(r,{architect:1,generator:2,review:3});r.isUsageLimit?un():(r.message,za(document.getElementById("code-generator-model").value),void 0),nt(s),Ae(s,!1),vp(r,{stage:s,runId:i}),bs(s,"error")}finally{re(i)&&(y.isRunning=!1,Ka(!1),rn())}}function L0(){const t=document.getElementById("code-generator-model").value,e=[ms,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(i=>i!==t),n=prompt(`Retry with different model? + Fixing…`);const s=Wh();try{ql();const o=nh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});bp(),Zs({runId:i}),Ft(2,i),nt(2),Ae(2,!0);const a=await Us(o,n,[],i);if(!re(i))return;y.step2Result=a,Bs(),tn(2,i);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),nt(3),Ft(3,i),Ae(3,!0);const c=await Hs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,Ds(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const f=Ls(y.step3Result);ur(u,f),t&&(t.value="")}catch(o){if(console.error("Fix from errors failed:",o),!re(i))return;const a=Ms(o,{architect:2,generator:2,review:3});zh(o,{previous:s,stage:a,runId:i,retry:Gh})}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function or(){if(console.log("runThinkingPipeline called"),y.isRunning)return;localStorage.setItem("hasSeenWalkthrough","true");const t=document.getElementById("pipeline-input").value,e=document.getElementById("code-generator-model").value,n=Ne.slice();if(!t.trim()){Ee("Please describe your FlutterFlow widget first.","warning");return}y.isRunning=!0;const i=Gs();try{if(await Oa,!re(i)||(pn.length&&await Promise.allSettled(pn.map(v=>v.job)),!re(i))||!await rw()||!re(i)||(await X0(),!re(i)))return;const r=za(e);t.length,g0(),y.submittedPrompt=t,y.submittedImages=n.filter(v=>v.url),Ka(!0),qa(r),Nn();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const o=document.getElementById("paywall-exhausted");o&&o.classList.add("hidden"),Zs({prompt:t,runId:i}),Ow(),nt(1),Ft(1,i),Ae(1,!0);const a=y.submittedImages.map(v=>({url:v.url})),l=await A0(t,a);if(!re(i))return;y.step1Result=l,m0(),tn(1,i);const u=document.getElementById("step1-output"),c=li(y.step1Result);u.textContent=c,u.dataset.raw=c,Ae(1,!1),nt(2),Ft(2,i),Ae(2,!0);const d=await Us(y.step1Result,r,a,i);if(!re(i))return;y.step2Result=d,Bs(),tn(2,i);const f=document.getElementById("step2-output"),h=li(y.step2Result);f.textContent=h,f.dataset.raw=h,Ae(2,!1),nt(3),Ft(3,i),Ae(3,!0);const p=await Hs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=p,Ds(),tn(3,i);const g=document.getElementById("step3-output");g.textContent=y.step3Result,Ae(3,!1),cr();const m=Ls(y.step3Result);Bw(),ur(h,m)}catch(r){if(r.isPipelineCancel||console.error("Pipeline failed:",r),!re(i))return;const s=Ms(r,{architect:1,generator:2,review:3});r.isUsageLimit?un():(r.message,za(document.getElementById("code-generator-model").value),void 0),nt(s),Ae(s,!1),vp(r,{stage:s,runId:i}),bs(s,"error")}finally{re(i)&&(y.isRunning=!1,Ka(!1),rn())}}function L0(){const t=document.getElementById("code-generator-model").value,e=[ms,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(i=>i!==t),n=prompt(`Retry with different model? Current: ${t} @@ -164,8 +164,8 @@ ${a.content}`).join(` Error: ${g} `}else s+=`${t} -`;const o=nh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:s});Zs({runId:i}),Pt(2,i),nt(2),Ae(2,!0);const a=await Us(o,n,[],i);if(!re(i))return;y.step2Result=a,Bs(),tn(2,i);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),nt(3),Pt(3,i),Ae(3,!0);const c=await Hs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,Ds(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const f=Ls(y.step3Result);ur(u,f)}catch(s){if(console.error("Regeneration failed:",s),!re(i))return;const o=Ms(s,{architect:2,generator:2,review:3});s.isUsageLimit&&un(),nt(o),Ae(o,!1),vp(s,{stage:o,runId:i,retry:()=>Kh(t,e)}),bs(o,"error")}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function D0(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const n=await Te("flutterflow"),i=await Te("flutterflow_project_id");n&&i?(t.className="w-2 h-2 rounded-full bg-green-500",e.textContent="FlutterFlow credentials configured",e.className="text-green-600"):n||i?(t.className="w-2 h-2 rounded-full bg-yellow-500",e.textContent="FlutterFlow credentials incomplete",e.className="text-yellow-600"):(t.className="w-2 h-2 rounded-full bg-red-500",e.textContent="FlutterFlow credentials not configured",e.className="text-red-600")}async function Yh(t){try{const e=await fetch(`${vt}/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 j0(t){try{const n=await(await fetch(`${vt}/auth/verify-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})})).json();if(n.error||!n.email||!n.sessionToken)throw new Error(n.error||"Invalid or expired link");return n}catch(e){throw console.error("verifyMagicLink failed:",{message:e.message,stack:e.stack}),e}}async function U0(t){try{const e=await fetch(`${vt}/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:`${vt}/auth/refresh-session`,status:e.status}),null;const n=await e.json();return n.error||!n.email||!n.sessionToken?(console.warn("refreshSession: validation failed",{error:n.error,hasEmail:!!n.email,hasToken:!!n.sessionToken}),null):n}catch(e){return console.error("refreshSession: fetch failed",{url:`${vt}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function td(t,e){const n=Zh(),i=(z.email||n.email)!==t;z.email=t,z.sessionToken=e,z.isVerified=!0,ce=Mn({isLoading:!0}),localStorage.setItem(hs,JSON.stringify({email:t,sessionToken:e})),i&&ip()}function Jh(){z.email=null,z.sessionToken=null,z.isVerified=!1,ce=Mn({isResolved:!0}),localStorage.removeItem(hs),localStorage.removeItem(gs)}function Zh(){try{const t=localStorage.getItem(hs);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(hs),{email:null,sessionToken:null}}}async function H0(){const e=new URLSearchParams(window.location.search).get("token");if(e){window.history.replaceState({},"",window.location.pathname+window.location.hash);try{const{email:n,sessionToken:i}=await j0(e);td(n,i),Xh();const r=nd();r&&!window.location.hash&&(window.location.hash=r)}catch(n){nd();const i=n.message||"Sign-in link invalid or expired.";Ee(i,"error"),Ws(),Jn(i,"error")}}else{const{email:n,sessionToken:i}=Zh();if(n&&i){const r=await U0(i);r?td(r.email,r.sessionToken):Jh()}}Vl()}function W0(){try{localStorage.setItem(Na,JSON.stringify({hash:window.location.hash||"#home",ts:Date.now()}))}catch(t){console.warn("rememberSignInReturnSurface: failed to persist return surface:",t)}}function nd(){try{const t=localStorage.getItem(Na);if(localStorage.removeItem(Na),!t)return null;const{hash:e,ts:n}=JSON.parse(t);return!e||typeof n!="number"||Date.now()-n>Iy?null:e}catch(t){return console.warn("consumeSignInReturnSurface: failed to read return surface:",t),null}}function Ws(){const t=document.getElementById("signin-modal");if(!t)return;W0(),document.getElementById("signin-email-input")?.removeAttribute("aria-invalid"),Jn(""),He(t)}function Xh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&We(e)}function Jn(t,e){const n=document.getElementById("signin-message");n&&(n.textContent=t||"",n.classList.remove("signin-message-success","signin-message-error"),e&&n.classList.add(`signin-message-${e}`))}async function q0(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),n=Fs(t?.value);if(!n||!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(n)||n.length>254){t?.setAttribute("aria-invalid","true"),Jn("Please enter a valid email address.","error");return}t?.removeAttribute("aria-invalid"),e&&(e.disabled=!0,e.textContent="Sending…");const r=uh(n);r&&Jn(r,"error");try{const s=await Yh(n),o=s?.code===ch;t&&!o&&(t.value=""),t?.setAttribute("aria-invalid",String(o)),Jn(dh(s,n),o?"error":"success"),e&&(e.disabled=!1,e.textContent=o?"Send Sign-in Link":"Sent!",o||setTimeout(()=>{e.textContent==="Sent!"&&(e.textContent="Send Sign-in Link")},2500))}catch(s){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:n,err:s}),Jn("Something went wrong. Please try again.","error"),e&&(e.disabled=!1,e.textContent="Send Sign-in Link")}}function z0(){z.email=null,z.sessionToken=null,z.isVerified=!1,ce=Mn({isResolved:!0}),$_({storage:window.localStorage,onIdentityChanged:Vl,onPlanChanged:zs})}const V0=M_({sendLink:Yh,getEmail:()=>z.email||"",onState:G0});function G0(t){const e=document.getElementById("send-new-link-btn"),n=document.getElementById("send-new-link-msg");if(!e||!n)return;if(t.status==="pending"){e.disabled=!0,e.textContent="Sending…",n.className="acct-access-msg",n.textContent="Sending a fresh sign-in link…";return}if(t.status==="sent"){e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg",n.textContent=dh(t.data,z.email||"")||"Link sent — check your email.";return}e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg error";const i=t.error?.message?`Couldn't send a link right now. ${t.error.message}`:"Couldn't send a link right now. Please try again.";n.textContent=i}async function K0(){await V0()}function Y0(){const t=R_(window.localStorage),e=t.length?`Cleared disposable UI caches: ${t.join(", ")}.`:"Nothing disposable to clear.";Ee(`${e} Your run count, identity and stored keys are kept.`,"info")}function J0(){const t=document.getElementById("delete-unavailable-modal");t&&He(t,{trigger:document.activeElement})}function Z0(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("delete-unavailable-modal");e&&We(e)}function Vl(){const t=z.isVerified&&!!z.email,e=document.getElementById("auth-signedout"),n=document.getElementById("auth-signedin"),i=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),n&&n.classList.toggle("hidden",!t),i&&i.classList.toggle("hidden",t);const r=document.getElementById("auth-user-email");r&&(r.textContent=z.email||"");const s=document.getElementById("access-signed-email");s&&(s.textContent=z.email||""),aw(),zs()}async function Qh(){try{if(typeof FingerprintJS>"u"){console.warn("resolveIdentity: FingerprintJS not loaded, skipping");return}const e=await(await FingerprintJS.load()).get(),n=e.visitorId,i=await fetch(Py,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fingerprint:e.visitorId,cookie_id:n})});if(!i.ok)throw new Error(`Identity check HTTP ${i.status}`);const r=await i.json();if(ft.userId=r.user_id,ft.token=r.identity_token||null,ft.status=r.status,ft.resolved=!0,sessionStorage.setItem(Cy,r.user_id),ft.token&&sessionStorage.setItem(Ay,ft.token),r.usage_count!==void 0){const s=gn(),a=(r.usage_month||s)===s?r.usage_count:0;localStorage.setItem(Fn,JSON.stringify({count:a,month:s})),un()}console.log(`Identity resolved: ${r.status} (${r.user_id.slice(0,8)}...) usage: ${r.usage_count??"n/a"}`)}catch(t){console.error("resolveIdentity failed:",t)}}let Wo=null;function X0(t=5e3){return ft.resolved?Promise.resolve():(Wo||(Wo=Qh().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([Wo,new Promise(e=>setTimeout(e,t))]))}function ep(){const t=gn();try{const e=localStorage.getItem(Fn);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Fn,month:t,err:e}),localStorage.removeItem(Fn),{count:0,month:t}}}function gn(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function lr(){const t=ep();return t.month!==gn()?{count:0,month:gn()}:t}function Q0(){const e={count:lr().count+1,month:gn()};return localStorage.setItem(Fn,JSON.stringify(e)),e}function pi(){return!!ce.isLoading}function Rt(){return!!ce.isResolved}function ew(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(ps,e)?e:null}function tw(t){return t&&Object.entries(Eh).find(([,e])=>e===t)?.[0]||null}function Cr(...t){return t.find(e=>e!=null&&e!=="")}function nw(...t){return t.find(e=>e&&typeof e=="object")||{}}function iw(t){const e=t.data&&typeof t.data=="object"?t.data:t,n=nw(e.subscription,e.stripeSubscription,e.currentSubscription,e.customer?.subscriptions?.data?.[0],e.subscriptions?.data?.[0],e.subscriptions?.[0]),i=e.metadata||n.metadata||e.customer?.metadata||{},r=Cr(e.priceId,e.price_id,e.stripePriceId,e.stripe_price_id,n.priceId,n.price_id,n.plan?.id,n.price?.id,n.items?.data?.[0]?.price?.id,n.items?.[0]?.price?.id,n.lines?.data?.[0]?.price?.id),s=Cr(e.status,e.subscriptionStatus,e.subscription_status,n.status,"none"),o=ew(Cr(e.tier,e.plan,e.planId,e.plan_id,e.subscriptionTier,e.subscription_tier,e.product,e.productName,n.tier,n.plan,i.tier,i.plan)),a=Fy.has(String(s).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||tw(r)||(a||l?"professional":"free");return Mn({tier:u,status:s,periodEnd:Cr(e.periodEnd,e.currentPeriodEnd,e.current_period_end,n.current_period_end,n.periodEnd,null),isResolved:!0})}function qs(){return ps[ce.tier]??ps.free}async function rw(){if(z.isVerified&&(!Rt()||pi())&&(await np({force:!0}),zs()),z.isVerified&&!Rt())return Ee("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=lr(),e=qs();if(t>=e)return tp(t,e,{openModal:!0}),!1;const n=Math.floor(e*.8);if(t>=n){const i=e-t;Ee(`${i} run${i===1?"":"s"} remaining this month.`,"warning")}return!0}function id(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function tp(t,e,n={}){nn(!0);const i=document.getElementById("walkthrough-modal");i&&We(i,{restoreFocus:!1});const r=document.getElementById("ready-state");r&&r.classList.add("hidden");const s=document.getElementById("preview-frame-container");s&&(s.style.display="none");const o=document.getElementById("main-stage-container");o&&o.classList.add("visible");const a=document.getElementById("results-view");a&&a.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar");const l=document.getElementById("pipeline-progress");l&&l.classList.remove("visible");const u=document.getElementById("paywall-exhausted");if(!u){Ee(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),di();return}const c=document.getElementById("paywall-exhausted-text");if(c){const f=ce.tier;f==="free"?c.textContent=`You've used all ${e} free generations this month. Upgrade to Pro for 50 generations/month and access to all AI models.`:c.textContent=`You've used all ${e} generations this month on your ${f} plan. Your limit resets next month.`}const d=document.getElementById("paywall-signin-btn");d&&d.classList.toggle("hidden",z.isVerified),u.classList.remove("hidden"),n.openModal&&di()}function za(t){return ce.tier==="free"&&Nr.includes(t)?ms:t}function sw(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const n=ce.tier,r=!(z.isVerified&&!Rt())&&n==="free";Array.from(e.options).forEach(o=>{const a=Vt(o.value),l=Nr.includes(o.value);o.textContent=l&&r?`${a} (PRO)`:a,o.disabled=!1}),r&&Nr.includes(e.value)&&(e.value=ms),e.disabled=!1,qu.has(e)||(e.addEventListener("change",()=>{Rt()&&ce.tier==="free"&&Nr.includes(e.value)&&(e.value=ms,di()),qa(e.value),kl()}),qu.add(e));let s=document.getElementById("model-selector-free-notice");r?(s||(s=document.createElement("p"),s.id="model-selector-free-notice",s.className="text-xs text-gray-400 mt-1",t.appendChild(s)),s.innerHTML='Free plan — Gemini only. '):s&&s.remove(),qa(e.value)}function Gl(){const t=z.isVerified&&!!z.email,e=t&&pi(),n=!t||Rt(),i=lr(),r=n?i.count:0,s=n?qs():0,o=Math.max(0,s-r),a=`${r} / ${s} runs this month`,l=gl,u=n?ce.tier||"free":null,c=document.getElementById("topbar-credits-count");c&&(e?c.textContent="…":n?c.textContent=String(o):c.textContent="—");const d=document.getElementById("credits-balance");d&&(e?d.textContent="Checking plan…":n?d.textContent=a:d.textContent="Plan check failed");const f=document.getElementById("usage-dialog-tier");f&&(e?f.textContent="Checking…":n?f.textContent=l[u]||"Free":f.textContent="Unavailable");const h=document.getElementById("usage-dialog-status");h&&(e?h.textContent="Verifying your subscription…":n?h.textContent="Runs reset at the start of each month.":h.textContent="Could not verify your subscription. Try again or sign out.");const p=document.getElementById("usage-counter");if(p)if(e&&t)p.textContent="Checking plan…",p.className="text-xs text-gray-500";else if(!n&&t)p.textContent="Plan check failed",p.className="text-xs text-red-600 font-medium";else{p.textContent=a;const g=s>0?r/s:0;p.className=g>=1?"text-xs text-red-600 font-medium":g>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500"}if(!t){const g=document.getElementById("guest-usage-text");if(g){const m=ep(),v=m.month===gn()?m.count??0:0;g.textContent=`${v} / ${ps.free} generations used`}}ow()}function ow(){if(!(z.isVerified&&!!z.email))return;const e=pi(),n=Rt(),i=lr(),r=n?i.count:0,s=n?qs():0,o=Math.max(0,s-r),a=n?ce.tier||"free":null,l={free:"Free",professional:"Pro",power:"Power"}[a]||"Free",u=z.email||"",c=u.split("@")[0]||u,d=document.getElementById("acct-avatar");d&&(d.textContent=(u[0]||"?").toUpperCase());const f=document.getElementById("acct-name");f&&(f.textContent=c||"—");const h=document.getElementById("acct-plan-tier"),p=document.getElementById("acct-plan-price"),g=document.getElementById("acct-plan-note"),m=document.getElementById("acct-renewal");if(h&&(h.textContent=e?"Checking…":n?l:"Plan unavailable"),p)if(e)p.textContent="—";else if(!n)p.textContent="—";else if(a==="free")p.textContent="$0 / month";else{const E=Oi(Ni[a]??0,Cl());p.textContent=`${E} / month`}if(g&&(e?g.textContent="Verifying your subscription…":n?a==="free"?g.textContent="No subscription. Upgrade for more generations.":g.textContent="billed monthly through Stripe":g.textContent="Could not verify your subscription. Check billing or sign out."),m){const E=Date.parse(ce.periodEnd||""),P=n&&a!=="free"&&!!ce.periodEnd&&!Number.isNaN(E);if(e)m.textContent="";else if(!n)m.textContent="";else if(a==="free")m.textContent="";else if(P){const $=new Date(E).toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"});m.textContent=`Renews ${$} · reset at the start of each month.`}else m.textContent="Renewal date is not available for this period."}const v=document.getElementById("acct-left-count"),S=document.getElementById("acct-left-limit"),b=document.getElementById("acct-reset-note");v&&(v.textContent=e?"…":n?String(o):"—"),S&&(S.textContent=e?"…":n?String(s):"—"),b&&(e?b.textContent="Checking plan…":n?b.textContent="Runs reset at the start of each month.":b.textContent="Plan check failed. Refresh or manage billing.");const _=document.getElementById("acct-used-count"),x=document.getElementById("acct-meter-fill"),I=document.getElementById("acct-meter-meta"),T=document.getElementById("acct-meter-track");if(_&&(_.textContent=e?"…":n?String(r):"—"),x){const E=n&&s>0?Math.min(100,Math.round(r/s*100)):0;x.style.width=`${E}%`}if(I)if(e)I.textContent="Checking…";else if(!n)I.textContent="Plan check failed";else if(s===0)I.textContent=`${r} of ${s}`;else{const E=Math.round(r/s*100);I.textContent=`${r} of ${s} · ${E}%`}T&&(e?T.setAttribute("aria-label","Checking usage…"):n?T.setAttribute("aria-label",`${r} of ${s} generations used`):T.setAttribute("aria-label","Usage unavailable")),mt()}function un(){if(Gl(),z.isVerified&&(pi()||!Rt())){id();return}const{count:t}=lr(),e=qs();t>=e&&!y.isRunning?tp(t,e):id()}function aw(){Gl()}async function np(t={}){const e=t.force===!0;if(!z.isVerified||!z.sessionToken){ce=Mn({isResolved:!0});return}ce={...ce,isLoading:!0,error:null};const n=localStorage.getItem(gs);if(!e&&n)try{const{data:i,email:r,ts:s,version:o}=JSON.parse(n);if(o===zu&&r===z.email&&Date.now()-s<300*1e3){ce={...i,isLoading:!1,isResolved:i.isResolved!==!1};return}}catch(i){console.warn("Failed to parse subscription cache:",i,"| raw value:",n)}try{const r=await(await fetch(`${vt}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:z.sessionToken,user_id:ft.userId})})).json();if(r.error){if(["unauthorized","invalid session","expired session"].some(o=>String(r.error).toLowerCase().includes(o))){Jh(),Vl();return}ce=Mn({isResolved:!1,error:r.error});return}ce=iw(r),localStorage.setItem(gs,JSON.stringify({version:zu,data:ce,email:z.email,ts:Date.now()}))}catch(i){console.error("fetchSubscription failed:",i),ce={...ce,isLoading:!1,isResolved:!1,error:i.message}}}function ip(){localStorage.removeItem(gs)}async function lw(t){if(!z.isVerified||!z.sessionToken){rp(),Ws();return}if(!Eh[t]){Ee("Invalid plan selected.","error");return}const e=document.getElementById(`checkout-btn-${t}`);e&&(e.disabled=!0,e.textContent="Redirecting…");try{const i=await(await fetch(`${vt}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:z.sessionToken,currency:Cl()})})).json();if(i.error||!i.url)throw new Error(i.error||"Failed to create checkout session");const{url:r}=i;window.location.href=r}catch(n){console.error("startCheckout failed:",n),e&&(e.disabled=!1,e.textContent="Subscribe"),Ee("Could not start checkout. Please try again.","error")}}async function cw(t){if(!z.isVerified||!z.sessionToken){Ws();return}const e=t||document.getElementById("manage-billing-btn"),n=e?e.textContent:"";e&&(e.disabled=!0,e.textContent="Loading…");try{const r=await(await fetch(`${vt}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:z.sessionToken})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to open billing portal");const{url:s}=r;window.location.href=s}catch(i){console.error("openCustomerPortal failed:",i),e&&(e.disabled=!1,e.textContent=n),Ee("Could not open billing portal. Please try again.","error")}}const Es=new Set;function uw(){Es.forEach(t=>t.abort()),Es.clear()}async function Ss(t,e,n,i={},r=[]){const o=new AbortController;Es.add(o);let a=!1;const l=setTimeout(()=>{a=!0,o.abort()},12e4);try{const u=await fetch(ky,{method:"POST",headers:{"Content-Type":"application/json",...ft.token?{Authorization:`Bearer ${ft.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:ft.userId,step:t,model:e,prompt:n,images:r,context:i})}),c=await u.text();let d={};try{d=c?JSON.parse(c):{}}catch{d={}}if(u.status===429){d.serverCount!==void 0&&(localStorage.setItem(Fn,JSON.stringify({count:d.serverCount,month:gn()})),un());const p=new Error(d.message||"Monthly usage limit reached. Upgrade to continue.");throw p.isUsageLimit=!0,p.pipelineStep=t,p}const f=wv(d,t);if(f)throw f;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(d),"content type:",typeof d.content),!u.ok)throw new Error(`${d.message||d.error||"BuildShip pipeline error"} (HTTP ${u.status})`);if(t==="generator")if(d.usage_status==="success"&&Number.isFinite(d.usage_count)){const p=gn();(d.usage_month||p)===p&&(localStorage.setItem(Fn,JSON.stringify({count:d.usage_count,month:p})),un())}else Q0(),un();let h=d.output||d.content;if(!h){const p=c?` (body: ${c.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${p}`)}return Array.isArray(h)&&(h=h.map(p=>typeof p=="string"?p:p.text||"").join("")),typeof h!="string"&&(h=JSON.stringify(h)),h}catch(u){if(u.name==="AbortError"){if(a)throw new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`);const c=new Error(`BuildShip ${t} request cancelled`);throw c.isPipelineCancel=!0,c}throw u instanceof TypeError?new Error(`BuildShip unreachable: ${u.message}`):u}finally{clearTimeout(l),Es.delete(o)}}let Va=!1;function dw(){const e=new URLSearchParams(window.location.search).get("checkout");return e==="success"?(window.history.replaceState({},"",window.location.pathname+window.location.hash),ip(),Va=!0):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname+window.location.hash),Ee("Checkout cancelled.","info")),e}function fw(){if(!Va)return;Va=!1;const t=ce.tier!=="free";Ee(t?"Subscription active! Your plan is live.":"Checkout complete — confirming your subscription. Check Manage billing if it does not update.",t?"success":"info")}function zs(){const t=z.isVerified&&!!z.email,e=ce.tier,n=t&&pi(),i=!t||Rt(),r=document.getElementById("subscription-tier-badge");if(r){const a=gl,l={free:"bg-gray-100 text-gray-600",professional:"bg-indigo-100 text-indigo-700",power:"bg-purple-100 text-purple-700",unresolved:"bg-red-50 text-red-600"};r.textContent=n?"Checking…":i?a[e]||"Free":"Plan unavailable",r.className=`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${i?l[e]||l.free:l.unresolved}`}const s=document.getElementById("upgrade-prompt");s&&s.classList.toggle("hidden",!t||n||!i||e!=="free");const o=document.getElementById("manage-billing-btn");o&&o.classList.toggle("hidden",!t||n||i&&e==="free"),hw(i?e:null),sw(),kl(),un(),Ep()}function hw(t){const e=["bg-gray-100","text-gray-500","cursor-default"];Object.entries({professional:{btnId:"checkout-btn-professional",defaultText:"Subscribe"},power:{btnId:"checkout-btn-power",defaultText:"Subscribe"}}).forEach(([r,{btnId:s,defaultText:o}])=>{const a=document.getElementById(s);a&&(r===t?(a.disabled=!0,a.textContent="Current plan",a.classList.add(...e)):(a.disabled=!1,a.textContent=o,a.classList.remove(...e)))});const i=document.getElementById("free-tier-current");i&&i.classList.toggle("hidden",t!=="free")}function pw(){document.querySelectorAll(".pm-card[data-tier]").forEach(t=>{const e=t.dataset.tier,n=av[e];if(!n)return;const i=t.querySelector("ul.pm-features");if(i){i.innerHTML="";for(const r of n){const s=document.createElement("li");s.textContent=r,i.appendChild(s)}}})}function Ga(){const t=Cl(),e=document.getElementById("pro-price"),n=document.getElementById("power-price"),i=document.getElementById("plans-pro-price"),r=document.getElementById("plans-power-price"),s=document.getElementById("pro-price-note"),o=document.getElementById("power-price-note"),a=document.getElementById("plans-pro-price-note"),l=document.getElementById("plans-power-price-note");e&&(e.textContent=Oi(Ni.professional,t)),n&&(n.textContent=Oi(Ni.power,t)),i&&(i.textContent=Oi(Ni.professional,t)),r&&(r.textContent=Oi(Ni.power,t));const u="billed monthly";s&&(s.textContent=u),o&&(o.textContent=u),a&&(a.textContent=u),l&&(l.textContent=u)}function di(){Ga();const t=document.getElementById("pricing-modal");t&&He(t),Uy().then(()=>Ga())}function rp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&We(e)}function Ee(t,e="info"){const n={success:"bg-green-600 text-white",error:"bg-red-600 text-white",warning:"bg-amber-500 text-white",info:"bg-gray-800 text-white"},i=document.createElement("div");i.className=`fixed bottom-6 left-1/2 -translate-x-1/2 px-5 py-3 rounded-lg text-sm font-medium shadow-lg z-50 transition-opacity duration-300 ${n[e]||n.info}`,i.textContent=t,document.body.appendChild(i),setTimeout(()=>{i.style.opacity="0",setTimeout(()=>i.remove(),300)},3500)}document.addEventListener("DOMContentLoaded",async()=>{rv(),hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),gw(),window.__heroField=X_(),window.__pipelineLogo=ny(),xh=Sy({onSubmit:or}),Oa=(async()=>{try{await H0(),dw(),await np()}catch(n){console.warn("Startup auth/subscription initialization failed:",n)}})(),await Oa,fw(),zs(),Ga(),pw(),await v0(),f0();const t=document.getElementById("flutterflow-endpoint-select");if(t){const n=_t();t.value=n}Nh(),Qh();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{en===2&&e.value.trim().length>0&&(Tl(),Ns())}),e.addEventListener("blur",()=>{const n=document.getElementById("walkthrough-modal");en===2&&n&&He(n)}),e.addEventListener("keydown",n=>{if(n.key==="Tab"){const i=document.getElementById("walkthrough-modal");en===2&&i&&setTimeout(()=>{He(i)},100)}})),window.addEventListener("commitStateChange",n=>{const{state:i}=n.detail;i===ee.PREPARING||i===ee.VALIDATING||i===ee.PUSHING?(Oe.phaseId||up(),sd(i)):(i===ee.SUCCESS||i===ee.ERROR)&&(sd(i),setTimeout(Jl,1e3))}),ic()});function gw(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function mw(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Nn),document.addEventListener("keydown",Nn))}function Nn(){const t=document.getElementById("preview-frame-container"),e=document.getElementById("main-stage-container"),n=document.getElementById("ready-state");t&&(t.style.display="none"),e&&e.classList.add("visible"),n&&n.classList.remove("hidden");const i=document.getElementById("welcome-video-player");i&&i.removeEventListener("click",Nn),document.removeEventListener("keydown",Nn),Nh()}let zi=null;async function vw(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++Ju,n=()=>e===Ju,i=await Te("flutterflow"),r=await Te("flutterflow_project_id");if(n()){if(!i){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const o=await new hi(i,"","main",_t()).listProjects();if(!n())return;if(!o||o.length===0){t.innerHTML='';return}t.innerHTML='',o.forEach(a=>{const l=document.createElement("option");l.value=a.id||a.projectId||"",l.textContent=a.name||a.projectName||`Project ${a.id}`,t.appendChild(l)}),r&&(t.value=r)}catch(s){if(!n())return;console.error("Failed to load projects for deploy:",s),t.innerHTML=''}}}function _w(){return document.getElementById("confirm-project-select")?.value?.trim()||null}function Kl(t,e,n,i=null){zi={codeInfo:t,checks:e,deps:n,bundlePlan:i},document.getElementById("confirm-file-name").textContent=t.fileName,document.getElementById("confirm-artifact-type").textContent=t.artifactType,document.getElementById("confirm-file-size").textContent=`${(t.content.length/1024).toFixed(1)} KB`,document.getElementById("confirm-line-count").textContent=i?`${i.fileEntries.length} files`:t.content.split(` -`).length,vw();const r=document.getElementById("confirm-deps-list"),s=document.getElementById("confirm-deps-section");n&&Object.keys(n).length>0?(r.innerHTML=Object.entries(n).map(([u,c])=>{const d=c?`at least ${Qt(c)}`:"version resolved from your project";return`
  • • ${Qt(u)}: ${d}
  • `}).join(""),s.classList.remove("hidden")):s.classList.add("hidden");const o=document.getElementById("confirm-warnings-list"),a=document.getElementById("confirm-warnings-section");e.warnings&&e.warnings.length>0?(o.innerHTML=e.warnings.map(u=>`
  • • ${Qt(u)}
  • `).join(""),a.classList.remove("hidden")):a.classList.add("hidden"),document.getElementById("confirm-code-preview").textContent=t.content,document.getElementById("code-preview-content").classList.add("hidden"),document.getElementById("code-preview-chevron").style.transform="rotate(0deg)";const l=document.getElementById("commit-confirm-modal");l&&He(l)}function sp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&We(e),zi=null}function yw(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&We(e);const n=["success-message","success-project-id","success-file-name","success-artifact-type","success-time","success-size"];for(const s of n){const o=document.getElementById(s);o&&(o.textContent="")}const i=document.getElementById("success-warnings-section");i&&i.classList.add("hidden");const r=document.getElementById("success-warnings-list");r&&(r.innerHTML="")}function op(t){const e=(m,v)=>{const S=document.getElementById(m);S&&(S.textContent=v||"")},n=t.metadata?.fileName||"",i=t.metadata?.projectId||"",r=t.metadata?.artifactType||"",s=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",i),e("success-file-name",n),e("success-artifact-type",r),e("success-time",s),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&i&&(u.href=`https://app.flutterflow.io/project/${i}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),f=t.unverified||[],h=t.approximate||[],p=t.warnings||[];(p.length>0||f.length>0||h.length>0)&&c&&d&&(d.innerHTML=[...f.map(m=>`
  • Not verified before deploying: ${q(String(m))}
  • `),...h.map(m=>`
  • Verified approximately: ${q(String(m))}
  • `),...p.map(([m,v])=>`
  • ${q(m)}: ${q(String(v))}
  • `)].join(""),c.classList.remove("hidden"));const g=document.getElementById("commit-success-modal");g&&He(g)}function ap(t){Jl(),B0(t),Yl(t,{heading:"Deploy failed",title:"FlutterFlow refused this deploy — nothing was confirmed written.",guidance:"Review the error and any per-file outcomes above, fix them in your code or in FlutterFlow, then deploy again. A refusal is definitive: no part of this deploy was applied, so retrying is safe once the problem is fixed."})}function Yl(t,{heading:e,title:n,guidance:i}){const r=t.targetIdentity||{},s=document.getElementById("commit-terminal-modal");if(!s)return!1;const o=(h,p)=>{const g=document.getElementById(h);g&&(g.textContent=p||"")};o("terminal-heading",e),o("terminal-title",n),o("terminal-message",t.error||t.message||"");const a=document.getElementById("terminal-identity-list");if(a){const h=[["Project",r.projectId||t.metadata?.projectId],["Endpoint",r.endpoint],["File",r.fileName||t.metadata?.fileName],["Artifact",r.artifactType||t.metadata?.artifactType]];a.innerHTML=h.map(([p,g])=>`
    ${q(p)}:${q(String(g??"—"))}
    `).join("")}const l=document.getElementById("terminal-file-outcomes");let u=t.errorMap;u&&!(u instanceof Map)&&(u=new Map(Object.entries(u))),l&&u&&u.size>0?(l.innerHTML=[...u.entries()].map(([h,p])=>`
  • ${q(h)}: ${q(El(p))}
  • `).join(""),l.classList.remove("hidden")):l&&l.classList.add("hidden");const c=document.getElementById("terminal-guidance");c&&(c.innerHTML=i);const d=document.getElementById("terminal-open-ff-link"),f=r.projectId||t.metadata?.projectId;return d&&(d.href=f?`https://app.flutterflow.io/project/${f}`:"https://app.flutterflow.io/"),He(s),!0}function lp(t){Yl(t,{heading:"Deploy partially applied",title:"Some custom classes reached FlutterFlow, but the deploy did not fully complete.",guidance:"The custom classes the runner confirmed are already in your project and are not lost. Review the per-file errors above, fix them in FlutterFlow or regenerate, then deploy again. Open the project to see exactly what landed."})}function cp(t){Yl(t,{heading:"Deploy outcome not yet known",title:"This browser stopped waiting before the FlutterFlow server reported a result.",guidance:"The deploy may still be finishing on the server — it was not cancelled. Open your FlutterFlow project and confirm whether the class landed before retrying, so you do not push a duplicate or build on top of an unknown state."})}function ww(t){t&&t.target!==t.currentTarget||We(document.getElementById("commit-terminal-modal"))}function bw(){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 rd={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}},Ew=[{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..."}],Oe={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&&(Eu(e,!0,"Deploying to FlutterFlow"),He(e)),this.set("prepare")},set(t,e=null){if(!(!rd[t]||t===this.phaseId)){if(!this.sequence.includes(t)){const n=this.sequence.indexOf("package");this.sequence.splice(n===-1?this.sequence.length:n,0,t)}this.phaseId=t,this.phaseStartedAt=Date.now(),this.substatus=e,this.liveSubstatus=!1,this.render(),this.timer&&clearInterval(this.timer),t!=="done"&&(this.timer=setInterval(()=>this.render(),500))}},setSubstatus(t){t&&(this.liveSubstatus=!0,this.substatus=t,this.render())},render(){const t=rd[this.phaseId];if(!t)return;const e=(Date.now()-this.phaseStartedAt)/1e3,n=t.start+(t.end-t.start)*(1-Math.exp(-e/25));if(this.phaseId==="provision"&&!this.liveSubstatus){const o=Ew.filter(a=>e>=a.after).pop();o&&(this.substatus=o.text)}const i=this.sequence.indexOf(this.phaseId),s=[`Step ${i===-1?1:i+1} of ${this.sequence.length}`];e>=5&&s.push(Sw(e)),dp(this.phaseId==="done"?100:n,t.message,s.join(" · "),this.substatus)},stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.phaseId=null;const t=document.getElementById("commit-progress-overlay");t&&(Eu(t,!1),We(t,{force:!0,restoreFocus:!1}))}};function Sw(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 up(t){Oe.start(t)}function Jl(){Oe.stop()}function dp(t,e,n,i=null){const r=document.getElementById("commit-progress-bar"),s=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");r&&(r.style.width=`${Math.round(t*10)/10}%`),s&&(s.textContent=e),o&&(o.textContent=n),a&&(a.textContent=i||"",a.classList.toggle("hidden",!i))}function sd(t){const e={[ee.PREPARING]:"prepare",[ee.VALIDATING]:"validate",[ee.PUSHING]:"project",[ee.SUCCESS]:"done"};if(t===ee.ERROR){Oe.timer&&clearInterval(Oe.timer),Oe.timer=null,dp(100,"Failed","Error occurred");return}const n=e[t];n&&Oe.set(n)}function xw(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===J.CODE_FILE):t.codeInfo?.codeType===J.CODE_FILE}let fp=!1;function hp(t){fp=t;const e=document.querySelector("#commit-confirm-modal button[data-deploy-confirm]");e&&(e.disabled=t),[...document.querySelectorAll("[data-deploy-start]"),...document.querySelectorAll("#btn-deploy-to-ff")].forEach(i=>{i.disabled=t})}function od(t){Jl(),hp(!1);const e=_h(t);e===Xe.COMMITTED?op(t):e===Xe.PARTIAL?lp(t):e===Xe.UNCONFIRMED?cp(t):ap(t)}async function Iw(){if(!zi){console.error("No pending commit data");return}if(fp){console.warn("Deploy already in flight; ignoring duplicate confirm.");return}const t=zi;if(zi=null,qi=_w(),sp(),hp(!0),up({withProvisioning:xw(t)}),t.bundlePlan){const o=await C0(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});qi=null,od(o);return}const{codeInfo:e}=t,{artifactType:n,artifactName:i,fileName:r}=Oh(),s=await k0(e.content,{artifactType:n,artifactName:i,fileName:r,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});qi=null,od(s)}window.runThinkingPipeline=or;window.toggleStep=F0;window.toggleSection=P0;window.selectWorkflowStep=nt;window.copyCode=R0;window.retryWithDifferentModel=L0;window.openApiKeysModal=Rl;window.closeApiKeysModal=Mh;window.openComposerSettings=t0;window.closeComposerSettings=n0;window.walkthroughConnectAccount=e0;window.closeWalkthroughModal=r0;window.openWalkthroughModal=i0;window.advanceWalkthrough=Tl;window.commitToFlutterFlow=I0;function kw(){const t=document.getElementById("pipeline-input");t&&t.focus()}function Cw(){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=kw;window.openModelSelector=Cw;window.handlePromptImageSelect=Dy;window.removePromptImage=jy;window.saveApiKeys=a0;window.validateFlutterFlowConnection=Ml;window.clearAllApiKeys=l0;window.toggleKeyVisibility=p0;window.handleWelcomeVideoEnd=mw;window.dismissWelcomeVideo=Nn;window.initiateCommitToFlutterFlow=N0;window.updateFlutterFlowCredentialStatus=D0;window.openCommitConfirmModal=Kl;window.closeCommitConfirmModal=sp;window.closeCommitSuccessModal=yw;window.closeCommitTerminalModal=ww;window.showCommitPartialModal=lp;window.showCommitUnconfirmedModal=cp;window.showCommitSuccessModal=op;window.showCommitFailureModal=ap;window.toggleCodePreview=bw;window.confirmCommitToFlutterFlow=Iw;window.runRefinement=Vh;window.regenerateFromPastedErrors=Gh;window.clearErrorInput=M0;window.setFlutterFlowEndpoint=Qy;window.getFlutterFlowEndpoint=_t;window.commitProgress=Oe;window.openSignInModal=Ws;window.closeSignInModal=Xh;window.handleMagicLinkRequest=q0;window.handleSignOut=z0;window.handleSendNewLink=K0;window.handleClearCache=Y0;window.handleDeleteAccount=J0;window.closeDeleteUnavailableModal=Z0;window.startCheckout=lw;window.openCustomerPortal=cw;window.openPricingModal=di;window.closePricingModal=rp;let jr=null,pp=null,On={1:"pending",2:"pending",3:"pending"},Zl=1,Xl=null;const Vs={1:"Prompt Architect",2:"Code Generator",3:"Code Review"},Aw={1:"Understanding your prompt",2:"Generating Dart code",3:"Running the code audit"},Pw={1:"Prompt understood",2:"Dart code generated",3:"Code audit complete"};function Gs(){return y.runId+=1,y.runId}function re(t){return t===void 0||t===y.runId}function Fw(){y.runId+=1}function Ql(t){return document.getElementById(`pdot-${t}`)}function Ka(t){const e=document.getElementById("btn-run-pipeline")||document.getElementById("hero-send");e&&(e.disabled=t,e.classList.toggle("is-busy",t),t?e.setAttribute("aria-busy","true"):e.removeAttribute("aria-busy"))}function Ks(t){const e=document.getElementById("pipeline-progress");e&&(e.dataset.runState=t)}function Rn(t,e){On[t]=e;const n=Ql(t);if(!n)return;n.dataset.state=e,n.disabled=e==="pending"||e==="skipped";const i=Vs[t],r={pending:"not started",active:"in progress",done:"complete",failed:"failed",skipped:"not run"};n.setAttribute("aria-label",`Step ${t} of 3, ${i}: ${r[e]||e}`),e==="active"?n.setAttribute("aria-current","step"):n.removeAttribute("aria-current")}function Rw(){return[1,2,3].filter(t=>On[t]==="done").length}function Ys(){const t=document.getElementById("pipeline-progress-fill");t&&(t.style.width=`${Rw()/3*100}%`);const e=document.getElementById("progress-stage-count");e&&(e.textContent=`Step ${Zl} of 3`)}function Js(t,{done:e=!1}={}){const n=document.getElementById("progress-title-text"),i=document.getElementById("progress-substep-text"),r=On[t],s=e||r==="done";if(n&&(n.textContent=s?Pw[t]:Aw[t]),i){const o=s?" — complete":r==="failed"?" — stopped":"";i.textContent=`Step ${t} of 3 — ${Vs[t]}${o}`}}function Tw(t){On[t]==="pending"||On[t]==="skipped"||(Xl=t,[1,2,3].forEach(e=>{const n=Ql(e);n&&n.setAttribute("aria-pressed",String(e===t))}),Js(t))}function ec(){Xl=null,[1,2,3].forEach(t=>{const e=Ql(t);e&&e.removeAttribute("aria-pressed")})}function gp(t){const e=document.getElementById("pipeline-note");e&&(e.textContent=t||"",e.hidden=!t)}function $w(t,e,n){re(n)&&gp(`${Vt(t)} did not answer. Continuing on ${Vt(e)}.`)}function tc(){const t=document.getElementById("pipeline-failure");if(!t)return;t.hidden=!0;const e=document.getElementById("pipeline-failure-actions");e&&e.replaceChildren()}const Mw=1120;function Lw(){const t=getComputedStyle(document.documentElement).getPropertyValue("--t-morph").trim(),e=Number.parseFloat(t);return Number.isFinite(e)&&e>0?e:Mw}let Qn=null,Ur=null;function Nw(){return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0}function dn(){if(Ur){try{Ur.cancel()}catch{}Ur=null}Qn&&(Qn.remove(),Qn=null),window.removeEventListener("resize",dn)}function mp(t,e){if(dn(),Nw()||!t||!e||!document.body||typeof Element.prototype.animate!="function")return;const n=t.getBoundingClientRect(),i=e.getBoundingClientRect();if(!n.width||!n.height||!i.width||!i.height)return;const r=document.createElement("div");r.className="composer-morph",r.setAttribute("aria-hidden","true"),r.style.cssText=`left:${i.left}px;top:${i.top}px;width:${i.width}px;height:${i.height}px;opacity:0;`,document.body.appendChild(r);const s=n.left+n.width/2-(i.left+i.width/2),o=n.top+n.height/2-(i.top+i.height/2),a=n.width/i.width,l=n.height/i.height,u=`translate(${s}px,${o}px) scale(${a},${l})`,c=r.animate([{transform:u,opacity:0,offset:0,easing:"cubic-bezier(.2,0,0,1)"},{transform:u,opacity:1,offset:.14,easing:"cubic-bezier(.4,0,.2,1)"},{transform:`translate(${s}px,${o}px) scale(${a*.93},${l*.93})`,opacity:1,offset:.28,easing:"cubic-bezier(.32,1.38,.5,1)"},{transform:"translate(0px,0px) scale(1,1)",opacity:1,offset:1}],{duration:Lw(),fill:"both"});Qn=r,Ur=c,window.addEventListener("resize",dn),c.onfinish=()=>{if(Qn!==r)return;const d=r.animate([{opacity:1},{opacity:0}],{duration:260,fill:"forwards"});d.onfinish=()=>{Qn===r&&dn()}}}function Ow(){const e=document.getElementById("composer")?.getBoundingClientRect();e&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{mp({getBoundingClientRect:()=>e},document.getElementById("main-stage-container"))})})}function Bw(){mp(document.getElementById("pipeline-progress"),document.getElementById("main-stage-container"))}window.addEventListener("hashchange",dn);window.addEventListener("popstate",dn);function Zs(t={}){const{prompt:e=null,runId:n}=t;if(!re(n))return;Qs(),nn(!0);const i=document.getElementById("pipeline-progress"),r=document.getElementById("results-view"),s=document.getElementById("ready-state");if(s&&s.classList.add("hidden"),r&&r.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),i&&i.classList.add("visible"),Ks("running"),e!==null){const a=document.getElementById("pipeline-submitted-prompt");a&&(a.textContent=e)}pp=Date.now();const o=document.getElementById("progress-elapsed");o&&(o.textContent="0s"),On={1:"pending",2:"pending",3:"pending"},ec(),tc(),gp(""),[1,2,3].forEach(a=>Rn(a,"pending")),Pt(1,n),Dw()}function Pt(t,e){re(e)&&(Zl=t,ec(),[1,2,3].forEach(n=>{n===t?Rn(n,"active"):nt&&Rn(n,"pending")}),Js(t),Ys())}function tn(t,e){re(e)&&(Rn(t,"done"),Xl===null&&Js(t,{done:!0}),Ys())}function vp(t,{stage:e=1,runId:n,retry:i=_p}={}){if(!re(n))return;Xs(),Qs(),dn(),Ks("failed"),nn(!0);const r=document.getElementById("pipeline-progress");r&&r.classList.add("visible");const s=document.getElementById("results-view");s&&s.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),Rn(e,"failed"),[1,2,3].forEach(p=>{p>e&&Rn(p,"pending")}),Zl=e,ec(),Js(e),Ys();const o=wh(t),a=document.getElementById("pipeline-failure"),l=document.getElementById("pipeline-failure-title"),u=document.getElementById("pipeline-failure-message"),c=document.getElementById("pipeline-failure-hint"),d=document.getElementById("pipeline-failure-actions");if(!a||!l||!u||!d)return;if(a.dataset.kind=o.kind,l.textContent=`${Vs[e]}: ${o.title}`,u.textContent=o.message,c){const p=o.detail&&o.detail!==o.message?o.detail:"";c.textContent=p,c.hidden=!p}d.replaceChildren();const f=[o.canUpgrade&&{id:"upgrade",label:"View plans",variant:"primary",onClick:()=>di()},o.canRetry&&{id:"retry",label:"Retry",variant:o.canUpgrade?"secondary":"primary",onClick:i},o.canEdit&&{id:"edit",label:"Edit prompt",variant:"secondary",onClick:Ya}].filter(Boolean);!o.canEdit&&!o.canRetry&&f.push({id:"edit",label:"Back to prompt",variant:"secondary",onClick:Ya}),f.forEach(p=>{const g=document.createElement("button");g.type="button",g.textContent=p.label,g.dataset.action=p.id,g.dataset.variant=p.variant,g.addEventListener("click",p.onClick),d.appendChild(g)}),a.hidden=!1;const h=d.querySelector("button");h&&h.focus({preventScroll:!0})}function Ya(){Fw(),uw(),y.isRunning=!1,Ka(!1),rn(),Ks("settled"),dn(),Xs(),Qs(),tc();const t=document.getElementById("pipeline-progress");t&&t.classList.remove("visible"),nn(!1);const e=document.getElementById("pipeline-input");e&&(y.submittedPrompt&&(e.value=y.submittedPrompt,e.dispatchEvent(new Event("input",{bubbles:!0}))),e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length))}function _p(){const t=document.getElementById("pipeline-input");t&&y.submittedPrompt&&(t.value=y.submittedPrompt,t.dispatchEvent(new Event("input",{bubbles:!0}))),Ne=y.submittedImages.slice(),cn(),tc(),or()}function Dw(){Xs(),jr=setInterval(()=>{const t=(Date.now()-pp)/1e3,e=document.getElementById("progress-elapsed");e&&(e.textContent=`${Math.floor(t)}s`)},250)}function Xs(){jr&&(clearInterval(jr),jr=null)}let Vi=null;function Qs(){Vi&&(clearTimeout(Vi),Vi=null)}function cr(){Xs(),Qs(),Ks("settled"),Ys();const t=document.getElementById("pipeline-progress-fill");Vi=setTimeout(()=>{Vi=null;const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function Tn(t,e=""){const n={pass:'',warning:'',fail:'',info:''};return``}function yp(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function jw(){return f_({bundle:y.artifactBundle,reviewResult:y.step3Result})}function Uw(t){return` +`;const o=nh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:s});Zs({runId:i}),Ft(2,i),nt(2),Ae(2,!0);const a=await Us(o,n,[],i);if(!re(i))return;y.step2Result=a,Bs(),tn(2,i);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),nt(3),Ft(3,i),Ae(3,!0);const c=await Hs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,Ds(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const f=Ls(y.step3Result);ur(u,f)}catch(s){if(console.error("Regeneration failed:",s),!re(i))return;const o=Ms(s,{architect:2,generator:2,review:3});s.isUsageLimit&&un(),nt(o),Ae(o,!1),vp(s,{stage:o,runId:i,retry:()=>Kh(t,e)}),bs(o,"error")}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function D0(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const n=await Te("flutterflow"),i=await Te("flutterflow_project_id");n&&i?(t.className="w-2 h-2 rounded-full bg-green-500",e.textContent="FlutterFlow credentials configured",e.className="text-green-600"):n||i?(t.className="w-2 h-2 rounded-full bg-yellow-500",e.textContent="FlutterFlow credentials incomplete",e.className="text-yellow-600"):(t.className="w-2 h-2 rounded-full bg-red-500",e.textContent="FlutterFlow credentials not configured",e.className="text-red-600")}async function Yh(t){try{const e=await fetch(`${_t}/auth/send-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:t})});if(!e.ok)throw new Error(`Failed to send magic link: HTTP ${e.status}`);return e.json()}catch(e){throw console.error("sendMagicLink failed:",{email:t,message:e.message,stack:e.stack}),e}}async function j0(t){try{const n=await(await fetch(`${_t}/auth/verify-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})})).json();if(n.error||!n.email||!n.sessionToken)throw new Error(n.error||"Invalid or expired link");return n}catch(e){throw console.error("verifyMagicLink failed:",{message:e.message,stack:e.stack}),e}}async function U0(t){try{const e=await fetch(`${_t}/auth/refresh-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:t})});if(!e.ok)return console.error("refreshSession: non-OK response",{url:`${_t}/auth/refresh-session`,status:e.status}),null;const n=await e.json();return n.error||!n.email||!n.sessionToken?(console.warn("refreshSession: validation failed",{error:n.error,hasEmail:!!n.email,hasToken:!!n.sessionToken}),null):n}catch(e){return console.error("refreshSession: fetch failed",{url:`${_t}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function td(t,e){const n=Zh(),i=(z.email||n.email)!==t;z.email=t,z.sessionToken=e,z.isVerified=!0,ce=Mn({isLoading:!0}),localStorage.setItem(hs,JSON.stringify({email:t,sessionToken:e})),i&&ip()}function Jh(){z.email=null,z.sessionToken=null,z.isVerified=!1,ce=Mn({isResolved:!0}),localStorage.removeItem(hs),localStorage.removeItem(gs)}function Zh(){try{const t=localStorage.getItem(hs);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(hs),{email:null,sessionToken:null}}}async function H0(){const e=new URLSearchParams(window.location.search).get("token");if(e){window.history.replaceState({},"",window.location.pathname+window.location.hash);try{const{email:n,sessionToken:i}=await j0(e);td(n,i),Xh();const r=nd();r&&!window.location.hash&&(window.location.hash=r)}catch(n){nd();const i=n.message||"Sign-in link invalid or expired.";Ee(i,"error"),Ws(),Jn(i,"error")}}else{const{email:n,sessionToken:i}=Zh();if(n&&i){const r=await U0(i);r?td(r.email,r.sessionToken):Jh()}}Vl()}function W0(){try{localStorage.setItem(Na,JSON.stringify({hash:window.location.hash||"#home",ts:Date.now()}))}catch(t){console.warn("rememberSignInReturnSurface: failed to persist return surface:",t)}}function nd(){try{const t=localStorage.getItem(Na);if(localStorage.removeItem(Na),!t)return null;const{hash:e,ts:n}=JSON.parse(t);return!e||typeof n!="number"||Date.now()-n>Iy?null:e}catch(t){return console.warn("consumeSignInReturnSurface: failed to read return surface:",t),null}}function Ws(){const t=document.getElementById("signin-modal");if(!t)return;W0(),document.getElementById("signin-email-input")?.removeAttribute("aria-invalid"),Jn(""),He(t)}function Xh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&We(e)}function Jn(t,e){const n=document.getElementById("signin-message");n&&(n.textContent=t||"",n.classList.remove("signin-message-success","signin-message-error"),e&&n.classList.add(`signin-message-${e}`))}async function q0(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),n=Fs(t?.value);if(!n||!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(n)||n.length>254){t?.setAttribute("aria-invalid","true"),Jn("Please enter a valid email address.","error");return}t?.removeAttribute("aria-invalid"),e&&(e.disabled=!0,e.textContent="Sending…");const r=uh(n);r&&Jn(r,"error");try{const s=await Yh(n),o=s?.code===ch;t&&!o&&(t.value=""),t?.setAttribute("aria-invalid",String(o)),Jn(dh(s,n),o?"error":"success"),e&&(e.disabled=!1,e.textContent=o?"Send Sign-in Link":"Sent!",o||setTimeout(()=>{e.textContent==="Sent!"&&(e.textContent="Send Sign-in Link")},2500))}catch(s){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:n,err:s}),Jn("Something went wrong. Please try again.","error"),e&&(e.disabled=!1,e.textContent="Send Sign-in Link")}}function z0(){z.email=null,z.sessionToken=null,z.isVerified=!1,ce=Mn({isResolved:!0}),$_({storage:window.localStorage,onIdentityChanged:Vl,onPlanChanged:zs})}const V0=M_({sendLink:Yh,getEmail:()=>z.email||"",onState:G0});function G0(t){const e=document.getElementById("send-new-link-btn"),n=document.getElementById("send-new-link-msg");if(!e||!n)return;if(t.status==="pending"){e.disabled=!0,e.textContent="Sending…",n.className="acct-access-msg",n.textContent="Sending a fresh sign-in link…";return}if(t.status==="sent"){e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg",n.textContent=dh(t.data,z.email||"")||"Link sent — check your email.";return}e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg error";const i=t.error?.message?`Couldn't send a link right now. ${t.error.message}`:"Couldn't send a link right now. Please try again.";n.textContent=i}async function K0(){await V0()}function Y0(){const t=R_(window.localStorage),e=t.length?`Cleared disposable UI caches: ${t.join(", ")}.`:"Nothing disposable to clear.";Ee(`${e} Your run count, identity and stored keys are kept.`,"info")}function J0(){const t=document.getElementById("delete-unavailable-modal");t&&He(t,{trigger:document.activeElement})}function Z0(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("delete-unavailable-modal");e&&We(e)}function Vl(){const t=z.isVerified&&!!z.email,e=document.getElementById("auth-signedout"),n=document.getElementById("auth-signedin"),i=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),n&&n.classList.toggle("hidden",!t),i&&i.classList.toggle("hidden",t);const r=document.getElementById("auth-user-email");r&&(r.textContent=z.email||"");const s=document.getElementById("access-signed-email");s&&(s.textContent=z.email||""),aw(),zs()}async function Qh(){try{if(typeof FingerprintJS>"u"){console.warn("resolveIdentity: FingerprintJS not loaded, skipping");return}const e=await(await FingerprintJS.load()).get(),n=e.visitorId,i=await fetch(Py,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fingerprint:e.visitorId,cookie_id:n})});if(!i.ok)throw new Error(`Identity check HTTP ${i.status}`);const r=await i.json();if(ft.userId=r.user_id,ft.token=r.identity_token||null,ft.status=r.status,ft.resolved=!0,sessionStorage.setItem(Cy,r.user_id),ft.token&&sessionStorage.setItem(Ay,ft.token),r.usage_count!==void 0){const s=gn(),a=(r.usage_month||s)===s?r.usage_count:0;localStorage.setItem(Fn,JSON.stringify({count:a,month:s})),un()}console.log(`Identity resolved: ${r.status} (${r.user_id.slice(0,8)}...) usage: ${r.usage_count??"n/a"}`)}catch(t){console.error("resolveIdentity failed:",t)}}let Wo=null;function X0(t=5e3){return ft.resolved?Promise.resolve():(Wo||(Wo=Qh().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([Wo,new Promise(e=>setTimeout(e,t))]))}function ep(){const t=gn();try{const e=localStorage.getItem(Fn);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Fn,month:t,err:e}),localStorage.removeItem(Fn),{count:0,month:t}}}function gn(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function lr(){const t=ep();return t.month!==gn()?{count:0,month:gn()}:t}function Q0(){const e={count:lr().count+1,month:gn()};return localStorage.setItem(Fn,JSON.stringify(e)),e}function pi(){return!!ce.isLoading}function Tt(){return!!ce.isResolved}function ew(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(ps,e)?e:null}function tw(t){return t&&Object.entries(Eh).find(([,e])=>e===t)?.[0]||null}function Cr(...t){return t.find(e=>e!=null&&e!=="")}function nw(...t){return t.find(e=>e&&typeof e=="object")||{}}function iw(t){const e=t.data&&typeof t.data=="object"?t.data:t,n=nw(e.subscription,e.stripeSubscription,e.currentSubscription,e.customer?.subscriptions?.data?.[0],e.subscriptions?.data?.[0],e.subscriptions?.[0]),i=e.metadata||n.metadata||e.customer?.metadata||{},r=Cr(e.priceId,e.price_id,e.stripePriceId,e.stripe_price_id,n.priceId,n.price_id,n.plan?.id,n.price?.id,n.items?.data?.[0]?.price?.id,n.items?.[0]?.price?.id,n.lines?.data?.[0]?.price?.id),s=Cr(e.status,e.subscriptionStatus,e.subscription_status,n.status,"none"),o=ew(Cr(e.tier,e.plan,e.planId,e.plan_id,e.subscriptionTier,e.subscription_tier,e.product,e.productName,n.tier,n.plan,i.tier,i.plan)),a=Fy.has(String(s).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||tw(r)||(a||l?"professional":"free");return Mn({tier:u,status:s,periodEnd:Cr(e.periodEnd,e.currentPeriodEnd,e.current_period_end,n.current_period_end,n.periodEnd,null),isResolved:!0})}function qs(){return ps[ce.tier]??ps.free}async function rw(){if(z.isVerified&&(!Tt()||pi())&&(await np({force:!0}),zs()),z.isVerified&&!Tt())return Ee("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=lr(),e=qs();if(t>=e)return tp(t,e,{openModal:!0}),!1;const n=Math.floor(e*.8);if(t>=n){const i=e-t;Ee(`${i} run${i===1?"":"s"} remaining this month.`,"warning")}return!0}function id(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function tp(t,e,n={}){nn(!0);const i=document.getElementById("walkthrough-modal");i&&We(i,{restoreFocus:!1});const r=document.getElementById("ready-state");r&&r.classList.add("hidden");const s=document.getElementById("preview-frame-container");s&&(s.style.display="none");const o=document.getElementById("main-stage-container");o&&o.classList.add("visible");const a=document.getElementById("results-view");a&&a.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar");const l=document.getElementById("pipeline-progress");l&&l.classList.remove("visible");const u=document.getElementById("paywall-exhausted");if(!u){Ee(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),di();return}const c=document.getElementById("paywall-exhausted-text");if(c){const f=ce.tier;f==="free"?c.textContent=`You've used all ${e} free generations this month. Upgrade to Pro for 50 generations/month and access to all AI models.`:c.textContent=`You've used all ${e} generations this month on your ${f} plan. Your limit resets next month.`}const d=document.getElementById("paywall-signin-btn");d&&d.classList.toggle("hidden",z.isVerified),u.classList.remove("hidden"),n.openModal&&di()}function za(t){return ce.tier==="free"&&Nr.includes(t)?ms:t}function sw(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const n=ce.tier,r=!(z.isVerified&&!Tt())&&n==="free";Array.from(e.options).forEach(o=>{const a=Gt(o.value),l=Nr.includes(o.value);o.textContent=l&&r?`${a} (PRO)`:a,o.disabled=!1}),r&&Nr.includes(e.value)&&(e.value=ms),e.disabled=!1,qu.has(e)||(e.addEventListener("change",()=>{Tt()&&ce.tier==="free"&&Nr.includes(e.value)&&(e.value=ms,di()),qa(e.value),kl()}),qu.add(e));let s=document.getElementById("model-selector-free-notice");r?(s||(s=document.createElement("p"),s.id="model-selector-free-notice",s.className="text-xs text-gray-400 mt-1",t.appendChild(s)),s.innerHTML='Free plan — Gemini only. '):s&&s.remove(),qa(e.value)}function Gl(){const t=z.isVerified&&!!z.email,e=t&&pi(),n=!t||Tt(),i=lr(),r=n?i.count:0,s=n?qs():0,o=Math.max(0,s-r),a=`${r} / ${s} runs this month`,l=gl,u=n?ce.tier||"free":null,c=document.getElementById("topbar-credits-count");c&&(e?c.textContent="…":n?c.textContent=String(o):c.textContent="—");const d=document.getElementById("credits-balance");d&&(e?d.textContent="Checking plan…":n?d.textContent=a:d.textContent="Plan check failed");const f=document.getElementById("usage-dialog-tier");f&&(e?f.textContent="Checking…":n?f.textContent=l[u]||"Free":f.textContent="Unavailable");const h=document.getElementById("usage-dialog-status");h&&(e?h.textContent="Verifying your subscription…":n?h.textContent="Runs reset at the start of each month.":h.textContent="Could not verify your subscription. Try again or sign out.");const p=document.getElementById("usage-counter");if(p)if(e&&t)p.textContent="Checking plan…",p.className="text-xs text-gray-500";else if(!n&&t)p.textContent="Plan check failed",p.className="text-xs text-red-600 font-medium";else{p.textContent=a;const g=s>0?r/s:0;p.className=g>=1?"text-xs text-red-600 font-medium":g>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500"}if(!t){const g=document.getElementById("guest-usage-text");if(g){const m=ep(),v=m.month===gn()?m.count??0:0;g.textContent=`${v} / ${ps.free} generations used`}}ow()}function ow(){if(!(z.isVerified&&!!z.email))return;const e=pi(),n=Tt(),i=lr(),r=n?i.count:0,s=n?qs():0,o=Math.max(0,s-r),a=n?ce.tier||"free":null,l={free:"Free",professional:"Pro",power:"Power"}[a]||"Free",u=z.email||"",c=u.split("@")[0]||u,d=document.getElementById("acct-avatar");d&&(d.textContent=(u[0]||"?").toUpperCase());const f=document.getElementById("acct-name");f&&(f.textContent=c||"—");const h=document.getElementById("acct-plan-tier"),p=document.getElementById("acct-plan-price"),g=document.getElementById("acct-plan-note"),m=document.getElementById("acct-renewal");if(h&&(h.textContent=e?"Checking…":n?l:"Plan unavailable"),p)if(e)p.textContent="—";else if(!n)p.textContent="—";else if(a==="free")p.textContent="$0 / month";else{const E=Oi(Ni[a]??0,Cl());p.textContent=`${E} / month`}if(g&&(e?g.textContent="Verifying your subscription…":n?a==="free"?g.textContent="No subscription. Upgrade for more generations.":g.textContent="billed monthly through Stripe":g.textContent="Could not verify your subscription. Check billing or sign out."),m){const E=Date.parse(ce.periodEnd||""),P=n&&a!=="free"&&!!ce.periodEnd&&!Number.isNaN(E);if(e)m.textContent="";else if(!n)m.textContent="";else if(a==="free")m.textContent="";else if(P){const $=new Date(E).toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"});m.textContent=`Renews ${$} · reset at the start of each month.`}else m.textContent="Renewal date is not available for this period."}const v=document.getElementById("acct-left-count"),S=document.getElementById("acct-left-limit"),b=document.getElementById("acct-reset-note");v&&(v.textContent=e?"…":n?String(o):"—"),S&&(S.textContent=e?"…":n?String(s):"—"),b&&(e?b.textContent="Checking plan…":n?b.textContent="Runs reset at the start of each month.":b.textContent="Plan check failed. Refresh or manage billing.");const _=document.getElementById("acct-used-count"),x=document.getElementById("acct-meter-fill"),I=document.getElementById("acct-meter-meta"),T=document.getElementById("acct-meter-track");if(_&&(_.textContent=e?"…":n?String(r):"—"),x){const E=n&&s>0?Math.min(100,Math.round(r/s*100)):0;x.style.width=`${E}%`}if(I)if(e)I.textContent="Checking…";else if(!n)I.textContent="Plan check failed";else if(s===0)I.textContent=`${r} of ${s}`;else{const E=Math.round(r/s*100);I.textContent=`${r} of ${s} · ${E}%`}T&&(e?T.setAttribute("aria-label","Checking usage…"):n?T.setAttribute("aria-label",`${r} of ${s} generations used`):T.setAttribute("aria-label","Usage unavailable")),vt()}function un(){if(Gl(),z.isVerified&&(pi()||!Tt())){id();return}const{count:t}=lr(),e=qs();t>=e&&!y.isRunning?tp(t,e):id()}function aw(){Gl()}async function np(t={}){const e=t.force===!0;if(!z.isVerified||!z.sessionToken){ce=Mn({isResolved:!0});return}ce={...ce,isLoading:!0,error:null};const n=localStorage.getItem(gs);if(!e&&n)try{const{data:i,email:r,ts:s,version:o}=JSON.parse(n);if(o===zu&&r===z.email&&Date.now()-s<300*1e3){ce={...i,isLoading:!1,isResolved:i.isResolved!==!1};return}}catch(i){console.warn("Failed to parse subscription cache:",i,"| raw value:",n)}try{const r=await(await fetch(`${_t}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:z.sessionToken,user_id:ft.userId})})).json();if(r.error){if(["unauthorized","invalid session","expired session"].some(o=>String(r.error).toLowerCase().includes(o))){Jh(),Vl();return}ce=Mn({isResolved:!1,error:r.error});return}ce=iw(r),localStorage.setItem(gs,JSON.stringify({version:zu,data:ce,email:z.email,ts:Date.now()}))}catch(i){console.error("fetchSubscription failed:",i),ce={...ce,isLoading:!1,isResolved:!1,error:i.message}}}function ip(){localStorage.removeItem(gs)}async function lw(t){if(!z.isVerified||!z.sessionToken){rp(),Ws();return}if(!Eh[t]){Ee("Invalid plan selected.","error");return}const e=document.getElementById(`checkout-btn-${t}`);e&&(e.disabled=!0,e.textContent="Redirecting…");try{const i=await(await fetch(`${_t}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:z.sessionToken,currency:Cl()})})).json();if(i.error||!i.url)throw new Error(i.error||"Failed to create checkout session");const{url:r}=i;window.location.href=r}catch(n){console.error("startCheckout failed:",n),e&&(e.disabled=!1,e.textContent="Subscribe"),Ee("Could not start checkout. Please try again.","error")}}async function cw(t){if(!z.isVerified||!z.sessionToken){Ws();return}const e=t||document.getElementById("manage-billing-btn"),n=e?e.textContent:"";e&&(e.disabled=!0,e.textContent="Loading…");try{const r=await(await fetch(`${_t}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:z.sessionToken})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to open billing portal");const{url:s}=r;window.location.href=s}catch(i){console.error("openCustomerPortal failed:",i),e&&(e.disabled=!1,e.textContent=n),Ee("Could not open billing portal. Please try again.","error")}}const Es=new Set;function uw(){Es.forEach(t=>t.abort()),Es.clear()}async function Ss(t,e,n,i={},r=[]){const o=new AbortController;Es.add(o);let a=!1;const l=setTimeout(()=>{a=!0,o.abort()},12e4);try{const u=await fetch(ky,{method:"POST",headers:{"Content-Type":"application/json",...ft.token?{Authorization:`Bearer ${ft.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:ft.userId,step:t,model:e,prompt:n,images:r,context:i})}),c=await u.text();let d={};try{d=c?JSON.parse(c):{}}catch{d={}}if(u.status===429){d.serverCount!==void 0&&(localStorage.setItem(Fn,JSON.stringify({count:d.serverCount,month:gn()})),un());const p=new Error(d.message||"Monthly usage limit reached. Upgrade to continue.");throw p.isUsageLimit=!0,p.pipelineStep=t,p}const f=wv(d,t);if(f)throw f;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(d),"content type:",typeof d.content),!u.ok)throw new Error(`${d.message||d.error||"BuildShip pipeline error"} (HTTP ${u.status})`);if(t==="generator")if(d.usage_status==="success"&&Number.isFinite(d.usage_count)){const p=gn();(d.usage_month||p)===p&&(localStorage.setItem(Fn,JSON.stringify({count:d.usage_count,month:p})),un())}else Q0(),un();let h=d.output||d.content;if(!h){const p=c?` (body: ${c.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${p}`)}return Array.isArray(h)&&(h=h.map(p=>typeof p=="string"?p:p.text||"").join("")),typeof h!="string"&&(h=JSON.stringify(h)),h}catch(u){if(u.name==="AbortError"){if(a)throw new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`);const c=new Error(`BuildShip ${t} request cancelled`);throw c.isPipelineCancel=!0,c}throw u instanceof TypeError?new Error(`BuildShip unreachable: ${u.message}`):u}finally{clearTimeout(l),Es.delete(o)}}let Va=!1;function dw(){const e=new URLSearchParams(window.location.search).get("checkout");return e==="success"?(window.history.replaceState({},"",window.location.pathname+window.location.hash),ip(),Va=!0):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname+window.location.hash),Ee("Checkout cancelled.","info")),e}function fw(){if(!Va)return;Va=!1;const t=ce.tier!=="free";Ee(t?"Subscription active! Your plan is live.":"Checkout complete — confirming your subscription. Check Manage billing if it does not update.",t?"success":"info")}function zs(){const t=z.isVerified&&!!z.email,e=ce.tier,n=t&&pi(),i=!t||Tt(),r=document.getElementById("subscription-tier-badge");if(r){const a=gl,l={free:"bg-gray-100 text-gray-600",professional:"bg-indigo-100 text-indigo-700",power:"bg-purple-100 text-purple-700",unresolved:"bg-red-50 text-red-600"};r.textContent=n?"Checking…":i?a[e]||"Free":"Plan unavailable",r.className=`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${i?l[e]||l.free:l.unresolved}`}const s=document.getElementById("upgrade-prompt");s&&s.classList.toggle("hidden",!t||n||!i||e!=="free");const o=document.getElementById("manage-billing-btn");o&&o.classList.toggle("hidden",!t||n||i&&e==="free"),hw(i?e:null),sw(),kl(),un(),Ep()}function hw(t){const e=["bg-gray-100","text-gray-500","cursor-default"];Object.entries({professional:{btnId:"checkout-btn-professional",defaultText:"Subscribe"},power:{btnId:"checkout-btn-power",defaultText:"Subscribe"}}).forEach(([r,{btnId:s,defaultText:o}])=>{const a=document.getElementById(s);a&&(r===t?(a.disabled=!0,a.textContent="Current plan",a.classList.add(...e)):(a.disabled=!1,a.textContent=o,a.classList.remove(...e)))});const i=document.getElementById("free-tier-current");i&&i.classList.toggle("hidden",t!=="free")}function pw(){document.querySelectorAll(".pm-card[data-tier]").forEach(t=>{const e=t.dataset.tier,n=av[e];if(!n)return;const i=t.querySelector("ul.pm-features");if(i){i.innerHTML="";for(const r of n){const s=document.createElement("li");s.textContent=r,i.appendChild(s)}}})}function Ga(){const t=Cl(),e=document.getElementById("pro-price"),n=document.getElementById("power-price"),i=document.getElementById("plans-pro-price"),r=document.getElementById("plans-power-price"),s=document.getElementById("pro-price-note"),o=document.getElementById("power-price-note"),a=document.getElementById("plans-pro-price-note"),l=document.getElementById("plans-power-price-note");e&&(e.textContent=Oi(Ni.professional,t)),n&&(n.textContent=Oi(Ni.power,t)),i&&(i.textContent=Oi(Ni.professional,t)),r&&(r.textContent=Oi(Ni.power,t));const u="billed monthly";s&&(s.textContent=u),o&&(o.textContent=u),a&&(a.textContent=u),l&&(l.textContent=u)}function di(){Ga();const t=document.getElementById("pricing-modal");t&&He(t),Uy().then(()=>Ga())}function rp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&We(e)}function Ee(t,e="info"){const n={success:"bg-green-600 text-white",error:"bg-red-600 text-white",warning:"bg-amber-500 text-white",info:"bg-gray-800 text-white"},i=document.createElement("div");i.className=`fixed bottom-6 left-1/2 -translate-x-1/2 px-5 py-3 rounded-lg text-sm font-medium shadow-lg z-50 transition-opacity duration-300 ${n[e]||n.info}`,i.textContent=t,document.body.appendChild(i),setTimeout(()=>{i.style.opacity="0",setTimeout(()=>i.remove(),300)},3500)}document.addEventListener("DOMContentLoaded",async()=>{rv(),hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),gw(),window.__heroField=X_(),window.__pipelineLogo=ny(),xh=Sy({onSubmit:or}),Oa=(async()=>{try{await H0(),dw(),await np()}catch(n){console.warn("Startup auth/subscription initialization failed:",n)}})(),await Oa,fw(),zs(),Ga(),pw(),await v0(),f0();const t=document.getElementById("flutterflow-endpoint-select");if(t){const n=yt();t.value=n}Nh(),Qh();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{en===2&&e.value.trim().length>0&&(Tl(),Ns())}),e.addEventListener("blur",()=>{const n=document.getElementById("walkthrough-modal");en===2&&n&&He(n)}),e.addEventListener("keydown",n=>{if(n.key==="Tab"){const i=document.getElementById("walkthrough-modal");en===2&&i&&setTimeout(()=>{He(i)},100)}})),window.addEventListener("commitStateChange",n=>{const{state:i}=n.detail;i===ee.PREPARING||i===ee.VALIDATING||i===ee.PUSHING?(Oe.phaseId||up(),sd(i)):(i===ee.SUCCESS||i===ee.ERROR)&&(sd(i),setTimeout(Jl,1e3))}),ic()});function gw(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function mw(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Nn),document.addEventListener("keydown",Nn))}function Nn(){const t=document.getElementById("preview-frame-container"),e=document.getElementById("main-stage-container"),n=document.getElementById("ready-state");t&&(t.style.display="none"),e&&e.classList.add("visible"),n&&n.classList.remove("hidden");const i=document.getElementById("welcome-video-player");i&&i.removeEventListener("click",Nn),document.removeEventListener("keydown",Nn),Nh()}let zi=null;async function vw(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++Ju,n=()=>e===Ju,i=await Te("flutterflow"),r=await Te("flutterflow_project_id");if(n()){if(!i){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const o=await new hi(i,"","main",yt()).listProjects();if(!n())return;if(!o||o.length===0){t.innerHTML='';return}t.innerHTML='',o.forEach(a=>{const l=document.createElement("option");l.value=a.id||a.projectId||"",l.textContent=a.name||a.projectName||`Project ${a.id}`,t.appendChild(l)}),r&&(t.value=r)}catch(s){if(!n())return;console.error("Failed to load projects for deploy:",s),t.innerHTML=''}}}function _w(){return document.getElementById("confirm-project-select")?.value?.trim()||null}function Kl(t,e,n,i=null){zi={codeInfo:t,checks:e,deps:n,bundlePlan:i},document.getElementById("confirm-file-name").textContent=t.fileName,document.getElementById("confirm-artifact-type").textContent=t.artifactType,document.getElementById("confirm-file-size").textContent=`${(t.content.length/1024).toFixed(1)} KB`,document.getElementById("confirm-line-count").textContent=i?`${i.fileEntries.length} files`:t.content.split(` +`).length,vw();const r=document.getElementById("confirm-deps-list"),s=document.getElementById("confirm-deps-section");n&&Object.keys(n).length>0?(r.innerHTML=Object.entries(n).map(([u,c])=>{const d=c?`at least ${Qt(c)}`:"version resolved from your project";return`
  • • ${Qt(u)}: ${d}
  • `}).join(""),s.classList.remove("hidden")):s.classList.add("hidden");const o=document.getElementById("confirm-warnings-list"),a=document.getElementById("confirm-warnings-section");e.warnings&&e.warnings.length>0?(o.innerHTML=e.warnings.map(u=>`
  • • ${Qt(u)}
  • `).join(""),a.classList.remove("hidden")):a.classList.add("hidden"),document.getElementById("confirm-code-preview").textContent=t.content,document.getElementById("code-preview-content").classList.add("hidden"),document.getElementById("code-preview-chevron").style.transform="rotate(0deg)";const l=document.getElementById("commit-confirm-modal");l&&He(l)}function sp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&We(e),zi=null}function yw(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&We(e);const n=["success-message","success-project-id","success-file-name","success-artifact-type","success-time","success-size"];for(const s of n){const o=document.getElementById(s);o&&(o.textContent="")}const i=document.getElementById("success-warnings-section");i&&i.classList.add("hidden");const r=document.getElementById("success-warnings-list");r&&(r.innerHTML="")}function op(t){const e=(m,v)=>{const S=document.getElementById(m);S&&(S.textContent=v||"")},n=t.metadata?.fileName||"",i=t.metadata?.projectId||"",r=t.metadata?.artifactType||"",s=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",i),e("success-file-name",n),e("success-artifact-type",r),e("success-time",s),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&i&&(u.href=`https://app.flutterflow.io/project/${i}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),f=t.unverified||[],h=t.approximate||[],p=t.warnings||[];(p.length>0||f.length>0||h.length>0)&&c&&d&&(d.innerHTML=[...f.map(m=>`
  • Not verified before deploying: ${q(String(m))}
  • `),...h.map(m=>`
  • Verified approximately: ${q(String(m))}
  • `),...p.map(([m,v])=>`
  • ${q(m)}: ${q(String(v))}
  • `)].join(""),c.classList.remove("hidden"));const g=document.getElementById("commit-success-modal");g&&He(g)}function ap(t){Jl(),B0(t),Yl(t,{heading:"Deploy failed",title:"FlutterFlow refused this deploy — nothing was confirmed written.",guidance:"Review the error and any per-file outcomes above, fix them in your code or in FlutterFlow, then deploy again. A refusal is definitive: no part of this deploy was applied, so retrying is safe once the problem is fixed."})}function Yl(t,{heading:e,title:n,guidance:i}){const r=t.targetIdentity||{},s=document.getElementById("commit-terminal-modal");if(!s)return!1;const o=(h,p)=>{const g=document.getElementById(h);g&&(g.textContent=p||"")};o("terminal-heading",e),o("terminal-title",n),o("terminal-message",t.error||t.message||"");const a=document.getElementById("terminal-identity-list");if(a){const h=[["Project",r.projectId||t.metadata?.projectId],["Endpoint",r.endpoint],["File",r.fileName||t.metadata?.fileName],["Artifact",r.artifactType||t.metadata?.artifactType]];a.innerHTML=h.map(([p,g])=>`
    ${q(p)}:${q(String(g??"—"))}
    `).join("")}const l=document.getElementById("terminal-file-outcomes");let u=t.errorMap;u&&!(u instanceof Map)&&(u=new Map(Object.entries(u))),l&&u&&u.size>0?(l.innerHTML=[...u.entries()].map(([h,p])=>`
  • ${q(h)}: ${q(El(p))}
  • `).join(""),l.classList.remove("hidden")):l&&l.classList.add("hidden");const c=document.getElementById("terminal-guidance");c&&(c.innerHTML=i);const d=document.getElementById("terminal-open-ff-link"),f=r.projectId||t.metadata?.projectId;return d&&(d.href=f?`https://app.flutterflow.io/project/${f}`:"https://app.flutterflow.io/"),He(s),!0}function lp(t){Yl(t,{heading:"Deploy partially applied",title:"Some custom classes reached FlutterFlow, but the deploy did not fully complete.",guidance:"The custom classes the runner confirmed are already in your project and are not lost. Review the per-file errors above, fix them in FlutterFlow or regenerate, then deploy again. Open the project to see exactly what landed."})}function cp(t){Yl(t,{heading:"Deploy outcome not yet known",title:"This browser stopped waiting before the FlutterFlow server reported a result.",guidance:"The deploy may still be finishing on the server — it was not cancelled. Open your FlutterFlow project and confirm whether the class landed before retrying, so you do not push a duplicate or build on top of an unknown state."})}function ww(t){t&&t.target!==t.currentTarget||We(document.getElementById("commit-terminal-modal"))}function bw(){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 rd={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}},Ew=[{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..."}],Oe={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&&(Eu(e,!0,"Deploying to FlutterFlow"),He(e)),this.set("prepare")},set(t,e=null){if(!(!rd[t]||t===this.phaseId)){if(!this.sequence.includes(t)){const n=this.sequence.indexOf("package");this.sequence.splice(n===-1?this.sequence.length:n,0,t)}this.phaseId=t,this.phaseStartedAt=Date.now(),this.substatus=e,this.liveSubstatus=!1,this.render(),this.timer&&clearInterval(this.timer),t!=="done"&&(this.timer=setInterval(()=>this.render(),500))}},setSubstatus(t){t&&(this.liveSubstatus=!0,this.substatus=t,this.render())},render(){const t=rd[this.phaseId];if(!t)return;const e=(Date.now()-this.phaseStartedAt)/1e3,n=t.start+(t.end-t.start)*(1-Math.exp(-e/25));if(this.phaseId==="provision"&&!this.liveSubstatus){const o=Ew.filter(a=>e>=a.after).pop();o&&(this.substatus=o.text)}const i=this.sequence.indexOf(this.phaseId),s=[`Step ${i===-1?1:i+1} of ${this.sequence.length}`];e>=5&&s.push(Sw(e)),dp(this.phaseId==="done"?100:n,t.message,s.join(" · "),this.substatus)},stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.phaseId=null;const t=document.getElementById("commit-progress-overlay");t&&(Eu(t,!1),We(t,{force:!0,restoreFocus:!1}))}};function Sw(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 up(t){Oe.start(t)}function Jl(){Oe.stop()}function dp(t,e,n,i=null){const r=document.getElementById("commit-progress-bar"),s=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");r&&(r.style.width=`${Math.round(t*10)/10}%`),s&&(s.textContent=e),o&&(o.textContent=n),a&&(a.textContent=i||"",a.classList.toggle("hidden",!i))}function sd(t){const e={[ee.PREPARING]:"prepare",[ee.VALIDATING]:"validate",[ee.PUSHING]:"project",[ee.SUCCESS]:"done"};if(t===ee.ERROR){Oe.timer&&clearInterval(Oe.timer),Oe.timer=null,dp(100,"Failed","Error occurred");return}const n=e[t];n&&Oe.set(n)}function xw(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===J.CODE_FILE):t.codeInfo?.codeType===J.CODE_FILE}let fp=!1;function hp(t){fp=t;const e=document.querySelector("#commit-confirm-modal button[data-deploy-confirm]");e&&(e.disabled=t),[...document.querySelectorAll("[data-deploy-start]"),...document.querySelectorAll("#btn-deploy-to-ff")].forEach(i=>{i.disabled=t})}function od(t){Jl(),hp(!1);const e=_h(t);e===Xe.COMMITTED?op(t):e===Xe.PARTIAL?lp(t):e===Xe.UNCONFIRMED?cp(t):ap(t)}async function Iw(){if(!zi){console.error("No pending commit data");return}if(fp){console.warn("Deploy already in flight; ignoring duplicate confirm.");return}const t=zi;if(zi=null,qi=_w(),sp(),hp(!0),up({withProvisioning:xw(t)}),t.bundlePlan){const o=await C0(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});qi=null,od(o);return}const{codeInfo:e}=t,{artifactType:n,artifactName:i,fileName:r}=Oh(),s=await k0(e.content,{artifactType:n,artifactName:i,fileName:r,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});qi=null,od(s)}window.runThinkingPipeline=or;window.toggleStep=F0;window.toggleSection=P0;window.selectWorkflowStep=nt;window.copyCode=R0;window.retryWithDifferentModel=L0;window.openApiKeysModal=Rl;window.closeApiKeysModal=Mh;window.openComposerSettings=t0;window.closeComposerSettings=n0;window.walkthroughConnectAccount=e0;window.closeWalkthroughModal=r0;window.openWalkthroughModal=i0;window.advanceWalkthrough=Tl;window.commitToFlutterFlow=I0;function kw(){const t=document.getElementById("pipeline-input");t&&t.focus()}function Cw(){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=kw;window.openModelSelector=Cw;window.handlePromptImageSelect=Dy;window.removePromptImage=jy;window.saveApiKeys=a0;window.validateFlutterFlowConnection=Ml;window.clearAllApiKeys=l0;window.toggleKeyVisibility=p0;window.handleWelcomeVideoEnd=mw;window.dismissWelcomeVideo=Nn;window.initiateCommitToFlutterFlow=N0;window.updateFlutterFlowCredentialStatus=D0;window.openCommitConfirmModal=Kl;window.closeCommitConfirmModal=sp;window.closeCommitSuccessModal=yw;window.closeCommitTerminalModal=ww;window.showCommitPartialModal=lp;window.showCommitUnconfirmedModal=cp;window.showCommitSuccessModal=op;window.showCommitFailureModal=ap;window.toggleCodePreview=bw;window.confirmCommitToFlutterFlow=Iw;window.runRefinement=Vh;window.regenerateFromPastedErrors=Gh;window.clearErrorInput=M0;window.setFlutterFlowEndpoint=Qy;window.getFlutterFlowEndpoint=yt;window.commitProgress=Oe;window.openSignInModal=Ws;window.closeSignInModal=Xh;window.handleMagicLinkRequest=q0;window.handleSignOut=z0;window.handleSendNewLink=K0;window.handleClearCache=Y0;window.handleDeleteAccount=J0;window.closeDeleteUnavailableModal=Z0;window.startCheckout=lw;window.openCustomerPortal=cw;window.openPricingModal=di;window.closePricingModal=rp;let jr=null,pp=null,On={1:"pending",2:"pending",3:"pending"},Zl=1,Xl=null;const Vs={1:"Prompt Architect",2:"Code Generator",3:"Code Review"},Aw={1:"Understanding your prompt",2:"Generating Dart code",3:"Running the code audit"},Pw={1:"Prompt understood",2:"Dart code generated",3:"Code audit complete"};function Gs(){return y.runId+=1,y.runId}function re(t){return t===void 0||t===y.runId}function Fw(){y.runId+=1}function Ql(t){return document.getElementById(`pdot-${t}`)}function Ka(t){const e=document.getElementById("btn-run-pipeline")||document.getElementById("hero-send");e&&(e.disabled=t,e.classList.toggle("is-busy",t),t?e.setAttribute("aria-busy","true"):e.removeAttribute("aria-busy"))}function Ks(t){const e=document.getElementById("pipeline-progress");e&&(e.dataset.runState=t)}function Rn(t,e){On[t]=e;const n=Ql(t);if(!n)return;n.dataset.state=e,n.disabled=e==="pending"||e==="skipped";const i=Vs[t],r={pending:"not started",active:"in progress",done:"complete",failed:"failed",skipped:"not run"};n.setAttribute("aria-label",`Step ${t} of 3, ${i}: ${r[e]||e}`),e==="active"?n.setAttribute("aria-current","step"):n.removeAttribute("aria-current")}function Rw(){return[1,2,3].filter(t=>On[t]==="done").length}function Ys(){const t=document.getElementById("pipeline-progress-fill");t&&(t.style.width=`${Rw()/3*100}%`);const e=document.getElementById("progress-stage-count");e&&(e.textContent=`Step ${Zl} of 3`)}function Js(t,{done:e=!1}={}){const n=document.getElementById("progress-title-text"),i=document.getElementById("progress-substep-text"),r=On[t],s=e||r==="done";if(n&&(n.textContent=s?Pw[t]:Aw[t]),i){const o=s?" — complete":r==="failed"?" — stopped":"";i.textContent=`Step ${t} of 3 — ${Vs[t]}${o}`}}function Tw(t){On[t]==="pending"||On[t]==="skipped"||(Xl=t,[1,2,3].forEach(e=>{const n=Ql(e);n&&n.setAttribute("aria-pressed",String(e===t))}),Js(t))}function ec(){Xl=null,[1,2,3].forEach(t=>{const e=Ql(t);e&&e.removeAttribute("aria-pressed")})}function gp(t){const e=document.getElementById("pipeline-note");e&&(e.textContent=t||"",e.hidden=!t)}function $w(t,e,n){re(n)&&gp(`${Gt(t)} did not answer. Continuing on ${Gt(e)}.`)}function tc(){const t=document.getElementById("pipeline-failure");if(!t)return;t.hidden=!0;const e=document.getElementById("pipeline-failure-actions");e&&e.replaceChildren()}const Mw=1120;function Lw(){const t=getComputedStyle(document.documentElement).getPropertyValue("--t-morph").trim(),e=Number.parseFloat(t);return Number.isFinite(e)&&e>0?e:Mw}let Qn=null,Ur=null;function Nw(){return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0}function dn(){if(Ur){try{Ur.cancel()}catch{}Ur=null}Qn&&(Qn.remove(),Qn=null),window.removeEventListener("resize",dn)}function mp(t,e){if(dn(),Nw()||!t||!e||!document.body||typeof Element.prototype.animate!="function")return;const n=t.getBoundingClientRect(),i=e.getBoundingClientRect();if(!n.width||!n.height||!i.width||!i.height)return;const r=document.createElement("div");r.className="composer-morph",r.setAttribute("aria-hidden","true"),r.style.cssText=`left:${i.left}px;top:${i.top}px;width:${i.width}px;height:${i.height}px;opacity:0;`,document.body.appendChild(r);const s=n.left+n.width/2-(i.left+i.width/2),o=n.top+n.height/2-(i.top+i.height/2),a=n.width/i.width,l=n.height/i.height,u=`translate(${s}px,${o}px) scale(${a},${l})`,c=r.animate([{transform:u,opacity:0,offset:0,easing:"cubic-bezier(.2,0,0,1)"},{transform:u,opacity:1,offset:.14,easing:"cubic-bezier(.4,0,.2,1)"},{transform:`translate(${s}px,${o}px) scale(${a*.93},${l*.93})`,opacity:1,offset:.28,easing:"cubic-bezier(.32,1.38,.5,1)"},{transform:"translate(0px,0px) scale(1,1)",opacity:1,offset:1}],{duration:Lw(),fill:"both"});Qn=r,Ur=c,window.addEventListener("resize",dn),c.onfinish=()=>{if(Qn!==r)return;const d=r.animate([{opacity:1},{opacity:0}],{duration:260,fill:"forwards"});d.onfinish=()=>{Qn===r&&dn()}}}function Ow(){const e=document.getElementById("composer")?.getBoundingClientRect();e&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{mp({getBoundingClientRect:()=>e},document.getElementById("main-stage-container"))})})}function Bw(){mp(document.getElementById("pipeline-progress"),document.getElementById("main-stage-container"))}window.addEventListener("hashchange",dn);window.addEventListener("popstate",dn);function Zs(t={}){const{prompt:e=null,runId:n}=t;if(!re(n))return;Qs(),nn(!0);const i=document.getElementById("pipeline-progress"),r=document.getElementById("results-view"),s=document.getElementById("ready-state");if(s&&s.classList.add("hidden"),r&&r.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),i&&i.classList.add("visible"),Ks("running"),e!==null){const a=document.getElementById("pipeline-submitted-prompt");a&&(a.textContent=e)}pp=Date.now();const o=document.getElementById("progress-elapsed");o&&(o.textContent="0s"),On={1:"pending",2:"pending",3:"pending"},ec(),tc(),gp(""),[1,2,3].forEach(a=>Rn(a,"pending")),Ft(1,n),Dw()}function Ft(t,e){re(e)&&(Zl=t,ec(),[1,2,3].forEach(n=>{n===t?Rn(n,"active"):nt&&Rn(n,"pending")}),Js(t),Ys())}function tn(t,e){re(e)&&(Rn(t,"done"),Xl===null&&Js(t,{done:!0}),Ys())}function vp(t,{stage:e=1,runId:n,retry:i=_p}={}){if(!re(n))return;Xs(),Qs(),dn(),Ks("failed"),nn(!0);const r=document.getElementById("pipeline-progress");r&&r.classList.add("visible");const s=document.getElementById("results-view");s&&s.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),Rn(e,"failed"),[1,2,3].forEach(p=>{p>e&&Rn(p,"pending")}),Zl=e,ec(),Js(e),Ys();const o=wh(t),a=document.getElementById("pipeline-failure"),l=document.getElementById("pipeline-failure-title"),u=document.getElementById("pipeline-failure-message"),c=document.getElementById("pipeline-failure-hint"),d=document.getElementById("pipeline-failure-actions");if(!a||!l||!u||!d)return;if(a.dataset.kind=o.kind,l.textContent=`${Vs[e]}: ${o.title}`,u.textContent=o.message,c){const p=o.detail&&o.detail!==o.message?o.detail:"";c.textContent=p,c.hidden=!p}d.replaceChildren();const f=[o.canUpgrade&&{id:"upgrade",label:"View plans",variant:"primary",onClick:()=>di()},o.canRetry&&{id:"retry",label:"Retry",variant:o.canUpgrade?"secondary":"primary",onClick:i},o.canEdit&&{id:"edit",label:"Edit prompt",variant:"secondary",onClick:Ya}].filter(Boolean);!o.canEdit&&!o.canRetry&&f.push({id:"edit",label:"Back to prompt",variant:"secondary",onClick:Ya}),f.forEach(p=>{const g=document.createElement("button");g.type="button",g.textContent=p.label,g.dataset.action=p.id,g.dataset.variant=p.variant,g.addEventListener("click",p.onClick),d.appendChild(g)}),a.hidden=!1;const h=d.querySelector("button");h&&h.focus({preventScroll:!0})}function Ya(){Fw(),uw(),y.isRunning=!1,Ka(!1),rn(),Ks("settled"),dn(),Xs(),Qs(),tc();const t=document.getElementById("pipeline-progress");t&&t.classList.remove("visible"),nn(!1);const e=document.getElementById("pipeline-input");e&&(y.submittedPrompt&&(e.value=y.submittedPrompt,e.dispatchEvent(new Event("input",{bubbles:!0}))),e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length))}function _p(){const t=document.getElementById("pipeline-input");t&&y.submittedPrompt&&(t.value=y.submittedPrompt,t.dispatchEvent(new Event("input",{bubbles:!0}))),Ne=y.submittedImages.slice(),cn(),tc(),or()}function Dw(){Xs(),jr=setInterval(()=>{const t=(Date.now()-pp)/1e3,e=document.getElementById("progress-elapsed");e&&(e.textContent=`${Math.floor(t)}s`)},250)}function Xs(){jr&&(clearInterval(jr),jr=null)}let Vi=null;function Qs(){Vi&&(clearTimeout(Vi),Vi=null)}function cr(){Xs(),Qs(),Ks("settled"),Ys();const t=document.getElementById("pipeline-progress-fill");Vi=setTimeout(()=>{Vi=null;const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function Tn(t,e=""){const n={pass:'',warning:'',fail:'',info:''};return``}function yp(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function jw(){return f_({bundle:y.artifactBundle,reviewResult:y.step3Result})}function Uw(t){return`
    ${Tn(t.severity)}
    @@ -315,4 +315,4 @@ Error: ${g} ${q(s.artifactType)} - `}).join(""),i.onclick=s=>{const o=s.target.closest(".artifact-tab");o?.dataset?.artifactId&&nc(o.dataset.artifactId)},ad()),e&&e.classList.add("visible")}function ad(){const t=document.getElementById("bundle-strip");!t||t.dataset.tabKeyboard==="bound"||(t.dataset.tabKeyboard="bound",t.addEventListener("keydown",e=>{if(e.defaultPrevented)return;const n=[document.getElementById("results-summary-tab"),...Array.from(document.querySelectorAll("#artifact-tabs .artifact-tab"))].filter(Boolean);if(!n.length||!n.includes(document.activeElement))return;let i=-1;const r=n.indexOf(document.activeElement);if(e.key==="ArrowRight")i=(r+1)%n.length;else if(e.key==="ArrowLeft")i=(r-1+n.length)%n.length;else if(e.key==="Home")i=0;else if(e.key==="End")i=n.length-1;else return;e.preventDefault();const s=n[i];if(!s)return;if(s.id==="results-summary-tab")wp();else{const a=s.dataset.artifactId;a&&nc(a)}const o=s.id==="results-summary-tab"?document.getElementById("results-summary-tab"):document.querySelector(`#artifact-tabs .artifact-tab[data-artifact-id="${s.dataset.artifactId}"]`);o&&o.focus()}))}function eo(){document.body.classList.add("results-fullscreen"),document.body.classList.add("results-with-sidebar");const t=document.getElementById("results-view"),e=document.getElementById("results-code-output"),n=document.getElementById("results-audit-output"),i=document.getElementById("results-summary-detail"),r=document.getElementById("artifact-results-split"),s=jw(),o=Ol();if(i&&(i.setAttribute("role","tabpanel"),i.setAttribute("aria-labelledby","results-summary-tab")),r){r.setAttribute("role","tabpanel");const a=s?.artifacts?.find(l=>l.id===y.selectedArtifactId);r.setAttribute("aria-labelledby",a?`artifact-tab-${a.id}`:"results-summary-tab")}if(Ww(s),zw(s),e&&(e.textContent=""),e){const a=bh(o);e.innerHTML=a}n&&(n.innerHTML=qw(s)),i&&i.classList.toggle("hidden",y.resultsViewMode!=="summary"),r&&r.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function ur(t,e){nn(!0),y.selectedArtifactId||(y.selectedArtifactId=oi(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const n=document.getElementById("step3-output");n&&(n.textContent=""),eo(),rn(),Vw()}function Vw(){const t=document.getElementById("btn-feedback-up"),e=document.getElementById("btn-feedback-down"),n=document.getElementById("results-feedback-status");t&&(t.className="feedback-btn",t.setAttribute("aria-pressed","false"),t.disabled=!1,t.removeAttribute("aria-disabled")),e&&(e.className="feedback-btn",e.setAttribute("aria-pressed","false"),e.disabled=!1,e.removeAttribute("aria-disabled")),n&&(n.textContent=""),Ja=!1}function nc(t){y.selectedArtifactId=t,y.resultsViewMode="file",eo()}function wp(){y.resultsViewMode="summary",eo()}function Gw(){const t=document.getElementById("btn-copy-results"),e=document.getElementById("results-copy-status"),n=Ol(),i=(r,s)=>{e&&(e.textContent=r,e.classList.toggle("ok",!!s),e.classList.toggle("fail",!s))};if(!navigator.clipboard?.writeText){i("Copying isn't supported in this browser.",!1);return}navigator.clipboard.writeText(n).then(()=>{if(i("Copied to clipboard",!0),t){t.classList.add("copied");const r=t.querySelector("span");if(r){const s=r.textContent;r.textContent="Copied!",setTimeout(()=>{t.classList.remove("copied"),r.textContent=s},2e3)}}}).catch(()=>{i("Clipboard permission was denied. Select the code to copy it manually.",!1)})}let Ja=!1;async function Kw(t){const e=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down"),i=document.getElementById("results-feedback-status");if(!e||!n||Ja)return;const r=l=>{i&&(i.textContent="",i.offsetWidth,i.textContent=l)},s=l=>{Ja=l,[e,n].forEach(u=>{u.disabled=l,u.setAttribute("aria-disabled",String(l))})},o=t==="up"?"thumbsUp":"thumbsDown";s(!0),r("Submitting review feedback…");const a={type:o,code:y.step2Result,input:y.step1Result};try{const l=await zl(a.type,a.code,a.input);if(!l||l.success!==!0){s(!1),r("Review feedback could not be sent. Tap again to retry.");return}e.classList.toggle("active-up",t==="up"),n.classList.toggle("active-down",t==="down"),e.setAttribute("aria-pressed",String(t==="up")),n.setAttribute("aria-pressed",String(t==="down")),s(!1),r("Review feedback saved.")}catch{s(!1),r("Review feedback could not be sent. Tap again to retry.")}}function Yw(){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 bp(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}function nn(t){const e=document.getElementById("generation-stage");e&&(t?(e.hidden=!1,e.inert=!1,requestAnimationFrame(()=>e.classList.add("is-active"))):(e.classList.remove("is-active"),e.inert=!0,setTimeout(()=>{e.classList.contains("is-active")||(e.hidden=!0)},260)))}function Ep(){const t=z.isVerified&&!!z.email,e=ce.tier||"free",n=t&&pi(),i=!t||Rt(),s=n?"Checking…":i?gl[e]||"Free":"—",o=document.getElementById("topbar-plan");o&&(o.textContent=s);const a=document.getElementById("topbar-avatar");a&&(a.textContent=(z.email||"?")[0].toUpperCase()),Gl();const l=document.getElementById("plans-free-current");l&&l.classList.toggle("hidden",e!=="free"||!i);const u=document.getElementById("plans-checkout-btn-professional");if(u){const d=e==="professional"&&i;u.disabled=d,u.textContent=d?"Current plan":"Subscribe"}const c=document.getElementById("plans-checkout-btn-power");if(c){const d=e==="power"&&i;c.disabled=d,c.textContent=d?"Current plan":"Subscribe"}}function Jw(){Ep();const t=document.getElementById("credits-modal");t&&He(t)}function Zw(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("credits-modal");e&&We(e)}function Sp(t,e=!0,n=!0){if(t=["home","account","plans"].includes(t)?t:"home",document.querySelectorAll(".view[data-view]").forEach(r=>{r.dataset.view===t?(r.hidden=!1,r.removeAttribute("inert"),requestAnimationFrame(()=>{r.classList.add("is-active"),n&&r.focus({preventScroll:!0})})):(r.classList.remove("is-active"),r.setAttribute("inert","true"),setTimeout(()=>{r.classList.contains("is-active")||(r.hidden=!0)},260))}),t!=="home")nn(!1);else{const r=document.getElementById("main-stage-container");r&&r.classList.contains("visible")&&nn(!0)}if(document.querySelectorAll(".nav-link[data-view]").forEach(r=>{const s=r.dataset.view===t;r.setAttribute("aria-current",s?"page":null),s||r.removeAttribute("aria-current")}),e){const r=t==="home"?"":`#${t}`;window.location.hash!==r&&window.history.pushState({view:t},"",r||"#")}}let ld=!1;function ic(){const t=window.location.hash.replace(/^#/,"");Sp(t||"home",!1,ld),ld=!0}window.addEventListener("popstate",t=>{ic()});window.addEventListener("hashchange",()=>{ic()});window.copyResultsCode=Gw;window.selectArtifact=nc;window.selectResultsSummary=wp;window.submitResultsFeedback=Kw;window.showErrorInputPanel=Yw;window.hideErrorInputPanel=bp;window.setGenerationStageVisible=nn;window.switchView=Sp;window.selectPipelineStage=Tw;window.editPipelinePrompt=Ya;window.retryPipelineRun=_p;window.openCreditsModal=Jw;window.closeCreditsModal=Zw; + `}).join(""),i.onclick=s=>{const o=s.target.closest(".artifact-tab");o?.dataset?.artifactId&&nc(o.dataset.artifactId)},ad()),e&&e.classList.add("visible")}function ad(){const t=document.getElementById("bundle-strip");!t||t.dataset.tabKeyboard==="bound"||(t.dataset.tabKeyboard="bound",t.addEventListener("keydown",e=>{if(e.defaultPrevented)return;const n=[document.getElementById("results-summary-tab"),...Array.from(document.querySelectorAll("#artifact-tabs .artifact-tab"))].filter(Boolean);if(!n.length||!n.includes(document.activeElement))return;let i=-1;const r=n.indexOf(document.activeElement);if(e.key==="ArrowRight")i=(r+1)%n.length;else if(e.key==="ArrowLeft")i=(r-1+n.length)%n.length;else if(e.key==="Home")i=0;else if(e.key==="End")i=n.length-1;else return;e.preventDefault();const s=n[i];if(!s)return;if(s.id==="results-summary-tab")wp();else{const a=s.dataset.artifactId;a&&nc(a)}const o=s.id==="results-summary-tab"?document.getElementById("results-summary-tab"):document.querySelector(`#artifact-tabs .artifact-tab[data-artifact-id="${s.dataset.artifactId}"]`);o&&o.focus()}))}function eo(){document.body.classList.add("results-fullscreen"),document.body.classList.add("results-with-sidebar");const t=document.getElementById("results-view"),e=document.getElementById("results-code-output"),n=document.getElementById("results-audit-output"),i=document.getElementById("results-summary-detail"),r=document.getElementById("artifact-results-split"),s=jw(),o=Ol();if(i&&(i.setAttribute("role","tabpanel"),i.setAttribute("aria-labelledby","results-summary-tab")),r){r.setAttribute("role","tabpanel");const a=s?.artifacts?.find(l=>l.id===y.selectedArtifactId);r.setAttribute("aria-labelledby",a?`artifact-tab-${a.id}`:"results-summary-tab")}if(Ww(s),zw(s),e&&(e.textContent=""),e){const a=bh(o);e.innerHTML=a}n&&(n.innerHTML=qw(s)),i&&i.classList.toggle("hidden",y.resultsViewMode!=="summary"),r&&r.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function ur(t,e){nn(!0),y.selectedArtifactId||(y.selectedArtifactId=oi(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const n=document.getElementById("step3-output");n&&(n.textContent=""),eo(),rn(),Vw()}function Vw(){const t=document.getElementById("btn-feedback-up"),e=document.getElementById("btn-feedback-down"),n=document.getElementById("results-feedback-status");t&&(t.className="feedback-btn",t.setAttribute("aria-pressed","false"),t.disabled=!1,t.removeAttribute("aria-disabled")),e&&(e.className="feedback-btn",e.setAttribute("aria-pressed","false"),e.disabled=!1,e.removeAttribute("aria-disabled")),n&&(n.textContent=""),Ja=!1}function nc(t){y.selectedArtifactId=t,y.resultsViewMode="file",eo()}function wp(){y.resultsViewMode="summary",eo()}function Gw(){const t=document.getElementById("btn-copy-results"),e=document.getElementById("results-copy-status"),n=Ol(),i=(r,s)=>{e&&(e.textContent=r,e.classList.toggle("ok",!!s),e.classList.toggle("fail",!s))};if(!navigator.clipboard?.writeText){i("Copying isn't supported in this browser.",!1);return}navigator.clipboard.writeText(n).then(()=>{if(i("Copied to clipboard",!0),t){t.classList.add("copied");const r=t.querySelector("span");if(r){const s=r.textContent;r.textContent="Copied!",setTimeout(()=>{t.classList.remove("copied"),r.textContent=s},2e3)}}}).catch(()=>{i("Clipboard permission was denied. Select the code to copy it manually.",!1)})}let Ja=!1;async function Kw(t){const e=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down"),i=document.getElementById("results-feedback-status");if(!e||!n||Ja)return;const r=l=>{i&&(i.textContent="",i.offsetWidth,i.textContent=l)},s=l=>{Ja=l,[e,n].forEach(u=>{u.disabled=l,u.setAttribute("aria-disabled",String(l))})},o=t==="up"?"thumbsUp":"thumbsDown";s(!0),r("Submitting review feedback…");const a={type:o,code:y.step2Result,input:y.step1Result};try{const l=await zl(a.type,a.code,a.input);if(!l||l.success!==!0){s(!1),r("Review feedback could not be sent. Tap again to retry.");return}e.classList.toggle("active-up",t==="up"),n.classList.toggle("active-down",t==="down"),e.setAttribute("aria-pressed",String(t==="up")),n.setAttribute("aria-pressed",String(t==="down")),s(!1),r("Review feedback saved.")}catch{s(!1),r("Review feedback could not be sent. Tap again to retry.")}}function Yw(){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 bp(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}function nn(t){const e=document.getElementById("generation-stage");e&&(t?(e.hidden=!1,e.inert=!1,requestAnimationFrame(()=>e.classList.add("is-active"))):(e.classList.remove("is-active"),e.inert=!0,setTimeout(()=>{e.classList.contains("is-active")||(e.hidden=!0)},260)))}function Ep(){const t=z.isVerified&&!!z.email,e=ce.tier||"free",n=t&&pi(),i=!t||Tt(),s=n?"Checking…":i?gl[e]||"Free":"—",o=document.getElementById("topbar-plan");o&&(o.textContent=s);const a=document.getElementById("topbar-avatar");a&&(a.textContent=(z.email||"?")[0].toUpperCase()),Gl();const l=document.getElementById("plans-free-current");l&&l.classList.toggle("hidden",e!=="free"||!i);const u=document.getElementById("plans-checkout-btn-professional");if(u){const d=e==="professional"&&i;u.disabled=d,u.textContent=d?"Current plan":"Subscribe"}const c=document.getElementById("plans-checkout-btn-power");if(c){const d=e==="power"&&i;c.disabled=d,c.textContent=d?"Current plan":"Subscribe"}}function Jw(){Ep();const t=document.getElementById("credits-modal");t&&He(t)}function Zw(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("credits-modal");e&&We(e)}function Sp(t,e=!0,n=!0){if(t=["home","account","plans"].includes(t)?t:"home",document.querySelectorAll(".view[data-view]").forEach(r=>{r.dataset.view===t?(r.hidden=!1,r.removeAttribute("inert"),requestAnimationFrame(()=>{r.classList.add("is-active"),n&&r.focus({preventScroll:!0})})):(r.classList.remove("is-active"),r.setAttribute("inert","true"),setTimeout(()=>{r.classList.contains("is-active")||(r.hidden=!0)},260))}),t!=="home")nn(!1);else{const r=document.getElementById("main-stage-container");r&&r.classList.contains("visible")&&nn(!0)}if(document.querySelectorAll(".nav-link[data-view]").forEach(r=>{const s=r.dataset.view===t;r.setAttribute("aria-current",s?"page":null),s||r.removeAttribute("aria-current")}),e){const r=t==="home"?"":`#${t}`;window.location.hash!==r&&window.history.pushState({view:t},"",r||"#")}}let ld=!1;function ic(){const t=window.location.hash.replace(/^#/,"");Sp(t||"home",!1,ld),ld=!0}window.addEventListener("popstate",t=>{ic()});window.addEventListener("hashchange",()=>{ic()});window.copyResultsCode=Gw;window.selectArtifact=nc;window.selectResultsSummary=wp;window.submitResultsFeedback=Kw;window.showErrorInputPanel=Yw;window.hideErrorInputPanel=bp;window.setGenerationStageVisible=nn;window.switchView=Sp;window.selectPipelineStage=Tw;window.editPipelinePrompt=Ya;window.retryPipelineRun=_p;window.openCreditsModal=Jw;window.closeCreditsModal=Zw; diff --git a/dist/index.html b/dist/index.html index 62c098d..ca74ef4 100644 --- a/dist/index.html +++ b/dist/index.html @@ -3313,7 +3313,7 @@ .send.is-busy .send-spin { animation: none; opacity: 0.6; } } - + diff --git a/e2e/stu380-deploy.spec.js b/e2e/stu380-deploy.spec.js index 8e96e7b..281ee57 100644 --- a/e2e/stu380-deploy.spec.js +++ b/e2e/stu380-deploy.spec.js @@ -6,9 +6,10 @@ import { applyDefaultRoutes, ENDPOINTS } from "./fixtures/apiFixtures.js"; * STU-380 — truthful deployment terminal outcomes. * * A deploy ends in one of four states and the UI must never flatten them: - * only a confirmed success may say "committed". 403 / file rejection / compile - * gate are failures; a mixed outcome (classes written, rest rejected) is - * partial; a client wait expiry or a dropped stream is unconfirmed. Every + * only a confirmed success may say "committed". A refusal issued before any + * write (403 / file rejection / compile gate) is a failure; a mixed outcome + * (classes written, rest rejected) is partial; a client wait expiry, a + * dropped stream, or a server error is unconfirmed. Every * terminal state must release the UI busy state and offer safe next actions * without concealing the manual FlutterFlow reconciliation step. These tests * drive the same presentation the real confirm flow uses @@ -415,8 +416,11 @@ test.describe("STU-380 transport outcome regressions", () => { expect(outcome.outcome).toBe("unconfirmed"); }); - test("a push refused with HTTP errors on every endpoint is a definitive failure", async ({ page }) => { + test("a push hitting server errors on every endpoint is unconfirmed, not failed", async ({ page }) => { await loadDeployHooks(page); + // Every endpoint answers 500. No response was lost, but a server error can + // be raised after the write was applied, so it cannot prove a refusal — + // the outcome stays unknown rather than fabricating a failure. await page.route("**/syncCustomCodeChanges", async (route) => { await route.fulfill({ status: 500, body: "server error" }); }); @@ -428,10 +432,113 @@ test.describe("STU-380 transport outcome regressions", () => { ); expect(outcome.settled).toBe("rejected"); - expect(outcome.name).not.toBe("UnconfirmedDeployError"); + expect(outcome.name).toBe("UnconfirmedDeployError"); + expect(outcome.outcome).toBe("unconfirmed"); expect(outcome.message).toContain("HTTP 500"); }); + test("a definitive refusal after a lost response is unconfirmed, not failed", async ({ page }) => { + await loadDeployHooks(page); + // Production drops the request entirely; staging then answers a clean 403. + // The refusal is definitive for staging but cannot prove production did + // not apply the push first — the outcome must stay unknown. + const outcome = await page.evaluate(async () => { + let calls = 0; + window.fetch = (url) => { + if (!String(url).includes("syncCustomCodeChanges")) { + return Promise.resolve(new Response("{}", { status: 200 })); + } + calls += 1; + if (calls === 1) return Promise.reject(new Error("connection reset")); + return Promise.resolve(new Response("forbidden", { status: 403 })); + }; + try { + await window.__CCC_PUSH_CODE_WITH_RETRY__( + { project_id: "ff-proj-0007", zipped_custom_code: "eA==" }, + 1, + ); + return { settled: "resolved", calls }; + } catch (error) { + return { + settled: "rejected", + calls, + name: error.name, + outcome: error.outcome, + message: error.message, + }; + } + }); + + expect(outcome.settled).toBe("rejected"); + expect(outcome.name).toBe("UnconfirmedDeployError"); + expect(outcome.outcome).toBe("unconfirmed"); + expect(outcome.calls).toBe(2); + }); + + test("a refusal after a server error is unconfirmed — the 5xx may have applied the write", async ({ page }) => { + await loadDeployHooks(page); + // Production 500s (maybe post-write); staging then answers 403. The later + // refusal cannot undo the uncertain first attempt. + const outcome = await page.evaluate(async () => { + let calls = 0; + window.fetch = (url) => { + if (!String(url).includes("syncCustomCodeChanges")) { + return Promise.resolve(new Response("{}", { status: 200 })); + } + calls += 1; + const status = calls === 1 ? 500 : 403; + return Promise.resolve(new Response("err", { status })); + }; + try { + await window.__CCC_PUSH_CODE_WITH_RETRY__( + { project_id: "ff-proj-0007", zipped_custom_code: "eA==" }, + 1, + ); + return { settled: "resolved", calls }; + } catch (error) { + return { + settled: "rejected", + calls, + name: error.name, + outcome: error.outcome, + message: error.message, + }; + } + }); + + expect(outcome.settled).toBe("rejected"); + expect(outcome.name).toBe("UnconfirmedDeployError"); + expect(outcome.outcome).toBe("unconfirmed"); + expect(outcome.calls).toBe(2); + }); + + test("a server error other than 500 is unconfirmed too — no retry needed to be unsure", async ({ page }) => { + await loadDeployHooks(page); + const outcome = await page.evaluate(async () => { + window.fetch = () => + Promise.resolve(new Response("bad gateway", { status: 502 })); + try { + await window.__CCC_PUSH_CODE_WITH_RETRY__( + { project_id: "ff-proj-0007", zipped_custom_code: "eA==" }, + 1, + ); + return { settled: "resolved" }; + } catch (error) { + return { + settled: "rejected", + name: error.name, + outcome: error.outcome, + message: error.message, + }; + } + }); + + expect(outcome.settled).toBe("rejected"); + expect(outcome.name).toBe("UnconfirmedDeployError"); + expect(outcome.outcome).toBe("unconfirmed"); + expect(outcome.message).toContain("HTTP 502"); + }); + test("a sync response whose body drops mid-read is unconfirmed, not failed", async ({ page }) => { await loadDeployHooks(page); @@ -468,6 +575,8 @@ test.describe("STU-380 transport outcome regressions", () => { test("a refusal whose body drops mid-read is still a definitive failure", async ({ page }) => { await loadDeployHooks(page); + // A 4xx refusal is definitive even when its body cannot be read — the + // status alone proves the server rejected the request before any write. const outcome = await page.evaluate(async () => { const body = new ReadableStream({ start(controller) { @@ -477,7 +586,7 @@ test.describe("STU-380 transport outcome regressions", () => { }); try { const parsed = await window.__CCC_PARSE_PUSH_RESPONSE__( - new Response(body, { status: 500 }), + new Response(body, { status: 403 }), ); return { settled: "resolved", parsed }; } catch (error) { @@ -487,15 +596,15 @@ test.describe("STU-380 transport outcome regressions", () => { expect(outcome.settled).toBe("resolved"); expect(outcome.parsed.success).toBe(false); - expect(outcome.parsed.responseCode).toBe(500); + expect(outcome.parsed.responseCode).toBe(403); }); - test("a refusal with an unreadable body is not mistaken for a lost response", async ({ page }) => { + test("a server error with an unreadable body still lands as unconfirmed", async ({ page }) => { await loadDeployHooks(page); - // Every endpoint replies 500 but closes its body early: the statuses are - // definitive answers, so exhaustion must report the refusal — not claim - // the push outcome is unknown because a logging read failed. + // Every endpoint replies 500 but closes its body early: the statuses were + // received, so the outcome is unconfirmed because a 5xx cannot prove a + // refusal — not because a logging read failed, and never a crash. const outcome = await page.evaluate(async () => { const stubBody = () => new ReadableStream({ @@ -523,7 +632,8 @@ test.describe("STU-380 transport outcome regressions", () => { }); expect(outcome.settled).toBe("rejected"); - expect(outcome.name).not.toBe("UnconfirmedDeployError"); + expect(outcome.name).toBe("UnconfirmedDeployError"); + expect(outcome.outcome).toBe("unconfirmed"); expect(outcome.message).toContain("HTTP 500"); }); diff --git a/src/deployOutcome.js b/src/deployOutcome.js index 46386bd..c0997fa 100644 --- a/src/deployOutcome.js +++ b/src/deployOutcome.js @@ -15,7 +15,9 @@ export const DeployOutcome = Object.freeze({ COMMITTED: "committed", /** Custom classes were written to FlutterFlow, but the remaining sync failed. */ PARTIAL: "partial", - /** A definitive rejection: nothing was confirmed written. */ + /** A definitive rejection before any write: nothing was confirmed written. + * Server errors (5xx) and lost responses are UNCONFIRMED instead — they + * cannot prove the write was refused. */ FAILED: "failed", /** The remote outcome is unknown (UI wait expired or the stream dropped). */ UNCONFIRMED: "unconfirmed", @@ -84,30 +86,22 @@ export class UnconfirmedDeployError extends Error { * Builds the error thrown when a push to FlutterFlow has retried every * endpoint without a definitive answer. * - * The deciding question is whether any attempt *may have reached* the server: - * a transport error — the fetch rejected before a response arrived — cannot - * prove the write did not land, because a connection can drop after the server - * accepted the request. Exhaustion is therefore UNCONFIRMED if any attempt - * ended that way; only attempts that all came back as HTTP rejections are a - * definitive refusal and may be reported as failed. + * Exhaustion is only reachable through attempts whose outcome is unknown — a + * dropped response (the request may have landed) or a 5xx (the server's own + * failure report, which can follow a write and never proves a refusal). A + * definitive refusal returns out of the retry loop before exhaustion, so an + * exhausted push is always UNCONFIRMED — never a fabricated failure. * * @param {Object} [attempts] - * @param {boolean} [attempts.sawTransportError] - True when at least one - * attempt failed without an HTTP response * @param {number} [attempts.httpStatus] - Last HTTP status the server * returned, when it returned one - * @returns {Error} An UnconfirmedDeployError for a lost response, a plain - * Error for a definitive refusal + * @returns {Error} Always an UnconfirmedDeployError */ -export function exhaustedPushError({ sawTransportError, httpStatus } = {}) { - if (sawTransportError) { - return new UnconfirmedDeployError( - "Every FlutterFlow sync endpoint stopped answering without a definitive " + - "response. The push may still have been applied — open the FlutterFlow " + - "project to reconcile before retrying.", - ); - } - return new Error( - `FlutterFlow rejected the code sync${httpStatus ? ` (HTTP ${httpStatus})` : ""} after every retry.`, +export function exhaustedPushError({ httpStatus } = {}) { + return new UnconfirmedDeployError( + "Every FlutterFlow sync endpoint lost its response or ended in a server " + + `error${httpStatus ? ` (last: HTTP ${httpStatus})` : ""} — neither can ` + + "prove the push was refused, so it may already have been applied. Open " + + "the FlutterFlow project to reconcile before retrying.", ); } diff --git a/src/deployOutcome.test.js b/src/deployOutcome.test.js index 5ef990c..073cc5a 100644 --- a/src/deployOutcome.test.js +++ b/src/deployOutcome.test.js @@ -88,29 +88,25 @@ test("an unconfirmed marker beats every other signal", () => { ); }); -test("push retries exhausted by a lost response are unconfirmed, never a fabricated failure", () => { - // At least one attempt rejected without an HTTP response: the write may have - // reached FlutterFlow, so the terminal outcome must be UNCONFIRMED — a plain - // failure would lie about a deploy that might have committed. - const error = exhaustedPushError({ sawTransportError: true }); +test("push retries exhausted without a definitive answer are unconfirmed, never a fabricated failure", () => { + // Exhaustion is only reachable through attempts that cannot prove refusal — + // dropped responses or 5xx server errors — so the terminal outcome must be + // UNCONFIRMED; a plain failure would lie about a deploy that might have + // committed. + const error = exhaustedPushError(); assert.ok(error instanceof UnconfirmedDeployError); assert.equal(error.outcome, DeployOutcome.UNCONFIRMED); assert.equal(classifyDeployResult({ outcome: error.outcome }), DeployOutcome.UNCONFIRMED); - - // Falsification: marking the same exhaustion as a definitive refusal must - // flip the outcome it produces. - assert.equal( - exhaustedPushError({ sawTransportError: false }) instanceof UnconfirmedDeployError, - false, - ); }); -test("push retries refused on every endpoint are a definitive failure", () => { - const error = exhaustedPushError({ sawTransportError: false, httpStatus: 500 }); - assert.equal(error instanceof UnconfirmedDeployError, false); +test("exhaustion on server errors is unconfirmed too — a 5xx cannot prove refusal", () => { + // Every endpoint answered 500: no response was lost, but a server error can + // be raised after the write, so it still cannot prove the push was refused. + const error = exhaustedPushError({ httpStatus: 500 }); + assert.ok(error instanceof UnconfirmedDeployError); + assert.equal(error.outcome, DeployOutcome.UNCONFIRMED); assert.match(error.message, /HTTP 500/); - // And the result shape it drives classifies as FAILED, not UNCONFIRMED. - assert.equal(classifyDeployResult({ success: false, error: error.message }), DeployOutcome.FAILED); + assert.equal(classifyDeployResult({ outcome: error.outcome }), DeployOutcome.UNCONFIRMED); }); test("the UI waiting bound is finite and below the documented server deadline", () => { From 04541963cefbc4083645bc30ef5bca4011ac2d16 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Sun, 27 Sep 2026 17:22:04 +0000 Subject: [PATCH 07/16] fix(STU-380): bound the sync push so a stalled FlutterFlow cannot hang the deploy pushCodeWithRetry had no timeout: a fetch that never flushed headers (or a response body that stalled mid-parse) parked the deploy forever. All three commit paths now run push + parse under pushCodeWithUiTimeout, which expires into UnconfirmedDeployError and leaves the in-flight write running rather than aborting a request that may have landed. The exported project snapshot was already invalidated before every push. Co-Authored-By: Stuart Gardoll --- app.js | 55 +++++++++-- .../{index-DBkaFUBQ.js => index-284-nqdE.js} | 96 +++++++++---------- dist/index.html | 2 +- e2e/stu380-deploy.spec.js | 64 ++++++++++++- 4 files changed, 161 insertions(+), 56 deletions(-) rename dist/assets/{index-DBkaFUBQ.js => index-284-nqdE.js} (80%) diff --git a/app.js b/app.js index 46641d9..a0fc905 100644 --- a/app.js +++ b/app.js @@ -2648,6 +2648,38 @@ function withUiTimeout(promise, ms, onExpire) { }); } +/** + * Runs the sync push and its response parsing under one UI bound. A stalled + * fetch (headers never flush) or a stalled body read would otherwise park the + * deploy forever; on expiry the outcome is unconfirmed — the request may have + * been applied — and the in-flight write is left running rather than aborted. + * @param {FlutterFlowApiClient} apiClient - Configured API client + * @param {Object} pushRequest - The syncCustomCodeChanges request body + * @param {number} uiTimeoutMs - How long the UI waits for a decision + * @returns {Promise} The parsed push result + */ +async function pushCodeWithUiTimeout( + apiClient, + pushRequest, + uiTimeoutMs = DEPLOY_UI_TIMEOUT_MS, +) { + return withUiTimeout( + (async () => { + const response = await apiClient.pushCode(pushRequest); + return parsePushCodeResponse(response); + })(), + uiTimeoutMs, + (resolve, reject) => + reject( + new UnconfirmedDeployError( + "FlutterFlow did not answer the sync in time — the push may still " + + "have been applied. The outcome is not yet known: open your " + + "FlutterFlow project to reconcile before retrying the deploy.", + ), + ), + ); +} + async function provisionMissingCodeFiles( apiClient, fileMap, @@ -3472,8 +3504,7 @@ async function commitToFlutterFlow(dartCode, fileName, options = {}) { invalidateProjectSourceCache(apiClient); commitProgress.set("push"); - const response = await apiClient.pushCode(pushRequest); - const result = await parsePushCodeResponse(response); + const result = await pushCodeWithUiTimeout(apiClient, pushRequest); if (result.success) { commitState.setSuccess({ @@ -3678,8 +3709,7 @@ async function executeCommit(code, options = {}) { invalidateProjectSourceCache(apiClient); commitProgress.set("push"); - const response = await apiClient.pushCode(pushRequest); - const result = await parsePushCodeResponse(response); + const result = await pushCodeWithUiTimeout(apiClient, pushRequest); // Step 10: Handle result if (result.success) { @@ -3883,8 +3913,7 @@ async function executeBundleCommit(bundlePlan, options = {}) { invalidateProjectSourceCache(apiClient); commitProgress.set("push"); - const response = await apiClient.pushCode(pushRequest); - const result = await parsePushCodeResponse(response); + const result = await pushCodeWithUiTimeout(apiClient, pushRequest); if (result.success) { const metadata = { @@ -8540,6 +8569,20 @@ if (import.meta.env.DEV) { // received status instead of leaking the raw read error. window.__CCC_PARSE_PUSH_RESPONSE__ = (response) => parsePushCodeResponse(response); + // Lets the browser suite drive the bounded push (fetch + parse under the UI + // timeout) with a short bound, so a stalled request provably settles as + // unconfirmed instead of hanging the deploy. + window.__CCC_PUSH_CODE_WITH_TIMEOUT__ = (pushCodeRequest, uiTimeoutMs) => + pushCodeWithUiTimeout( + new FlutterFlowApiClient( + "test-key", + "ff-proj-0007", + "main", + FF_API_ENDPOINTS.production, + ), + pushCodeRequest, + uiTimeoutMs, + ); // Lets the browser suite seed/observe the project-source cache: a deploy // that lost its provisioning result must leave the cache empty so the next // one re-reads the project instead of re-provisioning written classes. diff --git a/dist/assets/index-DBkaFUBQ.js b/dist/assets/index-284-nqdE.js similarity index 80% rename from dist/assets/index-DBkaFUBQ.js rename to dist/assets/index-284-nqdE.js index 8cf3eb4..051db0d 100644 --- a/dist/assets/index-DBkaFUBQ.js +++ b/dist/assets/index-284-nqdE.js @@ -1,7 +1,7 @@ -(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const s of r)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function n(r){const s={};return r.integrity&&(s.integrity=r.integrity),r.referrerPolicy&&(s.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?s.credentials="include":r.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function i(r){if(r.ep)return;r.ep=!0;const s=n(r);fetch(r.href,s)}})();var w=typeof window<"u"?window:void 0,Le=typeof globalThis<"u"?globalThis:w,Ue=Le?.navigator,F=Le?.document,me=Le?.location,Za=Le?.fetch,qo=Le!=null&&Le.XMLHttpRequest&&"withCredentials"in new Le.XMLHttpRequest?Le.XMLHttpRequest:void 0,uc=Le?.AbortController,Fp=Le?.CompressionStream,Ve=Ue?.userAgent;function cd(){return!(!w||w.navigator.onLine===!1)}var vi=typeof globalThis<"u"?globalThis:w;vi&&typeof self>"u"&&(vi.self=vi),vi&&typeof File>"u"&&(vi.File=function(){});var B=w??{},ne={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function dc(t,e,n,i,r,s,o){try{var a=t[s](o),l=a.value}catch(u){return void n(u)}a.done?e(l):Promise.resolve(l).then(i,r)}function se(t){return function(){var e=this,n=arguments;return new Promise((function(i,r){var s=t.apply(e,n);function o(l){dc(s,i,r,o,a,"next",l)}function a(l){dc(s,i,r,o,a,"throw",l)}o(void 0)}))}}function k(){return k=Object.assign?Object.assign.bind():function(t){for(var e=1;arguments.length>e;e++){var n=arguments[e];for(var i in n)({}).hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},k.apply(null,arguments)}function ud(t,e){if(t==null)return{};var n={};for(var i in t)if({}.hasOwnProperty.call(t,i)){if(e.indexOf(i)!==-1)continue;n[i]=t[i]}return n}var fc=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function hc(t){return typeof t=="string"||t}function pc(t){return typeof t=="string"?t:void 0}var _i,Rp=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],Ut=(function(t){return t.AnonymousId="anonymous_id",t.DistinctId="distinct_id",t.Props="props",t.EnablePersonProcessing="enable_person_processing",t.PersonMode="person_mode",t.FeatureFlagDetails="feature_flag_details",t.FeatureFlags="feature_flags",t.FeatureFlagPayloads="feature_flag_payloads",t.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",t.BootstrapFeatureFlags="bootstrap_feature_flags",t.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",t.OverrideFeatureFlags="override_feature_flags",t.Queue="queue",t.AiQueue="ai_queue",t.LogsQueue="logs_queue",t.OptedOut="opted_out",t.SessionId="session_id",t.SessionStartTimestamp="session_start_timestamp",t.SessionLastTimestamp="session_timestamp",t.PersonProperties="person_properties",t.GroupProperties="group_properties",t.InstalledAppBuild="installed_app_build",t.InstalledAppVersion="installed_app_version",t.SessionReplay="session_replay",t.PushRegistered="push_registered",t.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",t.SurveyLastSeenDate="survey_last_seen_date",t.SurveysSeen="surveys_seen",t.Surveys="surveys",t.RemoteConfig="remote_config",t.FlagsEndpointWasHit="flags_endpoint_was_hit",t.DeviceId="device_id",t})({}),gc=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),Tp=["$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"],$p=["token"],dd="NativeGzipValidationError",zo=t=>t.length>=2&&t[0]===31&&t[1]===139,mc=(t,e)=>t===gc.GZipJS||e===gc.GZipJS||e==="gzip",vc=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",pr=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=dd,e},Mp=(function(){var t=se((function*(e,n){18>e.size&&pr("too-short");var i=new Uint8Array(yield e.slice(0,10).arrayBuffer());zo(i)&&i[2]===8||pr("invalid-header");var r=new DataView(yield e.slice(e.size-8).arrayBuffer());r.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(_i)return _i;_i=[];for(var c=0;256>c;c++){for(var d=c,f=0;8>f;f++)d=1&d?3988292384^d>>>1:d>>>1;_i[c]=d>>>0}return _i})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(n)&&pr("invalid-crc");var s=n.length>>>0;r.getUint32(4,!0)!==s&&pr("invalid-size")}));return function(e,n){return t.apply(this,arguments)}})();function Vo(){return Vo=se((function*(t,e,n){e===void 0&&(e=!0);try{var i=new TextEncoder().encode(t),r=new globalThis.CompressionStream("gzip"),s=r.writable.getWriter(),o=s.write(i).then((()=>s.close())).catch((function(){var u=se((function*(c){try{yield s.abort(c)}catch{}throw c}));return function(c){return u.apply(this,arguments)}})()),a=new Response(r.readable).blob(),l=(yield Promise.all([a,o]))[0];return yield Mp(l,i),l}catch(u){if(n!=null&&n.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),Vo.apply(this,arguments)}var Lp=["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"],_c=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var n=t.toLowerCase();return Lp.concat(e).some((i=>{var r=i.toLowerCase();return n.indexOf(r)!==-1}))};function j(t,e){return t.indexOf(e)!==-1}var xs=function(t){return t.trim()},Go=function(t){return t.replace(/^\$/,"")};function fd(t){var e,n=[];return(e=JSON.stringify(t,(function(i,r){if(typeof r=="bigint")return r.toString();if(typeof r!="function"&&typeof r!="symbol"){if(r instanceof Error)return{name:r.name,message:r.message,stack:r.stack};if(r&&typeof r=="object"){for(;n.length>0&&n[n.length-1]!==this;)n.pop();if(n.includes(r))return"[Circular]";n.push(r)}return r}})))!==null&&e!==void 0?e:"null"}var hd=Object.prototype,pd=hd.hasOwnProperty,Is=hd.toString,U=Array.isArray||function(t){return Is.call(t)==="[object Array]"},De=t=>typeof t=="function",he=t=>t===Object(t)&&!U(t),Kt=t=>{if(he(t)){for(var e in t)if(pd.call(t,e))return!1;return!0}return!1},C=t=>t===void 0,X=t=>Is.call(t)=="[object String]",Ko=t=>X(t)&&t.trim().length===0,Ke=t=>t===null,H=t=>C(t)||Ke(t),ke=t=>Is.call(t)=="[object Number]"&&t==t,Dt=t=>ke(t)&&t>0,gt=t=>Is.call(t)==="[object Boolean]",Np=t=>t instanceof FormData,Op=t=>j(Tp,t),Bp=t=>j($p,t);function gd(t){return t===null||typeof t!="object"}function Hr(t,e){return{}.toString.call(t)==="[object "+e+"]"}function Xa(t){return typeof Event<"u"&&md(t,Event)}function md(t,e){try{return t instanceof e}catch{return!1}}var Dp=[!0,"true",1,"1","yes"],uo=t=>j(Dp,t),jp=[!1,"false",0,"0","no"];function At(t,e,n,i,r){return e>n&&(i.warn("min cannot be greater than max."),e=n),ke(t)?t>n?(i.warn(" cannot be greater than max: "+n+". Using max value instead."),n):e>t?(i.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(i.warn(" must be a number. using max or fallback. max: "+n+", fallback: "+r),At(r||n,e,n,i))}class Up{constructor(e){this.tt={},this.et=e.et,this.it=At(e.bucketSize,0,100,e.rt),this.nt=At(e.refillRate,0,this.it,e.rt),this.st=At(e.refillInterval,0,864e5,e.rt)}ot(e,n){var i=Math.floor((n-e.lastAccess)/this.st);i>0&&(e.tokens=Math.min(e.tokens+i*this.nt,this.it),e.lastAccess=e.lastAccess+i*this.st)}consumeRateLimit(e){var n,i=Date.now(),r=String(e),s=this.tt[r];return s?this.ot(s,i):this.tt[r]=s={tokens:this.it,lastAccess:i},s.tokens===0||(s.tokens--,s.tokens===0&&((n=this.et)==null||n.call(this,e)),s.tokens===0)}stop(){this.tt={}}}var it="Mobile",Wr="iOS",Yt="Android",ei="Tablet",vd=Yt+" "+ei,_d="iPad",yd="Apple",wd=yd+" Watch",Bi="Safari",ti="BlackBerry",bd="Samsung",Ed=bd+"Browser",Sd=bd+" Internet",Pn="Chrome",Hp=Pn+" OS",xd=Pn+" "+Wr,Qa="Internet Explorer",Id=Qa+" "+it,el="Opera",Wp=el+" Mini",tl="Edge",kd="Microsoft "+tl,Zn="Firefox",Cd=Zn+" "+Wr,Gi="Nintendo",Ki="PlayStation",Xn="Xbox",Ad=Yt+" "+it,Pd=it+" "+Bi,Pi="Windows",Yo=Pi+" Phone",yc="Nokia",Jo="Ouya",Fd="Generic",qp=Fd+" "+it.toLowerCase(),Rd=Fd+" "+ei.toLowerCase(),Zo="Konqueror",Td="Oculus Browser",qr="Vivaldi",$d="Yandex",zr="Whale",Xo="DuckDuckGo",Md="Pale Moon",Vr="Waterfox",Di="Brave",Ld="Google Search App",we="(\\d+(\\.\\d+)?)",fo=new RegExp("Version/"+we),zp=new RegExp(Xn,"i"),Vp=new RegExp(Ki+" \\w+","i"),Gp=new RegExp(Gi+" \\w+","i"),nl=new RegExp(ti+"|PlayBook|BB10","i"),Kp={"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"},Nd=function(t,e,n,i){e=e||"";var r=(function(s){return s!=null&&s.brave?Di:null})(n);return r||(i!=null&&i.detectGoogleSearchApp&&j(t,"GSA/")?Ld:j(t," OPR/")&&j(t,"Mini")?Wp:j(t," OPR/")?el:nl.test(t)?ti:j(t,"IE"+it)||j(t,"WPDesktop")?Id:j(t,"OculusBrowser")?Td:j(t,Ed)?Sd:j(t,tl)||j(t,"Edg/")?kd:j(t,qr+"/")?qr:j(t,"YaBrowser/")?$d:j(t,zr+"/")?zr:j(t,Xo+"/")||j(t,"Ddg/")?Xo:j(t,"FBIOS")?"Facebook "+it:j(t,"UCWEB")||j(t,"UCBrowser")?"UC Browser":j(t,"CriOS")?xd:j(t,"CrMo")||j(t,Pn)?Pn:j(t,Yt)&&j(t,Bi)?Ad:j(t,"FxiOS")?Cd:j(t.toLowerCase(),Zo.toLowerCase())?Zo:j(t,Di+"/")?Di:((s,o)=>o&&j(o,yd)||(function(a){return j(a,Bi)&&!j(a,Pn)&&!j(a,Yt)})(s))(t,e)?j(t,it)?Pd:Bi:j(t,"PaleMoon/")?Md:j(t,Vr+"/")?Vr:j(t,Zn)?Zn:j(t,"MSIE")||j(t,"Trident/")?Qa:j(t,"Gecko")?Zn:"")},Yp={[Id]:[new RegExp("rv:"+we)],[kd]:[new RegExp(tl+"?\\/"+we)],[Pn]:[new RegExp("("+Pn+"|CrMo)\\/"+we)],[xd]:[new RegExp("CriOS\\/"+we)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+we)],[Bi]:[fo],[Pd]:[fo],[el]:[new RegExp("(Opera|OPR)\\/"+we)],[Zn]:[new RegExp(Zn+"\\/"+we)],[Cd]:[new RegExp("FxiOS\\/"+we)],[Zo]:[new RegExp("Konqueror[:/]?"+we,"i")],[ti]:[new RegExp(ti+" "+we),fo],[Ad]:[new RegExp("android\\s"+we,"i")],[Sd]:[new RegExp(Ed+"\\/"+we)],[Td]:[new RegExp("OculusBrowser\\/"+we)],[qr]:[new RegExp(qr+"\\/"+we)],[$d]:[new RegExp("YaBrowser\\/"+we)],[zr]:[new RegExp(zr+"\\/"+we)],[Di]:[new RegExp(Di+"\\/"+we)],[Xo]:[new RegExp("(DuckDuckGo|Ddg)\\/"+we)],[Md]:[new RegExp("PaleMoon\\/"+we)],[Vr]:[new RegExp(Vr+"\\/"+we)],[Ld]:[new RegExp("GSA\\/"+we)],[Qa]:[new RegExp("(rv:|MSIE )"+we)],Mozilla:[new RegExp("rv:"+we)]},Jp=function(t,e,n,i){var r=Nd(t,e,n,i),s=Yp[r];if(C(s))return null;for(var o=0;s.length>o;o++){var a=t.match(s[o]);if(a)return parseFloat(a[a.length-2])}return null},wc=[[new RegExp(Xn+"; "+Xn+" (.*?)[);]","i"),t=>[Xn,t&&t[1]||""]],[new RegExp(Gi,"i"),[Gi,""]],[new RegExp(Ki,"i"),[Ki,""]],[nl,[ti,""]],[new RegExp(Pi,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Yo,""];if(new RegExp(it).test(e)&&!/IEMobile\b/.test(e))return[Pi+" "+it,""];var n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){var i=Kp[n[1]]||"";return/arm/i.test(e)&&(i="RT"),[Pi,i]}return[Pi,""]}],[/((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=C(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+Yt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Yt+")","i"),t=>t&&t[2]?[Yt,[t[2],t[3],t[4]||"0"].join(".")]:[Yt,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{var e=["Mac OS X",""];return t&&t[1]&&(e[1]=[t[1],t[2],t[3]||"0"].join(".")),e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[Hp,""]],[/Linux|debian/i,["Linux",""]]],bc=function(t){return Gp.test(t)?Gi:Vp.test(t)?Ki:zp.test(t)?Xn:new RegExp(Jo,"i").test(t)?Jo:new RegExp("("+Yo+"|WPDesktop)","i").test(t)?Yo:/iPad/.test(t)?_d:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?wd:nl.test(t)?ti:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(yc,"i").test(t)?yc:/(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(it).test(t)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(t)||/pixel[\daxl ]{1,6}/i.test(t)&&!/pixel c/i.test(t)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(t)||/lmy47v/i.test(t)&&!/QTAQZ3/i.test(t)?Yt:vd:new RegExp("(pda|"+it+")","i").test(t)?qp:new RegExp(ei,"i").test(t)&&!new RegExp(ei+" pc","i").test(t)?Rd:""},Zp=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ec(t,e){return typeof(n=t)=="string"&&Zp.test(n)?t:e();var n}function fn(t){return t&&t.split("#")[0]}function il(t,e){var n=setTimeout(t,e);return n?.unref&&n?.unref(),n}function Sc(t,e,n){return Od.apply(this,arguments)}function Od(){return(Od=se((function*(t,e,n){var i;try{return yield Promise.race([t,new Promise(((r,s)=>{i=il((()=>{try{n?.(),r()}catch(o){s(o)}}),e)}))])}finally{clearTimeout(i)}}))).apply(this,arguments)}var Xp=t=>t instanceof Error,Bd={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},Qp=Bd.info;function Dd(t){if(gt(t))return{boolValue:t};if(typeof t=="number")return Number.isFinite(t)?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:{stringValue:String(t)};if(typeof t=="string")return{stringValue:t};if(U(t))return{arrayValue:{values:t.map((e=>Dd(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function Gr(t){var e=[];for(var n in t){var i=t[n];Ke(i)||C(i)||e.push({key:n,value:Dd(i)})}return e}function eg(t,e){var n=Bd[t.level||"info"]||Qp,i=n.text,r=n.number,s=String(Date.now())+"000000",o={};e.distinctId&&(o.posthogDistinctId=e.distinctId),e.sessionId&&(o.sessionId=e.sessionId),e.windowId&&(o["window.id"]=e.windowId),H(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),H(e.lastActivityTimestamp)||(o.lastActivityTimestamp=String(e.lastActivityTimestamp)),e.currentUrl&&(o["url.full"]=e.currentUrl),e.screenName&&(o["screen.name"]=e.screenName),e.appState&&(o["app.state"]=e.appState),e.activeFeatureFlags&&e.activeFeatureFlags.length>0&&(o.feature_flags=e.activeFeatureFlags);var a=k({},o,t.attributes||{}),l={timeUnixNano:s,observedTimeUnixNano:s,severityNumber:r,severityText:i,body:{stringValue:t.body},attributes:Gr(a)};return t.trace_id&&(l.traceId=t.trace_id),t.span_id&&(l.spanId=t.span_id),C(t.trace_flags)||(l.flags=t.trace_flags),l}function jd(t,e,n){return k({},t.resourceAttributes,{"service.name":t.serviceName||"unknown_service"},t.environment&&{"deployment.environment":t.environment},t.serviceVersion&&{"service.version":t.serviceVersion},{"telemetry.sdk.name":e,"telemetry.sdk.version":n})}function Ud(t,e,n,i){return{resourceLogs:[{resource:{attributes:Gr(e)},scopeLogs:[{scope:{name:n,version:i},logRecords:t}]}]}}let tg=class{constructor(t,e,n,i,r,s,o){var a;s===void 0&&(s=()=>Promise.resolve()),this._instance=t,this.Ne=e,this.rt=n,this.ut=i,this.ht=r,this.dt=s,this.vt=o,this.ct=null,this.ft=0,this.yt=0,this.bt=0,this._t=0,this.wt=!1,this.kt=e.maxBufferSize,this.xt=Math.max((a=e.maxQueueSize)!==null&&a!==void 0?a:e.maxBufferSize,e.maxBufferSize),this.St=e.flushIntervalMs,this.Ct=e.maxBatchRecordsPerPost,this.Mt=e.rateCapWindowMs,this.Tt=e.maxLogsPerInterval}reset(){this.Et(),this.ct=null,this.bt=0,this._t=0,this.wt=!1,this.ft=0,this.yt=0,this.Ct=this.Ne.maxBatchRecordsPerPost}onReconnect(){this.yt=0,this.It()}captureLog(t){if(!this._instance.isDisabled&&!this._instance.optedOut&&t!=null&&t.body){var e=this.Pt(t);if(e!==null)if(e.body){if(this.Rt()){var n={record:eg(e,this.ut())};this.ht((()=>this.At(n)))}}else this.rt.info("Log was rejected in beforeSend function")}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Log was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for log:",o),null}return i}Rt(){if(this.Tt===void 0)return!0;var t=Date.now(),e=t-this.bt;return this.Mt>e&&e>=0||(this.bt=t,this._t=0,this.wt=!1),this.Tt>this._t?(this._t++,!0):(this.wt||(this.rt.warn("captureLog dropping logs: exceeded "+this.Tt+" logs per "+this.Mt+"ms"),this.wt=!0),!1)}flush(){var t=this;return se((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return se((function*(){var e;t.Et();var n=(e=t._instance.getPersistedProperty(Ut.LogsQueue))!==null&&e!==void 0?e:[];if(n.length!==0)for(var i=n.length,r=0;n.length>0&&i>r;){var s,o;t.ft=0;var a=Math.min(n.length,t.Ct),l=n.slice(0,a),u=Ud(l.map((d=>d.record)),t.Lt(),(s=t.vt)!==null&&s!==void 0?s:t._instance.getLibraryId(),t._instance.getLibraryVersion()),c=yield t._instance.Ot(u);if(c.kind==="too-large"&&l.length>1)t.Ct=Math.max(1,Math.floor(l.length/2)),t.rt.warn("Received 413 when sending logs batch of size "+l.length+", reducing batch size to "+t.Ct);else if(c.kind==="retry-later"||(c.kind==="too-large"?t.rt.warn("Dropping a single log record after 413 with batch size 1 — the record is larger than the server cap and cannot be split further."):c.kind==="ok"&&t.Ne.maxBatchRecordsPerPost>t.Ct&&(t.Ct=Math.min(t.Ne.maxBatchRecordsPerPost,t.Ct+1)),yield t.Dt(l.length),n=(o=t._instance.getPersistedProperty(Ut.LogsQueue))!==null&&o!==void 0?o:[],r+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return se((function*(){var n,i=Math.max(0,t-e.ft),r=(n=e._instance.getPersistedProperty(Ut.LogsQueue))!==null&&n!==void 0?n:[];e._instance.setPersistedProperty(Ut.LogsQueue,r.slice(i)),yield e.dt()}))()}Lt(){return jd(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var n=(e=this._instance.getPersistedProperty(Ut.LogsQueue))!==null&&e!==void 0?e:[];this.xt>n.length||(n.shift(),this.ft++,this.rt.info("Logs queue is full, dropping oldest record.")),n.push(t),this._instance.setPersistedProperty(Ut.LogsQueue,n),this.kt>n.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=il((()=>{this.Nt=void 0,this.It()}),t))}qt(){var t=Math.min(Math.max(0,this.yt-1),6);return this.St*Math.pow(2,t)}jt(){var t=this._instance.getPersistedProperty(Ut.LogsQueue);return!!t&&t.length>0}shutdown(t){var e=this;return se((function*(){e.Et();var n=e.flush().catch((()=>{}));t!==void 0?yield Sc(n,t):yield n}))()}flushWithTimeout(t){var e=this;return se((function*(){var n=e.flush();yield Sc(n,t,(()=>{n.catch((()=>{}))}))}))()}It(){this.flush().then((()=>{this.yt=0}),(t=>{this.yt++,this.rt.error("PostHog logs flush failed:",t)})).finally((()=>{!this._instance.isDisabled&&this.jt()&&this.$t(this.qt())}))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}};var ho=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function xc(t){return String(t)+"000000"}function Ic(t,e,n,i){var r="";return i&&(r=Object.keys(i).sort().map((s=>JSON.stringify(s)+":"+JSON.stringify(i[s]))).join(",")),t+"\0"+e+"\0"+(n??"")+"\0"+r}let ng=class{constructor(t,e,n){this._instance=t,this.Ne=e,this.rt=n,this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Wt=0}count(t,e,n){e===void 0&&(e=1),this.Vt({name:t,type:"count",value:e,unit:n?.unit,attributes:n?.attributes})}gauge(t,e,n){this.Vt({name:t,type:"gauge",value:e,unit:n?.unit,attributes:n?.attributes})}histogram(t,e,n){this.Vt({name:t,type:"histogram",value:e,unit:n?.unit,attributes:n?.attributes})}flush(){var t=this,e=this.ct,n=(function(){var r=se((function*(){e&&(yield e.catch((()=>{}))),yield t.Zt()}));return function(){return r.apply(this,arguments)}})(),i=n().finally((()=>{this.ct===i&&(this.ct=null)}));return this.ct=i,i}drainWindow(){if(this.Bt.size===0)return null;var t=this.Bt;return this.Bt=new Map,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Gt(t)}reset(){this.Wt++,this.Et(),this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set}Vt(t){if(!this._instance.isDisabled&&!this._instance.optedOut){var e=this.Pt(t);if(e!==null)if(e.name&&typeof e.name=="string")if(typeof e.value=="number"&&Number.isFinite(e.value))if(e.type==="count"&&0>e.value)this.rt.warn("Dropping count '"+e.name+"': counters are monotonic, value must be >= 0");else{var n,i;try{n=e.attributes?k({},e.attributes):void 0,i=Ic(e.type,e.name,e.unit,n)}catch(o){return void this.rt.warn("Dropping metric '"+e.name+"': attributes could not be serialized",o)}var r=this.Bt.get(i);if(!r){if(!this.Qt())return;r={name:e.name,type:e.type,unit:e.unit,attributes:n,windowStartMs:Date.now()},this.Bt.set(i,r)}var s=this.Ut.get(e.name);s===void 0?this.Ut.set(e.name,e.type):s===e.type||this.zt.has(e.name)||(this.zt.add(e.name),this.rt.warn("Metric name '"+e.name+"' is already used as a "+s+"; recording it as a "+e.type+" too will blend both series in charts. Use a distinct name.")),this.Kt(r,e.value),this.$t()}else this.rt.warn("Dropping metric '"+e.name+"': value must be a finite number");else this.rt.warn("Dropping metric with empty name")}}Qt(){return this.Ne.maxSeriesPerFlush>this.Bt.size||(this.Ht||(this.Ht=!0,this.rt.warn("Metric series cap reached ("+this.Ne.maxSeriesPerFlush+" per flush window); dropping new series until the next flush. Reduce attribute cardinality.")),!1)}Kt(t,e){var n;switch(t.type){case"count":t.total=((n=t.total)!==null&&n!==void 0?n:0)+e;break;case"gauge":t.last=e;break;case"histogram":t.hist||(t.hist={count:0,sum:0,min:e,max:e,bucketCounts:new Array(ho.length+1).fill(0)});var i=t.hist;i.count+=1,i.sum+=e,i.min=Math.min(i.min,e),i.max=Math.max(i.max,e),i.bucketCounts[(function(r,s){for(var o=0;s.length>o;o++)if(s[o]>=r)return o;return s.length})(e,ho)]+=1}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Metric was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for metric:",o),null}return i}$t(){this.Nt||(this.Nt=il((()=>{this.Nt=void 0,this.flush().catch((t=>{this.rt.error("Metrics flush failed:",t)}))}),this.Ne.flushIntervalMs))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}Zt(){var t=this;return se((function*(){if(t.Bt.size!==0){var e=t.Bt;t.Bt=new Map,t.Ht=!1,t.Ut=new Map,t.zt=new Set;var n=t.Wt,i=yield t._instance.Jt(t.Gt(e));if(n===t.Wt)switch(i.kind){case"ok":return;case"retry-later":return t.Yt(e),void t.$t();case"too-large":return void t.rt.warn("Metrics batch exceeded the server size limit and was dropped");case"fatal":return void t.rt.error("Failed to send metrics batch:",i.error)}}}))()}Gt(t){return e=this.Xt(t),n=(function(s,o,a){return k({},s.resourceAttributes,{"service.name":s.serviceName||"unknown_service"},s.environment&&{"deployment.environment":s.environment},s.serviceVersion&&{"service.version":s.serviceVersion},{"telemetry.sdk.name":o,"telemetry.sdk.version":a})})(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion()),i=this._instance.getLibraryId(),r=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:Gr(n)},scopeMetrics:[{scope:{name:i,version:r},metrics:e}]}]};var e,n,i,r}Xt(t){var e=xc(Date.now()),n=new Map;for(var i of t.values()){var r,s=Ic(i.type,i.name,i.unit,void 0),o=n.get(s);o||(o=k({name:i.name},i.unit&&{unit:i.unit}),i.type==="count"?o.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:i.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:1,dataPoints:[]},n.set(s,o));var a=Gr((r=i.attributes)!==null&&r!==void 0?r:{}),l=xc(i.windowStartMs);if(i.type==="count"){var u,c={attributes:a,startTimeUnixNano:l,timeUnixNano:e,asDouble:(u=i.total)!==null&&u!==void 0?u:0};o.sum.dataPoints.push(c)}else if(i.type==="gauge"){var d,f={attributes:a,timeUnixNano:e,asDouble:(d=i.last)!==null&&d!==void 0?d:0};o.gauge.dataPoints.push(f)}else i.hist&&o.histogram.dataPoints.push({attributes:a,startTimeUnixNano:l,timeUnixNano:e,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:ho})}return Array.from(n.values())}Yt(t){var e,n;for(var i of t){var r=i[0],s=i[1],o=this.Bt.get(r);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,s.windowStartMs),o.type){case"count":o.total=((e=o.total)!==null&&e!==void 0?e:0)+((n=s.total)!==null&&n!==void 0?n:0);break;case"gauge":break;case"histogram":if(s.hist)if(o.hist){o.hist.count+=s.hist.count,o.hist.sum+=s.hist.sum,o.hist.min=Math.min(o.hist.min,s.hist.min),o.hist.max=Math.max(o.hist.max,s.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=s.hist.bucketCounts[a]}else o.hist=s.hist}else this.Qt()&&this.Bt.set(r,s)}}};var gr,kc,po;function ig(t){var e=globalThis._posthogChunkIds;if(e){var n=Object.keys(e);return po&&n.length===kc||(kc=n.length,po=n.reduce(((i,r)=>{gr||(gr={});var s=gr[r];if(s)i[s[0]]=s[1];else for(var o=t(r),a=o.length-1;a>=0;a--){var l=o[a],u=l?.filename,c=e[r];if(u&&c){i[u]=c,gr[r]=[u,c];break}}return i}),{})),po}}class rg{constructor(e,n,i){i===void 0&&(i=[]),this.coercers=e,this.stackParser=n,this.modifiers=i}buildFromUnknown(e,n){n===void 0&&(n={});var i=n&&n.mechanism||{handled:!0,type:"generic"},r=this.buildCoercingContext(i,n,0).apply(e),s=this.buildParsingContext(n),o=this.parseStacktrace(r,s);return{$exception_list:this.convertToExceptionList(o,i),$exception_level:"error"}}modifyFrames(e){var n=this;return se((function*(){for(var i of e)i.stacktrace&&i.stacktrace.frames&&U(i.stacktrace.frames)&&(i.stacktrace.frames=yield n.applyModifiers(i.stacktrace.frames));return e}))()}coerceFallback(e){var n;return{type:"Error",value:"Unknown error",stack:(n=e.syntheticException)==null?void 0:n.stack,synthetic:!0}}parseStacktrace(e,n){var i,r;return e.cause!=null&&(i=this.parseStacktrace(e.cause,n)),e.stack!=""&&e.stack!=null&&(r=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?n.skipFirstLines:0),n.chunkIdMap)),k({},e,{cause:i,stack:r})}applyChunkIds(e,n){return e.map((i=>(i.filename&&n&&(i.chunk_id=n[i.filename]),i)))}applyCoercers(e,n){for(var i of this.coercers)if(i.match(e))return i.coerce(e,n);return this.coerceFallback(n)}applyModifiers(e){var n=this;return se((function*(){var i=e;for(var r of n.modifiers)i=yield r(i);return i}))()}convertToExceptionList(e,n){var i,r,s,o={type:e.type,value:e.value,mechanism:{type:(i=n.type)!==null&&i!==void 0?i:"generic",handled:(r=n.handled)===null||r===void 0||r,synthetic:(s=e.synthetic)!==null&&s!==void 0&&s}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,k({},n,{handled:!0}))),a}buildParsingContext(e){var n;return{chunkIdMap:ig(this.stackParser),skipFirstLines:(n=e.skipFirstLines)!==null&&n!==void 0?n:1}}buildCoercingContext(e,n,i){i===void 0&&(i=0);var r=(s,o)=>{if(4>=o){var a=this.buildCoercingContext(e,n,o);return this.applyCoercers(s,a)}};return k({},n,{syntheticException:i==0?n.syntheticException:void 0,mechanism:e,apply:s=>r(s,i),next:s=>r(s,i+1)})}}var ni="?";function Qo(t,e,n,i,r){var s={platform:t,filename:e,function:n===""?ni:n,in_app:!0};return C(i)||(s.lineno=i),C(r)||(s.colno=r),s}var Hd=(t,e)=>{var n=t.indexOf("safari-extension")!==-1,i=t.indexOf("safari-web-extension")!==-1;return n||i?[t.indexOf("@")!==-1?t.split("@")[0]:ni,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},sg=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,og=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,ag=/\((\S*)(?::(\d+))(?::(\d+))\)/,lg=(t,e)=>{var n=sg.exec(t);if(n)return Qo(e,n[1],ni,+n[2],+n[3]);var i=og.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var r=ag.exec(i[2]);r&&(i[2]=r[1],i[3]=r[2],i[4]=r[3])}var s=Hd(i[1]||ni,i[2]);return Qo(e,s[1],s[0],i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},cg=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,ug=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,dg=(t,e)=>{var n=cg.exec(t);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){var i=ug.exec(n[3]);i&&(n[1]=n[1]||"eval",n[3]=i[1],n[4]=i[2],n[5]="")}var r=n[3],s=n[1]||ni,o=Hd(s,r);return Qo(e,r=o[1],s=o[0],n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},Cc=/\(error: (.*)\)/;class fg{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,n){var i=X(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:i?e.stack:void 0,cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var n=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?n+": "+e.message:n}isDOMException(e){return Hr(e,"DOMException")}isDOMError(e){return Hr(e,"DOMError")}}class hg{match(e){return(function(n){switch({}.toString.call(n)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return md(n,Error)}})(e)}coerce(e,n){return{type:this.getType(e),value:this.getMessage(e,n),stack:this.getStack(e),cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,n){var i=e.message;return String(i.error&&typeof i.error.message=="string"?i.error.message:i)}getStack(e){return e.stacktrace||e.stack||void 0}}class pg{constructor(){}match(e){return!!Hr(e,"ErrorEvent")&&(e.error!=null||this.fe(e))}coerce(e,n){var i;if(e.error!=null)return n.apply(e.error);var r=n.apply(e.message);return k({},r,{stack:(i=this.pe(e))!==null&&i!==void 0?i:r.stack,synthetic:!0})}fe(e){return X(e.message)&&e.message.length>0}pe(e){var n=e;if(X(n.filename)&&n.filename.length>0){var i,r,s=(i=n.lineno)!==null&&i!==void 0?i:0,o=(r=n.colno)!==null&&r!==void 0?r:0;return`Error - at `+n.filename+":"+s+":"+o}}}var gg=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class mg{match(e){return typeof e=="string"}coerce(e,n){var i,r=this.getInfos(e),s=r[0],o=r[1];return{type:s??"Error",value:o??e,stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}getInfos(e){var n="Error",i=e,r=e.match(gg);return r&&(n=r[1],i=r[2]),[n,i]}}var vg=["fatal","error","warning","log","info","debug"];function Wd(t,e){e===void 0&&(e=40);var n=Object.keys(t);if(n.sort(),!n.length)return"[object has no keys]";for(var i=n.length;i>0;i--){var r=n.slice(0,i).join(", ");if(e>=r.length)return i===n.length?r:r.length>e?r.slice(0,e)+"...":r}return""}class _g{match(e){return typeof e=="object"&&e!==null}coerce(e,n){var i,r,s=this.getErrorPropertyFromObject(e);return s?n.apply(s):{type:this.getType(e),value:this.getValue(e),stack:(i=this.getStack(e))!==null&&i!==void 0?i:(r=n.syntheticException)==null?void 0:r.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return Xa(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var n="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(n+=" with message: '"+e.message+"'"),n}if("message"in e&&typeof e.message=="string")return e.message;var i=this.getObjectClassName(e);return(i&&i!=="Object"?"'"+i+"'":"Object")+" captured as exception with keys: "+Wd(e)}isSeverityLevel(e){return X(e)&&!Ko(e)&&vg.indexOf(e)>=0}getStack(e){try{return X(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:X(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(var n in e)if({}.hasOwnProperty.call(e,n)){var i=e[n];if(Xp(i))return i}}getObjectClassName(e){try{var n=Object.getPrototypeOf(e);return n?n.constructor.name:void 0}catch{return}}}class yg{match(e){return Xa(e)}coerce(e,n){var i,r=e.constructor.name;return{type:r,value:r+" captured as exception with keys: "+Wd(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class wg{match(e){return gd(e)}coerce(e,n){var i;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class bg{match(e){return Hr(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Xa(e))return!1;try{var n=e.detail;return n!=null&&typeof n=="object"&&"reason"in n}catch{return!1}}coerce(e,n){var i,r=this.getUnhandledRejectionReason(e);return gd(r)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(r),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}:n.apply(r)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}}var Kr="$message",Yr="$timestamp",Eg=new Set([Kr,Yr]),go={enabled:!0,max_bytes:32768};function Jr(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:go.enabled,max_bytes:xg(t.max_bytes,go.max_bytes)}:k({},go)}class Sg{constructor(e){this.Ke=[],this.Je=0,this.Ne=Jr(e)}setConfig(e){this.Ne=Jr(e),this.Xe()}add(e){var n=(function(r){var s;try{s=fd(r)}catch{return}try{var o=JSON.parse(s);if(!he(o))return;var a=o,l=a[Kr],u=a[Yr];return!X(l)||l.trim().length===0||!X(u)&&!ke(u)?void 0:{step:a,json:s}}catch{return}})(e);if(n){var i=(function(r){if(typeof TextEncoder<"u")return new TextEncoder().encode(r).length;for(var s=encodeURIComponent(r),o=0,a=0;s.length>a;a++)s[a]==="%"?(o+=1,a+=2):o+=1;return o})(n.json);i>this.Ne.max_bytes||(this.Ke.push({step:n.step,bytes:i}),this.Je+=i,this.Xe())}}getAttachable(){return this.Ke.map((e=>e.step))}clear(){this.Ke=[],this.Je=0}size(){return this.Ke.length}Xe(){for(;this.Je>this.Ne.max_bytes&&this.Ke.length>0;){var e=this.Ke.shift();e&&(this.Je-=e.bytes)}}}function xg(t,e){if(!ke(t)||t===1/0||t===-1/0)return e;var n=Math.floor(t);return 0>n?e:n}var qd=function(t,e){var n=(e===void 0?{}:e).debugEnabled,i={k(r){if(w&&(ne.DEBUG||w.POSTHOG_DEBUG||n)&&!C(w.console)&&w.console){for(var s=("__rrweb_original__"in w.console[r])?w.console[r].__rrweb_original__:w.console[r],o=arguments.length,a=new Array(o>1?o-1:0),l=1;o>l;l++)a[l-1]=arguments[l];s(t,...a)}},debug(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("debug",...s)},info(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("log",...s)},warn(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("warn",...s)},error(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("error",...s)},critical(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];console.error(t,...s)},uninitializedWarning(r){i.error("You must initialize PostHog before calling "+r)},createLogger:(r,s)=>qd(t+" "+r,s)};return i},A=qd("[PostHog.js]"),pe=A.createLogger,Ig=pe("[ExternalScriptsLoader]"),mo=(t,e,n)=>{if(t.config.disable_external_dependency_loading)return Ig.warn(e+" was requested but loading of external scripts is disabled."),n("Loading of external scripts is disabled");var i=F?.querySelectorAll("script");if(i){for(var r,s=function(){if(i[o].src===e){var l=i[o];return l.__posthog_loading_callback_fired?{v:n()}:(l.addEventListener("load",(u=>{l.__posthog_loading_callback_fired=!0,n(void 0,u)})),l.onerror=u=>n(u),{v:void 0})}},o=0;i.length>o;o++)if(r=s())return r.v}var a=()=>{if(!F)return n("document not found");var l=F.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=d=>{l.__posthog_loading_callback_fired=!0,n(void 0,d)},l.onerror=d=>n(d),t.config.prepare_external_dependency_script&&(l=t.config.prepare_external_dependency_script(l)),!l)return n("prepare_external_dependency_script returned null");if(t.config.external_scripts_inject_target==="head")F.head.appendChild(l);else{var u,c=F.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):F.body.appendChild(l)}};F!=null&&F.body?a():F?.addEventListener("DOMContentLoaded",a)};B.__PosthogExtensions__=B.__PosthogExtensions__||{},B.__PosthogExtensions__.loadExternalDependency=(t,e,n)=>{if(e!=="remote-config"){var i;if(t.config.strict_script_versioning)i=t.requestRouter.endpointFor("assets","/static/"+t.version+"/"+e+".js");else{var r="/static/"+e+".js?v="+t.version;if(e==="toolbar"){var s=3e5;r=r+"&t="+Math.floor(Date.now()/s)*s}i=t.requestRouter.endpointFor("assets",r)}mo(t,i,n)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");mo(t,o,n)}},B.__PosthogExtensions__.loadSiteApp=(t,e,n)=>{var i=t.requestRouter.endpointFor("api",e);mo(t,i,n)};ne.DEBUG=!1,ne.LIB_VERSION="1.415.7",ne.LIB_NAME="web";var zd="$people_distinct_id",Yi="$device_id",vo="$device_model",Fi="__alias",Ri="__timers",ea="$autocapture_disabled_server_side",ta="$heatmaps_enabled_server_side",na="$exception_capture_enabled_server_side",ia="$error_tracking_suppression_rules",ra="$error_tracking_capture_extension_exceptions",sa="$web_vitals_enabled_server_side",rl="$dead_clicks_enabled_server_side",sl="$product_tours_enabled_server_side",oa="$web_vitals_allowed_metrics",An="$session_recording_remote_config",Vd="$replay_sample_rate",Gd="$replay_override_sampling",Kd="$replay_override_linked_flag",Yd="$replay_override_url_trigger",Jd="$replay_override_event_trigger",Kn="$sesid",ol="$session_is_sampled",Sn="$enabled_feature_flags",Ti="$active_feature_flags",Ar="$early_access_features",aa="$feature_flag_details",$i="$feature_flag_payloads",Pr="$feature_flag_request_id",Zr="$minimal_flag_called_events",It="$override_feature_flags",xn="$override_feature_flag_payloads",jt="$stored_person_properties",In="$stored_group_properties",la="$surveys",Xr="$surveys_loaded_at",ca="$surveys_activated",Fr="$surveys_activated_session",Rr="$surveys_activated_timestamps",Mi="ph_product_tours",Cn="$flag_call_reported",Li="$flag_call_reported_session_id",Tr="$feature_flag_errors",ji="$feature_flag_evaluated_at",ot="$user_state",ua="$client_session_props",da="$capture_rate_limit",fa="$initial_campaign_params",ha="$initial_referrer_info",Qr="$initial_person_info",es="$epp",mr="$posthog_cookieless",Zd="$cookieless_mode",Xd="$sdk_debug_extensions_init_method",Qd="$sdk_debug_extensions_init_time_ms",ef="$sdk_debug_recording_script_not_loaded",al="PostHog loadExternalDependency extension not found.",kn="on_reject",Wt="always",Un="anonymous",vn="identified",pa="identified_only",ts="visibilitychange",ns="beforeunload",Vn="$pageview",_o="$pageleave",yo="$identify",Ac="$groupidentify";function vr(t,e){U(t)&&t.forEach(e)}function ie(t,e){if(!H(t))if(U(t))t.forEach(e);else if(Np(t))t.forEach(((i,r)=>e(i,r)));else for(var n in t)pd.call(t,n)&&e(t[n],n)}var fe=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;e>i;i++)n[i-1]=arguments[i];for(var r of n)for(var s in r)r[s]!==void 0&&(t[s]=r[s]);return t};function $r(t){for(var e=Object.keys(t),n=e.length,i=new Array(n);n--;)i[n]=[e[n],t[e[n]]];return i}var Pc=function(t){try{return t()}catch{return}},kg=function(t){return function(){try{for(var e=arguments.length,n=new Array(e),i=0;e>i;i++)n[i]=arguments[i];return t.apply(this,n)}catch(r){A.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),A.critical(r)}}},ll=function(t){var e={};return ie(t,(function(n,i){(X(n)&&n.length>0||ke(n))&&(e[i]=n)})),e},Cg=["herokuapp.com","vercel.app","netlify.app"];function Ag(t){var e=t?.hostname;if(!X(e))return!1;var n=e.split(".").slice(-2).join(".");for(var i of Cg)if(n===i)return!1;return!0}function ve(t,e,n,i){var r=i??{},s=r.capture,o=r.passive;t?.addEventListener(e,n,{capture:s!==void 0&&s,passive:o===void 0||o})}function ga(t){return t.name==="ph_toolbar_internal"}var tf=t=>{if(F){try{for(var e=t+"=",n=F.cookie.split(";").filter((s=>s.length)),i=0;n.length>i;i++){for(var r=n[i];r.charAt(0)==" ";)r=r.substring(1,r.length);if(r.indexOf(e)===0)return decodeURIComponent(r.substring(e.length,r.length))}}catch{}return null}};Math.trunc||(Math.trunc=function(t){return 0>t?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return ke(t)&&isFinite(t)&&Math.floor(t)===t});class is{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,n,i,r){if(!Number.isInteger(e)||!Number.isInteger(n)||!Number.isInteger(i)||!Number.isInteger(r)||0>e||0>n||0>i||0>r||e>0xffffffffffff||n>4095||i>1073741823||r>4294967295)throw new RangeError("invalid field value");var s=new Uint8Array(16);return s[0]=e/Math.pow(2,40),s[1]=e/Math.pow(2,32),s[2]=e/Math.pow(2,24),s[3]=e/Math.pow(2,16),s[4]=e/256,s[5]=e,s[6]=112|n>>>8,s[7]=n,s[8]=128|i>>>24,s[9]=i>>>16,s[10]=i>>>8,s[11]=i,s[12]=r>>>24,s[13]=r>>>16,s[14]=r>>>8,s[15]=r,new is(s)}toString(){for(var e="",n=0;this.bytes.length>n;n++)e=e+(this.bytes[n]>>>4).toString(16)+(15&this.bytes[n]).toString(16),n!==3&&n!==5&&n!==7&&n!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new is(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var n=0;16>n;n++){var i=this.bytes[n]-e.bytes[n];if(i!==0)return Math.sign(i)}return 0}}class Pg{generate(){var e=this.generateOrAbort();if(!C(e))return e;this.S=0;var n=this.generateOrAbort();if(C(n))throw new Error("Could not generate UUID after timestamp reset");return n}generateOrAbort(){var e=Date.now();if(e>this.S)this.S=e,this.C();else{if(this.S>=e+1e4)return;this.I++,this.I>4398046511103&&(this.S++,this.C())}return is.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 Fg}}var Fc,nf=t=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;t.length>e;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};w&&!C(w.crypto)&&crypto.getRandomValues&&(nf=t=>crypto.getRandomValues(t));class Fg{nextUint32(){return this.R.length>this.O||(nf(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var Ht=()=>Rg().toString(),Rg=()=>(Fc||(Fc=new Pg)).generate(),yi="",Tg=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,qt={N:()=>!!F,j(t){A.error("cookieStore error: "+t)},P:tf,H(t){var e;try{e=JSON.parse(qt.P(t))||{}}catch{}return e},F(t,e,n,i,r){if(!F)return!1;try{var s="",o="",a=(function(c,d){if(d){var f=(function(p,g){if(g===void 0&&(g=F),yi)return yi;if(!g||["localhost","127.0.0.1"].includes(p))return"";for(var m=p.split("."),v=Math.min(m.length,8),S="dmn_chk_"+Ht();!yi&&v--;){var b=m.slice(v).join("."),_=S+"=1;domain=."+b+";path=/";g.cookie=_+";max-age=3",g.cookie.includes(S)&&(g.cookie=_+";max-age=0",yi=b)}return yi})(c);if(!f){var h=(p=>{var g=p.match(Tg);return g?g[0]:""})(c);h!==f&&A.info("Warning: cookie subdomain discovery mismatch",h,f),f=h}return f?"; domain=."+f:""}return""})(F.location.hostname,i);if(n){var l=new Date;l.setTime(l.getTime()+864e5*n),s="; expires="+l.toUTCString()}r&&(o="; secure");var u=t+"="+encodeURIComponent(JSON.stringify(e))+s+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&A.warn("cookieStore warning: large cookie, len="+u.length),F.cookie=u,!0}catch{return!1}},q(t,e){if(F!=null&&F.cookie)try{qt.F(t,"",-1,e)}catch{return}}},wo=null,le={N(){if(!Ke(wo))return wo;var t=!0;if(C(w))t=!1;else try{var e="__mplssupport__";le.F(e,"xyz"),le.P(e)!=='"xyz"'&&(t=!1),le.q(e)}catch{t=!1}return t||A.error("localStorage unsupported; falling back to cookie store"),wo=t,t},j(t){A.error("localStorage error: "+t)},P(t){try{return w?.localStorage.getItem(t)}catch(e){le.j(e)}return null},H(t){try{return JSON.parse(le.P(t))||{}}catch{}return null},F(t,e){try{return w?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(n){le.j(n)}return!1},q(t){try{w?.localStorage.removeItem(t)}catch(e){le.j(e)}}},$g=[Yi,"distinct_id",Kn,ol,es,Qr,ot],_r={},Mg={N:()=>!0,j(t){A.error("memoryStorage error: "+t)},P:t=>_r[t]||null,H:t=>_r[t]||null,F:(t,e)=>(_r[t]=e,!0),q(t){delete _r[t]}},_n=null,be={N(){if(!Ke(_n))return _n;if(_n=!0,C(w))_n=!1;else try{var t="__support__";be.F(t,"xyz"),be.P(t)!=='"xyz"'&&(_n=!1),be.q(t)}catch{_n=!1}return _n},j(t){A.error("sessionStorage error: ",t)},P(t){try{return w?.sessionStorage.getItem(t)}catch(e){be.j(e)}return null},H(t){try{return JSON.parse(be.P(t))||null}catch{}return null},F(t,e){try{return w?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(n){be.j(n)}return!1},q(t){try{w?.sessionStorage.removeItem(t)}catch(e){be.j(e)}}};class Lg{constructor(e){this._instance=e}get Ne(){return this._instance.config}get consent(){return this.ti()?0:this.ei}isOptedOut(){return this.Ne.cookieless_mode===Wt||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===kn}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===0}isRejected(){return this.consent===0||this.consent===-1&&this.Ne.opt_out_capturing_by_default}optInOut(e){this.ii.F(this.ri,e?1:0,this.Ne.cookie_expiration,this.Ne.cross_subdomain_cookie,this.Ne.secure_cookie)}reset(){this.ii.q(this.ri,this.Ne.cross_subdomain_cookie)}get ri(){var e=this._instance.config,n=e.token,i=e.opt_out_capturing_cookie_prefix;return e.consent_persistence_name||(i?i+n:"__ph_opt_in_out_"+n)}get ei(){var e=this.ii.P(this.ri);return uo(e)?1:j(jp,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,n=e==="localStorage"?le:qt;if(!this.ni||this.ni!==n){this.ni=n;var i=e==="localStorage"?qt:le;i.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(uo(i.P(this.ri))),i.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[Ue?.doNotTrack,Ue?.msDoNotTrack,B.doNotTrack].some((e=>uo(e)))}}function rf(t,e){var n,i=t==null||(n=t.config)==null?void 0:n.get_current_url;if(!De(i))return e;try{var r=i(e);return X(r)&&r?r:e}catch(s){return A.error("Error in get_current_url, falling back to window.location.href",s),e}}var sf="__POSTHOG_TOOLBAR__",Ng=1,Og=3,Bg=11;function Rc(t){return t instanceof Element&&(t.id===sf||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function hn(t){return!!t&&t.nodeType===Ng}function Qe(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function of(t){return!!t&&t.nodeType===Og}function af(t){return!!t&&t.nodeType===Bg&&hn(t.host)}var lf=1e3;function cl(t){return t?xs(t).split(/\s+/):[]}function Tc(t,e){var n=(function(i){var r,s=w==null||(r=w.location)==null?void 0:r.href;return C(s)?void 0:rf(i,s)})(e);return!!(n&&t&&t.some((i=>n.match(i))))}function rs(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 cl(e)}function cf(t){return H(t)?null:xs(t).split(/(\s+)/).filter((e=>Ui(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function Ji(t){var e="";return va(t)&&!hf(t)&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;of(n)&&n.textContent&&(e+=(i=cf(n.textContent))!==null&&i!==void 0?i:"")})),xs(e)}function bo(t){var e;return C(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var ul=["a","button","form","input","select","textarea","label"];function ma(t,e){if(C(e))return!0;var n,i=function(s){if(e.some((o=>(function(a,l){var u=a.matches||a.matchesSelector||a.msMatchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.oMatchesSelector;try{return!!u&&u.call(a,l)}catch{return!1}})(s,o))))return{v:!0}};for(var r of t)if(n=i(r))return n.v;return!1}function uf(t){var e=t.parentNode;return!(!e||!hn(e))&&e}var Dg=[".ph-no-autocapture","[data-ph-no-autocapture]"],df=["next","previous","prev",">","<"],jg=[...df,"+","-","−","–"],$c=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,Mc=[".ph-no-rageclick",".ph-no-capture"],Ug=["","text","search","email","password","url","tel","number"];function Lc(t,e){if(!w||dl(t))return!1;var n,i,r,s,o;if(gt(e)?(n=!!e&&Mc,i=void 0,r=!1):(n=(s=e?.css_selector_ignorelist)!==null&&s!==void 0?s:Mc,i=e?.content_ignorelist,r=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),n===!1||r&&(function(l){return!(!l||!hn(l))&&(!!Qe(l,"textarea")||(Qe(l,"input")?j(Ug,(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=ff(t,!1).targetElementList;return!(function(l,u){if(l===!1||C(l))return!1;var c;if(l===!0)c=df;else{if(!U(l))return!1;if(l.length>10)return A.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var f=d.safeText,h=d.ariaLabel;return c.some((p=>$c(f,p)||$c(h,p)))}))})(i,a.map((l=>{var u;return{safeText:Ji(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!ma(a,n)}var dl=t=>!t||Qe(t,"html")||!hn(t),ff=(t,e)=>{if(!w||dl(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,i=[t],r=t;r.parentNode&&!Qe(r,"body");)if(af(r.parentNode))i.push(r.parentNode.host),r=r.parentNode.host;else{var s=uf(r);if(!s)break;if(e||ul.indexOf(s.tagName.toLowerCase())>-1)n=!0;else try{var o=w.getComputedStyle(s);o&&o.getPropertyValue("cursor")==="pointer"&&(n=!0)}catch{}i.push(s),r=s}return{parentIsUsefulElement:n,targetElementList:i}};function va(t){for(var e=new Set,n=0,i=t;i.parentNode&&!Qe(i,"body");i=i.parentNode){if(n++>=lf||e.has(i))return!1;e.add(i);var r=rs(i);if(j(r,"ph-sensitive")||j(r,"ph-no-capture"))return!1}if(j(rs(t),"ph-include"))return!0;var s=t.type||"";if(X(s))switch(s.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!X(o)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(o.replace(/[^a-zA-Z0-9]/g,""))}function hf(t){return!!(Qe(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||Qe(t,"select")||Qe(t,"textarea")||t.getAttribute("contenteditable")==="true")}var Nc=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}))$"),Oc=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,Hg=[16,15,14,13],Wg=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),Bc=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),Dc=/[0-9A-Za-z_]/;function qg(t){for(var e=0,n=!1,i=t.length-1;i>=0;i--){var r=t.charCodeAt(i)-48;n&&(r*=2)>9&&(r-=9),e+=r,n=!n}return e%10==0}function Ui(t,e){if(e===void 0&&(e=!0),H(t))return!1;if(X(t)){t=xs(t);var n=e?Nc.test((t||"").replace(/[- ]/g,"")):(function(r){var s;for(Oc.lastIndex=0;s=Oc.exec(r);){var o=s[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of Hg){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(Nc.test(d)&&qg(d))return!0}}}return!1})(t);if(n)return!1;var i=e?Wg.test(t):(function(r){var s;for(Bc.lastIndex=0;s=Bc.exec(r);){var o=s[1],a=s[3];if(!(o&&a&&Dc.test(o)&&Dc.test(a)))return!0}return!1})(t);if(i)return!1}return!0}function jc(t){var e=Ji(t);return Ui(e=(e+" "+pf(t)).trim())?e:""}function pf(t){var e="";return t&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;if(n&&((i=n.tagName)==null?void 0:i.toLowerCase())==="span")try{var r=Ji(n);e=(e+" "+r).trim(),n.childNodes&&n.childNodes.length&&(e=(e+" "+pf(n)).trim())}catch(s){A.error("[AutoCapture]",s)}})),e}function Uc(t){return t.replace(/"|\\"/g,'\\"')}function zg(t){var e=t.attr__class;if(e)return U(e)?e:cl(e)}var yr=pe("[Dead Clicks]"),Vg=()=>!0,Gg=t=>{var e,n=!((e=t.instance.persistence)==null||!e.get_property(rl)),i=t.instance.config.capture_dead_clicks;return gt(i)?i:!!he(i)||n};class Hc{get lazyLoadedDeadClicksAutocapture(){return this.si}constructor(e,n,i){this.instance=e,this.isEnabled=n,this.onCapture=i,this.startIfEnabledOrStop()}onRemoteConfig(e){if(e.ok){var n=e.config;"captureDeadClicks"in n&&(this.instance.persistence&&this.instance.persistence.register({[rl]:n.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var n,i;(n=B.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture?e():(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"dead-clicks-autocapture",(r=>{r?yr.error("failed to load script",r):e()}))}oi(){var e;if(F){if(!this.si&&(e=B.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var n=he(this.instance.config.capture_dead_clicks)?k({},this.instance.config.capture_dead_clicks):{};n.__onCapture=this.onCapture,this.onCapture&&(n.capture_dead_swipes=!1),this.si=B.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.si.start(F),yr.info("starting...")}}else yr.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,yr.info("stopping..."))}}var Eo=pe("[SegmentIntegration]"),gf="posthog-js";function mf(t,e){var n=e===void 0?{}:e,i=n.organization,r=n.projectId,s=n.prefix,o=n.severityAllowList,a=o===void 0?["error"]:o,l=n.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,f,h,p,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var v,S=((d=c.exception)==null?void 0:d.values)||[],b=S.map((x=>k({},x,{stacktrace:x.stacktrace?k({},x.stacktrace,{type:"raw",frames:(x.stacktrace.frames||[]).map((I=>k({},I,{platform:"web:javascript"})))}):void 0}))),_={$exception_message:((f=S[0])==null?void 0:f.value)||c.message,$exception_type:(h=S[0])==null?void 0:h.type,$exception_level:c.level,$exception_list:b,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((p=S[0])==null?void 0:p.value)||c.message,$sentry_exception_type:(g=S[0])==null?void 0:g.type,$sentry_tags:c.tags};return i&&r&&(_.$sentry_url=(s||"https://sentry.io/organizations/")+i+"/issues/?project="+r+"&query="+c.event_id),u&&((v=t.exceptions)==null||v.sendExceptionEvent(_)),c}}class Kg{constructor(e,n,i,r,s,o){this.name=gf,this.setupOnce=function(a){a(mf(e,{organization:n,projectId:i,prefix:r,severityAllowList:s,sendExceptionsToPostHog:o==null||o}))}}}class Wc{constructor(e){this.li=(n,i,r)=>{r&&(r.noSessionId||r.activityTimeout||r.sessionPastMaximumLength||r.crossTabAdoption)&&(A.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:n,changeReason:r}),this.ui=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.hi()}hi(){var e;this.di=(e=this._instance.sessionManager)==null?void 0:e.onSessionId(this.li)}destroy(){var e;(e=this.di)==null||e.call(this),this.di=void 0}doPageView(e,n){var i,r=this.vi(e,n);return this.ui={pathname:(i=w?.location.pathname)!==null&&i!==void 0?i:"",pageViewId:n,timestamp:e},this._instance.scrollManager.resetContext(),r}doPageLeave(e){var n;return this.vi(e,(n=this.ui)==null?void 0:n.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.ui)==null?void 0:e.pageViewId}}vi(e,n){var i=this.ui;if(!i)return{$pageview_id:n};var r={$pageview_id:n,$prev_pageview_id:i.pageViewId},s=this._instance.scrollManager.getContext();if(s&&!this._instance.config.disable_scroll_properties){var o=s.maxScrollHeight,a=s.lastScrollY,l=s.maxScrollY,u=s.maxContentHeight,c=s.lastContentY,d=s.maxContentY;if(!(C(o)||C(a)||C(l)||C(u)||C(c)||C(d))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),d=Math.ceil(d);var f=o>1?At(a/o,0,1,A):1,h=o>1?At(l/o,0,1,A):1,p=u>1?At(c/u,0,1,A):1,g=u>1?At(d/u,0,1,A):1;r=fe(r,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:f,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:h,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:p,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return i.pathname&&(r.$prev_pageview_pathname=i.pathname),i.timestamp&&(r.$prev_pageview_duration=(e.getTime()-i.timestamp.getTime())/1e3),r}}var So=["flags","surveys"],Yg={[zd]:{exposure:"hidden"},[Fi]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[Ri]:{exposure:"hidden"},[ea]:{exposure:"event"},[ta]:{exposure:"hidden"},[na]:{exposure:"event"},[ia]:{exposure:"hidden"},[ra]:{exposure:"event"},[sa]:{exposure:"event"},[rl]:{exposure:"event"},[sl]:{exposure:"hidden"},[oa]:{exposure:"event"},[An]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[Kn]:{exposure:"hidden"},[ol]:{exposure:"event"},[Vd]:{exposure:"event",shouldSkipFromEventProperties:t=>Ke(t)},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},$sess_rec_flush_size:{exposure:"hidden"},[Sn]:{exposure:"hidden",storageGroup:"flags"},[Ti]:{exposure:"hidden",storageGroup:"flags"},[Ar]:{exposure:"hidden"},[aa]:{exposure:"hidden",storageGroup:"flags"},[$i]:{exposure:"hidden",storageGroup:"flags"},[Pr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[Zr]:{exposure:"hidden",storageGroup:"flags"},[It]:{exposure:"hidden"},[xn]:{exposure:"hidden"},[jt]:{exposure:"hidden"},[In]:{exposure:"hidden"},[la]:{exposure:"hidden",storageGroup:"surveys"},[Xr]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[ca]:{exposure:"event"},[Fr]:{exposure:"hidden"},[Rr]:{exposure:"hidden"},[Mi]:{exposure:"hidden"},$product_tours_activated:{exposure:"hidden"},$product_tours_activated_session:{exposure:"hidden"},$conversations_widget_session_id:{exposure:"event"},$conversations_ticket_id:{exposure:"event"},$conversations_widget_state:{exposure:"event"},$conversations_user_traits:{exposure:"event"},[Cn]:{exposure:"hidden"},[Li]:{exposure:"hidden"},[Tr]:{exposure:"hidden"},[ji]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[ot]:{exposure:"hidden"},[ua]:{exposure:"hidden"},[da]:{exposure:"hidden"},[fa]:{exposure:"hidden"},[ha]:{exposure:"hidden"},[Qr]:{exposure:"hidden"},[es]:{exposure:"hidden"},[Gd]:{exposure:"event"},[Kd]:{exposure:"event"},[Yd]:{exposure:"event"},[Jd]:{exposure:"event"},[Xd]:{exposure:"event"},[Qd]:{exposure:"event"},[ef]:{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"}},Jg=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],yn=t=>{var e=Yg[t];if(e)return e;for(var n of Jg){var i=n[1];if(t.indexOf(n[0])===0)return i}},Yn=(t,e)=>{try{return JSON.stringify(t,((n,i)=>typeof i=="bigint"?i.toString():i),e)}catch{return fd(t)}},ss=t=>{var e=F?.createElement("a");return C(e)?null:(e.href=t,e)},ii=function(t,e){for(var n,i=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),r=0;i.length>r;r++){var s=i[r].split("=");if(s[0]===e){n=s;break}}if(!U(n)||2>n.length)return"";var o=n[1];try{o=decodeURIComponent(o)}catch{A.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},Zi=function(t,e,n){if(!t||!e||!e.length)return t;for(var i=t.split("#"),r=i[1],s=(i[0]||"").split("?"),o=s[1],a=s[0],l=(o||"").split("&"),u=[],c=0;l.length>c;c++){var d=l[c].split("=");U(d)&&(e.includes(d[0])?u.push(d[0]+"="+n):u.push(l[c]))}var f=a;return o!=null&&(f+="?"+u.join("&")),r!=null&&(f+="#"+r),f},os=function(t,e){var n=t.match(new RegExp(e+"=([^&]*)"));return n?n[1]:null},vf=(t,e)=>t>=e&&cd(),_f=(t,e,n,i)=>{if(t===0){if(cd()){var r=e+1;return r===n&&i(),r}return e}return 0},wr="https?://(.*)",ri=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Zg=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...ri],Xi="",Xg=["li_fat_id"];function yf(t,e,n){if(!F)return{};var i,r=e?[...ri,...n||[]]:[],s=wf(Zi(F.URL,r,Xi),t),o=(i={},ie(Xg,(function(a){var l=tf(a);i[a]=l||null})),i);return fe(o,s)}function wf(t,e){var n=Zg.concat(e||[]),i={};return ie(n,(function(r){var s=ii(t,r);i[r]=s||null})),i}function bf(t){var e=(function(s){return s?s.search(wr+"google.([^/?]*)")===0?"google":s.search(wr+"bing.com")===0?"bing":s.search(wr+"yahoo.com")===0?"yahoo":s.search(wr+"duckduckgo.com")===0?"duckduckgo":null:null})(t),n=e!="yahoo"?"q":"p",i={};if(!Ke(e)){i.$search_engine=e;var r=F?ii(F.referrer,n):"";r.length&&(i.ph_keyword=r)}return i}function qc(){return navigator.language||navigator.userLanguage}var as="$direct";function Ef(){return F?.referrer||as}function Sf(t,e,n){n===void 0&&(n=!1);var i=t?[...ri,...e||[]]:[],r=n?fn(me?.href):me?.href,s=r?.substring(0,1e3);return{r:Ef().substring(0,1e3),u:s?Zi(s,i,Xi):void 0}}function xf(t,e){var n;e===void 0&&(e=!1);var i=t.r,r=t.u,s=e?fn(r):r,o={$referrer:i,$referring_domain:i==null?void 0:i==as?as:(n=ss(i))==null?void 0:n.host};if(s){o.$current_url=s;var a=ss(s);o.$host=a?.host,o.$pathname=a?.pathname;var l=wf(s);fe(o,l)}if(i){var u=bf(i);fe(o,u)}return o}function If(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function Qg(){try{return new Date().getTimezoneOffset()}catch{return}}var em={flags:ji,surveys:Xr},tm=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],Hn="main";class xo{constructor(e,n,i){if(i===void 0&&(i=!0),this.ci={},this.fi=!1,this.pi=!1,this.Ne=e,this.gi=i,this.props={},this.mi=void 0,this.yi=(s=>{var o="";return s.token&&(o=s.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),s.persistence_name?"ph_"+s.persistence_name:"ph_"+o+"_posthog"})(e),this.ii=this.bi(e),this.pi=this.wi(e),this.load(),e.debug&&A.info("Persistence loaded",e.persistence,k({},this.props)),this.update_config(e,e,n),this.save(),w){var r=()=>this.flush();ve(w,"beforeunload",r,{capture:!1}),ve(w,"pagehide",r,{capture:!1})}}ki(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return ke(n)&&n>0?n:0}isDisabled(){return!!this.xi}bi(e){tm.indexOf(e.persistence.toLowerCase())===-1&&(A.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var n,i=(function(o,a){o===void 0&&(o=[]),a===void 0&&(a=!1);var l=[...$g,...o];return k({},le,{H(u){try{var c={};try{c=qt.H(u)||{}}catch{}var d,f=JSON.parse(le.P(u)||"{}");if(a){var h={};for(var p in c){var g=c[p];Ke(g)||g===""||(h[p]=g)}d=fe(f,h)}else d=fe(c,f);return le.F(u,d),d}catch{}return null},F(u,c,d,f,h,p){var g=le.F(u,c,void 0,void 0,p);try{var m={};l.forEach((v=>{c[v]&&(m[v]=c[v])})),Object.keys(m).length&&qt.F(u,m,d,f,h,p)}catch(v){le.j(v)}return g},q(u,c){try{w?.localStorage.removeItem(u),qt.q(u,c)}catch(d){le.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),r=!1,s=e.persistence.toLowerCase();return s==="localstorage"&&le.N()?(n=le,r=!0):s==="localstorage+cookie"&&i.N()?(n=i,r=!0):s==="sessionstorage"&&be.N()?n=be:s==="memory"?n=Mg:s==="cookie"?n=qt:i.N()?(n=i,r=!0):n=qt,this.fi=r,n}Si(e){return this.yi+"__"+e}wi(e){return this.fi&&!!e.split_storage}properties(){var e={};return ie(this.props,((n,i)=>{var r=yn(i);if(!r||r.exposure==="event"){if(r!=null&&r.shouldSkipFromEventProperties!=null&&r.shouldSkipFromEventProperties(n))return;e[i]=n}})),e}load(){if(!this.xi){var e=this.ii.H(this.yi);e&&(this.props=fe({},e)),this.pi&&this.Ci()}}Ci(){for(var e of So){var n=le.H(this.Si(e));if(n&&!Kt(n)){var i=this.Mi(e);i.persisted=!0,this.Ti(e)||(i.fingerprint=this.Ei(n,e)),this.Ii(e,n)||fe(this.props,n)}}}Ti(e){return Object.keys(this.props).some((n=>{var i;return((i=yn(n))==null?void 0:i.storageGroup)===e}))}Ii(e,n){var i=em[e];if(!i)return!1;var r=n[i],s=this.props[i];return ke(r)&&ke(s)&&s>r}refreshKey(e){var n;if(!this.xi){var i=this.pi?(n=yn(e))==null?void 0:n.storageGroup:void 0,r=i?le.H(this.Si(i)):this.ii.H(this.yi);if(r&&e in r)this.Pi(e,r[e]);else{if(i){var s=this.ii.H(this.yi);if(s&&e in s)return void this.Pi(e,s[e])}this.Ri(e)}}}save(){if(!this.xi){var e=this.ki();e>0?C(this.Ai)&&(this.Ai=setTimeout((()=>{this.Ai=void 0,this.Fi()}),e)):this.Fi()}}flush(){C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0,this.Fi())}Fi(){this.xi||(this.pi?this.Li():this.Oi(this.ii,this.yi,this.props,Hn))}Li(){var e=this.Di(),n=e.main,i=e.groups;for(var r of(this.Oi(this.ii,this.yi,n,Hn),So)){var s,o=i[r];(!Kt(o)||(s=this.ci[r])!=null&&s.persisted)&&this.Oi(le,this.Si(r),o,r)}}Di(){var e={},n={flags:{},surveys:{}};return ie(this.props,((i,r)=>{var s,o=(s=yn(r))==null?void 0:s.storageGroup;o?n[o][r]=i:e[r]=i})),{main:e,groups:n}}Ei(e,n){if(n===Hn)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var i={};return ie(e,((r,s)=>{var o;i[s]=(o=yn(s))!=null&&o.volatile?"__volatile__":r})),JSON.stringify(i)}Oi(e,n,i,r){var s=this.Mi(r);if(r===Hn||s.dirty||C(s.fingerprint)){var o;try{if((o=this.Ei(i,r))===s.fingerprint)return void(s.dirty=!1)}catch{o=void 0}e.F(n,i,this.$i,this.Ni,this.qi,this.Ne.debug)?(s.dirty=!1,r!==Hn&&(s.persisted=!0),C(o)||(s.fingerprint=o)):this.Ne.debug&&A.warn('failed to persist storage entry "'+n+'"; will retry on next save')}}remove(e){var n=(e===void 0?{}:e).keepGroupEntries,i=n!==void 0&&n;if(C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0),this.ii.q(this.yi,!1),this.ii.q(this.yi,!0),!i&&this.gi)for(var r of So)le.q(this.Si(r));i?delete this.ci[Hn]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,n,i){if(he(e)){C(n)&&(n="None"),this.$i=C(i)?this.ji:i;var r=!1;if(ie(e,((s,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==n||(this.Pi(o,s),r=!0)})),r)return this.save(),!0}return!1}register(e,n){if(he(e)){this.$i=C(n)?this.ji:n;var i=!1;if(ie(e,((r,s)=>{e.hasOwnProperty(s)&&(this.props[s]!==r||he(r)||U(r))&&(this.Pi(s,r),i=!0)})),i)return this.save(),!0}return!1}unregister(e){var n=typeof e=="string"?[e]:e,i=!1;for(var r of n)r in this.props&&(this.Ri(r),i=!0);i&&this.save()}update_campaign_params(){var e=F?.URL;if(e!==this.mi){var n=yf(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);Kt(ll(n))||this.register(n),this.mi=e}}update_search_keyword(){var e;this.register((e=F?.referrer)?bf(e):{})}update_referrer_info(){var e;this.register_once({$referrer:Ef(),$referring_domain:F!=null&&F.referrer&&((e=ss(F.referrer))==null?void 0:e.host)||as},void 0)}set_initial_person_info(){this.props[fa]||this.props[ha]||this.register_once({[Qr]:Sf(this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties,this.Ne.disable_capture_url_hashes)},void 0)}get_initial_props(){var e={};ie([ha,fa],(r=>{var s=this.props[r];s&&ie(s,(function(o,a){e["$initial_"+Go(a)]=o}))}));var n=this.props[Qr];if(n){var i=(function(r,s){s===void 0&&(s=!1);var o=xf(r,s),a={};return ie(o,(function(l,u){a["$initial_"+Go(u)]=l})),a})(n,this.Ne.disable_capture_url_hashes);fe(e,i)}return e}safe_merge(e){return ie(this.props,(function(n,i){i in e||(e[i]=n)})),e}update_config(e,n,i){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!i),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var r=e.persistence!==n.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((f,h)=>f===d[h]))})(e.cookie_persisted_properties||[],n.cookie_persisted_properties||[]),s=r?this.bi(e):this.ii,o=this.wi(e);if(r||o!==this.pi){var a=this.props;this.clear(),this.ii=s,this.pi=o,this.props=a,this.save()}}set_disabled(e){this.xi=e,this.xi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ni&&(this.Ni=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this.qi&&(this.qi=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,n){var i=this.props[Ri]||{};i[e]=n,this.Pi(Ri,i),this.save()}remove_event_timer(e){var n=this.props[Ri]||{},i=n[e];return C(i)||(delete n[e],this.Pi(Ri,n),this.save()),i}get_property(e){return this.props[e]}set_property(e,n){this.Pi(e,n),this.save()}Pi(e,n){var i;this.props[e]=n,(i=yn(e))!=null&&i.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var n,i=(n=yn(e))==null?void 0:n.storageGroup;i&&(this.Mi(i).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function br(t){var e=!0;return{dispose(){if(e){e=!1;var n=t();n&&De(n.then)&&n.then(void 0,(()=>{}))}}}}var je={GZipJS:"gzip-js",Base64:"base64"},wi={Activation:"events",Cancellation:"cancelEvents"},Io={Popover:"popover",API:"api",Widget:"widget"},zt={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},ko={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},_a={Popover:"popover",Inline:"inline"},nm={SHOWN:"product tour shown"},zc={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},Vc=pe("[RateLimiter]");class im{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=n=>{var i=n.text;if(i&&i.length)try{(JSON.parse(i).quota_limited||[]).forEach((r=>{Vc.info((r||"events")+" is quota limited."),this.serverLimits[r]=new Date().getTime()+6e4}))}catch(r){return void Vc.warn('could not rate limit - continuing. Error: "'+r?.message+'"',{text:i})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var n,i,r;e===void 0&&(e=!1);var s=this.captureEventsBurstLimit,o=this.captureEventsPerSecond,a=new Date().getTime(),l=(n=(i=this.instance.persistence)==null?void 0:i.get_property(da))!==null&&n!==void 0?n:{tokens:s,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>s&&(l.tokens=s);var u=1>l.tokens;if(u||e||(l.tokens=Math.max(0,l.tokens-1)),u&&!e){var c=(ke(l.dropped)?l.dropped:0)+1;l.dropped=c,!this.lastEventRateLimited&&this.Hi(c)&&(l.dropped=0)}return this.lastEventRateLimited=u,(r=this.instance.persistence)==null||r.set_property(da,l),{isRateLimited:u,remainingTokens:l.tokens}}Ui(e){var n=this.instance.config.property_denylist;return!U(n)||!n.includes(e)}zi(){var e;if(this.Ui("$current_url")&&this.Ui("$pathname")&&me!=null&&me.pathname)return""+((e=me.origin)!==null&&e!==void 0?e:"")+me.pathname}Hi(e){var n,i,r=this.captureEventsBurstLimit,s=this.captureEventsPerSecond,o=this.zi(),a=this.Ui("$session_id")?(n=(i=this.instance).get_session_id)==null?void 0:n.call(i):void 0,l=[e+" event(s) dropped since the last warning",o?"triggered on "+o:void 0,a?"session "+a:void 0].filter(Boolean).join(", ");return!!this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited: "+l+". Config is set to "+s+" events per second and "+r+" events burst limit."},{skip_client_rate_limiting:!0})}isServerRateLimited(e){var n=this.serverLimits[e||"events"]||!1;return n!==!1&&new Date().getTime()e(this.remoteConfig))):e()}Vi(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:e})}load(){try{if(this.remoteConfig)return an.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void an.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return an.info("No config found after loading remote JS config. Falling back to JSON."),void this.Vi((n=>{this.Zi(n.json,n),this.Gi()}));this.Zi(e),this.Gi()}))}catch(e){an.error("Error loading remote config",e),this.Zi()}}stop(){this.Ki&&(clearInterval(this.Ki),this.Ki=void 0)}refresh(){!this._instance.Qi()&&F&&F.visibilityState!=="hidden"&&this._instance.reloadFeatureFlags()}Gi(){var e;if(!this.Ki){var n=(e=this._instance.config.remote_config_refresh_interval_ms)!==null&&e!==void 0?e:3e5;n!==0&&(this.Ki=setInterval((()=>{this.refresh()}),n))}}Zi(e,n){!e&&n&&(n.statusCode===0?n.error||an.warn("Failed to fetch remote config from PostHog."):an.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(r){an.error("Error applying remote config",r)}if(e?.hasFeatureFlags!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var i;(i=this._instance.featureFlags)==null||i.ensureFlagsLoaded()}catch(r){an.error("Error loading feature flags",r)}}}var lt=Uint8Array,Ge=Uint16Array,si=Uint32Array,fl=new lt([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]),hl=new lt([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]),Gc=new lt([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Cf=function(t,e){for(var n=new Ge(31),i=0;31>i;++i)n[i]=e+=1<i;++i)for(var s=n[i];n[i+1]>s;++s)r[s]=s-n[i]<<5|i;return[n,r]},Af=Cf(fl,2),ya=Af[1];Af[0][28]=258,ya[258]=28;for(var Kc=Cf(hl,0)[1],Pf=new Ge(32768),_e=0;32768>_e;++_e){var Wn=(43690&_e)>>>1|(21845&_e)<<1;Pf[_e]=((65280&(Wn=(61680&(Wn=(52428&Wn)>>>2|(13107&Wn)<<2))>>>4|(3855&Wn)<<4))>>>8|(255&Wn)<<8)>>>1}var Hi=function(t,e,n){for(var i=t.length,r=0,s=new Ge(e);i>r;++r)++s[t[r]-1];var o,a=new Ge(e);for(r=0;e>r;++r)a[r]=a[r-1]+s[r-1]<<1;for(o=new Ge(i),r=0;i>r;++r)o[r]=Pf[a[t[r]-1]++]>>>15-t[r];return o},$n=new lt(288);for(_e=0;144>_e;++_e)$n[_e]=8;for(_e=144;256>_e;++_e)$n[_e]=9;for(_e=256;280>_e;++_e)$n[_e]=7;for(_e=280;288>_e;++_e)$n[_e]=8;var ls=new lt(32);for(_e=0;32>_e;++_e)ls[_e]=5;var rm=Hi($n,9),sm=Hi(ls,5),Ff=function(t){return(t/8>>0)+(7&t&&1)},Rf=function(t,e,n){(n==null||n>t.length)&&(n=t.length);var i=new(t instanceof Ge?Ge:t instanceof si?si:lt)(n-e);return i.set(t.subarray(e,n)),i},Ot=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8},bi=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8,t[i+2]|=n>>>16},Co=function(t,e){for(var n=[],i=0;t.length>i;++i)t[i]&&n.push({s:i,f:t[i]});var r=n.length,s=n.slice();if(!r)return[new lt(0),0];if(r==1){var o=new lt(n[0].s+1);return o[n[0].s]=1,[o,1]}n.sort((function(x,I){return x.f-I.f})),n.push({s:-1,f:25001});var a=n[0],l=n[1],u=0,c=1,d=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=r-1;)a=n[n[d].f>n[u].f?u++:d++],l=n[u!=c&&n[d].f>n[u].f?u++:d++],n[c++]={s:-1,f:a.f+l.f,l:a,r:l};var f=s[0].s;for(i=1;r>i;++i)s[i].s>f&&(f=s[i].s);var h=new Ge(f+1),p=wa(n[c-1],h,0);if(p>e){i=0;var g=0,m=p-e,v=1<i;++i){var S=s[i].s;if(e>=h[S])break;g+=v-(1<>>=m;g>0;){var b=s[i].s;e>h[b]?g-=1<=0&&g;--i){var _=s[i].s;h[_]==e&&(--h[_],++g)}p=e}return[new lt(h),p]},wa=function(t,e,n){return t.s==-1?Math.max(wa(t.l,e,n+1),wa(t.r,e,n+1)):e[t.s]=n},Yc=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new Ge(++e),i=0,r=t[0],s=1,o=function(l){n[i++]=l},a=1;e>=a;++a)if(t[a]==r&&a!=e)++s;else{if(!r&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(r),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(r);s=1,r=t[a]}return[n.subarray(0,i),e]},Ei=function(t,e){for(var n=0,i=0;e.length>i;++i)n+=t[i]*e[i];return n},ba=function(t,e,n){var i=n.length,r=Ff(e+2);t[r]=255&i,t[r+1]=i>>>8,t[r+2]=255^t[r],t[r+3]=255^t[r+1];for(var s=0;i>s;++s)t[r+s+4]=n[s];return 8*(r+4+i)},Jc=function(t,e,n,i,r,s,o,a,l,u,c){Ot(e,c++,n),++r[256];for(var d=Co(r,15),f=d[0],h=d[1],p=Co(s,15),g=p[0],m=p[1],v=Yc(f),S=v[0],b=v[1],_=Yc(g),x=_[0],I=_[1],T=new Ge(19),E=0;S.length>E;++E)T[31&S[E]]++;for(E=0;x.length>E;++E)T[31&x[E]]++;for(var P=Co(T,7),$=P[0],O=P[1],L=19;L>4&&!$[Gc[L-1]];--L);var N,K,V,M,R=u+5<<3,Z=Ei(r,$n)+Ei(s,ls)+o,Ce=Ei(r,f)+Ei(s,g)+o+14+3*L+Ei(T,$)+(2*T[16]+3*T[17]+7*T[18]);if(Z>=R&&Ce>=R)return ba(e,c,t.subarray(l,l+u));if(Ot(e,c,1+(Z>Ce)),c+=2,Z>Ce){N=Hi(f,h),K=f,V=Hi(g,m),M=g;var oe=Hi($,O);for(Ot(e,c,b-257),Ot(e,c+5,I-1),Ot(e,c+10,L-4),c+=14,E=0;L>E;++E)Ot(e,c+3*E,$[Gc[E]]);c+=3*L;for(var ye=[S,x],$e=0;2>$e;++$e){var ae=ye[$e];for(E=0;ae.length>E;++E)Ot(e,c,oe[Ie=31&ae[E]]),c+=$[Ie],Ie>15&&(Ot(e,c,ae[E]>>>5&127),c+=ae[E]>>>12)}}else N=rm,K=$n,V=sm,M=ls;for(E=0;a>E;++E)if(i[E]>255){var Ie;bi(e,c,N[257+(Ie=i[E]>>>18&31)]),c+=K[Ie+257],Ie>7&&(Ot(e,c,i[E]>>>23&31),c+=fl[Ie]);var Se=31&i[E];bi(e,c,V[Se]),c+=M[Se],Se>3&&(bi(e,c,i[E]>>>5&8191),c+=hl[Se])}else bi(e,c,N[i[E]]),c+=K[i[E]];return bi(e,c,N[256]),c+K[256]},om=new si([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),am=(function(){for(var t=new si(256),e=0;256>e;++e){for(var n=e,i=9;--i;)n=(1&n&&3988292384)^n>>>1;t[e]=n}return t})(),Ao=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8};function lm(t,e){e===void 0&&(e={});var n=(function(){var d=4294967295;return{p(f){for(var h=d,p=0;f.length>p;++p)h=am[255&h^f[p]]^h>>>8;d=h},d(){return 4294967295^d}}})(),i=t.length;n.p(t);var r,s,o,a,l,u=(a=10+((r=e).filename&&r.filename.length+1||0),l=8,(function(d,f,h,p,g,m){var v=d.length,S=new lt(p+v+5*(1+Math.floor(v/7e3))+g),b=S.subarray(p,S.length-g),_=0;if(!f||8>v)for(var x=0;v>=x;x+=65535){var I=x+65535;v>I?_=ba(b,_,d.subarray(x,I)):(b[x]=!0,_=ba(b,_,d.subarray(x,v)))}else{for(var T=om[f-1],E=T>>>13,P=8191&T,$=(1<x;++x){var Ie=V(x),Se=32767&x,Be=L[Ie];if(O[Se]=Be,L[Ie]=Se,x>=$e){var wt=v-x;if((Ce>7e3||ye>24576)&&wt>423){_=Jc(d,b,0,M,R,Z,oe,ye,ae,x-ae,_),ye=Ce=oe=0,ae=x;for(var ge=0;286>ge;++ge)R[ge]=0;for(ge=0;30>ge;++ge)Z[ge]=0}var Ye=2,bt=0,mn=P,Re=Se-Be&32767;if(wt>2&&Ie==V(x-Re))for(var Pe=Math.min(E,wt)-1,$t=Math.min(32767,x),Bn=Math.min(258,wt);$t>=Re&&--mn&&Se!=Be;){if(d[x+Ye]==d[x+Ye-Re]){for(var qe=0;Bn>qe&&d[x+qe]==d[x+qe-Re];++qe);if(qe>Ye){if(Ye=qe,bt=Re,qe>Pe)break;var Dn=Math.min(Re,qe-2),Mt=0;for(ge=0;Dn>ge;++ge){var Lt=x-Re+ge+32768&32767,ct=Lt-O[Lt]+32768&32767;ct>Mt&&(Mt=ct,Be=Lt)}}}Re+=(Se=Be)-(Be=O[Se])+32768&32767}if(bt){M[ye++]=268435456|ya[Ye]<<18|Kc[bt];var sn=31&ya[Ye],gi=31&Kc[bt];oe+=fl[sn]+hl[gi],++R[257+sn],++Z[gi],$e=x+Ye,++Ce}else M[ye++]=d[x],++R[d[x]]}}_=Jc(d,b,!0,M,R,Z,oe,ye,ae,x-ae,_)}return Rf(S,0,p+Ff(_)+g)})(s=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):12+o.mem,a,l)),c=u.length;return(function(d,f){var h=f.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>f.level?4:f.level==9?2:0,d[9]=3,f.mtime!=0&&Ao(d,4,Math.floor(new Date(f.mtime||Date.now())/1e3)),h){d[3]=8;for(var p=0;h.length>=p;++p)d[p+10]=h.charCodeAt(p)}})(u,e),Ao(u,c-8,n.d()),Ao(u,c-4,i),u}var cm=!!qo||!!Za,Tf="text/plain",Mr=!1,$f=(t,e)=>{var n=t.split("#"),i=n[1],r=n[0].split("?"),s=r[0],o=r[1];if(!o)return t;var a=o.split("&").filter((l=>l.split("=")[0]!==e)).join("&");return s+(a?"?"+a:"")+(i?"#"+i:"")},ks=function(t,e,n){var i;n===void 0&&(n=!0);var r=t.split("?"),s=r[0],o=r[1],a=k({},e),l=(i=o?.split("&").map((c=>{var d,f=c.split("="),h=f[0],p=n&&(d=a[h])!==null&&d!==void 0?d:f[1];return delete a[h],h+"="+p})))!==null&&i!==void 0?i:[],u=(function(c,d){var f,h;d===void 0&&(d="&");var p=[];return ie(c,(function(g,m){C(g)||C(m)||m==="undefined"||(f=encodeURIComponent((v=>v instanceof File)(g)?g.name:g.toString()),h=encodeURIComponent(m),p[p.length]=h+"="+f)})),p.join(d)})(a);return u&&l.push(u),l.length>0?s+"?"+l.join("&"):s},Po=t=>{if(t.Ji)return t.Ji;var e=t.data,n=t.compression;if(e){if(n===je.GZipJS){var i=lm((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new lt(a.length+(a.length>>>1)),d=0,f=function(m){c[d++]=m},h=0;u>h;++h){if(d+5>c.length){var p=new lt(d+8+(u-h<<1));p.set(c),c=p}var g=a.charCodeAt(h);128>g?f(g):2048>g?(f(192|g>>>6),f(128|63&g)):g>55295&&57344>g?(f(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++h))>>>18),f(128|g>>>12&63),f(128|g>>>6&63),f(128|63&g)):(f(224|g>>>12),f(128|g>>>6&63),f(128|63&g))}return Rf(c,0,d)})(Yn(e)),{mtime:0});return{contentType:Tf,body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),estimatedSize:i.byteLength}}if(n===je.Base64){var r=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(Yn(e)),s=(a=>"data="+encodeURIComponent(typeof a=="string"?a:Yn(a)))(r);return{contentType:"application/x-www-form-urlencoded",body:s,estimatedSize:new Blob([s]).size}}var o=Yn(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},Mf=t=>{var e,n,i=()=>t.transport==="sendBeacon"?{url:ks(t.url,{compression:je.Base64}),encodedBody:Po(k({},t,{compression:je.Base64,Ji:void 0}))}:{url:$f(t.url,"compression"),encodedBody:Po(k({},t,{compression:void 0,Ji:void 0}))};try{e=Po(t)}catch(r){if(mc(t.compression,ii(t.url,"compression")))return A.error("Failed to gzip request body, sending uncompressed payload",r),i();throw r}return e&&mc(t.compression,ii(t.url,"compression"))&&!((n=e.body)instanceof ArrayBuffer?zo(new Uint8Array(n)):ArrayBuffer.isView(n)&&zo(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)))?(Mr=!0,i()):{url:t.url,encodedBody:e}},Lf=t=>{try{return Mf(t)}catch(e){return A.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},um=(function(){var t=se((function*(e){var n=Yn(e.data),i=yield(function(s,o,a){return Vo.apply(this,arguments)})(n,ne.DEBUG,{rethrow:!0});if(!i)return e;var r=yield i.arrayBuffer();return k({},e,{Ji:{contentType:Tf,body:r,estimatedSize:r.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),dm=/Failed to fetch|NetworkError|Load failed/i,Nf=t=>t?.name==="TypeError"&&dm.test(t?.message||""),Of=t=>{var e=Lf(t);if(e){var n=e.url,i=e.encodedBody,r=i??{},s=r.contentType,o=r.body,a=r.estimatedSize,l=new Headers;ie(t.headers,(function(p,g){l.append(g,p)})),s&&l.append("Content-Type",s);var u=null,c=!1;if(uc){var d=new uc;u={signal:d.signal,timeout:setTimeout((()=>{var p,g;c=!0,d.abort((p=t.timeout,(g=new Error("PostHog request timed out"+(p?" after "+p+"ms":""))).name="AbortError",g))}),t.timeout)}}var f=p=>{c&&p?.name==="AbortError"||Nf(p)?A.warn(p):A.error(p),t.callback==null||t.callback({statusCode:0,error:p})};try{var h;Za(n,k({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(h=u)==null?void 0:h.signal},t.fetchOptions)).then((p=>p.text().then((g=>{var m={statusCode:p.status,text:g};if(p.status===200)try{m.json=JSON.parse(g)}catch(v){A.error(v)}t.callback==null||t.callback(m)})))).catch(f).finally((()=>u?clearTimeout(u.timeout):null))}catch(p){u&&clearTimeout(u.timeout),f(p)}}},Ea=t=>{try{var e,n=Mf(t),i=n.url,r=n.encodedBody,s=r??{},o=s.body,a=s.estimatedSize;if(!o)return;var l=o instanceof Blob?o:new Blob([o],{type:s.contentType});if(Ue.sendBeacon(i,l))return;var u=U(t.data)?t.data:(e=t.data)==null?void 0:e.batch;if(U(u)&&u.length>1&&(a??0)>16384){var c=Math.ceil(u.length/2),d=f=>U(t.data)?f:k({},t.data,{batch:f});return Ea(k({},t,{data:d(u.slice(0,c))})),void Ea(k({},t,{data:d(u.slice(c))}))}A.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),Of(k({},t,{Yi:!0}))}catch(f){A.warn("Beacon send failed",f)}},Zc=(t,e,n,i)=>{var r=i==="query"?e==="POST"?"sent_at":"_":void 0;return ks(n===je.GZipJS?$f(t,"compression"):t,k({},r?{[r]:Date.now().toString()}:{},n===je.GZipJS?{}:{compression:n}))},Lr=[];Za&&Lr.push({transport:"fetch",method:Of}),qo&&Lr.push({transport:"XHR",method(t){var e=Lf(t);if(e){var n=new qo,i=e.encodedBody;n.open(t.method||"GET",e.url,!0);var r=i??{},s=r.contentType,o=r.body;ie(t.headers,(function(a,l){n.setRequestHeader(l,a)})),s&&n.setRequestHeader("Content-Type",s),t.timeout&&(n.timeout=t.timeout),n.onreadystatechange=()=>{if(n.readyState===4){var a={statusCode:n.status,text:n.responseText};if(n.status===200)try{a.json=JSON.parse(n.responseText)}catch{}t.callback==null||t.callback(a)}},n.send(o)}}}),Ue!=null&&Ue.sendBeacon&&Lr.push({transport:"sendBeacon",method:Ea});var Sa=3e3;class fm{constructor(e,n){this.Xi=!0,this.tr=[],this.er=At(n?.flush_interval_ms||Sa,250,5e3,A.createLogger("flush interval"),Sa),this.ir=e}enqueue(e){this.tr.push(e),this.rr||this.nr()}unload(){this.sr();var e=this.tr.length>0?this.ar():{},n=Object.values(e);[...n.filter((i=>i.url.indexOf("/e")===0)),...n.filter((i=>i.url.indexOf("/e")!==0))].map((i=>{this.lr(k({},i,{transport:"sendBeacon"}))}))}enable(){this.Xi=!1,this.nr()}nr(){var e=this;this.Xi||(this.rr=setTimeout((()=>{if(this.sr(),this.tr.length>0){var n=this.ar(),i=function(){var s=n[r],o=new Date().getTime();s.data&&U(s.data)&&ie(s.data,(a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp})),e.lr(s)};for(var r in n)i()}}),this.er))}lr(e){try{this.ir(e)}catch(n){A.error(n)}}sr(){clearTimeout(this.rr),this.rr=void 0}ar(){var e={};return ie(this.tr,(n=>{var i,r=n,s=(r?r.batchKey:null)||r.url;C(e[s])&&(e[s]=k({},r,{data:[]})),(i=e[s].data)==null||i.push(r.data)})),this.tr=[],e}}var hm=["retriesPerformedSoFar"];class pm{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!C(w)&&"onLine"in w.navigator&&(this.dr=w.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},ve(w,"online",this.vr),ve(w,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var n=e.retriesPerformedSoFar,i=ud(e,hm);Dt(n)&&(i.url=ks(i.url,{retry_count:n})),this._instance._send_request(k({},i,{callback:r=>{if(r.statusCode!==200&&(400>r.statusCode||r.statusCode>=500)){if((r.statusCode===0?3:10)>(n??0))return void this.At(k({retriesPerformedSoFar:n},i));r.statusCode===0&&A.warn("Request failed before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped retrying after "+(n??0)+" retries.")}i.callback==null||i.callback(r)}}))}At(e){var n=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=n+1;var i=(function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),c=Math.random()-.5;return Math.ceil(u+c*(u-l))})(n),r=Date.now()+i;this.tr.push({retryAt:r,requestOptions:e});var s="Enqueued failed request for retry in "+i;navigator.onLine||(s+=" (Browser is offline)"),A.warn(s),this.ur||(this.ur=!0,this.gr())}gr(){if(this.mr&&clearTimeout(this.mr),this.tr.length===0)return this.ur=!1,void(this.mr=void 0);this.mr=setTimeout((()=>{this.dr&&this.tr.length>0&&this.cr(),this.gr()}),this.hr)}cr(){var e=Date.now(),n=[],i=this.tr.filter((s=>e>s.retryAt||(n.push(s),!1)));if(this.tr=n,i.length>0)for(var r of i)this.retriableRequest(r.requestOptions)}unload(){for(var e of(this.mr&&(clearTimeout(this.mr),this.mr=void 0),this.ur=!1,C(w)||(this.vr&&(w.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(w.removeEventListener("offline",this.pr),this.pr=void 0)),this.tr)){var n=e.requestOptions;try{this._instance._send_request(k({},n,{transport:"sendBeacon"}))}catch(i){A.error(i)}}this.tr=[]}}class gm{constructor(e){this.yr=()=>{var n,i,r,s;this.br||(this.br={});var o=this.scrollElement(),a=this.scrollY(),l=o?Math.max(0,o.scrollHeight-o.clientHeight):0,u=a+(o?.clientHeight||0),c=o?.scrollHeight||0;this.br.lastScrollY=Math.ceil(a),this.br.maxScrollY=Math.max(a,(n=this.br.maxScrollY)!==null&&n!==void 0?n:0),this.br.maxScrollHeight=Math.max(l,(i=this.br.maxScrollHeight)!==null&&i!==void 0?i:0),this.br.lastContentY=u,this.br.maxContentY=Math.max(u,(r=this.br.maxContentY)!==null&&r!==void 0?r:0),this.br.maxContentHeight=Math.max(c,(s=this.br.maxContentHeight)!==null&&s!==void 0?s:0)},this._instance=e}get _r(){return this._instance.config.scroll_root_selector}getContext(){return this.br}resetContext(){var e=this.br;return setTimeout(this.yr,0),e}startMeasuringScrollPosition(){ve(w,"scroll",this.yr,{capture:!0}),ve(w,"scrollend",this.yr,{capture:!0}),ve(w,"resize",this.yr)}scrollElement(){if(!this._r)return w?.document.documentElement;var e=U(this._r)?this._r:[this._r];for(var n of e){var i=w?.document.querySelector(n);if(i)return i}}wr(e){var n=e==="y"?"scrollTop":"scrollLeft";if(this._r){var i=this.scrollElement();return i&&i[n]||0}return w?e==="y"?w.scrollY||w.pageYOffset||w.document.documentElement.scrollTop||0:w.scrollX||w.pageXOffset||w.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var mm=t=>Sf(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class Xc{constructor(e,n,i,r){this.kr=s=>{var o=this.Sr();if(!o||o.sessionId!==s){var a={sessionId:s,props:this.Cr(this._instance)};this.Mr.register({[ua]:a})}},this._instance=e,this.Tr=n,this.Mr=i,this.Cr=r||mm,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[ua]}getSetOnceProps(){var e,n=(e=this.Sr())==null?void 0:e.props;return n?"r"in n?xf(n,this._instance.config.disable_capture_url_hashes):{$referring_domain:n.referringDomain,$pathname:n.initialPathName,utm_source:n.utm_source,utm_campaign:n.utm_campaign,utm_medium:n.utm_medium,utm_content:n.utm_content,utm_term:n.utm_term}:{}}getSessionProps(){var e={};return ie(ll(this.getSetOnceProps()),((n,i)=>{i==="$current_url"&&(i="url"),e["$session_entry_"+Go(i)]=n})),e}}class pl{on(e,n){return this.Er[e]||(this.Er[e]=[]),this.Er[e].push(n),()=>{this.Er[e]=this.Er[e].filter((i=>i!==n))}}emit(e,n){for(var i of this.Er[e]||[])i(n);for(var r of this.Er["*"]||[])r(e,n)}constructor(){this.Er={}}}var Si=pe("[SessionId]");class Qc{on(e,n){return this.Ir.on(e,n)}constructor(e,n,i){var r;if(this.Pr=null,this.Rr=[],this.Ar=void 0,this.Fr=!1,this.Ir=new pl,this.Lr=(u,c)=>!(!Dt(u)||!Dt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===Wt)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Ne=e.config,this.Mr=e.persistence,this.Or=void 0,this.Dr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.$r=n||Ht,this.Nr=i||Ht;var s=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*At(this.Ne.session_idle_timeout_seconds||1800,60,36e3,Si.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.qr(),this.jr="ph_"+s+"_window_id",this.Br="ph_"+s+"_primary_window_exists",this.Hr()){var o=be.H(this.jr),a=be.H(this.Br);o&&!a?this.Or=o:be.q(this.jr),be.F(this.Br,!0)}if((r=this.Ne.bootstrap)!=null&&r.sessionID)try{var l=(u=>{var c=this.Ne.bootstrap.sessionID.replace(/-/g,"");if(c.length!==32)throw new Error("Not a valid UUID");if(c[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(c.substring(0,12),16)})();this.Ur(this.Ne.bootstrap.sessionID,new Date().getTime(),l)}catch(u){Si.error("Invalid sessionID in bootstrap",u)}this.zr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return C(this.Rr)&&(this.Rr=[]),this.Rr.push(e),this.Dr&&e(this.Dr,this.Or),()=>{this.Rr=this.Rr.filter((n=>n!==e))}}Hr(){return this.Ne.persistence!=="memory"&&!this.Mr.xi&&be.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&be.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?be.H(this.jr):null}Zr(e){var n=this.Pr;return!Ke(n)&&!Ke(e)&&5e3>Math.abs(e-n)}Ur(e,n,i){var r=n!==this._sessionActivityTimestamp,s=!(e!==this.Dr||i!==this._sessionStartTimestamp);this._sessionStartTimestamp=i,this._sessionActivityTimestamp=n,this.Dr=e,s&&!r||s&&this.Zr(n)||(this.Pr=n,this.Mr.register({[Kn]:[n,e,i]}))}Gr(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return Dt(n)&&n>0}Qr(){this.Gr()?this.Mr.refreshKey(Kn):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!Ke(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this.Pr){this.Qr();var n=this.Jr();n[1]===this.Dr&&n[2]===this._sessionStartTimestamp&&(this.Pr=this._sessionActivityTimestamp,this.Mr.register({[Kn]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],n=Dt(e)?e:0,i=Dt(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(n,i)}Xr(e){return this.Qr(),this.Lr(e,this.Yr())}Jr(){var e=this.Mr.props[Kn];return U(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Pr=null,clearTimeout(this.tn),this.tn=void 0,this.Ur(null,null,null)}destroy(){this.Fr=!0,this.Kr(),clearTimeout(this.tn),this.tn=void 0,this.Ar&&w&&(w.removeEventListener(ns,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&be.q(this.Br)},ve(w,ns,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=null),this.Ne.cookieless_mode===Wt)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var i=n||new Date().getTime(),r=this.Jr(),s=r[1],o=r[2],a=this.Yr(),l=this.Vr(),u=Dt(o)&&Math.abs(i-o)>864e5,c=!1,d=!1,f=!s,h=s,p=!f&&!e&&this.Lr(i,a);if(p){(p=this.Xr(i))||Si.info("cross-tab refresh kept the session alive",{sessionId:s});var g=this.Jr();s=g[1],o=g[2]}f||p||u?(s=this.$r(),l=this.Nr(),Si.info("new session ID generated",{sessionId:s,windowId:l,changeReason:{noSessionId:f,activityTimeout:p,sessionPastMaximumLength:u}}),o=i,c=!0):(l||(l=this.Nr(),c=!0),(d=s!==h)&&(Si.info("adopted cross-tab session id",{sessionId:s,windowId:l}),c=!0));var m=Dt(a)&&e&&!u?a:i,v=Dt(o)?o:new Date().getTime();this.Wr(l),this.Ur(s,m,v),e||this.qr();var S={noSessionId:f,activityTimeout:p,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((b=>b(s,l,S))),{sessionId:s,windowId:l,sessionStartTimestamp:v,changeReason:c?S: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 Bf=function(t,e){if(!t)return!1;var n=t.userAgent;if(n&&_c(n,e))return!0;try{var i=t?.userAgentData;if(i!=null&&i.brands&&i.brands.some((r=>_c(r?.brand,e))))return!0}catch{}return!!t.webdriver};function Df(){return(Df=se((function*(){var t=Ue?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),n=e?.model;return X(n)&&n.length>0?n:void 0}catch(i){return void A.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",i)}}))).apply(this,arguments)}var cs=function(t,e){if(!(function(n){try{new RegExp(n)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function Fo(t,e,n){return Yn({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}var jf={exact:(t,e)=>e.some((n=>t.some((i=>n===i)))),is_not:(t,e)=>e.every((n=>t.every((i=>n!==i)))),regex:(t,e)=>e.some((n=>t.some((i=>cs(n,i))))),not_regex:(t,e)=>e.every((n=>t.every((i=>!cs(n,i))))),icontains:(t,e)=>e.map(Er).some((n=>t.map(Er).some((i=>n.includes(i))))),not_icontains:(t,e)=>e.map(Er).every((n=>t.map(Er).every((i=>!n.includes(i))))),gt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>i>parseFloat(r)))})),lt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>it.toLowerCase();function Uf(t,e){return!t||Object.entries(t).every((n=>{var i=n[1],r=e?.[n[0]];if(C(r)||Ke(r))return!1;var s=[String(r)],o=jf[i.operator];return!!o&&o(i.values,s)}))}var xa="custom",eu="i.posthog.com",vm=/^\/static\//;class _m{constructor(e){this.en={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,n=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return n||(n=this.apiHost.replace("."+eu,".posthog.com")),n==="https://app.posthog.com"?"https://us.posthog.com":n}get region(){return this.en[this.apiHost]||(this.en[this.apiHost]=/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"us":/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"eu":xa),this.en[this.apiHost]}rn(e){if(vm.test(e)){var n=this.instance.config.asset_host;if(typeof n=="string")return n.trim().replace(/\/$/,"")||void 0}}endpointFor(e,n){if(n===void 0&&(n=""),n&&(n=n[0]==="/"?n:"/"+n),e==="ui")return this.uiHost+n;if(e==="flags")return this.flagsApiHost+n;if(e==="assets"){var i=this.rn(n);if(i)return""+i+n}if(this.region===xa)return this.apiHost+n;var r=eu+n;switch(e){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}}function Hf(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var Q=pe("[Surveys]"),Wf="seenSurvey_",qf=t=>{try{var e=(n=>((i,r)=>""+Wf+(function(s){return s.current_iteration&&s.current_iteration>0?s.id+"_"+s.current_iteration:s.id})(r))(0,n))(t);if(localStorage.getItem(e))return;localStorage.setItem(e,"true")}catch(n){Q.error("Failed to persist survey seen state",n)}},ym=[Io.Popover,Io.Widget,Io.API],wm={ignoreConditions:!1,ignoreDelay:!1,displayType:_a.Popover},bm=pe("[PostHog ExternalIntegrations]"),Em={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class Sm{constructor(e){this._instance=e}ai(e,n){var i;(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,e,(r=>{if(r)return bm.error("failed to load script",r);n()}))}startIfEnabledOrStop(){var e=this,n=function(){var s,o,a,l=i[0],u=i[1];!u||(s=B.__PosthogExtensions__)!=null&&(s=s.integrations)!=null&&s[l]||e.ai(Em[l],(()=>{var c;(c=B.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=B.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=B.__PosthogExtensions__)==null||(a=a.integrations)==null||(a=a[l])==null||a.stop())};for(var i of Object.entries((r=this._instance.config.integrations)!==null&&r!==void 0?r:{})){var r;n()}}}class xm{constructor(e,n){this.rt=e,this.nn=n,this.sn=new Map,this.an=!1}add(e){var n=this;return se((function*(){if(n.an)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(n.sn.has(e.name))throw new Error('Browser extension "'+e.name+'" is already registered');n.sn.set(e.name,e);try{var i=e.setup(n.nn);i&&(yield i)}catch(s){var r=n.sn.get(e.name)===e;r&&n.sn.delete(e.name),n.rt.error('Failed to set up browser extension "'+e.name+'"',s),r&&n.ln(e)}}))()}dispose(){if(!this.an){this.an=!0;var e=Array.from(this.sn.values()).reverse();for(var n of(this.sn.clear(),e))this.ln(n)}}ln(e){try{var n=e.dispose==null?void 0:e.dispose();n&&De(n.then)&&n.then(void 0,(i=>{this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}))}catch(i){this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}}}class Im{constructor(e){this._instance=e}initialize(){}get(e){var n=this._instance.persistence;if(typeof e=="string")return n?.get_property(e);var i={};for(var r of e){var s=n?.get_property(r);C(s)||(i[r]=s)}return i}set(e,n){var i;(i=this._instance.persistence)==null||i.register(typeof e=="string"?{[e]:n}:e)}remove(e){var n;(n=this._instance.persistence)==null||n.unregister(e)}}var tu="extensionsRemoteConfig";class km{constructor(e){this.an=!1,this.instance=e,this.rt=A,this.un=e.hn,this.kv=new Im(e),this.onEvent=n=>br(this.instance.on("eventCaptured",(i=>{try{n({event:i.event,properties:i.properties})}catch(r){this.rt.error("Browser extension event listener failed",r)}}))),this.onRemoteConfig=n=>{if(this.an)return br((()=>{}));var i=s=>{try{n(s)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},r=this.instance.dn.on(tu,i);return this.un&&i(this.un),br(r)},this.vn=new xm(A.createLogger("[BrowserExtensions]"),this)}get logger(){return this.rt}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return(e=this.instance.get_property(Yi))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(Yi);return typeof e=="string"?e:void 0}get library(){return{name:ne.LIB_NAME,version:ne.LIB_VERSION}}get initialPersonProperties(){var e,n;return(e=(n=this.instance.persistence)==null?void 0:n.get_initial_props())!==null&&e!==void 0?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,n,i,r,s=(e=this.instance.sessionManager)==null?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:(n=s?.sessionId)!==null&&n!==void 0?n:"",windowId:(i=s?.windowId)!==null&&i!==void 0?i:"",sessionStartTimestamp:(r=s?.sessionStartTimestamp)!==null&&r!==void 0?r:0}}catch{return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get projectToken(){return this.instance.config.token}add(e){return this.vn.add(e)}capture(e,n,i){var r=this;return se((function*(){i?r.instance.capture(e,n,{timestamp:i.timestamp,uuid:i.uuid,$set:i.set,$set_once:i.setOnce}):r.instance.capture(e,n)}))()}registerDynamicEventProperties(e){return br(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(tu,e))}sendRequest(e,n){var i=this;return se((function*(){var r;n===void 0&&(n={});var s=i.instance.requestRouter.endpointFor((r=n.target)!==null&&r!==void 0?r:"api",e),o={method:n.method,url:n.query?ks(s,n.query):s,data:n.body,headers:n.headers,timeout:n.timeoutMs,fireCallbackOnDrop:!0,transport:n.transport,compression:n.compression,timestampMode:n.sentAt};return n.transport==="sendBeacon"?(i.instance._send_request(o),{statusCode:202}):new Promise((a=>{o.callback=a,i.instance._send_request(o)}))}))()}dispose(){this.an||(this.an=!0,this.vn.dispose())}}var Wi={},Ro=0,us=()=>{},nu='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',xi="Surveys module not available",iu="sanitize_properties is deprecated. Use before_send instead",zf="Invalid value for property_denylist config: ",Cm=["token","distinct_id",Zd],Gn="posthog",Vf=!cm&&Ve?.indexOf("MSIE")===-1&&Ve?.indexOf("Mozilla")===-1,To=t=>{var e;return k({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:Ag(F?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:us,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:t??"unset",__preview_deferred_init_extensions:!1,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:me&&X(me?.search)&&me.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disableDeviceModel:!1,disable_external_dependency_loading:!1,strict_script_versioning:!1,enable_recording_console_log:void 0,secure_cookie:(w==null||(e=w.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(n){A.error("Bad HTTP status: "+n.statusCode+" "+n.text)},get_device_id:n=>n,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:pa,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:Sa},error_tracking:{},_onCapture:us},(n=>({rageclick:n&&n>="2026-05-30"?{content_ignorelist:jg,ignore_text_selection:!0}:!n||"2025-11-30">n||{content_ignorelist:!0},capture_pageview:!n||"2025-05-24">n||"history_change",session_recording:n&&n>="2026-06-25"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6},streamNetworkBody:!0}:n&&n>="2026-05-30"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6}}:n&&n>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:n&&n>="2026-01-30"?"head":"body",internal_or_test_user_hostname:n&&n>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:n&&n>="2026-05-30"?250:0,split_storage:!(!n||"2026-05-30">n),detect_google_search_app:!(!n||"2026-05-30">n),disable_capture_url_hashes:!(!n||"2026-06-25">n)}))(t))},Am=[["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"]],ru=t=>{var e={};for(var n of Am){var i=n[0],r=n[1];C(t[i])||(e[r]=t[i])}var s=fe({},e,t),o=t.__preview_external_dependency_versioned_paths;return C(o)||(C(t.strict_script_versioning)&&(s.strict_script_versioning=!!o),X(o)&&C(t.asset_host)&&(s.asset_host=o)),U(t.property_blacklist)&&(C(t.property_denylist)?s.property_denylist=t.property_blacklist:U(t.property_denylist)?s.property_denylist=[...t.property_blacklist,...t.property_denylist]:A.error(zf+t.property_denylist)),s};class Pm{constructor(){this.__forceAllowLocalhost=!1}get fn(){return this.__forceAllowLocalhost}set fn(e){A.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class Je{pn(e,n){if(e){var i=this.sn.indexOf(e);i!==-1&&this.sn.splice(i,1)}return this.sn.push(n),n.initialize==null||n.initialize(),n}gn(){return this.config.cookieless_mode===Wt||this.config.cookieless_mode===kn&&this.consent.isRejected()}get decideEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){var e;this.webPerformance=new Pm,this.mn=!1,this.version=ne.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new pl,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=To(),this.SentryIntegration=Kg,this.sentryIntegration=i=>(function(r,s){var o=mf(r,s);return{name:gf,processEvent:a=>o(a)}})(this,i),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.wn=!1,this.kn=null,this.xn=null,this.Sn=null,this.scrollManager=new gm(this),this.pageViewManager=new Wc(this),this.rateLimiter=new im(this),this.requestRouter=new _m(this),this.consent=new Lg(this),this.externalIntegrations=new Sm(this);var n=(e=Je.__defaultExtensionClasses)!==null&&e!==void 0?e:{};this.featureFlags=n.featureFlags&&new n.featureFlags(this),this.toolbar=n.toolbar&&new n.toolbar(this),this.surveys=n.surveys&&new n.surveys(this),this.conversations=n.conversations&&new n.conversations(this),this.logs=n.logs&&new n.logs(this),this.metrics=n.metrics&&new n.metrics(this),this.experiments=n.experiments&&new n.experiments(this),this.exceptions=n.exceptions&&new n.exceptions(this),this.people={set:(i,r,s)=>{var o=X(i)?{[i]:r}:i;this.setPersonProperties(o),s?.({})},set_once:(i,r,s)=>{var o=X(i)?{[i]:r}:i;this.setPersonProperties(void 0,o),s?.({})}},this.on("eventCaptured",(i=>A.info('send "'+i?.event+'"',i)))}init(e,n,i){if(i&&i!==Gn){var r,s=(r=Wi[i])!==null&&r!==void 0?r:new Je;return s._init(e,n,i),Wi[i]=s,Wi[Gn][i]=s,s}return this._init(e,n,i)}_init(e,n,i){var r,s;n===void 0&&(n={});var o,a=X(e)?e.trim():"";if(!a)return A.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return a!==((o=this.config)==null?void 0:o.token)?console.warn("[PostHog.js]","You have already initialized PostHog with a different project token! Re-initializing is a no-op, so events will keep going to the project this instance was initialized with. To capture into a second project, load PostHog once, then initialize a named instance after the SDK has loaded, e.g. posthog.init('"+a+"', { ... }, 'project2')"):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=To(n.defaults),n.debug=this.Cn(n.debug),this.Mn=n,this.Tn=[],n.person_profiles?this.xn=n.person_profiles:n.process_person&&(this.xn=n.process_person);var l=To(n.defaults),u=ru(n),c=fe({},l,u,{name:i,token:a});he(l.rageclick)&&he(u.rageclick)&&(c.rageclick=fe({},l.rageclick,u.rageclick)),he(l.session_recording)&&he(u.session_recording)&&(c.session_recording=fe({},l.session_recording,u.session_recording)),this.set_config(c),this.config.on_xhr_error&&A.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=n.disable_compression?void 0:je.GZipJS;var d=this.En();if(this.persistence=new xo(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new xo(k({},this.config,{persistence:"sessionStorage"}),d,!1),this.bn="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&be.N()){var f=be.H(this.bn);U(f)&&f.forEach((I=>{X(I)&&this.yn.add(I)}))}else be.q(this.bn);var h=k({},this.persistence.props),p=k({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new fm((I=>this.Pn(I)),this.config.request_queue_config),this.Rn=new pm(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new Qc(this),this.sessionPropsManager=new Xc(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((I,T,E)=>{(E!=null&&E.activityTimeout||E!=null&&E.sessionPastMaximumLength||E!=null&&E.crossTabAdoption)&&this.An()}))),this.Fn(),this.config.__preview_deferred_init_extensions?(A.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Ln(g)}),0)):(A.info("Initializing extensions synchronously"),this.Ln(g)),ne.DEBUG=ne.DEBUG||this.config.debug,ne.DEBUG&&A.info("Starting in debug mode",{this:this,config:n,thisC:k({},this.config),p:h,s:p}),!this.config.identity_distinct_id||(r=n.bootstrap)!=null&&r.distinctID||(n.bootstrap=k({},n.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((s=n.bootstrap)==null?void 0:s.distinctID)!==void 0){var m=n.bootstrap.distinctID,v=this.get_distinct_id(),S=this.persistence.get_property(ot);if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&S===Un)this.identify(m);else if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&S===vn)A.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{var b=this.config.get_device_id(Ht()),_=n.bootstrap.isIdentifiedID?b:m;this.persistence.set_property(ot,n.bootstrap.isIdentifiedID?vn:Un),this.register({distinct_id:m,$device_id:_})}}if(g)this.register_once({distinct_id:mr,$device_id:null},"");else if(!this.get_distinct_id()){var x=this.config.get_device_id(Ht());this.register_once({distinct_id:x,$device_id:x},""),this.persistence.set_property(ot,Un)}return ve(w,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),n.segment?(function(I,T){var E=I.config.segment;if(!E)return T();(function(P,$){var O=P.config.segment;if(!O)return $();var L=K=>{var V=()=>K.anonymousId()||Ht();P.config.get_device_id=V,K.id()&&(P.register({distinct_id:K.id(),$device_id:V()}),P.persistence.set_property(ot,vn)),$()},N=O.user();"then"in N&&De(N.then)?N.then(L):L(N)})(I,(()=>{E.register((P=>{typeof Promise<"u"&&Promise.resolve||Eo.warn("This browser does not have Promise support, and can not use the segment integration");var $=(O,L)=>{if(!L)return O;O.event.userId||O.event.anonymousId===P.get_distinct_id()||(Eo.info("No userId set, resetting PostHog"),P.reset()),O.event.userId&&O.event.userId!==P.get_distinct_id()&&(Eo.info("UserId set, identifying with PostHog"),P.identify(O.event.userId));var N=P.calculateEventProperties(L,O.event.properties);return O.event.properties=Object.assign({},N,O.event.properties),O};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:O=>$(O,O.event.event),page:O=>$(O,Vn),identify:O=>$(O,yo),screen:O=>$(O,"$screen")}})(I)).then((()=>{T()}))}))})(this,(()=>this.On())):this.On(),De(this.config._onCapture)&&this.config._onCapture!==us&&(A.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(I=>this.config._onCapture(I.event,I)))),this.config.ip&&A.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this.config.disableDeviceModel||(function(){return Df.apply(this,arguments)})().then((I=>{I&&this.register({[vo]:I})})).catch(us),this}Fn(){var e,n,i,r,s,o,a=(e=(n=this.config.__extensionClasses)==null?void 0:n.featureFlags)!==null&&e!==void 0?e:(i=Je.__defaultExtensionClasses)==null?void 0:i.featureFlags;a&&(this.featureFlags&&this.featureFlags instanceof a||((r=this.Dn)==null||r.call(this),this.Dn=void 0,this.featureFlags=new a(this)),De(this.featureFlags.onReloading)&&De(this.featureFlags.setup)?this.Dn||(this.Dn=this.featureFlags.onReloading((()=>{this.dn.emit("featureFlagsReloading",!0)})),this.$n().add(this.featureFlags)):(s=(o=this.featureFlags).initialize)==null||s.call(o))}Ln(e){var n,i,r,s,o,a,l,u=performance.now(),c=k({},Je.__defaultExtensionClasses,this.config.__extensionClasses),d=[];c.exceptions&&this.sn.push(this.exceptions=(n=this.exceptions)!==null&&n!==void 0?n:new c.exceptions(this)),c.historyAutocapture&&this.sn.push(this.historyAutocapture=new c.historyAutocapture(this)),c.tracingHeaders&&this.sn.push(this.tracingHeaders=new c.tracingHeaders(this)),c.siteApps&&this.sn.push(this.siteApps=new c.siteApps(this)),c.sessionRecording&&!e&&this.sn.push(this.sessionRecording=new c.sessionRecording(this)),this.config.disable_scroll_properties||d.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),c.autocapture&&this.sn.push(this.autocapture=new c.autocapture(this)),c.surveys&&this.sn.push(this.surveys=(i=this.surveys)!==null&&i!==void 0?i:new c.surveys(this)),c.logs&&this.sn.push(this.logs=(r=this.logs)!==null&&r!==void 0?r:new c.logs(this)),c.metrics&&this.sn.push(this.metrics=(s=this.metrics)!==null&&s!==void 0?s:new c.metrics(this)),c.conversations&&this.sn.push(this.conversations=(o=this.conversations)!==null&&o!==void 0?o:new c.conversations(this)),c.productTours&&this.sn.push(this.productTours=new c.productTours(this)),c.heatmaps&&this.sn.push(this.heatmaps=new c.heatmaps(this)),c.webVitalsAutocapture&&this.sn.push(this.webVitalsAutocapture=new c.webVitalsAutocapture(this)),c.exceptionObserver&&this.sn.push(this.exceptionObserver=new c.exceptionObserver(this)),c.deadClicksAutocapture&&this.sn.push(this.deadClicksAutocapture=new c.deadClicksAutocapture(this,Gg)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((f=>{f.initialize&&d.push((()=>{f.initialize==null||f.initialize()}))})),d.push((()=>{if(this.Nn){var f=this.Nn;this.Nn=void 0,this.sn.forEach((h=>h.onRemoteConfig==null?void 0:h.onRemoteConfig(f)))}})),this.qn(d,u)}qn(e,n){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,n)}),0);var i=e.shift();if(i)try{i()}catch(s){A.error("Error initializing extension:",s)}}var r=Math.round(performance.now()-n);this.register_for_session({[Xd]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[Qd]:r}),this.config.__preview_deferred_init_extensions&&A.info("PostHog extensions initialized ("+r+"ms)")}Zi(e){var n;if(!F||!F.body)return A.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.Zi(e)}),500);if(this.config.__preview_deferred_init_extensions&&(this.Nn=e),this.hn=e,this.compression=void 0,e.ok){var i,r=e.config;r.supportedCompression&&!this.config.disable_compression&&(this.compression=j(r.supportedCompression,je.GZipJS)?je.GZipJS:j(r.supportedCompression,je.Base64)?je.Base64:void 0),(i=r.analytics)!=null&&i.endpoint&&(this.analyticsDefaultEndpoint=r.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:pa}),(n=this.jn)==null||n.handleRemoteConfig(e),this.sn.forEach((s=>s.onRemoteConfig==null?void 0:s.onRemoteConfig(e)))}On(){try{this.config.loaded(this)}catch(i){A.critical("`loaded` function failed",i)}if(this.Bn(),this.config.internal_or_test_user_hostname&&me!=null&&me.hostname){var e=me.hostname,n=this.config.internal_or_test_user_hostname;(typeof n=="string"?e===n:n.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.gn())&&this.Hn()}),1),this.Un=new kf(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()&&vr(this.__request_queue,(e=>this.Pn(e))),this.__request_queue=[],this.Bn()}_handle_unload(){var e,n,i,r,s;(e=this.surveys)==null||e.handlePageUnload==null||e.handlePageUnload(),(n=this.metrics)==null||n.flush("sendBeacon"),this.config.request_batching?(this.zn()&&this.capture(_o),(i=this.logs)==null||i.flushLogs("sendBeacon"),(r=this.In)==null||r.unload(),(s=this.Rn)==null||s.unload()):this.zn()&&this.capture(_o,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?Vf?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)?e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:429})):(e.transport=e.transport||this.config.api_transport,e.headers=k({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,(C(this.config.disable_beacon)?this.config.__preview_disable_beacon:this.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(n=>{var i,r,s,o=k({},n);o.timeout=o.timeout||6e4;var a,l,u,c,d,f=(i=o.transport)!==null&&i!==void 0?i:"fetch";f==="sendBeacon"&&C(o.compression)&&o.data&&(o.compression=je.Base64),o.method==="POST"&&o.data&&(o.timestampMode==="capture-body"?o.data={api_key:(l=(d=(c=U(a=o.data)?a:[a])[0])==null||(u=d.properties)==null?void 0:u.token)!==null&&l!==void 0?l:d?.token,batch:c,sent_at:new Date().toISOString()}:o.timestampMode==="body"&&(o.data=(function(m,v){return v===void 0&&(v=new Date().toISOString()),U(m)?m.map((S=>k({},S,{sent_at:v}))):k({},m,{sent_at:v})})(o.data))),o.url=Zc(o.url,o.method,o.compression,o.timestampMode);var h=Lr.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),p=(r=(s=(function(m,v){for(var S=0;m.length>S;S++)if(m[S].transport===f)return m[S]})(h))==null?void 0:s.method)!==null&&r!==void 0?r:h[0].method;if(!p)throw new Error("No available transport method");var g=m=>{try{p(m)}catch(v){Nf(v)?A.warn(v):A.error(v),o.callback==null||o.callback({statusCode:0,error:v})}};f!=="sendBeacon"&&o.data&&o.compression===je.GZipJS&&Fp&&typeof Promise<"u"&&!Mr?um(o).then((m=>{g(m)})).catch((m=>{if(vc(m))return Mr=!0,void g(k({},o,{compression:void 0,url:Zc(n.url,n.method,void 0,n.timestampMode)}));(v=>{if(!v||typeof v!="object")return!1;var S="name"in v?String(v.name):"";return vc(v)||S===dd})(m)&&(Mr=!0),g(o)})):p(o)})(k({},e,{callback:n=>{var i,r;this.rateLimiter.checkForLimiting(n),400>n.statusCode||(i=(r=this.config).on_request_error)==null||i.call(r,n),e.callback==null||e.callback(n)}}))):e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:0}))}Pn(e){this.Rn?this.Rn.retriableRequest(e):this._send_request(e)}_execute_array(e){Ro++;try{var n,i=[],r=[],s=[];vr(e,(a=>{if(a)if(U(n=a[0]))s.push(a);else if(De(a))try{a.call(this)}catch(l){A.error("Error executing queued PostHog call",a,l)}else U(a)&&n==="alias"?i.push(a):U(a)&&n.indexOf("capture")!==-1&&De(this[n])?s.push(a):r.push(a)}));var o=function(a,l){vr(a,(function(u){try{if(U(u[0])){var c=l;ie(u,(function(d){c=c[d[0]].apply(c,d.slice(1))}))}else l[u[0]].apply(l,u.slice(1))}catch(d){A.error("Error executing queued PostHog call",u,d)}}))};o(i,this),o(r,this),o(s,this)}finally{Ro--}}push(e){if(Ro>0&&U(e)&&X(e[0])){var n=Je.prototype[e[0]];De(n)&&n.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,n,i){var r,s,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.In){if(this.is_capturing())if(!C(e)&&X(e)){var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var c=i!=null&&i.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(c==null||!c.isRateLimited){n!=null&&n.$current_url&&!X(n?.$current_url)&&(A.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),n==null||delete n.$current_url),e!=="$exception"||i!=null&&i.Wn||A.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,f=i?.timestamp||d,h=Ec(i?.uuid,Ht),p={uuid:h,event:e,properties:this.calculateEventProperties(e,n||{},f,h)};e===Vn&&this.config.__preview_capture_bot_pageviews&&u&&(p.event="$bot_pageview",p.properties.$browser_type="bot"),c&&(p.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&p.properties.$feature_flag_has_experiment===!1&&this.get_property(Zr)===!0;i?.$set&&!g&&(p.$set=i?.$set);var m=i?.$unset;m&&(p.$unset=m);var v,S,b,_=g?void 0:this.Vn(i?.$set_once,e!==Ac,e===yo);if(_&&(p.$set_once=_),i!=null&&i._noTruncate||(s=this.config.properties_string_max_length,o=p,a=L=>X(L)?L.slice(0,s):L,l=new Set,p=(function L(N,K){if(N!==Object(N))return a?a(N):N;if(!l.has(N)){var V;if(l.add(N),U(N))V=[],vr(N,(R=>{V.push(L(R))}));else{var M={};ie(N,((R,Z)=>{l.has(R)||(M[Z]=L(R))})),V=M}return V}})(o)),p.timestamp=f,C(i?.timestamp)||(p.properties.$event_time_override_provided=!0,p.properties.$event_time_override_system_time=d),g&&(p.properties=(function(L,N){N===void 0&&(N=[]);var K={},V=M=>{L[M]!==void 0&&(K[M]=L[M])};return Rp.forEach(V),N.forEach(V),K})(p.properties,Cm)),e===zt.DISMISSED||e===zt.SENT){var x=n?.[ko.SURVEY_ID],I=n?.[ko.SURVEY_ITERATION];qf({id:x,current_iteration:I}),p.$set=k({},p.$set,{[(v={id:x,current_iteration:I},S=e===zt.SENT?"responded":"dismissed",b="$survey_"+S+"/"+v.id,v.current_iteration&&v.current_iteration>0&&(b="$survey_"+S+"/"+v.id+"/"+v.current_iteration),b)]:!0})}else e===zt.SHOWN&&(p.$set=k({},p.$set,{[ko.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===nm.SHOWN){var T=n?.[zc.TOUR_TYPE];T&&(p.$set=k({},p.$set,{[zc.TOUR_LAST_SEEN_DATE+"/"+T]:new Date().toISOString()}))}var E=k({},p.properties.$set,p.$set);if(Kt(E)||this.setPersonPropertiesForFlags(E),!H(this.config.before_send)){var P=this.Pt(p);if(!P)return;(p=P).uuid=Ec(p.uuid,Ht)}this.dn.emit("eventCaptured",p);var $=(r=i?._url)!==null&&r!==void 0?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),O={method:"POST",url:$,data:p,compression:"best-available",timestampMode:i?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test($)?"body":"capture-body",batchKey:i?._batchKey,transport:i?.transport};return!this.config.request_batching||i&&(i==null||!i._batchKey)||i!=null&&i.send_instantly?this.Pn(O):this.In.enqueue(O),p}A.critical("This capture call is ignored due to client rate limiting.")}}else A.error("No event name provided to posthog.capture")}else A.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(n=>e(n.event,n)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new km(this)}cn(e){this._n.push(e);var n=!0;return()=>{if(n){n=!1;var i=this._n.indexOf(e);i!==-1&&this._n.splice(i,1)}}}calculateEventProperties(e,n,i,r,s){if(i=i||new Date,!this.persistence||!this.sessionPersistence)return n;var o=s?void 0:this.persistence.remove_event_timer(e),a=k({},n);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.gn()&&(a[Zd]=!0),e==="$snapshot"){var l=k({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!X(a.distinct_id)&&!ke(a.distinct_id)||Ko(a.distinct_id))&&A.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=(function(x,I,T,E){var P,$,O,L;if(E===void 0&&(E=!1),!Ve)return{};var N,K=x?[...ri,...I||[]]:[],V=(function(Bn){for(var qe=0;wc.length>qe;qe++){var Dn=wc[qe],Mt=Dn[1],Lt=Dn[0].exec(Bn),ct=Lt&&(De(Mt)?Mt(Lt,Bn):Mt);if(ct)return ct}return["",""]})(Ve),M=V[0],R=V[1],Z=(N=typeof navigator<"u"?navigator:void 0)!=null&&N.brave?{brave:!0}:{},Ce={};C(T)||(Ce.detectGoogleSearchApp=T);var oe={},ye=(P=navigator)==null||(P=P.userAgentData)==null?void 0:P.platform,$e=($=navigator)==null?void 0:$.maxTouchPoints,ae=w==null||(O=w.screen)==null?void 0:O.width,Ie=w==null||(L=w.screen)==null?void 0:L.height,Se=w?.devicePixelRatio;C(ye)||(oe.userAgentDataPlatform=ye),C($e)||(oe.maxTouchPoints=$e),C(ae)||(oe.screenWidth=ae),C(Ie)||(oe.screenHeight=Ie),C(Se)||(oe.devicePixelRatio=Se);var Be,wt,ge,Ye,bt,mn,Re,Pe,$t=fe(ll({$os:M,$os_version:R,$browser:Nd(Ve,navigator.vendor,Z,Ce),$device:bc(Ve),$device_type:(wt=Ve,ge=oe,Pe=bc(wt),Pe===_d||Pe===vd||Pe==="Kobo"||Pe==="Kindle Fire"||Pe===Rd?ei:Pe===Gi||Pe===Xn||Pe===Ki||Pe===Jo?"Console":Pe===wd?"Wearable":Pe?it:ge?.userAgentDataPlatform==="Android"&&((Ye=ge?.maxTouchPoints)!==null&&Ye!==void 0?Ye:0)>0?600>Math.min((bt=ge?.screenWidth)!==null&&bt!==void 0?bt:0,(mn=ge?.screenHeight)!==null&&mn!==void 0?mn:0)/((Re=ge?.devicePixelRatio)!==null&&Re!==void 0?Re:1)?it:ei:"Desktop"),$timezone:If(),$timezone_offset:Qg()}),{$current_url:Zi(E?fn(me?.href):me?.href,K,Xi),$host:me?.host,$pathname:me?.pathname,$raw_user_agent:Ve.length>1e3?Ve.substring(0,997)+"...":Ve,$browser_version:Jp(Ve,navigator.vendor,Z,Ce),$browser_language:qc(),$browser_language_prefix:(Be=qc(),typeof Be=="string"?Be.split("-")[0]:void 0),$screen_height:w?.screen.height,$screen_width:w?.screen.width,$viewport_height:w?.innerHeight,$viewport_width:w?.innerWidth,$lib:ne.LIB_NAME,$lib_version:ne.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return ne.SDK_DIST_CHANNEL&&($t.$sdk_dist_channel=ne.SDK_DIST_CHANNEL),$t})(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties,this.config.detect_google_search_app,this.config.disable_capture_url_hashes);if(this.sessionManager){var d=this.sessionManager.checkAndGetSessionAndWindowId(s,i.getTime()),f=d.windowId;a.$session_id=d.sessionId,a.$window_id=f}this.sessionPropsManager&&fe(a,this.sessionPropsManager.getSessionProps());try{var h;this.sessionRecording&&fe(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(h=this.Rn)==null?void 0:h.length}catch(x){a.$sdk_debug_error_capturing_properties=String(x)}if(this.requestRouter.region===xa&&(a.$lib_custom_api_host=this.config.api_host),u=e!==Vn||s?e!==_o||s?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(i):this.pageViewManager.doPageView(i,r),a=fe(a,u),e===Vn&&F&&(a.title=F.title),!C(o)){var p=i.getTime()-o;a.$duration=parseFloat((p/1e3).toFixed(3))}Ve&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();ie(["$referrer","$referring_domain"],(x=>{x in g&&delete m[x]}));var v={};if(this._n.length>0)for(var S of this._n.slice())try{fe(v,S())}catch(x){A.error("Failed to produce browser extension event properties",x)}(a=fe({},c,g,m,k({},v,a))).$is_identified=this._isIdentified(),U(this.config.property_denylist)?ie(this.config.property_denylist,(function(x){delete a[x]})):A.error(zf+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var b=this.config.sanitize_properties;b&&(A.error(iu),a=b(a,e));var _=this.Zn();return a.$process_person_profile=_,_&&!s&&this.Gn("_calculate_event_properties"),a}Vn(e,n,i){var r;if(n===void 0&&(n=!0),i===void 0&&(i=!1),!this.persistence||!this.Zn()||this.mn&&!i)return e;var s=this.persistence.get_initial_props(),o=(r=this.sessionPropsManager)==null?void 0:r.getSetOnceProps(),a=fe({},s,o||{},e||{}),l=this.config.sanitize_properties;return l&&(A.error(iu),a=l(a,"$set_once")),n&&(this.mn=!0),Kt(a)?void 0:a}register(e,n){var i;(i=this.persistence)==null||i.register(e,n)}register_once(e,n,i){var r;(r=this.persistence)==null||r.register_once(e,n,i)}register_for_session(e){var n;(n=this.sessionPersistence)==null||n.register(e),Object.keys(e).forEach((i=>this.yn.add(i))),this.Qn()}unregister(e){var n;(n=this.persistence)==null||n.unregister(e)}unregister_for_session(e){var n;(n=this.sessionPersistence)==null||n.unregister(e),this.yn.delete(e),this.Qn()}Kn(e,n){this.register({[e]:n})}An(){this.yn.forEach((e=>{var n;(n=this.sessionPersistence)==null||n.unregister(e)})),this.yn.clear(),this.Qn()}Qn(){var e;if(this.bn)if(this.config.persistence==="memory"||(e=this.sessionPersistence)!=null&&e.xi||!be.N())be.q(this.bn);else{var n=[];this.yn.forEach((i=>n.push(i))),n.length>0?be.F(this.bn,n):be.q(this.bn)}}getFeatureFlag(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlag(e,n)}getFeatureFlagPayload(e){var n;return(n=this.featureFlags)==null?void 0:n.getFeatureFlagPayload(e)}getFeatureFlagResult(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlagResult(e,n)}getAllFeatureFlags(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.getAllFeatureFlags())!==null&&e!==void 0?e:[]}isFeatureEnabled(e,n){var i,r;return(i=(r=this.featureFlags)==null?void 0:r.isFeatureEnabled(e,n))!==null&&i!==void 0?i:n?.defaultValue}reloadFeatureFlags(){var e;(e=this.featureFlags)==null||e.reloadFeatureFlags()}updateFlags(e,n,i){var r;(r=this.featureFlags)==null||r.updateFlags(e,n,i)}updateEarlyAccessFeatureEnrollment(e,n,i){var r;(r=this.featureFlags)==null||r.updateEarlyAccessFeatureEnrollment(e,n,i)}getEarlyAccessFeatures(e,n,i){var r;return n===void 0&&(n=!1),(r=this.featureFlags)==null?void 0:r.getEarlyAccessFeatures(e,n,i)}on(e,n){return this.dn.on(e,n)}onFeatureFlags(e){return this.featureFlags?this.featureFlags.onFeatureFlags(e):(e([],{},{errorsLoading:!0}),()=>{})}onSurveysLoaded(e){return this.surveys?this.surveys.onSurveysLoaded(e):(e([],{isLoaded:!1,error:xi}),()=>{})}onSessionId(e){var n,i;return(n=(i=this.sessionManager)==null?void 0:i.onSessionId(e))!==null&&n!==void 0?n:()=>{}}getSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getSurveys(e,n):e([],{isLoaded:!1,error:xi})}getActiveMatchingSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,n):e([],{isLoaded:!1,error:xi})}renderSurvey(e,n){var i;(i=this.surveys)==null||i.renderSurvey(e,n)}displaySurvey(e,n){var i;n===void 0&&(n=wm),(i=this.surveys)==null||i.displaySurvey(e,n)}cancelPendingSurvey(e){var n;(n=this.surveys)==null||n.cancelPendingSurvey(e)}canRenderSurvey(e){var n,i;return(n=(i=this.surveys)==null?void 0:i.canRenderSurvey(e))!==null&&n!==void 0?n:{visible:!1,disabledReason:xi}}canRenderSurveyAsync(e,n){var i,r;return n===void 0&&(n=!1),(i=(r=this.surveys)==null?void 0:r.canRenderSurveyAsync(e,n))!==null&&i!==void 0?i:Promise.resolve({visible:!1,disabledReason:xi})}Jn(e){return!e||Ko(e)?(A.critical("Unique user id has not been set in posthog.identify"),!1):e===mr?(A.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.'),!1):!["distinct_id","distinctid"].includes(e.toLowerCase())&&!["undefined","null"].includes(e.toLowerCase())||(A.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.'),!1)}identify(e,n,i){if(!this.__loaded||!this.persistence)return A.uninitializedWarning("posthog.identify");if(ke(e)&&(e=e.toString(),A.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.Jn(e)&&this.Gn("posthog.identify")){var r=this.get_distinct_id();this.register({$user_id:e}),this.get_property(Yi)||this.register_once({$had_persisted_distinct_id:!0,$device_id:r},""),e!==r&&e!==this.get_property(Fi)&&(this.unregister(Fi),this.register({distinct_id:e}));var s,o=(this.persistence.get_property(ot)||Un)===Un,a=e!==r,l=!a&&o;if(a&&o)this.persistence.set_property(ot,vn),this.setPersonPropertiesForFlags({$set:n||{},$set_once:i||{}},!1),this.capture(yo,{distinct_id:e,$anon_distinct_id:r},{$set:n||{},$set_once:i||{}}),this.Sn=Fo(e,n,i),(s=this.featureFlags)==null||s.setAnonymousDistinctId(r);else if(l){this.persistence.set_property(ot,vn);var u=n||{},c=i||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=Fo(e,n,i)}else(n||i)&&this.setPersonProperties(n,i);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Cn)):l&&(n||i)&&this.reloadFeatureFlags()}}setPersonProperties(e,n){if((e||n)&&this.Gn("posthog.setPersonProperties")){var i=Fo(this.get_distinct_id(),e,n);this.Sn!==i?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:n||{}},!0),this.capture("$set",{$set:e||{},$set_once:n||{}}),this.Sn=i):A.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}unsetPersonProperties(e){var n,i=(U(e)?e:[e]).filter((r=>X(r)&&r.length>0));i.length!==0&&this.Gn("posthog.unsetPersonProperties")&&((n=this.featureFlags)==null||n.unsetPersonPropertiesForFlags(i,!0),this.capture("$set",{$unset:i}),this.Sn=null)}group(e,n,i){if(e&&n){var r=this.getGroups(),s=r[e]!==n;if(s&&this.resetGroupPropertiesForFlags(e),this.register({$groups:k({},r,{[e]:n})}),s||i){var o={$group_type:e,$group_key:n};i&&(o.$group_set=i),this.capture(Ac,o)}i&&this.setGroupPropertiesForFlags({[e]:i}),s&&!i&&this.reloadFeatureFlags()}else A.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),(i=this.featureFlags)==null||i.setPersonPropertiesForFlags(e,n)}resetPersonPropertiesForFlags(e){var n;e===void 0&&(e=!0),(n=this.featureFlags)==null||n.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((i=this.featureFlags)==null||i.setGroupPropertiesForFlags(e,n))}resetGroupPropertiesForFlags(e){var n;(n=this.featureFlags)==null||n.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,n){var i,r,s,o,a,l,u,c,d,f;if(n===void 0&&(n=!1),A.info("reset"),!this.__loaded)return A.uninitializedWarning("posthog.reset");var h,p=this.get_property(Yi),g=this.get_property(vo),m=this.get_property(An),v=this.is_capturing();if(this.consent.reset(),n||!v||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after."),(i=this.persistence)==null||i.clear(),(r=this.sessionPersistence)==null||r.clear(),this.yn.clear(),this.Qn(),C(m)||(h=this.persistence)==null||h.register({[An]:m}),(s=this.surveys)==null||s.reset(),(o=this.Un)==null||o.stop(),(a=this.featureFlags)==null||a.reset(),(l=this.conversations)==null||l.reset(),(u=this.logs)==null||u.reset(),(c=this.metrics)==null||c.reset(),(d=this.persistence)==null||d.set_property(ot,Un),(f=this.sessionManager)==null||f.resetSessionId(),this.Sn=null,this.config.cookieless_mode===Wt)this.register_once({distinct_id:mr,$device_id:null},"");else{var S=this.config.get_device_id(Ht());this.register_once({distinct_id:S,$device_id:e?S:p},""),e||C(g)||this.register({[vo]:g})}this.register({$last_posthog_reset:new Date().toISOString()},1),delete this.config.identity_distinct_id,delete this.config.identity_hash,this.reloadFeatureFlags()}shutdown(e){var n=this;return se((function*(){var i,r,s,o,a,l,u;if(n.__loaded){(i=n.Un)==null||i.stop(),(r=n.jn)==null||r.dispose(),(s=n.sessionRecording)==null||s.dispose(),(o=n.logs)==null||o.flushLogs("sendBeacon"),(a=n.metrics)==null||a.flush("sendBeacon"),(l=n.In)==null||l.unload(),(u=n.Rn)==null||u.unload();try{var c;(c=n.featureFlags)==null||c.destroy()}catch(d){A.error("Error while destroying feature flags",d)}}else A.uninitializedWarning("posthog.shutdown")}))()}setIdentity(e,n){var i;this.config.identity_distinct_id=e,this.config.identity_hash=n,this.alias(e),(i=this.conversations)==null||i.Xn()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,(e=this.conversations)==null||e.ts()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,n;return(e=(n=this.sessionManager)==null?void 0:n.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var n=this.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.sessionStartTimestamp,r=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+n.sessionId);if(e!=null&&e.withTimestamp&&i){var s,o=(s=e.timestampLookBack)!==null&&s!==void 0?s:10;if(!i)return r;r+="?t="+Math.max(Math.floor((new Date().getTime()-i)/1e3)-o,0)}return r}alias(e,n){return e===this.get_property(zd)?(A.critical("Attempting to create alias for existing People user - aborting."),-2):this.Gn("posthog.alias")?(C(n)&&(n=this.get_distinct_id()),e!==n?(this.Kn(Fi,e),this.capture("$create_alias",{alias:e,distinct_id:n})):(A.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var n=k({},this.config);if(he(e)){var i,r,s,o,a,l,u,c,d,f,h,p;fe(this.config,ru(e));var g=this.En();(i=this.persistence)==null||i.update_config(this.config,n,g),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new xo(k({},this.config,{persistence:"sessionStorage"}),g,!1);var m=this.Cn(this.config.debug);gt(m)&&(this.config.debug=m),gt(this.config.debug)&&(this.config.debug?(ne.DEBUG=!0,le.N()&&le.F("ph_debug",!0),A.info("set_config",{config:e,oldConfig:n,newConfig:k({},this.config)})):(ne.DEBUG=!1,le.N()&&le.q("ph_debug"))),(r=this.featureFlags)==null||r.updateConfig==null||r.updateConfig(this.config,this.Qi()),(s=this.exceptionObserver)==null||s.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(f=this.deadClicksAutocapture)==null||f.startIfEnabledOrStop(),(h=this.surveys)==null||h.loadIfEnabled(),this.es(),(p=this.externalIntegrations)==null||p.startIfEnabledOrStop()}}_overrideSDKInfo(e,n){ne.LIB_NAME=e,ne.LIB_VERSION=n}startSessionRecording(e){var n,i,r,s,o,a=e===!0,l={sampling:a||!(e==null||!e.sampling),linked_flag:a||!(e==null||!e.linked_flag),url_trigger:a||!(e==null||!e.url_trigger),event_trigger:a||!(e==null||!e.event_trigger)};Object.values(l).some(Boolean)&&((n=this.sessionManager)==null||n.checkAndGetSessionAndWindowId(),l.sampling&&((i=this.sessionRecording)==null||i.overrideSampling()),l.linked_flag&&((r=this.sessionRecording)==null||r.overrideLinkedFlag()),l.url_trigger&&((s=this.sessionRecording)==null||s.overrideTrigger("url")),l.event_trigger&&((o=this.sessionRecording)==null||o.overrideTrigger("event"))),this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,n){if(this.exceptions){var i=new Error("PostHog syntheticException"),r=this.exceptions.buildProperties(e,{handled:!0,syntheticException:i});return this.exceptions.sendExceptionEvent(k({},r,n))}}addExceptionStep(e,n){var i;(i=this.exceptions)==null||i.addExceptionStep(e,n)}captureLog(e){var n;(n=this.logs)==null||n.captureLog(e)}get logger(){var e,n;return(e=(n=this.logs)==null?void 0:n.logger)!==null&&e!==void 0?e:Je.rs}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var n,i;return(n=(i=this.toolbar)==null?void 0:i.loadToolbar(e))!==null&&n!==void 0&&n}get_property(e){var n;return(n=this.persistence)==null?void 0:n.props[e]}getSessionProperty(e){var n;return(n=this.sessionPersistence)==null?void 0:n.props[e]}toString(){var e,n=(e=this.config.name)!==null&&e!==void 0?e:Gn;return n!==Gn&&(n=Gn+"."+n),n}_isIdentified(){var e,n;return((e=this.persistence)==null?void 0:e.get_property(ot))===vn||((n=this.sessionPersistence)==null?void 0:n.get_property(ot))===vn}Zn(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles===pa&&!this._isIdentified()&&Kt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[Fi])&&((n=this.persistence)==null||(n=n.props)==null||!n[es]))}zn(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Zn()||this.Gn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.Gn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}Gn(e){return this.config.person_profiles==="never"?(A.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Kn(es,!0),!0)}En(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut();return this.config.disable_persistence||e&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!==kn)}es(){var e,n,i,r,s=this.En();return((e=this.persistence)==null?void 0:e.xi)!==s&&((i=this.persistence)==null||i.set_disabled(s)),((n=this.sessionPersistence)==null?void 0:n.xi)!==s&&((r=this.sessionPersistence)==null||r.set_disabled(s)),s&&(this.yn.clear(),this.Qn()),s}opt_in_capturing(e){var n;if(this.config.cookieless_mode!==Wt){if(this.gn()){var i,r,s,o,a;this.Yn(!0,!0),(i=this.sessionManager)==null||i.destroy(),(r=this.pageViewManager)==null||r.destroy(),this.sessionManager=new Qc(this),this.pageViewManager=new Wc(this),this.persistence&&(this.sessionPropsManager=new Xc(this,this.sessionManager,this.persistence));var l,u=(s=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&s!==void 0?s:(a=Je.__defaultExtensionClasses)==null?void 0:a.sessionRecording;u&&(this.sessionRecording=this.pn(this.sessionRecording,new u(this)),this.hn&&((l=this.sessionRecording)==null||l.onRemoteConfig==null||l.onRemoteConfig(this.hn)))}var c,d;this.consent.optInOut(!0),this.es(),this.Bn(),(n=this.sessionRecording)==null||n.startIfEnabledOrStop(),this.config.cookieless_mode==kn&&((c=this.surveys)==null||c.loadIfEnabled()),(C(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((d=e?.captureEventName)!==null&&d!==void 0?d:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hn()}else A.warn(nu)}opt_out_capturing(){var e,n,i;this.config.cookieless_mode!==Wt?(this.config.cookieless_mode===kn&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===kn&&(this.register({distinct_id:mr,$device_id:null}),(e=this.sessionRecording)==null||e.stopRecording(),this.sessionRecording=void 0,(n=this.sessionManager)==null||n.destroy(),(i=this.pageViewManager)==null||i.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.Hn(),this.Bn())):A.warn(nu)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===Wt||(this.config.cookieless_mode===kn?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return Ue?Bf(Ue,this.config.custom_blocked_useragents):void 0}Hn(){F&&(F.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(Vn,{title:F.title},{send_instantly:!0}),this.kn&&(F.removeEventListener(ts,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),ve(F,ts,this.kn)))}debug(e){e===!1?(w?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(w?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}Qi(){var e=this.Mn||{};return"advanced_disable_flags"in e?!!e.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(A.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(function(n,i,r,s,o){var a=i in n&&!H(n[i]),l=r in n&&!H(n[r]);return a?n[i]:!!l&&(o&&o.warn("Config field '"+r+"' is deprecated. Please use '"+i+"' instead. The old field will be removed in a future major version."),n[r])})(e,"advanced_disable_flags","advanced_disable_decide",0,A)}Pt(e){var n;if(H(this.config.before_send))return e;var i=Object.keys((n=e.properties)!==null&&n!==void 0?n:{}).filter(Bp),r=U(this.config.before_send)?this.config.before_send:[this.config.before_send],s=e;for(var o of r){if(s=o(s),H(s)){var a="Event '"+e.event+"' was rejected in beforeSend function";return Op(e.event)?A.warn(a+". This can cause unexpected behavior."):A.info(a),null}s.properties&&!Kt(s.properties)||A.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}for(var l of i)if(s.properties&&H(s.properties[l]))return A.warn("Event '"+e.event+"' had its '"+l+"' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped."),null;return s}getPageViewId(){var e;return(e=this.pageViewManager.ui)==null?void 0:e.pageViewId}captureTraceFeedback(e,n){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:n})}captureTraceMetric(e,n,i){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:n,$ai_metric_value:String(i)})}Cn(e){var n=gt(e)&&!e,i=le.N()&&le.P("ph_debug")==="true";return!n&&(!!i||e)}}Je.__defaultExtensionClasses={},Je.rs=(()=>{var t=()=>{};return{trace:t,debug:t,info:t,warn:t,error:t,fatal:t}})(),(function(t,e){for(var n=0;e.length>n;n++)t.prototype[e[n]]=kg(t.prototype[e[n]])})(Je,["identify"]);class su{constructor(e){this.disabled=e===!1;var n=he(e)?e:{};this.thresholdPx=n.threshold_px||30,this.timeoutMs=n.timeout_ms||1e3,this.clickCount=n.click_count||3,this.clicks=[]}isRageClick(e,n,i){if(this.disabled)return!1;var r=this.clicks[this.clicks.length-1];if(r&&Math.abs(e-r.x)+Math.abs(n-r.y)i-r.timestamp){if(this.clicks.push({x:e,y:n,timestamp:i}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:n,timestamp:i}];return!1}}var $o="$copy_autocapture",Mo=pe("[AutoCapture]");function Lo(t,e){return e.length>t?e.slice(0,t)+"...":e}function Fm(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!hn(e));return e}function Rm(t,e){var n,i,r=e.e,s=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!hn(t))return{props:{}};for(var c=[t],d=new Set([t]),f=t;f.parentNode&&!Qe(f,"body")&&lf>c.length;)if(af(f.parentNode)){var h=f.parentNode.host;if(d.has(h))break;d.add(h),c.push(h),f=h}else{if(!hn(f.parentNode)||d.has(f.parentNode))break;d.add(f.parentNode),c.push(f.parentNode),f=f.parentNode}var p,g,m=[],v={},S=!1,b=!1;if(ie(c,(E=>{var P=va(E);if(Qe(E,"a")){var $=E.getAttribute("href");S=!!(P&&$&&Ui($))&&(u?fn($):$)}j(rs(E),"ph-no-capture")&&(b=!0),m.push((function(L,N,K,V,M){M===void 0&&(M=!1);var R=L.tagName.toLowerCase(),Z={tag_name:R};ul.indexOf(R)>-1&&!K&&(Z.$el_text=R.toLowerCase()==="a"||R.toLowerCase()==="button"?Lo(1024,jc(L)):Lo(1024,Ji(L)));var Ce=rs(L);Ce.length>0&&(Z.classes=Ce.filter((function(ae){return ae!==""}))),ie(L.attributes,(function(ae){var Ie;if((!hf(L)||["name","id","class","aria-label"].indexOf(ae.name)!==-1)&&(V==null||!V.includes(ae.name))&&!N&&Ui(ae.value)&&(!X(Ie=ae.name)||Ie.substring(0,10)!=="_ngcontent"&&Ie.substring(0,7)!=="_nghost")){var Se=ae.value;ae.name==="class"&&(Se=cl(Se).join(" ")),Z["attr__"+ae.name]=Lo(1024,ae.name==="href"&&M?fn(Se):Se)}}));for(var oe=1,ye=1,$e=L;$e=Fm($e);)oe++,$e.tagName===L.tagName&&ye++;return Z.nth_child=oe,Z.nth_of_type=ye,Z})(E,s,o,a,u));var O=(function(L){if(!va(L))return{};var N={};return ie(L.attributes,(function(K){if(K.name&&K.name.indexOf("data-ph-capture-attribute")===0){var V=K.name.replace("data-ph-capture-attribute-",""),M=K.value;V&&M&&Ui(M)&&(N[V]=M)}})),N})(E);fe(v,O)})),b)return{props:{},explicitNoCapture:b};if(o||(m[0].$el_text=Qe(t,"a")||Qe(t,"button")?jc(t):Ji(t)),S){var _,x;m[0].attr__href=S;var I=(_=ss(S))==null?void 0:_.host,T=w==null||(x=w.location)==null?void 0:x.host;I&&T&&I!==T&&(p=S)}return{props:fe({$event_type:r.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(E){return E.map((P=>{var $,O,L="";if(P.tag_name&&(L+=P.tag_name),P.attr_class)for(var N of(P.attr_class.sort(),P.attr_class))L+="."+N.replace(/"/g,"");var K=k({},P.text?{text:P.text}:{},{"nth-child":($=P.nth_child)!==null&&$!==void 0?$:0,"nth-of-type":(O=P.nth_of_type)!==null&&O!==void 0?O:0},P.href?{href:P.href}:{},P.attr_id?{attr_id:P.attr_id}:{},P.attributes),V={};return $r(K).sort(((M,R)=>M[0].localeCompare(R[0]))).forEach((M=>{var R=M[1];return V[Uc(M[0].toString())]=Uc(R.toString())})),(L+=":")+$r(V).map((M=>M[0]+'="'+M[1]+'"')).join("")})).join(";")})((function(E){return E.map((P=>{var $,O,L={text:($=P.$el_text)==null?void 0:$.slice(0,400),tag_name:P.tag_name,href:(O=P.attr__href)==null?void 0:O.slice(0,2048),attr_class:zg(P),attr_id:P.attr__id,nth_child:P.nth_child,nth_of_type:P.nth_of_type,attributes:{}};return $r(P).filter((N=>N[0].indexOf("attr__")===0)).forEach((N=>L.attributes[N[0]]=N[1])),L}))})(g)))},(n=m[0])!=null&&n.$el_text?{$el_text:(i=m[0])==null?void 0:i.$el_text}:{},p&&r.type==="click"?{$external_click_url:p}:{},v)}}var Ii=pe("[ExceptionAutocapture]"),ou=()=>{},Tm=pe("[TracingHeaders]"),wn=pe("[Web Vitals]"),au=9e5,lu="disabled",cu="lazy_loading",ki="awaiting_config",Sr="missing_config";pe("[SessionRecording]"),pe("[SessionRecording]");var Ia="[SessionRecording]",Bt=pe(Ia),$m=pe("[Heatmaps]");function No(t){return he(t)&&"clientX"in t&&"clientY"in t&&ke(t.clientX)&&ke(t.clientY)}var xr=pe("[Product Tours]"),Oo=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(sl))},Mm=["$set_once","$set"],Et=pe("[SiteApps]"),uu="Error while initializing PostHog app with config id ";function qn(t,e,n){if(H(t))return!1;switch(n){case"exact":return t===e;case"contains":var i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(i,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}class Lm{constructor(e){this.ns=new pl,this.ss=(n,i)=>this.os(n,i)&&this.ls(n,i)&&this.us(n,i)&&this.hs(n,i),this.os=(n,i)=>i==null||!i.event||n?.event===i?.event,this._instance=e,this.ds=new Set,this.vs=new Set}init(){var e,n;C((e=this._instance)==null?void 0:e._addCaptureHook)||(n=this._instance)==null||n._addCaptureHook(((i,r)=>{this.on(i,r)}))}register(e){var n,i;if(!C((n=this._instance)==null?void 0:n._addCaptureHook)&&(e.forEach((o=>{var a,l;(a=this.vs)==null||a.add(o),(l=o.steps)==null||l.forEach((u=>{var c;(c=this.ds)==null||c.add(u?.event||"")}))})),(i=this._instance)!=null&&i.autocapture)){var r,s=new Set;e.forEach((o=>{var a;(a=o.steps)==null||a.forEach((l=>{l!=null&&l.selector&&s.add(l?.selector)}))})),(r=this._instance)==null||r.autocapture.setElementSelectors(s)}}on(e,n){var i;n!=null&&e.length!=0&&(this.ds.has(e)||this.ds.has(n.event))&&this.vs&&((i=this.vs)==null?void 0:i.size)>0&&this.vs.forEach((r=>{this.cs(n,r)&&this.ns.emit("actionCaptured",r.name)}))}fs(e){this.onAction("actionCaptured",(n=>e(n)))}cs(e,n){if(n?.steps==null)return!1;for(var i of n.steps)if(this.ss(e,i))return!0;return!1}onAction(e,n){return this.ns.on(e,n)}ls(e,n){if(n!=null&&n.url){var i,r=e==null||(i=e.properties)==null?void 0:i.$current_url;if(!r||typeof r!="string"||!qn(r,n.url,n.url_matching||"contains"))return!1}return!0}us(e,n){return!!this.ps(e,n)&&!!this.gs(e,n)&&!!this.ys(e,n)}ps(e,n){var i;if(n==null||!n.href)return!0;var r=this.bs(e);if(r.length>0)return r.some((a=>qn(a.href,n.href,n.href_matching||"exact")));var s,o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!o&&qn((s=o.match(/(?::|")href="(.*?)"/))?s[1]:"",n.href,n.href_matching||"exact")}gs(e,n){var i;if(n==null||!n.text)return!0;var r=this.bs(e);if(r.length>0)return r.some((u=>qn(u.text,n.text,n.text_matching||"exact")||qn(u.$el_text,n.text,n.text_matching||"exact")));var s,o,a,l=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!l&&(s=(function(u){for(var c,d=[],f=/(?::|")text="(.*?)"/g;!H(c=f.exec(u));)d.includes(c[1])||d.push(c[1]);return d})(l),o=n.text,a=n.text_matching||"exact",s.some((u=>qn(u,o,a))))}ys(e,n){var i,r;if(n==null||!n.selector)return!0;var s=e==null||(i=e.properties)==null?void 0:i.$element_selectors;if(s!=null&&s.includes(n.selector))return!0;var o=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";if(n.selector_regex&&o)try{return new RegExp(n.selector_regex).test(o)}catch{return!1}return!1}bs(e){var n;return(e==null||(n=e.properties)==null?void 0:n.$elements)==null?[]:e?.properties.$elements}hs(e,n){return n==null||!n.properties||n.properties.length===0||Uf(n.properties.reduce(((i,r)=>{var s=U(r.value)?r.value.map(String):r.value!=null?[String(r.value)]:[];return i[r.key]={values:s,operator:r.operator||"exact"},i}),{}),e?.properties)}}class Nm{constructor(e){var n;this._s=[],this._instance=e,this.ws=new Map,this.ks=new Map,this.xs=new Map,(n=this._instance)==null||n.onSessionId==null||n.onSessionId((i=>this.Ss(i)))}Cs(e){return!1}Ms(){return null}Ts(e){}Es(){}Is(e,n){return!!e&&Uf(e.propertyFilters,n?.properties)}Ps(e,n){var i=new Map;return e.forEach((r=>{var s;(s=r.conditions)==null||(s=s[n])==null||(s=s.values)==null||s.forEach((o=>{if(o!=null&&o.name){var a=i.get(o.name)||[];a.push(r.id),i.set(o.name,a)}}))})),i}Rs(e,n,i){var r=(i===wi.Activation?this.ws:this.ks).get(e),s=[];return this.As((o=>{s=o.filter((a=>r?.includes(a.id)))})),s.filter((o=>{var a,l=(a=o.conditions)==null||(a=a[i])==null||(a=a.values)==null?void 0:a.find((u=>u.name===e));return this.Is(l,n)}))}register(e){var n;C((n=this._instance)==null?void 0:n._addCaptureHook)||(this.Fs(e),this.Ls(e))}Ls(e){var n=e.filter((i=>{var r,s;return((r=i.conditions)==null?void 0:r.actions)&&((s=i.conditions)==null||(s=s.actions)==null||(s=s.values)==null?void 0:s.length)>0}));n.length!==0&&(this.Os==null&&(this.Os=new Lm(this._instance),this.Os.init(),this.Os.fs((i=>{this.onAction(i)}))),n.forEach((i=>{var r,s,o,a,l;i.conditions&&(r=i.conditions)!=null&&r.actions&&(s=i.conditions)!=null&&(s=s.actions)!=null&&s.values&&((o=i.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.Os)==null||a.register(i.conditions.actions.values),(l=i.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var c=this.xs.get(u.name);c&&c.push(i.id),this.xs.set(u.name,c||[i.id])}})))})))}Fs(e){var n,i=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.events)&&((a=s.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0})),r=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.cancelEvents)&&((a=s.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0}));i.length===0&&r.length===0||((n=this._instance)==null||n._addCaptureHook(((s,o)=>{this.onEvent(s,o)})),this.ws=this.Ps(e,wi.Activation),this.ks=this.Ps(e,wi.Cancellation))}onEvent(e,n){var i,r,s=this.Ds(),o=(n==null||(i=n.properties)==null?void 0:i.$survey_id)||(n==null||(r=n.properties)==null?void 0:r.$product_tour_id);if(o&&this.getActivatedIds().includes(o)){var a=this.$s(e,o);if(a==="consume")return s.info("event consumed activated item, removing it",{event:e,itemId:o}),void this.Ns([o]);if(a==="persist")return s.info("shown item promoted to persisted activation",{event:e,itemId:o}),this.qs(o),void this.js([o])}if(this.ks.has(e)){var l=this.Rs(e,n,wi.Cancellation);l.length>0&&(s.info("cancel event matched, cancelling items",{event:e,itemsToCancel:l.map((c=>c.id))}),this.Ns(l.map((c=>c.id))),l.forEach((c=>this.Bs(c.id))))}if(this.ws.has(e)){s.info("event name matched",{event:e,eventPayload:n,items:this.ws.get(e)});var u=this.Rs(e,n,wi.Activation);this.Hs(u.map((c=>c.id)))}}onAction(e){this.xs.has(e)&&this.Hs(this.xs.get(e)||[])}Hs(e){var n;if(e.length!==0){var i=!((n=this._instance)==null||n.get_session_id==null||!n.get_session_id()),r=[];for(var s of e)i&&this.Cs(s)?this.qs(s)&&this.Us(s):r.push(s);r.length>0&&(this._s=[...new Set([...this._s,...r])]),this.Ds().info("updating activated items",{activatedItems:this.getActivatedIds()})}}qs(e){this._s=this._s.filter((i=>i!==e));var n=this.zs();return!n.includes(e)&&(this.Ws([...n,e]),this.Vs(),!0)}Ns(e){var n=new Set(e);this._s=this._s.filter((s=>!n.has(s)));var i=this.Zs(),r=i.filter((s=>!n.has(s)));r.length!==i.length&&(this.Ws(r),r.length===0&&this.Gs()),this.js(e)}Qs(){var e,n=this.Ms();if(!n)return{};var i=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n];return i&&typeof i=="object"?i:{}}Us(e){if(this.Ms()){var n=this.Qs();this.Ts(k({},n,{[e]:Date.now()}))}}js(e){if(this.Ms()){var n=this.Qs(),i={},r=!1;for(var s of Object.entries(n)){var o=s[0],a=s[1];e.includes(o)?r=!0:i[o]=a}r&&(Kt(i)?this.Es():this.Ts(i))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var n=this.Qs()[e];return ke(n)?n:void 0}}Zs(){var e,n=this.Js();return((e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n])||[]}zs(){var e,n,i=this.Zs();if(i.length===0)return[];var r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[this.Ys()],s=(n=this._instance)==null||n.get_session_id==null?void 0:n.get_session_id();return s&&r===s?i:[]}Vs(){var e,n=(e=this._instance)==null||e.get_session_id==null?void 0:e.get_session_id();n&&this.Xs(n)}Gs(){this.ta()}Ss(e){var n,i=(n=this._instance)==null||(n=n.persistence)==null?void 0:n.props[this.Ys()];if(i&&i!==e){var r=this.Zs(),s=this.Qs();r.length>0&&(this.Ws([]),r.filter((o=>ke(s[o]))).forEach((o=>this.Bs(o)))),this.Gs(),this.Ks()}}getActivatedIds(){return[...new Set([...this.zs(),...this._s])].filter((e=>!this.ea(e)))}reset(){this._s=[],this.Zs().length>0&&this.Ws([]),this.Gs(),this.Ks()}getEventToItemsMap(){return this.ws}ia(){return this.Os}}class Om extends Nm{constructor(e){super(e)}Js(){return ca}Ys(){return Fr}Ms(){return Rr}Ts(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Rr]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Rr)}Cs(e){var n,i;this.As((s=>{i=s.find((o=>o.id===e))}));var r=(n=i)==null||(n=n.appearance)==null?void 0:n.surveyPopupDelaySeconds;return ke(r)&&r>0}ra(){return zt.SHOWN}As(e){var n;(n=this._instance)==null||n.getSurveys(e)}Bs(e){var n;(n=this._instance)==null||n.cancelPendingSurvey(e)}Ds(){return Q}Ws(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[ca]:e})}Xs(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Fr]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Fr)}ea(){return!1}$s(e,n){var i;this.As((s=>{i=s.find((o=>o.id===n))}));var r=!i||(function(s){var o;return Hf(s)&&!((o=s.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||s.schedule==="always"})(i);return r?e===zt.SHOWN?"consume":"ignore":e===zt.SHOWN?"persist":e===zt.DISMISSED||e===zt.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var Ir="SDK is not enabled or survey functionality is not yet loaded",du="Disabled. Not loading surveys.",Bm=w!=null&&w.location?os(w.location.hash,"__posthog")||os(location.hash,"state"):null,fu="_postHogToolbarParams",hu=pe("[Toolbar]"),pu=pe("[FeatureFlags]");class Dm{constructor(e,n){n===void 0&&(n=!1),this.na=!1,this.update(e,n)}update(e,n){this.sa=((i,r)=>{var s,o,a,l;return{bootstrap:{featureFlags:(s=i.bootstrap)==null?void 0:s.featureFlags,featureFlagPayloads:(o=i.bootstrap)==null?void 0:o.featureFlagPayloads},remoteRequestsDisabled:r,featureFlagsDisabled:!!i.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!i.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!i.advanced_feature_flags_dedup_per_session,cacheTtlMs:i.feature_flag_cache_ttl_ms,requestTimeoutMs:i.feature_flag_request_timeout_ms,compression:i.disable_compression?"none":"base64",evaluationContexts:(a=(l=i.evaluation_contexts)!==null&&l!==void 0?l:i.evaluation_environments)!==null&&a!==void 0?a:[],flagKeys:U(i.flag_keys)?i.flag_keys:void 0}})(e,n),!e.evaluation_environments||e.evaluation_contexts||this.na||(pu.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.na=!0),C(e.flag_keys)||U(e.flag_keys)||pu.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var gu=pe("[FeatureFlags]"),bn=pe("[FeatureFlags]",{debugEnabled:!0}),Bo=`" failed. Feature flags didn't load in time.`,mu="connection_error",vu=t=>{for(var e={},n=0;t.length>n;n++)e[t[n]]=!0;return e},_u=t=>{var e={};for(var n of $r(t||{})){var i=n[1];i&&(e[n[0]]=i)}return e},St=pe("[Error tracking]"),yu="Refusing to render web experiment since the viewer is a likely bot",jm={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>cs(e,t),not_regex:(t,e)=>!cs(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class Me{get Ne(){return this._instance.config}constructor(e){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(i){i===void 0&&(i=!1),n.getWebExperiments((r=>{Me.aa("retrieved web experiments from the server"),n.oa=new Map,r.forEach((s=>{if(s.feature_flag_key){var o;n.oa&&(Me.aa("setting flag key ",s.feature_flag_key," to web experiment ",s),(o=n.oa)==null||o.set(s.feature_flag_key,s));var a=n._instance.getFeatureFlag(s.feature_flag_key);X(a)&&s.variants[a]&&n.la(s.name,a,s.variants[a].transforms)}else if(s.variants)for(var l in s.variants){var u=s.variants[l];Me.ua(u,n._instance)&&n.la(s.name,l,u.transforms)}}))}),i)},this._instance=e,this._instance.onFeatureFlags((i=>{this.onFeatureFlags(i)}))}initialize(){}onFeatureFlags(e){if(this._is_bot())Me.aa(yu);else if(!this.Ne.disable_web_experiments){if(H(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();Me.aa("applying feature flags",e),e.forEach((n=>{var i;if(this.oa&&(i=this.oa)!=null&&i.has(n)){var r,s=this._instance.getFeatureFlag(n),o=(r=this.oa)==null?void 0:r.get(n);s&&o!=null&&o.variants[s]&&this.la(o.name,s,o.variants[s].transforms)}}))}}previewWebExperiment(){var e=Me.getWindowLocation();if(e!=null&&e.search){var n=ii(e?.search,"__experiment_id"),i=ii(e?.search,"__experiment_variant");n&&i&&(Me.aa("previewing web experiments "+n+" && "+i),this.getWebExperiments((r=>{this.ha(parseInt(n),i,r)}),!1,!0))}}loadIfEnabled(){this.Ne.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,n,i){if(this.Ne.disable_web_experiments&&!i)return e([]);var r=this._instance.get_property("$web_experiments");if(r&&!n)return e(r);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this.Ne.token),method:"GET",timestampMode:"query",callback:s=>e(s.statusCode===200&&s.json&&s.json.experiments||[])})}ha(e,n,i){var r=i.filter((s=>s.id===e));r&&r.length>0&&(Me.aa("Previewing web experiment ["+r[0].name+"] with variant ["+n+"]"),this.la(r[0].name,n,r[0].variants[n].transforms))}static ua(e,n){return!H(e.conditions)&&Me.da(e,n)&&Me.va(e)}static da(e,n){var i;if(H(e.conditions)||H((i=e.conditions)==null?void 0:i.url))return!0;var r=Me.getWindowLocation();if(r){var s,o,a,l=rf(n,r.href);return(s=e.conditions)==null||!s.url||jm[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return w?.location}static va(e){var n;if(H(e.conditions)||H((n=e.conditions)==null?void 0:n.utm))return!0;var i=yf();if(i.utm_source){var r,s,o,a,l,u,c,d,f=(r=e.conditions)==null||(r=r.utm)==null||!r.utm_campaign||((s=e.conditions)==null||(s=s.utm)==null?void 0:s.utm_campaign)==i.utm_campaign,h=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==i.utm_source,p=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==i.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==i.utm_term;return f&&p&&g&&h}return!1}static aa(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;n>r;r++)i[r-1]=arguments[r];A.info("[WebExperiments] "+e,i)}la(e,n,i){this._is_bot()?Me.aa(yu):n!=="control"?i.forEach((r=>{if(r.selector){var s;Me.aa("applying transform of variant "+n+" for experiment "+e+" ",r);var o=(s=document)==null?void 0:s.querySelectorAll(r.selector);o?.forEach((a=>{var l=a;r.html&&(l.innerHTML=r.html),r.css&&l.setAttribute("style",r.css)}))}})):Me.aa("Control variants leave the page unmodified.")}_is_bot(){return Ue&&this._instance?Bf(Ue,this.Ne.custom_blocked_useragents):void 0}}var st=pe("[Conversations]"),En="Conversations not available yet.",wu="console",Gf="__posthogHandledLogsRequestError",Do=(t,e)=>{var n=t instanceof Error?t:new Error(e);return n[Gf]=!0,n},bu=t=>!!t&&typeof t=="object"&&t[Gf]===!0,Cs={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=gu,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 Dm(t.config,t.Qi()),this.Ta=this.Ea)}updateConfig(t,e){var n;(n=this.Ea)==null||n.update(t,e)}setup(t){return this.Ia=t,this.rt=t.logger.createLogger("[FeatureFlags]"),n=()=>{this.Ia===t&&(this.Ia=void 0,this.nn=t,this.Pa(t))},(e=t.kv.initialize())!=null&&e.then?e.then(n):n();var e,n}Pa(t){if(this.nn===t)return w&&ve(w,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){w?.removeEventListener("online",this.Ca)}dispose(){var t;this.ba++,this.wa=!1,this.Ia=void 0,this.nn&&(this.La(),(t=this.Ra)==null||t.dispose(),this.Ra=void 0,this.ga=[],w?.removeEventListener("online",this.Ca),this.nn=void 0)}get Ne(){return this.Ta.get()}Oa(t){var e;return(e=this.nn)==null?void 0:e.kv.get(t)}F(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.set(t)}))}q(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.remove(t)}))}Da(t){try{t()}catch(e){this.rt.error("Failed to update feature flag persistence",e)}}Fa(){var t={};for(var e of[Ti,$i,Pr,It]){var n=this.Oa(e);C(n)||(t[e]=n)}this.fa=t;var i=k({},t),r=this.Oa(Sn);if(r)for(var s of Object.entries(r))i["$feature/"+s[0]]=s[1];this.pa=i}Aa(){var t=this.Ne.cacheTtlMs;if(!t||0>=t)return!1;var e=this.Oa(ji);return typeof e!="number"||Date.now()-e>t}$a(){return!!this.Aa()&&(this.xa||this.ya||(this.xa=!0,this.rt.warn("Feature flag cache is stale, triggering refresh..."),this.reloadFeatureFlags()),!0)}Na(){var t=this.Ne.evaluationContexts;return t!=null&&t.length?t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid evaluation context found:",e,"Expected non-empty string"),n})):[]}qa(){var t=this.Ne.flagKeys;if(!C(t))return t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid flag key found:",e,"Expected non-empty string"),n}))}initialize(){var t,e,n=this.Ne,i=(t=(e=n.bootstrap)==null?void 0:e.featureFlags)!==null&&t!==void 0?t:{};if(Object.keys(i).length){var r,s,o=(r=(s=n.bootstrap)==null?void 0:s.featureFlagPayloads)!==null&&r!==void 0?r:{},a=Object.keys(i).filter((u=>!!i[u])).reduce(((u,c)=>(u[c]=i[c]||!1,u)),{}),l=Object.keys(o).filter((u=>a[u])).reduce(((u,c)=>(o[c]&&(u[c]=o[c]),u)),{});return this.ja({featureFlags:a,featureFlagPayloads:l})}}updateFlags(t,e,n){var i,r,s=n!=null&&n.merge&&(i=this.Oa(Sn))!==null&&i!==void 0?i:{},o=n!=null&&n.merge&&(r=this.Oa($i))!==null&&r!==void 0?r:{},a=k({},s,t),l=k({},o,e),u={};for(var c of Object.entries(a)){var d=c[0],f=c[1];u[d]={key:d,enabled:hc(f),variant:pc(f),reason:void 0,metadata:C(l?.[d])?void 0:{id:0,version:void 0,description:void 0,payload:l[d]}}}this.ja({flags:u})}get hasLoadedFlags(){return this.ma}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var t=this.Oa(aa),e=this.Oa(It),n=this.Oa(xn);if(!n&&!e)return t||{};var i=fe({},t||{}),r=[...new Set([...Object.keys(n||{}),...Object.keys(e||{})])];for(var s of r){var o,a,l=i[s],u=e?.[s],c=C(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=C(u)?l?.variant:typeof u=="string"?u:void 0,f=n?.[s],h=k({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(h.original_enabled=l?.enabled),d!==l?.variant&&(h.original_variant=l?.variant),f&&(h.metadata=k({},l?.metadata,{payload:f,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),i[s]=h}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:n,finalDetails:i}),this.ca=!0),i}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((n=>{var i=t[n];return{key:n,enabled:hc(i),variant:pc(i),payload:fc(e[n])}}))}getFlagVariants(){var t=this.Oa(Sn),e=this.Oa(It);if(!e)return t||{};for(var n=fe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:e,finalFlags:n}),this.ca=!0),n}getFlagPayloads(){var t=this.Oa($i),e=this.Oa(xn);if(!e)return t||{};for(var n=fe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flag payloads!",{flagPayloads:t,overriddenPayloads:e,finalPayloads:n}),this.ca=!0),n}reloadFeatureFlags(){this._a||this.Ne.featureFlagsDisabled||this.Ma()||this.Ba||(this.ga.slice().forEach((t=>{try{t()}catch(e){this.rt.error("Error while running feature flags reloading callback",e)}})),this.Ba=setTimeout((()=>{this.Ha()}),5))}La(){clearTimeout(this.Ba),this.Ba=void 0}onReloading(t){return this.ga.push(t),()=>{this.ga=this.ga.filter((e=>e!==t))}}ensureFlagsLoaded(){this.ma||this.ya||this.Ba||this.reloadFeatureFlags()}setAnonymousDistinctId(t){this.$anon_distinct_id=t}setReloadingPaused(t){this._a=t}resetFlagCallReported(){this.q(Cn)}Ha(t){this.La();var e=this.nn;if(e&&!this.Ne.remoteRequestsDisabled&&!this.Ma())if(this.ya)this.wa=!0;else{var n={token:e.projectToken,distinct_id:e.distinctId,groups:e.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:k({},e.initialPersonProperties,this.Oa(jt)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(In),timezone:If()};C(e.deviceId)||(n.$device_id=e.deviceId),(t!=null&&t.disableFlags||this.Ne.featureFlagsDisabled)&&(n.disable_flags=!0);var i=this.Na();i.length&&(n.evaluation_contexts=i);var r=this.qa();C(r)||(n.flag_keys=r);var s=this.Ne.onlyEvaluateSurveyFeatureFlags,o="/flags/?v=2"+(s?"&only_evaluate_survey_feature_flags=true":""),a=this.ba;this.ya=!0;var l=()=>{this.wa&&(this.wa=!1,this.Ha())},u=c=>{this.ya=!1,a===this.ba&&(this.F({[Tr]:[mu]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:n,compression:this.Ne.compression==="base64"?je.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,f,h=(d=c.json)!==null&&d!==void 0?d:{},p=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),p||this.wa||(this.$anon_distinct_id=void 0),!n.disable_flags||this.wa){this.ka=!p;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?mu:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),h.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((f=h.quotaLimited)==null||!f.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[Tr]:g}),m?this.rt.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more."):n.disable_flags||this.ja(h,p,{partialResponse:s}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return vf(this.Sa,3)}Ua(t){this.Sa=_f(t,this.Sa,3,(()=>this.rt.warn("Feature flag requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped refreshing feature flags; will try again when connectivity changes.")))}getFeatureFlag(t,e){var n;if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var i=this.getFeatureFlagResult(t,e);return(n=i?.variant)!==null&&n!==void 0?n:i?.enabled}}else this.rt.warn('getFeatureFlag for key "'+t+Bo)}getFeatureFlagDetails(t){return this.getFlagsWithDetails()[t]}getFeatureFlagPayload(t){var e=this.getFeatureFlagResult(t,{send_event:!1});return e?.payload}getFeatureFlagResult(t,e){if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var n,i=this.getFlagVariants(),r=t in i,s=i[t],o=this.getFlagPayloads()[t],a=String(s),l=this.Oa(Pr)||void 0,u=this.Oa(ji)||void 0,c=this.Oa(Cn)||{};if(this.Ne.deduplicateCallsPerSession){var d,f=(d=this.nn)==null?void 0:d.session.sessionId,h=this.Oa(Li);f&&f!==h&&(c={},n=f)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))n&&this.F({[Cn]:c,[Li]:n});else{var p,g,m,v,S,b,_,x,I,T;U(c[t])?c[t].push(a):c[t]=[a],this.F(k({[Cn]:c},n?{[Li]:n}:{}));var E=this.getFeatureFlagDetails(t),P=[...(p=this.Oa(Tr))!==null&&p!==void 0?p:[]];C(s)&&P.push("flag_missing");var $={$feature_flag:t,$feature_flag_response:s,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((g=this.Ne.bootstrap)==null||(g=g.featureFlags)==null?void 0:g[t])||null,$feature_flag_bootstrapped_payload:((m=this.Ne.bootstrap)==null||(m=m.featureFlagPayloads)==null?void 0:m[t])||null,$used_bootstrap_value:!this.ka};C(E==null||(v=E.metadata)==null?void 0:v.has_experiment)||($.$feature_flag_has_experiment=E.metadata.has_experiment),C(E==null||(S=E.metadata)==null?void 0:S.version)||($.$feature_flag_version=E.metadata.version);var O,L=(b=E==null||(_=E.reason)==null?void 0:_.description)!==null&&b!==void 0?b:E==null||(x=E.reason)==null?void 0:x.code;L&&($.$feature_flag_reason=L),E!=null&&(I=E.metadata)!=null&&I.id&&($.$feature_flag_id=E.metadata.id),C(E?.original_variant)&&C(E?.original_enabled)||($.$feature_flag_original_response=C(E.original_variant)?E.original_enabled:E.original_variant),E!=null&&(T=E.metadata)!=null&&T.original_payload&&($.$feature_flag_original_payload=E==null||(O=E.metadata)==null?void 0:O.original_payload),P.length&&($.$feature_flag_error=P.join(",")),this.za($)}else n&&this.F({[Cn]:c,[Li]:n});if(r)return{key:t,enabled:!!s,variant:typeof s=="string"?s:void 0,payload:fc(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+Bo)}za(t){try{var e;(e=this.nn)==null||e.capture("$feature_flag_called",t).catch((n=>{this.rt.error("Failed to capture feature flag call",n)}))}catch(n){this.rt.error("Failed to capture feature flag call",n)}}getRemoteConfigPayload(t,e){this.Wa(t,e)}Wa(t,e){var n=this;return se((function*(){var i=n.nn;if(i){var r={distinct_id:i.distinctId,token:i.projectToken,person_properties:{$lib:i.library.name,$lib_version:i.library.version}},s=n.Na();s.length&&(r.evaluation_contexts=s);var o,a=n.qa();C(a)||(r.flag_keys=a);try{var l,u=(l=(yield i.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:r,compression:n.Ne.compression==="base64"?je.Base64:void 0,sentAt:"body",timeoutMs:n.Ne.requestTimeoutMs})).json)==null?void 0:l.featureFlagPayloads;o=u?.[t]||void 0}catch(c){return void n.rt.error("Remote config feature flag request failed",c)}try{e(o)}catch(c){n.rt.error("Remote config feature flag callback failed",c)}}}))()}isFeatureEnabled(t,e){if(e===void 0&&(e={}),e.fresh&&!this.ka)return e.defaultValue;if(!(this.ma||this.getFlags()&&this.getFlags().length>0))return this.rt.warn('isFeatureEnabled for key "'+t+Bo),e.defaultValue;var n=this.getFeatureFlag(t,e);return C(n)?e.defaultValue:!!n}addFeatureFlagsHandler(t){this.featureFlagEventHandlers.push(t)}removeFeatureFlagsHandler(t){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((e=>e!==t))}receivedFeatureFlags(t,e,n){this.ja(t,e,n)}ja(t,e,n){if(this.nn){this.ma=!0;var i=(function(r,s,o,a,l,u){s===void 0&&(s={}),o===void 0&&(o={}),a===void 0&&(a={}),u===void 0&&(u=gu);var c=((I,T)=>{var E=I.flags;return E?k({},I,{featureFlags:Object.fromEntries(Object.keys(E).map((P=>{var $;return[P,($=E[P].variant)!==null&&$!==void 0?$:E[P].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(E).filter((P=>E[P].enabled)).filter((P=>{var $;return($=E[P].metadata)==null?void 0:$.payload})).map((P=>{var $;return[P,($=E[P].metadata)==null?void 0:$.payload]})))}):(I.featureFlags&&T.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),I)})(r,u),d=c.flags,f=c.featureFlags,h=c.featureFlagPayloads;if(f){var p=r.requestId,g=r.evaluatedAt;if(U(f)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(f)for(var v=0;f.length>v;v++)m[f[v]]=!0;return{[Ti]:f,[Sn]:m,[Zr]:!1}}var S=f,b=h,_=d;if(l!=null&&l.partialResponse)S=k({},s,S),b=k({},o,b),_=k({},a,_);else if(r.errorsWhileComputingFlags)if(d){var x=new Set(Object.keys(d).filter((I=>{var T;return!((T=d[I])!=null&&T.failed)})));S=k({},s,Object.fromEntries(Object.entries(S).filter((I=>x.has(I[0]))))),b=k({},o,Object.fromEntries(Object.entries(b||{}).filter((I=>x.has(I[0]))))),_=k({},a,Object.fromEntries(Object.entries(_||{}).filter((I=>x.has(I[0])))))}else S=k({},s,S),b=k({},o,b),_=k({},a,_);return k({[Ti]:Object.keys(_u(S)),[Sn]:S||{},[$i]:b||{},[aa]:_||{},[Zr]:r.minimalFlagCalledEvents===!0},p?{[Pr]:p}:{},g?{[ji]:g}:{})}})(t,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),n,this.rt);i&&this.F(i),e||(this.xa=!1),this.Va(e)}}override(t,e){e===void 0&&(e=!1),this.rt.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:t,suppressWarning:e})}overrideFeatureFlags(t){this.Za(t)}Za(t){if(this.nn){if(t===!1)return this.q([It,xn]),this.Va(),void bn.info("All overrides cleared");if(U(t))return this.F({[It]:vu(t)}),this.Va(),void bn.info("Flag overrides set",{flags:t});if(t&&typeof t=="object"&&("flags"in t||"payloads"in t)){var e,n=t;this.ca=!!((e=n.suppressWarning)!==null&&e!==void 0&&e);var i={},r=n.flags,s=n.payloads;return r&&(i[It]=U(r)?vu(r):r),s&&(i[xn]=s),Object.keys(i).length&&this.F(i),r===!1&&s===!1?this.q([It,xn]):r===!1?this.q(It):s===!1&&this.q(xn),this.Va(),r===!1?bn.info("Flag overrides cleared"):r&&bn.info("Flag overrides set",{flags:r}),void(s===!1?bn.info("Payload overrides cleared"):s&&bn.info("Payload overrides set",{payloads:s}))}if(t&&typeof t=="object")return this.F({[It]:t}),this.Va(),void bn.info("Flag overrides set",{flags:t});this.rt.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:t})}else this.rt.warn("posthog.featureFlags.overrideFeatureFlags called before feature flags were ready")}onFeatureFlags(t){if(this.addFeatureFlagsHandler(t),this.ma){var e=this.Ga(),n=e.flags,i=e.flagVariants;try{t(n,i)}catch(r){this.rt.error("Error while running feature flags callback",r)}}return()=>this.removeFeatureFlagsHandler(t)}updateEarlyAccessFeatureEnrollment(t,e,n){var i=(this.Oa(Ar)||[]).find((l=>l.flagKey===t)),r={["$feature_enrollment/"+t]:e},s={$feature_flag:t,$feature_enrollment:e,$set:r};i&&(s.$early_access_feature_name=i.name),n&&(s.$feature_enrollment_stage=n);var o=k({},this.getFlagVariants(),{[t]:e});this.F({[Ti]:Object.keys(_u(o)),[Sn]:o,[jt]:k({},this.Oa(jt)||{},r)}),this.Va();try{var a;(a=this.nn)==null||a.capture("$feature_enrollment_update",s).catch((l=>{this.rt.error("Failed to capture early access feature enrollment",l)}))}catch(l){this.rt.error("Failed to capture early access feature enrollment",l)}}getEarlyAccessFeatures(t,e,n){e===void 0&&(e=!1);var i=this.Oa(Ar);!i||e?this.Qa(t,n):t(i)}Qa(t,e){var n=this;return se((function*(){var i=n.nn;if(i){var r,s=e?"&"+e.map((a=>"stage="+a)).join("&"):"";try{var o=yield i.sendRequest("/api/early_access_features/?token="+i.projectToken+s,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;n.F({[Ar]:r=o.json.earlyAccessFeatures})}catch(a){return void n.rt.error("Early access feature request failed",a)}try{t(r)}catch(a){n.rt.error("Early access feature callback failed",a)}}}))()}Ga(){var t=this.getFlags(),e=this.getFlagVariants();return{flags:t.filter((n=>e[n])),flagVariants:Object.keys(e).filter((n=>e[n])).reduce(((n,i)=>(n[i]=e[i],n)),{})}}Va(t){this.Fa();var e=this.Ga(),n=e.flags,i=e.flagVariants;this.featureFlagEventHandlers.forEach((r=>{try{r(n,i,{errorsLoading:t})}catch(s){this.rt.error("Error while running feature flags callback",s)}}))}setPersonPropertiesForFlags(t,e){e===void 0&&(e=!0),this.Ka(t,e)}Ka(t,e){e===void 0&&(e=!0);var n=this.Oa(jt)||{},i=t?.$set||(t!=null&&t.$set_once?{}:t),r=t?.$set_once,s={};if(r)for(var o in r)({}).hasOwnProperty.call(r,o)&&(o in n||(s[o]=r[o]));this.F({[jt]:k({},n,s,i)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=k({},this.Oa(jt)||{});t.forEach((i=>{delete n[i]})),this.F({[jt]:n}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(jt),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=this.Oa(In)||{},i=k({},n);for(var r of Object.keys(t))i[r]=k({},n[r],t[r]);this.F({[In]:i}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(In)||{};this.F({[In]:k({},e,{[t]:{}})})}else this.q(In)}reset(){this.ba++,this.wa=!1,this.Fa(),this.ma=!1,this._a=!1,this.ka=!1,this.$anon_distinct_id=void 0,this.La(),this.ca=!1,this.Sa=0}}},Um={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===ki||this.Ya===Sr?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=lu,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(F==null||!F.visibilityState||F.visibilityState==="visible")return!0;var n=w==null||(e=w.performance)==null||e.getEntriesByType==null?void 0:e.getEntriesByType("visibility-state");return!(n!=null&&n.length)||n.some((i=>i.name==="visible"))})(),this.Ie=()=>{var e;F?.visibilityState==="visible"&&(this.io=!0,(e=this.Ja)==null||e.setDocumentWasEverVisible==null||e.setDocumentWasEverVisible(!0))},this._instance=t,!this._instance.sessionManager)throw Bt.error("started without valid sessionManager"),new Error(Ia+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===Wt)throw new Error(Ia+' cannot be used with cookieless_mode="always"');F!=null&&F.addEventListener&&ve(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(An))==null||!t.enabled),n=!this.Ne.disable_session_recording,i=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return w&&e&&n&&!i}startIfEnabledOrStop(t){var e;if(!(this.eo||this.ro&&(e=this.Ja)!=null&&e.isStarted)){var n=!C(Object.assign)&&!C(Array.from);this.ro&&n?(this.no(t),Bt.info("starting")):(this.Ya=lu,this.stopRecording())}}no(t){var e,n,i;this.ro&&(this.Ya!==ki&&this.Ya!==Sr&&(this.Ya=cu),B!=null&&(e=B.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(n=B.__PosthogExtensions__)!=null&&n.initSessionRecording?this.so(t):(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,this.ao,(r=>{if(r)return Bt.error("could not load recorder",r);this.so(t)})))}stopRecording(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.stop()}oo(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.discard()}lo(){var t,e;(t=this.Mr)==null||t.unregister(ol),(e=this.Mr)==null||e.unregister(Vd)}uo(t,e){if(H(t))return null;var n,i=ke(t)?t:parseFloat(t);return typeof(n=i)!="number"||!Number.isFinite(n)||0>n||n>1?(Bt.warn(e+" must be between 0 and 1. Ignoring invalid value:",t),null):i}ho(t){if(this.Mr){var e,n,i=this.Mr,r=()=>{var s,o=t.sessionRecording===!1?void 0:t.sessionRecording,a=this.uo((s=this.Ne.session_recording)==null?void 0:s.sampleRate,"session_recording.sampleRate"),l=this.uo(o?.sampleRate,"remote config sampleRate"),u=a??l;H(u)&&this.lo();var c=o?.minimumDurationMilliseconds;i.register({[An]:k({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:k({capturePerformance:t.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:u,minimumDurationMilliseconds:C(c)?null:c,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers,version:o?.version,triggerGroups:o?.triggerGroups})})};r(),(e=this.Xa)==null||e.call(this),this.Xa=(n=this._instance.sessionManager)==null?void 0:n.onSessionId(r)}}onRemoteConfig(t){var e=t.ok?t.config:void 0;return e&&"sessionRecording"in e?e.sessionRecording===!1?(this.ho(e),void this.oo()):(this.ho(e),void this.startIfEnabledOrStop()):(this.Ya===ki&&(this.Ya=Sr,Bt.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(t,e){var n;e===void 0&&(e="log"),(n=this.Ja)!=null&&n.log?this.Ja.log(t,e):Bt.warn("log called before recorder was ready")}get ao(){var t,e,n=(t=this._instance)==null||(t=t.persistence)==null?void 0:t.get_property(An);return(n==null||(e=n.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(An);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(n){return Bt.warn("persisted remote config for session recording is invalid and will be ignored",n),!1}return!H(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,n,i;if(!this.eo){if((e=B.__PosthogExtensions__)==null||!e.initSessionRecording)return Bt.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[ef]:!0});var r;if(this.Ja||(this.Ja=(r=B.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===Sr||this.Ya===ki?void 0:(this.Ya=ki,Bt.info("persisted remote config is stale, requesting fresh config before starting"),void new kf(this._instance).load());this.Ya=cu,(n=(i=this.Ja).setDocumentWasEverVisible)==null||n.call(i,this.io),this.Ja.start(t)}}onRRwebEmit(t){var e;(e=this.Ja)==null||e.onRRwebEmit==null||e.onRRwebEmit(t)}overrideLinkedFlag(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Kd]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Gd]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,n;this.Ja||(n=this.Mr)==null||n.register({[t==="url"?Yd:Jd]:!0}),(e=this.Ja)==null||e.overrideTrigger(t)}get sdkDebugProperties(){var t;return((t=this.Ja)==null?void 0:t.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(t,e){var n;return!((n=this.Ja)==null||!n.tryAddCustomEvent(t,e))}}},Hm={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new su(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,n=he(this.instance.config.autocapture)?this.instance.config.autocapture:{};return n.url_allowlist=(t=n.url_allowlist)==null?void 0:t.map((i=>new RegExp(i))),n.url_ignorelist=(e=n.url_ignorelist)==null?void 0:e.map((i=>new RegExp(i))),n}yo(){if(this.isBrowserSupported()){if(w&&F){var t=n=>{n=n||w?.event;try{this.bo(n)}catch(i){Mo.error("Failed to capture event",i)}};if(ve(F,"submit",t,{capture:!0}),ve(F,"change",t,{capture:!0}),ve(F,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=n=>{n=n||w?.event;try{this.bo(n,$o)}catch(i){Mo.error("Failed to capture copy/cut event",i)}};ve(F,"copy",e,{capture:!0}),ve(F,"cut",e,{capture:!0})}}}else Mo.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.vo&&(this.yo(),this.vo=!0)}onRemoteConfig(t){if(this.fo=!0,t.ok){var e=t.config;e.elementsChainAsString&&(this.po=e.elementsChainAsString);var n=e.autocapture_opt_out;gt(n)&&(this.instance.persistence&&this.instance.persistence.register({[ea]:n}),this.co=n),this.startIfEnabled()}else this.startIfEnabled()}setElementSelectors(t){this.mo=t}getElementSelectors(t){var e,n=[];return(e=this.mo)==null||e.forEach((i=>{var r=F?.querySelectorAll(i);r?.forEach((s=>{t===s&&n.push(i)}))})),n}get isEnabled(){var t,e,n=(t=this.instance.persistence)==null?void 0:t.props[ea],i=this.co,r=this.instance.Qi()&&!this.fo;if(Ke(i)&&!gt(n)&&!r)return!1;var s=(e=this.co)!==null&&e!==void 0?e:!!n;return!!this.instance.config.autocapture&&!s}bo(t,e){if(e===void 0&&(e="$autocapture"),this.isEnabled){var n,i=bo(t);of(i)&&(i=i.parentNode||null),e==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&this.instance.config.rageclick&&(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,t.timeStamp||new Date().getTime())&&Lc(i,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var r=e===$o;if(i&&(function(d,f,h,p,g,m){var v;if(!w||dl(d)||h!=null&&h.url_allowlist&&!Tc(h.url_allowlist,m)||h!=null&&h.url_ignorelist&&Tc(h.url_ignorelist,m))return!1;if(h!=null&&h.dom_event_allowlist){var S=h.dom_event_allowlist;if(S&&!S.some((E=>f.type===E)))return!1}var b=ff(d,p),_=b.parentIsUsefulElement,x=b.targetElementList;if(!(function(E,P){var $=P?.element_allowlist;if(C($))return!0;var O,L=function(K){if($.some((V=>K.tagName.toLowerCase()===V)))return{v:!0}};for(var N of E)if(O=L(N))return O.v;return!1})(x,h)||!ma(x,h?.css_selector_allowlist)||ma(x,(v=h?.css_selector_ignorelist)!==null&&v!==void 0?v:Dg))return!1;try{var I=w.getComputedStyle(d);if(I&&I.getPropertyValue("cursor")==="pointer"&&f.type==="click")return!0}catch{}var T=d.tagName.toLowerCase();switch(T){case"html":return!1;case"form":return(g||["submit"]).indexOf(f.type)>=0;case"input":case"select":case"textarea":return(g||["change","click"]).indexOf(f.type)>=0;default:return _?(g||["click"]).indexOf(f.type)>=0:(g||["click"]).indexOf(f.type)>=0&&(ul.indexOf(T)>-1||d.getAttribute("contenteditable")==="true")}})(i,t,this.Ne,r,r?["copy","cut"]:void 0,this.instance)){var s=Rm(i,{e:t,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.Ne.element_attribute_ignorelist,elementsChainAsString:this.po,disableCaptureUrlHashes:this.instance.config.disable_capture_url_hashes}),o=s.props;if(s.explicitNoCapture)return!1;var a=this.getElementSelectors(i);if(a&&a.length>0&&(o.$element_selectors=a),e===$o){var l,u=cf(w==null||(l=w.getSelection())==null?void 0:l.toString()),c=t.type||"clipboard";if(!u)return!1;o.$selected_content=u,o.$copy_type=c}return this.instance.capture(e,o),!0}}}isBrowserSupported(){return De(F?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(w==null||(e=w.location)==null?void 0:e.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(A.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.wo&&this.wo(),this.wo=void 0,A.info("History API monitoring stopped")}monitorHistoryChanges(){w&&w.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(w&&((e=w.history[t])==null||!e.__posthog_wrapped__)){var n=this;(function(i,r,s){try{if(!(r in i))return ou;var o={next:i[r]},a=s((function(){for(var l=arguments.length,u=new Array(l),c=0;l>c;c++)u[c]=arguments[c];return o.next.apply(this,u)}));return De(a)&&(a.prototype=a.prototype||{},Object.defineProperties(a,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:o}})),i[r]=a,()=>{if(i[r]!==a)for(var l=i[r];De(l)&&l.__posthog_layer__;){var u=l.__posthog_layer__;if(u.next===a)return void(u.next=o.next);l=u.next}else i[r]=o.next}}catch{return ou}})(w.history,t,(i=>function(r,s,o){i.call(this,r,s,o),n.So(t)}))}}So(t){try{var e,n=w==null||(e=w.location)==null?void 0:e.pathname;if(!n)return;n!==this._o&&this.isEnabled&&this._instance.capture(Vn,{navigation_type:t}),this._o=n}catch(i){A.error("Error capturing "+t+" pageview",i)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};ve(w,"popstate",t),this.wo=()=>{w&&w.removeEventListener("popstate",t)}}}},heatmaps:class{get Ne(){return this.instance.config}constructor(t){var e;this.Co=!1,this.vo=!1,this.Mo=null,this.instance=t,this.Co=!((e=this.instance.persistence)==null||!e.props[ta]),this.rageclicks=new su(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return he(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return H(this.Ne.capture_heatmaps)?H(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;$m.info("starting..."),this.To(),this.Ie()}else{var t;clearInterval((t=this.Mo)!==null&&t!==void 0?t:void 0),this.Eo(),this.getAndClearBuffer()}}onRemoteConfig(t){if(t.ok){var e=t.config;if("heatmaps"in e){var n=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[ta]:n}),this.Co=n,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){No(t.originalEvent)&&this.ke(t.originalEvent,"deadclick")}Ie(){this.Mo&&clearInterval(this.Mo),this.Mo=F?.visibilityState==="visible"?setInterval(this.cr.bind(this),this.flushIntervalMilliseconds):null}To(){w&&F&&(this.Po=this.cr.bind(this),ve(w,ns,this.Po),this.Ro=t=>this.ke(t||w?.event),ve(F,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||w?.event),ve(F,"mousemove",this.Ao,{capture:!0}),this.Lo=new Hc(this.instance,Vg,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),ve(F,ts,this.Oo),this.vo=!0)}Eo(){var t;w&&F&&(this.Po&&w.removeEventListener(ns,this.Po),this.Ro&&F.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&F.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&F.removeEventListener(ts,this.Oo),clearTimeout(this.Do),(t=this.Lo)==null||t.stop(),this.vo=!1)}$o(t,e){var n=this.instance.scrollManager.scrollY(),i=this.instance.scrollManager.scrollX(),r=this.instance.scrollManager.scrollElement(),s=(function(o,a,l){for(var u=o;u&&hn(u)&&!Qe(u,"body");){if(u===l)return!1;var c=void 0;try{var d,f,h;c=(d=(f=(h=u.ownerDocument)==null?void 0:h.defaultView)!==null&&f!==void 0?f:w)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(j(a,c))return!0;u=uf(u)}return!1})(bo(t),["fixed","sticky"],r);return{x:t.clientX+(s?0:i),y:t.clientY+(s?0:n),target_fixed:s,type:e}}ke(t,e){var n;if(e===void 0&&(e="click"),!Rc(t.target)&&No(t)){var i=this.$o(t,e);(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,new Date().getTime())&&Lc(bo(t),this.instance.config.rageclick)&&this.Vt(k({},i,{type:"rageclick"})),this.Vt(i)}}Fo(t){!Rc(t.target)&&No(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(w){var e=this.Ne.disable_capture_url_hashes?fn(w.location.href):w.location.href,n=this.Ne.custom_personal_data_properties,i=this.Ne.mask_personal_data_properties?[...ri,...n||[]]:[],r=Zi(e,i,Xi);this.R=this.R||{},this.R[r]||(this.R[r]=[]),this.R[r].push(t)}}cr(){this.R&&!Kt(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:Hc,webVitalsAutocapture:class{constructor(t){var e;this.Co=!1,this.vo=!1,this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this.No=()=>{clearTimeout(this.qo),this.qo=void 0,this.R.metrics.length!==0&&(this._instance.capture("$web_vitals",k({$current_url:this.R.url},this.R.metrics.reduce(((n,i)=>k({},n,{["$web_vitals_"+i.name+"_event"]:k({},i),["$web_vitals_"+i.name+"_value"]:i.value})),{}))),this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.jo=n=>{var i;if(this.R=this.R||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},H(n?.name)||H(n?.value))wn.error("Invalid metric received",n);else{var r=typeof n.navigationURL=="string"?n.navigationURL:void 0,s=this.Bo(r);if(!C(s)){var o=ke(n.navigationId)||typeof n.navigationId=="string"?"navigation:"+n.navigationId:"url:"+s;if(!this.Ho||this.Ho>n.value){this.R.navigationKey!==o&&(this.No(),this.qo=setTimeout(this.No,this.flushToCaptureTimeoutMs)),C(this.R.navigationKey)&&(this.R.navigationKey=o,this.R.url=s),this.R.firstMetricTimestamp=C(this.R.firstMetricTimestamp)?Date.now():this.R.firstMetricTimestamp,n.attribution&&n.attribution.interactionTargetElement&&(n.attribution.interactionTargetElement=void 0);var a=(i=this._instance.sessionManager)==null?void 0:i.checkAndGetSessionAndWindowId(!0),l=k({},n,r?{navigationURL:s}:{},{$current_url:s,timestamp:Date.now()});C(a)||(l.$session_id=a.sessionId,l.$window_id=a.windowId),this.R.metrics.push(l),this.R.metrics.length===this.allowedMetrics.length&&this.No()}else wn.error("Ignoring metric with value >= "+this.Ho,n)}}},this.Uo=()=>{if(!this.vo){var n,i,r,s,o=B.__PosthogExtensions__,a=o?.postHogWebVitalsCallbacksByFlavor,l=a?.[this.zo]||(this.zo==="web-vitals"&&C(a)?o?.postHogWebVitalsCallbacks:void 0);if(C(l)||(n=l.onLCP,i=l.onCLS,r=l.onFCP,s=l.onINP),n&&i&&r&&s){var u={reportSoftNavs:this.useSoftNavs};this.allowedMetrics.indexOf("LCP")>-1&&n(this.jo.bind(this),u),this.allowedMetrics.indexOf("CLS")>-1&&i(this.jo.bind(this),u),this.allowedMetrics.indexOf("FCP")>-1&&r(this.jo.bind(this),u),this.allowedMetrics.indexOf("INP")>-1&&s(this.jo.bind(this),u),this.vo=!0}else wn.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[sa]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,n=he(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return H(n)?((e=this._instance.persistence)==null?void 0:e.props[oa])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(he(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=he(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=he(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=he(this.Wo)&&ke(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:au;return t>0&&6e4>=t?au:t}get isEnabled(){var t=me?.protocol;if(t!=="http:"&&t!=="https:")return wn.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=he(this.Wo)?this.Wo.web_vitals:gt(this.Wo)?this.Wo:void 0;return gt(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(wn.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var n=he(e.capturePerformance)&&!!e.capturePerformance.web_vitals,i=he(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[sa]:n}),this._instance.persistence.register({[oa]:i})),this.Co=n,this.startIfEnabled()}}}get zo(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}ai(t){var e=B.__PosthogExtensions__,n=this.zo,i=e?.postHogWebVitalsCallbacksByFlavor;i!=null&&i[n]||n==="web-vitals"&&C(i)&&e!=null&&e.postHogWebVitalsCallbacks?t():e==null||e.loadExternalDependency==null||e.loadExternalDependency(this._instance,n,(r=>{r?wn.error("failed to load script",r):t()}))}Bo(t){var e=t||w?.location.href;if(e){var n=this._instance.config.disable_capture_url_hashes?fn(e):e,i=this._instance.config.custom_personal_data_properties,r=this._instance.config.mask_personal_data_properties?[...ri,...i||[]]:[];return Zi(n,r,Xi)}wn.error("Could not determine current URL")}}},Wm={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var n;if(w&&this.isEnabled&&(n=B.__PosthogExtensions__)!=null&&n.errorWrappingFunctions){var i=B.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,r=B.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,s=B.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.Vo&&this.Ne.capture_unhandled_errors&&(this.Vo=i(this.captureException.bind(this))),!this.Zo&&this.Ne.capture_unhandled_rejections&&(this.Zo=r(this.captureException.bind(this))),!this.Go&&this.Ne.capture_console_errors&&(this.Go=s(this.captureException.bind(this)))}catch(o){Ii.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[na]),this.Jo=new Up(k({},(function(n){var i,r,s,o;return n===void 0&&(n={}),{refillRate:(i=(r=n.exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:n.__exceptionRateLimiterRefillRate)!==null&&i!==void 0?i:1,bucketSize:(s=(o=n.exceptionRateLimiterBucketSize)!==null&&o!==void 0?o:n.__exceptionRateLimiterBucketSize)!==null&&s!==void 0?s:10}})(this._instance.config.error_tracking),{refillInterval:1e4,rt:Ii})),this.Ne=this.Yo(),this.startIfEnabledOrStop()}Yo(){var t=this._instance.config.capture_exceptions,e={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return he(t)?e=k({},e,t):(C(t)?this.Ko:t)&&(e=k({},e,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),e}get isEnabled(){return this.Ne.capture_console_errors||this.Ne.capture_unhandled_errors||this.Ne.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(Ii.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",(i=>{if(i)return Ii.error("failed to load script",i);t()}))}Qo(){var t,e,n;(t=this.Vo)==null||t.call(this),this.Vo=void 0,(e=this.Zo)==null||e.call(this),this.Zo=void 0,(n=this.Go)==null||n.call(this),this.Go=void 0}onRemoteConfig(t){if(t.ok){var e=t.config;"autocaptureExceptions"in e&&(this.Ko=!!e.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[na]:this.Ko}),this.Ne=this.Yo(),this.startIfEnabledOrStop())}}onConfigChange(){this.Ne=this.Yo()}captureException(t){var e,n,i,r=(e=t==null||(n=t.$exception_list)==null||(n=n[0])==null?void 0:n.type)!==null&&e!==void 0?e:"Exception";this.Jo.consumeRateLimit(r)?Ii.info("Skipping exception capture because of client rate limiting.",{exception:r}):(i=this._instance.exceptions)==null||i.sendExceptionEvent(t)}},exceptions:class{constructor(t){var e,n;this.Xo=[],this.tl=new rg([new fg,new bg,new pg,new hg,new yg,new _g,new mg,new wg],(function(i){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;r>o;o++)s[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` -`),d=l;c.length>d;d++){var f=c[d];if(1024>=f.length){var h=Cc.test(f)?f.replace(Cc,"$1"):f;if(!h.match(/\S*Error: /)){for(var p of s){var g=p(h,i);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var v=Array.from(m);return v.reverse(),v.slice(0,50).map((S=>{return k({},S,{filename:S.filename||(b=v,b[b.length-1]||{}).filename,function:S.function||ni});var b}))})(u)}})("web:javascript",lg,dg)),this._instance=t,this.Xo=(e=(n=this._instance.persistence)==null?void 0:n.get_property(ia))!==null&&e!==void 0?e:[],this.el=Jr(this.il()),this.rl=new Sg(this.el)}onConfigChange(){this.el=Jr(this.il()),this.rl.setConfig(this.el)}onRemoteConfig(t){var e,n,i;if(t.ok){var r=t.config;if("errorTracking"in r){var s=(e=(n=r.errorTracking)==null?void 0:n.suppressionRules)!==null&&e!==void 0?e:[],o=(i=r.errorTracking)==null?void 0:i.captureExtensionExceptions;this.Xo=s,this._instance.persistence&&this._instance.persistence.register({[ia]:this.Xo,[ra]:o})}}}get nl(){var t,e=!!this._instance.get_property(ra),n=this._instance.config.error_tracking.captureExtensionExceptions;return(t=n??e)!==null&&t!==void 0&&t}buildProperties(t,e){return this.tl.buildFromUnknown(t,{syntheticException:e?.syntheticException,mechanism:{handled:e?.handled}})}addExceptionStep(t,e){if(this.el.enabled)try{if(!X(t)||t.trim().length===0)return void St.warn("Ignoring exception step because message must be a non-empty string");var n=(function(s){if(!s)return{sanitizedProperties:{},droppedKeys:[]};var o=[];return{sanitizedProperties:Object.keys(s).reduce(((a,l)=>Eg.has(l)?(o.push(l),a):(a[l]=s[l],a)),{}),droppedKeys:o}})(this.sl(e)),i=n.sanitizedProperties,r=n.droppedKeys;r.length>0&&St.warn("Ignoring reserved exception step fields",{droppedKeys:r}),this.rl.add(k({[Kr]:t,[Yr]:new Date().toISOString()},i))}catch(s){St.error("Failed to add exception step. Ignoring breadcrumb.",s)}}sendExceptionEvent(t){try{var e=t.$exception_list;if(this.al(e)){if(this.ol(e))return this.ll("Exception dropped: matched a suppression rule"),void St.info("Skipping exception capture because a suppression rule matched");if(!this.nl&&this.ul(e))return this.ll("Exception dropped: thrown by a browser extension"),void St.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.hl(e))return this.ll("Exception dropped: thrown by the PostHog SDK"),void St.info("Skipping exception capture because it was thrown by the PostHog SDK")}var n=this.el.enabled&&H(t.$exception_steps)?this.dl(t):t,i=typeof(s=globalThis._posthogReleaseId)=="string"&&s.length>0?s:void 0;i&&(n.$release_id=i);try{var r=this._instance.capture("$exception",n,{_noTruncate:!0,_batchKey:"exceptionEvent",Wn:!0});return r&&this.rl.clear(),r}catch(o){return St.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void St.error("Failed to process exception event. Ignoring this exception.",o)}var s}dl(t){try{var e=this.rl.getAttachable();return e.length===0?t:k({},t,{$exception_steps:e})}catch(n){return St.error("Failed to read buffered exception steps. Capturing exception without steps.",n),t}}ll(t){this.el.enabled&&this.rl.add({[Kr]:t,[Yr]:new Date().toISOString()})}sl(t){return he(t)?k({},t):{}}il(){var t,e;return(t=(e=this._instance.config.error_tracking)==null?void 0:e.exception_steps)!==null&&t!==void 0?t:{}}ol(t){if(t.length===0)return!1;try{var e=t.reduce(((n,i)=>{var r=i.type,s=i.value;return X(r)&&r.length>0&&n.$exception_types.push(r),X(s)&&s.length>0&&n.$exception_values.push(s),n}),{$exception_types:[],$exception_values:[]});return this.Xo.some((n=>{var i=n.values.map((r=>{var s=jf[r.operator],o=e[r.key];if(!s||!o)return!1;var a=U(r.value)?r.value:[r.value];return a.length>0&&s(a,o)}));return n.type==="OR"?i.some(Boolean):i.every(Boolean)}))}catch(n){return St.warn("Failed to evaluate suppression rules. Capturing the exception.",n),!1}}ul(t){return t.flatMap((e=>{var n,i;return(n=(i=e.stacktrace)==null?void 0:i.frames)!==null&&n!==void 0?n:[]})).some((e=>e.filename&&e.filename.startsWith("chrome-extension://")))}hl(t){if(t.length>0){var e,n,i,r,s=(e=(n=t[0].stacktrace)==null?void 0:n.frames)!==null&&e!==void 0?e:[],o=s[s.length-1];return(i=o==null||(r=o.filename)==null?void 0:r.includes("posthog.com/static"))!==null&&i!==void 0&&i}return!1}al(t){return!H(t)&&U(t)}}},qm=k({productTours:class{get Mr(){return this._instance.persistence}constructor(t){this.vl=null,this.cl=null,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(t.ok){var e=t.config;if("productTours"in e){var n,i;if(this.Mr&&this.Mr.register({[sl]:!!e.productTours}),!Oo(this._instance))return!this.vl&&H((n=this.Mr)==null?void 0:n.props[Mi])||xr.info("product tours disabled; stopping and clearing cached tours"),(i=this.vl)==null||i.stop(),this.vl=null,void this.clearCache();this.loadIfEnabled()}}}loadIfEnabled(){!this.vl&&Oo(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.generateProductTours?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",(i=>{i?xr.error("Could not load product tours script",i):t()}))}fl(){var t;!this.vl&&(t=B.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=B.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(t,e){if(e===void 0&&(e=!1),!U(this.cl)||e){var n=this.Mr;if(n){var i=n.props[Mi];if(U(i)&&!e)return this.cl=i,void t(i,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",timestampMode:"query",callback:r=>{if(Oo(this._instance)){var s=r.statusCode;if(s!==200||!r.json){var o="Product Tours API could not be loaded, status: "+s;return s===0?r.error||xr.warn(o):xr.error(o),void t([],{isLoaded:!1,error:o})}var a=U(r.json.product_tours)?r.json.product_tours:[];this.cl=a,n&&n.register({[Mi]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){H(this.vl)?t([],{isLoaded:!1,error:"Product tours not loaded"}):this.vl.getActiveProductTours(t)}showProductTour(t){var e;(e=this.vl)==null||e.showTourById(t)}previewTour(t){this.vl?this.vl.previewTour(t):this.ai((()=>{var e;this.fl(),(e=this.vl)==null||e.previewTour(t)}))}dismissProductTour(){var t;(t=this.vl)==null||t.dismissTour("user_clicked_skip")}nextStep(){var t;(t=this.vl)==null||t.nextStep()}previousStep(){var t;(t=this.vl)==null||t.previousStep()}clearCache(){var t;this.cl=null,(t=this.Mr)==null||t.unregister(Mi)}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)}}},Cs),zm={siteApps:class{constructor(t){this.pl=0,this._instance=t,this.gl=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}ml(t,e){if(e){var n=this.globalsForEvent(e);this.gl.push(n),this.gl.length>1e3&&(this.gl=this.gl.slice(10))}}get siteAppLoaders(){var t;return(t=B._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,n,i,r,s,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var f=d[0];l[f]={id:u[f],type:f,properties:d[1]}}var h=t.$set_once,p=t.$set;return{event:k({},ud(t,Mm),{properties:k({},t.properties,p?{$set:k({},(e=(n=t.properties)==null?void 0:n.$set)!==null&&e!==void 0?e:{},p)}:{},h?{$set_once:k({},(i=(r=t.properties)==null?void 0:r.$set_once)!==null&&i!==void 0?i:{},h)}:{}),elements_chain:(s=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&s!==void 0?s:"",distinct_id:(a=t.properties)==null?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}bl(t){var e,n=(e=t.tagName)==null?void 0:e.toLowerCase();return n==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(Et.error("prepare_external_dependency_stylesheet returned null"),null):n==="script"&&this._instance.config.prepare_external_dependency_script?this._instance.config.prepare_external_dependency_script(t)||(Et.error("prepare_external_dependency_script returned null"),null):t}_l(){var t,e,n,i,r,s,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=F?.defaultView,u=l==null||(t=l.Node)==null?void 0:t.prototype;if(!l||!u)return()=>{};if(this.pl++,this.wl)return this.kl();var c=[],d=this,f=new WeakSet,h=(m,v,S)=>{if(m!=null&&m[v]){var b=m[v];m[v]=S(b),c.push((()=>{m[v]=b}))}},p=m=>{if(f.has(m))return m;var v=d.bl(m);return v&&f.add(v),v},g=m=>m.map((v=>typeof v=="string"?v:p(v))).filter((v=>!Ke(v)));return h(u,"appendChild",(m=>function(v){var S=p(v);return S?m.call(this,S):v})),h(u,"insertBefore",(m=>function(v,S){var b=p(v);return b?m.call(this,b,S):v})),h(u,"replaceChild",(m=>function(v,S){var b=p(v);return b?m.call(this,b,S):S})),[(e=l.Element)==null?void 0:e.prototype,(n=l.Document)==null?void 0:n.prototype,(i=l.DocumentFragment)==null?void 0:i.prototype].forEach((m=>{h(m,"append",(v=>function(){for(var S=arguments.length,b=new Array(S),_=0;S>_;_++)b[_]=arguments[_];return v.apply(this,g(b))})),h(m,"prepend",(v=>function(){for(var S=arguments.length,b=new Array(S),_=0;S>_;_++)b[_]=arguments[_];return v.apply(this,g(b))}))})),[(r=l.Element)==null?void 0:r.prototype,(s=l.CharacterData)==null?void 0:s.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((m=>{h(m,"before",(v=>function(){for(var S=arguments.length,b=new Array(S),_=0;S>_;_++)b[_]=arguments[_];return v.apply(this,g(b))})),h(m,"after",(v=>function(){for(var S=arguments.length,b=new Array(S),_=0;S>_;_++)b[_]=arguments[_];return v.apply(this,g(b))})),h(m,"replaceWith",(v=>function(){for(var S=arguments.length,b=new Array(S),_=0;S>_;_++)b[_]=arguments[_];var x=g(b);return b.length&&!x.length?void 0:v.apply(this,x)}))})),h((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(v,S){var b=p(S);return b?m.call(this,v,b):null})),this.wl=()=>{c.forEach((m=>m())),this.wl=void 0},this.kl()}kl(){var t=!1;return()=>{var e;t||(t=!0,this.pl--,this.pl===0&&((e=this.wl)==null||e.call(this)))}}xl(t,e){e===void 0&&(e=!0);var n=this._l();try{var i=t(n);return e&&n(),i}catch(r){throw n(),r}}setupSiteApp(t){var e=this.apps[t.id],n=()=>{var o;!e.errored&&this.gl.length&&(Et.info("Processing "+this.gl.length+" events for site app with id "+t.id),this.gl.forEach((a=>this.xl((()=>e.processEvent==null?void 0:e.processEvent(a))))),e.processedBuffer=!0),Object.values(this.apps).every((a=>a.processedBuffer||a.errored))&&((o=this.yl)==null||o.call(this))},i=!1,r=o=>{e.errored=!o,e.loaded=!0,Et.info("Site app with id "+t.id+" "+(o?"loaded":"errored")),i&&n()};try{var s=this.xl((o=>t.init({posthog:this._instance,callback(a){o(),r(a)}})),!1).processEvent;s&&(e.processEvent=s),i=!0}catch(o){Et.error(uu+t.id,o),r(!1)}if(i&&e.loaded)try{n()}catch(o){Et.error("Error while processing buffered events PostHog app with config id "+t.id,o),e.errored=!0}}Sl(){var t=this.siteAppLoaders||[];for(var e of t)this.apps[e.id]={id:e.id,loaded:!1,errored:!1,processedBuffer:!1};for(var n of t)this.setupSiteApp(n)}Cl(t){var e=this;if(Object.keys(this.apps).length!==0){var n=this.globalsForEvent(t),i=function(s){try{e.xl((()=>s.processEvent==null?void 0:s.processEvent(n)))}catch(o){Et.error("Error while processing event "+t.event+" for site app "+s.id,o)}};for(var r of Object.values(this.apps))i(r)}}onRemoteConfig(t){var e,n,i,r=this;if((e=this.siteAppLoaders)!=null&&e.length)return this.isEnabled?(this.Sl(),void this._instance.on("eventCaptured",(l=>this.Cl(l)))):void Et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((n=this.yl)==null||n.call(this),t.ok){var s=t.config;if((i=s.siteApps)!=null&&i.length)if(this.isEnabled){var o=function(){var l,u=a.id,c=a.url;B["__$$ph_site_app_"+u]=r._instance,(l=B.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(r._instance,c,(d=>{if(d)return Et.error(uu+u,d)}))};for(var a of s.siteApps)o()}else Et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},Vm={tracingHeaders:class{constructor(t){this.Ml=void 0,this.Tl=void 0,this.El=void 0,this.Uo=()=>{var e,n,i=this.Il();i?(C(this.Ml)&&(this.Ml=(e=B.__PosthogExtensions__)==null||(e=e.tracingHeadersPatchFns)==null?void 0:e._patchXHR(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager)),C(this.Tl)&&(this.Tl=(n=B.__PosthogExtensions__)==null||(n=n.tracingHeadersPatchFns)==null?void 0:n._patchFetch(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager))):this.Qo()},this._instance=t}initialize(){this.startIfEnabledOrStop()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",(i=>{if(i)return Tm.error("failed to load script",i);t()}))}Pl(){var t,e;return(t=(e=this._instance.config.tracing_headers)!==null&&e!==void 0?e:this._instance.config.addTracingHeaders)!==null&&t!==void 0?t:this._instance.config.__add_tracing_headers}Il(){var t=this.Pl();return U(t)?(U(this.El)?this.El.splice(0,this.El.length,...t):this.El=[...t],t.length>0?this.El:void 0):(U(this.El)&&this.El.splice(0),this.El=t||void 0,this.El)}Qo(){var t,e;(t=this.Ml)==null||t.call(this),(e=this.Tl)==null||e.call(this),this.Ml=void 0,this.Tl=void 0}startIfEnabledOrStop(){this.Il()?this.ai(this.Uo):this.Qo()}}},Gm=k({surveys:class{get Ne(){return this._instance.config}constructor(t){this.Rl=void 0,this._surveyManager=null,this.Al=!1,this.Fl=[],this.Ll=null,this.Ol=null,this._instance=t,this._surveyEventReceiver=null}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this.Ne.disable_surveys){if(!t.ok)return Q.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(H(e))return Q.warn("Flags not loaded yet. Not loading surveys.");var n=U(e);this.Rl=n?e.length>0:e,Q.info("flags response received, isSurveysEnabled: "+this.Rl),this.loadIfEnabled()}}reset(){try{var t;(t=this._surveyEventReceiver)==null||t.reset(),localStorage.removeItem("lastSeenSurveyDate");for(var e=[],n=0;nlocalStorage.removeItem(r)))}catch{}}loadIfEnabled(){if(!this._surveyManager)if(this.Al)Q.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)Q.info(du);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())Q.info("Not loading surveys in cookieless mode without consent.");else{var t=B?.__PosthogExtensions__;if(t){if(!C(this.Rl)||this.Ne.advanced_enable_surveys){var e=this.Rl||this.Ne.advanced_enable_surveys;this.Al=!0;try{var n=t.generateSurveys;if(n)return void this.Dl(n,e);var i=t.loadExternalDependency;if(!i)return void this.$l(al);i(this._instance,"surveys",(r=>{r||!t.generateSurveys?this.$l("Could not load surveys script",r):this.Dl(t.generateSurveys,e)}))}catch(r){throw this.$l("Error initializing surveys",r),r}finally{this.Al=!1}}}else Q.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new Om(this._instance),Q.info("Surveys loaded successfully"),this.Nl({isLoaded:!0})}$l(t,e){Q.error(t,e),this.Nl({isLoaded:!1,error:t})}onSurveysLoaded(t){return this.Fl.push(t),this._surveyManager&&this.Nl({isLoaded:!0}),()=>{this.Fl=this.Fl.filter((e=>e!==t))}}getSurveys(t,e){if(e===void 0&&(e=!1),this.Ne.disable_surveys)return Q.info(du),t([]);var n,i=this._instance.get_property(la);if(i&&!e)return t(i,{isLoaded:!0}),void(this.ql()&&this.getSurveys((()=>{}),!0));typeof Promise<"u"&&this.Ll?this.Ll.then((r=>t(r.surveys,r.context))):(typeof Promise<"u"&&(this.Ll=new Promise((r=>{n=r}))),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this.Ne.token),method:"GET",timestampMode:"query",timeout:this.Ne.surveys_request_timeout_ms,callback:r=>{var s;this.Ll=null;var o=r.statusCode;if(o!==200||!r.json){var a="Surveys API could not be loaded, status: "+o;o!==0?Q.error(a):r.error||Q.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(n==null||n({surveys:[],context:l}))}this.Ol=null;var u,c=r.json.surveys||[],d=c.filter((h=>(function(p){return!(!p.start_date||p.end_date)})(h)&&(Hf(h)||(function(p){var g;return!((g=p.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(h))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(s=this._instance.persistence)==null||s.register({[la]:c,[Xr]:Date.now()});var f={isLoaded:!0};t(c,f),n?.({surveys:c,context:f})}}))}ql(){return this.jl()&&!this.Ll&&!this.Bl()}jl(){var t=this._instance.get_property(Xr);return ke(t)&&Date.now()-t>3e5}Bl(){return ke(this.Ol)&&3e5>Date.now()-this.Ol}markSurveyAsSeen(t,e){var n,i={id:t,current_iteration:(n=e?.iteration)!==null&&n!==void 0?n:null};qf(i);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}}Nl(t){for(var e of this.Fl)try{if(!t.isLoaded)return e([],t);this.getSurveys(e)}catch(n){Q.error("Error in survey callback",n)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!H(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);Q.warn("init was not called")}Hl(t){var e=null;return this.getSurveys((n=>{var i;e=(i=n.find((r=>r.id===t)))!==null&&i!==void 0?i:null})),e}Ul(t){if(H(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(H(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(H(this._surveyManager))return Q.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 H(this._surveyManager)?(Q.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Ir})):new Promise((n=>{this.getSurveys((i=>{var r,s=(r=i.find((a=>a.id===t)))!==null&&r!==void 0?r:null;if(s){var o=this.zl(s);n({visible:o.eligible,disabledReason:o.reason})}else n({visible:!1,disabledReason:"Survey not found"})}),e)}))}renderSurvey(t,e,n){var i;if(H(this._surveyManager))Q.warn("init was not called");else{var r=typeof t=="string"?this.Hl(t):t;if(r!=null&&r.id)if(ym.includes(r.type)){var s=F?.querySelector(e);if(s)return(i=r.appearance)!=null&&i.surveyPopupDelaySeconds?(Q.info("Rendering survey "+r.id+" with delay of "+r.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;Q.info("Rendering survey "+r.id+" with delay of "+((o=r.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(a=this._surveyManager)==null||a.renderSurvey(r,s,n),Q.info("Survey "+r.id+" rendered")}),1e3*r.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(r,s,n);Q.warn("Survey element not found")}else Q.warn("Surveys of type "+r.type+" cannot be rendered in the app");else Q.warn("Survey not found")}}displaySurvey(t,e){var n;if(H(this._surveyManager))Q.warn("init was not called");else{var i=this.Hl(t);if(i){var r=i;if((n=i.appearance)!=null&&n.surveyPopupDelaySeconds&&e.ignoreDelay&&(r=k({},i,{appearance:k({},i.appearance,{surveyPopupDelaySeconds:0})})),e.displayType!==_a.Popover&&e.initialResponses&&Q.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),e.ignoreConditions===!1){var s=this.Ul(i);if(!s.eligible)return void Q.warn("Survey is not eligible to be displayed: ",s.reason)}e.displayType!==_a.Inline?this._surveyManager.handlePopoverSurvey(r,e):this.renderSurvey(r,e.selector,e.properties)}else Q.warn("Survey not found")}}cancelPendingSurvey(t){H(this._surveyManager)?Q.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},Cs),Km={toolbar:class{constructor(t){this.instance=t}Wl(t){B.ph_toolbar_state=t}Vl(){var t;return(t=B.ph_toolbar_state)!==null&&t!==void 0?t:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(t,e,n){if(t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),ga(this.instance.config)||!w||!F)return!1;t=t??w.location,n=n??w.history;try{if(!e){try{w.localStorage.setItem("test","test"),w.localStorage.removeItem("test")}catch{return!1}e=w?.localStorage}var i,r=Bm||os(t.hash,"__posthog")||os(t.hash,"state"),s=r?Pc((()=>JSON.parse(atob(decodeURIComponent(r)))))||Pc((()=>JSON.parse(decodeURIComponent(r)))):null;return s&&s.action==="ph_authorize"?((i=s).source="url",i&&Object.keys(i).length>0&&(s.desiredHash?t.hash=s.desiredHash:n?n.replaceState(n.state,"",t.pathname+t.search):t.hash="")):((i=JSON.parse(e.getItem(fu)||"{}")).source="localstorage",delete i.userIntent),!(!i.token||this.instance.config.token!==i.token||(this.loadToolbar(i),0))}catch{return!1}}Zl(t){var e=B.ph_load_toolbar||B.ph_load_editor;!H(e)&&De(e)?e(t,this.instance):hu.warn("No toolbar load function found")}loadToolbar(t){var e=!(F==null||!F.getElementById(sf));if(!w||e)return!1;var n=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,i=k({token:this.instance.config.token},t,{apiURL:this.instance.requestRouter.endpointFor("ui")},n?{instrument:!1}:{});if(w.localStorage.setItem(fu,JSON.stringify(k({},i,{source:void 0}))),this.Vl()===2)this.Zl(i);else if(this.Vl()===0){var r;this.Wl(1),(r=B.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"toolbar",(s=>{if(s)return hu.error("[Toolbar] Failed to load",s),void this.Wl(0);this.Wl(2),this.Zl(i)})),ve(w,"turbolinks:load",(()=>{this.Wl(0),this.loadToolbar(i)}))}return!0}Gl(t){return this.loadToolbar(t)}maybeLoadEditor(t,e,n){return t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),this.maybeLoadToolbar(t,e,n)}}},Ym=k({experiments:Me},Cs),Jm={conversations:class{constructor(t){this.Ql=void 0,this._conversationsManager=null,this.Kl=!1,this.Jl=null,this.Yl=!1,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this._instance.config.disable_conversations&&(this.Xl=t.ok,t.ok)){var e=t.config.conversations;H(e)||(gt(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||ga(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=B?.__PosthogExtensions__;if(t&&!C(this.Ql)&&this.Ql)if(this.Jl&&this.Jl.token){this.Kl=!0;try{var e=t.initConversations;if(e)return this.tu(e),void(this.Kl=!1);var n=t.loadExternalDependency;if(!n)return void this.eu(al);n(this._instance,"conversations",(i=>{i||!t.initConversations?this.eu("Could not load conversations script",i):this.tu(t.initConversations),this.Kl=!1}))}catch(i){this.eu("Error initializing conversations",i),this.Kl=!1}}else st.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,st.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else st.error("Cannot complete initialization: remote config is null")}eu(t,e){st.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():st.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!Ke(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":ga(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.Xl===!1?"remote_config_failed":C(this.Ql)?this.Xl?"disabled_in_project":"remote_config_pending":this.Ql?H(this.Jl)||!this.Jl.token?"missing_token":B!=null&&B.__PosthogExtensions__?this.Kl?"initializing":this.Yl?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.isVisible())!==null&&t!==void 0&&t}sendMessage(t,e,n){var i=this;return se((function*(){return i._conversationsManager?i._conversationsManager.sendMessage(t,e,n):(st.warn(En),null)}))()}getMessages(t,e){var n=this;return se((function*(){return n._conversationsManager?n._conversationsManager.getMessages(t,e):(st.warn(En),null)}))()}markAsRead(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(st.warn(En),null)}))()}getTickets(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(st.warn(En),null)}))()}requestRestoreLink(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(st.warn(En),null)}))()}restoreFromToken(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(st.warn(En),null)}))()}restoreFromUrlToken(){var t=this;return se((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(st.warn(En),null)}))()}getCurrentTicketId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getCurrentTicketId())!==null&&t!==void 0?t:null}getWidgetSessionId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getWidgetSessionId())!==null&&t!==void 0?t:null}Xn(){var t;(t=this._conversationsManager)==null||t.setIdentity()}ts(){var t;(t=this._conversationsManager)==null||t.clearIdentity()}}},Zm={logs:class{constructor(t){var e,n=this;this.iu=!1,this.ru=!1,this.rt=pe("[logs]"),this.nu=k({},this.rt,{error(){for(var i=arguments.length,r=new Array(i),s=0;i>s;s++)r[s]=arguments[s];r.some(bu)||n.rt.error(...r)}}),this.tr=[],this.su=[],this.Sa=0,this.au=()=>{var i,r;this.Sa=0,(i=this.ou)==null||i.onReconnect(),(r=this.lu)==null||r.onReconnect()},this._instance=t,this._instance&&(e=this._instance.config.logs)!=null&&e.captureConsoleLogs&&(this.iu=!0),w&&ve(w,"online",this.au)}uu(t,e,n,i){var r,s=(function(o,a){var l,u,c,d,f,h,p,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,v=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,S=C(v)?Math.max(m,2048):Math.max(m,v),b=o?.resourceAttributes;return{serviceName:(d=(f=b?.["service.name"])!==null&&f!==void 0?f:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(h=b?.["service.version"])!==null&&h!==void 0?h:o?.serviceVersion,environment:(p=b?.["deployment.environment"])!==null&&p!==void 0?p:o?.environment,resourceAttributes:b,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:S,maxBatchRecordsPerPost:100,rateCapWindowMs:g,maxLogsPerInterval:v,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}})((r=this._instance)==null||(r=r.config)==null?void 0:r.logs,n);return[new tg(this.hu(t,e),s,this.nu,(()=>this.du()),(o=>o()),void 0,i),s]}vu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.ou||this.cu!==e){var n;(n=this.ou)==null||n.reset(),this.cu=e;var i=this.uu((()=>this.tr),(r=>{this.tr=r}));this.ou=i[0],this.fu=i[1]}return this.ou}pu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.lu||this.gu!==e){var n;(n=this.lu)==null||n.reset(),this.gu=e;var i=this.uu((()=>this.su),(r=>{this.su=r}),{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},wu);this.lu=i[0],this.mu=i[1]}return this.lu}initialize(){this.loadIfEnabled()}onRemoteConfig(t){var e;if(t.ok){var n=(e=t.config.logs)==null?void 0:e.captureConsoleLogs;!H(n)&&n&&(this.iu=!0,this.loadIfEnabled())}}reset(){var t,e;this.tr=[],(t=this.ou)==null||t.reset(),this.su=[],(e=this.lu)==null||e.reset(),this.Sa=0}captureLog(t){this.vu().captureLog(t)}he(t){this.pu().captureLog(t)}get logger(){return this.yu||(this.yu={trace:(t,e)=>this.captureLog({body:t,level:"trace",attributes:e}),debug:(t,e)=>this.captureLog({body:t,level:"debug",attributes:e}),info:(t,e)=>this.captureLog({body:t,level:"info",attributes:e}),warn:(t,e)=>this.captureLog({body:t,level:"warn",attributes:e}),error:(t,e)=>this.captureLog({body:t,level:"error",attributes:e}),fatal:(t,e)=>this.captureLog({body:t,level:"fatal",attributes:e})}),this.yu}flushLogs(t){t?this.bu(t):(this.ou&&this.ou.flush().catch((e=>this._u(e))),this.lu&&this.lu.flush().catch((e=>this._u(e))))}_u(t){bu(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=B?.__PosthogExtensions__;if(t){var e=t.loadExternalDependency;e?e(this._instance,"logs",(n=>{var i;n||(i=t.logs)==null||!i.initializeLogs?this.rt.error("Could not load logs script",n):(t.logs.initializeLogs(this._instance),this.ru=!0)})):this.rt.error(al)}else this.rt.error("PostHog Extensions not found.")}}hu(t,e){var n=this._instance;return{get isDisabled(){return!1},get optedOut(){return!n.is_capturing()},getPersistedProperty:i=>i===Ut.LogsQueue?t():void 0,setPersistedProperty(i,r){var s;i===Ut.LogsQueue&&e((s=r)!==null&&s!==void 0?s:[])},Ot:i=>this.Ot(i),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Ot(t){return new Promise((e=>{if(vf(this.Sa,3))e({kind:"fatal",error:Do(void 0,"logs endpoint is unreachable, dropping batch")});else{var n=!1,i=s=>{n||(n=!0,clearTimeout(r),e(s))},r=setTimeout((()=>{this.rt.warn("Logs request timed out before receiving a response"),i({kind:"retry-later",error:Do(void 0,"logs request timed out")})}),9e4);this._instance._send_request({method:"POST",url:this.wu(),data:t,compression:"best-available",batchKey:"logs",fireCallbackOnDrop:!0,callback:s=>{var o=s.statusCode;if(this.ku(o),o>=200&&300>o)i({kind:"ok"});else if(o===413)i({kind:"too-large"});else if(o!==0&&o!==429&&500>o)i({kind:"fatal",error:new Error("logs request failed with status "+o)});else{var a;o===0?(s.error||this.rt.warn("Logs request failed before receiving an HTTP response"),i({kind:"retry-later",error:Do(s.error,"logs request failed before receiving an HTTP response")})):i({kind:"retry-later",error:(a=s.error)!==null&&a!==void 0?a:new Error("logs request failed with status "+o)})}}})}}))}ku(t){(t!==0||this._instance.__loaded)&&(this.Sa=_f(t,this.Sa,3,(()=>this.rt.warn("Log requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped sending logs; will try again when connectivity changes."))))}bu(t){this.tr.length>0&&this.xu(t,this.tr,this.fu,ne.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,wu,(e=>{this.su=e}))}xu(t,e,n,i,r){if(e.length!==0){var s=e.map((a=>a.record));r([]);var o=Ud(s,jd(n,ne.LIB_NAME,ne.LIB_VERSION),i,ne.LIB_VERSION);this._instance._send_request({method:"POST",url:this.wu(),data:o,compression:"best-available",batchKey:"logs",transport:t})}}wu(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}du(){var t,e={};if(e.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var n=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.windowId,r=n.sessionStartTimestamp,s=n.lastActivityTimestamp;e.sessionId=n.sessionId,e.windowId=i,H(r)||(e.sessionStartTimestamp=r),H(s)||(e.lastActivityTimestamp=s)}if(B!=null&&(t=B.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?fn(B.location.href):B.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},Xm={metrics:class{constructor(t){this.rt=pe("[metrics]"),this._instance=t}initialize(){}vu(){var t,e,n=(t=this._instance)==null||(t=t.config)==null?void 0:t.metrics;return this.ou&&this.cu===n||((e=this.ou)==null||e.reset(),this.cu=n,this.ou=new ng(this.hu(),(function(i){var r,s,o,a,l,u=i?.resourceAttributes;return{serviceName:(r=u?.["service.name"])!==null&&r!==void 0?r:i?.serviceName,serviceVersion:(s=u?.["service.version"])!==null&&s!==void 0?s:i?.serviceVersion,environment:(o=u?.["deployment.environment"])!==null&&o!==void 0?o:i?.environment,resourceAttributes:u,beforeSend:i?.beforeSend,flushIntervalMs:(a=i?.flushIntervalMs)!==null&&a!==void 0?a:1e4,maxSeriesPerFlush:(l=i?.maxSeriesPerFlush)!==null&&l!==void 0?l:1e3}})(n),this.rt)),this.ou}count(t,e,n){e===void 0&&(e=1),this.vu().count(t,e,n)}gauge(t,e,n){this.vu().gauge(t,e,n)}histogram(t,e,n){this.vu().histogram(t,e,n)}flush(t){if(!this.ou)return Promise.resolve();if(t){var e=this.ou.drainWindow();return e&&this.Jt(e,t),Promise.resolve()}return this.ou.flush().catch((n=>this.rt.error("PostHog metrics flush failed:",n)))}reset(){var t;(t=this.ou)==null||t.reset()}hu(){var t=this._instance,e=this;return{get isDisabled(){return!1},get optedOut(){return!t.is_capturing()},Jt:n=>e.Jt(n),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Jt(t,e){return new Promise((n=>{var i=!1,r=o=>{i||(i=!0,clearTimeout(s),n(o))},s=setTimeout((()=>r({kind:"retry-later",error:new Error("metrics request timed out")})),9e4);this._instance._send_request(k({method:"POST",url:this.Su(),data:t,compression:"best-available",batchKey:"metrics"},e&&{transport:e},{fireCallbackOnDrop:!0,callback(o){var a=o.statusCode;if(a>=200&&300>a)r({kind:"ok"});else if(a===413)r({kind:"too-large"});else if(a!==0&&a!==429&&500>a)r({kind:"fatal",error:new Error("metrics request failed with status "+a)});else{var l;r({kind:"retry-later",error:(l=o.error)!==null&&l!==void 0?l:new Error("metrics request failed with status "+a)})}}}))}))}Su(){return this._instance.requestRouter.endpointFor("api","/i/v1/metrics")+"?token="+encodeURIComponent(this._instance.config.token)}}},Qm=k({},Cs,Um,Hm,Wm,qm,zm,Gm,Vm,Km,Ym,Jm,Zm,Xm);Je.__defaultExtensionClasses=k({},Qm);(function(){ne.SDK_DIST_CHANNEL="npm";var t=Wi[Gn]=new Je;return(function(){function e(){e.done||(e.done=!0,Vf=!1,ie(Wi,(function(n){n._dom_loaded()})))}F!=null&&F.addEventListener?F.readyState==="complete"?e():ve(F,"DOMContentLoaded",e,{capture:!1}):w&&A.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const ev=["a[href]","button:not([disabled])","input:not([disabled]):not([type='hidden'])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(",");let ht=null,ka=null,Kf="";const Ca=new Map;function Yf(t){return[...t.querySelectorAll(ev)].filter(e=>!e.hidden&&e.getAttribute("aria-hidden")!=="true"&&e.getClientRects().length>0)}function tv(t){for(const e of document.body.children)e===t||e.tagName==="SCRIPT"||(Ca.set(e,{inert:e.inert,ariaHidden:e.getAttribute("aria-hidden")}),e.inert=!0,e.setAttribute("aria-hidden","true"))}function nv(){for(const[t,e]of Ca)t.inert=e.inert,e.ariaHidden===null?t.removeAttribute("aria-hidden"):t.setAttribute("aria-hidden",e.ariaHidden);Ca.clear()}function Jf(t){return t?.dataset.modalDismissible!=="false"&&t?.getAttribute("aria-busy")!=="true"}function He(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n)return!1;ht&&ht!==n&&We(ht,{restoreFocus:!1,force:!0}),ka=e.trigger||document.activeElement,ht=n,Kf=document.body.style.overflow,tv(n),document.body.style.overflow="hidden",n.classList.add("open"),n.setAttribute("aria-hidden","false");const i=n.querySelector(".modal-content");i&&(i.style.transform="scale(1) translateY(0)");const r=()=>{if(ht!==n)return;((e.initialFocus?n.querySelector(e.initialFocus):n.querySelector("[data-modal-initial-focus]"))||Yf(n)[0]||n.querySelector(".modal-content")||n).focus({preventScroll:!0})};return requestAnimationFrame(r),setTimeout(r,260),!0}function We(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n||!e.force&&!Jf(n))return!1;n.classList.remove("open"),n.setAttribute("aria-hidden","true"),nv(),document.body.style.overflow=Kf,ht=null;const i=ka;return ka=null,e.restoreFocus!==!1&&i?.isConnected&&i.focus({preventScroll:!0}),!0}function Eu(t,e,n="Operation in progress"){const i=typeof t=="string"?document.getElementById(t):t;i&&(i.dataset.modalDismissible=e?"false":"true",i.setAttribute("aria-busy",String(!!e)),e?i.setAttribute("aria-label",n):i.removeAttribute("aria-label"))}function iv(t){if(!Jf(t))return;const e=t.dataset.modalCloseHandler;e&&typeof window[e]=="function"?window[e]():We(t)}document.addEventListener("keydown",t=>{if(!ht)return;if(t.key==="Escape"){t.preventDefault(),t.stopImmediatePropagation(),iv(ht);return}if(t.key!=="Tab"){t.stopPropagation();return}const e=Yf(ht);if(!e.length){t.preventDefault(),(ht.querySelector(".modal-content")||ht).focus();return}const n=e[0],i=e[e.length-1];t.shiftKey&&document.activeElement===n?(t.preventDefault(),i.focus()):!t.shiftKey&&document.activeElement===i&&(t.preventDefault(),n.focus())},!0);function rv(){document.querySelectorAll(".modal-overlay").forEach(t=>{t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-hidden",t.classList.contains("open")?"false":"true");const e=t.querySelector(".modal-content");e&&!e.hasAttribute("tabindex")&&(e.tabIndex=-1);const n=t.querySelector("h1, h2, h3");n&&(n.id||(n.id=`${t.id}-title`),t.setAttribute("aria-labelledby",n.id)),t.querySelectorAll(".modal-close").forEach(i=>{i.getAttribute("aria-label")||i.setAttribute("aria-label","Close dialog")})})}const gl=Object.freeze({free:"Free",professional:"Pro",power:"Power"}),sv=Object.freeze({free:2,professional:50,power:2e3}),ov="(contact us)",av=Object.freeze({free:Object.freeze(["2 generations/month","Gemini model only","Code Review"]),professional:Object.freeze(["50 generations/month","All models","Code Regeneration","Code Review"]),power:Object.freeze(["2000 generations/month","All models","Code Regeneration","Bring your own key (BYOK)","Code Review","All models + early access",`API & MCP access ${ov}`])}),Zf="CodeFile",Xf="GeneratedCode",lv={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function ln(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Aa(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function cv(t={},e=0){const n=Aa(t.artifactType||t.type||Zf),i=Aa(t.artifactName||t.name||t.fileName||`${Xf}-${e+1}`);return`${n||"artifact"}-${i||e+1}`}function Qf(t={},e=0){const n=ln(t),i=n.artifactType||n.type||Zf,r=n.artifactName||n.name||Xf;let s=n.fileName||r;return s.endsWith(".dart")||(s+=".dart"),{id:Aa(n.id)||cv({...n,artifactType:i,artifactName:r,fileName:s},e),artifactType:i,artifactName:r,fileName:s,deployPath:n.deployPath||"",description:n.description||"",code:n.code||n.content||"",dependencies:eh(n.dependencies),imports:Array.isArray(n.imports)?n.imports:[],publicApi:Array.isArray(n.publicApi)?n.publicApi:[],relationships:th(n.relationships),deployStatus:n.deployStatus||"pending",review:n.review||null,metadata:ln(n.metadata),codeType:n.codeType||lv[i]||"O"}}function eh(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const n=ln(e),i=n.name||n.package;return i?{name:i,version:n.version||null,versionRequired:!!(n.versionRequired||n.required),inferred:!!n.inferred,...n.reason?{reason:n.reason}:{}}:null}).filter(Boolean):Object.entries(ln(t)).map(([e,n])=>({name:e,version:n||null,inferred:!1})):[]}function th(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const n=ln(e);return!n.from&&!n.to?null:{from:n.from||null,to:n.to||null,type:n.type||"uses",description:n.description||""}}).filter(Boolean):[]}function Pa(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;try{return JSON.parse(e)}catch{const n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(!n)return null;try{return JSON.parse(n[1].trim())}catch{return null}}}function Qi(t,e={}){const n=[],i=typeof t=="string"?Pa(t):t,s=ln(i||{});!i&&typeof t=="string"&&n.push("Structured bundle parse failed; using legacy single-artifact fallback.");const o=Array.isArray(s.artifacts)?s.artifacts:[{artifactType:s.artifactType||e.artifactType,artifactName:s.artifactName||e.artifactName,fileName:s.fileName||e.fileName,description:s.description,code:s.code||e.code||(typeof t=="string"?t:""),dependencies:s.dependencies||e.dependencies,relationships:s.relationships||e.relationships}];o.forEach((d,f)=>{!d?.artifactType&&!d?.type&&n.push(`Artifact ${f+1} has no artifactType; it will deploy as a standalone code file under lib/custom_code/ root.`)});const a=o.map((d,f)=>Qf(d,f)),l=new Map(o.map((d,f)=>[ln(d).id,a[f]?.id]).filter(([d,f])=>d&&f)),u=d=>l.get(d)||d,c=th(s.relationships||e.relationships).map(d=>({...d,from:d.from?u(d.from):d.from,to:d.to?u(d.to):d.to}));return{schemaVersion:s.schemaVersion||e.schemaVersion||null,id:s.id||e.id||"bundle-current",title:s.title||s.name||e.title||"Generated artifact bundle",description:s.description||e.description||"",artifacts:a,dependencies:eh(s.dependencies||e.dependencies),relationships:c,deployOrder:Array.isArray(s.deployOrder)?s.deployOrder.map(u):a.map(d=>d.id),warnings:[...n,...Array.isArray(s.warnings)?s.warnings:[]],metadata:ln(s.metadata)}}function oi(t){return Qi(t).artifacts[0]||Qf()}function Zt(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function ai(t){return JSON.stringify(t,null,2)}function uv(t){return ai({task:"architect",userRequest:String(t??"")})}function dv(t){const e=Zt(t);return e&&typeof e=="object"&&typeof e.task=="string"?ai(e):ai({task:"generate_bundle",bundleSpec:e})}function fv(t){return ai({task:"review_bundle",generatedBundle:Zt(t),outputRequirements:{bundleReview:["status","score","summary","manualActions","findings"],scoreRange:[0,100],eachArtifact:["id","review.status","review.findings"],manualActions:{definition:"Setup the developer must perform by hand in the FlutterFlow editor that FlutterFlow will NOT do for them.",exclude:["creating the Custom Action, Widget or Code File itself - deploying the code creates it","declaring parameters or return values FlutterFlow derives from the function signature","anything that resolves as a side effect of using the action or widget in the editor","generic advice such as testing, reviewing or rebuilding the app"],preferEmpty:"Return an empty array when nothing qualifies - an empty list is the expected result for most bundles."}}})}function ml(t,e=null){const n={stage:t};return e!=null&&(n.bundle=Zt(e)),n}function hv({bundleSpec:t,artifactBundle:e,bundleReview:n,artifactId:i,userFeedback:r}){return ai({task:"regenerate_artifact",artifactId:i,bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(r)})}function nh({bundleSpec:t,artifactBundle:e,bundleReview:n,userFeedback:i}){return ai({task:"regenerate_bundle",bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(i??"")})}const Su={csam:"child-safety content",dangerous:"dangerous content",harassment:"harassment",hate_speech:"hate speech",maliciousUrls:"a potentially malicious URL",malicious_uris:"a potentially malicious URL",pi_and_jailbreak:"prompt-injection or jailbreak instructions",promptInjection:"prompt-injection or jailbreak instructions",rai:"restricted content",sdp:"sensitive personal data",sexually_explicit:"sexually explicit content",virus_scan:"potentially malicious file content"},pv=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function et(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function gv(t){return et(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||et(t.filterSummary)||et(t.filterResults):!1}function ih(t,e=0){if(!et(t)||e>3)return null;if(gv(t))return t;for(const n of pv){const i=t[n];if(et(i)){const r=ih(i,e+1);if(r)return r}}return null}function ds(t){return Array.isArray(t)?t.some(ds):et(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(ds):!1}function Fa(t){return Array.isArray(t)?t.some(Fa):et(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(Fa):!1}function rh(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function mv(t,e){if(et(t))for(const[n,i]of Object.entries(t)){if(!et(i))continue;const r=et(i.categories)?i.categories:{},s=Object.entries(r).filter(([,o])=>et(o)&&o.matched===!0).map(([o])=>o);s.length>0?s.forEach(o=>e.add(o)):i.matched===!0&&e.add(rh(n))}}function vv(t,e){if(!t)return;const n=Array.isArray(t)?t.flatMap(i=>et(i)?Object.entries(i):[]):Object.entries(t);for(const[i,r]of n){if(!ds(r))continue;const s=rh(i),o=r?.raiFilterResult?.raiFilterTypeResults||(s==="rai"?r?.raiFilterTypeResults:null),a=et(o)?Object.entries(o).filter(([,l])=>ds(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(s)}}function _v(t){return Su[t]?Su[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function xu(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 yv(t){const e=ih(t);if(!e)return null;const n=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);mv(e.filterSummary,n),vv(e.filterResults,n);const i=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||n.size>0,r=e.invocationResult||null,s=Fa(e.filterSummary||e.filterResults);return!i&&!s&&!["PARTIAL","FAILURE"].includes(r)?null:{kind:i?"blocked":"unavailable",invocationResult:r,matchedFilters:[...n]}}function wv(t,e){const n=yv(t);if(!n)return null;const i=[...new Set(n.matchedFilters.map(_v))],r=n.kind==="blocked",s=new Error(r?`Safety screening blocked this pipeline step for ${xu(i)}.`:"Safety screening could not be completed. Please try again.");return s.name="ModelArmorError",s.code=r?"MODEL_ARMOR_BLOCKED":"MODEL_ARMOR_UNAVAILABLE",s.isModelArmor=!0,s.pipelineStep=e,s.userTitle=r?"Request blocked for safety":"Safety check unavailable",s.userMessage=r?`The safety check detected ${xu(i)}. Edit your request to remove or rephrase the flagged content, then run the pipeline again.`:"The safety service did not finish all of its checks. Please wait a moment and run the pipeline again.",s.retryExplanation=r?"Trying another model would not change this safety decision.":"A fallback model was not attempted because safety screening must complete first.",s.matchedFilters=n.matchedFilters,s}function bv(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function Iu(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,n=[];for(const i of bv(t).split(` -`)){if(!/^[A-Za-z_$]/.test(i)||e.test(i))continue;const r=i.match(/^[\w$<>,?\s[\]]+?\s([a-zA-Z_$][\w$]*)\s*\(/);r&&n.push(r[1])}return n}function vl(t,e){const n=t.replace(/\.dart$/,"");if(e==="W")return n.replace(/(^|_)(\w)/g,(i,r,s)=>s.toUpperCase());if(e==="A"){const i=n.replace(/(^|_)(\w)/g,(r,s,o)=>o.toUpperCase());return i.charAt(0).toLowerCase()+i.slice(1)}return e==="F"?"CustomFunctions":e==="C"?t.endsWith(".dart")?t:`${t}.dart`:n}async function ku(t){const e=new TextEncoder().encode(String(t||"")),n=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n),i=>i.toString(16).padStart(2,"0")).join("")}async function Ev(t,e=new Map){const n={},i=new Set;for(const[o,a]of t.entries()){if(a.type==="D"||a.type==="O")continue;const l=vl(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await ku(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await ku(c)),n[o]=u,a.type==="F"){const d=Iu(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(h=>i.add(h))}}const r=new Set(Iu(e.get("lib/flutter_flow/custom_functions.dart")||"")),s={functions_to_rename:[],functions_to_delete:[],functions_to_add:Array.from(i).filter(o=>!r.has(o))};return{fileMapContents:JSON.stringify(n),functionsMapContents:JSON.stringify(s)}}const Sv=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),Cu={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},xv=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),Iv=["Struct","Record"],kv=[{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=>jo(t).some(e=>/\brequired\s+this\.\w+/.test(e)),pos:"class W extends StatefulWidget { const W({required this.value}); final double value; }",neg:`class _P { const _P({required this.t}); final double t; } +(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const s of r)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function n(r){const s={};return r.integrity&&(s.integrity=r.integrity),r.referrerPolicy&&(s.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?s.credentials="include":r.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function i(r){if(r.ep)return;r.ep=!0;const s=n(r);fetch(r.href,s)}})();var w=typeof window<"u"?window:void 0,Le=typeof globalThis<"u"?globalThis:w,Ue=Le?.navigator,P=Le?.document,me=Le?.location,Za=Le?.fetch,qo=Le!=null&&Le.XMLHttpRequest&&"withCredentials"in new Le.XMLHttpRequest?Le.XMLHttpRequest:void 0,uc=Le?.AbortController,Tp=Le?.CompressionStream,Ve=Ue?.userAgent;function cd(){return!(!w||w.navigator.onLine===!1)}var vi=typeof globalThis<"u"?globalThis:w;vi&&typeof self>"u"&&(vi.self=vi),vi&&typeof File>"u"&&(vi.File=function(){});var B=w??{},ne={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function dc(t,e,n,i,r,s,o){try{var a=t[s](o),l=a.value}catch(u){return void n(u)}a.done?e(l):Promise.resolve(l).then(i,r)}function se(t){return function(){var e=this,n=arguments;return new Promise((function(i,r){var s=t.apply(e,n);function o(l){dc(s,i,r,o,a,"next",l)}function a(l){dc(s,i,r,o,a,"throw",l)}o(void 0)}))}}function I(){return I=Object.assign?Object.assign.bind():function(t){for(var e=1;arguments.length>e;e++){var n=arguments[e];for(var i in n)({}).hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},I.apply(null,arguments)}function ud(t,e){if(t==null)return{};var n={};for(var i in t)if({}.hasOwnProperty.call(t,i)){if(e.indexOf(i)!==-1)continue;n[i]=t[i]}return n}var fc=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function hc(t){return typeof t=="string"||t}function pc(t){return typeof t=="string"?t:void 0}var _i,$p=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],Ut=(function(t){return t.AnonymousId="anonymous_id",t.DistinctId="distinct_id",t.Props="props",t.EnablePersonProcessing="enable_person_processing",t.PersonMode="person_mode",t.FeatureFlagDetails="feature_flag_details",t.FeatureFlags="feature_flags",t.FeatureFlagPayloads="feature_flag_payloads",t.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",t.BootstrapFeatureFlags="bootstrap_feature_flags",t.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",t.OverrideFeatureFlags="override_feature_flags",t.Queue="queue",t.AiQueue="ai_queue",t.LogsQueue="logs_queue",t.OptedOut="opted_out",t.SessionId="session_id",t.SessionStartTimestamp="session_start_timestamp",t.SessionLastTimestamp="session_timestamp",t.PersonProperties="person_properties",t.GroupProperties="group_properties",t.InstalledAppBuild="installed_app_build",t.InstalledAppVersion="installed_app_version",t.SessionReplay="session_replay",t.PushRegistered="push_registered",t.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",t.SurveyLastSeenDate="survey_last_seen_date",t.SurveysSeen="surveys_seen",t.Surveys="surveys",t.RemoteConfig="remote_config",t.FlagsEndpointWasHit="flags_endpoint_was_hit",t.DeviceId="device_id",t})({}),gc=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),Mp=["$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"],Lp=["token"],dd="NativeGzipValidationError",zo=t=>t.length>=2&&t[0]===31&&t[1]===139,mc=(t,e)=>t===gc.GZipJS||e===gc.GZipJS||e==="gzip",vc=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",pr=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=dd,e},Np=(function(){var t=se((function*(e,n){18>e.size&&pr("too-short");var i=new Uint8Array(yield e.slice(0,10).arrayBuffer());zo(i)&&i[2]===8||pr("invalid-header");var r=new DataView(yield e.slice(e.size-8).arrayBuffer());r.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(_i)return _i;_i=[];for(var c=0;256>c;c++){for(var d=c,f=0;8>f;f++)d=1&d?3988292384^d>>>1:d>>>1;_i[c]=d>>>0}return _i})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(n)&&pr("invalid-crc");var s=n.length>>>0;r.getUint32(4,!0)!==s&&pr("invalid-size")}));return function(e,n){return t.apply(this,arguments)}})();function Vo(){return Vo=se((function*(t,e,n){e===void 0&&(e=!0);try{var i=new TextEncoder().encode(t),r=new globalThis.CompressionStream("gzip"),s=r.writable.getWriter(),o=s.write(i).then((()=>s.close())).catch((function(){var u=se((function*(c){try{yield s.abort(c)}catch{}throw c}));return function(c){return u.apply(this,arguments)}})()),a=new Response(r.readable).blob(),l=(yield Promise.all([a,o]))[0];return yield Np(l,i),l}catch(u){if(n!=null&&n.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),Vo.apply(this,arguments)}var Op=["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"],_c=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var n=t.toLowerCase();return Op.concat(e).some((i=>{var r=i.toLowerCase();return n.indexOf(r)!==-1}))};function j(t,e){return t.indexOf(e)!==-1}var xs=function(t){return t.trim()},Go=function(t){return t.replace(/^\$/,"")};function fd(t){var e,n=[];return(e=JSON.stringify(t,(function(i,r){if(typeof r=="bigint")return r.toString();if(typeof r!="function"&&typeof r!="symbol"){if(r instanceof Error)return{name:r.name,message:r.message,stack:r.stack};if(r&&typeof r=="object"){for(;n.length>0&&n[n.length-1]!==this;)n.pop();if(n.includes(r))return"[Circular]";n.push(r)}return r}})))!==null&&e!==void 0?e:"null"}var hd=Object.prototype,pd=hd.hasOwnProperty,Is=hd.toString,U=Array.isArray||function(t){return Is.call(t)==="[object Array]"},De=t=>typeof t=="function",he=t=>t===Object(t)&&!U(t),Kt=t=>{if(he(t)){for(var e in t)if(pd.call(t,e))return!1;return!0}return!1},C=t=>t===void 0,X=t=>Is.call(t)=="[object String]",Ko=t=>X(t)&&t.trim().length===0,Ke=t=>t===null,H=t=>C(t)||Ke(t),ke=t=>Is.call(t)=="[object Number]"&&t==t,Dt=t=>ke(t)&&t>0,mt=t=>Is.call(t)==="[object Boolean]",Bp=t=>t instanceof FormData,Dp=t=>j(Mp,t),jp=t=>j(Lp,t);function gd(t){return t===null||typeof t!="object"}function Hr(t,e){return{}.toString.call(t)==="[object "+e+"]"}function Xa(t){return typeof Event<"u"&&md(t,Event)}function md(t,e){try{return t instanceof e}catch{return!1}}var Up=[!0,"true",1,"1","yes"],uo=t=>j(Up,t),Hp=[!1,"false",0,"0","no"];function At(t,e,n,i,r){return e>n&&(i.warn("min cannot be greater than max."),e=n),ke(t)?t>n?(i.warn(" cannot be greater than max: "+n+". Using max value instead."),n):e>t?(i.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(i.warn(" must be a number. using max or fallback. max: "+n+", fallback: "+r),At(r||n,e,n,i))}class Wp{constructor(e){this.tt={},this.et=e.et,this.it=At(e.bucketSize,0,100,e.rt),this.nt=At(e.refillRate,0,this.it,e.rt),this.st=At(e.refillInterval,0,864e5,e.rt)}ot(e,n){var i=Math.floor((n-e.lastAccess)/this.st);i>0&&(e.tokens=Math.min(e.tokens+i*this.nt,this.it),e.lastAccess=e.lastAccess+i*this.st)}consumeRateLimit(e){var n,i=Date.now(),r=String(e),s=this.tt[r];return s?this.ot(s,i):this.tt[r]=s={tokens:this.it,lastAccess:i},s.tokens===0||(s.tokens--,s.tokens===0&&((n=this.et)==null||n.call(this,e)),s.tokens===0)}stop(){this.tt={}}}var it="Mobile",Wr="iOS",Yt="Android",ei="Tablet",vd=Yt+" "+ei,_d="iPad",yd="Apple",wd=yd+" Watch",Bi="Safari",ti="BlackBerry",bd="Samsung",Ed=bd+"Browser",Sd=bd+" Internet",Pn="Chrome",qp=Pn+" OS",xd=Pn+" "+Wr,Qa="Internet Explorer",Id=Qa+" "+it,el="Opera",zp=el+" Mini",tl="Edge",kd="Microsoft "+tl,Zn="Firefox",Cd=Zn+" "+Wr,Gi="Nintendo",Ki="PlayStation",Xn="Xbox",Ad=Yt+" "+it,Pd=it+" "+Bi,Pi="Windows",Yo=Pi+" Phone",yc="Nokia",Jo="Ouya",Fd="Generic",Vp=Fd+" "+it.toLowerCase(),Rd=Fd+" "+ei.toLowerCase(),Zo="Konqueror",Td="Oculus Browser",qr="Vivaldi",$d="Yandex",zr="Whale",Xo="DuckDuckGo",Md="Pale Moon",Vr="Waterfox",Di="Brave",Ld="Google Search App",we="(\\d+(\\.\\d+)?)",fo=new RegExp("Version/"+we),Gp=new RegExp(Xn,"i"),Kp=new RegExp(Ki+" \\w+","i"),Yp=new RegExp(Gi+" \\w+","i"),nl=new RegExp(ti+"|PlayBook|BB10","i"),Jp={"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"},Nd=function(t,e,n,i){e=e||"";var r=(function(s){return s!=null&&s.brave?Di:null})(n);return r||(i!=null&&i.detectGoogleSearchApp&&j(t,"GSA/")?Ld:j(t," OPR/")&&j(t,"Mini")?zp:j(t," OPR/")?el:nl.test(t)?ti:j(t,"IE"+it)||j(t,"WPDesktop")?Id:j(t,"OculusBrowser")?Td:j(t,Ed)?Sd:j(t,tl)||j(t,"Edg/")?kd:j(t,qr+"/")?qr:j(t,"YaBrowser/")?$d:j(t,zr+"/")?zr:j(t,Xo+"/")||j(t,"Ddg/")?Xo:j(t,"FBIOS")?"Facebook "+it:j(t,"UCWEB")||j(t,"UCBrowser")?"UC Browser":j(t,"CriOS")?xd:j(t,"CrMo")||j(t,Pn)?Pn:j(t,Yt)&&j(t,Bi)?Ad:j(t,"FxiOS")?Cd:j(t.toLowerCase(),Zo.toLowerCase())?Zo:j(t,Di+"/")?Di:((s,o)=>o&&j(o,yd)||(function(a){return j(a,Bi)&&!j(a,Pn)&&!j(a,Yt)})(s))(t,e)?j(t,it)?Pd:Bi:j(t,"PaleMoon/")?Md:j(t,Vr+"/")?Vr:j(t,Zn)?Zn:j(t,"MSIE")||j(t,"Trident/")?Qa:j(t,"Gecko")?Zn:"")},Zp={[Id]:[new RegExp("rv:"+we)],[kd]:[new RegExp(tl+"?\\/"+we)],[Pn]:[new RegExp("("+Pn+"|CrMo)\\/"+we)],[xd]:[new RegExp("CriOS\\/"+we)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+we)],[Bi]:[fo],[Pd]:[fo],[el]:[new RegExp("(Opera|OPR)\\/"+we)],[Zn]:[new RegExp(Zn+"\\/"+we)],[Cd]:[new RegExp("FxiOS\\/"+we)],[Zo]:[new RegExp("Konqueror[:/]?"+we,"i")],[ti]:[new RegExp(ti+" "+we),fo],[Ad]:[new RegExp("android\\s"+we,"i")],[Sd]:[new RegExp(Ed+"\\/"+we)],[Td]:[new RegExp("OculusBrowser\\/"+we)],[qr]:[new RegExp(qr+"\\/"+we)],[$d]:[new RegExp("YaBrowser\\/"+we)],[zr]:[new RegExp(zr+"\\/"+we)],[Di]:[new RegExp(Di+"\\/"+we)],[Xo]:[new RegExp("(DuckDuckGo|Ddg)\\/"+we)],[Md]:[new RegExp("PaleMoon\\/"+we)],[Vr]:[new RegExp(Vr+"\\/"+we)],[Ld]:[new RegExp("GSA\\/"+we)],[Qa]:[new RegExp("(rv:|MSIE )"+we)],Mozilla:[new RegExp("rv:"+we)]},Xp=function(t,e,n,i){var r=Nd(t,e,n,i),s=Zp[r];if(C(s))return null;for(var o=0;s.length>o;o++){var a=t.match(s[o]);if(a)return parseFloat(a[a.length-2])}return null},wc=[[new RegExp(Xn+"; "+Xn+" (.*?)[);]","i"),t=>[Xn,t&&t[1]||""]],[new RegExp(Gi,"i"),[Gi,""]],[new RegExp(Ki,"i"),[Ki,""]],[nl,[ti,""]],[new RegExp(Pi,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Yo,""];if(new RegExp(it).test(e)&&!/IEMobile\b/.test(e))return[Pi+" "+it,""];var n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){var i=Jp[n[1]]||"";return/arm/i.test(e)&&(i="RT"),[Pi,i]}return[Pi,""]}],[/((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=C(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+Yt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Yt+")","i"),t=>t&&t[2]?[Yt,[t[2],t[3],t[4]||"0"].join(".")]:[Yt,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{var e=["Mac OS X",""];return t&&t[1]&&(e[1]=[t[1],t[2],t[3]||"0"].join(".")),e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[qp,""]],[/Linux|debian/i,["Linux",""]]],bc=function(t){return Yp.test(t)?Gi:Kp.test(t)?Ki:Gp.test(t)?Xn:new RegExp(Jo,"i").test(t)?Jo:new RegExp("("+Yo+"|WPDesktop)","i").test(t)?Yo:/iPad/.test(t)?_d:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?wd:nl.test(t)?ti:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(yc,"i").test(t)?yc:/(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(it).test(t)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(t)||/pixel[\daxl ]{1,6}/i.test(t)&&!/pixel c/i.test(t)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(t)||/lmy47v/i.test(t)&&!/QTAQZ3/i.test(t)?Yt:vd:new RegExp("(pda|"+it+")","i").test(t)?Vp:new RegExp(ei,"i").test(t)&&!new RegExp(ei+" pc","i").test(t)?Rd:""},Qp=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ec(t,e){return typeof(n=t)=="string"&&Qp.test(n)?t:e();var n}function fn(t){return t&&t.split("#")[0]}function il(t,e){var n=setTimeout(t,e);return n?.unref&&n?.unref(),n}function Sc(t,e,n){return Od.apply(this,arguments)}function Od(){return(Od=se((function*(t,e,n){var i;try{return yield Promise.race([t,new Promise(((r,s)=>{i=il((()=>{try{n?.(),r()}catch(o){s(o)}}),e)}))])}finally{clearTimeout(i)}}))).apply(this,arguments)}var eg=t=>t instanceof Error,Bd={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}},tg=Bd.info;function Dd(t){if(mt(t))return{boolValue:t};if(typeof t=="number")return Number.isFinite(t)?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:{stringValue:String(t)};if(typeof t=="string")return{stringValue:t};if(U(t))return{arrayValue:{values:t.map((e=>Dd(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function Gr(t){var e=[];for(var n in t){var i=t[n];Ke(i)||C(i)||e.push({key:n,value:Dd(i)})}return e}function ng(t,e){var n=Bd[t.level||"info"]||tg,i=n.text,r=n.number,s=String(Date.now())+"000000",o={};e.distinctId&&(o.posthogDistinctId=e.distinctId),e.sessionId&&(o.sessionId=e.sessionId),e.windowId&&(o["window.id"]=e.windowId),H(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),H(e.lastActivityTimestamp)||(o.lastActivityTimestamp=String(e.lastActivityTimestamp)),e.currentUrl&&(o["url.full"]=e.currentUrl),e.screenName&&(o["screen.name"]=e.screenName),e.appState&&(o["app.state"]=e.appState),e.activeFeatureFlags&&e.activeFeatureFlags.length>0&&(o.feature_flags=e.activeFeatureFlags);var a=I({},o,t.attributes||{}),l={timeUnixNano:s,observedTimeUnixNano:s,severityNumber:r,severityText:i,body:{stringValue:t.body},attributes:Gr(a)};return t.trace_id&&(l.traceId=t.trace_id),t.span_id&&(l.spanId=t.span_id),C(t.trace_flags)||(l.flags=t.trace_flags),l}function jd(t,e,n){return I({},t.resourceAttributes,{"service.name":t.serviceName||"unknown_service"},t.environment&&{"deployment.environment":t.environment},t.serviceVersion&&{"service.version":t.serviceVersion},{"telemetry.sdk.name":e,"telemetry.sdk.version":n})}function Ud(t,e,n,i){return{resourceLogs:[{resource:{attributes:Gr(e)},scopeLogs:[{scope:{name:n,version:i},logRecords:t}]}]}}let ig=class{constructor(t,e,n,i,r,s,o){var a;s===void 0&&(s=()=>Promise.resolve()),this._instance=t,this.Ne=e,this.rt=n,this.ut=i,this.ht=r,this.dt=s,this.vt=o,this.ct=null,this.ft=0,this.yt=0,this.bt=0,this._t=0,this.wt=!1,this.kt=e.maxBufferSize,this.xt=Math.max((a=e.maxQueueSize)!==null&&a!==void 0?a:e.maxBufferSize,e.maxBufferSize),this.St=e.flushIntervalMs,this.Ct=e.maxBatchRecordsPerPost,this.Mt=e.rateCapWindowMs,this.Tt=e.maxLogsPerInterval}reset(){this.Et(),this.ct=null,this.bt=0,this._t=0,this.wt=!1,this.ft=0,this.yt=0,this.Ct=this.Ne.maxBatchRecordsPerPost}onReconnect(){this.yt=0,this.It()}captureLog(t){if(!this._instance.isDisabled&&!this._instance.optedOut&&t!=null&&t.body){var e=this.Pt(t);if(e!==null)if(e.body){if(this.Rt()){var n={record:ng(e,this.ut())};this.ht((()=>this.At(n)))}}else this.rt.info("Log was rejected in beforeSend function")}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Log was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for log:",o),null}return i}Rt(){if(this.Tt===void 0)return!0;var t=Date.now(),e=t-this.bt;return this.Mt>e&&e>=0||(this.bt=t,this._t=0,this.wt=!1),this.Tt>this._t?(this._t++,!0):(this.wt||(this.rt.warn("captureLog dropping logs: exceeded "+this.Tt+" logs per "+this.Mt+"ms"),this.wt=!0),!1)}flush(){var t=this;return se((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return se((function*(){var e;t.Et();var n=(e=t._instance.getPersistedProperty(Ut.LogsQueue))!==null&&e!==void 0?e:[];if(n.length!==0)for(var i=n.length,r=0;n.length>0&&i>r;){var s,o;t.ft=0;var a=Math.min(n.length,t.Ct),l=n.slice(0,a),u=Ud(l.map((d=>d.record)),t.Lt(),(s=t.vt)!==null&&s!==void 0?s:t._instance.getLibraryId(),t._instance.getLibraryVersion()),c=yield t._instance.Ot(u);if(c.kind==="too-large"&&l.length>1)t.Ct=Math.max(1,Math.floor(l.length/2)),t.rt.warn("Received 413 when sending logs batch of size "+l.length+", reducing batch size to "+t.Ct);else if(c.kind==="retry-later"||(c.kind==="too-large"?t.rt.warn("Dropping a single log record after 413 with batch size 1 — the record is larger than the server cap and cannot be split further."):c.kind==="ok"&&t.Ne.maxBatchRecordsPerPost>t.Ct&&(t.Ct=Math.min(t.Ne.maxBatchRecordsPerPost,t.Ct+1)),yield t.Dt(l.length),n=(o=t._instance.getPersistedProperty(Ut.LogsQueue))!==null&&o!==void 0?o:[],r+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return se((function*(){var n,i=Math.max(0,t-e.ft),r=(n=e._instance.getPersistedProperty(Ut.LogsQueue))!==null&&n!==void 0?n:[];e._instance.setPersistedProperty(Ut.LogsQueue,r.slice(i)),yield e.dt()}))()}Lt(){return jd(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var n=(e=this._instance.getPersistedProperty(Ut.LogsQueue))!==null&&e!==void 0?e:[];this.xt>n.length||(n.shift(),this.ft++,this.rt.info("Logs queue is full, dropping oldest record.")),n.push(t),this._instance.setPersistedProperty(Ut.LogsQueue,n),this.kt>n.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=il((()=>{this.Nt=void 0,this.It()}),t))}qt(){var t=Math.min(Math.max(0,this.yt-1),6);return this.St*Math.pow(2,t)}jt(){var t=this._instance.getPersistedProperty(Ut.LogsQueue);return!!t&&t.length>0}shutdown(t){var e=this;return se((function*(){e.Et();var n=e.flush().catch((()=>{}));t!==void 0?yield Sc(n,t):yield n}))()}flushWithTimeout(t){var e=this;return se((function*(){var n=e.flush();yield Sc(n,t,(()=>{n.catch((()=>{}))}))}))()}It(){this.flush().then((()=>{this.yt=0}),(t=>{this.yt++,this.rt.error("PostHog logs flush failed:",t)})).finally((()=>{!this._instance.isDisabled&&this.jt()&&this.$t(this.qt())}))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}};var ho=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function xc(t){return String(t)+"000000"}function Ic(t,e,n,i){var r="";return i&&(r=Object.keys(i).sort().map((s=>JSON.stringify(s)+":"+JSON.stringify(i[s]))).join(",")),t+"\0"+e+"\0"+(n??"")+"\0"+r}let rg=class{constructor(t,e,n){this._instance=t,this.Ne=e,this.rt=n,this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Wt=0}count(t,e,n){e===void 0&&(e=1),this.Vt({name:t,type:"count",value:e,unit:n?.unit,attributes:n?.attributes})}gauge(t,e,n){this.Vt({name:t,type:"gauge",value:e,unit:n?.unit,attributes:n?.attributes})}histogram(t,e,n){this.Vt({name:t,type:"histogram",value:e,unit:n?.unit,attributes:n?.attributes})}flush(){var t=this,e=this.ct,n=(function(){var r=se((function*(){e&&(yield e.catch((()=>{}))),yield t.Zt()}));return function(){return r.apply(this,arguments)}})(),i=n().finally((()=>{this.ct===i&&(this.ct=null)}));return this.ct=i,i}drainWindow(){if(this.Bt.size===0)return null;var t=this.Bt;return this.Bt=new Map,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Gt(t)}reset(){this.Wt++,this.Et(),this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set}Vt(t){if(!this._instance.isDisabled&&!this._instance.optedOut){var e=this.Pt(t);if(e!==null)if(e.name&&typeof e.name=="string")if(typeof e.value=="number"&&Number.isFinite(e.value))if(e.type==="count"&&0>e.value)this.rt.warn("Dropping count '"+e.name+"': counters are monotonic, value must be >= 0");else{var n,i;try{n=e.attributes?I({},e.attributes):void 0,i=Ic(e.type,e.name,e.unit,n)}catch(o){return void this.rt.warn("Dropping metric '"+e.name+"': attributes could not be serialized",o)}var r=this.Bt.get(i);if(!r){if(!this.Qt())return;r={name:e.name,type:e.type,unit:e.unit,attributes:n,windowStartMs:Date.now()},this.Bt.set(i,r)}var s=this.Ut.get(e.name);s===void 0?this.Ut.set(e.name,e.type):s===e.type||this.zt.has(e.name)||(this.zt.add(e.name),this.rt.warn("Metric name '"+e.name+"' is already used as a "+s+"; recording it as a "+e.type+" too will blend both series in charts. Use a distinct name.")),this.Kt(r,e.value),this.$t()}else this.rt.warn("Dropping metric '"+e.name+"': value must be a finite number");else this.rt.warn("Dropping metric with empty name")}}Qt(){return this.Ne.maxSeriesPerFlush>this.Bt.size||(this.Ht||(this.Ht=!0,this.rt.warn("Metric series cap reached ("+this.Ne.maxSeriesPerFlush+" per flush window); dropping new series until the next flush. Reduce attribute cardinality.")),!1)}Kt(t,e){var n;switch(t.type){case"count":t.total=((n=t.total)!==null&&n!==void 0?n:0)+e;break;case"gauge":t.last=e;break;case"histogram":t.hist||(t.hist={count:0,sum:0,min:e,max:e,bucketCounts:new Array(ho.length+1).fill(0)});var i=t.hist;i.count+=1,i.sum+=e,i.min=Math.min(i.min,e),i.max=Math.max(i.max,e),i.bucketCounts[(function(r,s){for(var o=0;s.length>o;o++)if(s[o]>=r)return o;return s.length})(e,ho)]+=1}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Metric was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for metric:",o),null}return i}$t(){this.Nt||(this.Nt=il((()=>{this.Nt=void 0,this.flush().catch((t=>{this.rt.error("Metrics flush failed:",t)}))}),this.Ne.flushIntervalMs))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}Zt(){var t=this;return se((function*(){if(t.Bt.size!==0){var e=t.Bt;t.Bt=new Map,t.Ht=!1,t.Ut=new Map,t.zt=new Set;var n=t.Wt,i=yield t._instance.Jt(t.Gt(e));if(n===t.Wt)switch(i.kind){case"ok":return;case"retry-later":return t.Yt(e),void t.$t();case"too-large":return void t.rt.warn("Metrics batch exceeded the server size limit and was dropped");case"fatal":return void t.rt.error("Failed to send metrics batch:",i.error)}}}))()}Gt(t){return e=this.Xt(t),n=(function(s,o,a){return I({},s.resourceAttributes,{"service.name":s.serviceName||"unknown_service"},s.environment&&{"deployment.environment":s.environment},s.serviceVersion&&{"service.version":s.serviceVersion},{"telemetry.sdk.name":o,"telemetry.sdk.version":a})})(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion()),i=this._instance.getLibraryId(),r=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:Gr(n)},scopeMetrics:[{scope:{name:i,version:r},metrics:e}]}]};var e,n,i,r}Xt(t){var e=xc(Date.now()),n=new Map;for(var i of t.values()){var r,s=Ic(i.type,i.name,i.unit,void 0),o=n.get(s);o||(o=I({name:i.name},i.unit&&{unit:i.unit}),i.type==="count"?o.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:i.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:1,dataPoints:[]},n.set(s,o));var a=Gr((r=i.attributes)!==null&&r!==void 0?r:{}),l=xc(i.windowStartMs);if(i.type==="count"){var u,c={attributes:a,startTimeUnixNano:l,timeUnixNano:e,asDouble:(u=i.total)!==null&&u!==void 0?u:0};o.sum.dataPoints.push(c)}else if(i.type==="gauge"){var d,f={attributes:a,timeUnixNano:e,asDouble:(d=i.last)!==null&&d!==void 0?d:0};o.gauge.dataPoints.push(f)}else i.hist&&o.histogram.dataPoints.push({attributes:a,startTimeUnixNano:l,timeUnixNano:e,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:ho})}return Array.from(n.values())}Yt(t){var e,n;for(var i of t){var r=i[0],s=i[1],o=this.Bt.get(r);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,s.windowStartMs),o.type){case"count":o.total=((e=o.total)!==null&&e!==void 0?e:0)+((n=s.total)!==null&&n!==void 0?n:0);break;case"gauge":break;case"histogram":if(s.hist)if(o.hist){o.hist.count+=s.hist.count,o.hist.sum+=s.hist.sum,o.hist.min=Math.min(o.hist.min,s.hist.min),o.hist.max=Math.max(o.hist.max,s.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=s.hist.bucketCounts[a]}else o.hist=s.hist}else this.Qt()&&this.Bt.set(r,s)}}};var gr,kc,po;function sg(t){var e=globalThis._posthogChunkIds;if(e){var n=Object.keys(e);return po&&n.length===kc||(kc=n.length,po=n.reduce(((i,r)=>{gr||(gr={});var s=gr[r];if(s)i[s[0]]=s[1];else for(var o=t(r),a=o.length-1;a>=0;a--){var l=o[a],u=l?.filename,c=e[r];if(u&&c){i[u]=c,gr[r]=[u,c];break}}return i}),{})),po}}class og{constructor(e,n,i){i===void 0&&(i=[]),this.coercers=e,this.stackParser=n,this.modifiers=i}buildFromUnknown(e,n){n===void 0&&(n={});var i=n&&n.mechanism||{handled:!0,type:"generic"},r=this.buildCoercingContext(i,n,0).apply(e),s=this.buildParsingContext(n),o=this.parseStacktrace(r,s);return{$exception_list:this.convertToExceptionList(o,i),$exception_level:"error"}}modifyFrames(e){var n=this;return se((function*(){for(var i of e)i.stacktrace&&i.stacktrace.frames&&U(i.stacktrace.frames)&&(i.stacktrace.frames=yield n.applyModifiers(i.stacktrace.frames));return e}))()}coerceFallback(e){var n;return{type:"Error",value:"Unknown error",stack:(n=e.syntheticException)==null?void 0:n.stack,synthetic:!0}}parseStacktrace(e,n){var i,r;return e.cause!=null&&(i=this.parseStacktrace(e.cause,n)),e.stack!=""&&e.stack!=null&&(r=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?n.skipFirstLines:0),n.chunkIdMap)),I({},e,{cause:i,stack:r})}applyChunkIds(e,n){return e.map((i=>(i.filename&&n&&(i.chunk_id=n[i.filename]),i)))}applyCoercers(e,n){for(var i of this.coercers)if(i.match(e))return i.coerce(e,n);return this.coerceFallback(n)}applyModifiers(e){var n=this;return se((function*(){var i=e;for(var r of n.modifiers)i=yield r(i);return i}))()}convertToExceptionList(e,n){var i,r,s,o={type:e.type,value:e.value,mechanism:{type:(i=n.type)!==null&&i!==void 0?i:"generic",handled:(r=n.handled)===null||r===void 0||r,synthetic:(s=e.synthetic)!==null&&s!==void 0&&s}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,I({},n,{handled:!0}))),a}buildParsingContext(e){var n;return{chunkIdMap:sg(this.stackParser),skipFirstLines:(n=e.skipFirstLines)!==null&&n!==void 0?n:1}}buildCoercingContext(e,n,i){i===void 0&&(i=0);var r=(s,o)=>{if(4>=o){var a=this.buildCoercingContext(e,n,o);return this.applyCoercers(s,a)}};return I({},n,{syntheticException:i==0?n.syntheticException:void 0,mechanism:e,apply:s=>r(s,i),next:s=>r(s,i+1)})}}var ni="?";function Qo(t,e,n,i,r){var s={platform:t,filename:e,function:n===""?ni:n,in_app:!0};return C(i)||(s.lineno=i),C(r)||(s.colno=r),s}var Hd=(t,e)=>{var n=t.indexOf("safari-extension")!==-1,i=t.indexOf("safari-web-extension")!==-1;return n||i?[t.indexOf("@")!==-1?t.split("@")[0]:ni,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},ag=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,lg=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,cg=/\((\S*)(?::(\d+))(?::(\d+))\)/,ug=(t,e)=>{var n=ag.exec(t);if(n)return Qo(e,n[1],ni,+n[2],+n[3]);var i=lg.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var r=cg.exec(i[2]);r&&(i[2]=r[1],i[3]=r[2],i[4]=r[3])}var s=Hd(i[1]||ni,i[2]);return Qo(e,s[1],s[0],i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},dg=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,fg=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,hg=(t,e)=>{var n=dg.exec(t);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){var i=fg.exec(n[3]);i&&(n[1]=n[1]||"eval",n[3]=i[1],n[4]=i[2],n[5]="")}var r=n[3],s=n[1]||ni,o=Hd(s,r);return Qo(e,r=o[1],s=o[0],n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},Cc=/\(error: (.*)\)/;class pg{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,n){var i=X(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:i?e.stack:void 0,cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var n=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?n+": "+e.message:n}isDOMException(e){return Hr(e,"DOMException")}isDOMError(e){return Hr(e,"DOMError")}}class gg{match(e){return(function(n){switch({}.toString.call(n)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return md(n,Error)}})(e)}coerce(e,n){return{type:this.getType(e),value:this.getMessage(e,n),stack:this.getStack(e),cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,n){var i=e.message;return String(i.error&&typeof i.error.message=="string"?i.error.message:i)}getStack(e){return e.stacktrace||e.stack||void 0}}class mg{constructor(){}match(e){return!!Hr(e,"ErrorEvent")&&(e.error!=null||this.fe(e))}coerce(e,n){var i;if(e.error!=null)return n.apply(e.error);var r=n.apply(e.message);return I({},r,{stack:(i=this.pe(e))!==null&&i!==void 0?i:r.stack,synthetic:!0})}fe(e){return X(e.message)&&e.message.length>0}pe(e){var n=e;if(X(n.filename)&&n.filename.length>0){var i,r,s=(i=n.lineno)!==null&&i!==void 0?i:0,o=(r=n.colno)!==null&&r!==void 0?r:0;return`Error + at `+n.filename+":"+s+":"+o}}}var vg=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class _g{match(e){return typeof e=="string"}coerce(e,n){var i,r=this.getInfos(e),s=r[0],o=r[1];return{type:s??"Error",value:o??e,stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}getInfos(e){var n="Error",i=e,r=e.match(vg);return r&&(n=r[1],i=r[2]),[n,i]}}var yg=["fatal","error","warning","log","info","debug"];function Wd(t,e){e===void 0&&(e=40);var n=Object.keys(t);if(n.sort(),!n.length)return"[object has no keys]";for(var i=n.length;i>0;i--){var r=n.slice(0,i).join(", ");if(e>=r.length)return i===n.length?r:r.length>e?r.slice(0,e)+"...":r}return""}class wg{match(e){return typeof e=="object"&&e!==null}coerce(e,n){var i,r,s=this.getErrorPropertyFromObject(e);return s?n.apply(s):{type:this.getType(e),value:this.getValue(e),stack:(i=this.getStack(e))!==null&&i!==void 0?i:(r=n.syntheticException)==null?void 0:r.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return Xa(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var n="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(n+=" with message: '"+e.message+"'"),n}if("message"in e&&typeof e.message=="string")return e.message;var i=this.getObjectClassName(e);return(i&&i!=="Object"?"'"+i+"'":"Object")+" captured as exception with keys: "+Wd(e)}isSeverityLevel(e){return X(e)&&!Ko(e)&&yg.indexOf(e)>=0}getStack(e){try{return X(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:X(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(var n in e)if({}.hasOwnProperty.call(e,n)){var i=e[n];if(eg(i))return i}}getObjectClassName(e){try{var n=Object.getPrototypeOf(e);return n?n.constructor.name:void 0}catch{return}}}class bg{match(e){return Xa(e)}coerce(e,n){var i,r=e.constructor.name;return{type:r,value:r+" captured as exception with keys: "+Wd(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class Eg{match(e){return gd(e)}coerce(e,n){var i;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class Sg{match(e){return Hr(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Xa(e))return!1;try{var n=e.detail;return n!=null&&typeof n=="object"&&"reason"in n}catch{return!1}}coerce(e,n){var i,r=this.getUnhandledRejectionReason(e);return gd(r)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(r),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}:n.apply(r)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}}var Kr="$message",Yr="$timestamp",xg=new Set([Kr,Yr]),go={enabled:!0,max_bytes:32768};function Jr(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:go.enabled,max_bytes:kg(t.max_bytes,go.max_bytes)}:I({},go)}class Ig{constructor(e){this.Ke=[],this.Je=0,this.Ne=Jr(e)}setConfig(e){this.Ne=Jr(e),this.Xe()}add(e){var n=(function(r){var s;try{s=fd(r)}catch{return}try{var o=JSON.parse(s);if(!he(o))return;var a=o,l=a[Kr],u=a[Yr];return!X(l)||l.trim().length===0||!X(u)&&!ke(u)?void 0:{step:a,json:s}}catch{return}})(e);if(n){var i=(function(r){if(typeof TextEncoder<"u")return new TextEncoder().encode(r).length;for(var s=encodeURIComponent(r),o=0,a=0;s.length>a;a++)s[a]==="%"?(o+=1,a+=2):o+=1;return o})(n.json);i>this.Ne.max_bytes||(this.Ke.push({step:n.step,bytes:i}),this.Je+=i,this.Xe())}}getAttachable(){return this.Ke.map((e=>e.step))}clear(){this.Ke=[],this.Je=0}size(){return this.Ke.length}Xe(){for(;this.Je>this.Ne.max_bytes&&this.Ke.length>0;){var e=this.Ke.shift();e&&(this.Je-=e.bytes)}}}function kg(t,e){if(!ke(t)||t===1/0||t===-1/0)return e;var n=Math.floor(t);return 0>n?e:n}var qd=function(t,e){var n=(e===void 0?{}:e).debugEnabled,i={k(r){if(w&&(ne.DEBUG||w.POSTHOG_DEBUG||n)&&!C(w.console)&&w.console){for(var s=("__rrweb_original__"in w.console[r])?w.console[r].__rrweb_original__:w.console[r],o=arguments.length,a=new Array(o>1?o-1:0),l=1;o>l;l++)a[l-1]=arguments[l];s(t,...a)}},debug(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("debug",...s)},info(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("log",...s)},warn(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("warn",...s)},error(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("error",...s)},critical(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];console.error(t,...s)},uninitializedWarning(r){i.error("You must initialize PostHog before calling "+r)},createLogger:(r,s)=>qd(t+" "+r,s)};return i},A=qd("[PostHog.js]"),pe=A.createLogger,Cg=pe("[ExternalScriptsLoader]"),mo=(t,e,n)=>{if(t.config.disable_external_dependency_loading)return Cg.warn(e+" was requested but loading of external scripts is disabled."),n("Loading of external scripts is disabled");var i=P?.querySelectorAll("script");if(i){for(var r,s=function(){if(i[o].src===e){var l=i[o];return l.__posthog_loading_callback_fired?{v:n()}:(l.addEventListener("load",(u=>{l.__posthog_loading_callback_fired=!0,n(void 0,u)})),l.onerror=u=>n(u),{v:void 0})}},o=0;i.length>o;o++)if(r=s())return r.v}var a=()=>{if(!P)return n("document not found");var l=P.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=d=>{l.__posthog_loading_callback_fired=!0,n(void 0,d)},l.onerror=d=>n(d),t.config.prepare_external_dependency_script&&(l=t.config.prepare_external_dependency_script(l)),!l)return n("prepare_external_dependency_script returned null");if(t.config.external_scripts_inject_target==="head")P.head.appendChild(l);else{var u,c=P.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):P.body.appendChild(l)}};P!=null&&P.body?a():P?.addEventListener("DOMContentLoaded",a)};B.__PosthogExtensions__=B.__PosthogExtensions__||{},B.__PosthogExtensions__.loadExternalDependency=(t,e,n)=>{if(e!=="remote-config"){var i;if(t.config.strict_script_versioning)i=t.requestRouter.endpointFor("assets","/static/"+t.version+"/"+e+".js");else{var r="/static/"+e+".js?v="+t.version;if(e==="toolbar"){var s=3e5;r=r+"&t="+Math.floor(Date.now()/s)*s}i=t.requestRouter.endpointFor("assets",r)}mo(t,i,n)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");mo(t,o,n)}},B.__PosthogExtensions__.loadSiteApp=(t,e,n)=>{var i=t.requestRouter.endpointFor("api",e);mo(t,i,n)};ne.DEBUG=!1,ne.LIB_VERSION="1.415.7",ne.LIB_NAME="web";var zd="$people_distinct_id",Yi="$device_id",vo="$device_model",Fi="__alias",Ri="__timers",ea="$autocapture_disabled_server_side",ta="$heatmaps_enabled_server_side",na="$exception_capture_enabled_server_side",ia="$error_tracking_suppression_rules",ra="$error_tracking_capture_extension_exceptions",sa="$web_vitals_enabled_server_side",rl="$dead_clicks_enabled_server_side",sl="$product_tours_enabled_server_side",oa="$web_vitals_allowed_metrics",An="$session_recording_remote_config",Vd="$replay_sample_rate",Gd="$replay_override_sampling",Kd="$replay_override_linked_flag",Yd="$replay_override_url_trigger",Jd="$replay_override_event_trigger",Kn="$sesid",ol="$session_is_sampled",Sn="$enabled_feature_flags",Ti="$active_feature_flags",Ar="$early_access_features",aa="$feature_flag_details",$i="$feature_flag_payloads",Pr="$feature_flag_request_id",Zr="$minimal_flag_called_events",It="$override_feature_flags",xn="$override_feature_flag_payloads",jt="$stored_person_properties",In="$stored_group_properties",la="$surveys",Xr="$surveys_loaded_at",ca="$surveys_activated",Fr="$surveys_activated_session",Rr="$surveys_activated_timestamps",Mi="ph_product_tours",Cn="$flag_call_reported",Li="$flag_call_reported_session_id",Tr="$feature_flag_errors",ji="$feature_flag_evaluated_at",ot="$user_state",ua="$client_session_props",da="$capture_rate_limit",fa="$initial_campaign_params",ha="$initial_referrer_info",Qr="$initial_person_info",es="$epp",mr="$posthog_cookieless",Zd="$cookieless_mode",Xd="$sdk_debug_extensions_init_method",Qd="$sdk_debug_extensions_init_time_ms",ef="$sdk_debug_recording_script_not_loaded",al="PostHog loadExternalDependency extension not found.",kn="on_reject",Wt="always",Un="anonymous",vn="identified",pa="identified_only",ts="visibilitychange",ns="beforeunload",Vn="$pageview",_o="$pageleave",yo="$identify",Ac="$groupidentify";function vr(t,e){U(t)&&t.forEach(e)}function ie(t,e){if(!H(t))if(U(t))t.forEach(e);else if(Bp(t))t.forEach(((i,r)=>e(i,r)));else for(var n in t)pd.call(t,n)&&e(t[n],n)}var fe=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;e>i;i++)n[i-1]=arguments[i];for(var r of n)for(var s in r)r[s]!==void 0&&(t[s]=r[s]);return t};function $r(t){for(var e=Object.keys(t),n=e.length,i=new Array(n);n--;)i[n]=[e[n],t[e[n]]];return i}var Pc=function(t){try{return t()}catch{return}},Ag=function(t){return function(){try{for(var e=arguments.length,n=new Array(e),i=0;e>i;i++)n[i]=arguments[i];return t.apply(this,n)}catch(r){A.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),A.critical(r)}}},ll=function(t){var e={};return ie(t,(function(n,i){(X(n)&&n.length>0||ke(n))&&(e[i]=n)})),e},Pg=["herokuapp.com","vercel.app","netlify.app"];function Fg(t){var e=t?.hostname;if(!X(e))return!1;var n=e.split(".").slice(-2).join(".");for(var i of Pg)if(n===i)return!1;return!0}function ve(t,e,n,i){var r=i??{},s=r.capture,o=r.passive;t?.addEventListener(e,n,{capture:s!==void 0&&s,passive:o===void 0||o})}function ga(t){return t.name==="ph_toolbar_internal"}var tf=t=>{if(P){try{for(var e=t+"=",n=P.cookie.split(";").filter((s=>s.length)),i=0;n.length>i;i++){for(var r=n[i];r.charAt(0)==" ";)r=r.substring(1,r.length);if(r.indexOf(e)===0)return decodeURIComponent(r.substring(e.length,r.length))}}catch{}return null}};Math.trunc||(Math.trunc=function(t){return 0>t?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return ke(t)&&isFinite(t)&&Math.floor(t)===t});class is{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,n,i,r){if(!Number.isInteger(e)||!Number.isInteger(n)||!Number.isInteger(i)||!Number.isInteger(r)||0>e||0>n||0>i||0>r||e>0xffffffffffff||n>4095||i>1073741823||r>4294967295)throw new RangeError("invalid field value");var s=new Uint8Array(16);return s[0]=e/Math.pow(2,40),s[1]=e/Math.pow(2,32),s[2]=e/Math.pow(2,24),s[3]=e/Math.pow(2,16),s[4]=e/256,s[5]=e,s[6]=112|n>>>8,s[7]=n,s[8]=128|i>>>24,s[9]=i>>>16,s[10]=i>>>8,s[11]=i,s[12]=r>>>24,s[13]=r>>>16,s[14]=r>>>8,s[15]=r,new is(s)}toString(){for(var e="",n=0;this.bytes.length>n;n++)e=e+(this.bytes[n]>>>4).toString(16)+(15&this.bytes[n]).toString(16),n!==3&&n!==5&&n!==7&&n!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new is(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var n=0;16>n;n++){var i=this.bytes[n]-e.bytes[n];if(i!==0)return Math.sign(i)}return 0}}class Rg{generate(){var e=this.generateOrAbort();if(!C(e))return e;this.S=0;var n=this.generateOrAbort();if(C(n))throw new Error("Could not generate UUID after timestamp reset");return n}generateOrAbort(){var e=Date.now();if(e>this.S)this.S=e,this.C();else{if(this.S>=e+1e4)return;this.I++,this.I>4398046511103&&(this.S++,this.C())}return is.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 Tg}}var Fc,nf=t=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;t.length>e;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};w&&!C(w.crypto)&&crypto.getRandomValues&&(nf=t=>crypto.getRandomValues(t));class Tg{nextUint32(){return this.R.length>this.O||(nf(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var Ht=()=>$g().toString(),$g=()=>(Fc||(Fc=new Rg)).generate(),yi="",Mg=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,qt={N:()=>!!P,j(t){A.error("cookieStore error: "+t)},P:tf,H(t){var e;try{e=JSON.parse(qt.P(t))||{}}catch{}return e},F(t,e,n,i,r){if(!P)return!1;try{var s="",o="",a=(function(c,d){if(d){var f=(function(p,g){if(g===void 0&&(g=P),yi)return yi;if(!g||["localhost","127.0.0.1"].includes(p))return"";for(var m=p.split("."),v=Math.min(m.length,8),E="dmn_chk_"+Ht();!yi&&v--;){var S=m.slice(v).join("."),_=E+"=1;domain=."+S+";path=/";g.cookie=_+";max-age=3",g.cookie.includes(E)&&(g.cookie=_+";max-age=0",yi=S)}return yi})(c);if(!f){var h=(p=>{var g=p.match(Mg);return g?g[0]:""})(c);h!==f&&A.info("Warning: cookie subdomain discovery mismatch",h,f),f=h}return f?"; domain=."+f:""}return""})(P.location.hostname,i);if(n){var l=new Date;l.setTime(l.getTime()+864e5*n),s="; expires="+l.toUTCString()}r&&(o="; secure");var u=t+"="+encodeURIComponent(JSON.stringify(e))+s+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&A.warn("cookieStore warning: large cookie, len="+u.length),P.cookie=u,!0}catch{return!1}},q(t,e){if(P!=null&&P.cookie)try{qt.F(t,"",-1,e)}catch{return}}},wo=null,le={N(){if(!Ke(wo))return wo;var t=!0;if(C(w))t=!1;else try{var e="__mplssupport__";le.F(e,"xyz"),le.P(e)!=='"xyz"'&&(t=!1),le.q(e)}catch{t=!1}return t||A.error("localStorage unsupported; falling back to cookie store"),wo=t,t},j(t){A.error("localStorage error: "+t)},P(t){try{return w?.localStorage.getItem(t)}catch(e){le.j(e)}return null},H(t){try{return JSON.parse(le.P(t))||{}}catch{}return null},F(t,e){try{return w?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(n){le.j(n)}return!1},q(t){try{w?.localStorage.removeItem(t)}catch(e){le.j(e)}}},Lg=[Yi,"distinct_id",Kn,ol,es,Qr,ot],_r={},Ng={N:()=>!0,j(t){A.error("memoryStorage error: "+t)},P:t=>_r[t]||null,H:t=>_r[t]||null,F:(t,e)=>(_r[t]=e,!0),q(t){delete _r[t]}},_n=null,be={N(){if(!Ke(_n))return _n;if(_n=!0,C(w))_n=!1;else try{var t="__support__";be.F(t,"xyz"),be.P(t)!=='"xyz"'&&(_n=!1),be.q(t)}catch{_n=!1}return _n},j(t){A.error("sessionStorage error: ",t)},P(t){try{return w?.sessionStorage.getItem(t)}catch(e){be.j(e)}return null},H(t){try{return JSON.parse(be.P(t))||null}catch{}return null},F(t,e){try{return w?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(n){be.j(n)}return!1},q(t){try{w?.sessionStorage.removeItem(t)}catch(e){be.j(e)}}};class Og{constructor(e){this._instance=e}get Ne(){return this._instance.config}get consent(){return this.ti()?0:this.ei}isOptedOut(){return this.Ne.cookieless_mode===Wt||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===kn}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===0}isRejected(){return this.consent===0||this.consent===-1&&this.Ne.opt_out_capturing_by_default}optInOut(e){this.ii.F(this.ri,e?1:0,this.Ne.cookie_expiration,this.Ne.cross_subdomain_cookie,this.Ne.secure_cookie)}reset(){this.ii.q(this.ri,this.Ne.cross_subdomain_cookie)}get ri(){var e=this._instance.config,n=e.token,i=e.opt_out_capturing_cookie_prefix;return e.consent_persistence_name||(i?i+n:"__ph_opt_in_out_"+n)}get ei(){var e=this.ii.P(this.ri);return uo(e)?1:j(Hp,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,n=e==="localStorage"?le:qt;if(!this.ni||this.ni!==n){this.ni=n;var i=e==="localStorage"?qt:le;i.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(uo(i.P(this.ri))),i.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[Ue?.doNotTrack,Ue?.msDoNotTrack,B.doNotTrack].some((e=>uo(e)))}}function rf(t,e){var n,i=t==null||(n=t.config)==null?void 0:n.get_current_url;if(!De(i))return e;try{var r=i(e);return X(r)&&r?r:e}catch(s){return A.error("Error in get_current_url, falling back to window.location.href",s),e}}var sf="__POSTHOG_TOOLBAR__",Bg=1,Dg=3,jg=11;function Rc(t){return t instanceof Element&&(t.id===sf||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function hn(t){return!!t&&t.nodeType===Bg}function Qe(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function of(t){return!!t&&t.nodeType===Dg}function af(t){return!!t&&t.nodeType===jg&&hn(t.host)}var lf=1e3;function cl(t){return t?xs(t).split(/\s+/):[]}function Tc(t,e){var n=(function(i){var r,s=w==null||(r=w.location)==null?void 0:r.href;return C(s)?void 0:rf(i,s)})(e);return!!(n&&t&&t.some((i=>n.match(i))))}function rs(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 cl(e)}function cf(t){return H(t)?null:xs(t).split(/(\s+)/).filter((e=>Ui(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function Ji(t){var e="";return va(t)&&!hf(t)&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;of(n)&&n.textContent&&(e+=(i=cf(n.textContent))!==null&&i!==void 0?i:"")})),xs(e)}function bo(t){var e;return C(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var ul=["a","button","form","input","select","textarea","label"];function ma(t,e){if(C(e))return!0;var n,i=function(s){if(e.some((o=>(function(a,l){var u=a.matches||a.matchesSelector||a.msMatchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.oMatchesSelector;try{return!!u&&u.call(a,l)}catch{return!1}})(s,o))))return{v:!0}};for(var r of t)if(n=i(r))return n.v;return!1}function uf(t){var e=t.parentNode;return!(!e||!hn(e))&&e}var Ug=[".ph-no-autocapture","[data-ph-no-autocapture]"],df=["next","previous","prev",">","<"],Hg=[...df,"+","-","−","–"],$c=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,Mc=[".ph-no-rageclick",".ph-no-capture"],Wg=["","text","search","email","password","url","tel","number"];function Lc(t,e){if(!w||dl(t))return!1;var n,i,r,s,o;if(mt(e)?(n=!!e&&Mc,i=void 0,r=!1):(n=(s=e?.css_selector_ignorelist)!==null&&s!==void 0?s:Mc,i=e?.content_ignorelist,r=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),n===!1||r&&(function(l){return!(!l||!hn(l))&&(!!Qe(l,"textarea")||(Qe(l,"input")?j(Wg,(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=ff(t,!1).targetElementList;return!(function(l,u){if(l===!1||C(l))return!1;var c;if(l===!0)c=df;else{if(!U(l))return!1;if(l.length>10)return A.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var f=d.safeText,h=d.ariaLabel;return c.some((p=>$c(f,p)||$c(h,p)))}))})(i,a.map((l=>{var u;return{safeText:Ji(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!ma(a,n)}var dl=t=>!t||Qe(t,"html")||!hn(t),ff=(t,e)=>{if(!w||dl(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,i=[t],r=t;r.parentNode&&!Qe(r,"body");)if(af(r.parentNode))i.push(r.parentNode.host),r=r.parentNode.host;else{var s=uf(r);if(!s)break;if(e||ul.indexOf(s.tagName.toLowerCase())>-1)n=!0;else try{var o=w.getComputedStyle(s);o&&o.getPropertyValue("cursor")==="pointer"&&(n=!0)}catch{}i.push(s),r=s}return{parentIsUsefulElement:n,targetElementList:i}};function va(t){for(var e=new Set,n=0,i=t;i.parentNode&&!Qe(i,"body");i=i.parentNode){if(n++>=lf||e.has(i))return!1;e.add(i);var r=rs(i);if(j(r,"ph-sensitive")||j(r,"ph-no-capture"))return!1}if(j(rs(t),"ph-include"))return!0;var s=t.type||"";if(X(s))switch(s.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!X(o)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(o.replace(/[^a-zA-Z0-9]/g,""))}function hf(t){return!!(Qe(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||Qe(t,"select")||Qe(t,"textarea")||t.getAttribute("contenteditable")==="true")}var Nc=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}))$"),Oc=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,qg=[16,15,14,13],zg=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),Bc=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),Dc=/[0-9A-Za-z_]/;function Vg(t){for(var e=0,n=!1,i=t.length-1;i>=0;i--){var r=t.charCodeAt(i)-48;n&&(r*=2)>9&&(r-=9),e+=r,n=!n}return e%10==0}function Ui(t,e){if(e===void 0&&(e=!0),H(t))return!1;if(X(t)){t=xs(t);var n=e?Nc.test((t||"").replace(/[- ]/g,"")):(function(r){var s;for(Oc.lastIndex=0;s=Oc.exec(r);){var o=s[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of qg){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(Nc.test(d)&&Vg(d))return!0}}}return!1})(t);if(n)return!1;var i=e?zg.test(t):(function(r){var s;for(Bc.lastIndex=0;s=Bc.exec(r);){var o=s[1],a=s[3];if(!(o&&a&&Dc.test(o)&&Dc.test(a)))return!0}return!1})(t);if(i)return!1}return!0}function jc(t){var e=Ji(t);return Ui(e=(e+" "+pf(t)).trim())?e:""}function pf(t){var e="";return t&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;if(n&&((i=n.tagName)==null?void 0:i.toLowerCase())==="span")try{var r=Ji(n);e=(e+" "+r).trim(),n.childNodes&&n.childNodes.length&&(e=(e+" "+pf(n)).trim())}catch(s){A.error("[AutoCapture]",s)}})),e}function Uc(t){return t.replace(/"|\\"/g,'\\"')}function Gg(t){var e=t.attr__class;if(e)return U(e)?e:cl(e)}var yr=pe("[Dead Clicks]"),Kg=()=>!0,Yg=t=>{var e,n=!((e=t.instance.persistence)==null||!e.get_property(rl)),i=t.instance.config.capture_dead_clicks;return mt(i)?i:!!he(i)||n};class Hc{get lazyLoadedDeadClicksAutocapture(){return this.si}constructor(e,n,i){this.instance=e,this.isEnabled=n,this.onCapture=i,this.startIfEnabledOrStop()}onRemoteConfig(e){if(e.ok){var n=e.config;"captureDeadClicks"in n&&(this.instance.persistence&&this.instance.persistence.register({[rl]:n.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var n,i;(n=B.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture?e():(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"dead-clicks-autocapture",(r=>{r?yr.error("failed to load script",r):e()}))}oi(){var e;if(P){if(!this.si&&(e=B.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var n=he(this.instance.config.capture_dead_clicks)?I({},this.instance.config.capture_dead_clicks):{};n.__onCapture=this.onCapture,this.onCapture&&(n.capture_dead_swipes=!1),this.si=B.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.si.start(P),yr.info("starting...")}}else yr.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,yr.info("stopping..."))}}var Eo=pe("[SegmentIntegration]"),gf="posthog-js";function mf(t,e){var n=e===void 0?{}:e,i=n.organization,r=n.projectId,s=n.prefix,o=n.severityAllowList,a=o===void 0?["error"]:o,l=n.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,f,h,p,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var v,E=((d=c.exception)==null?void 0:d.values)||[],S=E.map((b=>I({},b,{stacktrace:b.stacktrace?I({},b.stacktrace,{type:"raw",frames:(b.stacktrace.frames||[]).map((k=>I({},k,{platform:"web:javascript"})))}):void 0}))),_={$exception_message:((f=E[0])==null?void 0:f.value)||c.message,$exception_type:(h=E[0])==null?void 0:h.type,$exception_level:c.level,$exception_list:S,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((p=E[0])==null?void 0:p.value)||c.message,$sentry_exception_type:(g=E[0])==null?void 0:g.type,$sentry_tags:c.tags};return i&&r&&(_.$sentry_url=(s||"https://sentry.io/organizations/")+i+"/issues/?project="+r+"&query="+c.event_id),u&&((v=t.exceptions)==null||v.sendExceptionEvent(_)),c}}class Jg{constructor(e,n,i,r,s,o){this.name=gf,this.setupOnce=function(a){a(mf(e,{organization:n,projectId:i,prefix:r,severityAllowList:s,sendExceptionsToPostHog:o==null||o}))}}}class Wc{constructor(e){this.li=(n,i,r)=>{r&&(r.noSessionId||r.activityTimeout||r.sessionPastMaximumLength||r.crossTabAdoption)&&(A.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:n,changeReason:r}),this.ui=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.hi()}hi(){var e;this.di=(e=this._instance.sessionManager)==null?void 0:e.onSessionId(this.li)}destroy(){var e;(e=this.di)==null||e.call(this),this.di=void 0}doPageView(e,n){var i,r=this.vi(e,n);return this.ui={pathname:(i=w?.location.pathname)!==null&&i!==void 0?i:"",pageViewId:n,timestamp:e},this._instance.scrollManager.resetContext(),r}doPageLeave(e){var n;return this.vi(e,(n=this.ui)==null?void 0:n.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.ui)==null?void 0:e.pageViewId}}vi(e,n){var i=this.ui;if(!i)return{$pageview_id:n};var r={$pageview_id:n,$prev_pageview_id:i.pageViewId},s=this._instance.scrollManager.getContext();if(s&&!this._instance.config.disable_scroll_properties){var o=s.maxScrollHeight,a=s.lastScrollY,l=s.maxScrollY,u=s.maxContentHeight,c=s.lastContentY,d=s.maxContentY;if(!(C(o)||C(a)||C(l)||C(u)||C(c)||C(d))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),d=Math.ceil(d);var f=o>1?At(a/o,0,1,A):1,h=o>1?At(l/o,0,1,A):1,p=u>1?At(c/u,0,1,A):1,g=u>1?At(d/u,0,1,A):1;r=fe(r,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:f,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:h,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:p,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return i.pathname&&(r.$prev_pageview_pathname=i.pathname),i.timestamp&&(r.$prev_pageview_duration=(e.getTime()-i.timestamp.getTime())/1e3),r}}var So=["flags","surveys"],Zg={[zd]:{exposure:"hidden"},[Fi]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[Ri]:{exposure:"hidden"},[ea]:{exposure:"event"},[ta]:{exposure:"hidden"},[na]:{exposure:"event"},[ia]:{exposure:"hidden"},[ra]:{exposure:"event"},[sa]:{exposure:"event"},[rl]:{exposure:"event"},[sl]:{exposure:"hidden"},[oa]:{exposure:"event"},[An]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[Kn]:{exposure:"hidden"},[ol]:{exposure:"event"},[Vd]:{exposure:"event",shouldSkipFromEventProperties:t=>Ke(t)},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},$sess_rec_flush_size:{exposure:"hidden"},[Sn]:{exposure:"hidden",storageGroup:"flags"},[Ti]:{exposure:"hidden",storageGroup:"flags"},[Ar]:{exposure:"hidden"},[aa]:{exposure:"hidden",storageGroup:"flags"},[$i]:{exposure:"hidden",storageGroup:"flags"},[Pr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[Zr]:{exposure:"hidden",storageGroup:"flags"},[It]:{exposure:"hidden"},[xn]:{exposure:"hidden"},[jt]:{exposure:"hidden"},[In]:{exposure:"hidden"},[la]:{exposure:"hidden",storageGroup:"surveys"},[Xr]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[ca]:{exposure:"event"},[Fr]:{exposure:"hidden"},[Rr]:{exposure:"hidden"},[Mi]:{exposure:"hidden"},$product_tours_activated:{exposure:"hidden"},$product_tours_activated_session:{exposure:"hidden"},$conversations_widget_session_id:{exposure:"event"},$conversations_ticket_id:{exposure:"event"},$conversations_widget_state:{exposure:"event"},$conversations_user_traits:{exposure:"event"},[Cn]:{exposure:"hidden"},[Li]:{exposure:"hidden"},[Tr]:{exposure:"hidden"},[ji]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[ot]:{exposure:"hidden"},[ua]:{exposure:"hidden"},[da]:{exposure:"hidden"},[fa]:{exposure:"hidden"},[ha]:{exposure:"hidden"},[Qr]:{exposure:"hidden"},[es]:{exposure:"hidden"},[Gd]:{exposure:"event"},[Kd]:{exposure:"event"},[Yd]:{exposure:"event"},[Jd]:{exposure:"event"},[Xd]:{exposure:"event"},[Qd]:{exposure:"event"},[ef]:{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"}},Xg=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],yn=t=>{var e=Zg[t];if(e)return e;for(var n of Xg){var i=n[1];if(t.indexOf(n[0])===0)return i}},Yn=(t,e)=>{try{return JSON.stringify(t,((n,i)=>typeof i=="bigint"?i.toString():i),e)}catch{return fd(t)}},ss=t=>{var e=P?.createElement("a");return C(e)?null:(e.href=t,e)},ii=function(t,e){for(var n,i=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),r=0;i.length>r;r++){var s=i[r].split("=");if(s[0]===e){n=s;break}}if(!U(n)||2>n.length)return"";var o=n[1];try{o=decodeURIComponent(o)}catch{A.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},Zi=function(t,e,n){if(!t||!e||!e.length)return t;for(var i=t.split("#"),r=i[1],s=(i[0]||"").split("?"),o=s[1],a=s[0],l=(o||"").split("&"),u=[],c=0;l.length>c;c++){var d=l[c].split("=");U(d)&&(e.includes(d[0])?u.push(d[0]+"="+n):u.push(l[c]))}var f=a;return o!=null&&(f+="?"+u.join("&")),r!=null&&(f+="#"+r),f},os=function(t,e){var n=t.match(new RegExp(e+"=([^&]*)"));return n?n[1]:null},vf=(t,e)=>t>=e&&cd(),_f=(t,e,n,i)=>{if(t===0){if(cd()){var r=e+1;return r===n&&i(),r}return e}return 0},wr="https?://(.*)",ri=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Qg=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...ri],Xi="",em=["li_fat_id"];function yf(t,e,n){if(!P)return{};var i,r=e?[...ri,...n||[]]:[],s=wf(Zi(P.URL,r,Xi),t),o=(i={},ie(em,(function(a){var l=tf(a);i[a]=l||null})),i);return fe(o,s)}function wf(t,e){var n=Qg.concat(e||[]),i={};return ie(n,(function(r){var s=ii(t,r);i[r]=s||null})),i}function bf(t){var e=(function(s){return s?s.search(wr+"google.([^/?]*)")===0?"google":s.search(wr+"bing.com")===0?"bing":s.search(wr+"yahoo.com")===0?"yahoo":s.search(wr+"duckduckgo.com")===0?"duckduckgo":null:null})(t),n=e!="yahoo"?"q":"p",i={};if(!Ke(e)){i.$search_engine=e;var r=P?ii(P.referrer,n):"";r.length&&(i.ph_keyword=r)}return i}function qc(){return navigator.language||navigator.userLanguage}var as="$direct";function Ef(){return P?.referrer||as}function Sf(t,e,n){n===void 0&&(n=!1);var i=t?[...ri,...e||[]]:[],r=n?fn(me?.href):me?.href,s=r?.substring(0,1e3);return{r:Ef().substring(0,1e3),u:s?Zi(s,i,Xi):void 0}}function xf(t,e){var n;e===void 0&&(e=!1);var i=t.r,r=t.u,s=e?fn(r):r,o={$referrer:i,$referring_domain:i==null?void 0:i==as?as:(n=ss(i))==null?void 0:n.host};if(s){o.$current_url=s;var a=ss(s);o.$host=a?.host,o.$pathname=a?.pathname;var l=wf(s);fe(o,l)}if(i){var u=bf(i);fe(o,u)}return o}function If(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function tm(){try{return new Date().getTimezoneOffset()}catch{return}}var nm={flags:ji,surveys:Xr},im=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],Hn="main";class xo{constructor(e,n,i){if(i===void 0&&(i=!0),this.ci={},this.fi=!1,this.pi=!1,this.Ne=e,this.gi=i,this.props={},this.mi=void 0,this.yi=(s=>{var o="";return s.token&&(o=s.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),s.persistence_name?"ph_"+s.persistence_name:"ph_"+o+"_posthog"})(e),this.ii=this.bi(e),this.pi=this.wi(e),this.load(),e.debug&&A.info("Persistence loaded",e.persistence,I({},this.props)),this.update_config(e,e,n),this.save(),w){var r=()=>this.flush();ve(w,"beforeunload",r,{capture:!1}),ve(w,"pagehide",r,{capture:!1})}}ki(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return ke(n)&&n>0?n:0}isDisabled(){return!!this.xi}bi(e){im.indexOf(e.persistence.toLowerCase())===-1&&(A.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var n,i=(function(o,a){o===void 0&&(o=[]),a===void 0&&(a=!1);var l=[...Lg,...o];return I({},le,{H(u){try{var c={};try{c=qt.H(u)||{}}catch{}var d,f=JSON.parse(le.P(u)||"{}");if(a){var h={};for(var p in c){var g=c[p];Ke(g)||g===""||(h[p]=g)}d=fe(f,h)}else d=fe(c,f);return le.F(u,d),d}catch{}return null},F(u,c,d,f,h,p){var g=le.F(u,c,void 0,void 0,p);try{var m={};l.forEach((v=>{c[v]&&(m[v]=c[v])})),Object.keys(m).length&&qt.F(u,m,d,f,h,p)}catch(v){le.j(v)}return g},q(u,c){try{w?.localStorage.removeItem(u),qt.q(u,c)}catch(d){le.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),r=!1,s=e.persistence.toLowerCase();return s==="localstorage"&&le.N()?(n=le,r=!0):s==="localstorage+cookie"&&i.N()?(n=i,r=!0):s==="sessionstorage"&&be.N()?n=be:s==="memory"?n=Ng:s==="cookie"?n=qt:i.N()?(n=i,r=!0):n=qt,this.fi=r,n}Si(e){return this.yi+"__"+e}wi(e){return this.fi&&!!e.split_storage}properties(){var e={};return ie(this.props,((n,i)=>{var r=yn(i);if(!r||r.exposure==="event"){if(r!=null&&r.shouldSkipFromEventProperties!=null&&r.shouldSkipFromEventProperties(n))return;e[i]=n}})),e}load(){if(!this.xi){var e=this.ii.H(this.yi);e&&(this.props=fe({},e)),this.pi&&this.Ci()}}Ci(){for(var e of So){var n=le.H(this.Si(e));if(n&&!Kt(n)){var i=this.Mi(e);i.persisted=!0,this.Ti(e)||(i.fingerprint=this.Ei(n,e)),this.Ii(e,n)||fe(this.props,n)}}}Ti(e){return Object.keys(this.props).some((n=>{var i;return((i=yn(n))==null?void 0:i.storageGroup)===e}))}Ii(e,n){var i=nm[e];if(!i)return!1;var r=n[i],s=this.props[i];return ke(r)&&ke(s)&&s>r}refreshKey(e){var n;if(!this.xi){var i=this.pi?(n=yn(e))==null?void 0:n.storageGroup:void 0,r=i?le.H(this.Si(i)):this.ii.H(this.yi);if(r&&e in r)this.Pi(e,r[e]);else{if(i){var s=this.ii.H(this.yi);if(s&&e in s)return void this.Pi(e,s[e])}this.Ri(e)}}}save(){if(!this.xi){var e=this.ki();e>0?C(this.Ai)&&(this.Ai=setTimeout((()=>{this.Ai=void 0,this.Fi()}),e)):this.Fi()}}flush(){C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0,this.Fi())}Fi(){this.xi||(this.pi?this.Li():this.Oi(this.ii,this.yi,this.props,Hn))}Li(){var e=this.Di(),n=e.main,i=e.groups;for(var r of(this.Oi(this.ii,this.yi,n,Hn),So)){var s,o=i[r];(!Kt(o)||(s=this.ci[r])!=null&&s.persisted)&&this.Oi(le,this.Si(r),o,r)}}Di(){var e={},n={flags:{},surveys:{}};return ie(this.props,((i,r)=>{var s,o=(s=yn(r))==null?void 0:s.storageGroup;o?n[o][r]=i:e[r]=i})),{main:e,groups:n}}Ei(e,n){if(n===Hn)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var i={};return ie(e,((r,s)=>{var o;i[s]=(o=yn(s))!=null&&o.volatile?"__volatile__":r})),JSON.stringify(i)}Oi(e,n,i,r){var s=this.Mi(r);if(r===Hn||s.dirty||C(s.fingerprint)){var o;try{if((o=this.Ei(i,r))===s.fingerprint)return void(s.dirty=!1)}catch{o=void 0}e.F(n,i,this.$i,this.Ni,this.qi,this.Ne.debug)?(s.dirty=!1,r!==Hn&&(s.persisted=!0),C(o)||(s.fingerprint=o)):this.Ne.debug&&A.warn('failed to persist storage entry "'+n+'"; will retry on next save')}}remove(e){var n=(e===void 0?{}:e).keepGroupEntries,i=n!==void 0&&n;if(C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0),this.ii.q(this.yi,!1),this.ii.q(this.yi,!0),!i&&this.gi)for(var r of So)le.q(this.Si(r));i?delete this.ci[Hn]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,n,i){if(he(e)){C(n)&&(n="None"),this.$i=C(i)?this.ji:i;var r=!1;if(ie(e,((s,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==n||(this.Pi(o,s),r=!0)})),r)return this.save(),!0}return!1}register(e,n){if(he(e)){this.$i=C(n)?this.ji:n;var i=!1;if(ie(e,((r,s)=>{e.hasOwnProperty(s)&&(this.props[s]!==r||he(r)||U(r))&&(this.Pi(s,r),i=!0)})),i)return this.save(),!0}return!1}unregister(e){var n=typeof e=="string"?[e]:e,i=!1;for(var r of n)r in this.props&&(this.Ri(r),i=!0);i&&this.save()}update_campaign_params(){var e=P?.URL;if(e!==this.mi){var n=yf(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);Kt(ll(n))||this.register(n),this.mi=e}}update_search_keyword(){var e;this.register((e=P?.referrer)?bf(e):{})}update_referrer_info(){var e;this.register_once({$referrer:Ef(),$referring_domain:P!=null&&P.referrer&&((e=ss(P.referrer))==null?void 0:e.host)||as},void 0)}set_initial_person_info(){this.props[fa]||this.props[ha]||this.register_once({[Qr]:Sf(this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties,this.Ne.disable_capture_url_hashes)},void 0)}get_initial_props(){var e={};ie([ha,fa],(r=>{var s=this.props[r];s&&ie(s,(function(o,a){e["$initial_"+Go(a)]=o}))}));var n=this.props[Qr];if(n){var i=(function(r,s){s===void 0&&(s=!1);var o=xf(r,s),a={};return ie(o,(function(l,u){a["$initial_"+Go(u)]=l})),a})(n,this.Ne.disable_capture_url_hashes);fe(e,i)}return e}safe_merge(e){return ie(this.props,(function(n,i){i in e||(e[i]=n)})),e}update_config(e,n,i){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!i),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var r=e.persistence!==n.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((f,h)=>f===d[h]))})(e.cookie_persisted_properties||[],n.cookie_persisted_properties||[]),s=r?this.bi(e):this.ii,o=this.wi(e);if(r||o!==this.pi){var a=this.props;this.clear(),this.ii=s,this.pi=o,this.props=a,this.save()}}set_disabled(e){this.xi=e,this.xi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ni&&(this.Ni=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this.qi&&(this.qi=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,n){var i=this.props[Ri]||{};i[e]=n,this.Pi(Ri,i),this.save()}remove_event_timer(e){var n=this.props[Ri]||{},i=n[e];return C(i)||(delete n[e],this.Pi(Ri,n),this.save()),i}get_property(e){return this.props[e]}set_property(e,n){this.Pi(e,n),this.save()}Pi(e,n){var i;this.props[e]=n,(i=yn(e))!=null&&i.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var n,i=(n=yn(e))==null?void 0:n.storageGroup;i&&(this.Mi(i).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function br(t){var e=!0;return{dispose(){if(e){e=!1;var n=t();n&&De(n.then)&&n.then(void 0,(()=>{}))}}}}var je={GZipJS:"gzip-js",Base64:"base64"},wi={Activation:"events",Cancellation:"cancelEvents"},Io={Popover:"popover",API:"api",Widget:"widget"},zt={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},ko={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},_a={Popover:"popover",Inline:"inline"},rm={SHOWN:"product tour shown"},zc={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},Vc=pe("[RateLimiter]");class sm{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=n=>{var i=n.text;if(i&&i.length)try{(JSON.parse(i).quota_limited||[]).forEach((r=>{Vc.info((r||"events")+" is quota limited."),this.serverLimits[r]=new Date().getTime()+6e4}))}catch(r){return void Vc.warn('could not rate limit - continuing. Error: "'+r?.message+'"',{text:i})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var n,i,r;e===void 0&&(e=!1);var s=this.captureEventsBurstLimit,o=this.captureEventsPerSecond,a=new Date().getTime(),l=(n=(i=this.instance.persistence)==null?void 0:i.get_property(da))!==null&&n!==void 0?n:{tokens:s,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>s&&(l.tokens=s);var u=1>l.tokens;if(u||e||(l.tokens=Math.max(0,l.tokens-1)),u&&!e){var c=(ke(l.dropped)?l.dropped:0)+1;l.dropped=c,!this.lastEventRateLimited&&this.Hi(c)&&(l.dropped=0)}return this.lastEventRateLimited=u,(r=this.instance.persistence)==null||r.set_property(da,l),{isRateLimited:u,remainingTokens:l.tokens}}Ui(e){var n=this.instance.config.property_denylist;return!U(n)||!n.includes(e)}zi(){var e;if(this.Ui("$current_url")&&this.Ui("$pathname")&&me!=null&&me.pathname)return""+((e=me.origin)!==null&&e!==void 0?e:"")+me.pathname}Hi(e){var n,i,r=this.captureEventsBurstLimit,s=this.captureEventsPerSecond,o=this.zi(),a=this.Ui("$session_id")?(n=(i=this.instance).get_session_id)==null?void 0:n.call(i):void 0,l=[e+" event(s) dropped since the last warning",o?"triggered on "+o:void 0,a?"session "+a:void 0].filter(Boolean).join(", ");return!!this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited: "+l+". Config is set to "+s+" events per second and "+r+" events burst limit."},{skip_client_rate_limiting:!0})}isServerRateLimited(e){var n=this.serverLimits[e||"events"]||!1;return n!==!1&&new Date().getTime()e(this.remoteConfig))):e()}Vi(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:e})}load(){try{if(this.remoteConfig)return an.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void an.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return an.info("No config found after loading remote JS config. Falling back to JSON."),void this.Vi((n=>{this.Zi(n.json,n),this.Gi()}));this.Zi(e),this.Gi()}))}catch(e){an.error("Error loading remote config",e),this.Zi()}}stop(){this.Ki&&(clearInterval(this.Ki),this.Ki=void 0)}refresh(){!this._instance.Qi()&&P&&P.visibilityState!=="hidden"&&this._instance.reloadFeatureFlags()}Gi(){var e;if(!this.Ki){var n=(e=this._instance.config.remote_config_refresh_interval_ms)!==null&&e!==void 0?e:3e5;n!==0&&(this.Ki=setInterval((()=>{this.refresh()}),n))}}Zi(e,n){!e&&n&&(n.statusCode===0?n.error||an.warn("Failed to fetch remote config from PostHog."):an.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(r){an.error("Error applying remote config",r)}if(e?.hasFeatureFlags!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var i;(i=this._instance.featureFlags)==null||i.ensureFlagsLoaded()}catch(r){an.error("Error loading feature flags",r)}}}var ct=Uint8Array,Ge=Uint16Array,si=Uint32Array,fl=new ct([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]),hl=new ct([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]),Gc=new ct([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Cf=function(t,e){for(var n=new Ge(31),i=0;31>i;++i)n[i]=e+=1<i;++i)for(var s=n[i];n[i+1]>s;++s)r[s]=s-n[i]<<5|i;return[n,r]},Af=Cf(fl,2),ya=Af[1];Af[0][28]=258,ya[258]=28;for(var Kc=Cf(hl,0)[1],Pf=new Ge(32768),_e=0;32768>_e;++_e){var Wn=(43690&_e)>>>1|(21845&_e)<<1;Pf[_e]=((65280&(Wn=(61680&(Wn=(52428&Wn)>>>2|(13107&Wn)<<2))>>>4|(3855&Wn)<<4))>>>8|(255&Wn)<<8)>>>1}var Hi=function(t,e,n){for(var i=t.length,r=0,s=new Ge(e);i>r;++r)++s[t[r]-1];var o,a=new Ge(e);for(r=0;e>r;++r)a[r]=a[r-1]+s[r-1]<<1;for(o=new Ge(i),r=0;i>r;++r)o[r]=Pf[a[t[r]-1]++]>>>15-t[r];return o},$n=new ct(288);for(_e=0;144>_e;++_e)$n[_e]=8;for(_e=144;256>_e;++_e)$n[_e]=9;for(_e=256;280>_e;++_e)$n[_e]=7;for(_e=280;288>_e;++_e)$n[_e]=8;var ls=new ct(32);for(_e=0;32>_e;++_e)ls[_e]=5;var om=Hi($n,9),am=Hi(ls,5),Ff=function(t){return(t/8>>0)+(7&t&&1)},Rf=function(t,e,n){(n==null||n>t.length)&&(n=t.length);var i=new(t instanceof Ge?Ge:t instanceof si?si:ct)(n-e);return i.set(t.subarray(e,n)),i},Ot=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8},bi=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8,t[i+2]|=n>>>16},Co=function(t,e){for(var n=[],i=0;t.length>i;++i)t[i]&&n.push({s:i,f:t[i]});var r=n.length,s=n.slice();if(!r)return[new ct(0),0];if(r==1){var o=new ct(n[0].s+1);return o[n[0].s]=1,[o,1]}n.sort((function(b,k){return b.f-k.f})),n.push({s:-1,f:25001});var a=n[0],l=n[1],u=0,c=1,d=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=r-1;)a=n[n[d].f>n[u].f?u++:d++],l=n[u!=c&&n[d].f>n[u].f?u++:d++],n[c++]={s:-1,f:a.f+l.f,l:a,r:l};var f=s[0].s;for(i=1;r>i;++i)s[i].s>f&&(f=s[i].s);var h=new Ge(f+1),p=wa(n[c-1],h,0);if(p>e){i=0;var g=0,m=p-e,v=1<i;++i){var E=s[i].s;if(e>=h[E])break;g+=v-(1<>>=m;g>0;){var S=s[i].s;e>h[S]?g-=1<=0&&g;--i){var _=s[i].s;h[_]==e&&(--h[_],++g)}p=e}return[new ct(h),p]},wa=function(t,e,n){return t.s==-1?Math.max(wa(t.l,e,n+1),wa(t.r,e,n+1)):e[t.s]=n},Yc=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new Ge(++e),i=0,r=t[0],s=1,o=function(l){n[i++]=l},a=1;e>=a;++a)if(t[a]==r&&a!=e)++s;else{if(!r&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(r),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(r);s=1,r=t[a]}return[n.subarray(0,i),e]},Ei=function(t,e){for(var n=0,i=0;e.length>i;++i)n+=t[i]*e[i];return n},ba=function(t,e,n){var i=n.length,r=Ff(e+2);t[r]=255&i,t[r+1]=i>>>8,t[r+2]=255^t[r],t[r+3]=255^t[r+1];for(var s=0;i>s;++s)t[r+s+4]=n[s];return 8*(r+4+i)},Jc=function(t,e,n,i,r,s,o,a,l,u,c){Ot(e,c++,n),++r[256];for(var d=Co(r,15),f=d[0],h=d[1],p=Co(s,15),g=p[0],m=p[1],v=Yc(f),E=v[0],S=v[1],_=Yc(g),b=_[0],k=_[1],T=new Ge(19),x=0;E.length>x;++x)T[31&E[x]]++;for(x=0;b.length>x;++x)T[31&b[x]]++;for(var F=Co(T,7),$=F[0],O=F[1],L=19;L>4&&!$[Gc[L-1]];--L);var N,K,V,M,R=u+5<<3,Z=Ei(r,$n)+Ei(s,ls)+o,Ce=Ei(r,f)+Ei(s,g)+o+14+3*L+Ei(T,$)+(2*T[16]+3*T[17]+7*T[18]);if(Z>=R&&Ce>=R)return ba(e,c,t.subarray(l,l+u));if(Ot(e,c,1+(Z>Ce)),c+=2,Z>Ce){N=Hi(f,h),K=f,V=Hi(g,m),M=g;var oe=Hi($,O);for(Ot(e,c,S-257),Ot(e,c+5,k-1),Ot(e,c+10,L-4),c+=14,x=0;L>x;++x)Ot(e,c+3*x,$[Gc[x]]);c+=3*L;for(var ye=[E,b],$e=0;2>$e;++$e){var ae=ye[$e];for(x=0;ae.length>x;++x)Ot(e,c,oe[Ie=31&ae[x]]),c+=$[Ie],Ie>15&&(Ot(e,c,ae[x]>>>5&127),c+=ae[x]>>>12)}}else N=om,K=$n,V=am,M=ls;for(x=0;a>x;++x)if(i[x]>255){var Ie;bi(e,c,N[257+(Ie=i[x]>>>18&31)]),c+=K[Ie+257],Ie>7&&(Ot(e,c,i[x]>>>23&31),c+=fl[Ie]);var Se=31&i[x];bi(e,c,V[Se]),c+=M[Se],Se>3&&(bi(e,c,i[x]>>>5&8191),c+=hl[Se])}else bi(e,c,N[i[x]]),c+=K[i[x]];return bi(e,c,N[256]),c+K[256]},lm=new si([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),cm=(function(){for(var t=new si(256),e=0;256>e;++e){for(var n=e,i=9;--i;)n=(1&n&&3988292384)^n>>>1;t[e]=n}return t})(),Ao=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8};function um(t,e){e===void 0&&(e={});var n=(function(){var d=4294967295;return{p(f){for(var h=d,p=0;f.length>p;++p)h=cm[255&h^f[p]]^h>>>8;d=h},d(){return 4294967295^d}}})(),i=t.length;n.p(t);var r,s,o,a,l,u=(a=10+((r=e).filename&&r.filename.length+1||0),l=8,(function(d,f,h,p,g,m){var v=d.length,E=new ct(p+v+5*(1+Math.floor(v/7e3))+g),S=E.subarray(p,E.length-g),_=0;if(!f||8>v)for(var b=0;v>=b;b+=65535){var k=b+65535;v>k?_=ba(S,_,d.subarray(b,k)):(S[b]=!0,_=ba(S,_,d.subarray(b,v)))}else{for(var T=lm[f-1],x=T>>>13,F=8191&T,$=(1<b;++b){var Ie=V(b),Se=32767&b,Be=L[Ie];if(O[Se]=Be,L[Ie]=Se,b>=$e){var wt=v-b;if((Ce>7e3||ye>24576)&&wt>423){_=Jc(d,S,0,M,R,Z,oe,ye,ae,b-ae,_),ye=Ce=oe=0,ae=b;for(var ge=0;286>ge;++ge)R[ge]=0;for(ge=0;30>ge;++ge)Z[ge]=0}var Ye=2,bt=0,mn=F,Re=Se-Be&32767;if(wt>2&&Ie==V(b-Re))for(var Pe=Math.min(x,wt)-1,$t=Math.min(32767,b),Bn=Math.min(258,wt);$t>=Re&&--mn&&Se!=Be;){if(d[b+Ye]==d[b+Ye-Re]){for(var qe=0;Bn>qe&&d[b+qe]==d[b+qe-Re];++qe);if(qe>Ye){if(Ye=qe,bt=Re,qe>Pe)break;var Dn=Math.min(Re,qe-2),Mt=0;for(ge=0;Dn>ge;++ge){var Lt=b-Re+ge+32768&32767,ut=Lt-O[Lt]+32768&32767;ut>Mt&&(Mt=ut,Be=Lt)}}}Re+=(Se=Be)-(Be=O[Se])+32768&32767}if(bt){M[ye++]=268435456|ya[Ye]<<18|Kc[bt];var sn=31&ya[Ye],gi=31&Kc[bt];oe+=fl[sn]+hl[gi],++R[257+sn],++Z[gi],$e=b+Ye,++Ce}else M[ye++]=d[b],++R[d[b]]}}_=Jc(d,S,!0,M,R,Z,oe,ye,ae,b-ae,_)}return Rf(E,0,p+Ff(_)+g)})(s=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):12+o.mem,a,l)),c=u.length;return(function(d,f){var h=f.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>f.level?4:f.level==9?2:0,d[9]=3,f.mtime!=0&&Ao(d,4,Math.floor(new Date(f.mtime||Date.now())/1e3)),h){d[3]=8;for(var p=0;h.length>=p;++p)d[p+10]=h.charCodeAt(p)}})(u,e),Ao(u,c-8,n.d()),Ao(u,c-4,i),u}var dm=!!qo||!!Za,Tf="text/plain",Mr=!1,$f=(t,e)=>{var n=t.split("#"),i=n[1],r=n[0].split("?"),s=r[0],o=r[1];if(!o)return t;var a=o.split("&").filter((l=>l.split("=")[0]!==e)).join("&");return s+(a?"?"+a:"")+(i?"#"+i:"")},ks=function(t,e,n){var i;n===void 0&&(n=!0);var r=t.split("?"),s=r[0],o=r[1],a=I({},e),l=(i=o?.split("&").map((c=>{var d,f=c.split("="),h=f[0],p=n&&(d=a[h])!==null&&d!==void 0?d:f[1];return delete a[h],h+"="+p})))!==null&&i!==void 0?i:[],u=(function(c,d){var f,h;d===void 0&&(d="&");var p=[];return ie(c,(function(g,m){C(g)||C(m)||m==="undefined"||(f=encodeURIComponent((v=>v instanceof File)(g)?g.name:g.toString()),h=encodeURIComponent(m),p[p.length]=h+"="+f)})),p.join(d)})(a);return u&&l.push(u),l.length>0?s+"?"+l.join("&"):s},Po=t=>{if(t.Ji)return t.Ji;var e=t.data,n=t.compression;if(e){if(n===je.GZipJS){var i=um((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new ct(a.length+(a.length>>>1)),d=0,f=function(m){c[d++]=m},h=0;u>h;++h){if(d+5>c.length){var p=new ct(d+8+(u-h<<1));p.set(c),c=p}var g=a.charCodeAt(h);128>g?f(g):2048>g?(f(192|g>>>6),f(128|63&g)):g>55295&&57344>g?(f(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++h))>>>18),f(128|g>>>12&63),f(128|g>>>6&63),f(128|63&g)):(f(224|g>>>12),f(128|g>>>6&63),f(128|63&g))}return Rf(c,0,d)})(Yn(e)),{mtime:0});return{contentType:Tf,body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),estimatedSize:i.byteLength}}if(n===je.Base64){var r=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(Yn(e)),s=(a=>"data="+encodeURIComponent(typeof a=="string"?a:Yn(a)))(r);return{contentType:"application/x-www-form-urlencoded",body:s,estimatedSize:new Blob([s]).size}}var o=Yn(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},Mf=t=>{var e,n,i=()=>t.transport==="sendBeacon"?{url:ks(t.url,{compression:je.Base64}),encodedBody:Po(I({},t,{compression:je.Base64,Ji:void 0}))}:{url:$f(t.url,"compression"),encodedBody:Po(I({},t,{compression:void 0,Ji:void 0}))};try{e=Po(t)}catch(r){if(mc(t.compression,ii(t.url,"compression")))return A.error("Failed to gzip request body, sending uncompressed payload",r),i();throw r}return e&&mc(t.compression,ii(t.url,"compression"))&&!((n=e.body)instanceof ArrayBuffer?zo(new Uint8Array(n)):ArrayBuffer.isView(n)&&zo(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)))?(Mr=!0,i()):{url:t.url,encodedBody:e}},Lf=t=>{try{return Mf(t)}catch(e){return A.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},fm=(function(){var t=se((function*(e){var n=Yn(e.data),i=yield(function(s,o,a){return Vo.apply(this,arguments)})(n,ne.DEBUG,{rethrow:!0});if(!i)return e;var r=yield i.arrayBuffer();return I({},e,{Ji:{contentType:Tf,body:r,estimatedSize:r.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),hm=/Failed to fetch|NetworkError|Load failed/i,Nf=t=>t?.name==="TypeError"&&hm.test(t?.message||""),Of=t=>{var e=Lf(t);if(e){var n=e.url,i=e.encodedBody,r=i??{},s=r.contentType,o=r.body,a=r.estimatedSize,l=new Headers;ie(t.headers,(function(p,g){l.append(g,p)})),s&&l.append("Content-Type",s);var u=null,c=!1;if(uc){var d=new uc;u={signal:d.signal,timeout:setTimeout((()=>{var p,g;c=!0,d.abort((p=t.timeout,(g=new Error("PostHog request timed out"+(p?" after "+p+"ms":""))).name="AbortError",g))}),t.timeout)}}var f=p=>{c&&p?.name==="AbortError"||Nf(p)?A.warn(p):A.error(p),t.callback==null||t.callback({statusCode:0,error:p})};try{var h;Za(n,I({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(h=u)==null?void 0:h.signal},t.fetchOptions)).then((p=>p.text().then((g=>{var m={statusCode:p.status,text:g};if(p.status===200)try{m.json=JSON.parse(g)}catch(v){A.error(v)}t.callback==null||t.callback(m)})))).catch(f).finally((()=>u?clearTimeout(u.timeout):null))}catch(p){u&&clearTimeout(u.timeout),f(p)}}},Ea=t=>{try{var e,n=Mf(t),i=n.url,r=n.encodedBody,s=r??{},o=s.body,a=s.estimatedSize;if(!o)return;var l=o instanceof Blob?o:new Blob([o],{type:s.contentType});if(Ue.sendBeacon(i,l))return;var u=U(t.data)?t.data:(e=t.data)==null?void 0:e.batch;if(U(u)&&u.length>1&&(a??0)>16384){var c=Math.ceil(u.length/2),d=f=>U(t.data)?f:I({},t.data,{batch:f});return Ea(I({},t,{data:d(u.slice(0,c))})),void Ea(I({},t,{data:d(u.slice(c))}))}A.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),Of(I({},t,{Yi:!0}))}catch(f){A.warn("Beacon send failed",f)}},Zc=(t,e,n,i)=>{var r=i==="query"?e==="POST"?"sent_at":"_":void 0;return ks(n===je.GZipJS?$f(t,"compression"):t,I({},r?{[r]:Date.now().toString()}:{},n===je.GZipJS?{}:{compression:n}))},Lr=[];Za&&Lr.push({transport:"fetch",method:Of}),qo&&Lr.push({transport:"XHR",method(t){var e=Lf(t);if(e){var n=new qo,i=e.encodedBody;n.open(t.method||"GET",e.url,!0);var r=i??{},s=r.contentType,o=r.body;ie(t.headers,(function(a,l){n.setRequestHeader(l,a)})),s&&n.setRequestHeader("Content-Type",s),t.timeout&&(n.timeout=t.timeout),n.onreadystatechange=()=>{if(n.readyState===4){var a={statusCode:n.status,text:n.responseText};if(n.status===200)try{a.json=JSON.parse(n.responseText)}catch{}t.callback==null||t.callback(a)}},n.send(o)}}}),Ue!=null&&Ue.sendBeacon&&Lr.push({transport:"sendBeacon",method:Ea});var Sa=3e3;class pm{constructor(e,n){this.Xi=!0,this.tr=[],this.er=At(n?.flush_interval_ms||Sa,250,5e3,A.createLogger("flush interval"),Sa),this.ir=e}enqueue(e){this.tr.push(e),this.rr||this.nr()}unload(){this.sr();var e=this.tr.length>0?this.ar():{},n=Object.values(e);[...n.filter((i=>i.url.indexOf("/e")===0)),...n.filter((i=>i.url.indexOf("/e")!==0))].map((i=>{this.lr(I({},i,{transport:"sendBeacon"}))}))}enable(){this.Xi=!1,this.nr()}nr(){var e=this;this.Xi||(this.rr=setTimeout((()=>{if(this.sr(),this.tr.length>0){var n=this.ar(),i=function(){var s=n[r],o=new Date().getTime();s.data&&U(s.data)&&ie(s.data,(a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp})),e.lr(s)};for(var r in n)i()}}),this.er))}lr(e){try{this.ir(e)}catch(n){A.error(n)}}sr(){clearTimeout(this.rr),this.rr=void 0}ar(){var e={};return ie(this.tr,(n=>{var i,r=n,s=(r?r.batchKey:null)||r.url;C(e[s])&&(e[s]=I({},r,{data:[]})),(i=e[s].data)==null||i.push(r.data)})),this.tr=[],e}}var gm=["retriesPerformedSoFar"];class mm{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!C(w)&&"onLine"in w.navigator&&(this.dr=w.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},ve(w,"online",this.vr),ve(w,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var n=e.retriesPerformedSoFar,i=ud(e,gm);Dt(n)&&(i.url=ks(i.url,{retry_count:n})),this._instance._send_request(I({},i,{callback:r=>{if(r.statusCode!==200&&(400>r.statusCode||r.statusCode>=500)){if((r.statusCode===0?3:10)>(n??0))return void this.At(I({retriesPerformedSoFar:n},i));r.statusCode===0&&A.warn("Request failed before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped retrying after "+(n??0)+" retries.")}i.callback==null||i.callback(r)}}))}At(e){var n=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=n+1;var i=(function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),c=Math.random()-.5;return Math.ceil(u+c*(u-l))})(n),r=Date.now()+i;this.tr.push({retryAt:r,requestOptions:e});var s="Enqueued failed request for retry in "+i;navigator.onLine||(s+=" (Browser is offline)"),A.warn(s),this.ur||(this.ur=!0,this.gr())}gr(){if(this.mr&&clearTimeout(this.mr),this.tr.length===0)return this.ur=!1,void(this.mr=void 0);this.mr=setTimeout((()=>{this.dr&&this.tr.length>0&&this.cr(),this.gr()}),this.hr)}cr(){var e=Date.now(),n=[],i=this.tr.filter((s=>e>s.retryAt||(n.push(s),!1)));if(this.tr=n,i.length>0)for(var r of i)this.retriableRequest(r.requestOptions)}unload(){for(var e of(this.mr&&(clearTimeout(this.mr),this.mr=void 0),this.ur=!1,C(w)||(this.vr&&(w.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(w.removeEventListener("offline",this.pr),this.pr=void 0)),this.tr)){var n=e.requestOptions;try{this._instance._send_request(I({},n,{transport:"sendBeacon"}))}catch(i){A.error(i)}}this.tr=[]}}class vm{constructor(e){this.yr=()=>{var n,i,r,s;this.br||(this.br={});var o=this.scrollElement(),a=this.scrollY(),l=o?Math.max(0,o.scrollHeight-o.clientHeight):0,u=a+(o?.clientHeight||0),c=o?.scrollHeight||0;this.br.lastScrollY=Math.ceil(a),this.br.maxScrollY=Math.max(a,(n=this.br.maxScrollY)!==null&&n!==void 0?n:0),this.br.maxScrollHeight=Math.max(l,(i=this.br.maxScrollHeight)!==null&&i!==void 0?i:0),this.br.lastContentY=u,this.br.maxContentY=Math.max(u,(r=this.br.maxContentY)!==null&&r!==void 0?r:0),this.br.maxContentHeight=Math.max(c,(s=this.br.maxContentHeight)!==null&&s!==void 0?s:0)},this._instance=e}get _r(){return this._instance.config.scroll_root_selector}getContext(){return this.br}resetContext(){var e=this.br;return setTimeout(this.yr,0),e}startMeasuringScrollPosition(){ve(w,"scroll",this.yr,{capture:!0}),ve(w,"scrollend",this.yr,{capture:!0}),ve(w,"resize",this.yr)}scrollElement(){if(!this._r)return w?.document.documentElement;var e=U(this._r)?this._r:[this._r];for(var n of e){var i=w?.document.querySelector(n);if(i)return i}}wr(e){var n=e==="y"?"scrollTop":"scrollLeft";if(this._r){var i=this.scrollElement();return i&&i[n]||0}return w?e==="y"?w.scrollY||w.pageYOffset||w.document.documentElement.scrollTop||0:w.scrollX||w.pageXOffset||w.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var _m=t=>Sf(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class Xc{constructor(e,n,i,r){this.kr=s=>{var o=this.Sr();if(!o||o.sessionId!==s){var a={sessionId:s,props:this.Cr(this._instance)};this.Mr.register({[ua]:a})}},this._instance=e,this.Tr=n,this.Mr=i,this.Cr=r||_m,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[ua]}getSetOnceProps(){var e,n=(e=this.Sr())==null?void 0:e.props;return n?"r"in n?xf(n,this._instance.config.disable_capture_url_hashes):{$referring_domain:n.referringDomain,$pathname:n.initialPathName,utm_source:n.utm_source,utm_campaign:n.utm_campaign,utm_medium:n.utm_medium,utm_content:n.utm_content,utm_term:n.utm_term}:{}}getSessionProps(){var e={};return ie(ll(this.getSetOnceProps()),((n,i)=>{i==="$current_url"&&(i="url"),e["$session_entry_"+Go(i)]=n})),e}}class pl{on(e,n){return this.Er[e]||(this.Er[e]=[]),this.Er[e].push(n),()=>{this.Er[e]=this.Er[e].filter((i=>i!==n))}}emit(e,n){for(var i of this.Er[e]||[])i(n);for(var r of this.Er["*"]||[])r(e,n)}constructor(){this.Er={}}}var Si=pe("[SessionId]");class Qc{on(e,n){return this.Ir.on(e,n)}constructor(e,n,i){var r;if(this.Pr=null,this.Rr=[],this.Ar=void 0,this.Fr=!1,this.Ir=new pl,this.Lr=(u,c)=>!(!Dt(u)||!Dt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===Wt)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Ne=e.config,this.Mr=e.persistence,this.Or=void 0,this.Dr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.$r=n||Ht,this.Nr=i||Ht;var s=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*At(this.Ne.session_idle_timeout_seconds||1800,60,36e3,Si.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.qr(),this.jr="ph_"+s+"_window_id",this.Br="ph_"+s+"_primary_window_exists",this.Hr()){var o=be.H(this.jr),a=be.H(this.Br);o&&!a?this.Or=o:be.q(this.jr),be.F(this.Br,!0)}if((r=this.Ne.bootstrap)!=null&&r.sessionID)try{var l=(u=>{var c=this.Ne.bootstrap.sessionID.replace(/-/g,"");if(c.length!==32)throw new Error("Not a valid UUID");if(c[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(c.substring(0,12),16)})();this.Ur(this.Ne.bootstrap.sessionID,new Date().getTime(),l)}catch(u){Si.error("Invalid sessionID in bootstrap",u)}this.zr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return C(this.Rr)&&(this.Rr=[]),this.Rr.push(e),this.Dr&&e(this.Dr,this.Or),()=>{this.Rr=this.Rr.filter((n=>n!==e))}}Hr(){return this.Ne.persistence!=="memory"&&!this.Mr.xi&&be.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&be.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?be.H(this.jr):null}Zr(e){var n=this.Pr;return!Ke(n)&&!Ke(e)&&5e3>Math.abs(e-n)}Ur(e,n,i){var r=n!==this._sessionActivityTimestamp,s=!(e!==this.Dr||i!==this._sessionStartTimestamp);this._sessionStartTimestamp=i,this._sessionActivityTimestamp=n,this.Dr=e,s&&!r||s&&this.Zr(n)||(this.Pr=n,this.Mr.register({[Kn]:[n,e,i]}))}Gr(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return Dt(n)&&n>0}Qr(){this.Gr()?this.Mr.refreshKey(Kn):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!Ke(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this.Pr){this.Qr();var n=this.Jr();n[1]===this.Dr&&n[2]===this._sessionStartTimestamp&&(this.Pr=this._sessionActivityTimestamp,this.Mr.register({[Kn]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],n=Dt(e)?e:0,i=Dt(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(n,i)}Xr(e){return this.Qr(),this.Lr(e,this.Yr())}Jr(){var e=this.Mr.props[Kn];return U(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Pr=null,clearTimeout(this.tn),this.tn=void 0,this.Ur(null,null,null)}destroy(){this.Fr=!0,this.Kr(),clearTimeout(this.tn),this.tn=void 0,this.Ar&&w&&(w.removeEventListener(ns,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&be.q(this.Br)},ve(w,ns,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=null),this.Ne.cookieless_mode===Wt)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var i=n||new Date().getTime(),r=this.Jr(),s=r[1],o=r[2],a=this.Yr(),l=this.Vr(),u=Dt(o)&&Math.abs(i-o)>864e5,c=!1,d=!1,f=!s,h=s,p=!f&&!e&&this.Lr(i,a);if(p){(p=this.Xr(i))||Si.info("cross-tab refresh kept the session alive",{sessionId:s});var g=this.Jr();s=g[1],o=g[2]}f||p||u?(s=this.$r(),l=this.Nr(),Si.info("new session ID generated",{sessionId:s,windowId:l,changeReason:{noSessionId:f,activityTimeout:p,sessionPastMaximumLength:u}}),o=i,c=!0):(l||(l=this.Nr(),c=!0),(d=s!==h)&&(Si.info("adopted cross-tab session id",{sessionId:s,windowId:l}),c=!0));var m=Dt(a)&&e&&!u?a:i,v=Dt(o)?o:new Date().getTime();this.Wr(l),this.Ur(s,m,v),e||this.qr();var E={noSessionId:f,activityTimeout:p,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((S=>S(s,l,E))),{sessionId:s,windowId:l,sessionStartTimestamp:v,changeReason:c?E:void 0,lastActivityTimestamp:a}}qr(){this.Fr||(clearTimeout(this.tn),this.tn=setTimeout((()=>{if(!this.Fr)if(this.Xr(new Date().getTime())){var e=this.Dr;this.resetSessionId(),this.Ir.emit("forcedIdleReset",{idleSessionId:e})}else this.qr()}),1.1*this.sessionTimeoutMs))}}var Bf=function(t,e){if(!t)return!1;var n=t.userAgent;if(n&&_c(n,e))return!0;try{var i=t?.userAgentData;if(i!=null&&i.brands&&i.brands.some((r=>_c(r?.brand,e))))return!0}catch{}return!!t.webdriver};function Df(){return(Df=se((function*(){var t=Ue?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),n=e?.model;return X(n)&&n.length>0?n:void 0}catch(i){return void A.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",i)}}))).apply(this,arguments)}var cs=function(t,e){if(!(function(n){try{new RegExp(n)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function Fo(t,e,n){return Yn({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}var jf={exact:(t,e)=>e.some((n=>t.some((i=>n===i)))),is_not:(t,e)=>e.every((n=>t.every((i=>n!==i)))),regex:(t,e)=>e.some((n=>t.some((i=>cs(n,i))))),not_regex:(t,e)=>e.every((n=>t.every((i=>!cs(n,i))))),icontains:(t,e)=>e.map(Er).some((n=>t.map(Er).some((i=>n.includes(i))))),not_icontains:(t,e)=>e.map(Er).every((n=>t.map(Er).every((i=>!n.includes(i))))),gt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>i>parseFloat(r)))})),lt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>it.toLowerCase();function Uf(t,e){return!t||Object.entries(t).every((n=>{var i=n[1],r=e?.[n[0]];if(C(r)||Ke(r))return!1;var s=[String(r)],o=jf[i.operator];return!!o&&o(i.values,s)}))}var xa="custom",eu="i.posthog.com",ym=/^\/static\//;class wm{constructor(e){this.en={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,n=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return n||(n=this.apiHost.replace("."+eu,".posthog.com")),n==="https://app.posthog.com"?"https://us.posthog.com":n}get region(){return this.en[this.apiHost]||(this.en[this.apiHost]=/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"us":/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"eu":xa),this.en[this.apiHost]}rn(e){if(ym.test(e)){var n=this.instance.config.asset_host;if(typeof n=="string")return n.trim().replace(/\/$/,"")||void 0}}endpointFor(e,n){if(n===void 0&&(n=""),n&&(n=n[0]==="/"?n:"/"+n),e==="ui")return this.uiHost+n;if(e==="flags")return this.flagsApiHost+n;if(e==="assets"){var i=this.rn(n);if(i)return""+i+n}if(this.region===xa)return this.apiHost+n;var r=eu+n;switch(e){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}}function Hf(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var Q=pe("[Surveys]"),Wf="seenSurvey_",qf=t=>{try{var e=(n=>((i,r)=>""+Wf+(function(s){return s.current_iteration&&s.current_iteration>0?s.id+"_"+s.current_iteration:s.id})(r))(0,n))(t);if(localStorage.getItem(e))return;localStorage.setItem(e,"true")}catch(n){Q.error("Failed to persist survey seen state",n)}},bm=[Io.Popover,Io.Widget,Io.API],Em={ignoreConditions:!1,ignoreDelay:!1,displayType:_a.Popover},Sm=pe("[PostHog ExternalIntegrations]"),xm={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class Im{constructor(e){this._instance=e}ai(e,n){var i;(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,e,(r=>{if(r)return Sm.error("failed to load script",r);n()}))}startIfEnabledOrStop(){var e=this,n=function(){var s,o,a,l=i[0],u=i[1];!u||(s=B.__PosthogExtensions__)!=null&&(s=s.integrations)!=null&&s[l]||e.ai(xm[l],(()=>{var c;(c=B.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=B.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=B.__PosthogExtensions__)==null||(a=a.integrations)==null||(a=a[l])==null||a.stop())};for(var i of Object.entries((r=this._instance.config.integrations)!==null&&r!==void 0?r:{})){var r;n()}}}class km{constructor(e,n){this.rt=e,this.nn=n,this.sn=new Map,this.an=!1}add(e){var n=this;return se((function*(){if(n.an)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(n.sn.has(e.name))throw new Error('Browser extension "'+e.name+'" is already registered');n.sn.set(e.name,e);try{var i=e.setup(n.nn);i&&(yield i)}catch(s){var r=n.sn.get(e.name)===e;r&&n.sn.delete(e.name),n.rt.error('Failed to set up browser extension "'+e.name+'"',s),r&&n.ln(e)}}))()}dispose(){if(!this.an){this.an=!0;var e=Array.from(this.sn.values()).reverse();for(var n of(this.sn.clear(),e))this.ln(n)}}ln(e){try{var n=e.dispose==null?void 0:e.dispose();n&&De(n.then)&&n.then(void 0,(i=>{this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}))}catch(i){this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}}}class Cm{constructor(e){this._instance=e}initialize(){}get(e){var n=this._instance.persistence;if(typeof e=="string")return n?.get_property(e);var i={};for(var r of e){var s=n?.get_property(r);C(s)||(i[r]=s)}return i}set(e,n){var i;(i=this._instance.persistence)==null||i.register(typeof e=="string"?{[e]:n}:e)}remove(e){var n;(n=this._instance.persistence)==null||n.unregister(e)}}var tu="extensionsRemoteConfig";class Am{constructor(e){this.an=!1,this.instance=e,this.rt=A,this.un=e.hn,this.kv=new Cm(e),this.onEvent=n=>br(this.instance.on("eventCaptured",(i=>{try{n({event:i.event,properties:i.properties})}catch(r){this.rt.error("Browser extension event listener failed",r)}}))),this.onRemoteConfig=n=>{if(this.an)return br((()=>{}));var i=s=>{try{n(s)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},r=this.instance.dn.on(tu,i);return this.un&&i(this.un),br(r)},this.vn=new km(A.createLogger("[BrowserExtensions]"),this)}get logger(){return this.rt}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return(e=this.instance.get_property(Yi))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(Yi);return typeof e=="string"?e:void 0}get library(){return{name:ne.LIB_NAME,version:ne.LIB_VERSION}}get initialPersonProperties(){var e,n;return(e=(n=this.instance.persistence)==null?void 0:n.get_initial_props())!==null&&e!==void 0?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,n,i,r,s=(e=this.instance.sessionManager)==null?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:(n=s?.sessionId)!==null&&n!==void 0?n:"",windowId:(i=s?.windowId)!==null&&i!==void 0?i:"",sessionStartTimestamp:(r=s?.sessionStartTimestamp)!==null&&r!==void 0?r:0}}catch{return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get projectToken(){return this.instance.config.token}add(e){return this.vn.add(e)}capture(e,n,i){var r=this;return se((function*(){i?r.instance.capture(e,n,{timestamp:i.timestamp,uuid:i.uuid,$set:i.set,$set_once:i.setOnce}):r.instance.capture(e,n)}))()}registerDynamicEventProperties(e){return br(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(tu,e))}sendRequest(e,n){var i=this;return se((function*(){var r;n===void 0&&(n={});var s=i.instance.requestRouter.endpointFor((r=n.target)!==null&&r!==void 0?r:"api",e),o={method:n.method,url:n.query?ks(s,n.query):s,data:n.body,headers:n.headers,timeout:n.timeoutMs,fireCallbackOnDrop:!0,transport:n.transport,compression:n.compression,timestampMode:n.sentAt};return n.transport==="sendBeacon"?(i.instance._send_request(o),{statusCode:202}):new Promise((a=>{o.callback=a,i.instance._send_request(o)}))}))()}dispose(){this.an||(this.an=!0,this.vn.dispose())}}var Wi={},Ro=0,us=()=>{},nu='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',xi="Surveys module not available",iu="sanitize_properties is deprecated. Use before_send instead",zf="Invalid value for property_denylist config: ",Pm=["token","distinct_id",Zd],Gn="posthog",Vf=!dm&&Ve?.indexOf("MSIE")===-1&&Ve?.indexOf("Mozilla")===-1,To=t=>{var e;return I({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:Fg(P?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:us,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:t??"unset",__preview_deferred_init_extensions:!1,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:me&&X(me?.search)&&me.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disableDeviceModel:!1,disable_external_dependency_loading:!1,strict_script_versioning:!1,enable_recording_console_log:void 0,secure_cookie:(w==null||(e=w.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(n){A.error("Bad HTTP status: "+n.statusCode+" "+n.text)},get_device_id:n=>n,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:pa,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:Sa},error_tracking:{},_onCapture:us},(n=>({rageclick:n&&n>="2026-05-30"?{content_ignorelist:Hg,ignore_text_selection:!0}:!n||"2025-11-30">n||{content_ignorelist:!0},capture_pageview:!n||"2025-05-24">n||"history_change",session_recording:n&&n>="2026-06-25"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6},streamNetworkBody:!0}:n&&n>="2026-05-30"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6}}:n&&n>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:n&&n>="2026-01-30"?"head":"body",internal_or_test_user_hostname:n&&n>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:n&&n>="2026-05-30"?250:0,split_storage:!(!n||"2026-05-30">n),detect_google_search_app:!(!n||"2026-05-30">n),disable_capture_url_hashes:!(!n||"2026-06-25">n)}))(t))},Fm=[["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"]],ru=t=>{var e={};for(var n of Fm){var i=n[0],r=n[1];C(t[i])||(e[r]=t[i])}var s=fe({},e,t),o=t.__preview_external_dependency_versioned_paths;return C(o)||(C(t.strict_script_versioning)&&(s.strict_script_versioning=!!o),X(o)&&C(t.asset_host)&&(s.asset_host=o)),U(t.property_blacklist)&&(C(t.property_denylist)?s.property_denylist=t.property_blacklist:U(t.property_denylist)?s.property_denylist=[...t.property_blacklist,...t.property_denylist]:A.error(zf+t.property_denylist)),s};class Rm{constructor(){this.__forceAllowLocalhost=!1}get fn(){return this.__forceAllowLocalhost}set fn(e){A.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class Je{pn(e,n){if(e){var i=this.sn.indexOf(e);i!==-1&&this.sn.splice(i,1)}return this.sn.push(n),n.initialize==null||n.initialize(),n}gn(){return this.config.cookieless_mode===Wt||this.config.cookieless_mode===kn&&this.consent.isRejected()}get decideEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){var e;this.webPerformance=new Rm,this.mn=!1,this.version=ne.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new pl,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=To(),this.SentryIntegration=Jg,this.sentryIntegration=i=>(function(r,s){var o=mf(r,s);return{name:gf,processEvent:a=>o(a)}})(this,i),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.wn=!1,this.kn=null,this.xn=null,this.Sn=null,this.scrollManager=new vm(this),this.pageViewManager=new Wc(this),this.rateLimiter=new sm(this),this.requestRouter=new wm(this),this.consent=new Og(this),this.externalIntegrations=new Im(this);var n=(e=Je.__defaultExtensionClasses)!==null&&e!==void 0?e:{};this.featureFlags=n.featureFlags&&new n.featureFlags(this),this.toolbar=n.toolbar&&new n.toolbar(this),this.surveys=n.surveys&&new n.surveys(this),this.conversations=n.conversations&&new n.conversations(this),this.logs=n.logs&&new n.logs(this),this.metrics=n.metrics&&new n.metrics(this),this.experiments=n.experiments&&new n.experiments(this),this.exceptions=n.exceptions&&new n.exceptions(this),this.people={set:(i,r,s)=>{var o=X(i)?{[i]:r}:i;this.setPersonProperties(o),s?.({})},set_once:(i,r,s)=>{var o=X(i)?{[i]:r}:i;this.setPersonProperties(void 0,o),s?.({})}},this.on("eventCaptured",(i=>A.info('send "'+i?.event+'"',i)))}init(e,n,i){if(i&&i!==Gn){var r,s=(r=Wi[i])!==null&&r!==void 0?r:new Je;return s._init(e,n,i),Wi[i]=s,Wi[Gn][i]=s,s}return this._init(e,n,i)}_init(e,n,i){var r,s;n===void 0&&(n={});var o,a=X(e)?e.trim():"";if(!a)return A.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return a!==((o=this.config)==null?void 0:o.token)?console.warn("[PostHog.js]","You have already initialized PostHog with a different project token! Re-initializing is a no-op, so events will keep going to the project this instance was initialized with. To capture into a second project, load PostHog once, then initialize a named instance after the SDK has loaded, e.g. posthog.init('"+a+"', { ... }, 'project2')"):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=To(n.defaults),n.debug=this.Cn(n.debug),this.Mn=n,this.Tn=[],n.person_profiles?this.xn=n.person_profiles:n.process_person&&(this.xn=n.process_person);var l=To(n.defaults),u=ru(n),c=fe({},l,u,{name:i,token:a});he(l.rageclick)&&he(u.rageclick)&&(c.rageclick=fe({},l.rageclick,u.rageclick)),he(l.session_recording)&&he(u.session_recording)&&(c.session_recording=fe({},l.session_recording,u.session_recording)),this.set_config(c),this.config.on_xhr_error&&A.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=n.disable_compression?void 0:je.GZipJS;var d=this.En();if(this.persistence=new xo(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new xo(I({},this.config,{persistence:"sessionStorage"}),d,!1),this.bn="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&be.N()){var f=be.H(this.bn);U(f)&&f.forEach((k=>{X(k)&&this.yn.add(k)}))}else be.q(this.bn);var h=I({},this.persistence.props),p=I({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new pm((k=>this.Pn(k)),this.config.request_queue_config),this.Rn=new mm(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new Qc(this),this.sessionPropsManager=new Xc(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((k,T,x)=>{(x!=null&&x.activityTimeout||x!=null&&x.sessionPastMaximumLength||x!=null&&x.crossTabAdoption)&&this.An()}))),this.Fn(),this.config.__preview_deferred_init_extensions?(A.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Ln(g)}),0)):(A.info("Initializing extensions synchronously"),this.Ln(g)),ne.DEBUG=ne.DEBUG||this.config.debug,ne.DEBUG&&A.info("Starting in debug mode",{this:this,config:n,thisC:I({},this.config),p:h,s:p}),!this.config.identity_distinct_id||(r=n.bootstrap)!=null&&r.distinctID||(n.bootstrap=I({},n.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((s=n.bootstrap)==null?void 0:s.distinctID)!==void 0){var m=n.bootstrap.distinctID,v=this.get_distinct_id(),E=this.persistence.get_property(ot);if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&E===Un)this.identify(m);else if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&E===vn)A.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{var S=this.config.get_device_id(Ht()),_=n.bootstrap.isIdentifiedID?S:m;this.persistence.set_property(ot,n.bootstrap.isIdentifiedID?vn:Un),this.register({distinct_id:m,$device_id:_})}}if(g)this.register_once({distinct_id:mr,$device_id:null},"");else if(!this.get_distinct_id()){var b=this.config.get_device_id(Ht());this.register_once({distinct_id:b,$device_id:b},""),this.persistence.set_property(ot,Un)}return ve(w,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),n.segment?(function(k,T){var x=k.config.segment;if(!x)return T();(function(F,$){var O=F.config.segment;if(!O)return $();var L=K=>{var V=()=>K.anonymousId()||Ht();F.config.get_device_id=V,K.id()&&(F.register({distinct_id:K.id(),$device_id:V()}),F.persistence.set_property(ot,vn)),$()},N=O.user();"then"in N&&De(N.then)?N.then(L):L(N)})(k,(()=>{x.register((F=>{typeof Promise<"u"&&Promise.resolve||Eo.warn("This browser does not have Promise support, and can not use the segment integration");var $=(O,L)=>{if(!L)return O;O.event.userId||O.event.anonymousId===F.get_distinct_id()||(Eo.info("No userId set, resetting PostHog"),F.reset()),O.event.userId&&O.event.userId!==F.get_distinct_id()&&(Eo.info("UserId set, identifying with PostHog"),F.identify(O.event.userId));var N=F.calculateEventProperties(L,O.event.properties);return O.event.properties=Object.assign({},N,O.event.properties),O};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:O=>$(O,O.event.event),page:O=>$(O,Vn),identify:O=>$(O,yo),screen:O=>$(O,"$screen")}})(k)).then((()=>{T()}))}))})(this,(()=>this.On())):this.On(),De(this.config._onCapture)&&this.config._onCapture!==us&&(A.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(k=>this.config._onCapture(k.event,k)))),this.config.ip&&A.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this.config.disableDeviceModel||(function(){return Df.apply(this,arguments)})().then((k=>{k&&this.register({[vo]:k})})).catch(us),this}Fn(){var e,n,i,r,s,o,a=(e=(n=this.config.__extensionClasses)==null?void 0:n.featureFlags)!==null&&e!==void 0?e:(i=Je.__defaultExtensionClasses)==null?void 0:i.featureFlags;a&&(this.featureFlags&&this.featureFlags instanceof a||((r=this.Dn)==null||r.call(this),this.Dn=void 0,this.featureFlags=new a(this)),De(this.featureFlags.onReloading)&&De(this.featureFlags.setup)?this.Dn||(this.Dn=this.featureFlags.onReloading((()=>{this.dn.emit("featureFlagsReloading",!0)})),this.$n().add(this.featureFlags)):(s=(o=this.featureFlags).initialize)==null||s.call(o))}Ln(e){var n,i,r,s,o,a,l,u=performance.now(),c=I({},Je.__defaultExtensionClasses,this.config.__extensionClasses),d=[];c.exceptions&&this.sn.push(this.exceptions=(n=this.exceptions)!==null&&n!==void 0?n:new c.exceptions(this)),c.historyAutocapture&&this.sn.push(this.historyAutocapture=new c.historyAutocapture(this)),c.tracingHeaders&&this.sn.push(this.tracingHeaders=new c.tracingHeaders(this)),c.siteApps&&this.sn.push(this.siteApps=new c.siteApps(this)),c.sessionRecording&&!e&&this.sn.push(this.sessionRecording=new c.sessionRecording(this)),this.config.disable_scroll_properties||d.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),c.autocapture&&this.sn.push(this.autocapture=new c.autocapture(this)),c.surveys&&this.sn.push(this.surveys=(i=this.surveys)!==null&&i!==void 0?i:new c.surveys(this)),c.logs&&this.sn.push(this.logs=(r=this.logs)!==null&&r!==void 0?r:new c.logs(this)),c.metrics&&this.sn.push(this.metrics=(s=this.metrics)!==null&&s!==void 0?s:new c.metrics(this)),c.conversations&&this.sn.push(this.conversations=(o=this.conversations)!==null&&o!==void 0?o:new c.conversations(this)),c.productTours&&this.sn.push(this.productTours=new c.productTours(this)),c.heatmaps&&this.sn.push(this.heatmaps=new c.heatmaps(this)),c.webVitalsAutocapture&&this.sn.push(this.webVitalsAutocapture=new c.webVitalsAutocapture(this)),c.exceptionObserver&&this.sn.push(this.exceptionObserver=new c.exceptionObserver(this)),c.deadClicksAutocapture&&this.sn.push(this.deadClicksAutocapture=new c.deadClicksAutocapture(this,Yg)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((f=>{f.initialize&&d.push((()=>{f.initialize==null||f.initialize()}))})),d.push((()=>{if(this.Nn){var f=this.Nn;this.Nn=void 0,this.sn.forEach((h=>h.onRemoteConfig==null?void 0:h.onRemoteConfig(f)))}})),this.qn(d,u)}qn(e,n){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,n)}),0);var i=e.shift();if(i)try{i()}catch(s){A.error("Error initializing extension:",s)}}var r=Math.round(performance.now()-n);this.register_for_session({[Xd]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[Qd]:r}),this.config.__preview_deferred_init_extensions&&A.info("PostHog extensions initialized ("+r+"ms)")}Zi(e){var n;if(!P||!P.body)return A.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.Zi(e)}),500);if(this.config.__preview_deferred_init_extensions&&(this.Nn=e),this.hn=e,this.compression=void 0,e.ok){var i,r=e.config;r.supportedCompression&&!this.config.disable_compression&&(this.compression=j(r.supportedCompression,je.GZipJS)?je.GZipJS:j(r.supportedCompression,je.Base64)?je.Base64:void 0),(i=r.analytics)!=null&&i.endpoint&&(this.analyticsDefaultEndpoint=r.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:pa}),(n=this.jn)==null||n.handleRemoteConfig(e),this.sn.forEach((s=>s.onRemoteConfig==null?void 0:s.onRemoteConfig(e)))}On(){try{this.config.loaded(this)}catch(i){A.critical("`loaded` function failed",i)}if(this.Bn(),this.config.internal_or_test_user_hostname&&me!=null&&me.hostname){var e=me.hostname,n=this.config.internal_or_test_user_hostname;(typeof n=="string"?e===n:n.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.gn())&&this.Hn()}),1),this.Un=new kf(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()&&vr(this.__request_queue,(e=>this.Pn(e))),this.__request_queue=[],this.Bn()}_handle_unload(){var e,n,i,r,s;(e=this.surveys)==null||e.handlePageUnload==null||e.handlePageUnload(),(n=this.metrics)==null||n.flush("sendBeacon"),this.config.request_batching?(this.zn()&&this.capture(_o),(i=this.logs)==null||i.flushLogs("sendBeacon"),(r=this.In)==null||r.unload(),(s=this.Rn)==null||s.unload()):this.zn()&&this.capture(_o,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?Vf?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)?e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:429})):(e.transport=e.transport||this.config.api_transport,e.headers=I({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,(C(this.config.disable_beacon)?this.config.__preview_disable_beacon:this.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(n=>{var i,r,s,o=I({},n);o.timeout=o.timeout||6e4;var a,l,u,c,d,f=(i=o.transport)!==null&&i!==void 0?i:"fetch";f==="sendBeacon"&&C(o.compression)&&o.data&&(o.compression=je.Base64),o.method==="POST"&&o.data&&(o.timestampMode==="capture-body"?o.data={api_key:(l=(d=(c=U(a=o.data)?a:[a])[0])==null||(u=d.properties)==null?void 0:u.token)!==null&&l!==void 0?l:d?.token,batch:c,sent_at:new Date().toISOString()}:o.timestampMode==="body"&&(o.data=(function(m,v){return v===void 0&&(v=new Date().toISOString()),U(m)?m.map((E=>I({},E,{sent_at:v}))):I({},m,{sent_at:v})})(o.data))),o.url=Zc(o.url,o.method,o.compression,o.timestampMode);var h=Lr.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),p=(r=(s=(function(m,v){for(var E=0;m.length>E;E++)if(m[E].transport===f)return m[E]})(h))==null?void 0:s.method)!==null&&r!==void 0?r:h[0].method;if(!p)throw new Error("No available transport method");var g=m=>{try{p(m)}catch(v){Nf(v)?A.warn(v):A.error(v),o.callback==null||o.callback({statusCode:0,error:v})}};f!=="sendBeacon"&&o.data&&o.compression===je.GZipJS&&Tp&&typeof Promise<"u"&&!Mr?fm(o).then((m=>{g(m)})).catch((m=>{if(vc(m))return Mr=!0,void g(I({},o,{compression:void 0,url:Zc(n.url,n.method,void 0,n.timestampMode)}));(v=>{if(!v||typeof v!="object")return!1;var E="name"in v?String(v.name):"";return vc(v)||E===dd})(m)&&(Mr=!0),g(o)})):p(o)})(I({},e,{callback:n=>{var i,r;this.rateLimiter.checkForLimiting(n),400>n.statusCode||(i=(r=this.config).on_request_error)==null||i.call(r,n),e.callback==null||e.callback(n)}}))):e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:0}))}Pn(e){this.Rn?this.Rn.retriableRequest(e):this._send_request(e)}_execute_array(e){Ro++;try{var n,i=[],r=[],s=[];vr(e,(a=>{if(a)if(U(n=a[0]))s.push(a);else if(De(a))try{a.call(this)}catch(l){A.error("Error executing queued PostHog call",a,l)}else U(a)&&n==="alias"?i.push(a):U(a)&&n.indexOf("capture")!==-1&&De(this[n])?s.push(a):r.push(a)}));var o=function(a,l){vr(a,(function(u){try{if(U(u[0])){var c=l;ie(u,(function(d){c=c[d[0]].apply(c,d.slice(1))}))}else l[u[0]].apply(l,u.slice(1))}catch(d){A.error("Error executing queued PostHog call",u,d)}}))};o(i,this),o(r,this),o(s,this)}finally{Ro--}}push(e){if(Ro>0&&U(e)&&X(e[0])){var n=Je.prototype[e[0]];De(n)&&n.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,n,i){var r,s,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.In){if(this.is_capturing())if(!C(e)&&X(e)){var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var c=i!=null&&i.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(c==null||!c.isRateLimited){n!=null&&n.$current_url&&!X(n?.$current_url)&&(A.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),n==null||delete n.$current_url),e!=="$exception"||i!=null&&i.Wn||A.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,f=i?.timestamp||d,h=Ec(i?.uuid,Ht),p={uuid:h,event:e,properties:this.calculateEventProperties(e,n||{},f,h)};e===Vn&&this.config.__preview_capture_bot_pageviews&&u&&(p.event="$bot_pageview",p.properties.$browser_type="bot"),c&&(p.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&p.properties.$feature_flag_has_experiment===!1&&this.get_property(Zr)===!0;i?.$set&&!g&&(p.$set=i?.$set);var m=i?.$unset;m&&(p.$unset=m);var v,E,S,_=g?void 0:this.Vn(i?.$set_once,e!==Ac,e===yo);if(_&&(p.$set_once=_),i!=null&&i._noTruncate||(s=this.config.properties_string_max_length,o=p,a=L=>X(L)?L.slice(0,s):L,l=new Set,p=(function L(N,K){if(N!==Object(N))return a?a(N):N;if(!l.has(N)){var V;if(l.add(N),U(N))V=[],vr(N,(R=>{V.push(L(R))}));else{var M={};ie(N,((R,Z)=>{l.has(R)||(M[Z]=L(R))})),V=M}return V}})(o)),p.timestamp=f,C(i?.timestamp)||(p.properties.$event_time_override_provided=!0,p.properties.$event_time_override_system_time=d),g&&(p.properties=(function(L,N){N===void 0&&(N=[]);var K={},V=M=>{L[M]!==void 0&&(K[M]=L[M])};return $p.forEach(V),N.forEach(V),K})(p.properties,Pm)),e===zt.DISMISSED||e===zt.SENT){var b=n?.[ko.SURVEY_ID],k=n?.[ko.SURVEY_ITERATION];qf({id:b,current_iteration:k}),p.$set=I({},p.$set,{[(v={id:b,current_iteration:k},E=e===zt.SENT?"responded":"dismissed",S="$survey_"+E+"/"+v.id,v.current_iteration&&v.current_iteration>0&&(S="$survey_"+E+"/"+v.id+"/"+v.current_iteration),S)]:!0})}else e===zt.SHOWN&&(p.$set=I({},p.$set,{[ko.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===rm.SHOWN){var T=n?.[zc.TOUR_TYPE];T&&(p.$set=I({},p.$set,{[zc.TOUR_LAST_SEEN_DATE+"/"+T]:new Date().toISOString()}))}var x=I({},p.properties.$set,p.$set);if(Kt(x)||this.setPersonPropertiesForFlags(x),!H(this.config.before_send)){var F=this.Pt(p);if(!F)return;(p=F).uuid=Ec(p.uuid,Ht)}this.dn.emit("eventCaptured",p);var $=(r=i?._url)!==null&&r!==void 0?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),O={method:"POST",url:$,data:p,compression:"best-available",timestampMode:i?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test($)?"body":"capture-body",batchKey:i?._batchKey,transport:i?.transport};return!this.config.request_batching||i&&(i==null||!i._batchKey)||i!=null&&i.send_instantly?this.Pn(O):this.In.enqueue(O),p}A.critical("This capture call is ignored due to client rate limiting.")}}else A.error("No event name provided to posthog.capture")}else A.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(n=>e(n.event,n)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new Am(this)}cn(e){this._n.push(e);var n=!0;return()=>{if(n){n=!1;var i=this._n.indexOf(e);i!==-1&&this._n.splice(i,1)}}}calculateEventProperties(e,n,i,r,s){if(i=i||new Date,!this.persistence||!this.sessionPersistence)return n;var o=s?void 0:this.persistence.remove_event_timer(e),a=I({},n);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.gn()&&(a[Zd]=!0),e==="$snapshot"){var l=I({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!X(a.distinct_id)&&!ke(a.distinct_id)||Ko(a.distinct_id))&&A.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=(function(b,k,T,x){var F,$,O,L;if(x===void 0&&(x=!1),!Ve)return{};var N,K=b?[...ri,...k||[]]:[],V=(function(Bn){for(var qe=0;wc.length>qe;qe++){var Dn=wc[qe],Mt=Dn[1],Lt=Dn[0].exec(Bn),ut=Lt&&(De(Mt)?Mt(Lt,Bn):Mt);if(ut)return ut}return["",""]})(Ve),M=V[0],R=V[1],Z=(N=typeof navigator<"u"?navigator:void 0)!=null&&N.brave?{brave:!0}:{},Ce={};C(T)||(Ce.detectGoogleSearchApp=T);var oe={},ye=(F=navigator)==null||(F=F.userAgentData)==null?void 0:F.platform,$e=($=navigator)==null?void 0:$.maxTouchPoints,ae=w==null||(O=w.screen)==null?void 0:O.width,Ie=w==null||(L=w.screen)==null?void 0:L.height,Se=w?.devicePixelRatio;C(ye)||(oe.userAgentDataPlatform=ye),C($e)||(oe.maxTouchPoints=$e),C(ae)||(oe.screenWidth=ae),C(Ie)||(oe.screenHeight=Ie),C(Se)||(oe.devicePixelRatio=Se);var Be,wt,ge,Ye,bt,mn,Re,Pe,$t=fe(ll({$os:M,$os_version:R,$browser:Nd(Ve,navigator.vendor,Z,Ce),$device:bc(Ve),$device_type:(wt=Ve,ge=oe,Pe=bc(wt),Pe===_d||Pe===vd||Pe==="Kobo"||Pe==="Kindle Fire"||Pe===Rd?ei:Pe===Gi||Pe===Xn||Pe===Ki||Pe===Jo?"Console":Pe===wd?"Wearable":Pe?it:ge?.userAgentDataPlatform==="Android"&&((Ye=ge?.maxTouchPoints)!==null&&Ye!==void 0?Ye:0)>0?600>Math.min((bt=ge?.screenWidth)!==null&&bt!==void 0?bt:0,(mn=ge?.screenHeight)!==null&&mn!==void 0?mn:0)/((Re=ge?.devicePixelRatio)!==null&&Re!==void 0?Re:1)?it:ei:"Desktop"),$timezone:If(),$timezone_offset:tm()}),{$current_url:Zi(x?fn(me?.href):me?.href,K,Xi),$host:me?.host,$pathname:me?.pathname,$raw_user_agent:Ve.length>1e3?Ve.substring(0,997)+"...":Ve,$browser_version:Xp(Ve,navigator.vendor,Z,Ce),$browser_language:qc(),$browser_language_prefix:(Be=qc(),typeof Be=="string"?Be.split("-")[0]:void 0),$screen_height:w?.screen.height,$screen_width:w?.screen.width,$viewport_height:w?.innerHeight,$viewport_width:w?.innerWidth,$lib:ne.LIB_NAME,$lib_version:ne.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return ne.SDK_DIST_CHANNEL&&($t.$sdk_dist_channel=ne.SDK_DIST_CHANNEL),$t})(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties,this.config.detect_google_search_app,this.config.disable_capture_url_hashes);if(this.sessionManager){var d=this.sessionManager.checkAndGetSessionAndWindowId(s,i.getTime()),f=d.windowId;a.$session_id=d.sessionId,a.$window_id=f}this.sessionPropsManager&&fe(a,this.sessionPropsManager.getSessionProps());try{var h;this.sessionRecording&&fe(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(h=this.Rn)==null?void 0:h.length}catch(b){a.$sdk_debug_error_capturing_properties=String(b)}if(this.requestRouter.region===xa&&(a.$lib_custom_api_host=this.config.api_host),u=e!==Vn||s?e!==_o||s?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(i):this.pageViewManager.doPageView(i,r),a=fe(a,u),e===Vn&&P&&(a.title=P.title),!C(o)){var p=i.getTime()-o;a.$duration=parseFloat((p/1e3).toFixed(3))}Ve&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();ie(["$referrer","$referring_domain"],(b=>{b in g&&delete m[b]}));var v={};if(this._n.length>0)for(var E of this._n.slice())try{fe(v,E())}catch(b){A.error("Failed to produce browser extension event properties",b)}(a=fe({},c,g,m,I({},v,a))).$is_identified=this._isIdentified(),U(this.config.property_denylist)?ie(this.config.property_denylist,(function(b){delete a[b]})):A.error(zf+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var S=this.config.sanitize_properties;S&&(A.error(iu),a=S(a,e));var _=this.Zn();return a.$process_person_profile=_,_&&!s&&this.Gn("_calculate_event_properties"),a}Vn(e,n,i){var r;if(n===void 0&&(n=!0),i===void 0&&(i=!1),!this.persistence||!this.Zn()||this.mn&&!i)return e;var s=this.persistence.get_initial_props(),o=(r=this.sessionPropsManager)==null?void 0:r.getSetOnceProps(),a=fe({},s,o||{},e||{}),l=this.config.sanitize_properties;return l&&(A.error(iu),a=l(a,"$set_once")),n&&(this.mn=!0),Kt(a)?void 0:a}register(e,n){var i;(i=this.persistence)==null||i.register(e,n)}register_once(e,n,i){var r;(r=this.persistence)==null||r.register_once(e,n,i)}register_for_session(e){var n;(n=this.sessionPersistence)==null||n.register(e),Object.keys(e).forEach((i=>this.yn.add(i))),this.Qn()}unregister(e){var n;(n=this.persistence)==null||n.unregister(e)}unregister_for_session(e){var n;(n=this.sessionPersistence)==null||n.unregister(e),this.yn.delete(e),this.Qn()}Kn(e,n){this.register({[e]:n})}An(){this.yn.forEach((e=>{var n;(n=this.sessionPersistence)==null||n.unregister(e)})),this.yn.clear(),this.Qn()}Qn(){var e;if(this.bn)if(this.config.persistence==="memory"||(e=this.sessionPersistence)!=null&&e.xi||!be.N())be.q(this.bn);else{var n=[];this.yn.forEach((i=>n.push(i))),n.length>0?be.F(this.bn,n):be.q(this.bn)}}getFeatureFlag(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlag(e,n)}getFeatureFlagPayload(e){var n;return(n=this.featureFlags)==null?void 0:n.getFeatureFlagPayload(e)}getFeatureFlagResult(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlagResult(e,n)}getAllFeatureFlags(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.getAllFeatureFlags())!==null&&e!==void 0?e:[]}isFeatureEnabled(e,n){var i,r;return(i=(r=this.featureFlags)==null?void 0:r.isFeatureEnabled(e,n))!==null&&i!==void 0?i:n?.defaultValue}reloadFeatureFlags(){var e;(e=this.featureFlags)==null||e.reloadFeatureFlags()}updateFlags(e,n,i){var r;(r=this.featureFlags)==null||r.updateFlags(e,n,i)}updateEarlyAccessFeatureEnrollment(e,n,i){var r;(r=this.featureFlags)==null||r.updateEarlyAccessFeatureEnrollment(e,n,i)}getEarlyAccessFeatures(e,n,i){var r;return n===void 0&&(n=!1),(r=this.featureFlags)==null?void 0:r.getEarlyAccessFeatures(e,n,i)}on(e,n){return this.dn.on(e,n)}onFeatureFlags(e){return this.featureFlags?this.featureFlags.onFeatureFlags(e):(e([],{},{errorsLoading:!0}),()=>{})}onSurveysLoaded(e){return this.surveys?this.surveys.onSurveysLoaded(e):(e([],{isLoaded:!1,error:xi}),()=>{})}onSessionId(e){var n,i;return(n=(i=this.sessionManager)==null?void 0:i.onSessionId(e))!==null&&n!==void 0?n:()=>{}}getSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getSurveys(e,n):e([],{isLoaded:!1,error:xi})}getActiveMatchingSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,n):e([],{isLoaded:!1,error:xi})}renderSurvey(e,n){var i;(i=this.surveys)==null||i.renderSurvey(e,n)}displaySurvey(e,n){var i;n===void 0&&(n=Em),(i=this.surveys)==null||i.displaySurvey(e,n)}cancelPendingSurvey(e){var n;(n=this.surveys)==null||n.cancelPendingSurvey(e)}canRenderSurvey(e){var n,i;return(n=(i=this.surveys)==null?void 0:i.canRenderSurvey(e))!==null&&n!==void 0?n:{visible:!1,disabledReason:xi}}canRenderSurveyAsync(e,n){var i,r;return n===void 0&&(n=!1),(i=(r=this.surveys)==null?void 0:r.canRenderSurveyAsync(e,n))!==null&&i!==void 0?i:Promise.resolve({visible:!1,disabledReason:xi})}Jn(e){return!e||Ko(e)?(A.critical("Unique user id has not been set in posthog.identify"),!1):e===mr?(A.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.'),!1):!["distinct_id","distinctid"].includes(e.toLowerCase())&&!["undefined","null"].includes(e.toLowerCase())||(A.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.'),!1)}identify(e,n,i){if(!this.__loaded||!this.persistence)return A.uninitializedWarning("posthog.identify");if(ke(e)&&(e=e.toString(),A.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.Jn(e)&&this.Gn("posthog.identify")){var r=this.get_distinct_id();this.register({$user_id:e}),this.get_property(Yi)||this.register_once({$had_persisted_distinct_id:!0,$device_id:r},""),e!==r&&e!==this.get_property(Fi)&&(this.unregister(Fi),this.register({distinct_id:e}));var s,o=(this.persistence.get_property(ot)||Un)===Un,a=e!==r,l=!a&&o;if(a&&o)this.persistence.set_property(ot,vn),this.setPersonPropertiesForFlags({$set:n||{},$set_once:i||{}},!1),this.capture(yo,{distinct_id:e,$anon_distinct_id:r},{$set:n||{},$set_once:i||{}}),this.Sn=Fo(e,n,i),(s=this.featureFlags)==null||s.setAnonymousDistinctId(r);else if(l){this.persistence.set_property(ot,vn);var u=n||{},c=i||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=Fo(e,n,i)}else(n||i)&&this.setPersonProperties(n,i);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Cn)):l&&(n||i)&&this.reloadFeatureFlags()}}setPersonProperties(e,n){if((e||n)&&this.Gn("posthog.setPersonProperties")){var i=Fo(this.get_distinct_id(),e,n);this.Sn!==i?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:n||{}},!0),this.capture("$set",{$set:e||{},$set_once:n||{}}),this.Sn=i):A.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}unsetPersonProperties(e){var n,i=(U(e)?e:[e]).filter((r=>X(r)&&r.length>0));i.length!==0&&this.Gn("posthog.unsetPersonProperties")&&((n=this.featureFlags)==null||n.unsetPersonPropertiesForFlags(i,!0),this.capture("$set",{$unset:i}),this.Sn=null)}group(e,n,i){if(e&&n){var r=this.getGroups(),s=r[e]!==n;if(s&&this.resetGroupPropertiesForFlags(e),this.register({$groups:I({},r,{[e]:n})}),s||i){var o={$group_type:e,$group_key:n};i&&(o.$group_set=i),this.capture(Ac,o)}i&&this.setGroupPropertiesForFlags({[e]:i}),s&&!i&&this.reloadFeatureFlags()}else A.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),(i=this.featureFlags)==null||i.setPersonPropertiesForFlags(e,n)}resetPersonPropertiesForFlags(e){var n;e===void 0&&(e=!0),(n=this.featureFlags)==null||n.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((i=this.featureFlags)==null||i.setGroupPropertiesForFlags(e,n))}resetGroupPropertiesForFlags(e){var n;(n=this.featureFlags)==null||n.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,n){var i,r,s,o,a,l,u,c,d,f;if(n===void 0&&(n=!1),A.info("reset"),!this.__loaded)return A.uninitializedWarning("posthog.reset");var h,p=this.get_property(Yi),g=this.get_property(vo),m=this.get_property(An),v=this.is_capturing();if(this.consent.reset(),n||!v||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after."),(i=this.persistence)==null||i.clear(),(r=this.sessionPersistence)==null||r.clear(),this.yn.clear(),this.Qn(),C(m)||(h=this.persistence)==null||h.register({[An]:m}),(s=this.surveys)==null||s.reset(),(o=this.Un)==null||o.stop(),(a=this.featureFlags)==null||a.reset(),(l=this.conversations)==null||l.reset(),(u=this.logs)==null||u.reset(),(c=this.metrics)==null||c.reset(),(d=this.persistence)==null||d.set_property(ot,Un),(f=this.sessionManager)==null||f.resetSessionId(),this.Sn=null,this.config.cookieless_mode===Wt)this.register_once({distinct_id:mr,$device_id:null},"");else{var E=this.config.get_device_id(Ht());this.register_once({distinct_id:E,$device_id:e?E:p},""),e||C(g)||this.register({[vo]:g})}this.register({$last_posthog_reset:new Date().toISOString()},1),delete this.config.identity_distinct_id,delete this.config.identity_hash,this.reloadFeatureFlags()}shutdown(e){var n=this;return se((function*(){var i,r,s,o,a,l,u;if(n.__loaded){(i=n.Un)==null||i.stop(),(r=n.jn)==null||r.dispose(),(s=n.sessionRecording)==null||s.dispose(),(o=n.logs)==null||o.flushLogs("sendBeacon"),(a=n.metrics)==null||a.flush("sendBeacon"),(l=n.In)==null||l.unload(),(u=n.Rn)==null||u.unload();try{var c;(c=n.featureFlags)==null||c.destroy()}catch(d){A.error("Error while destroying feature flags",d)}}else A.uninitializedWarning("posthog.shutdown")}))()}setIdentity(e,n){var i;this.config.identity_distinct_id=e,this.config.identity_hash=n,this.alias(e),(i=this.conversations)==null||i.Xn()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,(e=this.conversations)==null||e.ts()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,n;return(e=(n=this.sessionManager)==null?void 0:n.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var n=this.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.sessionStartTimestamp,r=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+n.sessionId);if(e!=null&&e.withTimestamp&&i){var s,o=(s=e.timestampLookBack)!==null&&s!==void 0?s:10;if(!i)return r;r+="?t="+Math.max(Math.floor((new Date().getTime()-i)/1e3)-o,0)}return r}alias(e,n){return e===this.get_property(zd)?(A.critical("Attempting to create alias for existing People user - aborting."),-2):this.Gn("posthog.alias")?(C(n)&&(n=this.get_distinct_id()),e!==n?(this.Kn(Fi,e),this.capture("$create_alias",{alias:e,distinct_id:n})):(A.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var n=I({},this.config);if(he(e)){var i,r,s,o,a,l,u,c,d,f,h,p;fe(this.config,ru(e));var g=this.En();(i=this.persistence)==null||i.update_config(this.config,n,g),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new xo(I({},this.config,{persistence:"sessionStorage"}),g,!1);var m=this.Cn(this.config.debug);mt(m)&&(this.config.debug=m),mt(this.config.debug)&&(this.config.debug?(ne.DEBUG=!0,le.N()&&le.F("ph_debug",!0),A.info("set_config",{config:e,oldConfig:n,newConfig:I({},this.config)})):(ne.DEBUG=!1,le.N()&&le.q("ph_debug"))),(r=this.featureFlags)==null||r.updateConfig==null||r.updateConfig(this.config,this.Qi()),(s=this.exceptionObserver)==null||s.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(f=this.deadClicksAutocapture)==null||f.startIfEnabledOrStop(),(h=this.surveys)==null||h.loadIfEnabled(),this.es(),(p=this.externalIntegrations)==null||p.startIfEnabledOrStop()}}_overrideSDKInfo(e,n){ne.LIB_NAME=e,ne.LIB_VERSION=n}startSessionRecording(e){var n,i,r,s,o,a=e===!0,l={sampling:a||!(e==null||!e.sampling),linked_flag:a||!(e==null||!e.linked_flag),url_trigger:a||!(e==null||!e.url_trigger),event_trigger:a||!(e==null||!e.event_trigger)};Object.values(l).some(Boolean)&&((n=this.sessionManager)==null||n.checkAndGetSessionAndWindowId(),l.sampling&&((i=this.sessionRecording)==null||i.overrideSampling()),l.linked_flag&&((r=this.sessionRecording)==null||r.overrideLinkedFlag()),l.url_trigger&&((s=this.sessionRecording)==null||s.overrideTrigger("url")),l.event_trigger&&((o=this.sessionRecording)==null||o.overrideTrigger("event"))),this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,n){if(this.exceptions){var i=new Error("PostHog syntheticException"),r=this.exceptions.buildProperties(e,{handled:!0,syntheticException:i});return this.exceptions.sendExceptionEvent(I({},r,n))}}addExceptionStep(e,n){var i;(i=this.exceptions)==null||i.addExceptionStep(e,n)}captureLog(e){var n;(n=this.logs)==null||n.captureLog(e)}get logger(){var e,n;return(e=(n=this.logs)==null?void 0:n.logger)!==null&&e!==void 0?e:Je.rs}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var n,i;return(n=(i=this.toolbar)==null?void 0:i.loadToolbar(e))!==null&&n!==void 0&&n}get_property(e){var n;return(n=this.persistence)==null?void 0:n.props[e]}getSessionProperty(e){var n;return(n=this.sessionPersistence)==null?void 0:n.props[e]}toString(){var e,n=(e=this.config.name)!==null&&e!==void 0?e:Gn;return n!==Gn&&(n=Gn+"."+n),n}_isIdentified(){var e,n;return((e=this.persistence)==null?void 0:e.get_property(ot))===vn||((n=this.sessionPersistence)==null?void 0:n.get_property(ot))===vn}Zn(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles===pa&&!this._isIdentified()&&Kt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[Fi])&&((n=this.persistence)==null||(n=n.props)==null||!n[es]))}zn(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Zn()||this.Gn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.Gn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}Gn(e){return this.config.person_profiles==="never"?(A.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Kn(es,!0),!0)}En(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut();return this.config.disable_persistence||e&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!==kn)}es(){var e,n,i,r,s=this.En();return((e=this.persistence)==null?void 0:e.xi)!==s&&((i=this.persistence)==null||i.set_disabled(s)),((n=this.sessionPersistence)==null?void 0:n.xi)!==s&&((r=this.sessionPersistence)==null||r.set_disabled(s)),s&&(this.yn.clear(),this.Qn()),s}opt_in_capturing(e){var n;if(this.config.cookieless_mode!==Wt){if(this.gn()){var i,r,s,o,a;this.Yn(!0,!0),(i=this.sessionManager)==null||i.destroy(),(r=this.pageViewManager)==null||r.destroy(),this.sessionManager=new Qc(this),this.pageViewManager=new Wc(this),this.persistence&&(this.sessionPropsManager=new Xc(this,this.sessionManager,this.persistence));var l,u=(s=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&s!==void 0?s:(a=Je.__defaultExtensionClasses)==null?void 0:a.sessionRecording;u&&(this.sessionRecording=this.pn(this.sessionRecording,new u(this)),this.hn&&((l=this.sessionRecording)==null||l.onRemoteConfig==null||l.onRemoteConfig(this.hn)))}var c,d;this.consent.optInOut(!0),this.es(),this.Bn(),(n=this.sessionRecording)==null||n.startIfEnabledOrStop(),this.config.cookieless_mode==kn&&((c=this.surveys)==null||c.loadIfEnabled()),(C(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((d=e?.captureEventName)!==null&&d!==void 0?d:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hn()}else A.warn(nu)}opt_out_capturing(){var e,n,i;this.config.cookieless_mode!==Wt?(this.config.cookieless_mode===kn&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===kn&&(this.register({distinct_id:mr,$device_id:null}),(e=this.sessionRecording)==null||e.stopRecording(),this.sessionRecording=void 0,(n=this.sessionManager)==null||n.destroy(),(i=this.pageViewManager)==null||i.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.Hn(),this.Bn())):A.warn(nu)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===Wt||(this.config.cookieless_mode===kn?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return Ue?Bf(Ue,this.config.custom_blocked_useragents):void 0}Hn(){P&&(P.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(Vn,{title:P.title},{send_instantly:!0}),this.kn&&(P.removeEventListener(ts,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),ve(P,ts,this.kn)))}debug(e){e===!1?(w?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(w?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}Qi(){var e=this.Mn||{};return"advanced_disable_flags"in e?!!e.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(A.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(function(n,i,r,s,o){var a=i in n&&!H(n[i]),l=r in n&&!H(n[r]);return a?n[i]:!!l&&(o&&o.warn("Config field '"+r+"' is deprecated. Please use '"+i+"' instead. The old field will be removed in a future major version."),n[r])})(e,"advanced_disable_flags","advanced_disable_decide",0,A)}Pt(e){var n;if(H(this.config.before_send))return e;var i=Object.keys((n=e.properties)!==null&&n!==void 0?n:{}).filter(jp),r=U(this.config.before_send)?this.config.before_send:[this.config.before_send],s=e;for(var o of r){if(s=o(s),H(s)){var a="Event '"+e.event+"' was rejected in beforeSend function";return Dp(e.event)?A.warn(a+". This can cause unexpected behavior."):A.info(a),null}s.properties&&!Kt(s.properties)||A.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}for(var l of i)if(s.properties&&H(s.properties[l]))return A.warn("Event '"+e.event+"' had its '"+l+"' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped."),null;return s}getPageViewId(){var e;return(e=this.pageViewManager.ui)==null?void 0:e.pageViewId}captureTraceFeedback(e,n){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:n})}captureTraceMetric(e,n,i){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:n,$ai_metric_value:String(i)})}Cn(e){var n=mt(e)&&!e,i=le.N()&&le.P("ph_debug")==="true";return!n&&(!!i||e)}}Je.__defaultExtensionClasses={},Je.rs=(()=>{var t=()=>{};return{trace:t,debug:t,info:t,warn:t,error:t,fatal:t}})(),(function(t,e){for(var n=0;e.length>n;n++)t.prototype[e[n]]=Ag(t.prototype[e[n]])})(Je,["identify"]);class su{constructor(e){this.disabled=e===!1;var n=he(e)?e:{};this.thresholdPx=n.threshold_px||30,this.timeoutMs=n.timeout_ms||1e3,this.clickCount=n.click_count||3,this.clicks=[]}isRageClick(e,n,i){if(this.disabled)return!1;var r=this.clicks[this.clicks.length-1];if(r&&Math.abs(e-r.x)+Math.abs(n-r.y)i-r.timestamp){if(this.clicks.push({x:e,y:n,timestamp:i}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:n,timestamp:i}];return!1}}var $o="$copy_autocapture",Mo=pe("[AutoCapture]");function Lo(t,e){return e.length>t?e.slice(0,t)+"...":e}function Tm(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!hn(e));return e}function $m(t,e){var n,i,r=e.e,s=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!hn(t))return{props:{}};for(var c=[t],d=new Set([t]),f=t;f.parentNode&&!Qe(f,"body")&&lf>c.length;)if(af(f.parentNode)){var h=f.parentNode.host;if(d.has(h))break;d.add(h),c.push(h),f=h}else{if(!hn(f.parentNode)||d.has(f.parentNode))break;d.add(f.parentNode),c.push(f.parentNode),f=f.parentNode}var p,g,m=[],v={},E=!1,S=!1;if(ie(c,(x=>{var F=va(x);if(Qe(x,"a")){var $=x.getAttribute("href");E=!!(F&&$&&Ui($))&&(u?fn($):$)}j(rs(x),"ph-no-capture")&&(S=!0),m.push((function(L,N,K,V,M){M===void 0&&(M=!1);var R=L.tagName.toLowerCase(),Z={tag_name:R};ul.indexOf(R)>-1&&!K&&(Z.$el_text=R.toLowerCase()==="a"||R.toLowerCase()==="button"?Lo(1024,jc(L)):Lo(1024,Ji(L)));var Ce=rs(L);Ce.length>0&&(Z.classes=Ce.filter((function(ae){return ae!==""}))),ie(L.attributes,(function(ae){var Ie;if((!hf(L)||["name","id","class","aria-label"].indexOf(ae.name)!==-1)&&(V==null||!V.includes(ae.name))&&!N&&Ui(ae.value)&&(!X(Ie=ae.name)||Ie.substring(0,10)!=="_ngcontent"&&Ie.substring(0,7)!=="_nghost")){var Se=ae.value;ae.name==="class"&&(Se=cl(Se).join(" ")),Z["attr__"+ae.name]=Lo(1024,ae.name==="href"&&M?fn(Se):Se)}}));for(var oe=1,ye=1,$e=L;$e=Tm($e);)oe++,$e.tagName===L.tagName&&ye++;return Z.nth_child=oe,Z.nth_of_type=ye,Z})(x,s,o,a,u));var O=(function(L){if(!va(L))return{};var N={};return ie(L.attributes,(function(K){if(K.name&&K.name.indexOf("data-ph-capture-attribute")===0){var V=K.name.replace("data-ph-capture-attribute-",""),M=K.value;V&&M&&Ui(M)&&(N[V]=M)}})),N})(x);fe(v,O)})),S)return{props:{},explicitNoCapture:S};if(o||(m[0].$el_text=Qe(t,"a")||Qe(t,"button")?jc(t):Ji(t)),E){var _,b;m[0].attr__href=E;var k=(_=ss(E))==null?void 0:_.host,T=w==null||(b=w.location)==null?void 0:b.host;k&&T&&k!==T&&(p=E)}return{props:fe({$event_type:r.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(x){return x.map((F=>{var $,O,L="";if(F.tag_name&&(L+=F.tag_name),F.attr_class)for(var N of(F.attr_class.sort(),F.attr_class))L+="."+N.replace(/"/g,"");var K=I({},F.text?{text:F.text}:{},{"nth-child":($=F.nth_child)!==null&&$!==void 0?$:0,"nth-of-type":(O=F.nth_of_type)!==null&&O!==void 0?O:0},F.href?{href:F.href}:{},F.attr_id?{attr_id:F.attr_id}:{},F.attributes),V={};return $r(K).sort(((M,R)=>M[0].localeCompare(R[0]))).forEach((M=>{var R=M[1];return V[Uc(M[0].toString())]=Uc(R.toString())})),(L+=":")+$r(V).map((M=>M[0]+'="'+M[1]+'"')).join("")})).join(";")})((function(x){return x.map((F=>{var $,O,L={text:($=F.$el_text)==null?void 0:$.slice(0,400),tag_name:F.tag_name,href:(O=F.attr__href)==null?void 0:O.slice(0,2048),attr_class:Gg(F),attr_id:F.attr__id,nth_child:F.nth_child,nth_of_type:F.nth_of_type,attributes:{}};return $r(F).filter((N=>N[0].indexOf("attr__")===0)).forEach((N=>L.attributes[N[0]]=N[1])),L}))})(g)))},(n=m[0])!=null&&n.$el_text?{$el_text:(i=m[0])==null?void 0:i.$el_text}:{},p&&r.type==="click"?{$external_click_url:p}:{},v)}}var Ii=pe("[ExceptionAutocapture]"),ou=()=>{},Mm=pe("[TracingHeaders]"),wn=pe("[Web Vitals]"),au=9e5,lu="disabled",cu="lazy_loading",ki="awaiting_config",Sr="missing_config";pe("[SessionRecording]"),pe("[SessionRecording]");var Ia="[SessionRecording]",Bt=pe(Ia),Lm=pe("[Heatmaps]");function No(t){return he(t)&&"clientX"in t&&"clientY"in t&&ke(t.clientX)&&ke(t.clientY)}var xr=pe("[Product Tours]"),Oo=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(sl))},Nm=["$set_once","$set"],Et=pe("[SiteApps]"),uu="Error while initializing PostHog app with config id ";function qn(t,e,n){if(H(t))return!1;switch(n){case"exact":return t===e;case"contains":var i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(i,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}class Om{constructor(e){this.ns=new pl,this.ss=(n,i)=>this.os(n,i)&&this.ls(n,i)&&this.us(n,i)&&this.hs(n,i),this.os=(n,i)=>i==null||!i.event||n?.event===i?.event,this._instance=e,this.ds=new Set,this.vs=new Set}init(){var e,n;C((e=this._instance)==null?void 0:e._addCaptureHook)||(n=this._instance)==null||n._addCaptureHook(((i,r)=>{this.on(i,r)}))}register(e){var n,i;if(!C((n=this._instance)==null?void 0:n._addCaptureHook)&&(e.forEach((o=>{var a,l;(a=this.vs)==null||a.add(o),(l=o.steps)==null||l.forEach((u=>{var c;(c=this.ds)==null||c.add(u?.event||"")}))})),(i=this._instance)!=null&&i.autocapture)){var r,s=new Set;e.forEach((o=>{var a;(a=o.steps)==null||a.forEach((l=>{l!=null&&l.selector&&s.add(l?.selector)}))})),(r=this._instance)==null||r.autocapture.setElementSelectors(s)}}on(e,n){var i;n!=null&&e.length!=0&&(this.ds.has(e)||this.ds.has(n.event))&&this.vs&&((i=this.vs)==null?void 0:i.size)>0&&this.vs.forEach((r=>{this.cs(n,r)&&this.ns.emit("actionCaptured",r.name)}))}fs(e){this.onAction("actionCaptured",(n=>e(n)))}cs(e,n){if(n?.steps==null)return!1;for(var i of n.steps)if(this.ss(e,i))return!0;return!1}onAction(e,n){return this.ns.on(e,n)}ls(e,n){if(n!=null&&n.url){var i,r=e==null||(i=e.properties)==null?void 0:i.$current_url;if(!r||typeof r!="string"||!qn(r,n.url,n.url_matching||"contains"))return!1}return!0}us(e,n){return!!this.ps(e,n)&&!!this.gs(e,n)&&!!this.ys(e,n)}ps(e,n){var i;if(n==null||!n.href)return!0;var r=this.bs(e);if(r.length>0)return r.some((a=>qn(a.href,n.href,n.href_matching||"exact")));var s,o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!o&&qn((s=o.match(/(?::|")href="(.*?)"/))?s[1]:"",n.href,n.href_matching||"exact")}gs(e,n){var i;if(n==null||!n.text)return!0;var r=this.bs(e);if(r.length>0)return r.some((u=>qn(u.text,n.text,n.text_matching||"exact")||qn(u.$el_text,n.text,n.text_matching||"exact")));var s,o,a,l=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!l&&(s=(function(u){for(var c,d=[],f=/(?::|")text="(.*?)"/g;!H(c=f.exec(u));)d.includes(c[1])||d.push(c[1]);return d})(l),o=n.text,a=n.text_matching||"exact",s.some((u=>qn(u,o,a))))}ys(e,n){var i,r;if(n==null||!n.selector)return!0;var s=e==null||(i=e.properties)==null?void 0:i.$element_selectors;if(s!=null&&s.includes(n.selector))return!0;var o=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";if(n.selector_regex&&o)try{return new RegExp(n.selector_regex).test(o)}catch{return!1}return!1}bs(e){var n;return(e==null||(n=e.properties)==null?void 0:n.$elements)==null?[]:e?.properties.$elements}hs(e,n){return n==null||!n.properties||n.properties.length===0||Uf(n.properties.reduce(((i,r)=>{var s=U(r.value)?r.value.map(String):r.value!=null?[String(r.value)]:[];return i[r.key]={values:s,operator:r.operator||"exact"},i}),{}),e?.properties)}}class Bm{constructor(e){var n;this._s=[],this._instance=e,this.ws=new Map,this.ks=new Map,this.xs=new Map,(n=this._instance)==null||n.onSessionId==null||n.onSessionId((i=>this.Ss(i)))}Cs(e){return!1}Ms(){return null}Ts(e){}Es(){}Is(e,n){return!!e&&Uf(e.propertyFilters,n?.properties)}Ps(e,n){var i=new Map;return e.forEach((r=>{var s;(s=r.conditions)==null||(s=s[n])==null||(s=s.values)==null||s.forEach((o=>{if(o!=null&&o.name){var a=i.get(o.name)||[];a.push(r.id),i.set(o.name,a)}}))})),i}Rs(e,n,i){var r=(i===wi.Activation?this.ws:this.ks).get(e),s=[];return this.As((o=>{s=o.filter((a=>r?.includes(a.id)))})),s.filter((o=>{var a,l=(a=o.conditions)==null||(a=a[i])==null||(a=a.values)==null?void 0:a.find((u=>u.name===e));return this.Is(l,n)}))}register(e){var n;C((n=this._instance)==null?void 0:n._addCaptureHook)||(this.Fs(e),this.Ls(e))}Ls(e){var n=e.filter((i=>{var r,s;return((r=i.conditions)==null?void 0:r.actions)&&((s=i.conditions)==null||(s=s.actions)==null||(s=s.values)==null?void 0:s.length)>0}));n.length!==0&&(this.Os==null&&(this.Os=new Om(this._instance),this.Os.init(),this.Os.fs((i=>{this.onAction(i)}))),n.forEach((i=>{var r,s,o,a,l;i.conditions&&(r=i.conditions)!=null&&r.actions&&(s=i.conditions)!=null&&(s=s.actions)!=null&&s.values&&((o=i.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.Os)==null||a.register(i.conditions.actions.values),(l=i.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var c=this.xs.get(u.name);c&&c.push(i.id),this.xs.set(u.name,c||[i.id])}})))})))}Fs(e){var n,i=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.events)&&((a=s.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0})),r=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.cancelEvents)&&((a=s.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0}));i.length===0&&r.length===0||((n=this._instance)==null||n._addCaptureHook(((s,o)=>{this.onEvent(s,o)})),this.ws=this.Ps(e,wi.Activation),this.ks=this.Ps(e,wi.Cancellation))}onEvent(e,n){var i,r,s=this.Ds(),o=(n==null||(i=n.properties)==null?void 0:i.$survey_id)||(n==null||(r=n.properties)==null?void 0:r.$product_tour_id);if(o&&this.getActivatedIds().includes(o)){var a=this.$s(e,o);if(a==="consume")return s.info("event consumed activated item, removing it",{event:e,itemId:o}),void this.Ns([o]);if(a==="persist")return s.info("shown item promoted to persisted activation",{event:e,itemId:o}),this.qs(o),void this.js([o])}if(this.ks.has(e)){var l=this.Rs(e,n,wi.Cancellation);l.length>0&&(s.info("cancel event matched, cancelling items",{event:e,itemsToCancel:l.map((c=>c.id))}),this.Ns(l.map((c=>c.id))),l.forEach((c=>this.Bs(c.id))))}if(this.ws.has(e)){s.info("event name matched",{event:e,eventPayload:n,items:this.ws.get(e)});var u=this.Rs(e,n,wi.Activation);this.Hs(u.map((c=>c.id)))}}onAction(e){this.xs.has(e)&&this.Hs(this.xs.get(e)||[])}Hs(e){var n;if(e.length!==0){var i=!((n=this._instance)==null||n.get_session_id==null||!n.get_session_id()),r=[];for(var s of e)i&&this.Cs(s)?this.qs(s)&&this.Us(s):r.push(s);r.length>0&&(this._s=[...new Set([...this._s,...r])]),this.Ds().info("updating activated items",{activatedItems:this.getActivatedIds()})}}qs(e){this._s=this._s.filter((i=>i!==e));var n=this.zs();return!n.includes(e)&&(this.Ws([...n,e]),this.Vs(),!0)}Ns(e){var n=new Set(e);this._s=this._s.filter((s=>!n.has(s)));var i=this.Zs(),r=i.filter((s=>!n.has(s)));r.length!==i.length&&(this.Ws(r),r.length===0&&this.Gs()),this.js(e)}Qs(){var e,n=this.Ms();if(!n)return{};var i=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n];return i&&typeof i=="object"?i:{}}Us(e){if(this.Ms()){var n=this.Qs();this.Ts(I({},n,{[e]:Date.now()}))}}js(e){if(this.Ms()){var n=this.Qs(),i={},r=!1;for(var s of Object.entries(n)){var o=s[0],a=s[1];e.includes(o)?r=!0:i[o]=a}r&&(Kt(i)?this.Es():this.Ts(i))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var n=this.Qs()[e];return ke(n)?n:void 0}}Zs(){var e,n=this.Js();return((e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n])||[]}zs(){var e,n,i=this.Zs();if(i.length===0)return[];var r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[this.Ys()],s=(n=this._instance)==null||n.get_session_id==null?void 0:n.get_session_id();return s&&r===s?i:[]}Vs(){var e,n=(e=this._instance)==null||e.get_session_id==null?void 0:e.get_session_id();n&&this.Xs(n)}Gs(){this.ta()}Ss(e){var n,i=(n=this._instance)==null||(n=n.persistence)==null?void 0:n.props[this.Ys()];if(i&&i!==e){var r=this.Zs(),s=this.Qs();r.length>0&&(this.Ws([]),r.filter((o=>ke(s[o]))).forEach((o=>this.Bs(o)))),this.Gs(),this.Ks()}}getActivatedIds(){return[...new Set([...this.zs(),...this._s])].filter((e=>!this.ea(e)))}reset(){this._s=[],this.Zs().length>0&&this.Ws([]),this.Gs(),this.Ks()}getEventToItemsMap(){return this.ws}ia(){return this.Os}}class Dm extends Bm{constructor(e){super(e)}Js(){return ca}Ys(){return Fr}Ms(){return Rr}Ts(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Rr]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Rr)}Cs(e){var n,i;this.As((s=>{i=s.find((o=>o.id===e))}));var r=(n=i)==null||(n=n.appearance)==null?void 0:n.surveyPopupDelaySeconds;return ke(r)&&r>0}ra(){return zt.SHOWN}As(e){var n;(n=this._instance)==null||n.getSurveys(e)}Bs(e){var n;(n=this._instance)==null||n.cancelPendingSurvey(e)}Ds(){return Q}Ws(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[ca]:e})}Xs(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Fr]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Fr)}ea(){return!1}$s(e,n){var i;this.As((s=>{i=s.find((o=>o.id===n))}));var r=!i||(function(s){var o;return Hf(s)&&!((o=s.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||s.schedule==="always"})(i);return r?e===zt.SHOWN?"consume":"ignore":e===zt.SHOWN?"persist":e===zt.DISMISSED||e===zt.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var Ir="SDK is not enabled or survey functionality is not yet loaded",du="Disabled. Not loading surveys.",jm=w!=null&&w.location?os(w.location.hash,"__posthog")||os(location.hash,"state"):null,fu="_postHogToolbarParams",hu=pe("[Toolbar]"),pu=pe("[FeatureFlags]");class Um{constructor(e,n){n===void 0&&(n=!1),this.na=!1,this.update(e,n)}update(e,n){this.sa=((i,r)=>{var s,o,a,l;return{bootstrap:{featureFlags:(s=i.bootstrap)==null?void 0:s.featureFlags,featureFlagPayloads:(o=i.bootstrap)==null?void 0:o.featureFlagPayloads},remoteRequestsDisabled:r,featureFlagsDisabled:!!i.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!i.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!i.advanced_feature_flags_dedup_per_session,cacheTtlMs:i.feature_flag_cache_ttl_ms,requestTimeoutMs:i.feature_flag_request_timeout_ms,compression:i.disable_compression?"none":"base64",evaluationContexts:(a=(l=i.evaluation_contexts)!==null&&l!==void 0?l:i.evaluation_environments)!==null&&a!==void 0?a:[],flagKeys:U(i.flag_keys)?i.flag_keys:void 0}})(e,n),!e.evaluation_environments||e.evaluation_contexts||this.na||(pu.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.na=!0),C(e.flag_keys)||U(e.flag_keys)||pu.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var gu=pe("[FeatureFlags]"),bn=pe("[FeatureFlags]",{debugEnabled:!0}),Bo=`" failed. Feature flags didn't load in time.`,mu="connection_error",vu=t=>{for(var e={},n=0;t.length>n;n++)e[t[n]]=!0;return e},_u=t=>{var e={};for(var n of $r(t||{})){var i=n[1];i&&(e[n[0]]=i)}return e},St=pe("[Error tracking]"),yu="Refusing to render web experiment since the viewer is a likely bot",Hm={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>cs(e,t),not_regex:(t,e)=>!cs(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class Me{get Ne(){return this._instance.config}constructor(e){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(i){i===void 0&&(i=!1),n.getWebExperiments((r=>{Me.aa("retrieved web experiments from the server"),n.oa=new Map,r.forEach((s=>{if(s.feature_flag_key){var o;n.oa&&(Me.aa("setting flag key ",s.feature_flag_key," to web experiment ",s),(o=n.oa)==null||o.set(s.feature_flag_key,s));var a=n._instance.getFeatureFlag(s.feature_flag_key);X(a)&&s.variants[a]&&n.la(s.name,a,s.variants[a].transforms)}else if(s.variants)for(var l in s.variants){var u=s.variants[l];Me.ua(u,n._instance)&&n.la(s.name,l,u.transforms)}}))}),i)},this._instance=e,this._instance.onFeatureFlags((i=>{this.onFeatureFlags(i)}))}initialize(){}onFeatureFlags(e){if(this._is_bot())Me.aa(yu);else if(!this.Ne.disable_web_experiments){if(H(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();Me.aa("applying feature flags",e),e.forEach((n=>{var i;if(this.oa&&(i=this.oa)!=null&&i.has(n)){var r,s=this._instance.getFeatureFlag(n),o=(r=this.oa)==null?void 0:r.get(n);s&&o!=null&&o.variants[s]&&this.la(o.name,s,o.variants[s].transforms)}}))}}previewWebExperiment(){var e=Me.getWindowLocation();if(e!=null&&e.search){var n=ii(e?.search,"__experiment_id"),i=ii(e?.search,"__experiment_variant");n&&i&&(Me.aa("previewing web experiments "+n+" && "+i),this.getWebExperiments((r=>{this.ha(parseInt(n),i,r)}),!1,!0))}}loadIfEnabled(){this.Ne.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,n,i){if(this.Ne.disable_web_experiments&&!i)return e([]);var r=this._instance.get_property("$web_experiments");if(r&&!n)return e(r);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this.Ne.token),method:"GET",timestampMode:"query",callback:s=>e(s.statusCode===200&&s.json&&s.json.experiments||[])})}ha(e,n,i){var r=i.filter((s=>s.id===e));r&&r.length>0&&(Me.aa("Previewing web experiment ["+r[0].name+"] with variant ["+n+"]"),this.la(r[0].name,n,r[0].variants[n].transforms))}static ua(e,n){return!H(e.conditions)&&Me.da(e,n)&&Me.va(e)}static da(e,n){var i;if(H(e.conditions)||H((i=e.conditions)==null?void 0:i.url))return!0;var r=Me.getWindowLocation();if(r){var s,o,a,l=rf(n,r.href);return(s=e.conditions)==null||!s.url||Hm[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return w?.location}static va(e){var n;if(H(e.conditions)||H((n=e.conditions)==null?void 0:n.utm))return!0;var i=yf();if(i.utm_source){var r,s,o,a,l,u,c,d,f=(r=e.conditions)==null||(r=r.utm)==null||!r.utm_campaign||((s=e.conditions)==null||(s=s.utm)==null?void 0:s.utm_campaign)==i.utm_campaign,h=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==i.utm_source,p=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==i.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==i.utm_term;return f&&p&&g&&h}return!1}static aa(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;n>r;r++)i[r-1]=arguments[r];A.info("[WebExperiments] "+e,i)}la(e,n,i){this._is_bot()?Me.aa(yu):n!=="control"?i.forEach((r=>{if(r.selector){var s;Me.aa("applying transform of variant "+n+" for experiment "+e+" ",r);var o=(s=document)==null?void 0:s.querySelectorAll(r.selector);o?.forEach((a=>{var l=a;r.html&&(l.innerHTML=r.html),r.css&&l.setAttribute("style",r.css)}))}})):Me.aa("Control variants leave the page unmodified.")}_is_bot(){return Ue&&this._instance?Bf(Ue,this.Ne.custom_blocked_useragents):void 0}}var st=pe("[Conversations]"),En="Conversations not available yet.",wu="console",Gf="__posthogHandledLogsRequestError",Do=(t,e)=>{var n=t instanceof Error?t:new Error(e);return n[Gf]=!0,n},bu=t=>!!t&&typeof t=="object"&&t[Gf]===!0,Cs={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=gu,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 Um(t.config,t.Qi()),this.Ta=this.Ea)}updateConfig(t,e){var n;(n=this.Ea)==null||n.update(t,e)}setup(t){return this.Ia=t,this.rt=t.logger.createLogger("[FeatureFlags]"),n=()=>{this.Ia===t&&(this.Ia=void 0,this.nn=t,this.Pa(t))},(e=t.kv.initialize())!=null&&e.then?e.then(n):n();var e,n}Pa(t){if(this.nn===t)return w&&ve(w,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){w?.removeEventListener("online",this.Ca)}dispose(){var t;this.ba++,this.wa=!1,this.Ia=void 0,this.nn&&(this.La(),(t=this.Ra)==null||t.dispose(),this.Ra=void 0,this.ga=[],w?.removeEventListener("online",this.Ca),this.nn=void 0)}get Ne(){return this.Ta.get()}Oa(t){var e;return(e=this.nn)==null?void 0:e.kv.get(t)}F(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.set(t)}))}q(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.remove(t)}))}Da(t){try{t()}catch(e){this.rt.error("Failed to update feature flag persistence",e)}}Fa(){var t={};for(var e of[Ti,$i,Pr,It]){var n=this.Oa(e);C(n)||(t[e]=n)}this.fa=t;var i=I({},t),r=this.Oa(Sn);if(r)for(var s of Object.entries(r))i["$feature/"+s[0]]=s[1];this.pa=i}Aa(){var t=this.Ne.cacheTtlMs;if(!t||0>=t)return!1;var e=this.Oa(ji);return typeof e!="number"||Date.now()-e>t}$a(){return!!this.Aa()&&(this.xa||this.ya||(this.xa=!0,this.rt.warn("Feature flag cache is stale, triggering refresh..."),this.reloadFeatureFlags()),!0)}Na(){var t=this.Ne.evaluationContexts;return t!=null&&t.length?t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid evaluation context found:",e,"Expected non-empty string"),n})):[]}qa(){var t=this.Ne.flagKeys;if(!C(t))return t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid flag key found:",e,"Expected non-empty string"),n}))}initialize(){var t,e,n=this.Ne,i=(t=(e=n.bootstrap)==null?void 0:e.featureFlags)!==null&&t!==void 0?t:{};if(Object.keys(i).length){var r,s,o=(r=(s=n.bootstrap)==null?void 0:s.featureFlagPayloads)!==null&&r!==void 0?r:{},a=Object.keys(i).filter((u=>!!i[u])).reduce(((u,c)=>(u[c]=i[c]||!1,u)),{}),l=Object.keys(o).filter((u=>a[u])).reduce(((u,c)=>(o[c]&&(u[c]=o[c]),u)),{});return this.ja({featureFlags:a,featureFlagPayloads:l})}}updateFlags(t,e,n){var i,r,s=n!=null&&n.merge&&(i=this.Oa(Sn))!==null&&i!==void 0?i:{},o=n!=null&&n.merge&&(r=this.Oa($i))!==null&&r!==void 0?r:{},a=I({},s,t),l=I({},o,e),u={};for(var c of Object.entries(a)){var d=c[0],f=c[1];u[d]={key:d,enabled:hc(f),variant:pc(f),reason:void 0,metadata:C(l?.[d])?void 0:{id:0,version:void 0,description:void 0,payload:l[d]}}}this.ja({flags:u})}get hasLoadedFlags(){return this.ma}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var t=this.Oa(aa),e=this.Oa(It),n=this.Oa(xn);if(!n&&!e)return t||{};var i=fe({},t||{}),r=[...new Set([...Object.keys(n||{}),...Object.keys(e||{})])];for(var s of r){var o,a,l=i[s],u=e?.[s],c=C(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=C(u)?l?.variant:typeof u=="string"?u:void 0,f=n?.[s],h=I({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(h.original_enabled=l?.enabled),d!==l?.variant&&(h.original_variant=l?.variant),f&&(h.metadata=I({},l?.metadata,{payload:f,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),i[s]=h}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:n,finalDetails:i}),this.ca=!0),i}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((n=>{var i=t[n];return{key:n,enabled:hc(i),variant:pc(i),payload:fc(e[n])}}))}getFlagVariants(){var t=this.Oa(Sn),e=this.Oa(It);if(!e)return t||{};for(var n=fe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:e,finalFlags:n}),this.ca=!0),n}getFlagPayloads(){var t=this.Oa($i),e=this.Oa(xn);if(!e)return t||{};for(var n=fe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flag payloads!",{flagPayloads:t,overriddenPayloads:e,finalPayloads:n}),this.ca=!0),n}reloadFeatureFlags(){this._a||this.Ne.featureFlagsDisabled||this.Ma()||this.Ba||(this.ga.slice().forEach((t=>{try{t()}catch(e){this.rt.error("Error while running feature flags reloading callback",e)}})),this.Ba=setTimeout((()=>{this.Ha()}),5))}La(){clearTimeout(this.Ba),this.Ba=void 0}onReloading(t){return this.ga.push(t),()=>{this.ga=this.ga.filter((e=>e!==t))}}ensureFlagsLoaded(){this.ma||this.ya||this.Ba||this.reloadFeatureFlags()}setAnonymousDistinctId(t){this.$anon_distinct_id=t}setReloadingPaused(t){this._a=t}resetFlagCallReported(){this.q(Cn)}Ha(t){this.La();var e=this.nn;if(e&&!this.Ne.remoteRequestsDisabled&&!this.Ma())if(this.ya)this.wa=!0;else{var n={token:e.projectToken,distinct_id:e.distinctId,groups:e.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:I({},e.initialPersonProperties,this.Oa(jt)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(In),timezone:If()};C(e.deviceId)||(n.$device_id=e.deviceId),(t!=null&&t.disableFlags||this.Ne.featureFlagsDisabled)&&(n.disable_flags=!0);var i=this.Na();i.length&&(n.evaluation_contexts=i);var r=this.qa();C(r)||(n.flag_keys=r);var s=this.Ne.onlyEvaluateSurveyFeatureFlags,o="/flags/?v=2"+(s?"&only_evaluate_survey_feature_flags=true":""),a=this.ba;this.ya=!0;var l=()=>{this.wa&&(this.wa=!1,this.Ha())},u=c=>{this.ya=!1,a===this.ba&&(this.F({[Tr]:[mu]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:n,compression:this.Ne.compression==="base64"?je.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,f,h=(d=c.json)!==null&&d!==void 0?d:{},p=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),p||this.wa||(this.$anon_distinct_id=void 0),!n.disable_flags||this.wa){this.ka=!p;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?mu:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),h.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((f=h.quotaLimited)==null||!f.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[Tr]:g}),m?this.rt.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more."):n.disable_flags||this.ja(h,p,{partialResponse:s}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return vf(this.Sa,3)}Ua(t){this.Sa=_f(t,this.Sa,3,(()=>this.rt.warn("Feature flag requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped refreshing feature flags; will try again when connectivity changes.")))}getFeatureFlag(t,e){var n;if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var i=this.getFeatureFlagResult(t,e);return(n=i?.variant)!==null&&n!==void 0?n:i?.enabled}}else this.rt.warn('getFeatureFlag for key "'+t+Bo)}getFeatureFlagDetails(t){return this.getFlagsWithDetails()[t]}getFeatureFlagPayload(t){var e=this.getFeatureFlagResult(t,{send_event:!1});return e?.payload}getFeatureFlagResult(t,e){if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var n,i=this.getFlagVariants(),r=t in i,s=i[t],o=this.getFlagPayloads()[t],a=String(s),l=this.Oa(Pr)||void 0,u=this.Oa(ji)||void 0,c=this.Oa(Cn)||{};if(this.Ne.deduplicateCallsPerSession){var d,f=(d=this.nn)==null?void 0:d.session.sessionId,h=this.Oa(Li);f&&f!==h&&(c={},n=f)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))n&&this.F({[Cn]:c,[Li]:n});else{var p,g,m,v,E,S,_,b,k,T;U(c[t])?c[t].push(a):c[t]=[a],this.F(I({[Cn]:c},n?{[Li]:n}:{}));var x=this.getFeatureFlagDetails(t),F=[...(p=this.Oa(Tr))!==null&&p!==void 0?p:[]];C(s)&&F.push("flag_missing");var $={$feature_flag:t,$feature_flag_response:s,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((g=this.Ne.bootstrap)==null||(g=g.featureFlags)==null?void 0:g[t])||null,$feature_flag_bootstrapped_payload:((m=this.Ne.bootstrap)==null||(m=m.featureFlagPayloads)==null?void 0:m[t])||null,$used_bootstrap_value:!this.ka};C(x==null||(v=x.metadata)==null?void 0:v.has_experiment)||($.$feature_flag_has_experiment=x.metadata.has_experiment),C(x==null||(E=x.metadata)==null?void 0:E.version)||($.$feature_flag_version=x.metadata.version);var O,L=(S=x==null||(_=x.reason)==null?void 0:_.description)!==null&&S!==void 0?S:x==null||(b=x.reason)==null?void 0:b.code;L&&($.$feature_flag_reason=L),x!=null&&(k=x.metadata)!=null&&k.id&&($.$feature_flag_id=x.metadata.id),C(x?.original_variant)&&C(x?.original_enabled)||($.$feature_flag_original_response=C(x.original_variant)?x.original_enabled:x.original_variant),x!=null&&(T=x.metadata)!=null&&T.original_payload&&($.$feature_flag_original_payload=x==null||(O=x.metadata)==null?void 0:O.original_payload),F.length&&($.$feature_flag_error=F.join(",")),this.za($)}else n&&this.F({[Cn]:c,[Li]:n});if(r)return{key:t,enabled:!!s,variant:typeof s=="string"?s:void 0,payload:fc(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+Bo)}za(t){try{var e;(e=this.nn)==null||e.capture("$feature_flag_called",t).catch((n=>{this.rt.error("Failed to capture feature flag call",n)}))}catch(n){this.rt.error("Failed to capture feature flag call",n)}}getRemoteConfigPayload(t,e){this.Wa(t,e)}Wa(t,e){var n=this;return se((function*(){var i=n.nn;if(i){var r={distinct_id:i.distinctId,token:i.projectToken,person_properties:{$lib:i.library.name,$lib_version:i.library.version}},s=n.Na();s.length&&(r.evaluation_contexts=s);var o,a=n.qa();C(a)||(r.flag_keys=a);try{var l,u=(l=(yield i.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:r,compression:n.Ne.compression==="base64"?je.Base64:void 0,sentAt:"body",timeoutMs:n.Ne.requestTimeoutMs})).json)==null?void 0:l.featureFlagPayloads;o=u?.[t]||void 0}catch(c){return void n.rt.error("Remote config feature flag request failed",c)}try{e(o)}catch(c){n.rt.error("Remote config feature flag callback failed",c)}}}))()}isFeatureEnabled(t,e){if(e===void 0&&(e={}),e.fresh&&!this.ka)return e.defaultValue;if(!(this.ma||this.getFlags()&&this.getFlags().length>0))return this.rt.warn('isFeatureEnabled for key "'+t+Bo),e.defaultValue;var n=this.getFeatureFlag(t,e);return C(n)?e.defaultValue:!!n}addFeatureFlagsHandler(t){this.featureFlagEventHandlers.push(t)}removeFeatureFlagsHandler(t){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((e=>e!==t))}receivedFeatureFlags(t,e,n){this.ja(t,e,n)}ja(t,e,n){if(this.nn){this.ma=!0;var i=(function(r,s,o,a,l,u){s===void 0&&(s={}),o===void 0&&(o={}),a===void 0&&(a={}),u===void 0&&(u=gu);var c=((k,T)=>{var x=k.flags;return x?I({},k,{featureFlags:Object.fromEntries(Object.keys(x).map((F=>{var $;return[F,($=x[F].variant)!==null&&$!==void 0?$:x[F].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(x).filter((F=>x[F].enabled)).filter((F=>{var $;return($=x[F].metadata)==null?void 0:$.payload})).map((F=>{var $;return[F,($=x[F].metadata)==null?void 0:$.payload]})))}):(k.featureFlags&&T.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),k)})(r,u),d=c.flags,f=c.featureFlags,h=c.featureFlagPayloads;if(f){var p=r.requestId,g=r.evaluatedAt;if(U(f)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(f)for(var v=0;f.length>v;v++)m[f[v]]=!0;return{[Ti]:f,[Sn]:m,[Zr]:!1}}var E=f,S=h,_=d;if(l!=null&&l.partialResponse)E=I({},s,E),S=I({},o,S),_=I({},a,_);else if(r.errorsWhileComputingFlags)if(d){var b=new Set(Object.keys(d).filter((k=>{var T;return!((T=d[k])!=null&&T.failed)})));E=I({},s,Object.fromEntries(Object.entries(E).filter((k=>b.has(k[0]))))),S=I({},o,Object.fromEntries(Object.entries(S||{}).filter((k=>b.has(k[0]))))),_=I({},a,Object.fromEntries(Object.entries(_||{}).filter((k=>b.has(k[0])))))}else E=I({},s,E),S=I({},o,S),_=I({},a,_);return I({[Ti]:Object.keys(_u(E)),[Sn]:E||{},[$i]:S||{},[aa]:_||{},[Zr]:r.minimalFlagCalledEvents===!0},p?{[Pr]:p}:{},g?{[ji]:g}:{})}})(t,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),n,this.rt);i&&this.F(i),e||(this.xa=!1),this.Va(e)}}override(t,e){e===void 0&&(e=!1),this.rt.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:t,suppressWarning:e})}overrideFeatureFlags(t){this.Za(t)}Za(t){if(this.nn){if(t===!1)return this.q([It,xn]),this.Va(),void bn.info("All overrides cleared");if(U(t))return this.F({[It]:vu(t)}),this.Va(),void bn.info("Flag overrides set",{flags:t});if(t&&typeof t=="object"&&("flags"in t||"payloads"in t)){var e,n=t;this.ca=!!((e=n.suppressWarning)!==null&&e!==void 0&&e);var i={},r=n.flags,s=n.payloads;return r&&(i[It]=U(r)?vu(r):r),s&&(i[xn]=s),Object.keys(i).length&&this.F(i),r===!1&&s===!1?this.q([It,xn]):r===!1?this.q(It):s===!1&&this.q(xn),this.Va(),r===!1?bn.info("Flag overrides cleared"):r&&bn.info("Flag overrides set",{flags:r}),void(s===!1?bn.info("Payload overrides cleared"):s&&bn.info("Payload overrides set",{payloads:s}))}if(t&&typeof t=="object")return this.F({[It]:t}),this.Va(),void bn.info("Flag overrides set",{flags:t});this.rt.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:t})}else this.rt.warn("posthog.featureFlags.overrideFeatureFlags called before feature flags were ready")}onFeatureFlags(t){if(this.addFeatureFlagsHandler(t),this.ma){var e=this.Ga(),n=e.flags,i=e.flagVariants;try{t(n,i)}catch(r){this.rt.error("Error while running feature flags callback",r)}}return()=>this.removeFeatureFlagsHandler(t)}updateEarlyAccessFeatureEnrollment(t,e,n){var i=(this.Oa(Ar)||[]).find((l=>l.flagKey===t)),r={["$feature_enrollment/"+t]:e},s={$feature_flag:t,$feature_enrollment:e,$set:r};i&&(s.$early_access_feature_name=i.name),n&&(s.$feature_enrollment_stage=n);var o=I({},this.getFlagVariants(),{[t]:e});this.F({[Ti]:Object.keys(_u(o)),[Sn]:o,[jt]:I({},this.Oa(jt)||{},r)}),this.Va();try{var a;(a=this.nn)==null||a.capture("$feature_enrollment_update",s).catch((l=>{this.rt.error("Failed to capture early access feature enrollment",l)}))}catch(l){this.rt.error("Failed to capture early access feature enrollment",l)}}getEarlyAccessFeatures(t,e,n){e===void 0&&(e=!1);var i=this.Oa(Ar);!i||e?this.Qa(t,n):t(i)}Qa(t,e){var n=this;return se((function*(){var i=n.nn;if(i){var r,s=e?"&"+e.map((a=>"stage="+a)).join("&"):"";try{var o=yield i.sendRequest("/api/early_access_features/?token="+i.projectToken+s,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;n.F({[Ar]:r=o.json.earlyAccessFeatures})}catch(a){return void n.rt.error("Early access feature request failed",a)}try{t(r)}catch(a){n.rt.error("Early access feature callback failed",a)}}}))()}Ga(){var t=this.getFlags(),e=this.getFlagVariants();return{flags:t.filter((n=>e[n])),flagVariants:Object.keys(e).filter((n=>e[n])).reduce(((n,i)=>(n[i]=e[i],n)),{})}}Va(t){this.Fa();var e=this.Ga(),n=e.flags,i=e.flagVariants;this.featureFlagEventHandlers.forEach((r=>{try{r(n,i,{errorsLoading:t})}catch(s){this.rt.error("Error while running feature flags callback",s)}}))}setPersonPropertiesForFlags(t,e){e===void 0&&(e=!0),this.Ka(t,e)}Ka(t,e){e===void 0&&(e=!0);var n=this.Oa(jt)||{},i=t?.$set||(t!=null&&t.$set_once?{}:t),r=t?.$set_once,s={};if(r)for(var o in r)({}).hasOwnProperty.call(r,o)&&(o in n||(s[o]=r[o]));this.F({[jt]:I({},n,s,i)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=I({},this.Oa(jt)||{});t.forEach((i=>{delete n[i]})),this.F({[jt]:n}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(jt),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=this.Oa(In)||{},i=I({},n);for(var r of Object.keys(t))i[r]=I({},n[r],t[r]);this.F({[In]:i}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(In)||{};this.F({[In]:I({},e,{[t]:{}})})}else this.q(In)}reset(){this.ba++,this.wa=!1,this.Fa(),this.ma=!1,this._a=!1,this.ka=!1,this.$anon_distinct_id=void 0,this.La(),this.ca=!1,this.Sa=0}}},Wm={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===ki||this.Ya===Sr?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=lu,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(P==null||!P.visibilityState||P.visibilityState==="visible")return!0;var n=w==null||(e=w.performance)==null||e.getEntriesByType==null?void 0:e.getEntriesByType("visibility-state");return!(n!=null&&n.length)||n.some((i=>i.name==="visible"))})(),this.Ie=()=>{var e;P?.visibilityState==="visible"&&(this.io=!0,(e=this.Ja)==null||e.setDocumentWasEverVisible==null||e.setDocumentWasEverVisible(!0))},this._instance=t,!this._instance.sessionManager)throw Bt.error("started without valid sessionManager"),new Error(Ia+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===Wt)throw new Error(Ia+' cannot be used with cookieless_mode="always"');P!=null&&P.addEventListener&&ve(P,"visibilitychange",this.Ie)}initialize(){this.startIfEnabledOrStop()}dispose(){this.eo=!0,P==null||P.removeEventListener==null||P.removeEventListener("visibilitychange",this.Ie),this.stopRecording()}get ro(){var t,e=!((t=this._instance.get_property(An))==null||!t.enabled),n=!this.Ne.disable_session_recording,i=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return w&&e&&n&&!i}startIfEnabledOrStop(t){var e;if(!(this.eo||this.ro&&(e=this.Ja)!=null&&e.isStarted)){var n=!C(Object.assign)&&!C(Array.from);this.ro&&n?(this.no(t),Bt.info("starting")):(this.Ya=lu,this.stopRecording())}}no(t){var e,n,i;this.ro&&(this.Ya!==ki&&this.Ya!==Sr&&(this.Ya=cu),B!=null&&(e=B.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(n=B.__PosthogExtensions__)!=null&&n.initSessionRecording?this.so(t):(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,this.ao,(r=>{if(r)return Bt.error("could not load recorder",r);this.so(t)})))}stopRecording(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.stop()}oo(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.discard()}lo(){var t,e;(t=this.Mr)==null||t.unregister(ol),(e=this.Mr)==null||e.unregister(Vd)}uo(t,e){if(H(t))return null;var n,i=ke(t)?t:parseFloat(t);return typeof(n=i)!="number"||!Number.isFinite(n)||0>n||n>1?(Bt.warn(e+" must be between 0 and 1. Ignoring invalid value:",t),null):i}ho(t){if(this.Mr){var e,n,i=this.Mr,r=()=>{var s,o=t.sessionRecording===!1?void 0:t.sessionRecording,a=this.uo((s=this.Ne.session_recording)==null?void 0:s.sampleRate,"session_recording.sampleRate"),l=this.uo(o?.sampleRate,"remote config sampleRate"),u=a??l;H(u)&&this.lo();var c=o?.minimumDurationMilliseconds;i.register({[An]:I({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:I({capturePerformance:t.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:u,minimumDurationMilliseconds:C(c)?null:c,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers,version:o?.version,triggerGroups:o?.triggerGroups})})};r(),(e=this.Xa)==null||e.call(this),this.Xa=(n=this._instance.sessionManager)==null?void 0:n.onSessionId(r)}}onRemoteConfig(t){var e=t.ok?t.config:void 0;return e&&"sessionRecording"in e?e.sessionRecording===!1?(this.ho(e),void this.oo()):(this.ho(e),void this.startIfEnabledOrStop()):(this.Ya===ki&&(this.Ya=Sr,Bt.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(t,e){var n;e===void 0&&(e="log"),(n=this.Ja)!=null&&n.log?this.Ja.log(t,e):Bt.warn("log called before recorder was ready")}get ao(){var t,e,n=(t=this._instance)==null||(t=t.persistence)==null?void 0:t.get_property(An);return(n==null||(e=n.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(An);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(n){return Bt.warn("persisted remote config for session recording is invalid and will be ignored",n),!1}return!H(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,n,i;if(!this.eo){if((e=B.__PosthogExtensions__)==null||!e.initSessionRecording)return Bt.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[ef]:!0});var r;if(this.Ja||(this.Ja=(r=B.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===Sr||this.Ya===ki?void 0:(this.Ya=ki,Bt.info("persisted remote config is stale, requesting fresh config before starting"),void new kf(this._instance).load());this.Ya=cu,(n=(i=this.Ja).setDocumentWasEverVisible)==null||n.call(i,this.io),this.Ja.start(t)}}onRRwebEmit(t){var e;(e=this.Ja)==null||e.onRRwebEmit==null||e.onRRwebEmit(t)}overrideLinkedFlag(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Kd]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Gd]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,n;this.Ja||(n=this.Mr)==null||n.register({[t==="url"?Yd:Jd]:!0}),(e=this.Ja)==null||e.overrideTrigger(t)}get sdkDebugProperties(){var t;return((t=this.Ja)==null?void 0:t.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(t,e){var n;return!((n=this.Ja)==null||!n.tryAddCustomEvent(t,e))}}},qm={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new su(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,n=he(this.instance.config.autocapture)?this.instance.config.autocapture:{};return n.url_allowlist=(t=n.url_allowlist)==null?void 0:t.map((i=>new RegExp(i))),n.url_ignorelist=(e=n.url_ignorelist)==null?void 0:e.map((i=>new RegExp(i))),n}yo(){if(this.isBrowserSupported()){if(w&&P){var t=n=>{n=n||w?.event;try{this.bo(n)}catch(i){Mo.error("Failed to capture event",i)}};if(ve(P,"submit",t,{capture:!0}),ve(P,"change",t,{capture:!0}),ve(P,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=n=>{n=n||w?.event;try{this.bo(n,$o)}catch(i){Mo.error("Failed to capture copy/cut event",i)}};ve(P,"copy",e,{capture:!0}),ve(P,"cut",e,{capture:!0})}}}else Mo.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.vo&&(this.yo(),this.vo=!0)}onRemoteConfig(t){if(this.fo=!0,t.ok){var e=t.config;e.elementsChainAsString&&(this.po=e.elementsChainAsString);var n=e.autocapture_opt_out;mt(n)&&(this.instance.persistence&&this.instance.persistence.register({[ea]:n}),this.co=n),this.startIfEnabled()}else this.startIfEnabled()}setElementSelectors(t){this.mo=t}getElementSelectors(t){var e,n=[];return(e=this.mo)==null||e.forEach((i=>{var r=P?.querySelectorAll(i);r?.forEach((s=>{t===s&&n.push(i)}))})),n}get isEnabled(){var t,e,n=(t=this.instance.persistence)==null?void 0:t.props[ea],i=this.co,r=this.instance.Qi()&&!this.fo;if(Ke(i)&&!mt(n)&&!r)return!1;var s=(e=this.co)!==null&&e!==void 0?e:!!n;return!!this.instance.config.autocapture&&!s}bo(t,e){if(e===void 0&&(e="$autocapture"),this.isEnabled){var n,i=bo(t);of(i)&&(i=i.parentNode||null),e==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&this.instance.config.rageclick&&(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,t.timeStamp||new Date().getTime())&&Lc(i,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var r=e===$o;if(i&&(function(d,f,h,p,g,m){var v;if(!w||dl(d)||h!=null&&h.url_allowlist&&!Tc(h.url_allowlist,m)||h!=null&&h.url_ignorelist&&Tc(h.url_ignorelist,m))return!1;if(h!=null&&h.dom_event_allowlist){var E=h.dom_event_allowlist;if(E&&!E.some((x=>f.type===x)))return!1}var S=ff(d,p),_=S.parentIsUsefulElement,b=S.targetElementList;if(!(function(x,F){var $=F?.element_allowlist;if(C($))return!0;var O,L=function(K){if($.some((V=>K.tagName.toLowerCase()===V)))return{v:!0}};for(var N of x)if(O=L(N))return O.v;return!1})(b,h)||!ma(b,h?.css_selector_allowlist)||ma(b,(v=h?.css_selector_ignorelist)!==null&&v!==void 0?v:Ug))return!1;try{var k=w.getComputedStyle(d);if(k&&k.getPropertyValue("cursor")==="pointer"&&f.type==="click")return!0}catch{}var T=d.tagName.toLowerCase();switch(T){case"html":return!1;case"form":return(g||["submit"]).indexOf(f.type)>=0;case"input":case"select":case"textarea":return(g||["change","click"]).indexOf(f.type)>=0;default:return _?(g||["click"]).indexOf(f.type)>=0:(g||["click"]).indexOf(f.type)>=0&&(ul.indexOf(T)>-1||d.getAttribute("contenteditable")==="true")}})(i,t,this.Ne,r,r?["copy","cut"]:void 0,this.instance)){var s=$m(i,{e:t,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.Ne.element_attribute_ignorelist,elementsChainAsString:this.po,disableCaptureUrlHashes:this.instance.config.disable_capture_url_hashes}),o=s.props;if(s.explicitNoCapture)return!1;var a=this.getElementSelectors(i);if(a&&a.length>0&&(o.$element_selectors=a),e===$o){var l,u=cf(w==null||(l=w.getSelection())==null?void 0:l.toString()),c=t.type||"clipboard";if(!u)return!1;o.$selected_content=u,o.$copy_type=c}return this.instance.capture(e,o),!0}}}isBrowserSupported(){return De(P?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(w==null||(e=w.location)==null?void 0:e.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(A.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.wo&&this.wo(),this.wo=void 0,A.info("History API monitoring stopped")}monitorHistoryChanges(){w&&w.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(w&&((e=w.history[t])==null||!e.__posthog_wrapped__)){var n=this;(function(i,r,s){try{if(!(r in i))return ou;var o={next:i[r]},a=s((function(){for(var l=arguments.length,u=new Array(l),c=0;l>c;c++)u[c]=arguments[c];return o.next.apply(this,u)}));return De(a)&&(a.prototype=a.prototype||{},Object.defineProperties(a,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:o}})),i[r]=a,()=>{if(i[r]!==a)for(var l=i[r];De(l)&&l.__posthog_layer__;){var u=l.__posthog_layer__;if(u.next===a)return void(u.next=o.next);l=u.next}else i[r]=o.next}}catch{return ou}})(w.history,t,(i=>function(r,s,o){i.call(this,r,s,o),n.So(t)}))}}So(t){try{var e,n=w==null||(e=w.location)==null?void 0:e.pathname;if(!n)return;n!==this._o&&this.isEnabled&&this._instance.capture(Vn,{navigation_type:t}),this._o=n}catch(i){A.error("Error capturing "+t+" pageview",i)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};ve(w,"popstate",t),this.wo=()=>{w&&w.removeEventListener("popstate",t)}}}},heatmaps:class{get Ne(){return this.instance.config}constructor(t){var e;this.Co=!1,this.vo=!1,this.Mo=null,this.instance=t,this.Co=!((e=this.instance.persistence)==null||!e.props[ta]),this.rageclicks=new su(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return he(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return H(this.Ne.capture_heatmaps)?H(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;Lm.info("starting..."),this.To(),this.Ie()}else{var t;clearInterval((t=this.Mo)!==null&&t!==void 0?t:void 0),this.Eo(),this.getAndClearBuffer()}}onRemoteConfig(t){if(t.ok){var e=t.config;if("heatmaps"in e){var n=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[ta]:n}),this.Co=n,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){No(t.originalEvent)&&this.ke(t.originalEvent,"deadclick")}Ie(){this.Mo&&clearInterval(this.Mo),this.Mo=P?.visibilityState==="visible"?setInterval(this.cr.bind(this),this.flushIntervalMilliseconds):null}To(){w&&P&&(this.Po=this.cr.bind(this),ve(w,ns,this.Po),this.Ro=t=>this.ke(t||w?.event),ve(P,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||w?.event),ve(P,"mousemove",this.Ao,{capture:!0}),this.Lo=new Hc(this.instance,Kg,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),ve(P,ts,this.Oo),this.vo=!0)}Eo(){var t;w&&P&&(this.Po&&w.removeEventListener(ns,this.Po),this.Ro&&P.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&P.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&P.removeEventListener(ts,this.Oo),clearTimeout(this.Do),(t=this.Lo)==null||t.stop(),this.vo=!1)}$o(t,e){var n=this.instance.scrollManager.scrollY(),i=this.instance.scrollManager.scrollX(),r=this.instance.scrollManager.scrollElement(),s=(function(o,a,l){for(var u=o;u&&hn(u)&&!Qe(u,"body");){if(u===l)return!1;var c=void 0;try{var d,f,h;c=(d=(f=(h=u.ownerDocument)==null?void 0:h.defaultView)!==null&&f!==void 0?f:w)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(j(a,c))return!0;u=uf(u)}return!1})(bo(t),["fixed","sticky"],r);return{x:t.clientX+(s?0:i),y:t.clientY+(s?0:n),target_fixed:s,type:e}}ke(t,e){var n;if(e===void 0&&(e="click"),!Rc(t.target)&&No(t)){var i=this.$o(t,e);(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,new Date().getTime())&&Lc(bo(t),this.instance.config.rageclick)&&this.Vt(I({},i,{type:"rageclick"})),this.Vt(i)}}Fo(t){!Rc(t.target)&&No(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(w){var e=this.Ne.disable_capture_url_hashes?fn(w.location.href):w.location.href,n=this.Ne.custom_personal_data_properties,i=this.Ne.mask_personal_data_properties?[...ri,...n||[]]:[],r=Zi(e,i,Xi);this.R=this.R||{},this.R[r]||(this.R[r]=[]),this.R[r].push(t)}}cr(){this.R&&!Kt(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:Hc,webVitalsAutocapture:class{constructor(t){var e;this.Co=!1,this.vo=!1,this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this.No=()=>{clearTimeout(this.qo),this.qo=void 0,this.R.metrics.length!==0&&(this._instance.capture("$web_vitals",I({$current_url:this.R.url},this.R.metrics.reduce(((n,i)=>I({},n,{["$web_vitals_"+i.name+"_event"]:I({},i),["$web_vitals_"+i.name+"_value"]:i.value})),{}))),this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.jo=n=>{var i;if(this.R=this.R||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},H(n?.name)||H(n?.value))wn.error("Invalid metric received",n);else{var r=typeof n.navigationURL=="string"?n.navigationURL:void 0,s=this.Bo(r);if(!C(s)){var o=ke(n.navigationId)||typeof n.navigationId=="string"?"navigation:"+n.navigationId:"url:"+s;if(!this.Ho||this.Ho>n.value){this.R.navigationKey!==o&&(this.No(),this.qo=setTimeout(this.No,this.flushToCaptureTimeoutMs)),C(this.R.navigationKey)&&(this.R.navigationKey=o,this.R.url=s),this.R.firstMetricTimestamp=C(this.R.firstMetricTimestamp)?Date.now():this.R.firstMetricTimestamp,n.attribution&&n.attribution.interactionTargetElement&&(n.attribution.interactionTargetElement=void 0);var a=(i=this._instance.sessionManager)==null?void 0:i.checkAndGetSessionAndWindowId(!0),l=I({},n,r?{navigationURL:s}:{},{$current_url:s,timestamp:Date.now()});C(a)||(l.$session_id=a.sessionId,l.$window_id=a.windowId),this.R.metrics.push(l),this.R.metrics.length===this.allowedMetrics.length&&this.No()}else wn.error("Ignoring metric with value >= "+this.Ho,n)}}},this.Uo=()=>{if(!this.vo){var n,i,r,s,o=B.__PosthogExtensions__,a=o?.postHogWebVitalsCallbacksByFlavor,l=a?.[this.zo]||(this.zo==="web-vitals"&&C(a)?o?.postHogWebVitalsCallbacks:void 0);if(C(l)||(n=l.onLCP,i=l.onCLS,r=l.onFCP,s=l.onINP),n&&i&&r&&s){var u={reportSoftNavs:this.useSoftNavs};this.allowedMetrics.indexOf("LCP")>-1&&n(this.jo.bind(this),u),this.allowedMetrics.indexOf("CLS")>-1&&i(this.jo.bind(this),u),this.allowedMetrics.indexOf("FCP")>-1&&r(this.jo.bind(this),u),this.allowedMetrics.indexOf("INP")>-1&&s(this.jo.bind(this),u),this.vo=!0}else wn.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[sa]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,n=he(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return H(n)?((e=this._instance.persistence)==null?void 0:e.props[oa])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(he(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=he(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=he(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=he(this.Wo)&&ke(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:au;return t>0&&6e4>=t?au:t}get isEnabled(){var t=me?.protocol;if(t!=="http:"&&t!=="https:")return wn.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=he(this.Wo)?this.Wo.web_vitals:mt(this.Wo)?this.Wo:void 0;return mt(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(wn.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var n=he(e.capturePerformance)&&!!e.capturePerformance.web_vitals,i=he(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[sa]:n}),this._instance.persistence.register({[oa]:i})),this.Co=n,this.startIfEnabled()}}}get zo(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}ai(t){var e=B.__PosthogExtensions__,n=this.zo,i=e?.postHogWebVitalsCallbacksByFlavor;i!=null&&i[n]||n==="web-vitals"&&C(i)&&e!=null&&e.postHogWebVitalsCallbacks?t():e==null||e.loadExternalDependency==null||e.loadExternalDependency(this._instance,n,(r=>{r?wn.error("failed to load script",r):t()}))}Bo(t){var e=t||w?.location.href;if(e){var n=this._instance.config.disable_capture_url_hashes?fn(e):e,i=this._instance.config.custom_personal_data_properties,r=this._instance.config.mask_personal_data_properties?[...ri,...i||[]]:[];return Zi(n,r,Xi)}wn.error("Could not determine current URL")}}},zm={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var n;if(w&&this.isEnabled&&(n=B.__PosthogExtensions__)!=null&&n.errorWrappingFunctions){var i=B.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,r=B.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,s=B.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.Vo&&this.Ne.capture_unhandled_errors&&(this.Vo=i(this.captureException.bind(this))),!this.Zo&&this.Ne.capture_unhandled_rejections&&(this.Zo=r(this.captureException.bind(this))),!this.Go&&this.Ne.capture_console_errors&&(this.Go=s(this.captureException.bind(this)))}catch(o){Ii.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[na]),this.Jo=new Wp(I({},(function(n){var i,r,s,o;return n===void 0&&(n={}),{refillRate:(i=(r=n.exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:n.__exceptionRateLimiterRefillRate)!==null&&i!==void 0?i:1,bucketSize:(s=(o=n.exceptionRateLimiterBucketSize)!==null&&o!==void 0?o:n.__exceptionRateLimiterBucketSize)!==null&&s!==void 0?s:10}})(this._instance.config.error_tracking),{refillInterval:1e4,rt:Ii})),this.Ne=this.Yo(),this.startIfEnabledOrStop()}Yo(){var t=this._instance.config.capture_exceptions,e={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return he(t)?e=I({},e,t):(C(t)?this.Ko:t)&&(e=I({},e,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),e}get isEnabled(){return this.Ne.capture_console_errors||this.Ne.capture_unhandled_errors||this.Ne.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(Ii.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",(i=>{if(i)return Ii.error("failed to load script",i);t()}))}Qo(){var t,e,n;(t=this.Vo)==null||t.call(this),this.Vo=void 0,(e=this.Zo)==null||e.call(this),this.Zo=void 0,(n=this.Go)==null||n.call(this),this.Go=void 0}onRemoteConfig(t){if(t.ok){var e=t.config;"autocaptureExceptions"in e&&(this.Ko=!!e.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[na]:this.Ko}),this.Ne=this.Yo(),this.startIfEnabledOrStop())}}onConfigChange(){this.Ne=this.Yo()}captureException(t){var e,n,i,r=(e=t==null||(n=t.$exception_list)==null||(n=n[0])==null?void 0:n.type)!==null&&e!==void 0?e:"Exception";this.Jo.consumeRateLimit(r)?Ii.info("Skipping exception capture because of client rate limiting.",{exception:r}):(i=this._instance.exceptions)==null||i.sendExceptionEvent(t)}},exceptions:class{constructor(t){var e,n;this.Xo=[],this.tl=new og([new pg,new Sg,new mg,new gg,new bg,new wg,new _g,new Eg],(function(i){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;r>o;o++)s[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` +`),d=l;c.length>d;d++){var f=c[d];if(1024>=f.length){var h=Cc.test(f)?f.replace(Cc,"$1"):f;if(!h.match(/\S*Error: /)){for(var p of s){var g=p(h,i);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var v=Array.from(m);return v.reverse(),v.slice(0,50).map((E=>{return I({},E,{filename:E.filename||(S=v,S[S.length-1]||{}).filename,function:E.function||ni});var S}))})(u)}})("web:javascript",ug,hg)),this._instance=t,this.Xo=(e=(n=this._instance.persistence)==null?void 0:n.get_property(ia))!==null&&e!==void 0?e:[],this.el=Jr(this.il()),this.rl=new Ig(this.el)}onConfigChange(){this.el=Jr(this.il()),this.rl.setConfig(this.el)}onRemoteConfig(t){var e,n,i;if(t.ok){var r=t.config;if("errorTracking"in r){var s=(e=(n=r.errorTracking)==null?void 0:n.suppressionRules)!==null&&e!==void 0?e:[],o=(i=r.errorTracking)==null?void 0:i.captureExtensionExceptions;this.Xo=s,this._instance.persistence&&this._instance.persistence.register({[ia]:this.Xo,[ra]:o})}}}get nl(){var t,e=!!this._instance.get_property(ra),n=this._instance.config.error_tracking.captureExtensionExceptions;return(t=n??e)!==null&&t!==void 0&&t}buildProperties(t,e){return this.tl.buildFromUnknown(t,{syntheticException:e?.syntheticException,mechanism:{handled:e?.handled}})}addExceptionStep(t,e){if(this.el.enabled)try{if(!X(t)||t.trim().length===0)return void St.warn("Ignoring exception step because message must be a non-empty string");var n=(function(s){if(!s)return{sanitizedProperties:{},droppedKeys:[]};var o=[];return{sanitizedProperties:Object.keys(s).reduce(((a,l)=>xg.has(l)?(o.push(l),a):(a[l]=s[l],a)),{}),droppedKeys:o}})(this.sl(e)),i=n.sanitizedProperties,r=n.droppedKeys;r.length>0&&St.warn("Ignoring reserved exception step fields",{droppedKeys:r}),this.rl.add(I({[Kr]:t,[Yr]:new Date().toISOString()},i))}catch(s){St.error("Failed to add exception step. Ignoring breadcrumb.",s)}}sendExceptionEvent(t){try{var e=t.$exception_list;if(this.al(e)){if(this.ol(e))return this.ll("Exception dropped: matched a suppression rule"),void St.info("Skipping exception capture because a suppression rule matched");if(!this.nl&&this.ul(e))return this.ll("Exception dropped: thrown by a browser extension"),void St.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.hl(e))return this.ll("Exception dropped: thrown by the PostHog SDK"),void St.info("Skipping exception capture because it was thrown by the PostHog SDK")}var n=this.el.enabled&&H(t.$exception_steps)?this.dl(t):t,i=typeof(s=globalThis._posthogReleaseId)=="string"&&s.length>0?s:void 0;i&&(n.$release_id=i);try{var r=this._instance.capture("$exception",n,{_noTruncate:!0,_batchKey:"exceptionEvent",Wn:!0});return r&&this.rl.clear(),r}catch(o){return St.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void St.error("Failed to process exception event. Ignoring this exception.",o)}var s}dl(t){try{var e=this.rl.getAttachable();return e.length===0?t:I({},t,{$exception_steps:e})}catch(n){return St.error("Failed to read buffered exception steps. Capturing exception without steps.",n),t}}ll(t){this.el.enabled&&this.rl.add({[Kr]:t,[Yr]:new Date().toISOString()})}sl(t){return he(t)?I({},t):{}}il(){var t,e;return(t=(e=this._instance.config.error_tracking)==null?void 0:e.exception_steps)!==null&&t!==void 0?t:{}}ol(t){if(t.length===0)return!1;try{var e=t.reduce(((n,i)=>{var r=i.type,s=i.value;return X(r)&&r.length>0&&n.$exception_types.push(r),X(s)&&s.length>0&&n.$exception_values.push(s),n}),{$exception_types:[],$exception_values:[]});return this.Xo.some((n=>{var i=n.values.map((r=>{var s=jf[r.operator],o=e[r.key];if(!s||!o)return!1;var a=U(r.value)?r.value:[r.value];return a.length>0&&s(a,o)}));return n.type==="OR"?i.some(Boolean):i.every(Boolean)}))}catch(n){return St.warn("Failed to evaluate suppression rules. Capturing the exception.",n),!1}}ul(t){return t.flatMap((e=>{var n,i;return(n=(i=e.stacktrace)==null?void 0:i.frames)!==null&&n!==void 0?n:[]})).some((e=>e.filename&&e.filename.startsWith("chrome-extension://")))}hl(t){if(t.length>0){var e,n,i,r,s=(e=(n=t[0].stacktrace)==null?void 0:n.frames)!==null&&e!==void 0?e:[],o=s[s.length-1];return(i=o==null||(r=o.filename)==null?void 0:r.includes("posthog.com/static"))!==null&&i!==void 0&&i}return!1}al(t){return!H(t)&&U(t)}}},Vm=I({productTours:class{get Mr(){return this._instance.persistence}constructor(t){this.vl=null,this.cl=null,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(t.ok){var e=t.config;if("productTours"in e){var n,i;if(this.Mr&&this.Mr.register({[sl]:!!e.productTours}),!Oo(this._instance))return!this.vl&&H((n=this.Mr)==null?void 0:n.props[Mi])||xr.info("product tours disabled; stopping and clearing cached tours"),(i=this.vl)==null||i.stop(),this.vl=null,void this.clearCache();this.loadIfEnabled()}}}loadIfEnabled(){!this.vl&&Oo(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.generateProductTours?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",(i=>{i?xr.error("Could not load product tours script",i):t()}))}fl(){var t;!this.vl&&(t=B.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=B.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(t,e){if(e===void 0&&(e=!1),!U(this.cl)||e){var n=this.Mr;if(n){var i=n.props[Mi];if(U(i)&&!e)return this.cl=i,void t(i,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",timestampMode:"query",callback:r=>{if(Oo(this._instance)){var s=r.statusCode;if(s!==200||!r.json){var o="Product Tours API could not be loaded, status: "+s;return s===0?r.error||xr.warn(o):xr.error(o),void t([],{isLoaded:!1,error:o})}var a=U(r.json.product_tours)?r.json.product_tours:[];this.cl=a,n&&n.register({[Mi]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){H(this.vl)?t([],{isLoaded:!1,error:"Product tours not loaded"}):this.vl.getActiveProductTours(t)}showProductTour(t){var e;(e=this.vl)==null||e.showTourById(t)}previewTour(t){this.vl?this.vl.previewTour(t):this.ai((()=>{var e;this.fl(),(e=this.vl)==null||e.previewTour(t)}))}dismissProductTour(){var t;(t=this.vl)==null||t.dismissTour("user_clicked_skip")}nextStep(){var t;(t=this.vl)==null||t.nextStep()}previousStep(){var t;(t=this.vl)==null||t.previousStep()}clearCache(){var t;this.cl=null,(t=this.Mr)==null||t.unregister(Mi)}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)}}},Cs),Gm={siteApps:class{constructor(t){this.pl=0,this._instance=t,this.gl=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}ml(t,e){if(e){var n=this.globalsForEvent(e);this.gl.push(n),this.gl.length>1e3&&(this.gl=this.gl.slice(10))}}get siteAppLoaders(){var t;return(t=B._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,n,i,r,s,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var f=d[0];l[f]={id:u[f],type:f,properties:d[1]}}var h=t.$set_once,p=t.$set;return{event:I({},ud(t,Nm),{properties:I({},t.properties,p?{$set:I({},(e=(n=t.properties)==null?void 0:n.$set)!==null&&e!==void 0?e:{},p)}:{},h?{$set_once:I({},(i=(r=t.properties)==null?void 0:r.$set_once)!==null&&i!==void 0?i:{},h)}:{}),elements_chain:(s=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&s!==void 0?s:"",distinct_id:(a=t.properties)==null?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}bl(t){var e,n=(e=t.tagName)==null?void 0:e.toLowerCase();return n==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(Et.error("prepare_external_dependency_stylesheet returned null"),null):n==="script"&&this._instance.config.prepare_external_dependency_script?this._instance.config.prepare_external_dependency_script(t)||(Et.error("prepare_external_dependency_script returned null"),null):t}_l(){var t,e,n,i,r,s,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=P?.defaultView,u=l==null||(t=l.Node)==null?void 0:t.prototype;if(!l||!u)return()=>{};if(this.pl++,this.wl)return this.kl();var c=[],d=this,f=new WeakSet,h=(m,v,E)=>{if(m!=null&&m[v]){var S=m[v];m[v]=E(S),c.push((()=>{m[v]=S}))}},p=m=>{if(f.has(m))return m;var v=d.bl(m);return v&&f.add(v),v},g=m=>m.map((v=>typeof v=="string"?v:p(v))).filter((v=>!Ke(v)));return h(u,"appendChild",(m=>function(v){var E=p(v);return E?m.call(this,E):v})),h(u,"insertBefore",(m=>function(v,E){var S=p(v);return S?m.call(this,S,E):v})),h(u,"replaceChild",(m=>function(v,E){var S=p(v);return S?m.call(this,S,E):E})),[(e=l.Element)==null?void 0:e.prototype,(n=l.Document)==null?void 0:n.prototype,(i=l.DocumentFragment)==null?void 0:i.prototype].forEach((m=>{h(m,"append",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),h(m,"prepend",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))}))})),[(r=l.Element)==null?void 0:r.prototype,(s=l.CharacterData)==null?void 0:s.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((m=>{h(m,"before",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),h(m,"after",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),h(m,"replaceWith",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];var b=g(S);return S.length&&!b.length?void 0:v.apply(this,b)}))})),h((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(v,E){var S=p(E);return S?m.call(this,v,S):null})),this.wl=()=>{c.forEach((m=>m())),this.wl=void 0},this.kl()}kl(){var t=!1;return()=>{var e;t||(t=!0,this.pl--,this.pl===0&&((e=this.wl)==null||e.call(this)))}}xl(t,e){e===void 0&&(e=!0);var n=this._l();try{var i=t(n);return e&&n(),i}catch(r){throw n(),r}}setupSiteApp(t){var e=this.apps[t.id],n=()=>{var o;!e.errored&&this.gl.length&&(Et.info("Processing "+this.gl.length+" events for site app with id "+t.id),this.gl.forEach((a=>this.xl((()=>e.processEvent==null?void 0:e.processEvent(a))))),e.processedBuffer=!0),Object.values(this.apps).every((a=>a.processedBuffer||a.errored))&&((o=this.yl)==null||o.call(this))},i=!1,r=o=>{e.errored=!o,e.loaded=!0,Et.info("Site app with id "+t.id+" "+(o?"loaded":"errored")),i&&n()};try{var s=this.xl((o=>t.init({posthog:this._instance,callback(a){o(),r(a)}})),!1).processEvent;s&&(e.processEvent=s),i=!0}catch(o){Et.error(uu+t.id,o),r(!1)}if(i&&e.loaded)try{n()}catch(o){Et.error("Error while processing buffered events PostHog app with config id "+t.id,o),e.errored=!0}}Sl(){var t=this.siteAppLoaders||[];for(var e of t)this.apps[e.id]={id:e.id,loaded:!1,errored:!1,processedBuffer:!1};for(var n of t)this.setupSiteApp(n)}Cl(t){var e=this;if(Object.keys(this.apps).length!==0){var n=this.globalsForEvent(t),i=function(s){try{e.xl((()=>s.processEvent==null?void 0:s.processEvent(n)))}catch(o){Et.error("Error while processing event "+t.event+" for site app "+s.id,o)}};for(var r of Object.values(this.apps))i(r)}}onRemoteConfig(t){var e,n,i,r=this;if((e=this.siteAppLoaders)!=null&&e.length)return this.isEnabled?(this.Sl(),void this._instance.on("eventCaptured",(l=>this.Cl(l)))):void Et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((n=this.yl)==null||n.call(this),t.ok){var s=t.config;if((i=s.siteApps)!=null&&i.length)if(this.isEnabled){var o=function(){var l,u=a.id,c=a.url;B["__$$ph_site_app_"+u]=r._instance,(l=B.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(r._instance,c,(d=>{if(d)return Et.error(uu+u,d)}))};for(var a of s.siteApps)o()}else Et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},Km={tracingHeaders:class{constructor(t){this.Ml=void 0,this.Tl=void 0,this.El=void 0,this.Uo=()=>{var e,n,i=this.Il();i?(C(this.Ml)&&(this.Ml=(e=B.__PosthogExtensions__)==null||(e=e.tracingHeadersPatchFns)==null?void 0:e._patchXHR(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager)),C(this.Tl)&&(this.Tl=(n=B.__PosthogExtensions__)==null||(n=n.tracingHeadersPatchFns)==null?void 0:n._patchFetch(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager))):this.Qo()},this._instance=t}initialize(){this.startIfEnabledOrStop()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",(i=>{if(i)return Mm.error("failed to load script",i);t()}))}Pl(){var t,e;return(t=(e=this._instance.config.tracing_headers)!==null&&e!==void 0?e:this._instance.config.addTracingHeaders)!==null&&t!==void 0?t:this._instance.config.__add_tracing_headers}Il(){var t=this.Pl();return U(t)?(U(this.El)?this.El.splice(0,this.El.length,...t):this.El=[...t],t.length>0?this.El:void 0):(U(this.El)&&this.El.splice(0),this.El=t||void 0,this.El)}Qo(){var t,e;(t=this.Ml)==null||t.call(this),(e=this.Tl)==null||e.call(this),this.Ml=void 0,this.Tl=void 0}startIfEnabledOrStop(){this.Il()?this.ai(this.Uo):this.Qo()}}},Ym=I({surveys:class{get Ne(){return this._instance.config}constructor(t){this.Rl=void 0,this._surveyManager=null,this.Al=!1,this.Fl=[],this.Ll=null,this.Ol=null,this._instance=t,this._surveyEventReceiver=null}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this.Ne.disable_surveys){if(!t.ok)return Q.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(H(e))return Q.warn("Flags not loaded yet. Not loading surveys.");var n=U(e);this.Rl=n?e.length>0:e,Q.info("flags response received, isSurveysEnabled: "+this.Rl),this.loadIfEnabled()}}reset(){try{var t;(t=this._surveyEventReceiver)==null||t.reset(),localStorage.removeItem("lastSeenSurveyDate");for(var e=[],n=0;nlocalStorage.removeItem(r)))}catch{}}loadIfEnabled(){if(!this._surveyManager)if(this.Al)Q.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)Q.info(du);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())Q.info("Not loading surveys in cookieless mode without consent.");else{var t=B?.__PosthogExtensions__;if(t){if(!C(this.Rl)||this.Ne.advanced_enable_surveys){var e=this.Rl||this.Ne.advanced_enable_surveys;this.Al=!0;try{var n=t.generateSurveys;if(n)return void this.Dl(n,e);var i=t.loadExternalDependency;if(!i)return void this.$l(al);i(this._instance,"surveys",(r=>{r||!t.generateSurveys?this.$l("Could not load surveys script",r):this.Dl(t.generateSurveys,e)}))}catch(r){throw this.$l("Error initializing surveys",r),r}finally{this.Al=!1}}}else Q.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new Dm(this._instance),Q.info("Surveys loaded successfully"),this.Nl({isLoaded:!0})}$l(t,e){Q.error(t,e),this.Nl({isLoaded:!1,error:t})}onSurveysLoaded(t){return this.Fl.push(t),this._surveyManager&&this.Nl({isLoaded:!0}),()=>{this.Fl=this.Fl.filter((e=>e!==t))}}getSurveys(t,e){if(e===void 0&&(e=!1),this.Ne.disable_surveys)return Q.info(du),t([]);var n,i=this._instance.get_property(la);if(i&&!e)return t(i,{isLoaded:!0}),void(this.ql()&&this.getSurveys((()=>{}),!0));typeof Promise<"u"&&this.Ll?this.Ll.then((r=>t(r.surveys,r.context))):(typeof Promise<"u"&&(this.Ll=new Promise((r=>{n=r}))),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this.Ne.token),method:"GET",timestampMode:"query",timeout:this.Ne.surveys_request_timeout_ms,callback:r=>{var s;this.Ll=null;var o=r.statusCode;if(o!==200||!r.json){var a="Surveys API could not be loaded, status: "+o;o!==0?Q.error(a):r.error||Q.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(n==null||n({surveys:[],context:l}))}this.Ol=null;var u,c=r.json.surveys||[],d=c.filter((h=>(function(p){return!(!p.start_date||p.end_date)})(h)&&(Hf(h)||(function(p){var g;return!((g=p.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(h))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(s=this._instance.persistence)==null||s.register({[la]:c,[Xr]:Date.now()});var f={isLoaded:!0};t(c,f),n?.({surveys:c,context:f})}}))}ql(){return this.jl()&&!this.Ll&&!this.Bl()}jl(){var t=this._instance.get_property(Xr);return ke(t)&&Date.now()-t>3e5}Bl(){return ke(this.Ol)&&3e5>Date.now()-this.Ol}markSurveyAsSeen(t,e){var n,i={id:t,current_iteration:(n=e?.iteration)!==null&&n!==void 0?n:null};qf(i);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}}Nl(t){for(var e of this.Fl)try{if(!t.isLoaded)return e([],t);this.getSurveys(e)}catch(n){Q.error("Error in survey callback",n)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!H(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);Q.warn("init was not called")}Hl(t){var e=null;return this.getSurveys((n=>{var i;e=(i=n.find((r=>r.id===t)))!==null&&i!==void 0?i:null})),e}Ul(t){if(H(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(H(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(H(this._surveyManager))return Q.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 H(this._surveyManager)?(Q.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Ir})):new Promise((n=>{this.getSurveys((i=>{var r,s=(r=i.find((a=>a.id===t)))!==null&&r!==void 0?r:null;if(s){var o=this.zl(s);n({visible:o.eligible,disabledReason:o.reason})}else n({visible:!1,disabledReason:"Survey not found"})}),e)}))}renderSurvey(t,e,n){var i;if(H(this._surveyManager))Q.warn("init was not called");else{var r=typeof t=="string"?this.Hl(t):t;if(r!=null&&r.id)if(bm.includes(r.type)){var s=P?.querySelector(e);if(s)return(i=r.appearance)!=null&&i.surveyPopupDelaySeconds?(Q.info("Rendering survey "+r.id+" with delay of "+r.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;Q.info("Rendering survey "+r.id+" with delay of "+((o=r.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(a=this._surveyManager)==null||a.renderSurvey(r,s,n),Q.info("Survey "+r.id+" rendered")}),1e3*r.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(r,s,n);Q.warn("Survey element not found")}else Q.warn("Surveys of type "+r.type+" cannot be rendered in the app");else Q.warn("Survey not found")}}displaySurvey(t,e){var n;if(H(this._surveyManager))Q.warn("init was not called");else{var i=this.Hl(t);if(i){var r=i;if((n=i.appearance)!=null&&n.surveyPopupDelaySeconds&&e.ignoreDelay&&(r=I({},i,{appearance:I({},i.appearance,{surveyPopupDelaySeconds:0})})),e.displayType!==_a.Popover&&e.initialResponses&&Q.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),e.ignoreConditions===!1){var s=this.Ul(i);if(!s.eligible)return void Q.warn("Survey is not eligible to be displayed: ",s.reason)}e.displayType!==_a.Inline?this._surveyManager.handlePopoverSurvey(r,e):this.renderSurvey(r,e.selector,e.properties)}else Q.warn("Survey not found")}}cancelPendingSurvey(t){H(this._surveyManager)?Q.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},Cs),Jm={toolbar:class{constructor(t){this.instance=t}Wl(t){B.ph_toolbar_state=t}Vl(){var t;return(t=B.ph_toolbar_state)!==null&&t!==void 0?t:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(t,e,n){if(t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),ga(this.instance.config)||!w||!P)return!1;t=t??w.location,n=n??w.history;try{if(!e){try{w.localStorage.setItem("test","test"),w.localStorage.removeItem("test")}catch{return!1}e=w?.localStorage}var i,r=jm||os(t.hash,"__posthog")||os(t.hash,"state"),s=r?Pc((()=>JSON.parse(atob(decodeURIComponent(r)))))||Pc((()=>JSON.parse(decodeURIComponent(r)))):null;return s&&s.action==="ph_authorize"?((i=s).source="url",i&&Object.keys(i).length>0&&(s.desiredHash?t.hash=s.desiredHash:n?n.replaceState(n.state,"",t.pathname+t.search):t.hash="")):((i=JSON.parse(e.getItem(fu)||"{}")).source="localstorage",delete i.userIntent),!(!i.token||this.instance.config.token!==i.token||(this.loadToolbar(i),0))}catch{return!1}}Zl(t){var e=B.ph_load_toolbar||B.ph_load_editor;!H(e)&&De(e)?e(t,this.instance):hu.warn("No toolbar load function found")}loadToolbar(t){var e=!(P==null||!P.getElementById(sf));if(!w||e)return!1;var n=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,i=I({token:this.instance.config.token},t,{apiURL:this.instance.requestRouter.endpointFor("ui")},n?{instrument:!1}:{});if(w.localStorage.setItem(fu,JSON.stringify(I({},i,{source:void 0}))),this.Vl()===2)this.Zl(i);else if(this.Vl()===0){var r;this.Wl(1),(r=B.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"toolbar",(s=>{if(s)return hu.error("[Toolbar] Failed to load",s),void this.Wl(0);this.Wl(2),this.Zl(i)})),ve(w,"turbolinks:load",(()=>{this.Wl(0),this.loadToolbar(i)}))}return!0}Gl(t){return this.loadToolbar(t)}maybeLoadEditor(t,e,n){return t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),this.maybeLoadToolbar(t,e,n)}}},Zm=I({experiments:Me},Cs),Xm={conversations:class{constructor(t){this.Ql=void 0,this._conversationsManager=null,this.Kl=!1,this.Jl=null,this.Yl=!1,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this._instance.config.disable_conversations&&(this.Xl=t.ok,t.ok)){var e=t.config.conversations;H(e)||(mt(e)?this.Ql=e:(this.Ql=e.enabled,this.Jl=e),this.loadIfEnabled())}}reset(){var t;(t=this._conversationsManager)==null||t.reset(),this._conversationsManager=null,this.Ql=void 0,this.Jl=null,this.Xl=void 0,this.Yl=!1}loadIfEnabled(){if(!(this._conversationsManager||this.Kl||this._instance.config.disable_conversations||ga(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=B?.__PosthogExtensions__;if(t&&!C(this.Ql)&&this.Ql)if(this.Jl&&this.Jl.token){this.Kl=!0;try{var e=t.initConversations;if(e)return this.tu(e),void(this.Kl=!1);var n=t.loadExternalDependency;if(!n)return void this.eu(al);n(this._instance,"conversations",(i=>{i||!t.initConversations?this.eu("Could not load conversations script",i):this.tu(t.initConversations),this.Kl=!1}))}catch(i){this.eu("Error initializing conversations",i),this.Kl=!1}}else st.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,st.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else st.error("Cannot complete initialization: remote config is null")}eu(t,e){st.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():st.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!Ke(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":ga(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.Xl===!1?"remote_config_failed":C(this.Ql)?this.Xl?"disabled_in_project":"remote_config_pending":this.Ql?H(this.Jl)||!this.Jl.token?"missing_token":B!=null&&B.__PosthogExtensions__?this.Kl?"initializing":this.Yl?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.isVisible())!==null&&t!==void 0&&t}sendMessage(t,e,n){var i=this;return se((function*(){return i._conversationsManager?i._conversationsManager.sendMessage(t,e,n):(st.warn(En),null)}))()}getMessages(t,e){var n=this;return se((function*(){return n._conversationsManager?n._conversationsManager.getMessages(t,e):(st.warn(En),null)}))()}markAsRead(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(st.warn(En),null)}))()}getTickets(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(st.warn(En),null)}))()}requestRestoreLink(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(st.warn(En),null)}))()}restoreFromToken(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(st.warn(En),null)}))()}restoreFromUrlToken(){var t=this;return se((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(st.warn(En),null)}))()}getCurrentTicketId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getCurrentTicketId())!==null&&t!==void 0?t:null}getWidgetSessionId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getWidgetSessionId())!==null&&t!==void 0?t:null}Xn(){var t;(t=this._conversationsManager)==null||t.setIdentity()}ts(){var t;(t=this._conversationsManager)==null||t.clearIdentity()}}},Qm={logs:class{constructor(t){var e,n=this;this.iu=!1,this.ru=!1,this.rt=pe("[logs]"),this.nu=I({},this.rt,{error(){for(var i=arguments.length,r=new Array(i),s=0;i>s;s++)r[s]=arguments[s];r.some(bu)||n.rt.error(...r)}}),this.tr=[],this.su=[],this.Sa=0,this.au=()=>{var i,r;this.Sa=0,(i=this.ou)==null||i.onReconnect(),(r=this.lu)==null||r.onReconnect()},this._instance=t,this._instance&&(e=this._instance.config.logs)!=null&&e.captureConsoleLogs&&(this.iu=!0),w&&ve(w,"online",this.au)}uu(t,e,n,i){var r,s=(function(o,a){var l,u,c,d,f,h,p,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,v=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,E=C(v)?Math.max(m,2048):Math.max(m,v),S=o?.resourceAttributes;return{serviceName:(d=(f=S?.["service.name"])!==null&&f!==void 0?f:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(h=S?.["service.version"])!==null&&h!==void 0?h:o?.serviceVersion,environment:(p=S?.["deployment.environment"])!==null&&p!==void 0?p:o?.environment,resourceAttributes:S,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:E,maxBatchRecordsPerPost:100,rateCapWindowMs:g,maxLogsPerInterval:v,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}})((r=this._instance)==null||(r=r.config)==null?void 0:r.logs,n);return[new ig(this.hu(t,e),s,this.nu,(()=>this.du()),(o=>o()),void 0,i),s]}vu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.ou||this.cu!==e){var n;(n=this.ou)==null||n.reset(),this.cu=e;var i=this.uu((()=>this.tr),(r=>{this.tr=r}));this.ou=i[0],this.fu=i[1]}return this.ou}pu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.lu||this.gu!==e){var n;(n=this.lu)==null||n.reset(),this.gu=e;var i=this.uu((()=>this.su),(r=>{this.su=r}),{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},wu);this.lu=i[0],this.mu=i[1]}return this.lu}initialize(){this.loadIfEnabled()}onRemoteConfig(t){var e;if(t.ok){var n=(e=t.config.logs)==null?void 0:e.captureConsoleLogs;!H(n)&&n&&(this.iu=!0,this.loadIfEnabled())}}reset(){var t,e;this.tr=[],(t=this.ou)==null||t.reset(),this.su=[],(e=this.lu)==null||e.reset(),this.Sa=0}captureLog(t){this.vu().captureLog(t)}he(t){this.pu().captureLog(t)}get logger(){return this.yu||(this.yu={trace:(t,e)=>this.captureLog({body:t,level:"trace",attributes:e}),debug:(t,e)=>this.captureLog({body:t,level:"debug",attributes:e}),info:(t,e)=>this.captureLog({body:t,level:"info",attributes:e}),warn:(t,e)=>this.captureLog({body:t,level:"warn",attributes:e}),error:(t,e)=>this.captureLog({body:t,level:"error",attributes:e}),fatal:(t,e)=>this.captureLog({body:t,level:"fatal",attributes:e})}),this.yu}flushLogs(t){t?this.bu(t):(this.ou&&this.ou.flush().catch((e=>this._u(e))),this.lu&&this.lu.flush().catch((e=>this._u(e))))}_u(t){bu(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=B?.__PosthogExtensions__;if(t){var e=t.loadExternalDependency;e?e(this._instance,"logs",(n=>{var i;n||(i=t.logs)==null||!i.initializeLogs?this.rt.error("Could not load logs script",n):(t.logs.initializeLogs(this._instance),this.ru=!0)})):this.rt.error(al)}else this.rt.error("PostHog Extensions not found.")}}hu(t,e){var n=this._instance;return{get isDisabled(){return!1},get optedOut(){return!n.is_capturing()},getPersistedProperty:i=>i===Ut.LogsQueue?t():void 0,setPersistedProperty(i,r){var s;i===Ut.LogsQueue&&e((s=r)!==null&&s!==void 0?s:[])},Ot:i=>this.Ot(i),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Ot(t){return new Promise((e=>{if(vf(this.Sa,3))e({kind:"fatal",error:Do(void 0,"logs endpoint is unreachable, dropping batch")});else{var n=!1,i=s=>{n||(n=!0,clearTimeout(r),e(s))},r=setTimeout((()=>{this.rt.warn("Logs request timed out before receiving a response"),i({kind:"retry-later",error:Do(void 0,"logs request timed out")})}),9e4);this._instance._send_request({method:"POST",url:this.wu(),data:t,compression:"best-available",batchKey:"logs",fireCallbackOnDrop:!0,callback:s=>{var o=s.statusCode;if(this.ku(o),o>=200&&300>o)i({kind:"ok"});else if(o===413)i({kind:"too-large"});else if(o!==0&&o!==429&&500>o)i({kind:"fatal",error:new Error("logs request failed with status "+o)});else{var a;o===0?(s.error||this.rt.warn("Logs request failed before receiving an HTTP response"),i({kind:"retry-later",error:Do(s.error,"logs request failed before receiving an HTTP response")})):i({kind:"retry-later",error:(a=s.error)!==null&&a!==void 0?a:new Error("logs request failed with status "+o)})}}})}}))}ku(t){(t!==0||this._instance.__loaded)&&(this.Sa=_f(t,this.Sa,3,(()=>this.rt.warn("Log requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped sending logs; will try again when connectivity changes."))))}bu(t){this.tr.length>0&&this.xu(t,this.tr,this.fu,ne.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,wu,(e=>{this.su=e}))}xu(t,e,n,i,r){if(e.length!==0){var s=e.map((a=>a.record));r([]);var o=Ud(s,jd(n,ne.LIB_NAME,ne.LIB_VERSION),i,ne.LIB_VERSION);this._instance._send_request({method:"POST",url:this.wu(),data:o,compression:"best-available",batchKey:"logs",transport:t})}}wu(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}du(){var t,e={};if(e.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var n=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.windowId,r=n.sessionStartTimestamp,s=n.lastActivityTimestamp;e.sessionId=n.sessionId,e.windowId=i,H(r)||(e.sessionStartTimestamp=r),H(s)||(e.lastActivityTimestamp=s)}if(B!=null&&(t=B.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?fn(B.location.href):B.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},ev={metrics:class{constructor(t){this.rt=pe("[metrics]"),this._instance=t}initialize(){}vu(){var t,e,n=(t=this._instance)==null||(t=t.config)==null?void 0:t.metrics;return this.ou&&this.cu===n||((e=this.ou)==null||e.reset(),this.cu=n,this.ou=new rg(this.hu(),(function(i){var r,s,o,a,l,u=i?.resourceAttributes;return{serviceName:(r=u?.["service.name"])!==null&&r!==void 0?r:i?.serviceName,serviceVersion:(s=u?.["service.version"])!==null&&s!==void 0?s:i?.serviceVersion,environment:(o=u?.["deployment.environment"])!==null&&o!==void 0?o:i?.environment,resourceAttributes:u,beforeSend:i?.beforeSend,flushIntervalMs:(a=i?.flushIntervalMs)!==null&&a!==void 0?a:1e4,maxSeriesPerFlush:(l=i?.maxSeriesPerFlush)!==null&&l!==void 0?l:1e3}})(n),this.rt)),this.ou}count(t,e,n){e===void 0&&(e=1),this.vu().count(t,e,n)}gauge(t,e,n){this.vu().gauge(t,e,n)}histogram(t,e,n){this.vu().histogram(t,e,n)}flush(t){if(!this.ou)return Promise.resolve();if(t){var e=this.ou.drainWindow();return e&&this.Jt(e,t),Promise.resolve()}return this.ou.flush().catch((n=>this.rt.error("PostHog metrics flush failed:",n)))}reset(){var t;(t=this.ou)==null||t.reset()}hu(){var t=this._instance,e=this;return{get isDisabled(){return!1},get optedOut(){return!t.is_capturing()},Jt:n=>e.Jt(n),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Jt(t,e){return new Promise((n=>{var i=!1,r=o=>{i||(i=!0,clearTimeout(s),n(o))},s=setTimeout((()=>r({kind:"retry-later",error:new Error("metrics request timed out")})),9e4);this._instance._send_request(I({method:"POST",url:this.Su(),data:t,compression:"best-available",batchKey:"metrics"},e&&{transport:e},{fireCallbackOnDrop:!0,callback(o){var a=o.statusCode;if(a>=200&&300>a)r({kind:"ok"});else if(a===413)r({kind:"too-large"});else if(a!==0&&a!==429&&500>a)r({kind:"fatal",error:new Error("metrics request failed with status "+a)});else{var l;r({kind:"retry-later",error:(l=o.error)!==null&&l!==void 0?l:new Error("metrics request failed with status "+a)})}}}))}))}Su(){return this._instance.requestRouter.endpointFor("api","/i/v1/metrics")+"?token="+encodeURIComponent(this._instance.config.token)}}},tv=I({},Cs,Wm,qm,zm,Vm,Gm,Ym,Km,Jm,Zm,Xm,Qm,ev);Je.__defaultExtensionClasses=I({},tv);(function(){ne.SDK_DIST_CHANNEL="npm";var t=Wi[Gn]=new Je;return(function(){function e(){e.done||(e.done=!0,Vf=!1,ie(Wi,(function(n){n._dom_loaded()})))}P!=null&&P.addEventListener?P.readyState==="complete"?e():ve(P,"DOMContentLoaded",e,{capture:!1}):w&&A.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const nv=["a[href]","button:not([disabled])","input:not([disabled]):not([type='hidden'])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(",");let pt=null,ka=null,Kf="";const Ca=new Map;function Yf(t){return[...t.querySelectorAll(nv)].filter(e=>!e.hidden&&e.getAttribute("aria-hidden")!=="true"&&e.getClientRects().length>0)}function iv(t){for(const e of document.body.children)e===t||e.tagName==="SCRIPT"||(Ca.set(e,{inert:e.inert,ariaHidden:e.getAttribute("aria-hidden")}),e.inert=!0,e.setAttribute("aria-hidden","true"))}function rv(){for(const[t,e]of Ca)t.inert=e.inert,e.ariaHidden===null?t.removeAttribute("aria-hidden"):t.setAttribute("aria-hidden",e.ariaHidden);Ca.clear()}function Jf(t){return t?.dataset.modalDismissible!=="false"&&t?.getAttribute("aria-busy")!=="true"}function He(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n)return!1;pt&&pt!==n&&We(pt,{restoreFocus:!1,force:!0}),ka=e.trigger||document.activeElement,pt=n,Kf=document.body.style.overflow,iv(n),document.body.style.overflow="hidden",n.classList.add("open"),n.setAttribute("aria-hidden","false");const i=n.querySelector(".modal-content");i&&(i.style.transform="scale(1) translateY(0)");const r=()=>{if(pt!==n)return;((e.initialFocus?n.querySelector(e.initialFocus):n.querySelector("[data-modal-initial-focus]"))||Yf(n)[0]||n.querySelector(".modal-content")||n).focus({preventScroll:!0})};return requestAnimationFrame(r),setTimeout(r,260),!0}function We(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n||!e.force&&!Jf(n))return!1;n.classList.remove("open"),n.setAttribute("aria-hidden","true"),rv(),document.body.style.overflow=Kf,pt=null;const i=ka;return ka=null,e.restoreFocus!==!1&&i?.isConnected&&i.focus({preventScroll:!0}),!0}function Eu(t,e,n="Operation in progress"){const i=typeof t=="string"?document.getElementById(t):t;i&&(i.dataset.modalDismissible=e?"false":"true",i.setAttribute("aria-busy",String(!!e)),e?i.setAttribute("aria-label",n):i.removeAttribute("aria-label"))}function sv(t){if(!Jf(t))return;const e=t.dataset.modalCloseHandler;e&&typeof window[e]=="function"?window[e]():We(t)}document.addEventListener("keydown",t=>{if(!pt)return;if(t.key==="Escape"){t.preventDefault(),t.stopImmediatePropagation(),sv(pt);return}if(t.key!=="Tab"){t.stopPropagation();return}const e=Yf(pt);if(!e.length){t.preventDefault(),(pt.querySelector(".modal-content")||pt).focus();return}const n=e[0],i=e[e.length-1];t.shiftKey&&document.activeElement===n?(t.preventDefault(),i.focus()):!t.shiftKey&&document.activeElement===i&&(t.preventDefault(),n.focus())},!0);function ov(){document.querySelectorAll(".modal-overlay").forEach(t=>{t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-hidden",t.classList.contains("open")?"false":"true");const e=t.querySelector(".modal-content");e&&!e.hasAttribute("tabindex")&&(e.tabIndex=-1);const n=t.querySelector("h1, h2, h3");n&&(n.id||(n.id=`${t.id}-title`),t.setAttribute("aria-labelledby",n.id)),t.querySelectorAll(".modal-close").forEach(i=>{i.getAttribute("aria-label")||i.setAttribute("aria-label","Close dialog")})})}const gl=Object.freeze({free:"Free",professional:"Pro",power:"Power"}),av=Object.freeze({free:2,professional:50,power:2e3}),lv="(contact us)",cv=Object.freeze({free:Object.freeze(["2 generations/month","Gemini model only","Code Review"]),professional:Object.freeze(["50 generations/month","All models","Code Regeneration","Code Review"]),power:Object.freeze(["2000 generations/month","All models","Code Regeneration","Bring your own key (BYOK)","Code Review","All models + early access",`API & MCP access ${lv}`])}),Zf="CodeFile",Xf="GeneratedCode",uv={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function ln(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Aa(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function dv(t={},e=0){const n=Aa(t.artifactType||t.type||Zf),i=Aa(t.artifactName||t.name||t.fileName||`${Xf}-${e+1}`);return`${n||"artifact"}-${i||e+1}`}function Qf(t={},e=0){const n=ln(t),i=n.artifactType||n.type||Zf,r=n.artifactName||n.name||Xf;let s=n.fileName||r;return s.endsWith(".dart")||(s+=".dart"),{id:Aa(n.id)||dv({...n,artifactType:i,artifactName:r,fileName:s},e),artifactType:i,artifactName:r,fileName:s,deployPath:n.deployPath||"",description:n.description||"",code:n.code||n.content||"",dependencies:eh(n.dependencies),imports:Array.isArray(n.imports)?n.imports:[],publicApi:Array.isArray(n.publicApi)?n.publicApi:[],relationships:th(n.relationships),deployStatus:n.deployStatus||"pending",review:n.review||null,metadata:ln(n.metadata),codeType:n.codeType||uv[i]||"O"}}function eh(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const n=ln(e),i=n.name||n.package;return i?{name:i,version:n.version||null,versionRequired:!!(n.versionRequired||n.required),inferred:!!n.inferred,...n.reason?{reason:n.reason}:{}}:null}).filter(Boolean):Object.entries(ln(t)).map(([e,n])=>({name:e,version:n||null,inferred:!1})):[]}function th(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const n=ln(e);return!n.from&&!n.to?null:{from:n.from||null,to:n.to||null,type:n.type||"uses",description:n.description||""}}).filter(Boolean):[]}function Pa(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;try{return JSON.parse(e)}catch{const n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(!n)return null;try{return JSON.parse(n[1].trim())}catch{return null}}}function Qi(t,e={}){const n=[],i=typeof t=="string"?Pa(t):t,s=ln(i||{});!i&&typeof t=="string"&&n.push("Structured bundle parse failed; using legacy single-artifact fallback.");const o=Array.isArray(s.artifacts)?s.artifacts:[{artifactType:s.artifactType||e.artifactType,artifactName:s.artifactName||e.artifactName,fileName:s.fileName||e.fileName,description:s.description,code:s.code||e.code||(typeof t=="string"?t:""),dependencies:s.dependencies||e.dependencies,relationships:s.relationships||e.relationships}];o.forEach((d,f)=>{!d?.artifactType&&!d?.type&&n.push(`Artifact ${f+1} has no artifactType; it will deploy as a standalone code file under lib/custom_code/ root.`)});const a=o.map((d,f)=>Qf(d,f)),l=new Map(o.map((d,f)=>[ln(d).id,a[f]?.id]).filter(([d,f])=>d&&f)),u=d=>l.get(d)||d,c=th(s.relationships||e.relationships).map(d=>({...d,from:d.from?u(d.from):d.from,to:d.to?u(d.to):d.to}));return{schemaVersion:s.schemaVersion||e.schemaVersion||null,id:s.id||e.id||"bundle-current",title:s.title||s.name||e.title||"Generated artifact bundle",description:s.description||e.description||"",artifacts:a,dependencies:eh(s.dependencies||e.dependencies),relationships:c,deployOrder:Array.isArray(s.deployOrder)?s.deployOrder.map(u):a.map(d=>d.id),warnings:[...n,...Array.isArray(s.warnings)?s.warnings:[]],metadata:ln(s.metadata)}}function oi(t){return Qi(t).artifacts[0]||Qf()}function Zt(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function ai(t){return JSON.stringify(t,null,2)}function fv(t){return ai({task:"architect",userRequest:String(t??"")})}function hv(t){const e=Zt(t);return e&&typeof e=="object"&&typeof e.task=="string"?ai(e):ai({task:"generate_bundle",bundleSpec:e})}function pv(t){return ai({task:"review_bundle",generatedBundle:Zt(t),outputRequirements:{bundleReview:["status","score","summary","manualActions","findings"],scoreRange:[0,100],eachArtifact:["id","review.status","review.findings"],manualActions:{definition:"Setup the developer must perform by hand in the FlutterFlow editor that FlutterFlow will NOT do for them.",exclude:["creating the Custom Action, Widget or Code File itself - deploying the code creates it","declaring parameters or return values FlutterFlow derives from the function signature","anything that resolves as a side effect of using the action or widget in the editor","generic advice such as testing, reviewing or rebuilding the app"],preferEmpty:"Return an empty array when nothing qualifies - an empty list is the expected result for most bundles."}}})}function ml(t,e=null){const n={stage:t};return e!=null&&(n.bundle=Zt(e)),n}function gv({bundleSpec:t,artifactBundle:e,bundleReview:n,artifactId:i,userFeedback:r}){return ai({task:"regenerate_artifact",artifactId:i,bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(r)})}function nh({bundleSpec:t,artifactBundle:e,bundleReview:n,userFeedback:i}){return ai({task:"regenerate_bundle",bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(i??"")})}const Su={csam:"child-safety content",dangerous:"dangerous content",harassment:"harassment",hate_speech:"hate speech",maliciousUrls:"a potentially malicious URL",malicious_uris:"a potentially malicious URL",pi_and_jailbreak:"prompt-injection or jailbreak instructions",promptInjection:"prompt-injection or jailbreak instructions",rai:"restricted content",sdp:"sensitive personal data",sexually_explicit:"sexually explicit content",virus_scan:"potentially malicious file content"},mv=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function et(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function vv(t){return et(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||et(t.filterSummary)||et(t.filterResults):!1}function ih(t,e=0){if(!et(t)||e>3)return null;if(vv(t))return t;for(const n of mv){const i=t[n];if(et(i)){const r=ih(i,e+1);if(r)return r}}return null}function ds(t){return Array.isArray(t)?t.some(ds):et(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(ds):!1}function Fa(t){return Array.isArray(t)?t.some(Fa):et(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(Fa):!1}function rh(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function _v(t,e){if(et(t))for(const[n,i]of Object.entries(t)){if(!et(i))continue;const r=et(i.categories)?i.categories:{},s=Object.entries(r).filter(([,o])=>et(o)&&o.matched===!0).map(([o])=>o);s.length>0?s.forEach(o=>e.add(o)):i.matched===!0&&e.add(rh(n))}}function yv(t,e){if(!t)return;const n=Array.isArray(t)?t.flatMap(i=>et(i)?Object.entries(i):[]):Object.entries(t);for(const[i,r]of n){if(!ds(r))continue;const s=rh(i),o=r?.raiFilterResult?.raiFilterTypeResults||(s==="rai"?r?.raiFilterTypeResults:null),a=et(o)?Object.entries(o).filter(([,l])=>ds(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(s)}}function wv(t){return Su[t]?Su[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function xu(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 bv(t){const e=ih(t);if(!e)return null;const n=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);_v(e.filterSummary,n),yv(e.filterResults,n);const i=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||n.size>0,r=e.invocationResult||null,s=Fa(e.filterSummary||e.filterResults);return!i&&!s&&!["PARTIAL","FAILURE"].includes(r)?null:{kind:i?"blocked":"unavailable",invocationResult:r,matchedFilters:[...n]}}function Ev(t,e){const n=bv(t);if(!n)return null;const i=[...new Set(n.matchedFilters.map(wv))],r=n.kind==="blocked",s=new Error(r?`Safety screening blocked this pipeline step for ${xu(i)}.`:"Safety screening could not be completed. Please try again.");return s.name="ModelArmorError",s.code=r?"MODEL_ARMOR_BLOCKED":"MODEL_ARMOR_UNAVAILABLE",s.isModelArmor=!0,s.pipelineStep=e,s.userTitle=r?"Request blocked for safety":"Safety check unavailable",s.userMessage=r?`The safety check detected ${xu(i)}. Edit your request to remove or rephrase the flagged content, then run the pipeline again.`:"The safety service did not finish all of its checks. Please wait a moment and run the pipeline again.",s.retryExplanation=r?"Trying another model would not change this safety decision.":"A fallback model was not attempted because safety screening must complete first.",s.matchedFilters=n.matchedFilters,s}function Sv(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function Iu(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,n=[];for(const i of Sv(t).split(` +`)){if(!/^[A-Za-z_$]/.test(i)||e.test(i))continue;const r=i.match(/^[\w$<>,?\s[\]]+?\s([a-zA-Z_$][\w$]*)\s*\(/);r&&n.push(r[1])}return n}function vl(t,e){const n=t.replace(/\.dart$/,"");if(e==="W")return n.replace(/(^|_)(\w)/g,(i,r,s)=>s.toUpperCase());if(e==="A"){const i=n.replace(/(^|_)(\w)/g,(r,s,o)=>o.toUpperCase());return i.charAt(0).toLowerCase()+i.slice(1)}return e==="F"?"CustomFunctions":e==="C"?t.endsWith(".dart")?t:`${t}.dart`:n}async function ku(t){const e=new TextEncoder().encode(String(t||"")),n=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n),i=>i.toString(16).padStart(2,"0")).join("")}async function xv(t,e=new Map){const n={},i=new Set;for(const[o,a]of t.entries()){if(a.type==="D"||a.type==="O")continue;const l=vl(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await ku(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await ku(c)),n[o]=u,a.type==="F"){const d=Iu(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(h=>i.add(h))}}const r=new Set(Iu(e.get("lib/flutter_flow/custom_functions.dart")||"")),s={functions_to_rename:[],functions_to_delete:[],functions_to_add:Array.from(i).filter(o=>!r.has(o))};return{fileMapContents:JSON.stringify(n),functionsMapContents:JSON.stringify(s)}}const Iv=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),Cu={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},kv=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),Cv=["Struct","Record"],Av=[{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=>jo(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=>jo(t).some(e=>{const n=/^\s*final\s+(?:double|int|String|bool|Color|num)\s+(\w+)\s*;/gm;let i;for(;(i=n.exec(e))!==null;){const r=i[1];if(!(new RegExp(`this\\.${r}\\s*=(?!=)`).test(e)||new RegExp(`[:,]\\s*${r}\\s*=(?!=)`).test(e)))return!0}return!1}),pos:`class W extends StatefulWidget { const W({required this.value}); final double value; @@ -25,46 +25,46 @@ class _S extends State { @override Widget build(BuildContext c) => const Size @override _S createState() => _S(); } class _S extends State { @override Widget build(BuildContext c) => Padding(padding: const EdgeInsets.all(8), child: const SizedBox()); }`}];function xt(t,e,n){return{artifactId:t.id,artifactName:t.artifactName,artifactType:t.artifactType,severity:e,message:n}}function er(t){let e="",n=0;for(;n"&&(n--,n===0))return{inner:t.slice(e+1,i),end:i+1};return null}function Av(t,e){const n=new RegExp(`class\\s+${e}\\b[^{]*\\{`).exec(t);if(!n)return null;let i=0;for(let r=n.index+n[0].length-1;rPv(t).usable);function Rv(t=""){const e=er(t);return Fv.filter(n=>n.detect(e)).map(({id:n,severity:i,message:r})=>({id:n,severity:i,message:r}))}function Tv(t){const e=[],n=t.matchAll(/\bFuture\b/g);for(const i of n){let r=i.index+6,s=null;const o=r;for(;ro;if(t[r]==="<"){const u=Cv(t,r);if(!u||(s=u.inner.replace(/\s+/g," ").trim(),r=u.end,!/\s/.test(t[r]||"")))continue;for(;rAu(o.functionName)===i);if(r)return r;const s=o=>!o.functionName.startsWith("_");return n.find(s)||n[0]}function As(t=""){return Array.from(er(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function $v(t="",e=""){return _l(t,e)?.returnType||null}function Pu(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 Mv(t,e){const n=As(e);if(n.length===0)return null;const r=String(t||"").split("/").pop().replace(/\.dart$/,"");if(n.some(l=>Pu(l)===r)||n.length>1)return null;const[o]=n,a=`${Pu(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 yl(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function Lv(t,e,n=""){const i=_l(e,n)?.functionName;if(!i)return null;const r=String(t||"").split("/").pop(),s=vl(r,"A");if(s===i)return null;const o=`${yl(i)}.dart`;return`File name "${r}" does not match Action "${i}". FlutterFlow derives the action from the file name, so it looks for "${s}" and reports Action "${s}" declaration not found. Rename the file to "${o}" - FlutterFlow puts an underscore before every capital - or rename the function to "${s}".`}function Nv(t="",e=""){return _l(t,e)!==null}function Ov(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(i=>xv.has(i)?!1:!Iv.some(s=>i.endsWith(s))||e.has(i))}function Bv(t,{functionName:e="",declaredTypes:n=new Set}={}){const i=$v(t,e),r=Ov(i,n);if(r.length===0)return null;const[s]=r;let o;return n.has(s)?o=`uses Code File type "${s}", which FlutterFlow cannot process as an Action Return Value`:i===s?o="is not a FlutterFlow Action Return Value":o=`uses type "${s}", which is not a FlutterFlow Action Return Value`,`CustomAction return type "${i}" ${o}. Return JSON (Future) or an existing FlutterFlow Data Type (*Struct) instead.`}function Dv(t,e={}){const n=[],i=t.fileName||"",r=t.code||"";if(Sv.has(t.artifactType)||n.push(xt(t,"error",`Unsupported artifact type "${t.artifactType}".`)),i.endsWith(".dart")||n.push(xt(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!r.trim())return n.push(xt(t,"warning","Generated artifact has no Dart code yet.")),n;if(t.artifactType==="CustomWidget"){/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)||n.push(xt(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const s of Rv(r))n.push(xt(t,s.severity,s.message))}if(t.artifactType==="CustomAction"&&!Nv(r,t.artifactName)&&n.push(xt(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const s=e.declaredTypes||new Set(As(r)),o=Bv(r,{functionName:t.artifactName,declaredTypes:s});o&&n.push(xt(t,"error",o));const a=Lv(i,r,t.artifactName);a&&n.push(xt(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)&&n.push(xt(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const s=Mv(i,r);s&&n.push(xt(t,"info",s))}return n}function jv(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],n=new Set(e.flatMap(s=>As(s.code||""))),i=e.flatMap(s=>Dv(s,{declaredTypes:n})),r=e.map(s=>({artifactId:s.id,fileName:s.fileName,pathHint:Cu[s.artifactType]||Cu.CodeFile}));return{valid:i.every(s=>s.severity!=="error"),findings:i,deployHints:r}}const Fu="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function Ru(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function Uv(t=""){const e=t.indexOf(Fu);return e===-1?t:t.slice(e+Fu.length).replace(/^\s*\n/,"")}const Hv=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function Wv(t="",e=""){const n=Uv(t),i=new Set((e.match(/^\s*import .*$/gm)||[]).map(Ru).filter(Boolean)),r=n.split(` -`).filter(s=>{const o=Ru(s);return o===null||!i.has(o)?!0:!Hv.test(s)}).join(` -`).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+r}const qv=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations"]);function sh(t){let e="",n=0;for(;n{const i=n.name||n.package;if(!i||i==="flutter")return e;const r=n.versionRequired||n.required;return e[i]=r&&n.version||"",e},{})}function Yv(t){const e=new Map,n=new Map,i=[];for(const r of t)e.has(r.fileName)?i.push(`Duplicate deploy file name "${r.fileName}" for artifacts "${e.get(r.fileName)}" and "${r.artifactId}".`):e.set(r.fileName,r.artifactId),n.has(r.path)?i.push(`Duplicate deploy path "${r.path}" for artifacts "${n.get(r.path)}" and "${r.artifactId}".`):n.set(r.path,r.artifactId);return i}function Jv(t,e={}){const n=Array.isArray(t?.artifacts)?t.artifacts:[],r=(e.selectedArtifactIds||t?.deployOrder||n.map(h=>h.id)).map(h=>n.find(p=>p.id===h)).filter(Boolean),s=[...t?.warnings||[]];let o=[];r.forEach(h=>{const p=Kv(h),g=h.fixedCode||h.code||"",m=h.codeType||Vv[h.artifactType]||Ze.OTHER;g.trim()||s.push(`${h.artifactName||h.id} has no generated code.`),o.push({artifactId:h.id,artifactName:h.artifactName,artifactType:h.artifactType,fileName:p,content:g,type:m,path:h.deployPath||Gv(p,m),deployPath:h.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((h,p)=>({entry:h,index:p})).filter(({entry:h})=>h.type===Ze.FUNCTION&&h.path===a);if(l.length>1){const h=l[0],p={...h.entry,artifactId:l.map(({entry:m})=>m.artifactId).join("+"),artifactName:h.entry.artifactName,content:l.map(({entry:m})=>`// ${m.artifactId} +`;)n++;e+=" "}else if(i==="/*"){for(n+=2;n"&&(n--,n===0))return{inner:t.slice(e+1,i),end:i+1};return null}function Fv(t,e){const n=new RegExp(`class\\s+${e}\\b[^{]*\\{`).exec(t);if(!n)return null;let i=0;for(let r=n.index+n[0].length-1;rRv(t).usable);function $v(t=""){const e=er(t);return Tv.filter(n=>n.detect(e)).map(({id:n,severity:i,message:r})=>({id:n,severity:i,message:r}))}function Mv(t){const e=[],n=t.matchAll(/\bFuture\b/g);for(const i of n){let r=i.index+6,s=null;const o=r;for(;ro;if(t[r]==="<"){const u=Pv(t,r);if(!u||(s=u.inner.replace(/\s+/g," ").trim(),r=u.end,!/\s/.test(t[r]||"")))continue;for(;rAu(o.functionName)===i);if(r)return r;const s=o=>!o.functionName.startsWith("_");return n.find(s)||n[0]}function As(t=""){return Array.from(er(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function Lv(t="",e=""){return _l(t,e)?.returnType||null}function Pu(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 Nv(t,e){const n=As(e);if(n.length===0)return null;const r=String(t||"").split("/").pop().replace(/\.dart$/,"");if(n.some(l=>Pu(l)===r)||n.length>1)return null;const[o]=n,a=`${Pu(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 yl(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function Ov(t,e,n=""){const i=_l(e,n)?.functionName;if(!i)return null;const r=String(t||"").split("/").pop(),s=vl(r,"A");if(s===i)return null;const o=`${yl(i)}.dart`;return`File name "${r}" does not match Action "${i}". FlutterFlow derives the action from the file name, so it looks for "${s}" and reports Action "${s}" declaration not found. Rename the file to "${o}" - FlutterFlow puts an underscore before every capital - or rename the function to "${s}".`}function Bv(t="",e=""){return _l(t,e)!==null}function Dv(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(i=>kv.has(i)?!1:!Cv.some(s=>i.endsWith(s))||e.has(i))}function jv(t,{functionName:e="",declaredTypes:n=new Set}={}){const i=Lv(t,e),r=Dv(i,n);if(r.length===0)return null;const[s]=r;let o;return n.has(s)?o=`uses Code File type "${s}", which FlutterFlow cannot process as an Action Return Value`:i===s?o="is not a FlutterFlow Action Return Value":o=`uses type "${s}", which is not a FlutterFlow Action Return Value`,`CustomAction return type "${i}" ${o}. Return JSON (Future) or an existing FlutterFlow Data Type (*Struct) instead.`}function Uv(t,e={}){const n=[],i=t.fileName||"",r=t.code||"";if(Iv.has(t.artifactType)||n.push(xt(t,"error",`Unsupported artifact type "${t.artifactType}".`)),i.endsWith(".dart")||n.push(xt(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!r.trim())return n.push(xt(t,"warning","Generated artifact has no Dart code yet.")),n;if(t.artifactType==="CustomWidget"){/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)||n.push(xt(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const s of $v(r))n.push(xt(t,s.severity,s.message))}if(t.artifactType==="CustomAction"&&!Bv(r,t.artifactName)&&n.push(xt(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const s=e.declaredTypes||new Set(As(r)),o=jv(r,{functionName:t.artifactName,declaredTypes:s});o&&n.push(xt(t,"error",o));const a=Ov(i,r,t.artifactName);a&&n.push(xt(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)&&n.push(xt(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const s=Nv(i,r);s&&n.push(xt(t,"info",s))}return n}function Hv(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],n=new Set(e.flatMap(s=>As(s.code||""))),i=e.flatMap(s=>Uv(s,{declaredTypes:n})),r=e.map(s=>({artifactId:s.id,fileName:s.fileName,pathHint:Cu[s.artifactType]||Cu.CodeFile}));return{valid:i.every(s=>s.severity!=="error"),findings:i,deployHints:r}}const Fu="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function Ru(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function Wv(t=""){const e=t.indexOf(Fu);return e===-1?t:t.slice(e+Fu.length).replace(/^\s*\n/,"")}const qv=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function zv(t="",e=""){const n=Wv(t),i=new Set((e.match(/^\s*import .*$/gm)||[]).map(Ru).filter(Boolean)),r=n.split(` +`).filter(s=>{const o=Ru(s);return o===null||!i.has(o)?!0:!qv.test(s)}).join(` +`).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+r}const Vv=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations"]);function sh(t){let e="",n=0;for(;n{const i=n.name||n.package;if(!i||i==="flutter")return e;const r=n.versionRequired||n.required;return e[i]=r&&n.version||"",e},{})}function Zv(t){const e=new Map,n=new Map,i=[];for(const r of t)e.has(r.fileName)?i.push(`Duplicate deploy file name "${r.fileName}" for artifacts "${e.get(r.fileName)}" and "${r.artifactId}".`):e.set(r.fileName,r.artifactId),n.has(r.path)?i.push(`Duplicate deploy path "${r.path}" for artifacts "${n.get(r.path)}" and "${r.artifactId}".`):n.set(r.path,r.artifactId);return i}function Xv(t,e={}){const n=Array.isArray(t?.artifacts)?t.artifacts:[],r=(e.selectedArtifactIds||t?.deployOrder||n.map(h=>h.id)).map(h=>n.find(p=>p.id===h)).filter(Boolean),s=[...t?.warnings||[]];let o=[];r.forEach(h=>{const p=Jv(h),g=h.fixedCode||h.code||"",m=h.codeType||Kv[h.artifactType]||Ze.OTHER;g.trim()||s.push(`${h.artifactName||h.id} has no generated code.`),o.push({artifactId:h.id,artifactName:h.artifactName,artifactType:h.artifactType,fileName:p,content:g,type:m,path:h.deployPath||Yv(p,m),deployPath:h.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((h,p)=>({entry:h,index:p})).filter(({entry:h})=>h.type===Ze.FUNCTION&&h.path===a);if(l.length>1){const h=l[0],p={...h.entry,artifactId:l.map(({entry:m})=>m.artifactId).join("+"),artifactName:h.entry.artifactName,content:l.map(({entry:m})=>`// ${m.artifactId} ${m.content}`).join(` -`)},g=new Set(l.slice(1).map(({index:m})=>m));o=o.filter((m,v)=>!g.has(v)),o[h.index]=p}const u={...Tu(t?.dependencies),...r.reduce((h,p)=>({...h,...Tu(p.dependencies)}),{})},c={};r.forEach(h=>{wl(h.code||"").forEach(p=>{p in u||(c[p]="")})});const d={...c,...u},f=Yv(o);return{bundleId:t?.id||"bundle-current",title:t?.title||"Generated artifact bundle",fileEntries:o,dependencies:d,relationships:t?.relationships||[],warnings:s,errors:f}}function Zv(t){return String(t||"").match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/)?.[1]}function Xv(t){return String(t||"").split("/").pop().replace(/\.dart$/,"").split(/[^A-Za-z0-9]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function Qv(t,e){const i=[Xv(t),Zv(e.content),e.artifactName].find(r=>/^[A-Z][A-Za-z0-9_]*$/.test(String(r||"")));if(!i)throw new Error(`Cannot derive a FlutterFlow custom class name for ${t}.`);return i}function e_(t,e=new Map){const n=[];for(const[i,r]of t.entries())r.type!=="C"||e.has(r.path)||n.push({artifactId:r.artifactId||i,className:Qv(i,r),content:r.content,fileName:i,path:r.path});return n}function t_(t,e){const n=new Set(e.map(i=>i.path));return new Map(Array.from(t.entries()).filter(([,i])=>!n.has(i.path)))}const $u={pass:0,warning:1,fail:2},n_=["manualActions"];function rt(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Vt(...t){for(const e of t){if(typeof e=="string"&&e.trim())return e.trim();if(Array.isArray(e)&&e.length>0){const n=e.filter(i=>typeof i=="string").join(` -`);if(n)return n}}return""}function kt(t){return t==null?[]:Array.isArray(t)?t:[t]}function i_(t){const e=rt(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const n=Number(e);if(Number.isFinite(n))return Mu(n);const i=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return i?Mu(Number(i[1])):null}function Mu(t){return t>=0&&t<=100?t:null}function at(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function bl(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 Ra(...t){return t.filter(Boolean).reduce((e,n)=>$u[n]>$u[e]?n:e,"pass")}function oh(t,e="warning",n="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:n};const i=rt(t),r=Vt(i.message,i.title,i.issue,i.description,i.summary);return r?{severity:bl(i.severity||i.status||i.level)||e,message:r,suggestion:Vt(i.suggestion,i.fix,i.recommendation,i.action),source:i.source||n}:null}function Ta(t,e="review"){const n=rt(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([r,s])=>kt(n[r]).map(o=>oh(o,s,e)).filter(Boolean))}function r_(t,e,n=null){if(typeof t=="string")return{id:`${n||"bundle"}-manual-${e+1}`,title:t,detail:"",location:"",timing:"unspecified",artifactId:n,source:"Code Review"};const i=rt(t),r=Vt(i.title,i.action,i.step,i.message,i.name,i.description);return r?{id:i.id||`${n||"bundle"}-manual-${e+1}`,title:r,detail:Vt(i.detail,i.instructions,i.description),location:Vt(i.location,i.flutterFlowPath,i.path),timing:Vt(i.timing,i.phase)||"unspecified",artifactId:n,source:Vt(i.source)||"Code Review"}:null}function $a(t,e=null){const n=rt(t);return n_.flatMap(i=>kt(n[i])).map((i,r)=>r_(i,r,e)).filter(Boolean)}function s_(t){let e=typeof t=="string"?Pa(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const n=rt(e);typeof n.content=="string"&&(e=Pa(n.content)||e);const i=rt(e),r=rt(i.reviewResult||i.codeReview||i.result);return{rawText:"",root:Object.keys(r).length?r:i}}function o_(t,e){const n=[e.id,e.fileName,e.artifactName].map(at);return t.find(i=>{const r=rt(i);return[r.id,r.fileName,r.artifactName,r.name].map(at).some(s=>s&&n.includes(s))})||null}function a_(t,e){return kt(t?.metadata?.compatibility?.deployHints).find(r=>at(r?.artifactId)===at(e.id)||at(r?.fileName)===at(e.fileName))?.pathHint||""}function l_(t,e){return kt(t?.relationships).filter(n=>at(n?.from)===at(e.id)||at(n?.to)===at(e.id))}function c_(t,e){return kt(t?.metadata?.compatibility?.findings).filter(n=>!n?.artifactId||at(n.artifactId)===at(e.id)).map(n=>oh(n,"warning","Compatibility check")).filter(Boolean)}function u_(t,e,n,i){const r=o_(e,n),s=rt(r?.review||r||n.review),o=Object.keys(s).length>0,a=[...Ta(s),...c_(t,n)],l=$a(s,n.id),u=bl(s.status||s.verdict||s.outcome||s.result),c=a.length?Ra(...a.map(f=>f.severity)):null,d=Ra(u,c,o?null:"warning");return{...n,index:i,status:d,statusReason:o?Vt(s.summary,s.overview,s.assessment,s.conclusion)||(a.length?`${a.length} review finding${a.length===1?"":"s"}`:"No file-level findings"):"No file-level verdict was returned",reviewComplete:o,findings:a,manualSteps:l,fixedSource:typeof s.fixedSource=="string"&&s.fixedSource.trim()?s.fixedSource.trim():null,pathHint:a_(t,n),relationships:l_(t,n)}}function d_({status:t,score:e,artifactPresentations:n,manualSteps:i}){const r=n.length;if(r===0&&i.length===0)return e==null?"Code review returned no overall summary and no score.":`Reviewed bundle with score ${e}/100.`;const s=n.reduce((a,l)=>(a[l.status]+=1,a),{pass:0,warning:0,fail:0}),o=[];return t&&o.push(`Overall verdict: ${t}.`),r&&o.push(`${r} artifact${r===1?"":"s"}: ${s.pass} pass, ${s.warning} warn, ${s.fail} fail.`),i.length&&o.push(`Do before deploy: ${i.map(a=>a.title).join("; ")}.`),e==null&&o.push("No numeric score (0-100) was returned."),o.join(" ")}function f_({bundle:t,reviewResult:e}){const n=rt(t),i=kt(n.artifacts),{root:r,rawText:s}=s_(e),o=[r.bundleReview,r.overallReview,r.overall,r.bundleSummary,r.summaryReview,r.review].map(rt).find(b=>Object.keys(b).length)||{},a=kt(r.artifacts||r.files||r.reviews),l=i.map((b,_)=>u_(n,a,b,_)),u=Ta(r),d=[...Ta(o),...u],f=[...$a(o),...$a(r),...l.flatMap(b=>b.manualSteps)].filter((b,_,x)=>x.findIndex(I=>I.title===b.title&&I.artifactId===b.artifactId)===_),h=bl(o.status||o.verdict||o.overallStatus||r.status||r.verdict||r.overallStatus||r.outcome),p=Ra(h,...d.map(b=>b.severity),...l.map(b=>b.status)),g=o.score??r.score??r.overallScore??s,m=i_(g),v=Vt(o.headline,o.summary,o.executiveSummary,o.overview,o.assessment,o.conclusion,r.overallSummary,r.headline,r.summary,r.executiveSummary,r.overview,r.assessment,r.conclusion,s)||d_({status:p,score:m,artifactPresentations:l,manualSteps:f}),S=l.reduce((b,_)=>(b[_.status]+=1,b),{pass:0,warning:0,fail:0});return{title:n.title||"Generated artifact bundle",description:n.description||"",status:p,score:m,summary:v,findings:d,manualSteps:f,artifacts:l,counts:S,reviewCoverage:{reviewed:l.filter(b=>b.reviewComplete).length,total:l.length},deployOrder:kt(n.deployOrder),relationships:kt(n.relationships),warnings:kt(n.warnings),compatibility:rt(n.metadata?.compatibility)}}const h_=/^\uFEFF/;function Ci(t){let e=0,n=t.length;for(;ee&&!t[n-1].trim();)n--;return t.slice(e,n).join(` -`)}function p_(t){const e=String(t??"").replace(h_,"");if(!e.trim())return"";const n=e.split(` +`)},g=new Set(l.slice(1).map(({index:m})=>m));o=o.filter((m,v)=>!g.has(v)),o[h.index]=p}const u={...Tu(t?.dependencies),...r.reduce((h,p)=>({...h,...Tu(p.dependencies)}),{})},c={};r.forEach(h=>{wl(h.code||"").forEach(p=>{p in u||(c[p]="")})});const d={...c,...u},f=Zv(o);return{bundleId:t?.id||"bundle-current",title:t?.title||"Generated artifact bundle",fileEntries:o,dependencies:d,relationships:t?.relationships||[],warnings:s,errors:f}}function Qv(t){return String(t||"").match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/)?.[1]}function e_(t){return String(t||"").split("/").pop().replace(/\.dart$/,"").split(/[^A-Za-z0-9]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function t_(t,e){const i=[e_(t),Qv(e.content),e.artifactName].find(r=>/^[A-Z][A-Za-z0-9_]*$/.test(String(r||"")));if(!i)throw new Error(`Cannot derive a FlutterFlow custom class name for ${t}.`);return i}function n_(t,e=new Map){const n=[];for(const[i,r]of t.entries())r.type!=="C"||e.has(r.path)||n.push({artifactId:r.artifactId||i,className:t_(i,r),content:r.content,fileName:i,path:r.path});return n}function i_(t,e){const n=new Set(e.map(i=>i.path));return new Map(Array.from(t.entries()).filter(([,i])=>!n.has(i.path)))}const $u={pass:0,warning:1,fail:2},r_=["manualActions"];function rt(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Vt(...t){for(const e of t){if(typeof e=="string"&&e.trim())return e.trim();if(Array.isArray(e)&&e.length>0){const n=e.filter(i=>typeof i=="string").join(` +`);if(n)return n}}return""}function kt(t){return t==null?[]:Array.isArray(t)?t:[t]}function s_(t){const e=rt(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const n=Number(e);if(Number.isFinite(n))return Mu(n);const i=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return i?Mu(Number(i[1])):null}function Mu(t){return t>=0&&t<=100?t:null}function at(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function bl(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 Ra(...t){return t.filter(Boolean).reduce((e,n)=>$u[n]>$u[e]?n:e,"pass")}function oh(t,e="warning",n="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:n};const i=rt(t),r=Vt(i.message,i.title,i.issue,i.description,i.summary);return r?{severity:bl(i.severity||i.status||i.level)||e,message:r,suggestion:Vt(i.suggestion,i.fix,i.recommendation,i.action),source:i.source||n}:null}function Ta(t,e="review"){const n=rt(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([r,s])=>kt(n[r]).map(o=>oh(o,s,e)).filter(Boolean))}function o_(t,e,n=null){if(typeof t=="string")return{id:`${n||"bundle"}-manual-${e+1}`,title:t,detail:"",location:"",timing:"unspecified",artifactId:n,source:"Code Review"};const i=rt(t),r=Vt(i.title,i.action,i.step,i.message,i.name,i.description);return r?{id:i.id||`${n||"bundle"}-manual-${e+1}`,title:r,detail:Vt(i.detail,i.instructions,i.description),location:Vt(i.location,i.flutterFlowPath,i.path),timing:Vt(i.timing,i.phase)||"unspecified",artifactId:n,source:Vt(i.source)||"Code Review"}:null}function $a(t,e=null){const n=rt(t);return r_.flatMap(i=>kt(n[i])).map((i,r)=>o_(i,r,e)).filter(Boolean)}function a_(t){let e=typeof t=="string"?Pa(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const n=rt(e);typeof n.content=="string"&&(e=Pa(n.content)||e);const i=rt(e),r=rt(i.reviewResult||i.codeReview||i.result);return{rawText:"",root:Object.keys(r).length?r:i}}function l_(t,e){const n=[e.id,e.fileName,e.artifactName].map(at);return t.find(i=>{const r=rt(i);return[r.id,r.fileName,r.artifactName,r.name].map(at).some(s=>s&&n.includes(s))})||null}function c_(t,e){return kt(t?.metadata?.compatibility?.deployHints).find(r=>at(r?.artifactId)===at(e.id)||at(r?.fileName)===at(e.fileName))?.pathHint||""}function u_(t,e){return kt(t?.relationships).filter(n=>at(n?.from)===at(e.id)||at(n?.to)===at(e.id))}function d_(t,e){return kt(t?.metadata?.compatibility?.findings).filter(n=>!n?.artifactId||at(n.artifactId)===at(e.id)).map(n=>oh(n,"warning","Compatibility check")).filter(Boolean)}function f_(t,e,n,i){const r=l_(e,n),s=rt(r?.review||r||n.review),o=Object.keys(s).length>0,a=[...Ta(s),...d_(t,n)],l=$a(s,n.id),u=bl(s.status||s.verdict||s.outcome||s.result),c=a.length?Ra(...a.map(f=>f.severity)):null,d=Ra(u,c,o?null:"warning");return{...n,index:i,status:d,statusReason:o?Vt(s.summary,s.overview,s.assessment,s.conclusion)||(a.length?`${a.length} review finding${a.length===1?"":"s"}`:"No file-level findings"):"No file-level verdict was returned",reviewComplete:o,findings:a,manualSteps:l,fixedSource:typeof s.fixedSource=="string"&&s.fixedSource.trim()?s.fixedSource.trim():null,pathHint:c_(t,n),relationships:u_(t,n)}}function h_({status:t,score:e,artifactPresentations:n,manualSteps:i}){const r=n.length;if(r===0&&i.length===0)return e==null?"Code review returned no overall summary and no score.":`Reviewed bundle with score ${e}/100.`;const s=n.reduce((a,l)=>(a[l.status]+=1,a),{pass:0,warning:0,fail:0}),o=[];return t&&o.push(`Overall verdict: ${t}.`),r&&o.push(`${r} artifact${r===1?"":"s"}: ${s.pass} pass, ${s.warning} warn, ${s.fail} fail.`),i.length&&o.push(`Do before deploy: ${i.map(a=>a.title).join("; ")}.`),e==null&&o.push("No numeric score (0-100) was returned."),o.join(" ")}function p_({bundle:t,reviewResult:e}){const n=rt(t),i=kt(n.artifacts),{root:r,rawText:s}=a_(e),o=[r.bundleReview,r.overallReview,r.overall,r.bundleSummary,r.summaryReview,r.review].map(rt).find(S=>Object.keys(S).length)||{},a=kt(r.artifacts||r.files||r.reviews),l=i.map((S,_)=>f_(n,a,S,_)),u=Ta(r),d=[...Ta(o),...u],f=[...$a(o),...$a(r),...l.flatMap(S=>S.manualSteps)].filter((S,_,b)=>b.findIndex(k=>k.title===S.title&&k.artifactId===S.artifactId)===_),h=bl(o.status||o.verdict||o.overallStatus||r.status||r.verdict||r.overallStatus||r.outcome),p=Ra(h,...d.map(S=>S.severity),...l.map(S=>S.status)),g=o.score??r.score??r.overallScore??s,m=s_(g),v=Vt(o.headline,o.summary,o.executiveSummary,o.overview,o.assessment,o.conclusion,r.overallSummary,r.headline,r.summary,r.executiveSummary,r.overview,r.assessment,r.conclusion,s)||h_({status:p,score:m,artifactPresentations:l,manualSteps:f}),E=l.reduce((S,_)=>(S[_.status]+=1,S),{pass:0,warning:0,fail:0});return{title:n.title||"Generated artifact bundle",description:n.description||"",status:p,score:m,summary:v,findings:d,manualSteps:f,artifacts:l,counts:E,reviewCoverage:{reviewed:l.filter(S=>S.reviewComplete).length,total:l.length},deployOrder:kt(n.deployOrder),relationships:kt(n.relationships),warnings:kt(n.warnings),compatibility:rt(n.metadata?.compatibility)}}const g_=/^\uFEFF/;function Ci(t){let e=0,n=t.length;for(;ee&&!t[n-1].trim();)n--;return t.slice(e,n).join(` +`)}function m_(t){const e=String(t??"").replace(g_,"");if(!e.trim())return"";const n=e.split(` `),i=c=>{const d=c.trim();return/^`{3,}[A-Za-z0-9+#_.-]*$/.test(d)?c.length-c.trimStart().length:-1};let r=0,s=-1;const o=[];{let c=0;for(let d=0;d=0&&(r++,s<0&&(s=d),o.push(c+f)),c+=n[d].length+1}}if(r===0)return Ci(n);{const c=Ma(e);if(!c.error&&o.every(f=>Nu(f,c.commentAndStringRanges)))return Ci(n)}if(r===1){const c=Ci(n.slice(0,s)),d=Ci(n.slice(s+1));return d.length>=c.length?d:c}const a=[];let l=null;for(let c=0;cc.length>0);return u.length===0?"":u.join(` -`)}function g_(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 ah(t){const e=g_(t);return Array.from(e.matchAll(/class\s+([A-Z]\w*)\s+extends\s+[A-Za-z_]\w*Widget\b/g),n=>n[1])}function lh(t){return`${yl(t)}.dart`}function m_(t){return vl(t,"W")}const Lu={"(":")","[":"]","{":"}"},v_={")":"(","]":"[","}":"{"},__=/[A-Za-z0-9_]/;function Ma(t){const e=[{kind:"code",opener:null,openedLine:0}],n=[];let i=1,r=0;const s=(c,d)=>{(c===` +`)}function v_(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 ah(t){const e=v_(t);return Array.from(e.matchAll(/class\s+([A-Z]\w*)\s+extends\s+[A-Za-z_]\w*Widget\b/g),n=>n[1])}function lh(t){return`${yl(t)}.dart`}function __(t){return vl(t,"W")}const Lu={"(":")","[":"]","{":"}"},y_={")":"(","]":"[","}":"{"},w_=/[A-Za-z0-9_]/;function Ma(t){const e=[{kind:"code",opener:null,openedLine:0}],n=[];let i=1,r=0;const s=(c,d)=>{(c===` `||c==="\r"&&d!==` `)&&i++};let o=null;const a=()=>{for(const c of e)(c.kind==="string"||c.kind==="block-comment"||c.kind==="line-comment")&&n.push({start:c.startIndex,end:t.length})};for(;r0?t[r-1]:"",p=r>1?t[r-2]:"",g=(h==="r"||h==="R")&&!__.test(p);e.push({kind:"string",quote:c,triple:f,raw:g,startIndex:r,openedLine:i}),r+=f?3:1;continue}if(Lu[c]){e.push({kind:"code",opener:c,openedLine:i}),r++;continue}if(v_[c]){if(d.interpolation&&c==="}"){e.pop(),r++;continue}if(d.opener&&Lu[d.opener]===c){e.pop(),r++;continue}return d.opener?(a(),{error:o??`line ${i}: "${c}" closes nothing - "${d.opener}" opened on line ${d.openedLine} is still open`,commentAndStringRanges:n}):(a(),{error:o??`line ${i}: unexpected "${c}" with no matching opener`,commentAndStringRanges:n})}s(c,t[r+1]),r++}a();let l=e.length-1;for(;l>0&&e[l].kind==="line-comment";)l--;let u=o;if(!u){const c=e[l];if(!(c.kind==="code"&&!c.opener&&!c.interpolation))if(c.kind==="string")u=`unclosed ${c.triple?"triple-quoted ":""}string starting on line ${c.openedLine} was never closed`;else if(c.kind==="block-comment")u=`unterminated /* comment starting on line ${c.openedLine}`;else if(c.interpolation){const d=e.findLast(h=>h.opener);u=`unclosed "\${" expression${d?` opened on line ${d.openedLine}`:""} was never closed`}else u=`"${c.opener}" opened on line ${c.openedLine} is never closed`}return{error:u,commentAndStringRanges:n}}function y_(t){return Ma(String(t??"")).error}function Nu(t,e){return e.some(({start:n,end:i})=>t>=n&&ttypeof n=="string"?n:n?.errorMessage).filter(Boolean);return e.length>0?e.join("; "):JSON.stringify(t)}return t&&typeof t=="object"?t.errorMessage||JSON.stringify(t):String(t??"")}const w_=["gmail.com","googlemail.com","outlook.com","hotmail.com","live.com","msn.com"],b_="MAGIC_LINK_SENT",E_="PLUS_ALIAS_REJECTED",S_="Please enter your primary email address. Plus aliases (such as {email}) are not allowed for {domain} accounts.",Ps={allowlistedDomains:w_,successCode:b_,validationCode:E_,messageTemplate:S_},x_=new Set(Ps.allowlistedDomains),I_=Ps.successCode,ch=Ps.validationCode;function Fs(t){return typeof t=="string"?t.trim():""}function k_(t){const e=Fs(t),n=e.lastIndexOf("@");if(n<=0||n===e.length-1)return!1;const i=e.slice(0,n),r=e.slice(n+1).toLowerCase();return x_.has(r)?i.includes("+"):!1}function C_(t,e){return Ps.messageTemplate.replaceAll("{email}",t).replaceAll("{domain}",e)}function uh(t){if(!k_(t))return null;const e=Fs(t),n=e.lastIndexOf("@"),i=e.slice(n+1).toLowerCase();return C_(e,i)}function dh(t,e){return t?.code===ch?t.message||uh(e)||"Please enter your primary email address.":t?.code===I_||!t?.code?`Check your email — we sent a link to ${Fs(e)}`:t.message||"Something went wrong. Please try again."}const A_="ccc_auth_session",P_="ccc_subscription",F_=Object.freeze(["hasSeenWalkthrough"]);function R_(t){const e=[];for(const n of F_)t.getItem(n)!==null&&(t.removeItem(n),e.push(n));return e}function T_(){return[A_,P_]}function $_({storage:t,onIdentityChanged:e,onPlanChanged:n}){for(const i of T_())t.removeItem(i);typeof e=="function"&&e(),typeof n=="function"&&n()}function M_({sendLink:t,getEmail:e,onState:n}){let i=!1;return async function(){if(i)return{status:"busy"};i=!0;let s;try{n({status:"pending",error:null});const o=await t(e());return s={status:"sent",data:o},n({status:"sent",data:o}),s}catch(o){return s={status:"error",error:o},n({status:"error",error:o}),s}finally{i=!1}}}const L_=/^dependencies\s*:\s*(?:#.*)?$/,N_=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function Rs(t){const e=t.match(N_);return e?e[1]??e[2]??e[3]:null}function ar(t){const e=t.trim();return e===""||e.startsWith("#")}function fi(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function Sl(t,e){const n=t.findIndex(s=>e.test(s));if(n===-1)return null;let i=n,r=null;for(let s=n+1;s=0.0.0"}`}function j_(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([u])=>u&&u!=="flutter");if(i.length===0)return{yaml:n,added:[],alreadyPresent:[]};const r=n.split(` +`){n.push({start:d.startIndex,end:r}),o??=`line ${i}: string starting on line ${d.openedLine} is never closed`,e.pop();continue}if(!d.raw&&c==="\\"){s(t[r+1]??"",t[r+2]??""),r+=2;continue}if(!d.raw&&c==="$"&&t[r+1]==="{"){e.push({kind:"code",opener:null,interpolation:!0}),r+=2;continue}const f=d.triple?3:1;if(c===d.quote&&t.slice(r,r+f)===d.quote.repeat(f)){n.push({start:d.startIndex,end:r+f}),e.pop(),r+=f;continue}s(c,t[r+1]),r++;continue}if(c==="/"&&t[r+1]==="/"){e.push({kind:"line-comment",startIndex:r}),r+=2;continue}if(c==="/"&&t[r+1]==="*"){e.push({kind:"block-comment",startIndex:r,openedLine:i,depth:1}),r+=2;continue}if(c==="'"||c==='"'){const f=t.slice(r,r+3)===c.repeat(3),h=r>0?t[r-1]:"",p=r>1?t[r-2]:"",g=(h==="r"||h==="R")&&!w_.test(p);e.push({kind:"string",quote:c,triple:f,raw:g,startIndex:r,openedLine:i}),r+=f?3:1;continue}if(Lu[c]){e.push({kind:"code",opener:c,openedLine:i}),r++;continue}if(y_[c]){if(d.interpolation&&c==="}"){e.pop(),r++;continue}if(d.opener&&Lu[d.opener]===c){e.pop(),r++;continue}return d.opener?(a(),{error:o??`line ${i}: "${c}" closes nothing - "${d.opener}" opened on line ${d.openedLine} is still open`,commentAndStringRanges:n}):(a(),{error:o??`line ${i}: unexpected "${c}" with no matching opener`,commentAndStringRanges:n})}s(c,t[r+1]),r++}a();let l=e.length-1;for(;l>0&&e[l].kind==="line-comment";)l--;let u=o;if(!u){const c=e[l];if(!(c.kind==="code"&&!c.opener&&!c.interpolation))if(c.kind==="string")u=`unclosed ${c.triple?"triple-quoted ":""}string starting on line ${c.openedLine} was never closed`;else if(c.kind==="block-comment")u=`unterminated /* comment starting on line ${c.openedLine}`;else if(c.interpolation){const d=e.findLast(h=>h.opener);u=`unclosed "\${" expression${d?` opened on line ${d.openedLine}`:""} was never closed`}else u=`"${c.opener}" opened on line ${c.openedLine} is never closed`}return{error:u,commentAndStringRanges:n}}function b_(t){return Ma(String(t??"")).error}function Nu(t,e){return e.some(({start:n,end:i})=>t>=n&&ttypeof n=="string"?n:n?.errorMessage).filter(Boolean);return e.length>0?e.join("; "):JSON.stringify(t)}return t&&typeof t=="object"?t.errorMessage||JSON.stringify(t):String(t??"")}const E_=["gmail.com","googlemail.com","outlook.com","hotmail.com","live.com","msn.com"],S_="MAGIC_LINK_SENT",x_="PLUS_ALIAS_REJECTED",I_="Please enter your primary email address. Plus aliases (such as {email}) are not allowed for {domain} accounts.",Ps={allowlistedDomains:E_,successCode:S_,validationCode:x_,messageTemplate:I_},k_=new Set(Ps.allowlistedDomains),C_=Ps.successCode,ch=Ps.validationCode;function Fs(t){return typeof t=="string"?t.trim():""}function A_(t){const e=Fs(t),n=e.lastIndexOf("@");if(n<=0||n===e.length-1)return!1;const i=e.slice(0,n),r=e.slice(n+1).toLowerCase();return k_.has(r)?i.includes("+"):!1}function P_(t,e){return Ps.messageTemplate.replaceAll("{email}",t).replaceAll("{domain}",e)}function uh(t){if(!A_(t))return null;const e=Fs(t),n=e.lastIndexOf("@"),i=e.slice(n+1).toLowerCase();return P_(e,i)}function dh(t,e){return t?.code===ch?t.message||uh(e)||"Please enter your primary email address.":t?.code===C_||!t?.code?`Check your email — we sent a link to ${Fs(e)}`:t.message||"Something went wrong. Please try again."}const F_="ccc_auth_session",R_="ccc_subscription",T_=Object.freeze(["hasSeenWalkthrough"]);function $_(t){const e=[];for(const n of T_)t.getItem(n)!==null&&(t.removeItem(n),e.push(n));return e}function M_(){return[F_,R_]}function L_({storage:t,onIdentityChanged:e,onPlanChanged:n}){for(const i of M_())t.removeItem(i);typeof e=="function"&&e(),typeof n=="function"&&n()}function N_({sendLink:t,getEmail:e,onState:n}){let i=!1;return async function(){if(i)return{status:"busy"};i=!0;let s;try{n({status:"pending",error:null});const o=await t(e());return s={status:"sent",data:o},n({status:"sent",data:o}),s}catch(o){return s={status:"error",error:o},n({status:"error",error:o}),s}finally{i=!1}}}const O_=/^dependencies\s*:\s*(?:#.*)?$/,B_=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function Rs(t){const e=t.match(B_);return e?e[1]??e[2]??e[3]:null}function ar(t){const e=t.trim();return e===""||e.startsWith("#")}function fi(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function Sl(t,e){const n=t.findIndex(s=>e.test(s));if(n===-1)return null;let i=n,r=null;for(let s=n+1;s=0.0.0"}`}function H_(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([u])=>u&&u!=="flutter");if(i.length===0)return{yaml:n,added:[],alreadyPresent:[]};const r=n.split(` `),s=new Set(hh(n)),o=[],a=[];for(const[u,c]of i)s.has(u)?a.push(u):(o.push([u,c]),s.add(u));if(o.length===0)return{yaml:n,added:[],alreadyPresent:a};const l=xl(r);if(l){const u=o.map(([c,d])=>Ou(l.childIndent,c,d));r.splice(l.endIndex,0,...u)}else r.length>0&&r[r.length-1].trim()!==""&&r.push(""),r.push("dependencies:"),o.forEach(([u,c])=>{r.push(Ou(" ",u,c))});return{yaml:r.join(` -`),added:o.map(([u])=>u),alreadyPresent:a}}function U_(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([l])=>l&&l!=="flutter");if(i.length===0)return{yaml:n,overridden:[],skipped:[]};const r=n.split(` +`),added:o.map(([u])=>u),alreadyPresent:a}}function W_(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([l])=>l&&l!=="flutter");if(i.length===0)return{yaml:n,overridden:[],skipped:[]};const r=n.split(` `),s=$s(n),o=[],a=[];for(const[l,u]of i){const c=s.get(l);if(!c||!c.isScalar||!String(u||"").trim()){a.push(l);continue}const d=" ".repeat(fi(r[c.lineIndex]));r[c.lineIndex]=`${d}${l}: ${gh(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:r.join(` `),overridden:o,skipped:a}}function mh(t){const e=String(t||""),n=[];return e.trim()?(/^name:\s*\S+/m.test(e)||n.push("pubspec.yaml missing name field"),xl(e.split(` -`))||n.push("pubspec.yaml missing dependencies section"),hh(e).includes("flutter")||n.push("pubspec.yaml missing Flutter SDK dependency"),{valid:n.length===0,errors:n}):(n.push("pubspec.yaml is empty"),{valid:!1,errors:n})}const H_=">=3.0.0 <4.0.0";function La(t){const e=String(t||"").trim(),n=e[0];return n!=="'"&&n!=='"'||e[e.length-1]!==n?e:e.slice(1,-1).replaceAll(`${n}${n}`,n)}function W_(t=""){const e=zv(t).filter(n=>!n.startsWith("dart:")&&!n.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function Bu(t,e,n){const i=[];for(const[r,s]of t){if(s.isScalar){e[r]=La(s.constraint);continue}if(s.sourceKey==="sdk"){n.add(r);continue}if(s.sourceKey===null&&s.version){e[r]=La(s.version);continue}i.push(r)}return i}function q_(t){const e=new Set,n={},i={},r=Bu($s(t),n,e);r.push(...Bu(B_(t,"dependency_overrides"),i,e));const s=new Set([...Object.keys(n),...e]),{sdk:o}=ph(t);return{sdkConstraint:La(o)||H_,dependencies:n,overrides:i,sdkPackages:[...e].sort(),availablePackages:s,unrepresentable:r}}function z_(t,e,n){return e.length>0?`${t} imports ${e.join(", ")}, which FlutterFlow only generates once the app is built, so it could not be compiled before the deploy.`:`${t} imports ${n.join(", ")}, which your project's pubspec.yaml does not declare with a version constraint, so it could not be compiled before the deploy.`}function V_(t,e){const{sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s,availablePackages:o,unrepresentable:a}=q_(e),l={sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s},u=[],c=[],d=a.map(f=>`Your project declares ${f} from a source that cannot be reproduced outside it, so the pre-deploy compile check runs against a scratch package graph that omits ${f}. Classes that do not import ${f} directly are still checked, but against that reduced graph, so their transitive package resolution may differ from your project's and the check is approximate for them.`);for(const f of t){const{className:h,content:p}=f,g=wl(p),m=g.filter(b=>a.includes(b));if(m.length>0){c.push({className:h,reason:`${h} was not compiled before deploying: it imports ${m.join(", ")}, which your project declares from a source that cannot be reproduced outside it, so package resolution could not be matched exactly.`});continue}const{unresolvableImports:v}=W_(p),S=g.filter(b=>!o.has(b));if(v.length>0||S.length>0){c.push({className:h,reason:z_(h,v,S)});continue}u.push({fileName:`${yl(h)}.dart`,content:p})}return{manifest:l,sources:u,skipped:c,approximate:d}}function Du(t,e){const n=`${t}${e}`.split(` -`),i=n.pop()??"",r=[];for(const s of n){const o=vh(s);o&&r.push(o)}return{events:r,buffer:i}}function G_(t){const e=vh(t);return e?[e]:[]}function vh(t){const e=t.trim();if(!e)return null;try{const n=JSON.parse(e);return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}const Xe=Object.freeze({COMMITTED:"committed",PARTIAL:"partial",FAILED:"failed",UNCONFIRMED:"unconfirmed"}),K_=12e4;function _h(t){return t?.unconfirmed===!0||t?.outcome===Xe.UNCONFIRMED?Xe.UNCONFIRMED:t?.partial===!0||t?.outcome===Xe.PARTIAL?Xe.PARTIAL:t?.success===!0?Xe.COMMITTED:Xe.FAILED}class mt extends Error{constructor(e){super(e),this.name="UnconfirmedDeployError",this.outcome=Xe.UNCONFIRMED}}function Y_({httpStatus:t}={}){return new mt(`Every FlutterFlow sync endpoint lost its response or ended in a server error${t?` (last: HTTP ${t})`:""} — neither can prove the push was refused, so it may already have been applied. Open the FlutterFlow project to reconcile before retrying.`)}async function J_(t,e={}){const{onPhase:n,onLog:i}=e;let r=null,s="";const o=l=>{if(l.event==="phase"){l.message&&n&&n(l.message);return}if(l.event==="log"){l.message&&i&&i(l.message);return}r=l};let a=null;try{if(t.body?.getReader){const l=t.body.getReader(),u=new TextDecoder;for(;;){const{done:c,value:d}=await l.read();if(c)break;const f=Du(s,u.decode(d,{stream:!0}));s=f.buffer,f.events.forEach(o)}}else{const l=Du("",await t.text());s=l.buffer,l.events.forEach(o)}}catch(l){a=l}return G_(s).forEach(o),r?{...r,success:r.success===!0||r.success===void 0&&t.ok,finalResultReceived:!0}:{success:!1,finalResultReceived:!1,httpRejected:!t.ok,httpStatus:t.status,error:a?"The connection to the FlutterFlow deploy runner dropped before it reported a result.":t.ok?"The FlutterFlow deploy runner closed the connection before it finished.":`FlutterFlow custom class provisioning failed (HTTP ${t.status}).`}}function Z_(t){return t?.finalResultReceived?_h(t):t?.httpRejected?Xe.FAILED:Xe.UNCONFIRMED}function X_(){let t=document.getElementById("fx-grid");if(!t)return null;const e=window.matchMedia("(prefers-reduced-motion: reduce)"),n=window.matchMedia("(pointer: none)");let i=t.getContext("webgl2",{alpha:!0,antialias:!1,depth:!1,stencil:!1,premultipliedAlpha:!0,powerPreference:"low-power"}),r=i?null:t.getContext("2d");if(!i&&!r)return null;const s='',o=`#version 300 es +`))||n.push("pubspec.yaml missing dependencies section"),hh(e).includes("flutter")||n.push("pubspec.yaml missing Flutter SDK dependency"),{valid:n.length===0,errors:n}):(n.push("pubspec.yaml is empty"),{valid:!1,errors:n})}const q_=">=3.0.0 <4.0.0";function La(t){const e=String(t||"").trim(),n=e[0];return n!=="'"&&n!=='"'||e[e.length-1]!==n?e:e.slice(1,-1).replaceAll(`${n}${n}`,n)}function z_(t=""){const e=Gv(t).filter(n=>!n.startsWith("dart:")&&!n.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function Bu(t,e,n){const i=[];for(const[r,s]of t){if(s.isScalar){e[r]=La(s.constraint);continue}if(s.sourceKey==="sdk"){n.add(r);continue}if(s.sourceKey===null&&s.version){e[r]=La(s.version);continue}i.push(r)}return i}function V_(t){const e=new Set,n={},i={},r=Bu($s(t),n,e);r.push(...Bu(j_(t,"dependency_overrides"),i,e));const s=new Set([...Object.keys(n),...e]),{sdk:o}=ph(t);return{sdkConstraint:La(o)||q_,dependencies:n,overrides:i,sdkPackages:[...e].sort(),availablePackages:s,unrepresentable:r}}function G_(t,e,n){return e.length>0?`${t} imports ${e.join(", ")}, which FlutterFlow only generates once the app is built, so it could not be compiled before the deploy.`:`${t} imports ${n.join(", ")}, which your project's pubspec.yaml does not declare with a version constraint, so it could not be compiled before the deploy.`}function K_(t,e){const{sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s,availablePackages:o,unrepresentable:a}=V_(e),l={sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s},u=[],c=[],d=a.map(f=>`Your project declares ${f} from a source that cannot be reproduced outside it, so the pre-deploy compile check runs against a scratch package graph that omits ${f}. Classes that do not import ${f} directly are still checked, but against that reduced graph, so their transitive package resolution may differ from your project's and the check is approximate for them.`);for(const f of t){const{className:h,content:p}=f,g=wl(p),m=g.filter(S=>a.includes(S));if(m.length>0){c.push({className:h,reason:`${h} was not compiled before deploying: it imports ${m.join(", ")}, which your project declares from a source that cannot be reproduced outside it, so package resolution could not be matched exactly.`});continue}const{unresolvableImports:v}=z_(p),E=g.filter(S=>!o.has(S));if(v.length>0||E.length>0){c.push({className:h,reason:G_(h,v,E)});continue}u.push({fileName:`${yl(h)}.dart`,content:p})}return{manifest:l,sources:u,skipped:c,approximate:d}}function Du(t,e){const n=`${t}${e}`.split(` +`),i=n.pop()??"",r=[];for(const s of n){const o=vh(s);o&&r.push(o)}return{events:r,buffer:i}}function Y_(t){const e=vh(t);return e?[e]:[]}function vh(t){const e=t.trim();if(!e)return null;try{const n=JSON.parse(e);return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}const Xe=Object.freeze({COMMITTED:"committed",PARTIAL:"partial",FAILED:"failed",UNCONFIRMED:"unconfirmed"}),_h=12e4;function yh(t){return t?.unconfirmed===!0||t?.outcome===Xe.UNCONFIRMED?Xe.UNCONFIRMED:t?.partial===!0||t?.outcome===Xe.PARTIAL?Xe.PARTIAL:t?.success===!0?Xe.COMMITTED:Xe.FAILED}class lt extends Error{constructor(e){super(e),this.name="UnconfirmedDeployError",this.outcome=Xe.UNCONFIRMED}}function J_({httpStatus:t}={}){return new lt(`Every FlutterFlow sync endpoint lost its response or ended in a server error${t?` (last: HTTP ${t})`:""} — neither can prove the push was refused, so it may already have been applied. Open the FlutterFlow project to reconcile before retrying.`)}async function Z_(t,e={}){const{onPhase:n,onLog:i}=e;let r=null,s="";const o=l=>{if(l.event==="phase"){l.message&&n&&n(l.message);return}if(l.event==="log"){l.message&&i&&i(l.message);return}r=l};let a=null;try{if(t.body?.getReader){const l=t.body.getReader(),u=new TextDecoder;for(;;){const{done:c,value:d}=await l.read();if(c)break;const f=Du(s,u.decode(d,{stream:!0}));s=f.buffer,f.events.forEach(o)}}else{const l=Du("",await t.text());s=l.buffer,l.events.forEach(o)}}catch(l){a=l}return Y_(s).forEach(o),r?{...r,success:r.success===!0||r.success===void 0&&t.ok,finalResultReceived:!0}:{success:!1,finalResultReceived:!1,httpRejected:!t.ok,httpStatus:t.status,error:a?"The connection to the FlutterFlow deploy runner dropped before it reported a result.":t.ok?"The FlutterFlow deploy runner closed the connection before it finished.":`FlutterFlow custom class provisioning failed (HTTP ${t.status}).`}}function X_(t){return t?.finalResultReceived?yh(t):t?.httpRejected?Xe.FAILED:Xe.UNCONFIRMED}function Q_(){let t=document.getElementById("fx-grid");if(!t)return null;const e=window.matchMedia("(prefers-reduced-motion: reduce)"),n=window.matchMedia("(pointer: none)");let i=t.getContext("webgl2",{alpha:!0,antialias:!1,depth:!1,stencil:!1,premultipliedAlpha:!0,powerPreference:"low-power"}),r=i?null:t.getContext("2d");if(!i&&!r)return null;const s='',o=`#version 300 es in vec2 p; void main(){ gl_Position = vec4(p, 0.0, 1.0); }`;function a(){return["#version 300 es","precision highp float;","out vec4 o;","uniform vec2 res;","uniform vec2 design;","uniform vec2 mouse;","uniform float energy;","uniform float parallax;","uniform float t;","uniform vec3 ink;","uniform sampler2D mark;","uniform vec2 rot;","const float WARP_A = 0.0032;","void main(){"," vec2 px = gl_FragCoord.xy * (design / res);"," vec2 p = vec2(px.x, design.y - px.y);"," vec2 off = vec2(0.0, -parallax) + vec2(sin(t * 0.11), cos(t * 0.09)) * 7.0;"," vec2 g = p + off;"," vec2 gm = mouse + off;"," float base = min(design.x, design.y);"," float spacing = clamp(base / 10.0, 64.0, 118.0);"," vec2 rel = g - gm;"," float rho = length(rel) + 1e-5;"," vec2 dir = rel / rho;"," vec2 pw = gm + dir * (rho + WARP_A * rho * rho);"," vec2 cell = floor(pw / spacing);"," vec2 cw = (cell + 0.5) * spacing - gm;"," float Rc = length(cw) + 1e-5;"," float rhoC = (-1.0 + sqrt(1.0 + 4.0 * WARP_A * Rc)) / (2.0 * WARP_A);"," vec2 c = gm + (cw / Rc) * rhoC;"," float cellSize = spacing / (1.0 + 2.0 * WARP_A * rhoC);"," float sigma = spacing * 2.9;"," float f = exp(-(rhoC * rhoC) / (2.0 * sigma * sigma));"," float scale = mix(0.32, 1.42, f);"," float weight = smoothstep(0.06, 0.80, f);"," float hs = cellSize * 0.26 * scale;"," vec2 uv = (g - c) / hs;"," vec2 ruv = mat2(rot.x, rot.y, -rot.y, rot.x) * uv;"," float cov = 0.0;"," if (abs(ruv.x) <= 1.0 && abs(ruv.y) <= 1.0) cov = texture(mark, ruv * 0.5 + 0.5).a;"," float s = cov * weight * energy * 0.26;"," o = vec4(ink * s, s);","}"].join(` -`)}let l=null,u,c,d,f,h,p,g,m,v;function S(Y,W){if(!i)return null;const D=i.createShader(Y);return i.shaderSource(D,W),i.compileShader(D),i.getShaderParameter(D,i.COMPILE_STATUS)?D:(window.console&&console.warn("fx-grid shader: "+i.getShaderInfoLog(D)),null)}if(i){const Y=S(i.VERTEX_SHADER,o),W=S(i.FRAGMENT_SHADER,a());if(Y&&W&&(l=i.createProgram(),i.attachShader(l,Y),i.attachShader(l,W),i.linkProgram(l),i.getProgramParameter(l,i.LINK_STATUS)||(window.console&&console.warn("fx-grid link: "+i.getProgramInfoLog(l)),l=null)),l){i.useProgram(l),i.bindBuffer(i.ARRAY_BUFFER,i.createBuffer()),i.bufferData(i.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),i.STATIC_DRAW);const D=i.getAttribLocation(l,"p");i.enableVertexAttribArray(D),i.vertexAttribPointer(D,2,i.FLOAT,!1,0,0),u=i.getUniformLocation(l,"res"),c=i.getUniformLocation(l,"design"),d=i.getUniformLocation(l,"mouse"),f=i.getUniformLocation(l,"energy"),h=i.getUniformLocation(l,"parallax"),p=i.getUniformLocation(l,"t"),g=i.getUniformLocation(l,"ink"),m=i.getUniformLocation(l,"mark"),v=i.getUniformLocation(l,"rot"),i.enable(i.BLEND),i.blendFunc(i.ONE,i.ONE_MINUS_SRC_ALPHA),i.clearColor(0,0,0,0)}else{i=null;const D=t.cloneNode(!1);if(t.parentNode.replaceChild(D,t),t=D,r=t.getContext("2d"),!r)return null}}function b(Y){if(!Y)return null;const W=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(Y);if(W){let D=W[1];return D.length===3&&(D=D[0]+D[0]+D[1]+D[1]+D[2]+D[2]),[parseInt(D.slice(0,2),16)/255,parseInt(D.slice(2,4),16)/255,parseInt(D.slice(4,6),16)/255]}try{const D=document.createElement("canvas");D.width=1,D.height=1;const ue=D.getContext("2d");ue.fillStyle="rgb(9, 8, 7)";const xe=String(ue.fillStyle);ue.fillStyle=Y;const Fe=String(ue.fillStyle);if(Fe===xe)return null;const ut=/^#([0-9a-f]{6})$/i.exec(Fe);if(ut){const dt=ut[1];return[parseInt(dt.slice(0,2),16)/255,parseInt(dt.slice(2,4),16)/255,parseInt(dt.slice(4,6),16)/255]}const Nt=/rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i.exec(Fe);if(Nt)return[Number(Nt[1])/255,Number(Nt[2])/255,Number(Nt[3])/255]}catch{}return null}function _(){let Y="";try{const W=getComputedStyle(document.documentElement);Y=(W.getPropertyValue("--fx-ink")||"").trim()||(W.getPropertyValue("--fg")||"").trim()}catch{}return b(Y)||[.56,.68,.88]}const x=_();let I=1920,T=1080,E=960,P=540,$=960,O=540,L=.66,N=0,K=-1e9,V=!1,M=0,R=0,Z=null,Ce=!1,oe=!1,ye=!1;const $e=64,ae=15.2;let Ie=0,Se=0;const Be=.0032,wt=0,ge=.56,Ye=.26,bt=.32,mn=.16,Re=.349;let Pe=wt;function $t(){const Y=t.getBoundingClientRect(),W=t.clientWidth,D=t.clientHeight;if(!Y.width||!W||!D)return;const ue=Math.min(window.devicePixelRatio||1,2),xe=Math.max(.2,Math.min(2,Y.width/W*ue)),Fe=Math.max(2,Math.round(W*xe)),ut=Math.max(2,Math.round(D*xe));(Fe!==t.width||ut!==t.height)&&(t.width=Fe,t.height=ut,i&&i.viewport(0,0,Fe,ut)),I=W,T=D,V||(E=$=I/2,P=O=T/2,V=!0)}function Bn(Y){!l||!Ce||!i||(i.uniform2f(u,t.width,t.height),i.uniform2f(c,I,T),i.uniform2f(d,E,P),i.uniform1f(f,L),i.uniform1f(h,N),i.uniform2f(v,Math.cos(Pe),Math.sin(Pe)),i.uniform1f(p,Y),i.uniform3f(g,x[0],x[1],x[2]),i.clear(i.COLOR_BUFFER_BIT),i.drawArrays(i.TRIANGLES,0,3))}function qe(Y,W,D){const ue=Math.max(0,Math.min(1,(D-Y)/(W-Y)));return ue*ue*(3-2*ue)}function Dn(Y){if(!Z||!r)return;const W=r;W.setTransform(1,0,0,1,0,0),W.clearRect(0,0,t.width,t.height);const D=t.width/I;W.setTransform(D,0,0,D,0,0),W.globalAlpha=1;const ue=Math.min(I,T),xe=Math.max(64,Math.min(118,ue/10)),Fe=xe*2.9,ut=2*Fe*Fe,Nt=Math.sin(Y*.11)*7,dt=Math.cos(Y*.09)*7-N,dr=E+Nt,fr=P+dt,no=Fe*Math.sqrt(2*Math.log(1/.06)),mi=no+Be*no*no+xe,Ip=Math.floor((dr-mi)/xe)-1,kp=Math.ceil((dr+mi)/xe)+1,Cp=Math.floor((fr-mi)/xe)-1,Ap=Math.ceil((fr+mi)/xe)+1;for(let io=Cp;io<=Ap;io++){const Pp=(io+.5)*xe;for(let ro=Ip;ro<=kp;ro++){const so=(ro+.5)*xe-dr,oo=Pp-fr,ao=Math.sqrt(so*so+oo*oo)+1e-5;if(ao>mi)continue;const hr=(-1+Math.sqrt(1+4*Be*ao))/(2*Be),ac=Math.exp(-(hr*hr)/ut),lc=qe(.06,.8,ac)*L*.26;if(lc<.004)continue;const on=xe/(1+2*Be*hr)*.26*(.32+1.1*ac),cc=hr/ao,lo=dr+so*cc,co=fr+oo*cc;lo<-on*1.6||lo>I+on*1.6||co<-on*1.6||co>T+on*1.6||(W.globalAlpha=lc,W.save(),W.translate(lo,co),W.rotate(Pe),W.drawImage(Z,-on,-on,on*2,on*2),W.restore())}}W.globalAlpha=1}function Mt(Y){if(!oe)return;const W=R?Math.min(.05,(Y-R)/1e3):.016;R=Y;const ue=Y-K>2400?.6:1;L+=(ue-L)*Math.min(1,W*3.2);const xe=Math.min(.05,W);Ie+=(($-E)*$e-Ie*ae)*xe,Se+=((O-P)*$e-Se*ae)*xe,E+=Ie*xe,P+=Se*xe,N=(window.scrollY||window.pageYOffset||0)*.55;const Fe=Y/1e3,ut=E/(I||1)-.5,Nt=P/(T||1)-.5;let dt=ut*(ut>=0?ge:Ye)+Nt*(Nt>=0?bt:mn);dt>Re?dt=Re:dt<-Re&&(dt=-Re),Pe=wt+dt-N*6e-4,$t(),i?Bn(Fe):Dn(Fe),M=requestAnimationFrame(Mt)}function Lt(Y){if(!oe)return;const W=t.getBoundingClientRect();!W.width||!I||!T||($=(Y.clientX-W.left)/W.width*I,O=(Y.clientY-W.top)/W.height*T,K=performance.now())}function ct(){oe||to||e.matches||n.matches||!ye||document.hidden||(oe=!0,R=0,M=requestAnimationFrame(Mt))}function sn(){oe=!1,M&&(cancelAnimationFrame(M),M=0),R=0}function gi(){e.matches?(sn(),t.classList.remove("is-ready")):ye&&ct()}function jn(){n.matches?sn():ye&&ct()}function rc(){document.hidden?sn():ye&&ct()}const sc=new IntersectionObserver(Y=>{ye=Y[0]?.isIntersecting||!1,ye?ct():sn()},{threshold:0});sc.observe(t),window.addEventListener("pointermove",Lt,{passive:!0,capture:!0}),window.addEventListener("resize",$t),e.addEventListener("change",gi),n.addEventListener("change",jn),document.addEventListener("visibilitychange",rc);function xp(){const Y=(s.match(/\sd="([^"]+)"/)||[])[1],W=document.createElement("canvas");W.width=256,W.height=256;const D=W.getContext("2d");if(Y&&window.Path2D){const ue=Math.min(8.533333333333333,8.421052631578947);D.setTransform(ue,0,0,ue,ue+(256-30*ue)/2,-6.4*ue),D.fillStyle="rgb(255,255,255)",D.fill(new Path2D(Y),"evenodd"),D.setTransform(1,0,0,1,0,0)}try{const ue=D.getImageData(0,0,256,256),xe=ue.data;for(let Fe=3;Feoe}}const Q_=120;function ey(t,e,n){return tn?n:t}function de(t,e,n){return ey((t-e)/(n-e),0,1)}function ty(t){return t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2}function Uo(t){return 1-Math.pow(1-t,3)}function ze(t,e){return e=e===void 0?1.7:e,1+(e+1)*Math.pow(t-1,3)+e*Math.pow(t-1,2)}function ju(t){return 1-Math.pow(2,-9*t)*Math.cos(t*15)}function te(t,e){if(t<=e[0].t)return e[0].v;for(let n=1;n8.2&&_<9.4&&(s*=1-.07*Math.sin(de(_,8.2,9.4)*Math.PI))}else if(t<53){const _=t-42;g=te(_,[{t:0,v:1},{t:2,v:0},{t:4.2,v:0},{t:4.6,v:1},{t:6.8,v:1},{t:7.4,v:0},{t:9.4,v:0},{t:10.6,v:1}]),p=te(_,[{t:0,v:1},{t:2,v:.3},{t:4.6,v:1,e:ze}]),d=te(_,[{t:0,v:0},{t:2,v:.3},{t:4.6,v:.16,e:ze},{t:10.6,v:0}]),h=te(_,[{t:0,v:0},{t:2,v:-40},{t:4.6,v:0,e:ze}]),o=te(_,[{t:0,v:0},{t:4.6,v:-.12},{t:10.6,v:0}])}else if(t<60){const _=t-53;c=te(_,[{t:0,v:1},{t:.35,v:0},{t:.45,v:0},{t:.7,v:1}]);const x=de(_,.45,2.2);a=x>0?-2.6*(1-ju(x)):0,g=te(_,[{t:0,v:1},{t:.57,v:0},{t:.67,v:0},{t:.92,v:1}]);const I=de(_,.67,2.42);f=I>0?-2.6*(1-ju(I)):0,s=1-.05*(Math.sin(de(_,1.9,2.5)*Math.PI)+Math.sin(de(_,2.5,3.1)*Math.PI))}else if(t<74){let x=function(P){return[te(P,[{t:0,v:0},{t:.25,v:1},{t:.5,v:1},{t:.72,v:.14},{t:.82,v:.14},{t:1,v:0}]),te(P,[{t:0,v:0},{t:.08,v:-.62},{t:.25,v:-.62},{t:.33,v:.62},{t:.7,v:.62},{t:.82,v:-.62},{t:1,v:-.62}])]};var b=x;const _=t-60,I=1-de(_,12,14),T=x(de(_,0,12)),E=x(de(_-.5,0,12));n=T[0]*I,i=(T[1]+.05*Math.sin(_*7))*I,o=(E[0]-T[0])*.6*I,a=(E[1]-T[1])*.6*I,h=(E[0]-T[0])*30*I,S=de(_,0,.4)*I}else if(t<85.4){const _=t-74,x=te(_,[{t:0,v:0},{t:4,v:1},{t:8,v:.24},{t:9.6,v:1,e:ze},{t:11.4,v:0}]);o=x*.5,d=-x*.5,l=te(_,[{t:0,v:0},{t:4,v:6},{t:8,v:20},{t:9.6,v:38,e:ze},{t:11.4,v:0}]),h=-l*.7,a=te(_,[{t:0,v:0},{t:8,v:0},{t:9.6,v:.4},{t:11.4,v:0}])}else if(t<96.4){const _=t-85.4,x=de(_,0,5.6),I=de(_,5.6,7.6),T=.72*Math.min(1,_/.6)*(1-I);d=Math.cos(x*Math.PI*2)*T,f=Math.sin(x*Math.PI*2)*T*.55,h=x*360*(1-I);const E=te(_,[{t:0,v:0},{t:7.6,v:0},{t:8.2,v:1,e:Uo},{t:8.6,v:.55},{t:9.4,v:0}]);o=-.16*E,d+=.16*E,l=-6*E,h+=6*E,s=1+.05*E,m=1+.9*E}else if(t<108.6){const _=t-96.4,x=de(_,9.6,12.2);n=te(_,[{t:0,v:0},{t:2.1,v:1},{t:4.8,v:.08},{t:7.5,v:1},{t:9.6,v:0}])*(1-x),i=-.35*Math.abs(Math.sin(de(_,0,9.6)*Math.PI*3))*(1-x);const I=Math.sin(_*6.2)*(1-x);u=1+.12*I,p=1-.12*I,l=I*8,h=-I*8,o=.06*I,d=-.06*I,S=de(_,0,.4)*(1-x)}else{const _=t-108.6,x=Math.sin(de(_,0,8)*Math.PI),I=1-de(_,8,11.4);s=1+.04*x*I,i=-.1*x*I,r=2*x*I,m=1+.5*Math.sin(de(_,0,6)*Math.PI),v=1+.1*Math.sin(de(_,0,6)*Math.PI)}return e.x=n,e.y=i,e.rot=r,e.scale=s,e.ax=o,e.ay=a,e.ar=l,e.asc=u,e.afade=c,e.bx=d,e.by=f,e.br=h,e.bsc=p,e.bfade=g,e.hfade=m,e.hsc=v,e.shd=S,e}function ny(t={}){const e=t.arena||document.querySelector(".pipeline-glyph.logo-loop");if(!e)return null;const n=e.querySelector(".loop-mark"),i=e.querySelector(".loop-piece-a"),r=e.querySelector(".loop-piece-b"),s=e.querySelector(".loop-halo"),o=e.querySelector(".loop-shadow");if(!n||!i||!r||!s||!o)return null;const a=t.reducedMotion||window.matchMedia("(prefers-reduced-motion: reduce)"),l=Q_;let u=34,c=0,d=0;function f(){u=n.offsetWidth||34,c=Math.max(0,e.offsetWidth-u-4),d=Math.max(0,(e.offsetHeight-u)/2-2),e.style.setProperty("--mark-c",u/2+"px")}function h(M){const R=Math.min(1,Math.max(0,M.x))*c,Z=M.y*d;n.style.transform="translate3d("+R.toFixed(2)+"px,"+Z.toFixed(2)+"px,0) rotate("+M.rot.toFixed(2)+"deg) scale("+M.scale.toFixed(3)+")",i.style.transform="translate3d("+(M.ax*u).toFixed(2)+"px,"+(M.ay*u).toFixed(2)+"px,0) rotate("+M.ar.toFixed(2)+"deg) scale("+M.asc.toFixed(3)+")",i.style.opacity=M.afade.toFixed(3),r.style.transform="translate3d("+(M.bx*u).toFixed(2)+"px,"+(M.by*u).toFixed(2)+"px,0) rotate("+M.br.toFixed(2)+"deg) scale("+M.bsc.toFixed(3)+")",r.style.opacity=M.bfade.toFixed(3),s.style.transform="scale("+M.hsc.toFixed(3)+")",s.style.opacity=(.09*M.hfade).toFixed(3),o.style.transform="translateX("+R.toFixed(2)+"px) scaleX("+(.75+.4*Math.abs(M.x)).toFixed(3)+")",o.style.opacity=(M.shd*.5).toFixed(3)}let p=0,g=0,m=0,v=!1,S=!1,b=!1,_=0;function x(){return b||a.matches||document.hidden||!e.offsetParent?!1:S}function I(M){if(!v)return;if(m=requestAnimationFrame(I),!x()){E();return}const R=g?(M-g)/1e3:0;g=M,p=(p+Math.min(R,.1))%l,_+=1,h(Ai(p))}function T(){v||b||x()&&(v=!0,g=0,m=requestAnimationFrame(I))}function E(){v=!1,m&&(cancelAnimationFrame(m),m=0),g=0}function P(){x()?T():E()}function $(){a.matches?(E(),h(Ai(0))):P()}function O(){f(),v&&h(Ai(p))}function L(){g=0,P()}const N=new IntersectionObserver(M=>{S=M[0]?M[0].isIntersecting:!1,P()},{threshold:0});N.observe(e),window.addEventListener("resize",O),a.addEventListener("change",$),document.addEventListener("visibilitychange",L);function K(){b||(b=!0,E(),N.disconnect(),window.removeEventListener("resize",O),a.removeEventListener("change",$),document.removeEventListener("visibilitychange",L))}window.addEventListener("pagehide",K);function V(M){p=(M%l+l)%l,h(Ai(p))}return f(),h(Ai(0)),P(),{isRunning:()=>v,currentTime:()=>p,frameCount:()=>_,seek:V,dispose:K}}const iy=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function Xt(t){const e=String(t||"").trim().match(iy);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function ry(t,e){if(t.length===0&&e.length===0)return 0;if(t.length===0)return 1;if(e.length===0)return-1;for(let n=0;n0)}function oy(t){const e=Xt(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function Il(t){let e=String(t??"").trim();if((e.startsWith("'")||e.startsWith('"'))&&(e=e.slice(1,-1).trim()),e===""||e==="any"||e==="*")return{min:null,minInclusive:!1,max:null,maxInclusive:!1};if(e.startsWith("^")){const o=e.slice(1).trim();return Xt(o)?{min:o,minInclusive:!0,max:oy(o),maxInclusive:!1}:null}if(Xt(e))return{min:e,minInclusive:!0,max:e,maxInclusive:!0};const n={min:null,minInclusive:!1,max:null,maxInclusive:!1},i=/(>=|<=|>|<)\s*([0-9][0-9A-Za-z.+-]*)/g;let r=!1,s;for(;(s=i.exec(e))!==null;){const[,o,a]=s;if(!Xt(a))return null;r=!0,o===">="||o===">"?(n.min=a,n.minInclusive=o===">="):(n.max=a,n.maxInclusive=o==="<=")}return r?n:null}function Uu(t,e){const n=Il(t);if(!n||!Xt(e))return!1;if(n.min!==null){const i=fs(e,n.min);if(i<0||i===0&&!n.minInclusive)return!1}if(n.max!==null){const i=fs(e,n.max);if(i>0||i===0&&!n.maxInclusive)return!1}return!0}function ay(t,e){const n=Il(t);if(!n||!Xt(e))return!1;if(n.max===null)return!0;const i=fs(n.max,e);return i>0?!0:i===0&&n.maxInclusive}function zn(t){const e=Il(t);return e?e.min:null}const ly="https://pub.dev/api/packages/",cy=8e3;function uy(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null}=e,r=Array.isArray(t?.versions)?t.versions:[];let s=null;for(const o of r){const a=o?.version;if(!a||o.retracted||sy(a))continue;const l=o.pubspec?.environment||{};n&&l.sdk&&!Uu(l.sdk,n)||i&&l.flutter&&!Uu(l.flutter,i)||(!s||fs(a,s)>0)&&(s=a)}return s?{version:s,constraint:`^${s}`}:null}async function dy(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null,fetchImpl:r=fetch}=e;let s;try{const a=await r(`${ly}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(cy)});if(!a.ok)return{name:t,constraint:null,version:null,error:a.status===404?`"${t}" was not found on pub.dev`:`pub.dev returned ${a.status} for "${t}"`};s=await a.json()}catch(a){return{name:t,constraint:null,version:null,error:`could not reach pub.dev for "${t}" (${a.message})`}}const o=uy(s,{dartSdkFloor:n,flutterSdkFloor:i});return o?{name:t,...o,error:null}:{name:t,constraint:null,version:null,error:n?`no published "${t}" release supports Dart ${n}`:`no published "${t}" release could be read`}}async function fy(t,e={}){const n=await Promise.all(t.map(i=>dy(i,e)));return new Map(n.map(({name:i,...r})=>[i,r]))}async function hy(t,e={},n={}){const{resolveVersions:i=fy}=n,r=Object.entries(e).filter(([c])=>c&&c!=="flutter"),s=ph(t),o={dartSdkFloor:zn(s.sdk),flutterSdkFloor:zn(s.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(r.length===0)return a;const l=$s(t),u=[];for(const[c,d]of r){const f=l.get(c);if(!f){u.push(c);continue}const h=zn(d);if(!h){a.kept.push({name:c,constraint:f.constraint});continue}if(!f.isScalar){a.warnings.push(`"${c}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${h}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:c,constraint:f.constraint});continue}if(ay(f.constraint,h)){a.kept.push({name:c,constraint:f.constraint});continue}a.overrides[c]=`^${h}`,a.warnings.push(`"${c}" was pinned to ${f.constraint} in your project, which cannot resolve the ${h} the generated code needs. Raising it to ^${h} — this changes a dependency the rest of your app also uses.`)}if(u.length>0){const c=await i(u,o);for(const d of u){const f=c.get(d);if(f?.constraint){a.additions[d]=f.constraint;continue}const h=e[d]||"";if(zn(h)){a.additions[d]=`^${zn(h)}`,a.warnings.push(`Could not confirm "${d}" version on pub.dev (${f?.error||"lookup failed"}). Using ^${zn(h)} from the AI's recommendation — verify this is current.`);continue}a.additions[d]=">=0.0.0",a.warnings.push(`Could not determine a version for "${d}" (${f?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const py={"&":"&","<":"<",">":">",'"':""","'":"'"};function Qt(t){return String(t??"").replace(/[&<>"']/g,e=>py[e])}function q(t){return t?Qt(t).replace(/\n/g,"
    "):""}function Jt(t){return Qt(t).replace(/\r?\n/g," ")}function Ms(t,e={}){const n=t?.pipelineStep;if(n!=null&&e[n]!=null)return e[n];const i=t?.message||"";return i.includes("Code Generator")?2:i.includes("Code Review")?3:1}function wh(t){if(!t)return{kind:"generic",title:"Generation failed",message:"An unknown error occurred. Please try again.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1};if(t.isModelArmor){const n=t.code==="MODEL_ARMOR_BLOCKED";return{kind:"safety",title:t.userTitle||"Request blocked for safety",message:t.userMessage||t.message,detail:t.retryExplanation||"",canRetry:!n,canEdit:!0,canUpgrade:!1}}if(t.isUsageLimit)return{kind:"quota",title:"Monthly limit reached",message:t.message||"You've used all your generations for this period.",detail:"",canRetry:!1,canEdit:!1,canUpgrade:!0};const e=t.message||"";return/timed out after/i.test(e)?{kind:"timeout",title:"Request timed out",message:"The generation service took too long to respond.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:/unreachable|failed to fetch|load failed|cors/i.test(e)?{kind:"network",title:"Connection problem",message:"We couldn't reach the generation service. Check your connection and try again.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:{kind:"generic",title:"Generation failed",message:e||"An unexpected error occurred.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1}}function gy(t){const e={"Integration Audit Report":"📋","Critical Issues":"❌",Warnings:"⚠️",Recommendations:"✅","Overall Score":"📊"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📄"}function my(t){const e={critical:"❌",warning:"⚠️",recommendation:"✅",score:"📊",issue:"🔍",fix:"🔧"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📝"}function vy(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 li(t){if(!t)return"";if(typeof t!="string")return String(t);const e=/```(?:\w+)?\n?([\s\S]*?)```/,n=t.match(e);return n?n[1].trim():t.trim()}function Hu(t){return t=Qt(t),t=t.replace(/\*\*(.*?)\*\*/g,'$1'),t=t.replace(/\*(.*?)\*/g,'$1'),t=t.replace(/`(.*?)`/g,'$1'),t=t.replace(/\b(FAIL|ERROR|CRITICAL)\b/g,'$1'),t=t.replace(/\b(WARN|WARNING)\b/g,'$1'),t=t.replace(/\b(PASS|SUCCESS|OK)\b/g,'$1'),t}function bh(t,e="dart",n=globalThis.hljs){if(!t)return"";const i=li(t);try{return n.highlight(i,{language:e}).value}catch(r){console.warn("Syntax highlighting failed:",r);try{return n.highlight(i,{language:"json"}).value}catch{return Qt(i)}}}function Ls(t,e={}){const{highlighter:n=globalThis.hljs}=e;let i='
    ';const r=String(t??"").split(` -`);let s=!1,o="";for(const a of r){if(a.startsWith("```")){if(s){const l=vy(o),u=bh(o.trim(),l,n);i+=`
    +`)}let l=null,u,c,d,f,h,p,g,m,v;function E(Y,W){if(!i)return null;const D=i.createShader(Y);return i.shaderSource(D,W),i.compileShader(D),i.getShaderParameter(D,i.COMPILE_STATUS)?D:(window.console&&console.warn("fx-grid shader: "+i.getShaderInfoLog(D)),null)}if(i){const Y=E(i.VERTEX_SHADER,o),W=E(i.FRAGMENT_SHADER,a());if(Y&&W&&(l=i.createProgram(),i.attachShader(l,Y),i.attachShader(l,W),i.linkProgram(l),i.getProgramParameter(l,i.LINK_STATUS)||(window.console&&console.warn("fx-grid link: "+i.getProgramInfoLog(l)),l=null)),l){i.useProgram(l),i.bindBuffer(i.ARRAY_BUFFER,i.createBuffer()),i.bufferData(i.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),i.STATIC_DRAW);const D=i.getAttribLocation(l,"p");i.enableVertexAttribArray(D),i.vertexAttribPointer(D,2,i.FLOAT,!1,0,0),u=i.getUniformLocation(l,"res"),c=i.getUniformLocation(l,"design"),d=i.getUniformLocation(l,"mouse"),f=i.getUniformLocation(l,"energy"),h=i.getUniformLocation(l,"parallax"),p=i.getUniformLocation(l,"t"),g=i.getUniformLocation(l,"ink"),m=i.getUniformLocation(l,"mark"),v=i.getUniformLocation(l,"rot"),i.enable(i.BLEND),i.blendFunc(i.ONE,i.ONE_MINUS_SRC_ALPHA),i.clearColor(0,0,0,0)}else{i=null;const D=t.cloneNode(!1);if(t.parentNode.replaceChild(D,t),t=D,r=t.getContext("2d"),!r)return null}}function S(Y){if(!Y)return null;const W=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(Y);if(W){let D=W[1];return D.length===3&&(D=D[0]+D[0]+D[1]+D[1]+D[2]+D[2]),[parseInt(D.slice(0,2),16)/255,parseInt(D.slice(2,4),16)/255,parseInt(D.slice(4,6),16)/255]}try{const D=document.createElement("canvas");D.width=1,D.height=1;const ue=D.getContext("2d");ue.fillStyle="rgb(9, 8, 7)";const xe=String(ue.fillStyle);ue.fillStyle=Y;const Fe=String(ue.fillStyle);if(Fe===xe)return null;const dt=/^#([0-9a-f]{6})$/i.exec(Fe);if(dt){const ft=dt[1];return[parseInt(ft.slice(0,2),16)/255,parseInt(ft.slice(2,4),16)/255,parseInt(ft.slice(4,6),16)/255]}const Nt=/rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i.exec(Fe);if(Nt)return[Number(Nt[1])/255,Number(Nt[2])/255,Number(Nt[3])/255]}catch{}return null}function _(){let Y="";try{const W=getComputedStyle(document.documentElement);Y=(W.getPropertyValue("--fx-ink")||"").trim()||(W.getPropertyValue("--fg")||"").trim()}catch{}return S(Y)||[.56,.68,.88]}const b=_();let k=1920,T=1080,x=960,F=540,$=960,O=540,L=.66,N=0,K=-1e9,V=!1,M=0,R=0,Z=null,Ce=!1,oe=!1,ye=!1;const $e=64,ae=15.2;let Ie=0,Se=0;const Be=.0032,wt=0,ge=.56,Ye=.26,bt=.32,mn=.16,Re=.349;let Pe=wt;function $t(){const Y=t.getBoundingClientRect(),W=t.clientWidth,D=t.clientHeight;if(!Y.width||!W||!D)return;const ue=Math.min(window.devicePixelRatio||1,2),xe=Math.max(.2,Math.min(2,Y.width/W*ue)),Fe=Math.max(2,Math.round(W*xe)),dt=Math.max(2,Math.round(D*xe));(Fe!==t.width||dt!==t.height)&&(t.width=Fe,t.height=dt,i&&i.viewport(0,0,Fe,dt)),k=W,T=D,V||(x=$=k/2,F=O=T/2,V=!0)}function Bn(Y){!l||!Ce||!i||(i.uniform2f(u,t.width,t.height),i.uniform2f(c,k,T),i.uniform2f(d,x,F),i.uniform1f(f,L),i.uniform1f(h,N),i.uniform2f(v,Math.cos(Pe),Math.sin(Pe)),i.uniform1f(p,Y),i.uniform3f(g,b[0],b[1],b[2]),i.clear(i.COLOR_BUFFER_BIT),i.drawArrays(i.TRIANGLES,0,3))}function qe(Y,W,D){const ue=Math.max(0,Math.min(1,(D-Y)/(W-Y)));return ue*ue*(3-2*ue)}function Dn(Y){if(!Z||!r)return;const W=r;W.setTransform(1,0,0,1,0,0),W.clearRect(0,0,t.width,t.height);const D=t.width/k;W.setTransform(D,0,0,D,0,0),W.globalAlpha=1;const ue=Math.min(k,T),xe=Math.max(64,Math.min(118,ue/10)),Fe=xe*2.9,dt=2*Fe*Fe,Nt=Math.sin(Y*.11)*7,ft=Math.cos(Y*.09)*7-N,dr=x+Nt,fr=F+ft,no=Fe*Math.sqrt(2*Math.log(1/.06)),mi=no+Be*no*no+xe,Cp=Math.floor((dr-mi)/xe)-1,Ap=Math.ceil((dr+mi)/xe)+1,Pp=Math.floor((fr-mi)/xe)-1,Fp=Math.ceil((fr+mi)/xe)+1;for(let io=Pp;io<=Fp;io++){const Rp=(io+.5)*xe;for(let ro=Cp;ro<=Ap;ro++){const so=(ro+.5)*xe-dr,oo=Rp-fr,ao=Math.sqrt(so*so+oo*oo)+1e-5;if(ao>mi)continue;const hr=(-1+Math.sqrt(1+4*Be*ao))/(2*Be),ac=Math.exp(-(hr*hr)/dt),lc=qe(.06,.8,ac)*L*.26;if(lc<.004)continue;const on=xe/(1+2*Be*hr)*.26*(.32+1.1*ac),cc=hr/ao,lo=dr+so*cc,co=fr+oo*cc;lo<-on*1.6||lo>k+on*1.6||co<-on*1.6||co>T+on*1.6||(W.globalAlpha=lc,W.save(),W.translate(lo,co),W.rotate(Pe),W.drawImage(Z,-on,-on,on*2,on*2),W.restore())}}W.globalAlpha=1}function Mt(Y){if(!oe)return;const W=R?Math.min(.05,(Y-R)/1e3):.016;R=Y;const ue=Y-K>2400?.6:1;L+=(ue-L)*Math.min(1,W*3.2);const xe=Math.min(.05,W);Ie+=(($-x)*$e-Ie*ae)*xe,Se+=((O-F)*$e-Se*ae)*xe,x+=Ie*xe,F+=Se*xe,N=(window.scrollY||window.pageYOffset||0)*.55;const Fe=Y/1e3,dt=x/(k||1)-.5,Nt=F/(T||1)-.5;let ft=dt*(dt>=0?ge:Ye)+Nt*(Nt>=0?bt:mn);ft>Re?ft=Re:ft<-Re&&(ft=-Re),Pe=wt+ft-N*6e-4,$t(),i?Bn(Fe):Dn(Fe),M=requestAnimationFrame(Mt)}function Lt(Y){if(!oe)return;const W=t.getBoundingClientRect();!W.width||!k||!T||($=(Y.clientX-W.left)/W.width*k,O=(Y.clientY-W.top)/W.height*T,K=performance.now())}function ut(){oe||to||e.matches||n.matches||!ye||document.hidden||(oe=!0,R=0,M=requestAnimationFrame(Mt))}function sn(){oe=!1,M&&(cancelAnimationFrame(M),M=0),R=0}function gi(){e.matches?(sn(),t.classList.remove("is-ready")):ye&&ut()}function jn(){n.matches?sn():ye&&ut()}function rc(){document.hidden?sn():ye&&ut()}const sc=new IntersectionObserver(Y=>{ye=Y[0]?.isIntersecting||!1,ye?ut():sn()},{threshold:0});sc.observe(t),window.addEventListener("pointermove",Lt,{passive:!0,capture:!0}),window.addEventListener("resize",$t),e.addEventListener("change",gi),n.addEventListener("change",jn),document.addEventListener("visibilitychange",rc);function kp(){const Y=(s.match(/\sd="([^"]+)"/)||[])[1],W=document.createElement("canvas");W.width=256,W.height=256;const D=W.getContext("2d");if(Y&&window.Path2D){const ue=Math.min(8.533333333333333,8.421052631578947);D.setTransform(ue,0,0,ue,ue+(256-30*ue)/2,-6.4*ue),D.fillStyle="rgb(255,255,255)",D.fill(new Path2D(Y),"evenodd"),D.setTransform(1,0,0,1,0,0)}try{const ue=D.getImageData(0,0,256,256),xe=ue.data;for(let Fe=3;Feoe}}const ey=120;function ty(t,e,n){return tn?n:t}function de(t,e,n){return ty((t-e)/(n-e),0,1)}function ny(t){return t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2}function Uo(t){return 1-Math.pow(1-t,3)}function ze(t,e){return e=e===void 0?1.7:e,1+(e+1)*Math.pow(t-1,3)+e*Math.pow(t-1,2)}function ju(t){return 1-Math.pow(2,-9*t)*Math.cos(t*15)}function te(t,e){if(t<=e[0].t)return e[0].v;for(let n=1;n8.2&&_<9.4&&(s*=1-.07*Math.sin(de(_,8.2,9.4)*Math.PI))}else if(t<53){const _=t-42;g=te(_,[{t:0,v:1},{t:2,v:0},{t:4.2,v:0},{t:4.6,v:1},{t:6.8,v:1},{t:7.4,v:0},{t:9.4,v:0},{t:10.6,v:1}]),p=te(_,[{t:0,v:1},{t:2,v:.3},{t:4.6,v:1,e:ze}]),d=te(_,[{t:0,v:0},{t:2,v:.3},{t:4.6,v:.16,e:ze},{t:10.6,v:0}]),h=te(_,[{t:0,v:0},{t:2,v:-40},{t:4.6,v:0,e:ze}]),o=te(_,[{t:0,v:0},{t:4.6,v:-.12},{t:10.6,v:0}])}else if(t<60){const _=t-53;c=te(_,[{t:0,v:1},{t:.35,v:0},{t:.45,v:0},{t:.7,v:1}]);const b=de(_,.45,2.2);a=b>0?-2.6*(1-ju(b)):0,g=te(_,[{t:0,v:1},{t:.57,v:0},{t:.67,v:0},{t:.92,v:1}]);const k=de(_,.67,2.42);f=k>0?-2.6*(1-ju(k)):0,s=1-.05*(Math.sin(de(_,1.9,2.5)*Math.PI)+Math.sin(de(_,2.5,3.1)*Math.PI))}else if(t<74){let b=function(F){return[te(F,[{t:0,v:0},{t:.25,v:1},{t:.5,v:1},{t:.72,v:.14},{t:.82,v:.14},{t:1,v:0}]),te(F,[{t:0,v:0},{t:.08,v:-.62},{t:.25,v:-.62},{t:.33,v:.62},{t:.7,v:.62},{t:.82,v:-.62},{t:1,v:-.62}])]};var S=b;const _=t-60,k=1-de(_,12,14),T=b(de(_,0,12)),x=b(de(_-.5,0,12));n=T[0]*k,i=(T[1]+.05*Math.sin(_*7))*k,o=(x[0]-T[0])*.6*k,a=(x[1]-T[1])*.6*k,h=(x[0]-T[0])*30*k,E=de(_,0,.4)*k}else if(t<85.4){const _=t-74,b=te(_,[{t:0,v:0},{t:4,v:1},{t:8,v:.24},{t:9.6,v:1,e:ze},{t:11.4,v:0}]);o=b*.5,d=-b*.5,l=te(_,[{t:0,v:0},{t:4,v:6},{t:8,v:20},{t:9.6,v:38,e:ze},{t:11.4,v:0}]),h=-l*.7,a=te(_,[{t:0,v:0},{t:8,v:0},{t:9.6,v:.4},{t:11.4,v:0}])}else if(t<96.4){const _=t-85.4,b=de(_,0,5.6),k=de(_,5.6,7.6),T=.72*Math.min(1,_/.6)*(1-k);d=Math.cos(b*Math.PI*2)*T,f=Math.sin(b*Math.PI*2)*T*.55,h=b*360*(1-k);const x=te(_,[{t:0,v:0},{t:7.6,v:0},{t:8.2,v:1,e:Uo},{t:8.6,v:.55},{t:9.4,v:0}]);o=-.16*x,d+=.16*x,l=-6*x,h+=6*x,s=1+.05*x,m=1+.9*x}else if(t<108.6){const _=t-96.4,b=de(_,9.6,12.2);n=te(_,[{t:0,v:0},{t:2.1,v:1},{t:4.8,v:.08},{t:7.5,v:1},{t:9.6,v:0}])*(1-b),i=-.35*Math.abs(Math.sin(de(_,0,9.6)*Math.PI*3))*(1-b);const k=Math.sin(_*6.2)*(1-b);u=1+.12*k,p=1-.12*k,l=k*8,h=-k*8,o=.06*k,d=-.06*k,E=de(_,0,.4)*(1-b)}else{const _=t-108.6,b=Math.sin(de(_,0,8)*Math.PI),k=1-de(_,8,11.4);s=1+.04*b*k,i=-.1*b*k,r=2*b*k,m=1+.5*Math.sin(de(_,0,6)*Math.PI),v=1+.1*Math.sin(de(_,0,6)*Math.PI)}return e.x=n,e.y=i,e.rot=r,e.scale=s,e.ax=o,e.ay=a,e.ar=l,e.asc=u,e.afade=c,e.bx=d,e.by=f,e.br=h,e.bsc=p,e.bfade=g,e.hfade=m,e.hsc=v,e.shd=E,e}function iy(t={}){const e=t.arena||document.querySelector(".pipeline-glyph.logo-loop");if(!e)return null;const n=e.querySelector(".loop-mark"),i=e.querySelector(".loop-piece-a"),r=e.querySelector(".loop-piece-b"),s=e.querySelector(".loop-halo"),o=e.querySelector(".loop-shadow");if(!n||!i||!r||!s||!o)return null;const a=t.reducedMotion||window.matchMedia("(prefers-reduced-motion: reduce)"),l=ey;let u=34,c=0,d=0;function f(){u=n.offsetWidth||34,c=Math.max(0,e.offsetWidth-u-4),d=Math.max(0,(e.offsetHeight-u)/2-2),e.style.setProperty("--mark-c",u/2+"px")}function h(M){const R=Math.min(1,Math.max(0,M.x))*c,Z=M.y*d;n.style.transform="translate3d("+R.toFixed(2)+"px,"+Z.toFixed(2)+"px,0) rotate("+M.rot.toFixed(2)+"deg) scale("+M.scale.toFixed(3)+")",i.style.transform="translate3d("+(M.ax*u).toFixed(2)+"px,"+(M.ay*u).toFixed(2)+"px,0) rotate("+M.ar.toFixed(2)+"deg) scale("+M.asc.toFixed(3)+")",i.style.opacity=M.afade.toFixed(3),r.style.transform="translate3d("+(M.bx*u).toFixed(2)+"px,"+(M.by*u).toFixed(2)+"px,0) rotate("+M.br.toFixed(2)+"deg) scale("+M.bsc.toFixed(3)+")",r.style.opacity=M.bfade.toFixed(3),s.style.transform="scale("+M.hsc.toFixed(3)+")",s.style.opacity=(.09*M.hfade).toFixed(3),o.style.transform="translateX("+R.toFixed(2)+"px) scaleX("+(.75+.4*Math.abs(M.x)).toFixed(3)+")",o.style.opacity=(M.shd*.5).toFixed(3)}let p=0,g=0,m=0,v=!1,E=!1,S=!1,_=0;function b(){return S||a.matches||document.hidden||!e.offsetParent?!1:E}function k(M){if(!v)return;if(m=requestAnimationFrame(k),!b()){x();return}const R=g?(M-g)/1e3:0;g=M,p=(p+Math.min(R,.1))%l,_+=1,h(Ai(p))}function T(){v||S||b()&&(v=!0,g=0,m=requestAnimationFrame(k))}function x(){v=!1,m&&(cancelAnimationFrame(m),m=0),g=0}function F(){b()?T():x()}function $(){a.matches?(x(),h(Ai(0))):F()}function O(){f(),v&&h(Ai(p))}function L(){g=0,F()}const N=new IntersectionObserver(M=>{E=M[0]?M[0].isIntersecting:!1,F()},{threshold:0});N.observe(e),window.addEventListener("resize",O),a.addEventListener("change",$),document.addEventListener("visibilitychange",L);function K(){S||(S=!0,x(),N.disconnect(),window.removeEventListener("resize",O),a.removeEventListener("change",$),document.removeEventListener("visibilitychange",L))}window.addEventListener("pagehide",K);function V(M){p=(M%l+l)%l,h(Ai(p))}return f(),h(Ai(0)),F(),{isRunning:()=>v,currentTime:()=>p,frameCount:()=>_,seek:V,dispose:K}}const ry=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function Xt(t){const e=String(t||"").trim().match(ry);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function sy(t,e){if(t.length===0&&e.length===0)return 0;if(t.length===0)return 1;if(e.length===0)return-1;for(let n=0;n0)}function ay(t){const e=Xt(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function Il(t){let e=String(t??"").trim();if((e.startsWith("'")||e.startsWith('"'))&&(e=e.slice(1,-1).trim()),e===""||e==="any"||e==="*")return{min:null,minInclusive:!1,max:null,maxInclusive:!1};if(e.startsWith("^")){const o=e.slice(1).trim();return Xt(o)?{min:o,minInclusive:!0,max:ay(o),maxInclusive:!1}:null}if(Xt(e))return{min:e,minInclusive:!0,max:e,maxInclusive:!0};const n={min:null,minInclusive:!1,max:null,maxInclusive:!1},i=/(>=|<=|>|<)\s*([0-9][0-9A-Za-z.+-]*)/g;let r=!1,s;for(;(s=i.exec(e))!==null;){const[,o,a]=s;if(!Xt(a))return null;r=!0,o===">="||o===">"?(n.min=a,n.minInclusive=o===">="):(n.max=a,n.maxInclusive=o==="<=")}return r?n:null}function Uu(t,e){const n=Il(t);if(!n||!Xt(e))return!1;if(n.min!==null){const i=fs(e,n.min);if(i<0||i===0&&!n.minInclusive)return!1}if(n.max!==null){const i=fs(e,n.max);if(i>0||i===0&&!n.maxInclusive)return!1}return!0}function ly(t,e){const n=Il(t);if(!n||!Xt(e))return!1;if(n.max===null)return!0;const i=fs(n.max,e);return i>0?!0:i===0&&n.maxInclusive}function zn(t){const e=Il(t);return e?e.min:null}const cy="https://pub.dev/api/packages/",uy=8e3;function dy(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null}=e,r=Array.isArray(t?.versions)?t.versions:[];let s=null;for(const o of r){const a=o?.version;if(!a||o.retracted||oy(a))continue;const l=o.pubspec?.environment||{};n&&l.sdk&&!Uu(l.sdk,n)||i&&l.flutter&&!Uu(l.flutter,i)||(!s||fs(a,s)>0)&&(s=a)}return s?{version:s,constraint:`^${s}`}:null}async function fy(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null,fetchImpl:r=fetch}=e;let s;try{const a=await r(`${cy}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(uy)});if(!a.ok)return{name:t,constraint:null,version:null,error:a.status===404?`"${t}" was not found on pub.dev`:`pub.dev returned ${a.status} for "${t}"`};s=await a.json()}catch(a){return{name:t,constraint:null,version:null,error:`could not reach pub.dev for "${t}" (${a.message})`}}const o=dy(s,{dartSdkFloor:n,flutterSdkFloor:i});return o?{name:t,...o,error:null}:{name:t,constraint:null,version:null,error:n?`no published "${t}" release supports Dart ${n}`:`no published "${t}" release could be read`}}async function hy(t,e={}){const n=await Promise.all(t.map(i=>fy(i,e)));return new Map(n.map(({name:i,...r})=>[i,r]))}async function py(t,e={},n={}){const{resolveVersions:i=hy}=n,r=Object.entries(e).filter(([c])=>c&&c!=="flutter"),s=ph(t),o={dartSdkFloor:zn(s.sdk),flutterSdkFloor:zn(s.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(r.length===0)return a;const l=$s(t),u=[];for(const[c,d]of r){const f=l.get(c);if(!f){u.push(c);continue}const h=zn(d);if(!h){a.kept.push({name:c,constraint:f.constraint});continue}if(!f.isScalar){a.warnings.push(`"${c}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${h}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:c,constraint:f.constraint});continue}if(ly(f.constraint,h)){a.kept.push({name:c,constraint:f.constraint});continue}a.overrides[c]=`^${h}`,a.warnings.push(`"${c}" was pinned to ${f.constraint} in your project, which cannot resolve the ${h} the generated code needs. Raising it to ^${h} — this changes a dependency the rest of your app also uses.`)}if(u.length>0){const c=await i(u,o);for(const d of u){const f=c.get(d);if(f?.constraint){a.additions[d]=f.constraint;continue}const h=e[d]||"";if(zn(h)){a.additions[d]=`^${zn(h)}`,a.warnings.push(`Could not confirm "${d}" version on pub.dev (${f?.error||"lookup failed"}). Using ^${zn(h)} from the AI's recommendation — verify this is current.`);continue}a.additions[d]=">=0.0.0",a.warnings.push(`Could not determine a version for "${d}" (${f?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const gy={"&":"&","<":"<",">":">",'"':""","'":"'"};function Qt(t){return String(t??"").replace(/[&<>"']/g,e=>gy[e])}function q(t){return t?Qt(t).replace(/\n/g,"
    "):""}function Jt(t){return Qt(t).replace(/\r?\n/g," ")}function Ms(t,e={}){const n=t?.pipelineStep;if(n!=null&&e[n]!=null)return e[n];const i=t?.message||"";return i.includes("Code Generator")?2:i.includes("Code Review")?3:1}function bh(t){if(!t)return{kind:"generic",title:"Generation failed",message:"An unknown error occurred. Please try again.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1};if(t.isModelArmor){const n=t.code==="MODEL_ARMOR_BLOCKED";return{kind:"safety",title:t.userTitle||"Request blocked for safety",message:t.userMessage||t.message,detail:t.retryExplanation||"",canRetry:!n,canEdit:!0,canUpgrade:!1}}if(t.isUsageLimit)return{kind:"quota",title:"Monthly limit reached",message:t.message||"You've used all your generations for this period.",detail:"",canRetry:!1,canEdit:!1,canUpgrade:!0};const e=t.message||"";return/timed out after/i.test(e)?{kind:"timeout",title:"Request timed out",message:"The generation service took too long to respond.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:/unreachable|failed to fetch|load failed|cors/i.test(e)?{kind:"network",title:"Connection problem",message:"We couldn't reach the generation service. Check your connection and try again.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:{kind:"generic",title:"Generation failed",message:e||"An unexpected error occurred.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1}}function my(t){const e={"Integration Audit Report":"📋","Critical Issues":"❌",Warnings:"⚠️",Recommendations:"✅","Overall Score":"📊"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📄"}function vy(t){const e={critical:"❌",warning:"⚠️",recommendation:"✅",score:"📊",issue:"🔍",fix:"🔧"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📝"}function _y(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 li(t){if(!t)return"";if(typeof t!="string")return String(t);const e=/```(?:\w+)?\n?([\s\S]*?)```/,n=t.match(e);return n?n[1].trim():t.trim()}function Hu(t){return t=Qt(t),t=t.replace(/\*\*(.*?)\*\*/g,'$1'),t=t.replace(/\*(.*?)\*/g,'$1'),t=t.replace(/`(.*?)`/g,'$1'),t=t.replace(/\b(FAIL|ERROR|CRITICAL)\b/g,'$1'),t=t.replace(/\b(WARN|WARNING)\b/g,'$1'),t=t.replace(/\b(PASS|SUCCESS|OK)\b/g,'$1'),t}function Eh(t,e="dart",n=globalThis.hljs){if(!t)return"";const i=li(t);try{return n.highlight(i,{language:e}).value}catch(r){console.warn("Syntax highlighting failed:",r);try{return n.highlight(i,{language:"json"}).value}catch{return Qt(i)}}}function Ls(t,e={}){const{highlighter:n=globalThis.hljs}=e;let i='
    ';const r=String(t??"").split(` +`);let s=!1,o="";for(const a of r){if(a.startsWith("```")){if(s){const l=_y(o),u=Eh(o.trim(),l,n);i+=`
    ${u}
    `,o="",s=!1}else s=!0;continue}if(s){o+=a+` `;continue}if(a.startsWith("# ")){const l=a.substring(2).trim();i+=`

    - ${gy(l)} + ${my(l)} ${Qt(l)}

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

    - ${my(l)} + ${vy(l)} ${Qt(l)}

    `;continue}if(/^[-*+]\s+/.test(a)||/^\d+\.\s+/.test(a)){const l=a.replace(/^([-*+]|\d+\.)\s+/,"").trim();i+=`
    @@ -78,14 +78,14 @@ in vec2 p; void main(){ gl_Position = vec4(p, 0.0, 1.0); }`;function a(){return[
    ${i}
    - `}const _y=[[/gradient stroke\s*$/i," and an animated percentage label"],[/gauge\s*$/i," with a gradient stroke and animated fill"],[/rating\s*(bar|widget)?\s*$/i," with half-star support and haptic feedback"],[/list\s*$/i," with swipe-to-delete and an undo snackbar"],[/pad\s*$/i," that exports a transparent PNG"],[/carousel\s*$/i," with parallax cards and page indicators"],[/(button|cta)\s*$/i," with a loading spinner and success state"],[/(chart|graph)\s*$/i," that animates from a Firestore stream"],[/action\s*(that|to)?\s*$/i," uploads an image to Firebase Storage and returns the URL"],[/timer\s*$/i," with pause, resume and a completion callback"],[/map\s*$/i," with clustered markers and a custom info window"],[/^a\s+\w*$/i," widget that"],[/(picker|selector)\s*$/i," with search and multi-select"]],yy=220,wy=6;function Wu(t,e){return!!(t&&t.trim())&&!e}function by(t,e=""){if(typeof t!="string"||!t||t===e||t.trim().lengthi.test(t));return n?n[1]:null}function Ey(){let t="",e="";return{get active(){return t},resolve(n){return t=by(n,e)??"",t},dismiss(){t=""},accept(n){if(!t)return null;const i=n+t;return e=i,t="",i}}}function Sy({onSubmit:t}){const e=document.getElementById("composer"),n=document.getElementById("pipeline-input"),i=document.getElementById("hero-send");if(!e||!n||!i||typeof t!="function")return;const r=e.querySelector(".ghost .typed"),s=e.querySelector(".ghost .suggest"),o=document.getElementById("tab-hint"),a=document.getElementById("suggest-status"),l=Array.from(document.querySelectorAll("#example-chips .chip")),u=document.getElementById("btn-add-images"),c=document.getElementById("prompt-image-input"),d=window.matchMedia("(prefers-reduced-motion: reduce)"),f=Ey();let h=!1,p=!1,g=!1,m=!1,v=null,S=null;function b(){i.disabled=!Wu(n.value,p||g||m)}function _(){r&&(r.textContent=n.value)}function x(){s&&(s.textContent=""),_(),e.classList.remove("has-suggest"),o&&(o.hidden=!0,o.tabIndex=-1),a&&(a.textContent="")}function I(R){s&&(s.textContent=R),_(),e.classList.add("has-suggest"),o&&(o.hidden=!1,o.tabIndex=0,o.setAttribute("aria-label","Accept suggestion: "+R.trim())),a&&(a.textContent="Suggestion: "+R+". Press Tab to accept.")}function T(){f.dismiss(),x()}function E(){if(h||p)return;const R=f.resolve(n.value);R&&I(R)}function P(){clearTimeout(v),!h&&(v=setTimeout(E,yy))}function $(){const R=f.accept(n.value);return R===null?!1:(n.value=R,x(),b(),!0)}function O(R){p=R,e.classList.toggle("is-busy",R),i.classList.toggle("is-busy",R),i.setAttribute("aria-label",R?"Generating":"Generate"),n.readOnly=R,l.forEach(Z=>{Z.disabled=R}),u&&(u.disabled=R),c&&(c.disabled=R),b()}async function L(){if(Wu(n.value,p||g||m)){T(),O(!0);try{await t()}finally{O(!1)}}}function N(){g=!1,S&&(clearInterval(S),S=null),e.classList.remove("is-demo-typing"),b()}function K(){l.forEach(R=>{R.classList.remove("is-active"),R.setAttribute("aria-pressed","false")})}function V(){try{n.focus({preventScroll:!0}),n.setSelectionRange(n.value.length,n.value.length)}catch{}}function M(R){const Z=R.dataset.prompt||"";if(N(),clearTimeout(v),v=null,T(),l.forEach(oe=>{const ye=oe===R;oe.classList.toggle("is-active",ye),oe.setAttribute("aria-pressed",String(ye))}),d.matches||!Z){n.value=Z,_(),b(),V();return}n.value="",_(),g=!0,b(),e.classList.add("is-demo-typing");let Ce=0;S=setInterval(()=>{Ce+=1,n.value=Z.slice(0,Ce),_(),Ce>=Z.length?(N(),V()):b()},22)}return l.forEach(R=>{R.setAttribute("aria-pressed","false"),R.addEventListener("click",()=>M(R))}),n.addEventListener("keydown",R=>{if(g&&R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!h){R.preventDefault();return}N(),R.key==="Tab"&&!R.shiftKey&&f.active?(R.preventDefault(),$()):R.key==="Escape"?(clearTimeout(v),v=null,T()):R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!h&&(R.preventDefault(),L())}),n.addEventListener("input",()=>{N(),K(),T(),b(),P()}),n.addEventListener("compositionstart",()=>{h=!0}),n.addEventListener("compositionend",()=>{h=!1,T(),b(),P()}),n.addEventListener("scroll",()=>{r&&r.parentNode&&(r.parentNode.scrollTop=n.scrollTop)}),o&&o.addEventListener("click",()=>{$(),n.focus({preventScroll:!0})}),i.addEventListener("click",L),n.addEventListener("pointerdown",()=>{N(),K()}),_(),b(),{setAttachmentsPending(R){m=!!R,b()}}}const xy="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses";const _t="https://4tgke4.buildship.run",Eh={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},hs="ccc_auth_session",Na="ccc_signin_return",Iy=1800*1e3,qu=new WeakSet;let z={email:null,sessionToken:null,isVerified:!1};function Mn(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let ce=Mn({isResolved:!0}),Oa=Promise.resolve();const ky=`${_t}/service/runpipeline`,Cy="bs_user_id",Ay="bs_identity_token",Py=`${_t}/authUserCheck`;let ft={userId:null,token:null,status:null,resolved:!1};const ps=sv,gs="ccc_subscription",zu=3,Fy=new Set(["active","trialing","paid"]),ms="google/gemini-3.7-flash",Nr=["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"],Ry={"google/gemini-3.7-flash":"Gemini 3.7 Flash","anthropic/claude-opus-5":"Claude Opus 5","openai/gpt-5.6-sol":"GPT-5.6 Sol","z-ai/glm-5.2":"GLM 5.2","moonshotai/kimi-k3":"Kimi K3","openrouter/auto-beta":"OpenRouter: Auto Router","openrouter/free":"OpenRouter: Free Models","openrouter/deepseek/deepseek-v4-pro":"DeepSeek v4 Pro"};function Gt(t){return Ry[t]||t}const Ty=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 Sh(t){return Ty.has(t)}const Ba=4,Ho=8*1024*1024,$y="https://4tgke4.buildship.run/service/runpipeline-image";let Ne=[];const pn=[],My=3e4;let xh=null;function Ly(t){return new Promise(e=>{const n=new FileReader;n.onload=()=>e(n.result),n.onerror=()=>e(null),n.readAsDataURL(t)})}async function Ny(t,e){const n=new FormData;return n.append("file",t),(await fetch($y,{method:"POST",body:n,signal:e})).json()}function Oy(t){if(Array.isArray(t)){const e=t[0];if(e&&typeof e=="object")for(const n of Object.keys(e)){if(n==="item"||n==="index")continue;const i=e[n];if(i&&typeof i=="object"){if(typeof i.file=="string")return i.file;if(typeof i.url=="string")return i.url}if(typeof i=="string")return i}return""}return typeof t=="string"?t:t&&typeof t=="object"&&(t.url||t.fileUrl||t.file_url||t.downloadUrl||t.imageUrl||t.image_url||t.file)||""}async function By(t,e,n){const i=await Ly(t);i&&Ne.includes(e)&&(e.dataUrl=i,cn());let r="";if(i)try{r=Oy(await Ny(t,n))}catch{r=""}return Ne.includes(e)?!i||!r?(Ne.splice(Ne.indexOf(e),1),cn(),"failed"):(e.url=r,cn(),"added"):"dropped"}function Ih(t){const e=pn.indexOf(t);e>=0&&pn.splice(e,1),Ch()}function kh(t){t.controller.abort(),Ih(t);const e=Ne.indexOf(t.slot);e>=0&&(Ne.splice(e,1),cn())}function Ch(){xh?.setAttachmentsPending(pn.length>0)}async function Dy(t){const e=Array.from(t.target.files||[]);if(!e.length)return;if(t.target.value="",y.isRunning){Ee("Wait for the current generation to finish before attaching images.","info");return}const n=e.filter(u=>u.size>Ho);n.length&&Ee(`Skipped ${n.length} image(s) over the ${(Ho/1024/1024).toFixed(0)} MB limit.`,"warning");const i=e.filter(u=>u.size<=Ho);if(!i.length)return;const r=Ba-Ne.length,s=i.slice(0,r);if(i.length>r&&Ee(`You can attach up to ${Ba} images.`,"info"),!s.length)return;const o=s.map(u=>{const c={dataUrl:null,name:u.name,url:null};Ne.push(c);const d={slot:c,controller:new AbortController},f=setTimeout(()=>d.controller.abort(),My);return d.job=By(u,c,d.controller.signal),pn.push(d),d.job.finally(()=>{clearTimeout(f),Ih(d)}),d.job});cn(),Ch();const l=(await Promise.all(o)).filter(u=>u==="failed").length;l&&Ee(`${l} image(s) could not be uploaded and were not attached.`,"error")}function jy(t){const e=Ne[t],n=pn.find(i=>i.slot===e);if(n){kh(n);return}Ne.splice(t,1),cn()}function cn(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",Ne.forEach((n,i)=>{const r=document.createElement("div");r.className="prompt-img-thumb"+(n.url?"":" is-pending"),r.innerHTML=(n.dataUrl?`Prompt image`:"")+``,t.appendChild(r)}),e&&(e.textContent=Ne.length>=Ba?"Image limit reached":"Add images"))}function kl(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),n=Sh(e?.value);t.classList.toggle("hidden",!n),!n&&Ne.length&&(pn.slice().forEach(kh),Ne=[],cn())}const Fn="ccc_usage",Ah="google/gemini-3.7-flash",Ph="google/gemini-3.7-flash",kr="google/gemini-3.7-flash",Ni={professional:11,power:49},Da={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"},Or={AUD:1,USD:.65,EUR:.6,GBP:.52,CAD:.88,NZD:1.08,JPY:97,KRW:870,INR:54,SGD:.87,HKD:5.08,BRL:3.18,CNY:4.7,TWD:20.5,THB:22.5,VND:16200,IDR:10200,MYR:2.88,SEK:6.8,NOK:6.95,DKK:4.48,PLN:2.6,CZK:15.2,HUF:238,RON:2.98,TRY:20.9,AED:2.39,ILS:2.38,PHP:36.4,ZAR:11.8,RUB:58,UAH:26.8,CHF:.57,MXN:11.1,ARS:580,CLP:610,COP:2700,PEN:2.44};let Br={...Or};async function Uy(){const t=new AbortController,e=setTimeout(()=>t.abort(),5e3);try{const n=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:t.signal});if(!n.ok)return;const i=await n.json();if(i.result!=="success"||!i.rates)return;const r=i.rates,s={AUD:1},o=new Set([...Object.keys(Or),...Object.values(ja),...Object.values(Da)]);for(const a of o)a!=="AUD"&&(typeof r[a]=="number"&&r[a]>0?s[a]=r[a]:Or[a]&&(s[a]=Or[a]));Br=s}catch{}finally{clearTimeout(e)}}const ja={"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 Cl(){try{const s=Intl.DateTimeFormat().resolvedOptions().timeZone;if(s&&ja[s])return ja[s]}catch{}const e=(navigator.language||"en-US").replace("-","_"),n=Da[e];if(n)return n;const i=e.split("_")[0],r=Da[i];return r||"USD"}function Oi(t,e){const n=Br[e]??Br.USD,i=t*n,r=Math.round(i*100)/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:r>=100||r%1===0?0:2}).format(r)}catch{return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(t*Br.USD)}}const pt="ccc_api_key_",Pt="ccc_session_api_key_",Rt="ccc_encryption_key",tr="ccc_encryption_key_scope",Hy="ccc_keystore",vs="keys",nr="ccc_encryption_key_version";let Ua=null,_s=null,ir=!1,ys=!1,Vu=!1;class ws extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function Gu(){if(Vu)return;Vu=!0;const t="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(t),document.body&&Ee(t,"warning")}function Fh(){return localStorage.getItem(nr)||""}function Ha(){return crypto.randomUUID?.()||Th(crypto.getRandomValues(new Uint8Array(16)))}function Wy(){const t=Fh();if(t)return t;const e=Ha();return localStorage.setItem(nr,e),e}function ci(){Ua=null,_s=null,ir=!1,ys=!1}window.addEventListener("storage",t=>{t.key===nr&&ci()});function qy(){return new Promise((t,e)=>{const n=indexedDB.open(Hy,1);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(vs)||i.createObjectStore(vs)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function Al(t,e){const n=await qy();return new Promise((i,r)=>{const s=n.transaction(vs,t);let o;try{o=e(s.objectStore(vs))}catch(l){n.close(),r(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>r(o.error),s.oncomplete=()=>{n.close(),i(a)},s.onerror=()=>{n.close(),r(s.error||new Error("Encryption key transaction failed."))},s.onabort=()=>{n.close(),r(s.error||new Error("Encryption key transaction aborted."))}})}function zy(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function Vy(){const t=await Al("readonly",e=>e.get(Rt));return zy(t)?t:null}async function Rh(t){await Al("readwrite",e=>e.put(t,Rt))}async function Gy(){ci();try{await Al("readwrite",t=>t.delete(Rt))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function Ky(){const t=sessionStorage.getItem(Rt);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Rh(e),sessionStorage.removeItem(Rt),sessionStorage.removeItem(tr),localStorage.removeItem(pt+"salt"),e}async function Ku(t){const e=sessionStorage.getItem(Rt);if(e)return ys=sessionStorage.getItem(tr)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new ws;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),i=await crypto.subtle.exportKey("jwk",n);return sessionStorage.setItem(Rt,JSON.stringify(i)),sessionStorage.setItem(tr,"session"),ys=!1,crypto.subtle.importKey("jwk",i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function Yy(t){if(sessionStorage.getItem(tr)==="session"&&sessionStorage.getItem(Rt))return Gu(),ir=!0,Ku(t);try{const e=await Vy();if(e)return e;const n=await Ky();if(n)return n;const i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Rh(i),i}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),Gu(),ir=!0,Ku(t)}}async function Pl(t={}){const{allowSessionFallbackCreation:e=!0}=t,n=Wy();_s!==n&&ci();const i=Ua||Yy(e);Ua=i,_s=n;try{return await i}catch(r){throw ci(),r}}async function Jy(t){const e=await Pl(),n=_s,i=new TextEncoder,r=crypto.getRandomValues(new Uint8Array(12)),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},e,i.encode(t)),o=new Uint8Array(r.length+s.byteLength);return o.set(r),o.set(new Uint8Array(s),r.length),{ciphertext:Th(o),keyVersion:n,sessionFallback:ir}}async function Zy(t,e={}){const{isSessionCredential:n=!1}=e;try{const i=await Pl({allowSessionFallbackCreation:!1});if(ir&&!n&&!ys)throw new ws;const r=Xy(t),s=r.slice(0,12),o=r.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},i,o);return new TextDecoder().decode(a)}catch(i){if(i instanceof ws)throw i;return console.error("Decryption failed:",i),null}}function Th(t){const e=new Uint8Array(t);let n="";for(let i=0;i0}let Ln="",ui="",qi=null,Ju=0,tt="not-configured";async function Fl(){sessionStorage.getItem(Rt)&&await Pl(),Ln=await Te("flutterflow"),ui=await Te("flutterflow_project_id"),o0(),rn(),Ln?Ml():(tt="not-configured",vt())}let rr=!1;function $h(){const t=document.getElementById("api-keys-modal");He(t),$l(),Ln&&Ll(Ln)}function Rl(){rr=!1,$h()}function e0(){rr=!0;const t=document.getElementById("walkthrough-modal");t&&We(t),$h()}let Zu=!1;function Xu(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-settings-model");if(!t||!e)return;e.value=t.value;const n=Array.from(t.options);Array.from(e.options).forEach((r,s)=>{const o=n[s];o&&(r.textContent=o.textContent)});const i=document.getElementById("composer-settings-free-notice");i&&(document.getElementById("model-selector-free-notice")?(i.hidden=!1,i.innerHTML='Free plan — Gemini only. '):i.hidden=!0)}function Qu(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-image-capability"),n=document.getElementById("composer-image-capability-note");if(!t)return;const i=Gt(t.value),r=Sh(t.value);e&&(e.textContent=r?"Supported":"Not supported"),n&&(n.textContent=r?`${i} accepts reference images you attach to the prompt.`:`Images can't be attached with ${i}. Attached images are removed when you switch to it.`),kl()}function t0(){if(rr=!1,Xu(),Qu(),!Zu){const e=document.getElementById("composer-settings-model");e&&e.addEventListener("change",()=>{const n=document.getElementById("code-generator-model");n.value=e.value,n.dispatchEvent(new Event("change")),Xu(),Qu()}),Zu=!0}const t=document.querySelector('.composer [aria-label="Generation settings"]');He("composer-settings-modal",{trigger:t})}function n0(t){t&&t.target!==t.currentTarget||We("composer-settings-modal")}function Mh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&We(e);const n=rr;if(rr=!1,n){const i=document.getElementById("walkthrough-modal");i&&(tt==="connected"&&Tl(),He(i))}}let en=1;function Lh(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function Ns(){const t=Lh();t.length&&t.forEach((e,n)=>{const i=n+1;e.classList.remove("wt-current","wt-done","wt-pending");const r=e.querySelector(".wt-step-num");i===en?(e.classList.add("wt-current"),r&&(r.textContent=i)):i0&&en<=t&&(en++,Ns())}function i0(){const t=document.getElementById("walkthrough-modal");t&&(en=1,Ns(),He(t))}function r0(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&We(e);const n=document.getElementById("walkthrough-dont-show");n&&n.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function Nh(){if(z.isVerified&&Tt()&&ce.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(en=1,Ns(),He(e))}}async function $l(){const t=document.getElementById("flutterflow-api-key-input");Ln?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",s0()}function s0(){ed("flutterflow","flutterflow-key-status"),ed("flutterflow_project_id","flutterflow-project-status")}function ed(t,e){const n=document.getElementById(e);if(!n)return;const i=n.querySelector(".key-status-dot"),r=n.querySelector("span");Ct(t)?(i.className="key-status-dot configured",r.className="text-green-600",r.textContent="User key configured"):(i.className="key-status-dot missing",r.className="text-gray-500",r.textContent="Not configured")}function rn(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff");e&&e.classList.toggle("hidden",!t)}function o0(){const t=document.getElementById("api-keys-status");if(!t)return;const e=t.querySelectorAll(".key-status-dot"),n=["flutterflow"];e.forEach((i,r)=>{const s=n[r];s==="flutterflow"?Ct("flutterflow")&&Ct("flutterflow_project_id")?(i.className="key-status-dot configured",i.title="FlutterFlow (Fully configured)"):Ct("flutterflow")||Ct("flutterflow_project_id")?(i.className="key-status-dot env",i.title="FlutterFlow (Partially configured)"):(i.className="key-status-dot missing",i.title="FlutterFlow (Not configured)"):Ct(s)?(i.className="key-status-dot configured",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (User key)"):(i.className="key-status-dot missing",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (Not configured)")}),rn()}async function a0(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select"),n=t.value.trim();n&&await Yu("flutterflow",n);const i=e?.value.trim()||"";if(i){if(!Os(i)){Ee("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await Yu("flutterflow_project_id",i)}await Fl(),n&&await Ml(),$l();const r=document.querySelector("#api-keys-modal .bg-blue-500"),s=r.textContent;r.textContent="Saved!",r.classList.remove("bg-blue-500","hover:bg-blue-600"),r.classList.add("bg-green-500"),setTimeout(()=>{r.textContent=s,r.classList.remove("bg-green-500"),r.classList.add("bg-blue-500","hover:bg-blue-600"),Mh()},1e3)}async function l0(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(nr,Ha()),ci(),localStorage.removeItem(pt+"flutterflow"),localStorage.removeItem(pt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow"),sessionStorage.removeItem(Pt+"flutterflow_project_id"),sessionStorage.removeItem(Rt),sessionStorage.removeItem(tr),localStorage.removeItem(pt+"salt"),await Gy(),localStorage.setItem(nr,Ha()),localStorage.removeItem(pt+"flutterflow"),localStorage.removeItem(pt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow"),sessionStorage.removeItem(Pt+"flutterflow_project_id"),await Fl();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),$l()}function Os(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function vt(){const t=document.getElementById("acct-ff-dot"),e=document.getElementById("acct-ff-status"),n=document.getElementById("acct-ff-endpoint"),i=document.getElementById("acct-ff-project");if(n){const o=yt();n.textContent=o.includes("staging")?"Staging":"Production"}if(i&&(i.textContent=ui||"—"),!e)return;let r,s;if(!Ct("flutterflow"))r="Not connected — add your FlutterFlow API key",s="";else switch(tt){case"connected":r="Connected to FlutterFlow",s="ok";break;case"no-projects":r="Key accepted — no projects found",s="warn";break;case"unauthorized":r="API key rejected (401/403) — re-enter your key",s="bad";break;case"network-error":r="Could not reach FlutterFlow — check your network",s="bad";break;default:r="Checking connection…",s="warn";break}e.textContent=r,t&&(t.className=`acct-dot${s?" "+s:""}`)}async function Ml(){const t=await Te("flutterflow");if(!t||!Ct("flutterflow"))return tt="not-configured",vt(),null;tt="validating",vt();try{const n=await new hi(t,"","main",yt()).listProjects();return tt=n&&n.length>0?"connected":"no-projects",vt(),n}catch(e){const n=String(e&&e.message||"");return tt=/(401|403)|denied|unauthorized|scoped|list permission/i.test(n)?"unauthorized":"network-error",vt(),null}}function c0(){ui="",localStorage.removeItem(pt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow_project_id")}function u0(){c0();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML='',t.value=""),Ct("flutterflow")?(tt="validating",Ll(Ln)):tt="not-configured",vt()}function d0(t,e){const n=document.getElementById(t);n&&(n.value?e?n.style.borderColor="#22c55e":n.style.borderColor="#ef4444":n.style.borderColor="")}function f0(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const n=e.target.value.trim().length>0;d0("flutterflow-api-key-input",n)}),t.addEventListener("blur",h0(async e=>{const n=e.target.value.trim();n&&await Ll(n)},500)))}function h0(t,e){let n;return function(...r){const s=()=>{clearTimeout(n),t(...r)};clearTimeout(n),n=setTimeout(s,e)}}async function Ll(t){const e=document.getElementById("flutterflow-projects-select"),n=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',n&&n.classList.add("hidden"),(Ct("flutterflow")||t)&&(tt="validating"),vt();try{const r=await new hi(t,"","main",yt()).listProjects();if(!r||r.length===0){tt="no-projects",vt(),e.innerHTML='';return}tt="connected",vt(),e.innerHTML='',r.forEach(s=>{const o=document.createElement("option");o.value=s.id||s.projectId||"",o.textContent=s.name||s.projectName||`Project ${s.id}`,e.appendChild(o)}),ui&&(e.value=ui)}catch(i){console.error("Failed to fetch projects:",i);const r=String(i&&i.message||"");tt=/(401|403)|denied|unauthorized|scoped|list permission/i.test(r)?"unauthorized":"network-error",vt(),e.innerHTML='',n&&(n.textContent=`Failed to load projects: ${i.message}`,n.classList.remove("hidden"))}}function p0(t){const e=document.getElementById(t),i=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",i.innerHTML=` + `}const yy=[[/gradient stroke\s*$/i," and an animated percentage label"],[/gauge\s*$/i," with a gradient stroke and animated fill"],[/rating\s*(bar|widget)?\s*$/i," with half-star support and haptic feedback"],[/list\s*$/i," with swipe-to-delete and an undo snackbar"],[/pad\s*$/i," that exports a transparent PNG"],[/carousel\s*$/i," with parallax cards and page indicators"],[/(button|cta)\s*$/i," with a loading spinner and success state"],[/(chart|graph)\s*$/i," that animates from a Firestore stream"],[/action\s*(that|to)?\s*$/i," uploads an image to Firebase Storage and returns the URL"],[/timer\s*$/i," with pause, resume and a completion callback"],[/map\s*$/i," with clustered markers and a custom info window"],[/^a\s+\w*$/i," widget that"],[/(picker|selector)\s*$/i," with search and multi-select"]],wy=220,by=6;function Wu(t,e){return!!(t&&t.trim())&&!e}function Ey(t,e=""){if(typeof t!="string"||!t||t===e||t.trim().lengthi.test(t));return n?n[1]:null}function Sy(){let t="",e="";return{get active(){return t},resolve(n){return t=Ey(n,e)??"",t},dismiss(){t=""},accept(n){if(!t)return null;const i=n+t;return e=i,t="",i}}}function xy({onSubmit:t}){const e=document.getElementById("composer"),n=document.getElementById("pipeline-input"),i=document.getElementById("hero-send");if(!e||!n||!i||typeof t!="function")return;const r=e.querySelector(".ghost .typed"),s=e.querySelector(".ghost .suggest"),o=document.getElementById("tab-hint"),a=document.getElementById("suggest-status"),l=Array.from(document.querySelectorAll("#example-chips .chip")),u=document.getElementById("btn-add-images"),c=document.getElementById("prompt-image-input"),d=window.matchMedia("(prefers-reduced-motion: reduce)"),f=Sy();let h=!1,p=!1,g=!1,m=!1,v=null,E=null;function S(){i.disabled=!Wu(n.value,p||g||m)}function _(){r&&(r.textContent=n.value)}function b(){s&&(s.textContent=""),_(),e.classList.remove("has-suggest"),o&&(o.hidden=!0,o.tabIndex=-1),a&&(a.textContent="")}function k(R){s&&(s.textContent=R),_(),e.classList.add("has-suggest"),o&&(o.hidden=!1,o.tabIndex=0,o.setAttribute("aria-label","Accept suggestion: "+R.trim())),a&&(a.textContent="Suggestion: "+R+". Press Tab to accept.")}function T(){f.dismiss(),b()}function x(){if(h||p)return;const R=f.resolve(n.value);R&&k(R)}function F(){clearTimeout(v),!h&&(v=setTimeout(x,wy))}function $(){const R=f.accept(n.value);return R===null?!1:(n.value=R,b(),S(),!0)}function O(R){p=R,e.classList.toggle("is-busy",R),i.classList.toggle("is-busy",R),i.setAttribute("aria-label",R?"Generating":"Generate"),n.readOnly=R,l.forEach(Z=>{Z.disabled=R}),u&&(u.disabled=R),c&&(c.disabled=R),S()}async function L(){if(Wu(n.value,p||g||m)){T(),O(!0);try{await t()}finally{O(!1)}}}function N(){g=!1,E&&(clearInterval(E),E=null),e.classList.remove("is-demo-typing"),S()}function K(){l.forEach(R=>{R.classList.remove("is-active"),R.setAttribute("aria-pressed","false")})}function V(){try{n.focus({preventScroll:!0}),n.setSelectionRange(n.value.length,n.value.length)}catch{}}function M(R){const Z=R.dataset.prompt||"";if(N(),clearTimeout(v),v=null,T(),l.forEach(oe=>{const ye=oe===R;oe.classList.toggle("is-active",ye),oe.setAttribute("aria-pressed",String(ye))}),d.matches||!Z){n.value=Z,_(),S(),V();return}n.value="",_(),g=!0,S(),e.classList.add("is-demo-typing");let Ce=0;E=setInterval(()=>{Ce+=1,n.value=Z.slice(0,Ce),_(),Ce>=Z.length?(N(),V()):S()},22)}return l.forEach(R=>{R.setAttribute("aria-pressed","false"),R.addEventListener("click",()=>M(R))}),n.addEventListener("keydown",R=>{if(g&&R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!h){R.preventDefault();return}N(),R.key==="Tab"&&!R.shiftKey&&f.active?(R.preventDefault(),$()):R.key==="Escape"?(clearTimeout(v),v=null,T()):R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!h&&(R.preventDefault(),L())}),n.addEventListener("input",()=>{N(),K(),T(),S(),F()}),n.addEventListener("compositionstart",()=>{h=!0}),n.addEventListener("compositionend",()=>{h=!1,T(),S(),F()}),n.addEventListener("scroll",()=>{r&&r.parentNode&&(r.parentNode.scrollTop=n.scrollTop)}),o&&o.addEventListener("click",()=>{$(),n.focus({preventScroll:!0})}),i.addEventListener("click",L),n.addEventListener("pointerdown",()=>{N(),K()}),_(),S(),{setAttachmentsPending(R){m=!!R,S()}}}const Iy="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses";const _t="https://4tgke4.buildship.run",Sh={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},hs="ccc_auth_session",Na="ccc_signin_return",ky=1800*1e3,qu=new WeakSet;let z={email:null,sessionToken:null,isVerified:!1};function Mn(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let ce=Mn({isResolved:!0}),Oa=Promise.resolve();const Cy=`${_t}/service/runpipeline`,Ay="bs_user_id",Py="bs_identity_token",Fy=`${_t}/authUserCheck`;let ht={userId:null,token:null,status:null,resolved:!1};const ps=av,gs="ccc_subscription",zu=3,Ry=new Set(["active","trialing","paid"]),ms="google/gemini-3.7-flash",Nr=["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"],Ty={"google/gemini-3.7-flash":"Gemini 3.7 Flash","anthropic/claude-opus-5":"Claude Opus 5","openai/gpt-5.6-sol":"GPT-5.6 Sol","z-ai/glm-5.2":"GLM 5.2","moonshotai/kimi-k3":"Kimi K3","openrouter/auto-beta":"OpenRouter: Auto Router","openrouter/free":"OpenRouter: Free Models","openrouter/deepseek/deepseek-v4-pro":"DeepSeek v4 Pro"};function Gt(t){return Ty[t]||t}const $y=new Set(["google/gemini-3.7-flash","anthropic/claude-opus-5","openai/gpt-5.6-sol","z-ai/glm-5.2","moonshotai/kimi-k3","openrouter/auto-beta"]);function xh(t){return $y.has(t)}const Ba=4,Ho=8*1024*1024,My="https://4tgke4.buildship.run/service/runpipeline-image";let Ne=[];const pn=[],Ly=3e4;let Ih=null;function Ny(t){return new Promise(e=>{const n=new FileReader;n.onload=()=>e(n.result),n.onerror=()=>e(null),n.readAsDataURL(t)})}async function Oy(t,e){const n=new FormData;return n.append("file",t),(await fetch(My,{method:"POST",body:n,signal:e})).json()}function By(t){if(Array.isArray(t)){const e=t[0];if(e&&typeof e=="object")for(const n of Object.keys(e)){if(n==="item"||n==="index")continue;const i=e[n];if(i&&typeof i=="object"){if(typeof i.file=="string")return i.file;if(typeof i.url=="string")return i.url}if(typeof i=="string")return i}return""}return typeof t=="string"?t:t&&typeof t=="object"&&(t.url||t.fileUrl||t.file_url||t.downloadUrl||t.imageUrl||t.image_url||t.file)||""}async function Dy(t,e,n){const i=await Ny(t);i&&Ne.includes(e)&&(e.dataUrl=i,cn());let r="";if(i)try{r=By(await Oy(t,n))}catch{r=""}return Ne.includes(e)?!i||!r?(Ne.splice(Ne.indexOf(e),1),cn(),"failed"):(e.url=r,cn(),"added"):"dropped"}function kh(t){const e=pn.indexOf(t);e>=0&&pn.splice(e,1),Ah()}function Ch(t){t.controller.abort(),kh(t);const e=Ne.indexOf(t.slot);e>=0&&(Ne.splice(e,1),cn())}function Ah(){Ih?.setAttachmentsPending(pn.length>0)}async function jy(t){const e=Array.from(t.target.files||[]);if(!e.length)return;if(t.target.value="",y.isRunning){Ee("Wait for the current generation to finish before attaching images.","info");return}const n=e.filter(u=>u.size>Ho);n.length&&Ee(`Skipped ${n.length} image(s) over the ${(Ho/1024/1024).toFixed(0)} MB limit.`,"warning");const i=e.filter(u=>u.size<=Ho);if(!i.length)return;const r=Ba-Ne.length,s=i.slice(0,r);if(i.length>r&&Ee(`You can attach up to ${Ba} images.`,"info"),!s.length)return;const o=s.map(u=>{const c={dataUrl:null,name:u.name,url:null};Ne.push(c);const d={slot:c,controller:new AbortController},f=setTimeout(()=>d.controller.abort(),Ly);return d.job=Dy(u,c,d.controller.signal),pn.push(d),d.job.finally(()=>{clearTimeout(f),kh(d)}),d.job});cn(),Ah();const l=(await Promise.all(o)).filter(u=>u==="failed").length;l&&Ee(`${l} image(s) could not be uploaded and were not attached.`,"error")}function Uy(t){const e=Ne[t],n=pn.find(i=>i.slot===e);if(n){Ch(n);return}Ne.splice(t,1),cn()}function cn(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",Ne.forEach((n,i)=>{const r=document.createElement("div");r.className="prompt-img-thumb"+(n.url?"":" is-pending"),r.innerHTML=(n.dataUrl?`Prompt image`:"")+``,t.appendChild(r)}),e&&(e.textContent=Ne.length>=Ba?"Image limit reached":"Add images"))}function kl(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),n=xh(e?.value);t.classList.toggle("hidden",!n),!n&&Ne.length&&(pn.slice().forEach(Ch),Ne=[],cn())}const Fn="ccc_usage",Ph="google/gemini-3.7-flash",Fh="google/gemini-3.7-flash",kr="google/gemini-3.7-flash",Ni={professional:11,power:49},Da={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"},Or={AUD:1,USD:.65,EUR:.6,GBP:.52,CAD:.88,NZD:1.08,JPY:97,KRW:870,INR:54,SGD:.87,HKD:5.08,BRL:3.18,CNY:4.7,TWD:20.5,THB:22.5,VND:16200,IDR:10200,MYR:2.88,SEK:6.8,NOK:6.95,DKK:4.48,PLN:2.6,CZK:15.2,HUF:238,RON:2.98,TRY:20.9,AED:2.39,ILS:2.38,PHP:36.4,ZAR:11.8,RUB:58,UAH:26.8,CHF:.57,MXN:11.1,ARS:580,CLP:610,COP:2700,PEN:2.44};let Br={...Or};async function Hy(){const t=new AbortController,e=setTimeout(()=>t.abort(),5e3);try{const n=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:t.signal});if(!n.ok)return;const i=await n.json();if(i.result!=="success"||!i.rates)return;const r=i.rates,s={AUD:1},o=new Set([...Object.keys(Or),...Object.values(ja),...Object.values(Da)]);for(const a of o)a!=="AUD"&&(typeof r[a]=="number"&&r[a]>0?s[a]=r[a]:Or[a]&&(s[a]=Or[a]));Br=s}catch{}finally{clearTimeout(e)}}const ja={"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 Cl(){try{const s=Intl.DateTimeFormat().resolvedOptions().timeZone;if(s&&ja[s])return ja[s]}catch{}const e=(navigator.language||"en-US").replace("-","_"),n=Da[e];if(n)return n;const i=e.split("_")[0],r=Da[i];return r||"USD"}function Oi(t,e){const n=Br[e]??Br.USD,i=t*n,r=Math.round(i*100)/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:r>=100||r%1===0?0:2}).format(r)}catch{return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(t*Br.USD)}}const gt="ccc_api_key_",Pt="ccc_session_api_key_",Rt="ccc_encryption_key",tr="ccc_encryption_key_scope",Wy="ccc_keystore",vs="keys",nr="ccc_encryption_key_version";let Ua=null,_s=null,ir=!1,ys=!1,Vu=!1;class ws extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function Gu(){if(Vu)return;Vu=!0;const t="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(t),document.body&&Ee(t,"warning")}function Rh(){return localStorage.getItem(nr)||""}function Ha(){return crypto.randomUUID?.()||$h(crypto.getRandomValues(new Uint8Array(16)))}function qy(){const t=Rh();if(t)return t;const e=Ha();return localStorage.setItem(nr,e),e}function ci(){Ua=null,_s=null,ir=!1,ys=!1}window.addEventListener("storage",t=>{t.key===nr&&ci()});function zy(){return new Promise((t,e)=>{const n=indexedDB.open(Wy,1);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(vs)||i.createObjectStore(vs)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function Al(t,e){const n=await zy();return new Promise((i,r)=>{const s=n.transaction(vs,t);let o;try{o=e(s.objectStore(vs))}catch(l){n.close(),r(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>r(o.error),s.oncomplete=()=>{n.close(),i(a)},s.onerror=()=>{n.close(),r(s.error||new Error("Encryption key transaction failed."))},s.onabort=()=>{n.close(),r(s.error||new Error("Encryption key transaction aborted."))}})}function Vy(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function Gy(){const t=await Al("readonly",e=>e.get(Rt));return Vy(t)?t:null}async function Th(t){await Al("readwrite",e=>e.put(t,Rt))}async function Ky(){ci();try{await Al("readwrite",t=>t.delete(Rt))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function Yy(){const t=sessionStorage.getItem(Rt);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Th(e),sessionStorage.removeItem(Rt),sessionStorage.removeItem(tr),localStorage.removeItem(gt+"salt"),e}async function Ku(t){const e=sessionStorage.getItem(Rt);if(e)return ys=sessionStorage.getItem(tr)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new ws;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),i=await crypto.subtle.exportKey("jwk",n);return sessionStorage.setItem(Rt,JSON.stringify(i)),sessionStorage.setItem(tr,"session"),ys=!1,crypto.subtle.importKey("jwk",i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function Jy(t){if(sessionStorage.getItem(tr)==="session"&&sessionStorage.getItem(Rt))return Gu(),ir=!0,Ku(t);try{const e=await Gy();if(e)return e;const n=await Yy();if(n)return n;const i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Th(i),i}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),Gu(),ir=!0,Ku(t)}}async function Pl(t={}){const{allowSessionFallbackCreation:e=!0}=t,n=qy();_s!==n&&ci();const i=Ua||Jy(e);Ua=i,_s=n;try{return await i}catch(r){throw ci(),r}}async function Zy(t){const e=await Pl(),n=_s,i=new TextEncoder,r=crypto.getRandomValues(new Uint8Array(12)),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},e,i.encode(t)),o=new Uint8Array(r.length+s.byteLength);return o.set(r),o.set(new Uint8Array(s),r.length),{ciphertext:$h(o),keyVersion:n,sessionFallback:ir}}async function Xy(t,e={}){const{isSessionCredential:n=!1}=e;try{const i=await Pl({allowSessionFallbackCreation:!1});if(ir&&!n&&!ys)throw new ws;const r=Qy(t),s=r.slice(0,12),o=r.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},i,o);return new TextDecoder().decode(a)}catch(i){if(i instanceof ws)throw i;return console.error("Decryption failed:",i),null}}function $h(t){const e=new Uint8Array(t);let n="";for(let i=0;i0}let Ln="",ui="",qi=null,Ju=0,tt="not-configured";async function Fl(){sessionStorage.getItem(Rt)&&await Pl(),Ln=await Te("flutterflow"),ui=await Te("flutterflow_project_id"),a0(),rn(),Ln?Ml():(tt="not-configured",vt())}let rr=!1;function Mh(){const t=document.getElementById("api-keys-modal");He(t),$l(),Ln&&Ll(Ln)}function Rl(){rr=!1,Mh()}function t0(){rr=!0;const t=document.getElementById("walkthrough-modal");t&&We(t),Mh()}let Zu=!1;function Xu(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-settings-model");if(!t||!e)return;e.value=t.value;const n=Array.from(t.options);Array.from(e.options).forEach((r,s)=>{const o=n[s];o&&(r.textContent=o.textContent)});const i=document.getElementById("composer-settings-free-notice");i&&(document.getElementById("model-selector-free-notice")?(i.hidden=!1,i.innerHTML='Free plan — Gemini only. '):i.hidden=!0)}function Qu(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-image-capability"),n=document.getElementById("composer-image-capability-note");if(!t)return;const i=Gt(t.value),r=xh(t.value);e&&(e.textContent=r?"Supported":"Not supported"),n&&(n.textContent=r?`${i} accepts reference images you attach to the prompt.`:`Images can't be attached with ${i}. Attached images are removed when you switch to it.`),kl()}function n0(){if(rr=!1,Xu(),Qu(),!Zu){const e=document.getElementById("composer-settings-model");e&&e.addEventListener("change",()=>{const n=document.getElementById("code-generator-model");n.value=e.value,n.dispatchEvent(new Event("change")),Xu(),Qu()}),Zu=!0}const t=document.querySelector('.composer [aria-label="Generation settings"]');He("composer-settings-modal",{trigger:t})}function i0(t){t&&t.target!==t.currentTarget||We("composer-settings-modal")}function Lh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&We(e);const n=rr;if(rr=!1,n){const i=document.getElementById("walkthrough-modal");i&&(tt==="connected"&&Tl(),He(i))}}let en=1;function Nh(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function Ns(){const t=Nh();t.length&&t.forEach((e,n)=>{const i=n+1;e.classList.remove("wt-current","wt-done","wt-pending");const r=e.querySelector(".wt-step-num");i===en?(e.classList.add("wt-current"),r&&(r.textContent=i)):i0&&en<=t&&(en++,Ns())}function r0(){const t=document.getElementById("walkthrough-modal");t&&(en=1,Ns(),He(t))}function s0(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&We(e);const n=document.getElementById("walkthrough-dont-show");n&&n.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function Oh(){if(z.isVerified&&Tt()&&ce.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(en=1,Ns(),He(e))}}async function $l(){const t=document.getElementById("flutterflow-api-key-input");Ln?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",o0()}function o0(){ed("flutterflow","flutterflow-key-status"),ed("flutterflow_project_id","flutterflow-project-status")}function ed(t,e){const n=document.getElementById(e);if(!n)return;const i=n.querySelector(".key-status-dot"),r=n.querySelector("span");Ct(t)?(i.className="key-status-dot configured",r.className="text-green-600",r.textContent="User key configured"):(i.className="key-status-dot missing",r.className="text-gray-500",r.textContent="Not configured")}function rn(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff");e&&e.classList.toggle("hidden",!t)}function a0(){const t=document.getElementById("api-keys-status");if(!t)return;const e=t.querySelectorAll(".key-status-dot"),n=["flutterflow"];e.forEach((i,r)=>{const s=n[r];s==="flutterflow"?Ct("flutterflow")&&Ct("flutterflow_project_id")?(i.className="key-status-dot configured",i.title="FlutterFlow (Fully configured)"):Ct("flutterflow")||Ct("flutterflow_project_id")?(i.className="key-status-dot env",i.title="FlutterFlow (Partially configured)"):(i.className="key-status-dot missing",i.title="FlutterFlow (Not configured)"):Ct(s)?(i.className="key-status-dot configured",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (User key)"):(i.className="key-status-dot missing",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (Not configured)")}),rn()}async function l0(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select"),n=t.value.trim();n&&await Yu("flutterflow",n);const i=e?.value.trim()||"";if(i){if(!Os(i)){Ee("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await Yu("flutterflow_project_id",i)}await Fl(),n&&await Ml(),$l();const r=document.querySelector("#api-keys-modal .bg-blue-500"),s=r.textContent;r.textContent="Saved!",r.classList.remove("bg-blue-500","hover:bg-blue-600"),r.classList.add("bg-green-500"),setTimeout(()=>{r.textContent=s,r.classList.remove("bg-green-500"),r.classList.add("bg-blue-500","hover:bg-blue-600"),Lh()},1e3)}async function c0(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(nr,Ha()),ci(),localStorage.removeItem(gt+"flutterflow"),localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow"),sessionStorage.removeItem(Pt+"flutterflow_project_id"),sessionStorage.removeItem(Rt),sessionStorage.removeItem(tr),localStorage.removeItem(gt+"salt"),await Ky(),localStorage.setItem(nr,Ha()),localStorage.removeItem(gt+"flutterflow"),localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow"),sessionStorage.removeItem(Pt+"flutterflow_project_id"),await Fl();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),$l()}function Os(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function vt(){const t=document.getElementById("acct-ff-dot"),e=document.getElementById("acct-ff-status"),n=document.getElementById("acct-ff-endpoint"),i=document.getElementById("acct-ff-project");if(n){const o=yt();n.textContent=o.includes("staging")?"Staging":"Production"}if(i&&(i.textContent=ui||"—"),!e)return;let r,s;if(!Ct("flutterflow"))r="Not connected — add your FlutterFlow API key",s="";else switch(tt){case"connected":r="Connected to FlutterFlow",s="ok";break;case"no-projects":r="Key accepted — no projects found",s="warn";break;case"unauthorized":r="API key rejected (401/403) — re-enter your key",s="bad";break;case"network-error":r="Could not reach FlutterFlow — check your network",s="bad";break;default:r="Checking connection…",s="warn";break}e.textContent=r,t&&(t.className=`acct-dot${s?" "+s:""}`)}async function Ml(){const t=await Te("flutterflow");if(!t||!Ct("flutterflow"))return tt="not-configured",vt(),null;tt="validating",vt();try{const n=await new hi(t,"","main",yt()).listProjects();return tt=n&&n.length>0?"connected":"no-projects",vt(),n}catch(e){const n=String(e&&e.message||"");return tt=/(401|403)|denied|unauthorized|scoped|list permission/i.test(n)?"unauthorized":"network-error",vt(),null}}function u0(){ui="",localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow_project_id")}function d0(){u0();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML='',t.value=""),Ct("flutterflow")?(tt="validating",Ll(Ln)):tt="not-configured",vt()}function f0(t,e){const n=document.getElementById(t);n&&(n.value?e?n.style.borderColor="#22c55e":n.style.borderColor="#ef4444":n.style.borderColor="")}function h0(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const n=e.target.value.trim().length>0;f0("flutterflow-api-key-input",n)}),t.addEventListener("blur",p0(async e=>{const n=e.target.value.trim();n&&await Ll(n)},500)))}function p0(t,e){let n;return function(...r){const s=()=>{clearTimeout(n),t(...r)};clearTimeout(n),n=setTimeout(s,e)}}async function Ll(t){const e=document.getElementById("flutterflow-projects-select"),n=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',n&&n.classList.add("hidden"),(Ct("flutterflow")||t)&&(tt="validating"),vt();try{const r=await new hi(t,"","main",yt()).listProjects();if(!r||r.length===0){tt="no-projects",vt(),e.innerHTML='';return}tt="connected",vt(),e.innerHTML='',r.forEach(s=>{const o=document.createElement("option");o.value=s.id||s.projectId||"",o.textContent=s.name||s.projectName||`Project ${s.id}`,e.appendChild(o)}),ui&&(e.value=ui)}catch(i){console.error("Failed to fetch projects:",i);const r=String(i&&i.message||"");tt=/(401|403)|denied|unauthorized|scoped|list permission/i.test(r)?"unauthorized":"network-error",vt(),e.innerHTML='',n&&(n.textContent=`Failed to load projects: ${i.message}`,n.classList.remove("hidden"))}}function g0(t){const e=document.getElementById(t),i=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",i.innerHTML=` `):(e.type="password",i.innerHTML=` - `)}let y={step1Result:null,step2Result:null,step3Result:null,bundleSpec:null,artifactBundle:null,bundleReview:null,selectedArtifactId:null,resultsViewMode:"summary",currentStep:0,isRunning:!1,runId:0,submittedPrompt:"",submittedImages:[]};function g0(){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 m0(){y.bundleSpec=Qi(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function Bs(){const t=oi(y.bundleSpec);y.artifactBundle=Qi(y.step2Result,{id:y.bundleSpec?.id,title:y.bundleSpec?.title,description:y.bundleSpec?.description,artifactType:t.artifactType,artifactName:t.artifactName,fileName:t.fileName,dependencies:t.dependencies,relationships:y.bundleSpec?.relationships,code:y.step2Result||""});const e=jv(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(n=>n.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=oi(y.artifactBundle).id}function Ds(){const t=Qi(y.step3Result,{id:y.artifactBundle?.id,title:y.artifactBundle?.title}),e=new Map(t.artifacts.map(i=>[i.id,i.review])),n=new Map(t.artifacts.filter(i=>{const r=i.review;return r&&typeof r.fixedSource=="string"&&r.fixedSource.trim()}).map(i=>[i.id,i.review.fixedSource.trim()]));y.bundleReview=Qi({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(i=>{const r=n.get(i.id)||null;return{...i,review:e.get(i.id)||i.review||y.step3Result||null,...r?{fixedCode:r}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function Oh(){const t=Nl();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function Nl(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(n=>n.id===y.selectedArtifactId)||oi(t)}function Ol(){return Nl().code||y.step2Result||""}async function v0(){try{await Fl()}catch(t){return console.error("checkConnection: initializeApiKeys failed:",t),!1}return!0}const Dr={production:"https://api.flutterflow.io/v2/",staging:"https://api.flutterflow.io/v2-staging/"};function _0(t,e){const n=e?.trim()?` (${e.trim().slice(0,200)})`:"";return t===401?`Your FlutterFlow API key was rejected (401 Unauthorized)${n}. Re-enter a current key under API Keys settings, then try again.`:`Listing FlutterFlow projects was denied (403)${n}. The key may be scoped to sync a single project without list permission - verify the key's access in FlutterFlow, re-enter it under API Keys settings, then retry.`}class hi{constructor(e,n,i="main",r=Dr.production){this.apiKey=e,this.baseUrl=r,this._projectId=n,this._branchName=i,this._endpoint=r}get projectId(){return this._projectId}get branchName(){return this._branchName==="main"?"":this._branchName}async exportProjectZip(){console.log(`Exporting code from FlutterFlow project: ${this.projectId}, branch: ${this.branchName||"main"}`);const e=[{project:{path:`projects/${this.projectId}`},...this.branchName?{branch_name:this.branchName}:{},export_as_module:!1,include_assets_map:!1,format:!1,export_as_debug:!1},{project_id:this.projectId,branch_name:this.branchName,include_assets:!1,export_as_module:!1}];let n=null;for(const i of e)try{const r=await fetch(`${this.baseUrl}exportCode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(i)});if(!r.ok){const a=await r.text();n=new Error(`Export failed: ${r.status} - ${a}`);continue}const s=await r.json(),o=s?.value?.project_zip||s?.project_zip;if(!o){n=new Error("Export response did not include project source.");continue}return o}catch(r){n=r}throw n||new Error("Export failed for an unknown reason.")}async fetchProjectSource(){const e=await this.exportProjectZip(),n=await JSZip.loadAsync(e,{base64:!0}),i=Object.keys(n.files).filter(a=>!n.files[a].dir&&(a==="pubspec.yaml"||a.endsWith("/pubspec.yaml"))).sort((a,l)=>a.split("/").length-l.split("/").length)[0];if(!i)throw new Error("Export did not contain a pubspec.yaml.");const r=i.slice(0,i.length-12),s=new Map,o=Object.keys(n.files).filter(a=>{if(n.files[a].dir||!a.startsWith(r))return!1;const l=a.slice(r.length);return l==="lib/flutter_flow/custom_functions.dart"||l.startsWith("lib/custom_code/")&&l.endsWith(".dart")});return await Promise.all(o.map(async a=>{s.set(a.slice(r.length),await n.files[a].async("string"))})),{pubspecYaml:await n.files[i].async("string"),files:s}}async pushCodeWithRetry(e,n=3){const i=[Dr.production,Dr.staging],r=Math.max(0,i.indexOf(this._endpoint));let s=!1,o=null;for(let a=0;asetTimeout(h,1e3*(a+1)));continue}if(c.ok)return console.log(`Push to ${u} succeeded!`),c;o=c.status;let d;try{d=await c.clone().text()}catch{d="(unreadable response body)"}if(console.log(`Push to ${u} returned ${c.status}: ${d}`),c.status>=500&&(s=!0),c.status===500){console.warn(`Endpoint ${u} returned 500, trying next...`),await new Promise(f=>setTimeout(f,1e3*(a+1)));continue}if(c.status>=500)throw new mt(`FlutterFlow reported a server error (HTTP ${c.status}), which cannot prove the push was refused — the write may have been applied before the failure. Open your FlutterFlow project to reconcile before retrying.`);if(s)throw new mt(`The push was refused (HTTP ${c.status}), but an earlier sync attempt may already have applied it — server errors and dropped responses cannot prove a refusal. Open your FlutterFlow project to reconcile before retrying.`);return c}throw Y_({httpStatus:o})}async pushCode(e){return this.pushCodeWithRetry(e)}parseProjectsResponse(e){if(e?.success&&typeof e.value=="string")try{const i=JSON.parse(e.value);if(i&&Array.isArray(i.entries))return i.entries.map(r=>({id:r.id,name:r.project?.name||r.id}))}catch(i){console.error("Failed to parse stringified project value:",i)}const n=e?.projects||e?.items||e?.entries||(Array.isArray(e)?e:[]);return Array.isArray(n)?n:[]}async listProjects(){console.log("Listing projects for API key");const e=[`${this.baseUrl}listProjects`,"https://api.flutterflow.io/v2/l/listProjects"];let n=0,i="";for(const r of e){const s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({project_type:"ALL",deserialize_response:!0})});if(s.ok)return r!==e[0]&&console.log(`listProjects answered on legacy path ${r}`),this.parseProjectsResponse(await s.json());if(n=s.status,i=await s.text(),console.warn(`listProjects via ${r} returned ${n}: ${i}`),s.status===401||s.status===403)throw new Error(_0(s.status,i));if(s.status!==404)throw new Error(`List projects failed: ${s.status} - ${i}`)}throw new Error(`List projects failed: ${n} - ${i}`)}}async function Bl(t){const e=t.clone();let n;try{n=await t.json()}catch{let s="";try{s=await e.text()}catch{}if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:s||`HTTP ${t.status}`,errorMap:new Map};throw new mt(`FlutterFlow accepted the sync but returned an unreadable response${s?`: ${s.slice(0,200)}`:"."}`)}if(!t.ok){let r=n.message||`HTTP ${t.status}`,s=new Map;if(n.errors)s=new Map(Object.entries(n.errors));else if(!n.message&&typeof n=="object"){const o=Object.keys(n).filter(a=>a.endsWith(".dart")&&Array.isArray(n[a]));o.length>0&&(s=new Map(Object.entries(n)),r=o.flatMap(l=>n[l].map(u=>`${l}: ${u.errorMessage}`)).join(` -`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:r,errorMap:s}}let i={};if(n.value)try{i=typeof n.value=="string"?JSON.parse(n.value):n.value}catch(r){console.warn("Ignoring malformed push response value:",r)}return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(i))}}function Dl(t,e){return{401:"Authentication failed. Please check your FlutterFlow API key.",403:"Access denied. You may not have permission to modify this project.",404:"Project not found. Please check your Project ID.",409:"Conflict detected. The project may have been modified elsewhere.",422:"Validation failed: Invalid request format",429:"Rate limit exceeded. Please try again in a few minutes.",500:"FlutterFlow server error. Please try again later.",503:"FlutterFlow service temporarily unavailable."}[t]||`FlutterFlow API error: ${`HTTP ${t}`}`}const J={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},Bh=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,Dh=/extends\s+State<\w+>/;function y0(t,e=""){if(t==="pubspec.yaml")return J.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return J.OTHER;if(t==="custom_functions.dart")return J.FUNCTION;if(e){const n=Bh.test(e),i=Dh.test(e);if(n||i)return J.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return J.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return J.FUNCTION}return J.CODE_FILE}function jh(t,e){switch(e){case J.ACTION:return`lib/custom_code/actions/${t}`;case J.WIDGET:return`lib/custom_code/widgets/${t}`;case J.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case J.CODE_FILE:return`lib/custom_code/${t}`;case J.DEPENDENCIES:return"pubspec.yaml";case J.OTHER:return`lib/custom_code/${t}`;default:return t}}async function jl(t,e=new Map){return Ev(t,e)}const Wa=new Map;function Uh(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function sr(t){Wa.delete(Uh(t))}function w0(t,e,n){return new Promise((i,r)=>{let s=!1;const o=(l,u,c)=>{s||(s=!0,c==="resolve"?i(u):r(u))},a=setTimeout(()=>{s||(s=!0,n(i,r))},e);t.then(l=>{clearTimeout(a),o(i,l,"resolve")},l=>{clearTimeout(a),o(r,l,"reject")})})}async function Ul(t,e,n,i,r="",s=K_){const o=e_(e,n);if(o.length===0)return{remoteFiles:n,syncFileMap:e,unverified:[],approximate:[]};const a=V_(o,r),l={...a.manifest,sources:a.sources},u=a.skipped.map(h=>h.reason);u.forEach(h=>console.warn(`[custom class deploy] ${h}`));const c=a.approximate;c.forEach(h=>console.warn(`[custom class deploy] ${h}`)),console.log(`Provisioning ${o.length} new FlutterFlow custom code file(s) before sync.`),Oe.set("provision");let d=!0,f;try{if(f=await w0((async()=>{let h;try{h=await fetch(xy,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:i,customClasses:o,verification:l,stream:!0})})}catch{throw new mt("The provisioning request did not return a response. The deploy may have reached the FlutterFlow server — open your FlutterFlow project to reconcile before retrying.")}return J_(h,{onPhase:p=>{d&&Oe.setSubstatus(p)},onLog:p=>{d&&console.log(`[custom class deploy] ${p}`)}})})(),s,(h,p)=>{d=!1,p(new mt("The deploy is still working on the FlutterFlow server, but this browser tab has stopped waiting. Your custom classes may or may not have been written — the outcome is not yet known. Open your FlutterFlow project to reconcile before retrying the deploy."))}),!f.finalResultReceived)throw Z_(f)===Xe.FAILED?new Error(f.error||`FlutterFlow custom class provisioning failed (HTTP ${f.httpStatus}).`):new mt("The connection to the FlutterFlow deploy runner dropped before it reported a result. The deploy may still be finishing on the server; open your FlutterFlow project to reconcile before retrying.")}catch(h){throw h instanceof mt&&sr(t),h}if(!f.success){const h=f.details?` ${f.details}`:"";throw new Error(`${f.error||"FlutterFlow custom class provisioning failed."}${h}`)}return sr(t),f.verificationSkipped&&(console.warn(`[custom class deploy] ${f.verificationSkipped}`),u.push(f.verificationSkipped)),{remoteFiles:n,syncFileMap:t_(e,o),unverified:u,approximate:c,provisionSucceeded:!0}}async function Hl(t,e={}){const n=Uh(t);let i=Wa.get(n);if(i===void 0){try{i=await t.fetchProjectSource()}catch(l){throw new Error(`Could not read your project's pubspec.yaml (${l.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=mh(i.pubspecYaml);if(!a.valid)throw new Error(`Your project's pubspec.yaml could not be read reliably (${a.errors.join("; ")}). Deploy was stopped so your existing package dependencies aren't overwritten.`);Wa.set(n,i)}const r=await hy(i.pubspecYaml,e),s=U_(i.pubspecYaml,r.overrides),o=j_(s.yaml,r.additions);return r.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>`${a}: ${r.additions[a]||"any"}`).join(", "),r.sdk.dartSdkFloor?`(resolved for Dart ${r.sdk.dartSdkFloor})`:""),r.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:s.overridden,warnings:r.warnings,remoteFiles:i.files}}function b0(t){const e=[],n=[];t.content.length>5e4&&n.push("Code file is large (>50KB). This may take longer to commit."),t.content.length>1e5&&e.push("Code file is too large (>100KB). Consider splitting into smaller components.");const i=t.content.split(` -`).length;i>500&&n.push(`Code has ${i} lines. Consider breaking it into smaller widgets.`),t.content.includes("setState")&&t.codeType===J.ACTION&&n.push("Using setState in a Custom Action may not work as expected. Consider using a Custom Widget."),t.content.includes("dynamic")&&!t.content.includes("?")&&n.push('Code uses "dynamic" types. Consider adding explicit types for better null safety.'),t.content.match(/Color\(0xFF[0-9A-Fa-f]{6}\)/)&&n.push("Code contains hardcoded colors. Consider using FlutterFlowTheme.of(context) for theme consistency.");const r=t.content.match(/print\s*\(/g);r&&r.length>3&&n.push(`Code contains ${r.length} print statements. Consider removing debug prints before committing.`);const s=y_(t.content);if(s&&e.push(`FlutterFlow cannot format this code - ${s}. Fix or regenerate before committing.`),t.codeType===J.WIDGET){const o=ah(t.content),a=m_(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=`${lh(o[0])}`;e.push(`Widget class name "${o[0]}" does not match the file name "${t.fileName}". FlutterFlow derives the widget from the file name, so it will report "No widget ${a} found". Rename the file to "${l}" or the class to match before committing.`)}}return{canProceed:e.length===0,issues:e,warnings:n}}function Hh(t,e={}){const{artifactType:n="CustomWidget",artifactName:i="GeneratedCode",fileName:r}=e,s=p_(t);let o=r||i;if(n==="CustomFunction")o="custom_functions.dart";else if(n==="CustomWidget"){const u=ah(s)[0],c=u?lh(u):null;c&&o!==c?(console.warn(`Commit file name "${o}" does not match declared widget class "${u}"; renaming to "${c}" so FlutterFlow can find the widget.`),o=c):o.endsWith(".dart")||(o+=".dart")}else o.endsWith(".dart")||(o+=".dart");let a=J.CODE_FILE;switch(n){case"CustomAction":a=J.ACTION;break;case"CustomWidget":a=J.WIDGET;break;case"CustomFunction":a=J.FUNCTION;break;case"CustomClass":case"CodeFile":a=J.CODE_FILE;break}let l="";return a===J.WIDGET?l=`// Automatic FlutterFlow imports + `)}let y={step1Result:null,step2Result:null,step3Result:null,bundleSpec:null,artifactBundle:null,bundleReview:null,selectedArtifactId:null,resultsViewMode:"summary",currentStep:0,isRunning:!1,runId:0,submittedPrompt:"",submittedImages:[]};function m0(){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 v0(){y.bundleSpec=Qi(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function Bs(){const t=oi(y.bundleSpec);y.artifactBundle=Qi(y.step2Result,{id:y.bundleSpec?.id,title:y.bundleSpec?.title,description:y.bundleSpec?.description,artifactType:t.artifactType,artifactName:t.artifactName,fileName:t.fileName,dependencies:t.dependencies,relationships:y.bundleSpec?.relationships,code:y.step2Result||""});const e=Hv(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(n=>n.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=oi(y.artifactBundle).id}function Ds(){const t=Qi(y.step3Result,{id:y.artifactBundle?.id,title:y.artifactBundle?.title}),e=new Map(t.artifacts.map(i=>[i.id,i.review])),n=new Map(t.artifacts.filter(i=>{const r=i.review;return r&&typeof r.fixedSource=="string"&&r.fixedSource.trim()}).map(i=>[i.id,i.review.fixedSource.trim()]));y.bundleReview=Qi({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(i=>{const r=n.get(i.id)||null;return{...i,review:e.get(i.id)||i.review||y.step3Result||null,...r?{fixedCode:r}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function Bh(){const t=Nl();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function Nl(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(n=>n.id===y.selectedArtifactId)||oi(t)}function Ol(){return Nl().code||y.step2Result||""}async function _0(){try{await Fl()}catch(t){return console.error("checkConnection: initializeApiKeys failed:",t),!1}return!0}const Dr={production:"https://api.flutterflow.io/v2/",staging:"https://api.flutterflow.io/v2-staging/"};function y0(t,e){const n=e?.trim()?` (${e.trim().slice(0,200)})`:"";return t===401?`Your FlutterFlow API key was rejected (401 Unauthorized)${n}. Re-enter a current key under API Keys settings, then try again.`:`Listing FlutterFlow projects was denied (403)${n}. The key may be scoped to sync a single project without list permission - verify the key's access in FlutterFlow, re-enter it under API Keys settings, then retry.`}class hi{constructor(e,n,i="main",r=Dr.production){this.apiKey=e,this.baseUrl=r,this._projectId=n,this._branchName=i,this._endpoint=r}get projectId(){return this._projectId}get branchName(){return this._branchName==="main"?"":this._branchName}async exportProjectZip(){console.log(`Exporting code from FlutterFlow project: ${this.projectId}, branch: ${this.branchName||"main"}`);const e=[{project:{path:`projects/${this.projectId}`},...this.branchName?{branch_name:this.branchName}:{},export_as_module:!1,include_assets_map:!1,format:!1,export_as_debug:!1},{project_id:this.projectId,branch_name:this.branchName,include_assets:!1,export_as_module:!1}];let n=null;for(const i of e)try{const r=await fetch(`${this.baseUrl}exportCode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(i)});if(!r.ok){const a=await r.text();n=new Error(`Export failed: ${r.status} - ${a}`);continue}const s=await r.json(),o=s?.value?.project_zip||s?.project_zip;if(!o){n=new Error("Export response did not include project source.");continue}return o}catch(r){n=r}throw n||new Error("Export failed for an unknown reason.")}async fetchProjectSource(){const e=await this.exportProjectZip(),n=await JSZip.loadAsync(e,{base64:!0}),i=Object.keys(n.files).filter(a=>!n.files[a].dir&&(a==="pubspec.yaml"||a.endsWith("/pubspec.yaml"))).sort((a,l)=>a.split("/").length-l.split("/").length)[0];if(!i)throw new Error("Export did not contain a pubspec.yaml.");const r=i.slice(0,i.length-12),s=new Map,o=Object.keys(n.files).filter(a=>{if(n.files[a].dir||!a.startsWith(r))return!1;const l=a.slice(r.length);return l==="lib/flutter_flow/custom_functions.dart"||l.startsWith("lib/custom_code/")&&l.endsWith(".dart")});return await Promise.all(o.map(async a=>{s.set(a.slice(r.length),await n.files[a].async("string"))})),{pubspecYaml:await n.files[i].async("string"),files:s}}async pushCodeWithRetry(e,n=3){const i=[Dr.production,Dr.staging],r=Math.max(0,i.indexOf(this._endpoint));let s=!1,o=null;for(let a=0;asetTimeout(h,1e3*(a+1)));continue}if(c.ok)return console.log(`Push to ${u} succeeded!`),c;o=c.status;let d;try{d=await c.clone().text()}catch{d="(unreadable response body)"}if(console.log(`Push to ${u} returned ${c.status}: ${d}`),c.status>=500&&(s=!0),c.status===500){console.warn(`Endpoint ${u} returned 500, trying next...`),await new Promise(f=>setTimeout(f,1e3*(a+1)));continue}if(c.status>=500)throw new lt(`FlutterFlow reported a server error (HTTP ${c.status}), which cannot prove the push was refused — the write may have been applied before the failure. Open your FlutterFlow project to reconcile before retrying.`);if(s)throw new lt(`The push was refused (HTTP ${c.status}), but an earlier sync attempt may already have applied it — server errors and dropped responses cannot prove a refusal. Open your FlutterFlow project to reconcile before retrying.`);return c}throw J_({httpStatus:o})}async pushCode(e){return this.pushCodeWithRetry(e)}parseProjectsResponse(e){if(e?.success&&typeof e.value=="string")try{const i=JSON.parse(e.value);if(i&&Array.isArray(i.entries))return i.entries.map(r=>({id:r.id,name:r.project?.name||r.id}))}catch(i){console.error("Failed to parse stringified project value:",i)}const n=e?.projects||e?.items||e?.entries||(Array.isArray(e)?e:[]);return Array.isArray(n)?n:[]}async listProjects(){console.log("Listing projects for API key");const e=[`${this.baseUrl}listProjects`,"https://api.flutterflow.io/v2/l/listProjects"];let n=0,i="";for(const r of e){const s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({project_type:"ALL",deserialize_response:!0})});if(s.ok)return r!==e[0]&&console.log(`listProjects answered on legacy path ${r}`),this.parseProjectsResponse(await s.json());if(n=s.status,i=await s.text(),console.warn(`listProjects via ${r} returned ${n}: ${i}`),s.status===401||s.status===403)throw new Error(y0(s.status,i));if(s.status!==404)throw new Error(`List projects failed: ${s.status} - ${i}`)}throw new Error(`List projects failed: ${n} - ${i}`)}}async function w0(t){const e=t.clone();let n;try{n=await t.json()}catch{let s="";try{s=await e.text()}catch{}if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:s||`HTTP ${t.status}`,errorMap:new Map};throw new lt(`FlutterFlow accepted the sync but returned an unreadable response${s?`: ${s.slice(0,200)}`:"."}`)}if(!t.ok){let r=n.message||`HTTP ${t.status}`,s=new Map;if(n.errors)s=new Map(Object.entries(n.errors));else if(!n.message&&typeof n=="object"){const o=Object.keys(n).filter(a=>a.endsWith(".dart")&&Array.isArray(n[a]));o.length>0&&(s=new Map(Object.entries(n)),r=o.flatMap(l=>n[l].map(u=>`${l}: ${u.errorMessage}`)).join(` +`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:r,errorMap:s}}let i={};if(n.value)try{i=typeof n.value=="string"?JSON.parse(n.value):n.value}catch(r){console.warn("Ignoring malformed push response value:",r)}return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(i))}}function Bl(t,e){return{401:"Authentication failed. Please check your FlutterFlow API key.",403:"Access denied. You may not have permission to modify this project.",404:"Project not found. Please check your Project ID.",409:"Conflict detected. The project may have been modified elsewhere.",422:"Validation failed: Invalid request format",429:"Rate limit exceeded. Please try again in a few minutes.",500:"FlutterFlow server error. Please try again later.",503:"FlutterFlow service temporarily unavailable."}[t]||`FlutterFlow API error: ${`HTTP ${t}`}`}const J={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},Dh=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,jh=/extends\s+State<\w+>/;function b0(t,e=""){if(t==="pubspec.yaml")return J.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return J.OTHER;if(t==="custom_functions.dart")return J.FUNCTION;if(e){const n=Dh.test(e),i=jh.test(e);if(n||i)return J.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return J.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return J.FUNCTION}return J.CODE_FILE}function Uh(t,e){switch(e){case J.ACTION:return`lib/custom_code/actions/${t}`;case J.WIDGET:return`lib/custom_code/widgets/${t}`;case J.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case J.CODE_FILE:return`lib/custom_code/${t}`;case J.DEPENDENCIES:return"pubspec.yaml";case J.OTHER:return`lib/custom_code/${t}`;default:return t}}async function Dl(t,e=new Map){return xv(t,e)}const Wa=new Map;function Hh(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function sr(t){Wa.delete(Hh(t))}function Wh(t,e,n){return new Promise((i,r)=>{let s=!1;const o=(l,u,c)=>{s||(s=!0,c==="resolve"?i(u):r(u))},a=setTimeout(()=>{s||(s=!0,n(i,r))},e);t.then(l=>{clearTimeout(a),o(i,l,"resolve")},l=>{clearTimeout(a),o(r,l,"reject")})})}async function jl(t,e,n=_h){return Wh((async()=>{const i=await t.pushCode(e);return w0(i)})(),n,(i,r)=>r(new lt("FlutterFlow did not answer the sync in time — the push may still have been applied. The outcome is not yet known: open your FlutterFlow project to reconcile before retrying the deploy.")))}async function Ul(t,e,n,i,r="",s=_h){const o=n_(e,n);if(o.length===0)return{remoteFiles:n,syncFileMap:e,unverified:[],approximate:[]};const a=K_(o,r),l={...a.manifest,sources:a.sources},u=a.skipped.map(h=>h.reason);u.forEach(h=>console.warn(`[custom class deploy] ${h}`));const c=a.approximate;c.forEach(h=>console.warn(`[custom class deploy] ${h}`)),console.log(`Provisioning ${o.length} new FlutterFlow custom code file(s) before sync.`),Oe.set("provision");let d=!0,f;try{if(f=await Wh((async()=>{let h;try{h=await fetch(Iy,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:i,customClasses:o,verification:l,stream:!0})})}catch{throw new lt("The provisioning request did not return a response. The deploy may have reached the FlutterFlow server — open your FlutterFlow project to reconcile before retrying.")}return Z_(h,{onPhase:p=>{d&&Oe.setSubstatus(p)},onLog:p=>{d&&console.log(`[custom class deploy] ${p}`)}})})(),s,(h,p)=>{d=!1,p(new lt("The deploy is still working on the FlutterFlow server, but this browser tab has stopped waiting. Your custom classes may or may not have been written — the outcome is not yet known. Open your FlutterFlow project to reconcile before retrying the deploy."))}),!f.finalResultReceived)throw X_(f)===Xe.FAILED?new Error(f.error||`FlutterFlow custom class provisioning failed (HTTP ${f.httpStatus}).`):new lt("The connection to the FlutterFlow deploy runner dropped before it reported a result. The deploy may still be finishing on the server; open your FlutterFlow project to reconcile before retrying.")}catch(h){throw h instanceof lt&&sr(t),h}if(!f.success){const h=f.details?` ${f.details}`:"";throw new Error(`${f.error||"FlutterFlow custom class provisioning failed."}${h}`)}return sr(t),f.verificationSkipped&&(console.warn(`[custom class deploy] ${f.verificationSkipped}`),u.push(f.verificationSkipped)),{remoteFiles:n,syncFileMap:i_(e,o),unverified:u,approximate:c,provisionSucceeded:!0}}async function Hl(t,e={}){const n=Hh(t);let i=Wa.get(n);if(i===void 0){try{i=await t.fetchProjectSource()}catch(l){throw new Error(`Could not read your project's pubspec.yaml (${l.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=mh(i.pubspecYaml);if(!a.valid)throw new Error(`Your project's pubspec.yaml could not be read reliably (${a.errors.join("; ")}). Deploy was stopped so your existing package dependencies aren't overwritten.`);Wa.set(n,i)}const r=await py(i.pubspecYaml,e),s=W_(i.pubspecYaml,r.overrides),o=H_(s.yaml,r.additions);return r.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>`${a}: ${r.additions[a]||"any"}`).join(", "),r.sdk.dartSdkFloor?`(resolved for Dart ${r.sdk.dartSdkFloor})`:""),r.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:s.overridden,warnings:r.warnings,remoteFiles:i.files}}function E0(t){const e=[],n=[];t.content.length>5e4&&n.push("Code file is large (>50KB). This may take longer to commit."),t.content.length>1e5&&e.push("Code file is too large (>100KB). Consider splitting into smaller components.");const i=t.content.split(` +`).length;i>500&&n.push(`Code has ${i} lines. Consider breaking it into smaller widgets.`),t.content.includes("setState")&&t.codeType===J.ACTION&&n.push("Using setState in a Custom Action may not work as expected. Consider using a Custom Widget."),t.content.includes("dynamic")&&!t.content.includes("?")&&n.push('Code uses "dynamic" types. Consider adding explicit types for better null safety.'),t.content.match(/Color\(0xFF[0-9A-Fa-f]{6}\)/)&&n.push("Code contains hardcoded colors. Consider using FlutterFlowTheme.of(context) for theme consistency.");const r=t.content.match(/print\s*\(/g);r&&r.length>3&&n.push(`Code contains ${r.length} print statements. Consider removing debug prints before committing.`);const s=b_(t.content);if(s&&e.push(`FlutterFlow cannot format this code - ${s}. Fix or regenerate before committing.`),t.codeType===J.WIDGET){const o=ah(t.content),a=__(t.fileName);if(o.length===0)e.push("No public widget class found (must extend StatelessWidget or StatefulWidget).");else if(!o.includes(a)){const l=`${lh(o[0])}`;e.push(`Widget class name "${o[0]}" does not match the file name "${t.fileName}". FlutterFlow derives the widget from the file name, so it will report "No widget ${a} found". Rename the file to "${l}" or the class to match before committing.`)}}return{canProceed:e.length===0,issues:e,warnings:n}}function qh(t,e={}){const{artifactType:n="CustomWidget",artifactName:i="GeneratedCode",fileName:r}=e,s=m_(t);let o=r||i;if(n==="CustomFunction")o="custom_functions.dart";else if(n==="CustomWidget"){const u=ah(s)[0],c=u?lh(u):null;c&&o!==c?(console.warn(`Commit file name "${o}" does not match declared widget class "${u}"; renaming to "${c}" so FlutterFlow can find the widget.`),o=c):o.endsWith(".dart")||(o+=".dart")}else o.endsWith(".dart")||(o+=".dart");let a=J.CODE_FILE;switch(n){case"CustomAction":a=J.ACTION;break;case"CustomWidget":a=J.WIDGET;break;case"CustomFunction":a=J.FUNCTION;break;case"CustomClass":case"CodeFile":a=J.CODE_FILE;break}let l="";return a===J.WIDGET?l=`// Automatic FlutterFlow imports import '/flutter_flow/flutter_flow_theme.dart'; import '/flutter_flow/flutter_flow_util.dart'; import 'package:flutter/material.dart'; @@ -111,15 +111,15 @@ import '/flutter_flow/lat_lng.dart'; import '/flutter_flow/place.dart'; import '/flutter_flow/uploaded_file.dart'; -`),{content:Wv(s,l),fileName:o,codeType:a,artifactType:n,artifactName:i}}function E0(t){const e={};for(const n of wl(t))e[n]="";return e}function S0(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 x0(t,e,n,i=new Set,r=""){const s=[],o=Bh.test(e),a=Dh.test(e);return n===J.WIDGET&&!o&&!a&&s.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:s.length===0,errors:s}}function js(t){const e=[],n=[];if(!t||t.size===0)return e.push("No files to commit"),{valid:!1,errors:e,warnings:n};const i=new Set(Array.from(t.values()).flatMap(r=>As(r.content||"")));for(const[r,s]of t.entries()){if((!s.content||s.content.trim().length===0)&&e.push(`File ${r} is empty`),s.content&&s.content.length>1e5&&n.push(`File ${r} is very large (>100KB)`),r.endsWith(".dart")){const o=x0(r,s.content,s.type,i,s.artifactName);o.valid||e.push(...o.errors.map(a=>`${r}: ${a}`))}if(r==="pubspec.yaml"){const o=mh(s.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:n}}const ee={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},G={currentState:ee.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=ee.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(ee).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===ee.PREPARING&&(this.startTime=Date.now()),(t===ee.SUCCESS||t===ee.ERROR)&&(this.endTime=Date.now()),typeof window<"u"&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("commitStateChange",{detail:{state:t,commitState:this}})),console.log(`Commit state changed to: ${t}`)},setError(t){this.error=t,this.setState(ee.ERROR)},setSuccess(t){this.result=t,this.setState(ee.SUCCESS)},setProgress(t,e){this.filesProcessed=t,this.totalFiles=e},getElapsedTime(){return this.startTime?(this.endTime||Date.now())-this.startTime:null},isInProgress(){return this.currentState===ee.PREPARING||this.currentState===ee.VALIDATING||this.currentState===ee.PUSHING}};async function I0(t,e,n={}){let{codeType:i="W"}=n;const{pubspecDeps:r={},artifactName:s=e}=n;i==="CustomWidget"&&(i=J.WIDGET),i==="CustomAction"&&(i=J.ACTION),i==="CustomFunction"&&(i=J.FUNCTION),i==="CustomClass"&&(i=J.CODE_FILE),i==="CodeFile"&&(i=J.CODE_FILE),G.reset(),G.setState(ee.PREPARING);try{const o=await Te("flutterflow"),a=await Te("flutterflow_project_id");if(!o||!a)throw new Error("FlutterFlow credentials not configured. Please set your API key and Project ID in the API Keys settings.");if(!Os(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=yt(),u=new hi(o,a,"main",l);G.setState(ee.VALIDATING);const c=new Map,d=i||y0(e,t),f=jh(e,d);c.set(e,{artifactName:s,content:t,type:d,path:f}),G.setProgress(0,c.size);const h=js(c);if(!h.valid)throw new Error(`Validation failed: +`),{content:zv(s,l),fileName:o,codeType:a,artifactType:n,artifactName:i}}function S0(t){const e={};for(const n of wl(t))e[n]="";return e}function x0(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 I0(t,e,n,i=new Set,r=""){const s=[],o=Dh.test(e),a=jh.test(e);return n===J.WIDGET&&!o&&!a&&s.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:s.length===0,errors:s}}function js(t){const e=[],n=[];if(!t||t.size===0)return e.push("No files to commit"),{valid:!1,errors:e,warnings:n};const i=new Set(Array.from(t.values()).flatMap(r=>As(r.content||"")));for(const[r,s]of t.entries()){if((!s.content||s.content.trim().length===0)&&e.push(`File ${r} is empty`),s.content&&s.content.length>1e5&&n.push(`File ${r} is very large (>100KB)`),r.endsWith(".dart")){const o=I0(r,s.content,s.type,i,s.artifactName);o.valid||e.push(...o.errors.map(a=>`${r}: ${a}`))}if(r==="pubspec.yaml"){const o=mh(s.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:n}}const ee={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},G={currentState:ee.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=ee.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(ee).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===ee.PREPARING&&(this.startTime=Date.now()),(t===ee.SUCCESS||t===ee.ERROR)&&(this.endTime=Date.now()),typeof window<"u"&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("commitStateChange",{detail:{state:t,commitState:this}})),console.log(`Commit state changed to: ${t}`)},setError(t){this.error=t,this.setState(ee.ERROR)},setSuccess(t){this.result=t,this.setState(ee.SUCCESS)},setProgress(t,e){this.filesProcessed=t,this.totalFiles=e},getElapsedTime(){return this.startTime?(this.endTime||Date.now())-this.startTime:null},isInProgress(){return this.currentState===ee.PREPARING||this.currentState===ee.VALIDATING||this.currentState===ee.PUSHING}};async function k0(t,e,n={}){let{codeType:i="W"}=n;const{pubspecDeps:r={},artifactName:s=e}=n;i==="CustomWidget"&&(i=J.WIDGET),i==="CustomAction"&&(i=J.ACTION),i==="CustomFunction"&&(i=J.FUNCTION),i==="CustomClass"&&(i=J.CODE_FILE),i==="CodeFile"&&(i=J.CODE_FILE),G.reset(),G.setState(ee.PREPARING);try{const o=await Te("flutterflow"),a=await Te("flutterflow_project_id");if(!o||!a)throw new Error("FlutterFlow credentials not configured. Please set your API key and Project ID in the API Keys settings.");if(!Os(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=yt(),u=new hi(o,a,"main",l);G.setState(ee.VALIDATING);const c=new Map,d=i||b0(e,t),f=Uh(e,d);c.set(e,{artifactName:s,content:t,type:d,path:f}),G.setProgress(0,c.size);const h=js(c);if(!h.valid)throw new Error(`Validation failed: ${h.errors.join(` -`)}`);const p=await Hl(u,r),g=p.yaml,m=await Ul(u,c,p.remoteFiles,`Provision ${s} custom class`,g),v=await jl(m.syncFileMap,m.remoteFiles),S=new Map(m.syncFileMap);S.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),Oe.set("package");const b=await Wl(S),_={project_id:a,zipped_custom_code:b,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};G.setState(ee.PUSHING),G.setProgress(1,c.size),sr(u),Oe.set("push");const x=await u.pushCode(_),I=await Bl(x);if(I.success)G.setSuccess({fileCount:c.size,projectId:a,warnings:I.errorMap&&I.errorMap.size>0?Array.from(I.errorMap.entries()):[]});else{const T=I.errorMessage||Dl(I.responseCode);throw new Error(T)}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:p.added,unverified:m.unverified,approximate:m.approximate,warnings:I.errorMap?Array.from(I.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),G.setError(o),o instanceof mt?{success:!1,unconfirmed:!0,error:o.message,state:G.currentState}:{success:!1,error:o.message,state:G.currentState}}}async function Wl(t){const e=new JSZip;for(const[n,i]of t.entries())e.file(n,i.content);return e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}async function k0(t,e={}){const{artifactType:n,artifactName:i,fileName:r,pipelineResult:s}=e;console.log(`Starting commit for ${i} (${n})`);let o=!1;const a={projectId:null,endpoint:yt(),artifactType:n,artifactName:i,fileName:r};try{G.setState(ee.PREPARING);const l=Hh(t,{artifactType:n,artifactName:i,fileName:r}),u=E0(l.content);console.log("Detected dependencies:",u),G.setState(ee.VALIDATING);const c=await Te("flutterflow"),d=qi||await Te("flutterflow_project_id");if(!c)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!d)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Os(d))throw new Error("Invalid FlutterFlow Project ID format.");a.projectId=d;const f=new Map;f.set(l.fileName,{artifactName:i,content:l.content,type:l.codeType,path:jh(l.fileName,l.codeType),functionName:l.codeType===J.FUNCTION?i:void 0}),G.setProgress(0,f.size);const h=js(f);if(!h.valid)throw new Error(`File validation failed: +`)}`);const p=await Hl(u,r),g=p.yaml,m=await Ul(u,c,p.remoteFiles,`Provision ${s} custom class`,g),v=await Dl(m.syncFileMap,m.remoteFiles),E=new Map(m.syncFileMap);E.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),Oe.set("package");const S=await Wl(E),_={project_id:a,zipped_custom_code:S,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};G.setState(ee.PUSHING),G.setProgress(1,c.size),sr(u),Oe.set("push");const b=await jl(u,_);if(b.success)G.setSuccess({fileCount:c.size,projectId:a,warnings:b.errorMap&&b.errorMap.size>0?Array.from(b.errorMap.entries()):[]});else{const k=b.errorMessage||Bl(b.responseCode);throw new Error(k)}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:p.added,unverified:m.unverified,approximate:m.approximate,warnings:b.errorMap?Array.from(b.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),G.setError(o),o instanceof lt?{success:!1,unconfirmed:!0,error:o.message,state:G.currentState}:{success:!1,error:o.message,state:G.currentState}}}async function Wl(t){const e=new JSZip;for(const[n,i]of t.entries())e.file(n,i.content);return e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}async function C0(t,e={}){const{artifactType:n,artifactName:i,fileName:r,pipelineResult:s}=e;console.log(`Starting commit for ${i} (${n})`);let o=!1;const a={projectId:null,endpoint:yt(),artifactType:n,artifactName:i,fileName:r};try{G.setState(ee.PREPARING);const l=qh(t,{artifactType:n,artifactName:i,fileName:r}),u=S0(l.content);console.log("Detected dependencies:",u),G.setState(ee.VALIDATING);const c=await Te("flutterflow"),d=qi||await Te("flutterflow_project_id");if(!c)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!d)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Os(d))throw new Error("Invalid FlutterFlow Project ID format.");a.projectId=d;const f=new Map;f.set(l.fileName,{artifactName:i,content:l.content,type:l.codeType,path:Uh(l.fileName,l.codeType),functionName:l.codeType===J.FUNCTION?i:void 0}),G.setProgress(0,f.size);const h=js(f);if(!h.valid)throw new Error(`File validation failed: ${h.errors.join(` -`)}`);h.warnings.length>0&&console.warn("Validation warnings:",h.warnings),G.setState(ee.PUSHING);const p=yt(),g=new hi(c,d,"main",p),m=await Hl(g,u),v=m.yaml,S=await Ul(g,f,m.remoteFiles,`Provision ${i} custom class`,v);o=S.provisionSucceeded===!0;const b=await jl(S.syncFileMap,S.remoteFiles),_=new Map(S.syncFileMap);_.set("pubspec.yaml",{content:v,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Oe.set("package");const x=await Wl(_),I={project_id:d,zipped_custom_code:x,uid:`web_${Date.now()}`,branch_name:g.branchName,serialized_yaml:v,file_map:b.fileMapContents,functions_map:b.functionsMapContents};G.setProgress(1,f.size),sr(g),Oe.set("push");const T=await g.pushCode(I),E=await Bl(T);if(E.success){const P={...S0(l,s),projectId:d};return G.setSuccess({...P,fileCount:f.size,warnings:E.errorMap?Array.from(E.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${l.fileName} to FlutterFlow`,metadata:P,targetIdentity:a,addedDependencies:m.added,unverified:S.unverified,approximate:S.approximate,warnings:E.errorMap?Array.from(E.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}else{const P=E.errorMessage||Dl(E.responseCode),$=new Error(P);throw $.errorMap=E.errorMap,$}}catch(l){console.error("Commit execution failed:",l),G.setError(l);let u=new Map;if(l.errorMap)u=l.errorMap;else if(l.message&&l.message.includes("{"))try{const c=l.message.match(/\{[\s\S]*\}/);if(c){const d=JSON.parse(c[0]);u=new Map(Object.entries(d))}}catch(c){console.warn("Failed to parse error map from commit response:",c)}return l instanceof mt?{success:!1,unconfirmed:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:o?{success:!1,partial:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function C0(t,e={}){const{pipelineResult:n}=e;let i=!1;const r={projectId:null,endpoint:yt(),artifactType:"Bundle",artifactName:t?.title,fileName:t?.fileEntries?`${t.fileEntries.length} artifacts`:"bundle"};try{if(G.setState(ee.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: +`)}`);h.warnings.length>0&&console.warn("Validation warnings:",h.warnings),G.setState(ee.PUSHING);const p=yt(),g=new hi(c,d,"main",p),m=await Hl(g,u),v=m.yaml,E=await Ul(g,f,m.remoteFiles,`Provision ${i} custom class`,v);o=E.provisionSucceeded===!0;const S=await Dl(E.syncFileMap,E.remoteFiles),_=new Map(E.syncFileMap);_.set("pubspec.yaml",{content:v,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Oe.set("package");const b=await Wl(_),k={project_id:d,zipped_custom_code:b,uid:`web_${Date.now()}`,branch_name:g.branchName,serialized_yaml:v,file_map:S.fileMapContents,functions_map:S.functionsMapContents};G.setProgress(1,f.size),sr(g),Oe.set("push");const T=await jl(g,k);if(T.success){const x={...x0(l,s),projectId:d};return G.setSuccess({...x,fileCount:f.size,warnings:T.errorMap?Array.from(T.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${l.fileName} to FlutterFlow`,metadata:x,targetIdentity:a,addedDependencies:m.added,unverified:E.unverified,approximate:E.approximate,warnings:T.errorMap?Array.from(T.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}else{const x=T.errorMessage||Bl(T.responseCode),F=new Error(x);throw F.errorMap=T.errorMap,F}}catch(l){console.error("Commit execution failed:",l),G.setError(l);let u=new Map;if(l.errorMap)u=l.errorMap;else if(l.message&&l.message.includes("{"))try{const c=l.message.match(/\{[\s\S]*\}/);if(c){const d=JSON.parse(c[0]);u=new Map(Object.entries(d))}}catch(c){console.warn("Failed to parse error map from commit response:",c)}return l instanceof lt?{success:!1,unconfirmed:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:o?{success:!1,partial:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function A0(t,e={}){const{pipelineResult:n}=e;let i=!1;const r={projectId:null,endpoint:yt(),artifactType:"Bundle",artifactName:t?.title,fileName:t?.fileEntries?`${t.fileEntries.length} artifacts`:"bundle"};try{if(G.setState(ee.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: ${t.errors.join(` -`)}`);const s=new Map(t.fileEntries.map(I=>[I.fileName,{artifactId:I.artifactId,artifactName:I.artifactName,content:I.content,type:I.type,path:I.path,functionName:I.type===J.FUNCTION?I.artifactName:void 0}]));G.setProgress(0,s.size);const o=js(s);if(!o.valid)throw new Error(`File validation failed: +`)}`);const s=new Map(t.fileEntries.map(b=>[b.fileName,{artifactId:b.artifactId,artifactName:b.artifactName,content:b.content,type:b.type,path:b.path,functionName:b.type===J.FUNCTION?b.artifactName:void 0}]));G.setProgress(0,s.size);const o=js(s);if(!o.valid)throw new Error(`File validation failed: ${o.errors.join(` -`)}`);G.setState(ee.VALIDATING);const a=await Te("flutterflow"),l=qi||await Te("flutterflow_project_id");if(!a)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!l)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Os(l))throw new Error("Invalid FlutterFlow Project ID format.");r.projectId=l,G.setState(ee.PUSHING);const u=yt(),c=new hi(a,l,"main",u),d=await Hl(c,t.dependencies),f=d.yaml,h=await Ul(c,s,d.remoteFiles,`Provision ${t.title} custom classes`,f);i=h.provisionSucceeded===!0;const p=await jl(h.syncFileMap,h.remoteFiles),g=new Map(h.syncFileMap);g.set("pubspec.yaml",{content:f,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Oe.set("package");const m=await Wl(g),v={project_id:l,zipped_custom_code:m,uid:`web_${Date.now()}`,branch_name:c.branchName,serialized_yaml:f,file_map:p.fileMapContents,functions_map:p.functionsMapContents};G.setProgress(1,s.size),sr(c),Oe.set("push");const S=await c.pushCode(v),b=await Bl(S);if(b.success){const I={...n,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((T,E)=>T+E.content.length,0),projectId:l};return G.setSuccess({...I,fileCount:s.size,warnings:b.errorMap?Array.from(b.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:I,targetIdentity:r,addedDependencies:d.added,unverified:h.unverified,approximate:h.approximate,warnings:b.errorMap?Array.from(b.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}const _=b.errorMessage||Dl(b.responseCode),x=new Error(_);throw x.errorMap=b.errorMap,x}catch(s){console.error("Bundle commit execution failed:",s),G.setError(s);const o=s.errorMap||new Map;return s instanceof mt?{success:!1,unconfirmed:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:i?{success:!1,partial:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function A0(t,e=[]){const n=ml("architect");try{return await Ss("architect",Ah,uv(t),n,e)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Prompt Architect failed: ${i.message}`)}}async function Us(t,e,n=[],i){const r=dv(t),s=ml("generator",y.bundleSpec);try{return await Ss("generator",e,r,s,n)}catch(o){if(o.isModelArmor||o.isUsageLimit||o.isPipelineCancel)throw o;if(e!==kr){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,o.message),$w(e,kr,i);try{return await Ss("generator",kr,r,s,n)}catch(a){throw a.isModelArmor||a.isUsageLimit||a.isPipelineCancel?a:new Error(`Code Generator failed: primary (${e}): ${o.message} | fallback (${kr}): ${a.message}`)}}throw new Error(`Code Generator failed: ${o.message}`)}}async function Hs(t,e=null){const n={...ml("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await Ss("review",Ph,fv(t),n)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Code Review failed: ${i.message}`)}}function bs(t,e){const n=document.getElementById(`step${t}-item`),i=document.getElementById(`step${t}-status`);!n||!i||(n.classList.remove("active","completed","error"),i.classList.remove("running","completed","error"),e==="active"?(n.classList.add("active"),i.classList.add("running"),i.innerHTML=` +`)}`);G.setState(ee.VALIDATING);const a=await Te("flutterflow"),l=qi||await Te("flutterflow_project_id");if(!a)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!l)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Os(l))throw new Error("Invalid FlutterFlow Project ID format.");r.projectId=l,G.setState(ee.PUSHING);const u=yt(),c=new hi(a,l,"main",u),d=await Hl(c,t.dependencies),f=d.yaml,h=await Ul(c,s,d.remoteFiles,`Provision ${t.title} custom classes`,f);i=h.provisionSucceeded===!0;const p=await Dl(h.syncFileMap,h.remoteFiles),g=new Map(h.syncFileMap);g.set("pubspec.yaml",{content:f,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Oe.set("package");const m=await Wl(g),v={project_id:l,zipped_custom_code:m,uid:`web_${Date.now()}`,branch_name:c.branchName,serialized_yaml:f,file_map:p.fileMapContents,functions_map:p.functionsMapContents};G.setProgress(1,s.size),sr(c),Oe.set("push");const E=await jl(c,v);if(E.success){const b={...n,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((k,T)=>k+T.content.length,0),projectId:l};return G.setSuccess({...b,fileCount:s.size,warnings:E.errorMap?Array.from(E.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:b,targetIdentity:r,addedDependencies:d.added,unverified:h.unverified,approximate:h.approximate,warnings:E.errorMap?Array.from(E.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}const S=E.errorMessage||Bl(E.responseCode),_=new Error(S);throw _.errorMap=E.errorMap,_}catch(s){console.error("Bundle commit execution failed:",s),G.setError(s);const o=s.errorMap||new Map;return s instanceof lt?{success:!1,unconfirmed:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:i?{success:!1,partial:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function P0(t,e=[]){const n=ml("architect");try{return await Ss("architect",Ph,fv(t),n,e)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Prompt Architect failed: ${i.message}`)}}async function Us(t,e,n=[],i){const r=hv(t),s=ml("generator",y.bundleSpec);try{return await Ss("generator",e,r,s,n)}catch(o){if(o.isModelArmor||o.isUsageLimit||o.isPipelineCancel)throw o;if(e!==kr){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,o.message),Mw(e,kr,i);try{return await Ss("generator",kr,r,s,n)}catch(a){throw a.isModelArmor||a.isUsageLimit||a.isPipelineCancel?a:new Error(`Code Generator failed: primary (${e}): ${o.message} | fallback (${kr}): ${a.message}`)}}throw new Error(`Code Generator failed: ${o.message}`)}}async function Hs(t,e=null){const n={...ml("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await Ss("review",Fh,pv(t),n)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Code Review failed: ${i.message}`)}}function bs(t,e){const n=document.getElementById(`step${t}-item`),i=document.getElementById(`step${t}-status`);!n||!i||(n.classList.remove("active","completed","error"),i.classList.remove("running","completed","error"),e==="active"?(n.classList.add("active"),i.classList.add("running"),i.innerHTML=` `):e==="completed"?(n.classList.add("completed"),i.classList.add("completed"),i.innerHTML=` @@ -127,12 +127,12 @@ ${o.errors.join(` `):i.innerHTML=` - `)}function Ae(t,e){const n=document.getElementById(`step${t}-loading`),i=document.getElementById(`step${t}-result`);e?(n.classList.remove("hidden"),i.classList.add("hidden"),bs(t,"active")):(n.classList.add("hidden"),i.classList.remove("hidden"),bs(t,"completed"))}function P0(t){const e=document.getElementById(`${t}-content`),n=document.getElementById(`${t}-chevron`);e.classList.contains("open")?(e.classList.remove("open"),n&&(n.style.transform="rotate(0deg)")):(e.classList.add("open"),n&&(n.style.transform="rotate(180deg)"))}function F0(t){nt(parseInt(t.replace("step","")))}function nt(t){for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-item`);a&&a.classList.remove("active")}const e=document.getElementById(`step${t}-item`);e&&e.classList.add("active"),Nn();const n=document.getElementById("ready-state");n&&n.classList.add("hidden");for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-content`);a&&a.classList.add("hidden")}const i=document.getElementById(`step${t}-content`);i&&i.classList.remove("hidden");const r=document.getElementById("stage-title"),s={1:"Prompt Architect",2:"Code Generator",3:"Code Review"};r&&(r.textContent=s[t]||"Active Workflow Stage")}function R0(t){const e=document.getElementById(t);if(!e)return;const n=e.dataset.raw||e.textContent;navigator.clipboard.writeText(n).then(()=>{const r=e.closest(".code-container")?.querySelector(".copy-btn");r&&(r.classList.add("copied"),r.innerHTML=' Copied!',setTimeout(()=>{r.classList.remove("copied"),r.innerHTML=' Copy'},2e3))}).catch(i=>{console.warn("Failed to copy to clipboard:",i)})}function qa(t){const e=za(t);console.log(`Step 1 (Prompt Architect): ${Gt(Ah)}`),console.log(e!==t?`Step 2 (Code Generator): ${Gt(t)} → ${Gt(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${Gt(t)}`),console.log(`Step 3 (Code Review): ${Gt(Ph)}`)}function Wh(){return{step1Result:y.step1Result,step2Result:y.step2Result,step3Result:y.step3Result,artifactBundle:y.artifactBundle,bundleReview:y.bundleReview,selectedArtifactId:y.selectedArtifactId}}function T0(t){if(!t)return;Object.assign(y,t),new Set((y.artifactBundle?.artifacts||[]).map(n=>n.id)).has(y.selectedArtifactId)||(y.selectedArtifactId=oi(y.artifactBundle)?.id||null)}const qh="results-replacement-error";function $0(t,{stage:e=2,runId:n,retry:i}){if(!re(n))return;const r=document.getElementById(qh);if(!r)return;const s=wh(t),o=document.getElementById("results-replacement-error-title"),a=document.getElementById("results-replacement-error-message"),l=document.getElementById("results-replacement-error-retry"),u=document.getElementById("results-replacement-error-upgrade");o&&(o.textContent=`${Vs[e]||"Regeneration"}: ${s.title}`),a&&(a.textContent=s.message),r.hidden=!1;let c=null;u&&(u.hidden=!s.canUpgrade,s.canUpgrade&&(u.textContent="View plans",u.onclick=()=>di(),c=u)),l&&(l.hidden=s.canUpgrade,s.canUpgrade||(l.onclick=()=>{ql(),typeof i=="function"&&i()},l.textContent="Retry",c=l)),(c||r).focus({preventScroll:!0})}function ql(){const t=document.getElementById(qh);t&&(t.hidden=!0)}function zh(t,{previous:e,stage:n,runId:i,retry:r}){re(i)&&(t.isUsageLimit&&un(),T0(e),cr(),nn(!0),ur(),eo(),$0(t,{stage:n,runId:i,retry:r}),rn())}async function Vh(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0;const e=Gs();zl("standardRegenerate",y.step2Result,y.step1Result);const n=document.querySelectorAll(".btn-refine-action"),i=Wh();n.forEach(r=>{r.disabled=!0,r.innerHTML=` + `)}function Ae(t,e){const n=document.getElementById(`step${t}-loading`),i=document.getElementById(`step${t}-result`);e?(n.classList.remove("hidden"),i.classList.add("hidden"),bs(t,"active")):(n.classList.add("hidden"),i.classList.remove("hidden"),bs(t,"completed"))}function F0(t){const e=document.getElementById(`${t}-content`),n=document.getElementById(`${t}-chevron`);e.classList.contains("open")?(e.classList.remove("open"),n&&(n.style.transform="rotate(0deg)")):(e.classList.add("open"),n&&(n.style.transform="rotate(180deg)"))}function R0(t){nt(parseInt(t.replace("step","")))}function nt(t){for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-item`);a&&a.classList.remove("active")}const e=document.getElementById(`step${t}-item`);e&&e.classList.add("active"),Nn();const n=document.getElementById("ready-state");n&&n.classList.add("hidden");for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-content`);a&&a.classList.add("hidden")}const i=document.getElementById(`step${t}-content`);i&&i.classList.remove("hidden");const r=document.getElementById("stage-title"),s={1:"Prompt Architect",2:"Code Generator",3:"Code Review"};r&&(r.textContent=s[t]||"Active Workflow Stage")}function T0(t){const e=document.getElementById(t);if(!e)return;const n=e.dataset.raw||e.textContent;navigator.clipboard.writeText(n).then(()=>{const r=e.closest(".code-container")?.querySelector(".copy-btn");r&&(r.classList.add("copied"),r.innerHTML=' Copied!',setTimeout(()=>{r.classList.remove("copied"),r.innerHTML=' Copy'},2e3))}).catch(i=>{console.warn("Failed to copy to clipboard:",i)})}function qa(t){const e=za(t);console.log(`Step 1 (Prompt Architect): ${Gt(Ph)}`),console.log(e!==t?`Step 2 (Code Generator): ${Gt(t)} → ${Gt(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${Gt(t)}`),console.log(`Step 3 (Code Review): ${Gt(Fh)}`)}function zh(){return{step1Result:y.step1Result,step2Result:y.step2Result,step3Result:y.step3Result,artifactBundle:y.artifactBundle,bundleReview:y.bundleReview,selectedArtifactId:y.selectedArtifactId}}function $0(t){if(!t)return;Object.assign(y,t),new Set((y.artifactBundle?.artifacts||[]).map(n=>n.id)).has(y.selectedArtifactId)||(y.selectedArtifactId=oi(y.artifactBundle)?.id||null)}const Vh="results-replacement-error";function M0(t,{stage:e=2,runId:n,retry:i}){if(!re(n))return;const r=document.getElementById(Vh);if(!r)return;const s=bh(t),o=document.getElementById("results-replacement-error-title"),a=document.getElementById("results-replacement-error-message"),l=document.getElementById("results-replacement-error-retry"),u=document.getElementById("results-replacement-error-upgrade");o&&(o.textContent=`${Vs[e]||"Regeneration"}: ${s.title}`),a&&(a.textContent=s.message),r.hidden=!1;let c=null;u&&(u.hidden=!s.canUpgrade,s.canUpgrade&&(u.textContent="View plans",u.onclick=()=>di(),c=u)),l&&(l.hidden=s.canUpgrade,s.canUpgrade||(l.onclick=()=>{ql(),typeof i=="function"&&i()},l.textContent="Retry",c=l)),(c||r).focus({preventScroll:!0})}function ql(){const t=document.getElementById(Vh);t&&(t.hidden=!0)}function Gh(t,{previous:e,stage:n,runId:i,retry:r}){re(i)&&(t.isUsageLimit&&un(),$0(e),cr(),nn(!0),ur(),eo(),M0(t,{stage:n,runId:i,retry:r}),rn())}async function Kh(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0;const e=Gs();zl("standardRegenerate",y.step2Result,y.step1Result);const n=document.querySelectorAll(".btn-refine-action"),i=zh();n.forEach(r=>{r.disabled=!0,r.innerHTML=` - Refining...`});try{ql();const r=Nl(),s=r.id,o=hv({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,artifactId:r.id,userFeedback:"Fix the issues listed in the audit report."});Zs({runId:e}),Ft(2,e),nt(2),Ae(2,!0);const a=await Us(o,t,[],e);if(!re(e))return;y.step2Result=a,Bs(),tn(2,e);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),nt(3),Ft(3,e),Ae(3,!0);const c=await Hs(y.step2Result,y.step1Result);if(!re(e))return;y.step3Result=c,Ds(),tn(3,e),y.artifactBundle?.artifacts?.some(h=>h.id===s)?y.selectedArtifactId=s:y.selectedArtifactId=oi(y.artifactBundle)?.id||null;const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const f=Ls(y.step3Result);ur(u,f)}catch(r){if(console.error("Refinement failed:",r),!re(e))return;const s=Ms(r,{architect:2,generator:2,review:3});zh(r,{previous:i,stage:s,runId:e,retry:Vh})}finally{n.forEach(r=>{r.disabled=!1,r.textContent="Refine & Regenerate"}),re(e)&&(y.isRunning=!1,rn())}}async function zl(t,e,n){const i=`${_t}/connectFeedback`,r={type:t,code:e,input:n};try{const s=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok){const a=await s.text();return console.error(`callEndpoint failed: ${s.status} ${s.statusText}`,a),{success:!1,status:s.status,error:a}}const o=await s.json();return console.log("Telemetry success:",o),o}catch(s){return console.error("callEndpoint failed:",s),{success:!1,error:s.message}}}function M0(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function Gh(){const t=document.getElementById("ff-error-paste-input"),e=t?.value?.trim();if(!e){t?.focus(),t?.classList.add("ring-2","ring-red-400","border-red-300"),setTimeout(()=>t?.classList.remove("ring-2","ring-red-400","border-red-300"),2e3);return}if(!y.step2Result){Ee("No generated code found. Please run the full pipeline first.","warning");return}if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=Gs();zl("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` + Refining...`});try{ql();const r=Nl(),s=r.id,o=gv({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,artifactId:r.id,userFeedback:"Fix the issues listed in the audit report."});Zs({runId:e}),Ft(2,e),nt(2),Ae(2,!0);const a=await Us(o,t,[],e);if(!re(e))return;y.step2Result=a,Bs(),tn(2,e);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),nt(3),Ft(3,e),Ae(3,!0);const c=await Hs(y.step2Result,y.step1Result);if(!re(e))return;y.step3Result=c,Ds(),tn(3,e),y.artifactBundle?.artifacts?.some(h=>h.id===s)?y.selectedArtifactId=s:y.selectedArtifactId=oi(y.artifactBundle)?.id||null;const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const f=Ls(y.step3Result);ur(u,f)}catch(r){if(console.error("Refinement failed:",r),!re(e))return;const s=Ms(r,{architect:2,generator:2,review:3});Gh(r,{previous:i,stage:s,runId:e,retry:Kh})}finally{n.forEach(r=>{r.disabled=!1,r.textContent="Refine & Regenerate"}),re(e)&&(y.isRunning=!1,rn())}}async function zl(t,e,n){const i=`${_t}/connectFeedback`,r={type:t,code:e,input:n};try{const s=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok){const a=await s.text();return console.error(`callEndpoint failed: ${s.status} ${s.statusText}`,a),{success:!1,status:s.status,error:a}}const o=await s.json();return console.log("Telemetry success:",o),o}catch(s){return console.error("callEndpoint failed:",s),{success:!1,error:s.message}}}function L0(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function Yh(){const t=document.getElementById("ff-error-paste-input"),e=t?.value?.trim();if(!e){t?.focus(),t?.classList.add("ring-2","ring-red-400","border-red-300"),setTimeout(()=>t?.classList.remove("ring-2","ring-red-400","border-red-300"),2e3);return}if(!y.step2Result){Ee("No generated code found. Please run the full pipeline first.","warning");return}if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=Gs();zl("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` - Fixing…`);const s=Wh();try{ql();const o=nh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});bp(),Zs({runId:i}),Ft(2,i),nt(2),Ae(2,!0);const a=await Us(o,n,[],i);if(!re(i))return;y.step2Result=a,Bs(),tn(2,i);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),nt(3),Ft(3,i),Ae(3,!0);const c=await Hs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,Ds(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const f=Ls(y.step3Result);ur(u,f),t&&(t.value="")}catch(o){if(console.error("Fix from errors failed:",o),!re(i))return;const a=Ms(o,{architect:2,generator:2,review:3});zh(o,{previous:s,stage:a,runId:i,retry:Gh})}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function or(){if(console.log("runThinkingPipeline called"),y.isRunning)return;localStorage.setItem("hasSeenWalkthrough","true");const t=document.getElementById("pipeline-input").value,e=document.getElementById("code-generator-model").value,n=Ne.slice();if(!t.trim()){Ee("Please describe your FlutterFlow widget first.","warning");return}y.isRunning=!0;const i=Gs();try{if(await Oa,!re(i)||(pn.length&&await Promise.allSettled(pn.map(v=>v.job)),!re(i))||!await rw()||!re(i)||(await X0(),!re(i)))return;const r=za(e);t.length,g0(),y.submittedPrompt=t,y.submittedImages=n.filter(v=>v.url),Ka(!0),qa(r),Nn();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const o=document.getElementById("paywall-exhausted");o&&o.classList.add("hidden"),Zs({prompt:t,runId:i}),Ow(),nt(1),Ft(1,i),Ae(1,!0);const a=y.submittedImages.map(v=>({url:v.url})),l=await A0(t,a);if(!re(i))return;y.step1Result=l,m0(),tn(1,i);const u=document.getElementById("step1-output"),c=li(y.step1Result);u.textContent=c,u.dataset.raw=c,Ae(1,!1),nt(2),Ft(2,i),Ae(2,!0);const d=await Us(y.step1Result,r,a,i);if(!re(i))return;y.step2Result=d,Bs(),tn(2,i);const f=document.getElementById("step2-output"),h=li(y.step2Result);f.textContent=h,f.dataset.raw=h,Ae(2,!1),nt(3),Ft(3,i),Ae(3,!0);const p=await Hs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=p,Ds(),tn(3,i);const g=document.getElementById("step3-output");g.textContent=y.step3Result,Ae(3,!1),cr();const m=Ls(y.step3Result);Bw(),ur(h,m)}catch(r){if(r.isPipelineCancel||console.error("Pipeline failed:",r),!re(i))return;const s=Ms(r,{architect:1,generator:2,review:3});r.isUsageLimit?un():(r.message,za(document.getElementById("code-generator-model").value),void 0),nt(s),Ae(s,!1),vp(r,{stage:s,runId:i}),bs(s,"error")}finally{re(i)&&(y.isRunning=!1,Ka(!1),rn())}}function L0(){const t=document.getElementById("code-generator-model").value,e=[ms,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(i=>i!==t),n=prompt(`Retry with different model? + Fixing…`);const s=zh();try{ql();const o=nh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});Sp(),Zs({runId:i}),Ft(2,i),nt(2),Ae(2,!0);const a=await Us(o,n,[],i);if(!re(i))return;y.step2Result=a,Bs(),tn(2,i);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),nt(3),Ft(3,i),Ae(3,!0);const c=await Hs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,Ds(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const f=Ls(y.step3Result);ur(u,f),t&&(t.value="")}catch(o){if(console.error("Fix from errors failed:",o),!re(i))return;const a=Ms(o,{architect:2,generator:2,review:3});Gh(o,{previous:s,stage:a,runId:i,retry:Yh})}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function or(){if(console.log("runThinkingPipeline called"),y.isRunning)return;localStorage.setItem("hasSeenWalkthrough","true");const t=document.getElementById("pipeline-input").value,e=document.getElementById("code-generator-model").value,n=Ne.slice();if(!t.trim()){Ee("Please describe your FlutterFlow widget first.","warning");return}y.isRunning=!0;const i=Gs();try{if(await Oa,!re(i)||(pn.length&&await Promise.allSettled(pn.map(v=>v.job)),!re(i))||!await sw()||!re(i)||(await Q0(),!re(i)))return;const r=za(e);t.length,m0(),y.submittedPrompt=t,y.submittedImages=n.filter(v=>v.url),Ka(!0),qa(r),Nn();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const o=document.getElementById("paywall-exhausted");o&&o.classList.add("hidden"),Zs({prompt:t,runId:i}),Bw(),nt(1),Ft(1,i),Ae(1,!0);const a=y.submittedImages.map(v=>({url:v.url})),l=await P0(t,a);if(!re(i))return;y.step1Result=l,v0(),tn(1,i);const u=document.getElementById("step1-output"),c=li(y.step1Result);u.textContent=c,u.dataset.raw=c,Ae(1,!1),nt(2),Ft(2,i),Ae(2,!0);const d=await Us(y.step1Result,r,a,i);if(!re(i))return;y.step2Result=d,Bs(),tn(2,i);const f=document.getElementById("step2-output"),h=li(y.step2Result);f.textContent=h,f.dataset.raw=h,Ae(2,!1),nt(3),Ft(3,i),Ae(3,!0);const p=await Hs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=p,Ds(),tn(3,i);const g=document.getElementById("step3-output");g.textContent=y.step3Result,Ae(3,!1),cr();const m=Ls(y.step3Result);Dw(),ur(h,m)}catch(r){if(r.isPipelineCancel||console.error("Pipeline failed:",r),!re(i))return;const s=Ms(r,{architect:1,generator:2,review:3});r.isUsageLimit?un():(r.message,za(document.getElementById("code-generator-model").value),void 0),nt(s),Ae(s,!1),yp(r,{stage:s,runId:i}),bs(s,"error")}finally{re(i)&&(y.isRunning=!1,Ka(!1),rn())}}function N0(){const t=document.getElementById("code-generator-model").value,e=[ms,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(i=>i!==t),n=prompt(`Retry with different model? Current: ${t} @@ -140,10 +140,10 @@ Options: 1. ${e[0]} 2. ${e[1]} -Enter 1 or 2:`);n==="1"?(document.getElementById("code-generator-model").value=e[0],or()):n==="2"&&(document.getElementById("code-generator-model").value=e[1],or())}async function N0(){const t=Ol();if(!t){Ee("No code to commit. Please run the pipeline first.","warning");return}const e=await Te("flutterflow"),n=await Te("flutterflow_project_id");if(!e||!n){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),Rl();return}if(y.artifactBundle?.artifacts?.length>1){await O0();return}const{artifactType:i,artifactName:r,fileName:s}=Oh(),o=Hh(t,{artifactType:i,artifactName:r,fileName:s}),a=b0(o);if(!a.canProceed){Ee(`Pre-commit checks failed: ${a.issues.join("; ")}`,"error");return}Kl(o,a,null,null)}async function O0(){const t=await Te("flutterflow"),e=await Te("flutterflow_project_id");if(!t||!e){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),Rl();return}const n=Jv(y.artifactBundle);if(n.errors.length>0){Ee(`Bundle validation failed: ${n.errors.join("; ")}`,"error");return}const i=new Map(n.fileEntries.map(a=>[a.fileName,{content:a.content,type:a.type,path:a.path}])),r=js(i),s={canProceed:r.valid&&n.errors.length===0,issues:[...n.errors,...r.errors],warnings:[...n.warnings,...r.warnings]};if(!s.canProceed){Ee(`Bundle validation failed: ${s.issues.join("; ")}`,"error");return}const o={content:n.fileEntries.map(a=>`// ${a.fileName} +Enter 1 or 2:`);n==="1"?(document.getElementById("code-generator-model").value=e[0],or()):n==="2"&&(document.getElementById("code-generator-model").value=e[1],or())}async function O0(){const t=Ol();if(!t){Ee("No code to commit. Please run the pipeline first.","warning");return}const e=await Te("flutterflow"),n=await Te("flutterflow_project_id");if(!e||!n){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),Rl();return}if(y.artifactBundle?.artifacts?.length>1){await B0();return}const{artifactType:i,artifactName:r,fileName:s}=Bh(),o=qh(t,{artifactType:i,artifactName:r,fileName:s}),a=E0(o);if(!a.canProceed){Ee(`Pre-commit checks failed: ${a.issues.join("; ")}`,"error");return}Kl(o,a,null,null)}async function B0(){const t=await Te("flutterflow"),e=await Te("flutterflow_project_id");if(!t||!e){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),Rl();return}const n=Xv(y.artifactBundle);if(n.errors.length>0){Ee(`Bundle validation failed: ${n.errors.join("; ")}`,"error");return}const i=new Map(n.fileEntries.map(a=>[a.fileName,{content:a.content,type:a.type,path:a.path}])),r=js(i),s={canProceed:r.valid&&n.errors.length===0,issues:[...n.errors,...r.errors],warnings:[...n.warnings,...r.warnings]};if(!s.canProceed){Ee(`Bundle validation failed: ${s.issues.join("; ")}`,"error");return}const o={content:n.fileEntries.map(a=>`// ${a.fileName} ${a.content}`).join(` -`),fileName:`${n.fileEntries.length} files`,codeType:"bundle",artifactType:"Bundle",artifactName:n.title};Kl(o,s,n.dependencies,n)}function B0(t){let e=t.errorMap||new Map;!(e instanceof Map)&&typeof e=="object"&&(e=new Map(Object.entries(e)));let n=`
    +`),fileName:`${n.fileEntries.length} files`,codeType:"bundle",artifactType:"Bundle",artifactName:n.title};Kl(o,s,n.dependencies,n)}function D0(t){let e=t.errorMap||new Map;!(e instanceof Map)&&typeof e=="object"&&(e=new Map(Object.entries(e)));let n=`

    FlutterFlow Commit Failed

    ${q(t.error)}

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

    Errors:

    @@ -156,7 +156,7 @@ ${a.content}`).join(` Fix Errors & Regenerate -
    `;const i=document.getElementById("step3-output");i&&(i.innerHTML=n,document.getElementById("btn-regenerate-from-error")?.addEventListener("click",()=>{Kh(t.error,e)}))}async function Kh(t,e){if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=Gs(),r=document.getElementById("btn-regenerate-from-error");r&&(r.disabled=!0,r.innerHTML=` +
    `;const i=document.getElementById("step3-output");i&&(i.innerHTML=n,document.getElementById("btn-regenerate-from-error")?.addEventListener("click",()=>{Jh(t.error,e)}))}async function Jh(t,e){if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=Gs(),r=document.getElementById("btn-regenerate-from-error");r&&(r.disabled=!0,r.innerHTML=` Fixing...`);try{let s=`The previous code had the following errors when committing to FlutterFlow: @@ -164,8 +164,8 @@ ${a.content}`).join(` Error: ${g} `}else s+=`${t} -`;const o=nh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:s});Zs({runId:i}),Ft(2,i),nt(2),Ae(2,!0);const a=await Us(o,n,[],i);if(!re(i))return;y.step2Result=a,Bs(),tn(2,i);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),nt(3),Ft(3,i),Ae(3,!0);const c=await Hs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,Ds(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const f=Ls(y.step3Result);ur(u,f)}catch(s){if(console.error("Regeneration failed:",s),!re(i))return;const o=Ms(s,{architect:2,generator:2,review:3});s.isUsageLimit&&un(),nt(o),Ae(o,!1),vp(s,{stage:o,runId:i,retry:()=>Kh(t,e)}),bs(o,"error")}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function D0(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const n=await Te("flutterflow"),i=await Te("flutterflow_project_id");n&&i?(t.className="w-2 h-2 rounded-full bg-green-500",e.textContent="FlutterFlow credentials configured",e.className="text-green-600"):n||i?(t.className="w-2 h-2 rounded-full bg-yellow-500",e.textContent="FlutterFlow credentials incomplete",e.className="text-yellow-600"):(t.className="w-2 h-2 rounded-full bg-red-500",e.textContent="FlutterFlow credentials not configured",e.className="text-red-600")}async function Yh(t){try{const e=await fetch(`${_t}/auth/send-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:t})});if(!e.ok)throw new Error(`Failed to send magic link: HTTP ${e.status}`);return e.json()}catch(e){throw console.error("sendMagicLink failed:",{email:t,message:e.message,stack:e.stack}),e}}async function j0(t){try{const n=await(await fetch(`${_t}/auth/verify-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})})).json();if(n.error||!n.email||!n.sessionToken)throw new Error(n.error||"Invalid or expired link");return n}catch(e){throw console.error("verifyMagicLink failed:",{message:e.message,stack:e.stack}),e}}async function U0(t){try{const e=await fetch(`${_t}/auth/refresh-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:t})});if(!e.ok)return console.error("refreshSession: non-OK response",{url:`${_t}/auth/refresh-session`,status:e.status}),null;const n=await e.json();return n.error||!n.email||!n.sessionToken?(console.warn("refreshSession: validation failed",{error:n.error,hasEmail:!!n.email,hasToken:!!n.sessionToken}),null):n}catch(e){return console.error("refreshSession: fetch failed",{url:`${_t}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function td(t,e){const n=Zh(),i=(z.email||n.email)!==t;z.email=t,z.sessionToken=e,z.isVerified=!0,ce=Mn({isLoading:!0}),localStorage.setItem(hs,JSON.stringify({email:t,sessionToken:e})),i&&ip()}function Jh(){z.email=null,z.sessionToken=null,z.isVerified=!1,ce=Mn({isResolved:!0}),localStorage.removeItem(hs),localStorage.removeItem(gs)}function Zh(){try{const t=localStorage.getItem(hs);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(hs),{email:null,sessionToken:null}}}async function H0(){const e=new URLSearchParams(window.location.search).get("token");if(e){window.history.replaceState({},"",window.location.pathname+window.location.hash);try{const{email:n,sessionToken:i}=await j0(e);td(n,i),Xh();const r=nd();r&&!window.location.hash&&(window.location.hash=r)}catch(n){nd();const i=n.message||"Sign-in link invalid or expired.";Ee(i,"error"),Ws(),Jn(i,"error")}}else{const{email:n,sessionToken:i}=Zh();if(n&&i){const r=await U0(i);r?td(r.email,r.sessionToken):Jh()}}Vl()}function W0(){try{localStorage.setItem(Na,JSON.stringify({hash:window.location.hash||"#home",ts:Date.now()}))}catch(t){console.warn("rememberSignInReturnSurface: failed to persist return surface:",t)}}function nd(){try{const t=localStorage.getItem(Na);if(localStorage.removeItem(Na),!t)return null;const{hash:e,ts:n}=JSON.parse(t);return!e||typeof n!="number"||Date.now()-n>Iy?null:e}catch(t){return console.warn("consumeSignInReturnSurface: failed to read return surface:",t),null}}function Ws(){const t=document.getElementById("signin-modal");if(!t)return;W0(),document.getElementById("signin-email-input")?.removeAttribute("aria-invalid"),Jn(""),He(t)}function Xh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&We(e)}function Jn(t,e){const n=document.getElementById("signin-message");n&&(n.textContent=t||"",n.classList.remove("signin-message-success","signin-message-error"),e&&n.classList.add(`signin-message-${e}`))}async function q0(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),n=Fs(t?.value);if(!n||!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(n)||n.length>254){t?.setAttribute("aria-invalid","true"),Jn("Please enter a valid email address.","error");return}t?.removeAttribute("aria-invalid"),e&&(e.disabled=!0,e.textContent="Sending…");const r=uh(n);r&&Jn(r,"error");try{const s=await Yh(n),o=s?.code===ch;t&&!o&&(t.value=""),t?.setAttribute("aria-invalid",String(o)),Jn(dh(s,n),o?"error":"success"),e&&(e.disabled=!1,e.textContent=o?"Send Sign-in Link":"Sent!",o||setTimeout(()=>{e.textContent==="Sent!"&&(e.textContent="Send Sign-in Link")},2500))}catch(s){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:n,err:s}),Jn("Something went wrong. Please try again.","error"),e&&(e.disabled=!1,e.textContent="Send Sign-in Link")}}function z0(){z.email=null,z.sessionToken=null,z.isVerified=!1,ce=Mn({isResolved:!0}),$_({storage:window.localStorage,onIdentityChanged:Vl,onPlanChanged:zs})}const V0=M_({sendLink:Yh,getEmail:()=>z.email||"",onState:G0});function G0(t){const e=document.getElementById("send-new-link-btn"),n=document.getElementById("send-new-link-msg");if(!e||!n)return;if(t.status==="pending"){e.disabled=!0,e.textContent="Sending…",n.className="acct-access-msg",n.textContent="Sending a fresh sign-in link…";return}if(t.status==="sent"){e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg",n.textContent=dh(t.data,z.email||"")||"Link sent — check your email.";return}e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg error";const i=t.error?.message?`Couldn't send a link right now. ${t.error.message}`:"Couldn't send a link right now. Please try again.";n.textContent=i}async function K0(){await V0()}function Y0(){const t=R_(window.localStorage),e=t.length?`Cleared disposable UI caches: ${t.join(", ")}.`:"Nothing disposable to clear.";Ee(`${e} Your run count, identity and stored keys are kept.`,"info")}function J0(){const t=document.getElementById("delete-unavailable-modal");t&&He(t,{trigger:document.activeElement})}function Z0(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("delete-unavailable-modal");e&&We(e)}function Vl(){const t=z.isVerified&&!!z.email,e=document.getElementById("auth-signedout"),n=document.getElementById("auth-signedin"),i=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),n&&n.classList.toggle("hidden",!t),i&&i.classList.toggle("hidden",t);const r=document.getElementById("auth-user-email");r&&(r.textContent=z.email||"");const s=document.getElementById("access-signed-email");s&&(s.textContent=z.email||""),aw(),zs()}async function Qh(){try{if(typeof FingerprintJS>"u"){console.warn("resolveIdentity: FingerprintJS not loaded, skipping");return}const e=await(await FingerprintJS.load()).get(),n=e.visitorId,i=await fetch(Py,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fingerprint:e.visitorId,cookie_id:n})});if(!i.ok)throw new Error(`Identity check HTTP ${i.status}`);const r=await i.json();if(ft.userId=r.user_id,ft.token=r.identity_token||null,ft.status=r.status,ft.resolved=!0,sessionStorage.setItem(Cy,r.user_id),ft.token&&sessionStorage.setItem(Ay,ft.token),r.usage_count!==void 0){const s=gn(),a=(r.usage_month||s)===s?r.usage_count:0;localStorage.setItem(Fn,JSON.stringify({count:a,month:s})),un()}console.log(`Identity resolved: ${r.status} (${r.user_id.slice(0,8)}...) usage: ${r.usage_count??"n/a"}`)}catch(t){console.error("resolveIdentity failed:",t)}}let Wo=null;function X0(t=5e3){return ft.resolved?Promise.resolve():(Wo||(Wo=Qh().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([Wo,new Promise(e=>setTimeout(e,t))]))}function ep(){const t=gn();try{const e=localStorage.getItem(Fn);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Fn,month:t,err:e}),localStorage.removeItem(Fn),{count:0,month:t}}}function gn(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function lr(){const t=ep();return t.month!==gn()?{count:0,month:gn()}:t}function Q0(){const e={count:lr().count+1,month:gn()};return localStorage.setItem(Fn,JSON.stringify(e)),e}function pi(){return!!ce.isLoading}function Tt(){return!!ce.isResolved}function ew(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(ps,e)?e:null}function tw(t){return t&&Object.entries(Eh).find(([,e])=>e===t)?.[0]||null}function Cr(...t){return t.find(e=>e!=null&&e!=="")}function nw(...t){return t.find(e=>e&&typeof e=="object")||{}}function iw(t){const e=t.data&&typeof t.data=="object"?t.data:t,n=nw(e.subscription,e.stripeSubscription,e.currentSubscription,e.customer?.subscriptions?.data?.[0],e.subscriptions?.data?.[0],e.subscriptions?.[0]),i=e.metadata||n.metadata||e.customer?.metadata||{},r=Cr(e.priceId,e.price_id,e.stripePriceId,e.stripe_price_id,n.priceId,n.price_id,n.plan?.id,n.price?.id,n.items?.data?.[0]?.price?.id,n.items?.[0]?.price?.id,n.lines?.data?.[0]?.price?.id),s=Cr(e.status,e.subscriptionStatus,e.subscription_status,n.status,"none"),o=ew(Cr(e.tier,e.plan,e.planId,e.plan_id,e.subscriptionTier,e.subscription_tier,e.product,e.productName,n.tier,n.plan,i.tier,i.plan)),a=Fy.has(String(s).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||tw(r)||(a||l?"professional":"free");return Mn({tier:u,status:s,periodEnd:Cr(e.periodEnd,e.currentPeriodEnd,e.current_period_end,n.current_period_end,n.periodEnd,null),isResolved:!0})}function qs(){return ps[ce.tier]??ps.free}async function rw(){if(z.isVerified&&(!Tt()||pi())&&(await np({force:!0}),zs()),z.isVerified&&!Tt())return Ee("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=lr(),e=qs();if(t>=e)return tp(t,e,{openModal:!0}),!1;const n=Math.floor(e*.8);if(t>=n){const i=e-t;Ee(`${i} run${i===1?"":"s"} remaining this month.`,"warning")}return!0}function id(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function tp(t,e,n={}){nn(!0);const i=document.getElementById("walkthrough-modal");i&&We(i,{restoreFocus:!1});const r=document.getElementById("ready-state");r&&r.classList.add("hidden");const s=document.getElementById("preview-frame-container");s&&(s.style.display="none");const o=document.getElementById("main-stage-container");o&&o.classList.add("visible");const a=document.getElementById("results-view");a&&a.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar");const l=document.getElementById("pipeline-progress");l&&l.classList.remove("visible");const u=document.getElementById("paywall-exhausted");if(!u){Ee(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),di();return}const c=document.getElementById("paywall-exhausted-text");if(c){const f=ce.tier;f==="free"?c.textContent=`You've used all ${e} free generations this month. Upgrade to Pro for 50 generations/month and access to all AI models.`:c.textContent=`You've used all ${e} generations this month on your ${f} plan. Your limit resets next month.`}const d=document.getElementById("paywall-signin-btn");d&&d.classList.toggle("hidden",z.isVerified),u.classList.remove("hidden"),n.openModal&&di()}function za(t){return ce.tier==="free"&&Nr.includes(t)?ms:t}function sw(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const n=ce.tier,r=!(z.isVerified&&!Tt())&&n==="free";Array.from(e.options).forEach(o=>{const a=Gt(o.value),l=Nr.includes(o.value);o.textContent=l&&r?`${a} (PRO)`:a,o.disabled=!1}),r&&Nr.includes(e.value)&&(e.value=ms),e.disabled=!1,qu.has(e)||(e.addEventListener("change",()=>{Tt()&&ce.tier==="free"&&Nr.includes(e.value)&&(e.value=ms,di()),qa(e.value),kl()}),qu.add(e));let s=document.getElementById("model-selector-free-notice");r?(s||(s=document.createElement("p"),s.id="model-selector-free-notice",s.className="text-xs text-gray-400 mt-1",t.appendChild(s)),s.innerHTML='Free plan — Gemini only. '):s&&s.remove(),qa(e.value)}function Gl(){const t=z.isVerified&&!!z.email,e=t&&pi(),n=!t||Tt(),i=lr(),r=n?i.count:0,s=n?qs():0,o=Math.max(0,s-r),a=`${r} / ${s} runs this month`,l=gl,u=n?ce.tier||"free":null,c=document.getElementById("topbar-credits-count");c&&(e?c.textContent="…":n?c.textContent=String(o):c.textContent="—");const d=document.getElementById("credits-balance");d&&(e?d.textContent="Checking plan…":n?d.textContent=a:d.textContent="Plan check failed");const f=document.getElementById("usage-dialog-tier");f&&(e?f.textContent="Checking…":n?f.textContent=l[u]||"Free":f.textContent="Unavailable");const h=document.getElementById("usage-dialog-status");h&&(e?h.textContent="Verifying your subscription…":n?h.textContent="Runs reset at the start of each month.":h.textContent="Could not verify your subscription. Try again or sign out.");const p=document.getElementById("usage-counter");if(p)if(e&&t)p.textContent="Checking plan…",p.className="text-xs text-gray-500";else if(!n&&t)p.textContent="Plan check failed",p.className="text-xs text-red-600 font-medium";else{p.textContent=a;const g=s>0?r/s:0;p.className=g>=1?"text-xs text-red-600 font-medium":g>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500"}if(!t){const g=document.getElementById("guest-usage-text");if(g){const m=ep(),v=m.month===gn()?m.count??0:0;g.textContent=`${v} / ${ps.free} generations used`}}ow()}function ow(){if(!(z.isVerified&&!!z.email))return;const e=pi(),n=Tt(),i=lr(),r=n?i.count:0,s=n?qs():0,o=Math.max(0,s-r),a=n?ce.tier||"free":null,l={free:"Free",professional:"Pro",power:"Power"}[a]||"Free",u=z.email||"",c=u.split("@")[0]||u,d=document.getElementById("acct-avatar");d&&(d.textContent=(u[0]||"?").toUpperCase());const f=document.getElementById("acct-name");f&&(f.textContent=c||"—");const h=document.getElementById("acct-plan-tier"),p=document.getElementById("acct-plan-price"),g=document.getElementById("acct-plan-note"),m=document.getElementById("acct-renewal");if(h&&(h.textContent=e?"Checking…":n?l:"Plan unavailable"),p)if(e)p.textContent="—";else if(!n)p.textContent="—";else if(a==="free")p.textContent="$0 / month";else{const E=Oi(Ni[a]??0,Cl());p.textContent=`${E} / month`}if(g&&(e?g.textContent="Verifying your subscription…":n?a==="free"?g.textContent="No subscription. Upgrade for more generations.":g.textContent="billed monthly through Stripe":g.textContent="Could not verify your subscription. Check billing or sign out."),m){const E=Date.parse(ce.periodEnd||""),P=n&&a!=="free"&&!!ce.periodEnd&&!Number.isNaN(E);if(e)m.textContent="";else if(!n)m.textContent="";else if(a==="free")m.textContent="";else if(P){const $=new Date(E).toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"});m.textContent=`Renews ${$} · reset at the start of each month.`}else m.textContent="Renewal date is not available for this period."}const v=document.getElementById("acct-left-count"),S=document.getElementById("acct-left-limit"),b=document.getElementById("acct-reset-note");v&&(v.textContent=e?"…":n?String(o):"—"),S&&(S.textContent=e?"…":n?String(s):"—"),b&&(e?b.textContent="Checking plan…":n?b.textContent="Runs reset at the start of each month.":b.textContent="Plan check failed. Refresh or manage billing.");const _=document.getElementById("acct-used-count"),x=document.getElementById("acct-meter-fill"),I=document.getElementById("acct-meter-meta"),T=document.getElementById("acct-meter-track");if(_&&(_.textContent=e?"…":n?String(r):"—"),x){const E=n&&s>0?Math.min(100,Math.round(r/s*100)):0;x.style.width=`${E}%`}if(I)if(e)I.textContent="Checking…";else if(!n)I.textContent="Plan check failed";else if(s===0)I.textContent=`${r} of ${s}`;else{const E=Math.round(r/s*100);I.textContent=`${r} of ${s} · ${E}%`}T&&(e?T.setAttribute("aria-label","Checking usage…"):n?T.setAttribute("aria-label",`${r} of ${s} generations used`):T.setAttribute("aria-label","Usage unavailable")),vt()}function un(){if(Gl(),z.isVerified&&(pi()||!Tt())){id();return}const{count:t}=lr(),e=qs();t>=e&&!y.isRunning?tp(t,e):id()}function aw(){Gl()}async function np(t={}){const e=t.force===!0;if(!z.isVerified||!z.sessionToken){ce=Mn({isResolved:!0});return}ce={...ce,isLoading:!0,error:null};const n=localStorage.getItem(gs);if(!e&&n)try{const{data:i,email:r,ts:s,version:o}=JSON.parse(n);if(o===zu&&r===z.email&&Date.now()-s<300*1e3){ce={...i,isLoading:!1,isResolved:i.isResolved!==!1};return}}catch(i){console.warn("Failed to parse subscription cache:",i,"| raw value:",n)}try{const r=await(await fetch(`${_t}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:z.sessionToken,user_id:ft.userId})})).json();if(r.error){if(["unauthorized","invalid session","expired session"].some(o=>String(r.error).toLowerCase().includes(o))){Jh(),Vl();return}ce=Mn({isResolved:!1,error:r.error});return}ce=iw(r),localStorage.setItem(gs,JSON.stringify({version:zu,data:ce,email:z.email,ts:Date.now()}))}catch(i){console.error("fetchSubscription failed:",i),ce={...ce,isLoading:!1,isResolved:!1,error:i.message}}}function ip(){localStorage.removeItem(gs)}async function lw(t){if(!z.isVerified||!z.sessionToken){rp(),Ws();return}if(!Eh[t]){Ee("Invalid plan selected.","error");return}const e=document.getElementById(`checkout-btn-${t}`);e&&(e.disabled=!0,e.textContent="Redirecting…");try{const i=await(await fetch(`${_t}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:z.sessionToken,currency:Cl()})})).json();if(i.error||!i.url)throw new Error(i.error||"Failed to create checkout session");const{url:r}=i;window.location.href=r}catch(n){console.error("startCheckout failed:",n),e&&(e.disabled=!1,e.textContent="Subscribe"),Ee("Could not start checkout. Please try again.","error")}}async function cw(t){if(!z.isVerified||!z.sessionToken){Ws();return}const e=t||document.getElementById("manage-billing-btn"),n=e?e.textContent:"";e&&(e.disabled=!0,e.textContent="Loading…");try{const r=await(await fetch(`${_t}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:z.sessionToken})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to open billing portal");const{url:s}=r;window.location.href=s}catch(i){console.error("openCustomerPortal failed:",i),e&&(e.disabled=!1,e.textContent=n),Ee("Could not open billing portal. Please try again.","error")}}const Es=new Set;function uw(){Es.forEach(t=>t.abort()),Es.clear()}async function Ss(t,e,n,i={},r=[]){const o=new AbortController;Es.add(o);let a=!1;const l=setTimeout(()=>{a=!0,o.abort()},12e4);try{const u=await fetch(ky,{method:"POST",headers:{"Content-Type":"application/json",...ft.token?{Authorization:`Bearer ${ft.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:ft.userId,step:t,model:e,prompt:n,images:r,context:i})}),c=await u.text();let d={};try{d=c?JSON.parse(c):{}}catch{d={}}if(u.status===429){d.serverCount!==void 0&&(localStorage.setItem(Fn,JSON.stringify({count:d.serverCount,month:gn()})),un());const p=new Error(d.message||"Monthly usage limit reached. Upgrade to continue.");throw p.isUsageLimit=!0,p.pipelineStep=t,p}const f=wv(d,t);if(f)throw f;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(d),"content type:",typeof d.content),!u.ok)throw new Error(`${d.message||d.error||"BuildShip pipeline error"} (HTTP ${u.status})`);if(t==="generator")if(d.usage_status==="success"&&Number.isFinite(d.usage_count)){const p=gn();(d.usage_month||p)===p&&(localStorage.setItem(Fn,JSON.stringify({count:d.usage_count,month:p})),un())}else Q0(),un();let h=d.output||d.content;if(!h){const p=c?` (body: ${c.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${p}`)}return Array.isArray(h)&&(h=h.map(p=>typeof p=="string"?p:p.text||"").join("")),typeof h!="string"&&(h=JSON.stringify(h)),h}catch(u){if(u.name==="AbortError"){if(a)throw new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`);const c=new Error(`BuildShip ${t} request cancelled`);throw c.isPipelineCancel=!0,c}throw u instanceof TypeError?new Error(`BuildShip unreachable: ${u.message}`):u}finally{clearTimeout(l),Es.delete(o)}}let Va=!1;function dw(){const e=new URLSearchParams(window.location.search).get("checkout");return e==="success"?(window.history.replaceState({},"",window.location.pathname+window.location.hash),ip(),Va=!0):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname+window.location.hash),Ee("Checkout cancelled.","info")),e}function fw(){if(!Va)return;Va=!1;const t=ce.tier!=="free";Ee(t?"Subscription active! Your plan is live.":"Checkout complete — confirming your subscription. Check Manage billing if it does not update.",t?"success":"info")}function zs(){const t=z.isVerified&&!!z.email,e=ce.tier,n=t&&pi(),i=!t||Tt(),r=document.getElementById("subscription-tier-badge");if(r){const a=gl,l={free:"bg-gray-100 text-gray-600",professional:"bg-indigo-100 text-indigo-700",power:"bg-purple-100 text-purple-700",unresolved:"bg-red-50 text-red-600"};r.textContent=n?"Checking…":i?a[e]||"Free":"Plan unavailable",r.className=`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${i?l[e]||l.free:l.unresolved}`}const s=document.getElementById("upgrade-prompt");s&&s.classList.toggle("hidden",!t||n||!i||e!=="free");const o=document.getElementById("manage-billing-btn");o&&o.classList.toggle("hidden",!t||n||i&&e==="free"),hw(i?e:null),sw(),kl(),un(),Ep()}function hw(t){const e=["bg-gray-100","text-gray-500","cursor-default"];Object.entries({professional:{btnId:"checkout-btn-professional",defaultText:"Subscribe"},power:{btnId:"checkout-btn-power",defaultText:"Subscribe"}}).forEach(([r,{btnId:s,defaultText:o}])=>{const a=document.getElementById(s);a&&(r===t?(a.disabled=!0,a.textContent="Current plan",a.classList.add(...e)):(a.disabled=!1,a.textContent=o,a.classList.remove(...e)))});const i=document.getElementById("free-tier-current");i&&i.classList.toggle("hidden",t!=="free")}function pw(){document.querySelectorAll(".pm-card[data-tier]").forEach(t=>{const e=t.dataset.tier,n=av[e];if(!n)return;const i=t.querySelector("ul.pm-features");if(i){i.innerHTML="";for(const r of n){const s=document.createElement("li");s.textContent=r,i.appendChild(s)}}})}function Ga(){const t=Cl(),e=document.getElementById("pro-price"),n=document.getElementById("power-price"),i=document.getElementById("plans-pro-price"),r=document.getElementById("plans-power-price"),s=document.getElementById("pro-price-note"),o=document.getElementById("power-price-note"),a=document.getElementById("plans-pro-price-note"),l=document.getElementById("plans-power-price-note");e&&(e.textContent=Oi(Ni.professional,t)),n&&(n.textContent=Oi(Ni.power,t)),i&&(i.textContent=Oi(Ni.professional,t)),r&&(r.textContent=Oi(Ni.power,t));const u="billed monthly";s&&(s.textContent=u),o&&(o.textContent=u),a&&(a.textContent=u),l&&(l.textContent=u)}function di(){Ga();const t=document.getElementById("pricing-modal");t&&He(t),Uy().then(()=>Ga())}function rp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&We(e)}function Ee(t,e="info"){const n={success:"bg-green-600 text-white",error:"bg-red-600 text-white",warning:"bg-amber-500 text-white",info:"bg-gray-800 text-white"},i=document.createElement("div");i.className=`fixed bottom-6 left-1/2 -translate-x-1/2 px-5 py-3 rounded-lg text-sm font-medium shadow-lg z-50 transition-opacity duration-300 ${n[e]||n.info}`,i.textContent=t,document.body.appendChild(i),setTimeout(()=>{i.style.opacity="0",setTimeout(()=>i.remove(),300)},3500)}document.addEventListener("DOMContentLoaded",async()=>{rv(),hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),gw(),window.__heroField=X_(),window.__pipelineLogo=ny(),xh=Sy({onSubmit:or}),Oa=(async()=>{try{await H0(),dw(),await np()}catch(n){console.warn("Startup auth/subscription initialization failed:",n)}})(),await Oa,fw(),zs(),Ga(),pw(),await v0(),f0();const t=document.getElementById("flutterflow-endpoint-select");if(t){const n=yt();t.value=n}Nh(),Qh();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{en===2&&e.value.trim().length>0&&(Tl(),Ns())}),e.addEventListener("blur",()=>{const n=document.getElementById("walkthrough-modal");en===2&&n&&He(n)}),e.addEventListener("keydown",n=>{if(n.key==="Tab"){const i=document.getElementById("walkthrough-modal");en===2&&i&&setTimeout(()=>{He(i)},100)}})),window.addEventListener("commitStateChange",n=>{const{state:i}=n.detail;i===ee.PREPARING||i===ee.VALIDATING||i===ee.PUSHING?(Oe.phaseId||up(),sd(i)):(i===ee.SUCCESS||i===ee.ERROR)&&(sd(i),setTimeout(Jl,1e3))}),ic()});function gw(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function mw(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Nn),document.addEventListener("keydown",Nn))}function Nn(){const t=document.getElementById("preview-frame-container"),e=document.getElementById("main-stage-container"),n=document.getElementById("ready-state");t&&(t.style.display="none"),e&&e.classList.add("visible"),n&&n.classList.remove("hidden");const i=document.getElementById("welcome-video-player");i&&i.removeEventListener("click",Nn),document.removeEventListener("keydown",Nn),Nh()}let zi=null;async function vw(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++Ju,n=()=>e===Ju,i=await Te("flutterflow"),r=await Te("flutterflow_project_id");if(n()){if(!i){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const o=await new hi(i,"","main",yt()).listProjects();if(!n())return;if(!o||o.length===0){t.innerHTML='';return}t.innerHTML='',o.forEach(a=>{const l=document.createElement("option");l.value=a.id||a.projectId||"",l.textContent=a.name||a.projectName||`Project ${a.id}`,t.appendChild(l)}),r&&(t.value=r)}catch(s){if(!n())return;console.error("Failed to load projects for deploy:",s),t.innerHTML=''}}}function _w(){return document.getElementById("confirm-project-select")?.value?.trim()||null}function Kl(t,e,n,i=null){zi={codeInfo:t,checks:e,deps:n,bundlePlan:i},document.getElementById("confirm-file-name").textContent=t.fileName,document.getElementById("confirm-artifact-type").textContent=t.artifactType,document.getElementById("confirm-file-size").textContent=`${(t.content.length/1024).toFixed(1)} KB`,document.getElementById("confirm-line-count").textContent=i?`${i.fileEntries.length} files`:t.content.split(` -`).length,vw();const r=document.getElementById("confirm-deps-list"),s=document.getElementById("confirm-deps-section");n&&Object.keys(n).length>0?(r.innerHTML=Object.entries(n).map(([u,c])=>{const d=c?`at least ${Qt(c)}`:"version resolved from your project";return`
  • • ${Qt(u)}: ${d}
  • `}).join(""),s.classList.remove("hidden")):s.classList.add("hidden");const o=document.getElementById("confirm-warnings-list"),a=document.getElementById("confirm-warnings-section");e.warnings&&e.warnings.length>0?(o.innerHTML=e.warnings.map(u=>`
  • • ${Qt(u)}
  • `).join(""),a.classList.remove("hidden")):a.classList.add("hidden"),document.getElementById("confirm-code-preview").textContent=t.content,document.getElementById("code-preview-content").classList.add("hidden"),document.getElementById("code-preview-chevron").style.transform="rotate(0deg)";const l=document.getElementById("commit-confirm-modal");l&&He(l)}function sp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&We(e),zi=null}function yw(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&We(e);const n=["success-message","success-project-id","success-file-name","success-artifact-type","success-time","success-size"];for(const s of n){const o=document.getElementById(s);o&&(o.textContent="")}const i=document.getElementById("success-warnings-section");i&&i.classList.add("hidden");const r=document.getElementById("success-warnings-list");r&&(r.innerHTML="")}function op(t){const e=(m,v)=>{const S=document.getElementById(m);S&&(S.textContent=v||"")},n=t.metadata?.fileName||"",i=t.metadata?.projectId||"",r=t.metadata?.artifactType||"",s=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",i),e("success-file-name",n),e("success-artifact-type",r),e("success-time",s),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&i&&(u.href=`https://app.flutterflow.io/project/${i}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),f=t.unverified||[],h=t.approximate||[],p=t.warnings||[];(p.length>0||f.length>0||h.length>0)&&c&&d&&(d.innerHTML=[...f.map(m=>`
  • Not verified before deploying: ${q(String(m))}
  • `),...h.map(m=>`
  • Verified approximately: ${q(String(m))}
  • `),...p.map(([m,v])=>`
  • ${q(m)}: ${q(String(v))}
  • `)].join(""),c.classList.remove("hidden"));const g=document.getElementById("commit-success-modal");g&&He(g)}function ap(t){Jl(),B0(t),Yl(t,{heading:"Deploy failed",title:"FlutterFlow refused this deploy — nothing was confirmed written.",guidance:"Review the error and any per-file outcomes above, fix them in your code or in FlutterFlow, then deploy again. A refusal is definitive: no part of this deploy was applied, so retrying is safe once the problem is fixed."})}function Yl(t,{heading:e,title:n,guidance:i}){const r=t.targetIdentity||{},s=document.getElementById("commit-terminal-modal");if(!s)return!1;const o=(h,p)=>{const g=document.getElementById(h);g&&(g.textContent=p||"")};o("terminal-heading",e),o("terminal-title",n),o("terminal-message",t.error||t.message||"");const a=document.getElementById("terminal-identity-list");if(a){const h=[["Project",r.projectId||t.metadata?.projectId],["Endpoint",r.endpoint],["File",r.fileName||t.metadata?.fileName],["Artifact",r.artifactType||t.metadata?.artifactType]];a.innerHTML=h.map(([p,g])=>`
    ${q(p)}:${q(String(g??"—"))}
    `).join("")}const l=document.getElementById("terminal-file-outcomes");let u=t.errorMap;u&&!(u instanceof Map)&&(u=new Map(Object.entries(u))),l&&u&&u.size>0?(l.innerHTML=[...u.entries()].map(([h,p])=>`
  • ${q(h)}: ${q(El(p))}
  • `).join(""),l.classList.remove("hidden")):l&&l.classList.add("hidden");const c=document.getElementById("terminal-guidance");c&&(c.innerHTML=i);const d=document.getElementById("terminal-open-ff-link"),f=r.projectId||t.metadata?.projectId;return d&&(d.href=f?`https://app.flutterflow.io/project/${f}`:"https://app.flutterflow.io/"),He(s),!0}function lp(t){Yl(t,{heading:"Deploy partially applied",title:"Some custom classes reached FlutterFlow, but the deploy did not fully complete.",guidance:"The custom classes the runner confirmed are already in your project and are not lost. Review the per-file errors above, fix them in FlutterFlow or regenerate, then deploy again. Open the project to see exactly what landed."})}function cp(t){Yl(t,{heading:"Deploy outcome not yet known",title:"This browser stopped waiting before the FlutterFlow server reported a result.",guidance:"The deploy may still be finishing on the server — it was not cancelled. Open your FlutterFlow project and confirm whether the class landed before retrying, so you do not push a duplicate or build on top of an unknown state."})}function ww(t){t&&t.target!==t.currentTarget||We(document.getElementById("commit-terminal-modal"))}function bw(){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 rd={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}},Ew=[{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..."}],Oe={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&&(Eu(e,!0,"Deploying to FlutterFlow"),He(e)),this.set("prepare")},set(t,e=null){if(!(!rd[t]||t===this.phaseId)){if(!this.sequence.includes(t)){const n=this.sequence.indexOf("package");this.sequence.splice(n===-1?this.sequence.length:n,0,t)}this.phaseId=t,this.phaseStartedAt=Date.now(),this.substatus=e,this.liveSubstatus=!1,this.render(),this.timer&&clearInterval(this.timer),t!=="done"&&(this.timer=setInterval(()=>this.render(),500))}},setSubstatus(t){t&&(this.liveSubstatus=!0,this.substatus=t,this.render())},render(){const t=rd[this.phaseId];if(!t)return;const e=(Date.now()-this.phaseStartedAt)/1e3,n=t.start+(t.end-t.start)*(1-Math.exp(-e/25));if(this.phaseId==="provision"&&!this.liveSubstatus){const o=Ew.filter(a=>e>=a.after).pop();o&&(this.substatus=o.text)}const i=this.sequence.indexOf(this.phaseId),s=[`Step ${i===-1?1:i+1} of ${this.sequence.length}`];e>=5&&s.push(Sw(e)),dp(this.phaseId==="done"?100:n,t.message,s.join(" · "),this.substatus)},stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.phaseId=null;const t=document.getElementById("commit-progress-overlay");t&&(Eu(t,!1),We(t,{force:!0,restoreFocus:!1}))}};function Sw(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 up(t){Oe.start(t)}function Jl(){Oe.stop()}function dp(t,e,n,i=null){const r=document.getElementById("commit-progress-bar"),s=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");r&&(r.style.width=`${Math.round(t*10)/10}%`),s&&(s.textContent=e),o&&(o.textContent=n),a&&(a.textContent=i||"",a.classList.toggle("hidden",!i))}function sd(t){const e={[ee.PREPARING]:"prepare",[ee.VALIDATING]:"validate",[ee.PUSHING]:"project",[ee.SUCCESS]:"done"};if(t===ee.ERROR){Oe.timer&&clearInterval(Oe.timer),Oe.timer=null,dp(100,"Failed","Error occurred");return}const n=e[t];n&&Oe.set(n)}function xw(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===J.CODE_FILE):t.codeInfo?.codeType===J.CODE_FILE}let fp=!1;function hp(t){fp=t;const e=document.querySelector("#commit-confirm-modal button[data-deploy-confirm]");e&&(e.disabled=t),[...document.querySelectorAll("[data-deploy-start]"),...document.querySelectorAll("#btn-deploy-to-ff")].forEach(i=>{i.disabled=t})}function od(t){Jl(),hp(!1);const e=_h(t);e===Xe.COMMITTED?op(t):e===Xe.PARTIAL?lp(t):e===Xe.UNCONFIRMED?cp(t):ap(t)}async function Iw(){if(!zi){console.error("No pending commit data");return}if(fp){console.warn("Deploy already in flight; ignoring duplicate confirm.");return}const t=zi;if(zi=null,qi=_w(),sp(),hp(!0),up({withProvisioning:xw(t)}),t.bundlePlan){const o=await C0(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});qi=null,od(o);return}const{codeInfo:e}=t,{artifactType:n,artifactName:i,fileName:r}=Oh(),s=await k0(e.content,{artifactType:n,artifactName:i,fileName:r,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});qi=null,od(s)}window.runThinkingPipeline=or;window.toggleStep=F0;window.toggleSection=P0;window.selectWorkflowStep=nt;window.copyCode=R0;window.retryWithDifferentModel=L0;window.openApiKeysModal=Rl;window.closeApiKeysModal=Mh;window.openComposerSettings=t0;window.closeComposerSettings=n0;window.walkthroughConnectAccount=e0;window.closeWalkthroughModal=r0;window.openWalkthroughModal=i0;window.advanceWalkthrough=Tl;window.commitToFlutterFlow=I0;function kw(){const t=document.getElementById("pipeline-input");t&&t.focus()}function Cw(){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=kw;window.openModelSelector=Cw;window.handlePromptImageSelect=Dy;window.removePromptImage=jy;window.saveApiKeys=a0;window.validateFlutterFlowConnection=Ml;window.clearAllApiKeys=l0;window.toggleKeyVisibility=p0;window.handleWelcomeVideoEnd=mw;window.dismissWelcomeVideo=Nn;window.initiateCommitToFlutterFlow=N0;window.updateFlutterFlowCredentialStatus=D0;window.openCommitConfirmModal=Kl;window.closeCommitConfirmModal=sp;window.closeCommitSuccessModal=yw;window.closeCommitTerminalModal=ww;window.showCommitPartialModal=lp;window.showCommitUnconfirmedModal=cp;window.showCommitSuccessModal=op;window.showCommitFailureModal=ap;window.toggleCodePreview=bw;window.confirmCommitToFlutterFlow=Iw;window.runRefinement=Vh;window.regenerateFromPastedErrors=Gh;window.clearErrorInput=M0;window.setFlutterFlowEndpoint=Qy;window.getFlutterFlowEndpoint=yt;window.commitProgress=Oe;window.openSignInModal=Ws;window.closeSignInModal=Xh;window.handleMagicLinkRequest=q0;window.handleSignOut=z0;window.handleSendNewLink=K0;window.handleClearCache=Y0;window.handleDeleteAccount=J0;window.closeDeleteUnavailableModal=Z0;window.startCheckout=lw;window.openCustomerPortal=cw;window.openPricingModal=di;window.closePricingModal=rp;let jr=null,pp=null,On={1:"pending",2:"pending",3:"pending"},Zl=1,Xl=null;const Vs={1:"Prompt Architect",2:"Code Generator",3:"Code Review"},Aw={1:"Understanding your prompt",2:"Generating Dart code",3:"Running the code audit"},Pw={1:"Prompt understood",2:"Dart code generated",3:"Code audit complete"};function Gs(){return y.runId+=1,y.runId}function re(t){return t===void 0||t===y.runId}function Fw(){y.runId+=1}function Ql(t){return document.getElementById(`pdot-${t}`)}function Ka(t){const e=document.getElementById("btn-run-pipeline")||document.getElementById("hero-send");e&&(e.disabled=t,e.classList.toggle("is-busy",t),t?e.setAttribute("aria-busy","true"):e.removeAttribute("aria-busy"))}function Ks(t){const e=document.getElementById("pipeline-progress");e&&(e.dataset.runState=t)}function Rn(t,e){On[t]=e;const n=Ql(t);if(!n)return;n.dataset.state=e,n.disabled=e==="pending"||e==="skipped";const i=Vs[t],r={pending:"not started",active:"in progress",done:"complete",failed:"failed",skipped:"not run"};n.setAttribute("aria-label",`Step ${t} of 3, ${i}: ${r[e]||e}`),e==="active"?n.setAttribute("aria-current","step"):n.removeAttribute("aria-current")}function Rw(){return[1,2,3].filter(t=>On[t]==="done").length}function Ys(){const t=document.getElementById("pipeline-progress-fill");t&&(t.style.width=`${Rw()/3*100}%`);const e=document.getElementById("progress-stage-count");e&&(e.textContent=`Step ${Zl} of 3`)}function Js(t,{done:e=!1}={}){const n=document.getElementById("progress-title-text"),i=document.getElementById("progress-substep-text"),r=On[t],s=e||r==="done";if(n&&(n.textContent=s?Pw[t]:Aw[t]),i){const o=s?" — complete":r==="failed"?" — stopped":"";i.textContent=`Step ${t} of 3 — ${Vs[t]}${o}`}}function Tw(t){On[t]==="pending"||On[t]==="skipped"||(Xl=t,[1,2,3].forEach(e=>{const n=Ql(e);n&&n.setAttribute("aria-pressed",String(e===t))}),Js(t))}function ec(){Xl=null,[1,2,3].forEach(t=>{const e=Ql(t);e&&e.removeAttribute("aria-pressed")})}function gp(t){const e=document.getElementById("pipeline-note");e&&(e.textContent=t||"",e.hidden=!t)}function $w(t,e,n){re(n)&&gp(`${Gt(t)} did not answer. Continuing on ${Gt(e)}.`)}function tc(){const t=document.getElementById("pipeline-failure");if(!t)return;t.hidden=!0;const e=document.getElementById("pipeline-failure-actions");e&&e.replaceChildren()}const Mw=1120;function Lw(){const t=getComputedStyle(document.documentElement).getPropertyValue("--t-morph").trim(),e=Number.parseFloat(t);return Number.isFinite(e)&&e>0?e:Mw}let Qn=null,Ur=null;function Nw(){return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0}function dn(){if(Ur){try{Ur.cancel()}catch{}Ur=null}Qn&&(Qn.remove(),Qn=null),window.removeEventListener("resize",dn)}function mp(t,e){if(dn(),Nw()||!t||!e||!document.body||typeof Element.prototype.animate!="function")return;const n=t.getBoundingClientRect(),i=e.getBoundingClientRect();if(!n.width||!n.height||!i.width||!i.height)return;const r=document.createElement("div");r.className="composer-morph",r.setAttribute("aria-hidden","true"),r.style.cssText=`left:${i.left}px;top:${i.top}px;width:${i.width}px;height:${i.height}px;opacity:0;`,document.body.appendChild(r);const s=n.left+n.width/2-(i.left+i.width/2),o=n.top+n.height/2-(i.top+i.height/2),a=n.width/i.width,l=n.height/i.height,u=`translate(${s}px,${o}px) scale(${a},${l})`,c=r.animate([{transform:u,opacity:0,offset:0,easing:"cubic-bezier(.2,0,0,1)"},{transform:u,opacity:1,offset:.14,easing:"cubic-bezier(.4,0,.2,1)"},{transform:`translate(${s}px,${o}px) scale(${a*.93},${l*.93})`,opacity:1,offset:.28,easing:"cubic-bezier(.32,1.38,.5,1)"},{transform:"translate(0px,0px) scale(1,1)",opacity:1,offset:1}],{duration:Lw(),fill:"both"});Qn=r,Ur=c,window.addEventListener("resize",dn),c.onfinish=()=>{if(Qn!==r)return;const d=r.animate([{opacity:1},{opacity:0}],{duration:260,fill:"forwards"});d.onfinish=()=>{Qn===r&&dn()}}}function Ow(){const e=document.getElementById("composer")?.getBoundingClientRect();e&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{mp({getBoundingClientRect:()=>e},document.getElementById("main-stage-container"))})})}function Bw(){mp(document.getElementById("pipeline-progress"),document.getElementById("main-stage-container"))}window.addEventListener("hashchange",dn);window.addEventListener("popstate",dn);function Zs(t={}){const{prompt:e=null,runId:n}=t;if(!re(n))return;Qs(),nn(!0);const i=document.getElementById("pipeline-progress"),r=document.getElementById("results-view"),s=document.getElementById("ready-state");if(s&&s.classList.add("hidden"),r&&r.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),i&&i.classList.add("visible"),Ks("running"),e!==null){const a=document.getElementById("pipeline-submitted-prompt");a&&(a.textContent=e)}pp=Date.now();const o=document.getElementById("progress-elapsed");o&&(o.textContent="0s"),On={1:"pending",2:"pending",3:"pending"},ec(),tc(),gp(""),[1,2,3].forEach(a=>Rn(a,"pending")),Ft(1,n),Dw()}function Ft(t,e){re(e)&&(Zl=t,ec(),[1,2,3].forEach(n=>{n===t?Rn(n,"active"):nt&&Rn(n,"pending")}),Js(t),Ys())}function tn(t,e){re(e)&&(Rn(t,"done"),Xl===null&&Js(t,{done:!0}),Ys())}function vp(t,{stage:e=1,runId:n,retry:i=_p}={}){if(!re(n))return;Xs(),Qs(),dn(),Ks("failed"),nn(!0);const r=document.getElementById("pipeline-progress");r&&r.classList.add("visible");const s=document.getElementById("results-view");s&&s.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),Rn(e,"failed"),[1,2,3].forEach(p=>{p>e&&Rn(p,"pending")}),Zl=e,ec(),Js(e),Ys();const o=wh(t),a=document.getElementById("pipeline-failure"),l=document.getElementById("pipeline-failure-title"),u=document.getElementById("pipeline-failure-message"),c=document.getElementById("pipeline-failure-hint"),d=document.getElementById("pipeline-failure-actions");if(!a||!l||!u||!d)return;if(a.dataset.kind=o.kind,l.textContent=`${Vs[e]}: ${o.title}`,u.textContent=o.message,c){const p=o.detail&&o.detail!==o.message?o.detail:"";c.textContent=p,c.hidden=!p}d.replaceChildren();const f=[o.canUpgrade&&{id:"upgrade",label:"View plans",variant:"primary",onClick:()=>di()},o.canRetry&&{id:"retry",label:"Retry",variant:o.canUpgrade?"secondary":"primary",onClick:i},o.canEdit&&{id:"edit",label:"Edit prompt",variant:"secondary",onClick:Ya}].filter(Boolean);!o.canEdit&&!o.canRetry&&f.push({id:"edit",label:"Back to prompt",variant:"secondary",onClick:Ya}),f.forEach(p=>{const g=document.createElement("button");g.type="button",g.textContent=p.label,g.dataset.action=p.id,g.dataset.variant=p.variant,g.addEventListener("click",p.onClick),d.appendChild(g)}),a.hidden=!1;const h=d.querySelector("button");h&&h.focus({preventScroll:!0})}function Ya(){Fw(),uw(),y.isRunning=!1,Ka(!1),rn(),Ks("settled"),dn(),Xs(),Qs(),tc();const t=document.getElementById("pipeline-progress");t&&t.classList.remove("visible"),nn(!1);const e=document.getElementById("pipeline-input");e&&(y.submittedPrompt&&(e.value=y.submittedPrompt,e.dispatchEvent(new Event("input",{bubbles:!0}))),e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length))}function _p(){const t=document.getElementById("pipeline-input");t&&y.submittedPrompt&&(t.value=y.submittedPrompt,t.dispatchEvent(new Event("input",{bubbles:!0}))),Ne=y.submittedImages.slice(),cn(),tc(),or()}function Dw(){Xs(),jr=setInterval(()=>{const t=(Date.now()-pp)/1e3,e=document.getElementById("progress-elapsed");e&&(e.textContent=`${Math.floor(t)}s`)},250)}function Xs(){jr&&(clearInterval(jr),jr=null)}let Vi=null;function Qs(){Vi&&(clearTimeout(Vi),Vi=null)}function cr(){Xs(),Qs(),Ks("settled"),Ys();const t=document.getElementById("pipeline-progress-fill");Vi=setTimeout(()=>{Vi=null;const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function Tn(t,e=""){const n={pass:'',warning:'',fail:'',info:''};return``}function yp(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function jw(){return f_({bundle:y.artifactBundle,reviewResult:y.step3Result})}function Uw(t){return` +`;const o=nh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:s});Zs({runId:i}),Ft(2,i),nt(2),Ae(2,!0);const a=await Us(o,n,[],i);if(!re(i))return;y.step2Result=a,Bs(),tn(2,i);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),nt(3),Ft(3,i),Ae(3,!0);const c=await Hs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,Ds(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const f=Ls(y.step3Result);ur(u,f)}catch(s){if(console.error("Regeneration failed:",s),!re(i))return;const o=Ms(s,{architect:2,generator:2,review:3});s.isUsageLimit&&un(),nt(o),Ae(o,!1),yp(s,{stage:o,runId:i,retry:()=>Jh(t,e)}),bs(o,"error")}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function j0(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const n=await Te("flutterflow"),i=await Te("flutterflow_project_id");n&&i?(t.className="w-2 h-2 rounded-full bg-green-500",e.textContent="FlutterFlow credentials configured",e.className="text-green-600"):n||i?(t.className="w-2 h-2 rounded-full bg-yellow-500",e.textContent="FlutterFlow credentials incomplete",e.className="text-yellow-600"):(t.className="w-2 h-2 rounded-full bg-red-500",e.textContent="FlutterFlow credentials not configured",e.className="text-red-600")}async function Zh(t){try{const e=await fetch(`${_t}/auth/send-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:t})});if(!e.ok)throw new Error(`Failed to send magic link: HTTP ${e.status}`);return e.json()}catch(e){throw console.error("sendMagicLink failed:",{email:t,message:e.message,stack:e.stack}),e}}async function U0(t){try{const n=await(await fetch(`${_t}/auth/verify-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})})).json();if(n.error||!n.email||!n.sessionToken)throw new Error(n.error||"Invalid or expired link");return n}catch(e){throw console.error("verifyMagicLink failed:",{message:e.message,stack:e.stack}),e}}async function H0(t){try{const e=await fetch(`${_t}/auth/refresh-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:t})});if(!e.ok)return console.error("refreshSession: non-OK response",{url:`${_t}/auth/refresh-session`,status:e.status}),null;const n=await e.json();return n.error||!n.email||!n.sessionToken?(console.warn("refreshSession: validation failed",{error:n.error,hasEmail:!!n.email,hasToken:!!n.sessionToken}),null):n}catch(e){return console.error("refreshSession: fetch failed",{url:`${_t}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function td(t,e){const n=Qh(),i=(z.email||n.email)!==t;z.email=t,z.sessionToken=e,z.isVerified=!0,ce=Mn({isLoading:!0}),localStorage.setItem(hs,JSON.stringify({email:t,sessionToken:e})),i&&sp()}function Xh(){z.email=null,z.sessionToken=null,z.isVerified=!1,ce=Mn({isResolved:!0}),localStorage.removeItem(hs),localStorage.removeItem(gs)}function Qh(){try{const t=localStorage.getItem(hs);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(hs),{email:null,sessionToken:null}}}async function W0(){const e=new URLSearchParams(window.location.search).get("token");if(e){window.history.replaceState({},"",window.location.pathname+window.location.hash);try{const{email:n,sessionToken:i}=await U0(e);td(n,i),ep();const r=nd();r&&!window.location.hash&&(window.location.hash=r)}catch(n){nd();const i=n.message||"Sign-in link invalid or expired.";Ee(i,"error"),Ws(),Jn(i,"error")}}else{const{email:n,sessionToken:i}=Qh();if(n&&i){const r=await H0(i);r?td(r.email,r.sessionToken):Xh()}}Vl()}function q0(){try{localStorage.setItem(Na,JSON.stringify({hash:window.location.hash||"#home",ts:Date.now()}))}catch(t){console.warn("rememberSignInReturnSurface: failed to persist return surface:",t)}}function nd(){try{const t=localStorage.getItem(Na);if(localStorage.removeItem(Na),!t)return null;const{hash:e,ts:n}=JSON.parse(t);return!e||typeof n!="number"||Date.now()-n>ky?null:e}catch(t){return console.warn("consumeSignInReturnSurface: failed to read return surface:",t),null}}function Ws(){const t=document.getElementById("signin-modal");if(!t)return;q0(),document.getElementById("signin-email-input")?.removeAttribute("aria-invalid"),Jn(""),He(t)}function ep(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&We(e)}function Jn(t,e){const n=document.getElementById("signin-message");n&&(n.textContent=t||"",n.classList.remove("signin-message-success","signin-message-error"),e&&n.classList.add(`signin-message-${e}`))}async function z0(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),n=Fs(t?.value);if(!n||!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(n)||n.length>254){t?.setAttribute("aria-invalid","true"),Jn("Please enter a valid email address.","error");return}t?.removeAttribute("aria-invalid"),e&&(e.disabled=!0,e.textContent="Sending…");const r=uh(n);r&&Jn(r,"error");try{const s=await Zh(n),o=s?.code===ch;t&&!o&&(t.value=""),t?.setAttribute("aria-invalid",String(o)),Jn(dh(s,n),o?"error":"success"),e&&(e.disabled=!1,e.textContent=o?"Send Sign-in Link":"Sent!",o||setTimeout(()=>{e.textContent==="Sent!"&&(e.textContent="Send Sign-in Link")},2500))}catch(s){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:n,err:s}),Jn("Something went wrong. Please try again.","error"),e&&(e.disabled=!1,e.textContent="Send Sign-in Link")}}function V0(){z.email=null,z.sessionToken=null,z.isVerified=!1,ce=Mn({isResolved:!0}),L_({storage:window.localStorage,onIdentityChanged:Vl,onPlanChanged:zs})}const G0=N_({sendLink:Zh,getEmail:()=>z.email||"",onState:K0});function K0(t){const e=document.getElementById("send-new-link-btn"),n=document.getElementById("send-new-link-msg");if(!e||!n)return;if(t.status==="pending"){e.disabled=!0,e.textContent="Sending…",n.className="acct-access-msg",n.textContent="Sending a fresh sign-in link…";return}if(t.status==="sent"){e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg",n.textContent=dh(t.data,z.email||"")||"Link sent — check your email.";return}e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg error";const i=t.error?.message?`Couldn't send a link right now. ${t.error.message}`:"Couldn't send a link right now. Please try again.";n.textContent=i}async function Y0(){await G0()}function J0(){const t=$_(window.localStorage),e=t.length?`Cleared disposable UI caches: ${t.join(", ")}.`:"Nothing disposable to clear.";Ee(`${e} Your run count, identity and stored keys are kept.`,"info")}function Z0(){const t=document.getElementById("delete-unavailable-modal");t&&He(t,{trigger:document.activeElement})}function X0(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("delete-unavailable-modal");e&&We(e)}function Vl(){const t=z.isVerified&&!!z.email,e=document.getElementById("auth-signedout"),n=document.getElementById("auth-signedin"),i=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),n&&n.classList.toggle("hidden",!t),i&&i.classList.toggle("hidden",t);const r=document.getElementById("auth-user-email");r&&(r.textContent=z.email||"");const s=document.getElementById("access-signed-email");s&&(s.textContent=z.email||""),lw(),zs()}async function tp(){try{if(typeof FingerprintJS>"u"){console.warn("resolveIdentity: FingerprintJS not loaded, skipping");return}const e=await(await FingerprintJS.load()).get(),n=e.visitorId,i=await fetch(Fy,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fingerprint:e.visitorId,cookie_id:n})});if(!i.ok)throw new Error(`Identity check HTTP ${i.status}`);const r=await i.json();if(ht.userId=r.user_id,ht.token=r.identity_token||null,ht.status=r.status,ht.resolved=!0,sessionStorage.setItem(Ay,r.user_id),ht.token&&sessionStorage.setItem(Py,ht.token),r.usage_count!==void 0){const s=gn(),a=(r.usage_month||s)===s?r.usage_count:0;localStorage.setItem(Fn,JSON.stringify({count:a,month:s})),un()}console.log(`Identity resolved: ${r.status} (${r.user_id.slice(0,8)}...) usage: ${r.usage_count??"n/a"}`)}catch(t){console.error("resolveIdentity failed:",t)}}let Wo=null;function Q0(t=5e3){return ht.resolved?Promise.resolve():(Wo||(Wo=tp().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([Wo,new Promise(e=>setTimeout(e,t))]))}function np(){const t=gn();try{const e=localStorage.getItem(Fn);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Fn,month:t,err:e}),localStorage.removeItem(Fn),{count:0,month:t}}}function gn(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function lr(){const t=np();return t.month!==gn()?{count:0,month:gn()}:t}function ew(){const e={count:lr().count+1,month:gn()};return localStorage.setItem(Fn,JSON.stringify(e)),e}function pi(){return!!ce.isLoading}function Tt(){return!!ce.isResolved}function tw(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(ps,e)?e:null}function nw(t){return t&&Object.entries(Sh).find(([,e])=>e===t)?.[0]||null}function Cr(...t){return t.find(e=>e!=null&&e!=="")}function iw(...t){return t.find(e=>e&&typeof e=="object")||{}}function rw(t){const e=t.data&&typeof t.data=="object"?t.data:t,n=iw(e.subscription,e.stripeSubscription,e.currentSubscription,e.customer?.subscriptions?.data?.[0],e.subscriptions?.data?.[0],e.subscriptions?.[0]),i=e.metadata||n.metadata||e.customer?.metadata||{},r=Cr(e.priceId,e.price_id,e.stripePriceId,e.stripe_price_id,n.priceId,n.price_id,n.plan?.id,n.price?.id,n.items?.data?.[0]?.price?.id,n.items?.[0]?.price?.id,n.lines?.data?.[0]?.price?.id),s=Cr(e.status,e.subscriptionStatus,e.subscription_status,n.status,"none"),o=tw(Cr(e.tier,e.plan,e.planId,e.plan_id,e.subscriptionTier,e.subscription_tier,e.product,e.productName,n.tier,n.plan,i.tier,i.plan)),a=Ry.has(String(s).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||nw(r)||(a||l?"professional":"free");return Mn({tier:u,status:s,periodEnd:Cr(e.periodEnd,e.currentPeriodEnd,e.current_period_end,n.current_period_end,n.periodEnd,null),isResolved:!0})}function qs(){return ps[ce.tier]??ps.free}async function sw(){if(z.isVerified&&(!Tt()||pi())&&(await rp({force:!0}),zs()),z.isVerified&&!Tt())return Ee("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=lr(),e=qs();if(t>=e)return ip(t,e,{openModal:!0}),!1;const n=Math.floor(e*.8);if(t>=n){const i=e-t;Ee(`${i} run${i===1?"":"s"} remaining this month.`,"warning")}return!0}function id(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function ip(t,e,n={}){nn(!0);const i=document.getElementById("walkthrough-modal");i&&We(i,{restoreFocus:!1});const r=document.getElementById("ready-state");r&&r.classList.add("hidden");const s=document.getElementById("preview-frame-container");s&&(s.style.display="none");const o=document.getElementById("main-stage-container");o&&o.classList.add("visible");const a=document.getElementById("results-view");a&&a.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar");const l=document.getElementById("pipeline-progress");l&&l.classList.remove("visible");const u=document.getElementById("paywall-exhausted");if(!u){Ee(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),di();return}const c=document.getElementById("paywall-exhausted-text");if(c){const f=ce.tier;f==="free"?c.textContent=`You've used all ${e} free generations this month. Upgrade to Pro for 50 generations/month and access to all AI models.`:c.textContent=`You've used all ${e} generations this month on your ${f} plan. Your limit resets next month.`}const d=document.getElementById("paywall-signin-btn");d&&d.classList.toggle("hidden",z.isVerified),u.classList.remove("hidden"),n.openModal&&di()}function za(t){return ce.tier==="free"&&Nr.includes(t)?ms:t}function ow(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const n=ce.tier,r=!(z.isVerified&&!Tt())&&n==="free";Array.from(e.options).forEach(o=>{const a=Gt(o.value),l=Nr.includes(o.value);o.textContent=l&&r?`${a} (PRO)`:a,o.disabled=!1}),r&&Nr.includes(e.value)&&(e.value=ms),e.disabled=!1,qu.has(e)||(e.addEventListener("change",()=>{Tt()&&ce.tier==="free"&&Nr.includes(e.value)&&(e.value=ms,di()),qa(e.value),kl()}),qu.add(e));let s=document.getElementById("model-selector-free-notice");r?(s||(s=document.createElement("p"),s.id="model-selector-free-notice",s.className="text-xs text-gray-400 mt-1",t.appendChild(s)),s.innerHTML='Free plan — Gemini only. '):s&&s.remove(),qa(e.value)}function Gl(){const t=z.isVerified&&!!z.email,e=t&&pi(),n=!t||Tt(),i=lr(),r=n?i.count:0,s=n?qs():0,o=Math.max(0,s-r),a=`${r} / ${s} runs this month`,l=gl,u=n?ce.tier||"free":null,c=document.getElementById("topbar-credits-count");c&&(e?c.textContent="…":n?c.textContent=String(o):c.textContent="—");const d=document.getElementById("credits-balance");d&&(e?d.textContent="Checking plan…":n?d.textContent=a:d.textContent="Plan check failed");const f=document.getElementById("usage-dialog-tier");f&&(e?f.textContent="Checking…":n?f.textContent=l[u]||"Free":f.textContent="Unavailable");const h=document.getElementById("usage-dialog-status");h&&(e?h.textContent="Verifying your subscription…":n?h.textContent="Runs reset at the start of each month.":h.textContent="Could not verify your subscription. Try again or sign out.");const p=document.getElementById("usage-counter");if(p)if(e&&t)p.textContent="Checking plan…",p.className="text-xs text-gray-500";else if(!n&&t)p.textContent="Plan check failed",p.className="text-xs text-red-600 font-medium";else{p.textContent=a;const g=s>0?r/s:0;p.className=g>=1?"text-xs text-red-600 font-medium":g>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500"}if(!t){const g=document.getElementById("guest-usage-text");if(g){const m=np(),v=m.month===gn()?m.count??0:0;g.textContent=`${v} / ${ps.free} generations used`}}aw()}function aw(){if(!(z.isVerified&&!!z.email))return;const e=pi(),n=Tt(),i=lr(),r=n?i.count:0,s=n?qs():0,o=Math.max(0,s-r),a=n?ce.tier||"free":null,l={free:"Free",professional:"Pro",power:"Power"}[a]||"Free",u=z.email||"",c=u.split("@")[0]||u,d=document.getElementById("acct-avatar");d&&(d.textContent=(u[0]||"?").toUpperCase());const f=document.getElementById("acct-name");f&&(f.textContent=c||"—");const h=document.getElementById("acct-plan-tier"),p=document.getElementById("acct-plan-price"),g=document.getElementById("acct-plan-note"),m=document.getElementById("acct-renewal");if(h&&(h.textContent=e?"Checking…":n?l:"Plan unavailable"),p)if(e)p.textContent="—";else if(!n)p.textContent="—";else if(a==="free")p.textContent="$0 / month";else{const x=Oi(Ni[a]??0,Cl());p.textContent=`${x} / month`}if(g&&(e?g.textContent="Verifying your subscription…":n?a==="free"?g.textContent="No subscription. Upgrade for more generations.":g.textContent="billed monthly through Stripe":g.textContent="Could not verify your subscription. Check billing or sign out."),m){const x=Date.parse(ce.periodEnd||""),F=n&&a!=="free"&&!!ce.periodEnd&&!Number.isNaN(x);if(e)m.textContent="";else if(!n)m.textContent="";else if(a==="free")m.textContent="";else if(F){const $=new Date(x).toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"});m.textContent=`Renews ${$} · reset at the start of each month.`}else m.textContent="Renewal date is not available for this period."}const v=document.getElementById("acct-left-count"),E=document.getElementById("acct-left-limit"),S=document.getElementById("acct-reset-note");v&&(v.textContent=e?"…":n?String(o):"—"),E&&(E.textContent=e?"…":n?String(s):"—"),S&&(e?S.textContent="Checking plan…":n?S.textContent="Runs reset at the start of each month.":S.textContent="Plan check failed. Refresh or manage billing.");const _=document.getElementById("acct-used-count"),b=document.getElementById("acct-meter-fill"),k=document.getElementById("acct-meter-meta"),T=document.getElementById("acct-meter-track");if(_&&(_.textContent=e?"…":n?String(r):"—"),b){const x=n&&s>0?Math.min(100,Math.round(r/s*100)):0;b.style.width=`${x}%`}if(k)if(e)k.textContent="Checking…";else if(!n)k.textContent="Plan check failed";else if(s===0)k.textContent=`${r} of ${s}`;else{const x=Math.round(r/s*100);k.textContent=`${r} of ${s} · ${x}%`}T&&(e?T.setAttribute("aria-label","Checking usage…"):n?T.setAttribute("aria-label",`${r} of ${s} generations used`):T.setAttribute("aria-label","Usage unavailable")),vt()}function un(){if(Gl(),z.isVerified&&(pi()||!Tt())){id();return}const{count:t}=lr(),e=qs();t>=e&&!y.isRunning?ip(t,e):id()}function lw(){Gl()}async function rp(t={}){const e=t.force===!0;if(!z.isVerified||!z.sessionToken){ce=Mn({isResolved:!0});return}ce={...ce,isLoading:!0,error:null};const n=localStorage.getItem(gs);if(!e&&n)try{const{data:i,email:r,ts:s,version:o}=JSON.parse(n);if(o===zu&&r===z.email&&Date.now()-s<300*1e3){ce={...i,isLoading:!1,isResolved:i.isResolved!==!1};return}}catch(i){console.warn("Failed to parse subscription cache:",i,"| raw value:",n)}try{const r=await(await fetch(`${_t}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:z.sessionToken,user_id:ht.userId})})).json();if(r.error){if(["unauthorized","invalid session","expired session"].some(o=>String(r.error).toLowerCase().includes(o))){Xh(),Vl();return}ce=Mn({isResolved:!1,error:r.error});return}ce=rw(r),localStorage.setItem(gs,JSON.stringify({version:zu,data:ce,email:z.email,ts:Date.now()}))}catch(i){console.error("fetchSubscription failed:",i),ce={...ce,isLoading:!1,isResolved:!1,error:i.message}}}function sp(){localStorage.removeItem(gs)}async function cw(t){if(!z.isVerified||!z.sessionToken){op(),Ws();return}if(!Sh[t]){Ee("Invalid plan selected.","error");return}const e=document.getElementById(`checkout-btn-${t}`);e&&(e.disabled=!0,e.textContent="Redirecting…");try{const i=await(await fetch(`${_t}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:z.sessionToken,currency:Cl()})})).json();if(i.error||!i.url)throw new Error(i.error||"Failed to create checkout session");const{url:r}=i;window.location.href=r}catch(n){console.error("startCheckout failed:",n),e&&(e.disabled=!1,e.textContent="Subscribe"),Ee("Could not start checkout. Please try again.","error")}}async function uw(t){if(!z.isVerified||!z.sessionToken){Ws();return}const e=t||document.getElementById("manage-billing-btn"),n=e?e.textContent:"";e&&(e.disabled=!0,e.textContent="Loading…");try{const r=await(await fetch(`${_t}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:z.sessionToken})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to open billing portal");const{url:s}=r;window.location.href=s}catch(i){console.error("openCustomerPortal failed:",i),e&&(e.disabled=!1,e.textContent=n),Ee("Could not open billing portal. Please try again.","error")}}const Es=new Set;function dw(){Es.forEach(t=>t.abort()),Es.clear()}async function Ss(t,e,n,i={},r=[]){const o=new AbortController;Es.add(o);let a=!1;const l=setTimeout(()=>{a=!0,o.abort()},12e4);try{const u=await fetch(Cy,{method:"POST",headers:{"Content-Type":"application/json",...ht.token?{Authorization:`Bearer ${ht.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:ht.userId,step:t,model:e,prompt:n,images:r,context:i})}),c=await u.text();let d={};try{d=c?JSON.parse(c):{}}catch{d={}}if(u.status===429){d.serverCount!==void 0&&(localStorage.setItem(Fn,JSON.stringify({count:d.serverCount,month:gn()})),un());const p=new Error(d.message||"Monthly usage limit reached. Upgrade to continue.");throw p.isUsageLimit=!0,p.pipelineStep=t,p}const f=Ev(d,t);if(f)throw f;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(d),"content type:",typeof d.content),!u.ok)throw new Error(`${d.message||d.error||"BuildShip pipeline error"} (HTTP ${u.status})`);if(t==="generator")if(d.usage_status==="success"&&Number.isFinite(d.usage_count)){const p=gn();(d.usage_month||p)===p&&(localStorage.setItem(Fn,JSON.stringify({count:d.usage_count,month:p})),un())}else ew(),un();let h=d.output||d.content;if(!h){const p=c?` (body: ${c.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${p}`)}return Array.isArray(h)&&(h=h.map(p=>typeof p=="string"?p:p.text||"").join("")),typeof h!="string"&&(h=JSON.stringify(h)),h}catch(u){if(u.name==="AbortError"){if(a)throw new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`);const c=new Error(`BuildShip ${t} request cancelled`);throw c.isPipelineCancel=!0,c}throw u instanceof TypeError?new Error(`BuildShip unreachable: ${u.message}`):u}finally{clearTimeout(l),Es.delete(o)}}let Va=!1;function fw(){const e=new URLSearchParams(window.location.search).get("checkout");return e==="success"?(window.history.replaceState({},"",window.location.pathname+window.location.hash),sp(),Va=!0):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname+window.location.hash),Ee("Checkout cancelled.","info")),e}function hw(){if(!Va)return;Va=!1;const t=ce.tier!=="free";Ee(t?"Subscription active! Your plan is live.":"Checkout complete — confirming your subscription. Check Manage billing if it does not update.",t?"success":"info")}function zs(){const t=z.isVerified&&!!z.email,e=ce.tier,n=t&&pi(),i=!t||Tt(),r=document.getElementById("subscription-tier-badge");if(r){const a=gl,l={free:"bg-gray-100 text-gray-600",professional:"bg-indigo-100 text-indigo-700",power:"bg-purple-100 text-purple-700",unresolved:"bg-red-50 text-red-600"};r.textContent=n?"Checking…":i?a[e]||"Free":"Plan unavailable",r.className=`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${i?l[e]||l.free:l.unresolved}`}const s=document.getElementById("upgrade-prompt");s&&s.classList.toggle("hidden",!t||n||!i||e!=="free");const o=document.getElementById("manage-billing-btn");o&&o.classList.toggle("hidden",!t||n||i&&e==="free"),pw(i?e:null),ow(),kl(),un(),xp()}function pw(t){const e=["bg-gray-100","text-gray-500","cursor-default"];Object.entries({professional:{btnId:"checkout-btn-professional",defaultText:"Subscribe"},power:{btnId:"checkout-btn-power",defaultText:"Subscribe"}}).forEach(([r,{btnId:s,defaultText:o}])=>{const a=document.getElementById(s);a&&(r===t?(a.disabled=!0,a.textContent="Current plan",a.classList.add(...e)):(a.disabled=!1,a.textContent=o,a.classList.remove(...e)))});const i=document.getElementById("free-tier-current");i&&i.classList.toggle("hidden",t!=="free")}function gw(){document.querySelectorAll(".pm-card[data-tier]").forEach(t=>{const e=t.dataset.tier,n=cv[e];if(!n)return;const i=t.querySelector("ul.pm-features");if(i){i.innerHTML="";for(const r of n){const s=document.createElement("li");s.textContent=r,i.appendChild(s)}}})}function Ga(){const t=Cl(),e=document.getElementById("pro-price"),n=document.getElementById("power-price"),i=document.getElementById("plans-pro-price"),r=document.getElementById("plans-power-price"),s=document.getElementById("pro-price-note"),o=document.getElementById("power-price-note"),a=document.getElementById("plans-pro-price-note"),l=document.getElementById("plans-power-price-note");e&&(e.textContent=Oi(Ni.professional,t)),n&&(n.textContent=Oi(Ni.power,t)),i&&(i.textContent=Oi(Ni.professional,t)),r&&(r.textContent=Oi(Ni.power,t));const u="billed monthly";s&&(s.textContent=u),o&&(o.textContent=u),a&&(a.textContent=u),l&&(l.textContent=u)}function di(){Ga();const t=document.getElementById("pricing-modal");t&&He(t),Hy().then(()=>Ga())}function op(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&We(e)}function Ee(t,e="info"){const n={success:"bg-green-600 text-white",error:"bg-red-600 text-white",warning:"bg-amber-500 text-white",info:"bg-gray-800 text-white"},i=document.createElement("div");i.className=`fixed bottom-6 left-1/2 -translate-x-1/2 px-5 py-3 rounded-lg text-sm font-medium shadow-lg z-50 transition-opacity duration-300 ${n[e]||n.info}`,i.textContent=t,document.body.appendChild(i),setTimeout(()=>{i.style.opacity="0",setTimeout(()=>i.remove(),300)},3500)}document.addEventListener("DOMContentLoaded",async()=>{ov(),hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),mw(),window.__heroField=Q_(),window.__pipelineLogo=iy(),Ih=xy({onSubmit:or}),Oa=(async()=>{try{await W0(),fw(),await rp()}catch(n){console.warn("Startup auth/subscription initialization failed:",n)}})(),await Oa,hw(),zs(),Ga(),gw(),await _0(),h0();const t=document.getElementById("flutterflow-endpoint-select");if(t){const n=yt();t.value=n}Oh(),tp();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{en===2&&e.value.trim().length>0&&(Tl(),Ns())}),e.addEventListener("blur",()=>{const n=document.getElementById("walkthrough-modal");en===2&&n&&He(n)}),e.addEventListener("keydown",n=>{if(n.key==="Tab"){const i=document.getElementById("walkthrough-modal");en===2&&i&&setTimeout(()=>{He(i)},100)}})),window.addEventListener("commitStateChange",n=>{const{state:i}=n.detail;i===ee.PREPARING||i===ee.VALIDATING||i===ee.PUSHING?(Oe.phaseId||fp(),sd(i)):(i===ee.SUCCESS||i===ee.ERROR)&&(sd(i),setTimeout(Jl,1e3))}),ic()});function mw(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function vw(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Nn),document.addEventListener("keydown",Nn))}function Nn(){const t=document.getElementById("preview-frame-container"),e=document.getElementById("main-stage-container"),n=document.getElementById("ready-state");t&&(t.style.display="none"),e&&e.classList.add("visible"),n&&n.classList.remove("hidden");const i=document.getElementById("welcome-video-player");i&&i.removeEventListener("click",Nn),document.removeEventListener("keydown",Nn),Oh()}let zi=null;async function _w(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++Ju,n=()=>e===Ju,i=await Te("flutterflow"),r=await Te("flutterflow_project_id");if(n()){if(!i){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const o=await new hi(i,"","main",yt()).listProjects();if(!n())return;if(!o||o.length===0){t.innerHTML='';return}t.innerHTML='',o.forEach(a=>{const l=document.createElement("option");l.value=a.id||a.projectId||"",l.textContent=a.name||a.projectName||`Project ${a.id}`,t.appendChild(l)}),r&&(t.value=r)}catch(s){if(!n())return;console.error("Failed to load projects for deploy:",s),t.innerHTML=''}}}function yw(){return document.getElementById("confirm-project-select")?.value?.trim()||null}function Kl(t,e,n,i=null){zi={codeInfo:t,checks:e,deps:n,bundlePlan:i},document.getElementById("confirm-file-name").textContent=t.fileName,document.getElementById("confirm-artifact-type").textContent=t.artifactType,document.getElementById("confirm-file-size").textContent=`${(t.content.length/1024).toFixed(1)} KB`,document.getElementById("confirm-line-count").textContent=i?`${i.fileEntries.length} files`:t.content.split(` +`).length,_w();const r=document.getElementById("confirm-deps-list"),s=document.getElementById("confirm-deps-section");n&&Object.keys(n).length>0?(r.innerHTML=Object.entries(n).map(([u,c])=>{const d=c?`at least ${Qt(c)}`:"version resolved from your project";return`
  • • ${Qt(u)}: ${d}
  • `}).join(""),s.classList.remove("hidden")):s.classList.add("hidden");const o=document.getElementById("confirm-warnings-list"),a=document.getElementById("confirm-warnings-section");e.warnings&&e.warnings.length>0?(o.innerHTML=e.warnings.map(u=>`
  • • ${Qt(u)}
  • `).join(""),a.classList.remove("hidden")):a.classList.add("hidden"),document.getElementById("confirm-code-preview").textContent=t.content,document.getElementById("code-preview-content").classList.add("hidden"),document.getElementById("code-preview-chevron").style.transform="rotate(0deg)";const l=document.getElementById("commit-confirm-modal");l&&He(l)}function ap(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&We(e),zi=null}function ww(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&We(e);const n=["success-message","success-project-id","success-file-name","success-artifact-type","success-time","success-size"];for(const s of n){const o=document.getElementById(s);o&&(o.textContent="")}const i=document.getElementById("success-warnings-section");i&&i.classList.add("hidden");const r=document.getElementById("success-warnings-list");r&&(r.innerHTML="")}function lp(t){const e=(m,v)=>{const E=document.getElementById(m);E&&(E.textContent=v||"")},n=t.metadata?.fileName||"",i=t.metadata?.projectId||"",r=t.metadata?.artifactType||"",s=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",i),e("success-file-name",n),e("success-artifact-type",r),e("success-time",s),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&i&&(u.href=`https://app.flutterflow.io/project/${i}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),f=t.unverified||[],h=t.approximate||[],p=t.warnings||[];(p.length>0||f.length>0||h.length>0)&&c&&d&&(d.innerHTML=[...f.map(m=>`
  • Not verified before deploying: ${q(String(m))}
  • `),...h.map(m=>`
  • Verified approximately: ${q(String(m))}
  • `),...p.map(([m,v])=>`
  • ${q(m)}: ${q(String(v))}
  • `)].join(""),c.classList.remove("hidden"));const g=document.getElementById("commit-success-modal");g&&He(g)}function cp(t){Jl(),D0(t),Yl(t,{heading:"Deploy failed",title:"FlutterFlow refused this deploy — nothing was confirmed written.",guidance:"Review the error and any per-file outcomes above, fix them in your code or in FlutterFlow, then deploy again. A refusal is definitive: no part of this deploy was applied, so retrying is safe once the problem is fixed."})}function Yl(t,{heading:e,title:n,guidance:i}){const r=t.targetIdentity||{},s=document.getElementById("commit-terminal-modal");if(!s)return!1;const o=(h,p)=>{const g=document.getElementById(h);g&&(g.textContent=p||"")};o("terminal-heading",e),o("terminal-title",n),o("terminal-message",t.error||t.message||"");const a=document.getElementById("terminal-identity-list");if(a){const h=[["Project",r.projectId||t.metadata?.projectId],["Endpoint",r.endpoint],["File",r.fileName||t.metadata?.fileName],["Artifact",r.artifactType||t.metadata?.artifactType]];a.innerHTML=h.map(([p,g])=>`
    ${q(p)}:${q(String(g??"—"))}
    `).join("")}const l=document.getElementById("terminal-file-outcomes");let u=t.errorMap;u&&!(u instanceof Map)&&(u=new Map(Object.entries(u))),l&&u&&u.size>0?(l.innerHTML=[...u.entries()].map(([h,p])=>`
  • ${q(h)}: ${q(El(p))}
  • `).join(""),l.classList.remove("hidden")):l&&l.classList.add("hidden");const c=document.getElementById("terminal-guidance");c&&(c.innerHTML=i);const d=document.getElementById("terminal-open-ff-link"),f=r.projectId||t.metadata?.projectId;return d&&(d.href=f?`https://app.flutterflow.io/project/${f}`:"https://app.flutterflow.io/"),He(s),!0}function up(t){Yl(t,{heading:"Deploy partially applied",title:"Some custom classes reached FlutterFlow, but the deploy did not fully complete.",guidance:"The custom classes the runner confirmed are already in your project and are not lost. Review the per-file errors above, fix them in FlutterFlow or regenerate, then deploy again. Open the project to see exactly what landed."})}function dp(t){Yl(t,{heading:"Deploy outcome not yet known",title:"This browser stopped waiting before the FlutterFlow server reported a result.",guidance:"The deploy may still be finishing on the server — it was not cancelled. Open your FlutterFlow project and confirm whether the class landed before retrying, so you do not push a duplicate or build on top of an unknown state."})}function bw(t){t&&t.target!==t.currentTarget||We(document.getElementById("commit-terminal-modal"))}function Ew(){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 rd={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}},Sw=[{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..."}],Oe={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&&(Eu(e,!0,"Deploying to FlutterFlow"),He(e)),this.set("prepare")},set(t,e=null){if(!(!rd[t]||t===this.phaseId)){if(!this.sequence.includes(t)){const n=this.sequence.indexOf("package");this.sequence.splice(n===-1?this.sequence.length:n,0,t)}this.phaseId=t,this.phaseStartedAt=Date.now(),this.substatus=e,this.liveSubstatus=!1,this.render(),this.timer&&clearInterval(this.timer),t!=="done"&&(this.timer=setInterval(()=>this.render(),500))}},setSubstatus(t){t&&(this.liveSubstatus=!0,this.substatus=t,this.render())},render(){const t=rd[this.phaseId];if(!t)return;const e=(Date.now()-this.phaseStartedAt)/1e3,n=t.start+(t.end-t.start)*(1-Math.exp(-e/25));if(this.phaseId==="provision"&&!this.liveSubstatus){const o=Sw.filter(a=>e>=a.after).pop();o&&(this.substatus=o.text)}const i=this.sequence.indexOf(this.phaseId),s=[`Step ${i===-1?1:i+1} of ${this.sequence.length}`];e>=5&&s.push(xw(e)),hp(this.phaseId==="done"?100:n,t.message,s.join(" · "),this.substatus)},stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.phaseId=null;const t=document.getElementById("commit-progress-overlay");t&&(Eu(t,!1),We(t,{force:!0,restoreFocus:!1}))}};function xw(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 fp(t){Oe.start(t)}function Jl(){Oe.stop()}function hp(t,e,n,i=null){const r=document.getElementById("commit-progress-bar"),s=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");r&&(r.style.width=`${Math.round(t*10)/10}%`),s&&(s.textContent=e),o&&(o.textContent=n),a&&(a.textContent=i||"",a.classList.toggle("hidden",!i))}function sd(t){const e={[ee.PREPARING]:"prepare",[ee.VALIDATING]:"validate",[ee.PUSHING]:"project",[ee.SUCCESS]:"done"};if(t===ee.ERROR){Oe.timer&&clearInterval(Oe.timer),Oe.timer=null,hp(100,"Failed","Error occurred");return}const n=e[t];n&&Oe.set(n)}function Iw(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===J.CODE_FILE):t.codeInfo?.codeType===J.CODE_FILE}let pp=!1;function gp(t){pp=t;const e=document.querySelector("#commit-confirm-modal button[data-deploy-confirm]");e&&(e.disabled=t),[...document.querySelectorAll("[data-deploy-start]"),...document.querySelectorAll("#btn-deploy-to-ff")].forEach(i=>{i.disabled=t})}function od(t){Jl(),gp(!1);const e=yh(t);e===Xe.COMMITTED?lp(t):e===Xe.PARTIAL?up(t):e===Xe.UNCONFIRMED?dp(t):cp(t)}async function kw(){if(!zi){console.error("No pending commit data");return}if(pp){console.warn("Deploy already in flight; ignoring duplicate confirm.");return}const t=zi;if(zi=null,qi=yw(),ap(),gp(!0),fp({withProvisioning:Iw(t)}),t.bundlePlan){const o=await A0(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});qi=null,od(o);return}const{codeInfo:e}=t,{artifactType:n,artifactName:i,fileName:r}=Bh(),s=await C0(e.content,{artifactType:n,artifactName:i,fileName:r,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});qi=null,od(s)}window.runThinkingPipeline=or;window.toggleStep=R0;window.toggleSection=F0;window.selectWorkflowStep=nt;window.copyCode=T0;window.retryWithDifferentModel=N0;window.openApiKeysModal=Rl;window.closeApiKeysModal=Lh;window.openComposerSettings=n0;window.closeComposerSettings=i0;window.walkthroughConnectAccount=t0;window.closeWalkthroughModal=s0;window.openWalkthroughModal=r0;window.advanceWalkthrough=Tl;window.commitToFlutterFlow=k0;function Cw(){const t=document.getElementById("pipeline-input");t&&t.focus()}function Aw(){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=Cw;window.openModelSelector=Aw;window.handlePromptImageSelect=jy;window.removePromptImage=Uy;window.saveApiKeys=l0;window.validateFlutterFlowConnection=Ml;window.clearAllApiKeys=c0;window.toggleKeyVisibility=g0;window.handleWelcomeVideoEnd=vw;window.dismissWelcomeVideo=Nn;window.initiateCommitToFlutterFlow=O0;window.updateFlutterFlowCredentialStatus=j0;window.openCommitConfirmModal=Kl;window.closeCommitConfirmModal=ap;window.closeCommitSuccessModal=ww;window.closeCommitTerminalModal=bw;window.showCommitPartialModal=up;window.showCommitUnconfirmedModal=dp;window.showCommitSuccessModal=lp;window.showCommitFailureModal=cp;window.toggleCodePreview=Ew;window.confirmCommitToFlutterFlow=kw;window.runRefinement=Kh;window.regenerateFromPastedErrors=Yh;window.clearErrorInput=L0;window.setFlutterFlowEndpoint=e0;window.getFlutterFlowEndpoint=yt;window.commitProgress=Oe;window.openSignInModal=Ws;window.closeSignInModal=ep;window.handleMagicLinkRequest=z0;window.handleSignOut=V0;window.handleSendNewLink=Y0;window.handleClearCache=J0;window.handleDeleteAccount=Z0;window.closeDeleteUnavailableModal=X0;window.startCheckout=cw;window.openCustomerPortal=uw;window.openPricingModal=di;window.closePricingModal=op;let jr=null,mp=null,On={1:"pending",2:"pending",3:"pending"},Zl=1,Xl=null;const Vs={1:"Prompt Architect",2:"Code Generator",3:"Code Review"},Pw={1:"Understanding your prompt",2:"Generating Dart code",3:"Running the code audit"},Fw={1:"Prompt understood",2:"Dart code generated",3:"Code audit complete"};function Gs(){return y.runId+=1,y.runId}function re(t){return t===void 0||t===y.runId}function Rw(){y.runId+=1}function Ql(t){return document.getElementById(`pdot-${t}`)}function Ka(t){const e=document.getElementById("btn-run-pipeline")||document.getElementById("hero-send");e&&(e.disabled=t,e.classList.toggle("is-busy",t),t?e.setAttribute("aria-busy","true"):e.removeAttribute("aria-busy"))}function Ks(t){const e=document.getElementById("pipeline-progress");e&&(e.dataset.runState=t)}function Rn(t,e){On[t]=e;const n=Ql(t);if(!n)return;n.dataset.state=e,n.disabled=e==="pending"||e==="skipped";const i=Vs[t],r={pending:"not started",active:"in progress",done:"complete",failed:"failed",skipped:"not run"};n.setAttribute("aria-label",`Step ${t} of 3, ${i}: ${r[e]||e}`),e==="active"?n.setAttribute("aria-current","step"):n.removeAttribute("aria-current")}function Tw(){return[1,2,3].filter(t=>On[t]==="done").length}function Ys(){const t=document.getElementById("pipeline-progress-fill");t&&(t.style.width=`${Tw()/3*100}%`);const e=document.getElementById("progress-stage-count");e&&(e.textContent=`Step ${Zl} of 3`)}function Js(t,{done:e=!1}={}){const n=document.getElementById("progress-title-text"),i=document.getElementById("progress-substep-text"),r=On[t],s=e||r==="done";if(n&&(n.textContent=s?Fw[t]:Pw[t]),i){const o=s?" — complete":r==="failed"?" — stopped":"";i.textContent=`Step ${t} of 3 — ${Vs[t]}${o}`}}function $w(t){On[t]==="pending"||On[t]==="skipped"||(Xl=t,[1,2,3].forEach(e=>{const n=Ql(e);n&&n.setAttribute("aria-pressed",String(e===t))}),Js(t))}function ec(){Xl=null,[1,2,3].forEach(t=>{const e=Ql(t);e&&e.removeAttribute("aria-pressed")})}function vp(t){const e=document.getElementById("pipeline-note");e&&(e.textContent=t||"",e.hidden=!t)}function Mw(t,e,n){re(n)&&vp(`${Gt(t)} did not answer. Continuing on ${Gt(e)}.`)}function tc(){const t=document.getElementById("pipeline-failure");if(!t)return;t.hidden=!0;const e=document.getElementById("pipeline-failure-actions");e&&e.replaceChildren()}const Lw=1120;function Nw(){const t=getComputedStyle(document.documentElement).getPropertyValue("--t-morph").trim(),e=Number.parseFloat(t);return Number.isFinite(e)&&e>0?e:Lw}let Qn=null,Ur=null;function Ow(){return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0}function dn(){if(Ur){try{Ur.cancel()}catch{}Ur=null}Qn&&(Qn.remove(),Qn=null),window.removeEventListener("resize",dn)}function _p(t,e){if(dn(),Ow()||!t||!e||!document.body||typeof Element.prototype.animate!="function")return;const n=t.getBoundingClientRect(),i=e.getBoundingClientRect();if(!n.width||!n.height||!i.width||!i.height)return;const r=document.createElement("div");r.className="composer-morph",r.setAttribute("aria-hidden","true"),r.style.cssText=`left:${i.left}px;top:${i.top}px;width:${i.width}px;height:${i.height}px;opacity:0;`,document.body.appendChild(r);const s=n.left+n.width/2-(i.left+i.width/2),o=n.top+n.height/2-(i.top+i.height/2),a=n.width/i.width,l=n.height/i.height,u=`translate(${s}px,${o}px) scale(${a},${l})`,c=r.animate([{transform:u,opacity:0,offset:0,easing:"cubic-bezier(.2,0,0,1)"},{transform:u,opacity:1,offset:.14,easing:"cubic-bezier(.4,0,.2,1)"},{transform:`translate(${s}px,${o}px) scale(${a*.93},${l*.93})`,opacity:1,offset:.28,easing:"cubic-bezier(.32,1.38,.5,1)"},{transform:"translate(0px,0px) scale(1,1)",opacity:1,offset:1}],{duration:Nw(),fill:"both"});Qn=r,Ur=c,window.addEventListener("resize",dn),c.onfinish=()=>{if(Qn!==r)return;const d=r.animate([{opacity:1},{opacity:0}],{duration:260,fill:"forwards"});d.onfinish=()=>{Qn===r&&dn()}}}function Bw(){const e=document.getElementById("composer")?.getBoundingClientRect();e&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{_p({getBoundingClientRect:()=>e},document.getElementById("main-stage-container"))})})}function Dw(){_p(document.getElementById("pipeline-progress"),document.getElementById("main-stage-container"))}window.addEventListener("hashchange",dn);window.addEventListener("popstate",dn);function Zs(t={}){const{prompt:e=null,runId:n}=t;if(!re(n))return;Qs(),nn(!0);const i=document.getElementById("pipeline-progress"),r=document.getElementById("results-view"),s=document.getElementById("ready-state");if(s&&s.classList.add("hidden"),r&&r.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),i&&i.classList.add("visible"),Ks("running"),e!==null){const a=document.getElementById("pipeline-submitted-prompt");a&&(a.textContent=e)}mp=Date.now();const o=document.getElementById("progress-elapsed");o&&(o.textContent="0s"),On={1:"pending",2:"pending",3:"pending"},ec(),tc(),vp(""),[1,2,3].forEach(a=>Rn(a,"pending")),Ft(1,n),jw()}function Ft(t,e){re(e)&&(Zl=t,ec(),[1,2,3].forEach(n=>{n===t?Rn(n,"active"):nt&&Rn(n,"pending")}),Js(t),Ys())}function tn(t,e){re(e)&&(Rn(t,"done"),Xl===null&&Js(t,{done:!0}),Ys())}function yp(t,{stage:e=1,runId:n,retry:i=wp}={}){if(!re(n))return;Xs(),Qs(),dn(),Ks("failed"),nn(!0);const r=document.getElementById("pipeline-progress");r&&r.classList.add("visible");const s=document.getElementById("results-view");s&&s.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),Rn(e,"failed"),[1,2,3].forEach(p=>{p>e&&Rn(p,"pending")}),Zl=e,ec(),Js(e),Ys();const o=bh(t),a=document.getElementById("pipeline-failure"),l=document.getElementById("pipeline-failure-title"),u=document.getElementById("pipeline-failure-message"),c=document.getElementById("pipeline-failure-hint"),d=document.getElementById("pipeline-failure-actions");if(!a||!l||!u||!d)return;if(a.dataset.kind=o.kind,l.textContent=`${Vs[e]}: ${o.title}`,u.textContent=o.message,c){const p=o.detail&&o.detail!==o.message?o.detail:"";c.textContent=p,c.hidden=!p}d.replaceChildren();const f=[o.canUpgrade&&{id:"upgrade",label:"View plans",variant:"primary",onClick:()=>di()},o.canRetry&&{id:"retry",label:"Retry",variant:o.canUpgrade?"secondary":"primary",onClick:i},o.canEdit&&{id:"edit",label:"Edit prompt",variant:"secondary",onClick:Ya}].filter(Boolean);!o.canEdit&&!o.canRetry&&f.push({id:"edit",label:"Back to prompt",variant:"secondary",onClick:Ya}),f.forEach(p=>{const g=document.createElement("button");g.type="button",g.textContent=p.label,g.dataset.action=p.id,g.dataset.variant=p.variant,g.addEventListener("click",p.onClick),d.appendChild(g)}),a.hidden=!1;const h=d.querySelector("button");h&&h.focus({preventScroll:!0})}function Ya(){Rw(),dw(),y.isRunning=!1,Ka(!1),rn(),Ks("settled"),dn(),Xs(),Qs(),tc();const t=document.getElementById("pipeline-progress");t&&t.classList.remove("visible"),nn(!1);const e=document.getElementById("pipeline-input");e&&(y.submittedPrompt&&(e.value=y.submittedPrompt,e.dispatchEvent(new Event("input",{bubbles:!0}))),e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length))}function wp(){const t=document.getElementById("pipeline-input");t&&y.submittedPrompt&&(t.value=y.submittedPrompt,t.dispatchEvent(new Event("input",{bubbles:!0}))),Ne=y.submittedImages.slice(),cn(),tc(),or()}function jw(){Xs(),jr=setInterval(()=>{const t=(Date.now()-mp)/1e3,e=document.getElementById("progress-elapsed");e&&(e.textContent=`${Math.floor(t)}s`)},250)}function Xs(){jr&&(clearInterval(jr),jr=null)}let Vi=null;function Qs(){Vi&&(clearTimeout(Vi),Vi=null)}function cr(){Xs(),Qs(),Ks("settled"),Ys();const t=document.getElementById("pipeline-progress-fill");Vi=setTimeout(()=>{Vi=null;const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function Tn(t,e=""){const n={pass:'',warning:'',fail:'',info:''};return``}function bp(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function Uw(){return p_({bundle:y.artifactBundle,reviewResult:y.step3Result})}function Hw(t){return`
    ${Tn(t.severity)}
    @@ -174,14 +174,14 @@ Error: ${g} ${q(t.source)}
    - `}function Hw(t){return` + `}function Ww(t){return`
  • ${q(t.title)} ${t.detail&&t.detail!==t.title?`

    ${q(t.detail)}

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

    ${q(l.reason)}

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

    ${q(l.description)}

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

    ${q(e.artifactName)}

    ${e.description?`

    ${q(e.description)}

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

    Manual FlutterFlow steps for this file

    -
      ${e.manualSteps.map(Hw).join("")}
    +
      ${e.manualSteps.map(Ww).join("")}
    `:""}
    @@ -297,7 +297,7 @@ Error: ${g}
      ${a}
    - `}function zw(t){const e=document.getElementById("bundle-strip"),n=document.getElementById("results-summary-tab"),i=document.getElementById("artifact-tabs"),r=document.getElementById("results-file-count");if(n){const s=y.resultsViewMode==="summary";n.classList.toggle("active",s),n.setAttribute("role","tab"),n.setAttribute("aria-selected",String(s)),n.setAttribute("aria-controls","results-summary-detail"),n.tabIndex=s?0:-1}if(i&&(i.setAttribute("role","tablist"),i.setAttribute("aria-label","Artifacts in this bundle")),!t.artifacts.length){r&&(r.textContent="0 files"),e&&e.classList.remove("visible"),i&&(i.innerHTML=""),ad();return}if(r){const s=t.artifacts.length;r.textContent=`${s} ${s===1?"file":"files"}`}i&&(i.innerHTML=t.artifacts.map(s=>{const o=y.resultsViewMode==="file"&&s.id===y.selectedArtifactId;return` + `}function Vw(t){const e=document.getElementById("bundle-strip"),n=document.getElementById("results-summary-tab"),i=document.getElementById("artifact-tabs"),r=document.getElementById("results-file-count");if(n){const s=y.resultsViewMode==="summary";n.classList.toggle("active",s),n.setAttribute("role","tab"),n.setAttribute("aria-selected",String(s)),n.setAttribute("aria-controls","results-summary-detail"),n.tabIndex=s?0:-1}if(i&&(i.setAttribute("role","tablist"),i.setAttribute("aria-label","Artifacts in this bundle")),!t.artifacts.length){r&&(r.textContent="0 files"),e&&e.classList.remove("visible"),i&&(i.innerHTML=""),ad();return}if(r){const s=t.artifacts.length;r.textContent=`${s} ${s===1?"file":"files"}`}i&&(i.innerHTML=t.artifacts.map(s=>{const o=y.resultsViewMode==="file"&&s.id===y.selectedArtifactId;return` - `}).join(""),i.onclick=s=>{const o=s.target.closest(".artifact-tab");o?.dataset?.artifactId&&nc(o.dataset.artifactId)},ad()),e&&e.classList.add("visible")}function ad(){const t=document.getElementById("bundle-strip");!t||t.dataset.tabKeyboard==="bound"||(t.dataset.tabKeyboard="bound",t.addEventListener("keydown",e=>{if(e.defaultPrevented)return;const n=[document.getElementById("results-summary-tab"),...Array.from(document.querySelectorAll("#artifact-tabs .artifact-tab"))].filter(Boolean);if(!n.length||!n.includes(document.activeElement))return;let i=-1;const r=n.indexOf(document.activeElement);if(e.key==="ArrowRight")i=(r+1)%n.length;else if(e.key==="ArrowLeft")i=(r-1+n.length)%n.length;else if(e.key==="Home")i=0;else if(e.key==="End")i=n.length-1;else return;e.preventDefault();const s=n[i];if(!s)return;if(s.id==="results-summary-tab")wp();else{const a=s.dataset.artifactId;a&&nc(a)}const o=s.id==="results-summary-tab"?document.getElementById("results-summary-tab"):document.querySelector(`#artifact-tabs .artifact-tab[data-artifact-id="${s.dataset.artifactId}"]`);o&&o.focus()}))}function eo(){document.body.classList.add("results-fullscreen"),document.body.classList.add("results-with-sidebar");const t=document.getElementById("results-view"),e=document.getElementById("results-code-output"),n=document.getElementById("results-audit-output"),i=document.getElementById("results-summary-detail"),r=document.getElementById("artifact-results-split"),s=jw(),o=Ol();if(i&&(i.setAttribute("role","tabpanel"),i.setAttribute("aria-labelledby","results-summary-tab")),r){r.setAttribute("role","tabpanel");const a=s?.artifacts?.find(l=>l.id===y.selectedArtifactId);r.setAttribute("aria-labelledby",a?`artifact-tab-${a.id}`:"results-summary-tab")}if(Ww(s),zw(s),e&&(e.textContent=""),e){const a=bh(o);e.innerHTML=a}n&&(n.innerHTML=qw(s)),i&&i.classList.toggle("hidden",y.resultsViewMode!=="summary"),r&&r.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function ur(t,e){nn(!0),y.selectedArtifactId||(y.selectedArtifactId=oi(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const n=document.getElementById("step3-output");n&&(n.textContent=""),eo(),rn(),Vw()}function Vw(){const t=document.getElementById("btn-feedback-up"),e=document.getElementById("btn-feedback-down"),n=document.getElementById("results-feedback-status");t&&(t.className="feedback-btn",t.setAttribute("aria-pressed","false"),t.disabled=!1,t.removeAttribute("aria-disabled")),e&&(e.className="feedback-btn",e.setAttribute("aria-pressed","false"),e.disabled=!1,e.removeAttribute("aria-disabled")),n&&(n.textContent=""),Ja=!1}function nc(t){y.selectedArtifactId=t,y.resultsViewMode="file",eo()}function wp(){y.resultsViewMode="summary",eo()}function Gw(){const t=document.getElementById("btn-copy-results"),e=document.getElementById("results-copy-status"),n=Ol(),i=(r,s)=>{e&&(e.textContent=r,e.classList.toggle("ok",!!s),e.classList.toggle("fail",!s))};if(!navigator.clipboard?.writeText){i("Copying isn't supported in this browser.",!1);return}navigator.clipboard.writeText(n).then(()=>{if(i("Copied to clipboard",!0),t){t.classList.add("copied");const r=t.querySelector("span");if(r){const s=r.textContent;r.textContent="Copied!",setTimeout(()=>{t.classList.remove("copied"),r.textContent=s},2e3)}}}).catch(()=>{i("Clipboard permission was denied. Select the code to copy it manually.",!1)})}let Ja=!1;async function Kw(t){const e=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down"),i=document.getElementById("results-feedback-status");if(!e||!n||Ja)return;const r=l=>{i&&(i.textContent="",i.offsetWidth,i.textContent=l)},s=l=>{Ja=l,[e,n].forEach(u=>{u.disabled=l,u.setAttribute("aria-disabled",String(l))})},o=t==="up"?"thumbsUp":"thumbsDown";s(!0),r("Submitting review feedback…");const a={type:o,code:y.step2Result,input:y.step1Result};try{const l=await zl(a.type,a.code,a.input);if(!l||l.success!==!0){s(!1),r("Review feedback could not be sent. Tap again to retry.");return}e.classList.toggle("active-up",t==="up"),n.classList.toggle("active-down",t==="down"),e.setAttribute("aria-pressed",String(t==="up")),n.setAttribute("aria-pressed",String(t==="down")),s(!1),r("Review feedback saved.")}catch{s(!1),r("Review feedback could not be sent. Tap again to retry.")}}function Yw(){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 bp(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}function nn(t){const e=document.getElementById("generation-stage");e&&(t?(e.hidden=!1,e.inert=!1,requestAnimationFrame(()=>e.classList.add("is-active"))):(e.classList.remove("is-active"),e.inert=!0,setTimeout(()=>{e.classList.contains("is-active")||(e.hidden=!0)},260)))}function Ep(){const t=z.isVerified&&!!z.email,e=ce.tier||"free",n=t&&pi(),i=!t||Tt(),s=n?"Checking…":i?gl[e]||"Free":"—",o=document.getElementById("topbar-plan");o&&(o.textContent=s);const a=document.getElementById("topbar-avatar");a&&(a.textContent=(z.email||"?")[0].toUpperCase()),Gl();const l=document.getElementById("plans-free-current");l&&l.classList.toggle("hidden",e!=="free"||!i);const u=document.getElementById("plans-checkout-btn-professional");if(u){const d=e==="professional"&&i;u.disabled=d,u.textContent=d?"Current plan":"Subscribe"}const c=document.getElementById("plans-checkout-btn-power");if(c){const d=e==="power"&&i;c.disabled=d,c.textContent=d?"Current plan":"Subscribe"}}function Jw(){Ep();const t=document.getElementById("credits-modal");t&&He(t)}function Zw(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("credits-modal");e&&We(e)}function Sp(t,e=!0,n=!0){if(t=["home","account","plans"].includes(t)?t:"home",document.querySelectorAll(".view[data-view]").forEach(r=>{r.dataset.view===t?(r.hidden=!1,r.removeAttribute("inert"),requestAnimationFrame(()=>{r.classList.add("is-active"),n&&r.focus({preventScroll:!0})})):(r.classList.remove("is-active"),r.setAttribute("inert","true"),setTimeout(()=>{r.classList.contains("is-active")||(r.hidden=!0)},260))}),t!=="home")nn(!1);else{const r=document.getElementById("main-stage-container");r&&r.classList.contains("visible")&&nn(!0)}if(document.querySelectorAll(".nav-link[data-view]").forEach(r=>{const s=r.dataset.view===t;r.setAttribute("aria-current",s?"page":null),s||r.removeAttribute("aria-current")}),e){const r=t==="home"?"":`#${t}`;window.location.hash!==r&&window.history.pushState({view:t},"",r||"#")}}let ld=!1;function ic(){const t=window.location.hash.replace(/^#/,"");Sp(t||"home",!1,ld),ld=!0}window.addEventListener("popstate",t=>{ic()});window.addEventListener("hashchange",()=>{ic()});window.copyResultsCode=Gw;window.selectArtifact=nc;window.selectResultsSummary=wp;window.submitResultsFeedback=Kw;window.showErrorInputPanel=Yw;window.hideErrorInputPanel=bp;window.setGenerationStageVisible=nn;window.switchView=Sp;window.selectPipelineStage=Tw;window.editPipelinePrompt=Ya;window.retryPipelineRun=_p;window.openCreditsModal=Jw;window.closeCreditsModal=Zw; + `}).join(""),i.onclick=s=>{const o=s.target.closest(".artifact-tab");o?.dataset?.artifactId&&nc(o.dataset.artifactId)},ad()),e&&e.classList.add("visible")}function ad(){const t=document.getElementById("bundle-strip");!t||t.dataset.tabKeyboard==="bound"||(t.dataset.tabKeyboard="bound",t.addEventListener("keydown",e=>{if(e.defaultPrevented)return;const n=[document.getElementById("results-summary-tab"),...Array.from(document.querySelectorAll("#artifact-tabs .artifact-tab"))].filter(Boolean);if(!n.length||!n.includes(document.activeElement))return;let i=-1;const r=n.indexOf(document.activeElement);if(e.key==="ArrowRight")i=(r+1)%n.length;else if(e.key==="ArrowLeft")i=(r-1+n.length)%n.length;else if(e.key==="Home")i=0;else if(e.key==="End")i=n.length-1;else return;e.preventDefault();const s=n[i];if(!s)return;if(s.id==="results-summary-tab")Ep();else{const a=s.dataset.artifactId;a&&nc(a)}const o=s.id==="results-summary-tab"?document.getElementById("results-summary-tab"):document.querySelector(`#artifact-tabs .artifact-tab[data-artifact-id="${s.dataset.artifactId}"]`);o&&o.focus()}))}function eo(){document.body.classList.add("results-fullscreen"),document.body.classList.add("results-with-sidebar");const t=document.getElementById("results-view"),e=document.getElementById("results-code-output"),n=document.getElementById("results-audit-output"),i=document.getElementById("results-summary-detail"),r=document.getElementById("artifact-results-split"),s=Uw(),o=Ol();if(i&&(i.setAttribute("role","tabpanel"),i.setAttribute("aria-labelledby","results-summary-tab")),r){r.setAttribute("role","tabpanel");const a=s?.artifacts?.find(l=>l.id===y.selectedArtifactId);r.setAttribute("aria-labelledby",a?`artifact-tab-${a.id}`:"results-summary-tab")}if(qw(s),Vw(s),e&&(e.textContent=""),e){const a=Eh(o);e.innerHTML=a}n&&(n.innerHTML=zw(s)),i&&i.classList.toggle("hidden",y.resultsViewMode!=="summary"),r&&r.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function ur(t,e){nn(!0),y.selectedArtifactId||(y.selectedArtifactId=oi(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const n=document.getElementById("step3-output");n&&(n.textContent=""),eo(),rn(),Gw()}function Gw(){const t=document.getElementById("btn-feedback-up"),e=document.getElementById("btn-feedback-down"),n=document.getElementById("results-feedback-status");t&&(t.className="feedback-btn",t.setAttribute("aria-pressed","false"),t.disabled=!1,t.removeAttribute("aria-disabled")),e&&(e.className="feedback-btn",e.setAttribute("aria-pressed","false"),e.disabled=!1,e.removeAttribute("aria-disabled")),n&&(n.textContent=""),Ja=!1}function nc(t){y.selectedArtifactId=t,y.resultsViewMode="file",eo()}function Ep(){y.resultsViewMode="summary",eo()}function Kw(){const t=document.getElementById("btn-copy-results"),e=document.getElementById("results-copy-status"),n=Ol(),i=(r,s)=>{e&&(e.textContent=r,e.classList.toggle("ok",!!s),e.classList.toggle("fail",!s))};if(!navigator.clipboard?.writeText){i("Copying isn't supported in this browser.",!1);return}navigator.clipboard.writeText(n).then(()=>{if(i("Copied to clipboard",!0),t){t.classList.add("copied");const r=t.querySelector("span");if(r){const s=r.textContent;r.textContent="Copied!",setTimeout(()=>{t.classList.remove("copied"),r.textContent=s},2e3)}}}).catch(()=>{i("Clipboard permission was denied. Select the code to copy it manually.",!1)})}let Ja=!1;async function Yw(t){const e=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down"),i=document.getElementById("results-feedback-status");if(!e||!n||Ja)return;const r=l=>{i&&(i.textContent="",i.offsetWidth,i.textContent=l)},s=l=>{Ja=l,[e,n].forEach(u=>{u.disabled=l,u.setAttribute("aria-disabled",String(l))})},o=t==="up"?"thumbsUp":"thumbsDown";s(!0),r("Submitting review feedback…");const a={type:o,code:y.step2Result,input:y.step1Result};try{const l=await zl(a.type,a.code,a.input);if(!l||l.success!==!0){s(!1),r("Review feedback could not be sent. Tap again to retry.");return}e.classList.toggle("active-up",t==="up"),n.classList.toggle("active-down",t==="down"),e.setAttribute("aria-pressed",String(t==="up")),n.setAttribute("aria-pressed",String(t==="down")),s(!1),r("Review feedback saved.")}catch{s(!1),r("Review feedback could not be sent. Tap again to retry.")}}function Jw(){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 Sp(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}function nn(t){const e=document.getElementById("generation-stage");e&&(t?(e.hidden=!1,e.inert=!1,requestAnimationFrame(()=>e.classList.add("is-active"))):(e.classList.remove("is-active"),e.inert=!0,setTimeout(()=>{e.classList.contains("is-active")||(e.hidden=!0)},260)))}function xp(){const t=z.isVerified&&!!z.email,e=ce.tier||"free",n=t&&pi(),i=!t||Tt(),s=n?"Checking…":i?gl[e]||"Free":"—",o=document.getElementById("topbar-plan");o&&(o.textContent=s);const a=document.getElementById("topbar-avatar");a&&(a.textContent=(z.email||"?")[0].toUpperCase()),Gl();const l=document.getElementById("plans-free-current");l&&l.classList.toggle("hidden",e!=="free"||!i);const u=document.getElementById("plans-checkout-btn-professional");if(u){const d=e==="professional"&&i;u.disabled=d,u.textContent=d?"Current plan":"Subscribe"}const c=document.getElementById("plans-checkout-btn-power");if(c){const d=e==="power"&&i;c.disabled=d,c.textContent=d?"Current plan":"Subscribe"}}function Zw(){xp();const t=document.getElementById("credits-modal");t&&He(t)}function Xw(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("credits-modal");e&&We(e)}function Ip(t,e=!0,n=!0){if(t=["home","account","plans"].includes(t)?t:"home",document.querySelectorAll(".view[data-view]").forEach(r=>{r.dataset.view===t?(r.hidden=!1,r.removeAttribute("inert"),requestAnimationFrame(()=>{r.classList.add("is-active"),n&&r.focus({preventScroll:!0})})):(r.classList.remove("is-active"),r.setAttribute("inert","true"),setTimeout(()=>{r.classList.contains("is-active")||(r.hidden=!0)},260))}),t!=="home")nn(!1);else{const r=document.getElementById("main-stage-container");r&&r.classList.contains("visible")&&nn(!0)}if(document.querySelectorAll(".nav-link[data-view]").forEach(r=>{const s=r.dataset.view===t;r.setAttribute("aria-current",s?"page":null),s||r.removeAttribute("aria-current")}),e){const r=t==="home"?"":`#${t}`;window.location.hash!==r&&window.history.pushState({view:t},"",r||"#")}}let ld=!1;function ic(){const t=window.location.hash.replace(/^#/,"");Ip(t||"home",!1,ld),ld=!0}window.addEventListener("popstate",t=>{ic()});window.addEventListener("hashchange",()=>{ic()});window.copyResultsCode=Kw;window.selectArtifact=nc;window.selectResultsSummary=Ep;window.submitResultsFeedback=Yw;window.showErrorInputPanel=Jw;window.hideErrorInputPanel=Sp;window.setGenerationStageVisible=nn;window.switchView=Ip;window.selectPipelineStage=$w;window.editPipelinePrompt=Ya;window.retryPipelineRun=wp;window.openCreditsModal=Zw;window.closeCreditsModal=Xw; diff --git a/dist/index.html b/dist/index.html index ca74ef4..8dc2762 100644 --- a/dist/index.html +++ b/dist/index.html @@ -3313,7 +3313,7 @@ .send.is-busy .send-spin { animation: none; opacity: 0.6; } } - + diff --git a/e2e/stu380-deploy.spec.js b/e2e/stu380-deploy.spec.js index 281ee57..16c13f2 100644 --- a/e2e/stu380-deploy.spec.js +++ b/e2e/stu380-deploy.spec.js @@ -329,7 +329,8 @@ async function loadDeployHooks(page) { await page.waitForFunction( () => typeof window.__CCC_PROVISION_CUSTOM_CLASSES__ === "function" && - typeof window.__CCC_PUSH_CODE_WITH_RETRY__ === "function", + typeof window.__CCC_PUSH_CODE_WITH_RETRY__ === "function" && + typeof window.__CCC_PUSH_CODE_WITH_TIMEOUT__ === "function", ); } @@ -539,6 +540,67 @@ test.describe("STU-380 transport outcome regressions", () => { expect(outcome.message).toContain("HTTP 502"); }); + test("a push that never answers settles unconfirmed instead of hanging", async ({ page }) => { + await loadDeployHooks(page); + + // The request may have landed even though no response ever arrives, so the + // bounded wait must produce unconfirmed rather than parking the deploy. + const outcome = await page.evaluate(async () => { + window.fetch = () => new Promise(() => {}); + try { + await window.__CCC_PUSH_CODE_WITH_TIMEOUT__( + { project_id: "ff-proj-0007", zipped_custom_code: "eA==" }, + 75, + ); + return { settled: "resolved" }; + } catch (error) { + return { + settled: "rejected", + name: error.name, + outcome: error.outcome, + }; + } + }); + + expect(outcome.settled).toBe("rejected"); + expect(outcome.name).toBe("UnconfirmedDeployError"); + expect(outcome.outcome).toBe("unconfirmed"); + }); + + test("a sync body that stalls mid-read is unconfirmed under the same bound", async ({ page }) => { + await loadDeployHooks(page); + + // Headers arrive and the first bytes flush, then nothing: json() neither + // resolves nor rejects, so without the bound the deploy would hang even + // though the accepted write may already be applied. + const outcome = await page.evaluate(async () => { + const body = new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode('{"succ')); + }, + }); + window.fetch = () => + Promise.resolve(new Response(body, { status: 200 })); + try { + await window.__CCC_PUSH_CODE_WITH_TIMEOUT__( + { project_id: "ff-proj-0007", zipped_custom_code: "eA==" }, + 75, + ); + return { settled: "resolved" }; + } catch (error) { + return { + settled: "rejected", + name: error.name, + outcome: error.outcome, + }; + } + }); + + expect(outcome.settled).toBe("rejected"); + expect(outcome.name).toBe("UnconfirmedDeployError"); + expect(outcome.outcome).toBe("unconfirmed"); + }); + test("a sync response whose body drops mid-read is unconfirmed, not failed", async ({ page }) => { await loadDeployHooks(page); From 0dfb761cb5fe9ffd1f1da8f174a63b27154e99ce Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Sun, 27 Sep 2026 17:25:10 +0000 Subject: [PATCH 08/16] fix(STU-380): keep the HTTP status on a provisioning refusal whose body is unreadable MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A non-2xx response with a body that fails to read reported 'connection dropped' instead of the refusal status — hiding the reason the deploy was refused. The status is already received at that point, so the error now names it (httpRejected/httpStatus were already correct; only the message was wrong). Co-Authored-By: Stuart Gardoll --- .../{index-284-nqdE.js => index-BYdMHYLC.js} | 2 +- dist/index.html | 2 +- src/provisionStream.js | 10 +++++----- src/provisionStream.test.js | 17 +++++++++++++++++ 4 files changed, 24 insertions(+), 7 deletions(-) rename dist/assets/{index-284-nqdE.js => index-BYdMHYLC.js} (99%) diff --git a/dist/assets/index-284-nqdE.js b/dist/assets/index-BYdMHYLC.js similarity index 99% rename from dist/assets/index-284-nqdE.js rename to dist/assets/index-BYdMHYLC.js index 051db0d..1fb5b2a 100644 --- a/dist/assets/index-284-nqdE.js +++ b/dist/assets/index-BYdMHYLC.js @@ -51,7 +51,7 @@ ${d}`,{commentAndStringRanges:g}=Ma(p),m=h.length+1+f;if(Nu(m,g)){l.push(d);cont `),s=$s(n),o=[],a=[];for(const[l,u]of i){const c=s.get(l);if(!c||!c.isScalar||!String(u||"").trim()){a.push(l);continue}const d=" ".repeat(fi(r[c.lineIndex]));r[c.lineIndex]=`${d}${l}: ${gh(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:r.join(` `),overridden:o,skipped:a}}function mh(t){const e=String(t||""),n=[];return e.trim()?(/^name:\s*\S+/m.test(e)||n.push("pubspec.yaml missing name field"),xl(e.split(` `))||n.push("pubspec.yaml missing dependencies section"),hh(e).includes("flutter")||n.push("pubspec.yaml missing Flutter SDK dependency"),{valid:n.length===0,errors:n}):(n.push("pubspec.yaml is empty"),{valid:!1,errors:n})}const q_=">=3.0.0 <4.0.0";function La(t){const e=String(t||"").trim(),n=e[0];return n!=="'"&&n!=='"'||e[e.length-1]!==n?e:e.slice(1,-1).replaceAll(`${n}${n}`,n)}function z_(t=""){const e=Gv(t).filter(n=>!n.startsWith("dart:")&&!n.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function Bu(t,e,n){const i=[];for(const[r,s]of t){if(s.isScalar){e[r]=La(s.constraint);continue}if(s.sourceKey==="sdk"){n.add(r);continue}if(s.sourceKey===null&&s.version){e[r]=La(s.version);continue}i.push(r)}return i}function V_(t){const e=new Set,n={},i={},r=Bu($s(t),n,e);r.push(...Bu(j_(t,"dependency_overrides"),i,e));const s=new Set([...Object.keys(n),...e]),{sdk:o}=ph(t);return{sdkConstraint:La(o)||q_,dependencies:n,overrides:i,sdkPackages:[...e].sort(),availablePackages:s,unrepresentable:r}}function G_(t,e,n){return e.length>0?`${t} imports ${e.join(", ")}, which FlutterFlow only generates once the app is built, so it could not be compiled before the deploy.`:`${t} imports ${n.join(", ")}, which your project's pubspec.yaml does not declare with a version constraint, so it could not be compiled before the deploy.`}function K_(t,e){const{sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s,availablePackages:o,unrepresentable:a}=V_(e),l={sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s},u=[],c=[],d=a.map(f=>`Your project declares ${f} from a source that cannot be reproduced outside it, so the pre-deploy compile check runs against a scratch package graph that omits ${f}. Classes that do not import ${f} directly are still checked, but against that reduced graph, so their transitive package resolution may differ from your project's and the check is approximate for them.`);for(const f of t){const{className:h,content:p}=f,g=wl(p),m=g.filter(S=>a.includes(S));if(m.length>0){c.push({className:h,reason:`${h} was not compiled before deploying: it imports ${m.join(", ")}, which your project declares from a source that cannot be reproduced outside it, so package resolution could not be matched exactly.`});continue}const{unresolvableImports:v}=z_(p),E=g.filter(S=>!o.has(S));if(v.length>0||E.length>0){c.push({className:h,reason:G_(h,v,E)});continue}u.push({fileName:`${yl(h)}.dart`,content:p})}return{manifest:l,sources:u,skipped:c,approximate:d}}function Du(t,e){const n=`${t}${e}`.split(` -`),i=n.pop()??"",r=[];for(const s of n){const o=vh(s);o&&r.push(o)}return{events:r,buffer:i}}function Y_(t){const e=vh(t);return e?[e]:[]}function vh(t){const e=t.trim();if(!e)return null;try{const n=JSON.parse(e);return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}const Xe=Object.freeze({COMMITTED:"committed",PARTIAL:"partial",FAILED:"failed",UNCONFIRMED:"unconfirmed"}),_h=12e4;function yh(t){return t?.unconfirmed===!0||t?.outcome===Xe.UNCONFIRMED?Xe.UNCONFIRMED:t?.partial===!0||t?.outcome===Xe.PARTIAL?Xe.PARTIAL:t?.success===!0?Xe.COMMITTED:Xe.FAILED}class lt extends Error{constructor(e){super(e),this.name="UnconfirmedDeployError",this.outcome=Xe.UNCONFIRMED}}function J_({httpStatus:t}={}){return new lt(`Every FlutterFlow sync endpoint lost its response or ended in a server error${t?` (last: HTTP ${t})`:""} — neither can prove the push was refused, so it may already have been applied. Open the FlutterFlow project to reconcile before retrying.`)}async function Z_(t,e={}){const{onPhase:n,onLog:i}=e;let r=null,s="";const o=l=>{if(l.event==="phase"){l.message&&n&&n(l.message);return}if(l.event==="log"){l.message&&i&&i(l.message);return}r=l};let a=null;try{if(t.body?.getReader){const l=t.body.getReader(),u=new TextDecoder;for(;;){const{done:c,value:d}=await l.read();if(c)break;const f=Du(s,u.decode(d,{stream:!0}));s=f.buffer,f.events.forEach(o)}}else{const l=Du("",await t.text());s=l.buffer,l.events.forEach(o)}}catch(l){a=l}return Y_(s).forEach(o),r?{...r,success:r.success===!0||r.success===void 0&&t.ok,finalResultReceived:!0}:{success:!1,finalResultReceived:!1,httpRejected:!t.ok,httpStatus:t.status,error:a?"The connection to the FlutterFlow deploy runner dropped before it reported a result.":t.ok?"The FlutterFlow deploy runner closed the connection before it finished.":`FlutterFlow custom class provisioning failed (HTTP ${t.status}).`}}function X_(t){return t?.finalResultReceived?yh(t):t?.httpRejected?Xe.FAILED:Xe.UNCONFIRMED}function Q_(){let t=document.getElementById("fx-grid");if(!t)return null;const e=window.matchMedia("(prefers-reduced-motion: reduce)"),n=window.matchMedia("(pointer: none)");let i=t.getContext("webgl2",{alpha:!0,antialias:!1,depth:!1,stencil:!1,premultipliedAlpha:!0,powerPreference:"low-power"}),r=i?null:t.getContext("2d");if(!i&&!r)return null;const s='',o=`#version 300 es +`),i=n.pop()??"",r=[];for(const s of n){const o=vh(s);o&&r.push(o)}return{events:r,buffer:i}}function Y_(t){const e=vh(t);return e?[e]:[]}function vh(t){const e=t.trim();if(!e)return null;try{const n=JSON.parse(e);return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}const Xe=Object.freeze({COMMITTED:"committed",PARTIAL:"partial",FAILED:"failed",UNCONFIRMED:"unconfirmed"}),_h=12e4;function yh(t){return t?.unconfirmed===!0||t?.outcome===Xe.UNCONFIRMED?Xe.UNCONFIRMED:t?.partial===!0||t?.outcome===Xe.PARTIAL?Xe.PARTIAL:t?.success===!0?Xe.COMMITTED:Xe.FAILED}class lt extends Error{constructor(e){super(e),this.name="UnconfirmedDeployError",this.outcome=Xe.UNCONFIRMED}}function J_({httpStatus:t}={}){return new lt(`Every FlutterFlow sync endpoint lost its response or ended in a server error${t?` (last: HTTP ${t})`:""} — neither can prove the push was refused, so it may already have been applied. Open the FlutterFlow project to reconcile before retrying.`)}async function Z_(t,e={}){const{onPhase:n,onLog:i}=e;let r=null,s="";const o=l=>{if(l.event==="phase"){l.message&&n&&n(l.message);return}if(l.event==="log"){l.message&&i&&i(l.message);return}r=l};let a=null;try{if(t.body?.getReader){const l=t.body.getReader(),u=new TextDecoder;for(;;){const{done:c,value:d}=await l.read();if(c)break;const f=Du(s,u.decode(d,{stream:!0}));s=f.buffer,f.events.forEach(o)}}else{const l=Du("",await t.text());s=l.buffer,l.events.forEach(o)}}catch(l){a=l}return Y_(s).forEach(o),r?{...r,success:r.success===!0||r.success===void 0&&t.ok,finalResultReceived:!0}:{success:!1,finalResultReceived:!1,httpRejected:!t.ok,httpStatus:t.status,error:t.ok?a?"The connection to the FlutterFlow deploy runner dropped before it reported a result.":"The FlutterFlow deploy runner closed the connection before it finished.":`FlutterFlow custom class provisioning failed (HTTP ${t.status}).`}}function X_(t){return t?.finalResultReceived?yh(t):t?.httpRejected?Xe.FAILED:Xe.UNCONFIRMED}function Q_(){let t=document.getElementById("fx-grid");if(!t)return null;const e=window.matchMedia("(prefers-reduced-motion: reduce)"),n=window.matchMedia("(pointer: none)");let i=t.getContext("webgl2",{alpha:!0,antialias:!1,depth:!1,stencil:!1,premultipliedAlpha:!0,powerPreference:"low-power"}),r=i?null:t.getContext("2d");if(!i&&!r)return null;const s='',o=`#version 300 es in vec2 p; void main(){ gl_Position = vec4(p, 0.0, 1.0); }`;function a(){return["#version 300 es","precision highp float;","out vec4 o;","uniform vec2 res;","uniform vec2 design;","uniform vec2 mouse;","uniform float energy;","uniform float parallax;","uniform float t;","uniform vec3 ink;","uniform sampler2D mark;","uniform vec2 rot;","const float WARP_A = 0.0032;","void main(){"," vec2 px = gl_FragCoord.xy * (design / res);"," vec2 p = vec2(px.x, design.y - px.y);"," vec2 off = vec2(0.0, -parallax) + vec2(sin(t * 0.11), cos(t * 0.09)) * 7.0;"," vec2 g = p + off;"," vec2 gm = mouse + off;"," float base = min(design.x, design.y);"," float spacing = clamp(base / 10.0, 64.0, 118.0);"," vec2 rel = g - gm;"," float rho = length(rel) + 1e-5;"," vec2 dir = rel / rho;"," vec2 pw = gm + dir * (rho + WARP_A * rho * rho);"," vec2 cell = floor(pw / spacing);"," vec2 cw = (cell + 0.5) * spacing - gm;"," float Rc = length(cw) + 1e-5;"," float rhoC = (-1.0 + sqrt(1.0 + 4.0 * WARP_A * Rc)) / (2.0 * WARP_A);"," vec2 c = gm + (cw / Rc) * rhoC;"," float cellSize = spacing / (1.0 + 2.0 * WARP_A * rhoC);"," float sigma = spacing * 2.9;"," float f = exp(-(rhoC * rhoC) / (2.0 * sigma * sigma));"," float scale = mix(0.32, 1.42, f);"," float weight = smoothstep(0.06, 0.80, f);"," float hs = cellSize * 0.26 * scale;"," vec2 uv = (g - c) / hs;"," vec2 ruv = mat2(rot.x, rot.y, -rot.y, rot.x) * uv;"," float cov = 0.0;"," if (abs(ruv.x) <= 1.0 && abs(ruv.y) <= 1.0) cov = texture(mark, ruv * 0.5 + 0.5).a;"," float s = cov * weight * energy * 0.26;"," o = vec4(ink * s, s);","}"].join(` `)}let l=null,u,c,d,f,h,p,g,m,v;function E(Y,W){if(!i)return null;const D=i.createShader(Y);return i.shaderSource(D,W),i.compileShader(D),i.getShaderParameter(D,i.COMPILE_STATUS)?D:(window.console&&console.warn("fx-grid shader: "+i.getShaderInfoLog(D)),null)}if(i){const Y=E(i.VERTEX_SHADER,o),W=E(i.FRAGMENT_SHADER,a());if(Y&&W&&(l=i.createProgram(),i.attachShader(l,Y),i.attachShader(l,W),i.linkProgram(l),i.getProgramParameter(l,i.LINK_STATUS)||(window.console&&console.warn("fx-grid link: "+i.getProgramInfoLog(l)),l=null)),l){i.useProgram(l),i.bindBuffer(i.ARRAY_BUFFER,i.createBuffer()),i.bufferData(i.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),i.STATIC_DRAW);const D=i.getAttribLocation(l,"p");i.enableVertexAttribArray(D),i.vertexAttribPointer(D,2,i.FLOAT,!1,0,0),u=i.getUniformLocation(l,"res"),c=i.getUniformLocation(l,"design"),d=i.getUniformLocation(l,"mouse"),f=i.getUniformLocation(l,"energy"),h=i.getUniformLocation(l,"parallax"),p=i.getUniformLocation(l,"t"),g=i.getUniformLocation(l,"ink"),m=i.getUniformLocation(l,"mark"),v=i.getUniformLocation(l,"rot"),i.enable(i.BLEND),i.blendFunc(i.ONE,i.ONE_MINUS_SRC_ALPHA),i.clearColor(0,0,0,0)}else{i=null;const D=t.cloneNode(!1);if(t.parentNode.replaceChild(D,t),t=D,r=t.getContext("2d"),!r)return null}}function S(Y){if(!Y)return null;const W=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(Y);if(W){let D=W[1];return D.length===3&&(D=D[0]+D[0]+D[1]+D[1]+D[2]+D[2]),[parseInt(D.slice(0,2),16)/255,parseInt(D.slice(2,4),16)/255,parseInt(D.slice(4,6),16)/255]}try{const D=document.createElement("canvas");D.width=1,D.height=1;const ue=D.getContext("2d");ue.fillStyle="rgb(9, 8, 7)";const xe=String(ue.fillStyle);ue.fillStyle=Y;const Fe=String(ue.fillStyle);if(Fe===xe)return null;const dt=/^#([0-9a-f]{6})$/i.exec(Fe);if(dt){const ft=dt[1];return[parseInt(ft.slice(0,2),16)/255,parseInt(ft.slice(2,4),16)/255,parseInt(ft.slice(4,6),16)/255]}const Nt=/rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i.exec(Fe);if(Nt)return[Number(Nt[1])/255,Number(Nt[2])/255,Number(Nt[3])/255]}catch{}return null}function _(){let Y="";try{const W=getComputedStyle(document.documentElement);Y=(W.getPropertyValue("--fx-ink")||"").trim()||(W.getPropertyValue("--fg")||"").trim()}catch{}return S(Y)||[.56,.68,.88]}const b=_();let k=1920,T=1080,x=960,F=540,$=960,O=540,L=.66,N=0,K=-1e9,V=!1,M=0,R=0,Z=null,Ce=!1,oe=!1,ye=!1;const $e=64,ae=15.2;let Ie=0,Se=0;const Be=.0032,wt=0,ge=.56,Ye=.26,bt=.32,mn=.16,Re=.349;let Pe=wt;function $t(){const Y=t.getBoundingClientRect(),W=t.clientWidth,D=t.clientHeight;if(!Y.width||!W||!D)return;const ue=Math.min(window.devicePixelRatio||1,2),xe=Math.max(.2,Math.min(2,Y.width/W*ue)),Fe=Math.max(2,Math.round(W*xe)),dt=Math.max(2,Math.round(D*xe));(Fe!==t.width||dt!==t.height)&&(t.width=Fe,t.height=dt,i&&i.viewport(0,0,Fe,dt)),k=W,T=D,V||(x=$=k/2,F=O=T/2,V=!0)}function Bn(Y){!l||!Ce||!i||(i.uniform2f(u,t.width,t.height),i.uniform2f(c,k,T),i.uniform2f(d,x,F),i.uniform1f(f,L),i.uniform1f(h,N),i.uniform2f(v,Math.cos(Pe),Math.sin(Pe)),i.uniform1f(p,Y),i.uniform3f(g,b[0],b[1],b[2]),i.clear(i.COLOR_BUFFER_BIT),i.drawArrays(i.TRIANGLES,0,3))}function qe(Y,W,D){const ue=Math.max(0,Math.min(1,(D-Y)/(W-Y)));return ue*ue*(3-2*ue)}function Dn(Y){if(!Z||!r)return;const W=r;W.setTransform(1,0,0,1,0,0),W.clearRect(0,0,t.width,t.height);const D=t.width/k;W.setTransform(D,0,0,D,0,0),W.globalAlpha=1;const ue=Math.min(k,T),xe=Math.max(64,Math.min(118,ue/10)),Fe=xe*2.9,dt=2*Fe*Fe,Nt=Math.sin(Y*.11)*7,ft=Math.cos(Y*.09)*7-N,dr=x+Nt,fr=F+ft,no=Fe*Math.sqrt(2*Math.log(1/.06)),mi=no+Be*no*no+xe,Cp=Math.floor((dr-mi)/xe)-1,Ap=Math.ceil((dr+mi)/xe)+1,Pp=Math.floor((fr-mi)/xe)-1,Fp=Math.ceil((fr+mi)/xe)+1;for(let io=Pp;io<=Fp;io++){const Rp=(io+.5)*xe;for(let ro=Cp;ro<=Ap;ro++){const so=(ro+.5)*xe-dr,oo=Rp-fr,ao=Math.sqrt(so*so+oo*oo)+1e-5;if(ao>mi)continue;const hr=(-1+Math.sqrt(1+4*Be*ao))/(2*Be),ac=Math.exp(-(hr*hr)/dt),lc=qe(.06,.8,ac)*L*.26;if(lc<.004)continue;const on=xe/(1+2*Be*hr)*.26*(.32+1.1*ac),cc=hr/ao,lo=dr+so*cc,co=fr+oo*cc;lo<-on*1.6||lo>k+on*1.6||co<-on*1.6||co>T+on*1.6||(W.globalAlpha=lc,W.save(),W.translate(lo,co),W.rotate(Pe),W.drawImage(Z,-on,-on,on*2,on*2),W.restore())}}W.globalAlpha=1}function Mt(Y){if(!oe)return;const W=R?Math.min(.05,(Y-R)/1e3):.016;R=Y;const ue=Y-K>2400?.6:1;L+=(ue-L)*Math.min(1,W*3.2);const xe=Math.min(.05,W);Ie+=(($-x)*$e-Ie*ae)*xe,Se+=((O-F)*$e-Se*ae)*xe,x+=Ie*xe,F+=Se*xe,N=(window.scrollY||window.pageYOffset||0)*.55;const Fe=Y/1e3,dt=x/(k||1)-.5,Nt=F/(T||1)-.5;let ft=dt*(dt>=0?ge:Ye)+Nt*(Nt>=0?bt:mn);ft>Re?ft=Re:ft<-Re&&(ft=-Re),Pe=wt+ft-N*6e-4,$t(),i?Bn(Fe):Dn(Fe),M=requestAnimationFrame(Mt)}function Lt(Y){if(!oe)return;const W=t.getBoundingClientRect();!W.width||!k||!T||($=(Y.clientX-W.left)/W.width*k,O=(Y.clientY-W.top)/W.height*T,K=performance.now())}function ut(){oe||to||e.matches||n.matches||!ye||document.hidden||(oe=!0,R=0,M=requestAnimationFrame(Mt))}function sn(){oe=!1,M&&(cancelAnimationFrame(M),M=0),R=0}function gi(){e.matches?(sn(),t.classList.remove("is-ready")):ye&&ut()}function jn(){n.matches?sn():ye&&ut()}function rc(){document.hidden?sn():ye&&ut()}const sc=new IntersectionObserver(Y=>{ye=Y[0]?.isIntersecting||!1,ye?ut():sn()},{threshold:0});sc.observe(t),window.addEventListener("pointermove",Lt,{passive:!0,capture:!0}),window.addEventListener("resize",$t),e.addEventListener("change",gi),n.addEventListener("change",jn),document.addEventListener("visibilitychange",rc);function kp(){const Y=(s.match(/\sd="([^"]+)"/)||[])[1],W=document.createElement("canvas");W.width=256,W.height=256;const D=W.getContext("2d");if(Y&&window.Path2D){const ue=Math.min(8.533333333333333,8.421052631578947);D.setTransform(ue,0,0,ue,ue+(256-30*ue)/2,-6.4*ue),D.fillStyle="rgb(255,255,255)",D.fill(new Path2D(Y),"evenodd"),D.setTransform(1,0,0,1,0,0)}try{const ue=D.getImageData(0,0,256,256),xe=ue.data;for(let Fe=3;Feoe}}const ey=120;function ty(t,e,n){return tn?n:t}function de(t,e,n){return ty((t-e)/(n-e),0,1)}function ny(t){return t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2}function Uo(t){return 1-Math.pow(1-t,3)}function ze(t,e){return e=e===void 0?1.7:e,1+(e+1)*Math.pow(t-1,3)+e*Math.pow(t-1,2)}function ju(t){return 1-Math.pow(2,-9*t)*Math.cos(t*15)}function te(t,e){if(t<=e[0].t)return e[0].v;for(let n=1;n8.2&&_<9.4&&(s*=1-.07*Math.sin(de(_,8.2,9.4)*Math.PI))}else if(t<53){const _=t-42;g=te(_,[{t:0,v:1},{t:2,v:0},{t:4.2,v:0},{t:4.6,v:1},{t:6.8,v:1},{t:7.4,v:0},{t:9.4,v:0},{t:10.6,v:1}]),p=te(_,[{t:0,v:1},{t:2,v:.3},{t:4.6,v:1,e:ze}]),d=te(_,[{t:0,v:0},{t:2,v:.3},{t:4.6,v:.16,e:ze},{t:10.6,v:0}]),h=te(_,[{t:0,v:0},{t:2,v:-40},{t:4.6,v:0,e:ze}]),o=te(_,[{t:0,v:0},{t:4.6,v:-.12},{t:10.6,v:0}])}else if(t<60){const _=t-53;c=te(_,[{t:0,v:1},{t:.35,v:0},{t:.45,v:0},{t:.7,v:1}]);const b=de(_,.45,2.2);a=b>0?-2.6*(1-ju(b)):0,g=te(_,[{t:0,v:1},{t:.57,v:0},{t:.67,v:0},{t:.92,v:1}]);const k=de(_,.67,2.42);f=k>0?-2.6*(1-ju(k)):0,s=1-.05*(Math.sin(de(_,1.9,2.5)*Math.PI)+Math.sin(de(_,2.5,3.1)*Math.PI))}else if(t<74){let b=function(F){return[te(F,[{t:0,v:0},{t:.25,v:1},{t:.5,v:1},{t:.72,v:.14},{t:.82,v:.14},{t:1,v:0}]),te(F,[{t:0,v:0},{t:.08,v:-.62},{t:.25,v:-.62},{t:.33,v:.62},{t:.7,v:.62},{t:.82,v:-.62},{t:1,v:-.62}])]};var S=b;const _=t-60,k=1-de(_,12,14),T=b(de(_,0,12)),x=b(de(_-.5,0,12));n=T[0]*k,i=(T[1]+.05*Math.sin(_*7))*k,o=(x[0]-T[0])*.6*k,a=(x[1]-T[1])*.6*k,h=(x[0]-T[0])*30*k,E=de(_,0,.4)*k}else if(t<85.4){const _=t-74,b=te(_,[{t:0,v:0},{t:4,v:1},{t:8,v:.24},{t:9.6,v:1,e:ze},{t:11.4,v:0}]);o=b*.5,d=-b*.5,l=te(_,[{t:0,v:0},{t:4,v:6},{t:8,v:20},{t:9.6,v:38,e:ze},{t:11.4,v:0}]),h=-l*.7,a=te(_,[{t:0,v:0},{t:8,v:0},{t:9.6,v:.4},{t:11.4,v:0}])}else if(t<96.4){const _=t-85.4,b=de(_,0,5.6),k=de(_,5.6,7.6),T=.72*Math.min(1,_/.6)*(1-k);d=Math.cos(b*Math.PI*2)*T,f=Math.sin(b*Math.PI*2)*T*.55,h=b*360*(1-k);const x=te(_,[{t:0,v:0},{t:7.6,v:0},{t:8.2,v:1,e:Uo},{t:8.6,v:.55},{t:9.4,v:0}]);o=-.16*x,d+=.16*x,l=-6*x,h+=6*x,s=1+.05*x,m=1+.9*x}else if(t<108.6){const _=t-96.4,b=de(_,9.6,12.2);n=te(_,[{t:0,v:0},{t:2.1,v:1},{t:4.8,v:.08},{t:7.5,v:1},{t:9.6,v:0}])*(1-b),i=-.35*Math.abs(Math.sin(de(_,0,9.6)*Math.PI*3))*(1-b);const k=Math.sin(_*6.2)*(1-b);u=1+.12*k,p=1-.12*k,l=k*8,h=-k*8,o=.06*k,d=-.06*k,E=de(_,0,.4)*(1-b)}else{const _=t-108.6,b=Math.sin(de(_,0,8)*Math.PI),k=1-de(_,8,11.4);s=1+.04*b*k,i=-.1*b*k,r=2*b*k,m=1+.5*Math.sin(de(_,0,6)*Math.PI),v=1+.1*Math.sin(de(_,0,6)*Math.PI)}return e.x=n,e.y=i,e.rot=r,e.scale=s,e.ax=o,e.ay=a,e.ar=l,e.asc=u,e.afade=c,e.bx=d,e.by=f,e.br=h,e.bsc=p,e.bfade=g,e.hfade=m,e.hsc=v,e.shd=E,e}function iy(t={}){const e=t.arena||document.querySelector(".pipeline-glyph.logo-loop");if(!e)return null;const n=e.querySelector(".loop-mark"),i=e.querySelector(".loop-piece-a"),r=e.querySelector(".loop-piece-b"),s=e.querySelector(".loop-halo"),o=e.querySelector(".loop-shadow");if(!n||!i||!r||!s||!o)return null;const a=t.reducedMotion||window.matchMedia("(prefers-reduced-motion: reduce)"),l=ey;let u=34,c=0,d=0;function f(){u=n.offsetWidth||34,c=Math.max(0,e.offsetWidth-u-4),d=Math.max(0,(e.offsetHeight-u)/2-2),e.style.setProperty("--mark-c",u/2+"px")}function h(M){const R=Math.min(1,Math.max(0,M.x))*c,Z=M.y*d;n.style.transform="translate3d("+R.toFixed(2)+"px,"+Z.toFixed(2)+"px,0) rotate("+M.rot.toFixed(2)+"deg) scale("+M.scale.toFixed(3)+")",i.style.transform="translate3d("+(M.ax*u).toFixed(2)+"px,"+(M.ay*u).toFixed(2)+"px,0) rotate("+M.ar.toFixed(2)+"deg) scale("+M.asc.toFixed(3)+")",i.style.opacity=M.afade.toFixed(3),r.style.transform="translate3d("+(M.bx*u).toFixed(2)+"px,"+(M.by*u).toFixed(2)+"px,0) rotate("+M.br.toFixed(2)+"deg) scale("+M.bsc.toFixed(3)+")",r.style.opacity=M.bfade.toFixed(3),s.style.transform="scale("+M.hsc.toFixed(3)+")",s.style.opacity=(.09*M.hfade).toFixed(3),o.style.transform="translateX("+R.toFixed(2)+"px) scaleX("+(.75+.4*Math.abs(M.x)).toFixed(3)+")",o.style.opacity=(M.shd*.5).toFixed(3)}let p=0,g=0,m=0,v=!1,E=!1,S=!1,_=0;function b(){return S||a.matches||document.hidden||!e.offsetParent?!1:E}function k(M){if(!v)return;if(m=requestAnimationFrame(k),!b()){x();return}const R=g?(M-g)/1e3:0;g=M,p=(p+Math.min(R,.1))%l,_+=1,h(Ai(p))}function T(){v||S||b()&&(v=!0,g=0,m=requestAnimationFrame(k))}function x(){v=!1,m&&(cancelAnimationFrame(m),m=0),g=0}function F(){b()?T():x()}function $(){a.matches?(x(),h(Ai(0))):F()}function O(){f(),v&&h(Ai(p))}function L(){g=0,F()}const N=new IntersectionObserver(M=>{E=M[0]?M[0].isIntersecting:!1,F()},{threshold:0});N.observe(e),window.addEventListener("resize",O),a.addEventListener("change",$),document.addEventListener("visibilitychange",L);function K(){S||(S=!0,x(),N.disconnect(),window.removeEventListener("resize",O),a.removeEventListener("change",$),document.removeEventListener("visibilitychange",L))}window.addEventListener("pagehide",K);function V(M){p=(M%l+l)%l,h(Ai(p))}return f(),h(Ai(0)),F(),{isRunning:()=>v,currentTime:()=>p,frameCount:()=>_,seek:V,dispose:K}}const ry=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function Xt(t){const e=String(t||"").trim().match(ry);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function sy(t,e){if(t.length===0&&e.length===0)return 0;if(t.length===0)return 1;if(e.length===0)return-1;for(let n=0;n0)}function ay(t){const e=Xt(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function Il(t){let e=String(t??"").trim();if((e.startsWith("'")||e.startsWith('"'))&&(e=e.slice(1,-1).trim()),e===""||e==="any"||e==="*")return{min:null,minInclusive:!1,max:null,maxInclusive:!1};if(e.startsWith("^")){const o=e.slice(1).trim();return Xt(o)?{min:o,minInclusive:!0,max:ay(o),maxInclusive:!1}:null}if(Xt(e))return{min:e,minInclusive:!0,max:e,maxInclusive:!0};const n={min:null,minInclusive:!1,max:null,maxInclusive:!1},i=/(>=|<=|>|<)\s*([0-9][0-9A-Za-z.+-]*)/g;let r=!1,s;for(;(s=i.exec(e))!==null;){const[,o,a]=s;if(!Xt(a))return null;r=!0,o===">="||o===">"?(n.min=a,n.minInclusive=o===">="):(n.max=a,n.maxInclusive=o==="<=")}return r?n:null}function Uu(t,e){const n=Il(t);if(!n||!Xt(e))return!1;if(n.min!==null){const i=fs(e,n.min);if(i<0||i===0&&!n.minInclusive)return!1}if(n.max!==null){const i=fs(e,n.max);if(i>0||i===0&&!n.maxInclusive)return!1}return!0}function ly(t,e){const n=Il(t);if(!n||!Xt(e))return!1;if(n.max===null)return!0;const i=fs(n.max,e);return i>0?!0:i===0&&n.maxInclusive}function zn(t){const e=Il(t);return e?e.min:null}const cy="https://pub.dev/api/packages/",uy=8e3;function dy(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null}=e,r=Array.isArray(t?.versions)?t.versions:[];let s=null;for(const o of r){const a=o?.version;if(!a||o.retracted||oy(a))continue;const l=o.pubspec?.environment||{};n&&l.sdk&&!Uu(l.sdk,n)||i&&l.flutter&&!Uu(l.flutter,i)||(!s||fs(a,s)>0)&&(s=a)}return s?{version:s,constraint:`^${s}`}:null}async function fy(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null,fetchImpl:r=fetch}=e;let s;try{const a=await r(`${cy}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(uy)});if(!a.ok)return{name:t,constraint:null,version:null,error:a.status===404?`"${t}" was not found on pub.dev`:`pub.dev returned ${a.status} for "${t}"`};s=await a.json()}catch(a){return{name:t,constraint:null,version:null,error:`could not reach pub.dev for "${t}" (${a.message})`}}const o=dy(s,{dartSdkFloor:n,flutterSdkFloor:i});return o?{name:t,...o,error:null}:{name:t,constraint:null,version:null,error:n?`no published "${t}" release supports Dart ${n}`:`no published "${t}" release could be read`}}async function hy(t,e={}){const n=await Promise.all(t.map(i=>fy(i,e)));return new Map(n.map(({name:i,...r})=>[i,r]))}async function py(t,e={},n={}){const{resolveVersions:i=hy}=n,r=Object.entries(e).filter(([c])=>c&&c!=="flutter"),s=ph(t),o={dartSdkFloor:zn(s.sdk),flutterSdkFloor:zn(s.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(r.length===0)return a;const l=$s(t),u=[];for(const[c,d]of r){const f=l.get(c);if(!f){u.push(c);continue}const h=zn(d);if(!h){a.kept.push({name:c,constraint:f.constraint});continue}if(!f.isScalar){a.warnings.push(`"${c}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${h}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:c,constraint:f.constraint});continue}if(ly(f.constraint,h)){a.kept.push({name:c,constraint:f.constraint});continue}a.overrides[c]=`^${h}`,a.warnings.push(`"${c}" was pinned to ${f.constraint} in your project, which cannot resolve the ${h} the generated code needs. Raising it to ^${h} — this changes a dependency the rest of your app also uses.`)}if(u.length>0){const c=await i(u,o);for(const d of u){const f=c.get(d);if(f?.constraint){a.additions[d]=f.constraint;continue}const h=e[d]||"";if(zn(h)){a.additions[d]=`^${zn(h)}`,a.warnings.push(`Could not confirm "${d}" version on pub.dev (${f?.error||"lookup failed"}). Using ^${zn(h)} from the AI's recommendation — verify this is current.`);continue}a.additions[d]=">=0.0.0",a.warnings.push(`Could not determine a version for "${d}" (${f?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const gy={"&":"&","<":"<",">":">",'"':""","'":"'"};function Qt(t){return String(t??"").replace(/[&<>"']/g,e=>gy[e])}function q(t){return t?Qt(t).replace(/\n/g,"
    "):""}function Jt(t){return Qt(t).replace(/\r?\n/g," ")}function Ms(t,e={}){const n=t?.pipelineStep;if(n!=null&&e[n]!=null)return e[n];const i=t?.message||"";return i.includes("Code Generator")?2:i.includes("Code Review")?3:1}function bh(t){if(!t)return{kind:"generic",title:"Generation failed",message:"An unknown error occurred. Please try again.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1};if(t.isModelArmor){const n=t.code==="MODEL_ARMOR_BLOCKED";return{kind:"safety",title:t.userTitle||"Request blocked for safety",message:t.userMessage||t.message,detail:t.retryExplanation||"",canRetry:!n,canEdit:!0,canUpgrade:!1}}if(t.isUsageLimit)return{kind:"quota",title:"Monthly limit reached",message:t.message||"You've used all your generations for this period.",detail:"",canRetry:!1,canEdit:!1,canUpgrade:!0};const e=t.message||"";return/timed out after/i.test(e)?{kind:"timeout",title:"Request timed out",message:"The generation service took too long to respond.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:/unreachable|failed to fetch|load failed|cors/i.test(e)?{kind:"network",title:"Connection problem",message:"We couldn't reach the generation service. Check your connection and try again.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:{kind:"generic",title:"Generation failed",message:e||"An unexpected error occurred.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1}}function my(t){const e={"Integration Audit Report":"📋","Critical Issues":"❌",Warnings:"⚠️",Recommendations:"✅","Overall Score":"📊"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📄"}function vy(t){const e={critical:"❌",warning:"⚠️",recommendation:"✅",score:"📊",issue:"🔍",fix:"🔧"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📝"}function _y(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 li(t){if(!t)return"";if(typeof t!="string")return String(t);const e=/```(?:\w+)?\n?([\s\S]*?)```/,n=t.match(e);return n?n[1].trim():t.trim()}function Hu(t){return t=Qt(t),t=t.replace(/\*\*(.*?)\*\*/g,'$1'),t=t.replace(/\*(.*?)\*/g,'$1'),t=t.replace(/`(.*?)`/g,'$1'),t=t.replace(/\b(FAIL|ERROR|CRITICAL)\b/g,'$1'),t=t.replace(/\b(WARN|WARNING)\b/g,'$1'),t=t.replace(/\b(PASS|SUCCESS|OK)\b/g,'$1'),t}function Eh(t,e="dart",n=globalThis.hljs){if(!t)return"";const i=li(t);try{return n.highlight(i,{language:e}).value}catch(r){console.warn("Syntax highlighting failed:",r);try{return n.highlight(i,{language:"json"}).value}catch{return Qt(i)}}}function Ls(t,e={}){const{highlighter:n=globalThis.hljs}=e;let i='
    ';const r=String(t??"").split(` `);let s=!1,o="";for(const a of r){if(a.startsWith("```")){if(s){const l=_y(o),u=Eh(o.trim(),l,n);i+=`
    diff --git a/dist/index.html b/dist/index.html index 8dc2762..f999c8a 100644 --- a/dist/index.html +++ b/dist/index.html @@ -3313,7 +3313,7 @@ .send.is-busy .send-spin { animation: none; opacity: 0.6; } } - + diff --git a/src/provisionStream.js b/src/provisionStream.js index d5844df..dea687a 100644 --- a/src/provisionStream.js +++ b/src/provisionStream.js @@ -95,11 +95,11 @@ export async function readProvisionResponse(response, handlers = {}) { // remote write. httpRejected: !response.ok, httpStatus: response.status, - error: readError - ? "The connection to the FlutterFlow deploy runner dropped before it reported a result." - : response.ok - ? "The FlutterFlow deploy runner closed the connection before it finished." - : `FlutterFlow custom class provisioning failed (HTTP ${response.status}).`, + error: !response.ok + ? `FlutterFlow custom class provisioning failed (HTTP ${response.status}).` + : readError + ? "The connection to the FlutterFlow deploy runner dropped before it reported a result." + : "The FlutterFlow deploy runner closed the connection before it finished.", }; } diff --git a/src/provisionStream.test.js b/src/provisionStream.test.js index 734da45..a440767 100644 --- a/src/provisionStream.test.js +++ b/src/provisionStream.test.js @@ -138,6 +138,23 @@ test("a 403 with no streamed result is surfaced as an explicit HTTP rejection", assert.match(result.error, /HTTP 403/); }); +test("a refusal whose body is unreadable still reports its HTTP status", async () => { + const body = new ReadableStream({ + start(controller) { + controller.error(new Error("connection reset")); + }, + }); + const result = await readProvisionResponse( + new Response(body, { status: 403 }), + ); + + // An unreadable body must not reclassify a received refusal as a dropped + // connection — the status was delivered and still names the reason. + assert.equal(result.httpRejected, true); + assert.equal(result.httpStatus, 403); + assert.match(result.error, /HTTP 403/); +}); + test("an explicit HTTP rejection (403) is a failure, not unconfirmed", async () => { const result = await readProvisionResponse( provisionAtStatus( From de67238557b16ec14f13bd6b242572179e8f44a0 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Sun, 27 Sep 2026 17:34:18 +0000 Subject: [PATCH 09/16] fix(STU-380): stop retries after UI timeout; label failure terminal correctly MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - pushCodeWithUiTimeout hands the retry loop a stopToken set on expiry: a request already in flight is left to settle, but no further attempts may start — they could overlap a deploy the user just retried. - Definitive remote decisions (push refusal, provisioning non-2xx, runner failure result) are marked remoteRefusal=true and carried onto the result; showCommitFailureModal only says 'FlutterFlow refused' for those. Local failures (credentials, validation, compile gate) get a pre-write title instead — still truthful that nothing was applied. Co-Authored-By: Stuart Gardoll --- app.js | 62 ++++++++--- .../{index-BYdMHYLC.js => index-DbNvpST8.js} | 102 +++++++++--------- dist/index.html | 2 +- e2e/stu380-deploy.spec.js | 49 ++++++++- 4 files changed, 148 insertions(+), 67 deletions(-) rename dist/assets/{index-BYdMHYLC.js => index-DbNvpST8.js} (78%) diff --git a/app.js b/app.js index a0fc905..75b6db5 100644 --- a/app.js +++ b/app.js @@ -2162,7 +2162,7 @@ class FlutterFlowApiClient { * @param {string} pushCodeRequest.functions_map - JSON string of function definitions * @returns {Promise} Fetch response object */ - async pushCodeWithRetry(pushCodeRequest, maxRetries = 3) { + async pushCodeWithRetry(pushCodeRequest, maxRetries = 3, stopToken = null) { const endpointUrls = [ FF_API_ENDPOINTS.production, FF_API_ENDPOINTS.staging, @@ -2179,6 +2179,14 @@ class FlutterFlowApiClient { for (let ei = startEndpoint; ei < endpointUrls.length; ei++) { const baseUrl = endpointUrls[ei]; + // Once the UI bound expired, the outcome was already reported + // unconfirmed and the user may have started a new deploy — issuing + // another write would overlap it. An in-flight request is never + // aborted; this only stops attempts not yet sent. + if (stopToken?.stop) { + throw exhaustedPushError({ httpStatus: lastHttpStatus }); + } + // Only a fetch rejection is a lost response: once headers arrive, a // refusal status is a definitive answer for this endpoint — and a body // that fails to read for logging must not reclassify one as a lost @@ -2271,8 +2279,8 @@ class FlutterFlowApiClient { throw exhaustedPushError({ httpStatus: lastHttpStatus }); } - async pushCode(pushCodeRequest) { - return this.pushCodeWithRetry(pushCodeRequest); + async pushCode(pushCodeRequest, stopToken = null) { + return this.pushCodeWithRetry(pushCodeRequest, 3, stopToken); } /** @@ -2663,20 +2671,27 @@ async function pushCodeWithUiTimeout( pushRequest, uiTimeoutMs = DEPLOY_UI_TIMEOUT_MS, ) { + // Tells the retry loop to stop issuing writes once the bound expires: an + // in-flight request is left to settle on its own (its late result is + // ignored), but no further attempts may start — they could overlap a deploy + // the user just retried. + const stopToken = { stop: false }; return withUiTimeout( (async () => { - const response = await apiClient.pushCode(pushRequest); + const response = await apiClient.pushCode(pushRequest, stopToken); return parsePushCodeResponse(response); })(), uiTimeoutMs, - (resolve, reject) => + (resolve, reject) => { + stopToken.stop = true; reject( new UnconfirmedDeployError( "FlutterFlow did not answer the sync in time — the push may still " + "have been applied. The outcome is not yet known: open your " + "FlutterFlow project to reconcile before retrying the deploy.", ), - ), + ); + }, ); } @@ -2790,10 +2805,12 @@ async function provisionMissingCodeFiles( // remote state genuinely unknown and must be reported UNCONFIRMED. if (!result.finalResultReceived) { if (deployOutcomeOfStreamResult(result) === DeployOutcome.FAILED) { - throw new Error( + const refusal = new Error( result.error || `FlutterFlow custom class provisioning failed (HTTP ${result.httpStatus}).`, ); + refusal.remoteRefusal = true; + throw refusal; } throw new UnconfirmedDeployError( "The connection to the FlutterFlow deploy runner dropped before it reported a result. " + @@ -2814,9 +2831,13 @@ async function provisionMissingCodeFiles( if (!result.success) { const details = result.details ? ` ${result.details}` : ""; - throw new Error( + // The runner streamed a definitive failure result — a remote decision, + // not a local one. + const refusal = new Error( `${result.error || "FlutterFlow custom class provisioning failed."}${details}`, ); + refusal.remoteRefusal = true; + throw refusal; } invalidateProjectSourceCache(apiClient); @@ -3518,7 +3539,9 @@ async function commitToFlutterFlow(dartCode, fileName, options = {}) { } else { const errorMsg = result.errorMessage || getFlutterFlowErrorMessage(result.responseCode); - throw new Error(errorMsg); + const refusal = new Error(errorMsg); + refusal.remoteRefusal = true; + throw refusal; } return { @@ -3547,6 +3570,7 @@ async function commitToFlutterFlow(dartCode, fileName, options = {}) { return { success: false, error: error.message, + remoteRefusal: error.remoteRefusal === true, state: commitState.currentState, }; } @@ -3737,6 +3761,7 @@ async function executeCommit(code, options = {}) { result.errorMessage || getFlutterFlowErrorMessage(result.responseCode); const errorWithMap = new Error(errorMsg); errorWithMap.errorMap = result.errorMap; + errorWithMap.remoteRefusal = true; throw errorWithMap; } } catch (error) { @@ -3792,6 +3817,7 @@ async function executeCommit(code, options = {}) { success: false, error: error.message, errorMap: errorMap, + remoteRefusal: error.remoteRefusal === true, targetIdentity, state: commitState.currentState, elapsedTime: commitState.getElapsedTime(), @@ -3947,6 +3973,7 @@ async function executeBundleCommit(bundlePlan, options = {}) { const errorMsg = result.errorMessage || getFlutterFlowErrorMessage(result.responseCode); const errorWithMap = new Error(errorMsg); errorWithMap.errorMap = result.errorMap; + errorWithMap.remoteRefusal = true; throw errorWithMap; } catch (error) { console.error("Bundle commit execution failed:", error); @@ -6817,13 +6844,20 @@ function showCommitSuccessModal(result) { function showCommitFailureModal(result) { hideCommitProgress(); showCommitError(result); + // Only a remote refusal is FlutterFlow's answer — a local failure (missing + // credentials, validation) never reached the server, so it must not be + // labelled a refusal. Either way a FAILED outcome is provably pre-write: + // nothing was applied and retrying after a fix is safe. + const remote = result.remoteRefusal === true; populateCommitTerminalModal(result, { heading: "Deploy failed", - title: - "FlutterFlow refused this deploy — nothing was confirmed written.", - guidance: - "Review the error and any per-file outcomes above, fix them in your code or in FlutterFlow, then deploy again. " + - "A refusal is definitive: no part of this deploy was applied, so retrying is safe once the problem is fixed.", + title: remote + ? "FlutterFlow refused this deploy — nothing was confirmed written." + : "The deploy failed before FlutterFlow confirmed anything.", + guidance: remote + ? "Review the error and any per-file outcomes above, fix them in your code or in FlutterFlow, then deploy again. " + + "A refusal is definitive: no part of this deploy was applied, so retrying is safe once the problem is fixed." + : "Review the error above, fix it, then deploy again. The deploy stopped before a write was confirmed, so nothing was applied.", }); } diff --git a/dist/assets/index-BYdMHYLC.js b/dist/assets/index-DbNvpST8.js similarity index 78% rename from dist/assets/index-BYdMHYLC.js rename to dist/assets/index-DbNvpST8.js index 1fb5b2a..713c06f 100644 --- a/dist/assets/index-BYdMHYLC.js +++ b/dist/assets/index-DbNvpST8.js @@ -1,7 +1,7 @@ -(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const s of r)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function n(r){const s={};return r.integrity&&(s.integrity=r.integrity),r.referrerPolicy&&(s.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?s.credentials="include":r.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function i(r){if(r.ep)return;r.ep=!0;const s=n(r);fetch(r.href,s)}})();var w=typeof window<"u"?window:void 0,Le=typeof globalThis<"u"?globalThis:w,Ue=Le?.navigator,P=Le?.document,me=Le?.location,Za=Le?.fetch,qo=Le!=null&&Le.XMLHttpRequest&&"withCredentials"in new Le.XMLHttpRequest?Le.XMLHttpRequest:void 0,uc=Le?.AbortController,Tp=Le?.CompressionStream,Ve=Ue?.userAgent;function cd(){return!(!w||w.navigator.onLine===!1)}var vi=typeof globalThis<"u"?globalThis:w;vi&&typeof self>"u"&&(vi.self=vi),vi&&typeof File>"u"&&(vi.File=function(){});var B=w??{},ne={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function dc(t,e,n,i,r,s,o){try{var a=t[s](o),l=a.value}catch(u){return void n(u)}a.done?e(l):Promise.resolve(l).then(i,r)}function se(t){return function(){var e=this,n=arguments;return new Promise((function(i,r){var s=t.apply(e,n);function o(l){dc(s,i,r,o,a,"next",l)}function a(l){dc(s,i,r,o,a,"throw",l)}o(void 0)}))}}function I(){return I=Object.assign?Object.assign.bind():function(t){for(var e=1;arguments.length>e;e++){var n=arguments[e];for(var i in n)({}).hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},I.apply(null,arguments)}function ud(t,e){if(t==null)return{};var n={};for(var i in t)if({}.hasOwnProperty.call(t,i)){if(e.indexOf(i)!==-1)continue;n[i]=t[i]}return n}var fc=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function hc(t){return typeof t=="string"||t}function pc(t){return typeof t=="string"?t:void 0}var _i,$p=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],Ut=(function(t){return t.AnonymousId="anonymous_id",t.DistinctId="distinct_id",t.Props="props",t.EnablePersonProcessing="enable_person_processing",t.PersonMode="person_mode",t.FeatureFlagDetails="feature_flag_details",t.FeatureFlags="feature_flags",t.FeatureFlagPayloads="feature_flag_payloads",t.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",t.BootstrapFeatureFlags="bootstrap_feature_flags",t.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",t.OverrideFeatureFlags="override_feature_flags",t.Queue="queue",t.AiQueue="ai_queue",t.LogsQueue="logs_queue",t.OptedOut="opted_out",t.SessionId="session_id",t.SessionStartTimestamp="session_start_timestamp",t.SessionLastTimestamp="session_timestamp",t.PersonProperties="person_properties",t.GroupProperties="group_properties",t.InstalledAppBuild="installed_app_build",t.InstalledAppVersion="installed_app_version",t.SessionReplay="session_replay",t.PushRegistered="push_registered",t.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",t.SurveyLastSeenDate="survey_last_seen_date",t.SurveysSeen="surveys_seen",t.Surveys="surveys",t.RemoteConfig="remote_config",t.FlagsEndpointWasHit="flags_endpoint_was_hit",t.DeviceId="device_id",t})({}),gc=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),Mp=["$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"],Lp=["token"],dd="NativeGzipValidationError",zo=t=>t.length>=2&&t[0]===31&&t[1]===139,mc=(t,e)=>t===gc.GZipJS||e===gc.GZipJS||e==="gzip",vc=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",pr=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=dd,e},Np=(function(){var t=se((function*(e,n){18>e.size&&pr("too-short");var i=new Uint8Array(yield e.slice(0,10).arrayBuffer());zo(i)&&i[2]===8||pr("invalid-header");var r=new DataView(yield e.slice(e.size-8).arrayBuffer());r.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(_i)return _i;_i=[];for(var c=0;256>c;c++){for(var d=c,f=0;8>f;f++)d=1&d?3988292384^d>>>1:d>>>1;_i[c]=d>>>0}return _i})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(n)&&pr("invalid-crc");var s=n.length>>>0;r.getUint32(4,!0)!==s&&pr("invalid-size")}));return function(e,n){return t.apply(this,arguments)}})();function Vo(){return Vo=se((function*(t,e,n){e===void 0&&(e=!0);try{var i=new TextEncoder().encode(t),r=new globalThis.CompressionStream("gzip"),s=r.writable.getWriter(),o=s.write(i).then((()=>s.close())).catch((function(){var u=se((function*(c){try{yield s.abort(c)}catch{}throw c}));return function(c){return u.apply(this,arguments)}})()),a=new Response(r.readable).blob(),l=(yield Promise.all([a,o]))[0];return yield Np(l,i),l}catch(u){if(n!=null&&n.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),Vo.apply(this,arguments)}var Op=["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"],_c=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var n=t.toLowerCase();return Op.concat(e).some((i=>{var r=i.toLowerCase();return n.indexOf(r)!==-1}))};function j(t,e){return t.indexOf(e)!==-1}var xs=function(t){return t.trim()},Go=function(t){return t.replace(/^\$/,"")};function fd(t){var e,n=[];return(e=JSON.stringify(t,(function(i,r){if(typeof r=="bigint")return r.toString();if(typeof r!="function"&&typeof r!="symbol"){if(r instanceof Error)return{name:r.name,message:r.message,stack:r.stack};if(r&&typeof r=="object"){for(;n.length>0&&n[n.length-1]!==this;)n.pop();if(n.includes(r))return"[Circular]";n.push(r)}return r}})))!==null&&e!==void 0?e:"null"}var hd=Object.prototype,pd=hd.hasOwnProperty,Is=hd.toString,U=Array.isArray||function(t){return Is.call(t)==="[object Array]"},De=t=>typeof t=="function",he=t=>t===Object(t)&&!U(t),Kt=t=>{if(he(t)){for(var e in t)if(pd.call(t,e))return!1;return!0}return!1},C=t=>t===void 0,X=t=>Is.call(t)=="[object String]",Ko=t=>X(t)&&t.trim().length===0,Ke=t=>t===null,H=t=>C(t)||Ke(t),ke=t=>Is.call(t)=="[object Number]"&&t==t,Dt=t=>ke(t)&&t>0,mt=t=>Is.call(t)==="[object Boolean]",Bp=t=>t instanceof FormData,Dp=t=>j(Mp,t),jp=t=>j(Lp,t);function gd(t){return t===null||typeof t!="object"}function Hr(t,e){return{}.toString.call(t)==="[object "+e+"]"}function Xa(t){return typeof Event<"u"&&md(t,Event)}function md(t,e){try{return t instanceof e}catch{return!1}}var Up=[!0,"true",1,"1","yes"],uo=t=>j(Up,t),Hp=[!1,"false",0,"0","no"];function At(t,e,n,i,r){return e>n&&(i.warn("min cannot be greater than max."),e=n),ke(t)?t>n?(i.warn(" cannot be greater than max: "+n+". Using max value instead."),n):e>t?(i.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(i.warn(" must be a number. using max or fallback. max: "+n+", fallback: "+r),At(r||n,e,n,i))}class Wp{constructor(e){this.tt={},this.et=e.et,this.it=At(e.bucketSize,0,100,e.rt),this.nt=At(e.refillRate,0,this.it,e.rt),this.st=At(e.refillInterval,0,864e5,e.rt)}ot(e,n){var i=Math.floor((n-e.lastAccess)/this.st);i>0&&(e.tokens=Math.min(e.tokens+i*this.nt,this.it),e.lastAccess=e.lastAccess+i*this.st)}consumeRateLimit(e){var n,i=Date.now(),r=String(e),s=this.tt[r];return s?this.ot(s,i):this.tt[r]=s={tokens:this.it,lastAccess:i},s.tokens===0||(s.tokens--,s.tokens===0&&((n=this.et)==null||n.call(this,e)),s.tokens===0)}stop(){this.tt={}}}var it="Mobile",Wr="iOS",Yt="Android",ei="Tablet",vd=Yt+" "+ei,_d="iPad",yd="Apple",wd=yd+" Watch",Bi="Safari",ti="BlackBerry",bd="Samsung",Ed=bd+"Browser",Sd=bd+" Internet",Pn="Chrome",qp=Pn+" OS",xd=Pn+" "+Wr,Qa="Internet Explorer",Id=Qa+" "+it,el="Opera",zp=el+" Mini",tl="Edge",kd="Microsoft "+tl,Zn="Firefox",Cd=Zn+" "+Wr,Gi="Nintendo",Ki="PlayStation",Xn="Xbox",Ad=Yt+" "+it,Pd=it+" "+Bi,Pi="Windows",Yo=Pi+" Phone",yc="Nokia",Jo="Ouya",Fd="Generic",Vp=Fd+" "+it.toLowerCase(),Rd=Fd+" "+ei.toLowerCase(),Zo="Konqueror",Td="Oculus Browser",qr="Vivaldi",$d="Yandex",zr="Whale",Xo="DuckDuckGo",Md="Pale Moon",Vr="Waterfox",Di="Brave",Ld="Google Search App",we="(\\d+(\\.\\d+)?)",fo=new RegExp("Version/"+we),Gp=new RegExp(Xn,"i"),Kp=new RegExp(Ki+" \\w+","i"),Yp=new RegExp(Gi+" \\w+","i"),nl=new RegExp(ti+"|PlayBook|BB10","i"),Jp={"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"},Nd=function(t,e,n,i){e=e||"";var r=(function(s){return s!=null&&s.brave?Di:null})(n);return r||(i!=null&&i.detectGoogleSearchApp&&j(t,"GSA/")?Ld:j(t," OPR/")&&j(t,"Mini")?zp:j(t," OPR/")?el:nl.test(t)?ti:j(t,"IE"+it)||j(t,"WPDesktop")?Id:j(t,"OculusBrowser")?Td:j(t,Ed)?Sd:j(t,tl)||j(t,"Edg/")?kd:j(t,qr+"/")?qr:j(t,"YaBrowser/")?$d:j(t,zr+"/")?zr:j(t,Xo+"/")||j(t,"Ddg/")?Xo:j(t,"FBIOS")?"Facebook "+it:j(t,"UCWEB")||j(t,"UCBrowser")?"UC Browser":j(t,"CriOS")?xd:j(t,"CrMo")||j(t,Pn)?Pn:j(t,Yt)&&j(t,Bi)?Ad:j(t,"FxiOS")?Cd:j(t.toLowerCase(),Zo.toLowerCase())?Zo:j(t,Di+"/")?Di:((s,o)=>o&&j(o,yd)||(function(a){return j(a,Bi)&&!j(a,Pn)&&!j(a,Yt)})(s))(t,e)?j(t,it)?Pd:Bi:j(t,"PaleMoon/")?Md:j(t,Vr+"/")?Vr:j(t,Zn)?Zn:j(t,"MSIE")||j(t,"Trident/")?Qa:j(t,"Gecko")?Zn:"")},Zp={[Id]:[new RegExp("rv:"+we)],[kd]:[new RegExp(tl+"?\\/"+we)],[Pn]:[new RegExp("("+Pn+"|CrMo)\\/"+we)],[xd]:[new RegExp("CriOS\\/"+we)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+we)],[Bi]:[fo],[Pd]:[fo],[el]:[new RegExp("(Opera|OPR)\\/"+we)],[Zn]:[new RegExp(Zn+"\\/"+we)],[Cd]:[new RegExp("FxiOS\\/"+we)],[Zo]:[new RegExp("Konqueror[:/]?"+we,"i")],[ti]:[new RegExp(ti+" "+we),fo],[Ad]:[new RegExp("android\\s"+we,"i")],[Sd]:[new RegExp(Ed+"\\/"+we)],[Td]:[new RegExp("OculusBrowser\\/"+we)],[qr]:[new RegExp(qr+"\\/"+we)],[$d]:[new RegExp("YaBrowser\\/"+we)],[zr]:[new RegExp(zr+"\\/"+we)],[Di]:[new RegExp(Di+"\\/"+we)],[Xo]:[new RegExp("(DuckDuckGo|Ddg)\\/"+we)],[Md]:[new RegExp("PaleMoon\\/"+we)],[Vr]:[new RegExp(Vr+"\\/"+we)],[Ld]:[new RegExp("GSA\\/"+we)],[Qa]:[new RegExp("(rv:|MSIE )"+we)],Mozilla:[new RegExp("rv:"+we)]},Xp=function(t,e,n,i){var r=Nd(t,e,n,i),s=Zp[r];if(C(s))return null;for(var o=0;s.length>o;o++){var a=t.match(s[o]);if(a)return parseFloat(a[a.length-2])}return null},wc=[[new RegExp(Xn+"; "+Xn+" (.*?)[);]","i"),t=>[Xn,t&&t[1]||""]],[new RegExp(Gi,"i"),[Gi,""]],[new RegExp(Ki,"i"),[Ki,""]],[nl,[ti,""]],[new RegExp(Pi,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Yo,""];if(new RegExp(it).test(e)&&!/IEMobile\b/.test(e))return[Pi+" "+it,""];var n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){var i=Jp[n[1]]||"";return/arm/i.test(e)&&(i="RT"),[Pi,i]}return[Pi,""]}],[/((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=C(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+Yt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Yt+")","i"),t=>t&&t[2]?[Yt,[t[2],t[3],t[4]||"0"].join(".")]:[Yt,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{var e=["Mac OS X",""];return t&&t[1]&&(e[1]=[t[1],t[2],t[3]||"0"].join(".")),e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[qp,""]],[/Linux|debian/i,["Linux",""]]],bc=function(t){return Yp.test(t)?Gi:Kp.test(t)?Ki:Gp.test(t)?Xn:new RegExp(Jo,"i").test(t)?Jo:new RegExp("("+Yo+"|WPDesktop)","i").test(t)?Yo:/iPad/.test(t)?_d:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?wd:nl.test(t)?ti:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(yc,"i").test(t)?yc:/(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(it).test(t)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(t)||/pixel[\daxl ]{1,6}/i.test(t)&&!/pixel c/i.test(t)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(t)||/lmy47v/i.test(t)&&!/QTAQZ3/i.test(t)?Yt:vd:new RegExp("(pda|"+it+")","i").test(t)?Vp:new RegExp(ei,"i").test(t)&&!new RegExp(ei+" pc","i").test(t)?Rd:""},Qp=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ec(t,e){return typeof(n=t)=="string"&&Qp.test(n)?t:e();var n}function fn(t){return t&&t.split("#")[0]}function il(t,e){var n=setTimeout(t,e);return n?.unref&&n?.unref(),n}function Sc(t,e,n){return Od.apply(this,arguments)}function Od(){return(Od=se((function*(t,e,n){var i;try{return yield Promise.race([t,new Promise(((r,s)=>{i=il((()=>{try{n?.(),r()}catch(o){s(o)}}),e)}))])}finally{clearTimeout(i)}}))).apply(this,arguments)}var eg=t=>t instanceof Error,Bd={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}},tg=Bd.info;function Dd(t){if(mt(t))return{boolValue:t};if(typeof t=="number")return Number.isFinite(t)?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:{stringValue:String(t)};if(typeof t=="string")return{stringValue:t};if(U(t))return{arrayValue:{values:t.map((e=>Dd(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function Gr(t){var e=[];for(var n in t){var i=t[n];Ke(i)||C(i)||e.push({key:n,value:Dd(i)})}return e}function ng(t,e){var n=Bd[t.level||"info"]||tg,i=n.text,r=n.number,s=String(Date.now())+"000000",o={};e.distinctId&&(o.posthogDistinctId=e.distinctId),e.sessionId&&(o.sessionId=e.sessionId),e.windowId&&(o["window.id"]=e.windowId),H(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),H(e.lastActivityTimestamp)||(o.lastActivityTimestamp=String(e.lastActivityTimestamp)),e.currentUrl&&(o["url.full"]=e.currentUrl),e.screenName&&(o["screen.name"]=e.screenName),e.appState&&(o["app.state"]=e.appState),e.activeFeatureFlags&&e.activeFeatureFlags.length>0&&(o.feature_flags=e.activeFeatureFlags);var a=I({},o,t.attributes||{}),l={timeUnixNano:s,observedTimeUnixNano:s,severityNumber:r,severityText:i,body:{stringValue:t.body},attributes:Gr(a)};return t.trace_id&&(l.traceId=t.trace_id),t.span_id&&(l.spanId=t.span_id),C(t.trace_flags)||(l.flags=t.trace_flags),l}function jd(t,e,n){return I({},t.resourceAttributes,{"service.name":t.serviceName||"unknown_service"},t.environment&&{"deployment.environment":t.environment},t.serviceVersion&&{"service.version":t.serviceVersion},{"telemetry.sdk.name":e,"telemetry.sdk.version":n})}function Ud(t,e,n,i){return{resourceLogs:[{resource:{attributes:Gr(e)},scopeLogs:[{scope:{name:n,version:i},logRecords:t}]}]}}let ig=class{constructor(t,e,n,i,r,s,o){var a;s===void 0&&(s=()=>Promise.resolve()),this._instance=t,this.Ne=e,this.rt=n,this.ut=i,this.ht=r,this.dt=s,this.vt=o,this.ct=null,this.ft=0,this.yt=0,this.bt=0,this._t=0,this.wt=!1,this.kt=e.maxBufferSize,this.xt=Math.max((a=e.maxQueueSize)!==null&&a!==void 0?a:e.maxBufferSize,e.maxBufferSize),this.St=e.flushIntervalMs,this.Ct=e.maxBatchRecordsPerPost,this.Mt=e.rateCapWindowMs,this.Tt=e.maxLogsPerInterval}reset(){this.Et(),this.ct=null,this.bt=0,this._t=0,this.wt=!1,this.ft=0,this.yt=0,this.Ct=this.Ne.maxBatchRecordsPerPost}onReconnect(){this.yt=0,this.It()}captureLog(t){if(!this._instance.isDisabled&&!this._instance.optedOut&&t!=null&&t.body){var e=this.Pt(t);if(e!==null)if(e.body){if(this.Rt()){var n={record:ng(e,this.ut())};this.ht((()=>this.At(n)))}}else this.rt.info("Log was rejected in beforeSend function")}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Log was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for log:",o),null}return i}Rt(){if(this.Tt===void 0)return!0;var t=Date.now(),e=t-this.bt;return this.Mt>e&&e>=0||(this.bt=t,this._t=0,this.wt=!1),this.Tt>this._t?(this._t++,!0):(this.wt||(this.rt.warn("captureLog dropping logs: exceeded "+this.Tt+" logs per "+this.Mt+"ms"),this.wt=!0),!1)}flush(){var t=this;return se((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return se((function*(){var e;t.Et();var n=(e=t._instance.getPersistedProperty(Ut.LogsQueue))!==null&&e!==void 0?e:[];if(n.length!==0)for(var i=n.length,r=0;n.length>0&&i>r;){var s,o;t.ft=0;var a=Math.min(n.length,t.Ct),l=n.slice(0,a),u=Ud(l.map((d=>d.record)),t.Lt(),(s=t.vt)!==null&&s!==void 0?s:t._instance.getLibraryId(),t._instance.getLibraryVersion()),c=yield t._instance.Ot(u);if(c.kind==="too-large"&&l.length>1)t.Ct=Math.max(1,Math.floor(l.length/2)),t.rt.warn("Received 413 when sending logs batch of size "+l.length+", reducing batch size to "+t.Ct);else if(c.kind==="retry-later"||(c.kind==="too-large"?t.rt.warn("Dropping a single log record after 413 with batch size 1 — the record is larger than the server cap and cannot be split further."):c.kind==="ok"&&t.Ne.maxBatchRecordsPerPost>t.Ct&&(t.Ct=Math.min(t.Ne.maxBatchRecordsPerPost,t.Ct+1)),yield t.Dt(l.length),n=(o=t._instance.getPersistedProperty(Ut.LogsQueue))!==null&&o!==void 0?o:[],r+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return se((function*(){var n,i=Math.max(0,t-e.ft),r=(n=e._instance.getPersistedProperty(Ut.LogsQueue))!==null&&n!==void 0?n:[];e._instance.setPersistedProperty(Ut.LogsQueue,r.slice(i)),yield e.dt()}))()}Lt(){return jd(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var n=(e=this._instance.getPersistedProperty(Ut.LogsQueue))!==null&&e!==void 0?e:[];this.xt>n.length||(n.shift(),this.ft++,this.rt.info("Logs queue is full, dropping oldest record.")),n.push(t),this._instance.setPersistedProperty(Ut.LogsQueue,n),this.kt>n.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=il((()=>{this.Nt=void 0,this.It()}),t))}qt(){var t=Math.min(Math.max(0,this.yt-1),6);return this.St*Math.pow(2,t)}jt(){var t=this._instance.getPersistedProperty(Ut.LogsQueue);return!!t&&t.length>0}shutdown(t){var e=this;return se((function*(){e.Et();var n=e.flush().catch((()=>{}));t!==void 0?yield Sc(n,t):yield n}))()}flushWithTimeout(t){var e=this;return se((function*(){var n=e.flush();yield Sc(n,t,(()=>{n.catch((()=>{}))}))}))()}It(){this.flush().then((()=>{this.yt=0}),(t=>{this.yt++,this.rt.error("PostHog logs flush failed:",t)})).finally((()=>{!this._instance.isDisabled&&this.jt()&&this.$t(this.qt())}))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}};var ho=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function xc(t){return String(t)+"000000"}function Ic(t,e,n,i){var r="";return i&&(r=Object.keys(i).sort().map((s=>JSON.stringify(s)+":"+JSON.stringify(i[s]))).join(",")),t+"\0"+e+"\0"+(n??"")+"\0"+r}let rg=class{constructor(t,e,n){this._instance=t,this.Ne=e,this.rt=n,this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Wt=0}count(t,e,n){e===void 0&&(e=1),this.Vt({name:t,type:"count",value:e,unit:n?.unit,attributes:n?.attributes})}gauge(t,e,n){this.Vt({name:t,type:"gauge",value:e,unit:n?.unit,attributes:n?.attributes})}histogram(t,e,n){this.Vt({name:t,type:"histogram",value:e,unit:n?.unit,attributes:n?.attributes})}flush(){var t=this,e=this.ct,n=(function(){var r=se((function*(){e&&(yield e.catch((()=>{}))),yield t.Zt()}));return function(){return r.apply(this,arguments)}})(),i=n().finally((()=>{this.ct===i&&(this.ct=null)}));return this.ct=i,i}drainWindow(){if(this.Bt.size===0)return null;var t=this.Bt;return this.Bt=new Map,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Gt(t)}reset(){this.Wt++,this.Et(),this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set}Vt(t){if(!this._instance.isDisabled&&!this._instance.optedOut){var e=this.Pt(t);if(e!==null)if(e.name&&typeof e.name=="string")if(typeof e.value=="number"&&Number.isFinite(e.value))if(e.type==="count"&&0>e.value)this.rt.warn("Dropping count '"+e.name+"': counters are monotonic, value must be >= 0");else{var n,i;try{n=e.attributes?I({},e.attributes):void 0,i=Ic(e.type,e.name,e.unit,n)}catch(o){return void this.rt.warn("Dropping metric '"+e.name+"': attributes could not be serialized",o)}var r=this.Bt.get(i);if(!r){if(!this.Qt())return;r={name:e.name,type:e.type,unit:e.unit,attributes:n,windowStartMs:Date.now()},this.Bt.set(i,r)}var s=this.Ut.get(e.name);s===void 0?this.Ut.set(e.name,e.type):s===e.type||this.zt.has(e.name)||(this.zt.add(e.name),this.rt.warn("Metric name '"+e.name+"' is already used as a "+s+"; recording it as a "+e.type+" too will blend both series in charts. Use a distinct name.")),this.Kt(r,e.value),this.$t()}else this.rt.warn("Dropping metric '"+e.name+"': value must be a finite number");else this.rt.warn("Dropping metric with empty name")}}Qt(){return this.Ne.maxSeriesPerFlush>this.Bt.size||(this.Ht||(this.Ht=!0,this.rt.warn("Metric series cap reached ("+this.Ne.maxSeriesPerFlush+" per flush window); dropping new series until the next flush. Reduce attribute cardinality.")),!1)}Kt(t,e){var n;switch(t.type){case"count":t.total=((n=t.total)!==null&&n!==void 0?n:0)+e;break;case"gauge":t.last=e;break;case"histogram":t.hist||(t.hist={count:0,sum:0,min:e,max:e,bucketCounts:new Array(ho.length+1).fill(0)});var i=t.hist;i.count+=1,i.sum+=e,i.min=Math.min(i.min,e),i.max=Math.max(i.max,e),i.bucketCounts[(function(r,s){for(var o=0;s.length>o;o++)if(s[o]>=r)return o;return s.length})(e,ho)]+=1}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Metric was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for metric:",o),null}return i}$t(){this.Nt||(this.Nt=il((()=>{this.Nt=void 0,this.flush().catch((t=>{this.rt.error("Metrics flush failed:",t)}))}),this.Ne.flushIntervalMs))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}Zt(){var t=this;return se((function*(){if(t.Bt.size!==0){var e=t.Bt;t.Bt=new Map,t.Ht=!1,t.Ut=new Map,t.zt=new Set;var n=t.Wt,i=yield t._instance.Jt(t.Gt(e));if(n===t.Wt)switch(i.kind){case"ok":return;case"retry-later":return t.Yt(e),void t.$t();case"too-large":return void t.rt.warn("Metrics batch exceeded the server size limit and was dropped");case"fatal":return void t.rt.error("Failed to send metrics batch:",i.error)}}}))()}Gt(t){return e=this.Xt(t),n=(function(s,o,a){return I({},s.resourceAttributes,{"service.name":s.serviceName||"unknown_service"},s.environment&&{"deployment.environment":s.environment},s.serviceVersion&&{"service.version":s.serviceVersion},{"telemetry.sdk.name":o,"telemetry.sdk.version":a})})(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion()),i=this._instance.getLibraryId(),r=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:Gr(n)},scopeMetrics:[{scope:{name:i,version:r},metrics:e}]}]};var e,n,i,r}Xt(t){var e=xc(Date.now()),n=new Map;for(var i of t.values()){var r,s=Ic(i.type,i.name,i.unit,void 0),o=n.get(s);o||(o=I({name:i.name},i.unit&&{unit:i.unit}),i.type==="count"?o.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:i.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:1,dataPoints:[]},n.set(s,o));var a=Gr((r=i.attributes)!==null&&r!==void 0?r:{}),l=xc(i.windowStartMs);if(i.type==="count"){var u,c={attributes:a,startTimeUnixNano:l,timeUnixNano:e,asDouble:(u=i.total)!==null&&u!==void 0?u:0};o.sum.dataPoints.push(c)}else if(i.type==="gauge"){var d,f={attributes:a,timeUnixNano:e,asDouble:(d=i.last)!==null&&d!==void 0?d:0};o.gauge.dataPoints.push(f)}else i.hist&&o.histogram.dataPoints.push({attributes:a,startTimeUnixNano:l,timeUnixNano:e,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:ho})}return Array.from(n.values())}Yt(t){var e,n;for(var i of t){var r=i[0],s=i[1],o=this.Bt.get(r);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,s.windowStartMs),o.type){case"count":o.total=((e=o.total)!==null&&e!==void 0?e:0)+((n=s.total)!==null&&n!==void 0?n:0);break;case"gauge":break;case"histogram":if(s.hist)if(o.hist){o.hist.count+=s.hist.count,o.hist.sum+=s.hist.sum,o.hist.min=Math.min(o.hist.min,s.hist.min),o.hist.max=Math.max(o.hist.max,s.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=s.hist.bucketCounts[a]}else o.hist=s.hist}else this.Qt()&&this.Bt.set(r,s)}}};var gr,kc,po;function sg(t){var e=globalThis._posthogChunkIds;if(e){var n=Object.keys(e);return po&&n.length===kc||(kc=n.length,po=n.reduce(((i,r)=>{gr||(gr={});var s=gr[r];if(s)i[s[0]]=s[1];else for(var o=t(r),a=o.length-1;a>=0;a--){var l=o[a],u=l?.filename,c=e[r];if(u&&c){i[u]=c,gr[r]=[u,c];break}}return i}),{})),po}}class og{constructor(e,n,i){i===void 0&&(i=[]),this.coercers=e,this.stackParser=n,this.modifiers=i}buildFromUnknown(e,n){n===void 0&&(n={});var i=n&&n.mechanism||{handled:!0,type:"generic"},r=this.buildCoercingContext(i,n,0).apply(e),s=this.buildParsingContext(n),o=this.parseStacktrace(r,s);return{$exception_list:this.convertToExceptionList(o,i),$exception_level:"error"}}modifyFrames(e){var n=this;return se((function*(){for(var i of e)i.stacktrace&&i.stacktrace.frames&&U(i.stacktrace.frames)&&(i.stacktrace.frames=yield n.applyModifiers(i.stacktrace.frames));return e}))()}coerceFallback(e){var n;return{type:"Error",value:"Unknown error",stack:(n=e.syntheticException)==null?void 0:n.stack,synthetic:!0}}parseStacktrace(e,n){var i,r;return e.cause!=null&&(i=this.parseStacktrace(e.cause,n)),e.stack!=""&&e.stack!=null&&(r=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?n.skipFirstLines:0),n.chunkIdMap)),I({},e,{cause:i,stack:r})}applyChunkIds(e,n){return e.map((i=>(i.filename&&n&&(i.chunk_id=n[i.filename]),i)))}applyCoercers(e,n){for(var i of this.coercers)if(i.match(e))return i.coerce(e,n);return this.coerceFallback(n)}applyModifiers(e){var n=this;return se((function*(){var i=e;for(var r of n.modifiers)i=yield r(i);return i}))()}convertToExceptionList(e,n){var i,r,s,o={type:e.type,value:e.value,mechanism:{type:(i=n.type)!==null&&i!==void 0?i:"generic",handled:(r=n.handled)===null||r===void 0||r,synthetic:(s=e.synthetic)!==null&&s!==void 0&&s}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,I({},n,{handled:!0}))),a}buildParsingContext(e){var n;return{chunkIdMap:sg(this.stackParser),skipFirstLines:(n=e.skipFirstLines)!==null&&n!==void 0?n:1}}buildCoercingContext(e,n,i){i===void 0&&(i=0);var r=(s,o)=>{if(4>=o){var a=this.buildCoercingContext(e,n,o);return this.applyCoercers(s,a)}};return I({},n,{syntheticException:i==0?n.syntheticException:void 0,mechanism:e,apply:s=>r(s,i),next:s=>r(s,i+1)})}}var ni="?";function Qo(t,e,n,i,r){var s={platform:t,filename:e,function:n===""?ni:n,in_app:!0};return C(i)||(s.lineno=i),C(r)||(s.colno=r),s}var Hd=(t,e)=>{var n=t.indexOf("safari-extension")!==-1,i=t.indexOf("safari-web-extension")!==-1;return n||i?[t.indexOf("@")!==-1?t.split("@")[0]:ni,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},ag=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,lg=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,cg=/\((\S*)(?::(\d+))(?::(\d+))\)/,ug=(t,e)=>{var n=ag.exec(t);if(n)return Qo(e,n[1],ni,+n[2],+n[3]);var i=lg.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var r=cg.exec(i[2]);r&&(i[2]=r[1],i[3]=r[2],i[4]=r[3])}var s=Hd(i[1]||ni,i[2]);return Qo(e,s[1],s[0],i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},dg=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,fg=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,hg=(t,e)=>{var n=dg.exec(t);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){var i=fg.exec(n[3]);i&&(n[1]=n[1]||"eval",n[3]=i[1],n[4]=i[2],n[5]="")}var r=n[3],s=n[1]||ni,o=Hd(s,r);return Qo(e,r=o[1],s=o[0],n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},Cc=/\(error: (.*)\)/;class pg{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,n){var i=X(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:i?e.stack:void 0,cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var n=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?n+": "+e.message:n}isDOMException(e){return Hr(e,"DOMException")}isDOMError(e){return Hr(e,"DOMError")}}class gg{match(e){return(function(n){switch({}.toString.call(n)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return md(n,Error)}})(e)}coerce(e,n){return{type:this.getType(e),value:this.getMessage(e,n),stack:this.getStack(e),cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,n){var i=e.message;return String(i.error&&typeof i.error.message=="string"?i.error.message:i)}getStack(e){return e.stacktrace||e.stack||void 0}}class mg{constructor(){}match(e){return!!Hr(e,"ErrorEvent")&&(e.error!=null||this.fe(e))}coerce(e,n){var i;if(e.error!=null)return n.apply(e.error);var r=n.apply(e.message);return I({},r,{stack:(i=this.pe(e))!==null&&i!==void 0?i:r.stack,synthetic:!0})}fe(e){return X(e.message)&&e.message.length>0}pe(e){var n=e;if(X(n.filename)&&n.filename.length>0){var i,r,s=(i=n.lineno)!==null&&i!==void 0?i:0,o=(r=n.colno)!==null&&r!==void 0?r:0;return`Error - at `+n.filename+":"+s+":"+o}}}var vg=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class _g{match(e){return typeof e=="string"}coerce(e,n){var i,r=this.getInfos(e),s=r[0],o=r[1];return{type:s??"Error",value:o??e,stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}getInfos(e){var n="Error",i=e,r=e.match(vg);return r&&(n=r[1],i=r[2]),[n,i]}}var yg=["fatal","error","warning","log","info","debug"];function Wd(t,e){e===void 0&&(e=40);var n=Object.keys(t);if(n.sort(),!n.length)return"[object has no keys]";for(var i=n.length;i>0;i--){var r=n.slice(0,i).join(", ");if(e>=r.length)return i===n.length?r:r.length>e?r.slice(0,e)+"...":r}return""}class wg{match(e){return typeof e=="object"&&e!==null}coerce(e,n){var i,r,s=this.getErrorPropertyFromObject(e);return s?n.apply(s):{type:this.getType(e),value:this.getValue(e),stack:(i=this.getStack(e))!==null&&i!==void 0?i:(r=n.syntheticException)==null?void 0:r.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return Xa(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var n="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(n+=" with message: '"+e.message+"'"),n}if("message"in e&&typeof e.message=="string")return e.message;var i=this.getObjectClassName(e);return(i&&i!=="Object"?"'"+i+"'":"Object")+" captured as exception with keys: "+Wd(e)}isSeverityLevel(e){return X(e)&&!Ko(e)&&yg.indexOf(e)>=0}getStack(e){try{return X(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:X(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(var n in e)if({}.hasOwnProperty.call(e,n)){var i=e[n];if(eg(i))return i}}getObjectClassName(e){try{var n=Object.getPrototypeOf(e);return n?n.constructor.name:void 0}catch{return}}}class bg{match(e){return Xa(e)}coerce(e,n){var i,r=e.constructor.name;return{type:r,value:r+" captured as exception with keys: "+Wd(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class Eg{match(e){return gd(e)}coerce(e,n){var i;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class Sg{match(e){return Hr(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Xa(e))return!1;try{var n=e.detail;return n!=null&&typeof n=="object"&&"reason"in n}catch{return!1}}coerce(e,n){var i,r=this.getUnhandledRejectionReason(e);return gd(r)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(r),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}:n.apply(r)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}}var Kr="$message",Yr="$timestamp",xg=new Set([Kr,Yr]),go={enabled:!0,max_bytes:32768};function Jr(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:go.enabled,max_bytes:kg(t.max_bytes,go.max_bytes)}:I({},go)}class Ig{constructor(e){this.Ke=[],this.Je=0,this.Ne=Jr(e)}setConfig(e){this.Ne=Jr(e),this.Xe()}add(e){var n=(function(r){var s;try{s=fd(r)}catch{return}try{var o=JSON.parse(s);if(!he(o))return;var a=o,l=a[Kr],u=a[Yr];return!X(l)||l.trim().length===0||!X(u)&&!ke(u)?void 0:{step:a,json:s}}catch{return}})(e);if(n){var i=(function(r){if(typeof TextEncoder<"u")return new TextEncoder().encode(r).length;for(var s=encodeURIComponent(r),o=0,a=0;s.length>a;a++)s[a]==="%"?(o+=1,a+=2):o+=1;return o})(n.json);i>this.Ne.max_bytes||(this.Ke.push({step:n.step,bytes:i}),this.Je+=i,this.Xe())}}getAttachable(){return this.Ke.map((e=>e.step))}clear(){this.Ke=[],this.Je=0}size(){return this.Ke.length}Xe(){for(;this.Je>this.Ne.max_bytes&&this.Ke.length>0;){var e=this.Ke.shift();e&&(this.Je-=e.bytes)}}}function kg(t,e){if(!ke(t)||t===1/0||t===-1/0)return e;var n=Math.floor(t);return 0>n?e:n}var qd=function(t,e){var n=(e===void 0?{}:e).debugEnabled,i={k(r){if(w&&(ne.DEBUG||w.POSTHOG_DEBUG||n)&&!C(w.console)&&w.console){for(var s=("__rrweb_original__"in w.console[r])?w.console[r].__rrweb_original__:w.console[r],o=arguments.length,a=new Array(o>1?o-1:0),l=1;o>l;l++)a[l-1]=arguments[l];s(t,...a)}},debug(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("debug",...s)},info(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("log",...s)},warn(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("warn",...s)},error(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("error",...s)},critical(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];console.error(t,...s)},uninitializedWarning(r){i.error("You must initialize PostHog before calling "+r)},createLogger:(r,s)=>qd(t+" "+r,s)};return i},A=qd("[PostHog.js]"),pe=A.createLogger,Cg=pe("[ExternalScriptsLoader]"),mo=(t,e,n)=>{if(t.config.disable_external_dependency_loading)return Cg.warn(e+" was requested but loading of external scripts is disabled."),n("Loading of external scripts is disabled");var i=P?.querySelectorAll("script");if(i){for(var r,s=function(){if(i[o].src===e){var l=i[o];return l.__posthog_loading_callback_fired?{v:n()}:(l.addEventListener("load",(u=>{l.__posthog_loading_callback_fired=!0,n(void 0,u)})),l.onerror=u=>n(u),{v:void 0})}},o=0;i.length>o;o++)if(r=s())return r.v}var a=()=>{if(!P)return n("document not found");var l=P.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=d=>{l.__posthog_loading_callback_fired=!0,n(void 0,d)},l.onerror=d=>n(d),t.config.prepare_external_dependency_script&&(l=t.config.prepare_external_dependency_script(l)),!l)return n("prepare_external_dependency_script returned null");if(t.config.external_scripts_inject_target==="head")P.head.appendChild(l);else{var u,c=P.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):P.body.appendChild(l)}};P!=null&&P.body?a():P?.addEventListener("DOMContentLoaded",a)};B.__PosthogExtensions__=B.__PosthogExtensions__||{},B.__PosthogExtensions__.loadExternalDependency=(t,e,n)=>{if(e!=="remote-config"){var i;if(t.config.strict_script_versioning)i=t.requestRouter.endpointFor("assets","/static/"+t.version+"/"+e+".js");else{var r="/static/"+e+".js?v="+t.version;if(e==="toolbar"){var s=3e5;r=r+"&t="+Math.floor(Date.now()/s)*s}i=t.requestRouter.endpointFor("assets",r)}mo(t,i,n)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");mo(t,o,n)}},B.__PosthogExtensions__.loadSiteApp=(t,e,n)=>{var i=t.requestRouter.endpointFor("api",e);mo(t,i,n)};ne.DEBUG=!1,ne.LIB_VERSION="1.415.7",ne.LIB_NAME="web";var zd="$people_distinct_id",Yi="$device_id",vo="$device_model",Fi="__alias",Ri="__timers",ea="$autocapture_disabled_server_side",ta="$heatmaps_enabled_server_side",na="$exception_capture_enabled_server_side",ia="$error_tracking_suppression_rules",ra="$error_tracking_capture_extension_exceptions",sa="$web_vitals_enabled_server_side",rl="$dead_clicks_enabled_server_side",sl="$product_tours_enabled_server_side",oa="$web_vitals_allowed_metrics",An="$session_recording_remote_config",Vd="$replay_sample_rate",Gd="$replay_override_sampling",Kd="$replay_override_linked_flag",Yd="$replay_override_url_trigger",Jd="$replay_override_event_trigger",Kn="$sesid",ol="$session_is_sampled",Sn="$enabled_feature_flags",Ti="$active_feature_flags",Ar="$early_access_features",aa="$feature_flag_details",$i="$feature_flag_payloads",Pr="$feature_flag_request_id",Zr="$minimal_flag_called_events",It="$override_feature_flags",xn="$override_feature_flag_payloads",jt="$stored_person_properties",In="$stored_group_properties",la="$surveys",Xr="$surveys_loaded_at",ca="$surveys_activated",Fr="$surveys_activated_session",Rr="$surveys_activated_timestamps",Mi="ph_product_tours",Cn="$flag_call_reported",Li="$flag_call_reported_session_id",Tr="$feature_flag_errors",ji="$feature_flag_evaluated_at",ot="$user_state",ua="$client_session_props",da="$capture_rate_limit",fa="$initial_campaign_params",ha="$initial_referrer_info",Qr="$initial_person_info",es="$epp",mr="$posthog_cookieless",Zd="$cookieless_mode",Xd="$sdk_debug_extensions_init_method",Qd="$sdk_debug_extensions_init_time_ms",ef="$sdk_debug_recording_script_not_loaded",al="PostHog loadExternalDependency extension not found.",kn="on_reject",Wt="always",Un="anonymous",vn="identified",pa="identified_only",ts="visibilitychange",ns="beforeunload",Vn="$pageview",_o="$pageleave",yo="$identify",Ac="$groupidentify";function vr(t,e){U(t)&&t.forEach(e)}function ie(t,e){if(!H(t))if(U(t))t.forEach(e);else if(Bp(t))t.forEach(((i,r)=>e(i,r)));else for(var n in t)pd.call(t,n)&&e(t[n],n)}var fe=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;e>i;i++)n[i-1]=arguments[i];for(var r of n)for(var s in r)r[s]!==void 0&&(t[s]=r[s]);return t};function $r(t){for(var e=Object.keys(t),n=e.length,i=new Array(n);n--;)i[n]=[e[n],t[e[n]]];return i}var Pc=function(t){try{return t()}catch{return}},Ag=function(t){return function(){try{for(var e=arguments.length,n=new Array(e),i=0;e>i;i++)n[i]=arguments[i];return t.apply(this,n)}catch(r){A.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),A.critical(r)}}},ll=function(t){var e={};return ie(t,(function(n,i){(X(n)&&n.length>0||ke(n))&&(e[i]=n)})),e},Pg=["herokuapp.com","vercel.app","netlify.app"];function Fg(t){var e=t?.hostname;if(!X(e))return!1;var n=e.split(".").slice(-2).join(".");for(var i of Pg)if(n===i)return!1;return!0}function ve(t,e,n,i){var r=i??{},s=r.capture,o=r.passive;t?.addEventListener(e,n,{capture:s!==void 0&&s,passive:o===void 0||o})}function ga(t){return t.name==="ph_toolbar_internal"}var tf=t=>{if(P){try{for(var e=t+"=",n=P.cookie.split(";").filter((s=>s.length)),i=0;n.length>i;i++){for(var r=n[i];r.charAt(0)==" ";)r=r.substring(1,r.length);if(r.indexOf(e)===0)return decodeURIComponent(r.substring(e.length,r.length))}}catch{}return null}};Math.trunc||(Math.trunc=function(t){return 0>t?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return ke(t)&&isFinite(t)&&Math.floor(t)===t});class is{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,n,i,r){if(!Number.isInteger(e)||!Number.isInteger(n)||!Number.isInteger(i)||!Number.isInteger(r)||0>e||0>n||0>i||0>r||e>0xffffffffffff||n>4095||i>1073741823||r>4294967295)throw new RangeError("invalid field value");var s=new Uint8Array(16);return s[0]=e/Math.pow(2,40),s[1]=e/Math.pow(2,32),s[2]=e/Math.pow(2,24),s[3]=e/Math.pow(2,16),s[4]=e/256,s[5]=e,s[6]=112|n>>>8,s[7]=n,s[8]=128|i>>>24,s[9]=i>>>16,s[10]=i>>>8,s[11]=i,s[12]=r>>>24,s[13]=r>>>16,s[14]=r>>>8,s[15]=r,new is(s)}toString(){for(var e="",n=0;this.bytes.length>n;n++)e=e+(this.bytes[n]>>>4).toString(16)+(15&this.bytes[n]).toString(16),n!==3&&n!==5&&n!==7&&n!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new is(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var n=0;16>n;n++){var i=this.bytes[n]-e.bytes[n];if(i!==0)return Math.sign(i)}return 0}}class Rg{generate(){var e=this.generateOrAbort();if(!C(e))return e;this.S=0;var n=this.generateOrAbort();if(C(n))throw new Error("Could not generate UUID after timestamp reset");return n}generateOrAbort(){var e=Date.now();if(e>this.S)this.S=e,this.C();else{if(this.S>=e+1e4)return;this.I++,this.I>4398046511103&&(this.S++,this.C())}return is.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 Tg}}var Fc,nf=t=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;t.length>e;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};w&&!C(w.crypto)&&crypto.getRandomValues&&(nf=t=>crypto.getRandomValues(t));class Tg{nextUint32(){return this.R.length>this.O||(nf(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var Ht=()=>$g().toString(),$g=()=>(Fc||(Fc=new Rg)).generate(),yi="",Mg=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,qt={N:()=>!!P,j(t){A.error("cookieStore error: "+t)},P:tf,H(t){var e;try{e=JSON.parse(qt.P(t))||{}}catch{}return e},F(t,e,n,i,r){if(!P)return!1;try{var s="",o="",a=(function(c,d){if(d){var f=(function(p,g){if(g===void 0&&(g=P),yi)return yi;if(!g||["localhost","127.0.0.1"].includes(p))return"";for(var m=p.split("."),v=Math.min(m.length,8),E="dmn_chk_"+Ht();!yi&&v--;){var S=m.slice(v).join("."),_=E+"=1;domain=."+S+";path=/";g.cookie=_+";max-age=3",g.cookie.includes(E)&&(g.cookie=_+";max-age=0",yi=S)}return yi})(c);if(!f){var h=(p=>{var g=p.match(Mg);return g?g[0]:""})(c);h!==f&&A.info("Warning: cookie subdomain discovery mismatch",h,f),f=h}return f?"; domain=."+f:""}return""})(P.location.hostname,i);if(n){var l=new Date;l.setTime(l.getTime()+864e5*n),s="; expires="+l.toUTCString()}r&&(o="; secure");var u=t+"="+encodeURIComponent(JSON.stringify(e))+s+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&A.warn("cookieStore warning: large cookie, len="+u.length),P.cookie=u,!0}catch{return!1}},q(t,e){if(P!=null&&P.cookie)try{qt.F(t,"",-1,e)}catch{return}}},wo=null,le={N(){if(!Ke(wo))return wo;var t=!0;if(C(w))t=!1;else try{var e="__mplssupport__";le.F(e,"xyz"),le.P(e)!=='"xyz"'&&(t=!1),le.q(e)}catch{t=!1}return t||A.error("localStorage unsupported; falling back to cookie store"),wo=t,t},j(t){A.error("localStorage error: "+t)},P(t){try{return w?.localStorage.getItem(t)}catch(e){le.j(e)}return null},H(t){try{return JSON.parse(le.P(t))||{}}catch{}return null},F(t,e){try{return w?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(n){le.j(n)}return!1},q(t){try{w?.localStorage.removeItem(t)}catch(e){le.j(e)}}},Lg=[Yi,"distinct_id",Kn,ol,es,Qr,ot],_r={},Ng={N:()=>!0,j(t){A.error("memoryStorage error: "+t)},P:t=>_r[t]||null,H:t=>_r[t]||null,F:(t,e)=>(_r[t]=e,!0),q(t){delete _r[t]}},_n=null,be={N(){if(!Ke(_n))return _n;if(_n=!0,C(w))_n=!1;else try{var t="__support__";be.F(t,"xyz"),be.P(t)!=='"xyz"'&&(_n=!1),be.q(t)}catch{_n=!1}return _n},j(t){A.error("sessionStorage error: ",t)},P(t){try{return w?.sessionStorage.getItem(t)}catch(e){be.j(e)}return null},H(t){try{return JSON.parse(be.P(t))||null}catch{}return null},F(t,e){try{return w?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(n){be.j(n)}return!1},q(t){try{w?.sessionStorage.removeItem(t)}catch(e){be.j(e)}}};class Og{constructor(e){this._instance=e}get Ne(){return this._instance.config}get consent(){return this.ti()?0:this.ei}isOptedOut(){return this.Ne.cookieless_mode===Wt||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===kn}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===0}isRejected(){return this.consent===0||this.consent===-1&&this.Ne.opt_out_capturing_by_default}optInOut(e){this.ii.F(this.ri,e?1:0,this.Ne.cookie_expiration,this.Ne.cross_subdomain_cookie,this.Ne.secure_cookie)}reset(){this.ii.q(this.ri,this.Ne.cross_subdomain_cookie)}get ri(){var e=this._instance.config,n=e.token,i=e.opt_out_capturing_cookie_prefix;return e.consent_persistence_name||(i?i+n:"__ph_opt_in_out_"+n)}get ei(){var e=this.ii.P(this.ri);return uo(e)?1:j(Hp,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,n=e==="localStorage"?le:qt;if(!this.ni||this.ni!==n){this.ni=n;var i=e==="localStorage"?qt:le;i.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(uo(i.P(this.ri))),i.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[Ue?.doNotTrack,Ue?.msDoNotTrack,B.doNotTrack].some((e=>uo(e)))}}function rf(t,e){var n,i=t==null||(n=t.config)==null?void 0:n.get_current_url;if(!De(i))return e;try{var r=i(e);return X(r)&&r?r:e}catch(s){return A.error("Error in get_current_url, falling back to window.location.href",s),e}}var sf="__POSTHOG_TOOLBAR__",Bg=1,Dg=3,jg=11;function Rc(t){return t instanceof Element&&(t.id===sf||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function hn(t){return!!t&&t.nodeType===Bg}function Qe(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function of(t){return!!t&&t.nodeType===Dg}function af(t){return!!t&&t.nodeType===jg&&hn(t.host)}var lf=1e3;function cl(t){return t?xs(t).split(/\s+/):[]}function Tc(t,e){var n=(function(i){var r,s=w==null||(r=w.location)==null?void 0:r.href;return C(s)?void 0:rf(i,s)})(e);return!!(n&&t&&t.some((i=>n.match(i))))}function rs(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 cl(e)}function cf(t){return H(t)?null:xs(t).split(/(\s+)/).filter((e=>Ui(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function Ji(t){var e="";return va(t)&&!hf(t)&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;of(n)&&n.textContent&&(e+=(i=cf(n.textContent))!==null&&i!==void 0?i:"")})),xs(e)}function bo(t){var e;return C(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var ul=["a","button","form","input","select","textarea","label"];function ma(t,e){if(C(e))return!0;var n,i=function(s){if(e.some((o=>(function(a,l){var u=a.matches||a.matchesSelector||a.msMatchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.oMatchesSelector;try{return!!u&&u.call(a,l)}catch{return!1}})(s,o))))return{v:!0}};for(var r of t)if(n=i(r))return n.v;return!1}function uf(t){var e=t.parentNode;return!(!e||!hn(e))&&e}var Ug=[".ph-no-autocapture","[data-ph-no-autocapture]"],df=["next","previous","prev",">","<"],Hg=[...df,"+","-","−","–"],$c=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,Mc=[".ph-no-rageclick",".ph-no-capture"],Wg=["","text","search","email","password","url","tel","number"];function Lc(t,e){if(!w||dl(t))return!1;var n,i,r,s,o;if(mt(e)?(n=!!e&&Mc,i=void 0,r=!1):(n=(s=e?.css_selector_ignorelist)!==null&&s!==void 0?s:Mc,i=e?.content_ignorelist,r=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),n===!1||r&&(function(l){return!(!l||!hn(l))&&(!!Qe(l,"textarea")||(Qe(l,"input")?j(Wg,(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=ff(t,!1).targetElementList;return!(function(l,u){if(l===!1||C(l))return!1;var c;if(l===!0)c=df;else{if(!U(l))return!1;if(l.length>10)return A.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var f=d.safeText,h=d.ariaLabel;return c.some((p=>$c(f,p)||$c(h,p)))}))})(i,a.map((l=>{var u;return{safeText:Ji(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!ma(a,n)}var dl=t=>!t||Qe(t,"html")||!hn(t),ff=(t,e)=>{if(!w||dl(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,i=[t],r=t;r.parentNode&&!Qe(r,"body");)if(af(r.parentNode))i.push(r.parentNode.host),r=r.parentNode.host;else{var s=uf(r);if(!s)break;if(e||ul.indexOf(s.tagName.toLowerCase())>-1)n=!0;else try{var o=w.getComputedStyle(s);o&&o.getPropertyValue("cursor")==="pointer"&&(n=!0)}catch{}i.push(s),r=s}return{parentIsUsefulElement:n,targetElementList:i}};function va(t){for(var e=new Set,n=0,i=t;i.parentNode&&!Qe(i,"body");i=i.parentNode){if(n++>=lf||e.has(i))return!1;e.add(i);var r=rs(i);if(j(r,"ph-sensitive")||j(r,"ph-no-capture"))return!1}if(j(rs(t),"ph-include"))return!0;var s=t.type||"";if(X(s))switch(s.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!X(o)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(o.replace(/[^a-zA-Z0-9]/g,""))}function hf(t){return!!(Qe(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||Qe(t,"select")||Qe(t,"textarea")||t.getAttribute("contenteditable")==="true")}var Nc=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}))$"),Oc=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,qg=[16,15,14,13],zg=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),Bc=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),Dc=/[0-9A-Za-z_]/;function Vg(t){for(var e=0,n=!1,i=t.length-1;i>=0;i--){var r=t.charCodeAt(i)-48;n&&(r*=2)>9&&(r-=9),e+=r,n=!n}return e%10==0}function Ui(t,e){if(e===void 0&&(e=!0),H(t))return!1;if(X(t)){t=xs(t);var n=e?Nc.test((t||"").replace(/[- ]/g,"")):(function(r){var s;for(Oc.lastIndex=0;s=Oc.exec(r);){var o=s[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of qg){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(Nc.test(d)&&Vg(d))return!0}}}return!1})(t);if(n)return!1;var i=e?zg.test(t):(function(r){var s;for(Bc.lastIndex=0;s=Bc.exec(r);){var o=s[1],a=s[3];if(!(o&&a&&Dc.test(o)&&Dc.test(a)))return!0}return!1})(t);if(i)return!1}return!0}function jc(t){var e=Ji(t);return Ui(e=(e+" "+pf(t)).trim())?e:""}function pf(t){var e="";return t&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;if(n&&((i=n.tagName)==null?void 0:i.toLowerCase())==="span")try{var r=Ji(n);e=(e+" "+r).trim(),n.childNodes&&n.childNodes.length&&(e=(e+" "+pf(n)).trim())}catch(s){A.error("[AutoCapture]",s)}})),e}function Uc(t){return t.replace(/"|\\"/g,'\\"')}function Gg(t){var e=t.attr__class;if(e)return U(e)?e:cl(e)}var yr=pe("[Dead Clicks]"),Kg=()=>!0,Yg=t=>{var e,n=!((e=t.instance.persistence)==null||!e.get_property(rl)),i=t.instance.config.capture_dead_clicks;return mt(i)?i:!!he(i)||n};class Hc{get lazyLoadedDeadClicksAutocapture(){return this.si}constructor(e,n,i){this.instance=e,this.isEnabled=n,this.onCapture=i,this.startIfEnabledOrStop()}onRemoteConfig(e){if(e.ok){var n=e.config;"captureDeadClicks"in n&&(this.instance.persistence&&this.instance.persistence.register({[rl]:n.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var n,i;(n=B.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture?e():(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"dead-clicks-autocapture",(r=>{r?yr.error("failed to load script",r):e()}))}oi(){var e;if(P){if(!this.si&&(e=B.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var n=he(this.instance.config.capture_dead_clicks)?I({},this.instance.config.capture_dead_clicks):{};n.__onCapture=this.onCapture,this.onCapture&&(n.capture_dead_swipes=!1),this.si=B.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.si.start(P),yr.info("starting...")}}else yr.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,yr.info("stopping..."))}}var Eo=pe("[SegmentIntegration]"),gf="posthog-js";function mf(t,e){var n=e===void 0?{}:e,i=n.organization,r=n.projectId,s=n.prefix,o=n.severityAllowList,a=o===void 0?["error"]:o,l=n.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,f,h,p,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var v,E=((d=c.exception)==null?void 0:d.values)||[],S=E.map((b=>I({},b,{stacktrace:b.stacktrace?I({},b.stacktrace,{type:"raw",frames:(b.stacktrace.frames||[]).map((k=>I({},k,{platform:"web:javascript"})))}):void 0}))),_={$exception_message:((f=E[0])==null?void 0:f.value)||c.message,$exception_type:(h=E[0])==null?void 0:h.type,$exception_level:c.level,$exception_list:S,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((p=E[0])==null?void 0:p.value)||c.message,$sentry_exception_type:(g=E[0])==null?void 0:g.type,$sentry_tags:c.tags};return i&&r&&(_.$sentry_url=(s||"https://sentry.io/organizations/")+i+"/issues/?project="+r+"&query="+c.event_id),u&&((v=t.exceptions)==null||v.sendExceptionEvent(_)),c}}class Jg{constructor(e,n,i,r,s,o){this.name=gf,this.setupOnce=function(a){a(mf(e,{organization:n,projectId:i,prefix:r,severityAllowList:s,sendExceptionsToPostHog:o==null||o}))}}}class Wc{constructor(e){this.li=(n,i,r)=>{r&&(r.noSessionId||r.activityTimeout||r.sessionPastMaximumLength||r.crossTabAdoption)&&(A.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:n,changeReason:r}),this.ui=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.hi()}hi(){var e;this.di=(e=this._instance.sessionManager)==null?void 0:e.onSessionId(this.li)}destroy(){var e;(e=this.di)==null||e.call(this),this.di=void 0}doPageView(e,n){var i,r=this.vi(e,n);return this.ui={pathname:(i=w?.location.pathname)!==null&&i!==void 0?i:"",pageViewId:n,timestamp:e},this._instance.scrollManager.resetContext(),r}doPageLeave(e){var n;return this.vi(e,(n=this.ui)==null?void 0:n.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.ui)==null?void 0:e.pageViewId}}vi(e,n){var i=this.ui;if(!i)return{$pageview_id:n};var r={$pageview_id:n,$prev_pageview_id:i.pageViewId},s=this._instance.scrollManager.getContext();if(s&&!this._instance.config.disable_scroll_properties){var o=s.maxScrollHeight,a=s.lastScrollY,l=s.maxScrollY,u=s.maxContentHeight,c=s.lastContentY,d=s.maxContentY;if(!(C(o)||C(a)||C(l)||C(u)||C(c)||C(d))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),d=Math.ceil(d);var f=o>1?At(a/o,0,1,A):1,h=o>1?At(l/o,0,1,A):1,p=u>1?At(c/u,0,1,A):1,g=u>1?At(d/u,0,1,A):1;r=fe(r,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:f,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:h,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:p,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return i.pathname&&(r.$prev_pageview_pathname=i.pathname),i.timestamp&&(r.$prev_pageview_duration=(e.getTime()-i.timestamp.getTime())/1e3),r}}var So=["flags","surveys"],Zg={[zd]:{exposure:"hidden"},[Fi]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[Ri]:{exposure:"hidden"},[ea]:{exposure:"event"},[ta]:{exposure:"hidden"},[na]:{exposure:"event"},[ia]:{exposure:"hidden"},[ra]:{exposure:"event"},[sa]:{exposure:"event"},[rl]:{exposure:"event"},[sl]:{exposure:"hidden"},[oa]:{exposure:"event"},[An]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[Kn]:{exposure:"hidden"},[ol]:{exposure:"event"},[Vd]:{exposure:"event",shouldSkipFromEventProperties:t=>Ke(t)},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},$sess_rec_flush_size:{exposure:"hidden"},[Sn]:{exposure:"hidden",storageGroup:"flags"},[Ti]:{exposure:"hidden",storageGroup:"flags"},[Ar]:{exposure:"hidden"},[aa]:{exposure:"hidden",storageGroup:"flags"},[$i]:{exposure:"hidden",storageGroup:"flags"},[Pr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[Zr]:{exposure:"hidden",storageGroup:"flags"},[It]:{exposure:"hidden"},[xn]:{exposure:"hidden"},[jt]:{exposure:"hidden"},[In]:{exposure:"hidden"},[la]:{exposure:"hidden",storageGroup:"surveys"},[Xr]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[ca]:{exposure:"event"},[Fr]:{exposure:"hidden"},[Rr]:{exposure:"hidden"},[Mi]:{exposure:"hidden"},$product_tours_activated:{exposure:"hidden"},$product_tours_activated_session:{exposure:"hidden"},$conversations_widget_session_id:{exposure:"event"},$conversations_ticket_id:{exposure:"event"},$conversations_widget_state:{exposure:"event"},$conversations_user_traits:{exposure:"event"},[Cn]:{exposure:"hidden"},[Li]:{exposure:"hidden"},[Tr]:{exposure:"hidden"},[ji]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[ot]:{exposure:"hidden"},[ua]:{exposure:"hidden"},[da]:{exposure:"hidden"},[fa]:{exposure:"hidden"},[ha]:{exposure:"hidden"},[Qr]:{exposure:"hidden"},[es]:{exposure:"hidden"},[Gd]:{exposure:"event"},[Kd]:{exposure:"event"},[Yd]:{exposure:"event"},[Jd]:{exposure:"event"},[Xd]:{exposure:"event"},[Qd]:{exposure:"event"},[ef]:{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"}},Xg=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],yn=t=>{var e=Zg[t];if(e)return e;for(var n of Xg){var i=n[1];if(t.indexOf(n[0])===0)return i}},Yn=(t,e)=>{try{return JSON.stringify(t,((n,i)=>typeof i=="bigint"?i.toString():i),e)}catch{return fd(t)}},ss=t=>{var e=P?.createElement("a");return C(e)?null:(e.href=t,e)},ii=function(t,e){for(var n,i=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),r=0;i.length>r;r++){var s=i[r].split("=");if(s[0]===e){n=s;break}}if(!U(n)||2>n.length)return"";var o=n[1];try{o=decodeURIComponent(o)}catch{A.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},Zi=function(t,e,n){if(!t||!e||!e.length)return t;for(var i=t.split("#"),r=i[1],s=(i[0]||"").split("?"),o=s[1],a=s[0],l=(o||"").split("&"),u=[],c=0;l.length>c;c++){var d=l[c].split("=");U(d)&&(e.includes(d[0])?u.push(d[0]+"="+n):u.push(l[c]))}var f=a;return o!=null&&(f+="?"+u.join("&")),r!=null&&(f+="#"+r),f},os=function(t,e){var n=t.match(new RegExp(e+"=([^&]*)"));return n?n[1]:null},vf=(t,e)=>t>=e&&cd(),_f=(t,e,n,i)=>{if(t===0){if(cd()){var r=e+1;return r===n&&i(),r}return e}return 0},wr="https?://(.*)",ri=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Qg=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...ri],Xi="",em=["li_fat_id"];function yf(t,e,n){if(!P)return{};var i,r=e?[...ri,...n||[]]:[],s=wf(Zi(P.URL,r,Xi),t),o=(i={},ie(em,(function(a){var l=tf(a);i[a]=l||null})),i);return fe(o,s)}function wf(t,e){var n=Qg.concat(e||[]),i={};return ie(n,(function(r){var s=ii(t,r);i[r]=s||null})),i}function bf(t){var e=(function(s){return s?s.search(wr+"google.([^/?]*)")===0?"google":s.search(wr+"bing.com")===0?"bing":s.search(wr+"yahoo.com")===0?"yahoo":s.search(wr+"duckduckgo.com")===0?"duckduckgo":null:null})(t),n=e!="yahoo"?"q":"p",i={};if(!Ke(e)){i.$search_engine=e;var r=P?ii(P.referrer,n):"";r.length&&(i.ph_keyword=r)}return i}function qc(){return navigator.language||navigator.userLanguage}var as="$direct";function Ef(){return P?.referrer||as}function Sf(t,e,n){n===void 0&&(n=!1);var i=t?[...ri,...e||[]]:[],r=n?fn(me?.href):me?.href,s=r?.substring(0,1e3);return{r:Ef().substring(0,1e3),u:s?Zi(s,i,Xi):void 0}}function xf(t,e){var n;e===void 0&&(e=!1);var i=t.r,r=t.u,s=e?fn(r):r,o={$referrer:i,$referring_domain:i==null?void 0:i==as?as:(n=ss(i))==null?void 0:n.host};if(s){o.$current_url=s;var a=ss(s);o.$host=a?.host,o.$pathname=a?.pathname;var l=wf(s);fe(o,l)}if(i){var u=bf(i);fe(o,u)}return o}function If(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function tm(){try{return new Date().getTimezoneOffset()}catch{return}}var nm={flags:ji,surveys:Xr},im=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],Hn="main";class xo{constructor(e,n,i){if(i===void 0&&(i=!0),this.ci={},this.fi=!1,this.pi=!1,this.Ne=e,this.gi=i,this.props={},this.mi=void 0,this.yi=(s=>{var o="";return s.token&&(o=s.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),s.persistence_name?"ph_"+s.persistence_name:"ph_"+o+"_posthog"})(e),this.ii=this.bi(e),this.pi=this.wi(e),this.load(),e.debug&&A.info("Persistence loaded",e.persistence,I({},this.props)),this.update_config(e,e,n),this.save(),w){var r=()=>this.flush();ve(w,"beforeunload",r,{capture:!1}),ve(w,"pagehide",r,{capture:!1})}}ki(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return ke(n)&&n>0?n:0}isDisabled(){return!!this.xi}bi(e){im.indexOf(e.persistence.toLowerCase())===-1&&(A.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var n,i=(function(o,a){o===void 0&&(o=[]),a===void 0&&(a=!1);var l=[...Lg,...o];return I({},le,{H(u){try{var c={};try{c=qt.H(u)||{}}catch{}var d,f=JSON.parse(le.P(u)||"{}");if(a){var h={};for(var p in c){var g=c[p];Ke(g)||g===""||(h[p]=g)}d=fe(f,h)}else d=fe(c,f);return le.F(u,d),d}catch{}return null},F(u,c,d,f,h,p){var g=le.F(u,c,void 0,void 0,p);try{var m={};l.forEach((v=>{c[v]&&(m[v]=c[v])})),Object.keys(m).length&&qt.F(u,m,d,f,h,p)}catch(v){le.j(v)}return g},q(u,c){try{w?.localStorage.removeItem(u),qt.q(u,c)}catch(d){le.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),r=!1,s=e.persistence.toLowerCase();return s==="localstorage"&&le.N()?(n=le,r=!0):s==="localstorage+cookie"&&i.N()?(n=i,r=!0):s==="sessionstorage"&&be.N()?n=be:s==="memory"?n=Ng:s==="cookie"?n=qt:i.N()?(n=i,r=!0):n=qt,this.fi=r,n}Si(e){return this.yi+"__"+e}wi(e){return this.fi&&!!e.split_storage}properties(){var e={};return ie(this.props,((n,i)=>{var r=yn(i);if(!r||r.exposure==="event"){if(r!=null&&r.shouldSkipFromEventProperties!=null&&r.shouldSkipFromEventProperties(n))return;e[i]=n}})),e}load(){if(!this.xi){var e=this.ii.H(this.yi);e&&(this.props=fe({},e)),this.pi&&this.Ci()}}Ci(){for(var e of So){var n=le.H(this.Si(e));if(n&&!Kt(n)){var i=this.Mi(e);i.persisted=!0,this.Ti(e)||(i.fingerprint=this.Ei(n,e)),this.Ii(e,n)||fe(this.props,n)}}}Ti(e){return Object.keys(this.props).some((n=>{var i;return((i=yn(n))==null?void 0:i.storageGroup)===e}))}Ii(e,n){var i=nm[e];if(!i)return!1;var r=n[i],s=this.props[i];return ke(r)&&ke(s)&&s>r}refreshKey(e){var n;if(!this.xi){var i=this.pi?(n=yn(e))==null?void 0:n.storageGroup:void 0,r=i?le.H(this.Si(i)):this.ii.H(this.yi);if(r&&e in r)this.Pi(e,r[e]);else{if(i){var s=this.ii.H(this.yi);if(s&&e in s)return void this.Pi(e,s[e])}this.Ri(e)}}}save(){if(!this.xi){var e=this.ki();e>0?C(this.Ai)&&(this.Ai=setTimeout((()=>{this.Ai=void 0,this.Fi()}),e)):this.Fi()}}flush(){C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0,this.Fi())}Fi(){this.xi||(this.pi?this.Li():this.Oi(this.ii,this.yi,this.props,Hn))}Li(){var e=this.Di(),n=e.main,i=e.groups;for(var r of(this.Oi(this.ii,this.yi,n,Hn),So)){var s,o=i[r];(!Kt(o)||(s=this.ci[r])!=null&&s.persisted)&&this.Oi(le,this.Si(r),o,r)}}Di(){var e={},n={flags:{},surveys:{}};return ie(this.props,((i,r)=>{var s,o=(s=yn(r))==null?void 0:s.storageGroup;o?n[o][r]=i:e[r]=i})),{main:e,groups:n}}Ei(e,n){if(n===Hn)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var i={};return ie(e,((r,s)=>{var o;i[s]=(o=yn(s))!=null&&o.volatile?"__volatile__":r})),JSON.stringify(i)}Oi(e,n,i,r){var s=this.Mi(r);if(r===Hn||s.dirty||C(s.fingerprint)){var o;try{if((o=this.Ei(i,r))===s.fingerprint)return void(s.dirty=!1)}catch{o=void 0}e.F(n,i,this.$i,this.Ni,this.qi,this.Ne.debug)?(s.dirty=!1,r!==Hn&&(s.persisted=!0),C(o)||(s.fingerprint=o)):this.Ne.debug&&A.warn('failed to persist storage entry "'+n+'"; will retry on next save')}}remove(e){var n=(e===void 0?{}:e).keepGroupEntries,i=n!==void 0&&n;if(C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0),this.ii.q(this.yi,!1),this.ii.q(this.yi,!0),!i&&this.gi)for(var r of So)le.q(this.Si(r));i?delete this.ci[Hn]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,n,i){if(he(e)){C(n)&&(n="None"),this.$i=C(i)?this.ji:i;var r=!1;if(ie(e,((s,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==n||(this.Pi(o,s),r=!0)})),r)return this.save(),!0}return!1}register(e,n){if(he(e)){this.$i=C(n)?this.ji:n;var i=!1;if(ie(e,((r,s)=>{e.hasOwnProperty(s)&&(this.props[s]!==r||he(r)||U(r))&&(this.Pi(s,r),i=!0)})),i)return this.save(),!0}return!1}unregister(e){var n=typeof e=="string"?[e]:e,i=!1;for(var r of n)r in this.props&&(this.Ri(r),i=!0);i&&this.save()}update_campaign_params(){var e=P?.URL;if(e!==this.mi){var n=yf(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);Kt(ll(n))||this.register(n),this.mi=e}}update_search_keyword(){var e;this.register((e=P?.referrer)?bf(e):{})}update_referrer_info(){var e;this.register_once({$referrer:Ef(),$referring_domain:P!=null&&P.referrer&&((e=ss(P.referrer))==null?void 0:e.host)||as},void 0)}set_initial_person_info(){this.props[fa]||this.props[ha]||this.register_once({[Qr]:Sf(this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties,this.Ne.disable_capture_url_hashes)},void 0)}get_initial_props(){var e={};ie([ha,fa],(r=>{var s=this.props[r];s&&ie(s,(function(o,a){e["$initial_"+Go(a)]=o}))}));var n=this.props[Qr];if(n){var i=(function(r,s){s===void 0&&(s=!1);var o=xf(r,s),a={};return ie(o,(function(l,u){a["$initial_"+Go(u)]=l})),a})(n,this.Ne.disable_capture_url_hashes);fe(e,i)}return e}safe_merge(e){return ie(this.props,(function(n,i){i in e||(e[i]=n)})),e}update_config(e,n,i){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!i),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var r=e.persistence!==n.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((f,h)=>f===d[h]))})(e.cookie_persisted_properties||[],n.cookie_persisted_properties||[]),s=r?this.bi(e):this.ii,o=this.wi(e);if(r||o!==this.pi){var a=this.props;this.clear(),this.ii=s,this.pi=o,this.props=a,this.save()}}set_disabled(e){this.xi=e,this.xi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ni&&(this.Ni=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this.qi&&(this.qi=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,n){var i=this.props[Ri]||{};i[e]=n,this.Pi(Ri,i),this.save()}remove_event_timer(e){var n=this.props[Ri]||{},i=n[e];return C(i)||(delete n[e],this.Pi(Ri,n),this.save()),i}get_property(e){return this.props[e]}set_property(e,n){this.Pi(e,n),this.save()}Pi(e,n){var i;this.props[e]=n,(i=yn(e))!=null&&i.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var n,i=(n=yn(e))==null?void 0:n.storageGroup;i&&(this.Mi(i).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function br(t){var e=!0;return{dispose(){if(e){e=!1;var n=t();n&&De(n.then)&&n.then(void 0,(()=>{}))}}}}var je={GZipJS:"gzip-js",Base64:"base64"},wi={Activation:"events",Cancellation:"cancelEvents"},Io={Popover:"popover",API:"api",Widget:"widget"},zt={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},ko={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},_a={Popover:"popover",Inline:"inline"},rm={SHOWN:"product tour shown"},zc={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},Vc=pe("[RateLimiter]");class sm{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=n=>{var i=n.text;if(i&&i.length)try{(JSON.parse(i).quota_limited||[]).forEach((r=>{Vc.info((r||"events")+" is quota limited."),this.serverLimits[r]=new Date().getTime()+6e4}))}catch(r){return void Vc.warn('could not rate limit - continuing. Error: "'+r?.message+'"',{text:i})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var n,i,r;e===void 0&&(e=!1);var s=this.captureEventsBurstLimit,o=this.captureEventsPerSecond,a=new Date().getTime(),l=(n=(i=this.instance.persistence)==null?void 0:i.get_property(da))!==null&&n!==void 0?n:{tokens:s,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>s&&(l.tokens=s);var u=1>l.tokens;if(u||e||(l.tokens=Math.max(0,l.tokens-1)),u&&!e){var c=(ke(l.dropped)?l.dropped:0)+1;l.dropped=c,!this.lastEventRateLimited&&this.Hi(c)&&(l.dropped=0)}return this.lastEventRateLimited=u,(r=this.instance.persistence)==null||r.set_property(da,l),{isRateLimited:u,remainingTokens:l.tokens}}Ui(e){var n=this.instance.config.property_denylist;return!U(n)||!n.includes(e)}zi(){var e;if(this.Ui("$current_url")&&this.Ui("$pathname")&&me!=null&&me.pathname)return""+((e=me.origin)!==null&&e!==void 0?e:"")+me.pathname}Hi(e){var n,i,r=this.captureEventsBurstLimit,s=this.captureEventsPerSecond,o=this.zi(),a=this.Ui("$session_id")?(n=(i=this.instance).get_session_id)==null?void 0:n.call(i):void 0,l=[e+" event(s) dropped since the last warning",o?"triggered on "+o:void 0,a?"session "+a:void 0].filter(Boolean).join(", ");return!!this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited: "+l+". Config is set to "+s+" events per second and "+r+" events burst limit."},{skip_client_rate_limiting:!0})}isServerRateLimited(e){var n=this.serverLimits[e||"events"]||!1;return n!==!1&&new Date().getTime()e(this.remoteConfig))):e()}Vi(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:e})}load(){try{if(this.remoteConfig)return an.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void an.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return an.info("No config found after loading remote JS config. Falling back to JSON."),void this.Vi((n=>{this.Zi(n.json,n),this.Gi()}));this.Zi(e),this.Gi()}))}catch(e){an.error("Error loading remote config",e),this.Zi()}}stop(){this.Ki&&(clearInterval(this.Ki),this.Ki=void 0)}refresh(){!this._instance.Qi()&&P&&P.visibilityState!=="hidden"&&this._instance.reloadFeatureFlags()}Gi(){var e;if(!this.Ki){var n=(e=this._instance.config.remote_config_refresh_interval_ms)!==null&&e!==void 0?e:3e5;n!==0&&(this.Ki=setInterval((()=>{this.refresh()}),n))}}Zi(e,n){!e&&n&&(n.statusCode===0?n.error||an.warn("Failed to fetch remote config from PostHog."):an.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(r){an.error("Error applying remote config",r)}if(e?.hasFeatureFlags!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var i;(i=this._instance.featureFlags)==null||i.ensureFlagsLoaded()}catch(r){an.error("Error loading feature flags",r)}}}var ct=Uint8Array,Ge=Uint16Array,si=Uint32Array,fl=new ct([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]),hl=new ct([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]),Gc=new ct([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Cf=function(t,e){for(var n=new Ge(31),i=0;31>i;++i)n[i]=e+=1<i;++i)for(var s=n[i];n[i+1]>s;++s)r[s]=s-n[i]<<5|i;return[n,r]},Af=Cf(fl,2),ya=Af[1];Af[0][28]=258,ya[258]=28;for(var Kc=Cf(hl,0)[1],Pf=new Ge(32768),_e=0;32768>_e;++_e){var Wn=(43690&_e)>>>1|(21845&_e)<<1;Pf[_e]=((65280&(Wn=(61680&(Wn=(52428&Wn)>>>2|(13107&Wn)<<2))>>>4|(3855&Wn)<<4))>>>8|(255&Wn)<<8)>>>1}var Hi=function(t,e,n){for(var i=t.length,r=0,s=new Ge(e);i>r;++r)++s[t[r]-1];var o,a=new Ge(e);for(r=0;e>r;++r)a[r]=a[r-1]+s[r-1]<<1;for(o=new Ge(i),r=0;i>r;++r)o[r]=Pf[a[t[r]-1]++]>>>15-t[r];return o},$n=new ct(288);for(_e=0;144>_e;++_e)$n[_e]=8;for(_e=144;256>_e;++_e)$n[_e]=9;for(_e=256;280>_e;++_e)$n[_e]=7;for(_e=280;288>_e;++_e)$n[_e]=8;var ls=new ct(32);for(_e=0;32>_e;++_e)ls[_e]=5;var om=Hi($n,9),am=Hi(ls,5),Ff=function(t){return(t/8>>0)+(7&t&&1)},Rf=function(t,e,n){(n==null||n>t.length)&&(n=t.length);var i=new(t instanceof Ge?Ge:t instanceof si?si:ct)(n-e);return i.set(t.subarray(e,n)),i},Ot=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8},bi=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8,t[i+2]|=n>>>16},Co=function(t,e){for(var n=[],i=0;t.length>i;++i)t[i]&&n.push({s:i,f:t[i]});var r=n.length,s=n.slice();if(!r)return[new ct(0),0];if(r==1){var o=new ct(n[0].s+1);return o[n[0].s]=1,[o,1]}n.sort((function(b,k){return b.f-k.f})),n.push({s:-1,f:25001});var a=n[0],l=n[1],u=0,c=1,d=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=r-1;)a=n[n[d].f>n[u].f?u++:d++],l=n[u!=c&&n[d].f>n[u].f?u++:d++],n[c++]={s:-1,f:a.f+l.f,l:a,r:l};var f=s[0].s;for(i=1;r>i;++i)s[i].s>f&&(f=s[i].s);var h=new Ge(f+1),p=wa(n[c-1],h,0);if(p>e){i=0;var g=0,m=p-e,v=1<i;++i){var E=s[i].s;if(e>=h[E])break;g+=v-(1<>>=m;g>0;){var S=s[i].s;e>h[S]?g-=1<=0&&g;--i){var _=s[i].s;h[_]==e&&(--h[_],++g)}p=e}return[new ct(h),p]},wa=function(t,e,n){return t.s==-1?Math.max(wa(t.l,e,n+1),wa(t.r,e,n+1)):e[t.s]=n},Yc=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new Ge(++e),i=0,r=t[0],s=1,o=function(l){n[i++]=l},a=1;e>=a;++a)if(t[a]==r&&a!=e)++s;else{if(!r&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(r),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(r);s=1,r=t[a]}return[n.subarray(0,i),e]},Ei=function(t,e){for(var n=0,i=0;e.length>i;++i)n+=t[i]*e[i];return n},ba=function(t,e,n){var i=n.length,r=Ff(e+2);t[r]=255&i,t[r+1]=i>>>8,t[r+2]=255^t[r],t[r+3]=255^t[r+1];for(var s=0;i>s;++s)t[r+s+4]=n[s];return 8*(r+4+i)},Jc=function(t,e,n,i,r,s,o,a,l,u,c){Ot(e,c++,n),++r[256];for(var d=Co(r,15),f=d[0],h=d[1],p=Co(s,15),g=p[0],m=p[1],v=Yc(f),E=v[0],S=v[1],_=Yc(g),b=_[0],k=_[1],T=new Ge(19),x=0;E.length>x;++x)T[31&E[x]]++;for(x=0;b.length>x;++x)T[31&b[x]]++;for(var F=Co(T,7),$=F[0],O=F[1],L=19;L>4&&!$[Gc[L-1]];--L);var N,K,V,M,R=u+5<<3,Z=Ei(r,$n)+Ei(s,ls)+o,Ce=Ei(r,f)+Ei(s,g)+o+14+3*L+Ei(T,$)+(2*T[16]+3*T[17]+7*T[18]);if(Z>=R&&Ce>=R)return ba(e,c,t.subarray(l,l+u));if(Ot(e,c,1+(Z>Ce)),c+=2,Z>Ce){N=Hi(f,h),K=f,V=Hi(g,m),M=g;var oe=Hi($,O);for(Ot(e,c,S-257),Ot(e,c+5,k-1),Ot(e,c+10,L-4),c+=14,x=0;L>x;++x)Ot(e,c+3*x,$[Gc[x]]);c+=3*L;for(var ye=[E,b],$e=0;2>$e;++$e){var ae=ye[$e];for(x=0;ae.length>x;++x)Ot(e,c,oe[Ie=31&ae[x]]),c+=$[Ie],Ie>15&&(Ot(e,c,ae[x]>>>5&127),c+=ae[x]>>>12)}}else N=om,K=$n,V=am,M=ls;for(x=0;a>x;++x)if(i[x]>255){var Ie;bi(e,c,N[257+(Ie=i[x]>>>18&31)]),c+=K[Ie+257],Ie>7&&(Ot(e,c,i[x]>>>23&31),c+=fl[Ie]);var Se=31&i[x];bi(e,c,V[Se]),c+=M[Se],Se>3&&(bi(e,c,i[x]>>>5&8191),c+=hl[Se])}else bi(e,c,N[i[x]]),c+=K[i[x]];return bi(e,c,N[256]),c+K[256]},lm=new si([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),cm=(function(){for(var t=new si(256),e=0;256>e;++e){for(var n=e,i=9;--i;)n=(1&n&&3988292384)^n>>>1;t[e]=n}return t})(),Ao=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8};function um(t,e){e===void 0&&(e={});var n=(function(){var d=4294967295;return{p(f){for(var h=d,p=0;f.length>p;++p)h=cm[255&h^f[p]]^h>>>8;d=h},d(){return 4294967295^d}}})(),i=t.length;n.p(t);var r,s,o,a,l,u=(a=10+((r=e).filename&&r.filename.length+1||0),l=8,(function(d,f,h,p,g,m){var v=d.length,E=new ct(p+v+5*(1+Math.floor(v/7e3))+g),S=E.subarray(p,E.length-g),_=0;if(!f||8>v)for(var b=0;v>=b;b+=65535){var k=b+65535;v>k?_=ba(S,_,d.subarray(b,k)):(S[b]=!0,_=ba(S,_,d.subarray(b,v)))}else{for(var T=lm[f-1],x=T>>>13,F=8191&T,$=(1<b;++b){var Ie=V(b),Se=32767&b,Be=L[Ie];if(O[Se]=Be,L[Ie]=Se,b>=$e){var wt=v-b;if((Ce>7e3||ye>24576)&&wt>423){_=Jc(d,S,0,M,R,Z,oe,ye,ae,b-ae,_),ye=Ce=oe=0,ae=b;for(var ge=0;286>ge;++ge)R[ge]=0;for(ge=0;30>ge;++ge)Z[ge]=0}var Ye=2,bt=0,mn=F,Re=Se-Be&32767;if(wt>2&&Ie==V(b-Re))for(var Pe=Math.min(x,wt)-1,$t=Math.min(32767,b),Bn=Math.min(258,wt);$t>=Re&&--mn&&Se!=Be;){if(d[b+Ye]==d[b+Ye-Re]){for(var qe=0;Bn>qe&&d[b+qe]==d[b+qe-Re];++qe);if(qe>Ye){if(Ye=qe,bt=Re,qe>Pe)break;var Dn=Math.min(Re,qe-2),Mt=0;for(ge=0;Dn>ge;++ge){var Lt=b-Re+ge+32768&32767,ut=Lt-O[Lt]+32768&32767;ut>Mt&&(Mt=ut,Be=Lt)}}}Re+=(Se=Be)-(Be=O[Se])+32768&32767}if(bt){M[ye++]=268435456|ya[Ye]<<18|Kc[bt];var sn=31&ya[Ye],gi=31&Kc[bt];oe+=fl[sn]+hl[gi],++R[257+sn],++Z[gi],$e=b+Ye,++Ce}else M[ye++]=d[b],++R[d[b]]}}_=Jc(d,S,!0,M,R,Z,oe,ye,ae,b-ae,_)}return Rf(E,0,p+Ff(_)+g)})(s=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):12+o.mem,a,l)),c=u.length;return(function(d,f){var h=f.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>f.level?4:f.level==9?2:0,d[9]=3,f.mtime!=0&&Ao(d,4,Math.floor(new Date(f.mtime||Date.now())/1e3)),h){d[3]=8;for(var p=0;h.length>=p;++p)d[p+10]=h.charCodeAt(p)}})(u,e),Ao(u,c-8,n.d()),Ao(u,c-4,i),u}var dm=!!qo||!!Za,Tf="text/plain",Mr=!1,$f=(t,e)=>{var n=t.split("#"),i=n[1],r=n[0].split("?"),s=r[0],o=r[1];if(!o)return t;var a=o.split("&").filter((l=>l.split("=")[0]!==e)).join("&");return s+(a?"?"+a:"")+(i?"#"+i:"")},ks=function(t,e,n){var i;n===void 0&&(n=!0);var r=t.split("?"),s=r[0],o=r[1],a=I({},e),l=(i=o?.split("&").map((c=>{var d,f=c.split("="),h=f[0],p=n&&(d=a[h])!==null&&d!==void 0?d:f[1];return delete a[h],h+"="+p})))!==null&&i!==void 0?i:[],u=(function(c,d){var f,h;d===void 0&&(d="&");var p=[];return ie(c,(function(g,m){C(g)||C(m)||m==="undefined"||(f=encodeURIComponent((v=>v instanceof File)(g)?g.name:g.toString()),h=encodeURIComponent(m),p[p.length]=h+"="+f)})),p.join(d)})(a);return u&&l.push(u),l.length>0?s+"?"+l.join("&"):s},Po=t=>{if(t.Ji)return t.Ji;var e=t.data,n=t.compression;if(e){if(n===je.GZipJS){var i=um((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new ct(a.length+(a.length>>>1)),d=0,f=function(m){c[d++]=m},h=0;u>h;++h){if(d+5>c.length){var p=new ct(d+8+(u-h<<1));p.set(c),c=p}var g=a.charCodeAt(h);128>g?f(g):2048>g?(f(192|g>>>6),f(128|63&g)):g>55295&&57344>g?(f(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++h))>>>18),f(128|g>>>12&63),f(128|g>>>6&63),f(128|63&g)):(f(224|g>>>12),f(128|g>>>6&63),f(128|63&g))}return Rf(c,0,d)})(Yn(e)),{mtime:0});return{contentType:Tf,body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),estimatedSize:i.byteLength}}if(n===je.Base64){var r=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(Yn(e)),s=(a=>"data="+encodeURIComponent(typeof a=="string"?a:Yn(a)))(r);return{contentType:"application/x-www-form-urlencoded",body:s,estimatedSize:new Blob([s]).size}}var o=Yn(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},Mf=t=>{var e,n,i=()=>t.transport==="sendBeacon"?{url:ks(t.url,{compression:je.Base64}),encodedBody:Po(I({},t,{compression:je.Base64,Ji:void 0}))}:{url:$f(t.url,"compression"),encodedBody:Po(I({},t,{compression:void 0,Ji:void 0}))};try{e=Po(t)}catch(r){if(mc(t.compression,ii(t.url,"compression")))return A.error("Failed to gzip request body, sending uncompressed payload",r),i();throw r}return e&&mc(t.compression,ii(t.url,"compression"))&&!((n=e.body)instanceof ArrayBuffer?zo(new Uint8Array(n)):ArrayBuffer.isView(n)&&zo(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)))?(Mr=!0,i()):{url:t.url,encodedBody:e}},Lf=t=>{try{return Mf(t)}catch(e){return A.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},fm=(function(){var t=se((function*(e){var n=Yn(e.data),i=yield(function(s,o,a){return Vo.apply(this,arguments)})(n,ne.DEBUG,{rethrow:!0});if(!i)return e;var r=yield i.arrayBuffer();return I({},e,{Ji:{contentType:Tf,body:r,estimatedSize:r.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),hm=/Failed to fetch|NetworkError|Load failed/i,Nf=t=>t?.name==="TypeError"&&hm.test(t?.message||""),Of=t=>{var e=Lf(t);if(e){var n=e.url,i=e.encodedBody,r=i??{},s=r.contentType,o=r.body,a=r.estimatedSize,l=new Headers;ie(t.headers,(function(p,g){l.append(g,p)})),s&&l.append("Content-Type",s);var u=null,c=!1;if(uc){var d=new uc;u={signal:d.signal,timeout:setTimeout((()=>{var p,g;c=!0,d.abort((p=t.timeout,(g=new Error("PostHog request timed out"+(p?" after "+p+"ms":""))).name="AbortError",g))}),t.timeout)}}var f=p=>{c&&p?.name==="AbortError"||Nf(p)?A.warn(p):A.error(p),t.callback==null||t.callback({statusCode:0,error:p})};try{var h;Za(n,I({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(h=u)==null?void 0:h.signal},t.fetchOptions)).then((p=>p.text().then((g=>{var m={statusCode:p.status,text:g};if(p.status===200)try{m.json=JSON.parse(g)}catch(v){A.error(v)}t.callback==null||t.callback(m)})))).catch(f).finally((()=>u?clearTimeout(u.timeout):null))}catch(p){u&&clearTimeout(u.timeout),f(p)}}},Ea=t=>{try{var e,n=Mf(t),i=n.url,r=n.encodedBody,s=r??{},o=s.body,a=s.estimatedSize;if(!o)return;var l=o instanceof Blob?o:new Blob([o],{type:s.contentType});if(Ue.sendBeacon(i,l))return;var u=U(t.data)?t.data:(e=t.data)==null?void 0:e.batch;if(U(u)&&u.length>1&&(a??0)>16384){var c=Math.ceil(u.length/2),d=f=>U(t.data)?f:I({},t.data,{batch:f});return Ea(I({},t,{data:d(u.slice(0,c))})),void Ea(I({},t,{data:d(u.slice(c))}))}A.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),Of(I({},t,{Yi:!0}))}catch(f){A.warn("Beacon send failed",f)}},Zc=(t,e,n,i)=>{var r=i==="query"?e==="POST"?"sent_at":"_":void 0;return ks(n===je.GZipJS?$f(t,"compression"):t,I({},r?{[r]:Date.now().toString()}:{},n===je.GZipJS?{}:{compression:n}))},Lr=[];Za&&Lr.push({transport:"fetch",method:Of}),qo&&Lr.push({transport:"XHR",method(t){var e=Lf(t);if(e){var n=new qo,i=e.encodedBody;n.open(t.method||"GET",e.url,!0);var r=i??{},s=r.contentType,o=r.body;ie(t.headers,(function(a,l){n.setRequestHeader(l,a)})),s&&n.setRequestHeader("Content-Type",s),t.timeout&&(n.timeout=t.timeout),n.onreadystatechange=()=>{if(n.readyState===4){var a={statusCode:n.status,text:n.responseText};if(n.status===200)try{a.json=JSON.parse(n.responseText)}catch{}t.callback==null||t.callback(a)}},n.send(o)}}}),Ue!=null&&Ue.sendBeacon&&Lr.push({transport:"sendBeacon",method:Ea});var Sa=3e3;class pm{constructor(e,n){this.Xi=!0,this.tr=[],this.er=At(n?.flush_interval_ms||Sa,250,5e3,A.createLogger("flush interval"),Sa),this.ir=e}enqueue(e){this.tr.push(e),this.rr||this.nr()}unload(){this.sr();var e=this.tr.length>0?this.ar():{},n=Object.values(e);[...n.filter((i=>i.url.indexOf("/e")===0)),...n.filter((i=>i.url.indexOf("/e")!==0))].map((i=>{this.lr(I({},i,{transport:"sendBeacon"}))}))}enable(){this.Xi=!1,this.nr()}nr(){var e=this;this.Xi||(this.rr=setTimeout((()=>{if(this.sr(),this.tr.length>0){var n=this.ar(),i=function(){var s=n[r],o=new Date().getTime();s.data&&U(s.data)&&ie(s.data,(a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp})),e.lr(s)};for(var r in n)i()}}),this.er))}lr(e){try{this.ir(e)}catch(n){A.error(n)}}sr(){clearTimeout(this.rr),this.rr=void 0}ar(){var e={};return ie(this.tr,(n=>{var i,r=n,s=(r?r.batchKey:null)||r.url;C(e[s])&&(e[s]=I({},r,{data:[]})),(i=e[s].data)==null||i.push(r.data)})),this.tr=[],e}}var gm=["retriesPerformedSoFar"];class mm{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!C(w)&&"onLine"in w.navigator&&(this.dr=w.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},ve(w,"online",this.vr),ve(w,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var n=e.retriesPerformedSoFar,i=ud(e,gm);Dt(n)&&(i.url=ks(i.url,{retry_count:n})),this._instance._send_request(I({},i,{callback:r=>{if(r.statusCode!==200&&(400>r.statusCode||r.statusCode>=500)){if((r.statusCode===0?3:10)>(n??0))return void this.At(I({retriesPerformedSoFar:n},i));r.statusCode===0&&A.warn("Request failed before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped retrying after "+(n??0)+" retries.")}i.callback==null||i.callback(r)}}))}At(e){var n=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=n+1;var i=(function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),c=Math.random()-.5;return Math.ceil(u+c*(u-l))})(n),r=Date.now()+i;this.tr.push({retryAt:r,requestOptions:e});var s="Enqueued failed request for retry in "+i;navigator.onLine||(s+=" (Browser is offline)"),A.warn(s),this.ur||(this.ur=!0,this.gr())}gr(){if(this.mr&&clearTimeout(this.mr),this.tr.length===0)return this.ur=!1,void(this.mr=void 0);this.mr=setTimeout((()=>{this.dr&&this.tr.length>0&&this.cr(),this.gr()}),this.hr)}cr(){var e=Date.now(),n=[],i=this.tr.filter((s=>e>s.retryAt||(n.push(s),!1)));if(this.tr=n,i.length>0)for(var r of i)this.retriableRequest(r.requestOptions)}unload(){for(var e of(this.mr&&(clearTimeout(this.mr),this.mr=void 0),this.ur=!1,C(w)||(this.vr&&(w.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(w.removeEventListener("offline",this.pr),this.pr=void 0)),this.tr)){var n=e.requestOptions;try{this._instance._send_request(I({},n,{transport:"sendBeacon"}))}catch(i){A.error(i)}}this.tr=[]}}class vm{constructor(e){this.yr=()=>{var n,i,r,s;this.br||(this.br={});var o=this.scrollElement(),a=this.scrollY(),l=o?Math.max(0,o.scrollHeight-o.clientHeight):0,u=a+(o?.clientHeight||0),c=o?.scrollHeight||0;this.br.lastScrollY=Math.ceil(a),this.br.maxScrollY=Math.max(a,(n=this.br.maxScrollY)!==null&&n!==void 0?n:0),this.br.maxScrollHeight=Math.max(l,(i=this.br.maxScrollHeight)!==null&&i!==void 0?i:0),this.br.lastContentY=u,this.br.maxContentY=Math.max(u,(r=this.br.maxContentY)!==null&&r!==void 0?r:0),this.br.maxContentHeight=Math.max(c,(s=this.br.maxContentHeight)!==null&&s!==void 0?s:0)},this._instance=e}get _r(){return this._instance.config.scroll_root_selector}getContext(){return this.br}resetContext(){var e=this.br;return setTimeout(this.yr,0),e}startMeasuringScrollPosition(){ve(w,"scroll",this.yr,{capture:!0}),ve(w,"scrollend",this.yr,{capture:!0}),ve(w,"resize",this.yr)}scrollElement(){if(!this._r)return w?.document.documentElement;var e=U(this._r)?this._r:[this._r];for(var n of e){var i=w?.document.querySelector(n);if(i)return i}}wr(e){var n=e==="y"?"scrollTop":"scrollLeft";if(this._r){var i=this.scrollElement();return i&&i[n]||0}return w?e==="y"?w.scrollY||w.pageYOffset||w.document.documentElement.scrollTop||0:w.scrollX||w.pageXOffset||w.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var _m=t=>Sf(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class Xc{constructor(e,n,i,r){this.kr=s=>{var o=this.Sr();if(!o||o.sessionId!==s){var a={sessionId:s,props:this.Cr(this._instance)};this.Mr.register({[ua]:a})}},this._instance=e,this.Tr=n,this.Mr=i,this.Cr=r||_m,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[ua]}getSetOnceProps(){var e,n=(e=this.Sr())==null?void 0:e.props;return n?"r"in n?xf(n,this._instance.config.disable_capture_url_hashes):{$referring_domain:n.referringDomain,$pathname:n.initialPathName,utm_source:n.utm_source,utm_campaign:n.utm_campaign,utm_medium:n.utm_medium,utm_content:n.utm_content,utm_term:n.utm_term}:{}}getSessionProps(){var e={};return ie(ll(this.getSetOnceProps()),((n,i)=>{i==="$current_url"&&(i="url"),e["$session_entry_"+Go(i)]=n})),e}}class pl{on(e,n){return this.Er[e]||(this.Er[e]=[]),this.Er[e].push(n),()=>{this.Er[e]=this.Er[e].filter((i=>i!==n))}}emit(e,n){for(var i of this.Er[e]||[])i(n);for(var r of this.Er["*"]||[])r(e,n)}constructor(){this.Er={}}}var Si=pe("[SessionId]");class Qc{on(e,n){return this.Ir.on(e,n)}constructor(e,n,i){var r;if(this.Pr=null,this.Rr=[],this.Ar=void 0,this.Fr=!1,this.Ir=new pl,this.Lr=(u,c)=>!(!Dt(u)||!Dt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===Wt)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Ne=e.config,this.Mr=e.persistence,this.Or=void 0,this.Dr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.$r=n||Ht,this.Nr=i||Ht;var s=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*At(this.Ne.session_idle_timeout_seconds||1800,60,36e3,Si.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.qr(),this.jr="ph_"+s+"_window_id",this.Br="ph_"+s+"_primary_window_exists",this.Hr()){var o=be.H(this.jr),a=be.H(this.Br);o&&!a?this.Or=o:be.q(this.jr),be.F(this.Br,!0)}if((r=this.Ne.bootstrap)!=null&&r.sessionID)try{var l=(u=>{var c=this.Ne.bootstrap.sessionID.replace(/-/g,"");if(c.length!==32)throw new Error("Not a valid UUID");if(c[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(c.substring(0,12),16)})();this.Ur(this.Ne.bootstrap.sessionID,new Date().getTime(),l)}catch(u){Si.error("Invalid sessionID in bootstrap",u)}this.zr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return C(this.Rr)&&(this.Rr=[]),this.Rr.push(e),this.Dr&&e(this.Dr,this.Or),()=>{this.Rr=this.Rr.filter((n=>n!==e))}}Hr(){return this.Ne.persistence!=="memory"&&!this.Mr.xi&&be.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&be.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?be.H(this.jr):null}Zr(e){var n=this.Pr;return!Ke(n)&&!Ke(e)&&5e3>Math.abs(e-n)}Ur(e,n,i){var r=n!==this._sessionActivityTimestamp,s=!(e!==this.Dr||i!==this._sessionStartTimestamp);this._sessionStartTimestamp=i,this._sessionActivityTimestamp=n,this.Dr=e,s&&!r||s&&this.Zr(n)||(this.Pr=n,this.Mr.register({[Kn]:[n,e,i]}))}Gr(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return Dt(n)&&n>0}Qr(){this.Gr()?this.Mr.refreshKey(Kn):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!Ke(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this.Pr){this.Qr();var n=this.Jr();n[1]===this.Dr&&n[2]===this._sessionStartTimestamp&&(this.Pr=this._sessionActivityTimestamp,this.Mr.register({[Kn]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],n=Dt(e)?e:0,i=Dt(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(n,i)}Xr(e){return this.Qr(),this.Lr(e,this.Yr())}Jr(){var e=this.Mr.props[Kn];return U(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Pr=null,clearTimeout(this.tn),this.tn=void 0,this.Ur(null,null,null)}destroy(){this.Fr=!0,this.Kr(),clearTimeout(this.tn),this.tn=void 0,this.Ar&&w&&(w.removeEventListener(ns,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&be.q(this.Br)},ve(w,ns,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=null),this.Ne.cookieless_mode===Wt)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var i=n||new Date().getTime(),r=this.Jr(),s=r[1],o=r[2],a=this.Yr(),l=this.Vr(),u=Dt(o)&&Math.abs(i-o)>864e5,c=!1,d=!1,f=!s,h=s,p=!f&&!e&&this.Lr(i,a);if(p){(p=this.Xr(i))||Si.info("cross-tab refresh kept the session alive",{sessionId:s});var g=this.Jr();s=g[1],o=g[2]}f||p||u?(s=this.$r(),l=this.Nr(),Si.info("new session ID generated",{sessionId:s,windowId:l,changeReason:{noSessionId:f,activityTimeout:p,sessionPastMaximumLength:u}}),o=i,c=!0):(l||(l=this.Nr(),c=!0),(d=s!==h)&&(Si.info("adopted cross-tab session id",{sessionId:s,windowId:l}),c=!0));var m=Dt(a)&&e&&!u?a:i,v=Dt(o)?o:new Date().getTime();this.Wr(l),this.Ur(s,m,v),e||this.qr();var E={noSessionId:f,activityTimeout:p,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((S=>S(s,l,E))),{sessionId:s,windowId:l,sessionStartTimestamp:v,changeReason:c?E:void 0,lastActivityTimestamp:a}}qr(){this.Fr||(clearTimeout(this.tn),this.tn=setTimeout((()=>{if(!this.Fr)if(this.Xr(new Date().getTime())){var e=this.Dr;this.resetSessionId(),this.Ir.emit("forcedIdleReset",{idleSessionId:e})}else this.qr()}),1.1*this.sessionTimeoutMs))}}var Bf=function(t,e){if(!t)return!1;var n=t.userAgent;if(n&&_c(n,e))return!0;try{var i=t?.userAgentData;if(i!=null&&i.brands&&i.brands.some((r=>_c(r?.brand,e))))return!0}catch{}return!!t.webdriver};function Df(){return(Df=se((function*(){var t=Ue?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),n=e?.model;return X(n)&&n.length>0?n:void 0}catch(i){return void A.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",i)}}))).apply(this,arguments)}var cs=function(t,e){if(!(function(n){try{new RegExp(n)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function Fo(t,e,n){return Yn({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}var jf={exact:(t,e)=>e.some((n=>t.some((i=>n===i)))),is_not:(t,e)=>e.every((n=>t.every((i=>n!==i)))),regex:(t,e)=>e.some((n=>t.some((i=>cs(n,i))))),not_regex:(t,e)=>e.every((n=>t.every((i=>!cs(n,i))))),icontains:(t,e)=>e.map(Er).some((n=>t.map(Er).some((i=>n.includes(i))))),not_icontains:(t,e)=>e.map(Er).every((n=>t.map(Er).every((i=>!n.includes(i))))),gt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>i>parseFloat(r)))})),lt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>it.toLowerCase();function Uf(t,e){return!t||Object.entries(t).every((n=>{var i=n[1],r=e?.[n[0]];if(C(r)||Ke(r))return!1;var s=[String(r)],o=jf[i.operator];return!!o&&o(i.values,s)}))}var xa="custom",eu="i.posthog.com",ym=/^\/static\//;class wm{constructor(e){this.en={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,n=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return n||(n=this.apiHost.replace("."+eu,".posthog.com")),n==="https://app.posthog.com"?"https://us.posthog.com":n}get region(){return this.en[this.apiHost]||(this.en[this.apiHost]=/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"us":/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"eu":xa),this.en[this.apiHost]}rn(e){if(ym.test(e)){var n=this.instance.config.asset_host;if(typeof n=="string")return n.trim().replace(/\/$/,"")||void 0}}endpointFor(e,n){if(n===void 0&&(n=""),n&&(n=n[0]==="/"?n:"/"+n),e==="ui")return this.uiHost+n;if(e==="flags")return this.flagsApiHost+n;if(e==="assets"){var i=this.rn(n);if(i)return""+i+n}if(this.region===xa)return this.apiHost+n;var r=eu+n;switch(e){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}}function Hf(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var Q=pe("[Surveys]"),Wf="seenSurvey_",qf=t=>{try{var e=(n=>((i,r)=>""+Wf+(function(s){return s.current_iteration&&s.current_iteration>0?s.id+"_"+s.current_iteration:s.id})(r))(0,n))(t);if(localStorage.getItem(e))return;localStorage.setItem(e,"true")}catch(n){Q.error("Failed to persist survey seen state",n)}},bm=[Io.Popover,Io.Widget,Io.API],Em={ignoreConditions:!1,ignoreDelay:!1,displayType:_a.Popover},Sm=pe("[PostHog ExternalIntegrations]"),xm={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class Im{constructor(e){this._instance=e}ai(e,n){var i;(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,e,(r=>{if(r)return Sm.error("failed to load script",r);n()}))}startIfEnabledOrStop(){var e=this,n=function(){var s,o,a,l=i[0],u=i[1];!u||(s=B.__PosthogExtensions__)!=null&&(s=s.integrations)!=null&&s[l]||e.ai(xm[l],(()=>{var c;(c=B.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=B.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=B.__PosthogExtensions__)==null||(a=a.integrations)==null||(a=a[l])==null||a.stop())};for(var i of Object.entries((r=this._instance.config.integrations)!==null&&r!==void 0?r:{})){var r;n()}}}class km{constructor(e,n){this.rt=e,this.nn=n,this.sn=new Map,this.an=!1}add(e){var n=this;return se((function*(){if(n.an)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(n.sn.has(e.name))throw new Error('Browser extension "'+e.name+'" is already registered');n.sn.set(e.name,e);try{var i=e.setup(n.nn);i&&(yield i)}catch(s){var r=n.sn.get(e.name)===e;r&&n.sn.delete(e.name),n.rt.error('Failed to set up browser extension "'+e.name+'"',s),r&&n.ln(e)}}))()}dispose(){if(!this.an){this.an=!0;var e=Array.from(this.sn.values()).reverse();for(var n of(this.sn.clear(),e))this.ln(n)}}ln(e){try{var n=e.dispose==null?void 0:e.dispose();n&&De(n.then)&&n.then(void 0,(i=>{this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}))}catch(i){this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}}}class Cm{constructor(e){this._instance=e}initialize(){}get(e){var n=this._instance.persistence;if(typeof e=="string")return n?.get_property(e);var i={};for(var r of e){var s=n?.get_property(r);C(s)||(i[r]=s)}return i}set(e,n){var i;(i=this._instance.persistence)==null||i.register(typeof e=="string"?{[e]:n}:e)}remove(e){var n;(n=this._instance.persistence)==null||n.unregister(e)}}var tu="extensionsRemoteConfig";class Am{constructor(e){this.an=!1,this.instance=e,this.rt=A,this.un=e.hn,this.kv=new Cm(e),this.onEvent=n=>br(this.instance.on("eventCaptured",(i=>{try{n({event:i.event,properties:i.properties})}catch(r){this.rt.error("Browser extension event listener failed",r)}}))),this.onRemoteConfig=n=>{if(this.an)return br((()=>{}));var i=s=>{try{n(s)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},r=this.instance.dn.on(tu,i);return this.un&&i(this.un),br(r)},this.vn=new km(A.createLogger("[BrowserExtensions]"),this)}get logger(){return this.rt}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return(e=this.instance.get_property(Yi))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(Yi);return typeof e=="string"?e:void 0}get library(){return{name:ne.LIB_NAME,version:ne.LIB_VERSION}}get initialPersonProperties(){var e,n;return(e=(n=this.instance.persistence)==null?void 0:n.get_initial_props())!==null&&e!==void 0?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,n,i,r,s=(e=this.instance.sessionManager)==null?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:(n=s?.sessionId)!==null&&n!==void 0?n:"",windowId:(i=s?.windowId)!==null&&i!==void 0?i:"",sessionStartTimestamp:(r=s?.sessionStartTimestamp)!==null&&r!==void 0?r:0}}catch{return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get projectToken(){return this.instance.config.token}add(e){return this.vn.add(e)}capture(e,n,i){var r=this;return se((function*(){i?r.instance.capture(e,n,{timestamp:i.timestamp,uuid:i.uuid,$set:i.set,$set_once:i.setOnce}):r.instance.capture(e,n)}))()}registerDynamicEventProperties(e){return br(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(tu,e))}sendRequest(e,n){var i=this;return se((function*(){var r;n===void 0&&(n={});var s=i.instance.requestRouter.endpointFor((r=n.target)!==null&&r!==void 0?r:"api",e),o={method:n.method,url:n.query?ks(s,n.query):s,data:n.body,headers:n.headers,timeout:n.timeoutMs,fireCallbackOnDrop:!0,transport:n.transport,compression:n.compression,timestampMode:n.sentAt};return n.transport==="sendBeacon"?(i.instance._send_request(o),{statusCode:202}):new Promise((a=>{o.callback=a,i.instance._send_request(o)}))}))()}dispose(){this.an||(this.an=!0,this.vn.dispose())}}var Wi={},Ro=0,us=()=>{},nu='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',xi="Surveys module not available",iu="sanitize_properties is deprecated. Use before_send instead",zf="Invalid value for property_denylist config: ",Pm=["token","distinct_id",Zd],Gn="posthog",Vf=!dm&&Ve?.indexOf("MSIE")===-1&&Ve?.indexOf("Mozilla")===-1,To=t=>{var e;return I({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:Fg(P?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:us,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:t??"unset",__preview_deferred_init_extensions:!1,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:me&&X(me?.search)&&me.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disableDeviceModel:!1,disable_external_dependency_loading:!1,strict_script_versioning:!1,enable_recording_console_log:void 0,secure_cookie:(w==null||(e=w.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(n){A.error("Bad HTTP status: "+n.statusCode+" "+n.text)},get_device_id:n=>n,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:pa,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:Sa},error_tracking:{},_onCapture:us},(n=>({rageclick:n&&n>="2026-05-30"?{content_ignorelist:Hg,ignore_text_selection:!0}:!n||"2025-11-30">n||{content_ignorelist:!0},capture_pageview:!n||"2025-05-24">n||"history_change",session_recording:n&&n>="2026-06-25"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6},streamNetworkBody:!0}:n&&n>="2026-05-30"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6}}:n&&n>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:n&&n>="2026-01-30"?"head":"body",internal_or_test_user_hostname:n&&n>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:n&&n>="2026-05-30"?250:0,split_storage:!(!n||"2026-05-30">n),detect_google_search_app:!(!n||"2026-05-30">n),disable_capture_url_hashes:!(!n||"2026-06-25">n)}))(t))},Fm=[["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"]],ru=t=>{var e={};for(var n of Fm){var i=n[0],r=n[1];C(t[i])||(e[r]=t[i])}var s=fe({},e,t),o=t.__preview_external_dependency_versioned_paths;return C(o)||(C(t.strict_script_versioning)&&(s.strict_script_versioning=!!o),X(o)&&C(t.asset_host)&&(s.asset_host=o)),U(t.property_blacklist)&&(C(t.property_denylist)?s.property_denylist=t.property_blacklist:U(t.property_denylist)?s.property_denylist=[...t.property_blacklist,...t.property_denylist]:A.error(zf+t.property_denylist)),s};class Rm{constructor(){this.__forceAllowLocalhost=!1}get fn(){return this.__forceAllowLocalhost}set fn(e){A.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class Je{pn(e,n){if(e){var i=this.sn.indexOf(e);i!==-1&&this.sn.splice(i,1)}return this.sn.push(n),n.initialize==null||n.initialize(),n}gn(){return this.config.cookieless_mode===Wt||this.config.cookieless_mode===kn&&this.consent.isRejected()}get decideEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){var e;this.webPerformance=new Rm,this.mn=!1,this.version=ne.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new pl,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=To(),this.SentryIntegration=Jg,this.sentryIntegration=i=>(function(r,s){var o=mf(r,s);return{name:gf,processEvent:a=>o(a)}})(this,i),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.wn=!1,this.kn=null,this.xn=null,this.Sn=null,this.scrollManager=new vm(this),this.pageViewManager=new Wc(this),this.rateLimiter=new sm(this),this.requestRouter=new wm(this),this.consent=new Og(this),this.externalIntegrations=new Im(this);var n=(e=Je.__defaultExtensionClasses)!==null&&e!==void 0?e:{};this.featureFlags=n.featureFlags&&new n.featureFlags(this),this.toolbar=n.toolbar&&new n.toolbar(this),this.surveys=n.surveys&&new n.surveys(this),this.conversations=n.conversations&&new n.conversations(this),this.logs=n.logs&&new n.logs(this),this.metrics=n.metrics&&new n.metrics(this),this.experiments=n.experiments&&new n.experiments(this),this.exceptions=n.exceptions&&new n.exceptions(this),this.people={set:(i,r,s)=>{var o=X(i)?{[i]:r}:i;this.setPersonProperties(o),s?.({})},set_once:(i,r,s)=>{var o=X(i)?{[i]:r}:i;this.setPersonProperties(void 0,o),s?.({})}},this.on("eventCaptured",(i=>A.info('send "'+i?.event+'"',i)))}init(e,n,i){if(i&&i!==Gn){var r,s=(r=Wi[i])!==null&&r!==void 0?r:new Je;return s._init(e,n,i),Wi[i]=s,Wi[Gn][i]=s,s}return this._init(e,n,i)}_init(e,n,i){var r,s;n===void 0&&(n={});var o,a=X(e)?e.trim():"";if(!a)return A.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return a!==((o=this.config)==null?void 0:o.token)?console.warn("[PostHog.js]","You have already initialized PostHog with a different project token! Re-initializing is a no-op, so events will keep going to the project this instance was initialized with. To capture into a second project, load PostHog once, then initialize a named instance after the SDK has loaded, e.g. posthog.init('"+a+"', { ... }, 'project2')"):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=To(n.defaults),n.debug=this.Cn(n.debug),this.Mn=n,this.Tn=[],n.person_profiles?this.xn=n.person_profiles:n.process_person&&(this.xn=n.process_person);var l=To(n.defaults),u=ru(n),c=fe({},l,u,{name:i,token:a});he(l.rageclick)&&he(u.rageclick)&&(c.rageclick=fe({},l.rageclick,u.rageclick)),he(l.session_recording)&&he(u.session_recording)&&(c.session_recording=fe({},l.session_recording,u.session_recording)),this.set_config(c),this.config.on_xhr_error&&A.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=n.disable_compression?void 0:je.GZipJS;var d=this.En();if(this.persistence=new xo(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new xo(I({},this.config,{persistence:"sessionStorage"}),d,!1),this.bn="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&be.N()){var f=be.H(this.bn);U(f)&&f.forEach((k=>{X(k)&&this.yn.add(k)}))}else be.q(this.bn);var h=I({},this.persistence.props),p=I({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new pm((k=>this.Pn(k)),this.config.request_queue_config),this.Rn=new mm(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new Qc(this),this.sessionPropsManager=new Xc(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((k,T,x)=>{(x!=null&&x.activityTimeout||x!=null&&x.sessionPastMaximumLength||x!=null&&x.crossTabAdoption)&&this.An()}))),this.Fn(),this.config.__preview_deferred_init_extensions?(A.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Ln(g)}),0)):(A.info("Initializing extensions synchronously"),this.Ln(g)),ne.DEBUG=ne.DEBUG||this.config.debug,ne.DEBUG&&A.info("Starting in debug mode",{this:this,config:n,thisC:I({},this.config),p:h,s:p}),!this.config.identity_distinct_id||(r=n.bootstrap)!=null&&r.distinctID||(n.bootstrap=I({},n.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((s=n.bootstrap)==null?void 0:s.distinctID)!==void 0){var m=n.bootstrap.distinctID,v=this.get_distinct_id(),E=this.persistence.get_property(ot);if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&E===Un)this.identify(m);else if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&E===vn)A.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{var S=this.config.get_device_id(Ht()),_=n.bootstrap.isIdentifiedID?S:m;this.persistence.set_property(ot,n.bootstrap.isIdentifiedID?vn:Un),this.register({distinct_id:m,$device_id:_})}}if(g)this.register_once({distinct_id:mr,$device_id:null},"");else if(!this.get_distinct_id()){var b=this.config.get_device_id(Ht());this.register_once({distinct_id:b,$device_id:b},""),this.persistence.set_property(ot,Un)}return ve(w,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),n.segment?(function(k,T){var x=k.config.segment;if(!x)return T();(function(F,$){var O=F.config.segment;if(!O)return $();var L=K=>{var V=()=>K.anonymousId()||Ht();F.config.get_device_id=V,K.id()&&(F.register({distinct_id:K.id(),$device_id:V()}),F.persistence.set_property(ot,vn)),$()},N=O.user();"then"in N&&De(N.then)?N.then(L):L(N)})(k,(()=>{x.register((F=>{typeof Promise<"u"&&Promise.resolve||Eo.warn("This browser does not have Promise support, and can not use the segment integration");var $=(O,L)=>{if(!L)return O;O.event.userId||O.event.anonymousId===F.get_distinct_id()||(Eo.info("No userId set, resetting PostHog"),F.reset()),O.event.userId&&O.event.userId!==F.get_distinct_id()&&(Eo.info("UserId set, identifying with PostHog"),F.identify(O.event.userId));var N=F.calculateEventProperties(L,O.event.properties);return O.event.properties=Object.assign({},N,O.event.properties),O};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:O=>$(O,O.event.event),page:O=>$(O,Vn),identify:O=>$(O,yo),screen:O=>$(O,"$screen")}})(k)).then((()=>{T()}))}))})(this,(()=>this.On())):this.On(),De(this.config._onCapture)&&this.config._onCapture!==us&&(A.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(k=>this.config._onCapture(k.event,k)))),this.config.ip&&A.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this.config.disableDeviceModel||(function(){return Df.apply(this,arguments)})().then((k=>{k&&this.register({[vo]:k})})).catch(us),this}Fn(){var e,n,i,r,s,o,a=(e=(n=this.config.__extensionClasses)==null?void 0:n.featureFlags)!==null&&e!==void 0?e:(i=Je.__defaultExtensionClasses)==null?void 0:i.featureFlags;a&&(this.featureFlags&&this.featureFlags instanceof a||((r=this.Dn)==null||r.call(this),this.Dn=void 0,this.featureFlags=new a(this)),De(this.featureFlags.onReloading)&&De(this.featureFlags.setup)?this.Dn||(this.Dn=this.featureFlags.onReloading((()=>{this.dn.emit("featureFlagsReloading",!0)})),this.$n().add(this.featureFlags)):(s=(o=this.featureFlags).initialize)==null||s.call(o))}Ln(e){var n,i,r,s,o,a,l,u=performance.now(),c=I({},Je.__defaultExtensionClasses,this.config.__extensionClasses),d=[];c.exceptions&&this.sn.push(this.exceptions=(n=this.exceptions)!==null&&n!==void 0?n:new c.exceptions(this)),c.historyAutocapture&&this.sn.push(this.historyAutocapture=new c.historyAutocapture(this)),c.tracingHeaders&&this.sn.push(this.tracingHeaders=new c.tracingHeaders(this)),c.siteApps&&this.sn.push(this.siteApps=new c.siteApps(this)),c.sessionRecording&&!e&&this.sn.push(this.sessionRecording=new c.sessionRecording(this)),this.config.disable_scroll_properties||d.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),c.autocapture&&this.sn.push(this.autocapture=new c.autocapture(this)),c.surveys&&this.sn.push(this.surveys=(i=this.surveys)!==null&&i!==void 0?i:new c.surveys(this)),c.logs&&this.sn.push(this.logs=(r=this.logs)!==null&&r!==void 0?r:new c.logs(this)),c.metrics&&this.sn.push(this.metrics=(s=this.metrics)!==null&&s!==void 0?s:new c.metrics(this)),c.conversations&&this.sn.push(this.conversations=(o=this.conversations)!==null&&o!==void 0?o:new c.conversations(this)),c.productTours&&this.sn.push(this.productTours=new c.productTours(this)),c.heatmaps&&this.sn.push(this.heatmaps=new c.heatmaps(this)),c.webVitalsAutocapture&&this.sn.push(this.webVitalsAutocapture=new c.webVitalsAutocapture(this)),c.exceptionObserver&&this.sn.push(this.exceptionObserver=new c.exceptionObserver(this)),c.deadClicksAutocapture&&this.sn.push(this.deadClicksAutocapture=new c.deadClicksAutocapture(this,Yg)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((f=>{f.initialize&&d.push((()=>{f.initialize==null||f.initialize()}))})),d.push((()=>{if(this.Nn){var f=this.Nn;this.Nn=void 0,this.sn.forEach((h=>h.onRemoteConfig==null?void 0:h.onRemoteConfig(f)))}})),this.qn(d,u)}qn(e,n){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,n)}),0);var i=e.shift();if(i)try{i()}catch(s){A.error("Error initializing extension:",s)}}var r=Math.round(performance.now()-n);this.register_for_session({[Xd]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[Qd]:r}),this.config.__preview_deferred_init_extensions&&A.info("PostHog extensions initialized ("+r+"ms)")}Zi(e){var n;if(!P||!P.body)return A.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.Zi(e)}),500);if(this.config.__preview_deferred_init_extensions&&(this.Nn=e),this.hn=e,this.compression=void 0,e.ok){var i,r=e.config;r.supportedCompression&&!this.config.disable_compression&&(this.compression=j(r.supportedCompression,je.GZipJS)?je.GZipJS:j(r.supportedCompression,je.Base64)?je.Base64:void 0),(i=r.analytics)!=null&&i.endpoint&&(this.analyticsDefaultEndpoint=r.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:pa}),(n=this.jn)==null||n.handleRemoteConfig(e),this.sn.forEach((s=>s.onRemoteConfig==null?void 0:s.onRemoteConfig(e)))}On(){try{this.config.loaded(this)}catch(i){A.critical("`loaded` function failed",i)}if(this.Bn(),this.config.internal_or_test_user_hostname&&me!=null&&me.hostname){var e=me.hostname,n=this.config.internal_or_test_user_hostname;(typeof n=="string"?e===n:n.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.gn())&&this.Hn()}),1),this.Un=new kf(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()&&vr(this.__request_queue,(e=>this.Pn(e))),this.__request_queue=[],this.Bn()}_handle_unload(){var e,n,i,r,s;(e=this.surveys)==null||e.handlePageUnload==null||e.handlePageUnload(),(n=this.metrics)==null||n.flush("sendBeacon"),this.config.request_batching?(this.zn()&&this.capture(_o),(i=this.logs)==null||i.flushLogs("sendBeacon"),(r=this.In)==null||r.unload(),(s=this.Rn)==null||s.unload()):this.zn()&&this.capture(_o,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?Vf?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)?e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:429})):(e.transport=e.transport||this.config.api_transport,e.headers=I({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,(C(this.config.disable_beacon)?this.config.__preview_disable_beacon:this.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(n=>{var i,r,s,o=I({},n);o.timeout=o.timeout||6e4;var a,l,u,c,d,f=(i=o.transport)!==null&&i!==void 0?i:"fetch";f==="sendBeacon"&&C(o.compression)&&o.data&&(o.compression=je.Base64),o.method==="POST"&&o.data&&(o.timestampMode==="capture-body"?o.data={api_key:(l=(d=(c=U(a=o.data)?a:[a])[0])==null||(u=d.properties)==null?void 0:u.token)!==null&&l!==void 0?l:d?.token,batch:c,sent_at:new Date().toISOString()}:o.timestampMode==="body"&&(o.data=(function(m,v){return v===void 0&&(v=new Date().toISOString()),U(m)?m.map((E=>I({},E,{sent_at:v}))):I({},m,{sent_at:v})})(o.data))),o.url=Zc(o.url,o.method,o.compression,o.timestampMode);var h=Lr.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),p=(r=(s=(function(m,v){for(var E=0;m.length>E;E++)if(m[E].transport===f)return m[E]})(h))==null?void 0:s.method)!==null&&r!==void 0?r:h[0].method;if(!p)throw new Error("No available transport method");var g=m=>{try{p(m)}catch(v){Nf(v)?A.warn(v):A.error(v),o.callback==null||o.callback({statusCode:0,error:v})}};f!=="sendBeacon"&&o.data&&o.compression===je.GZipJS&&Tp&&typeof Promise<"u"&&!Mr?fm(o).then((m=>{g(m)})).catch((m=>{if(vc(m))return Mr=!0,void g(I({},o,{compression:void 0,url:Zc(n.url,n.method,void 0,n.timestampMode)}));(v=>{if(!v||typeof v!="object")return!1;var E="name"in v?String(v.name):"";return vc(v)||E===dd})(m)&&(Mr=!0),g(o)})):p(o)})(I({},e,{callback:n=>{var i,r;this.rateLimiter.checkForLimiting(n),400>n.statusCode||(i=(r=this.config).on_request_error)==null||i.call(r,n),e.callback==null||e.callback(n)}}))):e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:0}))}Pn(e){this.Rn?this.Rn.retriableRequest(e):this._send_request(e)}_execute_array(e){Ro++;try{var n,i=[],r=[],s=[];vr(e,(a=>{if(a)if(U(n=a[0]))s.push(a);else if(De(a))try{a.call(this)}catch(l){A.error("Error executing queued PostHog call",a,l)}else U(a)&&n==="alias"?i.push(a):U(a)&&n.indexOf("capture")!==-1&&De(this[n])?s.push(a):r.push(a)}));var o=function(a,l){vr(a,(function(u){try{if(U(u[0])){var c=l;ie(u,(function(d){c=c[d[0]].apply(c,d.slice(1))}))}else l[u[0]].apply(l,u.slice(1))}catch(d){A.error("Error executing queued PostHog call",u,d)}}))};o(i,this),o(r,this),o(s,this)}finally{Ro--}}push(e){if(Ro>0&&U(e)&&X(e[0])){var n=Je.prototype[e[0]];De(n)&&n.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,n,i){var r,s,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.In){if(this.is_capturing())if(!C(e)&&X(e)){var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var c=i!=null&&i.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(c==null||!c.isRateLimited){n!=null&&n.$current_url&&!X(n?.$current_url)&&(A.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),n==null||delete n.$current_url),e!=="$exception"||i!=null&&i.Wn||A.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,f=i?.timestamp||d,h=Ec(i?.uuid,Ht),p={uuid:h,event:e,properties:this.calculateEventProperties(e,n||{},f,h)};e===Vn&&this.config.__preview_capture_bot_pageviews&&u&&(p.event="$bot_pageview",p.properties.$browser_type="bot"),c&&(p.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&p.properties.$feature_flag_has_experiment===!1&&this.get_property(Zr)===!0;i?.$set&&!g&&(p.$set=i?.$set);var m=i?.$unset;m&&(p.$unset=m);var v,E,S,_=g?void 0:this.Vn(i?.$set_once,e!==Ac,e===yo);if(_&&(p.$set_once=_),i!=null&&i._noTruncate||(s=this.config.properties_string_max_length,o=p,a=L=>X(L)?L.slice(0,s):L,l=new Set,p=(function L(N,K){if(N!==Object(N))return a?a(N):N;if(!l.has(N)){var V;if(l.add(N),U(N))V=[],vr(N,(R=>{V.push(L(R))}));else{var M={};ie(N,((R,Z)=>{l.has(R)||(M[Z]=L(R))})),V=M}return V}})(o)),p.timestamp=f,C(i?.timestamp)||(p.properties.$event_time_override_provided=!0,p.properties.$event_time_override_system_time=d),g&&(p.properties=(function(L,N){N===void 0&&(N=[]);var K={},V=M=>{L[M]!==void 0&&(K[M]=L[M])};return $p.forEach(V),N.forEach(V),K})(p.properties,Pm)),e===zt.DISMISSED||e===zt.SENT){var b=n?.[ko.SURVEY_ID],k=n?.[ko.SURVEY_ITERATION];qf({id:b,current_iteration:k}),p.$set=I({},p.$set,{[(v={id:b,current_iteration:k},E=e===zt.SENT?"responded":"dismissed",S="$survey_"+E+"/"+v.id,v.current_iteration&&v.current_iteration>0&&(S="$survey_"+E+"/"+v.id+"/"+v.current_iteration),S)]:!0})}else e===zt.SHOWN&&(p.$set=I({},p.$set,{[ko.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===rm.SHOWN){var T=n?.[zc.TOUR_TYPE];T&&(p.$set=I({},p.$set,{[zc.TOUR_LAST_SEEN_DATE+"/"+T]:new Date().toISOString()}))}var x=I({},p.properties.$set,p.$set);if(Kt(x)||this.setPersonPropertiesForFlags(x),!H(this.config.before_send)){var F=this.Pt(p);if(!F)return;(p=F).uuid=Ec(p.uuid,Ht)}this.dn.emit("eventCaptured",p);var $=(r=i?._url)!==null&&r!==void 0?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),O={method:"POST",url:$,data:p,compression:"best-available",timestampMode:i?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test($)?"body":"capture-body",batchKey:i?._batchKey,transport:i?.transport};return!this.config.request_batching||i&&(i==null||!i._batchKey)||i!=null&&i.send_instantly?this.Pn(O):this.In.enqueue(O),p}A.critical("This capture call is ignored due to client rate limiting.")}}else A.error("No event name provided to posthog.capture")}else A.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(n=>e(n.event,n)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new Am(this)}cn(e){this._n.push(e);var n=!0;return()=>{if(n){n=!1;var i=this._n.indexOf(e);i!==-1&&this._n.splice(i,1)}}}calculateEventProperties(e,n,i,r,s){if(i=i||new Date,!this.persistence||!this.sessionPersistence)return n;var o=s?void 0:this.persistence.remove_event_timer(e),a=I({},n);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.gn()&&(a[Zd]=!0),e==="$snapshot"){var l=I({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!X(a.distinct_id)&&!ke(a.distinct_id)||Ko(a.distinct_id))&&A.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=(function(b,k,T,x){var F,$,O,L;if(x===void 0&&(x=!1),!Ve)return{};var N,K=b?[...ri,...k||[]]:[],V=(function(Bn){for(var qe=0;wc.length>qe;qe++){var Dn=wc[qe],Mt=Dn[1],Lt=Dn[0].exec(Bn),ut=Lt&&(De(Mt)?Mt(Lt,Bn):Mt);if(ut)return ut}return["",""]})(Ve),M=V[0],R=V[1],Z=(N=typeof navigator<"u"?navigator:void 0)!=null&&N.brave?{brave:!0}:{},Ce={};C(T)||(Ce.detectGoogleSearchApp=T);var oe={},ye=(F=navigator)==null||(F=F.userAgentData)==null?void 0:F.platform,$e=($=navigator)==null?void 0:$.maxTouchPoints,ae=w==null||(O=w.screen)==null?void 0:O.width,Ie=w==null||(L=w.screen)==null?void 0:L.height,Se=w?.devicePixelRatio;C(ye)||(oe.userAgentDataPlatform=ye),C($e)||(oe.maxTouchPoints=$e),C(ae)||(oe.screenWidth=ae),C(Ie)||(oe.screenHeight=Ie),C(Se)||(oe.devicePixelRatio=Se);var Be,wt,ge,Ye,bt,mn,Re,Pe,$t=fe(ll({$os:M,$os_version:R,$browser:Nd(Ve,navigator.vendor,Z,Ce),$device:bc(Ve),$device_type:(wt=Ve,ge=oe,Pe=bc(wt),Pe===_d||Pe===vd||Pe==="Kobo"||Pe==="Kindle Fire"||Pe===Rd?ei:Pe===Gi||Pe===Xn||Pe===Ki||Pe===Jo?"Console":Pe===wd?"Wearable":Pe?it:ge?.userAgentDataPlatform==="Android"&&((Ye=ge?.maxTouchPoints)!==null&&Ye!==void 0?Ye:0)>0?600>Math.min((bt=ge?.screenWidth)!==null&&bt!==void 0?bt:0,(mn=ge?.screenHeight)!==null&&mn!==void 0?mn:0)/((Re=ge?.devicePixelRatio)!==null&&Re!==void 0?Re:1)?it:ei:"Desktop"),$timezone:If(),$timezone_offset:tm()}),{$current_url:Zi(x?fn(me?.href):me?.href,K,Xi),$host:me?.host,$pathname:me?.pathname,$raw_user_agent:Ve.length>1e3?Ve.substring(0,997)+"...":Ve,$browser_version:Xp(Ve,navigator.vendor,Z,Ce),$browser_language:qc(),$browser_language_prefix:(Be=qc(),typeof Be=="string"?Be.split("-")[0]:void 0),$screen_height:w?.screen.height,$screen_width:w?.screen.width,$viewport_height:w?.innerHeight,$viewport_width:w?.innerWidth,$lib:ne.LIB_NAME,$lib_version:ne.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return ne.SDK_DIST_CHANNEL&&($t.$sdk_dist_channel=ne.SDK_DIST_CHANNEL),$t})(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties,this.config.detect_google_search_app,this.config.disable_capture_url_hashes);if(this.sessionManager){var d=this.sessionManager.checkAndGetSessionAndWindowId(s,i.getTime()),f=d.windowId;a.$session_id=d.sessionId,a.$window_id=f}this.sessionPropsManager&&fe(a,this.sessionPropsManager.getSessionProps());try{var h;this.sessionRecording&&fe(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(h=this.Rn)==null?void 0:h.length}catch(b){a.$sdk_debug_error_capturing_properties=String(b)}if(this.requestRouter.region===xa&&(a.$lib_custom_api_host=this.config.api_host),u=e!==Vn||s?e!==_o||s?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(i):this.pageViewManager.doPageView(i,r),a=fe(a,u),e===Vn&&P&&(a.title=P.title),!C(o)){var p=i.getTime()-o;a.$duration=parseFloat((p/1e3).toFixed(3))}Ve&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();ie(["$referrer","$referring_domain"],(b=>{b in g&&delete m[b]}));var v={};if(this._n.length>0)for(var E of this._n.slice())try{fe(v,E())}catch(b){A.error("Failed to produce browser extension event properties",b)}(a=fe({},c,g,m,I({},v,a))).$is_identified=this._isIdentified(),U(this.config.property_denylist)?ie(this.config.property_denylist,(function(b){delete a[b]})):A.error(zf+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var S=this.config.sanitize_properties;S&&(A.error(iu),a=S(a,e));var _=this.Zn();return a.$process_person_profile=_,_&&!s&&this.Gn("_calculate_event_properties"),a}Vn(e,n,i){var r;if(n===void 0&&(n=!0),i===void 0&&(i=!1),!this.persistence||!this.Zn()||this.mn&&!i)return e;var s=this.persistence.get_initial_props(),o=(r=this.sessionPropsManager)==null?void 0:r.getSetOnceProps(),a=fe({},s,o||{},e||{}),l=this.config.sanitize_properties;return l&&(A.error(iu),a=l(a,"$set_once")),n&&(this.mn=!0),Kt(a)?void 0:a}register(e,n){var i;(i=this.persistence)==null||i.register(e,n)}register_once(e,n,i){var r;(r=this.persistence)==null||r.register_once(e,n,i)}register_for_session(e){var n;(n=this.sessionPersistence)==null||n.register(e),Object.keys(e).forEach((i=>this.yn.add(i))),this.Qn()}unregister(e){var n;(n=this.persistence)==null||n.unregister(e)}unregister_for_session(e){var n;(n=this.sessionPersistence)==null||n.unregister(e),this.yn.delete(e),this.Qn()}Kn(e,n){this.register({[e]:n})}An(){this.yn.forEach((e=>{var n;(n=this.sessionPersistence)==null||n.unregister(e)})),this.yn.clear(),this.Qn()}Qn(){var e;if(this.bn)if(this.config.persistence==="memory"||(e=this.sessionPersistence)!=null&&e.xi||!be.N())be.q(this.bn);else{var n=[];this.yn.forEach((i=>n.push(i))),n.length>0?be.F(this.bn,n):be.q(this.bn)}}getFeatureFlag(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlag(e,n)}getFeatureFlagPayload(e){var n;return(n=this.featureFlags)==null?void 0:n.getFeatureFlagPayload(e)}getFeatureFlagResult(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlagResult(e,n)}getAllFeatureFlags(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.getAllFeatureFlags())!==null&&e!==void 0?e:[]}isFeatureEnabled(e,n){var i,r;return(i=(r=this.featureFlags)==null?void 0:r.isFeatureEnabled(e,n))!==null&&i!==void 0?i:n?.defaultValue}reloadFeatureFlags(){var e;(e=this.featureFlags)==null||e.reloadFeatureFlags()}updateFlags(e,n,i){var r;(r=this.featureFlags)==null||r.updateFlags(e,n,i)}updateEarlyAccessFeatureEnrollment(e,n,i){var r;(r=this.featureFlags)==null||r.updateEarlyAccessFeatureEnrollment(e,n,i)}getEarlyAccessFeatures(e,n,i){var r;return n===void 0&&(n=!1),(r=this.featureFlags)==null?void 0:r.getEarlyAccessFeatures(e,n,i)}on(e,n){return this.dn.on(e,n)}onFeatureFlags(e){return this.featureFlags?this.featureFlags.onFeatureFlags(e):(e([],{},{errorsLoading:!0}),()=>{})}onSurveysLoaded(e){return this.surveys?this.surveys.onSurveysLoaded(e):(e([],{isLoaded:!1,error:xi}),()=>{})}onSessionId(e){var n,i;return(n=(i=this.sessionManager)==null?void 0:i.onSessionId(e))!==null&&n!==void 0?n:()=>{}}getSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getSurveys(e,n):e([],{isLoaded:!1,error:xi})}getActiveMatchingSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,n):e([],{isLoaded:!1,error:xi})}renderSurvey(e,n){var i;(i=this.surveys)==null||i.renderSurvey(e,n)}displaySurvey(e,n){var i;n===void 0&&(n=Em),(i=this.surveys)==null||i.displaySurvey(e,n)}cancelPendingSurvey(e){var n;(n=this.surveys)==null||n.cancelPendingSurvey(e)}canRenderSurvey(e){var n,i;return(n=(i=this.surveys)==null?void 0:i.canRenderSurvey(e))!==null&&n!==void 0?n:{visible:!1,disabledReason:xi}}canRenderSurveyAsync(e,n){var i,r;return n===void 0&&(n=!1),(i=(r=this.surveys)==null?void 0:r.canRenderSurveyAsync(e,n))!==null&&i!==void 0?i:Promise.resolve({visible:!1,disabledReason:xi})}Jn(e){return!e||Ko(e)?(A.critical("Unique user id has not been set in posthog.identify"),!1):e===mr?(A.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.'),!1):!["distinct_id","distinctid"].includes(e.toLowerCase())&&!["undefined","null"].includes(e.toLowerCase())||(A.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.'),!1)}identify(e,n,i){if(!this.__loaded||!this.persistence)return A.uninitializedWarning("posthog.identify");if(ke(e)&&(e=e.toString(),A.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.Jn(e)&&this.Gn("posthog.identify")){var r=this.get_distinct_id();this.register({$user_id:e}),this.get_property(Yi)||this.register_once({$had_persisted_distinct_id:!0,$device_id:r},""),e!==r&&e!==this.get_property(Fi)&&(this.unregister(Fi),this.register({distinct_id:e}));var s,o=(this.persistence.get_property(ot)||Un)===Un,a=e!==r,l=!a&&o;if(a&&o)this.persistence.set_property(ot,vn),this.setPersonPropertiesForFlags({$set:n||{},$set_once:i||{}},!1),this.capture(yo,{distinct_id:e,$anon_distinct_id:r},{$set:n||{},$set_once:i||{}}),this.Sn=Fo(e,n,i),(s=this.featureFlags)==null||s.setAnonymousDistinctId(r);else if(l){this.persistence.set_property(ot,vn);var u=n||{},c=i||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=Fo(e,n,i)}else(n||i)&&this.setPersonProperties(n,i);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Cn)):l&&(n||i)&&this.reloadFeatureFlags()}}setPersonProperties(e,n){if((e||n)&&this.Gn("posthog.setPersonProperties")){var i=Fo(this.get_distinct_id(),e,n);this.Sn!==i?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:n||{}},!0),this.capture("$set",{$set:e||{},$set_once:n||{}}),this.Sn=i):A.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}unsetPersonProperties(e){var n,i=(U(e)?e:[e]).filter((r=>X(r)&&r.length>0));i.length!==0&&this.Gn("posthog.unsetPersonProperties")&&((n=this.featureFlags)==null||n.unsetPersonPropertiesForFlags(i,!0),this.capture("$set",{$unset:i}),this.Sn=null)}group(e,n,i){if(e&&n){var r=this.getGroups(),s=r[e]!==n;if(s&&this.resetGroupPropertiesForFlags(e),this.register({$groups:I({},r,{[e]:n})}),s||i){var o={$group_type:e,$group_key:n};i&&(o.$group_set=i),this.capture(Ac,o)}i&&this.setGroupPropertiesForFlags({[e]:i}),s&&!i&&this.reloadFeatureFlags()}else A.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),(i=this.featureFlags)==null||i.setPersonPropertiesForFlags(e,n)}resetPersonPropertiesForFlags(e){var n;e===void 0&&(e=!0),(n=this.featureFlags)==null||n.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((i=this.featureFlags)==null||i.setGroupPropertiesForFlags(e,n))}resetGroupPropertiesForFlags(e){var n;(n=this.featureFlags)==null||n.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,n){var i,r,s,o,a,l,u,c,d,f;if(n===void 0&&(n=!1),A.info("reset"),!this.__loaded)return A.uninitializedWarning("posthog.reset");var h,p=this.get_property(Yi),g=this.get_property(vo),m=this.get_property(An),v=this.is_capturing();if(this.consent.reset(),n||!v||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after."),(i=this.persistence)==null||i.clear(),(r=this.sessionPersistence)==null||r.clear(),this.yn.clear(),this.Qn(),C(m)||(h=this.persistence)==null||h.register({[An]:m}),(s=this.surveys)==null||s.reset(),(o=this.Un)==null||o.stop(),(a=this.featureFlags)==null||a.reset(),(l=this.conversations)==null||l.reset(),(u=this.logs)==null||u.reset(),(c=this.metrics)==null||c.reset(),(d=this.persistence)==null||d.set_property(ot,Un),(f=this.sessionManager)==null||f.resetSessionId(),this.Sn=null,this.config.cookieless_mode===Wt)this.register_once({distinct_id:mr,$device_id:null},"");else{var E=this.config.get_device_id(Ht());this.register_once({distinct_id:E,$device_id:e?E:p},""),e||C(g)||this.register({[vo]:g})}this.register({$last_posthog_reset:new Date().toISOString()},1),delete this.config.identity_distinct_id,delete this.config.identity_hash,this.reloadFeatureFlags()}shutdown(e){var n=this;return se((function*(){var i,r,s,o,a,l,u;if(n.__loaded){(i=n.Un)==null||i.stop(),(r=n.jn)==null||r.dispose(),(s=n.sessionRecording)==null||s.dispose(),(o=n.logs)==null||o.flushLogs("sendBeacon"),(a=n.metrics)==null||a.flush("sendBeacon"),(l=n.In)==null||l.unload(),(u=n.Rn)==null||u.unload();try{var c;(c=n.featureFlags)==null||c.destroy()}catch(d){A.error("Error while destroying feature flags",d)}}else A.uninitializedWarning("posthog.shutdown")}))()}setIdentity(e,n){var i;this.config.identity_distinct_id=e,this.config.identity_hash=n,this.alias(e),(i=this.conversations)==null||i.Xn()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,(e=this.conversations)==null||e.ts()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,n;return(e=(n=this.sessionManager)==null?void 0:n.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var n=this.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.sessionStartTimestamp,r=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+n.sessionId);if(e!=null&&e.withTimestamp&&i){var s,o=(s=e.timestampLookBack)!==null&&s!==void 0?s:10;if(!i)return r;r+="?t="+Math.max(Math.floor((new Date().getTime()-i)/1e3)-o,0)}return r}alias(e,n){return e===this.get_property(zd)?(A.critical("Attempting to create alias for existing People user - aborting."),-2):this.Gn("posthog.alias")?(C(n)&&(n=this.get_distinct_id()),e!==n?(this.Kn(Fi,e),this.capture("$create_alias",{alias:e,distinct_id:n})):(A.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var n=I({},this.config);if(he(e)){var i,r,s,o,a,l,u,c,d,f,h,p;fe(this.config,ru(e));var g=this.En();(i=this.persistence)==null||i.update_config(this.config,n,g),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new xo(I({},this.config,{persistence:"sessionStorage"}),g,!1);var m=this.Cn(this.config.debug);mt(m)&&(this.config.debug=m),mt(this.config.debug)&&(this.config.debug?(ne.DEBUG=!0,le.N()&&le.F("ph_debug",!0),A.info("set_config",{config:e,oldConfig:n,newConfig:I({},this.config)})):(ne.DEBUG=!1,le.N()&&le.q("ph_debug"))),(r=this.featureFlags)==null||r.updateConfig==null||r.updateConfig(this.config,this.Qi()),(s=this.exceptionObserver)==null||s.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(f=this.deadClicksAutocapture)==null||f.startIfEnabledOrStop(),(h=this.surveys)==null||h.loadIfEnabled(),this.es(),(p=this.externalIntegrations)==null||p.startIfEnabledOrStop()}}_overrideSDKInfo(e,n){ne.LIB_NAME=e,ne.LIB_VERSION=n}startSessionRecording(e){var n,i,r,s,o,a=e===!0,l={sampling:a||!(e==null||!e.sampling),linked_flag:a||!(e==null||!e.linked_flag),url_trigger:a||!(e==null||!e.url_trigger),event_trigger:a||!(e==null||!e.event_trigger)};Object.values(l).some(Boolean)&&((n=this.sessionManager)==null||n.checkAndGetSessionAndWindowId(),l.sampling&&((i=this.sessionRecording)==null||i.overrideSampling()),l.linked_flag&&((r=this.sessionRecording)==null||r.overrideLinkedFlag()),l.url_trigger&&((s=this.sessionRecording)==null||s.overrideTrigger("url")),l.event_trigger&&((o=this.sessionRecording)==null||o.overrideTrigger("event"))),this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,n){if(this.exceptions){var i=new Error("PostHog syntheticException"),r=this.exceptions.buildProperties(e,{handled:!0,syntheticException:i});return this.exceptions.sendExceptionEvent(I({},r,n))}}addExceptionStep(e,n){var i;(i=this.exceptions)==null||i.addExceptionStep(e,n)}captureLog(e){var n;(n=this.logs)==null||n.captureLog(e)}get logger(){var e,n;return(e=(n=this.logs)==null?void 0:n.logger)!==null&&e!==void 0?e:Je.rs}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var n,i;return(n=(i=this.toolbar)==null?void 0:i.loadToolbar(e))!==null&&n!==void 0&&n}get_property(e){var n;return(n=this.persistence)==null?void 0:n.props[e]}getSessionProperty(e){var n;return(n=this.sessionPersistence)==null?void 0:n.props[e]}toString(){var e,n=(e=this.config.name)!==null&&e!==void 0?e:Gn;return n!==Gn&&(n=Gn+"."+n),n}_isIdentified(){var e,n;return((e=this.persistence)==null?void 0:e.get_property(ot))===vn||((n=this.sessionPersistence)==null?void 0:n.get_property(ot))===vn}Zn(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles===pa&&!this._isIdentified()&&Kt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[Fi])&&((n=this.persistence)==null||(n=n.props)==null||!n[es]))}zn(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Zn()||this.Gn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.Gn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}Gn(e){return this.config.person_profiles==="never"?(A.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Kn(es,!0),!0)}En(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut();return this.config.disable_persistence||e&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!==kn)}es(){var e,n,i,r,s=this.En();return((e=this.persistence)==null?void 0:e.xi)!==s&&((i=this.persistence)==null||i.set_disabled(s)),((n=this.sessionPersistence)==null?void 0:n.xi)!==s&&((r=this.sessionPersistence)==null||r.set_disabled(s)),s&&(this.yn.clear(),this.Qn()),s}opt_in_capturing(e){var n;if(this.config.cookieless_mode!==Wt){if(this.gn()){var i,r,s,o,a;this.Yn(!0,!0),(i=this.sessionManager)==null||i.destroy(),(r=this.pageViewManager)==null||r.destroy(),this.sessionManager=new Qc(this),this.pageViewManager=new Wc(this),this.persistence&&(this.sessionPropsManager=new Xc(this,this.sessionManager,this.persistence));var l,u=(s=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&s!==void 0?s:(a=Je.__defaultExtensionClasses)==null?void 0:a.sessionRecording;u&&(this.sessionRecording=this.pn(this.sessionRecording,new u(this)),this.hn&&((l=this.sessionRecording)==null||l.onRemoteConfig==null||l.onRemoteConfig(this.hn)))}var c,d;this.consent.optInOut(!0),this.es(),this.Bn(),(n=this.sessionRecording)==null||n.startIfEnabledOrStop(),this.config.cookieless_mode==kn&&((c=this.surveys)==null||c.loadIfEnabled()),(C(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((d=e?.captureEventName)!==null&&d!==void 0?d:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hn()}else A.warn(nu)}opt_out_capturing(){var e,n,i;this.config.cookieless_mode!==Wt?(this.config.cookieless_mode===kn&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===kn&&(this.register({distinct_id:mr,$device_id:null}),(e=this.sessionRecording)==null||e.stopRecording(),this.sessionRecording=void 0,(n=this.sessionManager)==null||n.destroy(),(i=this.pageViewManager)==null||i.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.Hn(),this.Bn())):A.warn(nu)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===Wt||(this.config.cookieless_mode===kn?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return Ue?Bf(Ue,this.config.custom_blocked_useragents):void 0}Hn(){P&&(P.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(Vn,{title:P.title},{send_instantly:!0}),this.kn&&(P.removeEventListener(ts,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),ve(P,ts,this.kn)))}debug(e){e===!1?(w?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(w?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}Qi(){var e=this.Mn||{};return"advanced_disable_flags"in e?!!e.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(A.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(function(n,i,r,s,o){var a=i in n&&!H(n[i]),l=r in n&&!H(n[r]);return a?n[i]:!!l&&(o&&o.warn("Config field '"+r+"' is deprecated. Please use '"+i+"' instead. The old field will be removed in a future major version."),n[r])})(e,"advanced_disable_flags","advanced_disable_decide",0,A)}Pt(e){var n;if(H(this.config.before_send))return e;var i=Object.keys((n=e.properties)!==null&&n!==void 0?n:{}).filter(jp),r=U(this.config.before_send)?this.config.before_send:[this.config.before_send],s=e;for(var o of r){if(s=o(s),H(s)){var a="Event '"+e.event+"' was rejected in beforeSend function";return Dp(e.event)?A.warn(a+". This can cause unexpected behavior."):A.info(a),null}s.properties&&!Kt(s.properties)||A.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}for(var l of i)if(s.properties&&H(s.properties[l]))return A.warn("Event '"+e.event+"' had its '"+l+"' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped."),null;return s}getPageViewId(){var e;return(e=this.pageViewManager.ui)==null?void 0:e.pageViewId}captureTraceFeedback(e,n){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:n})}captureTraceMetric(e,n,i){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:n,$ai_metric_value:String(i)})}Cn(e){var n=mt(e)&&!e,i=le.N()&&le.P("ph_debug")==="true";return!n&&(!!i||e)}}Je.__defaultExtensionClasses={},Je.rs=(()=>{var t=()=>{};return{trace:t,debug:t,info:t,warn:t,error:t,fatal:t}})(),(function(t,e){for(var n=0;e.length>n;n++)t.prototype[e[n]]=Ag(t.prototype[e[n]])})(Je,["identify"]);class su{constructor(e){this.disabled=e===!1;var n=he(e)?e:{};this.thresholdPx=n.threshold_px||30,this.timeoutMs=n.timeout_ms||1e3,this.clickCount=n.click_count||3,this.clicks=[]}isRageClick(e,n,i){if(this.disabled)return!1;var r=this.clicks[this.clicks.length-1];if(r&&Math.abs(e-r.x)+Math.abs(n-r.y)i-r.timestamp){if(this.clicks.push({x:e,y:n,timestamp:i}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:n,timestamp:i}];return!1}}var $o="$copy_autocapture",Mo=pe("[AutoCapture]");function Lo(t,e){return e.length>t?e.slice(0,t)+"...":e}function Tm(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!hn(e));return e}function $m(t,e){var n,i,r=e.e,s=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!hn(t))return{props:{}};for(var c=[t],d=new Set([t]),f=t;f.parentNode&&!Qe(f,"body")&&lf>c.length;)if(af(f.parentNode)){var h=f.parentNode.host;if(d.has(h))break;d.add(h),c.push(h),f=h}else{if(!hn(f.parentNode)||d.has(f.parentNode))break;d.add(f.parentNode),c.push(f.parentNode),f=f.parentNode}var p,g,m=[],v={},E=!1,S=!1;if(ie(c,(x=>{var F=va(x);if(Qe(x,"a")){var $=x.getAttribute("href");E=!!(F&&$&&Ui($))&&(u?fn($):$)}j(rs(x),"ph-no-capture")&&(S=!0),m.push((function(L,N,K,V,M){M===void 0&&(M=!1);var R=L.tagName.toLowerCase(),Z={tag_name:R};ul.indexOf(R)>-1&&!K&&(Z.$el_text=R.toLowerCase()==="a"||R.toLowerCase()==="button"?Lo(1024,jc(L)):Lo(1024,Ji(L)));var Ce=rs(L);Ce.length>0&&(Z.classes=Ce.filter((function(ae){return ae!==""}))),ie(L.attributes,(function(ae){var Ie;if((!hf(L)||["name","id","class","aria-label"].indexOf(ae.name)!==-1)&&(V==null||!V.includes(ae.name))&&!N&&Ui(ae.value)&&(!X(Ie=ae.name)||Ie.substring(0,10)!=="_ngcontent"&&Ie.substring(0,7)!=="_nghost")){var Se=ae.value;ae.name==="class"&&(Se=cl(Se).join(" ")),Z["attr__"+ae.name]=Lo(1024,ae.name==="href"&&M?fn(Se):Se)}}));for(var oe=1,ye=1,$e=L;$e=Tm($e);)oe++,$e.tagName===L.tagName&&ye++;return Z.nth_child=oe,Z.nth_of_type=ye,Z})(x,s,o,a,u));var O=(function(L){if(!va(L))return{};var N={};return ie(L.attributes,(function(K){if(K.name&&K.name.indexOf("data-ph-capture-attribute")===0){var V=K.name.replace("data-ph-capture-attribute-",""),M=K.value;V&&M&&Ui(M)&&(N[V]=M)}})),N})(x);fe(v,O)})),S)return{props:{},explicitNoCapture:S};if(o||(m[0].$el_text=Qe(t,"a")||Qe(t,"button")?jc(t):Ji(t)),E){var _,b;m[0].attr__href=E;var k=(_=ss(E))==null?void 0:_.host,T=w==null||(b=w.location)==null?void 0:b.host;k&&T&&k!==T&&(p=E)}return{props:fe({$event_type:r.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(x){return x.map((F=>{var $,O,L="";if(F.tag_name&&(L+=F.tag_name),F.attr_class)for(var N of(F.attr_class.sort(),F.attr_class))L+="."+N.replace(/"/g,"");var K=I({},F.text?{text:F.text}:{},{"nth-child":($=F.nth_child)!==null&&$!==void 0?$:0,"nth-of-type":(O=F.nth_of_type)!==null&&O!==void 0?O:0},F.href?{href:F.href}:{},F.attr_id?{attr_id:F.attr_id}:{},F.attributes),V={};return $r(K).sort(((M,R)=>M[0].localeCompare(R[0]))).forEach((M=>{var R=M[1];return V[Uc(M[0].toString())]=Uc(R.toString())})),(L+=":")+$r(V).map((M=>M[0]+'="'+M[1]+'"')).join("")})).join(";")})((function(x){return x.map((F=>{var $,O,L={text:($=F.$el_text)==null?void 0:$.slice(0,400),tag_name:F.tag_name,href:(O=F.attr__href)==null?void 0:O.slice(0,2048),attr_class:Gg(F),attr_id:F.attr__id,nth_child:F.nth_child,nth_of_type:F.nth_of_type,attributes:{}};return $r(F).filter((N=>N[0].indexOf("attr__")===0)).forEach((N=>L.attributes[N[0]]=N[1])),L}))})(g)))},(n=m[0])!=null&&n.$el_text?{$el_text:(i=m[0])==null?void 0:i.$el_text}:{},p&&r.type==="click"?{$external_click_url:p}:{},v)}}var Ii=pe("[ExceptionAutocapture]"),ou=()=>{},Mm=pe("[TracingHeaders]"),wn=pe("[Web Vitals]"),au=9e5,lu="disabled",cu="lazy_loading",ki="awaiting_config",Sr="missing_config";pe("[SessionRecording]"),pe("[SessionRecording]");var Ia="[SessionRecording]",Bt=pe(Ia),Lm=pe("[Heatmaps]");function No(t){return he(t)&&"clientX"in t&&"clientY"in t&&ke(t.clientX)&&ke(t.clientY)}var xr=pe("[Product Tours]"),Oo=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(sl))},Nm=["$set_once","$set"],Et=pe("[SiteApps]"),uu="Error while initializing PostHog app with config id ";function qn(t,e,n){if(H(t))return!1;switch(n){case"exact":return t===e;case"contains":var i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(i,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}class Om{constructor(e){this.ns=new pl,this.ss=(n,i)=>this.os(n,i)&&this.ls(n,i)&&this.us(n,i)&&this.hs(n,i),this.os=(n,i)=>i==null||!i.event||n?.event===i?.event,this._instance=e,this.ds=new Set,this.vs=new Set}init(){var e,n;C((e=this._instance)==null?void 0:e._addCaptureHook)||(n=this._instance)==null||n._addCaptureHook(((i,r)=>{this.on(i,r)}))}register(e){var n,i;if(!C((n=this._instance)==null?void 0:n._addCaptureHook)&&(e.forEach((o=>{var a,l;(a=this.vs)==null||a.add(o),(l=o.steps)==null||l.forEach((u=>{var c;(c=this.ds)==null||c.add(u?.event||"")}))})),(i=this._instance)!=null&&i.autocapture)){var r,s=new Set;e.forEach((o=>{var a;(a=o.steps)==null||a.forEach((l=>{l!=null&&l.selector&&s.add(l?.selector)}))})),(r=this._instance)==null||r.autocapture.setElementSelectors(s)}}on(e,n){var i;n!=null&&e.length!=0&&(this.ds.has(e)||this.ds.has(n.event))&&this.vs&&((i=this.vs)==null?void 0:i.size)>0&&this.vs.forEach((r=>{this.cs(n,r)&&this.ns.emit("actionCaptured",r.name)}))}fs(e){this.onAction("actionCaptured",(n=>e(n)))}cs(e,n){if(n?.steps==null)return!1;for(var i of n.steps)if(this.ss(e,i))return!0;return!1}onAction(e,n){return this.ns.on(e,n)}ls(e,n){if(n!=null&&n.url){var i,r=e==null||(i=e.properties)==null?void 0:i.$current_url;if(!r||typeof r!="string"||!qn(r,n.url,n.url_matching||"contains"))return!1}return!0}us(e,n){return!!this.ps(e,n)&&!!this.gs(e,n)&&!!this.ys(e,n)}ps(e,n){var i;if(n==null||!n.href)return!0;var r=this.bs(e);if(r.length>0)return r.some((a=>qn(a.href,n.href,n.href_matching||"exact")));var s,o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!o&&qn((s=o.match(/(?::|")href="(.*?)"/))?s[1]:"",n.href,n.href_matching||"exact")}gs(e,n){var i;if(n==null||!n.text)return!0;var r=this.bs(e);if(r.length>0)return r.some((u=>qn(u.text,n.text,n.text_matching||"exact")||qn(u.$el_text,n.text,n.text_matching||"exact")));var s,o,a,l=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!l&&(s=(function(u){for(var c,d=[],f=/(?::|")text="(.*?)"/g;!H(c=f.exec(u));)d.includes(c[1])||d.push(c[1]);return d})(l),o=n.text,a=n.text_matching||"exact",s.some((u=>qn(u,o,a))))}ys(e,n){var i,r;if(n==null||!n.selector)return!0;var s=e==null||(i=e.properties)==null?void 0:i.$element_selectors;if(s!=null&&s.includes(n.selector))return!0;var o=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";if(n.selector_regex&&o)try{return new RegExp(n.selector_regex).test(o)}catch{return!1}return!1}bs(e){var n;return(e==null||(n=e.properties)==null?void 0:n.$elements)==null?[]:e?.properties.$elements}hs(e,n){return n==null||!n.properties||n.properties.length===0||Uf(n.properties.reduce(((i,r)=>{var s=U(r.value)?r.value.map(String):r.value!=null?[String(r.value)]:[];return i[r.key]={values:s,operator:r.operator||"exact"},i}),{}),e?.properties)}}class Bm{constructor(e){var n;this._s=[],this._instance=e,this.ws=new Map,this.ks=new Map,this.xs=new Map,(n=this._instance)==null||n.onSessionId==null||n.onSessionId((i=>this.Ss(i)))}Cs(e){return!1}Ms(){return null}Ts(e){}Es(){}Is(e,n){return!!e&&Uf(e.propertyFilters,n?.properties)}Ps(e,n){var i=new Map;return e.forEach((r=>{var s;(s=r.conditions)==null||(s=s[n])==null||(s=s.values)==null||s.forEach((o=>{if(o!=null&&o.name){var a=i.get(o.name)||[];a.push(r.id),i.set(o.name,a)}}))})),i}Rs(e,n,i){var r=(i===wi.Activation?this.ws:this.ks).get(e),s=[];return this.As((o=>{s=o.filter((a=>r?.includes(a.id)))})),s.filter((o=>{var a,l=(a=o.conditions)==null||(a=a[i])==null||(a=a.values)==null?void 0:a.find((u=>u.name===e));return this.Is(l,n)}))}register(e){var n;C((n=this._instance)==null?void 0:n._addCaptureHook)||(this.Fs(e),this.Ls(e))}Ls(e){var n=e.filter((i=>{var r,s;return((r=i.conditions)==null?void 0:r.actions)&&((s=i.conditions)==null||(s=s.actions)==null||(s=s.values)==null?void 0:s.length)>0}));n.length!==0&&(this.Os==null&&(this.Os=new Om(this._instance),this.Os.init(),this.Os.fs((i=>{this.onAction(i)}))),n.forEach((i=>{var r,s,o,a,l;i.conditions&&(r=i.conditions)!=null&&r.actions&&(s=i.conditions)!=null&&(s=s.actions)!=null&&s.values&&((o=i.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.Os)==null||a.register(i.conditions.actions.values),(l=i.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var c=this.xs.get(u.name);c&&c.push(i.id),this.xs.set(u.name,c||[i.id])}})))})))}Fs(e){var n,i=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.events)&&((a=s.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0})),r=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.cancelEvents)&&((a=s.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0}));i.length===0&&r.length===0||((n=this._instance)==null||n._addCaptureHook(((s,o)=>{this.onEvent(s,o)})),this.ws=this.Ps(e,wi.Activation),this.ks=this.Ps(e,wi.Cancellation))}onEvent(e,n){var i,r,s=this.Ds(),o=(n==null||(i=n.properties)==null?void 0:i.$survey_id)||(n==null||(r=n.properties)==null?void 0:r.$product_tour_id);if(o&&this.getActivatedIds().includes(o)){var a=this.$s(e,o);if(a==="consume")return s.info("event consumed activated item, removing it",{event:e,itemId:o}),void this.Ns([o]);if(a==="persist")return s.info("shown item promoted to persisted activation",{event:e,itemId:o}),this.qs(o),void this.js([o])}if(this.ks.has(e)){var l=this.Rs(e,n,wi.Cancellation);l.length>0&&(s.info("cancel event matched, cancelling items",{event:e,itemsToCancel:l.map((c=>c.id))}),this.Ns(l.map((c=>c.id))),l.forEach((c=>this.Bs(c.id))))}if(this.ws.has(e)){s.info("event name matched",{event:e,eventPayload:n,items:this.ws.get(e)});var u=this.Rs(e,n,wi.Activation);this.Hs(u.map((c=>c.id)))}}onAction(e){this.xs.has(e)&&this.Hs(this.xs.get(e)||[])}Hs(e){var n;if(e.length!==0){var i=!((n=this._instance)==null||n.get_session_id==null||!n.get_session_id()),r=[];for(var s of e)i&&this.Cs(s)?this.qs(s)&&this.Us(s):r.push(s);r.length>0&&(this._s=[...new Set([...this._s,...r])]),this.Ds().info("updating activated items",{activatedItems:this.getActivatedIds()})}}qs(e){this._s=this._s.filter((i=>i!==e));var n=this.zs();return!n.includes(e)&&(this.Ws([...n,e]),this.Vs(),!0)}Ns(e){var n=new Set(e);this._s=this._s.filter((s=>!n.has(s)));var i=this.Zs(),r=i.filter((s=>!n.has(s)));r.length!==i.length&&(this.Ws(r),r.length===0&&this.Gs()),this.js(e)}Qs(){var e,n=this.Ms();if(!n)return{};var i=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n];return i&&typeof i=="object"?i:{}}Us(e){if(this.Ms()){var n=this.Qs();this.Ts(I({},n,{[e]:Date.now()}))}}js(e){if(this.Ms()){var n=this.Qs(),i={},r=!1;for(var s of Object.entries(n)){var o=s[0],a=s[1];e.includes(o)?r=!0:i[o]=a}r&&(Kt(i)?this.Es():this.Ts(i))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var n=this.Qs()[e];return ke(n)?n:void 0}}Zs(){var e,n=this.Js();return((e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n])||[]}zs(){var e,n,i=this.Zs();if(i.length===0)return[];var r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[this.Ys()],s=(n=this._instance)==null||n.get_session_id==null?void 0:n.get_session_id();return s&&r===s?i:[]}Vs(){var e,n=(e=this._instance)==null||e.get_session_id==null?void 0:e.get_session_id();n&&this.Xs(n)}Gs(){this.ta()}Ss(e){var n,i=(n=this._instance)==null||(n=n.persistence)==null?void 0:n.props[this.Ys()];if(i&&i!==e){var r=this.Zs(),s=this.Qs();r.length>0&&(this.Ws([]),r.filter((o=>ke(s[o]))).forEach((o=>this.Bs(o)))),this.Gs(),this.Ks()}}getActivatedIds(){return[...new Set([...this.zs(),...this._s])].filter((e=>!this.ea(e)))}reset(){this._s=[],this.Zs().length>0&&this.Ws([]),this.Gs(),this.Ks()}getEventToItemsMap(){return this.ws}ia(){return this.Os}}class Dm extends Bm{constructor(e){super(e)}Js(){return ca}Ys(){return Fr}Ms(){return Rr}Ts(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Rr]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Rr)}Cs(e){var n,i;this.As((s=>{i=s.find((o=>o.id===e))}));var r=(n=i)==null||(n=n.appearance)==null?void 0:n.surveyPopupDelaySeconds;return ke(r)&&r>0}ra(){return zt.SHOWN}As(e){var n;(n=this._instance)==null||n.getSurveys(e)}Bs(e){var n;(n=this._instance)==null||n.cancelPendingSurvey(e)}Ds(){return Q}Ws(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[ca]:e})}Xs(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Fr]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Fr)}ea(){return!1}$s(e,n){var i;this.As((s=>{i=s.find((o=>o.id===n))}));var r=!i||(function(s){var o;return Hf(s)&&!((o=s.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||s.schedule==="always"})(i);return r?e===zt.SHOWN?"consume":"ignore":e===zt.SHOWN?"persist":e===zt.DISMISSED||e===zt.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var Ir="SDK is not enabled or survey functionality is not yet loaded",du="Disabled. Not loading surveys.",jm=w!=null&&w.location?os(w.location.hash,"__posthog")||os(location.hash,"state"):null,fu="_postHogToolbarParams",hu=pe("[Toolbar]"),pu=pe("[FeatureFlags]");class Um{constructor(e,n){n===void 0&&(n=!1),this.na=!1,this.update(e,n)}update(e,n){this.sa=((i,r)=>{var s,o,a,l;return{bootstrap:{featureFlags:(s=i.bootstrap)==null?void 0:s.featureFlags,featureFlagPayloads:(o=i.bootstrap)==null?void 0:o.featureFlagPayloads},remoteRequestsDisabled:r,featureFlagsDisabled:!!i.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!i.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!i.advanced_feature_flags_dedup_per_session,cacheTtlMs:i.feature_flag_cache_ttl_ms,requestTimeoutMs:i.feature_flag_request_timeout_ms,compression:i.disable_compression?"none":"base64",evaluationContexts:(a=(l=i.evaluation_contexts)!==null&&l!==void 0?l:i.evaluation_environments)!==null&&a!==void 0?a:[],flagKeys:U(i.flag_keys)?i.flag_keys:void 0}})(e,n),!e.evaluation_environments||e.evaluation_contexts||this.na||(pu.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.na=!0),C(e.flag_keys)||U(e.flag_keys)||pu.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var gu=pe("[FeatureFlags]"),bn=pe("[FeatureFlags]",{debugEnabled:!0}),Bo=`" failed. Feature flags didn't load in time.`,mu="connection_error",vu=t=>{for(var e={},n=0;t.length>n;n++)e[t[n]]=!0;return e},_u=t=>{var e={};for(var n of $r(t||{})){var i=n[1];i&&(e[n[0]]=i)}return e},St=pe("[Error tracking]"),yu="Refusing to render web experiment since the viewer is a likely bot",Hm={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>cs(e,t),not_regex:(t,e)=>!cs(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class Me{get Ne(){return this._instance.config}constructor(e){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(i){i===void 0&&(i=!1),n.getWebExperiments((r=>{Me.aa("retrieved web experiments from the server"),n.oa=new Map,r.forEach((s=>{if(s.feature_flag_key){var o;n.oa&&(Me.aa("setting flag key ",s.feature_flag_key," to web experiment ",s),(o=n.oa)==null||o.set(s.feature_flag_key,s));var a=n._instance.getFeatureFlag(s.feature_flag_key);X(a)&&s.variants[a]&&n.la(s.name,a,s.variants[a].transforms)}else if(s.variants)for(var l in s.variants){var u=s.variants[l];Me.ua(u,n._instance)&&n.la(s.name,l,u.transforms)}}))}),i)},this._instance=e,this._instance.onFeatureFlags((i=>{this.onFeatureFlags(i)}))}initialize(){}onFeatureFlags(e){if(this._is_bot())Me.aa(yu);else if(!this.Ne.disable_web_experiments){if(H(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();Me.aa("applying feature flags",e),e.forEach((n=>{var i;if(this.oa&&(i=this.oa)!=null&&i.has(n)){var r,s=this._instance.getFeatureFlag(n),o=(r=this.oa)==null?void 0:r.get(n);s&&o!=null&&o.variants[s]&&this.la(o.name,s,o.variants[s].transforms)}}))}}previewWebExperiment(){var e=Me.getWindowLocation();if(e!=null&&e.search){var n=ii(e?.search,"__experiment_id"),i=ii(e?.search,"__experiment_variant");n&&i&&(Me.aa("previewing web experiments "+n+" && "+i),this.getWebExperiments((r=>{this.ha(parseInt(n),i,r)}),!1,!0))}}loadIfEnabled(){this.Ne.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,n,i){if(this.Ne.disable_web_experiments&&!i)return e([]);var r=this._instance.get_property("$web_experiments");if(r&&!n)return e(r);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this.Ne.token),method:"GET",timestampMode:"query",callback:s=>e(s.statusCode===200&&s.json&&s.json.experiments||[])})}ha(e,n,i){var r=i.filter((s=>s.id===e));r&&r.length>0&&(Me.aa("Previewing web experiment ["+r[0].name+"] with variant ["+n+"]"),this.la(r[0].name,n,r[0].variants[n].transforms))}static ua(e,n){return!H(e.conditions)&&Me.da(e,n)&&Me.va(e)}static da(e,n){var i;if(H(e.conditions)||H((i=e.conditions)==null?void 0:i.url))return!0;var r=Me.getWindowLocation();if(r){var s,o,a,l=rf(n,r.href);return(s=e.conditions)==null||!s.url||Hm[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return w?.location}static va(e){var n;if(H(e.conditions)||H((n=e.conditions)==null?void 0:n.utm))return!0;var i=yf();if(i.utm_source){var r,s,o,a,l,u,c,d,f=(r=e.conditions)==null||(r=r.utm)==null||!r.utm_campaign||((s=e.conditions)==null||(s=s.utm)==null?void 0:s.utm_campaign)==i.utm_campaign,h=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==i.utm_source,p=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==i.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==i.utm_term;return f&&p&&g&&h}return!1}static aa(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;n>r;r++)i[r-1]=arguments[r];A.info("[WebExperiments] "+e,i)}la(e,n,i){this._is_bot()?Me.aa(yu):n!=="control"?i.forEach((r=>{if(r.selector){var s;Me.aa("applying transform of variant "+n+" for experiment "+e+" ",r);var o=(s=document)==null?void 0:s.querySelectorAll(r.selector);o?.forEach((a=>{var l=a;r.html&&(l.innerHTML=r.html),r.css&&l.setAttribute("style",r.css)}))}})):Me.aa("Control variants leave the page unmodified.")}_is_bot(){return Ue&&this._instance?Bf(Ue,this.Ne.custom_blocked_useragents):void 0}}var st=pe("[Conversations]"),En="Conversations not available yet.",wu="console",Gf="__posthogHandledLogsRequestError",Do=(t,e)=>{var n=t instanceof Error?t:new Error(e);return n[Gf]=!0,n},bu=t=>!!t&&typeof t=="object"&&t[Gf]===!0,Cs={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=gu,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 Um(t.config,t.Qi()),this.Ta=this.Ea)}updateConfig(t,e){var n;(n=this.Ea)==null||n.update(t,e)}setup(t){return this.Ia=t,this.rt=t.logger.createLogger("[FeatureFlags]"),n=()=>{this.Ia===t&&(this.Ia=void 0,this.nn=t,this.Pa(t))},(e=t.kv.initialize())!=null&&e.then?e.then(n):n();var e,n}Pa(t){if(this.nn===t)return w&&ve(w,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){w?.removeEventListener("online",this.Ca)}dispose(){var t;this.ba++,this.wa=!1,this.Ia=void 0,this.nn&&(this.La(),(t=this.Ra)==null||t.dispose(),this.Ra=void 0,this.ga=[],w?.removeEventListener("online",this.Ca),this.nn=void 0)}get Ne(){return this.Ta.get()}Oa(t){var e;return(e=this.nn)==null?void 0:e.kv.get(t)}F(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.set(t)}))}q(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.remove(t)}))}Da(t){try{t()}catch(e){this.rt.error("Failed to update feature flag persistence",e)}}Fa(){var t={};for(var e of[Ti,$i,Pr,It]){var n=this.Oa(e);C(n)||(t[e]=n)}this.fa=t;var i=I({},t),r=this.Oa(Sn);if(r)for(var s of Object.entries(r))i["$feature/"+s[0]]=s[1];this.pa=i}Aa(){var t=this.Ne.cacheTtlMs;if(!t||0>=t)return!1;var e=this.Oa(ji);return typeof e!="number"||Date.now()-e>t}$a(){return!!this.Aa()&&(this.xa||this.ya||(this.xa=!0,this.rt.warn("Feature flag cache is stale, triggering refresh..."),this.reloadFeatureFlags()),!0)}Na(){var t=this.Ne.evaluationContexts;return t!=null&&t.length?t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid evaluation context found:",e,"Expected non-empty string"),n})):[]}qa(){var t=this.Ne.flagKeys;if(!C(t))return t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid flag key found:",e,"Expected non-empty string"),n}))}initialize(){var t,e,n=this.Ne,i=(t=(e=n.bootstrap)==null?void 0:e.featureFlags)!==null&&t!==void 0?t:{};if(Object.keys(i).length){var r,s,o=(r=(s=n.bootstrap)==null?void 0:s.featureFlagPayloads)!==null&&r!==void 0?r:{},a=Object.keys(i).filter((u=>!!i[u])).reduce(((u,c)=>(u[c]=i[c]||!1,u)),{}),l=Object.keys(o).filter((u=>a[u])).reduce(((u,c)=>(o[c]&&(u[c]=o[c]),u)),{});return this.ja({featureFlags:a,featureFlagPayloads:l})}}updateFlags(t,e,n){var i,r,s=n!=null&&n.merge&&(i=this.Oa(Sn))!==null&&i!==void 0?i:{},o=n!=null&&n.merge&&(r=this.Oa($i))!==null&&r!==void 0?r:{},a=I({},s,t),l=I({},o,e),u={};for(var c of Object.entries(a)){var d=c[0],f=c[1];u[d]={key:d,enabled:hc(f),variant:pc(f),reason:void 0,metadata:C(l?.[d])?void 0:{id:0,version:void 0,description:void 0,payload:l[d]}}}this.ja({flags:u})}get hasLoadedFlags(){return this.ma}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var t=this.Oa(aa),e=this.Oa(It),n=this.Oa(xn);if(!n&&!e)return t||{};var i=fe({},t||{}),r=[...new Set([...Object.keys(n||{}),...Object.keys(e||{})])];for(var s of r){var o,a,l=i[s],u=e?.[s],c=C(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=C(u)?l?.variant:typeof u=="string"?u:void 0,f=n?.[s],h=I({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(h.original_enabled=l?.enabled),d!==l?.variant&&(h.original_variant=l?.variant),f&&(h.metadata=I({},l?.metadata,{payload:f,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),i[s]=h}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:n,finalDetails:i}),this.ca=!0),i}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((n=>{var i=t[n];return{key:n,enabled:hc(i),variant:pc(i),payload:fc(e[n])}}))}getFlagVariants(){var t=this.Oa(Sn),e=this.Oa(It);if(!e)return t||{};for(var n=fe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:e,finalFlags:n}),this.ca=!0),n}getFlagPayloads(){var t=this.Oa($i),e=this.Oa(xn);if(!e)return t||{};for(var n=fe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flag payloads!",{flagPayloads:t,overriddenPayloads:e,finalPayloads:n}),this.ca=!0),n}reloadFeatureFlags(){this._a||this.Ne.featureFlagsDisabled||this.Ma()||this.Ba||(this.ga.slice().forEach((t=>{try{t()}catch(e){this.rt.error("Error while running feature flags reloading callback",e)}})),this.Ba=setTimeout((()=>{this.Ha()}),5))}La(){clearTimeout(this.Ba),this.Ba=void 0}onReloading(t){return this.ga.push(t),()=>{this.ga=this.ga.filter((e=>e!==t))}}ensureFlagsLoaded(){this.ma||this.ya||this.Ba||this.reloadFeatureFlags()}setAnonymousDistinctId(t){this.$anon_distinct_id=t}setReloadingPaused(t){this._a=t}resetFlagCallReported(){this.q(Cn)}Ha(t){this.La();var e=this.nn;if(e&&!this.Ne.remoteRequestsDisabled&&!this.Ma())if(this.ya)this.wa=!0;else{var n={token:e.projectToken,distinct_id:e.distinctId,groups:e.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:I({},e.initialPersonProperties,this.Oa(jt)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(In),timezone:If()};C(e.deviceId)||(n.$device_id=e.deviceId),(t!=null&&t.disableFlags||this.Ne.featureFlagsDisabled)&&(n.disable_flags=!0);var i=this.Na();i.length&&(n.evaluation_contexts=i);var r=this.qa();C(r)||(n.flag_keys=r);var s=this.Ne.onlyEvaluateSurveyFeatureFlags,o="/flags/?v=2"+(s?"&only_evaluate_survey_feature_flags=true":""),a=this.ba;this.ya=!0;var l=()=>{this.wa&&(this.wa=!1,this.Ha())},u=c=>{this.ya=!1,a===this.ba&&(this.F({[Tr]:[mu]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:n,compression:this.Ne.compression==="base64"?je.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,f,h=(d=c.json)!==null&&d!==void 0?d:{},p=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),p||this.wa||(this.$anon_distinct_id=void 0),!n.disable_flags||this.wa){this.ka=!p;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?mu:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),h.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((f=h.quotaLimited)==null||!f.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[Tr]:g}),m?this.rt.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more."):n.disable_flags||this.ja(h,p,{partialResponse:s}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return vf(this.Sa,3)}Ua(t){this.Sa=_f(t,this.Sa,3,(()=>this.rt.warn("Feature flag requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped refreshing feature flags; will try again when connectivity changes.")))}getFeatureFlag(t,e){var n;if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var i=this.getFeatureFlagResult(t,e);return(n=i?.variant)!==null&&n!==void 0?n:i?.enabled}}else this.rt.warn('getFeatureFlag for key "'+t+Bo)}getFeatureFlagDetails(t){return this.getFlagsWithDetails()[t]}getFeatureFlagPayload(t){var e=this.getFeatureFlagResult(t,{send_event:!1});return e?.payload}getFeatureFlagResult(t,e){if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var n,i=this.getFlagVariants(),r=t in i,s=i[t],o=this.getFlagPayloads()[t],a=String(s),l=this.Oa(Pr)||void 0,u=this.Oa(ji)||void 0,c=this.Oa(Cn)||{};if(this.Ne.deduplicateCallsPerSession){var d,f=(d=this.nn)==null?void 0:d.session.sessionId,h=this.Oa(Li);f&&f!==h&&(c={},n=f)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))n&&this.F({[Cn]:c,[Li]:n});else{var p,g,m,v,E,S,_,b,k,T;U(c[t])?c[t].push(a):c[t]=[a],this.F(I({[Cn]:c},n?{[Li]:n}:{}));var x=this.getFeatureFlagDetails(t),F=[...(p=this.Oa(Tr))!==null&&p!==void 0?p:[]];C(s)&&F.push("flag_missing");var $={$feature_flag:t,$feature_flag_response:s,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((g=this.Ne.bootstrap)==null||(g=g.featureFlags)==null?void 0:g[t])||null,$feature_flag_bootstrapped_payload:((m=this.Ne.bootstrap)==null||(m=m.featureFlagPayloads)==null?void 0:m[t])||null,$used_bootstrap_value:!this.ka};C(x==null||(v=x.metadata)==null?void 0:v.has_experiment)||($.$feature_flag_has_experiment=x.metadata.has_experiment),C(x==null||(E=x.metadata)==null?void 0:E.version)||($.$feature_flag_version=x.metadata.version);var O,L=(S=x==null||(_=x.reason)==null?void 0:_.description)!==null&&S!==void 0?S:x==null||(b=x.reason)==null?void 0:b.code;L&&($.$feature_flag_reason=L),x!=null&&(k=x.metadata)!=null&&k.id&&($.$feature_flag_id=x.metadata.id),C(x?.original_variant)&&C(x?.original_enabled)||($.$feature_flag_original_response=C(x.original_variant)?x.original_enabled:x.original_variant),x!=null&&(T=x.metadata)!=null&&T.original_payload&&($.$feature_flag_original_payload=x==null||(O=x.metadata)==null?void 0:O.original_payload),F.length&&($.$feature_flag_error=F.join(",")),this.za($)}else n&&this.F({[Cn]:c,[Li]:n});if(r)return{key:t,enabled:!!s,variant:typeof s=="string"?s:void 0,payload:fc(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+Bo)}za(t){try{var e;(e=this.nn)==null||e.capture("$feature_flag_called",t).catch((n=>{this.rt.error("Failed to capture feature flag call",n)}))}catch(n){this.rt.error("Failed to capture feature flag call",n)}}getRemoteConfigPayload(t,e){this.Wa(t,e)}Wa(t,e){var n=this;return se((function*(){var i=n.nn;if(i){var r={distinct_id:i.distinctId,token:i.projectToken,person_properties:{$lib:i.library.name,$lib_version:i.library.version}},s=n.Na();s.length&&(r.evaluation_contexts=s);var o,a=n.qa();C(a)||(r.flag_keys=a);try{var l,u=(l=(yield i.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:r,compression:n.Ne.compression==="base64"?je.Base64:void 0,sentAt:"body",timeoutMs:n.Ne.requestTimeoutMs})).json)==null?void 0:l.featureFlagPayloads;o=u?.[t]||void 0}catch(c){return void n.rt.error("Remote config feature flag request failed",c)}try{e(o)}catch(c){n.rt.error("Remote config feature flag callback failed",c)}}}))()}isFeatureEnabled(t,e){if(e===void 0&&(e={}),e.fresh&&!this.ka)return e.defaultValue;if(!(this.ma||this.getFlags()&&this.getFlags().length>0))return this.rt.warn('isFeatureEnabled for key "'+t+Bo),e.defaultValue;var n=this.getFeatureFlag(t,e);return C(n)?e.defaultValue:!!n}addFeatureFlagsHandler(t){this.featureFlagEventHandlers.push(t)}removeFeatureFlagsHandler(t){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((e=>e!==t))}receivedFeatureFlags(t,e,n){this.ja(t,e,n)}ja(t,e,n){if(this.nn){this.ma=!0;var i=(function(r,s,o,a,l,u){s===void 0&&(s={}),o===void 0&&(o={}),a===void 0&&(a={}),u===void 0&&(u=gu);var c=((k,T)=>{var x=k.flags;return x?I({},k,{featureFlags:Object.fromEntries(Object.keys(x).map((F=>{var $;return[F,($=x[F].variant)!==null&&$!==void 0?$:x[F].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(x).filter((F=>x[F].enabled)).filter((F=>{var $;return($=x[F].metadata)==null?void 0:$.payload})).map((F=>{var $;return[F,($=x[F].metadata)==null?void 0:$.payload]})))}):(k.featureFlags&&T.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),k)})(r,u),d=c.flags,f=c.featureFlags,h=c.featureFlagPayloads;if(f){var p=r.requestId,g=r.evaluatedAt;if(U(f)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(f)for(var v=0;f.length>v;v++)m[f[v]]=!0;return{[Ti]:f,[Sn]:m,[Zr]:!1}}var E=f,S=h,_=d;if(l!=null&&l.partialResponse)E=I({},s,E),S=I({},o,S),_=I({},a,_);else if(r.errorsWhileComputingFlags)if(d){var b=new Set(Object.keys(d).filter((k=>{var T;return!((T=d[k])!=null&&T.failed)})));E=I({},s,Object.fromEntries(Object.entries(E).filter((k=>b.has(k[0]))))),S=I({},o,Object.fromEntries(Object.entries(S||{}).filter((k=>b.has(k[0]))))),_=I({},a,Object.fromEntries(Object.entries(_||{}).filter((k=>b.has(k[0])))))}else E=I({},s,E),S=I({},o,S),_=I({},a,_);return I({[Ti]:Object.keys(_u(E)),[Sn]:E||{},[$i]:S||{},[aa]:_||{},[Zr]:r.minimalFlagCalledEvents===!0},p?{[Pr]:p}:{},g?{[ji]:g}:{})}})(t,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),n,this.rt);i&&this.F(i),e||(this.xa=!1),this.Va(e)}}override(t,e){e===void 0&&(e=!1),this.rt.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:t,suppressWarning:e})}overrideFeatureFlags(t){this.Za(t)}Za(t){if(this.nn){if(t===!1)return this.q([It,xn]),this.Va(),void bn.info("All overrides cleared");if(U(t))return this.F({[It]:vu(t)}),this.Va(),void bn.info("Flag overrides set",{flags:t});if(t&&typeof t=="object"&&("flags"in t||"payloads"in t)){var e,n=t;this.ca=!!((e=n.suppressWarning)!==null&&e!==void 0&&e);var i={},r=n.flags,s=n.payloads;return r&&(i[It]=U(r)?vu(r):r),s&&(i[xn]=s),Object.keys(i).length&&this.F(i),r===!1&&s===!1?this.q([It,xn]):r===!1?this.q(It):s===!1&&this.q(xn),this.Va(),r===!1?bn.info("Flag overrides cleared"):r&&bn.info("Flag overrides set",{flags:r}),void(s===!1?bn.info("Payload overrides cleared"):s&&bn.info("Payload overrides set",{payloads:s}))}if(t&&typeof t=="object")return this.F({[It]:t}),this.Va(),void bn.info("Flag overrides set",{flags:t});this.rt.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:t})}else this.rt.warn("posthog.featureFlags.overrideFeatureFlags called before feature flags were ready")}onFeatureFlags(t){if(this.addFeatureFlagsHandler(t),this.ma){var e=this.Ga(),n=e.flags,i=e.flagVariants;try{t(n,i)}catch(r){this.rt.error("Error while running feature flags callback",r)}}return()=>this.removeFeatureFlagsHandler(t)}updateEarlyAccessFeatureEnrollment(t,e,n){var i=(this.Oa(Ar)||[]).find((l=>l.flagKey===t)),r={["$feature_enrollment/"+t]:e},s={$feature_flag:t,$feature_enrollment:e,$set:r};i&&(s.$early_access_feature_name=i.name),n&&(s.$feature_enrollment_stage=n);var o=I({},this.getFlagVariants(),{[t]:e});this.F({[Ti]:Object.keys(_u(o)),[Sn]:o,[jt]:I({},this.Oa(jt)||{},r)}),this.Va();try{var a;(a=this.nn)==null||a.capture("$feature_enrollment_update",s).catch((l=>{this.rt.error("Failed to capture early access feature enrollment",l)}))}catch(l){this.rt.error("Failed to capture early access feature enrollment",l)}}getEarlyAccessFeatures(t,e,n){e===void 0&&(e=!1);var i=this.Oa(Ar);!i||e?this.Qa(t,n):t(i)}Qa(t,e){var n=this;return se((function*(){var i=n.nn;if(i){var r,s=e?"&"+e.map((a=>"stage="+a)).join("&"):"";try{var o=yield i.sendRequest("/api/early_access_features/?token="+i.projectToken+s,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;n.F({[Ar]:r=o.json.earlyAccessFeatures})}catch(a){return void n.rt.error("Early access feature request failed",a)}try{t(r)}catch(a){n.rt.error("Early access feature callback failed",a)}}}))()}Ga(){var t=this.getFlags(),e=this.getFlagVariants();return{flags:t.filter((n=>e[n])),flagVariants:Object.keys(e).filter((n=>e[n])).reduce(((n,i)=>(n[i]=e[i],n)),{})}}Va(t){this.Fa();var e=this.Ga(),n=e.flags,i=e.flagVariants;this.featureFlagEventHandlers.forEach((r=>{try{r(n,i,{errorsLoading:t})}catch(s){this.rt.error("Error while running feature flags callback",s)}}))}setPersonPropertiesForFlags(t,e){e===void 0&&(e=!0),this.Ka(t,e)}Ka(t,e){e===void 0&&(e=!0);var n=this.Oa(jt)||{},i=t?.$set||(t!=null&&t.$set_once?{}:t),r=t?.$set_once,s={};if(r)for(var o in r)({}).hasOwnProperty.call(r,o)&&(o in n||(s[o]=r[o]));this.F({[jt]:I({},n,s,i)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=I({},this.Oa(jt)||{});t.forEach((i=>{delete n[i]})),this.F({[jt]:n}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(jt),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=this.Oa(In)||{},i=I({},n);for(var r of Object.keys(t))i[r]=I({},n[r],t[r]);this.F({[In]:i}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(In)||{};this.F({[In]:I({},e,{[t]:{}})})}else this.q(In)}reset(){this.ba++,this.wa=!1,this.Fa(),this.ma=!1,this._a=!1,this.ka=!1,this.$anon_distinct_id=void 0,this.La(),this.ca=!1,this.Sa=0}}},Wm={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===ki||this.Ya===Sr?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=lu,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(P==null||!P.visibilityState||P.visibilityState==="visible")return!0;var n=w==null||(e=w.performance)==null||e.getEntriesByType==null?void 0:e.getEntriesByType("visibility-state");return!(n!=null&&n.length)||n.some((i=>i.name==="visible"))})(),this.Ie=()=>{var e;P?.visibilityState==="visible"&&(this.io=!0,(e=this.Ja)==null||e.setDocumentWasEverVisible==null||e.setDocumentWasEverVisible(!0))},this._instance=t,!this._instance.sessionManager)throw Bt.error("started without valid sessionManager"),new Error(Ia+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===Wt)throw new Error(Ia+' cannot be used with cookieless_mode="always"');P!=null&&P.addEventListener&&ve(P,"visibilitychange",this.Ie)}initialize(){this.startIfEnabledOrStop()}dispose(){this.eo=!0,P==null||P.removeEventListener==null||P.removeEventListener("visibilitychange",this.Ie),this.stopRecording()}get ro(){var t,e=!((t=this._instance.get_property(An))==null||!t.enabled),n=!this.Ne.disable_session_recording,i=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return w&&e&&n&&!i}startIfEnabledOrStop(t){var e;if(!(this.eo||this.ro&&(e=this.Ja)!=null&&e.isStarted)){var n=!C(Object.assign)&&!C(Array.from);this.ro&&n?(this.no(t),Bt.info("starting")):(this.Ya=lu,this.stopRecording())}}no(t){var e,n,i;this.ro&&(this.Ya!==ki&&this.Ya!==Sr&&(this.Ya=cu),B!=null&&(e=B.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(n=B.__PosthogExtensions__)!=null&&n.initSessionRecording?this.so(t):(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,this.ao,(r=>{if(r)return Bt.error("could not load recorder",r);this.so(t)})))}stopRecording(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.stop()}oo(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.discard()}lo(){var t,e;(t=this.Mr)==null||t.unregister(ol),(e=this.Mr)==null||e.unregister(Vd)}uo(t,e){if(H(t))return null;var n,i=ke(t)?t:parseFloat(t);return typeof(n=i)!="number"||!Number.isFinite(n)||0>n||n>1?(Bt.warn(e+" must be between 0 and 1. Ignoring invalid value:",t),null):i}ho(t){if(this.Mr){var e,n,i=this.Mr,r=()=>{var s,o=t.sessionRecording===!1?void 0:t.sessionRecording,a=this.uo((s=this.Ne.session_recording)==null?void 0:s.sampleRate,"session_recording.sampleRate"),l=this.uo(o?.sampleRate,"remote config sampleRate"),u=a??l;H(u)&&this.lo();var c=o?.minimumDurationMilliseconds;i.register({[An]:I({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:I({capturePerformance:t.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:u,minimumDurationMilliseconds:C(c)?null:c,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers,version:o?.version,triggerGroups:o?.triggerGroups})})};r(),(e=this.Xa)==null||e.call(this),this.Xa=(n=this._instance.sessionManager)==null?void 0:n.onSessionId(r)}}onRemoteConfig(t){var e=t.ok?t.config:void 0;return e&&"sessionRecording"in e?e.sessionRecording===!1?(this.ho(e),void this.oo()):(this.ho(e),void this.startIfEnabledOrStop()):(this.Ya===ki&&(this.Ya=Sr,Bt.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(t,e){var n;e===void 0&&(e="log"),(n=this.Ja)!=null&&n.log?this.Ja.log(t,e):Bt.warn("log called before recorder was ready")}get ao(){var t,e,n=(t=this._instance)==null||(t=t.persistence)==null?void 0:t.get_property(An);return(n==null||(e=n.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(An);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(n){return Bt.warn("persisted remote config for session recording is invalid and will be ignored",n),!1}return!H(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,n,i;if(!this.eo){if((e=B.__PosthogExtensions__)==null||!e.initSessionRecording)return Bt.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[ef]:!0});var r;if(this.Ja||(this.Ja=(r=B.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===Sr||this.Ya===ki?void 0:(this.Ya=ki,Bt.info("persisted remote config is stale, requesting fresh config before starting"),void new kf(this._instance).load());this.Ya=cu,(n=(i=this.Ja).setDocumentWasEverVisible)==null||n.call(i,this.io),this.Ja.start(t)}}onRRwebEmit(t){var e;(e=this.Ja)==null||e.onRRwebEmit==null||e.onRRwebEmit(t)}overrideLinkedFlag(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Kd]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Gd]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,n;this.Ja||(n=this.Mr)==null||n.register({[t==="url"?Yd:Jd]:!0}),(e=this.Ja)==null||e.overrideTrigger(t)}get sdkDebugProperties(){var t;return((t=this.Ja)==null?void 0:t.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(t,e){var n;return!((n=this.Ja)==null||!n.tryAddCustomEvent(t,e))}}},qm={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new su(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,n=he(this.instance.config.autocapture)?this.instance.config.autocapture:{};return n.url_allowlist=(t=n.url_allowlist)==null?void 0:t.map((i=>new RegExp(i))),n.url_ignorelist=(e=n.url_ignorelist)==null?void 0:e.map((i=>new RegExp(i))),n}yo(){if(this.isBrowserSupported()){if(w&&P){var t=n=>{n=n||w?.event;try{this.bo(n)}catch(i){Mo.error("Failed to capture event",i)}};if(ve(P,"submit",t,{capture:!0}),ve(P,"change",t,{capture:!0}),ve(P,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=n=>{n=n||w?.event;try{this.bo(n,$o)}catch(i){Mo.error("Failed to capture copy/cut event",i)}};ve(P,"copy",e,{capture:!0}),ve(P,"cut",e,{capture:!0})}}}else Mo.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.vo&&(this.yo(),this.vo=!0)}onRemoteConfig(t){if(this.fo=!0,t.ok){var e=t.config;e.elementsChainAsString&&(this.po=e.elementsChainAsString);var n=e.autocapture_opt_out;mt(n)&&(this.instance.persistence&&this.instance.persistence.register({[ea]:n}),this.co=n),this.startIfEnabled()}else this.startIfEnabled()}setElementSelectors(t){this.mo=t}getElementSelectors(t){var e,n=[];return(e=this.mo)==null||e.forEach((i=>{var r=P?.querySelectorAll(i);r?.forEach((s=>{t===s&&n.push(i)}))})),n}get isEnabled(){var t,e,n=(t=this.instance.persistence)==null?void 0:t.props[ea],i=this.co,r=this.instance.Qi()&&!this.fo;if(Ke(i)&&!mt(n)&&!r)return!1;var s=(e=this.co)!==null&&e!==void 0?e:!!n;return!!this.instance.config.autocapture&&!s}bo(t,e){if(e===void 0&&(e="$autocapture"),this.isEnabled){var n,i=bo(t);of(i)&&(i=i.parentNode||null),e==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&this.instance.config.rageclick&&(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,t.timeStamp||new Date().getTime())&&Lc(i,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var r=e===$o;if(i&&(function(d,f,h,p,g,m){var v;if(!w||dl(d)||h!=null&&h.url_allowlist&&!Tc(h.url_allowlist,m)||h!=null&&h.url_ignorelist&&Tc(h.url_ignorelist,m))return!1;if(h!=null&&h.dom_event_allowlist){var E=h.dom_event_allowlist;if(E&&!E.some((x=>f.type===x)))return!1}var S=ff(d,p),_=S.parentIsUsefulElement,b=S.targetElementList;if(!(function(x,F){var $=F?.element_allowlist;if(C($))return!0;var O,L=function(K){if($.some((V=>K.tagName.toLowerCase()===V)))return{v:!0}};for(var N of x)if(O=L(N))return O.v;return!1})(b,h)||!ma(b,h?.css_selector_allowlist)||ma(b,(v=h?.css_selector_ignorelist)!==null&&v!==void 0?v:Ug))return!1;try{var k=w.getComputedStyle(d);if(k&&k.getPropertyValue("cursor")==="pointer"&&f.type==="click")return!0}catch{}var T=d.tagName.toLowerCase();switch(T){case"html":return!1;case"form":return(g||["submit"]).indexOf(f.type)>=0;case"input":case"select":case"textarea":return(g||["change","click"]).indexOf(f.type)>=0;default:return _?(g||["click"]).indexOf(f.type)>=0:(g||["click"]).indexOf(f.type)>=0&&(ul.indexOf(T)>-1||d.getAttribute("contenteditable")==="true")}})(i,t,this.Ne,r,r?["copy","cut"]:void 0,this.instance)){var s=$m(i,{e:t,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.Ne.element_attribute_ignorelist,elementsChainAsString:this.po,disableCaptureUrlHashes:this.instance.config.disable_capture_url_hashes}),o=s.props;if(s.explicitNoCapture)return!1;var a=this.getElementSelectors(i);if(a&&a.length>0&&(o.$element_selectors=a),e===$o){var l,u=cf(w==null||(l=w.getSelection())==null?void 0:l.toString()),c=t.type||"clipboard";if(!u)return!1;o.$selected_content=u,o.$copy_type=c}return this.instance.capture(e,o),!0}}}isBrowserSupported(){return De(P?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(w==null||(e=w.location)==null?void 0:e.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(A.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.wo&&this.wo(),this.wo=void 0,A.info("History API monitoring stopped")}monitorHistoryChanges(){w&&w.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(w&&((e=w.history[t])==null||!e.__posthog_wrapped__)){var n=this;(function(i,r,s){try{if(!(r in i))return ou;var o={next:i[r]},a=s((function(){for(var l=arguments.length,u=new Array(l),c=0;l>c;c++)u[c]=arguments[c];return o.next.apply(this,u)}));return De(a)&&(a.prototype=a.prototype||{},Object.defineProperties(a,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:o}})),i[r]=a,()=>{if(i[r]!==a)for(var l=i[r];De(l)&&l.__posthog_layer__;){var u=l.__posthog_layer__;if(u.next===a)return void(u.next=o.next);l=u.next}else i[r]=o.next}}catch{return ou}})(w.history,t,(i=>function(r,s,o){i.call(this,r,s,o),n.So(t)}))}}So(t){try{var e,n=w==null||(e=w.location)==null?void 0:e.pathname;if(!n)return;n!==this._o&&this.isEnabled&&this._instance.capture(Vn,{navigation_type:t}),this._o=n}catch(i){A.error("Error capturing "+t+" pageview",i)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};ve(w,"popstate",t),this.wo=()=>{w&&w.removeEventListener("popstate",t)}}}},heatmaps:class{get Ne(){return this.instance.config}constructor(t){var e;this.Co=!1,this.vo=!1,this.Mo=null,this.instance=t,this.Co=!((e=this.instance.persistence)==null||!e.props[ta]),this.rageclicks=new su(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return he(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return H(this.Ne.capture_heatmaps)?H(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;Lm.info("starting..."),this.To(),this.Ie()}else{var t;clearInterval((t=this.Mo)!==null&&t!==void 0?t:void 0),this.Eo(),this.getAndClearBuffer()}}onRemoteConfig(t){if(t.ok){var e=t.config;if("heatmaps"in e){var n=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[ta]:n}),this.Co=n,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){No(t.originalEvent)&&this.ke(t.originalEvent,"deadclick")}Ie(){this.Mo&&clearInterval(this.Mo),this.Mo=P?.visibilityState==="visible"?setInterval(this.cr.bind(this),this.flushIntervalMilliseconds):null}To(){w&&P&&(this.Po=this.cr.bind(this),ve(w,ns,this.Po),this.Ro=t=>this.ke(t||w?.event),ve(P,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||w?.event),ve(P,"mousemove",this.Ao,{capture:!0}),this.Lo=new Hc(this.instance,Kg,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),ve(P,ts,this.Oo),this.vo=!0)}Eo(){var t;w&&P&&(this.Po&&w.removeEventListener(ns,this.Po),this.Ro&&P.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&P.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&P.removeEventListener(ts,this.Oo),clearTimeout(this.Do),(t=this.Lo)==null||t.stop(),this.vo=!1)}$o(t,e){var n=this.instance.scrollManager.scrollY(),i=this.instance.scrollManager.scrollX(),r=this.instance.scrollManager.scrollElement(),s=(function(o,a,l){for(var u=o;u&&hn(u)&&!Qe(u,"body");){if(u===l)return!1;var c=void 0;try{var d,f,h;c=(d=(f=(h=u.ownerDocument)==null?void 0:h.defaultView)!==null&&f!==void 0?f:w)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(j(a,c))return!0;u=uf(u)}return!1})(bo(t),["fixed","sticky"],r);return{x:t.clientX+(s?0:i),y:t.clientY+(s?0:n),target_fixed:s,type:e}}ke(t,e){var n;if(e===void 0&&(e="click"),!Rc(t.target)&&No(t)){var i=this.$o(t,e);(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,new Date().getTime())&&Lc(bo(t),this.instance.config.rageclick)&&this.Vt(I({},i,{type:"rageclick"})),this.Vt(i)}}Fo(t){!Rc(t.target)&&No(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(w){var e=this.Ne.disable_capture_url_hashes?fn(w.location.href):w.location.href,n=this.Ne.custom_personal_data_properties,i=this.Ne.mask_personal_data_properties?[...ri,...n||[]]:[],r=Zi(e,i,Xi);this.R=this.R||{},this.R[r]||(this.R[r]=[]),this.R[r].push(t)}}cr(){this.R&&!Kt(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:Hc,webVitalsAutocapture:class{constructor(t){var e;this.Co=!1,this.vo=!1,this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this.No=()=>{clearTimeout(this.qo),this.qo=void 0,this.R.metrics.length!==0&&(this._instance.capture("$web_vitals",I({$current_url:this.R.url},this.R.metrics.reduce(((n,i)=>I({},n,{["$web_vitals_"+i.name+"_event"]:I({},i),["$web_vitals_"+i.name+"_value"]:i.value})),{}))),this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.jo=n=>{var i;if(this.R=this.R||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},H(n?.name)||H(n?.value))wn.error("Invalid metric received",n);else{var r=typeof n.navigationURL=="string"?n.navigationURL:void 0,s=this.Bo(r);if(!C(s)){var o=ke(n.navigationId)||typeof n.navigationId=="string"?"navigation:"+n.navigationId:"url:"+s;if(!this.Ho||this.Ho>n.value){this.R.navigationKey!==o&&(this.No(),this.qo=setTimeout(this.No,this.flushToCaptureTimeoutMs)),C(this.R.navigationKey)&&(this.R.navigationKey=o,this.R.url=s),this.R.firstMetricTimestamp=C(this.R.firstMetricTimestamp)?Date.now():this.R.firstMetricTimestamp,n.attribution&&n.attribution.interactionTargetElement&&(n.attribution.interactionTargetElement=void 0);var a=(i=this._instance.sessionManager)==null?void 0:i.checkAndGetSessionAndWindowId(!0),l=I({},n,r?{navigationURL:s}:{},{$current_url:s,timestamp:Date.now()});C(a)||(l.$session_id=a.sessionId,l.$window_id=a.windowId),this.R.metrics.push(l),this.R.metrics.length===this.allowedMetrics.length&&this.No()}else wn.error("Ignoring metric with value >= "+this.Ho,n)}}},this.Uo=()=>{if(!this.vo){var n,i,r,s,o=B.__PosthogExtensions__,a=o?.postHogWebVitalsCallbacksByFlavor,l=a?.[this.zo]||(this.zo==="web-vitals"&&C(a)?o?.postHogWebVitalsCallbacks:void 0);if(C(l)||(n=l.onLCP,i=l.onCLS,r=l.onFCP,s=l.onINP),n&&i&&r&&s){var u={reportSoftNavs:this.useSoftNavs};this.allowedMetrics.indexOf("LCP")>-1&&n(this.jo.bind(this),u),this.allowedMetrics.indexOf("CLS")>-1&&i(this.jo.bind(this),u),this.allowedMetrics.indexOf("FCP")>-1&&r(this.jo.bind(this),u),this.allowedMetrics.indexOf("INP")>-1&&s(this.jo.bind(this),u),this.vo=!0}else wn.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[sa]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,n=he(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return H(n)?((e=this._instance.persistence)==null?void 0:e.props[oa])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(he(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=he(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=he(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=he(this.Wo)&&ke(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:au;return t>0&&6e4>=t?au:t}get isEnabled(){var t=me?.protocol;if(t!=="http:"&&t!=="https:")return wn.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=he(this.Wo)?this.Wo.web_vitals:mt(this.Wo)?this.Wo:void 0;return mt(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(wn.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var n=he(e.capturePerformance)&&!!e.capturePerformance.web_vitals,i=he(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[sa]:n}),this._instance.persistence.register({[oa]:i})),this.Co=n,this.startIfEnabled()}}}get zo(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}ai(t){var e=B.__PosthogExtensions__,n=this.zo,i=e?.postHogWebVitalsCallbacksByFlavor;i!=null&&i[n]||n==="web-vitals"&&C(i)&&e!=null&&e.postHogWebVitalsCallbacks?t():e==null||e.loadExternalDependency==null||e.loadExternalDependency(this._instance,n,(r=>{r?wn.error("failed to load script",r):t()}))}Bo(t){var e=t||w?.location.href;if(e){var n=this._instance.config.disable_capture_url_hashes?fn(e):e,i=this._instance.config.custom_personal_data_properties,r=this._instance.config.mask_personal_data_properties?[...ri,...i||[]]:[];return Zi(n,r,Xi)}wn.error("Could not determine current URL")}}},zm={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var n;if(w&&this.isEnabled&&(n=B.__PosthogExtensions__)!=null&&n.errorWrappingFunctions){var i=B.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,r=B.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,s=B.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.Vo&&this.Ne.capture_unhandled_errors&&(this.Vo=i(this.captureException.bind(this))),!this.Zo&&this.Ne.capture_unhandled_rejections&&(this.Zo=r(this.captureException.bind(this))),!this.Go&&this.Ne.capture_console_errors&&(this.Go=s(this.captureException.bind(this)))}catch(o){Ii.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[na]),this.Jo=new Wp(I({},(function(n){var i,r,s,o;return n===void 0&&(n={}),{refillRate:(i=(r=n.exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:n.__exceptionRateLimiterRefillRate)!==null&&i!==void 0?i:1,bucketSize:(s=(o=n.exceptionRateLimiterBucketSize)!==null&&o!==void 0?o:n.__exceptionRateLimiterBucketSize)!==null&&s!==void 0?s:10}})(this._instance.config.error_tracking),{refillInterval:1e4,rt:Ii})),this.Ne=this.Yo(),this.startIfEnabledOrStop()}Yo(){var t=this._instance.config.capture_exceptions,e={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return he(t)?e=I({},e,t):(C(t)?this.Ko:t)&&(e=I({},e,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),e}get isEnabled(){return this.Ne.capture_console_errors||this.Ne.capture_unhandled_errors||this.Ne.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(Ii.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",(i=>{if(i)return Ii.error("failed to load script",i);t()}))}Qo(){var t,e,n;(t=this.Vo)==null||t.call(this),this.Vo=void 0,(e=this.Zo)==null||e.call(this),this.Zo=void 0,(n=this.Go)==null||n.call(this),this.Go=void 0}onRemoteConfig(t){if(t.ok){var e=t.config;"autocaptureExceptions"in e&&(this.Ko=!!e.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[na]:this.Ko}),this.Ne=this.Yo(),this.startIfEnabledOrStop())}}onConfigChange(){this.Ne=this.Yo()}captureException(t){var e,n,i,r=(e=t==null||(n=t.$exception_list)==null||(n=n[0])==null?void 0:n.type)!==null&&e!==void 0?e:"Exception";this.Jo.consumeRateLimit(r)?Ii.info("Skipping exception capture because of client rate limiting.",{exception:r}):(i=this._instance.exceptions)==null||i.sendExceptionEvent(t)}},exceptions:class{constructor(t){var e,n;this.Xo=[],this.tl=new og([new pg,new Sg,new mg,new gg,new bg,new wg,new _g,new Eg],(function(i){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;r>o;o++)s[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` -`),d=l;c.length>d;d++){var f=c[d];if(1024>=f.length){var h=Cc.test(f)?f.replace(Cc,"$1"):f;if(!h.match(/\S*Error: /)){for(var p of s){var g=p(h,i);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var v=Array.from(m);return v.reverse(),v.slice(0,50).map((E=>{return I({},E,{filename:E.filename||(S=v,S[S.length-1]||{}).filename,function:E.function||ni});var S}))})(u)}})("web:javascript",ug,hg)),this._instance=t,this.Xo=(e=(n=this._instance.persistence)==null?void 0:n.get_property(ia))!==null&&e!==void 0?e:[],this.el=Jr(this.il()),this.rl=new Ig(this.el)}onConfigChange(){this.el=Jr(this.il()),this.rl.setConfig(this.el)}onRemoteConfig(t){var e,n,i;if(t.ok){var r=t.config;if("errorTracking"in r){var s=(e=(n=r.errorTracking)==null?void 0:n.suppressionRules)!==null&&e!==void 0?e:[],o=(i=r.errorTracking)==null?void 0:i.captureExtensionExceptions;this.Xo=s,this._instance.persistence&&this._instance.persistence.register({[ia]:this.Xo,[ra]:o})}}}get nl(){var t,e=!!this._instance.get_property(ra),n=this._instance.config.error_tracking.captureExtensionExceptions;return(t=n??e)!==null&&t!==void 0&&t}buildProperties(t,e){return this.tl.buildFromUnknown(t,{syntheticException:e?.syntheticException,mechanism:{handled:e?.handled}})}addExceptionStep(t,e){if(this.el.enabled)try{if(!X(t)||t.trim().length===0)return void St.warn("Ignoring exception step because message must be a non-empty string");var n=(function(s){if(!s)return{sanitizedProperties:{},droppedKeys:[]};var o=[];return{sanitizedProperties:Object.keys(s).reduce(((a,l)=>xg.has(l)?(o.push(l),a):(a[l]=s[l],a)),{}),droppedKeys:o}})(this.sl(e)),i=n.sanitizedProperties,r=n.droppedKeys;r.length>0&&St.warn("Ignoring reserved exception step fields",{droppedKeys:r}),this.rl.add(I({[Kr]:t,[Yr]:new Date().toISOString()},i))}catch(s){St.error("Failed to add exception step. Ignoring breadcrumb.",s)}}sendExceptionEvent(t){try{var e=t.$exception_list;if(this.al(e)){if(this.ol(e))return this.ll("Exception dropped: matched a suppression rule"),void St.info("Skipping exception capture because a suppression rule matched");if(!this.nl&&this.ul(e))return this.ll("Exception dropped: thrown by a browser extension"),void St.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.hl(e))return this.ll("Exception dropped: thrown by the PostHog SDK"),void St.info("Skipping exception capture because it was thrown by the PostHog SDK")}var n=this.el.enabled&&H(t.$exception_steps)?this.dl(t):t,i=typeof(s=globalThis._posthogReleaseId)=="string"&&s.length>0?s:void 0;i&&(n.$release_id=i);try{var r=this._instance.capture("$exception",n,{_noTruncate:!0,_batchKey:"exceptionEvent",Wn:!0});return r&&this.rl.clear(),r}catch(o){return St.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void St.error("Failed to process exception event. Ignoring this exception.",o)}var s}dl(t){try{var e=this.rl.getAttachable();return e.length===0?t:I({},t,{$exception_steps:e})}catch(n){return St.error("Failed to read buffered exception steps. Capturing exception without steps.",n),t}}ll(t){this.el.enabled&&this.rl.add({[Kr]:t,[Yr]:new Date().toISOString()})}sl(t){return he(t)?I({},t):{}}il(){var t,e;return(t=(e=this._instance.config.error_tracking)==null?void 0:e.exception_steps)!==null&&t!==void 0?t:{}}ol(t){if(t.length===0)return!1;try{var e=t.reduce(((n,i)=>{var r=i.type,s=i.value;return X(r)&&r.length>0&&n.$exception_types.push(r),X(s)&&s.length>0&&n.$exception_values.push(s),n}),{$exception_types:[],$exception_values:[]});return this.Xo.some((n=>{var i=n.values.map((r=>{var s=jf[r.operator],o=e[r.key];if(!s||!o)return!1;var a=U(r.value)?r.value:[r.value];return a.length>0&&s(a,o)}));return n.type==="OR"?i.some(Boolean):i.every(Boolean)}))}catch(n){return St.warn("Failed to evaluate suppression rules. Capturing the exception.",n),!1}}ul(t){return t.flatMap((e=>{var n,i;return(n=(i=e.stacktrace)==null?void 0:i.frames)!==null&&n!==void 0?n:[]})).some((e=>e.filename&&e.filename.startsWith("chrome-extension://")))}hl(t){if(t.length>0){var e,n,i,r,s=(e=(n=t[0].stacktrace)==null?void 0:n.frames)!==null&&e!==void 0?e:[],o=s[s.length-1];return(i=o==null||(r=o.filename)==null?void 0:r.includes("posthog.com/static"))!==null&&i!==void 0&&i}return!1}al(t){return!H(t)&&U(t)}}},Vm=I({productTours:class{get Mr(){return this._instance.persistence}constructor(t){this.vl=null,this.cl=null,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(t.ok){var e=t.config;if("productTours"in e){var n,i;if(this.Mr&&this.Mr.register({[sl]:!!e.productTours}),!Oo(this._instance))return!this.vl&&H((n=this.Mr)==null?void 0:n.props[Mi])||xr.info("product tours disabled; stopping and clearing cached tours"),(i=this.vl)==null||i.stop(),this.vl=null,void this.clearCache();this.loadIfEnabled()}}}loadIfEnabled(){!this.vl&&Oo(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.generateProductTours?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",(i=>{i?xr.error("Could not load product tours script",i):t()}))}fl(){var t;!this.vl&&(t=B.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=B.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(t,e){if(e===void 0&&(e=!1),!U(this.cl)||e){var n=this.Mr;if(n){var i=n.props[Mi];if(U(i)&&!e)return this.cl=i,void t(i,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",timestampMode:"query",callback:r=>{if(Oo(this._instance)){var s=r.statusCode;if(s!==200||!r.json){var o="Product Tours API could not be loaded, status: "+s;return s===0?r.error||xr.warn(o):xr.error(o),void t([],{isLoaded:!1,error:o})}var a=U(r.json.product_tours)?r.json.product_tours:[];this.cl=a,n&&n.register({[Mi]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){H(this.vl)?t([],{isLoaded:!1,error:"Product tours not loaded"}):this.vl.getActiveProductTours(t)}showProductTour(t){var e;(e=this.vl)==null||e.showTourById(t)}previewTour(t){this.vl?this.vl.previewTour(t):this.ai((()=>{var e;this.fl(),(e=this.vl)==null||e.previewTour(t)}))}dismissProductTour(){var t;(t=this.vl)==null||t.dismissTour("user_clicked_skip")}nextStep(){var t;(t=this.vl)==null||t.nextStep()}previousStep(){var t;(t=this.vl)==null||t.previousStep()}clearCache(){var t;this.cl=null,(t=this.Mr)==null||t.unregister(Mi)}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)}}},Cs),Gm={siteApps:class{constructor(t){this.pl=0,this._instance=t,this.gl=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}ml(t,e){if(e){var n=this.globalsForEvent(e);this.gl.push(n),this.gl.length>1e3&&(this.gl=this.gl.slice(10))}}get siteAppLoaders(){var t;return(t=B._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,n,i,r,s,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var f=d[0];l[f]={id:u[f],type:f,properties:d[1]}}var h=t.$set_once,p=t.$set;return{event:I({},ud(t,Nm),{properties:I({},t.properties,p?{$set:I({},(e=(n=t.properties)==null?void 0:n.$set)!==null&&e!==void 0?e:{},p)}:{},h?{$set_once:I({},(i=(r=t.properties)==null?void 0:r.$set_once)!==null&&i!==void 0?i:{},h)}:{}),elements_chain:(s=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&s!==void 0?s:"",distinct_id:(a=t.properties)==null?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}bl(t){var e,n=(e=t.tagName)==null?void 0:e.toLowerCase();return n==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(Et.error("prepare_external_dependency_stylesheet returned null"),null):n==="script"&&this._instance.config.prepare_external_dependency_script?this._instance.config.prepare_external_dependency_script(t)||(Et.error("prepare_external_dependency_script returned null"),null):t}_l(){var t,e,n,i,r,s,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=P?.defaultView,u=l==null||(t=l.Node)==null?void 0:t.prototype;if(!l||!u)return()=>{};if(this.pl++,this.wl)return this.kl();var c=[],d=this,f=new WeakSet,h=(m,v,E)=>{if(m!=null&&m[v]){var S=m[v];m[v]=E(S),c.push((()=>{m[v]=S}))}},p=m=>{if(f.has(m))return m;var v=d.bl(m);return v&&f.add(v),v},g=m=>m.map((v=>typeof v=="string"?v:p(v))).filter((v=>!Ke(v)));return h(u,"appendChild",(m=>function(v){var E=p(v);return E?m.call(this,E):v})),h(u,"insertBefore",(m=>function(v,E){var S=p(v);return S?m.call(this,S,E):v})),h(u,"replaceChild",(m=>function(v,E){var S=p(v);return S?m.call(this,S,E):E})),[(e=l.Element)==null?void 0:e.prototype,(n=l.Document)==null?void 0:n.prototype,(i=l.DocumentFragment)==null?void 0:i.prototype].forEach((m=>{h(m,"append",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),h(m,"prepend",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))}))})),[(r=l.Element)==null?void 0:r.prototype,(s=l.CharacterData)==null?void 0:s.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((m=>{h(m,"before",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),h(m,"after",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),h(m,"replaceWith",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];var b=g(S);return S.length&&!b.length?void 0:v.apply(this,b)}))})),h((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(v,E){var S=p(E);return S?m.call(this,v,S):null})),this.wl=()=>{c.forEach((m=>m())),this.wl=void 0},this.kl()}kl(){var t=!1;return()=>{var e;t||(t=!0,this.pl--,this.pl===0&&((e=this.wl)==null||e.call(this)))}}xl(t,e){e===void 0&&(e=!0);var n=this._l();try{var i=t(n);return e&&n(),i}catch(r){throw n(),r}}setupSiteApp(t){var e=this.apps[t.id],n=()=>{var o;!e.errored&&this.gl.length&&(Et.info("Processing "+this.gl.length+" events for site app with id "+t.id),this.gl.forEach((a=>this.xl((()=>e.processEvent==null?void 0:e.processEvent(a))))),e.processedBuffer=!0),Object.values(this.apps).every((a=>a.processedBuffer||a.errored))&&((o=this.yl)==null||o.call(this))},i=!1,r=o=>{e.errored=!o,e.loaded=!0,Et.info("Site app with id "+t.id+" "+(o?"loaded":"errored")),i&&n()};try{var s=this.xl((o=>t.init({posthog:this._instance,callback(a){o(),r(a)}})),!1).processEvent;s&&(e.processEvent=s),i=!0}catch(o){Et.error(uu+t.id,o),r(!1)}if(i&&e.loaded)try{n()}catch(o){Et.error("Error while processing buffered events PostHog app with config id "+t.id,o),e.errored=!0}}Sl(){var t=this.siteAppLoaders||[];for(var e of t)this.apps[e.id]={id:e.id,loaded:!1,errored:!1,processedBuffer:!1};for(var n of t)this.setupSiteApp(n)}Cl(t){var e=this;if(Object.keys(this.apps).length!==0){var n=this.globalsForEvent(t),i=function(s){try{e.xl((()=>s.processEvent==null?void 0:s.processEvent(n)))}catch(o){Et.error("Error while processing event "+t.event+" for site app "+s.id,o)}};for(var r of Object.values(this.apps))i(r)}}onRemoteConfig(t){var e,n,i,r=this;if((e=this.siteAppLoaders)!=null&&e.length)return this.isEnabled?(this.Sl(),void this._instance.on("eventCaptured",(l=>this.Cl(l)))):void Et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((n=this.yl)==null||n.call(this),t.ok){var s=t.config;if((i=s.siteApps)!=null&&i.length)if(this.isEnabled){var o=function(){var l,u=a.id,c=a.url;B["__$$ph_site_app_"+u]=r._instance,(l=B.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(r._instance,c,(d=>{if(d)return Et.error(uu+u,d)}))};for(var a of s.siteApps)o()}else Et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},Km={tracingHeaders:class{constructor(t){this.Ml=void 0,this.Tl=void 0,this.El=void 0,this.Uo=()=>{var e,n,i=this.Il();i?(C(this.Ml)&&(this.Ml=(e=B.__PosthogExtensions__)==null||(e=e.tracingHeadersPatchFns)==null?void 0:e._patchXHR(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager)),C(this.Tl)&&(this.Tl=(n=B.__PosthogExtensions__)==null||(n=n.tracingHeadersPatchFns)==null?void 0:n._patchFetch(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager))):this.Qo()},this._instance=t}initialize(){this.startIfEnabledOrStop()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",(i=>{if(i)return Mm.error("failed to load script",i);t()}))}Pl(){var t,e;return(t=(e=this._instance.config.tracing_headers)!==null&&e!==void 0?e:this._instance.config.addTracingHeaders)!==null&&t!==void 0?t:this._instance.config.__add_tracing_headers}Il(){var t=this.Pl();return U(t)?(U(this.El)?this.El.splice(0,this.El.length,...t):this.El=[...t],t.length>0?this.El:void 0):(U(this.El)&&this.El.splice(0),this.El=t||void 0,this.El)}Qo(){var t,e;(t=this.Ml)==null||t.call(this),(e=this.Tl)==null||e.call(this),this.Ml=void 0,this.Tl=void 0}startIfEnabledOrStop(){this.Il()?this.ai(this.Uo):this.Qo()}}},Ym=I({surveys:class{get Ne(){return this._instance.config}constructor(t){this.Rl=void 0,this._surveyManager=null,this.Al=!1,this.Fl=[],this.Ll=null,this.Ol=null,this._instance=t,this._surveyEventReceiver=null}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this.Ne.disable_surveys){if(!t.ok)return Q.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(H(e))return Q.warn("Flags not loaded yet. Not loading surveys.");var n=U(e);this.Rl=n?e.length>0:e,Q.info("flags response received, isSurveysEnabled: "+this.Rl),this.loadIfEnabled()}}reset(){try{var t;(t=this._surveyEventReceiver)==null||t.reset(),localStorage.removeItem("lastSeenSurveyDate");for(var e=[],n=0;nlocalStorage.removeItem(r)))}catch{}}loadIfEnabled(){if(!this._surveyManager)if(this.Al)Q.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)Q.info(du);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())Q.info("Not loading surveys in cookieless mode without consent.");else{var t=B?.__PosthogExtensions__;if(t){if(!C(this.Rl)||this.Ne.advanced_enable_surveys){var e=this.Rl||this.Ne.advanced_enable_surveys;this.Al=!0;try{var n=t.generateSurveys;if(n)return void this.Dl(n,e);var i=t.loadExternalDependency;if(!i)return void this.$l(al);i(this._instance,"surveys",(r=>{r||!t.generateSurveys?this.$l("Could not load surveys script",r):this.Dl(t.generateSurveys,e)}))}catch(r){throw this.$l("Error initializing surveys",r),r}finally{this.Al=!1}}}else Q.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new Dm(this._instance),Q.info("Surveys loaded successfully"),this.Nl({isLoaded:!0})}$l(t,e){Q.error(t,e),this.Nl({isLoaded:!1,error:t})}onSurveysLoaded(t){return this.Fl.push(t),this._surveyManager&&this.Nl({isLoaded:!0}),()=>{this.Fl=this.Fl.filter((e=>e!==t))}}getSurveys(t,e){if(e===void 0&&(e=!1),this.Ne.disable_surveys)return Q.info(du),t([]);var n,i=this._instance.get_property(la);if(i&&!e)return t(i,{isLoaded:!0}),void(this.ql()&&this.getSurveys((()=>{}),!0));typeof Promise<"u"&&this.Ll?this.Ll.then((r=>t(r.surveys,r.context))):(typeof Promise<"u"&&(this.Ll=new Promise((r=>{n=r}))),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this.Ne.token),method:"GET",timestampMode:"query",timeout:this.Ne.surveys_request_timeout_ms,callback:r=>{var s;this.Ll=null;var o=r.statusCode;if(o!==200||!r.json){var a="Surveys API could not be loaded, status: "+o;o!==0?Q.error(a):r.error||Q.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(n==null||n({surveys:[],context:l}))}this.Ol=null;var u,c=r.json.surveys||[],d=c.filter((h=>(function(p){return!(!p.start_date||p.end_date)})(h)&&(Hf(h)||(function(p){var g;return!((g=p.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(h))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(s=this._instance.persistence)==null||s.register({[la]:c,[Xr]:Date.now()});var f={isLoaded:!0};t(c,f),n?.({surveys:c,context:f})}}))}ql(){return this.jl()&&!this.Ll&&!this.Bl()}jl(){var t=this._instance.get_property(Xr);return ke(t)&&Date.now()-t>3e5}Bl(){return ke(this.Ol)&&3e5>Date.now()-this.Ol}markSurveyAsSeen(t,e){var n,i={id:t,current_iteration:(n=e?.iteration)!==null&&n!==void 0?n:null};qf(i);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}}Nl(t){for(var e of this.Fl)try{if(!t.isLoaded)return e([],t);this.getSurveys(e)}catch(n){Q.error("Error in survey callback",n)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!H(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);Q.warn("init was not called")}Hl(t){var e=null;return this.getSurveys((n=>{var i;e=(i=n.find((r=>r.id===t)))!==null&&i!==void 0?i:null})),e}Ul(t){if(H(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(H(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(H(this._surveyManager))return Q.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 H(this._surveyManager)?(Q.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Ir})):new Promise((n=>{this.getSurveys((i=>{var r,s=(r=i.find((a=>a.id===t)))!==null&&r!==void 0?r:null;if(s){var o=this.zl(s);n({visible:o.eligible,disabledReason:o.reason})}else n({visible:!1,disabledReason:"Survey not found"})}),e)}))}renderSurvey(t,e,n){var i;if(H(this._surveyManager))Q.warn("init was not called");else{var r=typeof t=="string"?this.Hl(t):t;if(r!=null&&r.id)if(bm.includes(r.type)){var s=P?.querySelector(e);if(s)return(i=r.appearance)!=null&&i.surveyPopupDelaySeconds?(Q.info("Rendering survey "+r.id+" with delay of "+r.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;Q.info("Rendering survey "+r.id+" with delay of "+((o=r.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(a=this._surveyManager)==null||a.renderSurvey(r,s,n),Q.info("Survey "+r.id+" rendered")}),1e3*r.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(r,s,n);Q.warn("Survey element not found")}else Q.warn("Surveys of type "+r.type+" cannot be rendered in the app");else Q.warn("Survey not found")}}displaySurvey(t,e){var n;if(H(this._surveyManager))Q.warn("init was not called");else{var i=this.Hl(t);if(i){var r=i;if((n=i.appearance)!=null&&n.surveyPopupDelaySeconds&&e.ignoreDelay&&(r=I({},i,{appearance:I({},i.appearance,{surveyPopupDelaySeconds:0})})),e.displayType!==_a.Popover&&e.initialResponses&&Q.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),e.ignoreConditions===!1){var s=this.Ul(i);if(!s.eligible)return void Q.warn("Survey is not eligible to be displayed: ",s.reason)}e.displayType!==_a.Inline?this._surveyManager.handlePopoverSurvey(r,e):this.renderSurvey(r,e.selector,e.properties)}else Q.warn("Survey not found")}}cancelPendingSurvey(t){H(this._surveyManager)?Q.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},Cs),Jm={toolbar:class{constructor(t){this.instance=t}Wl(t){B.ph_toolbar_state=t}Vl(){var t;return(t=B.ph_toolbar_state)!==null&&t!==void 0?t:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(t,e,n){if(t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),ga(this.instance.config)||!w||!P)return!1;t=t??w.location,n=n??w.history;try{if(!e){try{w.localStorage.setItem("test","test"),w.localStorage.removeItem("test")}catch{return!1}e=w?.localStorage}var i,r=jm||os(t.hash,"__posthog")||os(t.hash,"state"),s=r?Pc((()=>JSON.parse(atob(decodeURIComponent(r)))))||Pc((()=>JSON.parse(decodeURIComponent(r)))):null;return s&&s.action==="ph_authorize"?((i=s).source="url",i&&Object.keys(i).length>0&&(s.desiredHash?t.hash=s.desiredHash:n?n.replaceState(n.state,"",t.pathname+t.search):t.hash="")):((i=JSON.parse(e.getItem(fu)||"{}")).source="localstorage",delete i.userIntent),!(!i.token||this.instance.config.token!==i.token||(this.loadToolbar(i),0))}catch{return!1}}Zl(t){var e=B.ph_load_toolbar||B.ph_load_editor;!H(e)&&De(e)?e(t,this.instance):hu.warn("No toolbar load function found")}loadToolbar(t){var e=!(P==null||!P.getElementById(sf));if(!w||e)return!1;var n=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,i=I({token:this.instance.config.token},t,{apiURL:this.instance.requestRouter.endpointFor("ui")},n?{instrument:!1}:{});if(w.localStorage.setItem(fu,JSON.stringify(I({},i,{source:void 0}))),this.Vl()===2)this.Zl(i);else if(this.Vl()===0){var r;this.Wl(1),(r=B.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"toolbar",(s=>{if(s)return hu.error("[Toolbar] Failed to load",s),void this.Wl(0);this.Wl(2),this.Zl(i)})),ve(w,"turbolinks:load",(()=>{this.Wl(0),this.loadToolbar(i)}))}return!0}Gl(t){return this.loadToolbar(t)}maybeLoadEditor(t,e,n){return t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),this.maybeLoadToolbar(t,e,n)}}},Zm=I({experiments:Me},Cs),Xm={conversations:class{constructor(t){this.Ql=void 0,this._conversationsManager=null,this.Kl=!1,this.Jl=null,this.Yl=!1,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this._instance.config.disable_conversations&&(this.Xl=t.ok,t.ok)){var e=t.config.conversations;H(e)||(mt(e)?this.Ql=e:(this.Ql=e.enabled,this.Jl=e),this.loadIfEnabled())}}reset(){var t;(t=this._conversationsManager)==null||t.reset(),this._conversationsManager=null,this.Ql=void 0,this.Jl=null,this.Xl=void 0,this.Yl=!1}loadIfEnabled(){if(!(this._conversationsManager||this.Kl||this._instance.config.disable_conversations||ga(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=B?.__PosthogExtensions__;if(t&&!C(this.Ql)&&this.Ql)if(this.Jl&&this.Jl.token){this.Kl=!0;try{var e=t.initConversations;if(e)return this.tu(e),void(this.Kl=!1);var n=t.loadExternalDependency;if(!n)return void this.eu(al);n(this._instance,"conversations",(i=>{i||!t.initConversations?this.eu("Could not load conversations script",i):this.tu(t.initConversations),this.Kl=!1}))}catch(i){this.eu("Error initializing conversations",i),this.Kl=!1}}else st.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,st.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else st.error("Cannot complete initialization: remote config is null")}eu(t,e){st.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():st.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!Ke(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":ga(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.Xl===!1?"remote_config_failed":C(this.Ql)?this.Xl?"disabled_in_project":"remote_config_pending":this.Ql?H(this.Jl)||!this.Jl.token?"missing_token":B!=null&&B.__PosthogExtensions__?this.Kl?"initializing":this.Yl?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.isVisible())!==null&&t!==void 0&&t}sendMessage(t,e,n){var i=this;return se((function*(){return i._conversationsManager?i._conversationsManager.sendMessage(t,e,n):(st.warn(En),null)}))()}getMessages(t,e){var n=this;return se((function*(){return n._conversationsManager?n._conversationsManager.getMessages(t,e):(st.warn(En),null)}))()}markAsRead(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(st.warn(En),null)}))()}getTickets(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(st.warn(En),null)}))()}requestRestoreLink(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(st.warn(En),null)}))()}restoreFromToken(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(st.warn(En),null)}))()}restoreFromUrlToken(){var t=this;return se((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(st.warn(En),null)}))()}getCurrentTicketId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getCurrentTicketId())!==null&&t!==void 0?t:null}getWidgetSessionId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getWidgetSessionId())!==null&&t!==void 0?t:null}Xn(){var t;(t=this._conversationsManager)==null||t.setIdentity()}ts(){var t;(t=this._conversationsManager)==null||t.clearIdentity()}}},Qm={logs:class{constructor(t){var e,n=this;this.iu=!1,this.ru=!1,this.rt=pe("[logs]"),this.nu=I({},this.rt,{error(){for(var i=arguments.length,r=new Array(i),s=0;i>s;s++)r[s]=arguments[s];r.some(bu)||n.rt.error(...r)}}),this.tr=[],this.su=[],this.Sa=0,this.au=()=>{var i,r;this.Sa=0,(i=this.ou)==null||i.onReconnect(),(r=this.lu)==null||r.onReconnect()},this._instance=t,this._instance&&(e=this._instance.config.logs)!=null&&e.captureConsoleLogs&&(this.iu=!0),w&&ve(w,"online",this.au)}uu(t,e,n,i){var r,s=(function(o,a){var l,u,c,d,f,h,p,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,v=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,E=C(v)?Math.max(m,2048):Math.max(m,v),S=o?.resourceAttributes;return{serviceName:(d=(f=S?.["service.name"])!==null&&f!==void 0?f:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(h=S?.["service.version"])!==null&&h!==void 0?h:o?.serviceVersion,environment:(p=S?.["deployment.environment"])!==null&&p!==void 0?p:o?.environment,resourceAttributes:S,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:E,maxBatchRecordsPerPost:100,rateCapWindowMs:g,maxLogsPerInterval:v,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}})((r=this._instance)==null||(r=r.config)==null?void 0:r.logs,n);return[new ig(this.hu(t,e),s,this.nu,(()=>this.du()),(o=>o()),void 0,i),s]}vu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.ou||this.cu!==e){var n;(n=this.ou)==null||n.reset(),this.cu=e;var i=this.uu((()=>this.tr),(r=>{this.tr=r}));this.ou=i[0],this.fu=i[1]}return this.ou}pu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.lu||this.gu!==e){var n;(n=this.lu)==null||n.reset(),this.gu=e;var i=this.uu((()=>this.su),(r=>{this.su=r}),{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},wu);this.lu=i[0],this.mu=i[1]}return this.lu}initialize(){this.loadIfEnabled()}onRemoteConfig(t){var e;if(t.ok){var n=(e=t.config.logs)==null?void 0:e.captureConsoleLogs;!H(n)&&n&&(this.iu=!0,this.loadIfEnabled())}}reset(){var t,e;this.tr=[],(t=this.ou)==null||t.reset(),this.su=[],(e=this.lu)==null||e.reset(),this.Sa=0}captureLog(t){this.vu().captureLog(t)}he(t){this.pu().captureLog(t)}get logger(){return this.yu||(this.yu={trace:(t,e)=>this.captureLog({body:t,level:"trace",attributes:e}),debug:(t,e)=>this.captureLog({body:t,level:"debug",attributes:e}),info:(t,e)=>this.captureLog({body:t,level:"info",attributes:e}),warn:(t,e)=>this.captureLog({body:t,level:"warn",attributes:e}),error:(t,e)=>this.captureLog({body:t,level:"error",attributes:e}),fatal:(t,e)=>this.captureLog({body:t,level:"fatal",attributes:e})}),this.yu}flushLogs(t){t?this.bu(t):(this.ou&&this.ou.flush().catch((e=>this._u(e))),this.lu&&this.lu.flush().catch((e=>this._u(e))))}_u(t){bu(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=B?.__PosthogExtensions__;if(t){var e=t.loadExternalDependency;e?e(this._instance,"logs",(n=>{var i;n||(i=t.logs)==null||!i.initializeLogs?this.rt.error("Could not load logs script",n):(t.logs.initializeLogs(this._instance),this.ru=!0)})):this.rt.error(al)}else this.rt.error("PostHog Extensions not found.")}}hu(t,e){var n=this._instance;return{get isDisabled(){return!1},get optedOut(){return!n.is_capturing()},getPersistedProperty:i=>i===Ut.LogsQueue?t():void 0,setPersistedProperty(i,r){var s;i===Ut.LogsQueue&&e((s=r)!==null&&s!==void 0?s:[])},Ot:i=>this.Ot(i),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Ot(t){return new Promise((e=>{if(vf(this.Sa,3))e({kind:"fatal",error:Do(void 0,"logs endpoint is unreachable, dropping batch")});else{var n=!1,i=s=>{n||(n=!0,clearTimeout(r),e(s))},r=setTimeout((()=>{this.rt.warn("Logs request timed out before receiving a response"),i({kind:"retry-later",error:Do(void 0,"logs request timed out")})}),9e4);this._instance._send_request({method:"POST",url:this.wu(),data:t,compression:"best-available",batchKey:"logs",fireCallbackOnDrop:!0,callback:s=>{var o=s.statusCode;if(this.ku(o),o>=200&&300>o)i({kind:"ok"});else if(o===413)i({kind:"too-large"});else if(o!==0&&o!==429&&500>o)i({kind:"fatal",error:new Error("logs request failed with status "+o)});else{var a;o===0?(s.error||this.rt.warn("Logs request failed before receiving an HTTP response"),i({kind:"retry-later",error:Do(s.error,"logs request failed before receiving an HTTP response")})):i({kind:"retry-later",error:(a=s.error)!==null&&a!==void 0?a:new Error("logs request failed with status "+o)})}}})}}))}ku(t){(t!==0||this._instance.__loaded)&&(this.Sa=_f(t,this.Sa,3,(()=>this.rt.warn("Log requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped sending logs; will try again when connectivity changes."))))}bu(t){this.tr.length>0&&this.xu(t,this.tr,this.fu,ne.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,wu,(e=>{this.su=e}))}xu(t,e,n,i,r){if(e.length!==0){var s=e.map((a=>a.record));r([]);var o=Ud(s,jd(n,ne.LIB_NAME,ne.LIB_VERSION),i,ne.LIB_VERSION);this._instance._send_request({method:"POST",url:this.wu(),data:o,compression:"best-available",batchKey:"logs",transport:t})}}wu(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}du(){var t,e={};if(e.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var n=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.windowId,r=n.sessionStartTimestamp,s=n.lastActivityTimestamp;e.sessionId=n.sessionId,e.windowId=i,H(r)||(e.sessionStartTimestamp=r),H(s)||(e.lastActivityTimestamp=s)}if(B!=null&&(t=B.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?fn(B.location.href):B.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},ev={metrics:class{constructor(t){this.rt=pe("[metrics]"),this._instance=t}initialize(){}vu(){var t,e,n=(t=this._instance)==null||(t=t.config)==null?void 0:t.metrics;return this.ou&&this.cu===n||((e=this.ou)==null||e.reset(),this.cu=n,this.ou=new rg(this.hu(),(function(i){var r,s,o,a,l,u=i?.resourceAttributes;return{serviceName:(r=u?.["service.name"])!==null&&r!==void 0?r:i?.serviceName,serviceVersion:(s=u?.["service.version"])!==null&&s!==void 0?s:i?.serviceVersion,environment:(o=u?.["deployment.environment"])!==null&&o!==void 0?o:i?.environment,resourceAttributes:u,beforeSend:i?.beforeSend,flushIntervalMs:(a=i?.flushIntervalMs)!==null&&a!==void 0?a:1e4,maxSeriesPerFlush:(l=i?.maxSeriesPerFlush)!==null&&l!==void 0?l:1e3}})(n),this.rt)),this.ou}count(t,e,n){e===void 0&&(e=1),this.vu().count(t,e,n)}gauge(t,e,n){this.vu().gauge(t,e,n)}histogram(t,e,n){this.vu().histogram(t,e,n)}flush(t){if(!this.ou)return Promise.resolve();if(t){var e=this.ou.drainWindow();return e&&this.Jt(e,t),Promise.resolve()}return this.ou.flush().catch((n=>this.rt.error("PostHog metrics flush failed:",n)))}reset(){var t;(t=this.ou)==null||t.reset()}hu(){var t=this._instance,e=this;return{get isDisabled(){return!1},get optedOut(){return!t.is_capturing()},Jt:n=>e.Jt(n),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Jt(t,e){return new Promise((n=>{var i=!1,r=o=>{i||(i=!0,clearTimeout(s),n(o))},s=setTimeout((()=>r({kind:"retry-later",error:new Error("metrics request timed out")})),9e4);this._instance._send_request(I({method:"POST",url:this.Su(),data:t,compression:"best-available",batchKey:"metrics"},e&&{transport:e},{fireCallbackOnDrop:!0,callback(o){var a=o.statusCode;if(a>=200&&300>a)r({kind:"ok"});else if(a===413)r({kind:"too-large"});else if(a!==0&&a!==429&&500>a)r({kind:"fatal",error:new Error("metrics request failed with status "+a)});else{var l;r({kind:"retry-later",error:(l=o.error)!==null&&l!==void 0?l:new Error("metrics request failed with status "+a)})}}}))}))}Su(){return this._instance.requestRouter.endpointFor("api","/i/v1/metrics")+"?token="+encodeURIComponent(this._instance.config.token)}}},tv=I({},Cs,Wm,qm,zm,Vm,Gm,Ym,Km,Jm,Zm,Xm,Qm,ev);Je.__defaultExtensionClasses=I({},tv);(function(){ne.SDK_DIST_CHANNEL="npm";var t=Wi[Gn]=new Je;return(function(){function e(){e.done||(e.done=!0,Vf=!1,ie(Wi,(function(n){n._dom_loaded()})))}P!=null&&P.addEventListener?P.readyState==="complete"?e():ve(P,"DOMContentLoaded",e,{capture:!1}):w&&A.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const nv=["a[href]","button:not([disabled])","input:not([disabled]):not([type='hidden'])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(",");let pt=null,ka=null,Kf="";const Ca=new Map;function Yf(t){return[...t.querySelectorAll(nv)].filter(e=>!e.hidden&&e.getAttribute("aria-hidden")!=="true"&&e.getClientRects().length>0)}function iv(t){for(const e of document.body.children)e===t||e.tagName==="SCRIPT"||(Ca.set(e,{inert:e.inert,ariaHidden:e.getAttribute("aria-hidden")}),e.inert=!0,e.setAttribute("aria-hidden","true"))}function rv(){for(const[t,e]of Ca)t.inert=e.inert,e.ariaHidden===null?t.removeAttribute("aria-hidden"):t.setAttribute("aria-hidden",e.ariaHidden);Ca.clear()}function Jf(t){return t?.dataset.modalDismissible!=="false"&&t?.getAttribute("aria-busy")!=="true"}function He(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n)return!1;pt&&pt!==n&&We(pt,{restoreFocus:!1,force:!0}),ka=e.trigger||document.activeElement,pt=n,Kf=document.body.style.overflow,iv(n),document.body.style.overflow="hidden",n.classList.add("open"),n.setAttribute("aria-hidden","false");const i=n.querySelector(".modal-content");i&&(i.style.transform="scale(1) translateY(0)");const r=()=>{if(pt!==n)return;((e.initialFocus?n.querySelector(e.initialFocus):n.querySelector("[data-modal-initial-focus]"))||Yf(n)[0]||n.querySelector(".modal-content")||n).focus({preventScroll:!0})};return requestAnimationFrame(r),setTimeout(r,260),!0}function We(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n||!e.force&&!Jf(n))return!1;n.classList.remove("open"),n.setAttribute("aria-hidden","true"),rv(),document.body.style.overflow=Kf,pt=null;const i=ka;return ka=null,e.restoreFocus!==!1&&i?.isConnected&&i.focus({preventScroll:!0}),!0}function Eu(t,e,n="Operation in progress"){const i=typeof t=="string"?document.getElementById(t):t;i&&(i.dataset.modalDismissible=e?"false":"true",i.setAttribute("aria-busy",String(!!e)),e?i.setAttribute("aria-label",n):i.removeAttribute("aria-label"))}function sv(t){if(!Jf(t))return;const e=t.dataset.modalCloseHandler;e&&typeof window[e]=="function"?window[e]():We(t)}document.addEventListener("keydown",t=>{if(!pt)return;if(t.key==="Escape"){t.preventDefault(),t.stopImmediatePropagation(),sv(pt);return}if(t.key!=="Tab"){t.stopPropagation();return}const e=Yf(pt);if(!e.length){t.preventDefault(),(pt.querySelector(".modal-content")||pt).focus();return}const n=e[0],i=e[e.length-1];t.shiftKey&&document.activeElement===n?(t.preventDefault(),i.focus()):!t.shiftKey&&document.activeElement===i&&(t.preventDefault(),n.focus())},!0);function ov(){document.querySelectorAll(".modal-overlay").forEach(t=>{t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-hidden",t.classList.contains("open")?"false":"true");const e=t.querySelector(".modal-content");e&&!e.hasAttribute("tabindex")&&(e.tabIndex=-1);const n=t.querySelector("h1, h2, h3");n&&(n.id||(n.id=`${t.id}-title`),t.setAttribute("aria-labelledby",n.id)),t.querySelectorAll(".modal-close").forEach(i=>{i.getAttribute("aria-label")||i.setAttribute("aria-label","Close dialog")})})}const gl=Object.freeze({free:"Free",professional:"Pro",power:"Power"}),av=Object.freeze({free:2,professional:50,power:2e3}),lv="(contact us)",cv=Object.freeze({free:Object.freeze(["2 generations/month","Gemini model only","Code Review"]),professional:Object.freeze(["50 generations/month","All models","Code Regeneration","Code Review"]),power:Object.freeze(["2000 generations/month","All models","Code Regeneration","Bring your own key (BYOK)","Code Review","All models + early access",`API & MCP access ${lv}`])}),Zf="CodeFile",Xf="GeneratedCode",uv={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function ln(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Aa(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function dv(t={},e=0){const n=Aa(t.artifactType||t.type||Zf),i=Aa(t.artifactName||t.name||t.fileName||`${Xf}-${e+1}`);return`${n||"artifact"}-${i||e+1}`}function Qf(t={},e=0){const n=ln(t),i=n.artifactType||n.type||Zf,r=n.artifactName||n.name||Xf;let s=n.fileName||r;return s.endsWith(".dart")||(s+=".dart"),{id:Aa(n.id)||dv({...n,artifactType:i,artifactName:r,fileName:s},e),artifactType:i,artifactName:r,fileName:s,deployPath:n.deployPath||"",description:n.description||"",code:n.code||n.content||"",dependencies:eh(n.dependencies),imports:Array.isArray(n.imports)?n.imports:[],publicApi:Array.isArray(n.publicApi)?n.publicApi:[],relationships:th(n.relationships),deployStatus:n.deployStatus||"pending",review:n.review||null,metadata:ln(n.metadata),codeType:n.codeType||uv[i]||"O"}}function eh(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const n=ln(e),i=n.name||n.package;return i?{name:i,version:n.version||null,versionRequired:!!(n.versionRequired||n.required),inferred:!!n.inferred,...n.reason?{reason:n.reason}:{}}:null}).filter(Boolean):Object.entries(ln(t)).map(([e,n])=>({name:e,version:n||null,inferred:!1})):[]}function th(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const n=ln(e);return!n.from&&!n.to?null:{from:n.from||null,to:n.to||null,type:n.type||"uses",description:n.description||""}}).filter(Boolean):[]}function Pa(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;try{return JSON.parse(e)}catch{const n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(!n)return null;try{return JSON.parse(n[1].trim())}catch{return null}}}function Qi(t,e={}){const n=[],i=typeof t=="string"?Pa(t):t,s=ln(i||{});!i&&typeof t=="string"&&n.push("Structured bundle parse failed; using legacy single-artifact fallback.");const o=Array.isArray(s.artifacts)?s.artifacts:[{artifactType:s.artifactType||e.artifactType,artifactName:s.artifactName||e.artifactName,fileName:s.fileName||e.fileName,description:s.description,code:s.code||e.code||(typeof t=="string"?t:""),dependencies:s.dependencies||e.dependencies,relationships:s.relationships||e.relationships}];o.forEach((d,f)=>{!d?.artifactType&&!d?.type&&n.push(`Artifact ${f+1} has no artifactType; it will deploy as a standalone code file under lib/custom_code/ root.`)});const a=o.map((d,f)=>Qf(d,f)),l=new Map(o.map((d,f)=>[ln(d).id,a[f]?.id]).filter(([d,f])=>d&&f)),u=d=>l.get(d)||d,c=th(s.relationships||e.relationships).map(d=>({...d,from:d.from?u(d.from):d.from,to:d.to?u(d.to):d.to}));return{schemaVersion:s.schemaVersion||e.schemaVersion||null,id:s.id||e.id||"bundle-current",title:s.title||s.name||e.title||"Generated artifact bundle",description:s.description||e.description||"",artifacts:a,dependencies:eh(s.dependencies||e.dependencies),relationships:c,deployOrder:Array.isArray(s.deployOrder)?s.deployOrder.map(u):a.map(d=>d.id),warnings:[...n,...Array.isArray(s.warnings)?s.warnings:[]],metadata:ln(s.metadata)}}function oi(t){return Qi(t).artifacts[0]||Qf()}function Zt(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function ai(t){return JSON.stringify(t,null,2)}function fv(t){return ai({task:"architect",userRequest:String(t??"")})}function hv(t){const e=Zt(t);return e&&typeof e=="object"&&typeof e.task=="string"?ai(e):ai({task:"generate_bundle",bundleSpec:e})}function pv(t){return ai({task:"review_bundle",generatedBundle:Zt(t),outputRequirements:{bundleReview:["status","score","summary","manualActions","findings"],scoreRange:[0,100],eachArtifact:["id","review.status","review.findings"],manualActions:{definition:"Setup the developer must perform by hand in the FlutterFlow editor that FlutterFlow will NOT do for them.",exclude:["creating the Custom Action, Widget or Code File itself - deploying the code creates it","declaring parameters or return values FlutterFlow derives from the function signature","anything that resolves as a side effect of using the action or widget in the editor","generic advice such as testing, reviewing or rebuilding the app"],preferEmpty:"Return an empty array when nothing qualifies - an empty list is the expected result for most bundles."}}})}function ml(t,e=null){const n={stage:t};return e!=null&&(n.bundle=Zt(e)),n}function gv({bundleSpec:t,artifactBundle:e,bundleReview:n,artifactId:i,userFeedback:r}){return ai({task:"regenerate_artifact",artifactId:i,bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(r)})}function nh({bundleSpec:t,artifactBundle:e,bundleReview:n,userFeedback:i}){return ai({task:"regenerate_bundle",bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(i??"")})}const Su={csam:"child-safety content",dangerous:"dangerous content",harassment:"harassment",hate_speech:"hate speech",maliciousUrls:"a potentially malicious URL",malicious_uris:"a potentially malicious URL",pi_and_jailbreak:"prompt-injection or jailbreak instructions",promptInjection:"prompt-injection or jailbreak instructions",rai:"restricted content",sdp:"sensitive personal data",sexually_explicit:"sexually explicit content",virus_scan:"potentially malicious file content"},mv=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function et(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function vv(t){return et(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||et(t.filterSummary)||et(t.filterResults):!1}function ih(t,e=0){if(!et(t)||e>3)return null;if(vv(t))return t;for(const n of mv){const i=t[n];if(et(i)){const r=ih(i,e+1);if(r)return r}}return null}function ds(t){return Array.isArray(t)?t.some(ds):et(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(ds):!1}function Fa(t){return Array.isArray(t)?t.some(Fa):et(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(Fa):!1}function rh(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function _v(t,e){if(et(t))for(const[n,i]of Object.entries(t)){if(!et(i))continue;const r=et(i.categories)?i.categories:{},s=Object.entries(r).filter(([,o])=>et(o)&&o.matched===!0).map(([o])=>o);s.length>0?s.forEach(o=>e.add(o)):i.matched===!0&&e.add(rh(n))}}function yv(t,e){if(!t)return;const n=Array.isArray(t)?t.flatMap(i=>et(i)?Object.entries(i):[]):Object.entries(t);for(const[i,r]of n){if(!ds(r))continue;const s=rh(i),o=r?.raiFilterResult?.raiFilterTypeResults||(s==="rai"?r?.raiFilterTypeResults:null),a=et(o)?Object.entries(o).filter(([,l])=>ds(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(s)}}function wv(t){return Su[t]?Su[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function xu(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 bv(t){const e=ih(t);if(!e)return null;const n=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);_v(e.filterSummary,n),yv(e.filterResults,n);const i=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||n.size>0,r=e.invocationResult||null,s=Fa(e.filterSummary||e.filterResults);return!i&&!s&&!["PARTIAL","FAILURE"].includes(r)?null:{kind:i?"blocked":"unavailable",invocationResult:r,matchedFilters:[...n]}}function Ev(t,e){const n=bv(t);if(!n)return null;const i=[...new Set(n.matchedFilters.map(wv))],r=n.kind==="blocked",s=new Error(r?`Safety screening blocked this pipeline step for ${xu(i)}.`:"Safety screening could not be completed. Please try again.");return s.name="ModelArmorError",s.code=r?"MODEL_ARMOR_BLOCKED":"MODEL_ARMOR_UNAVAILABLE",s.isModelArmor=!0,s.pipelineStep=e,s.userTitle=r?"Request blocked for safety":"Safety check unavailable",s.userMessage=r?`The safety check detected ${xu(i)}. Edit your request to remove or rephrase the flagged content, then run the pipeline again.`:"The safety service did not finish all of its checks. Please wait a moment and run the pipeline again.",s.retryExplanation=r?"Trying another model would not change this safety decision.":"A fallback model was not attempted because safety screening must complete first.",s.matchedFilters=n.matchedFilters,s}function Sv(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function Iu(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,n=[];for(const i of Sv(t).split(` -`)){if(!/^[A-Za-z_$]/.test(i)||e.test(i))continue;const r=i.match(/^[\w$<>,?\s[\]]+?\s([a-zA-Z_$][\w$]*)\s*\(/);r&&n.push(r[1])}return n}function vl(t,e){const n=t.replace(/\.dart$/,"");if(e==="W")return n.replace(/(^|_)(\w)/g,(i,r,s)=>s.toUpperCase());if(e==="A"){const i=n.replace(/(^|_)(\w)/g,(r,s,o)=>o.toUpperCase());return i.charAt(0).toLowerCase()+i.slice(1)}return e==="F"?"CustomFunctions":e==="C"?t.endsWith(".dart")?t:`${t}.dart`:n}async function ku(t){const e=new TextEncoder().encode(String(t||"")),n=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n),i=>i.toString(16).padStart(2,"0")).join("")}async function xv(t,e=new Map){const n={},i=new Set;for(const[o,a]of t.entries()){if(a.type==="D"||a.type==="O")continue;const l=vl(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await ku(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await ku(c)),n[o]=u,a.type==="F"){const d=Iu(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(h=>i.add(h))}}const r=new Set(Iu(e.get("lib/flutter_flow/custom_functions.dart")||"")),s={functions_to_rename:[],functions_to_delete:[],functions_to_add:Array.from(i).filter(o=>!r.has(o))};return{fileMapContents:JSON.stringify(n),functionsMapContents:JSON.stringify(s)}}const Iv=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),Cu={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},kv=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),Cv=["Struct","Record"],Av=[{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=>jo(t).some(e=>/\brequired\s+this\.\w+/.test(e)),pos:"class W extends StatefulWidget { const W({required this.value}); final double value; }",neg:`class _P { const _P({required this.t}); final double t; } +(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const s of r)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function n(r){const s={};return r.integrity&&(s.integrity=r.integrity),r.referrerPolicy&&(s.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?s.credentials="include":r.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function i(r){if(r.ep)return;r.ep=!0;const s=n(r);fetch(r.href,s)}})();var w=typeof window<"u"?window:void 0,Le=typeof globalThis<"u"?globalThis:w,Ue=Le?.navigator,P=Le?.document,me=Le?.location,Za=Le?.fetch,qo=Le!=null&&Le.XMLHttpRequest&&"withCredentials"in new Le.XMLHttpRequest?Le.XMLHttpRequest:void 0,uc=Le?.AbortController,$p=Le?.CompressionStream,Ve=Ue?.userAgent;function ud(){return!(!w||w.navigator.onLine===!1)}var vi=typeof globalThis<"u"?globalThis:w;vi&&typeof self>"u"&&(vi.self=vi),vi&&typeof File>"u"&&(vi.File=function(){});var B=w??{},ne={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function dc(t,e,n,i,r,s,o){try{var a=t[s](o),l=a.value}catch(u){return void n(u)}a.done?e(l):Promise.resolve(l).then(i,r)}function se(t){return function(){var e=this,n=arguments;return new Promise((function(i,r){var s=t.apply(e,n);function o(l){dc(s,i,r,o,a,"next",l)}function a(l){dc(s,i,r,o,a,"throw",l)}o(void 0)}))}}function I(){return I=Object.assign?Object.assign.bind():function(t){for(var e=1;arguments.length>e;e++){var n=arguments[e];for(var i in n)({}).hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},I.apply(null,arguments)}function dd(t,e){if(t==null)return{};var n={};for(var i in t)if({}.hasOwnProperty.call(t,i)){if(e.indexOf(i)!==-1)continue;n[i]=t[i]}return n}var fc=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function hc(t){return typeof t=="string"||t}function pc(t){return typeof t=="string"?t:void 0}var _i,Mp=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],Ut=(function(t){return t.AnonymousId="anonymous_id",t.DistinctId="distinct_id",t.Props="props",t.EnablePersonProcessing="enable_person_processing",t.PersonMode="person_mode",t.FeatureFlagDetails="feature_flag_details",t.FeatureFlags="feature_flags",t.FeatureFlagPayloads="feature_flag_payloads",t.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",t.BootstrapFeatureFlags="bootstrap_feature_flags",t.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",t.OverrideFeatureFlags="override_feature_flags",t.Queue="queue",t.AiQueue="ai_queue",t.LogsQueue="logs_queue",t.OptedOut="opted_out",t.SessionId="session_id",t.SessionStartTimestamp="session_start_timestamp",t.SessionLastTimestamp="session_timestamp",t.PersonProperties="person_properties",t.GroupProperties="group_properties",t.InstalledAppBuild="installed_app_build",t.InstalledAppVersion="installed_app_version",t.SessionReplay="session_replay",t.PushRegistered="push_registered",t.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",t.SurveyLastSeenDate="survey_last_seen_date",t.SurveysSeen="surveys_seen",t.Surveys="surveys",t.RemoteConfig="remote_config",t.FlagsEndpointWasHit="flags_endpoint_was_hit",t.DeviceId="device_id",t})({}),gc=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),Lp=["$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"],Np=["token"],fd="NativeGzipValidationError",zo=t=>t.length>=2&&t[0]===31&&t[1]===139,mc=(t,e)=>t===gc.GZipJS||e===gc.GZipJS||e==="gzip",vc=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",pr=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=fd,e},Op=(function(){var t=se((function*(e,n){18>e.size&&pr("too-short");var i=new Uint8Array(yield e.slice(0,10).arrayBuffer());zo(i)&&i[2]===8||pr("invalid-header");var r=new DataView(yield e.slice(e.size-8).arrayBuffer());r.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(_i)return _i;_i=[];for(var c=0;256>c;c++){for(var d=c,h=0;8>h;h++)d=1&d?3988292384^d>>>1:d>>>1;_i[c]=d>>>0}return _i})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(n)&&pr("invalid-crc");var s=n.length>>>0;r.getUint32(4,!0)!==s&&pr("invalid-size")}));return function(e,n){return t.apply(this,arguments)}})();function Vo(){return Vo=se((function*(t,e,n){e===void 0&&(e=!0);try{var i=new TextEncoder().encode(t),r=new globalThis.CompressionStream("gzip"),s=r.writable.getWriter(),o=s.write(i).then((()=>s.close())).catch((function(){var u=se((function*(c){try{yield s.abort(c)}catch{}throw c}));return function(c){return u.apply(this,arguments)}})()),a=new Response(r.readable).blob(),l=(yield Promise.all([a,o]))[0];return yield Op(l,i),l}catch(u){if(n!=null&&n.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),Vo.apply(this,arguments)}var Bp=["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"],_c=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var n=t.toLowerCase();return Bp.concat(e).some((i=>{var r=i.toLowerCase();return n.indexOf(r)!==-1}))};function j(t,e){return t.indexOf(e)!==-1}var xs=function(t){return t.trim()},Go=function(t){return t.replace(/^\$/,"")};function hd(t){var e,n=[];return(e=JSON.stringify(t,(function(i,r){if(typeof r=="bigint")return r.toString();if(typeof r!="function"&&typeof r!="symbol"){if(r instanceof Error)return{name:r.name,message:r.message,stack:r.stack};if(r&&typeof r=="object"){for(;n.length>0&&n[n.length-1]!==this;)n.pop();if(n.includes(r))return"[Circular]";n.push(r)}return r}})))!==null&&e!==void 0?e:"null"}var pd=Object.prototype,gd=pd.hasOwnProperty,Is=pd.toString,U=Array.isArray||function(t){return Is.call(t)==="[object Array]"},De=t=>typeof t=="function",he=t=>t===Object(t)&&!U(t),Kt=t=>{if(he(t)){for(var e in t)if(gd.call(t,e))return!1;return!0}return!1},C=t=>t===void 0,X=t=>Is.call(t)=="[object String]",Ko=t=>X(t)&&t.trim().length===0,Ke=t=>t===null,H=t=>C(t)||Ke(t),ke=t=>Is.call(t)=="[object Number]"&&t==t,Dt=t=>ke(t)&&t>0,mt=t=>Is.call(t)==="[object Boolean]",Dp=t=>t instanceof FormData,jp=t=>j(Lp,t),Up=t=>j(Np,t);function md(t){return t===null||typeof t!="object"}function Hr(t,e){return{}.toString.call(t)==="[object "+e+"]"}function Xa(t){return typeof Event<"u"&&vd(t,Event)}function vd(t,e){try{return t instanceof e}catch{return!1}}var Hp=[!0,"true",1,"1","yes"],uo=t=>j(Hp,t),Wp=[!1,"false",0,"0","no"];function At(t,e,n,i,r){return e>n&&(i.warn("min cannot be greater than max."),e=n),ke(t)?t>n?(i.warn(" cannot be greater than max: "+n+". Using max value instead."),n):e>t?(i.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(i.warn(" must be a number. using max or fallback. max: "+n+", fallback: "+r),At(r||n,e,n,i))}class qp{constructor(e){this.tt={},this.et=e.et,this.it=At(e.bucketSize,0,100,e.rt),this.nt=At(e.refillRate,0,this.it,e.rt),this.st=At(e.refillInterval,0,864e5,e.rt)}ot(e,n){var i=Math.floor((n-e.lastAccess)/this.st);i>0&&(e.tokens=Math.min(e.tokens+i*this.nt,this.it),e.lastAccess=e.lastAccess+i*this.st)}consumeRateLimit(e){var n,i=Date.now(),r=String(e),s=this.tt[r];return s?this.ot(s,i):this.tt[r]=s={tokens:this.it,lastAccess:i},s.tokens===0||(s.tokens--,s.tokens===0&&((n=this.et)==null||n.call(this,e)),s.tokens===0)}stop(){this.tt={}}}var it="Mobile",Wr="iOS",Yt="Android",ei="Tablet",_d=Yt+" "+ei,yd="iPad",wd="Apple",bd=wd+" Watch",Bi="Safari",ti="BlackBerry",Ed="Samsung",Sd=Ed+"Browser",xd=Ed+" Internet",Pn="Chrome",zp=Pn+" OS",Id=Pn+" "+Wr,Qa="Internet Explorer",kd=Qa+" "+it,el="Opera",Vp=el+" Mini",tl="Edge",Cd="Microsoft "+tl,Zn="Firefox",Ad=Zn+" "+Wr,Gi="Nintendo",Ki="PlayStation",Xn="Xbox",Pd=Yt+" "+it,Fd=it+" "+Bi,Pi="Windows",Yo=Pi+" Phone",yc="Nokia",Jo="Ouya",Rd="Generic",Gp=Rd+" "+it.toLowerCase(),Td=Rd+" "+ei.toLowerCase(),Zo="Konqueror",$d="Oculus Browser",qr="Vivaldi",Md="Yandex",zr="Whale",Xo="DuckDuckGo",Ld="Pale Moon",Vr="Waterfox",Di="Brave",Nd="Google Search App",we="(\\d+(\\.\\d+)?)",fo=new RegExp("Version/"+we),Kp=new RegExp(Xn,"i"),Yp=new RegExp(Ki+" \\w+","i"),Jp=new RegExp(Gi+" \\w+","i"),nl=new RegExp(ti+"|PlayBook|BB10","i"),Zp={"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"},Od=function(t,e,n,i){e=e||"";var r=(function(s){return s!=null&&s.brave?Di:null})(n);return r||(i!=null&&i.detectGoogleSearchApp&&j(t,"GSA/")?Nd:j(t," OPR/")&&j(t,"Mini")?Vp:j(t," OPR/")?el:nl.test(t)?ti:j(t,"IE"+it)||j(t,"WPDesktop")?kd:j(t,"OculusBrowser")?$d:j(t,Sd)?xd:j(t,tl)||j(t,"Edg/")?Cd:j(t,qr+"/")?qr:j(t,"YaBrowser/")?Md:j(t,zr+"/")?zr:j(t,Xo+"/")||j(t,"Ddg/")?Xo:j(t,"FBIOS")?"Facebook "+it:j(t,"UCWEB")||j(t,"UCBrowser")?"UC Browser":j(t,"CriOS")?Id:j(t,"CrMo")||j(t,Pn)?Pn:j(t,Yt)&&j(t,Bi)?Pd:j(t,"FxiOS")?Ad:j(t.toLowerCase(),Zo.toLowerCase())?Zo:j(t,Di+"/")?Di:((s,o)=>o&&j(o,wd)||(function(a){return j(a,Bi)&&!j(a,Pn)&&!j(a,Yt)})(s))(t,e)?j(t,it)?Fd:Bi:j(t,"PaleMoon/")?Ld:j(t,Vr+"/")?Vr:j(t,Zn)?Zn:j(t,"MSIE")||j(t,"Trident/")?Qa:j(t,"Gecko")?Zn:"")},Xp={[kd]:[new RegExp("rv:"+we)],[Cd]:[new RegExp(tl+"?\\/"+we)],[Pn]:[new RegExp("("+Pn+"|CrMo)\\/"+we)],[Id]:[new RegExp("CriOS\\/"+we)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+we)],[Bi]:[fo],[Fd]:[fo],[el]:[new RegExp("(Opera|OPR)\\/"+we)],[Zn]:[new RegExp(Zn+"\\/"+we)],[Ad]:[new RegExp("FxiOS\\/"+we)],[Zo]:[new RegExp("Konqueror[:/]?"+we,"i")],[ti]:[new RegExp(ti+" "+we),fo],[Pd]:[new RegExp("android\\s"+we,"i")],[xd]:[new RegExp(Sd+"\\/"+we)],[$d]:[new RegExp("OculusBrowser\\/"+we)],[qr]:[new RegExp(qr+"\\/"+we)],[Md]:[new RegExp("YaBrowser\\/"+we)],[zr]:[new RegExp(zr+"\\/"+we)],[Di]:[new RegExp(Di+"\\/"+we)],[Xo]:[new RegExp("(DuckDuckGo|Ddg)\\/"+we)],[Ld]:[new RegExp("PaleMoon\\/"+we)],[Vr]:[new RegExp(Vr+"\\/"+we)],[Nd]:[new RegExp("GSA\\/"+we)],[Qa]:[new RegExp("(rv:|MSIE )"+we)],Mozilla:[new RegExp("rv:"+we)]},Qp=function(t,e,n,i){var r=Od(t,e,n,i),s=Xp[r];if(C(s))return null;for(var o=0;s.length>o;o++){var a=t.match(s[o]);if(a)return parseFloat(a[a.length-2])}return null},wc=[[new RegExp(Xn+"; "+Xn+" (.*?)[);]","i"),t=>[Xn,t&&t[1]||""]],[new RegExp(Gi,"i"),[Gi,""]],[new RegExp(Ki,"i"),[Ki,""]],[nl,[ti,""]],[new RegExp(Pi,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Yo,""];if(new RegExp(it).test(e)&&!/IEMobile\b/.test(e))return[Pi+" "+it,""];var n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){var i=Zp[n[1]]||"";return/arm/i.test(e)&&(i="RT"),[Pi,i]}return[Pi,""]}],[/((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=C(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+Yt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Yt+")","i"),t=>t&&t[2]?[Yt,[t[2],t[3],t[4]||"0"].join(".")]:[Yt,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{var e=["Mac OS X",""];return t&&t[1]&&(e[1]=[t[1],t[2],t[3]||"0"].join(".")),e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[zp,""]],[/Linux|debian/i,["Linux",""]]],bc=function(t){return Jp.test(t)?Gi:Yp.test(t)?Ki:Kp.test(t)?Xn:new RegExp(Jo,"i").test(t)?Jo:new RegExp("("+Yo+"|WPDesktop)","i").test(t)?Yo:/iPad/.test(t)?yd:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?bd:nl.test(t)?ti:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(yc,"i").test(t)?yc:/(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(it).test(t)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(t)||/pixel[\daxl ]{1,6}/i.test(t)&&!/pixel c/i.test(t)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(t)||/lmy47v/i.test(t)&&!/QTAQZ3/i.test(t)?Yt:_d:new RegExp("(pda|"+it+")","i").test(t)?Gp:new RegExp(ei,"i").test(t)&&!new RegExp(ei+" pc","i").test(t)?Td:""},eg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ec(t,e){return typeof(n=t)=="string"&&eg.test(n)?t:e();var n}function fn(t){return t&&t.split("#")[0]}function il(t,e){var n=setTimeout(t,e);return n?.unref&&n?.unref(),n}function Sc(t,e,n){return Bd.apply(this,arguments)}function Bd(){return(Bd=se((function*(t,e,n){var i;try{return yield Promise.race([t,new Promise(((r,s)=>{i=il((()=>{try{n?.(),r()}catch(o){s(o)}}),e)}))])}finally{clearTimeout(i)}}))).apply(this,arguments)}var tg=t=>t instanceof Error,Dd={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}},ng=Dd.info;function jd(t){if(mt(t))return{boolValue:t};if(typeof t=="number")return Number.isFinite(t)?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:{stringValue:String(t)};if(typeof t=="string")return{stringValue:t};if(U(t))return{arrayValue:{values:t.map((e=>jd(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function Gr(t){var e=[];for(var n in t){var i=t[n];Ke(i)||C(i)||e.push({key:n,value:jd(i)})}return e}function ig(t,e){var n=Dd[t.level||"info"]||ng,i=n.text,r=n.number,s=String(Date.now())+"000000",o={};e.distinctId&&(o.posthogDistinctId=e.distinctId),e.sessionId&&(o.sessionId=e.sessionId),e.windowId&&(o["window.id"]=e.windowId),H(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),H(e.lastActivityTimestamp)||(o.lastActivityTimestamp=String(e.lastActivityTimestamp)),e.currentUrl&&(o["url.full"]=e.currentUrl),e.screenName&&(o["screen.name"]=e.screenName),e.appState&&(o["app.state"]=e.appState),e.activeFeatureFlags&&e.activeFeatureFlags.length>0&&(o.feature_flags=e.activeFeatureFlags);var a=I({},o,t.attributes||{}),l={timeUnixNano:s,observedTimeUnixNano:s,severityNumber:r,severityText:i,body:{stringValue:t.body},attributes:Gr(a)};return t.trace_id&&(l.traceId=t.trace_id),t.span_id&&(l.spanId=t.span_id),C(t.trace_flags)||(l.flags=t.trace_flags),l}function Ud(t,e,n){return I({},t.resourceAttributes,{"service.name":t.serviceName||"unknown_service"},t.environment&&{"deployment.environment":t.environment},t.serviceVersion&&{"service.version":t.serviceVersion},{"telemetry.sdk.name":e,"telemetry.sdk.version":n})}function Hd(t,e,n,i){return{resourceLogs:[{resource:{attributes:Gr(e)},scopeLogs:[{scope:{name:n,version:i},logRecords:t}]}]}}let rg=class{constructor(t,e,n,i,r,s,o){var a;s===void 0&&(s=()=>Promise.resolve()),this._instance=t,this.Ne=e,this.rt=n,this.ut=i,this.ht=r,this.dt=s,this.vt=o,this.ct=null,this.ft=0,this.yt=0,this.bt=0,this._t=0,this.wt=!1,this.kt=e.maxBufferSize,this.xt=Math.max((a=e.maxQueueSize)!==null&&a!==void 0?a:e.maxBufferSize,e.maxBufferSize),this.St=e.flushIntervalMs,this.Ct=e.maxBatchRecordsPerPost,this.Mt=e.rateCapWindowMs,this.Tt=e.maxLogsPerInterval}reset(){this.Et(),this.ct=null,this.bt=0,this._t=0,this.wt=!1,this.ft=0,this.yt=0,this.Ct=this.Ne.maxBatchRecordsPerPost}onReconnect(){this.yt=0,this.It()}captureLog(t){if(!this._instance.isDisabled&&!this._instance.optedOut&&t!=null&&t.body){var e=this.Pt(t);if(e!==null)if(e.body){if(this.Rt()){var n={record:ig(e,this.ut())};this.ht((()=>this.At(n)))}}else this.rt.info("Log was rejected in beforeSend function")}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Log was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for log:",o),null}return i}Rt(){if(this.Tt===void 0)return!0;var t=Date.now(),e=t-this.bt;return this.Mt>e&&e>=0||(this.bt=t,this._t=0,this.wt=!1),this.Tt>this._t?(this._t++,!0):(this.wt||(this.rt.warn("captureLog dropping logs: exceeded "+this.Tt+" logs per "+this.Mt+"ms"),this.wt=!0),!1)}flush(){var t=this;return se((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return se((function*(){var e;t.Et();var n=(e=t._instance.getPersistedProperty(Ut.LogsQueue))!==null&&e!==void 0?e:[];if(n.length!==0)for(var i=n.length,r=0;n.length>0&&i>r;){var s,o;t.ft=0;var a=Math.min(n.length,t.Ct),l=n.slice(0,a),u=Hd(l.map((d=>d.record)),t.Lt(),(s=t.vt)!==null&&s!==void 0?s:t._instance.getLibraryId(),t._instance.getLibraryVersion()),c=yield t._instance.Ot(u);if(c.kind==="too-large"&&l.length>1)t.Ct=Math.max(1,Math.floor(l.length/2)),t.rt.warn("Received 413 when sending logs batch of size "+l.length+", reducing batch size to "+t.Ct);else if(c.kind==="retry-later"||(c.kind==="too-large"?t.rt.warn("Dropping a single log record after 413 with batch size 1 — the record is larger than the server cap and cannot be split further."):c.kind==="ok"&&t.Ne.maxBatchRecordsPerPost>t.Ct&&(t.Ct=Math.min(t.Ne.maxBatchRecordsPerPost,t.Ct+1)),yield t.Dt(l.length),n=(o=t._instance.getPersistedProperty(Ut.LogsQueue))!==null&&o!==void 0?o:[],r+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return se((function*(){var n,i=Math.max(0,t-e.ft),r=(n=e._instance.getPersistedProperty(Ut.LogsQueue))!==null&&n!==void 0?n:[];e._instance.setPersistedProperty(Ut.LogsQueue,r.slice(i)),yield e.dt()}))()}Lt(){return Ud(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var n=(e=this._instance.getPersistedProperty(Ut.LogsQueue))!==null&&e!==void 0?e:[];this.xt>n.length||(n.shift(),this.ft++,this.rt.info("Logs queue is full, dropping oldest record.")),n.push(t),this._instance.setPersistedProperty(Ut.LogsQueue,n),this.kt>n.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=il((()=>{this.Nt=void 0,this.It()}),t))}qt(){var t=Math.min(Math.max(0,this.yt-1),6);return this.St*Math.pow(2,t)}jt(){var t=this._instance.getPersistedProperty(Ut.LogsQueue);return!!t&&t.length>0}shutdown(t){var e=this;return se((function*(){e.Et();var n=e.flush().catch((()=>{}));t!==void 0?yield Sc(n,t):yield n}))()}flushWithTimeout(t){var e=this;return se((function*(){var n=e.flush();yield Sc(n,t,(()=>{n.catch((()=>{}))}))}))()}It(){this.flush().then((()=>{this.yt=0}),(t=>{this.yt++,this.rt.error("PostHog logs flush failed:",t)})).finally((()=>{!this._instance.isDisabled&&this.jt()&&this.$t(this.qt())}))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}};var ho=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function xc(t){return String(t)+"000000"}function Ic(t,e,n,i){var r="";return i&&(r=Object.keys(i).sort().map((s=>JSON.stringify(s)+":"+JSON.stringify(i[s]))).join(",")),t+"\0"+e+"\0"+(n??"")+"\0"+r}let sg=class{constructor(t,e,n){this._instance=t,this.Ne=e,this.rt=n,this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Wt=0}count(t,e,n){e===void 0&&(e=1),this.Vt({name:t,type:"count",value:e,unit:n?.unit,attributes:n?.attributes})}gauge(t,e,n){this.Vt({name:t,type:"gauge",value:e,unit:n?.unit,attributes:n?.attributes})}histogram(t,e,n){this.Vt({name:t,type:"histogram",value:e,unit:n?.unit,attributes:n?.attributes})}flush(){var t=this,e=this.ct,n=(function(){var r=se((function*(){e&&(yield e.catch((()=>{}))),yield t.Zt()}));return function(){return r.apply(this,arguments)}})(),i=n().finally((()=>{this.ct===i&&(this.ct=null)}));return this.ct=i,i}drainWindow(){if(this.Bt.size===0)return null;var t=this.Bt;return this.Bt=new Map,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Gt(t)}reset(){this.Wt++,this.Et(),this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set}Vt(t){if(!this._instance.isDisabled&&!this._instance.optedOut){var e=this.Pt(t);if(e!==null)if(e.name&&typeof e.name=="string")if(typeof e.value=="number"&&Number.isFinite(e.value))if(e.type==="count"&&0>e.value)this.rt.warn("Dropping count '"+e.name+"': counters are monotonic, value must be >= 0");else{var n,i;try{n=e.attributes?I({},e.attributes):void 0,i=Ic(e.type,e.name,e.unit,n)}catch(o){return void this.rt.warn("Dropping metric '"+e.name+"': attributes could not be serialized",o)}var r=this.Bt.get(i);if(!r){if(!this.Qt())return;r={name:e.name,type:e.type,unit:e.unit,attributes:n,windowStartMs:Date.now()},this.Bt.set(i,r)}var s=this.Ut.get(e.name);s===void 0?this.Ut.set(e.name,e.type):s===e.type||this.zt.has(e.name)||(this.zt.add(e.name),this.rt.warn("Metric name '"+e.name+"' is already used as a "+s+"; recording it as a "+e.type+" too will blend both series in charts. Use a distinct name.")),this.Kt(r,e.value),this.$t()}else this.rt.warn("Dropping metric '"+e.name+"': value must be a finite number");else this.rt.warn("Dropping metric with empty name")}}Qt(){return this.Ne.maxSeriesPerFlush>this.Bt.size||(this.Ht||(this.Ht=!0,this.rt.warn("Metric series cap reached ("+this.Ne.maxSeriesPerFlush+" per flush window); dropping new series until the next flush. Reduce attribute cardinality.")),!1)}Kt(t,e){var n;switch(t.type){case"count":t.total=((n=t.total)!==null&&n!==void 0?n:0)+e;break;case"gauge":t.last=e;break;case"histogram":t.hist||(t.hist={count:0,sum:0,min:e,max:e,bucketCounts:new Array(ho.length+1).fill(0)});var i=t.hist;i.count+=1,i.sum+=e,i.min=Math.min(i.min,e),i.max=Math.max(i.max,e),i.bucketCounts[(function(r,s){for(var o=0;s.length>o;o++)if(s[o]>=r)return o;return s.length})(e,ho)]+=1}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Metric was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for metric:",o),null}return i}$t(){this.Nt||(this.Nt=il((()=>{this.Nt=void 0,this.flush().catch((t=>{this.rt.error("Metrics flush failed:",t)}))}),this.Ne.flushIntervalMs))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}Zt(){var t=this;return se((function*(){if(t.Bt.size!==0){var e=t.Bt;t.Bt=new Map,t.Ht=!1,t.Ut=new Map,t.zt=new Set;var n=t.Wt,i=yield t._instance.Jt(t.Gt(e));if(n===t.Wt)switch(i.kind){case"ok":return;case"retry-later":return t.Yt(e),void t.$t();case"too-large":return void t.rt.warn("Metrics batch exceeded the server size limit and was dropped");case"fatal":return void t.rt.error("Failed to send metrics batch:",i.error)}}}))()}Gt(t){return e=this.Xt(t),n=(function(s,o,a){return I({},s.resourceAttributes,{"service.name":s.serviceName||"unknown_service"},s.environment&&{"deployment.environment":s.environment},s.serviceVersion&&{"service.version":s.serviceVersion},{"telemetry.sdk.name":o,"telemetry.sdk.version":a})})(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion()),i=this._instance.getLibraryId(),r=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:Gr(n)},scopeMetrics:[{scope:{name:i,version:r},metrics:e}]}]};var e,n,i,r}Xt(t){var e=xc(Date.now()),n=new Map;for(var i of t.values()){var r,s=Ic(i.type,i.name,i.unit,void 0),o=n.get(s);o||(o=I({name:i.name},i.unit&&{unit:i.unit}),i.type==="count"?o.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:i.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:1,dataPoints:[]},n.set(s,o));var a=Gr((r=i.attributes)!==null&&r!==void 0?r:{}),l=xc(i.windowStartMs);if(i.type==="count"){var u,c={attributes:a,startTimeUnixNano:l,timeUnixNano:e,asDouble:(u=i.total)!==null&&u!==void 0?u:0};o.sum.dataPoints.push(c)}else if(i.type==="gauge"){var d,h={attributes:a,timeUnixNano:e,asDouble:(d=i.last)!==null&&d!==void 0?d:0};o.gauge.dataPoints.push(h)}else i.hist&&o.histogram.dataPoints.push({attributes:a,startTimeUnixNano:l,timeUnixNano:e,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:ho})}return Array.from(n.values())}Yt(t){var e,n;for(var i of t){var r=i[0],s=i[1],o=this.Bt.get(r);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,s.windowStartMs),o.type){case"count":o.total=((e=o.total)!==null&&e!==void 0?e:0)+((n=s.total)!==null&&n!==void 0?n:0);break;case"gauge":break;case"histogram":if(s.hist)if(o.hist){o.hist.count+=s.hist.count,o.hist.sum+=s.hist.sum,o.hist.min=Math.min(o.hist.min,s.hist.min),o.hist.max=Math.max(o.hist.max,s.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=s.hist.bucketCounts[a]}else o.hist=s.hist}else this.Qt()&&this.Bt.set(r,s)}}};var gr,kc,po;function og(t){var e=globalThis._posthogChunkIds;if(e){var n=Object.keys(e);return po&&n.length===kc||(kc=n.length,po=n.reduce(((i,r)=>{gr||(gr={});var s=gr[r];if(s)i[s[0]]=s[1];else for(var o=t(r),a=o.length-1;a>=0;a--){var l=o[a],u=l?.filename,c=e[r];if(u&&c){i[u]=c,gr[r]=[u,c];break}}return i}),{})),po}}class ag{constructor(e,n,i){i===void 0&&(i=[]),this.coercers=e,this.stackParser=n,this.modifiers=i}buildFromUnknown(e,n){n===void 0&&(n={});var i=n&&n.mechanism||{handled:!0,type:"generic"},r=this.buildCoercingContext(i,n,0).apply(e),s=this.buildParsingContext(n),o=this.parseStacktrace(r,s);return{$exception_list:this.convertToExceptionList(o,i),$exception_level:"error"}}modifyFrames(e){var n=this;return se((function*(){for(var i of e)i.stacktrace&&i.stacktrace.frames&&U(i.stacktrace.frames)&&(i.stacktrace.frames=yield n.applyModifiers(i.stacktrace.frames));return e}))()}coerceFallback(e){var n;return{type:"Error",value:"Unknown error",stack:(n=e.syntheticException)==null?void 0:n.stack,synthetic:!0}}parseStacktrace(e,n){var i,r;return e.cause!=null&&(i=this.parseStacktrace(e.cause,n)),e.stack!=""&&e.stack!=null&&(r=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?n.skipFirstLines:0),n.chunkIdMap)),I({},e,{cause:i,stack:r})}applyChunkIds(e,n){return e.map((i=>(i.filename&&n&&(i.chunk_id=n[i.filename]),i)))}applyCoercers(e,n){for(var i of this.coercers)if(i.match(e))return i.coerce(e,n);return this.coerceFallback(n)}applyModifiers(e){var n=this;return se((function*(){var i=e;for(var r of n.modifiers)i=yield r(i);return i}))()}convertToExceptionList(e,n){var i,r,s,o={type:e.type,value:e.value,mechanism:{type:(i=n.type)!==null&&i!==void 0?i:"generic",handled:(r=n.handled)===null||r===void 0||r,synthetic:(s=e.synthetic)!==null&&s!==void 0&&s}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,I({},n,{handled:!0}))),a}buildParsingContext(e){var n;return{chunkIdMap:og(this.stackParser),skipFirstLines:(n=e.skipFirstLines)!==null&&n!==void 0?n:1}}buildCoercingContext(e,n,i){i===void 0&&(i=0);var r=(s,o)=>{if(4>=o){var a=this.buildCoercingContext(e,n,o);return this.applyCoercers(s,a)}};return I({},n,{syntheticException:i==0?n.syntheticException:void 0,mechanism:e,apply:s=>r(s,i),next:s=>r(s,i+1)})}}var ni="?";function Qo(t,e,n,i,r){var s={platform:t,filename:e,function:n===""?ni:n,in_app:!0};return C(i)||(s.lineno=i),C(r)||(s.colno=r),s}var Wd=(t,e)=>{var n=t.indexOf("safari-extension")!==-1,i=t.indexOf("safari-web-extension")!==-1;return n||i?[t.indexOf("@")!==-1?t.split("@")[0]:ni,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},lg=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,cg=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,ug=/\((\S*)(?::(\d+))(?::(\d+))\)/,dg=(t,e)=>{var n=lg.exec(t);if(n)return Qo(e,n[1],ni,+n[2],+n[3]);var i=cg.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var r=ug.exec(i[2]);r&&(i[2]=r[1],i[3]=r[2],i[4]=r[3])}var s=Wd(i[1]||ni,i[2]);return Qo(e,s[1],s[0],i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},fg=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,hg=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,pg=(t,e)=>{var n=fg.exec(t);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){var i=hg.exec(n[3]);i&&(n[1]=n[1]||"eval",n[3]=i[1],n[4]=i[2],n[5]="")}var r=n[3],s=n[1]||ni,o=Wd(s,r);return Qo(e,r=o[1],s=o[0],n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},Cc=/\(error: (.*)\)/;class gg{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,n){var i=X(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:i?e.stack:void 0,cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var n=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?n+": "+e.message:n}isDOMException(e){return Hr(e,"DOMException")}isDOMError(e){return Hr(e,"DOMError")}}class mg{match(e){return(function(n){switch({}.toString.call(n)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return vd(n,Error)}})(e)}coerce(e,n){return{type:this.getType(e),value:this.getMessage(e,n),stack:this.getStack(e),cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,n){var i=e.message;return String(i.error&&typeof i.error.message=="string"?i.error.message:i)}getStack(e){return e.stacktrace||e.stack||void 0}}class vg{constructor(){}match(e){return!!Hr(e,"ErrorEvent")&&(e.error!=null||this.fe(e))}coerce(e,n){var i;if(e.error!=null)return n.apply(e.error);var r=n.apply(e.message);return I({},r,{stack:(i=this.pe(e))!==null&&i!==void 0?i:r.stack,synthetic:!0})}fe(e){return X(e.message)&&e.message.length>0}pe(e){var n=e;if(X(n.filename)&&n.filename.length>0){var i,r,s=(i=n.lineno)!==null&&i!==void 0?i:0,o=(r=n.colno)!==null&&r!==void 0?r:0;return`Error + at `+n.filename+":"+s+":"+o}}}var _g=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class yg{match(e){return typeof e=="string"}coerce(e,n){var i,r=this.getInfos(e),s=r[0],o=r[1];return{type:s??"Error",value:o??e,stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}getInfos(e){var n="Error",i=e,r=e.match(_g);return r&&(n=r[1],i=r[2]),[n,i]}}var wg=["fatal","error","warning","log","info","debug"];function qd(t,e){e===void 0&&(e=40);var n=Object.keys(t);if(n.sort(),!n.length)return"[object has no keys]";for(var i=n.length;i>0;i--){var r=n.slice(0,i).join(", ");if(e>=r.length)return i===n.length?r:r.length>e?r.slice(0,e)+"...":r}return""}class bg{match(e){return typeof e=="object"&&e!==null}coerce(e,n){var i,r,s=this.getErrorPropertyFromObject(e);return s?n.apply(s):{type:this.getType(e),value:this.getValue(e),stack:(i=this.getStack(e))!==null&&i!==void 0?i:(r=n.syntheticException)==null?void 0:r.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return Xa(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var n="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(n+=" with message: '"+e.message+"'"),n}if("message"in e&&typeof e.message=="string")return e.message;var i=this.getObjectClassName(e);return(i&&i!=="Object"?"'"+i+"'":"Object")+" captured as exception with keys: "+qd(e)}isSeverityLevel(e){return X(e)&&!Ko(e)&&wg.indexOf(e)>=0}getStack(e){try{return X(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:X(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(var n in e)if({}.hasOwnProperty.call(e,n)){var i=e[n];if(tg(i))return i}}getObjectClassName(e){try{var n=Object.getPrototypeOf(e);return n?n.constructor.name:void 0}catch{return}}}class Eg{match(e){return Xa(e)}coerce(e,n){var i,r=e.constructor.name;return{type:r,value:r+" captured as exception with keys: "+qd(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class Sg{match(e){return md(e)}coerce(e,n){var i;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class xg{match(e){return Hr(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Xa(e))return!1;try{var n=e.detail;return n!=null&&typeof n=="object"&&"reason"in n}catch{return!1}}coerce(e,n){var i,r=this.getUnhandledRejectionReason(e);return md(r)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(r),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}:n.apply(r)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}}var Kr="$message",Yr="$timestamp",Ig=new Set([Kr,Yr]),go={enabled:!0,max_bytes:32768};function Jr(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:go.enabled,max_bytes:Cg(t.max_bytes,go.max_bytes)}:I({},go)}class kg{constructor(e){this.Ke=[],this.Je=0,this.Ne=Jr(e)}setConfig(e){this.Ne=Jr(e),this.Xe()}add(e){var n=(function(r){var s;try{s=hd(r)}catch{return}try{var o=JSON.parse(s);if(!he(o))return;var a=o,l=a[Kr],u=a[Yr];return!X(l)||l.trim().length===0||!X(u)&&!ke(u)?void 0:{step:a,json:s}}catch{return}})(e);if(n){var i=(function(r){if(typeof TextEncoder<"u")return new TextEncoder().encode(r).length;for(var s=encodeURIComponent(r),o=0,a=0;s.length>a;a++)s[a]==="%"?(o+=1,a+=2):o+=1;return o})(n.json);i>this.Ne.max_bytes||(this.Ke.push({step:n.step,bytes:i}),this.Je+=i,this.Xe())}}getAttachable(){return this.Ke.map((e=>e.step))}clear(){this.Ke=[],this.Je=0}size(){return this.Ke.length}Xe(){for(;this.Je>this.Ne.max_bytes&&this.Ke.length>0;){var e=this.Ke.shift();e&&(this.Je-=e.bytes)}}}function Cg(t,e){if(!ke(t)||t===1/0||t===-1/0)return e;var n=Math.floor(t);return 0>n?e:n}var zd=function(t,e){var n=(e===void 0?{}:e).debugEnabled,i={k(r){if(w&&(ne.DEBUG||w.POSTHOG_DEBUG||n)&&!C(w.console)&&w.console){for(var s=("__rrweb_original__"in w.console[r])?w.console[r].__rrweb_original__:w.console[r],o=arguments.length,a=new Array(o>1?o-1:0),l=1;o>l;l++)a[l-1]=arguments[l];s(t,...a)}},debug(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("debug",...s)},info(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("log",...s)},warn(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("warn",...s)},error(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("error",...s)},critical(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];console.error(t,...s)},uninitializedWarning(r){i.error("You must initialize PostHog before calling "+r)},createLogger:(r,s)=>zd(t+" "+r,s)};return i},A=zd("[PostHog.js]"),pe=A.createLogger,Ag=pe("[ExternalScriptsLoader]"),mo=(t,e,n)=>{if(t.config.disable_external_dependency_loading)return Ag.warn(e+" was requested but loading of external scripts is disabled."),n("Loading of external scripts is disabled");var i=P?.querySelectorAll("script");if(i){for(var r,s=function(){if(i[o].src===e){var l=i[o];return l.__posthog_loading_callback_fired?{v:n()}:(l.addEventListener("load",(u=>{l.__posthog_loading_callback_fired=!0,n(void 0,u)})),l.onerror=u=>n(u),{v:void 0})}},o=0;i.length>o;o++)if(r=s())return r.v}var a=()=>{if(!P)return n("document not found");var l=P.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=d=>{l.__posthog_loading_callback_fired=!0,n(void 0,d)},l.onerror=d=>n(d),t.config.prepare_external_dependency_script&&(l=t.config.prepare_external_dependency_script(l)),!l)return n("prepare_external_dependency_script returned null");if(t.config.external_scripts_inject_target==="head")P.head.appendChild(l);else{var u,c=P.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):P.body.appendChild(l)}};P!=null&&P.body?a():P?.addEventListener("DOMContentLoaded",a)};B.__PosthogExtensions__=B.__PosthogExtensions__||{},B.__PosthogExtensions__.loadExternalDependency=(t,e,n)=>{if(e!=="remote-config"){var i;if(t.config.strict_script_versioning)i=t.requestRouter.endpointFor("assets","/static/"+t.version+"/"+e+".js");else{var r="/static/"+e+".js?v="+t.version;if(e==="toolbar"){var s=3e5;r=r+"&t="+Math.floor(Date.now()/s)*s}i=t.requestRouter.endpointFor("assets",r)}mo(t,i,n)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");mo(t,o,n)}},B.__PosthogExtensions__.loadSiteApp=(t,e,n)=>{var i=t.requestRouter.endpointFor("api",e);mo(t,i,n)};ne.DEBUG=!1,ne.LIB_VERSION="1.415.7",ne.LIB_NAME="web";var Vd="$people_distinct_id",Yi="$device_id",vo="$device_model",Fi="__alias",Ri="__timers",ea="$autocapture_disabled_server_side",ta="$heatmaps_enabled_server_side",na="$exception_capture_enabled_server_side",ia="$error_tracking_suppression_rules",ra="$error_tracking_capture_extension_exceptions",sa="$web_vitals_enabled_server_side",rl="$dead_clicks_enabled_server_side",sl="$product_tours_enabled_server_side",oa="$web_vitals_allowed_metrics",An="$session_recording_remote_config",Gd="$replay_sample_rate",Kd="$replay_override_sampling",Yd="$replay_override_linked_flag",Jd="$replay_override_url_trigger",Zd="$replay_override_event_trigger",Kn="$sesid",ol="$session_is_sampled",Sn="$enabled_feature_flags",Ti="$active_feature_flags",Ar="$early_access_features",aa="$feature_flag_details",$i="$feature_flag_payloads",Pr="$feature_flag_request_id",Zr="$minimal_flag_called_events",It="$override_feature_flags",xn="$override_feature_flag_payloads",jt="$stored_person_properties",In="$stored_group_properties",la="$surveys",Xr="$surveys_loaded_at",ca="$surveys_activated",Fr="$surveys_activated_session",Rr="$surveys_activated_timestamps",Mi="ph_product_tours",Cn="$flag_call_reported",Li="$flag_call_reported_session_id",Tr="$feature_flag_errors",ji="$feature_flag_evaluated_at",ot="$user_state",ua="$client_session_props",da="$capture_rate_limit",fa="$initial_campaign_params",ha="$initial_referrer_info",Qr="$initial_person_info",es="$epp",mr="$posthog_cookieless",Xd="$cookieless_mode",Qd="$sdk_debug_extensions_init_method",ef="$sdk_debug_extensions_init_time_ms",tf="$sdk_debug_recording_script_not_loaded",al="PostHog loadExternalDependency extension not found.",kn="on_reject",Wt="always",Un="anonymous",vn="identified",pa="identified_only",ts="visibilitychange",ns="beforeunload",Vn="$pageview",_o="$pageleave",yo="$identify",Ac="$groupidentify";function vr(t,e){U(t)&&t.forEach(e)}function ie(t,e){if(!H(t))if(U(t))t.forEach(e);else if(Dp(t))t.forEach(((i,r)=>e(i,r)));else for(var n in t)gd.call(t,n)&&e(t[n],n)}var fe=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;e>i;i++)n[i-1]=arguments[i];for(var r of n)for(var s in r)r[s]!==void 0&&(t[s]=r[s]);return t};function $r(t){for(var e=Object.keys(t),n=e.length,i=new Array(n);n--;)i[n]=[e[n],t[e[n]]];return i}var Pc=function(t){try{return t()}catch{return}},Pg=function(t){return function(){try{for(var e=arguments.length,n=new Array(e),i=0;e>i;i++)n[i]=arguments[i];return t.apply(this,n)}catch(r){A.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),A.critical(r)}}},ll=function(t){var e={};return ie(t,(function(n,i){(X(n)&&n.length>0||ke(n))&&(e[i]=n)})),e},Fg=["herokuapp.com","vercel.app","netlify.app"];function Rg(t){var e=t?.hostname;if(!X(e))return!1;var n=e.split(".").slice(-2).join(".");for(var i of Fg)if(n===i)return!1;return!0}function ve(t,e,n,i){var r=i??{},s=r.capture,o=r.passive;t?.addEventListener(e,n,{capture:s!==void 0&&s,passive:o===void 0||o})}function ga(t){return t.name==="ph_toolbar_internal"}var nf=t=>{if(P){try{for(var e=t+"=",n=P.cookie.split(";").filter((s=>s.length)),i=0;n.length>i;i++){for(var r=n[i];r.charAt(0)==" ";)r=r.substring(1,r.length);if(r.indexOf(e)===0)return decodeURIComponent(r.substring(e.length,r.length))}}catch{}return null}};Math.trunc||(Math.trunc=function(t){return 0>t?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return ke(t)&&isFinite(t)&&Math.floor(t)===t});class is{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,n,i,r){if(!Number.isInteger(e)||!Number.isInteger(n)||!Number.isInteger(i)||!Number.isInteger(r)||0>e||0>n||0>i||0>r||e>0xffffffffffff||n>4095||i>1073741823||r>4294967295)throw new RangeError("invalid field value");var s=new Uint8Array(16);return s[0]=e/Math.pow(2,40),s[1]=e/Math.pow(2,32),s[2]=e/Math.pow(2,24),s[3]=e/Math.pow(2,16),s[4]=e/256,s[5]=e,s[6]=112|n>>>8,s[7]=n,s[8]=128|i>>>24,s[9]=i>>>16,s[10]=i>>>8,s[11]=i,s[12]=r>>>24,s[13]=r>>>16,s[14]=r>>>8,s[15]=r,new is(s)}toString(){for(var e="",n=0;this.bytes.length>n;n++)e=e+(this.bytes[n]>>>4).toString(16)+(15&this.bytes[n]).toString(16),n!==3&&n!==5&&n!==7&&n!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new is(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var n=0;16>n;n++){var i=this.bytes[n]-e.bytes[n];if(i!==0)return Math.sign(i)}return 0}}class Tg{generate(){var e=this.generateOrAbort();if(!C(e))return e;this.S=0;var n=this.generateOrAbort();if(C(n))throw new Error("Could not generate UUID after timestamp reset");return n}generateOrAbort(){var e=Date.now();if(e>this.S)this.S=e,this.C();else{if(this.S>=e+1e4)return;this.I++,this.I>4398046511103&&(this.S++,this.C())}return is.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 $g}}var Fc,rf=t=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;t.length>e;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};w&&!C(w.crypto)&&crypto.getRandomValues&&(rf=t=>crypto.getRandomValues(t));class $g{nextUint32(){return this.R.length>this.O||(rf(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var Ht=()=>Mg().toString(),Mg=()=>(Fc||(Fc=new Tg)).generate(),yi="",Lg=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,qt={N:()=>!!P,j(t){A.error("cookieStore error: "+t)},P:nf,H(t){var e;try{e=JSON.parse(qt.P(t))||{}}catch{}return e},F(t,e,n,i,r){if(!P)return!1;try{var s="",o="",a=(function(c,d){if(d){var h=(function(p,g){if(g===void 0&&(g=P),yi)return yi;if(!g||["localhost","127.0.0.1"].includes(p))return"";for(var m=p.split("."),v=Math.min(m.length,8),E="dmn_chk_"+Ht();!yi&&v--;){var S=m.slice(v).join("."),_=E+"=1;domain=."+S+";path=/";g.cookie=_+";max-age=3",g.cookie.includes(E)&&(g.cookie=_+";max-age=0",yi=S)}return yi})(c);if(!h){var f=(p=>{var g=p.match(Lg);return g?g[0]:""})(c);f!==h&&A.info("Warning: cookie subdomain discovery mismatch",f,h),h=f}return h?"; domain=."+h:""}return""})(P.location.hostname,i);if(n){var l=new Date;l.setTime(l.getTime()+864e5*n),s="; expires="+l.toUTCString()}r&&(o="; secure");var u=t+"="+encodeURIComponent(JSON.stringify(e))+s+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&A.warn("cookieStore warning: large cookie, len="+u.length),P.cookie=u,!0}catch{return!1}},q(t,e){if(P!=null&&P.cookie)try{qt.F(t,"",-1,e)}catch{return}}},wo=null,le={N(){if(!Ke(wo))return wo;var t=!0;if(C(w))t=!1;else try{var e="__mplssupport__";le.F(e,"xyz"),le.P(e)!=='"xyz"'&&(t=!1),le.q(e)}catch{t=!1}return t||A.error("localStorage unsupported; falling back to cookie store"),wo=t,t},j(t){A.error("localStorage error: "+t)},P(t){try{return w?.localStorage.getItem(t)}catch(e){le.j(e)}return null},H(t){try{return JSON.parse(le.P(t))||{}}catch{}return null},F(t,e){try{return w?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(n){le.j(n)}return!1},q(t){try{w?.localStorage.removeItem(t)}catch(e){le.j(e)}}},Ng=[Yi,"distinct_id",Kn,ol,es,Qr,ot],_r={},Og={N:()=>!0,j(t){A.error("memoryStorage error: "+t)},P:t=>_r[t]||null,H:t=>_r[t]||null,F:(t,e)=>(_r[t]=e,!0),q(t){delete _r[t]}},_n=null,be={N(){if(!Ke(_n))return _n;if(_n=!0,C(w))_n=!1;else try{var t="__support__";be.F(t,"xyz"),be.P(t)!=='"xyz"'&&(_n=!1),be.q(t)}catch{_n=!1}return _n},j(t){A.error("sessionStorage error: ",t)},P(t){try{return w?.sessionStorage.getItem(t)}catch(e){be.j(e)}return null},H(t){try{return JSON.parse(be.P(t))||null}catch{}return null},F(t,e){try{return w?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(n){be.j(n)}return!1},q(t){try{w?.sessionStorage.removeItem(t)}catch(e){be.j(e)}}};class Bg{constructor(e){this._instance=e}get Ne(){return this._instance.config}get consent(){return this.ti()?0:this.ei}isOptedOut(){return this.Ne.cookieless_mode===Wt||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===kn}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===0}isRejected(){return this.consent===0||this.consent===-1&&this.Ne.opt_out_capturing_by_default}optInOut(e){this.ii.F(this.ri,e?1:0,this.Ne.cookie_expiration,this.Ne.cross_subdomain_cookie,this.Ne.secure_cookie)}reset(){this.ii.q(this.ri,this.Ne.cross_subdomain_cookie)}get ri(){var e=this._instance.config,n=e.token,i=e.opt_out_capturing_cookie_prefix;return e.consent_persistence_name||(i?i+n:"__ph_opt_in_out_"+n)}get ei(){var e=this.ii.P(this.ri);return uo(e)?1:j(Wp,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,n=e==="localStorage"?le:qt;if(!this.ni||this.ni!==n){this.ni=n;var i=e==="localStorage"?qt:le;i.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(uo(i.P(this.ri))),i.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[Ue?.doNotTrack,Ue?.msDoNotTrack,B.doNotTrack].some((e=>uo(e)))}}function sf(t,e){var n,i=t==null||(n=t.config)==null?void 0:n.get_current_url;if(!De(i))return e;try{var r=i(e);return X(r)&&r?r:e}catch(s){return A.error("Error in get_current_url, falling back to window.location.href",s),e}}var of="__POSTHOG_TOOLBAR__",Dg=1,jg=3,Ug=11;function Rc(t){return t instanceof Element&&(t.id===of||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function hn(t){return!!t&&t.nodeType===Dg}function Qe(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function af(t){return!!t&&t.nodeType===jg}function lf(t){return!!t&&t.nodeType===Ug&&hn(t.host)}var cf=1e3;function cl(t){return t?xs(t).split(/\s+/):[]}function Tc(t,e){var n=(function(i){var r,s=w==null||(r=w.location)==null?void 0:r.href;return C(s)?void 0:sf(i,s)})(e);return!!(n&&t&&t.some((i=>n.match(i))))}function rs(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 cl(e)}function uf(t){return H(t)?null:xs(t).split(/(\s+)/).filter((e=>Ui(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function Ji(t){var e="";return va(t)&&!pf(t)&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;af(n)&&n.textContent&&(e+=(i=uf(n.textContent))!==null&&i!==void 0?i:"")})),xs(e)}function bo(t){var e;return C(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var ul=["a","button","form","input","select","textarea","label"];function ma(t,e){if(C(e))return!0;var n,i=function(s){if(e.some((o=>(function(a,l){var u=a.matches||a.matchesSelector||a.msMatchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.oMatchesSelector;try{return!!u&&u.call(a,l)}catch{return!1}})(s,o))))return{v:!0}};for(var r of t)if(n=i(r))return n.v;return!1}function df(t){var e=t.parentNode;return!(!e||!hn(e))&&e}var Hg=[".ph-no-autocapture","[data-ph-no-autocapture]"],ff=["next","previous","prev",">","<"],Wg=[...ff,"+","-","−","–"],$c=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,Mc=[".ph-no-rageclick",".ph-no-capture"],qg=["","text","search","email","password","url","tel","number"];function Lc(t,e){if(!w||dl(t))return!1;var n,i,r,s,o;if(mt(e)?(n=!!e&&Mc,i=void 0,r=!1):(n=(s=e?.css_selector_ignorelist)!==null&&s!==void 0?s:Mc,i=e?.content_ignorelist,r=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),n===!1||r&&(function(l){return!(!l||!hn(l))&&(!!Qe(l,"textarea")||(Qe(l,"input")?j(qg,(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=hf(t,!1).targetElementList;return!(function(l,u){if(l===!1||C(l))return!1;var c;if(l===!0)c=ff;else{if(!U(l))return!1;if(l.length>10)return A.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var h=d.safeText,f=d.ariaLabel;return c.some((p=>$c(h,p)||$c(f,p)))}))})(i,a.map((l=>{var u;return{safeText:Ji(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!ma(a,n)}var dl=t=>!t||Qe(t,"html")||!hn(t),hf=(t,e)=>{if(!w||dl(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,i=[t],r=t;r.parentNode&&!Qe(r,"body");)if(lf(r.parentNode))i.push(r.parentNode.host),r=r.parentNode.host;else{var s=df(r);if(!s)break;if(e||ul.indexOf(s.tagName.toLowerCase())>-1)n=!0;else try{var o=w.getComputedStyle(s);o&&o.getPropertyValue("cursor")==="pointer"&&(n=!0)}catch{}i.push(s),r=s}return{parentIsUsefulElement:n,targetElementList:i}};function va(t){for(var e=new Set,n=0,i=t;i.parentNode&&!Qe(i,"body");i=i.parentNode){if(n++>=cf||e.has(i))return!1;e.add(i);var r=rs(i);if(j(r,"ph-sensitive")||j(r,"ph-no-capture"))return!1}if(j(rs(t),"ph-include"))return!0;var s=t.type||"";if(X(s))switch(s.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!X(o)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(o.replace(/[^a-zA-Z0-9]/g,""))}function pf(t){return!!(Qe(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||Qe(t,"select")||Qe(t,"textarea")||t.getAttribute("contenteditable")==="true")}var Nc=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}))$"),Oc=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,zg=[16,15,14,13],Vg=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),Bc=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),Dc=/[0-9A-Za-z_]/;function Gg(t){for(var e=0,n=!1,i=t.length-1;i>=0;i--){var r=t.charCodeAt(i)-48;n&&(r*=2)>9&&(r-=9),e+=r,n=!n}return e%10==0}function Ui(t,e){if(e===void 0&&(e=!0),H(t))return!1;if(X(t)){t=xs(t);var n=e?Nc.test((t||"").replace(/[- ]/g,"")):(function(r){var s;for(Oc.lastIndex=0;s=Oc.exec(r);){var o=s[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of zg){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(Nc.test(d)&&Gg(d))return!0}}}return!1})(t);if(n)return!1;var i=e?Vg.test(t):(function(r){var s;for(Bc.lastIndex=0;s=Bc.exec(r);){var o=s[1],a=s[3];if(!(o&&a&&Dc.test(o)&&Dc.test(a)))return!0}return!1})(t);if(i)return!1}return!0}function jc(t){var e=Ji(t);return Ui(e=(e+" "+gf(t)).trim())?e:""}function gf(t){var e="";return t&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;if(n&&((i=n.tagName)==null?void 0:i.toLowerCase())==="span")try{var r=Ji(n);e=(e+" "+r).trim(),n.childNodes&&n.childNodes.length&&(e=(e+" "+gf(n)).trim())}catch(s){A.error("[AutoCapture]",s)}})),e}function Uc(t){return t.replace(/"|\\"/g,'\\"')}function Kg(t){var e=t.attr__class;if(e)return U(e)?e:cl(e)}var yr=pe("[Dead Clicks]"),Yg=()=>!0,Jg=t=>{var e,n=!((e=t.instance.persistence)==null||!e.get_property(rl)),i=t.instance.config.capture_dead_clicks;return mt(i)?i:!!he(i)||n};class Hc{get lazyLoadedDeadClicksAutocapture(){return this.si}constructor(e,n,i){this.instance=e,this.isEnabled=n,this.onCapture=i,this.startIfEnabledOrStop()}onRemoteConfig(e){if(e.ok){var n=e.config;"captureDeadClicks"in n&&(this.instance.persistence&&this.instance.persistence.register({[rl]:n.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var n,i;(n=B.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture?e():(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"dead-clicks-autocapture",(r=>{r?yr.error("failed to load script",r):e()}))}oi(){var e;if(P){if(!this.si&&(e=B.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var n=he(this.instance.config.capture_dead_clicks)?I({},this.instance.config.capture_dead_clicks):{};n.__onCapture=this.onCapture,this.onCapture&&(n.capture_dead_swipes=!1),this.si=B.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.si.start(P),yr.info("starting...")}}else yr.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,yr.info("stopping..."))}}var Eo=pe("[SegmentIntegration]"),mf="posthog-js";function vf(t,e){var n=e===void 0?{}:e,i=n.organization,r=n.projectId,s=n.prefix,o=n.severityAllowList,a=o===void 0?["error"]:o,l=n.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,h,f,p,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var v,E=((d=c.exception)==null?void 0:d.values)||[],S=E.map((b=>I({},b,{stacktrace:b.stacktrace?I({},b.stacktrace,{type:"raw",frames:(b.stacktrace.frames||[]).map((k=>I({},k,{platform:"web:javascript"})))}):void 0}))),_={$exception_message:((h=E[0])==null?void 0:h.value)||c.message,$exception_type:(f=E[0])==null?void 0:f.type,$exception_level:c.level,$exception_list:S,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((p=E[0])==null?void 0:p.value)||c.message,$sentry_exception_type:(g=E[0])==null?void 0:g.type,$sentry_tags:c.tags};return i&&r&&(_.$sentry_url=(s||"https://sentry.io/organizations/")+i+"/issues/?project="+r+"&query="+c.event_id),u&&((v=t.exceptions)==null||v.sendExceptionEvent(_)),c}}class Zg{constructor(e,n,i,r,s,o){this.name=mf,this.setupOnce=function(a){a(vf(e,{organization:n,projectId:i,prefix:r,severityAllowList:s,sendExceptionsToPostHog:o==null||o}))}}}class Wc{constructor(e){this.li=(n,i,r)=>{r&&(r.noSessionId||r.activityTimeout||r.sessionPastMaximumLength||r.crossTabAdoption)&&(A.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:n,changeReason:r}),this.ui=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.hi()}hi(){var e;this.di=(e=this._instance.sessionManager)==null?void 0:e.onSessionId(this.li)}destroy(){var e;(e=this.di)==null||e.call(this),this.di=void 0}doPageView(e,n){var i,r=this.vi(e,n);return this.ui={pathname:(i=w?.location.pathname)!==null&&i!==void 0?i:"",pageViewId:n,timestamp:e},this._instance.scrollManager.resetContext(),r}doPageLeave(e){var n;return this.vi(e,(n=this.ui)==null?void 0:n.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.ui)==null?void 0:e.pageViewId}}vi(e,n){var i=this.ui;if(!i)return{$pageview_id:n};var r={$pageview_id:n,$prev_pageview_id:i.pageViewId},s=this._instance.scrollManager.getContext();if(s&&!this._instance.config.disable_scroll_properties){var o=s.maxScrollHeight,a=s.lastScrollY,l=s.maxScrollY,u=s.maxContentHeight,c=s.lastContentY,d=s.maxContentY;if(!(C(o)||C(a)||C(l)||C(u)||C(c)||C(d))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),d=Math.ceil(d);var h=o>1?At(a/o,0,1,A):1,f=o>1?At(l/o,0,1,A):1,p=u>1?At(c/u,0,1,A):1,g=u>1?At(d/u,0,1,A):1;r=fe(r,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:h,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:f,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:p,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return i.pathname&&(r.$prev_pageview_pathname=i.pathname),i.timestamp&&(r.$prev_pageview_duration=(e.getTime()-i.timestamp.getTime())/1e3),r}}var So=["flags","surveys"],Xg={[Vd]:{exposure:"hidden"},[Fi]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[Ri]:{exposure:"hidden"},[ea]:{exposure:"event"},[ta]:{exposure:"hidden"},[na]:{exposure:"event"},[ia]:{exposure:"hidden"},[ra]:{exposure:"event"},[sa]:{exposure:"event"},[rl]:{exposure:"event"},[sl]:{exposure:"hidden"},[oa]:{exposure:"event"},[An]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[Kn]:{exposure:"hidden"},[ol]:{exposure:"event"},[Gd]:{exposure:"event",shouldSkipFromEventProperties:t=>Ke(t)},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},$sess_rec_flush_size:{exposure:"hidden"},[Sn]:{exposure:"hidden",storageGroup:"flags"},[Ti]:{exposure:"hidden",storageGroup:"flags"},[Ar]:{exposure:"hidden"},[aa]:{exposure:"hidden",storageGroup:"flags"},[$i]:{exposure:"hidden",storageGroup:"flags"},[Pr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[Zr]:{exposure:"hidden",storageGroup:"flags"},[It]:{exposure:"hidden"},[xn]:{exposure:"hidden"},[jt]:{exposure:"hidden"},[In]:{exposure:"hidden"},[la]:{exposure:"hidden",storageGroup:"surveys"},[Xr]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[ca]:{exposure:"event"},[Fr]:{exposure:"hidden"},[Rr]:{exposure:"hidden"},[Mi]:{exposure:"hidden"},$product_tours_activated:{exposure:"hidden"},$product_tours_activated_session:{exposure:"hidden"},$conversations_widget_session_id:{exposure:"event"},$conversations_ticket_id:{exposure:"event"},$conversations_widget_state:{exposure:"event"},$conversations_user_traits:{exposure:"event"},[Cn]:{exposure:"hidden"},[Li]:{exposure:"hidden"},[Tr]:{exposure:"hidden"},[ji]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[ot]:{exposure:"hidden"},[ua]:{exposure:"hidden"},[da]:{exposure:"hidden"},[fa]:{exposure:"hidden"},[ha]:{exposure:"hidden"},[Qr]:{exposure:"hidden"},[es]:{exposure:"hidden"},[Kd]:{exposure:"event"},[Yd]:{exposure:"event"},[Jd]:{exposure:"event"},[Zd]:{exposure:"event"},[Qd]:{exposure:"event"},[ef]:{exposure:"event"},[tf]:{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"}},Qg=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],yn=t=>{var e=Xg[t];if(e)return e;for(var n of Qg){var i=n[1];if(t.indexOf(n[0])===0)return i}},Yn=(t,e)=>{try{return JSON.stringify(t,((n,i)=>typeof i=="bigint"?i.toString():i),e)}catch{return hd(t)}},ss=t=>{var e=P?.createElement("a");return C(e)?null:(e.href=t,e)},ii=function(t,e){for(var n,i=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),r=0;i.length>r;r++){var s=i[r].split("=");if(s[0]===e){n=s;break}}if(!U(n)||2>n.length)return"";var o=n[1];try{o=decodeURIComponent(o)}catch{A.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},Zi=function(t,e,n){if(!t||!e||!e.length)return t;for(var i=t.split("#"),r=i[1],s=(i[0]||"").split("?"),o=s[1],a=s[0],l=(o||"").split("&"),u=[],c=0;l.length>c;c++){var d=l[c].split("=");U(d)&&(e.includes(d[0])?u.push(d[0]+"="+n):u.push(l[c]))}var h=a;return o!=null&&(h+="?"+u.join("&")),r!=null&&(h+="#"+r),h},os=function(t,e){var n=t.match(new RegExp(e+"=([^&]*)"));return n?n[1]:null},_f=(t,e)=>t>=e&&ud(),yf=(t,e,n,i)=>{if(t===0){if(ud()){var r=e+1;return r===n&&i(),r}return e}return 0},wr="https?://(.*)",ri=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],em=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...ri],Xi="",tm=["li_fat_id"];function wf(t,e,n){if(!P)return{};var i,r=e?[...ri,...n||[]]:[],s=bf(Zi(P.URL,r,Xi),t),o=(i={},ie(tm,(function(a){var l=nf(a);i[a]=l||null})),i);return fe(o,s)}function bf(t,e){var n=em.concat(e||[]),i={};return ie(n,(function(r){var s=ii(t,r);i[r]=s||null})),i}function Ef(t){var e=(function(s){return s?s.search(wr+"google.([^/?]*)")===0?"google":s.search(wr+"bing.com")===0?"bing":s.search(wr+"yahoo.com")===0?"yahoo":s.search(wr+"duckduckgo.com")===0?"duckduckgo":null:null})(t),n=e!="yahoo"?"q":"p",i={};if(!Ke(e)){i.$search_engine=e;var r=P?ii(P.referrer,n):"";r.length&&(i.ph_keyword=r)}return i}function qc(){return navigator.language||navigator.userLanguage}var as="$direct";function Sf(){return P?.referrer||as}function xf(t,e,n){n===void 0&&(n=!1);var i=t?[...ri,...e||[]]:[],r=n?fn(me?.href):me?.href,s=r?.substring(0,1e3);return{r:Sf().substring(0,1e3),u:s?Zi(s,i,Xi):void 0}}function If(t,e){var n;e===void 0&&(e=!1);var i=t.r,r=t.u,s=e?fn(r):r,o={$referrer:i,$referring_domain:i==null?void 0:i==as?as:(n=ss(i))==null?void 0:n.host};if(s){o.$current_url=s;var a=ss(s);o.$host=a?.host,o.$pathname=a?.pathname;var l=bf(s);fe(o,l)}if(i){var u=Ef(i);fe(o,u)}return o}function kf(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function nm(){try{return new Date().getTimezoneOffset()}catch{return}}var im={flags:ji,surveys:Xr},rm=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],Hn="main";class xo{constructor(e,n,i){if(i===void 0&&(i=!0),this.ci={},this.fi=!1,this.pi=!1,this.Ne=e,this.gi=i,this.props={},this.mi=void 0,this.yi=(s=>{var o="";return s.token&&(o=s.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),s.persistence_name?"ph_"+s.persistence_name:"ph_"+o+"_posthog"})(e),this.ii=this.bi(e),this.pi=this.wi(e),this.load(),e.debug&&A.info("Persistence loaded",e.persistence,I({},this.props)),this.update_config(e,e,n),this.save(),w){var r=()=>this.flush();ve(w,"beforeunload",r,{capture:!1}),ve(w,"pagehide",r,{capture:!1})}}ki(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return ke(n)&&n>0?n:0}isDisabled(){return!!this.xi}bi(e){rm.indexOf(e.persistence.toLowerCase())===-1&&(A.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var n,i=(function(o,a){o===void 0&&(o=[]),a===void 0&&(a=!1);var l=[...Ng,...o];return I({},le,{H(u){try{var c={};try{c=qt.H(u)||{}}catch{}var d,h=JSON.parse(le.P(u)||"{}");if(a){var f={};for(var p in c){var g=c[p];Ke(g)||g===""||(f[p]=g)}d=fe(h,f)}else d=fe(c,h);return le.F(u,d),d}catch{}return null},F(u,c,d,h,f,p){var g=le.F(u,c,void 0,void 0,p);try{var m={};l.forEach((v=>{c[v]&&(m[v]=c[v])})),Object.keys(m).length&&qt.F(u,m,d,h,f,p)}catch(v){le.j(v)}return g},q(u,c){try{w?.localStorage.removeItem(u),qt.q(u,c)}catch(d){le.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),r=!1,s=e.persistence.toLowerCase();return s==="localstorage"&&le.N()?(n=le,r=!0):s==="localstorage+cookie"&&i.N()?(n=i,r=!0):s==="sessionstorage"&&be.N()?n=be:s==="memory"?n=Og:s==="cookie"?n=qt:i.N()?(n=i,r=!0):n=qt,this.fi=r,n}Si(e){return this.yi+"__"+e}wi(e){return this.fi&&!!e.split_storage}properties(){var e={};return ie(this.props,((n,i)=>{var r=yn(i);if(!r||r.exposure==="event"){if(r!=null&&r.shouldSkipFromEventProperties!=null&&r.shouldSkipFromEventProperties(n))return;e[i]=n}})),e}load(){if(!this.xi){var e=this.ii.H(this.yi);e&&(this.props=fe({},e)),this.pi&&this.Ci()}}Ci(){for(var e of So){var n=le.H(this.Si(e));if(n&&!Kt(n)){var i=this.Mi(e);i.persisted=!0,this.Ti(e)||(i.fingerprint=this.Ei(n,e)),this.Ii(e,n)||fe(this.props,n)}}}Ti(e){return Object.keys(this.props).some((n=>{var i;return((i=yn(n))==null?void 0:i.storageGroup)===e}))}Ii(e,n){var i=im[e];if(!i)return!1;var r=n[i],s=this.props[i];return ke(r)&&ke(s)&&s>r}refreshKey(e){var n;if(!this.xi){var i=this.pi?(n=yn(e))==null?void 0:n.storageGroup:void 0,r=i?le.H(this.Si(i)):this.ii.H(this.yi);if(r&&e in r)this.Pi(e,r[e]);else{if(i){var s=this.ii.H(this.yi);if(s&&e in s)return void this.Pi(e,s[e])}this.Ri(e)}}}save(){if(!this.xi){var e=this.ki();e>0?C(this.Ai)&&(this.Ai=setTimeout((()=>{this.Ai=void 0,this.Fi()}),e)):this.Fi()}}flush(){C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0,this.Fi())}Fi(){this.xi||(this.pi?this.Li():this.Oi(this.ii,this.yi,this.props,Hn))}Li(){var e=this.Di(),n=e.main,i=e.groups;for(var r of(this.Oi(this.ii,this.yi,n,Hn),So)){var s,o=i[r];(!Kt(o)||(s=this.ci[r])!=null&&s.persisted)&&this.Oi(le,this.Si(r),o,r)}}Di(){var e={},n={flags:{},surveys:{}};return ie(this.props,((i,r)=>{var s,o=(s=yn(r))==null?void 0:s.storageGroup;o?n[o][r]=i:e[r]=i})),{main:e,groups:n}}Ei(e,n){if(n===Hn)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var i={};return ie(e,((r,s)=>{var o;i[s]=(o=yn(s))!=null&&o.volatile?"__volatile__":r})),JSON.stringify(i)}Oi(e,n,i,r){var s=this.Mi(r);if(r===Hn||s.dirty||C(s.fingerprint)){var o;try{if((o=this.Ei(i,r))===s.fingerprint)return void(s.dirty=!1)}catch{o=void 0}e.F(n,i,this.$i,this.Ni,this.qi,this.Ne.debug)?(s.dirty=!1,r!==Hn&&(s.persisted=!0),C(o)||(s.fingerprint=o)):this.Ne.debug&&A.warn('failed to persist storage entry "'+n+'"; will retry on next save')}}remove(e){var n=(e===void 0?{}:e).keepGroupEntries,i=n!==void 0&&n;if(C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0),this.ii.q(this.yi,!1),this.ii.q(this.yi,!0),!i&&this.gi)for(var r of So)le.q(this.Si(r));i?delete this.ci[Hn]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,n,i){if(he(e)){C(n)&&(n="None"),this.$i=C(i)?this.ji:i;var r=!1;if(ie(e,((s,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==n||(this.Pi(o,s),r=!0)})),r)return this.save(),!0}return!1}register(e,n){if(he(e)){this.$i=C(n)?this.ji:n;var i=!1;if(ie(e,((r,s)=>{e.hasOwnProperty(s)&&(this.props[s]!==r||he(r)||U(r))&&(this.Pi(s,r),i=!0)})),i)return this.save(),!0}return!1}unregister(e){var n=typeof e=="string"?[e]:e,i=!1;for(var r of n)r in this.props&&(this.Ri(r),i=!0);i&&this.save()}update_campaign_params(){var e=P?.URL;if(e!==this.mi){var n=wf(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);Kt(ll(n))||this.register(n),this.mi=e}}update_search_keyword(){var e;this.register((e=P?.referrer)?Ef(e):{})}update_referrer_info(){var e;this.register_once({$referrer:Sf(),$referring_domain:P!=null&&P.referrer&&((e=ss(P.referrer))==null?void 0:e.host)||as},void 0)}set_initial_person_info(){this.props[fa]||this.props[ha]||this.register_once({[Qr]:xf(this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties,this.Ne.disable_capture_url_hashes)},void 0)}get_initial_props(){var e={};ie([ha,fa],(r=>{var s=this.props[r];s&&ie(s,(function(o,a){e["$initial_"+Go(a)]=o}))}));var n=this.props[Qr];if(n){var i=(function(r,s){s===void 0&&(s=!1);var o=If(r,s),a={};return ie(o,(function(l,u){a["$initial_"+Go(u)]=l})),a})(n,this.Ne.disable_capture_url_hashes);fe(e,i)}return e}safe_merge(e){return ie(this.props,(function(n,i){i in e||(e[i]=n)})),e}update_config(e,n,i){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!i),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var r=e.persistence!==n.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((h,f)=>h===d[f]))})(e.cookie_persisted_properties||[],n.cookie_persisted_properties||[]),s=r?this.bi(e):this.ii,o=this.wi(e);if(r||o!==this.pi){var a=this.props;this.clear(),this.ii=s,this.pi=o,this.props=a,this.save()}}set_disabled(e){this.xi=e,this.xi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ni&&(this.Ni=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this.qi&&(this.qi=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,n){var i=this.props[Ri]||{};i[e]=n,this.Pi(Ri,i),this.save()}remove_event_timer(e){var n=this.props[Ri]||{},i=n[e];return C(i)||(delete n[e],this.Pi(Ri,n),this.save()),i}get_property(e){return this.props[e]}set_property(e,n){this.Pi(e,n),this.save()}Pi(e,n){var i;this.props[e]=n,(i=yn(e))!=null&&i.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var n,i=(n=yn(e))==null?void 0:n.storageGroup;i&&(this.Mi(i).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function br(t){var e=!0;return{dispose(){if(e){e=!1;var n=t();n&&De(n.then)&&n.then(void 0,(()=>{}))}}}}var je={GZipJS:"gzip-js",Base64:"base64"},wi={Activation:"events",Cancellation:"cancelEvents"},Io={Popover:"popover",API:"api",Widget:"widget"},zt={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},ko={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},_a={Popover:"popover",Inline:"inline"},sm={SHOWN:"product tour shown"},zc={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},Vc=pe("[RateLimiter]");class om{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=n=>{var i=n.text;if(i&&i.length)try{(JSON.parse(i).quota_limited||[]).forEach((r=>{Vc.info((r||"events")+" is quota limited."),this.serverLimits[r]=new Date().getTime()+6e4}))}catch(r){return void Vc.warn('could not rate limit - continuing. Error: "'+r?.message+'"',{text:i})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var n,i,r;e===void 0&&(e=!1);var s=this.captureEventsBurstLimit,o=this.captureEventsPerSecond,a=new Date().getTime(),l=(n=(i=this.instance.persistence)==null?void 0:i.get_property(da))!==null&&n!==void 0?n:{tokens:s,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>s&&(l.tokens=s);var u=1>l.tokens;if(u||e||(l.tokens=Math.max(0,l.tokens-1)),u&&!e){var c=(ke(l.dropped)?l.dropped:0)+1;l.dropped=c,!this.lastEventRateLimited&&this.Hi(c)&&(l.dropped=0)}return this.lastEventRateLimited=u,(r=this.instance.persistence)==null||r.set_property(da,l),{isRateLimited:u,remainingTokens:l.tokens}}Ui(e){var n=this.instance.config.property_denylist;return!U(n)||!n.includes(e)}zi(){var e;if(this.Ui("$current_url")&&this.Ui("$pathname")&&me!=null&&me.pathname)return""+((e=me.origin)!==null&&e!==void 0?e:"")+me.pathname}Hi(e){var n,i,r=this.captureEventsBurstLimit,s=this.captureEventsPerSecond,o=this.zi(),a=this.Ui("$session_id")?(n=(i=this.instance).get_session_id)==null?void 0:n.call(i):void 0,l=[e+" event(s) dropped since the last warning",o?"triggered on "+o:void 0,a?"session "+a:void 0].filter(Boolean).join(", ");return!!this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited: "+l+". Config is set to "+s+" events per second and "+r+" events burst limit."},{skip_client_rate_limiting:!0})}isServerRateLimited(e){var n=this.serverLimits[e||"events"]||!1;return n!==!1&&new Date().getTime()e(this.remoteConfig))):e()}Vi(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:e})}load(){try{if(this.remoteConfig)return an.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void an.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return an.info("No config found after loading remote JS config. Falling back to JSON."),void this.Vi((n=>{this.Zi(n.json,n),this.Gi()}));this.Zi(e),this.Gi()}))}catch(e){an.error("Error loading remote config",e),this.Zi()}}stop(){this.Ki&&(clearInterval(this.Ki),this.Ki=void 0)}refresh(){!this._instance.Qi()&&P&&P.visibilityState!=="hidden"&&this._instance.reloadFeatureFlags()}Gi(){var e;if(!this.Ki){var n=(e=this._instance.config.remote_config_refresh_interval_ms)!==null&&e!==void 0?e:3e5;n!==0&&(this.Ki=setInterval((()=>{this.refresh()}),n))}}Zi(e,n){!e&&n&&(n.statusCode===0?n.error||an.warn("Failed to fetch remote config from PostHog."):an.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(r){an.error("Error applying remote config",r)}if(e?.hasFeatureFlags!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var i;(i=this._instance.featureFlags)==null||i.ensureFlagsLoaded()}catch(r){an.error("Error loading feature flags",r)}}}var ct=Uint8Array,Ge=Uint16Array,si=Uint32Array,fl=new ct([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]),hl=new ct([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]),Gc=new ct([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Af=function(t,e){for(var n=new Ge(31),i=0;31>i;++i)n[i]=e+=1<i;++i)for(var s=n[i];n[i+1]>s;++s)r[s]=s-n[i]<<5|i;return[n,r]},Pf=Af(fl,2),ya=Pf[1];Pf[0][28]=258,ya[258]=28;for(var Kc=Af(hl,0)[1],Ff=new Ge(32768),_e=0;32768>_e;++_e){var Wn=(43690&_e)>>>1|(21845&_e)<<1;Ff[_e]=((65280&(Wn=(61680&(Wn=(52428&Wn)>>>2|(13107&Wn)<<2))>>>4|(3855&Wn)<<4))>>>8|(255&Wn)<<8)>>>1}var Hi=function(t,e,n){for(var i=t.length,r=0,s=new Ge(e);i>r;++r)++s[t[r]-1];var o,a=new Ge(e);for(r=0;e>r;++r)a[r]=a[r-1]+s[r-1]<<1;for(o=new Ge(i),r=0;i>r;++r)o[r]=Ff[a[t[r]-1]++]>>>15-t[r];return o},$n=new ct(288);for(_e=0;144>_e;++_e)$n[_e]=8;for(_e=144;256>_e;++_e)$n[_e]=9;for(_e=256;280>_e;++_e)$n[_e]=7;for(_e=280;288>_e;++_e)$n[_e]=8;var ls=new ct(32);for(_e=0;32>_e;++_e)ls[_e]=5;var am=Hi($n,9),lm=Hi(ls,5),Rf=function(t){return(t/8>>0)+(7&t&&1)},Tf=function(t,e,n){(n==null||n>t.length)&&(n=t.length);var i=new(t instanceof Ge?Ge:t instanceof si?si:ct)(n-e);return i.set(t.subarray(e,n)),i},Ot=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8},bi=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8,t[i+2]|=n>>>16},Co=function(t,e){for(var n=[],i=0;t.length>i;++i)t[i]&&n.push({s:i,f:t[i]});var r=n.length,s=n.slice();if(!r)return[new ct(0),0];if(r==1){var o=new ct(n[0].s+1);return o[n[0].s]=1,[o,1]}n.sort((function(b,k){return b.f-k.f})),n.push({s:-1,f:25001});var a=n[0],l=n[1],u=0,c=1,d=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=r-1;)a=n[n[d].f>n[u].f?u++:d++],l=n[u!=c&&n[d].f>n[u].f?u++:d++],n[c++]={s:-1,f:a.f+l.f,l:a,r:l};var h=s[0].s;for(i=1;r>i;++i)s[i].s>h&&(h=s[i].s);var f=new Ge(h+1),p=wa(n[c-1],f,0);if(p>e){i=0;var g=0,m=p-e,v=1<i;++i){var E=s[i].s;if(e>=f[E])break;g+=v-(1<>>=m;g>0;){var S=s[i].s;e>f[S]?g-=1<=0&&g;--i){var _=s[i].s;f[_]==e&&(--f[_],++g)}p=e}return[new ct(f),p]},wa=function(t,e,n){return t.s==-1?Math.max(wa(t.l,e,n+1),wa(t.r,e,n+1)):e[t.s]=n},Yc=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new Ge(++e),i=0,r=t[0],s=1,o=function(l){n[i++]=l},a=1;e>=a;++a)if(t[a]==r&&a!=e)++s;else{if(!r&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(r),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(r);s=1,r=t[a]}return[n.subarray(0,i),e]},Ei=function(t,e){for(var n=0,i=0;e.length>i;++i)n+=t[i]*e[i];return n},ba=function(t,e,n){var i=n.length,r=Rf(e+2);t[r]=255&i,t[r+1]=i>>>8,t[r+2]=255^t[r],t[r+3]=255^t[r+1];for(var s=0;i>s;++s)t[r+s+4]=n[s];return 8*(r+4+i)},Jc=function(t,e,n,i,r,s,o,a,l,u,c){Ot(e,c++,n),++r[256];for(var d=Co(r,15),h=d[0],f=d[1],p=Co(s,15),g=p[0],m=p[1],v=Yc(h),E=v[0],S=v[1],_=Yc(g),b=_[0],k=_[1],T=new Ge(19),x=0;E.length>x;++x)T[31&E[x]]++;for(x=0;b.length>x;++x)T[31&b[x]]++;for(var F=Co(T,7),$=F[0],O=F[1],L=19;L>4&&!$[Gc[L-1]];--L);var N,K,V,M,R=u+5<<3,Z=Ei(r,$n)+Ei(s,ls)+o,Ce=Ei(r,h)+Ei(s,g)+o+14+3*L+Ei(T,$)+(2*T[16]+3*T[17]+7*T[18]);if(Z>=R&&Ce>=R)return ba(e,c,t.subarray(l,l+u));if(Ot(e,c,1+(Z>Ce)),c+=2,Z>Ce){N=Hi(h,f),K=h,V=Hi(g,m),M=g;var oe=Hi($,O);for(Ot(e,c,S-257),Ot(e,c+5,k-1),Ot(e,c+10,L-4),c+=14,x=0;L>x;++x)Ot(e,c+3*x,$[Gc[x]]);c+=3*L;for(var ye=[E,b],$e=0;2>$e;++$e){var ae=ye[$e];for(x=0;ae.length>x;++x)Ot(e,c,oe[Ie=31&ae[x]]),c+=$[Ie],Ie>15&&(Ot(e,c,ae[x]>>>5&127),c+=ae[x]>>>12)}}else N=am,K=$n,V=lm,M=ls;for(x=0;a>x;++x)if(i[x]>255){var Ie;bi(e,c,N[257+(Ie=i[x]>>>18&31)]),c+=K[Ie+257],Ie>7&&(Ot(e,c,i[x]>>>23&31),c+=fl[Ie]);var Se=31&i[x];bi(e,c,V[Se]),c+=M[Se],Se>3&&(bi(e,c,i[x]>>>5&8191),c+=hl[Se])}else bi(e,c,N[i[x]]),c+=K[i[x]];return bi(e,c,N[256]),c+K[256]},cm=new si([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),um=(function(){for(var t=new si(256),e=0;256>e;++e){for(var n=e,i=9;--i;)n=(1&n&&3988292384)^n>>>1;t[e]=n}return t})(),Ao=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8};function dm(t,e){e===void 0&&(e={});var n=(function(){var d=4294967295;return{p(h){for(var f=d,p=0;h.length>p;++p)f=um[255&f^h[p]]^f>>>8;d=f},d(){return 4294967295^d}}})(),i=t.length;n.p(t);var r,s,o,a,l,u=(a=10+((r=e).filename&&r.filename.length+1||0),l=8,(function(d,h,f,p,g,m){var v=d.length,E=new ct(p+v+5*(1+Math.floor(v/7e3))+g),S=E.subarray(p,E.length-g),_=0;if(!h||8>v)for(var b=0;v>=b;b+=65535){var k=b+65535;v>k?_=ba(S,_,d.subarray(b,k)):(S[b]=!0,_=ba(S,_,d.subarray(b,v)))}else{for(var T=cm[h-1],x=T>>>13,F=8191&T,$=(1<b;++b){var Ie=V(b),Se=32767&b,Be=L[Ie];if(O[Se]=Be,L[Ie]=Se,b>=$e){var wt=v-b;if((Ce>7e3||ye>24576)&&wt>423){_=Jc(d,S,0,M,R,Z,oe,ye,ae,b-ae,_),ye=Ce=oe=0,ae=b;for(var ge=0;286>ge;++ge)R[ge]=0;for(ge=0;30>ge;++ge)Z[ge]=0}var Ye=2,bt=0,mn=F,Re=Se-Be&32767;if(wt>2&&Ie==V(b-Re))for(var Pe=Math.min(x,wt)-1,$t=Math.min(32767,b),Bn=Math.min(258,wt);$t>=Re&&--mn&&Se!=Be;){if(d[b+Ye]==d[b+Ye-Re]){for(var qe=0;Bn>qe&&d[b+qe]==d[b+qe-Re];++qe);if(qe>Ye){if(Ye=qe,bt=Re,qe>Pe)break;var Dn=Math.min(Re,qe-2),Mt=0;for(ge=0;Dn>ge;++ge){var Lt=b-Re+ge+32768&32767,ut=Lt-O[Lt]+32768&32767;ut>Mt&&(Mt=ut,Be=Lt)}}}Re+=(Se=Be)-(Be=O[Se])+32768&32767}if(bt){M[ye++]=268435456|ya[Ye]<<18|Kc[bt];var sn=31&ya[Ye],gi=31&Kc[bt];oe+=fl[sn]+hl[gi],++R[257+sn],++Z[gi],$e=b+Ye,++Ce}else M[ye++]=d[b],++R[d[b]]}}_=Jc(d,S,!0,M,R,Z,oe,ye,ae,b-ae,_)}return Tf(E,0,p+Rf(_)+g)})(s=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):12+o.mem,a,l)),c=u.length;return(function(d,h){var f=h.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>h.level?4:h.level==9?2:0,d[9]=3,h.mtime!=0&&Ao(d,4,Math.floor(new Date(h.mtime||Date.now())/1e3)),f){d[3]=8;for(var p=0;f.length>=p;++p)d[p+10]=f.charCodeAt(p)}})(u,e),Ao(u,c-8,n.d()),Ao(u,c-4,i),u}var fm=!!qo||!!Za,$f="text/plain",Mr=!1,Mf=(t,e)=>{var n=t.split("#"),i=n[1],r=n[0].split("?"),s=r[0],o=r[1];if(!o)return t;var a=o.split("&").filter((l=>l.split("=")[0]!==e)).join("&");return s+(a?"?"+a:"")+(i?"#"+i:"")},ks=function(t,e,n){var i;n===void 0&&(n=!0);var r=t.split("?"),s=r[0],o=r[1],a=I({},e),l=(i=o?.split("&").map((c=>{var d,h=c.split("="),f=h[0],p=n&&(d=a[f])!==null&&d!==void 0?d:h[1];return delete a[f],f+"="+p})))!==null&&i!==void 0?i:[],u=(function(c,d){var h,f;d===void 0&&(d="&");var p=[];return ie(c,(function(g,m){C(g)||C(m)||m==="undefined"||(h=encodeURIComponent((v=>v instanceof File)(g)?g.name:g.toString()),f=encodeURIComponent(m),p[p.length]=f+"="+h)})),p.join(d)})(a);return u&&l.push(u),l.length>0?s+"?"+l.join("&"):s},Po=t=>{if(t.Ji)return t.Ji;var e=t.data,n=t.compression;if(e){if(n===je.GZipJS){var i=dm((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new ct(a.length+(a.length>>>1)),d=0,h=function(m){c[d++]=m},f=0;u>f;++f){if(d+5>c.length){var p=new ct(d+8+(u-f<<1));p.set(c),c=p}var g=a.charCodeAt(f);128>g?h(g):2048>g?(h(192|g>>>6),h(128|63&g)):g>55295&&57344>g?(h(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++f))>>>18),h(128|g>>>12&63),h(128|g>>>6&63),h(128|63&g)):(h(224|g>>>12),h(128|g>>>6&63),h(128|63&g))}return Tf(c,0,d)})(Yn(e)),{mtime:0});return{contentType:$f,body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),estimatedSize:i.byteLength}}if(n===je.Base64){var r=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(Yn(e)),s=(a=>"data="+encodeURIComponent(typeof a=="string"?a:Yn(a)))(r);return{contentType:"application/x-www-form-urlencoded",body:s,estimatedSize:new Blob([s]).size}}var o=Yn(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},Lf=t=>{var e,n,i=()=>t.transport==="sendBeacon"?{url:ks(t.url,{compression:je.Base64}),encodedBody:Po(I({},t,{compression:je.Base64,Ji:void 0}))}:{url:Mf(t.url,"compression"),encodedBody:Po(I({},t,{compression:void 0,Ji:void 0}))};try{e=Po(t)}catch(r){if(mc(t.compression,ii(t.url,"compression")))return A.error("Failed to gzip request body, sending uncompressed payload",r),i();throw r}return e&&mc(t.compression,ii(t.url,"compression"))&&!((n=e.body)instanceof ArrayBuffer?zo(new Uint8Array(n)):ArrayBuffer.isView(n)&&zo(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)))?(Mr=!0,i()):{url:t.url,encodedBody:e}},Nf=t=>{try{return Lf(t)}catch(e){return A.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},hm=(function(){var t=se((function*(e){var n=Yn(e.data),i=yield(function(s,o,a){return Vo.apply(this,arguments)})(n,ne.DEBUG,{rethrow:!0});if(!i)return e;var r=yield i.arrayBuffer();return I({},e,{Ji:{contentType:$f,body:r,estimatedSize:r.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),pm=/Failed to fetch|NetworkError|Load failed/i,Of=t=>t?.name==="TypeError"&&pm.test(t?.message||""),Bf=t=>{var e=Nf(t);if(e){var n=e.url,i=e.encodedBody,r=i??{},s=r.contentType,o=r.body,a=r.estimatedSize,l=new Headers;ie(t.headers,(function(p,g){l.append(g,p)})),s&&l.append("Content-Type",s);var u=null,c=!1;if(uc){var d=new uc;u={signal:d.signal,timeout:setTimeout((()=>{var p,g;c=!0,d.abort((p=t.timeout,(g=new Error("PostHog request timed out"+(p?" after "+p+"ms":""))).name="AbortError",g))}),t.timeout)}}var h=p=>{c&&p?.name==="AbortError"||Of(p)?A.warn(p):A.error(p),t.callback==null||t.callback({statusCode:0,error:p})};try{var f;Za(n,I({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(f=u)==null?void 0:f.signal},t.fetchOptions)).then((p=>p.text().then((g=>{var m={statusCode:p.status,text:g};if(p.status===200)try{m.json=JSON.parse(g)}catch(v){A.error(v)}t.callback==null||t.callback(m)})))).catch(h).finally((()=>u?clearTimeout(u.timeout):null))}catch(p){u&&clearTimeout(u.timeout),h(p)}}},Ea=t=>{try{var e,n=Lf(t),i=n.url,r=n.encodedBody,s=r??{},o=s.body,a=s.estimatedSize;if(!o)return;var l=o instanceof Blob?o:new Blob([o],{type:s.contentType});if(Ue.sendBeacon(i,l))return;var u=U(t.data)?t.data:(e=t.data)==null?void 0:e.batch;if(U(u)&&u.length>1&&(a??0)>16384){var c=Math.ceil(u.length/2),d=h=>U(t.data)?h:I({},t.data,{batch:h});return Ea(I({},t,{data:d(u.slice(0,c))})),void Ea(I({},t,{data:d(u.slice(c))}))}A.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),Bf(I({},t,{Yi:!0}))}catch(h){A.warn("Beacon send failed",h)}},Zc=(t,e,n,i)=>{var r=i==="query"?e==="POST"?"sent_at":"_":void 0;return ks(n===je.GZipJS?Mf(t,"compression"):t,I({},r?{[r]:Date.now().toString()}:{},n===je.GZipJS?{}:{compression:n}))},Lr=[];Za&&Lr.push({transport:"fetch",method:Bf}),qo&&Lr.push({transport:"XHR",method(t){var e=Nf(t);if(e){var n=new qo,i=e.encodedBody;n.open(t.method||"GET",e.url,!0);var r=i??{},s=r.contentType,o=r.body;ie(t.headers,(function(a,l){n.setRequestHeader(l,a)})),s&&n.setRequestHeader("Content-Type",s),t.timeout&&(n.timeout=t.timeout),n.onreadystatechange=()=>{if(n.readyState===4){var a={statusCode:n.status,text:n.responseText};if(n.status===200)try{a.json=JSON.parse(n.responseText)}catch{}t.callback==null||t.callback(a)}},n.send(o)}}}),Ue!=null&&Ue.sendBeacon&&Lr.push({transport:"sendBeacon",method:Ea});var Sa=3e3;class gm{constructor(e,n){this.Xi=!0,this.tr=[],this.er=At(n?.flush_interval_ms||Sa,250,5e3,A.createLogger("flush interval"),Sa),this.ir=e}enqueue(e){this.tr.push(e),this.rr||this.nr()}unload(){this.sr();var e=this.tr.length>0?this.ar():{},n=Object.values(e);[...n.filter((i=>i.url.indexOf("/e")===0)),...n.filter((i=>i.url.indexOf("/e")!==0))].map((i=>{this.lr(I({},i,{transport:"sendBeacon"}))}))}enable(){this.Xi=!1,this.nr()}nr(){var e=this;this.Xi||(this.rr=setTimeout((()=>{if(this.sr(),this.tr.length>0){var n=this.ar(),i=function(){var s=n[r],o=new Date().getTime();s.data&&U(s.data)&&ie(s.data,(a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp})),e.lr(s)};for(var r in n)i()}}),this.er))}lr(e){try{this.ir(e)}catch(n){A.error(n)}}sr(){clearTimeout(this.rr),this.rr=void 0}ar(){var e={};return ie(this.tr,(n=>{var i,r=n,s=(r?r.batchKey:null)||r.url;C(e[s])&&(e[s]=I({},r,{data:[]})),(i=e[s].data)==null||i.push(r.data)})),this.tr=[],e}}var mm=["retriesPerformedSoFar"];class vm{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!C(w)&&"onLine"in w.navigator&&(this.dr=w.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},ve(w,"online",this.vr),ve(w,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var n=e.retriesPerformedSoFar,i=dd(e,mm);Dt(n)&&(i.url=ks(i.url,{retry_count:n})),this._instance._send_request(I({},i,{callback:r=>{if(r.statusCode!==200&&(400>r.statusCode||r.statusCode>=500)){if((r.statusCode===0?3:10)>(n??0))return void this.At(I({retriesPerformedSoFar:n},i));r.statusCode===0&&A.warn("Request failed before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped retrying after "+(n??0)+" retries.")}i.callback==null||i.callback(r)}}))}At(e){var n=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=n+1;var i=(function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),c=Math.random()-.5;return Math.ceil(u+c*(u-l))})(n),r=Date.now()+i;this.tr.push({retryAt:r,requestOptions:e});var s="Enqueued failed request for retry in "+i;navigator.onLine||(s+=" (Browser is offline)"),A.warn(s),this.ur||(this.ur=!0,this.gr())}gr(){if(this.mr&&clearTimeout(this.mr),this.tr.length===0)return this.ur=!1,void(this.mr=void 0);this.mr=setTimeout((()=>{this.dr&&this.tr.length>0&&this.cr(),this.gr()}),this.hr)}cr(){var e=Date.now(),n=[],i=this.tr.filter((s=>e>s.retryAt||(n.push(s),!1)));if(this.tr=n,i.length>0)for(var r of i)this.retriableRequest(r.requestOptions)}unload(){for(var e of(this.mr&&(clearTimeout(this.mr),this.mr=void 0),this.ur=!1,C(w)||(this.vr&&(w.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(w.removeEventListener("offline",this.pr),this.pr=void 0)),this.tr)){var n=e.requestOptions;try{this._instance._send_request(I({},n,{transport:"sendBeacon"}))}catch(i){A.error(i)}}this.tr=[]}}class _m{constructor(e){this.yr=()=>{var n,i,r,s;this.br||(this.br={});var o=this.scrollElement(),a=this.scrollY(),l=o?Math.max(0,o.scrollHeight-o.clientHeight):0,u=a+(o?.clientHeight||0),c=o?.scrollHeight||0;this.br.lastScrollY=Math.ceil(a),this.br.maxScrollY=Math.max(a,(n=this.br.maxScrollY)!==null&&n!==void 0?n:0),this.br.maxScrollHeight=Math.max(l,(i=this.br.maxScrollHeight)!==null&&i!==void 0?i:0),this.br.lastContentY=u,this.br.maxContentY=Math.max(u,(r=this.br.maxContentY)!==null&&r!==void 0?r:0),this.br.maxContentHeight=Math.max(c,(s=this.br.maxContentHeight)!==null&&s!==void 0?s:0)},this._instance=e}get _r(){return this._instance.config.scroll_root_selector}getContext(){return this.br}resetContext(){var e=this.br;return setTimeout(this.yr,0),e}startMeasuringScrollPosition(){ve(w,"scroll",this.yr,{capture:!0}),ve(w,"scrollend",this.yr,{capture:!0}),ve(w,"resize",this.yr)}scrollElement(){if(!this._r)return w?.document.documentElement;var e=U(this._r)?this._r:[this._r];for(var n of e){var i=w?.document.querySelector(n);if(i)return i}}wr(e){var n=e==="y"?"scrollTop":"scrollLeft";if(this._r){var i=this.scrollElement();return i&&i[n]||0}return w?e==="y"?w.scrollY||w.pageYOffset||w.document.documentElement.scrollTop||0:w.scrollX||w.pageXOffset||w.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var ym=t=>xf(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class Xc{constructor(e,n,i,r){this.kr=s=>{var o=this.Sr();if(!o||o.sessionId!==s){var a={sessionId:s,props:this.Cr(this._instance)};this.Mr.register({[ua]:a})}},this._instance=e,this.Tr=n,this.Mr=i,this.Cr=r||ym,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[ua]}getSetOnceProps(){var e,n=(e=this.Sr())==null?void 0:e.props;return n?"r"in n?If(n,this._instance.config.disable_capture_url_hashes):{$referring_domain:n.referringDomain,$pathname:n.initialPathName,utm_source:n.utm_source,utm_campaign:n.utm_campaign,utm_medium:n.utm_medium,utm_content:n.utm_content,utm_term:n.utm_term}:{}}getSessionProps(){var e={};return ie(ll(this.getSetOnceProps()),((n,i)=>{i==="$current_url"&&(i="url"),e["$session_entry_"+Go(i)]=n})),e}}class pl{on(e,n){return this.Er[e]||(this.Er[e]=[]),this.Er[e].push(n),()=>{this.Er[e]=this.Er[e].filter((i=>i!==n))}}emit(e,n){for(var i of this.Er[e]||[])i(n);for(var r of this.Er["*"]||[])r(e,n)}constructor(){this.Er={}}}var Si=pe("[SessionId]");class Qc{on(e,n){return this.Ir.on(e,n)}constructor(e,n,i){var r;if(this.Pr=null,this.Rr=[],this.Ar=void 0,this.Fr=!1,this.Ir=new pl,this.Lr=(u,c)=>!(!Dt(u)||!Dt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===Wt)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Ne=e.config,this.Mr=e.persistence,this.Or=void 0,this.Dr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.$r=n||Ht,this.Nr=i||Ht;var s=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*At(this.Ne.session_idle_timeout_seconds||1800,60,36e3,Si.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.qr(),this.jr="ph_"+s+"_window_id",this.Br="ph_"+s+"_primary_window_exists",this.Hr()){var o=be.H(this.jr),a=be.H(this.Br);o&&!a?this.Or=o:be.q(this.jr),be.F(this.Br,!0)}if((r=this.Ne.bootstrap)!=null&&r.sessionID)try{var l=(u=>{var c=this.Ne.bootstrap.sessionID.replace(/-/g,"");if(c.length!==32)throw new Error("Not a valid UUID");if(c[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(c.substring(0,12),16)})();this.Ur(this.Ne.bootstrap.sessionID,new Date().getTime(),l)}catch(u){Si.error("Invalid sessionID in bootstrap",u)}this.zr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return C(this.Rr)&&(this.Rr=[]),this.Rr.push(e),this.Dr&&e(this.Dr,this.Or),()=>{this.Rr=this.Rr.filter((n=>n!==e))}}Hr(){return this.Ne.persistence!=="memory"&&!this.Mr.xi&&be.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&be.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?be.H(this.jr):null}Zr(e){var n=this.Pr;return!Ke(n)&&!Ke(e)&&5e3>Math.abs(e-n)}Ur(e,n,i){var r=n!==this._sessionActivityTimestamp,s=!(e!==this.Dr||i!==this._sessionStartTimestamp);this._sessionStartTimestamp=i,this._sessionActivityTimestamp=n,this.Dr=e,s&&!r||s&&this.Zr(n)||(this.Pr=n,this.Mr.register({[Kn]:[n,e,i]}))}Gr(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return Dt(n)&&n>0}Qr(){this.Gr()?this.Mr.refreshKey(Kn):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!Ke(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this.Pr){this.Qr();var n=this.Jr();n[1]===this.Dr&&n[2]===this._sessionStartTimestamp&&(this.Pr=this._sessionActivityTimestamp,this.Mr.register({[Kn]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],n=Dt(e)?e:0,i=Dt(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(n,i)}Xr(e){return this.Qr(),this.Lr(e,this.Yr())}Jr(){var e=this.Mr.props[Kn];return U(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Pr=null,clearTimeout(this.tn),this.tn=void 0,this.Ur(null,null,null)}destroy(){this.Fr=!0,this.Kr(),clearTimeout(this.tn),this.tn=void 0,this.Ar&&w&&(w.removeEventListener(ns,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&be.q(this.Br)},ve(w,ns,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=null),this.Ne.cookieless_mode===Wt)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var i=n||new Date().getTime(),r=this.Jr(),s=r[1],o=r[2],a=this.Yr(),l=this.Vr(),u=Dt(o)&&Math.abs(i-o)>864e5,c=!1,d=!1,h=!s,f=s,p=!h&&!e&&this.Lr(i,a);if(p){(p=this.Xr(i))||Si.info("cross-tab refresh kept the session alive",{sessionId:s});var g=this.Jr();s=g[1],o=g[2]}h||p||u?(s=this.$r(),l=this.Nr(),Si.info("new session ID generated",{sessionId:s,windowId:l,changeReason:{noSessionId:h,activityTimeout:p,sessionPastMaximumLength:u}}),o=i,c=!0):(l||(l=this.Nr(),c=!0),(d=s!==f)&&(Si.info("adopted cross-tab session id",{sessionId:s,windowId:l}),c=!0));var m=Dt(a)&&e&&!u?a:i,v=Dt(o)?o:new Date().getTime();this.Wr(l),this.Ur(s,m,v),e||this.qr();var E={noSessionId:h,activityTimeout:p,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((S=>S(s,l,E))),{sessionId:s,windowId:l,sessionStartTimestamp:v,changeReason:c?E:void 0,lastActivityTimestamp:a}}qr(){this.Fr||(clearTimeout(this.tn),this.tn=setTimeout((()=>{if(!this.Fr)if(this.Xr(new Date().getTime())){var e=this.Dr;this.resetSessionId(),this.Ir.emit("forcedIdleReset",{idleSessionId:e})}else this.qr()}),1.1*this.sessionTimeoutMs))}}var Df=function(t,e){if(!t)return!1;var n=t.userAgent;if(n&&_c(n,e))return!0;try{var i=t?.userAgentData;if(i!=null&&i.brands&&i.brands.some((r=>_c(r?.brand,e))))return!0}catch{}return!!t.webdriver};function jf(){return(jf=se((function*(){var t=Ue?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),n=e?.model;return X(n)&&n.length>0?n:void 0}catch(i){return void A.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",i)}}))).apply(this,arguments)}var cs=function(t,e){if(!(function(n){try{new RegExp(n)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function Fo(t,e,n){return Yn({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}var Uf={exact:(t,e)=>e.some((n=>t.some((i=>n===i)))),is_not:(t,e)=>e.every((n=>t.every((i=>n!==i)))),regex:(t,e)=>e.some((n=>t.some((i=>cs(n,i))))),not_regex:(t,e)=>e.every((n=>t.every((i=>!cs(n,i))))),icontains:(t,e)=>e.map(Er).some((n=>t.map(Er).some((i=>n.includes(i))))),not_icontains:(t,e)=>e.map(Er).every((n=>t.map(Er).every((i=>!n.includes(i))))),gt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>i>parseFloat(r)))})),lt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>it.toLowerCase();function Hf(t,e){return!t||Object.entries(t).every((n=>{var i=n[1],r=e?.[n[0]];if(C(r)||Ke(r))return!1;var s=[String(r)],o=Uf[i.operator];return!!o&&o(i.values,s)}))}var xa="custom",eu="i.posthog.com",wm=/^\/static\//;class bm{constructor(e){this.en={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,n=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return n||(n=this.apiHost.replace("."+eu,".posthog.com")),n==="https://app.posthog.com"?"https://us.posthog.com":n}get region(){return this.en[this.apiHost]||(this.en[this.apiHost]=/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"us":/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"eu":xa),this.en[this.apiHost]}rn(e){if(wm.test(e)){var n=this.instance.config.asset_host;if(typeof n=="string")return n.trim().replace(/\/$/,"")||void 0}}endpointFor(e,n){if(n===void 0&&(n=""),n&&(n=n[0]==="/"?n:"/"+n),e==="ui")return this.uiHost+n;if(e==="flags")return this.flagsApiHost+n;if(e==="assets"){var i=this.rn(n);if(i)return""+i+n}if(this.region===xa)return this.apiHost+n;var r=eu+n;switch(e){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}}function Wf(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var Q=pe("[Surveys]"),qf="seenSurvey_",zf=t=>{try{var e=(n=>((i,r)=>""+qf+(function(s){return s.current_iteration&&s.current_iteration>0?s.id+"_"+s.current_iteration:s.id})(r))(0,n))(t);if(localStorage.getItem(e))return;localStorage.setItem(e,"true")}catch(n){Q.error("Failed to persist survey seen state",n)}},Em=[Io.Popover,Io.Widget,Io.API],Sm={ignoreConditions:!1,ignoreDelay:!1,displayType:_a.Popover},xm=pe("[PostHog ExternalIntegrations]"),Im={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class km{constructor(e){this._instance=e}ai(e,n){var i;(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,e,(r=>{if(r)return xm.error("failed to load script",r);n()}))}startIfEnabledOrStop(){var e=this,n=function(){var s,o,a,l=i[0],u=i[1];!u||(s=B.__PosthogExtensions__)!=null&&(s=s.integrations)!=null&&s[l]||e.ai(Im[l],(()=>{var c;(c=B.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=B.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=B.__PosthogExtensions__)==null||(a=a.integrations)==null||(a=a[l])==null||a.stop())};for(var i of Object.entries((r=this._instance.config.integrations)!==null&&r!==void 0?r:{})){var r;n()}}}class Cm{constructor(e,n){this.rt=e,this.nn=n,this.sn=new Map,this.an=!1}add(e){var n=this;return se((function*(){if(n.an)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(n.sn.has(e.name))throw new Error('Browser extension "'+e.name+'" is already registered');n.sn.set(e.name,e);try{var i=e.setup(n.nn);i&&(yield i)}catch(s){var r=n.sn.get(e.name)===e;r&&n.sn.delete(e.name),n.rt.error('Failed to set up browser extension "'+e.name+'"',s),r&&n.ln(e)}}))()}dispose(){if(!this.an){this.an=!0;var e=Array.from(this.sn.values()).reverse();for(var n of(this.sn.clear(),e))this.ln(n)}}ln(e){try{var n=e.dispose==null?void 0:e.dispose();n&&De(n.then)&&n.then(void 0,(i=>{this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}))}catch(i){this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}}}class Am{constructor(e){this._instance=e}initialize(){}get(e){var n=this._instance.persistence;if(typeof e=="string")return n?.get_property(e);var i={};for(var r of e){var s=n?.get_property(r);C(s)||(i[r]=s)}return i}set(e,n){var i;(i=this._instance.persistence)==null||i.register(typeof e=="string"?{[e]:n}:e)}remove(e){var n;(n=this._instance.persistence)==null||n.unregister(e)}}var tu="extensionsRemoteConfig";class Pm{constructor(e){this.an=!1,this.instance=e,this.rt=A,this.un=e.hn,this.kv=new Am(e),this.onEvent=n=>br(this.instance.on("eventCaptured",(i=>{try{n({event:i.event,properties:i.properties})}catch(r){this.rt.error("Browser extension event listener failed",r)}}))),this.onRemoteConfig=n=>{if(this.an)return br((()=>{}));var i=s=>{try{n(s)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},r=this.instance.dn.on(tu,i);return this.un&&i(this.un),br(r)},this.vn=new Cm(A.createLogger("[BrowserExtensions]"),this)}get logger(){return this.rt}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return(e=this.instance.get_property(Yi))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(Yi);return typeof e=="string"?e:void 0}get library(){return{name:ne.LIB_NAME,version:ne.LIB_VERSION}}get initialPersonProperties(){var e,n;return(e=(n=this.instance.persistence)==null?void 0:n.get_initial_props())!==null&&e!==void 0?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,n,i,r,s=(e=this.instance.sessionManager)==null?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:(n=s?.sessionId)!==null&&n!==void 0?n:"",windowId:(i=s?.windowId)!==null&&i!==void 0?i:"",sessionStartTimestamp:(r=s?.sessionStartTimestamp)!==null&&r!==void 0?r:0}}catch{return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get projectToken(){return this.instance.config.token}add(e){return this.vn.add(e)}capture(e,n,i){var r=this;return se((function*(){i?r.instance.capture(e,n,{timestamp:i.timestamp,uuid:i.uuid,$set:i.set,$set_once:i.setOnce}):r.instance.capture(e,n)}))()}registerDynamicEventProperties(e){return br(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(tu,e))}sendRequest(e,n){var i=this;return se((function*(){var r;n===void 0&&(n={});var s=i.instance.requestRouter.endpointFor((r=n.target)!==null&&r!==void 0?r:"api",e),o={method:n.method,url:n.query?ks(s,n.query):s,data:n.body,headers:n.headers,timeout:n.timeoutMs,fireCallbackOnDrop:!0,transport:n.transport,compression:n.compression,timestampMode:n.sentAt};return n.transport==="sendBeacon"?(i.instance._send_request(o),{statusCode:202}):new Promise((a=>{o.callback=a,i.instance._send_request(o)}))}))()}dispose(){this.an||(this.an=!0,this.vn.dispose())}}var Wi={},Ro=0,us=()=>{},nu='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',xi="Surveys module not available",iu="sanitize_properties is deprecated. Use before_send instead",Vf="Invalid value for property_denylist config: ",Fm=["token","distinct_id",Xd],Gn="posthog",Gf=!fm&&Ve?.indexOf("MSIE")===-1&&Ve?.indexOf("Mozilla")===-1,To=t=>{var e;return I({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:Rg(P?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:us,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:t??"unset",__preview_deferred_init_extensions:!1,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:me&&X(me?.search)&&me.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disableDeviceModel:!1,disable_external_dependency_loading:!1,strict_script_versioning:!1,enable_recording_console_log:void 0,secure_cookie:(w==null||(e=w.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(n){A.error("Bad HTTP status: "+n.statusCode+" "+n.text)},get_device_id:n=>n,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:pa,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:Sa},error_tracking:{},_onCapture:us},(n=>({rageclick:n&&n>="2026-05-30"?{content_ignorelist:Wg,ignore_text_selection:!0}:!n||"2025-11-30">n||{content_ignorelist:!0},capture_pageview:!n||"2025-05-24">n||"history_change",session_recording:n&&n>="2026-06-25"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6},streamNetworkBody:!0}:n&&n>="2026-05-30"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6}}:n&&n>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:n&&n>="2026-01-30"?"head":"body",internal_or_test_user_hostname:n&&n>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:n&&n>="2026-05-30"?250:0,split_storage:!(!n||"2026-05-30">n),detect_google_search_app:!(!n||"2026-05-30">n),disable_capture_url_hashes:!(!n||"2026-06-25">n)}))(t))},Rm=[["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"]],ru=t=>{var e={};for(var n of Rm){var i=n[0],r=n[1];C(t[i])||(e[r]=t[i])}var s=fe({},e,t),o=t.__preview_external_dependency_versioned_paths;return C(o)||(C(t.strict_script_versioning)&&(s.strict_script_versioning=!!o),X(o)&&C(t.asset_host)&&(s.asset_host=o)),U(t.property_blacklist)&&(C(t.property_denylist)?s.property_denylist=t.property_blacklist:U(t.property_denylist)?s.property_denylist=[...t.property_blacklist,...t.property_denylist]:A.error(Vf+t.property_denylist)),s};class Tm{constructor(){this.__forceAllowLocalhost=!1}get fn(){return this.__forceAllowLocalhost}set fn(e){A.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class Je{pn(e,n){if(e){var i=this.sn.indexOf(e);i!==-1&&this.sn.splice(i,1)}return this.sn.push(n),n.initialize==null||n.initialize(),n}gn(){return this.config.cookieless_mode===Wt||this.config.cookieless_mode===kn&&this.consent.isRejected()}get decideEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){var e;this.webPerformance=new Tm,this.mn=!1,this.version=ne.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new pl,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=To(),this.SentryIntegration=Zg,this.sentryIntegration=i=>(function(r,s){var o=vf(r,s);return{name:mf,processEvent:a=>o(a)}})(this,i),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.wn=!1,this.kn=null,this.xn=null,this.Sn=null,this.scrollManager=new _m(this),this.pageViewManager=new Wc(this),this.rateLimiter=new om(this),this.requestRouter=new bm(this),this.consent=new Bg(this),this.externalIntegrations=new km(this);var n=(e=Je.__defaultExtensionClasses)!==null&&e!==void 0?e:{};this.featureFlags=n.featureFlags&&new n.featureFlags(this),this.toolbar=n.toolbar&&new n.toolbar(this),this.surveys=n.surveys&&new n.surveys(this),this.conversations=n.conversations&&new n.conversations(this),this.logs=n.logs&&new n.logs(this),this.metrics=n.metrics&&new n.metrics(this),this.experiments=n.experiments&&new n.experiments(this),this.exceptions=n.exceptions&&new n.exceptions(this),this.people={set:(i,r,s)=>{var o=X(i)?{[i]:r}:i;this.setPersonProperties(o),s?.({})},set_once:(i,r,s)=>{var o=X(i)?{[i]:r}:i;this.setPersonProperties(void 0,o),s?.({})}},this.on("eventCaptured",(i=>A.info('send "'+i?.event+'"',i)))}init(e,n,i){if(i&&i!==Gn){var r,s=(r=Wi[i])!==null&&r!==void 0?r:new Je;return s._init(e,n,i),Wi[i]=s,Wi[Gn][i]=s,s}return this._init(e,n,i)}_init(e,n,i){var r,s;n===void 0&&(n={});var o,a=X(e)?e.trim():"";if(!a)return A.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return a!==((o=this.config)==null?void 0:o.token)?console.warn("[PostHog.js]","You have already initialized PostHog with a different project token! Re-initializing is a no-op, so events will keep going to the project this instance was initialized with. To capture into a second project, load PostHog once, then initialize a named instance after the SDK has loaded, e.g. posthog.init('"+a+"', { ... }, 'project2')"):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=To(n.defaults),n.debug=this.Cn(n.debug),this.Mn=n,this.Tn=[],n.person_profiles?this.xn=n.person_profiles:n.process_person&&(this.xn=n.process_person);var l=To(n.defaults),u=ru(n),c=fe({},l,u,{name:i,token:a});he(l.rageclick)&&he(u.rageclick)&&(c.rageclick=fe({},l.rageclick,u.rageclick)),he(l.session_recording)&&he(u.session_recording)&&(c.session_recording=fe({},l.session_recording,u.session_recording)),this.set_config(c),this.config.on_xhr_error&&A.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=n.disable_compression?void 0:je.GZipJS;var d=this.En();if(this.persistence=new xo(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new xo(I({},this.config,{persistence:"sessionStorage"}),d,!1),this.bn="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&be.N()){var h=be.H(this.bn);U(h)&&h.forEach((k=>{X(k)&&this.yn.add(k)}))}else be.q(this.bn);var f=I({},this.persistence.props),p=I({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new gm((k=>this.Pn(k)),this.config.request_queue_config),this.Rn=new vm(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new Qc(this),this.sessionPropsManager=new Xc(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((k,T,x)=>{(x!=null&&x.activityTimeout||x!=null&&x.sessionPastMaximumLength||x!=null&&x.crossTabAdoption)&&this.An()}))),this.Fn(),this.config.__preview_deferred_init_extensions?(A.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Ln(g)}),0)):(A.info("Initializing extensions synchronously"),this.Ln(g)),ne.DEBUG=ne.DEBUG||this.config.debug,ne.DEBUG&&A.info("Starting in debug mode",{this:this,config:n,thisC:I({},this.config),p:f,s:p}),!this.config.identity_distinct_id||(r=n.bootstrap)!=null&&r.distinctID||(n.bootstrap=I({},n.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((s=n.bootstrap)==null?void 0:s.distinctID)!==void 0){var m=n.bootstrap.distinctID,v=this.get_distinct_id(),E=this.persistence.get_property(ot);if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&E===Un)this.identify(m);else if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&E===vn)A.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{var S=this.config.get_device_id(Ht()),_=n.bootstrap.isIdentifiedID?S:m;this.persistence.set_property(ot,n.bootstrap.isIdentifiedID?vn:Un),this.register({distinct_id:m,$device_id:_})}}if(g)this.register_once({distinct_id:mr,$device_id:null},"");else if(!this.get_distinct_id()){var b=this.config.get_device_id(Ht());this.register_once({distinct_id:b,$device_id:b},""),this.persistence.set_property(ot,Un)}return ve(w,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),n.segment?(function(k,T){var x=k.config.segment;if(!x)return T();(function(F,$){var O=F.config.segment;if(!O)return $();var L=K=>{var V=()=>K.anonymousId()||Ht();F.config.get_device_id=V,K.id()&&(F.register({distinct_id:K.id(),$device_id:V()}),F.persistence.set_property(ot,vn)),$()},N=O.user();"then"in N&&De(N.then)?N.then(L):L(N)})(k,(()=>{x.register((F=>{typeof Promise<"u"&&Promise.resolve||Eo.warn("This browser does not have Promise support, and can not use the segment integration");var $=(O,L)=>{if(!L)return O;O.event.userId||O.event.anonymousId===F.get_distinct_id()||(Eo.info("No userId set, resetting PostHog"),F.reset()),O.event.userId&&O.event.userId!==F.get_distinct_id()&&(Eo.info("UserId set, identifying with PostHog"),F.identify(O.event.userId));var N=F.calculateEventProperties(L,O.event.properties);return O.event.properties=Object.assign({},N,O.event.properties),O};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:O=>$(O,O.event.event),page:O=>$(O,Vn),identify:O=>$(O,yo),screen:O=>$(O,"$screen")}})(k)).then((()=>{T()}))}))})(this,(()=>this.On())):this.On(),De(this.config._onCapture)&&this.config._onCapture!==us&&(A.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(k=>this.config._onCapture(k.event,k)))),this.config.ip&&A.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this.config.disableDeviceModel||(function(){return jf.apply(this,arguments)})().then((k=>{k&&this.register({[vo]:k})})).catch(us),this}Fn(){var e,n,i,r,s,o,a=(e=(n=this.config.__extensionClasses)==null?void 0:n.featureFlags)!==null&&e!==void 0?e:(i=Je.__defaultExtensionClasses)==null?void 0:i.featureFlags;a&&(this.featureFlags&&this.featureFlags instanceof a||((r=this.Dn)==null||r.call(this),this.Dn=void 0,this.featureFlags=new a(this)),De(this.featureFlags.onReloading)&&De(this.featureFlags.setup)?this.Dn||(this.Dn=this.featureFlags.onReloading((()=>{this.dn.emit("featureFlagsReloading",!0)})),this.$n().add(this.featureFlags)):(s=(o=this.featureFlags).initialize)==null||s.call(o))}Ln(e){var n,i,r,s,o,a,l,u=performance.now(),c=I({},Je.__defaultExtensionClasses,this.config.__extensionClasses),d=[];c.exceptions&&this.sn.push(this.exceptions=(n=this.exceptions)!==null&&n!==void 0?n:new c.exceptions(this)),c.historyAutocapture&&this.sn.push(this.historyAutocapture=new c.historyAutocapture(this)),c.tracingHeaders&&this.sn.push(this.tracingHeaders=new c.tracingHeaders(this)),c.siteApps&&this.sn.push(this.siteApps=new c.siteApps(this)),c.sessionRecording&&!e&&this.sn.push(this.sessionRecording=new c.sessionRecording(this)),this.config.disable_scroll_properties||d.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),c.autocapture&&this.sn.push(this.autocapture=new c.autocapture(this)),c.surveys&&this.sn.push(this.surveys=(i=this.surveys)!==null&&i!==void 0?i:new c.surveys(this)),c.logs&&this.sn.push(this.logs=(r=this.logs)!==null&&r!==void 0?r:new c.logs(this)),c.metrics&&this.sn.push(this.metrics=(s=this.metrics)!==null&&s!==void 0?s:new c.metrics(this)),c.conversations&&this.sn.push(this.conversations=(o=this.conversations)!==null&&o!==void 0?o:new c.conversations(this)),c.productTours&&this.sn.push(this.productTours=new c.productTours(this)),c.heatmaps&&this.sn.push(this.heatmaps=new c.heatmaps(this)),c.webVitalsAutocapture&&this.sn.push(this.webVitalsAutocapture=new c.webVitalsAutocapture(this)),c.exceptionObserver&&this.sn.push(this.exceptionObserver=new c.exceptionObserver(this)),c.deadClicksAutocapture&&this.sn.push(this.deadClicksAutocapture=new c.deadClicksAutocapture(this,Jg)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((h=>{h.initialize&&d.push((()=>{h.initialize==null||h.initialize()}))})),d.push((()=>{if(this.Nn){var h=this.Nn;this.Nn=void 0,this.sn.forEach((f=>f.onRemoteConfig==null?void 0:f.onRemoteConfig(h)))}})),this.qn(d,u)}qn(e,n){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,n)}),0);var i=e.shift();if(i)try{i()}catch(s){A.error("Error initializing extension:",s)}}var r=Math.round(performance.now()-n);this.register_for_session({[Qd]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[ef]:r}),this.config.__preview_deferred_init_extensions&&A.info("PostHog extensions initialized ("+r+"ms)")}Zi(e){var n;if(!P||!P.body)return A.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.Zi(e)}),500);if(this.config.__preview_deferred_init_extensions&&(this.Nn=e),this.hn=e,this.compression=void 0,e.ok){var i,r=e.config;r.supportedCompression&&!this.config.disable_compression&&(this.compression=j(r.supportedCompression,je.GZipJS)?je.GZipJS:j(r.supportedCompression,je.Base64)?je.Base64:void 0),(i=r.analytics)!=null&&i.endpoint&&(this.analyticsDefaultEndpoint=r.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:pa}),(n=this.jn)==null||n.handleRemoteConfig(e),this.sn.forEach((s=>s.onRemoteConfig==null?void 0:s.onRemoteConfig(e)))}On(){try{this.config.loaded(this)}catch(i){A.critical("`loaded` function failed",i)}if(this.Bn(),this.config.internal_or_test_user_hostname&&me!=null&&me.hostname){var e=me.hostname,n=this.config.internal_or_test_user_hostname;(typeof n=="string"?e===n:n.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.gn())&&this.Hn()}),1),this.Un=new Cf(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()&&vr(this.__request_queue,(e=>this.Pn(e))),this.__request_queue=[],this.Bn()}_handle_unload(){var e,n,i,r,s;(e=this.surveys)==null||e.handlePageUnload==null||e.handlePageUnload(),(n=this.metrics)==null||n.flush("sendBeacon"),this.config.request_batching?(this.zn()&&this.capture(_o),(i=this.logs)==null||i.flushLogs("sendBeacon"),(r=this.In)==null||r.unload(),(s=this.Rn)==null||s.unload()):this.zn()&&this.capture(_o,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?Gf?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)?e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:429})):(e.transport=e.transport||this.config.api_transport,e.headers=I({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,(C(this.config.disable_beacon)?this.config.__preview_disable_beacon:this.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(n=>{var i,r,s,o=I({},n);o.timeout=o.timeout||6e4;var a,l,u,c,d,h=(i=o.transport)!==null&&i!==void 0?i:"fetch";h==="sendBeacon"&&C(o.compression)&&o.data&&(o.compression=je.Base64),o.method==="POST"&&o.data&&(o.timestampMode==="capture-body"?o.data={api_key:(l=(d=(c=U(a=o.data)?a:[a])[0])==null||(u=d.properties)==null?void 0:u.token)!==null&&l!==void 0?l:d?.token,batch:c,sent_at:new Date().toISOString()}:o.timestampMode==="body"&&(o.data=(function(m,v){return v===void 0&&(v=new Date().toISOString()),U(m)?m.map((E=>I({},E,{sent_at:v}))):I({},m,{sent_at:v})})(o.data))),o.url=Zc(o.url,o.method,o.compression,o.timestampMode);var f=Lr.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),p=(r=(s=(function(m,v){for(var E=0;m.length>E;E++)if(m[E].transport===h)return m[E]})(f))==null?void 0:s.method)!==null&&r!==void 0?r:f[0].method;if(!p)throw new Error("No available transport method");var g=m=>{try{p(m)}catch(v){Of(v)?A.warn(v):A.error(v),o.callback==null||o.callback({statusCode:0,error:v})}};h!=="sendBeacon"&&o.data&&o.compression===je.GZipJS&&$p&&typeof Promise<"u"&&!Mr?hm(o).then((m=>{g(m)})).catch((m=>{if(vc(m))return Mr=!0,void g(I({},o,{compression:void 0,url:Zc(n.url,n.method,void 0,n.timestampMode)}));(v=>{if(!v||typeof v!="object")return!1;var E="name"in v?String(v.name):"";return vc(v)||E===fd})(m)&&(Mr=!0),g(o)})):p(o)})(I({},e,{callback:n=>{var i,r;this.rateLimiter.checkForLimiting(n),400>n.statusCode||(i=(r=this.config).on_request_error)==null||i.call(r,n),e.callback==null||e.callback(n)}}))):e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:0}))}Pn(e){this.Rn?this.Rn.retriableRequest(e):this._send_request(e)}_execute_array(e){Ro++;try{var n,i=[],r=[],s=[];vr(e,(a=>{if(a)if(U(n=a[0]))s.push(a);else if(De(a))try{a.call(this)}catch(l){A.error("Error executing queued PostHog call",a,l)}else U(a)&&n==="alias"?i.push(a):U(a)&&n.indexOf("capture")!==-1&&De(this[n])?s.push(a):r.push(a)}));var o=function(a,l){vr(a,(function(u){try{if(U(u[0])){var c=l;ie(u,(function(d){c=c[d[0]].apply(c,d.slice(1))}))}else l[u[0]].apply(l,u.slice(1))}catch(d){A.error("Error executing queued PostHog call",u,d)}}))};o(i,this),o(r,this),o(s,this)}finally{Ro--}}push(e){if(Ro>0&&U(e)&&X(e[0])){var n=Je.prototype[e[0]];De(n)&&n.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,n,i){var r,s,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.In){if(this.is_capturing())if(!C(e)&&X(e)){var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var c=i!=null&&i.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(c==null||!c.isRateLimited){n!=null&&n.$current_url&&!X(n?.$current_url)&&(A.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),n==null||delete n.$current_url),e!=="$exception"||i!=null&&i.Wn||A.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,h=i?.timestamp||d,f=Ec(i?.uuid,Ht),p={uuid:f,event:e,properties:this.calculateEventProperties(e,n||{},h,f)};e===Vn&&this.config.__preview_capture_bot_pageviews&&u&&(p.event="$bot_pageview",p.properties.$browser_type="bot"),c&&(p.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&p.properties.$feature_flag_has_experiment===!1&&this.get_property(Zr)===!0;i?.$set&&!g&&(p.$set=i?.$set);var m=i?.$unset;m&&(p.$unset=m);var v,E,S,_=g?void 0:this.Vn(i?.$set_once,e!==Ac,e===yo);if(_&&(p.$set_once=_),i!=null&&i._noTruncate||(s=this.config.properties_string_max_length,o=p,a=L=>X(L)?L.slice(0,s):L,l=new Set,p=(function L(N,K){if(N!==Object(N))return a?a(N):N;if(!l.has(N)){var V;if(l.add(N),U(N))V=[],vr(N,(R=>{V.push(L(R))}));else{var M={};ie(N,((R,Z)=>{l.has(R)||(M[Z]=L(R))})),V=M}return V}})(o)),p.timestamp=h,C(i?.timestamp)||(p.properties.$event_time_override_provided=!0,p.properties.$event_time_override_system_time=d),g&&(p.properties=(function(L,N){N===void 0&&(N=[]);var K={},V=M=>{L[M]!==void 0&&(K[M]=L[M])};return Mp.forEach(V),N.forEach(V),K})(p.properties,Fm)),e===zt.DISMISSED||e===zt.SENT){var b=n?.[ko.SURVEY_ID],k=n?.[ko.SURVEY_ITERATION];zf({id:b,current_iteration:k}),p.$set=I({},p.$set,{[(v={id:b,current_iteration:k},E=e===zt.SENT?"responded":"dismissed",S="$survey_"+E+"/"+v.id,v.current_iteration&&v.current_iteration>0&&(S="$survey_"+E+"/"+v.id+"/"+v.current_iteration),S)]:!0})}else e===zt.SHOWN&&(p.$set=I({},p.$set,{[ko.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===sm.SHOWN){var T=n?.[zc.TOUR_TYPE];T&&(p.$set=I({},p.$set,{[zc.TOUR_LAST_SEEN_DATE+"/"+T]:new Date().toISOString()}))}var x=I({},p.properties.$set,p.$set);if(Kt(x)||this.setPersonPropertiesForFlags(x),!H(this.config.before_send)){var F=this.Pt(p);if(!F)return;(p=F).uuid=Ec(p.uuid,Ht)}this.dn.emit("eventCaptured",p);var $=(r=i?._url)!==null&&r!==void 0?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),O={method:"POST",url:$,data:p,compression:"best-available",timestampMode:i?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test($)?"body":"capture-body",batchKey:i?._batchKey,transport:i?.transport};return!this.config.request_batching||i&&(i==null||!i._batchKey)||i!=null&&i.send_instantly?this.Pn(O):this.In.enqueue(O),p}A.critical("This capture call is ignored due to client rate limiting.")}}else A.error("No event name provided to posthog.capture")}else A.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(n=>e(n.event,n)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new Pm(this)}cn(e){this._n.push(e);var n=!0;return()=>{if(n){n=!1;var i=this._n.indexOf(e);i!==-1&&this._n.splice(i,1)}}}calculateEventProperties(e,n,i,r,s){if(i=i||new Date,!this.persistence||!this.sessionPersistence)return n;var o=s?void 0:this.persistence.remove_event_timer(e),a=I({},n);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.gn()&&(a[Xd]=!0),e==="$snapshot"){var l=I({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!X(a.distinct_id)&&!ke(a.distinct_id)||Ko(a.distinct_id))&&A.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=(function(b,k,T,x){var F,$,O,L;if(x===void 0&&(x=!1),!Ve)return{};var N,K=b?[...ri,...k||[]]:[],V=(function(Bn){for(var qe=0;wc.length>qe;qe++){var Dn=wc[qe],Mt=Dn[1],Lt=Dn[0].exec(Bn),ut=Lt&&(De(Mt)?Mt(Lt,Bn):Mt);if(ut)return ut}return["",""]})(Ve),M=V[0],R=V[1],Z=(N=typeof navigator<"u"?navigator:void 0)!=null&&N.brave?{brave:!0}:{},Ce={};C(T)||(Ce.detectGoogleSearchApp=T);var oe={},ye=(F=navigator)==null||(F=F.userAgentData)==null?void 0:F.platform,$e=($=navigator)==null?void 0:$.maxTouchPoints,ae=w==null||(O=w.screen)==null?void 0:O.width,Ie=w==null||(L=w.screen)==null?void 0:L.height,Se=w?.devicePixelRatio;C(ye)||(oe.userAgentDataPlatform=ye),C($e)||(oe.maxTouchPoints=$e),C(ae)||(oe.screenWidth=ae),C(Ie)||(oe.screenHeight=Ie),C(Se)||(oe.devicePixelRatio=Se);var Be,wt,ge,Ye,bt,mn,Re,Pe,$t=fe(ll({$os:M,$os_version:R,$browser:Od(Ve,navigator.vendor,Z,Ce),$device:bc(Ve),$device_type:(wt=Ve,ge=oe,Pe=bc(wt),Pe===yd||Pe===_d||Pe==="Kobo"||Pe==="Kindle Fire"||Pe===Td?ei:Pe===Gi||Pe===Xn||Pe===Ki||Pe===Jo?"Console":Pe===bd?"Wearable":Pe?it:ge?.userAgentDataPlatform==="Android"&&((Ye=ge?.maxTouchPoints)!==null&&Ye!==void 0?Ye:0)>0?600>Math.min((bt=ge?.screenWidth)!==null&&bt!==void 0?bt:0,(mn=ge?.screenHeight)!==null&&mn!==void 0?mn:0)/((Re=ge?.devicePixelRatio)!==null&&Re!==void 0?Re:1)?it:ei:"Desktop"),$timezone:kf(),$timezone_offset:nm()}),{$current_url:Zi(x?fn(me?.href):me?.href,K,Xi),$host:me?.host,$pathname:me?.pathname,$raw_user_agent:Ve.length>1e3?Ve.substring(0,997)+"...":Ve,$browser_version:Qp(Ve,navigator.vendor,Z,Ce),$browser_language:qc(),$browser_language_prefix:(Be=qc(),typeof Be=="string"?Be.split("-")[0]:void 0),$screen_height:w?.screen.height,$screen_width:w?.screen.width,$viewport_height:w?.innerHeight,$viewport_width:w?.innerWidth,$lib:ne.LIB_NAME,$lib_version:ne.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return ne.SDK_DIST_CHANNEL&&($t.$sdk_dist_channel=ne.SDK_DIST_CHANNEL),$t})(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties,this.config.detect_google_search_app,this.config.disable_capture_url_hashes);if(this.sessionManager){var d=this.sessionManager.checkAndGetSessionAndWindowId(s,i.getTime()),h=d.windowId;a.$session_id=d.sessionId,a.$window_id=h}this.sessionPropsManager&&fe(a,this.sessionPropsManager.getSessionProps());try{var f;this.sessionRecording&&fe(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(f=this.Rn)==null?void 0:f.length}catch(b){a.$sdk_debug_error_capturing_properties=String(b)}if(this.requestRouter.region===xa&&(a.$lib_custom_api_host=this.config.api_host),u=e!==Vn||s?e!==_o||s?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(i):this.pageViewManager.doPageView(i,r),a=fe(a,u),e===Vn&&P&&(a.title=P.title),!C(o)){var p=i.getTime()-o;a.$duration=parseFloat((p/1e3).toFixed(3))}Ve&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();ie(["$referrer","$referring_domain"],(b=>{b in g&&delete m[b]}));var v={};if(this._n.length>0)for(var E of this._n.slice())try{fe(v,E())}catch(b){A.error("Failed to produce browser extension event properties",b)}(a=fe({},c,g,m,I({},v,a))).$is_identified=this._isIdentified(),U(this.config.property_denylist)?ie(this.config.property_denylist,(function(b){delete a[b]})):A.error(Vf+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var S=this.config.sanitize_properties;S&&(A.error(iu),a=S(a,e));var _=this.Zn();return a.$process_person_profile=_,_&&!s&&this.Gn("_calculate_event_properties"),a}Vn(e,n,i){var r;if(n===void 0&&(n=!0),i===void 0&&(i=!1),!this.persistence||!this.Zn()||this.mn&&!i)return e;var s=this.persistence.get_initial_props(),o=(r=this.sessionPropsManager)==null?void 0:r.getSetOnceProps(),a=fe({},s,o||{},e||{}),l=this.config.sanitize_properties;return l&&(A.error(iu),a=l(a,"$set_once")),n&&(this.mn=!0),Kt(a)?void 0:a}register(e,n){var i;(i=this.persistence)==null||i.register(e,n)}register_once(e,n,i){var r;(r=this.persistence)==null||r.register_once(e,n,i)}register_for_session(e){var n;(n=this.sessionPersistence)==null||n.register(e),Object.keys(e).forEach((i=>this.yn.add(i))),this.Qn()}unregister(e){var n;(n=this.persistence)==null||n.unregister(e)}unregister_for_session(e){var n;(n=this.sessionPersistence)==null||n.unregister(e),this.yn.delete(e),this.Qn()}Kn(e,n){this.register({[e]:n})}An(){this.yn.forEach((e=>{var n;(n=this.sessionPersistence)==null||n.unregister(e)})),this.yn.clear(),this.Qn()}Qn(){var e;if(this.bn)if(this.config.persistence==="memory"||(e=this.sessionPersistence)!=null&&e.xi||!be.N())be.q(this.bn);else{var n=[];this.yn.forEach((i=>n.push(i))),n.length>0?be.F(this.bn,n):be.q(this.bn)}}getFeatureFlag(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlag(e,n)}getFeatureFlagPayload(e){var n;return(n=this.featureFlags)==null?void 0:n.getFeatureFlagPayload(e)}getFeatureFlagResult(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlagResult(e,n)}getAllFeatureFlags(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.getAllFeatureFlags())!==null&&e!==void 0?e:[]}isFeatureEnabled(e,n){var i,r;return(i=(r=this.featureFlags)==null?void 0:r.isFeatureEnabled(e,n))!==null&&i!==void 0?i:n?.defaultValue}reloadFeatureFlags(){var e;(e=this.featureFlags)==null||e.reloadFeatureFlags()}updateFlags(e,n,i){var r;(r=this.featureFlags)==null||r.updateFlags(e,n,i)}updateEarlyAccessFeatureEnrollment(e,n,i){var r;(r=this.featureFlags)==null||r.updateEarlyAccessFeatureEnrollment(e,n,i)}getEarlyAccessFeatures(e,n,i){var r;return n===void 0&&(n=!1),(r=this.featureFlags)==null?void 0:r.getEarlyAccessFeatures(e,n,i)}on(e,n){return this.dn.on(e,n)}onFeatureFlags(e){return this.featureFlags?this.featureFlags.onFeatureFlags(e):(e([],{},{errorsLoading:!0}),()=>{})}onSurveysLoaded(e){return this.surveys?this.surveys.onSurveysLoaded(e):(e([],{isLoaded:!1,error:xi}),()=>{})}onSessionId(e){var n,i;return(n=(i=this.sessionManager)==null?void 0:i.onSessionId(e))!==null&&n!==void 0?n:()=>{}}getSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getSurveys(e,n):e([],{isLoaded:!1,error:xi})}getActiveMatchingSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,n):e([],{isLoaded:!1,error:xi})}renderSurvey(e,n){var i;(i=this.surveys)==null||i.renderSurvey(e,n)}displaySurvey(e,n){var i;n===void 0&&(n=Sm),(i=this.surveys)==null||i.displaySurvey(e,n)}cancelPendingSurvey(e){var n;(n=this.surveys)==null||n.cancelPendingSurvey(e)}canRenderSurvey(e){var n,i;return(n=(i=this.surveys)==null?void 0:i.canRenderSurvey(e))!==null&&n!==void 0?n:{visible:!1,disabledReason:xi}}canRenderSurveyAsync(e,n){var i,r;return n===void 0&&(n=!1),(i=(r=this.surveys)==null?void 0:r.canRenderSurveyAsync(e,n))!==null&&i!==void 0?i:Promise.resolve({visible:!1,disabledReason:xi})}Jn(e){return!e||Ko(e)?(A.critical("Unique user id has not been set in posthog.identify"),!1):e===mr?(A.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.'),!1):!["distinct_id","distinctid"].includes(e.toLowerCase())&&!["undefined","null"].includes(e.toLowerCase())||(A.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.'),!1)}identify(e,n,i){if(!this.__loaded||!this.persistence)return A.uninitializedWarning("posthog.identify");if(ke(e)&&(e=e.toString(),A.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.Jn(e)&&this.Gn("posthog.identify")){var r=this.get_distinct_id();this.register({$user_id:e}),this.get_property(Yi)||this.register_once({$had_persisted_distinct_id:!0,$device_id:r},""),e!==r&&e!==this.get_property(Fi)&&(this.unregister(Fi),this.register({distinct_id:e}));var s,o=(this.persistence.get_property(ot)||Un)===Un,a=e!==r,l=!a&&o;if(a&&o)this.persistence.set_property(ot,vn),this.setPersonPropertiesForFlags({$set:n||{},$set_once:i||{}},!1),this.capture(yo,{distinct_id:e,$anon_distinct_id:r},{$set:n||{},$set_once:i||{}}),this.Sn=Fo(e,n,i),(s=this.featureFlags)==null||s.setAnonymousDistinctId(r);else if(l){this.persistence.set_property(ot,vn);var u=n||{},c=i||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=Fo(e,n,i)}else(n||i)&&this.setPersonProperties(n,i);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Cn)):l&&(n||i)&&this.reloadFeatureFlags()}}setPersonProperties(e,n){if((e||n)&&this.Gn("posthog.setPersonProperties")){var i=Fo(this.get_distinct_id(),e,n);this.Sn!==i?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:n||{}},!0),this.capture("$set",{$set:e||{},$set_once:n||{}}),this.Sn=i):A.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}unsetPersonProperties(e){var n,i=(U(e)?e:[e]).filter((r=>X(r)&&r.length>0));i.length!==0&&this.Gn("posthog.unsetPersonProperties")&&((n=this.featureFlags)==null||n.unsetPersonPropertiesForFlags(i,!0),this.capture("$set",{$unset:i}),this.Sn=null)}group(e,n,i){if(e&&n){var r=this.getGroups(),s=r[e]!==n;if(s&&this.resetGroupPropertiesForFlags(e),this.register({$groups:I({},r,{[e]:n})}),s||i){var o={$group_type:e,$group_key:n};i&&(o.$group_set=i),this.capture(Ac,o)}i&&this.setGroupPropertiesForFlags({[e]:i}),s&&!i&&this.reloadFeatureFlags()}else A.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),(i=this.featureFlags)==null||i.setPersonPropertiesForFlags(e,n)}resetPersonPropertiesForFlags(e){var n;e===void 0&&(e=!0),(n=this.featureFlags)==null||n.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((i=this.featureFlags)==null||i.setGroupPropertiesForFlags(e,n))}resetGroupPropertiesForFlags(e){var n;(n=this.featureFlags)==null||n.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,n){var i,r,s,o,a,l,u,c,d,h;if(n===void 0&&(n=!1),A.info("reset"),!this.__loaded)return A.uninitializedWarning("posthog.reset");var f,p=this.get_property(Yi),g=this.get_property(vo),m=this.get_property(An),v=this.is_capturing();if(this.consent.reset(),n||!v||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after."),(i=this.persistence)==null||i.clear(),(r=this.sessionPersistence)==null||r.clear(),this.yn.clear(),this.Qn(),C(m)||(f=this.persistence)==null||f.register({[An]:m}),(s=this.surveys)==null||s.reset(),(o=this.Un)==null||o.stop(),(a=this.featureFlags)==null||a.reset(),(l=this.conversations)==null||l.reset(),(u=this.logs)==null||u.reset(),(c=this.metrics)==null||c.reset(),(d=this.persistence)==null||d.set_property(ot,Un),(h=this.sessionManager)==null||h.resetSessionId(),this.Sn=null,this.config.cookieless_mode===Wt)this.register_once({distinct_id:mr,$device_id:null},"");else{var E=this.config.get_device_id(Ht());this.register_once({distinct_id:E,$device_id:e?E:p},""),e||C(g)||this.register({[vo]:g})}this.register({$last_posthog_reset:new Date().toISOString()},1),delete this.config.identity_distinct_id,delete this.config.identity_hash,this.reloadFeatureFlags()}shutdown(e){var n=this;return se((function*(){var i,r,s,o,a,l,u;if(n.__loaded){(i=n.Un)==null||i.stop(),(r=n.jn)==null||r.dispose(),(s=n.sessionRecording)==null||s.dispose(),(o=n.logs)==null||o.flushLogs("sendBeacon"),(a=n.metrics)==null||a.flush("sendBeacon"),(l=n.In)==null||l.unload(),(u=n.Rn)==null||u.unload();try{var c;(c=n.featureFlags)==null||c.destroy()}catch(d){A.error("Error while destroying feature flags",d)}}else A.uninitializedWarning("posthog.shutdown")}))()}setIdentity(e,n){var i;this.config.identity_distinct_id=e,this.config.identity_hash=n,this.alias(e),(i=this.conversations)==null||i.Xn()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,(e=this.conversations)==null||e.ts()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,n;return(e=(n=this.sessionManager)==null?void 0:n.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var n=this.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.sessionStartTimestamp,r=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+n.sessionId);if(e!=null&&e.withTimestamp&&i){var s,o=(s=e.timestampLookBack)!==null&&s!==void 0?s:10;if(!i)return r;r+="?t="+Math.max(Math.floor((new Date().getTime()-i)/1e3)-o,0)}return r}alias(e,n){return e===this.get_property(Vd)?(A.critical("Attempting to create alias for existing People user - aborting."),-2):this.Gn("posthog.alias")?(C(n)&&(n=this.get_distinct_id()),e!==n?(this.Kn(Fi,e),this.capture("$create_alias",{alias:e,distinct_id:n})):(A.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var n=I({},this.config);if(he(e)){var i,r,s,o,a,l,u,c,d,h,f,p;fe(this.config,ru(e));var g=this.En();(i=this.persistence)==null||i.update_config(this.config,n,g),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new xo(I({},this.config,{persistence:"sessionStorage"}),g,!1);var m=this.Cn(this.config.debug);mt(m)&&(this.config.debug=m),mt(this.config.debug)&&(this.config.debug?(ne.DEBUG=!0,le.N()&&le.F("ph_debug",!0),A.info("set_config",{config:e,oldConfig:n,newConfig:I({},this.config)})):(ne.DEBUG=!1,le.N()&&le.q("ph_debug"))),(r=this.featureFlags)==null||r.updateConfig==null||r.updateConfig(this.config,this.Qi()),(s=this.exceptionObserver)==null||s.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(h=this.deadClicksAutocapture)==null||h.startIfEnabledOrStop(),(f=this.surveys)==null||f.loadIfEnabled(),this.es(),(p=this.externalIntegrations)==null||p.startIfEnabledOrStop()}}_overrideSDKInfo(e,n){ne.LIB_NAME=e,ne.LIB_VERSION=n}startSessionRecording(e){var n,i,r,s,o,a=e===!0,l={sampling:a||!(e==null||!e.sampling),linked_flag:a||!(e==null||!e.linked_flag),url_trigger:a||!(e==null||!e.url_trigger),event_trigger:a||!(e==null||!e.event_trigger)};Object.values(l).some(Boolean)&&((n=this.sessionManager)==null||n.checkAndGetSessionAndWindowId(),l.sampling&&((i=this.sessionRecording)==null||i.overrideSampling()),l.linked_flag&&((r=this.sessionRecording)==null||r.overrideLinkedFlag()),l.url_trigger&&((s=this.sessionRecording)==null||s.overrideTrigger("url")),l.event_trigger&&((o=this.sessionRecording)==null||o.overrideTrigger("event"))),this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,n){if(this.exceptions){var i=new Error("PostHog syntheticException"),r=this.exceptions.buildProperties(e,{handled:!0,syntheticException:i});return this.exceptions.sendExceptionEvent(I({},r,n))}}addExceptionStep(e,n){var i;(i=this.exceptions)==null||i.addExceptionStep(e,n)}captureLog(e){var n;(n=this.logs)==null||n.captureLog(e)}get logger(){var e,n;return(e=(n=this.logs)==null?void 0:n.logger)!==null&&e!==void 0?e:Je.rs}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var n,i;return(n=(i=this.toolbar)==null?void 0:i.loadToolbar(e))!==null&&n!==void 0&&n}get_property(e){var n;return(n=this.persistence)==null?void 0:n.props[e]}getSessionProperty(e){var n;return(n=this.sessionPersistence)==null?void 0:n.props[e]}toString(){var e,n=(e=this.config.name)!==null&&e!==void 0?e:Gn;return n!==Gn&&(n=Gn+"."+n),n}_isIdentified(){var e,n;return((e=this.persistence)==null?void 0:e.get_property(ot))===vn||((n=this.sessionPersistence)==null?void 0:n.get_property(ot))===vn}Zn(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles===pa&&!this._isIdentified()&&Kt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[Fi])&&((n=this.persistence)==null||(n=n.props)==null||!n[es]))}zn(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Zn()||this.Gn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.Gn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}Gn(e){return this.config.person_profiles==="never"?(A.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Kn(es,!0),!0)}En(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut();return this.config.disable_persistence||e&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!==kn)}es(){var e,n,i,r,s=this.En();return((e=this.persistence)==null?void 0:e.xi)!==s&&((i=this.persistence)==null||i.set_disabled(s)),((n=this.sessionPersistence)==null?void 0:n.xi)!==s&&((r=this.sessionPersistence)==null||r.set_disabled(s)),s&&(this.yn.clear(),this.Qn()),s}opt_in_capturing(e){var n;if(this.config.cookieless_mode!==Wt){if(this.gn()){var i,r,s,o,a;this.Yn(!0,!0),(i=this.sessionManager)==null||i.destroy(),(r=this.pageViewManager)==null||r.destroy(),this.sessionManager=new Qc(this),this.pageViewManager=new Wc(this),this.persistence&&(this.sessionPropsManager=new Xc(this,this.sessionManager,this.persistence));var l,u=(s=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&s!==void 0?s:(a=Je.__defaultExtensionClasses)==null?void 0:a.sessionRecording;u&&(this.sessionRecording=this.pn(this.sessionRecording,new u(this)),this.hn&&((l=this.sessionRecording)==null||l.onRemoteConfig==null||l.onRemoteConfig(this.hn)))}var c,d;this.consent.optInOut(!0),this.es(),this.Bn(),(n=this.sessionRecording)==null||n.startIfEnabledOrStop(),this.config.cookieless_mode==kn&&((c=this.surveys)==null||c.loadIfEnabled()),(C(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((d=e?.captureEventName)!==null&&d!==void 0?d:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hn()}else A.warn(nu)}opt_out_capturing(){var e,n,i;this.config.cookieless_mode!==Wt?(this.config.cookieless_mode===kn&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===kn&&(this.register({distinct_id:mr,$device_id:null}),(e=this.sessionRecording)==null||e.stopRecording(),this.sessionRecording=void 0,(n=this.sessionManager)==null||n.destroy(),(i=this.pageViewManager)==null||i.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.Hn(),this.Bn())):A.warn(nu)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===Wt||(this.config.cookieless_mode===kn?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return Ue?Df(Ue,this.config.custom_blocked_useragents):void 0}Hn(){P&&(P.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(Vn,{title:P.title},{send_instantly:!0}),this.kn&&(P.removeEventListener(ts,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),ve(P,ts,this.kn)))}debug(e){e===!1?(w?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(w?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}Qi(){var e=this.Mn||{};return"advanced_disable_flags"in e?!!e.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(A.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(function(n,i,r,s,o){var a=i in n&&!H(n[i]),l=r in n&&!H(n[r]);return a?n[i]:!!l&&(o&&o.warn("Config field '"+r+"' is deprecated. Please use '"+i+"' instead. The old field will be removed in a future major version."),n[r])})(e,"advanced_disable_flags","advanced_disable_decide",0,A)}Pt(e){var n;if(H(this.config.before_send))return e;var i=Object.keys((n=e.properties)!==null&&n!==void 0?n:{}).filter(Up),r=U(this.config.before_send)?this.config.before_send:[this.config.before_send],s=e;for(var o of r){if(s=o(s),H(s)){var a="Event '"+e.event+"' was rejected in beforeSend function";return jp(e.event)?A.warn(a+". This can cause unexpected behavior."):A.info(a),null}s.properties&&!Kt(s.properties)||A.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}for(var l of i)if(s.properties&&H(s.properties[l]))return A.warn("Event '"+e.event+"' had its '"+l+"' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped."),null;return s}getPageViewId(){var e;return(e=this.pageViewManager.ui)==null?void 0:e.pageViewId}captureTraceFeedback(e,n){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:n})}captureTraceMetric(e,n,i){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:n,$ai_metric_value:String(i)})}Cn(e){var n=mt(e)&&!e,i=le.N()&&le.P("ph_debug")==="true";return!n&&(!!i||e)}}Je.__defaultExtensionClasses={},Je.rs=(()=>{var t=()=>{};return{trace:t,debug:t,info:t,warn:t,error:t,fatal:t}})(),(function(t,e){for(var n=0;e.length>n;n++)t.prototype[e[n]]=Pg(t.prototype[e[n]])})(Je,["identify"]);class su{constructor(e){this.disabled=e===!1;var n=he(e)?e:{};this.thresholdPx=n.threshold_px||30,this.timeoutMs=n.timeout_ms||1e3,this.clickCount=n.click_count||3,this.clicks=[]}isRageClick(e,n,i){if(this.disabled)return!1;var r=this.clicks[this.clicks.length-1];if(r&&Math.abs(e-r.x)+Math.abs(n-r.y)i-r.timestamp){if(this.clicks.push({x:e,y:n,timestamp:i}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:n,timestamp:i}];return!1}}var $o="$copy_autocapture",Mo=pe("[AutoCapture]");function Lo(t,e){return e.length>t?e.slice(0,t)+"...":e}function $m(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!hn(e));return e}function Mm(t,e){var n,i,r=e.e,s=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!hn(t))return{props:{}};for(var c=[t],d=new Set([t]),h=t;h.parentNode&&!Qe(h,"body")&&cf>c.length;)if(lf(h.parentNode)){var f=h.parentNode.host;if(d.has(f))break;d.add(f),c.push(f),h=f}else{if(!hn(h.parentNode)||d.has(h.parentNode))break;d.add(h.parentNode),c.push(h.parentNode),h=h.parentNode}var p,g,m=[],v={},E=!1,S=!1;if(ie(c,(x=>{var F=va(x);if(Qe(x,"a")){var $=x.getAttribute("href");E=!!(F&&$&&Ui($))&&(u?fn($):$)}j(rs(x),"ph-no-capture")&&(S=!0),m.push((function(L,N,K,V,M){M===void 0&&(M=!1);var R=L.tagName.toLowerCase(),Z={tag_name:R};ul.indexOf(R)>-1&&!K&&(Z.$el_text=R.toLowerCase()==="a"||R.toLowerCase()==="button"?Lo(1024,jc(L)):Lo(1024,Ji(L)));var Ce=rs(L);Ce.length>0&&(Z.classes=Ce.filter((function(ae){return ae!==""}))),ie(L.attributes,(function(ae){var Ie;if((!pf(L)||["name","id","class","aria-label"].indexOf(ae.name)!==-1)&&(V==null||!V.includes(ae.name))&&!N&&Ui(ae.value)&&(!X(Ie=ae.name)||Ie.substring(0,10)!=="_ngcontent"&&Ie.substring(0,7)!=="_nghost")){var Se=ae.value;ae.name==="class"&&(Se=cl(Se).join(" ")),Z["attr__"+ae.name]=Lo(1024,ae.name==="href"&&M?fn(Se):Se)}}));for(var oe=1,ye=1,$e=L;$e=$m($e);)oe++,$e.tagName===L.tagName&&ye++;return Z.nth_child=oe,Z.nth_of_type=ye,Z})(x,s,o,a,u));var O=(function(L){if(!va(L))return{};var N={};return ie(L.attributes,(function(K){if(K.name&&K.name.indexOf("data-ph-capture-attribute")===0){var V=K.name.replace("data-ph-capture-attribute-",""),M=K.value;V&&M&&Ui(M)&&(N[V]=M)}})),N})(x);fe(v,O)})),S)return{props:{},explicitNoCapture:S};if(o||(m[0].$el_text=Qe(t,"a")||Qe(t,"button")?jc(t):Ji(t)),E){var _,b;m[0].attr__href=E;var k=(_=ss(E))==null?void 0:_.host,T=w==null||(b=w.location)==null?void 0:b.host;k&&T&&k!==T&&(p=E)}return{props:fe({$event_type:r.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(x){return x.map((F=>{var $,O,L="";if(F.tag_name&&(L+=F.tag_name),F.attr_class)for(var N of(F.attr_class.sort(),F.attr_class))L+="."+N.replace(/"/g,"");var K=I({},F.text?{text:F.text}:{},{"nth-child":($=F.nth_child)!==null&&$!==void 0?$:0,"nth-of-type":(O=F.nth_of_type)!==null&&O!==void 0?O:0},F.href?{href:F.href}:{},F.attr_id?{attr_id:F.attr_id}:{},F.attributes),V={};return $r(K).sort(((M,R)=>M[0].localeCompare(R[0]))).forEach((M=>{var R=M[1];return V[Uc(M[0].toString())]=Uc(R.toString())})),(L+=":")+$r(V).map((M=>M[0]+'="'+M[1]+'"')).join("")})).join(";")})((function(x){return x.map((F=>{var $,O,L={text:($=F.$el_text)==null?void 0:$.slice(0,400),tag_name:F.tag_name,href:(O=F.attr__href)==null?void 0:O.slice(0,2048),attr_class:Kg(F),attr_id:F.attr__id,nth_child:F.nth_child,nth_of_type:F.nth_of_type,attributes:{}};return $r(F).filter((N=>N[0].indexOf("attr__")===0)).forEach((N=>L.attributes[N[0]]=N[1])),L}))})(g)))},(n=m[0])!=null&&n.$el_text?{$el_text:(i=m[0])==null?void 0:i.$el_text}:{},p&&r.type==="click"?{$external_click_url:p}:{},v)}}var Ii=pe("[ExceptionAutocapture]"),ou=()=>{},Lm=pe("[TracingHeaders]"),wn=pe("[Web Vitals]"),au=9e5,lu="disabled",cu="lazy_loading",ki="awaiting_config",Sr="missing_config";pe("[SessionRecording]"),pe("[SessionRecording]");var Ia="[SessionRecording]",Bt=pe(Ia),Nm=pe("[Heatmaps]");function No(t){return he(t)&&"clientX"in t&&"clientY"in t&&ke(t.clientX)&&ke(t.clientY)}var xr=pe("[Product Tours]"),Oo=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(sl))},Om=["$set_once","$set"],Et=pe("[SiteApps]"),uu="Error while initializing PostHog app with config id ";function qn(t,e,n){if(H(t))return!1;switch(n){case"exact":return t===e;case"contains":var i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(i,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}class Bm{constructor(e){this.ns=new pl,this.ss=(n,i)=>this.os(n,i)&&this.ls(n,i)&&this.us(n,i)&&this.hs(n,i),this.os=(n,i)=>i==null||!i.event||n?.event===i?.event,this._instance=e,this.ds=new Set,this.vs=new Set}init(){var e,n;C((e=this._instance)==null?void 0:e._addCaptureHook)||(n=this._instance)==null||n._addCaptureHook(((i,r)=>{this.on(i,r)}))}register(e){var n,i;if(!C((n=this._instance)==null?void 0:n._addCaptureHook)&&(e.forEach((o=>{var a,l;(a=this.vs)==null||a.add(o),(l=o.steps)==null||l.forEach((u=>{var c;(c=this.ds)==null||c.add(u?.event||"")}))})),(i=this._instance)!=null&&i.autocapture)){var r,s=new Set;e.forEach((o=>{var a;(a=o.steps)==null||a.forEach((l=>{l!=null&&l.selector&&s.add(l?.selector)}))})),(r=this._instance)==null||r.autocapture.setElementSelectors(s)}}on(e,n){var i;n!=null&&e.length!=0&&(this.ds.has(e)||this.ds.has(n.event))&&this.vs&&((i=this.vs)==null?void 0:i.size)>0&&this.vs.forEach((r=>{this.cs(n,r)&&this.ns.emit("actionCaptured",r.name)}))}fs(e){this.onAction("actionCaptured",(n=>e(n)))}cs(e,n){if(n?.steps==null)return!1;for(var i of n.steps)if(this.ss(e,i))return!0;return!1}onAction(e,n){return this.ns.on(e,n)}ls(e,n){if(n!=null&&n.url){var i,r=e==null||(i=e.properties)==null?void 0:i.$current_url;if(!r||typeof r!="string"||!qn(r,n.url,n.url_matching||"contains"))return!1}return!0}us(e,n){return!!this.ps(e,n)&&!!this.gs(e,n)&&!!this.ys(e,n)}ps(e,n){var i;if(n==null||!n.href)return!0;var r=this.bs(e);if(r.length>0)return r.some((a=>qn(a.href,n.href,n.href_matching||"exact")));var s,o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!o&&qn((s=o.match(/(?::|")href="(.*?)"/))?s[1]:"",n.href,n.href_matching||"exact")}gs(e,n){var i;if(n==null||!n.text)return!0;var r=this.bs(e);if(r.length>0)return r.some((u=>qn(u.text,n.text,n.text_matching||"exact")||qn(u.$el_text,n.text,n.text_matching||"exact")));var s,o,a,l=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!l&&(s=(function(u){for(var c,d=[],h=/(?::|")text="(.*?)"/g;!H(c=h.exec(u));)d.includes(c[1])||d.push(c[1]);return d})(l),o=n.text,a=n.text_matching||"exact",s.some((u=>qn(u,o,a))))}ys(e,n){var i,r;if(n==null||!n.selector)return!0;var s=e==null||(i=e.properties)==null?void 0:i.$element_selectors;if(s!=null&&s.includes(n.selector))return!0;var o=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";if(n.selector_regex&&o)try{return new RegExp(n.selector_regex).test(o)}catch{return!1}return!1}bs(e){var n;return(e==null||(n=e.properties)==null?void 0:n.$elements)==null?[]:e?.properties.$elements}hs(e,n){return n==null||!n.properties||n.properties.length===0||Hf(n.properties.reduce(((i,r)=>{var s=U(r.value)?r.value.map(String):r.value!=null?[String(r.value)]:[];return i[r.key]={values:s,operator:r.operator||"exact"},i}),{}),e?.properties)}}class Dm{constructor(e){var n;this._s=[],this._instance=e,this.ws=new Map,this.ks=new Map,this.xs=new Map,(n=this._instance)==null||n.onSessionId==null||n.onSessionId((i=>this.Ss(i)))}Cs(e){return!1}Ms(){return null}Ts(e){}Es(){}Is(e,n){return!!e&&Hf(e.propertyFilters,n?.properties)}Ps(e,n){var i=new Map;return e.forEach((r=>{var s;(s=r.conditions)==null||(s=s[n])==null||(s=s.values)==null||s.forEach((o=>{if(o!=null&&o.name){var a=i.get(o.name)||[];a.push(r.id),i.set(o.name,a)}}))})),i}Rs(e,n,i){var r=(i===wi.Activation?this.ws:this.ks).get(e),s=[];return this.As((o=>{s=o.filter((a=>r?.includes(a.id)))})),s.filter((o=>{var a,l=(a=o.conditions)==null||(a=a[i])==null||(a=a.values)==null?void 0:a.find((u=>u.name===e));return this.Is(l,n)}))}register(e){var n;C((n=this._instance)==null?void 0:n._addCaptureHook)||(this.Fs(e),this.Ls(e))}Ls(e){var n=e.filter((i=>{var r,s;return((r=i.conditions)==null?void 0:r.actions)&&((s=i.conditions)==null||(s=s.actions)==null||(s=s.values)==null?void 0:s.length)>0}));n.length!==0&&(this.Os==null&&(this.Os=new Bm(this._instance),this.Os.init(),this.Os.fs((i=>{this.onAction(i)}))),n.forEach((i=>{var r,s,o,a,l;i.conditions&&(r=i.conditions)!=null&&r.actions&&(s=i.conditions)!=null&&(s=s.actions)!=null&&s.values&&((o=i.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.Os)==null||a.register(i.conditions.actions.values),(l=i.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var c=this.xs.get(u.name);c&&c.push(i.id),this.xs.set(u.name,c||[i.id])}})))})))}Fs(e){var n,i=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.events)&&((a=s.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0})),r=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.cancelEvents)&&((a=s.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0}));i.length===0&&r.length===0||((n=this._instance)==null||n._addCaptureHook(((s,o)=>{this.onEvent(s,o)})),this.ws=this.Ps(e,wi.Activation),this.ks=this.Ps(e,wi.Cancellation))}onEvent(e,n){var i,r,s=this.Ds(),o=(n==null||(i=n.properties)==null?void 0:i.$survey_id)||(n==null||(r=n.properties)==null?void 0:r.$product_tour_id);if(o&&this.getActivatedIds().includes(o)){var a=this.$s(e,o);if(a==="consume")return s.info("event consumed activated item, removing it",{event:e,itemId:o}),void this.Ns([o]);if(a==="persist")return s.info("shown item promoted to persisted activation",{event:e,itemId:o}),this.qs(o),void this.js([o])}if(this.ks.has(e)){var l=this.Rs(e,n,wi.Cancellation);l.length>0&&(s.info("cancel event matched, cancelling items",{event:e,itemsToCancel:l.map((c=>c.id))}),this.Ns(l.map((c=>c.id))),l.forEach((c=>this.Bs(c.id))))}if(this.ws.has(e)){s.info("event name matched",{event:e,eventPayload:n,items:this.ws.get(e)});var u=this.Rs(e,n,wi.Activation);this.Hs(u.map((c=>c.id)))}}onAction(e){this.xs.has(e)&&this.Hs(this.xs.get(e)||[])}Hs(e){var n;if(e.length!==0){var i=!((n=this._instance)==null||n.get_session_id==null||!n.get_session_id()),r=[];for(var s of e)i&&this.Cs(s)?this.qs(s)&&this.Us(s):r.push(s);r.length>0&&(this._s=[...new Set([...this._s,...r])]),this.Ds().info("updating activated items",{activatedItems:this.getActivatedIds()})}}qs(e){this._s=this._s.filter((i=>i!==e));var n=this.zs();return!n.includes(e)&&(this.Ws([...n,e]),this.Vs(),!0)}Ns(e){var n=new Set(e);this._s=this._s.filter((s=>!n.has(s)));var i=this.Zs(),r=i.filter((s=>!n.has(s)));r.length!==i.length&&(this.Ws(r),r.length===0&&this.Gs()),this.js(e)}Qs(){var e,n=this.Ms();if(!n)return{};var i=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n];return i&&typeof i=="object"?i:{}}Us(e){if(this.Ms()){var n=this.Qs();this.Ts(I({},n,{[e]:Date.now()}))}}js(e){if(this.Ms()){var n=this.Qs(),i={},r=!1;for(var s of Object.entries(n)){var o=s[0],a=s[1];e.includes(o)?r=!0:i[o]=a}r&&(Kt(i)?this.Es():this.Ts(i))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var n=this.Qs()[e];return ke(n)?n:void 0}}Zs(){var e,n=this.Js();return((e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n])||[]}zs(){var e,n,i=this.Zs();if(i.length===0)return[];var r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[this.Ys()],s=(n=this._instance)==null||n.get_session_id==null?void 0:n.get_session_id();return s&&r===s?i:[]}Vs(){var e,n=(e=this._instance)==null||e.get_session_id==null?void 0:e.get_session_id();n&&this.Xs(n)}Gs(){this.ta()}Ss(e){var n,i=(n=this._instance)==null||(n=n.persistence)==null?void 0:n.props[this.Ys()];if(i&&i!==e){var r=this.Zs(),s=this.Qs();r.length>0&&(this.Ws([]),r.filter((o=>ke(s[o]))).forEach((o=>this.Bs(o)))),this.Gs(),this.Ks()}}getActivatedIds(){return[...new Set([...this.zs(),...this._s])].filter((e=>!this.ea(e)))}reset(){this._s=[],this.Zs().length>0&&this.Ws([]),this.Gs(),this.Ks()}getEventToItemsMap(){return this.ws}ia(){return this.Os}}class jm extends Dm{constructor(e){super(e)}Js(){return ca}Ys(){return Fr}Ms(){return Rr}Ts(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Rr]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Rr)}Cs(e){var n,i;this.As((s=>{i=s.find((o=>o.id===e))}));var r=(n=i)==null||(n=n.appearance)==null?void 0:n.surveyPopupDelaySeconds;return ke(r)&&r>0}ra(){return zt.SHOWN}As(e){var n;(n=this._instance)==null||n.getSurveys(e)}Bs(e){var n;(n=this._instance)==null||n.cancelPendingSurvey(e)}Ds(){return Q}Ws(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[ca]:e})}Xs(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Fr]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Fr)}ea(){return!1}$s(e,n){var i;this.As((s=>{i=s.find((o=>o.id===n))}));var r=!i||(function(s){var o;return Wf(s)&&!((o=s.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||s.schedule==="always"})(i);return r?e===zt.SHOWN?"consume":"ignore":e===zt.SHOWN?"persist":e===zt.DISMISSED||e===zt.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var Ir="SDK is not enabled or survey functionality is not yet loaded",du="Disabled. Not loading surveys.",Um=w!=null&&w.location?os(w.location.hash,"__posthog")||os(location.hash,"state"):null,fu="_postHogToolbarParams",hu=pe("[Toolbar]"),pu=pe("[FeatureFlags]");class Hm{constructor(e,n){n===void 0&&(n=!1),this.na=!1,this.update(e,n)}update(e,n){this.sa=((i,r)=>{var s,o,a,l;return{bootstrap:{featureFlags:(s=i.bootstrap)==null?void 0:s.featureFlags,featureFlagPayloads:(o=i.bootstrap)==null?void 0:o.featureFlagPayloads},remoteRequestsDisabled:r,featureFlagsDisabled:!!i.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!i.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!i.advanced_feature_flags_dedup_per_session,cacheTtlMs:i.feature_flag_cache_ttl_ms,requestTimeoutMs:i.feature_flag_request_timeout_ms,compression:i.disable_compression?"none":"base64",evaluationContexts:(a=(l=i.evaluation_contexts)!==null&&l!==void 0?l:i.evaluation_environments)!==null&&a!==void 0?a:[],flagKeys:U(i.flag_keys)?i.flag_keys:void 0}})(e,n),!e.evaluation_environments||e.evaluation_contexts||this.na||(pu.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.na=!0),C(e.flag_keys)||U(e.flag_keys)||pu.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var gu=pe("[FeatureFlags]"),bn=pe("[FeatureFlags]",{debugEnabled:!0}),Bo=`" failed. Feature flags didn't load in time.`,mu="connection_error",vu=t=>{for(var e={},n=0;t.length>n;n++)e[t[n]]=!0;return e},_u=t=>{var e={};for(var n of $r(t||{})){var i=n[1];i&&(e[n[0]]=i)}return e},St=pe("[Error tracking]"),yu="Refusing to render web experiment since the viewer is a likely bot",Wm={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>cs(e,t),not_regex:(t,e)=>!cs(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class Me{get Ne(){return this._instance.config}constructor(e){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(i){i===void 0&&(i=!1),n.getWebExperiments((r=>{Me.aa("retrieved web experiments from the server"),n.oa=new Map,r.forEach((s=>{if(s.feature_flag_key){var o;n.oa&&(Me.aa("setting flag key ",s.feature_flag_key," to web experiment ",s),(o=n.oa)==null||o.set(s.feature_flag_key,s));var a=n._instance.getFeatureFlag(s.feature_flag_key);X(a)&&s.variants[a]&&n.la(s.name,a,s.variants[a].transforms)}else if(s.variants)for(var l in s.variants){var u=s.variants[l];Me.ua(u,n._instance)&&n.la(s.name,l,u.transforms)}}))}),i)},this._instance=e,this._instance.onFeatureFlags((i=>{this.onFeatureFlags(i)}))}initialize(){}onFeatureFlags(e){if(this._is_bot())Me.aa(yu);else if(!this.Ne.disable_web_experiments){if(H(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();Me.aa("applying feature flags",e),e.forEach((n=>{var i;if(this.oa&&(i=this.oa)!=null&&i.has(n)){var r,s=this._instance.getFeatureFlag(n),o=(r=this.oa)==null?void 0:r.get(n);s&&o!=null&&o.variants[s]&&this.la(o.name,s,o.variants[s].transforms)}}))}}previewWebExperiment(){var e=Me.getWindowLocation();if(e!=null&&e.search){var n=ii(e?.search,"__experiment_id"),i=ii(e?.search,"__experiment_variant");n&&i&&(Me.aa("previewing web experiments "+n+" && "+i),this.getWebExperiments((r=>{this.ha(parseInt(n),i,r)}),!1,!0))}}loadIfEnabled(){this.Ne.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,n,i){if(this.Ne.disable_web_experiments&&!i)return e([]);var r=this._instance.get_property("$web_experiments");if(r&&!n)return e(r);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this.Ne.token),method:"GET",timestampMode:"query",callback:s=>e(s.statusCode===200&&s.json&&s.json.experiments||[])})}ha(e,n,i){var r=i.filter((s=>s.id===e));r&&r.length>0&&(Me.aa("Previewing web experiment ["+r[0].name+"] with variant ["+n+"]"),this.la(r[0].name,n,r[0].variants[n].transforms))}static ua(e,n){return!H(e.conditions)&&Me.da(e,n)&&Me.va(e)}static da(e,n){var i;if(H(e.conditions)||H((i=e.conditions)==null?void 0:i.url))return!0;var r=Me.getWindowLocation();if(r){var s,o,a,l=sf(n,r.href);return(s=e.conditions)==null||!s.url||Wm[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return w?.location}static va(e){var n;if(H(e.conditions)||H((n=e.conditions)==null?void 0:n.utm))return!0;var i=wf();if(i.utm_source){var r,s,o,a,l,u,c,d,h=(r=e.conditions)==null||(r=r.utm)==null||!r.utm_campaign||((s=e.conditions)==null||(s=s.utm)==null?void 0:s.utm_campaign)==i.utm_campaign,f=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==i.utm_source,p=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==i.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==i.utm_term;return h&&p&&g&&f}return!1}static aa(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;n>r;r++)i[r-1]=arguments[r];A.info("[WebExperiments] "+e,i)}la(e,n,i){this._is_bot()?Me.aa(yu):n!=="control"?i.forEach((r=>{if(r.selector){var s;Me.aa("applying transform of variant "+n+" for experiment "+e+" ",r);var o=(s=document)==null?void 0:s.querySelectorAll(r.selector);o?.forEach((a=>{var l=a;r.html&&(l.innerHTML=r.html),r.css&&l.setAttribute("style",r.css)}))}})):Me.aa("Control variants leave the page unmodified.")}_is_bot(){return Ue&&this._instance?Df(Ue,this.Ne.custom_blocked_useragents):void 0}}var st=pe("[Conversations]"),En="Conversations not available yet.",wu="console",Kf="__posthogHandledLogsRequestError",Do=(t,e)=>{var n=t instanceof Error?t:new Error(e);return n[Kf]=!0,n},bu=t=>!!t&&typeof t=="object"&&t[Kf]===!0,Cs={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=gu,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 Hm(t.config,t.Qi()),this.Ta=this.Ea)}updateConfig(t,e){var n;(n=this.Ea)==null||n.update(t,e)}setup(t){return this.Ia=t,this.rt=t.logger.createLogger("[FeatureFlags]"),n=()=>{this.Ia===t&&(this.Ia=void 0,this.nn=t,this.Pa(t))},(e=t.kv.initialize())!=null&&e.then?e.then(n):n();var e,n}Pa(t){if(this.nn===t)return w&&ve(w,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){w?.removeEventListener("online",this.Ca)}dispose(){var t;this.ba++,this.wa=!1,this.Ia=void 0,this.nn&&(this.La(),(t=this.Ra)==null||t.dispose(),this.Ra=void 0,this.ga=[],w?.removeEventListener("online",this.Ca),this.nn=void 0)}get Ne(){return this.Ta.get()}Oa(t){var e;return(e=this.nn)==null?void 0:e.kv.get(t)}F(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.set(t)}))}q(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.remove(t)}))}Da(t){try{t()}catch(e){this.rt.error("Failed to update feature flag persistence",e)}}Fa(){var t={};for(var e of[Ti,$i,Pr,It]){var n=this.Oa(e);C(n)||(t[e]=n)}this.fa=t;var i=I({},t),r=this.Oa(Sn);if(r)for(var s of Object.entries(r))i["$feature/"+s[0]]=s[1];this.pa=i}Aa(){var t=this.Ne.cacheTtlMs;if(!t||0>=t)return!1;var e=this.Oa(ji);return typeof e!="number"||Date.now()-e>t}$a(){return!!this.Aa()&&(this.xa||this.ya||(this.xa=!0,this.rt.warn("Feature flag cache is stale, triggering refresh..."),this.reloadFeatureFlags()),!0)}Na(){var t=this.Ne.evaluationContexts;return t!=null&&t.length?t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid evaluation context found:",e,"Expected non-empty string"),n})):[]}qa(){var t=this.Ne.flagKeys;if(!C(t))return t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid flag key found:",e,"Expected non-empty string"),n}))}initialize(){var t,e,n=this.Ne,i=(t=(e=n.bootstrap)==null?void 0:e.featureFlags)!==null&&t!==void 0?t:{};if(Object.keys(i).length){var r,s,o=(r=(s=n.bootstrap)==null?void 0:s.featureFlagPayloads)!==null&&r!==void 0?r:{},a=Object.keys(i).filter((u=>!!i[u])).reduce(((u,c)=>(u[c]=i[c]||!1,u)),{}),l=Object.keys(o).filter((u=>a[u])).reduce(((u,c)=>(o[c]&&(u[c]=o[c]),u)),{});return this.ja({featureFlags:a,featureFlagPayloads:l})}}updateFlags(t,e,n){var i,r,s=n!=null&&n.merge&&(i=this.Oa(Sn))!==null&&i!==void 0?i:{},o=n!=null&&n.merge&&(r=this.Oa($i))!==null&&r!==void 0?r:{},a=I({},s,t),l=I({},o,e),u={};for(var c of Object.entries(a)){var d=c[0],h=c[1];u[d]={key:d,enabled:hc(h),variant:pc(h),reason:void 0,metadata:C(l?.[d])?void 0:{id:0,version:void 0,description:void 0,payload:l[d]}}}this.ja({flags:u})}get hasLoadedFlags(){return this.ma}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var t=this.Oa(aa),e=this.Oa(It),n=this.Oa(xn);if(!n&&!e)return t||{};var i=fe({},t||{}),r=[...new Set([...Object.keys(n||{}),...Object.keys(e||{})])];for(var s of r){var o,a,l=i[s],u=e?.[s],c=C(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=C(u)?l?.variant:typeof u=="string"?u:void 0,h=n?.[s],f=I({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(f.original_enabled=l?.enabled),d!==l?.variant&&(f.original_variant=l?.variant),h&&(f.metadata=I({},l?.metadata,{payload:h,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),i[s]=f}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:n,finalDetails:i}),this.ca=!0),i}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((n=>{var i=t[n];return{key:n,enabled:hc(i),variant:pc(i),payload:fc(e[n])}}))}getFlagVariants(){var t=this.Oa(Sn),e=this.Oa(It);if(!e)return t||{};for(var n=fe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:e,finalFlags:n}),this.ca=!0),n}getFlagPayloads(){var t=this.Oa($i),e=this.Oa(xn);if(!e)return t||{};for(var n=fe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flag payloads!",{flagPayloads:t,overriddenPayloads:e,finalPayloads:n}),this.ca=!0),n}reloadFeatureFlags(){this._a||this.Ne.featureFlagsDisabled||this.Ma()||this.Ba||(this.ga.slice().forEach((t=>{try{t()}catch(e){this.rt.error("Error while running feature flags reloading callback",e)}})),this.Ba=setTimeout((()=>{this.Ha()}),5))}La(){clearTimeout(this.Ba),this.Ba=void 0}onReloading(t){return this.ga.push(t),()=>{this.ga=this.ga.filter((e=>e!==t))}}ensureFlagsLoaded(){this.ma||this.ya||this.Ba||this.reloadFeatureFlags()}setAnonymousDistinctId(t){this.$anon_distinct_id=t}setReloadingPaused(t){this._a=t}resetFlagCallReported(){this.q(Cn)}Ha(t){this.La();var e=this.nn;if(e&&!this.Ne.remoteRequestsDisabled&&!this.Ma())if(this.ya)this.wa=!0;else{var n={token:e.projectToken,distinct_id:e.distinctId,groups:e.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:I({},e.initialPersonProperties,this.Oa(jt)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(In),timezone:kf()};C(e.deviceId)||(n.$device_id=e.deviceId),(t!=null&&t.disableFlags||this.Ne.featureFlagsDisabled)&&(n.disable_flags=!0);var i=this.Na();i.length&&(n.evaluation_contexts=i);var r=this.qa();C(r)||(n.flag_keys=r);var s=this.Ne.onlyEvaluateSurveyFeatureFlags,o="/flags/?v=2"+(s?"&only_evaluate_survey_feature_flags=true":""),a=this.ba;this.ya=!0;var l=()=>{this.wa&&(this.wa=!1,this.Ha())},u=c=>{this.ya=!1,a===this.ba&&(this.F({[Tr]:[mu]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:n,compression:this.Ne.compression==="base64"?je.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,h,f=(d=c.json)!==null&&d!==void 0?d:{},p=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),p||this.wa||(this.$anon_distinct_id=void 0),!n.disable_flags||this.wa){this.ka=!p;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?mu:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),f.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((h=f.quotaLimited)==null||!h.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[Tr]:g}),m?this.rt.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more."):n.disable_flags||this.ja(f,p,{partialResponse:s}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return _f(this.Sa,3)}Ua(t){this.Sa=yf(t,this.Sa,3,(()=>this.rt.warn("Feature flag requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped refreshing feature flags; will try again when connectivity changes.")))}getFeatureFlag(t,e){var n;if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var i=this.getFeatureFlagResult(t,e);return(n=i?.variant)!==null&&n!==void 0?n:i?.enabled}}else this.rt.warn('getFeatureFlag for key "'+t+Bo)}getFeatureFlagDetails(t){return this.getFlagsWithDetails()[t]}getFeatureFlagPayload(t){var e=this.getFeatureFlagResult(t,{send_event:!1});return e?.payload}getFeatureFlagResult(t,e){if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var n,i=this.getFlagVariants(),r=t in i,s=i[t],o=this.getFlagPayloads()[t],a=String(s),l=this.Oa(Pr)||void 0,u=this.Oa(ji)||void 0,c=this.Oa(Cn)||{};if(this.Ne.deduplicateCallsPerSession){var d,h=(d=this.nn)==null?void 0:d.session.sessionId,f=this.Oa(Li);h&&h!==f&&(c={},n=h)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))n&&this.F({[Cn]:c,[Li]:n});else{var p,g,m,v,E,S,_,b,k,T;U(c[t])?c[t].push(a):c[t]=[a],this.F(I({[Cn]:c},n?{[Li]:n}:{}));var x=this.getFeatureFlagDetails(t),F=[...(p=this.Oa(Tr))!==null&&p!==void 0?p:[]];C(s)&&F.push("flag_missing");var $={$feature_flag:t,$feature_flag_response:s,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((g=this.Ne.bootstrap)==null||(g=g.featureFlags)==null?void 0:g[t])||null,$feature_flag_bootstrapped_payload:((m=this.Ne.bootstrap)==null||(m=m.featureFlagPayloads)==null?void 0:m[t])||null,$used_bootstrap_value:!this.ka};C(x==null||(v=x.metadata)==null?void 0:v.has_experiment)||($.$feature_flag_has_experiment=x.metadata.has_experiment),C(x==null||(E=x.metadata)==null?void 0:E.version)||($.$feature_flag_version=x.metadata.version);var O,L=(S=x==null||(_=x.reason)==null?void 0:_.description)!==null&&S!==void 0?S:x==null||(b=x.reason)==null?void 0:b.code;L&&($.$feature_flag_reason=L),x!=null&&(k=x.metadata)!=null&&k.id&&($.$feature_flag_id=x.metadata.id),C(x?.original_variant)&&C(x?.original_enabled)||($.$feature_flag_original_response=C(x.original_variant)?x.original_enabled:x.original_variant),x!=null&&(T=x.metadata)!=null&&T.original_payload&&($.$feature_flag_original_payload=x==null||(O=x.metadata)==null?void 0:O.original_payload),F.length&&($.$feature_flag_error=F.join(",")),this.za($)}else n&&this.F({[Cn]:c,[Li]:n});if(r)return{key:t,enabled:!!s,variant:typeof s=="string"?s:void 0,payload:fc(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+Bo)}za(t){try{var e;(e=this.nn)==null||e.capture("$feature_flag_called",t).catch((n=>{this.rt.error("Failed to capture feature flag call",n)}))}catch(n){this.rt.error("Failed to capture feature flag call",n)}}getRemoteConfigPayload(t,e){this.Wa(t,e)}Wa(t,e){var n=this;return se((function*(){var i=n.nn;if(i){var r={distinct_id:i.distinctId,token:i.projectToken,person_properties:{$lib:i.library.name,$lib_version:i.library.version}},s=n.Na();s.length&&(r.evaluation_contexts=s);var o,a=n.qa();C(a)||(r.flag_keys=a);try{var l,u=(l=(yield i.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:r,compression:n.Ne.compression==="base64"?je.Base64:void 0,sentAt:"body",timeoutMs:n.Ne.requestTimeoutMs})).json)==null?void 0:l.featureFlagPayloads;o=u?.[t]||void 0}catch(c){return void n.rt.error("Remote config feature flag request failed",c)}try{e(o)}catch(c){n.rt.error("Remote config feature flag callback failed",c)}}}))()}isFeatureEnabled(t,e){if(e===void 0&&(e={}),e.fresh&&!this.ka)return e.defaultValue;if(!(this.ma||this.getFlags()&&this.getFlags().length>0))return this.rt.warn('isFeatureEnabled for key "'+t+Bo),e.defaultValue;var n=this.getFeatureFlag(t,e);return C(n)?e.defaultValue:!!n}addFeatureFlagsHandler(t){this.featureFlagEventHandlers.push(t)}removeFeatureFlagsHandler(t){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((e=>e!==t))}receivedFeatureFlags(t,e,n){this.ja(t,e,n)}ja(t,e,n){if(this.nn){this.ma=!0;var i=(function(r,s,o,a,l,u){s===void 0&&(s={}),o===void 0&&(o={}),a===void 0&&(a={}),u===void 0&&(u=gu);var c=((k,T)=>{var x=k.flags;return x?I({},k,{featureFlags:Object.fromEntries(Object.keys(x).map((F=>{var $;return[F,($=x[F].variant)!==null&&$!==void 0?$:x[F].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(x).filter((F=>x[F].enabled)).filter((F=>{var $;return($=x[F].metadata)==null?void 0:$.payload})).map((F=>{var $;return[F,($=x[F].metadata)==null?void 0:$.payload]})))}):(k.featureFlags&&T.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),k)})(r,u),d=c.flags,h=c.featureFlags,f=c.featureFlagPayloads;if(h){var p=r.requestId,g=r.evaluatedAt;if(U(h)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(h)for(var v=0;h.length>v;v++)m[h[v]]=!0;return{[Ti]:h,[Sn]:m,[Zr]:!1}}var E=h,S=f,_=d;if(l!=null&&l.partialResponse)E=I({},s,E),S=I({},o,S),_=I({},a,_);else if(r.errorsWhileComputingFlags)if(d){var b=new Set(Object.keys(d).filter((k=>{var T;return!((T=d[k])!=null&&T.failed)})));E=I({},s,Object.fromEntries(Object.entries(E).filter((k=>b.has(k[0]))))),S=I({},o,Object.fromEntries(Object.entries(S||{}).filter((k=>b.has(k[0]))))),_=I({},a,Object.fromEntries(Object.entries(_||{}).filter((k=>b.has(k[0])))))}else E=I({},s,E),S=I({},o,S),_=I({},a,_);return I({[Ti]:Object.keys(_u(E)),[Sn]:E||{},[$i]:S||{},[aa]:_||{},[Zr]:r.minimalFlagCalledEvents===!0},p?{[Pr]:p}:{},g?{[ji]:g}:{})}})(t,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),n,this.rt);i&&this.F(i),e||(this.xa=!1),this.Va(e)}}override(t,e){e===void 0&&(e=!1),this.rt.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:t,suppressWarning:e})}overrideFeatureFlags(t){this.Za(t)}Za(t){if(this.nn){if(t===!1)return this.q([It,xn]),this.Va(),void bn.info("All overrides cleared");if(U(t))return this.F({[It]:vu(t)}),this.Va(),void bn.info("Flag overrides set",{flags:t});if(t&&typeof t=="object"&&("flags"in t||"payloads"in t)){var e,n=t;this.ca=!!((e=n.suppressWarning)!==null&&e!==void 0&&e);var i={},r=n.flags,s=n.payloads;return r&&(i[It]=U(r)?vu(r):r),s&&(i[xn]=s),Object.keys(i).length&&this.F(i),r===!1&&s===!1?this.q([It,xn]):r===!1?this.q(It):s===!1&&this.q(xn),this.Va(),r===!1?bn.info("Flag overrides cleared"):r&&bn.info("Flag overrides set",{flags:r}),void(s===!1?bn.info("Payload overrides cleared"):s&&bn.info("Payload overrides set",{payloads:s}))}if(t&&typeof t=="object")return this.F({[It]:t}),this.Va(),void bn.info("Flag overrides set",{flags:t});this.rt.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:t})}else this.rt.warn("posthog.featureFlags.overrideFeatureFlags called before feature flags were ready")}onFeatureFlags(t){if(this.addFeatureFlagsHandler(t),this.ma){var e=this.Ga(),n=e.flags,i=e.flagVariants;try{t(n,i)}catch(r){this.rt.error("Error while running feature flags callback",r)}}return()=>this.removeFeatureFlagsHandler(t)}updateEarlyAccessFeatureEnrollment(t,e,n){var i=(this.Oa(Ar)||[]).find((l=>l.flagKey===t)),r={["$feature_enrollment/"+t]:e},s={$feature_flag:t,$feature_enrollment:e,$set:r};i&&(s.$early_access_feature_name=i.name),n&&(s.$feature_enrollment_stage=n);var o=I({},this.getFlagVariants(),{[t]:e});this.F({[Ti]:Object.keys(_u(o)),[Sn]:o,[jt]:I({},this.Oa(jt)||{},r)}),this.Va();try{var a;(a=this.nn)==null||a.capture("$feature_enrollment_update",s).catch((l=>{this.rt.error("Failed to capture early access feature enrollment",l)}))}catch(l){this.rt.error("Failed to capture early access feature enrollment",l)}}getEarlyAccessFeatures(t,e,n){e===void 0&&(e=!1);var i=this.Oa(Ar);!i||e?this.Qa(t,n):t(i)}Qa(t,e){var n=this;return se((function*(){var i=n.nn;if(i){var r,s=e?"&"+e.map((a=>"stage="+a)).join("&"):"";try{var o=yield i.sendRequest("/api/early_access_features/?token="+i.projectToken+s,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;n.F({[Ar]:r=o.json.earlyAccessFeatures})}catch(a){return void n.rt.error("Early access feature request failed",a)}try{t(r)}catch(a){n.rt.error("Early access feature callback failed",a)}}}))()}Ga(){var t=this.getFlags(),e=this.getFlagVariants();return{flags:t.filter((n=>e[n])),flagVariants:Object.keys(e).filter((n=>e[n])).reduce(((n,i)=>(n[i]=e[i],n)),{})}}Va(t){this.Fa();var e=this.Ga(),n=e.flags,i=e.flagVariants;this.featureFlagEventHandlers.forEach((r=>{try{r(n,i,{errorsLoading:t})}catch(s){this.rt.error("Error while running feature flags callback",s)}}))}setPersonPropertiesForFlags(t,e){e===void 0&&(e=!0),this.Ka(t,e)}Ka(t,e){e===void 0&&(e=!0);var n=this.Oa(jt)||{},i=t?.$set||(t!=null&&t.$set_once?{}:t),r=t?.$set_once,s={};if(r)for(var o in r)({}).hasOwnProperty.call(r,o)&&(o in n||(s[o]=r[o]));this.F({[jt]:I({},n,s,i)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=I({},this.Oa(jt)||{});t.forEach((i=>{delete n[i]})),this.F({[jt]:n}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(jt),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=this.Oa(In)||{},i=I({},n);for(var r of Object.keys(t))i[r]=I({},n[r],t[r]);this.F({[In]:i}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(In)||{};this.F({[In]:I({},e,{[t]:{}})})}else this.q(In)}reset(){this.ba++,this.wa=!1,this.Fa(),this.ma=!1,this._a=!1,this.ka=!1,this.$anon_distinct_id=void 0,this.La(),this.ca=!1,this.Sa=0}}},qm={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===ki||this.Ya===Sr?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=lu,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(P==null||!P.visibilityState||P.visibilityState==="visible")return!0;var n=w==null||(e=w.performance)==null||e.getEntriesByType==null?void 0:e.getEntriesByType("visibility-state");return!(n!=null&&n.length)||n.some((i=>i.name==="visible"))})(),this.Ie=()=>{var e;P?.visibilityState==="visible"&&(this.io=!0,(e=this.Ja)==null||e.setDocumentWasEverVisible==null||e.setDocumentWasEverVisible(!0))},this._instance=t,!this._instance.sessionManager)throw Bt.error("started without valid sessionManager"),new Error(Ia+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===Wt)throw new Error(Ia+' cannot be used with cookieless_mode="always"');P!=null&&P.addEventListener&&ve(P,"visibilitychange",this.Ie)}initialize(){this.startIfEnabledOrStop()}dispose(){this.eo=!0,P==null||P.removeEventListener==null||P.removeEventListener("visibilitychange",this.Ie),this.stopRecording()}get ro(){var t,e=!((t=this._instance.get_property(An))==null||!t.enabled),n=!this.Ne.disable_session_recording,i=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return w&&e&&n&&!i}startIfEnabledOrStop(t){var e;if(!(this.eo||this.ro&&(e=this.Ja)!=null&&e.isStarted)){var n=!C(Object.assign)&&!C(Array.from);this.ro&&n?(this.no(t),Bt.info("starting")):(this.Ya=lu,this.stopRecording())}}no(t){var e,n,i;this.ro&&(this.Ya!==ki&&this.Ya!==Sr&&(this.Ya=cu),B!=null&&(e=B.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(n=B.__PosthogExtensions__)!=null&&n.initSessionRecording?this.so(t):(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,this.ao,(r=>{if(r)return Bt.error("could not load recorder",r);this.so(t)})))}stopRecording(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.stop()}oo(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.discard()}lo(){var t,e;(t=this.Mr)==null||t.unregister(ol),(e=this.Mr)==null||e.unregister(Gd)}uo(t,e){if(H(t))return null;var n,i=ke(t)?t:parseFloat(t);return typeof(n=i)!="number"||!Number.isFinite(n)||0>n||n>1?(Bt.warn(e+" must be between 0 and 1. Ignoring invalid value:",t),null):i}ho(t){if(this.Mr){var e,n,i=this.Mr,r=()=>{var s,o=t.sessionRecording===!1?void 0:t.sessionRecording,a=this.uo((s=this.Ne.session_recording)==null?void 0:s.sampleRate,"session_recording.sampleRate"),l=this.uo(o?.sampleRate,"remote config sampleRate"),u=a??l;H(u)&&this.lo();var c=o?.minimumDurationMilliseconds;i.register({[An]:I({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:I({capturePerformance:t.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:u,minimumDurationMilliseconds:C(c)?null:c,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers,version:o?.version,triggerGroups:o?.triggerGroups})})};r(),(e=this.Xa)==null||e.call(this),this.Xa=(n=this._instance.sessionManager)==null?void 0:n.onSessionId(r)}}onRemoteConfig(t){var e=t.ok?t.config:void 0;return e&&"sessionRecording"in e?e.sessionRecording===!1?(this.ho(e),void this.oo()):(this.ho(e),void this.startIfEnabledOrStop()):(this.Ya===ki&&(this.Ya=Sr,Bt.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(t,e){var n;e===void 0&&(e="log"),(n=this.Ja)!=null&&n.log?this.Ja.log(t,e):Bt.warn("log called before recorder was ready")}get ao(){var t,e,n=(t=this._instance)==null||(t=t.persistence)==null?void 0:t.get_property(An);return(n==null||(e=n.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(An);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(n){return Bt.warn("persisted remote config for session recording is invalid and will be ignored",n),!1}return!H(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,n,i;if(!this.eo){if((e=B.__PosthogExtensions__)==null||!e.initSessionRecording)return Bt.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[tf]:!0});var r;if(this.Ja||(this.Ja=(r=B.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===Sr||this.Ya===ki?void 0:(this.Ya=ki,Bt.info("persisted remote config is stale, requesting fresh config before starting"),void new Cf(this._instance).load());this.Ya=cu,(n=(i=this.Ja).setDocumentWasEverVisible)==null||n.call(i,this.io),this.Ja.start(t)}}onRRwebEmit(t){var e;(e=this.Ja)==null||e.onRRwebEmit==null||e.onRRwebEmit(t)}overrideLinkedFlag(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Yd]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Kd]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,n;this.Ja||(n=this.Mr)==null||n.register({[t==="url"?Jd:Zd]:!0}),(e=this.Ja)==null||e.overrideTrigger(t)}get sdkDebugProperties(){var t;return((t=this.Ja)==null?void 0:t.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(t,e){var n;return!((n=this.Ja)==null||!n.tryAddCustomEvent(t,e))}}},zm={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new su(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,n=he(this.instance.config.autocapture)?this.instance.config.autocapture:{};return n.url_allowlist=(t=n.url_allowlist)==null?void 0:t.map((i=>new RegExp(i))),n.url_ignorelist=(e=n.url_ignorelist)==null?void 0:e.map((i=>new RegExp(i))),n}yo(){if(this.isBrowserSupported()){if(w&&P){var t=n=>{n=n||w?.event;try{this.bo(n)}catch(i){Mo.error("Failed to capture event",i)}};if(ve(P,"submit",t,{capture:!0}),ve(P,"change",t,{capture:!0}),ve(P,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=n=>{n=n||w?.event;try{this.bo(n,$o)}catch(i){Mo.error("Failed to capture copy/cut event",i)}};ve(P,"copy",e,{capture:!0}),ve(P,"cut",e,{capture:!0})}}}else Mo.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.vo&&(this.yo(),this.vo=!0)}onRemoteConfig(t){if(this.fo=!0,t.ok){var e=t.config;e.elementsChainAsString&&(this.po=e.elementsChainAsString);var n=e.autocapture_opt_out;mt(n)&&(this.instance.persistence&&this.instance.persistence.register({[ea]:n}),this.co=n),this.startIfEnabled()}else this.startIfEnabled()}setElementSelectors(t){this.mo=t}getElementSelectors(t){var e,n=[];return(e=this.mo)==null||e.forEach((i=>{var r=P?.querySelectorAll(i);r?.forEach((s=>{t===s&&n.push(i)}))})),n}get isEnabled(){var t,e,n=(t=this.instance.persistence)==null?void 0:t.props[ea],i=this.co,r=this.instance.Qi()&&!this.fo;if(Ke(i)&&!mt(n)&&!r)return!1;var s=(e=this.co)!==null&&e!==void 0?e:!!n;return!!this.instance.config.autocapture&&!s}bo(t,e){if(e===void 0&&(e="$autocapture"),this.isEnabled){var n,i=bo(t);af(i)&&(i=i.parentNode||null),e==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&this.instance.config.rageclick&&(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,t.timeStamp||new Date().getTime())&&Lc(i,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var r=e===$o;if(i&&(function(d,h,f,p,g,m){var v;if(!w||dl(d)||f!=null&&f.url_allowlist&&!Tc(f.url_allowlist,m)||f!=null&&f.url_ignorelist&&Tc(f.url_ignorelist,m))return!1;if(f!=null&&f.dom_event_allowlist){var E=f.dom_event_allowlist;if(E&&!E.some((x=>h.type===x)))return!1}var S=hf(d,p),_=S.parentIsUsefulElement,b=S.targetElementList;if(!(function(x,F){var $=F?.element_allowlist;if(C($))return!0;var O,L=function(K){if($.some((V=>K.tagName.toLowerCase()===V)))return{v:!0}};for(var N of x)if(O=L(N))return O.v;return!1})(b,f)||!ma(b,f?.css_selector_allowlist)||ma(b,(v=f?.css_selector_ignorelist)!==null&&v!==void 0?v:Hg))return!1;try{var k=w.getComputedStyle(d);if(k&&k.getPropertyValue("cursor")==="pointer"&&h.type==="click")return!0}catch{}var T=d.tagName.toLowerCase();switch(T){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 _?(g||["click"]).indexOf(h.type)>=0:(g||["click"]).indexOf(h.type)>=0&&(ul.indexOf(T)>-1||d.getAttribute("contenteditable")==="true")}})(i,t,this.Ne,r,r?["copy","cut"]:void 0,this.instance)){var s=Mm(i,{e:t,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.Ne.element_attribute_ignorelist,elementsChainAsString:this.po,disableCaptureUrlHashes:this.instance.config.disable_capture_url_hashes}),o=s.props;if(s.explicitNoCapture)return!1;var a=this.getElementSelectors(i);if(a&&a.length>0&&(o.$element_selectors=a),e===$o){var l,u=uf(w==null||(l=w.getSelection())==null?void 0:l.toString()),c=t.type||"clipboard";if(!u)return!1;o.$selected_content=u,o.$copy_type=c}return this.instance.capture(e,o),!0}}}isBrowserSupported(){return De(P?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(w==null||(e=w.location)==null?void 0:e.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(A.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.wo&&this.wo(),this.wo=void 0,A.info("History API monitoring stopped")}monitorHistoryChanges(){w&&w.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(w&&((e=w.history[t])==null||!e.__posthog_wrapped__)){var n=this;(function(i,r,s){try{if(!(r in i))return ou;var o={next:i[r]},a=s((function(){for(var l=arguments.length,u=new Array(l),c=0;l>c;c++)u[c]=arguments[c];return o.next.apply(this,u)}));return De(a)&&(a.prototype=a.prototype||{},Object.defineProperties(a,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:o}})),i[r]=a,()=>{if(i[r]!==a)for(var l=i[r];De(l)&&l.__posthog_layer__;){var u=l.__posthog_layer__;if(u.next===a)return void(u.next=o.next);l=u.next}else i[r]=o.next}}catch{return ou}})(w.history,t,(i=>function(r,s,o){i.call(this,r,s,o),n.So(t)}))}}So(t){try{var e,n=w==null||(e=w.location)==null?void 0:e.pathname;if(!n)return;n!==this._o&&this.isEnabled&&this._instance.capture(Vn,{navigation_type:t}),this._o=n}catch(i){A.error("Error capturing "+t+" pageview",i)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};ve(w,"popstate",t),this.wo=()=>{w&&w.removeEventListener("popstate",t)}}}},heatmaps:class{get Ne(){return this.instance.config}constructor(t){var e;this.Co=!1,this.vo=!1,this.Mo=null,this.instance=t,this.Co=!((e=this.instance.persistence)==null||!e.props[ta]),this.rageclicks=new su(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return he(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return H(this.Ne.capture_heatmaps)?H(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;Nm.info("starting..."),this.To(),this.Ie()}else{var t;clearInterval((t=this.Mo)!==null&&t!==void 0?t:void 0),this.Eo(),this.getAndClearBuffer()}}onRemoteConfig(t){if(t.ok){var e=t.config;if("heatmaps"in e){var n=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[ta]:n}),this.Co=n,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){No(t.originalEvent)&&this.ke(t.originalEvent,"deadclick")}Ie(){this.Mo&&clearInterval(this.Mo),this.Mo=P?.visibilityState==="visible"?setInterval(this.cr.bind(this),this.flushIntervalMilliseconds):null}To(){w&&P&&(this.Po=this.cr.bind(this),ve(w,ns,this.Po),this.Ro=t=>this.ke(t||w?.event),ve(P,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||w?.event),ve(P,"mousemove",this.Ao,{capture:!0}),this.Lo=new Hc(this.instance,Yg,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),ve(P,ts,this.Oo),this.vo=!0)}Eo(){var t;w&&P&&(this.Po&&w.removeEventListener(ns,this.Po),this.Ro&&P.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&P.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&P.removeEventListener(ts,this.Oo),clearTimeout(this.Do),(t=this.Lo)==null||t.stop(),this.vo=!1)}$o(t,e){var n=this.instance.scrollManager.scrollY(),i=this.instance.scrollManager.scrollX(),r=this.instance.scrollManager.scrollElement(),s=(function(o,a,l){for(var u=o;u&&hn(u)&&!Qe(u,"body");){if(u===l)return!1;var c=void 0;try{var d,h,f;c=(d=(h=(f=u.ownerDocument)==null?void 0:f.defaultView)!==null&&h!==void 0?h:w)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(j(a,c))return!0;u=df(u)}return!1})(bo(t),["fixed","sticky"],r);return{x:t.clientX+(s?0:i),y:t.clientY+(s?0:n),target_fixed:s,type:e}}ke(t,e){var n;if(e===void 0&&(e="click"),!Rc(t.target)&&No(t)){var i=this.$o(t,e);(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,new Date().getTime())&&Lc(bo(t),this.instance.config.rageclick)&&this.Vt(I({},i,{type:"rageclick"})),this.Vt(i)}}Fo(t){!Rc(t.target)&&No(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(w){var e=this.Ne.disable_capture_url_hashes?fn(w.location.href):w.location.href,n=this.Ne.custom_personal_data_properties,i=this.Ne.mask_personal_data_properties?[...ri,...n||[]]:[],r=Zi(e,i,Xi);this.R=this.R||{},this.R[r]||(this.R[r]=[]),this.R[r].push(t)}}cr(){this.R&&!Kt(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:Hc,webVitalsAutocapture:class{constructor(t){var e;this.Co=!1,this.vo=!1,this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this.No=()=>{clearTimeout(this.qo),this.qo=void 0,this.R.metrics.length!==0&&(this._instance.capture("$web_vitals",I({$current_url:this.R.url},this.R.metrics.reduce(((n,i)=>I({},n,{["$web_vitals_"+i.name+"_event"]:I({},i),["$web_vitals_"+i.name+"_value"]:i.value})),{}))),this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.jo=n=>{var i;if(this.R=this.R||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},H(n?.name)||H(n?.value))wn.error("Invalid metric received",n);else{var r=typeof n.navigationURL=="string"?n.navigationURL:void 0,s=this.Bo(r);if(!C(s)){var o=ke(n.navigationId)||typeof n.navigationId=="string"?"navigation:"+n.navigationId:"url:"+s;if(!this.Ho||this.Ho>n.value){this.R.navigationKey!==o&&(this.No(),this.qo=setTimeout(this.No,this.flushToCaptureTimeoutMs)),C(this.R.navigationKey)&&(this.R.navigationKey=o,this.R.url=s),this.R.firstMetricTimestamp=C(this.R.firstMetricTimestamp)?Date.now():this.R.firstMetricTimestamp,n.attribution&&n.attribution.interactionTargetElement&&(n.attribution.interactionTargetElement=void 0);var a=(i=this._instance.sessionManager)==null?void 0:i.checkAndGetSessionAndWindowId(!0),l=I({},n,r?{navigationURL:s}:{},{$current_url:s,timestamp:Date.now()});C(a)||(l.$session_id=a.sessionId,l.$window_id=a.windowId),this.R.metrics.push(l),this.R.metrics.length===this.allowedMetrics.length&&this.No()}else wn.error("Ignoring metric with value >= "+this.Ho,n)}}},this.Uo=()=>{if(!this.vo){var n,i,r,s,o=B.__PosthogExtensions__,a=o?.postHogWebVitalsCallbacksByFlavor,l=a?.[this.zo]||(this.zo==="web-vitals"&&C(a)?o?.postHogWebVitalsCallbacks:void 0);if(C(l)||(n=l.onLCP,i=l.onCLS,r=l.onFCP,s=l.onINP),n&&i&&r&&s){var u={reportSoftNavs:this.useSoftNavs};this.allowedMetrics.indexOf("LCP")>-1&&n(this.jo.bind(this),u),this.allowedMetrics.indexOf("CLS")>-1&&i(this.jo.bind(this),u),this.allowedMetrics.indexOf("FCP")>-1&&r(this.jo.bind(this),u),this.allowedMetrics.indexOf("INP")>-1&&s(this.jo.bind(this),u),this.vo=!0}else wn.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[sa]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,n=he(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return H(n)?((e=this._instance.persistence)==null?void 0:e.props[oa])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(he(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=he(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=he(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=he(this.Wo)&&ke(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:au;return t>0&&6e4>=t?au:t}get isEnabled(){var t=me?.protocol;if(t!=="http:"&&t!=="https:")return wn.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=he(this.Wo)?this.Wo.web_vitals:mt(this.Wo)?this.Wo:void 0;return mt(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(wn.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var n=he(e.capturePerformance)&&!!e.capturePerformance.web_vitals,i=he(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[sa]:n}),this._instance.persistence.register({[oa]:i})),this.Co=n,this.startIfEnabled()}}}get zo(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}ai(t){var e=B.__PosthogExtensions__,n=this.zo,i=e?.postHogWebVitalsCallbacksByFlavor;i!=null&&i[n]||n==="web-vitals"&&C(i)&&e!=null&&e.postHogWebVitalsCallbacks?t():e==null||e.loadExternalDependency==null||e.loadExternalDependency(this._instance,n,(r=>{r?wn.error("failed to load script",r):t()}))}Bo(t){var e=t||w?.location.href;if(e){var n=this._instance.config.disable_capture_url_hashes?fn(e):e,i=this._instance.config.custom_personal_data_properties,r=this._instance.config.mask_personal_data_properties?[...ri,...i||[]]:[];return Zi(n,r,Xi)}wn.error("Could not determine current URL")}}},Vm={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var n;if(w&&this.isEnabled&&(n=B.__PosthogExtensions__)!=null&&n.errorWrappingFunctions){var i=B.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,r=B.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,s=B.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.Vo&&this.Ne.capture_unhandled_errors&&(this.Vo=i(this.captureException.bind(this))),!this.Zo&&this.Ne.capture_unhandled_rejections&&(this.Zo=r(this.captureException.bind(this))),!this.Go&&this.Ne.capture_console_errors&&(this.Go=s(this.captureException.bind(this)))}catch(o){Ii.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[na]),this.Jo=new qp(I({},(function(n){var i,r,s,o;return n===void 0&&(n={}),{refillRate:(i=(r=n.exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:n.__exceptionRateLimiterRefillRate)!==null&&i!==void 0?i:1,bucketSize:(s=(o=n.exceptionRateLimiterBucketSize)!==null&&o!==void 0?o:n.__exceptionRateLimiterBucketSize)!==null&&s!==void 0?s:10}})(this._instance.config.error_tracking),{refillInterval:1e4,rt:Ii})),this.Ne=this.Yo(),this.startIfEnabledOrStop()}Yo(){var t=this._instance.config.capture_exceptions,e={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return he(t)?e=I({},e,t):(C(t)?this.Ko:t)&&(e=I({},e,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),e}get isEnabled(){return this.Ne.capture_console_errors||this.Ne.capture_unhandled_errors||this.Ne.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(Ii.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",(i=>{if(i)return Ii.error("failed to load script",i);t()}))}Qo(){var t,e,n;(t=this.Vo)==null||t.call(this),this.Vo=void 0,(e=this.Zo)==null||e.call(this),this.Zo=void 0,(n=this.Go)==null||n.call(this),this.Go=void 0}onRemoteConfig(t){if(t.ok){var e=t.config;"autocaptureExceptions"in e&&(this.Ko=!!e.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[na]:this.Ko}),this.Ne=this.Yo(),this.startIfEnabledOrStop())}}onConfigChange(){this.Ne=this.Yo()}captureException(t){var e,n,i,r=(e=t==null||(n=t.$exception_list)==null||(n=n[0])==null?void 0:n.type)!==null&&e!==void 0?e:"Exception";this.Jo.consumeRateLimit(r)?Ii.info("Skipping exception capture because of client rate limiting.",{exception:r}):(i=this._instance.exceptions)==null||i.sendExceptionEvent(t)}},exceptions:class{constructor(t){var e,n;this.Xo=[],this.tl=new ag([new gg,new xg,new vg,new mg,new Eg,new bg,new yg,new Sg],(function(i){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;r>o;o++)s[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` +`),d=l;c.length>d;d++){var h=c[d];if(1024>=h.length){var f=Cc.test(h)?h.replace(Cc,"$1"):h;if(!f.match(/\S*Error: /)){for(var p of s){var g=p(f,i);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var v=Array.from(m);return v.reverse(),v.slice(0,50).map((E=>{return I({},E,{filename:E.filename||(S=v,S[S.length-1]||{}).filename,function:E.function||ni});var S}))})(u)}})("web:javascript",dg,pg)),this._instance=t,this.Xo=(e=(n=this._instance.persistence)==null?void 0:n.get_property(ia))!==null&&e!==void 0?e:[],this.el=Jr(this.il()),this.rl=new kg(this.el)}onConfigChange(){this.el=Jr(this.il()),this.rl.setConfig(this.el)}onRemoteConfig(t){var e,n,i;if(t.ok){var r=t.config;if("errorTracking"in r){var s=(e=(n=r.errorTracking)==null?void 0:n.suppressionRules)!==null&&e!==void 0?e:[],o=(i=r.errorTracking)==null?void 0:i.captureExtensionExceptions;this.Xo=s,this._instance.persistence&&this._instance.persistence.register({[ia]:this.Xo,[ra]:o})}}}get nl(){var t,e=!!this._instance.get_property(ra),n=this._instance.config.error_tracking.captureExtensionExceptions;return(t=n??e)!==null&&t!==void 0&&t}buildProperties(t,e){return this.tl.buildFromUnknown(t,{syntheticException:e?.syntheticException,mechanism:{handled:e?.handled}})}addExceptionStep(t,e){if(this.el.enabled)try{if(!X(t)||t.trim().length===0)return void St.warn("Ignoring exception step because message must be a non-empty string");var n=(function(s){if(!s)return{sanitizedProperties:{},droppedKeys:[]};var o=[];return{sanitizedProperties:Object.keys(s).reduce(((a,l)=>Ig.has(l)?(o.push(l),a):(a[l]=s[l],a)),{}),droppedKeys:o}})(this.sl(e)),i=n.sanitizedProperties,r=n.droppedKeys;r.length>0&&St.warn("Ignoring reserved exception step fields",{droppedKeys:r}),this.rl.add(I({[Kr]:t,[Yr]:new Date().toISOString()},i))}catch(s){St.error("Failed to add exception step. Ignoring breadcrumb.",s)}}sendExceptionEvent(t){try{var e=t.$exception_list;if(this.al(e)){if(this.ol(e))return this.ll("Exception dropped: matched a suppression rule"),void St.info("Skipping exception capture because a suppression rule matched");if(!this.nl&&this.ul(e))return this.ll("Exception dropped: thrown by a browser extension"),void St.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.hl(e))return this.ll("Exception dropped: thrown by the PostHog SDK"),void St.info("Skipping exception capture because it was thrown by the PostHog SDK")}var n=this.el.enabled&&H(t.$exception_steps)?this.dl(t):t,i=typeof(s=globalThis._posthogReleaseId)=="string"&&s.length>0?s:void 0;i&&(n.$release_id=i);try{var r=this._instance.capture("$exception",n,{_noTruncate:!0,_batchKey:"exceptionEvent",Wn:!0});return r&&this.rl.clear(),r}catch(o){return St.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void St.error("Failed to process exception event. Ignoring this exception.",o)}var s}dl(t){try{var e=this.rl.getAttachable();return e.length===0?t:I({},t,{$exception_steps:e})}catch(n){return St.error("Failed to read buffered exception steps. Capturing exception without steps.",n),t}}ll(t){this.el.enabled&&this.rl.add({[Kr]:t,[Yr]:new Date().toISOString()})}sl(t){return he(t)?I({},t):{}}il(){var t,e;return(t=(e=this._instance.config.error_tracking)==null?void 0:e.exception_steps)!==null&&t!==void 0?t:{}}ol(t){if(t.length===0)return!1;try{var e=t.reduce(((n,i)=>{var r=i.type,s=i.value;return X(r)&&r.length>0&&n.$exception_types.push(r),X(s)&&s.length>0&&n.$exception_values.push(s),n}),{$exception_types:[],$exception_values:[]});return this.Xo.some((n=>{var i=n.values.map((r=>{var s=Uf[r.operator],o=e[r.key];if(!s||!o)return!1;var a=U(r.value)?r.value:[r.value];return a.length>0&&s(a,o)}));return n.type==="OR"?i.some(Boolean):i.every(Boolean)}))}catch(n){return St.warn("Failed to evaluate suppression rules. Capturing the exception.",n),!1}}ul(t){return t.flatMap((e=>{var n,i;return(n=(i=e.stacktrace)==null?void 0:i.frames)!==null&&n!==void 0?n:[]})).some((e=>e.filename&&e.filename.startsWith("chrome-extension://")))}hl(t){if(t.length>0){var e,n,i,r,s=(e=(n=t[0].stacktrace)==null?void 0:n.frames)!==null&&e!==void 0?e:[],o=s[s.length-1];return(i=o==null||(r=o.filename)==null?void 0:r.includes("posthog.com/static"))!==null&&i!==void 0&&i}return!1}al(t){return!H(t)&&U(t)}}},Gm=I({productTours:class{get Mr(){return this._instance.persistence}constructor(t){this.vl=null,this.cl=null,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(t.ok){var e=t.config;if("productTours"in e){var n,i;if(this.Mr&&this.Mr.register({[sl]:!!e.productTours}),!Oo(this._instance))return!this.vl&&H((n=this.Mr)==null?void 0:n.props[Mi])||xr.info("product tours disabled; stopping and clearing cached tours"),(i=this.vl)==null||i.stop(),this.vl=null,void this.clearCache();this.loadIfEnabled()}}}loadIfEnabled(){!this.vl&&Oo(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.generateProductTours?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",(i=>{i?xr.error("Could not load product tours script",i):t()}))}fl(){var t;!this.vl&&(t=B.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=B.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(t,e){if(e===void 0&&(e=!1),!U(this.cl)||e){var n=this.Mr;if(n){var i=n.props[Mi];if(U(i)&&!e)return this.cl=i,void t(i,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",timestampMode:"query",callback:r=>{if(Oo(this._instance)){var s=r.statusCode;if(s!==200||!r.json){var o="Product Tours API could not be loaded, status: "+s;return s===0?r.error||xr.warn(o):xr.error(o),void t([],{isLoaded:!1,error:o})}var a=U(r.json.product_tours)?r.json.product_tours:[];this.cl=a,n&&n.register({[Mi]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){H(this.vl)?t([],{isLoaded:!1,error:"Product tours not loaded"}):this.vl.getActiveProductTours(t)}showProductTour(t){var e;(e=this.vl)==null||e.showTourById(t)}previewTour(t){this.vl?this.vl.previewTour(t):this.ai((()=>{var e;this.fl(),(e=this.vl)==null||e.previewTour(t)}))}dismissProductTour(){var t;(t=this.vl)==null||t.dismissTour("user_clicked_skip")}nextStep(){var t;(t=this.vl)==null||t.nextStep()}previousStep(){var t;(t=this.vl)==null||t.previousStep()}clearCache(){var t;this.cl=null,(t=this.Mr)==null||t.unregister(Mi)}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)}}},Cs),Km={siteApps:class{constructor(t){this.pl=0,this._instance=t,this.gl=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}ml(t,e){if(e){var n=this.globalsForEvent(e);this.gl.push(n),this.gl.length>1e3&&(this.gl=this.gl.slice(10))}}get siteAppLoaders(){var t;return(t=B._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,n,i,r,s,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var h=d[0];l[h]={id:u[h],type:h,properties:d[1]}}var f=t.$set_once,p=t.$set;return{event:I({},dd(t,Om),{properties:I({},t.properties,p?{$set:I({},(e=(n=t.properties)==null?void 0:n.$set)!==null&&e!==void 0?e:{},p)}:{},f?{$set_once:I({},(i=(r=t.properties)==null?void 0:r.$set_once)!==null&&i!==void 0?i:{},f)}:{}),elements_chain:(s=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&s!==void 0?s:"",distinct_id:(a=t.properties)==null?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}bl(t){var e,n=(e=t.tagName)==null?void 0:e.toLowerCase();return n==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(Et.error("prepare_external_dependency_stylesheet returned null"),null):n==="script"&&this._instance.config.prepare_external_dependency_script?this._instance.config.prepare_external_dependency_script(t)||(Et.error("prepare_external_dependency_script returned null"),null):t}_l(){var t,e,n,i,r,s,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=P?.defaultView,u=l==null||(t=l.Node)==null?void 0:t.prototype;if(!l||!u)return()=>{};if(this.pl++,this.wl)return this.kl();var c=[],d=this,h=new WeakSet,f=(m,v,E)=>{if(m!=null&&m[v]){var S=m[v];m[v]=E(S),c.push((()=>{m[v]=S}))}},p=m=>{if(h.has(m))return m;var v=d.bl(m);return v&&h.add(v),v},g=m=>m.map((v=>typeof v=="string"?v:p(v))).filter((v=>!Ke(v)));return f(u,"appendChild",(m=>function(v){var E=p(v);return E?m.call(this,E):v})),f(u,"insertBefore",(m=>function(v,E){var S=p(v);return S?m.call(this,S,E):v})),f(u,"replaceChild",(m=>function(v,E){var S=p(v);return S?m.call(this,S,E):E})),[(e=l.Element)==null?void 0:e.prototype,(n=l.Document)==null?void 0:n.prototype,(i=l.DocumentFragment)==null?void 0:i.prototype].forEach((m=>{f(m,"append",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),f(m,"prepend",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))}))})),[(r=l.Element)==null?void 0:r.prototype,(s=l.CharacterData)==null?void 0:s.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((m=>{f(m,"before",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),f(m,"after",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),f(m,"replaceWith",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];var b=g(S);return S.length&&!b.length?void 0:v.apply(this,b)}))})),f((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(v,E){var S=p(E);return S?m.call(this,v,S):null})),this.wl=()=>{c.forEach((m=>m())),this.wl=void 0},this.kl()}kl(){var t=!1;return()=>{var e;t||(t=!0,this.pl--,this.pl===0&&((e=this.wl)==null||e.call(this)))}}xl(t,e){e===void 0&&(e=!0);var n=this._l();try{var i=t(n);return e&&n(),i}catch(r){throw n(),r}}setupSiteApp(t){var e=this.apps[t.id],n=()=>{var o;!e.errored&&this.gl.length&&(Et.info("Processing "+this.gl.length+" events for site app with id "+t.id),this.gl.forEach((a=>this.xl((()=>e.processEvent==null?void 0:e.processEvent(a))))),e.processedBuffer=!0),Object.values(this.apps).every((a=>a.processedBuffer||a.errored))&&((o=this.yl)==null||o.call(this))},i=!1,r=o=>{e.errored=!o,e.loaded=!0,Et.info("Site app with id "+t.id+" "+(o?"loaded":"errored")),i&&n()};try{var s=this.xl((o=>t.init({posthog:this._instance,callback(a){o(),r(a)}})),!1).processEvent;s&&(e.processEvent=s),i=!0}catch(o){Et.error(uu+t.id,o),r(!1)}if(i&&e.loaded)try{n()}catch(o){Et.error("Error while processing buffered events PostHog app with config id "+t.id,o),e.errored=!0}}Sl(){var t=this.siteAppLoaders||[];for(var e of t)this.apps[e.id]={id:e.id,loaded:!1,errored:!1,processedBuffer:!1};for(var n of t)this.setupSiteApp(n)}Cl(t){var e=this;if(Object.keys(this.apps).length!==0){var n=this.globalsForEvent(t),i=function(s){try{e.xl((()=>s.processEvent==null?void 0:s.processEvent(n)))}catch(o){Et.error("Error while processing event "+t.event+" for site app "+s.id,o)}};for(var r of Object.values(this.apps))i(r)}}onRemoteConfig(t){var e,n,i,r=this;if((e=this.siteAppLoaders)!=null&&e.length)return this.isEnabled?(this.Sl(),void this._instance.on("eventCaptured",(l=>this.Cl(l)))):void Et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((n=this.yl)==null||n.call(this),t.ok){var s=t.config;if((i=s.siteApps)!=null&&i.length)if(this.isEnabled){var o=function(){var l,u=a.id,c=a.url;B["__$$ph_site_app_"+u]=r._instance,(l=B.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(r._instance,c,(d=>{if(d)return Et.error(uu+u,d)}))};for(var a of s.siteApps)o()}else Et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},Ym={tracingHeaders:class{constructor(t){this.Ml=void 0,this.Tl=void 0,this.El=void 0,this.Uo=()=>{var e,n,i=this.Il();i?(C(this.Ml)&&(this.Ml=(e=B.__PosthogExtensions__)==null||(e=e.tracingHeadersPatchFns)==null?void 0:e._patchXHR(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager)),C(this.Tl)&&(this.Tl=(n=B.__PosthogExtensions__)==null||(n=n.tracingHeadersPatchFns)==null?void 0:n._patchFetch(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager))):this.Qo()},this._instance=t}initialize(){this.startIfEnabledOrStop()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",(i=>{if(i)return Lm.error("failed to load script",i);t()}))}Pl(){var t,e;return(t=(e=this._instance.config.tracing_headers)!==null&&e!==void 0?e:this._instance.config.addTracingHeaders)!==null&&t!==void 0?t:this._instance.config.__add_tracing_headers}Il(){var t=this.Pl();return U(t)?(U(this.El)?this.El.splice(0,this.El.length,...t):this.El=[...t],t.length>0?this.El:void 0):(U(this.El)&&this.El.splice(0),this.El=t||void 0,this.El)}Qo(){var t,e;(t=this.Ml)==null||t.call(this),(e=this.Tl)==null||e.call(this),this.Ml=void 0,this.Tl=void 0}startIfEnabledOrStop(){this.Il()?this.ai(this.Uo):this.Qo()}}},Jm=I({surveys:class{get Ne(){return this._instance.config}constructor(t){this.Rl=void 0,this._surveyManager=null,this.Al=!1,this.Fl=[],this.Ll=null,this.Ol=null,this._instance=t,this._surveyEventReceiver=null}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this.Ne.disable_surveys){if(!t.ok)return Q.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(H(e))return Q.warn("Flags not loaded yet. Not loading surveys.");var n=U(e);this.Rl=n?e.length>0:e,Q.info("flags response received, isSurveysEnabled: "+this.Rl),this.loadIfEnabled()}}reset(){try{var t;(t=this._surveyEventReceiver)==null||t.reset(),localStorage.removeItem("lastSeenSurveyDate");for(var e=[],n=0;nlocalStorage.removeItem(r)))}catch{}}loadIfEnabled(){if(!this._surveyManager)if(this.Al)Q.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)Q.info(du);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())Q.info("Not loading surveys in cookieless mode without consent.");else{var t=B?.__PosthogExtensions__;if(t){if(!C(this.Rl)||this.Ne.advanced_enable_surveys){var e=this.Rl||this.Ne.advanced_enable_surveys;this.Al=!0;try{var n=t.generateSurveys;if(n)return void this.Dl(n,e);var i=t.loadExternalDependency;if(!i)return void this.$l(al);i(this._instance,"surveys",(r=>{r||!t.generateSurveys?this.$l("Could not load surveys script",r):this.Dl(t.generateSurveys,e)}))}catch(r){throw this.$l("Error initializing surveys",r),r}finally{this.Al=!1}}}else Q.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new jm(this._instance),Q.info("Surveys loaded successfully"),this.Nl({isLoaded:!0})}$l(t,e){Q.error(t,e),this.Nl({isLoaded:!1,error:t})}onSurveysLoaded(t){return this.Fl.push(t),this._surveyManager&&this.Nl({isLoaded:!0}),()=>{this.Fl=this.Fl.filter((e=>e!==t))}}getSurveys(t,e){if(e===void 0&&(e=!1),this.Ne.disable_surveys)return Q.info(du),t([]);var n,i=this._instance.get_property(la);if(i&&!e)return t(i,{isLoaded:!0}),void(this.ql()&&this.getSurveys((()=>{}),!0));typeof Promise<"u"&&this.Ll?this.Ll.then((r=>t(r.surveys,r.context))):(typeof Promise<"u"&&(this.Ll=new Promise((r=>{n=r}))),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this.Ne.token),method:"GET",timestampMode:"query",timeout:this.Ne.surveys_request_timeout_ms,callback:r=>{var s;this.Ll=null;var o=r.statusCode;if(o!==200||!r.json){var a="Surveys API could not be loaded, status: "+o;o!==0?Q.error(a):r.error||Q.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(n==null||n({surveys:[],context:l}))}this.Ol=null;var u,c=r.json.surveys||[],d=c.filter((f=>(function(p){return!(!p.start_date||p.end_date)})(f)&&(Wf(f)||(function(p){var g;return!((g=p.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(f))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(s=this._instance.persistence)==null||s.register({[la]:c,[Xr]:Date.now()});var h={isLoaded:!0};t(c,h),n?.({surveys:c,context:h})}}))}ql(){return this.jl()&&!this.Ll&&!this.Bl()}jl(){var t=this._instance.get_property(Xr);return ke(t)&&Date.now()-t>3e5}Bl(){return ke(this.Ol)&&3e5>Date.now()-this.Ol}markSurveyAsSeen(t,e){var n,i={id:t,current_iteration:(n=e?.iteration)!==null&&n!==void 0?n:null};zf(i);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}}Nl(t){for(var e of this.Fl)try{if(!t.isLoaded)return e([],t);this.getSurveys(e)}catch(n){Q.error("Error in survey callback",n)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!H(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);Q.warn("init was not called")}Hl(t){var e=null;return this.getSurveys((n=>{var i;e=(i=n.find((r=>r.id===t)))!==null&&i!==void 0?i:null})),e}Ul(t){if(H(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(H(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(H(this._surveyManager))return Q.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 H(this._surveyManager)?(Q.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Ir})):new Promise((n=>{this.getSurveys((i=>{var r,s=(r=i.find((a=>a.id===t)))!==null&&r!==void 0?r:null;if(s){var o=this.zl(s);n({visible:o.eligible,disabledReason:o.reason})}else n({visible:!1,disabledReason:"Survey not found"})}),e)}))}renderSurvey(t,e,n){var i;if(H(this._surveyManager))Q.warn("init was not called");else{var r=typeof t=="string"?this.Hl(t):t;if(r!=null&&r.id)if(Em.includes(r.type)){var s=P?.querySelector(e);if(s)return(i=r.appearance)!=null&&i.surveyPopupDelaySeconds?(Q.info("Rendering survey "+r.id+" with delay of "+r.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;Q.info("Rendering survey "+r.id+" with delay of "+((o=r.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(a=this._surveyManager)==null||a.renderSurvey(r,s,n),Q.info("Survey "+r.id+" rendered")}),1e3*r.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(r,s,n);Q.warn("Survey element not found")}else Q.warn("Surveys of type "+r.type+" cannot be rendered in the app");else Q.warn("Survey not found")}}displaySurvey(t,e){var n;if(H(this._surveyManager))Q.warn("init was not called");else{var i=this.Hl(t);if(i){var r=i;if((n=i.appearance)!=null&&n.surveyPopupDelaySeconds&&e.ignoreDelay&&(r=I({},i,{appearance:I({},i.appearance,{surveyPopupDelaySeconds:0})})),e.displayType!==_a.Popover&&e.initialResponses&&Q.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),e.ignoreConditions===!1){var s=this.Ul(i);if(!s.eligible)return void Q.warn("Survey is not eligible to be displayed: ",s.reason)}e.displayType!==_a.Inline?this._surveyManager.handlePopoverSurvey(r,e):this.renderSurvey(r,e.selector,e.properties)}else Q.warn("Survey not found")}}cancelPendingSurvey(t){H(this._surveyManager)?Q.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},Cs),Zm={toolbar:class{constructor(t){this.instance=t}Wl(t){B.ph_toolbar_state=t}Vl(){var t;return(t=B.ph_toolbar_state)!==null&&t!==void 0?t:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(t,e,n){if(t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),ga(this.instance.config)||!w||!P)return!1;t=t??w.location,n=n??w.history;try{if(!e){try{w.localStorage.setItem("test","test"),w.localStorage.removeItem("test")}catch{return!1}e=w?.localStorage}var i,r=Um||os(t.hash,"__posthog")||os(t.hash,"state"),s=r?Pc((()=>JSON.parse(atob(decodeURIComponent(r)))))||Pc((()=>JSON.parse(decodeURIComponent(r)))):null;return s&&s.action==="ph_authorize"?((i=s).source="url",i&&Object.keys(i).length>0&&(s.desiredHash?t.hash=s.desiredHash:n?n.replaceState(n.state,"",t.pathname+t.search):t.hash="")):((i=JSON.parse(e.getItem(fu)||"{}")).source="localstorage",delete i.userIntent),!(!i.token||this.instance.config.token!==i.token||(this.loadToolbar(i),0))}catch{return!1}}Zl(t){var e=B.ph_load_toolbar||B.ph_load_editor;!H(e)&&De(e)?e(t,this.instance):hu.warn("No toolbar load function found")}loadToolbar(t){var e=!(P==null||!P.getElementById(of));if(!w||e)return!1;var n=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,i=I({token:this.instance.config.token},t,{apiURL:this.instance.requestRouter.endpointFor("ui")},n?{instrument:!1}:{});if(w.localStorage.setItem(fu,JSON.stringify(I({},i,{source:void 0}))),this.Vl()===2)this.Zl(i);else if(this.Vl()===0){var r;this.Wl(1),(r=B.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"toolbar",(s=>{if(s)return hu.error("[Toolbar] Failed to load",s),void this.Wl(0);this.Wl(2),this.Zl(i)})),ve(w,"turbolinks:load",(()=>{this.Wl(0),this.loadToolbar(i)}))}return!0}Gl(t){return this.loadToolbar(t)}maybeLoadEditor(t,e,n){return t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),this.maybeLoadToolbar(t,e,n)}}},Xm=I({experiments:Me},Cs),Qm={conversations:class{constructor(t){this.Ql=void 0,this._conversationsManager=null,this.Kl=!1,this.Jl=null,this.Yl=!1,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this._instance.config.disable_conversations&&(this.Xl=t.ok,t.ok)){var e=t.config.conversations;H(e)||(mt(e)?this.Ql=e:(this.Ql=e.enabled,this.Jl=e),this.loadIfEnabled())}}reset(){var t;(t=this._conversationsManager)==null||t.reset(),this._conversationsManager=null,this.Ql=void 0,this.Jl=null,this.Xl=void 0,this.Yl=!1}loadIfEnabled(){if(!(this._conversationsManager||this.Kl||this._instance.config.disable_conversations||ga(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=B?.__PosthogExtensions__;if(t&&!C(this.Ql)&&this.Ql)if(this.Jl&&this.Jl.token){this.Kl=!0;try{var e=t.initConversations;if(e)return this.tu(e),void(this.Kl=!1);var n=t.loadExternalDependency;if(!n)return void this.eu(al);n(this._instance,"conversations",(i=>{i||!t.initConversations?this.eu("Could not load conversations script",i):this.tu(t.initConversations),this.Kl=!1}))}catch(i){this.eu("Error initializing conversations",i),this.Kl=!1}}else st.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,st.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else st.error("Cannot complete initialization: remote config is null")}eu(t,e){st.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():st.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!Ke(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":ga(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.Xl===!1?"remote_config_failed":C(this.Ql)?this.Xl?"disabled_in_project":"remote_config_pending":this.Ql?H(this.Jl)||!this.Jl.token?"missing_token":B!=null&&B.__PosthogExtensions__?this.Kl?"initializing":this.Yl?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.isVisible())!==null&&t!==void 0&&t}sendMessage(t,e,n){var i=this;return se((function*(){return i._conversationsManager?i._conversationsManager.sendMessage(t,e,n):(st.warn(En),null)}))()}getMessages(t,e){var n=this;return se((function*(){return n._conversationsManager?n._conversationsManager.getMessages(t,e):(st.warn(En),null)}))()}markAsRead(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(st.warn(En),null)}))()}getTickets(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(st.warn(En),null)}))()}requestRestoreLink(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(st.warn(En),null)}))()}restoreFromToken(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(st.warn(En),null)}))()}restoreFromUrlToken(){var t=this;return se((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(st.warn(En),null)}))()}getCurrentTicketId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getCurrentTicketId())!==null&&t!==void 0?t:null}getWidgetSessionId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getWidgetSessionId())!==null&&t!==void 0?t:null}Xn(){var t;(t=this._conversationsManager)==null||t.setIdentity()}ts(){var t;(t=this._conversationsManager)==null||t.clearIdentity()}}},ev={logs:class{constructor(t){var e,n=this;this.iu=!1,this.ru=!1,this.rt=pe("[logs]"),this.nu=I({},this.rt,{error(){for(var i=arguments.length,r=new Array(i),s=0;i>s;s++)r[s]=arguments[s];r.some(bu)||n.rt.error(...r)}}),this.tr=[],this.su=[],this.Sa=0,this.au=()=>{var i,r;this.Sa=0,(i=this.ou)==null||i.onReconnect(),(r=this.lu)==null||r.onReconnect()},this._instance=t,this._instance&&(e=this._instance.config.logs)!=null&&e.captureConsoleLogs&&(this.iu=!0),w&&ve(w,"online",this.au)}uu(t,e,n,i){var r,s=(function(o,a){var l,u,c,d,h,f,p,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,v=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,E=C(v)?Math.max(m,2048):Math.max(m,v),S=o?.resourceAttributes;return{serviceName:(d=(h=S?.["service.name"])!==null&&h!==void 0?h:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(f=S?.["service.version"])!==null&&f!==void 0?f:o?.serviceVersion,environment:(p=S?.["deployment.environment"])!==null&&p!==void 0?p:o?.environment,resourceAttributes:S,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:E,maxBatchRecordsPerPost:100,rateCapWindowMs:g,maxLogsPerInterval:v,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}})((r=this._instance)==null||(r=r.config)==null?void 0:r.logs,n);return[new rg(this.hu(t,e),s,this.nu,(()=>this.du()),(o=>o()),void 0,i),s]}vu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.ou||this.cu!==e){var n;(n=this.ou)==null||n.reset(),this.cu=e;var i=this.uu((()=>this.tr),(r=>{this.tr=r}));this.ou=i[0],this.fu=i[1]}return this.ou}pu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.lu||this.gu!==e){var n;(n=this.lu)==null||n.reset(),this.gu=e;var i=this.uu((()=>this.su),(r=>{this.su=r}),{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},wu);this.lu=i[0],this.mu=i[1]}return this.lu}initialize(){this.loadIfEnabled()}onRemoteConfig(t){var e;if(t.ok){var n=(e=t.config.logs)==null?void 0:e.captureConsoleLogs;!H(n)&&n&&(this.iu=!0,this.loadIfEnabled())}}reset(){var t,e;this.tr=[],(t=this.ou)==null||t.reset(),this.su=[],(e=this.lu)==null||e.reset(),this.Sa=0}captureLog(t){this.vu().captureLog(t)}he(t){this.pu().captureLog(t)}get logger(){return this.yu||(this.yu={trace:(t,e)=>this.captureLog({body:t,level:"trace",attributes:e}),debug:(t,e)=>this.captureLog({body:t,level:"debug",attributes:e}),info:(t,e)=>this.captureLog({body:t,level:"info",attributes:e}),warn:(t,e)=>this.captureLog({body:t,level:"warn",attributes:e}),error:(t,e)=>this.captureLog({body:t,level:"error",attributes:e}),fatal:(t,e)=>this.captureLog({body:t,level:"fatal",attributes:e})}),this.yu}flushLogs(t){t?this.bu(t):(this.ou&&this.ou.flush().catch((e=>this._u(e))),this.lu&&this.lu.flush().catch((e=>this._u(e))))}_u(t){bu(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=B?.__PosthogExtensions__;if(t){var e=t.loadExternalDependency;e?e(this._instance,"logs",(n=>{var i;n||(i=t.logs)==null||!i.initializeLogs?this.rt.error("Could not load logs script",n):(t.logs.initializeLogs(this._instance),this.ru=!0)})):this.rt.error(al)}else this.rt.error("PostHog Extensions not found.")}}hu(t,e){var n=this._instance;return{get isDisabled(){return!1},get optedOut(){return!n.is_capturing()},getPersistedProperty:i=>i===Ut.LogsQueue?t():void 0,setPersistedProperty(i,r){var s;i===Ut.LogsQueue&&e((s=r)!==null&&s!==void 0?s:[])},Ot:i=>this.Ot(i),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Ot(t){return new Promise((e=>{if(_f(this.Sa,3))e({kind:"fatal",error:Do(void 0,"logs endpoint is unreachable, dropping batch")});else{var n=!1,i=s=>{n||(n=!0,clearTimeout(r),e(s))},r=setTimeout((()=>{this.rt.warn("Logs request timed out before receiving a response"),i({kind:"retry-later",error:Do(void 0,"logs request timed out")})}),9e4);this._instance._send_request({method:"POST",url:this.wu(),data:t,compression:"best-available",batchKey:"logs",fireCallbackOnDrop:!0,callback:s=>{var o=s.statusCode;if(this.ku(o),o>=200&&300>o)i({kind:"ok"});else if(o===413)i({kind:"too-large"});else if(o!==0&&o!==429&&500>o)i({kind:"fatal",error:new Error("logs request failed with status "+o)});else{var a;o===0?(s.error||this.rt.warn("Logs request failed before receiving an HTTP response"),i({kind:"retry-later",error:Do(s.error,"logs request failed before receiving an HTTP response")})):i({kind:"retry-later",error:(a=s.error)!==null&&a!==void 0?a:new Error("logs request failed with status "+o)})}}})}}))}ku(t){(t!==0||this._instance.__loaded)&&(this.Sa=yf(t,this.Sa,3,(()=>this.rt.warn("Log requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped sending logs; will try again when connectivity changes."))))}bu(t){this.tr.length>0&&this.xu(t,this.tr,this.fu,ne.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,wu,(e=>{this.su=e}))}xu(t,e,n,i,r){if(e.length!==0){var s=e.map((a=>a.record));r([]);var o=Hd(s,Ud(n,ne.LIB_NAME,ne.LIB_VERSION),i,ne.LIB_VERSION);this._instance._send_request({method:"POST",url:this.wu(),data:o,compression:"best-available",batchKey:"logs",transport:t})}}wu(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}du(){var t,e={};if(e.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var n=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.windowId,r=n.sessionStartTimestamp,s=n.lastActivityTimestamp;e.sessionId=n.sessionId,e.windowId=i,H(r)||(e.sessionStartTimestamp=r),H(s)||(e.lastActivityTimestamp=s)}if(B!=null&&(t=B.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?fn(B.location.href):B.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},tv={metrics:class{constructor(t){this.rt=pe("[metrics]"),this._instance=t}initialize(){}vu(){var t,e,n=(t=this._instance)==null||(t=t.config)==null?void 0:t.metrics;return this.ou&&this.cu===n||((e=this.ou)==null||e.reset(),this.cu=n,this.ou=new sg(this.hu(),(function(i){var r,s,o,a,l,u=i?.resourceAttributes;return{serviceName:(r=u?.["service.name"])!==null&&r!==void 0?r:i?.serviceName,serviceVersion:(s=u?.["service.version"])!==null&&s!==void 0?s:i?.serviceVersion,environment:(o=u?.["deployment.environment"])!==null&&o!==void 0?o:i?.environment,resourceAttributes:u,beforeSend:i?.beforeSend,flushIntervalMs:(a=i?.flushIntervalMs)!==null&&a!==void 0?a:1e4,maxSeriesPerFlush:(l=i?.maxSeriesPerFlush)!==null&&l!==void 0?l:1e3}})(n),this.rt)),this.ou}count(t,e,n){e===void 0&&(e=1),this.vu().count(t,e,n)}gauge(t,e,n){this.vu().gauge(t,e,n)}histogram(t,e,n){this.vu().histogram(t,e,n)}flush(t){if(!this.ou)return Promise.resolve();if(t){var e=this.ou.drainWindow();return e&&this.Jt(e,t),Promise.resolve()}return this.ou.flush().catch((n=>this.rt.error("PostHog metrics flush failed:",n)))}reset(){var t;(t=this.ou)==null||t.reset()}hu(){var t=this._instance,e=this;return{get isDisabled(){return!1},get optedOut(){return!t.is_capturing()},Jt:n=>e.Jt(n),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Jt(t,e){return new Promise((n=>{var i=!1,r=o=>{i||(i=!0,clearTimeout(s),n(o))},s=setTimeout((()=>r({kind:"retry-later",error:new Error("metrics request timed out")})),9e4);this._instance._send_request(I({method:"POST",url:this.Su(),data:t,compression:"best-available",batchKey:"metrics"},e&&{transport:e},{fireCallbackOnDrop:!0,callback(o){var a=o.statusCode;if(a>=200&&300>a)r({kind:"ok"});else if(a===413)r({kind:"too-large"});else if(a!==0&&a!==429&&500>a)r({kind:"fatal",error:new Error("metrics request failed with status "+a)});else{var l;r({kind:"retry-later",error:(l=o.error)!==null&&l!==void 0?l:new Error("metrics request failed with status "+a)})}}}))}))}Su(){return this._instance.requestRouter.endpointFor("api","/i/v1/metrics")+"?token="+encodeURIComponent(this._instance.config.token)}}},nv=I({},Cs,qm,zm,Vm,Gm,Km,Jm,Ym,Zm,Xm,Qm,ev,tv);Je.__defaultExtensionClasses=I({},nv);(function(){ne.SDK_DIST_CHANNEL="npm";var t=Wi[Gn]=new Je;return(function(){function e(){e.done||(e.done=!0,Gf=!1,ie(Wi,(function(n){n._dom_loaded()})))}P!=null&&P.addEventListener?P.readyState==="complete"?e():ve(P,"DOMContentLoaded",e,{capture:!1}):w&&A.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const iv=["a[href]","button:not([disabled])","input:not([disabled]):not([type='hidden'])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(",");let pt=null,ka=null,Yf="";const Ca=new Map;function Jf(t){return[...t.querySelectorAll(iv)].filter(e=>!e.hidden&&e.getAttribute("aria-hidden")!=="true"&&e.getClientRects().length>0)}function rv(t){for(const e of document.body.children)e===t||e.tagName==="SCRIPT"||(Ca.set(e,{inert:e.inert,ariaHidden:e.getAttribute("aria-hidden")}),e.inert=!0,e.setAttribute("aria-hidden","true"))}function sv(){for(const[t,e]of Ca)t.inert=e.inert,e.ariaHidden===null?t.removeAttribute("aria-hidden"):t.setAttribute("aria-hidden",e.ariaHidden);Ca.clear()}function Zf(t){return t?.dataset.modalDismissible!=="false"&&t?.getAttribute("aria-busy")!=="true"}function He(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n)return!1;pt&&pt!==n&&We(pt,{restoreFocus:!1,force:!0}),ka=e.trigger||document.activeElement,pt=n,Yf=document.body.style.overflow,rv(n),document.body.style.overflow="hidden",n.classList.add("open"),n.setAttribute("aria-hidden","false");const i=n.querySelector(".modal-content");i&&(i.style.transform="scale(1) translateY(0)");const r=()=>{if(pt!==n)return;((e.initialFocus?n.querySelector(e.initialFocus):n.querySelector("[data-modal-initial-focus]"))||Jf(n)[0]||n.querySelector(".modal-content")||n).focus({preventScroll:!0})};return requestAnimationFrame(r),setTimeout(r,260),!0}function We(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n||!e.force&&!Zf(n))return!1;n.classList.remove("open"),n.setAttribute("aria-hidden","true"),sv(),document.body.style.overflow=Yf,pt=null;const i=ka;return ka=null,e.restoreFocus!==!1&&i?.isConnected&&i.focus({preventScroll:!0}),!0}function Eu(t,e,n="Operation in progress"){const i=typeof t=="string"?document.getElementById(t):t;i&&(i.dataset.modalDismissible=e?"false":"true",i.setAttribute("aria-busy",String(!!e)),e?i.setAttribute("aria-label",n):i.removeAttribute("aria-label"))}function ov(t){if(!Zf(t))return;const e=t.dataset.modalCloseHandler;e&&typeof window[e]=="function"?window[e]():We(t)}document.addEventListener("keydown",t=>{if(!pt)return;if(t.key==="Escape"){t.preventDefault(),t.stopImmediatePropagation(),ov(pt);return}if(t.key!=="Tab"){t.stopPropagation();return}const e=Jf(pt);if(!e.length){t.preventDefault(),(pt.querySelector(".modal-content")||pt).focus();return}const n=e[0],i=e[e.length-1];t.shiftKey&&document.activeElement===n?(t.preventDefault(),i.focus()):!t.shiftKey&&document.activeElement===i&&(t.preventDefault(),n.focus())},!0);function av(){document.querySelectorAll(".modal-overlay").forEach(t=>{t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-hidden",t.classList.contains("open")?"false":"true");const e=t.querySelector(".modal-content");e&&!e.hasAttribute("tabindex")&&(e.tabIndex=-1);const n=t.querySelector("h1, h2, h3");n&&(n.id||(n.id=`${t.id}-title`),t.setAttribute("aria-labelledby",n.id)),t.querySelectorAll(".modal-close").forEach(i=>{i.getAttribute("aria-label")||i.setAttribute("aria-label","Close dialog")})})}const gl=Object.freeze({free:"Free",professional:"Pro",power:"Power"}),lv=Object.freeze({free:2,professional:50,power:2e3}),cv="(contact us)",uv=Object.freeze({free:Object.freeze(["2 generations/month","Gemini model only","Code Review"]),professional:Object.freeze(["50 generations/month","All models","Code Regeneration","Code Review"]),power:Object.freeze(["2000 generations/month","All models","Code Regeneration","Bring your own key (BYOK)","Code Review","All models + early access",`API & MCP access ${cv}`])}),Xf="CodeFile",Qf="GeneratedCode",dv={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function ln(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Aa(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function fv(t={},e=0){const n=Aa(t.artifactType||t.type||Xf),i=Aa(t.artifactName||t.name||t.fileName||`${Qf}-${e+1}`);return`${n||"artifact"}-${i||e+1}`}function eh(t={},e=0){const n=ln(t),i=n.artifactType||n.type||Xf,r=n.artifactName||n.name||Qf;let s=n.fileName||r;return s.endsWith(".dart")||(s+=".dart"),{id:Aa(n.id)||fv({...n,artifactType:i,artifactName:r,fileName:s},e),artifactType:i,artifactName:r,fileName:s,deployPath:n.deployPath||"",description:n.description||"",code:n.code||n.content||"",dependencies:th(n.dependencies),imports:Array.isArray(n.imports)?n.imports:[],publicApi:Array.isArray(n.publicApi)?n.publicApi:[],relationships:nh(n.relationships),deployStatus:n.deployStatus||"pending",review:n.review||null,metadata:ln(n.metadata),codeType:n.codeType||dv[i]||"O"}}function th(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const n=ln(e),i=n.name||n.package;return i?{name:i,version:n.version||null,versionRequired:!!(n.versionRequired||n.required),inferred:!!n.inferred,...n.reason?{reason:n.reason}:{}}:null}).filter(Boolean):Object.entries(ln(t)).map(([e,n])=>({name:e,version:n||null,inferred:!1})):[]}function nh(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const n=ln(e);return!n.from&&!n.to?null:{from:n.from||null,to:n.to||null,type:n.type||"uses",description:n.description||""}}).filter(Boolean):[]}function Pa(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;try{return JSON.parse(e)}catch{const n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(!n)return null;try{return JSON.parse(n[1].trim())}catch{return null}}}function Qi(t,e={}){const n=[],i=typeof t=="string"?Pa(t):t,s=ln(i||{});!i&&typeof t=="string"&&n.push("Structured bundle parse failed; using legacy single-artifact fallback.");const o=Array.isArray(s.artifacts)?s.artifacts:[{artifactType:s.artifactType||e.artifactType,artifactName:s.artifactName||e.artifactName,fileName:s.fileName||e.fileName,description:s.description,code:s.code||e.code||(typeof t=="string"?t:""),dependencies:s.dependencies||e.dependencies,relationships:s.relationships||e.relationships}];o.forEach((d,h)=>{!d?.artifactType&&!d?.type&&n.push(`Artifact ${h+1} has no artifactType; it will deploy as a standalone code file under lib/custom_code/ root.`)});const a=o.map((d,h)=>eh(d,h)),l=new Map(o.map((d,h)=>[ln(d).id,a[h]?.id]).filter(([d,h])=>d&&h)),u=d=>l.get(d)||d,c=nh(s.relationships||e.relationships).map(d=>({...d,from:d.from?u(d.from):d.from,to:d.to?u(d.to):d.to}));return{schemaVersion:s.schemaVersion||e.schemaVersion||null,id:s.id||e.id||"bundle-current",title:s.title||s.name||e.title||"Generated artifact bundle",description:s.description||e.description||"",artifacts:a,dependencies:th(s.dependencies||e.dependencies),relationships:c,deployOrder:Array.isArray(s.deployOrder)?s.deployOrder.map(u):a.map(d=>d.id),warnings:[...n,...Array.isArray(s.warnings)?s.warnings:[]],metadata:ln(s.metadata)}}function oi(t){return Qi(t).artifacts[0]||eh()}function Zt(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function ai(t){return JSON.stringify(t,null,2)}function hv(t){return ai({task:"architect",userRequest:String(t??"")})}function pv(t){const e=Zt(t);return e&&typeof e=="object"&&typeof e.task=="string"?ai(e):ai({task:"generate_bundle",bundleSpec:e})}function gv(t){return ai({task:"review_bundle",generatedBundle:Zt(t),outputRequirements:{bundleReview:["status","score","summary","manualActions","findings"],scoreRange:[0,100],eachArtifact:["id","review.status","review.findings"],manualActions:{definition:"Setup the developer must perform by hand in the FlutterFlow editor that FlutterFlow will NOT do for them.",exclude:["creating the Custom Action, Widget or Code File itself - deploying the code creates it","declaring parameters or return values FlutterFlow derives from the function signature","anything that resolves as a side effect of using the action or widget in the editor","generic advice such as testing, reviewing or rebuilding the app"],preferEmpty:"Return an empty array when nothing qualifies - an empty list is the expected result for most bundles."}}})}function ml(t,e=null){const n={stage:t};return e!=null&&(n.bundle=Zt(e)),n}function mv({bundleSpec:t,artifactBundle:e,bundleReview:n,artifactId:i,userFeedback:r}){return ai({task:"regenerate_artifact",artifactId:i,bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(r)})}function ih({bundleSpec:t,artifactBundle:e,bundleReview:n,userFeedback:i}){return ai({task:"regenerate_bundle",bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(i??"")})}const Su={csam:"child-safety content",dangerous:"dangerous content",harassment:"harassment",hate_speech:"hate speech",maliciousUrls:"a potentially malicious URL",malicious_uris:"a potentially malicious URL",pi_and_jailbreak:"prompt-injection or jailbreak instructions",promptInjection:"prompt-injection or jailbreak instructions",rai:"restricted content",sdp:"sensitive personal data",sexually_explicit:"sexually explicit content",virus_scan:"potentially malicious file content"},vv=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function et(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function _v(t){return et(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||et(t.filterSummary)||et(t.filterResults):!1}function rh(t,e=0){if(!et(t)||e>3)return null;if(_v(t))return t;for(const n of vv){const i=t[n];if(et(i)){const r=rh(i,e+1);if(r)return r}}return null}function ds(t){return Array.isArray(t)?t.some(ds):et(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(ds):!1}function Fa(t){return Array.isArray(t)?t.some(Fa):et(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(Fa):!1}function sh(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function yv(t,e){if(et(t))for(const[n,i]of Object.entries(t)){if(!et(i))continue;const r=et(i.categories)?i.categories:{},s=Object.entries(r).filter(([,o])=>et(o)&&o.matched===!0).map(([o])=>o);s.length>0?s.forEach(o=>e.add(o)):i.matched===!0&&e.add(sh(n))}}function wv(t,e){if(!t)return;const n=Array.isArray(t)?t.flatMap(i=>et(i)?Object.entries(i):[]):Object.entries(t);for(const[i,r]of n){if(!ds(r))continue;const s=sh(i),o=r?.raiFilterResult?.raiFilterTypeResults||(s==="rai"?r?.raiFilterTypeResults:null),a=et(o)?Object.entries(o).filter(([,l])=>ds(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(s)}}function bv(t){return Su[t]?Su[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function xu(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 Ev(t){const e=rh(t);if(!e)return null;const n=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);yv(e.filterSummary,n),wv(e.filterResults,n);const i=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||n.size>0,r=e.invocationResult||null,s=Fa(e.filterSummary||e.filterResults);return!i&&!s&&!["PARTIAL","FAILURE"].includes(r)?null:{kind:i?"blocked":"unavailable",invocationResult:r,matchedFilters:[...n]}}function Sv(t,e){const n=Ev(t);if(!n)return null;const i=[...new Set(n.matchedFilters.map(bv))],r=n.kind==="blocked",s=new Error(r?`Safety screening blocked this pipeline step for ${xu(i)}.`:"Safety screening could not be completed. Please try again.");return s.name="ModelArmorError",s.code=r?"MODEL_ARMOR_BLOCKED":"MODEL_ARMOR_UNAVAILABLE",s.isModelArmor=!0,s.pipelineStep=e,s.userTitle=r?"Request blocked for safety":"Safety check unavailable",s.userMessage=r?`The safety check detected ${xu(i)}. Edit your request to remove or rephrase the flagged content, then run the pipeline again.`:"The safety service did not finish all of its checks. Please wait a moment and run the pipeline again.",s.retryExplanation=r?"Trying another model would not change this safety decision.":"A fallback model was not attempted because safety screening must complete first.",s.matchedFilters=n.matchedFilters,s}function xv(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function Iu(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,n=[];for(const i of xv(t).split(` +`)){if(!/^[A-Za-z_$]/.test(i)||e.test(i))continue;const r=i.match(/^[\w$<>,?\s[\]]+?\s([a-zA-Z_$][\w$]*)\s*\(/);r&&n.push(r[1])}return n}function vl(t,e){const n=t.replace(/\.dart$/,"");if(e==="W")return n.replace(/(^|_)(\w)/g,(i,r,s)=>s.toUpperCase());if(e==="A"){const i=n.replace(/(^|_)(\w)/g,(r,s,o)=>o.toUpperCase());return i.charAt(0).toLowerCase()+i.slice(1)}return e==="F"?"CustomFunctions":e==="C"?t.endsWith(".dart")?t:`${t}.dart`:n}async function ku(t){const e=new TextEncoder().encode(String(t||"")),n=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n),i=>i.toString(16).padStart(2,"0")).join("")}async function Iv(t,e=new Map){const n={},i=new Set;for(const[o,a]of t.entries()){if(a.type==="D"||a.type==="O")continue;const l=vl(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await ku(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await ku(c)),n[o]=u,a.type==="F"){const d=Iu(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(f=>i.add(f))}}const r=new Set(Iu(e.get("lib/flutter_flow/custom_functions.dart")||"")),s={functions_to_rename:[],functions_to_delete:[],functions_to_add:Array.from(i).filter(o=>!r.has(o))};return{fileMapContents:JSON.stringify(n),functionsMapContents:JSON.stringify(s)}}const kv=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),Cu={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},Cv=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),Av=["Struct","Record"],Pv=[{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=>jo(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=>jo(t).some(e=>{const n=/^\s*final\s+(?:double|int|String|bool|Color|num)\s+(\w+)\s*;/gm;let i;for(;(i=n.exec(e))!==null;){const r=i[1];if(!(new RegExp(`this\\.${r}\\s*=(?!=)`).test(e)||new RegExp(`[:,]\\s*${r}\\s*=(?!=)`).test(e)))return!0}return!1}),pos:`class W extends StatefulWidget { const W({required this.value}); final double value; @@ -25,36 +25,36 @@ class _S extends State { @override Widget build(BuildContext c) => const Size @override _S createState() => _S(); } class _S extends State { @override Widget build(BuildContext c) => Padding(padding: const EdgeInsets.all(8), child: const SizedBox()); }`}];function xt(t,e,n){return{artifactId:t.id,artifactName:t.artifactName,artifactType:t.artifactType,severity:e,message:n}}function er(t){let e="",n=0;for(;n"&&(n--,n===0))return{inner:t.slice(e+1,i),end:i+1};return null}function Fv(t,e){const n=new RegExp(`class\\s+${e}\\b[^{]*\\{`).exec(t);if(!n)return null;let i=0;for(let r=n.index+n[0].length-1;rRv(t).usable);function $v(t=""){const e=er(t);return Tv.filter(n=>n.detect(e)).map(({id:n,severity:i,message:r})=>({id:n,severity:i,message:r}))}function Mv(t){const e=[],n=t.matchAll(/\bFuture\b/g);for(const i of n){let r=i.index+6,s=null;const o=r;for(;ro;if(t[r]==="<"){const u=Pv(t,r);if(!u||(s=u.inner.replace(/\s+/g," ").trim(),r=u.end,!/\s/.test(t[r]||"")))continue;for(;rAu(o.functionName)===i);if(r)return r;const s=o=>!o.functionName.startsWith("_");return n.find(s)||n[0]}function As(t=""){return Array.from(er(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function Lv(t="",e=""){return _l(t,e)?.returnType||null}function Pu(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 Nv(t,e){const n=As(e);if(n.length===0)return null;const r=String(t||"").split("/").pop().replace(/\.dart$/,"");if(n.some(l=>Pu(l)===r)||n.length>1)return null;const[o]=n,a=`${Pu(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 yl(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function Ov(t,e,n=""){const i=_l(e,n)?.functionName;if(!i)return null;const r=String(t||"").split("/").pop(),s=vl(r,"A");if(s===i)return null;const o=`${yl(i)}.dart`;return`File name "${r}" does not match Action "${i}". FlutterFlow derives the action from the file name, so it looks for "${s}" and reports Action "${s}" declaration not found. Rename the file to "${o}" - FlutterFlow puts an underscore before every capital - or rename the function to "${s}".`}function Bv(t="",e=""){return _l(t,e)!==null}function Dv(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(i=>kv.has(i)?!1:!Cv.some(s=>i.endsWith(s))||e.has(i))}function jv(t,{functionName:e="",declaredTypes:n=new Set}={}){const i=Lv(t,e),r=Dv(i,n);if(r.length===0)return null;const[s]=r;let o;return n.has(s)?o=`uses Code File type "${s}", which FlutterFlow cannot process as an Action Return Value`:i===s?o="is not a FlutterFlow Action Return Value":o=`uses type "${s}", which is not a FlutterFlow Action Return Value`,`CustomAction return type "${i}" ${o}. Return JSON (Future) or an existing FlutterFlow Data Type (*Struct) instead.`}function Uv(t,e={}){const n=[],i=t.fileName||"",r=t.code||"";if(Iv.has(t.artifactType)||n.push(xt(t,"error",`Unsupported artifact type "${t.artifactType}".`)),i.endsWith(".dart")||n.push(xt(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!r.trim())return n.push(xt(t,"warning","Generated artifact has no Dart code yet.")),n;if(t.artifactType==="CustomWidget"){/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)||n.push(xt(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const s of $v(r))n.push(xt(t,s.severity,s.message))}if(t.artifactType==="CustomAction"&&!Bv(r,t.artifactName)&&n.push(xt(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const s=e.declaredTypes||new Set(As(r)),o=jv(r,{functionName:t.artifactName,declaredTypes:s});o&&n.push(xt(t,"error",o));const a=Ov(i,r,t.artifactName);a&&n.push(xt(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)&&n.push(xt(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const s=Nv(i,r);s&&n.push(xt(t,"info",s))}return n}function Hv(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],n=new Set(e.flatMap(s=>As(s.code||""))),i=e.flatMap(s=>Uv(s,{declaredTypes:n})),r=e.map(s=>({artifactId:s.id,fileName:s.fileName,pathHint:Cu[s.artifactType]||Cu.CodeFile}));return{valid:i.every(s=>s.severity!=="error"),findings:i,deployHints:r}}const Fu="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function Ru(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function Wv(t=""){const e=t.indexOf(Fu);return e===-1?t:t.slice(e+Fu.length).replace(/^\s*\n/,"")}const qv=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function zv(t="",e=""){const n=Wv(t),i=new Set((e.match(/^\s*import .*$/gm)||[]).map(Ru).filter(Boolean)),r=n.split(` -`).filter(s=>{const o=Ru(s);return o===null||!i.has(o)?!0:!qv.test(s)}).join(` -`).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+r}const Vv=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations"]);function sh(t){let e="",n=0;for(;n{const i=n.name||n.package;if(!i||i==="flutter")return e;const r=n.versionRequired||n.required;return e[i]=r&&n.version||"",e},{})}function Zv(t){const e=new Map,n=new Map,i=[];for(const r of t)e.has(r.fileName)?i.push(`Duplicate deploy file name "${r.fileName}" for artifacts "${e.get(r.fileName)}" and "${r.artifactId}".`):e.set(r.fileName,r.artifactId),n.has(r.path)?i.push(`Duplicate deploy path "${r.path}" for artifacts "${n.get(r.path)}" and "${r.artifactId}".`):n.set(r.path,r.artifactId);return i}function Xv(t,e={}){const n=Array.isArray(t?.artifacts)?t.artifacts:[],r=(e.selectedArtifactIds||t?.deployOrder||n.map(h=>h.id)).map(h=>n.find(p=>p.id===h)).filter(Boolean),s=[...t?.warnings||[]];let o=[];r.forEach(h=>{const p=Jv(h),g=h.fixedCode||h.code||"",m=h.codeType||Kv[h.artifactType]||Ze.OTHER;g.trim()||s.push(`${h.artifactName||h.id} has no generated code.`),o.push({artifactId:h.id,artifactName:h.artifactName,artifactType:h.artifactType,fileName:p,content:g,type:m,path:h.deployPath||Yv(p,m),deployPath:h.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((h,p)=>({entry:h,index:p})).filter(({entry:h})=>h.type===Ze.FUNCTION&&h.path===a);if(l.length>1){const h=l[0],p={...h.entry,artifactId:l.map(({entry:m})=>m.artifactId).join("+"),artifactName:h.entry.artifactName,content:l.map(({entry:m})=>`// ${m.artifactId} +`;)n++;e+=" "}else if(i==="/*"){for(n+=2;n"&&(n--,n===0))return{inner:t.slice(e+1,i),end:i+1};return null}function Rv(t,e){const n=new RegExp(`class\\s+${e}\\b[^{]*\\{`).exec(t);if(!n)return null;let i=0;for(let r=n.index+n[0].length-1;rTv(t).usable);function Mv(t=""){const e=er(t);return $v.filter(n=>n.detect(e)).map(({id:n,severity:i,message:r})=>({id:n,severity:i,message:r}))}function Lv(t){const e=[],n=t.matchAll(/\bFuture\b/g);for(const i of n){let r=i.index+6,s=null;const o=r;for(;ro;if(t[r]==="<"){const u=Fv(t,r);if(!u||(s=u.inner.replace(/\s+/g," ").trim(),r=u.end,!/\s/.test(t[r]||"")))continue;for(;rAu(o.functionName)===i);if(r)return r;const s=o=>!o.functionName.startsWith("_");return n.find(s)||n[0]}function As(t=""){return Array.from(er(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function Nv(t="",e=""){return _l(t,e)?.returnType||null}function Pu(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 Ov(t,e){const n=As(e);if(n.length===0)return null;const r=String(t||"").split("/").pop().replace(/\.dart$/,"");if(n.some(l=>Pu(l)===r)||n.length>1)return null;const[o]=n,a=`${Pu(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 yl(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function Bv(t,e,n=""){const i=_l(e,n)?.functionName;if(!i)return null;const r=String(t||"").split("/").pop(),s=vl(r,"A");if(s===i)return null;const o=`${yl(i)}.dart`;return`File name "${r}" does not match Action "${i}". FlutterFlow derives the action from the file name, so it looks for "${s}" and reports Action "${s}" declaration not found. Rename the file to "${o}" - FlutterFlow puts an underscore before every capital - or rename the function to "${s}".`}function Dv(t="",e=""){return _l(t,e)!==null}function jv(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(i=>Cv.has(i)?!1:!Av.some(s=>i.endsWith(s))||e.has(i))}function Uv(t,{functionName:e="",declaredTypes:n=new Set}={}){const i=Nv(t,e),r=jv(i,n);if(r.length===0)return null;const[s]=r;let o;return n.has(s)?o=`uses Code File type "${s}", which FlutterFlow cannot process as an Action Return Value`:i===s?o="is not a FlutterFlow Action Return Value":o=`uses type "${s}", which is not a FlutterFlow Action Return Value`,`CustomAction return type "${i}" ${o}. Return JSON (Future) or an existing FlutterFlow Data Type (*Struct) instead.`}function Hv(t,e={}){const n=[],i=t.fileName||"",r=t.code||"";if(kv.has(t.artifactType)||n.push(xt(t,"error",`Unsupported artifact type "${t.artifactType}".`)),i.endsWith(".dart")||n.push(xt(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!r.trim())return n.push(xt(t,"warning","Generated artifact has no Dart code yet.")),n;if(t.artifactType==="CustomWidget"){/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)||n.push(xt(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const s of Mv(r))n.push(xt(t,s.severity,s.message))}if(t.artifactType==="CustomAction"&&!Dv(r,t.artifactName)&&n.push(xt(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const s=e.declaredTypes||new Set(As(r)),o=Uv(r,{functionName:t.artifactName,declaredTypes:s});o&&n.push(xt(t,"error",o));const a=Bv(i,r,t.artifactName);a&&n.push(xt(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)&&n.push(xt(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const s=Ov(i,r);s&&n.push(xt(t,"info",s))}return n}function Wv(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],n=new Set(e.flatMap(s=>As(s.code||""))),i=e.flatMap(s=>Hv(s,{declaredTypes:n})),r=e.map(s=>({artifactId:s.id,fileName:s.fileName,pathHint:Cu[s.artifactType]||Cu.CodeFile}));return{valid:i.every(s=>s.severity!=="error"),findings:i,deployHints:r}}const Fu="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function Ru(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function qv(t=""){const e=t.indexOf(Fu);return e===-1?t:t.slice(e+Fu.length).replace(/^\s*\n/,"")}const zv=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function Vv(t="",e=""){const n=qv(t),i=new Set((e.match(/^\s*import .*$/gm)||[]).map(Ru).filter(Boolean)),r=n.split(` +`).filter(s=>{const o=Ru(s);return o===null||!i.has(o)?!0:!zv.test(s)}).join(` +`).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+r}const Gv=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations"]);function oh(t){let e="",n=0;for(;n{const i=n.name||n.package;if(!i||i==="flutter")return e;const r=n.versionRequired||n.required;return e[i]=r&&n.version||"",e},{})}function Xv(t){const e=new Map,n=new Map,i=[];for(const r of t)e.has(r.fileName)?i.push(`Duplicate deploy file name "${r.fileName}" for artifacts "${e.get(r.fileName)}" and "${r.artifactId}".`):e.set(r.fileName,r.artifactId),n.has(r.path)?i.push(`Duplicate deploy path "${r.path}" for artifacts "${n.get(r.path)}" and "${r.artifactId}".`):n.set(r.path,r.artifactId);return i}function Qv(t,e={}){const n=Array.isArray(t?.artifacts)?t.artifacts:[],r=(e.selectedArtifactIds||t?.deployOrder||n.map(f=>f.id)).map(f=>n.find(p=>p.id===f)).filter(Boolean),s=[...t?.warnings||[]];let o=[];r.forEach(f=>{const p=Zv(f),g=f.fixedCode||f.code||"",m=f.codeType||Yv[f.artifactType]||Ze.OTHER;g.trim()||s.push(`${f.artifactName||f.id} has no generated code.`),o.push({artifactId:f.id,artifactName:f.artifactName,artifactType:f.artifactType,fileName:p,content:g,type:m,path:f.deployPath||Jv(p,m),deployPath:f.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((f,p)=>({entry:f,index:p})).filter(({entry:f})=>f.type===Ze.FUNCTION&&f.path===a);if(l.length>1){const f=l[0],p={...f.entry,artifactId:l.map(({entry:m})=>m.artifactId).join("+"),artifactName:f.entry.artifactName,content:l.map(({entry:m})=>`// ${m.artifactId} ${m.content}`).join(` -`)},g=new Set(l.slice(1).map(({index:m})=>m));o=o.filter((m,v)=>!g.has(v)),o[h.index]=p}const u={...Tu(t?.dependencies),...r.reduce((h,p)=>({...h,...Tu(p.dependencies)}),{})},c={};r.forEach(h=>{wl(h.code||"").forEach(p=>{p in u||(c[p]="")})});const d={...c,...u},f=Zv(o);return{bundleId:t?.id||"bundle-current",title:t?.title||"Generated artifact bundle",fileEntries:o,dependencies:d,relationships:t?.relationships||[],warnings:s,errors:f}}function Qv(t){return String(t||"").match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/)?.[1]}function e_(t){return String(t||"").split("/").pop().replace(/\.dart$/,"").split(/[^A-Za-z0-9]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function t_(t,e){const i=[e_(t),Qv(e.content),e.artifactName].find(r=>/^[A-Z][A-Za-z0-9_]*$/.test(String(r||"")));if(!i)throw new Error(`Cannot derive a FlutterFlow custom class name for ${t}.`);return i}function n_(t,e=new Map){const n=[];for(const[i,r]of t.entries())r.type!=="C"||e.has(r.path)||n.push({artifactId:r.artifactId||i,className:t_(i,r),content:r.content,fileName:i,path:r.path});return n}function i_(t,e){const n=new Set(e.map(i=>i.path));return new Map(Array.from(t.entries()).filter(([,i])=>!n.has(i.path)))}const $u={pass:0,warning:1,fail:2},r_=["manualActions"];function rt(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Vt(...t){for(const e of t){if(typeof e=="string"&&e.trim())return e.trim();if(Array.isArray(e)&&e.length>0){const n=e.filter(i=>typeof i=="string").join(` -`);if(n)return n}}return""}function kt(t){return t==null?[]:Array.isArray(t)?t:[t]}function s_(t){const e=rt(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const n=Number(e);if(Number.isFinite(n))return Mu(n);const i=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return i?Mu(Number(i[1])):null}function Mu(t){return t>=0&&t<=100?t:null}function at(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function bl(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 Ra(...t){return t.filter(Boolean).reduce((e,n)=>$u[n]>$u[e]?n:e,"pass")}function oh(t,e="warning",n="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:n};const i=rt(t),r=Vt(i.message,i.title,i.issue,i.description,i.summary);return r?{severity:bl(i.severity||i.status||i.level)||e,message:r,suggestion:Vt(i.suggestion,i.fix,i.recommendation,i.action),source:i.source||n}:null}function Ta(t,e="review"){const n=rt(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([r,s])=>kt(n[r]).map(o=>oh(o,s,e)).filter(Boolean))}function o_(t,e,n=null){if(typeof t=="string")return{id:`${n||"bundle"}-manual-${e+1}`,title:t,detail:"",location:"",timing:"unspecified",artifactId:n,source:"Code Review"};const i=rt(t),r=Vt(i.title,i.action,i.step,i.message,i.name,i.description);return r?{id:i.id||`${n||"bundle"}-manual-${e+1}`,title:r,detail:Vt(i.detail,i.instructions,i.description),location:Vt(i.location,i.flutterFlowPath,i.path),timing:Vt(i.timing,i.phase)||"unspecified",artifactId:n,source:Vt(i.source)||"Code Review"}:null}function $a(t,e=null){const n=rt(t);return r_.flatMap(i=>kt(n[i])).map((i,r)=>o_(i,r,e)).filter(Boolean)}function a_(t){let e=typeof t=="string"?Pa(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const n=rt(e);typeof n.content=="string"&&(e=Pa(n.content)||e);const i=rt(e),r=rt(i.reviewResult||i.codeReview||i.result);return{rawText:"",root:Object.keys(r).length?r:i}}function l_(t,e){const n=[e.id,e.fileName,e.artifactName].map(at);return t.find(i=>{const r=rt(i);return[r.id,r.fileName,r.artifactName,r.name].map(at).some(s=>s&&n.includes(s))})||null}function c_(t,e){return kt(t?.metadata?.compatibility?.deployHints).find(r=>at(r?.artifactId)===at(e.id)||at(r?.fileName)===at(e.fileName))?.pathHint||""}function u_(t,e){return kt(t?.relationships).filter(n=>at(n?.from)===at(e.id)||at(n?.to)===at(e.id))}function d_(t,e){return kt(t?.metadata?.compatibility?.findings).filter(n=>!n?.artifactId||at(n.artifactId)===at(e.id)).map(n=>oh(n,"warning","Compatibility check")).filter(Boolean)}function f_(t,e,n,i){const r=l_(e,n),s=rt(r?.review||r||n.review),o=Object.keys(s).length>0,a=[...Ta(s),...d_(t,n)],l=$a(s,n.id),u=bl(s.status||s.verdict||s.outcome||s.result),c=a.length?Ra(...a.map(f=>f.severity)):null,d=Ra(u,c,o?null:"warning");return{...n,index:i,status:d,statusReason:o?Vt(s.summary,s.overview,s.assessment,s.conclusion)||(a.length?`${a.length} review finding${a.length===1?"":"s"}`:"No file-level findings"):"No file-level verdict was returned",reviewComplete:o,findings:a,manualSteps:l,fixedSource:typeof s.fixedSource=="string"&&s.fixedSource.trim()?s.fixedSource.trim():null,pathHint:c_(t,n),relationships:u_(t,n)}}function h_({status:t,score:e,artifactPresentations:n,manualSteps:i}){const r=n.length;if(r===0&&i.length===0)return e==null?"Code review returned no overall summary and no score.":`Reviewed bundle with score ${e}/100.`;const s=n.reduce((a,l)=>(a[l.status]+=1,a),{pass:0,warning:0,fail:0}),o=[];return t&&o.push(`Overall verdict: ${t}.`),r&&o.push(`${r} artifact${r===1?"":"s"}: ${s.pass} pass, ${s.warning} warn, ${s.fail} fail.`),i.length&&o.push(`Do before deploy: ${i.map(a=>a.title).join("; ")}.`),e==null&&o.push("No numeric score (0-100) was returned."),o.join(" ")}function p_({bundle:t,reviewResult:e}){const n=rt(t),i=kt(n.artifacts),{root:r,rawText:s}=a_(e),o=[r.bundleReview,r.overallReview,r.overall,r.bundleSummary,r.summaryReview,r.review].map(rt).find(S=>Object.keys(S).length)||{},a=kt(r.artifacts||r.files||r.reviews),l=i.map((S,_)=>f_(n,a,S,_)),u=Ta(r),d=[...Ta(o),...u],f=[...$a(o),...$a(r),...l.flatMap(S=>S.manualSteps)].filter((S,_,b)=>b.findIndex(k=>k.title===S.title&&k.artifactId===S.artifactId)===_),h=bl(o.status||o.verdict||o.overallStatus||r.status||r.verdict||r.overallStatus||r.outcome),p=Ra(h,...d.map(S=>S.severity),...l.map(S=>S.status)),g=o.score??r.score??r.overallScore??s,m=s_(g),v=Vt(o.headline,o.summary,o.executiveSummary,o.overview,o.assessment,o.conclusion,r.overallSummary,r.headline,r.summary,r.executiveSummary,r.overview,r.assessment,r.conclusion,s)||h_({status:p,score:m,artifactPresentations:l,manualSteps:f}),E=l.reduce((S,_)=>(S[_.status]+=1,S),{pass:0,warning:0,fail:0});return{title:n.title||"Generated artifact bundle",description:n.description||"",status:p,score:m,summary:v,findings:d,manualSteps:f,artifacts:l,counts:E,reviewCoverage:{reviewed:l.filter(S=>S.reviewComplete).length,total:l.length},deployOrder:kt(n.deployOrder),relationships:kt(n.relationships),warnings:kt(n.warnings),compatibility:rt(n.metadata?.compatibility)}}const g_=/^\uFEFF/;function Ci(t){let e=0,n=t.length;for(;ee&&!t[n-1].trim();)n--;return t.slice(e,n).join(` -`)}function m_(t){const e=String(t??"").replace(g_,"");if(!e.trim())return"";const n=e.split(` -`),i=c=>{const d=c.trim();return/^`{3,}[A-Za-z0-9+#_.-]*$/.test(d)?c.length-c.trimStart().length:-1};let r=0,s=-1;const o=[];{let c=0;for(let d=0;d=0&&(r++,s<0&&(s=d),o.push(c+f)),c+=n[d].length+1}}if(r===0)return Ci(n);{const c=Ma(e);if(!c.error&&o.every(f=>Nu(f,c.commentAndStringRanges)))return Ci(n)}if(r===1){const c=Ci(n.slice(0,s)),d=Ci(n.slice(s+1));return d.length>=c.length?d:c}const a=[];let l=null;for(let c=0;cc.length>0);return u.length===0?"":u.join(` +`)},g=new Set(l.slice(1).map(({index:m})=>m));o=o.filter((m,v)=>!g.has(v)),o[f.index]=p}const u={...Tu(t?.dependencies),...r.reduce((f,p)=>({...f,...Tu(p.dependencies)}),{})},c={};r.forEach(f=>{wl(f.code||"").forEach(p=>{p in u||(c[p]="")})});const d={...c,...u},h=Xv(o);return{bundleId:t?.id||"bundle-current",title:t?.title||"Generated artifact bundle",fileEntries:o,dependencies:d,relationships:t?.relationships||[],warnings:s,errors:h}}function e_(t){return String(t||"").match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/)?.[1]}function t_(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 n_(t,e){const i=[t_(t),e_(e.content),e.artifactName].find(r=>/^[A-Z][A-Za-z0-9_]*$/.test(String(r||"")));if(!i)throw new Error(`Cannot derive a FlutterFlow custom class name for ${t}.`);return i}function i_(t,e=new Map){const n=[];for(const[i,r]of t.entries())r.type!=="C"||e.has(r.path)||n.push({artifactId:r.artifactId||i,className:n_(i,r),content:r.content,fileName:i,path:r.path});return n}function r_(t,e){const n=new Set(e.map(i=>i.path));return new Map(Array.from(t.entries()).filter(([,i])=>!n.has(i.path)))}const $u={pass:0,warning:1,fail:2},s_=["manualActions"];function rt(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Vt(...t){for(const e of t){if(typeof e=="string"&&e.trim())return e.trim();if(Array.isArray(e)&&e.length>0){const n=e.filter(i=>typeof i=="string").join(` +`);if(n)return n}}return""}function kt(t){return t==null?[]:Array.isArray(t)?t:[t]}function o_(t){const e=rt(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const n=Number(e);if(Number.isFinite(n))return Mu(n);const i=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return i?Mu(Number(i[1])):null}function Mu(t){return t>=0&&t<=100?t:null}function at(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function bl(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 Ra(...t){return t.filter(Boolean).reduce((e,n)=>$u[n]>$u[e]?n:e,"pass")}function ah(t,e="warning",n="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:n};const i=rt(t),r=Vt(i.message,i.title,i.issue,i.description,i.summary);return r?{severity:bl(i.severity||i.status||i.level)||e,message:r,suggestion:Vt(i.suggestion,i.fix,i.recommendation,i.action),source:i.source||n}:null}function Ta(t,e="review"){const n=rt(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([r,s])=>kt(n[r]).map(o=>ah(o,s,e)).filter(Boolean))}function a_(t,e,n=null){if(typeof t=="string")return{id:`${n||"bundle"}-manual-${e+1}`,title:t,detail:"",location:"",timing:"unspecified",artifactId:n,source:"Code Review"};const i=rt(t),r=Vt(i.title,i.action,i.step,i.message,i.name,i.description);return r?{id:i.id||`${n||"bundle"}-manual-${e+1}`,title:r,detail:Vt(i.detail,i.instructions,i.description),location:Vt(i.location,i.flutterFlowPath,i.path),timing:Vt(i.timing,i.phase)||"unspecified",artifactId:n,source:Vt(i.source)||"Code Review"}:null}function $a(t,e=null){const n=rt(t);return s_.flatMap(i=>kt(n[i])).map((i,r)=>a_(i,r,e)).filter(Boolean)}function l_(t){let e=typeof t=="string"?Pa(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const n=rt(e);typeof n.content=="string"&&(e=Pa(n.content)||e);const i=rt(e),r=rt(i.reviewResult||i.codeReview||i.result);return{rawText:"",root:Object.keys(r).length?r:i}}function c_(t,e){const n=[e.id,e.fileName,e.artifactName].map(at);return t.find(i=>{const r=rt(i);return[r.id,r.fileName,r.artifactName,r.name].map(at).some(s=>s&&n.includes(s))})||null}function u_(t,e){return kt(t?.metadata?.compatibility?.deployHints).find(r=>at(r?.artifactId)===at(e.id)||at(r?.fileName)===at(e.fileName))?.pathHint||""}function d_(t,e){return kt(t?.relationships).filter(n=>at(n?.from)===at(e.id)||at(n?.to)===at(e.id))}function f_(t,e){return kt(t?.metadata?.compatibility?.findings).filter(n=>!n?.artifactId||at(n.artifactId)===at(e.id)).map(n=>ah(n,"warning","Compatibility check")).filter(Boolean)}function h_(t,e,n,i){const r=c_(e,n),s=rt(r?.review||r||n.review),o=Object.keys(s).length>0,a=[...Ta(s),...f_(t,n)],l=$a(s,n.id),u=bl(s.status||s.verdict||s.outcome||s.result),c=a.length?Ra(...a.map(h=>h.severity)):null,d=Ra(u,c,o?null:"warning");return{...n,index:i,status:d,statusReason:o?Vt(s.summary,s.overview,s.assessment,s.conclusion)||(a.length?`${a.length} review finding${a.length===1?"":"s"}`:"No file-level findings"):"No file-level verdict was returned",reviewComplete:o,findings:a,manualSteps:l,fixedSource:typeof s.fixedSource=="string"&&s.fixedSource.trim()?s.fixedSource.trim():null,pathHint:u_(t,n),relationships:d_(t,n)}}function p_({status:t,score:e,artifactPresentations:n,manualSteps:i}){const r=n.length;if(r===0&&i.length===0)return e==null?"Code review returned no overall summary and no score.":`Reviewed bundle with score ${e}/100.`;const s=n.reduce((a,l)=>(a[l.status]+=1,a),{pass:0,warning:0,fail:0}),o=[];return t&&o.push(`Overall verdict: ${t}.`),r&&o.push(`${r} artifact${r===1?"":"s"}: ${s.pass} pass, ${s.warning} warn, ${s.fail} fail.`),i.length&&o.push(`Do before deploy: ${i.map(a=>a.title).join("; ")}.`),e==null&&o.push("No numeric score (0-100) was returned."),o.join(" ")}function g_({bundle:t,reviewResult:e}){const n=rt(t),i=kt(n.artifacts),{root:r,rawText:s}=l_(e),o=[r.bundleReview,r.overallReview,r.overall,r.bundleSummary,r.summaryReview,r.review].map(rt).find(S=>Object.keys(S).length)||{},a=kt(r.artifacts||r.files||r.reviews),l=i.map((S,_)=>h_(n,a,S,_)),u=Ta(r),d=[...Ta(o),...u],h=[...$a(o),...$a(r),...l.flatMap(S=>S.manualSteps)].filter((S,_,b)=>b.findIndex(k=>k.title===S.title&&k.artifactId===S.artifactId)===_),f=bl(o.status||o.verdict||o.overallStatus||r.status||r.verdict||r.overallStatus||r.outcome),p=Ra(f,...d.map(S=>S.severity),...l.map(S=>S.status)),g=o.score??r.score??r.overallScore??s,m=o_(g),v=Vt(o.headline,o.summary,o.executiveSummary,o.overview,o.assessment,o.conclusion,r.overallSummary,r.headline,r.summary,r.executiveSummary,r.overview,r.assessment,r.conclusion,s)||p_({status:p,score:m,artifactPresentations:l,manualSteps:h}),E=l.reduce((S,_)=>(S[_.status]+=1,S),{pass:0,warning:0,fail:0});return{title:n.title||"Generated artifact bundle",description:n.description||"",status:p,score:m,summary:v,findings:d,manualSteps:h,artifacts:l,counts:E,reviewCoverage:{reviewed:l.filter(S=>S.reviewComplete).length,total:l.length},deployOrder:kt(n.deployOrder),relationships:kt(n.relationships),warnings:kt(n.warnings),compatibility:rt(n.metadata?.compatibility)}}const m_=/^\uFEFF/;function Ci(t){let e=0,n=t.length;for(;ee&&!t[n-1].trim();)n--;return t.slice(e,n).join(` +`)}function v_(t){const e=String(t??"").replace(m_,"");if(!e.trim())return"";const n=e.split(` +`),i=c=>{const d=c.trim();return/^`{3,}[A-Za-z0-9+#_.-]*$/.test(d)?c.length-c.trimStart().length:-1};let r=0,s=-1;const o=[];{let c=0;for(let d=0;d=0&&(r++,s<0&&(s=d),o.push(c+h)),c+=n[d].length+1}}if(r===0)return Ci(n);{const c=Ma(e);if(!c.error&&o.every(h=>Nu(h,c.commentAndStringRanges)))return Ci(n)}if(r===1){const c=Ci(n.slice(0,s)),d=Ci(n.slice(s+1));return d.length>=c.length?d:c}const a=[];let l=null;for(let c=0;cc.length>0);return u.length===0?"":u.join(` -`)}function v_(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 ah(t){const e=v_(t);return Array.from(e.matchAll(/class\s+([A-Z]\w*)\s+extends\s+[A-Za-z_]\w*Widget\b/g),n=>n[1])}function lh(t){return`${yl(t)}.dart`}function __(t){return vl(t,"W")}const Lu={"(":")","[":"]","{":"}"},y_={")":"(","]":"[","}":"{"},w_=/[A-Za-z0-9_]/;function Ma(t){const e=[{kind:"code",opener:null,openedLine:0}],n=[];let i=1,r=0;const s=(c,d)=>{(c===` +`)}function __(t){return String(t??"").replace(/\/\*[\s\S]*?\*\//g," ").replace(/\/\/[^\n]*/g,"").replace(/'''[\s\S]*?'''/g,'""').replace(/"""[\s\S]*?"""/g,'""').replace(/'(?:\\.|[^'\\\n])*'/g,'""').replace(/"(?:\\.|[^"\\\n])*"/g,'""')}function lh(t){const e=__(t);return Array.from(e.matchAll(/class\s+([A-Z]\w*)\s+extends\s+[A-Za-z_]\w*Widget\b/g),n=>n[1])}function ch(t){return`${yl(t)}.dart`}function y_(t){return vl(t,"W")}const Lu={"(":")","[":"]","{":"}"},w_={")":"(","]":"[","}":"{"},b_=/[A-Za-z0-9_]/;function Ma(t){const e=[{kind:"code",opener:null,openedLine:0}],n=[];let i=1,r=0;const s=(c,d)=>{(c===` `||c==="\r"&&d!==` `)&&i++};let o=null;const a=()=>{for(const c of e)(c.kind==="string"||c.kind==="block-comment"||c.kind==="line-comment")&&n.push({start:c.startIndex,end:t.length})};for(;r0?t[r-1]:"",p=r>1?t[r-2]:"",g=(h==="r"||h==="R")&&!w_.test(p);e.push({kind:"string",quote:c,triple:f,raw:g,startIndex:r,openedLine:i}),r+=f?3:1;continue}if(Lu[c]){e.push({kind:"code",opener:c,openedLine:i}),r++;continue}if(y_[c]){if(d.interpolation&&c==="}"){e.pop(),r++;continue}if(d.opener&&Lu[d.opener]===c){e.pop(),r++;continue}return d.opener?(a(),{error:o??`line ${i}: "${c}" closes nothing - "${d.opener}" opened on line ${d.openedLine} is still open`,commentAndStringRanges:n}):(a(),{error:o??`line ${i}: unexpected "${c}" with no matching opener`,commentAndStringRanges:n})}s(c,t[r+1]),r++}a();let l=e.length-1;for(;l>0&&e[l].kind==="line-comment";)l--;let u=o;if(!u){const c=e[l];if(!(c.kind==="code"&&!c.opener&&!c.interpolation))if(c.kind==="string")u=`unclosed ${c.triple?"triple-quoted ":""}string starting on line ${c.openedLine} was never closed`;else if(c.kind==="block-comment")u=`unterminated /* comment starting on line ${c.openedLine}`;else if(c.interpolation){const d=e.findLast(h=>h.opener);u=`unclosed "\${" expression${d?` opened on line ${d.openedLine}`:""} was never closed`}else u=`"${c.opener}" opened on line ${c.openedLine} is never closed`}return{error:u,commentAndStringRanges:n}}function b_(t){return Ma(String(t??"")).error}function Nu(t,e){return e.some(({start:n,end:i})=>t>=n&&ttypeof n=="string"?n:n?.errorMessage).filter(Boolean);return e.length>0?e.join("; "):JSON.stringify(t)}return t&&typeof t=="object"?t.errorMessage||JSON.stringify(t):String(t??"")}const E_=["gmail.com","googlemail.com","outlook.com","hotmail.com","live.com","msn.com"],S_="MAGIC_LINK_SENT",x_="PLUS_ALIAS_REJECTED",I_="Please enter your primary email address. Plus aliases (such as {email}) are not allowed for {domain} accounts.",Ps={allowlistedDomains:E_,successCode:S_,validationCode:x_,messageTemplate:I_},k_=new Set(Ps.allowlistedDomains),C_=Ps.successCode,ch=Ps.validationCode;function Fs(t){return typeof t=="string"?t.trim():""}function A_(t){const e=Fs(t),n=e.lastIndexOf("@");if(n<=0||n===e.length-1)return!1;const i=e.slice(0,n),r=e.slice(n+1).toLowerCase();return k_.has(r)?i.includes("+"):!1}function P_(t,e){return Ps.messageTemplate.replaceAll("{email}",t).replaceAll("{domain}",e)}function uh(t){if(!A_(t))return null;const e=Fs(t),n=e.lastIndexOf("@"),i=e.slice(n+1).toLowerCase();return P_(e,i)}function dh(t,e){return t?.code===ch?t.message||uh(e)||"Please enter your primary email address.":t?.code===C_||!t?.code?`Check your email — we sent a link to ${Fs(e)}`:t.message||"Something went wrong. Please try again."}const F_="ccc_auth_session",R_="ccc_subscription",T_=Object.freeze(["hasSeenWalkthrough"]);function $_(t){const e=[];for(const n of T_)t.getItem(n)!==null&&(t.removeItem(n),e.push(n));return e}function M_(){return[F_,R_]}function L_({storage:t,onIdentityChanged:e,onPlanChanged:n}){for(const i of M_())t.removeItem(i);typeof e=="function"&&e(),typeof n=="function"&&n()}function N_({sendLink:t,getEmail:e,onState:n}){let i=!1;return async function(){if(i)return{status:"busy"};i=!0;let s;try{n({status:"pending",error:null});const o=await t(e());return s={status:"sent",data:o},n({status:"sent",data:o}),s}catch(o){return s={status:"error",error:o},n({status:"error",error:o}),s}finally{i=!1}}}const O_=/^dependencies\s*:\s*(?:#.*)?$/,B_=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function Rs(t){const e=t.match(B_);return e?e[1]??e[2]??e[3]:null}function ar(t){const e=t.trim();return e===""||e.startsWith("#")}function fi(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function Sl(t,e){const n=t.findIndex(s=>e.test(s));if(n===-1)return null;let i=n,r=null;for(let s=n+1;s=0.0.0"}`}function H_(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([u])=>u&&u!=="flutter");if(i.length===0)return{yaml:n,added:[],alreadyPresent:[]};const r=n.split(` -`),s=new Set(hh(n)),o=[],a=[];for(const[u,c]of i)s.has(u)?a.push(u):(o.push([u,c]),s.add(u));if(o.length===0)return{yaml:n,added:[],alreadyPresent:a};const l=xl(r);if(l){const u=o.map(([c,d])=>Ou(l.childIndent,c,d));r.splice(l.endIndex,0,...u)}else r.length>0&&r[r.length-1].trim()!==""&&r.push(""),r.push("dependencies:"),o.forEach(([u,c])=>{r.push(Ou(" ",u,c))});return{yaml:r.join(` -`),added:o.map(([u])=>u),alreadyPresent:a}}function W_(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([l])=>l&&l!=="flutter");if(i.length===0)return{yaml:n,overridden:[],skipped:[]};const r=n.split(` -`),s=$s(n),o=[],a=[];for(const[l,u]of i){const c=s.get(l);if(!c||!c.isScalar||!String(u||"").trim()){a.push(l);continue}const d=" ".repeat(fi(r[c.lineIndex]));r[c.lineIndex]=`${d}${l}: ${gh(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:r.join(` -`),overridden:o,skipped:a}}function mh(t){const e=String(t||""),n=[];return e.trim()?(/^name:\s*\S+/m.test(e)||n.push("pubspec.yaml missing name field"),xl(e.split(` -`))||n.push("pubspec.yaml missing dependencies section"),hh(e).includes("flutter")||n.push("pubspec.yaml missing Flutter SDK dependency"),{valid:n.length===0,errors:n}):(n.push("pubspec.yaml is empty"),{valid:!1,errors:n})}const q_=">=3.0.0 <4.0.0";function La(t){const e=String(t||"").trim(),n=e[0];return n!=="'"&&n!=='"'||e[e.length-1]!==n?e:e.slice(1,-1).replaceAll(`${n}${n}`,n)}function z_(t=""){const e=Gv(t).filter(n=>!n.startsWith("dart:")&&!n.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function Bu(t,e,n){const i=[];for(const[r,s]of t){if(s.isScalar){e[r]=La(s.constraint);continue}if(s.sourceKey==="sdk"){n.add(r);continue}if(s.sourceKey===null&&s.version){e[r]=La(s.version);continue}i.push(r)}return i}function V_(t){const e=new Set,n={},i={},r=Bu($s(t),n,e);r.push(...Bu(j_(t,"dependency_overrides"),i,e));const s=new Set([...Object.keys(n),...e]),{sdk:o}=ph(t);return{sdkConstraint:La(o)||q_,dependencies:n,overrides:i,sdkPackages:[...e].sort(),availablePackages:s,unrepresentable:r}}function G_(t,e,n){return e.length>0?`${t} imports ${e.join(", ")}, which FlutterFlow only generates once the app is built, so it could not be compiled before the deploy.`:`${t} imports ${n.join(", ")}, which your project's pubspec.yaml does not declare with a version constraint, so it could not be compiled before the deploy.`}function K_(t,e){const{sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s,availablePackages:o,unrepresentable:a}=V_(e),l={sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s},u=[],c=[],d=a.map(f=>`Your project declares ${f} from a source that cannot be reproduced outside it, so the pre-deploy compile check runs against a scratch package graph that omits ${f}. Classes that do not import ${f} directly are still checked, but against that reduced graph, so their transitive package resolution may differ from your project's and the check is approximate for them.`);for(const f of t){const{className:h,content:p}=f,g=wl(p),m=g.filter(S=>a.includes(S));if(m.length>0){c.push({className:h,reason:`${h} was not compiled before deploying: it imports ${m.join(", ")}, which your project declares from a source that cannot be reproduced outside it, so package resolution could not be matched exactly.`});continue}const{unresolvableImports:v}=z_(p),E=g.filter(S=>!o.has(S));if(v.length>0||E.length>0){c.push({className:h,reason:G_(h,v,E)});continue}u.push({fileName:`${yl(h)}.dart`,content:p})}return{manifest:l,sources:u,skipped:c,approximate:d}}function Du(t,e){const n=`${t}${e}`.split(` -`),i=n.pop()??"",r=[];for(const s of n){const o=vh(s);o&&r.push(o)}return{events:r,buffer:i}}function Y_(t){const e=vh(t);return e?[e]:[]}function vh(t){const e=t.trim();if(!e)return null;try{const n=JSON.parse(e);return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}const Xe=Object.freeze({COMMITTED:"committed",PARTIAL:"partial",FAILED:"failed",UNCONFIRMED:"unconfirmed"}),_h=12e4;function yh(t){return t?.unconfirmed===!0||t?.outcome===Xe.UNCONFIRMED?Xe.UNCONFIRMED:t?.partial===!0||t?.outcome===Xe.PARTIAL?Xe.PARTIAL:t?.success===!0?Xe.COMMITTED:Xe.FAILED}class lt extends Error{constructor(e){super(e),this.name="UnconfirmedDeployError",this.outcome=Xe.UNCONFIRMED}}function J_({httpStatus:t}={}){return new lt(`Every FlutterFlow sync endpoint lost its response or ended in a server error${t?` (last: HTTP ${t})`:""} — neither can prove the push was refused, so it may already have been applied. Open the FlutterFlow project to reconcile before retrying.`)}async function Z_(t,e={}){const{onPhase:n,onLog:i}=e;let r=null,s="";const o=l=>{if(l.event==="phase"){l.message&&n&&n(l.message);return}if(l.event==="log"){l.message&&i&&i(l.message);return}r=l};let a=null;try{if(t.body?.getReader){const l=t.body.getReader(),u=new TextDecoder;for(;;){const{done:c,value:d}=await l.read();if(c)break;const f=Du(s,u.decode(d,{stream:!0}));s=f.buffer,f.events.forEach(o)}}else{const l=Du("",await t.text());s=l.buffer,l.events.forEach(o)}}catch(l){a=l}return Y_(s).forEach(o),r?{...r,success:r.success===!0||r.success===void 0&&t.ok,finalResultReceived:!0}:{success:!1,finalResultReceived:!1,httpRejected:!t.ok,httpStatus:t.status,error:t.ok?a?"The connection to the FlutterFlow deploy runner dropped before it reported a result.":"The FlutterFlow deploy runner closed the connection before it finished.":`FlutterFlow custom class provisioning failed (HTTP ${t.status}).`}}function X_(t){return t?.finalResultReceived?yh(t):t?.httpRejected?Xe.FAILED:Xe.UNCONFIRMED}function Q_(){let t=document.getElementById("fx-grid");if(!t)return null;const e=window.matchMedia("(prefers-reduced-motion: reduce)"),n=window.matchMedia("(pointer: none)");let i=t.getContext("webgl2",{alpha:!0,antialias:!1,depth:!1,stencil:!1,premultipliedAlpha:!0,powerPreference:"low-power"}),r=i?null:t.getContext("2d");if(!i&&!r)return null;const s='',o=`#version 300 es +`){n.push({start:d.startIndex,end:r}),o??=`line ${i}: string starting on line ${d.openedLine} is never closed`,e.pop();continue}if(!d.raw&&c==="\\"){s(t[r+1]??"",t[r+2]??""),r+=2;continue}if(!d.raw&&c==="$"&&t[r+1]==="{"){e.push({kind:"code",opener:null,interpolation:!0}),r+=2;continue}const h=d.triple?3:1;if(c===d.quote&&t.slice(r,r+h)===d.quote.repeat(h)){n.push({start:d.startIndex,end:r+h}),e.pop(),r+=h;continue}s(c,t[r+1]),r++;continue}if(c==="/"&&t[r+1]==="/"){e.push({kind:"line-comment",startIndex:r}),r+=2;continue}if(c==="/"&&t[r+1]==="*"){e.push({kind:"block-comment",startIndex:r,openedLine:i,depth:1}),r+=2;continue}if(c==="'"||c==='"'){const h=t.slice(r,r+3)===c.repeat(3),f=r>0?t[r-1]:"",p=r>1?t[r-2]:"",g=(f==="r"||f==="R")&&!b_.test(p);e.push({kind:"string",quote:c,triple:h,raw:g,startIndex:r,openedLine:i}),r+=h?3:1;continue}if(Lu[c]){e.push({kind:"code",opener:c,openedLine:i}),r++;continue}if(w_[c]){if(d.interpolation&&c==="}"){e.pop(),r++;continue}if(d.opener&&Lu[d.opener]===c){e.pop(),r++;continue}return d.opener?(a(),{error:o??`line ${i}: "${c}" closes nothing - "${d.opener}" opened on line ${d.openedLine} is still open`,commentAndStringRanges:n}):(a(),{error:o??`line ${i}: unexpected "${c}" with no matching opener`,commentAndStringRanges:n})}s(c,t[r+1]),r++}a();let l=e.length-1;for(;l>0&&e[l].kind==="line-comment";)l--;let u=o;if(!u){const c=e[l];if(!(c.kind==="code"&&!c.opener&&!c.interpolation))if(c.kind==="string")u=`unclosed ${c.triple?"triple-quoted ":""}string starting on line ${c.openedLine} was never closed`;else if(c.kind==="block-comment")u=`unterminated /* comment starting on line ${c.openedLine}`;else if(c.interpolation){const d=e.findLast(f=>f.opener);u=`unclosed "\${" expression${d?` opened on line ${d.openedLine}`:""} was never closed`}else u=`"${c.opener}" opened on line ${c.openedLine} is never closed`}return{error:u,commentAndStringRanges:n}}function E_(t){return Ma(String(t??"")).error}function Nu(t,e){return e.some(({start:n,end:i})=>t>=n&&ttypeof n=="string"?n:n?.errorMessage).filter(Boolean);return e.length>0?e.join("; "):JSON.stringify(t)}return t&&typeof t=="object"?t.errorMessage||JSON.stringify(t):String(t??"")}const S_=["gmail.com","googlemail.com","outlook.com","hotmail.com","live.com","msn.com"],x_="MAGIC_LINK_SENT",I_="PLUS_ALIAS_REJECTED",k_="Please enter your primary email address. Plus aliases (such as {email}) are not allowed for {domain} accounts.",Ps={allowlistedDomains:S_,successCode:x_,validationCode:I_,messageTemplate:k_},C_=new Set(Ps.allowlistedDomains),A_=Ps.successCode,uh=Ps.validationCode;function Fs(t){return typeof t=="string"?t.trim():""}function P_(t){const e=Fs(t),n=e.lastIndexOf("@");if(n<=0||n===e.length-1)return!1;const i=e.slice(0,n),r=e.slice(n+1).toLowerCase();return C_.has(r)?i.includes("+"):!1}function F_(t,e){return Ps.messageTemplate.replaceAll("{email}",t).replaceAll("{domain}",e)}function dh(t){if(!P_(t))return null;const e=Fs(t),n=e.lastIndexOf("@"),i=e.slice(n+1).toLowerCase();return F_(e,i)}function fh(t,e){return t?.code===uh?t.message||dh(e)||"Please enter your primary email address.":t?.code===A_||!t?.code?`Check your email — we sent a link to ${Fs(e)}`:t.message||"Something went wrong. Please try again."}const R_="ccc_auth_session",T_="ccc_subscription",$_=Object.freeze(["hasSeenWalkthrough"]);function M_(t){const e=[];for(const n of $_)t.getItem(n)!==null&&(t.removeItem(n),e.push(n));return e}function L_(){return[R_,T_]}function N_({storage:t,onIdentityChanged:e,onPlanChanged:n}){for(const i of L_())t.removeItem(i);typeof e=="function"&&e(),typeof n=="function"&&n()}function O_({sendLink:t,getEmail:e,onState:n}){let i=!1;return async function(){if(i)return{status:"busy"};i=!0;let s;try{n({status:"pending",error:null});const o=await t(e());return s={status:"sent",data:o},n({status:"sent",data:o}),s}catch(o){return s={status:"error",error:o},n({status:"error",error:o}),s}finally{i=!1}}}const B_=/^dependencies\s*:\s*(?:#.*)?$/,D_=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function Rs(t){const e=t.match(D_);return e?e[1]??e[2]??e[3]:null}function ar(t){const e=t.trim();return e===""||e.startsWith("#")}function fi(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function Sl(t,e){const n=t.findIndex(s=>e.test(s));if(n===-1)return null;let i=n,r=null;for(let s=n+1;s=0.0.0"}`}function W_(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([u])=>u&&u!=="flutter");if(i.length===0)return{yaml:n,added:[],alreadyPresent:[]};const r=n.split(` +`),s=new Set(ph(n)),o=[],a=[];for(const[u,c]of i)s.has(u)?a.push(u):(o.push([u,c]),s.add(u));if(o.length===0)return{yaml:n,added:[],alreadyPresent:a};const l=xl(r);if(l){const u=o.map(([c,d])=>Ou(l.childIndent,c,d));r.splice(l.endIndex,0,...u)}else r.length>0&&r[r.length-1].trim()!==""&&r.push(""),r.push("dependencies:"),o.forEach(([u,c])=>{r.push(Ou(" ",u,c))});return{yaml:r.join(` +`),added:o.map(([u])=>u),alreadyPresent:a}}function q_(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([l])=>l&&l!=="flutter");if(i.length===0)return{yaml:n,overridden:[],skipped:[]};const r=n.split(` +`),s=$s(n),o=[],a=[];for(const[l,u]of i){const c=s.get(l);if(!c||!c.isScalar||!String(u||"").trim()){a.push(l);continue}const d=" ".repeat(fi(r[c.lineIndex]));r[c.lineIndex]=`${d}${l}: ${mh(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:r.join(` +`),overridden:o,skipped:a}}function vh(t){const e=String(t||""),n=[];return e.trim()?(/^name:\s*\S+/m.test(e)||n.push("pubspec.yaml missing name field"),xl(e.split(` +`))||n.push("pubspec.yaml missing dependencies section"),ph(e).includes("flutter")||n.push("pubspec.yaml missing Flutter SDK dependency"),{valid:n.length===0,errors:n}):(n.push("pubspec.yaml is empty"),{valid:!1,errors:n})}const z_=">=3.0.0 <4.0.0";function La(t){const e=String(t||"").trim(),n=e[0];return n!=="'"&&n!=='"'||e[e.length-1]!==n?e:e.slice(1,-1).replaceAll(`${n}${n}`,n)}function V_(t=""){const e=Kv(t).filter(n=>!n.startsWith("dart:")&&!n.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function Bu(t,e,n){const i=[];for(const[r,s]of t){if(s.isScalar){e[r]=La(s.constraint);continue}if(s.sourceKey==="sdk"){n.add(r);continue}if(s.sourceKey===null&&s.version){e[r]=La(s.version);continue}i.push(r)}return i}function G_(t){const e=new Set,n={},i={},r=Bu($s(t),n,e);r.push(...Bu(U_(t,"dependency_overrides"),i,e));const s=new Set([...Object.keys(n),...e]),{sdk:o}=gh(t);return{sdkConstraint:La(o)||z_,dependencies:n,overrides:i,sdkPackages:[...e].sort(),availablePackages:s,unrepresentable:r}}function K_(t,e,n){return e.length>0?`${t} imports ${e.join(", ")}, which FlutterFlow only generates once the app is built, so it could not be compiled before the deploy.`:`${t} imports ${n.join(", ")}, which your project's pubspec.yaml does not declare with a version constraint, so it could not be compiled before the deploy.`}function Y_(t,e){const{sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s,availablePackages:o,unrepresentable:a}=G_(e),l={sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s},u=[],c=[],d=a.map(h=>`Your project declares ${h} from a source that cannot be reproduced outside it, so the pre-deploy compile check runs against a scratch package graph that omits ${h}. Classes that do not import ${h} directly are still checked, but against that reduced graph, so their transitive package resolution may differ from your project's and the check is approximate for them.`);for(const h of t){const{className:f,content:p}=h,g=wl(p),m=g.filter(S=>a.includes(S));if(m.length>0){c.push({className:f,reason:`${f} was not compiled before deploying: it imports ${m.join(", ")}, which your project declares from a source that cannot be reproduced outside it, so package resolution could not be matched exactly.`});continue}const{unresolvableImports:v}=V_(p),E=g.filter(S=>!o.has(S));if(v.length>0||E.length>0){c.push({className:f,reason:K_(f,v,E)});continue}u.push({fileName:`${yl(f)}.dart`,content:p})}return{manifest:l,sources:u,skipped:c,approximate:d}}function Du(t,e){const n=`${t}${e}`.split(` +`),i=n.pop()??"",r=[];for(const s of n){const o=_h(s);o&&r.push(o)}return{events:r,buffer:i}}function J_(t){const e=_h(t);return e?[e]:[]}function _h(t){const e=t.trim();if(!e)return null;try{const n=JSON.parse(e);return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}const Xe=Object.freeze({COMMITTED:"committed",PARTIAL:"partial",FAILED:"failed",UNCONFIRMED:"unconfirmed"}),yh=12e4;function wh(t){return t?.unconfirmed===!0||t?.outcome===Xe.UNCONFIRMED?Xe.UNCONFIRMED:t?.partial===!0||t?.outcome===Xe.PARTIAL?Xe.PARTIAL:t?.success===!0?Xe.COMMITTED:Xe.FAILED}class lt extends Error{constructor(e){super(e),this.name="UnconfirmedDeployError",this.outcome=Xe.UNCONFIRMED}}function ju({httpStatus:t}={}){return new lt(`Every FlutterFlow sync endpoint lost its response or ended in a server error${t?` (last: HTTP ${t})`:""} — neither can prove the push was refused, so it may already have been applied. Open the FlutterFlow project to reconcile before retrying.`)}async function Z_(t,e={}){const{onPhase:n,onLog:i}=e;let r=null,s="";const o=l=>{if(l.event==="phase"){l.message&&n&&n(l.message);return}if(l.event==="log"){l.message&&i&&i(l.message);return}r=l};let a=null;try{if(t.body?.getReader){const l=t.body.getReader(),u=new TextDecoder;for(;;){const{done:c,value:d}=await l.read();if(c)break;const h=Du(s,u.decode(d,{stream:!0}));s=h.buffer,h.events.forEach(o)}}else{const l=Du("",await t.text());s=l.buffer,l.events.forEach(o)}}catch(l){a=l}return J_(s).forEach(o),r?{...r,success:r.success===!0||r.success===void 0&&t.ok,finalResultReceived:!0}:{success:!1,finalResultReceived:!1,httpRejected:!t.ok,httpStatus:t.status,error:t.ok?a?"The connection to the FlutterFlow deploy runner dropped before it reported a result.":"The FlutterFlow deploy runner closed the connection before it finished.":`FlutterFlow custom class provisioning failed (HTTP ${t.status}).`}}function X_(t){return t?.finalResultReceived?wh(t):t?.httpRejected?Xe.FAILED:Xe.UNCONFIRMED}function Q_(){let t=document.getElementById("fx-grid");if(!t)return null;const e=window.matchMedia("(prefers-reduced-motion: reduce)"),n=window.matchMedia("(pointer: none)");let i=t.getContext("webgl2",{alpha:!0,antialias:!1,depth:!1,stencil:!1,premultipliedAlpha:!0,powerPreference:"low-power"}),r=i?null:t.getContext("2d");if(!i&&!r)return null;const s='',o=`#version 300 es in vec2 p; void main(){ gl_Position = vec4(p, 0.0, 1.0); }`;function a(){return["#version 300 es","precision highp float;","out vec4 o;","uniform vec2 res;","uniform vec2 design;","uniform vec2 mouse;","uniform float energy;","uniform float parallax;","uniform float t;","uniform vec3 ink;","uniform sampler2D mark;","uniform vec2 rot;","const float WARP_A = 0.0032;","void main(){"," vec2 px = gl_FragCoord.xy * (design / res);"," vec2 p = vec2(px.x, design.y - px.y);"," vec2 off = vec2(0.0, -parallax) + vec2(sin(t * 0.11), cos(t * 0.09)) * 7.0;"," vec2 g = p + off;"," vec2 gm = mouse + off;"," float base = min(design.x, design.y);"," float spacing = clamp(base / 10.0, 64.0, 118.0);"," vec2 rel = g - gm;"," float rho = length(rel) + 1e-5;"," vec2 dir = rel / rho;"," vec2 pw = gm + dir * (rho + WARP_A * rho * rho);"," vec2 cell = floor(pw / spacing);"," vec2 cw = (cell + 0.5) * spacing - gm;"," float Rc = length(cw) + 1e-5;"," float rhoC = (-1.0 + sqrt(1.0 + 4.0 * WARP_A * Rc)) / (2.0 * WARP_A);"," vec2 c = gm + (cw / Rc) * rhoC;"," float cellSize = spacing / (1.0 + 2.0 * WARP_A * rhoC);"," float sigma = spacing * 2.9;"," float f = exp(-(rhoC * rhoC) / (2.0 * sigma * sigma));"," float scale = mix(0.32, 1.42, f);"," float weight = smoothstep(0.06, 0.80, f);"," float hs = cellSize * 0.26 * scale;"," vec2 uv = (g - c) / hs;"," vec2 ruv = mat2(rot.x, rot.y, -rot.y, rot.x) * uv;"," float cov = 0.0;"," if (abs(ruv.x) <= 1.0 && abs(ruv.y) <= 1.0) cov = texture(mark, ruv * 0.5 + 0.5).a;"," float s = cov * weight * energy * 0.26;"," o = vec4(ink * s, s);","}"].join(` -`)}let l=null,u,c,d,f,h,p,g,m,v;function E(Y,W){if(!i)return null;const D=i.createShader(Y);return i.shaderSource(D,W),i.compileShader(D),i.getShaderParameter(D,i.COMPILE_STATUS)?D:(window.console&&console.warn("fx-grid shader: "+i.getShaderInfoLog(D)),null)}if(i){const Y=E(i.VERTEX_SHADER,o),W=E(i.FRAGMENT_SHADER,a());if(Y&&W&&(l=i.createProgram(),i.attachShader(l,Y),i.attachShader(l,W),i.linkProgram(l),i.getProgramParameter(l,i.LINK_STATUS)||(window.console&&console.warn("fx-grid link: "+i.getProgramInfoLog(l)),l=null)),l){i.useProgram(l),i.bindBuffer(i.ARRAY_BUFFER,i.createBuffer()),i.bufferData(i.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),i.STATIC_DRAW);const D=i.getAttribLocation(l,"p");i.enableVertexAttribArray(D),i.vertexAttribPointer(D,2,i.FLOAT,!1,0,0),u=i.getUniformLocation(l,"res"),c=i.getUniformLocation(l,"design"),d=i.getUniformLocation(l,"mouse"),f=i.getUniformLocation(l,"energy"),h=i.getUniformLocation(l,"parallax"),p=i.getUniformLocation(l,"t"),g=i.getUniformLocation(l,"ink"),m=i.getUniformLocation(l,"mark"),v=i.getUniformLocation(l,"rot"),i.enable(i.BLEND),i.blendFunc(i.ONE,i.ONE_MINUS_SRC_ALPHA),i.clearColor(0,0,0,0)}else{i=null;const D=t.cloneNode(!1);if(t.parentNode.replaceChild(D,t),t=D,r=t.getContext("2d"),!r)return null}}function S(Y){if(!Y)return null;const W=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(Y);if(W){let D=W[1];return D.length===3&&(D=D[0]+D[0]+D[1]+D[1]+D[2]+D[2]),[parseInt(D.slice(0,2),16)/255,parseInt(D.slice(2,4),16)/255,parseInt(D.slice(4,6),16)/255]}try{const D=document.createElement("canvas");D.width=1,D.height=1;const ue=D.getContext("2d");ue.fillStyle="rgb(9, 8, 7)";const xe=String(ue.fillStyle);ue.fillStyle=Y;const Fe=String(ue.fillStyle);if(Fe===xe)return null;const dt=/^#([0-9a-f]{6})$/i.exec(Fe);if(dt){const ft=dt[1];return[parseInt(ft.slice(0,2),16)/255,parseInt(ft.slice(2,4),16)/255,parseInt(ft.slice(4,6),16)/255]}const Nt=/rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i.exec(Fe);if(Nt)return[Number(Nt[1])/255,Number(Nt[2])/255,Number(Nt[3])/255]}catch{}return null}function _(){let Y="";try{const W=getComputedStyle(document.documentElement);Y=(W.getPropertyValue("--fx-ink")||"").trim()||(W.getPropertyValue("--fg")||"").trim()}catch{}return S(Y)||[.56,.68,.88]}const b=_();let k=1920,T=1080,x=960,F=540,$=960,O=540,L=.66,N=0,K=-1e9,V=!1,M=0,R=0,Z=null,Ce=!1,oe=!1,ye=!1;const $e=64,ae=15.2;let Ie=0,Se=0;const Be=.0032,wt=0,ge=.56,Ye=.26,bt=.32,mn=.16,Re=.349;let Pe=wt;function $t(){const Y=t.getBoundingClientRect(),W=t.clientWidth,D=t.clientHeight;if(!Y.width||!W||!D)return;const ue=Math.min(window.devicePixelRatio||1,2),xe=Math.max(.2,Math.min(2,Y.width/W*ue)),Fe=Math.max(2,Math.round(W*xe)),dt=Math.max(2,Math.round(D*xe));(Fe!==t.width||dt!==t.height)&&(t.width=Fe,t.height=dt,i&&i.viewport(0,0,Fe,dt)),k=W,T=D,V||(x=$=k/2,F=O=T/2,V=!0)}function Bn(Y){!l||!Ce||!i||(i.uniform2f(u,t.width,t.height),i.uniform2f(c,k,T),i.uniform2f(d,x,F),i.uniform1f(f,L),i.uniform1f(h,N),i.uniform2f(v,Math.cos(Pe),Math.sin(Pe)),i.uniform1f(p,Y),i.uniform3f(g,b[0],b[1],b[2]),i.clear(i.COLOR_BUFFER_BIT),i.drawArrays(i.TRIANGLES,0,3))}function qe(Y,W,D){const ue=Math.max(0,Math.min(1,(D-Y)/(W-Y)));return ue*ue*(3-2*ue)}function Dn(Y){if(!Z||!r)return;const W=r;W.setTransform(1,0,0,1,0,0),W.clearRect(0,0,t.width,t.height);const D=t.width/k;W.setTransform(D,0,0,D,0,0),W.globalAlpha=1;const ue=Math.min(k,T),xe=Math.max(64,Math.min(118,ue/10)),Fe=xe*2.9,dt=2*Fe*Fe,Nt=Math.sin(Y*.11)*7,ft=Math.cos(Y*.09)*7-N,dr=x+Nt,fr=F+ft,no=Fe*Math.sqrt(2*Math.log(1/.06)),mi=no+Be*no*no+xe,Cp=Math.floor((dr-mi)/xe)-1,Ap=Math.ceil((dr+mi)/xe)+1,Pp=Math.floor((fr-mi)/xe)-1,Fp=Math.ceil((fr+mi)/xe)+1;for(let io=Pp;io<=Fp;io++){const Rp=(io+.5)*xe;for(let ro=Cp;ro<=Ap;ro++){const so=(ro+.5)*xe-dr,oo=Rp-fr,ao=Math.sqrt(so*so+oo*oo)+1e-5;if(ao>mi)continue;const hr=(-1+Math.sqrt(1+4*Be*ao))/(2*Be),ac=Math.exp(-(hr*hr)/dt),lc=qe(.06,.8,ac)*L*.26;if(lc<.004)continue;const on=xe/(1+2*Be*hr)*.26*(.32+1.1*ac),cc=hr/ao,lo=dr+so*cc,co=fr+oo*cc;lo<-on*1.6||lo>k+on*1.6||co<-on*1.6||co>T+on*1.6||(W.globalAlpha=lc,W.save(),W.translate(lo,co),W.rotate(Pe),W.drawImage(Z,-on,-on,on*2,on*2),W.restore())}}W.globalAlpha=1}function Mt(Y){if(!oe)return;const W=R?Math.min(.05,(Y-R)/1e3):.016;R=Y;const ue=Y-K>2400?.6:1;L+=(ue-L)*Math.min(1,W*3.2);const xe=Math.min(.05,W);Ie+=(($-x)*$e-Ie*ae)*xe,Se+=((O-F)*$e-Se*ae)*xe,x+=Ie*xe,F+=Se*xe,N=(window.scrollY||window.pageYOffset||0)*.55;const Fe=Y/1e3,dt=x/(k||1)-.5,Nt=F/(T||1)-.5;let ft=dt*(dt>=0?ge:Ye)+Nt*(Nt>=0?bt:mn);ft>Re?ft=Re:ft<-Re&&(ft=-Re),Pe=wt+ft-N*6e-4,$t(),i?Bn(Fe):Dn(Fe),M=requestAnimationFrame(Mt)}function Lt(Y){if(!oe)return;const W=t.getBoundingClientRect();!W.width||!k||!T||($=(Y.clientX-W.left)/W.width*k,O=(Y.clientY-W.top)/W.height*T,K=performance.now())}function ut(){oe||to||e.matches||n.matches||!ye||document.hidden||(oe=!0,R=0,M=requestAnimationFrame(Mt))}function sn(){oe=!1,M&&(cancelAnimationFrame(M),M=0),R=0}function gi(){e.matches?(sn(),t.classList.remove("is-ready")):ye&&ut()}function jn(){n.matches?sn():ye&&ut()}function rc(){document.hidden?sn():ye&&ut()}const sc=new IntersectionObserver(Y=>{ye=Y[0]?.isIntersecting||!1,ye?ut():sn()},{threshold:0});sc.observe(t),window.addEventListener("pointermove",Lt,{passive:!0,capture:!0}),window.addEventListener("resize",$t),e.addEventListener("change",gi),n.addEventListener("change",jn),document.addEventListener("visibilitychange",rc);function kp(){const Y=(s.match(/\sd="([^"]+)"/)||[])[1],W=document.createElement("canvas");W.width=256,W.height=256;const D=W.getContext("2d");if(Y&&window.Path2D){const ue=Math.min(8.533333333333333,8.421052631578947);D.setTransform(ue,0,0,ue,ue+(256-30*ue)/2,-6.4*ue),D.fillStyle="rgb(255,255,255)",D.fill(new Path2D(Y),"evenodd"),D.setTransform(1,0,0,1,0,0)}try{const ue=D.getImageData(0,0,256,256),xe=ue.data;for(let Fe=3;Feoe}}const ey=120;function ty(t,e,n){return tn?n:t}function de(t,e,n){return ty((t-e)/(n-e),0,1)}function ny(t){return t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2}function Uo(t){return 1-Math.pow(1-t,3)}function ze(t,e){return e=e===void 0?1.7:e,1+(e+1)*Math.pow(t-1,3)+e*Math.pow(t-1,2)}function ju(t){return 1-Math.pow(2,-9*t)*Math.cos(t*15)}function te(t,e){if(t<=e[0].t)return e[0].v;for(let n=1;n8.2&&_<9.4&&(s*=1-.07*Math.sin(de(_,8.2,9.4)*Math.PI))}else if(t<53){const _=t-42;g=te(_,[{t:0,v:1},{t:2,v:0},{t:4.2,v:0},{t:4.6,v:1},{t:6.8,v:1},{t:7.4,v:0},{t:9.4,v:0},{t:10.6,v:1}]),p=te(_,[{t:0,v:1},{t:2,v:.3},{t:4.6,v:1,e:ze}]),d=te(_,[{t:0,v:0},{t:2,v:.3},{t:4.6,v:.16,e:ze},{t:10.6,v:0}]),h=te(_,[{t:0,v:0},{t:2,v:-40},{t:4.6,v:0,e:ze}]),o=te(_,[{t:0,v:0},{t:4.6,v:-.12},{t:10.6,v:0}])}else if(t<60){const _=t-53;c=te(_,[{t:0,v:1},{t:.35,v:0},{t:.45,v:0},{t:.7,v:1}]);const b=de(_,.45,2.2);a=b>0?-2.6*(1-ju(b)):0,g=te(_,[{t:0,v:1},{t:.57,v:0},{t:.67,v:0},{t:.92,v:1}]);const k=de(_,.67,2.42);f=k>0?-2.6*(1-ju(k)):0,s=1-.05*(Math.sin(de(_,1.9,2.5)*Math.PI)+Math.sin(de(_,2.5,3.1)*Math.PI))}else if(t<74){let b=function(F){return[te(F,[{t:0,v:0},{t:.25,v:1},{t:.5,v:1},{t:.72,v:.14},{t:.82,v:.14},{t:1,v:0}]),te(F,[{t:0,v:0},{t:.08,v:-.62},{t:.25,v:-.62},{t:.33,v:.62},{t:.7,v:.62},{t:.82,v:-.62},{t:1,v:-.62}])]};var S=b;const _=t-60,k=1-de(_,12,14),T=b(de(_,0,12)),x=b(de(_-.5,0,12));n=T[0]*k,i=(T[1]+.05*Math.sin(_*7))*k,o=(x[0]-T[0])*.6*k,a=(x[1]-T[1])*.6*k,h=(x[0]-T[0])*30*k,E=de(_,0,.4)*k}else if(t<85.4){const _=t-74,b=te(_,[{t:0,v:0},{t:4,v:1},{t:8,v:.24},{t:9.6,v:1,e:ze},{t:11.4,v:0}]);o=b*.5,d=-b*.5,l=te(_,[{t:0,v:0},{t:4,v:6},{t:8,v:20},{t:9.6,v:38,e:ze},{t:11.4,v:0}]),h=-l*.7,a=te(_,[{t:0,v:0},{t:8,v:0},{t:9.6,v:.4},{t:11.4,v:0}])}else if(t<96.4){const _=t-85.4,b=de(_,0,5.6),k=de(_,5.6,7.6),T=.72*Math.min(1,_/.6)*(1-k);d=Math.cos(b*Math.PI*2)*T,f=Math.sin(b*Math.PI*2)*T*.55,h=b*360*(1-k);const x=te(_,[{t:0,v:0},{t:7.6,v:0},{t:8.2,v:1,e:Uo},{t:8.6,v:.55},{t:9.4,v:0}]);o=-.16*x,d+=.16*x,l=-6*x,h+=6*x,s=1+.05*x,m=1+.9*x}else if(t<108.6){const _=t-96.4,b=de(_,9.6,12.2);n=te(_,[{t:0,v:0},{t:2.1,v:1},{t:4.8,v:.08},{t:7.5,v:1},{t:9.6,v:0}])*(1-b),i=-.35*Math.abs(Math.sin(de(_,0,9.6)*Math.PI*3))*(1-b);const k=Math.sin(_*6.2)*(1-b);u=1+.12*k,p=1-.12*k,l=k*8,h=-k*8,o=.06*k,d=-.06*k,E=de(_,0,.4)*(1-b)}else{const _=t-108.6,b=Math.sin(de(_,0,8)*Math.PI),k=1-de(_,8,11.4);s=1+.04*b*k,i=-.1*b*k,r=2*b*k,m=1+.5*Math.sin(de(_,0,6)*Math.PI),v=1+.1*Math.sin(de(_,0,6)*Math.PI)}return e.x=n,e.y=i,e.rot=r,e.scale=s,e.ax=o,e.ay=a,e.ar=l,e.asc=u,e.afade=c,e.bx=d,e.by=f,e.br=h,e.bsc=p,e.bfade=g,e.hfade=m,e.hsc=v,e.shd=E,e}function iy(t={}){const e=t.arena||document.querySelector(".pipeline-glyph.logo-loop");if(!e)return null;const n=e.querySelector(".loop-mark"),i=e.querySelector(".loop-piece-a"),r=e.querySelector(".loop-piece-b"),s=e.querySelector(".loop-halo"),o=e.querySelector(".loop-shadow");if(!n||!i||!r||!s||!o)return null;const a=t.reducedMotion||window.matchMedia("(prefers-reduced-motion: reduce)"),l=ey;let u=34,c=0,d=0;function f(){u=n.offsetWidth||34,c=Math.max(0,e.offsetWidth-u-4),d=Math.max(0,(e.offsetHeight-u)/2-2),e.style.setProperty("--mark-c",u/2+"px")}function h(M){const R=Math.min(1,Math.max(0,M.x))*c,Z=M.y*d;n.style.transform="translate3d("+R.toFixed(2)+"px,"+Z.toFixed(2)+"px,0) rotate("+M.rot.toFixed(2)+"deg) scale("+M.scale.toFixed(3)+")",i.style.transform="translate3d("+(M.ax*u).toFixed(2)+"px,"+(M.ay*u).toFixed(2)+"px,0) rotate("+M.ar.toFixed(2)+"deg) scale("+M.asc.toFixed(3)+")",i.style.opacity=M.afade.toFixed(3),r.style.transform="translate3d("+(M.bx*u).toFixed(2)+"px,"+(M.by*u).toFixed(2)+"px,0) rotate("+M.br.toFixed(2)+"deg) scale("+M.bsc.toFixed(3)+")",r.style.opacity=M.bfade.toFixed(3),s.style.transform="scale("+M.hsc.toFixed(3)+")",s.style.opacity=(.09*M.hfade).toFixed(3),o.style.transform="translateX("+R.toFixed(2)+"px) scaleX("+(.75+.4*Math.abs(M.x)).toFixed(3)+")",o.style.opacity=(M.shd*.5).toFixed(3)}let p=0,g=0,m=0,v=!1,E=!1,S=!1,_=0;function b(){return S||a.matches||document.hidden||!e.offsetParent?!1:E}function k(M){if(!v)return;if(m=requestAnimationFrame(k),!b()){x();return}const R=g?(M-g)/1e3:0;g=M,p=(p+Math.min(R,.1))%l,_+=1,h(Ai(p))}function T(){v||S||b()&&(v=!0,g=0,m=requestAnimationFrame(k))}function x(){v=!1,m&&(cancelAnimationFrame(m),m=0),g=0}function F(){b()?T():x()}function $(){a.matches?(x(),h(Ai(0))):F()}function O(){f(),v&&h(Ai(p))}function L(){g=0,F()}const N=new IntersectionObserver(M=>{E=M[0]?M[0].isIntersecting:!1,F()},{threshold:0});N.observe(e),window.addEventListener("resize",O),a.addEventListener("change",$),document.addEventListener("visibilitychange",L);function K(){S||(S=!0,x(),N.disconnect(),window.removeEventListener("resize",O),a.removeEventListener("change",$),document.removeEventListener("visibilitychange",L))}window.addEventListener("pagehide",K);function V(M){p=(M%l+l)%l,h(Ai(p))}return f(),h(Ai(0)),F(),{isRunning:()=>v,currentTime:()=>p,frameCount:()=>_,seek:V,dispose:K}}const ry=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function Xt(t){const e=String(t||"").trim().match(ry);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function sy(t,e){if(t.length===0&&e.length===0)return 0;if(t.length===0)return 1;if(e.length===0)return-1;for(let n=0;n0)}function ay(t){const e=Xt(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function Il(t){let e=String(t??"").trim();if((e.startsWith("'")||e.startsWith('"'))&&(e=e.slice(1,-1).trim()),e===""||e==="any"||e==="*")return{min:null,minInclusive:!1,max:null,maxInclusive:!1};if(e.startsWith("^")){const o=e.slice(1).trim();return Xt(o)?{min:o,minInclusive:!0,max:ay(o),maxInclusive:!1}:null}if(Xt(e))return{min:e,minInclusive:!0,max:e,maxInclusive:!0};const n={min:null,minInclusive:!1,max:null,maxInclusive:!1},i=/(>=|<=|>|<)\s*([0-9][0-9A-Za-z.+-]*)/g;let r=!1,s;for(;(s=i.exec(e))!==null;){const[,o,a]=s;if(!Xt(a))return null;r=!0,o===">="||o===">"?(n.min=a,n.minInclusive=o===">="):(n.max=a,n.maxInclusive=o==="<=")}return r?n:null}function Uu(t,e){const n=Il(t);if(!n||!Xt(e))return!1;if(n.min!==null){const i=fs(e,n.min);if(i<0||i===0&&!n.minInclusive)return!1}if(n.max!==null){const i=fs(e,n.max);if(i>0||i===0&&!n.maxInclusive)return!1}return!0}function ly(t,e){const n=Il(t);if(!n||!Xt(e))return!1;if(n.max===null)return!0;const i=fs(n.max,e);return i>0?!0:i===0&&n.maxInclusive}function zn(t){const e=Il(t);return e?e.min:null}const cy="https://pub.dev/api/packages/",uy=8e3;function dy(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null}=e,r=Array.isArray(t?.versions)?t.versions:[];let s=null;for(const o of r){const a=o?.version;if(!a||o.retracted||oy(a))continue;const l=o.pubspec?.environment||{};n&&l.sdk&&!Uu(l.sdk,n)||i&&l.flutter&&!Uu(l.flutter,i)||(!s||fs(a,s)>0)&&(s=a)}return s?{version:s,constraint:`^${s}`}:null}async function fy(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null,fetchImpl:r=fetch}=e;let s;try{const a=await r(`${cy}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(uy)});if(!a.ok)return{name:t,constraint:null,version:null,error:a.status===404?`"${t}" was not found on pub.dev`:`pub.dev returned ${a.status} for "${t}"`};s=await a.json()}catch(a){return{name:t,constraint:null,version:null,error:`could not reach pub.dev for "${t}" (${a.message})`}}const o=dy(s,{dartSdkFloor:n,flutterSdkFloor:i});return o?{name:t,...o,error:null}:{name:t,constraint:null,version:null,error:n?`no published "${t}" release supports Dart ${n}`:`no published "${t}" release could be read`}}async function hy(t,e={}){const n=await Promise.all(t.map(i=>fy(i,e)));return new Map(n.map(({name:i,...r})=>[i,r]))}async function py(t,e={},n={}){const{resolveVersions:i=hy}=n,r=Object.entries(e).filter(([c])=>c&&c!=="flutter"),s=ph(t),o={dartSdkFloor:zn(s.sdk),flutterSdkFloor:zn(s.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(r.length===0)return a;const l=$s(t),u=[];for(const[c,d]of r){const f=l.get(c);if(!f){u.push(c);continue}const h=zn(d);if(!h){a.kept.push({name:c,constraint:f.constraint});continue}if(!f.isScalar){a.warnings.push(`"${c}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${h}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:c,constraint:f.constraint});continue}if(ly(f.constraint,h)){a.kept.push({name:c,constraint:f.constraint});continue}a.overrides[c]=`^${h}`,a.warnings.push(`"${c}" was pinned to ${f.constraint} in your project, which cannot resolve the ${h} the generated code needs. Raising it to ^${h} — this changes a dependency the rest of your app also uses.`)}if(u.length>0){const c=await i(u,o);for(const d of u){const f=c.get(d);if(f?.constraint){a.additions[d]=f.constraint;continue}const h=e[d]||"";if(zn(h)){a.additions[d]=`^${zn(h)}`,a.warnings.push(`Could not confirm "${d}" version on pub.dev (${f?.error||"lookup failed"}). Using ^${zn(h)} from the AI's recommendation — verify this is current.`);continue}a.additions[d]=">=0.0.0",a.warnings.push(`Could not determine a version for "${d}" (${f?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const gy={"&":"&","<":"<",">":">",'"':""","'":"'"};function Qt(t){return String(t??"").replace(/[&<>"']/g,e=>gy[e])}function q(t){return t?Qt(t).replace(/\n/g,"
    "):""}function Jt(t){return Qt(t).replace(/\r?\n/g," ")}function Ms(t,e={}){const n=t?.pipelineStep;if(n!=null&&e[n]!=null)return e[n];const i=t?.message||"";return i.includes("Code Generator")?2:i.includes("Code Review")?3:1}function bh(t){if(!t)return{kind:"generic",title:"Generation failed",message:"An unknown error occurred. Please try again.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1};if(t.isModelArmor){const n=t.code==="MODEL_ARMOR_BLOCKED";return{kind:"safety",title:t.userTitle||"Request blocked for safety",message:t.userMessage||t.message,detail:t.retryExplanation||"",canRetry:!n,canEdit:!0,canUpgrade:!1}}if(t.isUsageLimit)return{kind:"quota",title:"Monthly limit reached",message:t.message||"You've used all your generations for this period.",detail:"",canRetry:!1,canEdit:!1,canUpgrade:!0};const e=t.message||"";return/timed out after/i.test(e)?{kind:"timeout",title:"Request timed out",message:"The generation service took too long to respond.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:/unreachable|failed to fetch|load failed|cors/i.test(e)?{kind:"network",title:"Connection problem",message:"We couldn't reach the generation service. Check your connection and try again.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:{kind:"generic",title:"Generation failed",message:e||"An unexpected error occurred.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1}}function my(t){const e={"Integration Audit Report":"📋","Critical Issues":"❌",Warnings:"⚠️",Recommendations:"✅","Overall Score":"📊"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📄"}function vy(t){const e={critical:"❌",warning:"⚠️",recommendation:"✅",score:"📊",issue:"🔍",fix:"🔧"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📝"}function _y(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 li(t){if(!t)return"";if(typeof t!="string")return String(t);const e=/```(?:\w+)?\n?([\s\S]*?)```/,n=t.match(e);return n?n[1].trim():t.trim()}function Hu(t){return t=Qt(t),t=t.replace(/\*\*(.*?)\*\*/g,'$1'),t=t.replace(/\*(.*?)\*/g,'$1'),t=t.replace(/`(.*?)`/g,'$1'),t=t.replace(/\b(FAIL|ERROR|CRITICAL)\b/g,'$1'),t=t.replace(/\b(WARN|WARNING)\b/g,'$1'),t=t.replace(/\b(PASS|SUCCESS|OK)\b/g,'$1'),t}function Eh(t,e="dart",n=globalThis.hljs){if(!t)return"";const i=li(t);try{return n.highlight(i,{language:e}).value}catch(r){console.warn("Syntax highlighting failed:",r);try{return n.highlight(i,{language:"json"}).value}catch{return Qt(i)}}}function Ls(t,e={}){const{highlighter:n=globalThis.hljs}=e;let i='
    ';const r=String(t??"").split(` -`);let s=!1,o="";for(const a of r){if(a.startsWith("```")){if(s){const l=_y(o),u=Eh(o.trim(),l,n);i+=`
    +`)}let l=null,u,c,d,h,f,p,g,m,v;function E(Y,W){if(!i)return null;const D=i.createShader(Y);return i.shaderSource(D,W),i.compileShader(D),i.getShaderParameter(D,i.COMPILE_STATUS)?D:(window.console&&console.warn("fx-grid shader: "+i.getShaderInfoLog(D)),null)}if(i){const Y=E(i.VERTEX_SHADER,o),W=E(i.FRAGMENT_SHADER,a());if(Y&&W&&(l=i.createProgram(),i.attachShader(l,Y),i.attachShader(l,W),i.linkProgram(l),i.getProgramParameter(l,i.LINK_STATUS)||(window.console&&console.warn("fx-grid link: "+i.getProgramInfoLog(l)),l=null)),l){i.useProgram(l),i.bindBuffer(i.ARRAY_BUFFER,i.createBuffer()),i.bufferData(i.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),i.STATIC_DRAW);const D=i.getAttribLocation(l,"p");i.enableVertexAttribArray(D),i.vertexAttribPointer(D,2,i.FLOAT,!1,0,0),u=i.getUniformLocation(l,"res"),c=i.getUniformLocation(l,"design"),d=i.getUniformLocation(l,"mouse"),h=i.getUniformLocation(l,"energy"),f=i.getUniformLocation(l,"parallax"),p=i.getUniformLocation(l,"t"),g=i.getUniformLocation(l,"ink"),m=i.getUniformLocation(l,"mark"),v=i.getUniformLocation(l,"rot"),i.enable(i.BLEND),i.blendFunc(i.ONE,i.ONE_MINUS_SRC_ALPHA),i.clearColor(0,0,0,0)}else{i=null;const D=t.cloneNode(!1);if(t.parentNode.replaceChild(D,t),t=D,r=t.getContext("2d"),!r)return null}}function S(Y){if(!Y)return null;const W=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(Y);if(W){let D=W[1];return D.length===3&&(D=D[0]+D[0]+D[1]+D[1]+D[2]+D[2]),[parseInt(D.slice(0,2),16)/255,parseInt(D.slice(2,4),16)/255,parseInt(D.slice(4,6),16)/255]}try{const D=document.createElement("canvas");D.width=1,D.height=1;const ue=D.getContext("2d");ue.fillStyle="rgb(9, 8, 7)";const xe=String(ue.fillStyle);ue.fillStyle=Y;const Fe=String(ue.fillStyle);if(Fe===xe)return null;const dt=/^#([0-9a-f]{6})$/i.exec(Fe);if(dt){const ft=dt[1];return[parseInt(ft.slice(0,2),16)/255,parseInt(ft.slice(2,4),16)/255,parseInt(ft.slice(4,6),16)/255]}const Nt=/rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i.exec(Fe);if(Nt)return[Number(Nt[1])/255,Number(Nt[2])/255,Number(Nt[3])/255]}catch{}return null}function _(){let Y="";try{const W=getComputedStyle(document.documentElement);Y=(W.getPropertyValue("--fx-ink")||"").trim()||(W.getPropertyValue("--fg")||"").trim()}catch{}return S(Y)||[.56,.68,.88]}const b=_();let k=1920,T=1080,x=960,F=540,$=960,O=540,L=.66,N=0,K=-1e9,V=!1,M=0,R=0,Z=null,Ce=!1,oe=!1,ye=!1;const $e=64,ae=15.2;let Ie=0,Se=0;const Be=.0032,wt=0,ge=.56,Ye=.26,bt=.32,mn=.16,Re=.349;let Pe=wt;function $t(){const Y=t.getBoundingClientRect(),W=t.clientWidth,D=t.clientHeight;if(!Y.width||!W||!D)return;const ue=Math.min(window.devicePixelRatio||1,2),xe=Math.max(.2,Math.min(2,Y.width/W*ue)),Fe=Math.max(2,Math.round(W*xe)),dt=Math.max(2,Math.round(D*xe));(Fe!==t.width||dt!==t.height)&&(t.width=Fe,t.height=dt,i&&i.viewport(0,0,Fe,dt)),k=W,T=D,V||(x=$=k/2,F=O=T/2,V=!0)}function Bn(Y){!l||!Ce||!i||(i.uniform2f(u,t.width,t.height),i.uniform2f(c,k,T),i.uniform2f(d,x,F),i.uniform1f(h,L),i.uniform1f(f,N),i.uniform2f(v,Math.cos(Pe),Math.sin(Pe)),i.uniform1f(p,Y),i.uniform3f(g,b[0],b[1],b[2]),i.clear(i.COLOR_BUFFER_BIT),i.drawArrays(i.TRIANGLES,0,3))}function qe(Y,W,D){const ue=Math.max(0,Math.min(1,(D-Y)/(W-Y)));return ue*ue*(3-2*ue)}function Dn(Y){if(!Z||!r)return;const W=r;W.setTransform(1,0,0,1,0,0),W.clearRect(0,0,t.width,t.height);const D=t.width/k;W.setTransform(D,0,0,D,0,0),W.globalAlpha=1;const ue=Math.min(k,T),xe=Math.max(64,Math.min(118,ue/10)),Fe=xe*2.9,dt=2*Fe*Fe,Nt=Math.sin(Y*.11)*7,ft=Math.cos(Y*.09)*7-N,dr=x+Nt,fr=F+ft,no=Fe*Math.sqrt(2*Math.log(1/.06)),mi=no+Be*no*no+xe,Ap=Math.floor((dr-mi)/xe)-1,Pp=Math.ceil((dr+mi)/xe)+1,Fp=Math.floor((fr-mi)/xe)-1,Rp=Math.ceil((fr+mi)/xe)+1;for(let io=Fp;io<=Rp;io++){const Tp=(io+.5)*xe;for(let ro=Ap;ro<=Pp;ro++){const so=(ro+.5)*xe-dr,oo=Tp-fr,ao=Math.sqrt(so*so+oo*oo)+1e-5;if(ao>mi)continue;const hr=(-1+Math.sqrt(1+4*Be*ao))/(2*Be),ac=Math.exp(-(hr*hr)/dt),lc=qe(.06,.8,ac)*L*.26;if(lc<.004)continue;const on=xe/(1+2*Be*hr)*.26*(.32+1.1*ac),cc=hr/ao,lo=dr+so*cc,co=fr+oo*cc;lo<-on*1.6||lo>k+on*1.6||co<-on*1.6||co>T+on*1.6||(W.globalAlpha=lc,W.save(),W.translate(lo,co),W.rotate(Pe),W.drawImage(Z,-on,-on,on*2,on*2),W.restore())}}W.globalAlpha=1}function Mt(Y){if(!oe)return;const W=R?Math.min(.05,(Y-R)/1e3):.016;R=Y;const ue=Y-K>2400?.6:1;L+=(ue-L)*Math.min(1,W*3.2);const xe=Math.min(.05,W);Ie+=(($-x)*$e-Ie*ae)*xe,Se+=((O-F)*$e-Se*ae)*xe,x+=Ie*xe,F+=Se*xe,N=(window.scrollY||window.pageYOffset||0)*.55;const Fe=Y/1e3,dt=x/(k||1)-.5,Nt=F/(T||1)-.5;let ft=dt*(dt>=0?ge:Ye)+Nt*(Nt>=0?bt:mn);ft>Re?ft=Re:ft<-Re&&(ft=-Re),Pe=wt+ft-N*6e-4,$t(),i?Bn(Fe):Dn(Fe),M=requestAnimationFrame(Mt)}function Lt(Y){if(!oe)return;const W=t.getBoundingClientRect();!W.width||!k||!T||($=(Y.clientX-W.left)/W.width*k,O=(Y.clientY-W.top)/W.height*T,K=performance.now())}function ut(){oe||to||e.matches||n.matches||!ye||document.hidden||(oe=!0,R=0,M=requestAnimationFrame(Mt))}function sn(){oe=!1,M&&(cancelAnimationFrame(M),M=0),R=0}function gi(){e.matches?(sn(),t.classList.remove("is-ready")):ye&&ut()}function jn(){n.matches?sn():ye&&ut()}function rc(){document.hidden?sn():ye&&ut()}const sc=new IntersectionObserver(Y=>{ye=Y[0]?.isIntersecting||!1,ye?ut():sn()},{threshold:0});sc.observe(t),window.addEventListener("pointermove",Lt,{passive:!0,capture:!0}),window.addEventListener("resize",$t),e.addEventListener("change",gi),n.addEventListener("change",jn),document.addEventListener("visibilitychange",rc);function Cp(){const Y=(s.match(/\sd="([^"]+)"/)||[])[1],W=document.createElement("canvas");W.width=256,W.height=256;const D=W.getContext("2d");if(Y&&window.Path2D){const ue=Math.min(8.533333333333333,8.421052631578947);D.setTransform(ue,0,0,ue,ue+(256-30*ue)/2,-6.4*ue),D.fillStyle="rgb(255,255,255)",D.fill(new Path2D(Y),"evenodd"),D.setTransform(1,0,0,1,0,0)}try{const ue=D.getImageData(0,0,256,256),xe=ue.data;for(let Fe=3;Feoe}}const ey=120;function ty(t,e,n){return tn?n:t}function de(t,e,n){return ty((t-e)/(n-e),0,1)}function ny(t){return t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2}function Uo(t){return 1-Math.pow(1-t,3)}function ze(t,e){return e=e===void 0?1.7:e,1+(e+1)*Math.pow(t-1,3)+e*Math.pow(t-1,2)}function Uu(t){return 1-Math.pow(2,-9*t)*Math.cos(t*15)}function te(t,e){if(t<=e[0].t)return e[0].v;for(let n=1;n8.2&&_<9.4&&(s*=1-.07*Math.sin(de(_,8.2,9.4)*Math.PI))}else if(t<53){const _=t-42;g=te(_,[{t:0,v:1},{t:2,v:0},{t:4.2,v:0},{t:4.6,v:1},{t:6.8,v:1},{t:7.4,v:0},{t:9.4,v:0},{t:10.6,v:1}]),p=te(_,[{t:0,v:1},{t:2,v:.3},{t:4.6,v:1,e:ze}]),d=te(_,[{t:0,v:0},{t:2,v:.3},{t:4.6,v:.16,e:ze},{t:10.6,v:0}]),f=te(_,[{t:0,v:0},{t:2,v:-40},{t:4.6,v:0,e:ze}]),o=te(_,[{t:0,v:0},{t:4.6,v:-.12},{t:10.6,v:0}])}else if(t<60){const _=t-53;c=te(_,[{t:0,v:1},{t:.35,v:0},{t:.45,v:0},{t:.7,v:1}]);const b=de(_,.45,2.2);a=b>0?-2.6*(1-Uu(b)):0,g=te(_,[{t:0,v:1},{t:.57,v:0},{t:.67,v:0},{t:.92,v:1}]);const k=de(_,.67,2.42);h=k>0?-2.6*(1-Uu(k)):0,s=1-.05*(Math.sin(de(_,1.9,2.5)*Math.PI)+Math.sin(de(_,2.5,3.1)*Math.PI))}else if(t<74){let b=function(F){return[te(F,[{t:0,v:0},{t:.25,v:1},{t:.5,v:1},{t:.72,v:.14},{t:.82,v:.14},{t:1,v:0}]),te(F,[{t:0,v:0},{t:.08,v:-.62},{t:.25,v:-.62},{t:.33,v:.62},{t:.7,v:.62},{t:.82,v:-.62},{t:1,v:-.62}])]};var S=b;const _=t-60,k=1-de(_,12,14),T=b(de(_,0,12)),x=b(de(_-.5,0,12));n=T[0]*k,i=(T[1]+.05*Math.sin(_*7))*k,o=(x[0]-T[0])*.6*k,a=(x[1]-T[1])*.6*k,f=(x[0]-T[0])*30*k,E=de(_,0,.4)*k}else if(t<85.4){const _=t-74,b=te(_,[{t:0,v:0},{t:4,v:1},{t:8,v:.24},{t:9.6,v:1,e:ze},{t:11.4,v:0}]);o=b*.5,d=-b*.5,l=te(_,[{t:0,v:0},{t:4,v:6},{t:8,v:20},{t:9.6,v:38,e:ze},{t:11.4,v:0}]),f=-l*.7,a=te(_,[{t:0,v:0},{t:8,v:0},{t:9.6,v:.4},{t:11.4,v:0}])}else if(t<96.4){const _=t-85.4,b=de(_,0,5.6),k=de(_,5.6,7.6),T=.72*Math.min(1,_/.6)*(1-k);d=Math.cos(b*Math.PI*2)*T,h=Math.sin(b*Math.PI*2)*T*.55,f=b*360*(1-k);const x=te(_,[{t:0,v:0},{t:7.6,v:0},{t:8.2,v:1,e:Uo},{t:8.6,v:.55},{t:9.4,v:0}]);o=-.16*x,d+=.16*x,l=-6*x,f+=6*x,s=1+.05*x,m=1+.9*x}else if(t<108.6){const _=t-96.4,b=de(_,9.6,12.2);n=te(_,[{t:0,v:0},{t:2.1,v:1},{t:4.8,v:.08},{t:7.5,v:1},{t:9.6,v:0}])*(1-b),i=-.35*Math.abs(Math.sin(de(_,0,9.6)*Math.PI*3))*(1-b);const k=Math.sin(_*6.2)*(1-b);u=1+.12*k,p=1-.12*k,l=k*8,f=-k*8,o=.06*k,d=-.06*k,E=de(_,0,.4)*(1-b)}else{const _=t-108.6,b=Math.sin(de(_,0,8)*Math.PI),k=1-de(_,8,11.4);s=1+.04*b*k,i=-.1*b*k,r=2*b*k,m=1+.5*Math.sin(de(_,0,6)*Math.PI),v=1+.1*Math.sin(de(_,0,6)*Math.PI)}return e.x=n,e.y=i,e.rot=r,e.scale=s,e.ax=o,e.ay=a,e.ar=l,e.asc=u,e.afade=c,e.bx=d,e.by=h,e.br=f,e.bsc=p,e.bfade=g,e.hfade=m,e.hsc=v,e.shd=E,e}function iy(t={}){const e=t.arena||document.querySelector(".pipeline-glyph.logo-loop");if(!e)return null;const n=e.querySelector(".loop-mark"),i=e.querySelector(".loop-piece-a"),r=e.querySelector(".loop-piece-b"),s=e.querySelector(".loop-halo"),o=e.querySelector(".loop-shadow");if(!n||!i||!r||!s||!o)return null;const a=t.reducedMotion||window.matchMedia("(prefers-reduced-motion: reduce)"),l=ey;let u=34,c=0,d=0;function h(){u=n.offsetWidth||34,c=Math.max(0,e.offsetWidth-u-4),d=Math.max(0,(e.offsetHeight-u)/2-2),e.style.setProperty("--mark-c",u/2+"px")}function f(M){const R=Math.min(1,Math.max(0,M.x))*c,Z=M.y*d;n.style.transform="translate3d("+R.toFixed(2)+"px,"+Z.toFixed(2)+"px,0) rotate("+M.rot.toFixed(2)+"deg) scale("+M.scale.toFixed(3)+")",i.style.transform="translate3d("+(M.ax*u).toFixed(2)+"px,"+(M.ay*u).toFixed(2)+"px,0) rotate("+M.ar.toFixed(2)+"deg) scale("+M.asc.toFixed(3)+")",i.style.opacity=M.afade.toFixed(3),r.style.transform="translate3d("+(M.bx*u).toFixed(2)+"px,"+(M.by*u).toFixed(2)+"px,0) rotate("+M.br.toFixed(2)+"deg) scale("+M.bsc.toFixed(3)+")",r.style.opacity=M.bfade.toFixed(3),s.style.transform="scale("+M.hsc.toFixed(3)+")",s.style.opacity=(.09*M.hfade).toFixed(3),o.style.transform="translateX("+R.toFixed(2)+"px) scaleX("+(.75+.4*Math.abs(M.x)).toFixed(3)+")",o.style.opacity=(M.shd*.5).toFixed(3)}let p=0,g=0,m=0,v=!1,E=!1,S=!1,_=0;function b(){return S||a.matches||document.hidden||!e.offsetParent?!1:E}function k(M){if(!v)return;if(m=requestAnimationFrame(k),!b()){x();return}const R=g?(M-g)/1e3:0;g=M,p=(p+Math.min(R,.1))%l,_+=1,f(Ai(p))}function T(){v||S||b()&&(v=!0,g=0,m=requestAnimationFrame(k))}function x(){v=!1,m&&(cancelAnimationFrame(m),m=0),g=0}function F(){b()?T():x()}function $(){a.matches?(x(),f(Ai(0))):F()}function O(){h(),v&&f(Ai(p))}function L(){g=0,F()}const N=new IntersectionObserver(M=>{E=M[0]?M[0].isIntersecting:!1,F()},{threshold:0});N.observe(e),window.addEventListener("resize",O),a.addEventListener("change",$),document.addEventListener("visibilitychange",L);function K(){S||(S=!0,x(),N.disconnect(),window.removeEventListener("resize",O),a.removeEventListener("change",$),document.removeEventListener("visibilitychange",L))}window.addEventListener("pagehide",K);function V(M){p=(M%l+l)%l,f(Ai(p))}return h(),f(Ai(0)),F(),{isRunning:()=>v,currentTime:()=>p,frameCount:()=>_,seek:V,dispose:K}}const ry=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function Xt(t){const e=String(t||"").trim().match(ry);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function sy(t,e){if(t.length===0&&e.length===0)return 0;if(t.length===0)return 1;if(e.length===0)return-1;for(let n=0;n0)}function ay(t){const e=Xt(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function Il(t){let e=String(t??"").trim();if((e.startsWith("'")||e.startsWith('"'))&&(e=e.slice(1,-1).trim()),e===""||e==="any"||e==="*")return{min:null,minInclusive:!1,max:null,maxInclusive:!1};if(e.startsWith("^")){const o=e.slice(1).trim();return Xt(o)?{min:o,minInclusive:!0,max:ay(o),maxInclusive:!1}:null}if(Xt(e))return{min:e,minInclusive:!0,max:e,maxInclusive:!0};const n={min:null,minInclusive:!1,max:null,maxInclusive:!1},i=/(>=|<=|>|<)\s*([0-9][0-9A-Za-z.+-]*)/g;let r=!1,s;for(;(s=i.exec(e))!==null;){const[,o,a]=s;if(!Xt(a))return null;r=!0,o===">="||o===">"?(n.min=a,n.minInclusive=o===">="):(n.max=a,n.maxInclusive=o==="<=")}return r?n:null}function Hu(t,e){const n=Il(t);if(!n||!Xt(e))return!1;if(n.min!==null){const i=fs(e,n.min);if(i<0||i===0&&!n.minInclusive)return!1}if(n.max!==null){const i=fs(e,n.max);if(i>0||i===0&&!n.maxInclusive)return!1}return!0}function ly(t,e){const n=Il(t);if(!n||!Xt(e))return!1;if(n.max===null)return!0;const i=fs(n.max,e);return i>0?!0:i===0&&n.maxInclusive}function zn(t){const e=Il(t);return e?e.min:null}const cy="https://pub.dev/api/packages/",uy=8e3;function dy(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null}=e,r=Array.isArray(t?.versions)?t.versions:[];let s=null;for(const o of r){const a=o?.version;if(!a||o.retracted||oy(a))continue;const l=o.pubspec?.environment||{};n&&l.sdk&&!Hu(l.sdk,n)||i&&l.flutter&&!Hu(l.flutter,i)||(!s||fs(a,s)>0)&&(s=a)}return s?{version:s,constraint:`^${s}`}:null}async function fy(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null,fetchImpl:r=fetch}=e;let s;try{const a=await r(`${cy}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(uy)});if(!a.ok)return{name:t,constraint:null,version:null,error:a.status===404?`"${t}" was not found on pub.dev`:`pub.dev returned ${a.status} for "${t}"`};s=await a.json()}catch(a){return{name:t,constraint:null,version:null,error:`could not reach pub.dev for "${t}" (${a.message})`}}const o=dy(s,{dartSdkFloor:n,flutterSdkFloor:i});return o?{name:t,...o,error:null}:{name:t,constraint:null,version:null,error:n?`no published "${t}" release supports Dart ${n}`:`no published "${t}" release could be read`}}async function hy(t,e={}){const n=await Promise.all(t.map(i=>fy(i,e)));return new Map(n.map(({name:i,...r})=>[i,r]))}async function py(t,e={},n={}){const{resolveVersions:i=hy}=n,r=Object.entries(e).filter(([c])=>c&&c!=="flutter"),s=gh(t),o={dartSdkFloor:zn(s.sdk),flutterSdkFloor:zn(s.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(r.length===0)return a;const l=$s(t),u=[];for(const[c,d]of r){const h=l.get(c);if(!h){u.push(c);continue}const f=zn(d);if(!f){a.kept.push({name:c,constraint:h.constraint});continue}if(!h.isScalar){a.warnings.push(`"${c}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${f}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:c,constraint:h.constraint});continue}if(ly(h.constraint,f)){a.kept.push({name:c,constraint:h.constraint});continue}a.overrides[c]=`^${f}`,a.warnings.push(`"${c}" was pinned to ${h.constraint} in your project, which cannot resolve the ${f} the generated code needs. Raising it to ^${f} — this changes a dependency the rest of your app also uses.`)}if(u.length>0){const c=await i(u,o);for(const d of u){const h=c.get(d);if(h?.constraint){a.additions[d]=h.constraint;continue}const f=e[d]||"";if(zn(f)){a.additions[d]=`^${zn(f)}`,a.warnings.push(`Could not confirm "${d}" version on pub.dev (${h?.error||"lookup failed"}). Using ^${zn(f)} from the AI's recommendation — verify this is current.`);continue}a.additions[d]=">=0.0.0",a.warnings.push(`Could not determine a version for "${d}" (${h?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const gy={"&":"&","<":"<",">":">",'"':""","'":"'"};function Qt(t){return String(t??"").replace(/[&<>"']/g,e=>gy[e])}function q(t){return t?Qt(t).replace(/\n/g,"
    "):""}function Jt(t){return Qt(t).replace(/\r?\n/g," ")}function Ms(t,e={}){const n=t?.pipelineStep;if(n!=null&&e[n]!=null)return e[n];const i=t?.message||"";return i.includes("Code Generator")?2:i.includes("Code Review")?3:1}function Eh(t){if(!t)return{kind:"generic",title:"Generation failed",message:"An unknown error occurred. Please try again.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1};if(t.isModelArmor){const n=t.code==="MODEL_ARMOR_BLOCKED";return{kind:"safety",title:t.userTitle||"Request blocked for safety",message:t.userMessage||t.message,detail:t.retryExplanation||"",canRetry:!n,canEdit:!0,canUpgrade:!1}}if(t.isUsageLimit)return{kind:"quota",title:"Monthly limit reached",message:t.message||"You've used all your generations for this period.",detail:"",canRetry:!1,canEdit:!1,canUpgrade:!0};const e=t.message||"";return/timed out after/i.test(e)?{kind:"timeout",title:"Request timed out",message:"The generation service took too long to respond.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:/unreachable|failed to fetch|load failed|cors/i.test(e)?{kind:"network",title:"Connection problem",message:"We couldn't reach the generation service. Check your connection and try again.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:{kind:"generic",title:"Generation failed",message:e||"An unexpected error occurred.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1}}function my(t){const e={"Integration Audit Report":"📋","Critical Issues":"❌",Warnings:"⚠️",Recommendations:"✅","Overall Score":"📊"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📄"}function vy(t){const e={critical:"❌",warning:"⚠️",recommendation:"✅",score:"📊",issue:"🔍",fix:"🔧"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📝"}function _y(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 li(t){if(!t)return"";if(typeof t!="string")return String(t);const e=/```(?:\w+)?\n?([\s\S]*?)```/,n=t.match(e);return n?n[1].trim():t.trim()}function Wu(t){return t=Qt(t),t=t.replace(/\*\*(.*?)\*\*/g,'$1'),t=t.replace(/\*(.*?)\*/g,'$1'),t=t.replace(/`(.*?)`/g,'$1'),t=t.replace(/\b(FAIL|ERROR|CRITICAL)\b/g,'$1'),t=t.replace(/\b(WARN|WARNING)\b/g,'$1'),t=t.replace(/\b(PASS|SUCCESS|OK)\b/g,'$1'),t}function Sh(t,e="dart",n=globalThis.hljs){if(!t)return"";const i=li(t);try{return n.highlight(i,{language:e}).value}catch(r){console.warn("Syntax highlighting failed:",r);try{return n.highlight(i,{language:"json"}).value}catch{return Qt(i)}}}function Ls(t,e={}){const{highlighter:n=globalThis.hljs}=e;let i='
    ';const r=String(t??"").split(` +`);let s=!1,o="";for(const a of r){if(a.startsWith("```")){if(s){const l=_y(o),u=Sh(o.trim(),l,n);i+=`
    ${u}
    `,o="",s=!1}else s=!0;continue}if(s){o+=a+` `;continue}if(a.startsWith("# ")){const l=a.substring(2).trim();i+=`
    @@ -69,8 +69,8 @@ in vec2 p; void main(){ gl_Position = vec4(p, 0.0, 1.0); }`;function a(){return[
    `;continue}if(/^[-*+]\s+/.test(a)||/^\d+\.\s+/.test(a)){const l=a.replace(/^([-*+]|\d+\.)\s+/,"").trim();i+=`
    • - ${Hu(l)} -
    `;continue}a.trim()!==""&&(i+=`

    ${Hu(a)}

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

    ${Wu(a)}

    `)}return i+="
    ",`
    @@ -78,14 +78,14 @@ in vec2 p; void main(){ gl_Position = vec4(p, 0.0, 1.0); }`;function a(){return[
    ${i}
    - `}const yy=[[/gradient stroke\s*$/i," and an animated percentage label"],[/gauge\s*$/i," with a gradient stroke and animated fill"],[/rating\s*(bar|widget)?\s*$/i," with half-star support and haptic feedback"],[/list\s*$/i," with swipe-to-delete and an undo snackbar"],[/pad\s*$/i," that exports a transparent PNG"],[/carousel\s*$/i," with parallax cards and page indicators"],[/(button|cta)\s*$/i," with a loading spinner and success state"],[/(chart|graph)\s*$/i," that animates from a Firestore stream"],[/action\s*(that|to)?\s*$/i," uploads an image to Firebase Storage and returns the URL"],[/timer\s*$/i," with pause, resume and a completion callback"],[/map\s*$/i," with clustered markers and a custom info window"],[/^a\s+\w*$/i," widget that"],[/(picker|selector)\s*$/i," with search and multi-select"]],wy=220,by=6;function Wu(t,e){return!!(t&&t.trim())&&!e}function Ey(t,e=""){if(typeof t!="string"||!t||t===e||t.trim().lengthi.test(t));return n?n[1]:null}function Sy(){let t="",e="";return{get active(){return t},resolve(n){return t=Ey(n,e)??"",t},dismiss(){t=""},accept(n){if(!t)return null;const i=n+t;return e=i,t="",i}}}function xy({onSubmit:t}){const e=document.getElementById("composer"),n=document.getElementById("pipeline-input"),i=document.getElementById("hero-send");if(!e||!n||!i||typeof t!="function")return;const r=e.querySelector(".ghost .typed"),s=e.querySelector(".ghost .suggest"),o=document.getElementById("tab-hint"),a=document.getElementById("suggest-status"),l=Array.from(document.querySelectorAll("#example-chips .chip")),u=document.getElementById("btn-add-images"),c=document.getElementById("prompt-image-input"),d=window.matchMedia("(prefers-reduced-motion: reduce)"),f=Sy();let h=!1,p=!1,g=!1,m=!1,v=null,E=null;function S(){i.disabled=!Wu(n.value,p||g||m)}function _(){r&&(r.textContent=n.value)}function b(){s&&(s.textContent=""),_(),e.classList.remove("has-suggest"),o&&(o.hidden=!0,o.tabIndex=-1),a&&(a.textContent="")}function k(R){s&&(s.textContent=R),_(),e.classList.add("has-suggest"),o&&(o.hidden=!1,o.tabIndex=0,o.setAttribute("aria-label","Accept suggestion: "+R.trim())),a&&(a.textContent="Suggestion: "+R+". Press Tab to accept.")}function T(){f.dismiss(),b()}function x(){if(h||p)return;const R=f.resolve(n.value);R&&k(R)}function F(){clearTimeout(v),!h&&(v=setTimeout(x,wy))}function $(){const R=f.accept(n.value);return R===null?!1:(n.value=R,b(),S(),!0)}function O(R){p=R,e.classList.toggle("is-busy",R),i.classList.toggle("is-busy",R),i.setAttribute("aria-label",R?"Generating":"Generate"),n.readOnly=R,l.forEach(Z=>{Z.disabled=R}),u&&(u.disabled=R),c&&(c.disabled=R),S()}async function L(){if(Wu(n.value,p||g||m)){T(),O(!0);try{await t()}finally{O(!1)}}}function N(){g=!1,E&&(clearInterval(E),E=null),e.classList.remove("is-demo-typing"),S()}function K(){l.forEach(R=>{R.classList.remove("is-active"),R.setAttribute("aria-pressed","false")})}function V(){try{n.focus({preventScroll:!0}),n.setSelectionRange(n.value.length,n.value.length)}catch{}}function M(R){const Z=R.dataset.prompt||"";if(N(),clearTimeout(v),v=null,T(),l.forEach(oe=>{const ye=oe===R;oe.classList.toggle("is-active",ye),oe.setAttribute("aria-pressed",String(ye))}),d.matches||!Z){n.value=Z,_(),S(),V();return}n.value="",_(),g=!0,S(),e.classList.add("is-demo-typing");let Ce=0;E=setInterval(()=>{Ce+=1,n.value=Z.slice(0,Ce),_(),Ce>=Z.length?(N(),V()):S()},22)}return l.forEach(R=>{R.setAttribute("aria-pressed","false"),R.addEventListener("click",()=>M(R))}),n.addEventListener("keydown",R=>{if(g&&R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!h){R.preventDefault();return}N(),R.key==="Tab"&&!R.shiftKey&&f.active?(R.preventDefault(),$()):R.key==="Escape"?(clearTimeout(v),v=null,T()):R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!h&&(R.preventDefault(),L())}),n.addEventListener("input",()=>{N(),K(),T(),S(),F()}),n.addEventListener("compositionstart",()=>{h=!0}),n.addEventListener("compositionend",()=>{h=!1,T(),S(),F()}),n.addEventListener("scroll",()=>{r&&r.parentNode&&(r.parentNode.scrollTop=n.scrollTop)}),o&&o.addEventListener("click",()=>{$(),n.focus({preventScroll:!0})}),i.addEventListener("click",L),n.addEventListener("pointerdown",()=>{N(),K()}),_(),S(),{setAttachmentsPending(R){m=!!R,S()}}}const Iy="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses";const _t="https://4tgke4.buildship.run",Sh={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},hs="ccc_auth_session",Na="ccc_signin_return",ky=1800*1e3,qu=new WeakSet;let z={email:null,sessionToken:null,isVerified:!1};function Mn(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let ce=Mn({isResolved:!0}),Oa=Promise.resolve();const Cy=`${_t}/service/runpipeline`,Ay="bs_user_id",Py="bs_identity_token",Fy=`${_t}/authUserCheck`;let ht={userId:null,token:null,status:null,resolved:!1};const ps=av,gs="ccc_subscription",zu=3,Ry=new Set(["active","trialing","paid"]),ms="google/gemini-3.7-flash",Nr=["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"],Ty={"google/gemini-3.7-flash":"Gemini 3.7 Flash","anthropic/claude-opus-5":"Claude Opus 5","openai/gpt-5.6-sol":"GPT-5.6 Sol","z-ai/glm-5.2":"GLM 5.2","moonshotai/kimi-k3":"Kimi K3","openrouter/auto-beta":"OpenRouter: Auto Router","openrouter/free":"OpenRouter: Free Models","openrouter/deepseek/deepseek-v4-pro":"DeepSeek v4 Pro"};function Gt(t){return Ty[t]||t}const $y=new Set(["google/gemini-3.7-flash","anthropic/claude-opus-5","openai/gpt-5.6-sol","z-ai/glm-5.2","moonshotai/kimi-k3","openrouter/auto-beta"]);function xh(t){return $y.has(t)}const Ba=4,Ho=8*1024*1024,My="https://4tgke4.buildship.run/service/runpipeline-image";let Ne=[];const pn=[],Ly=3e4;let Ih=null;function Ny(t){return new Promise(e=>{const n=new FileReader;n.onload=()=>e(n.result),n.onerror=()=>e(null),n.readAsDataURL(t)})}async function Oy(t,e){const n=new FormData;return n.append("file",t),(await fetch(My,{method:"POST",body:n,signal:e})).json()}function By(t){if(Array.isArray(t)){const e=t[0];if(e&&typeof e=="object")for(const n of Object.keys(e)){if(n==="item"||n==="index")continue;const i=e[n];if(i&&typeof i=="object"){if(typeof i.file=="string")return i.file;if(typeof i.url=="string")return i.url}if(typeof i=="string")return i}return""}return typeof t=="string"?t:t&&typeof t=="object"&&(t.url||t.fileUrl||t.file_url||t.downloadUrl||t.imageUrl||t.image_url||t.file)||""}async function Dy(t,e,n){const i=await Ny(t);i&&Ne.includes(e)&&(e.dataUrl=i,cn());let r="";if(i)try{r=By(await Oy(t,n))}catch{r=""}return Ne.includes(e)?!i||!r?(Ne.splice(Ne.indexOf(e),1),cn(),"failed"):(e.url=r,cn(),"added"):"dropped"}function kh(t){const e=pn.indexOf(t);e>=0&&pn.splice(e,1),Ah()}function Ch(t){t.controller.abort(),kh(t);const e=Ne.indexOf(t.slot);e>=0&&(Ne.splice(e,1),cn())}function Ah(){Ih?.setAttachmentsPending(pn.length>0)}async function jy(t){const e=Array.from(t.target.files||[]);if(!e.length)return;if(t.target.value="",y.isRunning){Ee("Wait for the current generation to finish before attaching images.","info");return}const n=e.filter(u=>u.size>Ho);n.length&&Ee(`Skipped ${n.length} image(s) over the ${(Ho/1024/1024).toFixed(0)} MB limit.`,"warning");const i=e.filter(u=>u.size<=Ho);if(!i.length)return;const r=Ba-Ne.length,s=i.slice(0,r);if(i.length>r&&Ee(`You can attach up to ${Ba} images.`,"info"),!s.length)return;const o=s.map(u=>{const c={dataUrl:null,name:u.name,url:null};Ne.push(c);const d={slot:c,controller:new AbortController},f=setTimeout(()=>d.controller.abort(),Ly);return d.job=Dy(u,c,d.controller.signal),pn.push(d),d.job.finally(()=>{clearTimeout(f),kh(d)}),d.job});cn(),Ah();const l=(await Promise.all(o)).filter(u=>u==="failed").length;l&&Ee(`${l} image(s) could not be uploaded and were not attached.`,"error")}function Uy(t){const e=Ne[t],n=pn.find(i=>i.slot===e);if(n){Ch(n);return}Ne.splice(t,1),cn()}function cn(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",Ne.forEach((n,i)=>{const r=document.createElement("div");r.className="prompt-img-thumb"+(n.url?"":" is-pending"),r.innerHTML=(n.dataUrl?`Prompt image`:"")+``,t.appendChild(r)}),e&&(e.textContent=Ne.length>=Ba?"Image limit reached":"Add images"))}function kl(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),n=xh(e?.value);t.classList.toggle("hidden",!n),!n&&Ne.length&&(pn.slice().forEach(Ch),Ne=[],cn())}const Fn="ccc_usage",Ph="google/gemini-3.7-flash",Fh="google/gemini-3.7-flash",kr="google/gemini-3.7-flash",Ni={professional:11,power:49},Da={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"},Or={AUD:1,USD:.65,EUR:.6,GBP:.52,CAD:.88,NZD:1.08,JPY:97,KRW:870,INR:54,SGD:.87,HKD:5.08,BRL:3.18,CNY:4.7,TWD:20.5,THB:22.5,VND:16200,IDR:10200,MYR:2.88,SEK:6.8,NOK:6.95,DKK:4.48,PLN:2.6,CZK:15.2,HUF:238,RON:2.98,TRY:20.9,AED:2.39,ILS:2.38,PHP:36.4,ZAR:11.8,RUB:58,UAH:26.8,CHF:.57,MXN:11.1,ARS:580,CLP:610,COP:2700,PEN:2.44};let Br={...Or};async function Hy(){const t=new AbortController,e=setTimeout(()=>t.abort(),5e3);try{const n=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:t.signal});if(!n.ok)return;const i=await n.json();if(i.result!=="success"||!i.rates)return;const r=i.rates,s={AUD:1},o=new Set([...Object.keys(Or),...Object.values(ja),...Object.values(Da)]);for(const a of o)a!=="AUD"&&(typeof r[a]=="number"&&r[a]>0?s[a]=r[a]:Or[a]&&(s[a]=Or[a]));Br=s}catch{}finally{clearTimeout(e)}}const ja={"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 Cl(){try{const s=Intl.DateTimeFormat().resolvedOptions().timeZone;if(s&&ja[s])return ja[s]}catch{}const e=(navigator.language||"en-US").replace("-","_"),n=Da[e];if(n)return n;const i=e.split("_")[0],r=Da[i];return r||"USD"}function Oi(t,e){const n=Br[e]??Br.USD,i=t*n,r=Math.round(i*100)/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:r>=100||r%1===0?0:2}).format(r)}catch{return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(t*Br.USD)}}const gt="ccc_api_key_",Pt="ccc_session_api_key_",Rt="ccc_encryption_key",tr="ccc_encryption_key_scope",Wy="ccc_keystore",vs="keys",nr="ccc_encryption_key_version";let Ua=null,_s=null,ir=!1,ys=!1,Vu=!1;class ws extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function Gu(){if(Vu)return;Vu=!0;const t="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(t),document.body&&Ee(t,"warning")}function Rh(){return localStorage.getItem(nr)||""}function Ha(){return crypto.randomUUID?.()||$h(crypto.getRandomValues(new Uint8Array(16)))}function qy(){const t=Rh();if(t)return t;const e=Ha();return localStorage.setItem(nr,e),e}function ci(){Ua=null,_s=null,ir=!1,ys=!1}window.addEventListener("storage",t=>{t.key===nr&&ci()});function zy(){return new Promise((t,e)=>{const n=indexedDB.open(Wy,1);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(vs)||i.createObjectStore(vs)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function Al(t,e){const n=await zy();return new Promise((i,r)=>{const s=n.transaction(vs,t);let o;try{o=e(s.objectStore(vs))}catch(l){n.close(),r(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>r(o.error),s.oncomplete=()=>{n.close(),i(a)},s.onerror=()=>{n.close(),r(s.error||new Error("Encryption key transaction failed."))},s.onabort=()=>{n.close(),r(s.error||new Error("Encryption key transaction aborted."))}})}function Vy(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function Gy(){const t=await Al("readonly",e=>e.get(Rt));return Vy(t)?t:null}async function Th(t){await Al("readwrite",e=>e.put(t,Rt))}async function Ky(){ci();try{await Al("readwrite",t=>t.delete(Rt))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function Yy(){const t=sessionStorage.getItem(Rt);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Th(e),sessionStorage.removeItem(Rt),sessionStorage.removeItem(tr),localStorage.removeItem(gt+"salt"),e}async function Ku(t){const e=sessionStorage.getItem(Rt);if(e)return ys=sessionStorage.getItem(tr)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new ws;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),i=await crypto.subtle.exportKey("jwk",n);return sessionStorage.setItem(Rt,JSON.stringify(i)),sessionStorage.setItem(tr,"session"),ys=!1,crypto.subtle.importKey("jwk",i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function Jy(t){if(sessionStorage.getItem(tr)==="session"&&sessionStorage.getItem(Rt))return Gu(),ir=!0,Ku(t);try{const e=await Gy();if(e)return e;const n=await Yy();if(n)return n;const i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Th(i),i}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),Gu(),ir=!0,Ku(t)}}async function Pl(t={}){const{allowSessionFallbackCreation:e=!0}=t,n=qy();_s!==n&&ci();const i=Ua||Jy(e);Ua=i,_s=n;try{return await i}catch(r){throw ci(),r}}async function Zy(t){const e=await Pl(),n=_s,i=new TextEncoder,r=crypto.getRandomValues(new Uint8Array(12)),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},e,i.encode(t)),o=new Uint8Array(r.length+s.byteLength);return o.set(r),o.set(new Uint8Array(s),r.length),{ciphertext:$h(o),keyVersion:n,sessionFallback:ir}}async function Xy(t,e={}){const{isSessionCredential:n=!1}=e;try{const i=await Pl({allowSessionFallbackCreation:!1});if(ir&&!n&&!ys)throw new ws;const r=Qy(t),s=r.slice(0,12),o=r.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},i,o);return new TextDecoder().decode(a)}catch(i){if(i instanceof ws)throw i;return console.error("Decryption failed:",i),null}}function $h(t){const e=new Uint8Array(t);let n="";for(let i=0;i0}let Ln="",ui="",qi=null,Ju=0,tt="not-configured";async function Fl(){sessionStorage.getItem(Rt)&&await Pl(),Ln=await Te("flutterflow"),ui=await Te("flutterflow_project_id"),a0(),rn(),Ln?Ml():(tt="not-configured",vt())}let rr=!1;function Mh(){const t=document.getElementById("api-keys-modal");He(t),$l(),Ln&&Ll(Ln)}function Rl(){rr=!1,Mh()}function t0(){rr=!0;const t=document.getElementById("walkthrough-modal");t&&We(t),Mh()}let Zu=!1;function Xu(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-settings-model");if(!t||!e)return;e.value=t.value;const n=Array.from(t.options);Array.from(e.options).forEach((r,s)=>{const o=n[s];o&&(r.textContent=o.textContent)});const i=document.getElementById("composer-settings-free-notice");i&&(document.getElementById("model-selector-free-notice")?(i.hidden=!1,i.innerHTML='Free plan — Gemini only. '):i.hidden=!0)}function Qu(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-image-capability"),n=document.getElementById("composer-image-capability-note");if(!t)return;const i=Gt(t.value),r=xh(t.value);e&&(e.textContent=r?"Supported":"Not supported"),n&&(n.textContent=r?`${i} accepts reference images you attach to the prompt.`:`Images can't be attached with ${i}. Attached images are removed when you switch to it.`),kl()}function n0(){if(rr=!1,Xu(),Qu(),!Zu){const e=document.getElementById("composer-settings-model");e&&e.addEventListener("change",()=>{const n=document.getElementById("code-generator-model");n.value=e.value,n.dispatchEvent(new Event("change")),Xu(),Qu()}),Zu=!0}const t=document.querySelector('.composer [aria-label="Generation settings"]');He("composer-settings-modal",{trigger:t})}function i0(t){t&&t.target!==t.currentTarget||We("composer-settings-modal")}function Lh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&We(e);const n=rr;if(rr=!1,n){const i=document.getElementById("walkthrough-modal");i&&(tt==="connected"&&Tl(),He(i))}}let en=1;function Nh(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function Ns(){const t=Nh();t.length&&t.forEach((e,n)=>{const i=n+1;e.classList.remove("wt-current","wt-done","wt-pending");const r=e.querySelector(".wt-step-num");i===en?(e.classList.add("wt-current"),r&&(r.textContent=i)):i0&&en<=t&&(en++,Ns())}function r0(){const t=document.getElementById("walkthrough-modal");t&&(en=1,Ns(),He(t))}function s0(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&We(e);const n=document.getElementById("walkthrough-dont-show");n&&n.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function Oh(){if(z.isVerified&&Tt()&&ce.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(en=1,Ns(),He(e))}}async function $l(){const t=document.getElementById("flutterflow-api-key-input");Ln?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",o0()}function o0(){ed("flutterflow","flutterflow-key-status"),ed("flutterflow_project_id","flutterflow-project-status")}function ed(t,e){const n=document.getElementById(e);if(!n)return;const i=n.querySelector(".key-status-dot"),r=n.querySelector("span");Ct(t)?(i.className="key-status-dot configured",r.className="text-green-600",r.textContent="User key configured"):(i.className="key-status-dot missing",r.className="text-gray-500",r.textContent="Not configured")}function rn(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff");e&&e.classList.toggle("hidden",!t)}function a0(){const t=document.getElementById("api-keys-status");if(!t)return;const e=t.querySelectorAll(".key-status-dot"),n=["flutterflow"];e.forEach((i,r)=>{const s=n[r];s==="flutterflow"?Ct("flutterflow")&&Ct("flutterflow_project_id")?(i.className="key-status-dot configured",i.title="FlutterFlow (Fully configured)"):Ct("flutterflow")||Ct("flutterflow_project_id")?(i.className="key-status-dot env",i.title="FlutterFlow (Partially configured)"):(i.className="key-status-dot missing",i.title="FlutterFlow (Not configured)"):Ct(s)?(i.className="key-status-dot configured",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (User key)"):(i.className="key-status-dot missing",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (Not configured)")}),rn()}async function l0(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select"),n=t.value.trim();n&&await Yu("flutterflow",n);const i=e?.value.trim()||"";if(i){if(!Os(i)){Ee("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await Yu("flutterflow_project_id",i)}await Fl(),n&&await Ml(),$l();const r=document.querySelector("#api-keys-modal .bg-blue-500"),s=r.textContent;r.textContent="Saved!",r.classList.remove("bg-blue-500","hover:bg-blue-600"),r.classList.add("bg-green-500"),setTimeout(()=>{r.textContent=s,r.classList.remove("bg-green-500"),r.classList.add("bg-blue-500","hover:bg-blue-600"),Lh()},1e3)}async function c0(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(nr,Ha()),ci(),localStorage.removeItem(gt+"flutterflow"),localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow"),sessionStorage.removeItem(Pt+"flutterflow_project_id"),sessionStorage.removeItem(Rt),sessionStorage.removeItem(tr),localStorage.removeItem(gt+"salt"),await Ky(),localStorage.setItem(nr,Ha()),localStorage.removeItem(gt+"flutterflow"),localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow"),sessionStorage.removeItem(Pt+"flutterflow_project_id"),await Fl();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),$l()}function Os(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function vt(){const t=document.getElementById("acct-ff-dot"),e=document.getElementById("acct-ff-status"),n=document.getElementById("acct-ff-endpoint"),i=document.getElementById("acct-ff-project");if(n){const o=yt();n.textContent=o.includes("staging")?"Staging":"Production"}if(i&&(i.textContent=ui||"—"),!e)return;let r,s;if(!Ct("flutterflow"))r="Not connected — add your FlutterFlow API key",s="";else switch(tt){case"connected":r="Connected to FlutterFlow",s="ok";break;case"no-projects":r="Key accepted — no projects found",s="warn";break;case"unauthorized":r="API key rejected (401/403) — re-enter your key",s="bad";break;case"network-error":r="Could not reach FlutterFlow — check your network",s="bad";break;default:r="Checking connection…",s="warn";break}e.textContent=r,t&&(t.className=`acct-dot${s?" "+s:""}`)}async function Ml(){const t=await Te("flutterflow");if(!t||!Ct("flutterflow"))return tt="not-configured",vt(),null;tt="validating",vt();try{const n=await new hi(t,"","main",yt()).listProjects();return tt=n&&n.length>0?"connected":"no-projects",vt(),n}catch(e){const n=String(e&&e.message||"");return tt=/(401|403)|denied|unauthorized|scoped|list permission/i.test(n)?"unauthorized":"network-error",vt(),null}}function u0(){ui="",localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow_project_id")}function d0(){u0();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML='',t.value=""),Ct("flutterflow")?(tt="validating",Ll(Ln)):tt="not-configured",vt()}function f0(t,e){const n=document.getElementById(t);n&&(n.value?e?n.style.borderColor="#22c55e":n.style.borderColor="#ef4444":n.style.borderColor="")}function h0(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const n=e.target.value.trim().length>0;f0("flutterflow-api-key-input",n)}),t.addEventListener("blur",p0(async e=>{const n=e.target.value.trim();n&&await Ll(n)},500)))}function p0(t,e){let n;return function(...r){const s=()=>{clearTimeout(n),t(...r)};clearTimeout(n),n=setTimeout(s,e)}}async function Ll(t){const e=document.getElementById("flutterflow-projects-select"),n=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',n&&n.classList.add("hidden"),(Ct("flutterflow")||t)&&(tt="validating"),vt();try{const r=await new hi(t,"","main",yt()).listProjects();if(!r||r.length===0){tt="no-projects",vt(),e.innerHTML='';return}tt="connected",vt(),e.innerHTML='',r.forEach(s=>{const o=document.createElement("option");o.value=s.id||s.projectId||"",o.textContent=s.name||s.projectName||`Project ${s.id}`,e.appendChild(o)}),ui&&(e.value=ui)}catch(i){console.error("Failed to fetch projects:",i);const r=String(i&&i.message||"");tt=/(401|403)|denied|unauthorized|scoped|list permission/i.test(r)?"unauthorized":"network-error",vt(),e.innerHTML='',n&&(n.textContent=`Failed to load projects: ${i.message}`,n.classList.remove("hidden"))}}function g0(t){const e=document.getElementById(t),i=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",i.innerHTML=` + `}const yy=[[/gradient stroke\s*$/i," and an animated percentage label"],[/gauge\s*$/i," with a gradient stroke and animated fill"],[/rating\s*(bar|widget)?\s*$/i," with half-star support and haptic feedback"],[/list\s*$/i," with swipe-to-delete and an undo snackbar"],[/pad\s*$/i," that exports a transparent PNG"],[/carousel\s*$/i," with parallax cards and page indicators"],[/(button|cta)\s*$/i," with a loading spinner and success state"],[/(chart|graph)\s*$/i," that animates from a Firestore stream"],[/action\s*(that|to)?\s*$/i," uploads an image to Firebase Storage and returns the URL"],[/timer\s*$/i," with pause, resume and a completion callback"],[/map\s*$/i," with clustered markers and a custom info window"],[/^a\s+\w*$/i," widget that"],[/(picker|selector)\s*$/i," with search and multi-select"]],wy=220,by=6;function qu(t,e){return!!(t&&t.trim())&&!e}function Ey(t,e=""){if(typeof t!="string"||!t||t===e||t.trim().lengthi.test(t));return n?n[1]:null}function Sy(){let t="",e="";return{get active(){return t},resolve(n){return t=Ey(n,e)??"",t},dismiss(){t=""},accept(n){if(!t)return null;const i=n+t;return e=i,t="",i}}}function xy({onSubmit:t}){const e=document.getElementById("composer"),n=document.getElementById("pipeline-input"),i=document.getElementById("hero-send");if(!e||!n||!i||typeof t!="function")return;const r=e.querySelector(".ghost .typed"),s=e.querySelector(".ghost .suggest"),o=document.getElementById("tab-hint"),a=document.getElementById("suggest-status"),l=Array.from(document.querySelectorAll("#example-chips .chip")),u=document.getElementById("btn-add-images"),c=document.getElementById("prompt-image-input"),d=window.matchMedia("(prefers-reduced-motion: reduce)"),h=Sy();let f=!1,p=!1,g=!1,m=!1,v=null,E=null;function S(){i.disabled=!qu(n.value,p||g||m)}function _(){r&&(r.textContent=n.value)}function b(){s&&(s.textContent=""),_(),e.classList.remove("has-suggest"),o&&(o.hidden=!0,o.tabIndex=-1),a&&(a.textContent="")}function k(R){s&&(s.textContent=R),_(),e.classList.add("has-suggest"),o&&(o.hidden=!1,o.tabIndex=0,o.setAttribute("aria-label","Accept suggestion: "+R.trim())),a&&(a.textContent="Suggestion: "+R+". Press Tab to accept.")}function T(){h.dismiss(),b()}function x(){if(f||p)return;const R=h.resolve(n.value);R&&k(R)}function F(){clearTimeout(v),!f&&(v=setTimeout(x,wy))}function $(){const R=h.accept(n.value);return R===null?!1:(n.value=R,b(),S(),!0)}function O(R){p=R,e.classList.toggle("is-busy",R),i.classList.toggle("is-busy",R),i.setAttribute("aria-label",R?"Generating":"Generate"),n.readOnly=R,l.forEach(Z=>{Z.disabled=R}),u&&(u.disabled=R),c&&(c.disabled=R),S()}async function L(){if(qu(n.value,p||g||m)){T(),O(!0);try{await t()}finally{O(!1)}}}function N(){g=!1,E&&(clearInterval(E),E=null),e.classList.remove("is-demo-typing"),S()}function K(){l.forEach(R=>{R.classList.remove("is-active"),R.setAttribute("aria-pressed","false")})}function V(){try{n.focus({preventScroll:!0}),n.setSelectionRange(n.value.length,n.value.length)}catch{}}function M(R){const Z=R.dataset.prompt||"";if(N(),clearTimeout(v),v=null,T(),l.forEach(oe=>{const ye=oe===R;oe.classList.toggle("is-active",ye),oe.setAttribute("aria-pressed",String(ye))}),d.matches||!Z){n.value=Z,_(),S(),V();return}n.value="",_(),g=!0,S(),e.classList.add("is-demo-typing");let Ce=0;E=setInterval(()=>{Ce+=1,n.value=Z.slice(0,Ce),_(),Ce>=Z.length?(N(),V()):S()},22)}return l.forEach(R=>{R.setAttribute("aria-pressed","false"),R.addEventListener("click",()=>M(R))}),n.addEventListener("keydown",R=>{if(g&&R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!f){R.preventDefault();return}N(),R.key==="Tab"&&!R.shiftKey&&h.active?(R.preventDefault(),$()):R.key==="Escape"?(clearTimeout(v),v=null,T()):R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!f&&(R.preventDefault(),L())}),n.addEventListener("input",()=>{N(),K(),T(),S(),F()}),n.addEventListener("compositionstart",()=>{f=!0}),n.addEventListener("compositionend",()=>{f=!1,T(),S(),F()}),n.addEventListener("scroll",()=>{r&&r.parentNode&&(r.parentNode.scrollTop=n.scrollTop)}),o&&o.addEventListener("click",()=>{$(),n.focus({preventScroll:!0})}),i.addEventListener("click",L),n.addEventListener("pointerdown",()=>{N(),K()}),_(),S(),{setAttachmentsPending(R){m=!!R,S()}}}const Iy="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses";const _t="https://4tgke4.buildship.run",xh={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},hs="ccc_auth_session",Na="ccc_signin_return",ky=1800*1e3,zu=new WeakSet;let z={email:null,sessionToken:null,isVerified:!1};function Mn(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let ce=Mn({isResolved:!0}),Oa=Promise.resolve();const Cy=`${_t}/service/runpipeline`,Ay="bs_user_id",Py="bs_identity_token",Fy=`${_t}/authUserCheck`;let ht={userId:null,token:null,status:null,resolved:!1};const ps=lv,gs="ccc_subscription",Vu=3,Ry=new Set(["active","trialing","paid"]),ms="google/gemini-3.7-flash",Nr=["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"],Ty={"google/gemini-3.7-flash":"Gemini 3.7 Flash","anthropic/claude-opus-5":"Claude Opus 5","openai/gpt-5.6-sol":"GPT-5.6 Sol","z-ai/glm-5.2":"GLM 5.2","moonshotai/kimi-k3":"Kimi K3","openrouter/auto-beta":"OpenRouter: Auto Router","openrouter/free":"OpenRouter: Free Models","openrouter/deepseek/deepseek-v4-pro":"DeepSeek v4 Pro"};function Gt(t){return Ty[t]||t}const $y=new Set(["google/gemini-3.7-flash","anthropic/claude-opus-5","openai/gpt-5.6-sol","z-ai/glm-5.2","moonshotai/kimi-k3","openrouter/auto-beta"]);function Ih(t){return $y.has(t)}const Ba=4,Ho=8*1024*1024,My="https://4tgke4.buildship.run/service/runpipeline-image";let Ne=[];const pn=[],Ly=3e4;let kh=null;function Ny(t){return new Promise(e=>{const n=new FileReader;n.onload=()=>e(n.result),n.onerror=()=>e(null),n.readAsDataURL(t)})}async function Oy(t,e){const n=new FormData;return n.append("file",t),(await fetch(My,{method:"POST",body:n,signal:e})).json()}function By(t){if(Array.isArray(t)){const e=t[0];if(e&&typeof e=="object")for(const n of Object.keys(e)){if(n==="item"||n==="index")continue;const i=e[n];if(i&&typeof i=="object"){if(typeof i.file=="string")return i.file;if(typeof i.url=="string")return i.url}if(typeof i=="string")return i}return""}return typeof t=="string"?t:t&&typeof t=="object"&&(t.url||t.fileUrl||t.file_url||t.downloadUrl||t.imageUrl||t.image_url||t.file)||""}async function Dy(t,e,n){const i=await Ny(t);i&&Ne.includes(e)&&(e.dataUrl=i,cn());let r="";if(i)try{r=By(await Oy(t,n))}catch{r=""}return Ne.includes(e)?!i||!r?(Ne.splice(Ne.indexOf(e),1),cn(),"failed"):(e.url=r,cn(),"added"):"dropped"}function Ch(t){const e=pn.indexOf(t);e>=0&&pn.splice(e,1),Ph()}function Ah(t){t.controller.abort(),Ch(t);const e=Ne.indexOf(t.slot);e>=0&&(Ne.splice(e,1),cn())}function Ph(){kh?.setAttachmentsPending(pn.length>0)}async function jy(t){const e=Array.from(t.target.files||[]);if(!e.length)return;if(t.target.value="",y.isRunning){Ee("Wait for the current generation to finish before attaching images.","info");return}const n=e.filter(u=>u.size>Ho);n.length&&Ee(`Skipped ${n.length} image(s) over the ${(Ho/1024/1024).toFixed(0)} MB limit.`,"warning");const i=e.filter(u=>u.size<=Ho);if(!i.length)return;const r=Ba-Ne.length,s=i.slice(0,r);if(i.length>r&&Ee(`You can attach up to ${Ba} images.`,"info"),!s.length)return;const o=s.map(u=>{const c={dataUrl:null,name:u.name,url:null};Ne.push(c);const d={slot:c,controller:new AbortController},h=setTimeout(()=>d.controller.abort(),Ly);return d.job=Dy(u,c,d.controller.signal),pn.push(d),d.job.finally(()=>{clearTimeout(h),Ch(d)}),d.job});cn(),Ph();const l=(await Promise.all(o)).filter(u=>u==="failed").length;l&&Ee(`${l} image(s) could not be uploaded and were not attached.`,"error")}function Uy(t){const e=Ne[t],n=pn.find(i=>i.slot===e);if(n){Ah(n);return}Ne.splice(t,1),cn()}function cn(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",Ne.forEach((n,i)=>{const r=document.createElement("div");r.className="prompt-img-thumb"+(n.url?"":" is-pending"),r.innerHTML=(n.dataUrl?`Prompt image`:"")+``,t.appendChild(r)}),e&&(e.textContent=Ne.length>=Ba?"Image limit reached":"Add images"))}function kl(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),n=Ih(e?.value);t.classList.toggle("hidden",!n),!n&&Ne.length&&(pn.slice().forEach(Ah),Ne=[],cn())}const Fn="ccc_usage",Fh="google/gemini-3.7-flash",Rh="google/gemini-3.7-flash",kr="google/gemini-3.7-flash",Ni={professional:11,power:49},Da={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"},Or={AUD:1,USD:.65,EUR:.6,GBP:.52,CAD:.88,NZD:1.08,JPY:97,KRW:870,INR:54,SGD:.87,HKD:5.08,BRL:3.18,CNY:4.7,TWD:20.5,THB:22.5,VND:16200,IDR:10200,MYR:2.88,SEK:6.8,NOK:6.95,DKK:4.48,PLN:2.6,CZK:15.2,HUF:238,RON:2.98,TRY:20.9,AED:2.39,ILS:2.38,PHP:36.4,ZAR:11.8,RUB:58,UAH:26.8,CHF:.57,MXN:11.1,ARS:580,CLP:610,COP:2700,PEN:2.44};let Br={...Or};async function Hy(){const t=new AbortController,e=setTimeout(()=>t.abort(),5e3);try{const n=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:t.signal});if(!n.ok)return;const i=await n.json();if(i.result!=="success"||!i.rates)return;const r=i.rates,s={AUD:1},o=new Set([...Object.keys(Or),...Object.values(ja),...Object.values(Da)]);for(const a of o)a!=="AUD"&&(typeof r[a]=="number"&&r[a]>0?s[a]=r[a]:Or[a]&&(s[a]=Or[a]));Br=s}catch{}finally{clearTimeout(e)}}const ja={"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 Cl(){try{const s=Intl.DateTimeFormat().resolvedOptions().timeZone;if(s&&ja[s])return ja[s]}catch{}const e=(navigator.language||"en-US").replace("-","_"),n=Da[e];if(n)return n;const i=e.split("_")[0],r=Da[i];return r||"USD"}function Oi(t,e){const n=Br[e]??Br.USD,i=t*n,r=Math.round(i*100)/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:r>=100||r%1===0?0:2}).format(r)}catch{return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(t*Br.USD)}}const gt="ccc_api_key_",Pt="ccc_session_api_key_",Rt="ccc_encryption_key",tr="ccc_encryption_key_scope",Wy="ccc_keystore",vs="keys",nr="ccc_encryption_key_version";let Ua=null,_s=null,ir=!1,ys=!1,Gu=!1;class ws extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function Ku(){if(Gu)return;Gu=!0;const t="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(t),document.body&&Ee(t,"warning")}function Th(){return localStorage.getItem(nr)||""}function Ha(){return crypto.randomUUID?.()||Mh(crypto.getRandomValues(new Uint8Array(16)))}function qy(){const t=Th();if(t)return t;const e=Ha();return localStorage.setItem(nr,e),e}function ci(){Ua=null,_s=null,ir=!1,ys=!1}window.addEventListener("storage",t=>{t.key===nr&&ci()});function zy(){return new Promise((t,e)=>{const n=indexedDB.open(Wy,1);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(vs)||i.createObjectStore(vs)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function Al(t,e){const n=await zy();return new Promise((i,r)=>{const s=n.transaction(vs,t);let o;try{o=e(s.objectStore(vs))}catch(l){n.close(),r(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>r(o.error),s.oncomplete=()=>{n.close(),i(a)},s.onerror=()=>{n.close(),r(s.error||new Error("Encryption key transaction failed."))},s.onabort=()=>{n.close(),r(s.error||new Error("Encryption key transaction aborted."))}})}function Vy(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function Gy(){const t=await Al("readonly",e=>e.get(Rt));return Vy(t)?t:null}async function $h(t){await Al("readwrite",e=>e.put(t,Rt))}async function Ky(){ci();try{await Al("readwrite",t=>t.delete(Rt))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function Yy(){const t=sessionStorage.getItem(Rt);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await $h(e),sessionStorage.removeItem(Rt),sessionStorage.removeItem(tr),localStorage.removeItem(gt+"salt"),e}async function Yu(t){const e=sessionStorage.getItem(Rt);if(e)return ys=sessionStorage.getItem(tr)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new ws;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),i=await crypto.subtle.exportKey("jwk",n);return sessionStorage.setItem(Rt,JSON.stringify(i)),sessionStorage.setItem(tr,"session"),ys=!1,crypto.subtle.importKey("jwk",i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function Jy(t){if(sessionStorage.getItem(tr)==="session"&&sessionStorage.getItem(Rt))return Ku(),ir=!0,Yu(t);try{const e=await Gy();if(e)return e;const n=await Yy();if(n)return n;const i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await $h(i),i}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),Ku(),ir=!0,Yu(t)}}async function Pl(t={}){const{allowSessionFallbackCreation:e=!0}=t,n=qy();_s!==n&&ci();const i=Ua||Jy(e);Ua=i,_s=n;try{return await i}catch(r){throw ci(),r}}async function Zy(t){const e=await Pl(),n=_s,i=new TextEncoder,r=crypto.getRandomValues(new Uint8Array(12)),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},e,i.encode(t)),o=new Uint8Array(r.length+s.byteLength);return o.set(r),o.set(new Uint8Array(s),r.length),{ciphertext:Mh(o),keyVersion:n,sessionFallback:ir}}async function Xy(t,e={}){const{isSessionCredential:n=!1}=e;try{const i=await Pl({allowSessionFallbackCreation:!1});if(ir&&!n&&!ys)throw new ws;const r=Qy(t),s=r.slice(0,12),o=r.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},i,o);return new TextDecoder().decode(a)}catch(i){if(i instanceof ws)throw i;return console.error("Decryption failed:",i),null}}function Mh(t){const e=new Uint8Array(t);let n="";for(let i=0;i0}let Ln="",ui="",qi=null,Zu=0,tt="not-configured";async function Fl(){sessionStorage.getItem(Rt)&&await Pl(),Ln=await Te("flutterflow"),ui=await Te("flutterflow_project_id"),a0(),rn(),Ln?Ml():(tt="not-configured",vt())}let rr=!1;function Lh(){const t=document.getElementById("api-keys-modal");He(t),$l(),Ln&&Ll(Ln)}function Rl(){rr=!1,Lh()}function t0(){rr=!0;const t=document.getElementById("walkthrough-modal");t&&We(t),Lh()}let Xu=!1;function Qu(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-settings-model");if(!t||!e)return;e.value=t.value;const n=Array.from(t.options);Array.from(e.options).forEach((r,s)=>{const o=n[s];o&&(r.textContent=o.textContent)});const i=document.getElementById("composer-settings-free-notice");i&&(document.getElementById("model-selector-free-notice")?(i.hidden=!1,i.innerHTML='Free plan — Gemini only. '):i.hidden=!0)}function ed(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-image-capability"),n=document.getElementById("composer-image-capability-note");if(!t)return;const i=Gt(t.value),r=Ih(t.value);e&&(e.textContent=r?"Supported":"Not supported"),n&&(n.textContent=r?`${i} accepts reference images you attach to the prompt.`:`Images can't be attached with ${i}. Attached images are removed when you switch to it.`),kl()}function n0(){if(rr=!1,Qu(),ed(),!Xu){const e=document.getElementById("composer-settings-model");e&&e.addEventListener("change",()=>{const n=document.getElementById("code-generator-model");n.value=e.value,n.dispatchEvent(new Event("change")),Qu(),ed()}),Xu=!0}const t=document.querySelector('.composer [aria-label="Generation settings"]');He("composer-settings-modal",{trigger:t})}function i0(t){t&&t.target!==t.currentTarget||We("composer-settings-modal")}function Nh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&We(e);const n=rr;if(rr=!1,n){const i=document.getElementById("walkthrough-modal");i&&(tt==="connected"&&Tl(),He(i))}}let en=1;function Oh(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function Ns(){const t=Oh();t.length&&t.forEach((e,n)=>{const i=n+1;e.classList.remove("wt-current","wt-done","wt-pending");const r=e.querySelector(".wt-step-num");i===en?(e.classList.add("wt-current"),r&&(r.textContent=i)):i0&&en<=t&&(en++,Ns())}function r0(){const t=document.getElementById("walkthrough-modal");t&&(en=1,Ns(),He(t))}function s0(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&We(e);const n=document.getElementById("walkthrough-dont-show");n&&n.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function Bh(){if(z.isVerified&&Tt()&&ce.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(en=1,Ns(),He(e))}}async function $l(){const t=document.getElementById("flutterflow-api-key-input");Ln?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",o0()}function o0(){td("flutterflow","flutterflow-key-status"),td("flutterflow_project_id","flutterflow-project-status")}function td(t,e){const n=document.getElementById(e);if(!n)return;const i=n.querySelector(".key-status-dot"),r=n.querySelector("span");Ct(t)?(i.className="key-status-dot configured",r.className="text-green-600",r.textContent="User key configured"):(i.className="key-status-dot missing",r.className="text-gray-500",r.textContent="Not configured")}function rn(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff");e&&e.classList.toggle("hidden",!t)}function a0(){const t=document.getElementById("api-keys-status");if(!t)return;const e=t.querySelectorAll(".key-status-dot"),n=["flutterflow"];e.forEach((i,r)=>{const s=n[r];s==="flutterflow"?Ct("flutterflow")&&Ct("flutterflow_project_id")?(i.className="key-status-dot configured",i.title="FlutterFlow (Fully configured)"):Ct("flutterflow")||Ct("flutterflow_project_id")?(i.className="key-status-dot env",i.title="FlutterFlow (Partially configured)"):(i.className="key-status-dot missing",i.title="FlutterFlow (Not configured)"):Ct(s)?(i.className="key-status-dot configured",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (User key)"):(i.className="key-status-dot missing",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (Not configured)")}),rn()}async function l0(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select"),n=t.value.trim();n&&await Ju("flutterflow",n);const i=e?.value.trim()||"";if(i){if(!Os(i)){Ee("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await Ju("flutterflow_project_id",i)}await Fl(),n&&await Ml(),$l();const r=document.querySelector("#api-keys-modal .bg-blue-500"),s=r.textContent;r.textContent="Saved!",r.classList.remove("bg-blue-500","hover:bg-blue-600"),r.classList.add("bg-green-500"),setTimeout(()=>{r.textContent=s,r.classList.remove("bg-green-500"),r.classList.add("bg-blue-500","hover:bg-blue-600"),Nh()},1e3)}async function c0(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(nr,Ha()),ci(),localStorage.removeItem(gt+"flutterflow"),localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow"),sessionStorage.removeItem(Pt+"flutterflow_project_id"),sessionStorage.removeItem(Rt),sessionStorage.removeItem(tr),localStorage.removeItem(gt+"salt"),await Ky(),localStorage.setItem(nr,Ha()),localStorage.removeItem(gt+"flutterflow"),localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow"),sessionStorage.removeItem(Pt+"flutterflow_project_id"),await Fl();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),$l()}function Os(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function vt(){const t=document.getElementById("acct-ff-dot"),e=document.getElementById("acct-ff-status"),n=document.getElementById("acct-ff-endpoint"),i=document.getElementById("acct-ff-project");if(n){const o=yt();n.textContent=o.includes("staging")?"Staging":"Production"}if(i&&(i.textContent=ui||"—"),!e)return;let r,s;if(!Ct("flutterflow"))r="Not connected — add your FlutterFlow API key",s="";else switch(tt){case"connected":r="Connected to FlutterFlow",s="ok";break;case"no-projects":r="Key accepted — no projects found",s="warn";break;case"unauthorized":r="API key rejected (401/403) — re-enter your key",s="bad";break;case"network-error":r="Could not reach FlutterFlow — check your network",s="bad";break;default:r="Checking connection…",s="warn";break}e.textContent=r,t&&(t.className=`acct-dot${s?" "+s:""}`)}async function Ml(){const t=await Te("flutterflow");if(!t||!Ct("flutterflow"))return tt="not-configured",vt(),null;tt="validating",vt();try{const n=await new hi(t,"","main",yt()).listProjects();return tt=n&&n.length>0?"connected":"no-projects",vt(),n}catch(e){const n=String(e&&e.message||"");return tt=/(401|403)|denied|unauthorized|scoped|list permission/i.test(n)?"unauthorized":"network-error",vt(),null}}function u0(){ui="",localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow_project_id")}function d0(){u0();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML='',t.value=""),Ct("flutterflow")?(tt="validating",Ll(Ln)):tt="not-configured",vt()}function f0(t,e){const n=document.getElementById(t);n&&(n.value?e?n.style.borderColor="#22c55e":n.style.borderColor="#ef4444":n.style.borderColor="")}function h0(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const n=e.target.value.trim().length>0;f0("flutterflow-api-key-input",n)}),t.addEventListener("blur",p0(async e=>{const n=e.target.value.trim();n&&await Ll(n)},500)))}function p0(t,e){let n;return function(...r){const s=()=>{clearTimeout(n),t(...r)};clearTimeout(n),n=setTimeout(s,e)}}async function Ll(t){const e=document.getElementById("flutterflow-projects-select"),n=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',n&&n.classList.add("hidden"),(Ct("flutterflow")||t)&&(tt="validating"),vt();try{const r=await new hi(t,"","main",yt()).listProjects();if(!r||r.length===0){tt="no-projects",vt(),e.innerHTML='';return}tt="connected",vt(),e.innerHTML='',r.forEach(s=>{const o=document.createElement("option");o.value=s.id||s.projectId||"",o.textContent=s.name||s.projectName||`Project ${s.id}`,e.appendChild(o)}),ui&&(e.value=ui)}catch(i){console.error("Failed to fetch projects:",i);const r=String(i&&i.message||"");tt=/(401|403)|denied|unauthorized|scoped|list permission/i.test(r)?"unauthorized":"network-error",vt(),e.innerHTML='',n&&(n.textContent=`Failed to load projects: ${i.message}`,n.classList.remove("hidden"))}}function g0(t){const e=document.getElementById(t),i=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",i.innerHTML=` `):(e.type="password",i.innerHTML=` - `)}let y={step1Result:null,step2Result:null,step3Result:null,bundleSpec:null,artifactBundle:null,bundleReview:null,selectedArtifactId:null,resultsViewMode:"summary",currentStep:0,isRunning:!1,runId:0,submittedPrompt:"",submittedImages:[]};function m0(){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 v0(){y.bundleSpec=Qi(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function Bs(){const t=oi(y.bundleSpec);y.artifactBundle=Qi(y.step2Result,{id:y.bundleSpec?.id,title:y.bundleSpec?.title,description:y.bundleSpec?.description,artifactType:t.artifactType,artifactName:t.artifactName,fileName:t.fileName,dependencies:t.dependencies,relationships:y.bundleSpec?.relationships,code:y.step2Result||""});const e=Hv(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(n=>n.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=oi(y.artifactBundle).id}function Ds(){const t=Qi(y.step3Result,{id:y.artifactBundle?.id,title:y.artifactBundle?.title}),e=new Map(t.artifacts.map(i=>[i.id,i.review])),n=new Map(t.artifacts.filter(i=>{const r=i.review;return r&&typeof r.fixedSource=="string"&&r.fixedSource.trim()}).map(i=>[i.id,i.review.fixedSource.trim()]));y.bundleReview=Qi({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(i=>{const r=n.get(i.id)||null;return{...i,review:e.get(i.id)||i.review||y.step3Result||null,...r?{fixedCode:r}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function Bh(){const t=Nl();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function Nl(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(n=>n.id===y.selectedArtifactId)||oi(t)}function Ol(){return Nl().code||y.step2Result||""}async function _0(){try{await Fl()}catch(t){return console.error("checkConnection: initializeApiKeys failed:",t),!1}return!0}const Dr={production:"https://api.flutterflow.io/v2/",staging:"https://api.flutterflow.io/v2-staging/"};function y0(t,e){const n=e?.trim()?` (${e.trim().slice(0,200)})`:"";return t===401?`Your FlutterFlow API key was rejected (401 Unauthorized)${n}. Re-enter a current key under API Keys settings, then try again.`:`Listing FlutterFlow projects was denied (403)${n}. The key may be scoped to sync a single project without list permission - verify the key's access in FlutterFlow, re-enter it under API Keys settings, then retry.`}class hi{constructor(e,n,i="main",r=Dr.production){this.apiKey=e,this.baseUrl=r,this._projectId=n,this._branchName=i,this._endpoint=r}get projectId(){return this._projectId}get branchName(){return this._branchName==="main"?"":this._branchName}async exportProjectZip(){console.log(`Exporting code from FlutterFlow project: ${this.projectId}, branch: ${this.branchName||"main"}`);const e=[{project:{path:`projects/${this.projectId}`},...this.branchName?{branch_name:this.branchName}:{},export_as_module:!1,include_assets_map:!1,format:!1,export_as_debug:!1},{project_id:this.projectId,branch_name:this.branchName,include_assets:!1,export_as_module:!1}];let n=null;for(const i of e)try{const r=await fetch(`${this.baseUrl}exportCode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(i)});if(!r.ok){const a=await r.text();n=new Error(`Export failed: ${r.status} - ${a}`);continue}const s=await r.json(),o=s?.value?.project_zip||s?.project_zip;if(!o){n=new Error("Export response did not include project source.");continue}return o}catch(r){n=r}throw n||new Error("Export failed for an unknown reason.")}async fetchProjectSource(){const e=await this.exportProjectZip(),n=await JSZip.loadAsync(e,{base64:!0}),i=Object.keys(n.files).filter(a=>!n.files[a].dir&&(a==="pubspec.yaml"||a.endsWith("/pubspec.yaml"))).sort((a,l)=>a.split("/").length-l.split("/").length)[0];if(!i)throw new Error("Export did not contain a pubspec.yaml.");const r=i.slice(0,i.length-12),s=new Map,o=Object.keys(n.files).filter(a=>{if(n.files[a].dir||!a.startsWith(r))return!1;const l=a.slice(r.length);return l==="lib/flutter_flow/custom_functions.dart"||l.startsWith("lib/custom_code/")&&l.endsWith(".dart")});return await Promise.all(o.map(async a=>{s.set(a.slice(r.length),await n.files[a].async("string"))})),{pubspecYaml:await n.files[i].async("string"),files:s}}async pushCodeWithRetry(e,n=3){const i=[Dr.production,Dr.staging],r=Math.max(0,i.indexOf(this._endpoint));let s=!1,o=null;for(let a=0;asetTimeout(h,1e3*(a+1)));continue}if(c.ok)return console.log(`Push to ${u} succeeded!`),c;o=c.status;let d;try{d=await c.clone().text()}catch{d="(unreadable response body)"}if(console.log(`Push to ${u} returned ${c.status}: ${d}`),c.status>=500&&(s=!0),c.status===500){console.warn(`Endpoint ${u} returned 500, trying next...`),await new Promise(f=>setTimeout(f,1e3*(a+1)));continue}if(c.status>=500)throw new lt(`FlutterFlow reported a server error (HTTP ${c.status}), which cannot prove the push was refused — the write may have been applied before the failure. Open your FlutterFlow project to reconcile before retrying.`);if(s)throw new lt(`The push was refused (HTTP ${c.status}), but an earlier sync attempt may already have applied it — server errors and dropped responses cannot prove a refusal. Open your FlutterFlow project to reconcile before retrying.`);return c}throw J_({httpStatus:o})}async pushCode(e){return this.pushCodeWithRetry(e)}parseProjectsResponse(e){if(e?.success&&typeof e.value=="string")try{const i=JSON.parse(e.value);if(i&&Array.isArray(i.entries))return i.entries.map(r=>({id:r.id,name:r.project?.name||r.id}))}catch(i){console.error("Failed to parse stringified project value:",i)}const n=e?.projects||e?.items||e?.entries||(Array.isArray(e)?e:[]);return Array.isArray(n)?n:[]}async listProjects(){console.log("Listing projects for API key");const e=[`${this.baseUrl}listProjects`,"https://api.flutterflow.io/v2/l/listProjects"];let n=0,i="";for(const r of e){const s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({project_type:"ALL",deserialize_response:!0})});if(s.ok)return r!==e[0]&&console.log(`listProjects answered on legacy path ${r}`),this.parseProjectsResponse(await s.json());if(n=s.status,i=await s.text(),console.warn(`listProjects via ${r} returned ${n}: ${i}`),s.status===401||s.status===403)throw new Error(y0(s.status,i));if(s.status!==404)throw new Error(`List projects failed: ${s.status} - ${i}`)}throw new Error(`List projects failed: ${n} - ${i}`)}}async function w0(t){const e=t.clone();let n;try{n=await t.json()}catch{let s="";try{s=await e.text()}catch{}if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:s||`HTTP ${t.status}`,errorMap:new Map};throw new lt(`FlutterFlow accepted the sync but returned an unreadable response${s?`: ${s.slice(0,200)}`:"."}`)}if(!t.ok){let r=n.message||`HTTP ${t.status}`,s=new Map;if(n.errors)s=new Map(Object.entries(n.errors));else if(!n.message&&typeof n=="object"){const o=Object.keys(n).filter(a=>a.endsWith(".dart")&&Array.isArray(n[a]));o.length>0&&(s=new Map(Object.entries(n)),r=o.flatMap(l=>n[l].map(u=>`${l}: ${u.errorMessage}`)).join(` -`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:r,errorMap:s}}let i={};if(n.value)try{i=typeof n.value=="string"?JSON.parse(n.value):n.value}catch(r){console.warn("Ignoring malformed push response value:",r)}return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(i))}}function Bl(t,e){return{401:"Authentication failed. Please check your FlutterFlow API key.",403:"Access denied. You may not have permission to modify this project.",404:"Project not found. Please check your Project ID.",409:"Conflict detected. The project may have been modified elsewhere.",422:"Validation failed: Invalid request format",429:"Rate limit exceeded. Please try again in a few minutes.",500:"FlutterFlow server error. Please try again later.",503:"FlutterFlow service temporarily unavailable."}[t]||`FlutterFlow API error: ${`HTTP ${t}`}`}const J={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},Dh=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,jh=/extends\s+State<\w+>/;function b0(t,e=""){if(t==="pubspec.yaml")return J.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return J.OTHER;if(t==="custom_functions.dart")return J.FUNCTION;if(e){const n=Dh.test(e),i=jh.test(e);if(n||i)return J.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return J.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return J.FUNCTION}return J.CODE_FILE}function Uh(t,e){switch(e){case J.ACTION:return`lib/custom_code/actions/${t}`;case J.WIDGET:return`lib/custom_code/widgets/${t}`;case J.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case J.CODE_FILE:return`lib/custom_code/${t}`;case J.DEPENDENCIES:return"pubspec.yaml";case J.OTHER:return`lib/custom_code/${t}`;default:return t}}async function Dl(t,e=new Map){return xv(t,e)}const Wa=new Map;function Hh(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function sr(t){Wa.delete(Hh(t))}function Wh(t,e,n){return new Promise((i,r)=>{let s=!1;const o=(l,u,c)=>{s||(s=!0,c==="resolve"?i(u):r(u))},a=setTimeout(()=>{s||(s=!0,n(i,r))},e);t.then(l=>{clearTimeout(a),o(i,l,"resolve")},l=>{clearTimeout(a),o(r,l,"reject")})})}async function jl(t,e,n=_h){return Wh((async()=>{const i=await t.pushCode(e);return w0(i)})(),n,(i,r)=>r(new lt("FlutterFlow did not answer the sync in time — the push may still have been applied. The outcome is not yet known: open your FlutterFlow project to reconcile before retrying the deploy.")))}async function Ul(t,e,n,i,r="",s=_h){const o=n_(e,n);if(o.length===0)return{remoteFiles:n,syncFileMap:e,unverified:[],approximate:[]};const a=K_(o,r),l={...a.manifest,sources:a.sources},u=a.skipped.map(h=>h.reason);u.forEach(h=>console.warn(`[custom class deploy] ${h}`));const c=a.approximate;c.forEach(h=>console.warn(`[custom class deploy] ${h}`)),console.log(`Provisioning ${o.length} new FlutterFlow custom code file(s) before sync.`),Oe.set("provision");let d=!0,f;try{if(f=await Wh((async()=>{let h;try{h=await fetch(Iy,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:i,customClasses:o,verification:l,stream:!0})})}catch{throw new lt("The provisioning request did not return a response. The deploy may have reached the FlutterFlow server — open your FlutterFlow project to reconcile before retrying.")}return Z_(h,{onPhase:p=>{d&&Oe.setSubstatus(p)},onLog:p=>{d&&console.log(`[custom class deploy] ${p}`)}})})(),s,(h,p)=>{d=!1,p(new lt("The deploy is still working on the FlutterFlow server, but this browser tab has stopped waiting. Your custom classes may or may not have been written — the outcome is not yet known. Open your FlutterFlow project to reconcile before retrying the deploy."))}),!f.finalResultReceived)throw X_(f)===Xe.FAILED?new Error(f.error||`FlutterFlow custom class provisioning failed (HTTP ${f.httpStatus}).`):new lt("The connection to the FlutterFlow deploy runner dropped before it reported a result. The deploy may still be finishing on the server; open your FlutterFlow project to reconcile before retrying.")}catch(h){throw h instanceof lt&&sr(t),h}if(!f.success){const h=f.details?` ${f.details}`:"";throw new Error(`${f.error||"FlutterFlow custom class provisioning failed."}${h}`)}return sr(t),f.verificationSkipped&&(console.warn(`[custom class deploy] ${f.verificationSkipped}`),u.push(f.verificationSkipped)),{remoteFiles:n,syncFileMap:i_(e,o),unverified:u,approximate:c,provisionSucceeded:!0}}async function Hl(t,e={}){const n=Hh(t);let i=Wa.get(n);if(i===void 0){try{i=await t.fetchProjectSource()}catch(l){throw new Error(`Could not read your project's pubspec.yaml (${l.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=mh(i.pubspecYaml);if(!a.valid)throw new Error(`Your project's pubspec.yaml could not be read reliably (${a.errors.join("; ")}). Deploy was stopped so your existing package dependencies aren't overwritten.`);Wa.set(n,i)}const r=await py(i.pubspecYaml,e),s=W_(i.pubspecYaml,r.overrides),o=H_(s.yaml,r.additions);return r.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>`${a}: ${r.additions[a]||"any"}`).join(", "),r.sdk.dartSdkFloor?`(resolved for Dart ${r.sdk.dartSdkFloor})`:""),r.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:s.overridden,warnings:r.warnings,remoteFiles:i.files}}function E0(t){const e=[],n=[];t.content.length>5e4&&n.push("Code file is large (>50KB). This may take longer to commit."),t.content.length>1e5&&e.push("Code file is too large (>100KB). Consider splitting into smaller components.");const i=t.content.split(` -`).length;i>500&&n.push(`Code has ${i} lines. Consider breaking it into smaller widgets.`),t.content.includes("setState")&&t.codeType===J.ACTION&&n.push("Using setState in a Custom Action may not work as expected. Consider using a Custom Widget."),t.content.includes("dynamic")&&!t.content.includes("?")&&n.push('Code uses "dynamic" types. Consider adding explicit types for better null safety.'),t.content.match(/Color\(0xFF[0-9A-Fa-f]{6}\)/)&&n.push("Code contains hardcoded colors. Consider using FlutterFlowTheme.of(context) for theme consistency.");const r=t.content.match(/print\s*\(/g);r&&r.length>3&&n.push(`Code contains ${r.length} print statements. Consider removing debug prints before committing.`);const s=b_(t.content);if(s&&e.push(`FlutterFlow cannot format this code - ${s}. Fix or regenerate before committing.`),t.codeType===J.WIDGET){const o=ah(t.content),a=__(t.fileName);if(o.length===0)e.push("No public widget class found (must extend StatelessWidget or StatefulWidget).");else if(!o.includes(a)){const l=`${lh(o[0])}`;e.push(`Widget class name "${o[0]}" does not match the file name "${t.fileName}". FlutterFlow derives the widget from the file name, so it will report "No widget ${a} found". Rename the file to "${l}" or the class to match before committing.`)}}return{canProceed:e.length===0,issues:e,warnings:n}}function qh(t,e={}){const{artifactType:n="CustomWidget",artifactName:i="GeneratedCode",fileName:r}=e,s=m_(t);let o=r||i;if(n==="CustomFunction")o="custom_functions.dart";else if(n==="CustomWidget"){const u=ah(s)[0],c=u?lh(u):null;c&&o!==c?(console.warn(`Commit file name "${o}" does not match declared widget class "${u}"; renaming to "${c}" so FlutterFlow can find the widget.`),o=c):o.endsWith(".dart")||(o+=".dart")}else o.endsWith(".dart")||(o+=".dart");let a=J.CODE_FILE;switch(n){case"CustomAction":a=J.ACTION;break;case"CustomWidget":a=J.WIDGET;break;case"CustomFunction":a=J.FUNCTION;break;case"CustomClass":case"CodeFile":a=J.CODE_FILE;break}let l="";return a===J.WIDGET?l=`// Automatic FlutterFlow imports + `)}let y={step1Result:null,step2Result:null,step3Result:null,bundleSpec:null,artifactBundle:null,bundleReview:null,selectedArtifactId:null,resultsViewMode:"summary",currentStep:0,isRunning:!1,runId:0,submittedPrompt:"",submittedImages:[]};function m0(){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 v0(){y.bundleSpec=Qi(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function Bs(){const t=oi(y.bundleSpec);y.artifactBundle=Qi(y.step2Result,{id:y.bundleSpec?.id,title:y.bundleSpec?.title,description:y.bundleSpec?.description,artifactType:t.artifactType,artifactName:t.artifactName,fileName:t.fileName,dependencies:t.dependencies,relationships:y.bundleSpec?.relationships,code:y.step2Result||""});const e=Wv(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(n=>n.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=oi(y.artifactBundle).id}function Ds(){const t=Qi(y.step3Result,{id:y.artifactBundle?.id,title:y.artifactBundle?.title}),e=new Map(t.artifacts.map(i=>[i.id,i.review])),n=new Map(t.artifacts.filter(i=>{const r=i.review;return r&&typeof r.fixedSource=="string"&&r.fixedSource.trim()}).map(i=>[i.id,i.review.fixedSource.trim()]));y.bundleReview=Qi({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(i=>{const r=n.get(i.id)||null;return{...i,review:e.get(i.id)||i.review||y.step3Result||null,...r?{fixedCode:r}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function Dh(){const t=Nl();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function Nl(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(n=>n.id===y.selectedArtifactId)||oi(t)}function Ol(){return Nl().code||y.step2Result||""}async function _0(){try{await Fl()}catch(t){return console.error("checkConnection: initializeApiKeys failed:",t),!1}return!0}const Dr={production:"https://api.flutterflow.io/v2/",staging:"https://api.flutterflow.io/v2-staging/"};function y0(t,e){const n=e?.trim()?` (${e.trim().slice(0,200)})`:"";return t===401?`Your FlutterFlow API key was rejected (401 Unauthorized)${n}. Re-enter a current key under API Keys settings, then try again.`:`Listing FlutterFlow projects was denied (403)${n}. The key may be scoped to sync a single project without list permission - verify the key's access in FlutterFlow, re-enter it under API Keys settings, then retry.`}class hi{constructor(e,n,i="main",r=Dr.production){this.apiKey=e,this.baseUrl=r,this._projectId=n,this._branchName=i,this._endpoint=r}get projectId(){return this._projectId}get branchName(){return this._branchName==="main"?"":this._branchName}async exportProjectZip(){console.log(`Exporting code from FlutterFlow project: ${this.projectId}, branch: ${this.branchName||"main"}`);const e=[{project:{path:`projects/${this.projectId}`},...this.branchName?{branch_name:this.branchName}:{},export_as_module:!1,include_assets_map:!1,format:!1,export_as_debug:!1},{project_id:this.projectId,branch_name:this.branchName,include_assets:!1,export_as_module:!1}];let n=null;for(const i of e)try{const r=await fetch(`${this.baseUrl}exportCode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(i)});if(!r.ok){const a=await r.text();n=new Error(`Export failed: ${r.status} - ${a}`);continue}const s=await r.json(),o=s?.value?.project_zip||s?.project_zip;if(!o){n=new Error("Export response did not include project source.");continue}return o}catch(r){n=r}throw n||new Error("Export failed for an unknown reason.")}async fetchProjectSource(){const e=await this.exportProjectZip(),n=await JSZip.loadAsync(e,{base64:!0}),i=Object.keys(n.files).filter(a=>!n.files[a].dir&&(a==="pubspec.yaml"||a.endsWith("/pubspec.yaml"))).sort((a,l)=>a.split("/").length-l.split("/").length)[0];if(!i)throw new Error("Export did not contain a pubspec.yaml.");const r=i.slice(0,i.length-12),s=new Map,o=Object.keys(n.files).filter(a=>{if(n.files[a].dir||!a.startsWith(r))return!1;const l=a.slice(r.length);return l==="lib/flutter_flow/custom_functions.dart"||l.startsWith("lib/custom_code/")&&l.endsWith(".dart")});return await Promise.all(o.map(async a=>{s.set(a.slice(r.length),await n.files[a].async("string"))})),{pubspecYaml:await n.files[i].async("string"),files:s}}async pushCodeWithRetry(e,n=3,i=null){const r=[Dr.production,Dr.staging],s=Math.max(0,r.indexOf(this._endpoint));let o=!1,a=null;for(let l=0;lsetTimeout(p,1e3*(l+1)));continue}if(d.ok)return console.log(`Push to ${c} succeeded!`),d;a=d.status;let h;try{h=await d.clone().text()}catch{h="(unreadable response body)"}if(console.log(`Push to ${c} returned ${d.status}: ${h}`),d.status>=500&&(o=!0),d.status===500){console.warn(`Endpoint ${c} returned 500, trying next...`),await new Promise(f=>setTimeout(f,1e3*(l+1)));continue}if(d.status>=500)throw new lt(`FlutterFlow reported a server error (HTTP ${d.status}), which cannot prove the push was refused — the write may have been applied before the failure. Open your FlutterFlow project to reconcile before retrying.`);if(o)throw new lt(`The push was refused (HTTP ${d.status}), but an earlier sync attempt may already have applied it — server errors and dropped responses cannot prove a refusal. Open your FlutterFlow project to reconcile before retrying.`);return d}throw ju({httpStatus:a})}async pushCode(e,n=null){return this.pushCodeWithRetry(e,3,n)}parseProjectsResponse(e){if(e?.success&&typeof e.value=="string")try{const i=JSON.parse(e.value);if(i&&Array.isArray(i.entries))return i.entries.map(r=>({id:r.id,name:r.project?.name||r.id}))}catch(i){console.error("Failed to parse stringified project value:",i)}const n=e?.projects||e?.items||e?.entries||(Array.isArray(e)?e:[]);return Array.isArray(n)?n:[]}async listProjects(){console.log("Listing projects for API key");const e=[`${this.baseUrl}listProjects`,"https://api.flutterflow.io/v2/l/listProjects"];let n=0,i="";for(const r of e){const s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({project_type:"ALL",deserialize_response:!0})});if(s.ok)return r!==e[0]&&console.log(`listProjects answered on legacy path ${r}`),this.parseProjectsResponse(await s.json());if(n=s.status,i=await s.text(),console.warn(`listProjects via ${r} returned ${n}: ${i}`),s.status===401||s.status===403)throw new Error(y0(s.status,i));if(s.status!==404)throw new Error(`List projects failed: ${s.status} - ${i}`)}throw new Error(`List projects failed: ${n} - ${i}`)}}async function w0(t){const e=t.clone();let n;try{n=await t.json()}catch{let s="";try{s=await e.text()}catch{}if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:s||`HTTP ${t.status}`,errorMap:new Map};throw new lt(`FlutterFlow accepted the sync but returned an unreadable response${s?`: ${s.slice(0,200)}`:"."}`)}if(!t.ok){let r=n.message||`HTTP ${t.status}`,s=new Map;if(n.errors)s=new Map(Object.entries(n.errors));else if(!n.message&&typeof n=="object"){const o=Object.keys(n).filter(a=>a.endsWith(".dart")&&Array.isArray(n[a]));o.length>0&&(s=new Map(Object.entries(n)),r=o.flatMap(l=>n[l].map(u=>`${l}: ${u.errorMessage}`)).join(` +`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:r,errorMap:s}}let i={};if(n.value)try{i=typeof n.value=="string"?JSON.parse(n.value):n.value}catch(r){console.warn("Ignoring malformed push response value:",r)}return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(i))}}function Bl(t,e){return{401:"Authentication failed. Please check your FlutterFlow API key.",403:"Access denied. You may not have permission to modify this project.",404:"Project not found. Please check your Project ID.",409:"Conflict detected. The project may have been modified elsewhere.",422:"Validation failed: Invalid request format",429:"Rate limit exceeded. Please try again in a few minutes.",500:"FlutterFlow server error. Please try again later.",503:"FlutterFlow service temporarily unavailable."}[t]||`FlutterFlow API error: ${`HTTP ${t}`}`}const J={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},jh=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,Uh=/extends\s+State<\w+>/;function b0(t,e=""){if(t==="pubspec.yaml")return J.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return J.OTHER;if(t==="custom_functions.dart")return J.FUNCTION;if(e){const n=jh.test(e),i=Uh.test(e);if(n||i)return J.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return J.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return J.FUNCTION}return J.CODE_FILE}function Hh(t,e){switch(e){case J.ACTION:return`lib/custom_code/actions/${t}`;case J.WIDGET:return`lib/custom_code/widgets/${t}`;case J.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case J.CODE_FILE:return`lib/custom_code/${t}`;case J.DEPENDENCIES:return"pubspec.yaml";case J.OTHER:return`lib/custom_code/${t}`;default:return t}}async function Dl(t,e=new Map){return Iv(t,e)}const Wa=new Map;function Wh(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function sr(t){Wa.delete(Wh(t))}function qh(t,e,n){return new Promise((i,r)=>{let s=!1;const o=(l,u,c)=>{s||(s=!0,c==="resolve"?i(u):r(u))},a=setTimeout(()=>{s||(s=!0,n(i,r))},e);t.then(l=>{clearTimeout(a),o(i,l,"resolve")},l=>{clearTimeout(a),o(r,l,"reject")})})}async function jl(t,e,n=yh){const i={stop:!1};return qh((async()=>{const r=await t.pushCode(e,i);return w0(r)})(),n,(r,s)=>{i.stop=!0,s(new lt("FlutterFlow did not answer the sync in time — the push may still have been applied. The outcome is not yet known: open your FlutterFlow project to reconcile before retrying the deploy."))})}async function Ul(t,e,n,i,r="",s=yh){const o=i_(e,n);if(o.length===0)return{remoteFiles:n,syncFileMap:e,unverified:[],approximate:[]};const a=Y_(o,r),l={...a.manifest,sources:a.sources},u=a.skipped.map(f=>f.reason);u.forEach(f=>console.warn(`[custom class deploy] ${f}`));const c=a.approximate;c.forEach(f=>console.warn(`[custom class deploy] ${f}`)),console.log(`Provisioning ${o.length} new FlutterFlow custom code file(s) before sync.`),Oe.set("provision");let d=!0,h;try{if(h=await qh((async()=>{let f;try{f=await fetch(Iy,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:i,customClasses:o,verification:l,stream:!0})})}catch{throw new lt("The provisioning request did not return a response. The deploy may have reached the FlutterFlow server — open your FlutterFlow project to reconcile before retrying.")}return Z_(f,{onPhase:p=>{d&&Oe.setSubstatus(p)},onLog:p=>{d&&console.log(`[custom class deploy] ${p}`)}})})(),s,(f,p)=>{d=!1,p(new lt("The deploy is still working on the FlutterFlow server, but this browser tab has stopped waiting. Your custom classes may or may not have been written — the outcome is not yet known. Open your FlutterFlow project to reconcile before retrying the deploy."))}),!h.finalResultReceived){if(X_(h)===Xe.FAILED){const f=new Error(h.error||`FlutterFlow custom class provisioning failed (HTTP ${h.httpStatus}).`);throw f.remoteRefusal=!0,f}throw new lt("The connection to the FlutterFlow deploy runner dropped before it reported a result. The deploy may still be finishing on the server; open your FlutterFlow project to reconcile before retrying.")}}catch(f){throw f instanceof lt&&sr(t),f}if(!h.success){const f=h.details?` ${h.details}`:"",p=new Error(`${h.error||"FlutterFlow custom class provisioning failed."}${f}`);throw p.remoteRefusal=!0,p}return sr(t),h.verificationSkipped&&(console.warn(`[custom class deploy] ${h.verificationSkipped}`),u.push(h.verificationSkipped)),{remoteFiles:n,syncFileMap:r_(e,o),unverified:u,approximate:c,provisionSucceeded:!0}}async function Hl(t,e={}){const n=Wh(t);let i=Wa.get(n);if(i===void 0){try{i=await t.fetchProjectSource()}catch(l){throw new Error(`Could not read your project's pubspec.yaml (${l.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=vh(i.pubspecYaml);if(!a.valid)throw new Error(`Your project's pubspec.yaml could not be read reliably (${a.errors.join("; ")}). Deploy was stopped so your existing package dependencies aren't overwritten.`);Wa.set(n,i)}const r=await py(i.pubspecYaml,e),s=q_(i.pubspecYaml,r.overrides),o=W_(s.yaml,r.additions);return r.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>`${a}: ${r.additions[a]||"any"}`).join(", "),r.sdk.dartSdkFloor?`(resolved for Dart ${r.sdk.dartSdkFloor})`:""),r.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:s.overridden,warnings:r.warnings,remoteFiles:i.files}}function E0(t){const e=[],n=[];t.content.length>5e4&&n.push("Code file is large (>50KB). This may take longer to commit."),t.content.length>1e5&&e.push("Code file is too large (>100KB). Consider splitting into smaller components.");const i=t.content.split(` +`).length;i>500&&n.push(`Code has ${i} lines. Consider breaking it into smaller widgets.`),t.content.includes("setState")&&t.codeType===J.ACTION&&n.push("Using setState in a Custom Action may not work as expected. Consider using a Custom Widget."),t.content.includes("dynamic")&&!t.content.includes("?")&&n.push('Code uses "dynamic" types. Consider adding explicit types for better null safety.'),t.content.match(/Color\(0xFF[0-9A-Fa-f]{6}\)/)&&n.push("Code contains hardcoded colors. Consider using FlutterFlowTheme.of(context) for theme consistency.");const r=t.content.match(/print\s*\(/g);r&&r.length>3&&n.push(`Code contains ${r.length} print statements. Consider removing debug prints before committing.`);const s=E_(t.content);if(s&&e.push(`FlutterFlow cannot format this code - ${s}. Fix or regenerate before committing.`),t.codeType===J.WIDGET){const o=lh(t.content),a=y_(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=`${ch(o[0])}`;e.push(`Widget class name "${o[0]}" does not match the file name "${t.fileName}". FlutterFlow derives the widget from the file name, so it will report "No widget ${a} found". Rename the file to "${l}" or the class to match before committing.`)}}return{canProceed:e.length===0,issues:e,warnings:n}}function zh(t,e={}){const{artifactType:n="CustomWidget",artifactName:i="GeneratedCode",fileName:r}=e,s=v_(t);let o=r||i;if(n==="CustomFunction")o="custom_functions.dart";else if(n==="CustomWidget"){const u=lh(s)[0],c=u?ch(u):null;c&&o!==c?(console.warn(`Commit file name "${o}" does not match declared widget class "${u}"; renaming to "${c}" so FlutterFlow can find the widget.`),o=c):o.endsWith(".dart")||(o+=".dart")}else o.endsWith(".dart")||(o+=".dart");let a=J.CODE_FILE;switch(n){case"CustomAction":a=J.ACTION;break;case"CustomWidget":a=J.WIDGET;break;case"CustomFunction":a=J.FUNCTION;break;case"CustomClass":case"CodeFile":a=J.CODE_FILE;break}let l="";return a===J.WIDGET?l=`// Automatic FlutterFlow imports import '/flutter_flow/flutter_flow_theme.dart'; import '/flutter_flow/flutter_flow_util.dart'; import 'package:flutter/material.dart'; @@ -111,15 +111,15 @@ import '/flutter_flow/lat_lng.dart'; import '/flutter_flow/place.dart'; import '/flutter_flow/uploaded_file.dart'; -`),{content:zv(s,l),fileName:o,codeType:a,artifactType:n,artifactName:i}}function S0(t){const e={};for(const n of wl(t))e[n]="";return e}function x0(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 I0(t,e,n,i=new Set,r=""){const s=[],o=Dh.test(e),a=jh.test(e);return n===J.WIDGET&&!o&&!a&&s.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:s.length===0,errors:s}}function js(t){const e=[],n=[];if(!t||t.size===0)return e.push("No files to commit"),{valid:!1,errors:e,warnings:n};const i=new Set(Array.from(t.values()).flatMap(r=>As(r.content||"")));for(const[r,s]of t.entries()){if((!s.content||s.content.trim().length===0)&&e.push(`File ${r} is empty`),s.content&&s.content.length>1e5&&n.push(`File ${r} is very large (>100KB)`),r.endsWith(".dart")){const o=I0(r,s.content,s.type,i,s.artifactName);o.valid||e.push(...o.errors.map(a=>`${r}: ${a}`))}if(r==="pubspec.yaml"){const o=mh(s.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:n}}const ee={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},G={currentState:ee.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=ee.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(ee).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===ee.PREPARING&&(this.startTime=Date.now()),(t===ee.SUCCESS||t===ee.ERROR)&&(this.endTime=Date.now()),typeof window<"u"&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("commitStateChange",{detail:{state:t,commitState:this}})),console.log(`Commit state changed to: ${t}`)},setError(t){this.error=t,this.setState(ee.ERROR)},setSuccess(t){this.result=t,this.setState(ee.SUCCESS)},setProgress(t,e){this.filesProcessed=t,this.totalFiles=e},getElapsedTime(){return this.startTime?(this.endTime||Date.now())-this.startTime:null},isInProgress(){return this.currentState===ee.PREPARING||this.currentState===ee.VALIDATING||this.currentState===ee.PUSHING}};async function k0(t,e,n={}){let{codeType:i="W"}=n;const{pubspecDeps:r={},artifactName:s=e}=n;i==="CustomWidget"&&(i=J.WIDGET),i==="CustomAction"&&(i=J.ACTION),i==="CustomFunction"&&(i=J.FUNCTION),i==="CustomClass"&&(i=J.CODE_FILE),i==="CodeFile"&&(i=J.CODE_FILE),G.reset(),G.setState(ee.PREPARING);try{const o=await Te("flutterflow"),a=await Te("flutterflow_project_id");if(!o||!a)throw new Error("FlutterFlow credentials not configured. Please set your API key and Project ID in the API Keys settings.");if(!Os(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=yt(),u=new hi(o,a,"main",l);G.setState(ee.VALIDATING);const c=new Map,d=i||b0(e,t),f=Uh(e,d);c.set(e,{artifactName:s,content:t,type:d,path:f}),G.setProgress(0,c.size);const h=js(c);if(!h.valid)throw new Error(`Validation failed: -${h.errors.join(` -`)}`);const p=await Hl(u,r),g=p.yaml,m=await Ul(u,c,p.remoteFiles,`Provision ${s} custom class`,g),v=await Dl(m.syncFileMap,m.remoteFiles),E=new Map(m.syncFileMap);E.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),Oe.set("package");const S=await Wl(E),_={project_id:a,zipped_custom_code:S,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};G.setState(ee.PUSHING),G.setProgress(1,c.size),sr(u),Oe.set("push");const b=await jl(u,_);if(b.success)G.setSuccess({fileCount:c.size,projectId:a,warnings:b.errorMap&&b.errorMap.size>0?Array.from(b.errorMap.entries()):[]});else{const k=b.errorMessage||Bl(b.responseCode);throw new Error(k)}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:p.added,unverified:m.unverified,approximate:m.approximate,warnings:b.errorMap?Array.from(b.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),G.setError(o),o instanceof lt?{success:!1,unconfirmed:!0,error:o.message,state:G.currentState}:{success:!1,error:o.message,state:G.currentState}}}async function Wl(t){const e=new JSZip;for(const[n,i]of t.entries())e.file(n,i.content);return e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}async function C0(t,e={}){const{artifactType:n,artifactName:i,fileName:r,pipelineResult:s}=e;console.log(`Starting commit for ${i} (${n})`);let o=!1;const a={projectId:null,endpoint:yt(),artifactType:n,artifactName:i,fileName:r};try{G.setState(ee.PREPARING);const l=qh(t,{artifactType:n,artifactName:i,fileName:r}),u=S0(l.content);console.log("Detected dependencies:",u),G.setState(ee.VALIDATING);const c=await Te("flutterflow"),d=qi||await Te("flutterflow_project_id");if(!c)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!d)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Os(d))throw new Error("Invalid FlutterFlow Project ID format.");a.projectId=d;const f=new Map;f.set(l.fileName,{artifactName:i,content:l.content,type:l.codeType,path:Uh(l.fileName,l.codeType),functionName:l.codeType===J.FUNCTION?i:void 0}),G.setProgress(0,f.size);const h=js(f);if(!h.valid)throw new Error(`File validation failed: -${h.errors.join(` -`)}`);h.warnings.length>0&&console.warn("Validation warnings:",h.warnings),G.setState(ee.PUSHING);const p=yt(),g=new hi(c,d,"main",p),m=await Hl(g,u),v=m.yaml,E=await Ul(g,f,m.remoteFiles,`Provision ${i} custom class`,v);o=E.provisionSucceeded===!0;const S=await Dl(E.syncFileMap,E.remoteFiles),_=new Map(E.syncFileMap);_.set("pubspec.yaml",{content:v,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Oe.set("package");const b=await Wl(_),k={project_id:d,zipped_custom_code:b,uid:`web_${Date.now()}`,branch_name:g.branchName,serialized_yaml:v,file_map:S.fileMapContents,functions_map:S.functionsMapContents};G.setProgress(1,f.size),sr(g),Oe.set("push");const T=await jl(g,k);if(T.success){const x={...x0(l,s),projectId:d};return G.setSuccess({...x,fileCount:f.size,warnings:T.errorMap?Array.from(T.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${l.fileName} to FlutterFlow`,metadata:x,targetIdentity:a,addedDependencies:m.added,unverified:E.unverified,approximate:E.approximate,warnings:T.errorMap?Array.from(T.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}else{const x=T.errorMessage||Bl(T.responseCode),F=new Error(x);throw F.errorMap=T.errorMap,F}}catch(l){console.error("Commit execution failed:",l),G.setError(l);let u=new Map;if(l.errorMap)u=l.errorMap;else if(l.message&&l.message.includes("{"))try{const c=l.message.match(/\{[\s\S]*\}/);if(c){const d=JSON.parse(c[0]);u=new Map(Object.entries(d))}}catch(c){console.warn("Failed to parse error map from commit response:",c)}return l instanceof lt?{success:!1,unconfirmed:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:o?{success:!1,partial:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function A0(t,e={}){const{pipelineResult:n}=e;let i=!1;const r={projectId:null,endpoint:yt(),artifactType:"Bundle",artifactName:t?.title,fileName:t?.fileEntries?`${t.fileEntries.length} artifacts`:"bundle"};try{if(G.setState(ee.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: +`),{content:Vv(s,l),fileName:o,codeType:a,artifactType:n,artifactName:i}}function S0(t){const e={};for(const n of wl(t))e[n]="";return e}function x0(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 I0(t,e,n,i=new Set,r=""){const s=[],o=jh.test(e),a=Uh.test(e);return n===J.WIDGET&&!o&&!a&&s.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:s.length===0,errors:s}}function js(t){const e=[],n=[];if(!t||t.size===0)return e.push("No files to commit"),{valid:!1,errors:e,warnings:n};const i=new Set(Array.from(t.values()).flatMap(r=>As(r.content||"")));for(const[r,s]of t.entries()){if((!s.content||s.content.trim().length===0)&&e.push(`File ${r} is empty`),s.content&&s.content.length>1e5&&n.push(`File ${r} is very large (>100KB)`),r.endsWith(".dart")){const o=I0(r,s.content,s.type,i,s.artifactName);o.valid||e.push(...o.errors.map(a=>`${r}: ${a}`))}if(r==="pubspec.yaml"){const o=vh(s.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:n}}const ee={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},G={currentState:ee.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=ee.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(ee).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===ee.PREPARING&&(this.startTime=Date.now()),(t===ee.SUCCESS||t===ee.ERROR)&&(this.endTime=Date.now()),typeof window<"u"&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("commitStateChange",{detail:{state:t,commitState:this}})),console.log(`Commit state changed to: ${t}`)},setError(t){this.error=t,this.setState(ee.ERROR)},setSuccess(t){this.result=t,this.setState(ee.SUCCESS)},setProgress(t,e){this.filesProcessed=t,this.totalFiles=e},getElapsedTime(){return this.startTime?(this.endTime||Date.now())-this.startTime:null},isInProgress(){return this.currentState===ee.PREPARING||this.currentState===ee.VALIDATING||this.currentState===ee.PUSHING}};async function k0(t,e,n={}){let{codeType:i="W"}=n;const{pubspecDeps:r={},artifactName:s=e}=n;i==="CustomWidget"&&(i=J.WIDGET),i==="CustomAction"&&(i=J.ACTION),i==="CustomFunction"&&(i=J.FUNCTION),i==="CustomClass"&&(i=J.CODE_FILE),i==="CodeFile"&&(i=J.CODE_FILE),G.reset(),G.setState(ee.PREPARING);try{const o=await Te("flutterflow"),a=await Te("flutterflow_project_id");if(!o||!a)throw new Error("FlutterFlow credentials not configured. Please set your API key and Project ID in the API Keys settings.");if(!Os(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=yt(),u=new hi(o,a,"main",l);G.setState(ee.VALIDATING);const c=new Map,d=i||b0(e,t),h=Hh(e,d);c.set(e,{artifactName:s,content:t,type:d,path:h}),G.setProgress(0,c.size);const f=js(c);if(!f.valid)throw new Error(`Validation failed: +${f.errors.join(` +`)}`);const p=await Hl(u,r),g=p.yaml,m=await Ul(u,c,p.remoteFiles,`Provision ${s} custom class`,g),v=await Dl(m.syncFileMap,m.remoteFiles),E=new Map(m.syncFileMap);E.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),Oe.set("package");const S=await Wl(E),_={project_id:a,zipped_custom_code:S,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};G.setState(ee.PUSHING),G.setProgress(1,c.size),sr(u),Oe.set("push");const b=await jl(u,_);if(b.success)G.setSuccess({fileCount:c.size,projectId:a,warnings:b.errorMap&&b.errorMap.size>0?Array.from(b.errorMap.entries()):[]});else{const k=b.errorMessage||Bl(b.responseCode),T=new Error(k);throw T.remoteRefusal=!0,T}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:p.added,unverified:m.unverified,approximate:m.approximate,warnings:b.errorMap?Array.from(b.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),G.setError(o),o instanceof lt?{success:!1,unconfirmed:!0,error:o.message,state:G.currentState}:{success:!1,error:o.message,remoteRefusal:o.remoteRefusal===!0,state:G.currentState}}}async function Wl(t){const e=new JSZip;for(const[n,i]of t.entries())e.file(n,i.content);return e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}async function C0(t,e={}){const{artifactType:n,artifactName:i,fileName:r,pipelineResult:s}=e;console.log(`Starting commit for ${i} (${n})`);let o=!1;const a={projectId:null,endpoint:yt(),artifactType:n,artifactName:i,fileName:r};try{G.setState(ee.PREPARING);const l=zh(t,{artifactType:n,artifactName:i,fileName:r}),u=S0(l.content);console.log("Detected dependencies:",u),G.setState(ee.VALIDATING);const c=await Te("flutterflow"),d=qi||await Te("flutterflow_project_id");if(!c)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!d)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Os(d))throw new Error("Invalid FlutterFlow Project ID format.");a.projectId=d;const h=new Map;h.set(l.fileName,{artifactName:i,content:l.content,type:l.codeType,path:Hh(l.fileName,l.codeType),functionName:l.codeType===J.FUNCTION?i:void 0}),G.setProgress(0,h.size);const f=js(h);if(!f.valid)throw new Error(`File validation failed: +${f.errors.join(` +`)}`);f.warnings.length>0&&console.warn("Validation warnings:",f.warnings),G.setState(ee.PUSHING);const p=yt(),g=new hi(c,d,"main",p),m=await Hl(g,u),v=m.yaml,E=await Ul(g,h,m.remoteFiles,`Provision ${i} custom class`,v);o=E.provisionSucceeded===!0;const S=await Dl(E.syncFileMap,E.remoteFiles),_=new Map(E.syncFileMap);_.set("pubspec.yaml",{content:v,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Oe.set("package");const b=await Wl(_),k={project_id:d,zipped_custom_code:b,uid:`web_${Date.now()}`,branch_name:g.branchName,serialized_yaml:v,file_map:S.fileMapContents,functions_map:S.functionsMapContents};G.setProgress(1,h.size),sr(g),Oe.set("push");const T=await jl(g,k);if(T.success){const x={...x0(l,s),projectId:d};return G.setSuccess({...x,fileCount:h.size,warnings:T.errorMap?Array.from(T.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${l.fileName} to FlutterFlow`,metadata:x,targetIdentity:a,addedDependencies:m.added,unverified:E.unverified,approximate:E.approximate,warnings:T.errorMap?Array.from(T.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}else{const x=T.errorMessage||Bl(T.responseCode),F=new Error(x);throw F.errorMap=T.errorMap,F.remoteRefusal=!0,F}}catch(l){console.error("Commit execution failed:",l),G.setError(l);let u=new Map;if(l.errorMap)u=l.errorMap;else if(l.message&&l.message.includes("{"))try{const c=l.message.match(/\{[\s\S]*\}/);if(c){const d=JSON.parse(c[0]);u=new Map(Object.entries(d))}}catch(c){console.warn("Failed to parse error map from commit response:",c)}return l instanceof lt?{success:!1,unconfirmed:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:o?{success:!1,partial:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:l.message,errorMap:u,remoteRefusal:l.remoteRefusal===!0,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function A0(t,e={}){const{pipelineResult:n}=e;let i=!1;const r={projectId:null,endpoint:yt(),artifactType:"Bundle",artifactName:t?.title,fileName:t?.fileEntries?`${t.fileEntries.length} artifacts`:"bundle"};try{if(G.setState(ee.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: ${t.errors.join(` `)}`);const s=new Map(t.fileEntries.map(b=>[b.fileName,{artifactId:b.artifactId,artifactName:b.artifactName,content:b.content,type:b.type,path:b.path,functionName:b.type===J.FUNCTION?b.artifactName:void 0}]));G.setProgress(0,s.size);const o=js(s);if(!o.valid)throw new Error(`File validation failed: ${o.errors.join(` -`)}`);G.setState(ee.VALIDATING);const a=await Te("flutterflow"),l=qi||await Te("flutterflow_project_id");if(!a)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!l)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Os(l))throw new Error("Invalid FlutterFlow Project ID format.");r.projectId=l,G.setState(ee.PUSHING);const u=yt(),c=new hi(a,l,"main",u),d=await Hl(c,t.dependencies),f=d.yaml,h=await Ul(c,s,d.remoteFiles,`Provision ${t.title} custom classes`,f);i=h.provisionSucceeded===!0;const p=await Dl(h.syncFileMap,h.remoteFiles),g=new Map(h.syncFileMap);g.set("pubspec.yaml",{content:f,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Oe.set("package");const m=await Wl(g),v={project_id:l,zipped_custom_code:m,uid:`web_${Date.now()}`,branch_name:c.branchName,serialized_yaml:f,file_map:p.fileMapContents,functions_map:p.functionsMapContents};G.setProgress(1,s.size),sr(c),Oe.set("push");const E=await jl(c,v);if(E.success){const b={...n,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((k,T)=>k+T.content.length,0),projectId:l};return G.setSuccess({...b,fileCount:s.size,warnings:E.errorMap?Array.from(E.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:b,targetIdentity:r,addedDependencies:d.added,unverified:h.unverified,approximate:h.approximate,warnings:E.errorMap?Array.from(E.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}const S=E.errorMessage||Bl(E.responseCode),_=new Error(S);throw _.errorMap=E.errorMap,_}catch(s){console.error("Bundle commit execution failed:",s),G.setError(s);const o=s.errorMap||new Map;return s instanceof lt?{success:!1,unconfirmed:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:i?{success:!1,partial:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function P0(t,e=[]){const n=ml("architect");try{return await Ss("architect",Ph,fv(t),n,e)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Prompt Architect failed: ${i.message}`)}}async function Us(t,e,n=[],i){const r=hv(t),s=ml("generator",y.bundleSpec);try{return await Ss("generator",e,r,s,n)}catch(o){if(o.isModelArmor||o.isUsageLimit||o.isPipelineCancel)throw o;if(e!==kr){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,o.message),Mw(e,kr,i);try{return await Ss("generator",kr,r,s,n)}catch(a){throw a.isModelArmor||a.isUsageLimit||a.isPipelineCancel?a:new Error(`Code Generator failed: primary (${e}): ${o.message} | fallback (${kr}): ${a.message}`)}}throw new Error(`Code Generator failed: ${o.message}`)}}async function Hs(t,e=null){const n={...ml("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await Ss("review",Fh,pv(t),n)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Code Review failed: ${i.message}`)}}function bs(t,e){const n=document.getElementById(`step${t}-item`),i=document.getElementById(`step${t}-status`);!n||!i||(n.classList.remove("active","completed","error"),i.classList.remove("running","completed","error"),e==="active"?(n.classList.add("active"),i.classList.add("running"),i.innerHTML=` +`)}`);G.setState(ee.VALIDATING);const a=await Te("flutterflow"),l=qi||await Te("flutterflow_project_id");if(!a)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!l)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Os(l))throw new Error("Invalid FlutterFlow Project ID format.");r.projectId=l,G.setState(ee.PUSHING);const u=yt(),c=new hi(a,l,"main",u),d=await Hl(c,t.dependencies),h=d.yaml,f=await Ul(c,s,d.remoteFiles,`Provision ${t.title} custom classes`,h);i=f.provisionSucceeded===!0;const p=await Dl(f.syncFileMap,f.remoteFiles),g=new Map(f.syncFileMap);g.set("pubspec.yaml",{content:h,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Oe.set("package");const m=await Wl(g),v={project_id:l,zipped_custom_code:m,uid:`web_${Date.now()}`,branch_name:c.branchName,serialized_yaml:h,file_map:p.fileMapContents,functions_map:p.functionsMapContents};G.setProgress(1,s.size),sr(c),Oe.set("push");const E=await jl(c,v);if(E.success){const b={...n,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((k,T)=>k+T.content.length,0),projectId:l};return G.setSuccess({...b,fileCount:s.size,warnings:E.errorMap?Array.from(E.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:b,targetIdentity:r,addedDependencies:d.added,unverified:f.unverified,approximate:f.approximate,warnings:E.errorMap?Array.from(E.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}const S=E.errorMessage||Bl(E.responseCode),_=new Error(S);throw _.errorMap=E.errorMap,_.remoteRefusal=!0,_}catch(s){console.error("Bundle commit execution failed:",s),G.setError(s);const o=s.errorMap||new Map;return s instanceof lt?{success:!1,unconfirmed:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:i?{success:!1,partial:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function P0(t,e=[]){const n=ml("architect");try{return await Ss("architect",Fh,hv(t),n,e)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Prompt Architect failed: ${i.message}`)}}async function Us(t,e,n=[],i){const r=pv(t),s=ml("generator",y.bundleSpec);try{return await Ss("generator",e,r,s,n)}catch(o){if(o.isModelArmor||o.isUsageLimit||o.isPipelineCancel)throw o;if(e!==kr){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,o.message),Mw(e,kr,i);try{return await Ss("generator",kr,r,s,n)}catch(a){throw a.isModelArmor||a.isUsageLimit||a.isPipelineCancel?a:new Error(`Code Generator failed: primary (${e}): ${o.message} | fallback (${kr}): ${a.message}`)}}throw new Error(`Code Generator failed: ${o.message}`)}}async function Hs(t,e=null){const n={...ml("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await Ss("review",Rh,gv(t),n)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Code Review failed: ${i.message}`)}}function bs(t,e){const n=document.getElementById(`step${t}-item`),i=document.getElementById(`step${t}-status`);!n||!i||(n.classList.remove("active","completed","error"),i.classList.remove("running","completed","error"),e==="active"?(n.classList.add("active"),i.classList.add("running"),i.innerHTML=` `):e==="completed"?(n.classList.add("completed"),i.classList.add("completed"),i.innerHTML=` @@ -127,12 +127,12 @@ ${o.errors.join(` `):i.innerHTML=` - `)}function Ae(t,e){const n=document.getElementById(`step${t}-loading`),i=document.getElementById(`step${t}-result`);e?(n.classList.remove("hidden"),i.classList.add("hidden"),bs(t,"active")):(n.classList.add("hidden"),i.classList.remove("hidden"),bs(t,"completed"))}function F0(t){const e=document.getElementById(`${t}-content`),n=document.getElementById(`${t}-chevron`);e.classList.contains("open")?(e.classList.remove("open"),n&&(n.style.transform="rotate(0deg)")):(e.classList.add("open"),n&&(n.style.transform="rotate(180deg)"))}function R0(t){nt(parseInt(t.replace("step","")))}function nt(t){for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-item`);a&&a.classList.remove("active")}const e=document.getElementById(`step${t}-item`);e&&e.classList.add("active"),Nn();const n=document.getElementById("ready-state");n&&n.classList.add("hidden");for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-content`);a&&a.classList.add("hidden")}const i=document.getElementById(`step${t}-content`);i&&i.classList.remove("hidden");const r=document.getElementById("stage-title"),s={1:"Prompt Architect",2:"Code Generator",3:"Code Review"};r&&(r.textContent=s[t]||"Active Workflow Stage")}function T0(t){const e=document.getElementById(t);if(!e)return;const n=e.dataset.raw||e.textContent;navigator.clipboard.writeText(n).then(()=>{const r=e.closest(".code-container")?.querySelector(".copy-btn");r&&(r.classList.add("copied"),r.innerHTML=' Copied!',setTimeout(()=>{r.classList.remove("copied"),r.innerHTML=' Copy'},2e3))}).catch(i=>{console.warn("Failed to copy to clipboard:",i)})}function qa(t){const e=za(t);console.log(`Step 1 (Prompt Architect): ${Gt(Ph)}`),console.log(e!==t?`Step 2 (Code Generator): ${Gt(t)} → ${Gt(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${Gt(t)}`),console.log(`Step 3 (Code Review): ${Gt(Fh)}`)}function zh(){return{step1Result:y.step1Result,step2Result:y.step2Result,step3Result:y.step3Result,artifactBundle:y.artifactBundle,bundleReview:y.bundleReview,selectedArtifactId:y.selectedArtifactId}}function $0(t){if(!t)return;Object.assign(y,t),new Set((y.artifactBundle?.artifacts||[]).map(n=>n.id)).has(y.selectedArtifactId)||(y.selectedArtifactId=oi(y.artifactBundle)?.id||null)}const Vh="results-replacement-error";function M0(t,{stage:e=2,runId:n,retry:i}){if(!re(n))return;const r=document.getElementById(Vh);if(!r)return;const s=bh(t),o=document.getElementById("results-replacement-error-title"),a=document.getElementById("results-replacement-error-message"),l=document.getElementById("results-replacement-error-retry"),u=document.getElementById("results-replacement-error-upgrade");o&&(o.textContent=`${Vs[e]||"Regeneration"}: ${s.title}`),a&&(a.textContent=s.message),r.hidden=!1;let c=null;u&&(u.hidden=!s.canUpgrade,s.canUpgrade&&(u.textContent="View plans",u.onclick=()=>di(),c=u)),l&&(l.hidden=s.canUpgrade,s.canUpgrade||(l.onclick=()=>{ql(),typeof i=="function"&&i()},l.textContent="Retry",c=l)),(c||r).focus({preventScroll:!0})}function ql(){const t=document.getElementById(Vh);t&&(t.hidden=!0)}function Gh(t,{previous:e,stage:n,runId:i,retry:r}){re(i)&&(t.isUsageLimit&&un(),$0(e),cr(),nn(!0),ur(),eo(),M0(t,{stage:n,runId:i,retry:r}),rn())}async function Kh(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0;const e=Gs();zl("standardRegenerate",y.step2Result,y.step1Result);const n=document.querySelectorAll(".btn-refine-action"),i=zh();n.forEach(r=>{r.disabled=!0,r.innerHTML=` + `)}function Ae(t,e){const n=document.getElementById(`step${t}-loading`),i=document.getElementById(`step${t}-result`);e?(n.classList.remove("hidden"),i.classList.add("hidden"),bs(t,"active")):(n.classList.add("hidden"),i.classList.remove("hidden"),bs(t,"completed"))}function F0(t){const e=document.getElementById(`${t}-content`),n=document.getElementById(`${t}-chevron`);e.classList.contains("open")?(e.classList.remove("open"),n&&(n.style.transform="rotate(0deg)")):(e.classList.add("open"),n&&(n.style.transform="rotate(180deg)"))}function R0(t){nt(parseInt(t.replace("step","")))}function nt(t){for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-item`);a&&a.classList.remove("active")}const e=document.getElementById(`step${t}-item`);e&&e.classList.add("active"),Nn();const n=document.getElementById("ready-state");n&&n.classList.add("hidden");for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-content`);a&&a.classList.add("hidden")}const i=document.getElementById(`step${t}-content`);i&&i.classList.remove("hidden");const r=document.getElementById("stage-title"),s={1:"Prompt Architect",2:"Code Generator",3:"Code Review"};r&&(r.textContent=s[t]||"Active Workflow Stage")}function T0(t){const e=document.getElementById(t);if(!e)return;const n=e.dataset.raw||e.textContent;navigator.clipboard.writeText(n).then(()=>{const r=e.closest(".code-container")?.querySelector(".copy-btn");r&&(r.classList.add("copied"),r.innerHTML=' Copied!',setTimeout(()=>{r.classList.remove("copied"),r.innerHTML=' Copy'},2e3))}).catch(i=>{console.warn("Failed to copy to clipboard:",i)})}function qa(t){const e=za(t);console.log(`Step 1 (Prompt Architect): ${Gt(Fh)}`),console.log(e!==t?`Step 2 (Code Generator): ${Gt(t)} → ${Gt(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${Gt(t)}`),console.log(`Step 3 (Code Review): ${Gt(Rh)}`)}function Vh(){return{step1Result:y.step1Result,step2Result:y.step2Result,step3Result:y.step3Result,artifactBundle:y.artifactBundle,bundleReview:y.bundleReview,selectedArtifactId:y.selectedArtifactId}}function $0(t){if(!t)return;Object.assign(y,t),new Set((y.artifactBundle?.artifacts||[]).map(n=>n.id)).has(y.selectedArtifactId)||(y.selectedArtifactId=oi(y.artifactBundle)?.id||null)}const Gh="results-replacement-error";function M0(t,{stage:e=2,runId:n,retry:i}){if(!re(n))return;const r=document.getElementById(Gh);if(!r)return;const s=Eh(t),o=document.getElementById("results-replacement-error-title"),a=document.getElementById("results-replacement-error-message"),l=document.getElementById("results-replacement-error-retry"),u=document.getElementById("results-replacement-error-upgrade");o&&(o.textContent=`${Vs[e]||"Regeneration"}: ${s.title}`),a&&(a.textContent=s.message),r.hidden=!1;let c=null;u&&(u.hidden=!s.canUpgrade,s.canUpgrade&&(u.textContent="View plans",u.onclick=()=>di(),c=u)),l&&(l.hidden=s.canUpgrade,s.canUpgrade||(l.onclick=()=>{ql(),typeof i=="function"&&i()},l.textContent="Retry",c=l)),(c||r).focus({preventScroll:!0})}function ql(){const t=document.getElementById(Gh);t&&(t.hidden=!0)}function Kh(t,{previous:e,stage:n,runId:i,retry:r}){re(i)&&(t.isUsageLimit&&un(),$0(e),cr(),nn(!0),ur(),eo(),M0(t,{stage:n,runId:i,retry:r}),rn())}async function Yh(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0;const e=Gs();zl("standardRegenerate",y.step2Result,y.step1Result);const n=document.querySelectorAll(".btn-refine-action"),i=Vh();n.forEach(r=>{r.disabled=!0,r.innerHTML=` - Refining...`});try{ql();const r=Nl(),s=r.id,o=gv({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,artifactId:r.id,userFeedback:"Fix the issues listed in the audit report."});Zs({runId:e}),Ft(2,e),nt(2),Ae(2,!0);const a=await Us(o,t,[],e);if(!re(e))return;y.step2Result=a,Bs(),tn(2,e);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),nt(3),Ft(3,e),Ae(3,!0);const c=await Hs(y.step2Result,y.step1Result);if(!re(e))return;y.step3Result=c,Ds(),tn(3,e),y.artifactBundle?.artifacts?.some(h=>h.id===s)?y.selectedArtifactId=s:y.selectedArtifactId=oi(y.artifactBundle)?.id||null;const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const f=Ls(y.step3Result);ur(u,f)}catch(r){if(console.error("Refinement failed:",r),!re(e))return;const s=Ms(r,{architect:2,generator:2,review:3});Gh(r,{previous:i,stage:s,runId:e,retry:Kh})}finally{n.forEach(r=>{r.disabled=!1,r.textContent="Refine & Regenerate"}),re(e)&&(y.isRunning=!1,rn())}}async function zl(t,e,n){const i=`${_t}/connectFeedback`,r={type:t,code:e,input:n};try{const s=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok){const a=await s.text();return console.error(`callEndpoint failed: ${s.status} ${s.statusText}`,a),{success:!1,status:s.status,error:a}}const o=await s.json();return console.log("Telemetry success:",o),o}catch(s){return console.error("callEndpoint failed:",s),{success:!1,error:s.message}}}function L0(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function Yh(){const t=document.getElementById("ff-error-paste-input"),e=t?.value?.trim();if(!e){t?.focus(),t?.classList.add("ring-2","ring-red-400","border-red-300"),setTimeout(()=>t?.classList.remove("ring-2","ring-red-400","border-red-300"),2e3);return}if(!y.step2Result){Ee("No generated code found. Please run the full pipeline first.","warning");return}if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=Gs();zl("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` + Refining...`});try{ql();const r=Nl(),s=r.id,o=mv({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,artifactId:r.id,userFeedback:"Fix the issues listed in the audit report."});Zs({runId:e}),Ft(2,e),nt(2),Ae(2,!0);const a=await Us(o,t,[],e);if(!re(e))return;y.step2Result=a,Bs(),tn(2,e);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),nt(3),Ft(3,e),Ae(3,!0);const c=await Hs(y.step2Result,y.step1Result);if(!re(e))return;y.step3Result=c,Ds(),tn(3,e),y.artifactBundle?.artifacts?.some(f=>f.id===s)?y.selectedArtifactId=s:y.selectedArtifactId=oi(y.artifactBundle)?.id||null;const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const h=Ls(y.step3Result);ur(u,h)}catch(r){if(console.error("Refinement failed:",r),!re(e))return;const s=Ms(r,{architect:2,generator:2,review:3});Kh(r,{previous:i,stage:s,runId:e,retry:Yh})}finally{n.forEach(r=>{r.disabled=!1,r.textContent="Refine & Regenerate"}),re(e)&&(y.isRunning=!1,rn())}}async function zl(t,e,n){const i=`${_t}/connectFeedback`,r={type:t,code:e,input:n};try{const s=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok){const a=await s.text();return console.error(`callEndpoint failed: ${s.status} ${s.statusText}`,a),{success:!1,status:s.status,error:a}}const o=await s.json();return console.log("Telemetry success:",o),o}catch(s){return console.error("callEndpoint failed:",s),{success:!1,error:s.message}}}function L0(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function Jh(){const t=document.getElementById("ff-error-paste-input"),e=t?.value?.trim();if(!e){t?.focus(),t?.classList.add("ring-2","ring-red-400","border-red-300"),setTimeout(()=>t?.classList.remove("ring-2","ring-red-400","border-red-300"),2e3);return}if(!y.step2Result){Ee("No generated code found. Please run the full pipeline first.","warning");return}if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=Gs();zl("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` - Fixing…`);const s=zh();try{ql();const o=nh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});Sp(),Zs({runId:i}),Ft(2,i),nt(2),Ae(2,!0);const a=await Us(o,n,[],i);if(!re(i))return;y.step2Result=a,Bs(),tn(2,i);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),nt(3),Ft(3,i),Ae(3,!0);const c=await Hs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,Ds(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const f=Ls(y.step3Result);ur(u,f),t&&(t.value="")}catch(o){if(console.error("Fix from errors failed:",o),!re(i))return;const a=Ms(o,{architect:2,generator:2,review:3});Gh(o,{previous:s,stage:a,runId:i,retry:Yh})}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function or(){if(console.log("runThinkingPipeline called"),y.isRunning)return;localStorage.setItem("hasSeenWalkthrough","true");const t=document.getElementById("pipeline-input").value,e=document.getElementById("code-generator-model").value,n=Ne.slice();if(!t.trim()){Ee("Please describe your FlutterFlow widget first.","warning");return}y.isRunning=!0;const i=Gs();try{if(await Oa,!re(i)||(pn.length&&await Promise.allSettled(pn.map(v=>v.job)),!re(i))||!await sw()||!re(i)||(await Q0(),!re(i)))return;const r=za(e);t.length,m0(),y.submittedPrompt=t,y.submittedImages=n.filter(v=>v.url),Ka(!0),qa(r),Nn();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const o=document.getElementById("paywall-exhausted");o&&o.classList.add("hidden"),Zs({prompt:t,runId:i}),Bw(),nt(1),Ft(1,i),Ae(1,!0);const a=y.submittedImages.map(v=>({url:v.url})),l=await P0(t,a);if(!re(i))return;y.step1Result=l,v0(),tn(1,i);const u=document.getElementById("step1-output"),c=li(y.step1Result);u.textContent=c,u.dataset.raw=c,Ae(1,!1),nt(2),Ft(2,i),Ae(2,!0);const d=await Us(y.step1Result,r,a,i);if(!re(i))return;y.step2Result=d,Bs(),tn(2,i);const f=document.getElementById("step2-output"),h=li(y.step2Result);f.textContent=h,f.dataset.raw=h,Ae(2,!1),nt(3),Ft(3,i),Ae(3,!0);const p=await Hs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=p,Ds(),tn(3,i);const g=document.getElementById("step3-output");g.textContent=y.step3Result,Ae(3,!1),cr();const m=Ls(y.step3Result);Dw(),ur(h,m)}catch(r){if(r.isPipelineCancel||console.error("Pipeline failed:",r),!re(i))return;const s=Ms(r,{architect:1,generator:2,review:3});r.isUsageLimit?un():(r.message,za(document.getElementById("code-generator-model").value),void 0),nt(s),Ae(s,!1),yp(r,{stage:s,runId:i}),bs(s,"error")}finally{re(i)&&(y.isRunning=!1,Ka(!1),rn())}}function N0(){const t=document.getElementById("code-generator-model").value,e=[ms,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(i=>i!==t),n=prompt(`Retry with different model? + Fixing…`);const s=Vh();try{ql();const o=ih({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});xp(),Zs({runId:i}),Ft(2,i),nt(2),Ae(2,!0);const a=await Us(o,n,[],i);if(!re(i))return;y.step2Result=a,Bs(),tn(2,i);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),nt(3),Ft(3,i),Ae(3,!0);const c=await Hs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,Ds(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const h=Ls(y.step3Result);ur(u,h),t&&(t.value="")}catch(o){if(console.error("Fix from errors failed:",o),!re(i))return;const a=Ms(o,{architect:2,generator:2,review:3});Kh(o,{previous:s,stage:a,runId:i,retry:Jh})}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function or(){if(console.log("runThinkingPipeline called"),y.isRunning)return;localStorage.setItem("hasSeenWalkthrough","true");const t=document.getElementById("pipeline-input").value,e=document.getElementById("code-generator-model").value,n=Ne.slice();if(!t.trim()){Ee("Please describe your FlutterFlow widget first.","warning");return}y.isRunning=!0;const i=Gs();try{if(await Oa,!re(i)||(pn.length&&await Promise.allSettled(pn.map(v=>v.job)),!re(i))||!await sw()||!re(i)||(await Q0(),!re(i)))return;const r=za(e);t.length,m0(),y.submittedPrompt=t,y.submittedImages=n.filter(v=>v.url),Ka(!0),qa(r),Nn();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const o=document.getElementById("paywall-exhausted");o&&o.classList.add("hidden"),Zs({prompt:t,runId:i}),Bw(),nt(1),Ft(1,i),Ae(1,!0);const a=y.submittedImages.map(v=>({url:v.url})),l=await P0(t,a);if(!re(i))return;y.step1Result=l,v0(),tn(1,i);const u=document.getElementById("step1-output"),c=li(y.step1Result);u.textContent=c,u.dataset.raw=c,Ae(1,!1),nt(2),Ft(2,i),Ae(2,!0);const d=await Us(y.step1Result,r,a,i);if(!re(i))return;y.step2Result=d,Bs(),tn(2,i);const h=document.getElementById("step2-output"),f=li(y.step2Result);h.textContent=f,h.dataset.raw=f,Ae(2,!1),nt(3),Ft(3,i),Ae(3,!0);const p=await Hs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=p,Ds(),tn(3,i);const g=document.getElementById("step3-output");g.textContent=y.step3Result,Ae(3,!1),cr();const m=Ls(y.step3Result);Dw(),ur(f,m)}catch(r){if(r.isPipelineCancel||console.error("Pipeline failed:",r),!re(i))return;const s=Ms(r,{architect:1,generator:2,review:3});r.isUsageLimit?un():(r.message,za(document.getElementById("code-generator-model").value),void 0),nt(s),Ae(s,!1),wp(r,{stage:s,runId:i}),bs(s,"error")}finally{re(i)&&(y.isRunning=!1,Ka(!1),rn())}}function N0(){const t=document.getElementById("code-generator-model").value,e=[ms,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(i=>i!==t),n=prompt(`Retry with different model? Current: ${t} @@ -140,7 +140,7 @@ Options: 1. ${e[0]} 2. ${e[1]} -Enter 1 or 2:`);n==="1"?(document.getElementById("code-generator-model").value=e[0],or()):n==="2"&&(document.getElementById("code-generator-model").value=e[1],or())}async function O0(){const t=Ol();if(!t){Ee("No code to commit. Please run the pipeline first.","warning");return}const e=await Te("flutterflow"),n=await Te("flutterflow_project_id");if(!e||!n){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),Rl();return}if(y.artifactBundle?.artifacts?.length>1){await B0();return}const{artifactType:i,artifactName:r,fileName:s}=Bh(),o=qh(t,{artifactType:i,artifactName:r,fileName:s}),a=E0(o);if(!a.canProceed){Ee(`Pre-commit checks failed: ${a.issues.join("; ")}`,"error");return}Kl(o,a,null,null)}async function B0(){const t=await Te("flutterflow"),e=await Te("flutterflow_project_id");if(!t||!e){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),Rl();return}const n=Xv(y.artifactBundle);if(n.errors.length>0){Ee(`Bundle validation failed: ${n.errors.join("; ")}`,"error");return}const i=new Map(n.fileEntries.map(a=>[a.fileName,{content:a.content,type:a.type,path:a.path}])),r=js(i),s={canProceed:r.valid&&n.errors.length===0,issues:[...n.errors,...r.errors],warnings:[...n.warnings,...r.warnings]};if(!s.canProceed){Ee(`Bundle validation failed: ${s.issues.join("; ")}`,"error");return}const o={content:n.fileEntries.map(a=>`// ${a.fileName} +Enter 1 or 2:`);n==="1"?(document.getElementById("code-generator-model").value=e[0],or()):n==="2"&&(document.getElementById("code-generator-model").value=e[1],or())}async function O0(){const t=Ol();if(!t){Ee("No code to commit. Please run the pipeline first.","warning");return}const e=await Te("flutterflow"),n=await Te("flutterflow_project_id");if(!e||!n){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),Rl();return}if(y.artifactBundle?.artifacts?.length>1){await B0();return}const{artifactType:i,artifactName:r,fileName:s}=Dh(),o=zh(t,{artifactType:i,artifactName:r,fileName:s}),a=E0(o);if(!a.canProceed){Ee(`Pre-commit checks failed: ${a.issues.join("; ")}`,"error");return}Kl(o,a,null,null)}async function B0(){const t=await Te("flutterflow"),e=await Te("flutterflow_project_id");if(!t||!e){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),Rl();return}const n=Qv(y.artifactBundle);if(n.errors.length>0){Ee(`Bundle validation failed: ${n.errors.join("; ")}`,"error");return}const i=new Map(n.fileEntries.map(a=>[a.fileName,{content:a.content,type:a.type,path:a.path}])),r=js(i),s={canProceed:r.valid&&n.errors.length===0,issues:[...n.errors,...r.errors],warnings:[...n.warnings,...r.warnings]};if(!s.canProceed){Ee(`Bundle validation failed: ${s.issues.join("; ")}`,"error");return}const o={content:n.fileEntries.map(a=>`// ${a.fileName} ${a.content}`).join(` `),fileName:`${n.fileEntries.length} files`,codeType:"bundle",artifactType:"Bundle",artifactName:n.title};Kl(o,s,n.dependencies,n)}function D0(t){let e=t.errorMap||new Map;!(e instanceof Map)&&typeof e=="object"&&(e=new Map(Object.entries(e)));let n=`
    @@ -156,16 +156,16 @@ ${a.content}`).join(` Fix Errors & Regenerate -
    `;const i=document.getElementById("step3-output");i&&(i.innerHTML=n,document.getElementById("btn-regenerate-from-error")?.addEventListener("click",()=>{Jh(t.error,e)}))}async function Jh(t,e){if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=Gs(),r=document.getElementById("btn-regenerate-from-error");r&&(r.disabled=!0,r.innerHTML=` +
    `;const i=document.getElementById("step3-output");i&&(i.innerHTML=n,document.getElementById("btn-regenerate-from-error")?.addEventListener("click",()=>{Zh(t.error,e)}))}async function Zh(t,e){if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=Gs(),r=document.getElementById("btn-regenerate-from-error");r&&(r.disabled=!0,r.innerHTML=` Fixing...`);try{let s=`The previous code had the following errors when committing to FlutterFlow: -`;if(e&&e.size>0)for(const[h,p]of e.entries()){const g=El(p);s+=`File: ${h} +`;if(e&&e.size>0)for(const[f,p]of e.entries()){const g=El(p);s+=`File: ${f} Error: ${g} `}else s+=`${t} -`;const o=nh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:s});Zs({runId:i}),Ft(2,i),nt(2),Ae(2,!0);const a=await Us(o,n,[],i);if(!re(i))return;y.step2Result=a,Bs(),tn(2,i);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),nt(3),Ft(3,i),Ae(3,!0);const c=await Hs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,Ds(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const f=Ls(y.step3Result);ur(u,f)}catch(s){if(console.error("Regeneration failed:",s),!re(i))return;const o=Ms(s,{architect:2,generator:2,review:3});s.isUsageLimit&&un(),nt(o),Ae(o,!1),yp(s,{stage:o,runId:i,retry:()=>Jh(t,e)}),bs(o,"error")}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function j0(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const n=await Te("flutterflow"),i=await Te("flutterflow_project_id");n&&i?(t.className="w-2 h-2 rounded-full bg-green-500",e.textContent="FlutterFlow credentials configured",e.className="text-green-600"):n||i?(t.className="w-2 h-2 rounded-full bg-yellow-500",e.textContent="FlutterFlow credentials incomplete",e.className="text-yellow-600"):(t.className="w-2 h-2 rounded-full bg-red-500",e.textContent="FlutterFlow credentials not configured",e.className="text-red-600")}async function Zh(t){try{const e=await fetch(`${_t}/auth/send-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:t})});if(!e.ok)throw new Error(`Failed to send magic link: HTTP ${e.status}`);return e.json()}catch(e){throw console.error("sendMagicLink failed:",{email:t,message:e.message,stack:e.stack}),e}}async function U0(t){try{const n=await(await fetch(`${_t}/auth/verify-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})})).json();if(n.error||!n.email||!n.sessionToken)throw new Error(n.error||"Invalid or expired link");return n}catch(e){throw console.error("verifyMagicLink failed:",{message:e.message,stack:e.stack}),e}}async function H0(t){try{const e=await fetch(`${_t}/auth/refresh-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:t})});if(!e.ok)return console.error("refreshSession: non-OK response",{url:`${_t}/auth/refresh-session`,status:e.status}),null;const n=await e.json();return n.error||!n.email||!n.sessionToken?(console.warn("refreshSession: validation failed",{error:n.error,hasEmail:!!n.email,hasToken:!!n.sessionToken}),null):n}catch(e){return console.error("refreshSession: fetch failed",{url:`${_t}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function td(t,e){const n=Qh(),i=(z.email||n.email)!==t;z.email=t,z.sessionToken=e,z.isVerified=!0,ce=Mn({isLoading:!0}),localStorage.setItem(hs,JSON.stringify({email:t,sessionToken:e})),i&&sp()}function Xh(){z.email=null,z.sessionToken=null,z.isVerified=!1,ce=Mn({isResolved:!0}),localStorage.removeItem(hs),localStorage.removeItem(gs)}function Qh(){try{const t=localStorage.getItem(hs);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(hs),{email:null,sessionToken:null}}}async function W0(){const e=new URLSearchParams(window.location.search).get("token");if(e){window.history.replaceState({},"",window.location.pathname+window.location.hash);try{const{email:n,sessionToken:i}=await U0(e);td(n,i),ep();const r=nd();r&&!window.location.hash&&(window.location.hash=r)}catch(n){nd();const i=n.message||"Sign-in link invalid or expired.";Ee(i,"error"),Ws(),Jn(i,"error")}}else{const{email:n,sessionToken:i}=Qh();if(n&&i){const r=await H0(i);r?td(r.email,r.sessionToken):Xh()}}Vl()}function q0(){try{localStorage.setItem(Na,JSON.stringify({hash:window.location.hash||"#home",ts:Date.now()}))}catch(t){console.warn("rememberSignInReturnSurface: failed to persist return surface:",t)}}function nd(){try{const t=localStorage.getItem(Na);if(localStorage.removeItem(Na),!t)return null;const{hash:e,ts:n}=JSON.parse(t);return!e||typeof n!="number"||Date.now()-n>ky?null:e}catch(t){return console.warn("consumeSignInReturnSurface: failed to read return surface:",t),null}}function Ws(){const t=document.getElementById("signin-modal");if(!t)return;q0(),document.getElementById("signin-email-input")?.removeAttribute("aria-invalid"),Jn(""),He(t)}function ep(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&We(e)}function Jn(t,e){const n=document.getElementById("signin-message");n&&(n.textContent=t||"",n.classList.remove("signin-message-success","signin-message-error"),e&&n.classList.add(`signin-message-${e}`))}async function z0(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),n=Fs(t?.value);if(!n||!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(n)||n.length>254){t?.setAttribute("aria-invalid","true"),Jn("Please enter a valid email address.","error");return}t?.removeAttribute("aria-invalid"),e&&(e.disabled=!0,e.textContent="Sending…");const r=uh(n);r&&Jn(r,"error");try{const s=await Zh(n),o=s?.code===ch;t&&!o&&(t.value=""),t?.setAttribute("aria-invalid",String(o)),Jn(dh(s,n),o?"error":"success"),e&&(e.disabled=!1,e.textContent=o?"Send Sign-in Link":"Sent!",o||setTimeout(()=>{e.textContent==="Sent!"&&(e.textContent="Send Sign-in Link")},2500))}catch(s){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:n,err:s}),Jn("Something went wrong. Please try again.","error"),e&&(e.disabled=!1,e.textContent="Send Sign-in Link")}}function V0(){z.email=null,z.sessionToken=null,z.isVerified=!1,ce=Mn({isResolved:!0}),L_({storage:window.localStorage,onIdentityChanged:Vl,onPlanChanged:zs})}const G0=N_({sendLink:Zh,getEmail:()=>z.email||"",onState:K0});function K0(t){const e=document.getElementById("send-new-link-btn"),n=document.getElementById("send-new-link-msg");if(!e||!n)return;if(t.status==="pending"){e.disabled=!0,e.textContent="Sending…",n.className="acct-access-msg",n.textContent="Sending a fresh sign-in link…";return}if(t.status==="sent"){e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg",n.textContent=dh(t.data,z.email||"")||"Link sent — check your email.";return}e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg error";const i=t.error?.message?`Couldn't send a link right now. ${t.error.message}`:"Couldn't send a link right now. Please try again.";n.textContent=i}async function Y0(){await G0()}function J0(){const t=$_(window.localStorage),e=t.length?`Cleared disposable UI caches: ${t.join(", ")}.`:"Nothing disposable to clear.";Ee(`${e} Your run count, identity and stored keys are kept.`,"info")}function Z0(){const t=document.getElementById("delete-unavailable-modal");t&&He(t,{trigger:document.activeElement})}function X0(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("delete-unavailable-modal");e&&We(e)}function Vl(){const t=z.isVerified&&!!z.email,e=document.getElementById("auth-signedout"),n=document.getElementById("auth-signedin"),i=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),n&&n.classList.toggle("hidden",!t),i&&i.classList.toggle("hidden",t);const r=document.getElementById("auth-user-email");r&&(r.textContent=z.email||"");const s=document.getElementById("access-signed-email");s&&(s.textContent=z.email||""),lw(),zs()}async function tp(){try{if(typeof FingerprintJS>"u"){console.warn("resolveIdentity: FingerprintJS not loaded, skipping");return}const e=await(await FingerprintJS.load()).get(),n=e.visitorId,i=await fetch(Fy,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fingerprint:e.visitorId,cookie_id:n})});if(!i.ok)throw new Error(`Identity check HTTP ${i.status}`);const r=await i.json();if(ht.userId=r.user_id,ht.token=r.identity_token||null,ht.status=r.status,ht.resolved=!0,sessionStorage.setItem(Ay,r.user_id),ht.token&&sessionStorage.setItem(Py,ht.token),r.usage_count!==void 0){const s=gn(),a=(r.usage_month||s)===s?r.usage_count:0;localStorage.setItem(Fn,JSON.stringify({count:a,month:s})),un()}console.log(`Identity resolved: ${r.status} (${r.user_id.slice(0,8)}...) usage: ${r.usage_count??"n/a"}`)}catch(t){console.error("resolveIdentity failed:",t)}}let Wo=null;function Q0(t=5e3){return ht.resolved?Promise.resolve():(Wo||(Wo=tp().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([Wo,new Promise(e=>setTimeout(e,t))]))}function np(){const t=gn();try{const e=localStorage.getItem(Fn);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Fn,month:t,err:e}),localStorage.removeItem(Fn),{count:0,month:t}}}function gn(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function lr(){const t=np();return t.month!==gn()?{count:0,month:gn()}:t}function ew(){const e={count:lr().count+1,month:gn()};return localStorage.setItem(Fn,JSON.stringify(e)),e}function pi(){return!!ce.isLoading}function Tt(){return!!ce.isResolved}function tw(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(ps,e)?e:null}function nw(t){return t&&Object.entries(Sh).find(([,e])=>e===t)?.[0]||null}function Cr(...t){return t.find(e=>e!=null&&e!=="")}function iw(...t){return t.find(e=>e&&typeof e=="object")||{}}function rw(t){const e=t.data&&typeof t.data=="object"?t.data:t,n=iw(e.subscription,e.stripeSubscription,e.currentSubscription,e.customer?.subscriptions?.data?.[0],e.subscriptions?.data?.[0],e.subscriptions?.[0]),i=e.metadata||n.metadata||e.customer?.metadata||{},r=Cr(e.priceId,e.price_id,e.stripePriceId,e.stripe_price_id,n.priceId,n.price_id,n.plan?.id,n.price?.id,n.items?.data?.[0]?.price?.id,n.items?.[0]?.price?.id,n.lines?.data?.[0]?.price?.id),s=Cr(e.status,e.subscriptionStatus,e.subscription_status,n.status,"none"),o=tw(Cr(e.tier,e.plan,e.planId,e.plan_id,e.subscriptionTier,e.subscription_tier,e.product,e.productName,n.tier,n.plan,i.tier,i.plan)),a=Ry.has(String(s).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||nw(r)||(a||l?"professional":"free");return Mn({tier:u,status:s,periodEnd:Cr(e.periodEnd,e.currentPeriodEnd,e.current_period_end,n.current_period_end,n.periodEnd,null),isResolved:!0})}function qs(){return ps[ce.tier]??ps.free}async function sw(){if(z.isVerified&&(!Tt()||pi())&&(await rp({force:!0}),zs()),z.isVerified&&!Tt())return Ee("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=lr(),e=qs();if(t>=e)return ip(t,e,{openModal:!0}),!1;const n=Math.floor(e*.8);if(t>=n){const i=e-t;Ee(`${i} run${i===1?"":"s"} remaining this month.`,"warning")}return!0}function id(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function ip(t,e,n={}){nn(!0);const i=document.getElementById("walkthrough-modal");i&&We(i,{restoreFocus:!1});const r=document.getElementById("ready-state");r&&r.classList.add("hidden");const s=document.getElementById("preview-frame-container");s&&(s.style.display="none");const o=document.getElementById("main-stage-container");o&&o.classList.add("visible");const a=document.getElementById("results-view");a&&a.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar");const l=document.getElementById("pipeline-progress");l&&l.classList.remove("visible");const u=document.getElementById("paywall-exhausted");if(!u){Ee(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),di();return}const c=document.getElementById("paywall-exhausted-text");if(c){const f=ce.tier;f==="free"?c.textContent=`You've used all ${e} free generations this month. Upgrade to Pro for 50 generations/month and access to all AI models.`:c.textContent=`You've used all ${e} generations this month on your ${f} plan. Your limit resets next month.`}const d=document.getElementById("paywall-signin-btn");d&&d.classList.toggle("hidden",z.isVerified),u.classList.remove("hidden"),n.openModal&&di()}function za(t){return ce.tier==="free"&&Nr.includes(t)?ms:t}function ow(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const n=ce.tier,r=!(z.isVerified&&!Tt())&&n==="free";Array.from(e.options).forEach(o=>{const a=Gt(o.value),l=Nr.includes(o.value);o.textContent=l&&r?`${a} (PRO)`:a,o.disabled=!1}),r&&Nr.includes(e.value)&&(e.value=ms),e.disabled=!1,qu.has(e)||(e.addEventListener("change",()=>{Tt()&&ce.tier==="free"&&Nr.includes(e.value)&&(e.value=ms,di()),qa(e.value),kl()}),qu.add(e));let s=document.getElementById("model-selector-free-notice");r?(s||(s=document.createElement("p"),s.id="model-selector-free-notice",s.className="text-xs text-gray-400 mt-1",t.appendChild(s)),s.innerHTML='Free plan — Gemini only. '):s&&s.remove(),qa(e.value)}function Gl(){const t=z.isVerified&&!!z.email,e=t&&pi(),n=!t||Tt(),i=lr(),r=n?i.count:0,s=n?qs():0,o=Math.max(0,s-r),a=`${r} / ${s} runs this month`,l=gl,u=n?ce.tier||"free":null,c=document.getElementById("topbar-credits-count");c&&(e?c.textContent="…":n?c.textContent=String(o):c.textContent="—");const d=document.getElementById("credits-balance");d&&(e?d.textContent="Checking plan…":n?d.textContent=a:d.textContent="Plan check failed");const f=document.getElementById("usage-dialog-tier");f&&(e?f.textContent="Checking…":n?f.textContent=l[u]||"Free":f.textContent="Unavailable");const h=document.getElementById("usage-dialog-status");h&&(e?h.textContent="Verifying your subscription…":n?h.textContent="Runs reset at the start of each month.":h.textContent="Could not verify your subscription. Try again or sign out.");const p=document.getElementById("usage-counter");if(p)if(e&&t)p.textContent="Checking plan…",p.className="text-xs text-gray-500";else if(!n&&t)p.textContent="Plan check failed",p.className="text-xs text-red-600 font-medium";else{p.textContent=a;const g=s>0?r/s:0;p.className=g>=1?"text-xs text-red-600 font-medium":g>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500"}if(!t){const g=document.getElementById("guest-usage-text");if(g){const m=np(),v=m.month===gn()?m.count??0:0;g.textContent=`${v} / ${ps.free} generations used`}}aw()}function aw(){if(!(z.isVerified&&!!z.email))return;const e=pi(),n=Tt(),i=lr(),r=n?i.count:0,s=n?qs():0,o=Math.max(0,s-r),a=n?ce.tier||"free":null,l={free:"Free",professional:"Pro",power:"Power"}[a]||"Free",u=z.email||"",c=u.split("@")[0]||u,d=document.getElementById("acct-avatar");d&&(d.textContent=(u[0]||"?").toUpperCase());const f=document.getElementById("acct-name");f&&(f.textContent=c||"—");const h=document.getElementById("acct-plan-tier"),p=document.getElementById("acct-plan-price"),g=document.getElementById("acct-plan-note"),m=document.getElementById("acct-renewal");if(h&&(h.textContent=e?"Checking…":n?l:"Plan unavailable"),p)if(e)p.textContent="—";else if(!n)p.textContent="—";else if(a==="free")p.textContent="$0 / month";else{const x=Oi(Ni[a]??0,Cl());p.textContent=`${x} / month`}if(g&&(e?g.textContent="Verifying your subscription…":n?a==="free"?g.textContent="No subscription. Upgrade for more generations.":g.textContent="billed monthly through Stripe":g.textContent="Could not verify your subscription. Check billing or sign out."),m){const x=Date.parse(ce.periodEnd||""),F=n&&a!=="free"&&!!ce.periodEnd&&!Number.isNaN(x);if(e)m.textContent="";else if(!n)m.textContent="";else if(a==="free")m.textContent="";else if(F){const $=new Date(x).toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"});m.textContent=`Renews ${$} · reset at the start of each month.`}else m.textContent="Renewal date is not available for this period."}const v=document.getElementById("acct-left-count"),E=document.getElementById("acct-left-limit"),S=document.getElementById("acct-reset-note");v&&(v.textContent=e?"…":n?String(o):"—"),E&&(E.textContent=e?"…":n?String(s):"—"),S&&(e?S.textContent="Checking plan…":n?S.textContent="Runs reset at the start of each month.":S.textContent="Plan check failed. Refresh or manage billing.");const _=document.getElementById("acct-used-count"),b=document.getElementById("acct-meter-fill"),k=document.getElementById("acct-meter-meta"),T=document.getElementById("acct-meter-track");if(_&&(_.textContent=e?"…":n?String(r):"—"),b){const x=n&&s>0?Math.min(100,Math.round(r/s*100)):0;b.style.width=`${x}%`}if(k)if(e)k.textContent="Checking…";else if(!n)k.textContent="Plan check failed";else if(s===0)k.textContent=`${r} of ${s}`;else{const x=Math.round(r/s*100);k.textContent=`${r} of ${s} · ${x}%`}T&&(e?T.setAttribute("aria-label","Checking usage…"):n?T.setAttribute("aria-label",`${r} of ${s} generations used`):T.setAttribute("aria-label","Usage unavailable")),vt()}function un(){if(Gl(),z.isVerified&&(pi()||!Tt())){id();return}const{count:t}=lr(),e=qs();t>=e&&!y.isRunning?ip(t,e):id()}function lw(){Gl()}async function rp(t={}){const e=t.force===!0;if(!z.isVerified||!z.sessionToken){ce=Mn({isResolved:!0});return}ce={...ce,isLoading:!0,error:null};const n=localStorage.getItem(gs);if(!e&&n)try{const{data:i,email:r,ts:s,version:o}=JSON.parse(n);if(o===zu&&r===z.email&&Date.now()-s<300*1e3){ce={...i,isLoading:!1,isResolved:i.isResolved!==!1};return}}catch(i){console.warn("Failed to parse subscription cache:",i,"| raw value:",n)}try{const r=await(await fetch(`${_t}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:z.sessionToken,user_id:ht.userId})})).json();if(r.error){if(["unauthorized","invalid session","expired session"].some(o=>String(r.error).toLowerCase().includes(o))){Xh(),Vl();return}ce=Mn({isResolved:!1,error:r.error});return}ce=rw(r),localStorage.setItem(gs,JSON.stringify({version:zu,data:ce,email:z.email,ts:Date.now()}))}catch(i){console.error("fetchSubscription failed:",i),ce={...ce,isLoading:!1,isResolved:!1,error:i.message}}}function sp(){localStorage.removeItem(gs)}async function cw(t){if(!z.isVerified||!z.sessionToken){op(),Ws();return}if(!Sh[t]){Ee("Invalid plan selected.","error");return}const e=document.getElementById(`checkout-btn-${t}`);e&&(e.disabled=!0,e.textContent="Redirecting…");try{const i=await(await fetch(`${_t}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:z.sessionToken,currency:Cl()})})).json();if(i.error||!i.url)throw new Error(i.error||"Failed to create checkout session");const{url:r}=i;window.location.href=r}catch(n){console.error("startCheckout failed:",n),e&&(e.disabled=!1,e.textContent="Subscribe"),Ee("Could not start checkout. Please try again.","error")}}async function uw(t){if(!z.isVerified||!z.sessionToken){Ws();return}const e=t||document.getElementById("manage-billing-btn"),n=e?e.textContent:"";e&&(e.disabled=!0,e.textContent="Loading…");try{const r=await(await fetch(`${_t}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:z.sessionToken})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to open billing portal");const{url:s}=r;window.location.href=s}catch(i){console.error("openCustomerPortal failed:",i),e&&(e.disabled=!1,e.textContent=n),Ee("Could not open billing portal. Please try again.","error")}}const Es=new Set;function dw(){Es.forEach(t=>t.abort()),Es.clear()}async function Ss(t,e,n,i={},r=[]){const o=new AbortController;Es.add(o);let a=!1;const l=setTimeout(()=>{a=!0,o.abort()},12e4);try{const u=await fetch(Cy,{method:"POST",headers:{"Content-Type":"application/json",...ht.token?{Authorization:`Bearer ${ht.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:ht.userId,step:t,model:e,prompt:n,images:r,context:i})}),c=await u.text();let d={};try{d=c?JSON.parse(c):{}}catch{d={}}if(u.status===429){d.serverCount!==void 0&&(localStorage.setItem(Fn,JSON.stringify({count:d.serverCount,month:gn()})),un());const p=new Error(d.message||"Monthly usage limit reached. Upgrade to continue.");throw p.isUsageLimit=!0,p.pipelineStep=t,p}const f=Ev(d,t);if(f)throw f;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(d),"content type:",typeof d.content),!u.ok)throw new Error(`${d.message||d.error||"BuildShip pipeline error"} (HTTP ${u.status})`);if(t==="generator")if(d.usage_status==="success"&&Number.isFinite(d.usage_count)){const p=gn();(d.usage_month||p)===p&&(localStorage.setItem(Fn,JSON.stringify({count:d.usage_count,month:p})),un())}else ew(),un();let h=d.output||d.content;if(!h){const p=c?` (body: ${c.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${p}`)}return Array.isArray(h)&&(h=h.map(p=>typeof p=="string"?p:p.text||"").join("")),typeof h!="string"&&(h=JSON.stringify(h)),h}catch(u){if(u.name==="AbortError"){if(a)throw new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`);const c=new Error(`BuildShip ${t} request cancelled`);throw c.isPipelineCancel=!0,c}throw u instanceof TypeError?new Error(`BuildShip unreachable: ${u.message}`):u}finally{clearTimeout(l),Es.delete(o)}}let Va=!1;function fw(){const e=new URLSearchParams(window.location.search).get("checkout");return e==="success"?(window.history.replaceState({},"",window.location.pathname+window.location.hash),sp(),Va=!0):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname+window.location.hash),Ee("Checkout cancelled.","info")),e}function hw(){if(!Va)return;Va=!1;const t=ce.tier!=="free";Ee(t?"Subscription active! Your plan is live.":"Checkout complete — confirming your subscription. Check Manage billing if it does not update.",t?"success":"info")}function zs(){const t=z.isVerified&&!!z.email,e=ce.tier,n=t&&pi(),i=!t||Tt(),r=document.getElementById("subscription-tier-badge");if(r){const a=gl,l={free:"bg-gray-100 text-gray-600",professional:"bg-indigo-100 text-indigo-700",power:"bg-purple-100 text-purple-700",unresolved:"bg-red-50 text-red-600"};r.textContent=n?"Checking…":i?a[e]||"Free":"Plan unavailable",r.className=`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${i?l[e]||l.free:l.unresolved}`}const s=document.getElementById("upgrade-prompt");s&&s.classList.toggle("hidden",!t||n||!i||e!=="free");const o=document.getElementById("manage-billing-btn");o&&o.classList.toggle("hidden",!t||n||i&&e==="free"),pw(i?e:null),ow(),kl(),un(),xp()}function pw(t){const e=["bg-gray-100","text-gray-500","cursor-default"];Object.entries({professional:{btnId:"checkout-btn-professional",defaultText:"Subscribe"},power:{btnId:"checkout-btn-power",defaultText:"Subscribe"}}).forEach(([r,{btnId:s,defaultText:o}])=>{const a=document.getElementById(s);a&&(r===t?(a.disabled=!0,a.textContent="Current plan",a.classList.add(...e)):(a.disabled=!1,a.textContent=o,a.classList.remove(...e)))});const i=document.getElementById("free-tier-current");i&&i.classList.toggle("hidden",t!=="free")}function gw(){document.querySelectorAll(".pm-card[data-tier]").forEach(t=>{const e=t.dataset.tier,n=cv[e];if(!n)return;const i=t.querySelector("ul.pm-features");if(i){i.innerHTML="";for(const r of n){const s=document.createElement("li");s.textContent=r,i.appendChild(s)}}})}function Ga(){const t=Cl(),e=document.getElementById("pro-price"),n=document.getElementById("power-price"),i=document.getElementById("plans-pro-price"),r=document.getElementById("plans-power-price"),s=document.getElementById("pro-price-note"),o=document.getElementById("power-price-note"),a=document.getElementById("plans-pro-price-note"),l=document.getElementById("plans-power-price-note");e&&(e.textContent=Oi(Ni.professional,t)),n&&(n.textContent=Oi(Ni.power,t)),i&&(i.textContent=Oi(Ni.professional,t)),r&&(r.textContent=Oi(Ni.power,t));const u="billed monthly";s&&(s.textContent=u),o&&(o.textContent=u),a&&(a.textContent=u),l&&(l.textContent=u)}function di(){Ga();const t=document.getElementById("pricing-modal");t&&He(t),Hy().then(()=>Ga())}function op(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&We(e)}function Ee(t,e="info"){const n={success:"bg-green-600 text-white",error:"bg-red-600 text-white",warning:"bg-amber-500 text-white",info:"bg-gray-800 text-white"},i=document.createElement("div");i.className=`fixed bottom-6 left-1/2 -translate-x-1/2 px-5 py-3 rounded-lg text-sm font-medium shadow-lg z-50 transition-opacity duration-300 ${n[e]||n.info}`,i.textContent=t,document.body.appendChild(i),setTimeout(()=>{i.style.opacity="0",setTimeout(()=>i.remove(),300)},3500)}document.addEventListener("DOMContentLoaded",async()=>{ov(),hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),mw(),window.__heroField=Q_(),window.__pipelineLogo=iy(),Ih=xy({onSubmit:or}),Oa=(async()=>{try{await W0(),fw(),await rp()}catch(n){console.warn("Startup auth/subscription initialization failed:",n)}})(),await Oa,hw(),zs(),Ga(),gw(),await _0(),h0();const t=document.getElementById("flutterflow-endpoint-select");if(t){const n=yt();t.value=n}Oh(),tp();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{en===2&&e.value.trim().length>0&&(Tl(),Ns())}),e.addEventListener("blur",()=>{const n=document.getElementById("walkthrough-modal");en===2&&n&&He(n)}),e.addEventListener("keydown",n=>{if(n.key==="Tab"){const i=document.getElementById("walkthrough-modal");en===2&&i&&setTimeout(()=>{He(i)},100)}})),window.addEventListener("commitStateChange",n=>{const{state:i}=n.detail;i===ee.PREPARING||i===ee.VALIDATING||i===ee.PUSHING?(Oe.phaseId||fp(),sd(i)):(i===ee.SUCCESS||i===ee.ERROR)&&(sd(i),setTimeout(Jl,1e3))}),ic()});function mw(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function vw(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Nn),document.addEventListener("keydown",Nn))}function Nn(){const t=document.getElementById("preview-frame-container"),e=document.getElementById("main-stage-container"),n=document.getElementById("ready-state");t&&(t.style.display="none"),e&&e.classList.add("visible"),n&&n.classList.remove("hidden");const i=document.getElementById("welcome-video-player");i&&i.removeEventListener("click",Nn),document.removeEventListener("keydown",Nn),Oh()}let zi=null;async function _w(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++Ju,n=()=>e===Ju,i=await Te("flutterflow"),r=await Te("flutterflow_project_id");if(n()){if(!i){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const o=await new hi(i,"","main",yt()).listProjects();if(!n())return;if(!o||o.length===0){t.innerHTML='';return}t.innerHTML='',o.forEach(a=>{const l=document.createElement("option");l.value=a.id||a.projectId||"",l.textContent=a.name||a.projectName||`Project ${a.id}`,t.appendChild(l)}),r&&(t.value=r)}catch(s){if(!n())return;console.error("Failed to load projects for deploy:",s),t.innerHTML=''}}}function yw(){return document.getElementById("confirm-project-select")?.value?.trim()||null}function Kl(t,e,n,i=null){zi={codeInfo:t,checks:e,deps:n,bundlePlan:i},document.getElementById("confirm-file-name").textContent=t.fileName,document.getElementById("confirm-artifact-type").textContent=t.artifactType,document.getElementById("confirm-file-size").textContent=`${(t.content.length/1024).toFixed(1)} KB`,document.getElementById("confirm-line-count").textContent=i?`${i.fileEntries.length} files`:t.content.split(` -`).length,_w();const r=document.getElementById("confirm-deps-list"),s=document.getElementById("confirm-deps-section");n&&Object.keys(n).length>0?(r.innerHTML=Object.entries(n).map(([u,c])=>{const d=c?`at least ${Qt(c)}`:"version resolved from your project";return`
  • • ${Qt(u)}: ${d}
  • `}).join(""),s.classList.remove("hidden")):s.classList.add("hidden");const o=document.getElementById("confirm-warnings-list"),a=document.getElementById("confirm-warnings-section");e.warnings&&e.warnings.length>0?(o.innerHTML=e.warnings.map(u=>`
  • • ${Qt(u)}
  • `).join(""),a.classList.remove("hidden")):a.classList.add("hidden"),document.getElementById("confirm-code-preview").textContent=t.content,document.getElementById("code-preview-content").classList.add("hidden"),document.getElementById("code-preview-chevron").style.transform="rotate(0deg)";const l=document.getElementById("commit-confirm-modal");l&&He(l)}function ap(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&We(e),zi=null}function ww(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&We(e);const n=["success-message","success-project-id","success-file-name","success-artifact-type","success-time","success-size"];for(const s of n){const o=document.getElementById(s);o&&(o.textContent="")}const i=document.getElementById("success-warnings-section");i&&i.classList.add("hidden");const r=document.getElementById("success-warnings-list");r&&(r.innerHTML="")}function lp(t){const e=(m,v)=>{const E=document.getElementById(m);E&&(E.textContent=v||"")},n=t.metadata?.fileName||"",i=t.metadata?.projectId||"",r=t.metadata?.artifactType||"",s=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",i),e("success-file-name",n),e("success-artifact-type",r),e("success-time",s),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&i&&(u.href=`https://app.flutterflow.io/project/${i}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),f=t.unverified||[],h=t.approximate||[],p=t.warnings||[];(p.length>0||f.length>0||h.length>0)&&c&&d&&(d.innerHTML=[...f.map(m=>`
  • Not verified before deploying: ${q(String(m))}
  • `),...h.map(m=>`
  • Verified approximately: ${q(String(m))}
  • `),...p.map(([m,v])=>`
  • ${q(m)}: ${q(String(v))}
  • `)].join(""),c.classList.remove("hidden"));const g=document.getElementById("commit-success-modal");g&&He(g)}function cp(t){Jl(),D0(t),Yl(t,{heading:"Deploy failed",title:"FlutterFlow refused this deploy — nothing was confirmed written.",guidance:"Review the error and any per-file outcomes above, fix them in your code or in FlutterFlow, then deploy again. A refusal is definitive: no part of this deploy was applied, so retrying is safe once the problem is fixed."})}function Yl(t,{heading:e,title:n,guidance:i}){const r=t.targetIdentity||{},s=document.getElementById("commit-terminal-modal");if(!s)return!1;const o=(h,p)=>{const g=document.getElementById(h);g&&(g.textContent=p||"")};o("terminal-heading",e),o("terminal-title",n),o("terminal-message",t.error||t.message||"");const a=document.getElementById("terminal-identity-list");if(a){const h=[["Project",r.projectId||t.metadata?.projectId],["Endpoint",r.endpoint],["File",r.fileName||t.metadata?.fileName],["Artifact",r.artifactType||t.metadata?.artifactType]];a.innerHTML=h.map(([p,g])=>`
    ${q(p)}:${q(String(g??"—"))}
    `).join("")}const l=document.getElementById("terminal-file-outcomes");let u=t.errorMap;u&&!(u instanceof Map)&&(u=new Map(Object.entries(u))),l&&u&&u.size>0?(l.innerHTML=[...u.entries()].map(([h,p])=>`
  • ${q(h)}: ${q(El(p))}
  • `).join(""),l.classList.remove("hidden")):l&&l.classList.add("hidden");const c=document.getElementById("terminal-guidance");c&&(c.innerHTML=i);const d=document.getElementById("terminal-open-ff-link"),f=r.projectId||t.metadata?.projectId;return d&&(d.href=f?`https://app.flutterflow.io/project/${f}`:"https://app.flutterflow.io/"),He(s),!0}function up(t){Yl(t,{heading:"Deploy partially applied",title:"Some custom classes reached FlutterFlow, but the deploy did not fully complete.",guidance:"The custom classes the runner confirmed are already in your project and are not lost. Review the per-file errors above, fix them in FlutterFlow or regenerate, then deploy again. Open the project to see exactly what landed."})}function dp(t){Yl(t,{heading:"Deploy outcome not yet known",title:"This browser stopped waiting before the FlutterFlow server reported a result.",guidance:"The deploy may still be finishing on the server — it was not cancelled. Open your FlutterFlow project and confirm whether the class landed before retrying, so you do not push a duplicate or build on top of an unknown state."})}function bw(t){t&&t.target!==t.currentTarget||We(document.getElementById("commit-terminal-modal"))}function Ew(){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 rd={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}},Sw=[{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..."}],Oe={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&&(Eu(e,!0,"Deploying to FlutterFlow"),He(e)),this.set("prepare")},set(t,e=null){if(!(!rd[t]||t===this.phaseId)){if(!this.sequence.includes(t)){const n=this.sequence.indexOf("package");this.sequence.splice(n===-1?this.sequence.length:n,0,t)}this.phaseId=t,this.phaseStartedAt=Date.now(),this.substatus=e,this.liveSubstatus=!1,this.render(),this.timer&&clearInterval(this.timer),t!=="done"&&(this.timer=setInterval(()=>this.render(),500))}},setSubstatus(t){t&&(this.liveSubstatus=!0,this.substatus=t,this.render())},render(){const t=rd[this.phaseId];if(!t)return;const e=(Date.now()-this.phaseStartedAt)/1e3,n=t.start+(t.end-t.start)*(1-Math.exp(-e/25));if(this.phaseId==="provision"&&!this.liveSubstatus){const o=Sw.filter(a=>e>=a.after).pop();o&&(this.substatus=o.text)}const i=this.sequence.indexOf(this.phaseId),s=[`Step ${i===-1?1:i+1} of ${this.sequence.length}`];e>=5&&s.push(xw(e)),hp(this.phaseId==="done"?100:n,t.message,s.join(" · "),this.substatus)},stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.phaseId=null;const t=document.getElementById("commit-progress-overlay");t&&(Eu(t,!1),We(t,{force:!0,restoreFocus:!1}))}};function xw(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 fp(t){Oe.start(t)}function Jl(){Oe.stop()}function hp(t,e,n,i=null){const r=document.getElementById("commit-progress-bar"),s=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");r&&(r.style.width=`${Math.round(t*10)/10}%`),s&&(s.textContent=e),o&&(o.textContent=n),a&&(a.textContent=i||"",a.classList.toggle("hidden",!i))}function sd(t){const e={[ee.PREPARING]:"prepare",[ee.VALIDATING]:"validate",[ee.PUSHING]:"project",[ee.SUCCESS]:"done"};if(t===ee.ERROR){Oe.timer&&clearInterval(Oe.timer),Oe.timer=null,hp(100,"Failed","Error occurred");return}const n=e[t];n&&Oe.set(n)}function Iw(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===J.CODE_FILE):t.codeInfo?.codeType===J.CODE_FILE}let pp=!1;function gp(t){pp=t;const e=document.querySelector("#commit-confirm-modal button[data-deploy-confirm]");e&&(e.disabled=t),[...document.querySelectorAll("[data-deploy-start]"),...document.querySelectorAll("#btn-deploy-to-ff")].forEach(i=>{i.disabled=t})}function od(t){Jl(),gp(!1);const e=yh(t);e===Xe.COMMITTED?lp(t):e===Xe.PARTIAL?up(t):e===Xe.UNCONFIRMED?dp(t):cp(t)}async function kw(){if(!zi){console.error("No pending commit data");return}if(pp){console.warn("Deploy already in flight; ignoring duplicate confirm.");return}const t=zi;if(zi=null,qi=yw(),ap(),gp(!0),fp({withProvisioning:Iw(t)}),t.bundlePlan){const o=await A0(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});qi=null,od(o);return}const{codeInfo:e}=t,{artifactType:n,artifactName:i,fileName:r}=Bh(),s=await C0(e.content,{artifactType:n,artifactName:i,fileName:r,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});qi=null,od(s)}window.runThinkingPipeline=or;window.toggleStep=R0;window.toggleSection=F0;window.selectWorkflowStep=nt;window.copyCode=T0;window.retryWithDifferentModel=N0;window.openApiKeysModal=Rl;window.closeApiKeysModal=Lh;window.openComposerSettings=n0;window.closeComposerSettings=i0;window.walkthroughConnectAccount=t0;window.closeWalkthroughModal=s0;window.openWalkthroughModal=r0;window.advanceWalkthrough=Tl;window.commitToFlutterFlow=k0;function Cw(){const t=document.getElementById("pipeline-input");t&&t.focus()}function Aw(){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=Cw;window.openModelSelector=Aw;window.handlePromptImageSelect=jy;window.removePromptImage=Uy;window.saveApiKeys=l0;window.validateFlutterFlowConnection=Ml;window.clearAllApiKeys=c0;window.toggleKeyVisibility=g0;window.handleWelcomeVideoEnd=vw;window.dismissWelcomeVideo=Nn;window.initiateCommitToFlutterFlow=O0;window.updateFlutterFlowCredentialStatus=j0;window.openCommitConfirmModal=Kl;window.closeCommitConfirmModal=ap;window.closeCommitSuccessModal=ww;window.closeCommitTerminalModal=bw;window.showCommitPartialModal=up;window.showCommitUnconfirmedModal=dp;window.showCommitSuccessModal=lp;window.showCommitFailureModal=cp;window.toggleCodePreview=Ew;window.confirmCommitToFlutterFlow=kw;window.runRefinement=Kh;window.regenerateFromPastedErrors=Yh;window.clearErrorInput=L0;window.setFlutterFlowEndpoint=e0;window.getFlutterFlowEndpoint=yt;window.commitProgress=Oe;window.openSignInModal=Ws;window.closeSignInModal=ep;window.handleMagicLinkRequest=z0;window.handleSignOut=V0;window.handleSendNewLink=Y0;window.handleClearCache=J0;window.handleDeleteAccount=Z0;window.closeDeleteUnavailableModal=X0;window.startCheckout=cw;window.openCustomerPortal=uw;window.openPricingModal=di;window.closePricingModal=op;let jr=null,mp=null,On={1:"pending",2:"pending",3:"pending"},Zl=1,Xl=null;const Vs={1:"Prompt Architect",2:"Code Generator",3:"Code Review"},Pw={1:"Understanding your prompt",2:"Generating Dart code",3:"Running the code audit"},Fw={1:"Prompt understood",2:"Dart code generated",3:"Code audit complete"};function Gs(){return y.runId+=1,y.runId}function re(t){return t===void 0||t===y.runId}function Rw(){y.runId+=1}function Ql(t){return document.getElementById(`pdot-${t}`)}function Ka(t){const e=document.getElementById("btn-run-pipeline")||document.getElementById("hero-send");e&&(e.disabled=t,e.classList.toggle("is-busy",t),t?e.setAttribute("aria-busy","true"):e.removeAttribute("aria-busy"))}function Ks(t){const e=document.getElementById("pipeline-progress");e&&(e.dataset.runState=t)}function Rn(t,e){On[t]=e;const n=Ql(t);if(!n)return;n.dataset.state=e,n.disabled=e==="pending"||e==="skipped";const i=Vs[t],r={pending:"not started",active:"in progress",done:"complete",failed:"failed",skipped:"not run"};n.setAttribute("aria-label",`Step ${t} of 3, ${i}: ${r[e]||e}`),e==="active"?n.setAttribute("aria-current","step"):n.removeAttribute("aria-current")}function Tw(){return[1,2,3].filter(t=>On[t]==="done").length}function Ys(){const t=document.getElementById("pipeline-progress-fill");t&&(t.style.width=`${Tw()/3*100}%`);const e=document.getElementById("progress-stage-count");e&&(e.textContent=`Step ${Zl} of 3`)}function Js(t,{done:e=!1}={}){const n=document.getElementById("progress-title-text"),i=document.getElementById("progress-substep-text"),r=On[t],s=e||r==="done";if(n&&(n.textContent=s?Fw[t]:Pw[t]),i){const o=s?" — complete":r==="failed"?" — stopped":"";i.textContent=`Step ${t} of 3 — ${Vs[t]}${o}`}}function $w(t){On[t]==="pending"||On[t]==="skipped"||(Xl=t,[1,2,3].forEach(e=>{const n=Ql(e);n&&n.setAttribute("aria-pressed",String(e===t))}),Js(t))}function ec(){Xl=null,[1,2,3].forEach(t=>{const e=Ql(t);e&&e.removeAttribute("aria-pressed")})}function vp(t){const e=document.getElementById("pipeline-note");e&&(e.textContent=t||"",e.hidden=!t)}function Mw(t,e,n){re(n)&&vp(`${Gt(t)} did not answer. Continuing on ${Gt(e)}.`)}function tc(){const t=document.getElementById("pipeline-failure");if(!t)return;t.hidden=!0;const e=document.getElementById("pipeline-failure-actions");e&&e.replaceChildren()}const Lw=1120;function Nw(){const t=getComputedStyle(document.documentElement).getPropertyValue("--t-morph").trim(),e=Number.parseFloat(t);return Number.isFinite(e)&&e>0?e:Lw}let Qn=null,Ur=null;function Ow(){return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0}function dn(){if(Ur){try{Ur.cancel()}catch{}Ur=null}Qn&&(Qn.remove(),Qn=null),window.removeEventListener("resize",dn)}function _p(t,e){if(dn(),Ow()||!t||!e||!document.body||typeof Element.prototype.animate!="function")return;const n=t.getBoundingClientRect(),i=e.getBoundingClientRect();if(!n.width||!n.height||!i.width||!i.height)return;const r=document.createElement("div");r.className="composer-morph",r.setAttribute("aria-hidden","true"),r.style.cssText=`left:${i.left}px;top:${i.top}px;width:${i.width}px;height:${i.height}px;opacity:0;`,document.body.appendChild(r);const s=n.left+n.width/2-(i.left+i.width/2),o=n.top+n.height/2-(i.top+i.height/2),a=n.width/i.width,l=n.height/i.height,u=`translate(${s}px,${o}px) scale(${a},${l})`,c=r.animate([{transform:u,opacity:0,offset:0,easing:"cubic-bezier(.2,0,0,1)"},{transform:u,opacity:1,offset:.14,easing:"cubic-bezier(.4,0,.2,1)"},{transform:`translate(${s}px,${o}px) scale(${a*.93},${l*.93})`,opacity:1,offset:.28,easing:"cubic-bezier(.32,1.38,.5,1)"},{transform:"translate(0px,0px) scale(1,1)",opacity:1,offset:1}],{duration:Nw(),fill:"both"});Qn=r,Ur=c,window.addEventListener("resize",dn),c.onfinish=()=>{if(Qn!==r)return;const d=r.animate([{opacity:1},{opacity:0}],{duration:260,fill:"forwards"});d.onfinish=()=>{Qn===r&&dn()}}}function Bw(){const e=document.getElementById("composer")?.getBoundingClientRect();e&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{_p({getBoundingClientRect:()=>e},document.getElementById("main-stage-container"))})})}function Dw(){_p(document.getElementById("pipeline-progress"),document.getElementById("main-stage-container"))}window.addEventListener("hashchange",dn);window.addEventListener("popstate",dn);function Zs(t={}){const{prompt:e=null,runId:n}=t;if(!re(n))return;Qs(),nn(!0);const i=document.getElementById("pipeline-progress"),r=document.getElementById("results-view"),s=document.getElementById("ready-state");if(s&&s.classList.add("hidden"),r&&r.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),i&&i.classList.add("visible"),Ks("running"),e!==null){const a=document.getElementById("pipeline-submitted-prompt");a&&(a.textContent=e)}mp=Date.now();const o=document.getElementById("progress-elapsed");o&&(o.textContent="0s"),On={1:"pending",2:"pending",3:"pending"},ec(),tc(),vp(""),[1,2,3].forEach(a=>Rn(a,"pending")),Ft(1,n),jw()}function Ft(t,e){re(e)&&(Zl=t,ec(),[1,2,3].forEach(n=>{n===t?Rn(n,"active"):nt&&Rn(n,"pending")}),Js(t),Ys())}function tn(t,e){re(e)&&(Rn(t,"done"),Xl===null&&Js(t,{done:!0}),Ys())}function yp(t,{stage:e=1,runId:n,retry:i=wp}={}){if(!re(n))return;Xs(),Qs(),dn(),Ks("failed"),nn(!0);const r=document.getElementById("pipeline-progress");r&&r.classList.add("visible");const s=document.getElementById("results-view");s&&s.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),Rn(e,"failed"),[1,2,3].forEach(p=>{p>e&&Rn(p,"pending")}),Zl=e,ec(),Js(e),Ys();const o=bh(t),a=document.getElementById("pipeline-failure"),l=document.getElementById("pipeline-failure-title"),u=document.getElementById("pipeline-failure-message"),c=document.getElementById("pipeline-failure-hint"),d=document.getElementById("pipeline-failure-actions");if(!a||!l||!u||!d)return;if(a.dataset.kind=o.kind,l.textContent=`${Vs[e]}: ${o.title}`,u.textContent=o.message,c){const p=o.detail&&o.detail!==o.message?o.detail:"";c.textContent=p,c.hidden=!p}d.replaceChildren();const f=[o.canUpgrade&&{id:"upgrade",label:"View plans",variant:"primary",onClick:()=>di()},o.canRetry&&{id:"retry",label:"Retry",variant:o.canUpgrade?"secondary":"primary",onClick:i},o.canEdit&&{id:"edit",label:"Edit prompt",variant:"secondary",onClick:Ya}].filter(Boolean);!o.canEdit&&!o.canRetry&&f.push({id:"edit",label:"Back to prompt",variant:"secondary",onClick:Ya}),f.forEach(p=>{const g=document.createElement("button");g.type="button",g.textContent=p.label,g.dataset.action=p.id,g.dataset.variant=p.variant,g.addEventListener("click",p.onClick),d.appendChild(g)}),a.hidden=!1;const h=d.querySelector("button");h&&h.focus({preventScroll:!0})}function Ya(){Rw(),dw(),y.isRunning=!1,Ka(!1),rn(),Ks("settled"),dn(),Xs(),Qs(),tc();const t=document.getElementById("pipeline-progress");t&&t.classList.remove("visible"),nn(!1);const e=document.getElementById("pipeline-input");e&&(y.submittedPrompt&&(e.value=y.submittedPrompt,e.dispatchEvent(new Event("input",{bubbles:!0}))),e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length))}function wp(){const t=document.getElementById("pipeline-input");t&&y.submittedPrompt&&(t.value=y.submittedPrompt,t.dispatchEvent(new Event("input",{bubbles:!0}))),Ne=y.submittedImages.slice(),cn(),tc(),or()}function jw(){Xs(),jr=setInterval(()=>{const t=(Date.now()-mp)/1e3,e=document.getElementById("progress-elapsed");e&&(e.textContent=`${Math.floor(t)}s`)},250)}function Xs(){jr&&(clearInterval(jr),jr=null)}let Vi=null;function Qs(){Vi&&(clearTimeout(Vi),Vi=null)}function cr(){Xs(),Qs(),Ks("settled"),Ys();const t=document.getElementById("pipeline-progress-fill");Vi=setTimeout(()=>{Vi=null;const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function Tn(t,e=""){const n={pass:'',warning:'',fail:'',info:''};return``}function bp(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function Uw(){return p_({bundle:y.artifactBundle,reviewResult:y.step3Result})}function Hw(t){return` +`;const o=ih({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:s});Zs({runId:i}),Ft(2,i),nt(2),Ae(2,!0);const a=await Us(o,n,[],i);if(!re(i))return;y.step2Result=a,Bs(),tn(2,i);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),nt(3),Ft(3,i),Ae(3,!0);const c=await Hs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,Ds(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const h=Ls(y.step3Result);ur(u,h)}catch(s){if(console.error("Regeneration failed:",s),!re(i))return;const o=Ms(s,{architect:2,generator:2,review:3});s.isUsageLimit&&un(),nt(o),Ae(o,!1),wp(s,{stage:o,runId:i,retry:()=>Zh(t,e)}),bs(o,"error")}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function j0(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const n=await Te("flutterflow"),i=await Te("flutterflow_project_id");n&&i?(t.className="w-2 h-2 rounded-full bg-green-500",e.textContent="FlutterFlow credentials configured",e.className="text-green-600"):n||i?(t.className="w-2 h-2 rounded-full bg-yellow-500",e.textContent="FlutterFlow credentials incomplete",e.className="text-yellow-600"):(t.className="w-2 h-2 rounded-full bg-red-500",e.textContent="FlutterFlow credentials not configured",e.className="text-red-600")}async function Xh(t){try{const e=await fetch(`${_t}/auth/send-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:t})});if(!e.ok)throw new Error(`Failed to send magic link: HTTP ${e.status}`);return e.json()}catch(e){throw console.error("sendMagicLink failed:",{email:t,message:e.message,stack:e.stack}),e}}async function U0(t){try{const n=await(await fetch(`${_t}/auth/verify-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})})).json();if(n.error||!n.email||!n.sessionToken)throw new Error(n.error||"Invalid or expired link");return n}catch(e){throw console.error("verifyMagicLink failed:",{message:e.message,stack:e.stack}),e}}async function H0(t){try{const e=await fetch(`${_t}/auth/refresh-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:t})});if(!e.ok)return console.error("refreshSession: non-OK response",{url:`${_t}/auth/refresh-session`,status:e.status}),null;const n=await e.json();return n.error||!n.email||!n.sessionToken?(console.warn("refreshSession: validation failed",{error:n.error,hasEmail:!!n.email,hasToken:!!n.sessionToken}),null):n}catch(e){return console.error("refreshSession: fetch failed",{url:`${_t}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function nd(t,e){const n=ep(),i=(z.email||n.email)!==t;z.email=t,z.sessionToken=e,z.isVerified=!0,ce=Mn({isLoading:!0}),localStorage.setItem(hs,JSON.stringify({email:t,sessionToken:e})),i&&op()}function Qh(){z.email=null,z.sessionToken=null,z.isVerified=!1,ce=Mn({isResolved:!0}),localStorage.removeItem(hs),localStorage.removeItem(gs)}function ep(){try{const t=localStorage.getItem(hs);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(hs),{email:null,sessionToken:null}}}async function W0(){const e=new URLSearchParams(window.location.search).get("token");if(e){window.history.replaceState({},"",window.location.pathname+window.location.hash);try{const{email:n,sessionToken:i}=await U0(e);nd(n,i),tp();const r=id();r&&!window.location.hash&&(window.location.hash=r)}catch(n){id();const i=n.message||"Sign-in link invalid or expired.";Ee(i,"error"),Ws(),Jn(i,"error")}}else{const{email:n,sessionToken:i}=ep();if(n&&i){const r=await H0(i);r?nd(r.email,r.sessionToken):Qh()}}Vl()}function q0(){try{localStorage.setItem(Na,JSON.stringify({hash:window.location.hash||"#home",ts:Date.now()}))}catch(t){console.warn("rememberSignInReturnSurface: failed to persist return surface:",t)}}function id(){try{const t=localStorage.getItem(Na);if(localStorage.removeItem(Na),!t)return null;const{hash:e,ts:n}=JSON.parse(t);return!e||typeof n!="number"||Date.now()-n>ky?null:e}catch(t){return console.warn("consumeSignInReturnSurface: failed to read return surface:",t),null}}function Ws(){const t=document.getElementById("signin-modal");if(!t)return;q0(),document.getElementById("signin-email-input")?.removeAttribute("aria-invalid"),Jn(""),He(t)}function tp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&We(e)}function Jn(t,e){const n=document.getElementById("signin-message");n&&(n.textContent=t||"",n.classList.remove("signin-message-success","signin-message-error"),e&&n.classList.add(`signin-message-${e}`))}async function z0(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),n=Fs(t?.value);if(!n||!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(n)||n.length>254){t?.setAttribute("aria-invalid","true"),Jn("Please enter a valid email address.","error");return}t?.removeAttribute("aria-invalid"),e&&(e.disabled=!0,e.textContent="Sending…");const r=dh(n);r&&Jn(r,"error");try{const s=await Xh(n),o=s?.code===uh;t&&!o&&(t.value=""),t?.setAttribute("aria-invalid",String(o)),Jn(fh(s,n),o?"error":"success"),e&&(e.disabled=!1,e.textContent=o?"Send Sign-in Link":"Sent!",o||setTimeout(()=>{e.textContent==="Sent!"&&(e.textContent="Send Sign-in Link")},2500))}catch(s){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:n,err:s}),Jn("Something went wrong. Please try again.","error"),e&&(e.disabled=!1,e.textContent="Send Sign-in Link")}}function V0(){z.email=null,z.sessionToken=null,z.isVerified=!1,ce=Mn({isResolved:!0}),N_({storage:window.localStorage,onIdentityChanged:Vl,onPlanChanged:zs})}const G0=O_({sendLink:Xh,getEmail:()=>z.email||"",onState:K0});function K0(t){const e=document.getElementById("send-new-link-btn"),n=document.getElementById("send-new-link-msg");if(!e||!n)return;if(t.status==="pending"){e.disabled=!0,e.textContent="Sending…",n.className="acct-access-msg",n.textContent="Sending a fresh sign-in link…";return}if(t.status==="sent"){e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg",n.textContent=fh(t.data,z.email||"")||"Link sent — check your email.";return}e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg error";const i=t.error?.message?`Couldn't send a link right now. ${t.error.message}`:"Couldn't send a link right now. Please try again.";n.textContent=i}async function Y0(){await G0()}function J0(){const t=M_(window.localStorage),e=t.length?`Cleared disposable UI caches: ${t.join(", ")}.`:"Nothing disposable to clear.";Ee(`${e} Your run count, identity and stored keys are kept.`,"info")}function Z0(){const t=document.getElementById("delete-unavailable-modal");t&&He(t,{trigger:document.activeElement})}function X0(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("delete-unavailable-modal");e&&We(e)}function Vl(){const t=z.isVerified&&!!z.email,e=document.getElementById("auth-signedout"),n=document.getElementById("auth-signedin"),i=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),n&&n.classList.toggle("hidden",!t),i&&i.classList.toggle("hidden",t);const r=document.getElementById("auth-user-email");r&&(r.textContent=z.email||"");const s=document.getElementById("access-signed-email");s&&(s.textContent=z.email||""),lw(),zs()}async function np(){try{if(typeof FingerprintJS>"u"){console.warn("resolveIdentity: FingerprintJS not loaded, skipping");return}const e=await(await FingerprintJS.load()).get(),n=e.visitorId,i=await fetch(Fy,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fingerprint:e.visitorId,cookie_id:n})});if(!i.ok)throw new Error(`Identity check HTTP ${i.status}`);const r=await i.json();if(ht.userId=r.user_id,ht.token=r.identity_token||null,ht.status=r.status,ht.resolved=!0,sessionStorage.setItem(Ay,r.user_id),ht.token&&sessionStorage.setItem(Py,ht.token),r.usage_count!==void 0){const s=gn(),a=(r.usage_month||s)===s?r.usage_count:0;localStorage.setItem(Fn,JSON.stringify({count:a,month:s})),un()}console.log(`Identity resolved: ${r.status} (${r.user_id.slice(0,8)}...) usage: ${r.usage_count??"n/a"}`)}catch(t){console.error("resolveIdentity failed:",t)}}let Wo=null;function Q0(t=5e3){return ht.resolved?Promise.resolve():(Wo||(Wo=np().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([Wo,new Promise(e=>setTimeout(e,t))]))}function ip(){const t=gn();try{const e=localStorage.getItem(Fn);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Fn,month:t,err:e}),localStorage.removeItem(Fn),{count:0,month:t}}}function gn(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function lr(){const t=ip();return t.month!==gn()?{count:0,month:gn()}:t}function ew(){const e={count:lr().count+1,month:gn()};return localStorage.setItem(Fn,JSON.stringify(e)),e}function pi(){return!!ce.isLoading}function Tt(){return!!ce.isResolved}function tw(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(ps,e)?e:null}function nw(t){return t&&Object.entries(xh).find(([,e])=>e===t)?.[0]||null}function Cr(...t){return t.find(e=>e!=null&&e!=="")}function iw(...t){return t.find(e=>e&&typeof e=="object")||{}}function rw(t){const e=t.data&&typeof t.data=="object"?t.data:t,n=iw(e.subscription,e.stripeSubscription,e.currentSubscription,e.customer?.subscriptions?.data?.[0],e.subscriptions?.data?.[0],e.subscriptions?.[0]),i=e.metadata||n.metadata||e.customer?.metadata||{},r=Cr(e.priceId,e.price_id,e.stripePriceId,e.stripe_price_id,n.priceId,n.price_id,n.plan?.id,n.price?.id,n.items?.data?.[0]?.price?.id,n.items?.[0]?.price?.id,n.lines?.data?.[0]?.price?.id),s=Cr(e.status,e.subscriptionStatus,e.subscription_status,n.status,"none"),o=tw(Cr(e.tier,e.plan,e.planId,e.plan_id,e.subscriptionTier,e.subscription_tier,e.product,e.productName,n.tier,n.plan,i.tier,i.plan)),a=Ry.has(String(s).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||nw(r)||(a||l?"professional":"free");return Mn({tier:u,status:s,periodEnd:Cr(e.periodEnd,e.currentPeriodEnd,e.current_period_end,n.current_period_end,n.periodEnd,null),isResolved:!0})}function qs(){return ps[ce.tier]??ps.free}async function sw(){if(z.isVerified&&(!Tt()||pi())&&(await sp({force:!0}),zs()),z.isVerified&&!Tt())return Ee("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=lr(),e=qs();if(t>=e)return rp(t,e,{openModal:!0}),!1;const n=Math.floor(e*.8);if(t>=n){const i=e-t;Ee(`${i} run${i===1?"":"s"} remaining this month.`,"warning")}return!0}function rd(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function rp(t,e,n={}){nn(!0);const i=document.getElementById("walkthrough-modal");i&&We(i,{restoreFocus:!1});const r=document.getElementById("ready-state");r&&r.classList.add("hidden");const s=document.getElementById("preview-frame-container");s&&(s.style.display="none");const o=document.getElementById("main-stage-container");o&&o.classList.add("visible");const a=document.getElementById("results-view");a&&a.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar");const l=document.getElementById("pipeline-progress");l&&l.classList.remove("visible");const u=document.getElementById("paywall-exhausted");if(!u){Ee(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),di();return}const c=document.getElementById("paywall-exhausted-text");if(c){const h=ce.tier;h==="free"?c.textContent=`You've used all ${e} free generations this month. Upgrade to Pro for 50 generations/month and access to all AI models.`:c.textContent=`You've used all ${e} generations this month on your ${h} plan. Your limit resets next month.`}const d=document.getElementById("paywall-signin-btn");d&&d.classList.toggle("hidden",z.isVerified),u.classList.remove("hidden"),n.openModal&&di()}function za(t){return ce.tier==="free"&&Nr.includes(t)?ms:t}function ow(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const n=ce.tier,r=!(z.isVerified&&!Tt())&&n==="free";Array.from(e.options).forEach(o=>{const a=Gt(o.value),l=Nr.includes(o.value);o.textContent=l&&r?`${a} (PRO)`:a,o.disabled=!1}),r&&Nr.includes(e.value)&&(e.value=ms),e.disabled=!1,zu.has(e)||(e.addEventListener("change",()=>{Tt()&&ce.tier==="free"&&Nr.includes(e.value)&&(e.value=ms,di()),qa(e.value),kl()}),zu.add(e));let s=document.getElementById("model-selector-free-notice");r?(s||(s=document.createElement("p"),s.id="model-selector-free-notice",s.className="text-xs text-gray-400 mt-1",t.appendChild(s)),s.innerHTML='Free plan — Gemini only. '):s&&s.remove(),qa(e.value)}function Gl(){const t=z.isVerified&&!!z.email,e=t&&pi(),n=!t||Tt(),i=lr(),r=n?i.count:0,s=n?qs():0,o=Math.max(0,s-r),a=`${r} / ${s} runs this month`,l=gl,u=n?ce.tier||"free":null,c=document.getElementById("topbar-credits-count");c&&(e?c.textContent="…":n?c.textContent=String(o):c.textContent="—");const d=document.getElementById("credits-balance");d&&(e?d.textContent="Checking plan…":n?d.textContent=a:d.textContent="Plan check failed");const h=document.getElementById("usage-dialog-tier");h&&(e?h.textContent="Checking…":n?h.textContent=l[u]||"Free":h.textContent="Unavailable");const f=document.getElementById("usage-dialog-status");f&&(e?f.textContent="Verifying your subscription…":n?f.textContent="Runs reset at the start of each month.":f.textContent="Could not verify your subscription. Try again or sign out.");const p=document.getElementById("usage-counter");if(p)if(e&&t)p.textContent="Checking plan…",p.className="text-xs text-gray-500";else if(!n&&t)p.textContent="Plan check failed",p.className="text-xs text-red-600 font-medium";else{p.textContent=a;const g=s>0?r/s:0;p.className=g>=1?"text-xs text-red-600 font-medium":g>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500"}if(!t){const g=document.getElementById("guest-usage-text");if(g){const m=ip(),v=m.month===gn()?m.count??0:0;g.textContent=`${v} / ${ps.free} generations used`}}aw()}function aw(){if(!(z.isVerified&&!!z.email))return;const e=pi(),n=Tt(),i=lr(),r=n?i.count:0,s=n?qs():0,o=Math.max(0,s-r),a=n?ce.tier||"free":null,l={free:"Free",professional:"Pro",power:"Power"}[a]||"Free",u=z.email||"",c=u.split("@")[0]||u,d=document.getElementById("acct-avatar");d&&(d.textContent=(u[0]||"?").toUpperCase());const h=document.getElementById("acct-name");h&&(h.textContent=c||"—");const f=document.getElementById("acct-plan-tier"),p=document.getElementById("acct-plan-price"),g=document.getElementById("acct-plan-note"),m=document.getElementById("acct-renewal");if(f&&(f.textContent=e?"Checking…":n?l:"Plan unavailable"),p)if(e)p.textContent="—";else if(!n)p.textContent="—";else if(a==="free")p.textContent="$0 / month";else{const x=Oi(Ni[a]??0,Cl());p.textContent=`${x} / month`}if(g&&(e?g.textContent="Verifying your subscription…":n?a==="free"?g.textContent="No subscription. Upgrade for more generations.":g.textContent="billed monthly through Stripe":g.textContent="Could not verify your subscription. Check billing or sign out."),m){const x=Date.parse(ce.periodEnd||""),F=n&&a!=="free"&&!!ce.periodEnd&&!Number.isNaN(x);if(e)m.textContent="";else if(!n)m.textContent="";else if(a==="free")m.textContent="";else if(F){const $=new Date(x).toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"});m.textContent=`Renews ${$} · reset at the start of each month.`}else m.textContent="Renewal date is not available for this period."}const v=document.getElementById("acct-left-count"),E=document.getElementById("acct-left-limit"),S=document.getElementById("acct-reset-note");v&&(v.textContent=e?"…":n?String(o):"—"),E&&(E.textContent=e?"…":n?String(s):"—"),S&&(e?S.textContent="Checking plan…":n?S.textContent="Runs reset at the start of each month.":S.textContent="Plan check failed. Refresh or manage billing.");const _=document.getElementById("acct-used-count"),b=document.getElementById("acct-meter-fill"),k=document.getElementById("acct-meter-meta"),T=document.getElementById("acct-meter-track");if(_&&(_.textContent=e?"…":n?String(r):"—"),b){const x=n&&s>0?Math.min(100,Math.round(r/s*100)):0;b.style.width=`${x}%`}if(k)if(e)k.textContent="Checking…";else if(!n)k.textContent="Plan check failed";else if(s===0)k.textContent=`${r} of ${s}`;else{const x=Math.round(r/s*100);k.textContent=`${r} of ${s} · ${x}%`}T&&(e?T.setAttribute("aria-label","Checking usage…"):n?T.setAttribute("aria-label",`${r} of ${s} generations used`):T.setAttribute("aria-label","Usage unavailable")),vt()}function un(){if(Gl(),z.isVerified&&(pi()||!Tt())){rd();return}const{count:t}=lr(),e=qs();t>=e&&!y.isRunning?rp(t,e):rd()}function lw(){Gl()}async function sp(t={}){const e=t.force===!0;if(!z.isVerified||!z.sessionToken){ce=Mn({isResolved:!0});return}ce={...ce,isLoading:!0,error:null};const n=localStorage.getItem(gs);if(!e&&n)try{const{data:i,email:r,ts:s,version:o}=JSON.parse(n);if(o===Vu&&r===z.email&&Date.now()-s<300*1e3){ce={...i,isLoading:!1,isResolved:i.isResolved!==!1};return}}catch(i){console.warn("Failed to parse subscription cache:",i,"| raw value:",n)}try{const r=await(await fetch(`${_t}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:z.sessionToken,user_id:ht.userId})})).json();if(r.error){if(["unauthorized","invalid session","expired session"].some(o=>String(r.error).toLowerCase().includes(o))){Qh(),Vl();return}ce=Mn({isResolved:!1,error:r.error});return}ce=rw(r),localStorage.setItem(gs,JSON.stringify({version:Vu,data:ce,email:z.email,ts:Date.now()}))}catch(i){console.error("fetchSubscription failed:",i),ce={...ce,isLoading:!1,isResolved:!1,error:i.message}}}function op(){localStorage.removeItem(gs)}async function cw(t){if(!z.isVerified||!z.sessionToken){ap(),Ws();return}if(!xh[t]){Ee("Invalid plan selected.","error");return}const e=document.getElementById(`checkout-btn-${t}`);e&&(e.disabled=!0,e.textContent="Redirecting…");try{const i=await(await fetch(`${_t}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:z.sessionToken,currency:Cl()})})).json();if(i.error||!i.url)throw new Error(i.error||"Failed to create checkout session");const{url:r}=i;window.location.href=r}catch(n){console.error("startCheckout failed:",n),e&&(e.disabled=!1,e.textContent="Subscribe"),Ee("Could not start checkout. Please try again.","error")}}async function uw(t){if(!z.isVerified||!z.sessionToken){Ws();return}const e=t||document.getElementById("manage-billing-btn"),n=e?e.textContent:"";e&&(e.disabled=!0,e.textContent="Loading…");try{const r=await(await fetch(`${_t}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:z.sessionToken})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to open billing portal");const{url:s}=r;window.location.href=s}catch(i){console.error("openCustomerPortal failed:",i),e&&(e.disabled=!1,e.textContent=n),Ee("Could not open billing portal. Please try again.","error")}}const Es=new Set;function dw(){Es.forEach(t=>t.abort()),Es.clear()}async function Ss(t,e,n,i={},r=[]){const o=new AbortController;Es.add(o);let a=!1;const l=setTimeout(()=>{a=!0,o.abort()},12e4);try{const u=await fetch(Cy,{method:"POST",headers:{"Content-Type":"application/json",...ht.token?{Authorization:`Bearer ${ht.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:ht.userId,step:t,model:e,prompt:n,images:r,context:i})}),c=await u.text();let d={};try{d=c?JSON.parse(c):{}}catch{d={}}if(u.status===429){d.serverCount!==void 0&&(localStorage.setItem(Fn,JSON.stringify({count:d.serverCount,month:gn()})),un());const p=new Error(d.message||"Monthly usage limit reached. Upgrade to continue.");throw p.isUsageLimit=!0,p.pipelineStep=t,p}const h=Sv(d,t);if(h)throw h;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(d),"content type:",typeof d.content),!u.ok)throw new Error(`${d.message||d.error||"BuildShip pipeline error"} (HTTP ${u.status})`);if(t==="generator")if(d.usage_status==="success"&&Number.isFinite(d.usage_count)){const p=gn();(d.usage_month||p)===p&&(localStorage.setItem(Fn,JSON.stringify({count:d.usage_count,month:p})),un())}else ew(),un();let f=d.output||d.content;if(!f){const p=c?` (body: ${c.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${p}`)}return Array.isArray(f)&&(f=f.map(p=>typeof p=="string"?p:p.text||"").join("")),typeof f!="string"&&(f=JSON.stringify(f)),f}catch(u){if(u.name==="AbortError"){if(a)throw new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`);const c=new Error(`BuildShip ${t} request cancelled`);throw c.isPipelineCancel=!0,c}throw u instanceof TypeError?new Error(`BuildShip unreachable: ${u.message}`):u}finally{clearTimeout(l),Es.delete(o)}}let Va=!1;function fw(){const e=new URLSearchParams(window.location.search).get("checkout");return e==="success"?(window.history.replaceState({},"",window.location.pathname+window.location.hash),op(),Va=!0):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname+window.location.hash),Ee("Checkout cancelled.","info")),e}function hw(){if(!Va)return;Va=!1;const t=ce.tier!=="free";Ee(t?"Subscription active! Your plan is live.":"Checkout complete — confirming your subscription. Check Manage billing if it does not update.",t?"success":"info")}function zs(){const t=z.isVerified&&!!z.email,e=ce.tier,n=t&&pi(),i=!t||Tt(),r=document.getElementById("subscription-tier-badge");if(r){const a=gl,l={free:"bg-gray-100 text-gray-600",professional:"bg-indigo-100 text-indigo-700",power:"bg-purple-100 text-purple-700",unresolved:"bg-red-50 text-red-600"};r.textContent=n?"Checking…":i?a[e]||"Free":"Plan unavailable",r.className=`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${i?l[e]||l.free:l.unresolved}`}const s=document.getElementById("upgrade-prompt");s&&s.classList.toggle("hidden",!t||n||!i||e!=="free");const o=document.getElementById("manage-billing-btn");o&&o.classList.toggle("hidden",!t||n||i&&e==="free"),pw(i?e:null),ow(),kl(),un(),Ip()}function pw(t){const e=["bg-gray-100","text-gray-500","cursor-default"];Object.entries({professional:{btnId:"checkout-btn-professional",defaultText:"Subscribe"},power:{btnId:"checkout-btn-power",defaultText:"Subscribe"}}).forEach(([r,{btnId:s,defaultText:o}])=>{const a=document.getElementById(s);a&&(r===t?(a.disabled=!0,a.textContent="Current plan",a.classList.add(...e)):(a.disabled=!1,a.textContent=o,a.classList.remove(...e)))});const i=document.getElementById("free-tier-current");i&&i.classList.toggle("hidden",t!=="free")}function gw(){document.querySelectorAll(".pm-card[data-tier]").forEach(t=>{const e=t.dataset.tier,n=uv[e];if(!n)return;const i=t.querySelector("ul.pm-features");if(i){i.innerHTML="";for(const r of n){const s=document.createElement("li");s.textContent=r,i.appendChild(s)}}})}function Ga(){const t=Cl(),e=document.getElementById("pro-price"),n=document.getElementById("power-price"),i=document.getElementById("plans-pro-price"),r=document.getElementById("plans-power-price"),s=document.getElementById("pro-price-note"),o=document.getElementById("power-price-note"),a=document.getElementById("plans-pro-price-note"),l=document.getElementById("plans-power-price-note");e&&(e.textContent=Oi(Ni.professional,t)),n&&(n.textContent=Oi(Ni.power,t)),i&&(i.textContent=Oi(Ni.professional,t)),r&&(r.textContent=Oi(Ni.power,t));const u="billed monthly";s&&(s.textContent=u),o&&(o.textContent=u),a&&(a.textContent=u),l&&(l.textContent=u)}function di(){Ga();const t=document.getElementById("pricing-modal");t&&He(t),Hy().then(()=>Ga())}function ap(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&We(e)}function Ee(t,e="info"){const n={success:"bg-green-600 text-white",error:"bg-red-600 text-white",warning:"bg-amber-500 text-white",info:"bg-gray-800 text-white"},i=document.createElement("div");i.className=`fixed bottom-6 left-1/2 -translate-x-1/2 px-5 py-3 rounded-lg text-sm font-medium shadow-lg z-50 transition-opacity duration-300 ${n[e]||n.info}`,i.textContent=t,document.body.appendChild(i),setTimeout(()=>{i.style.opacity="0",setTimeout(()=>i.remove(),300)},3500)}document.addEventListener("DOMContentLoaded",async()=>{av(),hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),mw(),window.__heroField=Q_(),window.__pipelineLogo=iy(),kh=xy({onSubmit:or}),Oa=(async()=>{try{await W0(),fw(),await sp()}catch(n){console.warn("Startup auth/subscription initialization failed:",n)}})(),await Oa,hw(),zs(),Ga(),gw(),await _0(),h0();const t=document.getElementById("flutterflow-endpoint-select");if(t){const n=yt();t.value=n}Bh(),np();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{en===2&&e.value.trim().length>0&&(Tl(),Ns())}),e.addEventListener("blur",()=>{const n=document.getElementById("walkthrough-modal");en===2&&n&&He(n)}),e.addEventListener("keydown",n=>{if(n.key==="Tab"){const i=document.getElementById("walkthrough-modal");en===2&&i&&setTimeout(()=>{He(i)},100)}})),window.addEventListener("commitStateChange",n=>{const{state:i}=n.detail;i===ee.PREPARING||i===ee.VALIDATING||i===ee.PUSHING?(Oe.phaseId||hp(),od(i)):(i===ee.SUCCESS||i===ee.ERROR)&&(od(i),setTimeout(Jl,1e3))}),ic()});function mw(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function vw(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Nn),document.addEventListener("keydown",Nn))}function Nn(){const t=document.getElementById("preview-frame-container"),e=document.getElementById("main-stage-container"),n=document.getElementById("ready-state");t&&(t.style.display="none"),e&&e.classList.add("visible"),n&&n.classList.remove("hidden");const i=document.getElementById("welcome-video-player");i&&i.removeEventListener("click",Nn),document.removeEventListener("keydown",Nn),Bh()}let zi=null;async function _w(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++Zu,n=()=>e===Zu,i=await Te("flutterflow"),r=await Te("flutterflow_project_id");if(n()){if(!i){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const o=await new hi(i,"","main",yt()).listProjects();if(!n())return;if(!o||o.length===0){t.innerHTML='';return}t.innerHTML='',o.forEach(a=>{const l=document.createElement("option");l.value=a.id||a.projectId||"",l.textContent=a.name||a.projectName||`Project ${a.id}`,t.appendChild(l)}),r&&(t.value=r)}catch(s){if(!n())return;console.error("Failed to load projects for deploy:",s),t.innerHTML=''}}}function yw(){return document.getElementById("confirm-project-select")?.value?.trim()||null}function Kl(t,e,n,i=null){zi={codeInfo:t,checks:e,deps:n,bundlePlan:i},document.getElementById("confirm-file-name").textContent=t.fileName,document.getElementById("confirm-artifact-type").textContent=t.artifactType,document.getElementById("confirm-file-size").textContent=`${(t.content.length/1024).toFixed(1)} KB`,document.getElementById("confirm-line-count").textContent=i?`${i.fileEntries.length} files`:t.content.split(` +`).length,_w();const r=document.getElementById("confirm-deps-list"),s=document.getElementById("confirm-deps-section");n&&Object.keys(n).length>0?(r.innerHTML=Object.entries(n).map(([u,c])=>{const d=c?`at least ${Qt(c)}`:"version resolved from your project";return`
  • • ${Qt(u)}: ${d}
  • `}).join(""),s.classList.remove("hidden")):s.classList.add("hidden");const o=document.getElementById("confirm-warnings-list"),a=document.getElementById("confirm-warnings-section");e.warnings&&e.warnings.length>0?(o.innerHTML=e.warnings.map(u=>`
  • • ${Qt(u)}
  • `).join(""),a.classList.remove("hidden")):a.classList.add("hidden"),document.getElementById("confirm-code-preview").textContent=t.content,document.getElementById("code-preview-content").classList.add("hidden"),document.getElementById("code-preview-chevron").style.transform="rotate(0deg)";const l=document.getElementById("commit-confirm-modal");l&&He(l)}function lp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&We(e),zi=null}function ww(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&We(e);const n=["success-message","success-project-id","success-file-name","success-artifact-type","success-time","success-size"];for(const s of n){const o=document.getElementById(s);o&&(o.textContent="")}const i=document.getElementById("success-warnings-section");i&&i.classList.add("hidden");const r=document.getElementById("success-warnings-list");r&&(r.innerHTML="")}function cp(t){const e=(m,v)=>{const E=document.getElementById(m);E&&(E.textContent=v||"")},n=t.metadata?.fileName||"",i=t.metadata?.projectId||"",r=t.metadata?.artifactType||"",s=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",i),e("success-file-name",n),e("success-artifact-type",r),e("success-time",s),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&i&&(u.href=`https://app.flutterflow.io/project/${i}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),h=t.unverified||[],f=t.approximate||[],p=t.warnings||[];(p.length>0||h.length>0||f.length>0)&&c&&d&&(d.innerHTML=[...h.map(m=>`
  • Not verified before deploying: ${q(String(m))}
  • `),...f.map(m=>`
  • Verified approximately: ${q(String(m))}
  • `),...p.map(([m,v])=>`
  • ${q(m)}: ${q(String(v))}
  • `)].join(""),c.classList.remove("hidden"));const g=document.getElementById("commit-success-modal");g&&He(g)}function up(t){Jl(),D0(t);const e=t.remoteRefusal===!0;Yl(t,{heading:"Deploy failed",title:e?"FlutterFlow refused this deploy — nothing was confirmed written.":"The deploy failed before FlutterFlow confirmed anything.",guidance:e?"Review the error and any per-file outcomes above, fix them in your code or in FlutterFlow, then deploy again. A refusal is definitive: no part of this deploy was applied, so retrying is safe once the problem is fixed.":"Review the error above, fix it, then deploy again. The deploy stopped before a write was confirmed, so nothing was applied."})}function Yl(t,{heading:e,title:n,guidance:i}){const r=t.targetIdentity||{},s=document.getElementById("commit-terminal-modal");if(!s)return!1;const o=(f,p)=>{const g=document.getElementById(f);g&&(g.textContent=p||"")};o("terminal-heading",e),o("terminal-title",n),o("terminal-message",t.error||t.message||"");const a=document.getElementById("terminal-identity-list");if(a){const f=[["Project",r.projectId||t.metadata?.projectId],["Endpoint",r.endpoint],["File",r.fileName||t.metadata?.fileName],["Artifact",r.artifactType||t.metadata?.artifactType]];a.innerHTML=f.map(([p,g])=>`
    ${q(p)}:${q(String(g??"—"))}
    `).join("")}const l=document.getElementById("terminal-file-outcomes");let u=t.errorMap;u&&!(u instanceof Map)&&(u=new Map(Object.entries(u))),l&&u&&u.size>0?(l.innerHTML=[...u.entries()].map(([f,p])=>`
  • ${q(f)}: ${q(El(p))}
  • `).join(""),l.classList.remove("hidden")):l&&l.classList.add("hidden");const c=document.getElementById("terminal-guidance");c&&(c.innerHTML=i);const d=document.getElementById("terminal-open-ff-link"),h=r.projectId||t.metadata?.projectId;return d&&(d.href=h?`https://app.flutterflow.io/project/${h}`:"https://app.flutterflow.io/"),He(s),!0}function dp(t){Yl(t,{heading:"Deploy partially applied",title:"Some custom classes reached FlutterFlow, but the deploy did not fully complete.",guidance:"The custom classes the runner confirmed are already in your project and are not lost. Review the per-file errors above, fix them in FlutterFlow or regenerate, then deploy again. Open the project to see exactly what landed."})}function fp(t){Yl(t,{heading:"Deploy outcome not yet known",title:"This browser stopped waiting before the FlutterFlow server reported a result.",guidance:"The deploy may still be finishing on the server — it was not cancelled. Open your FlutterFlow project and confirm whether the class landed before retrying, so you do not push a duplicate or build on top of an unknown state."})}function bw(t){t&&t.target!==t.currentTarget||We(document.getElementById("commit-terminal-modal"))}function Ew(){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 sd={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}},Sw=[{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..."}],Oe={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&&(Eu(e,!0,"Deploying to FlutterFlow"),He(e)),this.set("prepare")},set(t,e=null){if(!(!sd[t]||t===this.phaseId)){if(!this.sequence.includes(t)){const n=this.sequence.indexOf("package");this.sequence.splice(n===-1?this.sequence.length:n,0,t)}this.phaseId=t,this.phaseStartedAt=Date.now(),this.substatus=e,this.liveSubstatus=!1,this.render(),this.timer&&clearInterval(this.timer),t!=="done"&&(this.timer=setInterval(()=>this.render(),500))}},setSubstatus(t){t&&(this.liveSubstatus=!0,this.substatus=t,this.render())},render(){const t=sd[this.phaseId];if(!t)return;const e=(Date.now()-this.phaseStartedAt)/1e3,n=t.start+(t.end-t.start)*(1-Math.exp(-e/25));if(this.phaseId==="provision"&&!this.liveSubstatus){const o=Sw.filter(a=>e>=a.after).pop();o&&(this.substatus=o.text)}const i=this.sequence.indexOf(this.phaseId),s=[`Step ${i===-1?1:i+1} of ${this.sequence.length}`];e>=5&&s.push(xw(e)),pp(this.phaseId==="done"?100:n,t.message,s.join(" · "),this.substatus)},stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.phaseId=null;const t=document.getElementById("commit-progress-overlay");t&&(Eu(t,!1),We(t,{force:!0,restoreFocus:!1}))}};function xw(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 hp(t){Oe.start(t)}function Jl(){Oe.stop()}function pp(t,e,n,i=null){const r=document.getElementById("commit-progress-bar"),s=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");r&&(r.style.width=`${Math.round(t*10)/10}%`),s&&(s.textContent=e),o&&(o.textContent=n),a&&(a.textContent=i||"",a.classList.toggle("hidden",!i))}function od(t){const e={[ee.PREPARING]:"prepare",[ee.VALIDATING]:"validate",[ee.PUSHING]:"project",[ee.SUCCESS]:"done"};if(t===ee.ERROR){Oe.timer&&clearInterval(Oe.timer),Oe.timer=null,pp(100,"Failed","Error occurred");return}const n=e[t];n&&Oe.set(n)}function Iw(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===J.CODE_FILE):t.codeInfo?.codeType===J.CODE_FILE}let gp=!1;function mp(t){gp=t;const e=document.querySelector("#commit-confirm-modal button[data-deploy-confirm]");e&&(e.disabled=t),[...document.querySelectorAll("[data-deploy-start]"),...document.querySelectorAll("#btn-deploy-to-ff")].forEach(i=>{i.disabled=t})}function ad(t){Jl(),mp(!1);const e=wh(t);e===Xe.COMMITTED?cp(t):e===Xe.PARTIAL?dp(t):e===Xe.UNCONFIRMED?fp(t):up(t)}async function kw(){if(!zi){console.error("No pending commit data");return}if(gp){console.warn("Deploy already in flight; ignoring duplicate confirm.");return}const t=zi;if(zi=null,qi=yw(),lp(),mp(!0),hp({withProvisioning:Iw(t)}),t.bundlePlan){const o=await A0(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});qi=null,ad(o);return}const{codeInfo:e}=t,{artifactType:n,artifactName:i,fileName:r}=Dh(),s=await C0(e.content,{artifactType:n,artifactName:i,fileName:r,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});qi=null,ad(s)}window.runThinkingPipeline=or;window.toggleStep=R0;window.toggleSection=F0;window.selectWorkflowStep=nt;window.copyCode=T0;window.retryWithDifferentModel=N0;window.openApiKeysModal=Rl;window.closeApiKeysModal=Nh;window.openComposerSettings=n0;window.closeComposerSettings=i0;window.walkthroughConnectAccount=t0;window.closeWalkthroughModal=s0;window.openWalkthroughModal=r0;window.advanceWalkthrough=Tl;window.commitToFlutterFlow=k0;function Cw(){const t=document.getElementById("pipeline-input");t&&t.focus()}function Aw(){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=Cw;window.openModelSelector=Aw;window.handlePromptImageSelect=jy;window.removePromptImage=Uy;window.saveApiKeys=l0;window.validateFlutterFlowConnection=Ml;window.clearAllApiKeys=c0;window.toggleKeyVisibility=g0;window.handleWelcomeVideoEnd=vw;window.dismissWelcomeVideo=Nn;window.initiateCommitToFlutterFlow=O0;window.updateFlutterFlowCredentialStatus=j0;window.openCommitConfirmModal=Kl;window.closeCommitConfirmModal=lp;window.closeCommitSuccessModal=ww;window.closeCommitTerminalModal=bw;window.showCommitPartialModal=dp;window.showCommitUnconfirmedModal=fp;window.showCommitSuccessModal=cp;window.showCommitFailureModal=up;window.toggleCodePreview=Ew;window.confirmCommitToFlutterFlow=kw;window.runRefinement=Yh;window.regenerateFromPastedErrors=Jh;window.clearErrorInput=L0;window.setFlutterFlowEndpoint=e0;window.getFlutterFlowEndpoint=yt;window.commitProgress=Oe;window.openSignInModal=Ws;window.closeSignInModal=tp;window.handleMagicLinkRequest=z0;window.handleSignOut=V0;window.handleSendNewLink=Y0;window.handleClearCache=J0;window.handleDeleteAccount=Z0;window.closeDeleteUnavailableModal=X0;window.startCheckout=cw;window.openCustomerPortal=uw;window.openPricingModal=di;window.closePricingModal=ap;let jr=null,vp=null,On={1:"pending",2:"pending",3:"pending"},Zl=1,Xl=null;const Vs={1:"Prompt Architect",2:"Code Generator",3:"Code Review"},Pw={1:"Understanding your prompt",2:"Generating Dart code",3:"Running the code audit"},Fw={1:"Prompt understood",2:"Dart code generated",3:"Code audit complete"};function Gs(){return y.runId+=1,y.runId}function re(t){return t===void 0||t===y.runId}function Rw(){y.runId+=1}function Ql(t){return document.getElementById(`pdot-${t}`)}function Ka(t){const e=document.getElementById("btn-run-pipeline")||document.getElementById("hero-send");e&&(e.disabled=t,e.classList.toggle("is-busy",t),t?e.setAttribute("aria-busy","true"):e.removeAttribute("aria-busy"))}function Ks(t){const e=document.getElementById("pipeline-progress");e&&(e.dataset.runState=t)}function Rn(t,e){On[t]=e;const n=Ql(t);if(!n)return;n.dataset.state=e,n.disabled=e==="pending"||e==="skipped";const i=Vs[t],r={pending:"not started",active:"in progress",done:"complete",failed:"failed",skipped:"not run"};n.setAttribute("aria-label",`Step ${t} of 3, ${i}: ${r[e]||e}`),e==="active"?n.setAttribute("aria-current","step"):n.removeAttribute("aria-current")}function Tw(){return[1,2,3].filter(t=>On[t]==="done").length}function Ys(){const t=document.getElementById("pipeline-progress-fill");t&&(t.style.width=`${Tw()/3*100}%`);const e=document.getElementById("progress-stage-count");e&&(e.textContent=`Step ${Zl} of 3`)}function Js(t,{done:e=!1}={}){const n=document.getElementById("progress-title-text"),i=document.getElementById("progress-substep-text"),r=On[t],s=e||r==="done";if(n&&(n.textContent=s?Fw[t]:Pw[t]),i){const o=s?" — complete":r==="failed"?" — stopped":"";i.textContent=`Step ${t} of 3 — ${Vs[t]}${o}`}}function $w(t){On[t]==="pending"||On[t]==="skipped"||(Xl=t,[1,2,3].forEach(e=>{const n=Ql(e);n&&n.setAttribute("aria-pressed",String(e===t))}),Js(t))}function ec(){Xl=null,[1,2,3].forEach(t=>{const e=Ql(t);e&&e.removeAttribute("aria-pressed")})}function _p(t){const e=document.getElementById("pipeline-note");e&&(e.textContent=t||"",e.hidden=!t)}function Mw(t,e,n){re(n)&&_p(`${Gt(t)} did not answer. Continuing on ${Gt(e)}.`)}function tc(){const t=document.getElementById("pipeline-failure");if(!t)return;t.hidden=!0;const e=document.getElementById("pipeline-failure-actions");e&&e.replaceChildren()}const Lw=1120;function Nw(){const t=getComputedStyle(document.documentElement).getPropertyValue("--t-morph").trim(),e=Number.parseFloat(t);return Number.isFinite(e)&&e>0?e:Lw}let Qn=null,Ur=null;function Ow(){return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0}function dn(){if(Ur){try{Ur.cancel()}catch{}Ur=null}Qn&&(Qn.remove(),Qn=null),window.removeEventListener("resize",dn)}function yp(t,e){if(dn(),Ow()||!t||!e||!document.body||typeof Element.prototype.animate!="function")return;const n=t.getBoundingClientRect(),i=e.getBoundingClientRect();if(!n.width||!n.height||!i.width||!i.height)return;const r=document.createElement("div");r.className="composer-morph",r.setAttribute("aria-hidden","true"),r.style.cssText=`left:${i.left}px;top:${i.top}px;width:${i.width}px;height:${i.height}px;opacity:0;`,document.body.appendChild(r);const s=n.left+n.width/2-(i.left+i.width/2),o=n.top+n.height/2-(i.top+i.height/2),a=n.width/i.width,l=n.height/i.height,u=`translate(${s}px,${o}px) scale(${a},${l})`,c=r.animate([{transform:u,opacity:0,offset:0,easing:"cubic-bezier(.2,0,0,1)"},{transform:u,opacity:1,offset:.14,easing:"cubic-bezier(.4,0,.2,1)"},{transform:`translate(${s}px,${o}px) scale(${a*.93},${l*.93})`,opacity:1,offset:.28,easing:"cubic-bezier(.32,1.38,.5,1)"},{transform:"translate(0px,0px) scale(1,1)",opacity:1,offset:1}],{duration:Nw(),fill:"both"});Qn=r,Ur=c,window.addEventListener("resize",dn),c.onfinish=()=>{if(Qn!==r)return;const d=r.animate([{opacity:1},{opacity:0}],{duration:260,fill:"forwards"});d.onfinish=()=>{Qn===r&&dn()}}}function Bw(){const e=document.getElementById("composer")?.getBoundingClientRect();e&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{yp({getBoundingClientRect:()=>e},document.getElementById("main-stage-container"))})})}function Dw(){yp(document.getElementById("pipeline-progress"),document.getElementById("main-stage-container"))}window.addEventListener("hashchange",dn);window.addEventListener("popstate",dn);function Zs(t={}){const{prompt:e=null,runId:n}=t;if(!re(n))return;Qs(),nn(!0);const i=document.getElementById("pipeline-progress"),r=document.getElementById("results-view"),s=document.getElementById("ready-state");if(s&&s.classList.add("hidden"),r&&r.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),i&&i.classList.add("visible"),Ks("running"),e!==null){const a=document.getElementById("pipeline-submitted-prompt");a&&(a.textContent=e)}vp=Date.now();const o=document.getElementById("progress-elapsed");o&&(o.textContent="0s"),On={1:"pending",2:"pending",3:"pending"},ec(),tc(),_p(""),[1,2,3].forEach(a=>Rn(a,"pending")),Ft(1,n),jw()}function Ft(t,e){re(e)&&(Zl=t,ec(),[1,2,3].forEach(n=>{n===t?Rn(n,"active"):nt&&Rn(n,"pending")}),Js(t),Ys())}function tn(t,e){re(e)&&(Rn(t,"done"),Xl===null&&Js(t,{done:!0}),Ys())}function wp(t,{stage:e=1,runId:n,retry:i=bp}={}){if(!re(n))return;Xs(),Qs(),dn(),Ks("failed"),nn(!0);const r=document.getElementById("pipeline-progress");r&&r.classList.add("visible");const s=document.getElementById("results-view");s&&s.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),Rn(e,"failed"),[1,2,3].forEach(p=>{p>e&&Rn(p,"pending")}),Zl=e,ec(),Js(e),Ys();const o=Eh(t),a=document.getElementById("pipeline-failure"),l=document.getElementById("pipeline-failure-title"),u=document.getElementById("pipeline-failure-message"),c=document.getElementById("pipeline-failure-hint"),d=document.getElementById("pipeline-failure-actions");if(!a||!l||!u||!d)return;if(a.dataset.kind=o.kind,l.textContent=`${Vs[e]}: ${o.title}`,u.textContent=o.message,c){const p=o.detail&&o.detail!==o.message?o.detail:"";c.textContent=p,c.hidden=!p}d.replaceChildren();const h=[o.canUpgrade&&{id:"upgrade",label:"View plans",variant:"primary",onClick:()=>di()},o.canRetry&&{id:"retry",label:"Retry",variant:o.canUpgrade?"secondary":"primary",onClick:i},o.canEdit&&{id:"edit",label:"Edit prompt",variant:"secondary",onClick:Ya}].filter(Boolean);!o.canEdit&&!o.canRetry&&h.push({id:"edit",label:"Back to prompt",variant:"secondary",onClick:Ya}),h.forEach(p=>{const g=document.createElement("button");g.type="button",g.textContent=p.label,g.dataset.action=p.id,g.dataset.variant=p.variant,g.addEventListener("click",p.onClick),d.appendChild(g)}),a.hidden=!1;const f=d.querySelector("button");f&&f.focus({preventScroll:!0})}function Ya(){Rw(),dw(),y.isRunning=!1,Ka(!1),rn(),Ks("settled"),dn(),Xs(),Qs(),tc();const t=document.getElementById("pipeline-progress");t&&t.classList.remove("visible"),nn(!1);const e=document.getElementById("pipeline-input");e&&(y.submittedPrompt&&(e.value=y.submittedPrompt,e.dispatchEvent(new Event("input",{bubbles:!0}))),e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length))}function bp(){const t=document.getElementById("pipeline-input");t&&y.submittedPrompt&&(t.value=y.submittedPrompt,t.dispatchEvent(new Event("input",{bubbles:!0}))),Ne=y.submittedImages.slice(),cn(),tc(),or()}function jw(){Xs(),jr=setInterval(()=>{const t=(Date.now()-vp)/1e3,e=document.getElementById("progress-elapsed");e&&(e.textContent=`${Math.floor(t)}s`)},250)}function Xs(){jr&&(clearInterval(jr),jr=null)}let Vi=null;function Qs(){Vi&&(clearTimeout(Vi),Vi=null)}function cr(){Xs(),Qs(),Ks("settled"),Ys();const t=document.getElementById("pipeline-progress-fill");Vi=setTimeout(()=>{Vi=null;const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function Tn(t,e=""){const n={pass:'',warning:'',fail:'',info:''};return``}function Ep(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function Uw(){return g_({bundle:y.artifactBundle,reviewResult:y.step3Result})}function Hw(t){return`
    ${Tn(t.severity)}
    @@ -249,7 +249,7 @@ Error: ${g} `).join(""):'
  • No relationships for this file
  • ';return`
    - ${Tn(e.status)} ${q(bp(e.status))} + ${Tn(e.status)} ${q(Ep(e.status))}

    ${q(e.artifactName)}

    ${e.description?`

    ${q(e.description)}

    `:""}
    @@ -297,7 +297,7 @@ Error: ${g}
      ${a}
    - `}function Vw(t){const e=document.getElementById("bundle-strip"),n=document.getElementById("results-summary-tab"),i=document.getElementById("artifact-tabs"),r=document.getElementById("results-file-count");if(n){const s=y.resultsViewMode==="summary";n.classList.toggle("active",s),n.setAttribute("role","tab"),n.setAttribute("aria-selected",String(s)),n.setAttribute("aria-controls","results-summary-detail"),n.tabIndex=s?0:-1}if(i&&(i.setAttribute("role","tablist"),i.setAttribute("aria-label","Artifacts in this bundle")),!t.artifacts.length){r&&(r.textContent="0 files"),e&&e.classList.remove("visible"),i&&(i.innerHTML=""),ad();return}if(r){const s=t.artifacts.length;r.textContent=`${s} ${s===1?"file":"files"}`}i&&(i.innerHTML=t.artifacts.map(s=>{const o=y.resultsViewMode==="file"&&s.id===y.selectedArtifactId;return` + `}function Vw(t){const e=document.getElementById("bundle-strip"),n=document.getElementById("results-summary-tab"),i=document.getElementById("artifact-tabs"),r=document.getElementById("results-file-count");if(n){const s=y.resultsViewMode==="summary";n.classList.toggle("active",s),n.setAttribute("role","tab"),n.setAttribute("aria-selected",String(s)),n.setAttribute("aria-controls","results-summary-detail"),n.tabIndex=s?0:-1}if(i&&(i.setAttribute("role","tablist"),i.setAttribute("aria-label","Artifacts in this bundle")),!t.artifacts.length){r&&(r.textContent="0 files"),e&&e.classList.remove("visible"),i&&(i.innerHTML=""),ld();return}if(r){const s=t.artifacts.length;r.textContent=`${s} ${s===1?"file":"files"}`}i&&(i.innerHTML=t.artifacts.map(s=>{const o=y.resultsViewMode==="file"&&s.id===y.selectedArtifactId;return` - `}).join(""),i.onclick=s=>{const o=s.target.closest(".artifact-tab");o?.dataset?.artifactId&&nc(o.dataset.artifactId)},ad()),e&&e.classList.add("visible")}function ad(){const t=document.getElementById("bundle-strip");!t||t.dataset.tabKeyboard==="bound"||(t.dataset.tabKeyboard="bound",t.addEventListener("keydown",e=>{if(e.defaultPrevented)return;const n=[document.getElementById("results-summary-tab"),...Array.from(document.querySelectorAll("#artifact-tabs .artifact-tab"))].filter(Boolean);if(!n.length||!n.includes(document.activeElement))return;let i=-1;const r=n.indexOf(document.activeElement);if(e.key==="ArrowRight")i=(r+1)%n.length;else if(e.key==="ArrowLeft")i=(r-1+n.length)%n.length;else if(e.key==="Home")i=0;else if(e.key==="End")i=n.length-1;else return;e.preventDefault();const s=n[i];if(!s)return;if(s.id==="results-summary-tab")Ep();else{const a=s.dataset.artifactId;a&&nc(a)}const o=s.id==="results-summary-tab"?document.getElementById("results-summary-tab"):document.querySelector(`#artifact-tabs .artifact-tab[data-artifact-id="${s.dataset.artifactId}"]`);o&&o.focus()}))}function eo(){document.body.classList.add("results-fullscreen"),document.body.classList.add("results-with-sidebar");const t=document.getElementById("results-view"),e=document.getElementById("results-code-output"),n=document.getElementById("results-audit-output"),i=document.getElementById("results-summary-detail"),r=document.getElementById("artifact-results-split"),s=Uw(),o=Ol();if(i&&(i.setAttribute("role","tabpanel"),i.setAttribute("aria-labelledby","results-summary-tab")),r){r.setAttribute("role","tabpanel");const a=s?.artifacts?.find(l=>l.id===y.selectedArtifactId);r.setAttribute("aria-labelledby",a?`artifact-tab-${a.id}`:"results-summary-tab")}if(qw(s),Vw(s),e&&(e.textContent=""),e){const a=Eh(o);e.innerHTML=a}n&&(n.innerHTML=zw(s)),i&&i.classList.toggle("hidden",y.resultsViewMode!=="summary"),r&&r.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function ur(t,e){nn(!0),y.selectedArtifactId||(y.selectedArtifactId=oi(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const n=document.getElementById("step3-output");n&&(n.textContent=""),eo(),rn(),Gw()}function Gw(){const t=document.getElementById("btn-feedback-up"),e=document.getElementById("btn-feedback-down"),n=document.getElementById("results-feedback-status");t&&(t.className="feedback-btn",t.setAttribute("aria-pressed","false"),t.disabled=!1,t.removeAttribute("aria-disabled")),e&&(e.className="feedback-btn",e.setAttribute("aria-pressed","false"),e.disabled=!1,e.removeAttribute("aria-disabled")),n&&(n.textContent=""),Ja=!1}function nc(t){y.selectedArtifactId=t,y.resultsViewMode="file",eo()}function Ep(){y.resultsViewMode="summary",eo()}function Kw(){const t=document.getElementById("btn-copy-results"),e=document.getElementById("results-copy-status"),n=Ol(),i=(r,s)=>{e&&(e.textContent=r,e.classList.toggle("ok",!!s),e.classList.toggle("fail",!s))};if(!navigator.clipboard?.writeText){i("Copying isn't supported in this browser.",!1);return}navigator.clipboard.writeText(n).then(()=>{if(i("Copied to clipboard",!0),t){t.classList.add("copied");const r=t.querySelector("span");if(r){const s=r.textContent;r.textContent="Copied!",setTimeout(()=>{t.classList.remove("copied"),r.textContent=s},2e3)}}}).catch(()=>{i("Clipboard permission was denied. Select the code to copy it manually.",!1)})}let Ja=!1;async function Yw(t){const e=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down"),i=document.getElementById("results-feedback-status");if(!e||!n||Ja)return;const r=l=>{i&&(i.textContent="",i.offsetWidth,i.textContent=l)},s=l=>{Ja=l,[e,n].forEach(u=>{u.disabled=l,u.setAttribute("aria-disabled",String(l))})},o=t==="up"?"thumbsUp":"thumbsDown";s(!0),r("Submitting review feedback…");const a={type:o,code:y.step2Result,input:y.step1Result};try{const l=await zl(a.type,a.code,a.input);if(!l||l.success!==!0){s(!1),r("Review feedback could not be sent. Tap again to retry.");return}e.classList.toggle("active-up",t==="up"),n.classList.toggle("active-down",t==="down"),e.setAttribute("aria-pressed",String(t==="up")),n.setAttribute("aria-pressed",String(t==="down")),s(!1),r("Review feedback saved.")}catch{s(!1),r("Review feedback could not be sent. Tap again to retry.")}}function Jw(){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 Sp(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}function nn(t){const e=document.getElementById("generation-stage");e&&(t?(e.hidden=!1,e.inert=!1,requestAnimationFrame(()=>e.classList.add("is-active"))):(e.classList.remove("is-active"),e.inert=!0,setTimeout(()=>{e.classList.contains("is-active")||(e.hidden=!0)},260)))}function xp(){const t=z.isVerified&&!!z.email,e=ce.tier||"free",n=t&&pi(),i=!t||Tt(),s=n?"Checking…":i?gl[e]||"Free":"—",o=document.getElementById("topbar-plan");o&&(o.textContent=s);const a=document.getElementById("topbar-avatar");a&&(a.textContent=(z.email||"?")[0].toUpperCase()),Gl();const l=document.getElementById("plans-free-current");l&&l.classList.toggle("hidden",e!=="free"||!i);const u=document.getElementById("plans-checkout-btn-professional");if(u){const d=e==="professional"&&i;u.disabled=d,u.textContent=d?"Current plan":"Subscribe"}const c=document.getElementById("plans-checkout-btn-power");if(c){const d=e==="power"&&i;c.disabled=d,c.textContent=d?"Current plan":"Subscribe"}}function Zw(){xp();const t=document.getElementById("credits-modal");t&&He(t)}function Xw(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("credits-modal");e&&We(e)}function Ip(t,e=!0,n=!0){if(t=["home","account","plans"].includes(t)?t:"home",document.querySelectorAll(".view[data-view]").forEach(r=>{r.dataset.view===t?(r.hidden=!1,r.removeAttribute("inert"),requestAnimationFrame(()=>{r.classList.add("is-active"),n&&r.focus({preventScroll:!0})})):(r.classList.remove("is-active"),r.setAttribute("inert","true"),setTimeout(()=>{r.classList.contains("is-active")||(r.hidden=!0)},260))}),t!=="home")nn(!1);else{const r=document.getElementById("main-stage-container");r&&r.classList.contains("visible")&&nn(!0)}if(document.querySelectorAll(".nav-link[data-view]").forEach(r=>{const s=r.dataset.view===t;r.setAttribute("aria-current",s?"page":null),s||r.removeAttribute("aria-current")}),e){const r=t==="home"?"":`#${t}`;window.location.hash!==r&&window.history.pushState({view:t},"",r||"#")}}let ld=!1;function ic(){const t=window.location.hash.replace(/^#/,"");Ip(t||"home",!1,ld),ld=!0}window.addEventListener("popstate",t=>{ic()});window.addEventListener("hashchange",()=>{ic()});window.copyResultsCode=Kw;window.selectArtifact=nc;window.selectResultsSummary=Ep;window.submitResultsFeedback=Yw;window.showErrorInputPanel=Jw;window.hideErrorInputPanel=Sp;window.setGenerationStageVisible=nn;window.switchView=Ip;window.selectPipelineStage=$w;window.editPipelinePrompt=Ya;window.retryPipelineRun=wp;window.openCreditsModal=Zw;window.closeCreditsModal=Xw; + `}).join(""),i.onclick=s=>{const o=s.target.closest(".artifact-tab");o?.dataset?.artifactId&&nc(o.dataset.artifactId)},ld()),e&&e.classList.add("visible")}function ld(){const t=document.getElementById("bundle-strip");!t||t.dataset.tabKeyboard==="bound"||(t.dataset.tabKeyboard="bound",t.addEventListener("keydown",e=>{if(e.defaultPrevented)return;const n=[document.getElementById("results-summary-tab"),...Array.from(document.querySelectorAll("#artifact-tabs .artifact-tab"))].filter(Boolean);if(!n.length||!n.includes(document.activeElement))return;let i=-1;const r=n.indexOf(document.activeElement);if(e.key==="ArrowRight")i=(r+1)%n.length;else if(e.key==="ArrowLeft")i=(r-1+n.length)%n.length;else if(e.key==="Home")i=0;else if(e.key==="End")i=n.length-1;else return;e.preventDefault();const s=n[i];if(!s)return;if(s.id==="results-summary-tab")Sp();else{const a=s.dataset.artifactId;a&&nc(a)}const o=s.id==="results-summary-tab"?document.getElementById("results-summary-tab"):document.querySelector(`#artifact-tabs .artifact-tab[data-artifact-id="${s.dataset.artifactId}"]`);o&&o.focus()}))}function eo(){document.body.classList.add("results-fullscreen"),document.body.classList.add("results-with-sidebar");const t=document.getElementById("results-view"),e=document.getElementById("results-code-output"),n=document.getElementById("results-audit-output"),i=document.getElementById("results-summary-detail"),r=document.getElementById("artifact-results-split"),s=Uw(),o=Ol();if(i&&(i.setAttribute("role","tabpanel"),i.setAttribute("aria-labelledby","results-summary-tab")),r){r.setAttribute("role","tabpanel");const a=s?.artifacts?.find(l=>l.id===y.selectedArtifactId);r.setAttribute("aria-labelledby",a?`artifact-tab-${a.id}`:"results-summary-tab")}if(qw(s),Vw(s),e&&(e.textContent=""),e){const a=Sh(o);e.innerHTML=a}n&&(n.innerHTML=zw(s)),i&&i.classList.toggle("hidden",y.resultsViewMode!=="summary"),r&&r.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function ur(t,e){nn(!0),y.selectedArtifactId||(y.selectedArtifactId=oi(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const n=document.getElementById("step3-output");n&&(n.textContent=""),eo(),rn(),Gw()}function Gw(){const t=document.getElementById("btn-feedback-up"),e=document.getElementById("btn-feedback-down"),n=document.getElementById("results-feedback-status");t&&(t.className="feedback-btn",t.setAttribute("aria-pressed","false"),t.disabled=!1,t.removeAttribute("aria-disabled")),e&&(e.className="feedback-btn",e.setAttribute("aria-pressed","false"),e.disabled=!1,e.removeAttribute("aria-disabled")),n&&(n.textContent=""),Ja=!1}function nc(t){y.selectedArtifactId=t,y.resultsViewMode="file",eo()}function Sp(){y.resultsViewMode="summary",eo()}function Kw(){const t=document.getElementById("btn-copy-results"),e=document.getElementById("results-copy-status"),n=Ol(),i=(r,s)=>{e&&(e.textContent=r,e.classList.toggle("ok",!!s),e.classList.toggle("fail",!s))};if(!navigator.clipboard?.writeText){i("Copying isn't supported in this browser.",!1);return}navigator.clipboard.writeText(n).then(()=>{if(i("Copied to clipboard",!0),t){t.classList.add("copied");const r=t.querySelector("span");if(r){const s=r.textContent;r.textContent="Copied!",setTimeout(()=>{t.classList.remove("copied"),r.textContent=s},2e3)}}}).catch(()=>{i("Clipboard permission was denied. Select the code to copy it manually.",!1)})}let Ja=!1;async function Yw(t){const e=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down"),i=document.getElementById("results-feedback-status");if(!e||!n||Ja)return;const r=l=>{i&&(i.textContent="",i.offsetWidth,i.textContent=l)},s=l=>{Ja=l,[e,n].forEach(u=>{u.disabled=l,u.setAttribute("aria-disabled",String(l))})},o=t==="up"?"thumbsUp":"thumbsDown";s(!0),r("Submitting review feedback…");const a={type:o,code:y.step2Result,input:y.step1Result};try{const l=await zl(a.type,a.code,a.input);if(!l||l.success!==!0){s(!1),r("Review feedback could not be sent. Tap again to retry.");return}e.classList.toggle("active-up",t==="up"),n.classList.toggle("active-down",t==="down"),e.setAttribute("aria-pressed",String(t==="up")),n.setAttribute("aria-pressed",String(t==="down")),s(!1),r("Review feedback saved.")}catch{s(!1),r("Review feedback could not be sent. Tap again to retry.")}}function Jw(){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 xp(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}function nn(t){const e=document.getElementById("generation-stage");e&&(t?(e.hidden=!1,e.inert=!1,requestAnimationFrame(()=>e.classList.add("is-active"))):(e.classList.remove("is-active"),e.inert=!0,setTimeout(()=>{e.classList.contains("is-active")||(e.hidden=!0)},260)))}function Ip(){const t=z.isVerified&&!!z.email,e=ce.tier||"free",n=t&&pi(),i=!t||Tt(),s=n?"Checking…":i?gl[e]||"Free":"—",o=document.getElementById("topbar-plan");o&&(o.textContent=s);const a=document.getElementById("topbar-avatar");a&&(a.textContent=(z.email||"?")[0].toUpperCase()),Gl();const l=document.getElementById("plans-free-current");l&&l.classList.toggle("hidden",e!=="free"||!i);const u=document.getElementById("plans-checkout-btn-professional");if(u){const d=e==="professional"&&i;u.disabled=d,u.textContent=d?"Current plan":"Subscribe"}const c=document.getElementById("plans-checkout-btn-power");if(c){const d=e==="power"&&i;c.disabled=d,c.textContent=d?"Current plan":"Subscribe"}}function Zw(){Ip();const t=document.getElementById("credits-modal");t&&He(t)}function Xw(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("credits-modal");e&&We(e)}function kp(t,e=!0,n=!0){if(t=["home","account","plans"].includes(t)?t:"home",document.querySelectorAll(".view[data-view]").forEach(r=>{r.dataset.view===t?(r.hidden=!1,r.removeAttribute("inert"),requestAnimationFrame(()=>{r.classList.add("is-active"),n&&r.focus({preventScroll:!0})})):(r.classList.remove("is-active"),r.setAttribute("inert","true"),setTimeout(()=>{r.classList.contains("is-active")||(r.hidden=!0)},260))}),t!=="home")nn(!1);else{const r=document.getElementById("main-stage-container");r&&r.classList.contains("visible")&&nn(!0)}if(document.querySelectorAll(".nav-link[data-view]").forEach(r=>{const s=r.dataset.view===t;r.setAttribute("aria-current",s?"page":null),s||r.removeAttribute("aria-current")}),e){const r=t==="home"?"":`#${t}`;window.location.hash!==r&&window.history.pushState({view:t},"",r||"#")}}let cd=!1;function ic(){const t=window.location.hash.replace(/^#/,"");kp(t||"home",!1,cd),cd=!0}window.addEventListener("popstate",t=>{ic()});window.addEventListener("hashchange",()=>{ic()});window.copyResultsCode=Kw;window.selectArtifact=nc;window.selectResultsSummary=Sp;window.submitResultsFeedback=Yw;window.showErrorInputPanel=Jw;window.hideErrorInputPanel=xp;window.setGenerationStageVisible=nn;window.switchView=kp;window.selectPipelineStage=$w;window.editPipelinePrompt=Ya;window.retryPipelineRun=bp;window.openCreditsModal=Zw;window.closeCreditsModal=Xw; diff --git a/dist/index.html b/dist/index.html index f999c8a..29ae3da 100644 --- a/dist/index.html +++ b/dist/index.html @@ -3313,7 +3313,7 @@ .send.is-busy .send-spin { animation: none; opacity: 0.6; } } - + diff --git a/e2e/stu380-deploy.spec.js b/e2e/stu380-deploy.spec.js index 16c13f2..db16415 100644 --- a/e2e/stu380-deploy.spec.js +++ b/e2e/stu380-deploy.spec.js @@ -74,6 +74,7 @@ test.describe("STU-380 deployment terminal outcomes", () => { test("a 403 rejection is a failure that never claims committed", async ({ page }) => { await render(page, { success: false, + remoteRefusal: true, targetIdentity: identity, error: "HTTP 403 Forbidden — your FlutterFlow API key lacks write access.", }); @@ -90,6 +91,7 @@ test.describe("STU-380 deployment terminal outcomes", () => { const terminal = page.locator("#commit-terminal-modal"); await expect(terminal).toBeVisible(); await expect(terminal).toContainText("Deploy failed"); + await expect(terminal).toContainText("FlutterFlow refused this deploy"); await expect(terminal).toContainText("403"); await expect(terminal).toContainText(identity.projectId); await expect(terminal).not.toContainText("Committed"); @@ -98,6 +100,7 @@ test.describe("STU-380 deployment terminal outcomes", () => { test("a per-file rejection surfaces each file's error, not a blanket success", async ({ page }) => { await render(page, { success: false, + remoteRefusal: true, targetIdentity: identity, error: "FlutterFlow rejected 1 of 1 files.", errorMap: { @@ -130,10 +133,13 @@ test.describe("STU-380 deployment terminal outcomes", () => { await expect(output).toContainText("does not compile"); await expect(output).not.toContainText("committed"); - // The analyzer refusal reaches the visible terminal too. + // The analyzer refusal reaches the visible terminal too — a local gate, + // so it must not claim FlutterFlow refused a request it never received. const terminal = page.locator("#commit-terminal-modal"); await expect(terminal).toBeVisible(); await expect(terminal).toContainText("Deploy failed"); + await expect(terminal).toContainText("before FlutterFlow confirmed anything"); + await expect(terminal).not.toContainText("refused this deploy"); await expect(terminal).toContainText("does not compile"); }); @@ -567,6 +573,47 @@ test.describe("STU-380 transport outcome regressions", () => { expect(outcome.outcome).toBe("unconfirmed"); }); + test("a timed-out push issues no further writes once the UI gives up", async ({ page }) => { + await loadDeployHooks(page); + + // The bound expires mid-attempt; when the stalled request finally answers + // 500, the loop must not send another POST — the outcome is already + // reported and the user may have started a new deploy. + const outcome = await page.evaluate(async () => { + let calls = 0; + window.fetch = (url) => { + if (!String(url).includes("syncCustomCodeChanges")) { + return Promise.resolve(new Response("{}", { status: 200 })); + } + calls += 1; + return new Promise((resolve) => + setTimeout(() => resolve(new Response("err", { status: 500 })), 120), + ); + }; + try { + await window.__CCC_PUSH_CODE_WITH_TIMEOUT__( + { project_id: "ff-proj-0007", zipped_custom_code: "eA==" }, + 75, + ); + return { settled: "resolved", calls }; + } catch (error) { + // Wait past the retry sleep so a further attempt would have fired. + await new Promise((r) => setTimeout(r, 1500)); + return { + settled: "rejected", + calls, + name: error.name, + outcome: error.outcome, + }; + } + }); + + expect(outcome.settled).toBe("rejected"); + expect(outcome.name).toBe("UnconfirmedDeployError"); + expect(outcome.outcome).toBe("unconfirmed"); + expect(outcome.calls).toBe(1); + }); + test("a sync body that stalls mid-read is unconfirmed under the same bound", async ({ page }) => { await loadDeployHooks(page); From bd605a16dabf99e3e4d45cd851246f3f031a907c Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Sun, 27 Sep 2026 17:44:28 +0000 Subject: [PATCH 10/16] fix(deploy): runner failures after deploy begins are unconfirmed, not refusals MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A streamed result{success:false} only proves the runner finished — the deploy CLI can fail or time out after its upload phase already wrote classes. Marking every runner-reported failure remoteRefusal rendered the FAILED modal's 'nothing was applied / safe to retry' copy over state the runner could not verify. Classify runner failures by stage: the stream's last phase (deploy_start or later → unconfirmed; workspace/verifying → failed), analyzerErrors as a compile-gate proof, an explicit preWrite field new runners now emit, or a non-streaming runner's real HTTP status (4xx refused, 5xx unknown). Co-Authored-By: Stuart Gardoll --- app.js | 17 +- cloud-run/ffai-runner/bin/server.dart | 12 ++ .../{index-DbNvpST8.js => index-B66yOOGg.js} | 154 +++++++++--------- dist/index.html | 2 +- e2e/stu380-deploy.spec.js | 47 ++++++ src/provisionStream.js | 52 +++++- src/provisionStream.test.js | 84 +++++++++- 7 files changed, 281 insertions(+), 87 deletions(-) rename dist/assets/{index-DbNvpST8.js => index-B66yOOGg.js} (79%) diff --git a/app.js b/app.js index 75b6db5..d367a3c 100644 --- a/app.js +++ b/app.js @@ -2831,11 +2831,18 @@ async function provisionMissingCodeFiles( if (!result.success) { const details = result.details ? ` ${result.details}` : ""; - // The runner streamed a definitive failure result — a remote decision, - // not a local one. - const refusal = new Error( - `${result.error || "FlutterFlow custom class provisioning failed."}${details}`, - ); + const message = `${result.error || "FlutterFlow custom class provisioning failed."}${details}`; + // A runner-reported failure is only a definitive refusal when it provably + // precedes the write; a failure after the deploy began can follow classes + // already uploaded, so it must be reported unconfirmed. + if (deployOutcomeOfStreamResult(result) === DeployOutcome.UNCONFIRMED) { + throw new UnconfirmedDeployError( + `${message} The failure arrived after the deploy began — custom classes ` + + "may already be written. Open your FlutterFlow project to reconcile " + + "before retrying.", + ); + } + const refusal = new Error(message); refusal.remoteRefusal = true; throw refusal; } diff --git a/cloud-run/ffai-runner/bin/server.dart b/cloud-run/ffai-runner/bin/server.dart index 49ae5aa..99181c2 100644 --- a/cloud-run/ffai-runner/bin/server.dart +++ b/cloud-run/ffai-runner/bin/server.dart @@ -52,6 +52,7 @@ Future _handle(HttpRequest request) async { await channel.result(HttpStatus.notFound, { 'success': false, 'error': 'Not found.', + 'preWrite': true, }); return; } @@ -89,6 +90,8 @@ Future _handle(HttpRequest request) async { : 'FlutterFlow AI workspace initialization failed.', 'details': _trimOutput(initResult.output), 'exitCode': initResult.exitCode, + // Workspace setup precedes any write to FlutterFlow. + 'preWrite': true, }); return; } @@ -106,6 +109,8 @@ Future _handle(HttpRequest request) async { 'deployed to FlutterFlow.', 'details': analysis.report, 'analyzerErrors': analysis.errors, + // The compile gate runs before the deploy script starts. + 'preWrite': true, }); return; } @@ -153,6 +158,8 @@ Future _handle(HttpRequest request) async { 'success': false, 'error': 'FlutterFlow AI DSL deploy timed out.', 'details': _trimOutput(result.output), + // The CLI may already have uploaded classes before timing out. + 'preWrite': false, }); return; } @@ -163,6 +170,7 @@ Future _handle(HttpRequest request) async { 'error': 'FlutterFlow AI DSL deploy failed.', 'details': _trimOutput(result.output), 'exitCode': result.exitCode, + 'preWrite': false, }); return; } @@ -184,6 +192,8 @@ Future _handle(HttpRequest request) async { await channel.result(HttpStatus.badRequest, { 'success': false, 'error': error.message, + // Request validation precedes any work against the project. + 'preWrite': true, }); } catch (error, stackTrace) { stderr.writeln(error); @@ -191,6 +201,8 @@ Future _handle(HttpRequest request) async { await channel.result(HttpStatus.internalServerError, { 'success': false, 'error': '$error', + // The stage is unknown, so the write cannot be proven not to have run. + 'preWrite': false, }); } } diff --git a/dist/assets/index-DbNvpST8.js b/dist/assets/index-B66yOOGg.js similarity index 79% rename from dist/assets/index-DbNvpST8.js rename to dist/assets/index-B66yOOGg.js index 713c06f..c541dd2 100644 --- a/dist/assets/index-DbNvpST8.js +++ b/dist/assets/index-B66yOOGg.js @@ -1,7 +1,7 @@ -(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const s of r)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function n(r){const s={};return r.integrity&&(s.integrity=r.integrity),r.referrerPolicy&&(s.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?s.credentials="include":r.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function i(r){if(r.ep)return;r.ep=!0;const s=n(r);fetch(r.href,s)}})();var w=typeof window<"u"?window:void 0,Le=typeof globalThis<"u"?globalThis:w,Ue=Le?.navigator,P=Le?.document,me=Le?.location,Za=Le?.fetch,qo=Le!=null&&Le.XMLHttpRequest&&"withCredentials"in new Le.XMLHttpRequest?Le.XMLHttpRequest:void 0,uc=Le?.AbortController,$p=Le?.CompressionStream,Ve=Ue?.userAgent;function ud(){return!(!w||w.navigator.onLine===!1)}var vi=typeof globalThis<"u"?globalThis:w;vi&&typeof self>"u"&&(vi.self=vi),vi&&typeof File>"u"&&(vi.File=function(){});var B=w??{},ne={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function dc(t,e,n,i,r,s,o){try{var a=t[s](o),l=a.value}catch(u){return void n(u)}a.done?e(l):Promise.resolve(l).then(i,r)}function se(t){return function(){var e=this,n=arguments;return new Promise((function(i,r){var s=t.apply(e,n);function o(l){dc(s,i,r,o,a,"next",l)}function a(l){dc(s,i,r,o,a,"throw",l)}o(void 0)}))}}function I(){return I=Object.assign?Object.assign.bind():function(t){for(var e=1;arguments.length>e;e++){var n=arguments[e];for(var i in n)({}).hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},I.apply(null,arguments)}function dd(t,e){if(t==null)return{};var n={};for(var i in t)if({}.hasOwnProperty.call(t,i)){if(e.indexOf(i)!==-1)continue;n[i]=t[i]}return n}var fc=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function hc(t){return typeof t=="string"||t}function pc(t){return typeof t=="string"?t:void 0}var _i,Mp=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],Ut=(function(t){return t.AnonymousId="anonymous_id",t.DistinctId="distinct_id",t.Props="props",t.EnablePersonProcessing="enable_person_processing",t.PersonMode="person_mode",t.FeatureFlagDetails="feature_flag_details",t.FeatureFlags="feature_flags",t.FeatureFlagPayloads="feature_flag_payloads",t.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",t.BootstrapFeatureFlags="bootstrap_feature_flags",t.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",t.OverrideFeatureFlags="override_feature_flags",t.Queue="queue",t.AiQueue="ai_queue",t.LogsQueue="logs_queue",t.OptedOut="opted_out",t.SessionId="session_id",t.SessionStartTimestamp="session_start_timestamp",t.SessionLastTimestamp="session_timestamp",t.PersonProperties="person_properties",t.GroupProperties="group_properties",t.InstalledAppBuild="installed_app_build",t.InstalledAppVersion="installed_app_version",t.SessionReplay="session_replay",t.PushRegistered="push_registered",t.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",t.SurveyLastSeenDate="survey_last_seen_date",t.SurveysSeen="surveys_seen",t.Surveys="surveys",t.RemoteConfig="remote_config",t.FlagsEndpointWasHit="flags_endpoint_was_hit",t.DeviceId="device_id",t})({}),gc=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),Lp=["$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"],Np=["token"],fd="NativeGzipValidationError",zo=t=>t.length>=2&&t[0]===31&&t[1]===139,mc=(t,e)=>t===gc.GZipJS||e===gc.GZipJS||e==="gzip",vc=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",pr=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=fd,e},Op=(function(){var t=se((function*(e,n){18>e.size&&pr("too-short");var i=new Uint8Array(yield e.slice(0,10).arrayBuffer());zo(i)&&i[2]===8||pr("invalid-header");var r=new DataView(yield e.slice(e.size-8).arrayBuffer());r.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(_i)return _i;_i=[];for(var c=0;256>c;c++){for(var d=c,h=0;8>h;h++)d=1&d?3988292384^d>>>1:d>>>1;_i[c]=d>>>0}return _i})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(n)&&pr("invalid-crc");var s=n.length>>>0;r.getUint32(4,!0)!==s&&pr("invalid-size")}));return function(e,n){return t.apply(this,arguments)}})();function Vo(){return Vo=se((function*(t,e,n){e===void 0&&(e=!0);try{var i=new TextEncoder().encode(t),r=new globalThis.CompressionStream("gzip"),s=r.writable.getWriter(),o=s.write(i).then((()=>s.close())).catch((function(){var u=se((function*(c){try{yield s.abort(c)}catch{}throw c}));return function(c){return u.apply(this,arguments)}})()),a=new Response(r.readable).blob(),l=(yield Promise.all([a,o]))[0];return yield Op(l,i),l}catch(u){if(n!=null&&n.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),Vo.apply(this,arguments)}var Bp=["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"],_c=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var n=t.toLowerCase();return Bp.concat(e).some((i=>{var r=i.toLowerCase();return n.indexOf(r)!==-1}))};function j(t,e){return t.indexOf(e)!==-1}var xs=function(t){return t.trim()},Go=function(t){return t.replace(/^\$/,"")};function hd(t){var e,n=[];return(e=JSON.stringify(t,(function(i,r){if(typeof r=="bigint")return r.toString();if(typeof r!="function"&&typeof r!="symbol"){if(r instanceof Error)return{name:r.name,message:r.message,stack:r.stack};if(r&&typeof r=="object"){for(;n.length>0&&n[n.length-1]!==this;)n.pop();if(n.includes(r))return"[Circular]";n.push(r)}return r}})))!==null&&e!==void 0?e:"null"}var pd=Object.prototype,gd=pd.hasOwnProperty,Is=pd.toString,U=Array.isArray||function(t){return Is.call(t)==="[object Array]"},De=t=>typeof t=="function",he=t=>t===Object(t)&&!U(t),Kt=t=>{if(he(t)){for(var e in t)if(gd.call(t,e))return!1;return!0}return!1},C=t=>t===void 0,X=t=>Is.call(t)=="[object String]",Ko=t=>X(t)&&t.trim().length===0,Ke=t=>t===null,H=t=>C(t)||Ke(t),ke=t=>Is.call(t)=="[object Number]"&&t==t,Dt=t=>ke(t)&&t>0,mt=t=>Is.call(t)==="[object Boolean]",Dp=t=>t instanceof FormData,jp=t=>j(Lp,t),Up=t=>j(Np,t);function md(t){return t===null||typeof t!="object"}function Hr(t,e){return{}.toString.call(t)==="[object "+e+"]"}function Xa(t){return typeof Event<"u"&&vd(t,Event)}function vd(t,e){try{return t instanceof e}catch{return!1}}var Hp=[!0,"true",1,"1","yes"],uo=t=>j(Hp,t),Wp=[!1,"false",0,"0","no"];function At(t,e,n,i,r){return e>n&&(i.warn("min cannot be greater than max."),e=n),ke(t)?t>n?(i.warn(" cannot be greater than max: "+n+". Using max value instead."),n):e>t?(i.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(i.warn(" must be a number. using max or fallback. max: "+n+", fallback: "+r),At(r||n,e,n,i))}class qp{constructor(e){this.tt={},this.et=e.et,this.it=At(e.bucketSize,0,100,e.rt),this.nt=At(e.refillRate,0,this.it,e.rt),this.st=At(e.refillInterval,0,864e5,e.rt)}ot(e,n){var i=Math.floor((n-e.lastAccess)/this.st);i>0&&(e.tokens=Math.min(e.tokens+i*this.nt,this.it),e.lastAccess=e.lastAccess+i*this.st)}consumeRateLimit(e){var n,i=Date.now(),r=String(e),s=this.tt[r];return s?this.ot(s,i):this.tt[r]=s={tokens:this.it,lastAccess:i},s.tokens===0||(s.tokens--,s.tokens===0&&((n=this.et)==null||n.call(this,e)),s.tokens===0)}stop(){this.tt={}}}var it="Mobile",Wr="iOS",Yt="Android",ei="Tablet",_d=Yt+" "+ei,yd="iPad",wd="Apple",bd=wd+" Watch",Bi="Safari",ti="BlackBerry",Ed="Samsung",Sd=Ed+"Browser",xd=Ed+" Internet",Pn="Chrome",zp=Pn+" OS",Id=Pn+" "+Wr,Qa="Internet Explorer",kd=Qa+" "+it,el="Opera",Vp=el+" Mini",tl="Edge",Cd="Microsoft "+tl,Zn="Firefox",Ad=Zn+" "+Wr,Gi="Nintendo",Ki="PlayStation",Xn="Xbox",Pd=Yt+" "+it,Fd=it+" "+Bi,Pi="Windows",Yo=Pi+" Phone",yc="Nokia",Jo="Ouya",Rd="Generic",Gp=Rd+" "+it.toLowerCase(),Td=Rd+" "+ei.toLowerCase(),Zo="Konqueror",$d="Oculus Browser",qr="Vivaldi",Md="Yandex",zr="Whale",Xo="DuckDuckGo",Ld="Pale Moon",Vr="Waterfox",Di="Brave",Nd="Google Search App",we="(\\d+(\\.\\d+)?)",fo=new RegExp("Version/"+we),Kp=new RegExp(Xn,"i"),Yp=new RegExp(Ki+" \\w+","i"),Jp=new RegExp(Gi+" \\w+","i"),nl=new RegExp(ti+"|PlayBook|BB10","i"),Zp={"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"},Od=function(t,e,n,i){e=e||"";var r=(function(s){return s!=null&&s.brave?Di:null})(n);return r||(i!=null&&i.detectGoogleSearchApp&&j(t,"GSA/")?Nd:j(t," OPR/")&&j(t,"Mini")?Vp:j(t," OPR/")?el:nl.test(t)?ti:j(t,"IE"+it)||j(t,"WPDesktop")?kd:j(t,"OculusBrowser")?$d:j(t,Sd)?xd:j(t,tl)||j(t,"Edg/")?Cd:j(t,qr+"/")?qr:j(t,"YaBrowser/")?Md:j(t,zr+"/")?zr:j(t,Xo+"/")||j(t,"Ddg/")?Xo:j(t,"FBIOS")?"Facebook "+it:j(t,"UCWEB")||j(t,"UCBrowser")?"UC Browser":j(t,"CriOS")?Id:j(t,"CrMo")||j(t,Pn)?Pn:j(t,Yt)&&j(t,Bi)?Pd:j(t,"FxiOS")?Ad:j(t.toLowerCase(),Zo.toLowerCase())?Zo:j(t,Di+"/")?Di:((s,o)=>o&&j(o,wd)||(function(a){return j(a,Bi)&&!j(a,Pn)&&!j(a,Yt)})(s))(t,e)?j(t,it)?Fd:Bi:j(t,"PaleMoon/")?Ld:j(t,Vr+"/")?Vr:j(t,Zn)?Zn:j(t,"MSIE")||j(t,"Trident/")?Qa:j(t,"Gecko")?Zn:"")},Xp={[kd]:[new RegExp("rv:"+we)],[Cd]:[new RegExp(tl+"?\\/"+we)],[Pn]:[new RegExp("("+Pn+"|CrMo)\\/"+we)],[Id]:[new RegExp("CriOS\\/"+we)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+we)],[Bi]:[fo],[Fd]:[fo],[el]:[new RegExp("(Opera|OPR)\\/"+we)],[Zn]:[new RegExp(Zn+"\\/"+we)],[Ad]:[new RegExp("FxiOS\\/"+we)],[Zo]:[new RegExp("Konqueror[:/]?"+we,"i")],[ti]:[new RegExp(ti+" "+we),fo],[Pd]:[new RegExp("android\\s"+we,"i")],[xd]:[new RegExp(Sd+"\\/"+we)],[$d]:[new RegExp("OculusBrowser\\/"+we)],[qr]:[new RegExp(qr+"\\/"+we)],[Md]:[new RegExp("YaBrowser\\/"+we)],[zr]:[new RegExp(zr+"\\/"+we)],[Di]:[new RegExp(Di+"\\/"+we)],[Xo]:[new RegExp("(DuckDuckGo|Ddg)\\/"+we)],[Ld]:[new RegExp("PaleMoon\\/"+we)],[Vr]:[new RegExp(Vr+"\\/"+we)],[Nd]:[new RegExp("GSA\\/"+we)],[Qa]:[new RegExp("(rv:|MSIE )"+we)],Mozilla:[new RegExp("rv:"+we)]},Qp=function(t,e,n,i){var r=Od(t,e,n,i),s=Xp[r];if(C(s))return null;for(var o=0;s.length>o;o++){var a=t.match(s[o]);if(a)return parseFloat(a[a.length-2])}return null},wc=[[new RegExp(Xn+"; "+Xn+" (.*?)[);]","i"),t=>[Xn,t&&t[1]||""]],[new RegExp(Gi,"i"),[Gi,""]],[new RegExp(Ki,"i"),[Ki,""]],[nl,[ti,""]],[new RegExp(Pi,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Yo,""];if(new RegExp(it).test(e)&&!/IEMobile\b/.test(e))return[Pi+" "+it,""];var n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){var i=Zp[n[1]]||"";return/arm/i.test(e)&&(i="RT"),[Pi,i]}return[Pi,""]}],[/((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=C(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+Yt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Yt+")","i"),t=>t&&t[2]?[Yt,[t[2],t[3],t[4]||"0"].join(".")]:[Yt,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{var e=["Mac OS X",""];return t&&t[1]&&(e[1]=[t[1],t[2],t[3]||"0"].join(".")),e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[zp,""]],[/Linux|debian/i,["Linux",""]]],bc=function(t){return Jp.test(t)?Gi:Yp.test(t)?Ki:Kp.test(t)?Xn:new RegExp(Jo,"i").test(t)?Jo:new RegExp("("+Yo+"|WPDesktop)","i").test(t)?Yo:/iPad/.test(t)?yd:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?bd:nl.test(t)?ti:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(yc,"i").test(t)?yc:/(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(it).test(t)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(t)||/pixel[\daxl ]{1,6}/i.test(t)&&!/pixel c/i.test(t)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(t)||/lmy47v/i.test(t)&&!/QTAQZ3/i.test(t)?Yt:_d:new RegExp("(pda|"+it+")","i").test(t)?Gp:new RegExp(ei,"i").test(t)&&!new RegExp(ei+" pc","i").test(t)?Td:""},eg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ec(t,e){return typeof(n=t)=="string"&&eg.test(n)?t:e();var n}function fn(t){return t&&t.split("#")[0]}function il(t,e){var n=setTimeout(t,e);return n?.unref&&n?.unref(),n}function Sc(t,e,n){return Bd.apply(this,arguments)}function Bd(){return(Bd=se((function*(t,e,n){var i;try{return yield Promise.race([t,new Promise(((r,s)=>{i=il((()=>{try{n?.(),r()}catch(o){s(o)}}),e)}))])}finally{clearTimeout(i)}}))).apply(this,arguments)}var tg=t=>t instanceof Error,Dd={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}},ng=Dd.info;function jd(t){if(mt(t))return{boolValue:t};if(typeof t=="number")return Number.isFinite(t)?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:{stringValue:String(t)};if(typeof t=="string")return{stringValue:t};if(U(t))return{arrayValue:{values:t.map((e=>jd(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function Gr(t){var e=[];for(var n in t){var i=t[n];Ke(i)||C(i)||e.push({key:n,value:jd(i)})}return e}function ig(t,e){var n=Dd[t.level||"info"]||ng,i=n.text,r=n.number,s=String(Date.now())+"000000",o={};e.distinctId&&(o.posthogDistinctId=e.distinctId),e.sessionId&&(o.sessionId=e.sessionId),e.windowId&&(o["window.id"]=e.windowId),H(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),H(e.lastActivityTimestamp)||(o.lastActivityTimestamp=String(e.lastActivityTimestamp)),e.currentUrl&&(o["url.full"]=e.currentUrl),e.screenName&&(o["screen.name"]=e.screenName),e.appState&&(o["app.state"]=e.appState),e.activeFeatureFlags&&e.activeFeatureFlags.length>0&&(o.feature_flags=e.activeFeatureFlags);var a=I({},o,t.attributes||{}),l={timeUnixNano:s,observedTimeUnixNano:s,severityNumber:r,severityText:i,body:{stringValue:t.body},attributes:Gr(a)};return t.trace_id&&(l.traceId=t.trace_id),t.span_id&&(l.spanId=t.span_id),C(t.trace_flags)||(l.flags=t.trace_flags),l}function Ud(t,e,n){return I({},t.resourceAttributes,{"service.name":t.serviceName||"unknown_service"},t.environment&&{"deployment.environment":t.environment},t.serviceVersion&&{"service.version":t.serviceVersion},{"telemetry.sdk.name":e,"telemetry.sdk.version":n})}function Hd(t,e,n,i){return{resourceLogs:[{resource:{attributes:Gr(e)},scopeLogs:[{scope:{name:n,version:i},logRecords:t}]}]}}let rg=class{constructor(t,e,n,i,r,s,o){var a;s===void 0&&(s=()=>Promise.resolve()),this._instance=t,this.Ne=e,this.rt=n,this.ut=i,this.ht=r,this.dt=s,this.vt=o,this.ct=null,this.ft=0,this.yt=0,this.bt=0,this._t=0,this.wt=!1,this.kt=e.maxBufferSize,this.xt=Math.max((a=e.maxQueueSize)!==null&&a!==void 0?a:e.maxBufferSize,e.maxBufferSize),this.St=e.flushIntervalMs,this.Ct=e.maxBatchRecordsPerPost,this.Mt=e.rateCapWindowMs,this.Tt=e.maxLogsPerInterval}reset(){this.Et(),this.ct=null,this.bt=0,this._t=0,this.wt=!1,this.ft=0,this.yt=0,this.Ct=this.Ne.maxBatchRecordsPerPost}onReconnect(){this.yt=0,this.It()}captureLog(t){if(!this._instance.isDisabled&&!this._instance.optedOut&&t!=null&&t.body){var e=this.Pt(t);if(e!==null)if(e.body){if(this.Rt()){var n={record:ig(e,this.ut())};this.ht((()=>this.At(n)))}}else this.rt.info("Log was rejected in beforeSend function")}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Log was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for log:",o),null}return i}Rt(){if(this.Tt===void 0)return!0;var t=Date.now(),e=t-this.bt;return this.Mt>e&&e>=0||(this.bt=t,this._t=0,this.wt=!1),this.Tt>this._t?(this._t++,!0):(this.wt||(this.rt.warn("captureLog dropping logs: exceeded "+this.Tt+" logs per "+this.Mt+"ms"),this.wt=!0),!1)}flush(){var t=this;return se((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return se((function*(){var e;t.Et();var n=(e=t._instance.getPersistedProperty(Ut.LogsQueue))!==null&&e!==void 0?e:[];if(n.length!==0)for(var i=n.length,r=0;n.length>0&&i>r;){var s,o;t.ft=0;var a=Math.min(n.length,t.Ct),l=n.slice(0,a),u=Hd(l.map((d=>d.record)),t.Lt(),(s=t.vt)!==null&&s!==void 0?s:t._instance.getLibraryId(),t._instance.getLibraryVersion()),c=yield t._instance.Ot(u);if(c.kind==="too-large"&&l.length>1)t.Ct=Math.max(1,Math.floor(l.length/2)),t.rt.warn("Received 413 when sending logs batch of size "+l.length+", reducing batch size to "+t.Ct);else if(c.kind==="retry-later"||(c.kind==="too-large"?t.rt.warn("Dropping a single log record after 413 with batch size 1 — the record is larger than the server cap and cannot be split further."):c.kind==="ok"&&t.Ne.maxBatchRecordsPerPost>t.Ct&&(t.Ct=Math.min(t.Ne.maxBatchRecordsPerPost,t.Ct+1)),yield t.Dt(l.length),n=(o=t._instance.getPersistedProperty(Ut.LogsQueue))!==null&&o!==void 0?o:[],r+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return se((function*(){var n,i=Math.max(0,t-e.ft),r=(n=e._instance.getPersistedProperty(Ut.LogsQueue))!==null&&n!==void 0?n:[];e._instance.setPersistedProperty(Ut.LogsQueue,r.slice(i)),yield e.dt()}))()}Lt(){return Ud(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var n=(e=this._instance.getPersistedProperty(Ut.LogsQueue))!==null&&e!==void 0?e:[];this.xt>n.length||(n.shift(),this.ft++,this.rt.info("Logs queue is full, dropping oldest record.")),n.push(t),this._instance.setPersistedProperty(Ut.LogsQueue,n),this.kt>n.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=il((()=>{this.Nt=void 0,this.It()}),t))}qt(){var t=Math.min(Math.max(0,this.yt-1),6);return this.St*Math.pow(2,t)}jt(){var t=this._instance.getPersistedProperty(Ut.LogsQueue);return!!t&&t.length>0}shutdown(t){var e=this;return se((function*(){e.Et();var n=e.flush().catch((()=>{}));t!==void 0?yield Sc(n,t):yield n}))()}flushWithTimeout(t){var e=this;return se((function*(){var n=e.flush();yield Sc(n,t,(()=>{n.catch((()=>{}))}))}))()}It(){this.flush().then((()=>{this.yt=0}),(t=>{this.yt++,this.rt.error("PostHog logs flush failed:",t)})).finally((()=>{!this._instance.isDisabled&&this.jt()&&this.$t(this.qt())}))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}};var ho=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function xc(t){return String(t)+"000000"}function Ic(t,e,n,i){var r="";return i&&(r=Object.keys(i).sort().map((s=>JSON.stringify(s)+":"+JSON.stringify(i[s]))).join(",")),t+"\0"+e+"\0"+(n??"")+"\0"+r}let sg=class{constructor(t,e,n){this._instance=t,this.Ne=e,this.rt=n,this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Wt=0}count(t,e,n){e===void 0&&(e=1),this.Vt({name:t,type:"count",value:e,unit:n?.unit,attributes:n?.attributes})}gauge(t,e,n){this.Vt({name:t,type:"gauge",value:e,unit:n?.unit,attributes:n?.attributes})}histogram(t,e,n){this.Vt({name:t,type:"histogram",value:e,unit:n?.unit,attributes:n?.attributes})}flush(){var t=this,e=this.ct,n=(function(){var r=se((function*(){e&&(yield e.catch((()=>{}))),yield t.Zt()}));return function(){return r.apply(this,arguments)}})(),i=n().finally((()=>{this.ct===i&&(this.ct=null)}));return this.ct=i,i}drainWindow(){if(this.Bt.size===0)return null;var t=this.Bt;return this.Bt=new Map,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Gt(t)}reset(){this.Wt++,this.Et(),this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set}Vt(t){if(!this._instance.isDisabled&&!this._instance.optedOut){var e=this.Pt(t);if(e!==null)if(e.name&&typeof e.name=="string")if(typeof e.value=="number"&&Number.isFinite(e.value))if(e.type==="count"&&0>e.value)this.rt.warn("Dropping count '"+e.name+"': counters are monotonic, value must be >= 0");else{var n,i;try{n=e.attributes?I({},e.attributes):void 0,i=Ic(e.type,e.name,e.unit,n)}catch(o){return void this.rt.warn("Dropping metric '"+e.name+"': attributes could not be serialized",o)}var r=this.Bt.get(i);if(!r){if(!this.Qt())return;r={name:e.name,type:e.type,unit:e.unit,attributes:n,windowStartMs:Date.now()},this.Bt.set(i,r)}var s=this.Ut.get(e.name);s===void 0?this.Ut.set(e.name,e.type):s===e.type||this.zt.has(e.name)||(this.zt.add(e.name),this.rt.warn("Metric name '"+e.name+"' is already used as a "+s+"; recording it as a "+e.type+" too will blend both series in charts. Use a distinct name.")),this.Kt(r,e.value),this.$t()}else this.rt.warn("Dropping metric '"+e.name+"': value must be a finite number");else this.rt.warn("Dropping metric with empty name")}}Qt(){return this.Ne.maxSeriesPerFlush>this.Bt.size||(this.Ht||(this.Ht=!0,this.rt.warn("Metric series cap reached ("+this.Ne.maxSeriesPerFlush+" per flush window); dropping new series until the next flush. Reduce attribute cardinality.")),!1)}Kt(t,e){var n;switch(t.type){case"count":t.total=((n=t.total)!==null&&n!==void 0?n:0)+e;break;case"gauge":t.last=e;break;case"histogram":t.hist||(t.hist={count:0,sum:0,min:e,max:e,bucketCounts:new Array(ho.length+1).fill(0)});var i=t.hist;i.count+=1,i.sum+=e,i.min=Math.min(i.min,e),i.max=Math.max(i.max,e),i.bucketCounts[(function(r,s){for(var o=0;s.length>o;o++)if(s[o]>=r)return o;return s.length})(e,ho)]+=1}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Metric was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for metric:",o),null}return i}$t(){this.Nt||(this.Nt=il((()=>{this.Nt=void 0,this.flush().catch((t=>{this.rt.error("Metrics flush failed:",t)}))}),this.Ne.flushIntervalMs))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}Zt(){var t=this;return se((function*(){if(t.Bt.size!==0){var e=t.Bt;t.Bt=new Map,t.Ht=!1,t.Ut=new Map,t.zt=new Set;var n=t.Wt,i=yield t._instance.Jt(t.Gt(e));if(n===t.Wt)switch(i.kind){case"ok":return;case"retry-later":return t.Yt(e),void t.$t();case"too-large":return void t.rt.warn("Metrics batch exceeded the server size limit and was dropped");case"fatal":return void t.rt.error("Failed to send metrics batch:",i.error)}}}))()}Gt(t){return e=this.Xt(t),n=(function(s,o,a){return I({},s.resourceAttributes,{"service.name":s.serviceName||"unknown_service"},s.environment&&{"deployment.environment":s.environment},s.serviceVersion&&{"service.version":s.serviceVersion},{"telemetry.sdk.name":o,"telemetry.sdk.version":a})})(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion()),i=this._instance.getLibraryId(),r=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:Gr(n)},scopeMetrics:[{scope:{name:i,version:r},metrics:e}]}]};var e,n,i,r}Xt(t){var e=xc(Date.now()),n=new Map;for(var i of t.values()){var r,s=Ic(i.type,i.name,i.unit,void 0),o=n.get(s);o||(o=I({name:i.name},i.unit&&{unit:i.unit}),i.type==="count"?o.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:i.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:1,dataPoints:[]},n.set(s,o));var a=Gr((r=i.attributes)!==null&&r!==void 0?r:{}),l=xc(i.windowStartMs);if(i.type==="count"){var u,c={attributes:a,startTimeUnixNano:l,timeUnixNano:e,asDouble:(u=i.total)!==null&&u!==void 0?u:0};o.sum.dataPoints.push(c)}else if(i.type==="gauge"){var d,h={attributes:a,timeUnixNano:e,asDouble:(d=i.last)!==null&&d!==void 0?d:0};o.gauge.dataPoints.push(h)}else i.hist&&o.histogram.dataPoints.push({attributes:a,startTimeUnixNano:l,timeUnixNano:e,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:ho})}return Array.from(n.values())}Yt(t){var e,n;for(var i of t){var r=i[0],s=i[1],o=this.Bt.get(r);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,s.windowStartMs),o.type){case"count":o.total=((e=o.total)!==null&&e!==void 0?e:0)+((n=s.total)!==null&&n!==void 0?n:0);break;case"gauge":break;case"histogram":if(s.hist)if(o.hist){o.hist.count+=s.hist.count,o.hist.sum+=s.hist.sum,o.hist.min=Math.min(o.hist.min,s.hist.min),o.hist.max=Math.max(o.hist.max,s.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=s.hist.bucketCounts[a]}else o.hist=s.hist}else this.Qt()&&this.Bt.set(r,s)}}};var gr,kc,po;function og(t){var e=globalThis._posthogChunkIds;if(e){var n=Object.keys(e);return po&&n.length===kc||(kc=n.length,po=n.reduce(((i,r)=>{gr||(gr={});var s=gr[r];if(s)i[s[0]]=s[1];else for(var o=t(r),a=o.length-1;a>=0;a--){var l=o[a],u=l?.filename,c=e[r];if(u&&c){i[u]=c,gr[r]=[u,c];break}}return i}),{})),po}}class ag{constructor(e,n,i){i===void 0&&(i=[]),this.coercers=e,this.stackParser=n,this.modifiers=i}buildFromUnknown(e,n){n===void 0&&(n={});var i=n&&n.mechanism||{handled:!0,type:"generic"},r=this.buildCoercingContext(i,n,0).apply(e),s=this.buildParsingContext(n),o=this.parseStacktrace(r,s);return{$exception_list:this.convertToExceptionList(o,i),$exception_level:"error"}}modifyFrames(e){var n=this;return se((function*(){for(var i of e)i.stacktrace&&i.stacktrace.frames&&U(i.stacktrace.frames)&&(i.stacktrace.frames=yield n.applyModifiers(i.stacktrace.frames));return e}))()}coerceFallback(e){var n;return{type:"Error",value:"Unknown error",stack:(n=e.syntheticException)==null?void 0:n.stack,synthetic:!0}}parseStacktrace(e,n){var i,r;return e.cause!=null&&(i=this.parseStacktrace(e.cause,n)),e.stack!=""&&e.stack!=null&&(r=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?n.skipFirstLines:0),n.chunkIdMap)),I({},e,{cause:i,stack:r})}applyChunkIds(e,n){return e.map((i=>(i.filename&&n&&(i.chunk_id=n[i.filename]),i)))}applyCoercers(e,n){for(var i of this.coercers)if(i.match(e))return i.coerce(e,n);return this.coerceFallback(n)}applyModifiers(e){var n=this;return se((function*(){var i=e;for(var r of n.modifiers)i=yield r(i);return i}))()}convertToExceptionList(e,n){var i,r,s,o={type:e.type,value:e.value,mechanism:{type:(i=n.type)!==null&&i!==void 0?i:"generic",handled:(r=n.handled)===null||r===void 0||r,synthetic:(s=e.synthetic)!==null&&s!==void 0&&s}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,I({},n,{handled:!0}))),a}buildParsingContext(e){var n;return{chunkIdMap:og(this.stackParser),skipFirstLines:(n=e.skipFirstLines)!==null&&n!==void 0?n:1}}buildCoercingContext(e,n,i){i===void 0&&(i=0);var r=(s,o)=>{if(4>=o){var a=this.buildCoercingContext(e,n,o);return this.applyCoercers(s,a)}};return I({},n,{syntheticException:i==0?n.syntheticException:void 0,mechanism:e,apply:s=>r(s,i),next:s=>r(s,i+1)})}}var ni="?";function Qo(t,e,n,i,r){var s={platform:t,filename:e,function:n===""?ni:n,in_app:!0};return C(i)||(s.lineno=i),C(r)||(s.colno=r),s}var Wd=(t,e)=>{var n=t.indexOf("safari-extension")!==-1,i=t.indexOf("safari-web-extension")!==-1;return n||i?[t.indexOf("@")!==-1?t.split("@")[0]:ni,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},lg=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,cg=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,ug=/\((\S*)(?::(\d+))(?::(\d+))\)/,dg=(t,e)=>{var n=lg.exec(t);if(n)return Qo(e,n[1],ni,+n[2],+n[3]);var i=cg.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var r=ug.exec(i[2]);r&&(i[2]=r[1],i[3]=r[2],i[4]=r[3])}var s=Wd(i[1]||ni,i[2]);return Qo(e,s[1],s[0],i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},fg=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,hg=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,pg=(t,e)=>{var n=fg.exec(t);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){var i=hg.exec(n[3]);i&&(n[1]=n[1]||"eval",n[3]=i[1],n[4]=i[2],n[5]="")}var r=n[3],s=n[1]||ni,o=Wd(s,r);return Qo(e,r=o[1],s=o[0],n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},Cc=/\(error: (.*)\)/;class gg{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,n){var i=X(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:i?e.stack:void 0,cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var n=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?n+": "+e.message:n}isDOMException(e){return Hr(e,"DOMException")}isDOMError(e){return Hr(e,"DOMError")}}class mg{match(e){return(function(n){switch({}.toString.call(n)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return vd(n,Error)}})(e)}coerce(e,n){return{type:this.getType(e),value:this.getMessage(e,n),stack:this.getStack(e),cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,n){var i=e.message;return String(i.error&&typeof i.error.message=="string"?i.error.message:i)}getStack(e){return e.stacktrace||e.stack||void 0}}class vg{constructor(){}match(e){return!!Hr(e,"ErrorEvent")&&(e.error!=null||this.fe(e))}coerce(e,n){var i;if(e.error!=null)return n.apply(e.error);var r=n.apply(e.message);return I({},r,{stack:(i=this.pe(e))!==null&&i!==void 0?i:r.stack,synthetic:!0})}fe(e){return X(e.message)&&e.message.length>0}pe(e){var n=e;if(X(n.filename)&&n.filename.length>0){var i,r,s=(i=n.lineno)!==null&&i!==void 0?i:0,o=(r=n.colno)!==null&&r!==void 0?r:0;return`Error - at `+n.filename+":"+s+":"+o}}}var _g=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class yg{match(e){return typeof e=="string"}coerce(e,n){var i,r=this.getInfos(e),s=r[0],o=r[1];return{type:s??"Error",value:o??e,stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}getInfos(e){var n="Error",i=e,r=e.match(_g);return r&&(n=r[1],i=r[2]),[n,i]}}var wg=["fatal","error","warning","log","info","debug"];function qd(t,e){e===void 0&&(e=40);var n=Object.keys(t);if(n.sort(),!n.length)return"[object has no keys]";for(var i=n.length;i>0;i--){var r=n.slice(0,i).join(", ");if(e>=r.length)return i===n.length?r:r.length>e?r.slice(0,e)+"...":r}return""}class bg{match(e){return typeof e=="object"&&e!==null}coerce(e,n){var i,r,s=this.getErrorPropertyFromObject(e);return s?n.apply(s):{type:this.getType(e),value:this.getValue(e),stack:(i=this.getStack(e))!==null&&i!==void 0?i:(r=n.syntheticException)==null?void 0:r.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return Xa(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var n="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(n+=" with message: '"+e.message+"'"),n}if("message"in e&&typeof e.message=="string")return e.message;var i=this.getObjectClassName(e);return(i&&i!=="Object"?"'"+i+"'":"Object")+" captured as exception with keys: "+qd(e)}isSeverityLevel(e){return X(e)&&!Ko(e)&&wg.indexOf(e)>=0}getStack(e){try{return X(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:X(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(var n in e)if({}.hasOwnProperty.call(e,n)){var i=e[n];if(tg(i))return i}}getObjectClassName(e){try{var n=Object.getPrototypeOf(e);return n?n.constructor.name:void 0}catch{return}}}class Eg{match(e){return Xa(e)}coerce(e,n){var i,r=e.constructor.name;return{type:r,value:r+" captured as exception with keys: "+qd(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class Sg{match(e){return md(e)}coerce(e,n){var i;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class xg{match(e){return Hr(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Xa(e))return!1;try{var n=e.detail;return n!=null&&typeof n=="object"&&"reason"in n}catch{return!1}}coerce(e,n){var i,r=this.getUnhandledRejectionReason(e);return md(r)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(r),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}:n.apply(r)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}}var Kr="$message",Yr="$timestamp",Ig=new Set([Kr,Yr]),go={enabled:!0,max_bytes:32768};function Jr(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:go.enabled,max_bytes:Cg(t.max_bytes,go.max_bytes)}:I({},go)}class kg{constructor(e){this.Ke=[],this.Je=0,this.Ne=Jr(e)}setConfig(e){this.Ne=Jr(e),this.Xe()}add(e){var n=(function(r){var s;try{s=hd(r)}catch{return}try{var o=JSON.parse(s);if(!he(o))return;var a=o,l=a[Kr],u=a[Yr];return!X(l)||l.trim().length===0||!X(u)&&!ke(u)?void 0:{step:a,json:s}}catch{return}})(e);if(n){var i=(function(r){if(typeof TextEncoder<"u")return new TextEncoder().encode(r).length;for(var s=encodeURIComponent(r),o=0,a=0;s.length>a;a++)s[a]==="%"?(o+=1,a+=2):o+=1;return o})(n.json);i>this.Ne.max_bytes||(this.Ke.push({step:n.step,bytes:i}),this.Je+=i,this.Xe())}}getAttachable(){return this.Ke.map((e=>e.step))}clear(){this.Ke=[],this.Je=0}size(){return this.Ke.length}Xe(){for(;this.Je>this.Ne.max_bytes&&this.Ke.length>0;){var e=this.Ke.shift();e&&(this.Je-=e.bytes)}}}function Cg(t,e){if(!ke(t)||t===1/0||t===-1/0)return e;var n=Math.floor(t);return 0>n?e:n}var zd=function(t,e){var n=(e===void 0?{}:e).debugEnabled,i={k(r){if(w&&(ne.DEBUG||w.POSTHOG_DEBUG||n)&&!C(w.console)&&w.console){for(var s=("__rrweb_original__"in w.console[r])?w.console[r].__rrweb_original__:w.console[r],o=arguments.length,a=new Array(o>1?o-1:0),l=1;o>l;l++)a[l-1]=arguments[l];s(t,...a)}},debug(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("debug",...s)},info(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("log",...s)},warn(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("warn",...s)},error(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("error",...s)},critical(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];console.error(t,...s)},uninitializedWarning(r){i.error("You must initialize PostHog before calling "+r)},createLogger:(r,s)=>zd(t+" "+r,s)};return i},A=zd("[PostHog.js]"),pe=A.createLogger,Ag=pe("[ExternalScriptsLoader]"),mo=(t,e,n)=>{if(t.config.disable_external_dependency_loading)return Ag.warn(e+" was requested but loading of external scripts is disabled."),n("Loading of external scripts is disabled");var i=P?.querySelectorAll("script");if(i){for(var r,s=function(){if(i[o].src===e){var l=i[o];return l.__posthog_loading_callback_fired?{v:n()}:(l.addEventListener("load",(u=>{l.__posthog_loading_callback_fired=!0,n(void 0,u)})),l.onerror=u=>n(u),{v:void 0})}},o=0;i.length>o;o++)if(r=s())return r.v}var a=()=>{if(!P)return n("document not found");var l=P.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=d=>{l.__posthog_loading_callback_fired=!0,n(void 0,d)},l.onerror=d=>n(d),t.config.prepare_external_dependency_script&&(l=t.config.prepare_external_dependency_script(l)),!l)return n("prepare_external_dependency_script returned null");if(t.config.external_scripts_inject_target==="head")P.head.appendChild(l);else{var u,c=P.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):P.body.appendChild(l)}};P!=null&&P.body?a():P?.addEventListener("DOMContentLoaded",a)};B.__PosthogExtensions__=B.__PosthogExtensions__||{},B.__PosthogExtensions__.loadExternalDependency=(t,e,n)=>{if(e!=="remote-config"){var i;if(t.config.strict_script_versioning)i=t.requestRouter.endpointFor("assets","/static/"+t.version+"/"+e+".js");else{var r="/static/"+e+".js?v="+t.version;if(e==="toolbar"){var s=3e5;r=r+"&t="+Math.floor(Date.now()/s)*s}i=t.requestRouter.endpointFor("assets",r)}mo(t,i,n)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");mo(t,o,n)}},B.__PosthogExtensions__.loadSiteApp=(t,e,n)=>{var i=t.requestRouter.endpointFor("api",e);mo(t,i,n)};ne.DEBUG=!1,ne.LIB_VERSION="1.415.7",ne.LIB_NAME="web";var Vd="$people_distinct_id",Yi="$device_id",vo="$device_model",Fi="__alias",Ri="__timers",ea="$autocapture_disabled_server_side",ta="$heatmaps_enabled_server_side",na="$exception_capture_enabled_server_side",ia="$error_tracking_suppression_rules",ra="$error_tracking_capture_extension_exceptions",sa="$web_vitals_enabled_server_side",rl="$dead_clicks_enabled_server_side",sl="$product_tours_enabled_server_side",oa="$web_vitals_allowed_metrics",An="$session_recording_remote_config",Gd="$replay_sample_rate",Kd="$replay_override_sampling",Yd="$replay_override_linked_flag",Jd="$replay_override_url_trigger",Zd="$replay_override_event_trigger",Kn="$sesid",ol="$session_is_sampled",Sn="$enabled_feature_flags",Ti="$active_feature_flags",Ar="$early_access_features",aa="$feature_flag_details",$i="$feature_flag_payloads",Pr="$feature_flag_request_id",Zr="$minimal_flag_called_events",It="$override_feature_flags",xn="$override_feature_flag_payloads",jt="$stored_person_properties",In="$stored_group_properties",la="$surveys",Xr="$surveys_loaded_at",ca="$surveys_activated",Fr="$surveys_activated_session",Rr="$surveys_activated_timestamps",Mi="ph_product_tours",Cn="$flag_call_reported",Li="$flag_call_reported_session_id",Tr="$feature_flag_errors",ji="$feature_flag_evaluated_at",ot="$user_state",ua="$client_session_props",da="$capture_rate_limit",fa="$initial_campaign_params",ha="$initial_referrer_info",Qr="$initial_person_info",es="$epp",mr="$posthog_cookieless",Xd="$cookieless_mode",Qd="$sdk_debug_extensions_init_method",ef="$sdk_debug_extensions_init_time_ms",tf="$sdk_debug_recording_script_not_loaded",al="PostHog loadExternalDependency extension not found.",kn="on_reject",Wt="always",Un="anonymous",vn="identified",pa="identified_only",ts="visibilitychange",ns="beforeunload",Vn="$pageview",_o="$pageleave",yo="$identify",Ac="$groupidentify";function vr(t,e){U(t)&&t.forEach(e)}function ie(t,e){if(!H(t))if(U(t))t.forEach(e);else if(Dp(t))t.forEach(((i,r)=>e(i,r)));else for(var n in t)gd.call(t,n)&&e(t[n],n)}var fe=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;e>i;i++)n[i-1]=arguments[i];for(var r of n)for(var s in r)r[s]!==void 0&&(t[s]=r[s]);return t};function $r(t){for(var e=Object.keys(t),n=e.length,i=new Array(n);n--;)i[n]=[e[n],t[e[n]]];return i}var Pc=function(t){try{return t()}catch{return}},Pg=function(t){return function(){try{for(var e=arguments.length,n=new Array(e),i=0;e>i;i++)n[i]=arguments[i];return t.apply(this,n)}catch(r){A.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),A.critical(r)}}},ll=function(t){var e={};return ie(t,(function(n,i){(X(n)&&n.length>0||ke(n))&&(e[i]=n)})),e},Fg=["herokuapp.com","vercel.app","netlify.app"];function Rg(t){var e=t?.hostname;if(!X(e))return!1;var n=e.split(".").slice(-2).join(".");for(var i of Fg)if(n===i)return!1;return!0}function ve(t,e,n,i){var r=i??{},s=r.capture,o=r.passive;t?.addEventListener(e,n,{capture:s!==void 0&&s,passive:o===void 0||o})}function ga(t){return t.name==="ph_toolbar_internal"}var nf=t=>{if(P){try{for(var e=t+"=",n=P.cookie.split(";").filter((s=>s.length)),i=0;n.length>i;i++){for(var r=n[i];r.charAt(0)==" ";)r=r.substring(1,r.length);if(r.indexOf(e)===0)return decodeURIComponent(r.substring(e.length,r.length))}}catch{}return null}};Math.trunc||(Math.trunc=function(t){return 0>t?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return ke(t)&&isFinite(t)&&Math.floor(t)===t});class is{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,n,i,r){if(!Number.isInteger(e)||!Number.isInteger(n)||!Number.isInteger(i)||!Number.isInteger(r)||0>e||0>n||0>i||0>r||e>0xffffffffffff||n>4095||i>1073741823||r>4294967295)throw new RangeError("invalid field value");var s=new Uint8Array(16);return s[0]=e/Math.pow(2,40),s[1]=e/Math.pow(2,32),s[2]=e/Math.pow(2,24),s[3]=e/Math.pow(2,16),s[4]=e/256,s[5]=e,s[6]=112|n>>>8,s[7]=n,s[8]=128|i>>>24,s[9]=i>>>16,s[10]=i>>>8,s[11]=i,s[12]=r>>>24,s[13]=r>>>16,s[14]=r>>>8,s[15]=r,new is(s)}toString(){for(var e="",n=0;this.bytes.length>n;n++)e=e+(this.bytes[n]>>>4).toString(16)+(15&this.bytes[n]).toString(16),n!==3&&n!==5&&n!==7&&n!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new is(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var n=0;16>n;n++){var i=this.bytes[n]-e.bytes[n];if(i!==0)return Math.sign(i)}return 0}}class Tg{generate(){var e=this.generateOrAbort();if(!C(e))return e;this.S=0;var n=this.generateOrAbort();if(C(n))throw new Error("Could not generate UUID after timestamp reset");return n}generateOrAbort(){var e=Date.now();if(e>this.S)this.S=e,this.C();else{if(this.S>=e+1e4)return;this.I++,this.I>4398046511103&&(this.S++,this.C())}return is.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 $g}}var Fc,rf=t=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;t.length>e;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};w&&!C(w.crypto)&&crypto.getRandomValues&&(rf=t=>crypto.getRandomValues(t));class $g{nextUint32(){return this.R.length>this.O||(rf(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var Ht=()=>Mg().toString(),Mg=()=>(Fc||(Fc=new Tg)).generate(),yi="",Lg=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,qt={N:()=>!!P,j(t){A.error("cookieStore error: "+t)},P:nf,H(t){var e;try{e=JSON.parse(qt.P(t))||{}}catch{}return e},F(t,e,n,i,r){if(!P)return!1;try{var s="",o="",a=(function(c,d){if(d){var h=(function(p,g){if(g===void 0&&(g=P),yi)return yi;if(!g||["localhost","127.0.0.1"].includes(p))return"";for(var m=p.split("."),v=Math.min(m.length,8),E="dmn_chk_"+Ht();!yi&&v--;){var S=m.slice(v).join("."),_=E+"=1;domain=."+S+";path=/";g.cookie=_+";max-age=3",g.cookie.includes(E)&&(g.cookie=_+";max-age=0",yi=S)}return yi})(c);if(!h){var f=(p=>{var g=p.match(Lg);return g?g[0]:""})(c);f!==h&&A.info("Warning: cookie subdomain discovery mismatch",f,h),h=f}return h?"; domain=."+h:""}return""})(P.location.hostname,i);if(n){var l=new Date;l.setTime(l.getTime()+864e5*n),s="; expires="+l.toUTCString()}r&&(o="; secure");var u=t+"="+encodeURIComponent(JSON.stringify(e))+s+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&A.warn("cookieStore warning: large cookie, len="+u.length),P.cookie=u,!0}catch{return!1}},q(t,e){if(P!=null&&P.cookie)try{qt.F(t,"",-1,e)}catch{return}}},wo=null,le={N(){if(!Ke(wo))return wo;var t=!0;if(C(w))t=!1;else try{var e="__mplssupport__";le.F(e,"xyz"),le.P(e)!=='"xyz"'&&(t=!1),le.q(e)}catch{t=!1}return t||A.error("localStorage unsupported; falling back to cookie store"),wo=t,t},j(t){A.error("localStorage error: "+t)},P(t){try{return w?.localStorage.getItem(t)}catch(e){le.j(e)}return null},H(t){try{return JSON.parse(le.P(t))||{}}catch{}return null},F(t,e){try{return w?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(n){le.j(n)}return!1},q(t){try{w?.localStorage.removeItem(t)}catch(e){le.j(e)}}},Ng=[Yi,"distinct_id",Kn,ol,es,Qr,ot],_r={},Og={N:()=>!0,j(t){A.error("memoryStorage error: "+t)},P:t=>_r[t]||null,H:t=>_r[t]||null,F:(t,e)=>(_r[t]=e,!0),q(t){delete _r[t]}},_n=null,be={N(){if(!Ke(_n))return _n;if(_n=!0,C(w))_n=!1;else try{var t="__support__";be.F(t,"xyz"),be.P(t)!=='"xyz"'&&(_n=!1),be.q(t)}catch{_n=!1}return _n},j(t){A.error("sessionStorage error: ",t)},P(t){try{return w?.sessionStorage.getItem(t)}catch(e){be.j(e)}return null},H(t){try{return JSON.parse(be.P(t))||null}catch{}return null},F(t,e){try{return w?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(n){be.j(n)}return!1},q(t){try{w?.sessionStorage.removeItem(t)}catch(e){be.j(e)}}};class Bg{constructor(e){this._instance=e}get Ne(){return this._instance.config}get consent(){return this.ti()?0:this.ei}isOptedOut(){return this.Ne.cookieless_mode===Wt||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===kn}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===0}isRejected(){return this.consent===0||this.consent===-1&&this.Ne.opt_out_capturing_by_default}optInOut(e){this.ii.F(this.ri,e?1:0,this.Ne.cookie_expiration,this.Ne.cross_subdomain_cookie,this.Ne.secure_cookie)}reset(){this.ii.q(this.ri,this.Ne.cross_subdomain_cookie)}get ri(){var e=this._instance.config,n=e.token,i=e.opt_out_capturing_cookie_prefix;return e.consent_persistence_name||(i?i+n:"__ph_opt_in_out_"+n)}get ei(){var e=this.ii.P(this.ri);return uo(e)?1:j(Wp,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,n=e==="localStorage"?le:qt;if(!this.ni||this.ni!==n){this.ni=n;var i=e==="localStorage"?qt:le;i.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(uo(i.P(this.ri))),i.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[Ue?.doNotTrack,Ue?.msDoNotTrack,B.doNotTrack].some((e=>uo(e)))}}function sf(t,e){var n,i=t==null||(n=t.config)==null?void 0:n.get_current_url;if(!De(i))return e;try{var r=i(e);return X(r)&&r?r:e}catch(s){return A.error("Error in get_current_url, falling back to window.location.href",s),e}}var of="__POSTHOG_TOOLBAR__",Dg=1,jg=3,Ug=11;function Rc(t){return t instanceof Element&&(t.id===of||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function hn(t){return!!t&&t.nodeType===Dg}function Qe(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function af(t){return!!t&&t.nodeType===jg}function lf(t){return!!t&&t.nodeType===Ug&&hn(t.host)}var cf=1e3;function cl(t){return t?xs(t).split(/\s+/):[]}function Tc(t,e){var n=(function(i){var r,s=w==null||(r=w.location)==null?void 0:r.href;return C(s)?void 0:sf(i,s)})(e);return!!(n&&t&&t.some((i=>n.match(i))))}function rs(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 cl(e)}function uf(t){return H(t)?null:xs(t).split(/(\s+)/).filter((e=>Ui(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function Ji(t){var e="";return va(t)&&!pf(t)&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;af(n)&&n.textContent&&(e+=(i=uf(n.textContent))!==null&&i!==void 0?i:"")})),xs(e)}function bo(t){var e;return C(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var ul=["a","button","form","input","select","textarea","label"];function ma(t,e){if(C(e))return!0;var n,i=function(s){if(e.some((o=>(function(a,l){var u=a.matches||a.matchesSelector||a.msMatchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.oMatchesSelector;try{return!!u&&u.call(a,l)}catch{return!1}})(s,o))))return{v:!0}};for(var r of t)if(n=i(r))return n.v;return!1}function df(t){var e=t.parentNode;return!(!e||!hn(e))&&e}var Hg=[".ph-no-autocapture","[data-ph-no-autocapture]"],ff=["next","previous","prev",">","<"],Wg=[...ff,"+","-","−","–"],$c=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,Mc=[".ph-no-rageclick",".ph-no-capture"],qg=["","text","search","email","password","url","tel","number"];function Lc(t,e){if(!w||dl(t))return!1;var n,i,r,s,o;if(mt(e)?(n=!!e&&Mc,i=void 0,r=!1):(n=(s=e?.css_selector_ignorelist)!==null&&s!==void 0?s:Mc,i=e?.content_ignorelist,r=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),n===!1||r&&(function(l){return!(!l||!hn(l))&&(!!Qe(l,"textarea")||(Qe(l,"input")?j(qg,(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=hf(t,!1).targetElementList;return!(function(l,u){if(l===!1||C(l))return!1;var c;if(l===!0)c=ff;else{if(!U(l))return!1;if(l.length>10)return A.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var h=d.safeText,f=d.ariaLabel;return c.some((p=>$c(h,p)||$c(f,p)))}))})(i,a.map((l=>{var u;return{safeText:Ji(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!ma(a,n)}var dl=t=>!t||Qe(t,"html")||!hn(t),hf=(t,e)=>{if(!w||dl(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,i=[t],r=t;r.parentNode&&!Qe(r,"body");)if(lf(r.parentNode))i.push(r.parentNode.host),r=r.parentNode.host;else{var s=df(r);if(!s)break;if(e||ul.indexOf(s.tagName.toLowerCase())>-1)n=!0;else try{var o=w.getComputedStyle(s);o&&o.getPropertyValue("cursor")==="pointer"&&(n=!0)}catch{}i.push(s),r=s}return{parentIsUsefulElement:n,targetElementList:i}};function va(t){for(var e=new Set,n=0,i=t;i.parentNode&&!Qe(i,"body");i=i.parentNode){if(n++>=cf||e.has(i))return!1;e.add(i);var r=rs(i);if(j(r,"ph-sensitive")||j(r,"ph-no-capture"))return!1}if(j(rs(t),"ph-include"))return!0;var s=t.type||"";if(X(s))switch(s.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!X(o)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(o.replace(/[^a-zA-Z0-9]/g,""))}function pf(t){return!!(Qe(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||Qe(t,"select")||Qe(t,"textarea")||t.getAttribute("contenteditable")==="true")}var Nc=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}))$"),Oc=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,zg=[16,15,14,13],Vg=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),Bc=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),Dc=/[0-9A-Za-z_]/;function Gg(t){for(var e=0,n=!1,i=t.length-1;i>=0;i--){var r=t.charCodeAt(i)-48;n&&(r*=2)>9&&(r-=9),e+=r,n=!n}return e%10==0}function Ui(t,e){if(e===void 0&&(e=!0),H(t))return!1;if(X(t)){t=xs(t);var n=e?Nc.test((t||"").replace(/[- ]/g,"")):(function(r){var s;for(Oc.lastIndex=0;s=Oc.exec(r);){var o=s[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of zg){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(Nc.test(d)&&Gg(d))return!0}}}return!1})(t);if(n)return!1;var i=e?Vg.test(t):(function(r){var s;for(Bc.lastIndex=0;s=Bc.exec(r);){var o=s[1],a=s[3];if(!(o&&a&&Dc.test(o)&&Dc.test(a)))return!0}return!1})(t);if(i)return!1}return!0}function jc(t){var e=Ji(t);return Ui(e=(e+" "+gf(t)).trim())?e:""}function gf(t){var e="";return t&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;if(n&&((i=n.tagName)==null?void 0:i.toLowerCase())==="span")try{var r=Ji(n);e=(e+" "+r).trim(),n.childNodes&&n.childNodes.length&&(e=(e+" "+gf(n)).trim())}catch(s){A.error("[AutoCapture]",s)}})),e}function Uc(t){return t.replace(/"|\\"/g,'\\"')}function Kg(t){var e=t.attr__class;if(e)return U(e)?e:cl(e)}var yr=pe("[Dead Clicks]"),Yg=()=>!0,Jg=t=>{var e,n=!((e=t.instance.persistence)==null||!e.get_property(rl)),i=t.instance.config.capture_dead_clicks;return mt(i)?i:!!he(i)||n};class Hc{get lazyLoadedDeadClicksAutocapture(){return this.si}constructor(e,n,i){this.instance=e,this.isEnabled=n,this.onCapture=i,this.startIfEnabledOrStop()}onRemoteConfig(e){if(e.ok){var n=e.config;"captureDeadClicks"in n&&(this.instance.persistence&&this.instance.persistence.register({[rl]:n.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var n,i;(n=B.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture?e():(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"dead-clicks-autocapture",(r=>{r?yr.error("failed to load script",r):e()}))}oi(){var e;if(P){if(!this.si&&(e=B.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var n=he(this.instance.config.capture_dead_clicks)?I({},this.instance.config.capture_dead_clicks):{};n.__onCapture=this.onCapture,this.onCapture&&(n.capture_dead_swipes=!1),this.si=B.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.si.start(P),yr.info("starting...")}}else yr.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,yr.info("stopping..."))}}var Eo=pe("[SegmentIntegration]"),mf="posthog-js";function vf(t,e){var n=e===void 0?{}:e,i=n.organization,r=n.projectId,s=n.prefix,o=n.severityAllowList,a=o===void 0?["error"]:o,l=n.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,h,f,p,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var v,E=((d=c.exception)==null?void 0:d.values)||[],S=E.map((b=>I({},b,{stacktrace:b.stacktrace?I({},b.stacktrace,{type:"raw",frames:(b.stacktrace.frames||[]).map((k=>I({},k,{platform:"web:javascript"})))}):void 0}))),_={$exception_message:((h=E[0])==null?void 0:h.value)||c.message,$exception_type:(f=E[0])==null?void 0:f.type,$exception_level:c.level,$exception_list:S,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((p=E[0])==null?void 0:p.value)||c.message,$sentry_exception_type:(g=E[0])==null?void 0:g.type,$sentry_tags:c.tags};return i&&r&&(_.$sentry_url=(s||"https://sentry.io/organizations/")+i+"/issues/?project="+r+"&query="+c.event_id),u&&((v=t.exceptions)==null||v.sendExceptionEvent(_)),c}}class Zg{constructor(e,n,i,r,s,o){this.name=mf,this.setupOnce=function(a){a(vf(e,{organization:n,projectId:i,prefix:r,severityAllowList:s,sendExceptionsToPostHog:o==null||o}))}}}class Wc{constructor(e){this.li=(n,i,r)=>{r&&(r.noSessionId||r.activityTimeout||r.sessionPastMaximumLength||r.crossTabAdoption)&&(A.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:n,changeReason:r}),this.ui=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.hi()}hi(){var e;this.di=(e=this._instance.sessionManager)==null?void 0:e.onSessionId(this.li)}destroy(){var e;(e=this.di)==null||e.call(this),this.di=void 0}doPageView(e,n){var i,r=this.vi(e,n);return this.ui={pathname:(i=w?.location.pathname)!==null&&i!==void 0?i:"",pageViewId:n,timestamp:e},this._instance.scrollManager.resetContext(),r}doPageLeave(e){var n;return this.vi(e,(n=this.ui)==null?void 0:n.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.ui)==null?void 0:e.pageViewId}}vi(e,n){var i=this.ui;if(!i)return{$pageview_id:n};var r={$pageview_id:n,$prev_pageview_id:i.pageViewId},s=this._instance.scrollManager.getContext();if(s&&!this._instance.config.disable_scroll_properties){var o=s.maxScrollHeight,a=s.lastScrollY,l=s.maxScrollY,u=s.maxContentHeight,c=s.lastContentY,d=s.maxContentY;if(!(C(o)||C(a)||C(l)||C(u)||C(c)||C(d))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),d=Math.ceil(d);var h=o>1?At(a/o,0,1,A):1,f=o>1?At(l/o,0,1,A):1,p=u>1?At(c/u,0,1,A):1,g=u>1?At(d/u,0,1,A):1;r=fe(r,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:h,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:f,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:p,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return i.pathname&&(r.$prev_pageview_pathname=i.pathname),i.timestamp&&(r.$prev_pageview_duration=(e.getTime()-i.timestamp.getTime())/1e3),r}}var So=["flags","surveys"],Xg={[Vd]:{exposure:"hidden"},[Fi]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[Ri]:{exposure:"hidden"},[ea]:{exposure:"event"},[ta]:{exposure:"hidden"},[na]:{exposure:"event"},[ia]:{exposure:"hidden"},[ra]:{exposure:"event"},[sa]:{exposure:"event"},[rl]:{exposure:"event"},[sl]:{exposure:"hidden"},[oa]:{exposure:"event"},[An]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[Kn]:{exposure:"hidden"},[ol]:{exposure:"event"},[Gd]:{exposure:"event",shouldSkipFromEventProperties:t=>Ke(t)},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},$sess_rec_flush_size:{exposure:"hidden"},[Sn]:{exposure:"hidden",storageGroup:"flags"},[Ti]:{exposure:"hidden",storageGroup:"flags"},[Ar]:{exposure:"hidden"},[aa]:{exposure:"hidden",storageGroup:"flags"},[$i]:{exposure:"hidden",storageGroup:"flags"},[Pr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[Zr]:{exposure:"hidden",storageGroup:"flags"},[It]:{exposure:"hidden"},[xn]:{exposure:"hidden"},[jt]:{exposure:"hidden"},[In]:{exposure:"hidden"},[la]:{exposure:"hidden",storageGroup:"surveys"},[Xr]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[ca]:{exposure:"event"},[Fr]:{exposure:"hidden"},[Rr]:{exposure:"hidden"},[Mi]:{exposure:"hidden"},$product_tours_activated:{exposure:"hidden"},$product_tours_activated_session:{exposure:"hidden"},$conversations_widget_session_id:{exposure:"event"},$conversations_ticket_id:{exposure:"event"},$conversations_widget_state:{exposure:"event"},$conversations_user_traits:{exposure:"event"},[Cn]:{exposure:"hidden"},[Li]:{exposure:"hidden"},[Tr]:{exposure:"hidden"},[ji]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[ot]:{exposure:"hidden"},[ua]:{exposure:"hidden"},[da]:{exposure:"hidden"},[fa]:{exposure:"hidden"},[ha]:{exposure:"hidden"},[Qr]:{exposure:"hidden"},[es]:{exposure:"hidden"},[Kd]:{exposure:"event"},[Yd]:{exposure:"event"},[Jd]:{exposure:"event"},[Zd]:{exposure:"event"},[Qd]:{exposure:"event"},[ef]:{exposure:"event"},[tf]:{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"}},Qg=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],yn=t=>{var e=Xg[t];if(e)return e;for(var n of Qg){var i=n[1];if(t.indexOf(n[0])===0)return i}},Yn=(t,e)=>{try{return JSON.stringify(t,((n,i)=>typeof i=="bigint"?i.toString():i),e)}catch{return hd(t)}},ss=t=>{var e=P?.createElement("a");return C(e)?null:(e.href=t,e)},ii=function(t,e){for(var n,i=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),r=0;i.length>r;r++){var s=i[r].split("=");if(s[0]===e){n=s;break}}if(!U(n)||2>n.length)return"";var o=n[1];try{o=decodeURIComponent(o)}catch{A.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},Zi=function(t,e,n){if(!t||!e||!e.length)return t;for(var i=t.split("#"),r=i[1],s=(i[0]||"").split("?"),o=s[1],a=s[0],l=(o||"").split("&"),u=[],c=0;l.length>c;c++){var d=l[c].split("=");U(d)&&(e.includes(d[0])?u.push(d[0]+"="+n):u.push(l[c]))}var h=a;return o!=null&&(h+="?"+u.join("&")),r!=null&&(h+="#"+r),h},os=function(t,e){var n=t.match(new RegExp(e+"=([^&]*)"));return n?n[1]:null},_f=(t,e)=>t>=e&&ud(),yf=(t,e,n,i)=>{if(t===0){if(ud()){var r=e+1;return r===n&&i(),r}return e}return 0},wr="https?://(.*)",ri=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],em=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...ri],Xi="",tm=["li_fat_id"];function wf(t,e,n){if(!P)return{};var i,r=e?[...ri,...n||[]]:[],s=bf(Zi(P.URL,r,Xi),t),o=(i={},ie(tm,(function(a){var l=nf(a);i[a]=l||null})),i);return fe(o,s)}function bf(t,e){var n=em.concat(e||[]),i={};return ie(n,(function(r){var s=ii(t,r);i[r]=s||null})),i}function Ef(t){var e=(function(s){return s?s.search(wr+"google.([^/?]*)")===0?"google":s.search(wr+"bing.com")===0?"bing":s.search(wr+"yahoo.com")===0?"yahoo":s.search(wr+"duckduckgo.com")===0?"duckduckgo":null:null})(t),n=e!="yahoo"?"q":"p",i={};if(!Ke(e)){i.$search_engine=e;var r=P?ii(P.referrer,n):"";r.length&&(i.ph_keyword=r)}return i}function qc(){return navigator.language||navigator.userLanguage}var as="$direct";function Sf(){return P?.referrer||as}function xf(t,e,n){n===void 0&&(n=!1);var i=t?[...ri,...e||[]]:[],r=n?fn(me?.href):me?.href,s=r?.substring(0,1e3);return{r:Sf().substring(0,1e3),u:s?Zi(s,i,Xi):void 0}}function If(t,e){var n;e===void 0&&(e=!1);var i=t.r,r=t.u,s=e?fn(r):r,o={$referrer:i,$referring_domain:i==null?void 0:i==as?as:(n=ss(i))==null?void 0:n.host};if(s){o.$current_url=s;var a=ss(s);o.$host=a?.host,o.$pathname=a?.pathname;var l=bf(s);fe(o,l)}if(i){var u=Ef(i);fe(o,u)}return o}function kf(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function nm(){try{return new Date().getTimezoneOffset()}catch{return}}var im={flags:ji,surveys:Xr},rm=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],Hn="main";class xo{constructor(e,n,i){if(i===void 0&&(i=!0),this.ci={},this.fi=!1,this.pi=!1,this.Ne=e,this.gi=i,this.props={},this.mi=void 0,this.yi=(s=>{var o="";return s.token&&(o=s.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),s.persistence_name?"ph_"+s.persistence_name:"ph_"+o+"_posthog"})(e),this.ii=this.bi(e),this.pi=this.wi(e),this.load(),e.debug&&A.info("Persistence loaded",e.persistence,I({},this.props)),this.update_config(e,e,n),this.save(),w){var r=()=>this.flush();ve(w,"beforeunload",r,{capture:!1}),ve(w,"pagehide",r,{capture:!1})}}ki(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return ke(n)&&n>0?n:0}isDisabled(){return!!this.xi}bi(e){rm.indexOf(e.persistence.toLowerCase())===-1&&(A.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var n,i=(function(o,a){o===void 0&&(o=[]),a===void 0&&(a=!1);var l=[...Ng,...o];return I({},le,{H(u){try{var c={};try{c=qt.H(u)||{}}catch{}var d,h=JSON.parse(le.P(u)||"{}");if(a){var f={};for(var p in c){var g=c[p];Ke(g)||g===""||(f[p]=g)}d=fe(h,f)}else d=fe(c,h);return le.F(u,d),d}catch{}return null},F(u,c,d,h,f,p){var g=le.F(u,c,void 0,void 0,p);try{var m={};l.forEach((v=>{c[v]&&(m[v]=c[v])})),Object.keys(m).length&&qt.F(u,m,d,h,f,p)}catch(v){le.j(v)}return g},q(u,c){try{w?.localStorage.removeItem(u),qt.q(u,c)}catch(d){le.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),r=!1,s=e.persistence.toLowerCase();return s==="localstorage"&&le.N()?(n=le,r=!0):s==="localstorage+cookie"&&i.N()?(n=i,r=!0):s==="sessionstorage"&&be.N()?n=be:s==="memory"?n=Og:s==="cookie"?n=qt:i.N()?(n=i,r=!0):n=qt,this.fi=r,n}Si(e){return this.yi+"__"+e}wi(e){return this.fi&&!!e.split_storage}properties(){var e={};return ie(this.props,((n,i)=>{var r=yn(i);if(!r||r.exposure==="event"){if(r!=null&&r.shouldSkipFromEventProperties!=null&&r.shouldSkipFromEventProperties(n))return;e[i]=n}})),e}load(){if(!this.xi){var e=this.ii.H(this.yi);e&&(this.props=fe({},e)),this.pi&&this.Ci()}}Ci(){for(var e of So){var n=le.H(this.Si(e));if(n&&!Kt(n)){var i=this.Mi(e);i.persisted=!0,this.Ti(e)||(i.fingerprint=this.Ei(n,e)),this.Ii(e,n)||fe(this.props,n)}}}Ti(e){return Object.keys(this.props).some((n=>{var i;return((i=yn(n))==null?void 0:i.storageGroup)===e}))}Ii(e,n){var i=im[e];if(!i)return!1;var r=n[i],s=this.props[i];return ke(r)&&ke(s)&&s>r}refreshKey(e){var n;if(!this.xi){var i=this.pi?(n=yn(e))==null?void 0:n.storageGroup:void 0,r=i?le.H(this.Si(i)):this.ii.H(this.yi);if(r&&e in r)this.Pi(e,r[e]);else{if(i){var s=this.ii.H(this.yi);if(s&&e in s)return void this.Pi(e,s[e])}this.Ri(e)}}}save(){if(!this.xi){var e=this.ki();e>0?C(this.Ai)&&(this.Ai=setTimeout((()=>{this.Ai=void 0,this.Fi()}),e)):this.Fi()}}flush(){C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0,this.Fi())}Fi(){this.xi||(this.pi?this.Li():this.Oi(this.ii,this.yi,this.props,Hn))}Li(){var e=this.Di(),n=e.main,i=e.groups;for(var r of(this.Oi(this.ii,this.yi,n,Hn),So)){var s,o=i[r];(!Kt(o)||(s=this.ci[r])!=null&&s.persisted)&&this.Oi(le,this.Si(r),o,r)}}Di(){var e={},n={flags:{},surveys:{}};return ie(this.props,((i,r)=>{var s,o=(s=yn(r))==null?void 0:s.storageGroup;o?n[o][r]=i:e[r]=i})),{main:e,groups:n}}Ei(e,n){if(n===Hn)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var i={};return ie(e,((r,s)=>{var o;i[s]=(o=yn(s))!=null&&o.volatile?"__volatile__":r})),JSON.stringify(i)}Oi(e,n,i,r){var s=this.Mi(r);if(r===Hn||s.dirty||C(s.fingerprint)){var o;try{if((o=this.Ei(i,r))===s.fingerprint)return void(s.dirty=!1)}catch{o=void 0}e.F(n,i,this.$i,this.Ni,this.qi,this.Ne.debug)?(s.dirty=!1,r!==Hn&&(s.persisted=!0),C(o)||(s.fingerprint=o)):this.Ne.debug&&A.warn('failed to persist storage entry "'+n+'"; will retry on next save')}}remove(e){var n=(e===void 0?{}:e).keepGroupEntries,i=n!==void 0&&n;if(C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0),this.ii.q(this.yi,!1),this.ii.q(this.yi,!0),!i&&this.gi)for(var r of So)le.q(this.Si(r));i?delete this.ci[Hn]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,n,i){if(he(e)){C(n)&&(n="None"),this.$i=C(i)?this.ji:i;var r=!1;if(ie(e,((s,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==n||(this.Pi(o,s),r=!0)})),r)return this.save(),!0}return!1}register(e,n){if(he(e)){this.$i=C(n)?this.ji:n;var i=!1;if(ie(e,((r,s)=>{e.hasOwnProperty(s)&&(this.props[s]!==r||he(r)||U(r))&&(this.Pi(s,r),i=!0)})),i)return this.save(),!0}return!1}unregister(e){var n=typeof e=="string"?[e]:e,i=!1;for(var r of n)r in this.props&&(this.Ri(r),i=!0);i&&this.save()}update_campaign_params(){var e=P?.URL;if(e!==this.mi){var n=wf(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);Kt(ll(n))||this.register(n),this.mi=e}}update_search_keyword(){var e;this.register((e=P?.referrer)?Ef(e):{})}update_referrer_info(){var e;this.register_once({$referrer:Sf(),$referring_domain:P!=null&&P.referrer&&((e=ss(P.referrer))==null?void 0:e.host)||as},void 0)}set_initial_person_info(){this.props[fa]||this.props[ha]||this.register_once({[Qr]:xf(this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties,this.Ne.disable_capture_url_hashes)},void 0)}get_initial_props(){var e={};ie([ha,fa],(r=>{var s=this.props[r];s&&ie(s,(function(o,a){e["$initial_"+Go(a)]=o}))}));var n=this.props[Qr];if(n){var i=(function(r,s){s===void 0&&(s=!1);var o=If(r,s),a={};return ie(o,(function(l,u){a["$initial_"+Go(u)]=l})),a})(n,this.Ne.disable_capture_url_hashes);fe(e,i)}return e}safe_merge(e){return ie(this.props,(function(n,i){i in e||(e[i]=n)})),e}update_config(e,n,i){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!i),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var r=e.persistence!==n.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((h,f)=>h===d[f]))})(e.cookie_persisted_properties||[],n.cookie_persisted_properties||[]),s=r?this.bi(e):this.ii,o=this.wi(e);if(r||o!==this.pi){var a=this.props;this.clear(),this.ii=s,this.pi=o,this.props=a,this.save()}}set_disabled(e){this.xi=e,this.xi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ni&&(this.Ni=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this.qi&&(this.qi=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,n){var i=this.props[Ri]||{};i[e]=n,this.Pi(Ri,i),this.save()}remove_event_timer(e){var n=this.props[Ri]||{},i=n[e];return C(i)||(delete n[e],this.Pi(Ri,n),this.save()),i}get_property(e){return this.props[e]}set_property(e,n){this.Pi(e,n),this.save()}Pi(e,n){var i;this.props[e]=n,(i=yn(e))!=null&&i.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var n,i=(n=yn(e))==null?void 0:n.storageGroup;i&&(this.Mi(i).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function br(t){var e=!0;return{dispose(){if(e){e=!1;var n=t();n&&De(n.then)&&n.then(void 0,(()=>{}))}}}}var je={GZipJS:"gzip-js",Base64:"base64"},wi={Activation:"events",Cancellation:"cancelEvents"},Io={Popover:"popover",API:"api",Widget:"widget"},zt={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},ko={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},_a={Popover:"popover",Inline:"inline"},sm={SHOWN:"product tour shown"},zc={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},Vc=pe("[RateLimiter]");class om{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=n=>{var i=n.text;if(i&&i.length)try{(JSON.parse(i).quota_limited||[]).forEach((r=>{Vc.info((r||"events")+" is quota limited."),this.serverLimits[r]=new Date().getTime()+6e4}))}catch(r){return void Vc.warn('could not rate limit - continuing. Error: "'+r?.message+'"',{text:i})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var n,i,r;e===void 0&&(e=!1);var s=this.captureEventsBurstLimit,o=this.captureEventsPerSecond,a=new Date().getTime(),l=(n=(i=this.instance.persistence)==null?void 0:i.get_property(da))!==null&&n!==void 0?n:{tokens:s,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>s&&(l.tokens=s);var u=1>l.tokens;if(u||e||(l.tokens=Math.max(0,l.tokens-1)),u&&!e){var c=(ke(l.dropped)?l.dropped:0)+1;l.dropped=c,!this.lastEventRateLimited&&this.Hi(c)&&(l.dropped=0)}return this.lastEventRateLimited=u,(r=this.instance.persistence)==null||r.set_property(da,l),{isRateLimited:u,remainingTokens:l.tokens}}Ui(e){var n=this.instance.config.property_denylist;return!U(n)||!n.includes(e)}zi(){var e;if(this.Ui("$current_url")&&this.Ui("$pathname")&&me!=null&&me.pathname)return""+((e=me.origin)!==null&&e!==void 0?e:"")+me.pathname}Hi(e){var n,i,r=this.captureEventsBurstLimit,s=this.captureEventsPerSecond,o=this.zi(),a=this.Ui("$session_id")?(n=(i=this.instance).get_session_id)==null?void 0:n.call(i):void 0,l=[e+" event(s) dropped since the last warning",o?"triggered on "+o:void 0,a?"session "+a:void 0].filter(Boolean).join(", ");return!!this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited: "+l+". Config is set to "+s+" events per second and "+r+" events burst limit."},{skip_client_rate_limiting:!0})}isServerRateLimited(e){var n=this.serverLimits[e||"events"]||!1;return n!==!1&&new Date().getTime()e(this.remoteConfig))):e()}Vi(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:e})}load(){try{if(this.remoteConfig)return an.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void an.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return an.info("No config found after loading remote JS config. Falling back to JSON."),void this.Vi((n=>{this.Zi(n.json,n),this.Gi()}));this.Zi(e),this.Gi()}))}catch(e){an.error("Error loading remote config",e),this.Zi()}}stop(){this.Ki&&(clearInterval(this.Ki),this.Ki=void 0)}refresh(){!this._instance.Qi()&&P&&P.visibilityState!=="hidden"&&this._instance.reloadFeatureFlags()}Gi(){var e;if(!this.Ki){var n=(e=this._instance.config.remote_config_refresh_interval_ms)!==null&&e!==void 0?e:3e5;n!==0&&(this.Ki=setInterval((()=>{this.refresh()}),n))}}Zi(e,n){!e&&n&&(n.statusCode===0?n.error||an.warn("Failed to fetch remote config from PostHog."):an.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(r){an.error("Error applying remote config",r)}if(e?.hasFeatureFlags!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var i;(i=this._instance.featureFlags)==null||i.ensureFlagsLoaded()}catch(r){an.error("Error loading feature flags",r)}}}var ct=Uint8Array,Ge=Uint16Array,si=Uint32Array,fl=new ct([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]),hl=new ct([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]),Gc=new ct([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Af=function(t,e){for(var n=new Ge(31),i=0;31>i;++i)n[i]=e+=1<i;++i)for(var s=n[i];n[i+1]>s;++s)r[s]=s-n[i]<<5|i;return[n,r]},Pf=Af(fl,2),ya=Pf[1];Pf[0][28]=258,ya[258]=28;for(var Kc=Af(hl,0)[1],Ff=new Ge(32768),_e=0;32768>_e;++_e){var Wn=(43690&_e)>>>1|(21845&_e)<<1;Ff[_e]=((65280&(Wn=(61680&(Wn=(52428&Wn)>>>2|(13107&Wn)<<2))>>>4|(3855&Wn)<<4))>>>8|(255&Wn)<<8)>>>1}var Hi=function(t,e,n){for(var i=t.length,r=0,s=new Ge(e);i>r;++r)++s[t[r]-1];var o,a=new Ge(e);for(r=0;e>r;++r)a[r]=a[r-1]+s[r-1]<<1;for(o=new Ge(i),r=0;i>r;++r)o[r]=Ff[a[t[r]-1]++]>>>15-t[r];return o},$n=new ct(288);for(_e=0;144>_e;++_e)$n[_e]=8;for(_e=144;256>_e;++_e)$n[_e]=9;for(_e=256;280>_e;++_e)$n[_e]=7;for(_e=280;288>_e;++_e)$n[_e]=8;var ls=new ct(32);for(_e=0;32>_e;++_e)ls[_e]=5;var am=Hi($n,9),lm=Hi(ls,5),Rf=function(t){return(t/8>>0)+(7&t&&1)},Tf=function(t,e,n){(n==null||n>t.length)&&(n=t.length);var i=new(t instanceof Ge?Ge:t instanceof si?si:ct)(n-e);return i.set(t.subarray(e,n)),i},Ot=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8},bi=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8,t[i+2]|=n>>>16},Co=function(t,e){for(var n=[],i=0;t.length>i;++i)t[i]&&n.push({s:i,f:t[i]});var r=n.length,s=n.slice();if(!r)return[new ct(0),0];if(r==1){var o=new ct(n[0].s+1);return o[n[0].s]=1,[o,1]}n.sort((function(b,k){return b.f-k.f})),n.push({s:-1,f:25001});var a=n[0],l=n[1],u=0,c=1,d=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=r-1;)a=n[n[d].f>n[u].f?u++:d++],l=n[u!=c&&n[d].f>n[u].f?u++:d++],n[c++]={s:-1,f:a.f+l.f,l:a,r:l};var h=s[0].s;for(i=1;r>i;++i)s[i].s>h&&(h=s[i].s);var f=new Ge(h+1),p=wa(n[c-1],f,0);if(p>e){i=0;var g=0,m=p-e,v=1<i;++i){var E=s[i].s;if(e>=f[E])break;g+=v-(1<>>=m;g>0;){var S=s[i].s;e>f[S]?g-=1<=0&&g;--i){var _=s[i].s;f[_]==e&&(--f[_],++g)}p=e}return[new ct(f),p]},wa=function(t,e,n){return t.s==-1?Math.max(wa(t.l,e,n+1),wa(t.r,e,n+1)):e[t.s]=n},Yc=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new Ge(++e),i=0,r=t[0],s=1,o=function(l){n[i++]=l},a=1;e>=a;++a)if(t[a]==r&&a!=e)++s;else{if(!r&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(r),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(r);s=1,r=t[a]}return[n.subarray(0,i),e]},Ei=function(t,e){for(var n=0,i=0;e.length>i;++i)n+=t[i]*e[i];return n},ba=function(t,e,n){var i=n.length,r=Rf(e+2);t[r]=255&i,t[r+1]=i>>>8,t[r+2]=255^t[r],t[r+3]=255^t[r+1];for(var s=0;i>s;++s)t[r+s+4]=n[s];return 8*(r+4+i)},Jc=function(t,e,n,i,r,s,o,a,l,u,c){Ot(e,c++,n),++r[256];for(var d=Co(r,15),h=d[0],f=d[1],p=Co(s,15),g=p[0],m=p[1],v=Yc(h),E=v[0],S=v[1],_=Yc(g),b=_[0],k=_[1],T=new Ge(19),x=0;E.length>x;++x)T[31&E[x]]++;for(x=0;b.length>x;++x)T[31&b[x]]++;for(var F=Co(T,7),$=F[0],O=F[1],L=19;L>4&&!$[Gc[L-1]];--L);var N,K,V,M,R=u+5<<3,Z=Ei(r,$n)+Ei(s,ls)+o,Ce=Ei(r,h)+Ei(s,g)+o+14+3*L+Ei(T,$)+(2*T[16]+3*T[17]+7*T[18]);if(Z>=R&&Ce>=R)return ba(e,c,t.subarray(l,l+u));if(Ot(e,c,1+(Z>Ce)),c+=2,Z>Ce){N=Hi(h,f),K=h,V=Hi(g,m),M=g;var oe=Hi($,O);for(Ot(e,c,S-257),Ot(e,c+5,k-1),Ot(e,c+10,L-4),c+=14,x=0;L>x;++x)Ot(e,c+3*x,$[Gc[x]]);c+=3*L;for(var ye=[E,b],$e=0;2>$e;++$e){var ae=ye[$e];for(x=0;ae.length>x;++x)Ot(e,c,oe[Ie=31&ae[x]]),c+=$[Ie],Ie>15&&(Ot(e,c,ae[x]>>>5&127),c+=ae[x]>>>12)}}else N=am,K=$n,V=lm,M=ls;for(x=0;a>x;++x)if(i[x]>255){var Ie;bi(e,c,N[257+(Ie=i[x]>>>18&31)]),c+=K[Ie+257],Ie>7&&(Ot(e,c,i[x]>>>23&31),c+=fl[Ie]);var Se=31&i[x];bi(e,c,V[Se]),c+=M[Se],Se>3&&(bi(e,c,i[x]>>>5&8191),c+=hl[Se])}else bi(e,c,N[i[x]]),c+=K[i[x]];return bi(e,c,N[256]),c+K[256]},cm=new si([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),um=(function(){for(var t=new si(256),e=0;256>e;++e){for(var n=e,i=9;--i;)n=(1&n&&3988292384)^n>>>1;t[e]=n}return t})(),Ao=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8};function dm(t,e){e===void 0&&(e={});var n=(function(){var d=4294967295;return{p(h){for(var f=d,p=0;h.length>p;++p)f=um[255&f^h[p]]^f>>>8;d=f},d(){return 4294967295^d}}})(),i=t.length;n.p(t);var r,s,o,a,l,u=(a=10+((r=e).filename&&r.filename.length+1||0),l=8,(function(d,h,f,p,g,m){var v=d.length,E=new ct(p+v+5*(1+Math.floor(v/7e3))+g),S=E.subarray(p,E.length-g),_=0;if(!h||8>v)for(var b=0;v>=b;b+=65535){var k=b+65535;v>k?_=ba(S,_,d.subarray(b,k)):(S[b]=!0,_=ba(S,_,d.subarray(b,v)))}else{for(var T=cm[h-1],x=T>>>13,F=8191&T,$=(1<b;++b){var Ie=V(b),Se=32767&b,Be=L[Ie];if(O[Se]=Be,L[Ie]=Se,b>=$e){var wt=v-b;if((Ce>7e3||ye>24576)&&wt>423){_=Jc(d,S,0,M,R,Z,oe,ye,ae,b-ae,_),ye=Ce=oe=0,ae=b;for(var ge=0;286>ge;++ge)R[ge]=0;for(ge=0;30>ge;++ge)Z[ge]=0}var Ye=2,bt=0,mn=F,Re=Se-Be&32767;if(wt>2&&Ie==V(b-Re))for(var Pe=Math.min(x,wt)-1,$t=Math.min(32767,b),Bn=Math.min(258,wt);$t>=Re&&--mn&&Se!=Be;){if(d[b+Ye]==d[b+Ye-Re]){for(var qe=0;Bn>qe&&d[b+qe]==d[b+qe-Re];++qe);if(qe>Ye){if(Ye=qe,bt=Re,qe>Pe)break;var Dn=Math.min(Re,qe-2),Mt=0;for(ge=0;Dn>ge;++ge){var Lt=b-Re+ge+32768&32767,ut=Lt-O[Lt]+32768&32767;ut>Mt&&(Mt=ut,Be=Lt)}}}Re+=(Se=Be)-(Be=O[Se])+32768&32767}if(bt){M[ye++]=268435456|ya[Ye]<<18|Kc[bt];var sn=31&ya[Ye],gi=31&Kc[bt];oe+=fl[sn]+hl[gi],++R[257+sn],++Z[gi],$e=b+Ye,++Ce}else M[ye++]=d[b],++R[d[b]]}}_=Jc(d,S,!0,M,R,Z,oe,ye,ae,b-ae,_)}return Tf(E,0,p+Rf(_)+g)})(s=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):12+o.mem,a,l)),c=u.length;return(function(d,h){var f=h.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>h.level?4:h.level==9?2:0,d[9]=3,h.mtime!=0&&Ao(d,4,Math.floor(new Date(h.mtime||Date.now())/1e3)),f){d[3]=8;for(var p=0;f.length>=p;++p)d[p+10]=f.charCodeAt(p)}})(u,e),Ao(u,c-8,n.d()),Ao(u,c-4,i),u}var fm=!!qo||!!Za,$f="text/plain",Mr=!1,Mf=(t,e)=>{var n=t.split("#"),i=n[1],r=n[0].split("?"),s=r[0],o=r[1];if(!o)return t;var a=o.split("&").filter((l=>l.split("=")[0]!==e)).join("&");return s+(a?"?"+a:"")+(i?"#"+i:"")},ks=function(t,e,n){var i;n===void 0&&(n=!0);var r=t.split("?"),s=r[0],o=r[1],a=I({},e),l=(i=o?.split("&").map((c=>{var d,h=c.split("="),f=h[0],p=n&&(d=a[f])!==null&&d!==void 0?d:h[1];return delete a[f],f+"="+p})))!==null&&i!==void 0?i:[],u=(function(c,d){var h,f;d===void 0&&(d="&");var p=[];return ie(c,(function(g,m){C(g)||C(m)||m==="undefined"||(h=encodeURIComponent((v=>v instanceof File)(g)?g.name:g.toString()),f=encodeURIComponent(m),p[p.length]=f+"="+h)})),p.join(d)})(a);return u&&l.push(u),l.length>0?s+"?"+l.join("&"):s},Po=t=>{if(t.Ji)return t.Ji;var e=t.data,n=t.compression;if(e){if(n===je.GZipJS){var i=dm((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new ct(a.length+(a.length>>>1)),d=0,h=function(m){c[d++]=m},f=0;u>f;++f){if(d+5>c.length){var p=new ct(d+8+(u-f<<1));p.set(c),c=p}var g=a.charCodeAt(f);128>g?h(g):2048>g?(h(192|g>>>6),h(128|63&g)):g>55295&&57344>g?(h(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++f))>>>18),h(128|g>>>12&63),h(128|g>>>6&63),h(128|63&g)):(h(224|g>>>12),h(128|g>>>6&63),h(128|63&g))}return Tf(c,0,d)})(Yn(e)),{mtime:0});return{contentType:$f,body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),estimatedSize:i.byteLength}}if(n===je.Base64){var r=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(Yn(e)),s=(a=>"data="+encodeURIComponent(typeof a=="string"?a:Yn(a)))(r);return{contentType:"application/x-www-form-urlencoded",body:s,estimatedSize:new Blob([s]).size}}var o=Yn(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},Lf=t=>{var e,n,i=()=>t.transport==="sendBeacon"?{url:ks(t.url,{compression:je.Base64}),encodedBody:Po(I({},t,{compression:je.Base64,Ji:void 0}))}:{url:Mf(t.url,"compression"),encodedBody:Po(I({},t,{compression:void 0,Ji:void 0}))};try{e=Po(t)}catch(r){if(mc(t.compression,ii(t.url,"compression")))return A.error("Failed to gzip request body, sending uncompressed payload",r),i();throw r}return e&&mc(t.compression,ii(t.url,"compression"))&&!((n=e.body)instanceof ArrayBuffer?zo(new Uint8Array(n)):ArrayBuffer.isView(n)&&zo(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)))?(Mr=!0,i()):{url:t.url,encodedBody:e}},Nf=t=>{try{return Lf(t)}catch(e){return A.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},hm=(function(){var t=se((function*(e){var n=Yn(e.data),i=yield(function(s,o,a){return Vo.apply(this,arguments)})(n,ne.DEBUG,{rethrow:!0});if(!i)return e;var r=yield i.arrayBuffer();return I({},e,{Ji:{contentType:$f,body:r,estimatedSize:r.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),pm=/Failed to fetch|NetworkError|Load failed/i,Of=t=>t?.name==="TypeError"&&pm.test(t?.message||""),Bf=t=>{var e=Nf(t);if(e){var n=e.url,i=e.encodedBody,r=i??{},s=r.contentType,o=r.body,a=r.estimatedSize,l=new Headers;ie(t.headers,(function(p,g){l.append(g,p)})),s&&l.append("Content-Type",s);var u=null,c=!1;if(uc){var d=new uc;u={signal:d.signal,timeout:setTimeout((()=>{var p,g;c=!0,d.abort((p=t.timeout,(g=new Error("PostHog request timed out"+(p?" after "+p+"ms":""))).name="AbortError",g))}),t.timeout)}}var h=p=>{c&&p?.name==="AbortError"||Of(p)?A.warn(p):A.error(p),t.callback==null||t.callback({statusCode:0,error:p})};try{var f;Za(n,I({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(f=u)==null?void 0:f.signal},t.fetchOptions)).then((p=>p.text().then((g=>{var m={statusCode:p.status,text:g};if(p.status===200)try{m.json=JSON.parse(g)}catch(v){A.error(v)}t.callback==null||t.callback(m)})))).catch(h).finally((()=>u?clearTimeout(u.timeout):null))}catch(p){u&&clearTimeout(u.timeout),h(p)}}},Ea=t=>{try{var e,n=Lf(t),i=n.url,r=n.encodedBody,s=r??{},o=s.body,a=s.estimatedSize;if(!o)return;var l=o instanceof Blob?o:new Blob([o],{type:s.contentType});if(Ue.sendBeacon(i,l))return;var u=U(t.data)?t.data:(e=t.data)==null?void 0:e.batch;if(U(u)&&u.length>1&&(a??0)>16384){var c=Math.ceil(u.length/2),d=h=>U(t.data)?h:I({},t.data,{batch:h});return Ea(I({},t,{data:d(u.slice(0,c))})),void Ea(I({},t,{data:d(u.slice(c))}))}A.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),Bf(I({},t,{Yi:!0}))}catch(h){A.warn("Beacon send failed",h)}},Zc=(t,e,n,i)=>{var r=i==="query"?e==="POST"?"sent_at":"_":void 0;return ks(n===je.GZipJS?Mf(t,"compression"):t,I({},r?{[r]:Date.now().toString()}:{},n===je.GZipJS?{}:{compression:n}))},Lr=[];Za&&Lr.push({transport:"fetch",method:Bf}),qo&&Lr.push({transport:"XHR",method(t){var e=Nf(t);if(e){var n=new qo,i=e.encodedBody;n.open(t.method||"GET",e.url,!0);var r=i??{},s=r.contentType,o=r.body;ie(t.headers,(function(a,l){n.setRequestHeader(l,a)})),s&&n.setRequestHeader("Content-Type",s),t.timeout&&(n.timeout=t.timeout),n.onreadystatechange=()=>{if(n.readyState===4){var a={statusCode:n.status,text:n.responseText};if(n.status===200)try{a.json=JSON.parse(n.responseText)}catch{}t.callback==null||t.callback(a)}},n.send(o)}}}),Ue!=null&&Ue.sendBeacon&&Lr.push({transport:"sendBeacon",method:Ea});var Sa=3e3;class gm{constructor(e,n){this.Xi=!0,this.tr=[],this.er=At(n?.flush_interval_ms||Sa,250,5e3,A.createLogger("flush interval"),Sa),this.ir=e}enqueue(e){this.tr.push(e),this.rr||this.nr()}unload(){this.sr();var e=this.tr.length>0?this.ar():{},n=Object.values(e);[...n.filter((i=>i.url.indexOf("/e")===0)),...n.filter((i=>i.url.indexOf("/e")!==0))].map((i=>{this.lr(I({},i,{transport:"sendBeacon"}))}))}enable(){this.Xi=!1,this.nr()}nr(){var e=this;this.Xi||(this.rr=setTimeout((()=>{if(this.sr(),this.tr.length>0){var n=this.ar(),i=function(){var s=n[r],o=new Date().getTime();s.data&&U(s.data)&&ie(s.data,(a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp})),e.lr(s)};for(var r in n)i()}}),this.er))}lr(e){try{this.ir(e)}catch(n){A.error(n)}}sr(){clearTimeout(this.rr),this.rr=void 0}ar(){var e={};return ie(this.tr,(n=>{var i,r=n,s=(r?r.batchKey:null)||r.url;C(e[s])&&(e[s]=I({},r,{data:[]})),(i=e[s].data)==null||i.push(r.data)})),this.tr=[],e}}var mm=["retriesPerformedSoFar"];class vm{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!C(w)&&"onLine"in w.navigator&&(this.dr=w.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},ve(w,"online",this.vr),ve(w,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var n=e.retriesPerformedSoFar,i=dd(e,mm);Dt(n)&&(i.url=ks(i.url,{retry_count:n})),this._instance._send_request(I({},i,{callback:r=>{if(r.statusCode!==200&&(400>r.statusCode||r.statusCode>=500)){if((r.statusCode===0?3:10)>(n??0))return void this.At(I({retriesPerformedSoFar:n},i));r.statusCode===0&&A.warn("Request failed before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped retrying after "+(n??0)+" retries.")}i.callback==null||i.callback(r)}}))}At(e){var n=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=n+1;var i=(function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),c=Math.random()-.5;return Math.ceil(u+c*(u-l))})(n),r=Date.now()+i;this.tr.push({retryAt:r,requestOptions:e});var s="Enqueued failed request for retry in "+i;navigator.onLine||(s+=" (Browser is offline)"),A.warn(s),this.ur||(this.ur=!0,this.gr())}gr(){if(this.mr&&clearTimeout(this.mr),this.tr.length===0)return this.ur=!1,void(this.mr=void 0);this.mr=setTimeout((()=>{this.dr&&this.tr.length>0&&this.cr(),this.gr()}),this.hr)}cr(){var e=Date.now(),n=[],i=this.tr.filter((s=>e>s.retryAt||(n.push(s),!1)));if(this.tr=n,i.length>0)for(var r of i)this.retriableRequest(r.requestOptions)}unload(){for(var e of(this.mr&&(clearTimeout(this.mr),this.mr=void 0),this.ur=!1,C(w)||(this.vr&&(w.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(w.removeEventListener("offline",this.pr),this.pr=void 0)),this.tr)){var n=e.requestOptions;try{this._instance._send_request(I({},n,{transport:"sendBeacon"}))}catch(i){A.error(i)}}this.tr=[]}}class _m{constructor(e){this.yr=()=>{var n,i,r,s;this.br||(this.br={});var o=this.scrollElement(),a=this.scrollY(),l=o?Math.max(0,o.scrollHeight-o.clientHeight):0,u=a+(o?.clientHeight||0),c=o?.scrollHeight||0;this.br.lastScrollY=Math.ceil(a),this.br.maxScrollY=Math.max(a,(n=this.br.maxScrollY)!==null&&n!==void 0?n:0),this.br.maxScrollHeight=Math.max(l,(i=this.br.maxScrollHeight)!==null&&i!==void 0?i:0),this.br.lastContentY=u,this.br.maxContentY=Math.max(u,(r=this.br.maxContentY)!==null&&r!==void 0?r:0),this.br.maxContentHeight=Math.max(c,(s=this.br.maxContentHeight)!==null&&s!==void 0?s:0)},this._instance=e}get _r(){return this._instance.config.scroll_root_selector}getContext(){return this.br}resetContext(){var e=this.br;return setTimeout(this.yr,0),e}startMeasuringScrollPosition(){ve(w,"scroll",this.yr,{capture:!0}),ve(w,"scrollend",this.yr,{capture:!0}),ve(w,"resize",this.yr)}scrollElement(){if(!this._r)return w?.document.documentElement;var e=U(this._r)?this._r:[this._r];for(var n of e){var i=w?.document.querySelector(n);if(i)return i}}wr(e){var n=e==="y"?"scrollTop":"scrollLeft";if(this._r){var i=this.scrollElement();return i&&i[n]||0}return w?e==="y"?w.scrollY||w.pageYOffset||w.document.documentElement.scrollTop||0:w.scrollX||w.pageXOffset||w.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var ym=t=>xf(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class Xc{constructor(e,n,i,r){this.kr=s=>{var o=this.Sr();if(!o||o.sessionId!==s){var a={sessionId:s,props:this.Cr(this._instance)};this.Mr.register({[ua]:a})}},this._instance=e,this.Tr=n,this.Mr=i,this.Cr=r||ym,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[ua]}getSetOnceProps(){var e,n=(e=this.Sr())==null?void 0:e.props;return n?"r"in n?If(n,this._instance.config.disable_capture_url_hashes):{$referring_domain:n.referringDomain,$pathname:n.initialPathName,utm_source:n.utm_source,utm_campaign:n.utm_campaign,utm_medium:n.utm_medium,utm_content:n.utm_content,utm_term:n.utm_term}:{}}getSessionProps(){var e={};return ie(ll(this.getSetOnceProps()),((n,i)=>{i==="$current_url"&&(i="url"),e["$session_entry_"+Go(i)]=n})),e}}class pl{on(e,n){return this.Er[e]||(this.Er[e]=[]),this.Er[e].push(n),()=>{this.Er[e]=this.Er[e].filter((i=>i!==n))}}emit(e,n){for(var i of this.Er[e]||[])i(n);for(var r of this.Er["*"]||[])r(e,n)}constructor(){this.Er={}}}var Si=pe("[SessionId]");class Qc{on(e,n){return this.Ir.on(e,n)}constructor(e,n,i){var r;if(this.Pr=null,this.Rr=[],this.Ar=void 0,this.Fr=!1,this.Ir=new pl,this.Lr=(u,c)=>!(!Dt(u)||!Dt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===Wt)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Ne=e.config,this.Mr=e.persistence,this.Or=void 0,this.Dr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.$r=n||Ht,this.Nr=i||Ht;var s=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*At(this.Ne.session_idle_timeout_seconds||1800,60,36e3,Si.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.qr(),this.jr="ph_"+s+"_window_id",this.Br="ph_"+s+"_primary_window_exists",this.Hr()){var o=be.H(this.jr),a=be.H(this.Br);o&&!a?this.Or=o:be.q(this.jr),be.F(this.Br,!0)}if((r=this.Ne.bootstrap)!=null&&r.sessionID)try{var l=(u=>{var c=this.Ne.bootstrap.sessionID.replace(/-/g,"");if(c.length!==32)throw new Error("Not a valid UUID");if(c[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(c.substring(0,12),16)})();this.Ur(this.Ne.bootstrap.sessionID,new Date().getTime(),l)}catch(u){Si.error("Invalid sessionID in bootstrap",u)}this.zr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return C(this.Rr)&&(this.Rr=[]),this.Rr.push(e),this.Dr&&e(this.Dr,this.Or),()=>{this.Rr=this.Rr.filter((n=>n!==e))}}Hr(){return this.Ne.persistence!=="memory"&&!this.Mr.xi&&be.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&be.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?be.H(this.jr):null}Zr(e){var n=this.Pr;return!Ke(n)&&!Ke(e)&&5e3>Math.abs(e-n)}Ur(e,n,i){var r=n!==this._sessionActivityTimestamp,s=!(e!==this.Dr||i!==this._sessionStartTimestamp);this._sessionStartTimestamp=i,this._sessionActivityTimestamp=n,this.Dr=e,s&&!r||s&&this.Zr(n)||(this.Pr=n,this.Mr.register({[Kn]:[n,e,i]}))}Gr(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return Dt(n)&&n>0}Qr(){this.Gr()?this.Mr.refreshKey(Kn):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!Ke(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this.Pr){this.Qr();var n=this.Jr();n[1]===this.Dr&&n[2]===this._sessionStartTimestamp&&(this.Pr=this._sessionActivityTimestamp,this.Mr.register({[Kn]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],n=Dt(e)?e:0,i=Dt(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(n,i)}Xr(e){return this.Qr(),this.Lr(e,this.Yr())}Jr(){var e=this.Mr.props[Kn];return U(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Pr=null,clearTimeout(this.tn),this.tn=void 0,this.Ur(null,null,null)}destroy(){this.Fr=!0,this.Kr(),clearTimeout(this.tn),this.tn=void 0,this.Ar&&w&&(w.removeEventListener(ns,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&be.q(this.Br)},ve(w,ns,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=null),this.Ne.cookieless_mode===Wt)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var i=n||new Date().getTime(),r=this.Jr(),s=r[1],o=r[2],a=this.Yr(),l=this.Vr(),u=Dt(o)&&Math.abs(i-o)>864e5,c=!1,d=!1,h=!s,f=s,p=!h&&!e&&this.Lr(i,a);if(p){(p=this.Xr(i))||Si.info("cross-tab refresh kept the session alive",{sessionId:s});var g=this.Jr();s=g[1],o=g[2]}h||p||u?(s=this.$r(),l=this.Nr(),Si.info("new session ID generated",{sessionId:s,windowId:l,changeReason:{noSessionId:h,activityTimeout:p,sessionPastMaximumLength:u}}),o=i,c=!0):(l||(l=this.Nr(),c=!0),(d=s!==f)&&(Si.info("adopted cross-tab session id",{sessionId:s,windowId:l}),c=!0));var m=Dt(a)&&e&&!u?a:i,v=Dt(o)?o:new Date().getTime();this.Wr(l),this.Ur(s,m,v),e||this.qr();var E={noSessionId:h,activityTimeout:p,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((S=>S(s,l,E))),{sessionId:s,windowId:l,sessionStartTimestamp:v,changeReason:c?E:void 0,lastActivityTimestamp:a}}qr(){this.Fr||(clearTimeout(this.tn),this.tn=setTimeout((()=>{if(!this.Fr)if(this.Xr(new Date().getTime())){var e=this.Dr;this.resetSessionId(),this.Ir.emit("forcedIdleReset",{idleSessionId:e})}else this.qr()}),1.1*this.sessionTimeoutMs))}}var Df=function(t,e){if(!t)return!1;var n=t.userAgent;if(n&&_c(n,e))return!0;try{var i=t?.userAgentData;if(i!=null&&i.brands&&i.brands.some((r=>_c(r?.brand,e))))return!0}catch{}return!!t.webdriver};function jf(){return(jf=se((function*(){var t=Ue?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),n=e?.model;return X(n)&&n.length>0?n:void 0}catch(i){return void A.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",i)}}))).apply(this,arguments)}var cs=function(t,e){if(!(function(n){try{new RegExp(n)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function Fo(t,e,n){return Yn({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}var Uf={exact:(t,e)=>e.some((n=>t.some((i=>n===i)))),is_not:(t,e)=>e.every((n=>t.every((i=>n!==i)))),regex:(t,e)=>e.some((n=>t.some((i=>cs(n,i))))),not_regex:(t,e)=>e.every((n=>t.every((i=>!cs(n,i))))),icontains:(t,e)=>e.map(Er).some((n=>t.map(Er).some((i=>n.includes(i))))),not_icontains:(t,e)=>e.map(Er).every((n=>t.map(Er).every((i=>!n.includes(i))))),gt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>i>parseFloat(r)))})),lt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>it.toLowerCase();function Hf(t,e){return!t||Object.entries(t).every((n=>{var i=n[1],r=e?.[n[0]];if(C(r)||Ke(r))return!1;var s=[String(r)],o=Uf[i.operator];return!!o&&o(i.values,s)}))}var xa="custom",eu="i.posthog.com",wm=/^\/static\//;class bm{constructor(e){this.en={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,n=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return n||(n=this.apiHost.replace("."+eu,".posthog.com")),n==="https://app.posthog.com"?"https://us.posthog.com":n}get region(){return this.en[this.apiHost]||(this.en[this.apiHost]=/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"us":/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"eu":xa),this.en[this.apiHost]}rn(e){if(wm.test(e)){var n=this.instance.config.asset_host;if(typeof n=="string")return n.trim().replace(/\/$/,"")||void 0}}endpointFor(e,n){if(n===void 0&&(n=""),n&&(n=n[0]==="/"?n:"/"+n),e==="ui")return this.uiHost+n;if(e==="flags")return this.flagsApiHost+n;if(e==="assets"){var i=this.rn(n);if(i)return""+i+n}if(this.region===xa)return this.apiHost+n;var r=eu+n;switch(e){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}}function Wf(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var Q=pe("[Surveys]"),qf="seenSurvey_",zf=t=>{try{var e=(n=>((i,r)=>""+qf+(function(s){return s.current_iteration&&s.current_iteration>0?s.id+"_"+s.current_iteration:s.id})(r))(0,n))(t);if(localStorage.getItem(e))return;localStorage.setItem(e,"true")}catch(n){Q.error("Failed to persist survey seen state",n)}},Em=[Io.Popover,Io.Widget,Io.API],Sm={ignoreConditions:!1,ignoreDelay:!1,displayType:_a.Popover},xm=pe("[PostHog ExternalIntegrations]"),Im={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class km{constructor(e){this._instance=e}ai(e,n){var i;(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,e,(r=>{if(r)return xm.error("failed to load script",r);n()}))}startIfEnabledOrStop(){var e=this,n=function(){var s,o,a,l=i[0],u=i[1];!u||(s=B.__PosthogExtensions__)!=null&&(s=s.integrations)!=null&&s[l]||e.ai(Im[l],(()=>{var c;(c=B.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=B.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=B.__PosthogExtensions__)==null||(a=a.integrations)==null||(a=a[l])==null||a.stop())};for(var i of Object.entries((r=this._instance.config.integrations)!==null&&r!==void 0?r:{})){var r;n()}}}class Cm{constructor(e,n){this.rt=e,this.nn=n,this.sn=new Map,this.an=!1}add(e){var n=this;return se((function*(){if(n.an)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(n.sn.has(e.name))throw new Error('Browser extension "'+e.name+'" is already registered');n.sn.set(e.name,e);try{var i=e.setup(n.nn);i&&(yield i)}catch(s){var r=n.sn.get(e.name)===e;r&&n.sn.delete(e.name),n.rt.error('Failed to set up browser extension "'+e.name+'"',s),r&&n.ln(e)}}))()}dispose(){if(!this.an){this.an=!0;var e=Array.from(this.sn.values()).reverse();for(var n of(this.sn.clear(),e))this.ln(n)}}ln(e){try{var n=e.dispose==null?void 0:e.dispose();n&&De(n.then)&&n.then(void 0,(i=>{this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}))}catch(i){this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}}}class Am{constructor(e){this._instance=e}initialize(){}get(e){var n=this._instance.persistence;if(typeof e=="string")return n?.get_property(e);var i={};for(var r of e){var s=n?.get_property(r);C(s)||(i[r]=s)}return i}set(e,n){var i;(i=this._instance.persistence)==null||i.register(typeof e=="string"?{[e]:n}:e)}remove(e){var n;(n=this._instance.persistence)==null||n.unregister(e)}}var tu="extensionsRemoteConfig";class Pm{constructor(e){this.an=!1,this.instance=e,this.rt=A,this.un=e.hn,this.kv=new Am(e),this.onEvent=n=>br(this.instance.on("eventCaptured",(i=>{try{n({event:i.event,properties:i.properties})}catch(r){this.rt.error("Browser extension event listener failed",r)}}))),this.onRemoteConfig=n=>{if(this.an)return br((()=>{}));var i=s=>{try{n(s)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},r=this.instance.dn.on(tu,i);return this.un&&i(this.un),br(r)},this.vn=new Cm(A.createLogger("[BrowserExtensions]"),this)}get logger(){return this.rt}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return(e=this.instance.get_property(Yi))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(Yi);return typeof e=="string"?e:void 0}get library(){return{name:ne.LIB_NAME,version:ne.LIB_VERSION}}get initialPersonProperties(){var e,n;return(e=(n=this.instance.persistence)==null?void 0:n.get_initial_props())!==null&&e!==void 0?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,n,i,r,s=(e=this.instance.sessionManager)==null?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:(n=s?.sessionId)!==null&&n!==void 0?n:"",windowId:(i=s?.windowId)!==null&&i!==void 0?i:"",sessionStartTimestamp:(r=s?.sessionStartTimestamp)!==null&&r!==void 0?r:0}}catch{return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get projectToken(){return this.instance.config.token}add(e){return this.vn.add(e)}capture(e,n,i){var r=this;return se((function*(){i?r.instance.capture(e,n,{timestamp:i.timestamp,uuid:i.uuid,$set:i.set,$set_once:i.setOnce}):r.instance.capture(e,n)}))()}registerDynamicEventProperties(e){return br(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(tu,e))}sendRequest(e,n){var i=this;return se((function*(){var r;n===void 0&&(n={});var s=i.instance.requestRouter.endpointFor((r=n.target)!==null&&r!==void 0?r:"api",e),o={method:n.method,url:n.query?ks(s,n.query):s,data:n.body,headers:n.headers,timeout:n.timeoutMs,fireCallbackOnDrop:!0,transport:n.transport,compression:n.compression,timestampMode:n.sentAt};return n.transport==="sendBeacon"?(i.instance._send_request(o),{statusCode:202}):new Promise((a=>{o.callback=a,i.instance._send_request(o)}))}))()}dispose(){this.an||(this.an=!0,this.vn.dispose())}}var Wi={},Ro=0,us=()=>{},nu='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',xi="Surveys module not available",iu="sanitize_properties is deprecated. Use before_send instead",Vf="Invalid value for property_denylist config: ",Fm=["token","distinct_id",Xd],Gn="posthog",Gf=!fm&&Ve?.indexOf("MSIE")===-1&&Ve?.indexOf("Mozilla")===-1,To=t=>{var e;return I({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:Rg(P?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:us,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:t??"unset",__preview_deferred_init_extensions:!1,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:me&&X(me?.search)&&me.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disableDeviceModel:!1,disable_external_dependency_loading:!1,strict_script_versioning:!1,enable_recording_console_log:void 0,secure_cookie:(w==null||(e=w.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(n){A.error("Bad HTTP status: "+n.statusCode+" "+n.text)},get_device_id:n=>n,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:pa,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:Sa},error_tracking:{},_onCapture:us},(n=>({rageclick:n&&n>="2026-05-30"?{content_ignorelist:Wg,ignore_text_selection:!0}:!n||"2025-11-30">n||{content_ignorelist:!0},capture_pageview:!n||"2025-05-24">n||"history_change",session_recording:n&&n>="2026-06-25"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6},streamNetworkBody:!0}:n&&n>="2026-05-30"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6}}:n&&n>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:n&&n>="2026-01-30"?"head":"body",internal_or_test_user_hostname:n&&n>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:n&&n>="2026-05-30"?250:0,split_storage:!(!n||"2026-05-30">n),detect_google_search_app:!(!n||"2026-05-30">n),disable_capture_url_hashes:!(!n||"2026-06-25">n)}))(t))},Rm=[["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"]],ru=t=>{var e={};for(var n of Rm){var i=n[0],r=n[1];C(t[i])||(e[r]=t[i])}var s=fe({},e,t),o=t.__preview_external_dependency_versioned_paths;return C(o)||(C(t.strict_script_versioning)&&(s.strict_script_versioning=!!o),X(o)&&C(t.asset_host)&&(s.asset_host=o)),U(t.property_blacklist)&&(C(t.property_denylist)?s.property_denylist=t.property_blacklist:U(t.property_denylist)?s.property_denylist=[...t.property_blacklist,...t.property_denylist]:A.error(Vf+t.property_denylist)),s};class Tm{constructor(){this.__forceAllowLocalhost=!1}get fn(){return this.__forceAllowLocalhost}set fn(e){A.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class Je{pn(e,n){if(e){var i=this.sn.indexOf(e);i!==-1&&this.sn.splice(i,1)}return this.sn.push(n),n.initialize==null||n.initialize(),n}gn(){return this.config.cookieless_mode===Wt||this.config.cookieless_mode===kn&&this.consent.isRejected()}get decideEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){var e;this.webPerformance=new Tm,this.mn=!1,this.version=ne.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new pl,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=To(),this.SentryIntegration=Zg,this.sentryIntegration=i=>(function(r,s){var o=vf(r,s);return{name:mf,processEvent:a=>o(a)}})(this,i),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.wn=!1,this.kn=null,this.xn=null,this.Sn=null,this.scrollManager=new _m(this),this.pageViewManager=new Wc(this),this.rateLimiter=new om(this),this.requestRouter=new bm(this),this.consent=new Bg(this),this.externalIntegrations=new km(this);var n=(e=Je.__defaultExtensionClasses)!==null&&e!==void 0?e:{};this.featureFlags=n.featureFlags&&new n.featureFlags(this),this.toolbar=n.toolbar&&new n.toolbar(this),this.surveys=n.surveys&&new n.surveys(this),this.conversations=n.conversations&&new n.conversations(this),this.logs=n.logs&&new n.logs(this),this.metrics=n.metrics&&new n.metrics(this),this.experiments=n.experiments&&new n.experiments(this),this.exceptions=n.exceptions&&new n.exceptions(this),this.people={set:(i,r,s)=>{var o=X(i)?{[i]:r}:i;this.setPersonProperties(o),s?.({})},set_once:(i,r,s)=>{var o=X(i)?{[i]:r}:i;this.setPersonProperties(void 0,o),s?.({})}},this.on("eventCaptured",(i=>A.info('send "'+i?.event+'"',i)))}init(e,n,i){if(i&&i!==Gn){var r,s=(r=Wi[i])!==null&&r!==void 0?r:new Je;return s._init(e,n,i),Wi[i]=s,Wi[Gn][i]=s,s}return this._init(e,n,i)}_init(e,n,i){var r,s;n===void 0&&(n={});var o,a=X(e)?e.trim():"";if(!a)return A.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return a!==((o=this.config)==null?void 0:o.token)?console.warn("[PostHog.js]","You have already initialized PostHog with a different project token! Re-initializing is a no-op, so events will keep going to the project this instance was initialized with. To capture into a second project, load PostHog once, then initialize a named instance after the SDK has loaded, e.g. posthog.init('"+a+"', { ... }, 'project2')"):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=To(n.defaults),n.debug=this.Cn(n.debug),this.Mn=n,this.Tn=[],n.person_profiles?this.xn=n.person_profiles:n.process_person&&(this.xn=n.process_person);var l=To(n.defaults),u=ru(n),c=fe({},l,u,{name:i,token:a});he(l.rageclick)&&he(u.rageclick)&&(c.rageclick=fe({},l.rageclick,u.rageclick)),he(l.session_recording)&&he(u.session_recording)&&(c.session_recording=fe({},l.session_recording,u.session_recording)),this.set_config(c),this.config.on_xhr_error&&A.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=n.disable_compression?void 0:je.GZipJS;var d=this.En();if(this.persistence=new xo(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new xo(I({},this.config,{persistence:"sessionStorage"}),d,!1),this.bn="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&be.N()){var h=be.H(this.bn);U(h)&&h.forEach((k=>{X(k)&&this.yn.add(k)}))}else be.q(this.bn);var f=I({},this.persistence.props),p=I({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new gm((k=>this.Pn(k)),this.config.request_queue_config),this.Rn=new vm(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new Qc(this),this.sessionPropsManager=new Xc(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((k,T,x)=>{(x!=null&&x.activityTimeout||x!=null&&x.sessionPastMaximumLength||x!=null&&x.crossTabAdoption)&&this.An()}))),this.Fn(),this.config.__preview_deferred_init_extensions?(A.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Ln(g)}),0)):(A.info("Initializing extensions synchronously"),this.Ln(g)),ne.DEBUG=ne.DEBUG||this.config.debug,ne.DEBUG&&A.info("Starting in debug mode",{this:this,config:n,thisC:I({},this.config),p:f,s:p}),!this.config.identity_distinct_id||(r=n.bootstrap)!=null&&r.distinctID||(n.bootstrap=I({},n.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((s=n.bootstrap)==null?void 0:s.distinctID)!==void 0){var m=n.bootstrap.distinctID,v=this.get_distinct_id(),E=this.persistence.get_property(ot);if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&E===Un)this.identify(m);else if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&E===vn)A.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{var S=this.config.get_device_id(Ht()),_=n.bootstrap.isIdentifiedID?S:m;this.persistence.set_property(ot,n.bootstrap.isIdentifiedID?vn:Un),this.register({distinct_id:m,$device_id:_})}}if(g)this.register_once({distinct_id:mr,$device_id:null},"");else if(!this.get_distinct_id()){var b=this.config.get_device_id(Ht());this.register_once({distinct_id:b,$device_id:b},""),this.persistence.set_property(ot,Un)}return ve(w,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),n.segment?(function(k,T){var x=k.config.segment;if(!x)return T();(function(F,$){var O=F.config.segment;if(!O)return $();var L=K=>{var V=()=>K.anonymousId()||Ht();F.config.get_device_id=V,K.id()&&(F.register({distinct_id:K.id(),$device_id:V()}),F.persistence.set_property(ot,vn)),$()},N=O.user();"then"in N&&De(N.then)?N.then(L):L(N)})(k,(()=>{x.register((F=>{typeof Promise<"u"&&Promise.resolve||Eo.warn("This browser does not have Promise support, and can not use the segment integration");var $=(O,L)=>{if(!L)return O;O.event.userId||O.event.anonymousId===F.get_distinct_id()||(Eo.info("No userId set, resetting PostHog"),F.reset()),O.event.userId&&O.event.userId!==F.get_distinct_id()&&(Eo.info("UserId set, identifying with PostHog"),F.identify(O.event.userId));var N=F.calculateEventProperties(L,O.event.properties);return O.event.properties=Object.assign({},N,O.event.properties),O};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:O=>$(O,O.event.event),page:O=>$(O,Vn),identify:O=>$(O,yo),screen:O=>$(O,"$screen")}})(k)).then((()=>{T()}))}))})(this,(()=>this.On())):this.On(),De(this.config._onCapture)&&this.config._onCapture!==us&&(A.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(k=>this.config._onCapture(k.event,k)))),this.config.ip&&A.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this.config.disableDeviceModel||(function(){return jf.apply(this,arguments)})().then((k=>{k&&this.register({[vo]:k})})).catch(us),this}Fn(){var e,n,i,r,s,o,a=(e=(n=this.config.__extensionClasses)==null?void 0:n.featureFlags)!==null&&e!==void 0?e:(i=Je.__defaultExtensionClasses)==null?void 0:i.featureFlags;a&&(this.featureFlags&&this.featureFlags instanceof a||((r=this.Dn)==null||r.call(this),this.Dn=void 0,this.featureFlags=new a(this)),De(this.featureFlags.onReloading)&&De(this.featureFlags.setup)?this.Dn||(this.Dn=this.featureFlags.onReloading((()=>{this.dn.emit("featureFlagsReloading",!0)})),this.$n().add(this.featureFlags)):(s=(o=this.featureFlags).initialize)==null||s.call(o))}Ln(e){var n,i,r,s,o,a,l,u=performance.now(),c=I({},Je.__defaultExtensionClasses,this.config.__extensionClasses),d=[];c.exceptions&&this.sn.push(this.exceptions=(n=this.exceptions)!==null&&n!==void 0?n:new c.exceptions(this)),c.historyAutocapture&&this.sn.push(this.historyAutocapture=new c.historyAutocapture(this)),c.tracingHeaders&&this.sn.push(this.tracingHeaders=new c.tracingHeaders(this)),c.siteApps&&this.sn.push(this.siteApps=new c.siteApps(this)),c.sessionRecording&&!e&&this.sn.push(this.sessionRecording=new c.sessionRecording(this)),this.config.disable_scroll_properties||d.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),c.autocapture&&this.sn.push(this.autocapture=new c.autocapture(this)),c.surveys&&this.sn.push(this.surveys=(i=this.surveys)!==null&&i!==void 0?i:new c.surveys(this)),c.logs&&this.sn.push(this.logs=(r=this.logs)!==null&&r!==void 0?r:new c.logs(this)),c.metrics&&this.sn.push(this.metrics=(s=this.metrics)!==null&&s!==void 0?s:new c.metrics(this)),c.conversations&&this.sn.push(this.conversations=(o=this.conversations)!==null&&o!==void 0?o:new c.conversations(this)),c.productTours&&this.sn.push(this.productTours=new c.productTours(this)),c.heatmaps&&this.sn.push(this.heatmaps=new c.heatmaps(this)),c.webVitalsAutocapture&&this.sn.push(this.webVitalsAutocapture=new c.webVitalsAutocapture(this)),c.exceptionObserver&&this.sn.push(this.exceptionObserver=new c.exceptionObserver(this)),c.deadClicksAutocapture&&this.sn.push(this.deadClicksAutocapture=new c.deadClicksAutocapture(this,Jg)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((h=>{h.initialize&&d.push((()=>{h.initialize==null||h.initialize()}))})),d.push((()=>{if(this.Nn){var h=this.Nn;this.Nn=void 0,this.sn.forEach((f=>f.onRemoteConfig==null?void 0:f.onRemoteConfig(h)))}})),this.qn(d,u)}qn(e,n){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,n)}),0);var i=e.shift();if(i)try{i()}catch(s){A.error("Error initializing extension:",s)}}var r=Math.round(performance.now()-n);this.register_for_session({[Qd]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[ef]:r}),this.config.__preview_deferred_init_extensions&&A.info("PostHog extensions initialized ("+r+"ms)")}Zi(e){var n;if(!P||!P.body)return A.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.Zi(e)}),500);if(this.config.__preview_deferred_init_extensions&&(this.Nn=e),this.hn=e,this.compression=void 0,e.ok){var i,r=e.config;r.supportedCompression&&!this.config.disable_compression&&(this.compression=j(r.supportedCompression,je.GZipJS)?je.GZipJS:j(r.supportedCompression,je.Base64)?je.Base64:void 0),(i=r.analytics)!=null&&i.endpoint&&(this.analyticsDefaultEndpoint=r.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:pa}),(n=this.jn)==null||n.handleRemoteConfig(e),this.sn.forEach((s=>s.onRemoteConfig==null?void 0:s.onRemoteConfig(e)))}On(){try{this.config.loaded(this)}catch(i){A.critical("`loaded` function failed",i)}if(this.Bn(),this.config.internal_or_test_user_hostname&&me!=null&&me.hostname){var e=me.hostname,n=this.config.internal_or_test_user_hostname;(typeof n=="string"?e===n:n.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.gn())&&this.Hn()}),1),this.Un=new Cf(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()&&vr(this.__request_queue,(e=>this.Pn(e))),this.__request_queue=[],this.Bn()}_handle_unload(){var e,n,i,r,s;(e=this.surveys)==null||e.handlePageUnload==null||e.handlePageUnload(),(n=this.metrics)==null||n.flush("sendBeacon"),this.config.request_batching?(this.zn()&&this.capture(_o),(i=this.logs)==null||i.flushLogs("sendBeacon"),(r=this.In)==null||r.unload(),(s=this.Rn)==null||s.unload()):this.zn()&&this.capture(_o,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?Gf?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)?e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:429})):(e.transport=e.transport||this.config.api_transport,e.headers=I({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,(C(this.config.disable_beacon)?this.config.__preview_disable_beacon:this.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(n=>{var i,r,s,o=I({},n);o.timeout=o.timeout||6e4;var a,l,u,c,d,h=(i=o.transport)!==null&&i!==void 0?i:"fetch";h==="sendBeacon"&&C(o.compression)&&o.data&&(o.compression=je.Base64),o.method==="POST"&&o.data&&(o.timestampMode==="capture-body"?o.data={api_key:(l=(d=(c=U(a=o.data)?a:[a])[0])==null||(u=d.properties)==null?void 0:u.token)!==null&&l!==void 0?l:d?.token,batch:c,sent_at:new Date().toISOString()}:o.timestampMode==="body"&&(o.data=(function(m,v){return v===void 0&&(v=new Date().toISOString()),U(m)?m.map((E=>I({},E,{sent_at:v}))):I({},m,{sent_at:v})})(o.data))),o.url=Zc(o.url,o.method,o.compression,o.timestampMode);var f=Lr.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),p=(r=(s=(function(m,v){for(var E=0;m.length>E;E++)if(m[E].transport===h)return m[E]})(f))==null?void 0:s.method)!==null&&r!==void 0?r:f[0].method;if(!p)throw new Error("No available transport method");var g=m=>{try{p(m)}catch(v){Of(v)?A.warn(v):A.error(v),o.callback==null||o.callback({statusCode:0,error:v})}};h!=="sendBeacon"&&o.data&&o.compression===je.GZipJS&&$p&&typeof Promise<"u"&&!Mr?hm(o).then((m=>{g(m)})).catch((m=>{if(vc(m))return Mr=!0,void g(I({},o,{compression:void 0,url:Zc(n.url,n.method,void 0,n.timestampMode)}));(v=>{if(!v||typeof v!="object")return!1;var E="name"in v?String(v.name):"";return vc(v)||E===fd})(m)&&(Mr=!0),g(o)})):p(o)})(I({},e,{callback:n=>{var i,r;this.rateLimiter.checkForLimiting(n),400>n.statusCode||(i=(r=this.config).on_request_error)==null||i.call(r,n),e.callback==null||e.callback(n)}}))):e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:0}))}Pn(e){this.Rn?this.Rn.retriableRequest(e):this._send_request(e)}_execute_array(e){Ro++;try{var n,i=[],r=[],s=[];vr(e,(a=>{if(a)if(U(n=a[0]))s.push(a);else if(De(a))try{a.call(this)}catch(l){A.error("Error executing queued PostHog call",a,l)}else U(a)&&n==="alias"?i.push(a):U(a)&&n.indexOf("capture")!==-1&&De(this[n])?s.push(a):r.push(a)}));var o=function(a,l){vr(a,(function(u){try{if(U(u[0])){var c=l;ie(u,(function(d){c=c[d[0]].apply(c,d.slice(1))}))}else l[u[0]].apply(l,u.slice(1))}catch(d){A.error("Error executing queued PostHog call",u,d)}}))};o(i,this),o(r,this),o(s,this)}finally{Ro--}}push(e){if(Ro>0&&U(e)&&X(e[0])){var n=Je.prototype[e[0]];De(n)&&n.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,n,i){var r,s,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.In){if(this.is_capturing())if(!C(e)&&X(e)){var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var c=i!=null&&i.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(c==null||!c.isRateLimited){n!=null&&n.$current_url&&!X(n?.$current_url)&&(A.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),n==null||delete n.$current_url),e!=="$exception"||i!=null&&i.Wn||A.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,h=i?.timestamp||d,f=Ec(i?.uuid,Ht),p={uuid:f,event:e,properties:this.calculateEventProperties(e,n||{},h,f)};e===Vn&&this.config.__preview_capture_bot_pageviews&&u&&(p.event="$bot_pageview",p.properties.$browser_type="bot"),c&&(p.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&p.properties.$feature_flag_has_experiment===!1&&this.get_property(Zr)===!0;i?.$set&&!g&&(p.$set=i?.$set);var m=i?.$unset;m&&(p.$unset=m);var v,E,S,_=g?void 0:this.Vn(i?.$set_once,e!==Ac,e===yo);if(_&&(p.$set_once=_),i!=null&&i._noTruncate||(s=this.config.properties_string_max_length,o=p,a=L=>X(L)?L.slice(0,s):L,l=new Set,p=(function L(N,K){if(N!==Object(N))return a?a(N):N;if(!l.has(N)){var V;if(l.add(N),U(N))V=[],vr(N,(R=>{V.push(L(R))}));else{var M={};ie(N,((R,Z)=>{l.has(R)||(M[Z]=L(R))})),V=M}return V}})(o)),p.timestamp=h,C(i?.timestamp)||(p.properties.$event_time_override_provided=!0,p.properties.$event_time_override_system_time=d),g&&(p.properties=(function(L,N){N===void 0&&(N=[]);var K={},V=M=>{L[M]!==void 0&&(K[M]=L[M])};return Mp.forEach(V),N.forEach(V),K})(p.properties,Fm)),e===zt.DISMISSED||e===zt.SENT){var b=n?.[ko.SURVEY_ID],k=n?.[ko.SURVEY_ITERATION];zf({id:b,current_iteration:k}),p.$set=I({},p.$set,{[(v={id:b,current_iteration:k},E=e===zt.SENT?"responded":"dismissed",S="$survey_"+E+"/"+v.id,v.current_iteration&&v.current_iteration>0&&(S="$survey_"+E+"/"+v.id+"/"+v.current_iteration),S)]:!0})}else e===zt.SHOWN&&(p.$set=I({},p.$set,{[ko.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===sm.SHOWN){var T=n?.[zc.TOUR_TYPE];T&&(p.$set=I({},p.$set,{[zc.TOUR_LAST_SEEN_DATE+"/"+T]:new Date().toISOString()}))}var x=I({},p.properties.$set,p.$set);if(Kt(x)||this.setPersonPropertiesForFlags(x),!H(this.config.before_send)){var F=this.Pt(p);if(!F)return;(p=F).uuid=Ec(p.uuid,Ht)}this.dn.emit("eventCaptured",p);var $=(r=i?._url)!==null&&r!==void 0?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),O={method:"POST",url:$,data:p,compression:"best-available",timestampMode:i?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test($)?"body":"capture-body",batchKey:i?._batchKey,transport:i?.transport};return!this.config.request_batching||i&&(i==null||!i._batchKey)||i!=null&&i.send_instantly?this.Pn(O):this.In.enqueue(O),p}A.critical("This capture call is ignored due to client rate limiting.")}}else A.error("No event name provided to posthog.capture")}else A.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(n=>e(n.event,n)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new Pm(this)}cn(e){this._n.push(e);var n=!0;return()=>{if(n){n=!1;var i=this._n.indexOf(e);i!==-1&&this._n.splice(i,1)}}}calculateEventProperties(e,n,i,r,s){if(i=i||new Date,!this.persistence||!this.sessionPersistence)return n;var o=s?void 0:this.persistence.remove_event_timer(e),a=I({},n);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.gn()&&(a[Xd]=!0),e==="$snapshot"){var l=I({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!X(a.distinct_id)&&!ke(a.distinct_id)||Ko(a.distinct_id))&&A.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=(function(b,k,T,x){var F,$,O,L;if(x===void 0&&(x=!1),!Ve)return{};var N,K=b?[...ri,...k||[]]:[],V=(function(Bn){for(var qe=0;wc.length>qe;qe++){var Dn=wc[qe],Mt=Dn[1],Lt=Dn[0].exec(Bn),ut=Lt&&(De(Mt)?Mt(Lt,Bn):Mt);if(ut)return ut}return["",""]})(Ve),M=V[0],R=V[1],Z=(N=typeof navigator<"u"?navigator:void 0)!=null&&N.brave?{brave:!0}:{},Ce={};C(T)||(Ce.detectGoogleSearchApp=T);var oe={},ye=(F=navigator)==null||(F=F.userAgentData)==null?void 0:F.platform,$e=($=navigator)==null?void 0:$.maxTouchPoints,ae=w==null||(O=w.screen)==null?void 0:O.width,Ie=w==null||(L=w.screen)==null?void 0:L.height,Se=w?.devicePixelRatio;C(ye)||(oe.userAgentDataPlatform=ye),C($e)||(oe.maxTouchPoints=$e),C(ae)||(oe.screenWidth=ae),C(Ie)||(oe.screenHeight=Ie),C(Se)||(oe.devicePixelRatio=Se);var Be,wt,ge,Ye,bt,mn,Re,Pe,$t=fe(ll({$os:M,$os_version:R,$browser:Od(Ve,navigator.vendor,Z,Ce),$device:bc(Ve),$device_type:(wt=Ve,ge=oe,Pe=bc(wt),Pe===yd||Pe===_d||Pe==="Kobo"||Pe==="Kindle Fire"||Pe===Td?ei:Pe===Gi||Pe===Xn||Pe===Ki||Pe===Jo?"Console":Pe===bd?"Wearable":Pe?it:ge?.userAgentDataPlatform==="Android"&&((Ye=ge?.maxTouchPoints)!==null&&Ye!==void 0?Ye:0)>0?600>Math.min((bt=ge?.screenWidth)!==null&&bt!==void 0?bt:0,(mn=ge?.screenHeight)!==null&&mn!==void 0?mn:0)/((Re=ge?.devicePixelRatio)!==null&&Re!==void 0?Re:1)?it:ei:"Desktop"),$timezone:kf(),$timezone_offset:nm()}),{$current_url:Zi(x?fn(me?.href):me?.href,K,Xi),$host:me?.host,$pathname:me?.pathname,$raw_user_agent:Ve.length>1e3?Ve.substring(0,997)+"...":Ve,$browser_version:Qp(Ve,navigator.vendor,Z,Ce),$browser_language:qc(),$browser_language_prefix:(Be=qc(),typeof Be=="string"?Be.split("-")[0]:void 0),$screen_height:w?.screen.height,$screen_width:w?.screen.width,$viewport_height:w?.innerHeight,$viewport_width:w?.innerWidth,$lib:ne.LIB_NAME,$lib_version:ne.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return ne.SDK_DIST_CHANNEL&&($t.$sdk_dist_channel=ne.SDK_DIST_CHANNEL),$t})(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties,this.config.detect_google_search_app,this.config.disable_capture_url_hashes);if(this.sessionManager){var d=this.sessionManager.checkAndGetSessionAndWindowId(s,i.getTime()),h=d.windowId;a.$session_id=d.sessionId,a.$window_id=h}this.sessionPropsManager&&fe(a,this.sessionPropsManager.getSessionProps());try{var f;this.sessionRecording&&fe(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(f=this.Rn)==null?void 0:f.length}catch(b){a.$sdk_debug_error_capturing_properties=String(b)}if(this.requestRouter.region===xa&&(a.$lib_custom_api_host=this.config.api_host),u=e!==Vn||s?e!==_o||s?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(i):this.pageViewManager.doPageView(i,r),a=fe(a,u),e===Vn&&P&&(a.title=P.title),!C(o)){var p=i.getTime()-o;a.$duration=parseFloat((p/1e3).toFixed(3))}Ve&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();ie(["$referrer","$referring_domain"],(b=>{b in g&&delete m[b]}));var v={};if(this._n.length>0)for(var E of this._n.slice())try{fe(v,E())}catch(b){A.error("Failed to produce browser extension event properties",b)}(a=fe({},c,g,m,I({},v,a))).$is_identified=this._isIdentified(),U(this.config.property_denylist)?ie(this.config.property_denylist,(function(b){delete a[b]})):A.error(Vf+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var S=this.config.sanitize_properties;S&&(A.error(iu),a=S(a,e));var _=this.Zn();return a.$process_person_profile=_,_&&!s&&this.Gn("_calculate_event_properties"),a}Vn(e,n,i){var r;if(n===void 0&&(n=!0),i===void 0&&(i=!1),!this.persistence||!this.Zn()||this.mn&&!i)return e;var s=this.persistence.get_initial_props(),o=(r=this.sessionPropsManager)==null?void 0:r.getSetOnceProps(),a=fe({},s,o||{},e||{}),l=this.config.sanitize_properties;return l&&(A.error(iu),a=l(a,"$set_once")),n&&(this.mn=!0),Kt(a)?void 0:a}register(e,n){var i;(i=this.persistence)==null||i.register(e,n)}register_once(e,n,i){var r;(r=this.persistence)==null||r.register_once(e,n,i)}register_for_session(e){var n;(n=this.sessionPersistence)==null||n.register(e),Object.keys(e).forEach((i=>this.yn.add(i))),this.Qn()}unregister(e){var n;(n=this.persistence)==null||n.unregister(e)}unregister_for_session(e){var n;(n=this.sessionPersistence)==null||n.unregister(e),this.yn.delete(e),this.Qn()}Kn(e,n){this.register({[e]:n})}An(){this.yn.forEach((e=>{var n;(n=this.sessionPersistence)==null||n.unregister(e)})),this.yn.clear(),this.Qn()}Qn(){var e;if(this.bn)if(this.config.persistence==="memory"||(e=this.sessionPersistence)!=null&&e.xi||!be.N())be.q(this.bn);else{var n=[];this.yn.forEach((i=>n.push(i))),n.length>0?be.F(this.bn,n):be.q(this.bn)}}getFeatureFlag(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlag(e,n)}getFeatureFlagPayload(e){var n;return(n=this.featureFlags)==null?void 0:n.getFeatureFlagPayload(e)}getFeatureFlagResult(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlagResult(e,n)}getAllFeatureFlags(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.getAllFeatureFlags())!==null&&e!==void 0?e:[]}isFeatureEnabled(e,n){var i,r;return(i=(r=this.featureFlags)==null?void 0:r.isFeatureEnabled(e,n))!==null&&i!==void 0?i:n?.defaultValue}reloadFeatureFlags(){var e;(e=this.featureFlags)==null||e.reloadFeatureFlags()}updateFlags(e,n,i){var r;(r=this.featureFlags)==null||r.updateFlags(e,n,i)}updateEarlyAccessFeatureEnrollment(e,n,i){var r;(r=this.featureFlags)==null||r.updateEarlyAccessFeatureEnrollment(e,n,i)}getEarlyAccessFeatures(e,n,i){var r;return n===void 0&&(n=!1),(r=this.featureFlags)==null?void 0:r.getEarlyAccessFeatures(e,n,i)}on(e,n){return this.dn.on(e,n)}onFeatureFlags(e){return this.featureFlags?this.featureFlags.onFeatureFlags(e):(e([],{},{errorsLoading:!0}),()=>{})}onSurveysLoaded(e){return this.surveys?this.surveys.onSurveysLoaded(e):(e([],{isLoaded:!1,error:xi}),()=>{})}onSessionId(e){var n,i;return(n=(i=this.sessionManager)==null?void 0:i.onSessionId(e))!==null&&n!==void 0?n:()=>{}}getSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getSurveys(e,n):e([],{isLoaded:!1,error:xi})}getActiveMatchingSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,n):e([],{isLoaded:!1,error:xi})}renderSurvey(e,n){var i;(i=this.surveys)==null||i.renderSurvey(e,n)}displaySurvey(e,n){var i;n===void 0&&(n=Sm),(i=this.surveys)==null||i.displaySurvey(e,n)}cancelPendingSurvey(e){var n;(n=this.surveys)==null||n.cancelPendingSurvey(e)}canRenderSurvey(e){var n,i;return(n=(i=this.surveys)==null?void 0:i.canRenderSurvey(e))!==null&&n!==void 0?n:{visible:!1,disabledReason:xi}}canRenderSurveyAsync(e,n){var i,r;return n===void 0&&(n=!1),(i=(r=this.surveys)==null?void 0:r.canRenderSurveyAsync(e,n))!==null&&i!==void 0?i:Promise.resolve({visible:!1,disabledReason:xi})}Jn(e){return!e||Ko(e)?(A.critical("Unique user id has not been set in posthog.identify"),!1):e===mr?(A.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.'),!1):!["distinct_id","distinctid"].includes(e.toLowerCase())&&!["undefined","null"].includes(e.toLowerCase())||(A.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.'),!1)}identify(e,n,i){if(!this.__loaded||!this.persistence)return A.uninitializedWarning("posthog.identify");if(ke(e)&&(e=e.toString(),A.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.Jn(e)&&this.Gn("posthog.identify")){var r=this.get_distinct_id();this.register({$user_id:e}),this.get_property(Yi)||this.register_once({$had_persisted_distinct_id:!0,$device_id:r},""),e!==r&&e!==this.get_property(Fi)&&(this.unregister(Fi),this.register({distinct_id:e}));var s,o=(this.persistence.get_property(ot)||Un)===Un,a=e!==r,l=!a&&o;if(a&&o)this.persistence.set_property(ot,vn),this.setPersonPropertiesForFlags({$set:n||{},$set_once:i||{}},!1),this.capture(yo,{distinct_id:e,$anon_distinct_id:r},{$set:n||{},$set_once:i||{}}),this.Sn=Fo(e,n,i),(s=this.featureFlags)==null||s.setAnonymousDistinctId(r);else if(l){this.persistence.set_property(ot,vn);var u=n||{},c=i||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=Fo(e,n,i)}else(n||i)&&this.setPersonProperties(n,i);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Cn)):l&&(n||i)&&this.reloadFeatureFlags()}}setPersonProperties(e,n){if((e||n)&&this.Gn("posthog.setPersonProperties")){var i=Fo(this.get_distinct_id(),e,n);this.Sn!==i?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:n||{}},!0),this.capture("$set",{$set:e||{},$set_once:n||{}}),this.Sn=i):A.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}unsetPersonProperties(e){var n,i=(U(e)?e:[e]).filter((r=>X(r)&&r.length>0));i.length!==0&&this.Gn("posthog.unsetPersonProperties")&&((n=this.featureFlags)==null||n.unsetPersonPropertiesForFlags(i,!0),this.capture("$set",{$unset:i}),this.Sn=null)}group(e,n,i){if(e&&n){var r=this.getGroups(),s=r[e]!==n;if(s&&this.resetGroupPropertiesForFlags(e),this.register({$groups:I({},r,{[e]:n})}),s||i){var o={$group_type:e,$group_key:n};i&&(o.$group_set=i),this.capture(Ac,o)}i&&this.setGroupPropertiesForFlags({[e]:i}),s&&!i&&this.reloadFeatureFlags()}else A.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),(i=this.featureFlags)==null||i.setPersonPropertiesForFlags(e,n)}resetPersonPropertiesForFlags(e){var n;e===void 0&&(e=!0),(n=this.featureFlags)==null||n.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((i=this.featureFlags)==null||i.setGroupPropertiesForFlags(e,n))}resetGroupPropertiesForFlags(e){var n;(n=this.featureFlags)==null||n.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,n){var i,r,s,o,a,l,u,c,d,h;if(n===void 0&&(n=!1),A.info("reset"),!this.__loaded)return A.uninitializedWarning("posthog.reset");var f,p=this.get_property(Yi),g=this.get_property(vo),m=this.get_property(An),v=this.is_capturing();if(this.consent.reset(),n||!v||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after."),(i=this.persistence)==null||i.clear(),(r=this.sessionPersistence)==null||r.clear(),this.yn.clear(),this.Qn(),C(m)||(f=this.persistence)==null||f.register({[An]:m}),(s=this.surveys)==null||s.reset(),(o=this.Un)==null||o.stop(),(a=this.featureFlags)==null||a.reset(),(l=this.conversations)==null||l.reset(),(u=this.logs)==null||u.reset(),(c=this.metrics)==null||c.reset(),(d=this.persistence)==null||d.set_property(ot,Un),(h=this.sessionManager)==null||h.resetSessionId(),this.Sn=null,this.config.cookieless_mode===Wt)this.register_once({distinct_id:mr,$device_id:null},"");else{var E=this.config.get_device_id(Ht());this.register_once({distinct_id:E,$device_id:e?E:p},""),e||C(g)||this.register({[vo]:g})}this.register({$last_posthog_reset:new Date().toISOString()},1),delete this.config.identity_distinct_id,delete this.config.identity_hash,this.reloadFeatureFlags()}shutdown(e){var n=this;return se((function*(){var i,r,s,o,a,l,u;if(n.__loaded){(i=n.Un)==null||i.stop(),(r=n.jn)==null||r.dispose(),(s=n.sessionRecording)==null||s.dispose(),(o=n.logs)==null||o.flushLogs("sendBeacon"),(a=n.metrics)==null||a.flush("sendBeacon"),(l=n.In)==null||l.unload(),(u=n.Rn)==null||u.unload();try{var c;(c=n.featureFlags)==null||c.destroy()}catch(d){A.error("Error while destroying feature flags",d)}}else A.uninitializedWarning("posthog.shutdown")}))()}setIdentity(e,n){var i;this.config.identity_distinct_id=e,this.config.identity_hash=n,this.alias(e),(i=this.conversations)==null||i.Xn()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,(e=this.conversations)==null||e.ts()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,n;return(e=(n=this.sessionManager)==null?void 0:n.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var n=this.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.sessionStartTimestamp,r=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+n.sessionId);if(e!=null&&e.withTimestamp&&i){var s,o=(s=e.timestampLookBack)!==null&&s!==void 0?s:10;if(!i)return r;r+="?t="+Math.max(Math.floor((new Date().getTime()-i)/1e3)-o,0)}return r}alias(e,n){return e===this.get_property(Vd)?(A.critical("Attempting to create alias for existing People user - aborting."),-2):this.Gn("posthog.alias")?(C(n)&&(n=this.get_distinct_id()),e!==n?(this.Kn(Fi,e),this.capture("$create_alias",{alias:e,distinct_id:n})):(A.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var n=I({},this.config);if(he(e)){var i,r,s,o,a,l,u,c,d,h,f,p;fe(this.config,ru(e));var g=this.En();(i=this.persistence)==null||i.update_config(this.config,n,g),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new xo(I({},this.config,{persistence:"sessionStorage"}),g,!1);var m=this.Cn(this.config.debug);mt(m)&&(this.config.debug=m),mt(this.config.debug)&&(this.config.debug?(ne.DEBUG=!0,le.N()&&le.F("ph_debug",!0),A.info("set_config",{config:e,oldConfig:n,newConfig:I({},this.config)})):(ne.DEBUG=!1,le.N()&&le.q("ph_debug"))),(r=this.featureFlags)==null||r.updateConfig==null||r.updateConfig(this.config,this.Qi()),(s=this.exceptionObserver)==null||s.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(h=this.deadClicksAutocapture)==null||h.startIfEnabledOrStop(),(f=this.surveys)==null||f.loadIfEnabled(),this.es(),(p=this.externalIntegrations)==null||p.startIfEnabledOrStop()}}_overrideSDKInfo(e,n){ne.LIB_NAME=e,ne.LIB_VERSION=n}startSessionRecording(e){var n,i,r,s,o,a=e===!0,l={sampling:a||!(e==null||!e.sampling),linked_flag:a||!(e==null||!e.linked_flag),url_trigger:a||!(e==null||!e.url_trigger),event_trigger:a||!(e==null||!e.event_trigger)};Object.values(l).some(Boolean)&&((n=this.sessionManager)==null||n.checkAndGetSessionAndWindowId(),l.sampling&&((i=this.sessionRecording)==null||i.overrideSampling()),l.linked_flag&&((r=this.sessionRecording)==null||r.overrideLinkedFlag()),l.url_trigger&&((s=this.sessionRecording)==null||s.overrideTrigger("url")),l.event_trigger&&((o=this.sessionRecording)==null||o.overrideTrigger("event"))),this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,n){if(this.exceptions){var i=new Error("PostHog syntheticException"),r=this.exceptions.buildProperties(e,{handled:!0,syntheticException:i});return this.exceptions.sendExceptionEvent(I({},r,n))}}addExceptionStep(e,n){var i;(i=this.exceptions)==null||i.addExceptionStep(e,n)}captureLog(e){var n;(n=this.logs)==null||n.captureLog(e)}get logger(){var e,n;return(e=(n=this.logs)==null?void 0:n.logger)!==null&&e!==void 0?e:Je.rs}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var n,i;return(n=(i=this.toolbar)==null?void 0:i.loadToolbar(e))!==null&&n!==void 0&&n}get_property(e){var n;return(n=this.persistence)==null?void 0:n.props[e]}getSessionProperty(e){var n;return(n=this.sessionPersistence)==null?void 0:n.props[e]}toString(){var e,n=(e=this.config.name)!==null&&e!==void 0?e:Gn;return n!==Gn&&(n=Gn+"."+n),n}_isIdentified(){var e,n;return((e=this.persistence)==null?void 0:e.get_property(ot))===vn||((n=this.sessionPersistence)==null?void 0:n.get_property(ot))===vn}Zn(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles===pa&&!this._isIdentified()&&Kt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[Fi])&&((n=this.persistence)==null||(n=n.props)==null||!n[es]))}zn(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Zn()||this.Gn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.Gn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}Gn(e){return this.config.person_profiles==="never"?(A.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Kn(es,!0),!0)}En(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut();return this.config.disable_persistence||e&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!==kn)}es(){var e,n,i,r,s=this.En();return((e=this.persistence)==null?void 0:e.xi)!==s&&((i=this.persistence)==null||i.set_disabled(s)),((n=this.sessionPersistence)==null?void 0:n.xi)!==s&&((r=this.sessionPersistence)==null||r.set_disabled(s)),s&&(this.yn.clear(),this.Qn()),s}opt_in_capturing(e){var n;if(this.config.cookieless_mode!==Wt){if(this.gn()){var i,r,s,o,a;this.Yn(!0,!0),(i=this.sessionManager)==null||i.destroy(),(r=this.pageViewManager)==null||r.destroy(),this.sessionManager=new Qc(this),this.pageViewManager=new Wc(this),this.persistence&&(this.sessionPropsManager=new Xc(this,this.sessionManager,this.persistence));var l,u=(s=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&s!==void 0?s:(a=Je.__defaultExtensionClasses)==null?void 0:a.sessionRecording;u&&(this.sessionRecording=this.pn(this.sessionRecording,new u(this)),this.hn&&((l=this.sessionRecording)==null||l.onRemoteConfig==null||l.onRemoteConfig(this.hn)))}var c,d;this.consent.optInOut(!0),this.es(),this.Bn(),(n=this.sessionRecording)==null||n.startIfEnabledOrStop(),this.config.cookieless_mode==kn&&((c=this.surveys)==null||c.loadIfEnabled()),(C(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((d=e?.captureEventName)!==null&&d!==void 0?d:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hn()}else A.warn(nu)}opt_out_capturing(){var e,n,i;this.config.cookieless_mode!==Wt?(this.config.cookieless_mode===kn&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===kn&&(this.register({distinct_id:mr,$device_id:null}),(e=this.sessionRecording)==null||e.stopRecording(),this.sessionRecording=void 0,(n=this.sessionManager)==null||n.destroy(),(i=this.pageViewManager)==null||i.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.Hn(),this.Bn())):A.warn(nu)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===Wt||(this.config.cookieless_mode===kn?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return Ue?Df(Ue,this.config.custom_blocked_useragents):void 0}Hn(){P&&(P.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(Vn,{title:P.title},{send_instantly:!0}),this.kn&&(P.removeEventListener(ts,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),ve(P,ts,this.kn)))}debug(e){e===!1?(w?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(w?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}Qi(){var e=this.Mn||{};return"advanced_disable_flags"in e?!!e.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(A.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(function(n,i,r,s,o){var a=i in n&&!H(n[i]),l=r in n&&!H(n[r]);return a?n[i]:!!l&&(o&&o.warn("Config field '"+r+"' is deprecated. Please use '"+i+"' instead. The old field will be removed in a future major version."),n[r])})(e,"advanced_disable_flags","advanced_disable_decide",0,A)}Pt(e){var n;if(H(this.config.before_send))return e;var i=Object.keys((n=e.properties)!==null&&n!==void 0?n:{}).filter(Up),r=U(this.config.before_send)?this.config.before_send:[this.config.before_send],s=e;for(var o of r){if(s=o(s),H(s)){var a="Event '"+e.event+"' was rejected in beforeSend function";return jp(e.event)?A.warn(a+". This can cause unexpected behavior."):A.info(a),null}s.properties&&!Kt(s.properties)||A.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}for(var l of i)if(s.properties&&H(s.properties[l]))return A.warn("Event '"+e.event+"' had its '"+l+"' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped."),null;return s}getPageViewId(){var e;return(e=this.pageViewManager.ui)==null?void 0:e.pageViewId}captureTraceFeedback(e,n){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:n})}captureTraceMetric(e,n,i){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:n,$ai_metric_value:String(i)})}Cn(e){var n=mt(e)&&!e,i=le.N()&&le.P("ph_debug")==="true";return!n&&(!!i||e)}}Je.__defaultExtensionClasses={},Je.rs=(()=>{var t=()=>{};return{trace:t,debug:t,info:t,warn:t,error:t,fatal:t}})(),(function(t,e){for(var n=0;e.length>n;n++)t.prototype[e[n]]=Pg(t.prototype[e[n]])})(Je,["identify"]);class su{constructor(e){this.disabled=e===!1;var n=he(e)?e:{};this.thresholdPx=n.threshold_px||30,this.timeoutMs=n.timeout_ms||1e3,this.clickCount=n.click_count||3,this.clicks=[]}isRageClick(e,n,i){if(this.disabled)return!1;var r=this.clicks[this.clicks.length-1];if(r&&Math.abs(e-r.x)+Math.abs(n-r.y)i-r.timestamp){if(this.clicks.push({x:e,y:n,timestamp:i}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:n,timestamp:i}];return!1}}var $o="$copy_autocapture",Mo=pe("[AutoCapture]");function Lo(t,e){return e.length>t?e.slice(0,t)+"...":e}function $m(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!hn(e));return e}function Mm(t,e){var n,i,r=e.e,s=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!hn(t))return{props:{}};for(var c=[t],d=new Set([t]),h=t;h.parentNode&&!Qe(h,"body")&&cf>c.length;)if(lf(h.parentNode)){var f=h.parentNode.host;if(d.has(f))break;d.add(f),c.push(f),h=f}else{if(!hn(h.parentNode)||d.has(h.parentNode))break;d.add(h.parentNode),c.push(h.parentNode),h=h.parentNode}var p,g,m=[],v={},E=!1,S=!1;if(ie(c,(x=>{var F=va(x);if(Qe(x,"a")){var $=x.getAttribute("href");E=!!(F&&$&&Ui($))&&(u?fn($):$)}j(rs(x),"ph-no-capture")&&(S=!0),m.push((function(L,N,K,V,M){M===void 0&&(M=!1);var R=L.tagName.toLowerCase(),Z={tag_name:R};ul.indexOf(R)>-1&&!K&&(Z.$el_text=R.toLowerCase()==="a"||R.toLowerCase()==="button"?Lo(1024,jc(L)):Lo(1024,Ji(L)));var Ce=rs(L);Ce.length>0&&(Z.classes=Ce.filter((function(ae){return ae!==""}))),ie(L.attributes,(function(ae){var Ie;if((!pf(L)||["name","id","class","aria-label"].indexOf(ae.name)!==-1)&&(V==null||!V.includes(ae.name))&&!N&&Ui(ae.value)&&(!X(Ie=ae.name)||Ie.substring(0,10)!=="_ngcontent"&&Ie.substring(0,7)!=="_nghost")){var Se=ae.value;ae.name==="class"&&(Se=cl(Se).join(" ")),Z["attr__"+ae.name]=Lo(1024,ae.name==="href"&&M?fn(Se):Se)}}));for(var oe=1,ye=1,$e=L;$e=$m($e);)oe++,$e.tagName===L.tagName&&ye++;return Z.nth_child=oe,Z.nth_of_type=ye,Z})(x,s,o,a,u));var O=(function(L){if(!va(L))return{};var N={};return ie(L.attributes,(function(K){if(K.name&&K.name.indexOf("data-ph-capture-attribute")===0){var V=K.name.replace("data-ph-capture-attribute-",""),M=K.value;V&&M&&Ui(M)&&(N[V]=M)}})),N})(x);fe(v,O)})),S)return{props:{},explicitNoCapture:S};if(o||(m[0].$el_text=Qe(t,"a")||Qe(t,"button")?jc(t):Ji(t)),E){var _,b;m[0].attr__href=E;var k=(_=ss(E))==null?void 0:_.host,T=w==null||(b=w.location)==null?void 0:b.host;k&&T&&k!==T&&(p=E)}return{props:fe({$event_type:r.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(x){return x.map((F=>{var $,O,L="";if(F.tag_name&&(L+=F.tag_name),F.attr_class)for(var N of(F.attr_class.sort(),F.attr_class))L+="."+N.replace(/"/g,"");var K=I({},F.text?{text:F.text}:{},{"nth-child":($=F.nth_child)!==null&&$!==void 0?$:0,"nth-of-type":(O=F.nth_of_type)!==null&&O!==void 0?O:0},F.href?{href:F.href}:{},F.attr_id?{attr_id:F.attr_id}:{},F.attributes),V={};return $r(K).sort(((M,R)=>M[0].localeCompare(R[0]))).forEach((M=>{var R=M[1];return V[Uc(M[0].toString())]=Uc(R.toString())})),(L+=":")+$r(V).map((M=>M[0]+'="'+M[1]+'"')).join("")})).join(";")})((function(x){return x.map((F=>{var $,O,L={text:($=F.$el_text)==null?void 0:$.slice(0,400),tag_name:F.tag_name,href:(O=F.attr__href)==null?void 0:O.slice(0,2048),attr_class:Kg(F),attr_id:F.attr__id,nth_child:F.nth_child,nth_of_type:F.nth_of_type,attributes:{}};return $r(F).filter((N=>N[0].indexOf("attr__")===0)).forEach((N=>L.attributes[N[0]]=N[1])),L}))})(g)))},(n=m[0])!=null&&n.$el_text?{$el_text:(i=m[0])==null?void 0:i.$el_text}:{},p&&r.type==="click"?{$external_click_url:p}:{},v)}}var Ii=pe("[ExceptionAutocapture]"),ou=()=>{},Lm=pe("[TracingHeaders]"),wn=pe("[Web Vitals]"),au=9e5,lu="disabled",cu="lazy_loading",ki="awaiting_config",Sr="missing_config";pe("[SessionRecording]"),pe("[SessionRecording]");var Ia="[SessionRecording]",Bt=pe(Ia),Nm=pe("[Heatmaps]");function No(t){return he(t)&&"clientX"in t&&"clientY"in t&&ke(t.clientX)&&ke(t.clientY)}var xr=pe("[Product Tours]"),Oo=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(sl))},Om=["$set_once","$set"],Et=pe("[SiteApps]"),uu="Error while initializing PostHog app with config id ";function qn(t,e,n){if(H(t))return!1;switch(n){case"exact":return t===e;case"contains":var i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(i,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}class Bm{constructor(e){this.ns=new pl,this.ss=(n,i)=>this.os(n,i)&&this.ls(n,i)&&this.us(n,i)&&this.hs(n,i),this.os=(n,i)=>i==null||!i.event||n?.event===i?.event,this._instance=e,this.ds=new Set,this.vs=new Set}init(){var e,n;C((e=this._instance)==null?void 0:e._addCaptureHook)||(n=this._instance)==null||n._addCaptureHook(((i,r)=>{this.on(i,r)}))}register(e){var n,i;if(!C((n=this._instance)==null?void 0:n._addCaptureHook)&&(e.forEach((o=>{var a,l;(a=this.vs)==null||a.add(o),(l=o.steps)==null||l.forEach((u=>{var c;(c=this.ds)==null||c.add(u?.event||"")}))})),(i=this._instance)!=null&&i.autocapture)){var r,s=new Set;e.forEach((o=>{var a;(a=o.steps)==null||a.forEach((l=>{l!=null&&l.selector&&s.add(l?.selector)}))})),(r=this._instance)==null||r.autocapture.setElementSelectors(s)}}on(e,n){var i;n!=null&&e.length!=0&&(this.ds.has(e)||this.ds.has(n.event))&&this.vs&&((i=this.vs)==null?void 0:i.size)>0&&this.vs.forEach((r=>{this.cs(n,r)&&this.ns.emit("actionCaptured",r.name)}))}fs(e){this.onAction("actionCaptured",(n=>e(n)))}cs(e,n){if(n?.steps==null)return!1;for(var i of n.steps)if(this.ss(e,i))return!0;return!1}onAction(e,n){return this.ns.on(e,n)}ls(e,n){if(n!=null&&n.url){var i,r=e==null||(i=e.properties)==null?void 0:i.$current_url;if(!r||typeof r!="string"||!qn(r,n.url,n.url_matching||"contains"))return!1}return!0}us(e,n){return!!this.ps(e,n)&&!!this.gs(e,n)&&!!this.ys(e,n)}ps(e,n){var i;if(n==null||!n.href)return!0;var r=this.bs(e);if(r.length>0)return r.some((a=>qn(a.href,n.href,n.href_matching||"exact")));var s,o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!o&&qn((s=o.match(/(?::|")href="(.*?)"/))?s[1]:"",n.href,n.href_matching||"exact")}gs(e,n){var i;if(n==null||!n.text)return!0;var r=this.bs(e);if(r.length>0)return r.some((u=>qn(u.text,n.text,n.text_matching||"exact")||qn(u.$el_text,n.text,n.text_matching||"exact")));var s,o,a,l=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!l&&(s=(function(u){for(var c,d=[],h=/(?::|")text="(.*?)"/g;!H(c=h.exec(u));)d.includes(c[1])||d.push(c[1]);return d})(l),o=n.text,a=n.text_matching||"exact",s.some((u=>qn(u,o,a))))}ys(e,n){var i,r;if(n==null||!n.selector)return!0;var s=e==null||(i=e.properties)==null?void 0:i.$element_selectors;if(s!=null&&s.includes(n.selector))return!0;var o=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";if(n.selector_regex&&o)try{return new RegExp(n.selector_regex).test(o)}catch{return!1}return!1}bs(e){var n;return(e==null||(n=e.properties)==null?void 0:n.$elements)==null?[]:e?.properties.$elements}hs(e,n){return n==null||!n.properties||n.properties.length===0||Hf(n.properties.reduce(((i,r)=>{var s=U(r.value)?r.value.map(String):r.value!=null?[String(r.value)]:[];return i[r.key]={values:s,operator:r.operator||"exact"},i}),{}),e?.properties)}}class Dm{constructor(e){var n;this._s=[],this._instance=e,this.ws=new Map,this.ks=new Map,this.xs=new Map,(n=this._instance)==null||n.onSessionId==null||n.onSessionId((i=>this.Ss(i)))}Cs(e){return!1}Ms(){return null}Ts(e){}Es(){}Is(e,n){return!!e&&Hf(e.propertyFilters,n?.properties)}Ps(e,n){var i=new Map;return e.forEach((r=>{var s;(s=r.conditions)==null||(s=s[n])==null||(s=s.values)==null||s.forEach((o=>{if(o!=null&&o.name){var a=i.get(o.name)||[];a.push(r.id),i.set(o.name,a)}}))})),i}Rs(e,n,i){var r=(i===wi.Activation?this.ws:this.ks).get(e),s=[];return this.As((o=>{s=o.filter((a=>r?.includes(a.id)))})),s.filter((o=>{var a,l=(a=o.conditions)==null||(a=a[i])==null||(a=a.values)==null?void 0:a.find((u=>u.name===e));return this.Is(l,n)}))}register(e){var n;C((n=this._instance)==null?void 0:n._addCaptureHook)||(this.Fs(e),this.Ls(e))}Ls(e){var n=e.filter((i=>{var r,s;return((r=i.conditions)==null?void 0:r.actions)&&((s=i.conditions)==null||(s=s.actions)==null||(s=s.values)==null?void 0:s.length)>0}));n.length!==0&&(this.Os==null&&(this.Os=new Bm(this._instance),this.Os.init(),this.Os.fs((i=>{this.onAction(i)}))),n.forEach((i=>{var r,s,o,a,l;i.conditions&&(r=i.conditions)!=null&&r.actions&&(s=i.conditions)!=null&&(s=s.actions)!=null&&s.values&&((o=i.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.Os)==null||a.register(i.conditions.actions.values),(l=i.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var c=this.xs.get(u.name);c&&c.push(i.id),this.xs.set(u.name,c||[i.id])}})))})))}Fs(e){var n,i=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.events)&&((a=s.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0})),r=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.cancelEvents)&&((a=s.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0}));i.length===0&&r.length===0||((n=this._instance)==null||n._addCaptureHook(((s,o)=>{this.onEvent(s,o)})),this.ws=this.Ps(e,wi.Activation),this.ks=this.Ps(e,wi.Cancellation))}onEvent(e,n){var i,r,s=this.Ds(),o=(n==null||(i=n.properties)==null?void 0:i.$survey_id)||(n==null||(r=n.properties)==null?void 0:r.$product_tour_id);if(o&&this.getActivatedIds().includes(o)){var a=this.$s(e,o);if(a==="consume")return s.info("event consumed activated item, removing it",{event:e,itemId:o}),void this.Ns([o]);if(a==="persist")return s.info("shown item promoted to persisted activation",{event:e,itemId:o}),this.qs(o),void this.js([o])}if(this.ks.has(e)){var l=this.Rs(e,n,wi.Cancellation);l.length>0&&(s.info("cancel event matched, cancelling items",{event:e,itemsToCancel:l.map((c=>c.id))}),this.Ns(l.map((c=>c.id))),l.forEach((c=>this.Bs(c.id))))}if(this.ws.has(e)){s.info("event name matched",{event:e,eventPayload:n,items:this.ws.get(e)});var u=this.Rs(e,n,wi.Activation);this.Hs(u.map((c=>c.id)))}}onAction(e){this.xs.has(e)&&this.Hs(this.xs.get(e)||[])}Hs(e){var n;if(e.length!==0){var i=!((n=this._instance)==null||n.get_session_id==null||!n.get_session_id()),r=[];for(var s of e)i&&this.Cs(s)?this.qs(s)&&this.Us(s):r.push(s);r.length>0&&(this._s=[...new Set([...this._s,...r])]),this.Ds().info("updating activated items",{activatedItems:this.getActivatedIds()})}}qs(e){this._s=this._s.filter((i=>i!==e));var n=this.zs();return!n.includes(e)&&(this.Ws([...n,e]),this.Vs(),!0)}Ns(e){var n=new Set(e);this._s=this._s.filter((s=>!n.has(s)));var i=this.Zs(),r=i.filter((s=>!n.has(s)));r.length!==i.length&&(this.Ws(r),r.length===0&&this.Gs()),this.js(e)}Qs(){var e,n=this.Ms();if(!n)return{};var i=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n];return i&&typeof i=="object"?i:{}}Us(e){if(this.Ms()){var n=this.Qs();this.Ts(I({},n,{[e]:Date.now()}))}}js(e){if(this.Ms()){var n=this.Qs(),i={},r=!1;for(var s of Object.entries(n)){var o=s[0],a=s[1];e.includes(o)?r=!0:i[o]=a}r&&(Kt(i)?this.Es():this.Ts(i))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var n=this.Qs()[e];return ke(n)?n:void 0}}Zs(){var e,n=this.Js();return((e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n])||[]}zs(){var e,n,i=this.Zs();if(i.length===0)return[];var r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[this.Ys()],s=(n=this._instance)==null||n.get_session_id==null?void 0:n.get_session_id();return s&&r===s?i:[]}Vs(){var e,n=(e=this._instance)==null||e.get_session_id==null?void 0:e.get_session_id();n&&this.Xs(n)}Gs(){this.ta()}Ss(e){var n,i=(n=this._instance)==null||(n=n.persistence)==null?void 0:n.props[this.Ys()];if(i&&i!==e){var r=this.Zs(),s=this.Qs();r.length>0&&(this.Ws([]),r.filter((o=>ke(s[o]))).forEach((o=>this.Bs(o)))),this.Gs(),this.Ks()}}getActivatedIds(){return[...new Set([...this.zs(),...this._s])].filter((e=>!this.ea(e)))}reset(){this._s=[],this.Zs().length>0&&this.Ws([]),this.Gs(),this.Ks()}getEventToItemsMap(){return this.ws}ia(){return this.Os}}class jm extends Dm{constructor(e){super(e)}Js(){return ca}Ys(){return Fr}Ms(){return Rr}Ts(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Rr]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Rr)}Cs(e){var n,i;this.As((s=>{i=s.find((o=>o.id===e))}));var r=(n=i)==null||(n=n.appearance)==null?void 0:n.surveyPopupDelaySeconds;return ke(r)&&r>0}ra(){return zt.SHOWN}As(e){var n;(n=this._instance)==null||n.getSurveys(e)}Bs(e){var n;(n=this._instance)==null||n.cancelPendingSurvey(e)}Ds(){return Q}Ws(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[ca]:e})}Xs(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Fr]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Fr)}ea(){return!1}$s(e,n){var i;this.As((s=>{i=s.find((o=>o.id===n))}));var r=!i||(function(s){var o;return Wf(s)&&!((o=s.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||s.schedule==="always"})(i);return r?e===zt.SHOWN?"consume":"ignore":e===zt.SHOWN?"persist":e===zt.DISMISSED||e===zt.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var Ir="SDK is not enabled or survey functionality is not yet loaded",du="Disabled. Not loading surveys.",Um=w!=null&&w.location?os(w.location.hash,"__posthog")||os(location.hash,"state"):null,fu="_postHogToolbarParams",hu=pe("[Toolbar]"),pu=pe("[FeatureFlags]");class Hm{constructor(e,n){n===void 0&&(n=!1),this.na=!1,this.update(e,n)}update(e,n){this.sa=((i,r)=>{var s,o,a,l;return{bootstrap:{featureFlags:(s=i.bootstrap)==null?void 0:s.featureFlags,featureFlagPayloads:(o=i.bootstrap)==null?void 0:o.featureFlagPayloads},remoteRequestsDisabled:r,featureFlagsDisabled:!!i.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!i.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!i.advanced_feature_flags_dedup_per_session,cacheTtlMs:i.feature_flag_cache_ttl_ms,requestTimeoutMs:i.feature_flag_request_timeout_ms,compression:i.disable_compression?"none":"base64",evaluationContexts:(a=(l=i.evaluation_contexts)!==null&&l!==void 0?l:i.evaluation_environments)!==null&&a!==void 0?a:[],flagKeys:U(i.flag_keys)?i.flag_keys:void 0}})(e,n),!e.evaluation_environments||e.evaluation_contexts||this.na||(pu.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.na=!0),C(e.flag_keys)||U(e.flag_keys)||pu.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var gu=pe("[FeatureFlags]"),bn=pe("[FeatureFlags]",{debugEnabled:!0}),Bo=`" failed. Feature flags didn't load in time.`,mu="connection_error",vu=t=>{for(var e={},n=0;t.length>n;n++)e[t[n]]=!0;return e},_u=t=>{var e={};for(var n of $r(t||{})){var i=n[1];i&&(e[n[0]]=i)}return e},St=pe("[Error tracking]"),yu="Refusing to render web experiment since the viewer is a likely bot",Wm={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>cs(e,t),not_regex:(t,e)=>!cs(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class Me{get Ne(){return this._instance.config}constructor(e){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(i){i===void 0&&(i=!1),n.getWebExperiments((r=>{Me.aa("retrieved web experiments from the server"),n.oa=new Map,r.forEach((s=>{if(s.feature_flag_key){var o;n.oa&&(Me.aa("setting flag key ",s.feature_flag_key," to web experiment ",s),(o=n.oa)==null||o.set(s.feature_flag_key,s));var a=n._instance.getFeatureFlag(s.feature_flag_key);X(a)&&s.variants[a]&&n.la(s.name,a,s.variants[a].transforms)}else if(s.variants)for(var l in s.variants){var u=s.variants[l];Me.ua(u,n._instance)&&n.la(s.name,l,u.transforms)}}))}),i)},this._instance=e,this._instance.onFeatureFlags((i=>{this.onFeatureFlags(i)}))}initialize(){}onFeatureFlags(e){if(this._is_bot())Me.aa(yu);else if(!this.Ne.disable_web_experiments){if(H(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();Me.aa("applying feature flags",e),e.forEach((n=>{var i;if(this.oa&&(i=this.oa)!=null&&i.has(n)){var r,s=this._instance.getFeatureFlag(n),o=(r=this.oa)==null?void 0:r.get(n);s&&o!=null&&o.variants[s]&&this.la(o.name,s,o.variants[s].transforms)}}))}}previewWebExperiment(){var e=Me.getWindowLocation();if(e!=null&&e.search){var n=ii(e?.search,"__experiment_id"),i=ii(e?.search,"__experiment_variant");n&&i&&(Me.aa("previewing web experiments "+n+" && "+i),this.getWebExperiments((r=>{this.ha(parseInt(n),i,r)}),!1,!0))}}loadIfEnabled(){this.Ne.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,n,i){if(this.Ne.disable_web_experiments&&!i)return e([]);var r=this._instance.get_property("$web_experiments");if(r&&!n)return e(r);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this.Ne.token),method:"GET",timestampMode:"query",callback:s=>e(s.statusCode===200&&s.json&&s.json.experiments||[])})}ha(e,n,i){var r=i.filter((s=>s.id===e));r&&r.length>0&&(Me.aa("Previewing web experiment ["+r[0].name+"] with variant ["+n+"]"),this.la(r[0].name,n,r[0].variants[n].transforms))}static ua(e,n){return!H(e.conditions)&&Me.da(e,n)&&Me.va(e)}static da(e,n){var i;if(H(e.conditions)||H((i=e.conditions)==null?void 0:i.url))return!0;var r=Me.getWindowLocation();if(r){var s,o,a,l=sf(n,r.href);return(s=e.conditions)==null||!s.url||Wm[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return w?.location}static va(e){var n;if(H(e.conditions)||H((n=e.conditions)==null?void 0:n.utm))return!0;var i=wf();if(i.utm_source){var r,s,o,a,l,u,c,d,h=(r=e.conditions)==null||(r=r.utm)==null||!r.utm_campaign||((s=e.conditions)==null||(s=s.utm)==null?void 0:s.utm_campaign)==i.utm_campaign,f=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==i.utm_source,p=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==i.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==i.utm_term;return h&&p&&g&&f}return!1}static aa(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;n>r;r++)i[r-1]=arguments[r];A.info("[WebExperiments] "+e,i)}la(e,n,i){this._is_bot()?Me.aa(yu):n!=="control"?i.forEach((r=>{if(r.selector){var s;Me.aa("applying transform of variant "+n+" for experiment "+e+" ",r);var o=(s=document)==null?void 0:s.querySelectorAll(r.selector);o?.forEach((a=>{var l=a;r.html&&(l.innerHTML=r.html),r.css&&l.setAttribute("style",r.css)}))}})):Me.aa("Control variants leave the page unmodified.")}_is_bot(){return Ue&&this._instance?Df(Ue,this.Ne.custom_blocked_useragents):void 0}}var st=pe("[Conversations]"),En="Conversations not available yet.",wu="console",Kf="__posthogHandledLogsRequestError",Do=(t,e)=>{var n=t instanceof Error?t:new Error(e);return n[Kf]=!0,n},bu=t=>!!t&&typeof t=="object"&&t[Kf]===!0,Cs={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=gu,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 Hm(t.config,t.Qi()),this.Ta=this.Ea)}updateConfig(t,e){var n;(n=this.Ea)==null||n.update(t,e)}setup(t){return this.Ia=t,this.rt=t.logger.createLogger("[FeatureFlags]"),n=()=>{this.Ia===t&&(this.Ia=void 0,this.nn=t,this.Pa(t))},(e=t.kv.initialize())!=null&&e.then?e.then(n):n();var e,n}Pa(t){if(this.nn===t)return w&&ve(w,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){w?.removeEventListener("online",this.Ca)}dispose(){var t;this.ba++,this.wa=!1,this.Ia=void 0,this.nn&&(this.La(),(t=this.Ra)==null||t.dispose(),this.Ra=void 0,this.ga=[],w?.removeEventListener("online",this.Ca),this.nn=void 0)}get Ne(){return this.Ta.get()}Oa(t){var e;return(e=this.nn)==null?void 0:e.kv.get(t)}F(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.set(t)}))}q(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.remove(t)}))}Da(t){try{t()}catch(e){this.rt.error("Failed to update feature flag persistence",e)}}Fa(){var t={};for(var e of[Ti,$i,Pr,It]){var n=this.Oa(e);C(n)||(t[e]=n)}this.fa=t;var i=I({},t),r=this.Oa(Sn);if(r)for(var s of Object.entries(r))i["$feature/"+s[0]]=s[1];this.pa=i}Aa(){var t=this.Ne.cacheTtlMs;if(!t||0>=t)return!1;var e=this.Oa(ji);return typeof e!="number"||Date.now()-e>t}$a(){return!!this.Aa()&&(this.xa||this.ya||(this.xa=!0,this.rt.warn("Feature flag cache is stale, triggering refresh..."),this.reloadFeatureFlags()),!0)}Na(){var t=this.Ne.evaluationContexts;return t!=null&&t.length?t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid evaluation context found:",e,"Expected non-empty string"),n})):[]}qa(){var t=this.Ne.flagKeys;if(!C(t))return t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid flag key found:",e,"Expected non-empty string"),n}))}initialize(){var t,e,n=this.Ne,i=(t=(e=n.bootstrap)==null?void 0:e.featureFlags)!==null&&t!==void 0?t:{};if(Object.keys(i).length){var r,s,o=(r=(s=n.bootstrap)==null?void 0:s.featureFlagPayloads)!==null&&r!==void 0?r:{},a=Object.keys(i).filter((u=>!!i[u])).reduce(((u,c)=>(u[c]=i[c]||!1,u)),{}),l=Object.keys(o).filter((u=>a[u])).reduce(((u,c)=>(o[c]&&(u[c]=o[c]),u)),{});return this.ja({featureFlags:a,featureFlagPayloads:l})}}updateFlags(t,e,n){var i,r,s=n!=null&&n.merge&&(i=this.Oa(Sn))!==null&&i!==void 0?i:{},o=n!=null&&n.merge&&(r=this.Oa($i))!==null&&r!==void 0?r:{},a=I({},s,t),l=I({},o,e),u={};for(var c of Object.entries(a)){var d=c[0],h=c[1];u[d]={key:d,enabled:hc(h),variant:pc(h),reason:void 0,metadata:C(l?.[d])?void 0:{id:0,version:void 0,description:void 0,payload:l[d]}}}this.ja({flags:u})}get hasLoadedFlags(){return this.ma}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var t=this.Oa(aa),e=this.Oa(It),n=this.Oa(xn);if(!n&&!e)return t||{};var i=fe({},t||{}),r=[...new Set([...Object.keys(n||{}),...Object.keys(e||{})])];for(var s of r){var o,a,l=i[s],u=e?.[s],c=C(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=C(u)?l?.variant:typeof u=="string"?u:void 0,h=n?.[s],f=I({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(f.original_enabled=l?.enabled),d!==l?.variant&&(f.original_variant=l?.variant),h&&(f.metadata=I({},l?.metadata,{payload:h,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),i[s]=f}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:n,finalDetails:i}),this.ca=!0),i}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((n=>{var i=t[n];return{key:n,enabled:hc(i),variant:pc(i),payload:fc(e[n])}}))}getFlagVariants(){var t=this.Oa(Sn),e=this.Oa(It);if(!e)return t||{};for(var n=fe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:e,finalFlags:n}),this.ca=!0),n}getFlagPayloads(){var t=this.Oa($i),e=this.Oa(xn);if(!e)return t||{};for(var n=fe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flag payloads!",{flagPayloads:t,overriddenPayloads:e,finalPayloads:n}),this.ca=!0),n}reloadFeatureFlags(){this._a||this.Ne.featureFlagsDisabled||this.Ma()||this.Ba||(this.ga.slice().forEach((t=>{try{t()}catch(e){this.rt.error("Error while running feature flags reloading callback",e)}})),this.Ba=setTimeout((()=>{this.Ha()}),5))}La(){clearTimeout(this.Ba),this.Ba=void 0}onReloading(t){return this.ga.push(t),()=>{this.ga=this.ga.filter((e=>e!==t))}}ensureFlagsLoaded(){this.ma||this.ya||this.Ba||this.reloadFeatureFlags()}setAnonymousDistinctId(t){this.$anon_distinct_id=t}setReloadingPaused(t){this._a=t}resetFlagCallReported(){this.q(Cn)}Ha(t){this.La();var e=this.nn;if(e&&!this.Ne.remoteRequestsDisabled&&!this.Ma())if(this.ya)this.wa=!0;else{var n={token:e.projectToken,distinct_id:e.distinctId,groups:e.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:I({},e.initialPersonProperties,this.Oa(jt)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(In),timezone:kf()};C(e.deviceId)||(n.$device_id=e.deviceId),(t!=null&&t.disableFlags||this.Ne.featureFlagsDisabled)&&(n.disable_flags=!0);var i=this.Na();i.length&&(n.evaluation_contexts=i);var r=this.qa();C(r)||(n.flag_keys=r);var s=this.Ne.onlyEvaluateSurveyFeatureFlags,o="/flags/?v=2"+(s?"&only_evaluate_survey_feature_flags=true":""),a=this.ba;this.ya=!0;var l=()=>{this.wa&&(this.wa=!1,this.Ha())},u=c=>{this.ya=!1,a===this.ba&&(this.F({[Tr]:[mu]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:n,compression:this.Ne.compression==="base64"?je.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,h,f=(d=c.json)!==null&&d!==void 0?d:{},p=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),p||this.wa||(this.$anon_distinct_id=void 0),!n.disable_flags||this.wa){this.ka=!p;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?mu:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),f.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((h=f.quotaLimited)==null||!h.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[Tr]:g}),m?this.rt.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more."):n.disable_flags||this.ja(f,p,{partialResponse:s}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return _f(this.Sa,3)}Ua(t){this.Sa=yf(t,this.Sa,3,(()=>this.rt.warn("Feature flag requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped refreshing feature flags; will try again when connectivity changes.")))}getFeatureFlag(t,e){var n;if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var i=this.getFeatureFlagResult(t,e);return(n=i?.variant)!==null&&n!==void 0?n:i?.enabled}}else this.rt.warn('getFeatureFlag for key "'+t+Bo)}getFeatureFlagDetails(t){return this.getFlagsWithDetails()[t]}getFeatureFlagPayload(t){var e=this.getFeatureFlagResult(t,{send_event:!1});return e?.payload}getFeatureFlagResult(t,e){if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var n,i=this.getFlagVariants(),r=t in i,s=i[t],o=this.getFlagPayloads()[t],a=String(s),l=this.Oa(Pr)||void 0,u=this.Oa(ji)||void 0,c=this.Oa(Cn)||{};if(this.Ne.deduplicateCallsPerSession){var d,h=(d=this.nn)==null?void 0:d.session.sessionId,f=this.Oa(Li);h&&h!==f&&(c={},n=h)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))n&&this.F({[Cn]:c,[Li]:n});else{var p,g,m,v,E,S,_,b,k,T;U(c[t])?c[t].push(a):c[t]=[a],this.F(I({[Cn]:c},n?{[Li]:n}:{}));var x=this.getFeatureFlagDetails(t),F=[...(p=this.Oa(Tr))!==null&&p!==void 0?p:[]];C(s)&&F.push("flag_missing");var $={$feature_flag:t,$feature_flag_response:s,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((g=this.Ne.bootstrap)==null||(g=g.featureFlags)==null?void 0:g[t])||null,$feature_flag_bootstrapped_payload:((m=this.Ne.bootstrap)==null||(m=m.featureFlagPayloads)==null?void 0:m[t])||null,$used_bootstrap_value:!this.ka};C(x==null||(v=x.metadata)==null?void 0:v.has_experiment)||($.$feature_flag_has_experiment=x.metadata.has_experiment),C(x==null||(E=x.metadata)==null?void 0:E.version)||($.$feature_flag_version=x.metadata.version);var O,L=(S=x==null||(_=x.reason)==null?void 0:_.description)!==null&&S!==void 0?S:x==null||(b=x.reason)==null?void 0:b.code;L&&($.$feature_flag_reason=L),x!=null&&(k=x.metadata)!=null&&k.id&&($.$feature_flag_id=x.metadata.id),C(x?.original_variant)&&C(x?.original_enabled)||($.$feature_flag_original_response=C(x.original_variant)?x.original_enabled:x.original_variant),x!=null&&(T=x.metadata)!=null&&T.original_payload&&($.$feature_flag_original_payload=x==null||(O=x.metadata)==null?void 0:O.original_payload),F.length&&($.$feature_flag_error=F.join(",")),this.za($)}else n&&this.F({[Cn]:c,[Li]:n});if(r)return{key:t,enabled:!!s,variant:typeof s=="string"?s:void 0,payload:fc(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+Bo)}za(t){try{var e;(e=this.nn)==null||e.capture("$feature_flag_called",t).catch((n=>{this.rt.error("Failed to capture feature flag call",n)}))}catch(n){this.rt.error("Failed to capture feature flag call",n)}}getRemoteConfigPayload(t,e){this.Wa(t,e)}Wa(t,e){var n=this;return se((function*(){var i=n.nn;if(i){var r={distinct_id:i.distinctId,token:i.projectToken,person_properties:{$lib:i.library.name,$lib_version:i.library.version}},s=n.Na();s.length&&(r.evaluation_contexts=s);var o,a=n.qa();C(a)||(r.flag_keys=a);try{var l,u=(l=(yield i.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:r,compression:n.Ne.compression==="base64"?je.Base64:void 0,sentAt:"body",timeoutMs:n.Ne.requestTimeoutMs})).json)==null?void 0:l.featureFlagPayloads;o=u?.[t]||void 0}catch(c){return void n.rt.error("Remote config feature flag request failed",c)}try{e(o)}catch(c){n.rt.error("Remote config feature flag callback failed",c)}}}))()}isFeatureEnabled(t,e){if(e===void 0&&(e={}),e.fresh&&!this.ka)return e.defaultValue;if(!(this.ma||this.getFlags()&&this.getFlags().length>0))return this.rt.warn('isFeatureEnabled for key "'+t+Bo),e.defaultValue;var n=this.getFeatureFlag(t,e);return C(n)?e.defaultValue:!!n}addFeatureFlagsHandler(t){this.featureFlagEventHandlers.push(t)}removeFeatureFlagsHandler(t){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((e=>e!==t))}receivedFeatureFlags(t,e,n){this.ja(t,e,n)}ja(t,e,n){if(this.nn){this.ma=!0;var i=(function(r,s,o,a,l,u){s===void 0&&(s={}),o===void 0&&(o={}),a===void 0&&(a={}),u===void 0&&(u=gu);var c=((k,T)=>{var x=k.flags;return x?I({},k,{featureFlags:Object.fromEntries(Object.keys(x).map((F=>{var $;return[F,($=x[F].variant)!==null&&$!==void 0?$:x[F].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(x).filter((F=>x[F].enabled)).filter((F=>{var $;return($=x[F].metadata)==null?void 0:$.payload})).map((F=>{var $;return[F,($=x[F].metadata)==null?void 0:$.payload]})))}):(k.featureFlags&&T.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),k)})(r,u),d=c.flags,h=c.featureFlags,f=c.featureFlagPayloads;if(h){var p=r.requestId,g=r.evaluatedAt;if(U(h)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(h)for(var v=0;h.length>v;v++)m[h[v]]=!0;return{[Ti]:h,[Sn]:m,[Zr]:!1}}var E=h,S=f,_=d;if(l!=null&&l.partialResponse)E=I({},s,E),S=I({},o,S),_=I({},a,_);else if(r.errorsWhileComputingFlags)if(d){var b=new Set(Object.keys(d).filter((k=>{var T;return!((T=d[k])!=null&&T.failed)})));E=I({},s,Object.fromEntries(Object.entries(E).filter((k=>b.has(k[0]))))),S=I({},o,Object.fromEntries(Object.entries(S||{}).filter((k=>b.has(k[0]))))),_=I({},a,Object.fromEntries(Object.entries(_||{}).filter((k=>b.has(k[0])))))}else E=I({},s,E),S=I({},o,S),_=I({},a,_);return I({[Ti]:Object.keys(_u(E)),[Sn]:E||{},[$i]:S||{},[aa]:_||{},[Zr]:r.minimalFlagCalledEvents===!0},p?{[Pr]:p}:{},g?{[ji]:g}:{})}})(t,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),n,this.rt);i&&this.F(i),e||(this.xa=!1),this.Va(e)}}override(t,e){e===void 0&&(e=!1),this.rt.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:t,suppressWarning:e})}overrideFeatureFlags(t){this.Za(t)}Za(t){if(this.nn){if(t===!1)return this.q([It,xn]),this.Va(),void bn.info("All overrides cleared");if(U(t))return this.F({[It]:vu(t)}),this.Va(),void bn.info("Flag overrides set",{flags:t});if(t&&typeof t=="object"&&("flags"in t||"payloads"in t)){var e,n=t;this.ca=!!((e=n.suppressWarning)!==null&&e!==void 0&&e);var i={},r=n.flags,s=n.payloads;return r&&(i[It]=U(r)?vu(r):r),s&&(i[xn]=s),Object.keys(i).length&&this.F(i),r===!1&&s===!1?this.q([It,xn]):r===!1?this.q(It):s===!1&&this.q(xn),this.Va(),r===!1?bn.info("Flag overrides cleared"):r&&bn.info("Flag overrides set",{flags:r}),void(s===!1?bn.info("Payload overrides cleared"):s&&bn.info("Payload overrides set",{payloads:s}))}if(t&&typeof t=="object")return this.F({[It]:t}),this.Va(),void bn.info("Flag overrides set",{flags:t});this.rt.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:t})}else this.rt.warn("posthog.featureFlags.overrideFeatureFlags called before feature flags were ready")}onFeatureFlags(t){if(this.addFeatureFlagsHandler(t),this.ma){var e=this.Ga(),n=e.flags,i=e.flagVariants;try{t(n,i)}catch(r){this.rt.error("Error while running feature flags callback",r)}}return()=>this.removeFeatureFlagsHandler(t)}updateEarlyAccessFeatureEnrollment(t,e,n){var i=(this.Oa(Ar)||[]).find((l=>l.flagKey===t)),r={["$feature_enrollment/"+t]:e},s={$feature_flag:t,$feature_enrollment:e,$set:r};i&&(s.$early_access_feature_name=i.name),n&&(s.$feature_enrollment_stage=n);var o=I({},this.getFlagVariants(),{[t]:e});this.F({[Ti]:Object.keys(_u(o)),[Sn]:o,[jt]:I({},this.Oa(jt)||{},r)}),this.Va();try{var a;(a=this.nn)==null||a.capture("$feature_enrollment_update",s).catch((l=>{this.rt.error("Failed to capture early access feature enrollment",l)}))}catch(l){this.rt.error("Failed to capture early access feature enrollment",l)}}getEarlyAccessFeatures(t,e,n){e===void 0&&(e=!1);var i=this.Oa(Ar);!i||e?this.Qa(t,n):t(i)}Qa(t,e){var n=this;return se((function*(){var i=n.nn;if(i){var r,s=e?"&"+e.map((a=>"stage="+a)).join("&"):"";try{var o=yield i.sendRequest("/api/early_access_features/?token="+i.projectToken+s,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;n.F({[Ar]:r=o.json.earlyAccessFeatures})}catch(a){return void n.rt.error("Early access feature request failed",a)}try{t(r)}catch(a){n.rt.error("Early access feature callback failed",a)}}}))()}Ga(){var t=this.getFlags(),e=this.getFlagVariants();return{flags:t.filter((n=>e[n])),flagVariants:Object.keys(e).filter((n=>e[n])).reduce(((n,i)=>(n[i]=e[i],n)),{})}}Va(t){this.Fa();var e=this.Ga(),n=e.flags,i=e.flagVariants;this.featureFlagEventHandlers.forEach((r=>{try{r(n,i,{errorsLoading:t})}catch(s){this.rt.error("Error while running feature flags callback",s)}}))}setPersonPropertiesForFlags(t,e){e===void 0&&(e=!0),this.Ka(t,e)}Ka(t,e){e===void 0&&(e=!0);var n=this.Oa(jt)||{},i=t?.$set||(t!=null&&t.$set_once?{}:t),r=t?.$set_once,s={};if(r)for(var o in r)({}).hasOwnProperty.call(r,o)&&(o in n||(s[o]=r[o]));this.F({[jt]:I({},n,s,i)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=I({},this.Oa(jt)||{});t.forEach((i=>{delete n[i]})),this.F({[jt]:n}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(jt),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=this.Oa(In)||{},i=I({},n);for(var r of Object.keys(t))i[r]=I({},n[r],t[r]);this.F({[In]:i}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(In)||{};this.F({[In]:I({},e,{[t]:{}})})}else this.q(In)}reset(){this.ba++,this.wa=!1,this.Fa(),this.ma=!1,this._a=!1,this.ka=!1,this.$anon_distinct_id=void 0,this.La(),this.ca=!1,this.Sa=0}}},qm={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===ki||this.Ya===Sr?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=lu,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(P==null||!P.visibilityState||P.visibilityState==="visible")return!0;var n=w==null||(e=w.performance)==null||e.getEntriesByType==null?void 0:e.getEntriesByType("visibility-state");return!(n!=null&&n.length)||n.some((i=>i.name==="visible"))})(),this.Ie=()=>{var e;P?.visibilityState==="visible"&&(this.io=!0,(e=this.Ja)==null||e.setDocumentWasEverVisible==null||e.setDocumentWasEverVisible(!0))},this._instance=t,!this._instance.sessionManager)throw Bt.error("started without valid sessionManager"),new Error(Ia+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===Wt)throw new Error(Ia+' cannot be used with cookieless_mode="always"');P!=null&&P.addEventListener&&ve(P,"visibilitychange",this.Ie)}initialize(){this.startIfEnabledOrStop()}dispose(){this.eo=!0,P==null||P.removeEventListener==null||P.removeEventListener("visibilitychange",this.Ie),this.stopRecording()}get ro(){var t,e=!((t=this._instance.get_property(An))==null||!t.enabled),n=!this.Ne.disable_session_recording,i=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return w&&e&&n&&!i}startIfEnabledOrStop(t){var e;if(!(this.eo||this.ro&&(e=this.Ja)!=null&&e.isStarted)){var n=!C(Object.assign)&&!C(Array.from);this.ro&&n?(this.no(t),Bt.info("starting")):(this.Ya=lu,this.stopRecording())}}no(t){var e,n,i;this.ro&&(this.Ya!==ki&&this.Ya!==Sr&&(this.Ya=cu),B!=null&&(e=B.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(n=B.__PosthogExtensions__)!=null&&n.initSessionRecording?this.so(t):(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,this.ao,(r=>{if(r)return Bt.error("could not load recorder",r);this.so(t)})))}stopRecording(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.stop()}oo(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.discard()}lo(){var t,e;(t=this.Mr)==null||t.unregister(ol),(e=this.Mr)==null||e.unregister(Gd)}uo(t,e){if(H(t))return null;var n,i=ke(t)?t:parseFloat(t);return typeof(n=i)!="number"||!Number.isFinite(n)||0>n||n>1?(Bt.warn(e+" must be between 0 and 1. Ignoring invalid value:",t),null):i}ho(t){if(this.Mr){var e,n,i=this.Mr,r=()=>{var s,o=t.sessionRecording===!1?void 0:t.sessionRecording,a=this.uo((s=this.Ne.session_recording)==null?void 0:s.sampleRate,"session_recording.sampleRate"),l=this.uo(o?.sampleRate,"remote config sampleRate"),u=a??l;H(u)&&this.lo();var c=o?.minimumDurationMilliseconds;i.register({[An]:I({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:I({capturePerformance:t.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:u,minimumDurationMilliseconds:C(c)?null:c,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers,version:o?.version,triggerGroups:o?.triggerGroups})})};r(),(e=this.Xa)==null||e.call(this),this.Xa=(n=this._instance.sessionManager)==null?void 0:n.onSessionId(r)}}onRemoteConfig(t){var e=t.ok?t.config:void 0;return e&&"sessionRecording"in e?e.sessionRecording===!1?(this.ho(e),void this.oo()):(this.ho(e),void this.startIfEnabledOrStop()):(this.Ya===ki&&(this.Ya=Sr,Bt.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(t,e){var n;e===void 0&&(e="log"),(n=this.Ja)!=null&&n.log?this.Ja.log(t,e):Bt.warn("log called before recorder was ready")}get ao(){var t,e,n=(t=this._instance)==null||(t=t.persistence)==null?void 0:t.get_property(An);return(n==null||(e=n.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(An);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(n){return Bt.warn("persisted remote config for session recording is invalid and will be ignored",n),!1}return!H(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,n,i;if(!this.eo){if((e=B.__PosthogExtensions__)==null||!e.initSessionRecording)return Bt.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[tf]:!0});var r;if(this.Ja||(this.Ja=(r=B.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===Sr||this.Ya===ki?void 0:(this.Ya=ki,Bt.info("persisted remote config is stale, requesting fresh config before starting"),void new Cf(this._instance).load());this.Ya=cu,(n=(i=this.Ja).setDocumentWasEverVisible)==null||n.call(i,this.io),this.Ja.start(t)}}onRRwebEmit(t){var e;(e=this.Ja)==null||e.onRRwebEmit==null||e.onRRwebEmit(t)}overrideLinkedFlag(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Yd]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Kd]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,n;this.Ja||(n=this.Mr)==null||n.register({[t==="url"?Jd:Zd]:!0}),(e=this.Ja)==null||e.overrideTrigger(t)}get sdkDebugProperties(){var t;return((t=this.Ja)==null?void 0:t.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(t,e){var n;return!((n=this.Ja)==null||!n.tryAddCustomEvent(t,e))}}},zm={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new su(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,n=he(this.instance.config.autocapture)?this.instance.config.autocapture:{};return n.url_allowlist=(t=n.url_allowlist)==null?void 0:t.map((i=>new RegExp(i))),n.url_ignorelist=(e=n.url_ignorelist)==null?void 0:e.map((i=>new RegExp(i))),n}yo(){if(this.isBrowserSupported()){if(w&&P){var t=n=>{n=n||w?.event;try{this.bo(n)}catch(i){Mo.error("Failed to capture event",i)}};if(ve(P,"submit",t,{capture:!0}),ve(P,"change",t,{capture:!0}),ve(P,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=n=>{n=n||w?.event;try{this.bo(n,$o)}catch(i){Mo.error("Failed to capture copy/cut event",i)}};ve(P,"copy",e,{capture:!0}),ve(P,"cut",e,{capture:!0})}}}else Mo.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.vo&&(this.yo(),this.vo=!0)}onRemoteConfig(t){if(this.fo=!0,t.ok){var e=t.config;e.elementsChainAsString&&(this.po=e.elementsChainAsString);var n=e.autocapture_opt_out;mt(n)&&(this.instance.persistence&&this.instance.persistence.register({[ea]:n}),this.co=n),this.startIfEnabled()}else this.startIfEnabled()}setElementSelectors(t){this.mo=t}getElementSelectors(t){var e,n=[];return(e=this.mo)==null||e.forEach((i=>{var r=P?.querySelectorAll(i);r?.forEach((s=>{t===s&&n.push(i)}))})),n}get isEnabled(){var t,e,n=(t=this.instance.persistence)==null?void 0:t.props[ea],i=this.co,r=this.instance.Qi()&&!this.fo;if(Ke(i)&&!mt(n)&&!r)return!1;var s=(e=this.co)!==null&&e!==void 0?e:!!n;return!!this.instance.config.autocapture&&!s}bo(t,e){if(e===void 0&&(e="$autocapture"),this.isEnabled){var n,i=bo(t);af(i)&&(i=i.parentNode||null),e==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&this.instance.config.rageclick&&(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,t.timeStamp||new Date().getTime())&&Lc(i,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var r=e===$o;if(i&&(function(d,h,f,p,g,m){var v;if(!w||dl(d)||f!=null&&f.url_allowlist&&!Tc(f.url_allowlist,m)||f!=null&&f.url_ignorelist&&Tc(f.url_ignorelist,m))return!1;if(f!=null&&f.dom_event_allowlist){var E=f.dom_event_allowlist;if(E&&!E.some((x=>h.type===x)))return!1}var S=hf(d,p),_=S.parentIsUsefulElement,b=S.targetElementList;if(!(function(x,F){var $=F?.element_allowlist;if(C($))return!0;var O,L=function(K){if($.some((V=>K.tagName.toLowerCase()===V)))return{v:!0}};for(var N of x)if(O=L(N))return O.v;return!1})(b,f)||!ma(b,f?.css_selector_allowlist)||ma(b,(v=f?.css_selector_ignorelist)!==null&&v!==void 0?v:Hg))return!1;try{var k=w.getComputedStyle(d);if(k&&k.getPropertyValue("cursor")==="pointer"&&h.type==="click")return!0}catch{}var T=d.tagName.toLowerCase();switch(T){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 _?(g||["click"]).indexOf(h.type)>=0:(g||["click"]).indexOf(h.type)>=0&&(ul.indexOf(T)>-1||d.getAttribute("contenteditable")==="true")}})(i,t,this.Ne,r,r?["copy","cut"]:void 0,this.instance)){var s=Mm(i,{e:t,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.Ne.element_attribute_ignorelist,elementsChainAsString:this.po,disableCaptureUrlHashes:this.instance.config.disable_capture_url_hashes}),o=s.props;if(s.explicitNoCapture)return!1;var a=this.getElementSelectors(i);if(a&&a.length>0&&(o.$element_selectors=a),e===$o){var l,u=uf(w==null||(l=w.getSelection())==null?void 0:l.toString()),c=t.type||"clipboard";if(!u)return!1;o.$selected_content=u,o.$copy_type=c}return this.instance.capture(e,o),!0}}}isBrowserSupported(){return De(P?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(w==null||(e=w.location)==null?void 0:e.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(A.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.wo&&this.wo(),this.wo=void 0,A.info("History API monitoring stopped")}monitorHistoryChanges(){w&&w.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(w&&((e=w.history[t])==null||!e.__posthog_wrapped__)){var n=this;(function(i,r,s){try{if(!(r in i))return ou;var o={next:i[r]},a=s((function(){for(var l=arguments.length,u=new Array(l),c=0;l>c;c++)u[c]=arguments[c];return o.next.apply(this,u)}));return De(a)&&(a.prototype=a.prototype||{},Object.defineProperties(a,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:o}})),i[r]=a,()=>{if(i[r]!==a)for(var l=i[r];De(l)&&l.__posthog_layer__;){var u=l.__posthog_layer__;if(u.next===a)return void(u.next=o.next);l=u.next}else i[r]=o.next}}catch{return ou}})(w.history,t,(i=>function(r,s,o){i.call(this,r,s,o),n.So(t)}))}}So(t){try{var e,n=w==null||(e=w.location)==null?void 0:e.pathname;if(!n)return;n!==this._o&&this.isEnabled&&this._instance.capture(Vn,{navigation_type:t}),this._o=n}catch(i){A.error("Error capturing "+t+" pageview",i)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};ve(w,"popstate",t),this.wo=()=>{w&&w.removeEventListener("popstate",t)}}}},heatmaps:class{get Ne(){return this.instance.config}constructor(t){var e;this.Co=!1,this.vo=!1,this.Mo=null,this.instance=t,this.Co=!((e=this.instance.persistence)==null||!e.props[ta]),this.rageclicks=new su(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return he(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return H(this.Ne.capture_heatmaps)?H(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;Nm.info("starting..."),this.To(),this.Ie()}else{var t;clearInterval((t=this.Mo)!==null&&t!==void 0?t:void 0),this.Eo(),this.getAndClearBuffer()}}onRemoteConfig(t){if(t.ok){var e=t.config;if("heatmaps"in e){var n=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[ta]:n}),this.Co=n,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){No(t.originalEvent)&&this.ke(t.originalEvent,"deadclick")}Ie(){this.Mo&&clearInterval(this.Mo),this.Mo=P?.visibilityState==="visible"?setInterval(this.cr.bind(this),this.flushIntervalMilliseconds):null}To(){w&&P&&(this.Po=this.cr.bind(this),ve(w,ns,this.Po),this.Ro=t=>this.ke(t||w?.event),ve(P,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||w?.event),ve(P,"mousemove",this.Ao,{capture:!0}),this.Lo=new Hc(this.instance,Yg,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),ve(P,ts,this.Oo),this.vo=!0)}Eo(){var t;w&&P&&(this.Po&&w.removeEventListener(ns,this.Po),this.Ro&&P.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&P.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&P.removeEventListener(ts,this.Oo),clearTimeout(this.Do),(t=this.Lo)==null||t.stop(),this.vo=!1)}$o(t,e){var n=this.instance.scrollManager.scrollY(),i=this.instance.scrollManager.scrollX(),r=this.instance.scrollManager.scrollElement(),s=(function(o,a,l){for(var u=o;u&&hn(u)&&!Qe(u,"body");){if(u===l)return!1;var c=void 0;try{var d,h,f;c=(d=(h=(f=u.ownerDocument)==null?void 0:f.defaultView)!==null&&h!==void 0?h:w)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(j(a,c))return!0;u=df(u)}return!1})(bo(t),["fixed","sticky"],r);return{x:t.clientX+(s?0:i),y:t.clientY+(s?0:n),target_fixed:s,type:e}}ke(t,e){var n;if(e===void 0&&(e="click"),!Rc(t.target)&&No(t)){var i=this.$o(t,e);(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,new Date().getTime())&&Lc(bo(t),this.instance.config.rageclick)&&this.Vt(I({},i,{type:"rageclick"})),this.Vt(i)}}Fo(t){!Rc(t.target)&&No(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(w){var e=this.Ne.disable_capture_url_hashes?fn(w.location.href):w.location.href,n=this.Ne.custom_personal_data_properties,i=this.Ne.mask_personal_data_properties?[...ri,...n||[]]:[],r=Zi(e,i,Xi);this.R=this.R||{},this.R[r]||(this.R[r]=[]),this.R[r].push(t)}}cr(){this.R&&!Kt(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:Hc,webVitalsAutocapture:class{constructor(t){var e;this.Co=!1,this.vo=!1,this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this.No=()=>{clearTimeout(this.qo),this.qo=void 0,this.R.metrics.length!==0&&(this._instance.capture("$web_vitals",I({$current_url:this.R.url},this.R.metrics.reduce(((n,i)=>I({},n,{["$web_vitals_"+i.name+"_event"]:I({},i),["$web_vitals_"+i.name+"_value"]:i.value})),{}))),this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.jo=n=>{var i;if(this.R=this.R||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},H(n?.name)||H(n?.value))wn.error("Invalid metric received",n);else{var r=typeof n.navigationURL=="string"?n.navigationURL:void 0,s=this.Bo(r);if(!C(s)){var o=ke(n.navigationId)||typeof n.navigationId=="string"?"navigation:"+n.navigationId:"url:"+s;if(!this.Ho||this.Ho>n.value){this.R.navigationKey!==o&&(this.No(),this.qo=setTimeout(this.No,this.flushToCaptureTimeoutMs)),C(this.R.navigationKey)&&(this.R.navigationKey=o,this.R.url=s),this.R.firstMetricTimestamp=C(this.R.firstMetricTimestamp)?Date.now():this.R.firstMetricTimestamp,n.attribution&&n.attribution.interactionTargetElement&&(n.attribution.interactionTargetElement=void 0);var a=(i=this._instance.sessionManager)==null?void 0:i.checkAndGetSessionAndWindowId(!0),l=I({},n,r?{navigationURL:s}:{},{$current_url:s,timestamp:Date.now()});C(a)||(l.$session_id=a.sessionId,l.$window_id=a.windowId),this.R.metrics.push(l),this.R.metrics.length===this.allowedMetrics.length&&this.No()}else wn.error("Ignoring metric with value >= "+this.Ho,n)}}},this.Uo=()=>{if(!this.vo){var n,i,r,s,o=B.__PosthogExtensions__,a=o?.postHogWebVitalsCallbacksByFlavor,l=a?.[this.zo]||(this.zo==="web-vitals"&&C(a)?o?.postHogWebVitalsCallbacks:void 0);if(C(l)||(n=l.onLCP,i=l.onCLS,r=l.onFCP,s=l.onINP),n&&i&&r&&s){var u={reportSoftNavs:this.useSoftNavs};this.allowedMetrics.indexOf("LCP")>-1&&n(this.jo.bind(this),u),this.allowedMetrics.indexOf("CLS")>-1&&i(this.jo.bind(this),u),this.allowedMetrics.indexOf("FCP")>-1&&r(this.jo.bind(this),u),this.allowedMetrics.indexOf("INP")>-1&&s(this.jo.bind(this),u),this.vo=!0}else wn.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[sa]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,n=he(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return H(n)?((e=this._instance.persistence)==null?void 0:e.props[oa])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(he(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=he(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=he(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=he(this.Wo)&&ke(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:au;return t>0&&6e4>=t?au:t}get isEnabled(){var t=me?.protocol;if(t!=="http:"&&t!=="https:")return wn.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=he(this.Wo)?this.Wo.web_vitals:mt(this.Wo)?this.Wo:void 0;return mt(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(wn.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var n=he(e.capturePerformance)&&!!e.capturePerformance.web_vitals,i=he(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[sa]:n}),this._instance.persistence.register({[oa]:i})),this.Co=n,this.startIfEnabled()}}}get zo(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}ai(t){var e=B.__PosthogExtensions__,n=this.zo,i=e?.postHogWebVitalsCallbacksByFlavor;i!=null&&i[n]||n==="web-vitals"&&C(i)&&e!=null&&e.postHogWebVitalsCallbacks?t():e==null||e.loadExternalDependency==null||e.loadExternalDependency(this._instance,n,(r=>{r?wn.error("failed to load script",r):t()}))}Bo(t){var e=t||w?.location.href;if(e){var n=this._instance.config.disable_capture_url_hashes?fn(e):e,i=this._instance.config.custom_personal_data_properties,r=this._instance.config.mask_personal_data_properties?[...ri,...i||[]]:[];return Zi(n,r,Xi)}wn.error("Could not determine current URL")}}},Vm={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var n;if(w&&this.isEnabled&&(n=B.__PosthogExtensions__)!=null&&n.errorWrappingFunctions){var i=B.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,r=B.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,s=B.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.Vo&&this.Ne.capture_unhandled_errors&&(this.Vo=i(this.captureException.bind(this))),!this.Zo&&this.Ne.capture_unhandled_rejections&&(this.Zo=r(this.captureException.bind(this))),!this.Go&&this.Ne.capture_console_errors&&(this.Go=s(this.captureException.bind(this)))}catch(o){Ii.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[na]),this.Jo=new qp(I({},(function(n){var i,r,s,o;return n===void 0&&(n={}),{refillRate:(i=(r=n.exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:n.__exceptionRateLimiterRefillRate)!==null&&i!==void 0?i:1,bucketSize:(s=(o=n.exceptionRateLimiterBucketSize)!==null&&o!==void 0?o:n.__exceptionRateLimiterBucketSize)!==null&&s!==void 0?s:10}})(this._instance.config.error_tracking),{refillInterval:1e4,rt:Ii})),this.Ne=this.Yo(),this.startIfEnabledOrStop()}Yo(){var t=this._instance.config.capture_exceptions,e={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return he(t)?e=I({},e,t):(C(t)?this.Ko:t)&&(e=I({},e,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),e}get isEnabled(){return this.Ne.capture_console_errors||this.Ne.capture_unhandled_errors||this.Ne.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(Ii.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",(i=>{if(i)return Ii.error("failed to load script",i);t()}))}Qo(){var t,e,n;(t=this.Vo)==null||t.call(this),this.Vo=void 0,(e=this.Zo)==null||e.call(this),this.Zo=void 0,(n=this.Go)==null||n.call(this),this.Go=void 0}onRemoteConfig(t){if(t.ok){var e=t.config;"autocaptureExceptions"in e&&(this.Ko=!!e.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[na]:this.Ko}),this.Ne=this.Yo(),this.startIfEnabledOrStop())}}onConfigChange(){this.Ne=this.Yo()}captureException(t){var e,n,i,r=(e=t==null||(n=t.$exception_list)==null||(n=n[0])==null?void 0:n.type)!==null&&e!==void 0?e:"Exception";this.Jo.consumeRateLimit(r)?Ii.info("Skipping exception capture because of client rate limiting.",{exception:r}):(i=this._instance.exceptions)==null||i.sendExceptionEvent(t)}},exceptions:class{constructor(t){var e,n;this.Xo=[],this.tl=new ag([new gg,new xg,new vg,new mg,new Eg,new bg,new yg,new Sg],(function(i){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;r>o;o++)s[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` -`),d=l;c.length>d;d++){var h=c[d];if(1024>=h.length){var f=Cc.test(h)?h.replace(Cc,"$1"):h;if(!f.match(/\S*Error: /)){for(var p of s){var g=p(f,i);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var v=Array.from(m);return v.reverse(),v.slice(0,50).map((E=>{return I({},E,{filename:E.filename||(S=v,S[S.length-1]||{}).filename,function:E.function||ni});var S}))})(u)}})("web:javascript",dg,pg)),this._instance=t,this.Xo=(e=(n=this._instance.persistence)==null?void 0:n.get_property(ia))!==null&&e!==void 0?e:[],this.el=Jr(this.il()),this.rl=new kg(this.el)}onConfigChange(){this.el=Jr(this.il()),this.rl.setConfig(this.el)}onRemoteConfig(t){var e,n,i;if(t.ok){var r=t.config;if("errorTracking"in r){var s=(e=(n=r.errorTracking)==null?void 0:n.suppressionRules)!==null&&e!==void 0?e:[],o=(i=r.errorTracking)==null?void 0:i.captureExtensionExceptions;this.Xo=s,this._instance.persistence&&this._instance.persistence.register({[ia]:this.Xo,[ra]:o})}}}get nl(){var t,e=!!this._instance.get_property(ra),n=this._instance.config.error_tracking.captureExtensionExceptions;return(t=n??e)!==null&&t!==void 0&&t}buildProperties(t,e){return this.tl.buildFromUnknown(t,{syntheticException:e?.syntheticException,mechanism:{handled:e?.handled}})}addExceptionStep(t,e){if(this.el.enabled)try{if(!X(t)||t.trim().length===0)return void St.warn("Ignoring exception step because message must be a non-empty string");var n=(function(s){if(!s)return{sanitizedProperties:{},droppedKeys:[]};var o=[];return{sanitizedProperties:Object.keys(s).reduce(((a,l)=>Ig.has(l)?(o.push(l),a):(a[l]=s[l],a)),{}),droppedKeys:o}})(this.sl(e)),i=n.sanitizedProperties,r=n.droppedKeys;r.length>0&&St.warn("Ignoring reserved exception step fields",{droppedKeys:r}),this.rl.add(I({[Kr]:t,[Yr]:new Date().toISOString()},i))}catch(s){St.error("Failed to add exception step. Ignoring breadcrumb.",s)}}sendExceptionEvent(t){try{var e=t.$exception_list;if(this.al(e)){if(this.ol(e))return this.ll("Exception dropped: matched a suppression rule"),void St.info("Skipping exception capture because a suppression rule matched");if(!this.nl&&this.ul(e))return this.ll("Exception dropped: thrown by a browser extension"),void St.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.hl(e))return this.ll("Exception dropped: thrown by the PostHog SDK"),void St.info("Skipping exception capture because it was thrown by the PostHog SDK")}var n=this.el.enabled&&H(t.$exception_steps)?this.dl(t):t,i=typeof(s=globalThis._posthogReleaseId)=="string"&&s.length>0?s:void 0;i&&(n.$release_id=i);try{var r=this._instance.capture("$exception",n,{_noTruncate:!0,_batchKey:"exceptionEvent",Wn:!0});return r&&this.rl.clear(),r}catch(o){return St.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void St.error("Failed to process exception event. Ignoring this exception.",o)}var s}dl(t){try{var e=this.rl.getAttachable();return e.length===0?t:I({},t,{$exception_steps:e})}catch(n){return St.error("Failed to read buffered exception steps. Capturing exception without steps.",n),t}}ll(t){this.el.enabled&&this.rl.add({[Kr]:t,[Yr]:new Date().toISOString()})}sl(t){return he(t)?I({},t):{}}il(){var t,e;return(t=(e=this._instance.config.error_tracking)==null?void 0:e.exception_steps)!==null&&t!==void 0?t:{}}ol(t){if(t.length===0)return!1;try{var e=t.reduce(((n,i)=>{var r=i.type,s=i.value;return X(r)&&r.length>0&&n.$exception_types.push(r),X(s)&&s.length>0&&n.$exception_values.push(s),n}),{$exception_types:[],$exception_values:[]});return this.Xo.some((n=>{var i=n.values.map((r=>{var s=Uf[r.operator],o=e[r.key];if(!s||!o)return!1;var a=U(r.value)?r.value:[r.value];return a.length>0&&s(a,o)}));return n.type==="OR"?i.some(Boolean):i.every(Boolean)}))}catch(n){return St.warn("Failed to evaluate suppression rules. Capturing the exception.",n),!1}}ul(t){return t.flatMap((e=>{var n,i;return(n=(i=e.stacktrace)==null?void 0:i.frames)!==null&&n!==void 0?n:[]})).some((e=>e.filename&&e.filename.startsWith("chrome-extension://")))}hl(t){if(t.length>0){var e,n,i,r,s=(e=(n=t[0].stacktrace)==null?void 0:n.frames)!==null&&e!==void 0?e:[],o=s[s.length-1];return(i=o==null||(r=o.filename)==null?void 0:r.includes("posthog.com/static"))!==null&&i!==void 0&&i}return!1}al(t){return!H(t)&&U(t)}}},Gm=I({productTours:class{get Mr(){return this._instance.persistence}constructor(t){this.vl=null,this.cl=null,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(t.ok){var e=t.config;if("productTours"in e){var n,i;if(this.Mr&&this.Mr.register({[sl]:!!e.productTours}),!Oo(this._instance))return!this.vl&&H((n=this.Mr)==null?void 0:n.props[Mi])||xr.info("product tours disabled; stopping and clearing cached tours"),(i=this.vl)==null||i.stop(),this.vl=null,void this.clearCache();this.loadIfEnabled()}}}loadIfEnabled(){!this.vl&&Oo(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.generateProductTours?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",(i=>{i?xr.error("Could not load product tours script",i):t()}))}fl(){var t;!this.vl&&(t=B.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=B.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(t,e){if(e===void 0&&(e=!1),!U(this.cl)||e){var n=this.Mr;if(n){var i=n.props[Mi];if(U(i)&&!e)return this.cl=i,void t(i,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",timestampMode:"query",callback:r=>{if(Oo(this._instance)){var s=r.statusCode;if(s!==200||!r.json){var o="Product Tours API could not be loaded, status: "+s;return s===0?r.error||xr.warn(o):xr.error(o),void t([],{isLoaded:!1,error:o})}var a=U(r.json.product_tours)?r.json.product_tours:[];this.cl=a,n&&n.register({[Mi]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){H(this.vl)?t([],{isLoaded:!1,error:"Product tours not loaded"}):this.vl.getActiveProductTours(t)}showProductTour(t){var e;(e=this.vl)==null||e.showTourById(t)}previewTour(t){this.vl?this.vl.previewTour(t):this.ai((()=>{var e;this.fl(),(e=this.vl)==null||e.previewTour(t)}))}dismissProductTour(){var t;(t=this.vl)==null||t.dismissTour("user_clicked_skip")}nextStep(){var t;(t=this.vl)==null||t.nextStep()}previousStep(){var t;(t=this.vl)==null||t.previousStep()}clearCache(){var t;this.cl=null,(t=this.Mr)==null||t.unregister(Mi)}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)}}},Cs),Km={siteApps:class{constructor(t){this.pl=0,this._instance=t,this.gl=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}ml(t,e){if(e){var n=this.globalsForEvent(e);this.gl.push(n),this.gl.length>1e3&&(this.gl=this.gl.slice(10))}}get siteAppLoaders(){var t;return(t=B._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,n,i,r,s,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var h=d[0];l[h]={id:u[h],type:h,properties:d[1]}}var f=t.$set_once,p=t.$set;return{event:I({},dd(t,Om),{properties:I({},t.properties,p?{$set:I({},(e=(n=t.properties)==null?void 0:n.$set)!==null&&e!==void 0?e:{},p)}:{},f?{$set_once:I({},(i=(r=t.properties)==null?void 0:r.$set_once)!==null&&i!==void 0?i:{},f)}:{}),elements_chain:(s=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&s!==void 0?s:"",distinct_id:(a=t.properties)==null?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}bl(t){var e,n=(e=t.tagName)==null?void 0:e.toLowerCase();return n==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(Et.error("prepare_external_dependency_stylesheet returned null"),null):n==="script"&&this._instance.config.prepare_external_dependency_script?this._instance.config.prepare_external_dependency_script(t)||(Et.error("prepare_external_dependency_script returned null"),null):t}_l(){var t,e,n,i,r,s,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=P?.defaultView,u=l==null||(t=l.Node)==null?void 0:t.prototype;if(!l||!u)return()=>{};if(this.pl++,this.wl)return this.kl();var c=[],d=this,h=new WeakSet,f=(m,v,E)=>{if(m!=null&&m[v]){var S=m[v];m[v]=E(S),c.push((()=>{m[v]=S}))}},p=m=>{if(h.has(m))return m;var v=d.bl(m);return v&&h.add(v),v},g=m=>m.map((v=>typeof v=="string"?v:p(v))).filter((v=>!Ke(v)));return f(u,"appendChild",(m=>function(v){var E=p(v);return E?m.call(this,E):v})),f(u,"insertBefore",(m=>function(v,E){var S=p(v);return S?m.call(this,S,E):v})),f(u,"replaceChild",(m=>function(v,E){var S=p(v);return S?m.call(this,S,E):E})),[(e=l.Element)==null?void 0:e.prototype,(n=l.Document)==null?void 0:n.prototype,(i=l.DocumentFragment)==null?void 0:i.prototype].forEach((m=>{f(m,"append",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),f(m,"prepend",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))}))})),[(r=l.Element)==null?void 0:r.prototype,(s=l.CharacterData)==null?void 0:s.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((m=>{f(m,"before",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),f(m,"after",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),f(m,"replaceWith",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];var b=g(S);return S.length&&!b.length?void 0:v.apply(this,b)}))})),f((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(v,E){var S=p(E);return S?m.call(this,v,S):null})),this.wl=()=>{c.forEach((m=>m())),this.wl=void 0},this.kl()}kl(){var t=!1;return()=>{var e;t||(t=!0,this.pl--,this.pl===0&&((e=this.wl)==null||e.call(this)))}}xl(t,e){e===void 0&&(e=!0);var n=this._l();try{var i=t(n);return e&&n(),i}catch(r){throw n(),r}}setupSiteApp(t){var e=this.apps[t.id],n=()=>{var o;!e.errored&&this.gl.length&&(Et.info("Processing "+this.gl.length+" events for site app with id "+t.id),this.gl.forEach((a=>this.xl((()=>e.processEvent==null?void 0:e.processEvent(a))))),e.processedBuffer=!0),Object.values(this.apps).every((a=>a.processedBuffer||a.errored))&&((o=this.yl)==null||o.call(this))},i=!1,r=o=>{e.errored=!o,e.loaded=!0,Et.info("Site app with id "+t.id+" "+(o?"loaded":"errored")),i&&n()};try{var s=this.xl((o=>t.init({posthog:this._instance,callback(a){o(),r(a)}})),!1).processEvent;s&&(e.processEvent=s),i=!0}catch(o){Et.error(uu+t.id,o),r(!1)}if(i&&e.loaded)try{n()}catch(o){Et.error("Error while processing buffered events PostHog app with config id "+t.id,o),e.errored=!0}}Sl(){var t=this.siteAppLoaders||[];for(var e of t)this.apps[e.id]={id:e.id,loaded:!1,errored:!1,processedBuffer:!1};for(var n of t)this.setupSiteApp(n)}Cl(t){var e=this;if(Object.keys(this.apps).length!==0){var n=this.globalsForEvent(t),i=function(s){try{e.xl((()=>s.processEvent==null?void 0:s.processEvent(n)))}catch(o){Et.error("Error while processing event "+t.event+" for site app "+s.id,o)}};for(var r of Object.values(this.apps))i(r)}}onRemoteConfig(t){var e,n,i,r=this;if((e=this.siteAppLoaders)!=null&&e.length)return this.isEnabled?(this.Sl(),void this._instance.on("eventCaptured",(l=>this.Cl(l)))):void Et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((n=this.yl)==null||n.call(this),t.ok){var s=t.config;if((i=s.siteApps)!=null&&i.length)if(this.isEnabled){var o=function(){var l,u=a.id,c=a.url;B["__$$ph_site_app_"+u]=r._instance,(l=B.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(r._instance,c,(d=>{if(d)return Et.error(uu+u,d)}))};for(var a of s.siteApps)o()}else Et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},Ym={tracingHeaders:class{constructor(t){this.Ml=void 0,this.Tl=void 0,this.El=void 0,this.Uo=()=>{var e,n,i=this.Il();i?(C(this.Ml)&&(this.Ml=(e=B.__PosthogExtensions__)==null||(e=e.tracingHeadersPatchFns)==null?void 0:e._patchXHR(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager)),C(this.Tl)&&(this.Tl=(n=B.__PosthogExtensions__)==null||(n=n.tracingHeadersPatchFns)==null?void 0:n._patchFetch(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager))):this.Qo()},this._instance=t}initialize(){this.startIfEnabledOrStop()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",(i=>{if(i)return Lm.error("failed to load script",i);t()}))}Pl(){var t,e;return(t=(e=this._instance.config.tracing_headers)!==null&&e!==void 0?e:this._instance.config.addTracingHeaders)!==null&&t!==void 0?t:this._instance.config.__add_tracing_headers}Il(){var t=this.Pl();return U(t)?(U(this.El)?this.El.splice(0,this.El.length,...t):this.El=[...t],t.length>0?this.El:void 0):(U(this.El)&&this.El.splice(0),this.El=t||void 0,this.El)}Qo(){var t,e;(t=this.Ml)==null||t.call(this),(e=this.Tl)==null||e.call(this),this.Ml=void 0,this.Tl=void 0}startIfEnabledOrStop(){this.Il()?this.ai(this.Uo):this.Qo()}}},Jm=I({surveys:class{get Ne(){return this._instance.config}constructor(t){this.Rl=void 0,this._surveyManager=null,this.Al=!1,this.Fl=[],this.Ll=null,this.Ol=null,this._instance=t,this._surveyEventReceiver=null}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this.Ne.disable_surveys){if(!t.ok)return Q.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(H(e))return Q.warn("Flags not loaded yet. Not loading surveys.");var n=U(e);this.Rl=n?e.length>0:e,Q.info("flags response received, isSurveysEnabled: "+this.Rl),this.loadIfEnabled()}}reset(){try{var t;(t=this._surveyEventReceiver)==null||t.reset(),localStorage.removeItem("lastSeenSurveyDate");for(var e=[],n=0;nlocalStorage.removeItem(r)))}catch{}}loadIfEnabled(){if(!this._surveyManager)if(this.Al)Q.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)Q.info(du);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())Q.info("Not loading surveys in cookieless mode without consent.");else{var t=B?.__PosthogExtensions__;if(t){if(!C(this.Rl)||this.Ne.advanced_enable_surveys){var e=this.Rl||this.Ne.advanced_enable_surveys;this.Al=!0;try{var n=t.generateSurveys;if(n)return void this.Dl(n,e);var i=t.loadExternalDependency;if(!i)return void this.$l(al);i(this._instance,"surveys",(r=>{r||!t.generateSurveys?this.$l("Could not load surveys script",r):this.Dl(t.generateSurveys,e)}))}catch(r){throw this.$l("Error initializing surveys",r),r}finally{this.Al=!1}}}else Q.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new jm(this._instance),Q.info("Surveys loaded successfully"),this.Nl({isLoaded:!0})}$l(t,e){Q.error(t,e),this.Nl({isLoaded:!1,error:t})}onSurveysLoaded(t){return this.Fl.push(t),this._surveyManager&&this.Nl({isLoaded:!0}),()=>{this.Fl=this.Fl.filter((e=>e!==t))}}getSurveys(t,e){if(e===void 0&&(e=!1),this.Ne.disable_surveys)return Q.info(du),t([]);var n,i=this._instance.get_property(la);if(i&&!e)return t(i,{isLoaded:!0}),void(this.ql()&&this.getSurveys((()=>{}),!0));typeof Promise<"u"&&this.Ll?this.Ll.then((r=>t(r.surveys,r.context))):(typeof Promise<"u"&&(this.Ll=new Promise((r=>{n=r}))),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this.Ne.token),method:"GET",timestampMode:"query",timeout:this.Ne.surveys_request_timeout_ms,callback:r=>{var s;this.Ll=null;var o=r.statusCode;if(o!==200||!r.json){var a="Surveys API could not be loaded, status: "+o;o!==0?Q.error(a):r.error||Q.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(n==null||n({surveys:[],context:l}))}this.Ol=null;var u,c=r.json.surveys||[],d=c.filter((f=>(function(p){return!(!p.start_date||p.end_date)})(f)&&(Wf(f)||(function(p){var g;return!((g=p.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(f))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(s=this._instance.persistence)==null||s.register({[la]:c,[Xr]:Date.now()});var h={isLoaded:!0};t(c,h),n?.({surveys:c,context:h})}}))}ql(){return this.jl()&&!this.Ll&&!this.Bl()}jl(){var t=this._instance.get_property(Xr);return ke(t)&&Date.now()-t>3e5}Bl(){return ke(this.Ol)&&3e5>Date.now()-this.Ol}markSurveyAsSeen(t,e){var n,i={id:t,current_iteration:(n=e?.iteration)!==null&&n!==void 0?n:null};zf(i);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}}Nl(t){for(var e of this.Fl)try{if(!t.isLoaded)return e([],t);this.getSurveys(e)}catch(n){Q.error("Error in survey callback",n)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!H(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);Q.warn("init was not called")}Hl(t){var e=null;return this.getSurveys((n=>{var i;e=(i=n.find((r=>r.id===t)))!==null&&i!==void 0?i:null})),e}Ul(t){if(H(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(H(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(H(this._surveyManager))return Q.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 H(this._surveyManager)?(Q.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Ir})):new Promise((n=>{this.getSurveys((i=>{var r,s=(r=i.find((a=>a.id===t)))!==null&&r!==void 0?r:null;if(s){var o=this.zl(s);n({visible:o.eligible,disabledReason:o.reason})}else n({visible:!1,disabledReason:"Survey not found"})}),e)}))}renderSurvey(t,e,n){var i;if(H(this._surveyManager))Q.warn("init was not called");else{var r=typeof t=="string"?this.Hl(t):t;if(r!=null&&r.id)if(Em.includes(r.type)){var s=P?.querySelector(e);if(s)return(i=r.appearance)!=null&&i.surveyPopupDelaySeconds?(Q.info("Rendering survey "+r.id+" with delay of "+r.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;Q.info("Rendering survey "+r.id+" with delay of "+((o=r.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(a=this._surveyManager)==null||a.renderSurvey(r,s,n),Q.info("Survey "+r.id+" rendered")}),1e3*r.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(r,s,n);Q.warn("Survey element not found")}else Q.warn("Surveys of type "+r.type+" cannot be rendered in the app");else Q.warn("Survey not found")}}displaySurvey(t,e){var n;if(H(this._surveyManager))Q.warn("init was not called");else{var i=this.Hl(t);if(i){var r=i;if((n=i.appearance)!=null&&n.surveyPopupDelaySeconds&&e.ignoreDelay&&(r=I({},i,{appearance:I({},i.appearance,{surveyPopupDelaySeconds:0})})),e.displayType!==_a.Popover&&e.initialResponses&&Q.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),e.ignoreConditions===!1){var s=this.Ul(i);if(!s.eligible)return void Q.warn("Survey is not eligible to be displayed: ",s.reason)}e.displayType!==_a.Inline?this._surveyManager.handlePopoverSurvey(r,e):this.renderSurvey(r,e.selector,e.properties)}else Q.warn("Survey not found")}}cancelPendingSurvey(t){H(this._surveyManager)?Q.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},Cs),Zm={toolbar:class{constructor(t){this.instance=t}Wl(t){B.ph_toolbar_state=t}Vl(){var t;return(t=B.ph_toolbar_state)!==null&&t!==void 0?t:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(t,e,n){if(t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),ga(this.instance.config)||!w||!P)return!1;t=t??w.location,n=n??w.history;try{if(!e){try{w.localStorage.setItem("test","test"),w.localStorage.removeItem("test")}catch{return!1}e=w?.localStorage}var i,r=Um||os(t.hash,"__posthog")||os(t.hash,"state"),s=r?Pc((()=>JSON.parse(atob(decodeURIComponent(r)))))||Pc((()=>JSON.parse(decodeURIComponent(r)))):null;return s&&s.action==="ph_authorize"?((i=s).source="url",i&&Object.keys(i).length>0&&(s.desiredHash?t.hash=s.desiredHash:n?n.replaceState(n.state,"",t.pathname+t.search):t.hash="")):((i=JSON.parse(e.getItem(fu)||"{}")).source="localstorage",delete i.userIntent),!(!i.token||this.instance.config.token!==i.token||(this.loadToolbar(i),0))}catch{return!1}}Zl(t){var e=B.ph_load_toolbar||B.ph_load_editor;!H(e)&&De(e)?e(t,this.instance):hu.warn("No toolbar load function found")}loadToolbar(t){var e=!(P==null||!P.getElementById(of));if(!w||e)return!1;var n=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,i=I({token:this.instance.config.token},t,{apiURL:this.instance.requestRouter.endpointFor("ui")},n?{instrument:!1}:{});if(w.localStorage.setItem(fu,JSON.stringify(I({},i,{source:void 0}))),this.Vl()===2)this.Zl(i);else if(this.Vl()===0){var r;this.Wl(1),(r=B.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"toolbar",(s=>{if(s)return hu.error("[Toolbar] Failed to load",s),void this.Wl(0);this.Wl(2),this.Zl(i)})),ve(w,"turbolinks:load",(()=>{this.Wl(0),this.loadToolbar(i)}))}return!0}Gl(t){return this.loadToolbar(t)}maybeLoadEditor(t,e,n){return t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),this.maybeLoadToolbar(t,e,n)}}},Xm=I({experiments:Me},Cs),Qm={conversations:class{constructor(t){this.Ql=void 0,this._conversationsManager=null,this.Kl=!1,this.Jl=null,this.Yl=!1,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this._instance.config.disable_conversations&&(this.Xl=t.ok,t.ok)){var e=t.config.conversations;H(e)||(mt(e)?this.Ql=e:(this.Ql=e.enabled,this.Jl=e),this.loadIfEnabled())}}reset(){var t;(t=this._conversationsManager)==null||t.reset(),this._conversationsManager=null,this.Ql=void 0,this.Jl=null,this.Xl=void 0,this.Yl=!1}loadIfEnabled(){if(!(this._conversationsManager||this.Kl||this._instance.config.disable_conversations||ga(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=B?.__PosthogExtensions__;if(t&&!C(this.Ql)&&this.Ql)if(this.Jl&&this.Jl.token){this.Kl=!0;try{var e=t.initConversations;if(e)return this.tu(e),void(this.Kl=!1);var n=t.loadExternalDependency;if(!n)return void this.eu(al);n(this._instance,"conversations",(i=>{i||!t.initConversations?this.eu("Could not load conversations script",i):this.tu(t.initConversations),this.Kl=!1}))}catch(i){this.eu("Error initializing conversations",i),this.Kl=!1}}else st.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,st.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else st.error("Cannot complete initialization: remote config is null")}eu(t,e){st.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():st.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!Ke(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":ga(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.Xl===!1?"remote_config_failed":C(this.Ql)?this.Xl?"disabled_in_project":"remote_config_pending":this.Ql?H(this.Jl)||!this.Jl.token?"missing_token":B!=null&&B.__PosthogExtensions__?this.Kl?"initializing":this.Yl?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.isVisible())!==null&&t!==void 0&&t}sendMessage(t,e,n){var i=this;return se((function*(){return i._conversationsManager?i._conversationsManager.sendMessage(t,e,n):(st.warn(En),null)}))()}getMessages(t,e){var n=this;return se((function*(){return n._conversationsManager?n._conversationsManager.getMessages(t,e):(st.warn(En),null)}))()}markAsRead(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(st.warn(En),null)}))()}getTickets(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(st.warn(En),null)}))()}requestRestoreLink(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(st.warn(En),null)}))()}restoreFromToken(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(st.warn(En),null)}))()}restoreFromUrlToken(){var t=this;return se((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(st.warn(En),null)}))()}getCurrentTicketId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getCurrentTicketId())!==null&&t!==void 0?t:null}getWidgetSessionId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getWidgetSessionId())!==null&&t!==void 0?t:null}Xn(){var t;(t=this._conversationsManager)==null||t.setIdentity()}ts(){var t;(t=this._conversationsManager)==null||t.clearIdentity()}}},ev={logs:class{constructor(t){var e,n=this;this.iu=!1,this.ru=!1,this.rt=pe("[logs]"),this.nu=I({},this.rt,{error(){for(var i=arguments.length,r=new Array(i),s=0;i>s;s++)r[s]=arguments[s];r.some(bu)||n.rt.error(...r)}}),this.tr=[],this.su=[],this.Sa=0,this.au=()=>{var i,r;this.Sa=0,(i=this.ou)==null||i.onReconnect(),(r=this.lu)==null||r.onReconnect()},this._instance=t,this._instance&&(e=this._instance.config.logs)!=null&&e.captureConsoleLogs&&(this.iu=!0),w&&ve(w,"online",this.au)}uu(t,e,n,i){var r,s=(function(o,a){var l,u,c,d,h,f,p,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,v=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,E=C(v)?Math.max(m,2048):Math.max(m,v),S=o?.resourceAttributes;return{serviceName:(d=(h=S?.["service.name"])!==null&&h!==void 0?h:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(f=S?.["service.version"])!==null&&f!==void 0?f:o?.serviceVersion,environment:(p=S?.["deployment.environment"])!==null&&p!==void 0?p:o?.environment,resourceAttributes:S,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:E,maxBatchRecordsPerPost:100,rateCapWindowMs:g,maxLogsPerInterval:v,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}})((r=this._instance)==null||(r=r.config)==null?void 0:r.logs,n);return[new rg(this.hu(t,e),s,this.nu,(()=>this.du()),(o=>o()),void 0,i),s]}vu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.ou||this.cu!==e){var n;(n=this.ou)==null||n.reset(),this.cu=e;var i=this.uu((()=>this.tr),(r=>{this.tr=r}));this.ou=i[0],this.fu=i[1]}return this.ou}pu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.lu||this.gu!==e){var n;(n=this.lu)==null||n.reset(),this.gu=e;var i=this.uu((()=>this.su),(r=>{this.su=r}),{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},wu);this.lu=i[0],this.mu=i[1]}return this.lu}initialize(){this.loadIfEnabled()}onRemoteConfig(t){var e;if(t.ok){var n=(e=t.config.logs)==null?void 0:e.captureConsoleLogs;!H(n)&&n&&(this.iu=!0,this.loadIfEnabled())}}reset(){var t,e;this.tr=[],(t=this.ou)==null||t.reset(),this.su=[],(e=this.lu)==null||e.reset(),this.Sa=0}captureLog(t){this.vu().captureLog(t)}he(t){this.pu().captureLog(t)}get logger(){return this.yu||(this.yu={trace:(t,e)=>this.captureLog({body:t,level:"trace",attributes:e}),debug:(t,e)=>this.captureLog({body:t,level:"debug",attributes:e}),info:(t,e)=>this.captureLog({body:t,level:"info",attributes:e}),warn:(t,e)=>this.captureLog({body:t,level:"warn",attributes:e}),error:(t,e)=>this.captureLog({body:t,level:"error",attributes:e}),fatal:(t,e)=>this.captureLog({body:t,level:"fatal",attributes:e})}),this.yu}flushLogs(t){t?this.bu(t):(this.ou&&this.ou.flush().catch((e=>this._u(e))),this.lu&&this.lu.flush().catch((e=>this._u(e))))}_u(t){bu(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=B?.__PosthogExtensions__;if(t){var e=t.loadExternalDependency;e?e(this._instance,"logs",(n=>{var i;n||(i=t.logs)==null||!i.initializeLogs?this.rt.error("Could not load logs script",n):(t.logs.initializeLogs(this._instance),this.ru=!0)})):this.rt.error(al)}else this.rt.error("PostHog Extensions not found.")}}hu(t,e){var n=this._instance;return{get isDisabled(){return!1},get optedOut(){return!n.is_capturing()},getPersistedProperty:i=>i===Ut.LogsQueue?t():void 0,setPersistedProperty(i,r){var s;i===Ut.LogsQueue&&e((s=r)!==null&&s!==void 0?s:[])},Ot:i=>this.Ot(i),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Ot(t){return new Promise((e=>{if(_f(this.Sa,3))e({kind:"fatal",error:Do(void 0,"logs endpoint is unreachable, dropping batch")});else{var n=!1,i=s=>{n||(n=!0,clearTimeout(r),e(s))},r=setTimeout((()=>{this.rt.warn("Logs request timed out before receiving a response"),i({kind:"retry-later",error:Do(void 0,"logs request timed out")})}),9e4);this._instance._send_request({method:"POST",url:this.wu(),data:t,compression:"best-available",batchKey:"logs",fireCallbackOnDrop:!0,callback:s=>{var o=s.statusCode;if(this.ku(o),o>=200&&300>o)i({kind:"ok"});else if(o===413)i({kind:"too-large"});else if(o!==0&&o!==429&&500>o)i({kind:"fatal",error:new Error("logs request failed with status "+o)});else{var a;o===0?(s.error||this.rt.warn("Logs request failed before receiving an HTTP response"),i({kind:"retry-later",error:Do(s.error,"logs request failed before receiving an HTTP response")})):i({kind:"retry-later",error:(a=s.error)!==null&&a!==void 0?a:new Error("logs request failed with status "+o)})}}})}}))}ku(t){(t!==0||this._instance.__loaded)&&(this.Sa=yf(t,this.Sa,3,(()=>this.rt.warn("Log requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped sending logs; will try again when connectivity changes."))))}bu(t){this.tr.length>0&&this.xu(t,this.tr,this.fu,ne.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,wu,(e=>{this.su=e}))}xu(t,e,n,i,r){if(e.length!==0){var s=e.map((a=>a.record));r([]);var o=Hd(s,Ud(n,ne.LIB_NAME,ne.LIB_VERSION),i,ne.LIB_VERSION);this._instance._send_request({method:"POST",url:this.wu(),data:o,compression:"best-available",batchKey:"logs",transport:t})}}wu(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}du(){var t,e={};if(e.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var n=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.windowId,r=n.sessionStartTimestamp,s=n.lastActivityTimestamp;e.sessionId=n.sessionId,e.windowId=i,H(r)||(e.sessionStartTimestamp=r),H(s)||(e.lastActivityTimestamp=s)}if(B!=null&&(t=B.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?fn(B.location.href):B.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},tv={metrics:class{constructor(t){this.rt=pe("[metrics]"),this._instance=t}initialize(){}vu(){var t,e,n=(t=this._instance)==null||(t=t.config)==null?void 0:t.metrics;return this.ou&&this.cu===n||((e=this.ou)==null||e.reset(),this.cu=n,this.ou=new sg(this.hu(),(function(i){var r,s,o,a,l,u=i?.resourceAttributes;return{serviceName:(r=u?.["service.name"])!==null&&r!==void 0?r:i?.serviceName,serviceVersion:(s=u?.["service.version"])!==null&&s!==void 0?s:i?.serviceVersion,environment:(o=u?.["deployment.environment"])!==null&&o!==void 0?o:i?.environment,resourceAttributes:u,beforeSend:i?.beforeSend,flushIntervalMs:(a=i?.flushIntervalMs)!==null&&a!==void 0?a:1e4,maxSeriesPerFlush:(l=i?.maxSeriesPerFlush)!==null&&l!==void 0?l:1e3}})(n),this.rt)),this.ou}count(t,e,n){e===void 0&&(e=1),this.vu().count(t,e,n)}gauge(t,e,n){this.vu().gauge(t,e,n)}histogram(t,e,n){this.vu().histogram(t,e,n)}flush(t){if(!this.ou)return Promise.resolve();if(t){var e=this.ou.drainWindow();return e&&this.Jt(e,t),Promise.resolve()}return this.ou.flush().catch((n=>this.rt.error("PostHog metrics flush failed:",n)))}reset(){var t;(t=this.ou)==null||t.reset()}hu(){var t=this._instance,e=this;return{get isDisabled(){return!1},get optedOut(){return!t.is_capturing()},Jt:n=>e.Jt(n),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Jt(t,e){return new Promise((n=>{var i=!1,r=o=>{i||(i=!0,clearTimeout(s),n(o))},s=setTimeout((()=>r({kind:"retry-later",error:new Error("metrics request timed out")})),9e4);this._instance._send_request(I({method:"POST",url:this.Su(),data:t,compression:"best-available",batchKey:"metrics"},e&&{transport:e},{fireCallbackOnDrop:!0,callback(o){var a=o.statusCode;if(a>=200&&300>a)r({kind:"ok"});else if(a===413)r({kind:"too-large"});else if(a!==0&&a!==429&&500>a)r({kind:"fatal",error:new Error("metrics request failed with status "+a)});else{var l;r({kind:"retry-later",error:(l=o.error)!==null&&l!==void 0?l:new Error("metrics request failed with status "+a)})}}}))}))}Su(){return this._instance.requestRouter.endpointFor("api","/i/v1/metrics")+"?token="+encodeURIComponent(this._instance.config.token)}}},nv=I({},Cs,qm,zm,Vm,Gm,Km,Jm,Ym,Zm,Xm,Qm,ev,tv);Je.__defaultExtensionClasses=I({},nv);(function(){ne.SDK_DIST_CHANNEL="npm";var t=Wi[Gn]=new Je;return(function(){function e(){e.done||(e.done=!0,Gf=!1,ie(Wi,(function(n){n._dom_loaded()})))}P!=null&&P.addEventListener?P.readyState==="complete"?e():ve(P,"DOMContentLoaded",e,{capture:!1}):w&&A.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const iv=["a[href]","button:not([disabled])","input:not([disabled]):not([type='hidden'])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(",");let pt=null,ka=null,Yf="";const Ca=new Map;function Jf(t){return[...t.querySelectorAll(iv)].filter(e=>!e.hidden&&e.getAttribute("aria-hidden")!=="true"&&e.getClientRects().length>0)}function rv(t){for(const e of document.body.children)e===t||e.tagName==="SCRIPT"||(Ca.set(e,{inert:e.inert,ariaHidden:e.getAttribute("aria-hidden")}),e.inert=!0,e.setAttribute("aria-hidden","true"))}function sv(){for(const[t,e]of Ca)t.inert=e.inert,e.ariaHidden===null?t.removeAttribute("aria-hidden"):t.setAttribute("aria-hidden",e.ariaHidden);Ca.clear()}function Zf(t){return t?.dataset.modalDismissible!=="false"&&t?.getAttribute("aria-busy")!=="true"}function He(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n)return!1;pt&&pt!==n&&We(pt,{restoreFocus:!1,force:!0}),ka=e.trigger||document.activeElement,pt=n,Yf=document.body.style.overflow,rv(n),document.body.style.overflow="hidden",n.classList.add("open"),n.setAttribute("aria-hidden","false");const i=n.querySelector(".modal-content");i&&(i.style.transform="scale(1) translateY(0)");const r=()=>{if(pt!==n)return;((e.initialFocus?n.querySelector(e.initialFocus):n.querySelector("[data-modal-initial-focus]"))||Jf(n)[0]||n.querySelector(".modal-content")||n).focus({preventScroll:!0})};return requestAnimationFrame(r),setTimeout(r,260),!0}function We(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n||!e.force&&!Zf(n))return!1;n.classList.remove("open"),n.setAttribute("aria-hidden","true"),sv(),document.body.style.overflow=Yf,pt=null;const i=ka;return ka=null,e.restoreFocus!==!1&&i?.isConnected&&i.focus({preventScroll:!0}),!0}function Eu(t,e,n="Operation in progress"){const i=typeof t=="string"?document.getElementById(t):t;i&&(i.dataset.modalDismissible=e?"false":"true",i.setAttribute("aria-busy",String(!!e)),e?i.setAttribute("aria-label",n):i.removeAttribute("aria-label"))}function ov(t){if(!Zf(t))return;const e=t.dataset.modalCloseHandler;e&&typeof window[e]=="function"?window[e]():We(t)}document.addEventListener("keydown",t=>{if(!pt)return;if(t.key==="Escape"){t.preventDefault(),t.stopImmediatePropagation(),ov(pt);return}if(t.key!=="Tab"){t.stopPropagation();return}const e=Jf(pt);if(!e.length){t.preventDefault(),(pt.querySelector(".modal-content")||pt).focus();return}const n=e[0],i=e[e.length-1];t.shiftKey&&document.activeElement===n?(t.preventDefault(),i.focus()):!t.shiftKey&&document.activeElement===i&&(t.preventDefault(),n.focus())},!0);function av(){document.querySelectorAll(".modal-overlay").forEach(t=>{t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-hidden",t.classList.contains("open")?"false":"true");const e=t.querySelector(".modal-content");e&&!e.hasAttribute("tabindex")&&(e.tabIndex=-1);const n=t.querySelector("h1, h2, h3");n&&(n.id||(n.id=`${t.id}-title`),t.setAttribute("aria-labelledby",n.id)),t.querySelectorAll(".modal-close").forEach(i=>{i.getAttribute("aria-label")||i.setAttribute("aria-label","Close dialog")})})}const gl=Object.freeze({free:"Free",professional:"Pro",power:"Power"}),lv=Object.freeze({free:2,professional:50,power:2e3}),cv="(contact us)",uv=Object.freeze({free:Object.freeze(["2 generations/month","Gemini model only","Code Review"]),professional:Object.freeze(["50 generations/month","All models","Code Regeneration","Code Review"]),power:Object.freeze(["2000 generations/month","All models","Code Regeneration","Bring your own key (BYOK)","Code Review","All models + early access",`API & MCP access ${cv}`])}),Xf="CodeFile",Qf="GeneratedCode",dv={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function ln(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Aa(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function fv(t={},e=0){const n=Aa(t.artifactType||t.type||Xf),i=Aa(t.artifactName||t.name||t.fileName||`${Qf}-${e+1}`);return`${n||"artifact"}-${i||e+1}`}function eh(t={},e=0){const n=ln(t),i=n.artifactType||n.type||Xf,r=n.artifactName||n.name||Qf;let s=n.fileName||r;return s.endsWith(".dart")||(s+=".dart"),{id:Aa(n.id)||fv({...n,artifactType:i,artifactName:r,fileName:s},e),artifactType:i,artifactName:r,fileName:s,deployPath:n.deployPath||"",description:n.description||"",code:n.code||n.content||"",dependencies:th(n.dependencies),imports:Array.isArray(n.imports)?n.imports:[],publicApi:Array.isArray(n.publicApi)?n.publicApi:[],relationships:nh(n.relationships),deployStatus:n.deployStatus||"pending",review:n.review||null,metadata:ln(n.metadata),codeType:n.codeType||dv[i]||"O"}}function th(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const n=ln(e),i=n.name||n.package;return i?{name:i,version:n.version||null,versionRequired:!!(n.versionRequired||n.required),inferred:!!n.inferred,...n.reason?{reason:n.reason}:{}}:null}).filter(Boolean):Object.entries(ln(t)).map(([e,n])=>({name:e,version:n||null,inferred:!1})):[]}function nh(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const n=ln(e);return!n.from&&!n.to?null:{from:n.from||null,to:n.to||null,type:n.type||"uses",description:n.description||""}}).filter(Boolean):[]}function Pa(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;try{return JSON.parse(e)}catch{const n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(!n)return null;try{return JSON.parse(n[1].trim())}catch{return null}}}function Qi(t,e={}){const n=[],i=typeof t=="string"?Pa(t):t,s=ln(i||{});!i&&typeof t=="string"&&n.push("Structured bundle parse failed; using legacy single-artifact fallback.");const o=Array.isArray(s.artifacts)?s.artifacts:[{artifactType:s.artifactType||e.artifactType,artifactName:s.artifactName||e.artifactName,fileName:s.fileName||e.fileName,description:s.description,code:s.code||e.code||(typeof t=="string"?t:""),dependencies:s.dependencies||e.dependencies,relationships:s.relationships||e.relationships}];o.forEach((d,h)=>{!d?.artifactType&&!d?.type&&n.push(`Artifact ${h+1} has no artifactType; it will deploy as a standalone code file under lib/custom_code/ root.`)});const a=o.map((d,h)=>eh(d,h)),l=new Map(o.map((d,h)=>[ln(d).id,a[h]?.id]).filter(([d,h])=>d&&h)),u=d=>l.get(d)||d,c=nh(s.relationships||e.relationships).map(d=>({...d,from:d.from?u(d.from):d.from,to:d.to?u(d.to):d.to}));return{schemaVersion:s.schemaVersion||e.schemaVersion||null,id:s.id||e.id||"bundle-current",title:s.title||s.name||e.title||"Generated artifact bundle",description:s.description||e.description||"",artifacts:a,dependencies:th(s.dependencies||e.dependencies),relationships:c,deployOrder:Array.isArray(s.deployOrder)?s.deployOrder.map(u):a.map(d=>d.id),warnings:[...n,...Array.isArray(s.warnings)?s.warnings:[]],metadata:ln(s.metadata)}}function oi(t){return Qi(t).artifacts[0]||eh()}function Zt(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function ai(t){return JSON.stringify(t,null,2)}function hv(t){return ai({task:"architect",userRequest:String(t??"")})}function pv(t){const e=Zt(t);return e&&typeof e=="object"&&typeof e.task=="string"?ai(e):ai({task:"generate_bundle",bundleSpec:e})}function gv(t){return ai({task:"review_bundle",generatedBundle:Zt(t),outputRequirements:{bundleReview:["status","score","summary","manualActions","findings"],scoreRange:[0,100],eachArtifact:["id","review.status","review.findings"],manualActions:{definition:"Setup the developer must perform by hand in the FlutterFlow editor that FlutterFlow will NOT do for them.",exclude:["creating the Custom Action, Widget or Code File itself - deploying the code creates it","declaring parameters or return values FlutterFlow derives from the function signature","anything that resolves as a side effect of using the action or widget in the editor","generic advice such as testing, reviewing or rebuilding the app"],preferEmpty:"Return an empty array when nothing qualifies - an empty list is the expected result for most bundles."}}})}function ml(t,e=null){const n={stage:t};return e!=null&&(n.bundle=Zt(e)),n}function mv({bundleSpec:t,artifactBundle:e,bundleReview:n,artifactId:i,userFeedback:r}){return ai({task:"regenerate_artifact",artifactId:i,bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(r)})}function ih({bundleSpec:t,artifactBundle:e,bundleReview:n,userFeedback:i}){return ai({task:"regenerate_bundle",bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(i??"")})}const Su={csam:"child-safety content",dangerous:"dangerous content",harassment:"harassment",hate_speech:"hate speech",maliciousUrls:"a potentially malicious URL",malicious_uris:"a potentially malicious URL",pi_and_jailbreak:"prompt-injection or jailbreak instructions",promptInjection:"prompt-injection or jailbreak instructions",rai:"restricted content",sdp:"sensitive personal data",sexually_explicit:"sexually explicit content",virus_scan:"potentially malicious file content"},vv=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function et(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function _v(t){return et(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||et(t.filterSummary)||et(t.filterResults):!1}function rh(t,e=0){if(!et(t)||e>3)return null;if(_v(t))return t;for(const n of vv){const i=t[n];if(et(i)){const r=rh(i,e+1);if(r)return r}}return null}function ds(t){return Array.isArray(t)?t.some(ds):et(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(ds):!1}function Fa(t){return Array.isArray(t)?t.some(Fa):et(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(Fa):!1}function sh(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function yv(t,e){if(et(t))for(const[n,i]of Object.entries(t)){if(!et(i))continue;const r=et(i.categories)?i.categories:{},s=Object.entries(r).filter(([,o])=>et(o)&&o.matched===!0).map(([o])=>o);s.length>0?s.forEach(o=>e.add(o)):i.matched===!0&&e.add(sh(n))}}function wv(t,e){if(!t)return;const n=Array.isArray(t)?t.flatMap(i=>et(i)?Object.entries(i):[]):Object.entries(t);for(const[i,r]of n){if(!ds(r))continue;const s=sh(i),o=r?.raiFilterResult?.raiFilterTypeResults||(s==="rai"?r?.raiFilterTypeResults:null),a=et(o)?Object.entries(o).filter(([,l])=>ds(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(s)}}function bv(t){return Su[t]?Su[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function xu(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 Ev(t){const e=rh(t);if(!e)return null;const n=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);yv(e.filterSummary,n),wv(e.filterResults,n);const i=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||n.size>0,r=e.invocationResult||null,s=Fa(e.filterSummary||e.filterResults);return!i&&!s&&!["PARTIAL","FAILURE"].includes(r)?null:{kind:i?"blocked":"unavailable",invocationResult:r,matchedFilters:[...n]}}function Sv(t,e){const n=Ev(t);if(!n)return null;const i=[...new Set(n.matchedFilters.map(bv))],r=n.kind==="blocked",s=new Error(r?`Safety screening blocked this pipeline step for ${xu(i)}.`:"Safety screening could not be completed. Please try again.");return s.name="ModelArmorError",s.code=r?"MODEL_ARMOR_BLOCKED":"MODEL_ARMOR_UNAVAILABLE",s.isModelArmor=!0,s.pipelineStep=e,s.userTitle=r?"Request blocked for safety":"Safety check unavailable",s.userMessage=r?`The safety check detected ${xu(i)}. Edit your request to remove or rephrase the flagged content, then run the pipeline again.`:"The safety service did not finish all of its checks. Please wait a moment and run the pipeline again.",s.retryExplanation=r?"Trying another model would not change this safety decision.":"A fallback model was not attempted because safety screening must complete first.",s.matchedFilters=n.matchedFilters,s}function xv(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function Iu(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,n=[];for(const i of xv(t).split(` -`)){if(!/^[A-Za-z_$]/.test(i)||e.test(i))continue;const r=i.match(/^[\w$<>,?\s[\]]+?\s([a-zA-Z_$][\w$]*)\s*\(/);r&&n.push(r[1])}return n}function vl(t,e){const n=t.replace(/\.dart$/,"");if(e==="W")return n.replace(/(^|_)(\w)/g,(i,r,s)=>s.toUpperCase());if(e==="A"){const i=n.replace(/(^|_)(\w)/g,(r,s,o)=>o.toUpperCase());return i.charAt(0).toLowerCase()+i.slice(1)}return e==="F"?"CustomFunctions":e==="C"?t.endsWith(".dart")?t:`${t}.dart`:n}async function ku(t){const e=new TextEncoder().encode(String(t||"")),n=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n),i=>i.toString(16).padStart(2,"0")).join("")}async function Iv(t,e=new Map){const n={},i=new Set;for(const[o,a]of t.entries()){if(a.type==="D"||a.type==="O")continue;const l=vl(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await ku(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await ku(c)),n[o]=u,a.type==="F"){const d=Iu(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(f=>i.add(f))}}const r=new Set(Iu(e.get("lib/flutter_flow/custom_functions.dart")||"")),s={functions_to_rename:[],functions_to_delete:[],functions_to_add:Array.from(i).filter(o=>!r.has(o))};return{fileMapContents:JSON.stringify(n),functionsMapContents:JSON.stringify(s)}}const kv=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),Cu={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},Cv=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),Av=["Struct","Record"],Pv=[{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=>jo(t).some(e=>/\brequired\s+this\.\w+/.test(e)),pos:"class W extends StatefulWidget { const W({required this.value}); final double value; }",neg:`class _P { const _P({required this.t}); final double t; } +(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const s of r)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function n(r){const s={};return r.integrity&&(s.integrity=r.integrity),r.referrerPolicy&&(s.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?s.credentials="include":r.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function i(r){if(r.ep)return;r.ep=!0;const s=n(r);fetch(r.href,s)}})();var w=typeof window<"u"?window:void 0,Ne=typeof globalThis<"u"?globalThis:w,He=Ne?.navigator,P=Ne?.document,me=Ne?.location,Za=Ne?.fetch,zo=Ne!=null&&Ne.XMLHttpRequest&&"withCredentials"in new Ne.XMLHttpRequest?Ne.XMLHttpRequest:void 0,uc=Ne?.AbortController,Mp=Ne?.CompressionStream,Ge=He?.userAgent;function dd(){return!(!w||w.navigator.onLine===!1)}var vi=typeof globalThis<"u"?globalThis:w;vi&&typeof self>"u"&&(vi.self=vi),vi&&typeof File>"u"&&(vi.File=function(){});var B=w??{},ne={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function dc(t,e,n,i,r,s,o){try{var a=t[s](o),l=a.value}catch(u){return void n(u)}a.done?e(l):Promise.resolve(l).then(i,r)}function se(t){return function(){var e=this,n=arguments;return new Promise((function(i,r){var s=t.apply(e,n);function o(l){dc(s,i,r,o,a,"next",l)}function a(l){dc(s,i,r,o,a,"throw",l)}o(void 0)}))}}function I(){return I=Object.assign?Object.assign.bind():function(t){for(var e=1;arguments.length>e;e++){var n=arguments[e];for(var i in n)({}).hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},I.apply(null,arguments)}function fd(t,e){if(t==null)return{};var n={};for(var i in t)if({}.hasOwnProperty.call(t,i)){if(e.indexOf(i)!==-1)continue;n[i]=t[i]}return n}var fc=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function hc(t){return typeof t=="string"||t}function pc(t){return typeof t=="string"?t:void 0}var _i,Lp=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],Ut=(function(t){return t.AnonymousId="anonymous_id",t.DistinctId="distinct_id",t.Props="props",t.EnablePersonProcessing="enable_person_processing",t.PersonMode="person_mode",t.FeatureFlagDetails="feature_flag_details",t.FeatureFlags="feature_flags",t.FeatureFlagPayloads="feature_flag_payloads",t.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",t.BootstrapFeatureFlags="bootstrap_feature_flags",t.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",t.OverrideFeatureFlags="override_feature_flags",t.Queue="queue",t.AiQueue="ai_queue",t.LogsQueue="logs_queue",t.OptedOut="opted_out",t.SessionId="session_id",t.SessionStartTimestamp="session_start_timestamp",t.SessionLastTimestamp="session_timestamp",t.PersonProperties="person_properties",t.GroupProperties="group_properties",t.InstalledAppBuild="installed_app_build",t.InstalledAppVersion="installed_app_version",t.SessionReplay="session_replay",t.PushRegistered="push_registered",t.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",t.SurveyLastSeenDate="survey_last_seen_date",t.SurveysSeen="surveys_seen",t.Surveys="surveys",t.RemoteConfig="remote_config",t.FlagsEndpointWasHit="flags_endpoint_was_hit",t.DeviceId="device_id",t})({}),gc=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),Np=["$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"],Op=["token"],hd="NativeGzipValidationError",qo=t=>t.length>=2&&t[0]===31&&t[1]===139,mc=(t,e)=>t===gc.GZipJS||e===gc.GZipJS||e==="gzip",vc=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",pr=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=hd,e},Bp=(function(){var t=se((function*(e,n){18>e.size&&pr("too-short");var i=new Uint8Array(yield e.slice(0,10).arrayBuffer());qo(i)&&i[2]===8||pr("invalid-header");var r=new DataView(yield e.slice(e.size-8).arrayBuffer());r.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(_i)return _i;_i=[];for(var c=0;256>c;c++){for(var d=c,h=0;8>h;h++)d=1&d?3988292384^d>>>1:d>>>1;_i[c]=d>>>0}return _i})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(n)&&pr("invalid-crc");var s=n.length>>>0;r.getUint32(4,!0)!==s&&pr("invalid-size")}));return function(e,n){return t.apply(this,arguments)}})();function Vo(){return Vo=se((function*(t,e,n){e===void 0&&(e=!0);try{var i=new TextEncoder().encode(t),r=new globalThis.CompressionStream("gzip"),s=r.writable.getWriter(),o=s.write(i).then((()=>s.close())).catch((function(){var u=se((function*(c){try{yield s.abort(c)}catch{}throw c}));return function(c){return u.apply(this,arguments)}})()),a=new Response(r.readable).blob(),l=(yield Promise.all([a,o]))[0];return yield Bp(l,i),l}catch(u){if(n!=null&&n.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),Vo.apply(this,arguments)}var Dp=["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"],_c=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var n=t.toLowerCase();return Dp.concat(e).some((i=>{var r=i.toLowerCase();return n.indexOf(r)!==-1}))};function j(t,e){return t.indexOf(e)!==-1}var xs=function(t){return t.trim()},Go=function(t){return t.replace(/^\$/,"")};function pd(t){var e,n=[];return(e=JSON.stringify(t,(function(i,r){if(typeof r=="bigint")return r.toString();if(typeof r!="function"&&typeof r!="symbol"){if(r instanceof Error)return{name:r.name,message:r.message,stack:r.stack};if(r&&typeof r=="object"){for(;n.length>0&&n[n.length-1]!==this;)n.pop();if(n.includes(r))return"[Circular]";n.push(r)}return r}})))!==null&&e!==void 0?e:"null"}var gd=Object.prototype,md=gd.hasOwnProperty,Is=gd.toString,U=Array.isArray||function(t){return Is.call(t)==="[object Array]"},je=t=>typeof t=="function",he=t=>t===Object(t)&&!U(t),Kt=t=>{if(he(t)){for(var e in t)if(md.call(t,e))return!1;return!0}return!1},C=t=>t===void 0,X=t=>Is.call(t)=="[object String]",Ko=t=>X(t)&&t.trim().length===0,Ye=t=>t===null,H=t=>C(t)||Ye(t),ke=t=>Is.call(t)=="[object Number]"&&t==t,Dt=t=>ke(t)&&t>0,mt=t=>Is.call(t)==="[object Boolean]",jp=t=>t instanceof FormData,Up=t=>j(Np,t),Hp=t=>j(Op,t);function vd(t){return t===null||typeof t!="object"}function Hr(t,e){return{}.toString.call(t)==="[object "+e+"]"}function Xa(t){return typeof Event<"u"&&_d(t,Event)}function _d(t,e){try{return t instanceof e}catch{return!1}}var Wp=[!0,"true",1,"1","yes"],uo=t=>j(Wp,t),zp=[!1,"false",0,"0","no"];function At(t,e,n,i,r){return e>n&&(i.warn("min cannot be greater than max."),e=n),ke(t)?t>n?(i.warn(" cannot be greater than max: "+n+". Using max value instead."),n):e>t?(i.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(i.warn(" must be a number. using max or fallback. max: "+n+", fallback: "+r),At(r||n,e,n,i))}class qp{constructor(e){this.tt={},this.et=e.et,this.it=At(e.bucketSize,0,100,e.rt),this.nt=At(e.refillRate,0,this.it,e.rt),this.st=At(e.refillInterval,0,864e5,e.rt)}ot(e,n){var i=Math.floor((n-e.lastAccess)/this.st);i>0&&(e.tokens=Math.min(e.tokens+i*this.nt,this.it),e.lastAccess=e.lastAccess+i*this.st)}consumeRateLimit(e){var n,i=Date.now(),r=String(e),s=this.tt[r];return s?this.ot(s,i):this.tt[r]=s={tokens:this.it,lastAccess:i},s.tokens===0||(s.tokens--,s.tokens===0&&((n=this.et)==null||n.call(this,e)),s.tokens===0)}stop(){this.tt={}}}var rt="Mobile",Wr="iOS",Yt="Android",ei="Tablet",yd=Yt+" "+ei,wd="iPad",bd="Apple",Ed=bd+" Watch",Bi="Safari",ti="BlackBerry",Sd="Samsung",xd=Sd+"Browser",Id=Sd+" Internet",Pn="Chrome",Vp=Pn+" OS",kd=Pn+" "+Wr,Qa="Internet Explorer",Cd=Qa+" "+rt,el="Opera",Gp=el+" Mini",tl="Edge",Ad="Microsoft "+tl,Zn="Firefox",Pd=Zn+" "+Wr,Gi="Nintendo",Ki="PlayStation",Xn="Xbox",Fd=Yt+" "+rt,Rd=rt+" "+Bi,Pi="Windows",Yo=Pi+" Phone",yc="Nokia",Jo="Ouya",Td="Generic",Kp=Td+" "+rt.toLowerCase(),$d=Td+" "+ei.toLowerCase(),Zo="Konqueror",Md="Oculus Browser",zr="Vivaldi",Ld="Yandex",qr="Whale",Xo="DuckDuckGo",Nd="Pale Moon",Vr="Waterfox",Di="Brave",Od="Google Search App",we="(\\d+(\\.\\d+)?)",fo=new RegExp("Version/"+we),Yp=new RegExp(Xn,"i"),Jp=new RegExp(Ki+" \\w+","i"),Zp=new RegExp(Gi+" \\w+","i"),nl=new RegExp(ti+"|PlayBook|BB10","i"),Xp={"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"},Bd=function(t,e,n,i){e=e||"";var r=(function(s){return s!=null&&s.brave?Di:null})(n);return r||(i!=null&&i.detectGoogleSearchApp&&j(t,"GSA/")?Od:j(t," OPR/")&&j(t,"Mini")?Gp:j(t," OPR/")?el:nl.test(t)?ti:j(t,"IE"+rt)||j(t,"WPDesktop")?Cd:j(t,"OculusBrowser")?Md:j(t,xd)?Id:j(t,tl)||j(t,"Edg/")?Ad:j(t,zr+"/")?zr:j(t,"YaBrowser/")?Ld:j(t,qr+"/")?qr:j(t,Xo+"/")||j(t,"Ddg/")?Xo:j(t,"FBIOS")?"Facebook "+rt:j(t,"UCWEB")||j(t,"UCBrowser")?"UC Browser":j(t,"CriOS")?kd:j(t,"CrMo")||j(t,Pn)?Pn:j(t,Yt)&&j(t,Bi)?Fd:j(t,"FxiOS")?Pd:j(t.toLowerCase(),Zo.toLowerCase())?Zo:j(t,Di+"/")?Di:((s,o)=>o&&j(o,bd)||(function(a){return j(a,Bi)&&!j(a,Pn)&&!j(a,Yt)})(s))(t,e)?j(t,rt)?Rd:Bi:j(t,"PaleMoon/")?Nd:j(t,Vr+"/")?Vr:j(t,Zn)?Zn:j(t,"MSIE")||j(t,"Trident/")?Qa:j(t,"Gecko")?Zn:"")},Qp={[Cd]:[new RegExp("rv:"+we)],[Ad]:[new RegExp(tl+"?\\/"+we)],[Pn]:[new RegExp("("+Pn+"|CrMo)\\/"+we)],[kd]:[new RegExp("CriOS\\/"+we)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+we)],[Bi]:[fo],[Rd]:[fo],[el]:[new RegExp("(Opera|OPR)\\/"+we)],[Zn]:[new RegExp(Zn+"\\/"+we)],[Pd]:[new RegExp("FxiOS\\/"+we)],[Zo]:[new RegExp("Konqueror[:/]?"+we,"i")],[ti]:[new RegExp(ti+" "+we),fo],[Fd]:[new RegExp("android\\s"+we,"i")],[Id]:[new RegExp(xd+"\\/"+we)],[Md]:[new RegExp("OculusBrowser\\/"+we)],[zr]:[new RegExp(zr+"\\/"+we)],[Ld]:[new RegExp("YaBrowser\\/"+we)],[qr]:[new RegExp(qr+"\\/"+we)],[Di]:[new RegExp(Di+"\\/"+we)],[Xo]:[new RegExp("(DuckDuckGo|Ddg)\\/"+we)],[Nd]:[new RegExp("PaleMoon\\/"+we)],[Vr]:[new RegExp(Vr+"\\/"+we)],[Od]:[new RegExp("GSA\\/"+we)],[Qa]:[new RegExp("(rv:|MSIE )"+we)],Mozilla:[new RegExp("rv:"+we)]},eg=function(t,e,n,i){var r=Bd(t,e,n,i),s=Qp[r];if(C(s))return null;for(var o=0;s.length>o;o++){var a=t.match(s[o]);if(a)return parseFloat(a[a.length-2])}return null},wc=[[new RegExp(Xn+"; "+Xn+" (.*?)[);]","i"),t=>[Xn,t&&t[1]||""]],[new RegExp(Gi,"i"),[Gi,""]],[new RegExp(Ki,"i"),[Ki,""]],[nl,[ti,""]],[new RegExp(Pi,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Yo,""];if(new RegExp(rt).test(e)&&!/IEMobile\b/.test(e))return[Pi+" "+rt,""];var n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){var i=Xp[n[1]]||"";return/arm/i.test(e)&&(i="RT"),[Pi,i]}return[Pi,""]}],[/((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=C(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+Yt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Yt+")","i"),t=>t&&t[2]?[Yt,[t[2],t[3],t[4]||"0"].join(".")]:[Yt,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{var e=["Mac OS X",""];return t&&t[1]&&(e[1]=[t[1],t[2],t[3]||"0"].join(".")),e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[Vp,""]],[/Linux|debian/i,["Linux",""]]],bc=function(t){return Zp.test(t)?Gi:Jp.test(t)?Ki:Yp.test(t)?Xn:new RegExp(Jo,"i").test(t)?Jo:new RegExp("("+Yo+"|WPDesktop)","i").test(t)?Yo:/iPad/.test(t)?wd:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?Ed:nl.test(t)?ti:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(yc,"i").test(t)?yc:/(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(rt).test(t)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(t)||/pixel[\daxl ]{1,6}/i.test(t)&&!/pixel c/i.test(t)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(t)||/lmy47v/i.test(t)&&!/QTAQZ3/i.test(t)?Yt:yd:new RegExp("(pda|"+rt+")","i").test(t)?Kp:new RegExp(ei,"i").test(t)&&!new RegExp(ei+" pc","i").test(t)?$d:""},tg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ec(t,e){return typeof(n=t)=="string"&&tg.test(n)?t:e();var n}function fn(t){return t&&t.split("#")[0]}function il(t,e){var n=setTimeout(t,e);return n?.unref&&n?.unref(),n}function Sc(t,e,n){return Dd.apply(this,arguments)}function Dd(){return(Dd=se((function*(t,e,n){var i;try{return yield Promise.race([t,new Promise(((r,s)=>{i=il((()=>{try{n?.(),r()}catch(o){s(o)}}),e)}))])}finally{clearTimeout(i)}}))).apply(this,arguments)}var ng=t=>t instanceof Error,jd={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}},ig=jd.info;function Ud(t){if(mt(t))return{boolValue:t};if(typeof t=="number")return Number.isFinite(t)?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:{stringValue:String(t)};if(typeof t=="string")return{stringValue:t};if(U(t))return{arrayValue:{values:t.map((e=>Ud(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function Gr(t){var e=[];for(var n in t){var i=t[n];Ye(i)||C(i)||e.push({key:n,value:Ud(i)})}return e}function rg(t,e){var n=jd[t.level||"info"]||ig,i=n.text,r=n.number,s=String(Date.now())+"000000",o={};e.distinctId&&(o.posthogDistinctId=e.distinctId),e.sessionId&&(o.sessionId=e.sessionId),e.windowId&&(o["window.id"]=e.windowId),H(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),H(e.lastActivityTimestamp)||(o.lastActivityTimestamp=String(e.lastActivityTimestamp)),e.currentUrl&&(o["url.full"]=e.currentUrl),e.screenName&&(o["screen.name"]=e.screenName),e.appState&&(o["app.state"]=e.appState),e.activeFeatureFlags&&e.activeFeatureFlags.length>0&&(o.feature_flags=e.activeFeatureFlags);var a=I({},o,t.attributes||{}),l={timeUnixNano:s,observedTimeUnixNano:s,severityNumber:r,severityText:i,body:{stringValue:t.body},attributes:Gr(a)};return t.trace_id&&(l.traceId=t.trace_id),t.span_id&&(l.spanId=t.span_id),C(t.trace_flags)||(l.flags=t.trace_flags),l}function Hd(t,e,n){return I({},t.resourceAttributes,{"service.name":t.serviceName||"unknown_service"},t.environment&&{"deployment.environment":t.environment},t.serviceVersion&&{"service.version":t.serviceVersion},{"telemetry.sdk.name":e,"telemetry.sdk.version":n})}function Wd(t,e,n,i){return{resourceLogs:[{resource:{attributes:Gr(e)},scopeLogs:[{scope:{name:n,version:i},logRecords:t}]}]}}let sg=class{constructor(t,e,n,i,r,s,o){var a;s===void 0&&(s=()=>Promise.resolve()),this._instance=t,this.Ne=e,this.rt=n,this.ut=i,this.ht=r,this.dt=s,this.vt=o,this.ct=null,this.ft=0,this.yt=0,this.bt=0,this._t=0,this.wt=!1,this.kt=e.maxBufferSize,this.xt=Math.max((a=e.maxQueueSize)!==null&&a!==void 0?a:e.maxBufferSize,e.maxBufferSize),this.St=e.flushIntervalMs,this.Ct=e.maxBatchRecordsPerPost,this.Mt=e.rateCapWindowMs,this.Tt=e.maxLogsPerInterval}reset(){this.Et(),this.ct=null,this.bt=0,this._t=0,this.wt=!1,this.ft=0,this.yt=0,this.Ct=this.Ne.maxBatchRecordsPerPost}onReconnect(){this.yt=0,this.It()}captureLog(t){if(!this._instance.isDisabled&&!this._instance.optedOut&&t!=null&&t.body){var e=this.Pt(t);if(e!==null)if(e.body){if(this.Rt()){var n={record:rg(e,this.ut())};this.ht((()=>this.At(n)))}}else this.rt.info("Log was rejected in beforeSend function")}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Log was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for log:",o),null}return i}Rt(){if(this.Tt===void 0)return!0;var t=Date.now(),e=t-this.bt;return this.Mt>e&&e>=0||(this.bt=t,this._t=0,this.wt=!1),this.Tt>this._t?(this._t++,!0):(this.wt||(this.rt.warn("captureLog dropping logs: exceeded "+this.Tt+" logs per "+this.Mt+"ms"),this.wt=!0),!1)}flush(){var t=this;return se((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return se((function*(){var e;t.Et();var n=(e=t._instance.getPersistedProperty(Ut.LogsQueue))!==null&&e!==void 0?e:[];if(n.length!==0)for(var i=n.length,r=0;n.length>0&&i>r;){var s,o;t.ft=0;var a=Math.min(n.length,t.Ct),l=n.slice(0,a),u=Wd(l.map((d=>d.record)),t.Lt(),(s=t.vt)!==null&&s!==void 0?s:t._instance.getLibraryId(),t._instance.getLibraryVersion()),c=yield t._instance.Ot(u);if(c.kind==="too-large"&&l.length>1)t.Ct=Math.max(1,Math.floor(l.length/2)),t.rt.warn("Received 413 when sending logs batch of size "+l.length+", reducing batch size to "+t.Ct);else if(c.kind==="retry-later"||(c.kind==="too-large"?t.rt.warn("Dropping a single log record after 413 with batch size 1 — the record is larger than the server cap and cannot be split further."):c.kind==="ok"&&t.Ne.maxBatchRecordsPerPost>t.Ct&&(t.Ct=Math.min(t.Ne.maxBatchRecordsPerPost,t.Ct+1)),yield t.Dt(l.length),n=(o=t._instance.getPersistedProperty(Ut.LogsQueue))!==null&&o!==void 0?o:[],r+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return se((function*(){var n,i=Math.max(0,t-e.ft),r=(n=e._instance.getPersistedProperty(Ut.LogsQueue))!==null&&n!==void 0?n:[];e._instance.setPersistedProperty(Ut.LogsQueue,r.slice(i)),yield e.dt()}))()}Lt(){return Hd(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var n=(e=this._instance.getPersistedProperty(Ut.LogsQueue))!==null&&e!==void 0?e:[];this.xt>n.length||(n.shift(),this.ft++,this.rt.info("Logs queue is full, dropping oldest record.")),n.push(t),this._instance.setPersistedProperty(Ut.LogsQueue,n),this.kt>n.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=il((()=>{this.Nt=void 0,this.It()}),t))}qt(){var t=Math.min(Math.max(0,this.yt-1),6);return this.St*Math.pow(2,t)}jt(){var t=this._instance.getPersistedProperty(Ut.LogsQueue);return!!t&&t.length>0}shutdown(t){var e=this;return se((function*(){e.Et();var n=e.flush().catch((()=>{}));t!==void 0?yield Sc(n,t):yield n}))()}flushWithTimeout(t){var e=this;return se((function*(){var n=e.flush();yield Sc(n,t,(()=>{n.catch((()=>{}))}))}))()}It(){this.flush().then((()=>{this.yt=0}),(t=>{this.yt++,this.rt.error("PostHog logs flush failed:",t)})).finally((()=>{!this._instance.isDisabled&&this.jt()&&this.$t(this.qt())}))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}};var ho=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function xc(t){return String(t)+"000000"}function Ic(t,e,n,i){var r="";return i&&(r=Object.keys(i).sort().map((s=>JSON.stringify(s)+":"+JSON.stringify(i[s]))).join(",")),t+"\0"+e+"\0"+(n??"")+"\0"+r}let og=class{constructor(t,e,n){this._instance=t,this.Ne=e,this.rt=n,this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Wt=0}count(t,e,n){e===void 0&&(e=1),this.Vt({name:t,type:"count",value:e,unit:n?.unit,attributes:n?.attributes})}gauge(t,e,n){this.Vt({name:t,type:"gauge",value:e,unit:n?.unit,attributes:n?.attributes})}histogram(t,e,n){this.Vt({name:t,type:"histogram",value:e,unit:n?.unit,attributes:n?.attributes})}flush(){var t=this,e=this.ct,n=(function(){var r=se((function*(){e&&(yield e.catch((()=>{}))),yield t.Zt()}));return function(){return r.apply(this,arguments)}})(),i=n().finally((()=>{this.ct===i&&(this.ct=null)}));return this.ct=i,i}drainWindow(){if(this.Bt.size===0)return null;var t=this.Bt;return this.Bt=new Map,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Gt(t)}reset(){this.Wt++,this.Et(),this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set}Vt(t){if(!this._instance.isDisabled&&!this._instance.optedOut){var e=this.Pt(t);if(e!==null)if(e.name&&typeof e.name=="string")if(typeof e.value=="number"&&Number.isFinite(e.value))if(e.type==="count"&&0>e.value)this.rt.warn("Dropping count '"+e.name+"': counters are monotonic, value must be >= 0");else{var n,i;try{n=e.attributes?I({},e.attributes):void 0,i=Ic(e.type,e.name,e.unit,n)}catch(o){return void this.rt.warn("Dropping metric '"+e.name+"': attributes could not be serialized",o)}var r=this.Bt.get(i);if(!r){if(!this.Qt())return;r={name:e.name,type:e.type,unit:e.unit,attributes:n,windowStartMs:Date.now()},this.Bt.set(i,r)}var s=this.Ut.get(e.name);s===void 0?this.Ut.set(e.name,e.type):s===e.type||this.zt.has(e.name)||(this.zt.add(e.name),this.rt.warn("Metric name '"+e.name+"' is already used as a "+s+"; recording it as a "+e.type+" too will blend both series in charts. Use a distinct name.")),this.Kt(r,e.value),this.$t()}else this.rt.warn("Dropping metric '"+e.name+"': value must be a finite number");else this.rt.warn("Dropping metric with empty name")}}Qt(){return this.Ne.maxSeriesPerFlush>this.Bt.size||(this.Ht||(this.Ht=!0,this.rt.warn("Metric series cap reached ("+this.Ne.maxSeriesPerFlush+" per flush window); dropping new series until the next flush. Reduce attribute cardinality.")),!1)}Kt(t,e){var n;switch(t.type){case"count":t.total=((n=t.total)!==null&&n!==void 0?n:0)+e;break;case"gauge":t.last=e;break;case"histogram":t.hist||(t.hist={count:0,sum:0,min:e,max:e,bucketCounts:new Array(ho.length+1).fill(0)});var i=t.hist;i.count+=1,i.sum+=e,i.min=Math.min(i.min,e),i.max=Math.max(i.max,e),i.bucketCounts[(function(r,s){for(var o=0;s.length>o;o++)if(s[o]>=r)return o;return s.length})(e,ho)]+=1}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Metric was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for metric:",o),null}return i}$t(){this.Nt||(this.Nt=il((()=>{this.Nt=void 0,this.flush().catch((t=>{this.rt.error("Metrics flush failed:",t)}))}),this.Ne.flushIntervalMs))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}Zt(){var t=this;return se((function*(){if(t.Bt.size!==0){var e=t.Bt;t.Bt=new Map,t.Ht=!1,t.Ut=new Map,t.zt=new Set;var n=t.Wt,i=yield t._instance.Jt(t.Gt(e));if(n===t.Wt)switch(i.kind){case"ok":return;case"retry-later":return t.Yt(e),void t.$t();case"too-large":return void t.rt.warn("Metrics batch exceeded the server size limit and was dropped");case"fatal":return void t.rt.error("Failed to send metrics batch:",i.error)}}}))()}Gt(t){return e=this.Xt(t),n=(function(s,o,a){return I({},s.resourceAttributes,{"service.name":s.serviceName||"unknown_service"},s.environment&&{"deployment.environment":s.environment},s.serviceVersion&&{"service.version":s.serviceVersion},{"telemetry.sdk.name":o,"telemetry.sdk.version":a})})(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion()),i=this._instance.getLibraryId(),r=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:Gr(n)},scopeMetrics:[{scope:{name:i,version:r},metrics:e}]}]};var e,n,i,r}Xt(t){var e=xc(Date.now()),n=new Map;for(var i of t.values()){var r,s=Ic(i.type,i.name,i.unit,void 0),o=n.get(s);o||(o=I({name:i.name},i.unit&&{unit:i.unit}),i.type==="count"?o.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:i.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:1,dataPoints:[]},n.set(s,o));var a=Gr((r=i.attributes)!==null&&r!==void 0?r:{}),l=xc(i.windowStartMs);if(i.type==="count"){var u,c={attributes:a,startTimeUnixNano:l,timeUnixNano:e,asDouble:(u=i.total)!==null&&u!==void 0?u:0};o.sum.dataPoints.push(c)}else if(i.type==="gauge"){var d,h={attributes:a,timeUnixNano:e,asDouble:(d=i.last)!==null&&d!==void 0?d:0};o.gauge.dataPoints.push(h)}else i.hist&&o.histogram.dataPoints.push({attributes:a,startTimeUnixNano:l,timeUnixNano:e,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:ho})}return Array.from(n.values())}Yt(t){var e,n;for(var i of t){var r=i[0],s=i[1],o=this.Bt.get(r);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,s.windowStartMs),o.type){case"count":o.total=((e=o.total)!==null&&e!==void 0?e:0)+((n=s.total)!==null&&n!==void 0?n:0);break;case"gauge":break;case"histogram":if(s.hist)if(o.hist){o.hist.count+=s.hist.count,o.hist.sum+=s.hist.sum,o.hist.min=Math.min(o.hist.min,s.hist.min),o.hist.max=Math.max(o.hist.max,s.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=s.hist.bucketCounts[a]}else o.hist=s.hist}else this.Qt()&&this.Bt.set(r,s)}}};var gr,kc,po;function ag(t){var e=globalThis._posthogChunkIds;if(e){var n=Object.keys(e);return po&&n.length===kc||(kc=n.length,po=n.reduce(((i,r)=>{gr||(gr={});var s=gr[r];if(s)i[s[0]]=s[1];else for(var o=t(r),a=o.length-1;a>=0;a--){var l=o[a],u=l?.filename,c=e[r];if(u&&c){i[u]=c,gr[r]=[u,c];break}}return i}),{})),po}}class lg{constructor(e,n,i){i===void 0&&(i=[]),this.coercers=e,this.stackParser=n,this.modifiers=i}buildFromUnknown(e,n){n===void 0&&(n={});var i=n&&n.mechanism||{handled:!0,type:"generic"},r=this.buildCoercingContext(i,n,0).apply(e),s=this.buildParsingContext(n),o=this.parseStacktrace(r,s);return{$exception_list:this.convertToExceptionList(o,i),$exception_level:"error"}}modifyFrames(e){var n=this;return se((function*(){for(var i of e)i.stacktrace&&i.stacktrace.frames&&U(i.stacktrace.frames)&&(i.stacktrace.frames=yield n.applyModifiers(i.stacktrace.frames));return e}))()}coerceFallback(e){var n;return{type:"Error",value:"Unknown error",stack:(n=e.syntheticException)==null?void 0:n.stack,synthetic:!0}}parseStacktrace(e,n){var i,r;return e.cause!=null&&(i=this.parseStacktrace(e.cause,n)),e.stack!=""&&e.stack!=null&&(r=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?n.skipFirstLines:0),n.chunkIdMap)),I({},e,{cause:i,stack:r})}applyChunkIds(e,n){return e.map((i=>(i.filename&&n&&(i.chunk_id=n[i.filename]),i)))}applyCoercers(e,n){for(var i of this.coercers)if(i.match(e))return i.coerce(e,n);return this.coerceFallback(n)}applyModifiers(e){var n=this;return se((function*(){var i=e;for(var r of n.modifiers)i=yield r(i);return i}))()}convertToExceptionList(e,n){var i,r,s,o={type:e.type,value:e.value,mechanism:{type:(i=n.type)!==null&&i!==void 0?i:"generic",handled:(r=n.handled)===null||r===void 0||r,synthetic:(s=e.synthetic)!==null&&s!==void 0&&s}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,I({},n,{handled:!0}))),a}buildParsingContext(e){var n;return{chunkIdMap:ag(this.stackParser),skipFirstLines:(n=e.skipFirstLines)!==null&&n!==void 0?n:1}}buildCoercingContext(e,n,i){i===void 0&&(i=0);var r=(s,o)=>{if(4>=o){var a=this.buildCoercingContext(e,n,o);return this.applyCoercers(s,a)}};return I({},n,{syntheticException:i==0?n.syntheticException:void 0,mechanism:e,apply:s=>r(s,i),next:s=>r(s,i+1)})}}var ni="?";function Qo(t,e,n,i,r){var s={platform:t,filename:e,function:n===""?ni:n,in_app:!0};return C(i)||(s.lineno=i),C(r)||(s.colno=r),s}var zd=(t,e)=>{var n=t.indexOf("safari-extension")!==-1,i=t.indexOf("safari-web-extension")!==-1;return n||i?[t.indexOf("@")!==-1?t.split("@")[0]:ni,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},cg=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,ug=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,dg=/\((\S*)(?::(\d+))(?::(\d+))\)/,fg=(t,e)=>{var n=cg.exec(t);if(n)return Qo(e,n[1],ni,+n[2],+n[3]);var i=ug.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var r=dg.exec(i[2]);r&&(i[2]=r[1],i[3]=r[2],i[4]=r[3])}var s=zd(i[1]||ni,i[2]);return Qo(e,s[1],s[0],i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},hg=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,pg=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,gg=(t,e)=>{var n=hg.exec(t);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){var i=pg.exec(n[3]);i&&(n[1]=n[1]||"eval",n[3]=i[1],n[4]=i[2],n[5]="")}var r=n[3],s=n[1]||ni,o=zd(s,r);return Qo(e,r=o[1],s=o[0],n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},Cc=/\(error: (.*)\)/;class mg{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,n){var i=X(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:i?e.stack:void 0,cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var n=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?n+": "+e.message:n}isDOMException(e){return Hr(e,"DOMException")}isDOMError(e){return Hr(e,"DOMError")}}class vg{match(e){return(function(n){switch({}.toString.call(n)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return _d(n,Error)}})(e)}coerce(e,n){return{type:this.getType(e),value:this.getMessage(e,n),stack:this.getStack(e),cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,n){var i=e.message;return String(i.error&&typeof i.error.message=="string"?i.error.message:i)}getStack(e){return e.stacktrace||e.stack||void 0}}class _g{constructor(){}match(e){return!!Hr(e,"ErrorEvent")&&(e.error!=null||this.fe(e))}coerce(e,n){var i;if(e.error!=null)return n.apply(e.error);var r=n.apply(e.message);return I({},r,{stack:(i=this.pe(e))!==null&&i!==void 0?i:r.stack,synthetic:!0})}fe(e){return X(e.message)&&e.message.length>0}pe(e){var n=e;if(X(n.filename)&&n.filename.length>0){var i,r,s=(i=n.lineno)!==null&&i!==void 0?i:0,o=(r=n.colno)!==null&&r!==void 0?r:0;return`Error + at `+n.filename+":"+s+":"+o}}}var yg=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class wg{match(e){return typeof e=="string"}coerce(e,n){var i,r=this.getInfos(e),s=r[0],o=r[1];return{type:s??"Error",value:o??e,stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}getInfos(e){var n="Error",i=e,r=e.match(yg);return r&&(n=r[1],i=r[2]),[n,i]}}var bg=["fatal","error","warning","log","info","debug"];function qd(t,e){e===void 0&&(e=40);var n=Object.keys(t);if(n.sort(),!n.length)return"[object has no keys]";for(var i=n.length;i>0;i--){var r=n.slice(0,i).join(", ");if(e>=r.length)return i===n.length?r:r.length>e?r.slice(0,e)+"...":r}return""}class Eg{match(e){return typeof e=="object"&&e!==null}coerce(e,n){var i,r,s=this.getErrorPropertyFromObject(e);return s?n.apply(s):{type:this.getType(e),value:this.getValue(e),stack:(i=this.getStack(e))!==null&&i!==void 0?i:(r=n.syntheticException)==null?void 0:r.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return Xa(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var n="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(n+=" with message: '"+e.message+"'"),n}if("message"in e&&typeof e.message=="string")return e.message;var i=this.getObjectClassName(e);return(i&&i!=="Object"?"'"+i+"'":"Object")+" captured as exception with keys: "+qd(e)}isSeverityLevel(e){return X(e)&&!Ko(e)&&bg.indexOf(e)>=0}getStack(e){try{return X(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:X(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(var n in e)if({}.hasOwnProperty.call(e,n)){var i=e[n];if(ng(i))return i}}getObjectClassName(e){try{var n=Object.getPrototypeOf(e);return n?n.constructor.name:void 0}catch{return}}}class Sg{match(e){return Xa(e)}coerce(e,n){var i,r=e.constructor.name;return{type:r,value:r+" captured as exception with keys: "+qd(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class xg{match(e){return vd(e)}coerce(e,n){var i;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class Ig{match(e){return Hr(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Xa(e))return!1;try{var n=e.detail;return n!=null&&typeof n=="object"&&"reason"in n}catch{return!1}}coerce(e,n){var i,r=this.getUnhandledRejectionReason(e);return vd(r)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(r),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}:n.apply(r)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}}var Kr="$message",Yr="$timestamp",kg=new Set([Kr,Yr]),go={enabled:!0,max_bytes:32768};function Jr(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:go.enabled,max_bytes:Ag(t.max_bytes,go.max_bytes)}:I({},go)}class Cg{constructor(e){this.Ke=[],this.Je=0,this.Ne=Jr(e)}setConfig(e){this.Ne=Jr(e),this.Xe()}add(e){var n=(function(r){var s;try{s=pd(r)}catch{return}try{var o=JSON.parse(s);if(!he(o))return;var a=o,l=a[Kr],u=a[Yr];return!X(l)||l.trim().length===0||!X(u)&&!ke(u)?void 0:{step:a,json:s}}catch{return}})(e);if(n){var i=(function(r){if(typeof TextEncoder<"u")return new TextEncoder().encode(r).length;for(var s=encodeURIComponent(r),o=0,a=0;s.length>a;a++)s[a]==="%"?(o+=1,a+=2):o+=1;return o})(n.json);i>this.Ne.max_bytes||(this.Ke.push({step:n.step,bytes:i}),this.Je+=i,this.Xe())}}getAttachable(){return this.Ke.map((e=>e.step))}clear(){this.Ke=[],this.Je=0}size(){return this.Ke.length}Xe(){for(;this.Je>this.Ne.max_bytes&&this.Ke.length>0;){var e=this.Ke.shift();e&&(this.Je-=e.bytes)}}}function Ag(t,e){if(!ke(t)||t===1/0||t===-1/0)return e;var n=Math.floor(t);return 0>n?e:n}var Vd=function(t,e){var n=(e===void 0?{}:e).debugEnabled,i={k(r){if(w&&(ne.DEBUG||w.POSTHOG_DEBUG||n)&&!C(w.console)&&w.console){for(var s=("__rrweb_original__"in w.console[r])?w.console[r].__rrweb_original__:w.console[r],o=arguments.length,a=new Array(o>1?o-1:0),l=1;o>l;l++)a[l-1]=arguments[l];s(t,...a)}},debug(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("debug",...s)},info(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("log",...s)},warn(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("warn",...s)},error(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("error",...s)},critical(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];console.error(t,...s)},uninitializedWarning(r){i.error("You must initialize PostHog before calling "+r)},createLogger:(r,s)=>Vd(t+" "+r,s)};return i},A=Vd("[PostHog.js]"),pe=A.createLogger,Pg=pe("[ExternalScriptsLoader]"),mo=(t,e,n)=>{if(t.config.disable_external_dependency_loading)return Pg.warn(e+" was requested but loading of external scripts is disabled."),n("Loading of external scripts is disabled");var i=P?.querySelectorAll("script");if(i){for(var r,s=function(){if(i[o].src===e){var l=i[o];return l.__posthog_loading_callback_fired?{v:n()}:(l.addEventListener("load",(u=>{l.__posthog_loading_callback_fired=!0,n(void 0,u)})),l.onerror=u=>n(u),{v:void 0})}},o=0;i.length>o;o++)if(r=s())return r.v}var a=()=>{if(!P)return n("document not found");var l=P.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=d=>{l.__posthog_loading_callback_fired=!0,n(void 0,d)},l.onerror=d=>n(d),t.config.prepare_external_dependency_script&&(l=t.config.prepare_external_dependency_script(l)),!l)return n("prepare_external_dependency_script returned null");if(t.config.external_scripts_inject_target==="head")P.head.appendChild(l);else{var u,c=P.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):P.body.appendChild(l)}};P!=null&&P.body?a():P?.addEventListener("DOMContentLoaded",a)};B.__PosthogExtensions__=B.__PosthogExtensions__||{},B.__PosthogExtensions__.loadExternalDependency=(t,e,n)=>{if(e!=="remote-config"){var i;if(t.config.strict_script_versioning)i=t.requestRouter.endpointFor("assets","/static/"+t.version+"/"+e+".js");else{var r="/static/"+e+".js?v="+t.version;if(e==="toolbar"){var s=3e5;r=r+"&t="+Math.floor(Date.now()/s)*s}i=t.requestRouter.endpointFor("assets",r)}mo(t,i,n)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");mo(t,o,n)}},B.__PosthogExtensions__.loadSiteApp=(t,e,n)=>{var i=t.requestRouter.endpointFor("api",e);mo(t,i,n)};ne.DEBUG=!1,ne.LIB_VERSION="1.415.7",ne.LIB_NAME="web";var Gd="$people_distinct_id",Yi="$device_id",vo="$device_model",Fi="__alias",Ri="__timers",ea="$autocapture_disabled_server_side",ta="$heatmaps_enabled_server_side",na="$exception_capture_enabled_server_side",ia="$error_tracking_suppression_rules",ra="$error_tracking_capture_extension_exceptions",sa="$web_vitals_enabled_server_side",rl="$dead_clicks_enabled_server_side",sl="$product_tours_enabled_server_side",oa="$web_vitals_allowed_metrics",An="$session_recording_remote_config",Kd="$replay_sample_rate",Yd="$replay_override_sampling",Jd="$replay_override_linked_flag",Zd="$replay_override_url_trigger",Xd="$replay_override_event_trigger",Kn="$sesid",ol="$session_is_sampled",Sn="$enabled_feature_flags",Ti="$active_feature_flags",Ar="$early_access_features",aa="$feature_flag_details",$i="$feature_flag_payloads",Pr="$feature_flag_request_id",Zr="$minimal_flag_called_events",It="$override_feature_flags",xn="$override_feature_flag_payloads",jt="$stored_person_properties",In="$stored_group_properties",la="$surveys",Xr="$surveys_loaded_at",ca="$surveys_activated",Fr="$surveys_activated_session",Rr="$surveys_activated_timestamps",Mi="ph_product_tours",Cn="$flag_call_reported",Li="$flag_call_reported_session_id",Tr="$feature_flag_errors",ji="$feature_flag_evaluated_at",at="$user_state",ua="$client_session_props",da="$capture_rate_limit",fa="$initial_campaign_params",ha="$initial_referrer_info",Qr="$initial_person_info",es="$epp",mr="$posthog_cookieless",Qd="$cookieless_mode",ef="$sdk_debug_extensions_init_method",tf="$sdk_debug_extensions_init_time_ms",nf="$sdk_debug_recording_script_not_loaded",al="PostHog loadExternalDependency extension not found.",kn="on_reject",Wt="always",Un="anonymous",vn="identified",pa="identified_only",ts="visibilitychange",ns="beforeunload",Vn="$pageview",_o="$pageleave",yo="$identify",Ac="$groupidentify";function vr(t,e){U(t)&&t.forEach(e)}function ie(t,e){if(!H(t))if(U(t))t.forEach(e);else if(jp(t))t.forEach(((i,r)=>e(i,r)));else for(var n in t)md.call(t,n)&&e(t[n],n)}var fe=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;e>i;i++)n[i-1]=arguments[i];for(var r of n)for(var s in r)r[s]!==void 0&&(t[s]=r[s]);return t};function $r(t){for(var e=Object.keys(t),n=e.length,i=new Array(n);n--;)i[n]=[e[n],t[e[n]]];return i}var Pc=function(t){try{return t()}catch{return}},Fg=function(t){return function(){try{for(var e=arguments.length,n=new Array(e),i=0;e>i;i++)n[i]=arguments[i];return t.apply(this,n)}catch(r){A.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),A.critical(r)}}},ll=function(t){var e={};return ie(t,(function(n,i){(X(n)&&n.length>0||ke(n))&&(e[i]=n)})),e},Rg=["herokuapp.com","vercel.app","netlify.app"];function Tg(t){var e=t?.hostname;if(!X(e))return!1;var n=e.split(".").slice(-2).join(".");for(var i of Rg)if(n===i)return!1;return!0}function ve(t,e,n,i){var r=i??{},s=r.capture,o=r.passive;t?.addEventListener(e,n,{capture:s!==void 0&&s,passive:o===void 0||o})}function ga(t){return t.name==="ph_toolbar_internal"}var rf=t=>{if(P){try{for(var e=t+"=",n=P.cookie.split(";").filter((s=>s.length)),i=0;n.length>i;i++){for(var r=n[i];r.charAt(0)==" ";)r=r.substring(1,r.length);if(r.indexOf(e)===0)return decodeURIComponent(r.substring(e.length,r.length))}}catch{}return null}};Math.trunc||(Math.trunc=function(t){return 0>t?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return ke(t)&&isFinite(t)&&Math.floor(t)===t});class is{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,n,i,r){if(!Number.isInteger(e)||!Number.isInteger(n)||!Number.isInteger(i)||!Number.isInteger(r)||0>e||0>n||0>i||0>r||e>0xffffffffffff||n>4095||i>1073741823||r>4294967295)throw new RangeError("invalid field value");var s=new Uint8Array(16);return s[0]=e/Math.pow(2,40),s[1]=e/Math.pow(2,32),s[2]=e/Math.pow(2,24),s[3]=e/Math.pow(2,16),s[4]=e/256,s[5]=e,s[6]=112|n>>>8,s[7]=n,s[8]=128|i>>>24,s[9]=i>>>16,s[10]=i>>>8,s[11]=i,s[12]=r>>>24,s[13]=r>>>16,s[14]=r>>>8,s[15]=r,new is(s)}toString(){for(var e="",n=0;this.bytes.length>n;n++)e=e+(this.bytes[n]>>>4).toString(16)+(15&this.bytes[n]).toString(16),n!==3&&n!==5&&n!==7&&n!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new is(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var n=0;16>n;n++){var i=this.bytes[n]-e.bytes[n];if(i!==0)return Math.sign(i)}return 0}}class $g{generate(){var e=this.generateOrAbort();if(!C(e))return e;this.S=0;var n=this.generateOrAbort();if(C(n))throw new Error("Could not generate UUID after timestamp reset");return n}generateOrAbort(){var e=Date.now();if(e>this.S)this.S=e,this.C();else{if(this.S>=e+1e4)return;this.I++,this.I>4398046511103&&(this.S++,this.C())}return is.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 Mg}}var Fc,sf=t=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;t.length>e;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};w&&!C(w.crypto)&&crypto.getRandomValues&&(sf=t=>crypto.getRandomValues(t));class Mg{nextUint32(){return this.R.length>this.O||(sf(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var Ht=()=>Lg().toString(),Lg=()=>(Fc||(Fc=new $g)).generate(),yi="",Ng=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,zt={N:()=>!!P,j(t){A.error("cookieStore error: "+t)},P:rf,H(t){var e;try{e=JSON.parse(zt.P(t))||{}}catch{}return e},F(t,e,n,i,r){if(!P)return!1;try{var s="",o="",a=(function(c,d){if(d){var h=(function(p,g){if(g===void 0&&(g=P),yi)return yi;if(!g||["localhost","127.0.0.1"].includes(p))return"";for(var m=p.split("."),v=Math.min(m.length,8),E="dmn_chk_"+Ht();!yi&&v--;){var S=m.slice(v).join("."),_=E+"=1;domain=."+S+";path=/";g.cookie=_+";max-age=3",g.cookie.includes(E)&&(g.cookie=_+";max-age=0",yi=S)}return yi})(c);if(!h){var f=(p=>{var g=p.match(Ng);return g?g[0]:""})(c);f!==h&&A.info("Warning: cookie subdomain discovery mismatch",f,h),h=f}return h?"; domain=."+h:""}return""})(P.location.hostname,i);if(n){var l=new Date;l.setTime(l.getTime()+864e5*n),s="; expires="+l.toUTCString()}r&&(o="; secure");var u=t+"="+encodeURIComponent(JSON.stringify(e))+s+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&A.warn("cookieStore warning: large cookie, len="+u.length),P.cookie=u,!0}catch{return!1}},q(t,e){if(P!=null&&P.cookie)try{zt.F(t,"",-1,e)}catch{return}}},wo=null,le={N(){if(!Ye(wo))return wo;var t=!0;if(C(w))t=!1;else try{var e="__mplssupport__";le.F(e,"xyz"),le.P(e)!=='"xyz"'&&(t=!1),le.q(e)}catch{t=!1}return t||A.error("localStorage unsupported; falling back to cookie store"),wo=t,t},j(t){A.error("localStorage error: "+t)},P(t){try{return w?.localStorage.getItem(t)}catch(e){le.j(e)}return null},H(t){try{return JSON.parse(le.P(t))||{}}catch{}return null},F(t,e){try{return w?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(n){le.j(n)}return!1},q(t){try{w?.localStorage.removeItem(t)}catch(e){le.j(e)}}},Og=[Yi,"distinct_id",Kn,ol,es,Qr,at],_r={},Bg={N:()=>!0,j(t){A.error("memoryStorage error: "+t)},P:t=>_r[t]||null,H:t=>_r[t]||null,F:(t,e)=>(_r[t]=e,!0),q(t){delete _r[t]}},_n=null,be={N(){if(!Ye(_n))return _n;if(_n=!0,C(w))_n=!1;else try{var t="__support__";be.F(t,"xyz"),be.P(t)!=='"xyz"'&&(_n=!1),be.q(t)}catch{_n=!1}return _n},j(t){A.error("sessionStorage error: ",t)},P(t){try{return w?.sessionStorage.getItem(t)}catch(e){be.j(e)}return null},H(t){try{return JSON.parse(be.P(t))||null}catch{}return null},F(t,e){try{return w?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(n){be.j(n)}return!1},q(t){try{w?.sessionStorage.removeItem(t)}catch(e){be.j(e)}}};class Dg{constructor(e){this._instance=e}get Ne(){return this._instance.config}get consent(){return this.ti()?0:this.ei}isOptedOut(){return this.Ne.cookieless_mode===Wt||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===kn}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===0}isRejected(){return this.consent===0||this.consent===-1&&this.Ne.opt_out_capturing_by_default}optInOut(e){this.ii.F(this.ri,e?1:0,this.Ne.cookie_expiration,this.Ne.cross_subdomain_cookie,this.Ne.secure_cookie)}reset(){this.ii.q(this.ri,this.Ne.cross_subdomain_cookie)}get ri(){var e=this._instance.config,n=e.token,i=e.opt_out_capturing_cookie_prefix;return e.consent_persistence_name||(i?i+n:"__ph_opt_in_out_"+n)}get ei(){var e=this.ii.P(this.ri);return uo(e)?1:j(zp,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,n=e==="localStorage"?le:zt;if(!this.ni||this.ni!==n){this.ni=n;var i=e==="localStorage"?zt:le;i.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(uo(i.P(this.ri))),i.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[He?.doNotTrack,He?.msDoNotTrack,B.doNotTrack].some((e=>uo(e)))}}function of(t,e){var n,i=t==null||(n=t.config)==null?void 0:n.get_current_url;if(!je(i))return e;try{var r=i(e);return X(r)&&r?r:e}catch(s){return A.error("Error in get_current_url, falling back to window.location.href",s),e}}var af="__POSTHOG_TOOLBAR__",jg=1,Ug=3,Hg=11;function Rc(t){return t instanceof Element&&(t.id===af||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function hn(t){return!!t&&t.nodeType===jg}function et(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function lf(t){return!!t&&t.nodeType===Ug}function cf(t){return!!t&&t.nodeType===Hg&&hn(t.host)}var uf=1e3;function cl(t){return t?xs(t).split(/\s+/):[]}function Tc(t,e){var n=(function(i){var r,s=w==null||(r=w.location)==null?void 0:r.href;return C(s)?void 0:of(i,s)})(e);return!!(n&&t&&t.some((i=>n.match(i))))}function rs(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 cl(e)}function df(t){return H(t)?null:xs(t).split(/(\s+)/).filter((e=>Ui(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function Ji(t){var e="";return va(t)&&!gf(t)&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;lf(n)&&n.textContent&&(e+=(i=df(n.textContent))!==null&&i!==void 0?i:"")})),xs(e)}function bo(t){var e;return C(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var ul=["a","button","form","input","select","textarea","label"];function ma(t,e){if(C(e))return!0;var n,i=function(s){if(e.some((o=>(function(a,l){var u=a.matches||a.matchesSelector||a.msMatchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.oMatchesSelector;try{return!!u&&u.call(a,l)}catch{return!1}})(s,o))))return{v:!0}};for(var r of t)if(n=i(r))return n.v;return!1}function ff(t){var e=t.parentNode;return!(!e||!hn(e))&&e}var Wg=[".ph-no-autocapture","[data-ph-no-autocapture]"],hf=["next","previous","prev",">","<"],zg=[...hf,"+","-","−","–"],$c=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,Mc=[".ph-no-rageclick",".ph-no-capture"],qg=["","text","search","email","password","url","tel","number"];function Lc(t,e){if(!w||dl(t))return!1;var n,i,r,s,o;if(mt(e)?(n=!!e&&Mc,i=void 0,r=!1):(n=(s=e?.css_selector_ignorelist)!==null&&s!==void 0?s:Mc,i=e?.content_ignorelist,r=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),n===!1||r&&(function(l){return!(!l||!hn(l))&&(!!et(l,"textarea")||(et(l,"input")?j(qg,(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=pf(t,!1).targetElementList;return!(function(l,u){if(l===!1||C(l))return!1;var c;if(l===!0)c=hf;else{if(!U(l))return!1;if(l.length>10)return A.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var h=d.safeText,f=d.ariaLabel;return c.some((p=>$c(h,p)||$c(f,p)))}))})(i,a.map((l=>{var u;return{safeText:Ji(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!ma(a,n)}var dl=t=>!t||et(t,"html")||!hn(t),pf=(t,e)=>{if(!w||dl(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,i=[t],r=t;r.parentNode&&!et(r,"body");)if(cf(r.parentNode))i.push(r.parentNode.host),r=r.parentNode.host;else{var s=ff(r);if(!s)break;if(e||ul.indexOf(s.tagName.toLowerCase())>-1)n=!0;else try{var o=w.getComputedStyle(s);o&&o.getPropertyValue("cursor")==="pointer"&&(n=!0)}catch{}i.push(s),r=s}return{parentIsUsefulElement:n,targetElementList:i}};function va(t){for(var e=new Set,n=0,i=t;i.parentNode&&!et(i,"body");i=i.parentNode){if(n++>=uf||e.has(i))return!1;e.add(i);var r=rs(i);if(j(r,"ph-sensitive")||j(r,"ph-no-capture"))return!1}if(j(rs(t),"ph-include"))return!0;var s=t.type||"";if(X(s))switch(s.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!X(o)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(o.replace(/[^a-zA-Z0-9]/g,""))}function gf(t){return!!(et(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||et(t,"select")||et(t,"textarea")||t.getAttribute("contenteditable")==="true")}var Nc=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}))$"),Oc=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,Vg=[16,15,14,13],Gg=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),Bc=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),Dc=/[0-9A-Za-z_]/;function Kg(t){for(var e=0,n=!1,i=t.length-1;i>=0;i--){var r=t.charCodeAt(i)-48;n&&(r*=2)>9&&(r-=9),e+=r,n=!n}return e%10==0}function Ui(t,e){if(e===void 0&&(e=!0),H(t))return!1;if(X(t)){t=xs(t);var n=e?Nc.test((t||"").replace(/[- ]/g,"")):(function(r){var s;for(Oc.lastIndex=0;s=Oc.exec(r);){var o=s[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of Vg){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(Nc.test(d)&&Kg(d))return!0}}}return!1})(t);if(n)return!1;var i=e?Gg.test(t):(function(r){var s;for(Bc.lastIndex=0;s=Bc.exec(r);){var o=s[1],a=s[3];if(!(o&&a&&Dc.test(o)&&Dc.test(a)))return!0}return!1})(t);if(i)return!1}return!0}function jc(t){var e=Ji(t);return Ui(e=(e+" "+mf(t)).trim())?e:""}function mf(t){var e="";return t&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;if(n&&((i=n.tagName)==null?void 0:i.toLowerCase())==="span")try{var r=Ji(n);e=(e+" "+r).trim(),n.childNodes&&n.childNodes.length&&(e=(e+" "+mf(n)).trim())}catch(s){A.error("[AutoCapture]",s)}})),e}function Uc(t){return t.replace(/"|\\"/g,'\\"')}function Yg(t){var e=t.attr__class;if(e)return U(e)?e:cl(e)}var yr=pe("[Dead Clicks]"),Jg=()=>!0,Zg=t=>{var e,n=!((e=t.instance.persistence)==null||!e.get_property(rl)),i=t.instance.config.capture_dead_clicks;return mt(i)?i:!!he(i)||n};class Hc{get lazyLoadedDeadClicksAutocapture(){return this.si}constructor(e,n,i){this.instance=e,this.isEnabled=n,this.onCapture=i,this.startIfEnabledOrStop()}onRemoteConfig(e){if(e.ok){var n=e.config;"captureDeadClicks"in n&&(this.instance.persistence&&this.instance.persistence.register({[rl]:n.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var n,i;(n=B.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture?e():(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"dead-clicks-autocapture",(r=>{r?yr.error("failed to load script",r):e()}))}oi(){var e;if(P){if(!this.si&&(e=B.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var n=he(this.instance.config.capture_dead_clicks)?I({},this.instance.config.capture_dead_clicks):{};n.__onCapture=this.onCapture,this.onCapture&&(n.capture_dead_swipes=!1),this.si=B.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.si.start(P),yr.info("starting...")}}else yr.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,yr.info("stopping..."))}}var Eo=pe("[SegmentIntegration]"),vf="posthog-js";function _f(t,e){var n=e===void 0?{}:e,i=n.organization,r=n.projectId,s=n.prefix,o=n.severityAllowList,a=o===void 0?["error"]:o,l=n.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,h,f,p,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var v,E=((d=c.exception)==null?void 0:d.values)||[],S=E.map((b=>I({},b,{stacktrace:b.stacktrace?I({},b.stacktrace,{type:"raw",frames:(b.stacktrace.frames||[]).map((k=>I({},k,{platform:"web:javascript"})))}):void 0}))),_={$exception_message:((h=E[0])==null?void 0:h.value)||c.message,$exception_type:(f=E[0])==null?void 0:f.type,$exception_level:c.level,$exception_list:S,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((p=E[0])==null?void 0:p.value)||c.message,$sentry_exception_type:(g=E[0])==null?void 0:g.type,$sentry_tags:c.tags};return i&&r&&(_.$sentry_url=(s||"https://sentry.io/organizations/")+i+"/issues/?project="+r+"&query="+c.event_id),u&&((v=t.exceptions)==null||v.sendExceptionEvent(_)),c}}class Xg{constructor(e,n,i,r,s,o){this.name=vf,this.setupOnce=function(a){a(_f(e,{organization:n,projectId:i,prefix:r,severityAllowList:s,sendExceptionsToPostHog:o==null||o}))}}}class Wc{constructor(e){this.li=(n,i,r)=>{r&&(r.noSessionId||r.activityTimeout||r.sessionPastMaximumLength||r.crossTabAdoption)&&(A.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:n,changeReason:r}),this.ui=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.hi()}hi(){var e;this.di=(e=this._instance.sessionManager)==null?void 0:e.onSessionId(this.li)}destroy(){var e;(e=this.di)==null||e.call(this),this.di=void 0}doPageView(e,n){var i,r=this.vi(e,n);return this.ui={pathname:(i=w?.location.pathname)!==null&&i!==void 0?i:"",pageViewId:n,timestamp:e},this._instance.scrollManager.resetContext(),r}doPageLeave(e){var n;return this.vi(e,(n=this.ui)==null?void 0:n.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.ui)==null?void 0:e.pageViewId}}vi(e,n){var i=this.ui;if(!i)return{$pageview_id:n};var r={$pageview_id:n,$prev_pageview_id:i.pageViewId},s=this._instance.scrollManager.getContext();if(s&&!this._instance.config.disable_scroll_properties){var o=s.maxScrollHeight,a=s.lastScrollY,l=s.maxScrollY,u=s.maxContentHeight,c=s.lastContentY,d=s.maxContentY;if(!(C(o)||C(a)||C(l)||C(u)||C(c)||C(d))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),d=Math.ceil(d);var h=o>1?At(a/o,0,1,A):1,f=o>1?At(l/o,0,1,A):1,p=u>1?At(c/u,0,1,A):1,g=u>1?At(d/u,0,1,A):1;r=fe(r,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:h,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:f,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:p,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return i.pathname&&(r.$prev_pageview_pathname=i.pathname),i.timestamp&&(r.$prev_pageview_duration=(e.getTime()-i.timestamp.getTime())/1e3),r}}var So=["flags","surveys"],Qg={[Gd]:{exposure:"hidden"},[Fi]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[Ri]:{exposure:"hidden"},[ea]:{exposure:"event"},[ta]:{exposure:"hidden"},[na]:{exposure:"event"},[ia]:{exposure:"hidden"},[ra]:{exposure:"event"},[sa]:{exposure:"event"},[rl]:{exposure:"event"},[sl]:{exposure:"hidden"},[oa]:{exposure:"event"},[An]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[Kn]:{exposure:"hidden"},[ol]:{exposure:"event"},[Kd]:{exposure:"event",shouldSkipFromEventProperties:t=>Ye(t)},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},$sess_rec_flush_size:{exposure:"hidden"},[Sn]:{exposure:"hidden",storageGroup:"flags"},[Ti]:{exposure:"hidden",storageGroup:"flags"},[Ar]:{exposure:"hidden"},[aa]:{exposure:"hidden",storageGroup:"flags"},[$i]:{exposure:"hidden",storageGroup:"flags"},[Pr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[Zr]:{exposure:"hidden",storageGroup:"flags"},[It]:{exposure:"hidden"},[xn]:{exposure:"hidden"},[jt]:{exposure:"hidden"},[In]:{exposure:"hidden"},[la]:{exposure:"hidden",storageGroup:"surveys"},[Xr]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[ca]:{exposure:"event"},[Fr]:{exposure:"hidden"},[Rr]:{exposure:"hidden"},[Mi]:{exposure:"hidden"},$product_tours_activated:{exposure:"hidden"},$product_tours_activated_session:{exposure:"hidden"},$conversations_widget_session_id:{exposure:"event"},$conversations_ticket_id:{exposure:"event"},$conversations_widget_state:{exposure:"event"},$conversations_user_traits:{exposure:"event"},[Cn]:{exposure:"hidden"},[Li]:{exposure:"hidden"},[Tr]:{exposure:"hidden"},[ji]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[at]:{exposure:"hidden"},[ua]:{exposure:"hidden"},[da]:{exposure:"hidden"},[fa]:{exposure:"hidden"},[ha]:{exposure:"hidden"},[Qr]:{exposure:"hidden"},[es]:{exposure:"hidden"},[Yd]:{exposure:"event"},[Jd]:{exposure:"event"},[Zd]:{exposure:"event"},[Xd]:{exposure:"event"},[ef]:{exposure:"event"},[tf]:{exposure:"event"},[nf]:{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"}},em=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],yn=t=>{var e=Qg[t];if(e)return e;for(var n of em){var i=n[1];if(t.indexOf(n[0])===0)return i}},Yn=(t,e)=>{try{return JSON.stringify(t,((n,i)=>typeof i=="bigint"?i.toString():i),e)}catch{return pd(t)}},ss=t=>{var e=P?.createElement("a");return C(e)?null:(e.href=t,e)},ii=function(t,e){for(var n,i=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),r=0;i.length>r;r++){var s=i[r].split("=");if(s[0]===e){n=s;break}}if(!U(n)||2>n.length)return"";var o=n[1];try{o=decodeURIComponent(o)}catch{A.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},Zi=function(t,e,n){if(!t||!e||!e.length)return t;for(var i=t.split("#"),r=i[1],s=(i[0]||"").split("?"),o=s[1],a=s[0],l=(o||"").split("&"),u=[],c=0;l.length>c;c++){var d=l[c].split("=");U(d)&&(e.includes(d[0])?u.push(d[0]+"="+n):u.push(l[c]))}var h=a;return o!=null&&(h+="?"+u.join("&")),r!=null&&(h+="#"+r),h},os=function(t,e){var n=t.match(new RegExp(e+"=([^&]*)"));return n?n[1]:null},yf=(t,e)=>t>=e&&dd(),wf=(t,e,n,i)=>{if(t===0){if(dd()){var r=e+1;return r===n&&i(),r}return e}return 0},wr="https?://(.*)",ri=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],tm=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...ri],Xi="",nm=["li_fat_id"];function bf(t,e,n){if(!P)return{};var i,r=e?[...ri,...n||[]]:[],s=Ef(Zi(P.URL,r,Xi),t),o=(i={},ie(nm,(function(a){var l=rf(a);i[a]=l||null})),i);return fe(o,s)}function Ef(t,e){var n=tm.concat(e||[]),i={};return ie(n,(function(r){var s=ii(t,r);i[r]=s||null})),i}function Sf(t){var e=(function(s){return s?s.search(wr+"google.([^/?]*)")===0?"google":s.search(wr+"bing.com")===0?"bing":s.search(wr+"yahoo.com")===0?"yahoo":s.search(wr+"duckduckgo.com")===0?"duckduckgo":null:null})(t),n=e!="yahoo"?"q":"p",i={};if(!Ye(e)){i.$search_engine=e;var r=P?ii(P.referrer,n):"";r.length&&(i.ph_keyword=r)}return i}function zc(){return navigator.language||navigator.userLanguage}var as="$direct";function xf(){return P?.referrer||as}function If(t,e,n){n===void 0&&(n=!1);var i=t?[...ri,...e||[]]:[],r=n?fn(me?.href):me?.href,s=r?.substring(0,1e3);return{r:xf().substring(0,1e3),u:s?Zi(s,i,Xi):void 0}}function kf(t,e){var n;e===void 0&&(e=!1);var i=t.r,r=t.u,s=e?fn(r):r,o={$referrer:i,$referring_domain:i==null?void 0:i==as?as:(n=ss(i))==null?void 0:n.host};if(s){o.$current_url=s;var a=ss(s);o.$host=a?.host,o.$pathname=a?.pathname;var l=Ef(s);fe(o,l)}if(i){var u=Sf(i);fe(o,u)}return o}function Cf(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function im(){try{return new Date().getTimezoneOffset()}catch{return}}var rm={flags:ji,surveys:Xr},sm=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],Hn="main";class xo{constructor(e,n,i){if(i===void 0&&(i=!0),this.ci={},this.fi=!1,this.pi=!1,this.Ne=e,this.gi=i,this.props={},this.mi=void 0,this.yi=(s=>{var o="";return s.token&&(o=s.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),s.persistence_name?"ph_"+s.persistence_name:"ph_"+o+"_posthog"})(e),this.ii=this.bi(e),this.pi=this.wi(e),this.load(),e.debug&&A.info("Persistence loaded",e.persistence,I({},this.props)),this.update_config(e,e,n),this.save(),w){var r=()=>this.flush();ve(w,"beforeunload",r,{capture:!1}),ve(w,"pagehide",r,{capture:!1})}}ki(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return ke(n)&&n>0?n:0}isDisabled(){return!!this.xi}bi(e){sm.indexOf(e.persistence.toLowerCase())===-1&&(A.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var n,i=(function(o,a){o===void 0&&(o=[]),a===void 0&&(a=!1);var l=[...Og,...o];return I({},le,{H(u){try{var c={};try{c=zt.H(u)||{}}catch{}var d,h=JSON.parse(le.P(u)||"{}");if(a){var f={};for(var p in c){var g=c[p];Ye(g)||g===""||(f[p]=g)}d=fe(h,f)}else d=fe(c,h);return le.F(u,d),d}catch{}return null},F(u,c,d,h,f,p){var g=le.F(u,c,void 0,void 0,p);try{var m={};l.forEach((v=>{c[v]&&(m[v]=c[v])})),Object.keys(m).length&&zt.F(u,m,d,h,f,p)}catch(v){le.j(v)}return g},q(u,c){try{w?.localStorage.removeItem(u),zt.q(u,c)}catch(d){le.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),r=!1,s=e.persistence.toLowerCase();return s==="localstorage"&&le.N()?(n=le,r=!0):s==="localstorage+cookie"&&i.N()?(n=i,r=!0):s==="sessionstorage"&&be.N()?n=be:s==="memory"?n=Bg:s==="cookie"?n=zt:i.N()?(n=i,r=!0):n=zt,this.fi=r,n}Si(e){return this.yi+"__"+e}wi(e){return this.fi&&!!e.split_storage}properties(){var e={};return ie(this.props,((n,i)=>{var r=yn(i);if(!r||r.exposure==="event"){if(r!=null&&r.shouldSkipFromEventProperties!=null&&r.shouldSkipFromEventProperties(n))return;e[i]=n}})),e}load(){if(!this.xi){var e=this.ii.H(this.yi);e&&(this.props=fe({},e)),this.pi&&this.Ci()}}Ci(){for(var e of So){var n=le.H(this.Si(e));if(n&&!Kt(n)){var i=this.Mi(e);i.persisted=!0,this.Ti(e)||(i.fingerprint=this.Ei(n,e)),this.Ii(e,n)||fe(this.props,n)}}}Ti(e){return Object.keys(this.props).some((n=>{var i;return((i=yn(n))==null?void 0:i.storageGroup)===e}))}Ii(e,n){var i=rm[e];if(!i)return!1;var r=n[i],s=this.props[i];return ke(r)&&ke(s)&&s>r}refreshKey(e){var n;if(!this.xi){var i=this.pi?(n=yn(e))==null?void 0:n.storageGroup:void 0,r=i?le.H(this.Si(i)):this.ii.H(this.yi);if(r&&e in r)this.Pi(e,r[e]);else{if(i){var s=this.ii.H(this.yi);if(s&&e in s)return void this.Pi(e,s[e])}this.Ri(e)}}}save(){if(!this.xi){var e=this.ki();e>0?C(this.Ai)&&(this.Ai=setTimeout((()=>{this.Ai=void 0,this.Fi()}),e)):this.Fi()}}flush(){C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0,this.Fi())}Fi(){this.xi||(this.pi?this.Li():this.Oi(this.ii,this.yi,this.props,Hn))}Li(){var e=this.Di(),n=e.main,i=e.groups;for(var r of(this.Oi(this.ii,this.yi,n,Hn),So)){var s,o=i[r];(!Kt(o)||(s=this.ci[r])!=null&&s.persisted)&&this.Oi(le,this.Si(r),o,r)}}Di(){var e={},n={flags:{},surveys:{}};return ie(this.props,((i,r)=>{var s,o=(s=yn(r))==null?void 0:s.storageGroup;o?n[o][r]=i:e[r]=i})),{main:e,groups:n}}Ei(e,n){if(n===Hn)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var i={};return ie(e,((r,s)=>{var o;i[s]=(o=yn(s))!=null&&o.volatile?"__volatile__":r})),JSON.stringify(i)}Oi(e,n,i,r){var s=this.Mi(r);if(r===Hn||s.dirty||C(s.fingerprint)){var o;try{if((o=this.Ei(i,r))===s.fingerprint)return void(s.dirty=!1)}catch{o=void 0}e.F(n,i,this.$i,this.Ni,this.qi,this.Ne.debug)?(s.dirty=!1,r!==Hn&&(s.persisted=!0),C(o)||(s.fingerprint=o)):this.Ne.debug&&A.warn('failed to persist storage entry "'+n+'"; will retry on next save')}}remove(e){var n=(e===void 0?{}:e).keepGroupEntries,i=n!==void 0&&n;if(C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0),this.ii.q(this.yi,!1),this.ii.q(this.yi,!0),!i&&this.gi)for(var r of So)le.q(this.Si(r));i?delete this.ci[Hn]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,n,i){if(he(e)){C(n)&&(n="None"),this.$i=C(i)?this.ji:i;var r=!1;if(ie(e,((s,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==n||(this.Pi(o,s),r=!0)})),r)return this.save(),!0}return!1}register(e,n){if(he(e)){this.$i=C(n)?this.ji:n;var i=!1;if(ie(e,((r,s)=>{e.hasOwnProperty(s)&&(this.props[s]!==r||he(r)||U(r))&&(this.Pi(s,r),i=!0)})),i)return this.save(),!0}return!1}unregister(e){var n=typeof e=="string"?[e]:e,i=!1;for(var r of n)r in this.props&&(this.Ri(r),i=!0);i&&this.save()}update_campaign_params(){var e=P?.URL;if(e!==this.mi){var n=bf(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);Kt(ll(n))||this.register(n),this.mi=e}}update_search_keyword(){var e;this.register((e=P?.referrer)?Sf(e):{})}update_referrer_info(){var e;this.register_once({$referrer:xf(),$referring_domain:P!=null&&P.referrer&&((e=ss(P.referrer))==null?void 0:e.host)||as},void 0)}set_initial_person_info(){this.props[fa]||this.props[ha]||this.register_once({[Qr]:If(this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties,this.Ne.disable_capture_url_hashes)},void 0)}get_initial_props(){var e={};ie([ha,fa],(r=>{var s=this.props[r];s&&ie(s,(function(o,a){e["$initial_"+Go(a)]=o}))}));var n=this.props[Qr];if(n){var i=(function(r,s){s===void 0&&(s=!1);var o=kf(r,s),a={};return ie(o,(function(l,u){a["$initial_"+Go(u)]=l})),a})(n,this.Ne.disable_capture_url_hashes);fe(e,i)}return e}safe_merge(e){return ie(this.props,(function(n,i){i in e||(e[i]=n)})),e}update_config(e,n,i){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!i),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var r=e.persistence!==n.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((h,f)=>h===d[f]))})(e.cookie_persisted_properties||[],n.cookie_persisted_properties||[]),s=r?this.bi(e):this.ii,o=this.wi(e);if(r||o!==this.pi){var a=this.props;this.clear(),this.ii=s,this.pi=o,this.props=a,this.save()}}set_disabled(e){this.xi=e,this.xi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ni&&(this.Ni=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this.qi&&(this.qi=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,n){var i=this.props[Ri]||{};i[e]=n,this.Pi(Ri,i),this.save()}remove_event_timer(e){var n=this.props[Ri]||{},i=n[e];return C(i)||(delete n[e],this.Pi(Ri,n),this.save()),i}get_property(e){return this.props[e]}set_property(e,n){this.Pi(e,n),this.save()}Pi(e,n){var i;this.props[e]=n,(i=yn(e))!=null&&i.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var n,i=(n=yn(e))==null?void 0:n.storageGroup;i&&(this.Mi(i).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function br(t){var e=!0;return{dispose(){if(e){e=!1;var n=t();n&&je(n.then)&&n.then(void 0,(()=>{}))}}}}var Ue={GZipJS:"gzip-js",Base64:"base64"},wi={Activation:"events",Cancellation:"cancelEvents"},Io={Popover:"popover",API:"api",Widget:"widget"},qt={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},ko={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},_a={Popover:"popover",Inline:"inline"},om={SHOWN:"product tour shown"},qc={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},Vc=pe("[RateLimiter]");class am{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=n=>{var i=n.text;if(i&&i.length)try{(JSON.parse(i).quota_limited||[]).forEach((r=>{Vc.info((r||"events")+" is quota limited."),this.serverLimits[r]=new Date().getTime()+6e4}))}catch(r){return void Vc.warn('could not rate limit - continuing. Error: "'+r?.message+'"',{text:i})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var n,i,r;e===void 0&&(e=!1);var s=this.captureEventsBurstLimit,o=this.captureEventsPerSecond,a=new Date().getTime(),l=(n=(i=this.instance.persistence)==null?void 0:i.get_property(da))!==null&&n!==void 0?n:{tokens:s,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>s&&(l.tokens=s);var u=1>l.tokens;if(u||e||(l.tokens=Math.max(0,l.tokens-1)),u&&!e){var c=(ke(l.dropped)?l.dropped:0)+1;l.dropped=c,!this.lastEventRateLimited&&this.Hi(c)&&(l.dropped=0)}return this.lastEventRateLimited=u,(r=this.instance.persistence)==null||r.set_property(da,l),{isRateLimited:u,remainingTokens:l.tokens}}Ui(e){var n=this.instance.config.property_denylist;return!U(n)||!n.includes(e)}zi(){var e;if(this.Ui("$current_url")&&this.Ui("$pathname")&&me!=null&&me.pathname)return""+((e=me.origin)!==null&&e!==void 0?e:"")+me.pathname}Hi(e){var n,i,r=this.captureEventsBurstLimit,s=this.captureEventsPerSecond,o=this.zi(),a=this.Ui("$session_id")?(n=(i=this.instance).get_session_id)==null?void 0:n.call(i):void 0,l=[e+" event(s) dropped since the last warning",o?"triggered on "+o:void 0,a?"session "+a:void 0].filter(Boolean).join(", ");return!!this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited: "+l+". Config is set to "+s+" events per second and "+r+" events burst limit."},{skip_client_rate_limiting:!0})}isServerRateLimited(e){var n=this.serverLimits[e||"events"]||!1;return n!==!1&&new Date().getTime()e(this.remoteConfig))):e()}Vi(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:e})}load(){try{if(this.remoteConfig)return an.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void an.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return an.info("No config found after loading remote JS config. Falling back to JSON."),void this.Vi((n=>{this.Zi(n.json,n),this.Gi()}));this.Zi(e),this.Gi()}))}catch(e){an.error("Error loading remote config",e),this.Zi()}}stop(){this.Ki&&(clearInterval(this.Ki),this.Ki=void 0)}refresh(){!this._instance.Qi()&&P&&P.visibilityState!=="hidden"&&this._instance.reloadFeatureFlags()}Gi(){var e;if(!this.Ki){var n=(e=this._instance.config.remote_config_refresh_interval_ms)!==null&&e!==void 0?e:3e5;n!==0&&(this.Ki=setInterval((()=>{this.refresh()}),n))}}Zi(e,n){!e&&n&&(n.statusCode===0?n.error||an.warn("Failed to fetch remote config from PostHog."):an.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(r){an.error("Error applying remote config",r)}if(e?.hasFeatureFlags!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var i;(i=this._instance.featureFlags)==null||i.ensureFlagsLoaded()}catch(r){an.error("Error loading feature flags",r)}}}var ct=Uint8Array,Ke=Uint16Array,si=Uint32Array,fl=new ct([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]),hl=new ct([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]),Gc=new ct([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Pf=function(t,e){for(var n=new Ke(31),i=0;31>i;++i)n[i]=e+=1<i;++i)for(var s=n[i];n[i+1]>s;++s)r[s]=s-n[i]<<5|i;return[n,r]},Ff=Pf(fl,2),ya=Ff[1];Ff[0][28]=258,ya[258]=28;for(var Kc=Pf(hl,0)[1],Rf=new Ke(32768),_e=0;32768>_e;++_e){var Wn=(43690&_e)>>>1|(21845&_e)<<1;Rf[_e]=((65280&(Wn=(61680&(Wn=(52428&Wn)>>>2|(13107&Wn)<<2))>>>4|(3855&Wn)<<4))>>>8|(255&Wn)<<8)>>>1}var Hi=function(t,e,n){for(var i=t.length,r=0,s=new Ke(e);i>r;++r)++s[t[r]-1];var o,a=new Ke(e);for(r=0;e>r;++r)a[r]=a[r-1]+s[r-1]<<1;for(o=new Ke(i),r=0;i>r;++r)o[r]=Rf[a[t[r]-1]++]>>>15-t[r];return o},$n=new ct(288);for(_e=0;144>_e;++_e)$n[_e]=8;for(_e=144;256>_e;++_e)$n[_e]=9;for(_e=256;280>_e;++_e)$n[_e]=7;for(_e=280;288>_e;++_e)$n[_e]=8;var ls=new ct(32);for(_e=0;32>_e;++_e)ls[_e]=5;var lm=Hi($n,9),cm=Hi(ls,5),Tf=function(t){return(t/8>>0)+(7&t&&1)},$f=function(t,e,n){(n==null||n>t.length)&&(n=t.length);var i=new(t instanceof Ke?Ke:t instanceof si?si:ct)(n-e);return i.set(t.subarray(e,n)),i},Ot=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8},bi=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8,t[i+2]|=n>>>16},Co=function(t,e){for(var n=[],i=0;t.length>i;++i)t[i]&&n.push({s:i,f:t[i]});var r=n.length,s=n.slice();if(!r)return[new ct(0),0];if(r==1){var o=new ct(n[0].s+1);return o[n[0].s]=1,[o,1]}n.sort((function(b,k){return b.f-k.f})),n.push({s:-1,f:25001});var a=n[0],l=n[1],u=0,c=1,d=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=r-1;)a=n[n[d].f>n[u].f?u++:d++],l=n[u!=c&&n[d].f>n[u].f?u++:d++],n[c++]={s:-1,f:a.f+l.f,l:a,r:l};var h=s[0].s;for(i=1;r>i;++i)s[i].s>h&&(h=s[i].s);var f=new Ke(h+1),p=wa(n[c-1],f,0);if(p>e){i=0;var g=0,m=p-e,v=1<i;++i){var E=s[i].s;if(e>=f[E])break;g+=v-(1<>>=m;g>0;){var S=s[i].s;e>f[S]?g-=1<=0&&g;--i){var _=s[i].s;f[_]==e&&(--f[_],++g)}p=e}return[new ct(f),p]},wa=function(t,e,n){return t.s==-1?Math.max(wa(t.l,e,n+1),wa(t.r,e,n+1)):e[t.s]=n},Yc=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new Ke(++e),i=0,r=t[0],s=1,o=function(l){n[i++]=l},a=1;e>=a;++a)if(t[a]==r&&a!=e)++s;else{if(!r&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(r),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(r);s=1,r=t[a]}return[n.subarray(0,i),e]},Ei=function(t,e){for(var n=0,i=0;e.length>i;++i)n+=t[i]*e[i];return n},ba=function(t,e,n){var i=n.length,r=Tf(e+2);t[r]=255&i,t[r+1]=i>>>8,t[r+2]=255^t[r],t[r+3]=255^t[r+1];for(var s=0;i>s;++s)t[r+s+4]=n[s];return 8*(r+4+i)},Jc=function(t,e,n,i,r,s,o,a,l,u,c){Ot(e,c++,n),++r[256];for(var d=Co(r,15),h=d[0],f=d[1],p=Co(s,15),g=p[0],m=p[1],v=Yc(h),E=v[0],S=v[1],_=Yc(g),b=_[0],k=_[1],T=new Ke(19),x=0;E.length>x;++x)T[31&E[x]]++;for(x=0;b.length>x;++x)T[31&b[x]]++;for(var F=Co(T,7),$=F[0],O=F[1],L=19;L>4&&!$[Gc[L-1]];--L);var N,K,V,M,R=u+5<<3,Z=Ei(r,$n)+Ei(s,ls)+o,Ce=Ei(r,h)+Ei(s,g)+o+14+3*L+Ei(T,$)+(2*T[16]+3*T[17]+7*T[18]);if(Z>=R&&Ce>=R)return ba(e,c,t.subarray(l,l+u));if(Ot(e,c,1+(Z>Ce)),c+=2,Z>Ce){N=Hi(h,f),K=h,V=Hi(g,m),M=g;var oe=Hi($,O);for(Ot(e,c,S-257),Ot(e,c+5,k-1),Ot(e,c+10,L-4),c+=14,x=0;L>x;++x)Ot(e,c+3*x,$[Gc[x]]);c+=3*L;for(var ye=[E,b],$e=0;2>$e;++$e){var ae=ye[$e];for(x=0;ae.length>x;++x)Ot(e,c,oe[Ie=31&ae[x]]),c+=$[Ie],Ie>15&&(Ot(e,c,ae[x]>>>5&127),c+=ae[x]>>>12)}}else N=lm,K=$n,V=cm,M=ls;for(x=0;a>x;++x)if(i[x]>255){var Ie;bi(e,c,N[257+(Ie=i[x]>>>18&31)]),c+=K[Ie+257],Ie>7&&(Ot(e,c,i[x]>>>23&31),c+=fl[Ie]);var Se=31&i[x];bi(e,c,V[Se]),c+=M[Se],Se>3&&(bi(e,c,i[x]>>>5&8191),c+=hl[Se])}else bi(e,c,N[i[x]]),c+=K[i[x]];return bi(e,c,N[256]),c+K[256]},um=new si([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),dm=(function(){for(var t=new si(256),e=0;256>e;++e){for(var n=e,i=9;--i;)n=(1&n&&3988292384)^n>>>1;t[e]=n}return t})(),Ao=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8};function fm(t,e){e===void 0&&(e={});var n=(function(){var d=4294967295;return{p(h){for(var f=d,p=0;h.length>p;++p)f=dm[255&f^h[p]]^f>>>8;d=f},d(){return 4294967295^d}}})(),i=t.length;n.p(t);var r,s,o,a,l,u=(a=10+((r=e).filename&&r.filename.length+1||0),l=8,(function(d,h,f,p,g,m){var v=d.length,E=new ct(p+v+5*(1+Math.floor(v/7e3))+g),S=E.subarray(p,E.length-g),_=0;if(!h||8>v)for(var b=0;v>=b;b+=65535){var k=b+65535;v>k?_=ba(S,_,d.subarray(b,k)):(S[b]=!0,_=ba(S,_,d.subarray(b,v)))}else{for(var T=um[h-1],x=T>>>13,F=8191&T,$=(1<b;++b){var Ie=V(b),Se=32767&b,De=L[Ie];if(O[Se]=De,L[Ie]=Se,b>=$e){var wt=v-b;if((Ce>7e3||ye>24576)&&wt>423){_=Jc(d,S,0,M,R,Z,oe,ye,ae,b-ae,_),ye=Ce=oe=0,ae=b;for(var ge=0;286>ge;++ge)R[ge]=0;for(ge=0;30>ge;++ge)Z[ge]=0}var Je=2,bt=0,mn=F,Re=Se-De&32767;if(wt>2&&Ie==V(b-Re))for(var Pe=Math.min(x,wt)-1,$t=Math.min(32767,b),Bn=Math.min(258,wt);$t>=Re&&--mn&&Se!=De;){if(d[b+Je]==d[b+Je-Re]){for(var qe=0;Bn>qe&&d[b+qe]==d[b+qe-Re];++qe);if(qe>Je){if(Je=qe,bt=Re,qe>Pe)break;var Dn=Math.min(Re,qe-2),Mt=0;for(ge=0;Dn>ge;++ge){var Lt=b-Re+ge+32768&32767,ut=Lt-O[Lt]+32768&32767;ut>Mt&&(Mt=ut,De=Lt)}}}Re+=(Se=De)-(De=O[Se])+32768&32767}if(bt){M[ye++]=268435456|ya[Je]<<18|Kc[bt];var sn=31&ya[Je],gi=31&Kc[bt];oe+=fl[sn]+hl[gi],++R[257+sn],++Z[gi],$e=b+Je,++Ce}else M[ye++]=d[b],++R[d[b]]}}_=Jc(d,S,!0,M,R,Z,oe,ye,ae,b-ae,_)}return $f(E,0,p+Tf(_)+g)})(s=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):12+o.mem,a,l)),c=u.length;return(function(d,h){var f=h.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>h.level?4:h.level==9?2:0,d[9]=3,h.mtime!=0&&Ao(d,4,Math.floor(new Date(h.mtime||Date.now())/1e3)),f){d[3]=8;for(var p=0;f.length>=p;++p)d[p+10]=f.charCodeAt(p)}})(u,e),Ao(u,c-8,n.d()),Ao(u,c-4,i),u}var hm=!!zo||!!Za,Mf="text/plain",Mr=!1,Lf=(t,e)=>{var n=t.split("#"),i=n[1],r=n[0].split("?"),s=r[0],o=r[1];if(!o)return t;var a=o.split("&").filter((l=>l.split("=")[0]!==e)).join("&");return s+(a?"?"+a:"")+(i?"#"+i:"")},ks=function(t,e,n){var i;n===void 0&&(n=!0);var r=t.split("?"),s=r[0],o=r[1],a=I({},e),l=(i=o?.split("&").map((c=>{var d,h=c.split("="),f=h[0],p=n&&(d=a[f])!==null&&d!==void 0?d:h[1];return delete a[f],f+"="+p})))!==null&&i!==void 0?i:[],u=(function(c,d){var h,f;d===void 0&&(d="&");var p=[];return ie(c,(function(g,m){C(g)||C(m)||m==="undefined"||(h=encodeURIComponent((v=>v instanceof File)(g)?g.name:g.toString()),f=encodeURIComponent(m),p[p.length]=f+"="+h)})),p.join(d)})(a);return u&&l.push(u),l.length>0?s+"?"+l.join("&"):s},Po=t=>{if(t.Ji)return t.Ji;var e=t.data,n=t.compression;if(e){if(n===Ue.GZipJS){var i=fm((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new ct(a.length+(a.length>>>1)),d=0,h=function(m){c[d++]=m},f=0;u>f;++f){if(d+5>c.length){var p=new ct(d+8+(u-f<<1));p.set(c),c=p}var g=a.charCodeAt(f);128>g?h(g):2048>g?(h(192|g>>>6),h(128|63&g)):g>55295&&57344>g?(h(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++f))>>>18),h(128|g>>>12&63),h(128|g>>>6&63),h(128|63&g)):(h(224|g>>>12),h(128|g>>>6&63),h(128|63&g))}return $f(c,0,d)})(Yn(e)),{mtime:0});return{contentType:Mf,body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),estimatedSize:i.byteLength}}if(n===Ue.Base64){var r=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(Yn(e)),s=(a=>"data="+encodeURIComponent(typeof a=="string"?a:Yn(a)))(r);return{contentType:"application/x-www-form-urlencoded",body:s,estimatedSize:new Blob([s]).size}}var o=Yn(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},Nf=t=>{var e,n,i=()=>t.transport==="sendBeacon"?{url:ks(t.url,{compression:Ue.Base64}),encodedBody:Po(I({},t,{compression:Ue.Base64,Ji:void 0}))}:{url:Lf(t.url,"compression"),encodedBody:Po(I({},t,{compression:void 0,Ji:void 0}))};try{e=Po(t)}catch(r){if(mc(t.compression,ii(t.url,"compression")))return A.error("Failed to gzip request body, sending uncompressed payload",r),i();throw r}return e&&mc(t.compression,ii(t.url,"compression"))&&!((n=e.body)instanceof ArrayBuffer?qo(new Uint8Array(n)):ArrayBuffer.isView(n)&&qo(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)))?(Mr=!0,i()):{url:t.url,encodedBody:e}},Of=t=>{try{return Nf(t)}catch(e){return A.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},pm=(function(){var t=se((function*(e){var n=Yn(e.data),i=yield(function(s,o,a){return Vo.apply(this,arguments)})(n,ne.DEBUG,{rethrow:!0});if(!i)return e;var r=yield i.arrayBuffer();return I({},e,{Ji:{contentType:Mf,body:r,estimatedSize:r.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),gm=/Failed to fetch|NetworkError|Load failed/i,Bf=t=>t?.name==="TypeError"&&gm.test(t?.message||""),Df=t=>{var e=Of(t);if(e){var n=e.url,i=e.encodedBody,r=i??{},s=r.contentType,o=r.body,a=r.estimatedSize,l=new Headers;ie(t.headers,(function(p,g){l.append(g,p)})),s&&l.append("Content-Type",s);var u=null,c=!1;if(uc){var d=new uc;u={signal:d.signal,timeout:setTimeout((()=>{var p,g;c=!0,d.abort((p=t.timeout,(g=new Error("PostHog request timed out"+(p?" after "+p+"ms":""))).name="AbortError",g))}),t.timeout)}}var h=p=>{c&&p?.name==="AbortError"||Bf(p)?A.warn(p):A.error(p),t.callback==null||t.callback({statusCode:0,error:p})};try{var f;Za(n,I({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(f=u)==null?void 0:f.signal},t.fetchOptions)).then((p=>p.text().then((g=>{var m={statusCode:p.status,text:g};if(p.status===200)try{m.json=JSON.parse(g)}catch(v){A.error(v)}t.callback==null||t.callback(m)})))).catch(h).finally((()=>u?clearTimeout(u.timeout):null))}catch(p){u&&clearTimeout(u.timeout),h(p)}}},Ea=t=>{try{var e,n=Nf(t),i=n.url,r=n.encodedBody,s=r??{},o=s.body,a=s.estimatedSize;if(!o)return;var l=o instanceof Blob?o:new Blob([o],{type:s.contentType});if(He.sendBeacon(i,l))return;var u=U(t.data)?t.data:(e=t.data)==null?void 0:e.batch;if(U(u)&&u.length>1&&(a??0)>16384){var c=Math.ceil(u.length/2),d=h=>U(t.data)?h:I({},t.data,{batch:h});return Ea(I({},t,{data:d(u.slice(0,c))})),void Ea(I({},t,{data:d(u.slice(c))}))}A.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),Df(I({},t,{Yi:!0}))}catch(h){A.warn("Beacon send failed",h)}},Zc=(t,e,n,i)=>{var r=i==="query"?e==="POST"?"sent_at":"_":void 0;return ks(n===Ue.GZipJS?Lf(t,"compression"):t,I({},r?{[r]:Date.now().toString()}:{},n===Ue.GZipJS?{}:{compression:n}))},Lr=[];Za&&Lr.push({transport:"fetch",method:Df}),zo&&Lr.push({transport:"XHR",method(t){var e=Of(t);if(e){var n=new zo,i=e.encodedBody;n.open(t.method||"GET",e.url,!0);var r=i??{},s=r.contentType,o=r.body;ie(t.headers,(function(a,l){n.setRequestHeader(l,a)})),s&&n.setRequestHeader("Content-Type",s),t.timeout&&(n.timeout=t.timeout),n.onreadystatechange=()=>{if(n.readyState===4){var a={statusCode:n.status,text:n.responseText};if(n.status===200)try{a.json=JSON.parse(n.responseText)}catch{}t.callback==null||t.callback(a)}},n.send(o)}}}),He!=null&&He.sendBeacon&&Lr.push({transport:"sendBeacon",method:Ea});var Sa=3e3;class mm{constructor(e,n){this.Xi=!0,this.tr=[],this.er=At(n?.flush_interval_ms||Sa,250,5e3,A.createLogger("flush interval"),Sa),this.ir=e}enqueue(e){this.tr.push(e),this.rr||this.nr()}unload(){this.sr();var e=this.tr.length>0?this.ar():{},n=Object.values(e);[...n.filter((i=>i.url.indexOf("/e")===0)),...n.filter((i=>i.url.indexOf("/e")!==0))].map((i=>{this.lr(I({},i,{transport:"sendBeacon"}))}))}enable(){this.Xi=!1,this.nr()}nr(){var e=this;this.Xi||(this.rr=setTimeout((()=>{if(this.sr(),this.tr.length>0){var n=this.ar(),i=function(){var s=n[r],o=new Date().getTime();s.data&&U(s.data)&&ie(s.data,(a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp})),e.lr(s)};for(var r in n)i()}}),this.er))}lr(e){try{this.ir(e)}catch(n){A.error(n)}}sr(){clearTimeout(this.rr),this.rr=void 0}ar(){var e={};return ie(this.tr,(n=>{var i,r=n,s=(r?r.batchKey:null)||r.url;C(e[s])&&(e[s]=I({},r,{data:[]})),(i=e[s].data)==null||i.push(r.data)})),this.tr=[],e}}var vm=["retriesPerformedSoFar"];class _m{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!C(w)&&"onLine"in w.navigator&&(this.dr=w.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},ve(w,"online",this.vr),ve(w,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var n=e.retriesPerformedSoFar,i=fd(e,vm);Dt(n)&&(i.url=ks(i.url,{retry_count:n})),this._instance._send_request(I({},i,{callback:r=>{if(r.statusCode!==200&&(400>r.statusCode||r.statusCode>=500)){if((r.statusCode===0?3:10)>(n??0))return void this.At(I({retriesPerformedSoFar:n},i));r.statusCode===0&&A.warn("Request failed before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped retrying after "+(n??0)+" retries.")}i.callback==null||i.callback(r)}}))}At(e){var n=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=n+1;var i=(function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),c=Math.random()-.5;return Math.ceil(u+c*(u-l))})(n),r=Date.now()+i;this.tr.push({retryAt:r,requestOptions:e});var s="Enqueued failed request for retry in "+i;navigator.onLine||(s+=" (Browser is offline)"),A.warn(s),this.ur||(this.ur=!0,this.gr())}gr(){if(this.mr&&clearTimeout(this.mr),this.tr.length===0)return this.ur=!1,void(this.mr=void 0);this.mr=setTimeout((()=>{this.dr&&this.tr.length>0&&this.cr(),this.gr()}),this.hr)}cr(){var e=Date.now(),n=[],i=this.tr.filter((s=>e>s.retryAt||(n.push(s),!1)));if(this.tr=n,i.length>0)for(var r of i)this.retriableRequest(r.requestOptions)}unload(){for(var e of(this.mr&&(clearTimeout(this.mr),this.mr=void 0),this.ur=!1,C(w)||(this.vr&&(w.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(w.removeEventListener("offline",this.pr),this.pr=void 0)),this.tr)){var n=e.requestOptions;try{this._instance._send_request(I({},n,{transport:"sendBeacon"}))}catch(i){A.error(i)}}this.tr=[]}}class ym{constructor(e){this.yr=()=>{var n,i,r,s;this.br||(this.br={});var o=this.scrollElement(),a=this.scrollY(),l=o?Math.max(0,o.scrollHeight-o.clientHeight):0,u=a+(o?.clientHeight||0),c=o?.scrollHeight||0;this.br.lastScrollY=Math.ceil(a),this.br.maxScrollY=Math.max(a,(n=this.br.maxScrollY)!==null&&n!==void 0?n:0),this.br.maxScrollHeight=Math.max(l,(i=this.br.maxScrollHeight)!==null&&i!==void 0?i:0),this.br.lastContentY=u,this.br.maxContentY=Math.max(u,(r=this.br.maxContentY)!==null&&r!==void 0?r:0),this.br.maxContentHeight=Math.max(c,(s=this.br.maxContentHeight)!==null&&s!==void 0?s:0)},this._instance=e}get _r(){return this._instance.config.scroll_root_selector}getContext(){return this.br}resetContext(){var e=this.br;return setTimeout(this.yr,0),e}startMeasuringScrollPosition(){ve(w,"scroll",this.yr,{capture:!0}),ve(w,"scrollend",this.yr,{capture:!0}),ve(w,"resize",this.yr)}scrollElement(){if(!this._r)return w?.document.documentElement;var e=U(this._r)?this._r:[this._r];for(var n of e){var i=w?.document.querySelector(n);if(i)return i}}wr(e){var n=e==="y"?"scrollTop":"scrollLeft";if(this._r){var i=this.scrollElement();return i&&i[n]||0}return w?e==="y"?w.scrollY||w.pageYOffset||w.document.documentElement.scrollTop||0:w.scrollX||w.pageXOffset||w.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var wm=t=>If(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class Xc{constructor(e,n,i,r){this.kr=s=>{var o=this.Sr();if(!o||o.sessionId!==s){var a={sessionId:s,props:this.Cr(this._instance)};this.Mr.register({[ua]:a})}},this._instance=e,this.Tr=n,this.Mr=i,this.Cr=r||wm,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[ua]}getSetOnceProps(){var e,n=(e=this.Sr())==null?void 0:e.props;return n?"r"in n?kf(n,this._instance.config.disable_capture_url_hashes):{$referring_domain:n.referringDomain,$pathname:n.initialPathName,utm_source:n.utm_source,utm_campaign:n.utm_campaign,utm_medium:n.utm_medium,utm_content:n.utm_content,utm_term:n.utm_term}:{}}getSessionProps(){var e={};return ie(ll(this.getSetOnceProps()),((n,i)=>{i==="$current_url"&&(i="url"),e["$session_entry_"+Go(i)]=n})),e}}class pl{on(e,n){return this.Er[e]||(this.Er[e]=[]),this.Er[e].push(n),()=>{this.Er[e]=this.Er[e].filter((i=>i!==n))}}emit(e,n){for(var i of this.Er[e]||[])i(n);for(var r of this.Er["*"]||[])r(e,n)}constructor(){this.Er={}}}var Si=pe("[SessionId]");class Qc{on(e,n){return this.Ir.on(e,n)}constructor(e,n,i){var r;if(this.Pr=null,this.Rr=[],this.Ar=void 0,this.Fr=!1,this.Ir=new pl,this.Lr=(u,c)=>!(!Dt(u)||!Dt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===Wt)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Ne=e.config,this.Mr=e.persistence,this.Or=void 0,this.Dr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.$r=n||Ht,this.Nr=i||Ht;var s=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*At(this.Ne.session_idle_timeout_seconds||1800,60,36e3,Si.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.qr(),this.jr="ph_"+s+"_window_id",this.Br="ph_"+s+"_primary_window_exists",this.Hr()){var o=be.H(this.jr),a=be.H(this.Br);o&&!a?this.Or=o:be.q(this.jr),be.F(this.Br,!0)}if((r=this.Ne.bootstrap)!=null&&r.sessionID)try{var l=(u=>{var c=this.Ne.bootstrap.sessionID.replace(/-/g,"");if(c.length!==32)throw new Error("Not a valid UUID");if(c[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(c.substring(0,12),16)})();this.Ur(this.Ne.bootstrap.sessionID,new Date().getTime(),l)}catch(u){Si.error("Invalid sessionID in bootstrap",u)}this.zr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return C(this.Rr)&&(this.Rr=[]),this.Rr.push(e),this.Dr&&e(this.Dr,this.Or),()=>{this.Rr=this.Rr.filter((n=>n!==e))}}Hr(){return this.Ne.persistence!=="memory"&&!this.Mr.xi&&be.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&be.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?be.H(this.jr):null}Zr(e){var n=this.Pr;return!Ye(n)&&!Ye(e)&&5e3>Math.abs(e-n)}Ur(e,n,i){var r=n!==this._sessionActivityTimestamp,s=!(e!==this.Dr||i!==this._sessionStartTimestamp);this._sessionStartTimestamp=i,this._sessionActivityTimestamp=n,this.Dr=e,s&&!r||s&&this.Zr(n)||(this.Pr=n,this.Mr.register({[Kn]:[n,e,i]}))}Gr(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return Dt(n)&&n>0}Qr(){this.Gr()?this.Mr.refreshKey(Kn):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!Ye(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this.Pr){this.Qr();var n=this.Jr();n[1]===this.Dr&&n[2]===this._sessionStartTimestamp&&(this.Pr=this._sessionActivityTimestamp,this.Mr.register({[Kn]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],n=Dt(e)?e:0,i=Dt(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(n,i)}Xr(e){return this.Qr(),this.Lr(e,this.Yr())}Jr(){var e=this.Mr.props[Kn];return U(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Pr=null,clearTimeout(this.tn),this.tn=void 0,this.Ur(null,null,null)}destroy(){this.Fr=!0,this.Kr(),clearTimeout(this.tn),this.tn=void 0,this.Ar&&w&&(w.removeEventListener(ns,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&be.q(this.Br)},ve(w,ns,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=null),this.Ne.cookieless_mode===Wt)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var i=n||new Date().getTime(),r=this.Jr(),s=r[1],o=r[2],a=this.Yr(),l=this.Vr(),u=Dt(o)&&Math.abs(i-o)>864e5,c=!1,d=!1,h=!s,f=s,p=!h&&!e&&this.Lr(i,a);if(p){(p=this.Xr(i))||Si.info("cross-tab refresh kept the session alive",{sessionId:s});var g=this.Jr();s=g[1],o=g[2]}h||p||u?(s=this.$r(),l=this.Nr(),Si.info("new session ID generated",{sessionId:s,windowId:l,changeReason:{noSessionId:h,activityTimeout:p,sessionPastMaximumLength:u}}),o=i,c=!0):(l||(l=this.Nr(),c=!0),(d=s!==f)&&(Si.info("adopted cross-tab session id",{sessionId:s,windowId:l}),c=!0));var m=Dt(a)&&e&&!u?a:i,v=Dt(o)?o:new Date().getTime();this.Wr(l),this.Ur(s,m,v),e||this.qr();var E={noSessionId:h,activityTimeout:p,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((S=>S(s,l,E))),{sessionId:s,windowId:l,sessionStartTimestamp:v,changeReason:c?E:void 0,lastActivityTimestamp:a}}qr(){this.Fr||(clearTimeout(this.tn),this.tn=setTimeout((()=>{if(!this.Fr)if(this.Xr(new Date().getTime())){var e=this.Dr;this.resetSessionId(),this.Ir.emit("forcedIdleReset",{idleSessionId:e})}else this.qr()}),1.1*this.sessionTimeoutMs))}}var jf=function(t,e){if(!t)return!1;var n=t.userAgent;if(n&&_c(n,e))return!0;try{var i=t?.userAgentData;if(i!=null&&i.brands&&i.brands.some((r=>_c(r?.brand,e))))return!0}catch{}return!!t.webdriver};function Uf(){return(Uf=se((function*(){var t=He?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),n=e?.model;return X(n)&&n.length>0?n:void 0}catch(i){return void A.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",i)}}))).apply(this,arguments)}var cs=function(t,e){if(!(function(n){try{new RegExp(n)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function Fo(t,e,n){return Yn({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}var Hf={exact:(t,e)=>e.some((n=>t.some((i=>n===i)))),is_not:(t,e)=>e.every((n=>t.every((i=>n!==i)))),regex:(t,e)=>e.some((n=>t.some((i=>cs(n,i))))),not_regex:(t,e)=>e.every((n=>t.every((i=>!cs(n,i))))),icontains:(t,e)=>e.map(Er).some((n=>t.map(Er).some((i=>n.includes(i))))),not_icontains:(t,e)=>e.map(Er).every((n=>t.map(Er).every((i=>!n.includes(i))))),gt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>i>parseFloat(r)))})),lt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>it.toLowerCase();function Wf(t,e){return!t||Object.entries(t).every((n=>{var i=n[1],r=e?.[n[0]];if(C(r)||Ye(r))return!1;var s=[String(r)],o=Hf[i.operator];return!!o&&o(i.values,s)}))}var xa="custom",eu="i.posthog.com",bm=/^\/static\//;class Em{constructor(e){this.en={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,n=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return n||(n=this.apiHost.replace("."+eu,".posthog.com")),n==="https://app.posthog.com"?"https://us.posthog.com":n}get region(){return this.en[this.apiHost]||(this.en[this.apiHost]=/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"us":/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"eu":xa),this.en[this.apiHost]}rn(e){if(bm.test(e)){var n=this.instance.config.asset_host;if(typeof n=="string")return n.trim().replace(/\/$/,"")||void 0}}endpointFor(e,n){if(n===void 0&&(n=""),n&&(n=n[0]==="/"?n:"/"+n),e==="ui")return this.uiHost+n;if(e==="flags")return this.flagsApiHost+n;if(e==="assets"){var i=this.rn(n);if(i)return""+i+n}if(this.region===xa)return this.apiHost+n;var r=eu+n;switch(e){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}}function zf(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var Q=pe("[Surveys]"),qf="seenSurvey_",Vf=t=>{try{var e=(n=>((i,r)=>""+qf+(function(s){return s.current_iteration&&s.current_iteration>0?s.id+"_"+s.current_iteration:s.id})(r))(0,n))(t);if(localStorage.getItem(e))return;localStorage.setItem(e,"true")}catch(n){Q.error("Failed to persist survey seen state",n)}},Sm=[Io.Popover,Io.Widget,Io.API],xm={ignoreConditions:!1,ignoreDelay:!1,displayType:_a.Popover},Im=pe("[PostHog ExternalIntegrations]"),km={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class Cm{constructor(e){this._instance=e}ai(e,n){var i;(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,e,(r=>{if(r)return Im.error("failed to load script",r);n()}))}startIfEnabledOrStop(){var e=this,n=function(){var s,o,a,l=i[0],u=i[1];!u||(s=B.__PosthogExtensions__)!=null&&(s=s.integrations)!=null&&s[l]||e.ai(km[l],(()=>{var c;(c=B.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=B.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=B.__PosthogExtensions__)==null||(a=a.integrations)==null||(a=a[l])==null||a.stop())};for(var i of Object.entries((r=this._instance.config.integrations)!==null&&r!==void 0?r:{})){var r;n()}}}class Am{constructor(e,n){this.rt=e,this.nn=n,this.sn=new Map,this.an=!1}add(e){var n=this;return se((function*(){if(n.an)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(n.sn.has(e.name))throw new Error('Browser extension "'+e.name+'" is already registered');n.sn.set(e.name,e);try{var i=e.setup(n.nn);i&&(yield i)}catch(s){var r=n.sn.get(e.name)===e;r&&n.sn.delete(e.name),n.rt.error('Failed to set up browser extension "'+e.name+'"',s),r&&n.ln(e)}}))()}dispose(){if(!this.an){this.an=!0;var e=Array.from(this.sn.values()).reverse();for(var n of(this.sn.clear(),e))this.ln(n)}}ln(e){try{var n=e.dispose==null?void 0:e.dispose();n&&je(n.then)&&n.then(void 0,(i=>{this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}))}catch(i){this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}}}class Pm{constructor(e){this._instance=e}initialize(){}get(e){var n=this._instance.persistence;if(typeof e=="string")return n?.get_property(e);var i={};for(var r of e){var s=n?.get_property(r);C(s)||(i[r]=s)}return i}set(e,n){var i;(i=this._instance.persistence)==null||i.register(typeof e=="string"?{[e]:n}:e)}remove(e){var n;(n=this._instance.persistence)==null||n.unregister(e)}}var tu="extensionsRemoteConfig";class Fm{constructor(e){this.an=!1,this.instance=e,this.rt=A,this.un=e.hn,this.kv=new Pm(e),this.onEvent=n=>br(this.instance.on("eventCaptured",(i=>{try{n({event:i.event,properties:i.properties})}catch(r){this.rt.error("Browser extension event listener failed",r)}}))),this.onRemoteConfig=n=>{if(this.an)return br((()=>{}));var i=s=>{try{n(s)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},r=this.instance.dn.on(tu,i);return this.un&&i(this.un),br(r)},this.vn=new Am(A.createLogger("[BrowserExtensions]"),this)}get logger(){return this.rt}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return(e=this.instance.get_property(Yi))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(Yi);return typeof e=="string"?e:void 0}get library(){return{name:ne.LIB_NAME,version:ne.LIB_VERSION}}get initialPersonProperties(){var e,n;return(e=(n=this.instance.persistence)==null?void 0:n.get_initial_props())!==null&&e!==void 0?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,n,i,r,s=(e=this.instance.sessionManager)==null?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:(n=s?.sessionId)!==null&&n!==void 0?n:"",windowId:(i=s?.windowId)!==null&&i!==void 0?i:"",sessionStartTimestamp:(r=s?.sessionStartTimestamp)!==null&&r!==void 0?r:0}}catch{return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get projectToken(){return this.instance.config.token}add(e){return this.vn.add(e)}capture(e,n,i){var r=this;return se((function*(){i?r.instance.capture(e,n,{timestamp:i.timestamp,uuid:i.uuid,$set:i.set,$set_once:i.setOnce}):r.instance.capture(e,n)}))()}registerDynamicEventProperties(e){return br(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(tu,e))}sendRequest(e,n){var i=this;return se((function*(){var r;n===void 0&&(n={});var s=i.instance.requestRouter.endpointFor((r=n.target)!==null&&r!==void 0?r:"api",e),o={method:n.method,url:n.query?ks(s,n.query):s,data:n.body,headers:n.headers,timeout:n.timeoutMs,fireCallbackOnDrop:!0,transport:n.transport,compression:n.compression,timestampMode:n.sentAt};return n.transport==="sendBeacon"?(i.instance._send_request(o),{statusCode:202}):new Promise((a=>{o.callback=a,i.instance._send_request(o)}))}))()}dispose(){this.an||(this.an=!0,this.vn.dispose())}}var Wi={},Ro=0,us=()=>{},nu='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',xi="Surveys module not available",iu="sanitize_properties is deprecated. Use before_send instead",Gf="Invalid value for property_denylist config: ",Rm=["token","distinct_id",Qd],Gn="posthog",Kf=!hm&&Ge?.indexOf("MSIE")===-1&&Ge?.indexOf("Mozilla")===-1,To=t=>{var e;return I({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:Tg(P?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:us,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:t??"unset",__preview_deferred_init_extensions:!1,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:me&&X(me?.search)&&me.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disableDeviceModel:!1,disable_external_dependency_loading:!1,strict_script_versioning:!1,enable_recording_console_log:void 0,secure_cookie:(w==null||(e=w.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(n){A.error("Bad HTTP status: "+n.statusCode+" "+n.text)},get_device_id:n=>n,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:pa,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:Sa},error_tracking:{},_onCapture:us},(n=>({rageclick:n&&n>="2026-05-30"?{content_ignorelist:zg,ignore_text_selection:!0}:!n||"2025-11-30">n||{content_ignorelist:!0},capture_pageview:!n||"2025-05-24">n||"history_change",session_recording:n&&n>="2026-06-25"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6},streamNetworkBody:!0}:n&&n>="2026-05-30"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6}}:n&&n>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:n&&n>="2026-01-30"?"head":"body",internal_or_test_user_hostname:n&&n>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:n&&n>="2026-05-30"?250:0,split_storage:!(!n||"2026-05-30">n),detect_google_search_app:!(!n||"2026-05-30">n),disable_capture_url_hashes:!(!n||"2026-06-25">n)}))(t))},Tm=[["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"]],ru=t=>{var e={};for(var n of Tm){var i=n[0],r=n[1];C(t[i])||(e[r]=t[i])}var s=fe({},e,t),o=t.__preview_external_dependency_versioned_paths;return C(o)||(C(t.strict_script_versioning)&&(s.strict_script_versioning=!!o),X(o)&&C(t.asset_host)&&(s.asset_host=o)),U(t.property_blacklist)&&(C(t.property_denylist)?s.property_denylist=t.property_blacklist:U(t.property_denylist)?s.property_denylist=[...t.property_blacklist,...t.property_denylist]:A.error(Gf+t.property_denylist)),s};class $m{constructor(){this.__forceAllowLocalhost=!1}get fn(){return this.__forceAllowLocalhost}set fn(e){A.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class Ze{pn(e,n){if(e){var i=this.sn.indexOf(e);i!==-1&&this.sn.splice(i,1)}return this.sn.push(n),n.initialize==null||n.initialize(),n}gn(){return this.config.cookieless_mode===Wt||this.config.cookieless_mode===kn&&this.consent.isRejected()}get decideEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){var e;this.webPerformance=new $m,this.mn=!1,this.version=ne.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new pl,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=To(),this.SentryIntegration=Xg,this.sentryIntegration=i=>(function(r,s){var o=_f(r,s);return{name:vf,processEvent:a=>o(a)}})(this,i),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.wn=!1,this.kn=null,this.xn=null,this.Sn=null,this.scrollManager=new ym(this),this.pageViewManager=new Wc(this),this.rateLimiter=new am(this),this.requestRouter=new Em(this),this.consent=new Dg(this),this.externalIntegrations=new Cm(this);var n=(e=Ze.__defaultExtensionClasses)!==null&&e!==void 0?e:{};this.featureFlags=n.featureFlags&&new n.featureFlags(this),this.toolbar=n.toolbar&&new n.toolbar(this),this.surveys=n.surveys&&new n.surveys(this),this.conversations=n.conversations&&new n.conversations(this),this.logs=n.logs&&new n.logs(this),this.metrics=n.metrics&&new n.metrics(this),this.experiments=n.experiments&&new n.experiments(this),this.exceptions=n.exceptions&&new n.exceptions(this),this.people={set:(i,r,s)=>{var o=X(i)?{[i]:r}:i;this.setPersonProperties(o),s?.({})},set_once:(i,r,s)=>{var o=X(i)?{[i]:r}:i;this.setPersonProperties(void 0,o),s?.({})}},this.on("eventCaptured",(i=>A.info('send "'+i?.event+'"',i)))}init(e,n,i){if(i&&i!==Gn){var r,s=(r=Wi[i])!==null&&r!==void 0?r:new Ze;return s._init(e,n,i),Wi[i]=s,Wi[Gn][i]=s,s}return this._init(e,n,i)}_init(e,n,i){var r,s;n===void 0&&(n={});var o,a=X(e)?e.trim():"";if(!a)return A.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return a!==((o=this.config)==null?void 0:o.token)?console.warn("[PostHog.js]","You have already initialized PostHog with a different project token! Re-initializing is a no-op, so events will keep going to the project this instance was initialized with. To capture into a second project, load PostHog once, then initialize a named instance after the SDK has loaded, e.g. posthog.init('"+a+"', { ... }, 'project2')"):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=To(n.defaults),n.debug=this.Cn(n.debug),this.Mn=n,this.Tn=[],n.person_profiles?this.xn=n.person_profiles:n.process_person&&(this.xn=n.process_person);var l=To(n.defaults),u=ru(n),c=fe({},l,u,{name:i,token:a});he(l.rageclick)&&he(u.rageclick)&&(c.rageclick=fe({},l.rageclick,u.rageclick)),he(l.session_recording)&&he(u.session_recording)&&(c.session_recording=fe({},l.session_recording,u.session_recording)),this.set_config(c),this.config.on_xhr_error&&A.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=n.disable_compression?void 0:Ue.GZipJS;var d=this.En();if(this.persistence=new xo(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new xo(I({},this.config,{persistence:"sessionStorage"}),d,!1),this.bn="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&be.N()){var h=be.H(this.bn);U(h)&&h.forEach((k=>{X(k)&&this.yn.add(k)}))}else be.q(this.bn);var f=I({},this.persistence.props),p=I({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new mm((k=>this.Pn(k)),this.config.request_queue_config),this.Rn=new _m(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new Qc(this),this.sessionPropsManager=new Xc(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((k,T,x)=>{(x!=null&&x.activityTimeout||x!=null&&x.sessionPastMaximumLength||x!=null&&x.crossTabAdoption)&&this.An()}))),this.Fn(),this.config.__preview_deferred_init_extensions?(A.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Ln(g)}),0)):(A.info("Initializing extensions synchronously"),this.Ln(g)),ne.DEBUG=ne.DEBUG||this.config.debug,ne.DEBUG&&A.info("Starting in debug mode",{this:this,config:n,thisC:I({},this.config),p:f,s:p}),!this.config.identity_distinct_id||(r=n.bootstrap)!=null&&r.distinctID||(n.bootstrap=I({},n.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((s=n.bootstrap)==null?void 0:s.distinctID)!==void 0){var m=n.bootstrap.distinctID,v=this.get_distinct_id(),E=this.persistence.get_property(at);if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&E===Un)this.identify(m);else if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&E===vn)A.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{var S=this.config.get_device_id(Ht()),_=n.bootstrap.isIdentifiedID?S:m;this.persistence.set_property(at,n.bootstrap.isIdentifiedID?vn:Un),this.register({distinct_id:m,$device_id:_})}}if(g)this.register_once({distinct_id:mr,$device_id:null},"");else if(!this.get_distinct_id()){var b=this.config.get_device_id(Ht());this.register_once({distinct_id:b,$device_id:b},""),this.persistence.set_property(at,Un)}return ve(w,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),n.segment?(function(k,T){var x=k.config.segment;if(!x)return T();(function(F,$){var O=F.config.segment;if(!O)return $();var L=K=>{var V=()=>K.anonymousId()||Ht();F.config.get_device_id=V,K.id()&&(F.register({distinct_id:K.id(),$device_id:V()}),F.persistence.set_property(at,vn)),$()},N=O.user();"then"in N&&je(N.then)?N.then(L):L(N)})(k,(()=>{x.register((F=>{typeof Promise<"u"&&Promise.resolve||Eo.warn("This browser does not have Promise support, and can not use the segment integration");var $=(O,L)=>{if(!L)return O;O.event.userId||O.event.anonymousId===F.get_distinct_id()||(Eo.info("No userId set, resetting PostHog"),F.reset()),O.event.userId&&O.event.userId!==F.get_distinct_id()&&(Eo.info("UserId set, identifying with PostHog"),F.identify(O.event.userId));var N=F.calculateEventProperties(L,O.event.properties);return O.event.properties=Object.assign({},N,O.event.properties),O};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:O=>$(O,O.event.event),page:O=>$(O,Vn),identify:O=>$(O,yo),screen:O=>$(O,"$screen")}})(k)).then((()=>{T()}))}))})(this,(()=>this.On())):this.On(),je(this.config._onCapture)&&this.config._onCapture!==us&&(A.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(k=>this.config._onCapture(k.event,k)))),this.config.ip&&A.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this.config.disableDeviceModel||(function(){return Uf.apply(this,arguments)})().then((k=>{k&&this.register({[vo]:k})})).catch(us),this}Fn(){var e,n,i,r,s,o,a=(e=(n=this.config.__extensionClasses)==null?void 0:n.featureFlags)!==null&&e!==void 0?e:(i=Ze.__defaultExtensionClasses)==null?void 0:i.featureFlags;a&&(this.featureFlags&&this.featureFlags instanceof a||((r=this.Dn)==null||r.call(this),this.Dn=void 0,this.featureFlags=new a(this)),je(this.featureFlags.onReloading)&&je(this.featureFlags.setup)?this.Dn||(this.Dn=this.featureFlags.onReloading((()=>{this.dn.emit("featureFlagsReloading",!0)})),this.$n().add(this.featureFlags)):(s=(o=this.featureFlags).initialize)==null||s.call(o))}Ln(e){var n,i,r,s,o,a,l,u=performance.now(),c=I({},Ze.__defaultExtensionClasses,this.config.__extensionClasses),d=[];c.exceptions&&this.sn.push(this.exceptions=(n=this.exceptions)!==null&&n!==void 0?n:new c.exceptions(this)),c.historyAutocapture&&this.sn.push(this.historyAutocapture=new c.historyAutocapture(this)),c.tracingHeaders&&this.sn.push(this.tracingHeaders=new c.tracingHeaders(this)),c.siteApps&&this.sn.push(this.siteApps=new c.siteApps(this)),c.sessionRecording&&!e&&this.sn.push(this.sessionRecording=new c.sessionRecording(this)),this.config.disable_scroll_properties||d.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),c.autocapture&&this.sn.push(this.autocapture=new c.autocapture(this)),c.surveys&&this.sn.push(this.surveys=(i=this.surveys)!==null&&i!==void 0?i:new c.surveys(this)),c.logs&&this.sn.push(this.logs=(r=this.logs)!==null&&r!==void 0?r:new c.logs(this)),c.metrics&&this.sn.push(this.metrics=(s=this.metrics)!==null&&s!==void 0?s:new c.metrics(this)),c.conversations&&this.sn.push(this.conversations=(o=this.conversations)!==null&&o!==void 0?o:new c.conversations(this)),c.productTours&&this.sn.push(this.productTours=new c.productTours(this)),c.heatmaps&&this.sn.push(this.heatmaps=new c.heatmaps(this)),c.webVitalsAutocapture&&this.sn.push(this.webVitalsAutocapture=new c.webVitalsAutocapture(this)),c.exceptionObserver&&this.sn.push(this.exceptionObserver=new c.exceptionObserver(this)),c.deadClicksAutocapture&&this.sn.push(this.deadClicksAutocapture=new c.deadClicksAutocapture(this,Zg)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((h=>{h.initialize&&d.push((()=>{h.initialize==null||h.initialize()}))})),d.push((()=>{if(this.Nn){var h=this.Nn;this.Nn=void 0,this.sn.forEach((f=>f.onRemoteConfig==null?void 0:f.onRemoteConfig(h)))}})),this.qn(d,u)}qn(e,n){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,n)}),0);var i=e.shift();if(i)try{i()}catch(s){A.error("Error initializing extension:",s)}}var r=Math.round(performance.now()-n);this.register_for_session({[ef]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[tf]:r}),this.config.__preview_deferred_init_extensions&&A.info("PostHog extensions initialized ("+r+"ms)")}Zi(e){var n;if(!P||!P.body)return A.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.Zi(e)}),500);if(this.config.__preview_deferred_init_extensions&&(this.Nn=e),this.hn=e,this.compression=void 0,e.ok){var i,r=e.config;r.supportedCompression&&!this.config.disable_compression&&(this.compression=j(r.supportedCompression,Ue.GZipJS)?Ue.GZipJS:j(r.supportedCompression,Ue.Base64)?Ue.Base64:void 0),(i=r.analytics)!=null&&i.endpoint&&(this.analyticsDefaultEndpoint=r.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:pa}),(n=this.jn)==null||n.handleRemoteConfig(e),this.sn.forEach((s=>s.onRemoteConfig==null?void 0:s.onRemoteConfig(e)))}On(){try{this.config.loaded(this)}catch(i){A.critical("`loaded` function failed",i)}if(this.Bn(),this.config.internal_or_test_user_hostname&&me!=null&&me.hostname){var e=me.hostname,n=this.config.internal_or_test_user_hostname;(typeof n=="string"?e===n:n.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.gn())&&this.Hn()}),1),this.Un=new Af(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()&&vr(this.__request_queue,(e=>this.Pn(e))),this.__request_queue=[],this.Bn()}_handle_unload(){var e,n,i,r,s;(e=this.surveys)==null||e.handlePageUnload==null||e.handlePageUnload(),(n=this.metrics)==null||n.flush("sendBeacon"),this.config.request_batching?(this.zn()&&this.capture(_o),(i=this.logs)==null||i.flushLogs("sendBeacon"),(r=this.In)==null||r.unload(),(s=this.Rn)==null||s.unload()):this.zn()&&this.capture(_o,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?Kf?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)?e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:429})):(e.transport=e.transport||this.config.api_transport,e.headers=I({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,(C(this.config.disable_beacon)?this.config.__preview_disable_beacon:this.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(n=>{var i,r,s,o=I({},n);o.timeout=o.timeout||6e4;var a,l,u,c,d,h=(i=o.transport)!==null&&i!==void 0?i:"fetch";h==="sendBeacon"&&C(o.compression)&&o.data&&(o.compression=Ue.Base64),o.method==="POST"&&o.data&&(o.timestampMode==="capture-body"?o.data={api_key:(l=(d=(c=U(a=o.data)?a:[a])[0])==null||(u=d.properties)==null?void 0:u.token)!==null&&l!==void 0?l:d?.token,batch:c,sent_at:new Date().toISOString()}:o.timestampMode==="body"&&(o.data=(function(m,v){return v===void 0&&(v=new Date().toISOString()),U(m)?m.map((E=>I({},E,{sent_at:v}))):I({},m,{sent_at:v})})(o.data))),o.url=Zc(o.url,o.method,o.compression,o.timestampMode);var f=Lr.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),p=(r=(s=(function(m,v){for(var E=0;m.length>E;E++)if(m[E].transport===h)return m[E]})(f))==null?void 0:s.method)!==null&&r!==void 0?r:f[0].method;if(!p)throw new Error("No available transport method");var g=m=>{try{p(m)}catch(v){Bf(v)?A.warn(v):A.error(v),o.callback==null||o.callback({statusCode:0,error:v})}};h!=="sendBeacon"&&o.data&&o.compression===Ue.GZipJS&&Mp&&typeof Promise<"u"&&!Mr?pm(o).then((m=>{g(m)})).catch((m=>{if(vc(m))return Mr=!0,void g(I({},o,{compression:void 0,url:Zc(n.url,n.method,void 0,n.timestampMode)}));(v=>{if(!v||typeof v!="object")return!1;var E="name"in v?String(v.name):"";return vc(v)||E===hd})(m)&&(Mr=!0),g(o)})):p(o)})(I({},e,{callback:n=>{var i,r;this.rateLimiter.checkForLimiting(n),400>n.statusCode||(i=(r=this.config).on_request_error)==null||i.call(r,n),e.callback==null||e.callback(n)}}))):e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:0}))}Pn(e){this.Rn?this.Rn.retriableRequest(e):this._send_request(e)}_execute_array(e){Ro++;try{var n,i=[],r=[],s=[];vr(e,(a=>{if(a)if(U(n=a[0]))s.push(a);else if(je(a))try{a.call(this)}catch(l){A.error("Error executing queued PostHog call",a,l)}else U(a)&&n==="alias"?i.push(a):U(a)&&n.indexOf("capture")!==-1&&je(this[n])?s.push(a):r.push(a)}));var o=function(a,l){vr(a,(function(u){try{if(U(u[0])){var c=l;ie(u,(function(d){c=c[d[0]].apply(c,d.slice(1))}))}else l[u[0]].apply(l,u.slice(1))}catch(d){A.error("Error executing queued PostHog call",u,d)}}))};o(i,this),o(r,this),o(s,this)}finally{Ro--}}push(e){if(Ro>0&&U(e)&&X(e[0])){var n=Ze.prototype[e[0]];je(n)&&n.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,n,i){var r,s,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.In){if(this.is_capturing())if(!C(e)&&X(e)){var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var c=i!=null&&i.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(c==null||!c.isRateLimited){n!=null&&n.$current_url&&!X(n?.$current_url)&&(A.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),n==null||delete n.$current_url),e!=="$exception"||i!=null&&i.Wn||A.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,h=i?.timestamp||d,f=Ec(i?.uuid,Ht),p={uuid:f,event:e,properties:this.calculateEventProperties(e,n||{},h,f)};e===Vn&&this.config.__preview_capture_bot_pageviews&&u&&(p.event="$bot_pageview",p.properties.$browser_type="bot"),c&&(p.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&p.properties.$feature_flag_has_experiment===!1&&this.get_property(Zr)===!0;i?.$set&&!g&&(p.$set=i?.$set);var m=i?.$unset;m&&(p.$unset=m);var v,E,S,_=g?void 0:this.Vn(i?.$set_once,e!==Ac,e===yo);if(_&&(p.$set_once=_),i!=null&&i._noTruncate||(s=this.config.properties_string_max_length,o=p,a=L=>X(L)?L.slice(0,s):L,l=new Set,p=(function L(N,K){if(N!==Object(N))return a?a(N):N;if(!l.has(N)){var V;if(l.add(N),U(N))V=[],vr(N,(R=>{V.push(L(R))}));else{var M={};ie(N,((R,Z)=>{l.has(R)||(M[Z]=L(R))})),V=M}return V}})(o)),p.timestamp=h,C(i?.timestamp)||(p.properties.$event_time_override_provided=!0,p.properties.$event_time_override_system_time=d),g&&(p.properties=(function(L,N){N===void 0&&(N=[]);var K={},V=M=>{L[M]!==void 0&&(K[M]=L[M])};return Lp.forEach(V),N.forEach(V),K})(p.properties,Rm)),e===qt.DISMISSED||e===qt.SENT){var b=n?.[ko.SURVEY_ID],k=n?.[ko.SURVEY_ITERATION];Vf({id:b,current_iteration:k}),p.$set=I({},p.$set,{[(v={id:b,current_iteration:k},E=e===qt.SENT?"responded":"dismissed",S="$survey_"+E+"/"+v.id,v.current_iteration&&v.current_iteration>0&&(S="$survey_"+E+"/"+v.id+"/"+v.current_iteration),S)]:!0})}else e===qt.SHOWN&&(p.$set=I({},p.$set,{[ko.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===om.SHOWN){var T=n?.[qc.TOUR_TYPE];T&&(p.$set=I({},p.$set,{[qc.TOUR_LAST_SEEN_DATE+"/"+T]:new Date().toISOString()}))}var x=I({},p.properties.$set,p.$set);if(Kt(x)||this.setPersonPropertiesForFlags(x),!H(this.config.before_send)){var F=this.Pt(p);if(!F)return;(p=F).uuid=Ec(p.uuid,Ht)}this.dn.emit("eventCaptured",p);var $=(r=i?._url)!==null&&r!==void 0?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),O={method:"POST",url:$,data:p,compression:"best-available",timestampMode:i?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test($)?"body":"capture-body",batchKey:i?._batchKey,transport:i?.transport};return!this.config.request_batching||i&&(i==null||!i._batchKey)||i!=null&&i.send_instantly?this.Pn(O):this.In.enqueue(O),p}A.critical("This capture call is ignored due to client rate limiting.")}}else A.error("No event name provided to posthog.capture")}else A.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(n=>e(n.event,n)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new Fm(this)}cn(e){this._n.push(e);var n=!0;return()=>{if(n){n=!1;var i=this._n.indexOf(e);i!==-1&&this._n.splice(i,1)}}}calculateEventProperties(e,n,i,r,s){if(i=i||new Date,!this.persistence||!this.sessionPersistence)return n;var o=s?void 0:this.persistence.remove_event_timer(e),a=I({},n);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.gn()&&(a[Qd]=!0),e==="$snapshot"){var l=I({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!X(a.distinct_id)&&!ke(a.distinct_id)||Ko(a.distinct_id))&&A.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=(function(b,k,T,x){var F,$,O,L;if(x===void 0&&(x=!1),!Ge)return{};var N,K=b?[...ri,...k||[]]:[],V=(function(Bn){for(var qe=0;wc.length>qe;qe++){var Dn=wc[qe],Mt=Dn[1],Lt=Dn[0].exec(Bn),ut=Lt&&(je(Mt)?Mt(Lt,Bn):Mt);if(ut)return ut}return["",""]})(Ge),M=V[0],R=V[1],Z=(N=typeof navigator<"u"?navigator:void 0)!=null&&N.brave?{brave:!0}:{},Ce={};C(T)||(Ce.detectGoogleSearchApp=T);var oe={},ye=(F=navigator)==null||(F=F.userAgentData)==null?void 0:F.platform,$e=($=navigator)==null?void 0:$.maxTouchPoints,ae=w==null||(O=w.screen)==null?void 0:O.width,Ie=w==null||(L=w.screen)==null?void 0:L.height,Se=w?.devicePixelRatio;C(ye)||(oe.userAgentDataPlatform=ye),C($e)||(oe.maxTouchPoints=$e),C(ae)||(oe.screenWidth=ae),C(Ie)||(oe.screenHeight=Ie),C(Se)||(oe.devicePixelRatio=Se);var De,wt,ge,Je,bt,mn,Re,Pe,$t=fe(ll({$os:M,$os_version:R,$browser:Bd(Ge,navigator.vendor,Z,Ce),$device:bc(Ge),$device_type:(wt=Ge,ge=oe,Pe=bc(wt),Pe===wd||Pe===yd||Pe==="Kobo"||Pe==="Kindle Fire"||Pe===$d?ei:Pe===Gi||Pe===Xn||Pe===Ki||Pe===Jo?"Console":Pe===Ed?"Wearable":Pe?rt:ge?.userAgentDataPlatform==="Android"&&((Je=ge?.maxTouchPoints)!==null&&Je!==void 0?Je:0)>0?600>Math.min((bt=ge?.screenWidth)!==null&&bt!==void 0?bt:0,(mn=ge?.screenHeight)!==null&&mn!==void 0?mn:0)/((Re=ge?.devicePixelRatio)!==null&&Re!==void 0?Re:1)?rt:ei:"Desktop"),$timezone:Cf(),$timezone_offset:im()}),{$current_url:Zi(x?fn(me?.href):me?.href,K,Xi),$host:me?.host,$pathname:me?.pathname,$raw_user_agent:Ge.length>1e3?Ge.substring(0,997)+"...":Ge,$browser_version:eg(Ge,navigator.vendor,Z,Ce),$browser_language:zc(),$browser_language_prefix:(De=zc(),typeof De=="string"?De.split("-")[0]:void 0),$screen_height:w?.screen.height,$screen_width:w?.screen.width,$viewport_height:w?.innerHeight,$viewport_width:w?.innerWidth,$lib:ne.LIB_NAME,$lib_version:ne.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return ne.SDK_DIST_CHANNEL&&($t.$sdk_dist_channel=ne.SDK_DIST_CHANNEL),$t})(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties,this.config.detect_google_search_app,this.config.disable_capture_url_hashes);if(this.sessionManager){var d=this.sessionManager.checkAndGetSessionAndWindowId(s,i.getTime()),h=d.windowId;a.$session_id=d.sessionId,a.$window_id=h}this.sessionPropsManager&&fe(a,this.sessionPropsManager.getSessionProps());try{var f;this.sessionRecording&&fe(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(f=this.Rn)==null?void 0:f.length}catch(b){a.$sdk_debug_error_capturing_properties=String(b)}if(this.requestRouter.region===xa&&(a.$lib_custom_api_host=this.config.api_host),u=e!==Vn||s?e!==_o||s?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(i):this.pageViewManager.doPageView(i,r),a=fe(a,u),e===Vn&&P&&(a.title=P.title),!C(o)){var p=i.getTime()-o;a.$duration=parseFloat((p/1e3).toFixed(3))}Ge&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();ie(["$referrer","$referring_domain"],(b=>{b in g&&delete m[b]}));var v={};if(this._n.length>0)for(var E of this._n.slice())try{fe(v,E())}catch(b){A.error("Failed to produce browser extension event properties",b)}(a=fe({},c,g,m,I({},v,a))).$is_identified=this._isIdentified(),U(this.config.property_denylist)?ie(this.config.property_denylist,(function(b){delete a[b]})):A.error(Gf+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var S=this.config.sanitize_properties;S&&(A.error(iu),a=S(a,e));var _=this.Zn();return a.$process_person_profile=_,_&&!s&&this.Gn("_calculate_event_properties"),a}Vn(e,n,i){var r;if(n===void 0&&(n=!0),i===void 0&&(i=!1),!this.persistence||!this.Zn()||this.mn&&!i)return e;var s=this.persistence.get_initial_props(),o=(r=this.sessionPropsManager)==null?void 0:r.getSetOnceProps(),a=fe({},s,o||{},e||{}),l=this.config.sanitize_properties;return l&&(A.error(iu),a=l(a,"$set_once")),n&&(this.mn=!0),Kt(a)?void 0:a}register(e,n){var i;(i=this.persistence)==null||i.register(e,n)}register_once(e,n,i){var r;(r=this.persistence)==null||r.register_once(e,n,i)}register_for_session(e){var n;(n=this.sessionPersistence)==null||n.register(e),Object.keys(e).forEach((i=>this.yn.add(i))),this.Qn()}unregister(e){var n;(n=this.persistence)==null||n.unregister(e)}unregister_for_session(e){var n;(n=this.sessionPersistence)==null||n.unregister(e),this.yn.delete(e),this.Qn()}Kn(e,n){this.register({[e]:n})}An(){this.yn.forEach((e=>{var n;(n=this.sessionPersistence)==null||n.unregister(e)})),this.yn.clear(),this.Qn()}Qn(){var e;if(this.bn)if(this.config.persistence==="memory"||(e=this.sessionPersistence)!=null&&e.xi||!be.N())be.q(this.bn);else{var n=[];this.yn.forEach((i=>n.push(i))),n.length>0?be.F(this.bn,n):be.q(this.bn)}}getFeatureFlag(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlag(e,n)}getFeatureFlagPayload(e){var n;return(n=this.featureFlags)==null?void 0:n.getFeatureFlagPayload(e)}getFeatureFlagResult(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlagResult(e,n)}getAllFeatureFlags(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.getAllFeatureFlags())!==null&&e!==void 0?e:[]}isFeatureEnabled(e,n){var i,r;return(i=(r=this.featureFlags)==null?void 0:r.isFeatureEnabled(e,n))!==null&&i!==void 0?i:n?.defaultValue}reloadFeatureFlags(){var e;(e=this.featureFlags)==null||e.reloadFeatureFlags()}updateFlags(e,n,i){var r;(r=this.featureFlags)==null||r.updateFlags(e,n,i)}updateEarlyAccessFeatureEnrollment(e,n,i){var r;(r=this.featureFlags)==null||r.updateEarlyAccessFeatureEnrollment(e,n,i)}getEarlyAccessFeatures(e,n,i){var r;return n===void 0&&(n=!1),(r=this.featureFlags)==null?void 0:r.getEarlyAccessFeatures(e,n,i)}on(e,n){return this.dn.on(e,n)}onFeatureFlags(e){return this.featureFlags?this.featureFlags.onFeatureFlags(e):(e([],{},{errorsLoading:!0}),()=>{})}onSurveysLoaded(e){return this.surveys?this.surveys.onSurveysLoaded(e):(e([],{isLoaded:!1,error:xi}),()=>{})}onSessionId(e){var n,i;return(n=(i=this.sessionManager)==null?void 0:i.onSessionId(e))!==null&&n!==void 0?n:()=>{}}getSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getSurveys(e,n):e([],{isLoaded:!1,error:xi})}getActiveMatchingSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,n):e([],{isLoaded:!1,error:xi})}renderSurvey(e,n){var i;(i=this.surveys)==null||i.renderSurvey(e,n)}displaySurvey(e,n){var i;n===void 0&&(n=xm),(i=this.surveys)==null||i.displaySurvey(e,n)}cancelPendingSurvey(e){var n;(n=this.surveys)==null||n.cancelPendingSurvey(e)}canRenderSurvey(e){var n,i;return(n=(i=this.surveys)==null?void 0:i.canRenderSurvey(e))!==null&&n!==void 0?n:{visible:!1,disabledReason:xi}}canRenderSurveyAsync(e,n){var i,r;return n===void 0&&(n=!1),(i=(r=this.surveys)==null?void 0:r.canRenderSurveyAsync(e,n))!==null&&i!==void 0?i:Promise.resolve({visible:!1,disabledReason:xi})}Jn(e){return!e||Ko(e)?(A.critical("Unique user id has not been set in posthog.identify"),!1):e===mr?(A.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.'),!1):!["distinct_id","distinctid"].includes(e.toLowerCase())&&!["undefined","null"].includes(e.toLowerCase())||(A.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.'),!1)}identify(e,n,i){if(!this.__loaded||!this.persistence)return A.uninitializedWarning("posthog.identify");if(ke(e)&&(e=e.toString(),A.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.Jn(e)&&this.Gn("posthog.identify")){var r=this.get_distinct_id();this.register({$user_id:e}),this.get_property(Yi)||this.register_once({$had_persisted_distinct_id:!0,$device_id:r},""),e!==r&&e!==this.get_property(Fi)&&(this.unregister(Fi),this.register({distinct_id:e}));var s,o=(this.persistence.get_property(at)||Un)===Un,a=e!==r,l=!a&&o;if(a&&o)this.persistence.set_property(at,vn),this.setPersonPropertiesForFlags({$set:n||{},$set_once:i||{}},!1),this.capture(yo,{distinct_id:e,$anon_distinct_id:r},{$set:n||{},$set_once:i||{}}),this.Sn=Fo(e,n,i),(s=this.featureFlags)==null||s.setAnonymousDistinctId(r);else if(l){this.persistence.set_property(at,vn);var u=n||{},c=i||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=Fo(e,n,i)}else(n||i)&&this.setPersonProperties(n,i);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Cn)):l&&(n||i)&&this.reloadFeatureFlags()}}setPersonProperties(e,n){if((e||n)&&this.Gn("posthog.setPersonProperties")){var i=Fo(this.get_distinct_id(),e,n);this.Sn!==i?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:n||{}},!0),this.capture("$set",{$set:e||{},$set_once:n||{}}),this.Sn=i):A.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}unsetPersonProperties(e){var n,i=(U(e)?e:[e]).filter((r=>X(r)&&r.length>0));i.length!==0&&this.Gn("posthog.unsetPersonProperties")&&((n=this.featureFlags)==null||n.unsetPersonPropertiesForFlags(i,!0),this.capture("$set",{$unset:i}),this.Sn=null)}group(e,n,i){if(e&&n){var r=this.getGroups(),s=r[e]!==n;if(s&&this.resetGroupPropertiesForFlags(e),this.register({$groups:I({},r,{[e]:n})}),s||i){var o={$group_type:e,$group_key:n};i&&(o.$group_set=i),this.capture(Ac,o)}i&&this.setGroupPropertiesForFlags({[e]:i}),s&&!i&&this.reloadFeatureFlags()}else A.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),(i=this.featureFlags)==null||i.setPersonPropertiesForFlags(e,n)}resetPersonPropertiesForFlags(e){var n;e===void 0&&(e=!0),(n=this.featureFlags)==null||n.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((i=this.featureFlags)==null||i.setGroupPropertiesForFlags(e,n))}resetGroupPropertiesForFlags(e){var n;(n=this.featureFlags)==null||n.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,n){var i,r,s,o,a,l,u,c,d,h;if(n===void 0&&(n=!1),A.info("reset"),!this.__loaded)return A.uninitializedWarning("posthog.reset");var f,p=this.get_property(Yi),g=this.get_property(vo),m=this.get_property(An),v=this.is_capturing();if(this.consent.reset(),n||!v||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after."),(i=this.persistence)==null||i.clear(),(r=this.sessionPersistence)==null||r.clear(),this.yn.clear(),this.Qn(),C(m)||(f=this.persistence)==null||f.register({[An]:m}),(s=this.surveys)==null||s.reset(),(o=this.Un)==null||o.stop(),(a=this.featureFlags)==null||a.reset(),(l=this.conversations)==null||l.reset(),(u=this.logs)==null||u.reset(),(c=this.metrics)==null||c.reset(),(d=this.persistence)==null||d.set_property(at,Un),(h=this.sessionManager)==null||h.resetSessionId(),this.Sn=null,this.config.cookieless_mode===Wt)this.register_once({distinct_id:mr,$device_id:null},"");else{var E=this.config.get_device_id(Ht());this.register_once({distinct_id:E,$device_id:e?E:p},""),e||C(g)||this.register({[vo]:g})}this.register({$last_posthog_reset:new Date().toISOString()},1),delete this.config.identity_distinct_id,delete this.config.identity_hash,this.reloadFeatureFlags()}shutdown(e){var n=this;return se((function*(){var i,r,s,o,a,l,u;if(n.__loaded){(i=n.Un)==null||i.stop(),(r=n.jn)==null||r.dispose(),(s=n.sessionRecording)==null||s.dispose(),(o=n.logs)==null||o.flushLogs("sendBeacon"),(a=n.metrics)==null||a.flush("sendBeacon"),(l=n.In)==null||l.unload(),(u=n.Rn)==null||u.unload();try{var c;(c=n.featureFlags)==null||c.destroy()}catch(d){A.error("Error while destroying feature flags",d)}}else A.uninitializedWarning("posthog.shutdown")}))()}setIdentity(e,n){var i;this.config.identity_distinct_id=e,this.config.identity_hash=n,this.alias(e),(i=this.conversations)==null||i.Xn()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,(e=this.conversations)==null||e.ts()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,n;return(e=(n=this.sessionManager)==null?void 0:n.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var n=this.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.sessionStartTimestamp,r=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+n.sessionId);if(e!=null&&e.withTimestamp&&i){var s,o=(s=e.timestampLookBack)!==null&&s!==void 0?s:10;if(!i)return r;r+="?t="+Math.max(Math.floor((new Date().getTime()-i)/1e3)-o,0)}return r}alias(e,n){return e===this.get_property(Gd)?(A.critical("Attempting to create alias for existing People user - aborting."),-2):this.Gn("posthog.alias")?(C(n)&&(n=this.get_distinct_id()),e!==n?(this.Kn(Fi,e),this.capture("$create_alias",{alias:e,distinct_id:n})):(A.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var n=I({},this.config);if(he(e)){var i,r,s,o,a,l,u,c,d,h,f,p;fe(this.config,ru(e));var g=this.En();(i=this.persistence)==null||i.update_config(this.config,n,g),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new xo(I({},this.config,{persistence:"sessionStorage"}),g,!1);var m=this.Cn(this.config.debug);mt(m)&&(this.config.debug=m),mt(this.config.debug)&&(this.config.debug?(ne.DEBUG=!0,le.N()&&le.F("ph_debug",!0),A.info("set_config",{config:e,oldConfig:n,newConfig:I({},this.config)})):(ne.DEBUG=!1,le.N()&&le.q("ph_debug"))),(r=this.featureFlags)==null||r.updateConfig==null||r.updateConfig(this.config,this.Qi()),(s=this.exceptionObserver)==null||s.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(h=this.deadClicksAutocapture)==null||h.startIfEnabledOrStop(),(f=this.surveys)==null||f.loadIfEnabled(),this.es(),(p=this.externalIntegrations)==null||p.startIfEnabledOrStop()}}_overrideSDKInfo(e,n){ne.LIB_NAME=e,ne.LIB_VERSION=n}startSessionRecording(e){var n,i,r,s,o,a=e===!0,l={sampling:a||!(e==null||!e.sampling),linked_flag:a||!(e==null||!e.linked_flag),url_trigger:a||!(e==null||!e.url_trigger),event_trigger:a||!(e==null||!e.event_trigger)};Object.values(l).some(Boolean)&&((n=this.sessionManager)==null||n.checkAndGetSessionAndWindowId(),l.sampling&&((i=this.sessionRecording)==null||i.overrideSampling()),l.linked_flag&&((r=this.sessionRecording)==null||r.overrideLinkedFlag()),l.url_trigger&&((s=this.sessionRecording)==null||s.overrideTrigger("url")),l.event_trigger&&((o=this.sessionRecording)==null||o.overrideTrigger("event"))),this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,n){if(this.exceptions){var i=new Error("PostHog syntheticException"),r=this.exceptions.buildProperties(e,{handled:!0,syntheticException:i});return this.exceptions.sendExceptionEvent(I({},r,n))}}addExceptionStep(e,n){var i;(i=this.exceptions)==null||i.addExceptionStep(e,n)}captureLog(e){var n;(n=this.logs)==null||n.captureLog(e)}get logger(){var e,n;return(e=(n=this.logs)==null?void 0:n.logger)!==null&&e!==void 0?e:Ze.rs}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var n,i;return(n=(i=this.toolbar)==null?void 0:i.loadToolbar(e))!==null&&n!==void 0&&n}get_property(e){var n;return(n=this.persistence)==null?void 0:n.props[e]}getSessionProperty(e){var n;return(n=this.sessionPersistence)==null?void 0:n.props[e]}toString(){var e,n=(e=this.config.name)!==null&&e!==void 0?e:Gn;return n!==Gn&&(n=Gn+"."+n),n}_isIdentified(){var e,n;return((e=this.persistence)==null?void 0:e.get_property(at))===vn||((n=this.sessionPersistence)==null?void 0:n.get_property(at))===vn}Zn(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles===pa&&!this._isIdentified()&&Kt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[Fi])&&((n=this.persistence)==null||(n=n.props)==null||!n[es]))}zn(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Zn()||this.Gn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.Gn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}Gn(e){return this.config.person_profiles==="never"?(A.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Kn(es,!0),!0)}En(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut();return this.config.disable_persistence||e&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!==kn)}es(){var e,n,i,r,s=this.En();return((e=this.persistence)==null?void 0:e.xi)!==s&&((i=this.persistence)==null||i.set_disabled(s)),((n=this.sessionPersistence)==null?void 0:n.xi)!==s&&((r=this.sessionPersistence)==null||r.set_disabled(s)),s&&(this.yn.clear(),this.Qn()),s}opt_in_capturing(e){var n;if(this.config.cookieless_mode!==Wt){if(this.gn()){var i,r,s,o,a;this.Yn(!0,!0),(i=this.sessionManager)==null||i.destroy(),(r=this.pageViewManager)==null||r.destroy(),this.sessionManager=new Qc(this),this.pageViewManager=new Wc(this),this.persistence&&(this.sessionPropsManager=new Xc(this,this.sessionManager,this.persistence));var l,u=(s=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&s!==void 0?s:(a=Ze.__defaultExtensionClasses)==null?void 0:a.sessionRecording;u&&(this.sessionRecording=this.pn(this.sessionRecording,new u(this)),this.hn&&((l=this.sessionRecording)==null||l.onRemoteConfig==null||l.onRemoteConfig(this.hn)))}var c,d;this.consent.optInOut(!0),this.es(),this.Bn(),(n=this.sessionRecording)==null||n.startIfEnabledOrStop(),this.config.cookieless_mode==kn&&((c=this.surveys)==null||c.loadIfEnabled()),(C(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((d=e?.captureEventName)!==null&&d!==void 0?d:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hn()}else A.warn(nu)}opt_out_capturing(){var e,n,i;this.config.cookieless_mode!==Wt?(this.config.cookieless_mode===kn&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===kn&&(this.register({distinct_id:mr,$device_id:null}),(e=this.sessionRecording)==null||e.stopRecording(),this.sessionRecording=void 0,(n=this.sessionManager)==null||n.destroy(),(i=this.pageViewManager)==null||i.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.Hn(),this.Bn())):A.warn(nu)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===Wt||(this.config.cookieless_mode===kn?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return He?jf(He,this.config.custom_blocked_useragents):void 0}Hn(){P&&(P.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(Vn,{title:P.title},{send_instantly:!0}),this.kn&&(P.removeEventListener(ts,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),ve(P,ts,this.kn)))}debug(e){e===!1?(w?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(w?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}Qi(){var e=this.Mn||{};return"advanced_disable_flags"in e?!!e.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(A.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(function(n,i,r,s,o){var a=i in n&&!H(n[i]),l=r in n&&!H(n[r]);return a?n[i]:!!l&&(o&&o.warn("Config field '"+r+"' is deprecated. Please use '"+i+"' instead. The old field will be removed in a future major version."),n[r])})(e,"advanced_disable_flags","advanced_disable_decide",0,A)}Pt(e){var n;if(H(this.config.before_send))return e;var i=Object.keys((n=e.properties)!==null&&n!==void 0?n:{}).filter(Hp),r=U(this.config.before_send)?this.config.before_send:[this.config.before_send],s=e;for(var o of r){if(s=o(s),H(s)){var a="Event '"+e.event+"' was rejected in beforeSend function";return Up(e.event)?A.warn(a+". This can cause unexpected behavior."):A.info(a),null}s.properties&&!Kt(s.properties)||A.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}for(var l of i)if(s.properties&&H(s.properties[l]))return A.warn("Event '"+e.event+"' had its '"+l+"' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped."),null;return s}getPageViewId(){var e;return(e=this.pageViewManager.ui)==null?void 0:e.pageViewId}captureTraceFeedback(e,n){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:n})}captureTraceMetric(e,n,i){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:n,$ai_metric_value:String(i)})}Cn(e){var n=mt(e)&&!e,i=le.N()&&le.P("ph_debug")==="true";return!n&&(!!i||e)}}Ze.__defaultExtensionClasses={},Ze.rs=(()=>{var t=()=>{};return{trace:t,debug:t,info:t,warn:t,error:t,fatal:t}})(),(function(t,e){for(var n=0;e.length>n;n++)t.prototype[e[n]]=Fg(t.prototype[e[n]])})(Ze,["identify"]);class su{constructor(e){this.disabled=e===!1;var n=he(e)?e:{};this.thresholdPx=n.threshold_px||30,this.timeoutMs=n.timeout_ms||1e3,this.clickCount=n.click_count||3,this.clicks=[]}isRageClick(e,n,i){if(this.disabled)return!1;var r=this.clicks[this.clicks.length-1];if(r&&Math.abs(e-r.x)+Math.abs(n-r.y)i-r.timestamp){if(this.clicks.push({x:e,y:n,timestamp:i}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:n,timestamp:i}];return!1}}var $o="$copy_autocapture",Mo=pe("[AutoCapture]");function Lo(t,e){return e.length>t?e.slice(0,t)+"...":e}function Mm(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!hn(e));return e}function Lm(t,e){var n,i,r=e.e,s=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!hn(t))return{props:{}};for(var c=[t],d=new Set([t]),h=t;h.parentNode&&!et(h,"body")&&uf>c.length;)if(cf(h.parentNode)){var f=h.parentNode.host;if(d.has(f))break;d.add(f),c.push(f),h=f}else{if(!hn(h.parentNode)||d.has(h.parentNode))break;d.add(h.parentNode),c.push(h.parentNode),h=h.parentNode}var p,g,m=[],v={},E=!1,S=!1;if(ie(c,(x=>{var F=va(x);if(et(x,"a")){var $=x.getAttribute("href");E=!!(F&&$&&Ui($))&&(u?fn($):$)}j(rs(x),"ph-no-capture")&&(S=!0),m.push((function(L,N,K,V,M){M===void 0&&(M=!1);var R=L.tagName.toLowerCase(),Z={tag_name:R};ul.indexOf(R)>-1&&!K&&(Z.$el_text=R.toLowerCase()==="a"||R.toLowerCase()==="button"?Lo(1024,jc(L)):Lo(1024,Ji(L)));var Ce=rs(L);Ce.length>0&&(Z.classes=Ce.filter((function(ae){return ae!==""}))),ie(L.attributes,(function(ae){var Ie;if((!gf(L)||["name","id","class","aria-label"].indexOf(ae.name)!==-1)&&(V==null||!V.includes(ae.name))&&!N&&Ui(ae.value)&&(!X(Ie=ae.name)||Ie.substring(0,10)!=="_ngcontent"&&Ie.substring(0,7)!=="_nghost")){var Se=ae.value;ae.name==="class"&&(Se=cl(Se).join(" ")),Z["attr__"+ae.name]=Lo(1024,ae.name==="href"&&M?fn(Se):Se)}}));for(var oe=1,ye=1,$e=L;$e=Mm($e);)oe++,$e.tagName===L.tagName&&ye++;return Z.nth_child=oe,Z.nth_of_type=ye,Z})(x,s,o,a,u));var O=(function(L){if(!va(L))return{};var N={};return ie(L.attributes,(function(K){if(K.name&&K.name.indexOf("data-ph-capture-attribute")===0){var V=K.name.replace("data-ph-capture-attribute-",""),M=K.value;V&&M&&Ui(M)&&(N[V]=M)}})),N})(x);fe(v,O)})),S)return{props:{},explicitNoCapture:S};if(o||(m[0].$el_text=et(t,"a")||et(t,"button")?jc(t):Ji(t)),E){var _,b;m[0].attr__href=E;var k=(_=ss(E))==null?void 0:_.host,T=w==null||(b=w.location)==null?void 0:b.host;k&&T&&k!==T&&(p=E)}return{props:fe({$event_type:r.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(x){return x.map((F=>{var $,O,L="";if(F.tag_name&&(L+=F.tag_name),F.attr_class)for(var N of(F.attr_class.sort(),F.attr_class))L+="."+N.replace(/"/g,"");var K=I({},F.text?{text:F.text}:{},{"nth-child":($=F.nth_child)!==null&&$!==void 0?$:0,"nth-of-type":(O=F.nth_of_type)!==null&&O!==void 0?O:0},F.href?{href:F.href}:{},F.attr_id?{attr_id:F.attr_id}:{},F.attributes),V={};return $r(K).sort(((M,R)=>M[0].localeCompare(R[0]))).forEach((M=>{var R=M[1];return V[Uc(M[0].toString())]=Uc(R.toString())})),(L+=":")+$r(V).map((M=>M[0]+'="'+M[1]+'"')).join("")})).join(";")})((function(x){return x.map((F=>{var $,O,L={text:($=F.$el_text)==null?void 0:$.slice(0,400),tag_name:F.tag_name,href:(O=F.attr__href)==null?void 0:O.slice(0,2048),attr_class:Yg(F),attr_id:F.attr__id,nth_child:F.nth_child,nth_of_type:F.nth_of_type,attributes:{}};return $r(F).filter((N=>N[0].indexOf("attr__")===0)).forEach((N=>L.attributes[N[0]]=N[1])),L}))})(g)))},(n=m[0])!=null&&n.$el_text?{$el_text:(i=m[0])==null?void 0:i.$el_text}:{},p&&r.type==="click"?{$external_click_url:p}:{},v)}}var Ii=pe("[ExceptionAutocapture]"),ou=()=>{},Nm=pe("[TracingHeaders]"),wn=pe("[Web Vitals]"),au=9e5,lu="disabled",cu="lazy_loading",ki="awaiting_config",Sr="missing_config";pe("[SessionRecording]"),pe("[SessionRecording]");var Ia="[SessionRecording]",Bt=pe(Ia),Om=pe("[Heatmaps]");function No(t){return he(t)&&"clientX"in t&&"clientY"in t&&ke(t.clientX)&&ke(t.clientY)}var xr=pe("[Product Tours]"),Oo=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(sl))},Bm=["$set_once","$set"],Et=pe("[SiteApps]"),uu="Error while initializing PostHog app with config id ";function zn(t,e,n){if(H(t))return!1;switch(n){case"exact":return t===e;case"contains":var i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(i,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}class Dm{constructor(e){this.ns=new pl,this.ss=(n,i)=>this.os(n,i)&&this.ls(n,i)&&this.us(n,i)&&this.hs(n,i),this.os=(n,i)=>i==null||!i.event||n?.event===i?.event,this._instance=e,this.ds=new Set,this.vs=new Set}init(){var e,n;C((e=this._instance)==null?void 0:e._addCaptureHook)||(n=this._instance)==null||n._addCaptureHook(((i,r)=>{this.on(i,r)}))}register(e){var n,i;if(!C((n=this._instance)==null?void 0:n._addCaptureHook)&&(e.forEach((o=>{var a,l;(a=this.vs)==null||a.add(o),(l=o.steps)==null||l.forEach((u=>{var c;(c=this.ds)==null||c.add(u?.event||"")}))})),(i=this._instance)!=null&&i.autocapture)){var r,s=new Set;e.forEach((o=>{var a;(a=o.steps)==null||a.forEach((l=>{l!=null&&l.selector&&s.add(l?.selector)}))})),(r=this._instance)==null||r.autocapture.setElementSelectors(s)}}on(e,n){var i;n!=null&&e.length!=0&&(this.ds.has(e)||this.ds.has(n.event))&&this.vs&&((i=this.vs)==null?void 0:i.size)>0&&this.vs.forEach((r=>{this.cs(n,r)&&this.ns.emit("actionCaptured",r.name)}))}fs(e){this.onAction("actionCaptured",(n=>e(n)))}cs(e,n){if(n?.steps==null)return!1;for(var i of n.steps)if(this.ss(e,i))return!0;return!1}onAction(e,n){return this.ns.on(e,n)}ls(e,n){if(n!=null&&n.url){var i,r=e==null||(i=e.properties)==null?void 0:i.$current_url;if(!r||typeof r!="string"||!zn(r,n.url,n.url_matching||"contains"))return!1}return!0}us(e,n){return!!this.ps(e,n)&&!!this.gs(e,n)&&!!this.ys(e,n)}ps(e,n){var i;if(n==null||!n.href)return!0;var r=this.bs(e);if(r.length>0)return r.some((a=>zn(a.href,n.href,n.href_matching||"exact")));var s,o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!o&&zn((s=o.match(/(?::|")href="(.*?)"/))?s[1]:"",n.href,n.href_matching||"exact")}gs(e,n){var i;if(n==null||!n.text)return!0;var r=this.bs(e);if(r.length>0)return r.some((u=>zn(u.text,n.text,n.text_matching||"exact")||zn(u.$el_text,n.text,n.text_matching||"exact")));var s,o,a,l=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!l&&(s=(function(u){for(var c,d=[],h=/(?::|")text="(.*?)"/g;!H(c=h.exec(u));)d.includes(c[1])||d.push(c[1]);return d})(l),o=n.text,a=n.text_matching||"exact",s.some((u=>zn(u,o,a))))}ys(e,n){var i,r;if(n==null||!n.selector)return!0;var s=e==null||(i=e.properties)==null?void 0:i.$element_selectors;if(s!=null&&s.includes(n.selector))return!0;var o=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";if(n.selector_regex&&o)try{return new RegExp(n.selector_regex).test(o)}catch{return!1}return!1}bs(e){var n;return(e==null||(n=e.properties)==null?void 0:n.$elements)==null?[]:e?.properties.$elements}hs(e,n){return n==null||!n.properties||n.properties.length===0||Wf(n.properties.reduce(((i,r)=>{var s=U(r.value)?r.value.map(String):r.value!=null?[String(r.value)]:[];return i[r.key]={values:s,operator:r.operator||"exact"},i}),{}),e?.properties)}}class jm{constructor(e){var n;this._s=[],this._instance=e,this.ws=new Map,this.ks=new Map,this.xs=new Map,(n=this._instance)==null||n.onSessionId==null||n.onSessionId((i=>this.Ss(i)))}Cs(e){return!1}Ms(){return null}Ts(e){}Es(){}Is(e,n){return!!e&&Wf(e.propertyFilters,n?.properties)}Ps(e,n){var i=new Map;return e.forEach((r=>{var s;(s=r.conditions)==null||(s=s[n])==null||(s=s.values)==null||s.forEach((o=>{if(o!=null&&o.name){var a=i.get(o.name)||[];a.push(r.id),i.set(o.name,a)}}))})),i}Rs(e,n,i){var r=(i===wi.Activation?this.ws:this.ks).get(e),s=[];return this.As((o=>{s=o.filter((a=>r?.includes(a.id)))})),s.filter((o=>{var a,l=(a=o.conditions)==null||(a=a[i])==null||(a=a.values)==null?void 0:a.find((u=>u.name===e));return this.Is(l,n)}))}register(e){var n;C((n=this._instance)==null?void 0:n._addCaptureHook)||(this.Fs(e),this.Ls(e))}Ls(e){var n=e.filter((i=>{var r,s;return((r=i.conditions)==null?void 0:r.actions)&&((s=i.conditions)==null||(s=s.actions)==null||(s=s.values)==null?void 0:s.length)>0}));n.length!==0&&(this.Os==null&&(this.Os=new Dm(this._instance),this.Os.init(),this.Os.fs((i=>{this.onAction(i)}))),n.forEach((i=>{var r,s,o,a,l;i.conditions&&(r=i.conditions)!=null&&r.actions&&(s=i.conditions)!=null&&(s=s.actions)!=null&&s.values&&((o=i.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.Os)==null||a.register(i.conditions.actions.values),(l=i.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var c=this.xs.get(u.name);c&&c.push(i.id),this.xs.set(u.name,c||[i.id])}})))})))}Fs(e){var n,i=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.events)&&((a=s.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0})),r=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.cancelEvents)&&((a=s.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0}));i.length===0&&r.length===0||((n=this._instance)==null||n._addCaptureHook(((s,o)=>{this.onEvent(s,o)})),this.ws=this.Ps(e,wi.Activation),this.ks=this.Ps(e,wi.Cancellation))}onEvent(e,n){var i,r,s=this.Ds(),o=(n==null||(i=n.properties)==null?void 0:i.$survey_id)||(n==null||(r=n.properties)==null?void 0:r.$product_tour_id);if(o&&this.getActivatedIds().includes(o)){var a=this.$s(e,o);if(a==="consume")return s.info("event consumed activated item, removing it",{event:e,itemId:o}),void this.Ns([o]);if(a==="persist")return s.info("shown item promoted to persisted activation",{event:e,itemId:o}),this.qs(o),void this.js([o])}if(this.ks.has(e)){var l=this.Rs(e,n,wi.Cancellation);l.length>0&&(s.info("cancel event matched, cancelling items",{event:e,itemsToCancel:l.map((c=>c.id))}),this.Ns(l.map((c=>c.id))),l.forEach((c=>this.Bs(c.id))))}if(this.ws.has(e)){s.info("event name matched",{event:e,eventPayload:n,items:this.ws.get(e)});var u=this.Rs(e,n,wi.Activation);this.Hs(u.map((c=>c.id)))}}onAction(e){this.xs.has(e)&&this.Hs(this.xs.get(e)||[])}Hs(e){var n;if(e.length!==0){var i=!((n=this._instance)==null||n.get_session_id==null||!n.get_session_id()),r=[];for(var s of e)i&&this.Cs(s)?this.qs(s)&&this.Us(s):r.push(s);r.length>0&&(this._s=[...new Set([...this._s,...r])]),this.Ds().info("updating activated items",{activatedItems:this.getActivatedIds()})}}qs(e){this._s=this._s.filter((i=>i!==e));var n=this.zs();return!n.includes(e)&&(this.Ws([...n,e]),this.Vs(),!0)}Ns(e){var n=new Set(e);this._s=this._s.filter((s=>!n.has(s)));var i=this.Zs(),r=i.filter((s=>!n.has(s)));r.length!==i.length&&(this.Ws(r),r.length===0&&this.Gs()),this.js(e)}Qs(){var e,n=this.Ms();if(!n)return{};var i=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n];return i&&typeof i=="object"?i:{}}Us(e){if(this.Ms()){var n=this.Qs();this.Ts(I({},n,{[e]:Date.now()}))}}js(e){if(this.Ms()){var n=this.Qs(),i={},r=!1;for(var s of Object.entries(n)){var o=s[0],a=s[1];e.includes(o)?r=!0:i[o]=a}r&&(Kt(i)?this.Es():this.Ts(i))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var n=this.Qs()[e];return ke(n)?n:void 0}}Zs(){var e,n=this.Js();return((e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n])||[]}zs(){var e,n,i=this.Zs();if(i.length===0)return[];var r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[this.Ys()],s=(n=this._instance)==null||n.get_session_id==null?void 0:n.get_session_id();return s&&r===s?i:[]}Vs(){var e,n=(e=this._instance)==null||e.get_session_id==null?void 0:e.get_session_id();n&&this.Xs(n)}Gs(){this.ta()}Ss(e){var n,i=(n=this._instance)==null||(n=n.persistence)==null?void 0:n.props[this.Ys()];if(i&&i!==e){var r=this.Zs(),s=this.Qs();r.length>0&&(this.Ws([]),r.filter((o=>ke(s[o]))).forEach((o=>this.Bs(o)))),this.Gs(),this.Ks()}}getActivatedIds(){return[...new Set([...this.zs(),...this._s])].filter((e=>!this.ea(e)))}reset(){this._s=[],this.Zs().length>0&&this.Ws([]),this.Gs(),this.Ks()}getEventToItemsMap(){return this.ws}ia(){return this.Os}}class Um extends jm{constructor(e){super(e)}Js(){return ca}Ys(){return Fr}Ms(){return Rr}Ts(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Rr]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Rr)}Cs(e){var n,i;this.As((s=>{i=s.find((o=>o.id===e))}));var r=(n=i)==null||(n=n.appearance)==null?void 0:n.surveyPopupDelaySeconds;return ke(r)&&r>0}ra(){return qt.SHOWN}As(e){var n;(n=this._instance)==null||n.getSurveys(e)}Bs(e){var n;(n=this._instance)==null||n.cancelPendingSurvey(e)}Ds(){return Q}Ws(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[ca]:e})}Xs(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Fr]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Fr)}ea(){return!1}$s(e,n){var i;this.As((s=>{i=s.find((o=>o.id===n))}));var r=!i||(function(s){var o;return zf(s)&&!((o=s.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||s.schedule==="always"})(i);return r?e===qt.SHOWN?"consume":"ignore":e===qt.SHOWN?"persist":e===qt.DISMISSED||e===qt.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var Ir="SDK is not enabled or survey functionality is not yet loaded",du="Disabled. Not loading surveys.",Hm=w!=null&&w.location?os(w.location.hash,"__posthog")||os(location.hash,"state"):null,fu="_postHogToolbarParams",hu=pe("[Toolbar]"),pu=pe("[FeatureFlags]");class Wm{constructor(e,n){n===void 0&&(n=!1),this.na=!1,this.update(e,n)}update(e,n){this.sa=((i,r)=>{var s,o,a,l;return{bootstrap:{featureFlags:(s=i.bootstrap)==null?void 0:s.featureFlags,featureFlagPayloads:(o=i.bootstrap)==null?void 0:o.featureFlagPayloads},remoteRequestsDisabled:r,featureFlagsDisabled:!!i.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!i.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!i.advanced_feature_flags_dedup_per_session,cacheTtlMs:i.feature_flag_cache_ttl_ms,requestTimeoutMs:i.feature_flag_request_timeout_ms,compression:i.disable_compression?"none":"base64",evaluationContexts:(a=(l=i.evaluation_contexts)!==null&&l!==void 0?l:i.evaluation_environments)!==null&&a!==void 0?a:[],flagKeys:U(i.flag_keys)?i.flag_keys:void 0}})(e,n),!e.evaluation_environments||e.evaluation_contexts||this.na||(pu.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.na=!0),C(e.flag_keys)||U(e.flag_keys)||pu.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var gu=pe("[FeatureFlags]"),bn=pe("[FeatureFlags]",{debugEnabled:!0}),Bo=`" failed. Feature flags didn't load in time.`,mu="connection_error",vu=t=>{for(var e={},n=0;t.length>n;n++)e[t[n]]=!0;return e},_u=t=>{var e={};for(var n of $r(t||{})){var i=n[1];i&&(e[n[0]]=i)}return e},St=pe("[Error tracking]"),yu="Refusing to render web experiment since the viewer is a likely bot",zm={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>cs(e,t),not_regex:(t,e)=>!cs(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class Me{get Ne(){return this._instance.config}constructor(e){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(i){i===void 0&&(i=!1),n.getWebExperiments((r=>{Me.aa("retrieved web experiments from the server"),n.oa=new Map,r.forEach((s=>{if(s.feature_flag_key){var o;n.oa&&(Me.aa("setting flag key ",s.feature_flag_key," to web experiment ",s),(o=n.oa)==null||o.set(s.feature_flag_key,s));var a=n._instance.getFeatureFlag(s.feature_flag_key);X(a)&&s.variants[a]&&n.la(s.name,a,s.variants[a].transforms)}else if(s.variants)for(var l in s.variants){var u=s.variants[l];Me.ua(u,n._instance)&&n.la(s.name,l,u.transforms)}}))}),i)},this._instance=e,this._instance.onFeatureFlags((i=>{this.onFeatureFlags(i)}))}initialize(){}onFeatureFlags(e){if(this._is_bot())Me.aa(yu);else if(!this.Ne.disable_web_experiments){if(H(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();Me.aa("applying feature flags",e),e.forEach((n=>{var i;if(this.oa&&(i=this.oa)!=null&&i.has(n)){var r,s=this._instance.getFeatureFlag(n),o=(r=this.oa)==null?void 0:r.get(n);s&&o!=null&&o.variants[s]&&this.la(o.name,s,o.variants[s].transforms)}}))}}previewWebExperiment(){var e=Me.getWindowLocation();if(e!=null&&e.search){var n=ii(e?.search,"__experiment_id"),i=ii(e?.search,"__experiment_variant");n&&i&&(Me.aa("previewing web experiments "+n+" && "+i),this.getWebExperiments((r=>{this.ha(parseInt(n),i,r)}),!1,!0))}}loadIfEnabled(){this.Ne.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,n,i){if(this.Ne.disable_web_experiments&&!i)return e([]);var r=this._instance.get_property("$web_experiments");if(r&&!n)return e(r);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this.Ne.token),method:"GET",timestampMode:"query",callback:s=>e(s.statusCode===200&&s.json&&s.json.experiments||[])})}ha(e,n,i){var r=i.filter((s=>s.id===e));r&&r.length>0&&(Me.aa("Previewing web experiment ["+r[0].name+"] with variant ["+n+"]"),this.la(r[0].name,n,r[0].variants[n].transforms))}static ua(e,n){return!H(e.conditions)&&Me.da(e,n)&&Me.va(e)}static da(e,n){var i;if(H(e.conditions)||H((i=e.conditions)==null?void 0:i.url))return!0;var r=Me.getWindowLocation();if(r){var s,o,a,l=of(n,r.href);return(s=e.conditions)==null||!s.url||zm[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return w?.location}static va(e){var n;if(H(e.conditions)||H((n=e.conditions)==null?void 0:n.utm))return!0;var i=bf();if(i.utm_source){var r,s,o,a,l,u,c,d,h=(r=e.conditions)==null||(r=r.utm)==null||!r.utm_campaign||((s=e.conditions)==null||(s=s.utm)==null?void 0:s.utm_campaign)==i.utm_campaign,f=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==i.utm_source,p=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==i.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==i.utm_term;return h&&p&&g&&f}return!1}static aa(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;n>r;r++)i[r-1]=arguments[r];A.info("[WebExperiments] "+e,i)}la(e,n,i){this._is_bot()?Me.aa(yu):n!=="control"?i.forEach((r=>{if(r.selector){var s;Me.aa("applying transform of variant "+n+" for experiment "+e+" ",r);var o=(s=document)==null?void 0:s.querySelectorAll(r.selector);o?.forEach((a=>{var l=a;r.html&&(l.innerHTML=r.html),r.css&&l.setAttribute("style",r.css)}))}})):Me.aa("Control variants leave the page unmodified.")}_is_bot(){return He&&this._instance?jf(He,this.Ne.custom_blocked_useragents):void 0}}var ot=pe("[Conversations]"),En="Conversations not available yet.",wu="console",Yf="__posthogHandledLogsRequestError",Do=(t,e)=>{var n=t instanceof Error?t:new Error(e);return n[Yf]=!0,n},bu=t=>!!t&&typeof t=="object"&&t[Yf]===!0,Cs={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=gu,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 Wm(t.config,t.Qi()),this.Ta=this.Ea)}updateConfig(t,e){var n;(n=this.Ea)==null||n.update(t,e)}setup(t){return this.Ia=t,this.rt=t.logger.createLogger("[FeatureFlags]"),n=()=>{this.Ia===t&&(this.Ia=void 0,this.nn=t,this.Pa(t))},(e=t.kv.initialize())!=null&&e.then?e.then(n):n();var e,n}Pa(t){if(this.nn===t)return w&&ve(w,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){w?.removeEventListener("online",this.Ca)}dispose(){var t;this.ba++,this.wa=!1,this.Ia=void 0,this.nn&&(this.La(),(t=this.Ra)==null||t.dispose(),this.Ra=void 0,this.ga=[],w?.removeEventListener("online",this.Ca),this.nn=void 0)}get Ne(){return this.Ta.get()}Oa(t){var e;return(e=this.nn)==null?void 0:e.kv.get(t)}F(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.set(t)}))}q(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.remove(t)}))}Da(t){try{t()}catch(e){this.rt.error("Failed to update feature flag persistence",e)}}Fa(){var t={};for(var e of[Ti,$i,Pr,It]){var n=this.Oa(e);C(n)||(t[e]=n)}this.fa=t;var i=I({},t),r=this.Oa(Sn);if(r)for(var s of Object.entries(r))i["$feature/"+s[0]]=s[1];this.pa=i}Aa(){var t=this.Ne.cacheTtlMs;if(!t||0>=t)return!1;var e=this.Oa(ji);return typeof e!="number"||Date.now()-e>t}$a(){return!!this.Aa()&&(this.xa||this.ya||(this.xa=!0,this.rt.warn("Feature flag cache is stale, triggering refresh..."),this.reloadFeatureFlags()),!0)}Na(){var t=this.Ne.evaluationContexts;return t!=null&&t.length?t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid evaluation context found:",e,"Expected non-empty string"),n})):[]}qa(){var t=this.Ne.flagKeys;if(!C(t))return t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid flag key found:",e,"Expected non-empty string"),n}))}initialize(){var t,e,n=this.Ne,i=(t=(e=n.bootstrap)==null?void 0:e.featureFlags)!==null&&t!==void 0?t:{};if(Object.keys(i).length){var r,s,o=(r=(s=n.bootstrap)==null?void 0:s.featureFlagPayloads)!==null&&r!==void 0?r:{},a=Object.keys(i).filter((u=>!!i[u])).reduce(((u,c)=>(u[c]=i[c]||!1,u)),{}),l=Object.keys(o).filter((u=>a[u])).reduce(((u,c)=>(o[c]&&(u[c]=o[c]),u)),{});return this.ja({featureFlags:a,featureFlagPayloads:l})}}updateFlags(t,e,n){var i,r,s=n!=null&&n.merge&&(i=this.Oa(Sn))!==null&&i!==void 0?i:{},o=n!=null&&n.merge&&(r=this.Oa($i))!==null&&r!==void 0?r:{},a=I({},s,t),l=I({},o,e),u={};for(var c of Object.entries(a)){var d=c[0],h=c[1];u[d]={key:d,enabled:hc(h),variant:pc(h),reason:void 0,metadata:C(l?.[d])?void 0:{id:0,version:void 0,description:void 0,payload:l[d]}}}this.ja({flags:u})}get hasLoadedFlags(){return this.ma}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var t=this.Oa(aa),e=this.Oa(It),n=this.Oa(xn);if(!n&&!e)return t||{};var i=fe({},t||{}),r=[...new Set([...Object.keys(n||{}),...Object.keys(e||{})])];for(var s of r){var o,a,l=i[s],u=e?.[s],c=C(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=C(u)?l?.variant:typeof u=="string"?u:void 0,h=n?.[s],f=I({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(f.original_enabled=l?.enabled),d!==l?.variant&&(f.original_variant=l?.variant),h&&(f.metadata=I({},l?.metadata,{payload:h,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),i[s]=f}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:n,finalDetails:i}),this.ca=!0),i}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((n=>{var i=t[n];return{key:n,enabled:hc(i),variant:pc(i),payload:fc(e[n])}}))}getFlagVariants(){var t=this.Oa(Sn),e=this.Oa(It);if(!e)return t||{};for(var n=fe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:e,finalFlags:n}),this.ca=!0),n}getFlagPayloads(){var t=this.Oa($i),e=this.Oa(xn);if(!e)return t||{};for(var n=fe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flag payloads!",{flagPayloads:t,overriddenPayloads:e,finalPayloads:n}),this.ca=!0),n}reloadFeatureFlags(){this._a||this.Ne.featureFlagsDisabled||this.Ma()||this.Ba||(this.ga.slice().forEach((t=>{try{t()}catch(e){this.rt.error("Error while running feature flags reloading callback",e)}})),this.Ba=setTimeout((()=>{this.Ha()}),5))}La(){clearTimeout(this.Ba),this.Ba=void 0}onReloading(t){return this.ga.push(t),()=>{this.ga=this.ga.filter((e=>e!==t))}}ensureFlagsLoaded(){this.ma||this.ya||this.Ba||this.reloadFeatureFlags()}setAnonymousDistinctId(t){this.$anon_distinct_id=t}setReloadingPaused(t){this._a=t}resetFlagCallReported(){this.q(Cn)}Ha(t){this.La();var e=this.nn;if(e&&!this.Ne.remoteRequestsDisabled&&!this.Ma())if(this.ya)this.wa=!0;else{var n={token:e.projectToken,distinct_id:e.distinctId,groups:e.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:I({},e.initialPersonProperties,this.Oa(jt)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(In),timezone:Cf()};C(e.deviceId)||(n.$device_id=e.deviceId),(t!=null&&t.disableFlags||this.Ne.featureFlagsDisabled)&&(n.disable_flags=!0);var i=this.Na();i.length&&(n.evaluation_contexts=i);var r=this.qa();C(r)||(n.flag_keys=r);var s=this.Ne.onlyEvaluateSurveyFeatureFlags,o="/flags/?v=2"+(s?"&only_evaluate_survey_feature_flags=true":""),a=this.ba;this.ya=!0;var l=()=>{this.wa&&(this.wa=!1,this.Ha())},u=c=>{this.ya=!1,a===this.ba&&(this.F({[Tr]:[mu]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:n,compression:this.Ne.compression==="base64"?Ue.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,h,f=(d=c.json)!==null&&d!==void 0?d:{},p=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),p||this.wa||(this.$anon_distinct_id=void 0),!n.disable_flags||this.wa){this.ka=!p;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?mu:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),f.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((h=f.quotaLimited)==null||!h.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[Tr]:g}),m?this.rt.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more."):n.disable_flags||this.ja(f,p,{partialResponse:s}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return yf(this.Sa,3)}Ua(t){this.Sa=wf(t,this.Sa,3,(()=>this.rt.warn("Feature flag requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped refreshing feature flags; will try again when connectivity changes.")))}getFeatureFlag(t,e){var n;if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var i=this.getFeatureFlagResult(t,e);return(n=i?.variant)!==null&&n!==void 0?n:i?.enabled}}else this.rt.warn('getFeatureFlag for key "'+t+Bo)}getFeatureFlagDetails(t){return this.getFlagsWithDetails()[t]}getFeatureFlagPayload(t){var e=this.getFeatureFlagResult(t,{send_event:!1});return e?.payload}getFeatureFlagResult(t,e){if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var n,i=this.getFlagVariants(),r=t in i,s=i[t],o=this.getFlagPayloads()[t],a=String(s),l=this.Oa(Pr)||void 0,u=this.Oa(ji)||void 0,c=this.Oa(Cn)||{};if(this.Ne.deduplicateCallsPerSession){var d,h=(d=this.nn)==null?void 0:d.session.sessionId,f=this.Oa(Li);h&&h!==f&&(c={},n=h)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))n&&this.F({[Cn]:c,[Li]:n});else{var p,g,m,v,E,S,_,b,k,T;U(c[t])?c[t].push(a):c[t]=[a],this.F(I({[Cn]:c},n?{[Li]:n}:{}));var x=this.getFeatureFlagDetails(t),F=[...(p=this.Oa(Tr))!==null&&p!==void 0?p:[]];C(s)&&F.push("flag_missing");var $={$feature_flag:t,$feature_flag_response:s,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((g=this.Ne.bootstrap)==null||(g=g.featureFlags)==null?void 0:g[t])||null,$feature_flag_bootstrapped_payload:((m=this.Ne.bootstrap)==null||(m=m.featureFlagPayloads)==null?void 0:m[t])||null,$used_bootstrap_value:!this.ka};C(x==null||(v=x.metadata)==null?void 0:v.has_experiment)||($.$feature_flag_has_experiment=x.metadata.has_experiment),C(x==null||(E=x.metadata)==null?void 0:E.version)||($.$feature_flag_version=x.metadata.version);var O,L=(S=x==null||(_=x.reason)==null?void 0:_.description)!==null&&S!==void 0?S:x==null||(b=x.reason)==null?void 0:b.code;L&&($.$feature_flag_reason=L),x!=null&&(k=x.metadata)!=null&&k.id&&($.$feature_flag_id=x.metadata.id),C(x?.original_variant)&&C(x?.original_enabled)||($.$feature_flag_original_response=C(x.original_variant)?x.original_enabled:x.original_variant),x!=null&&(T=x.metadata)!=null&&T.original_payload&&($.$feature_flag_original_payload=x==null||(O=x.metadata)==null?void 0:O.original_payload),F.length&&($.$feature_flag_error=F.join(",")),this.za($)}else n&&this.F({[Cn]:c,[Li]:n});if(r)return{key:t,enabled:!!s,variant:typeof s=="string"?s:void 0,payload:fc(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+Bo)}za(t){try{var e;(e=this.nn)==null||e.capture("$feature_flag_called",t).catch((n=>{this.rt.error("Failed to capture feature flag call",n)}))}catch(n){this.rt.error("Failed to capture feature flag call",n)}}getRemoteConfigPayload(t,e){this.Wa(t,e)}Wa(t,e){var n=this;return se((function*(){var i=n.nn;if(i){var r={distinct_id:i.distinctId,token:i.projectToken,person_properties:{$lib:i.library.name,$lib_version:i.library.version}},s=n.Na();s.length&&(r.evaluation_contexts=s);var o,a=n.qa();C(a)||(r.flag_keys=a);try{var l,u=(l=(yield i.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:r,compression:n.Ne.compression==="base64"?Ue.Base64:void 0,sentAt:"body",timeoutMs:n.Ne.requestTimeoutMs})).json)==null?void 0:l.featureFlagPayloads;o=u?.[t]||void 0}catch(c){return void n.rt.error("Remote config feature flag request failed",c)}try{e(o)}catch(c){n.rt.error("Remote config feature flag callback failed",c)}}}))()}isFeatureEnabled(t,e){if(e===void 0&&(e={}),e.fresh&&!this.ka)return e.defaultValue;if(!(this.ma||this.getFlags()&&this.getFlags().length>0))return this.rt.warn('isFeatureEnabled for key "'+t+Bo),e.defaultValue;var n=this.getFeatureFlag(t,e);return C(n)?e.defaultValue:!!n}addFeatureFlagsHandler(t){this.featureFlagEventHandlers.push(t)}removeFeatureFlagsHandler(t){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((e=>e!==t))}receivedFeatureFlags(t,e,n){this.ja(t,e,n)}ja(t,e,n){if(this.nn){this.ma=!0;var i=(function(r,s,o,a,l,u){s===void 0&&(s={}),o===void 0&&(o={}),a===void 0&&(a={}),u===void 0&&(u=gu);var c=((k,T)=>{var x=k.flags;return x?I({},k,{featureFlags:Object.fromEntries(Object.keys(x).map((F=>{var $;return[F,($=x[F].variant)!==null&&$!==void 0?$:x[F].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(x).filter((F=>x[F].enabled)).filter((F=>{var $;return($=x[F].metadata)==null?void 0:$.payload})).map((F=>{var $;return[F,($=x[F].metadata)==null?void 0:$.payload]})))}):(k.featureFlags&&T.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),k)})(r,u),d=c.flags,h=c.featureFlags,f=c.featureFlagPayloads;if(h){var p=r.requestId,g=r.evaluatedAt;if(U(h)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(h)for(var v=0;h.length>v;v++)m[h[v]]=!0;return{[Ti]:h,[Sn]:m,[Zr]:!1}}var E=h,S=f,_=d;if(l!=null&&l.partialResponse)E=I({},s,E),S=I({},o,S),_=I({},a,_);else if(r.errorsWhileComputingFlags)if(d){var b=new Set(Object.keys(d).filter((k=>{var T;return!((T=d[k])!=null&&T.failed)})));E=I({},s,Object.fromEntries(Object.entries(E).filter((k=>b.has(k[0]))))),S=I({},o,Object.fromEntries(Object.entries(S||{}).filter((k=>b.has(k[0]))))),_=I({},a,Object.fromEntries(Object.entries(_||{}).filter((k=>b.has(k[0])))))}else E=I({},s,E),S=I({},o,S),_=I({},a,_);return I({[Ti]:Object.keys(_u(E)),[Sn]:E||{},[$i]:S||{},[aa]:_||{},[Zr]:r.minimalFlagCalledEvents===!0},p?{[Pr]:p}:{},g?{[ji]:g}:{})}})(t,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),n,this.rt);i&&this.F(i),e||(this.xa=!1),this.Va(e)}}override(t,e){e===void 0&&(e=!1),this.rt.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:t,suppressWarning:e})}overrideFeatureFlags(t){this.Za(t)}Za(t){if(this.nn){if(t===!1)return this.q([It,xn]),this.Va(),void bn.info("All overrides cleared");if(U(t))return this.F({[It]:vu(t)}),this.Va(),void bn.info("Flag overrides set",{flags:t});if(t&&typeof t=="object"&&("flags"in t||"payloads"in t)){var e,n=t;this.ca=!!((e=n.suppressWarning)!==null&&e!==void 0&&e);var i={},r=n.flags,s=n.payloads;return r&&(i[It]=U(r)?vu(r):r),s&&(i[xn]=s),Object.keys(i).length&&this.F(i),r===!1&&s===!1?this.q([It,xn]):r===!1?this.q(It):s===!1&&this.q(xn),this.Va(),r===!1?bn.info("Flag overrides cleared"):r&&bn.info("Flag overrides set",{flags:r}),void(s===!1?bn.info("Payload overrides cleared"):s&&bn.info("Payload overrides set",{payloads:s}))}if(t&&typeof t=="object")return this.F({[It]:t}),this.Va(),void bn.info("Flag overrides set",{flags:t});this.rt.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:t})}else this.rt.warn("posthog.featureFlags.overrideFeatureFlags called before feature flags were ready")}onFeatureFlags(t){if(this.addFeatureFlagsHandler(t),this.ma){var e=this.Ga(),n=e.flags,i=e.flagVariants;try{t(n,i)}catch(r){this.rt.error("Error while running feature flags callback",r)}}return()=>this.removeFeatureFlagsHandler(t)}updateEarlyAccessFeatureEnrollment(t,e,n){var i=(this.Oa(Ar)||[]).find((l=>l.flagKey===t)),r={["$feature_enrollment/"+t]:e},s={$feature_flag:t,$feature_enrollment:e,$set:r};i&&(s.$early_access_feature_name=i.name),n&&(s.$feature_enrollment_stage=n);var o=I({},this.getFlagVariants(),{[t]:e});this.F({[Ti]:Object.keys(_u(o)),[Sn]:o,[jt]:I({},this.Oa(jt)||{},r)}),this.Va();try{var a;(a=this.nn)==null||a.capture("$feature_enrollment_update",s).catch((l=>{this.rt.error("Failed to capture early access feature enrollment",l)}))}catch(l){this.rt.error("Failed to capture early access feature enrollment",l)}}getEarlyAccessFeatures(t,e,n){e===void 0&&(e=!1);var i=this.Oa(Ar);!i||e?this.Qa(t,n):t(i)}Qa(t,e){var n=this;return se((function*(){var i=n.nn;if(i){var r,s=e?"&"+e.map((a=>"stage="+a)).join("&"):"";try{var o=yield i.sendRequest("/api/early_access_features/?token="+i.projectToken+s,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;n.F({[Ar]:r=o.json.earlyAccessFeatures})}catch(a){return void n.rt.error("Early access feature request failed",a)}try{t(r)}catch(a){n.rt.error("Early access feature callback failed",a)}}}))()}Ga(){var t=this.getFlags(),e=this.getFlagVariants();return{flags:t.filter((n=>e[n])),flagVariants:Object.keys(e).filter((n=>e[n])).reduce(((n,i)=>(n[i]=e[i],n)),{})}}Va(t){this.Fa();var e=this.Ga(),n=e.flags,i=e.flagVariants;this.featureFlagEventHandlers.forEach((r=>{try{r(n,i,{errorsLoading:t})}catch(s){this.rt.error("Error while running feature flags callback",s)}}))}setPersonPropertiesForFlags(t,e){e===void 0&&(e=!0),this.Ka(t,e)}Ka(t,e){e===void 0&&(e=!0);var n=this.Oa(jt)||{},i=t?.$set||(t!=null&&t.$set_once?{}:t),r=t?.$set_once,s={};if(r)for(var o in r)({}).hasOwnProperty.call(r,o)&&(o in n||(s[o]=r[o]));this.F({[jt]:I({},n,s,i)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=I({},this.Oa(jt)||{});t.forEach((i=>{delete n[i]})),this.F({[jt]:n}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(jt),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=this.Oa(In)||{},i=I({},n);for(var r of Object.keys(t))i[r]=I({},n[r],t[r]);this.F({[In]:i}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(In)||{};this.F({[In]:I({},e,{[t]:{}})})}else this.q(In)}reset(){this.ba++,this.wa=!1,this.Fa(),this.ma=!1,this._a=!1,this.ka=!1,this.$anon_distinct_id=void 0,this.La(),this.ca=!1,this.Sa=0}}},qm={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===ki||this.Ya===Sr?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=lu,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(P==null||!P.visibilityState||P.visibilityState==="visible")return!0;var n=w==null||(e=w.performance)==null||e.getEntriesByType==null?void 0:e.getEntriesByType("visibility-state");return!(n!=null&&n.length)||n.some((i=>i.name==="visible"))})(),this.Ie=()=>{var e;P?.visibilityState==="visible"&&(this.io=!0,(e=this.Ja)==null||e.setDocumentWasEverVisible==null||e.setDocumentWasEverVisible(!0))},this._instance=t,!this._instance.sessionManager)throw Bt.error("started without valid sessionManager"),new Error(Ia+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===Wt)throw new Error(Ia+' cannot be used with cookieless_mode="always"');P!=null&&P.addEventListener&&ve(P,"visibilitychange",this.Ie)}initialize(){this.startIfEnabledOrStop()}dispose(){this.eo=!0,P==null||P.removeEventListener==null||P.removeEventListener("visibilitychange",this.Ie),this.stopRecording()}get ro(){var t,e=!((t=this._instance.get_property(An))==null||!t.enabled),n=!this.Ne.disable_session_recording,i=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return w&&e&&n&&!i}startIfEnabledOrStop(t){var e;if(!(this.eo||this.ro&&(e=this.Ja)!=null&&e.isStarted)){var n=!C(Object.assign)&&!C(Array.from);this.ro&&n?(this.no(t),Bt.info("starting")):(this.Ya=lu,this.stopRecording())}}no(t){var e,n,i;this.ro&&(this.Ya!==ki&&this.Ya!==Sr&&(this.Ya=cu),B!=null&&(e=B.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(n=B.__PosthogExtensions__)!=null&&n.initSessionRecording?this.so(t):(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,this.ao,(r=>{if(r)return Bt.error("could not load recorder",r);this.so(t)})))}stopRecording(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.stop()}oo(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.discard()}lo(){var t,e;(t=this.Mr)==null||t.unregister(ol),(e=this.Mr)==null||e.unregister(Kd)}uo(t,e){if(H(t))return null;var n,i=ke(t)?t:parseFloat(t);return typeof(n=i)!="number"||!Number.isFinite(n)||0>n||n>1?(Bt.warn(e+" must be between 0 and 1. Ignoring invalid value:",t),null):i}ho(t){if(this.Mr){var e,n,i=this.Mr,r=()=>{var s,o=t.sessionRecording===!1?void 0:t.sessionRecording,a=this.uo((s=this.Ne.session_recording)==null?void 0:s.sampleRate,"session_recording.sampleRate"),l=this.uo(o?.sampleRate,"remote config sampleRate"),u=a??l;H(u)&&this.lo();var c=o?.minimumDurationMilliseconds;i.register({[An]:I({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:I({capturePerformance:t.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:u,minimumDurationMilliseconds:C(c)?null:c,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers,version:o?.version,triggerGroups:o?.triggerGroups})})};r(),(e=this.Xa)==null||e.call(this),this.Xa=(n=this._instance.sessionManager)==null?void 0:n.onSessionId(r)}}onRemoteConfig(t){var e=t.ok?t.config:void 0;return e&&"sessionRecording"in e?e.sessionRecording===!1?(this.ho(e),void this.oo()):(this.ho(e),void this.startIfEnabledOrStop()):(this.Ya===ki&&(this.Ya=Sr,Bt.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(t,e){var n;e===void 0&&(e="log"),(n=this.Ja)!=null&&n.log?this.Ja.log(t,e):Bt.warn("log called before recorder was ready")}get ao(){var t,e,n=(t=this._instance)==null||(t=t.persistence)==null?void 0:t.get_property(An);return(n==null||(e=n.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(An);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(n){return Bt.warn("persisted remote config for session recording is invalid and will be ignored",n),!1}return!H(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,n,i;if(!this.eo){if((e=B.__PosthogExtensions__)==null||!e.initSessionRecording)return Bt.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[nf]:!0});var r;if(this.Ja||(this.Ja=(r=B.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===Sr||this.Ya===ki?void 0:(this.Ya=ki,Bt.info("persisted remote config is stale, requesting fresh config before starting"),void new Af(this._instance).load());this.Ya=cu,(n=(i=this.Ja).setDocumentWasEverVisible)==null||n.call(i,this.io),this.Ja.start(t)}}onRRwebEmit(t){var e;(e=this.Ja)==null||e.onRRwebEmit==null||e.onRRwebEmit(t)}overrideLinkedFlag(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Jd]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Yd]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,n;this.Ja||(n=this.Mr)==null||n.register({[t==="url"?Zd:Xd]:!0}),(e=this.Ja)==null||e.overrideTrigger(t)}get sdkDebugProperties(){var t;return((t=this.Ja)==null?void 0:t.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(t,e){var n;return!((n=this.Ja)==null||!n.tryAddCustomEvent(t,e))}}},Vm={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new su(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,n=he(this.instance.config.autocapture)?this.instance.config.autocapture:{};return n.url_allowlist=(t=n.url_allowlist)==null?void 0:t.map((i=>new RegExp(i))),n.url_ignorelist=(e=n.url_ignorelist)==null?void 0:e.map((i=>new RegExp(i))),n}yo(){if(this.isBrowserSupported()){if(w&&P){var t=n=>{n=n||w?.event;try{this.bo(n)}catch(i){Mo.error("Failed to capture event",i)}};if(ve(P,"submit",t,{capture:!0}),ve(P,"change",t,{capture:!0}),ve(P,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=n=>{n=n||w?.event;try{this.bo(n,$o)}catch(i){Mo.error("Failed to capture copy/cut event",i)}};ve(P,"copy",e,{capture:!0}),ve(P,"cut",e,{capture:!0})}}}else Mo.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.vo&&(this.yo(),this.vo=!0)}onRemoteConfig(t){if(this.fo=!0,t.ok){var e=t.config;e.elementsChainAsString&&(this.po=e.elementsChainAsString);var n=e.autocapture_opt_out;mt(n)&&(this.instance.persistence&&this.instance.persistence.register({[ea]:n}),this.co=n),this.startIfEnabled()}else this.startIfEnabled()}setElementSelectors(t){this.mo=t}getElementSelectors(t){var e,n=[];return(e=this.mo)==null||e.forEach((i=>{var r=P?.querySelectorAll(i);r?.forEach((s=>{t===s&&n.push(i)}))})),n}get isEnabled(){var t,e,n=(t=this.instance.persistence)==null?void 0:t.props[ea],i=this.co,r=this.instance.Qi()&&!this.fo;if(Ye(i)&&!mt(n)&&!r)return!1;var s=(e=this.co)!==null&&e!==void 0?e:!!n;return!!this.instance.config.autocapture&&!s}bo(t,e){if(e===void 0&&(e="$autocapture"),this.isEnabled){var n,i=bo(t);lf(i)&&(i=i.parentNode||null),e==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&this.instance.config.rageclick&&(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,t.timeStamp||new Date().getTime())&&Lc(i,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var r=e===$o;if(i&&(function(d,h,f,p,g,m){var v;if(!w||dl(d)||f!=null&&f.url_allowlist&&!Tc(f.url_allowlist,m)||f!=null&&f.url_ignorelist&&Tc(f.url_ignorelist,m))return!1;if(f!=null&&f.dom_event_allowlist){var E=f.dom_event_allowlist;if(E&&!E.some((x=>h.type===x)))return!1}var S=pf(d,p),_=S.parentIsUsefulElement,b=S.targetElementList;if(!(function(x,F){var $=F?.element_allowlist;if(C($))return!0;var O,L=function(K){if($.some((V=>K.tagName.toLowerCase()===V)))return{v:!0}};for(var N of x)if(O=L(N))return O.v;return!1})(b,f)||!ma(b,f?.css_selector_allowlist)||ma(b,(v=f?.css_selector_ignorelist)!==null&&v!==void 0?v:Wg))return!1;try{var k=w.getComputedStyle(d);if(k&&k.getPropertyValue("cursor")==="pointer"&&h.type==="click")return!0}catch{}var T=d.tagName.toLowerCase();switch(T){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 _?(g||["click"]).indexOf(h.type)>=0:(g||["click"]).indexOf(h.type)>=0&&(ul.indexOf(T)>-1||d.getAttribute("contenteditable")==="true")}})(i,t,this.Ne,r,r?["copy","cut"]:void 0,this.instance)){var s=Lm(i,{e:t,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.Ne.element_attribute_ignorelist,elementsChainAsString:this.po,disableCaptureUrlHashes:this.instance.config.disable_capture_url_hashes}),o=s.props;if(s.explicitNoCapture)return!1;var a=this.getElementSelectors(i);if(a&&a.length>0&&(o.$element_selectors=a),e===$o){var l,u=df(w==null||(l=w.getSelection())==null?void 0:l.toString()),c=t.type||"clipboard";if(!u)return!1;o.$selected_content=u,o.$copy_type=c}return this.instance.capture(e,o),!0}}}isBrowserSupported(){return je(P?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(w==null||(e=w.location)==null?void 0:e.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(A.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.wo&&this.wo(),this.wo=void 0,A.info("History API monitoring stopped")}monitorHistoryChanges(){w&&w.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(w&&((e=w.history[t])==null||!e.__posthog_wrapped__)){var n=this;(function(i,r,s){try{if(!(r in i))return ou;var o={next:i[r]},a=s((function(){for(var l=arguments.length,u=new Array(l),c=0;l>c;c++)u[c]=arguments[c];return o.next.apply(this,u)}));return je(a)&&(a.prototype=a.prototype||{},Object.defineProperties(a,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:o}})),i[r]=a,()=>{if(i[r]!==a)for(var l=i[r];je(l)&&l.__posthog_layer__;){var u=l.__posthog_layer__;if(u.next===a)return void(u.next=o.next);l=u.next}else i[r]=o.next}}catch{return ou}})(w.history,t,(i=>function(r,s,o){i.call(this,r,s,o),n.So(t)}))}}So(t){try{var e,n=w==null||(e=w.location)==null?void 0:e.pathname;if(!n)return;n!==this._o&&this.isEnabled&&this._instance.capture(Vn,{navigation_type:t}),this._o=n}catch(i){A.error("Error capturing "+t+" pageview",i)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};ve(w,"popstate",t),this.wo=()=>{w&&w.removeEventListener("popstate",t)}}}},heatmaps:class{get Ne(){return this.instance.config}constructor(t){var e;this.Co=!1,this.vo=!1,this.Mo=null,this.instance=t,this.Co=!((e=this.instance.persistence)==null||!e.props[ta]),this.rageclicks=new su(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return he(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return H(this.Ne.capture_heatmaps)?H(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;Om.info("starting..."),this.To(),this.Ie()}else{var t;clearInterval((t=this.Mo)!==null&&t!==void 0?t:void 0),this.Eo(),this.getAndClearBuffer()}}onRemoteConfig(t){if(t.ok){var e=t.config;if("heatmaps"in e){var n=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[ta]:n}),this.Co=n,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){No(t.originalEvent)&&this.ke(t.originalEvent,"deadclick")}Ie(){this.Mo&&clearInterval(this.Mo),this.Mo=P?.visibilityState==="visible"?setInterval(this.cr.bind(this),this.flushIntervalMilliseconds):null}To(){w&&P&&(this.Po=this.cr.bind(this),ve(w,ns,this.Po),this.Ro=t=>this.ke(t||w?.event),ve(P,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||w?.event),ve(P,"mousemove",this.Ao,{capture:!0}),this.Lo=new Hc(this.instance,Jg,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),ve(P,ts,this.Oo),this.vo=!0)}Eo(){var t;w&&P&&(this.Po&&w.removeEventListener(ns,this.Po),this.Ro&&P.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&P.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&P.removeEventListener(ts,this.Oo),clearTimeout(this.Do),(t=this.Lo)==null||t.stop(),this.vo=!1)}$o(t,e){var n=this.instance.scrollManager.scrollY(),i=this.instance.scrollManager.scrollX(),r=this.instance.scrollManager.scrollElement(),s=(function(o,a,l){for(var u=o;u&&hn(u)&&!et(u,"body");){if(u===l)return!1;var c=void 0;try{var d,h,f;c=(d=(h=(f=u.ownerDocument)==null?void 0:f.defaultView)!==null&&h!==void 0?h:w)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(j(a,c))return!0;u=ff(u)}return!1})(bo(t),["fixed","sticky"],r);return{x:t.clientX+(s?0:i),y:t.clientY+(s?0:n),target_fixed:s,type:e}}ke(t,e){var n;if(e===void 0&&(e="click"),!Rc(t.target)&&No(t)){var i=this.$o(t,e);(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,new Date().getTime())&&Lc(bo(t),this.instance.config.rageclick)&&this.Vt(I({},i,{type:"rageclick"})),this.Vt(i)}}Fo(t){!Rc(t.target)&&No(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(w){var e=this.Ne.disable_capture_url_hashes?fn(w.location.href):w.location.href,n=this.Ne.custom_personal_data_properties,i=this.Ne.mask_personal_data_properties?[...ri,...n||[]]:[],r=Zi(e,i,Xi);this.R=this.R||{},this.R[r]||(this.R[r]=[]),this.R[r].push(t)}}cr(){this.R&&!Kt(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:Hc,webVitalsAutocapture:class{constructor(t){var e;this.Co=!1,this.vo=!1,this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this.No=()=>{clearTimeout(this.qo),this.qo=void 0,this.R.metrics.length!==0&&(this._instance.capture("$web_vitals",I({$current_url:this.R.url},this.R.metrics.reduce(((n,i)=>I({},n,{["$web_vitals_"+i.name+"_event"]:I({},i),["$web_vitals_"+i.name+"_value"]:i.value})),{}))),this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.jo=n=>{var i;if(this.R=this.R||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},H(n?.name)||H(n?.value))wn.error("Invalid metric received",n);else{var r=typeof n.navigationURL=="string"?n.navigationURL:void 0,s=this.Bo(r);if(!C(s)){var o=ke(n.navigationId)||typeof n.navigationId=="string"?"navigation:"+n.navigationId:"url:"+s;if(!this.Ho||this.Ho>n.value){this.R.navigationKey!==o&&(this.No(),this.qo=setTimeout(this.No,this.flushToCaptureTimeoutMs)),C(this.R.navigationKey)&&(this.R.navigationKey=o,this.R.url=s),this.R.firstMetricTimestamp=C(this.R.firstMetricTimestamp)?Date.now():this.R.firstMetricTimestamp,n.attribution&&n.attribution.interactionTargetElement&&(n.attribution.interactionTargetElement=void 0);var a=(i=this._instance.sessionManager)==null?void 0:i.checkAndGetSessionAndWindowId(!0),l=I({},n,r?{navigationURL:s}:{},{$current_url:s,timestamp:Date.now()});C(a)||(l.$session_id=a.sessionId,l.$window_id=a.windowId),this.R.metrics.push(l),this.R.metrics.length===this.allowedMetrics.length&&this.No()}else wn.error("Ignoring metric with value >= "+this.Ho,n)}}},this.Uo=()=>{if(!this.vo){var n,i,r,s,o=B.__PosthogExtensions__,a=o?.postHogWebVitalsCallbacksByFlavor,l=a?.[this.zo]||(this.zo==="web-vitals"&&C(a)?o?.postHogWebVitalsCallbacks:void 0);if(C(l)||(n=l.onLCP,i=l.onCLS,r=l.onFCP,s=l.onINP),n&&i&&r&&s){var u={reportSoftNavs:this.useSoftNavs};this.allowedMetrics.indexOf("LCP")>-1&&n(this.jo.bind(this),u),this.allowedMetrics.indexOf("CLS")>-1&&i(this.jo.bind(this),u),this.allowedMetrics.indexOf("FCP")>-1&&r(this.jo.bind(this),u),this.allowedMetrics.indexOf("INP")>-1&&s(this.jo.bind(this),u),this.vo=!0}else wn.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[sa]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,n=he(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return H(n)?((e=this._instance.persistence)==null?void 0:e.props[oa])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(he(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=he(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=he(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=he(this.Wo)&&ke(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:au;return t>0&&6e4>=t?au:t}get isEnabled(){var t=me?.protocol;if(t!=="http:"&&t!=="https:")return wn.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=he(this.Wo)?this.Wo.web_vitals:mt(this.Wo)?this.Wo:void 0;return mt(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(wn.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var n=he(e.capturePerformance)&&!!e.capturePerformance.web_vitals,i=he(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[sa]:n}),this._instance.persistence.register({[oa]:i})),this.Co=n,this.startIfEnabled()}}}get zo(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}ai(t){var e=B.__PosthogExtensions__,n=this.zo,i=e?.postHogWebVitalsCallbacksByFlavor;i!=null&&i[n]||n==="web-vitals"&&C(i)&&e!=null&&e.postHogWebVitalsCallbacks?t():e==null||e.loadExternalDependency==null||e.loadExternalDependency(this._instance,n,(r=>{r?wn.error("failed to load script",r):t()}))}Bo(t){var e=t||w?.location.href;if(e){var n=this._instance.config.disable_capture_url_hashes?fn(e):e,i=this._instance.config.custom_personal_data_properties,r=this._instance.config.mask_personal_data_properties?[...ri,...i||[]]:[];return Zi(n,r,Xi)}wn.error("Could not determine current URL")}}},Gm={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var n;if(w&&this.isEnabled&&(n=B.__PosthogExtensions__)!=null&&n.errorWrappingFunctions){var i=B.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,r=B.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,s=B.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.Vo&&this.Ne.capture_unhandled_errors&&(this.Vo=i(this.captureException.bind(this))),!this.Zo&&this.Ne.capture_unhandled_rejections&&(this.Zo=r(this.captureException.bind(this))),!this.Go&&this.Ne.capture_console_errors&&(this.Go=s(this.captureException.bind(this)))}catch(o){Ii.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[na]),this.Jo=new qp(I({},(function(n){var i,r,s,o;return n===void 0&&(n={}),{refillRate:(i=(r=n.exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:n.__exceptionRateLimiterRefillRate)!==null&&i!==void 0?i:1,bucketSize:(s=(o=n.exceptionRateLimiterBucketSize)!==null&&o!==void 0?o:n.__exceptionRateLimiterBucketSize)!==null&&s!==void 0?s:10}})(this._instance.config.error_tracking),{refillInterval:1e4,rt:Ii})),this.Ne=this.Yo(),this.startIfEnabledOrStop()}Yo(){var t=this._instance.config.capture_exceptions,e={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return he(t)?e=I({},e,t):(C(t)?this.Ko:t)&&(e=I({},e,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),e}get isEnabled(){return this.Ne.capture_console_errors||this.Ne.capture_unhandled_errors||this.Ne.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(Ii.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",(i=>{if(i)return Ii.error("failed to load script",i);t()}))}Qo(){var t,e,n;(t=this.Vo)==null||t.call(this),this.Vo=void 0,(e=this.Zo)==null||e.call(this),this.Zo=void 0,(n=this.Go)==null||n.call(this),this.Go=void 0}onRemoteConfig(t){if(t.ok){var e=t.config;"autocaptureExceptions"in e&&(this.Ko=!!e.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[na]:this.Ko}),this.Ne=this.Yo(),this.startIfEnabledOrStop())}}onConfigChange(){this.Ne=this.Yo()}captureException(t){var e,n,i,r=(e=t==null||(n=t.$exception_list)==null||(n=n[0])==null?void 0:n.type)!==null&&e!==void 0?e:"Exception";this.Jo.consumeRateLimit(r)?Ii.info("Skipping exception capture because of client rate limiting.",{exception:r}):(i=this._instance.exceptions)==null||i.sendExceptionEvent(t)}},exceptions:class{constructor(t){var e,n;this.Xo=[],this.tl=new lg([new mg,new Ig,new _g,new vg,new Sg,new Eg,new wg,new xg],(function(i){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;r>o;o++)s[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` +`),d=l;c.length>d;d++){var h=c[d];if(1024>=h.length){var f=Cc.test(h)?h.replace(Cc,"$1"):h;if(!f.match(/\S*Error: /)){for(var p of s){var g=p(f,i);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var v=Array.from(m);return v.reverse(),v.slice(0,50).map((E=>{return I({},E,{filename:E.filename||(S=v,S[S.length-1]||{}).filename,function:E.function||ni});var S}))})(u)}})("web:javascript",fg,gg)),this._instance=t,this.Xo=(e=(n=this._instance.persistence)==null?void 0:n.get_property(ia))!==null&&e!==void 0?e:[],this.el=Jr(this.il()),this.rl=new Cg(this.el)}onConfigChange(){this.el=Jr(this.il()),this.rl.setConfig(this.el)}onRemoteConfig(t){var e,n,i;if(t.ok){var r=t.config;if("errorTracking"in r){var s=(e=(n=r.errorTracking)==null?void 0:n.suppressionRules)!==null&&e!==void 0?e:[],o=(i=r.errorTracking)==null?void 0:i.captureExtensionExceptions;this.Xo=s,this._instance.persistence&&this._instance.persistence.register({[ia]:this.Xo,[ra]:o})}}}get nl(){var t,e=!!this._instance.get_property(ra),n=this._instance.config.error_tracking.captureExtensionExceptions;return(t=n??e)!==null&&t!==void 0&&t}buildProperties(t,e){return this.tl.buildFromUnknown(t,{syntheticException:e?.syntheticException,mechanism:{handled:e?.handled}})}addExceptionStep(t,e){if(this.el.enabled)try{if(!X(t)||t.trim().length===0)return void St.warn("Ignoring exception step because message must be a non-empty string");var n=(function(s){if(!s)return{sanitizedProperties:{},droppedKeys:[]};var o=[];return{sanitizedProperties:Object.keys(s).reduce(((a,l)=>kg.has(l)?(o.push(l),a):(a[l]=s[l],a)),{}),droppedKeys:o}})(this.sl(e)),i=n.sanitizedProperties,r=n.droppedKeys;r.length>0&&St.warn("Ignoring reserved exception step fields",{droppedKeys:r}),this.rl.add(I({[Kr]:t,[Yr]:new Date().toISOString()},i))}catch(s){St.error("Failed to add exception step. Ignoring breadcrumb.",s)}}sendExceptionEvent(t){try{var e=t.$exception_list;if(this.al(e)){if(this.ol(e))return this.ll("Exception dropped: matched a suppression rule"),void St.info("Skipping exception capture because a suppression rule matched");if(!this.nl&&this.ul(e))return this.ll("Exception dropped: thrown by a browser extension"),void St.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.hl(e))return this.ll("Exception dropped: thrown by the PostHog SDK"),void St.info("Skipping exception capture because it was thrown by the PostHog SDK")}var n=this.el.enabled&&H(t.$exception_steps)?this.dl(t):t,i=typeof(s=globalThis._posthogReleaseId)=="string"&&s.length>0?s:void 0;i&&(n.$release_id=i);try{var r=this._instance.capture("$exception",n,{_noTruncate:!0,_batchKey:"exceptionEvent",Wn:!0});return r&&this.rl.clear(),r}catch(o){return St.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void St.error("Failed to process exception event. Ignoring this exception.",o)}var s}dl(t){try{var e=this.rl.getAttachable();return e.length===0?t:I({},t,{$exception_steps:e})}catch(n){return St.error("Failed to read buffered exception steps. Capturing exception without steps.",n),t}}ll(t){this.el.enabled&&this.rl.add({[Kr]:t,[Yr]:new Date().toISOString()})}sl(t){return he(t)?I({},t):{}}il(){var t,e;return(t=(e=this._instance.config.error_tracking)==null?void 0:e.exception_steps)!==null&&t!==void 0?t:{}}ol(t){if(t.length===0)return!1;try{var e=t.reduce(((n,i)=>{var r=i.type,s=i.value;return X(r)&&r.length>0&&n.$exception_types.push(r),X(s)&&s.length>0&&n.$exception_values.push(s),n}),{$exception_types:[],$exception_values:[]});return this.Xo.some((n=>{var i=n.values.map((r=>{var s=Hf[r.operator],o=e[r.key];if(!s||!o)return!1;var a=U(r.value)?r.value:[r.value];return a.length>0&&s(a,o)}));return n.type==="OR"?i.some(Boolean):i.every(Boolean)}))}catch(n){return St.warn("Failed to evaluate suppression rules. Capturing the exception.",n),!1}}ul(t){return t.flatMap((e=>{var n,i;return(n=(i=e.stacktrace)==null?void 0:i.frames)!==null&&n!==void 0?n:[]})).some((e=>e.filename&&e.filename.startsWith("chrome-extension://")))}hl(t){if(t.length>0){var e,n,i,r,s=(e=(n=t[0].stacktrace)==null?void 0:n.frames)!==null&&e!==void 0?e:[],o=s[s.length-1];return(i=o==null||(r=o.filename)==null?void 0:r.includes("posthog.com/static"))!==null&&i!==void 0&&i}return!1}al(t){return!H(t)&&U(t)}}},Km=I({productTours:class{get Mr(){return this._instance.persistence}constructor(t){this.vl=null,this.cl=null,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(t.ok){var e=t.config;if("productTours"in e){var n,i;if(this.Mr&&this.Mr.register({[sl]:!!e.productTours}),!Oo(this._instance))return!this.vl&&H((n=this.Mr)==null?void 0:n.props[Mi])||xr.info("product tours disabled; stopping and clearing cached tours"),(i=this.vl)==null||i.stop(),this.vl=null,void this.clearCache();this.loadIfEnabled()}}}loadIfEnabled(){!this.vl&&Oo(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.generateProductTours?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",(i=>{i?xr.error("Could not load product tours script",i):t()}))}fl(){var t;!this.vl&&(t=B.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=B.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(t,e){if(e===void 0&&(e=!1),!U(this.cl)||e){var n=this.Mr;if(n){var i=n.props[Mi];if(U(i)&&!e)return this.cl=i,void t(i,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",timestampMode:"query",callback:r=>{if(Oo(this._instance)){var s=r.statusCode;if(s!==200||!r.json){var o="Product Tours API could not be loaded, status: "+s;return s===0?r.error||xr.warn(o):xr.error(o),void t([],{isLoaded:!1,error:o})}var a=U(r.json.product_tours)?r.json.product_tours:[];this.cl=a,n&&n.register({[Mi]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){H(this.vl)?t([],{isLoaded:!1,error:"Product tours not loaded"}):this.vl.getActiveProductTours(t)}showProductTour(t){var e;(e=this.vl)==null||e.showTourById(t)}previewTour(t){this.vl?this.vl.previewTour(t):this.ai((()=>{var e;this.fl(),(e=this.vl)==null||e.previewTour(t)}))}dismissProductTour(){var t;(t=this.vl)==null||t.dismissTour("user_clicked_skip")}nextStep(){var t;(t=this.vl)==null||t.nextStep()}previousStep(){var t;(t=this.vl)==null||t.previousStep()}clearCache(){var t;this.cl=null,(t=this.Mr)==null||t.unregister(Mi)}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)}}},Cs),Ym={siteApps:class{constructor(t){this.pl=0,this._instance=t,this.gl=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}ml(t,e){if(e){var n=this.globalsForEvent(e);this.gl.push(n),this.gl.length>1e3&&(this.gl=this.gl.slice(10))}}get siteAppLoaders(){var t;return(t=B._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,n,i,r,s,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var h=d[0];l[h]={id:u[h],type:h,properties:d[1]}}var f=t.$set_once,p=t.$set;return{event:I({},fd(t,Bm),{properties:I({},t.properties,p?{$set:I({},(e=(n=t.properties)==null?void 0:n.$set)!==null&&e!==void 0?e:{},p)}:{},f?{$set_once:I({},(i=(r=t.properties)==null?void 0:r.$set_once)!==null&&i!==void 0?i:{},f)}:{}),elements_chain:(s=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&s!==void 0?s:"",distinct_id:(a=t.properties)==null?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}bl(t){var e,n=(e=t.tagName)==null?void 0:e.toLowerCase();return n==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(Et.error("prepare_external_dependency_stylesheet returned null"),null):n==="script"&&this._instance.config.prepare_external_dependency_script?this._instance.config.prepare_external_dependency_script(t)||(Et.error("prepare_external_dependency_script returned null"),null):t}_l(){var t,e,n,i,r,s,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=P?.defaultView,u=l==null||(t=l.Node)==null?void 0:t.prototype;if(!l||!u)return()=>{};if(this.pl++,this.wl)return this.kl();var c=[],d=this,h=new WeakSet,f=(m,v,E)=>{if(m!=null&&m[v]){var S=m[v];m[v]=E(S),c.push((()=>{m[v]=S}))}},p=m=>{if(h.has(m))return m;var v=d.bl(m);return v&&h.add(v),v},g=m=>m.map((v=>typeof v=="string"?v:p(v))).filter((v=>!Ye(v)));return f(u,"appendChild",(m=>function(v){var E=p(v);return E?m.call(this,E):v})),f(u,"insertBefore",(m=>function(v,E){var S=p(v);return S?m.call(this,S,E):v})),f(u,"replaceChild",(m=>function(v,E){var S=p(v);return S?m.call(this,S,E):E})),[(e=l.Element)==null?void 0:e.prototype,(n=l.Document)==null?void 0:n.prototype,(i=l.DocumentFragment)==null?void 0:i.prototype].forEach((m=>{f(m,"append",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),f(m,"prepend",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))}))})),[(r=l.Element)==null?void 0:r.prototype,(s=l.CharacterData)==null?void 0:s.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((m=>{f(m,"before",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),f(m,"after",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),f(m,"replaceWith",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];var b=g(S);return S.length&&!b.length?void 0:v.apply(this,b)}))})),f((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(v,E){var S=p(E);return S?m.call(this,v,S):null})),this.wl=()=>{c.forEach((m=>m())),this.wl=void 0},this.kl()}kl(){var t=!1;return()=>{var e;t||(t=!0,this.pl--,this.pl===0&&((e=this.wl)==null||e.call(this)))}}xl(t,e){e===void 0&&(e=!0);var n=this._l();try{var i=t(n);return e&&n(),i}catch(r){throw n(),r}}setupSiteApp(t){var e=this.apps[t.id],n=()=>{var o;!e.errored&&this.gl.length&&(Et.info("Processing "+this.gl.length+" events for site app with id "+t.id),this.gl.forEach((a=>this.xl((()=>e.processEvent==null?void 0:e.processEvent(a))))),e.processedBuffer=!0),Object.values(this.apps).every((a=>a.processedBuffer||a.errored))&&((o=this.yl)==null||o.call(this))},i=!1,r=o=>{e.errored=!o,e.loaded=!0,Et.info("Site app with id "+t.id+" "+(o?"loaded":"errored")),i&&n()};try{var s=this.xl((o=>t.init({posthog:this._instance,callback(a){o(),r(a)}})),!1).processEvent;s&&(e.processEvent=s),i=!0}catch(o){Et.error(uu+t.id,o),r(!1)}if(i&&e.loaded)try{n()}catch(o){Et.error("Error while processing buffered events PostHog app with config id "+t.id,o),e.errored=!0}}Sl(){var t=this.siteAppLoaders||[];for(var e of t)this.apps[e.id]={id:e.id,loaded:!1,errored:!1,processedBuffer:!1};for(var n of t)this.setupSiteApp(n)}Cl(t){var e=this;if(Object.keys(this.apps).length!==0){var n=this.globalsForEvent(t),i=function(s){try{e.xl((()=>s.processEvent==null?void 0:s.processEvent(n)))}catch(o){Et.error("Error while processing event "+t.event+" for site app "+s.id,o)}};for(var r of Object.values(this.apps))i(r)}}onRemoteConfig(t){var e,n,i,r=this;if((e=this.siteAppLoaders)!=null&&e.length)return this.isEnabled?(this.Sl(),void this._instance.on("eventCaptured",(l=>this.Cl(l)))):void Et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((n=this.yl)==null||n.call(this),t.ok){var s=t.config;if((i=s.siteApps)!=null&&i.length)if(this.isEnabled){var o=function(){var l,u=a.id,c=a.url;B["__$$ph_site_app_"+u]=r._instance,(l=B.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(r._instance,c,(d=>{if(d)return Et.error(uu+u,d)}))};for(var a of s.siteApps)o()}else Et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},Jm={tracingHeaders:class{constructor(t){this.Ml=void 0,this.Tl=void 0,this.El=void 0,this.Uo=()=>{var e,n,i=this.Il();i?(C(this.Ml)&&(this.Ml=(e=B.__PosthogExtensions__)==null||(e=e.tracingHeadersPatchFns)==null?void 0:e._patchXHR(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager)),C(this.Tl)&&(this.Tl=(n=B.__PosthogExtensions__)==null||(n=n.tracingHeadersPatchFns)==null?void 0:n._patchFetch(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager))):this.Qo()},this._instance=t}initialize(){this.startIfEnabledOrStop()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",(i=>{if(i)return Nm.error("failed to load script",i);t()}))}Pl(){var t,e;return(t=(e=this._instance.config.tracing_headers)!==null&&e!==void 0?e:this._instance.config.addTracingHeaders)!==null&&t!==void 0?t:this._instance.config.__add_tracing_headers}Il(){var t=this.Pl();return U(t)?(U(this.El)?this.El.splice(0,this.El.length,...t):this.El=[...t],t.length>0?this.El:void 0):(U(this.El)&&this.El.splice(0),this.El=t||void 0,this.El)}Qo(){var t,e;(t=this.Ml)==null||t.call(this),(e=this.Tl)==null||e.call(this),this.Ml=void 0,this.Tl=void 0}startIfEnabledOrStop(){this.Il()?this.ai(this.Uo):this.Qo()}}},Zm=I({surveys:class{get Ne(){return this._instance.config}constructor(t){this.Rl=void 0,this._surveyManager=null,this.Al=!1,this.Fl=[],this.Ll=null,this.Ol=null,this._instance=t,this._surveyEventReceiver=null}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this.Ne.disable_surveys){if(!t.ok)return Q.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(H(e))return Q.warn("Flags not loaded yet. Not loading surveys.");var n=U(e);this.Rl=n?e.length>0:e,Q.info("flags response received, isSurveysEnabled: "+this.Rl),this.loadIfEnabled()}}reset(){try{var t;(t=this._surveyEventReceiver)==null||t.reset(),localStorage.removeItem("lastSeenSurveyDate");for(var e=[],n=0;nlocalStorage.removeItem(r)))}catch{}}loadIfEnabled(){if(!this._surveyManager)if(this.Al)Q.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)Q.info(du);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())Q.info("Not loading surveys in cookieless mode without consent.");else{var t=B?.__PosthogExtensions__;if(t){if(!C(this.Rl)||this.Ne.advanced_enable_surveys){var e=this.Rl||this.Ne.advanced_enable_surveys;this.Al=!0;try{var n=t.generateSurveys;if(n)return void this.Dl(n,e);var i=t.loadExternalDependency;if(!i)return void this.$l(al);i(this._instance,"surveys",(r=>{r||!t.generateSurveys?this.$l("Could not load surveys script",r):this.Dl(t.generateSurveys,e)}))}catch(r){throw this.$l("Error initializing surveys",r),r}finally{this.Al=!1}}}else Q.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new Um(this._instance),Q.info("Surveys loaded successfully"),this.Nl({isLoaded:!0})}$l(t,e){Q.error(t,e),this.Nl({isLoaded:!1,error:t})}onSurveysLoaded(t){return this.Fl.push(t),this._surveyManager&&this.Nl({isLoaded:!0}),()=>{this.Fl=this.Fl.filter((e=>e!==t))}}getSurveys(t,e){if(e===void 0&&(e=!1),this.Ne.disable_surveys)return Q.info(du),t([]);var n,i=this._instance.get_property(la);if(i&&!e)return t(i,{isLoaded:!0}),void(this.ql()&&this.getSurveys((()=>{}),!0));typeof Promise<"u"&&this.Ll?this.Ll.then((r=>t(r.surveys,r.context))):(typeof Promise<"u"&&(this.Ll=new Promise((r=>{n=r}))),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this.Ne.token),method:"GET",timestampMode:"query",timeout:this.Ne.surveys_request_timeout_ms,callback:r=>{var s;this.Ll=null;var o=r.statusCode;if(o!==200||!r.json){var a="Surveys API could not be loaded, status: "+o;o!==0?Q.error(a):r.error||Q.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(n==null||n({surveys:[],context:l}))}this.Ol=null;var u,c=r.json.surveys||[],d=c.filter((f=>(function(p){return!(!p.start_date||p.end_date)})(f)&&(zf(f)||(function(p){var g;return!((g=p.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(f))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(s=this._instance.persistence)==null||s.register({[la]:c,[Xr]:Date.now()});var h={isLoaded:!0};t(c,h),n?.({surveys:c,context:h})}}))}ql(){return this.jl()&&!this.Ll&&!this.Bl()}jl(){var t=this._instance.get_property(Xr);return ke(t)&&Date.now()-t>3e5}Bl(){return ke(this.Ol)&&3e5>Date.now()-this.Ol}markSurveyAsSeen(t,e){var n,i={id:t,current_iteration:(n=e?.iteration)!==null&&n!==void 0?n:null};Vf(i);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}}Nl(t){for(var e of this.Fl)try{if(!t.isLoaded)return e([],t);this.getSurveys(e)}catch(n){Q.error("Error in survey callback",n)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!H(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);Q.warn("init was not called")}Hl(t){var e=null;return this.getSurveys((n=>{var i;e=(i=n.find((r=>r.id===t)))!==null&&i!==void 0?i:null})),e}Ul(t){if(H(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(H(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(H(this._surveyManager))return Q.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 H(this._surveyManager)?(Q.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Ir})):new Promise((n=>{this.getSurveys((i=>{var r,s=(r=i.find((a=>a.id===t)))!==null&&r!==void 0?r:null;if(s){var o=this.zl(s);n({visible:o.eligible,disabledReason:o.reason})}else n({visible:!1,disabledReason:"Survey not found"})}),e)}))}renderSurvey(t,e,n){var i;if(H(this._surveyManager))Q.warn("init was not called");else{var r=typeof t=="string"?this.Hl(t):t;if(r!=null&&r.id)if(Sm.includes(r.type)){var s=P?.querySelector(e);if(s)return(i=r.appearance)!=null&&i.surveyPopupDelaySeconds?(Q.info("Rendering survey "+r.id+" with delay of "+r.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;Q.info("Rendering survey "+r.id+" with delay of "+((o=r.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(a=this._surveyManager)==null||a.renderSurvey(r,s,n),Q.info("Survey "+r.id+" rendered")}),1e3*r.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(r,s,n);Q.warn("Survey element not found")}else Q.warn("Surveys of type "+r.type+" cannot be rendered in the app");else Q.warn("Survey not found")}}displaySurvey(t,e){var n;if(H(this._surveyManager))Q.warn("init was not called");else{var i=this.Hl(t);if(i){var r=i;if((n=i.appearance)!=null&&n.surveyPopupDelaySeconds&&e.ignoreDelay&&(r=I({},i,{appearance:I({},i.appearance,{surveyPopupDelaySeconds:0})})),e.displayType!==_a.Popover&&e.initialResponses&&Q.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),e.ignoreConditions===!1){var s=this.Ul(i);if(!s.eligible)return void Q.warn("Survey is not eligible to be displayed: ",s.reason)}e.displayType!==_a.Inline?this._surveyManager.handlePopoverSurvey(r,e):this.renderSurvey(r,e.selector,e.properties)}else Q.warn("Survey not found")}}cancelPendingSurvey(t){H(this._surveyManager)?Q.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},Cs),Xm={toolbar:class{constructor(t){this.instance=t}Wl(t){B.ph_toolbar_state=t}Vl(){var t;return(t=B.ph_toolbar_state)!==null&&t!==void 0?t:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(t,e,n){if(t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),ga(this.instance.config)||!w||!P)return!1;t=t??w.location,n=n??w.history;try{if(!e){try{w.localStorage.setItem("test","test"),w.localStorage.removeItem("test")}catch{return!1}e=w?.localStorage}var i,r=Hm||os(t.hash,"__posthog")||os(t.hash,"state"),s=r?Pc((()=>JSON.parse(atob(decodeURIComponent(r)))))||Pc((()=>JSON.parse(decodeURIComponent(r)))):null;return s&&s.action==="ph_authorize"?((i=s).source="url",i&&Object.keys(i).length>0&&(s.desiredHash?t.hash=s.desiredHash:n?n.replaceState(n.state,"",t.pathname+t.search):t.hash="")):((i=JSON.parse(e.getItem(fu)||"{}")).source="localstorage",delete i.userIntent),!(!i.token||this.instance.config.token!==i.token||(this.loadToolbar(i),0))}catch{return!1}}Zl(t){var e=B.ph_load_toolbar||B.ph_load_editor;!H(e)&&je(e)?e(t,this.instance):hu.warn("No toolbar load function found")}loadToolbar(t){var e=!(P==null||!P.getElementById(af));if(!w||e)return!1;var n=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,i=I({token:this.instance.config.token},t,{apiURL:this.instance.requestRouter.endpointFor("ui")},n?{instrument:!1}:{});if(w.localStorage.setItem(fu,JSON.stringify(I({},i,{source:void 0}))),this.Vl()===2)this.Zl(i);else if(this.Vl()===0){var r;this.Wl(1),(r=B.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"toolbar",(s=>{if(s)return hu.error("[Toolbar] Failed to load",s),void this.Wl(0);this.Wl(2),this.Zl(i)})),ve(w,"turbolinks:load",(()=>{this.Wl(0),this.loadToolbar(i)}))}return!0}Gl(t){return this.loadToolbar(t)}maybeLoadEditor(t,e,n){return t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),this.maybeLoadToolbar(t,e,n)}}},Qm=I({experiments:Me},Cs),ev={conversations:class{constructor(t){this.Ql=void 0,this._conversationsManager=null,this.Kl=!1,this.Jl=null,this.Yl=!1,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this._instance.config.disable_conversations&&(this.Xl=t.ok,t.ok)){var e=t.config.conversations;H(e)||(mt(e)?this.Ql=e:(this.Ql=e.enabled,this.Jl=e),this.loadIfEnabled())}}reset(){var t;(t=this._conversationsManager)==null||t.reset(),this._conversationsManager=null,this.Ql=void 0,this.Jl=null,this.Xl=void 0,this.Yl=!1}loadIfEnabled(){if(!(this._conversationsManager||this.Kl||this._instance.config.disable_conversations||ga(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=B?.__PosthogExtensions__;if(t&&!C(this.Ql)&&this.Ql)if(this.Jl&&this.Jl.token){this.Kl=!0;try{var e=t.initConversations;if(e)return this.tu(e),void(this.Kl=!1);var n=t.loadExternalDependency;if(!n)return void this.eu(al);n(this._instance,"conversations",(i=>{i||!t.initConversations?this.eu("Could not load conversations script",i):this.tu(t.initConversations),this.Kl=!1}))}catch(i){this.eu("Error initializing conversations",i),this.Kl=!1}}else ot.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,ot.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else ot.error("Cannot complete initialization: remote config is null")}eu(t,e){ot.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():ot.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!Ye(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":ga(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.Xl===!1?"remote_config_failed":C(this.Ql)?this.Xl?"disabled_in_project":"remote_config_pending":this.Ql?H(this.Jl)||!this.Jl.token?"missing_token":B!=null&&B.__PosthogExtensions__?this.Kl?"initializing":this.Yl?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.isVisible())!==null&&t!==void 0&&t}sendMessage(t,e,n){var i=this;return se((function*(){return i._conversationsManager?i._conversationsManager.sendMessage(t,e,n):(ot.warn(En),null)}))()}getMessages(t,e){var n=this;return se((function*(){return n._conversationsManager?n._conversationsManager.getMessages(t,e):(ot.warn(En),null)}))()}markAsRead(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(ot.warn(En),null)}))()}getTickets(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(ot.warn(En),null)}))()}requestRestoreLink(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(ot.warn(En),null)}))()}restoreFromToken(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(ot.warn(En),null)}))()}restoreFromUrlToken(){var t=this;return se((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(ot.warn(En),null)}))()}getCurrentTicketId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getCurrentTicketId())!==null&&t!==void 0?t:null}getWidgetSessionId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getWidgetSessionId())!==null&&t!==void 0?t:null}Xn(){var t;(t=this._conversationsManager)==null||t.setIdentity()}ts(){var t;(t=this._conversationsManager)==null||t.clearIdentity()}}},tv={logs:class{constructor(t){var e,n=this;this.iu=!1,this.ru=!1,this.rt=pe("[logs]"),this.nu=I({},this.rt,{error(){for(var i=arguments.length,r=new Array(i),s=0;i>s;s++)r[s]=arguments[s];r.some(bu)||n.rt.error(...r)}}),this.tr=[],this.su=[],this.Sa=0,this.au=()=>{var i,r;this.Sa=0,(i=this.ou)==null||i.onReconnect(),(r=this.lu)==null||r.onReconnect()},this._instance=t,this._instance&&(e=this._instance.config.logs)!=null&&e.captureConsoleLogs&&(this.iu=!0),w&&ve(w,"online",this.au)}uu(t,e,n,i){var r,s=(function(o,a){var l,u,c,d,h,f,p,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,v=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,E=C(v)?Math.max(m,2048):Math.max(m,v),S=o?.resourceAttributes;return{serviceName:(d=(h=S?.["service.name"])!==null&&h!==void 0?h:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(f=S?.["service.version"])!==null&&f!==void 0?f:o?.serviceVersion,environment:(p=S?.["deployment.environment"])!==null&&p!==void 0?p:o?.environment,resourceAttributes:S,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:E,maxBatchRecordsPerPost:100,rateCapWindowMs:g,maxLogsPerInterval:v,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}})((r=this._instance)==null||(r=r.config)==null?void 0:r.logs,n);return[new sg(this.hu(t,e),s,this.nu,(()=>this.du()),(o=>o()),void 0,i),s]}vu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.ou||this.cu!==e){var n;(n=this.ou)==null||n.reset(),this.cu=e;var i=this.uu((()=>this.tr),(r=>{this.tr=r}));this.ou=i[0],this.fu=i[1]}return this.ou}pu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.lu||this.gu!==e){var n;(n=this.lu)==null||n.reset(),this.gu=e;var i=this.uu((()=>this.su),(r=>{this.su=r}),{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},wu);this.lu=i[0],this.mu=i[1]}return this.lu}initialize(){this.loadIfEnabled()}onRemoteConfig(t){var e;if(t.ok){var n=(e=t.config.logs)==null?void 0:e.captureConsoleLogs;!H(n)&&n&&(this.iu=!0,this.loadIfEnabled())}}reset(){var t,e;this.tr=[],(t=this.ou)==null||t.reset(),this.su=[],(e=this.lu)==null||e.reset(),this.Sa=0}captureLog(t){this.vu().captureLog(t)}he(t){this.pu().captureLog(t)}get logger(){return this.yu||(this.yu={trace:(t,e)=>this.captureLog({body:t,level:"trace",attributes:e}),debug:(t,e)=>this.captureLog({body:t,level:"debug",attributes:e}),info:(t,e)=>this.captureLog({body:t,level:"info",attributes:e}),warn:(t,e)=>this.captureLog({body:t,level:"warn",attributes:e}),error:(t,e)=>this.captureLog({body:t,level:"error",attributes:e}),fatal:(t,e)=>this.captureLog({body:t,level:"fatal",attributes:e})}),this.yu}flushLogs(t){t?this.bu(t):(this.ou&&this.ou.flush().catch((e=>this._u(e))),this.lu&&this.lu.flush().catch((e=>this._u(e))))}_u(t){bu(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=B?.__PosthogExtensions__;if(t){var e=t.loadExternalDependency;e?e(this._instance,"logs",(n=>{var i;n||(i=t.logs)==null||!i.initializeLogs?this.rt.error("Could not load logs script",n):(t.logs.initializeLogs(this._instance),this.ru=!0)})):this.rt.error(al)}else this.rt.error("PostHog Extensions not found.")}}hu(t,e){var n=this._instance;return{get isDisabled(){return!1},get optedOut(){return!n.is_capturing()},getPersistedProperty:i=>i===Ut.LogsQueue?t():void 0,setPersistedProperty(i,r){var s;i===Ut.LogsQueue&&e((s=r)!==null&&s!==void 0?s:[])},Ot:i=>this.Ot(i),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Ot(t){return new Promise((e=>{if(yf(this.Sa,3))e({kind:"fatal",error:Do(void 0,"logs endpoint is unreachable, dropping batch")});else{var n=!1,i=s=>{n||(n=!0,clearTimeout(r),e(s))},r=setTimeout((()=>{this.rt.warn("Logs request timed out before receiving a response"),i({kind:"retry-later",error:Do(void 0,"logs request timed out")})}),9e4);this._instance._send_request({method:"POST",url:this.wu(),data:t,compression:"best-available",batchKey:"logs",fireCallbackOnDrop:!0,callback:s=>{var o=s.statusCode;if(this.ku(o),o>=200&&300>o)i({kind:"ok"});else if(o===413)i({kind:"too-large"});else if(o!==0&&o!==429&&500>o)i({kind:"fatal",error:new Error("logs request failed with status "+o)});else{var a;o===0?(s.error||this.rt.warn("Logs request failed before receiving an HTTP response"),i({kind:"retry-later",error:Do(s.error,"logs request failed before receiving an HTTP response")})):i({kind:"retry-later",error:(a=s.error)!==null&&a!==void 0?a:new Error("logs request failed with status "+o)})}}})}}))}ku(t){(t!==0||this._instance.__loaded)&&(this.Sa=wf(t,this.Sa,3,(()=>this.rt.warn("Log requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped sending logs; will try again when connectivity changes."))))}bu(t){this.tr.length>0&&this.xu(t,this.tr,this.fu,ne.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,wu,(e=>{this.su=e}))}xu(t,e,n,i,r){if(e.length!==0){var s=e.map((a=>a.record));r([]);var o=Wd(s,Hd(n,ne.LIB_NAME,ne.LIB_VERSION),i,ne.LIB_VERSION);this._instance._send_request({method:"POST",url:this.wu(),data:o,compression:"best-available",batchKey:"logs",transport:t})}}wu(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}du(){var t,e={};if(e.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var n=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.windowId,r=n.sessionStartTimestamp,s=n.lastActivityTimestamp;e.sessionId=n.sessionId,e.windowId=i,H(r)||(e.sessionStartTimestamp=r),H(s)||(e.lastActivityTimestamp=s)}if(B!=null&&(t=B.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?fn(B.location.href):B.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},nv={metrics:class{constructor(t){this.rt=pe("[metrics]"),this._instance=t}initialize(){}vu(){var t,e,n=(t=this._instance)==null||(t=t.config)==null?void 0:t.metrics;return this.ou&&this.cu===n||((e=this.ou)==null||e.reset(),this.cu=n,this.ou=new og(this.hu(),(function(i){var r,s,o,a,l,u=i?.resourceAttributes;return{serviceName:(r=u?.["service.name"])!==null&&r!==void 0?r:i?.serviceName,serviceVersion:(s=u?.["service.version"])!==null&&s!==void 0?s:i?.serviceVersion,environment:(o=u?.["deployment.environment"])!==null&&o!==void 0?o:i?.environment,resourceAttributes:u,beforeSend:i?.beforeSend,flushIntervalMs:(a=i?.flushIntervalMs)!==null&&a!==void 0?a:1e4,maxSeriesPerFlush:(l=i?.maxSeriesPerFlush)!==null&&l!==void 0?l:1e3}})(n),this.rt)),this.ou}count(t,e,n){e===void 0&&(e=1),this.vu().count(t,e,n)}gauge(t,e,n){this.vu().gauge(t,e,n)}histogram(t,e,n){this.vu().histogram(t,e,n)}flush(t){if(!this.ou)return Promise.resolve();if(t){var e=this.ou.drainWindow();return e&&this.Jt(e,t),Promise.resolve()}return this.ou.flush().catch((n=>this.rt.error("PostHog metrics flush failed:",n)))}reset(){var t;(t=this.ou)==null||t.reset()}hu(){var t=this._instance,e=this;return{get isDisabled(){return!1},get optedOut(){return!t.is_capturing()},Jt:n=>e.Jt(n),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Jt(t,e){return new Promise((n=>{var i=!1,r=o=>{i||(i=!0,clearTimeout(s),n(o))},s=setTimeout((()=>r({kind:"retry-later",error:new Error("metrics request timed out")})),9e4);this._instance._send_request(I({method:"POST",url:this.Su(),data:t,compression:"best-available",batchKey:"metrics"},e&&{transport:e},{fireCallbackOnDrop:!0,callback(o){var a=o.statusCode;if(a>=200&&300>a)r({kind:"ok"});else if(a===413)r({kind:"too-large"});else if(a!==0&&a!==429&&500>a)r({kind:"fatal",error:new Error("metrics request failed with status "+a)});else{var l;r({kind:"retry-later",error:(l=o.error)!==null&&l!==void 0?l:new Error("metrics request failed with status "+a)})}}}))}))}Su(){return this._instance.requestRouter.endpointFor("api","/i/v1/metrics")+"?token="+encodeURIComponent(this._instance.config.token)}}},iv=I({},Cs,qm,Vm,Gm,Km,Ym,Zm,Jm,Xm,Qm,ev,tv,nv);Ze.__defaultExtensionClasses=I({},iv);(function(){ne.SDK_DIST_CHANNEL="npm";var t=Wi[Gn]=new Ze;return(function(){function e(){e.done||(e.done=!0,Kf=!1,ie(Wi,(function(n){n._dom_loaded()})))}P!=null&&P.addEventListener?P.readyState==="complete"?e():ve(P,"DOMContentLoaded",e,{capture:!1}):w&&A.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const rv=["a[href]","button:not([disabled])","input:not([disabled]):not([type='hidden'])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(",");let pt=null,ka=null,Jf="";const Ca=new Map;function Zf(t){return[...t.querySelectorAll(rv)].filter(e=>!e.hidden&&e.getAttribute("aria-hidden")!=="true"&&e.getClientRects().length>0)}function sv(t){for(const e of document.body.children)e===t||e.tagName==="SCRIPT"||(Ca.set(e,{inert:e.inert,ariaHidden:e.getAttribute("aria-hidden")}),e.inert=!0,e.setAttribute("aria-hidden","true"))}function ov(){for(const[t,e]of Ca)t.inert=e.inert,e.ariaHidden===null?t.removeAttribute("aria-hidden"):t.setAttribute("aria-hidden",e.ariaHidden);Ca.clear()}function Xf(t){return t?.dataset.modalDismissible!=="false"&&t?.getAttribute("aria-busy")!=="true"}function We(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n)return!1;pt&&pt!==n&&ze(pt,{restoreFocus:!1,force:!0}),ka=e.trigger||document.activeElement,pt=n,Jf=document.body.style.overflow,sv(n),document.body.style.overflow="hidden",n.classList.add("open"),n.setAttribute("aria-hidden","false");const i=n.querySelector(".modal-content");i&&(i.style.transform="scale(1) translateY(0)");const r=()=>{if(pt!==n)return;((e.initialFocus?n.querySelector(e.initialFocus):n.querySelector("[data-modal-initial-focus]"))||Zf(n)[0]||n.querySelector(".modal-content")||n).focus({preventScroll:!0})};return requestAnimationFrame(r),setTimeout(r,260),!0}function ze(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n||!e.force&&!Xf(n))return!1;n.classList.remove("open"),n.setAttribute("aria-hidden","true"),ov(),document.body.style.overflow=Jf,pt=null;const i=ka;return ka=null,e.restoreFocus!==!1&&i?.isConnected&&i.focus({preventScroll:!0}),!0}function Eu(t,e,n="Operation in progress"){const i=typeof t=="string"?document.getElementById(t):t;i&&(i.dataset.modalDismissible=e?"false":"true",i.setAttribute("aria-busy",String(!!e)),e?i.setAttribute("aria-label",n):i.removeAttribute("aria-label"))}function av(t){if(!Xf(t))return;const e=t.dataset.modalCloseHandler;e&&typeof window[e]=="function"?window[e]():ze(t)}document.addEventListener("keydown",t=>{if(!pt)return;if(t.key==="Escape"){t.preventDefault(),t.stopImmediatePropagation(),av(pt);return}if(t.key!=="Tab"){t.stopPropagation();return}const e=Zf(pt);if(!e.length){t.preventDefault(),(pt.querySelector(".modal-content")||pt).focus();return}const n=e[0],i=e[e.length-1];t.shiftKey&&document.activeElement===n?(t.preventDefault(),i.focus()):!t.shiftKey&&document.activeElement===i&&(t.preventDefault(),n.focus())},!0);function lv(){document.querySelectorAll(".modal-overlay").forEach(t=>{t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-hidden",t.classList.contains("open")?"false":"true");const e=t.querySelector(".modal-content");e&&!e.hasAttribute("tabindex")&&(e.tabIndex=-1);const n=t.querySelector("h1, h2, h3");n&&(n.id||(n.id=`${t.id}-title`),t.setAttribute("aria-labelledby",n.id)),t.querySelectorAll(".modal-close").forEach(i=>{i.getAttribute("aria-label")||i.setAttribute("aria-label","Close dialog")})})}const gl=Object.freeze({free:"Free",professional:"Pro",power:"Power"}),cv=Object.freeze({free:2,professional:50,power:2e3}),uv="(contact us)",dv=Object.freeze({free:Object.freeze(["2 generations/month","Gemini model only","Code Review"]),professional:Object.freeze(["50 generations/month","All models","Code Regeneration","Code Review"]),power:Object.freeze(["2000 generations/month","All models","Code Regeneration","Bring your own key (BYOK)","Code Review","All models + early access",`API & MCP access ${uv}`])}),Qf="CodeFile",eh="GeneratedCode",fv={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function ln(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Aa(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function hv(t={},e=0){const n=Aa(t.artifactType||t.type||Qf),i=Aa(t.artifactName||t.name||t.fileName||`${eh}-${e+1}`);return`${n||"artifact"}-${i||e+1}`}function th(t={},e=0){const n=ln(t),i=n.artifactType||n.type||Qf,r=n.artifactName||n.name||eh;let s=n.fileName||r;return s.endsWith(".dart")||(s+=".dart"),{id:Aa(n.id)||hv({...n,artifactType:i,artifactName:r,fileName:s},e),artifactType:i,artifactName:r,fileName:s,deployPath:n.deployPath||"",description:n.description||"",code:n.code||n.content||"",dependencies:nh(n.dependencies),imports:Array.isArray(n.imports)?n.imports:[],publicApi:Array.isArray(n.publicApi)?n.publicApi:[],relationships:ih(n.relationships),deployStatus:n.deployStatus||"pending",review:n.review||null,metadata:ln(n.metadata),codeType:n.codeType||fv[i]||"O"}}function nh(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const n=ln(e),i=n.name||n.package;return i?{name:i,version:n.version||null,versionRequired:!!(n.versionRequired||n.required),inferred:!!n.inferred,...n.reason?{reason:n.reason}:{}}:null}).filter(Boolean):Object.entries(ln(t)).map(([e,n])=>({name:e,version:n||null,inferred:!1})):[]}function ih(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const n=ln(e);return!n.from&&!n.to?null:{from:n.from||null,to:n.to||null,type:n.type||"uses",description:n.description||""}}).filter(Boolean):[]}function Pa(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;try{return JSON.parse(e)}catch{const n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(!n)return null;try{return JSON.parse(n[1].trim())}catch{return null}}}function Qi(t,e={}){const n=[],i=typeof t=="string"?Pa(t):t,s=ln(i||{});!i&&typeof t=="string"&&n.push("Structured bundle parse failed; using legacy single-artifact fallback.");const o=Array.isArray(s.artifacts)?s.artifacts:[{artifactType:s.artifactType||e.artifactType,artifactName:s.artifactName||e.artifactName,fileName:s.fileName||e.fileName,description:s.description,code:s.code||e.code||(typeof t=="string"?t:""),dependencies:s.dependencies||e.dependencies,relationships:s.relationships||e.relationships}];o.forEach((d,h)=>{!d?.artifactType&&!d?.type&&n.push(`Artifact ${h+1} has no artifactType; it will deploy as a standalone code file under lib/custom_code/ root.`)});const a=o.map((d,h)=>th(d,h)),l=new Map(o.map((d,h)=>[ln(d).id,a[h]?.id]).filter(([d,h])=>d&&h)),u=d=>l.get(d)||d,c=ih(s.relationships||e.relationships).map(d=>({...d,from:d.from?u(d.from):d.from,to:d.to?u(d.to):d.to}));return{schemaVersion:s.schemaVersion||e.schemaVersion||null,id:s.id||e.id||"bundle-current",title:s.title||s.name||e.title||"Generated artifact bundle",description:s.description||e.description||"",artifacts:a,dependencies:nh(s.dependencies||e.dependencies),relationships:c,deployOrder:Array.isArray(s.deployOrder)?s.deployOrder.map(u):a.map(d=>d.id),warnings:[...n,...Array.isArray(s.warnings)?s.warnings:[]],metadata:ln(s.metadata)}}function oi(t){return Qi(t).artifacts[0]||th()}function Zt(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function ai(t){return JSON.stringify(t,null,2)}function pv(t){return ai({task:"architect",userRequest:String(t??"")})}function gv(t){const e=Zt(t);return e&&typeof e=="object"&&typeof e.task=="string"?ai(e):ai({task:"generate_bundle",bundleSpec:e})}function mv(t){return ai({task:"review_bundle",generatedBundle:Zt(t),outputRequirements:{bundleReview:["status","score","summary","manualActions","findings"],scoreRange:[0,100],eachArtifact:["id","review.status","review.findings"],manualActions:{definition:"Setup the developer must perform by hand in the FlutterFlow editor that FlutterFlow will NOT do for them.",exclude:["creating the Custom Action, Widget or Code File itself - deploying the code creates it","declaring parameters or return values FlutterFlow derives from the function signature","anything that resolves as a side effect of using the action or widget in the editor","generic advice such as testing, reviewing or rebuilding the app"],preferEmpty:"Return an empty array when nothing qualifies - an empty list is the expected result for most bundles."}}})}function ml(t,e=null){const n={stage:t};return e!=null&&(n.bundle=Zt(e)),n}function vv({bundleSpec:t,artifactBundle:e,bundleReview:n,artifactId:i,userFeedback:r}){return ai({task:"regenerate_artifact",artifactId:i,bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(r)})}function rh({bundleSpec:t,artifactBundle:e,bundleReview:n,userFeedback:i}){return ai({task:"regenerate_bundle",bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(i??"")})}const Su={csam:"child-safety content",dangerous:"dangerous content",harassment:"harassment",hate_speech:"hate speech",maliciousUrls:"a potentially malicious URL",malicious_uris:"a potentially malicious URL",pi_and_jailbreak:"prompt-injection or jailbreak instructions",promptInjection:"prompt-injection or jailbreak instructions",rai:"restricted content",sdp:"sensitive personal data",sexually_explicit:"sexually explicit content",virus_scan:"potentially malicious file content"},_v=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function tt(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function yv(t){return tt(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||tt(t.filterSummary)||tt(t.filterResults):!1}function sh(t,e=0){if(!tt(t)||e>3)return null;if(yv(t))return t;for(const n of _v){const i=t[n];if(tt(i)){const r=sh(i,e+1);if(r)return r}}return null}function ds(t){return Array.isArray(t)?t.some(ds):tt(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(ds):!1}function Fa(t){return Array.isArray(t)?t.some(Fa):tt(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(Fa):!1}function oh(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function wv(t,e){if(tt(t))for(const[n,i]of Object.entries(t)){if(!tt(i))continue;const r=tt(i.categories)?i.categories:{},s=Object.entries(r).filter(([,o])=>tt(o)&&o.matched===!0).map(([o])=>o);s.length>0?s.forEach(o=>e.add(o)):i.matched===!0&&e.add(oh(n))}}function bv(t,e){if(!t)return;const n=Array.isArray(t)?t.flatMap(i=>tt(i)?Object.entries(i):[]):Object.entries(t);for(const[i,r]of n){if(!ds(r))continue;const s=oh(i),o=r?.raiFilterResult?.raiFilterTypeResults||(s==="rai"?r?.raiFilterTypeResults:null),a=tt(o)?Object.entries(o).filter(([,l])=>ds(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(s)}}function Ev(t){return Su[t]?Su[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function xu(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 Sv(t){const e=sh(t);if(!e)return null;const n=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);wv(e.filterSummary,n),bv(e.filterResults,n);const i=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||n.size>0,r=e.invocationResult||null,s=Fa(e.filterSummary||e.filterResults);return!i&&!s&&!["PARTIAL","FAILURE"].includes(r)?null:{kind:i?"blocked":"unavailable",invocationResult:r,matchedFilters:[...n]}}function xv(t,e){const n=Sv(t);if(!n)return null;const i=[...new Set(n.matchedFilters.map(Ev))],r=n.kind==="blocked",s=new Error(r?`Safety screening blocked this pipeline step for ${xu(i)}.`:"Safety screening could not be completed. Please try again.");return s.name="ModelArmorError",s.code=r?"MODEL_ARMOR_BLOCKED":"MODEL_ARMOR_UNAVAILABLE",s.isModelArmor=!0,s.pipelineStep=e,s.userTitle=r?"Request blocked for safety":"Safety check unavailable",s.userMessage=r?`The safety check detected ${xu(i)}. Edit your request to remove or rephrase the flagged content, then run the pipeline again.`:"The safety service did not finish all of its checks. Please wait a moment and run the pipeline again.",s.retryExplanation=r?"Trying another model would not change this safety decision.":"A fallback model was not attempted because safety screening must complete first.",s.matchedFilters=n.matchedFilters,s}function Iv(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function Iu(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,n=[];for(const i of Iv(t).split(` +`)){if(!/^[A-Za-z_$]/.test(i)||e.test(i))continue;const r=i.match(/^[\w$<>,?\s[\]]+?\s([a-zA-Z_$][\w$]*)\s*\(/);r&&n.push(r[1])}return n}function vl(t,e){const n=t.replace(/\.dart$/,"");if(e==="W")return n.replace(/(^|_)(\w)/g,(i,r,s)=>s.toUpperCase());if(e==="A"){const i=n.replace(/(^|_)(\w)/g,(r,s,o)=>o.toUpperCase());return i.charAt(0).toLowerCase()+i.slice(1)}return e==="F"?"CustomFunctions":e==="C"?t.endsWith(".dart")?t:`${t}.dart`:n}async function ku(t){const e=new TextEncoder().encode(String(t||"")),n=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n),i=>i.toString(16).padStart(2,"0")).join("")}async function kv(t,e=new Map){const n={},i=new Set;for(const[o,a]of t.entries()){if(a.type==="D"||a.type==="O")continue;const l=vl(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await ku(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await ku(c)),n[o]=u,a.type==="F"){const d=Iu(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(f=>i.add(f))}}const r=new Set(Iu(e.get("lib/flutter_flow/custom_functions.dart")||"")),s={functions_to_rename:[],functions_to_delete:[],functions_to_add:Array.from(i).filter(o=>!r.has(o))};return{fileMapContents:JSON.stringify(n),functionsMapContents:JSON.stringify(s)}}const Cv=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),Cu={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},Av=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),Pv=["Struct","Record"],Fv=[{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=>jo(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=>jo(t).some(e=>{const n=/^\s*final\s+(?:double|int|String|bool|Color|num)\s+(\w+)\s*;/gm;let i;for(;(i=n.exec(e))!==null;){const r=i[1];if(!(new RegExp(`this\\.${r}\\s*=(?!=)`).test(e)||new RegExp(`[:,]\\s*${r}\\s*=(?!=)`).test(e)))return!0}return!1}),pos:`class W extends StatefulWidget { const W({required this.value}); final double value; @@ -25,52 +25,52 @@ class _S extends State { @override Widget build(BuildContext c) => const Size @override _S createState() => _S(); } class _S extends State { @override Widget build(BuildContext c) => Padding(padding: const EdgeInsets.all(8), child: const SizedBox()); }`}];function xt(t,e,n){return{artifactId:t.id,artifactName:t.artifactName,artifactType:t.artifactType,severity:e,message:n}}function er(t){let e="",n=0;for(;n"&&(n--,n===0))return{inner:t.slice(e+1,i),end:i+1};return null}function Rv(t,e){const n=new RegExp(`class\\s+${e}\\b[^{]*\\{`).exec(t);if(!n)return null;let i=0;for(let r=n.index+n[0].length-1;rTv(t).usable);function Mv(t=""){const e=er(t);return $v.filter(n=>n.detect(e)).map(({id:n,severity:i,message:r})=>({id:n,severity:i,message:r}))}function Lv(t){const e=[],n=t.matchAll(/\bFuture\b/g);for(const i of n){let r=i.index+6,s=null;const o=r;for(;ro;if(t[r]==="<"){const u=Fv(t,r);if(!u||(s=u.inner.replace(/\s+/g," ").trim(),r=u.end,!/\s/.test(t[r]||"")))continue;for(;rAu(o.functionName)===i);if(r)return r;const s=o=>!o.functionName.startsWith("_");return n.find(s)||n[0]}function As(t=""){return Array.from(er(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function Nv(t="",e=""){return _l(t,e)?.returnType||null}function Pu(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 Ov(t,e){const n=As(e);if(n.length===0)return null;const r=String(t||"").split("/").pop().replace(/\.dart$/,"");if(n.some(l=>Pu(l)===r)||n.length>1)return null;const[o]=n,a=`${Pu(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 yl(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function Bv(t,e,n=""){const i=_l(e,n)?.functionName;if(!i)return null;const r=String(t||"").split("/").pop(),s=vl(r,"A");if(s===i)return null;const o=`${yl(i)}.dart`;return`File name "${r}" does not match Action "${i}". FlutterFlow derives the action from the file name, so it looks for "${s}" and reports Action "${s}" declaration not found. Rename the file to "${o}" - FlutterFlow puts an underscore before every capital - or rename the function to "${s}".`}function Dv(t="",e=""){return _l(t,e)!==null}function jv(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(i=>Cv.has(i)?!1:!Av.some(s=>i.endsWith(s))||e.has(i))}function Uv(t,{functionName:e="",declaredTypes:n=new Set}={}){const i=Nv(t,e),r=jv(i,n);if(r.length===0)return null;const[s]=r;let o;return n.has(s)?o=`uses Code File type "${s}", which FlutterFlow cannot process as an Action Return Value`:i===s?o="is not a FlutterFlow Action Return Value":o=`uses type "${s}", which is not a FlutterFlow Action Return Value`,`CustomAction return type "${i}" ${o}. Return JSON (Future) or an existing FlutterFlow Data Type (*Struct) instead.`}function Hv(t,e={}){const n=[],i=t.fileName||"",r=t.code||"";if(kv.has(t.artifactType)||n.push(xt(t,"error",`Unsupported artifact type "${t.artifactType}".`)),i.endsWith(".dart")||n.push(xt(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!r.trim())return n.push(xt(t,"warning","Generated artifact has no Dart code yet.")),n;if(t.artifactType==="CustomWidget"){/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)||n.push(xt(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const s of Mv(r))n.push(xt(t,s.severity,s.message))}if(t.artifactType==="CustomAction"&&!Dv(r,t.artifactName)&&n.push(xt(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const s=e.declaredTypes||new Set(As(r)),o=Uv(r,{functionName:t.artifactName,declaredTypes:s});o&&n.push(xt(t,"error",o));const a=Bv(i,r,t.artifactName);a&&n.push(xt(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)&&n.push(xt(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const s=Ov(i,r);s&&n.push(xt(t,"info",s))}return n}function Wv(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],n=new Set(e.flatMap(s=>As(s.code||""))),i=e.flatMap(s=>Hv(s,{declaredTypes:n})),r=e.map(s=>({artifactId:s.id,fileName:s.fileName,pathHint:Cu[s.artifactType]||Cu.CodeFile}));return{valid:i.every(s=>s.severity!=="error"),findings:i,deployHints:r}}const Fu="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function Ru(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function qv(t=""){const e=t.indexOf(Fu);return e===-1?t:t.slice(e+Fu.length).replace(/^\s*\n/,"")}const zv=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function Vv(t="",e=""){const n=qv(t),i=new Set((e.match(/^\s*import .*$/gm)||[]).map(Ru).filter(Boolean)),r=n.split(` -`).filter(s=>{const o=Ru(s);return o===null||!i.has(o)?!0:!zv.test(s)}).join(` -`).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+r}const Gv=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations"]);function oh(t){let e="",n=0;for(;n{const i=n.name||n.package;if(!i||i==="flutter")return e;const r=n.versionRequired||n.required;return e[i]=r&&n.version||"",e},{})}function Xv(t){const e=new Map,n=new Map,i=[];for(const r of t)e.has(r.fileName)?i.push(`Duplicate deploy file name "${r.fileName}" for artifacts "${e.get(r.fileName)}" and "${r.artifactId}".`):e.set(r.fileName,r.artifactId),n.has(r.path)?i.push(`Duplicate deploy path "${r.path}" for artifacts "${n.get(r.path)}" and "${r.artifactId}".`):n.set(r.path,r.artifactId);return i}function Qv(t,e={}){const n=Array.isArray(t?.artifacts)?t.artifacts:[],r=(e.selectedArtifactIds||t?.deployOrder||n.map(f=>f.id)).map(f=>n.find(p=>p.id===f)).filter(Boolean),s=[...t?.warnings||[]];let o=[];r.forEach(f=>{const p=Zv(f),g=f.fixedCode||f.code||"",m=f.codeType||Yv[f.artifactType]||Ze.OTHER;g.trim()||s.push(`${f.artifactName||f.id} has no generated code.`),o.push({artifactId:f.id,artifactName:f.artifactName,artifactType:f.artifactType,fileName:p,content:g,type:m,path:f.deployPath||Jv(p,m),deployPath:f.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((f,p)=>({entry:f,index:p})).filter(({entry:f})=>f.type===Ze.FUNCTION&&f.path===a);if(l.length>1){const f=l[0],p={...f.entry,artifactId:l.map(({entry:m})=>m.artifactId).join("+"),artifactName:f.entry.artifactName,content:l.map(({entry:m})=>`// ${m.artifactId} +`;)n++;e+=" "}else if(i==="/*"){for(n+=2;n"&&(n--,n===0))return{inner:t.slice(e+1,i),end:i+1};return null}function Tv(t,e){const n=new RegExp(`class\\s+${e}\\b[^{]*\\{`).exec(t);if(!n)return null;let i=0;for(let r=n.index+n[0].length-1;r$v(t).usable);function Lv(t=""){const e=er(t);return Mv.filter(n=>n.detect(e)).map(({id:n,severity:i,message:r})=>({id:n,severity:i,message:r}))}function Nv(t){const e=[],n=t.matchAll(/\bFuture\b/g);for(const i of n){let r=i.index+6,s=null;const o=r;for(;ro;if(t[r]==="<"){const u=Rv(t,r);if(!u||(s=u.inner.replace(/\s+/g," ").trim(),r=u.end,!/\s/.test(t[r]||"")))continue;for(;rAu(o.functionName)===i);if(r)return r;const s=o=>!o.functionName.startsWith("_");return n.find(s)||n[0]}function As(t=""){return Array.from(er(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function Ov(t="",e=""){return _l(t,e)?.returnType||null}function Pu(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 Bv(t,e){const n=As(e);if(n.length===0)return null;const r=String(t||"").split("/").pop().replace(/\.dart$/,"");if(n.some(l=>Pu(l)===r)||n.length>1)return null;const[o]=n,a=`${Pu(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 yl(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function Dv(t,e,n=""){const i=_l(e,n)?.functionName;if(!i)return null;const r=String(t||"").split("/").pop(),s=vl(r,"A");if(s===i)return null;const o=`${yl(i)}.dart`;return`File name "${r}" does not match Action "${i}". FlutterFlow derives the action from the file name, so it looks for "${s}" and reports Action "${s}" declaration not found. Rename the file to "${o}" - FlutterFlow puts an underscore before every capital - or rename the function to "${s}".`}function jv(t="",e=""){return _l(t,e)!==null}function Uv(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(i=>Av.has(i)?!1:!Pv.some(s=>i.endsWith(s))||e.has(i))}function Hv(t,{functionName:e="",declaredTypes:n=new Set}={}){const i=Ov(t,e),r=Uv(i,n);if(r.length===0)return null;const[s]=r;let o;return n.has(s)?o=`uses Code File type "${s}", which FlutterFlow cannot process as an Action Return Value`:i===s?o="is not a FlutterFlow Action Return Value":o=`uses type "${s}", which is not a FlutterFlow Action Return Value`,`CustomAction return type "${i}" ${o}. Return JSON (Future) or an existing FlutterFlow Data Type (*Struct) instead.`}function Wv(t,e={}){const n=[],i=t.fileName||"",r=t.code||"";if(Cv.has(t.artifactType)||n.push(xt(t,"error",`Unsupported artifact type "${t.artifactType}".`)),i.endsWith(".dart")||n.push(xt(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!r.trim())return n.push(xt(t,"warning","Generated artifact has no Dart code yet.")),n;if(t.artifactType==="CustomWidget"){/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)||n.push(xt(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const s of Lv(r))n.push(xt(t,s.severity,s.message))}if(t.artifactType==="CustomAction"&&!jv(r,t.artifactName)&&n.push(xt(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const s=e.declaredTypes||new Set(As(r)),o=Hv(r,{functionName:t.artifactName,declaredTypes:s});o&&n.push(xt(t,"error",o));const a=Dv(i,r,t.artifactName);a&&n.push(xt(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)&&n.push(xt(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const s=Bv(i,r);s&&n.push(xt(t,"info",s))}return n}function zv(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],n=new Set(e.flatMap(s=>As(s.code||""))),i=e.flatMap(s=>Wv(s,{declaredTypes:n})),r=e.map(s=>({artifactId:s.id,fileName:s.fileName,pathHint:Cu[s.artifactType]||Cu.CodeFile}));return{valid:i.every(s=>s.severity!=="error"),findings:i,deployHints:r}}const Fu="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function Ru(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function qv(t=""){const e=t.indexOf(Fu);return e===-1?t:t.slice(e+Fu.length).replace(/^\s*\n/,"")}const Vv=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function Gv(t="",e=""){const n=qv(t),i=new Set((e.match(/^\s*import .*$/gm)||[]).map(Ru).filter(Boolean)),r=n.split(` +`).filter(s=>{const o=Ru(s);return o===null||!i.has(o)?!0:!Vv.test(s)}).join(` +`).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+r}const Kv=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations"]);function ah(t){let e="",n=0;for(;n{const i=n.name||n.package;if(!i||i==="flutter")return e;const r=n.versionRequired||n.required;return e[i]=r&&n.version||"",e},{})}function Qv(t){const e=new Map,n=new Map,i=[];for(const r of t)e.has(r.fileName)?i.push(`Duplicate deploy file name "${r.fileName}" for artifacts "${e.get(r.fileName)}" and "${r.artifactId}".`):e.set(r.fileName,r.artifactId),n.has(r.path)?i.push(`Duplicate deploy path "${r.path}" for artifacts "${n.get(r.path)}" and "${r.artifactId}".`):n.set(r.path,r.artifactId);return i}function e_(t,e={}){const n=Array.isArray(t?.artifacts)?t.artifacts:[],r=(e.selectedArtifactIds||t?.deployOrder||n.map(f=>f.id)).map(f=>n.find(p=>p.id===f)).filter(Boolean),s=[...t?.warnings||[]];let o=[];r.forEach(f=>{const p=Xv(f),g=f.fixedCode||f.code||"",m=f.codeType||Jv[f.artifactType]||Xe.OTHER;g.trim()||s.push(`${f.artifactName||f.id} has no generated code.`),o.push({artifactId:f.id,artifactName:f.artifactName,artifactType:f.artifactType,fileName:p,content:g,type:m,path:f.deployPath||Zv(p,m),deployPath:f.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((f,p)=>({entry:f,index:p})).filter(({entry:f})=>f.type===Xe.FUNCTION&&f.path===a);if(l.length>1){const f=l[0],p={...f.entry,artifactId:l.map(({entry:m})=>m.artifactId).join("+"),artifactName:f.entry.artifactName,content:l.map(({entry:m})=>`// ${m.artifactId} ${m.content}`).join(` -`)},g=new Set(l.slice(1).map(({index:m})=>m));o=o.filter((m,v)=>!g.has(v)),o[f.index]=p}const u={...Tu(t?.dependencies),...r.reduce((f,p)=>({...f,...Tu(p.dependencies)}),{})},c={};r.forEach(f=>{wl(f.code||"").forEach(p=>{p in u||(c[p]="")})});const d={...c,...u},h=Xv(o);return{bundleId:t?.id||"bundle-current",title:t?.title||"Generated artifact bundle",fileEntries:o,dependencies:d,relationships:t?.relationships||[],warnings:s,errors:h}}function e_(t){return String(t||"").match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/)?.[1]}function t_(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 n_(t,e){const i=[t_(t),e_(e.content),e.artifactName].find(r=>/^[A-Z][A-Za-z0-9_]*$/.test(String(r||"")));if(!i)throw new Error(`Cannot derive a FlutterFlow custom class name for ${t}.`);return i}function i_(t,e=new Map){const n=[];for(const[i,r]of t.entries())r.type!=="C"||e.has(r.path)||n.push({artifactId:r.artifactId||i,className:n_(i,r),content:r.content,fileName:i,path:r.path});return n}function r_(t,e){const n=new Set(e.map(i=>i.path));return new Map(Array.from(t.entries()).filter(([,i])=>!n.has(i.path)))}const $u={pass:0,warning:1,fail:2},s_=["manualActions"];function rt(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Vt(...t){for(const e of t){if(typeof e=="string"&&e.trim())return e.trim();if(Array.isArray(e)&&e.length>0){const n=e.filter(i=>typeof i=="string").join(` -`);if(n)return n}}return""}function kt(t){return t==null?[]:Array.isArray(t)?t:[t]}function o_(t){const e=rt(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const n=Number(e);if(Number.isFinite(n))return Mu(n);const i=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return i?Mu(Number(i[1])):null}function Mu(t){return t>=0&&t<=100?t:null}function at(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function bl(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 Ra(...t){return t.filter(Boolean).reduce((e,n)=>$u[n]>$u[e]?n:e,"pass")}function ah(t,e="warning",n="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:n};const i=rt(t),r=Vt(i.message,i.title,i.issue,i.description,i.summary);return r?{severity:bl(i.severity||i.status||i.level)||e,message:r,suggestion:Vt(i.suggestion,i.fix,i.recommendation,i.action),source:i.source||n}:null}function Ta(t,e="review"){const n=rt(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([r,s])=>kt(n[r]).map(o=>ah(o,s,e)).filter(Boolean))}function a_(t,e,n=null){if(typeof t=="string")return{id:`${n||"bundle"}-manual-${e+1}`,title:t,detail:"",location:"",timing:"unspecified",artifactId:n,source:"Code Review"};const i=rt(t),r=Vt(i.title,i.action,i.step,i.message,i.name,i.description);return r?{id:i.id||`${n||"bundle"}-manual-${e+1}`,title:r,detail:Vt(i.detail,i.instructions,i.description),location:Vt(i.location,i.flutterFlowPath,i.path),timing:Vt(i.timing,i.phase)||"unspecified",artifactId:n,source:Vt(i.source)||"Code Review"}:null}function $a(t,e=null){const n=rt(t);return s_.flatMap(i=>kt(n[i])).map((i,r)=>a_(i,r,e)).filter(Boolean)}function l_(t){let e=typeof t=="string"?Pa(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const n=rt(e);typeof n.content=="string"&&(e=Pa(n.content)||e);const i=rt(e),r=rt(i.reviewResult||i.codeReview||i.result);return{rawText:"",root:Object.keys(r).length?r:i}}function c_(t,e){const n=[e.id,e.fileName,e.artifactName].map(at);return t.find(i=>{const r=rt(i);return[r.id,r.fileName,r.artifactName,r.name].map(at).some(s=>s&&n.includes(s))})||null}function u_(t,e){return kt(t?.metadata?.compatibility?.deployHints).find(r=>at(r?.artifactId)===at(e.id)||at(r?.fileName)===at(e.fileName))?.pathHint||""}function d_(t,e){return kt(t?.relationships).filter(n=>at(n?.from)===at(e.id)||at(n?.to)===at(e.id))}function f_(t,e){return kt(t?.metadata?.compatibility?.findings).filter(n=>!n?.artifactId||at(n.artifactId)===at(e.id)).map(n=>ah(n,"warning","Compatibility check")).filter(Boolean)}function h_(t,e,n,i){const r=c_(e,n),s=rt(r?.review||r||n.review),o=Object.keys(s).length>0,a=[...Ta(s),...f_(t,n)],l=$a(s,n.id),u=bl(s.status||s.verdict||s.outcome||s.result),c=a.length?Ra(...a.map(h=>h.severity)):null,d=Ra(u,c,o?null:"warning");return{...n,index:i,status:d,statusReason:o?Vt(s.summary,s.overview,s.assessment,s.conclusion)||(a.length?`${a.length} review finding${a.length===1?"":"s"}`:"No file-level findings"):"No file-level verdict was returned",reviewComplete:o,findings:a,manualSteps:l,fixedSource:typeof s.fixedSource=="string"&&s.fixedSource.trim()?s.fixedSource.trim():null,pathHint:u_(t,n),relationships:d_(t,n)}}function p_({status:t,score:e,artifactPresentations:n,manualSteps:i}){const r=n.length;if(r===0&&i.length===0)return e==null?"Code review returned no overall summary and no score.":`Reviewed bundle with score ${e}/100.`;const s=n.reduce((a,l)=>(a[l.status]+=1,a),{pass:0,warning:0,fail:0}),o=[];return t&&o.push(`Overall verdict: ${t}.`),r&&o.push(`${r} artifact${r===1?"":"s"}: ${s.pass} pass, ${s.warning} warn, ${s.fail} fail.`),i.length&&o.push(`Do before deploy: ${i.map(a=>a.title).join("; ")}.`),e==null&&o.push("No numeric score (0-100) was returned."),o.join(" ")}function g_({bundle:t,reviewResult:e}){const n=rt(t),i=kt(n.artifacts),{root:r,rawText:s}=l_(e),o=[r.bundleReview,r.overallReview,r.overall,r.bundleSummary,r.summaryReview,r.review].map(rt).find(S=>Object.keys(S).length)||{},a=kt(r.artifacts||r.files||r.reviews),l=i.map((S,_)=>h_(n,a,S,_)),u=Ta(r),d=[...Ta(o),...u],h=[...$a(o),...$a(r),...l.flatMap(S=>S.manualSteps)].filter((S,_,b)=>b.findIndex(k=>k.title===S.title&&k.artifactId===S.artifactId)===_),f=bl(o.status||o.verdict||o.overallStatus||r.status||r.verdict||r.overallStatus||r.outcome),p=Ra(f,...d.map(S=>S.severity),...l.map(S=>S.status)),g=o.score??r.score??r.overallScore??s,m=o_(g),v=Vt(o.headline,o.summary,o.executiveSummary,o.overview,o.assessment,o.conclusion,r.overallSummary,r.headline,r.summary,r.executiveSummary,r.overview,r.assessment,r.conclusion,s)||p_({status:p,score:m,artifactPresentations:l,manualSteps:h}),E=l.reduce((S,_)=>(S[_.status]+=1,S),{pass:0,warning:0,fail:0});return{title:n.title||"Generated artifact bundle",description:n.description||"",status:p,score:m,summary:v,findings:d,manualSteps:h,artifacts:l,counts:E,reviewCoverage:{reviewed:l.filter(S=>S.reviewComplete).length,total:l.length},deployOrder:kt(n.deployOrder),relationships:kt(n.relationships),warnings:kt(n.warnings),compatibility:rt(n.metadata?.compatibility)}}const m_=/^\uFEFF/;function Ci(t){let e=0,n=t.length;for(;ee&&!t[n-1].trim();)n--;return t.slice(e,n).join(` -`)}function v_(t){const e=String(t??"").replace(m_,"");if(!e.trim())return"";const n=e.split(` +`)},g=new Set(l.slice(1).map(({index:m})=>m));o=o.filter((m,v)=>!g.has(v)),o[f.index]=p}const u={...Tu(t?.dependencies),...r.reduce((f,p)=>({...f,...Tu(p.dependencies)}),{})},c={};r.forEach(f=>{wl(f.code||"").forEach(p=>{p in u||(c[p]="")})});const d={...c,...u},h=Qv(o);return{bundleId:t?.id||"bundle-current",title:t?.title||"Generated artifact bundle",fileEntries:o,dependencies:d,relationships:t?.relationships||[],warnings:s,errors:h}}function t_(t){return String(t||"").match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/)?.[1]}function n_(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 i_(t,e){const i=[n_(t),t_(e.content),e.artifactName].find(r=>/^[A-Z][A-Za-z0-9_]*$/.test(String(r||"")));if(!i)throw new Error(`Cannot derive a FlutterFlow custom class name for ${t}.`);return i}function r_(t,e=new Map){const n=[];for(const[i,r]of t.entries())r.type!=="C"||e.has(r.path)||n.push({artifactId:r.artifactId||i,className:i_(i,r),content:r.content,fileName:i,path:r.path});return n}function s_(t,e){const n=new Set(e.map(i=>i.path));return new Map(Array.from(t.entries()).filter(([,i])=>!n.has(i.path)))}const $u={pass:0,warning:1,fail:2},o_=["manualActions"];function st(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Vt(...t){for(const e of t){if(typeof e=="string"&&e.trim())return e.trim();if(Array.isArray(e)&&e.length>0){const n=e.filter(i=>typeof i=="string").join(` +`);if(n)return n}}return""}function kt(t){return t==null?[]:Array.isArray(t)?t:[t]}function a_(t){const e=st(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const n=Number(e);if(Number.isFinite(n))return Mu(n);const i=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return i?Mu(Number(i[1])):null}function Mu(t){return t>=0&&t<=100?t:null}function lt(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function bl(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 Ra(...t){return t.filter(Boolean).reduce((e,n)=>$u[n]>$u[e]?n:e,"pass")}function lh(t,e="warning",n="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:n};const i=st(t),r=Vt(i.message,i.title,i.issue,i.description,i.summary);return r?{severity:bl(i.severity||i.status||i.level)||e,message:r,suggestion:Vt(i.suggestion,i.fix,i.recommendation,i.action),source:i.source||n}:null}function Ta(t,e="review"){const n=st(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([r,s])=>kt(n[r]).map(o=>lh(o,s,e)).filter(Boolean))}function l_(t,e,n=null){if(typeof t=="string")return{id:`${n||"bundle"}-manual-${e+1}`,title:t,detail:"",location:"",timing:"unspecified",artifactId:n,source:"Code Review"};const i=st(t),r=Vt(i.title,i.action,i.step,i.message,i.name,i.description);return r?{id:i.id||`${n||"bundle"}-manual-${e+1}`,title:r,detail:Vt(i.detail,i.instructions,i.description),location:Vt(i.location,i.flutterFlowPath,i.path),timing:Vt(i.timing,i.phase)||"unspecified",artifactId:n,source:Vt(i.source)||"Code Review"}:null}function $a(t,e=null){const n=st(t);return o_.flatMap(i=>kt(n[i])).map((i,r)=>l_(i,r,e)).filter(Boolean)}function c_(t){let e=typeof t=="string"?Pa(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const n=st(e);typeof n.content=="string"&&(e=Pa(n.content)||e);const i=st(e),r=st(i.reviewResult||i.codeReview||i.result);return{rawText:"",root:Object.keys(r).length?r:i}}function u_(t,e){const n=[e.id,e.fileName,e.artifactName].map(lt);return t.find(i=>{const r=st(i);return[r.id,r.fileName,r.artifactName,r.name].map(lt).some(s=>s&&n.includes(s))})||null}function d_(t,e){return kt(t?.metadata?.compatibility?.deployHints).find(r=>lt(r?.artifactId)===lt(e.id)||lt(r?.fileName)===lt(e.fileName))?.pathHint||""}function f_(t,e){return kt(t?.relationships).filter(n=>lt(n?.from)===lt(e.id)||lt(n?.to)===lt(e.id))}function h_(t,e){return kt(t?.metadata?.compatibility?.findings).filter(n=>!n?.artifactId||lt(n.artifactId)===lt(e.id)).map(n=>lh(n,"warning","Compatibility check")).filter(Boolean)}function p_(t,e,n,i){const r=u_(e,n),s=st(r?.review||r||n.review),o=Object.keys(s).length>0,a=[...Ta(s),...h_(t,n)],l=$a(s,n.id),u=bl(s.status||s.verdict||s.outcome||s.result),c=a.length?Ra(...a.map(h=>h.severity)):null,d=Ra(u,c,o?null:"warning");return{...n,index:i,status:d,statusReason:o?Vt(s.summary,s.overview,s.assessment,s.conclusion)||(a.length?`${a.length} review finding${a.length===1?"":"s"}`:"No file-level findings"):"No file-level verdict was returned",reviewComplete:o,findings:a,manualSteps:l,fixedSource:typeof s.fixedSource=="string"&&s.fixedSource.trim()?s.fixedSource.trim():null,pathHint:d_(t,n),relationships:f_(t,n)}}function g_({status:t,score:e,artifactPresentations:n,manualSteps:i}){const r=n.length;if(r===0&&i.length===0)return e==null?"Code review returned no overall summary and no score.":`Reviewed bundle with score ${e}/100.`;const s=n.reduce((a,l)=>(a[l.status]+=1,a),{pass:0,warning:0,fail:0}),o=[];return t&&o.push(`Overall verdict: ${t}.`),r&&o.push(`${r} artifact${r===1?"":"s"}: ${s.pass} pass, ${s.warning} warn, ${s.fail} fail.`),i.length&&o.push(`Do before deploy: ${i.map(a=>a.title).join("; ")}.`),e==null&&o.push("No numeric score (0-100) was returned."),o.join(" ")}function m_({bundle:t,reviewResult:e}){const n=st(t),i=kt(n.artifacts),{root:r,rawText:s}=c_(e),o=[r.bundleReview,r.overallReview,r.overall,r.bundleSummary,r.summaryReview,r.review].map(st).find(S=>Object.keys(S).length)||{},a=kt(r.artifacts||r.files||r.reviews),l=i.map((S,_)=>p_(n,a,S,_)),u=Ta(r),d=[...Ta(o),...u],h=[...$a(o),...$a(r),...l.flatMap(S=>S.manualSteps)].filter((S,_,b)=>b.findIndex(k=>k.title===S.title&&k.artifactId===S.artifactId)===_),f=bl(o.status||o.verdict||o.overallStatus||r.status||r.verdict||r.overallStatus||r.outcome),p=Ra(f,...d.map(S=>S.severity),...l.map(S=>S.status)),g=o.score??r.score??r.overallScore??s,m=a_(g),v=Vt(o.headline,o.summary,o.executiveSummary,o.overview,o.assessment,o.conclusion,r.overallSummary,r.headline,r.summary,r.executiveSummary,r.overview,r.assessment,r.conclusion,s)||g_({status:p,score:m,artifactPresentations:l,manualSteps:h}),E=l.reduce((S,_)=>(S[_.status]+=1,S),{pass:0,warning:0,fail:0});return{title:n.title||"Generated artifact bundle",description:n.description||"",status:p,score:m,summary:v,findings:d,manualSteps:h,artifacts:l,counts:E,reviewCoverage:{reviewed:l.filter(S=>S.reviewComplete).length,total:l.length},deployOrder:kt(n.deployOrder),relationships:kt(n.relationships),warnings:kt(n.warnings),compatibility:st(n.metadata?.compatibility)}}const v_=/^\uFEFF/;function Ci(t){let e=0,n=t.length;for(;ee&&!t[n-1].trim();)n--;return t.slice(e,n).join(` +`)}function __(t){const e=String(t??"").replace(v_,"");if(!e.trim())return"";const n=e.split(` `),i=c=>{const d=c.trim();return/^`{3,}[A-Za-z0-9+#_.-]*$/.test(d)?c.length-c.trimStart().length:-1};let r=0,s=-1;const o=[];{let c=0;for(let d=0;d=0&&(r++,s<0&&(s=d),o.push(c+h)),c+=n[d].length+1}}if(r===0)return Ci(n);{const c=Ma(e);if(!c.error&&o.every(h=>Nu(h,c.commentAndStringRanges)))return Ci(n)}if(r===1){const c=Ci(n.slice(0,s)),d=Ci(n.slice(s+1));return d.length>=c.length?d:c}const a=[];let l=null;for(let c=0;cc.length>0);return u.length===0?"":u.join(` -`)}function __(t){return String(t??"").replace(/\/\*[\s\S]*?\*\//g," ").replace(/\/\/[^\n]*/g,"").replace(/'''[\s\S]*?'''/g,'""').replace(/"""[\s\S]*?"""/g,'""').replace(/'(?:\\.|[^'\\\n])*'/g,'""').replace(/"(?:\\.|[^"\\\n])*"/g,'""')}function lh(t){const e=__(t);return Array.from(e.matchAll(/class\s+([A-Z]\w*)\s+extends\s+[A-Za-z_]\w*Widget\b/g),n=>n[1])}function ch(t){return`${yl(t)}.dart`}function y_(t){return vl(t,"W")}const Lu={"(":")","[":"]","{":"}"},w_={")":"(","]":"[","}":"{"},b_=/[A-Za-z0-9_]/;function Ma(t){const e=[{kind:"code",opener:null,openedLine:0}],n=[];let i=1,r=0;const s=(c,d)=>{(c===` +`)}function y_(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 ch(t){const e=y_(t);return Array.from(e.matchAll(/class\s+([A-Z]\w*)\s+extends\s+[A-Za-z_]\w*Widget\b/g),n=>n[1])}function uh(t){return`${yl(t)}.dart`}function w_(t){return vl(t,"W")}const Lu={"(":")","[":"]","{":"}"},b_={")":"(","]":"[","}":"{"},E_=/[A-Za-z0-9_]/;function Ma(t){const e=[{kind:"code",opener:null,openedLine:0}],n=[];let i=1,r=0;const s=(c,d)=>{(c===` `||c==="\r"&&d!==` `)&&i++};let o=null;const a=()=>{for(const c of e)(c.kind==="string"||c.kind==="block-comment"||c.kind==="line-comment")&&n.push({start:c.startIndex,end:t.length})};for(;r0?t[r-1]:"",p=r>1?t[r-2]:"",g=(f==="r"||f==="R")&&!b_.test(p);e.push({kind:"string",quote:c,triple:h,raw:g,startIndex:r,openedLine:i}),r+=h?3:1;continue}if(Lu[c]){e.push({kind:"code",opener:c,openedLine:i}),r++;continue}if(w_[c]){if(d.interpolation&&c==="}"){e.pop(),r++;continue}if(d.opener&&Lu[d.opener]===c){e.pop(),r++;continue}return d.opener?(a(),{error:o??`line ${i}: "${c}" closes nothing - "${d.opener}" opened on line ${d.openedLine} is still open`,commentAndStringRanges:n}):(a(),{error:o??`line ${i}: unexpected "${c}" with no matching opener`,commentAndStringRanges:n})}s(c,t[r+1]),r++}a();let l=e.length-1;for(;l>0&&e[l].kind==="line-comment";)l--;let u=o;if(!u){const c=e[l];if(!(c.kind==="code"&&!c.opener&&!c.interpolation))if(c.kind==="string")u=`unclosed ${c.triple?"triple-quoted ":""}string starting on line ${c.openedLine} was never closed`;else if(c.kind==="block-comment")u=`unterminated /* comment starting on line ${c.openedLine}`;else if(c.interpolation){const d=e.findLast(f=>f.opener);u=`unclosed "\${" expression${d?` opened on line ${d.openedLine}`:""} was never closed`}else u=`"${c.opener}" opened on line ${c.openedLine} is never closed`}return{error:u,commentAndStringRanges:n}}function E_(t){return Ma(String(t??"")).error}function Nu(t,e){return e.some(({start:n,end:i})=>t>=n&&ttypeof n=="string"?n:n?.errorMessage).filter(Boolean);return e.length>0?e.join("; "):JSON.stringify(t)}return t&&typeof t=="object"?t.errorMessage||JSON.stringify(t):String(t??"")}const S_=["gmail.com","googlemail.com","outlook.com","hotmail.com","live.com","msn.com"],x_="MAGIC_LINK_SENT",I_="PLUS_ALIAS_REJECTED",k_="Please enter your primary email address. Plus aliases (such as {email}) are not allowed for {domain} accounts.",Ps={allowlistedDomains:S_,successCode:x_,validationCode:I_,messageTemplate:k_},C_=new Set(Ps.allowlistedDomains),A_=Ps.successCode,uh=Ps.validationCode;function Fs(t){return typeof t=="string"?t.trim():""}function P_(t){const e=Fs(t),n=e.lastIndexOf("@");if(n<=0||n===e.length-1)return!1;const i=e.slice(0,n),r=e.slice(n+1).toLowerCase();return C_.has(r)?i.includes("+"):!1}function F_(t,e){return Ps.messageTemplate.replaceAll("{email}",t).replaceAll("{domain}",e)}function dh(t){if(!P_(t))return null;const e=Fs(t),n=e.lastIndexOf("@"),i=e.slice(n+1).toLowerCase();return F_(e,i)}function fh(t,e){return t?.code===uh?t.message||dh(e)||"Please enter your primary email address.":t?.code===A_||!t?.code?`Check your email — we sent a link to ${Fs(e)}`:t.message||"Something went wrong. Please try again."}const R_="ccc_auth_session",T_="ccc_subscription",$_=Object.freeze(["hasSeenWalkthrough"]);function M_(t){const e=[];for(const n of $_)t.getItem(n)!==null&&(t.removeItem(n),e.push(n));return e}function L_(){return[R_,T_]}function N_({storage:t,onIdentityChanged:e,onPlanChanged:n}){for(const i of L_())t.removeItem(i);typeof e=="function"&&e(),typeof n=="function"&&n()}function O_({sendLink:t,getEmail:e,onState:n}){let i=!1;return async function(){if(i)return{status:"busy"};i=!0;let s;try{n({status:"pending",error:null});const o=await t(e());return s={status:"sent",data:o},n({status:"sent",data:o}),s}catch(o){return s={status:"error",error:o},n({status:"error",error:o}),s}finally{i=!1}}}const B_=/^dependencies\s*:\s*(?:#.*)?$/,D_=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function Rs(t){const e=t.match(D_);return e?e[1]??e[2]??e[3]:null}function ar(t){const e=t.trim();return e===""||e.startsWith("#")}function fi(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function Sl(t,e){const n=t.findIndex(s=>e.test(s));if(n===-1)return null;let i=n,r=null;for(let s=n+1;s=0.0.0"}`}function W_(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([u])=>u&&u!=="flutter");if(i.length===0)return{yaml:n,added:[],alreadyPresent:[]};const r=n.split(` -`),s=new Set(ph(n)),o=[],a=[];for(const[u,c]of i)s.has(u)?a.push(u):(o.push([u,c]),s.add(u));if(o.length===0)return{yaml:n,added:[],alreadyPresent:a};const l=xl(r);if(l){const u=o.map(([c,d])=>Ou(l.childIndent,c,d));r.splice(l.endIndex,0,...u)}else r.length>0&&r[r.length-1].trim()!==""&&r.push(""),r.push("dependencies:"),o.forEach(([u,c])=>{r.push(Ou(" ",u,c))});return{yaml:r.join(` +`){n.push({start:d.startIndex,end:r}),o??=`line ${i}: string starting on line ${d.openedLine} is never closed`,e.pop();continue}if(!d.raw&&c==="\\"){s(t[r+1]??"",t[r+2]??""),r+=2;continue}if(!d.raw&&c==="$"&&t[r+1]==="{"){e.push({kind:"code",opener:null,interpolation:!0}),r+=2;continue}const h=d.triple?3:1;if(c===d.quote&&t.slice(r,r+h)===d.quote.repeat(h)){n.push({start:d.startIndex,end:r+h}),e.pop(),r+=h;continue}s(c,t[r+1]),r++;continue}if(c==="/"&&t[r+1]==="/"){e.push({kind:"line-comment",startIndex:r}),r+=2;continue}if(c==="/"&&t[r+1]==="*"){e.push({kind:"block-comment",startIndex:r,openedLine:i,depth:1}),r+=2;continue}if(c==="'"||c==='"'){const h=t.slice(r,r+3)===c.repeat(3),f=r>0?t[r-1]:"",p=r>1?t[r-2]:"",g=(f==="r"||f==="R")&&!E_.test(p);e.push({kind:"string",quote:c,triple:h,raw:g,startIndex:r,openedLine:i}),r+=h?3:1;continue}if(Lu[c]){e.push({kind:"code",opener:c,openedLine:i}),r++;continue}if(b_[c]){if(d.interpolation&&c==="}"){e.pop(),r++;continue}if(d.opener&&Lu[d.opener]===c){e.pop(),r++;continue}return d.opener?(a(),{error:o??`line ${i}: "${c}" closes nothing - "${d.opener}" opened on line ${d.openedLine} is still open`,commentAndStringRanges:n}):(a(),{error:o??`line ${i}: unexpected "${c}" with no matching opener`,commentAndStringRanges:n})}s(c,t[r+1]),r++}a();let l=e.length-1;for(;l>0&&e[l].kind==="line-comment";)l--;let u=o;if(!u){const c=e[l];if(!(c.kind==="code"&&!c.opener&&!c.interpolation))if(c.kind==="string")u=`unclosed ${c.triple?"triple-quoted ":""}string starting on line ${c.openedLine} was never closed`;else if(c.kind==="block-comment")u=`unterminated /* comment starting on line ${c.openedLine}`;else if(c.interpolation){const d=e.findLast(f=>f.opener);u=`unclosed "\${" expression${d?` opened on line ${d.openedLine}`:""} was never closed`}else u=`"${c.opener}" opened on line ${c.openedLine} is never closed`}return{error:u,commentAndStringRanges:n}}function S_(t){return Ma(String(t??"")).error}function Nu(t,e){return e.some(({start:n,end:i})=>t>=n&&ttypeof n=="string"?n:n?.errorMessage).filter(Boolean);return e.length>0?e.join("; "):JSON.stringify(t)}return t&&typeof t=="object"?t.errorMessage||JSON.stringify(t):String(t??"")}const x_=["gmail.com","googlemail.com","outlook.com","hotmail.com","live.com","msn.com"],I_="MAGIC_LINK_SENT",k_="PLUS_ALIAS_REJECTED",C_="Please enter your primary email address. Plus aliases (such as {email}) are not allowed for {domain} accounts.",Ps={allowlistedDomains:x_,successCode:I_,validationCode:k_,messageTemplate:C_},A_=new Set(Ps.allowlistedDomains),P_=Ps.successCode,dh=Ps.validationCode;function Fs(t){return typeof t=="string"?t.trim():""}function F_(t){const e=Fs(t),n=e.lastIndexOf("@");if(n<=0||n===e.length-1)return!1;const i=e.slice(0,n),r=e.slice(n+1).toLowerCase();return A_.has(r)?i.includes("+"):!1}function R_(t,e){return Ps.messageTemplate.replaceAll("{email}",t).replaceAll("{domain}",e)}function fh(t){if(!F_(t))return null;const e=Fs(t),n=e.lastIndexOf("@"),i=e.slice(n+1).toLowerCase();return R_(e,i)}function hh(t,e){return t?.code===dh?t.message||fh(e)||"Please enter your primary email address.":t?.code===P_||!t?.code?`Check your email — we sent a link to ${Fs(e)}`:t.message||"Something went wrong. Please try again."}const T_="ccc_auth_session",$_="ccc_subscription",M_=Object.freeze(["hasSeenWalkthrough"]);function L_(t){const e=[];for(const n of M_)t.getItem(n)!==null&&(t.removeItem(n),e.push(n));return e}function N_(){return[T_,$_]}function O_({storage:t,onIdentityChanged:e,onPlanChanged:n}){for(const i of N_())t.removeItem(i);typeof e=="function"&&e(),typeof n=="function"&&n()}function B_({sendLink:t,getEmail:e,onState:n}){let i=!1;return async function(){if(i)return{status:"busy"};i=!0;let s;try{n({status:"pending",error:null});const o=await t(e());return s={status:"sent",data:o},n({status:"sent",data:o}),s}catch(o){return s={status:"error",error:o},n({status:"error",error:o}),s}finally{i=!1}}}const D_=/^dependencies\s*:\s*(?:#.*)?$/,j_=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function Rs(t){const e=t.match(j_);return e?e[1]??e[2]??e[3]:null}function ar(t){const e=t.trim();return e===""||e.startsWith("#")}function fi(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function Sl(t,e){const n=t.findIndex(s=>e.test(s));if(n===-1)return null;let i=n,r=null;for(let s=n+1;s=0.0.0"}`}function z_(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([u])=>u&&u!=="flutter");if(i.length===0)return{yaml:n,added:[],alreadyPresent:[]};const r=n.split(` +`),s=new Set(gh(n)),o=[],a=[];for(const[u,c]of i)s.has(u)?a.push(u):(o.push([u,c]),s.add(u));if(o.length===0)return{yaml:n,added:[],alreadyPresent:a};const l=xl(r);if(l){const u=o.map(([c,d])=>Ou(l.childIndent,c,d));r.splice(l.endIndex,0,...u)}else r.length>0&&r[r.length-1].trim()!==""&&r.push(""),r.push("dependencies:"),o.forEach(([u,c])=>{r.push(Ou(" ",u,c))});return{yaml:r.join(` `),added:o.map(([u])=>u),alreadyPresent:a}}function q_(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([l])=>l&&l!=="flutter");if(i.length===0)return{yaml:n,overridden:[],skipped:[]};const r=n.split(` -`),s=$s(n),o=[],a=[];for(const[l,u]of i){const c=s.get(l);if(!c||!c.isScalar||!String(u||"").trim()){a.push(l);continue}const d=" ".repeat(fi(r[c.lineIndex]));r[c.lineIndex]=`${d}${l}: ${mh(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:r.join(` -`),overridden:o,skipped:a}}function vh(t){const e=String(t||""),n=[];return e.trim()?(/^name:\s*\S+/m.test(e)||n.push("pubspec.yaml missing name field"),xl(e.split(` -`))||n.push("pubspec.yaml missing dependencies section"),ph(e).includes("flutter")||n.push("pubspec.yaml missing Flutter SDK dependency"),{valid:n.length===0,errors:n}):(n.push("pubspec.yaml is empty"),{valid:!1,errors:n})}const z_=">=3.0.0 <4.0.0";function La(t){const e=String(t||"").trim(),n=e[0];return n!=="'"&&n!=='"'||e[e.length-1]!==n?e:e.slice(1,-1).replaceAll(`${n}${n}`,n)}function V_(t=""){const e=Kv(t).filter(n=>!n.startsWith("dart:")&&!n.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function Bu(t,e,n){const i=[];for(const[r,s]of t){if(s.isScalar){e[r]=La(s.constraint);continue}if(s.sourceKey==="sdk"){n.add(r);continue}if(s.sourceKey===null&&s.version){e[r]=La(s.version);continue}i.push(r)}return i}function G_(t){const e=new Set,n={},i={},r=Bu($s(t),n,e);r.push(...Bu(U_(t,"dependency_overrides"),i,e));const s=new Set([...Object.keys(n),...e]),{sdk:o}=gh(t);return{sdkConstraint:La(o)||z_,dependencies:n,overrides:i,sdkPackages:[...e].sort(),availablePackages:s,unrepresentable:r}}function K_(t,e,n){return e.length>0?`${t} imports ${e.join(", ")}, which FlutterFlow only generates once the app is built, so it could not be compiled before the deploy.`:`${t} imports ${n.join(", ")}, which your project's pubspec.yaml does not declare with a version constraint, so it could not be compiled before the deploy.`}function Y_(t,e){const{sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s,availablePackages:o,unrepresentable:a}=G_(e),l={sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s},u=[],c=[],d=a.map(h=>`Your project declares ${h} from a source that cannot be reproduced outside it, so the pre-deploy compile check runs against a scratch package graph that omits ${h}. Classes that do not import ${h} directly are still checked, but against that reduced graph, so their transitive package resolution may differ from your project's and the check is approximate for them.`);for(const h of t){const{className:f,content:p}=h,g=wl(p),m=g.filter(S=>a.includes(S));if(m.length>0){c.push({className:f,reason:`${f} was not compiled before deploying: it imports ${m.join(", ")}, which your project declares from a source that cannot be reproduced outside it, so package resolution could not be matched exactly.`});continue}const{unresolvableImports:v}=V_(p),E=g.filter(S=>!o.has(S));if(v.length>0||E.length>0){c.push({className:f,reason:K_(f,v,E)});continue}u.push({fileName:`${yl(f)}.dart`,content:p})}return{manifest:l,sources:u,skipped:c,approximate:d}}function Du(t,e){const n=`${t}${e}`.split(` -`),i=n.pop()??"",r=[];for(const s of n){const o=_h(s);o&&r.push(o)}return{events:r,buffer:i}}function J_(t){const e=_h(t);return e?[e]:[]}function _h(t){const e=t.trim();if(!e)return null;try{const n=JSON.parse(e);return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}const Xe=Object.freeze({COMMITTED:"committed",PARTIAL:"partial",FAILED:"failed",UNCONFIRMED:"unconfirmed"}),yh=12e4;function wh(t){return t?.unconfirmed===!0||t?.outcome===Xe.UNCONFIRMED?Xe.UNCONFIRMED:t?.partial===!0||t?.outcome===Xe.PARTIAL?Xe.PARTIAL:t?.success===!0?Xe.COMMITTED:Xe.FAILED}class lt extends Error{constructor(e){super(e),this.name="UnconfirmedDeployError",this.outcome=Xe.UNCONFIRMED}}function ju({httpStatus:t}={}){return new lt(`Every FlutterFlow sync endpoint lost its response or ended in a server error${t?` (last: HTTP ${t})`:""} — neither can prove the push was refused, so it may already have been applied. Open the FlutterFlow project to reconcile before retrying.`)}async function Z_(t,e={}){const{onPhase:n,onLog:i}=e;let r=null,s="";const o=l=>{if(l.event==="phase"){l.message&&n&&n(l.message);return}if(l.event==="log"){l.message&&i&&i(l.message);return}r=l};let a=null;try{if(t.body?.getReader){const l=t.body.getReader(),u=new TextDecoder;for(;;){const{done:c,value:d}=await l.read();if(c)break;const h=Du(s,u.decode(d,{stream:!0}));s=h.buffer,h.events.forEach(o)}}else{const l=Du("",await t.text());s=l.buffer,l.events.forEach(o)}}catch(l){a=l}return J_(s).forEach(o),r?{...r,success:r.success===!0||r.success===void 0&&t.ok,finalResultReceived:!0}:{success:!1,finalResultReceived:!1,httpRejected:!t.ok,httpStatus:t.status,error:t.ok?a?"The connection to the FlutterFlow deploy runner dropped before it reported a result.":"The FlutterFlow deploy runner closed the connection before it finished.":`FlutterFlow custom class provisioning failed (HTTP ${t.status}).`}}function X_(t){return t?.finalResultReceived?wh(t):t?.httpRejected?Xe.FAILED:Xe.UNCONFIRMED}function Q_(){let t=document.getElementById("fx-grid");if(!t)return null;const e=window.matchMedia("(prefers-reduced-motion: reduce)"),n=window.matchMedia("(pointer: none)");let i=t.getContext("webgl2",{alpha:!0,antialias:!1,depth:!1,stencil:!1,premultipliedAlpha:!0,powerPreference:"low-power"}),r=i?null:t.getContext("2d");if(!i&&!r)return null;const s='',o=`#version 300 es +`),s=$s(n),o=[],a=[];for(const[l,u]of i){const c=s.get(l);if(!c||!c.isScalar||!String(u||"").trim()){a.push(l);continue}const d=" ".repeat(fi(r[c.lineIndex]));r[c.lineIndex]=`${d}${l}: ${vh(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:r.join(` +`),overridden:o,skipped:a}}function _h(t){const e=String(t||""),n=[];return e.trim()?(/^name:\s*\S+/m.test(e)||n.push("pubspec.yaml missing name field"),xl(e.split(` +`))||n.push("pubspec.yaml missing dependencies section"),gh(e).includes("flutter")||n.push("pubspec.yaml missing Flutter SDK dependency"),{valid:n.length===0,errors:n}):(n.push("pubspec.yaml is empty"),{valid:!1,errors:n})}const V_=">=3.0.0 <4.0.0";function La(t){const e=String(t||"").trim(),n=e[0];return n!=="'"&&n!=='"'||e[e.length-1]!==n?e:e.slice(1,-1).replaceAll(`${n}${n}`,n)}function G_(t=""){const e=Yv(t).filter(n=>!n.startsWith("dart:")&&!n.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function Bu(t,e,n){const i=[];for(const[r,s]of t){if(s.isScalar){e[r]=La(s.constraint);continue}if(s.sourceKey==="sdk"){n.add(r);continue}if(s.sourceKey===null&&s.version){e[r]=La(s.version);continue}i.push(r)}return i}function K_(t){const e=new Set,n={},i={},r=Bu($s(t),n,e);r.push(...Bu(H_(t,"dependency_overrides"),i,e));const s=new Set([...Object.keys(n),...e]),{sdk:o}=mh(t);return{sdkConstraint:La(o)||V_,dependencies:n,overrides:i,sdkPackages:[...e].sort(),availablePackages:s,unrepresentable:r}}function Y_(t,e,n){return e.length>0?`${t} imports ${e.join(", ")}, which FlutterFlow only generates once the app is built, so it could not be compiled before the deploy.`:`${t} imports ${n.join(", ")}, which your project's pubspec.yaml does not declare with a version constraint, so it could not be compiled before the deploy.`}function J_(t,e){const{sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s,availablePackages:o,unrepresentable:a}=K_(e),l={sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s},u=[],c=[],d=a.map(h=>`Your project declares ${h} from a source that cannot be reproduced outside it, so the pre-deploy compile check runs against a scratch package graph that omits ${h}. Classes that do not import ${h} directly are still checked, but against that reduced graph, so their transitive package resolution may differ from your project's and the check is approximate for them.`);for(const h of t){const{className:f,content:p}=h,g=wl(p),m=g.filter(S=>a.includes(S));if(m.length>0){c.push({className:f,reason:`${f} was not compiled before deploying: it imports ${m.join(", ")}, which your project declares from a source that cannot be reproduced outside it, so package resolution could not be matched exactly.`});continue}const{unresolvableImports:v}=G_(p),E=g.filter(S=>!o.has(S));if(v.length>0||E.length>0){c.push({className:f,reason:Y_(f,v,E)});continue}u.push({fileName:`${yl(f)}.dart`,content:p})}return{manifest:l,sources:u,skipped:c,approximate:d}}function Du(t,e){const n=`${t}${e}`.split(` +`),i=n.pop()??"",r=[];for(const s of n){const o=yh(s);o&&r.push(o)}return{events:r,buffer:i}}function Z_(t){const e=yh(t);return e?[e]:[]}function yh(t){const e=t.trim();if(!e)return null;try{const n=JSON.parse(e);return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}const Le=Object.freeze({COMMITTED:"committed",PARTIAL:"partial",FAILED:"failed",UNCONFIRMED:"unconfirmed"}),wh=12e4;function bh(t){return t?.unconfirmed===!0||t?.outcome===Le.UNCONFIRMED?Le.UNCONFIRMED:t?.partial===!0||t?.outcome===Le.PARTIAL?Le.PARTIAL:t?.success===!0?Le.COMMITTED:Le.FAILED}class Qe extends Error{constructor(e){super(e),this.name="UnconfirmedDeployError",this.outcome=Le.UNCONFIRMED}}function ju({httpStatus:t}={}){return new Qe(`Every FlutterFlow sync endpoint lost its response or ended in a server error${t?` (last: HTTP ${t})`:""} — neither can prove the push was refused, so it may already have been applied. Open the FlutterFlow project to reconcile before retrying.`)}async function X_(t,e={}){const{onPhase:n,onLog:i}=e;let r=null,s=null,o="";const a=u=>{if(u.event==="phase"){u.phase&&(s=u.phase),u.message&&n&&n(u.message);return}if(u.event==="log"){u.message&&i&&i(u.message);return}r=u};let l=null;try{if(t.body?.getReader){const u=t.body.getReader(),c=new TextDecoder;for(;;){const{done:d,value:h}=await u.read();if(d)break;const f=Du(o,c.decode(h,{stream:!0}));o=f.buffer,f.events.forEach(a)}}else{const u=Du("",await t.text());o=u.buffer,u.events.forEach(a)}}catch(u){l=u}return Z_(o).forEach(a),r?{...r,success:r.success===!0||r.success===void 0&&t.ok,finalResultReceived:!0,runnerPhase:s,httpStatus:t.status}:{success:!1,finalResultReceived:!1,httpRejected:!t.ok,httpStatus:t.status,runnerPhase:s,error:t.ok?l?"The connection to the FlutterFlow deploy runner dropped before it reported a result.":"The FlutterFlow deploy runner closed the connection before it finished.":`FlutterFlow custom class provisioning failed (HTTP ${t.status}).`}}const Q_=new Set(["connected","workspace_init","workspace_ready","verifying"]);function ey(t){return t?.preWrite===!0||Array.isArray(t?.analyzerErrors)&&t.analyzerErrors.length>0?!0:typeof t?.runnerPhase=="string"?Q_.has(t.runnerPhase):typeof t?.httpStatus=="number"?t.httpStatus>=400&&t.httpStatus<500:!1}function Uu(t){if(t?.finalResultReceived){const e=bh(t);return e===Le.FAILED&&!ey(t)?Le.UNCONFIRMED:e}return t?.httpRejected?Le.FAILED:Le.UNCONFIRMED}function ty(){let t=document.getElementById("fx-grid");if(!t)return null;const e=window.matchMedia("(prefers-reduced-motion: reduce)"),n=window.matchMedia("(pointer: none)");let i=t.getContext("webgl2",{alpha:!0,antialias:!1,depth:!1,stencil:!1,premultipliedAlpha:!0,powerPreference:"low-power"}),r=i?null:t.getContext("2d");if(!i&&!r)return null;const s='',o=`#version 300 es in vec2 p; void main(){ gl_Position = vec4(p, 0.0, 1.0); }`;function a(){return["#version 300 es","precision highp float;","out vec4 o;","uniform vec2 res;","uniform vec2 design;","uniform vec2 mouse;","uniform float energy;","uniform float parallax;","uniform float t;","uniform vec3 ink;","uniform sampler2D mark;","uniform vec2 rot;","const float WARP_A = 0.0032;","void main(){"," vec2 px = gl_FragCoord.xy * (design / res);"," vec2 p = vec2(px.x, design.y - px.y);"," vec2 off = vec2(0.0, -parallax) + vec2(sin(t * 0.11), cos(t * 0.09)) * 7.0;"," vec2 g = p + off;"," vec2 gm = mouse + off;"," float base = min(design.x, design.y);"," float spacing = clamp(base / 10.0, 64.0, 118.0);"," vec2 rel = g - gm;"," float rho = length(rel) + 1e-5;"," vec2 dir = rel / rho;"," vec2 pw = gm + dir * (rho + WARP_A * rho * rho);"," vec2 cell = floor(pw / spacing);"," vec2 cw = (cell + 0.5) * spacing - gm;"," float Rc = length(cw) + 1e-5;"," float rhoC = (-1.0 + sqrt(1.0 + 4.0 * WARP_A * Rc)) / (2.0 * WARP_A);"," vec2 c = gm + (cw / Rc) * rhoC;"," float cellSize = spacing / (1.0 + 2.0 * WARP_A * rhoC);"," float sigma = spacing * 2.9;"," float f = exp(-(rhoC * rhoC) / (2.0 * sigma * sigma));"," float scale = mix(0.32, 1.42, f);"," float weight = smoothstep(0.06, 0.80, f);"," float hs = cellSize * 0.26 * scale;"," vec2 uv = (g - c) / hs;"," vec2 ruv = mat2(rot.x, rot.y, -rot.y, rot.x) * uv;"," float cov = 0.0;"," if (abs(ruv.x) <= 1.0 && abs(ruv.y) <= 1.0) cov = texture(mark, ruv * 0.5 + 0.5).a;"," float s = cov * weight * energy * 0.26;"," o = vec4(ink * s, s);","}"].join(` -`)}let l=null,u,c,d,h,f,p,g,m,v;function E(Y,W){if(!i)return null;const D=i.createShader(Y);return i.shaderSource(D,W),i.compileShader(D),i.getShaderParameter(D,i.COMPILE_STATUS)?D:(window.console&&console.warn("fx-grid shader: "+i.getShaderInfoLog(D)),null)}if(i){const Y=E(i.VERTEX_SHADER,o),W=E(i.FRAGMENT_SHADER,a());if(Y&&W&&(l=i.createProgram(),i.attachShader(l,Y),i.attachShader(l,W),i.linkProgram(l),i.getProgramParameter(l,i.LINK_STATUS)||(window.console&&console.warn("fx-grid link: "+i.getProgramInfoLog(l)),l=null)),l){i.useProgram(l),i.bindBuffer(i.ARRAY_BUFFER,i.createBuffer()),i.bufferData(i.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),i.STATIC_DRAW);const D=i.getAttribLocation(l,"p");i.enableVertexAttribArray(D),i.vertexAttribPointer(D,2,i.FLOAT,!1,0,0),u=i.getUniformLocation(l,"res"),c=i.getUniformLocation(l,"design"),d=i.getUniformLocation(l,"mouse"),h=i.getUniformLocation(l,"energy"),f=i.getUniformLocation(l,"parallax"),p=i.getUniformLocation(l,"t"),g=i.getUniformLocation(l,"ink"),m=i.getUniformLocation(l,"mark"),v=i.getUniformLocation(l,"rot"),i.enable(i.BLEND),i.blendFunc(i.ONE,i.ONE_MINUS_SRC_ALPHA),i.clearColor(0,0,0,0)}else{i=null;const D=t.cloneNode(!1);if(t.parentNode.replaceChild(D,t),t=D,r=t.getContext("2d"),!r)return null}}function S(Y){if(!Y)return null;const W=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(Y);if(W){let D=W[1];return D.length===3&&(D=D[0]+D[0]+D[1]+D[1]+D[2]+D[2]),[parseInt(D.slice(0,2),16)/255,parseInt(D.slice(2,4),16)/255,parseInt(D.slice(4,6),16)/255]}try{const D=document.createElement("canvas");D.width=1,D.height=1;const ue=D.getContext("2d");ue.fillStyle="rgb(9, 8, 7)";const xe=String(ue.fillStyle);ue.fillStyle=Y;const Fe=String(ue.fillStyle);if(Fe===xe)return null;const dt=/^#([0-9a-f]{6})$/i.exec(Fe);if(dt){const ft=dt[1];return[parseInt(ft.slice(0,2),16)/255,parseInt(ft.slice(2,4),16)/255,parseInt(ft.slice(4,6),16)/255]}const Nt=/rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i.exec(Fe);if(Nt)return[Number(Nt[1])/255,Number(Nt[2])/255,Number(Nt[3])/255]}catch{}return null}function _(){let Y="";try{const W=getComputedStyle(document.documentElement);Y=(W.getPropertyValue("--fx-ink")||"").trim()||(W.getPropertyValue("--fg")||"").trim()}catch{}return S(Y)||[.56,.68,.88]}const b=_();let k=1920,T=1080,x=960,F=540,$=960,O=540,L=.66,N=0,K=-1e9,V=!1,M=0,R=0,Z=null,Ce=!1,oe=!1,ye=!1;const $e=64,ae=15.2;let Ie=0,Se=0;const Be=.0032,wt=0,ge=.56,Ye=.26,bt=.32,mn=.16,Re=.349;let Pe=wt;function $t(){const Y=t.getBoundingClientRect(),W=t.clientWidth,D=t.clientHeight;if(!Y.width||!W||!D)return;const ue=Math.min(window.devicePixelRatio||1,2),xe=Math.max(.2,Math.min(2,Y.width/W*ue)),Fe=Math.max(2,Math.round(W*xe)),dt=Math.max(2,Math.round(D*xe));(Fe!==t.width||dt!==t.height)&&(t.width=Fe,t.height=dt,i&&i.viewport(0,0,Fe,dt)),k=W,T=D,V||(x=$=k/2,F=O=T/2,V=!0)}function Bn(Y){!l||!Ce||!i||(i.uniform2f(u,t.width,t.height),i.uniform2f(c,k,T),i.uniform2f(d,x,F),i.uniform1f(h,L),i.uniform1f(f,N),i.uniform2f(v,Math.cos(Pe),Math.sin(Pe)),i.uniform1f(p,Y),i.uniform3f(g,b[0],b[1],b[2]),i.clear(i.COLOR_BUFFER_BIT),i.drawArrays(i.TRIANGLES,0,3))}function qe(Y,W,D){const ue=Math.max(0,Math.min(1,(D-Y)/(W-Y)));return ue*ue*(3-2*ue)}function Dn(Y){if(!Z||!r)return;const W=r;W.setTransform(1,0,0,1,0,0),W.clearRect(0,0,t.width,t.height);const D=t.width/k;W.setTransform(D,0,0,D,0,0),W.globalAlpha=1;const ue=Math.min(k,T),xe=Math.max(64,Math.min(118,ue/10)),Fe=xe*2.9,dt=2*Fe*Fe,Nt=Math.sin(Y*.11)*7,ft=Math.cos(Y*.09)*7-N,dr=x+Nt,fr=F+ft,no=Fe*Math.sqrt(2*Math.log(1/.06)),mi=no+Be*no*no+xe,Ap=Math.floor((dr-mi)/xe)-1,Pp=Math.ceil((dr+mi)/xe)+1,Fp=Math.floor((fr-mi)/xe)-1,Rp=Math.ceil((fr+mi)/xe)+1;for(let io=Fp;io<=Rp;io++){const Tp=(io+.5)*xe;for(let ro=Ap;ro<=Pp;ro++){const so=(ro+.5)*xe-dr,oo=Tp-fr,ao=Math.sqrt(so*so+oo*oo)+1e-5;if(ao>mi)continue;const hr=(-1+Math.sqrt(1+4*Be*ao))/(2*Be),ac=Math.exp(-(hr*hr)/dt),lc=qe(.06,.8,ac)*L*.26;if(lc<.004)continue;const on=xe/(1+2*Be*hr)*.26*(.32+1.1*ac),cc=hr/ao,lo=dr+so*cc,co=fr+oo*cc;lo<-on*1.6||lo>k+on*1.6||co<-on*1.6||co>T+on*1.6||(W.globalAlpha=lc,W.save(),W.translate(lo,co),W.rotate(Pe),W.drawImage(Z,-on,-on,on*2,on*2),W.restore())}}W.globalAlpha=1}function Mt(Y){if(!oe)return;const W=R?Math.min(.05,(Y-R)/1e3):.016;R=Y;const ue=Y-K>2400?.6:1;L+=(ue-L)*Math.min(1,W*3.2);const xe=Math.min(.05,W);Ie+=(($-x)*$e-Ie*ae)*xe,Se+=((O-F)*$e-Se*ae)*xe,x+=Ie*xe,F+=Se*xe,N=(window.scrollY||window.pageYOffset||0)*.55;const Fe=Y/1e3,dt=x/(k||1)-.5,Nt=F/(T||1)-.5;let ft=dt*(dt>=0?ge:Ye)+Nt*(Nt>=0?bt:mn);ft>Re?ft=Re:ft<-Re&&(ft=-Re),Pe=wt+ft-N*6e-4,$t(),i?Bn(Fe):Dn(Fe),M=requestAnimationFrame(Mt)}function Lt(Y){if(!oe)return;const W=t.getBoundingClientRect();!W.width||!k||!T||($=(Y.clientX-W.left)/W.width*k,O=(Y.clientY-W.top)/W.height*T,K=performance.now())}function ut(){oe||to||e.matches||n.matches||!ye||document.hidden||(oe=!0,R=0,M=requestAnimationFrame(Mt))}function sn(){oe=!1,M&&(cancelAnimationFrame(M),M=0),R=0}function gi(){e.matches?(sn(),t.classList.remove("is-ready")):ye&&ut()}function jn(){n.matches?sn():ye&&ut()}function rc(){document.hidden?sn():ye&&ut()}const sc=new IntersectionObserver(Y=>{ye=Y[0]?.isIntersecting||!1,ye?ut():sn()},{threshold:0});sc.observe(t),window.addEventListener("pointermove",Lt,{passive:!0,capture:!0}),window.addEventListener("resize",$t),e.addEventListener("change",gi),n.addEventListener("change",jn),document.addEventListener("visibilitychange",rc);function Cp(){const Y=(s.match(/\sd="([^"]+)"/)||[])[1],W=document.createElement("canvas");W.width=256,W.height=256;const D=W.getContext("2d");if(Y&&window.Path2D){const ue=Math.min(8.533333333333333,8.421052631578947);D.setTransform(ue,0,0,ue,ue+(256-30*ue)/2,-6.4*ue),D.fillStyle="rgb(255,255,255)",D.fill(new Path2D(Y),"evenodd"),D.setTransform(1,0,0,1,0,0)}try{const ue=D.getImageData(0,0,256,256),xe=ue.data;for(let Fe=3;Feoe}}const ey=120;function ty(t,e,n){return tn?n:t}function de(t,e,n){return ty((t-e)/(n-e),0,1)}function ny(t){return t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2}function Uo(t){return 1-Math.pow(1-t,3)}function ze(t,e){return e=e===void 0?1.7:e,1+(e+1)*Math.pow(t-1,3)+e*Math.pow(t-1,2)}function Uu(t){return 1-Math.pow(2,-9*t)*Math.cos(t*15)}function te(t,e){if(t<=e[0].t)return e[0].v;for(let n=1;n8.2&&_<9.4&&(s*=1-.07*Math.sin(de(_,8.2,9.4)*Math.PI))}else if(t<53){const _=t-42;g=te(_,[{t:0,v:1},{t:2,v:0},{t:4.2,v:0},{t:4.6,v:1},{t:6.8,v:1},{t:7.4,v:0},{t:9.4,v:0},{t:10.6,v:1}]),p=te(_,[{t:0,v:1},{t:2,v:.3},{t:4.6,v:1,e:ze}]),d=te(_,[{t:0,v:0},{t:2,v:.3},{t:4.6,v:.16,e:ze},{t:10.6,v:0}]),f=te(_,[{t:0,v:0},{t:2,v:-40},{t:4.6,v:0,e:ze}]),o=te(_,[{t:0,v:0},{t:4.6,v:-.12},{t:10.6,v:0}])}else if(t<60){const _=t-53;c=te(_,[{t:0,v:1},{t:.35,v:0},{t:.45,v:0},{t:.7,v:1}]);const b=de(_,.45,2.2);a=b>0?-2.6*(1-Uu(b)):0,g=te(_,[{t:0,v:1},{t:.57,v:0},{t:.67,v:0},{t:.92,v:1}]);const k=de(_,.67,2.42);h=k>0?-2.6*(1-Uu(k)):0,s=1-.05*(Math.sin(de(_,1.9,2.5)*Math.PI)+Math.sin(de(_,2.5,3.1)*Math.PI))}else if(t<74){let b=function(F){return[te(F,[{t:0,v:0},{t:.25,v:1},{t:.5,v:1},{t:.72,v:.14},{t:.82,v:.14},{t:1,v:0}]),te(F,[{t:0,v:0},{t:.08,v:-.62},{t:.25,v:-.62},{t:.33,v:.62},{t:.7,v:.62},{t:.82,v:-.62},{t:1,v:-.62}])]};var S=b;const _=t-60,k=1-de(_,12,14),T=b(de(_,0,12)),x=b(de(_-.5,0,12));n=T[0]*k,i=(T[1]+.05*Math.sin(_*7))*k,o=(x[0]-T[0])*.6*k,a=(x[1]-T[1])*.6*k,f=(x[0]-T[0])*30*k,E=de(_,0,.4)*k}else if(t<85.4){const _=t-74,b=te(_,[{t:0,v:0},{t:4,v:1},{t:8,v:.24},{t:9.6,v:1,e:ze},{t:11.4,v:0}]);o=b*.5,d=-b*.5,l=te(_,[{t:0,v:0},{t:4,v:6},{t:8,v:20},{t:9.6,v:38,e:ze},{t:11.4,v:0}]),f=-l*.7,a=te(_,[{t:0,v:0},{t:8,v:0},{t:9.6,v:.4},{t:11.4,v:0}])}else if(t<96.4){const _=t-85.4,b=de(_,0,5.6),k=de(_,5.6,7.6),T=.72*Math.min(1,_/.6)*(1-k);d=Math.cos(b*Math.PI*2)*T,h=Math.sin(b*Math.PI*2)*T*.55,f=b*360*(1-k);const x=te(_,[{t:0,v:0},{t:7.6,v:0},{t:8.2,v:1,e:Uo},{t:8.6,v:.55},{t:9.4,v:0}]);o=-.16*x,d+=.16*x,l=-6*x,f+=6*x,s=1+.05*x,m=1+.9*x}else if(t<108.6){const _=t-96.4,b=de(_,9.6,12.2);n=te(_,[{t:0,v:0},{t:2.1,v:1},{t:4.8,v:.08},{t:7.5,v:1},{t:9.6,v:0}])*(1-b),i=-.35*Math.abs(Math.sin(de(_,0,9.6)*Math.PI*3))*(1-b);const k=Math.sin(_*6.2)*(1-b);u=1+.12*k,p=1-.12*k,l=k*8,f=-k*8,o=.06*k,d=-.06*k,E=de(_,0,.4)*(1-b)}else{const _=t-108.6,b=Math.sin(de(_,0,8)*Math.PI),k=1-de(_,8,11.4);s=1+.04*b*k,i=-.1*b*k,r=2*b*k,m=1+.5*Math.sin(de(_,0,6)*Math.PI),v=1+.1*Math.sin(de(_,0,6)*Math.PI)}return e.x=n,e.y=i,e.rot=r,e.scale=s,e.ax=o,e.ay=a,e.ar=l,e.asc=u,e.afade=c,e.bx=d,e.by=h,e.br=f,e.bsc=p,e.bfade=g,e.hfade=m,e.hsc=v,e.shd=E,e}function iy(t={}){const e=t.arena||document.querySelector(".pipeline-glyph.logo-loop");if(!e)return null;const n=e.querySelector(".loop-mark"),i=e.querySelector(".loop-piece-a"),r=e.querySelector(".loop-piece-b"),s=e.querySelector(".loop-halo"),o=e.querySelector(".loop-shadow");if(!n||!i||!r||!s||!o)return null;const a=t.reducedMotion||window.matchMedia("(prefers-reduced-motion: reduce)"),l=ey;let u=34,c=0,d=0;function h(){u=n.offsetWidth||34,c=Math.max(0,e.offsetWidth-u-4),d=Math.max(0,(e.offsetHeight-u)/2-2),e.style.setProperty("--mark-c",u/2+"px")}function f(M){const R=Math.min(1,Math.max(0,M.x))*c,Z=M.y*d;n.style.transform="translate3d("+R.toFixed(2)+"px,"+Z.toFixed(2)+"px,0) rotate("+M.rot.toFixed(2)+"deg) scale("+M.scale.toFixed(3)+")",i.style.transform="translate3d("+(M.ax*u).toFixed(2)+"px,"+(M.ay*u).toFixed(2)+"px,0) rotate("+M.ar.toFixed(2)+"deg) scale("+M.asc.toFixed(3)+")",i.style.opacity=M.afade.toFixed(3),r.style.transform="translate3d("+(M.bx*u).toFixed(2)+"px,"+(M.by*u).toFixed(2)+"px,0) rotate("+M.br.toFixed(2)+"deg) scale("+M.bsc.toFixed(3)+")",r.style.opacity=M.bfade.toFixed(3),s.style.transform="scale("+M.hsc.toFixed(3)+")",s.style.opacity=(.09*M.hfade).toFixed(3),o.style.transform="translateX("+R.toFixed(2)+"px) scaleX("+(.75+.4*Math.abs(M.x)).toFixed(3)+")",o.style.opacity=(M.shd*.5).toFixed(3)}let p=0,g=0,m=0,v=!1,E=!1,S=!1,_=0;function b(){return S||a.matches||document.hidden||!e.offsetParent?!1:E}function k(M){if(!v)return;if(m=requestAnimationFrame(k),!b()){x();return}const R=g?(M-g)/1e3:0;g=M,p=(p+Math.min(R,.1))%l,_+=1,f(Ai(p))}function T(){v||S||b()&&(v=!0,g=0,m=requestAnimationFrame(k))}function x(){v=!1,m&&(cancelAnimationFrame(m),m=0),g=0}function F(){b()?T():x()}function $(){a.matches?(x(),f(Ai(0))):F()}function O(){h(),v&&f(Ai(p))}function L(){g=0,F()}const N=new IntersectionObserver(M=>{E=M[0]?M[0].isIntersecting:!1,F()},{threshold:0});N.observe(e),window.addEventListener("resize",O),a.addEventListener("change",$),document.addEventListener("visibilitychange",L);function K(){S||(S=!0,x(),N.disconnect(),window.removeEventListener("resize",O),a.removeEventListener("change",$),document.removeEventListener("visibilitychange",L))}window.addEventListener("pagehide",K);function V(M){p=(M%l+l)%l,f(Ai(p))}return h(),f(Ai(0)),F(),{isRunning:()=>v,currentTime:()=>p,frameCount:()=>_,seek:V,dispose:K}}const ry=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function Xt(t){const e=String(t||"").trim().match(ry);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function sy(t,e){if(t.length===0&&e.length===0)return 0;if(t.length===0)return 1;if(e.length===0)return-1;for(let n=0;n0)}function ay(t){const e=Xt(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function Il(t){let e=String(t??"").trim();if((e.startsWith("'")||e.startsWith('"'))&&(e=e.slice(1,-1).trim()),e===""||e==="any"||e==="*")return{min:null,minInclusive:!1,max:null,maxInclusive:!1};if(e.startsWith("^")){const o=e.slice(1).trim();return Xt(o)?{min:o,minInclusive:!0,max:ay(o),maxInclusive:!1}:null}if(Xt(e))return{min:e,minInclusive:!0,max:e,maxInclusive:!0};const n={min:null,minInclusive:!1,max:null,maxInclusive:!1},i=/(>=|<=|>|<)\s*([0-9][0-9A-Za-z.+-]*)/g;let r=!1,s;for(;(s=i.exec(e))!==null;){const[,o,a]=s;if(!Xt(a))return null;r=!0,o===">="||o===">"?(n.min=a,n.minInclusive=o===">="):(n.max=a,n.maxInclusive=o==="<=")}return r?n:null}function Hu(t,e){const n=Il(t);if(!n||!Xt(e))return!1;if(n.min!==null){const i=fs(e,n.min);if(i<0||i===0&&!n.minInclusive)return!1}if(n.max!==null){const i=fs(e,n.max);if(i>0||i===0&&!n.maxInclusive)return!1}return!0}function ly(t,e){const n=Il(t);if(!n||!Xt(e))return!1;if(n.max===null)return!0;const i=fs(n.max,e);return i>0?!0:i===0&&n.maxInclusive}function zn(t){const e=Il(t);return e?e.min:null}const cy="https://pub.dev/api/packages/",uy=8e3;function dy(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null}=e,r=Array.isArray(t?.versions)?t.versions:[];let s=null;for(const o of r){const a=o?.version;if(!a||o.retracted||oy(a))continue;const l=o.pubspec?.environment||{};n&&l.sdk&&!Hu(l.sdk,n)||i&&l.flutter&&!Hu(l.flutter,i)||(!s||fs(a,s)>0)&&(s=a)}return s?{version:s,constraint:`^${s}`}:null}async function fy(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null,fetchImpl:r=fetch}=e;let s;try{const a=await r(`${cy}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(uy)});if(!a.ok)return{name:t,constraint:null,version:null,error:a.status===404?`"${t}" was not found on pub.dev`:`pub.dev returned ${a.status} for "${t}"`};s=await a.json()}catch(a){return{name:t,constraint:null,version:null,error:`could not reach pub.dev for "${t}" (${a.message})`}}const o=dy(s,{dartSdkFloor:n,flutterSdkFloor:i});return o?{name:t,...o,error:null}:{name:t,constraint:null,version:null,error:n?`no published "${t}" release supports Dart ${n}`:`no published "${t}" release could be read`}}async function hy(t,e={}){const n=await Promise.all(t.map(i=>fy(i,e)));return new Map(n.map(({name:i,...r})=>[i,r]))}async function py(t,e={},n={}){const{resolveVersions:i=hy}=n,r=Object.entries(e).filter(([c])=>c&&c!=="flutter"),s=gh(t),o={dartSdkFloor:zn(s.sdk),flutterSdkFloor:zn(s.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(r.length===0)return a;const l=$s(t),u=[];for(const[c,d]of r){const h=l.get(c);if(!h){u.push(c);continue}const f=zn(d);if(!f){a.kept.push({name:c,constraint:h.constraint});continue}if(!h.isScalar){a.warnings.push(`"${c}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${f}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:c,constraint:h.constraint});continue}if(ly(h.constraint,f)){a.kept.push({name:c,constraint:h.constraint});continue}a.overrides[c]=`^${f}`,a.warnings.push(`"${c}" was pinned to ${h.constraint} in your project, which cannot resolve the ${f} the generated code needs. Raising it to ^${f} — this changes a dependency the rest of your app also uses.`)}if(u.length>0){const c=await i(u,o);for(const d of u){const h=c.get(d);if(h?.constraint){a.additions[d]=h.constraint;continue}const f=e[d]||"";if(zn(f)){a.additions[d]=`^${zn(f)}`,a.warnings.push(`Could not confirm "${d}" version on pub.dev (${h?.error||"lookup failed"}). Using ^${zn(f)} from the AI's recommendation — verify this is current.`);continue}a.additions[d]=">=0.0.0",a.warnings.push(`Could not determine a version for "${d}" (${h?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const gy={"&":"&","<":"<",">":">",'"':""","'":"'"};function Qt(t){return String(t??"").replace(/[&<>"']/g,e=>gy[e])}function q(t){return t?Qt(t).replace(/\n/g,"
    "):""}function Jt(t){return Qt(t).replace(/\r?\n/g," ")}function Ms(t,e={}){const n=t?.pipelineStep;if(n!=null&&e[n]!=null)return e[n];const i=t?.message||"";return i.includes("Code Generator")?2:i.includes("Code Review")?3:1}function Eh(t){if(!t)return{kind:"generic",title:"Generation failed",message:"An unknown error occurred. Please try again.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1};if(t.isModelArmor){const n=t.code==="MODEL_ARMOR_BLOCKED";return{kind:"safety",title:t.userTitle||"Request blocked for safety",message:t.userMessage||t.message,detail:t.retryExplanation||"",canRetry:!n,canEdit:!0,canUpgrade:!1}}if(t.isUsageLimit)return{kind:"quota",title:"Monthly limit reached",message:t.message||"You've used all your generations for this period.",detail:"",canRetry:!1,canEdit:!1,canUpgrade:!0};const e=t.message||"";return/timed out after/i.test(e)?{kind:"timeout",title:"Request timed out",message:"The generation service took too long to respond.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:/unreachable|failed to fetch|load failed|cors/i.test(e)?{kind:"network",title:"Connection problem",message:"We couldn't reach the generation service. Check your connection and try again.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:{kind:"generic",title:"Generation failed",message:e||"An unexpected error occurred.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1}}function my(t){const e={"Integration Audit Report":"📋","Critical Issues":"❌",Warnings:"⚠️",Recommendations:"✅","Overall Score":"📊"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📄"}function vy(t){const e={critical:"❌",warning:"⚠️",recommendation:"✅",score:"📊",issue:"🔍",fix:"🔧"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📝"}function _y(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 li(t){if(!t)return"";if(typeof t!="string")return String(t);const e=/```(?:\w+)?\n?([\s\S]*?)```/,n=t.match(e);return n?n[1].trim():t.trim()}function Wu(t){return t=Qt(t),t=t.replace(/\*\*(.*?)\*\*/g,'$1'),t=t.replace(/\*(.*?)\*/g,'$1'),t=t.replace(/`(.*?)`/g,'$1'),t=t.replace(/\b(FAIL|ERROR|CRITICAL)\b/g,'$1'),t=t.replace(/\b(WARN|WARNING)\b/g,'$1'),t=t.replace(/\b(PASS|SUCCESS|OK)\b/g,'$1'),t}function Sh(t,e="dart",n=globalThis.hljs){if(!t)return"";const i=li(t);try{return n.highlight(i,{language:e}).value}catch(r){console.warn("Syntax highlighting failed:",r);try{return n.highlight(i,{language:"json"}).value}catch{return Qt(i)}}}function Ls(t,e={}){const{highlighter:n=globalThis.hljs}=e;let i='
    ';const r=String(t??"").split(` -`);let s=!1,o="";for(const a of r){if(a.startsWith("```")){if(s){const l=_y(o),u=Sh(o.trim(),l,n);i+=`
    +`)}let l=null,u,c,d,h,f,p,g,m,v;function E(Y,W){if(!i)return null;const D=i.createShader(Y);return i.shaderSource(D,W),i.compileShader(D),i.getShaderParameter(D,i.COMPILE_STATUS)?D:(window.console&&console.warn("fx-grid shader: "+i.getShaderInfoLog(D)),null)}if(i){const Y=E(i.VERTEX_SHADER,o),W=E(i.FRAGMENT_SHADER,a());if(Y&&W&&(l=i.createProgram(),i.attachShader(l,Y),i.attachShader(l,W),i.linkProgram(l),i.getProgramParameter(l,i.LINK_STATUS)||(window.console&&console.warn("fx-grid link: "+i.getProgramInfoLog(l)),l=null)),l){i.useProgram(l),i.bindBuffer(i.ARRAY_BUFFER,i.createBuffer()),i.bufferData(i.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),i.STATIC_DRAW);const D=i.getAttribLocation(l,"p");i.enableVertexAttribArray(D),i.vertexAttribPointer(D,2,i.FLOAT,!1,0,0),u=i.getUniformLocation(l,"res"),c=i.getUniformLocation(l,"design"),d=i.getUniformLocation(l,"mouse"),h=i.getUniformLocation(l,"energy"),f=i.getUniformLocation(l,"parallax"),p=i.getUniformLocation(l,"t"),g=i.getUniformLocation(l,"ink"),m=i.getUniformLocation(l,"mark"),v=i.getUniformLocation(l,"rot"),i.enable(i.BLEND),i.blendFunc(i.ONE,i.ONE_MINUS_SRC_ALPHA),i.clearColor(0,0,0,0)}else{i=null;const D=t.cloneNode(!1);if(t.parentNode.replaceChild(D,t),t=D,r=t.getContext("2d"),!r)return null}}function S(Y){if(!Y)return null;const W=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(Y);if(W){let D=W[1];return D.length===3&&(D=D[0]+D[0]+D[1]+D[1]+D[2]+D[2]),[parseInt(D.slice(0,2),16)/255,parseInt(D.slice(2,4),16)/255,parseInt(D.slice(4,6),16)/255]}try{const D=document.createElement("canvas");D.width=1,D.height=1;const ue=D.getContext("2d");ue.fillStyle="rgb(9, 8, 7)";const xe=String(ue.fillStyle);ue.fillStyle=Y;const Fe=String(ue.fillStyle);if(Fe===xe)return null;const dt=/^#([0-9a-f]{6})$/i.exec(Fe);if(dt){const ft=dt[1];return[parseInt(ft.slice(0,2),16)/255,parseInt(ft.slice(2,4),16)/255,parseInt(ft.slice(4,6),16)/255]}const Nt=/rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i.exec(Fe);if(Nt)return[Number(Nt[1])/255,Number(Nt[2])/255,Number(Nt[3])/255]}catch{}return null}function _(){let Y="";try{const W=getComputedStyle(document.documentElement);Y=(W.getPropertyValue("--fx-ink")||"").trim()||(W.getPropertyValue("--fg")||"").trim()}catch{}return S(Y)||[.56,.68,.88]}const b=_();let k=1920,T=1080,x=960,F=540,$=960,O=540,L=.66,N=0,K=-1e9,V=!1,M=0,R=0,Z=null,Ce=!1,oe=!1,ye=!1;const $e=64,ae=15.2;let Ie=0,Se=0;const De=.0032,wt=0,ge=.56,Je=.26,bt=.32,mn=.16,Re=.349;let Pe=wt;function $t(){const Y=t.getBoundingClientRect(),W=t.clientWidth,D=t.clientHeight;if(!Y.width||!W||!D)return;const ue=Math.min(window.devicePixelRatio||1,2),xe=Math.max(.2,Math.min(2,Y.width/W*ue)),Fe=Math.max(2,Math.round(W*xe)),dt=Math.max(2,Math.round(D*xe));(Fe!==t.width||dt!==t.height)&&(t.width=Fe,t.height=dt,i&&i.viewport(0,0,Fe,dt)),k=W,T=D,V||(x=$=k/2,F=O=T/2,V=!0)}function Bn(Y){!l||!Ce||!i||(i.uniform2f(u,t.width,t.height),i.uniform2f(c,k,T),i.uniform2f(d,x,F),i.uniform1f(h,L),i.uniform1f(f,N),i.uniform2f(v,Math.cos(Pe),Math.sin(Pe)),i.uniform1f(p,Y),i.uniform3f(g,b[0],b[1],b[2]),i.clear(i.COLOR_BUFFER_BIT),i.drawArrays(i.TRIANGLES,0,3))}function qe(Y,W,D){const ue=Math.max(0,Math.min(1,(D-Y)/(W-Y)));return ue*ue*(3-2*ue)}function Dn(Y){if(!Z||!r)return;const W=r;W.setTransform(1,0,0,1,0,0),W.clearRect(0,0,t.width,t.height);const D=t.width/k;W.setTransform(D,0,0,D,0,0),W.globalAlpha=1;const ue=Math.min(k,T),xe=Math.max(64,Math.min(118,ue/10)),Fe=xe*2.9,dt=2*Fe*Fe,Nt=Math.sin(Y*.11)*7,ft=Math.cos(Y*.09)*7-N,dr=x+Nt,fr=F+ft,no=Fe*Math.sqrt(2*Math.log(1/.06)),mi=no+De*no*no+xe,Pp=Math.floor((dr-mi)/xe)-1,Fp=Math.ceil((dr+mi)/xe)+1,Rp=Math.floor((fr-mi)/xe)-1,Tp=Math.ceil((fr+mi)/xe)+1;for(let io=Rp;io<=Tp;io++){const $p=(io+.5)*xe;for(let ro=Pp;ro<=Fp;ro++){const so=(ro+.5)*xe-dr,oo=$p-fr,ao=Math.sqrt(so*so+oo*oo)+1e-5;if(ao>mi)continue;const hr=(-1+Math.sqrt(1+4*De*ao))/(2*De),ac=Math.exp(-(hr*hr)/dt),lc=qe(.06,.8,ac)*L*.26;if(lc<.004)continue;const on=xe/(1+2*De*hr)*.26*(.32+1.1*ac),cc=hr/ao,lo=dr+so*cc,co=fr+oo*cc;lo<-on*1.6||lo>k+on*1.6||co<-on*1.6||co>T+on*1.6||(W.globalAlpha=lc,W.save(),W.translate(lo,co),W.rotate(Pe),W.drawImage(Z,-on,-on,on*2,on*2),W.restore())}}W.globalAlpha=1}function Mt(Y){if(!oe)return;const W=R?Math.min(.05,(Y-R)/1e3):.016;R=Y;const ue=Y-K>2400?.6:1;L+=(ue-L)*Math.min(1,W*3.2);const xe=Math.min(.05,W);Ie+=(($-x)*$e-Ie*ae)*xe,Se+=((O-F)*$e-Se*ae)*xe,x+=Ie*xe,F+=Se*xe,N=(window.scrollY||window.pageYOffset||0)*.55;const Fe=Y/1e3,dt=x/(k||1)-.5,Nt=F/(T||1)-.5;let ft=dt*(dt>=0?ge:Je)+Nt*(Nt>=0?bt:mn);ft>Re?ft=Re:ft<-Re&&(ft=-Re),Pe=wt+ft-N*6e-4,$t(),i?Bn(Fe):Dn(Fe),M=requestAnimationFrame(Mt)}function Lt(Y){if(!oe)return;const W=t.getBoundingClientRect();!W.width||!k||!T||($=(Y.clientX-W.left)/W.width*k,O=(Y.clientY-W.top)/W.height*T,K=performance.now())}function ut(){oe||to||e.matches||n.matches||!ye||document.hidden||(oe=!0,R=0,M=requestAnimationFrame(Mt))}function sn(){oe=!1,M&&(cancelAnimationFrame(M),M=0),R=0}function gi(){e.matches?(sn(),t.classList.remove("is-ready")):ye&&ut()}function jn(){n.matches?sn():ye&&ut()}function rc(){document.hidden?sn():ye&&ut()}const sc=new IntersectionObserver(Y=>{ye=Y[0]?.isIntersecting||!1,ye?ut():sn()},{threshold:0});sc.observe(t),window.addEventListener("pointermove",Lt,{passive:!0,capture:!0}),window.addEventListener("resize",$t),e.addEventListener("change",gi),n.addEventListener("change",jn),document.addEventListener("visibilitychange",rc);function Ap(){const Y=(s.match(/\sd="([^"]+)"/)||[])[1],W=document.createElement("canvas");W.width=256,W.height=256;const D=W.getContext("2d");if(Y&&window.Path2D){const ue=Math.min(8.533333333333333,8.421052631578947);D.setTransform(ue,0,0,ue,ue+(256-30*ue)/2,-6.4*ue),D.fillStyle="rgb(255,255,255)",D.fill(new Path2D(Y),"evenodd"),D.setTransform(1,0,0,1,0,0)}try{const ue=D.getImageData(0,0,256,256),xe=ue.data;for(let Fe=3;Feoe}}const ny=120;function iy(t,e,n){return tn?n:t}function de(t,e,n){return iy((t-e)/(n-e),0,1)}function ry(t){return t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2}function Uo(t){return 1-Math.pow(1-t,3)}function Ve(t,e){return e=e===void 0?1.7:e,1+(e+1)*Math.pow(t-1,3)+e*Math.pow(t-1,2)}function Hu(t){return 1-Math.pow(2,-9*t)*Math.cos(t*15)}function te(t,e){if(t<=e[0].t)return e[0].v;for(let n=1;n8.2&&_<9.4&&(s*=1-.07*Math.sin(de(_,8.2,9.4)*Math.PI))}else if(t<53){const _=t-42;g=te(_,[{t:0,v:1},{t:2,v:0},{t:4.2,v:0},{t:4.6,v:1},{t:6.8,v:1},{t:7.4,v:0},{t:9.4,v:0},{t:10.6,v:1}]),p=te(_,[{t:0,v:1},{t:2,v:.3},{t:4.6,v:1,e:Ve}]),d=te(_,[{t:0,v:0},{t:2,v:.3},{t:4.6,v:.16,e:Ve},{t:10.6,v:0}]),f=te(_,[{t:0,v:0},{t:2,v:-40},{t:4.6,v:0,e:Ve}]),o=te(_,[{t:0,v:0},{t:4.6,v:-.12},{t:10.6,v:0}])}else if(t<60){const _=t-53;c=te(_,[{t:0,v:1},{t:.35,v:0},{t:.45,v:0},{t:.7,v:1}]);const b=de(_,.45,2.2);a=b>0?-2.6*(1-Hu(b)):0,g=te(_,[{t:0,v:1},{t:.57,v:0},{t:.67,v:0},{t:.92,v:1}]);const k=de(_,.67,2.42);h=k>0?-2.6*(1-Hu(k)):0,s=1-.05*(Math.sin(de(_,1.9,2.5)*Math.PI)+Math.sin(de(_,2.5,3.1)*Math.PI))}else if(t<74){let b=function(F){return[te(F,[{t:0,v:0},{t:.25,v:1},{t:.5,v:1},{t:.72,v:.14},{t:.82,v:.14},{t:1,v:0}]),te(F,[{t:0,v:0},{t:.08,v:-.62},{t:.25,v:-.62},{t:.33,v:.62},{t:.7,v:.62},{t:.82,v:-.62},{t:1,v:-.62}])]};var S=b;const _=t-60,k=1-de(_,12,14),T=b(de(_,0,12)),x=b(de(_-.5,0,12));n=T[0]*k,i=(T[1]+.05*Math.sin(_*7))*k,o=(x[0]-T[0])*.6*k,a=(x[1]-T[1])*.6*k,f=(x[0]-T[0])*30*k,E=de(_,0,.4)*k}else if(t<85.4){const _=t-74,b=te(_,[{t:0,v:0},{t:4,v:1},{t:8,v:.24},{t:9.6,v:1,e:Ve},{t:11.4,v:0}]);o=b*.5,d=-b*.5,l=te(_,[{t:0,v:0},{t:4,v:6},{t:8,v:20},{t:9.6,v:38,e:Ve},{t:11.4,v:0}]),f=-l*.7,a=te(_,[{t:0,v:0},{t:8,v:0},{t:9.6,v:.4},{t:11.4,v:0}])}else if(t<96.4){const _=t-85.4,b=de(_,0,5.6),k=de(_,5.6,7.6),T=.72*Math.min(1,_/.6)*(1-k);d=Math.cos(b*Math.PI*2)*T,h=Math.sin(b*Math.PI*2)*T*.55,f=b*360*(1-k);const x=te(_,[{t:0,v:0},{t:7.6,v:0},{t:8.2,v:1,e:Uo},{t:8.6,v:.55},{t:9.4,v:0}]);o=-.16*x,d+=.16*x,l=-6*x,f+=6*x,s=1+.05*x,m=1+.9*x}else if(t<108.6){const _=t-96.4,b=de(_,9.6,12.2);n=te(_,[{t:0,v:0},{t:2.1,v:1},{t:4.8,v:.08},{t:7.5,v:1},{t:9.6,v:0}])*(1-b),i=-.35*Math.abs(Math.sin(de(_,0,9.6)*Math.PI*3))*(1-b);const k=Math.sin(_*6.2)*(1-b);u=1+.12*k,p=1-.12*k,l=k*8,f=-k*8,o=.06*k,d=-.06*k,E=de(_,0,.4)*(1-b)}else{const _=t-108.6,b=Math.sin(de(_,0,8)*Math.PI),k=1-de(_,8,11.4);s=1+.04*b*k,i=-.1*b*k,r=2*b*k,m=1+.5*Math.sin(de(_,0,6)*Math.PI),v=1+.1*Math.sin(de(_,0,6)*Math.PI)}return e.x=n,e.y=i,e.rot=r,e.scale=s,e.ax=o,e.ay=a,e.ar=l,e.asc=u,e.afade=c,e.bx=d,e.by=h,e.br=f,e.bsc=p,e.bfade=g,e.hfade=m,e.hsc=v,e.shd=E,e}function sy(t={}){const e=t.arena||document.querySelector(".pipeline-glyph.logo-loop");if(!e)return null;const n=e.querySelector(".loop-mark"),i=e.querySelector(".loop-piece-a"),r=e.querySelector(".loop-piece-b"),s=e.querySelector(".loop-halo"),o=e.querySelector(".loop-shadow");if(!n||!i||!r||!s||!o)return null;const a=t.reducedMotion||window.matchMedia("(prefers-reduced-motion: reduce)"),l=ny;let u=34,c=0,d=0;function h(){u=n.offsetWidth||34,c=Math.max(0,e.offsetWidth-u-4),d=Math.max(0,(e.offsetHeight-u)/2-2),e.style.setProperty("--mark-c",u/2+"px")}function f(M){const R=Math.min(1,Math.max(0,M.x))*c,Z=M.y*d;n.style.transform="translate3d("+R.toFixed(2)+"px,"+Z.toFixed(2)+"px,0) rotate("+M.rot.toFixed(2)+"deg) scale("+M.scale.toFixed(3)+")",i.style.transform="translate3d("+(M.ax*u).toFixed(2)+"px,"+(M.ay*u).toFixed(2)+"px,0) rotate("+M.ar.toFixed(2)+"deg) scale("+M.asc.toFixed(3)+")",i.style.opacity=M.afade.toFixed(3),r.style.transform="translate3d("+(M.bx*u).toFixed(2)+"px,"+(M.by*u).toFixed(2)+"px,0) rotate("+M.br.toFixed(2)+"deg) scale("+M.bsc.toFixed(3)+")",r.style.opacity=M.bfade.toFixed(3),s.style.transform="scale("+M.hsc.toFixed(3)+")",s.style.opacity=(.09*M.hfade).toFixed(3),o.style.transform="translateX("+R.toFixed(2)+"px) scaleX("+(.75+.4*Math.abs(M.x)).toFixed(3)+")",o.style.opacity=(M.shd*.5).toFixed(3)}let p=0,g=0,m=0,v=!1,E=!1,S=!1,_=0;function b(){return S||a.matches||document.hidden||!e.offsetParent?!1:E}function k(M){if(!v)return;if(m=requestAnimationFrame(k),!b()){x();return}const R=g?(M-g)/1e3:0;g=M,p=(p+Math.min(R,.1))%l,_+=1,f(Ai(p))}function T(){v||S||b()&&(v=!0,g=0,m=requestAnimationFrame(k))}function x(){v=!1,m&&(cancelAnimationFrame(m),m=0),g=0}function F(){b()?T():x()}function $(){a.matches?(x(),f(Ai(0))):F()}function O(){h(),v&&f(Ai(p))}function L(){g=0,F()}const N=new IntersectionObserver(M=>{E=M[0]?M[0].isIntersecting:!1,F()},{threshold:0});N.observe(e),window.addEventListener("resize",O),a.addEventListener("change",$),document.addEventListener("visibilitychange",L);function K(){S||(S=!0,x(),N.disconnect(),window.removeEventListener("resize",O),a.removeEventListener("change",$),document.removeEventListener("visibilitychange",L))}window.addEventListener("pagehide",K);function V(M){p=(M%l+l)%l,f(Ai(p))}return h(),f(Ai(0)),F(),{isRunning:()=>v,currentTime:()=>p,frameCount:()=>_,seek:V,dispose:K}}const oy=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function Xt(t){const e=String(t||"").trim().match(oy);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function ay(t,e){if(t.length===0&&e.length===0)return 0;if(t.length===0)return 1;if(e.length===0)return-1;for(let n=0;n0)}function cy(t){const e=Xt(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function Il(t){let e=String(t??"").trim();if((e.startsWith("'")||e.startsWith('"'))&&(e=e.slice(1,-1).trim()),e===""||e==="any"||e==="*")return{min:null,minInclusive:!1,max:null,maxInclusive:!1};if(e.startsWith("^")){const o=e.slice(1).trim();return Xt(o)?{min:o,minInclusive:!0,max:cy(o),maxInclusive:!1}:null}if(Xt(e))return{min:e,minInclusive:!0,max:e,maxInclusive:!0};const n={min:null,minInclusive:!1,max:null,maxInclusive:!1},i=/(>=|<=|>|<)\s*([0-9][0-9A-Za-z.+-]*)/g;let r=!1,s;for(;(s=i.exec(e))!==null;){const[,o,a]=s;if(!Xt(a))return null;r=!0,o===">="||o===">"?(n.min=a,n.minInclusive=o===">="):(n.max=a,n.maxInclusive=o==="<=")}return r?n:null}function Wu(t,e){const n=Il(t);if(!n||!Xt(e))return!1;if(n.min!==null){const i=fs(e,n.min);if(i<0||i===0&&!n.minInclusive)return!1}if(n.max!==null){const i=fs(e,n.max);if(i>0||i===0&&!n.maxInclusive)return!1}return!0}function uy(t,e){const n=Il(t);if(!n||!Xt(e))return!1;if(n.max===null)return!0;const i=fs(n.max,e);return i>0?!0:i===0&&n.maxInclusive}function qn(t){const e=Il(t);return e?e.min:null}const dy="https://pub.dev/api/packages/",fy=8e3;function hy(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null}=e,r=Array.isArray(t?.versions)?t.versions:[];let s=null;for(const o of r){const a=o?.version;if(!a||o.retracted||ly(a))continue;const l=o.pubspec?.environment||{};n&&l.sdk&&!Wu(l.sdk,n)||i&&l.flutter&&!Wu(l.flutter,i)||(!s||fs(a,s)>0)&&(s=a)}return s?{version:s,constraint:`^${s}`}:null}async function py(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null,fetchImpl:r=fetch}=e;let s;try{const a=await r(`${dy}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(fy)});if(!a.ok)return{name:t,constraint:null,version:null,error:a.status===404?`"${t}" was not found on pub.dev`:`pub.dev returned ${a.status} for "${t}"`};s=await a.json()}catch(a){return{name:t,constraint:null,version:null,error:`could not reach pub.dev for "${t}" (${a.message})`}}const o=hy(s,{dartSdkFloor:n,flutterSdkFloor:i});return o?{name:t,...o,error:null}:{name:t,constraint:null,version:null,error:n?`no published "${t}" release supports Dart ${n}`:`no published "${t}" release could be read`}}async function gy(t,e={}){const n=await Promise.all(t.map(i=>py(i,e)));return new Map(n.map(({name:i,...r})=>[i,r]))}async function my(t,e={},n={}){const{resolveVersions:i=gy}=n,r=Object.entries(e).filter(([c])=>c&&c!=="flutter"),s=mh(t),o={dartSdkFloor:qn(s.sdk),flutterSdkFloor:qn(s.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(r.length===0)return a;const l=$s(t),u=[];for(const[c,d]of r){const h=l.get(c);if(!h){u.push(c);continue}const f=qn(d);if(!f){a.kept.push({name:c,constraint:h.constraint});continue}if(!h.isScalar){a.warnings.push(`"${c}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${f}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:c,constraint:h.constraint});continue}if(uy(h.constraint,f)){a.kept.push({name:c,constraint:h.constraint});continue}a.overrides[c]=`^${f}`,a.warnings.push(`"${c}" was pinned to ${h.constraint} in your project, which cannot resolve the ${f} the generated code needs. Raising it to ^${f} — this changes a dependency the rest of your app also uses.`)}if(u.length>0){const c=await i(u,o);for(const d of u){const h=c.get(d);if(h?.constraint){a.additions[d]=h.constraint;continue}const f=e[d]||"";if(qn(f)){a.additions[d]=`^${qn(f)}`,a.warnings.push(`Could not confirm "${d}" version on pub.dev (${h?.error||"lookup failed"}). Using ^${qn(f)} from the AI's recommendation — verify this is current.`);continue}a.additions[d]=">=0.0.0",a.warnings.push(`Could not determine a version for "${d}" (${h?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const vy={"&":"&","<":"<",">":">",'"':""","'":"'"};function Qt(t){return String(t??"").replace(/[&<>"']/g,e=>vy[e])}function z(t){return t?Qt(t).replace(/\n/g,"
    "):""}function Jt(t){return Qt(t).replace(/\r?\n/g," ")}function Ms(t,e={}){const n=t?.pipelineStep;if(n!=null&&e[n]!=null)return e[n];const i=t?.message||"";return i.includes("Code Generator")?2:i.includes("Code Review")?3:1}function Sh(t){if(!t)return{kind:"generic",title:"Generation failed",message:"An unknown error occurred. Please try again.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1};if(t.isModelArmor){const n=t.code==="MODEL_ARMOR_BLOCKED";return{kind:"safety",title:t.userTitle||"Request blocked for safety",message:t.userMessage||t.message,detail:t.retryExplanation||"",canRetry:!n,canEdit:!0,canUpgrade:!1}}if(t.isUsageLimit)return{kind:"quota",title:"Monthly limit reached",message:t.message||"You've used all your generations for this period.",detail:"",canRetry:!1,canEdit:!1,canUpgrade:!0};const e=t.message||"";return/timed out after/i.test(e)?{kind:"timeout",title:"Request timed out",message:"The generation service took too long to respond.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:/unreachable|failed to fetch|load failed|cors/i.test(e)?{kind:"network",title:"Connection problem",message:"We couldn't reach the generation service. Check your connection and try again.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:{kind:"generic",title:"Generation failed",message:e||"An unexpected error occurred.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1}}function _y(t){const e={"Integration Audit Report":"📋","Critical Issues":"❌",Warnings:"⚠️",Recommendations:"✅","Overall Score":"📊"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📄"}function yy(t){const e={critical:"❌",warning:"⚠️",recommendation:"✅",score:"📊",issue:"🔍",fix:"🔧"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📝"}function wy(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 li(t){if(!t)return"";if(typeof t!="string")return String(t);const e=/```(?:\w+)?\n?([\s\S]*?)```/,n=t.match(e);return n?n[1].trim():t.trim()}function zu(t){return t=Qt(t),t=t.replace(/\*\*(.*?)\*\*/g,'$1'),t=t.replace(/\*(.*?)\*/g,'$1'),t=t.replace(/`(.*?)`/g,'$1'),t=t.replace(/\b(FAIL|ERROR|CRITICAL)\b/g,'$1'),t=t.replace(/\b(WARN|WARNING)\b/g,'$1'),t=t.replace(/\b(PASS|SUCCESS|OK)\b/g,'$1'),t}function xh(t,e="dart",n=globalThis.hljs){if(!t)return"";const i=li(t);try{return n.highlight(i,{language:e}).value}catch(r){console.warn("Syntax highlighting failed:",r);try{return n.highlight(i,{language:"json"}).value}catch{return Qt(i)}}}function Ls(t,e={}){const{highlighter:n=globalThis.hljs}=e;let i='
    ';const r=String(t??"").split(` +`);let s=!1,o="";for(const a of r){if(a.startsWith("```")){if(s){const l=wy(o),u=xh(o.trim(),l,n);i+=`
    ${u}
    `,o="",s=!1}else s=!0;continue}if(s){o+=a+` `;continue}if(a.startsWith("# ")){const l=a.substring(2).trim();i+=`

    - ${my(l)} + ${_y(l)} ${Qt(l)}

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

    - ${vy(l)} + ${yy(l)} ${Qt(l)}

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

    ${Wu(a)}

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

    ${zu(a)}

    `)}return i+="
    ",`
    @@ -78,14 +78,14 @@ in vec2 p; void main(){ gl_Position = vec4(p, 0.0, 1.0); }`;function a(){return[
    ${i}
    - `}const yy=[[/gradient stroke\s*$/i," and an animated percentage label"],[/gauge\s*$/i," with a gradient stroke and animated fill"],[/rating\s*(bar|widget)?\s*$/i," with half-star support and haptic feedback"],[/list\s*$/i," with swipe-to-delete and an undo snackbar"],[/pad\s*$/i," that exports a transparent PNG"],[/carousel\s*$/i," with parallax cards and page indicators"],[/(button|cta)\s*$/i," with a loading spinner and success state"],[/(chart|graph)\s*$/i," that animates from a Firestore stream"],[/action\s*(that|to)?\s*$/i," uploads an image to Firebase Storage and returns the URL"],[/timer\s*$/i," with pause, resume and a completion callback"],[/map\s*$/i," with clustered markers and a custom info window"],[/^a\s+\w*$/i," widget that"],[/(picker|selector)\s*$/i," with search and multi-select"]],wy=220,by=6;function qu(t,e){return!!(t&&t.trim())&&!e}function Ey(t,e=""){if(typeof t!="string"||!t||t===e||t.trim().lengthi.test(t));return n?n[1]:null}function Sy(){let t="",e="";return{get active(){return t},resolve(n){return t=Ey(n,e)??"",t},dismiss(){t=""},accept(n){if(!t)return null;const i=n+t;return e=i,t="",i}}}function xy({onSubmit:t}){const e=document.getElementById("composer"),n=document.getElementById("pipeline-input"),i=document.getElementById("hero-send");if(!e||!n||!i||typeof t!="function")return;const r=e.querySelector(".ghost .typed"),s=e.querySelector(".ghost .suggest"),o=document.getElementById("tab-hint"),a=document.getElementById("suggest-status"),l=Array.from(document.querySelectorAll("#example-chips .chip")),u=document.getElementById("btn-add-images"),c=document.getElementById("prompt-image-input"),d=window.matchMedia("(prefers-reduced-motion: reduce)"),h=Sy();let f=!1,p=!1,g=!1,m=!1,v=null,E=null;function S(){i.disabled=!qu(n.value,p||g||m)}function _(){r&&(r.textContent=n.value)}function b(){s&&(s.textContent=""),_(),e.classList.remove("has-suggest"),o&&(o.hidden=!0,o.tabIndex=-1),a&&(a.textContent="")}function k(R){s&&(s.textContent=R),_(),e.classList.add("has-suggest"),o&&(o.hidden=!1,o.tabIndex=0,o.setAttribute("aria-label","Accept suggestion: "+R.trim())),a&&(a.textContent="Suggestion: "+R+". Press Tab to accept.")}function T(){h.dismiss(),b()}function x(){if(f||p)return;const R=h.resolve(n.value);R&&k(R)}function F(){clearTimeout(v),!f&&(v=setTimeout(x,wy))}function $(){const R=h.accept(n.value);return R===null?!1:(n.value=R,b(),S(),!0)}function O(R){p=R,e.classList.toggle("is-busy",R),i.classList.toggle("is-busy",R),i.setAttribute("aria-label",R?"Generating":"Generate"),n.readOnly=R,l.forEach(Z=>{Z.disabled=R}),u&&(u.disabled=R),c&&(c.disabled=R),S()}async function L(){if(qu(n.value,p||g||m)){T(),O(!0);try{await t()}finally{O(!1)}}}function N(){g=!1,E&&(clearInterval(E),E=null),e.classList.remove("is-demo-typing"),S()}function K(){l.forEach(R=>{R.classList.remove("is-active"),R.setAttribute("aria-pressed","false")})}function V(){try{n.focus({preventScroll:!0}),n.setSelectionRange(n.value.length,n.value.length)}catch{}}function M(R){const Z=R.dataset.prompt||"";if(N(),clearTimeout(v),v=null,T(),l.forEach(oe=>{const ye=oe===R;oe.classList.toggle("is-active",ye),oe.setAttribute("aria-pressed",String(ye))}),d.matches||!Z){n.value=Z,_(),S(),V();return}n.value="",_(),g=!0,S(),e.classList.add("is-demo-typing");let Ce=0;E=setInterval(()=>{Ce+=1,n.value=Z.slice(0,Ce),_(),Ce>=Z.length?(N(),V()):S()},22)}return l.forEach(R=>{R.setAttribute("aria-pressed","false"),R.addEventListener("click",()=>M(R))}),n.addEventListener("keydown",R=>{if(g&&R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!f){R.preventDefault();return}N(),R.key==="Tab"&&!R.shiftKey&&h.active?(R.preventDefault(),$()):R.key==="Escape"?(clearTimeout(v),v=null,T()):R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!f&&(R.preventDefault(),L())}),n.addEventListener("input",()=>{N(),K(),T(),S(),F()}),n.addEventListener("compositionstart",()=>{f=!0}),n.addEventListener("compositionend",()=>{f=!1,T(),S(),F()}),n.addEventListener("scroll",()=>{r&&r.parentNode&&(r.parentNode.scrollTop=n.scrollTop)}),o&&o.addEventListener("click",()=>{$(),n.focus({preventScroll:!0})}),i.addEventListener("click",L),n.addEventListener("pointerdown",()=>{N(),K()}),_(),S(),{setAttachmentsPending(R){m=!!R,S()}}}const Iy="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses";const _t="https://4tgke4.buildship.run",xh={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},hs="ccc_auth_session",Na="ccc_signin_return",ky=1800*1e3,zu=new WeakSet;let z={email:null,sessionToken:null,isVerified:!1};function Mn(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let ce=Mn({isResolved:!0}),Oa=Promise.resolve();const Cy=`${_t}/service/runpipeline`,Ay="bs_user_id",Py="bs_identity_token",Fy=`${_t}/authUserCheck`;let ht={userId:null,token:null,status:null,resolved:!1};const ps=lv,gs="ccc_subscription",Vu=3,Ry=new Set(["active","trialing","paid"]),ms="google/gemini-3.7-flash",Nr=["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"],Ty={"google/gemini-3.7-flash":"Gemini 3.7 Flash","anthropic/claude-opus-5":"Claude Opus 5","openai/gpt-5.6-sol":"GPT-5.6 Sol","z-ai/glm-5.2":"GLM 5.2","moonshotai/kimi-k3":"Kimi K3","openrouter/auto-beta":"OpenRouter: Auto Router","openrouter/free":"OpenRouter: Free Models","openrouter/deepseek/deepseek-v4-pro":"DeepSeek v4 Pro"};function Gt(t){return Ty[t]||t}const $y=new Set(["google/gemini-3.7-flash","anthropic/claude-opus-5","openai/gpt-5.6-sol","z-ai/glm-5.2","moonshotai/kimi-k3","openrouter/auto-beta"]);function Ih(t){return $y.has(t)}const Ba=4,Ho=8*1024*1024,My="https://4tgke4.buildship.run/service/runpipeline-image";let Ne=[];const pn=[],Ly=3e4;let kh=null;function Ny(t){return new Promise(e=>{const n=new FileReader;n.onload=()=>e(n.result),n.onerror=()=>e(null),n.readAsDataURL(t)})}async function Oy(t,e){const n=new FormData;return n.append("file",t),(await fetch(My,{method:"POST",body:n,signal:e})).json()}function By(t){if(Array.isArray(t)){const e=t[0];if(e&&typeof e=="object")for(const n of Object.keys(e)){if(n==="item"||n==="index")continue;const i=e[n];if(i&&typeof i=="object"){if(typeof i.file=="string")return i.file;if(typeof i.url=="string")return i.url}if(typeof i=="string")return i}return""}return typeof t=="string"?t:t&&typeof t=="object"&&(t.url||t.fileUrl||t.file_url||t.downloadUrl||t.imageUrl||t.image_url||t.file)||""}async function Dy(t,e,n){const i=await Ny(t);i&&Ne.includes(e)&&(e.dataUrl=i,cn());let r="";if(i)try{r=By(await Oy(t,n))}catch{r=""}return Ne.includes(e)?!i||!r?(Ne.splice(Ne.indexOf(e),1),cn(),"failed"):(e.url=r,cn(),"added"):"dropped"}function Ch(t){const e=pn.indexOf(t);e>=0&&pn.splice(e,1),Ph()}function Ah(t){t.controller.abort(),Ch(t);const e=Ne.indexOf(t.slot);e>=0&&(Ne.splice(e,1),cn())}function Ph(){kh?.setAttachmentsPending(pn.length>0)}async function jy(t){const e=Array.from(t.target.files||[]);if(!e.length)return;if(t.target.value="",y.isRunning){Ee("Wait for the current generation to finish before attaching images.","info");return}const n=e.filter(u=>u.size>Ho);n.length&&Ee(`Skipped ${n.length} image(s) over the ${(Ho/1024/1024).toFixed(0)} MB limit.`,"warning");const i=e.filter(u=>u.size<=Ho);if(!i.length)return;const r=Ba-Ne.length,s=i.slice(0,r);if(i.length>r&&Ee(`You can attach up to ${Ba} images.`,"info"),!s.length)return;const o=s.map(u=>{const c={dataUrl:null,name:u.name,url:null};Ne.push(c);const d={slot:c,controller:new AbortController},h=setTimeout(()=>d.controller.abort(),Ly);return d.job=Dy(u,c,d.controller.signal),pn.push(d),d.job.finally(()=>{clearTimeout(h),Ch(d)}),d.job});cn(),Ph();const l=(await Promise.all(o)).filter(u=>u==="failed").length;l&&Ee(`${l} image(s) could not be uploaded and were not attached.`,"error")}function Uy(t){const e=Ne[t],n=pn.find(i=>i.slot===e);if(n){Ah(n);return}Ne.splice(t,1),cn()}function cn(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",Ne.forEach((n,i)=>{const r=document.createElement("div");r.className="prompt-img-thumb"+(n.url?"":" is-pending"),r.innerHTML=(n.dataUrl?`Prompt image`:"")+``,t.appendChild(r)}),e&&(e.textContent=Ne.length>=Ba?"Image limit reached":"Add images"))}function kl(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),n=Ih(e?.value);t.classList.toggle("hidden",!n),!n&&Ne.length&&(pn.slice().forEach(Ah),Ne=[],cn())}const Fn="ccc_usage",Fh="google/gemini-3.7-flash",Rh="google/gemini-3.7-flash",kr="google/gemini-3.7-flash",Ni={professional:11,power:49},Da={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"},Or={AUD:1,USD:.65,EUR:.6,GBP:.52,CAD:.88,NZD:1.08,JPY:97,KRW:870,INR:54,SGD:.87,HKD:5.08,BRL:3.18,CNY:4.7,TWD:20.5,THB:22.5,VND:16200,IDR:10200,MYR:2.88,SEK:6.8,NOK:6.95,DKK:4.48,PLN:2.6,CZK:15.2,HUF:238,RON:2.98,TRY:20.9,AED:2.39,ILS:2.38,PHP:36.4,ZAR:11.8,RUB:58,UAH:26.8,CHF:.57,MXN:11.1,ARS:580,CLP:610,COP:2700,PEN:2.44};let Br={...Or};async function Hy(){const t=new AbortController,e=setTimeout(()=>t.abort(),5e3);try{const n=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:t.signal});if(!n.ok)return;const i=await n.json();if(i.result!=="success"||!i.rates)return;const r=i.rates,s={AUD:1},o=new Set([...Object.keys(Or),...Object.values(ja),...Object.values(Da)]);for(const a of o)a!=="AUD"&&(typeof r[a]=="number"&&r[a]>0?s[a]=r[a]:Or[a]&&(s[a]=Or[a]));Br=s}catch{}finally{clearTimeout(e)}}const ja={"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 Cl(){try{const s=Intl.DateTimeFormat().resolvedOptions().timeZone;if(s&&ja[s])return ja[s]}catch{}const e=(navigator.language||"en-US").replace("-","_"),n=Da[e];if(n)return n;const i=e.split("_")[0],r=Da[i];return r||"USD"}function Oi(t,e){const n=Br[e]??Br.USD,i=t*n,r=Math.round(i*100)/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:r>=100||r%1===0?0:2}).format(r)}catch{return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(t*Br.USD)}}const gt="ccc_api_key_",Pt="ccc_session_api_key_",Rt="ccc_encryption_key",tr="ccc_encryption_key_scope",Wy="ccc_keystore",vs="keys",nr="ccc_encryption_key_version";let Ua=null,_s=null,ir=!1,ys=!1,Gu=!1;class ws extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function Ku(){if(Gu)return;Gu=!0;const t="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(t),document.body&&Ee(t,"warning")}function Th(){return localStorage.getItem(nr)||""}function Ha(){return crypto.randomUUID?.()||Mh(crypto.getRandomValues(new Uint8Array(16)))}function qy(){const t=Th();if(t)return t;const e=Ha();return localStorage.setItem(nr,e),e}function ci(){Ua=null,_s=null,ir=!1,ys=!1}window.addEventListener("storage",t=>{t.key===nr&&ci()});function zy(){return new Promise((t,e)=>{const n=indexedDB.open(Wy,1);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(vs)||i.createObjectStore(vs)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function Al(t,e){const n=await zy();return new Promise((i,r)=>{const s=n.transaction(vs,t);let o;try{o=e(s.objectStore(vs))}catch(l){n.close(),r(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>r(o.error),s.oncomplete=()=>{n.close(),i(a)},s.onerror=()=>{n.close(),r(s.error||new Error("Encryption key transaction failed."))},s.onabort=()=>{n.close(),r(s.error||new Error("Encryption key transaction aborted."))}})}function Vy(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function Gy(){const t=await Al("readonly",e=>e.get(Rt));return Vy(t)?t:null}async function $h(t){await Al("readwrite",e=>e.put(t,Rt))}async function Ky(){ci();try{await Al("readwrite",t=>t.delete(Rt))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function Yy(){const t=sessionStorage.getItem(Rt);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await $h(e),sessionStorage.removeItem(Rt),sessionStorage.removeItem(tr),localStorage.removeItem(gt+"salt"),e}async function Yu(t){const e=sessionStorage.getItem(Rt);if(e)return ys=sessionStorage.getItem(tr)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new ws;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),i=await crypto.subtle.exportKey("jwk",n);return sessionStorage.setItem(Rt,JSON.stringify(i)),sessionStorage.setItem(tr,"session"),ys=!1,crypto.subtle.importKey("jwk",i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function Jy(t){if(sessionStorage.getItem(tr)==="session"&&sessionStorage.getItem(Rt))return Ku(),ir=!0,Yu(t);try{const e=await Gy();if(e)return e;const n=await Yy();if(n)return n;const i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await $h(i),i}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),Ku(),ir=!0,Yu(t)}}async function Pl(t={}){const{allowSessionFallbackCreation:e=!0}=t,n=qy();_s!==n&&ci();const i=Ua||Jy(e);Ua=i,_s=n;try{return await i}catch(r){throw ci(),r}}async function Zy(t){const e=await Pl(),n=_s,i=new TextEncoder,r=crypto.getRandomValues(new Uint8Array(12)),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},e,i.encode(t)),o=new Uint8Array(r.length+s.byteLength);return o.set(r),o.set(new Uint8Array(s),r.length),{ciphertext:Mh(o),keyVersion:n,sessionFallback:ir}}async function Xy(t,e={}){const{isSessionCredential:n=!1}=e;try{const i=await Pl({allowSessionFallbackCreation:!1});if(ir&&!n&&!ys)throw new ws;const r=Qy(t),s=r.slice(0,12),o=r.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},i,o);return new TextDecoder().decode(a)}catch(i){if(i instanceof ws)throw i;return console.error("Decryption failed:",i),null}}function Mh(t){const e=new Uint8Array(t);let n="";for(let i=0;i0}let Ln="",ui="",qi=null,Zu=0,tt="not-configured";async function Fl(){sessionStorage.getItem(Rt)&&await Pl(),Ln=await Te("flutterflow"),ui=await Te("flutterflow_project_id"),a0(),rn(),Ln?Ml():(tt="not-configured",vt())}let rr=!1;function Lh(){const t=document.getElementById("api-keys-modal");He(t),$l(),Ln&&Ll(Ln)}function Rl(){rr=!1,Lh()}function t0(){rr=!0;const t=document.getElementById("walkthrough-modal");t&&We(t),Lh()}let Xu=!1;function Qu(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-settings-model");if(!t||!e)return;e.value=t.value;const n=Array.from(t.options);Array.from(e.options).forEach((r,s)=>{const o=n[s];o&&(r.textContent=o.textContent)});const i=document.getElementById("composer-settings-free-notice");i&&(document.getElementById("model-selector-free-notice")?(i.hidden=!1,i.innerHTML='Free plan — Gemini only. '):i.hidden=!0)}function ed(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-image-capability"),n=document.getElementById("composer-image-capability-note");if(!t)return;const i=Gt(t.value),r=Ih(t.value);e&&(e.textContent=r?"Supported":"Not supported"),n&&(n.textContent=r?`${i} accepts reference images you attach to the prompt.`:`Images can't be attached with ${i}. Attached images are removed when you switch to it.`),kl()}function n0(){if(rr=!1,Qu(),ed(),!Xu){const e=document.getElementById("composer-settings-model");e&&e.addEventListener("change",()=>{const n=document.getElementById("code-generator-model");n.value=e.value,n.dispatchEvent(new Event("change")),Qu(),ed()}),Xu=!0}const t=document.querySelector('.composer [aria-label="Generation settings"]');He("composer-settings-modal",{trigger:t})}function i0(t){t&&t.target!==t.currentTarget||We("composer-settings-modal")}function Nh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&We(e);const n=rr;if(rr=!1,n){const i=document.getElementById("walkthrough-modal");i&&(tt==="connected"&&Tl(),He(i))}}let en=1;function Oh(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function Ns(){const t=Oh();t.length&&t.forEach((e,n)=>{const i=n+1;e.classList.remove("wt-current","wt-done","wt-pending");const r=e.querySelector(".wt-step-num");i===en?(e.classList.add("wt-current"),r&&(r.textContent=i)):i0&&en<=t&&(en++,Ns())}function r0(){const t=document.getElementById("walkthrough-modal");t&&(en=1,Ns(),He(t))}function s0(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&We(e);const n=document.getElementById("walkthrough-dont-show");n&&n.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function Bh(){if(z.isVerified&&Tt()&&ce.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(en=1,Ns(),He(e))}}async function $l(){const t=document.getElementById("flutterflow-api-key-input");Ln?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",o0()}function o0(){td("flutterflow","flutterflow-key-status"),td("flutterflow_project_id","flutterflow-project-status")}function td(t,e){const n=document.getElementById(e);if(!n)return;const i=n.querySelector(".key-status-dot"),r=n.querySelector("span");Ct(t)?(i.className="key-status-dot configured",r.className="text-green-600",r.textContent="User key configured"):(i.className="key-status-dot missing",r.className="text-gray-500",r.textContent="Not configured")}function rn(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff");e&&e.classList.toggle("hidden",!t)}function a0(){const t=document.getElementById("api-keys-status");if(!t)return;const e=t.querySelectorAll(".key-status-dot"),n=["flutterflow"];e.forEach((i,r)=>{const s=n[r];s==="flutterflow"?Ct("flutterflow")&&Ct("flutterflow_project_id")?(i.className="key-status-dot configured",i.title="FlutterFlow (Fully configured)"):Ct("flutterflow")||Ct("flutterflow_project_id")?(i.className="key-status-dot env",i.title="FlutterFlow (Partially configured)"):(i.className="key-status-dot missing",i.title="FlutterFlow (Not configured)"):Ct(s)?(i.className="key-status-dot configured",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (User key)"):(i.className="key-status-dot missing",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (Not configured)")}),rn()}async function l0(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select"),n=t.value.trim();n&&await Ju("flutterflow",n);const i=e?.value.trim()||"";if(i){if(!Os(i)){Ee("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await Ju("flutterflow_project_id",i)}await Fl(),n&&await Ml(),$l();const r=document.querySelector("#api-keys-modal .bg-blue-500"),s=r.textContent;r.textContent="Saved!",r.classList.remove("bg-blue-500","hover:bg-blue-600"),r.classList.add("bg-green-500"),setTimeout(()=>{r.textContent=s,r.classList.remove("bg-green-500"),r.classList.add("bg-blue-500","hover:bg-blue-600"),Nh()},1e3)}async function c0(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(nr,Ha()),ci(),localStorage.removeItem(gt+"flutterflow"),localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow"),sessionStorage.removeItem(Pt+"flutterflow_project_id"),sessionStorage.removeItem(Rt),sessionStorage.removeItem(tr),localStorage.removeItem(gt+"salt"),await Ky(),localStorage.setItem(nr,Ha()),localStorage.removeItem(gt+"flutterflow"),localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow"),sessionStorage.removeItem(Pt+"flutterflow_project_id"),await Fl();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),$l()}function Os(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function vt(){const t=document.getElementById("acct-ff-dot"),e=document.getElementById("acct-ff-status"),n=document.getElementById("acct-ff-endpoint"),i=document.getElementById("acct-ff-project");if(n){const o=yt();n.textContent=o.includes("staging")?"Staging":"Production"}if(i&&(i.textContent=ui||"—"),!e)return;let r,s;if(!Ct("flutterflow"))r="Not connected — add your FlutterFlow API key",s="";else switch(tt){case"connected":r="Connected to FlutterFlow",s="ok";break;case"no-projects":r="Key accepted — no projects found",s="warn";break;case"unauthorized":r="API key rejected (401/403) — re-enter your key",s="bad";break;case"network-error":r="Could not reach FlutterFlow — check your network",s="bad";break;default:r="Checking connection…",s="warn";break}e.textContent=r,t&&(t.className=`acct-dot${s?" "+s:""}`)}async function Ml(){const t=await Te("flutterflow");if(!t||!Ct("flutterflow"))return tt="not-configured",vt(),null;tt="validating",vt();try{const n=await new hi(t,"","main",yt()).listProjects();return tt=n&&n.length>0?"connected":"no-projects",vt(),n}catch(e){const n=String(e&&e.message||"");return tt=/(401|403)|denied|unauthorized|scoped|list permission/i.test(n)?"unauthorized":"network-error",vt(),null}}function u0(){ui="",localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow_project_id")}function d0(){u0();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML='',t.value=""),Ct("flutterflow")?(tt="validating",Ll(Ln)):tt="not-configured",vt()}function f0(t,e){const n=document.getElementById(t);n&&(n.value?e?n.style.borderColor="#22c55e":n.style.borderColor="#ef4444":n.style.borderColor="")}function h0(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const n=e.target.value.trim().length>0;f0("flutterflow-api-key-input",n)}),t.addEventListener("blur",p0(async e=>{const n=e.target.value.trim();n&&await Ll(n)},500)))}function p0(t,e){let n;return function(...r){const s=()=>{clearTimeout(n),t(...r)};clearTimeout(n),n=setTimeout(s,e)}}async function Ll(t){const e=document.getElementById("flutterflow-projects-select"),n=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',n&&n.classList.add("hidden"),(Ct("flutterflow")||t)&&(tt="validating"),vt();try{const r=await new hi(t,"","main",yt()).listProjects();if(!r||r.length===0){tt="no-projects",vt(),e.innerHTML='';return}tt="connected",vt(),e.innerHTML='',r.forEach(s=>{const o=document.createElement("option");o.value=s.id||s.projectId||"",o.textContent=s.name||s.projectName||`Project ${s.id}`,e.appendChild(o)}),ui&&(e.value=ui)}catch(i){console.error("Failed to fetch projects:",i);const r=String(i&&i.message||"");tt=/(401|403)|denied|unauthorized|scoped|list permission/i.test(r)?"unauthorized":"network-error",vt(),e.innerHTML='',n&&(n.textContent=`Failed to load projects: ${i.message}`,n.classList.remove("hidden"))}}function g0(t){const e=document.getElementById(t),i=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",i.innerHTML=` + `}const by=[[/gradient stroke\s*$/i," and an animated percentage label"],[/gauge\s*$/i," with a gradient stroke and animated fill"],[/rating\s*(bar|widget)?\s*$/i," with half-star support and haptic feedback"],[/list\s*$/i," with swipe-to-delete and an undo snackbar"],[/pad\s*$/i," that exports a transparent PNG"],[/carousel\s*$/i," with parallax cards and page indicators"],[/(button|cta)\s*$/i," with a loading spinner and success state"],[/(chart|graph)\s*$/i," that animates from a Firestore stream"],[/action\s*(that|to)?\s*$/i," uploads an image to Firebase Storage and returns the URL"],[/timer\s*$/i," with pause, resume and a completion callback"],[/map\s*$/i," with clustered markers and a custom info window"],[/^a\s+\w*$/i," widget that"],[/(picker|selector)\s*$/i," with search and multi-select"]],Ey=220,Sy=6;function qu(t,e){return!!(t&&t.trim())&&!e}function xy(t,e=""){if(typeof t!="string"||!t||t===e||t.trim().lengthi.test(t));return n?n[1]:null}function Iy(){let t="",e="";return{get active(){return t},resolve(n){return t=xy(n,e)??"",t},dismiss(){t=""},accept(n){if(!t)return null;const i=n+t;return e=i,t="",i}}}function ky({onSubmit:t}){const e=document.getElementById("composer"),n=document.getElementById("pipeline-input"),i=document.getElementById("hero-send");if(!e||!n||!i||typeof t!="function")return;const r=e.querySelector(".ghost .typed"),s=e.querySelector(".ghost .suggest"),o=document.getElementById("tab-hint"),a=document.getElementById("suggest-status"),l=Array.from(document.querySelectorAll("#example-chips .chip")),u=document.getElementById("btn-add-images"),c=document.getElementById("prompt-image-input"),d=window.matchMedia("(prefers-reduced-motion: reduce)"),h=Iy();let f=!1,p=!1,g=!1,m=!1,v=null,E=null;function S(){i.disabled=!qu(n.value,p||g||m)}function _(){r&&(r.textContent=n.value)}function b(){s&&(s.textContent=""),_(),e.classList.remove("has-suggest"),o&&(o.hidden=!0,o.tabIndex=-1),a&&(a.textContent="")}function k(R){s&&(s.textContent=R),_(),e.classList.add("has-suggest"),o&&(o.hidden=!1,o.tabIndex=0,o.setAttribute("aria-label","Accept suggestion: "+R.trim())),a&&(a.textContent="Suggestion: "+R+". Press Tab to accept.")}function T(){h.dismiss(),b()}function x(){if(f||p)return;const R=h.resolve(n.value);R&&k(R)}function F(){clearTimeout(v),!f&&(v=setTimeout(x,Ey))}function $(){const R=h.accept(n.value);return R===null?!1:(n.value=R,b(),S(),!0)}function O(R){p=R,e.classList.toggle("is-busy",R),i.classList.toggle("is-busy",R),i.setAttribute("aria-label",R?"Generating":"Generate"),n.readOnly=R,l.forEach(Z=>{Z.disabled=R}),u&&(u.disabled=R),c&&(c.disabled=R),S()}async function L(){if(qu(n.value,p||g||m)){T(),O(!0);try{await t()}finally{O(!1)}}}function N(){g=!1,E&&(clearInterval(E),E=null),e.classList.remove("is-demo-typing"),S()}function K(){l.forEach(R=>{R.classList.remove("is-active"),R.setAttribute("aria-pressed","false")})}function V(){try{n.focus({preventScroll:!0}),n.setSelectionRange(n.value.length,n.value.length)}catch{}}function M(R){const Z=R.dataset.prompt||"";if(N(),clearTimeout(v),v=null,T(),l.forEach(oe=>{const ye=oe===R;oe.classList.toggle("is-active",ye),oe.setAttribute("aria-pressed",String(ye))}),d.matches||!Z){n.value=Z,_(),S(),V();return}n.value="",_(),g=!0,S(),e.classList.add("is-demo-typing");let Ce=0;E=setInterval(()=>{Ce+=1,n.value=Z.slice(0,Ce),_(),Ce>=Z.length?(N(),V()):S()},22)}return l.forEach(R=>{R.setAttribute("aria-pressed","false"),R.addEventListener("click",()=>M(R))}),n.addEventListener("keydown",R=>{if(g&&R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!f){R.preventDefault();return}N(),R.key==="Tab"&&!R.shiftKey&&h.active?(R.preventDefault(),$()):R.key==="Escape"?(clearTimeout(v),v=null,T()):R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!f&&(R.preventDefault(),L())}),n.addEventListener("input",()=>{N(),K(),T(),S(),F()}),n.addEventListener("compositionstart",()=>{f=!0}),n.addEventListener("compositionend",()=>{f=!1,T(),S(),F()}),n.addEventListener("scroll",()=>{r&&r.parentNode&&(r.parentNode.scrollTop=n.scrollTop)}),o&&o.addEventListener("click",()=>{$(),n.focus({preventScroll:!0})}),i.addEventListener("click",L),n.addEventListener("pointerdown",()=>{N(),K()}),_(),S(),{setAttachmentsPending(R){m=!!R,S()}}}const Cy="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses";const _t="https://4tgke4.buildship.run",Ih={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},hs="ccc_auth_session",Na="ccc_signin_return",Ay=1800*1e3,Vu=new WeakSet;let q={email:null,sessionToken:null,isVerified:!1};function Mn(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let ce=Mn({isResolved:!0}),Oa=Promise.resolve();const Py=`${_t}/service/runpipeline`,Fy="bs_user_id",Ry="bs_identity_token",Ty=`${_t}/authUserCheck`;let ht={userId:null,token:null,status:null,resolved:!1};const ps=cv,gs="ccc_subscription",Gu=3,$y=new Set(["active","trialing","paid"]),ms="google/gemini-3.7-flash",Nr=["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"],My={"google/gemini-3.7-flash":"Gemini 3.7 Flash","anthropic/claude-opus-5":"Claude Opus 5","openai/gpt-5.6-sol":"GPT-5.6 Sol","z-ai/glm-5.2":"GLM 5.2","moonshotai/kimi-k3":"Kimi K3","openrouter/auto-beta":"OpenRouter: Auto Router","openrouter/free":"OpenRouter: Free Models","openrouter/deepseek/deepseek-v4-pro":"DeepSeek v4 Pro"};function Gt(t){return My[t]||t}const Ly=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 kh(t){return Ly.has(t)}const Ba=4,Ho=8*1024*1024,Ny="https://4tgke4.buildship.run/service/runpipeline-image";let Oe=[];const pn=[],Oy=3e4;let Ch=null;function By(t){return new Promise(e=>{const n=new FileReader;n.onload=()=>e(n.result),n.onerror=()=>e(null),n.readAsDataURL(t)})}async function Dy(t,e){const n=new FormData;return n.append("file",t),(await fetch(Ny,{method:"POST",body:n,signal:e})).json()}function jy(t){if(Array.isArray(t)){const e=t[0];if(e&&typeof e=="object")for(const n of Object.keys(e)){if(n==="item"||n==="index")continue;const i=e[n];if(i&&typeof i=="object"){if(typeof i.file=="string")return i.file;if(typeof i.url=="string")return i.url}if(typeof i=="string")return i}return""}return typeof t=="string"?t:t&&typeof t=="object"&&(t.url||t.fileUrl||t.file_url||t.downloadUrl||t.imageUrl||t.image_url||t.file)||""}async function Uy(t,e,n){const i=await By(t);i&&Oe.includes(e)&&(e.dataUrl=i,cn());let r="";if(i)try{r=jy(await Dy(t,n))}catch{r=""}return Oe.includes(e)?!i||!r?(Oe.splice(Oe.indexOf(e),1),cn(),"failed"):(e.url=r,cn(),"added"):"dropped"}function Ah(t){const e=pn.indexOf(t);e>=0&&pn.splice(e,1),Fh()}function Ph(t){t.controller.abort(),Ah(t);const e=Oe.indexOf(t.slot);e>=0&&(Oe.splice(e,1),cn())}function Fh(){Ch?.setAttachmentsPending(pn.length>0)}async function Hy(t){const e=Array.from(t.target.files||[]);if(!e.length)return;if(t.target.value="",y.isRunning){Ee("Wait for the current generation to finish before attaching images.","info");return}const n=e.filter(u=>u.size>Ho);n.length&&Ee(`Skipped ${n.length} image(s) over the ${(Ho/1024/1024).toFixed(0)} MB limit.`,"warning");const i=e.filter(u=>u.size<=Ho);if(!i.length)return;const r=Ba-Oe.length,s=i.slice(0,r);if(i.length>r&&Ee(`You can attach up to ${Ba} images.`,"info"),!s.length)return;const o=s.map(u=>{const c={dataUrl:null,name:u.name,url:null};Oe.push(c);const d={slot:c,controller:new AbortController},h=setTimeout(()=>d.controller.abort(),Oy);return d.job=Uy(u,c,d.controller.signal),pn.push(d),d.job.finally(()=>{clearTimeout(h),Ah(d)}),d.job});cn(),Fh();const l=(await Promise.all(o)).filter(u=>u==="failed").length;l&&Ee(`${l} image(s) could not be uploaded and were not attached.`,"error")}function Wy(t){const e=Oe[t],n=pn.find(i=>i.slot===e);if(n){Ph(n);return}Oe.splice(t,1),cn()}function cn(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",Oe.forEach((n,i)=>{const r=document.createElement("div");r.className="prompt-img-thumb"+(n.url?"":" is-pending"),r.innerHTML=(n.dataUrl?`Prompt image`:"")+``,t.appendChild(r)}),e&&(e.textContent=Oe.length>=Ba?"Image limit reached":"Add images"))}function kl(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),n=kh(e?.value);t.classList.toggle("hidden",!n),!n&&Oe.length&&(pn.slice().forEach(Ph),Oe=[],cn())}const Fn="ccc_usage",Rh="google/gemini-3.7-flash",Th="google/gemini-3.7-flash",kr="google/gemini-3.7-flash",Ni={professional:11,power:49},Da={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"},Or={AUD:1,USD:.65,EUR:.6,GBP:.52,CAD:.88,NZD:1.08,JPY:97,KRW:870,INR:54,SGD:.87,HKD:5.08,BRL:3.18,CNY:4.7,TWD:20.5,THB:22.5,VND:16200,IDR:10200,MYR:2.88,SEK:6.8,NOK:6.95,DKK:4.48,PLN:2.6,CZK:15.2,HUF:238,RON:2.98,TRY:20.9,AED:2.39,ILS:2.38,PHP:36.4,ZAR:11.8,RUB:58,UAH:26.8,CHF:.57,MXN:11.1,ARS:580,CLP:610,COP:2700,PEN:2.44};let Br={...Or};async function zy(){const t=new AbortController,e=setTimeout(()=>t.abort(),5e3);try{const n=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:t.signal});if(!n.ok)return;const i=await n.json();if(i.result!=="success"||!i.rates)return;const r=i.rates,s={AUD:1},o=new Set([...Object.keys(Or),...Object.values(ja),...Object.values(Da)]);for(const a of o)a!=="AUD"&&(typeof r[a]=="number"&&r[a]>0?s[a]=r[a]:Or[a]&&(s[a]=Or[a]));Br=s}catch{}finally{clearTimeout(e)}}const ja={"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 Cl(){try{const s=Intl.DateTimeFormat().resolvedOptions().timeZone;if(s&&ja[s])return ja[s]}catch{}const e=(navigator.language||"en-US").replace("-","_"),n=Da[e];if(n)return n;const i=e.split("_")[0],r=Da[i];return r||"USD"}function Oi(t,e){const n=Br[e]??Br.USD,i=t*n,r=Math.round(i*100)/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:r>=100||r%1===0?0:2}).format(r)}catch{return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(t*Br.USD)}}const gt="ccc_api_key_",Pt="ccc_session_api_key_",Rt="ccc_encryption_key",tr="ccc_encryption_key_scope",qy="ccc_keystore",vs="keys",nr="ccc_encryption_key_version";let Ua=null,_s=null,ir=!1,ys=!1,Ku=!1;class ws extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function Yu(){if(Ku)return;Ku=!0;const t="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(t),document.body&&Ee(t,"warning")}function $h(){return localStorage.getItem(nr)||""}function Ha(){return crypto.randomUUID?.()||Lh(crypto.getRandomValues(new Uint8Array(16)))}function Vy(){const t=$h();if(t)return t;const e=Ha();return localStorage.setItem(nr,e),e}function ci(){Ua=null,_s=null,ir=!1,ys=!1}window.addEventListener("storage",t=>{t.key===nr&&ci()});function Gy(){return new Promise((t,e)=>{const n=indexedDB.open(qy,1);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(vs)||i.createObjectStore(vs)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function Al(t,e){const n=await Gy();return new Promise((i,r)=>{const s=n.transaction(vs,t);let o;try{o=e(s.objectStore(vs))}catch(l){n.close(),r(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>r(o.error),s.oncomplete=()=>{n.close(),i(a)},s.onerror=()=>{n.close(),r(s.error||new Error("Encryption key transaction failed."))},s.onabort=()=>{n.close(),r(s.error||new Error("Encryption key transaction aborted."))}})}function Ky(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function Yy(){const t=await Al("readonly",e=>e.get(Rt));return Ky(t)?t:null}async function Mh(t){await Al("readwrite",e=>e.put(t,Rt))}async function Jy(){ci();try{await Al("readwrite",t=>t.delete(Rt))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function Zy(){const t=sessionStorage.getItem(Rt);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Mh(e),sessionStorage.removeItem(Rt),sessionStorage.removeItem(tr),localStorage.removeItem(gt+"salt"),e}async function Ju(t){const e=sessionStorage.getItem(Rt);if(e)return ys=sessionStorage.getItem(tr)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new ws;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),i=await crypto.subtle.exportKey("jwk",n);return sessionStorage.setItem(Rt,JSON.stringify(i)),sessionStorage.setItem(tr,"session"),ys=!1,crypto.subtle.importKey("jwk",i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function Xy(t){if(sessionStorage.getItem(tr)==="session"&&sessionStorage.getItem(Rt))return Yu(),ir=!0,Ju(t);try{const e=await Yy();if(e)return e;const n=await Zy();if(n)return n;const i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Mh(i),i}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),Yu(),ir=!0,Ju(t)}}async function Pl(t={}){const{allowSessionFallbackCreation:e=!0}=t,n=Vy();_s!==n&&ci();const i=Ua||Xy(e);Ua=i,_s=n;try{return await i}catch(r){throw ci(),r}}async function Qy(t){const e=await Pl(),n=_s,i=new TextEncoder,r=crypto.getRandomValues(new Uint8Array(12)),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},e,i.encode(t)),o=new Uint8Array(r.length+s.byteLength);return o.set(r),o.set(new Uint8Array(s),r.length),{ciphertext:Lh(o),keyVersion:n,sessionFallback:ir}}async function e0(t,e={}){const{isSessionCredential:n=!1}=e;try{const i=await Pl({allowSessionFallbackCreation:!1});if(ir&&!n&&!ys)throw new ws;const r=t0(t),s=r.slice(0,12),o=r.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},i,o);return new TextDecoder().decode(a)}catch(i){if(i instanceof ws)throw i;return console.error("Decryption failed:",i),null}}function Lh(t){const e=new Uint8Array(t);let n="";for(let i=0;i0}let Ln="",ui="",zi=null,Xu=0,nt="not-configured";async function Fl(){sessionStorage.getItem(Rt)&&await Pl(),Ln=await Te("flutterflow"),ui=await Te("flutterflow_project_id"),c0(),rn(),Ln?Ml():(nt="not-configured",vt())}let rr=!1;function Nh(){const t=document.getElementById("api-keys-modal");We(t),$l(),Ln&&Ll(Ln)}function Rl(){rr=!1,Nh()}function i0(){rr=!0;const t=document.getElementById("walkthrough-modal");t&&ze(t),Nh()}let Qu=!1;function ed(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-settings-model");if(!t||!e)return;e.value=t.value;const n=Array.from(t.options);Array.from(e.options).forEach((r,s)=>{const o=n[s];o&&(r.textContent=o.textContent)});const i=document.getElementById("composer-settings-free-notice");i&&(document.getElementById("model-selector-free-notice")?(i.hidden=!1,i.innerHTML='Free plan — Gemini only. '):i.hidden=!0)}function td(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-image-capability"),n=document.getElementById("composer-image-capability-note");if(!t)return;const i=Gt(t.value),r=kh(t.value);e&&(e.textContent=r?"Supported":"Not supported"),n&&(n.textContent=r?`${i} accepts reference images you attach to the prompt.`:`Images can't be attached with ${i}. Attached images are removed when you switch to it.`),kl()}function r0(){if(rr=!1,ed(),td(),!Qu){const e=document.getElementById("composer-settings-model");e&&e.addEventListener("change",()=>{const n=document.getElementById("code-generator-model");n.value=e.value,n.dispatchEvent(new Event("change")),ed(),td()}),Qu=!0}const t=document.querySelector('.composer [aria-label="Generation settings"]');We("composer-settings-modal",{trigger:t})}function s0(t){t&&t.target!==t.currentTarget||ze("composer-settings-modal")}function Oh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&ze(e);const n=rr;if(rr=!1,n){const i=document.getElementById("walkthrough-modal");i&&(nt==="connected"&&Tl(),We(i))}}let en=1;function Bh(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function Ns(){const t=Bh();t.length&&t.forEach((e,n)=>{const i=n+1;e.classList.remove("wt-current","wt-done","wt-pending");const r=e.querySelector(".wt-step-num");i===en?(e.classList.add("wt-current"),r&&(r.textContent=i)):i0&&en<=t&&(en++,Ns())}function o0(){const t=document.getElementById("walkthrough-modal");t&&(en=1,Ns(),We(t))}function a0(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&ze(e);const n=document.getElementById("walkthrough-dont-show");n&&n.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function Dh(){if(q.isVerified&&Tt()&&ce.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(en=1,Ns(),We(e))}}async function $l(){const t=document.getElementById("flutterflow-api-key-input");Ln?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",l0()}function l0(){nd("flutterflow","flutterflow-key-status"),nd("flutterflow_project_id","flutterflow-project-status")}function nd(t,e){const n=document.getElementById(e);if(!n)return;const i=n.querySelector(".key-status-dot"),r=n.querySelector("span");Ct(t)?(i.className="key-status-dot configured",r.className="text-green-600",r.textContent="User key configured"):(i.className="key-status-dot missing",r.className="text-gray-500",r.textContent="Not configured")}function rn(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff");e&&e.classList.toggle("hidden",!t)}function c0(){const t=document.getElementById("api-keys-status");if(!t)return;const e=t.querySelectorAll(".key-status-dot"),n=["flutterflow"];e.forEach((i,r)=>{const s=n[r];s==="flutterflow"?Ct("flutterflow")&&Ct("flutterflow_project_id")?(i.className="key-status-dot configured",i.title="FlutterFlow (Fully configured)"):Ct("flutterflow")||Ct("flutterflow_project_id")?(i.className="key-status-dot env",i.title="FlutterFlow (Partially configured)"):(i.className="key-status-dot missing",i.title="FlutterFlow (Not configured)"):Ct(s)?(i.className="key-status-dot configured",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (User key)"):(i.className="key-status-dot missing",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (Not configured)")}),rn()}async function u0(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select"),n=t.value.trim();n&&await Zu("flutterflow",n);const i=e?.value.trim()||"";if(i){if(!Os(i)){Ee("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await Zu("flutterflow_project_id",i)}await Fl(),n&&await Ml(),$l();const r=document.querySelector("#api-keys-modal .bg-blue-500"),s=r.textContent;r.textContent="Saved!",r.classList.remove("bg-blue-500","hover:bg-blue-600"),r.classList.add("bg-green-500"),setTimeout(()=>{r.textContent=s,r.classList.remove("bg-green-500"),r.classList.add("bg-blue-500","hover:bg-blue-600"),Oh()},1e3)}async function d0(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(nr,Ha()),ci(),localStorage.removeItem(gt+"flutterflow"),localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow"),sessionStorage.removeItem(Pt+"flutterflow_project_id"),sessionStorage.removeItem(Rt),sessionStorage.removeItem(tr),localStorage.removeItem(gt+"salt"),await Jy(),localStorage.setItem(nr,Ha()),localStorage.removeItem(gt+"flutterflow"),localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow"),sessionStorage.removeItem(Pt+"flutterflow_project_id"),await Fl();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),$l()}function Os(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function vt(){const t=document.getElementById("acct-ff-dot"),e=document.getElementById("acct-ff-status"),n=document.getElementById("acct-ff-endpoint"),i=document.getElementById("acct-ff-project");if(n){const o=yt();n.textContent=o.includes("staging")?"Staging":"Production"}if(i&&(i.textContent=ui||"—"),!e)return;let r,s;if(!Ct("flutterflow"))r="Not connected — add your FlutterFlow API key",s="";else switch(nt){case"connected":r="Connected to FlutterFlow",s="ok";break;case"no-projects":r="Key accepted — no projects found",s="warn";break;case"unauthorized":r="API key rejected (401/403) — re-enter your key",s="bad";break;case"network-error":r="Could not reach FlutterFlow — check your network",s="bad";break;default:r="Checking connection…",s="warn";break}e.textContent=r,t&&(t.className=`acct-dot${s?" "+s:""}`)}async function Ml(){const t=await Te("flutterflow");if(!t||!Ct("flutterflow"))return nt="not-configured",vt(),null;nt="validating",vt();try{const n=await new hi(t,"","main",yt()).listProjects();return nt=n&&n.length>0?"connected":"no-projects",vt(),n}catch(e){const n=String(e&&e.message||"");return nt=/(401|403)|denied|unauthorized|scoped|list permission/i.test(n)?"unauthorized":"network-error",vt(),null}}function f0(){ui="",localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow_project_id")}function h0(){f0();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML='',t.value=""),Ct("flutterflow")?(nt="validating",Ll(Ln)):nt="not-configured",vt()}function p0(t,e){const n=document.getElementById(t);n&&(n.value?e?n.style.borderColor="#22c55e":n.style.borderColor="#ef4444":n.style.borderColor="")}function g0(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const n=e.target.value.trim().length>0;p0("flutterflow-api-key-input",n)}),t.addEventListener("blur",m0(async e=>{const n=e.target.value.trim();n&&await Ll(n)},500)))}function m0(t,e){let n;return function(...r){const s=()=>{clearTimeout(n),t(...r)};clearTimeout(n),n=setTimeout(s,e)}}async function Ll(t){const e=document.getElementById("flutterflow-projects-select"),n=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',n&&n.classList.add("hidden"),(Ct("flutterflow")||t)&&(nt="validating"),vt();try{const r=await new hi(t,"","main",yt()).listProjects();if(!r||r.length===0){nt="no-projects",vt(),e.innerHTML='';return}nt="connected",vt(),e.innerHTML='',r.forEach(s=>{const o=document.createElement("option");o.value=s.id||s.projectId||"",o.textContent=s.name||s.projectName||`Project ${s.id}`,e.appendChild(o)}),ui&&(e.value=ui)}catch(i){console.error("Failed to fetch projects:",i);const r=String(i&&i.message||"");nt=/(401|403)|denied|unauthorized|scoped|list permission/i.test(r)?"unauthorized":"network-error",vt(),e.innerHTML='',n&&(n.textContent=`Failed to load projects: ${i.message}`,n.classList.remove("hidden"))}}function v0(t){const e=document.getElementById(t),i=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",i.innerHTML=` `):(e.type="password",i.innerHTML=` - `)}let y={step1Result:null,step2Result:null,step3Result:null,bundleSpec:null,artifactBundle:null,bundleReview:null,selectedArtifactId:null,resultsViewMode:"summary",currentStep:0,isRunning:!1,runId:0,submittedPrompt:"",submittedImages:[]};function m0(){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 v0(){y.bundleSpec=Qi(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function Bs(){const t=oi(y.bundleSpec);y.artifactBundle=Qi(y.step2Result,{id:y.bundleSpec?.id,title:y.bundleSpec?.title,description:y.bundleSpec?.description,artifactType:t.artifactType,artifactName:t.artifactName,fileName:t.fileName,dependencies:t.dependencies,relationships:y.bundleSpec?.relationships,code:y.step2Result||""});const e=Wv(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(n=>n.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=oi(y.artifactBundle).id}function Ds(){const t=Qi(y.step3Result,{id:y.artifactBundle?.id,title:y.artifactBundle?.title}),e=new Map(t.artifacts.map(i=>[i.id,i.review])),n=new Map(t.artifacts.filter(i=>{const r=i.review;return r&&typeof r.fixedSource=="string"&&r.fixedSource.trim()}).map(i=>[i.id,i.review.fixedSource.trim()]));y.bundleReview=Qi({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(i=>{const r=n.get(i.id)||null;return{...i,review:e.get(i.id)||i.review||y.step3Result||null,...r?{fixedCode:r}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function Dh(){const t=Nl();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function Nl(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(n=>n.id===y.selectedArtifactId)||oi(t)}function Ol(){return Nl().code||y.step2Result||""}async function _0(){try{await Fl()}catch(t){return console.error("checkConnection: initializeApiKeys failed:",t),!1}return!0}const Dr={production:"https://api.flutterflow.io/v2/",staging:"https://api.flutterflow.io/v2-staging/"};function y0(t,e){const n=e?.trim()?` (${e.trim().slice(0,200)})`:"";return t===401?`Your FlutterFlow API key was rejected (401 Unauthorized)${n}. Re-enter a current key under API Keys settings, then try again.`:`Listing FlutterFlow projects was denied (403)${n}. The key may be scoped to sync a single project without list permission - verify the key's access in FlutterFlow, re-enter it under API Keys settings, then retry.`}class hi{constructor(e,n,i="main",r=Dr.production){this.apiKey=e,this.baseUrl=r,this._projectId=n,this._branchName=i,this._endpoint=r}get projectId(){return this._projectId}get branchName(){return this._branchName==="main"?"":this._branchName}async exportProjectZip(){console.log(`Exporting code from FlutterFlow project: ${this.projectId}, branch: ${this.branchName||"main"}`);const e=[{project:{path:`projects/${this.projectId}`},...this.branchName?{branch_name:this.branchName}:{},export_as_module:!1,include_assets_map:!1,format:!1,export_as_debug:!1},{project_id:this.projectId,branch_name:this.branchName,include_assets:!1,export_as_module:!1}];let n=null;for(const i of e)try{const r=await fetch(`${this.baseUrl}exportCode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(i)});if(!r.ok){const a=await r.text();n=new Error(`Export failed: ${r.status} - ${a}`);continue}const s=await r.json(),o=s?.value?.project_zip||s?.project_zip;if(!o){n=new Error("Export response did not include project source.");continue}return o}catch(r){n=r}throw n||new Error("Export failed for an unknown reason.")}async fetchProjectSource(){const e=await this.exportProjectZip(),n=await JSZip.loadAsync(e,{base64:!0}),i=Object.keys(n.files).filter(a=>!n.files[a].dir&&(a==="pubspec.yaml"||a.endsWith("/pubspec.yaml"))).sort((a,l)=>a.split("/").length-l.split("/").length)[0];if(!i)throw new Error("Export did not contain a pubspec.yaml.");const r=i.slice(0,i.length-12),s=new Map,o=Object.keys(n.files).filter(a=>{if(n.files[a].dir||!a.startsWith(r))return!1;const l=a.slice(r.length);return l==="lib/flutter_flow/custom_functions.dart"||l.startsWith("lib/custom_code/")&&l.endsWith(".dart")});return await Promise.all(o.map(async a=>{s.set(a.slice(r.length),await n.files[a].async("string"))})),{pubspecYaml:await n.files[i].async("string"),files:s}}async pushCodeWithRetry(e,n=3,i=null){const r=[Dr.production,Dr.staging],s=Math.max(0,r.indexOf(this._endpoint));let o=!1,a=null;for(let l=0;lsetTimeout(p,1e3*(l+1)));continue}if(d.ok)return console.log(`Push to ${c} succeeded!`),d;a=d.status;let h;try{h=await d.clone().text()}catch{h="(unreadable response body)"}if(console.log(`Push to ${c} returned ${d.status}: ${h}`),d.status>=500&&(o=!0),d.status===500){console.warn(`Endpoint ${c} returned 500, trying next...`),await new Promise(f=>setTimeout(f,1e3*(l+1)));continue}if(d.status>=500)throw new lt(`FlutterFlow reported a server error (HTTP ${d.status}), which cannot prove the push was refused — the write may have been applied before the failure. Open your FlutterFlow project to reconcile before retrying.`);if(o)throw new lt(`The push was refused (HTTP ${d.status}), but an earlier sync attempt may already have applied it — server errors and dropped responses cannot prove a refusal. Open your FlutterFlow project to reconcile before retrying.`);return d}throw ju({httpStatus:a})}async pushCode(e,n=null){return this.pushCodeWithRetry(e,3,n)}parseProjectsResponse(e){if(e?.success&&typeof e.value=="string")try{const i=JSON.parse(e.value);if(i&&Array.isArray(i.entries))return i.entries.map(r=>({id:r.id,name:r.project?.name||r.id}))}catch(i){console.error("Failed to parse stringified project value:",i)}const n=e?.projects||e?.items||e?.entries||(Array.isArray(e)?e:[]);return Array.isArray(n)?n:[]}async listProjects(){console.log("Listing projects for API key");const e=[`${this.baseUrl}listProjects`,"https://api.flutterflow.io/v2/l/listProjects"];let n=0,i="";for(const r of e){const s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({project_type:"ALL",deserialize_response:!0})});if(s.ok)return r!==e[0]&&console.log(`listProjects answered on legacy path ${r}`),this.parseProjectsResponse(await s.json());if(n=s.status,i=await s.text(),console.warn(`listProjects via ${r} returned ${n}: ${i}`),s.status===401||s.status===403)throw new Error(y0(s.status,i));if(s.status!==404)throw new Error(`List projects failed: ${s.status} - ${i}`)}throw new Error(`List projects failed: ${n} - ${i}`)}}async function w0(t){const e=t.clone();let n;try{n=await t.json()}catch{let s="";try{s=await e.text()}catch{}if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:s||`HTTP ${t.status}`,errorMap:new Map};throw new lt(`FlutterFlow accepted the sync but returned an unreadable response${s?`: ${s.slice(0,200)}`:"."}`)}if(!t.ok){let r=n.message||`HTTP ${t.status}`,s=new Map;if(n.errors)s=new Map(Object.entries(n.errors));else if(!n.message&&typeof n=="object"){const o=Object.keys(n).filter(a=>a.endsWith(".dart")&&Array.isArray(n[a]));o.length>0&&(s=new Map(Object.entries(n)),r=o.flatMap(l=>n[l].map(u=>`${l}: ${u.errorMessage}`)).join(` -`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:r,errorMap:s}}let i={};if(n.value)try{i=typeof n.value=="string"?JSON.parse(n.value):n.value}catch(r){console.warn("Ignoring malformed push response value:",r)}return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(i))}}function Bl(t,e){return{401:"Authentication failed. Please check your FlutterFlow API key.",403:"Access denied. You may not have permission to modify this project.",404:"Project not found. Please check your Project ID.",409:"Conflict detected. The project may have been modified elsewhere.",422:"Validation failed: Invalid request format",429:"Rate limit exceeded. Please try again in a few minutes.",500:"FlutterFlow server error. Please try again later.",503:"FlutterFlow service temporarily unavailable."}[t]||`FlutterFlow API error: ${`HTTP ${t}`}`}const J={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},jh=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,Uh=/extends\s+State<\w+>/;function b0(t,e=""){if(t==="pubspec.yaml")return J.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return J.OTHER;if(t==="custom_functions.dart")return J.FUNCTION;if(e){const n=jh.test(e),i=Uh.test(e);if(n||i)return J.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return J.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return J.FUNCTION}return J.CODE_FILE}function Hh(t,e){switch(e){case J.ACTION:return`lib/custom_code/actions/${t}`;case J.WIDGET:return`lib/custom_code/widgets/${t}`;case J.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case J.CODE_FILE:return`lib/custom_code/${t}`;case J.DEPENDENCIES:return"pubspec.yaml";case J.OTHER:return`lib/custom_code/${t}`;default:return t}}async function Dl(t,e=new Map){return Iv(t,e)}const Wa=new Map;function Wh(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function sr(t){Wa.delete(Wh(t))}function qh(t,e,n){return new Promise((i,r)=>{let s=!1;const o=(l,u,c)=>{s||(s=!0,c==="resolve"?i(u):r(u))},a=setTimeout(()=>{s||(s=!0,n(i,r))},e);t.then(l=>{clearTimeout(a),o(i,l,"resolve")},l=>{clearTimeout(a),o(r,l,"reject")})})}async function jl(t,e,n=yh){const i={stop:!1};return qh((async()=>{const r=await t.pushCode(e,i);return w0(r)})(),n,(r,s)=>{i.stop=!0,s(new lt("FlutterFlow did not answer the sync in time — the push may still have been applied. The outcome is not yet known: open your FlutterFlow project to reconcile before retrying the deploy."))})}async function Ul(t,e,n,i,r="",s=yh){const o=i_(e,n);if(o.length===0)return{remoteFiles:n,syncFileMap:e,unverified:[],approximate:[]};const a=Y_(o,r),l={...a.manifest,sources:a.sources},u=a.skipped.map(f=>f.reason);u.forEach(f=>console.warn(`[custom class deploy] ${f}`));const c=a.approximate;c.forEach(f=>console.warn(`[custom class deploy] ${f}`)),console.log(`Provisioning ${o.length} new FlutterFlow custom code file(s) before sync.`),Oe.set("provision");let d=!0,h;try{if(h=await qh((async()=>{let f;try{f=await fetch(Iy,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:i,customClasses:o,verification:l,stream:!0})})}catch{throw new lt("The provisioning request did not return a response. The deploy may have reached the FlutterFlow server — open your FlutterFlow project to reconcile before retrying.")}return Z_(f,{onPhase:p=>{d&&Oe.setSubstatus(p)},onLog:p=>{d&&console.log(`[custom class deploy] ${p}`)}})})(),s,(f,p)=>{d=!1,p(new lt("The deploy is still working on the FlutterFlow server, but this browser tab has stopped waiting. Your custom classes may or may not have been written — the outcome is not yet known. Open your FlutterFlow project to reconcile before retrying the deploy."))}),!h.finalResultReceived){if(X_(h)===Xe.FAILED){const f=new Error(h.error||`FlutterFlow custom class provisioning failed (HTTP ${h.httpStatus}).`);throw f.remoteRefusal=!0,f}throw new lt("The connection to the FlutterFlow deploy runner dropped before it reported a result. The deploy may still be finishing on the server; open your FlutterFlow project to reconcile before retrying.")}}catch(f){throw f instanceof lt&&sr(t),f}if(!h.success){const f=h.details?` ${h.details}`:"",p=new Error(`${h.error||"FlutterFlow custom class provisioning failed."}${f}`);throw p.remoteRefusal=!0,p}return sr(t),h.verificationSkipped&&(console.warn(`[custom class deploy] ${h.verificationSkipped}`),u.push(h.verificationSkipped)),{remoteFiles:n,syncFileMap:r_(e,o),unverified:u,approximate:c,provisionSucceeded:!0}}async function Hl(t,e={}){const n=Wh(t);let i=Wa.get(n);if(i===void 0){try{i=await t.fetchProjectSource()}catch(l){throw new Error(`Could not read your project's pubspec.yaml (${l.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=vh(i.pubspecYaml);if(!a.valid)throw new Error(`Your project's pubspec.yaml could not be read reliably (${a.errors.join("; ")}). Deploy was stopped so your existing package dependencies aren't overwritten.`);Wa.set(n,i)}const r=await py(i.pubspecYaml,e),s=q_(i.pubspecYaml,r.overrides),o=W_(s.yaml,r.additions);return r.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>`${a}: ${r.additions[a]||"any"}`).join(", "),r.sdk.dartSdkFloor?`(resolved for Dart ${r.sdk.dartSdkFloor})`:""),r.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:s.overridden,warnings:r.warnings,remoteFiles:i.files}}function E0(t){const e=[],n=[];t.content.length>5e4&&n.push("Code file is large (>50KB). This may take longer to commit."),t.content.length>1e5&&e.push("Code file is too large (>100KB). Consider splitting into smaller components.");const i=t.content.split(` -`).length;i>500&&n.push(`Code has ${i} lines. Consider breaking it into smaller widgets.`),t.content.includes("setState")&&t.codeType===J.ACTION&&n.push("Using setState in a Custom Action may not work as expected. Consider using a Custom Widget."),t.content.includes("dynamic")&&!t.content.includes("?")&&n.push('Code uses "dynamic" types. Consider adding explicit types for better null safety.'),t.content.match(/Color\(0xFF[0-9A-Fa-f]{6}\)/)&&n.push("Code contains hardcoded colors. Consider using FlutterFlowTheme.of(context) for theme consistency.");const r=t.content.match(/print\s*\(/g);r&&r.length>3&&n.push(`Code contains ${r.length} print statements. Consider removing debug prints before committing.`);const s=E_(t.content);if(s&&e.push(`FlutterFlow cannot format this code - ${s}. Fix or regenerate before committing.`),t.codeType===J.WIDGET){const o=lh(t.content),a=y_(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=`${ch(o[0])}`;e.push(`Widget class name "${o[0]}" does not match the file name "${t.fileName}". FlutterFlow derives the widget from the file name, so it will report "No widget ${a} found". Rename the file to "${l}" or the class to match before committing.`)}}return{canProceed:e.length===0,issues:e,warnings:n}}function zh(t,e={}){const{artifactType:n="CustomWidget",artifactName:i="GeneratedCode",fileName:r}=e,s=v_(t);let o=r||i;if(n==="CustomFunction")o="custom_functions.dart";else if(n==="CustomWidget"){const u=lh(s)[0],c=u?ch(u):null;c&&o!==c?(console.warn(`Commit file name "${o}" does not match declared widget class "${u}"; renaming to "${c}" so FlutterFlow can find the widget.`),o=c):o.endsWith(".dart")||(o+=".dart")}else o.endsWith(".dart")||(o+=".dart");let a=J.CODE_FILE;switch(n){case"CustomAction":a=J.ACTION;break;case"CustomWidget":a=J.WIDGET;break;case"CustomFunction":a=J.FUNCTION;break;case"CustomClass":case"CodeFile":a=J.CODE_FILE;break}let l="";return a===J.WIDGET?l=`// Automatic FlutterFlow imports + `)}let y={step1Result:null,step2Result:null,step3Result:null,bundleSpec:null,artifactBundle:null,bundleReview:null,selectedArtifactId:null,resultsViewMode:"summary",currentStep:0,isRunning:!1,runId:0,submittedPrompt:"",submittedImages:[]};function _0(){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 y0(){y.bundleSpec=Qi(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function Bs(){const t=oi(y.bundleSpec);y.artifactBundle=Qi(y.step2Result,{id:y.bundleSpec?.id,title:y.bundleSpec?.title,description:y.bundleSpec?.description,artifactType:t.artifactType,artifactName:t.artifactName,fileName:t.fileName,dependencies:t.dependencies,relationships:y.bundleSpec?.relationships,code:y.step2Result||""});const e=zv(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(n=>n.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=oi(y.artifactBundle).id}function Ds(){const t=Qi(y.step3Result,{id:y.artifactBundle?.id,title:y.artifactBundle?.title}),e=new Map(t.artifacts.map(i=>[i.id,i.review])),n=new Map(t.artifacts.filter(i=>{const r=i.review;return r&&typeof r.fixedSource=="string"&&r.fixedSource.trim()}).map(i=>[i.id,i.review.fixedSource.trim()]));y.bundleReview=Qi({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(i=>{const r=n.get(i.id)||null;return{...i,review:e.get(i.id)||i.review||y.step3Result||null,...r?{fixedCode:r}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function jh(){const t=Nl();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function Nl(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(n=>n.id===y.selectedArtifactId)||oi(t)}function Ol(){return Nl().code||y.step2Result||""}async function w0(){try{await Fl()}catch(t){return console.error("checkConnection: initializeApiKeys failed:",t),!1}return!0}const Dr={production:"https://api.flutterflow.io/v2/",staging:"https://api.flutterflow.io/v2-staging/"};function b0(t,e){const n=e?.trim()?` (${e.trim().slice(0,200)})`:"";return t===401?`Your FlutterFlow API key was rejected (401 Unauthorized)${n}. Re-enter a current key under API Keys settings, then try again.`:`Listing FlutterFlow projects was denied (403)${n}. The key may be scoped to sync a single project without list permission - verify the key's access in FlutterFlow, re-enter it under API Keys settings, then retry.`}class hi{constructor(e,n,i="main",r=Dr.production){this.apiKey=e,this.baseUrl=r,this._projectId=n,this._branchName=i,this._endpoint=r}get projectId(){return this._projectId}get branchName(){return this._branchName==="main"?"":this._branchName}async exportProjectZip(){console.log(`Exporting code from FlutterFlow project: ${this.projectId}, branch: ${this.branchName||"main"}`);const e=[{project:{path:`projects/${this.projectId}`},...this.branchName?{branch_name:this.branchName}:{},export_as_module:!1,include_assets_map:!1,format:!1,export_as_debug:!1},{project_id:this.projectId,branch_name:this.branchName,include_assets:!1,export_as_module:!1}];let n=null;for(const i of e)try{const r=await fetch(`${this.baseUrl}exportCode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(i)});if(!r.ok){const a=await r.text();n=new Error(`Export failed: ${r.status} - ${a}`);continue}const s=await r.json(),o=s?.value?.project_zip||s?.project_zip;if(!o){n=new Error("Export response did not include project source.");continue}return o}catch(r){n=r}throw n||new Error("Export failed for an unknown reason.")}async fetchProjectSource(){const e=await this.exportProjectZip(),n=await JSZip.loadAsync(e,{base64:!0}),i=Object.keys(n.files).filter(a=>!n.files[a].dir&&(a==="pubspec.yaml"||a.endsWith("/pubspec.yaml"))).sort((a,l)=>a.split("/").length-l.split("/").length)[0];if(!i)throw new Error("Export did not contain a pubspec.yaml.");const r=i.slice(0,i.length-12),s=new Map,o=Object.keys(n.files).filter(a=>{if(n.files[a].dir||!a.startsWith(r))return!1;const l=a.slice(r.length);return l==="lib/flutter_flow/custom_functions.dart"||l.startsWith("lib/custom_code/")&&l.endsWith(".dart")});return await Promise.all(o.map(async a=>{s.set(a.slice(r.length),await n.files[a].async("string"))})),{pubspecYaml:await n.files[i].async("string"),files:s}}async pushCodeWithRetry(e,n=3,i=null){const r=[Dr.production,Dr.staging],s=Math.max(0,r.indexOf(this._endpoint));let o=!1,a=null;for(let l=0;lsetTimeout(p,1e3*(l+1)));continue}if(d.ok)return console.log(`Push to ${c} succeeded!`),d;a=d.status;let h;try{h=await d.clone().text()}catch{h="(unreadable response body)"}if(console.log(`Push to ${c} returned ${d.status}: ${h}`),d.status>=500&&(o=!0),d.status===500){console.warn(`Endpoint ${c} returned 500, trying next...`),await new Promise(f=>setTimeout(f,1e3*(l+1)));continue}if(d.status>=500)throw new Qe(`FlutterFlow reported a server error (HTTP ${d.status}), which cannot prove the push was refused — the write may have been applied before the failure. Open your FlutterFlow project to reconcile before retrying.`);if(o)throw new Qe(`The push was refused (HTTP ${d.status}), but an earlier sync attempt may already have applied it — server errors and dropped responses cannot prove a refusal. Open your FlutterFlow project to reconcile before retrying.`);return d}throw ju({httpStatus:a})}async pushCode(e,n=null){return this.pushCodeWithRetry(e,3,n)}parseProjectsResponse(e){if(e?.success&&typeof e.value=="string")try{const i=JSON.parse(e.value);if(i&&Array.isArray(i.entries))return i.entries.map(r=>({id:r.id,name:r.project?.name||r.id}))}catch(i){console.error("Failed to parse stringified project value:",i)}const n=e?.projects||e?.items||e?.entries||(Array.isArray(e)?e:[]);return Array.isArray(n)?n:[]}async listProjects(){console.log("Listing projects for API key");const e=[`${this.baseUrl}listProjects`,"https://api.flutterflow.io/v2/l/listProjects"];let n=0,i="";for(const r of e){const s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({project_type:"ALL",deserialize_response:!0})});if(s.ok)return r!==e[0]&&console.log(`listProjects answered on legacy path ${r}`),this.parseProjectsResponse(await s.json());if(n=s.status,i=await s.text(),console.warn(`listProjects via ${r} returned ${n}: ${i}`),s.status===401||s.status===403)throw new Error(b0(s.status,i));if(s.status!==404)throw new Error(`List projects failed: ${s.status} - ${i}`)}throw new Error(`List projects failed: ${n} - ${i}`)}}async function E0(t){const e=t.clone();let n;try{n=await t.json()}catch{let s="";try{s=await e.text()}catch{}if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:s||`HTTP ${t.status}`,errorMap:new Map};throw new Qe(`FlutterFlow accepted the sync but returned an unreadable response${s?`: ${s.slice(0,200)}`:"."}`)}if(!t.ok){let r=n.message||`HTTP ${t.status}`,s=new Map;if(n.errors)s=new Map(Object.entries(n.errors));else if(!n.message&&typeof n=="object"){const o=Object.keys(n).filter(a=>a.endsWith(".dart")&&Array.isArray(n[a]));o.length>0&&(s=new Map(Object.entries(n)),r=o.flatMap(l=>n[l].map(u=>`${l}: ${u.errorMessage}`)).join(` +`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:r,errorMap:s}}let i={};if(n.value)try{i=typeof n.value=="string"?JSON.parse(n.value):n.value}catch(r){console.warn("Ignoring malformed push response value:",r)}return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(i))}}function Bl(t,e){return{401:"Authentication failed. Please check your FlutterFlow API key.",403:"Access denied. You may not have permission to modify this project.",404:"Project not found. Please check your Project ID.",409:"Conflict detected. The project may have been modified elsewhere.",422:"Validation failed: Invalid request format",429:"Rate limit exceeded. Please try again in a few minutes.",500:"FlutterFlow server error. Please try again later.",503:"FlutterFlow service temporarily unavailable."}[t]||`FlutterFlow API error: ${`HTTP ${t}`}`}const J={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},Uh=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,Hh=/extends\s+State<\w+>/;function S0(t,e=""){if(t==="pubspec.yaml")return J.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return J.OTHER;if(t==="custom_functions.dart")return J.FUNCTION;if(e){const n=Uh.test(e),i=Hh.test(e);if(n||i)return J.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return J.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return J.FUNCTION}return J.CODE_FILE}function Wh(t,e){switch(e){case J.ACTION:return`lib/custom_code/actions/${t}`;case J.WIDGET:return`lib/custom_code/widgets/${t}`;case J.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case J.CODE_FILE:return`lib/custom_code/${t}`;case J.DEPENDENCIES:return"pubspec.yaml";case J.OTHER:return`lib/custom_code/${t}`;default:return t}}async function Dl(t,e=new Map){return kv(t,e)}const Wa=new Map;function zh(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function sr(t){Wa.delete(zh(t))}function qh(t,e,n){return new Promise((i,r)=>{let s=!1;const o=(l,u,c)=>{s||(s=!0,c==="resolve"?i(u):r(u))},a=setTimeout(()=>{s||(s=!0,n(i,r))},e);t.then(l=>{clearTimeout(a),o(i,l,"resolve")},l=>{clearTimeout(a),o(r,l,"reject")})})}async function jl(t,e,n=wh){const i={stop:!1};return qh((async()=>{const r=await t.pushCode(e,i);return E0(r)})(),n,(r,s)=>{i.stop=!0,s(new Qe("FlutterFlow did not answer the sync in time — the push may still have been applied. The outcome is not yet known: open your FlutterFlow project to reconcile before retrying the deploy."))})}async function Ul(t,e,n,i,r="",s=wh){const o=r_(e,n);if(o.length===0)return{remoteFiles:n,syncFileMap:e,unverified:[],approximate:[]};const a=J_(o,r),l={...a.manifest,sources:a.sources},u=a.skipped.map(f=>f.reason);u.forEach(f=>console.warn(`[custom class deploy] ${f}`));const c=a.approximate;c.forEach(f=>console.warn(`[custom class deploy] ${f}`)),console.log(`Provisioning ${o.length} new FlutterFlow custom code file(s) before sync.`),Be.set("provision");let d=!0,h;try{if(h=await qh((async()=>{let f;try{f=await fetch(Cy,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:i,customClasses:o,verification:l,stream:!0})})}catch{throw new Qe("The provisioning request did not return a response. The deploy may have reached the FlutterFlow server — open your FlutterFlow project to reconcile before retrying.")}return X_(f,{onPhase:p=>{d&&Be.setSubstatus(p)},onLog:p=>{d&&console.log(`[custom class deploy] ${p}`)}})})(),s,(f,p)=>{d=!1,p(new Qe("The deploy is still working on the FlutterFlow server, but this browser tab has stopped waiting. Your custom classes may or may not have been written — the outcome is not yet known. Open your FlutterFlow project to reconcile before retrying the deploy."))}),!h.finalResultReceived){if(Uu(h)===Le.FAILED){const f=new Error(h.error||`FlutterFlow custom class provisioning failed (HTTP ${h.httpStatus}).`);throw f.remoteRefusal=!0,f}throw new Qe("The connection to the FlutterFlow deploy runner dropped before it reported a result. The deploy may still be finishing on the server; open your FlutterFlow project to reconcile before retrying.")}}catch(f){throw f instanceof Qe&&sr(t),f}if(!h.success){const f=h.details?` ${h.details}`:"",p=`${h.error||"FlutterFlow custom class provisioning failed."}${f}`;if(Uu(h)===Le.UNCONFIRMED)throw new Qe(`${p} The failure arrived after the deploy began — custom classes may already be written. Open your FlutterFlow project to reconcile before retrying.`);const g=new Error(p);throw g.remoteRefusal=!0,g}return sr(t),h.verificationSkipped&&(console.warn(`[custom class deploy] ${h.verificationSkipped}`),u.push(h.verificationSkipped)),{remoteFiles:n,syncFileMap:s_(e,o),unverified:u,approximate:c,provisionSucceeded:!0}}async function Hl(t,e={}){const n=zh(t);let i=Wa.get(n);if(i===void 0){try{i=await t.fetchProjectSource()}catch(l){throw new Error(`Could not read your project's pubspec.yaml (${l.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=_h(i.pubspecYaml);if(!a.valid)throw new Error(`Your project's pubspec.yaml could not be read reliably (${a.errors.join("; ")}). Deploy was stopped so your existing package dependencies aren't overwritten.`);Wa.set(n,i)}const r=await my(i.pubspecYaml,e),s=q_(i.pubspecYaml,r.overrides),o=z_(s.yaml,r.additions);return r.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>`${a}: ${r.additions[a]||"any"}`).join(", "),r.sdk.dartSdkFloor?`(resolved for Dart ${r.sdk.dartSdkFloor})`:""),r.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:s.overridden,warnings:r.warnings,remoteFiles:i.files}}function x0(t){const e=[],n=[];t.content.length>5e4&&n.push("Code file is large (>50KB). This may take longer to commit."),t.content.length>1e5&&e.push("Code file is too large (>100KB). Consider splitting into smaller components.");const i=t.content.split(` +`).length;i>500&&n.push(`Code has ${i} lines. Consider breaking it into smaller widgets.`),t.content.includes("setState")&&t.codeType===J.ACTION&&n.push("Using setState in a Custom Action may not work as expected. Consider using a Custom Widget."),t.content.includes("dynamic")&&!t.content.includes("?")&&n.push('Code uses "dynamic" types. Consider adding explicit types for better null safety.'),t.content.match(/Color\(0xFF[0-9A-Fa-f]{6}\)/)&&n.push("Code contains hardcoded colors. Consider using FlutterFlowTheme.of(context) for theme consistency.");const r=t.content.match(/print\s*\(/g);r&&r.length>3&&n.push(`Code contains ${r.length} print statements. Consider removing debug prints before committing.`);const s=S_(t.content);if(s&&e.push(`FlutterFlow cannot format this code - ${s}. Fix or regenerate before committing.`),t.codeType===J.WIDGET){const o=ch(t.content),a=w_(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=`${uh(o[0])}`;e.push(`Widget class name "${o[0]}" does not match the file name "${t.fileName}". FlutterFlow derives the widget from the file name, so it will report "No widget ${a} found". Rename the file to "${l}" or the class to match before committing.`)}}return{canProceed:e.length===0,issues:e,warnings:n}}function Vh(t,e={}){const{artifactType:n="CustomWidget",artifactName:i="GeneratedCode",fileName:r}=e,s=__(t);let o=r||i;if(n==="CustomFunction")o="custom_functions.dart";else if(n==="CustomWidget"){const u=ch(s)[0],c=u?uh(u):null;c&&o!==c?(console.warn(`Commit file name "${o}" does not match declared widget class "${u}"; renaming to "${c}" so FlutterFlow can find the widget.`),o=c):o.endsWith(".dart")||(o+=".dart")}else o.endsWith(".dart")||(o+=".dart");let a=J.CODE_FILE;switch(n){case"CustomAction":a=J.ACTION;break;case"CustomWidget":a=J.WIDGET;break;case"CustomFunction":a=J.FUNCTION;break;case"CustomClass":case"CodeFile":a=J.CODE_FILE;break}let l="";return a===J.WIDGET?l=`// Automatic FlutterFlow imports import '/flutter_flow/flutter_flow_theme.dart'; import '/flutter_flow/flutter_flow_util.dart'; import 'package:flutter/material.dart'; @@ -111,15 +111,15 @@ import '/flutter_flow/lat_lng.dart'; import '/flutter_flow/place.dart'; import '/flutter_flow/uploaded_file.dart'; -`),{content:Vv(s,l),fileName:o,codeType:a,artifactType:n,artifactName:i}}function S0(t){const e={};for(const n of wl(t))e[n]="";return e}function x0(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 I0(t,e,n,i=new Set,r=""){const s=[],o=jh.test(e),a=Uh.test(e);return n===J.WIDGET&&!o&&!a&&s.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:s.length===0,errors:s}}function js(t){const e=[],n=[];if(!t||t.size===0)return e.push("No files to commit"),{valid:!1,errors:e,warnings:n};const i=new Set(Array.from(t.values()).flatMap(r=>As(r.content||"")));for(const[r,s]of t.entries()){if((!s.content||s.content.trim().length===0)&&e.push(`File ${r} is empty`),s.content&&s.content.length>1e5&&n.push(`File ${r} is very large (>100KB)`),r.endsWith(".dart")){const o=I0(r,s.content,s.type,i,s.artifactName);o.valid||e.push(...o.errors.map(a=>`${r}: ${a}`))}if(r==="pubspec.yaml"){const o=vh(s.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:n}}const ee={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},G={currentState:ee.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=ee.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(ee).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===ee.PREPARING&&(this.startTime=Date.now()),(t===ee.SUCCESS||t===ee.ERROR)&&(this.endTime=Date.now()),typeof window<"u"&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("commitStateChange",{detail:{state:t,commitState:this}})),console.log(`Commit state changed to: ${t}`)},setError(t){this.error=t,this.setState(ee.ERROR)},setSuccess(t){this.result=t,this.setState(ee.SUCCESS)},setProgress(t,e){this.filesProcessed=t,this.totalFiles=e},getElapsedTime(){return this.startTime?(this.endTime||Date.now())-this.startTime:null},isInProgress(){return this.currentState===ee.PREPARING||this.currentState===ee.VALIDATING||this.currentState===ee.PUSHING}};async function k0(t,e,n={}){let{codeType:i="W"}=n;const{pubspecDeps:r={},artifactName:s=e}=n;i==="CustomWidget"&&(i=J.WIDGET),i==="CustomAction"&&(i=J.ACTION),i==="CustomFunction"&&(i=J.FUNCTION),i==="CustomClass"&&(i=J.CODE_FILE),i==="CodeFile"&&(i=J.CODE_FILE),G.reset(),G.setState(ee.PREPARING);try{const o=await Te("flutterflow"),a=await Te("flutterflow_project_id");if(!o||!a)throw new Error("FlutterFlow credentials not configured. Please set your API key and Project ID in the API Keys settings.");if(!Os(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=yt(),u=new hi(o,a,"main",l);G.setState(ee.VALIDATING);const c=new Map,d=i||b0(e,t),h=Hh(e,d);c.set(e,{artifactName:s,content:t,type:d,path:h}),G.setProgress(0,c.size);const f=js(c);if(!f.valid)throw new Error(`Validation failed: +`),{content:Gv(s,l),fileName:o,codeType:a,artifactType:n,artifactName:i}}function I0(t){const e={};for(const n of wl(t))e[n]="";return e}function k0(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 C0(t,e,n,i=new Set,r=""){const s=[],o=Uh.test(e),a=Hh.test(e);return n===J.WIDGET&&!o&&!a&&s.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:s.length===0,errors:s}}function js(t){const e=[],n=[];if(!t||t.size===0)return e.push("No files to commit"),{valid:!1,errors:e,warnings:n};const i=new Set(Array.from(t.values()).flatMap(r=>As(r.content||"")));for(const[r,s]of t.entries()){if((!s.content||s.content.trim().length===0)&&e.push(`File ${r} is empty`),s.content&&s.content.length>1e5&&n.push(`File ${r} is very large (>100KB)`),r.endsWith(".dart")){const o=C0(r,s.content,s.type,i,s.artifactName);o.valid||e.push(...o.errors.map(a=>`${r}: ${a}`))}if(r==="pubspec.yaml"){const o=_h(s.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:n}}const ee={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},G={currentState:ee.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=ee.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(ee).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===ee.PREPARING&&(this.startTime=Date.now()),(t===ee.SUCCESS||t===ee.ERROR)&&(this.endTime=Date.now()),typeof window<"u"&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("commitStateChange",{detail:{state:t,commitState:this}})),console.log(`Commit state changed to: ${t}`)},setError(t){this.error=t,this.setState(ee.ERROR)},setSuccess(t){this.result=t,this.setState(ee.SUCCESS)},setProgress(t,e){this.filesProcessed=t,this.totalFiles=e},getElapsedTime(){return this.startTime?(this.endTime||Date.now())-this.startTime:null},isInProgress(){return this.currentState===ee.PREPARING||this.currentState===ee.VALIDATING||this.currentState===ee.PUSHING}};async function A0(t,e,n={}){let{codeType:i="W"}=n;const{pubspecDeps:r={},artifactName:s=e}=n;i==="CustomWidget"&&(i=J.WIDGET),i==="CustomAction"&&(i=J.ACTION),i==="CustomFunction"&&(i=J.FUNCTION),i==="CustomClass"&&(i=J.CODE_FILE),i==="CodeFile"&&(i=J.CODE_FILE),G.reset(),G.setState(ee.PREPARING);try{const o=await Te("flutterflow"),a=await Te("flutterflow_project_id");if(!o||!a)throw new Error("FlutterFlow credentials not configured. Please set your API key and Project ID in the API Keys settings.");if(!Os(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=yt(),u=new hi(o,a,"main",l);G.setState(ee.VALIDATING);const c=new Map,d=i||S0(e,t),h=Wh(e,d);c.set(e,{artifactName:s,content:t,type:d,path:h}),G.setProgress(0,c.size);const f=js(c);if(!f.valid)throw new Error(`Validation failed: ${f.errors.join(` -`)}`);const p=await Hl(u,r),g=p.yaml,m=await Ul(u,c,p.remoteFiles,`Provision ${s} custom class`,g),v=await Dl(m.syncFileMap,m.remoteFiles),E=new Map(m.syncFileMap);E.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),Oe.set("package");const S=await Wl(E),_={project_id:a,zipped_custom_code:S,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};G.setState(ee.PUSHING),G.setProgress(1,c.size),sr(u),Oe.set("push");const b=await jl(u,_);if(b.success)G.setSuccess({fileCount:c.size,projectId:a,warnings:b.errorMap&&b.errorMap.size>0?Array.from(b.errorMap.entries()):[]});else{const k=b.errorMessage||Bl(b.responseCode),T=new Error(k);throw T.remoteRefusal=!0,T}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:p.added,unverified:m.unverified,approximate:m.approximate,warnings:b.errorMap?Array.from(b.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),G.setError(o),o instanceof lt?{success:!1,unconfirmed:!0,error:o.message,state:G.currentState}:{success:!1,error:o.message,remoteRefusal:o.remoteRefusal===!0,state:G.currentState}}}async function Wl(t){const e=new JSZip;for(const[n,i]of t.entries())e.file(n,i.content);return e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}async function C0(t,e={}){const{artifactType:n,artifactName:i,fileName:r,pipelineResult:s}=e;console.log(`Starting commit for ${i} (${n})`);let o=!1;const a={projectId:null,endpoint:yt(),artifactType:n,artifactName:i,fileName:r};try{G.setState(ee.PREPARING);const l=zh(t,{artifactType:n,artifactName:i,fileName:r}),u=S0(l.content);console.log("Detected dependencies:",u),G.setState(ee.VALIDATING);const c=await Te("flutterflow"),d=qi||await Te("flutterflow_project_id");if(!c)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!d)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Os(d))throw new Error("Invalid FlutterFlow Project ID format.");a.projectId=d;const h=new Map;h.set(l.fileName,{artifactName:i,content:l.content,type:l.codeType,path:Hh(l.fileName,l.codeType),functionName:l.codeType===J.FUNCTION?i:void 0}),G.setProgress(0,h.size);const f=js(h);if(!f.valid)throw new Error(`File validation failed: +`)}`);const p=await Hl(u,r),g=p.yaml,m=await Ul(u,c,p.remoteFiles,`Provision ${s} custom class`,g),v=await Dl(m.syncFileMap,m.remoteFiles),E=new Map(m.syncFileMap);E.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),Be.set("package");const S=await Wl(E),_={project_id:a,zipped_custom_code:S,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};G.setState(ee.PUSHING),G.setProgress(1,c.size),sr(u),Be.set("push");const b=await jl(u,_);if(b.success)G.setSuccess({fileCount:c.size,projectId:a,warnings:b.errorMap&&b.errorMap.size>0?Array.from(b.errorMap.entries()):[]});else{const k=b.errorMessage||Bl(b.responseCode),T=new Error(k);throw T.remoteRefusal=!0,T}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:p.added,unverified:m.unverified,approximate:m.approximate,warnings:b.errorMap?Array.from(b.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),G.setError(o),o instanceof Qe?{success:!1,unconfirmed:!0,error:o.message,state:G.currentState}:{success:!1,error:o.message,remoteRefusal:o.remoteRefusal===!0,state:G.currentState}}}async function Wl(t){const e=new JSZip;for(const[n,i]of t.entries())e.file(n,i.content);return e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}async function P0(t,e={}){const{artifactType:n,artifactName:i,fileName:r,pipelineResult:s}=e;console.log(`Starting commit for ${i} (${n})`);let o=!1;const a={projectId:null,endpoint:yt(),artifactType:n,artifactName:i,fileName:r};try{G.setState(ee.PREPARING);const l=Vh(t,{artifactType:n,artifactName:i,fileName:r}),u=I0(l.content);console.log("Detected dependencies:",u),G.setState(ee.VALIDATING);const c=await Te("flutterflow"),d=zi||await Te("flutterflow_project_id");if(!c)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!d)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Os(d))throw new Error("Invalid FlutterFlow Project ID format.");a.projectId=d;const h=new Map;h.set(l.fileName,{artifactName:i,content:l.content,type:l.codeType,path:Wh(l.fileName,l.codeType),functionName:l.codeType===J.FUNCTION?i:void 0}),G.setProgress(0,h.size);const f=js(h);if(!f.valid)throw new Error(`File validation failed: ${f.errors.join(` -`)}`);f.warnings.length>0&&console.warn("Validation warnings:",f.warnings),G.setState(ee.PUSHING);const p=yt(),g=new hi(c,d,"main",p),m=await Hl(g,u),v=m.yaml,E=await Ul(g,h,m.remoteFiles,`Provision ${i} custom class`,v);o=E.provisionSucceeded===!0;const S=await Dl(E.syncFileMap,E.remoteFiles),_=new Map(E.syncFileMap);_.set("pubspec.yaml",{content:v,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Oe.set("package");const b=await Wl(_),k={project_id:d,zipped_custom_code:b,uid:`web_${Date.now()}`,branch_name:g.branchName,serialized_yaml:v,file_map:S.fileMapContents,functions_map:S.functionsMapContents};G.setProgress(1,h.size),sr(g),Oe.set("push");const T=await jl(g,k);if(T.success){const x={...x0(l,s),projectId:d};return G.setSuccess({...x,fileCount:h.size,warnings:T.errorMap?Array.from(T.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${l.fileName} to FlutterFlow`,metadata:x,targetIdentity:a,addedDependencies:m.added,unverified:E.unverified,approximate:E.approximate,warnings:T.errorMap?Array.from(T.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}else{const x=T.errorMessage||Bl(T.responseCode),F=new Error(x);throw F.errorMap=T.errorMap,F.remoteRefusal=!0,F}}catch(l){console.error("Commit execution failed:",l),G.setError(l);let u=new Map;if(l.errorMap)u=l.errorMap;else if(l.message&&l.message.includes("{"))try{const c=l.message.match(/\{[\s\S]*\}/);if(c){const d=JSON.parse(c[0]);u=new Map(Object.entries(d))}}catch(c){console.warn("Failed to parse error map from commit response:",c)}return l instanceof lt?{success:!1,unconfirmed:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:o?{success:!1,partial:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:l.message,errorMap:u,remoteRefusal:l.remoteRefusal===!0,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function A0(t,e={}){const{pipelineResult:n}=e;let i=!1;const r={projectId:null,endpoint:yt(),artifactType:"Bundle",artifactName:t?.title,fileName:t?.fileEntries?`${t.fileEntries.length} artifacts`:"bundle"};try{if(G.setState(ee.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: +`)}`);f.warnings.length>0&&console.warn("Validation warnings:",f.warnings),G.setState(ee.PUSHING);const p=yt(),g=new hi(c,d,"main",p),m=await Hl(g,u),v=m.yaml,E=await Ul(g,h,m.remoteFiles,`Provision ${i} custom class`,v);o=E.provisionSucceeded===!0;const S=await Dl(E.syncFileMap,E.remoteFiles),_=new Map(E.syncFileMap);_.set("pubspec.yaml",{content:v,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Be.set("package");const b=await Wl(_),k={project_id:d,zipped_custom_code:b,uid:`web_${Date.now()}`,branch_name:g.branchName,serialized_yaml:v,file_map:S.fileMapContents,functions_map:S.functionsMapContents};G.setProgress(1,h.size),sr(g),Be.set("push");const T=await jl(g,k);if(T.success){const x={...k0(l,s),projectId:d};return G.setSuccess({...x,fileCount:h.size,warnings:T.errorMap?Array.from(T.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${l.fileName} to FlutterFlow`,metadata:x,targetIdentity:a,addedDependencies:m.added,unverified:E.unverified,approximate:E.approximate,warnings:T.errorMap?Array.from(T.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}else{const x=T.errorMessage||Bl(T.responseCode),F=new Error(x);throw F.errorMap=T.errorMap,F.remoteRefusal=!0,F}}catch(l){console.error("Commit execution failed:",l),G.setError(l);let u=new Map;if(l.errorMap)u=l.errorMap;else if(l.message&&l.message.includes("{"))try{const c=l.message.match(/\{[\s\S]*\}/);if(c){const d=JSON.parse(c[0]);u=new Map(Object.entries(d))}}catch(c){console.warn("Failed to parse error map from commit response:",c)}return l instanceof Qe?{success:!1,unconfirmed:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:o?{success:!1,partial:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:l.message,errorMap:u,remoteRefusal:l.remoteRefusal===!0,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function F0(t,e={}){const{pipelineResult:n}=e;let i=!1;const r={projectId:null,endpoint:yt(),artifactType:"Bundle",artifactName:t?.title,fileName:t?.fileEntries?`${t.fileEntries.length} artifacts`:"bundle"};try{if(G.setState(ee.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: ${t.errors.join(` `)}`);const s=new Map(t.fileEntries.map(b=>[b.fileName,{artifactId:b.artifactId,artifactName:b.artifactName,content:b.content,type:b.type,path:b.path,functionName:b.type===J.FUNCTION?b.artifactName:void 0}]));G.setProgress(0,s.size);const o=js(s);if(!o.valid)throw new Error(`File validation failed: ${o.errors.join(` -`)}`);G.setState(ee.VALIDATING);const a=await Te("flutterflow"),l=qi||await Te("flutterflow_project_id");if(!a)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!l)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Os(l))throw new Error("Invalid FlutterFlow Project ID format.");r.projectId=l,G.setState(ee.PUSHING);const u=yt(),c=new hi(a,l,"main",u),d=await Hl(c,t.dependencies),h=d.yaml,f=await Ul(c,s,d.remoteFiles,`Provision ${t.title} custom classes`,h);i=f.provisionSucceeded===!0;const p=await Dl(f.syncFileMap,f.remoteFiles),g=new Map(f.syncFileMap);g.set("pubspec.yaml",{content:h,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Oe.set("package");const m=await Wl(g),v={project_id:l,zipped_custom_code:m,uid:`web_${Date.now()}`,branch_name:c.branchName,serialized_yaml:h,file_map:p.fileMapContents,functions_map:p.functionsMapContents};G.setProgress(1,s.size),sr(c),Oe.set("push");const E=await jl(c,v);if(E.success){const b={...n,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((k,T)=>k+T.content.length,0),projectId:l};return G.setSuccess({...b,fileCount:s.size,warnings:E.errorMap?Array.from(E.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:b,targetIdentity:r,addedDependencies:d.added,unverified:f.unverified,approximate:f.approximate,warnings:E.errorMap?Array.from(E.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}const S=E.errorMessage||Bl(E.responseCode),_=new Error(S);throw _.errorMap=E.errorMap,_.remoteRefusal=!0,_}catch(s){console.error("Bundle commit execution failed:",s),G.setError(s);const o=s.errorMap||new Map;return s instanceof lt?{success:!1,unconfirmed:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:i?{success:!1,partial:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function P0(t,e=[]){const n=ml("architect");try{return await Ss("architect",Fh,hv(t),n,e)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Prompt Architect failed: ${i.message}`)}}async function Us(t,e,n=[],i){const r=pv(t),s=ml("generator",y.bundleSpec);try{return await Ss("generator",e,r,s,n)}catch(o){if(o.isModelArmor||o.isUsageLimit||o.isPipelineCancel)throw o;if(e!==kr){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,o.message),Mw(e,kr,i);try{return await Ss("generator",kr,r,s,n)}catch(a){throw a.isModelArmor||a.isUsageLimit||a.isPipelineCancel?a:new Error(`Code Generator failed: primary (${e}): ${o.message} | fallback (${kr}): ${a.message}`)}}throw new Error(`Code Generator failed: ${o.message}`)}}async function Hs(t,e=null){const n={...ml("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await Ss("review",Rh,gv(t),n)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Code Review failed: ${i.message}`)}}function bs(t,e){const n=document.getElementById(`step${t}-item`),i=document.getElementById(`step${t}-status`);!n||!i||(n.classList.remove("active","completed","error"),i.classList.remove("running","completed","error"),e==="active"?(n.classList.add("active"),i.classList.add("running"),i.innerHTML=` +`)}`);G.setState(ee.VALIDATING);const a=await Te("flutterflow"),l=zi||await Te("flutterflow_project_id");if(!a)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!l)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Os(l))throw new Error("Invalid FlutterFlow Project ID format.");r.projectId=l,G.setState(ee.PUSHING);const u=yt(),c=new hi(a,l,"main",u),d=await Hl(c,t.dependencies),h=d.yaml,f=await Ul(c,s,d.remoteFiles,`Provision ${t.title} custom classes`,h);i=f.provisionSucceeded===!0;const p=await Dl(f.syncFileMap,f.remoteFiles),g=new Map(f.syncFileMap);g.set("pubspec.yaml",{content:h,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Be.set("package");const m=await Wl(g),v={project_id:l,zipped_custom_code:m,uid:`web_${Date.now()}`,branch_name:c.branchName,serialized_yaml:h,file_map:p.fileMapContents,functions_map:p.functionsMapContents};G.setProgress(1,s.size),sr(c),Be.set("push");const E=await jl(c,v);if(E.success){const b={...n,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((k,T)=>k+T.content.length,0),projectId:l};return G.setSuccess({...b,fileCount:s.size,warnings:E.errorMap?Array.from(E.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:b,targetIdentity:r,addedDependencies:d.added,unverified:f.unverified,approximate:f.approximate,warnings:E.errorMap?Array.from(E.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}const S=E.errorMessage||Bl(E.responseCode),_=new Error(S);throw _.errorMap=E.errorMap,_.remoteRefusal=!0,_}catch(s){console.error("Bundle commit execution failed:",s),G.setError(s);const o=s.errorMap||new Map;return s instanceof Qe?{success:!1,unconfirmed:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:i?{success:!1,partial:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function R0(t,e=[]){const n=ml("architect");try{return await Ss("architect",Rh,pv(t),n,e)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Prompt Architect failed: ${i.message}`)}}async function Us(t,e,n=[],i){const r=gv(t),s=ml("generator",y.bundleSpec);try{return await Ss("generator",e,r,s,n)}catch(o){if(o.isModelArmor||o.isUsageLimit||o.isPipelineCancel)throw o;if(e!==kr){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,o.message),Nw(e,kr,i);try{return await Ss("generator",kr,r,s,n)}catch(a){throw a.isModelArmor||a.isUsageLimit||a.isPipelineCancel?a:new Error(`Code Generator failed: primary (${e}): ${o.message} | fallback (${kr}): ${a.message}`)}}throw new Error(`Code Generator failed: ${o.message}`)}}async function Hs(t,e=null){const n={...ml("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await Ss("review",Th,mv(t),n)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Code Review failed: ${i.message}`)}}function bs(t,e){const n=document.getElementById(`step${t}-item`),i=document.getElementById(`step${t}-status`);!n||!i||(n.classList.remove("active","completed","error"),i.classList.remove("running","completed","error"),e==="active"?(n.classList.add("active"),i.classList.add("running"),i.innerHTML=` `):e==="completed"?(n.classList.add("completed"),i.classList.add("completed"),i.innerHTML=` @@ -127,12 +127,12 @@ ${o.errors.join(` `):i.innerHTML=` - `)}function Ae(t,e){const n=document.getElementById(`step${t}-loading`),i=document.getElementById(`step${t}-result`);e?(n.classList.remove("hidden"),i.classList.add("hidden"),bs(t,"active")):(n.classList.add("hidden"),i.classList.remove("hidden"),bs(t,"completed"))}function F0(t){const e=document.getElementById(`${t}-content`),n=document.getElementById(`${t}-chevron`);e.classList.contains("open")?(e.classList.remove("open"),n&&(n.style.transform="rotate(0deg)")):(e.classList.add("open"),n&&(n.style.transform="rotate(180deg)"))}function R0(t){nt(parseInt(t.replace("step","")))}function nt(t){for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-item`);a&&a.classList.remove("active")}const e=document.getElementById(`step${t}-item`);e&&e.classList.add("active"),Nn();const n=document.getElementById("ready-state");n&&n.classList.add("hidden");for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-content`);a&&a.classList.add("hidden")}const i=document.getElementById(`step${t}-content`);i&&i.classList.remove("hidden");const r=document.getElementById("stage-title"),s={1:"Prompt Architect",2:"Code Generator",3:"Code Review"};r&&(r.textContent=s[t]||"Active Workflow Stage")}function T0(t){const e=document.getElementById(t);if(!e)return;const n=e.dataset.raw||e.textContent;navigator.clipboard.writeText(n).then(()=>{const r=e.closest(".code-container")?.querySelector(".copy-btn");r&&(r.classList.add("copied"),r.innerHTML=' Copied!',setTimeout(()=>{r.classList.remove("copied"),r.innerHTML=' Copy'},2e3))}).catch(i=>{console.warn("Failed to copy to clipboard:",i)})}function qa(t){const e=za(t);console.log(`Step 1 (Prompt Architect): ${Gt(Fh)}`),console.log(e!==t?`Step 2 (Code Generator): ${Gt(t)} → ${Gt(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${Gt(t)}`),console.log(`Step 3 (Code Review): ${Gt(Rh)}`)}function Vh(){return{step1Result:y.step1Result,step2Result:y.step2Result,step3Result:y.step3Result,artifactBundle:y.artifactBundle,bundleReview:y.bundleReview,selectedArtifactId:y.selectedArtifactId}}function $0(t){if(!t)return;Object.assign(y,t),new Set((y.artifactBundle?.artifacts||[]).map(n=>n.id)).has(y.selectedArtifactId)||(y.selectedArtifactId=oi(y.artifactBundle)?.id||null)}const Gh="results-replacement-error";function M0(t,{stage:e=2,runId:n,retry:i}){if(!re(n))return;const r=document.getElementById(Gh);if(!r)return;const s=Eh(t),o=document.getElementById("results-replacement-error-title"),a=document.getElementById("results-replacement-error-message"),l=document.getElementById("results-replacement-error-retry"),u=document.getElementById("results-replacement-error-upgrade");o&&(o.textContent=`${Vs[e]||"Regeneration"}: ${s.title}`),a&&(a.textContent=s.message),r.hidden=!1;let c=null;u&&(u.hidden=!s.canUpgrade,s.canUpgrade&&(u.textContent="View plans",u.onclick=()=>di(),c=u)),l&&(l.hidden=s.canUpgrade,s.canUpgrade||(l.onclick=()=>{ql(),typeof i=="function"&&i()},l.textContent="Retry",c=l)),(c||r).focus({preventScroll:!0})}function ql(){const t=document.getElementById(Gh);t&&(t.hidden=!0)}function Kh(t,{previous:e,stage:n,runId:i,retry:r}){re(i)&&(t.isUsageLimit&&un(),$0(e),cr(),nn(!0),ur(),eo(),M0(t,{stage:n,runId:i,retry:r}),rn())}async function Yh(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0;const e=Gs();zl("standardRegenerate",y.step2Result,y.step1Result);const n=document.querySelectorAll(".btn-refine-action"),i=Vh();n.forEach(r=>{r.disabled=!0,r.innerHTML=` + `)}function Ae(t,e){const n=document.getElementById(`step${t}-loading`),i=document.getElementById(`step${t}-result`);e?(n.classList.remove("hidden"),i.classList.add("hidden"),bs(t,"active")):(n.classList.add("hidden"),i.classList.remove("hidden"),bs(t,"completed"))}function T0(t){const e=document.getElementById(`${t}-content`),n=document.getElementById(`${t}-chevron`);e.classList.contains("open")?(e.classList.remove("open"),n&&(n.style.transform="rotate(0deg)")):(e.classList.add("open"),n&&(n.style.transform="rotate(180deg)"))}function $0(t){it(parseInt(t.replace("step","")))}function it(t){for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-item`);a&&a.classList.remove("active")}const e=document.getElementById(`step${t}-item`);e&&e.classList.add("active"),Nn();const n=document.getElementById("ready-state");n&&n.classList.add("hidden");for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-content`);a&&a.classList.add("hidden")}const i=document.getElementById(`step${t}-content`);i&&i.classList.remove("hidden");const r=document.getElementById("stage-title"),s={1:"Prompt Architect",2:"Code Generator",3:"Code Review"};r&&(r.textContent=s[t]||"Active Workflow Stage")}function M0(t){const e=document.getElementById(t);if(!e)return;const n=e.dataset.raw||e.textContent;navigator.clipboard.writeText(n).then(()=>{const r=e.closest(".code-container")?.querySelector(".copy-btn");r&&(r.classList.add("copied"),r.innerHTML=' Copied!',setTimeout(()=>{r.classList.remove("copied"),r.innerHTML=' Copy'},2e3))}).catch(i=>{console.warn("Failed to copy to clipboard:",i)})}function za(t){const e=qa(t);console.log(`Step 1 (Prompt Architect): ${Gt(Rh)}`),console.log(e!==t?`Step 2 (Code Generator): ${Gt(t)} → ${Gt(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${Gt(t)}`),console.log(`Step 3 (Code Review): ${Gt(Th)}`)}function Gh(){return{step1Result:y.step1Result,step2Result:y.step2Result,step3Result:y.step3Result,artifactBundle:y.artifactBundle,bundleReview:y.bundleReview,selectedArtifactId:y.selectedArtifactId}}function L0(t){if(!t)return;Object.assign(y,t),new Set((y.artifactBundle?.artifacts||[]).map(n=>n.id)).has(y.selectedArtifactId)||(y.selectedArtifactId=oi(y.artifactBundle)?.id||null)}const Kh="results-replacement-error";function N0(t,{stage:e=2,runId:n,retry:i}){if(!re(n))return;const r=document.getElementById(Kh);if(!r)return;const s=Sh(t),o=document.getElementById("results-replacement-error-title"),a=document.getElementById("results-replacement-error-message"),l=document.getElementById("results-replacement-error-retry"),u=document.getElementById("results-replacement-error-upgrade");o&&(o.textContent=`${Vs[e]||"Regeneration"}: ${s.title}`),a&&(a.textContent=s.message),r.hidden=!1;let c=null;u&&(u.hidden=!s.canUpgrade,s.canUpgrade&&(u.textContent="View plans",u.onclick=()=>di(),c=u)),l&&(l.hidden=s.canUpgrade,s.canUpgrade||(l.onclick=()=>{zl(),typeof i=="function"&&i()},l.textContent="Retry",c=l)),(c||r).focus({preventScroll:!0})}function zl(){const t=document.getElementById(Kh);t&&(t.hidden=!0)}function Yh(t,{previous:e,stage:n,runId:i,retry:r}){re(i)&&(t.isUsageLimit&&un(),L0(e),cr(),nn(!0),ur(),eo(),N0(t,{stage:n,runId:i,retry:r}),rn())}async function Jh(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0;const e=Gs();ql("standardRegenerate",y.step2Result,y.step1Result);const n=document.querySelectorAll(".btn-refine-action"),i=Gh();n.forEach(r=>{r.disabled=!0,r.innerHTML=` - Refining...`});try{ql();const r=Nl(),s=r.id,o=mv({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,artifactId:r.id,userFeedback:"Fix the issues listed in the audit report."});Zs({runId:e}),Ft(2,e),nt(2),Ae(2,!0);const a=await Us(o,t,[],e);if(!re(e))return;y.step2Result=a,Bs(),tn(2,e);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),nt(3),Ft(3,e),Ae(3,!0);const c=await Hs(y.step2Result,y.step1Result);if(!re(e))return;y.step3Result=c,Ds(),tn(3,e),y.artifactBundle?.artifacts?.some(f=>f.id===s)?y.selectedArtifactId=s:y.selectedArtifactId=oi(y.artifactBundle)?.id||null;const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const h=Ls(y.step3Result);ur(u,h)}catch(r){if(console.error("Refinement failed:",r),!re(e))return;const s=Ms(r,{architect:2,generator:2,review:3});Kh(r,{previous:i,stage:s,runId:e,retry:Yh})}finally{n.forEach(r=>{r.disabled=!1,r.textContent="Refine & Regenerate"}),re(e)&&(y.isRunning=!1,rn())}}async function zl(t,e,n){const i=`${_t}/connectFeedback`,r={type:t,code:e,input:n};try{const s=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok){const a=await s.text();return console.error(`callEndpoint failed: ${s.status} ${s.statusText}`,a),{success:!1,status:s.status,error:a}}const o=await s.json();return console.log("Telemetry success:",o),o}catch(s){return console.error("callEndpoint failed:",s),{success:!1,error:s.message}}}function L0(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function Jh(){const t=document.getElementById("ff-error-paste-input"),e=t?.value?.trim();if(!e){t?.focus(),t?.classList.add("ring-2","ring-red-400","border-red-300"),setTimeout(()=>t?.classList.remove("ring-2","ring-red-400","border-red-300"),2e3);return}if(!y.step2Result){Ee("No generated code found. Please run the full pipeline first.","warning");return}if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=Gs();zl("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` + Refining...`});try{zl();const r=Nl(),s=r.id,o=vv({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,artifactId:r.id,userFeedback:"Fix the issues listed in the audit report."});Zs({runId:e}),Ft(2,e),it(2),Ae(2,!0);const a=await Us(o,t,[],e);if(!re(e))return;y.step2Result=a,Bs(),tn(2,e);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),it(3),Ft(3,e),Ae(3,!0);const c=await Hs(y.step2Result,y.step1Result);if(!re(e))return;y.step3Result=c,Ds(),tn(3,e),y.artifactBundle?.artifacts?.some(f=>f.id===s)?y.selectedArtifactId=s:y.selectedArtifactId=oi(y.artifactBundle)?.id||null;const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const h=Ls(y.step3Result);ur(u,h)}catch(r){if(console.error("Refinement failed:",r),!re(e))return;const s=Ms(r,{architect:2,generator:2,review:3});Yh(r,{previous:i,stage:s,runId:e,retry:Jh})}finally{n.forEach(r=>{r.disabled=!1,r.textContent="Refine & Regenerate"}),re(e)&&(y.isRunning=!1,rn())}}async function ql(t,e,n){const i=`${_t}/connectFeedback`,r={type:t,code:e,input:n};try{const s=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok){const a=await s.text();return console.error(`callEndpoint failed: ${s.status} ${s.statusText}`,a),{success:!1,status:s.status,error:a}}const o=await s.json();return console.log("Telemetry success:",o),o}catch(s){return console.error("callEndpoint failed:",s),{success:!1,error:s.message}}}function O0(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function Zh(){const t=document.getElementById("ff-error-paste-input"),e=t?.value?.trim();if(!e){t?.focus(),t?.classList.add("ring-2","ring-red-400","border-red-300"),setTimeout(()=>t?.classList.remove("ring-2","ring-red-400","border-red-300"),2e3);return}if(!y.step2Result){Ee("No generated code found. Please run the full pipeline first.","warning");return}if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=Gs();ql("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` - Fixing…`);const s=Vh();try{ql();const o=ih({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});xp(),Zs({runId:i}),Ft(2,i),nt(2),Ae(2,!0);const a=await Us(o,n,[],i);if(!re(i))return;y.step2Result=a,Bs(),tn(2,i);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),nt(3),Ft(3,i),Ae(3,!0);const c=await Hs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,Ds(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const h=Ls(y.step3Result);ur(u,h),t&&(t.value="")}catch(o){if(console.error("Fix from errors failed:",o),!re(i))return;const a=Ms(o,{architect:2,generator:2,review:3});Kh(o,{previous:s,stage:a,runId:i,retry:Jh})}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function or(){if(console.log("runThinkingPipeline called"),y.isRunning)return;localStorage.setItem("hasSeenWalkthrough","true");const t=document.getElementById("pipeline-input").value,e=document.getElementById("code-generator-model").value,n=Ne.slice();if(!t.trim()){Ee("Please describe your FlutterFlow widget first.","warning");return}y.isRunning=!0;const i=Gs();try{if(await Oa,!re(i)||(pn.length&&await Promise.allSettled(pn.map(v=>v.job)),!re(i))||!await sw()||!re(i)||(await Q0(),!re(i)))return;const r=za(e);t.length,m0(),y.submittedPrompt=t,y.submittedImages=n.filter(v=>v.url),Ka(!0),qa(r),Nn();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const o=document.getElementById("paywall-exhausted");o&&o.classList.add("hidden"),Zs({prompt:t,runId:i}),Bw(),nt(1),Ft(1,i),Ae(1,!0);const a=y.submittedImages.map(v=>({url:v.url})),l=await P0(t,a);if(!re(i))return;y.step1Result=l,v0(),tn(1,i);const u=document.getElementById("step1-output"),c=li(y.step1Result);u.textContent=c,u.dataset.raw=c,Ae(1,!1),nt(2),Ft(2,i),Ae(2,!0);const d=await Us(y.step1Result,r,a,i);if(!re(i))return;y.step2Result=d,Bs(),tn(2,i);const h=document.getElementById("step2-output"),f=li(y.step2Result);h.textContent=f,h.dataset.raw=f,Ae(2,!1),nt(3),Ft(3,i),Ae(3,!0);const p=await Hs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=p,Ds(),tn(3,i);const g=document.getElementById("step3-output");g.textContent=y.step3Result,Ae(3,!1),cr();const m=Ls(y.step3Result);Dw(),ur(f,m)}catch(r){if(r.isPipelineCancel||console.error("Pipeline failed:",r),!re(i))return;const s=Ms(r,{architect:1,generator:2,review:3});r.isUsageLimit?un():(r.message,za(document.getElementById("code-generator-model").value),void 0),nt(s),Ae(s,!1),wp(r,{stage:s,runId:i}),bs(s,"error")}finally{re(i)&&(y.isRunning=!1,Ka(!1),rn())}}function N0(){const t=document.getElementById("code-generator-model").value,e=[ms,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(i=>i!==t),n=prompt(`Retry with different model? + Fixing…`);const s=Gh();try{zl();const o=rh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});Ip(),Zs({runId:i}),Ft(2,i),it(2),Ae(2,!0);const a=await Us(o,n,[],i);if(!re(i))return;y.step2Result=a,Bs(),tn(2,i);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),it(3),Ft(3,i),Ae(3,!0);const c=await Hs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,Ds(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const h=Ls(y.step3Result);ur(u,h),t&&(t.value="")}catch(o){if(console.error("Fix from errors failed:",o),!re(i))return;const a=Ms(o,{architect:2,generator:2,review:3});Yh(o,{previous:s,stage:a,runId:i,retry:Zh})}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function or(){if(console.log("runThinkingPipeline called"),y.isRunning)return;localStorage.setItem("hasSeenWalkthrough","true");const t=document.getElementById("pipeline-input").value,e=document.getElementById("code-generator-model").value,n=Oe.slice();if(!t.trim()){Ee("Please describe your FlutterFlow widget first.","warning");return}y.isRunning=!0;const i=Gs();try{if(await Oa,!re(i)||(pn.length&&await Promise.allSettled(pn.map(v=>v.job)),!re(i))||!await aw()||!re(i)||(await tw(),!re(i)))return;const r=qa(e);t.length,_0(),y.submittedPrompt=t,y.submittedImages=n.filter(v=>v.url),Ka(!0),za(r),Nn();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const o=document.getElementById("paywall-exhausted");o&&o.classList.add("hidden"),Zs({prompt:t,runId:i}),jw(),it(1),Ft(1,i),Ae(1,!0);const a=y.submittedImages.map(v=>({url:v.url})),l=await R0(t,a);if(!re(i))return;y.step1Result=l,y0(),tn(1,i);const u=document.getElementById("step1-output"),c=li(y.step1Result);u.textContent=c,u.dataset.raw=c,Ae(1,!1),it(2),Ft(2,i),Ae(2,!0);const d=await Us(y.step1Result,r,a,i);if(!re(i))return;y.step2Result=d,Bs(),tn(2,i);const h=document.getElementById("step2-output"),f=li(y.step2Result);h.textContent=f,h.dataset.raw=f,Ae(2,!1),it(3),Ft(3,i),Ae(3,!0);const p=await Hs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=p,Ds(),tn(3,i);const g=document.getElementById("step3-output");g.textContent=y.step3Result,Ae(3,!1),cr();const m=Ls(y.step3Result);Uw(),ur(f,m)}catch(r){if(r.isPipelineCancel||console.error("Pipeline failed:",r),!re(i))return;const s=Ms(r,{architect:1,generator:2,review:3});r.isUsageLimit?un():(r.message,qa(document.getElementById("code-generator-model").value),void 0),it(s),Ae(s,!1),bp(r,{stage:s,runId:i}),bs(s,"error")}finally{re(i)&&(y.isRunning=!1,Ka(!1),rn())}}function B0(){const t=document.getElementById("code-generator-model").value,e=[ms,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(i=>i!==t),n=prompt(`Retry with different model? Current: ${t} @@ -140,15 +140,15 @@ Options: 1. ${e[0]} 2. ${e[1]} -Enter 1 or 2:`);n==="1"?(document.getElementById("code-generator-model").value=e[0],or()):n==="2"&&(document.getElementById("code-generator-model").value=e[1],or())}async function O0(){const t=Ol();if(!t){Ee("No code to commit. Please run the pipeline first.","warning");return}const e=await Te("flutterflow"),n=await Te("flutterflow_project_id");if(!e||!n){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),Rl();return}if(y.artifactBundle?.artifacts?.length>1){await B0();return}const{artifactType:i,artifactName:r,fileName:s}=Dh(),o=zh(t,{artifactType:i,artifactName:r,fileName:s}),a=E0(o);if(!a.canProceed){Ee(`Pre-commit checks failed: ${a.issues.join("; ")}`,"error");return}Kl(o,a,null,null)}async function B0(){const t=await Te("flutterflow"),e=await Te("flutterflow_project_id");if(!t||!e){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),Rl();return}const n=Qv(y.artifactBundle);if(n.errors.length>0){Ee(`Bundle validation failed: ${n.errors.join("; ")}`,"error");return}const i=new Map(n.fileEntries.map(a=>[a.fileName,{content:a.content,type:a.type,path:a.path}])),r=js(i),s={canProceed:r.valid&&n.errors.length===0,issues:[...n.errors,...r.errors],warnings:[...n.warnings,...r.warnings]};if(!s.canProceed){Ee(`Bundle validation failed: ${s.issues.join("; ")}`,"error");return}const o={content:n.fileEntries.map(a=>`// ${a.fileName} +Enter 1 or 2:`);n==="1"?(document.getElementById("code-generator-model").value=e[0],or()):n==="2"&&(document.getElementById("code-generator-model").value=e[1],or())}async function D0(){const t=Ol();if(!t){Ee("No code to commit. Please run the pipeline first.","warning");return}const e=await Te("flutterflow"),n=await Te("flutterflow_project_id");if(!e||!n){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),Rl();return}if(y.artifactBundle?.artifacts?.length>1){await j0();return}const{artifactType:i,artifactName:r,fileName:s}=jh(),o=Vh(t,{artifactType:i,artifactName:r,fileName:s}),a=x0(o);if(!a.canProceed){Ee(`Pre-commit checks failed: ${a.issues.join("; ")}`,"error");return}Kl(o,a,null,null)}async function j0(){const t=await Te("flutterflow"),e=await Te("flutterflow_project_id");if(!t||!e){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),Rl();return}const n=e_(y.artifactBundle);if(n.errors.length>0){Ee(`Bundle validation failed: ${n.errors.join("; ")}`,"error");return}const i=new Map(n.fileEntries.map(a=>[a.fileName,{content:a.content,type:a.type,path:a.path}])),r=js(i),s={canProceed:r.valid&&n.errors.length===0,issues:[...n.errors,...r.errors],warnings:[...n.warnings,...r.warnings]};if(!s.canProceed){Ee(`Bundle validation failed: ${s.issues.join("; ")}`,"error");return}const o={content:n.fileEntries.map(a=>`// ${a.fileName} ${a.content}`).join(` -`),fileName:`${n.fileEntries.length} files`,codeType:"bundle",artifactType:"Bundle",artifactName:n.title};Kl(o,s,n.dependencies,n)}function D0(t){let e=t.errorMap||new Map;!(e instanceof Map)&&typeof e=="object"&&(e=new Map(Object.entries(e)));let n=`
    +`),fileName:`${n.fileEntries.length} files`,codeType:"bundle",artifactType:"Bundle",artifactName:n.title};Kl(o,s,n.dependencies,n)}function U0(t){let e=t.errorMap||new Map;!(e instanceof Map)&&typeof e=="object"&&(e=new Map(Object.entries(e)));let n=`

    FlutterFlow Commit Failed

    -

    ${q(t.error)}

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

    ${z(t.error)}

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

    Errors:

      `;for(const[r,s]of e.entries()){const o=El(s);n+=`
    • - ${q(r)}: ${q(o)} + ${z(r)}: ${z(o)}
    • `}n+="
    "}n+="
    ",n+=`
    -
    `;const i=document.getElementById("step3-output");i&&(i.innerHTML=n,document.getElementById("btn-regenerate-from-error")?.addEventListener("click",()=>{Zh(t.error,e)}))}async function Zh(t,e){if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=Gs(),r=document.getElementById("btn-regenerate-from-error");r&&(r.disabled=!0,r.innerHTML=` +
    `;const i=document.getElementById("step3-output");i&&(i.innerHTML=n,document.getElementById("btn-regenerate-from-error")?.addEventListener("click",()=>{Xh(t.error,e)}))}async function Xh(t,e){if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=Gs(),r=document.getElementById("btn-regenerate-from-error");r&&(r.disabled=!0,r.innerHTML=` Fixing...`);try{let s=`The previous code had the following errors when committing to FlutterFlow: @@ -164,31 +164,31 @@ ${a.content}`).join(` Error: ${g} `}else s+=`${t} -`;const o=ih({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:s});Zs({runId:i}),Ft(2,i),nt(2),Ae(2,!0);const a=await Us(o,n,[],i);if(!re(i))return;y.step2Result=a,Bs(),tn(2,i);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),nt(3),Ft(3,i),Ae(3,!0);const c=await Hs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,Ds(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const h=Ls(y.step3Result);ur(u,h)}catch(s){if(console.error("Regeneration failed:",s),!re(i))return;const o=Ms(s,{architect:2,generator:2,review:3});s.isUsageLimit&&un(),nt(o),Ae(o,!1),wp(s,{stage:o,runId:i,retry:()=>Zh(t,e)}),bs(o,"error")}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function j0(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const n=await Te("flutterflow"),i=await Te("flutterflow_project_id");n&&i?(t.className="w-2 h-2 rounded-full bg-green-500",e.textContent="FlutterFlow credentials configured",e.className="text-green-600"):n||i?(t.className="w-2 h-2 rounded-full bg-yellow-500",e.textContent="FlutterFlow credentials incomplete",e.className="text-yellow-600"):(t.className="w-2 h-2 rounded-full bg-red-500",e.textContent="FlutterFlow credentials not configured",e.className="text-red-600")}async function Xh(t){try{const e=await fetch(`${_t}/auth/send-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:t})});if(!e.ok)throw new Error(`Failed to send magic link: HTTP ${e.status}`);return e.json()}catch(e){throw console.error("sendMagicLink failed:",{email:t,message:e.message,stack:e.stack}),e}}async function U0(t){try{const n=await(await fetch(`${_t}/auth/verify-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})})).json();if(n.error||!n.email||!n.sessionToken)throw new Error(n.error||"Invalid or expired link");return n}catch(e){throw console.error("verifyMagicLink failed:",{message:e.message,stack:e.stack}),e}}async function H0(t){try{const e=await fetch(`${_t}/auth/refresh-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:t})});if(!e.ok)return console.error("refreshSession: non-OK response",{url:`${_t}/auth/refresh-session`,status:e.status}),null;const n=await e.json();return n.error||!n.email||!n.sessionToken?(console.warn("refreshSession: validation failed",{error:n.error,hasEmail:!!n.email,hasToken:!!n.sessionToken}),null):n}catch(e){return console.error("refreshSession: fetch failed",{url:`${_t}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function nd(t,e){const n=ep(),i=(z.email||n.email)!==t;z.email=t,z.sessionToken=e,z.isVerified=!0,ce=Mn({isLoading:!0}),localStorage.setItem(hs,JSON.stringify({email:t,sessionToken:e})),i&&op()}function Qh(){z.email=null,z.sessionToken=null,z.isVerified=!1,ce=Mn({isResolved:!0}),localStorage.removeItem(hs),localStorage.removeItem(gs)}function ep(){try{const t=localStorage.getItem(hs);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(hs),{email:null,sessionToken:null}}}async function W0(){const e=new URLSearchParams(window.location.search).get("token");if(e){window.history.replaceState({},"",window.location.pathname+window.location.hash);try{const{email:n,sessionToken:i}=await U0(e);nd(n,i),tp();const r=id();r&&!window.location.hash&&(window.location.hash=r)}catch(n){id();const i=n.message||"Sign-in link invalid or expired.";Ee(i,"error"),Ws(),Jn(i,"error")}}else{const{email:n,sessionToken:i}=ep();if(n&&i){const r=await H0(i);r?nd(r.email,r.sessionToken):Qh()}}Vl()}function q0(){try{localStorage.setItem(Na,JSON.stringify({hash:window.location.hash||"#home",ts:Date.now()}))}catch(t){console.warn("rememberSignInReturnSurface: failed to persist return surface:",t)}}function id(){try{const t=localStorage.getItem(Na);if(localStorage.removeItem(Na),!t)return null;const{hash:e,ts:n}=JSON.parse(t);return!e||typeof n!="number"||Date.now()-n>ky?null:e}catch(t){return console.warn("consumeSignInReturnSurface: failed to read return surface:",t),null}}function Ws(){const t=document.getElementById("signin-modal");if(!t)return;q0(),document.getElementById("signin-email-input")?.removeAttribute("aria-invalid"),Jn(""),He(t)}function tp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&We(e)}function Jn(t,e){const n=document.getElementById("signin-message");n&&(n.textContent=t||"",n.classList.remove("signin-message-success","signin-message-error"),e&&n.classList.add(`signin-message-${e}`))}async function z0(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),n=Fs(t?.value);if(!n||!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(n)||n.length>254){t?.setAttribute("aria-invalid","true"),Jn("Please enter a valid email address.","error");return}t?.removeAttribute("aria-invalid"),e&&(e.disabled=!0,e.textContent="Sending…");const r=dh(n);r&&Jn(r,"error");try{const s=await Xh(n),o=s?.code===uh;t&&!o&&(t.value=""),t?.setAttribute("aria-invalid",String(o)),Jn(fh(s,n),o?"error":"success"),e&&(e.disabled=!1,e.textContent=o?"Send Sign-in Link":"Sent!",o||setTimeout(()=>{e.textContent==="Sent!"&&(e.textContent="Send Sign-in Link")},2500))}catch(s){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:n,err:s}),Jn("Something went wrong. Please try again.","error"),e&&(e.disabled=!1,e.textContent="Send Sign-in Link")}}function V0(){z.email=null,z.sessionToken=null,z.isVerified=!1,ce=Mn({isResolved:!0}),N_({storage:window.localStorage,onIdentityChanged:Vl,onPlanChanged:zs})}const G0=O_({sendLink:Xh,getEmail:()=>z.email||"",onState:K0});function K0(t){const e=document.getElementById("send-new-link-btn"),n=document.getElementById("send-new-link-msg");if(!e||!n)return;if(t.status==="pending"){e.disabled=!0,e.textContent="Sending…",n.className="acct-access-msg",n.textContent="Sending a fresh sign-in link…";return}if(t.status==="sent"){e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg",n.textContent=fh(t.data,z.email||"")||"Link sent — check your email.";return}e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg error";const i=t.error?.message?`Couldn't send a link right now. ${t.error.message}`:"Couldn't send a link right now. Please try again.";n.textContent=i}async function Y0(){await G0()}function J0(){const t=M_(window.localStorage),e=t.length?`Cleared disposable UI caches: ${t.join(", ")}.`:"Nothing disposable to clear.";Ee(`${e} Your run count, identity and stored keys are kept.`,"info")}function Z0(){const t=document.getElementById("delete-unavailable-modal");t&&He(t,{trigger:document.activeElement})}function X0(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("delete-unavailable-modal");e&&We(e)}function Vl(){const t=z.isVerified&&!!z.email,e=document.getElementById("auth-signedout"),n=document.getElementById("auth-signedin"),i=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),n&&n.classList.toggle("hidden",!t),i&&i.classList.toggle("hidden",t);const r=document.getElementById("auth-user-email");r&&(r.textContent=z.email||"");const s=document.getElementById("access-signed-email");s&&(s.textContent=z.email||""),lw(),zs()}async function np(){try{if(typeof FingerprintJS>"u"){console.warn("resolveIdentity: FingerprintJS not loaded, skipping");return}const e=await(await FingerprintJS.load()).get(),n=e.visitorId,i=await fetch(Fy,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fingerprint:e.visitorId,cookie_id:n})});if(!i.ok)throw new Error(`Identity check HTTP ${i.status}`);const r=await i.json();if(ht.userId=r.user_id,ht.token=r.identity_token||null,ht.status=r.status,ht.resolved=!0,sessionStorage.setItem(Ay,r.user_id),ht.token&&sessionStorage.setItem(Py,ht.token),r.usage_count!==void 0){const s=gn(),a=(r.usage_month||s)===s?r.usage_count:0;localStorage.setItem(Fn,JSON.stringify({count:a,month:s})),un()}console.log(`Identity resolved: ${r.status} (${r.user_id.slice(0,8)}...) usage: ${r.usage_count??"n/a"}`)}catch(t){console.error("resolveIdentity failed:",t)}}let Wo=null;function Q0(t=5e3){return ht.resolved?Promise.resolve():(Wo||(Wo=np().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([Wo,new Promise(e=>setTimeout(e,t))]))}function ip(){const t=gn();try{const e=localStorage.getItem(Fn);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Fn,month:t,err:e}),localStorage.removeItem(Fn),{count:0,month:t}}}function gn(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function lr(){const t=ip();return t.month!==gn()?{count:0,month:gn()}:t}function ew(){const e={count:lr().count+1,month:gn()};return localStorage.setItem(Fn,JSON.stringify(e)),e}function pi(){return!!ce.isLoading}function Tt(){return!!ce.isResolved}function tw(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(ps,e)?e:null}function nw(t){return t&&Object.entries(xh).find(([,e])=>e===t)?.[0]||null}function Cr(...t){return t.find(e=>e!=null&&e!=="")}function iw(...t){return t.find(e=>e&&typeof e=="object")||{}}function rw(t){const e=t.data&&typeof t.data=="object"?t.data:t,n=iw(e.subscription,e.stripeSubscription,e.currentSubscription,e.customer?.subscriptions?.data?.[0],e.subscriptions?.data?.[0],e.subscriptions?.[0]),i=e.metadata||n.metadata||e.customer?.metadata||{},r=Cr(e.priceId,e.price_id,e.stripePriceId,e.stripe_price_id,n.priceId,n.price_id,n.plan?.id,n.price?.id,n.items?.data?.[0]?.price?.id,n.items?.[0]?.price?.id,n.lines?.data?.[0]?.price?.id),s=Cr(e.status,e.subscriptionStatus,e.subscription_status,n.status,"none"),o=tw(Cr(e.tier,e.plan,e.planId,e.plan_id,e.subscriptionTier,e.subscription_tier,e.product,e.productName,n.tier,n.plan,i.tier,i.plan)),a=Ry.has(String(s).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||nw(r)||(a||l?"professional":"free");return Mn({tier:u,status:s,periodEnd:Cr(e.periodEnd,e.currentPeriodEnd,e.current_period_end,n.current_period_end,n.periodEnd,null),isResolved:!0})}function qs(){return ps[ce.tier]??ps.free}async function sw(){if(z.isVerified&&(!Tt()||pi())&&(await sp({force:!0}),zs()),z.isVerified&&!Tt())return Ee("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=lr(),e=qs();if(t>=e)return rp(t,e,{openModal:!0}),!1;const n=Math.floor(e*.8);if(t>=n){const i=e-t;Ee(`${i} run${i===1?"":"s"} remaining this month.`,"warning")}return!0}function rd(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function rp(t,e,n={}){nn(!0);const i=document.getElementById("walkthrough-modal");i&&We(i,{restoreFocus:!1});const r=document.getElementById("ready-state");r&&r.classList.add("hidden");const s=document.getElementById("preview-frame-container");s&&(s.style.display="none");const o=document.getElementById("main-stage-container");o&&o.classList.add("visible");const a=document.getElementById("results-view");a&&a.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar");const l=document.getElementById("pipeline-progress");l&&l.classList.remove("visible");const u=document.getElementById("paywall-exhausted");if(!u){Ee(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),di();return}const c=document.getElementById("paywall-exhausted-text");if(c){const h=ce.tier;h==="free"?c.textContent=`You've used all ${e} free generations this month. Upgrade to Pro for 50 generations/month and access to all AI models.`:c.textContent=`You've used all ${e} generations this month on your ${h} plan. Your limit resets next month.`}const d=document.getElementById("paywall-signin-btn");d&&d.classList.toggle("hidden",z.isVerified),u.classList.remove("hidden"),n.openModal&&di()}function za(t){return ce.tier==="free"&&Nr.includes(t)?ms:t}function ow(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const n=ce.tier,r=!(z.isVerified&&!Tt())&&n==="free";Array.from(e.options).forEach(o=>{const a=Gt(o.value),l=Nr.includes(o.value);o.textContent=l&&r?`${a} (PRO)`:a,o.disabled=!1}),r&&Nr.includes(e.value)&&(e.value=ms),e.disabled=!1,zu.has(e)||(e.addEventListener("change",()=>{Tt()&&ce.tier==="free"&&Nr.includes(e.value)&&(e.value=ms,di()),qa(e.value),kl()}),zu.add(e));let s=document.getElementById("model-selector-free-notice");r?(s||(s=document.createElement("p"),s.id="model-selector-free-notice",s.className="text-xs text-gray-400 mt-1",t.appendChild(s)),s.innerHTML='Free plan — Gemini only. '):s&&s.remove(),qa(e.value)}function Gl(){const t=z.isVerified&&!!z.email,e=t&&pi(),n=!t||Tt(),i=lr(),r=n?i.count:0,s=n?qs():0,o=Math.max(0,s-r),a=`${r} / ${s} runs this month`,l=gl,u=n?ce.tier||"free":null,c=document.getElementById("topbar-credits-count");c&&(e?c.textContent="…":n?c.textContent=String(o):c.textContent="—");const d=document.getElementById("credits-balance");d&&(e?d.textContent="Checking plan…":n?d.textContent=a:d.textContent="Plan check failed");const h=document.getElementById("usage-dialog-tier");h&&(e?h.textContent="Checking…":n?h.textContent=l[u]||"Free":h.textContent="Unavailable");const f=document.getElementById("usage-dialog-status");f&&(e?f.textContent="Verifying your subscription…":n?f.textContent="Runs reset at the start of each month.":f.textContent="Could not verify your subscription. Try again or sign out.");const p=document.getElementById("usage-counter");if(p)if(e&&t)p.textContent="Checking plan…",p.className="text-xs text-gray-500";else if(!n&&t)p.textContent="Plan check failed",p.className="text-xs text-red-600 font-medium";else{p.textContent=a;const g=s>0?r/s:0;p.className=g>=1?"text-xs text-red-600 font-medium":g>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500"}if(!t){const g=document.getElementById("guest-usage-text");if(g){const m=ip(),v=m.month===gn()?m.count??0:0;g.textContent=`${v} / ${ps.free} generations used`}}aw()}function aw(){if(!(z.isVerified&&!!z.email))return;const e=pi(),n=Tt(),i=lr(),r=n?i.count:0,s=n?qs():0,o=Math.max(0,s-r),a=n?ce.tier||"free":null,l={free:"Free",professional:"Pro",power:"Power"}[a]||"Free",u=z.email||"",c=u.split("@")[0]||u,d=document.getElementById("acct-avatar");d&&(d.textContent=(u[0]||"?").toUpperCase());const h=document.getElementById("acct-name");h&&(h.textContent=c||"—");const f=document.getElementById("acct-plan-tier"),p=document.getElementById("acct-plan-price"),g=document.getElementById("acct-plan-note"),m=document.getElementById("acct-renewal");if(f&&(f.textContent=e?"Checking…":n?l:"Plan unavailable"),p)if(e)p.textContent="—";else if(!n)p.textContent="—";else if(a==="free")p.textContent="$0 / month";else{const x=Oi(Ni[a]??0,Cl());p.textContent=`${x} / month`}if(g&&(e?g.textContent="Verifying your subscription…":n?a==="free"?g.textContent="No subscription. Upgrade for more generations.":g.textContent="billed monthly through Stripe":g.textContent="Could not verify your subscription. Check billing or sign out."),m){const x=Date.parse(ce.periodEnd||""),F=n&&a!=="free"&&!!ce.periodEnd&&!Number.isNaN(x);if(e)m.textContent="";else if(!n)m.textContent="";else if(a==="free")m.textContent="";else if(F){const $=new Date(x).toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"});m.textContent=`Renews ${$} · reset at the start of each month.`}else m.textContent="Renewal date is not available for this period."}const v=document.getElementById("acct-left-count"),E=document.getElementById("acct-left-limit"),S=document.getElementById("acct-reset-note");v&&(v.textContent=e?"…":n?String(o):"—"),E&&(E.textContent=e?"…":n?String(s):"—"),S&&(e?S.textContent="Checking plan…":n?S.textContent="Runs reset at the start of each month.":S.textContent="Plan check failed. Refresh or manage billing.");const _=document.getElementById("acct-used-count"),b=document.getElementById("acct-meter-fill"),k=document.getElementById("acct-meter-meta"),T=document.getElementById("acct-meter-track");if(_&&(_.textContent=e?"…":n?String(r):"—"),b){const x=n&&s>0?Math.min(100,Math.round(r/s*100)):0;b.style.width=`${x}%`}if(k)if(e)k.textContent="Checking…";else if(!n)k.textContent="Plan check failed";else if(s===0)k.textContent=`${r} of ${s}`;else{const x=Math.round(r/s*100);k.textContent=`${r} of ${s} · ${x}%`}T&&(e?T.setAttribute("aria-label","Checking usage…"):n?T.setAttribute("aria-label",`${r} of ${s} generations used`):T.setAttribute("aria-label","Usage unavailable")),vt()}function un(){if(Gl(),z.isVerified&&(pi()||!Tt())){rd();return}const{count:t}=lr(),e=qs();t>=e&&!y.isRunning?rp(t,e):rd()}function lw(){Gl()}async function sp(t={}){const e=t.force===!0;if(!z.isVerified||!z.sessionToken){ce=Mn({isResolved:!0});return}ce={...ce,isLoading:!0,error:null};const n=localStorage.getItem(gs);if(!e&&n)try{const{data:i,email:r,ts:s,version:o}=JSON.parse(n);if(o===Vu&&r===z.email&&Date.now()-s<300*1e3){ce={...i,isLoading:!1,isResolved:i.isResolved!==!1};return}}catch(i){console.warn("Failed to parse subscription cache:",i,"| raw value:",n)}try{const r=await(await fetch(`${_t}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:z.sessionToken,user_id:ht.userId})})).json();if(r.error){if(["unauthorized","invalid session","expired session"].some(o=>String(r.error).toLowerCase().includes(o))){Qh(),Vl();return}ce=Mn({isResolved:!1,error:r.error});return}ce=rw(r),localStorage.setItem(gs,JSON.stringify({version:Vu,data:ce,email:z.email,ts:Date.now()}))}catch(i){console.error("fetchSubscription failed:",i),ce={...ce,isLoading:!1,isResolved:!1,error:i.message}}}function op(){localStorage.removeItem(gs)}async function cw(t){if(!z.isVerified||!z.sessionToken){ap(),Ws();return}if(!xh[t]){Ee("Invalid plan selected.","error");return}const e=document.getElementById(`checkout-btn-${t}`);e&&(e.disabled=!0,e.textContent="Redirecting…");try{const i=await(await fetch(`${_t}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:z.sessionToken,currency:Cl()})})).json();if(i.error||!i.url)throw new Error(i.error||"Failed to create checkout session");const{url:r}=i;window.location.href=r}catch(n){console.error("startCheckout failed:",n),e&&(e.disabled=!1,e.textContent="Subscribe"),Ee("Could not start checkout. Please try again.","error")}}async function uw(t){if(!z.isVerified||!z.sessionToken){Ws();return}const e=t||document.getElementById("manage-billing-btn"),n=e?e.textContent:"";e&&(e.disabled=!0,e.textContent="Loading…");try{const r=await(await fetch(`${_t}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:z.sessionToken})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to open billing portal");const{url:s}=r;window.location.href=s}catch(i){console.error("openCustomerPortal failed:",i),e&&(e.disabled=!1,e.textContent=n),Ee("Could not open billing portal. Please try again.","error")}}const Es=new Set;function dw(){Es.forEach(t=>t.abort()),Es.clear()}async function Ss(t,e,n,i={},r=[]){const o=new AbortController;Es.add(o);let a=!1;const l=setTimeout(()=>{a=!0,o.abort()},12e4);try{const u=await fetch(Cy,{method:"POST",headers:{"Content-Type":"application/json",...ht.token?{Authorization:`Bearer ${ht.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:ht.userId,step:t,model:e,prompt:n,images:r,context:i})}),c=await u.text();let d={};try{d=c?JSON.parse(c):{}}catch{d={}}if(u.status===429){d.serverCount!==void 0&&(localStorage.setItem(Fn,JSON.stringify({count:d.serverCount,month:gn()})),un());const p=new Error(d.message||"Monthly usage limit reached. Upgrade to continue.");throw p.isUsageLimit=!0,p.pipelineStep=t,p}const h=Sv(d,t);if(h)throw h;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(d),"content type:",typeof d.content),!u.ok)throw new Error(`${d.message||d.error||"BuildShip pipeline error"} (HTTP ${u.status})`);if(t==="generator")if(d.usage_status==="success"&&Number.isFinite(d.usage_count)){const p=gn();(d.usage_month||p)===p&&(localStorage.setItem(Fn,JSON.stringify({count:d.usage_count,month:p})),un())}else ew(),un();let f=d.output||d.content;if(!f){const p=c?` (body: ${c.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${p}`)}return Array.isArray(f)&&(f=f.map(p=>typeof p=="string"?p:p.text||"").join("")),typeof f!="string"&&(f=JSON.stringify(f)),f}catch(u){if(u.name==="AbortError"){if(a)throw new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`);const c=new Error(`BuildShip ${t} request cancelled`);throw c.isPipelineCancel=!0,c}throw u instanceof TypeError?new Error(`BuildShip unreachable: ${u.message}`):u}finally{clearTimeout(l),Es.delete(o)}}let Va=!1;function fw(){const e=new URLSearchParams(window.location.search).get("checkout");return e==="success"?(window.history.replaceState({},"",window.location.pathname+window.location.hash),op(),Va=!0):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname+window.location.hash),Ee("Checkout cancelled.","info")),e}function hw(){if(!Va)return;Va=!1;const t=ce.tier!=="free";Ee(t?"Subscription active! Your plan is live.":"Checkout complete — confirming your subscription. Check Manage billing if it does not update.",t?"success":"info")}function zs(){const t=z.isVerified&&!!z.email,e=ce.tier,n=t&&pi(),i=!t||Tt(),r=document.getElementById("subscription-tier-badge");if(r){const a=gl,l={free:"bg-gray-100 text-gray-600",professional:"bg-indigo-100 text-indigo-700",power:"bg-purple-100 text-purple-700",unresolved:"bg-red-50 text-red-600"};r.textContent=n?"Checking…":i?a[e]||"Free":"Plan unavailable",r.className=`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${i?l[e]||l.free:l.unresolved}`}const s=document.getElementById("upgrade-prompt");s&&s.classList.toggle("hidden",!t||n||!i||e!=="free");const o=document.getElementById("manage-billing-btn");o&&o.classList.toggle("hidden",!t||n||i&&e==="free"),pw(i?e:null),ow(),kl(),un(),Ip()}function pw(t){const e=["bg-gray-100","text-gray-500","cursor-default"];Object.entries({professional:{btnId:"checkout-btn-professional",defaultText:"Subscribe"},power:{btnId:"checkout-btn-power",defaultText:"Subscribe"}}).forEach(([r,{btnId:s,defaultText:o}])=>{const a=document.getElementById(s);a&&(r===t?(a.disabled=!0,a.textContent="Current plan",a.classList.add(...e)):(a.disabled=!1,a.textContent=o,a.classList.remove(...e)))});const i=document.getElementById("free-tier-current");i&&i.classList.toggle("hidden",t!=="free")}function gw(){document.querySelectorAll(".pm-card[data-tier]").forEach(t=>{const e=t.dataset.tier,n=uv[e];if(!n)return;const i=t.querySelector("ul.pm-features");if(i){i.innerHTML="";for(const r of n){const s=document.createElement("li");s.textContent=r,i.appendChild(s)}}})}function Ga(){const t=Cl(),e=document.getElementById("pro-price"),n=document.getElementById("power-price"),i=document.getElementById("plans-pro-price"),r=document.getElementById("plans-power-price"),s=document.getElementById("pro-price-note"),o=document.getElementById("power-price-note"),a=document.getElementById("plans-pro-price-note"),l=document.getElementById("plans-power-price-note");e&&(e.textContent=Oi(Ni.professional,t)),n&&(n.textContent=Oi(Ni.power,t)),i&&(i.textContent=Oi(Ni.professional,t)),r&&(r.textContent=Oi(Ni.power,t));const u="billed monthly";s&&(s.textContent=u),o&&(o.textContent=u),a&&(a.textContent=u),l&&(l.textContent=u)}function di(){Ga();const t=document.getElementById("pricing-modal");t&&He(t),Hy().then(()=>Ga())}function ap(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&We(e)}function Ee(t,e="info"){const n={success:"bg-green-600 text-white",error:"bg-red-600 text-white",warning:"bg-amber-500 text-white",info:"bg-gray-800 text-white"},i=document.createElement("div");i.className=`fixed bottom-6 left-1/2 -translate-x-1/2 px-5 py-3 rounded-lg text-sm font-medium shadow-lg z-50 transition-opacity duration-300 ${n[e]||n.info}`,i.textContent=t,document.body.appendChild(i),setTimeout(()=>{i.style.opacity="0",setTimeout(()=>i.remove(),300)},3500)}document.addEventListener("DOMContentLoaded",async()=>{av(),hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),mw(),window.__heroField=Q_(),window.__pipelineLogo=iy(),kh=xy({onSubmit:or}),Oa=(async()=>{try{await W0(),fw(),await sp()}catch(n){console.warn("Startup auth/subscription initialization failed:",n)}})(),await Oa,hw(),zs(),Ga(),gw(),await _0(),h0();const t=document.getElementById("flutterflow-endpoint-select");if(t){const n=yt();t.value=n}Bh(),np();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{en===2&&e.value.trim().length>0&&(Tl(),Ns())}),e.addEventListener("blur",()=>{const n=document.getElementById("walkthrough-modal");en===2&&n&&He(n)}),e.addEventListener("keydown",n=>{if(n.key==="Tab"){const i=document.getElementById("walkthrough-modal");en===2&&i&&setTimeout(()=>{He(i)},100)}})),window.addEventListener("commitStateChange",n=>{const{state:i}=n.detail;i===ee.PREPARING||i===ee.VALIDATING||i===ee.PUSHING?(Oe.phaseId||hp(),od(i)):(i===ee.SUCCESS||i===ee.ERROR)&&(od(i),setTimeout(Jl,1e3))}),ic()});function mw(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function vw(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Nn),document.addEventListener("keydown",Nn))}function Nn(){const t=document.getElementById("preview-frame-container"),e=document.getElementById("main-stage-container"),n=document.getElementById("ready-state");t&&(t.style.display="none"),e&&e.classList.add("visible"),n&&n.classList.remove("hidden");const i=document.getElementById("welcome-video-player");i&&i.removeEventListener("click",Nn),document.removeEventListener("keydown",Nn),Bh()}let zi=null;async function _w(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++Zu,n=()=>e===Zu,i=await Te("flutterflow"),r=await Te("flutterflow_project_id");if(n()){if(!i){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const o=await new hi(i,"","main",yt()).listProjects();if(!n())return;if(!o||o.length===0){t.innerHTML='';return}t.innerHTML='',o.forEach(a=>{const l=document.createElement("option");l.value=a.id||a.projectId||"",l.textContent=a.name||a.projectName||`Project ${a.id}`,t.appendChild(l)}),r&&(t.value=r)}catch(s){if(!n())return;console.error("Failed to load projects for deploy:",s),t.innerHTML=''}}}function yw(){return document.getElementById("confirm-project-select")?.value?.trim()||null}function Kl(t,e,n,i=null){zi={codeInfo:t,checks:e,deps:n,bundlePlan:i},document.getElementById("confirm-file-name").textContent=t.fileName,document.getElementById("confirm-artifact-type").textContent=t.artifactType,document.getElementById("confirm-file-size").textContent=`${(t.content.length/1024).toFixed(1)} KB`,document.getElementById("confirm-line-count").textContent=i?`${i.fileEntries.length} files`:t.content.split(` -`).length,_w();const r=document.getElementById("confirm-deps-list"),s=document.getElementById("confirm-deps-section");n&&Object.keys(n).length>0?(r.innerHTML=Object.entries(n).map(([u,c])=>{const d=c?`at least ${Qt(c)}`:"version resolved from your project";return`
  • • ${Qt(u)}: ${d}
  • `}).join(""),s.classList.remove("hidden")):s.classList.add("hidden");const o=document.getElementById("confirm-warnings-list"),a=document.getElementById("confirm-warnings-section");e.warnings&&e.warnings.length>0?(o.innerHTML=e.warnings.map(u=>`
  • • ${Qt(u)}
  • `).join(""),a.classList.remove("hidden")):a.classList.add("hidden"),document.getElementById("confirm-code-preview").textContent=t.content,document.getElementById("code-preview-content").classList.add("hidden"),document.getElementById("code-preview-chevron").style.transform="rotate(0deg)";const l=document.getElementById("commit-confirm-modal");l&&He(l)}function lp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&We(e),zi=null}function ww(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&We(e);const n=["success-message","success-project-id","success-file-name","success-artifact-type","success-time","success-size"];for(const s of n){const o=document.getElementById(s);o&&(o.textContent="")}const i=document.getElementById("success-warnings-section");i&&i.classList.add("hidden");const r=document.getElementById("success-warnings-list");r&&(r.innerHTML="")}function cp(t){const e=(m,v)=>{const E=document.getElementById(m);E&&(E.textContent=v||"")},n=t.metadata?.fileName||"",i=t.metadata?.projectId||"",r=t.metadata?.artifactType||"",s=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",i),e("success-file-name",n),e("success-artifact-type",r),e("success-time",s),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&i&&(u.href=`https://app.flutterflow.io/project/${i}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),h=t.unverified||[],f=t.approximate||[],p=t.warnings||[];(p.length>0||h.length>0||f.length>0)&&c&&d&&(d.innerHTML=[...h.map(m=>`
  • Not verified before deploying: ${q(String(m))}
  • `),...f.map(m=>`
  • Verified approximately: ${q(String(m))}
  • `),...p.map(([m,v])=>`
  • ${q(m)}: ${q(String(v))}
  • `)].join(""),c.classList.remove("hidden"));const g=document.getElementById("commit-success-modal");g&&He(g)}function up(t){Jl(),D0(t);const e=t.remoteRefusal===!0;Yl(t,{heading:"Deploy failed",title:e?"FlutterFlow refused this deploy — nothing was confirmed written.":"The deploy failed before FlutterFlow confirmed anything.",guidance:e?"Review the error and any per-file outcomes above, fix them in your code or in FlutterFlow, then deploy again. A refusal is definitive: no part of this deploy was applied, so retrying is safe once the problem is fixed.":"Review the error above, fix it, then deploy again. The deploy stopped before a write was confirmed, so nothing was applied."})}function Yl(t,{heading:e,title:n,guidance:i}){const r=t.targetIdentity||{},s=document.getElementById("commit-terminal-modal");if(!s)return!1;const o=(f,p)=>{const g=document.getElementById(f);g&&(g.textContent=p||"")};o("terminal-heading",e),o("terminal-title",n),o("terminal-message",t.error||t.message||"");const a=document.getElementById("terminal-identity-list");if(a){const f=[["Project",r.projectId||t.metadata?.projectId],["Endpoint",r.endpoint],["File",r.fileName||t.metadata?.fileName],["Artifact",r.artifactType||t.metadata?.artifactType]];a.innerHTML=f.map(([p,g])=>`
    ${q(p)}:${q(String(g??"—"))}
    `).join("")}const l=document.getElementById("terminal-file-outcomes");let u=t.errorMap;u&&!(u instanceof Map)&&(u=new Map(Object.entries(u))),l&&u&&u.size>0?(l.innerHTML=[...u.entries()].map(([f,p])=>`
  • ${q(f)}: ${q(El(p))}
  • `).join(""),l.classList.remove("hidden")):l&&l.classList.add("hidden");const c=document.getElementById("terminal-guidance");c&&(c.innerHTML=i);const d=document.getElementById("terminal-open-ff-link"),h=r.projectId||t.metadata?.projectId;return d&&(d.href=h?`https://app.flutterflow.io/project/${h}`:"https://app.flutterflow.io/"),He(s),!0}function dp(t){Yl(t,{heading:"Deploy partially applied",title:"Some custom classes reached FlutterFlow, but the deploy did not fully complete.",guidance:"The custom classes the runner confirmed are already in your project and are not lost. Review the per-file errors above, fix them in FlutterFlow or regenerate, then deploy again. Open the project to see exactly what landed."})}function fp(t){Yl(t,{heading:"Deploy outcome not yet known",title:"This browser stopped waiting before the FlutterFlow server reported a result.",guidance:"The deploy may still be finishing on the server — it was not cancelled. Open your FlutterFlow project and confirm whether the class landed before retrying, so you do not push a duplicate or build on top of an unknown state."})}function bw(t){t&&t.target!==t.currentTarget||We(document.getElementById("commit-terminal-modal"))}function Ew(){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 sd={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}},Sw=[{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..."}],Oe={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&&(Eu(e,!0,"Deploying to FlutterFlow"),He(e)),this.set("prepare")},set(t,e=null){if(!(!sd[t]||t===this.phaseId)){if(!this.sequence.includes(t)){const n=this.sequence.indexOf("package");this.sequence.splice(n===-1?this.sequence.length:n,0,t)}this.phaseId=t,this.phaseStartedAt=Date.now(),this.substatus=e,this.liveSubstatus=!1,this.render(),this.timer&&clearInterval(this.timer),t!=="done"&&(this.timer=setInterval(()=>this.render(),500))}},setSubstatus(t){t&&(this.liveSubstatus=!0,this.substatus=t,this.render())},render(){const t=sd[this.phaseId];if(!t)return;const e=(Date.now()-this.phaseStartedAt)/1e3,n=t.start+(t.end-t.start)*(1-Math.exp(-e/25));if(this.phaseId==="provision"&&!this.liveSubstatus){const o=Sw.filter(a=>e>=a.after).pop();o&&(this.substatus=o.text)}const i=this.sequence.indexOf(this.phaseId),s=[`Step ${i===-1?1:i+1} of ${this.sequence.length}`];e>=5&&s.push(xw(e)),pp(this.phaseId==="done"?100:n,t.message,s.join(" · "),this.substatus)},stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.phaseId=null;const t=document.getElementById("commit-progress-overlay");t&&(Eu(t,!1),We(t,{force:!0,restoreFocus:!1}))}};function xw(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 hp(t){Oe.start(t)}function Jl(){Oe.stop()}function pp(t,e,n,i=null){const r=document.getElementById("commit-progress-bar"),s=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");r&&(r.style.width=`${Math.round(t*10)/10}%`),s&&(s.textContent=e),o&&(o.textContent=n),a&&(a.textContent=i||"",a.classList.toggle("hidden",!i))}function od(t){const e={[ee.PREPARING]:"prepare",[ee.VALIDATING]:"validate",[ee.PUSHING]:"project",[ee.SUCCESS]:"done"};if(t===ee.ERROR){Oe.timer&&clearInterval(Oe.timer),Oe.timer=null,pp(100,"Failed","Error occurred");return}const n=e[t];n&&Oe.set(n)}function Iw(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===J.CODE_FILE):t.codeInfo?.codeType===J.CODE_FILE}let gp=!1;function mp(t){gp=t;const e=document.querySelector("#commit-confirm-modal button[data-deploy-confirm]");e&&(e.disabled=t),[...document.querySelectorAll("[data-deploy-start]"),...document.querySelectorAll("#btn-deploy-to-ff")].forEach(i=>{i.disabled=t})}function ad(t){Jl(),mp(!1);const e=wh(t);e===Xe.COMMITTED?cp(t):e===Xe.PARTIAL?dp(t):e===Xe.UNCONFIRMED?fp(t):up(t)}async function kw(){if(!zi){console.error("No pending commit data");return}if(gp){console.warn("Deploy already in flight; ignoring duplicate confirm.");return}const t=zi;if(zi=null,qi=yw(),lp(),mp(!0),hp({withProvisioning:Iw(t)}),t.bundlePlan){const o=await A0(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});qi=null,ad(o);return}const{codeInfo:e}=t,{artifactType:n,artifactName:i,fileName:r}=Dh(),s=await C0(e.content,{artifactType:n,artifactName:i,fileName:r,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});qi=null,ad(s)}window.runThinkingPipeline=or;window.toggleStep=R0;window.toggleSection=F0;window.selectWorkflowStep=nt;window.copyCode=T0;window.retryWithDifferentModel=N0;window.openApiKeysModal=Rl;window.closeApiKeysModal=Nh;window.openComposerSettings=n0;window.closeComposerSettings=i0;window.walkthroughConnectAccount=t0;window.closeWalkthroughModal=s0;window.openWalkthroughModal=r0;window.advanceWalkthrough=Tl;window.commitToFlutterFlow=k0;function Cw(){const t=document.getElementById("pipeline-input");t&&t.focus()}function Aw(){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=Cw;window.openModelSelector=Aw;window.handlePromptImageSelect=jy;window.removePromptImage=Uy;window.saveApiKeys=l0;window.validateFlutterFlowConnection=Ml;window.clearAllApiKeys=c0;window.toggleKeyVisibility=g0;window.handleWelcomeVideoEnd=vw;window.dismissWelcomeVideo=Nn;window.initiateCommitToFlutterFlow=O0;window.updateFlutterFlowCredentialStatus=j0;window.openCommitConfirmModal=Kl;window.closeCommitConfirmModal=lp;window.closeCommitSuccessModal=ww;window.closeCommitTerminalModal=bw;window.showCommitPartialModal=dp;window.showCommitUnconfirmedModal=fp;window.showCommitSuccessModal=cp;window.showCommitFailureModal=up;window.toggleCodePreview=Ew;window.confirmCommitToFlutterFlow=kw;window.runRefinement=Yh;window.regenerateFromPastedErrors=Jh;window.clearErrorInput=L0;window.setFlutterFlowEndpoint=e0;window.getFlutterFlowEndpoint=yt;window.commitProgress=Oe;window.openSignInModal=Ws;window.closeSignInModal=tp;window.handleMagicLinkRequest=z0;window.handleSignOut=V0;window.handleSendNewLink=Y0;window.handleClearCache=J0;window.handleDeleteAccount=Z0;window.closeDeleteUnavailableModal=X0;window.startCheckout=cw;window.openCustomerPortal=uw;window.openPricingModal=di;window.closePricingModal=ap;let jr=null,vp=null,On={1:"pending",2:"pending",3:"pending"},Zl=1,Xl=null;const Vs={1:"Prompt Architect",2:"Code Generator",3:"Code Review"},Pw={1:"Understanding your prompt",2:"Generating Dart code",3:"Running the code audit"},Fw={1:"Prompt understood",2:"Dart code generated",3:"Code audit complete"};function Gs(){return y.runId+=1,y.runId}function re(t){return t===void 0||t===y.runId}function Rw(){y.runId+=1}function Ql(t){return document.getElementById(`pdot-${t}`)}function Ka(t){const e=document.getElementById("btn-run-pipeline")||document.getElementById("hero-send");e&&(e.disabled=t,e.classList.toggle("is-busy",t),t?e.setAttribute("aria-busy","true"):e.removeAttribute("aria-busy"))}function Ks(t){const e=document.getElementById("pipeline-progress");e&&(e.dataset.runState=t)}function Rn(t,e){On[t]=e;const n=Ql(t);if(!n)return;n.dataset.state=e,n.disabled=e==="pending"||e==="skipped";const i=Vs[t],r={pending:"not started",active:"in progress",done:"complete",failed:"failed",skipped:"not run"};n.setAttribute("aria-label",`Step ${t} of 3, ${i}: ${r[e]||e}`),e==="active"?n.setAttribute("aria-current","step"):n.removeAttribute("aria-current")}function Tw(){return[1,2,3].filter(t=>On[t]==="done").length}function Ys(){const t=document.getElementById("pipeline-progress-fill");t&&(t.style.width=`${Tw()/3*100}%`);const e=document.getElementById("progress-stage-count");e&&(e.textContent=`Step ${Zl} of 3`)}function Js(t,{done:e=!1}={}){const n=document.getElementById("progress-title-text"),i=document.getElementById("progress-substep-text"),r=On[t],s=e||r==="done";if(n&&(n.textContent=s?Fw[t]:Pw[t]),i){const o=s?" — complete":r==="failed"?" — stopped":"";i.textContent=`Step ${t} of 3 — ${Vs[t]}${o}`}}function $w(t){On[t]==="pending"||On[t]==="skipped"||(Xl=t,[1,2,3].forEach(e=>{const n=Ql(e);n&&n.setAttribute("aria-pressed",String(e===t))}),Js(t))}function ec(){Xl=null,[1,2,3].forEach(t=>{const e=Ql(t);e&&e.removeAttribute("aria-pressed")})}function _p(t){const e=document.getElementById("pipeline-note");e&&(e.textContent=t||"",e.hidden=!t)}function Mw(t,e,n){re(n)&&_p(`${Gt(t)} did not answer. Continuing on ${Gt(e)}.`)}function tc(){const t=document.getElementById("pipeline-failure");if(!t)return;t.hidden=!0;const e=document.getElementById("pipeline-failure-actions");e&&e.replaceChildren()}const Lw=1120;function Nw(){const t=getComputedStyle(document.documentElement).getPropertyValue("--t-morph").trim(),e=Number.parseFloat(t);return Number.isFinite(e)&&e>0?e:Lw}let Qn=null,Ur=null;function Ow(){return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0}function dn(){if(Ur){try{Ur.cancel()}catch{}Ur=null}Qn&&(Qn.remove(),Qn=null),window.removeEventListener("resize",dn)}function yp(t,e){if(dn(),Ow()||!t||!e||!document.body||typeof Element.prototype.animate!="function")return;const n=t.getBoundingClientRect(),i=e.getBoundingClientRect();if(!n.width||!n.height||!i.width||!i.height)return;const r=document.createElement("div");r.className="composer-morph",r.setAttribute("aria-hidden","true"),r.style.cssText=`left:${i.left}px;top:${i.top}px;width:${i.width}px;height:${i.height}px;opacity:0;`,document.body.appendChild(r);const s=n.left+n.width/2-(i.left+i.width/2),o=n.top+n.height/2-(i.top+i.height/2),a=n.width/i.width,l=n.height/i.height,u=`translate(${s}px,${o}px) scale(${a},${l})`,c=r.animate([{transform:u,opacity:0,offset:0,easing:"cubic-bezier(.2,0,0,1)"},{transform:u,opacity:1,offset:.14,easing:"cubic-bezier(.4,0,.2,1)"},{transform:`translate(${s}px,${o}px) scale(${a*.93},${l*.93})`,opacity:1,offset:.28,easing:"cubic-bezier(.32,1.38,.5,1)"},{transform:"translate(0px,0px) scale(1,1)",opacity:1,offset:1}],{duration:Nw(),fill:"both"});Qn=r,Ur=c,window.addEventListener("resize",dn),c.onfinish=()=>{if(Qn!==r)return;const d=r.animate([{opacity:1},{opacity:0}],{duration:260,fill:"forwards"});d.onfinish=()=>{Qn===r&&dn()}}}function Bw(){const e=document.getElementById("composer")?.getBoundingClientRect();e&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{yp({getBoundingClientRect:()=>e},document.getElementById("main-stage-container"))})})}function Dw(){yp(document.getElementById("pipeline-progress"),document.getElementById("main-stage-container"))}window.addEventListener("hashchange",dn);window.addEventListener("popstate",dn);function Zs(t={}){const{prompt:e=null,runId:n}=t;if(!re(n))return;Qs(),nn(!0);const i=document.getElementById("pipeline-progress"),r=document.getElementById("results-view"),s=document.getElementById("ready-state");if(s&&s.classList.add("hidden"),r&&r.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),i&&i.classList.add("visible"),Ks("running"),e!==null){const a=document.getElementById("pipeline-submitted-prompt");a&&(a.textContent=e)}vp=Date.now();const o=document.getElementById("progress-elapsed");o&&(o.textContent="0s"),On={1:"pending",2:"pending",3:"pending"},ec(),tc(),_p(""),[1,2,3].forEach(a=>Rn(a,"pending")),Ft(1,n),jw()}function Ft(t,e){re(e)&&(Zl=t,ec(),[1,2,3].forEach(n=>{n===t?Rn(n,"active"):nt&&Rn(n,"pending")}),Js(t),Ys())}function tn(t,e){re(e)&&(Rn(t,"done"),Xl===null&&Js(t,{done:!0}),Ys())}function wp(t,{stage:e=1,runId:n,retry:i=bp}={}){if(!re(n))return;Xs(),Qs(),dn(),Ks("failed"),nn(!0);const r=document.getElementById("pipeline-progress");r&&r.classList.add("visible");const s=document.getElementById("results-view");s&&s.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),Rn(e,"failed"),[1,2,3].forEach(p=>{p>e&&Rn(p,"pending")}),Zl=e,ec(),Js(e),Ys();const o=Eh(t),a=document.getElementById("pipeline-failure"),l=document.getElementById("pipeline-failure-title"),u=document.getElementById("pipeline-failure-message"),c=document.getElementById("pipeline-failure-hint"),d=document.getElementById("pipeline-failure-actions");if(!a||!l||!u||!d)return;if(a.dataset.kind=o.kind,l.textContent=`${Vs[e]}: ${o.title}`,u.textContent=o.message,c){const p=o.detail&&o.detail!==o.message?o.detail:"";c.textContent=p,c.hidden=!p}d.replaceChildren();const h=[o.canUpgrade&&{id:"upgrade",label:"View plans",variant:"primary",onClick:()=>di()},o.canRetry&&{id:"retry",label:"Retry",variant:o.canUpgrade?"secondary":"primary",onClick:i},o.canEdit&&{id:"edit",label:"Edit prompt",variant:"secondary",onClick:Ya}].filter(Boolean);!o.canEdit&&!o.canRetry&&h.push({id:"edit",label:"Back to prompt",variant:"secondary",onClick:Ya}),h.forEach(p=>{const g=document.createElement("button");g.type="button",g.textContent=p.label,g.dataset.action=p.id,g.dataset.variant=p.variant,g.addEventListener("click",p.onClick),d.appendChild(g)}),a.hidden=!1;const f=d.querySelector("button");f&&f.focus({preventScroll:!0})}function Ya(){Rw(),dw(),y.isRunning=!1,Ka(!1),rn(),Ks("settled"),dn(),Xs(),Qs(),tc();const t=document.getElementById("pipeline-progress");t&&t.classList.remove("visible"),nn(!1);const e=document.getElementById("pipeline-input");e&&(y.submittedPrompt&&(e.value=y.submittedPrompt,e.dispatchEvent(new Event("input",{bubbles:!0}))),e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length))}function bp(){const t=document.getElementById("pipeline-input");t&&y.submittedPrompt&&(t.value=y.submittedPrompt,t.dispatchEvent(new Event("input",{bubbles:!0}))),Ne=y.submittedImages.slice(),cn(),tc(),or()}function jw(){Xs(),jr=setInterval(()=>{const t=(Date.now()-vp)/1e3,e=document.getElementById("progress-elapsed");e&&(e.textContent=`${Math.floor(t)}s`)},250)}function Xs(){jr&&(clearInterval(jr),jr=null)}let Vi=null;function Qs(){Vi&&(clearTimeout(Vi),Vi=null)}function cr(){Xs(),Qs(),Ks("settled"),Ys();const t=document.getElementById("pipeline-progress-fill");Vi=setTimeout(()=>{Vi=null;const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function Tn(t,e=""){const n={pass:'',warning:'',fail:'',info:''};return``}function Ep(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function Uw(){return g_({bundle:y.artifactBundle,reviewResult:y.step3Result})}function Hw(t){return` +`;const o=rh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:s});Zs({runId:i}),Ft(2,i),it(2),Ae(2,!0);const a=await Us(o,n,[],i);if(!re(i))return;y.step2Result=a,Bs(),tn(2,i);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),it(3),Ft(3,i),Ae(3,!0);const c=await Hs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,Ds(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const h=Ls(y.step3Result);ur(u,h)}catch(s){if(console.error("Regeneration failed:",s),!re(i))return;const o=Ms(s,{architect:2,generator:2,review:3});s.isUsageLimit&&un(),it(o),Ae(o,!1),bp(s,{stage:o,runId:i,retry:()=>Xh(t,e)}),bs(o,"error")}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function H0(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const n=await Te("flutterflow"),i=await Te("flutterflow_project_id");n&&i?(t.className="w-2 h-2 rounded-full bg-green-500",e.textContent="FlutterFlow credentials configured",e.className="text-green-600"):n||i?(t.className="w-2 h-2 rounded-full bg-yellow-500",e.textContent="FlutterFlow credentials incomplete",e.className="text-yellow-600"):(t.className="w-2 h-2 rounded-full bg-red-500",e.textContent="FlutterFlow credentials not configured",e.className="text-red-600")}async function Qh(t){try{const e=await fetch(`${_t}/auth/send-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:t})});if(!e.ok)throw new Error(`Failed to send magic link: HTTP ${e.status}`);return e.json()}catch(e){throw console.error("sendMagicLink failed:",{email:t,message:e.message,stack:e.stack}),e}}async function W0(t){try{const n=await(await fetch(`${_t}/auth/verify-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})})).json();if(n.error||!n.email||!n.sessionToken)throw new Error(n.error||"Invalid or expired link");return n}catch(e){throw console.error("verifyMagicLink failed:",{message:e.message,stack:e.stack}),e}}async function z0(t){try{const e=await fetch(`${_t}/auth/refresh-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:t})});if(!e.ok)return console.error("refreshSession: non-OK response",{url:`${_t}/auth/refresh-session`,status:e.status}),null;const n=await e.json();return n.error||!n.email||!n.sessionToken?(console.warn("refreshSession: validation failed",{error:n.error,hasEmail:!!n.email,hasToken:!!n.sessionToken}),null):n}catch(e){return console.error("refreshSession: fetch failed",{url:`${_t}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function id(t,e){const n=tp(),i=(q.email||n.email)!==t;q.email=t,q.sessionToken=e,q.isVerified=!0,ce=Mn({isLoading:!0}),localStorage.setItem(hs,JSON.stringify({email:t,sessionToken:e})),i&&ap()}function ep(){q.email=null,q.sessionToken=null,q.isVerified=!1,ce=Mn({isResolved:!0}),localStorage.removeItem(hs),localStorage.removeItem(gs)}function tp(){try{const t=localStorage.getItem(hs);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(hs),{email:null,sessionToken:null}}}async function q0(){const e=new URLSearchParams(window.location.search).get("token");if(e){window.history.replaceState({},"",window.location.pathname+window.location.hash);try{const{email:n,sessionToken:i}=await W0(e);id(n,i),np();const r=rd();r&&!window.location.hash&&(window.location.hash=r)}catch(n){rd();const i=n.message||"Sign-in link invalid or expired.";Ee(i,"error"),Ws(),Jn(i,"error")}}else{const{email:n,sessionToken:i}=tp();if(n&&i){const r=await z0(i);r?id(r.email,r.sessionToken):ep()}}Vl()}function V0(){try{localStorage.setItem(Na,JSON.stringify({hash:window.location.hash||"#home",ts:Date.now()}))}catch(t){console.warn("rememberSignInReturnSurface: failed to persist return surface:",t)}}function rd(){try{const t=localStorage.getItem(Na);if(localStorage.removeItem(Na),!t)return null;const{hash:e,ts:n}=JSON.parse(t);return!e||typeof n!="number"||Date.now()-n>Ay?null:e}catch(t){return console.warn("consumeSignInReturnSurface: failed to read return surface:",t),null}}function Ws(){const t=document.getElementById("signin-modal");if(!t)return;V0(),document.getElementById("signin-email-input")?.removeAttribute("aria-invalid"),Jn(""),We(t)}function np(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&ze(e)}function Jn(t,e){const n=document.getElementById("signin-message");n&&(n.textContent=t||"",n.classList.remove("signin-message-success","signin-message-error"),e&&n.classList.add(`signin-message-${e}`))}async function G0(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),n=Fs(t?.value);if(!n||!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(n)||n.length>254){t?.setAttribute("aria-invalid","true"),Jn("Please enter a valid email address.","error");return}t?.removeAttribute("aria-invalid"),e&&(e.disabled=!0,e.textContent="Sending…");const r=fh(n);r&&Jn(r,"error");try{const s=await Qh(n),o=s?.code===dh;t&&!o&&(t.value=""),t?.setAttribute("aria-invalid",String(o)),Jn(hh(s,n),o?"error":"success"),e&&(e.disabled=!1,e.textContent=o?"Send Sign-in Link":"Sent!",o||setTimeout(()=>{e.textContent==="Sent!"&&(e.textContent="Send Sign-in Link")},2500))}catch(s){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:n,err:s}),Jn("Something went wrong. Please try again.","error"),e&&(e.disabled=!1,e.textContent="Send Sign-in Link")}}function K0(){q.email=null,q.sessionToken=null,q.isVerified=!1,ce=Mn({isResolved:!0}),O_({storage:window.localStorage,onIdentityChanged:Vl,onPlanChanged:qs})}const Y0=B_({sendLink:Qh,getEmail:()=>q.email||"",onState:J0});function J0(t){const e=document.getElementById("send-new-link-btn"),n=document.getElementById("send-new-link-msg");if(!e||!n)return;if(t.status==="pending"){e.disabled=!0,e.textContent="Sending…",n.className="acct-access-msg",n.textContent="Sending a fresh sign-in link…";return}if(t.status==="sent"){e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg",n.textContent=hh(t.data,q.email||"")||"Link sent — check your email.";return}e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg error";const i=t.error?.message?`Couldn't send a link right now. ${t.error.message}`:"Couldn't send a link right now. Please try again.";n.textContent=i}async function Z0(){await Y0()}function X0(){const t=L_(window.localStorage),e=t.length?`Cleared disposable UI caches: ${t.join(", ")}.`:"Nothing disposable to clear.";Ee(`${e} Your run count, identity and stored keys are kept.`,"info")}function Q0(){const t=document.getElementById("delete-unavailable-modal");t&&We(t,{trigger:document.activeElement})}function ew(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("delete-unavailable-modal");e&&ze(e)}function Vl(){const t=q.isVerified&&!!q.email,e=document.getElementById("auth-signedout"),n=document.getElementById("auth-signedin"),i=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),n&&n.classList.toggle("hidden",!t),i&&i.classList.toggle("hidden",t);const r=document.getElementById("auth-user-email");r&&(r.textContent=q.email||"");const s=document.getElementById("access-signed-email");s&&(s.textContent=q.email||""),uw(),qs()}async function ip(){try{if(typeof FingerprintJS>"u"){console.warn("resolveIdentity: FingerprintJS not loaded, skipping");return}const e=await(await FingerprintJS.load()).get(),n=e.visitorId,i=await fetch(Ty,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fingerprint:e.visitorId,cookie_id:n})});if(!i.ok)throw new Error(`Identity check HTTP ${i.status}`);const r=await i.json();if(ht.userId=r.user_id,ht.token=r.identity_token||null,ht.status=r.status,ht.resolved=!0,sessionStorage.setItem(Fy,r.user_id),ht.token&&sessionStorage.setItem(Ry,ht.token),r.usage_count!==void 0){const s=gn(),a=(r.usage_month||s)===s?r.usage_count:0;localStorage.setItem(Fn,JSON.stringify({count:a,month:s})),un()}console.log(`Identity resolved: ${r.status} (${r.user_id.slice(0,8)}...) usage: ${r.usage_count??"n/a"}`)}catch(t){console.error("resolveIdentity failed:",t)}}let Wo=null;function tw(t=5e3){return ht.resolved?Promise.resolve():(Wo||(Wo=ip().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([Wo,new Promise(e=>setTimeout(e,t))]))}function rp(){const t=gn();try{const e=localStorage.getItem(Fn);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Fn,month:t,err:e}),localStorage.removeItem(Fn),{count:0,month:t}}}function gn(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function lr(){const t=rp();return t.month!==gn()?{count:0,month:gn()}:t}function nw(){const e={count:lr().count+1,month:gn()};return localStorage.setItem(Fn,JSON.stringify(e)),e}function pi(){return!!ce.isLoading}function Tt(){return!!ce.isResolved}function iw(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(ps,e)?e:null}function rw(t){return t&&Object.entries(Ih).find(([,e])=>e===t)?.[0]||null}function Cr(...t){return t.find(e=>e!=null&&e!=="")}function sw(...t){return t.find(e=>e&&typeof e=="object")||{}}function ow(t){const e=t.data&&typeof t.data=="object"?t.data:t,n=sw(e.subscription,e.stripeSubscription,e.currentSubscription,e.customer?.subscriptions?.data?.[0],e.subscriptions?.data?.[0],e.subscriptions?.[0]),i=e.metadata||n.metadata||e.customer?.metadata||{},r=Cr(e.priceId,e.price_id,e.stripePriceId,e.stripe_price_id,n.priceId,n.price_id,n.plan?.id,n.price?.id,n.items?.data?.[0]?.price?.id,n.items?.[0]?.price?.id,n.lines?.data?.[0]?.price?.id),s=Cr(e.status,e.subscriptionStatus,e.subscription_status,n.status,"none"),o=iw(Cr(e.tier,e.plan,e.planId,e.plan_id,e.subscriptionTier,e.subscription_tier,e.product,e.productName,n.tier,n.plan,i.tier,i.plan)),a=$y.has(String(s).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||rw(r)||(a||l?"professional":"free");return Mn({tier:u,status:s,periodEnd:Cr(e.periodEnd,e.currentPeriodEnd,e.current_period_end,n.current_period_end,n.periodEnd,null),isResolved:!0})}function zs(){return ps[ce.tier]??ps.free}async function aw(){if(q.isVerified&&(!Tt()||pi())&&(await op({force:!0}),qs()),q.isVerified&&!Tt())return Ee("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=lr(),e=zs();if(t>=e)return sp(t,e,{openModal:!0}),!1;const n=Math.floor(e*.8);if(t>=n){const i=e-t;Ee(`${i} run${i===1?"":"s"} remaining this month.`,"warning")}return!0}function sd(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function sp(t,e,n={}){nn(!0);const i=document.getElementById("walkthrough-modal");i&&ze(i,{restoreFocus:!1});const r=document.getElementById("ready-state");r&&r.classList.add("hidden");const s=document.getElementById("preview-frame-container");s&&(s.style.display="none");const o=document.getElementById("main-stage-container");o&&o.classList.add("visible");const a=document.getElementById("results-view");a&&a.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar");const l=document.getElementById("pipeline-progress");l&&l.classList.remove("visible");const u=document.getElementById("paywall-exhausted");if(!u){Ee(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),di();return}const c=document.getElementById("paywall-exhausted-text");if(c){const h=ce.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"),n.openModal&&di()}function qa(t){return ce.tier==="free"&&Nr.includes(t)?ms:t}function lw(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const n=ce.tier,r=!(q.isVerified&&!Tt())&&n==="free";Array.from(e.options).forEach(o=>{const a=Gt(o.value),l=Nr.includes(o.value);o.textContent=l&&r?`${a} (PRO)`:a,o.disabled=!1}),r&&Nr.includes(e.value)&&(e.value=ms),e.disabled=!1,Vu.has(e)||(e.addEventListener("change",()=>{Tt()&&ce.tier==="free"&&Nr.includes(e.value)&&(e.value=ms,di()),za(e.value),kl()}),Vu.add(e));let s=document.getElementById("model-selector-free-notice");r?(s||(s=document.createElement("p"),s.id="model-selector-free-notice",s.className="text-xs text-gray-400 mt-1",t.appendChild(s)),s.innerHTML='Free plan — Gemini only. '):s&&s.remove(),za(e.value)}function Gl(){const t=q.isVerified&&!!q.email,e=t&&pi(),n=!t||Tt(),i=lr(),r=n?i.count:0,s=n?zs():0,o=Math.max(0,s-r),a=`${r} / ${s} runs this month`,l=gl,u=n?ce.tier||"free":null,c=document.getElementById("topbar-credits-count");c&&(e?c.textContent="…":n?c.textContent=String(o):c.textContent="—");const d=document.getElementById("credits-balance");d&&(e?d.textContent="Checking plan…":n?d.textContent=a:d.textContent="Plan check failed");const h=document.getElementById("usage-dialog-tier");h&&(e?h.textContent="Checking…":n?h.textContent=l[u]||"Free":h.textContent="Unavailable");const f=document.getElementById("usage-dialog-status");f&&(e?f.textContent="Verifying your subscription…":n?f.textContent="Runs reset at the start of each month.":f.textContent="Could not verify your subscription. Try again or sign out.");const p=document.getElementById("usage-counter");if(p)if(e&&t)p.textContent="Checking plan…",p.className="text-xs text-gray-500";else if(!n&&t)p.textContent="Plan check failed",p.className="text-xs text-red-600 font-medium";else{p.textContent=a;const g=s>0?r/s:0;p.className=g>=1?"text-xs text-red-600 font-medium":g>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500"}if(!t){const g=document.getElementById("guest-usage-text");if(g){const m=rp(),v=m.month===gn()?m.count??0:0;g.textContent=`${v} / ${ps.free} generations used`}}cw()}function cw(){if(!(q.isVerified&&!!q.email))return;const e=pi(),n=Tt(),i=lr(),r=n?i.count:0,s=n?zs():0,o=Math.max(0,s-r),a=n?ce.tier||"free":null,l={free:"Free",professional:"Pro",power:"Power"}[a]||"Free",u=q.email||"",c=u.split("@")[0]||u,d=document.getElementById("acct-avatar");d&&(d.textContent=(u[0]||"?").toUpperCase());const h=document.getElementById("acct-name");h&&(h.textContent=c||"—");const f=document.getElementById("acct-plan-tier"),p=document.getElementById("acct-plan-price"),g=document.getElementById("acct-plan-note"),m=document.getElementById("acct-renewal");if(f&&(f.textContent=e?"Checking…":n?l:"Plan unavailable"),p)if(e)p.textContent="—";else if(!n)p.textContent="—";else if(a==="free")p.textContent="$0 / month";else{const x=Oi(Ni[a]??0,Cl());p.textContent=`${x} / month`}if(g&&(e?g.textContent="Verifying your subscription…":n?a==="free"?g.textContent="No subscription. Upgrade for more generations.":g.textContent="billed monthly through Stripe":g.textContent="Could not verify your subscription. Check billing or sign out."),m){const x=Date.parse(ce.periodEnd||""),F=n&&a!=="free"&&!!ce.periodEnd&&!Number.isNaN(x);if(e)m.textContent="";else if(!n)m.textContent="";else if(a==="free")m.textContent="";else if(F){const $=new Date(x).toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"});m.textContent=`Renews ${$} · reset at the start of each month.`}else m.textContent="Renewal date is not available for this period."}const v=document.getElementById("acct-left-count"),E=document.getElementById("acct-left-limit"),S=document.getElementById("acct-reset-note");v&&(v.textContent=e?"…":n?String(o):"—"),E&&(E.textContent=e?"…":n?String(s):"—"),S&&(e?S.textContent="Checking plan…":n?S.textContent="Runs reset at the start of each month.":S.textContent="Plan check failed. Refresh or manage billing.");const _=document.getElementById("acct-used-count"),b=document.getElementById("acct-meter-fill"),k=document.getElementById("acct-meter-meta"),T=document.getElementById("acct-meter-track");if(_&&(_.textContent=e?"…":n?String(r):"—"),b){const x=n&&s>0?Math.min(100,Math.round(r/s*100)):0;b.style.width=`${x}%`}if(k)if(e)k.textContent="Checking…";else if(!n)k.textContent="Plan check failed";else if(s===0)k.textContent=`${r} of ${s}`;else{const x=Math.round(r/s*100);k.textContent=`${r} of ${s} · ${x}%`}T&&(e?T.setAttribute("aria-label","Checking usage…"):n?T.setAttribute("aria-label",`${r} of ${s} generations used`):T.setAttribute("aria-label","Usage unavailable")),vt()}function un(){if(Gl(),q.isVerified&&(pi()||!Tt())){sd();return}const{count:t}=lr(),e=zs();t>=e&&!y.isRunning?sp(t,e):sd()}function uw(){Gl()}async function op(t={}){const e=t.force===!0;if(!q.isVerified||!q.sessionToken){ce=Mn({isResolved:!0});return}ce={...ce,isLoading:!0,error:null};const n=localStorage.getItem(gs);if(!e&&n)try{const{data:i,email:r,ts:s,version:o}=JSON.parse(n);if(o===Gu&&r===q.email&&Date.now()-s<300*1e3){ce={...i,isLoading:!1,isResolved:i.isResolved!==!1};return}}catch(i){console.warn("Failed to parse subscription cache:",i,"| raw value:",n)}try{const r=await(await fetch(`${_t}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:q.sessionToken,user_id:ht.userId})})).json();if(r.error){if(["unauthorized","invalid session","expired session"].some(o=>String(r.error).toLowerCase().includes(o))){ep(),Vl();return}ce=Mn({isResolved:!1,error:r.error});return}ce=ow(r),localStorage.setItem(gs,JSON.stringify({version:Gu,data:ce,email:q.email,ts:Date.now()}))}catch(i){console.error("fetchSubscription failed:",i),ce={...ce,isLoading:!1,isResolved:!1,error:i.message}}}function ap(){localStorage.removeItem(gs)}async function dw(t){if(!q.isVerified||!q.sessionToken){lp(),Ws();return}if(!Ih[t]){Ee("Invalid plan selected.","error");return}const e=document.getElementById(`checkout-btn-${t}`);e&&(e.disabled=!0,e.textContent="Redirecting…");try{const i=await(await fetch(`${_t}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:q.sessionToken,currency:Cl()})})).json();if(i.error||!i.url)throw new Error(i.error||"Failed to create checkout session");const{url:r}=i;window.location.href=r}catch(n){console.error("startCheckout failed:",n),e&&(e.disabled=!1,e.textContent="Subscribe"),Ee("Could not start checkout. Please try again.","error")}}async function fw(t){if(!q.isVerified||!q.sessionToken){Ws();return}const e=t||document.getElementById("manage-billing-btn"),n=e?e.textContent:"";e&&(e.disabled=!0,e.textContent="Loading…");try{const r=await(await fetch(`${_t}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:q.sessionToken})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to open billing portal");const{url:s}=r;window.location.href=s}catch(i){console.error("openCustomerPortal failed:",i),e&&(e.disabled=!1,e.textContent=n),Ee("Could not open billing portal. Please try again.","error")}}const Es=new Set;function hw(){Es.forEach(t=>t.abort()),Es.clear()}async function Ss(t,e,n,i={},r=[]){const o=new AbortController;Es.add(o);let a=!1;const l=setTimeout(()=>{a=!0,o.abort()},12e4);try{const u=await fetch(Py,{method:"POST",headers:{"Content-Type":"application/json",...ht.token?{Authorization:`Bearer ${ht.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:ht.userId,step:t,model:e,prompt:n,images:r,context:i})}),c=await u.text();let d={};try{d=c?JSON.parse(c):{}}catch{d={}}if(u.status===429){d.serverCount!==void 0&&(localStorage.setItem(Fn,JSON.stringify({count:d.serverCount,month:gn()})),un());const p=new Error(d.message||"Monthly usage limit reached. Upgrade to continue.");throw p.isUsageLimit=!0,p.pipelineStep=t,p}const h=xv(d,t);if(h)throw h;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(d),"content type:",typeof d.content),!u.ok)throw new Error(`${d.message||d.error||"BuildShip pipeline error"} (HTTP ${u.status})`);if(t==="generator")if(d.usage_status==="success"&&Number.isFinite(d.usage_count)){const p=gn();(d.usage_month||p)===p&&(localStorage.setItem(Fn,JSON.stringify({count:d.usage_count,month:p})),un())}else nw(),un();let f=d.output||d.content;if(!f){const p=c?` (body: ${c.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${p}`)}return Array.isArray(f)&&(f=f.map(p=>typeof p=="string"?p:p.text||"").join("")),typeof f!="string"&&(f=JSON.stringify(f)),f}catch(u){if(u.name==="AbortError"){if(a)throw new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`);const c=new Error(`BuildShip ${t} request cancelled`);throw c.isPipelineCancel=!0,c}throw u instanceof TypeError?new Error(`BuildShip unreachable: ${u.message}`):u}finally{clearTimeout(l),Es.delete(o)}}let Va=!1;function pw(){const e=new URLSearchParams(window.location.search).get("checkout");return e==="success"?(window.history.replaceState({},"",window.location.pathname+window.location.hash),ap(),Va=!0):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname+window.location.hash),Ee("Checkout cancelled.","info")),e}function gw(){if(!Va)return;Va=!1;const t=ce.tier!=="free";Ee(t?"Subscription active! Your plan is live.":"Checkout complete — confirming your subscription. Check Manage billing if it does not update.",t?"success":"info")}function qs(){const t=q.isVerified&&!!q.email,e=ce.tier,n=t&&pi(),i=!t||Tt(),r=document.getElementById("subscription-tier-badge");if(r){const a=gl,l={free:"bg-gray-100 text-gray-600",professional:"bg-indigo-100 text-indigo-700",power:"bg-purple-100 text-purple-700",unresolved:"bg-red-50 text-red-600"};r.textContent=n?"Checking…":i?a[e]||"Free":"Plan unavailable",r.className=`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${i?l[e]||l.free:l.unresolved}`}const s=document.getElementById("upgrade-prompt");s&&s.classList.toggle("hidden",!t||n||!i||e!=="free");const o=document.getElementById("manage-billing-btn");o&&o.classList.toggle("hidden",!t||n||i&&e==="free"),mw(i?e:null),lw(),kl(),un(),kp()}function mw(t){const e=["bg-gray-100","text-gray-500","cursor-default"];Object.entries({professional:{btnId:"checkout-btn-professional",defaultText:"Subscribe"},power:{btnId:"checkout-btn-power",defaultText:"Subscribe"}}).forEach(([r,{btnId:s,defaultText:o}])=>{const a=document.getElementById(s);a&&(r===t?(a.disabled=!0,a.textContent="Current plan",a.classList.add(...e)):(a.disabled=!1,a.textContent=o,a.classList.remove(...e)))});const i=document.getElementById("free-tier-current");i&&i.classList.toggle("hidden",t!=="free")}function vw(){document.querySelectorAll(".pm-card[data-tier]").forEach(t=>{const e=t.dataset.tier,n=dv[e];if(!n)return;const i=t.querySelector("ul.pm-features");if(i){i.innerHTML="";for(const r of n){const s=document.createElement("li");s.textContent=r,i.appendChild(s)}}})}function Ga(){const t=Cl(),e=document.getElementById("pro-price"),n=document.getElementById("power-price"),i=document.getElementById("plans-pro-price"),r=document.getElementById("plans-power-price"),s=document.getElementById("pro-price-note"),o=document.getElementById("power-price-note"),a=document.getElementById("plans-pro-price-note"),l=document.getElementById("plans-power-price-note");e&&(e.textContent=Oi(Ni.professional,t)),n&&(n.textContent=Oi(Ni.power,t)),i&&(i.textContent=Oi(Ni.professional,t)),r&&(r.textContent=Oi(Ni.power,t));const u="billed monthly";s&&(s.textContent=u),o&&(o.textContent=u),a&&(a.textContent=u),l&&(l.textContent=u)}function di(){Ga();const t=document.getElementById("pricing-modal");t&&We(t),zy().then(()=>Ga())}function lp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&ze(e)}function Ee(t,e="info"){const n={success:"bg-green-600 text-white",error:"bg-red-600 text-white",warning:"bg-amber-500 text-white",info:"bg-gray-800 text-white"},i=document.createElement("div");i.className=`fixed bottom-6 left-1/2 -translate-x-1/2 px-5 py-3 rounded-lg text-sm font-medium shadow-lg z-50 transition-opacity duration-300 ${n[e]||n.info}`,i.textContent=t,document.body.appendChild(i),setTimeout(()=>{i.style.opacity="0",setTimeout(()=>i.remove(),300)},3500)}document.addEventListener("DOMContentLoaded",async()=>{lv(),hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),_w(),window.__heroField=ty(),window.__pipelineLogo=sy(),Ch=ky({onSubmit:or}),Oa=(async()=>{try{await q0(),pw(),await op()}catch(n){console.warn("Startup auth/subscription initialization failed:",n)}})(),await Oa,gw(),qs(),Ga(),vw(),await w0(),g0();const t=document.getElementById("flutterflow-endpoint-select");if(t){const n=yt();t.value=n}Dh(),ip();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{en===2&&e.value.trim().length>0&&(Tl(),Ns())}),e.addEventListener("blur",()=>{const n=document.getElementById("walkthrough-modal");en===2&&n&&We(n)}),e.addEventListener("keydown",n=>{if(n.key==="Tab"){const i=document.getElementById("walkthrough-modal");en===2&&i&&setTimeout(()=>{We(i)},100)}})),window.addEventListener("commitStateChange",n=>{const{state:i}=n.detail;i===ee.PREPARING||i===ee.VALIDATING||i===ee.PUSHING?(Be.phaseId||pp(),ad(i)):(i===ee.SUCCESS||i===ee.ERROR)&&(ad(i),setTimeout(Jl,1e3))}),ic()});function _w(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function yw(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Nn),document.addEventListener("keydown",Nn))}function Nn(){const t=document.getElementById("preview-frame-container"),e=document.getElementById("main-stage-container"),n=document.getElementById("ready-state");t&&(t.style.display="none"),e&&e.classList.add("visible"),n&&n.classList.remove("hidden");const i=document.getElementById("welcome-video-player");i&&i.removeEventListener("click",Nn),document.removeEventListener("keydown",Nn),Dh()}let qi=null;async function ww(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++Xu,n=()=>e===Xu,i=await Te("flutterflow"),r=await Te("flutterflow_project_id");if(n()){if(!i){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const o=await new hi(i,"","main",yt()).listProjects();if(!n())return;if(!o||o.length===0){t.innerHTML='';return}t.innerHTML='',o.forEach(a=>{const l=document.createElement("option");l.value=a.id||a.projectId||"",l.textContent=a.name||a.projectName||`Project ${a.id}`,t.appendChild(l)}),r&&(t.value=r)}catch(s){if(!n())return;console.error("Failed to load projects for deploy:",s),t.innerHTML=''}}}function bw(){return document.getElementById("confirm-project-select")?.value?.trim()||null}function Kl(t,e,n,i=null){qi={codeInfo:t,checks:e,deps:n,bundlePlan:i},document.getElementById("confirm-file-name").textContent=t.fileName,document.getElementById("confirm-artifact-type").textContent=t.artifactType,document.getElementById("confirm-file-size").textContent=`${(t.content.length/1024).toFixed(1)} KB`,document.getElementById("confirm-line-count").textContent=i?`${i.fileEntries.length} files`:t.content.split(` +`).length,ww();const r=document.getElementById("confirm-deps-list"),s=document.getElementById("confirm-deps-section");n&&Object.keys(n).length>0?(r.innerHTML=Object.entries(n).map(([u,c])=>{const d=c?`at least ${Qt(c)}`:"version resolved from your project";return`
  • • ${Qt(u)}: ${d}
  • `}).join(""),s.classList.remove("hidden")):s.classList.add("hidden");const o=document.getElementById("confirm-warnings-list"),a=document.getElementById("confirm-warnings-section");e.warnings&&e.warnings.length>0?(o.innerHTML=e.warnings.map(u=>`
  • • ${Qt(u)}
  • `).join(""),a.classList.remove("hidden")):a.classList.add("hidden"),document.getElementById("confirm-code-preview").textContent=t.content,document.getElementById("code-preview-content").classList.add("hidden"),document.getElementById("code-preview-chevron").style.transform="rotate(0deg)";const l=document.getElementById("commit-confirm-modal");l&&We(l)}function cp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&ze(e),qi=null}function Ew(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&ze(e);const n=["success-message","success-project-id","success-file-name","success-artifact-type","success-time","success-size"];for(const s of n){const o=document.getElementById(s);o&&(o.textContent="")}const i=document.getElementById("success-warnings-section");i&&i.classList.add("hidden");const r=document.getElementById("success-warnings-list");r&&(r.innerHTML="")}function up(t){const e=(m,v)=>{const E=document.getElementById(m);E&&(E.textContent=v||"")},n=t.metadata?.fileName||"",i=t.metadata?.projectId||"",r=t.metadata?.artifactType||"",s=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",i),e("success-file-name",n),e("success-artifact-type",r),e("success-time",s),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&i&&(u.href=`https://app.flutterflow.io/project/${i}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),h=t.unverified||[],f=t.approximate||[],p=t.warnings||[];(p.length>0||h.length>0||f.length>0)&&c&&d&&(d.innerHTML=[...h.map(m=>`
  • Not verified before deploying: ${z(String(m))}
  • `),...f.map(m=>`
  • Verified approximately: ${z(String(m))}
  • `),...p.map(([m,v])=>`
  • ${z(m)}: ${z(String(v))}
  • `)].join(""),c.classList.remove("hidden"));const g=document.getElementById("commit-success-modal");g&&We(g)}function dp(t){Jl(),U0(t);const e=t.remoteRefusal===!0;Yl(t,{heading:"Deploy failed",title:e?"FlutterFlow refused this deploy — nothing was confirmed written.":"The deploy failed before FlutterFlow confirmed anything.",guidance:e?"Review the error and any per-file outcomes above, fix them in your code or in FlutterFlow, then deploy again. A refusal is definitive: no part of this deploy was applied, so retrying is safe once the problem is fixed.":"Review the error above, fix it, then deploy again. The deploy stopped before a write was confirmed, so nothing was applied."})}function Yl(t,{heading:e,title:n,guidance:i}){const r=t.targetIdentity||{},s=document.getElementById("commit-terminal-modal");if(!s)return!1;const o=(f,p)=>{const g=document.getElementById(f);g&&(g.textContent=p||"")};o("terminal-heading",e),o("terminal-title",n),o("terminal-message",t.error||t.message||"");const a=document.getElementById("terminal-identity-list");if(a){const f=[["Project",r.projectId||t.metadata?.projectId],["Endpoint",r.endpoint],["File",r.fileName||t.metadata?.fileName],["Artifact",r.artifactType||t.metadata?.artifactType]];a.innerHTML=f.map(([p,g])=>`
    ${z(p)}:${z(String(g??"—"))}
    `).join("")}const l=document.getElementById("terminal-file-outcomes");let u=t.errorMap;u&&!(u instanceof Map)&&(u=new Map(Object.entries(u))),l&&u&&u.size>0?(l.innerHTML=[...u.entries()].map(([f,p])=>`
  • ${z(f)}: ${z(El(p))}
  • `).join(""),l.classList.remove("hidden")):l&&l.classList.add("hidden");const c=document.getElementById("terminal-guidance");c&&(c.innerHTML=i);const d=document.getElementById("terminal-open-ff-link"),h=r.projectId||t.metadata?.projectId;return d&&(d.href=h?`https://app.flutterflow.io/project/${h}`:"https://app.flutterflow.io/"),We(s),!0}function fp(t){Yl(t,{heading:"Deploy partially applied",title:"Some custom classes reached FlutterFlow, but the deploy did not fully complete.",guidance:"The custom classes the runner confirmed are already in your project and are not lost. Review the per-file errors above, fix them in FlutterFlow or regenerate, then deploy again. Open the project to see exactly what landed."})}function hp(t){Yl(t,{heading:"Deploy outcome not yet known",title:"This browser stopped waiting before the FlutterFlow server reported a result.",guidance:"The deploy may still be finishing on the server — it was not cancelled. Open your FlutterFlow project and confirm whether the class landed before retrying, so you do not push a duplicate or build on top of an unknown state."})}function Sw(t){t&&t.target!==t.currentTarget||ze(document.getElementById("commit-terminal-modal"))}function xw(){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 od={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}},Iw=[{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&&(Eu(e,!0,"Deploying to FlutterFlow"),We(e)),this.set("prepare")},set(t,e=null){if(!(!od[t]||t===this.phaseId)){if(!this.sequence.includes(t)){const n=this.sequence.indexOf("package");this.sequence.splice(n===-1?this.sequence.length:n,0,t)}this.phaseId=t,this.phaseStartedAt=Date.now(),this.substatus=e,this.liveSubstatus=!1,this.render(),this.timer&&clearInterval(this.timer),t!=="done"&&(this.timer=setInterval(()=>this.render(),500))}},setSubstatus(t){t&&(this.liveSubstatus=!0,this.substatus=t,this.render())},render(){const t=od[this.phaseId];if(!t)return;const e=(Date.now()-this.phaseStartedAt)/1e3,n=t.start+(t.end-t.start)*(1-Math.exp(-e/25));if(this.phaseId==="provision"&&!this.liveSubstatus){const o=Iw.filter(a=>e>=a.after).pop();o&&(this.substatus=o.text)}const i=this.sequence.indexOf(this.phaseId),s=[`Step ${i===-1?1:i+1} of ${this.sequence.length}`];e>=5&&s.push(kw(e)),gp(this.phaseId==="done"?100:n,t.message,s.join(" · "),this.substatus)},stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.phaseId=null;const t=document.getElementById("commit-progress-overlay");t&&(Eu(t,!1),ze(t,{force:!0,restoreFocus:!1}))}};function kw(t){const e=Math.floor(t);return e<60?`${e}s elapsed`:`${Math.floor(e/60)}m ${String(e%60).padStart(2,"0")}s elapsed`}function pp(t){Be.start(t)}function Jl(){Be.stop()}function gp(t,e,n,i=null){const r=document.getElementById("commit-progress-bar"),s=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");r&&(r.style.width=`${Math.round(t*10)/10}%`),s&&(s.textContent=e),o&&(o.textContent=n),a&&(a.textContent=i||"",a.classList.toggle("hidden",!i))}function ad(t){const e={[ee.PREPARING]:"prepare",[ee.VALIDATING]:"validate",[ee.PUSHING]:"project",[ee.SUCCESS]:"done"};if(t===ee.ERROR){Be.timer&&clearInterval(Be.timer),Be.timer=null,gp(100,"Failed","Error occurred");return}const n=e[t];n&&Be.set(n)}function Cw(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===J.CODE_FILE):t.codeInfo?.codeType===J.CODE_FILE}let mp=!1;function vp(t){mp=t;const e=document.querySelector("#commit-confirm-modal button[data-deploy-confirm]");e&&(e.disabled=t),[...document.querySelectorAll("[data-deploy-start]"),...document.querySelectorAll("#btn-deploy-to-ff")].forEach(i=>{i.disabled=t})}function ld(t){Jl(),vp(!1);const e=bh(t);e===Le.COMMITTED?up(t):e===Le.PARTIAL?fp(t):e===Le.UNCONFIRMED?hp(t):dp(t)}async function Aw(){if(!qi){console.error("No pending commit data");return}if(mp){console.warn("Deploy already in flight; ignoring duplicate confirm.");return}const t=qi;if(qi=null,zi=bw(),cp(),vp(!0),pp({withProvisioning:Cw(t)}),t.bundlePlan){const o=await F0(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});zi=null,ld(o);return}const{codeInfo:e}=t,{artifactType:n,artifactName:i,fileName:r}=jh(),s=await P0(e.content,{artifactType:n,artifactName:i,fileName:r,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});zi=null,ld(s)}window.runThinkingPipeline=or;window.toggleStep=$0;window.toggleSection=T0;window.selectWorkflowStep=it;window.copyCode=M0;window.retryWithDifferentModel=B0;window.openApiKeysModal=Rl;window.closeApiKeysModal=Oh;window.openComposerSettings=r0;window.closeComposerSettings=s0;window.walkthroughConnectAccount=i0;window.closeWalkthroughModal=a0;window.openWalkthroughModal=o0;window.advanceWalkthrough=Tl;window.commitToFlutterFlow=A0;function Pw(){const t=document.getElementById("pipeline-input");t&&t.focus()}function Fw(){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=Pw;window.openModelSelector=Fw;window.handlePromptImageSelect=Hy;window.removePromptImage=Wy;window.saveApiKeys=u0;window.validateFlutterFlowConnection=Ml;window.clearAllApiKeys=d0;window.toggleKeyVisibility=v0;window.handleWelcomeVideoEnd=yw;window.dismissWelcomeVideo=Nn;window.initiateCommitToFlutterFlow=D0;window.updateFlutterFlowCredentialStatus=H0;window.openCommitConfirmModal=Kl;window.closeCommitConfirmModal=cp;window.closeCommitSuccessModal=Ew;window.closeCommitTerminalModal=Sw;window.showCommitPartialModal=fp;window.showCommitUnconfirmedModal=hp;window.showCommitSuccessModal=up;window.showCommitFailureModal=dp;window.toggleCodePreview=xw;window.confirmCommitToFlutterFlow=Aw;window.runRefinement=Jh;window.regenerateFromPastedErrors=Zh;window.clearErrorInput=O0;window.setFlutterFlowEndpoint=n0;window.getFlutterFlowEndpoint=yt;window.commitProgress=Be;window.openSignInModal=Ws;window.closeSignInModal=np;window.handleMagicLinkRequest=G0;window.handleSignOut=K0;window.handleSendNewLink=Z0;window.handleClearCache=X0;window.handleDeleteAccount=Q0;window.closeDeleteUnavailableModal=ew;window.startCheckout=dw;window.openCustomerPortal=fw;window.openPricingModal=di;window.closePricingModal=lp;let jr=null,_p=null,On={1:"pending",2:"pending",3:"pending"},Zl=1,Xl=null;const Vs={1:"Prompt Architect",2:"Code Generator",3:"Code Review"},Rw={1:"Understanding your prompt",2:"Generating Dart code",3:"Running the code audit"},Tw={1:"Prompt understood",2:"Dart code generated",3:"Code audit complete"};function Gs(){return y.runId+=1,y.runId}function re(t){return t===void 0||t===y.runId}function $w(){y.runId+=1}function Ql(t){return document.getElementById(`pdot-${t}`)}function Ka(t){const e=document.getElementById("btn-run-pipeline")||document.getElementById("hero-send");e&&(e.disabled=t,e.classList.toggle("is-busy",t),t?e.setAttribute("aria-busy","true"):e.removeAttribute("aria-busy"))}function Ks(t){const e=document.getElementById("pipeline-progress");e&&(e.dataset.runState=t)}function Rn(t,e){On[t]=e;const n=Ql(t);if(!n)return;n.dataset.state=e,n.disabled=e==="pending"||e==="skipped";const i=Vs[t],r={pending:"not started",active:"in progress",done:"complete",failed:"failed",skipped:"not run"};n.setAttribute("aria-label",`Step ${t} of 3, ${i}: ${r[e]||e}`),e==="active"?n.setAttribute("aria-current","step"):n.removeAttribute("aria-current")}function Mw(){return[1,2,3].filter(t=>On[t]==="done").length}function Ys(){const t=document.getElementById("pipeline-progress-fill");t&&(t.style.width=`${Mw()/3*100}%`);const e=document.getElementById("progress-stage-count");e&&(e.textContent=`Step ${Zl} of 3`)}function Js(t,{done:e=!1}={}){const n=document.getElementById("progress-title-text"),i=document.getElementById("progress-substep-text"),r=On[t],s=e||r==="done";if(n&&(n.textContent=s?Tw[t]:Rw[t]),i){const o=s?" — complete":r==="failed"?" — stopped":"";i.textContent=`Step ${t} of 3 — ${Vs[t]}${o}`}}function Lw(t){On[t]==="pending"||On[t]==="skipped"||(Xl=t,[1,2,3].forEach(e=>{const n=Ql(e);n&&n.setAttribute("aria-pressed",String(e===t))}),Js(t))}function ec(){Xl=null,[1,2,3].forEach(t=>{const e=Ql(t);e&&e.removeAttribute("aria-pressed")})}function yp(t){const e=document.getElementById("pipeline-note");e&&(e.textContent=t||"",e.hidden=!t)}function Nw(t,e,n){re(n)&&yp(`${Gt(t)} did not answer. Continuing on ${Gt(e)}.`)}function tc(){const t=document.getElementById("pipeline-failure");if(!t)return;t.hidden=!0;const e=document.getElementById("pipeline-failure-actions");e&&e.replaceChildren()}const Ow=1120;function Bw(){const t=getComputedStyle(document.documentElement).getPropertyValue("--t-morph").trim(),e=Number.parseFloat(t);return Number.isFinite(e)&&e>0?e:Ow}let Qn=null,Ur=null;function Dw(){return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0}function dn(){if(Ur){try{Ur.cancel()}catch{}Ur=null}Qn&&(Qn.remove(),Qn=null),window.removeEventListener("resize",dn)}function wp(t,e){if(dn(),Dw()||!t||!e||!document.body||typeof Element.prototype.animate!="function")return;const n=t.getBoundingClientRect(),i=e.getBoundingClientRect();if(!n.width||!n.height||!i.width||!i.height)return;const r=document.createElement("div");r.className="composer-morph",r.setAttribute("aria-hidden","true"),r.style.cssText=`left:${i.left}px;top:${i.top}px;width:${i.width}px;height:${i.height}px;opacity:0;`,document.body.appendChild(r);const s=n.left+n.width/2-(i.left+i.width/2),o=n.top+n.height/2-(i.top+i.height/2),a=n.width/i.width,l=n.height/i.height,u=`translate(${s}px,${o}px) scale(${a},${l})`,c=r.animate([{transform:u,opacity:0,offset:0,easing:"cubic-bezier(.2,0,0,1)"},{transform:u,opacity:1,offset:.14,easing:"cubic-bezier(.4,0,.2,1)"},{transform:`translate(${s}px,${o}px) scale(${a*.93},${l*.93})`,opacity:1,offset:.28,easing:"cubic-bezier(.32,1.38,.5,1)"},{transform:"translate(0px,0px) scale(1,1)",opacity:1,offset:1}],{duration:Bw(),fill:"both"});Qn=r,Ur=c,window.addEventListener("resize",dn),c.onfinish=()=>{if(Qn!==r)return;const d=r.animate([{opacity:1},{opacity:0}],{duration:260,fill:"forwards"});d.onfinish=()=>{Qn===r&&dn()}}}function jw(){const e=document.getElementById("composer")?.getBoundingClientRect();e&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{wp({getBoundingClientRect:()=>e},document.getElementById("main-stage-container"))})})}function Uw(){wp(document.getElementById("pipeline-progress"),document.getElementById("main-stage-container"))}window.addEventListener("hashchange",dn);window.addEventListener("popstate",dn);function Zs(t={}){const{prompt:e=null,runId:n}=t;if(!re(n))return;Qs(),nn(!0);const i=document.getElementById("pipeline-progress"),r=document.getElementById("results-view"),s=document.getElementById("ready-state");if(s&&s.classList.add("hidden"),r&&r.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),i&&i.classList.add("visible"),Ks("running"),e!==null){const a=document.getElementById("pipeline-submitted-prompt");a&&(a.textContent=e)}_p=Date.now();const o=document.getElementById("progress-elapsed");o&&(o.textContent="0s"),On={1:"pending",2:"pending",3:"pending"},ec(),tc(),yp(""),[1,2,3].forEach(a=>Rn(a,"pending")),Ft(1,n),Hw()}function Ft(t,e){re(e)&&(Zl=t,ec(),[1,2,3].forEach(n=>{n===t?Rn(n,"active"):nt&&Rn(n,"pending")}),Js(t),Ys())}function tn(t,e){re(e)&&(Rn(t,"done"),Xl===null&&Js(t,{done:!0}),Ys())}function bp(t,{stage:e=1,runId:n,retry:i=Ep}={}){if(!re(n))return;Xs(),Qs(),dn(),Ks("failed"),nn(!0);const r=document.getElementById("pipeline-progress");r&&r.classList.add("visible");const s=document.getElementById("results-view");s&&s.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),Rn(e,"failed"),[1,2,3].forEach(p=>{p>e&&Rn(p,"pending")}),Zl=e,ec(),Js(e),Ys();const o=Sh(t),a=document.getElementById("pipeline-failure"),l=document.getElementById("pipeline-failure-title"),u=document.getElementById("pipeline-failure-message"),c=document.getElementById("pipeline-failure-hint"),d=document.getElementById("pipeline-failure-actions");if(!a||!l||!u||!d)return;if(a.dataset.kind=o.kind,l.textContent=`${Vs[e]}: ${o.title}`,u.textContent=o.message,c){const p=o.detail&&o.detail!==o.message?o.detail:"";c.textContent=p,c.hidden=!p}d.replaceChildren();const h=[o.canUpgrade&&{id:"upgrade",label:"View plans",variant:"primary",onClick:()=>di()},o.canRetry&&{id:"retry",label:"Retry",variant:o.canUpgrade?"secondary":"primary",onClick:i},o.canEdit&&{id:"edit",label:"Edit prompt",variant:"secondary",onClick:Ya}].filter(Boolean);!o.canEdit&&!o.canRetry&&h.push({id:"edit",label:"Back to prompt",variant:"secondary",onClick:Ya}),h.forEach(p=>{const g=document.createElement("button");g.type="button",g.textContent=p.label,g.dataset.action=p.id,g.dataset.variant=p.variant,g.addEventListener("click",p.onClick),d.appendChild(g)}),a.hidden=!1;const f=d.querySelector("button");f&&f.focus({preventScroll:!0})}function Ya(){$w(),hw(),y.isRunning=!1,Ka(!1),rn(),Ks("settled"),dn(),Xs(),Qs(),tc();const t=document.getElementById("pipeline-progress");t&&t.classList.remove("visible"),nn(!1);const e=document.getElementById("pipeline-input");e&&(y.submittedPrompt&&(e.value=y.submittedPrompt,e.dispatchEvent(new Event("input",{bubbles:!0}))),e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length))}function Ep(){const t=document.getElementById("pipeline-input");t&&y.submittedPrompt&&(t.value=y.submittedPrompt,t.dispatchEvent(new Event("input",{bubbles:!0}))),Oe=y.submittedImages.slice(),cn(),tc(),or()}function Hw(){Xs(),jr=setInterval(()=>{const t=(Date.now()-_p)/1e3,e=document.getElementById("progress-elapsed");e&&(e.textContent=`${Math.floor(t)}s`)},250)}function Xs(){jr&&(clearInterval(jr),jr=null)}let Vi=null;function Qs(){Vi&&(clearTimeout(Vi),Vi=null)}function cr(){Xs(),Qs(),Ks("settled"),Ys();const t=document.getElementById("pipeline-progress-fill");Vi=setTimeout(()=>{Vi=null;const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function Tn(t,e=""){const n={pass:'',warning:'',fail:'',info:''};return``}function Sp(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function Ww(){return m_({bundle:y.artifactBundle,reviewResult:y.step3Result})}function zw(t){return`
    ${Tn(t.severity)}
    -
    ${q(t.message)}
    - ${t.suggestion?`
    ${q(t.suggestion)}
    `:""} - ${q(t.source)} +
    ${z(t.message)}
    + ${t.suggestion?`
    ${z(t.suggestion)}
    `:""} + ${z(t.source)}
    - `}function Ww(t){return` + `}function qw(t){return`
  • - ${q(t.title)} - ${t.detail&&t.detail!==t.title?`

    ${q(t.detail)}

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

    ${z(t.detail)}

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

      ${Tn("warning")} Bundle

        - ${t.warnings.map(u=>`
      • ${q(u)}
      • `).join("")} + ${t.warnings.map(u=>`
      • ${z(u)}
      • `).join("")}
      `:"",l=t.manualSteps.length?` @@ -207,8 +207,8 @@ Error: ${g}
        ${t.manualSteps.map(u=>`
      • - ${q(u.title)} - ${u.detail&&u.detail!==u.title?`${q(u.detail)}`:""} + ${z(u.title)} + ${u.detail&&u.detail!==u.title?`${z(u.detail)}`:""}
      • `).join("")}
      @@ -216,7 +216,7 @@ Error: ${g} `:"";e.innerHTML=`
      -

      ${q(t.summary)}

      +

      ${z(t.summary)}

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

      ${q(l.reason)}

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

      ${q(l.description)}

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

      ${z(l.reason)}

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

      ${z(l.description)}

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

      ${q(e.artifactName)}

      - ${e.description?`

      ${q(e.description)}

      `:""} + ${Tn(e.status)} ${z(Sp(e.status))} +

      ${z(e.artifactName)}

      + ${e.description?`

      ${z(e.description)}

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

      Manual FlutterFlow steps for this file

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

      Deployment

      -
      Status
      ${q(e.deployStatus||"pending")}
      +
      Status
      ${z(e.deployStatus||"pending")}
      Order
      ${e.index+1} of ${t.artifacts.length}
      -
      Path hint
      ${q(e.pathHint||"Not returned")}
      +
      Path hint
      ${z(e.pathHint||"Not returned")}
    @@ -297,7 +297,7 @@ Error: ${g}
      ${a}
    - `}function Vw(t){const e=document.getElementById("bundle-strip"),n=document.getElementById("results-summary-tab"),i=document.getElementById("artifact-tabs"),r=document.getElementById("results-file-count");if(n){const s=y.resultsViewMode==="summary";n.classList.toggle("active",s),n.setAttribute("role","tab"),n.setAttribute("aria-selected",String(s)),n.setAttribute("aria-controls","results-summary-detail"),n.tabIndex=s?0:-1}if(i&&(i.setAttribute("role","tablist"),i.setAttribute("aria-label","Artifacts in this bundle")),!t.artifacts.length){r&&(r.textContent="0 files"),e&&e.classList.remove("visible"),i&&(i.innerHTML=""),ld();return}if(r){const s=t.artifacts.length;r.textContent=`${s} ${s===1?"file":"files"}`}i&&(i.innerHTML=t.artifacts.map(s=>{const o=y.resultsViewMode==="file"&&s.id===y.selectedArtifactId;return` + `}function Kw(t){const e=document.getElementById("bundle-strip"),n=document.getElementById("results-summary-tab"),i=document.getElementById("artifact-tabs"),r=document.getElementById("results-file-count");if(n){const s=y.resultsViewMode==="summary";n.classList.toggle("active",s),n.setAttribute("role","tab"),n.setAttribute("aria-selected",String(s)),n.setAttribute("aria-controls","results-summary-detail"),n.tabIndex=s?0:-1}if(i&&(i.setAttribute("role","tablist"),i.setAttribute("aria-label","Artifacts in this bundle")),!t.artifacts.length){r&&(r.textContent="0 files"),e&&e.classList.remove("visible"),i&&(i.innerHTML=""),cd();return}if(r){const s=t.artifacts.length;r.textContent=`${s} ${s===1?"file":"files"}`}i&&(i.innerHTML=t.artifacts.map(s=>{const o=y.resultsViewMode==="file"&&s.id===y.selectedArtifactId;return` - `}).join(""),i.onclick=s=>{const o=s.target.closest(".artifact-tab");o?.dataset?.artifactId&&nc(o.dataset.artifactId)},ld()),e&&e.classList.add("visible")}function ld(){const t=document.getElementById("bundle-strip");!t||t.dataset.tabKeyboard==="bound"||(t.dataset.tabKeyboard="bound",t.addEventListener("keydown",e=>{if(e.defaultPrevented)return;const n=[document.getElementById("results-summary-tab"),...Array.from(document.querySelectorAll("#artifact-tabs .artifact-tab"))].filter(Boolean);if(!n.length||!n.includes(document.activeElement))return;let i=-1;const r=n.indexOf(document.activeElement);if(e.key==="ArrowRight")i=(r+1)%n.length;else if(e.key==="ArrowLeft")i=(r-1+n.length)%n.length;else if(e.key==="Home")i=0;else if(e.key==="End")i=n.length-1;else return;e.preventDefault();const s=n[i];if(!s)return;if(s.id==="results-summary-tab")Sp();else{const a=s.dataset.artifactId;a&&nc(a)}const o=s.id==="results-summary-tab"?document.getElementById("results-summary-tab"):document.querySelector(`#artifact-tabs .artifact-tab[data-artifact-id="${s.dataset.artifactId}"]`);o&&o.focus()}))}function eo(){document.body.classList.add("results-fullscreen"),document.body.classList.add("results-with-sidebar");const t=document.getElementById("results-view"),e=document.getElementById("results-code-output"),n=document.getElementById("results-audit-output"),i=document.getElementById("results-summary-detail"),r=document.getElementById("artifact-results-split"),s=Uw(),o=Ol();if(i&&(i.setAttribute("role","tabpanel"),i.setAttribute("aria-labelledby","results-summary-tab")),r){r.setAttribute("role","tabpanel");const a=s?.artifacts?.find(l=>l.id===y.selectedArtifactId);r.setAttribute("aria-labelledby",a?`artifact-tab-${a.id}`:"results-summary-tab")}if(qw(s),Vw(s),e&&(e.textContent=""),e){const a=Sh(o);e.innerHTML=a}n&&(n.innerHTML=zw(s)),i&&i.classList.toggle("hidden",y.resultsViewMode!=="summary"),r&&r.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function ur(t,e){nn(!0),y.selectedArtifactId||(y.selectedArtifactId=oi(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const n=document.getElementById("step3-output");n&&(n.textContent=""),eo(),rn(),Gw()}function Gw(){const t=document.getElementById("btn-feedback-up"),e=document.getElementById("btn-feedback-down"),n=document.getElementById("results-feedback-status");t&&(t.className="feedback-btn",t.setAttribute("aria-pressed","false"),t.disabled=!1,t.removeAttribute("aria-disabled")),e&&(e.className="feedback-btn",e.setAttribute("aria-pressed","false"),e.disabled=!1,e.removeAttribute("aria-disabled")),n&&(n.textContent=""),Ja=!1}function nc(t){y.selectedArtifactId=t,y.resultsViewMode="file",eo()}function Sp(){y.resultsViewMode="summary",eo()}function Kw(){const t=document.getElementById("btn-copy-results"),e=document.getElementById("results-copy-status"),n=Ol(),i=(r,s)=>{e&&(e.textContent=r,e.classList.toggle("ok",!!s),e.classList.toggle("fail",!s))};if(!navigator.clipboard?.writeText){i("Copying isn't supported in this browser.",!1);return}navigator.clipboard.writeText(n).then(()=>{if(i("Copied to clipboard",!0),t){t.classList.add("copied");const r=t.querySelector("span");if(r){const s=r.textContent;r.textContent="Copied!",setTimeout(()=>{t.classList.remove("copied"),r.textContent=s},2e3)}}}).catch(()=>{i("Clipboard permission was denied. Select the code to copy it manually.",!1)})}let Ja=!1;async function Yw(t){const e=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down"),i=document.getElementById("results-feedback-status");if(!e||!n||Ja)return;const r=l=>{i&&(i.textContent="",i.offsetWidth,i.textContent=l)},s=l=>{Ja=l,[e,n].forEach(u=>{u.disabled=l,u.setAttribute("aria-disabled",String(l))})},o=t==="up"?"thumbsUp":"thumbsDown";s(!0),r("Submitting review feedback…");const a={type:o,code:y.step2Result,input:y.step1Result};try{const l=await zl(a.type,a.code,a.input);if(!l||l.success!==!0){s(!1),r("Review feedback could not be sent. Tap again to retry.");return}e.classList.toggle("active-up",t==="up"),n.classList.toggle("active-down",t==="down"),e.setAttribute("aria-pressed",String(t==="up")),n.setAttribute("aria-pressed",String(t==="down")),s(!1),r("Review feedback saved.")}catch{s(!1),r("Review feedback could not be sent. Tap again to retry.")}}function Jw(){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 xp(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}function nn(t){const e=document.getElementById("generation-stage");e&&(t?(e.hidden=!1,e.inert=!1,requestAnimationFrame(()=>e.classList.add("is-active"))):(e.classList.remove("is-active"),e.inert=!0,setTimeout(()=>{e.classList.contains("is-active")||(e.hidden=!0)},260)))}function Ip(){const t=z.isVerified&&!!z.email,e=ce.tier||"free",n=t&&pi(),i=!t||Tt(),s=n?"Checking…":i?gl[e]||"Free":"—",o=document.getElementById("topbar-plan");o&&(o.textContent=s);const a=document.getElementById("topbar-avatar");a&&(a.textContent=(z.email||"?")[0].toUpperCase()),Gl();const l=document.getElementById("plans-free-current");l&&l.classList.toggle("hidden",e!=="free"||!i);const u=document.getElementById("plans-checkout-btn-professional");if(u){const d=e==="professional"&&i;u.disabled=d,u.textContent=d?"Current plan":"Subscribe"}const c=document.getElementById("plans-checkout-btn-power");if(c){const d=e==="power"&&i;c.disabled=d,c.textContent=d?"Current plan":"Subscribe"}}function Zw(){Ip();const t=document.getElementById("credits-modal");t&&He(t)}function Xw(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("credits-modal");e&&We(e)}function kp(t,e=!0,n=!0){if(t=["home","account","plans"].includes(t)?t:"home",document.querySelectorAll(".view[data-view]").forEach(r=>{r.dataset.view===t?(r.hidden=!1,r.removeAttribute("inert"),requestAnimationFrame(()=>{r.classList.add("is-active"),n&&r.focus({preventScroll:!0})})):(r.classList.remove("is-active"),r.setAttribute("inert","true"),setTimeout(()=>{r.classList.contains("is-active")||(r.hidden=!0)},260))}),t!=="home")nn(!1);else{const r=document.getElementById("main-stage-container");r&&r.classList.contains("visible")&&nn(!0)}if(document.querySelectorAll(".nav-link[data-view]").forEach(r=>{const s=r.dataset.view===t;r.setAttribute("aria-current",s?"page":null),s||r.removeAttribute("aria-current")}),e){const r=t==="home"?"":`#${t}`;window.location.hash!==r&&window.history.pushState({view:t},"",r||"#")}}let cd=!1;function ic(){const t=window.location.hash.replace(/^#/,"");kp(t||"home",!1,cd),cd=!0}window.addEventListener("popstate",t=>{ic()});window.addEventListener("hashchange",()=>{ic()});window.copyResultsCode=Kw;window.selectArtifact=nc;window.selectResultsSummary=Sp;window.submitResultsFeedback=Yw;window.showErrorInputPanel=Jw;window.hideErrorInputPanel=xp;window.setGenerationStageVisible=nn;window.switchView=kp;window.selectPipelineStage=$w;window.editPipelinePrompt=Ya;window.retryPipelineRun=bp;window.openCreditsModal=Zw;window.closeCreditsModal=Xw; + `}).join(""),i.onclick=s=>{const o=s.target.closest(".artifact-tab");o?.dataset?.artifactId&&nc(o.dataset.artifactId)},cd()),e&&e.classList.add("visible")}function cd(){const t=document.getElementById("bundle-strip");!t||t.dataset.tabKeyboard==="bound"||(t.dataset.tabKeyboard="bound",t.addEventListener("keydown",e=>{if(e.defaultPrevented)return;const n=[document.getElementById("results-summary-tab"),...Array.from(document.querySelectorAll("#artifact-tabs .artifact-tab"))].filter(Boolean);if(!n.length||!n.includes(document.activeElement))return;let i=-1;const r=n.indexOf(document.activeElement);if(e.key==="ArrowRight")i=(r+1)%n.length;else if(e.key==="ArrowLeft")i=(r-1+n.length)%n.length;else if(e.key==="Home")i=0;else if(e.key==="End")i=n.length-1;else return;e.preventDefault();const s=n[i];if(!s)return;if(s.id==="results-summary-tab")xp();else{const a=s.dataset.artifactId;a&&nc(a)}const o=s.id==="results-summary-tab"?document.getElementById("results-summary-tab"):document.querySelector(`#artifact-tabs .artifact-tab[data-artifact-id="${s.dataset.artifactId}"]`);o&&o.focus()}))}function eo(){document.body.classList.add("results-fullscreen"),document.body.classList.add("results-with-sidebar");const t=document.getElementById("results-view"),e=document.getElementById("results-code-output"),n=document.getElementById("results-audit-output"),i=document.getElementById("results-summary-detail"),r=document.getElementById("artifact-results-split"),s=Ww(),o=Ol();if(i&&(i.setAttribute("role","tabpanel"),i.setAttribute("aria-labelledby","results-summary-tab")),r){r.setAttribute("role","tabpanel");const a=s?.artifacts?.find(l=>l.id===y.selectedArtifactId);r.setAttribute("aria-labelledby",a?`artifact-tab-${a.id}`:"results-summary-tab")}if(Vw(s),Kw(s),e&&(e.textContent=""),e){const a=xh(o);e.innerHTML=a}n&&(n.innerHTML=Gw(s)),i&&i.classList.toggle("hidden",y.resultsViewMode!=="summary"),r&&r.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function ur(t,e){nn(!0),y.selectedArtifactId||(y.selectedArtifactId=oi(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const n=document.getElementById("step3-output");n&&(n.textContent=""),eo(),rn(),Yw()}function Yw(){const t=document.getElementById("btn-feedback-up"),e=document.getElementById("btn-feedback-down"),n=document.getElementById("results-feedback-status");t&&(t.className="feedback-btn",t.setAttribute("aria-pressed","false"),t.disabled=!1,t.removeAttribute("aria-disabled")),e&&(e.className="feedback-btn",e.setAttribute("aria-pressed","false"),e.disabled=!1,e.removeAttribute("aria-disabled")),n&&(n.textContent=""),Ja=!1}function nc(t){y.selectedArtifactId=t,y.resultsViewMode="file",eo()}function xp(){y.resultsViewMode="summary",eo()}function Jw(){const t=document.getElementById("btn-copy-results"),e=document.getElementById("results-copy-status"),n=Ol(),i=(r,s)=>{e&&(e.textContent=r,e.classList.toggle("ok",!!s),e.classList.toggle("fail",!s))};if(!navigator.clipboard?.writeText){i("Copying isn't supported in this browser.",!1);return}navigator.clipboard.writeText(n).then(()=>{if(i("Copied to clipboard",!0),t){t.classList.add("copied");const r=t.querySelector("span");if(r){const s=r.textContent;r.textContent="Copied!",setTimeout(()=>{t.classList.remove("copied"),r.textContent=s},2e3)}}}).catch(()=>{i("Clipboard permission was denied. Select the code to copy it manually.",!1)})}let Ja=!1;async function Zw(t){const e=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down"),i=document.getElementById("results-feedback-status");if(!e||!n||Ja)return;const r=l=>{i&&(i.textContent="",i.offsetWidth,i.textContent=l)},s=l=>{Ja=l,[e,n].forEach(u=>{u.disabled=l,u.setAttribute("aria-disabled",String(l))})},o=t==="up"?"thumbsUp":"thumbsDown";s(!0),r("Submitting review feedback…");const a={type:o,code:y.step2Result,input:y.step1Result};try{const l=await ql(a.type,a.code,a.input);if(!l||l.success!==!0){s(!1),r("Review feedback could not be sent. Tap again to retry.");return}e.classList.toggle("active-up",t==="up"),n.classList.toggle("active-down",t==="down"),e.setAttribute("aria-pressed",String(t==="up")),n.setAttribute("aria-pressed",String(t==="down")),s(!1),r("Review feedback saved.")}catch{s(!1),r("Review feedback could not be sent. Tap again to retry.")}}function Xw(){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 Ip(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}function nn(t){const e=document.getElementById("generation-stage");e&&(t?(e.hidden=!1,e.inert=!1,requestAnimationFrame(()=>e.classList.add("is-active"))):(e.classList.remove("is-active"),e.inert=!0,setTimeout(()=>{e.classList.contains("is-active")||(e.hidden=!0)},260)))}function kp(){const t=q.isVerified&&!!q.email,e=ce.tier||"free",n=t&&pi(),i=!t||Tt(),s=n?"Checking…":i?gl[e]||"Free":"—",o=document.getElementById("topbar-plan");o&&(o.textContent=s);const a=document.getElementById("topbar-avatar");a&&(a.textContent=(q.email||"?")[0].toUpperCase()),Gl();const l=document.getElementById("plans-free-current");l&&l.classList.toggle("hidden",e!=="free"||!i);const u=document.getElementById("plans-checkout-btn-professional");if(u){const d=e==="professional"&&i;u.disabled=d,u.textContent=d?"Current plan":"Subscribe"}const c=document.getElementById("plans-checkout-btn-power");if(c){const d=e==="power"&&i;c.disabled=d,c.textContent=d?"Current plan":"Subscribe"}}function Qw(){kp();const t=document.getElementById("credits-modal");t&&We(t)}function eb(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("credits-modal");e&&ze(e)}function Cp(t,e=!0,n=!0){if(t=["home","account","plans"].includes(t)?t:"home",document.querySelectorAll(".view[data-view]").forEach(r=>{r.dataset.view===t?(r.hidden=!1,r.removeAttribute("inert"),requestAnimationFrame(()=>{r.classList.add("is-active"),n&&r.focus({preventScroll:!0})})):(r.classList.remove("is-active"),r.setAttribute("inert","true"),setTimeout(()=>{r.classList.contains("is-active")||(r.hidden=!0)},260))}),t!=="home")nn(!1);else{const r=document.getElementById("main-stage-container");r&&r.classList.contains("visible")&&nn(!0)}if(document.querySelectorAll(".nav-link[data-view]").forEach(r=>{const s=r.dataset.view===t;r.setAttribute("aria-current",s?"page":null),s||r.removeAttribute("aria-current")}),e){const r=t==="home"?"":`#${t}`;window.location.hash!==r&&window.history.pushState({view:t},"",r||"#")}}let ud=!1;function ic(){const t=window.location.hash.replace(/^#/,"");Cp(t||"home",!1,ud),ud=!0}window.addEventListener("popstate",t=>{ic()});window.addEventListener("hashchange",()=>{ic()});window.copyResultsCode=Jw;window.selectArtifact=nc;window.selectResultsSummary=xp;window.submitResultsFeedback=Zw;window.showErrorInputPanel=Xw;window.hideErrorInputPanel=Ip;window.setGenerationStageVisible=nn;window.switchView=Cp;window.selectPipelineStage=Lw;window.editPipelinePrompt=Ya;window.retryPipelineRun=Ep;window.openCreditsModal=Qw;window.closeCreditsModal=eb; diff --git a/dist/index.html b/dist/index.html index 29ae3da..3218e9f 100644 --- a/dist/index.html +++ b/dist/index.html @@ -3313,7 +3313,7 @@ .send.is-busy .send-spin { animation: none; opacity: 0.6; } } - + diff --git a/e2e/stu380-deploy.spec.js b/e2e/stu380-deploy.spec.js index db16415..0ac1595 100644 --- a/e2e/stu380-deploy.spec.js +++ b/e2e/stu380-deploy.spec.js @@ -406,6 +406,53 @@ test.describe("STU-380 transport outcome regressions", () => { expect(outcome.outcome).toBe("unconfirmed"); }); + test("a runner failure after the deploy began is unconfirmed, not a refusal", async ({ page }) => { + await loadDeployHooks(page); + // The runner answers definitively — but only after the deploy phase + // started, so classes may already be written. + await page.route(ENDPOINTS.deployCustomClasses, async (route) => { + await route.fulfill({ + status: 200, + contentType: "application/x-ndjson", + body: + '{"event":"phase","phase":"deploy_start","message":"Deploying 1 custom class to FlutterFlow..."}\n' + + '{"event":"result","success":false,"error":"FlutterFlow AI DSL deploy failed.","exitCode":1}\n', + }); + }); + + const outcome = await settleAsOutcome( + page, + "__CCC_PROVISION_CUSTOM_CLASSES__", + [{ fileMap: newClassFileMap }], + ); + + expect(outcome.name).toBe("UnconfirmedDeployError"); + expect(outcome.outcome).toBe("unconfirmed"); + expect(outcome.message).toMatch(/after the deploy began/); + }); + + test("a provisioning failure before the deploy phase stays a refusal", async ({ page }) => { + await loadDeployHooks(page); + await page.route(ENDPOINTS.deployCustomClasses, async (route) => { + await route.fulfill({ + status: 200, + contentType: "application/x-ndjson", + body: + '{"event":"phase","phase":"verifying","message":"Compiling your custom code..."}\n' + + '{"event":"result","success":false,"error":"The generated custom code does not compile, so nothing was deployed to FlutterFlow.","analyzerErrors":["bad arg"]}\n', + }); + }); + + const outcome = await settleAsOutcome( + page, + "__CCC_PROVISION_CUSTOM_CLASSES__", + [{ fileMap: newClassFileMap }], + ); + + expect(outcome.name).toBe("Error"); + expect(outcome.message).toMatch(/does not compile/); + }); + test("a push that loses every response is unconfirmed, not a fabricated partial/failure", async ({ page }) => { await loadDeployHooks(page); // Both sync endpoints drop the request without a response — the push may diff --git a/src/provisionStream.js b/src/provisionStream.js index dea687a..6fa09fa 100644 --- a/src/provisionStream.js +++ b/src/provisionStream.js @@ -25,10 +25,12 @@ import { classifyDeployResult, DeployOutcome } from "./deployOutcome.js"; export async function readProvisionResponse(response, handlers = {}) { const { onPhase, onLog } = handlers; let finalResult = null; + let lastPhase = null; let buffer = ""; const handleEvent = (event) => { if (event.event === "phase") { + if (event.phase) lastPhase = event.phase; if (event.message && onPhase) onPhase(event.message); return; } @@ -80,6 +82,11 @@ export async function readProvisionResponse(response, handlers = {}) { finalResult.success === true || (finalResult.success === undefined && response.ok), finalResultReceived: true, + // Where the runner was when it answered: streamed runners report phases + // (and `uploading` proves the write began); non-streaming runners leave + // this null and only their HTTP status is meaningful. + runnerPhase: lastPhase, + httpStatus: response.status, }; } @@ -95,6 +102,7 @@ export async function readProvisionResponse(response, handlers = {}) { // remote write. httpRejected: !response.ok, httpStatus: response.status, + runnerPhase: lastPhase, error: !response.ok ? `FlutterFlow custom class provisioning failed (HTTP ${response.status}).` : readError @@ -103,6 +111,41 @@ export async function readProvisionResponse(response, handlers = {}) { }; } +// Runner phases that provably precede the first remote write: workspace setup +// and the compile-gate verification all run before the deploy script starts. +const PRE_WRITE_RUNNER_PHASES = new Set([ + "connected", + "workspace_init", + "workspace_ready", + "verifying", +]); + +/** + * Whether a runner-reported failure can be proven to precede the first remote + * write. A `result` event with success:false only proves the runner finished — + * the deploy CLI can fail (or time out) after its upload phase already wrote + * classes, so only these shapes count as definitive pre-write rejections: + * an explicit `preWrite` marker from the runner, a compile-gate report + * (`analyzerErrors`), a last-reported phase before `deploy_start`, or — for a + * non-streaming runner — a 4xx status (request validation, always pre-write). + * + * @param {Object} result - The result from `readProvisionResponse` + * @returns {boolean} True only when the failure is provably pre-write + */ +export function isPreWriteRunnerFailure(result) { + if (result?.preWrite === true) return true; + if (Array.isArray(result?.analyzerErrors) && result.analyzerErrors.length > 0) { + return true; + } + if (typeof result?.runnerPhase === "string") { + return PRE_WRITE_RUNNER_PHASES.has(result.runnerPhase); + } + if (typeof result?.httpStatus === "number") { + return result.httpStatus >= 400 && result.httpStatus < 500; + } + return false; +} + /** * Maps a provisioning stream result to the single truthful terminal outcome. * @@ -122,7 +165,14 @@ export async function readProvisionResponse(response, handlers = {}) { */ export function deployOutcomeOfStreamResult(result) { if (result?.finalResultReceived) { - return classifyDeployResult(result); + const outcome = classifyDeployResult(result); + // A runner-reported failure proves the runner finished, not that nothing + // was written: it is FAILED only when provably pre-write (verification, + // request validation). Once the deploy phase began, a CLI failure can + // follow classes already uploaded — that outcome stays UNCONFIRMED. + return outcome === DeployOutcome.FAILED && !isPreWriteRunnerFailure(result) + ? DeployOutcome.UNCONFIRMED + : outcome; } if (result?.httpRejected) { return DeployOutcome.FAILED; diff --git a/src/provisionStream.test.js b/src/provisionStream.test.js index a440767..eff319c 100644 --- a/src/provisionStream.test.js +++ b/src/provisionStream.test.js @@ -246,16 +246,94 @@ test("a delivered result is classified by the ordinary rule, not the rejection c ); assert.equal(deployOutcomeOfStreamResult(shipped), DeployOutcome.COMMITTED); - const runnerFailed = await readProvisionResponse( + // A compile-gate rejection is a verified pre-write failure: analyzerErrors + // prove verification ran and the deploy script never started. + const compileGateFailed = await readProvisionResponse( provisionAtStatus( [ - '{"event":"result","success":false,"error":"compile gate failed","exitCode":1}\n', + '{"event":"phase","phase":"verifying","message":"Compiling..."}\n', + '{"event":"result","success":false,"error":"The generated custom code does not compile, so nothing was deployed to FlutterFlow.","analyzerErrors":["bad arg"]}\n', ], 200, ), ); assert.equal( - deployOutcomeOfStreamResult(runnerFailed), + deployOutcomeOfStreamResult(compileGateFailed), DeployOutcome.FAILED, ); }); + +// --- STU-380: a runner failure after the deploy began is not a refusal ----- +// A streamed `{success:false}` proves the runner finished, not that nothing +// was written: the deploy CLI can die after its upload phase already wrote +// classes. Only provably pre-write failures stay FAILED. + +test("a failure after the deploy phase began is unconfirmed, not a clean refusal", async () => { + const result = await readProvisionResponse( + provisionAtStatus( + [ + '{"event":"phase","phase":"deploy_start","message":"Deploying..."}\n', + '{"event":"result","success":false,"error":"FlutterFlow AI DSL deploy failed.","exitCode":1}\n', + ], + 200, + ), + ); + + assert.equal(result.runnerPhase, "deploy_start"); + assert.equal( + deployOutcomeOfStreamResult(result), + DeployOutcome.UNCONFIRMED, + ); +}); + +test("a failure reported during upload is unconfirmed even though the runner answered", async () => { + const result = await readProvisionResponse( + provisionAtStatus( + [ + '{"event":"phase","phase":"deploy_start","message":"Deploying..."}\n', + '{"event":"phase","phase":"uploading","message":"Saving the changes to FlutterFlow..."}\n', + '{"event":"result","success":false,"error":"FlutterFlow AI DSL deploy timed out."}\n', + ], + 200, + ), + ); + + assert.equal(result.runnerPhase, "uploading"); + assert.equal( + deployOutcomeOfStreamResult(result), + DeployOutcome.UNCONFIRMED, + ); +}); + +test("a runner failure before the deploy phase is a definitive refusal", async () => { + const result = await readProvisionResponse( + provisionAtStatus( + [ + '{"event":"phase","phase":"workspace_init","message":"Preparing..."}\n', + '{"event":"result","success":false,"error":"FlutterFlow AI workspace initialization failed.","exitCode":1}\n', + ], + 200, + ), + ); + + assert.equal(result.runnerPhase, "workspace_init"); + assert.equal(deployOutcomeOfStreamResult(result), DeployOutcome.FAILED); +}); + +test("a non-streaming runner failure is refused on 4xx, unconfirmed on 5xx", async () => { + const refused = await readProvisionResponse( + new Response( + JSON.stringify({ success: false, error: "verification must be an object." }), + { status: 400 }, + ), + ); + assert.equal(deployOutcomeOfStreamResult(refused), DeployOutcome.FAILED); + + const cliFailed = await readProvisionResponse( + new Response( + JSON.stringify({ success: false, error: "FlutterFlow AI DSL deploy failed." }), + { status: 502 }, + ), + ); + assert.equal(deployOutcomeOfStreamResult(cliFailed), DeployOutcome.UNCONFIRMED); +}); From ffe5e914ea0e6cee0c1d0df43be0cb4f7f39934b Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Sun, 27 Sep 2026 17:52:41 +0000 Subject: [PATCH 11/16] fix(deploy): keep provisional cache + honest provenance on post-start failures MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three review findings on the stage-aware classification: - An unconfirmed throw after deploy_start sat outside the cache-invali- dating catch, leaving the pre-write snapshot for the next deploy to re-provision already-written classes. The final-result classification now runs inside the protected region. - A stalled error body hid a definitive push refusal: the retry loop awaited the diagnostic clone().text() and the parser awaited response.json() unboundedly, so a 4xx could expire the UI bound as unconfirmed. The log read is detached and the parse reads run under PUSH_BODY_READ_TIMEOUT_MS — status alone classifies on expiry. - Provisioning refusals carried remoteRefusal, so a runner-side compile gate or request-validation rejection rendered 'FlutterFlow refused this deploy'. The provisioning endpoint is our runner — its answers are pipeline failures, not FlutterFlow's — so the flag is dropped there and stays only on true sync-endpoint refusals. Co-Authored-By: Stuart Gardoll --- app.js | 95 ++++++++------ .../{index-B66yOOGg.js => index-DXRCh_lW.js} | 116 +++++++++--------- dist/index.html | 2 +- e2e/stu380-deploy.spec.js | 76 ++++++++++++ src/deployOutcome.js | 5 + 5 files changed, 200 insertions(+), 94 deletions(-) rename dist/assets/{index-B66yOOGg.js => index-DXRCh_lW.js} (75%) diff --git a/app.js b/app.js index d367a3c..1f7e9df 100644 --- a/app.js +++ b/app.js @@ -66,6 +66,7 @@ import { DeployOutcome, DEPLOY_UI_TIMEOUT_MS, exhaustedPushError, + PUSH_BODY_READ_TIMEOUT_MS, UnconfirmedDeployError, } from "./src/deployOutcome.js"; import { buildFlutterFlowSyncMetadata } from "./src/flutterFlowSyncMetadata.js"; @@ -2228,15 +2229,22 @@ class FlutterFlowApiClient { } lastHttpStatus = response.status; - let responseText; - try { - responseText = await response.clone().text(); - } catch (readError) { - responseText = "(unreadable response body)"; - } - console.log( - `Push to ${baseUrl} returned ${response.status}: ${responseText}`, - ); + // The status alone classifies this response — the body read is + // diagnostic only, so it runs detached: a stalled error body must + // not hide a definitive refusal behind the UI bound. + response + .clone() + .text() + .then( + (responseText) => + console.log( + `Push to ${baseUrl} returned ${response.status}: ${responseText}`, + ), + () => + console.log( + `Push to ${baseUrl} returned ${response.status} (unreadable response body)`, + ), + ); // A 5xx is the server's own failure report: it can be raised after // the write was applied, so it can never prove a refusal. @@ -2374,12 +2382,23 @@ class FlutterFlowApiClient { * @param {Response} response - Fetch response object * @returns {Promise} Parsed result with file warnings */ -async function parsePushCodeResponse(response) { +async function parsePushCodeResponse( + response, + bodyTimeoutMs = PUSH_BODY_READ_TIMEOUT_MS, +) { const originalResponse = response.clone(); let jsonResult; try { - jsonResult = await response.json(); + // The status alone classifies the response — the body only carries the + // error detail, so this read is bounded: a stalled body must not hide a + // definitive refusal (or an acceptance) behind the outer UI bound. + jsonResult = await withUiTimeout( + response.json(), + bodyTimeoutMs, + (resolve, reject) => + reject(new Error("The push response body stalled before it finished.")), + ); } catch (error) { // Both reads share the same connection: a body dropped mid-flight makes // the clone reject too. The received status is still definitive — a non-ok @@ -2387,7 +2406,11 @@ async function parsePushCodeResponse(response) { // before the body was lost. let text = ""; try { - text = await originalResponse.text(); + text = await withUiTimeout( + originalResponse.text(), + bodyTimeoutMs, + (resolve, reject) => reject(new Error("stalled")), + ); } catch (readError) { // The body never arrived; classify on the status alone. } @@ -2805,12 +2828,12 @@ async function provisionMissingCodeFiles( // remote state genuinely unknown and must be reported UNCONFIRMED. if (!result.finalResultReceived) { if (deployOutcomeOfStreamResult(result) === DeployOutcome.FAILED) { - const refusal = new Error( + // Not marked remoteRefusal: the refusal comes from our deploy runner, + // not from FlutterFlow — its answer was never requested. + throw new Error( result.error || `FlutterFlow custom class provisioning failed (HTTP ${result.httpStatus}).`, ); - refusal.remoteRefusal = true; - throw refusal; } throw new UnconfirmedDeployError( "The connection to the FlutterFlow deploy runner dropped before it reported a result. " + @@ -2818,6 +2841,26 @@ async function provisionMissingCodeFiles( "before retrying.", ); } + + if (!result.success) { + const details = result.details ? ` ${result.details}` : ""; + const message = `${result.error || "FlutterFlow custom class provisioning failed."}${details}`; + // A runner-reported failure is only a definitive refusal when it provably + // precedes the write; a failure after the deploy began can follow classes + // already uploaded, so it must be reported unconfirmed (and the catch + // below drops the stale snapshot). + if (deployOutcomeOfStreamResult(result) === DeployOutcome.UNCONFIRMED) { + throw new UnconfirmedDeployError( + `${message} The failure arrived after the deploy began — custom classes ` + + "may already be written. Open your FlutterFlow project to reconcile " + + "before retrying.", + ); + } + // A verified pre-write rejection (compile gate, workspace, request + // validation) is still the runner's answer — FlutterFlow was never + // asked — so it is a plain failure, not a remoteRefusal. + throw new Error(message); + } } catch (error) { // An unconfirmed provisioning may have written classes on the runner after // the client stopped waiting, so the cached pre-write project snapshot is @@ -2829,24 +2872,6 @@ async function provisionMissingCodeFiles( throw error; } - if (!result.success) { - const details = result.details ? ` ${result.details}` : ""; - const message = `${result.error || "FlutterFlow custom class provisioning failed."}${details}`; - // A runner-reported failure is only a definitive refusal when it provably - // precedes the write; a failure after the deploy began can follow classes - // already uploaded, so it must be reported unconfirmed. - if (deployOutcomeOfStreamResult(result) === DeployOutcome.UNCONFIRMED) { - throw new UnconfirmedDeployError( - `${message} The failure arrived after the deploy began — custom classes ` + - "may already be written. Open your FlutterFlow project to reconcile " + - "before retrying.", - ); - } - const refusal = new Error(message); - refusal.remoteRefusal = true; - throw refusal; - } - invalidateProjectSourceCache(apiClient); if (result.verificationSkipped) { @@ -8608,8 +8633,8 @@ if (import.meta.env.DEV) { // Lets the browser suite feed a crafted Response into the real sync-response // parser, so a body that drops mid-read can be proven to classify on the // received status instead of leaking the raw read error. - window.__CCC_PARSE_PUSH_RESPONSE__ = (response) => - parsePushCodeResponse(response); + window.__CCC_PARSE_PUSH_RESPONSE__ = (response, bodyTimeoutMs) => + parsePushCodeResponse(response, bodyTimeoutMs); // Lets the browser suite drive the bounded push (fetch + parse under the UI // timeout) with a short bound, so a stalled request provably settles as // unconfirmed instead of hanging the deploy. diff --git a/dist/assets/index-B66yOOGg.js b/dist/assets/index-DXRCh_lW.js similarity index 75% rename from dist/assets/index-B66yOOGg.js rename to dist/assets/index-DXRCh_lW.js index c541dd2..2013dac 100644 --- a/dist/assets/index-B66yOOGg.js +++ b/dist/assets/index-DXRCh_lW.js @@ -1,8 +1,8 @@ -(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const s of r)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function n(r){const s={};return r.integrity&&(s.integrity=r.integrity),r.referrerPolicy&&(s.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?s.credentials="include":r.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function i(r){if(r.ep)return;r.ep=!0;const s=n(r);fetch(r.href,s)}})();var w=typeof window<"u"?window:void 0,Ne=typeof globalThis<"u"?globalThis:w,He=Ne?.navigator,P=Ne?.document,me=Ne?.location,Za=Ne?.fetch,zo=Ne!=null&&Ne.XMLHttpRequest&&"withCredentials"in new Ne.XMLHttpRequest?Ne.XMLHttpRequest:void 0,uc=Ne?.AbortController,Mp=Ne?.CompressionStream,Ge=He?.userAgent;function dd(){return!(!w||w.navigator.onLine===!1)}var vi=typeof globalThis<"u"?globalThis:w;vi&&typeof self>"u"&&(vi.self=vi),vi&&typeof File>"u"&&(vi.File=function(){});var B=w??{},ne={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function dc(t,e,n,i,r,s,o){try{var a=t[s](o),l=a.value}catch(u){return void n(u)}a.done?e(l):Promise.resolve(l).then(i,r)}function se(t){return function(){var e=this,n=arguments;return new Promise((function(i,r){var s=t.apply(e,n);function o(l){dc(s,i,r,o,a,"next",l)}function a(l){dc(s,i,r,o,a,"throw",l)}o(void 0)}))}}function I(){return I=Object.assign?Object.assign.bind():function(t){for(var e=1;arguments.length>e;e++){var n=arguments[e];for(var i in n)({}).hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},I.apply(null,arguments)}function fd(t,e){if(t==null)return{};var n={};for(var i in t)if({}.hasOwnProperty.call(t,i)){if(e.indexOf(i)!==-1)continue;n[i]=t[i]}return n}var fc=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function hc(t){return typeof t=="string"||t}function pc(t){return typeof t=="string"?t:void 0}var _i,Lp=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],Ut=(function(t){return t.AnonymousId="anonymous_id",t.DistinctId="distinct_id",t.Props="props",t.EnablePersonProcessing="enable_person_processing",t.PersonMode="person_mode",t.FeatureFlagDetails="feature_flag_details",t.FeatureFlags="feature_flags",t.FeatureFlagPayloads="feature_flag_payloads",t.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",t.BootstrapFeatureFlags="bootstrap_feature_flags",t.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",t.OverrideFeatureFlags="override_feature_flags",t.Queue="queue",t.AiQueue="ai_queue",t.LogsQueue="logs_queue",t.OptedOut="opted_out",t.SessionId="session_id",t.SessionStartTimestamp="session_start_timestamp",t.SessionLastTimestamp="session_timestamp",t.PersonProperties="person_properties",t.GroupProperties="group_properties",t.InstalledAppBuild="installed_app_build",t.InstalledAppVersion="installed_app_version",t.SessionReplay="session_replay",t.PushRegistered="push_registered",t.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",t.SurveyLastSeenDate="survey_last_seen_date",t.SurveysSeen="surveys_seen",t.Surveys="surveys",t.RemoteConfig="remote_config",t.FlagsEndpointWasHit="flags_endpoint_was_hit",t.DeviceId="device_id",t})({}),gc=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),Np=["$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"],Op=["token"],hd="NativeGzipValidationError",qo=t=>t.length>=2&&t[0]===31&&t[1]===139,mc=(t,e)=>t===gc.GZipJS||e===gc.GZipJS||e==="gzip",vc=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",pr=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=hd,e},Bp=(function(){var t=se((function*(e,n){18>e.size&&pr("too-short");var i=new Uint8Array(yield e.slice(0,10).arrayBuffer());qo(i)&&i[2]===8||pr("invalid-header");var r=new DataView(yield e.slice(e.size-8).arrayBuffer());r.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(_i)return _i;_i=[];for(var c=0;256>c;c++){for(var d=c,h=0;8>h;h++)d=1&d?3988292384^d>>>1:d>>>1;_i[c]=d>>>0}return _i})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(n)&&pr("invalid-crc");var s=n.length>>>0;r.getUint32(4,!0)!==s&&pr("invalid-size")}));return function(e,n){return t.apply(this,arguments)}})();function Vo(){return Vo=se((function*(t,e,n){e===void 0&&(e=!0);try{var i=new TextEncoder().encode(t),r=new globalThis.CompressionStream("gzip"),s=r.writable.getWriter(),o=s.write(i).then((()=>s.close())).catch((function(){var u=se((function*(c){try{yield s.abort(c)}catch{}throw c}));return function(c){return u.apply(this,arguments)}})()),a=new Response(r.readable).blob(),l=(yield Promise.all([a,o]))[0];return yield Bp(l,i),l}catch(u){if(n!=null&&n.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),Vo.apply(this,arguments)}var Dp=["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"],_c=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var n=t.toLowerCase();return Dp.concat(e).some((i=>{var r=i.toLowerCase();return n.indexOf(r)!==-1}))};function j(t,e){return t.indexOf(e)!==-1}var xs=function(t){return t.trim()},Go=function(t){return t.replace(/^\$/,"")};function pd(t){var e,n=[];return(e=JSON.stringify(t,(function(i,r){if(typeof r=="bigint")return r.toString();if(typeof r!="function"&&typeof r!="symbol"){if(r instanceof Error)return{name:r.name,message:r.message,stack:r.stack};if(r&&typeof r=="object"){for(;n.length>0&&n[n.length-1]!==this;)n.pop();if(n.includes(r))return"[Circular]";n.push(r)}return r}})))!==null&&e!==void 0?e:"null"}var gd=Object.prototype,md=gd.hasOwnProperty,Is=gd.toString,U=Array.isArray||function(t){return Is.call(t)==="[object Array]"},je=t=>typeof t=="function",he=t=>t===Object(t)&&!U(t),Kt=t=>{if(he(t)){for(var e in t)if(md.call(t,e))return!1;return!0}return!1},C=t=>t===void 0,X=t=>Is.call(t)=="[object String]",Ko=t=>X(t)&&t.trim().length===0,Ye=t=>t===null,H=t=>C(t)||Ye(t),ke=t=>Is.call(t)=="[object Number]"&&t==t,Dt=t=>ke(t)&&t>0,mt=t=>Is.call(t)==="[object Boolean]",jp=t=>t instanceof FormData,Up=t=>j(Np,t),Hp=t=>j(Op,t);function vd(t){return t===null||typeof t!="object"}function Hr(t,e){return{}.toString.call(t)==="[object "+e+"]"}function Xa(t){return typeof Event<"u"&&_d(t,Event)}function _d(t,e){try{return t instanceof e}catch{return!1}}var Wp=[!0,"true",1,"1","yes"],uo=t=>j(Wp,t),zp=[!1,"false",0,"0","no"];function At(t,e,n,i,r){return e>n&&(i.warn("min cannot be greater than max."),e=n),ke(t)?t>n?(i.warn(" cannot be greater than max: "+n+". Using max value instead."),n):e>t?(i.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(i.warn(" must be a number. using max or fallback. max: "+n+", fallback: "+r),At(r||n,e,n,i))}class qp{constructor(e){this.tt={},this.et=e.et,this.it=At(e.bucketSize,0,100,e.rt),this.nt=At(e.refillRate,0,this.it,e.rt),this.st=At(e.refillInterval,0,864e5,e.rt)}ot(e,n){var i=Math.floor((n-e.lastAccess)/this.st);i>0&&(e.tokens=Math.min(e.tokens+i*this.nt,this.it),e.lastAccess=e.lastAccess+i*this.st)}consumeRateLimit(e){var n,i=Date.now(),r=String(e),s=this.tt[r];return s?this.ot(s,i):this.tt[r]=s={tokens:this.it,lastAccess:i},s.tokens===0||(s.tokens--,s.tokens===0&&((n=this.et)==null||n.call(this,e)),s.tokens===0)}stop(){this.tt={}}}var rt="Mobile",Wr="iOS",Yt="Android",ei="Tablet",yd=Yt+" "+ei,wd="iPad",bd="Apple",Ed=bd+" Watch",Bi="Safari",ti="BlackBerry",Sd="Samsung",xd=Sd+"Browser",Id=Sd+" Internet",Pn="Chrome",Vp=Pn+" OS",kd=Pn+" "+Wr,Qa="Internet Explorer",Cd=Qa+" "+rt,el="Opera",Gp=el+" Mini",tl="Edge",Ad="Microsoft "+tl,Zn="Firefox",Pd=Zn+" "+Wr,Gi="Nintendo",Ki="PlayStation",Xn="Xbox",Fd=Yt+" "+rt,Rd=rt+" "+Bi,Pi="Windows",Yo=Pi+" Phone",yc="Nokia",Jo="Ouya",Td="Generic",Kp=Td+" "+rt.toLowerCase(),$d=Td+" "+ei.toLowerCase(),Zo="Konqueror",Md="Oculus Browser",zr="Vivaldi",Ld="Yandex",qr="Whale",Xo="DuckDuckGo",Nd="Pale Moon",Vr="Waterfox",Di="Brave",Od="Google Search App",we="(\\d+(\\.\\d+)?)",fo=new RegExp("Version/"+we),Yp=new RegExp(Xn,"i"),Jp=new RegExp(Ki+" \\w+","i"),Zp=new RegExp(Gi+" \\w+","i"),nl=new RegExp(ti+"|PlayBook|BB10","i"),Xp={"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"},Bd=function(t,e,n,i){e=e||"";var r=(function(s){return s!=null&&s.brave?Di:null})(n);return r||(i!=null&&i.detectGoogleSearchApp&&j(t,"GSA/")?Od:j(t," OPR/")&&j(t,"Mini")?Gp:j(t," OPR/")?el:nl.test(t)?ti:j(t,"IE"+rt)||j(t,"WPDesktop")?Cd:j(t,"OculusBrowser")?Md:j(t,xd)?Id:j(t,tl)||j(t,"Edg/")?Ad:j(t,zr+"/")?zr:j(t,"YaBrowser/")?Ld:j(t,qr+"/")?qr:j(t,Xo+"/")||j(t,"Ddg/")?Xo:j(t,"FBIOS")?"Facebook "+rt:j(t,"UCWEB")||j(t,"UCBrowser")?"UC Browser":j(t,"CriOS")?kd:j(t,"CrMo")||j(t,Pn)?Pn:j(t,Yt)&&j(t,Bi)?Fd:j(t,"FxiOS")?Pd:j(t.toLowerCase(),Zo.toLowerCase())?Zo:j(t,Di+"/")?Di:((s,o)=>o&&j(o,bd)||(function(a){return j(a,Bi)&&!j(a,Pn)&&!j(a,Yt)})(s))(t,e)?j(t,rt)?Rd:Bi:j(t,"PaleMoon/")?Nd:j(t,Vr+"/")?Vr:j(t,Zn)?Zn:j(t,"MSIE")||j(t,"Trident/")?Qa:j(t,"Gecko")?Zn:"")},Qp={[Cd]:[new RegExp("rv:"+we)],[Ad]:[new RegExp(tl+"?\\/"+we)],[Pn]:[new RegExp("("+Pn+"|CrMo)\\/"+we)],[kd]:[new RegExp("CriOS\\/"+we)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+we)],[Bi]:[fo],[Rd]:[fo],[el]:[new RegExp("(Opera|OPR)\\/"+we)],[Zn]:[new RegExp(Zn+"\\/"+we)],[Pd]:[new RegExp("FxiOS\\/"+we)],[Zo]:[new RegExp("Konqueror[:/]?"+we,"i")],[ti]:[new RegExp(ti+" "+we),fo],[Fd]:[new RegExp("android\\s"+we,"i")],[Id]:[new RegExp(xd+"\\/"+we)],[Md]:[new RegExp("OculusBrowser\\/"+we)],[zr]:[new RegExp(zr+"\\/"+we)],[Ld]:[new RegExp("YaBrowser\\/"+we)],[qr]:[new RegExp(qr+"\\/"+we)],[Di]:[new RegExp(Di+"\\/"+we)],[Xo]:[new RegExp("(DuckDuckGo|Ddg)\\/"+we)],[Nd]:[new RegExp("PaleMoon\\/"+we)],[Vr]:[new RegExp(Vr+"\\/"+we)],[Od]:[new RegExp("GSA\\/"+we)],[Qa]:[new RegExp("(rv:|MSIE )"+we)],Mozilla:[new RegExp("rv:"+we)]},eg=function(t,e,n,i){var r=Bd(t,e,n,i),s=Qp[r];if(C(s))return null;for(var o=0;s.length>o;o++){var a=t.match(s[o]);if(a)return parseFloat(a[a.length-2])}return null},wc=[[new RegExp(Xn+"; "+Xn+" (.*?)[);]","i"),t=>[Xn,t&&t[1]||""]],[new RegExp(Gi,"i"),[Gi,""]],[new RegExp(Ki,"i"),[Ki,""]],[nl,[ti,""]],[new RegExp(Pi,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Yo,""];if(new RegExp(rt).test(e)&&!/IEMobile\b/.test(e))return[Pi+" "+rt,""];var n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){var i=Xp[n[1]]||"";return/arm/i.test(e)&&(i="RT"),[Pi,i]}return[Pi,""]}],[/((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=C(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+Yt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Yt+")","i"),t=>t&&t[2]?[Yt,[t[2],t[3],t[4]||"0"].join(".")]:[Yt,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{var e=["Mac OS X",""];return t&&t[1]&&(e[1]=[t[1],t[2],t[3]||"0"].join(".")),e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[Vp,""]],[/Linux|debian/i,["Linux",""]]],bc=function(t){return Zp.test(t)?Gi:Jp.test(t)?Ki:Yp.test(t)?Xn:new RegExp(Jo,"i").test(t)?Jo:new RegExp("("+Yo+"|WPDesktop)","i").test(t)?Yo:/iPad/.test(t)?wd:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?Ed:nl.test(t)?ti:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(yc,"i").test(t)?yc:/(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(rt).test(t)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(t)||/pixel[\daxl ]{1,6}/i.test(t)&&!/pixel c/i.test(t)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(t)||/lmy47v/i.test(t)&&!/QTAQZ3/i.test(t)?Yt:yd:new RegExp("(pda|"+rt+")","i").test(t)?Kp:new RegExp(ei,"i").test(t)&&!new RegExp(ei+" pc","i").test(t)?$d:""},tg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ec(t,e){return typeof(n=t)=="string"&&tg.test(n)?t:e();var n}function fn(t){return t&&t.split("#")[0]}function il(t,e){var n=setTimeout(t,e);return n?.unref&&n?.unref(),n}function Sc(t,e,n){return Dd.apply(this,arguments)}function Dd(){return(Dd=se((function*(t,e,n){var i;try{return yield Promise.race([t,new Promise(((r,s)=>{i=il((()=>{try{n?.(),r()}catch(o){s(o)}}),e)}))])}finally{clearTimeout(i)}}))).apply(this,arguments)}var ng=t=>t instanceof Error,jd={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}},ig=jd.info;function Ud(t){if(mt(t))return{boolValue:t};if(typeof t=="number")return Number.isFinite(t)?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:{stringValue:String(t)};if(typeof t=="string")return{stringValue:t};if(U(t))return{arrayValue:{values:t.map((e=>Ud(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function Gr(t){var e=[];for(var n in t){var i=t[n];Ye(i)||C(i)||e.push({key:n,value:Ud(i)})}return e}function rg(t,e){var n=jd[t.level||"info"]||ig,i=n.text,r=n.number,s=String(Date.now())+"000000",o={};e.distinctId&&(o.posthogDistinctId=e.distinctId),e.sessionId&&(o.sessionId=e.sessionId),e.windowId&&(o["window.id"]=e.windowId),H(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),H(e.lastActivityTimestamp)||(o.lastActivityTimestamp=String(e.lastActivityTimestamp)),e.currentUrl&&(o["url.full"]=e.currentUrl),e.screenName&&(o["screen.name"]=e.screenName),e.appState&&(o["app.state"]=e.appState),e.activeFeatureFlags&&e.activeFeatureFlags.length>0&&(o.feature_flags=e.activeFeatureFlags);var a=I({},o,t.attributes||{}),l={timeUnixNano:s,observedTimeUnixNano:s,severityNumber:r,severityText:i,body:{stringValue:t.body},attributes:Gr(a)};return t.trace_id&&(l.traceId=t.trace_id),t.span_id&&(l.spanId=t.span_id),C(t.trace_flags)||(l.flags=t.trace_flags),l}function Hd(t,e,n){return I({},t.resourceAttributes,{"service.name":t.serviceName||"unknown_service"},t.environment&&{"deployment.environment":t.environment},t.serviceVersion&&{"service.version":t.serviceVersion},{"telemetry.sdk.name":e,"telemetry.sdk.version":n})}function Wd(t,e,n,i){return{resourceLogs:[{resource:{attributes:Gr(e)},scopeLogs:[{scope:{name:n,version:i},logRecords:t}]}]}}let sg=class{constructor(t,e,n,i,r,s,o){var a;s===void 0&&(s=()=>Promise.resolve()),this._instance=t,this.Ne=e,this.rt=n,this.ut=i,this.ht=r,this.dt=s,this.vt=o,this.ct=null,this.ft=0,this.yt=0,this.bt=0,this._t=0,this.wt=!1,this.kt=e.maxBufferSize,this.xt=Math.max((a=e.maxQueueSize)!==null&&a!==void 0?a:e.maxBufferSize,e.maxBufferSize),this.St=e.flushIntervalMs,this.Ct=e.maxBatchRecordsPerPost,this.Mt=e.rateCapWindowMs,this.Tt=e.maxLogsPerInterval}reset(){this.Et(),this.ct=null,this.bt=0,this._t=0,this.wt=!1,this.ft=0,this.yt=0,this.Ct=this.Ne.maxBatchRecordsPerPost}onReconnect(){this.yt=0,this.It()}captureLog(t){if(!this._instance.isDisabled&&!this._instance.optedOut&&t!=null&&t.body){var e=this.Pt(t);if(e!==null)if(e.body){if(this.Rt()){var n={record:rg(e,this.ut())};this.ht((()=>this.At(n)))}}else this.rt.info("Log was rejected in beforeSend function")}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Log was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for log:",o),null}return i}Rt(){if(this.Tt===void 0)return!0;var t=Date.now(),e=t-this.bt;return this.Mt>e&&e>=0||(this.bt=t,this._t=0,this.wt=!1),this.Tt>this._t?(this._t++,!0):(this.wt||(this.rt.warn("captureLog dropping logs: exceeded "+this.Tt+" logs per "+this.Mt+"ms"),this.wt=!0),!1)}flush(){var t=this;return se((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return se((function*(){var e;t.Et();var n=(e=t._instance.getPersistedProperty(Ut.LogsQueue))!==null&&e!==void 0?e:[];if(n.length!==0)for(var i=n.length,r=0;n.length>0&&i>r;){var s,o;t.ft=0;var a=Math.min(n.length,t.Ct),l=n.slice(0,a),u=Wd(l.map((d=>d.record)),t.Lt(),(s=t.vt)!==null&&s!==void 0?s:t._instance.getLibraryId(),t._instance.getLibraryVersion()),c=yield t._instance.Ot(u);if(c.kind==="too-large"&&l.length>1)t.Ct=Math.max(1,Math.floor(l.length/2)),t.rt.warn("Received 413 when sending logs batch of size "+l.length+", reducing batch size to "+t.Ct);else if(c.kind==="retry-later"||(c.kind==="too-large"?t.rt.warn("Dropping a single log record after 413 with batch size 1 — the record is larger than the server cap and cannot be split further."):c.kind==="ok"&&t.Ne.maxBatchRecordsPerPost>t.Ct&&(t.Ct=Math.min(t.Ne.maxBatchRecordsPerPost,t.Ct+1)),yield t.Dt(l.length),n=(o=t._instance.getPersistedProperty(Ut.LogsQueue))!==null&&o!==void 0?o:[],r+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return se((function*(){var n,i=Math.max(0,t-e.ft),r=(n=e._instance.getPersistedProperty(Ut.LogsQueue))!==null&&n!==void 0?n:[];e._instance.setPersistedProperty(Ut.LogsQueue,r.slice(i)),yield e.dt()}))()}Lt(){return Hd(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var n=(e=this._instance.getPersistedProperty(Ut.LogsQueue))!==null&&e!==void 0?e:[];this.xt>n.length||(n.shift(),this.ft++,this.rt.info("Logs queue is full, dropping oldest record.")),n.push(t),this._instance.setPersistedProperty(Ut.LogsQueue,n),this.kt>n.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=il((()=>{this.Nt=void 0,this.It()}),t))}qt(){var t=Math.min(Math.max(0,this.yt-1),6);return this.St*Math.pow(2,t)}jt(){var t=this._instance.getPersistedProperty(Ut.LogsQueue);return!!t&&t.length>0}shutdown(t){var e=this;return se((function*(){e.Et();var n=e.flush().catch((()=>{}));t!==void 0?yield Sc(n,t):yield n}))()}flushWithTimeout(t){var e=this;return se((function*(){var n=e.flush();yield Sc(n,t,(()=>{n.catch((()=>{}))}))}))()}It(){this.flush().then((()=>{this.yt=0}),(t=>{this.yt++,this.rt.error("PostHog logs flush failed:",t)})).finally((()=>{!this._instance.isDisabled&&this.jt()&&this.$t(this.qt())}))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}};var ho=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function xc(t){return String(t)+"000000"}function Ic(t,e,n,i){var r="";return i&&(r=Object.keys(i).sort().map((s=>JSON.stringify(s)+":"+JSON.stringify(i[s]))).join(",")),t+"\0"+e+"\0"+(n??"")+"\0"+r}let og=class{constructor(t,e,n){this._instance=t,this.Ne=e,this.rt=n,this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Wt=0}count(t,e,n){e===void 0&&(e=1),this.Vt({name:t,type:"count",value:e,unit:n?.unit,attributes:n?.attributes})}gauge(t,e,n){this.Vt({name:t,type:"gauge",value:e,unit:n?.unit,attributes:n?.attributes})}histogram(t,e,n){this.Vt({name:t,type:"histogram",value:e,unit:n?.unit,attributes:n?.attributes})}flush(){var t=this,e=this.ct,n=(function(){var r=se((function*(){e&&(yield e.catch((()=>{}))),yield t.Zt()}));return function(){return r.apply(this,arguments)}})(),i=n().finally((()=>{this.ct===i&&(this.ct=null)}));return this.ct=i,i}drainWindow(){if(this.Bt.size===0)return null;var t=this.Bt;return this.Bt=new Map,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Gt(t)}reset(){this.Wt++,this.Et(),this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set}Vt(t){if(!this._instance.isDisabled&&!this._instance.optedOut){var e=this.Pt(t);if(e!==null)if(e.name&&typeof e.name=="string")if(typeof e.value=="number"&&Number.isFinite(e.value))if(e.type==="count"&&0>e.value)this.rt.warn("Dropping count '"+e.name+"': counters are monotonic, value must be >= 0");else{var n,i;try{n=e.attributes?I({},e.attributes):void 0,i=Ic(e.type,e.name,e.unit,n)}catch(o){return void this.rt.warn("Dropping metric '"+e.name+"': attributes could not be serialized",o)}var r=this.Bt.get(i);if(!r){if(!this.Qt())return;r={name:e.name,type:e.type,unit:e.unit,attributes:n,windowStartMs:Date.now()},this.Bt.set(i,r)}var s=this.Ut.get(e.name);s===void 0?this.Ut.set(e.name,e.type):s===e.type||this.zt.has(e.name)||(this.zt.add(e.name),this.rt.warn("Metric name '"+e.name+"' is already used as a "+s+"; recording it as a "+e.type+" too will blend both series in charts. Use a distinct name.")),this.Kt(r,e.value),this.$t()}else this.rt.warn("Dropping metric '"+e.name+"': value must be a finite number");else this.rt.warn("Dropping metric with empty name")}}Qt(){return this.Ne.maxSeriesPerFlush>this.Bt.size||(this.Ht||(this.Ht=!0,this.rt.warn("Metric series cap reached ("+this.Ne.maxSeriesPerFlush+" per flush window); dropping new series until the next flush. Reduce attribute cardinality.")),!1)}Kt(t,e){var n;switch(t.type){case"count":t.total=((n=t.total)!==null&&n!==void 0?n:0)+e;break;case"gauge":t.last=e;break;case"histogram":t.hist||(t.hist={count:0,sum:0,min:e,max:e,bucketCounts:new Array(ho.length+1).fill(0)});var i=t.hist;i.count+=1,i.sum+=e,i.min=Math.min(i.min,e),i.max=Math.max(i.max,e),i.bucketCounts[(function(r,s){for(var o=0;s.length>o;o++)if(s[o]>=r)return o;return s.length})(e,ho)]+=1}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Metric was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for metric:",o),null}return i}$t(){this.Nt||(this.Nt=il((()=>{this.Nt=void 0,this.flush().catch((t=>{this.rt.error("Metrics flush failed:",t)}))}),this.Ne.flushIntervalMs))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}Zt(){var t=this;return se((function*(){if(t.Bt.size!==0){var e=t.Bt;t.Bt=new Map,t.Ht=!1,t.Ut=new Map,t.zt=new Set;var n=t.Wt,i=yield t._instance.Jt(t.Gt(e));if(n===t.Wt)switch(i.kind){case"ok":return;case"retry-later":return t.Yt(e),void t.$t();case"too-large":return void t.rt.warn("Metrics batch exceeded the server size limit and was dropped");case"fatal":return void t.rt.error("Failed to send metrics batch:",i.error)}}}))()}Gt(t){return e=this.Xt(t),n=(function(s,o,a){return I({},s.resourceAttributes,{"service.name":s.serviceName||"unknown_service"},s.environment&&{"deployment.environment":s.environment},s.serviceVersion&&{"service.version":s.serviceVersion},{"telemetry.sdk.name":o,"telemetry.sdk.version":a})})(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion()),i=this._instance.getLibraryId(),r=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:Gr(n)},scopeMetrics:[{scope:{name:i,version:r},metrics:e}]}]};var e,n,i,r}Xt(t){var e=xc(Date.now()),n=new Map;for(var i of t.values()){var r,s=Ic(i.type,i.name,i.unit,void 0),o=n.get(s);o||(o=I({name:i.name},i.unit&&{unit:i.unit}),i.type==="count"?o.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:i.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:1,dataPoints:[]},n.set(s,o));var a=Gr((r=i.attributes)!==null&&r!==void 0?r:{}),l=xc(i.windowStartMs);if(i.type==="count"){var u,c={attributes:a,startTimeUnixNano:l,timeUnixNano:e,asDouble:(u=i.total)!==null&&u!==void 0?u:0};o.sum.dataPoints.push(c)}else if(i.type==="gauge"){var d,h={attributes:a,timeUnixNano:e,asDouble:(d=i.last)!==null&&d!==void 0?d:0};o.gauge.dataPoints.push(h)}else i.hist&&o.histogram.dataPoints.push({attributes:a,startTimeUnixNano:l,timeUnixNano:e,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:ho})}return Array.from(n.values())}Yt(t){var e,n;for(var i of t){var r=i[0],s=i[1],o=this.Bt.get(r);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,s.windowStartMs),o.type){case"count":o.total=((e=o.total)!==null&&e!==void 0?e:0)+((n=s.total)!==null&&n!==void 0?n:0);break;case"gauge":break;case"histogram":if(s.hist)if(o.hist){o.hist.count+=s.hist.count,o.hist.sum+=s.hist.sum,o.hist.min=Math.min(o.hist.min,s.hist.min),o.hist.max=Math.max(o.hist.max,s.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=s.hist.bucketCounts[a]}else o.hist=s.hist}else this.Qt()&&this.Bt.set(r,s)}}};var gr,kc,po;function ag(t){var e=globalThis._posthogChunkIds;if(e){var n=Object.keys(e);return po&&n.length===kc||(kc=n.length,po=n.reduce(((i,r)=>{gr||(gr={});var s=gr[r];if(s)i[s[0]]=s[1];else for(var o=t(r),a=o.length-1;a>=0;a--){var l=o[a],u=l?.filename,c=e[r];if(u&&c){i[u]=c,gr[r]=[u,c];break}}return i}),{})),po}}class lg{constructor(e,n,i){i===void 0&&(i=[]),this.coercers=e,this.stackParser=n,this.modifiers=i}buildFromUnknown(e,n){n===void 0&&(n={});var i=n&&n.mechanism||{handled:!0,type:"generic"},r=this.buildCoercingContext(i,n,0).apply(e),s=this.buildParsingContext(n),o=this.parseStacktrace(r,s);return{$exception_list:this.convertToExceptionList(o,i),$exception_level:"error"}}modifyFrames(e){var n=this;return se((function*(){for(var i of e)i.stacktrace&&i.stacktrace.frames&&U(i.stacktrace.frames)&&(i.stacktrace.frames=yield n.applyModifiers(i.stacktrace.frames));return e}))()}coerceFallback(e){var n;return{type:"Error",value:"Unknown error",stack:(n=e.syntheticException)==null?void 0:n.stack,synthetic:!0}}parseStacktrace(e,n){var i,r;return e.cause!=null&&(i=this.parseStacktrace(e.cause,n)),e.stack!=""&&e.stack!=null&&(r=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?n.skipFirstLines:0),n.chunkIdMap)),I({},e,{cause:i,stack:r})}applyChunkIds(e,n){return e.map((i=>(i.filename&&n&&(i.chunk_id=n[i.filename]),i)))}applyCoercers(e,n){for(var i of this.coercers)if(i.match(e))return i.coerce(e,n);return this.coerceFallback(n)}applyModifiers(e){var n=this;return se((function*(){var i=e;for(var r of n.modifiers)i=yield r(i);return i}))()}convertToExceptionList(e,n){var i,r,s,o={type:e.type,value:e.value,mechanism:{type:(i=n.type)!==null&&i!==void 0?i:"generic",handled:(r=n.handled)===null||r===void 0||r,synthetic:(s=e.synthetic)!==null&&s!==void 0&&s}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,I({},n,{handled:!0}))),a}buildParsingContext(e){var n;return{chunkIdMap:ag(this.stackParser),skipFirstLines:(n=e.skipFirstLines)!==null&&n!==void 0?n:1}}buildCoercingContext(e,n,i){i===void 0&&(i=0);var r=(s,o)=>{if(4>=o){var a=this.buildCoercingContext(e,n,o);return this.applyCoercers(s,a)}};return I({},n,{syntheticException:i==0?n.syntheticException:void 0,mechanism:e,apply:s=>r(s,i),next:s=>r(s,i+1)})}}var ni="?";function Qo(t,e,n,i,r){var s={platform:t,filename:e,function:n===""?ni:n,in_app:!0};return C(i)||(s.lineno=i),C(r)||(s.colno=r),s}var zd=(t,e)=>{var n=t.indexOf("safari-extension")!==-1,i=t.indexOf("safari-web-extension")!==-1;return n||i?[t.indexOf("@")!==-1?t.split("@")[0]:ni,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},cg=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,ug=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,dg=/\((\S*)(?::(\d+))(?::(\d+))\)/,fg=(t,e)=>{var n=cg.exec(t);if(n)return Qo(e,n[1],ni,+n[2],+n[3]);var i=ug.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var r=dg.exec(i[2]);r&&(i[2]=r[1],i[3]=r[2],i[4]=r[3])}var s=zd(i[1]||ni,i[2]);return Qo(e,s[1],s[0],i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},hg=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,pg=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,gg=(t,e)=>{var n=hg.exec(t);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){var i=pg.exec(n[3]);i&&(n[1]=n[1]||"eval",n[3]=i[1],n[4]=i[2],n[5]="")}var r=n[3],s=n[1]||ni,o=zd(s,r);return Qo(e,r=o[1],s=o[0],n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},Cc=/\(error: (.*)\)/;class mg{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,n){var i=X(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:i?e.stack:void 0,cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var n=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?n+": "+e.message:n}isDOMException(e){return Hr(e,"DOMException")}isDOMError(e){return Hr(e,"DOMError")}}class vg{match(e){return(function(n){switch({}.toString.call(n)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return _d(n,Error)}})(e)}coerce(e,n){return{type:this.getType(e),value:this.getMessage(e,n),stack:this.getStack(e),cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,n){var i=e.message;return String(i.error&&typeof i.error.message=="string"?i.error.message:i)}getStack(e){return e.stacktrace||e.stack||void 0}}class _g{constructor(){}match(e){return!!Hr(e,"ErrorEvent")&&(e.error!=null||this.fe(e))}coerce(e,n){var i;if(e.error!=null)return n.apply(e.error);var r=n.apply(e.message);return I({},r,{stack:(i=this.pe(e))!==null&&i!==void 0?i:r.stack,synthetic:!0})}fe(e){return X(e.message)&&e.message.length>0}pe(e){var n=e;if(X(n.filename)&&n.filename.length>0){var i,r,s=(i=n.lineno)!==null&&i!==void 0?i:0,o=(r=n.colno)!==null&&r!==void 0?r:0;return`Error - at `+n.filename+":"+s+":"+o}}}var yg=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class wg{match(e){return typeof e=="string"}coerce(e,n){var i,r=this.getInfos(e),s=r[0],o=r[1];return{type:s??"Error",value:o??e,stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}getInfos(e){var n="Error",i=e,r=e.match(yg);return r&&(n=r[1],i=r[2]),[n,i]}}var bg=["fatal","error","warning","log","info","debug"];function qd(t,e){e===void 0&&(e=40);var n=Object.keys(t);if(n.sort(),!n.length)return"[object has no keys]";for(var i=n.length;i>0;i--){var r=n.slice(0,i).join(", ");if(e>=r.length)return i===n.length?r:r.length>e?r.slice(0,e)+"...":r}return""}class Eg{match(e){return typeof e=="object"&&e!==null}coerce(e,n){var i,r,s=this.getErrorPropertyFromObject(e);return s?n.apply(s):{type:this.getType(e),value:this.getValue(e),stack:(i=this.getStack(e))!==null&&i!==void 0?i:(r=n.syntheticException)==null?void 0:r.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return Xa(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var n="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(n+=" with message: '"+e.message+"'"),n}if("message"in e&&typeof e.message=="string")return e.message;var i=this.getObjectClassName(e);return(i&&i!=="Object"?"'"+i+"'":"Object")+" captured as exception with keys: "+qd(e)}isSeverityLevel(e){return X(e)&&!Ko(e)&&bg.indexOf(e)>=0}getStack(e){try{return X(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:X(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(var n in e)if({}.hasOwnProperty.call(e,n)){var i=e[n];if(ng(i))return i}}getObjectClassName(e){try{var n=Object.getPrototypeOf(e);return n?n.constructor.name:void 0}catch{return}}}class Sg{match(e){return Xa(e)}coerce(e,n){var i,r=e.constructor.name;return{type:r,value:r+" captured as exception with keys: "+qd(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class xg{match(e){return vd(e)}coerce(e,n){var i;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class Ig{match(e){return Hr(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Xa(e))return!1;try{var n=e.detail;return n!=null&&typeof n=="object"&&"reason"in n}catch{return!1}}coerce(e,n){var i,r=this.getUnhandledRejectionReason(e);return vd(r)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(r),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}:n.apply(r)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}}var Kr="$message",Yr="$timestamp",kg=new Set([Kr,Yr]),go={enabled:!0,max_bytes:32768};function Jr(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:go.enabled,max_bytes:Ag(t.max_bytes,go.max_bytes)}:I({},go)}class Cg{constructor(e){this.Ke=[],this.Je=0,this.Ne=Jr(e)}setConfig(e){this.Ne=Jr(e),this.Xe()}add(e){var n=(function(r){var s;try{s=pd(r)}catch{return}try{var o=JSON.parse(s);if(!he(o))return;var a=o,l=a[Kr],u=a[Yr];return!X(l)||l.trim().length===0||!X(u)&&!ke(u)?void 0:{step:a,json:s}}catch{return}})(e);if(n){var i=(function(r){if(typeof TextEncoder<"u")return new TextEncoder().encode(r).length;for(var s=encodeURIComponent(r),o=0,a=0;s.length>a;a++)s[a]==="%"?(o+=1,a+=2):o+=1;return o})(n.json);i>this.Ne.max_bytes||(this.Ke.push({step:n.step,bytes:i}),this.Je+=i,this.Xe())}}getAttachable(){return this.Ke.map((e=>e.step))}clear(){this.Ke=[],this.Je=0}size(){return this.Ke.length}Xe(){for(;this.Je>this.Ne.max_bytes&&this.Ke.length>0;){var e=this.Ke.shift();e&&(this.Je-=e.bytes)}}}function Ag(t,e){if(!ke(t)||t===1/0||t===-1/0)return e;var n=Math.floor(t);return 0>n?e:n}var Vd=function(t,e){var n=(e===void 0?{}:e).debugEnabled,i={k(r){if(w&&(ne.DEBUG||w.POSTHOG_DEBUG||n)&&!C(w.console)&&w.console){for(var s=("__rrweb_original__"in w.console[r])?w.console[r].__rrweb_original__:w.console[r],o=arguments.length,a=new Array(o>1?o-1:0),l=1;o>l;l++)a[l-1]=arguments[l];s(t,...a)}},debug(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("debug",...s)},info(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("log",...s)},warn(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("warn",...s)},error(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("error",...s)},critical(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];console.error(t,...s)},uninitializedWarning(r){i.error("You must initialize PostHog before calling "+r)},createLogger:(r,s)=>Vd(t+" "+r,s)};return i},A=Vd("[PostHog.js]"),pe=A.createLogger,Pg=pe("[ExternalScriptsLoader]"),mo=(t,e,n)=>{if(t.config.disable_external_dependency_loading)return Pg.warn(e+" was requested but loading of external scripts is disabled."),n("Loading of external scripts is disabled");var i=P?.querySelectorAll("script");if(i){for(var r,s=function(){if(i[o].src===e){var l=i[o];return l.__posthog_loading_callback_fired?{v:n()}:(l.addEventListener("load",(u=>{l.__posthog_loading_callback_fired=!0,n(void 0,u)})),l.onerror=u=>n(u),{v:void 0})}},o=0;i.length>o;o++)if(r=s())return r.v}var a=()=>{if(!P)return n("document not found");var l=P.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=d=>{l.__posthog_loading_callback_fired=!0,n(void 0,d)},l.onerror=d=>n(d),t.config.prepare_external_dependency_script&&(l=t.config.prepare_external_dependency_script(l)),!l)return n("prepare_external_dependency_script returned null");if(t.config.external_scripts_inject_target==="head")P.head.appendChild(l);else{var u,c=P.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):P.body.appendChild(l)}};P!=null&&P.body?a():P?.addEventListener("DOMContentLoaded",a)};B.__PosthogExtensions__=B.__PosthogExtensions__||{},B.__PosthogExtensions__.loadExternalDependency=(t,e,n)=>{if(e!=="remote-config"){var i;if(t.config.strict_script_versioning)i=t.requestRouter.endpointFor("assets","/static/"+t.version+"/"+e+".js");else{var r="/static/"+e+".js?v="+t.version;if(e==="toolbar"){var s=3e5;r=r+"&t="+Math.floor(Date.now()/s)*s}i=t.requestRouter.endpointFor("assets",r)}mo(t,i,n)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");mo(t,o,n)}},B.__PosthogExtensions__.loadSiteApp=(t,e,n)=>{var i=t.requestRouter.endpointFor("api",e);mo(t,i,n)};ne.DEBUG=!1,ne.LIB_VERSION="1.415.7",ne.LIB_NAME="web";var Gd="$people_distinct_id",Yi="$device_id",vo="$device_model",Fi="__alias",Ri="__timers",ea="$autocapture_disabled_server_side",ta="$heatmaps_enabled_server_side",na="$exception_capture_enabled_server_side",ia="$error_tracking_suppression_rules",ra="$error_tracking_capture_extension_exceptions",sa="$web_vitals_enabled_server_side",rl="$dead_clicks_enabled_server_side",sl="$product_tours_enabled_server_side",oa="$web_vitals_allowed_metrics",An="$session_recording_remote_config",Kd="$replay_sample_rate",Yd="$replay_override_sampling",Jd="$replay_override_linked_flag",Zd="$replay_override_url_trigger",Xd="$replay_override_event_trigger",Kn="$sesid",ol="$session_is_sampled",Sn="$enabled_feature_flags",Ti="$active_feature_flags",Ar="$early_access_features",aa="$feature_flag_details",$i="$feature_flag_payloads",Pr="$feature_flag_request_id",Zr="$minimal_flag_called_events",It="$override_feature_flags",xn="$override_feature_flag_payloads",jt="$stored_person_properties",In="$stored_group_properties",la="$surveys",Xr="$surveys_loaded_at",ca="$surveys_activated",Fr="$surveys_activated_session",Rr="$surveys_activated_timestamps",Mi="ph_product_tours",Cn="$flag_call_reported",Li="$flag_call_reported_session_id",Tr="$feature_flag_errors",ji="$feature_flag_evaluated_at",at="$user_state",ua="$client_session_props",da="$capture_rate_limit",fa="$initial_campaign_params",ha="$initial_referrer_info",Qr="$initial_person_info",es="$epp",mr="$posthog_cookieless",Qd="$cookieless_mode",ef="$sdk_debug_extensions_init_method",tf="$sdk_debug_extensions_init_time_ms",nf="$sdk_debug_recording_script_not_loaded",al="PostHog loadExternalDependency extension not found.",kn="on_reject",Wt="always",Un="anonymous",vn="identified",pa="identified_only",ts="visibilitychange",ns="beforeunload",Vn="$pageview",_o="$pageleave",yo="$identify",Ac="$groupidentify";function vr(t,e){U(t)&&t.forEach(e)}function ie(t,e){if(!H(t))if(U(t))t.forEach(e);else if(jp(t))t.forEach(((i,r)=>e(i,r)));else for(var n in t)md.call(t,n)&&e(t[n],n)}var fe=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;e>i;i++)n[i-1]=arguments[i];for(var r of n)for(var s in r)r[s]!==void 0&&(t[s]=r[s]);return t};function $r(t){for(var e=Object.keys(t),n=e.length,i=new Array(n);n--;)i[n]=[e[n],t[e[n]]];return i}var Pc=function(t){try{return t()}catch{return}},Fg=function(t){return function(){try{for(var e=arguments.length,n=new Array(e),i=0;e>i;i++)n[i]=arguments[i];return t.apply(this,n)}catch(r){A.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),A.critical(r)}}},ll=function(t){var e={};return ie(t,(function(n,i){(X(n)&&n.length>0||ke(n))&&(e[i]=n)})),e},Rg=["herokuapp.com","vercel.app","netlify.app"];function Tg(t){var e=t?.hostname;if(!X(e))return!1;var n=e.split(".").slice(-2).join(".");for(var i of Rg)if(n===i)return!1;return!0}function ve(t,e,n,i){var r=i??{},s=r.capture,o=r.passive;t?.addEventListener(e,n,{capture:s!==void 0&&s,passive:o===void 0||o})}function ga(t){return t.name==="ph_toolbar_internal"}var rf=t=>{if(P){try{for(var e=t+"=",n=P.cookie.split(";").filter((s=>s.length)),i=0;n.length>i;i++){for(var r=n[i];r.charAt(0)==" ";)r=r.substring(1,r.length);if(r.indexOf(e)===0)return decodeURIComponent(r.substring(e.length,r.length))}}catch{}return null}};Math.trunc||(Math.trunc=function(t){return 0>t?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return ke(t)&&isFinite(t)&&Math.floor(t)===t});class is{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,n,i,r){if(!Number.isInteger(e)||!Number.isInteger(n)||!Number.isInteger(i)||!Number.isInteger(r)||0>e||0>n||0>i||0>r||e>0xffffffffffff||n>4095||i>1073741823||r>4294967295)throw new RangeError("invalid field value");var s=new Uint8Array(16);return s[0]=e/Math.pow(2,40),s[1]=e/Math.pow(2,32),s[2]=e/Math.pow(2,24),s[3]=e/Math.pow(2,16),s[4]=e/256,s[5]=e,s[6]=112|n>>>8,s[7]=n,s[8]=128|i>>>24,s[9]=i>>>16,s[10]=i>>>8,s[11]=i,s[12]=r>>>24,s[13]=r>>>16,s[14]=r>>>8,s[15]=r,new is(s)}toString(){for(var e="",n=0;this.bytes.length>n;n++)e=e+(this.bytes[n]>>>4).toString(16)+(15&this.bytes[n]).toString(16),n!==3&&n!==5&&n!==7&&n!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new is(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var n=0;16>n;n++){var i=this.bytes[n]-e.bytes[n];if(i!==0)return Math.sign(i)}return 0}}class $g{generate(){var e=this.generateOrAbort();if(!C(e))return e;this.S=0;var n=this.generateOrAbort();if(C(n))throw new Error("Could not generate UUID after timestamp reset");return n}generateOrAbort(){var e=Date.now();if(e>this.S)this.S=e,this.C();else{if(this.S>=e+1e4)return;this.I++,this.I>4398046511103&&(this.S++,this.C())}return is.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 Mg}}var Fc,sf=t=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;t.length>e;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};w&&!C(w.crypto)&&crypto.getRandomValues&&(sf=t=>crypto.getRandomValues(t));class Mg{nextUint32(){return this.R.length>this.O||(sf(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var Ht=()=>Lg().toString(),Lg=()=>(Fc||(Fc=new $g)).generate(),yi="",Ng=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,zt={N:()=>!!P,j(t){A.error("cookieStore error: "+t)},P:rf,H(t){var e;try{e=JSON.parse(zt.P(t))||{}}catch{}return e},F(t,e,n,i,r){if(!P)return!1;try{var s="",o="",a=(function(c,d){if(d){var h=(function(p,g){if(g===void 0&&(g=P),yi)return yi;if(!g||["localhost","127.0.0.1"].includes(p))return"";for(var m=p.split("."),v=Math.min(m.length,8),E="dmn_chk_"+Ht();!yi&&v--;){var S=m.slice(v).join("."),_=E+"=1;domain=."+S+";path=/";g.cookie=_+";max-age=3",g.cookie.includes(E)&&(g.cookie=_+";max-age=0",yi=S)}return yi})(c);if(!h){var f=(p=>{var g=p.match(Ng);return g?g[0]:""})(c);f!==h&&A.info("Warning: cookie subdomain discovery mismatch",f,h),h=f}return h?"; domain=."+h:""}return""})(P.location.hostname,i);if(n){var l=new Date;l.setTime(l.getTime()+864e5*n),s="; expires="+l.toUTCString()}r&&(o="; secure");var u=t+"="+encodeURIComponent(JSON.stringify(e))+s+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&A.warn("cookieStore warning: large cookie, len="+u.length),P.cookie=u,!0}catch{return!1}},q(t,e){if(P!=null&&P.cookie)try{zt.F(t,"",-1,e)}catch{return}}},wo=null,le={N(){if(!Ye(wo))return wo;var t=!0;if(C(w))t=!1;else try{var e="__mplssupport__";le.F(e,"xyz"),le.P(e)!=='"xyz"'&&(t=!1),le.q(e)}catch{t=!1}return t||A.error("localStorage unsupported; falling back to cookie store"),wo=t,t},j(t){A.error("localStorage error: "+t)},P(t){try{return w?.localStorage.getItem(t)}catch(e){le.j(e)}return null},H(t){try{return JSON.parse(le.P(t))||{}}catch{}return null},F(t,e){try{return w?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(n){le.j(n)}return!1},q(t){try{w?.localStorage.removeItem(t)}catch(e){le.j(e)}}},Og=[Yi,"distinct_id",Kn,ol,es,Qr,at],_r={},Bg={N:()=>!0,j(t){A.error("memoryStorage error: "+t)},P:t=>_r[t]||null,H:t=>_r[t]||null,F:(t,e)=>(_r[t]=e,!0),q(t){delete _r[t]}},_n=null,be={N(){if(!Ye(_n))return _n;if(_n=!0,C(w))_n=!1;else try{var t="__support__";be.F(t,"xyz"),be.P(t)!=='"xyz"'&&(_n=!1),be.q(t)}catch{_n=!1}return _n},j(t){A.error("sessionStorage error: ",t)},P(t){try{return w?.sessionStorage.getItem(t)}catch(e){be.j(e)}return null},H(t){try{return JSON.parse(be.P(t))||null}catch{}return null},F(t,e){try{return w?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(n){be.j(n)}return!1},q(t){try{w?.sessionStorage.removeItem(t)}catch(e){be.j(e)}}};class Dg{constructor(e){this._instance=e}get Ne(){return this._instance.config}get consent(){return this.ti()?0:this.ei}isOptedOut(){return this.Ne.cookieless_mode===Wt||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===kn}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===0}isRejected(){return this.consent===0||this.consent===-1&&this.Ne.opt_out_capturing_by_default}optInOut(e){this.ii.F(this.ri,e?1:0,this.Ne.cookie_expiration,this.Ne.cross_subdomain_cookie,this.Ne.secure_cookie)}reset(){this.ii.q(this.ri,this.Ne.cross_subdomain_cookie)}get ri(){var e=this._instance.config,n=e.token,i=e.opt_out_capturing_cookie_prefix;return e.consent_persistence_name||(i?i+n:"__ph_opt_in_out_"+n)}get ei(){var e=this.ii.P(this.ri);return uo(e)?1:j(zp,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,n=e==="localStorage"?le:zt;if(!this.ni||this.ni!==n){this.ni=n;var i=e==="localStorage"?zt:le;i.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(uo(i.P(this.ri))),i.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[He?.doNotTrack,He?.msDoNotTrack,B.doNotTrack].some((e=>uo(e)))}}function of(t,e){var n,i=t==null||(n=t.config)==null?void 0:n.get_current_url;if(!je(i))return e;try{var r=i(e);return X(r)&&r?r:e}catch(s){return A.error("Error in get_current_url, falling back to window.location.href",s),e}}var af="__POSTHOG_TOOLBAR__",jg=1,Ug=3,Hg=11;function Rc(t){return t instanceof Element&&(t.id===af||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function hn(t){return!!t&&t.nodeType===jg}function et(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function lf(t){return!!t&&t.nodeType===Ug}function cf(t){return!!t&&t.nodeType===Hg&&hn(t.host)}var uf=1e3;function cl(t){return t?xs(t).split(/\s+/):[]}function Tc(t,e){var n=(function(i){var r,s=w==null||(r=w.location)==null?void 0:r.href;return C(s)?void 0:of(i,s)})(e);return!!(n&&t&&t.some((i=>n.match(i))))}function rs(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 cl(e)}function df(t){return H(t)?null:xs(t).split(/(\s+)/).filter((e=>Ui(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function Ji(t){var e="";return va(t)&&!gf(t)&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;lf(n)&&n.textContent&&(e+=(i=df(n.textContent))!==null&&i!==void 0?i:"")})),xs(e)}function bo(t){var e;return C(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var ul=["a","button","form","input","select","textarea","label"];function ma(t,e){if(C(e))return!0;var n,i=function(s){if(e.some((o=>(function(a,l){var u=a.matches||a.matchesSelector||a.msMatchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.oMatchesSelector;try{return!!u&&u.call(a,l)}catch{return!1}})(s,o))))return{v:!0}};for(var r of t)if(n=i(r))return n.v;return!1}function ff(t){var e=t.parentNode;return!(!e||!hn(e))&&e}var Wg=[".ph-no-autocapture","[data-ph-no-autocapture]"],hf=["next","previous","prev",">","<"],zg=[...hf,"+","-","−","–"],$c=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,Mc=[".ph-no-rageclick",".ph-no-capture"],qg=["","text","search","email","password","url","tel","number"];function Lc(t,e){if(!w||dl(t))return!1;var n,i,r,s,o;if(mt(e)?(n=!!e&&Mc,i=void 0,r=!1):(n=(s=e?.css_selector_ignorelist)!==null&&s!==void 0?s:Mc,i=e?.content_ignorelist,r=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),n===!1||r&&(function(l){return!(!l||!hn(l))&&(!!et(l,"textarea")||(et(l,"input")?j(qg,(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=pf(t,!1).targetElementList;return!(function(l,u){if(l===!1||C(l))return!1;var c;if(l===!0)c=hf;else{if(!U(l))return!1;if(l.length>10)return A.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var h=d.safeText,f=d.ariaLabel;return c.some((p=>$c(h,p)||$c(f,p)))}))})(i,a.map((l=>{var u;return{safeText:Ji(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!ma(a,n)}var dl=t=>!t||et(t,"html")||!hn(t),pf=(t,e)=>{if(!w||dl(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,i=[t],r=t;r.parentNode&&!et(r,"body");)if(cf(r.parentNode))i.push(r.parentNode.host),r=r.parentNode.host;else{var s=ff(r);if(!s)break;if(e||ul.indexOf(s.tagName.toLowerCase())>-1)n=!0;else try{var o=w.getComputedStyle(s);o&&o.getPropertyValue("cursor")==="pointer"&&(n=!0)}catch{}i.push(s),r=s}return{parentIsUsefulElement:n,targetElementList:i}};function va(t){for(var e=new Set,n=0,i=t;i.parentNode&&!et(i,"body");i=i.parentNode){if(n++>=uf||e.has(i))return!1;e.add(i);var r=rs(i);if(j(r,"ph-sensitive")||j(r,"ph-no-capture"))return!1}if(j(rs(t),"ph-include"))return!0;var s=t.type||"";if(X(s))switch(s.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!X(o)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(o.replace(/[^a-zA-Z0-9]/g,""))}function gf(t){return!!(et(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||et(t,"select")||et(t,"textarea")||t.getAttribute("contenteditable")==="true")}var Nc=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}))$"),Oc=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,Vg=[16,15,14,13],Gg=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),Bc=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),Dc=/[0-9A-Za-z_]/;function Kg(t){for(var e=0,n=!1,i=t.length-1;i>=0;i--){var r=t.charCodeAt(i)-48;n&&(r*=2)>9&&(r-=9),e+=r,n=!n}return e%10==0}function Ui(t,e){if(e===void 0&&(e=!0),H(t))return!1;if(X(t)){t=xs(t);var n=e?Nc.test((t||"").replace(/[- ]/g,"")):(function(r){var s;for(Oc.lastIndex=0;s=Oc.exec(r);){var o=s[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of Vg){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(Nc.test(d)&&Kg(d))return!0}}}return!1})(t);if(n)return!1;var i=e?Gg.test(t):(function(r){var s;for(Bc.lastIndex=0;s=Bc.exec(r);){var o=s[1],a=s[3];if(!(o&&a&&Dc.test(o)&&Dc.test(a)))return!0}return!1})(t);if(i)return!1}return!0}function jc(t){var e=Ji(t);return Ui(e=(e+" "+mf(t)).trim())?e:""}function mf(t){var e="";return t&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;if(n&&((i=n.tagName)==null?void 0:i.toLowerCase())==="span")try{var r=Ji(n);e=(e+" "+r).trim(),n.childNodes&&n.childNodes.length&&(e=(e+" "+mf(n)).trim())}catch(s){A.error("[AutoCapture]",s)}})),e}function Uc(t){return t.replace(/"|\\"/g,'\\"')}function Yg(t){var e=t.attr__class;if(e)return U(e)?e:cl(e)}var yr=pe("[Dead Clicks]"),Jg=()=>!0,Zg=t=>{var e,n=!((e=t.instance.persistence)==null||!e.get_property(rl)),i=t.instance.config.capture_dead_clicks;return mt(i)?i:!!he(i)||n};class Hc{get lazyLoadedDeadClicksAutocapture(){return this.si}constructor(e,n,i){this.instance=e,this.isEnabled=n,this.onCapture=i,this.startIfEnabledOrStop()}onRemoteConfig(e){if(e.ok){var n=e.config;"captureDeadClicks"in n&&(this.instance.persistence&&this.instance.persistence.register({[rl]:n.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var n,i;(n=B.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture?e():(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"dead-clicks-autocapture",(r=>{r?yr.error("failed to load script",r):e()}))}oi(){var e;if(P){if(!this.si&&(e=B.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var n=he(this.instance.config.capture_dead_clicks)?I({},this.instance.config.capture_dead_clicks):{};n.__onCapture=this.onCapture,this.onCapture&&(n.capture_dead_swipes=!1),this.si=B.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.si.start(P),yr.info("starting...")}}else yr.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,yr.info("stopping..."))}}var Eo=pe("[SegmentIntegration]"),vf="posthog-js";function _f(t,e){var n=e===void 0?{}:e,i=n.organization,r=n.projectId,s=n.prefix,o=n.severityAllowList,a=o===void 0?["error"]:o,l=n.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,h,f,p,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var v,E=((d=c.exception)==null?void 0:d.values)||[],S=E.map((b=>I({},b,{stacktrace:b.stacktrace?I({},b.stacktrace,{type:"raw",frames:(b.stacktrace.frames||[]).map((k=>I({},k,{platform:"web:javascript"})))}):void 0}))),_={$exception_message:((h=E[0])==null?void 0:h.value)||c.message,$exception_type:(f=E[0])==null?void 0:f.type,$exception_level:c.level,$exception_list:S,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((p=E[0])==null?void 0:p.value)||c.message,$sentry_exception_type:(g=E[0])==null?void 0:g.type,$sentry_tags:c.tags};return i&&r&&(_.$sentry_url=(s||"https://sentry.io/organizations/")+i+"/issues/?project="+r+"&query="+c.event_id),u&&((v=t.exceptions)==null||v.sendExceptionEvent(_)),c}}class Xg{constructor(e,n,i,r,s,o){this.name=vf,this.setupOnce=function(a){a(_f(e,{organization:n,projectId:i,prefix:r,severityAllowList:s,sendExceptionsToPostHog:o==null||o}))}}}class Wc{constructor(e){this.li=(n,i,r)=>{r&&(r.noSessionId||r.activityTimeout||r.sessionPastMaximumLength||r.crossTabAdoption)&&(A.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:n,changeReason:r}),this.ui=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.hi()}hi(){var e;this.di=(e=this._instance.sessionManager)==null?void 0:e.onSessionId(this.li)}destroy(){var e;(e=this.di)==null||e.call(this),this.di=void 0}doPageView(e,n){var i,r=this.vi(e,n);return this.ui={pathname:(i=w?.location.pathname)!==null&&i!==void 0?i:"",pageViewId:n,timestamp:e},this._instance.scrollManager.resetContext(),r}doPageLeave(e){var n;return this.vi(e,(n=this.ui)==null?void 0:n.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.ui)==null?void 0:e.pageViewId}}vi(e,n){var i=this.ui;if(!i)return{$pageview_id:n};var r={$pageview_id:n,$prev_pageview_id:i.pageViewId},s=this._instance.scrollManager.getContext();if(s&&!this._instance.config.disable_scroll_properties){var o=s.maxScrollHeight,a=s.lastScrollY,l=s.maxScrollY,u=s.maxContentHeight,c=s.lastContentY,d=s.maxContentY;if(!(C(o)||C(a)||C(l)||C(u)||C(c)||C(d))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),d=Math.ceil(d);var h=o>1?At(a/o,0,1,A):1,f=o>1?At(l/o,0,1,A):1,p=u>1?At(c/u,0,1,A):1,g=u>1?At(d/u,0,1,A):1;r=fe(r,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:h,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:f,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:p,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return i.pathname&&(r.$prev_pageview_pathname=i.pathname),i.timestamp&&(r.$prev_pageview_duration=(e.getTime()-i.timestamp.getTime())/1e3),r}}var So=["flags","surveys"],Qg={[Gd]:{exposure:"hidden"},[Fi]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[Ri]:{exposure:"hidden"},[ea]:{exposure:"event"},[ta]:{exposure:"hidden"},[na]:{exposure:"event"},[ia]:{exposure:"hidden"},[ra]:{exposure:"event"},[sa]:{exposure:"event"},[rl]:{exposure:"event"},[sl]:{exposure:"hidden"},[oa]:{exposure:"event"},[An]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[Kn]:{exposure:"hidden"},[ol]:{exposure:"event"},[Kd]:{exposure:"event",shouldSkipFromEventProperties:t=>Ye(t)},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},$sess_rec_flush_size:{exposure:"hidden"},[Sn]:{exposure:"hidden",storageGroup:"flags"},[Ti]:{exposure:"hidden",storageGroup:"flags"},[Ar]:{exposure:"hidden"},[aa]:{exposure:"hidden",storageGroup:"flags"},[$i]:{exposure:"hidden",storageGroup:"flags"},[Pr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[Zr]:{exposure:"hidden",storageGroup:"flags"},[It]:{exposure:"hidden"},[xn]:{exposure:"hidden"},[jt]:{exposure:"hidden"},[In]:{exposure:"hidden"},[la]:{exposure:"hidden",storageGroup:"surveys"},[Xr]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[ca]:{exposure:"event"},[Fr]:{exposure:"hidden"},[Rr]:{exposure:"hidden"},[Mi]:{exposure:"hidden"},$product_tours_activated:{exposure:"hidden"},$product_tours_activated_session:{exposure:"hidden"},$conversations_widget_session_id:{exposure:"event"},$conversations_ticket_id:{exposure:"event"},$conversations_widget_state:{exposure:"event"},$conversations_user_traits:{exposure:"event"},[Cn]:{exposure:"hidden"},[Li]:{exposure:"hidden"},[Tr]:{exposure:"hidden"},[ji]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[at]:{exposure:"hidden"},[ua]:{exposure:"hidden"},[da]:{exposure:"hidden"},[fa]:{exposure:"hidden"},[ha]:{exposure:"hidden"},[Qr]:{exposure:"hidden"},[es]:{exposure:"hidden"},[Yd]:{exposure:"event"},[Jd]:{exposure:"event"},[Zd]:{exposure:"event"},[Xd]:{exposure:"event"},[ef]:{exposure:"event"},[tf]:{exposure:"event"},[nf]:{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"}},em=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],yn=t=>{var e=Qg[t];if(e)return e;for(var n of em){var i=n[1];if(t.indexOf(n[0])===0)return i}},Yn=(t,e)=>{try{return JSON.stringify(t,((n,i)=>typeof i=="bigint"?i.toString():i),e)}catch{return pd(t)}},ss=t=>{var e=P?.createElement("a");return C(e)?null:(e.href=t,e)},ii=function(t,e){for(var n,i=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),r=0;i.length>r;r++){var s=i[r].split("=");if(s[0]===e){n=s;break}}if(!U(n)||2>n.length)return"";var o=n[1];try{o=decodeURIComponent(o)}catch{A.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},Zi=function(t,e,n){if(!t||!e||!e.length)return t;for(var i=t.split("#"),r=i[1],s=(i[0]||"").split("?"),o=s[1],a=s[0],l=(o||"").split("&"),u=[],c=0;l.length>c;c++){var d=l[c].split("=");U(d)&&(e.includes(d[0])?u.push(d[0]+"="+n):u.push(l[c]))}var h=a;return o!=null&&(h+="?"+u.join("&")),r!=null&&(h+="#"+r),h},os=function(t,e){var n=t.match(new RegExp(e+"=([^&]*)"));return n?n[1]:null},yf=(t,e)=>t>=e&&dd(),wf=(t,e,n,i)=>{if(t===0){if(dd()){var r=e+1;return r===n&&i(),r}return e}return 0},wr="https?://(.*)",ri=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],tm=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...ri],Xi="",nm=["li_fat_id"];function bf(t,e,n){if(!P)return{};var i,r=e?[...ri,...n||[]]:[],s=Ef(Zi(P.URL,r,Xi),t),o=(i={},ie(nm,(function(a){var l=rf(a);i[a]=l||null})),i);return fe(o,s)}function Ef(t,e){var n=tm.concat(e||[]),i={};return ie(n,(function(r){var s=ii(t,r);i[r]=s||null})),i}function Sf(t){var e=(function(s){return s?s.search(wr+"google.([^/?]*)")===0?"google":s.search(wr+"bing.com")===0?"bing":s.search(wr+"yahoo.com")===0?"yahoo":s.search(wr+"duckduckgo.com")===0?"duckduckgo":null:null})(t),n=e!="yahoo"?"q":"p",i={};if(!Ye(e)){i.$search_engine=e;var r=P?ii(P.referrer,n):"";r.length&&(i.ph_keyword=r)}return i}function zc(){return navigator.language||navigator.userLanguage}var as="$direct";function xf(){return P?.referrer||as}function If(t,e,n){n===void 0&&(n=!1);var i=t?[...ri,...e||[]]:[],r=n?fn(me?.href):me?.href,s=r?.substring(0,1e3);return{r:xf().substring(0,1e3),u:s?Zi(s,i,Xi):void 0}}function kf(t,e){var n;e===void 0&&(e=!1);var i=t.r,r=t.u,s=e?fn(r):r,o={$referrer:i,$referring_domain:i==null?void 0:i==as?as:(n=ss(i))==null?void 0:n.host};if(s){o.$current_url=s;var a=ss(s);o.$host=a?.host,o.$pathname=a?.pathname;var l=Ef(s);fe(o,l)}if(i){var u=Sf(i);fe(o,u)}return o}function Cf(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function im(){try{return new Date().getTimezoneOffset()}catch{return}}var rm={flags:ji,surveys:Xr},sm=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],Hn="main";class xo{constructor(e,n,i){if(i===void 0&&(i=!0),this.ci={},this.fi=!1,this.pi=!1,this.Ne=e,this.gi=i,this.props={},this.mi=void 0,this.yi=(s=>{var o="";return s.token&&(o=s.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),s.persistence_name?"ph_"+s.persistence_name:"ph_"+o+"_posthog"})(e),this.ii=this.bi(e),this.pi=this.wi(e),this.load(),e.debug&&A.info("Persistence loaded",e.persistence,I({},this.props)),this.update_config(e,e,n),this.save(),w){var r=()=>this.flush();ve(w,"beforeunload",r,{capture:!1}),ve(w,"pagehide",r,{capture:!1})}}ki(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return ke(n)&&n>0?n:0}isDisabled(){return!!this.xi}bi(e){sm.indexOf(e.persistence.toLowerCase())===-1&&(A.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var n,i=(function(o,a){o===void 0&&(o=[]),a===void 0&&(a=!1);var l=[...Og,...o];return I({},le,{H(u){try{var c={};try{c=zt.H(u)||{}}catch{}var d,h=JSON.parse(le.P(u)||"{}");if(a){var f={};for(var p in c){var g=c[p];Ye(g)||g===""||(f[p]=g)}d=fe(h,f)}else d=fe(c,h);return le.F(u,d),d}catch{}return null},F(u,c,d,h,f,p){var g=le.F(u,c,void 0,void 0,p);try{var m={};l.forEach((v=>{c[v]&&(m[v]=c[v])})),Object.keys(m).length&&zt.F(u,m,d,h,f,p)}catch(v){le.j(v)}return g},q(u,c){try{w?.localStorage.removeItem(u),zt.q(u,c)}catch(d){le.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),r=!1,s=e.persistence.toLowerCase();return s==="localstorage"&&le.N()?(n=le,r=!0):s==="localstorage+cookie"&&i.N()?(n=i,r=!0):s==="sessionstorage"&&be.N()?n=be:s==="memory"?n=Bg:s==="cookie"?n=zt:i.N()?(n=i,r=!0):n=zt,this.fi=r,n}Si(e){return this.yi+"__"+e}wi(e){return this.fi&&!!e.split_storage}properties(){var e={};return ie(this.props,((n,i)=>{var r=yn(i);if(!r||r.exposure==="event"){if(r!=null&&r.shouldSkipFromEventProperties!=null&&r.shouldSkipFromEventProperties(n))return;e[i]=n}})),e}load(){if(!this.xi){var e=this.ii.H(this.yi);e&&(this.props=fe({},e)),this.pi&&this.Ci()}}Ci(){for(var e of So){var n=le.H(this.Si(e));if(n&&!Kt(n)){var i=this.Mi(e);i.persisted=!0,this.Ti(e)||(i.fingerprint=this.Ei(n,e)),this.Ii(e,n)||fe(this.props,n)}}}Ti(e){return Object.keys(this.props).some((n=>{var i;return((i=yn(n))==null?void 0:i.storageGroup)===e}))}Ii(e,n){var i=rm[e];if(!i)return!1;var r=n[i],s=this.props[i];return ke(r)&&ke(s)&&s>r}refreshKey(e){var n;if(!this.xi){var i=this.pi?(n=yn(e))==null?void 0:n.storageGroup:void 0,r=i?le.H(this.Si(i)):this.ii.H(this.yi);if(r&&e in r)this.Pi(e,r[e]);else{if(i){var s=this.ii.H(this.yi);if(s&&e in s)return void this.Pi(e,s[e])}this.Ri(e)}}}save(){if(!this.xi){var e=this.ki();e>0?C(this.Ai)&&(this.Ai=setTimeout((()=>{this.Ai=void 0,this.Fi()}),e)):this.Fi()}}flush(){C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0,this.Fi())}Fi(){this.xi||(this.pi?this.Li():this.Oi(this.ii,this.yi,this.props,Hn))}Li(){var e=this.Di(),n=e.main,i=e.groups;for(var r of(this.Oi(this.ii,this.yi,n,Hn),So)){var s,o=i[r];(!Kt(o)||(s=this.ci[r])!=null&&s.persisted)&&this.Oi(le,this.Si(r),o,r)}}Di(){var e={},n={flags:{},surveys:{}};return ie(this.props,((i,r)=>{var s,o=(s=yn(r))==null?void 0:s.storageGroup;o?n[o][r]=i:e[r]=i})),{main:e,groups:n}}Ei(e,n){if(n===Hn)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var i={};return ie(e,((r,s)=>{var o;i[s]=(o=yn(s))!=null&&o.volatile?"__volatile__":r})),JSON.stringify(i)}Oi(e,n,i,r){var s=this.Mi(r);if(r===Hn||s.dirty||C(s.fingerprint)){var o;try{if((o=this.Ei(i,r))===s.fingerprint)return void(s.dirty=!1)}catch{o=void 0}e.F(n,i,this.$i,this.Ni,this.qi,this.Ne.debug)?(s.dirty=!1,r!==Hn&&(s.persisted=!0),C(o)||(s.fingerprint=o)):this.Ne.debug&&A.warn('failed to persist storage entry "'+n+'"; will retry on next save')}}remove(e){var n=(e===void 0?{}:e).keepGroupEntries,i=n!==void 0&&n;if(C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0),this.ii.q(this.yi,!1),this.ii.q(this.yi,!0),!i&&this.gi)for(var r of So)le.q(this.Si(r));i?delete this.ci[Hn]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,n,i){if(he(e)){C(n)&&(n="None"),this.$i=C(i)?this.ji:i;var r=!1;if(ie(e,((s,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==n||(this.Pi(o,s),r=!0)})),r)return this.save(),!0}return!1}register(e,n){if(he(e)){this.$i=C(n)?this.ji:n;var i=!1;if(ie(e,((r,s)=>{e.hasOwnProperty(s)&&(this.props[s]!==r||he(r)||U(r))&&(this.Pi(s,r),i=!0)})),i)return this.save(),!0}return!1}unregister(e){var n=typeof e=="string"?[e]:e,i=!1;for(var r of n)r in this.props&&(this.Ri(r),i=!0);i&&this.save()}update_campaign_params(){var e=P?.URL;if(e!==this.mi){var n=bf(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);Kt(ll(n))||this.register(n),this.mi=e}}update_search_keyword(){var e;this.register((e=P?.referrer)?Sf(e):{})}update_referrer_info(){var e;this.register_once({$referrer:xf(),$referring_domain:P!=null&&P.referrer&&((e=ss(P.referrer))==null?void 0:e.host)||as},void 0)}set_initial_person_info(){this.props[fa]||this.props[ha]||this.register_once({[Qr]:If(this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties,this.Ne.disable_capture_url_hashes)},void 0)}get_initial_props(){var e={};ie([ha,fa],(r=>{var s=this.props[r];s&&ie(s,(function(o,a){e["$initial_"+Go(a)]=o}))}));var n=this.props[Qr];if(n){var i=(function(r,s){s===void 0&&(s=!1);var o=kf(r,s),a={};return ie(o,(function(l,u){a["$initial_"+Go(u)]=l})),a})(n,this.Ne.disable_capture_url_hashes);fe(e,i)}return e}safe_merge(e){return ie(this.props,(function(n,i){i in e||(e[i]=n)})),e}update_config(e,n,i){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!i),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var r=e.persistence!==n.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((h,f)=>h===d[f]))})(e.cookie_persisted_properties||[],n.cookie_persisted_properties||[]),s=r?this.bi(e):this.ii,o=this.wi(e);if(r||o!==this.pi){var a=this.props;this.clear(),this.ii=s,this.pi=o,this.props=a,this.save()}}set_disabled(e){this.xi=e,this.xi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ni&&(this.Ni=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this.qi&&(this.qi=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,n){var i=this.props[Ri]||{};i[e]=n,this.Pi(Ri,i),this.save()}remove_event_timer(e){var n=this.props[Ri]||{},i=n[e];return C(i)||(delete n[e],this.Pi(Ri,n),this.save()),i}get_property(e){return this.props[e]}set_property(e,n){this.Pi(e,n),this.save()}Pi(e,n){var i;this.props[e]=n,(i=yn(e))!=null&&i.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var n,i=(n=yn(e))==null?void 0:n.storageGroup;i&&(this.Mi(i).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function br(t){var e=!0;return{dispose(){if(e){e=!1;var n=t();n&&je(n.then)&&n.then(void 0,(()=>{}))}}}}var Ue={GZipJS:"gzip-js",Base64:"base64"},wi={Activation:"events",Cancellation:"cancelEvents"},Io={Popover:"popover",API:"api",Widget:"widget"},qt={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},ko={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},_a={Popover:"popover",Inline:"inline"},om={SHOWN:"product tour shown"},qc={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},Vc=pe("[RateLimiter]");class am{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=n=>{var i=n.text;if(i&&i.length)try{(JSON.parse(i).quota_limited||[]).forEach((r=>{Vc.info((r||"events")+" is quota limited."),this.serverLimits[r]=new Date().getTime()+6e4}))}catch(r){return void Vc.warn('could not rate limit - continuing. Error: "'+r?.message+'"',{text:i})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var n,i,r;e===void 0&&(e=!1);var s=this.captureEventsBurstLimit,o=this.captureEventsPerSecond,a=new Date().getTime(),l=(n=(i=this.instance.persistence)==null?void 0:i.get_property(da))!==null&&n!==void 0?n:{tokens:s,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>s&&(l.tokens=s);var u=1>l.tokens;if(u||e||(l.tokens=Math.max(0,l.tokens-1)),u&&!e){var c=(ke(l.dropped)?l.dropped:0)+1;l.dropped=c,!this.lastEventRateLimited&&this.Hi(c)&&(l.dropped=0)}return this.lastEventRateLimited=u,(r=this.instance.persistence)==null||r.set_property(da,l),{isRateLimited:u,remainingTokens:l.tokens}}Ui(e){var n=this.instance.config.property_denylist;return!U(n)||!n.includes(e)}zi(){var e;if(this.Ui("$current_url")&&this.Ui("$pathname")&&me!=null&&me.pathname)return""+((e=me.origin)!==null&&e!==void 0?e:"")+me.pathname}Hi(e){var n,i,r=this.captureEventsBurstLimit,s=this.captureEventsPerSecond,o=this.zi(),a=this.Ui("$session_id")?(n=(i=this.instance).get_session_id)==null?void 0:n.call(i):void 0,l=[e+" event(s) dropped since the last warning",o?"triggered on "+o:void 0,a?"session "+a:void 0].filter(Boolean).join(", ");return!!this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited: "+l+". Config is set to "+s+" events per second and "+r+" events burst limit."},{skip_client_rate_limiting:!0})}isServerRateLimited(e){var n=this.serverLimits[e||"events"]||!1;return n!==!1&&new Date().getTime()e(this.remoteConfig))):e()}Vi(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:e})}load(){try{if(this.remoteConfig)return an.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void an.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return an.info("No config found after loading remote JS config. Falling back to JSON."),void this.Vi((n=>{this.Zi(n.json,n),this.Gi()}));this.Zi(e),this.Gi()}))}catch(e){an.error("Error loading remote config",e),this.Zi()}}stop(){this.Ki&&(clearInterval(this.Ki),this.Ki=void 0)}refresh(){!this._instance.Qi()&&P&&P.visibilityState!=="hidden"&&this._instance.reloadFeatureFlags()}Gi(){var e;if(!this.Ki){var n=(e=this._instance.config.remote_config_refresh_interval_ms)!==null&&e!==void 0?e:3e5;n!==0&&(this.Ki=setInterval((()=>{this.refresh()}),n))}}Zi(e,n){!e&&n&&(n.statusCode===0?n.error||an.warn("Failed to fetch remote config from PostHog."):an.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(r){an.error("Error applying remote config",r)}if(e?.hasFeatureFlags!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var i;(i=this._instance.featureFlags)==null||i.ensureFlagsLoaded()}catch(r){an.error("Error loading feature flags",r)}}}var ct=Uint8Array,Ke=Uint16Array,si=Uint32Array,fl=new ct([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]),hl=new ct([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]),Gc=new ct([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Pf=function(t,e){for(var n=new Ke(31),i=0;31>i;++i)n[i]=e+=1<i;++i)for(var s=n[i];n[i+1]>s;++s)r[s]=s-n[i]<<5|i;return[n,r]},Ff=Pf(fl,2),ya=Ff[1];Ff[0][28]=258,ya[258]=28;for(var Kc=Pf(hl,0)[1],Rf=new Ke(32768),_e=0;32768>_e;++_e){var Wn=(43690&_e)>>>1|(21845&_e)<<1;Rf[_e]=((65280&(Wn=(61680&(Wn=(52428&Wn)>>>2|(13107&Wn)<<2))>>>4|(3855&Wn)<<4))>>>8|(255&Wn)<<8)>>>1}var Hi=function(t,e,n){for(var i=t.length,r=0,s=new Ke(e);i>r;++r)++s[t[r]-1];var o,a=new Ke(e);for(r=0;e>r;++r)a[r]=a[r-1]+s[r-1]<<1;for(o=new Ke(i),r=0;i>r;++r)o[r]=Rf[a[t[r]-1]++]>>>15-t[r];return o},$n=new ct(288);for(_e=0;144>_e;++_e)$n[_e]=8;for(_e=144;256>_e;++_e)$n[_e]=9;for(_e=256;280>_e;++_e)$n[_e]=7;for(_e=280;288>_e;++_e)$n[_e]=8;var ls=new ct(32);for(_e=0;32>_e;++_e)ls[_e]=5;var lm=Hi($n,9),cm=Hi(ls,5),Tf=function(t){return(t/8>>0)+(7&t&&1)},$f=function(t,e,n){(n==null||n>t.length)&&(n=t.length);var i=new(t instanceof Ke?Ke:t instanceof si?si:ct)(n-e);return i.set(t.subarray(e,n)),i},Ot=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8},bi=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8,t[i+2]|=n>>>16},Co=function(t,e){for(var n=[],i=0;t.length>i;++i)t[i]&&n.push({s:i,f:t[i]});var r=n.length,s=n.slice();if(!r)return[new ct(0),0];if(r==1){var o=new ct(n[0].s+1);return o[n[0].s]=1,[o,1]}n.sort((function(b,k){return b.f-k.f})),n.push({s:-1,f:25001});var a=n[0],l=n[1],u=0,c=1,d=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=r-1;)a=n[n[d].f>n[u].f?u++:d++],l=n[u!=c&&n[d].f>n[u].f?u++:d++],n[c++]={s:-1,f:a.f+l.f,l:a,r:l};var h=s[0].s;for(i=1;r>i;++i)s[i].s>h&&(h=s[i].s);var f=new Ke(h+1),p=wa(n[c-1],f,0);if(p>e){i=0;var g=0,m=p-e,v=1<i;++i){var E=s[i].s;if(e>=f[E])break;g+=v-(1<>>=m;g>0;){var S=s[i].s;e>f[S]?g-=1<=0&&g;--i){var _=s[i].s;f[_]==e&&(--f[_],++g)}p=e}return[new ct(f),p]},wa=function(t,e,n){return t.s==-1?Math.max(wa(t.l,e,n+1),wa(t.r,e,n+1)):e[t.s]=n},Yc=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new Ke(++e),i=0,r=t[0],s=1,o=function(l){n[i++]=l},a=1;e>=a;++a)if(t[a]==r&&a!=e)++s;else{if(!r&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(r),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(r);s=1,r=t[a]}return[n.subarray(0,i),e]},Ei=function(t,e){for(var n=0,i=0;e.length>i;++i)n+=t[i]*e[i];return n},ba=function(t,e,n){var i=n.length,r=Tf(e+2);t[r]=255&i,t[r+1]=i>>>8,t[r+2]=255^t[r],t[r+3]=255^t[r+1];for(var s=0;i>s;++s)t[r+s+4]=n[s];return 8*(r+4+i)},Jc=function(t,e,n,i,r,s,o,a,l,u,c){Ot(e,c++,n),++r[256];for(var d=Co(r,15),h=d[0],f=d[1],p=Co(s,15),g=p[0],m=p[1],v=Yc(h),E=v[0],S=v[1],_=Yc(g),b=_[0],k=_[1],T=new Ke(19),x=0;E.length>x;++x)T[31&E[x]]++;for(x=0;b.length>x;++x)T[31&b[x]]++;for(var F=Co(T,7),$=F[0],O=F[1],L=19;L>4&&!$[Gc[L-1]];--L);var N,K,V,M,R=u+5<<3,Z=Ei(r,$n)+Ei(s,ls)+o,Ce=Ei(r,h)+Ei(s,g)+o+14+3*L+Ei(T,$)+(2*T[16]+3*T[17]+7*T[18]);if(Z>=R&&Ce>=R)return ba(e,c,t.subarray(l,l+u));if(Ot(e,c,1+(Z>Ce)),c+=2,Z>Ce){N=Hi(h,f),K=h,V=Hi(g,m),M=g;var oe=Hi($,O);for(Ot(e,c,S-257),Ot(e,c+5,k-1),Ot(e,c+10,L-4),c+=14,x=0;L>x;++x)Ot(e,c+3*x,$[Gc[x]]);c+=3*L;for(var ye=[E,b],$e=0;2>$e;++$e){var ae=ye[$e];for(x=0;ae.length>x;++x)Ot(e,c,oe[Ie=31&ae[x]]),c+=$[Ie],Ie>15&&(Ot(e,c,ae[x]>>>5&127),c+=ae[x]>>>12)}}else N=lm,K=$n,V=cm,M=ls;for(x=0;a>x;++x)if(i[x]>255){var Ie;bi(e,c,N[257+(Ie=i[x]>>>18&31)]),c+=K[Ie+257],Ie>7&&(Ot(e,c,i[x]>>>23&31),c+=fl[Ie]);var Se=31&i[x];bi(e,c,V[Se]),c+=M[Se],Se>3&&(bi(e,c,i[x]>>>5&8191),c+=hl[Se])}else bi(e,c,N[i[x]]),c+=K[i[x]];return bi(e,c,N[256]),c+K[256]},um=new si([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),dm=(function(){for(var t=new si(256),e=0;256>e;++e){for(var n=e,i=9;--i;)n=(1&n&&3988292384)^n>>>1;t[e]=n}return t})(),Ao=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8};function fm(t,e){e===void 0&&(e={});var n=(function(){var d=4294967295;return{p(h){for(var f=d,p=0;h.length>p;++p)f=dm[255&f^h[p]]^f>>>8;d=f},d(){return 4294967295^d}}})(),i=t.length;n.p(t);var r,s,o,a,l,u=(a=10+((r=e).filename&&r.filename.length+1||0),l=8,(function(d,h,f,p,g,m){var v=d.length,E=new ct(p+v+5*(1+Math.floor(v/7e3))+g),S=E.subarray(p,E.length-g),_=0;if(!h||8>v)for(var b=0;v>=b;b+=65535){var k=b+65535;v>k?_=ba(S,_,d.subarray(b,k)):(S[b]=!0,_=ba(S,_,d.subarray(b,v)))}else{for(var T=um[h-1],x=T>>>13,F=8191&T,$=(1<b;++b){var Ie=V(b),Se=32767&b,De=L[Ie];if(O[Se]=De,L[Ie]=Se,b>=$e){var wt=v-b;if((Ce>7e3||ye>24576)&&wt>423){_=Jc(d,S,0,M,R,Z,oe,ye,ae,b-ae,_),ye=Ce=oe=0,ae=b;for(var ge=0;286>ge;++ge)R[ge]=0;for(ge=0;30>ge;++ge)Z[ge]=0}var Je=2,bt=0,mn=F,Re=Se-De&32767;if(wt>2&&Ie==V(b-Re))for(var Pe=Math.min(x,wt)-1,$t=Math.min(32767,b),Bn=Math.min(258,wt);$t>=Re&&--mn&&Se!=De;){if(d[b+Je]==d[b+Je-Re]){for(var qe=0;Bn>qe&&d[b+qe]==d[b+qe-Re];++qe);if(qe>Je){if(Je=qe,bt=Re,qe>Pe)break;var Dn=Math.min(Re,qe-2),Mt=0;for(ge=0;Dn>ge;++ge){var Lt=b-Re+ge+32768&32767,ut=Lt-O[Lt]+32768&32767;ut>Mt&&(Mt=ut,De=Lt)}}}Re+=(Se=De)-(De=O[Se])+32768&32767}if(bt){M[ye++]=268435456|ya[Je]<<18|Kc[bt];var sn=31&ya[Je],gi=31&Kc[bt];oe+=fl[sn]+hl[gi],++R[257+sn],++Z[gi],$e=b+Je,++Ce}else M[ye++]=d[b],++R[d[b]]}}_=Jc(d,S,!0,M,R,Z,oe,ye,ae,b-ae,_)}return $f(E,0,p+Tf(_)+g)})(s=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):12+o.mem,a,l)),c=u.length;return(function(d,h){var f=h.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>h.level?4:h.level==9?2:0,d[9]=3,h.mtime!=0&&Ao(d,4,Math.floor(new Date(h.mtime||Date.now())/1e3)),f){d[3]=8;for(var p=0;f.length>=p;++p)d[p+10]=f.charCodeAt(p)}})(u,e),Ao(u,c-8,n.d()),Ao(u,c-4,i),u}var hm=!!zo||!!Za,Mf="text/plain",Mr=!1,Lf=(t,e)=>{var n=t.split("#"),i=n[1],r=n[0].split("?"),s=r[0],o=r[1];if(!o)return t;var a=o.split("&").filter((l=>l.split("=")[0]!==e)).join("&");return s+(a?"?"+a:"")+(i?"#"+i:"")},ks=function(t,e,n){var i;n===void 0&&(n=!0);var r=t.split("?"),s=r[0],o=r[1],a=I({},e),l=(i=o?.split("&").map((c=>{var d,h=c.split("="),f=h[0],p=n&&(d=a[f])!==null&&d!==void 0?d:h[1];return delete a[f],f+"="+p})))!==null&&i!==void 0?i:[],u=(function(c,d){var h,f;d===void 0&&(d="&");var p=[];return ie(c,(function(g,m){C(g)||C(m)||m==="undefined"||(h=encodeURIComponent((v=>v instanceof File)(g)?g.name:g.toString()),f=encodeURIComponent(m),p[p.length]=f+"="+h)})),p.join(d)})(a);return u&&l.push(u),l.length>0?s+"?"+l.join("&"):s},Po=t=>{if(t.Ji)return t.Ji;var e=t.data,n=t.compression;if(e){if(n===Ue.GZipJS){var i=fm((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new ct(a.length+(a.length>>>1)),d=0,h=function(m){c[d++]=m},f=0;u>f;++f){if(d+5>c.length){var p=new ct(d+8+(u-f<<1));p.set(c),c=p}var g=a.charCodeAt(f);128>g?h(g):2048>g?(h(192|g>>>6),h(128|63&g)):g>55295&&57344>g?(h(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++f))>>>18),h(128|g>>>12&63),h(128|g>>>6&63),h(128|63&g)):(h(224|g>>>12),h(128|g>>>6&63),h(128|63&g))}return $f(c,0,d)})(Yn(e)),{mtime:0});return{contentType:Mf,body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),estimatedSize:i.byteLength}}if(n===Ue.Base64){var r=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(Yn(e)),s=(a=>"data="+encodeURIComponent(typeof a=="string"?a:Yn(a)))(r);return{contentType:"application/x-www-form-urlencoded",body:s,estimatedSize:new Blob([s]).size}}var o=Yn(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},Nf=t=>{var e,n,i=()=>t.transport==="sendBeacon"?{url:ks(t.url,{compression:Ue.Base64}),encodedBody:Po(I({},t,{compression:Ue.Base64,Ji:void 0}))}:{url:Lf(t.url,"compression"),encodedBody:Po(I({},t,{compression:void 0,Ji:void 0}))};try{e=Po(t)}catch(r){if(mc(t.compression,ii(t.url,"compression")))return A.error("Failed to gzip request body, sending uncompressed payload",r),i();throw r}return e&&mc(t.compression,ii(t.url,"compression"))&&!((n=e.body)instanceof ArrayBuffer?qo(new Uint8Array(n)):ArrayBuffer.isView(n)&&qo(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)))?(Mr=!0,i()):{url:t.url,encodedBody:e}},Of=t=>{try{return Nf(t)}catch(e){return A.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},pm=(function(){var t=se((function*(e){var n=Yn(e.data),i=yield(function(s,o,a){return Vo.apply(this,arguments)})(n,ne.DEBUG,{rethrow:!0});if(!i)return e;var r=yield i.arrayBuffer();return I({},e,{Ji:{contentType:Mf,body:r,estimatedSize:r.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),gm=/Failed to fetch|NetworkError|Load failed/i,Bf=t=>t?.name==="TypeError"&&gm.test(t?.message||""),Df=t=>{var e=Of(t);if(e){var n=e.url,i=e.encodedBody,r=i??{},s=r.contentType,o=r.body,a=r.estimatedSize,l=new Headers;ie(t.headers,(function(p,g){l.append(g,p)})),s&&l.append("Content-Type",s);var u=null,c=!1;if(uc){var d=new uc;u={signal:d.signal,timeout:setTimeout((()=>{var p,g;c=!0,d.abort((p=t.timeout,(g=new Error("PostHog request timed out"+(p?" after "+p+"ms":""))).name="AbortError",g))}),t.timeout)}}var h=p=>{c&&p?.name==="AbortError"||Bf(p)?A.warn(p):A.error(p),t.callback==null||t.callback({statusCode:0,error:p})};try{var f;Za(n,I({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(f=u)==null?void 0:f.signal},t.fetchOptions)).then((p=>p.text().then((g=>{var m={statusCode:p.status,text:g};if(p.status===200)try{m.json=JSON.parse(g)}catch(v){A.error(v)}t.callback==null||t.callback(m)})))).catch(h).finally((()=>u?clearTimeout(u.timeout):null))}catch(p){u&&clearTimeout(u.timeout),h(p)}}},Ea=t=>{try{var e,n=Nf(t),i=n.url,r=n.encodedBody,s=r??{},o=s.body,a=s.estimatedSize;if(!o)return;var l=o instanceof Blob?o:new Blob([o],{type:s.contentType});if(He.sendBeacon(i,l))return;var u=U(t.data)?t.data:(e=t.data)==null?void 0:e.batch;if(U(u)&&u.length>1&&(a??0)>16384){var c=Math.ceil(u.length/2),d=h=>U(t.data)?h:I({},t.data,{batch:h});return Ea(I({},t,{data:d(u.slice(0,c))})),void Ea(I({},t,{data:d(u.slice(c))}))}A.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),Df(I({},t,{Yi:!0}))}catch(h){A.warn("Beacon send failed",h)}},Zc=(t,e,n,i)=>{var r=i==="query"?e==="POST"?"sent_at":"_":void 0;return ks(n===Ue.GZipJS?Lf(t,"compression"):t,I({},r?{[r]:Date.now().toString()}:{},n===Ue.GZipJS?{}:{compression:n}))},Lr=[];Za&&Lr.push({transport:"fetch",method:Df}),zo&&Lr.push({transport:"XHR",method(t){var e=Of(t);if(e){var n=new zo,i=e.encodedBody;n.open(t.method||"GET",e.url,!0);var r=i??{},s=r.contentType,o=r.body;ie(t.headers,(function(a,l){n.setRequestHeader(l,a)})),s&&n.setRequestHeader("Content-Type",s),t.timeout&&(n.timeout=t.timeout),n.onreadystatechange=()=>{if(n.readyState===4){var a={statusCode:n.status,text:n.responseText};if(n.status===200)try{a.json=JSON.parse(n.responseText)}catch{}t.callback==null||t.callback(a)}},n.send(o)}}}),He!=null&&He.sendBeacon&&Lr.push({transport:"sendBeacon",method:Ea});var Sa=3e3;class mm{constructor(e,n){this.Xi=!0,this.tr=[],this.er=At(n?.flush_interval_ms||Sa,250,5e3,A.createLogger("flush interval"),Sa),this.ir=e}enqueue(e){this.tr.push(e),this.rr||this.nr()}unload(){this.sr();var e=this.tr.length>0?this.ar():{},n=Object.values(e);[...n.filter((i=>i.url.indexOf("/e")===0)),...n.filter((i=>i.url.indexOf("/e")!==0))].map((i=>{this.lr(I({},i,{transport:"sendBeacon"}))}))}enable(){this.Xi=!1,this.nr()}nr(){var e=this;this.Xi||(this.rr=setTimeout((()=>{if(this.sr(),this.tr.length>0){var n=this.ar(),i=function(){var s=n[r],o=new Date().getTime();s.data&&U(s.data)&&ie(s.data,(a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp})),e.lr(s)};for(var r in n)i()}}),this.er))}lr(e){try{this.ir(e)}catch(n){A.error(n)}}sr(){clearTimeout(this.rr),this.rr=void 0}ar(){var e={};return ie(this.tr,(n=>{var i,r=n,s=(r?r.batchKey:null)||r.url;C(e[s])&&(e[s]=I({},r,{data:[]})),(i=e[s].data)==null||i.push(r.data)})),this.tr=[],e}}var vm=["retriesPerformedSoFar"];class _m{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!C(w)&&"onLine"in w.navigator&&(this.dr=w.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},ve(w,"online",this.vr),ve(w,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var n=e.retriesPerformedSoFar,i=fd(e,vm);Dt(n)&&(i.url=ks(i.url,{retry_count:n})),this._instance._send_request(I({},i,{callback:r=>{if(r.statusCode!==200&&(400>r.statusCode||r.statusCode>=500)){if((r.statusCode===0?3:10)>(n??0))return void this.At(I({retriesPerformedSoFar:n},i));r.statusCode===0&&A.warn("Request failed before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped retrying after "+(n??0)+" retries.")}i.callback==null||i.callback(r)}}))}At(e){var n=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=n+1;var i=(function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),c=Math.random()-.5;return Math.ceil(u+c*(u-l))})(n),r=Date.now()+i;this.tr.push({retryAt:r,requestOptions:e});var s="Enqueued failed request for retry in "+i;navigator.onLine||(s+=" (Browser is offline)"),A.warn(s),this.ur||(this.ur=!0,this.gr())}gr(){if(this.mr&&clearTimeout(this.mr),this.tr.length===0)return this.ur=!1,void(this.mr=void 0);this.mr=setTimeout((()=>{this.dr&&this.tr.length>0&&this.cr(),this.gr()}),this.hr)}cr(){var e=Date.now(),n=[],i=this.tr.filter((s=>e>s.retryAt||(n.push(s),!1)));if(this.tr=n,i.length>0)for(var r of i)this.retriableRequest(r.requestOptions)}unload(){for(var e of(this.mr&&(clearTimeout(this.mr),this.mr=void 0),this.ur=!1,C(w)||(this.vr&&(w.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(w.removeEventListener("offline",this.pr),this.pr=void 0)),this.tr)){var n=e.requestOptions;try{this._instance._send_request(I({},n,{transport:"sendBeacon"}))}catch(i){A.error(i)}}this.tr=[]}}class ym{constructor(e){this.yr=()=>{var n,i,r,s;this.br||(this.br={});var o=this.scrollElement(),a=this.scrollY(),l=o?Math.max(0,o.scrollHeight-o.clientHeight):0,u=a+(o?.clientHeight||0),c=o?.scrollHeight||0;this.br.lastScrollY=Math.ceil(a),this.br.maxScrollY=Math.max(a,(n=this.br.maxScrollY)!==null&&n!==void 0?n:0),this.br.maxScrollHeight=Math.max(l,(i=this.br.maxScrollHeight)!==null&&i!==void 0?i:0),this.br.lastContentY=u,this.br.maxContentY=Math.max(u,(r=this.br.maxContentY)!==null&&r!==void 0?r:0),this.br.maxContentHeight=Math.max(c,(s=this.br.maxContentHeight)!==null&&s!==void 0?s:0)},this._instance=e}get _r(){return this._instance.config.scroll_root_selector}getContext(){return this.br}resetContext(){var e=this.br;return setTimeout(this.yr,0),e}startMeasuringScrollPosition(){ve(w,"scroll",this.yr,{capture:!0}),ve(w,"scrollend",this.yr,{capture:!0}),ve(w,"resize",this.yr)}scrollElement(){if(!this._r)return w?.document.documentElement;var e=U(this._r)?this._r:[this._r];for(var n of e){var i=w?.document.querySelector(n);if(i)return i}}wr(e){var n=e==="y"?"scrollTop":"scrollLeft";if(this._r){var i=this.scrollElement();return i&&i[n]||0}return w?e==="y"?w.scrollY||w.pageYOffset||w.document.documentElement.scrollTop||0:w.scrollX||w.pageXOffset||w.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var wm=t=>If(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class Xc{constructor(e,n,i,r){this.kr=s=>{var o=this.Sr();if(!o||o.sessionId!==s){var a={sessionId:s,props:this.Cr(this._instance)};this.Mr.register({[ua]:a})}},this._instance=e,this.Tr=n,this.Mr=i,this.Cr=r||wm,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[ua]}getSetOnceProps(){var e,n=(e=this.Sr())==null?void 0:e.props;return n?"r"in n?kf(n,this._instance.config.disable_capture_url_hashes):{$referring_domain:n.referringDomain,$pathname:n.initialPathName,utm_source:n.utm_source,utm_campaign:n.utm_campaign,utm_medium:n.utm_medium,utm_content:n.utm_content,utm_term:n.utm_term}:{}}getSessionProps(){var e={};return ie(ll(this.getSetOnceProps()),((n,i)=>{i==="$current_url"&&(i="url"),e["$session_entry_"+Go(i)]=n})),e}}class pl{on(e,n){return this.Er[e]||(this.Er[e]=[]),this.Er[e].push(n),()=>{this.Er[e]=this.Er[e].filter((i=>i!==n))}}emit(e,n){for(var i of this.Er[e]||[])i(n);for(var r of this.Er["*"]||[])r(e,n)}constructor(){this.Er={}}}var Si=pe("[SessionId]");class Qc{on(e,n){return this.Ir.on(e,n)}constructor(e,n,i){var r;if(this.Pr=null,this.Rr=[],this.Ar=void 0,this.Fr=!1,this.Ir=new pl,this.Lr=(u,c)=>!(!Dt(u)||!Dt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===Wt)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Ne=e.config,this.Mr=e.persistence,this.Or=void 0,this.Dr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.$r=n||Ht,this.Nr=i||Ht;var s=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*At(this.Ne.session_idle_timeout_seconds||1800,60,36e3,Si.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.qr(),this.jr="ph_"+s+"_window_id",this.Br="ph_"+s+"_primary_window_exists",this.Hr()){var o=be.H(this.jr),a=be.H(this.Br);o&&!a?this.Or=o:be.q(this.jr),be.F(this.Br,!0)}if((r=this.Ne.bootstrap)!=null&&r.sessionID)try{var l=(u=>{var c=this.Ne.bootstrap.sessionID.replace(/-/g,"");if(c.length!==32)throw new Error("Not a valid UUID");if(c[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(c.substring(0,12),16)})();this.Ur(this.Ne.bootstrap.sessionID,new Date().getTime(),l)}catch(u){Si.error("Invalid sessionID in bootstrap",u)}this.zr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return C(this.Rr)&&(this.Rr=[]),this.Rr.push(e),this.Dr&&e(this.Dr,this.Or),()=>{this.Rr=this.Rr.filter((n=>n!==e))}}Hr(){return this.Ne.persistence!=="memory"&&!this.Mr.xi&&be.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&be.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?be.H(this.jr):null}Zr(e){var n=this.Pr;return!Ye(n)&&!Ye(e)&&5e3>Math.abs(e-n)}Ur(e,n,i){var r=n!==this._sessionActivityTimestamp,s=!(e!==this.Dr||i!==this._sessionStartTimestamp);this._sessionStartTimestamp=i,this._sessionActivityTimestamp=n,this.Dr=e,s&&!r||s&&this.Zr(n)||(this.Pr=n,this.Mr.register({[Kn]:[n,e,i]}))}Gr(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return Dt(n)&&n>0}Qr(){this.Gr()?this.Mr.refreshKey(Kn):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!Ye(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this.Pr){this.Qr();var n=this.Jr();n[1]===this.Dr&&n[2]===this._sessionStartTimestamp&&(this.Pr=this._sessionActivityTimestamp,this.Mr.register({[Kn]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],n=Dt(e)?e:0,i=Dt(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(n,i)}Xr(e){return this.Qr(),this.Lr(e,this.Yr())}Jr(){var e=this.Mr.props[Kn];return U(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Pr=null,clearTimeout(this.tn),this.tn=void 0,this.Ur(null,null,null)}destroy(){this.Fr=!0,this.Kr(),clearTimeout(this.tn),this.tn=void 0,this.Ar&&w&&(w.removeEventListener(ns,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&be.q(this.Br)},ve(w,ns,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=null),this.Ne.cookieless_mode===Wt)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var i=n||new Date().getTime(),r=this.Jr(),s=r[1],o=r[2],a=this.Yr(),l=this.Vr(),u=Dt(o)&&Math.abs(i-o)>864e5,c=!1,d=!1,h=!s,f=s,p=!h&&!e&&this.Lr(i,a);if(p){(p=this.Xr(i))||Si.info("cross-tab refresh kept the session alive",{sessionId:s});var g=this.Jr();s=g[1],o=g[2]}h||p||u?(s=this.$r(),l=this.Nr(),Si.info("new session ID generated",{sessionId:s,windowId:l,changeReason:{noSessionId:h,activityTimeout:p,sessionPastMaximumLength:u}}),o=i,c=!0):(l||(l=this.Nr(),c=!0),(d=s!==f)&&(Si.info("adopted cross-tab session id",{sessionId:s,windowId:l}),c=!0));var m=Dt(a)&&e&&!u?a:i,v=Dt(o)?o:new Date().getTime();this.Wr(l),this.Ur(s,m,v),e||this.qr();var E={noSessionId:h,activityTimeout:p,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((S=>S(s,l,E))),{sessionId:s,windowId:l,sessionStartTimestamp:v,changeReason:c?E:void 0,lastActivityTimestamp:a}}qr(){this.Fr||(clearTimeout(this.tn),this.tn=setTimeout((()=>{if(!this.Fr)if(this.Xr(new Date().getTime())){var e=this.Dr;this.resetSessionId(),this.Ir.emit("forcedIdleReset",{idleSessionId:e})}else this.qr()}),1.1*this.sessionTimeoutMs))}}var jf=function(t,e){if(!t)return!1;var n=t.userAgent;if(n&&_c(n,e))return!0;try{var i=t?.userAgentData;if(i!=null&&i.brands&&i.brands.some((r=>_c(r?.brand,e))))return!0}catch{}return!!t.webdriver};function Uf(){return(Uf=se((function*(){var t=He?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),n=e?.model;return X(n)&&n.length>0?n:void 0}catch(i){return void A.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",i)}}))).apply(this,arguments)}var cs=function(t,e){if(!(function(n){try{new RegExp(n)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function Fo(t,e,n){return Yn({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}var Hf={exact:(t,e)=>e.some((n=>t.some((i=>n===i)))),is_not:(t,e)=>e.every((n=>t.every((i=>n!==i)))),regex:(t,e)=>e.some((n=>t.some((i=>cs(n,i))))),not_regex:(t,e)=>e.every((n=>t.every((i=>!cs(n,i))))),icontains:(t,e)=>e.map(Er).some((n=>t.map(Er).some((i=>n.includes(i))))),not_icontains:(t,e)=>e.map(Er).every((n=>t.map(Er).every((i=>!n.includes(i))))),gt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>i>parseFloat(r)))})),lt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>it.toLowerCase();function Wf(t,e){return!t||Object.entries(t).every((n=>{var i=n[1],r=e?.[n[0]];if(C(r)||Ye(r))return!1;var s=[String(r)],o=Hf[i.operator];return!!o&&o(i.values,s)}))}var xa="custom",eu="i.posthog.com",bm=/^\/static\//;class Em{constructor(e){this.en={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,n=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return n||(n=this.apiHost.replace("."+eu,".posthog.com")),n==="https://app.posthog.com"?"https://us.posthog.com":n}get region(){return this.en[this.apiHost]||(this.en[this.apiHost]=/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"us":/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"eu":xa),this.en[this.apiHost]}rn(e){if(bm.test(e)){var n=this.instance.config.asset_host;if(typeof n=="string")return n.trim().replace(/\/$/,"")||void 0}}endpointFor(e,n){if(n===void 0&&(n=""),n&&(n=n[0]==="/"?n:"/"+n),e==="ui")return this.uiHost+n;if(e==="flags")return this.flagsApiHost+n;if(e==="assets"){var i=this.rn(n);if(i)return""+i+n}if(this.region===xa)return this.apiHost+n;var r=eu+n;switch(e){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}}function zf(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var Q=pe("[Surveys]"),qf="seenSurvey_",Vf=t=>{try{var e=(n=>((i,r)=>""+qf+(function(s){return s.current_iteration&&s.current_iteration>0?s.id+"_"+s.current_iteration:s.id})(r))(0,n))(t);if(localStorage.getItem(e))return;localStorage.setItem(e,"true")}catch(n){Q.error("Failed to persist survey seen state",n)}},Sm=[Io.Popover,Io.Widget,Io.API],xm={ignoreConditions:!1,ignoreDelay:!1,displayType:_a.Popover},Im=pe("[PostHog ExternalIntegrations]"),km={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class Cm{constructor(e){this._instance=e}ai(e,n){var i;(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,e,(r=>{if(r)return Im.error("failed to load script",r);n()}))}startIfEnabledOrStop(){var e=this,n=function(){var s,o,a,l=i[0],u=i[1];!u||(s=B.__PosthogExtensions__)!=null&&(s=s.integrations)!=null&&s[l]||e.ai(km[l],(()=>{var c;(c=B.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=B.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=B.__PosthogExtensions__)==null||(a=a.integrations)==null||(a=a[l])==null||a.stop())};for(var i of Object.entries((r=this._instance.config.integrations)!==null&&r!==void 0?r:{})){var r;n()}}}class Am{constructor(e,n){this.rt=e,this.nn=n,this.sn=new Map,this.an=!1}add(e){var n=this;return se((function*(){if(n.an)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(n.sn.has(e.name))throw new Error('Browser extension "'+e.name+'" is already registered');n.sn.set(e.name,e);try{var i=e.setup(n.nn);i&&(yield i)}catch(s){var r=n.sn.get(e.name)===e;r&&n.sn.delete(e.name),n.rt.error('Failed to set up browser extension "'+e.name+'"',s),r&&n.ln(e)}}))()}dispose(){if(!this.an){this.an=!0;var e=Array.from(this.sn.values()).reverse();for(var n of(this.sn.clear(),e))this.ln(n)}}ln(e){try{var n=e.dispose==null?void 0:e.dispose();n&&je(n.then)&&n.then(void 0,(i=>{this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}))}catch(i){this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}}}class Pm{constructor(e){this._instance=e}initialize(){}get(e){var n=this._instance.persistence;if(typeof e=="string")return n?.get_property(e);var i={};for(var r of e){var s=n?.get_property(r);C(s)||(i[r]=s)}return i}set(e,n){var i;(i=this._instance.persistence)==null||i.register(typeof e=="string"?{[e]:n}:e)}remove(e){var n;(n=this._instance.persistence)==null||n.unregister(e)}}var tu="extensionsRemoteConfig";class Fm{constructor(e){this.an=!1,this.instance=e,this.rt=A,this.un=e.hn,this.kv=new Pm(e),this.onEvent=n=>br(this.instance.on("eventCaptured",(i=>{try{n({event:i.event,properties:i.properties})}catch(r){this.rt.error("Browser extension event listener failed",r)}}))),this.onRemoteConfig=n=>{if(this.an)return br((()=>{}));var i=s=>{try{n(s)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},r=this.instance.dn.on(tu,i);return this.un&&i(this.un),br(r)},this.vn=new Am(A.createLogger("[BrowserExtensions]"),this)}get logger(){return this.rt}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return(e=this.instance.get_property(Yi))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(Yi);return typeof e=="string"?e:void 0}get library(){return{name:ne.LIB_NAME,version:ne.LIB_VERSION}}get initialPersonProperties(){var e,n;return(e=(n=this.instance.persistence)==null?void 0:n.get_initial_props())!==null&&e!==void 0?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,n,i,r,s=(e=this.instance.sessionManager)==null?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:(n=s?.sessionId)!==null&&n!==void 0?n:"",windowId:(i=s?.windowId)!==null&&i!==void 0?i:"",sessionStartTimestamp:(r=s?.sessionStartTimestamp)!==null&&r!==void 0?r:0}}catch{return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get projectToken(){return this.instance.config.token}add(e){return this.vn.add(e)}capture(e,n,i){var r=this;return se((function*(){i?r.instance.capture(e,n,{timestamp:i.timestamp,uuid:i.uuid,$set:i.set,$set_once:i.setOnce}):r.instance.capture(e,n)}))()}registerDynamicEventProperties(e){return br(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(tu,e))}sendRequest(e,n){var i=this;return se((function*(){var r;n===void 0&&(n={});var s=i.instance.requestRouter.endpointFor((r=n.target)!==null&&r!==void 0?r:"api",e),o={method:n.method,url:n.query?ks(s,n.query):s,data:n.body,headers:n.headers,timeout:n.timeoutMs,fireCallbackOnDrop:!0,transport:n.transport,compression:n.compression,timestampMode:n.sentAt};return n.transport==="sendBeacon"?(i.instance._send_request(o),{statusCode:202}):new Promise((a=>{o.callback=a,i.instance._send_request(o)}))}))()}dispose(){this.an||(this.an=!0,this.vn.dispose())}}var Wi={},Ro=0,us=()=>{},nu='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',xi="Surveys module not available",iu="sanitize_properties is deprecated. Use before_send instead",Gf="Invalid value for property_denylist config: ",Rm=["token","distinct_id",Qd],Gn="posthog",Kf=!hm&&Ge?.indexOf("MSIE")===-1&&Ge?.indexOf("Mozilla")===-1,To=t=>{var e;return I({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:Tg(P?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:us,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:t??"unset",__preview_deferred_init_extensions:!1,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:me&&X(me?.search)&&me.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disableDeviceModel:!1,disable_external_dependency_loading:!1,strict_script_versioning:!1,enable_recording_console_log:void 0,secure_cookie:(w==null||(e=w.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(n){A.error("Bad HTTP status: "+n.statusCode+" "+n.text)},get_device_id:n=>n,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:pa,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:Sa},error_tracking:{},_onCapture:us},(n=>({rageclick:n&&n>="2026-05-30"?{content_ignorelist:zg,ignore_text_selection:!0}:!n||"2025-11-30">n||{content_ignorelist:!0},capture_pageview:!n||"2025-05-24">n||"history_change",session_recording:n&&n>="2026-06-25"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6},streamNetworkBody:!0}:n&&n>="2026-05-30"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6}}:n&&n>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:n&&n>="2026-01-30"?"head":"body",internal_or_test_user_hostname:n&&n>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:n&&n>="2026-05-30"?250:0,split_storage:!(!n||"2026-05-30">n),detect_google_search_app:!(!n||"2026-05-30">n),disable_capture_url_hashes:!(!n||"2026-06-25">n)}))(t))},Tm=[["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"]],ru=t=>{var e={};for(var n of Tm){var i=n[0],r=n[1];C(t[i])||(e[r]=t[i])}var s=fe({},e,t),o=t.__preview_external_dependency_versioned_paths;return C(o)||(C(t.strict_script_versioning)&&(s.strict_script_versioning=!!o),X(o)&&C(t.asset_host)&&(s.asset_host=o)),U(t.property_blacklist)&&(C(t.property_denylist)?s.property_denylist=t.property_blacklist:U(t.property_denylist)?s.property_denylist=[...t.property_blacklist,...t.property_denylist]:A.error(Gf+t.property_denylist)),s};class $m{constructor(){this.__forceAllowLocalhost=!1}get fn(){return this.__forceAllowLocalhost}set fn(e){A.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class Ze{pn(e,n){if(e){var i=this.sn.indexOf(e);i!==-1&&this.sn.splice(i,1)}return this.sn.push(n),n.initialize==null||n.initialize(),n}gn(){return this.config.cookieless_mode===Wt||this.config.cookieless_mode===kn&&this.consent.isRejected()}get decideEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){var e;this.webPerformance=new $m,this.mn=!1,this.version=ne.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new pl,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=To(),this.SentryIntegration=Xg,this.sentryIntegration=i=>(function(r,s){var o=_f(r,s);return{name:vf,processEvent:a=>o(a)}})(this,i),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.wn=!1,this.kn=null,this.xn=null,this.Sn=null,this.scrollManager=new ym(this),this.pageViewManager=new Wc(this),this.rateLimiter=new am(this),this.requestRouter=new Em(this),this.consent=new Dg(this),this.externalIntegrations=new Cm(this);var n=(e=Ze.__defaultExtensionClasses)!==null&&e!==void 0?e:{};this.featureFlags=n.featureFlags&&new n.featureFlags(this),this.toolbar=n.toolbar&&new n.toolbar(this),this.surveys=n.surveys&&new n.surveys(this),this.conversations=n.conversations&&new n.conversations(this),this.logs=n.logs&&new n.logs(this),this.metrics=n.metrics&&new n.metrics(this),this.experiments=n.experiments&&new n.experiments(this),this.exceptions=n.exceptions&&new n.exceptions(this),this.people={set:(i,r,s)=>{var o=X(i)?{[i]:r}:i;this.setPersonProperties(o),s?.({})},set_once:(i,r,s)=>{var o=X(i)?{[i]:r}:i;this.setPersonProperties(void 0,o),s?.({})}},this.on("eventCaptured",(i=>A.info('send "'+i?.event+'"',i)))}init(e,n,i){if(i&&i!==Gn){var r,s=(r=Wi[i])!==null&&r!==void 0?r:new Ze;return s._init(e,n,i),Wi[i]=s,Wi[Gn][i]=s,s}return this._init(e,n,i)}_init(e,n,i){var r,s;n===void 0&&(n={});var o,a=X(e)?e.trim():"";if(!a)return A.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return a!==((o=this.config)==null?void 0:o.token)?console.warn("[PostHog.js]","You have already initialized PostHog with a different project token! Re-initializing is a no-op, so events will keep going to the project this instance was initialized with. To capture into a second project, load PostHog once, then initialize a named instance after the SDK has loaded, e.g. posthog.init('"+a+"', { ... }, 'project2')"):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=To(n.defaults),n.debug=this.Cn(n.debug),this.Mn=n,this.Tn=[],n.person_profiles?this.xn=n.person_profiles:n.process_person&&(this.xn=n.process_person);var l=To(n.defaults),u=ru(n),c=fe({},l,u,{name:i,token:a});he(l.rageclick)&&he(u.rageclick)&&(c.rageclick=fe({},l.rageclick,u.rageclick)),he(l.session_recording)&&he(u.session_recording)&&(c.session_recording=fe({},l.session_recording,u.session_recording)),this.set_config(c),this.config.on_xhr_error&&A.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=n.disable_compression?void 0:Ue.GZipJS;var d=this.En();if(this.persistence=new xo(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new xo(I({},this.config,{persistence:"sessionStorage"}),d,!1),this.bn="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&be.N()){var h=be.H(this.bn);U(h)&&h.forEach((k=>{X(k)&&this.yn.add(k)}))}else be.q(this.bn);var f=I({},this.persistence.props),p=I({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new mm((k=>this.Pn(k)),this.config.request_queue_config),this.Rn=new _m(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new Qc(this),this.sessionPropsManager=new Xc(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((k,T,x)=>{(x!=null&&x.activityTimeout||x!=null&&x.sessionPastMaximumLength||x!=null&&x.crossTabAdoption)&&this.An()}))),this.Fn(),this.config.__preview_deferred_init_extensions?(A.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Ln(g)}),0)):(A.info("Initializing extensions synchronously"),this.Ln(g)),ne.DEBUG=ne.DEBUG||this.config.debug,ne.DEBUG&&A.info("Starting in debug mode",{this:this,config:n,thisC:I({},this.config),p:f,s:p}),!this.config.identity_distinct_id||(r=n.bootstrap)!=null&&r.distinctID||(n.bootstrap=I({},n.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((s=n.bootstrap)==null?void 0:s.distinctID)!==void 0){var m=n.bootstrap.distinctID,v=this.get_distinct_id(),E=this.persistence.get_property(at);if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&E===Un)this.identify(m);else if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&E===vn)A.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{var S=this.config.get_device_id(Ht()),_=n.bootstrap.isIdentifiedID?S:m;this.persistence.set_property(at,n.bootstrap.isIdentifiedID?vn:Un),this.register({distinct_id:m,$device_id:_})}}if(g)this.register_once({distinct_id:mr,$device_id:null},"");else if(!this.get_distinct_id()){var b=this.config.get_device_id(Ht());this.register_once({distinct_id:b,$device_id:b},""),this.persistence.set_property(at,Un)}return ve(w,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),n.segment?(function(k,T){var x=k.config.segment;if(!x)return T();(function(F,$){var O=F.config.segment;if(!O)return $();var L=K=>{var V=()=>K.anonymousId()||Ht();F.config.get_device_id=V,K.id()&&(F.register({distinct_id:K.id(),$device_id:V()}),F.persistence.set_property(at,vn)),$()},N=O.user();"then"in N&&je(N.then)?N.then(L):L(N)})(k,(()=>{x.register((F=>{typeof Promise<"u"&&Promise.resolve||Eo.warn("This browser does not have Promise support, and can not use the segment integration");var $=(O,L)=>{if(!L)return O;O.event.userId||O.event.anonymousId===F.get_distinct_id()||(Eo.info("No userId set, resetting PostHog"),F.reset()),O.event.userId&&O.event.userId!==F.get_distinct_id()&&(Eo.info("UserId set, identifying with PostHog"),F.identify(O.event.userId));var N=F.calculateEventProperties(L,O.event.properties);return O.event.properties=Object.assign({},N,O.event.properties),O};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:O=>$(O,O.event.event),page:O=>$(O,Vn),identify:O=>$(O,yo),screen:O=>$(O,"$screen")}})(k)).then((()=>{T()}))}))})(this,(()=>this.On())):this.On(),je(this.config._onCapture)&&this.config._onCapture!==us&&(A.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(k=>this.config._onCapture(k.event,k)))),this.config.ip&&A.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this.config.disableDeviceModel||(function(){return Uf.apply(this,arguments)})().then((k=>{k&&this.register({[vo]:k})})).catch(us),this}Fn(){var e,n,i,r,s,o,a=(e=(n=this.config.__extensionClasses)==null?void 0:n.featureFlags)!==null&&e!==void 0?e:(i=Ze.__defaultExtensionClasses)==null?void 0:i.featureFlags;a&&(this.featureFlags&&this.featureFlags instanceof a||((r=this.Dn)==null||r.call(this),this.Dn=void 0,this.featureFlags=new a(this)),je(this.featureFlags.onReloading)&&je(this.featureFlags.setup)?this.Dn||(this.Dn=this.featureFlags.onReloading((()=>{this.dn.emit("featureFlagsReloading",!0)})),this.$n().add(this.featureFlags)):(s=(o=this.featureFlags).initialize)==null||s.call(o))}Ln(e){var n,i,r,s,o,a,l,u=performance.now(),c=I({},Ze.__defaultExtensionClasses,this.config.__extensionClasses),d=[];c.exceptions&&this.sn.push(this.exceptions=(n=this.exceptions)!==null&&n!==void 0?n:new c.exceptions(this)),c.historyAutocapture&&this.sn.push(this.historyAutocapture=new c.historyAutocapture(this)),c.tracingHeaders&&this.sn.push(this.tracingHeaders=new c.tracingHeaders(this)),c.siteApps&&this.sn.push(this.siteApps=new c.siteApps(this)),c.sessionRecording&&!e&&this.sn.push(this.sessionRecording=new c.sessionRecording(this)),this.config.disable_scroll_properties||d.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),c.autocapture&&this.sn.push(this.autocapture=new c.autocapture(this)),c.surveys&&this.sn.push(this.surveys=(i=this.surveys)!==null&&i!==void 0?i:new c.surveys(this)),c.logs&&this.sn.push(this.logs=(r=this.logs)!==null&&r!==void 0?r:new c.logs(this)),c.metrics&&this.sn.push(this.metrics=(s=this.metrics)!==null&&s!==void 0?s:new c.metrics(this)),c.conversations&&this.sn.push(this.conversations=(o=this.conversations)!==null&&o!==void 0?o:new c.conversations(this)),c.productTours&&this.sn.push(this.productTours=new c.productTours(this)),c.heatmaps&&this.sn.push(this.heatmaps=new c.heatmaps(this)),c.webVitalsAutocapture&&this.sn.push(this.webVitalsAutocapture=new c.webVitalsAutocapture(this)),c.exceptionObserver&&this.sn.push(this.exceptionObserver=new c.exceptionObserver(this)),c.deadClicksAutocapture&&this.sn.push(this.deadClicksAutocapture=new c.deadClicksAutocapture(this,Zg)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((h=>{h.initialize&&d.push((()=>{h.initialize==null||h.initialize()}))})),d.push((()=>{if(this.Nn){var h=this.Nn;this.Nn=void 0,this.sn.forEach((f=>f.onRemoteConfig==null?void 0:f.onRemoteConfig(h)))}})),this.qn(d,u)}qn(e,n){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,n)}),0);var i=e.shift();if(i)try{i()}catch(s){A.error("Error initializing extension:",s)}}var r=Math.round(performance.now()-n);this.register_for_session({[ef]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[tf]:r}),this.config.__preview_deferred_init_extensions&&A.info("PostHog extensions initialized ("+r+"ms)")}Zi(e){var n;if(!P||!P.body)return A.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.Zi(e)}),500);if(this.config.__preview_deferred_init_extensions&&(this.Nn=e),this.hn=e,this.compression=void 0,e.ok){var i,r=e.config;r.supportedCompression&&!this.config.disable_compression&&(this.compression=j(r.supportedCompression,Ue.GZipJS)?Ue.GZipJS:j(r.supportedCompression,Ue.Base64)?Ue.Base64:void 0),(i=r.analytics)!=null&&i.endpoint&&(this.analyticsDefaultEndpoint=r.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:pa}),(n=this.jn)==null||n.handleRemoteConfig(e),this.sn.forEach((s=>s.onRemoteConfig==null?void 0:s.onRemoteConfig(e)))}On(){try{this.config.loaded(this)}catch(i){A.critical("`loaded` function failed",i)}if(this.Bn(),this.config.internal_or_test_user_hostname&&me!=null&&me.hostname){var e=me.hostname,n=this.config.internal_or_test_user_hostname;(typeof n=="string"?e===n:n.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.gn())&&this.Hn()}),1),this.Un=new Af(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()&&vr(this.__request_queue,(e=>this.Pn(e))),this.__request_queue=[],this.Bn()}_handle_unload(){var e,n,i,r,s;(e=this.surveys)==null||e.handlePageUnload==null||e.handlePageUnload(),(n=this.metrics)==null||n.flush("sendBeacon"),this.config.request_batching?(this.zn()&&this.capture(_o),(i=this.logs)==null||i.flushLogs("sendBeacon"),(r=this.In)==null||r.unload(),(s=this.Rn)==null||s.unload()):this.zn()&&this.capture(_o,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?Kf?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)?e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:429})):(e.transport=e.transport||this.config.api_transport,e.headers=I({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,(C(this.config.disable_beacon)?this.config.__preview_disable_beacon:this.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(n=>{var i,r,s,o=I({},n);o.timeout=o.timeout||6e4;var a,l,u,c,d,h=(i=o.transport)!==null&&i!==void 0?i:"fetch";h==="sendBeacon"&&C(o.compression)&&o.data&&(o.compression=Ue.Base64),o.method==="POST"&&o.data&&(o.timestampMode==="capture-body"?o.data={api_key:(l=(d=(c=U(a=o.data)?a:[a])[0])==null||(u=d.properties)==null?void 0:u.token)!==null&&l!==void 0?l:d?.token,batch:c,sent_at:new Date().toISOString()}:o.timestampMode==="body"&&(o.data=(function(m,v){return v===void 0&&(v=new Date().toISOString()),U(m)?m.map((E=>I({},E,{sent_at:v}))):I({},m,{sent_at:v})})(o.data))),o.url=Zc(o.url,o.method,o.compression,o.timestampMode);var f=Lr.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),p=(r=(s=(function(m,v){for(var E=0;m.length>E;E++)if(m[E].transport===h)return m[E]})(f))==null?void 0:s.method)!==null&&r!==void 0?r:f[0].method;if(!p)throw new Error("No available transport method");var g=m=>{try{p(m)}catch(v){Bf(v)?A.warn(v):A.error(v),o.callback==null||o.callback({statusCode:0,error:v})}};h!=="sendBeacon"&&o.data&&o.compression===Ue.GZipJS&&Mp&&typeof Promise<"u"&&!Mr?pm(o).then((m=>{g(m)})).catch((m=>{if(vc(m))return Mr=!0,void g(I({},o,{compression:void 0,url:Zc(n.url,n.method,void 0,n.timestampMode)}));(v=>{if(!v||typeof v!="object")return!1;var E="name"in v?String(v.name):"";return vc(v)||E===hd})(m)&&(Mr=!0),g(o)})):p(o)})(I({},e,{callback:n=>{var i,r;this.rateLimiter.checkForLimiting(n),400>n.statusCode||(i=(r=this.config).on_request_error)==null||i.call(r,n),e.callback==null||e.callback(n)}}))):e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:0}))}Pn(e){this.Rn?this.Rn.retriableRequest(e):this._send_request(e)}_execute_array(e){Ro++;try{var n,i=[],r=[],s=[];vr(e,(a=>{if(a)if(U(n=a[0]))s.push(a);else if(je(a))try{a.call(this)}catch(l){A.error("Error executing queued PostHog call",a,l)}else U(a)&&n==="alias"?i.push(a):U(a)&&n.indexOf("capture")!==-1&&je(this[n])?s.push(a):r.push(a)}));var o=function(a,l){vr(a,(function(u){try{if(U(u[0])){var c=l;ie(u,(function(d){c=c[d[0]].apply(c,d.slice(1))}))}else l[u[0]].apply(l,u.slice(1))}catch(d){A.error("Error executing queued PostHog call",u,d)}}))};o(i,this),o(r,this),o(s,this)}finally{Ro--}}push(e){if(Ro>0&&U(e)&&X(e[0])){var n=Ze.prototype[e[0]];je(n)&&n.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,n,i){var r,s,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.In){if(this.is_capturing())if(!C(e)&&X(e)){var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var c=i!=null&&i.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(c==null||!c.isRateLimited){n!=null&&n.$current_url&&!X(n?.$current_url)&&(A.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),n==null||delete n.$current_url),e!=="$exception"||i!=null&&i.Wn||A.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,h=i?.timestamp||d,f=Ec(i?.uuid,Ht),p={uuid:f,event:e,properties:this.calculateEventProperties(e,n||{},h,f)};e===Vn&&this.config.__preview_capture_bot_pageviews&&u&&(p.event="$bot_pageview",p.properties.$browser_type="bot"),c&&(p.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&p.properties.$feature_flag_has_experiment===!1&&this.get_property(Zr)===!0;i?.$set&&!g&&(p.$set=i?.$set);var m=i?.$unset;m&&(p.$unset=m);var v,E,S,_=g?void 0:this.Vn(i?.$set_once,e!==Ac,e===yo);if(_&&(p.$set_once=_),i!=null&&i._noTruncate||(s=this.config.properties_string_max_length,o=p,a=L=>X(L)?L.slice(0,s):L,l=new Set,p=(function L(N,K){if(N!==Object(N))return a?a(N):N;if(!l.has(N)){var V;if(l.add(N),U(N))V=[],vr(N,(R=>{V.push(L(R))}));else{var M={};ie(N,((R,Z)=>{l.has(R)||(M[Z]=L(R))})),V=M}return V}})(o)),p.timestamp=h,C(i?.timestamp)||(p.properties.$event_time_override_provided=!0,p.properties.$event_time_override_system_time=d),g&&(p.properties=(function(L,N){N===void 0&&(N=[]);var K={},V=M=>{L[M]!==void 0&&(K[M]=L[M])};return Lp.forEach(V),N.forEach(V),K})(p.properties,Rm)),e===qt.DISMISSED||e===qt.SENT){var b=n?.[ko.SURVEY_ID],k=n?.[ko.SURVEY_ITERATION];Vf({id:b,current_iteration:k}),p.$set=I({},p.$set,{[(v={id:b,current_iteration:k},E=e===qt.SENT?"responded":"dismissed",S="$survey_"+E+"/"+v.id,v.current_iteration&&v.current_iteration>0&&(S="$survey_"+E+"/"+v.id+"/"+v.current_iteration),S)]:!0})}else e===qt.SHOWN&&(p.$set=I({},p.$set,{[ko.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===om.SHOWN){var T=n?.[qc.TOUR_TYPE];T&&(p.$set=I({},p.$set,{[qc.TOUR_LAST_SEEN_DATE+"/"+T]:new Date().toISOString()}))}var x=I({},p.properties.$set,p.$set);if(Kt(x)||this.setPersonPropertiesForFlags(x),!H(this.config.before_send)){var F=this.Pt(p);if(!F)return;(p=F).uuid=Ec(p.uuid,Ht)}this.dn.emit("eventCaptured",p);var $=(r=i?._url)!==null&&r!==void 0?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),O={method:"POST",url:$,data:p,compression:"best-available",timestampMode:i?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test($)?"body":"capture-body",batchKey:i?._batchKey,transport:i?.transport};return!this.config.request_batching||i&&(i==null||!i._batchKey)||i!=null&&i.send_instantly?this.Pn(O):this.In.enqueue(O),p}A.critical("This capture call is ignored due to client rate limiting.")}}else A.error("No event name provided to posthog.capture")}else A.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(n=>e(n.event,n)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new Fm(this)}cn(e){this._n.push(e);var n=!0;return()=>{if(n){n=!1;var i=this._n.indexOf(e);i!==-1&&this._n.splice(i,1)}}}calculateEventProperties(e,n,i,r,s){if(i=i||new Date,!this.persistence||!this.sessionPersistence)return n;var o=s?void 0:this.persistence.remove_event_timer(e),a=I({},n);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.gn()&&(a[Qd]=!0),e==="$snapshot"){var l=I({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!X(a.distinct_id)&&!ke(a.distinct_id)||Ko(a.distinct_id))&&A.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=(function(b,k,T,x){var F,$,O,L;if(x===void 0&&(x=!1),!Ge)return{};var N,K=b?[...ri,...k||[]]:[],V=(function(Bn){for(var qe=0;wc.length>qe;qe++){var Dn=wc[qe],Mt=Dn[1],Lt=Dn[0].exec(Bn),ut=Lt&&(je(Mt)?Mt(Lt,Bn):Mt);if(ut)return ut}return["",""]})(Ge),M=V[0],R=V[1],Z=(N=typeof navigator<"u"?navigator:void 0)!=null&&N.brave?{brave:!0}:{},Ce={};C(T)||(Ce.detectGoogleSearchApp=T);var oe={},ye=(F=navigator)==null||(F=F.userAgentData)==null?void 0:F.platform,$e=($=navigator)==null?void 0:$.maxTouchPoints,ae=w==null||(O=w.screen)==null?void 0:O.width,Ie=w==null||(L=w.screen)==null?void 0:L.height,Se=w?.devicePixelRatio;C(ye)||(oe.userAgentDataPlatform=ye),C($e)||(oe.maxTouchPoints=$e),C(ae)||(oe.screenWidth=ae),C(Ie)||(oe.screenHeight=Ie),C(Se)||(oe.devicePixelRatio=Se);var De,wt,ge,Je,bt,mn,Re,Pe,$t=fe(ll({$os:M,$os_version:R,$browser:Bd(Ge,navigator.vendor,Z,Ce),$device:bc(Ge),$device_type:(wt=Ge,ge=oe,Pe=bc(wt),Pe===wd||Pe===yd||Pe==="Kobo"||Pe==="Kindle Fire"||Pe===$d?ei:Pe===Gi||Pe===Xn||Pe===Ki||Pe===Jo?"Console":Pe===Ed?"Wearable":Pe?rt:ge?.userAgentDataPlatform==="Android"&&((Je=ge?.maxTouchPoints)!==null&&Je!==void 0?Je:0)>0?600>Math.min((bt=ge?.screenWidth)!==null&&bt!==void 0?bt:0,(mn=ge?.screenHeight)!==null&&mn!==void 0?mn:0)/((Re=ge?.devicePixelRatio)!==null&&Re!==void 0?Re:1)?rt:ei:"Desktop"),$timezone:Cf(),$timezone_offset:im()}),{$current_url:Zi(x?fn(me?.href):me?.href,K,Xi),$host:me?.host,$pathname:me?.pathname,$raw_user_agent:Ge.length>1e3?Ge.substring(0,997)+"...":Ge,$browser_version:eg(Ge,navigator.vendor,Z,Ce),$browser_language:zc(),$browser_language_prefix:(De=zc(),typeof De=="string"?De.split("-")[0]:void 0),$screen_height:w?.screen.height,$screen_width:w?.screen.width,$viewport_height:w?.innerHeight,$viewport_width:w?.innerWidth,$lib:ne.LIB_NAME,$lib_version:ne.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return ne.SDK_DIST_CHANNEL&&($t.$sdk_dist_channel=ne.SDK_DIST_CHANNEL),$t})(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties,this.config.detect_google_search_app,this.config.disable_capture_url_hashes);if(this.sessionManager){var d=this.sessionManager.checkAndGetSessionAndWindowId(s,i.getTime()),h=d.windowId;a.$session_id=d.sessionId,a.$window_id=h}this.sessionPropsManager&&fe(a,this.sessionPropsManager.getSessionProps());try{var f;this.sessionRecording&&fe(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(f=this.Rn)==null?void 0:f.length}catch(b){a.$sdk_debug_error_capturing_properties=String(b)}if(this.requestRouter.region===xa&&(a.$lib_custom_api_host=this.config.api_host),u=e!==Vn||s?e!==_o||s?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(i):this.pageViewManager.doPageView(i,r),a=fe(a,u),e===Vn&&P&&(a.title=P.title),!C(o)){var p=i.getTime()-o;a.$duration=parseFloat((p/1e3).toFixed(3))}Ge&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();ie(["$referrer","$referring_domain"],(b=>{b in g&&delete m[b]}));var v={};if(this._n.length>0)for(var E of this._n.slice())try{fe(v,E())}catch(b){A.error("Failed to produce browser extension event properties",b)}(a=fe({},c,g,m,I({},v,a))).$is_identified=this._isIdentified(),U(this.config.property_denylist)?ie(this.config.property_denylist,(function(b){delete a[b]})):A.error(Gf+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var S=this.config.sanitize_properties;S&&(A.error(iu),a=S(a,e));var _=this.Zn();return a.$process_person_profile=_,_&&!s&&this.Gn("_calculate_event_properties"),a}Vn(e,n,i){var r;if(n===void 0&&(n=!0),i===void 0&&(i=!1),!this.persistence||!this.Zn()||this.mn&&!i)return e;var s=this.persistence.get_initial_props(),o=(r=this.sessionPropsManager)==null?void 0:r.getSetOnceProps(),a=fe({},s,o||{},e||{}),l=this.config.sanitize_properties;return l&&(A.error(iu),a=l(a,"$set_once")),n&&(this.mn=!0),Kt(a)?void 0:a}register(e,n){var i;(i=this.persistence)==null||i.register(e,n)}register_once(e,n,i){var r;(r=this.persistence)==null||r.register_once(e,n,i)}register_for_session(e){var n;(n=this.sessionPersistence)==null||n.register(e),Object.keys(e).forEach((i=>this.yn.add(i))),this.Qn()}unregister(e){var n;(n=this.persistence)==null||n.unregister(e)}unregister_for_session(e){var n;(n=this.sessionPersistence)==null||n.unregister(e),this.yn.delete(e),this.Qn()}Kn(e,n){this.register({[e]:n})}An(){this.yn.forEach((e=>{var n;(n=this.sessionPersistence)==null||n.unregister(e)})),this.yn.clear(),this.Qn()}Qn(){var e;if(this.bn)if(this.config.persistence==="memory"||(e=this.sessionPersistence)!=null&&e.xi||!be.N())be.q(this.bn);else{var n=[];this.yn.forEach((i=>n.push(i))),n.length>0?be.F(this.bn,n):be.q(this.bn)}}getFeatureFlag(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlag(e,n)}getFeatureFlagPayload(e){var n;return(n=this.featureFlags)==null?void 0:n.getFeatureFlagPayload(e)}getFeatureFlagResult(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlagResult(e,n)}getAllFeatureFlags(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.getAllFeatureFlags())!==null&&e!==void 0?e:[]}isFeatureEnabled(e,n){var i,r;return(i=(r=this.featureFlags)==null?void 0:r.isFeatureEnabled(e,n))!==null&&i!==void 0?i:n?.defaultValue}reloadFeatureFlags(){var e;(e=this.featureFlags)==null||e.reloadFeatureFlags()}updateFlags(e,n,i){var r;(r=this.featureFlags)==null||r.updateFlags(e,n,i)}updateEarlyAccessFeatureEnrollment(e,n,i){var r;(r=this.featureFlags)==null||r.updateEarlyAccessFeatureEnrollment(e,n,i)}getEarlyAccessFeatures(e,n,i){var r;return n===void 0&&(n=!1),(r=this.featureFlags)==null?void 0:r.getEarlyAccessFeatures(e,n,i)}on(e,n){return this.dn.on(e,n)}onFeatureFlags(e){return this.featureFlags?this.featureFlags.onFeatureFlags(e):(e([],{},{errorsLoading:!0}),()=>{})}onSurveysLoaded(e){return this.surveys?this.surveys.onSurveysLoaded(e):(e([],{isLoaded:!1,error:xi}),()=>{})}onSessionId(e){var n,i;return(n=(i=this.sessionManager)==null?void 0:i.onSessionId(e))!==null&&n!==void 0?n:()=>{}}getSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getSurveys(e,n):e([],{isLoaded:!1,error:xi})}getActiveMatchingSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,n):e([],{isLoaded:!1,error:xi})}renderSurvey(e,n){var i;(i=this.surveys)==null||i.renderSurvey(e,n)}displaySurvey(e,n){var i;n===void 0&&(n=xm),(i=this.surveys)==null||i.displaySurvey(e,n)}cancelPendingSurvey(e){var n;(n=this.surveys)==null||n.cancelPendingSurvey(e)}canRenderSurvey(e){var n,i;return(n=(i=this.surveys)==null?void 0:i.canRenderSurvey(e))!==null&&n!==void 0?n:{visible:!1,disabledReason:xi}}canRenderSurveyAsync(e,n){var i,r;return n===void 0&&(n=!1),(i=(r=this.surveys)==null?void 0:r.canRenderSurveyAsync(e,n))!==null&&i!==void 0?i:Promise.resolve({visible:!1,disabledReason:xi})}Jn(e){return!e||Ko(e)?(A.critical("Unique user id has not been set in posthog.identify"),!1):e===mr?(A.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.'),!1):!["distinct_id","distinctid"].includes(e.toLowerCase())&&!["undefined","null"].includes(e.toLowerCase())||(A.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.'),!1)}identify(e,n,i){if(!this.__loaded||!this.persistence)return A.uninitializedWarning("posthog.identify");if(ke(e)&&(e=e.toString(),A.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.Jn(e)&&this.Gn("posthog.identify")){var r=this.get_distinct_id();this.register({$user_id:e}),this.get_property(Yi)||this.register_once({$had_persisted_distinct_id:!0,$device_id:r},""),e!==r&&e!==this.get_property(Fi)&&(this.unregister(Fi),this.register({distinct_id:e}));var s,o=(this.persistence.get_property(at)||Un)===Un,a=e!==r,l=!a&&o;if(a&&o)this.persistence.set_property(at,vn),this.setPersonPropertiesForFlags({$set:n||{},$set_once:i||{}},!1),this.capture(yo,{distinct_id:e,$anon_distinct_id:r},{$set:n||{},$set_once:i||{}}),this.Sn=Fo(e,n,i),(s=this.featureFlags)==null||s.setAnonymousDistinctId(r);else if(l){this.persistence.set_property(at,vn);var u=n||{},c=i||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=Fo(e,n,i)}else(n||i)&&this.setPersonProperties(n,i);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Cn)):l&&(n||i)&&this.reloadFeatureFlags()}}setPersonProperties(e,n){if((e||n)&&this.Gn("posthog.setPersonProperties")){var i=Fo(this.get_distinct_id(),e,n);this.Sn!==i?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:n||{}},!0),this.capture("$set",{$set:e||{},$set_once:n||{}}),this.Sn=i):A.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}unsetPersonProperties(e){var n,i=(U(e)?e:[e]).filter((r=>X(r)&&r.length>0));i.length!==0&&this.Gn("posthog.unsetPersonProperties")&&((n=this.featureFlags)==null||n.unsetPersonPropertiesForFlags(i,!0),this.capture("$set",{$unset:i}),this.Sn=null)}group(e,n,i){if(e&&n){var r=this.getGroups(),s=r[e]!==n;if(s&&this.resetGroupPropertiesForFlags(e),this.register({$groups:I({},r,{[e]:n})}),s||i){var o={$group_type:e,$group_key:n};i&&(o.$group_set=i),this.capture(Ac,o)}i&&this.setGroupPropertiesForFlags({[e]:i}),s&&!i&&this.reloadFeatureFlags()}else A.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),(i=this.featureFlags)==null||i.setPersonPropertiesForFlags(e,n)}resetPersonPropertiesForFlags(e){var n;e===void 0&&(e=!0),(n=this.featureFlags)==null||n.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((i=this.featureFlags)==null||i.setGroupPropertiesForFlags(e,n))}resetGroupPropertiesForFlags(e){var n;(n=this.featureFlags)==null||n.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,n){var i,r,s,o,a,l,u,c,d,h;if(n===void 0&&(n=!1),A.info("reset"),!this.__loaded)return A.uninitializedWarning("posthog.reset");var f,p=this.get_property(Yi),g=this.get_property(vo),m=this.get_property(An),v=this.is_capturing();if(this.consent.reset(),n||!v||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after."),(i=this.persistence)==null||i.clear(),(r=this.sessionPersistence)==null||r.clear(),this.yn.clear(),this.Qn(),C(m)||(f=this.persistence)==null||f.register({[An]:m}),(s=this.surveys)==null||s.reset(),(o=this.Un)==null||o.stop(),(a=this.featureFlags)==null||a.reset(),(l=this.conversations)==null||l.reset(),(u=this.logs)==null||u.reset(),(c=this.metrics)==null||c.reset(),(d=this.persistence)==null||d.set_property(at,Un),(h=this.sessionManager)==null||h.resetSessionId(),this.Sn=null,this.config.cookieless_mode===Wt)this.register_once({distinct_id:mr,$device_id:null},"");else{var E=this.config.get_device_id(Ht());this.register_once({distinct_id:E,$device_id:e?E:p},""),e||C(g)||this.register({[vo]:g})}this.register({$last_posthog_reset:new Date().toISOString()},1),delete this.config.identity_distinct_id,delete this.config.identity_hash,this.reloadFeatureFlags()}shutdown(e){var n=this;return se((function*(){var i,r,s,o,a,l,u;if(n.__loaded){(i=n.Un)==null||i.stop(),(r=n.jn)==null||r.dispose(),(s=n.sessionRecording)==null||s.dispose(),(o=n.logs)==null||o.flushLogs("sendBeacon"),(a=n.metrics)==null||a.flush("sendBeacon"),(l=n.In)==null||l.unload(),(u=n.Rn)==null||u.unload();try{var c;(c=n.featureFlags)==null||c.destroy()}catch(d){A.error("Error while destroying feature flags",d)}}else A.uninitializedWarning("posthog.shutdown")}))()}setIdentity(e,n){var i;this.config.identity_distinct_id=e,this.config.identity_hash=n,this.alias(e),(i=this.conversations)==null||i.Xn()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,(e=this.conversations)==null||e.ts()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,n;return(e=(n=this.sessionManager)==null?void 0:n.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var n=this.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.sessionStartTimestamp,r=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+n.sessionId);if(e!=null&&e.withTimestamp&&i){var s,o=(s=e.timestampLookBack)!==null&&s!==void 0?s:10;if(!i)return r;r+="?t="+Math.max(Math.floor((new Date().getTime()-i)/1e3)-o,0)}return r}alias(e,n){return e===this.get_property(Gd)?(A.critical("Attempting to create alias for existing People user - aborting."),-2):this.Gn("posthog.alias")?(C(n)&&(n=this.get_distinct_id()),e!==n?(this.Kn(Fi,e),this.capture("$create_alias",{alias:e,distinct_id:n})):(A.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var n=I({},this.config);if(he(e)){var i,r,s,o,a,l,u,c,d,h,f,p;fe(this.config,ru(e));var g=this.En();(i=this.persistence)==null||i.update_config(this.config,n,g),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new xo(I({},this.config,{persistence:"sessionStorage"}),g,!1);var m=this.Cn(this.config.debug);mt(m)&&(this.config.debug=m),mt(this.config.debug)&&(this.config.debug?(ne.DEBUG=!0,le.N()&&le.F("ph_debug",!0),A.info("set_config",{config:e,oldConfig:n,newConfig:I({},this.config)})):(ne.DEBUG=!1,le.N()&&le.q("ph_debug"))),(r=this.featureFlags)==null||r.updateConfig==null||r.updateConfig(this.config,this.Qi()),(s=this.exceptionObserver)==null||s.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(h=this.deadClicksAutocapture)==null||h.startIfEnabledOrStop(),(f=this.surveys)==null||f.loadIfEnabled(),this.es(),(p=this.externalIntegrations)==null||p.startIfEnabledOrStop()}}_overrideSDKInfo(e,n){ne.LIB_NAME=e,ne.LIB_VERSION=n}startSessionRecording(e){var n,i,r,s,o,a=e===!0,l={sampling:a||!(e==null||!e.sampling),linked_flag:a||!(e==null||!e.linked_flag),url_trigger:a||!(e==null||!e.url_trigger),event_trigger:a||!(e==null||!e.event_trigger)};Object.values(l).some(Boolean)&&((n=this.sessionManager)==null||n.checkAndGetSessionAndWindowId(),l.sampling&&((i=this.sessionRecording)==null||i.overrideSampling()),l.linked_flag&&((r=this.sessionRecording)==null||r.overrideLinkedFlag()),l.url_trigger&&((s=this.sessionRecording)==null||s.overrideTrigger("url")),l.event_trigger&&((o=this.sessionRecording)==null||o.overrideTrigger("event"))),this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,n){if(this.exceptions){var i=new Error("PostHog syntheticException"),r=this.exceptions.buildProperties(e,{handled:!0,syntheticException:i});return this.exceptions.sendExceptionEvent(I({},r,n))}}addExceptionStep(e,n){var i;(i=this.exceptions)==null||i.addExceptionStep(e,n)}captureLog(e){var n;(n=this.logs)==null||n.captureLog(e)}get logger(){var e,n;return(e=(n=this.logs)==null?void 0:n.logger)!==null&&e!==void 0?e:Ze.rs}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var n,i;return(n=(i=this.toolbar)==null?void 0:i.loadToolbar(e))!==null&&n!==void 0&&n}get_property(e){var n;return(n=this.persistence)==null?void 0:n.props[e]}getSessionProperty(e){var n;return(n=this.sessionPersistence)==null?void 0:n.props[e]}toString(){var e,n=(e=this.config.name)!==null&&e!==void 0?e:Gn;return n!==Gn&&(n=Gn+"."+n),n}_isIdentified(){var e,n;return((e=this.persistence)==null?void 0:e.get_property(at))===vn||((n=this.sessionPersistence)==null?void 0:n.get_property(at))===vn}Zn(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles===pa&&!this._isIdentified()&&Kt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[Fi])&&((n=this.persistence)==null||(n=n.props)==null||!n[es]))}zn(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Zn()||this.Gn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.Gn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}Gn(e){return this.config.person_profiles==="never"?(A.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Kn(es,!0),!0)}En(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut();return this.config.disable_persistence||e&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!==kn)}es(){var e,n,i,r,s=this.En();return((e=this.persistence)==null?void 0:e.xi)!==s&&((i=this.persistence)==null||i.set_disabled(s)),((n=this.sessionPersistence)==null?void 0:n.xi)!==s&&((r=this.sessionPersistence)==null||r.set_disabled(s)),s&&(this.yn.clear(),this.Qn()),s}opt_in_capturing(e){var n;if(this.config.cookieless_mode!==Wt){if(this.gn()){var i,r,s,o,a;this.Yn(!0,!0),(i=this.sessionManager)==null||i.destroy(),(r=this.pageViewManager)==null||r.destroy(),this.sessionManager=new Qc(this),this.pageViewManager=new Wc(this),this.persistence&&(this.sessionPropsManager=new Xc(this,this.sessionManager,this.persistence));var l,u=(s=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&s!==void 0?s:(a=Ze.__defaultExtensionClasses)==null?void 0:a.sessionRecording;u&&(this.sessionRecording=this.pn(this.sessionRecording,new u(this)),this.hn&&((l=this.sessionRecording)==null||l.onRemoteConfig==null||l.onRemoteConfig(this.hn)))}var c,d;this.consent.optInOut(!0),this.es(),this.Bn(),(n=this.sessionRecording)==null||n.startIfEnabledOrStop(),this.config.cookieless_mode==kn&&((c=this.surveys)==null||c.loadIfEnabled()),(C(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((d=e?.captureEventName)!==null&&d!==void 0?d:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hn()}else A.warn(nu)}opt_out_capturing(){var e,n,i;this.config.cookieless_mode!==Wt?(this.config.cookieless_mode===kn&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===kn&&(this.register({distinct_id:mr,$device_id:null}),(e=this.sessionRecording)==null||e.stopRecording(),this.sessionRecording=void 0,(n=this.sessionManager)==null||n.destroy(),(i=this.pageViewManager)==null||i.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.Hn(),this.Bn())):A.warn(nu)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===Wt||(this.config.cookieless_mode===kn?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return He?jf(He,this.config.custom_blocked_useragents):void 0}Hn(){P&&(P.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(Vn,{title:P.title},{send_instantly:!0}),this.kn&&(P.removeEventListener(ts,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),ve(P,ts,this.kn)))}debug(e){e===!1?(w?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(w?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}Qi(){var e=this.Mn||{};return"advanced_disable_flags"in e?!!e.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(A.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(function(n,i,r,s,o){var a=i in n&&!H(n[i]),l=r in n&&!H(n[r]);return a?n[i]:!!l&&(o&&o.warn("Config field '"+r+"' is deprecated. Please use '"+i+"' instead. The old field will be removed in a future major version."),n[r])})(e,"advanced_disable_flags","advanced_disable_decide",0,A)}Pt(e){var n;if(H(this.config.before_send))return e;var i=Object.keys((n=e.properties)!==null&&n!==void 0?n:{}).filter(Hp),r=U(this.config.before_send)?this.config.before_send:[this.config.before_send],s=e;for(var o of r){if(s=o(s),H(s)){var a="Event '"+e.event+"' was rejected in beforeSend function";return Up(e.event)?A.warn(a+". This can cause unexpected behavior."):A.info(a),null}s.properties&&!Kt(s.properties)||A.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}for(var l of i)if(s.properties&&H(s.properties[l]))return A.warn("Event '"+e.event+"' had its '"+l+"' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped."),null;return s}getPageViewId(){var e;return(e=this.pageViewManager.ui)==null?void 0:e.pageViewId}captureTraceFeedback(e,n){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:n})}captureTraceMetric(e,n,i){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:n,$ai_metric_value:String(i)})}Cn(e){var n=mt(e)&&!e,i=le.N()&&le.P("ph_debug")==="true";return!n&&(!!i||e)}}Ze.__defaultExtensionClasses={},Ze.rs=(()=>{var t=()=>{};return{trace:t,debug:t,info:t,warn:t,error:t,fatal:t}})(),(function(t,e){for(var n=0;e.length>n;n++)t.prototype[e[n]]=Fg(t.prototype[e[n]])})(Ze,["identify"]);class su{constructor(e){this.disabled=e===!1;var n=he(e)?e:{};this.thresholdPx=n.threshold_px||30,this.timeoutMs=n.timeout_ms||1e3,this.clickCount=n.click_count||3,this.clicks=[]}isRageClick(e,n,i){if(this.disabled)return!1;var r=this.clicks[this.clicks.length-1];if(r&&Math.abs(e-r.x)+Math.abs(n-r.y)i-r.timestamp){if(this.clicks.push({x:e,y:n,timestamp:i}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:n,timestamp:i}];return!1}}var $o="$copy_autocapture",Mo=pe("[AutoCapture]");function Lo(t,e){return e.length>t?e.slice(0,t)+"...":e}function Mm(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!hn(e));return e}function Lm(t,e){var n,i,r=e.e,s=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!hn(t))return{props:{}};for(var c=[t],d=new Set([t]),h=t;h.parentNode&&!et(h,"body")&&uf>c.length;)if(cf(h.parentNode)){var f=h.parentNode.host;if(d.has(f))break;d.add(f),c.push(f),h=f}else{if(!hn(h.parentNode)||d.has(h.parentNode))break;d.add(h.parentNode),c.push(h.parentNode),h=h.parentNode}var p,g,m=[],v={},E=!1,S=!1;if(ie(c,(x=>{var F=va(x);if(et(x,"a")){var $=x.getAttribute("href");E=!!(F&&$&&Ui($))&&(u?fn($):$)}j(rs(x),"ph-no-capture")&&(S=!0),m.push((function(L,N,K,V,M){M===void 0&&(M=!1);var R=L.tagName.toLowerCase(),Z={tag_name:R};ul.indexOf(R)>-1&&!K&&(Z.$el_text=R.toLowerCase()==="a"||R.toLowerCase()==="button"?Lo(1024,jc(L)):Lo(1024,Ji(L)));var Ce=rs(L);Ce.length>0&&(Z.classes=Ce.filter((function(ae){return ae!==""}))),ie(L.attributes,(function(ae){var Ie;if((!gf(L)||["name","id","class","aria-label"].indexOf(ae.name)!==-1)&&(V==null||!V.includes(ae.name))&&!N&&Ui(ae.value)&&(!X(Ie=ae.name)||Ie.substring(0,10)!=="_ngcontent"&&Ie.substring(0,7)!=="_nghost")){var Se=ae.value;ae.name==="class"&&(Se=cl(Se).join(" ")),Z["attr__"+ae.name]=Lo(1024,ae.name==="href"&&M?fn(Se):Se)}}));for(var oe=1,ye=1,$e=L;$e=Mm($e);)oe++,$e.tagName===L.tagName&&ye++;return Z.nth_child=oe,Z.nth_of_type=ye,Z})(x,s,o,a,u));var O=(function(L){if(!va(L))return{};var N={};return ie(L.attributes,(function(K){if(K.name&&K.name.indexOf("data-ph-capture-attribute")===0){var V=K.name.replace("data-ph-capture-attribute-",""),M=K.value;V&&M&&Ui(M)&&(N[V]=M)}})),N})(x);fe(v,O)})),S)return{props:{},explicitNoCapture:S};if(o||(m[0].$el_text=et(t,"a")||et(t,"button")?jc(t):Ji(t)),E){var _,b;m[0].attr__href=E;var k=(_=ss(E))==null?void 0:_.host,T=w==null||(b=w.location)==null?void 0:b.host;k&&T&&k!==T&&(p=E)}return{props:fe({$event_type:r.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(x){return x.map((F=>{var $,O,L="";if(F.tag_name&&(L+=F.tag_name),F.attr_class)for(var N of(F.attr_class.sort(),F.attr_class))L+="."+N.replace(/"/g,"");var K=I({},F.text?{text:F.text}:{},{"nth-child":($=F.nth_child)!==null&&$!==void 0?$:0,"nth-of-type":(O=F.nth_of_type)!==null&&O!==void 0?O:0},F.href?{href:F.href}:{},F.attr_id?{attr_id:F.attr_id}:{},F.attributes),V={};return $r(K).sort(((M,R)=>M[0].localeCompare(R[0]))).forEach((M=>{var R=M[1];return V[Uc(M[0].toString())]=Uc(R.toString())})),(L+=":")+$r(V).map((M=>M[0]+'="'+M[1]+'"')).join("")})).join(";")})((function(x){return x.map((F=>{var $,O,L={text:($=F.$el_text)==null?void 0:$.slice(0,400),tag_name:F.tag_name,href:(O=F.attr__href)==null?void 0:O.slice(0,2048),attr_class:Yg(F),attr_id:F.attr__id,nth_child:F.nth_child,nth_of_type:F.nth_of_type,attributes:{}};return $r(F).filter((N=>N[0].indexOf("attr__")===0)).forEach((N=>L.attributes[N[0]]=N[1])),L}))})(g)))},(n=m[0])!=null&&n.$el_text?{$el_text:(i=m[0])==null?void 0:i.$el_text}:{},p&&r.type==="click"?{$external_click_url:p}:{},v)}}var Ii=pe("[ExceptionAutocapture]"),ou=()=>{},Nm=pe("[TracingHeaders]"),wn=pe("[Web Vitals]"),au=9e5,lu="disabled",cu="lazy_loading",ki="awaiting_config",Sr="missing_config";pe("[SessionRecording]"),pe("[SessionRecording]");var Ia="[SessionRecording]",Bt=pe(Ia),Om=pe("[Heatmaps]");function No(t){return he(t)&&"clientX"in t&&"clientY"in t&&ke(t.clientX)&&ke(t.clientY)}var xr=pe("[Product Tours]"),Oo=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(sl))},Bm=["$set_once","$set"],Et=pe("[SiteApps]"),uu="Error while initializing PostHog app with config id ";function zn(t,e,n){if(H(t))return!1;switch(n){case"exact":return t===e;case"contains":var i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(i,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}class Dm{constructor(e){this.ns=new pl,this.ss=(n,i)=>this.os(n,i)&&this.ls(n,i)&&this.us(n,i)&&this.hs(n,i),this.os=(n,i)=>i==null||!i.event||n?.event===i?.event,this._instance=e,this.ds=new Set,this.vs=new Set}init(){var e,n;C((e=this._instance)==null?void 0:e._addCaptureHook)||(n=this._instance)==null||n._addCaptureHook(((i,r)=>{this.on(i,r)}))}register(e){var n,i;if(!C((n=this._instance)==null?void 0:n._addCaptureHook)&&(e.forEach((o=>{var a,l;(a=this.vs)==null||a.add(o),(l=o.steps)==null||l.forEach((u=>{var c;(c=this.ds)==null||c.add(u?.event||"")}))})),(i=this._instance)!=null&&i.autocapture)){var r,s=new Set;e.forEach((o=>{var a;(a=o.steps)==null||a.forEach((l=>{l!=null&&l.selector&&s.add(l?.selector)}))})),(r=this._instance)==null||r.autocapture.setElementSelectors(s)}}on(e,n){var i;n!=null&&e.length!=0&&(this.ds.has(e)||this.ds.has(n.event))&&this.vs&&((i=this.vs)==null?void 0:i.size)>0&&this.vs.forEach((r=>{this.cs(n,r)&&this.ns.emit("actionCaptured",r.name)}))}fs(e){this.onAction("actionCaptured",(n=>e(n)))}cs(e,n){if(n?.steps==null)return!1;for(var i of n.steps)if(this.ss(e,i))return!0;return!1}onAction(e,n){return this.ns.on(e,n)}ls(e,n){if(n!=null&&n.url){var i,r=e==null||(i=e.properties)==null?void 0:i.$current_url;if(!r||typeof r!="string"||!zn(r,n.url,n.url_matching||"contains"))return!1}return!0}us(e,n){return!!this.ps(e,n)&&!!this.gs(e,n)&&!!this.ys(e,n)}ps(e,n){var i;if(n==null||!n.href)return!0;var r=this.bs(e);if(r.length>0)return r.some((a=>zn(a.href,n.href,n.href_matching||"exact")));var s,o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!o&&zn((s=o.match(/(?::|")href="(.*?)"/))?s[1]:"",n.href,n.href_matching||"exact")}gs(e,n){var i;if(n==null||!n.text)return!0;var r=this.bs(e);if(r.length>0)return r.some((u=>zn(u.text,n.text,n.text_matching||"exact")||zn(u.$el_text,n.text,n.text_matching||"exact")));var s,o,a,l=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!l&&(s=(function(u){for(var c,d=[],h=/(?::|")text="(.*?)"/g;!H(c=h.exec(u));)d.includes(c[1])||d.push(c[1]);return d})(l),o=n.text,a=n.text_matching||"exact",s.some((u=>zn(u,o,a))))}ys(e,n){var i,r;if(n==null||!n.selector)return!0;var s=e==null||(i=e.properties)==null?void 0:i.$element_selectors;if(s!=null&&s.includes(n.selector))return!0;var o=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";if(n.selector_regex&&o)try{return new RegExp(n.selector_regex).test(o)}catch{return!1}return!1}bs(e){var n;return(e==null||(n=e.properties)==null?void 0:n.$elements)==null?[]:e?.properties.$elements}hs(e,n){return n==null||!n.properties||n.properties.length===0||Wf(n.properties.reduce(((i,r)=>{var s=U(r.value)?r.value.map(String):r.value!=null?[String(r.value)]:[];return i[r.key]={values:s,operator:r.operator||"exact"},i}),{}),e?.properties)}}class jm{constructor(e){var n;this._s=[],this._instance=e,this.ws=new Map,this.ks=new Map,this.xs=new Map,(n=this._instance)==null||n.onSessionId==null||n.onSessionId((i=>this.Ss(i)))}Cs(e){return!1}Ms(){return null}Ts(e){}Es(){}Is(e,n){return!!e&&Wf(e.propertyFilters,n?.properties)}Ps(e,n){var i=new Map;return e.forEach((r=>{var s;(s=r.conditions)==null||(s=s[n])==null||(s=s.values)==null||s.forEach((o=>{if(o!=null&&o.name){var a=i.get(o.name)||[];a.push(r.id),i.set(o.name,a)}}))})),i}Rs(e,n,i){var r=(i===wi.Activation?this.ws:this.ks).get(e),s=[];return this.As((o=>{s=o.filter((a=>r?.includes(a.id)))})),s.filter((o=>{var a,l=(a=o.conditions)==null||(a=a[i])==null||(a=a.values)==null?void 0:a.find((u=>u.name===e));return this.Is(l,n)}))}register(e){var n;C((n=this._instance)==null?void 0:n._addCaptureHook)||(this.Fs(e),this.Ls(e))}Ls(e){var n=e.filter((i=>{var r,s;return((r=i.conditions)==null?void 0:r.actions)&&((s=i.conditions)==null||(s=s.actions)==null||(s=s.values)==null?void 0:s.length)>0}));n.length!==0&&(this.Os==null&&(this.Os=new Dm(this._instance),this.Os.init(),this.Os.fs((i=>{this.onAction(i)}))),n.forEach((i=>{var r,s,o,a,l;i.conditions&&(r=i.conditions)!=null&&r.actions&&(s=i.conditions)!=null&&(s=s.actions)!=null&&s.values&&((o=i.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.Os)==null||a.register(i.conditions.actions.values),(l=i.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var c=this.xs.get(u.name);c&&c.push(i.id),this.xs.set(u.name,c||[i.id])}})))})))}Fs(e){var n,i=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.events)&&((a=s.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0})),r=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.cancelEvents)&&((a=s.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0}));i.length===0&&r.length===0||((n=this._instance)==null||n._addCaptureHook(((s,o)=>{this.onEvent(s,o)})),this.ws=this.Ps(e,wi.Activation),this.ks=this.Ps(e,wi.Cancellation))}onEvent(e,n){var i,r,s=this.Ds(),o=(n==null||(i=n.properties)==null?void 0:i.$survey_id)||(n==null||(r=n.properties)==null?void 0:r.$product_tour_id);if(o&&this.getActivatedIds().includes(o)){var a=this.$s(e,o);if(a==="consume")return s.info("event consumed activated item, removing it",{event:e,itemId:o}),void this.Ns([o]);if(a==="persist")return s.info("shown item promoted to persisted activation",{event:e,itemId:o}),this.qs(o),void this.js([o])}if(this.ks.has(e)){var l=this.Rs(e,n,wi.Cancellation);l.length>0&&(s.info("cancel event matched, cancelling items",{event:e,itemsToCancel:l.map((c=>c.id))}),this.Ns(l.map((c=>c.id))),l.forEach((c=>this.Bs(c.id))))}if(this.ws.has(e)){s.info("event name matched",{event:e,eventPayload:n,items:this.ws.get(e)});var u=this.Rs(e,n,wi.Activation);this.Hs(u.map((c=>c.id)))}}onAction(e){this.xs.has(e)&&this.Hs(this.xs.get(e)||[])}Hs(e){var n;if(e.length!==0){var i=!((n=this._instance)==null||n.get_session_id==null||!n.get_session_id()),r=[];for(var s of e)i&&this.Cs(s)?this.qs(s)&&this.Us(s):r.push(s);r.length>0&&(this._s=[...new Set([...this._s,...r])]),this.Ds().info("updating activated items",{activatedItems:this.getActivatedIds()})}}qs(e){this._s=this._s.filter((i=>i!==e));var n=this.zs();return!n.includes(e)&&(this.Ws([...n,e]),this.Vs(),!0)}Ns(e){var n=new Set(e);this._s=this._s.filter((s=>!n.has(s)));var i=this.Zs(),r=i.filter((s=>!n.has(s)));r.length!==i.length&&(this.Ws(r),r.length===0&&this.Gs()),this.js(e)}Qs(){var e,n=this.Ms();if(!n)return{};var i=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n];return i&&typeof i=="object"?i:{}}Us(e){if(this.Ms()){var n=this.Qs();this.Ts(I({},n,{[e]:Date.now()}))}}js(e){if(this.Ms()){var n=this.Qs(),i={},r=!1;for(var s of Object.entries(n)){var o=s[0],a=s[1];e.includes(o)?r=!0:i[o]=a}r&&(Kt(i)?this.Es():this.Ts(i))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var n=this.Qs()[e];return ke(n)?n:void 0}}Zs(){var e,n=this.Js();return((e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n])||[]}zs(){var e,n,i=this.Zs();if(i.length===0)return[];var r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[this.Ys()],s=(n=this._instance)==null||n.get_session_id==null?void 0:n.get_session_id();return s&&r===s?i:[]}Vs(){var e,n=(e=this._instance)==null||e.get_session_id==null?void 0:e.get_session_id();n&&this.Xs(n)}Gs(){this.ta()}Ss(e){var n,i=(n=this._instance)==null||(n=n.persistence)==null?void 0:n.props[this.Ys()];if(i&&i!==e){var r=this.Zs(),s=this.Qs();r.length>0&&(this.Ws([]),r.filter((o=>ke(s[o]))).forEach((o=>this.Bs(o)))),this.Gs(),this.Ks()}}getActivatedIds(){return[...new Set([...this.zs(),...this._s])].filter((e=>!this.ea(e)))}reset(){this._s=[],this.Zs().length>0&&this.Ws([]),this.Gs(),this.Ks()}getEventToItemsMap(){return this.ws}ia(){return this.Os}}class Um extends jm{constructor(e){super(e)}Js(){return ca}Ys(){return Fr}Ms(){return Rr}Ts(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Rr]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Rr)}Cs(e){var n,i;this.As((s=>{i=s.find((o=>o.id===e))}));var r=(n=i)==null||(n=n.appearance)==null?void 0:n.surveyPopupDelaySeconds;return ke(r)&&r>0}ra(){return qt.SHOWN}As(e){var n;(n=this._instance)==null||n.getSurveys(e)}Bs(e){var n;(n=this._instance)==null||n.cancelPendingSurvey(e)}Ds(){return Q}Ws(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[ca]:e})}Xs(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Fr]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Fr)}ea(){return!1}$s(e,n){var i;this.As((s=>{i=s.find((o=>o.id===n))}));var r=!i||(function(s){var o;return zf(s)&&!((o=s.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||s.schedule==="always"})(i);return r?e===qt.SHOWN?"consume":"ignore":e===qt.SHOWN?"persist":e===qt.DISMISSED||e===qt.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var Ir="SDK is not enabled or survey functionality is not yet loaded",du="Disabled. Not loading surveys.",Hm=w!=null&&w.location?os(w.location.hash,"__posthog")||os(location.hash,"state"):null,fu="_postHogToolbarParams",hu=pe("[Toolbar]"),pu=pe("[FeatureFlags]");class Wm{constructor(e,n){n===void 0&&(n=!1),this.na=!1,this.update(e,n)}update(e,n){this.sa=((i,r)=>{var s,o,a,l;return{bootstrap:{featureFlags:(s=i.bootstrap)==null?void 0:s.featureFlags,featureFlagPayloads:(o=i.bootstrap)==null?void 0:o.featureFlagPayloads},remoteRequestsDisabled:r,featureFlagsDisabled:!!i.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!i.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!i.advanced_feature_flags_dedup_per_session,cacheTtlMs:i.feature_flag_cache_ttl_ms,requestTimeoutMs:i.feature_flag_request_timeout_ms,compression:i.disable_compression?"none":"base64",evaluationContexts:(a=(l=i.evaluation_contexts)!==null&&l!==void 0?l:i.evaluation_environments)!==null&&a!==void 0?a:[],flagKeys:U(i.flag_keys)?i.flag_keys:void 0}})(e,n),!e.evaluation_environments||e.evaluation_contexts||this.na||(pu.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.na=!0),C(e.flag_keys)||U(e.flag_keys)||pu.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var gu=pe("[FeatureFlags]"),bn=pe("[FeatureFlags]",{debugEnabled:!0}),Bo=`" failed. Feature flags didn't load in time.`,mu="connection_error",vu=t=>{for(var e={},n=0;t.length>n;n++)e[t[n]]=!0;return e},_u=t=>{var e={};for(var n of $r(t||{})){var i=n[1];i&&(e[n[0]]=i)}return e},St=pe("[Error tracking]"),yu="Refusing to render web experiment since the viewer is a likely bot",zm={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>cs(e,t),not_regex:(t,e)=>!cs(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class Me{get Ne(){return this._instance.config}constructor(e){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(i){i===void 0&&(i=!1),n.getWebExperiments((r=>{Me.aa("retrieved web experiments from the server"),n.oa=new Map,r.forEach((s=>{if(s.feature_flag_key){var o;n.oa&&(Me.aa("setting flag key ",s.feature_flag_key," to web experiment ",s),(o=n.oa)==null||o.set(s.feature_flag_key,s));var a=n._instance.getFeatureFlag(s.feature_flag_key);X(a)&&s.variants[a]&&n.la(s.name,a,s.variants[a].transforms)}else if(s.variants)for(var l in s.variants){var u=s.variants[l];Me.ua(u,n._instance)&&n.la(s.name,l,u.transforms)}}))}),i)},this._instance=e,this._instance.onFeatureFlags((i=>{this.onFeatureFlags(i)}))}initialize(){}onFeatureFlags(e){if(this._is_bot())Me.aa(yu);else if(!this.Ne.disable_web_experiments){if(H(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();Me.aa("applying feature flags",e),e.forEach((n=>{var i;if(this.oa&&(i=this.oa)!=null&&i.has(n)){var r,s=this._instance.getFeatureFlag(n),o=(r=this.oa)==null?void 0:r.get(n);s&&o!=null&&o.variants[s]&&this.la(o.name,s,o.variants[s].transforms)}}))}}previewWebExperiment(){var e=Me.getWindowLocation();if(e!=null&&e.search){var n=ii(e?.search,"__experiment_id"),i=ii(e?.search,"__experiment_variant");n&&i&&(Me.aa("previewing web experiments "+n+" && "+i),this.getWebExperiments((r=>{this.ha(parseInt(n),i,r)}),!1,!0))}}loadIfEnabled(){this.Ne.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,n,i){if(this.Ne.disable_web_experiments&&!i)return e([]);var r=this._instance.get_property("$web_experiments");if(r&&!n)return e(r);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this.Ne.token),method:"GET",timestampMode:"query",callback:s=>e(s.statusCode===200&&s.json&&s.json.experiments||[])})}ha(e,n,i){var r=i.filter((s=>s.id===e));r&&r.length>0&&(Me.aa("Previewing web experiment ["+r[0].name+"] with variant ["+n+"]"),this.la(r[0].name,n,r[0].variants[n].transforms))}static ua(e,n){return!H(e.conditions)&&Me.da(e,n)&&Me.va(e)}static da(e,n){var i;if(H(e.conditions)||H((i=e.conditions)==null?void 0:i.url))return!0;var r=Me.getWindowLocation();if(r){var s,o,a,l=of(n,r.href);return(s=e.conditions)==null||!s.url||zm[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return w?.location}static va(e){var n;if(H(e.conditions)||H((n=e.conditions)==null?void 0:n.utm))return!0;var i=bf();if(i.utm_source){var r,s,o,a,l,u,c,d,h=(r=e.conditions)==null||(r=r.utm)==null||!r.utm_campaign||((s=e.conditions)==null||(s=s.utm)==null?void 0:s.utm_campaign)==i.utm_campaign,f=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==i.utm_source,p=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==i.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==i.utm_term;return h&&p&&g&&f}return!1}static aa(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;n>r;r++)i[r-1]=arguments[r];A.info("[WebExperiments] "+e,i)}la(e,n,i){this._is_bot()?Me.aa(yu):n!=="control"?i.forEach((r=>{if(r.selector){var s;Me.aa("applying transform of variant "+n+" for experiment "+e+" ",r);var o=(s=document)==null?void 0:s.querySelectorAll(r.selector);o?.forEach((a=>{var l=a;r.html&&(l.innerHTML=r.html),r.css&&l.setAttribute("style",r.css)}))}})):Me.aa("Control variants leave the page unmodified.")}_is_bot(){return He&&this._instance?jf(He,this.Ne.custom_blocked_useragents):void 0}}var ot=pe("[Conversations]"),En="Conversations not available yet.",wu="console",Yf="__posthogHandledLogsRequestError",Do=(t,e)=>{var n=t instanceof Error?t:new Error(e);return n[Yf]=!0,n},bu=t=>!!t&&typeof t=="object"&&t[Yf]===!0,Cs={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=gu,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 Wm(t.config,t.Qi()),this.Ta=this.Ea)}updateConfig(t,e){var n;(n=this.Ea)==null||n.update(t,e)}setup(t){return this.Ia=t,this.rt=t.logger.createLogger("[FeatureFlags]"),n=()=>{this.Ia===t&&(this.Ia=void 0,this.nn=t,this.Pa(t))},(e=t.kv.initialize())!=null&&e.then?e.then(n):n();var e,n}Pa(t){if(this.nn===t)return w&&ve(w,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){w?.removeEventListener("online",this.Ca)}dispose(){var t;this.ba++,this.wa=!1,this.Ia=void 0,this.nn&&(this.La(),(t=this.Ra)==null||t.dispose(),this.Ra=void 0,this.ga=[],w?.removeEventListener("online",this.Ca),this.nn=void 0)}get Ne(){return this.Ta.get()}Oa(t){var e;return(e=this.nn)==null?void 0:e.kv.get(t)}F(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.set(t)}))}q(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.remove(t)}))}Da(t){try{t()}catch(e){this.rt.error("Failed to update feature flag persistence",e)}}Fa(){var t={};for(var e of[Ti,$i,Pr,It]){var n=this.Oa(e);C(n)||(t[e]=n)}this.fa=t;var i=I({},t),r=this.Oa(Sn);if(r)for(var s of Object.entries(r))i["$feature/"+s[0]]=s[1];this.pa=i}Aa(){var t=this.Ne.cacheTtlMs;if(!t||0>=t)return!1;var e=this.Oa(ji);return typeof e!="number"||Date.now()-e>t}$a(){return!!this.Aa()&&(this.xa||this.ya||(this.xa=!0,this.rt.warn("Feature flag cache is stale, triggering refresh..."),this.reloadFeatureFlags()),!0)}Na(){var t=this.Ne.evaluationContexts;return t!=null&&t.length?t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid evaluation context found:",e,"Expected non-empty string"),n})):[]}qa(){var t=this.Ne.flagKeys;if(!C(t))return t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid flag key found:",e,"Expected non-empty string"),n}))}initialize(){var t,e,n=this.Ne,i=(t=(e=n.bootstrap)==null?void 0:e.featureFlags)!==null&&t!==void 0?t:{};if(Object.keys(i).length){var r,s,o=(r=(s=n.bootstrap)==null?void 0:s.featureFlagPayloads)!==null&&r!==void 0?r:{},a=Object.keys(i).filter((u=>!!i[u])).reduce(((u,c)=>(u[c]=i[c]||!1,u)),{}),l=Object.keys(o).filter((u=>a[u])).reduce(((u,c)=>(o[c]&&(u[c]=o[c]),u)),{});return this.ja({featureFlags:a,featureFlagPayloads:l})}}updateFlags(t,e,n){var i,r,s=n!=null&&n.merge&&(i=this.Oa(Sn))!==null&&i!==void 0?i:{},o=n!=null&&n.merge&&(r=this.Oa($i))!==null&&r!==void 0?r:{},a=I({},s,t),l=I({},o,e),u={};for(var c of Object.entries(a)){var d=c[0],h=c[1];u[d]={key:d,enabled:hc(h),variant:pc(h),reason:void 0,metadata:C(l?.[d])?void 0:{id:0,version:void 0,description:void 0,payload:l[d]}}}this.ja({flags:u})}get hasLoadedFlags(){return this.ma}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var t=this.Oa(aa),e=this.Oa(It),n=this.Oa(xn);if(!n&&!e)return t||{};var i=fe({},t||{}),r=[...new Set([...Object.keys(n||{}),...Object.keys(e||{})])];for(var s of r){var o,a,l=i[s],u=e?.[s],c=C(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=C(u)?l?.variant:typeof u=="string"?u:void 0,h=n?.[s],f=I({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(f.original_enabled=l?.enabled),d!==l?.variant&&(f.original_variant=l?.variant),h&&(f.metadata=I({},l?.metadata,{payload:h,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),i[s]=f}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:n,finalDetails:i}),this.ca=!0),i}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((n=>{var i=t[n];return{key:n,enabled:hc(i),variant:pc(i),payload:fc(e[n])}}))}getFlagVariants(){var t=this.Oa(Sn),e=this.Oa(It);if(!e)return t||{};for(var n=fe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:e,finalFlags:n}),this.ca=!0),n}getFlagPayloads(){var t=this.Oa($i),e=this.Oa(xn);if(!e)return t||{};for(var n=fe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flag payloads!",{flagPayloads:t,overriddenPayloads:e,finalPayloads:n}),this.ca=!0),n}reloadFeatureFlags(){this._a||this.Ne.featureFlagsDisabled||this.Ma()||this.Ba||(this.ga.slice().forEach((t=>{try{t()}catch(e){this.rt.error("Error while running feature flags reloading callback",e)}})),this.Ba=setTimeout((()=>{this.Ha()}),5))}La(){clearTimeout(this.Ba),this.Ba=void 0}onReloading(t){return this.ga.push(t),()=>{this.ga=this.ga.filter((e=>e!==t))}}ensureFlagsLoaded(){this.ma||this.ya||this.Ba||this.reloadFeatureFlags()}setAnonymousDistinctId(t){this.$anon_distinct_id=t}setReloadingPaused(t){this._a=t}resetFlagCallReported(){this.q(Cn)}Ha(t){this.La();var e=this.nn;if(e&&!this.Ne.remoteRequestsDisabled&&!this.Ma())if(this.ya)this.wa=!0;else{var n={token:e.projectToken,distinct_id:e.distinctId,groups:e.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:I({},e.initialPersonProperties,this.Oa(jt)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(In),timezone:Cf()};C(e.deviceId)||(n.$device_id=e.deviceId),(t!=null&&t.disableFlags||this.Ne.featureFlagsDisabled)&&(n.disable_flags=!0);var i=this.Na();i.length&&(n.evaluation_contexts=i);var r=this.qa();C(r)||(n.flag_keys=r);var s=this.Ne.onlyEvaluateSurveyFeatureFlags,o="/flags/?v=2"+(s?"&only_evaluate_survey_feature_flags=true":""),a=this.ba;this.ya=!0;var l=()=>{this.wa&&(this.wa=!1,this.Ha())},u=c=>{this.ya=!1,a===this.ba&&(this.F({[Tr]:[mu]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:n,compression:this.Ne.compression==="base64"?Ue.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,h,f=(d=c.json)!==null&&d!==void 0?d:{},p=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),p||this.wa||(this.$anon_distinct_id=void 0),!n.disable_flags||this.wa){this.ka=!p;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?mu:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),f.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((h=f.quotaLimited)==null||!h.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[Tr]:g}),m?this.rt.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more."):n.disable_flags||this.ja(f,p,{partialResponse:s}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return yf(this.Sa,3)}Ua(t){this.Sa=wf(t,this.Sa,3,(()=>this.rt.warn("Feature flag requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped refreshing feature flags; will try again when connectivity changes.")))}getFeatureFlag(t,e){var n;if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var i=this.getFeatureFlagResult(t,e);return(n=i?.variant)!==null&&n!==void 0?n:i?.enabled}}else this.rt.warn('getFeatureFlag for key "'+t+Bo)}getFeatureFlagDetails(t){return this.getFlagsWithDetails()[t]}getFeatureFlagPayload(t){var e=this.getFeatureFlagResult(t,{send_event:!1});return e?.payload}getFeatureFlagResult(t,e){if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var n,i=this.getFlagVariants(),r=t in i,s=i[t],o=this.getFlagPayloads()[t],a=String(s),l=this.Oa(Pr)||void 0,u=this.Oa(ji)||void 0,c=this.Oa(Cn)||{};if(this.Ne.deduplicateCallsPerSession){var d,h=(d=this.nn)==null?void 0:d.session.sessionId,f=this.Oa(Li);h&&h!==f&&(c={},n=h)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))n&&this.F({[Cn]:c,[Li]:n});else{var p,g,m,v,E,S,_,b,k,T;U(c[t])?c[t].push(a):c[t]=[a],this.F(I({[Cn]:c},n?{[Li]:n}:{}));var x=this.getFeatureFlagDetails(t),F=[...(p=this.Oa(Tr))!==null&&p!==void 0?p:[]];C(s)&&F.push("flag_missing");var $={$feature_flag:t,$feature_flag_response:s,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((g=this.Ne.bootstrap)==null||(g=g.featureFlags)==null?void 0:g[t])||null,$feature_flag_bootstrapped_payload:((m=this.Ne.bootstrap)==null||(m=m.featureFlagPayloads)==null?void 0:m[t])||null,$used_bootstrap_value:!this.ka};C(x==null||(v=x.metadata)==null?void 0:v.has_experiment)||($.$feature_flag_has_experiment=x.metadata.has_experiment),C(x==null||(E=x.metadata)==null?void 0:E.version)||($.$feature_flag_version=x.metadata.version);var O,L=(S=x==null||(_=x.reason)==null?void 0:_.description)!==null&&S!==void 0?S:x==null||(b=x.reason)==null?void 0:b.code;L&&($.$feature_flag_reason=L),x!=null&&(k=x.metadata)!=null&&k.id&&($.$feature_flag_id=x.metadata.id),C(x?.original_variant)&&C(x?.original_enabled)||($.$feature_flag_original_response=C(x.original_variant)?x.original_enabled:x.original_variant),x!=null&&(T=x.metadata)!=null&&T.original_payload&&($.$feature_flag_original_payload=x==null||(O=x.metadata)==null?void 0:O.original_payload),F.length&&($.$feature_flag_error=F.join(",")),this.za($)}else n&&this.F({[Cn]:c,[Li]:n});if(r)return{key:t,enabled:!!s,variant:typeof s=="string"?s:void 0,payload:fc(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+Bo)}za(t){try{var e;(e=this.nn)==null||e.capture("$feature_flag_called",t).catch((n=>{this.rt.error("Failed to capture feature flag call",n)}))}catch(n){this.rt.error("Failed to capture feature flag call",n)}}getRemoteConfigPayload(t,e){this.Wa(t,e)}Wa(t,e){var n=this;return se((function*(){var i=n.nn;if(i){var r={distinct_id:i.distinctId,token:i.projectToken,person_properties:{$lib:i.library.name,$lib_version:i.library.version}},s=n.Na();s.length&&(r.evaluation_contexts=s);var o,a=n.qa();C(a)||(r.flag_keys=a);try{var l,u=(l=(yield i.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:r,compression:n.Ne.compression==="base64"?Ue.Base64:void 0,sentAt:"body",timeoutMs:n.Ne.requestTimeoutMs})).json)==null?void 0:l.featureFlagPayloads;o=u?.[t]||void 0}catch(c){return void n.rt.error("Remote config feature flag request failed",c)}try{e(o)}catch(c){n.rt.error("Remote config feature flag callback failed",c)}}}))()}isFeatureEnabled(t,e){if(e===void 0&&(e={}),e.fresh&&!this.ka)return e.defaultValue;if(!(this.ma||this.getFlags()&&this.getFlags().length>0))return this.rt.warn('isFeatureEnabled for key "'+t+Bo),e.defaultValue;var n=this.getFeatureFlag(t,e);return C(n)?e.defaultValue:!!n}addFeatureFlagsHandler(t){this.featureFlagEventHandlers.push(t)}removeFeatureFlagsHandler(t){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((e=>e!==t))}receivedFeatureFlags(t,e,n){this.ja(t,e,n)}ja(t,e,n){if(this.nn){this.ma=!0;var i=(function(r,s,o,a,l,u){s===void 0&&(s={}),o===void 0&&(o={}),a===void 0&&(a={}),u===void 0&&(u=gu);var c=((k,T)=>{var x=k.flags;return x?I({},k,{featureFlags:Object.fromEntries(Object.keys(x).map((F=>{var $;return[F,($=x[F].variant)!==null&&$!==void 0?$:x[F].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(x).filter((F=>x[F].enabled)).filter((F=>{var $;return($=x[F].metadata)==null?void 0:$.payload})).map((F=>{var $;return[F,($=x[F].metadata)==null?void 0:$.payload]})))}):(k.featureFlags&&T.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),k)})(r,u),d=c.flags,h=c.featureFlags,f=c.featureFlagPayloads;if(h){var p=r.requestId,g=r.evaluatedAt;if(U(h)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(h)for(var v=0;h.length>v;v++)m[h[v]]=!0;return{[Ti]:h,[Sn]:m,[Zr]:!1}}var E=h,S=f,_=d;if(l!=null&&l.partialResponse)E=I({},s,E),S=I({},o,S),_=I({},a,_);else if(r.errorsWhileComputingFlags)if(d){var b=new Set(Object.keys(d).filter((k=>{var T;return!((T=d[k])!=null&&T.failed)})));E=I({},s,Object.fromEntries(Object.entries(E).filter((k=>b.has(k[0]))))),S=I({},o,Object.fromEntries(Object.entries(S||{}).filter((k=>b.has(k[0]))))),_=I({},a,Object.fromEntries(Object.entries(_||{}).filter((k=>b.has(k[0])))))}else E=I({},s,E),S=I({},o,S),_=I({},a,_);return I({[Ti]:Object.keys(_u(E)),[Sn]:E||{},[$i]:S||{},[aa]:_||{},[Zr]:r.minimalFlagCalledEvents===!0},p?{[Pr]:p}:{},g?{[ji]:g}:{})}})(t,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),n,this.rt);i&&this.F(i),e||(this.xa=!1),this.Va(e)}}override(t,e){e===void 0&&(e=!1),this.rt.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:t,suppressWarning:e})}overrideFeatureFlags(t){this.Za(t)}Za(t){if(this.nn){if(t===!1)return this.q([It,xn]),this.Va(),void bn.info("All overrides cleared");if(U(t))return this.F({[It]:vu(t)}),this.Va(),void bn.info("Flag overrides set",{flags:t});if(t&&typeof t=="object"&&("flags"in t||"payloads"in t)){var e,n=t;this.ca=!!((e=n.suppressWarning)!==null&&e!==void 0&&e);var i={},r=n.flags,s=n.payloads;return r&&(i[It]=U(r)?vu(r):r),s&&(i[xn]=s),Object.keys(i).length&&this.F(i),r===!1&&s===!1?this.q([It,xn]):r===!1?this.q(It):s===!1&&this.q(xn),this.Va(),r===!1?bn.info("Flag overrides cleared"):r&&bn.info("Flag overrides set",{flags:r}),void(s===!1?bn.info("Payload overrides cleared"):s&&bn.info("Payload overrides set",{payloads:s}))}if(t&&typeof t=="object")return this.F({[It]:t}),this.Va(),void bn.info("Flag overrides set",{flags:t});this.rt.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:t})}else this.rt.warn("posthog.featureFlags.overrideFeatureFlags called before feature flags were ready")}onFeatureFlags(t){if(this.addFeatureFlagsHandler(t),this.ma){var e=this.Ga(),n=e.flags,i=e.flagVariants;try{t(n,i)}catch(r){this.rt.error("Error while running feature flags callback",r)}}return()=>this.removeFeatureFlagsHandler(t)}updateEarlyAccessFeatureEnrollment(t,e,n){var i=(this.Oa(Ar)||[]).find((l=>l.flagKey===t)),r={["$feature_enrollment/"+t]:e},s={$feature_flag:t,$feature_enrollment:e,$set:r};i&&(s.$early_access_feature_name=i.name),n&&(s.$feature_enrollment_stage=n);var o=I({},this.getFlagVariants(),{[t]:e});this.F({[Ti]:Object.keys(_u(o)),[Sn]:o,[jt]:I({},this.Oa(jt)||{},r)}),this.Va();try{var a;(a=this.nn)==null||a.capture("$feature_enrollment_update",s).catch((l=>{this.rt.error("Failed to capture early access feature enrollment",l)}))}catch(l){this.rt.error("Failed to capture early access feature enrollment",l)}}getEarlyAccessFeatures(t,e,n){e===void 0&&(e=!1);var i=this.Oa(Ar);!i||e?this.Qa(t,n):t(i)}Qa(t,e){var n=this;return se((function*(){var i=n.nn;if(i){var r,s=e?"&"+e.map((a=>"stage="+a)).join("&"):"";try{var o=yield i.sendRequest("/api/early_access_features/?token="+i.projectToken+s,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;n.F({[Ar]:r=o.json.earlyAccessFeatures})}catch(a){return void n.rt.error("Early access feature request failed",a)}try{t(r)}catch(a){n.rt.error("Early access feature callback failed",a)}}}))()}Ga(){var t=this.getFlags(),e=this.getFlagVariants();return{flags:t.filter((n=>e[n])),flagVariants:Object.keys(e).filter((n=>e[n])).reduce(((n,i)=>(n[i]=e[i],n)),{})}}Va(t){this.Fa();var e=this.Ga(),n=e.flags,i=e.flagVariants;this.featureFlagEventHandlers.forEach((r=>{try{r(n,i,{errorsLoading:t})}catch(s){this.rt.error("Error while running feature flags callback",s)}}))}setPersonPropertiesForFlags(t,e){e===void 0&&(e=!0),this.Ka(t,e)}Ka(t,e){e===void 0&&(e=!0);var n=this.Oa(jt)||{},i=t?.$set||(t!=null&&t.$set_once?{}:t),r=t?.$set_once,s={};if(r)for(var o in r)({}).hasOwnProperty.call(r,o)&&(o in n||(s[o]=r[o]));this.F({[jt]:I({},n,s,i)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=I({},this.Oa(jt)||{});t.forEach((i=>{delete n[i]})),this.F({[jt]:n}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(jt),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=this.Oa(In)||{},i=I({},n);for(var r of Object.keys(t))i[r]=I({},n[r],t[r]);this.F({[In]:i}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(In)||{};this.F({[In]:I({},e,{[t]:{}})})}else this.q(In)}reset(){this.ba++,this.wa=!1,this.Fa(),this.ma=!1,this._a=!1,this.ka=!1,this.$anon_distinct_id=void 0,this.La(),this.ca=!1,this.Sa=0}}},qm={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===ki||this.Ya===Sr?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=lu,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(P==null||!P.visibilityState||P.visibilityState==="visible")return!0;var n=w==null||(e=w.performance)==null||e.getEntriesByType==null?void 0:e.getEntriesByType("visibility-state");return!(n!=null&&n.length)||n.some((i=>i.name==="visible"))})(),this.Ie=()=>{var e;P?.visibilityState==="visible"&&(this.io=!0,(e=this.Ja)==null||e.setDocumentWasEverVisible==null||e.setDocumentWasEverVisible(!0))},this._instance=t,!this._instance.sessionManager)throw Bt.error("started without valid sessionManager"),new Error(Ia+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===Wt)throw new Error(Ia+' cannot be used with cookieless_mode="always"');P!=null&&P.addEventListener&&ve(P,"visibilitychange",this.Ie)}initialize(){this.startIfEnabledOrStop()}dispose(){this.eo=!0,P==null||P.removeEventListener==null||P.removeEventListener("visibilitychange",this.Ie),this.stopRecording()}get ro(){var t,e=!((t=this._instance.get_property(An))==null||!t.enabled),n=!this.Ne.disable_session_recording,i=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return w&&e&&n&&!i}startIfEnabledOrStop(t){var e;if(!(this.eo||this.ro&&(e=this.Ja)!=null&&e.isStarted)){var n=!C(Object.assign)&&!C(Array.from);this.ro&&n?(this.no(t),Bt.info("starting")):(this.Ya=lu,this.stopRecording())}}no(t){var e,n,i;this.ro&&(this.Ya!==ki&&this.Ya!==Sr&&(this.Ya=cu),B!=null&&(e=B.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(n=B.__PosthogExtensions__)!=null&&n.initSessionRecording?this.so(t):(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,this.ao,(r=>{if(r)return Bt.error("could not load recorder",r);this.so(t)})))}stopRecording(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.stop()}oo(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.discard()}lo(){var t,e;(t=this.Mr)==null||t.unregister(ol),(e=this.Mr)==null||e.unregister(Kd)}uo(t,e){if(H(t))return null;var n,i=ke(t)?t:parseFloat(t);return typeof(n=i)!="number"||!Number.isFinite(n)||0>n||n>1?(Bt.warn(e+" must be between 0 and 1. Ignoring invalid value:",t),null):i}ho(t){if(this.Mr){var e,n,i=this.Mr,r=()=>{var s,o=t.sessionRecording===!1?void 0:t.sessionRecording,a=this.uo((s=this.Ne.session_recording)==null?void 0:s.sampleRate,"session_recording.sampleRate"),l=this.uo(o?.sampleRate,"remote config sampleRate"),u=a??l;H(u)&&this.lo();var c=o?.minimumDurationMilliseconds;i.register({[An]:I({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:I({capturePerformance:t.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:u,minimumDurationMilliseconds:C(c)?null:c,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers,version:o?.version,triggerGroups:o?.triggerGroups})})};r(),(e=this.Xa)==null||e.call(this),this.Xa=(n=this._instance.sessionManager)==null?void 0:n.onSessionId(r)}}onRemoteConfig(t){var e=t.ok?t.config:void 0;return e&&"sessionRecording"in e?e.sessionRecording===!1?(this.ho(e),void this.oo()):(this.ho(e),void this.startIfEnabledOrStop()):(this.Ya===ki&&(this.Ya=Sr,Bt.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(t,e){var n;e===void 0&&(e="log"),(n=this.Ja)!=null&&n.log?this.Ja.log(t,e):Bt.warn("log called before recorder was ready")}get ao(){var t,e,n=(t=this._instance)==null||(t=t.persistence)==null?void 0:t.get_property(An);return(n==null||(e=n.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(An);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(n){return Bt.warn("persisted remote config for session recording is invalid and will be ignored",n),!1}return!H(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,n,i;if(!this.eo){if((e=B.__PosthogExtensions__)==null||!e.initSessionRecording)return Bt.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[nf]:!0});var r;if(this.Ja||(this.Ja=(r=B.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===Sr||this.Ya===ki?void 0:(this.Ya=ki,Bt.info("persisted remote config is stale, requesting fresh config before starting"),void new Af(this._instance).load());this.Ya=cu,(n=(i=this.Ja).setDocumentWasEverVisible)==null||n.call(i,this.io),this.Ja.start(t)}}onRRwebEmit(t){var e;(e=this.Ja)==null||e.onRRwebEmit==null||e.onRRwebEmit(t)}overrideLinkedFlag(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Jd]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Yd]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,n;this.Ja||(n=this.Mr)==null||n.register({[t==="url"?Zd:Xd]:!0}),(e=this.Ja)==null||e.overrideTrigger(t)}get sdkDebugProperties(){var t;return((t=this.Ja)==null?void 0:t.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(t,e){var n;return!((n=this.Ja)==null||!n.tryAddCustomEvent(t,e))}}},Vm={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new su(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,n=he(this.instance.config.autocapture)?this.instance.config.autocapture:{};return n.url_allowlist=(t=n.url_allowlist)==null?void 0:t.map((i=>new RegExp(i))),n.url_ignorelist=(e=n.url_ignorelist)==null?void 0:e.map((i=>new RegExp(i))),n}yo(){if(this.isBrowserSupported()){if(w&&P){var t=n=>{n=n||w?.event;try{this.bo(n)}catch(i){Mo.error("Failed to capture event",i)}};if(ve(P,"submit",t,{capture:!0}),ve(P,"change",t,{capture:!0}),ve(P,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=n=>{n=n||w?.event;try{this.bo(n,$o)}catch(i){Mo.error("Failed to capture copy/cut event",i)}};ve(P,"copy",e,{capture:!0}),ve(P,"cut",e,{capture:!0})}}}else Mo.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.vo&&(this.yo(),this.vo=!0)}onRemoteConfig(t){if(this.fo=!0,t.ok){var e=t.config;e.elementsChainAsString&&(this.po=e.elementsChainAsString);var n=e.autocapture_opt_out;mt(n)&&(this.instance.persistence&&this.instance.persistence.register({[ea]:n}),this.co=n),this.startIfEnabled()}else this.startIfEnabled()}setElementSelectors(t){this.mo=t}getElementSelectors(t){var e,n=[];return(e=this.mo)==null||e.forEach((i=>{var r=P?.querySelectorAll(i);r?.forEach((s=>{t===s&&n.push(i)}))})),n}get isEnabled(){var t,e,n=(t=this.instance.persistence)==null?void 0:t.props[ea],i=this.co,r=this.instance.Qi()&&!this.fo;if(Ye(i)&&!mt(n)&&!r)return!1;var s=(e=this.co)!==null&&e!==void 0?e:!!n;return!!this.instance.config.autocapture&&!s}bo(t,e){if(e===void 0&&(e="$autocapture"),this.isEnabled){var n,i=bo(t);lf(i)&&(i=i.parentNode||null),e==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&this.instance.config.rageclick&&(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,t.timeStamp||new Date().getTime())&&Lc(i,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var r=e===$o;if(i&&(function(d,h,f,p,g,m){var v;if(!w||dl(d)||f!=null&&f.url_allowlist&&!Tc(f.url_allowlist,m)||f!=null&&f.url_ignorelist&&Tc(f.url_ignorelist,m))return!1;if(f!=null&&f.dom_event_allowlist){var E=f.dom_event_allowlist;if(E&&!E.some((x=>h.type===x)))return!1}var S=pf(d,p),_=S.parentIsUsefulElement,b=S.targetElementList;if(!(function(x,F){var $=F?.element_allowlist;if(C($))return!0;var O,L=function(K){if($.some((V=>K.tagName.toLowerCase()===V)))return{v:!0}};for(var N of x)if(O=L(N))return O.v;return!1})(b,f)||!ma(b,f?.css_selector_allowlist)||ma(b,(v=f?.css_selector_ignorelist)!==null&&v!==void 0?v:Wg))return!1;try{var k=w.getComputedStyle(d);if(k&&k.getPropertyValue("cursor")==="pointer"&&h.type==="click")return!0}catch{}var T=d.tagName.toLowerCase();switch(T){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 _?(g||["click"]).indexOf(h.type)>=0:(g||["click"]).indexOf(h.type)>=0&&(ul.indexOf(T)>-1||d.getAttribute("contenteditable")==="true")}})(i,t,this.Ne,r,r?["copy","cut"]:void 0,this.instance)){var s=Lm(i,{e:t,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.Ne.element_attribute_ignorelist,elementsChainAsString:this.po,disableCaptureUrlHashes:this.instance.config.disable_capture_url_hashes}),o=s.props;if(s.explicitNoCapture)return!1;var a=this.getElementSelectors(i);if(a&&a.length>0&&(o.$element_selectors=a),e===$o){var l,u=df(w==null||(l=w.getSelection())==null?void 0:l.toString()),c=t.type||"clipboard";if(!u)return!1;o.$selected_content=u,o.$copy_type=c}return this.instance.capture(e,o),!0}}}isBrowserSupported(){return je(P?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(w==null||(e=w.location)==null?void 0:e.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(A.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.wo&&this.wo(),this.wo=void 0,A.info("History API monitoring stopped")}monitorHistoryChanges(){w&&w.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(w&&((e=w.history[t])==null||!e.__posthog_wrapped__)){var n=this;(function(i,r,s){try{if(!(r in i))return ou;var o={next:i[r]},a=s((function(){for(var l=arguments.length,u=new Array(l),c=0;l>c;c++)u[c]=arguments[c];return o.next.apply(this,u)}));return je(a)&&(a.prototype=a.prototype||{},Object.defineProperties(a,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:o}})),i[r]=a,()=>{if(i[r]!==a)for(var l=i[r];je(l)&&l.__posthog_layer__;){var u=l.__posthog_layer__;if(u.next===a)return void(u.next=o.next);l=u.next}else i[r]=o.next}}catch{return ou}})(w.history,t,(i=>function(r,s,o){i.call(this,r,s,o),n.So(t)}))}}So(t){try{var e,n=w==null||(e=w.location)==null?void 0:e.pathname;if(!n)return;n!==this._o&&this.isEnabled&&this._instance.capture(Vn,{navigation_type:t}),this._o=n}catch(i){A.error("Error capturing "+t+" pageview",i)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};ve(w,"popstate",t),this.wo=()=>{w&&w.removeEventListener("popstate",t)}}}},heatmaps:class{get Ne(){return this.instance.config}constructor(t){var e;this.Co=!1,this.vo=!1,this.Mo=null,this.instance=t,this.Co=!((e=this.instance.persistence)==null||!e.props[ta]),this.rageclicks=new su(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return he(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return H(this.Ne.capture_heatmaps)?H(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;Om.info("starting..."),this.To(),this.Ie()}else{var t;clearInterval((t=this.Mo)!==null&&t!==void 0?t:void 0),this.Eo(),this.getAndClearBuffer()}}onRemoteConfig(t){if(t.ok){var e=t.config;if("heatmaps"in e){var n=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[ta]:n}),this.Co=n,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){No(t.originalEvent)&&this.ke(t.originalEvent,"deadclick")}Ie(){this.Mo&&clearInterval(this.Mo),this.Mo=P?.visibilityState==="visible"?setInterval(this.cr.bind(this),this.flushIntervalMilliseconds):null}To(){w&&P&&(this.Po=this.cr.bind(this),ve(w,ns,this.Po),this.Ro=t=>this.ke(t||w?.event),ve(P,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||w?.event),ve(P,"mousemove",this.Ao,{capture:!0}),this.Lo=new Hc(this.instance,Jg,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),ve(P,ts,this.Oo),this.vo=!0)}Eo(){var t;w&&P&&(this.Po&&w.removeEventListener(ns,this.Po),this.Ro&&P.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&P.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&P.removeEventListener(ts,this.Oo),clearTimeout(this.Do),(t=this.Lo)==null||t.stop(),this.vo=!1)}$o(t,e){var n=this.instance.scrollManager.scrollY(),i=this.instance.scrollManager.scrollX(),r=this.instance.scrollManager.scrollElement(),s=(function(o,a,l){for(var u=o;u&&hn(u)&&!et(u,"body");){if(u===l)return!1;var c=void 0;try{var d,h,f;c=(d=(h=(f=u.ownerDocument)==null?void 0:f.defaultView)!==null&&h!==void 0?h:w)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(j(a,c))return!0;u=ff(u)}return!1})(bo(t),["fixed","sticky"],r);return{x:t.clientX+(s?0:i),y:t.clientY+(s?0:n),target_fixed:s,type:e}}ke(t,e){var n;if(e===void 0&&(e="click"),!Rc(t.target)&&No(t)){var i=this.$o(t,e);(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,new Date().getTime())&&Lc(bo(t),this.instance.config.rageclick)&&this.Vt(I({},i,{type:"rageclick"})),this.Vt(i)}}Fo(t){!Rc(t.target)&&No(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(w){var e=this.Ne.disable_capture_url_hashes?fn(w.location.href):w.location.href,n=this.Ne.custom_personal_data_properties,i=this.Ne.mask_personal_data_properties?[...ri,...n||[]]:[],r=Zi(e,i,Xi);this.R=this.R||{},this.R[r]||(this.R[r]=[]),this.R[r].push(t)}}cr(){this.R&&!Kt(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:Hc,webVitalsAutocapture:class{constructor(t){var e;this.Co=!1,this.vo=!1,this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this.No=()=>{clearTimeout(this.qo),this.qo=void 0,this.R.metrics.length!==0&&(this._instance.capture("$web_vitals",I({$current_url:this.R.url},this.R.metrics.reduce(((n,i)=>I({},n,{["$web_vitals_"+i.name+"_event"]:I({},i),["$web_vitals_"+i.name+"_value"]:i.value})),{}))),this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.jo=n=>{var i;if(this.R=this.R||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},H(n?.name)||H(n?.value))wn.error("Invalid metric received",n);else{var r=typeof n.navigationURL=="string"?n.navigationURL:void 0,s=this.Bo(r);if(!C(s)){var o=ke(n.navigationId)||typeof n.navigationId=="string"?"navigation:"+n.navigationId:"url:"+s;if(!this.Ho||this.Ho>n.value){this.R.navigationKey!==o&&(this.No(),this.qo=setTimeout(this.No,this.flushToCaptureTimeoutMs)),C(this.R.navigationKey)&&(this.R.navigationKey=o,this.R.url=s),this.R.firstMetricTimestamp=C(this.R.firstMetricTimestamp)?Date.now():this.R.firstMetricTimestamp,n.attribution&&n.attribution.interactionTargetElement&&(n.attribution.interactionTargetElement=void 0);var a=(i=this._instance.sessionManager)==null?void 0:i.checkAndGetSessionAndWindowId(!0),l=I({},n,r?{navigationURL:s}:{},{$current_url:s,timestamp:Date.now()});C(a)||(l.$session_id=a.sessionId,l.$window_id=a.windowId),this.R.metrics.push(l),this.R.metrics.length===this.allowedMetrics.length&&this.No()}else wn.error("Ignoring metric with value >= "+this.Ho,n)}}},this.Uo=()=>{if(!this.vo){var n,i,r,s,o=B.__PosthogExtensions__,a=o?.postHogWebVitalsCallbacksByFlavor,l=a?.[this.zo]||(this.zo==="web-vitals"&&C(a)?o?.postHogWebVitalsCallbacks:void 0);if(C(l)||(n=l.onLCP,i=l.onCLS,r=l.onFCP,s=l.onINP),n&&i&&r&&s){var u={reportSoftNavs:this.useSoftNavs};this.allowedMetrics.indexOf("LCP")>-1&&n(this.jo.bind(this),u),this.allowedMetrics.indexOf("CLS")>-1&&i(this.jo.bind(this),u),this.allowedMetrics.indexOf("FCP")>-1&&r(this.jo.bind(this),u),this.allowedMetrics.indexOf("INP")>-1&&s(this.jo.bind(this),u),this.vo=!0}else wn.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[sa]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,n=he(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return H(n)?((e=this._instance.persistence)==null?void 0:e.props[oa])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(he(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=he(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=he(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=he(this.Wo)&&ke(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:au;return t>0&&6e4>=t?au:t}get isEnabled(){var t=me?.protocol;if(t!=="http:"&&t!=="https:")return wn.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=he(this.Wo)?this.Wo.web_vitals:mt(this.Wo)?this.Wo:void 0;return mt(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(wn.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var n=he(e.capturePerformance)&&!!e.capturePerformance.web_vitals,i=he(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[sa]:n}),this._instance.persistence.register({[oa]:i})),this.Co=n,this.startIfEnabled()}}}get zo(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}ai(t){var e=B.__PosthogExtensions__,n=this.zo,i=e?.postHogWebVitalsCallbacksByFlavor;i!=null&&i[n]||n==="web-vitals"&&C(i)&&e!=null&&e.postHogWebVitalsCallbacks?t():e==null||e.loadExternalDependency==null||e.loadExternalDependency(this._instance,n,(r=>{r?wn.error("failed to load script",r):t()}))}Bo(t){var e=t||w?.location.href;if(e){var n=this._instance.config.disable_capture_url_hashes?fn(e):e,i=this._instance.config.custom_personal_data_properties,r=this._instance.config.mask_personal_data_properties?[...ri,...i||[]]:[];return Zi(n,r,Xi)}wn.error("Could not determine current URL")}}},Gm={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var n;if(w&&this.isEnabled&&(n=B.__PosthogExtensions__)!=null&&n.errorWrappingFunctions){var i=B.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,r=B.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,s=B.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.Vo&&this.Ne.capture_unhandled_errors&&(this.Vo=i(this.captureException.bind(this))),!this.Zo&&this.Ne.capture_unhandled_rejections&&(this.Zo=r(this.captureException.bind(this))),!this.Go&&this.Ne.capture_console_errors&&(this.Go=s(this.captureException.bind(this)))}catch(o){Ii.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[na]),this.Jo=new qp(I({},(function(n){var i,r,s,o;return n===void 0&&(n={}),{refillRate:(i=(r=n.exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:n.__exceptionRateLimiterRefillRate)!==null&&i!==void 0?i:1,bucketSize:(s=(o=n.exceptionRateLimiterBucketSize)!==null&&o!==void 0?o:n.__exceptionRateLimiterBucketSize)!==null&&s!==void 0?s:10}})(this._instance.config.error_tracking),{refillInterval:1e4,rt:Ii})),this.Ne=this.Yo(),this.startIfEnabledOrStop()}Yo(){var t=this._instance.config.capture_exceptions,e={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return he(t)?e=I({},e,t):(C(t)?this.Ko:t)&&(e=I({},e,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),e}get isEnabled(){return this.Ne.capture_console_errors||this.Ne.capture_unhandled_errors||this.Ne.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(Ii.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",(i=>{if(i)return Ii.error("failed to load script",i);t()}))}Qo(){var t,e,n;(t=this.Vo)==null||t.call(this),this.Vo=void 0,(e=this.Zo)==null||e.call(this),this.Zo=void 0,(n=this.Go)==null||n.call(this),this.Go=void 0}onRemoteConfig(t){if(t.ok){var e=t.config;"autocaptureExceptions"in e&&(this.Ko=!!e.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[na]:this.Ko}),this.Ne=this.Yo(),this.startIfEnabledOrStop())}}onConfigChange(){this.Ne=this.Yo()}captureException(t){var e,n,i,r=(e=t==null||(n=t.$exception_list)==null||(n=n[0])==null?void 0:n.type)!==null&&e!==void 0?e:"Exception";this.Jo.consumeRateLimit(r)?Ii.info("Skipping exception capture because of client rate limiting.",{exception:r}):(i=this._instance.exceptions)==null||i.sendExceptionEvent(t)}},exceptions:class{constructor(t){var e,n;this.Xo=[],this.tl=new lg([new mg,new Ig,new _g,new vg,new Sg,new Eg,new wg,new xg],(function(i){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;r>o;o++)s[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` -`),d=l;c.length>d;d++){var h=c[d];if(1024>=h.length){var f=Cc.test(h)?h.replace(Cc,"$1"):h;if(!f.match(/\S*Error: /)){for(var p of s){var g=p(f,i);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var v=Array.from(m);return v.reverse(),v.slice(0,50).map((E=>{return I({},E,{filename:E.filename||(S=v,S[S.length-1]||{}).filename,function:E.function||ni});var S}))})(u)}})("web:javascript",fg,gg)),this._instance=t,this.Xo=(e=(n=this._instance.persistence)==null?void 0:n.get_property(ia))!==null&&e!==void 0?e:[],this.el=Jr(this.il()),this.rl=new Cg(this.el)}onConfigChange(){this.el=Jr(this.il()),this.rl.setConfig(this.el)}onRemoteConfig(t){var e,n,i;if(t.ok){var r=t.config;if("errorTracking"in r){var s=(e=(n=r.errorTracking)==null?void 0:n.suppressionRules)!==null&&e!==void 0?e:[],o=(i=r.errorTracking)==null?void 0:i.captureExtensionExceptions;this.Xo=s,this._instance.persistence&&this._instance.persistence.register({[ia]:this.Xo,[ra]:o})}}}get nl(){var t,e=!!this._instance.get_property(ra),n=this._instance.config.error_tracking.captureExtensionExceptions;return(t=n??e)!==null&&t!==void 0&&t}buildProperties(t,e){return this.tl.buildFromUnknown(t,{syntheticException:e?.syntheticException,mechanism:{handled:e?.handled}})}addExceptionStep(t,e){if(this.el.enabled)try{if(!X(t)||t.trim().length===0)return void St.warn("Ignoring exception step because message must be a non-empty string");var n=(function(s){if(!s)return{sanitizedProperties:{},droppedKeys:[]};var o=[];return{sanitizedProperties:Object.keys(s).reduce(((a,l)=>kg.has(l)?(o.push(l),a):(a[l]=s[l],a)),{}),droppedKeys:o}})(this.sl(e)),i=n.sanitizedProperties,r=n.droppedKeys;r.length>0&&St.warn("Ignoring reserved exception step fields",{droppedKeys:r}),this.rl.add(I({[Kr]:t,[Yr]:new Date().toISOString()},i))}catch(s){St.error("Failed to add exception step. Ignoring breadcrumb.",s)}}sendExceptionEvent(t){try{var e=t.$exception_list;if(this.al(e)){if(this.ol(e))return this.ll("Exception dropped: matched a suppression rule"),void St.info("Skipping exception capture because a suppression rule matched");if(!this.nl&&this.ul(e))return this.ll("Exception dropped: thrown by a browser extension"),void St.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.hl(e))return this.ll("Exception dropped: thrown by the PostHog SDK"),void St.info("Skipping exception capture because it was thrown by the PostHog SDK")}var n=this.el.enabled&&H(t.$exception_steps)?this.dl(t):t,i=typeof(s=globalThis._posthogReleaseId)=="string"&&s.length>0?s:void 0;i&&(n.$release_id=i);try{var r=this._instance.capture("$exception",n,{_noTruncate:!0,_batchKey:"exceptionEvent",Wn:!0});return r&&this.rl.clear(),r}catch(o){return St.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void St.error("Failed to process exception event. Ignoring this exception.",o)}var s}dl(t){try{var e=this.rl.getAttachable();return e.length===0?t:I({},t,{$exception_steps:e})}catch(n){return St.error("Failed to read buffered exception steps. Capturing exception without steps.",n),t}}ll(t){this.el.enabled&&this.rl.add({[Kr]:t,[Yr]:new Date().toISOString()})}sl(t){return he(t)?I({},t):{}}il(){var t,e;return(t=(e=this._instance.config.error_tracking)==null?void 0:e.exception_steps)!==null&&t!==void 0?t:{}}ol(t){if(t.length===0)return!1;try{var e=t.reduce(((n,i)=>{var r=i.type,s=i.value;return X(r)&&r.length>0&&n.$exception_types.push(r),X(s)&&s.length>0&&n.$exception_values.push(s),n}),{$exception_types:[],$exception_values:[]});return this.Xo.some((n=>{var i=n.values.map((r=>{var s=Hf[r.operator],o=e[r.key];if(!s||!o)return!1;var a=U(r.value)?r.value:[r.value];return a.length>0&&s(a,o)}));return n.type==="OR"?i.some(Boolean):i.every(Boolean)}))}catch(n){return St.warn("Failed to evaluate suppression rules. Capturing the exception.",n),!1}}ul(t){return t.flatMap((e=>{var n,i;return(n=(i=e.stacktrace)==null?void 0:i.frames)!==null&&n!==void 0?n:[]})).some((e=>e.filename&&e.filename.startsWith("chrome-extension://")))}hl(t){if(t.length>0){var e,n,i,r,s=(e=(n=t[0].stacktrace)==null?void 0:n.frames)!==null&&e!==void 0?e:[],o=s[s.length-1];return(i=o==null||(r=o.filename)==null?void 0:r.includes("posthog.com/static"))!==null&&i!==void 0&&i}return!1}al(t){return!H(t)&&U(t)}}},Km=I({productTours:class{get Mr(){return this._instance.persistence}constructor(t){this.vl=null,this.cl=null,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(t.ok){var e=t.config;if("productTours"in e){var n,i;if(this.Mr&&this.Mr.register({[sl]:!!e.productTours}),!Oo(this._instance))return!this.vl&&H((n=this.Mr)==null?void 0:n.props[Mi])||xr.info("product tours disabled; stopping and clearing cached tours"),(i=this.vl)==null||i.stop(),this.vl=null,void this.clearCache();this.loadIfEnabled()}}}loadIfEnabled(){!this.vl&&Oo(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.generateProductTours?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",(i=>{i?xr.error("Could not load product tours script",i):t()}))}fl(){var t;!this.vl&&(t=B.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=B.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(t,e){if(e===void 0&&(e=!1),!U(this.cl)||e){var n=this.Mr;if(n){var i=n.props[Mi];if(U(i)&&!e)return this.cl=i,void t(i,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",timestampMode:"query",callback:r=>{if(Oo(this._instance)){var s=r.statusCode;if(s!==200||!r.json){var o="Product Tours API could not be loaded, status: "+s;return s===0?r.error||xr.warn(o):xr.error(o),void t([],{isLoaded:!1,error:o})}var a=U(r.json.product_tours)?r.json.product_tours:[];this.cl=a,n&&n.register({[Mi]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){H(this.vl)?t([],{isLoaded:!1,error:"Product tours not loaded"}):this.vl.getActiveProductTours(t)}showProductTour(t){var e;(e=this.vl)==null||e.showTourById(t)}previewTour(t){this.vl?this.vl.previewTour(t):this.ai((()=>{var e;this.fl(),(e=this.vl)==null||e.previewTour(t)}))}dismissProductTour(){var t;(t=this.vl)==null||t.dismissTour("user_clicked_skip")}nextStep(){var t;(t=this.vl)==null||t.nextStep()}previousStep(){var t;(t=this.vl)==null||t.previousStep()}clearCache(){var t;this.cl=null,(t=this.Mr)==null||t.unregister(Mi)}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)}}},Cs),Ym={siteApps:class{constructor(t){this.pl=0,this._instance=t,this.gl=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}ml(t,e){if(e){var n=this.globalsForEvent(e);this.gl.push(n),this.gl.length>1e3&&(this.gl=this.gl.slice(10))}}get siteAppLoaders(){var t;return(t=B._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,n,i,r,s,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var h=d[0];l[h]={id:u[h],type:h,properties:d[1]}}var f=t.$set_once,p=t.$set;return{event:I({},fd(t,Bm),{properties:I({},t.properties,p?{$set:I({},(e=(n=t.properties)==null?void 0:n.$set)!==null&&e!==void 0?e:{},p)}:{},f?{$set_once:I({},(i=(r=t.properties)==null?void 0:r.$set_once)!==null&&i!==void 0?i:{},f)}:{}),elements_chain:(s=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&s!==void 0?s:"",distinct_id:(a=t.properties)==null?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}bl(t){var e,n=(e=t.tagName)==null?void 0:e.toLowerCase();return n==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(Et.error("prepare_external_dependency_stylesheet returned null"),null):n==="script"&&this._instance.config.prepare_external_dependency_script?this._instance.config.prepare_external_dependency_script(t)||(Et.error("prepare_external_dependency_script returned null"),null):t}_l(){var t,e,n,i,r,s,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=P?.defaultView,u=l==null||(t=l.Node)==null?void 0:t.prototype;if(!l||!u)return()=>{};if(this.pl++,this.wl)return this.kl();var c=[],d=this,h=new WeakSet,f=(m,v,E)=>{if(m!=null&&m[v]){var S=m[v];m[v]=E(S),c.push((()=>{m[v]=S}))}},p=m=>{if(h.has(m))return m;var v=d.bl(m);return v&&h.add(v),v},g=m=>m.map((v=>typeof v=="string"?v:p(v))).filter((v=>!Ye(v)));return f(u,"appendChild",(m=>function(v){var E=p(v);return E?m.call(this,E):v})),f(u,"insertBefore",(m=>function(v,E){var S=p(v);return S?m.call(this,S,E):v})),f(u,"replaceChild",(m=>function(v,E){var S=p(v);return S?m.call(this,S,E):E})),[(e=l.Element)==null?void 0:e.prototype,(n=l.Document)==null?void 0:n.prototype,(i=l.DocumentFragment)==null?void 0:i.prototype].forEach((m=>{f(m,"append",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),f(m,"prepend",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))}))})),[(r=l.Element)==null?void 0:r.prototype,(s=l.CharacterData)==null?void 0:s.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((m=>{f(m,"before",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),f(m,"after",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),f(m,"replaceWith",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];var b=g(S);return S.length&&!b.length?void 0:v.apply(this,b)}))})),f((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(v,E){var S=p(E);return S?m.call(this,v,S):null})),this.wl=()=>{c.forEach((m=>m())),this.wl=void 0},this.kl()}kl(){var t=!1;return()=>{var e;t||(t=!0,this.pl--,this.pl===0&&((e=this.wl)==null||e.call(this)))}}xl(t,e){e===void 0&&(e=!0);var n=this._l();try{var i=t(n);return e&&n(),i}catch(r){throw n(),r}}setupSiteApp(t){var e=this.apps[t.id],n=()=>{var o;!e.errored&&this.gl.length&&(Et.info("Processing "+this.gl.length+" events for site app with id "+t.id),this.gl.forEach((a=>this.xl((()=>e.processEvent==null?void 0:e.processEvent(a))))),e.processedBuffer=!0),Object.values(this.apps).every((a=>a.processedBuffer||a.errored))&&((o=this.yl)==null||o.call(this))},i=!1,r=o=>{e.errored=!o,e.loaded=!0,Et.info("Site app with id "+t.id+" "+(o?"loaded":"errored")),i&&n()};try{var s=this.xl((o=>t.init({posthog:this._instance,callback(a){o(),r(a)}})),!1).processEvent;s&&(e.processEvent=s),i=!0}catch(o){Et.error(uu+t.id,o),r(!1)}if(i&&e.loaded)try{n()}catch(o){Et.error("Error while processing buffered events PostHog app with config id "+t.id,o),e.errored=!0}}Sl(){var t=this.siteAppLoaders||[];for(var e of t)this.apps[e.id]={id:e.id,loaded:!1,errored:!1,processedBuffer:!1};for(var n of t)this.setupSiteApp(n)}Cl(t){var e=this;if(Object.keys(this.apps).length!==0){var n=this.globalsForEvent(t),i=function(s){try{e.xl((()=>s.processEvent==null?void 0:s.processEvent(n)))}catch(o){Et.error("Error while processing event "+t.event+" for site app "+s.id,o)}};for(var r of Object.values(this.apps))i(r)}}onRemoteConfig(t){var e,n,i,r=this;if((e=this.siteAppLoaders)!=null&&e.length)return this.isEnabled?(this.Sl(),void this._instance.on("eventCaptured",(l=>this.Cl(l)))):void Et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((n=this.yl)==null||n.call(this),t.ok){var s=t.config;if((i=s.siteApps)!=null&&i.length)if(this.isEnabled){var o=function(){var l,u=a.id,c=a.url;B["__$$ph_site_app_"+u]=r._instance,(l=B.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(r._instance,c,(d=>{if(d)return Et.error(uu+u,d)}))};for(var a of s.siteApps)o()}else Et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},Jm={tracingHeaders:class{constructor(t){this.Ml=void 0,this.Tl=void 0,this.El=void 0,this.Uo=()=>{var e,n,i=this.Il();i?(C(this.Ml)&&(this.Ml=(e=B.__PosthogExtensions__)==null||(e=e.tracingHeadersPatchFns)==null?void 0:e._patchXHR(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager)),C(this.Tl)&&(this.Tl=(n=B.__PosthogExtensions__)==null||(n=n.tracingHeadersPatchFns)==null?void 0:n._patchFetch(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager))):this.Qo()},this._instance=t}initialize(){this.startIfEnabledOrStop()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",(i=>{if(i)return Nm.error("failed to load script",i);t()}))}Pl(){var t,e;return(t=(e=this._instance.config.tracing_headers)!==null&&e!==void 0?e:this._instance.config.addTracingHeaders)!==null&&t!==void 0?t:this._instance.config.__add_tracing_headers}Il(){var t=this.Pl();return U(t)?(U(this.El)?this.El.splice(0,this.El.length,...t):this.El=[...t],t.length>0?this.El:void 0):(U(this.El)&&this.El.splice(0),this.El=t||void 0,this.El)}Qo(){var t,e;(t=this.Ml)==null||t.call(this),(e=this.Tl)==null||e.call(this),this.Ml=void 0,this.Tl=void 0}startIfEnabledOrStop(){this.Il()?this.ai(this.Uo):this.Qo()}}},Zm=I({surveys:class{get Ne(){return this._instance.config}constructor(t){this.Rl=void 0,this._surveyManager=null,this.Al=!1,this.Fl=[],this.Ll=null,this.Ol=null,this._instance=t,this._surveyEventReceiver=null}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this.Ne.disable_surveys){if(!t.ok)return Q.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(H(e))return Q.warn("Flags not loaded yet. Not loading surveys.");var n=U(e);this.Rl=n?e.length>0:e,Q.info("flags response received, isSurveysEnabled: "+this.Rl),this.loadIfEnabled()}}reset(){try{var t;(t=this._surveyEventReceiver)==null||t.reset(),localStorage.removeItem("lastSeenSurveyDate");for(var e=[],n=0;nlocalStorage.removeItem(r)))}catch{}}loadIfEnabled(){if(!this._surveyManager)if(this.Al)Q.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)Q.info(du);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())Q.info("Not loading surveys in cookieless mode without consent.");else{var t=B?.__PosthogExtensions__;if(t){if(!C(this.Rl)||this.Ne.advanced_enable_surveys){var e=this.Rl||this.Ne.advanced_enable_surveys;this.Al=!0;try{var n=t.generateSurveys;if(n)return void this.Dl(n,e);var i=t.loadExternalDependency;if(!i)return void this.$l(al);i(this._instance,"surveys",(r=>{r||!t.generateSurveys?this.$l("Could not load surveys script",r):this.Dl(t.generateSurveys,e)}))}catch(r){throw this.$l("Error initializing surveys",r),r}finally{this.Al=!1}}}else Q.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new Um(this._instance),Q.info("Surveys loaded successfully"),this.Nl({isLoaded:!0})}$l(t,e){Q.error(t,e),this.Nl({isLoaded:!1,error:t})}onSurveysLoaded(t){return this.Fl.push(t),this._surveyManager&&this.Nl({isLoaded:!0}),()=>{this.Fl=this.Fl.filter((e=>e!==t))}}getSurveys(t,e){if(e===void 0&&(e=!1),this.Ne.disable_surveys)return Q.info(du),t([]);var n,i=this._instance.get_property(la);if(i&&!e)return t(i,{isLoaded:!0}),void(this.ql()&&this.getSurveys((()=>{}),!0));typeof Promise<"u"&&this.Ll?this.Ll.then((r=>t(r.surveys,r.context))):(typeof Promise<"u"&&(this.Ll=new Promise((r=>{n=r}))),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this.Ne.token),method:"GET",timestampMode:"query",timeout:this.Ne.surveys_request_timeout_ms,callback:r=>{var s;this.Ll=null;var o=r.statusCode;if(o!==200||!r.json){var a="Surveys API could not be loaded, status: "+o;o!==0?Q.error(a):r.error||Q.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(n==null||n({surveys:[],context:l}))}this.Ol=null;var u,c=r.json.surveys||[],d=c.filter((f=>(function(p){return!(!p.start_date||p.end_date)})(f)&&(zf(f)||(function(p){var g;return!((g=p.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(f))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(s=this._instance.persistence)==null||s.register({[la]:c,[Xr]:Date.now()});var h={isLoaded:!0};t(c,h),n?.({surveys:c,context:h})}}))}ql(){return this.jl()&&!this.Ll&&!this.Bl()}jl(){var t=this._instance.get_property(Xr);return ke(t)&&Date.now()-t>3e5}Bl(){return ke(this.Ol)&&3e5>Date.now()-this.Ol}markSurveyAsSeen(t,e){var n,i={id:t,current_iteration:(n=e?.iteration)!==null&&n!==void 0?n:null};Vf(i);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}}Nl(t){for(var e of this.Fl)try{if(!t.isLoaded)return e([],t);this.getSurveys(e)}catch(n){Q.error("Error in survey callback",n)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!H(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);Q.warn("init was not called")}Hl(t){var e=null;return this.getSurveys((n=>{var i;e=(i=n.find((r=>r.id===t)))!==null&&i!==void 0?i:null})),e}Ul(t){if(H(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(H(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(H(this._surveyManager))return Q.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 H(this._surveyManager)?(Q.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Ir})):new Promise((n=>{this.getSurveys((i=>{var r,s=(r=i.find((a=>a.id===t)))!==null&&r!==void 0?r:null;if(s){var o=this.zl(s);n({visible:o.eligible,disabledReason:o.reason})}else n({visible:!1,disabledReason:"Survey not found"})}),e)}))}renderSurvey(t,e,n){var i;if(H(this._surveyManager))Q.warn("init was not called");else{var r=typeof t=="string"?this.Hl(t):t;if(r!=null&&r.id)if(Sm.includes(r.type)){var s=P?.querySelector(e);if(s)return(i=r.appearance)!=null&&i.surveyPopupDelaySeconds?(Q.info("Rendering survey "+r.id+" with delay of "+r.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;Q.info("Rendering survey "+r.id+" with delay of "+((o=r.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(a=this._surveyManager)==null||a.renderSurvey(r,s,n),Q.info("Survey "+r.id+" rendered")}),1e3*r.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(r,s,n);Q.warn("Survey element not found")}else Q.warn("Surveys of type "+r.type+" cannot be rendered in the app");else Q.warn("Survey not found")}}displaySurvey(t,e){var n;if(H(this._surveyManager))Q.warn("init was not called");else{var i=this.Hl(t);if(i){var r=i;if((n=i.appearance)!=null&&n.surveyPopupDelaySeconds&&e.ignoreDelay&&(r=I({},i,{appearance:I({},i.appearance,{surveyPopupDelaySeconds:0})})),e.displayType!==_a.Popover&&e.initialResponses&&Q.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),e.ignoreConditions===!1){var s=this.Ul(i);if(!s.eligible)return void Q.warn("Survey is not eligible to be displayed: ",s.reason)}e.displayType!==_a.Inline?this._surveyManager.handlePopoverSurvey(r,e):this.renderSurvey(r,e.selector,e.properties)}else Q.warn("Survey not found")}}cancelPendingSurvey(t){H(this._surveyManager)?Q.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},Cs),Xm={toolbar:class{constructor(t){this.instance=t}Wl(t){B.ph_toolbar_state=t}Vl(){var t;return(t=B.ph_toolbar_state)!==null&&t!==void 0?t:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(t,e,n){if(t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),ga(this.instance.config)||!w||!P)return!1;t=t??w.location,n=n??w.history;try{if(!e){try{w.localStorage.setItem("test","test"),w.localStorage.removeItem("test")}catch{return!1}e=w?.localStorage}var i,r=Hm||os(t.hash,"__posthog")||os(t.hash,"state"),s=r?Pc((()=>JSON.parse(atob(decodeURIComponent(r)))))||Pc((()=>JSON.parse(decodeURIComponent(r)))):null;return s&&s.action==="ph_authorize"?((i=s).source="url",i&&Object.keys(i).length>0&&(s.desiredHash?t.hash=s.desiredHash:n?n.replaceState(n.state,"",t.pathname+t.search):t.hash="")):((i=JSON.parse(e.getItem(fu)||"{}")).source="localstorage",delete i.userIntent),!(!i.token||this.instance.config.token!==i.token||(this.loadToolbar(i),0))}catch{return!1}}Zl(t){var e=B.ph_load_toolbar||B.ph_load_editor;!H(e)&&je(e)?e(t,this.instance):hu.warn("No toolbar load function found")}loadToolbar(t){var e=!(P==null||!P.getElementById(af));if(!w||e)return!1;var n=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,i=I({token:this.instance.config.token},t,{apiURL:this.instance.requestRouter.endpointFor("ui")},n?{instrument:!1}:{});if(w.localStorage.setItem(fu,JSON.stringify(I({},i,{source:void 0}))),this.Vl()===2)this.Zl(i);else if(this.Vl()===0){var r;this.Wl(1),(r=B.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"toolbar",(s=>{if(s)return hu.error("[Toolbar] Failed to load",s),void this.Wl(0);this.Wl(2),this.Zl(i)})),ve(w,"turbolinks:load",(()=>{this.Wl(0),this.loadToolbar(i)}))}return!0}Gl(t){return this.loadToolbar(t)}maybeLoadEditor(t,e,n){return t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),this.maybeLoadToolbar(t,e,n)}}},Qm=I({experiments:Me},Cs),ev={conversations:class{constructor(t){this.Ql=void 0,this._conversationsManager=null,this.Kl=!1,this.Jl=null,this.Yl=!1,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this._instance.config.disable_conversations&&(this.Xl=t.ok,t.ok)){var e=t.config.conversations;H(e)||(mt(e)?this.Ql=e:(this.Ql=e.enabled,this.Jl=e),this.loadIfEnabled())}}reset(){var t;(t=this._conversationsManager)==null||t.reset(),this._conversationsManager=null,this.Ql=void 0,this.Jl=null,this.Xl=void 0,this.Yl=!1}loadIfEnabled(){if(!(this._conversationsManager||this.Kl||this._instance.config.disable_conversations||ga(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=B?.__PosthogExtensions__;if(t&&!C(this.Ql)&&this.Ql)if(this.Jl&&this.Jl.token){this.Kl=!0;try{var e=t.initConversations;if(e)return this.tu(e),void(this.Kl=!1);var n=t.loadExternalDependency;if(!n)return void this.eu(al);n(this._instance,"conversations",(i=>{i||!t.initConversations?this.eu("Could not load conversations script",i):this.tu(t.initConversations),this.Kl=!1}))}catch(i){this.eu("Error initializing conversations",i),this.Kl=!1}}else ot.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,ot.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else ot.error("Cannot complete initialization: remote config is null")}eu(t,e){ot.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():ot.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!Ye(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":ga(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.Xl===!1?"remote_config_failed":C(this.Ql)?this.Xl?"disabled_in_project":"remote_config_pending":this.Ql?H(this.Jl)||!this.Jl.token?"missing_token":B!=null&&B.__PosthogExtensions__?this.Kl?"initializing":this.Yl?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.isVisible())!==null&&t!==void 0&&t}sendMessage(t,e,n){var i=this;return se((function*(){return i._conversationsManager?i._conversationsManager.sendMessage(t,e,n):(ot.warn(En),null)}))()}getMessages(t,e){var n=this;return se((function*(){return n._conversationsManager?n._conversationsManager.getMessages(t,e):(ot.warn(En),null)}))()}markAsRead(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(ot.warn(En),null)}))()}getTickets(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(ot.warn(En),null)}))()}requestRestoreLink(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(ot.warn(En),null)}))()}restoreFromToken(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(ot.warn(En),null)}))()}restoreFromUrlToken(){var t=this;return se((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(ot.warn(En),null)}))()}getCurrentTicketId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getCurrentTicketId())!==null&&t!==void 0?t:null}getWidgetSessionId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getWidgetSessionId())!==null&&t!==void 0?t:null}Xn(){var t;(t=this._conversationsManager)==null||t.setIdentity()}ts(){var t;(t=this._conversationsManager)==null||t.clearIdentity()}}},tv={logs:class{constructor(t){var e,n=this;this.iu=!1,this.ru=!1,this.rt=pe("[logs]"),this.nu=I({},this.rt,{error(){for(var i=arguments.length,r=new Array(i),s=0;i>s;s++)r[s]=arguments[s];r.some(bu)||n.rt.error(...r)}}),this.tr=[],this.su=[],this.Sa=0,this.au=()=>{var i,r;this.Sa=0,(i=this.ou)==null||i.onReconnect(),(r=this.lu)==null||r.onReconnect()},this._instance=t,this._instance&&(e=this._instance.config.logs)!=null&&e.captureConsoleLogs&&(this.iu=!0),w&&ve(w,"online",this.au)}uu(t,e,n,i){var r,s=(function(o,a){var l,u,c,d,h,f,p,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,v=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,E=C(v)?Math.max(m,2048):Math.max(m,v),S=o?.resourceAttributes;return{serviceName:(d=(h=S?.["service.name"])!==null&&h!==void 0?h:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(f=S?.["service.version"])!==null&&f!==void 0?f:o?.serviceVersion,environment:(p=S?.["deployment.environment"])!==null&&p!==void 0?p:o?.environment,resourceAttributes:S,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:E,maxBatchRecordsPerPost:100,rateCapWindowMs:g,maxLogsPerInterval:v,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}})((r=this._instance)==null||(r=r.config)==null?void 0:r.logs,n);return[new sg(this.hu(t,e),s,this.nu,(()=>this.du()),(o=>o()),void 0,i),s]}vu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.ou||this.cu!==e){var n;(n=this.ou)==null||n.reset(),this.cu=e;var i=this.uu((()=>this.tr),(r=>{this.tr=r}));this.ou=i[0],this.fu=i[1]}return this.ou}pu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.lu||this.gu!==e){var n;(n=this.lu)==null||n.reset(),this.gu=e;var i=this.uu((()=>this.su),(r=>{this.su=r}),{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},wu);this.lu=i[0],this.mu=i[1]}return this.lu}initialize(){this.loadIfEnabled()}onRemoteConfig(t){var e;if(t.ok){var n=(e=t.config.logs)==null?void 0:e.captureConsoleLogs;!H(n)&&n&&(this.iu=!0,this.loadIfEnabled())}}reset(){var t,e;this.tr=[],(t=this.ou)==null||t.reset(),this.su=[],(e=this.lu)==null||e.reset(),this.Sa=0}captureLog(t){this.vu().captureLog(t)}he(t){this.pu().captureLog(t)}get logger(){return this.yu||(this.yu={trace:(t,e)=>this.captureLog({body:t,level:"trace",attributes:e}),debug:(t,e)=>this.captureLog({body:t,level:"debug",attributes:e}),info:(t,e)=>this.captureLog({body:t,level:"info",attributes:e}),warn:(t,e)=>this.captureLog({body:t,level:"warn",attributes:e}),error:(t,e)=>this.captureLog({body:t,level:"error",attributes:e}),fatal:(t,e)=>this.captureLog({body:t,level:"fatal",attributes:e})}),this.yu}flushLogs(t){t?this.bu(t):(this.ou&&this.ou.flush().catch((e=>this._u(e))),this.lu&&this.lu.flush().catch((e=>this._u(e))))}_u(t){bu(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=B?.__PosthogExtensions__;if(t){var e=t.loadExternalDependency;e?e(this._instance,"logs",(n=>{var i;n||(i=t.logs)==null||!i.initializeLogs?this.rt.error("Could not load logs script",n):(t.logs.initializeLogs(this._instance),this.ru=!0)})):this.rt.error(al)}else this.rt.error("PostHog Extensions not found.")}}hu(t,e){var n=this._instance;return{get isDisabled(){return!1},get optedOut(){return!n.is_capturing()},getPersistedProperty:i=>i===Ut.LogsQueue?t():void 0,setPersistedProperty(i,r){var s;i===Ut.LogsQueue&&e((s=r)!==null&&s!==void 0?s:[])},Ot:i=>this.Ot(i),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Ot(t){return new Promise((e=>{if(yf(this.Sa,3))e({kind:"fatal",error:Do(void 0,"logs endpoint is unreachable, dropping batch")});else{var n=!1,i=s=>{n||(n=!0,clearTimeout(r),e(s))},r=setTimeout((()=>{this.rt.warn("Logs request timed out before receiving a response"),i({kind:"retry-later",error:Do(void 0,"logs request timed out")})}),9e4);this._instance._send_request({method:"POST",url:this.wu(),data:t,compression:"best-available",batchKey:"logs",fireCallbackOnDrop:!0,callback:s=>{var o=s.statusCode;if(this.ku(o),o>=200&&300>o)i({kind:"ok"});else if(o===413)i({kind:"too-large"});else if(o!==0&&o!==429&&500>o)i({kind:"fatal",error:new Error("logs request failed with status "+o)});else{var a;o===0?(s.error||this.rt.warn("Logs request failed before receiving an HTTP response"),i({kind:"retry-later",error:Do(s.error,"logs request failed before receiving an HTTP response")})):i({kind:"retry-later",error:(a=s.error)!==null&&a!==void 0?a:new Error("logs request failed with status "+o)})}}})}}))}ku(t){(t!==0||this._instance.__loaded)&&(this.Sa=wf(t,this.Sa,3,(()=>this.rt.warn("Log requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped sending logs; will try again when connectivity changes."))))}bu(t){this.tr.length>0&&this.xu(t,this.tr,this.fu,ne.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,wu,(e=>{this.su=e}))}xu(t,e,n,i,r){if(e.length!==0){var s=e.map((a=>a.record));r([]);var o=Wd(s,Hd(n,ne.LIB_NAME,ne.LIB_VERSION),i,ne.LIB_VERSION);this._instance._send_request({method:"POST",url:this.wu(),data:o,compression:"best-available",batchKey:"logs",transport:t})}}wu(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}du(){var t,e={};if(e.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var n=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.windowId,r=n.sessionStartTimestamp,s=n.lastActivityTimestamp;e.sessionId=n.sessionId,e.windowId=i,H(r)||(e.sessionStartTimestamp=r),H(s)||(e.lastActivityTimestamp=s)}if(B!=null&&(t=B.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?fn(B.location.href):B.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},nv={metrics:class{constructor(t){this.rt=pe("[metrics]"),this._instance=t}initialize(){}vu(){var t,e,n=(t=this._instance)==null||(t=t.config)==null?void 0:t.metrics;return this.ou&&this.cu===n||((e=this.ou)==null||e.reset(),this.cu=n,this.ou=new og(this.hu(),(function(i){var r,s,o,a,l,u=i?.resourceAttributes;return{serviceName:(r=u?.["service.name"])!==null&&r!==void 0?r:i?.serviceName,serviceVersion:(s=u?.["service.version"])!==null&&s!==void 0?s:i?.serviceVersion,environment:(o=u?.["deployment.environment"])!==null&&o!==void 0?o:i?.environment,resourceAttributes:u,beforeSend:i?.beforeSend,flushIntervalMs:(a=i?.flushIntervalMs)!==null&&a!==void 0?a:1e4,maxSeriesPerFlush:(l=i?.maxSeriesPerFlush)!==null&&l!==void 0?l:1e3}})(n),this.rt)),this.ou}count(t,e,n){e===void 0&&(e=1),this.vu().count(t,e,n)}gauge(t,e,n){this.vu().gauge(t,e,n)}histogram(t,e,n){this.vu().histogram(t,e,n)}flush(t){if(!this.ou)return Promise.resolve();if(t){var e=this.ou.drainWindow();return e&&this.Jt(e,t),Promise.resolve()}return this.ou.flush().catch((n=>this.rt.error("PostHog metrics flush failed:",n)))}reset(){var t;(t=this.ou)==null||t.reset()}hu(){var t=this._instance,e=this;return{get isDisabled(){return!1},get optedOut(){return!t.is_capturing()},Jt:n=>e.Jt(n),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Jt(t,e){return new Promise((n=>{var i=!1,r=o=>{i||(i=!0,clearTimeout(s),n(o))},s=setTimeout((()=>r({kind:"retry-later",error:new Error("metrics request timed out")})),9e4);this._instance._send_request(I({method:"POST",url:this.Su(),data:t,compression:"best-available",batchKey:"metrics"},e&&{transport:e},{fireCallbackOnDrop:!0,callback(o){var a=o.statusCode;if(a>=200&&300>a)r({kind:"ok"});else if(a===413)r({kind:"too-large"});else if(a!==0&&a!==429&&500>a)r({kind:"fatal",error:new Error("metrics request failed with status "+a)});else{var l;r({kind:"retry-later",error:(l=o.error)!==null&&l!==void 0?l:new Error("metrics request failed with status "+a)})}}}))}))}Su(){return this._instance.requestRouter.endpointFor("api","/i/v1/metrics")+"?token="+encodeURIComponent(this._instance.config.token)}}},iv=I({},Cs,qm,Vm,Gm,Km,Ym,Zm,Jm,Xm,Qm,ev,tv,nv);Ze.__defaultExtensionClasses=I({},iv);(function(){ne.SDK_DIST_CHANNEL="npm";var t=Wi[Gn]=new Ze;return(function(){function e(){e.done||(e.done=!0,Kf=!1,ie(Wi,(function(n){n._dom_loaded()})))}P!=null&&P.addEventListener?P.readyState==="complete"?e():ve(P,"DOMContentLoaded",e,{capture:!1}):w&&A.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const rv=["a[href]","button:not([disabled])","input:not([disabled]):not([type='hidden'])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(",");let pt=null,ka=null,Jf="";const Ca=new Map;function Zf(t){return[...t.querySelectorAll(rv)].filter(e=>!e.hidden&&e.getAttribute("aria-hidden")!=="true"&&e.getClientRects().length>0)}function sv(t){for(const e of document.body.children)e===t||e.tagName==="SCRIPT"||(Ca.set(e,{inert:e.inert,ariaHidden:e.getAttribute("aria-hidden")}),e.inert=!0,e.setAttribute("aria-hidden","true"))}function ov(){for(const[t,e]of Ca)t.inert=e.inert,e.ariaHidden===null?t.removeAttribute("aria-hidden"):t.setAttribute("aria-hidden",e.ariaHidden);Ca.clear()}function Xf(t){return t?.dataset.modalDismissible!=="false"&&t?.getAttribute("aria-busy")!=="true"}function We(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n)return!1;pt&&pt!==n&&ze(pt,{restoreFocus:!1,force:!0}),ka=e.trigger||document.activeElement,pt=n,Jf=document.body.style.overflow,sv(n),document.body.style.overflow="hidden",n.classList.add("open"),n.setAttribute("aria-hidden","false");const i=n.querySelector(".modal-content");i&&(i.style.transform="scale(1) translateY(0)");const r=()=>{if(pt!==n)return;((e.initialFocus?n.querySelector(e.initialFocus):n.querySelector("[data-modal-initial-focus]"))||Zf(n)[0]||n.querySelector(".modal-content")||n).focus({preventScroll:!0})};return requestAnimationFrame(r),setTimeout(r,260),!0}function ze(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n||!e.force&&!Xf(n))return!1;n.classList.remove("open"),n.setAttribute("aria-hidden","true"),ov(),document.body.style.overflow=Jf,pt=null;const i=ka;return ka=null,e.restoreFocus!==!1&&i?.isConnected&&i.focus({preventScroll:!0}),!0}function Eu(t,e,n="Operation in progress"){const i=typeof t=="string"?document.getElementById(t):t;i&&(i.dataset.modalDismissible=e?"false":"true",i.setAttribute("aria-busy",String(!!e)),e?i.setAttribute("aria-label",n):i.removeAttribute("aria-label"))}function av(t){if(!Xf(t))return;const e=t.dataset.modalCloseHandler;e&&typeof window[e]=="function"?window[e]():ze(t)}document.addEventListener("keydown",t=>{if(!pt)return;if(t.key==="Escape"){t.preventDefault(),t.stopImmediatePropagation(),av(pt);return}if(t.key!=="Tab"){t.stopPropagation();return}const e=Zf(pt);if(!e.length){t.preventDefault(),(pt.querySelector(".modal-content")||pt).focus();return}const n=e[0],i=e[e.length-1];t.shiftKey&&document.activeElement===n?(t.preventDefault(),i.focus()):!t.shiftKey&&document.activeElement===i&&(t.preventDefault(),n.focus())},!0);function lv(){document.querySelectorAll(".modal-overlay").forEach(t=>{t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-hidden",t.classList.contains("open")?"false":"true");const e=t.querySelector(".modal-content");e&&!e.hasAttribute("tabindex")&&(e.tabIndex=-1);const n=t.querySelector("h1, h2, h3");n&&(n.id||(n.id=`${t.id}-title`),t.setAttribute("aria-labelledby",n.id)),t.querySelectorAll(".modal-close").forEach(i=>{i.getAttribute("aria-label")||i.setAttribute("aria-label","Close dialog")})})}const gl=Object.freeze({free:"Free",professional:"Pro",power:"Power"}),cv=Object.freeze({free:2,professional:50,power:2e3}),uv="(contact us)",dv=Object.freeze({free:Object.freeze(["2 generations/month","Gemini model only","Code Review"]),professional:Object.freeze(["50 generations/month","All models","Code Regeneration","Code Review"]),power:Object.freeze(["2000 generations/month","All models","Code Regeneration","Bring your own key (BYOK)","Code Review","All models + early access",`API & MCP access ${uv}`])}),Qf="CodeFile",eh="GeneratedCode",fv={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function ln(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Aa(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function hv(t={},e=0){const n=Aa(t.artifactType||t.type||Qf),i=Aa(t.artifactName||t.name||t.fileName||`${eh}-${e+1}`);return`${n||"artifact"}-${i||e+1}`}function th(t={},e=0){const n=ln(t),i=n.artifactType||n.type||Qf,r=n.artifactName||n.name||eh;let s=n.fileName||r;return s.endsWith(".dart")||(s+=".dart"),{id:Aa(n.id)||hv({...n,artifactType:i,artifactName:r,fileName:s},e),artifactType:i,artifactName:r,fileName:s,deployPath:n.deployPath||"",description:n.description||"",code:n.code||n.content||"",dependencies:nh(n.dependencies),imports:Array.isArray(n.imports)?n.imports:[],publicApi:Array.isArray(n.publicApi)?n.publicApi:[],relationships:ih(n.relationships),deployStatus:n.deployStatus||"pending",review:n.review||null,metadata:ln(n.metadata),codeType:n.codeType||fv[i]||"O"}}function nh(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const n=ln(e),i=n.name||n.package;return i?{name:i,version:n.version||null,versionRequired:!!(n.versionRequired||n.required),inferred:!!n.inferred,...n.reason?{reason:n.reason}:{}}:null}).filter(Boolean):Object.entries(ln(t)).map(([e,n])=>({name:e,version:n||null,inferred:!1})):[]}function ih(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const n=ln(e);return!n.from&&!n.to?null:{from:n.from||null,to:n.to||null,type:n.type||"uses",description:n.description||""}}).filter(Boolean):[]}function Pa(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;try{return JSON.parse(e)}catch{const n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(!n)return null;try{return JSON.parse(n[1].trim())}catch{return null}}}function Qi(t,e={}){const n=[],i=typeof t=="string"?Pa(t):t,s=ln(i||{});!i&&typeof t=="string"&&n.push("Structured bundle parse failed; using legacy single-artifact fallback.");const o=Array.isArray(s.artifacts)?s.artifacts:[{artifactType:s.artifactType||e.artifactType,artifactName:s.artifactName||e.artifactName,fileName:s.fileName||e.fileName,description:s.description,code:s.code||e.code||(typeof t=="string"?t:""),dependencies:s.dependencies||e.dependencies,relationships:s.relationships||e.relationships}];o.forEach((d,h)=>{!d?.artifactType&&!d?.type&&n.push(`Artifact ${h+1} has no artifactType; it will deploy as a standalone code file under lib/custom_code/ root.`)});const a=o.map((d,h)=>th(d,h)),l=new Map(o.map((d,h)=>[ln(d).id,a[h]?.id]).filter(([d,h])=>d&&h)),u=d=>l.get(d)||d,c=ih(s.relationships||e.relationships).map(d=>({...d,from:d.from?u(d.from):d.from,to:d.to?u(d.to):d.to}));return{schemaVersion:s.schemaVersion||e.schemaVersion||null,id:s.id||e.id||"bundle-current",title:s.title||s.name||e.title||"Generated artifact bundle",description:s.description||e.description||"",artifacts:a,dependencies:nh(s.dependencies||e.dependencies),relationships:c,deployOrder:Array.isArray(s.deployOrder)?s.deployOrder.map(u):a.map(d=>d.id),warnings:[...n,...Array.isArray(s.warnings)?s.warnings:[]],metadata:ln(s.metadata)}}function oi(t){return Qi(t).artifacts[0]||th()}function Zt(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function ai(t){return JSON.stringify(t,null,2)}function pv(t){return ai({task:"architect",userRequest:String(t??"")})}function gv(t){const e=Zt(t);return e&&typeof e=="object"&&typeof e.task=="string"?ai(e):ai({task:"generate_bundle",bundleSpec:e})}function mv(t){return ai({task:"review_bundle",generatedBundle:Zt(t),outputRequirements:{bundleReview:["status","score","summary","manualActions","findings"],scoreRange:[0,100],eachArtifact:["id","review.status","review.findings"],manualActions:{definition:"Setup the developer must perform by hand in the FlutterFlow editor that FlutterFlow will NOT do for them.",exclude:["creating the Custom Action, Widget or Code File itself - deploying the code creates it","declaring parameters or return values FlutterFlow derives from the function signature","anything that resolves as a side effect of using the action or widget in the editor","generic advice such as testing, reviewing or rebuilding the app"],preferEmpty:"Return an empty array when nothing qualifies - an empty list is the expected result for most bundles."}}})}function ml(t,e=null){const n={stage:t};return e!=null&&(n.bundle=Zt(e)),n}function vv({bundleSpec:t,artifactBundle:e,bundleReview:n,artifactId:i,userFeedback:r}){return ai({task:"regenerate_artifact",artifactId:i,bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(r)})}function rh({bundleSpec:t,artifactBundle:e,bundleReview:n,userFeedback:i}){return ai({task:"regenerate_bundle",bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(i??"")})}const Su={csam:"child-safety content",dangerous:"dangerous content",harassment:"harassment",hate_speech:"hate speech",maliciousUrls:"a potentially malicious URL",malicious_uris:"a potentially malicious URL",pi_and_jailbreak:"prompt-injection or jailbreak instructions",promptInjection:"prompt-injection or jailbreak instructions",rai:"restricted content",sdp:"sensitive personal data",sexually_explicit:"sexually explicit content",virus_scan:"potentially malicious file content"},_v=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function tt(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function yv(t){return tt(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||tt(t.filterSummary)||tt(t.filterResults):!1}function sh(t,e=0){if(!tt(t)||e>3)return null;if(yv(t))return t;for(const n of _v){const i=t[n];if(tt(i)){const r=sh(i,e+1);if(r)return r}}return null}function ds(t){return Array.isArray(t)?t.some(ds):tt(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(ds):!1}function Fa(t){return Array.isArray(t)?t.some(Fa):tt(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(Fa):!1}function oh(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function wv(t,e){if(tt(t))for(const[n,i]of Object.entries(t)){if(!tt(i))continue;const r=tt(i.categories)?i.categories:{},s=Object.entries(r).filter(([,o])=>tt(o)&&o.matched===!0).map(([o])=>o);s.length>0?s.forEach(o=>e.add(o)):i.matched===!0&&e.add(oh(n))}}function bv(t,e){if(!t)return;const n=Array.isArray(t)?t.flatMap(i=>tt(i)?Object.entries(i):[]):Object.entries(t);for(const[i,r]of n){if(!ds(r))continue;const s=oh(i),o=r?.raiFilterResult?.raiFilterTypeResults||(s==="rai"?r?.raiFilterTypeResults:null),a=tt(o)?Object.entries(o).filter(([,l])=>ds(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(s)}}function Ev(t){return Su[t]?Su[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function xu(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 Sv(t){const e=sh(t);if(!e)return null;const n=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);wv(e.filterSummary,n),bv(e.filterResults,n);const i=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||n.size>0,r=e.invocationResult||null,s=Fa(e.filterSummary||e.filterResults);return!i&&!s&&!["PARTIAL","FAILURE"].includes(r)?null:{kind:i?"blocked":"unavailable",invocationResult:r,matchedFilters:[...n]}}function xv(t,e){const n=Sv(t);if(!n)return null;const i=[...new Set(n.matchedFilters.map(Ev))],r=n.kind==="blocked",s=new Error(r?`Safety screening blocked this pipeline step for ${xu(i)}.`:"Safety screening could not be completed. Please try again.");return s.name="ModelArmorError",s.code=r?"MODEL_ARMOR_BLOCKED":"MODEL_ARMOR_UNAVAILABLE",s.isModelArmor=!0,s.pipelineStep=e,s.userTitle=r?"Request blocked for safety":"Safety check unavailable",s.userMessage=r?`The safety check detected ${xu(i)}. Edit your request to remove or rephrase the flagged content, then run the pipeline again.`:"The safety service did not finish all of its checks. Please wait a moment and run the pipeline again.",s.retryExplanation=r?"Trying another model would not change this safety decision.":"A fallback model was not attempted because safety screening must complete first.",s.matchedFilters=n.matchedFilters,s}function Iv(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function Iu(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,n=[];for(const i of Iv(t).split(` -`)){if(!/^[A-Za-z_$]/.test(i)||e.test(i))continue;const r=i.match(/^[\w$<>,?\s[\]]+?\s([a-zA-Z_$][\w$]*)\s*\(/);r&&n.push(r[1])}return n}function vl(t,e){const n=t.replace(/\.dart$/,"");if(e==="W")return n.replace(/(^|_)(\w)/g,(i,r,s)=>s.toUpperCase());if(e==="A"){const i=n.replace(/(^|_)(\w)/g,(r,s,o)=>o.toUpperCase());return i.charAt(0).toLowerCase()+i.slice(1)}return e==="F"?"CustomFunctions":e==="C"?t.endsWith(".dart")?t:`${t}.dart`:n}async function ku(t){const e=new TextEncoder().encode(String(t||"")),n=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n),i=>i.toString(16).padStart(2,"0")).join("")}async function kv(t,e=new Map){const n={},i=new Set;for(const[o,a]of t.entries()){if(a.type==="D"||a.type==="O")continue;const l=vl(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await ku(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await ku(c)),n[o]=u,a.type==="F"){const d=Iu(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(f=>i.add(f))}}const r=new Set(Iu(e.get("lib/flutter_flow/custom_functions.dart")||"")),s={functions_to_rename:[],functions_to_delete:[],functions_to_add:Array.from(i).filter(o=>!r.has(o))};return{fileMapContents:JSON.stringify(n),functionsMapContents:JSON.stringify(s)}}const Cv=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),Cu={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},Av=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),Pv=["Struct","Record"],Fv=[{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=>jo(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=>jo(t).some(e=>{const n=/^\s*final\s+(?:double|int|String|bool|Color|num)\s+(\w+)\s*;/gm;let i;for(;(i=n.exec(e))!==null;){const r=i[1];if(!(new RegExp(`this\\.${r}\\s*=(?!=)`).test(e)||new RegExp(`[:,]\\s*${r}\\s*=(?!=)`).test(e)))return!0}return!1}),pos:`class W extends StatefulWidget { +(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const s of r)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function n(r){const s={};return r.integrity&&(s.integrity=r.integrity),r.referrerPolicy&&(s.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?s.credentials="include":r.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function i(r){if(r.ep)return;r.ep=!0;const s=n(r);fetch(r.href,s)}})();var w=typeof window<"u"?window:void 0,Ne=typeof globalThis<"u"?globalThis:w,He=Ne?.navigator,P=Ne?.document,me=Ne?.location,Xa=Ne?.fetch,qo=Ne!=null&&Ne.XMLHttpRequest&&"withCredentials"in new Ne.XMLHttpRequest?Ne.XMLHttpRequest:void 0,dc=Ne?.AbortController,Mp=Ne?.CompressionStream,Ge=He?.userAgent;function fd(){return!(!w||w.navigator.onLine===!1)}var vi=typeof globalThis<"u"?globalThis:w;vi&&typeof self>"u"&&(vi.self=vi),vi&&typeof File>"u"&&(vi.File=function(){});var B=w??{},ne={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function fc(t,e,n,i,r,s,o){try{var a=t[s](o),l=a.value}catch(u){return void n(u)}a.done?e(l):Promise.resolve(l).then(i,r)}function se(t){return function(){var e=this,n=arguments;return new Promise((function(i,r){var s=t.apply(e,n);function o(l){fc(s,i,r,o,a,"next",l)}function a(l){fc(s,i,r,o,a,"throw",l)}o(void 0)}))}}function I(){return I=Object.assign?Object.assign.bind():function(t){for(var e=1;arguments.length>e;e++){var n=arguments[e];for(var i in n)({}).hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},I.apply(null,arguments)}function hd(t,e){if(t==null)return{};var n={};for(var i in t)if({}.hasOwnProperty.call(t,i)){if(e.indexOf(i)!==-1)continue;n[i]=t[i]}return n}var hc=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function pc(t){return typeof t=="string"||t}function gc(t){return typeof t=="string"?t:void 0}var _i,Lp=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],Ut=(function(t){return t.AnonymousId="anonymous_id",t.DistinctId="distinct_id",t.Props="props",t.EnablePersonProcessing="enable_person_processing",t.PersonMode="person_mode",t.FeatureFlagDetails="feature_flag_details",t.FeatureFlags="feature_flags",t.FeatureFlagPayloads="feature_flag_payloads",t.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",t.BootstrapFeatureFlags="bootstrap_feature_flags",t.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",t.OverrideFeatureFlags="override_feature_flags",t.Queue="queue",t.AiQueue="ai_queue",t.LogsQueue="logs_queue",t.OptedOut="opted_out",t.SessionId="session_id",t.SessionStartTimestamp="session_start_timestamp",t.SessionLastTimestamp="session_timestamp",t.PersonProperties="person_properties",t.GroupProperties="group_properties",t.InstalledAppBuild="installed_app_build",t.InstalledAppVersion="installed_app_version",t.SessionReplay="session_replay",t.PushRegistered="push_registered",t.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",t.SurveyLastSeenDate="survey_last_seen_date",t.SurveysSeen="surveys_seen",t.Surveys="surveys",t.RemoteConfig="remote_config",t.FlagsEndpointWasHit="flags_endpoint_was_hit",t.DeviceId="device_id",t})({}),mc=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),Np=["$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"],Op=["token"],pd="NativeGzipValidationError",Vo=t=>t.length>=2&&t[0]===31&&t[1]===139,vc=(t,e)=>t===mc.GZipJS||e===mc.GZipJS||e==="gzip",_c=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",pr=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=pd,e},Bp=(function(){var t=se((function*(e,n){18>e.size&&pr("too-short");var i=new Uint8Array(yield e.slice(0,10).arrayBuffer());Vo(i)&&i[2]===8||pr("invalid-header");var r=new DataView(yield e.slice(e.size-8).arrayBuffer());r.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(_i)return _i;_i=[];for(var c=0;256>c;c++){for(var d=c,f=0;8>f;f++)d=1&d?3988292384^d>>>1:d>>>1;_i[c]=d>>>0}return _i})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(n)&&pr("invalid-crc");var s=n.length>>>0;r.getUint32(4,!0)!==s&&pr("invalid-size")}));return function(e,n){return t.apply(this,arguments)}})();function Go(){return Go=se((function*(t,e,n){e===void 0&&(e=!0);try{var i=new TextEncoder().encode(t),r=new globalThis.CompressionStream("gzip"),s=r.writable.getWriter(),o=s.write(i).then((()=>s.close())).catch((function(){var u=se((function*(c){try{yield s.abort(c)}catch{}throw c}));return function(c){return u.apply(this,arguments)}})()),a=new Response(r.readable).blob(),l=(yield Promise.all([a,o]))[0];return yield Bp(l,i),l}catch(u){if(n!=null&&n.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),Go.apply(this,arguments)}var Dp=["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"],yc=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var n=t.toLowerCase();return Dp.concat(e).some((i=>{var r=i.toLowerCase();return n.indexOf(r)!==-1}))};function j(t,e){return t.indexOf(e)!==-1}var Is=function(t){return t.trim()},Ko=function(t){return t.replace(/^\$/,"")};function gd(t){var e,n=[];return(e=JSON.stringify(t,(function(i,r){if(typeof r=="bigint")return r.toString();if(typeof r!="function"&&typeof r!="symbol"){if(r instanceof Error)return{name:r.name,message:r.message,stack:r.stack};if(r&&typeof r=="object"){for(;n.length>0&&n[n.length-1]!==this;)n.pop();if(n.includes(r))return"[Circular]";n.push(r)}return r}})))!==null&&e!==void 0?e:"null"}var md=Object.prototype,vd=md.hasOwnProperty,ks=md.toString,U=Array.isArray||function(t){return ks.call(t)==="[object Array]"},je=t=>typeof t=="function",he=t=>t===Object(t)&&!U(t),Kt=t=>{if(he(t)){for(var e in t)if(vd.call(t,e))return!1;return!0}return!1},C=t=>t===void 0,X=t=>ks.call(t)=="[object String]",Yo=t=>X(t)&&t.trim().length===0,Ye=t=>t===null,H=t=>C(t)||Ye(t),ke=t=>ks.call(t)=="[object Number]"&&t==t,Dt=t=>ke(t)&&t>0,mt=t=>ks.call(t)==="[object Boolean]",jp=t=>t instanceof FormData,Up=t=>j(Np,t),Hp=t=>j(Op,t);function _d(t){return t===null||typeof t!="object"}function Hr(t,e){return{}.toString.call(t)==="[object "+e+"]"}function Qa(t){return typeof Event<"u"&&yd(t,Event)}function yd(t,e){try{return t instanceof e}catch{return!1}}var Wp=[!0,"true",1,"1","yes"],fo=t=>j(Wp,t),zp=[!1,"false",0,"0","no"];function At(t,e,n,i,r){return e>n&&(i.warn("min cannot be greater than max."),e=n),ke(t)?t>n?(i.warn(" cannot be greater than max: "+n+". Using max value instead."),n):e>t?(i.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(i.warn(" must be a number. using max or fallback. max: "+n+", fallback: "+r),At(r||n,e,n,i))}class qp{constructor(e){this.tt={},this.et=e.et,this.it=At(e.bucketSize,0,100,e.rt),this.nt=At(e.refillRate,0,this.it,e.rt),this.st=At(e.refillInterval,0,864e5,e.rt)}ot(e,n){var i=Math.floor((n-e.lastAccess)/this.st);i>0&&(e.tokens=Math.min(e.tokens+i*this.nt,this.it),e.lastAccess=e.lastAccess+i*this.st)}consumeRateLimit(e){var n,i=Date.now(),r=String(e),s=this.tt[r];return s?this.ot(s,i):this.tt[r]=s={tokens:this.it,lastAccess:i},s.tokens===0||(s.tokens--,s.tokens===0&&((n=this.et)==null||n.call(this,e)),s.tokens===0)}stop(){this.tt={}}}var rt="Mobile",Wr="iOS",Yt="Android",ei="Tablet",wd=Yt+" "+ei,bd="iPad",Ed="Apple",Sd=Ed+" Watch",Bi="Safari",ti="BlackBerry",xd="Samsung",Id=xd+"Browser",kd=xd+" Internet",Pn="Chrome",Vp=Pn+" OS",Cd=Pn+" "+Wr,el="Internet Explorer",Ad=el+" "+rt,tl="Opera",Gp=tl+" Mini",nl="Edge",Pd="Microsoft "+nl,Zn="Firefox",Fd=Zn+" "+Wr,Gi="Nintendo",Ki="PlayStation",Xn="Xbox",Rd=Yt+" "+rt,Td=rt+" "+Bi,Pi="Windows",Jo=Pi+" Phone",wc="Nokia",Zo="Ouya",$d="Generic",Kp=$d+" "+rt.toLowerCase(),Md=$d+" "+ei.toLowerCase(),Xo="Konqueror",Ld="Oculus Browser",zr="Vivaldi",Nd="Yandex",qr="Whale",Qo="DuckDuckGo",Od="Pale Moon",Vr="Waterfox",Di="Brave",Bd="Google Search App",we="(\\d+(\\.\\d+)?)",ho=new RegExp("Version/"+we),Yp=new RegExp(Xn,"i"),Jp=new RegExp(Ki+" \\w+","i"),Zp=new RegExp(Gi+" \\w+","i"),il=new RegExp(ti+"|PlayBook|BB10","i"),Xp={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000",5.1:"XP",5.2:"XP","6.0":"Vista",6.1:"7",6.2:"8",6.3:"8.1",6.4:"10","10.0":"10"},Dd=function(t,e,n,i){e=e||"";var r=(function(s){return s!=null&&s.brave?Di:null})(n);return r||(i!=null&&i.detectGoogleSearchApp&&j(t,"GSA/")?Bd:j(t," OPR/")&&j(t,"Mini")?Gp:j(t," OPR/")?tl:il.test(t)?ti:j(t,"IE"+rt)||j(t,"WPDesktop")?Ad:j(t,"OculusBrowser")?Ld:j(t,Id)?kd:j(t,nl)||j(t,"Edg/")?Pd:j(t,zr+"/")?zr:j(t,"YaBrowser/")?Nd:j(t,qr+"/")?qr:j(t,Qo+"/")||j(t,"Ddg/")?Qo:j(t,"FBIOS")?"Facebook "+rt:j(t,"UCWEB")||j(t,"UCBrowser")?"UC Browser":j(t,"CriOS")?Cd:j(t,"CrMo")||j(t,Pn)?Pn:j(t,Yt)&&j(t,Bi)?Rd:j(t,"FxiOS")?Fd:j(t.toLowerCase(),Xo.toLowerCase())?Xo:j(t,Di+"/")?Di:((s,o)=>o&&j(o,Ed)||(function(a){return j(a,Bi)&&!j(a,Pn)&&!j(a,Yt)})(s))(t,e)?j(t,rt)?Td:Bi:j(t,"PaleMoon/")?Od:j(t,Vr+"/")?Vr:j(t,Zn)?Zn:j(t,"MSIE")||j(t,"Trident/")?el:j(t,"Gecko")?Zn:"")},Qp={[Ad]:[new RegExp("rv:"+we)],[Pd]:[new RegExp(nl+"?\\/"+we)],[Pn]:[new RegExp("("+Pn+"|CrMo)\\/"+we)],[Cd]:[new RegExp("CriOS\\/"+we)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+we)],[Bi]:[ho],[Td]:[ho],[tl]:[new RegExp("(Opera|OPR)\\/"+we)],[Zn]:[new RegExp(Zn+"\\/"+we)],[Fd]:[new RegExp("FxiOS\\/"+we)],[Xo]:[new RegExp("Konqueror[:/]?"+we,"i")],[ti]:[new RegExp(ti+" "+we),ho],[Rd]:[new RegExp("android\\s"+we,"i")],[kd]:[new RegExp(Id+"\\/"+we)],[Ld]:[new RegExp("OculusBrowser\\/"+we)],[zr]:[new RegExp(zr+"\\/"+we)],[Nd]:[new RegExp("YaBrowser\\/"+we)],[qr]:[new RegExp(qr+"\\/"+we)],[Di]:[new RegExp(Di+"\\/"+we)],[Qo]:[new RegExp("(DuckDuckGo|Ddg)\\/"+we)],[Od]:[new RegExp("PaleMoon\\/"+we)],[Vr]:[new RegExp(Vr+"\\/"+we)],[Bd]:[new RegExp("GSA\\/"+we)],[el]:[new RegExp("(rv:|MSIE )"+we)],Mozilla:[new RegExp("rv:"+we)]},eg=function(t,e,n,i){var r=Dd(t,e,n,i),s=Qp[r];if(C(s))return null;for(var o=0;s.length>o;o++){var a=t.match(s[o]);if(a)return parseFloat(a[a.length-2])}return null},bc=[[new RegExp(Xn+"; "+Xn+" (.*?)[);]","i"),t=>[Xn,t&&t[1]||""]],[new RegExp(Gi,"i"),[Gi,""]],[new RegExp(Ki,"i"),[Ki,""]],[il,[ti,""]],[new RegExp(Pi,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Jo,""];if(new RegExp(rt).test(e)&&!/IEMobile\b/.test(e))return[Pi+" "+rt,""];var n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){var i=Xp[n[1]]||"";return/arm/i.test(e)&&(i="RT"),[Pi,i]}return[Pi,""]}],[/((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=C(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+Yt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Yt+")","i"),t=>t&&t[2]?[Yt,[t[2],t[3],t[4]||"0"].join(".")]:[Yt,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{var e=["Mac OS X",""];return t&&t[1]&&(e[1]=[t[1],t[2],t[3]||"0"].join(".")),e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[Vp,""]],[/Linux|debian/i,["Linux",""]]],Ec=function(t){return Zp.test(t)?Gi:Jp.test(t)?Ki:Yp.test(t)?Xn:new RegExp(Zo,"i").test(t)?Zo:new RegExp("("+Jo+"|WPDesktop)","i").test(t)?Jo:/iPad/.test(t)?bd:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?Sd:il.test(t)?ti:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(wc,"i").test(t)?wc:/(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(rt).test(t)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(t)||/pixel[\daxl ]{1,6}/i.test(t)&&!/pixel c/i.test(t)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(t)||/lmy47v/i.test(t)&&!/QTAQZ3/i.test(t)?Yt:wd:new RegExp("(pda|"+rt+")","i").test(t)?Kp:new RegExp(ei,"i").test(t)&&!new RegExp(ei+" pc","i").test(t)?Md:""},tg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Sc(t,e){return typeof(n=t)=="string"&&tg.test(n)?t:e();var n}function fn(t){return t&&t.split("#")[0]}function rl(t,e){var n=setTimeout(t,e);return n?.unref&&n?.unref(),n}function xc(t,e,n){return jd.apply(this,arguments)}function jd(){return(jd=se((function*(t,e,n){var i;try{return yield Promise.race([t,new Promise(((r,s)=>{i=rl((()=>{try{n?.(),r()}catch(o){s(o)}}),e)}))])}finally{clearTimeout(i)}}))).apply(this,arguments)}var ng=t=>t instanceof Error,Ud={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}},ig=Ud.info;function Hd(t){if(mt(t))return{boolValue:t};if(typeof t=="number")return Number.isFinite(t)?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:{stringValue:String(t)};if(typeof t=="string")return{stringValue:t};if(U(t))return{arrayValue:{values:t.map((e=>Hd(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function Gr(t){var e=[];for(var n in t){var i=t[n];Ye(i)||C(i)||e.push({key:n,value:Hd(i)})}return e}function rg(t,e){var n=Ud[t.level||"info"]||ig,i=n.text,r=n.number,s=String(Date.now())+"000000",o={};e.distinctId&&(o.posthogDistinctId=e.distinctId),e.sessionId&&(o.sessionId=e.sessionId),e.windowId&&(o["window.id"]=e.windowId),H(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),H(e.lastActivityTimestamp)||(o.lastActivityTimestamp=String(e.lastActivityTimestamp)),e.currentUrl&&(o["url.full"]=e.currentUrl),e.screenName&&(o["screen.name"]=e.screenName),e.appState&&(o["app.state"]=e.appState),e.activeFeatureFlags&&e.activeFeatureFlags.length>0&&(o.feature_flags=e.activeFeatureFlags);var a=I({},o,t.attributes||{}),l={timeUnixNano:s,observedTimeUnixNano:s,severityNumber:r,severityText:i,body:{stringValue:t.body},attributes:Gr(a)};return t.trace_id&&(l.traceId=t.trace_id),t.span_id&&(l.spanId=t.span_id),C(t.trace_flags)||(l.flags=t.trace_flags),l}function Wd(t,e,n){return I({},t.resourceAttributes,{"service.name":t.serviceName||"unknown_service"},t.environment&&{"deployment.environment":t.environment},t.serviceVersion&&{"service.version":t.serviceVersion},{"telemetry.sdk.name":e,"telemetry.sdk.version":n})}function zd(t,e,n,i){return{resourceLogs:[{resource:{attributes:Gr(e)},scopeLogs:[{scope:{name:n,version:i},logRecords:t}]}]}}let sg=class{constructor(t,e,n,i,r,s,o){var a;s===void 0&&(s=()=>Promise.resolve()),this._instance=t,this.Ne=e,this.rt=n,this.ut=i,this.ht=r,this.dt=s,this.vt=o,this.ct=null,this.ft=0,this.yt=0,this.bt=0,this._t=0,this.wt=!1,this.kt=e.maxBufferSize,this.xt=Math.max((a=e.maxQueueSize)!==null&&a!==void 0?a:e.maxBufferSize,e.maxBufferSize),this.St=e.flushIntervalMs,this.Ct=e.maxBatchRecordsPerPost,this.Mt=e.rateCapWindowMs,this.Tt=e.maxLogsPerInterval}reset(){this.Et(),this.ct=null,this.bt=0,this._t=0,this.wt=!1,this.ft=0,this.yt=0,this.Ct=this.Ne.maxBatchRecordsPerPost}onReconnect(){this.yt=0,this.It()}captureLog(t){if(!this._instance.isDisabled&&!this._instance.optedOut&&t!=null&&t.body){var e=this.Pt(t);if(e!==null)if(e.body){if(this.Rt()){var n={record:rg(e,this.ut())};this.ht((()=>this.At(n)))}}else this.rt.info("Log was rejected in beforeSend function")}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Log was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for log:",o),null}return i}Rt(){if(this.Tt===void 0)return!0;var t=Date.now(),e=t-this.bt;return this.Mt>e&&e>=0||(this.bt=t,this._t=0,this.wt=!1),this.Tt>this._t?(this._t++,!0):(this.wt||(this.rt.warn("captureLog dropping logs: exceeded "+this.Tt+" logs per "+this.Mt+"ms"),this.wt=!0),!1)}flush(){var t=this;return se((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return se((function*(){var e;t.Et();var n=(e=t._instance.getPersistedProperty(Ut.LogsQueue))!==null&&e!==void 0?e:[];if(n.length!==0)for(var i=n.length,r=0;n.length>0&&i>r;){var s,o;t.ft=0;var a=Math.min(n.length,t.Ct),l=n.slice(0,a),u=zd(l.map((d=>d.record)),t.Lt(),(s=t.vt)!==null&&s!==void 0?s:t._instance.getLibraryId(),t._instance.getLibraryVersion()),c=yield t._instance.Ot(u);if(c.kind==="too-large"&&l.length>1)t.Ct=Math.max(1,Math.floor(l.length/2)),t.rt.warn("Received 413 when sending logs batch of size "+l.length+", reducing batch size to "+t.Ct);else if(c.kind==="retry-later"||(c.kind==="too-large"?t.rt.warn("Dropping a single log record after 413 with batch size 1 — the record is larger than the server cap and cannot be split further."):c.kind==="ok"&&t.Ne.maxBatchRecordsPerPost>t.Ct&&(t.Ct=Math.min(t.Ne.maxBatchRecordsPerPost,t.Ct+1)),yield t.Dt(l.length),n=(o=t._instance.getPersistedProperty(Ut.LogsQueue))!==null&&o!==void 0?o:[],r+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return se((function*(){var n,i=Math.max(0,t-e.ft),r=(n=e._instance.getPersistedProperty(Ut.LogsQueue))!==null&&n!==void 0?n:[];e._instance.setPersistedProperty(Ut.LogsQueue,r.slice(i)),yield e.dt()}))()}Lt(){return Wd(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var n=(e=this._instance.getPersistedProperty(Ut.LogsQueue))!==null&&e!==void 0?e:[];this.xt>n.length||(n.shift(),this.ft++,this.rt.info("Logs queue is full, dropping oldest record.")),n.push(t),this._instance.setPersistedProperty(Ut.LogsQueue,n),this.kt>n.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=rl((()=>{this.Nt=void 0,this.It()}),t))}qt(){var t=Math.min(Math.max(0,this.yt-1),6);return this.St*Math.pow(2,t)}jt(){var t=this._instance.getPersistedProperty(Ut.LogsQueue);return!!t&&t.length>0}shutdown(t){var e=this;return se((function*(){e.Et();var n=e.flush().catch((()=>{}));t!==void 0?yield xc(n,t):yield n}))()}flushWithTimeout(t){var e=this;return se((function*(){var n=e.flush();yield xc(n,t,(()=>{n.catch((()=>{}))}))}))()}It(){this.flush().then((()=>{this.yt=0}),(t=>{this.yt++,this.rt.error("PostHog logs flush failed:",t)})).finally((()=>{!this._instance.isDisabled&&this.jt()&&this.$t(this.qt())}))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}};var po=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function Ic(t){return String(t)+"000000"}function kc(t,e,n,i){var r="";return i&&(r=Object.keys(i).sort().map((s=>JSON.stringify(s)+":"+JSON.stringify(i[s]))).join(",")),t+"\0"+e+"\0"+(n??"")+"\0"+r}let og=class{constructor(t,e,n){this._instance=t,this.Ne=e,this.rt=n,this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Wt=0}count(t,e,n){e===void 0&&(e=1),this.Vt({name:t,type:"count",value:e,unit:n?.unit,attributes:n?.attributes})}gauge(t,e,n){this.Vt({name:t,type:"gauge",value:e,unit:n?.unit,attributes:n?.attributes})}histogram(t,e,n){this.Vt({name:t,type:"histogram",value:e,unit:n?.unit,attributes:n?.attributes})}flush(){var t=this,e=this.ct,n=(function(){var r=se((function*(){e&&(yield e.catch((()=>{}))),yield t.Zt()}));return function(){return r.apply(this,arguments)}})(),i=n().finally((()=>{this.ct===i&&(this.ct=null)}));return this.ct=i,i}drainWindow(){if(this.Bt.size===0)return null;var t=this.Bt;return this.Bt=new Map,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Gt(t)}reset(){this.Wt++,this.Et(),this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set}Vt(t){if(!this._instance.isDisabled&&!this._instance.optedOut){var e=this.Pt(t);if(e!==null)if(e.name&&typeof e.name=="string")if(typeof e.value=="number"&&Number.isFinite(e.value))if(e.type==="count"&&0>e.value)this.rt.warn("Dropping count '"+e.name+"': counters are monotonic, value must be >= 0");else{var n,i;try{n=e.attributes?I({},e.attributes):void 0,i=kc(e.type,e.name,e.unit,n)}catch(o){return void this.rt.warn("Dropping metric '"+e.name+"': attributes could not be serialized",o)}var r=this.Bt.get(i);if(!r){if(!this.Qt())return;r={name:e.name,type:e.type,unit:e.unit,attributes:n,windowStartMs:Date.now()},this.Bt.set(i,r)}var s=this.Ut.get(e.name);s===void 0?this.Ut.set(e.name,e.type):s===e.type||this.zt.has(e.name)||(this.zt.add(e.name),this.rt.warn("Metric name '"+e.name+"' is already used as a "+s+"; recording it as a "+e.type+" too will blend both series in charts. Use a distinct name.")),this.Kt(r,e.value),this.$t()}else this.rt.warn("Dropping metric '"+e.name+"': value must be a finite number");else this.rt.warn("Dropping metric with empty name")}}Qt(){return this.Ne.maxSeriesPerFlush>this.Bt.size||(this.Ht||(this.Ht=!0,this.rt.warn("Metric series cap reached ("+this.Ne.maxSeriesPerFlush+" per flush window); dropping new series until the next flush. Reduce attribute cardinality.")),!1)}Kt(t,e){var n;switch(t.type){case"count":t.total=((n=t.total)!==null&&n!==void 0?n:0)+e;break;case"gauge":t.last=e;break;case"histogram":t.hist||(t.hist={count:0,sum:0,min:e,max:e,bucketCounts:new Array(po.length+1).fill(0)});var i=t.hist;i.count+=1,i.sum+=e,i.min=Math.min(i.min,e),i.max=Math.max(i.max,e),i.bucketCounts[(function(r,s){for(var o=0;s.length>o;o++)if(s[o]>=r)return o;return s.length})(e,po)]+=1}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Metric was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for metric:",o),null}return i}$t(){this.Nt||(this.Nt=rl((()=>{this.Nt=void 0,this.flush().catch((t=>{this.rt.error("Metrics flush failed:",t)}))}),this.Ne.flushIntervalMs))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}Zt(){var t=this;return se((function*(){if(t.Bt.size!==0){var e=t.Bt;t.Bt=new Map,t.Ht=!1,t.Ut=new Map,t.zt=new Set;var n=t.Wt,i=yield t._instance.Jt(t.Gt(e));if(n===t.Wt)switch(i.kind){case"ok":return;case"retry-later":return t.Yt(e),void t.$t();case"too-large":return void t.rt.warn("Metrics batch exceeded the server size limit and was dropped");case"fatal":return void t.rt.error("Failed to send metrics batch:",i.error)}}}))()}Gt(t){return e=this.Xt(t),n=(function(s,o,a){return I({},s.resourceAttributes,{"service.name":s.serviceName||"unknown_service"},s.environment&&{"deployment.environment":s.environment},s.serviceVersion&&{"service.version":s.serviceVersion},{"telemetry.sdk.name":o,"telemetry.sdk.version":a})})(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion()),i=this._instance.getLibraryId(),r=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:Gr(n)},scopeMetrics:[{scope:{name:i,version:r},metrics:e}]}]};var e,n,i,r}Xt(t){var e=Ic(Date.now()),n=new Map;for(var i of t.values()){var r,s=kc(i.type,i.name,i.unit,void 0),o=n.get(s);o||(o=I({name:i.name},i.unit&&{unit:i.unit}),i.type==="count"?o.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:i.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:1,dataPoints:[]},n.set(s,o));var a=Gr((r=i.attributes)!==null&&r!==void 0?r:{}),l=Ic(i.windowStartMs);if(i.type==="count"){var u,c={attributes:a,startTimeUnixNano:l,timeUnixNano:e,asDouble:(u=i.total)!==null&&u!==void 0?u:0};o.sum.dataPoints.push(c)}else if(i.type==="gauge"){var d,f={attributes:a,timeUnixNano:e,asDouble:(d=i.last)!==null&&d!==void 0?d:0};o.gauge.dataPoints.push(f)}else i.hist&&o.histogram.dataPoints.push({attributes:a,startTimeUnixNano:l,timeUnixNano:e,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:po})}return Array.from(n.values())}Yt(t){var e,n;for(var i of t){var r=i[0],s=i[1],o=this.Bt.get(r);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,s.windowStartMs),o.type){case"count":o.total=((e=o.total)!==null&&e!==void 0?e:0)+((n=s.total)!==null&&n!==void 0?n:0);break;case"gauge":break;case"histogram":if(s.hist)if(o.hist){o.hist.count+=s.hist.count,o.hist.sum+=s.hist.sum,o.hist.min=Math.min(o.hist.min,s.hist.min),o.hist.max=Math.max(o.hist.max,s.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=s.hist.bucketCounts[a]}else o.hist=s.hist}else this.Qt()&&this.Bt.set(r,s)}}};var gr,Cc,go;function ag(t){var e=globalThis._posthogChunkIds;if(e){var n=Object.keys(e);return go&&n.length===Cc||(Cc=n.length,go=n.reduce(((i,r)=>{gr||(gr={});var s=gr[r];if(s)i[s[0]]=s[1];else for(var o=t(r),a=o.length-1;a>=0;a--){var l=o[a],u=l?.filename,c=e[r];if(u&&c){i[u]=c,gr[r]=[u,c];break}}return i}),{})),go}}class lg{constructor(e,n,i){i===void 0&&(i=[]),this.coercers=e,this.stackParser=n,this.modifiers=i}buildFromUnknown(e,n){n===void 0&&(n={});var i=n&&n.mechanism||{handled:!0,type:"generic"},r=this.buildCoercingContext(i,n,0).apply(e),s=this.buildParsingContext(n),o=this.parseStacktrace(r,s);return{$exception_list:this.convertToExceptionList(o,i),$exception_level:"error"}}modifyFrames(e){var n=this;return se((function*(){for(var i of e)i.stacktrace&&i.stacktrace.frames&&U(i.stacktrace.frames)&&(i.stacktrace.frames=yield n.applyModifiers(i.stacktrace.frames));return e}))()}coerceFallback(e){var n;return{type:"Error",value:"Unknown error",stack:(n=e.syntheticException)==null?void 0:n.stack,synthetic:!0}}parseStacktrace(e,n){var i,r;return e.cause!=null&&(i=this.parseStacktrace(e.cause,n)),e.stack!=""&&e.stack!=null&&(r=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?n.skipFirstLines:0),n.chunkIdMap)),I({},e,{cause:i,stack:r})}applyChunkIds(e,n){return e.map((i=>(i.filename&&n&&(i.chunk_id=n[i.filename]),i)))}applyCoercers(e,n){for(var i of this.coercers)if(i.match(e))return i.coerce(e,n);return this.coerceFallback(n)}applyModifiers(e){var n=this;return se((function*(){var i=e;for(var r of n.modifiers)i=yield r(i);return i}))()}convertToExceptionList(e,n){var i,r,s,o={type:e.type,value:e.value,mechanism:{type:(i=n.type)!==null&&i!==void 0?i:"generic",handled:(r=n.handled)===null||r===void 0||r,synthetic:(s=e.synthetic)!==null&&s!==void 0&&s}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,I({},n,{handled:!0}))),a}buildParsingContext(e){var n;return{chunkIdMap:ag(this.stackParser),skipFirstLines:(n=e.skipFirstLines)!==null&&n!==void 0?n:1}}buildCoercingContext(e,n,i){i===void 0&&(i=0);var r=(s,o)=>{if(4>=o){var a=this.buildCoercingContext(e,n,o);return this.applyCoercers(s,a)}};return I({},n,{syntheticException:i==0?n.syntheticException:void 0,mechanism:e,apply:s=>r(s,i),next:s=>r(s,i+1)})}}var ni="?";function ea(t,e,n,i,r){var s={platform:t,filename:e,function:n===""?ni:n,in_app:!0};return C(i)||(s.lineno=i),C(r)||(s.colno=r),s}var qd=(t,e)=>{var n=t.indexOf("safari-extension")!==-1,i=t.indexOf("safari-web-extension")!==-1;return n||i?[t.indexOf("@")!==-1?t.split("@")[0]:ni,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},cg=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,ug=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,dg=/\((\S*)(?::(\d+))(?::(\d+))\)/,fg=(t,e)=>{var n=cg.exec(t);if(n)return ea(e,n[1],ni,+n[2],+n[3]);var i=ug.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var r=dg.exec(i[2]);r&&(i[2]=r[1],i[3]=r[2],i[4]=r[3])}var s=qd(i[1]||ni,i[2]);return ea(e,s[1],s[0],i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},hg=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,pg=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,gg=(t,e)=>{var n=hg.exec(t);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){var i=pg.exec(n[3]);i&&(n[1]=n[1]||"eval",n[3]=i[1],n[4]=i[2],n[5]="")}var r=n[3],s=n[1]||ni,o=qd(s,r);return ea(e,r=o[1],s=o[0],n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},Ac=/\(error: (.*)\)/;class mg{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,n){var i=X(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:i?e.stack:void 0,cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var n=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?n+": "+e.message:n}isDOMException(e){return Hr(e,"DOMException")}isDOMError(e){return Hr(e,"DOMError")}}class vg{match(e){return(function(n){switch({}.toString.call(n)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return yd(n,Error)}})(e)}coerce(e,n){return{type:this.getType(e),value:this.getMessage(e,n),stack:this.getStack(e),cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,n){var i=e.message;return String(i.error&&typeof i.error.message=="string"?i.error.message:i)}getStack(e){return e.stacktrace||e.stack||void 0}}class _g{constructor(){}match(e){return!!Hr(e,"ErrorEvent")&&(e.error!=null||this.fe(e))}coerce(e,n){var i;if(e.error!=null)return n.apply(e.error);var r=n.apply(e.message);return I({},r,{stack:(i=this.pe(e))!==null&&i!==void 0?i:r.stack,synthetic:!0})}fe(e){return X(e.message)&&e.message.length>0}pe(e){var n=e;if(X(n.filename)&&n.filename.length>0){var i,r,s=(i=n.lineno)!==null&&i!==void 0?i:0,o=(r=n.colno)!==null&&r!==void 0?r:0;return`Error + at `+n.filename+":"+s+":"+o}}}var yg=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class wg{match(e){return typeof e=="string"}coerce(e,n){var i,r=this.getInfos(e),s=r[0],o=r[1];return{type:s??"Error",value:o??e,stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}getInfos(e){var n="Error",i=e,r=e.match(yg);return r&&(n=r[1],i=r[2]),[n,i]}}var bg=["fatal","error","warning","log","info","debug"];function Vd(t,e){e===void 0&&(e=40);var n=Object.keys(t);if(n.sort(),!n.length)return"[object has no keys]";for(var i=n.length;i>0;i--){var r=n.slice(0,i).join(", ");if(e>=r.length)return i===n.length?r:r.length>e?r.slice(0,e)+"...":r}return""}class Eg{match(e){return typeof e=="object"&&e!==null}coerce(e,n){var i,r,s=this.getErrorPropertyFromObject(e);return s?n.apply(s):{type:this.getType(e),value:this.getValue(e),stack:(i=this.getStack(e))!==null&&i!==void 0?i:(r=n.syntheticException)==null?void 0:r.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return Qa(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var n="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(n+=" with message: '"+e.message+"'"),n}if("message"in e&&typeof e.message=="string")return e.message;var i=this.getObjectClassName(e);return(i&&i!=="Object"?"'"+i+"'":"Object")+" captured as exception with keys: "+Vd(e)}isSeverityLevel(e){return X(e)&&!Yo(e)&&bg.indexOf(e)>=0}getStack(e){try{return X(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:X(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(var n in e)if({}.hasOwnProperty.call(e,n)){var i=e[n];if(ng(i))return i}}getObjectClassName(e){try{var n=Object.getPrototypeOf(e);return n?n.constructor.name:void 0}catch{return}}}class Sg{match(e){return Qa(e)}coerce(e,n){var i,r=e.constructor.name;return{type:r,value:r+" captured as exception with keys: "+Vd(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class xg{match(e){return _d(e)}coerce(e,n){var i;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class Ig{match(e){return Hr(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Qa(e))return!1;try{var n=e.detail;return n!=null&&typeof n=="object"&&"reason"in n}catch{return!1}}coerce(e,n){var i,r=this.getUnhandledRejectionReason(e);return _d(r)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(r),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}:n.apply(r)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}}var Kr="$message",Yr="$timestamp",kg=new Set([Kr,Yr]),mo={enabled:!0,max_bytes:32768};function Jr(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:mo.enabled,max_bytes:Ag(t.max_bytes,mo.max_bytes)}:I({},mo)}class Cg{constructor(e){this.Ke=[],this.Je=0,this.Ne=Jr(e)}setConfig(e){this.Ne=Jr(e),this.Xe()}add(e){var n=(function(r){var s;try{s=gd(r)}catch{return}try{var o=JSON.parse(s);if(!he(o))return;var a=o,l=a[Kr],u=a[Yr];return!X(l)||l.trim().length===0||!X(u)&&!ke(u)?void 0:{step:a,json:s}}catch{return}})(e);if(n){var i=(function(r){if(typeof TextEncoder<"u")return new TextEncoder().encode(r).length;for(var s=encodeURIComponent(r),o=0,a=0;s.length>a;a++)s[a]==="%"?(o+=1,a+=2):o+=1;return o})(n.json);i>this.Ne.max_bytes||(this.Ke.push({step:n.step,bytes:i}),this.Je+=i,this.Xe())}}getAttachable(){return this.Ke.map((e=>e.step))}clear(){this.Ke=[],this.Je=0}size(){return this.Ke.length}Xe(){for(;this.Je>this.Ne.max_bytes&&this.Ke.length>0;){var e=this.Ke.shift();e&&(this.Je-=e.bytes)}}}function Ag(t,e){if(!ke(t)||t===1/0||t===-1/0)return e;var n=Math.floor(t);return 0>n?e:n}var Gd=function(t,e){var n=(e===void 0?{}:e).debugEnabled,i={k(r){if(w&&(ne.DEBUG||w.POSTHOG_DEBUG||n)&&!C(w.console)&&w.console){for(var s=("__rrweb_original__"in w.console[r])?w.console[r].__rrweb_original__:w.console[r],o=arguments.length,a=new Array(o>1?o-1:0),l=1;o>l;l++)a[l-1]=arguments[l];s(t,...a)}},debug(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("debug",...s)},info(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("log",...s)},warn(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("warn",...s)},error(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("error",...s)},critical(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];console.error(t,...s)},uninitializedWarning(r){i.error("You must initialize PostHog before calling "+r)},createLogger:(r,s)=>Gd(t+" "+r,s)};return i},A=Gd("[PostHog.js]"),pe=A.createLogger,Pg=pe("[ExternalScriptsLoader]"),vo=(t,e,n)=>{if(t.config.disable_external_dependency_loading)return Pg.warn(e+" was requested but loading of external scripts is disabled."),n("Loading of external scripts is disabled");var i=P?.querySelectorAll("script");if(i){for(var r,s=function(){if(i[o].src===e){var l=i[o];return l.__posthog_loading_callback_fired?{v:n()}:(l.addEventListener("load",(u=>{l.__posthog_loading_callback_fired=!0,n(void 0,u)})),l.onerror=u=>n(u),{v:void 0})}},o=0;i.length>o;o++)if(r=s())return r.v}var a=()=>{if(!P)return n("document not found");var l=P.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=d=>{l.__posthog_loading_callback_fired=!0,n(void 0,d)},l.onerror=d=>n(d),t.config.prepare_external_dependency_script&&(l=t.config.prepare_external_dependency_script(l)),!l)return n("prepare_external_dependency_script returned null");if(t.config.external_scripts_inject_target==="head")P.head.appendChild(l);else{var u,c=P.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):P.body.appendChild(l)}};P!=null&&P.body?a():P?.addEventListener("DOMContentLoaded",a)};B.__PosthogExtensions__=B.__PosthogExtensions__||{},B.__PosthogExtensions__.loadExternalDependency=(t,e,n)=>{if(e!=="remote-config"){var i;if(t.config.strict_script_versioning)i=t.requestRouter.endpointFor("assets","/static/"+t.version+"/"+e+".js");else{var r="/static/"+e+".js?v="+t.version;if(e==="toolbar"){var s=3e5;r=r+"&t="+Math.floor(Date.now()/s)*s}i=t.requestRouter.endpointFor("assets",r)}vo(t,i,n)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");vo(t,o,n)}},B.__PosthogExtensions__.loadSiteApp=(t,e,n)=>{var i=t.requestRouter.endpointFor("api",e);vo(t,i,n)};ne.DEBUG=!1,ne.LIB_VERSION="1.415.7",ne.LIB_NAME="web";var Kd="$people_distinct_id",Yi="$device_id",_o="$device_model",Fi="__alias",Ri="__timers",ta="$autocapture_disabled_server_side",na="$heatmaps_enabled_server_side",ia="$exception_capture_enabled_server_side",ra="$error_tracking_suppression_rules",sa="$error_tracking_capture_extension_exceptions",oa="$web_vitals_enabled_server_side",sl="$dead_clicks_enabled_server_side",ol="$product_tours_enabled_server_side",aa="$web_vitals_allowed_metrics",An="$session_recording_remote_config",Yd="$replay_sample_rate",Jd="$replay_override_sampling",Zd="$replay_override_linked_flag",Xd="$replay_override_url_trigger",Qd="$replay_override_event_trigger",Kn="$sesid",al="$session_is_sampled",Sn="$enabled_feature_flags",Ti="$active_feature_flags",Ar="$early_access_features",la="$feature_flag_details",$i="$feature_flag_payloads",Pr="$feature_flag_request_id",Zr="$minimal_flag_called_events",It="$override_feature_flags",xn="$override_feature_flag_payloads",jt="$stored_person_properties",In="$stored_group_properties",ca="$surveys",Xr="$surveys_loaded_at",ua="$surveys_activated",Fr="$surveys_activated_session",Rr="$surveys_activated_timestamps",Mi="ph_product_tours",Cn="$flag_call_reported",Li="$flag_call_reported_session_id",Tr="$feature_flag_errors",ji="$feature_flag_evaluated_at",at="$user_state",da="$client_session_props",fa="$capture_rate_limit",ha="$initial_campaign_params",pa="$initial_referrer_info",Qr="$initial_person_info",es="$epp",mr="$posthog_cookieless",ef="$cookieless_mode",tf="$sdk_debug_extensions_init_method",nf="$sdk_debug_extensions_init_time_ms",rf="$sdk_debug_recording_script_not_loaded",ll="PostHog loadExternalDependency extension not found.",kn="on_reject",Wt="always",Un="anonymous",vn="identified",ga="identified_only",ts="visibilitychange",ns="beforeunload",Vn="$pageview",yo="$pageleave",wo="$identify",Pc="$groupidentify";function vr(t,e){U(t)&&t.forEach(e)}function ie(t,e){if(!H(t))if(U(t))t.forEach(e);else if(jp(t))t.forEach(((i,r)=>e(i,r)));else for(var n in t)vd.call(t,n)&&e(t[n],n)}var fe=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;e>i;i++)n[i-1]=arguments[i];for(var r of n)for(var s in r)r[s]!==void 0&&(t[s]=r[s]);return t};function $r(t){for(var e=Object.keys(t),n=e.length,i=new Array(n);n--;)i[n]=[e[n],t[e[n]]];return i}var Fc=function(t){try{return t()}catch{return}},Fg=function(t){return function(){try{for(var e=arguments.length,n=new Array(e),i=0;e>i;i++)n[i]=arguments[i];return t.apply(this,n)}catch(r){A.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),A.critical(r)}}},cl=function(t){var e={};return ie(t,(function(n,i){(X(n)&&n.length>0||ke(n))&&(e[i]=n)})),e},Rg=["herokuapp.com","vercel.app","netlify.app"];function Tg(t){var e=t?.hostname;if(!X(e))return!1;var n=e.split(".").slice(-2).join(".");for(var i of Rg)if(n===i)return!1;return!0}function ve(t,e,n,i){var r=i??{},s=r.capture,o=r.passive;t?.addEventListener(e,n,{capture:s!==void 0&&s,passive:o===void 0||o})}function ma(t){return t.name==="ph_toolbar_internal"}var sf=t=>{if(P){try{for(var e=t+"=",n=P.cookie.split(";").filter((s=>s.length)),i=0;n.length>i;i++){for(var r=n[i];r.charAt(0)==" ";)r=r.substring(1,r.length);if(r.indexOf(e)===0)return decodeURIComponent(r.substring(e.length,r.length))}}catch{}return null}};Math.trunc||(Math.trunc=function(t){return 0>t?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return ke(t)&&isFinite(t)&&Math.floor(t)===t});class is{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,n,i,r){if(!Number.isInteger(e)||!Number.isInteger(n)||!Number.isInteger(i)||!Number.isInteger(r)||0>e||0>n||0>i||0>r||e>0xffffffffffff||n>4095||i>1073741823||r>4294967295)throw new RangeError("invalid field value");var s=new Uint8Array(16);return s[0]=e/Math.pow(2,40),s[1]=e/Math.pow(2,32),s[2]=e/Math.pow(2,24),s[3]=e/Math.pow(2,16),s[4]=e/256,s[5]=e,s[6]=112|n>>>8,s[7]=n,s[8]=128|i>>>24,s[9]=i>>>16,s[10]=i>>>8,s[11]=i,s[12]=r>>>24,s[13]=r>>>16,s[14]=r>>>8,s[15]=r,new is(s)}toString(){for(var e="",n=0;this.bytes.length>n;n++)e=e+(this.bytes[n]>>>4).toString(16)+(15&this.bytes[n]).toString(16),n!==3&&n!==5&&n!==7&&n!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new is(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var n=0;16>n;n++){var i=this.bytes[n]-e.bytes[n];if(i!==0)return Math.sign(i)}return 0}}class $g{generate(){var e=this.generateOrAbort();if(!C(e))return e;this.S=0;var n=this.generateOrAbort();if(C(n))throw new Error("Could not generate UUID after timestamp reset");return n}generateOrAbort(){var e=Date.now();if(e>this.S)this.S=e,this.C();else{if(this.S>=e+1e4)return;this.I++,this.I>4398046511103&&(this.S++,this.C())}return is.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 Mg}}var Rc,of=t=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;t.length>e;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};w&&!C(w.crypto)&&crypto.getRandomValues&&(of=t=>crypto.getRandomValues(t));class Mg{nextUint32(){return this.R.length>this.O||(of(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var Ht=()=>Lg().toString(),Lg=()=>(Rc||(Rc=new $g)).generate(),yi="",Ng=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,zt={N:()=>!!P,j(t){A.error("cookieStore error: "+t)},P:sf,H(t){var e;try{e=JSON.parse(zt.P(t))||{}}catch{}return e},F(t,e,n,i,r){if(!P)return!1;try{var s="",o="",a=(function(c,d){if(d){var f=(function(p,g){if(g===void 0&&(g=P),yi)return yi;if(!g||["localhost","127.0.0.1"].includes(p))return"";for(var m=p.split("."),v=Math.min(m.length,8),E="dmn_chk_"+Ht();!yi&&v--;){var S=m.slice(v).join("."),_=E+"=1;domain=."+S+";path=/";g.cookie=_+";max-age=3",g.cookie.includes(E)&&(g.cookie=_+";max-age=0",yi=S)}return yi})(c);if(!f){var h=(p=>{var g=p.match(Ng);return g?g[0]:""})(c);h!==f&&A.info("Warning: cookie subdomain discovery mismatch",h,f),f=h}return f?"; domain=."+f:""}return""})(P.location.hostname,i);if(n){var l=new Date;l.setTime(l.getTime()+864e5*n),s="; expires="+l.toUTCString()}r&&(o="; secure");var u=t+"="+encodeURIComponent(JSON.stringify(e))+s+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&A.warn("cookieStore warning: large cookie, len="+u.length),P.cookie=u,!0}catch{return!1}},q(t,e){if(P!=null&&P.cookie)try{zt.F(t,"",-1,e)}catch{return}}},bo=null,le={N(){if(!Ye(bo))return bo;var t=!0;if(C(w))t=!1;else try{var e="__mplssupport__";le.F(e,"xyz"),le.P(e)!=='"xyz"'&&(t=!1),le.q(e)}catch{t=!1}return t||A.error("localStorage unsupported; falling back to cookie store"),bo=t,t},j(t){A.error("localStorage error: "+t)},P(t){try{return w?.localStorage.getItem(t)}catch(e){le.j(e)}return null},H(t){try{return JSON.parse(le.P(t))||{}}catch{}return null},F(t,e){try{return w?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(n){le.j(n)}return!1},q(t){try{w?.localStorage.removeItem(t)}catch(e){le.j(e)}}},Og=[Yi,"distinct_id",Kn,al,es,Qr,at],_r={},Bg={N:()=>!0,j(t){A.error("memoryStorage error: "+t)},P:t=>_r[t]||null,H:t=>_r[t]||null,F:(t,e)=>(_r[t]=e,!0),q(t){delete _r[t]}},_n=null,be={N(){if(!Ye(_n))return _n;if(_n=!0,C(w))_n=!1;else try{var t="__support__";be.F(t,"xyz"),be.P(t)!=='"xyz"'&&(_n=!1),be.q(t)}catch{_n=!1}return _n},j(t){A.error("sessionStorage error: ",t)},P(t){try{return w?.sessionStorage.getItem(t)}catch(e){be.j(e)}return null},H(t){try{return JSON.parse(be.P(t))||null}catch{}return null},F(t,e){try{return w?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(n){be.j(n)}return!1},q(t){try{w?.sessionStorage.removeItem(t)}catch(e){be.j(e)}}};class Dg{constructor(e){this._instance=e}get Ne(){return this._instance.config}get consent(){return this.ti()?0:this.ei}isOptedOut(){return this.Ne.cookieless_mode===Wt||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===kn}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===0}isRejected(){return this.consent===0||this.consent===-1&&this.Ne.opt_out_capturing_by_default}optInOut(e){this.ii.F(this.ri,e?1:0,this.Ne.cookie_expiration,this.Ne.cross_subdomain_cookie,this.Ne.secure_cookie)}reset(){this.ii.q(this.ri,this.Ne.cross_subdomain_cookie)}get ri(){var e=this._instance.config,n=e.token,i=e.opt_out_capturing_cookie_prefix;return e.consent_persistence_name||(i?i+n:"__ph_opt_in_out_"+n)}get ei(){var e=this.ii.P(this.ri);return fo(e)?1:j(zp,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,n=e==="localStorage"?le:zt;if(!this.ni||this.ni!==n){this.ni=n;var i=e==="localStorage"?zt:le;i.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(fo(i.P(this.ri))),i.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[He?.doNotTrack,He?.msDoNotTrack,B.doNotTrack].some((e=>fo(e)))}}function af(t,e){var n,i=t==null||(n=t.config)==null?void 0:n.get_current_url;if(!je(i))return e;try{var r=i(e);return X(r)&&r?r:e}catch(s){return A.error("Error in get_current_url, falling back to window.location.href",s),e}}var lf="__POSTHOG_TOOLBAR__",jg=1,Ug=3,Hg=11;function Tc(t){return t instanceof Element&&(t.id===lf||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function hn(t){return!!t&&t.nodeType===jg}function et(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function cf(t){return!!t&&t.nodeType===Ug}function uf(t){return!!t&&t.nodeType===Hg&&hn(t.host)}var df=1e3;function ul(t){return t?Is(t).split(/\s+/):[]}function $c(t,e){var n=(function(i){var r,s=w==null||(r=w.location)==null?void 0:r.href;return C(s)?void 0:af(i,s)})(e);return!!(n&&t&&t.some((i=>n.match(i))))}function rs(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 ul(e)}function ff(t){return H(t)?null:Is(t).split(/(\s+)/).filter((e=>Ui(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function Ji(t){var e="";return _a(t)&&!mf(t)&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;cf(n)&&n.textContent&&(e+=(i=ff(n.textContent))!==null&&i!==void 0?i:"")})),Is(e)}function Eo(t){var e;return C(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var dl=["a","button","form","input","select","textarea","label"];function va(t,e){if(C(e))return!0;var n,i=function(s){if(e.some((o=>(function(a,l){var u=a.matches||a.matchesSelector||a.msMatchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.oMatchesSelector;try{return!!u&&u.call(a,l)}catch{return!1}})(s,o))))return{v:!0}};for(var r of t)if(n=i(r))return n.v;return!1}function hf(t){var e=t.parentNode;return!(!e||!hn(e))&&e}var Wg=[".ph-no-autocapture","[data-ph-no-autocapture]"],pf=["next","previous","prev",">","<"],zg=[...pf,"+","-","−","–"],Mc=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,Lc=[".ph-no-rageclick",".ph-no-capture"],qg=["","text","search","email","password","url","tel","number"];function Nc(t,e){if(!w||fl(t))return!1;var n,i,r,s,o;if(mt(e)?(n=!!e&&Lc,i=void 0,r=!1):(n=(s=e?.css_selector_ignorelist)!==null&&s!==void 0?s:Lc,i=e?.content_ignorelist,r=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),n===!1||r&&(function(l){return!(!l||!hn(l))&&(!!et(l,"textarea")||(et(l,"input")?j(qg,(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=gf(t,!1).targetElementList;return!(function(l,u){if(l===!1||C(l))return!1;var c;if(l===!0)c=pf;else{if(!U(l))return!1;if(l.length>10)return A.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var f=d.safeText,h=d.ariaLabel;return c.some((p=>Mc(f,p)||Mc(h,p)))}))})(i,a.map((l=>{var u;return{safeText:Ji(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!va(a,n)}var fl=t=>!t||et(t,"html")||!hn(t),gf=(t,e)=>{if(!w||fl(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,i=[t],r=t;r.parentNode&&!et(r,"body");)if(uf(r.parentNode))i.push(r.parentNode.host),r=r.parentNode.host;else{var s=hf(r);if(!s)break;if(e||dl.indexOf(s.tagName.toLowerCase())>-1)n=!0;else try{var o=w.getComputedStyle(s);o&&o.getPropertyValue("cursor")==="pointer"&&(n=!0)}catch{}i.push(s),r=s}return{parentIsUsefulElement:n,targetElementList:i}};function _a(t){for(var e=new Set,n=0,i=t;i.parentNode&&!et(i,"body");i=i.parentNode){if(n++>=df||e.has(i))return!1;e.add(i);var r=rs(i);if(j(r,"ph-sensitive")||j(r,"ph-no-capture"))return!1}if(j(rs(t),"ph-include"))return!0;var s=t.type||"";if(X(s))switch(s.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!X(o)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(o.replace(/[^a-zA-Z0-9]/g,""))}function mf(t){return!!(et(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||et(t,"select")||et(t,"textarea")||t.getAttribute("contenteditable")==="true")}var Oc=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}))$"),Bc=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,Vg=[16,15,14,13],Gg=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),Dc=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),jc=/[0-9A-Za-z_]/;function Kg(t){for(var e=0,n=!1,i=t.length-1;i>=0;i--){var r=t.charCodeAt(i)-48;n&&(r*=2)>9&&(r-=9),e+=r,n=!n}return e%10==0}function Ui(t,e){if(e===void 0&&(e=!0),H(t))return!1;if(X(t)){t=Is(t);var n=e?Oc.test((t||"").replace(/[- ]/g,"")):(function(r){var s;for(Bc.lastIndex=0;s=Bc.exec(r);){var o=s[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of Vg){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(Oc.test(d)&&Kg(d))return!0}}}return!1})(t);if(n)return!1;var i=e?Gg.test(t):(function(r){var s;for(Dc.lastIndex=0;s=Dc.exec(r);){var o=s[1],a=s[3];if(!(o&&a&&jc.test(o)&&jc.test(a)))return!0}return!1})(t);if(i)return!1}return!0}function Uc(t){var e=Ji(t);return Ui(e=(e+" "+vf(t)).trim())?e:""}function vf(t){var e="";return t&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;if(n&&((i=n.tagName)==null?void 0:i.toLowerCase())==="span")try{var r=Ji(n);e=(e+" "+r).trim(),n.childNodes&&n.childNodes.length&&(e=(e+" "+vf(n)).trim())}catch(s){A.error("[AutoCapture]",s)}})),e}function Hc(t){return t.replace(/"|\\"/g,'\\"')}function Yg(t){var e=t.attr__class;if(e)return U(e)?e:ul(e)}var yr=pe("[Dead Clicks]"),Jg=()=>!0,Zg=t=>{var e,n=!((e=t.instance.persistence)==null||!e.get_property(sl)),i=t.instance.config.capture_dead_clicks;return mt(i)?i:!!he(i)||n};class Wc{get lazyLoadedDeadClicksAutocapture(){return this.si}constructor(e,n,i){this.instance=e,this.isEnabled=n,this.onCapture=i,this.startIfEnabledOrStop()}onRemoteConfig(e){if(e.ok){var n=e.config;"captureDeadClicks"in n&&(this.instance.persistence&&this.instance.persistence.register({[sl]:n.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var n,i;(n=B.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture?e():(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"dead-clicks-autocapture",(r=>{r?yr.error("failed to load script",r):e()}))}oi(){var e;if(P){if(!this.si&&(e=B.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var n=he(this.instance.config.capture_dead_clicks)?I({},this.instance.config.capture_dead_clicks):{};n.__onCapture=this.onCapture,this.onCapture&&(n.capture_dead_swipes=!1),this.si=B.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.si.start(P),yr.info("starting...")}}else yr.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,yr.info("stopping..."))}}var So=pe("[SegmentIntegration]"),_f="posthog-js";function yf(t,e){var n=e===void 0?{}:e,i=n.organization,r=n.projectId,s=n.prefix,o=n.severityAllowList,a=o===void 0?["error"]:o,l=n.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,f,h,p,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var v,E=((d=c.exception)==null?void 0:d.values)||[],S=E.map((b=>I({},b,{stacktrace:b.stacktrace?I({},b.stacktrace,{type:"raw",frames:(b.stacktrace.frames||[]).map((k=>I({},k,{platform:"web:javascript"})))}):void 0}))),_={$exception_message:((f=E[0])==null?void 0:f.value)||c.message,$exception_type:(h=E[0])==null?void 0:h.type,$exception_level:c.level,$exception_list:S,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((p=E[0])==null?void 0:p.value)||c.message,$sentry_exception_type:(g=E[0])==null?void 0:g.type,$sentry_tags:c.tags};return i&&r&&(_.$sentry_url=(s||"https://sentry.io/organizations/")+i+"/issues/?project="+r+"&query="+c.event_id),u&&((v=t.exceptions)==null||v.sendExceptionEvent(_)),c}}class Xg{constructor(e,n,i,r,s,o){this.name=_f,this.setupOnce=function(a){a(yf(e,{organization:n,projectId:i,prefix:r,severityAllowList:s,sendExceptionsToPostHog:o==null||o}))}}}class zc{constructor(e){this.li=(n,i,r)=>{r&&(r.noSessionId||r.activityTimeout||r.sessionPastMaximumLength||r.crossTabAdoption)&&(A.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:n,changeReason:r}),this.ui=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.hi()}hi(){var e;this.di=(e=this._instance.sessionManager)==null?void 0:e.onSessionId(this.li)}destroy(){var e;(e=this.di)==null||e.call(this),this.di=void 0}doPageView(e,n){var i,r=this.vi(e,n);return this.ui={pathname:(i=w?.location.pathname)!==null&&i!==void 0?i:"",pageViewId:n,timestamp:e},this._instance.scrollManager.resetContext(),r}doPageLeave(e){var n;return this.vi(e,(n=this.ui)==null?void 0:n.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.ui)==null?void 0:e.pageViewId}}vi(e,n){var i=this.ui;if(!i)return{$pageview_id:n};var r={$pageview_id:n,$prev_pageview_id:i.pageViewId},s=this._instance.scrollManager.getContext();if(s&&!this._instance.config.disable_scroll_properties){var o=s.maxScrollHeight,a=s.lastScrollY,l=s.maxScrollY,u=s.maxContentHeight,c=s.lastContentY,d=s.maxContentY;if(!(C(o)||C(a)||C(l)||C(u)||C(c)||C(d))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),d=Math.ceil(d);var f=o>1?At(a/o,0,1,A):1,h=o>1?At(l/o,0,1,A):1,p=u>1?At(c/u,0,1,A):1,g=u>1?At(d/u,0,1,A):1;r=fe(r,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:f,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:h,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:p,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return i.pathname&&(r.$prev_pageview_pathname=i.pathname),i.timestamp&&(r.$prev_pageview_duration=(e.getTime()-i.timestamp.getTime())/1e3),r}}var xo=["flags","surveys"],Qg={[Kd]:{exposure:"hidden"},[Fi]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[Ri]:{exposure:"hidden"},[ta]:{exposure:"event"},[na]:{exposure:"hidden"},[ia]:{exposure:"event"},[ra]:{exposure:"hidden"},[sa]:{exposure:"event"},[oa]:{exposure:"event"},[sl]:{exposure:"event"},[ol]:{exposure:"hidden"},[aa]:{exposure:"event"},[An]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[Kn]:{exposure:"hidden"},[al]:{exposure:"event"},[Yd]:{exposure:"event",shouldSkipFromEventProperties:t=>Ye(t)},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},$sess_rec_flush_size:{exposure:"hidden"},[Sn]:{exposure:"hidden",storageGroup:"flags"},[Ti]:{exposure:"hidden",storageGroup:"flags"},[Ar]:{exposure:"hidden"},[la]:{exposure:"hidden",storageGroup:"flags"},[$i]:{exposure:"hidden",storageGroup:"flags"},[Pr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[Zr]:{exposure:"hidden",storageGroup:"flags"},[It]:{exposure:"hidden"},[xn]:{exposure:"hidden"},[jt]:{exposure:"hidden"},[In]:{exposure:"hidden"},[ca]:{exposure:"hidden",storageGroup:"surveys"},[Xr]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[ua]:{exposure:"event"},[Fr]:{exposure:"hidden"},[Rr]:{exposure:"hidden"},[Mi]:{exposure:"hidden"},$product_tours_activated:{exposure:"hidden"},$product_tours_activated_session:{exposure:"hidden"},$conversations_widget_session_id:{exposure:"event"},$conversations_ticket_id:{exposure:"event"},$conversations_widget_state:{exposure:"event"},$conversations_user_traits:{exposure:"event"},[Cn]:{exposure:"hidden"},[Li]:{exposure:"hidden"},[Tr]:{exposure:"hidden"},[ji]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[at]:{exposure:"hidden"},[da]:{exposure:"hidden"},[fa]:{exposure:"hidden"},[ha]:{exposure:"hidden"},[pa]:{exposure:"hidden"},[Qr]:{exposure:"hidden"},[es]:{exposure:"hidden"},[Jd]:{exposure:"event"},[Zd]:{exposure:"event"},[Xd]:{exposure:"event"},[Qd]:{exposure:"event"},[tf]:{exposure:"event"},[nf]:{exposure:"event"},[rf]:{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"}},em=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],yn=t=>{var e=Qg[t];if(e)return e;for(var n of em){var i=n[1];if(t.indexOf(n[0])===0)return i}},Yn=(t,e)=>{try{return JSON.stringify(t,((n,i)=>typeof i=="bigint"?i.toString():i),e)}catch{return gd(t)}},ss=t=>{var e=P?.createElement("a");return C(e)?null:(e.href=t,e)},ii=function(t,e){for(var n,i=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),r=0;i.length>r;r++){var s=i[r].split("=");if(s[0]===e){n=s;break}}if(!U(n)||2>n.length)return"";var o=n[1];try{o=decodeURIComponent(o)}catch{A.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},Zi=function(t,e,n){if(!t||!e||!e.length)return t;for(var i=t.split("#"),r=i[1],s=(i[0]||"").split("?"),o=s[1],a=s[0],l=(o||"").split("&"),u=[],c=0;l.length>c;c++){var d=l[c].split("=");U(d)&&(e.includes(d[0])?u.push(d[0]+"="+n):u.push(l[c]))}var f=a;return o!=null&&(f+="?"+u.join("&")),r!=null&&(f+="#"+r),f},os=function(t,e){var n=t.match(new RegExp(e+"=([^&]*)"));return n?n[1]:null},wf=(t,e)=>t>=e&&fd(),bf=(t,e,n,i)=>{if(t===0){if(fd()){var r=e+1;return r===n&&i(),r}return e}return 0},wr="https?://(.*)",ri=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],tm=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...ri],Xi="",nm=["li_fat_id"];function Ef(t,e,n){if(!P)return{};var i,r=e?[...ri,...n||[]]:[],s=Sf(Zi(P.URL,r,Xi),t),o=(i={},ie(nm,(function(a){var l=sf(a);i[a]=l||null})),i);return fe(o,s)}function Sf(t,e){var n=tm.concat(e||[]),i={};return ie(n,(function(r){var s=ii(t,r);i[r]=s||null})),i}function xf(t){var e=(function(s){return s?s.search(wr+"google.([^/?]*)")===0?"google":s.search(wr+"bing.com")===0?"bing":s.search(wr+"yahoo.com")===0?"yahoo":s.search(wr+"duckduckgo.com")===0?"duckduckgo":null:null})(t),n=e!="yahoo"?"q":"p",i={};if(!Ye(e)){i.$search_engine=e;var r=P?ii(P.referrer,n):"";r.length&&(i.ph_keyword=r)}return i}function qc(){return navigator.language||navigator.userLanguage}var as="$direct";function If(){return P?.referrer||as}function kf(t,e,n){n===void 0&&(n=!1);var i=t?[...ri,...e||[]]:[],r=n?fn(me?.href):me?.href,s=r?.substring(0,1e3);return{r:If().substring(0,1e3),u:s?Zi(s,i,Xi):void 0}}function Cf(t,e){var n;e===void 0&&(e=!1);var i=t.r,r=t.u,s=e?fn(r):r,o={$referrer:i,$referring_domain:i==null?void 0:i==as?as:(n=ss(i))==null?void 0:n.host};if(s){o.$current_url=s;var a=ss(s);o.$host=a?.host,o.$pathname=a?.pathname;var l=Sf(s);fe(o,l)}if(i){var u=xf(i);fe(o,u)}return o}function Af(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function im(){try{return new Date().getTimezoneOffset()}catch{return}}var rm={flags:ji,surveys:Xr},sm=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],Hn="main";class Io{constructor(e,n,i){if(i===void 0&&(i=!0),this.ci={},this.fi=!1,this.pi=!1,this.Ne=e,this.gi=i,this.props={},this.mi=void 0,this.yi=(s=>{var o="";return s.token&&(o=s.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),s.persistence_name?"ph_"+s.persistence_name:"ph_"+o+"_posthog"})(e),this.ii=this.bi(e),this.pi=this.wi(e),this.load(),e.debug&&A.info("Persistence loaded",e.persistence,I({},this.props)),this.update_config(e,e,n),this.save(),w){var r=()=>this.flush();ve(w,"beforeunload",r,{capture:!1}),ve(w,"pagehide",r,{capture:!1})}}ki(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return ke(n)&&n>0?n:0}isDisabled(){return!!this.xi}bi(e){sm.indexOf(e.persistence.toLowerCase())===-1&&(A.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var n,i=(function(o,a){o===void 0&&(o=[]),a===void 0&&(a=!1);var l=[...Og,...o];return I({},le,{H(u){try{var c={};try{c=zt.H(u)||{}}catch{}var d,f=JSON.parse(le.P(u)||"{}");if(a){var h={};for(var p in c){var g=c[p];Ye(g)||g===""||(h[p]=g)}d=fe(f,h)}else d=fe(c,f);return le.F(u,d),d}catch{}return null},F(u,c,d,f,h,p){var g=le.F(u,c,void 0,void 0,p);try{var m={};l.forEach((v=>{c[v]&&(m[v]=c[v])})),Object.keys(m).length&&zt.F(u,m,d,f,h,p)}catch(v){le.j(v)}return g},q(u,c){try{w?.localStorage.removeItem(u),zt.q(u,c)}catch(d){le.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),r=!1,s=e.persistence.toLowerCase();return s==="localstorage"&&le.N()?(n=le,r=!0):s==="localstorage+cookie"&&i.N()?(n=i,r=!0):s==="sessionstorage"&&be.N()?n=be:s==="memory"?n=Bg:s==="cookie"?n=zt:i.N()?(n=i,r=!0):n=zt,this.fi=r,n}Si(e){return this.yi+"__"+e}wi(e){return this.fi&&!!e.split_storage}properties(){var e={};return ie(this.props,((n,i)=>{var r=yn(i);if(!r||r.exposure==="event"){if(r!=null&&r.shouldSkipFromEventProperties!=null&&r.shouldSkipFromEventProperties(n))return;e[i]=n}})),e}load(){if(!this.xi){var e=this.ii.H(this.yi);e&&(this.props=fe({},e)),this.pi&&this.Ci()}}Ci(){for(var e of xo){var n=le.H(this.Si(e));if(n&&!Kt(n)){var i=this.Mi(e);i.persisted=!0,this.Ti(e)||(i.fingerprint=this.Ei(n,e)),this.Ii(e,n)||fe(this.props,n)}}}Ti(e){return Object.keys(this.props).some((n=>{var i;return((i=yn(n))==null?void 0:i.storageGroup)===e}))}Ii(e,n){var i=rm[e];if(!i)return!1;var r=n[i],s=this.props[i];return ke(r)&&ke(s)&&s>r}refreshKey(e){var n;if(!this.xi){var i=this.pi?(n=yn(e))==null?void 0:n.storageGroup:void 0,r=i?le.H(this.Si(i)):this.ii.H(this.yi);if(r&&e in r)this.Pi(e,r[e]);else{if(i){var s=this.ii.H(this.yi);if(s&&e in s)return void this.Pi(e,s[e])}this.Ri(e)}}}save(){if(!this.xi){var e=this.ki();e>0?C(this.Ai)&&(this.Ai=setTimeout((()=>{this.Ai=void 0,this.Fi()}),e)):this.Fi()}}flush(){C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0,this.Fi())}Fi(){this.xi||(this.pi?this.Li():this.Oi(this.ii,this.yi,this.props,Hn))}Li(){var e=this.Di(),n=e.main,i=e.groups;for(var r of(this.Oi(this.ii,this.yi,n,Hn),xo)){var s,o=i[r];(!Kt(o)||(s=this.ci[r])!=null&&s.persisted)&&this.Oi(le,this.Si(r),o,r)}}Di(){var e={},n={flags:{},surveys:{}};return ie(this.props,((i,r)=>{var s,o=(s=yn(r))==null?void 0:s.storageGroup;o?n[o][r]=i:e[r]=i})),{main:e,groups:n}}Ei(e,n){if(n===Hn)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var i={};return ie(e,((r,s)=>{var o;i[s]=(o=yn(s))!=null&&o.volatile?"__volatile__":r})),JSON.stringify(i)}Oi(e,n,i,r){var s=this.Mi(r);if(r===Hn||s.dirty||C(s.fingerprint)){var o;try{if((o=this.Ei(i,r))===s.fingerprint)return void(s.dirty=!1)}catch{o=void 0}e.F(n,i,this.$i,this.Ni,this.qi,this.Ne.debug)?(s.dirty=!1,r!==Hn&&(s.persisted=!0),C(o)||(s.fingerprint=o)):this.Ne.debug&&A.warn('failed to persist storage entry "'+n+'"; will retry on next save')}}remove(e){var n=(e===void 0?{}:e).keepGroupEntries,i=n!==void 0&&n;if(C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0),this.ii.q(this.yi,!1),this.ii.q(this.yi,!0),!i&&this.gi)for(var r of xo)le.q(this.Si(r));i?delete this.ci[Hn]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,n,i){if(he(e)){C(n)&&(n="None"),this.$i=C(i)?this.ji:i;var r=!1;if(ie(e,((s,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==n||(this.Pi(o,s),r=!0)})),r)return this.save(),!0}return!1}register(e,n){if(he(e)){this.$i=C(n)?this.ji:n;var i=!1;if(ie(e,((r,s)=>{e.hasOwnProperty(s)&&(this.props[s]!==r||he(r)||U(r))&&(this.Pi(s,r),i=!0)})),i)return this.save(),!0}return!1}unregister(e){var n=typeof e=="string"?[e]:e,i=!1;for(var r of n)r in this.props&&(this.Ri(r),i=!0);i&&this.save()}update_campaign_params(){var e=P?.URL;if(e!==this.mi){var n=Ef(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);Kt(cl(n))||this.register(n),this.mi=e}}update_search_keyword(){var e;this.register((e=P?.referrer)?xf(e):{})}update_referrer_info(){var e;this.register_once({$referrer:If(),$referring_domain:P!=null&&P.referrer&&((e=ss(P.referrer))==null?void 0:e.host)||as},void 0)}set_initial_person_info(){this.props[ha]||this.props[pa]||this.register_once({[Qr]:kf(this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties,this.Ne.disable_capture_url_hashes)},void 0)}get_initial_props(){var e={};ie([pa,ha],(r=>{var s=this.props[r];s&&ie(s,(function(o,a){e["$initial_"+Ko(a)]=o}))}));var n=this.props[Qr];if(n){var i=(function(r,s){s===void 0&&(s=!1);var o=Cf(r,s),a={};return ie(o,(function(l,u){a["$initial_"+Ko(u)]=l})),a})(n,this.Ne.disable_capture_url_hashes);fe(e,i)}return e}safe_merge(e){return ie(this.props,(function(n,i){i in e||(e[i]=n)})),e}update_config(e,n,i){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!i),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var r=e.persistence!==n.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((f,h)=>f===d[h]))})(e.cookie_persisted_properties||[],n.cookie_persisted_properties||[]),s=r?this.bi(e):this.ii,o=this.wi(e);if(r||o!==this.pi){var a=this.props;this.clear(),this.ii=s,this.pi=o,this.props=a,this.save()}}set_disabled(e){this.xi=e,this.xi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ni&&(this.Ni=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this.qi&&(this.qi=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,n){var i=this.props[Ri]||{};i[e]=n,this.Pi(Ri,i),this.save()}remove_event_timer(e){var n=this.props[Ri]||{},i=n[e];return C(i)||(delete n[e],this.Pi(Ri,n),this.save()),i}get_property(e){return this.props[e]}set_property(e,n){this.Pi(e,n),this.save()}Pi(e,n){var i;this.props[e]=n,(i=yn(e))!=null&&i.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var n,i=(n=yn(e))==null?void 0:n.storageGroup;i&&(this.Mi(i).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function br(t){var e=!0;return{dispose(){if(e){e=!1;var n=t();n&&je(n.then)&&n.then(void 0,(()=>{}))}}}}var Ue={GZipJS:"gzip-js",Base64:"base64"},wi={Activation:"events",Cancellation:"cancelEvents"},ko={Popover:"popover",API:"api",Widget:"widget"},qt={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},Co={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},ya={Popover:"popover",Inline:"inline"},om={SHOWN:"product tour shown"},Vc={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},Gc=pe("[RateLimiter]");class am{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=n=>{var i=n.text;if(i&&i.length)try{(JSON.parse(i).quota_limited||[]).forEach((r=>{Gc.info((r||"events")+" is quota limited."),this.serverLimits[r]=new Date().getTime()+6e4}))}catch(r){return void Gc.warn('could not rate limit - continuing. Error: "'+r?.message+'"',{text:i})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var n,i,r;e===void 0&&(e=!1);var s=this.captureEventsBurstLimit,o=this.captureEventsPerSecond,a=new Date().getTime(),l=(n=(i=this.instance.persistence)==null?void 0:i.get_property(fa))!==null&&n!==void 0?n:{tokens:s,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>s&&(l.tokens=s);var u=1>l.tokens;if(u||e||(l.tokens=Math.max(0,l.tokens-1)),u&&!e){var c=(ke(l.dropped)?l.dropped:0)+1;l.dropped=c,!this.lastEventRateLimited&&this.Hi(c)&&(l.dropped=0)}return this.lastEventRateLimited=u,(r=this.instance.persistence)==null||r.set_property(fa,l),{isRateLimited:u,remainingTokens:l.tokens}}Ui(e){var n=this.instance.config.property_denylist;return!U(n)||!n.includes(e)}zi(){var e;if(this.Ui("$current_url")&&this.Ui("$pathname")&&me!=null&&me.pathname)return""+((e=me.origin)!==null&&e!==void 0?e:"")+me.pathname}Hi(e){var n,i,r=this.captureEventsBurstLimit,s=this.captureEventsPerSecond,o=this.zi(),a=this.Ui("$session_id")?(n=(i=this.instance).get_session_id)==null?void 0:n.call(i):void 0,l=[e+" event(s) dropped since the last warning",o?"triggered on "+o:void 0,a?"session "+a:void 0].filter(Boolean).join(", ");return!!this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited: "+l+". Config is set to "+s+" events per second and "+r+" events burst limit."},{skip_client_rate_limiting:!0})}isServerRateLimited(e){var n=this.serverLimits[e||"events"]||!1;return n!==!1&&new Date().getTime()e(this.remoteConfig))):e()}Vi(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:e})}load(){try{if(this.remoteConfig)return an.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void an.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return an.info("No config found after loading remote JS config. Falling back to JSON."),void this.Vi((n=>{this.Zi(n.json,n),this.Gi()}));this.Zi(e),this.Gi()}))}catch(e){an.error("Error loading remote config",e),this.Zi()}}stop(){this.Ki&&(clearInterval(this.Ki),this.Ki=void 0)}refresh(){!this._instance.Qi()&&P&&P.visibilityState!=="hidden"&&this._instance.reloadFeatureFlags()}Gi(){var e;if(!this.Ki){var n=(e=this._instance.config.remote_config_refresh_interval_ms)!==null&&e!==void 0?e:3e5;n!==0&&(this.Ki=setInterval((()=>{this.refresh()}),n))}}Zi(e,n){!e&&n&&(n.statusCode===0?n.error||an.warn("Failed to fetch remote config from PostHog."):an.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(r){an.error("Error applying remote config",r)}if(e?.hasFeatureFlags!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var i;(i=this._instance.featureFlags)==null||i.ensureFlagsLoaded()}catch(r){an.error("Error loading feature flags",r)}}}var ct=Uint8Array,Ke=Uint16Array,si=Uint32Array,hl=new ct([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]),pl=new ct([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]),Kc=new ct([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ff=function(t,e){for(var n=new Ke(31),i=0;31>i;++i)n[i]=e+=1<i;++i)for(var s=n[i];n[i+1]>s;++s)r[s]=s-n[i]<<5|i;return[n,r]},Rf=Ff(hl,2),wa=Rf[1];Rf[0][28]=258,wa[258]=28;for(var Yc=Ff(pl,0)[1],Tf=new Ke(32768),_e=0;32768>_e;++_e){var Wn=(43690&_e)>>>1|(21845&_e)<<1;Tf[_e]=((65280&(Wn=(61680&(Wn=(52428&Wn)>>>2|(13107&Wn)<<2))>>>4|(3855&Wn)<<4))>>>8|(255&Wn)<<8)>>>1}var Hi=function(t,e,n){for(var i=t.length,r=0,s=new Ke(e);i>r;++r)++s[t[r]-1];var o,a=new Ke(e);for(r=0;e>r;++r)a[r]=a[r-1]+s[r-1]<<1;for(o=new Ke(i),r=0;i>r;++r)o[r]=Tf[a[t[r]-1]++]>>>15-t[r];return o},$n=new ct(288);for(_e=0;144>_e;++_e)$n[_e]=8;for(_e=144;256>_e;++_e)$n[_e]=9;for(_e=256;280>_e;++_e)$n[_e]=7;for(_e=280;288>_e;++_e)$n[_e]=8;var ls=new ct(32);for(_e=0;32>_e;++_e)ls[_e]=5;var lm=Hi($n,9),cm=Hi(ls,5),$f=function(t){return(t/8>>0)+(7&t&&1)},Mf=function(t,e,n){(n==null||n>t.length)&&(n=t.length);var i=new(t instanceof Ke?Ke:t instanceof si?si:ct)(n-e);return i.set(t.subarray(e,n)),i},Ot=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8},bi=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8,t[i+2]|=n>>>16},Ao=function(t,e){for(var n=[],i=0;t.length>i;++i)t[i]&&n.push({s:i,f:t[i]});var r=n.length,s=n.slice();if(!r)return[new ct(0),0];if(r==1){var o=new ct(n[0].s+1);return o[n[0].s]=1,[o,1]}n.sort((function(b,k){return b.f-k.f})),n.push({s:-1,f:25001});var a=n[0],l=n[1],u=0,c=1,d=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=r-1;)a=n[n[d].f>n[u].f?u++:d++],l=n[u!=c&&n[d].f>n[u].f?u++:d++],n[c++]={s:-1,f:a.f+l.f,l:a,r:l};var f=s[0].s;for(i=1;r>i;++i)s[i].s>f&&(f=s[i].s);var h=new Ke(f+1),p=ba(n[c-1],h,0);if(p>e){i=0;var g=0,m=p-e,v=1<i;++i){var E=s[i].s;if(e>=h[E])break;g+=v-(1<>>=m;g>0;){var S=s[i].s;e>h[S]?g-=1<=0&&g;--i){var _=s[i].s;h[_]==e&&(--h[_],++g)}p=e}return[new ct(h),p]},ba=function(t,e,n){return t.s==-1?Math.max(ba(t.l,e,n+1),ba(t.r,e,n+1)):e[t.s]=n},Jc=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new Ke(++e),i=0,r=t[0],s=1,o=function(l){n[i++]=l},a=1;e>=a;++a)if(t[a]==r&&a!=e)++s;else{if(!r&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(r),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(r);s=1,r=t[a]}return[n.subarray(0,i),e]},Ei=function(t,e){for(var n=0,i=0;e.length>i;++i)n+=t[i]*e[i];return n},Ea=function(t,e,n){var i=n.length,r=$f(e+2);t[r]=255&i,t[r+1]=i>>>8,t[r+2]=255^t[r],t[r+3]=255^t[r+1];for(var s=0;i>s;++s)t[r+s+4]=n[s];return 8*(r+4+i)},Zc=function(t,e,n,i,r,s,o,a,l,u,c){Ot(e,c++,n),++r[256];for(var d=Ao(r,15),f=d[0],h=d[1],p=Ao(s,15),g=p[0],m=p[1],v=Jc(f),E=v[0],S=v[1],_=Jc(g),b=_[0],k=_[1],T=new Ke(19),x=0;E.length>x;++x)T[31&E[x]]++;for(x=0;b.length>x;++x)T[31&b[x]]++;for(var F=Ao(T,7),$=F[0],O=F[1],L=19;L>4&&!$[Kc[L-1]];--L);var N,K,V,M,R=u+5<<3,Z=Ei(r,$n)+Ei(s,ls)+o,Ce=Ei(r,f)+Ei(s,g)+o+14+3*L+Ei(T,$)+(2*T[16]+3*T[17]+7*T[18]);if(Z>=R&&Ce>=R)return Ea(e,c,t.subarray(l,l+u));if(Ot(e,c,1+(Z>Ce)),c+=2,Z>Ce){N=Hi(f,h),K=f,V=Hi(g,m),M=g;var oe=Hi($,O);for(Ot(e,c,S-257),Ot(e,c+5,k-1),Ot(e,c+10,L-4),c+=14,x=0;L>x;++x)Ot(e,c+3*x,$[Kc[x]]);c+=3*L;for(var ye=[E,b],$e=0;2>$e;++$e){var ae=ye[$e];for(x=0;ae.length>x;++x)Ot(e,c,oe[Ie=31&ae[x]]),c+=$[Ie],Ie>15&&(Ot(e,c,ae[x]>>>5&127),c+=ae[x]>>>12)}}else N=lm,K=$n,V=cm,M=ls;for(x=0;a>x;++x)if(i[x]>255){var Ie;bi(e,c,N[257+(Ie=i[x]>>>18&31)]),c+=K[Ie+257],Ie>7&&(Ot(e,c,i[x]>>>23&31),c+=hl[Ie]);var Se=31&i[x];bi(e,c,V[Se]),c+=M[Se],Se>3&&(bi(e,c,i[x]>>>5&8191),c+=pl[Se])}else bi(e,c,N[i[x]]),c+=K[i[x]];return bi(e,c,N[256]),c+K[256]},um=new si([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),dm=(function(){for(var t=new si(256),e=0;256>e;++e){for(var n=e,i=9;--i;)n=(1&n&&3988292384)^n>>>1;t[e]=n}return t})(),Po=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8};function fm(t,e){e===void 0&&(e={});var n=(function(){var d=4294967295;return{p(f){for(var h=d,p=0;f.length>p;++p)h=dm[255&h^f[p]]^h>>>8;d=h},d(){return 4294967295^d}}})(),i=t.length;n.p(t);var r,s,o,a,l,u=(a=10+((r=e).filename&&r.filename.length+1||0),l=8,(function(d,f,h,p,g,m){var v=d.length,E=new ct(p+v+5*(1+Math.floor(v/7e3))+g),S=E.subarray(p,E.length-g),_=0;if(!f||8>v)for(var b=0;v>=b;b+=65535){var k=b+65535;v>k?_=Ea(S,_,d.subarray(b,k)):(S[b]=!0,_=Ea(S,_,d.subarray(b,v)))}else{for(var T=um[f-1],x=T>>>13,F=8191&T,$=(1<b;++b){var Ie=V(b),Se=32767&b,De=L[Ie];if(O[Se]=De,L[Ie]=Se,b>=$e){var wt=v-b;if((Ce>7e3||ye>24576)&&wt>423){_=Zc(d,S,0,M,R,Z,oe,ye,ae,b-ae,_),ye=Ce=oe=0,ae=b;for(var ge=0;286>ge;++ge)R[ge]=0;for(ge=0;30>ge;++ge)Z[ge]=0}var Je=2,bt=0,mn=F,Re=Se-De&32767;if(wt>2&&Ie==V(b-Re))for(var Pe=Math.min(x,wt)-1,$t=Math.min(32767,b),Bn=Math.min(258,wt);$t>=Re&&--mn&&Se!=De;){if(d[b+Je]==d[b+Je-Re]){for(var qe=0;Bn>qe&&d[b+qe]==d[b+qe-Re];++qe);if(qe>Je){if(Je=qe,bt=Re,qe>Pe)break;var Dn=Math.min(Re,qe-2),Mt=0;for(ge=0;Dn>ge;++ge){var Lt=b-Re+ge+32768&32767,ut=Lt-O[Lt]+32768&32767;ut>Mt&&(Mt=ut,De=Lt)}}}Re+=(Se=De)-(De=O[Se])+32768&32767}if(bt){M[ye++]=268435456|wa[Je]<<18|Yc[bt];var sn=31&wa[Je],gi=31&Yc[bt];oe+=hl[sn]+pl[gi],++R[257+sn],++Z[gi],$e=b+Je,++Ce}else M[ye++]=d[b],++R[d[b]]}}_=Zc(d,S,!0,M,R,Z,oe,ye,ae,b-ae,_)}return Mf(E,0,p+$f(_)+g)})(s=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):12+o.mem,a,l)),c=u.length;return(function(d,f){var h=f.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>f.level?4:f.level==9?2:0,d[9]=3,f.mtime!=0&&Po(d,4,Math.floor(new Date(f.mtime||Date.now())/1e3)),h){d[3]=8;for(var p=0;h.length>=p;++p)d[p+10]=h.charCodeAt(p)}})(u,e),Po(u,c-8,n.d()),Po(u,c-4,i),u}var hm=!!qo||!!Xa,Lf="text/plain",Mr=!1,Nf=(t,e)=>{var n=t.split("#"),i=n[1],r=n[0].split("?"),s=r[0],o=r[1];if(!o)return t;var a=o.split("&").filter((l=>l.split("=")[0]!==e)).join("&");return s+(a?"?"+a:"")+(i?"#"+i:"")},Cs=function(t,e,n){var i;n===void 0&&(n=!0);var r=t.split("?"),s=r[0],o=r[1],a=I({},e),l=(i=o?.split("&").map((c=>{var d,f=c.split("="),h=f[0],p=n&&(d=a[h])!==null&&d!==void 0?d:f[1];return delete a[h],h+"="+p})))!==null&&i!==void 0?i:[],u=(function(c,d){var f,h;d===void 0&&(d="&");var p=[];return ie(c,(function(g,m){C(g)||C(m)||m==="undefined"||(f=encodeURIComponent((v=>v instanceof File)(g)?g.name:g.toString()),h=encodeURIComponent(m),p[p.length]=h+"="+f)})),p.join(d)})(a);return u&&l.push(u),l.length>0?s+"?"+l.join("&"):s},Fo=t=>{if(t.Ji)return t.Ji;var e=t.data,n=t.compression;if(e){if(n===Ue.GZipJS){var i=fm((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new ct(a.length+(a.length>>>1)),d=0,f=function(m){c[d++]=m},h=0;u>h;++h){if(d+5>c.length){var p=new ct(d+8+(u-h<<1));p.set(c),c=p}var g=a.charCodeAt(h);128>g?f(g):2048>g?(f(192|g>>>6),f(128|63&g)):g>55295&&57344>g?(f(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++h))>>>18),f(128|g>>>12&63),f(128|g>>>6&63),f(128|63&g)):(f(224|g>>>12),f(128|g>>>6&63),f(128|63&g))}return Mf(c,0,d)})(Yn(e)),{mtime:0});return{contentType:Lf,body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),estimatedSize:i.byteLength}}if(n===Ue.Base64){var r=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(Yn(e)),s=(a=>"data="+encodeURIComponent(typeof a=="string"?a:Yn(a)))(r);return{contentType:"application/x-www-form-urlencoded",body:s,estimatedSize:new Blob([s]).size}}var o=Yn(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},Of=t=>{var e,n,i=()=>t.transport==="sendBeacon"?{url:Cs(t.url,{compression:Ue.Base64}),encodedBody:Fo(I({},t,{compression:Ue.Base64,Ji:void 0}))}:{url:Nf(t.url,"compression"),encodedBody:Fo(I({},t,{compression:void 0,Ji:void 0}))};try{e=Fo(t)}catch(r){if(vc(t.compression,ii(t.url,"compression")))return A.error("Failed to gzip request body, sending uncompressed payload",r),i();throw r}return e&&vc(t.compression,ii(t.url,"compression"))&&!((n=e.body)instanceof ArrayBuffer?Vo(new Uint8Array(n)):ArrayBuffer.isView(n)&&Vo(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)))?(Mr=!0,i()):{url:t.url,encodedBody:e}},Bf=t=>{try{return Of(t)}catch(e){return A.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},pm=(function(){var t=se((function*(e){var n=Yn(e.data),i=yield(function(s,o,a){return Go.apply(this,arguments)})(n,ne.DEBUG,{rethrow:!0});if(!i)return e;var r=yield i.arrayBuffer();return I({},e,{Ji:{contentType:Lf,body:r,estimatedSize:r.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),gm=/Failed to fetch|NetworkError|Load failed/i,Df=t=>t?.name==="TypeError"&&gm.test(t?.message||""),jf=t=>{var e=Bf(t);if(e){var n=e.url,i=e.encodedBody,r=i??{},s=r.contentType,o=r.body,a=r.estimatedSize,l=new Headers;ie(t.headers,(function(p,g){l.append(g,p)})),s&&l.append("Content-Type",s);var u=null,c=!1;if(dc){var d=new dc;u={signal:d.signal,timeout:setTimeout((()=>{var p,g;c=!0,d.abort((p=t.timeout,(g=new Error("PostHog request timed out"+(p?" after "+p+"ms":""))).name="AbortError",g))}),t.timeout)}}var f=p=>{c&&p?.name==="AbortError"||Df(p)?A.warn(p):A.error(p),t.callback==null||t.callback({statusCode:0,error:p})};try{var h;Xa(n,I({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(h=u)==null?void 0:h.signal},t.fetchOptions)).then((p=>p.text().then((g=>{var m={statusCode:p.status,text:g};if(p.status===200)try{m.json=JSON.parse(g)}catch(v){A.error(v)}t.callback==null||t.callback(m)})))).catch(f).finally((()=>u?clearTimeout(u.timeout):null))}catch(p){u&&clearTimeout(u.timeout),f(p)}}},Sa=t=>{try{var e,n=Of(t),i=n.url,r=n.encodedBody,s=r??{},o=s.body,a=s.estimatedSize;if(!o)return;var l=o instanceof Blob?o:new Blob([o],{type:s.contentType});if(He.sendBeacon(i,l))return;var u=U(t.data)?t.data:(e=t.data)==null?void 0:e.batch;if(U(u)&&u.length>1&&(a??0)>16384){var c=Math.ceil(u.length/2),d=f=>U(t.data)?f:I({},t.data,{batch:f});return Sa(I({},t,{data:d(u.slice(0,c))})),void Sa(I({},t,{data:d(u.slice(c))}))}A.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),jf(I({},t,{Yi:!0}))}catch(f){A.warn("Beacon send failed",f)}},Xc=(t,e,n,i)=>{var r=i==="query"?e==="POST"?"sent_at":"_":void 0;return Cs(n===Ue.GZipJS?Nf(t,"compression"):t,I({},r?{[r]:Date.now().toString()}:{},n===Ue.GZipJS?{}:{compression:n}))},Lr=[];Xa&&Lr.push({transport:"fetch",method:jf}),qo&&Lr.push({transport:"XHR",method(t){var e=Bf(t);if(e){var n=new qo,i=e.encodedBody;n.open(t.method||"GET",e.url,!0);var r=i??{},s=r.contentType,o=r.body;ie(t.headers,(function(a,l){n.setRequestHeader(l,a)})),s&&n.setRequestHeader("Content-Type",s),t.timeout&&(n.timeout=t.timeout),n.onreadystatechange=()=>{if(n.readyState===4){var a={statusCode:n.status,text:n.responseText};if(n.status===200)try{a.json=JSON.parse(n.responseText)}catch{}t.callback==null||t.callback(a)}},n.send(o)}}}),He!=null&&He.sendBeacon&&Lr.push({transport:"sendBeacon",method:Sa});var xa=3e3;class mm{constructor(e,n){this.Xi=!0,this.tr=[],this.er=At(n?.flush_interval_ms||xa,250,5e3,A.createLogger("flush interval"),xa),this.ir=e}enqueue(e){this.tr.push(e),this.rr||this.nr()}unload(){this.sr();var e=this.tr.length>0?this.ar():{},n=Object.values(e);[...n.filter((i=>i.url.indexOf("/e")===0)),...n.filter((i=>i.url.indexOf("/e")!==0))].map((i=>{this.lr(I({},i,{transport:"sendBeacon"}))}))}enable(){this.Xi=!1,this.nr()}nr(){var e=this;this.Xi||(this.rr=setTimeout((()=>{if(this.sr(),this.tr.length>0){var n=this.ar(),i=function(){var s=n[r],o=new Date().getTime();s.data&&U(s.data)&&ie(s.data,(a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp})),e.lr(s)};for(var r in n)i()}}),this.er))}lr(e){try{this.ir(e)}catch(n){A.error(n)}}sr(){clearTimeout(this.rr),this.rr=void 0}ar(){var e={};return ie(this.tr,(n=>{var i,r=n,s=(r?r.batchKey:null)||r.url;C(e[s])&&(e[s]=I({},r,{data:[]})),(i=e[s].data)==null||i.push(r.data)})),this.tr=[],e}}var vm=["retriesPerformedSoFar"];class _m{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!C(w)&&"onLine"in w.navigator&&(this.dr=w.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},ve(w,"online",this.vr),ve(w,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var n=e.retriesPerformedSoFar,i=hd(e,vm);Dt(n)&&(i.url=Cs(i.url,{retry_count:n})),this._instance._send_request(I({},i,{callback:r=>{if(r.statusCode!==200&&(400>r.statusCode||r.statusCode>=500)){if((r.statusCode===0?3:10)>(n??0))return void this.At(I({retriesPerformedSoFar:n},i));r.statusCode===0&&A.warn("Request failed before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped retrying after "+(n??0)+" retries.")}i.callback==null||i.callback(r)}}))}At(e){var n=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=n+1;var i=(function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),c=Math.random()-.5;return Math.ceil(u+c*(u-l))})(n),r=Date.now()+i;this.tr.push({retryAt:r,requestOptions:e});var s="Enqueued failed request for retry in "+i;navigator.onLine||(s+=" (Browser is offline)"),A.warn(s),this.ur||(this.ur=!0,this.gr())}gr(){if(this.mr&&clearTimeout(this.mr),this.tr.length===0)return this.ur=!1,void(this.mr=void 0);this.mr=setTimeout((()=>{this.dr&&this.tr.length>0&&this.cr(),this.gr()}),this.hr)}cr(){var e=Date.now(),n=[],i=this.tr.filter((s=>e>s.retryAt||(n.push(s),!1)));if(this.tr=n,i.length>0)for(var r of i)this.retriableRequest(r.requestOptions)}unload(){for(var e of(this.mr&&(clearTimeout(this.mr),this.mr=void 0),this.ur=!1,C(w)||(this.vr&&(w.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(w.removeEventListener("offline",this.pr),this.pr=void 0)),this.tr)){var n=e.requestOptions;try{this._instance._send_request(I({},n,{transport:"sendBeacon"}))}catch(i){A.error(i)}}this.tr=[]}}class ym{constructor(e){this.yr=()=>{var n,i,r,s;this.br||(this.br={});var o=this.scrollElement(),a=this.scrollY(),l=o?Math.max(0,o.scrollHeight-o.clientHeight):0,u=a+(o?.clientHeight||0),c=o?.scrollHeight||0;this.br.lastScrollY=Math.ceil(a),this.br.maxScrollY=Math.max(a,(n=this.br.maxScrollY)!==null&&n!==void 0?n:0),this.br.maxScrollHeight=Math.max(l,(i=this.br.maxScrollHeight)!==null&&i!==void 0?i:0),this.br.lastContentY=u,this.br.maxContentY=Math.max(u,(r=this.br.maxContentY)!==null&&r!==void 0?r:0),this.br.maxContentHeight=Math.max(c,(s=this.br.maxContentHeight)!==null&&s!==void 0?s:0)},this._instance=e}get _r(){return this._instance.config.scroll_root_selector}getContext(){return this.br}resetContext(){var e=this.br;return setTimeout(this.yr,0),e}startMeasuringScrollPosition(){ve(w,"scroll",this.yr,{capture:!0}),ve(w,"scrollend",this.yr,{capture:!0}),ve(w,"resize",this.yr)}scrollElement(){if(!this._r)return w?.document.documentElement;var e=U(this._r)?this._r:[this._r];for(var n of e){var i=w?.document.querySelector(n);if(i)return i}}wr(e){var n=e==="y"?"scrollTop":"scrollLeft";if(this._r){var i=this.scrollElement();return i&&i[n]||0}return w?e==="y"?w.scrollY||w.pageYOffset||w.document.documentElement.scrollTop||0:w.scrollX||w.pageXOffset||w.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var wm=t=>kf(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class Qc{constructor(e,n,i,r){this.kr=s=>{var o=this.Sr();if(!o||o.sessionId!==s){var a={sessionId:s,props:this.Cr(this._instance)};this.Mr.register({[da]:a})}},this._instance=e,this.Tr=n,this.Mr=i,this.Cr=r||wm,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[da]}getSetOnceProps(){var e,n=(e=this.Sr())==null?void 0:e.props;return n?"r"in n?Cf(n,this._instance.config.disable_capture_url_hashes):{$referring_domain:n.referringDomain,$pathname:n.initialPathName,utm_source:n.utm_source,utm_campaign:n.utm_campaign,utm_medium:n.utm_medium,utm_content:n.utm_content,utm_term:n.utm_term}:{}}getSessionProps(){var e={};return ie(cl(this.getSetOnceProps()),((n,i)=>{i==="$current_url"&&(i="url"),e["$session_entry_"+Ko(i)]=n})),e}}class gl{on(e,n){return this.Er[e]||(this.Er[e]=[]),this.Er[e].push(n),()=>{this.Er[e]=this.Er[e].filter((i=>i!==n))}}emit(e,n){for(var i of this.Er[e]||[])i(n);for(var r of this.Er["*"]||[])r(e,n)}constructor(){this.Er={}}}var Si=pe("[SessionId]");class eu{on(e,n){return this.Ir.on(e,n)}constructor(e,n,i){var r;if(this.Pr=null,this.Rr=[],this.Ar=void 0,this.Fr=!1,this.Ir=new gl,this.Lr=(u,c)=>!(!Dt(u)||!Dt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===Wt)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Ne=e.config,this.Mr=e.persistence,this.Or=void 0,this.Dr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.$r=n||Ht,this.Nr=i||Ht;var s=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*At(this.Ne.session_idle_timeout_seconds||1800,60,36e3,Si.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.qr(),this.jr="ph_"+s+"_window_id",this.Br="ph_"+s+"_primary_window_exists",this.Hr()){var o=be.H(this.jr),a=be.H(this.Br);o&&!a?this.Or=o:be.q(this.jr),be.F(this.Br,!0)}if((r=this.Ne.bootstrap)!=null&&r.sessionID)try{var l=(u=>{var c=this.Ne.bootstrap.sessionID.replace(/-/g,"");if(c.length!==32)throw new Error("Not a valid UUID");if(c[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(c.substring(0,12),16)})();this.Ur(this.Ne.bootstrap.sessionID,new Date().getTime(),l)}catch(u){Si.error("Invalid sessionID in bootstrap",u)}this.zr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return C(this.Rr)&&(this.Rr=[]),this.Rr.push(e),this.Dr&&e(this.Dr,this.Or),()=>{this.Rr=this.Rr.filter((n=>n!==e))}}Hr(){return this.Ne.persistence!=="memory"&&!this.Mr.xi&&be.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&be.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?be.H(this.jr):null}Zr(e){var n=this.Pr;return!Ye(n)&&!Ye(e)&&5e3>Math.abs(e-n)}Ur(e,n,i){var r=n!==this._sessionActivityTimestamp,s=!(e!==this.Dr||i!==this._sessionStartTimestamp);this._sessionStartTimestamp=i,this._sessionActivityTimestamp=n,this.Dr=e,s&&!r||s&&this.Zr(n)||(this.Pr=n,this.Mr.register({[Kn]:[n,e,i]}))}Gr(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return Dt(n)&&n>0}Qr(){this.Gr()?this.Mr.refreshKey(Kn):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!Ye(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this.Pr){this.Qr();var n=this.Jr();n[1]===this.Dr&&n[2]===this._sessionStartTimestamp&&(this.Pr=this._sessionActivityTimestamp,this.Mr.register({[Kn]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],n=Dt(e)?e:0,i=Dt(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(n,i)}Xr(e){return this.Qr(),this.Lr(e,this.Yr())}Jr(){var e=this.Mr.props[Kn];return U(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Pr=null,clearTimeout(this.tn),this.tn=void 0,this.Ur(null,null,null)}destroy(){this.Fr=!0,this.Kr(),clearTimeout(this.tn),this.tn=void 0,this.Ar&&w&&(w.removeEventListener(ns,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&be.q(this.Br)},ve(w,ns,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=null),this.Ne.cookieless_mode===Wt)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var i=n||new Date().getTime(),r=this.Jr(),s=r[1],o=r[2],a=this.Yr(),l=this.Vr(),u=Dt(o)&&Math.abs(i-o)>864e5,c=!1,d=!1,f=!s,h=s,p=!f&&!e&&this.Lr(i,a);if(p){(p=this.Xr(i))||Si.info("cross-tab refresh kept the session alive",{sessionId:s});var g=this.Jr();s=g[1],o=g[2]}f||p||u?(s=this.$r(),l=this.Nr(),Si.info("new session ID generated",{sessionId:s,windowId:l,changeReason:{noSessionId:f,activityTimeout:p,sessionPastMaximumLength:u}}),o=i,c=!0):(l||(l=this.Nr(),c=!0),(d=s!==h)&&(Si.info("adopted cross-tab session id",{sessionId:s,windowId:l}),c=!0));var m=Dt(a)&&e&&!u?a:i,v=Dt(o)?o:new Date().getTime();this.Wr(l),this.Ur(s,m,v),e||this.qr();var E={noSessionId:f,activityTimeout:p,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((S=>S(s,l,E))),{sessionId:s,windowId:l,sessionStartTimestamp:v,changeReason:c?E:void 0,lastActivityTimestamp:a}}qr(){this.Fr||(clearTimeout(this.tn),this.tn=setTimeout((()=>{if(!this.Fr)if(this.Xr(new Date().getTime())){var e=this.Dr;this.resetSessionId(),this.Ir.emit("forcedIdleReset",{idleSessionId:e})}else this.qr()}),1.1*this.sessionTimeoutMs))}}var Uf=function(t,e){if(!t)return!1;var n=t.userAgent;if(n&&yc(n,e))return!0;try{var i=t?.userAgentData;if(i!=null&&i.brands&&i.brands.some((r=>yc(r?.brand,e))))return!0}catch{}return!!t.webdriver};function Hf(){return(Hf=se((function*(){var t=He?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),n=e?.model;return X(n)&&n.length>0?n:void 0}catch(i){return void A.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",i)}}))).apply(this,arguments)}var cs=function(t,e){if(!(function(n){try{new RegExp(n)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function Ro(t,e,n){return Yn({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}var Wf={exact:(t,e)=>e.some((n=>t.some((i=>n===i)))),is_not:(t,e)=>e.every((n=>t.every((i=>n!==i)))),regex:(t,e)=>e.some((n=>t.some((i=>cs(n,i))))),not_regex:(t,e)=>e.every((n=>t.every((i=>!cs(n,i))))),icontains:(t,e)=>e.map(Er).some((n=>t.map(Er).some((i=>n.includes(i))))),not_icontains:(t,e)=>e.map(Er).every((n=>t.map(Er).every((i=>!n.includes(i))))),gt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>i>parseFloat(r)))})),lt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>it.toLowerCase();function zf(t,e){return!t||Object.entries(t).every((n=>{var i=n[1],r=e?.[n[0]];if(C(r)||Ye(r))return!1;var s=[String(r)],o=Wf[i.operator];return!!o&&o(i.values,s)}))}var Ia="custom",tu="i.posthog.com",bm=/^\/static\//;class Em{constructor(e){this.en={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,n=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return n||(n=this.apiHost.replace("."+tu,".posthog.com")),n==="https://app.posthog.com"?"https://us.posthog.com":n}get region(){return this.en[this.apiHost]||(this.en[this.apiHost]=/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"us":/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"eu":Ia),this.en[this.apiHost]}rn(e){if(bm.test(e)){var n=this.instance.config.asset_host;if(typeof n=="string")return n.trim().replace(/\/$/,"")||void 0}}endpointFor(e,n){if(n===void 0&&(n=""),n&&(n=n[0]==="/"?n:"/"+n),e==="ui")return this.uiHost+n;if(e==="flags")return this.flagsApiHost+n;if(e==="assets"){var i=this.rn(n);if(i)return""+i+n}if(this.region===Ia)return this.apiHost+n;var r=tu+n;switch(e){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}}function qf(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var Q=pe("[Surveys]"),Vf="seenSurvey_",Gf=t=>{try{var e=(n=>((i,r)=>""+Vf+(function(s){return s.current_iteration&&s.current_iteration>0?s.id+"_"+s.current_iteration:s.id})(r))(0,n))(t);if(localStorage.getItem(e))return;localStorage.setItem(e,"true")}catch(n){Q.error("Failed to persist survey seen state",n)}},Sm=[ko.Popover,ko.Widget,ko.API],xm={ignoreConditions:!1,ignoreDelay:!1,displayType:ya.Popover},Im=pe("[PostHog ExternalIntegrations]"),km={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class Cm{constructor(e){this._instance=e}ai(e,n){var i;(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,e,(r=>{if(r)return Im.error("failed to load script",r);n()}))}startIfEnabledOrStop(){var e=this,n=function(){var s,o,a,l=i[0],u=i[1];!u||(s=B.__PosthogExtensions__)!=null&&(s=s.integrations)!=null&&s[l]||e.ai(km[l],(()=>{var c;(c=B.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=B.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=B.__PosthogExtensions__)==null||(a=a.integrations)==null||(a=a[l])==null||a.stop())};for(var i of Object.entries((r=this._instance.config.integrations)!==null&&r!==void 0?r:{})){var r;n()}}}class Am{constructor(e,n){this.rt=e,this.nn=n,this.sn=new Map,this.an=!1}add(e){var n=this;return se((function*(){if(n.an)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(n.sn.has(e.name))throw new Error('Browser extension "'+e.name+'" is already registered');n.sn.set(e.name,e);try{var i=e.setup(n.nn);i&&(yield i)}catch(s){var r=n.sn.get(e.name)===e;r&&n.sn.delete(e.name),n.rt.error('Failed to set up browser extension "'+e.name+'"',s),r&&n.ln(e)}}))()}dispose(){if(!this.an){this.an=!0;var e=Array.from(this.sn.values()).reverse();for(var n of(this.sn.clear(),e))this.ln(n)}}ln(e){try{var n=e.dispose==null?void 0:e.dispose();n&&je(n.then)&&n.then(void 0,(i=>{this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}))}catch(i){this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}}}class Pm{constructor(e){this._instance=e}initialize(){}get(e){var n=this._instance.persistence;if(typeof e=="string")return n?.get_property(e);var i={};for(var r of e){var s=n?.get_property(r);C(s)||(i[r]=s)}return i}set(e,n){var i;(i=this._instance.persistence)==null||i.register(typeof e=="string"?{[e]:n}:e)}remove(e){var n;(n=this._instance.persistence)==null||n.unregister(e)}}var nu="extensionsRemoteConfig";class Fm{constructor(e){this.an=!1,this.instance=e,this.rt=A,this.un=e.hn,this.kv=new Pm(e),this.onEvent=n=>br(this.instance.on("eventCaptured",(i=>{try{n({event:i.event,properties:i.properties})}catch(r){this.rt.error("Browser extension event listener failed",r)}}))),this.onRemoteConfig=n=>{if(this.an)return br((()=>{}));var i=s=>{try{n(s)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},r=this.instance.dn.on(nu,i);return this.un&&i(this.un),br(r)},this.vn=new Am(A.createLogger("[BrowserExtensions]"),this)}get logger(){return this.rt}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return(e=this.instance.get_property(Yi))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(Yi);return typeof e=="string"?e:void 0}get library(){return{name:ne.LIB_NAME,version:ne.LIB_VERSION}}get initialPersonProperties(){var e,n;return(e=(n=this.instance.persistence)==null?void 0:n.get_initial_props())!==null&&e!==void 0?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,n,i,r,s=(e=this.instance.sessionManager)==null?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:(n=s?.sessionId)!==null&&n!==void 0?n:"",windowId:(i=s?.windowId)!==null&&i!==void 0?i:"",sessionStartTimestamp:(r=s?.sessionStartTimestamp)!==null&&r!==void 0?r:0}}catch{return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get projectToken(){return this.instance.config.token}add(e){return this.vn.add(e)}capture(e,n,i){var r=this;return se((function*(){i?r.instance.capture(e,n,{timestamp:i.timestamp,uuid:i.uuid,$set:i.set,$set_once:i.setOnce}):r.instance.capture(e,n)}))()}registerDynamicEventProperties(e){return br(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(nu,e))}sendRequest(e,n){var i=this;return se((function*(){var r;n===void 0&&(n={});var s=i.instance.requestRouter.endpointFor((r=n.target)!==null&&r!==void 0?r:"api",e),o={method:n.method,url:n.query?Cs(s,n.query):s,data:n.body,headers:n.headers,timeout:n.timeoutMs,fireCallbackOnDrop:!0,transport:n.transport,compression:n.compression,timestampMode:n.sentAt};return n.transport==="sendBeacon"?(i.instance._send_request(o),{statusCode:202}):new Promise((a=>{o.callback=a,i.instance._send_request(o)}))}))()}dispose(){this.an||(this.an=!0,this.vn.dispose())}}var Wi={},To=0,us=()=>{},iu='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',xi="Surveys module not available",ru="sanitize_properties is deprecated. Use before_send instead",Kf="Invalid value for property_denylist config: ",Rm=["token","distinct_id",ef],Gn="posthog",Yf=!hm&&Ge?.indexOf("MSIE")===-1&&Ge?.indexOf("Mozilla")===-1,$o=t=>{var e;return I({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:Tg(P?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:us,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:t??"unset",__preview_deferred_init_extensions:!1,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:me&&X(me?.search)&&me.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disableDeviceModel:!1,disable_external_dependency_loading:!1,strict_script_versioning:!1,enable_recording_console_log:void 0,secure_cookie:(w==null||(e=w.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(n){A.error("Bad HTTP status: "+n.statusCode+" "+n.text)},get_device_id:n=>n,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:ga,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:xa},error_tracking:{},_onCapture:us},(n=>({rageclick:n&&n>="2026-05-30"?{content_ignorelist:zg,ignore_text_selection:!0}:!n||"2025-11-30">n||{content_ignorelist:!0},capture_pageview:!n||"2025-05-24">n||"history_change",session_recording:n&&n>="2026-06-25"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6},streamNetworkBody:!0}:n&&n>="2026-05-30"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6}}:n&&n>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:n&&n>="2026-01-30"?"head":"body",internal_or_test_user_hostname:n&&n>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:n&&n>="2026-05-30"?250:0,split_storage:!(!n||"2026-05-30">n),detect_google_search_app:!(!n||"2026-05-30">n),disable_capture_url_hashes:!(!n||"2026-06-25">n)}))(t))},Tm=[["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"]],su=t=>{var e={};for(var n of Tm){var i=n[0],r=n[1];C(t[i])||(e[r]=t[i])}var s=fe({},e,t),o=t.__preview_external_dependency_versioned_paths;return C(o)||(C(t.strict_script_versioning)&&(s.strict_script_versioning=!!o),X(o)&&C(t.asset_host)&&(s.asset_host=o)),U(t.property_blacklist)&&(C(t.property_denylist)?s.property_denylist=t.property_blacklist:U(t.property_denylist)?s.property_denylist=[...t.property_blacklist,...t.property_denylist]:A.error(Kf+t.property_denylist)),s};class $m{constructor(){this.__forceAllowLocalhost=!1}get fn(){return this.__forceAllowLocalhost}set fn(e){A.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class Ze{pn(e,n){if(e){var i=this.sn.indexOf(e);i!==-1&&this.sn.splice(i,1)}return this.sn.push(n),n.initialize==null||n.initialize(),n}gn(){return this.config.cookieless_mode===Wt||this.config.cookieless_mode===kn&&this.consent.isRejected()}get decideEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){var e;this.webPerformance=new $m,this.mn=!1,this.version=ne.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new gl,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=$o(),this.SentryIntegration=Xg,this.sentryIntegration=i=>(function(r,s){var o=yf(r,s);return{name:_f,processEvent:a=>o(a)}})(this,i),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.wn=!1,this.kn=null,this.xn=null,this.Sn=null,this.scrollManager=new ym(this),this.pageViewManager=new zc(this),this.rateLimiter=new am(this),this.requestRouter=new Em(this),this.consent=new Dg(this),this.externalIntegrations=new Cm(this);var n=(e=Ze.__defaultExtensionClasses)!==null&&e!==void 0?e:{};this.featureFlags=n.featureFlags&&new n.featureFlags(this),this.toolbar=n.toolbar&&new n.toolbar(this),this.surveys=n.surveys&&new n.surveys(this),this.conversations=n.conversations&&new n.conversations(this),this.logs=n.logs&&new n.logs(this),this.metrics=n.metrics&&new n.metrics(this),this.experiments=n.experiments&&new n.experiments(this),this.exceptions=n.exceptions&&new n.exceptions(this),this.people={set:(i,r,s)=>{var o=X(i)?{[i]:r}:i;this.setPersonProperties(o),s?.({})},set_once:(i,r,s)=>{var o=X(i)?{[i]:r}:i;this.setPersonProperties(void 0,o),s?.({})}},this.on("eventCaptured",(i=>A.info('send "'+i?.event+'"',i)))}init(e,n,i){if(i&&i!==Gn){var r,s=(r=Wi[i])!==null&&r!==void 0?r:new Ze;return s._init(e,n,i),Wi[i]=s,Wi[Gn][i]=s,s}return this._init(e,n,i)}_init(e,n,i){var r,s;n===void 0&&(n={});var o,a=X(e)?e.trim():"";if(!a)return A.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return a!==((o=this.config)==null?void 0:o.token)?console.warn("[PostHog.js]","You have already initialized PostHog with a different project token! Re-initializing is a no-op, so events will keep going to the project this instance was initialized with. To capture into a second project, load PostHog once, then initialize a named instance after the SDK has loaded, e.g. posthog.init('"+a+"', { ... }, 'project2')"):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=$o(n.defaults),n.debug=this.Cn(n.debug),this.Mn=n,this.Tn=[],n.person_profiles?this.xn=n.person_profiles:n.process_person&&(this.xn=n.process_person);var l=$o(n.defaults),u=su(n),c=fe({},l,u,{name:i,token:a});he(l.rageclick)&&he(u.rageclick)&&(c.rageclick=fe({},l.rageclick,u.rageclick)),he(l.session_recording)&&he(u.session_recording)&&(c.session_recording=fe({},l.session_recording,u.session_recording)),this.set_config(c),this.config.on_xhr_error&&A.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=n.disable_compression?void 0:Ue.GZipJS;var d=this.En();if(this.persistence=new Io(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Io(I({},this.config,{persistence:"sessionStorage"}),d,!1),this.bn="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&be.N()){var f=be.H(this.bn);U(f)&&f.forEach((k=>{X(k)&&this.yn.add(k)}))}else be.q(this.bn);var h=I({},this.persistence.props),p=I({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new mm((k=>this.Pn(k)),this.config.request_queue_config),this.Rn=new _m(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new eu(this),this.sessionPropsManager=new Qc(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((k,T,x)=>{(x!=null&&x.activityTimeout||x!=null&&x.sessionPastMaximumLength||x!=null&&x.crossTabAdoption)&&this.An()}))),this.Fn(),this.config.__preview_deferred_init_extensions?(A.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Ln(g)}),0)):(A.info("Initializing extensions synchronously"),this.Ln(g)),ne.DEBUG=ne.DEBUG||this.config.debug,ne.DEBUG&&A.info("Starting in debug mode",{this:this,config:n,thisC:I({},this.config),p:h,s:p}),!this.config.identity_distinct_id||(r=n.bootstrap)!=null&&r.distinctID||(n.bootstrap=I({},n.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((s=n.bootstrap)==null?void 0:s.distinctID)!==void 0){var m=n.bootstrap.distinctID,v=this.get_distinct_id(),E=this.persistence.get_property(at);if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&E===Un)this.identify(m);else if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&E===vn)A.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{var S=this.config.get_device_id(Ht()),_=n.bootstrap.isIdentifiedID?S:m;this.persistence.set_property(at,n.bootstrap.isIdentifiedID?vn:Un),this.register({distinct_id:m,$device_id:_})}}if(g)this.register_once({distinct_id:mr,$device_id:null},"");else if(!this.get_distinct_id()){var b=this.config.get_device_id(Ht());this.register_once({distinct_id:b,$device_id:b},""),this.persistence.set_property(at,Un)}return ve(w,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),n.segment?(function(k,T){var x=k.config.segment;if(!x)return T();(function(F,$){var O=F.config.segment;if(!O)return $();var L=K=>{var V=()=>K.anonymousId()||Ht();F.config.get_device_id=V,K.id()&&(F.register({distinct_id:K.id(),$device_id:V()}),F.persistence.set_property(at,vn)),$()},N=O.user();"then"in N&&je(N.then)?N.then(L):L(N)})(k,(()=>{x.register((F=>{typeof Promise<"u"&&Promise.resolve||So.warn("This browser does not have Promise support, and can not use the segment integration");var $=(O,L)=>{if(!L)return O;O.event.userId||O.event.anonymousId===F.get_distinct_id()||(So.info("No userId set, resetting PostHog"),F.reset()),O.event.userId&&O.event.userId!==F.get_distinct_id()&&(So.info("UserId set, identifying with PostHog"),F.identify(O.event.userId));var N=F.calculateEventProperties(L,O.event.properties);return O.event.properties=Object.assign({},N,O.event.properties),O};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:O=>$(O,O.event.event),page:O=>$(O,Vn),identify:O=>$(O,wo),screen:O=>$(O,"$screen")}})(k)).then((()=>{T()}))}))})(this,(()=>this.On())):this.On(),je(this.config._onCapture)&&this.config._onCapture!==us&&(A.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(k=>this.config._onCapture(k.event,k)))),this.config.ip&&A.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this.config.disableDeviceModel||(function(){return Hf.apply(this,arguments)})().then((k=>{k&&this.register({[_o]:k})})).catch(us),this}Fn(){var e,n,i,r,s,o,a=(e=(n=this.config.__extensionClasses)==null?void 0:n.featureFlags)!==null&&e!==void 0?e:(i=Ze.__defaultExtensionClasses)==null?void 0:i.featureFlags;a&&(this.featureFlags&&this.featureFlags instanceof a||((r=this.Dn)==null||r.call(this),this.Dn=void 0,this.featureFlags=new a(this)),je(this.featureFlags.onReloading)&&je(this.featureFlags.setup)?this.Dn||(this.Dn=this.featureFlags.onReloading((()=>{this.dn.emit("featureFlagsReloading",!0)})),this.$n().add(this.featureFlags)):(s=(o=this.featureFlags).initialize)==null||s.call(o))}Ln(e){var n,i,r,s,o,a,l,u=performance.now(),c=I({},Ze.__defaultExtensionClasses,this.config.__extensionClasses),d=[];c.exceptions&&this.sn.push(this.exceptions=(n=this.exceptions)!==null&&n!==void 0?n:new c.exceptions(this)),c.historyAutocapture&&this.sn.push(this.historyAutocapture=new c.historyAutocapture(this)),c.tracingHeaders&&this.sn.push(this.tracingHeaders=new c.tracingHeaders(this)),c.siteApps&&this.sn.push(this.siteApps=new c.siteApps(this)),c.sessionRecording&&!e&&this.sn.push(this.sessionRecording=new c.sessionRecording(this)),this.config.disable_scroll_properties||d.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),c.autocapture&&this.sn.push(this.autocapture=new c.autocapture(this)),c.surveys&&this.sn.push(this.surveys=(i=this.surveys)!==null&&i!==void 0?i:new c.surveys(this)),c.logs&&this.sn.push(this.logs=(r=this.logs)!==null&&r!==void 0?r:new c.logs(this)),c.metrics&&this.sn.push(this.metrics=(s=this.metrics)!==null&&s!==void 0?s:new c.metrics(this)),c.conversations&&this.sn.push(this.conversations=(o=this.conversations)!==null&&o!==void 0?o:new c.conversations(this)),c.productTours&&this.sn.push(this.productTours=new c.productTours(this)),c.heatmaps&&this.sn.push(this.heatmaps=new c.heatmaps(this)),c.webVitalsAutocapture&&this.sn.push(this.webVitalsAutocapture=new c.webVitalsAutocapture(this)),c.exceptionObserver&&this.sn.push(this.exceptionObserver=new c.exceptionObserver(this)),c.deadClicksAutocapture&&this.sn.push(this.deadClicksAutocapture=new c.deadClicksAutocapture(this,Zg)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((f=>{f.initialize&&d.push((()=>{f.initialize==null||f.initialize()}))})),d.push((()=>{if(this.Nn){var f=this.Nn;this.Nn=void 0,this.sn.forEach((h=>h.onRemoteConfig==null?void 0:h.onRemoteConfig(f)))}})),this.qn(d,u)}qn(e,n){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,n)}),0);var i=e.shift();if(i)try{i()}catch(s){A.error("Error initializing extension:",s)}}var r=Math.round(performance.now()-n);this.register_for_session({[tf]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[nf]:r}),this.config.__preview_deferred_init_extensions&&A.info("PostHog extensions initialized ("+r+"ms)")}Zi(e){var n;if(!P||!P.body)return A.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.Zi(e)}),500);if(this.config.__preview_deferred_init_extensions&&(this.Nn=e),this.hn=e,this.compression=void 0,e.ok){var i,r=e.config;r.supportedCompression&&!this.config.disable_compression&&(this.compression=j(r.supportedCompression,Ue.GZipJS)?Ue.GZipJS:j(r.supportedCompression,Ue.Base64)?Ue.Base64:void 0),(i=r.analytics)!=null&&i.endpoint&&(this.analyticsDefaultEndpoint=r.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:ga}),(n=this.jn)==null||n.handleRemoteConfig(e),this.sn.forEach((s=>s.onRemoteConfig==null?void 0:s.onRemoteConfig(e)))}On(){try{this.config.loaded(this)}catch(i){A.critical("`loaded` function failed",i)}if(this.Bn(),this.config.internal_or_test_user_hostname&&me!=null&&me.hostname){var e=me.hostname,n=this.config.internal_or_test_user_hostname;(typeof n=="string"?e===n:n.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.gn())&&this.Hn()}),1),this.Un=new Pf(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()&&vr(this.__request_queue,(e=>this.Pn(e))),this.__request_queue=[],this.Bn()}_handle_unload(){var e,n,i,r,s;(e=this.surveys)==null||e.handlePageUnload==null||e.handlePageUnload(),(n=this.metrics)==null||n.flush("sendBeacon"),this.config.request_batching?(this.zn()&&this.capture(yo),(i=this.logs)==null||i.flushLogs("sendBeacon"),(r=this.In)==null||r.unload(),(s=this.Rn)==null||s.unload()):this.zn()&&this.capture(yo,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?Yf?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)?e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:429})):(e.transport=e.transport||this.config.api_transport,e.headers=I({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,(C(this.config.disable_beacon)?this.config.__preview_disable_beacon:this.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(n=>{var i,r,s,o=I({},n);o.timeout=o.timeout||6e4;var a,l,u,c,d,f=(i=o.transport)!==null&&i!==void 0?i:"fetch";f==="sendBeacon"&&C(o.compression)&&o.data&&(o.compression=Ue.Base64),o.method==="POST"&&o.data&&(o.timestampMode==="capture-body"?o.data={api_key:(l=(d=(c=U(a=o.data)?a:[a])[0])==null||(u=d.properties)==null?void 0:u.token)!==null&&l!==void 0?l:d?.token,batch:c,sent_at:new Date().toISOString()}:o.timestampMode==="body"&&(o.data=(function(m,v){return v===void 0&&(v=new Date().toISOString()),U(m)?m.map((E=>I({},E,{sent_at:v}))):I({},m,{sent_at:v})})(o.data))),o.url=Xc(o.url,o.method,o.compression,o.timestampMode);var h=Lr.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),p=(r=(s=(function(m,v){for(var E=0;m.length>E;E++)if(m[E].transport===f)return m[E]})(h))==null?void 0:s.method)!==null&&r!==void 0?r:h[0].method;if(!p)throw new Error("No available transport method");var g=m=>{try{p(m)}catch(v){Df(v)?A.warn(v):A.error(v),o.callback==null||o.callback({statusCode:0,error:v})}};f!=="sendBeacon"&&o.data&&o.compression===Ue.GZipJS&&Mp&&typeof Promise<"u"&&!Mr?pm(o).then((m=>{g(m)})).catch((m=>{if(_c(m))return Mr=!0,void g(I({},o,{compression:void 0,url:Xc(n.url,n.method,void 0,n.timestampMode)}));(v=>{if(!v||typeof v!="object")return!1;var E="name"in v?String(v.name):"";return _c(v)||E===pd})(m)&&(Mr=!0),g(o)})):p(o)})(I({},e,{callback:n=>{var i,r;this.rateLimiter.checkForLimiting(n),400>n.statusCode||(i=(r=this.config).on_request_error)==null||i.call(r,n),e.callback==null||e.callback(n)}}))):e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:0}))}Pn(e){this.Rn?this.Rn.retriableRequest(e):this._send_request(e)}_execute_array(e){To++;try{var n,i=[],r=[],s=[];vr(e,(a=>{if(a)if(U(n=a[0]))s.push(a);else if(je(a))try{a.call(this)}catch(l){A.error("Error executing queued PostHog call",a,l)}else U(a)&&n==="alias"?i.push(a):U(a)&&n.indexOf("capture")!==-1&&je(this[n])?s.push(a):r.push(a)}));var o=function(a,l){vr(a,(function(u){try{if(U(u[0])){var c=l;ie(u,(function(d){c=c[d[0]].apply(c,d.slice(1))}))}else l[u[0]].apply(l,u.slice(1))}catch(d){A.error("Error executing queued PostHog call",u,d)}}))};o(i,this),o(r,this),o(s,this)}finally{To--}}push(e){if(To>0&&U(e)&&X(e[0])){var n=Ze.prototype[e[0]];je(n)&&n.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,n,i){var r,s,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.In){if(this.is_capturing())if(!C(e)&&X(e)){var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var c=i!=null&&i.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(c==null||!c.isRateLimited){n!=null&&n.$current_url&&!X(n?.$current_url)&&(A.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),n==null||delete n.$current_url),e!=="$exception"||i!=null&&i.Wn||A.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,f=i?.timestamp||d,h=Sc(i?.uuid,Ht),p={uuid:h,event:e,properties:this.calculateEventProperties(e,n||{},f,h)};e===Vn&&this.config.__preview_capture_bot_pageviews&&u&&(p.event="$bot_pageview",p.properties.$browser_type="bot"),c&&(p.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&p.properties.$feature_flag_has_experiment===!1&&this.get_property(Zr)===!0;i?.$set&&!g&&(p.$set=i?.$set);var m=i?.$unset;m&&(p.$unset=m);var v,E,S,_=g?void 0:this.Vn(i?.$set_once,e!==Pc,e===wo);if(_&&(p.$set_once=_),i!=null&&i._noTruncate||(s=this.config.properties_string_max_length,o=p,a=L=>X(L)?L.slice(0,s):L,l=new Set,p=(function L(N,K){if(N!==Object(N))return a?a(N):N;if(!l.has(N)){var V;if(l.add(N),U(N))V=[],vr(N,(R=>{V.push(L(R))}));else{var M={};ie(N,((R,Z)=>{l.has(R)||(M[Z]=L(R))})),V=M}return V}})(o)),p.timestamp=f,C(i?.timestamp)||(p.properties.$event_time_override_provided=!0,p.properties.$event_time_override_system_time=d),g&&(p.properties=(function(L,N){N===void 0&&(N=[]);var K={},V=M=>{L[M]!==void 0&&(K[M]=L[M])};return Lp.forEach(V),N.forEach(V),K})(p.properties,Rm)),e===qt.DISMISSED||e===qt.SENT){var b=n?.[Co.SURVEY_ID],k=n?.[Co.SURVEY_ITERATION];Gf({id:b,current_iteration:k}),p.$set=I({},p.$set,{[(v={id:b,current_iteration:k},E=e===qt.SENT?"responded":"dismissed",S="$survey_"+E+"/"+v.id,v.current_iteration&&v.current_iteration>0&&(S="$survey_"+E+"/"+v.id+"/"+v.current_iteration),S)]:!0})}else e===qt.SHOWN&&(p.$set=I({},p.$set,{[Co.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===om.SHOWN){var T=n?.[Vc.TOUR_TYPE];T&&(p.$set=I({},p.$set,{[Vc.TOUR_LAST_SEEN_DATE+"/"+T]:new Date().toISOString()}))}var x=I({},p.properties.$set,p.$set);if(Kt(x)||this.setPersonPropertiesForFlags(x),!H(this.config.before_send)){var F=this.Pt(p);if(!F)return;(p=F).uuid=Sc(p.uuid,Ht)}this.dn.emit("eventCaptured",p);var $=(r=i?._url)!==null&&r!==void 0?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),O={method:"POST",url:$,data:p,compression:"best-available",timestampMode:i?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test($)?"body":"capture-body",batchKey:i?._batchKey,transport:i?.transport};return!this.config.request_batching||i&&(i==null||!i._batchKey)||i!=null&&i.send_instantly?this.Pn(O):this.In.enqueue(O),p}A.critical("This capture call is ignored due to client rate limiting.")}}else A.error("No event name provided to posthog.capture")}else A.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(n=>e(n.event,n)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new Fm(this)}cn(e){this._n.push(e);var n=!0;return()=>{if(n){n=!1;var i=this._n.indexOf(e);i!==-1&&this._n.splice(i,1)}}}calculateEventProperties(e,n,i,r,s){if(i=i||new Date,!this.persistence||!this.sessionPersistence)return n;var o=s?void 0:this.persistence.remove_event_timer(e),a=I({},n);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.gn()&&(a[ef]=!0),e==="$snapshot"){var l=I({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!X(a.distinct_id)&&!ke(a.distinct_id)||Yo(a.distinct_id))&&A.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=(function(b,k,T,x){var F,$,O,L;if(x===void 0&&(x=!1),!Ge)return{};var N,K=b?[...ri,...k||[]]:[],V=(function(Bn){for(var qe=0;bc.length>qe;qe++){var Dn=bc[qe],Mt=Dn[1],Lt=Dn[0].exec(Bn),ut=Lt&&(je(Mt)?Mt(Lt,Bn):Mt);if(ut)return ut}return["",""]})(Ge),M=V[0],R=V[1],Z=(N=typeof navigator<"u"?navigator:void 0)!=null&&N.brave?{brave:!0}:{},Ce={};C(T)||(Ce.detectGoogleSearchApp=T);var oe={},ye=(F=navigator)==null||(F=F.userAgentData)==null?void 0:F.platform,$e=($=navigator)==null?void 0:$.maxTouchPoints,ae=w==null||(O=w.screen)==null?void 0:O.width,Ie=w==null||(L=w.screen)==null?void 0:L.height,Se=w?.devicePixelRatio;C(ye)||(oe.userAgentDataPlatform=ye),C($e)||(oe.maxTouchPoints=$e),C(ae)||(oe.screenWidth=ae),C(Ie)||(oe.screenHeight=Ie),C(Se)||(oe.devicePixelRatio=Se);var De,wt,ge,Je,bt,mn,Re,Pe,$t=fe(cl({$os:M,$os_version:R,$browser:Dd(Ge,navigator.vendor,Z,Ce),$device:Ec(Ge),$device_type:(wt=Ge,ge=oe,Pe=Ec(wt),Pe===bd||Pe===wd||Pe==="Kobo"||Pe==="Kindle Fire"||Pe===Md?ei:Pe===Gi||Pe===Xn||Pe===Ki||Pe===Zo?"Console":Pe===Sd?"Wearable":Pe?rt:ge?.userAgentDataPlatform==="Android"&&((Je=ge?.maxTouchPoints)!==null&&Je!==void 0?Je:0)>0?600>Math.min((bt=ge?.screenWidth)!==null&&bt!==void 0?bt:0,(mn=ge?.screenHeight)!==null&&mn!==void 0?mn:0)/((Re=ge?.devicePixelRatio)!==null&&Re!==void 0?Re:1)?rt:ei:"Desktop"),$timezone:Af(),$timezone_offset:im()}),{$current_url:Zi(x?fn(me?.href):me?.href,K,Xi),$host:me?.host,$pathname:me?.pathname,$raw_user_agent:Ge.length>1e3?Ge.substring(0,997)+"...":Ge,$browser_version:eg(Ge,navigator.vendor,Z,Ce),$browser_language:qc(),$browser_language_prefix:(De=qc(),typeof De=="string"?De.split("-")[0]:void 0),$screen_height:w?.screen.height,$screen_width:w?.screen.width,$viewport_height:w?.innerHeight,$viewport_width:w?.innerWidth,$lib:ne.LIB_NAME,$lib_version:ne.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return ne.SDK_DIST_CHANNEL&&($t.$sdk_dist_channel=ne.SDK_DIST_CHANNEL),$t})(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties,this.config.detect_google_search_app,this.config.disable_capture_url_hashes);if(this.sessionManager){var d=this.sessionManager.checkAndGetSessionAndWindowId(s,i.getTime()),f=d.windowId;a.$session_id=d.sessionId,a.$window_id=f}this.sessionPropsManager&&fe(a,this.sessionPropsManager.getSessionProps());try{var h;this.sessionRecording&&fe(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(h=this.Rn)==null?void 0:h.length}catch(b){a.$sdk_debug_error_capturing_properties=String(b)}if(this.requestRouter.region===Ia&&(a.$lib_custom_api_host=this.config.api_host),u=e!==Vn||s?e!==yo||s?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(i):this.pageViewManager.doPageView(i,r),a=fe(a,u),e===Vn&&P&&(a.title=P.title),!C(o)){var p=i.getTime()-o;a.$duration=parseFloat((p/1e3).toFixed(3))}Ge&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();ie(["$referrer","$referring_domain"],(b=>{b in g&&delete m[b]}));var v={};if(this._n.length>0)for(var E of this._n.slice())try{fe(v,E())}catch(b){A.error("Failed to produce browser extension event properties",b)}(a=fe({},c,g,m,I({},v,a))).$is_identified=this._isIdentified(),U(this.config.property_denylist)?ie(this.config.property_denylist,(function(b){delete a[b]})):A.error(Kf+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var S=this.config.sanitize_properties;S&&(A.error(ru),a=S(a,e));var _=this.Zn();return a.$process_person_profile=_,_&&!s&&this.Gn("_calculate_event_properties"),a}Vn(e,n,i){var r;if(n===void 0&&(n=!0),i===void 0&&(i=!1),!this.persistence||!this.Zn()||this.mn&&!i)return e;var s=this.persistence.get_initial_props(),o=(r=this.sessionPropsManager)==null?void 0:r.getSetOnceProps(),a=fe({},s,o||{},e||{}),l=this.config.sanitize_properties;return l&&(A.error(ru),a=l(a,"$set_once")),n&&(this.mn=!0),Kt(a)?void 0:a}register(e,n){var i;(i=this.persistence)==null||i.register(e,n)}register_once(e,n,i){var r;(r=this.persistence)==null||r.register_once(e,n,i)}register_for_session(e){var n;(n=this.sessionPersistence)==null||n.register(e),Object.keys(e).forEach((i=>this.yn.add(i))),this.Qn()}unregister(e){var n;(n=this.persistence)==null||n.unregister(e)}unregister_for_session(e){var n;(n=this.sessionPersistence)==null||n.unregister(e),this.yn.delete(e),this.Qn()}Kn(e,n){this.register({[e]:n})}An(){this.yn.forEach((e=>{var n;(n=this.sessionPersistence)==null||n.unregister(e)})),this.yn.clear(),this.Qn()}Qn(){var e;if(this.bn)if(this.config.persistence==="memory"||(e=this.sessionPersistence)!=null&&e.xi||!be.N())be.q(this.bn);else{var n=[];this.yn.forEach((i=>n.push(i))),n.length>0?be.F(this.bn,n):be.q(this.bn)}}getFeatureFlag(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlag(e,n)}getFeatureFlagPayload(e){var n;return(n=this.featureFlags)==null?void 0:n.getFeatureFlagPayload(e)}getFeatureFlagResult(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlagResult(e,n)}getAllFeatureFlags(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.getAllFeatureFlags())!==null&&e!==void 0?e:[]}isFeatureEnabled(e,n){var i,r;return(i=(r=this.featureFlags)==null?void 0:r.isFeatureEnabled(e,n))!==null&&i!==void 0?i:n?.defaultValue}reloadFeatureFlags(){var e;(e=this.featureFlags)==null||e.reloadFeatureFlags()}updateFlags(e,n,i){var r;(r=this.featureFlags)==null||r.updateFlags(e,n,i)}updateEarlyAccessFeatureEnrollment(e,n,i){var r;(r=this.featureFlags)==null||r.updateEarlyAccessFeatureEnrollment(e,n,i)}getEarlyAccessFeatures(e,n,i){var r;return n===void 0&&(n=!1),(r=this.featureFlags)==null?void 0:r.getEarlyAccessFeatures(e,n,i)}on(e,n){return this.dn.on(e,n)}onFeatureFlags(e){return this.featureFlags?this.featureFlags.onFeatureFlags(e):(e([],{},{errorsLoading:!0}),()=>{})}onSurveysLoaded(e){return this.surveys?this.surveys.onSurveysLoaded(e):(e([],{isLoaded:!1,error:xi}),()=>{})}onSessionId(e){var n,i;return(n=(i=this.sessionManager)==null?void 0:i.onSessionId(e))!==null&&n!==void 0?n:()=>{}}getSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getSurveys(e,n):e([],{isLoaded:!1,error:xi})}getActiveMatchingSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,n):e([],{isLoaded:!1,error:xi})}renderSurvey(e,n){var i;(i=this.surveys)==null||i.renderSurvey(e,n)}displaySurvey(e,n){var i;n===void 0&&(n=xm),(i=this.surveys)==null||i.displaySurvey(e,n)}cancelPendingSurvey(e){var n;(n=this.surveys)==null||n.cancelPendingSurvey(e)}canRenderSurvey(e){var n,i;return(n=(i=this.surveys)==null?void 0:i.canRenderSurvey(e))!==null&&n!==void 0?n:{visible:!1,disabledReason:xi}}canRenderSurveyAsync(e,n){var i,r;return n===void 0&&(n=!1),(i=(r=this.surveys)==null?void 0:r.canRenderSurveyAsync(e,n))!==null&&i!==void 0?i:Promise.resolve({visible:!1,disabledReason:xi})}Jn(e){return!e||Yo(e)?(A.critical("Unique user id has not been set in posthog.identify"),!1):e===mr?(A.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.'),!1):!["distinct_id","distinctid"].includes(e.toLowerCase())&&!["undefined","null"].includes(e.toLowerCase())||(A.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.'),!1)}identify(e,n,i){if(!this.__loaded||!this.persistence)return A.uninitializedWarning("posthog.identify");if(ke(e)&&(e=e.toString(),A.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.Jn(e)&&this.Gn("posthog.identify")){var r=this.get_distinct_id();this.register({$user_id:e}),this.get_property(Yi)||this.register_once({$had_persisted_distinct_id:!0,$device_id:r},""),e!==r&&e!==this.get_property(Fi)&&(this.unregister(Fi),this.register({distinct_id:e}));var s,o=(this.persistence.get_property(at)||Un)===Un,a=e!==r,l=!a&&o;if(a&&o)this.persistence.set_property(at,vn),this.setPersonPropertiesForFlags({$set:n||{},$set_once:i||{}},!1),this.capture(wo,{distinct_id:e,$anon_distinct_id:r},{$set:n||{},$set_once:i||{}}),this.Sn=Ro(e,n,i),(s=this.featureFlags)==null||s.setAnonymousDistinctId(r);else if(l){this.persistence.set_property(at,vn);var u=n||{},c=i||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=Ro(e,n,i)}else(n||i)&&this.setPersonProperties(n,i);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Cn)):l&&(n||i)&&this.reloadFeatureFlags()}}setPersonProperties(e,n){if((e||n)&&this.Gn("posthog.setPersonProperties")){var i=Ro(this.get_distinct_id(),e,n);this.Sn!==i?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:n||{}},!0),this.capture("$set",{$set:e||{},$set_once:n||{}}),this.Sn=i):A.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}unsetPersonProperties(e){var n,i=(U(e)?e:[e]).filter((r=>X(r)&&r.length>0));i.length!==0&&this.Gn("posthog.unsetPersonProperties")&&((n=this.featureFlags)==null||n.unsetPersonPropertiesForFlags(i,!0),this.capture("$set",{$unset:i}),this.Sn=null)}group(e,n,i){if(e&&n){var r=this.getGroups(),s=r[e]!==n;if(s&&this.resetGroupPropertiesForFlags(e),this.register({$groups:I({},r,{[e]:n})}),s||i){var o={$group_type:e,$group_key:n};i&&(o.$group_set=i),this.capture(Pc,o)}i&&this.setGroupPropertiesForFlags({[e]:i}),s&&!i&&this.reloadFeatureFlags()}else A.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),(i=this.featureFlags)==null||i.setPersonPropertiesForFlags(e,n)}resetPersonPropertiesForFlags(e){var n;e===void 0&&(e=!0),(n=this.featureFlags)==null||n.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((i=this.featureFlags)==null||i.setGroupPropertiesForFlags(e,n))}resetGroupPropertiesForFlags(e){var n;(n=this.featureFlags)==null||n.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,n){var i,r,s,o,a,l,u,c,d,f;if(n===void 0&&(n=!1),A.info("reset"),!this.__loaded)return A.uninitializedWarning("posthog.reset");var h,p=this.get_property(Yi),g=this.get_property(_o),m=this.get_property(An),v=this.is_capturing();if(this.consent.reset(),n||!v||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after."),(i=this.persistence)==null||i.clear(),(r=this.sessionPersistence)==null||r.clear(),this.yn.clear(),this.Qn(),C(m)||(h=this.persistence)==null||h.register({[An]:m}),(s=this.surveys)==null||s.reset(),(o=this.Un)==null||o.stop(),(a=this.featureFlags)==null||a.reset(),(l=this.conversations)==null||l.reset(),(u=this.logs)==null||u.reset(),(c=this.metrics)==null||c.reset(),(d=this.persistence)==null||d.set_property(at,Un),(f=this.sessionManager)==null||f.resetSessionId(),this.Sn=null,this.config.cookieless_mode===Wt)this.register_once({distinct_id:mr,$device_id:null},"");else{var E=this.config.get_device_id(Ht());this.register_once({distinct_id:E,$device_id:e?E:p},""),e||C(g)||this.register({[_o]:g})}this.register({$last_posthog_reset:new Date().toISOString()},1),delete this.config.identity_distinct_id,delete this.config.identity_hash,this.reloadFeatureFlags()}shutdown(e){var n=this;return se((function*(){var i,r,s,o,a,l,u;if(n.__loaded){(i=n.Un)==null||i.stop(),(r=n.jn)==null||r.dispose(),(s=n.sessionRecording)==null||s.dispose(),(o=n.logs)==null||o.flushLogs("sendBeacon"),(a=n.metrics)==null||a.flush("sendBeacon"),(l=n.In)==null||l.unload(),(u=n.Rn)==null||u.unload();try{var c;(c=n.featureFlags)==null||c.destroy()}catch(d){A.error("Error while destroying feature flags",d)}}else A.uninitializedWarning("posthog.shutdown")}))()}setIdentity(e,n){var i;this.config.identity_distinct_id=e,this.config.identity_hash=n,this.alias(e),(i=this.conversations)==null||i.Xn()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,(e=this.conversations)==null||e.ts()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,n;return(e=(n=this.sessionManager)==null?void 0:n.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var n=this.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.sessionStartTimestamp,r=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+n.sessionId);if(e!=null&&e.withTimestamp&&i){var s,o=(s=e.timestampLookBack)!==null&&s!==void 0?s:10;if(!i)return r;r+="?t="+Math.max(Math.floor((new Date().getTime()-i)/1e3)-o,0)}return r}alias(e,n){return e===this.get_property(Kd)?(A.critical("Attempting to create alias for existing People user - aborting."),-2):this.Gn("posthog.alias")?(C(n)&&(n=this.get_distinct_id()),e!==n?(this.Kn(Fi,e),this.capture("$create_alias",{alias:e,distinct_id:n})):(A.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var n=I({},this.config);if(he(e)){var i,r,s,o,a,l,u,c,d,f,h,p;fe(this.config,su(e));var g=this.En();(i=this.persistence)==null||i.update_config(this.config,n,g),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Io(I({},this.config,{persistence:"sessionStorage"}),g,!1);var m=this.Cn(this.config.debug);mt(m)&&(this.config.debug=m),mt(this.config.debug)&&(this.config.debug?(ne.DEBUG=!0,le.N()&&le.F("ph_debug",!0),A.info("set_config",{config:e,oldConfig:n,newConfig:I({},this.config)})):(ne.DEBUG=!1,le.N()&&le.q("ph_debug"))),(r=this.featureFlags)==null||r.updateConfig==null||r.updateConfig(this.config,this.Qi()),(s=this.exceptionObserver)==null||s.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(f=this.deadClicksAutocapture)==null||f.startIfEnabledOrStop(),(h=this.surveys)==null||h.loadIfEnabled(),this.es(),(p=this.externalIntegrations)==null||p.startIfEnabledOrStop()}}_overrideSDKInfo(e,n){ne.LIB_NAME=e,ne.LIB_VERSION=n}startSessionRecording(e){var n,i,r,s,o,a=e===!0,l={sampling:a||!(e==null||!e.sampling),linked_flag:a||!(e==null||!e.linked_flag),url_trigger:a||!(e==null||!e.url_trigger),event_trigger:a||!(e==null||!e.event_trigger)};Object.values(l).some(Boolean)&&((n=this.sessionManager)==null||n.checkAndGetSessionAndWindowId(),l.sampling&&((i=this.sessionRecording)==null||i.overrideSampling()),l.linked_flag&&((r=this.sessionRecording)==null||r.overrideLinkedFlag()),l.url_trigger&&((s=this.sessionRecording)==null||s.overrideTrigger("url")),l.event_trigger&&((o=this.sessionRecording)==null||o.overrideTrigger("event"))),this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,n){if(this.exceptions){var i=new Error("PostHog syntheticException"),r=this.exceptions.buildProperties(e,{handled:!0,syntheticException:i});return this.exceptions.sendExceptionEvent(I({},r,n))}}addExceptionStep(e,n){var i;(i=this.exceptions)==null||i.addExceptionStep(e,n)}captureLog(e){var n;(n=this.logs)==null||n.captureLog(e)}get logger(){var e,n;return(e=(n=this.logs)==null?void 0:n.logger)!==null&&e!==void 0?e:Ze.rs}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var n,i;return(n=(i=this.toolbar)==null?void 0:i.loadToolbar(e))!==null&&n!==void 0&&n}get_property(e){var n;return(n=this.persistence)==null?void 0:n.props[e]}getSessionProperty(e){var n;return(n=this.sessionPersistence)==null?void 0:n.props[e]}toString(){var e,n=(e=this.config.name)!==null&&e!==void 0?e:Gn;return n!==Gn&&(n=Gn+"."+n),n}_isIdentified(){var e,n;return((e=this.persistence)==null?void 0:e.get_property(at))===vn||((n=this.sessionPersistence)==null?void 0:n.get_property(at))===vn}Zn(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles===ga&&!this._isIdentified()&&Kt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[Fi])&&((n=this.persistence)==null||(n=n.props)==null||!n[es]))}zn(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Zn()||this.Gn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.Gn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}Gn(e){return this.config.person_profiles==="never"?(A.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Kn(es,!0),!0)}En(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut();return this.config.disable_persistence||e&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!==kn)}es(){var e,n,i,r,s=this.En();return((e=this.persistence)==null?void 0:e.xi)!==s&&((i=this.persistence)==null||i.set_disabled(s)),((n=this.sessionPersistence)==null?void 0:n.xi)!==s&&((r=this.sessionPersistence)==null||r.set_disabled(s)),s&&(this.yn.clear(),this.Qn()),s}opt_in_capturing(e){var n;if(this.config.cookieless_mode!==Wt){if(this.gn()){var i,r,s,o,a;this.Yn(!0,!0),(i=this.sessionManager)==null||i.destroy(),(r=this.pageViewManager)==null||r.destroy(),this.sessionManager=new eu(this),this.pageViewManager=new zc(this),this.persistence&&(this.sessionPropsManager=new Qc(this,this.sessionManager,this.persistence));var l,u=(s=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&s!==void 0?s:(a=Ze.__defaultExtensionClasses)==null?void 0:a.sessionRecording;u&&(this.sessionRecording=this.pn(this.sessionRecording,new u(this)),this.hn&&((l=this.sessionRecording)==null||l.onRemoteConfig==null||l.onRemoteConfig(this.hn)))}var c,d;this.consent.optInOut(!0),this.es(),this.Bn(),(n=this.sessionRecording)==null||n.startIfEnabledOrStop(),this.config.cookieless_mode==kn&&((c=this.surveys)==null||c.loadIfEnabled()),(C(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((d=e?.captureEventName)!==null&&d!==void 0?d:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hn()}else A.warn(iu)}opt_out_capturing(){var e,n,i;this.config.cookieless_mode!==Wt?(this.config.cookieless_mode===kn&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===kn&&(this.register({distinct_id:mr,$device_id:null}),(e=this.sessionRecording)==null||e.stopRecording(),this.sessionRecording=void 0,(n=this.sessionManager)==null||n.destroy(),(i=this.pageViewManager)==null||i.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.Hn(),this.Bn())):A.warn(iu)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===Wt||(this.config.cookieless_mode===kn?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return He?Uf(He,this.config.custom_blocked_useragents):void 0}Hn(){P&&(P.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(Vn,{title:P.title},{send_instantly:!0}),this.kn&&(P.removeEventListener(ts,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),ve(P,ts,this.kn)))}debug(e){e===!1?(w?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(w?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}Qi(){var e=this.Mn||{};return"advanced_disable_flags"in e?!!e.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(A.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(function(n,i,r,s,o){var a=i in n&&!H(n[i]),l=r in n&&!H(n[r]);return a?n[i]:!!l&&(o&&o.warn("Config field '"+r+"' is deprecated. Please use '"+i+"' instead. The old field will be removed in a future major version."),n[r])})(e,"advanced_disable_flags","advanced_disable_decide",0,A)}Pt(e){var n;if(H(this.config.before_send))return e;var i=Object.keys((n=e.properties)!==null&&n!==void 0?n:{}).filter(Hp),r=U(this.config.before_send)?this.config.before_send:[this.config.before_send],s=e;for(var o of r){if(s=o(s),H(s)){var a="Event '"+e.event+"' was rejected in beforeSend function";return Up(e.event)?A.warn(a+". This can cause unexpected behavior."):A.info(a),null}s.properties&&!Kt(s.properties)||A.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}for(var l of i)if(s.properties&&H(s.properties[l]))return A.warn("Event '"+e.event+"' had its '"+l+"' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped."),null;return s}getPageViewId(){var e;return(e=this.pageViewManager.ui)==null?void 0:e.pageViewId}captureTraceFeedback(e,n){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:n})}captureTraceMetric(e,n,i){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:n,$ai_metric_value:String(i)})}Cn(e){var n=mt(e)&&!e,i=le.N()&&le.P("ph_debug")==="true";return!n&&(!!i||e)}}Ze.__defaultExtensionClasses={},Ze.rs=(()=>{var t=()=>{};return{trace:t,debug:t,info:t,warn:t,error:t,fatal:t}})(),(function(t,e){for(var n=0;e.length>n;n++)t.prototype[e[n]]=Fg(t.prototype[e[n]])})(Ze,["identify"]);class ou{constructor(e){this.disabled=e===!1;var n=he(e)?e:{};this.thresholdPx=n.threshold_px||30,this.timeoutMs=n.timeout_ms||1e3,this.clickCount=n.click_count||3,this.clicks=[]}isRageClick(e,n,i){if(this.disabled)return!1;var r=this.clicks[this.clicks.length-1];if(r&&Math.abs(e-r.x)+Math.abs(n-r.y)i-r.timestamp){if(this.clicks.push({x:e,y:n,timestamp:i}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:n,timestamp:i}];return!1}}var Mo="$copy_autocapture",Lo=pe("[AutoCapture]");function No(t,e){return e.length>t?e.slice(0,t)+"...":e}function Mm(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!hn(e));return e}function Lm(t,e){var n,i,r=e.e,s=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!hn(t))return{props:{}};for(var c=[t],d=new Set([t]),f=t;f.parentNode&&!et(f,"body")&&df>c.length;)if(uf(f.parentNode)){var h=f.parentNode.host;if(d.has(h))break;d.add(h),c.push(h),f=h}else{if(!hn(f.parentNode)||d.has(f.parentNode))break;d.add(f.parentNode),c.push(f.parentNode),f=f.parentNode}var p,g,m=[],v={},E=!1,S=!1;if(ie(c,(x=>{var F=_a(x);if(et(x,"a")){var $=x.getAttribute("href");E=!!(F&&$&&Ui($))&&(u?fn($):$)}j(rs(x),"ph-no-capture")&&(S=!0),m.push((function(L,N,K,V,M){M===void 0&&(M=!1);var R=L.tagName.toLowerCase(),Z={tag_name:R};dl.indexOf(R)>-1&&!K&&(Z.$el_text=R.toLowerCase()==="a"||R.toLowerCase()==="button"?No(1024,Uc(L)):No(1024,Ji(L)));var Ce=rs(L);Ce.length>0&&(Z.classes=Ce.filter((function(ae){return ae!==""}))),ie(L.attributes,(function(ae){var Ie;if((!mf(L)||["name","id","class","aria-label"].indexOf(ae.name)!==-1)&&(V==null||!V.includes(ae.name))&&!N&&Ui(ae.value)&&(!X(Ie=ae.name)||Ie.substring(0,10)!=="_ngcontent"&&Ie.substring(0,7)!=="_nghost")){var Se=ae.value;ae.name==="class"&&(Se=ul(Se).join(" ")),Z["attr__"+ae.name]=No(1024,ae.name==="href"&&M?fn(Se):Se)}}));for(var oe=1,ye=1,$e=L;$e=Mm($e);)oe++,$e.tagName===L.tagName&&ye++;return Z.nth_child=oe,Z.nth_of_type=ye,Z})(x,s,o,a,u));var O=(function(L){if(!_a(L))return{};var N={};return ie(L.attributes,(function(K){if(K.name&&K.name.indexOf("data-ph-capture-attribute")===0){var V=K.name.replace("data-ph-capture-attribute-",""),M=K.value;V&&M&&Ui(M)&&(N[V]=M)}})),N})(x);fe(v,O)})),S)return{props:{},explicitNoCapture:S};if(o||(m[0].$el_text=et(t,"a")||et(t,"button")?Uc(t):Ji(t)),E){var _,b;m[0].attr__href=E;var k=(_=ss(E))==null?void 0:_.host,T=w==null||(b=w.location)==null?void 0:b.host;k&&T&&k!==T&&(p=E)}return{props:fe({$event_type:r.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(x){return x.map((F=>{var $,O,L="";if(F.tag_name&&(L+=F.tag_name),F.attr_class)for(var N of(F.attr_class.sort(),F.attr_class))L+="."+N.replace(/"/g,"");var K=I({},F.text?{text:F.text}:{},{"nth-child":($=F.nth_child)!==null&&$!==void 0?$:0,"nth-of-type":(O=F.nth_of_type)!==null&&O!==void 0?O:0},F.href?{href:F.href}:{},F.attr_id?{attr_id:F.attr_id}:{},F.attributes),V={};return $r(K).sort(((M,R)=>M[0].localeCompare(R[0]))).forEach((M=>{var R=M[1];return V[Hc(M[0].toString())]=Hc(R.toString())})),(L+=":")+$r(V).map((M=>M[0]+'="'+M[1]+'"')).join("")})).join(";")})((function(x){return x.map((F=>{var $,O,L={text:($=F.$el_text)==null?void 0:$.slice(0,400),tag_name:F.tag_name,href:(O=F.attr__href)==null?void 0:O.slice(0,2048),attr_class:Yg(F),attr_id:F.attr__id,nth_child:F.nth_child,nth_of_type:F.nth_of_type,attributes:{}};return $r(F).filter((N=>N[0].indexOf("attr__")===0)).forEach((N=>L.attributes[N[0]]=N[1])),L}))})(g)))},(n=m[0])!=null&&n.$el_text?{$el_text:(i=m[0])==null?void 0:i.$el_text}:{},p&&r.type==="click"?{$external_click_url:p}:{},v)}}var Ii=pe("[ExceptionAutocapture]"),au=()=>{},Nm=pe("[TracingHeaders]"),wn=pe("[Web Vitals]"),lu=9e5,cu="disabled",uu="lazy_loading",ki="awaiting_config",Sr="missing_config";pe("[SessionRecording]"),pe("[SessionRecording]");var ka="[SessionRecording]",Bt=pe(ka),Om=pe("[Heatmaps]");function Oo(t){return he(t)&&"clientX"in t&&"clientY"in t&&ke(t.clientX)&&ke(t.clientY)}var xr=pe("[Product Tours]"),Bo=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(ol))},Bm=["$set_once","$set"],Et=pe("[SiteApps]"),du="Error while initializing PostHog app with config id ";function zn(t,e,n){if(H(t))return!1;switch(n){case"exact":return t===e;case"contains":var i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(i,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}class Dm{constructor(e){this.ns=new gl,this.ss=(n,i)=>this.os(n,i)&&this.ls(n,i)&&this.us(n,i)&&this.hs(n,i),this.os=(n,i)=>i==null||!i.event||n?.event===i?.event,this._instance=e,this.ds=new Set,this.vs=new Set}init(){var e,n;C((e=this._instance)==null?void 0:e._addCaptureHook)||(n=this._instance)==null||n._addCaptureHook(((i,r)=>{this.on(i,r)}))}register(e){var n,i;if(!C((n=this._instance)==null?void 0:n._addCaptureHook)&&(e.forEach((o=>{var a,l;(a=this.vs)==null||a.add(o),(l=o.steps)==null||l.forEach((u=>{var c;(c=this.ds)==null||c.add(u?.event||"")}))})),(i=this._instance)!=null&&i.autocapture)){var r,s=new Set;e.forEach((o=>{var a;(a=o.steps)==null||a.forEach((l=>{l!=null&&l.selector&&s.add(l?.selector)}))})),(r=this._instance)==null||r.autocapture.setElementSelectors(s)}}on(e,n){var i;n!=null&&e.length!=0&&(this.ds.has(e)||this.ds.has(n.event))&&this.vs&&((i=this.vs)==null?void 0:i.size)>0&&this.vs.forEach((r=>{this.cs(n,r)&&this.ns.emit("actionCaptured",r.name)}))}fs(e){this.onAction("actionCaptured",(n=>e(n)))}cs(e,n){if(n?.steps==null)return!1;for(var i of n.steps)if(this.ss(e,i))return!0;return!1}onAction(e,n){return this.ns.on(e,n)}ls(e,n){if(n!=null&&n.url){var i,r=e==null||(i=e.properties)==null?void 0:i.$current_url;if(!r||typeof r!="string"||!zn(r,n.url,n.url_matching||"contains"))return!1}return!0}us(e,n){return!!this.ps(e,n)&&!!this.gs(e,n)&&!!this.ys(e,n)}ps(e,n){var i;if(n==null||!n.href)return!0;var r=this.bs(e);if(r.length>0)return r.some((a=>zn(a.href,n.href,n.href_matching||"exact")));var s,o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!o&&zn((s=o.match(/(?::|")href="(.*?)"/))?s[1]:"",n.href,n.href_matching||"exact")}gs(e,n){var i;if(n==null||!n.text)return!0;var r=this.bs(e);if(r.length>0)return r.some((u=>zn(u.text,n.text,n.text_matching||"exact")||zn(u.$el_text,n.text,n.text_matching||"exact")));var s,o,a,l=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!l&&(s=(function(u){for(var c,d=[],f=/(?::|")text="(.*?)"/g;!H(c=f.exec(u));)d.includes(c[1])||d.push(c[1]);return d})(l),o=n.text,a=n.text_matching||"exact",s.some((u=>zn(u,o,a))))}ys(e,n){var i,r;if(n==null||!n.selector)return!0;var s=e==null||(i=e.properties)==null?void 0:i.$element_selectors;if(s!=null&&s.includes(n.selector))return!0;var o=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";if(n.selector_regex&&o)try{return new RegExp(n.selector_regex).test(o)}catch{return!1}return!1}bs(e){var n;return(e==null||(n=e.properties)==null?void 0:n.$elements)==null?[]:e?.properties.$elements}hs(e,n){return n==null||!n.properties||n.properties.length===0||zf(n.properties.reduce(((i,r)=>{var s=U(r.value)?r.value.map(String):r.value!=null?[String(r.value)]:[];return i[r.key]={values:s,operator:r.operator||"exact"},i}),{}),e?.properties)}}class jm{constructor(e){var n;this._s=[],this._instance=e,this.ws=new Map,this.ks=new Map,this.xs=new Map,(n=this._instance)==null||n.onSessionId==null||n.onSessionId((i=>this.Ss(i)))}Cs(e){return!1}Ms(){return null}Ts(e){}Es(){}Is(e,n){return!!e&&zf(e.propertyFilters,n?.properties)}Ps(e,n){var i=new Map;return e.forEach((r=>{var s;(s=r.conditions)==null||(s=s[n])==null||(s=s.values)==null||s.forEach((o=>{if(o!=null&&o.name){var a=i.get(o.name)||[];a.push(r.id),i.set(o.name,a)}}))})),i}Rs(e,n,i){var r=(i===wi.Activation?this.ws:this.ks).get(e),s=[];return this.As((o=>{s=o.filter((a=>r?.includes(a.id)))})),s.filter((o=>{var a,l=(a=o.conditions)==null||(a=a[i])==null||(a=a.values)==null?void 0:a.find((u=>u.name===e));return this.Is(l,n)}))}register(e){var n;C((n=this._instance)==null?void 0:n._addCaptureHook)||(this.Fs(e),this.Ls(e))}Ls(e){var n=e.filter((i=>{var r,s;return((r=i.conditions)==null?void 0:r.actions)&&((s=i.conditions)==null||(s=s.actions)==null||(s=s.values)==null?void 0:s.length)>0}));n.length!==0&&(this.Os==null&&(this.Os=new Dm(this._instance),this.Os.init(),this.Os.fs((i=>{this.onAction(i)}))),n.forEach((i=>{var r,s,o,a,l;i.conditions&&(r=i.conditions)!=null&&r.actions&&(s=i.conditions)!=null&&(s=s.actions)!=null&&s.values&&((o=i.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.Os)==null||a.register(i.conditions.actions.values),(l=i.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var c=this.xs.get(u.name);c&&c.push(i.id),this.xs.set(u.name,c||[i.id])}})))})))}Fs(e){var n,i=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.events)&&((a=s.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0})),r=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.cancelEvents)&&((a=s.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0}));i.length===0&&r.length===0||((n=this._instance)==null||n._addCaptureHook(((s,o)=>{this.onEvent(s,o)})),this.ws=this.Ps(e,wi.Activation),this.ks=this.Ps(e,wi.Cancellation))}onEvent(e,n){var i,r,s=this.Ds(),o=(n==null||(i=n.properties)==null?void 0:i.$survey_id)||(n==null||(r=n.properties)==null?void 0:r.$product_tour_id);if(o&&this.getActivatedIds().includes(o)){var a=this.$s(e,o);if(a==="consume")return s.info("event consumed activated item, removing it",{event:e,itemId:o}),void this.Ns([o]);if(a==="persist")return s.info("shown item promoted to persisted activation",{event:e,itemId:o}),this.qs(o),void this.js([o])}if(this.ks.has(e)){var l=this.Rs(e,n,wi.Cancellation);l.length>0&&(s.info("cancel event matched, cancelling items",{event:e,itemsToCancel:l.map((c=>c.id))}),this.Ns(l.map((c=>c.id))),l.forEach((c=>this.Bs(c.id))))}if(this.ws.has(e)){s.info("event name matched",{event:e,eventPayload:n,items:this.ws.get(e)});var u=this.Rs(e,n,wi.Activation);this.Hs(u.map((c=>c.id)))}}onAction(e){this.xs.has(e)&&this.Hs(this.xs.get(e)||[])}Hs(e){var n;if(e.length!==0){var i=!((n=this._instance)==null||n.get_session_id==null||!n.get_session_id()),r=[];for(var s of e)i&&this.Cs(s)?this.qs(s)&&this.Us(s):r.push(s);r.length>0&&(this._s=[...new Set([...this._s,...r])]),this.Ds().info("updating activated items",{activatedItems:this.getActivatedIds()})}}qs(e){this._s=this._s.filter((i=>i!==e));var n=this.zs();return!n.includes(e)&&(this.Ws([...n,e]),this.Vs(),!0)}Ns(e){var n=new Set(e);this._s=this._s.filter((s=>!n.has(s)));var i=this.Zs(),r=i.filter((s=>!n.has(s)));r.length!==i.length&&(this.Ws(r),r.length===0&&this.Gs()),this.js(e)}Qs(){var e,n=this.Ms();if(!n)return{};var i=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n];return i&&typeof i=="object"?i:{}}Us(e){if(this.Ms()){var n=this.Qs();this.Ts(I({},n,{[e]:Date.now()}))}}js(e){if(this.Ms()){var n=this.Qs(),i={},r=!1;for(var s of Object.entries(n)){var o=s[0],a=s[1];e.includes(o)?r=!0:i[o]=a}r&&(Kt(i)?this.Es():this.Ts(i))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var n=this.Qs()[e];return ke(n)?n:void 0}}Zs(){var e,n=this.Js();return((e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n])||[]}zs(){var e,n,i=this.Zs();if(i.length===0)return[];var r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[this.Ys()],s=(n=this._instance)==null||n.get_session_id==null?void 0:n.get_session_id();return s&&r===s?i:[]}Vs(){var e,n=(e=this._instance)==null||e.get_session_id==null?void 0:e.get_session_id();n&&this.Xs(n)}Gs(){this.ta()}Ss(e){var n,i=(n=this._instance)==null||(n=n.persistence)==null?void 0:n.props[this.Ys()];if(i&&i!==e){var r=this.Zs(),s=this.Qs();r.length>0&&(this.Ws([]),r.filter((o=>ke(s[o]))).forEach((o=>this.Bs(o)))),this.Gs(),this.Ks()}}getActivatedIds(){return[...new Set([...this.zs(),...this._s])].filter((e=>!this.ea(e)))}reset(){this._s=[],this.Zs().length>0&&this.Ws([]),this.Gs(),this.Ks()}getEventToItemsMap(){return this.ws}ia(){return this.Os}}class Um extends jm{constructor(e){super(e)}Js(){return ua}Ys(){return Fr}Ms(){return Rr}Ts(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Rr]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Rr)}Cs(e){var n,i;this.As((s=>{i=s.find((o=>o.id===e))}));var r=(n=i)==null||(n=n.appearance)==null?void 0:n.surveyPopupDelaySeconds;return ke(r)&&r>0}ra(){return qt.SHOWN}As(e){var n;(n=this._instance)==null||n.getSurveys(e)}Bs(e){var n;(n=this._instance)==null||n.cancelPendingSurvey(e)}Ds(){return Q}Ws(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[ua]:e})}Xs(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Fr]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Fr)}ea(){return!1}$s(e,n){var i;this.As((s=>{i=s.find((o=>o.id===n))}));var r=!i||(function(s){var o;return qf(s)&&!((o=s.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||s.schedule==="always"})(i);return r?e===qt.SHOWN?"consume":"ignore":e===qt.SHOWN?"persist":e===qt.DISMISSED||e===qt.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var Ir="SDK is not enabled or survey functionality is not yet loaded",fu="Disabled. Not loading surveys.",Hm=w!=null&&w.location?os(w.location.hash,"__posthog")||os(location.hash,"state"):null,hu="_postHogToolbarParams",pu=pe("[Toolbar]"),gu=pe("[FeatureFlags]");class Wm{constructor(e,n){n===void 0&&(n=!1),this.na=!1,this.update(e,n)}update(e,n){this.sa=((i,r)=>{var s,o,a,l;return{bootstrap:{featureFlags:(s=i.bootstrap)==null?void 0:s.featureFlags,featureFlagPayloads:(o=i.bootstrap)==null?void 0:o.featureFlagPayloads},remoteRequestsDisabled:r,featureFlagsDisabled:!!i.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!i.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!i.advanced_feature_flags_dedup_per_session,cacheTtlMs:i.feature_flag_cache_ttl_ms,requestTimeoutMs:i.feature_flag_request_timeout_ms,compression:i.disable_compression?"none":"base64",evaluationContexts:(a=(l=i.evaluation_contexts)!==null&&l!==void 0?l:i.evaluation_environments)!==null&&a!==void 0?a:[],flagKeys:U(i.flag_keys)?i.flag_keys:void 0}})(e,n),!e.evaluation_environments||e.evaluation_contexts||this.na||(gu.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.na=!0),C(e.flag_keys)||U(e.flag_keys)||gu.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var mu=pe("[FeatureFlags]"),bn=pe("[FeatureFlags]",{debugEnabled:!0}),Do=`" failed. Feature flags didn't load in time.`,vu="connection_error",_u=t=>{for(var e={},n=0;t.length>n;n++)e[t[n]]=!0;return e},yu=t=>{var e={};for(var n of $r(t||{})){var i=n[1];i&&(e[n[0]]=i)}return e},St=pe("[Error tracking]"),wu="Refusing to render web experiment since the viewer is a likely bot",zm={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>cs(e,t),not_regex:(t,e)=>!cs(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class Me{get Ne(){return this._instance.config}constructor(e){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(i){i===void 0&&(i=!1),n.getWebExperiments((r=>{Me.aa("retrieved web experiments from the server"),n.oa=new Map,r.forEach((s=>{if(s.feature_flag_key){var o;n.oa&&(Me.aa("setting flag key ",s.feature_flag_key," to web experiment ",s),(o=n.oa)==null||o.set(s.feature_flag_key,s));var a=n._instance.getFeatureFlag(s.feature_flag_key);X(a)&&s.variants[a]&&n.la(s.name,a,s.variants[a].transforms)}else if(s.variants)for(var l in s.variants){var u=s.variants[l];Me.ua(u,n._instance)&&n.la(s.name,l,u.transforms)}}))}),i)},this._instance=e,this._instance.onFeatureFlags((i=>{this.onFeatureFlags(i)}))}initialize(){}onFeatureFlags(e){if(this._is_bot())Me.aa(wu);else if(!this.Ne.disable_web_experiments){if(H(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();Me.aa("applying feature flags",e),e.forEach((n=>{var i;if(this.oa&&(i=this.oa)!=null&&i.has(n)){var r,s=this._instance.getFeatureFlag(n),o=(r=this.oa)==null?void 0:r.get(n);s&&o!=null&&o.variants[s]&&this.la(o.name,s,o.variants[s].transforms)}}))}}previewWebExperiment(){var e=Me.getWindowLocation();if(e!=null&&e.search){var n=ii(e?.search,"__experiment_id"),i=ii(e?.search,"__experiment_variant");n&&i&&(Me.aa("previewing web experiments "+n+" && "+i),this.getWebExperiments((r=>{this.ha(parseInt(n),i,r)}),!1,!0))}}loadIfEnabled(){this.Ne.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,n,i){if(this.Ne.disable_web_experiments&&!i)return e([]);var r=this._instance.get_property("$web_experiments");if(r&&!n)return e(r);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this.Ne.token),method:"GET",timestampMode:"query",callback:s=>e(s.statusCode===200&&s.json&&s.json.experiments||[])})}ha(e,n,i){var r=i.filter((s=>s.id===e));r&&r.length>0&&(Me.aa("Previewing web experiment ["+r[0].name+"] with variant ["+n+"]"),this.la(r[0].name,n,r[0].variants[n].transforms))}static ua(e,n){return!H(e.conditions)&&Me.da(e,n)&&Me.va(e)}static da(e,n){var i;if(H(e.conditions)||H((i=e.conditions)==null?void 0:i.url))return!0;var r=Me.getWindowLocation();if(r){var s,o,a,l=af(n,r.href);return(s=e.conditions)==null||!s.url||zm[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return w?.location}static va(e){var n;if(H(e.conditions)||H((n=e.conditions)==null?void 0:n.utm))return!0;var i=Ef();if(i.utm_source){var r,s,o,a,l,u,c,d,f=(r=e.conditions)==null||(r=r.utm)==null||!r.utm_campaign||((s=e.conditions)==null||(s=s.utm)==null?void 0:s.utm_campaign)==i.utm_campaign,h=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==i.utm_source,p=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==i.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==i.utm_term;return f&&p&&g&&h}return!1}static aa(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;n>r;r++)i[r-1]=arguments[r];A.info("[WebExperiments] "+e,i)}la(e,n,i){this._is_bot()?Me.aa(wu):n!=="control"?i.forEach((r=>{if(r.selector){var s;Me.aa("applying transform of variant "+n+" for experiment "+e+" ",r);var o=(s=document)==null?void 0:s.querySelectorAll(r.selector);o?.forEach((a=>{var l=a;r.html&&(l.innerHTML=r.html),r.css&&l.setAttribute("style",r.css)}))}})):Me.aa("Control variants leave the page unmodified.")}_is_bot(){return He&&this._instance?Uf(He,this.Ne.custom_blocked_useragents):void 0}}var ot=pe("[Conversations]"),En="Conversations not available yet.",bu="console",Jf="__posthogHandledLogsRequestError",jo=(t,e)=>{var n=t instanceof Error?t:new Error(e);return n[Jf]=!0,n},Eu=t=>!!t&&typeof t=="object"&&t[Jf]===!0,As={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=mu,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 Wm(t.config,t.Qi()),this.Ta=this.Ea)}updateConfig(t,e){var n;(n=this.Ea)==null||n.update(t,e)}setup(t){return this.Ia=t,this.rt=t.logger.createLogger("[FeatureFlags]"),n=()=>{this.Ia===t&&(this.Ia=void 0,this.nn=t,this.Pa(t))},(e=t.kv.initialize())!=null&&e.then?e.then(n):n();var e,n}Pa(t){if(this.nn===t)return w&&ve(w,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){w?.removeEventListener("online",this.Ca)}dispose(){var t;this.ba++,this.wa=!1,this.Ia=void 0,this.nn&&(this.La(),(t=this.Ra)==null||t.dispose(),this.Ra=void 0,this.ga=[],w?.removeEventListener("online",this.Ca),this.nn=void 0)}get Ne(){return this.Ta.get()}Oa(t){var e;return(e=this.nn)==null?void 0:e.kv.get(t)}F(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.set(t)}))}q(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.remove(t)}))}Da(t){try{t()}catch(e){this.rt.error("Failed to update feature flag persistence",e)}}Fa(){var t={};for(var e of[Ti,$i,Pr,It]){var n=this.Oa(e);C(n)||(t[e]=n)}this.fa=t;var i=I({},t),r=this.Oa(Sn);if(r)for(var s of Object.entries(r))i["$feature/"+s[0]]=s[1];this.pa=i}Aa(){var t=this.Ne.cacheTtlMs;if(!t||0>=t)return!1;var e=this.Oa(ji);return typeof e!="number"||Date.now()-e>t}$a(){return!!this.Aa()&&(this.xa||this.ya||(this.xa=!0,this.rt.warn("Feature flag cache is stale, triggering refresh..."),this.reloadFeatureFlags()),!0)}Na(){var t=this.Ne.evaluationContexts;return t!=null&&t.length?t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid evaluation context found:",e,"Expected non-empty string"),n})):[]}qa(){var t=this.Ne.flagKeys;if(!C(t))return t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid flag key found:",e,"Expected non-empty string"),n}))}initialize(){var t,e,n=this.Ne,i=(t=(e=n.bootstrap)==null?void 0:e.featureFlags)!==null&&t!==void 0?t:{};if(Object.keys(i).length){var r,s,o=(r=(s=n.bootstrap)==null?void 0:s.featureFlagPayloads)!==null&&r!==void 0?r:{},a=Object.keys(i).filter((u=>!!i[u])).reduce(((u,c)=>(u[c]=i[c]||!1,u)),{}),l=Object.keys(o).filter((u=>a[u])).reduce(((u,c)=>(o[c]&&(u[c]=o[c]),u)),{});return this.ja({featureFlags:a,featureFlagPayloads:l})}}updateFlags(t,e,n){var i,r,s=n!=null&&n.merge&&(i=this.Oa(Sn))!==null&&i!==void 0?i:{},o=n!=null&&n.merge&&(r=this.Oa($i))!==null&&r!==void 0?r:{},a=I({},s,t),l=I({},o,e),u={};for(var c of Object.entries(a)){var d=c[0],f=c[1];u[d]={key:d,enabled:pc(f),variant:gc(f),reason:void 0,metadata:C(l?.[d])?void 0:{id:0,version:void 0,description:void 0,payload:l[d]}}}this.ja({flags:u})}get hasLoadedFlags(){return this.ma}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var t=this.Oa(la),e=this.Oa(It),n=this.Oa(xn);if(!n&&!e)return t||{};var i=fe({},t||{}),r=[...new Set([...Object.keys(n||{}),...Object.keys(e||{})])];for(var s of r){var o,a,l=i[s],u=e?.[s],c=C(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=C(u)?l?.variant:typeof u=="string"?u:void 0,f=n?.[s],h=I({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(h.original_enabled=l?.enabled),d!==l?.variant&&(h.original_variant=l?.variant),f&&(h.metadata=I({},l?.metadata,{payload:f,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),i[s]=h}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:n,finalDetails:i}),this.ca=!0),i}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((n=>{var i=t[n];return{key:n,enabled:pc(i),variant:gc(i),payload:hc(e[n])}}))}getFlagVariants(){var t=this.Oa(Sn),e=this.Oa(It);if(!e)return t||{};for(var n=fe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:e,finalFlags:n}),this.ca=!0),n}getFlagPayloads(){var t=this.Oa($i),e=this.Oa(xn);if(!e)return t||{};for(var n=fe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flag payloads!",{flagPayloads:t,overriddenPayloads:e,finalPayloads:n}),this.ca=!0),n}reloadFeatureFlags(){this._a||this.Ne.featureFlagsDisabled||this.Ma()||this.Ba||(this.ga.slice().forEach((t=>{try{t()}catch(e){this.rt.error("Error while running feature flags reloading callback",e)}})),this.Ba=setTimeout((()=>{this.Ha()}),5))}La(){clearTimeout(this.Ba),this.Ba=void 0}onReloading(t){return this.ga.push(t),()=>{this.ga=this.ga.filter((e=>e!==t))}}ensureFlagsLoaded(){this.ma||this.ya||this.Ba||this.reloadFeatureFlags()}setAnonymousDistinctId(t){this.$anon_distinct_id=t}setReloadingPaused(t){this._a=t}resetFlagCallReported(){this.q(Cn)}Ha(t){this.La();var e=this.nn;if(e&&!this.Ne.remoteRequestsDisabled&&!this.Ma())if(this.ya)this.wa=!0;else{var n={token:e.projectToken,distinct_id:e.distinctId,groups:e.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:I({},e.initialPersonProperties,this.Oa(jt)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(In),timezone:Af()};C(e.deviceId)||(n.$device_id=e.deviceId),(t!=null&&t.disableFlags||this.Ne.featureFlagsDisabled)&&(n.disable_flags=!0);var i=this.Na();i.length&&(n.evaluation_contexts=i);var r=this.qa();C(r)||(n.flag_keys=r);var s=this.Ne.onlyEvaluateSurveyFeatureFlags,o="/flags/?v=2"+(s?"&only_evaluate_survey_feature_flags=true":""),a=this.ba;this.ya=!0;var l=()=>{this.wa&&(this.wa=!1,this.Ha())},u=c=>{this.ya=!1,a===this.ba&&(this.F({[Tr]:[vu]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:n,compression:this.Ne.compression==="base64"?Ue.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,f,h=(d=c.json)!==null&&d!==void 0?d:{},p=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),p||this.wa||(this.$anon_distinct_id=void 0),!n.disable_flags||this.wa){this.ka=!p;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?vu:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),h.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((f=h.quotaLimited)==null||!f.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[Tr]:g}),m?this.rt.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more."):n.disable_flags||this.ja(h,p,{partialResponse:s}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return wf(this.Sa,3)}Ua(t){this.Sa=bf(t,this.Sa,3,(()=>this.rt.warn("Feature flag requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped refreshing feature flags; will try again when connectivity changes.")))}getFeatureFlag(t,e){var n;if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var i=this.getFeatureFlagResult(t,e);return(n=i?.variant)!==null&&n!==void 0?n:i?.enabled}}else this.rt.warn('getFeatureFlag for key "'+t+Do)}getFeatureFlagDetails(t){return this.getFlagsWithDetails()[t]}getFeatureFlagPayload(t){var e=this.getFeatureFlagResult(t,{send_event:!1});return e?.payload}getFeatureFlagResult(t,e){if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var n,i=this.getFlagVariants(),r=t in i,s=i[t],o=this.getFlagPayloads()[t],a=String(s),l=this.Oa(Pr)||void 0,u=this.Oa(ji)||void 0,c=this.Oa(Cn)||{};if(this.Ne.deduplicateCallsPerSession){var d,f=(d=this.nn)==null?void 0:d.session.sessionId,h=this.Oa(Li);f&&f!==h&&(c={},n=f)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))n&&this.F({[Cn]:c,[Li]:n});else{var p,g,m,v,E,S,_,b,k,T;U(c[t])?c[t].push(a):c[t]=[a],this.F(I({[Cn]:c},n?{[Li]:n}:{}));var x=this.getFeatureFlagDetails(t),F=[...(p=this.Oa(Tr))!==null&&p!==void 0?p:[]];C(s)&&F.push("flag_missing");var $={$feature_flag:t,$feature_flag_response:s,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((g=this.Ne.bootstrap)==null||(g=g.featureFlags)==null?void 0:g[t])||null,$feature_flag_bootstrapped_payload:((m=this.Ne.bootstrap)==null||(m=m.featureFlagPayloads)==null?void 0:m[t])||null,$used_bootstrap_value:!this.ka};C(x==null||(v=x.metadata)==null?void 0:v.has_experiment)||($.$feature_flag_has_experiment=x.metadata.has_experiment),C(x==null||(E=x.metadata)==null?void 0:E.version)||($.$feature_flag_version=x.metadata.version);var O,L=(S=x==null||(_=x.reason)==null?void 0:_.description)!==null&&S!==void 0?S:x==null||(b=x.reason)==null?void 0:b.code;L&&($.$feature_flag_reason=L),x!=null&&(k=x.metadata)!=null&&k.id&&($.$feature_flag_id=x.metadata.id),C(x?.original_variant)&&C(x?.original_enabled)||($.$feature_flag_original_response=C(x.original_variant)?x.original_enabled:x.original_variant),x!=null&&(T=x.metadata)!=null&&T.original_payload&&($.$feature_flag_original_payload=x==null||(O=x.metadata)==null?void 0:O.original_payload),F.length&&($.$feature_flag_error=F.join(",")),this.za($)}else n&&this.F({[Cn]:c,[Li]:n});if(r)return{key:t,enabled:!!s,variant:typeof s=="string"?s:void 0,payload:hc(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+Do)}za(t){try{var e;(e=this.nn)==null||e.capture("$feature_flag_called",t).catch((n=>{this.rt.error("Failed to capture feature flag call",n)}))}catch(n){this.rt.error("Failed to capture feature flag call",n)}}getRemoteConfigPayload(t,e){this.Wa(t,e)}Wa(t,e){var n=this;return se((function*(){var i=n.nn;if(i){var r={distinct_id:i.distinctId,token:i.projectToken,person_properties:{$lib:i.library.name,$lib_version:i.library.version}},s=n.Na();s.length&&(r.evaluation_contexts=s);var o,a=n.qa();C(a)||(r.flag_keys=a);try{var l,u=(l=(yield i.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:r,compression:n.Ne.compression==="base64"?Ue.Base64:void 0,sentAt:"body",timeoutMs:n.Ne.requestTimeoutMs})).json)==null?void 0:l.featureFlagPayloads;o=u?.[t]||void 0}catch(c){return void n.rt.error("Remote config feature flag request failed",c)}try{e(o)}catch(c){n.rt.error("Remote config feature flag callback failed",c)}}}))()}isFeatureEnabled(t,e){if(e===void 0&&(e={}),e.fresh&&!this.ka)return e.defaultValue;if(!(this.ma||this.getFlags()&&this.getFlags().length>0))return this.rt.warn('isFeatureEnabled for key "'+t+Do),e.defaultValue;var n=this.getFeatureFlag(t,e);return C(n)?e.defaultValue:!!n}addFeatureFlagsHandler(t){this.featureFlagEventHandlers.push(t)}removeFeatureFlagsHandler(t){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((e=>e!==t))}receivedFeatureFlags(t,e,n){this.ja(t,e,n)}ja(t,e,n){if(this.nn){this.ma=!0;var i=(function(r,s,o,a,l,u){s===void 0&&(s={}),o===void 0&&(o={}),a===void 0&&(a={}),u===void 0&&(u=mu);var c=((k,T)=>{var x=k.flags;return x?I({},k,{featureFlags:Object.fromEntries(Object.keys(x).map((F=>{var $;return[F,($=x[F].variant)!==null&&$!==void 0?$:x[F].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(x).filter((F=>x[F].enabled)).filter((F=>{var $;return($=x[F].metadata)==null?void 0:$.payload})).map((F=>{var $;return[F,($=x[F].metadata)==null?void 0:$.payload]})))}):(k.featureFlags&&T.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),k)})(r,u),d=c.flags,f=c.featureFlags,h=c.featureFlagPayloads;if(f){var p=r.requestId,g=r.evaluatedAt;if(U(f)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(f)for(var v=0;f.length>v;v++)m[f[v]]=!0;return{[Ti]:f,[Sn]:m,[Zr]:!1}}var E=f,S=h,_=d;if(l!=null&&l.partialResponse)E=I({},s,E),S=I({},o,S),_=I({},a,_);else if(r.errorsWhileComputingFlags)if(d){var b=new Set(Object.keys(d).filter((k=>{var T;return!((T=d[k])!=null&&T.failed)})));E=I({},s,Object.fromEntries(Object.entries(E).filter((k=>b.has(k[0]))))),S=I({},o,Object.fromEntries(Object.entries(S||{}).filter((k=>b.has(k[0]))))),_=I({},a,Object.fromEntries(Object.entries(_||{}).filter((k=>b.has(k[0])))))}else E=I({},s,E),S=I({},o,S),_=I({},a,_);return I({[Ti]:Object.keys(yu(E)),[Sn]:E||{},[$i]:S||{},[la]:_||{},[Zr]:r.minimalFlagCalledEvents===!0},p?{[Pr]:p}:{},g?{[ji]:g}:{})}})(t,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),n,this.rt);i&&this.F(i),e||(this.xa=!1),this.Va(e)}}override(t,e){e===void 0&&(e=!1),this.rt.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:t,suppressWarning:e})}overrideFeatureFlags(t){this.Za(t)}Za(t){if(this.nn){if(t===!1)return this.q([It,xn]),this.Va(),void bn.info("All overrides cleared");if(U(t))return this.F({[It]:_u(t)}),this.Va(),void bn.info("Flag overrides set",{flags:t});if(t&&typeof t=="object"&&("flags"in t||"payloads"in t)){var e,n=t;this.ca=!!((e=n.suppressWarning)!==null&&e!==void 0&&e);var i={},r=n.flags,s=n.payloads;return r&&(i[It]=U(r)?_u(r):r),s&&(i[xn]=s),Object.keys(i).length&&this.F(i),r===!1&&s===!1?this.q([It,xn]):r===!1?this.q(It):s===!1&&this.q(xn),this.Va(),r===!1?bn.info("Flag overrides cleared"):r&&bn.info("Flag overrides set",{flags:r}),void(s===!1?bn.info("Payload overrides cleared"):s&&bn.info("Payload overrides set",{payloads:s}))}if(t&&typeof t=="object")return this.F({[It]:t}),this.Va(),void bn.info("Flag overrides set",{flags:t});this.rt.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:t})}else this.rt.warn("posthog.featureFlags.overrideFeatureFlags called before feature flags were ready")}onFeatureFlags(t){if(this.addFeatureFlagsHandler(t),this.ma){var e=this.Ga(),n=e.flags,i=e.flagVariants;try{t(n,i)}catch(r){this.rt.error("Error while running feature flags callback",r)}}return()=>this.removeFeatureFlagsHandler(t)}updateEarlyAccessFeatureEnrollment(t,e,n){var i=(this.Oa(Ar)||[]).find((l=>l.flagKey===t)),r={["$feature_enrollment/"+t]:e},s={$feature_flag:t,$feature_enrollment:e,$set:r};i&&(s.$early_access_feature_name=i.name),n&&(s.$feature_enrollment_stage=n);var o=I({},this.getFlagVariants(),{[t]:e});this.F({[Ti]:Object.keys(yu(o)),[Sn]:o,[jt]:I({},this.Oa(jt)||{},r)}),this.Va();try{var a;(a=this.nn)==null||a.capture("$feature_enrollment_update",s).catch((l=>{this.rt.error("Failed to capture early access feature enrollment",l)}))}catch(l){this.rt.error("Failed to capture early access feature enrollment",l)}}getEarlyAccessFeatures(t,e,n){e===void 0&&(e=!1);var i=this.Oa(Ar);!i||e?this.Qa(t,n):t(i)}Qa(t,e){var n=this;return se((function*(){var i=n.nn;if(i){var r,s=e?"&"+e.map((a=>"stage="+a)).join("&"):"";try{var o=yield i.sendRequest("/api/early_access_features/?token="+i.projectToken+s,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;n.F({[Ar]:r=o.json.earlyAccessFeatures})}catch(a){return void n.rt.error("Early access feature request failed",a)}try{t(r)}catch(a){n.rt.error("Early access feature callback failed",a)}}}))()}Ga(){var t=this.getFlags(),e=this.getFlagVariants();return{flags:t.filter((n=>e[n])),flagVariants:Object.keys(e).filter((n=>e[n])).reduce(((n,i)=>(n[i]=e[i],n)),{})}}Va(t){this.Fa();var e=this.Ga(),n=e.flags,i=e.flagVariants;this.featureFlagEventHandlers.forEach((r=>{try{r(n,i,{errorsLoading:t})}catch(s){this.rt.error("Error while running feature flags callback",s)}}))}setPersonPropertiesForFlags(t,e){e===void 0&&(e=!0),this.Ka(t,e)}Ka(t,e){e===void 0&&(e=!0);var n=this.Oa(jt)||{},i=t?.$set||(t!=null&&t.$set_once?{}:t),r=t?.$set_once,s={};if(r)for(var o in r)({}).hasOwnProperty.call(r,o)&&(o in n||(s[o]=r[o]));this.F({[jt]:I({},n,s,i)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=I({},this.Oa(jt)||{});t.forEach((i=>{delete n[i]})),this.F({[jt]:n}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(jt),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=this.Oa(In)||{},i=I({},n);for(var r of Object.keys(t))i[r]=I({},n[r],t[r]);this.F({[In]:i}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(In)||{};this.F({[In]:I({},e,{[t]:{}})})}else this.q(In)}reset(){this.ba++,this.wa=!1,this.Fa(),this.ma=!1,this._a=!1,this.ka=!1,this.$anon_distinct_id=void 0,this.La(),this.ca=!1,this.Sa=0}}},qm={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===ki||this.Ya===Sr?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=cu,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(P==null||!P.visibilityState||P.visibilityState==="visible")return!0;var n=w==null||(e=w.performance)==null||e.getEntriesByType==null?void 0:e.getEntriesByType("visibility-state");return!(n!=null&&n.length)||n.some((i=>i.name==="visible"))})(),this.Ie=()=>{var e;P?.visibilityState==="visible"&&(this.io=!0,(e=this.Ja)==null||e.setDocumentWasEverVisible==null||e.setDocumentWasEverVisible(!0))},this._instance=t,!this._instance.sessionManager)throw Bt.error("started without valid sessionManager"),new Error(ka+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===Wt)throw new Error(ka+' cannot be used with cookieless_mode="always"');P!=null&&P.addEventListener&&ve(P,"visibilitychange",this.Ie)}initialize(){this.startIfEnabledOrStop()}dispose(){this.eo=!0,P==null||P.removeEventListener==null||P.removeEventListener("visibilitychange",this.Ie),this.stopRecording()}get ro(){var t,e=!((t=this._instance.get_property(An))==null||!t.enabled),n=!this.Ne.disable_session_recording,i=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return w&&e&&n&&!i}startIfEnabledOrStop(t){var e;if(!(this.eo||this.ro&&(e=this.Ja)!=null&&e.isStarted)){var n=!C(Object.assign)&&!C(Array.from);this.ro&&n?(this.no(t),Bt.info("starting")):(this.Ya=cu,this.stopRecording())}}no(t){var e,n,i;this.ro&&(this.Ya!==ki&&this.Ya!==Sr&&(this.Ya=uu),B!=null&&(e=B.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(n=B.__PosthogExtensions__)!=null&&n.initSessionRecording?this.so(t):(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,this.ao,(r=>{if(r)return Bt.error("could not load recorder",r);this.so(t)})))}stopRecording(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.stop()}oo(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.discard()}lo(){var t,e;(t=this.Mr)==null||t.unregister(al),(e=this.Mr)==null||e.unregister(Yd)}uo(t,e){if(H(t))return null;var n,i=ke(t)?t:parseFloat(t);return typeof(n=i)!="number"||!Number.isFinite(n)||0>n||n>1?(Bt.warn(e+" must be between 0 and 1. Ignoring invalid value:",t),null):i}ho(t){if(this.Mr){var e,n,i=this.Mr,r=()=>{var s,o=t.sessionRecording===!1?void 0:t.sessionRecording,a=this.uo((s=this.Ne.session_recording)==null?void 0:s.sampleRate,"session_recording.sampleRate"),l=this.uo(o?.sampleRate,"remote config sampleRate"),u=a??l;H(u)&&this.lo();var c=o?.minimumDurationMilliseconds;i.register({[An]:I({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:I({capturePerformance:t.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:u,minimumDurationMilliseconds:C(c)?null:c,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers,version:o?.version,triggerGroups:o?.triggerGroups})})};r(),(e=this.Xa)==null||e.call(this),this.Xa=(n=this._instance.sessionManager)==null?void 0:n.onSessionId(r)}}onRemoteConfig(t){var e=t.ok?t.config:void 0;return e&&"sessionRecording"in e?e.sessionRecording===!1?(this.ho(e),void this.oo()):(this.ho(e),void this.startIfEnabledOrStop()):(this.Ya===ki&&(this.Ya=Sr,Bt.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(t,e){var n;e===void 0&&(e="log"),(n=this.Ja)!=null&&n.log?this.Ja.log(t,e):Bt.warn("log called before recorder was ready")}get ao(){var t,e,n=(t=this._instance)==null||(t=t.persistence)==null?void 0:t.get_property(An);return(n==null||(e=n.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(An);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(n){return Bt.warn("persisted remote config for session recording is invalid and will be ignored",n),!1}return!H(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,n,i;if(!this.eo){if((e=B.__PosthogExtensions__)==null||!e.initSessionRecording)return Bt.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[rf]:!0});var r;if(this.Ja||(this.Ja=(r=B.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===Sr||this.Ya===ki?void 0:(this.Ya=ki,Bt.info("persisted remote config is stale, requesting fresh config before starting"),void new Pf(this._instance).load());this.Ya=uu,(n=(i=this.Ja).setDocumentWasEverVisible)==null||n.call(i,this.io),this.Ja.start(t)}}onRRwebEmit(t){var e;(e=this.Ja)==null||e.onRRwebEmit==null||e.onRRwebEmit(t)}overrideLinkedFlag(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Zd]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Jd]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,n;this.Ja||(n=this.Mr)==null||n.register({[t==="url"?Xd:Qd]:!0}),(e=this.Ja)==null||e.overrideTrigger(t)}get sdkDebugProperties(){var t;return((t=this.Ja)==null?void 0:t.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(t,e){var n;return!((n=this.Ja)==null||!n.tryAddCustomEvent(t,e))}}},Vm={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new ou(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,n=he(this.instance.config.autocapture)?this.instance.config.autocapture:{};return n.url_allowlist=(t=n.url_allowlist)==null?void 0:t.map((i=>new RegExp(i))),n.url_ignorelist=(e=n.url_ignorelist)==null?void 0:e.map((i=>new RegExp(i))),n}yo(){if(this.isBrowserSupported()){if(w&&P){var t=n=>{n=n||w?.event;try{this.bo(n)}catch(i){Lo.error("Failed to capture event",i)}};if(ve(P,"submit",t,{capture:!0}),ve(P,"change",t,{capture:!0}),ve(P,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=n=>{n=n||w?.event;try{this.bo(n,Mo)}catch(i){Lo.error("Failed to capture copy/cut event",i)}};ve(P,"copy",e,{capture:!0}),ve(P,"cut",e,{capture:!0})}}}else Lo.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.vo&&(this.yo(),this.vo=!0)}onRemoteConfig(t){if(this.fo=!0,t.ok){var e=t.config;e.elementsChainAsString&&(this.po=e.elementsChainAsString);var n=e.autocapture_opt_out;mt(n)&&(this.instance.persistence&&this.instance.persistence.register({[ta]:n}),this.co=n),this.startIfEnabled()}else this.startIfEnabled()}setElementSelectors(t){this.mo=t}getElementSelectors(t){var e,n=[];return(e=this.mo)==null||e.forEach((i=>{var r=P?.querySelectorAll(i);r?.forEach((s=>{t===s&&n.push(i)}))})),n}get isEnabled(){var t,e,n=(t=this.instance.persistence)==null?void 0:t.props[ta],i=this.co,r=this.instance.Qi()&&!this.fo;if(Ye(i)&&!mt(n)&&!r)return!1;var s=(e=this.co)!==null&&e!==void 0?e:!!n;return!!this.instance.config.autocapture&&!s}bo(t,e){if(e===void 0&&(e="$autocapture"),this.isEnabled){var n,i=Eo(t);cf(i)&&(i=i.parentNode||null),e==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&this.instance.config.rageclick&&(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,t.timeStamp||new Date().getTime())&&Nc(i,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var r=e===Mo;if(i&&(function(d,f,h,p,g,m){var v;if(!w||fl(d)||h!=null&&h.url_allowlist&&!$c(h.url_allowlist,m)||h!=null&&h.url_ignorelist&&$c(h.url_ignorelist,m))return!1;if(h!=null&&h.dom_event_allowlist){var E=h.dom_event_allowlist;if(E&&!E.some((x=>f.type===x)))return!1}var S=gf(d,p),_=S.parentIsUsefulElement,b=S.targetElementList;if(!(function(x,F){var $=F?.element_allowlist;if(C($))return!0;var O,L=function(K){if($.some((V=>K.tagName.toLowerCase()===V)))return{v:!0}};for(var N of x)if(O=L(N))return O.v;return!1})(b,h)||!va(b,h?.css_selector_allowlist)||va(b,(v=h?.css_selector_ignorelist)!==null&&v!==void 0?v:Wg))return!1;try{var k=w.getComputedStyle(d);if(k&&k.getPropertyValue("cursor")==="pointer"&&f.type==="click")return!0}catch{}var T=d.tagName.toLowerCase();switch(T){case"html":return!1;case"form":return(g||["submit"]).indexOf(f.type)>=0;case"input":case"select":case"textarea":return(g||["change","click"]).indexOf(f.type)>=0;default:return _?(g||["click"]).indexOf(f.type)>=0:(g||["click"]).indexOf(f.type)>=0&&(dl.indexOf(T)>-1||d.getAttribute("contenteditable")==="true")}})(i,t,this.Ne,r,r?["copy","cut"]:void 0,this.instance)){var s=Lm(i,{e:t,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.Ne.element_attribute_ignorelist,elementsChainAsString:this.po,disableCaptureUrlHashes:this.instance.config.disable_capture_url_hashes}),o=s.props;if(s.explicitNoCapture)return!1;var a=this.getElementSelectors(i);if(a&&a.length>0&&(o.$element_selectors=a),e===Mo){var l,u=ff(w==null||(l=w.getSelection())==null?void 0:l.toString()),c=t.type||"clipboard";if(!u)return!1;o.$selected_content=u,o.$copy_type=c}return this.instance.capture(e,o),!0}}}isBrowserSupported(){return je(P?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(w==null||(e=w.location)==null?void 0:e.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(A.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.wo&&this.wo(),this.wo=void 0,A.info("History API monitoring stopped")}monitorHistoryChanges(){w&&w.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(w&&((e=w.history[t])==null||!e.__posthog_wrapped__)){var n=this;(function(i,r,s){try{if(!(r in i))return au;var o={next:i[r]},a=s((function(){for(var l=arguments.length,u=new Array(l),c=0;l>c;c++)u[c]=arguments[c];return o.next.apply(this,u)}));return je(a)&&(a.prototype=a.prototype||{},Object.defineProperties(a,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:o}})),i[r]=a,()=>{if(i[r]!==a)for(var l=i[r];je(l)&&l.__posthog_layer__;){var u=l.__posthog_layer__;if(u.next===a)return void(u.next=o.next);l=u.next}else i[r]=o.next}}catch{return au}})(w.history,t,(i=>function(r,s,o){i.call(this,r,s,o),n.So(t)}))}}So(t){try{var e,n=w==null||(e=w.location)==null?void 0:e.pathname;if(!n)return;n!==this._o&&this.isEnabled&&this._instance.capture(Vn,{navigation_type:t}),this._o=n}catch(i){A.error("Error capturing "+t+" pageview",i)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};ve(w,"popstate",t),this.wo=()=>{w&&w.removeEventListener("popstate",t)}}}},heatmaps:class{get Ne(){return this.instance.config}constructor(t){var e;this.Co=!1,this.vo=!1,this.Mo=null,this.instance=t,this.Co=!((e=this.instance.persistence)==null||!e.props[na]),this.rageclicks=new ou(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return he(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return H(this.Ne.capture_heatmaps)?H(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;Om.info("starting..."),this.To(),this.Ie()}else{var t;clearInterval((t=this.Mo)!==null&&t!==void 0?t:void 0),this.Eo(),this.getAndClearBuffer()}}onRemoteConfig(t){if(t.ok){var e=t.config;if("heatmaps"in e){var n=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[na]:n}),this.Co=n,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){Oo(t.originalEvent)&&this.ke(t.originalEvent,"deadclick")}Ie(){this.Mo&&clearInterval(this.Mo),this.Mo=P?.visibilityState==="visible"?setInterval(this.cr.bind(this),this.flushIntervalMilliseconds):null}To(){w&&P&&(this.Po=this.cr.bind(this),ve(w,ns,this.Po),this.Ro=t=>this.ke(t||w?.event),ve(P,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||w?.event),ve(P,"mousemove",this.Ao,{capture:!0}),this.Lo=new Wc(this.instance,Jg,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),ve(P,ts,this.Oo),this.vo=!0)}Eo(){var t;w&&P&&(this.Po&&w.removeEventListener(ns,this.Po),this.Ro&&P.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&P.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&P.removeEventListener(ts,this.Oo),clearTimeout(this.Do),(t=this.Lo)==null||t.stop(),this.vo=!1)}$o(t,e){var n=this.instance.scrollManager.scrollY(),i=this.instance.scrollManager.scrollX(),r=this.instance.scrollManager.scrollElement(),s=(function(o,a,l){for(var u=o;u&&hn(u)&&!et(u,"body");){if(u===l)return!1;var c=void 0;try{var d,f,h;c=(d=(f=(h=u.ownerDocument)==null?void 0:h.defaultView)!==null&&f!==void 0?f:w)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(j(a,c))return!0;u=hf(u)}return!1})(Eo(t),["fixed","sticky"],r);return{x:t.clientX+(s?0:i),y:t.clientY+(s?0:n),target_fixed:s,type:e}}ke(t,e){var n;if(e===void 0&&(e="click"),!Tc(t.target)&&Oo(t)){var i=this.$o(t,e);(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,new Date().getTime())&&Nc(Eo(t),this.instance.config.rageclick)&&this.Vt(I({},i,{type:"rageclick"})),this.Vt(i)}}Fo(t){!Tc(t.target)&&Oo(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(w){var e=this.Ne.disable_capture_url_hashes?fn(w.location.href):w.location.href,n=this.Ne.custom_personal_data_properties,i=this.Ne.mask_personal_data_properties?[...ri,...n||[]]:[],r=Zi(e,i,Xi);this.R=this.R||{},this.R[r]||(this.R[r]=[]),this.R[r].push(t)}}cr(){this.R&&!Kt(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:Wc,webVitalsAutocapture:class{constructor(t){var e;this.Co=!1,this.vo=!1,this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this.No=()=>{clearTimeout(this.qo),this.qo=void 0,this.R.metrics.length!==0&&(this._instance.capture("$web_vitals",I({$current_url:this.R.url},this.R.metrics.reduce(((n,i)=>I({},n,{["$web_vitals_"+i.name+"_event"]:I({},i),["$web_vitals_"+i.name+"_value"]:i.value})),{}))),this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.jo=n=>{var i;if(this.R=this.R||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},H(n?.name)||H(n?.value))wn.error("Invalid metric received",n);else{var r=typeof n.navigationURL=="string"?n.navigationURL:void 0,s=this.Bo(r);if(!C(s)){var o=ke(n.navigationId)||typeof n.navigationId=="string"?"navigation:"+n.navigationId:"url:"+s;if(!this.Ho||this.Ho>n.value){this.R.navigationKey!==o&&(this.No(),this.qo=setTimeout(this.No,this.flushToCaptureTimeoutMs)),C(this.R.navigationKey)&&(this.R.navigationKey=o,this.R.url=s),this.R.firstMetricTimestamp=C(this.R.firstMetricTimestamp)?Date.now():this.R.firstMetricTimestamp,n.attribution&&n.attribution.interactionTargetElement&&(n.attribution.interactionTargetElement=void 0);var a=(i=this._instance.sessionManager)==null?void 0:i.checkAndGetSessionAndWindowId(!0),l=I({},n,r?{navigationURL:s}:{},{$current_url:s,timestamp:Date.now()});C(a)||(l.$session_id=a.sessionId,l.$window_id=a.windowId),this.R.metrics.push(l),this.R.metrics.length===this.allowedMetrics.length&&this.No()}else wn.error("Ignoring metric with value >= "+this.Ho,n)}}},this.Uo=()=>{if(!this.vo){var n,i,r,s,o=B.__PosthogExtensions__,a=o?.postHogWebVitalsCallbacksByFlavor,l=a?.[this.zo]||(this.zo==="web-vitals"&&C(a)?o?.postHogWebVitalsCallbacks:void 0);if(C(l)||(n=l.onLCP,i=l.onCLS,r=l.onFCP,s=l.onINP),n&&i&&r&&s){var u={reportSoftNavs:this.useSoftNavs};this.allowedMetrics.indexOf("LCP")>-1&&n(this.jo.bind(this),u),this.allowedMetrics.indexOf("CLS")>-1&&i(this.jo.bind(this),u),this.allowedMetrics.indexOf("FCP")>-1&&r(this.jo.bind(this),u),this.allowedMetrics.indexOf("INP")>-1&&s(this.jo.bind(this),u),this.vo=!0}else wn.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[oa]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,n=he(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return H(n)?((e=this._instance.persistence)==null?void 0:e.props[aa])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(he(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=he(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=he(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=he(this.Wo)&&ke(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:lu;return t>0&&6e4>=t?lu:t}get isEnabled(){var t=me?.protocol;if(t!=="http:"&&t!=="https:")return wn.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=he(this.Wo)?this.Wo.web_vitals:mt(this.Wo)?this.Wo:void 0;return mt(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(wn.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var n=he(e.capturePerformance)&&!!e.capturePerformance.web_vitals,i=he(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[oa]:n}),this._instance.persistence.register({[aa]:i})),this.Co=n,this.startIfEnabled()}}}get zo(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}ai(t){var e=B.__PosthogExtensions__,n=this.zo,i=e?.postHogWebVitalsCallbacksByFlavor;i!=null&&i[n]||n==="web-vitals"&&C(i)&&e!=null&&e.postHogWebVitalsCallbacks?t():e==null||e.loadExternalDependency==null||e.loadExternalDependency(this._instance,n,(r=>{r?wn.error("failed to load script",r):t()}))}Bo(t){var e=t||w?.location.href;if(e){var n=this._instance.config.disable_capture_url_hashes?fn(e):e,i=this._instance.config.custom_personal_data_properties,r=this._instance.config.mask_personal_data_properties?[...ri,...i||[]]:[];return Zi(n,r,Xi)}wn.error("Could not determine current URL")}}},Gm={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var n;if(w&&this.isEnabled&&(n=B.__PosthogExtensions__)!=null&&n.errorWrappingFunctions){var i=B.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,r=B.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,s=B.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.Vo&&this.Ne.capture_unhandled_errors&&(this.Vo=i(this.captureException.bind(this))),!this.Zo&&this.Ne.capture_unhandled_rejections&&(this.Zo=r(this.captureException.bind(this))),!this.Go&&this.Ne.capture_console_errors&&(this.Go=s(this.captureException.bind(this)))}catch(o){Ii.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[ia]),this.Jo=new qp(I({},(function(n){var i,r,s,o;return n===void 0&&(n={}),{refillRate:(i=(r=n.exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:n.__exceptionRateLimiterRefillRate)!==null&&i!==void 0?i:1,bucketSize:(s=(o=n.exceptionRateLimiterBucketSize)!==null&&o!==void 0?o:n.__exceptionRateLimiterBucketSize)!==null&&s!==void 0?s:10}})(this._instance.config.error_tracking),{refillInterval:1e4,rt:Ii})),this.Ne=this.Yo(),this.startIfEnabledOrStop()}Yo(){var t=this._instance.config.capture_exceptions,e={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return he(t)?e=I({},e,t):(C(t)?this.Ko:t)&&(e=I({},e,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),e}get isEnabled(){return this.Ne.capture_console_errors||this.Ne.capture_unhandled_errors||this.Ne.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(Ii.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",(i=>{if(i)return Ii.error("failed to load script",i);t()}))}Qo(){var t,e,n;(t=this.Vo)==null||t.call(this),this.Vo=void 0,(e=this.Zo)==null||e.call(this),this.Zo=void 0,(n=this.Go)==null||n.call(this),this.Go=void 0}onRemoteConfig(t){if(t.ok){var e=t.config;"autocaptureExceptions"in e&&(this.Ko=!!e.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[ia]:this.Ko}),this.Ne=this.Yo(),this.startIfEnabledOrStop())}}onConfigChange(){this.Ne=this.Yo()}captureException(t){var e,n,i,r=(e=t==null||(n=t.$exception_list)==null||(n=n[0])==null?void 0:n.type)!==null&&e!==void 0?e:"Exception";this.Jo.consumeRateLimit(r)?Ii.info("Skipping exception capture because of client rate limiting.",{exception:r}):(i=this._instance.exceptions)==null||i.sendExceptionEvent(t)}},exceptions:class{constructor(t){var e,n;this.Xo=[],this.tl=new lg([new mg,new Ig,new _g,new vg,new Sg,new Eg,new wg,new xg],(function(i){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;r>o;o++)s[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` +`),d=l;c.length>d;d++){var f=c[d];if(1024>=f.length){var h=Ac.test(f)?f.replace(Ac,"$1"):f;if(!h.match(/\S*Error: /)){for(var p of s){var g=p(h,i);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var v=Array.from(m);return v.reverse(),v.slice(0,50).map((E=>{return I({},E,{filename:E.filename||(S=v,S[S.length-1]||{}).filename,function:E.function||ni});var S}))})(u)}})("web:javascript",fg,gg)),this._instance=t,this.Xo=(e=(n=this._instance.persistence)==null?void 0:n.get_property(ra))!==null&&e!==void 0?e:[],this.el=Jr(this.il()),this.rl=new Cg(this.el)}onConfigChange(){this.el=Jr(this.il()),this.rl.setConfig(this.el)}onRemoteConfig(t){var e,n,i;if(t.ok){var r=t.config;if("errorTracking"in r){var s=(e=(n=r.errorTracking)==null?void 0:n.suppressionRules)!==null&&e!==void 0?e:[],o=(i=r.errorTracking)==null?void 0:i.captureExtensionExceptions;this.Xo=s,this._instance.persistence&&this._instance.persistence.register({[ra]:this.Xo,[sa]:o})}}}get nl(){var t,e=!!this._instance.get_property(sa),n=this._instance.config.error_tracking.captureExtensionExceptions;return(t=n??e)!==null&&t!==void 0&&t}buildProperties(t,e){return this.tl.buildFromUnknown(t,{syntheticException:e?.syntheticException,mechanism:{handled:e?.handled}})}addExceptionStep(t,e){if(this.el.enabled)try{if(!X(t)||t.trim().length===0)return void St.warn("Ignoring exception step because message must be a non-empty string");var n=(function(s){if(!s)return{sanitizedProperties:{},droppedKeys:[]};var o=[];return{sanitizedProperties:Object.keys(s).reduce(((a,l)=>kg.has(l)?(o.push(l),a):(a[l]=s[l],a)),{}),droppedKeys:o}})(this.sl(e)),i=n.sanitizedProperties,r=n.droppedKeys;r.length>0&&St.warn("Ignoring reserved exception step fields",{droppedKeys:r}),this.rl.add(I({[Kr]:t,[Yr]:new Date().toISOString()},i))}catch(s){St.error("Failed to add exception step. Ignoring breadcrumb.",s)}}sendExceptionEvent(t){try{var e=t.$exception_list;if(this.al(e)){if(this.ol(e))return this.ll("Exception dropped: matched a suppression rule"),void St.info("Skipping exception capture because a suppression rule matched");if(!this.nl&&this.ul(e))return this.ll("Exception dropped: thrown by a browser extension"),void St.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.hl(e))return this.ll("Exception dropped: thrown by the PostHog SDK"),void St.info("Skipping exception capture because it was thrown by the PostHog SDK")}var n=this.el.enabled&&H(t.$exception_steps)?this.dl(t):t,i=typeof(s=globalThis._posthogReleaseId)=="string"&&s.length>0?s:void 0;i&&(n.$release_id=i);try{var r=this._instance.capture("$exception",n,{_noTruncate:!0,_batchKey:"exceptionEvent",Wn:!0});return r&&this.rl.clear(),r}catch(o){return St.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void St.error("Failed to process exception event. Ignoring this exception.",o)}var s}dl(t){try{var e=this.rl.getAttachable();return e.length===0?t:I({},t,{$exception_steps:e})}catch(n){return St.error("Failed to read buffered exception steps. Capturing exception without steps.",n),t}}ll(t){this.el.enabled&&this.rl.add({[Kr]:t,[Yr]:new Date().toISOString()})}sl(t){return he(t)?I({},t):{}}il(){var t,e;return(t=(e=this._instance.config.error_tracking)==null?void 0:e.exception_steps)!==null&&t!==void 0?t:{}}ol(t){if(t.length===0)return!1;try{var e=t.reduce(((n,i)=>{var r=i.type,s=i.value;return X(r)&&r.length>0&&n.$exception_types.push(r),X(s)&&s.length>0&&n.$exception_values.push(s),n}),{$exception_types:[],$exception_values:[]});return this.Xo.some((n=>{var i=n.values.map((r=>{var s=Wf[r.operator],o=e[r.key];if(!s||!o)return!1;var a=U(r.value)?r.value:[r.value];return a.length>0&&s(a,o)}));return n.type==="OR"?i.some(Boolean):i.every(Boolean)}))}catch(n){return St.warn("Failed to evaluate suppression rules. Capturing the exception.",n),!1}}ul(t){return t.flatMap((e=>{var n,i;return(n=(i=e.stacktrace)==null?void 0:i.frames)!==null&&n!==void 0?n:[]})).some((e=>e.filename&&e.filename.startsWith("chrome-extension://")))}hl(t){if(t.length>0){var e,n,i,r,s=(e=(n=t[0].stacktrace)==null?void 0:n.frames)!==null&&e!==void 0?e:[],o=s[s.length-1];return(i=o==null||(r=o.filename)==null?void 0:r.includes("posthog.com/static"))!==null&&i!==void 0&&i}return!1}al(t){return!H(t)&&U(t)}}},Km=I({productTours:class{get Mr(){return this._instance.persistence}constructor(t){this.vl=null,this.cl=null,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(t.ok){var e=t.config;if("productTours"in e){var n,i;if(this.Mr&&this.Mr.register({[ol]:!!e.productTours}),!Bo(this._instance))return!this.vl&&H((n=this.Mr)==null?void 0:n.props[Mi])||xr.info("product tours disabled; stopping and clearing cached tours"),(i=this.vl)==null||i.stop(),this.vl=null,void this.clearCache();this.loadIfEnabled()}}}loadIfEnabled(){!this.vl&&Bo(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.generateProductTours?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",(i=>{i?xr.error("Could not load product tours script",i):t()}))}fl(){var t;!this.vl&&(t=B.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=B.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(t,e){if(e===void 0&&(e=!1),!U(this.cl)||e){var n=this.Mr;if(n){var i=n.props[Mi];if(U(i)&&!e)return this.cl=i,void t(i,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",timestampMode:"query",callback:r=>{if(Bo(this._instance)){var s=r.statusCode;if(s!==200||!r.json){var o="Product Tours API could not be loaded, status: "+s;return s===0?r.error||xr.warn(o):xr.error(o),void t([],{isLoaded:!1,error:o})}var a=U(r.json.product_tours)?r.json.product_tours:[];this.cl=a,n&&n.register({[Mi]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){H(this.vl)?t([],{isLoaded:!1,error:"Product tours not loaded"}):this.vl.getActiveProductTours(t)}showProductTour(t){var e;(e=this.vl)==null||e.showTourById(t)}previewTour(t){this.vl?this.vl.previewTour(t):this.ai((()=>{var e;this.fl(),(e=this.vl)==null||e.previewTour(t)}))}dismissProductTour(){var t;(t=this.vl)==null||t.dismissTour("user_clicked_skip")}nextStep(){var t;(t=this.vl)==null||t.nextStep()}previousStep(){var t;(t=this.vl)==null||t.previousStep()}clearCache(){var t;this.cl=null,(t=this.Mr)==null||t.unregister(Mi)}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)}}},As),Ym={siteApps:class{constructor(t){this.pl=0,this._instance=t,this.gl=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}ml(t,e){if(e){var n=this.globalsForEvent(e);this.gl.push(n),this.gl.length>1e3&&(this.gl=this.gl.slice(10))}}get siteAppLoaders(){var t;return(t=B._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,n,i,r,s,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var f=d[0];l[f]={id:u[f],type:f,properties:d[1]}}var h=t.$set_once,p=t.$set;return{event:I({},hd(t,Bm),{properties:I({},t.properties,p?{$set:I({},(e=(n=t.properties)==null?void 0:n.$set)!==null&&e!==void 0?e:{},p)}:{},h?{$set_once:I({},(i=(r=t.properties)==null?void 0:r.$set_once)!==null&&i!==void 0?i:{},h)}:{}),elements_chain:(s=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&s!==void 0?s:"",distinct_id:(a=t.properties)==null?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}bl(t){var e,n=(e=t.tagName)==null?void 0:e.toLowerCase();return n==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(Et.error("prepare_external_dependency_stylesheet returned null"),null):n==="script"&&this._instance.config.prepare_external_dependency_script?this._instance.config.prepare_external_dependency_script(t)||(Et.error("prepare_external_dependency_script returned null"),null):t}_l(){var t,e,n,i,r,s,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=P?.defaultView,u=l==null||(t=l.Node)==null?void 0:t.prototype;if(!l||!u)return()=>{};if(this.pl++,this.wl)return this.kl();var c=[],d=this,f=new WeakSet,h=(m,v,E)=>{if(m!=null&&m[v]){var S=m[v];m[v]=E(S),c.push((()=>{m[v]=S}))}},p=m=>{if(f.has(m))return m;var v=d.bl(m);return v&&f.add(v),v},g=m=>m.map((v=>typeof v=="string"?v:p(v))).filter((v=>!Ye(v)));return h(u,"appendChild",(m=>function(v){var E=p(v);return E?m.call(this,E):v})),h(u,"insertBefore",(m=>function(v,E){var S=p(v);return S?m.call(this,S,E):v})),h(u,"replaceChild",(m=>function(v,E){var S=p(v);return S?m.call(this,S,E):E})),[(e=l.Element)==null?void 0:e.prototype,(n=l.Document)==null?void 0:n.prototype,(i=l.DocumentFragment)==null?void 0:i.prototype].forEach((m=>{h(m,"append",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),h(m,"prepend",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))}))})),[(r=l.Element)==null?void 0:r.prototype,(s=l.CharacterData)==null?void 0:s.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((m=>{h(m,"before",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),h(m,"after",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),h(m,"replaceWith",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];var b=g(S);return S.length&&!b.length?void 0:v.apply(this,b)}))})),h((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(v,E){var S=p(E);return S?m.call(this,v,S):null})),this.wl=()=>{c.forEach((m=>m())),this.wl=void 0},this.kl()}kl(){var t=!1;return()=>{var e;t||(t=!0,this.pl--,this.pl===0&&((e=this.wl)==null||e.call(this)))}}xl(t,e){e===void 0&&(e=!0);var n=this._l();try{var i=t(n);return e&&n(),i}catch(r){throw n(),r}}setupSiteApp(t){var e=this.apps[t.id],n=()=>{var o;!e.errored&&this.gl.length&&(Et.info("Processing "+this.gl.length+" events for site app with id "+t.id),this.gl.forEach((a=>this.xl((()=>e.processEvent==null?void 0:e.processEvent(a))))),e.processedBuffer=!0),Object.values(this.apps).every((a=>a.processedBuffer||a.errored))&&((o=this.yl)==null||o.call(this))},i=!1,r=o=>{e.errored=!o,e.loaded=!0,Et.info("Site app with id "+t.id+" "+(o?"loaded":"errored")),i&&n()};try{var s=this.xl((o=>t.init({posthog:this._instance,callback(a){o(),r(a)}})),!1).processEvent;s&&(e.processEvent=s),i=!0}catch(o){Et.error(du+t.id,o),r(!1)}if(i&&e.loaded)try{n()}catch(o){Et.error("Error while processing buffered events PostHog app with config id "+t.id,o),e.errored=!0}}Sl(){var t=this.siteAppLoaders||[];for(var e of t)this.apps[e.id]={id:e.id,loaded:!1,errored:!1,processedBuffer:!1};for(var n of t)this.setupSiteApp(n)}Cl(t){var e=this;if(Object.keys(this.apps).length!==0){var n=this.globalsForEvent(t),i=function(s){try{e.xl((()=>s.processEvent==null?void 0:s.processEvent(n)))}catch(o){Et.error("Error while processing event "+t.event+" for site app "+s.id,o)}};for(var r of Object.values(this.apps))i(r)}}onRemoteConfig(t){var e,n,i,r=this;if((e=this.siteAppLoaders)!=null&&e.length)return this.isEnabled?(this.Sl(),void this._instance.on("eventCaptured",(l=>this.Cl(l)))):void Et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((n=this.yl)==null||n.call(this),t.ok){var s=t.config;if((i=s.siteApps)!=null&&i.length)if(this.isEnabled){var o=function(){var l,u=a.id,c=a.url;B["__$$ph_site_app_"+u]=r._instance,(l=B.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(r._instance,c,(d=>{if(d)return Et.error(du+u,d)}))};for(var a of s.siteApps)o()}else Et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},Jm={tracingHeaders:class{constructor(t){this.Ml=void 0,this.Tl=void 0,this.El=void 0,this.Uo=()=>{var e,n,i=this.Il();i?(C(this.Ml)&&(this.Ml=(e=B.__PosthogExtensions__)==null||(e=e.tracingHeadersPatchFns)==null?void 0:e._patchXHR(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager)),C(this.Tl)&&(this.Tl=(n=B.__PosthogExtensions__)==null||(n=n.tracingHeadersPatchFns)==null?void 0:n._patchFetch(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager))):this.Qo()},this._instance=t}initialize(){this.startIfEnabledOrStop()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",(i=>{if(i)return Nm.error("failed to load script",i);t()}))}Pl(){var t,e;return(t=(e=this._instance.config.tracing_headers)!==null&&e!==void 0?e:this._instance.config.addTracingHeaders)!==null&&t!==void 0?t:this._instance.config.__add_tracing_headers}Il(){var t=this.Pl();return U(t)?(U(this.El)?this.El.splice(0,this.El.length,...t):this.El=[...t],t.length>0?this.El:void 0):(U(this.El)&&this.El.splice(0),this.El=t||void 0,this.El)}Qo(){var t,e;(t=this.Ml)==null||t.call(this),(e=this.Tl)==null||e.call(this),this.Ml=void 0,this.Tl=void 0}startIfEnabledOrStop(){this.Il()?this.ai(this.Uo):this.Qo()}}},Zm=I({surveys:class{get Ne(){return this._instance.config}constructor(t){this.Rl=void 0,this._surveyManager=null,this.Al=!1,this.Fl=[],this.Ll=null,this.Ol=null,this._instance=t,this._surveyEventReceiver=null}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this.Ne.disable_surveys){if(!t.ok)return Q.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(H(e))return Q.warn("Flags not loaded yet. Not loading surveys.");var n=U(e);this.Rl=n?e.length>0:e,Q.info("flags response received, isSurveysEnabled: "+this.Rl),this.loadIfEnabled()}}reset(){try{var t;(t=this._surveyEventReceiver)==null||t.reset(),localStorage.removeItem("lastSeenSurveyDate");for(var e=[],n=0;nlocalStorage.removeItem(r)))}catch{}}loadIfEnabled(){if(!this._surveyManager)if(this.Al)Q.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)Q.info(fu);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())Q.info("Not loading surveys in cookieless mode without consent.");else{var t=B?.__PosthogExtensions__;if(t){if(!C(this.Rl)||this.Ne.advanced_enable_surveys){var e=this.Rl||this.Ne.advanced_enable_surveys;this.Al=!0;try{var n=t.generateSurveys;if(n)return void this.Dl(n,e);var i=t.loadExternalDependency;if(!i)return void this.$l(ll);i(this._instance,"surveys",(r=>{r||!t.generateSurveys?this.$l("Could not load surveys script",r):this.Dl(t.generateSurveys,e)}))}catch(r){throw this.$l("Error initializing surveys",r),r}finally{this.Al=!1}}}else Q.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new Um(this._instance),Q.info("Surveys loaded successfully"),this.Nl({isLoaded:!0})}$l(t,e){Q.error(t,e),this.Nl({isLoaded:!1,error:t})}onSurveysLoaded(t){return this.Fl.push(t),this._surveyManager&&this.Nl({isLoaded:!0}),()=>{this.Fl=this.Fl.filter((e=>e!==t))}}getSurveys(t,e){if(e===void 0&&(e=!1),this.Ne.disable_surveys)return Q.info(fu),t([]);var n,i=this._instance.get_property(ca);if(i&&!e)return t(i,{isLoaded:!0}),void(this.ql()&&this.getSurveys((()=>{}),!0));typeof Promise<"u"&&this.Ll?this.Ll.then((r=>t(r.surveys,r.context))):(typeof Promise<"u"&&(this.Ll=new Promise((r=>{n=r}))),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this.Ne.token),method:"GET",timestampMode:"query",timeout:this.Ne.surveys_request_timeout_ms,callback:r=>{var s;this.Ll=null;var o=r.statusCode;if(o!==200||!r.json){var a="Surveys API could not be loaded, status: "+o;o!==0?Q.error(a):r.error||Q.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(n==null||n({surveys:[],context:l}))}this.Ol=null;var u,c=r.json.surveys||[],d=c.filter((h=>(function(p){return!(!p.start_date||p.end_date)})(h)&&(qf(h)||(function(p){var g;return!((g=p.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(h))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(s=this._instance.persistence)==null||s.register({[ca]:c,[Xr]:Date.now()});var f={isLoaded:!0};t(c,f),n?.({surveys:c,context:f})}}))}ql(){return this.jl()&&!this.Ll&&!this.Bl()}jl(){var t=this._instance.get_property(Xr);return ke(t)&&Date.now()-t>3e5}Bl(){return ke(this.Ol)&&3e5>Date.now()-this.Ol}markSurveyAsSeen(t,e){var n,i={id:t,current_iteration:(n=e?.iteration)!==null&&n!==void 0?n:null};Gf(i);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}}Nl(t){for(var e of this.Fl)try{if(!t.isLoaded)return e([],t);this.getSurveys(e)}catch(n){Q.error("Error in survey callback",n)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!H(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);Q.warn("init was not called")}Hl(t){var e=null;return this.getSurveys((n=>{var i;e=(i=n.find((r=>r.id===t)))!==null&&i!==void 0?i:null})),e}Ul(t){if(H(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(H(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(H(this._surveyManager))return Q.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 H(this._surveyManager)?(Q.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Ir})):new Promise((n=>{this.getSurveys((i=>{var r,s=(r=i.find((a=>a.id===t)))!==null&&r!==void 0?r:null;if(s){var o=this.zl(s);n({visible:o.eligible,disabledReason:o.reason})}else n({visible:!1,disabledReason:"Survey not found"})}),e)}))}renderSurvey(t,e,n){var i;if(H(this._surveyManager))Q.warn("init was not called");else{var r=typeof t=="string"?this.Hl(t):t;if(r!=null&&r.id)if(Sm.includes(r.type)){var s=P?.querySelector(e);if(s)return(i=r.appearance)!=null&&i.surveyPopupDelaySeconds?(Q.info("Rendering survey "+r.id+" with delay of "+r.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;Q.info("Rendering survey "+r.id+" with delay of "+((o=r.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(a=this._surveyManager)==null||a.renderSurvey(r,s,n),Q.info("Survey "+r.id+" rendered")}),1e3*r.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(r,s,n);Q.warn("Survey element not found")}else Q.warn("Surveys of type "+r.type+" cannot be rendered in the app");else Q.warn("Survey not found")}}displaySurvey(t,e){var n;if(H(this._surveyManager))Q.warn("init was not called");else{var i=this.Hl(t);if(i){var r=i;if((n=i.appearance)!=null&&n.surveyPopupDelaySeconds&&e.ignoreDelay&&(r=I({},i,{appearance:I({},i.appearance,{surveyPopupDelaySeconds:0})})),e.displayType!==ya.Popover&&e.initialResponses&&Q.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),e.ignoreConditions===!1){var s=this.Ul(i);if(!s.eligible)return void Q.warn("Survey is not eligible to be displayed: ",s.reason)}e.displayType!==ya.Inline?this._surveyManager.handlePopoverSurvey(r,e):this.renderSurvey(r,e.selector,e.properties)}else Q.warn("Survey not found")}}cancelPendingSurvey(t){H(this._surveyManager)?Q.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},As),Xm={toolbar:class{constructor(t){this.instance=t}Wl(t){B.ph_toolbar_state=t}Vl(){var t;return(t=B.ph_toolbar_state)!==null&&t!==void 0?t:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(t,e,n){if(t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),ma(this.instance.config)||!w||!P)return!1;t=t??w.location,n=n??w.history;try{if(!e){try{w.localStorage.setItem("test","test"),w.localStorage.removeItem("test")}catch{return!1}e=w?.localStorage}var i,r=Hm||os(t.hash,"__posthog")||os(t.hash,"state"),s=r?Fc((()=>JSON.parse(atob(decodeURIComponent(r)))))||Fc((()=>JSON.parse(decodeURIComponent(r)))):null;return s&&s.action==="ph_authorize"?((i=s).source="url",i&&Object.keys(i).length>0&&(s.desiredHash?t.hash=s.desiredHash:n?n.replaceState(n.state,"",t.pathname+t.search):t.hash="")):((i=JSON.parse(e.getItem(hu)||"{}")).source="localstorage",delete i.userIntent),!(!i.token||this.instance.config.token!==i.token||(this.loadToolbar(i),0))}catch{return!1}}Zl(t){var e=B.ph_load_toolbar||B.ph_load_editor;!H(e)&&je(e)?e(t,this.instance):pu.warn("No toolbar load function found")}loadToolbar(t){var e=!(P==null||!P.getElementById(lf));if(!w||e)return!1;var n=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,i=I({token:this.instance.config.token},t,{apiURL:this.instance.requestRouter.endpointFor("ui")},n?{instrument:!1}:{});if(w.localStorage.setItem(hu,JSON.stringify(I({},i,{source:void 0}))),this.Vl()===2)this.Zl(i);else if(this.Vl()===0){var r;this.Wl(1),(r=B.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"toolbar",(s=>{if(s)return pu.error("[Toolbar] Failed to load",s),void this.Wl(0);this.Wl(2),this.Zl(i)})),ve(w,"turbolinks:load",(()=>{this.Wl(0),this.loadToolbar(i)}))}return!0}Gl(t){return this.loadToolbar(t)}maybeLoadEditor(t,e,n){return t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),this.maybeLoadToolbar(t,e,n)}}},Qm=I({experiments:Me},As),ev={conversations:class{constructor(t){this.Ql=void 0,this._conversationsManager=null,this.Kl=!1,this.Jl=null,this.Yl=!1,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this._instance.config.disable_conversations&&(this.Xl=t.ok,t.ok)){var e=t.config.conversations;H(e)||(mt(e)?this.Ql=e:(this.Ql=e.enabled,this.Jl=e),this.loadIfEnabled())}}reset(){var t;(t=this._conversationsManager)==null||t.reset(),this._conversationsManager=null,this.Ql=void 0,this.Jl=null,this.Xl=void 0,this.Yl=!1}loadIfEnabled(){if(!(this._conversationsManager||this.Kl||this._instance.config.disable_conversations||ma(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=B?.__PosthogExtensions__;if(t&&!C(this.Ql)&&this.Ql)if(this.Jl&&this.Jl.token){this.Kl=!0;try{var e=t.initConversations;if(e)return this.tu(e),void(this.Kl=!1);var n=t.loadExternalDependency;if(!n)return void this.eu(ll);n(this._instance,"conversations",(i=>{i||!t.initConversations?this.eu("Could not load conversations script",i):this.tu(t.initConversations),this.Kl=!1}))}catch(i){this.eu("Error initializing conversations",i),this.Kl=!1}}else ot.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,ot.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else ot.error("Cannot complete initialization: remote config is null")}eu(t,e){ot.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():ot.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!Ye(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":ma(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.Xl===!1?"remote_config_failed":C(this.Ql)?this.Xl?"disabled_in_project":"remote_config_pending":this.Ql?H(this.Jl)||!this.Jl.token?"missing_token":B!=null&&B.__PosthogExtensions__?this.Kl?"initializing":this.Yl?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.isVisible())!==null&&t!==void 0&&t}sendMessage(t,e,n){var i=this;return se((function*(){return i._conversationsManager?i._conversationsManager.sendMessage(t,e,n):(ot.warn(En),null)}))()}getMessages(t,e){var n=this;return se((function*(){return n._conversationsManager?n._conversationsManager.getMessages(t,e):(ot.warn(En),null)}))()}markAsRead(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(ot.warn(En),null)}))()}getTickets(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(ot.warn(En),null)}))()}requestRestoreLink(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(ot.warn(En),null)}))()}restoreFromToken(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(ot.warn(En),null)}))()}restoreFromUrlToken(){var t=this;return se((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(ot.warn(En),null)}))()}getCurrentTicketId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getCurrentTicketId())!==null&&t!==void 0?t:null}getWidgetSessionId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getWidgetSessionId())!==null&&t!==void 0?t:null}Xn(){var t;(t=this._conversationsManager)==null||t.setIdentity()}ts(){var t;(t=this._conversationsManager)==null||t.clearIdentity()}}},tv={logs:class{constructor(t){var e,n=this;this.iu=!1,this.ru=!1,this.rt=pe("[logs]"),this.nu=I({},this.rt,{error(){for(var i=arguments.length,r=new Array(i),s=0;i>s;s++)r[s]=arguments[s];r.some(Eu)||n.rt.error(...r)}}),this.tr=[],this.su=[],this.Sa=0,this.au=()=>{var i,r;this.Sa=0,(i=this.ou)==null||i.onReconnect(),(r=this.lu)==null||r.onReconnect()},this._instance=t,this._instance&&(e=this._instance.config.logs)!=null&&e.captureConsoleLogs&&(this.iu=!0),w&&ve(w,"online",this.au)}uu(t,e,n,i){var r,s=(function(o,a){var l,u,c,d,f,h,p,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,v=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,E=C(v)?Math.max(m,2048):Math.max(m,v),S=o?.resourceAttributes;return{serviceName:(d=(f=S?.["service.name"])!==null&&f!==void 0?f:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(h=S?.["service.version"])!==null&&h!==void 0?h:o?.serviceVersion,environment:(p=S?.["deployment.environment"])!==null&&p!==void 0?p:o?.environment,resourceAttributes:S,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:E,maxBatchRecordsPerPost:100,rateCapWindowMs:g,maxLogsPerInterval:v,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}})((r=this._instance)==null||(r=r.config)==null?void 0:r.logs,n);return[new sg(this.hu(t,e),s,this.nu,(()=>this.du()),(o=>o()),void 0,i),s]}vu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.ou||this.cu!==e){var n;(n=this.ou)==null||n.reset(),this.cu=e;var i=this.uu((()=>this.tr),(r=>{this.tr=r}));this.ou=i[0],this.fu=i[1]}return this.ou}pu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.lu||this.gu!==e){var n;(n=this.lu)==null||n.reset(),this.gu=e;var i=this.uu((()=>this.su),(r=>{this.su=r}),{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},bu);this.lu=i[0],this.mu=i[1]}return this.lu}initialize(){this.loadIfEnabled()}onRemoteConfig(t){var e;if(t.ok){var n=(e=t.config.logs)==null?void 0:e.captureConsoleLogs;!H(n)&&n&&(this.iu=!0,this.loadIfEnabled())}}reset(){var t,e;this.tr=[],(t=this.ou)==null||t.reset(),this.su=[],(e=this.lu)==null||e.reset(),this.Sa=0}captureLog(t){this.vu().captureLog(t)}he(t){this.pu().captureLog(t)}get logger(){return this.yu||(this.yu={trace:(t,e)=>this.captureLog({body:t,level:"trace",attributes:e}),debug:(t,e)=>this.captureLog({body:t,level:"debug",attributes:e}),info:(t,e)=>this.captureLog({body:t,level:"info",attributes:e}),warn:(t,e)=>this.captureLog({body:t,level:"warn",attributes:e}),error:(t,e)=>this.captureLog({body:t,level:"error",attributes:e}),fatal:(t,e)=>this.captureLog({body:t,level:"fatal",attributes:e})}),this.yu}flushLogs(t){t?this.bu(t):(this.ou&&this.ou.flush().catch((e=>this._u(e))),this.lu&&this.lu.flush().catch((e=>this._u(e))))}_u(t){Eu(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=B?.__PosthogExtensions__;if(t){var e=t.loadExternalDependency;e?e(this._instance,"logs",(n=>{var i;n||(i=t.logs)==null||!i.initializeLogs?this.rt.error("Could not load logs script",n):(t.logs.initializeLogs(this._instance),this.ru=!0)})):this.rt.error(ll)}else this.rt.error("PostHog Extensions not found.")}}hu(t,e){var n=this._instance;return{get isDisabled(){return!1},get optedOut(){return!n.is_capturing()},getPersistedProperty:i=>i===Ut.LogsQueue?t():void 0,setPersistedProperty(i,r){var s;i===Ut.LogsQueue&&e((s=r)!==null&&s!==void 0?s:[])},Ot:i=>this.Ot(i),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Ot(t){return new Promise((e=>{if(wf(this.Sa,3))e({kind:"fatal",error:jo(void 0,"logs endpoint is unreachable, dropping batch")});else{var n=!1,i=s=>{n||(n=!0,clearTimeout(r),e(s))},r=setTimeout((()=>{this.rt.warn("Logs request timed out before receiving a response"),i({kind:"retry-later",error:jo(void 0,"logs request timed out")})}),9e4);this._instance._send_request({method:"POST",url:this.wu(),data:t,compression:"best-available",batchKey:"logs",fireCallbackOnDrop:!0,callback:s=>{var o=s.statusCode;if(this.ku(o),o>=200&&300>o)i({kind:"ok"});else if(o===413)i({kind:"too-large"});else if(o!==0&&o!==429&&500>o)i({kind:"fatal",error:new Error("logs request failed with status "+o)});else{var a;o===0?(s.error||this.rt.warn("Logs request failed before receiving an HTTP response"),i({kind:"retry-later",error:jo(s.error,"logs request failed before receiving an HTTP response")})):i({kind:"retry-later",error:(a=s.error)!==null&&a!==void 0?a:new Error("logs request failed with status "+o)})}}})}}))}ku(t){(t!==0||this._instance.__loaded)&&(this.Sa=bf(t,this.Sa,3,(()=>this.rt.warn("Log requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped sending logs; will try again when connectivity changes."))))}bu(t){this.tr.length>0&&this.xu(t,this.tr,this.fu,ne.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,bu,(e=>{this.su=e}))}xu(t,e,n,i,r){if(e.length!==0){var s=e.map((a=>a.record));r([]);var o=zd(s,Wd(n,ne.LIB_NAME,ne.LIB_VERSION),i,ne.LIB_VERSION);this._instance._send_request({method:"POST",url:this.wu(),data:o,compression:"best-available",batchKey:"logs",transport:t})}}wu(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}du(){var t,e={};if(e.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var n=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.windowId,r=n.sessionStartTimestamp,s=n.lastActivityTimestamp;e.sessionId=n.sessionId,e.windowId=i,H(r)||(e.sessionStartTimestamp=r),H(s)||(e.lastActivityTimestamp=s)}if(B!=null&&(t=B.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?fn(B.location.href):B.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},nv={metrics:class{constructor(t){this.rt=pe("[metrics]"),this._instance=t}initialize(){}vu(){var t,e,n=(t=this._instance)==null||(t=t.config)==null?void 0:t.metrics;return this.ou&&this.cu===n||((e=this.ou)==null||e.reset(),this.cu=n,this.ou=new og(this.hu(),(function(i){var r,s,o,a,l,u=i?.resourceAttributes;return{serviceName:(r=u?.["service.name"])!==null&&r!==void 0?r:i?.serviceName,serviceVersion:(s=u?.["service.version"])!==null&&s!==void 0?s:i?.serviceVersion,environment:(o=u?.["deployment.environment"])!==null&&o!==void 0?o:i?.environment,resourceAttributes:u,beforeSend:i?.beforeSend,flushIntervalMs:(a=i?.flushIntervalMs)!==null&&a!==void 0?a:1e4,maxSeriesPerFlush:(l=i?.maxSeriesPerFlush)!==null&&l!==void 0?l:1e3}})(n),this.rt)),this.ou}count(t,e,n){e===void 0&&(e=1),this.vu().count(t,e,n)}gauge(t,e,n){this.vu().gauge(t,e,n)}histogram(t,e,n){this.vu().histogram(t,e,n)}flush(t){if(!this.ou)return Promise.resolve();if(t){var e=this.ou.drainWindow();return e&&this.Jt(e,t),Promise.resolve()}return this.ou.flush().catch((n=>this.rt.error("PostHog metrics flush failed:",n)))}reset(){var t;(t=this.ou)==null||t.reset()}hu(){var t=this._instance,e=this;return{get isDisabled(){return!1},get optedOut(){return!t.is_capturing()},Jt:n=>e.Jt(n),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Jt(t,e){return new Promise((n=>{var i=!1,r=o=>{i||(i=!0,clearTimeout(s),n(o))},s=setTimeout((()=>r({kind:"retry-later",error:new Error("metrics request timed out")})),9e4);this._instance._send_request(I({method:"POST",url:this.Su(),data:t,compression:"best-available",batchKey:"metrics"},e&&{transport:e},{fireCallbackOnDrop:!0,callback(o){var a=o.statusCode;if(a>=200&&300>a)r({kind:"ok"});else if(a===413)r({kind:"too-large"});else if(a!==0&&a!==429&&500>a)r({kind:"fatal",error:new Error("metrics request failed with status "+a)});else{var l;r({kind:"retry-later",error:(l=o.error)!==null&&l!==void 0?l:new Error("metrics request failed with status "+a)})}}}))}))}Su(){return this._instance.requestRouter.endpointFor("api","/i/v1/metrics")+"?token="+encodeURIComponent(this._instance.config.token)}}},iv=I({},As,qm,Vm,Gm,Km,Ym,Zm,Jm,Xm,Qm,ev,tv,nv);Ze.__defaultExtensionClasses=I({},iv);(function(){ne.SDK_DIST_CHANNEL="npm";var t=Wi[Gn]=new Ze;return(function(){function e(){e.done||(e.done=!0,Yf=!1,ie(Wi,(function(n){n._dom_loaded()})))}P!=null&&P.addEventListener?P.readyState==="complete"?e():ve(P,"DOMContentLoaded",e,{capture:!1}):w&&A.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const rv=["a[href]","button:not([disabled])","input:not([disabled]):not([type='hidden'])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(",");let pt=null,Ca=null,Zf="";const Aa=new Map;function Xf(t){return[...t.querySelectorAll(rv)].filter(e=>!e.hidden&&e.getAttribute("aria-hidden")!=="true"&&e.getClientRects().length>0)}function sv(t){for(const e of document.body.children)e===t||e.tagName==="SCRIPT"||(Aa.set(e,{inert:e.inert,ariaHidden:e.getAttribute("aria-hidden")}),e.inert=!0,e.setAttribute("aria-hidden","true"))}function ov(){for(const[t,e]of Aa)t.inert=e.inert,e.ariaHidden===null?t.removeAttribute("aria-hidden"):t.setAttribute("aria-hidden",e.ariaHidden);Aa.clear()}function Qf(t){return t?.dataset.modalDismissible!=="false"&&t?.getAttribute("aria-busy")!=="true"}function We(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n)return!1;pt&&pt!==n&&ze(pt,{restoreFocus:!1,force:!0}),Ca=e.trigger||document.activeElement,pt=n,Zf=document.body.style.overflow,sv(n),document.body.style.overflow="hidden",n.classList.add("open"),n.setAttribute("aria-hidden","false");const i=n.querySelector(".modal-content");i&&(i.style.transform="scale(1) translateY(0)");const r=()=>{if(pt!==n)return;((e.initialFocus?n.querySelector(e.initialFocus):n.querySelector("[data-modal-initial-focus]"))||Xf(n)[0]||n.querySelector(".modal-content")||n).focus({preventScroll:!0})};return requestAnimationFrame(r),setTimeout(r,260),!0}function ze(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n||!e.force&&!Qf(n))return!1;n.classList.remove("open"),n.setAttribute("aria-hidden","true"),ov(),document.body.style.overflow=Zf,pt=null;const i=Ca;return Ca=null,e.restoreFocus!==!1&&i?.isConnected&&i.focus({preventScroll:!0}),!0}function Su(t,e,n="Operation in progress"){const i=typeof t=="string"?document.getElementById(t):t;i&&(i.dataset.modalDismissible=e?"false":"true",i.setAttribute("aria-busy",String(!!e)),e?i.setAttribute("aria-label",n):i.removeAttribute("aria-label"))}function av(t){if(!Qf(t))return;const e=t.dataset.modalCloseHandler;e&&typeof window[e]=="function"?window[e]():ze(t)}document.addEventListener("keydown",t=>{if(!pt)return;if(t.key==="Escape"){t.preventDefault(),t.stopImmediatePropagation(),av(pt);return}if(t.key!=="Tab"){t.stopPropagation();return}const e=Xf(pt);if(!e.length){t.preventDefault(),(pt.querySelector(".modal-content")||pt).focus();return}const n=e[0],i=e[e.length-1];t.shiftKey&&document.activeElement===n?(t.preventDefault(),i.focus()):!t.shiftKey&&document.activeElement===i&&(t.preventDefault(),n.focus())},!0);function lv(){document.querySelectorAll(".modal-overlay").forEach(t=>{t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-hidden",t.classList.contains("open")?"false":"true");const e=t.querySelector(".modal-content");e&&!e.hasAttribute("tabindex")&&(e.tabIndex=-1);const n=t.querySelector("h1, h2, h3");n&&(n.id||(n.id=`${t.id}-title`),t.setAttribute("aria-labelledby",n.id)),t.querySelectorAll(".modal-close").forEach(i=>{i.getAttribute("aria-label")||i.setAttribute("aria-label","Close dialog")})})}const ml=Object.freeze({free:"Free",professional:"Pro",power:"Power"}),cv=Object.freeze({free:2,professional:50,power:2e3}),uv="(contact us)",dv=Object.freeze({free:Object.freeze(["2 generations/month","Gemini model only","Code Review"]),professional:Object.freeze(["50 generations/month","All models","Code Regeneration","Code Review"]),power:Object.freeze(["2000 generations/month","All models","Code Regeneration","Bring your own key (BYOK)","Code Review","All models + early access",`API & MCP access ${uv}`])}),eh="CodeFile",th="GeneratedCode",fv={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function ln(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Pa(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function hv(t={},e=0){const n=Pa(t.artifactType||t.type||eh),i=Pa(t.artifactName||t.name||t.fileName||`${th}-${e+1}`);return`${n||"artifact"}-${i||e+1}`}function nh(t={},e=0){const n=ln(t),i=n.artifactType||n.type||eh,r=n.artifactName||n.name||th;let s=n.fileName||r;return s.endsWith(".dart")||(s+=".dart"),{id:Pa(n.id)||hv({...n,artifactType:i,artifactName:r,fileName:s},e),artifactType:i,artifactName:r,fileName:s,deployPath:n.deployPath||"",description:n.description||"",code:n.code||n.content||"",dependencies:ih(n.dependencies),imports:Array.isArray(n.imports)?n.imports:[],publicApi:Array.isArray(n.publicApi)?n.publicApi:[],relationships:rh(n.relationships),deployStatus:n.deployStatus||"pending",review:n.review||null,metadata:ln(n.metadata),codeType:n.codeType||fv[i]||"O"}}function ih(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const n=ln(e),i=n.name||n.package;return i?{name:i,version:n.version||null,versionRequired:!!(n.versionRequired||n.required),inferred:!!n.inferred,...n.reason?{reason:n.reason}:{}}:null}).filter(Boolean):Object.entries(ln(t)).map(([e,n])=>({name:e,version:n||null,inferred:!1})):[]}function rh(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const n=ln(e);return!n.from&&!n.to?null:{from:n.from||null,to:n.to||null,type:n.type||"uses",description:n.description||""}}).filter(Boolean):[]}function Fa(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;try{return JSON.parse(e)}catch{const n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(!n)return null;try{return JSON.parse(n[1].trim())}catch{return null}}}function Qi(t,e={}){const n=[],i=typeof t=="string"?Fa(t):t,s=ln(i||{});!i&&typeof t=="string"&&n.push("Structured bundle parse failed; using legacy single-artifact fallback.");const o=Array.isArray(s.artifacts)?s.artifacts:[{artifactType:s.artifactType||e.artifactType,artifactName:s.artifactName||e.artifactName,fileName:s.fileName||e.fileName,description:s.description,code:s.code||e.code||(typeof t=="string"?t:""),dependencies:s.dependencies||e.dependencies,relationships:s.relationships||e.relationships}];o.forEach((d,f)=>{!d?.artifactType&&!d?.type&&n.push(`Artifact ${f+1} has no artifactType; it will deploy as a standalone code file under lib/custom_code/ root.`)});const a=o.map((d,f)=>nh(d,f)),l=new Map(o.map((d,f)=>[ln(d).id,a[f]?.id]).filter(([d,f])=>d&&f)),u=d=>l.get(d)||d,c=rh(s.relationships||e.relationships).map(d=>({...d,from:d.from?u(d.from):d.from,to:d.to?u(d.to):d.to}));return{schemaVersion:s.schemaVersion||e.schemaVersion||null,id:s.id||e.id||"bundle-current",title:s.title||s.name||e.title||"Generated artifact bundle",description:s.description||e.description||"",artifacts:a,dependencies:ih(s.dependencies||e.dependencies),relationships:c,deployOrder:Array.isArray(s.deployOrder)?s.deployOrder.map(u):a.map(d=>d.id),warnings:[...n,...Array.isArray(s.warnings)?s.warnings:[]],metadata:ln(s.metadata)}}function oi(t){return Qi(t).artifacts[0]||nh()}function Zt(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function ai(t){return JSON.stringify(t,null,2)}function pv(t){return ai({task:"architect",userRequest:String(t??"")})}function gv(t){const e=Zt(t);return e&&typeof e=="object"&&typeof e.task=="string"?ai(e):ai({task:"generate_bundle",bundleSpec:e})}function mv(t){return ai({task:"review_bundle",generatedBundle:Zt(t),outputRequirements:{bundleReview:["status","score","summary","manualActions","findings"],scoreRange:[0,100],eachArtifact:["id","review.status","review.findings"],manualActions:{definition:"Setup the developer must perform by hand in the FlutterFlow editor that FlutterFlow will NOT do for them.",exclude:["creating the Custom Action, Widget or Code File itself - deploying the code creates it","declaring parameters or return values FlutterFlow derives from the function signature","anything that resolves as a side effect of using the action or widget in the editor","generic advice such as testing, reviewing or rebuilding the app"],preferEmpty:"Return an empty array when nothing qualifies - an empty list is the expected result for most bundles."}}})}function vl(t,e=null){const n={stage:t};return e!=null&&(n.bundle=Zt(e)),n}function vv({bundleSpec:t,artifactBundle:e,bundleReview:n,artifactId:i,userFeedback:r}){return ai({task:"regenerate_artifact",artifactId:i,bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(r)})}function sh({bundleSpec:t,artifactBundle:e,bundleReview:n,userFeedback:i}){return ai({task:"regenerate_bundle",bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(i??"")})}const xu={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"},_v=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function tt(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function yv(t){return tt(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||tt(t.filterSummary)||tt(t.filterResults):!1}function oh(t,e=0){if(!tt(t)||e>3)return null;if(yv(t))return t;for(const n of _v){const i=t[n];if(tt(i)){const r=oh(i,e+1);if(r)return r}}return null}function ds(t){return Array.isArray(t)?t.some(ds):tt(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(ds):!1}function Ra(t){return Array.isArray(t)?t.some(Ra):tt(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(Ra):!1}function ah(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function wv(t,e){if(tt(t))for(const[n,i]of Object.entries(t)){if(!tt(i))continue;const r=tt(i.categories)?i.categories:{},s=Object.entries(r).filter(([,o])=>tt(o)&&o.matched===!0).map(([o])=>o);s.length>0?s.forEach(o=>e.add(o)):i.matched===!0&&e.add(ah(n))}}function bv(t,e){if(!t)return;const n=Array.isArray(t)?t.flatMap(i=>tt(i)?Object.entries(i):[]):Object.entries(t);for(const[i,r]of n){if(!ds(r))continue;const s=ah(i),o=r?.raiFilterResult?.raiFilterTypeResults||(s==="rai"?r?.raiFilterTypeResults:null),a=tt(o)?Object.entries(o).filter(([,l])=>ds(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(s)}}function Ev(t){return xu[t]?xu[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function Iu(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 Sv(t){const e=oh(t);if(!e)return null;const n=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);wv(e.filterSummary,n),bv(e.filterResults,n);const i=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||n.size>0,r=e.invocationResult||null,s=Ra(e.filterSummary||e.filterResults);return!i&&!s&&!["PARTIAL","FAILURE"].includes(r)?null:{kind:i?"blocked":"unavailable",invocationResult:r,matchedFilters:[...n]}}function xv(t,e){const n=Sv(t);if(!n)return null;const i=[...new Set(n.matchedFilters.map(Ev))],r=n.kind==="blocked",s=new Error(r?`Safety screening blocked this pipeline step for ${Iu(i)}.`:"Safety screening could not be completed. Please try again.");return s.name="ModelArmorError",s.code=r?"MODEL_ARMOR_BLOCKED":"MODEL_ARMOR_UNAVAILABLE",s.isModelArmor=!0,s.pipelineStep=e,s.userTitle=r?"Request blocked for safety":"Safety check unavailable",s.userMessage=r?`The safety check detected ${Iu(i)}. Edit your request to remove or rephrase the flagged content, then run the pipeline again.`:"The safety service did not finish all of its checks. Please wait a moment and run the pipeline again.",s.retryExplanation=r?"Trying another model would not change this safety decision.":"A fallback model was not attempted because safety screening must complete first.",s.matchedFilters=n.matchedFilters,s}function Iv(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function ku(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,n=[];for(const i of Iv(t).split(` +`)){if(!/^[A-Za-z_$]/.test(i)||e.test(i))continue;const r=i.match(/^[\w$<>,?\s[\]]+?\s([a-zA-Z_$][\w$]*)\s*\(/);r&&n.push(r[1])}return n}function _l(t,e){const n=t.replace(/\.dart$/,"");if(e==="W")return n.replace(/(^|_)(\w)/g,(i,r,s)=>s.toUpperCase());if(e==="A"){const i=n.replace(/(^|_)(\w)/g,(r,s,o)=>o.toUpperCase());return i.charAt(0).toLowerCase()+i.slice(1)}return e==="F"?"CustomFunctions":e==="C"?t.endsWith(".dart")?t:`${t}.dart`:n}async function Cu(t){const e=new TextEncoder().encode(String(t||"")),n=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n),i=>i.toString(16).padStart(2,"0")).join("")}async function kv(t,e=new Map){const n={},i=new Set;for(const[o,a]of t.entries()){if(a.type==="D"||a.type==="O")continue;const l=_l(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await Cu(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await Cu(c)),n[o]=u,a.type==="F"){const d=ku(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(h=>i.add(h))}}const r=new Set(ku(e.get("lib/flutter_flow/custom_functions.dart")||"")),s={functions_to_rename:[],functions_to_delete:[],functions_to_add:Array.from(i).filter(o=>!r.has(o))};return{fileMapContents:JSON.stringify(n),functionsMapContents:JSON.stringify(s)}}const Cv=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),Au={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},Av=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),Pv=["Struct","Record"],Fv=[{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=>Uo(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=>Uo(t).some(e=>{const n=/^\s*final\s+(?:double|int|String|bool|Color|num)\s+(\w+)\s*;/gm;let i;for(;(i=n.exec(e))!==null;){const r=i[1];if(!(new RegExp(`this\\.${r}\\s*=(?!=)`).test(e)||new RegExp(`[:,]\\s*${r}\\s*=(?!=)`).test(e)))return!0}return!1}),pos:`class W extends StatefulWidget { const W({required this.value}); final double value; }`,neg:`class _P { @@ -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=>jo(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=>Uo(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,52 +25,52 @@ class _S extends State { @override Widget build(BuildContext c) => const Size @override _S createState() => _S(); } class _S extends State { @override Widget build(BuildContext c) => Padding(padding: const EdgeInsets.all(8), child: const SizedBox()); }`}];function xt(t,e,n){return{artifactId:t.id,artifactName:t.artifactName,artifactType:t.artifactType,severity:e,message:n}}function er(t){let e="",n=0;for(;n"&&(n--,n===0))return{inner:t.slice(e+1,i),end:i+1};return null}function Tv(t,e){const n=new RegExp(`class\\s+${e}\\b[^{]*\\{`).exec(t);if(!n)return null;let i=0;for(let r=n.index+n[0].length-1;r$v(t).usable);function Lv(t=""){const e=er(t);return Mv.filter(n=>n.detect(e)).map(({id:n,severity:i,message:r})=>({id:n,severity:i,message:r}))}function Nv(t){const e=[],n=t.matchAll(/\bFuture\b/g);for(const i of n){let r=i.index+6,s=null;const o=r;for(;ro;if(t[r]==="<"){const u=Rv(t,r);if(!u||(s=u.inner.replace(/\s+/g," ").trim(),r=u.end,!/\s/.test(t[r]||"")))continue;for(;rAu(o.functionName)===i);if(r)return r;const s=o=>!o.functionName.startsWith("_");return n.find(s)||n[0]}function As(t=""){return Array.from(er(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function Ov(t="",e=""){return _l(t,e)?.returnType||null}function Pu(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 Bv(t,e){const n=As(e);if(n.length===0)return null;const r=String(t||"").split("/").pop().replace(/\.dart$/,"");if(n.some(l=>Pu(l)===r)||n.length>1)return null;const[o]=n,a=`${Pu(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 yl(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function Dv(t,e,n=""){const i=_l(e,n)?.functionName;if(!i)return null;const r=String(t||"").split("/").pop(),s=vl(r,"A");if(s===i)return null;const o=`${yl(i)}.dart`;return`File name "${r}" does not match Action "${i}". FlutterFlow derives the action from the file name, so it looks for "${s}" and reports Action "${s}" declaration not found. Rename the file to "${o}" - FlutterFlow puts an underscore before every capital - or rename the function to "${s}".`}function jv(t="",e=""){return _l(t,e)!==null}function Uv(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(i=>Av.has(i)?!1:!Pv.some(s=>i.endsWith(s))||e.has(i))}function Hv(t,{functionName:e="",declaredTypes:n=new Set}={}){const i=Ov(t,e),r=Uv(i,n);if(r.length===0)return null;const[s]=r;let o;return n.has(s)?o=`uses Code File type "${s}", which FlutterFlow cannot process as an Action Return Value`:i===s?o="is not a FlutterFlow Action Return Value":o=`uses type "${s}", which is not a FlutterFlow Action Return Value`,`CustomAction return type "${i}" ${o}. Return JSON (Future) or an existing FlutterFlow Data Type (*Struct) instead.`}function Wv(t,e={}){const n=[],i=t.fileName||"",r=t.code||"";if(Cv.has(t.artifactType)||n.push(xt(t,"error",`Unsupported artifact type "${t.artifactType}".`)),i.endsWith(".dart")||n.push(xt(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!r.trim())return n.push(xt(t,"warning","Generated artifact has no Dart code yet.")),n;if(t.artifactType==="CustomWidget"){/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)||n.push(xt(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const s of Lv(r))n.push(xt(t,s.severity,s.message))}if(t.artifactType==="CustomAction"&&!jv(r,t.artifactName)&&n.push(xt(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const s=e.declaredTypes||new Set(As(r)),o=Hv(r,{functionName:t.artifactName,declaredTypes:s});o&&n.push(xt(t,"error",o));const a=Dv(i,r,t.artifactName);a&&n.push(xt(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)&&n.push(xt(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const s=Bv(i,r);s&&n.push(xt(t,"info",s))}return n}function zv(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],n=new Set(e.flatMap(s=>As(s.code||""))),i=e.flatMap(s=>Wv(s,{declaredTypes:n})),r=e.map(s=>({artifactId:s.id,fileName:s.fileName,pathHint:Cu[s.artifactType]||Cu.CodeFile}));return{valid:i.every(s=>s.severity!=="error"),findings:i,deployHints:r}}const Fu="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function Ru(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function qv(t=""){const e=t.indexOf(Fu);return e===-1?t:t.slice(e+Fu.length).replace(/^\s*\n/,"")}const Vv=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function Gv(t="",e=""){const n=qv(t),i=new Set((e.match(/^\s*import .*$/gm)||[]).map(Ru).filter(Boolean)),r=n.split(` -`).filter(s=>{const o=Ru(s);return o===null||!i.has(o)?!0:!Vv.test(s)}).join(` -`).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+r}const Kv=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations"]);function ah(t){let e="",n=0;for(;n{const i=n.name||n.package;if(!i||i==="flutter")return e;const r=n.versionRequired||n.required;return e[i]=r&&n.version||"",e},{})}function Qv(t){const e=new Map,n=new Map,i=[];for(const r of t)e.has(r.fileName)?i.push(`Duplicate deploy file name "${r.fileName}" for artifacts "${e.get(r.fileName)}" and "${r.artifactId}".`):e.set(r.fileName,r.artifactId),n.has(r.path)?i.push(`Duplicate deploy path "${r.path}" for artifacts "${n.get(r.path)}" and "${r.artifactId}".`):n.set(r.path,r.artifactId);return i}function e_(t,e={}){const n=Array.isArray(t?.artifacts)?t.artifacts:[],r=(e.selectedArtifactIds||t?.deployOrder||n.map(f=>f.id)).map(f=>n.find(p=>p.id===f)).filter(Boolean),s=[...t?.warnings||[]];let o=[];r.forEach(f=>{const p=Xv(f),g=f.fixedCode||f.code||"",m=f.codeType||Jv[f.artifactType]||Xe.OTHER;g.trim()||s.push(`${f.artifactName||f.id} has no generated code.`),o.push({artifactId:f.id,artifactName:f.artifactName,artifactType:f.artifactType,fileName:p,content:g,type:m,path:f.deployPath||Zv(p,m),deployPath:f.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((f,p)=>({entry:f,index:p})).filter(({entry:f})=>f.type===Xe.FUNCTION&&f.path===a);if(l.length>1){const f=l[0],p={...f.entry,artifactId:l.map(({entry:m})=>m.artifactId).join("+"),artifactName:f.entry.artifactName,content:l.map(({entry:m})=>`// ${m.artifactId} +`;)n++;e+=" "}else if(i==="/*"){for(n+=2;n"&&(n--,n===0))return{inner:t.slice(e+1,i),end:i+1};return null}function Tv(t,e){const n=new RegExp(`class\\s+${e}\\b[^{]*\\{`).exec(t);if(!n)return null;let i=0;for(let r=n.index+n[0].length-1;r$v(t).usable);function Lv(t=""){const e=er(t);return Mv.filter(n=>n.detect(e)).map(({id:n,severity:i,message:r})=>({id:n,severity:i,message:r}))}function Nv(t){const e=[],n=t.matchAll(/\bFuture\b/g);for(const i of n){let r=i.index+6,s=null;const o=r;for(;ro;if(t[r]==="<"){const u=Rv(t,r);if(!u||(s=u.inner.replace(/\s+/g," ").trim(),r=u.end,!/\s/.test(t[r]||"")))continue;for(;rPu(o.functionName)===i);if(r)return r;const s=o=>!o.functionName.startsWith("_");return n.find(s)||n[0]}function Ps(t=""){return Array.from(er(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function Ov(t="",e=""){return yl(t,e)?.returnType||null}function Fu(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 Bv(t,e){const n=Ps(e);if(n.length===0)return null;const r=String(t||"").split("/").pop().replace(/\.dart$/,"");if(n.some(l=>Fu(l)===r)||n.length>1)return null;const[o]=n,a=`${Fu(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 wl(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function Dv(t,e,n=""){const i=yl(e,n)?.functionName;if(!i)return null;const r=String(t||"").split("/").pop(),s=_l(r,"A");if(s===i)return null;const o=`${wl(i)}.dart`;return`File name "${r}" does not match Action "${i}". FlutterFlow derives the action from the file name, so it looks for "${s}" and reports Action "${s}" declaration not found. Rename the file to "${o}" - FlutterFlow puts an underscore before every capital - or rename the function to "${s}".`}function jv(t="",e=""){return yl(t,e)!==null}function Uv(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(i=>Av.has(i)?!1:!Pv.some(s=>i.endsWith(s))||e.has(i))}function Hv(t,{functionName:e="",declaredTypes:n=new Set}={}){const i=Ov(t,e),r=Uv(i,n);if(r.length===0)return null;const[s]=r;let o;return n.has(s)?o=`uses Code File type "${s}", which FlutterFlow cannot process as an Action Return Value`:i===s?o="is not a FlutterFlow Action Return Value":o=`uses type "${s}", which is not a FlutterFlow Action Return Value`,`CustomAction return type "${i}" ${o}. Return JSON (Future) or an existing FlutterFlow Data Type (*Struct) instead.`}function Wv(t,e={}){const n=[],i=t.fileName||"",r=t.code||"";if(Cv.has(t.artifactType)||n.push(xt(t,"error",`Unsupported artifact type "${t.artifactType}".`)),i.endsWith(".dart")||n.push(xt(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!r.trim())return n.push(xt(t,"warning","Generated artifact has no Dart code yet.")),n;if(t.artifactType==="CustomWidget"){/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)||n.push(xt(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const s of Lv(r))n.push(xt(t,s.severity,s.message))}if(t.artifactType==="CustomAction"&&!jv(r,t.artifactName)&&n.push(xt(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const s=e.declaredTypes||new Set(Ps(r)),o=Hv(r,{functionName:t.artifactName,declaredTypes:s});o&&n.push(xt(t,"error",o));const a=Dv(i,r,t.artifactName);a&&n.push(xt(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)&&n.push(xt(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const s=Bv(i,r);s&&n.push(xt(t,"info",s))}return n}function zv(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],n=new Set(e.flatMap(s=>Ps(s.code||""))),i=e.flatMap(s=>Wv(s,{declaredTypes:n})),r=e.map(s=>({artifactId:s.id,fileName:s.fileName,pathHint:Au[s.artifactType]||Au.CodeFile}));return{valid:i.every(s=>s.severity!=="error"),findings:i,deployHints:r}}const Ru="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function Tu(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function qv(t=""){const e=t.indexOf(Ru);return e===-1?t:t.slice(e+Ru.length).replace(/^\s*\n/,"")}const Vv=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function Gv(t="",e=""){const n=qv(t),i=new Set((e.match(/^\s*import .*$/gm)||[]).map(Tu).filter(Boolean)),r=n.split(` +`).filter(s=>{const o=Tu(s);return o===null||!i.has(o)?!0:!Vv.test(s)}).join(` +`).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+r}const Kv=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations"]);function lh(t){let e="",n=0;for(;n{const i=n.name||n.package;if(!i||i==="flutter")return e;const r=n.versionRequired||n.required;return e[i]=r&&n.version||"",e},{})}function Qv(t){const e=new Map,n=new Map,i=[];for(const r of t)e.has(r.fileName)?i.push(`Duplicate deploy file name "${r.fileName}" for artifacts "${e.get(r.fileName)}" and "${r.artifactId}".`):e.set(r.fileName,r.artifactId),n.has(r.path)?i.push(`Duplicate deploy path "${r.path}" for artifacts "${n.get(r.path)}" and "${r.artifactId}".`):n.set(r.path,r.artifactId);return i}function e_(t,e={}){const n=Array.isArray(t?.artifacts)?t.artifacts:[],r=(e.selectedArtifactIds||t?.deployOrder||n.map(h=>h.id)).map(h=>n.find(p=>p.id===h)).filter(Boolean),s=[...t?.warnings||[]];let o=[];r.forEach(h=>{const p=Xv(h),g=h.fixedCode||h.code||"",m=h.codeType||Jv[h.artifactType]||Xe.OTHER;g.trim()||s.push(`${h.artifactName||h.id} has no generated code.`),o.push({artifactId:h.id,artifactName:h.artifactName,artifactType:h.artifactType,fileName:p,content:g,type:m,path:h.deployPath||Zv(p,m),deployPath:h.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((h,p)=>({entry:h,index:p})).filter(({entry:h})=>h.type===Xe.FUNCTION&&h.path===a);if(l.length>1){const h=l[0],p={...h.entry,artifactId:l.map(({entry:m})=>m.artifactId).join("+"),artifactName:h.entry.artifactName,content:l.map(({entry:m})=>`// ${m.artifactId} ${m.content}`).join(` -`)},g=new Set(l.slice(1).map(({index:m})=>m));o=o.filter((m,v)=>!g.has(v)),o[f.index]=p}const u={...Tu(t?.dependencies),...r.reduce((f,p)=>({...f,...Tu(p.dependencies)}),{})},c={};r.forEach(f=>{wl(f.code||"").forEach(p=>{p in u||(c[p]="")})});const d={...c,...u},h=Qv(o);return{bundleId:t?.id||"bundle-current",title:t?.title||"Generated artifact bundle",fileEntries:o,dependencies:d,relationships:t?.relationships||[],warnings:s,errors:h}}function t_(t){return String(t||"").match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/)?.[1]}function n_(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 i_(t,e){const i=[n_(t),t_(e.content),e.artifactName].find(r=>/^[A-Z][A-Za-z0-9_]*$/.test(String(r||"")));if(!i)throw new Error(`Cannot derive a FlutterFlow custom class name for ${t}.`);return i}function r_(t,e=new Map){const n=[];for(const[i,r]of t.entries())r.type!=="C"||e.has(r.path)||n.push({artifactId:r.artifactId||i,className:i_(i,r),content:r.content,fileName:i,path:r.path});return n}function s_(t,e){const n=new Set(e.map(i=>i.path));return new Map(Array.from(t.entries()).filter(([,i])=>!n.has(i.path)))}const $u={pass:0,warning:1,fail:2},o_=["manualActions"];function st(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Vt(...t){for(const e of t){if(typeof e=="string"&&e.trim())return e.trim();if(Array.isArray(e)&&e.length>0){const n=e.filter(i=>typeof i=="string").join(` -`);if(n)return n}}return""}function kt(t){return t==null?[]:Array.isArray(t)?t:[t]}function a_(t){const e=st(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const n=Number(e);if(Number.isFinite(n))return Mu(n);const i=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return i?Mu(Number(i[1])):null}function Mu(t){return t>=0&&t<=100?t:null}function lt(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function bl(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 Ra(...t){return t.filter(Boolean).reduce((e,n)=>$u[n]>$u[e]?n:e,"pass")}function lh(t,e="warning",n="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:n};const i=st(t),r=Vt(i.message,i.title,i.issue,i.description,i.summary);return r?{severity:bl(i.severity||i.status||i.level)||e,message:r,suggestion:Vt(i.suggestion,i.fix,i.recommendation,i.action),source:i.source||n}:null}function Ta(t,e="review"){const n=st(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([r,s])=>kt(n[r]).map(o=>lh(o,s,e)).filter(Boolean))}function l_(t,e,n=null){if(typeof t=="string")return{id:`${n||"bundle"}-manual-${e+1}`,title:t,detail:"",location:"",timing:"unspecified",artifactId:n,source:"Code Review"};const i=st(t),r=Vt(i.title,i.action,i.step,i.message,i.name,i.description);return r?{id:i.id||`${n||"bundle"}-manual-${e+1}`,title:r,detail:Vt(i.detail,i.instructions,i.description),location:Vt(i.location,i.flutterFlowPath,i.path),timing:Vt(i.timing,i.phase)||"unspecified",artifactId:n,source:Vt(i.source)||"Code Review"}:null}function $a(t,e=null){const n=st(t);return o_.flatMap(i=>kt(n[i])).map((i,r)=>l_(i,r,e)).filter(Boolean)}function c_(t){let e=typeof t=="string"?Pa(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const n=st(e);typeof n.content=="string"&&(e=Pa(n.content)||e);const i=st(e),r=st(i.reviewResult||i.codeReview||i.result);return{rawText:"",root:Object.keys(r).length?r:i}}function u_(t,e){const n=[e.id,e.fileName,e.artifactName].map(lt);return t.find(i=>{const r=st(i);return[r.id,r.fileName,r.artifactName,r.name].map(lt).some(s=>s&&n.includes(s))})||null}function d_(t,e){return kt(t?.metadata?.compatibility?.deployHints).find(r=>lt(r?.artifactId)===lt(e.id)||lt(r?.fileName)===lt(e.fileName))?.pathHint||""}function f_(t,e){return kt(t?.relationships).filter(n=>lt(n?.from)===lt(e.id)||lt(n?.to)===lt(e.id))}function h_(t,e){return kt(t?.metadata?.compatibility?.findings).filter(n=>!n?.artifactId||lt(n.artifactId)===lt(e.id)).map(n=>lh(n,"warning","Compatibility check")).filter(Boolean)}function p_(t,e,n,i){const r=u_(e,n),s=st(r?.review||r||n.review),o=Object.keys(s).length>0,a=[...Ta(s),...h_(t,n)],l=$a(s,n.id),u=bl(s.status||s.verdict||s.outcome||s.result),c=a.length?Ra(...a.map(h=>h.severity)):null,d=Ra(u,c,o?null:"warning");return{...n,index:i,status:d,statusReason:o?Vt(s.summary,s.overview,s.assessment,s.conclusion)||(a.length?`${a.length} review finding${a.length===1?"":"s"}`:"No file-level findings"):"No file-level verdict was returned",reviewComplete:o,findings:a,manualSteps:l,fixedSource:typeof s.fixedSource=="string"&&s.fixedSource.trim()?s.fixedSource.trim():null,pathHint:d_(t,n),relationships:f_(t,n)}}function g_({status:t,score:e,artifactPresentations:n,manualSteps:i}){const r=n.length;if(r===0&&i.length===0)return e==null?"Code review returned no overall summary and no score.":`Reviewed bundle with score ${e}/100.`;const s=n.reduce((a,l)=>(a[l.status]+=1,a),{pass:0,warning:0,fail:0}),o=[];return t&&o.push(`Overall verdict: ${t}.`),r&&o.push(`${r} artifact${r===1?"":"s"}: ${s.pass} pass, ${s.warning} warn, ${s.fail} fail.`),i.length&&o.push(`Do before deploy: ${i.map(a=>a.title).join("; ")}.`),e==null&&o.push("No numeric score (0-100) was returned."),o.join(" ")}function m_({bundle:t,reviewResult:e}){const n=st(t),i=kt(n.artifacts),{root:r,rawText:s}=c_(e),o=[r.bundleReview,r.overallReview,r.overall,r.bundleSummary,r.summaryReview,r.review].map(st).find(S=>Object.keys(S).length)||{},a=kt(r.artifacts||r.files||r.reviews),l=i.map((S,_)=>p_(n,a,S,_)),u=Ta(r),d=[...Ta(o),...u],h=[...$a(o),...$a(r),...l.flatMap(S=>S.manualSteps)].filter((S,_,b)=>b.findIndex(k=>k.title===S.title&&k.artifactId===S.artifactId)===_),f=bl(o.status||o.verdict||o.overallStatus||r.status||r.verdict||r.overallStatus||r.outcome),p=Ra(f,...d.map(S=>S.severity),...l.map(S=>S.status)),g=o.score??r.score??r.overallScore??s,m=a_(g),v=Vt(o.headline,o.summary,o.executiveSummary,o.overview,o.assessment,o.conclusion,r.overallSummary,r.headline,r.summary,r.executiveSummary,r.overview,r.assessment,r.conclusion,s)||g_({status:p,score:m,artifactPresentations:l,manualSteps:h}),E=l.reduce((S,_)=>(S[_.status]+=1,S),{pass:0,warning:0,fail:0});return{title:n.title||"Generated artifact bundle",description:n.description||"",status:p,score:m,summary:v,findings:d,manualSteps:h,artifacts:l,counts:E,reviewCoverage:{reviewed:l.filter(S=>S.reviewComplete).length,total:l.length},deployOrder:kt(n.deployOrder),relationships:kt(n.relationships),warnings:kt(n.warnings),compatibility:st(n.metadata?.compatibility)}}const v_=/^\uFEFF/;function Ci(t){let e=0,n=t.length;for(;ee&&!t[n-1].trim();)n--;return t.slice(e,n).join(` +`)},g=new Set(l.slice(1).map(({index:m})=>m));o=o.filter((m,v)=>!g.has(v)),o[h.index]=p}const u={...$u(t?.dependencies),...r.reduce((h,p)=>({...h,...$u(p.dependencies)}),{})},c={};r.forEach(h=>{bl(h.code||"").forEach(p=>{p in u||(c[p]="")})});const d={...c,...u},f=Qv(o);return{bundleId:t?.id||"bundle-current",title:t?.title||"Generated artifact bundle",fileEntries:o,dependencies:d,relationships:t?.relationships||[],warnings:s,errors:f}}function t_(t){return String(t||"").match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/)?.[1]}function n_(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 i_(t,e){const i=[n_(t),t_(e.content),e.artifactName].find(r=>/^[A-Z][A-Za-z0-9_]*$/.test(String(r||"")));if(!i)throw new Error(`Cannot derive a FlutterFlow custom class name for ${t}.`);return i}function r_(t,e=new Map){const n=[];for(const[i,r]of t.entries())r.type!=="C"||e.has(r.path)||n.push({artifactId:r.artifactId||i,className:i_(i,r),content:r.content,fileName:i,path:r.path});return n}function s_(t,e){const n=new Set(e.map(i=>i.path));return new Map(Array.from(t.entries()).filter(([,i])=>!n.has(i.path)))}const Mu={pass:0,warning:1,fail:2},o_=["manualActions"];function st(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Vt(...t){for(const e of t){if(typeof e=="string"&&e.trim())return e.trim();if(Array.isArray(e)&&e.length>0){const n=e.filter(i=>typeof i=="string").join(` +`);if(n)return n}}return""}function kt(t){return t==null?[]:Array.isArray(t)?t:[t]}function a_(t){const e=st(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const n=Number(e);if(Number.isFinite(n))return Lu(n);const i=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return i?Lu(Number(i[1])):null}function Lu(t){return t>=0&&t<=100?t:null}function lt(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function El(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 Ta(...t){return t.filter(Boolean).reduce((e,n)=>Mu[n]>Mu[e]?n:e,"pass")}function ch(t,e="warning",n="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:n};const i=st(t),r=Vt(i.message,i.title,i.issue,i.description,i.summary);return r?{severity:El(i.severity||i.status||i.level)||e,message:r,suggestion:Vt(i.suggestion,i.fix,i.recommendation,i.action),source:i.source||n}:null}function $a(t,e="review"){const n=st(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([r,s])=>kt(n[r]).map(o=>ch(o,s,e)).filter(Boolean))}function l_(t,e,n=null){if(typeof t=="string")return{id:`${n||"bundle"}-manual-${e+1}`,title:t,detail:"",location:"",timing:"unspecified",artifactId:n,source:"Code Review"};const i=st(t),r=Vt(i.title,i.action,i.step,i.message,i.name,i.description);return r?{id:i.id||`${n||"bundle"}-manual-${e+1}`,title:r,detail:Vt(i.detail,i.instructions,i.description),location:Vt(i.location,i.flutterFlowPath,i.path),timing:Vt(i.timing,i.phase)||"unspecified",artifactId:n,source:Vt(i.source)||"Code Review"}:null}function Ma(t,e=null){const n=st(t);return o_.flatMap(i=>kt(n[i])).map((i,r)=>l_(i,r,e)).filter(Boolean)}function c_(t){let e=typeof t=="string"?Fa(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const n=st(e);typeof n.content=="string"&&(e=Fa(n.content)||e);const i=st(e),r=st(i.reviewResult||i.codeReview||i.result);return{rawText:"",root:Object.keys(r).length?r:i}}function u_(t,e){const n=[e.id,e.fileName,e.artifactName].map(lt);return t.find(i=>{const r=st(i);return[r.id,r.fileName,r.artifactName,r.name].map(lt).some(s=>s&&n.includes(s))})||null}function d_(t,e){return kt(t?.metadata?.compatibility?.deployHints).find(r=>lt(r?.artifactId)===lt(e.id)||lt(r?.fileName)===lt(e.fileName))?.pathHint||""}function f_(t,e){return kt(t?.relationships).filter(n=>lt(n?.from)===lt(e.id)||lt(n?.to)===lt(e.id))}function h_(t,e){return kt(t?.metadata?.compatibility?.findings).filter(n=>!n?.artifactId||lt(n.artifactId)===lt(e.id)).map(n=>ch(n,"warning","Compatibility check")).filter(Boolean)}function p_(t,e,n,i){const r=u_(e,n),s=st(r?.review||r||n.review),o=Object.keys(s).length>0,a=[...$a(s),...h_(t,n)],l=Ma(s,n.id),u=El(s.status||s.verdict||s.outcome||s.result),c=a.length?Ta(...a.map(f=>f.severity)):null,d=Ta(u,c,o?null:"warning");return{...n,index:i,status:d,statusReason:o?Vt(s.summary,s.overview,s.assessment,s.conclusion)||(a.length?`${a.length} review finding${a.length===1?"":"s"}`:"No file-level findings"):"No file-level verdict was returned",reviewComplete:o,findings:a,manualSteps:l,fixedSource:typeof s.fixedSource=="string"&&s.fixedSource.trim()?s.fixedSource.trim():null,pathHint:d_(t,n),relationships:f_(t,n)}}function g_({status:t,score:e,artifactPresentations:n,manualSteps:i}){const r=n.length;if(r===0&&i.length===0)return e==null?"Code review returned no overall summary and no score.":`Reviewed bundle with score ${e}/100.`;const s=n.reduce((a,l)=>(a[l.status]+=1,a),{pass:0,warning:0,fail:0}),o=[];return t&&o.push(`Overall verdict: ${t}.`),r&&o.push(`${r} artifact${r===1?"":"s"}: ${s.pass} pass, ${s.warning} warn, ${s.fail} fail.`),i.length&&o.push(`Do before deploy: ${i.map(a=>a.title).join("; ")}.`),e==null&&o.push("No numeric score (0-100) was returned."),o.join(" ")}function m_({bundle:t,reviewResult:e}){const n=st(t),i=kt(n.artifacts),{root:r,rawText:s}=c_(e),o=[r.bundleReview,r.overallReview,r.overall,r.bundleSummary,r.summaryReview,r.review].map(st).find(S=>Object.keys(S).length)||{},a=kt(r.artifacts||r.files||r.reviews),l=i.map((S,_)=>p_(n,a,S,_)),u=$a(r),d=[...$a(o),...u],f=[...Ma(o),...Ma(r),...l.flatMap(S=>S.manualSteps)].filter((S,_,b)=>b.findIndex(k=>k.title===S.title&&k.artifactId===S.artifactId)===_),h=El(o.status||o.verdict||o.overallStatus||r.status||r.verdict||r.overallStatus||r.outcome),p=Ta(h,...d.map(S=>S.severity),...l.map(S=>S.status)),g=o.score??r.score??r.overallScore??s,m=a_(g),v=Vt(o.headline,o.summary,o.executiveSummary,o.overview,o.assessment,o.conclusion,r.overallSummary,r.headline,r.summary,r.executiveSummary,r.overview,r.assessment,r.conclusion,s)||g_({status:p,score:m,artifactPresentations:l,manualSteps:f}),E=l.reduce((S,_)=>(S[_.status]+=1,S),{pass:0,warning:0,fail:0});return{title:n.title||"Generated artifact bundle",description:n.description||"",status:p,score:m,summary:v,findings:d,manualSteps:f,artifacts:l,counts:E,reviewCoverage:{reviewed:l.filter(S=>S.reviewComplete).length,total:l.length},deployOrder:kt(n.deployOrder),relationships:kt(n.relationships),warnings:kt(n.warnings),compatibility:st(n.metadata?.compatibility)}}const v_=/^\uFEFF/;function Ci(t){let e=0,n=t.length;for(;ee&&!t[n-1].trim();)n--;return t.slice(e,n).join(` `)}function __(t){const e=String(t??"").replace(v_,"");if(!e.trim())return"";const n=e.split(` -`),i=c=>{const d=c.trim();return/^`{3,}[A-Za-z0-9+#_.-]*$/.test(d)?c.length-c.trimStart().length:-1};let r=0,s=-1;const o=[];{let c=0;for(let d=0;d=0&&(r++,s<0&&(s=d),o.push(c+h)),c+=n[d].length+1}}if(r===0)return Ci(n);{const c=Ma(e);if(!c.error&&o.every(h=>Nu(h,c.commentAndStringRanges)))return Ci(n)}if(r===1){const c=Ci(n.slice(0,s)),d=Ci(n.slice(s+1));return d.length>=c.length?d:c}const a=[];let l=null;for(let c=0;cc.length>0);return u.length===0?"":u.join(` +`),i=c=>{const d=c.trim();return/^`{3,}[A-Za-z0-9+#_.-]*$/.test(d)?c.length-c.trimStart().length:-1};let r=0,s=-1;const o=[];{let c=0;for(let d=0;d=0&&(r++,s<0&&(s=d),o.push(c+f)),c+=n[d].length+1}}if(r===0)return Ci(n);{const c=La(e);if(!c.error&&o.every(f=>Ou(f,c.commentAndStringRanges)))return Ci(n)}if(r===1){const c=Ci(n.slice(0,s)),d=Ci(n.slice(s+1));return d.length>=c.length?d:c}const a=[];let l=null;for(let c=0;cc.length>0);return u.length===0?"":u.join(` -`)}function y_(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 ch(t){const e=y_(t);return Array.from(e.matchAll(/class\s+([A-Z]\w*)\s+extends\s+[A-Za-z_]\w*Widget\b/g),n=>n[1])}function uh(t){return`${yl(t)}.dart`}function w_(t){return vl(t,"W")}const Lu={"(":")","[":"]","{":"}"},b_={")":"(","]":"[","}":"{"},E_=/[A-Za-z0-9_]/;function Ma(t){const e=[{kind:"code",opener:null,openedLine:0}],n=[];let i=1,r=0;const s=(c,d)=>{(c===` +`)}function y_(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 uh(t){const e=y_(t);return Array.from(e.matchAll(/class\s+([A-Z]\w*)\s+extends\s+[A-Za-z_]\w*Widget\b/g),n=>n[1])}function dh(t){return`${wl(t)}.dart`}function w_(t){return _l(t,"W")}const Nu={"(":")","[":"]","{":"}"},b_={")":"(","]":"[","}":"{"},E_=/[A-Za-z0-9_]/;function La(t){const e=[{kind:"code",opener:null,openedLine:0}],n=[];let i=1,r=0;const s=(c,d)=>{(c===` `||c==="\r"&&d!==` `)&&i++};let o=null;const a=()=>{for(const c of e)(c.kind==="string"||c.kind==="block-comment"||c.kind==="line-comment")&&n.push({start:c.startIndex,end:t.length})};for(;r0?t[r-1]:"",p=r>1?t[r-2]:"",g=(f==="r"||f==="R")&&!E_.test(p);e.push({kind:"string",quote:c,triple:h,raw:g,startIndex:r,openedLine:i}),r+=h?3:1;continue}if(Lu[c]){e.push({kind:"code",opener:c,openedLine:i}),r++;continue}if(b_[c]){if(d.interpolation&&c==="}"){e.pop(),r++;continue}if(d.opener&&Lu[d.opener]===c){e.pop(),r++;continue}return d.opener?(a(),{error:o??`line ${i}: "${c}" closes nothing - "${d.opener}" opened on line ${d.openedLine} is still open`,commentAndStringRanges:n}):(a(),{error:o??`line ${i}: unexpected "${c}" with no matching opener`,commentAndStringRanges:n})}s(c,t[r+1]),r++}a();let l=e.length-1;for(;l>0&&e[l].kind==="line-comment";)l--;let u=o;if(!u){const c=e[l];if(!(c.kind==="code"&&!c.opener&&!c.interpolation))if(c.kind==="string")u=`unclosed ${c.triple?"triple-quoted ":""}string starting on line ${c.openedLine} was never closed`;else if(c.kind==="block-comment")u=`unterminated /* comment starting on line ${c.openedLine}`;else if(c.interpolation){const d=e.findLast(f=>f.opener);u=`unclosed "\${" expression${d?` opened on line ${d.openedLine}`:""} was never closed`}else u=`"${c.opener}" opened on line ${c.openedLine} is never closed`}return{error:u,commentAndStringRanges:n}}function S_(t){return Ma(String(t??"")).error}function Nu(t,e){return e.some(({start:n,end:i})=>t>=n&&ttypeof n=="string"?n:n?.errorMessage).filter(Boolean);return e.length>0?e.join("; "):JSON.stringify(t)}return t&&typeof t=="object"?t.errorMessage||JSON.stringify(t):String(t??"")}const x_=["gmail.com","googlemail.com","outlook.com","hotmail.com","live.com","msn.com"],I_="MAGIC_LINK_SENT",k_="PLUS_ALIAS_REJECTED",C_="Please enter your primary email address. Plus aliases (such as {email}) are not allowed for {domain} accounts.",Ps={allowlistedDomains:x_,successCode:I_,validationCode:k_,messageTemplate:C_},A_=new Set(Ps.allowlistedDomains),P_=Ps.successCode,dh=Ps.validationCode;function Fs(t){return typeof t=="string"?t.trim():""}function F_(t){const e=Fs(t),n=e.lastIndexOf("@");if(n<=0||n===e.length-1)return!1;const i=e.slice(0,n),r=e.slice(n+1).toLowerCase();return A_.has(r)?i.includes("+"):!1}function R_(t,e){return Ps.messageTemplate.replaceAll("{email}",t).replaceAll("{domain}",e)}function fh(t){if(!F_(t))return null;const e=Fs(t),n=e.lastIndexOf("@"),i=e.slice(n+1).toLowerCase();return R_(e,i)}function hh(t,e){return t?.code===dh?t.message||fh(e)||"Please enter your primary email address.":t?.code===P_||!t?.code?`Check your email — we sent a link to ${Fs(e)}`:t.message||"Something went wrong. Please try again."}const T_="ccc_auth_session",$_="ccc_subscription",M_=Object.freeze(["hasSeenWalkthrough"]);function L_(t){const e=[];for(const n of M_)t.getItem(n)!==null&&(t.removeItem(n),e.push(n));return e}function N_(){return[T_,$_]}function O_({storage:t,onIdentityChanged:e,onPlanChanged:n}){for(const i of N_())t.removeItem(i);typeof e=="function"&&e(),typeof n=="function"&&n()}function B_({sendLink:t,getEmail:e,onState:n}){let i=!1;return async function(){if(i)return{status:"busy"};i=!0;let s;try{n({status:"pending",error:null});const o=await t(e());return s={status:"sent",data:o},n({status:"sent",data:o}),s}catch(o){return s={status:"error",error:o},n({status:"error",error:o}),s}finally{i=!1}}}const D_=/^dependencies\s*:\s*(?:#.*)?$/,j_=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function Rs(t){const e=t.match(j_);return e?e[1]??e[2]??e[3]:null}function ar(t){const e=t.trim();return e===""||e.startsWith("#")}function fi(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function Sl(t,e){const n=t.findIndex(s=>e.test(s));if(n===-1)return null;let i=n,r=null;for(let s=n+1;s=0.0.0"}`}function z_(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([u])=>u&&u!=="flutter");if(i.length===0)return{yaml:n,added:[],alreadyPresent:[]};const r=n.split(` -`),s=new Set(gh(n)),o=[],a=[];for(const[u,c]of i)s.has(u)?a.push(u):(o.push([u,c]),s.add(u));if(o.length===0)return{yaml:n,added:[],alreadyPresent:a};const l=xl(r);if(l){const u=o.map(([c,d])=>Ou(l.childIndent,c,d));r.splice(l.endIndex,0,...u)}else r.length>0&&r[r.length-1].trim()!==""&&r.push(""),r.push("dependencies:"),o.forEach(([u,c])=>{r.push(Ou(" ",u,c))});return{yaml:r.join(` +`){n.push({start:d.startIndex,end:r}),o??=`line ${i}: string starting on line ${d.openedLine} is never closed`,e.pop();continue}if(!d.raw&&c==="\\"){s(t[r+1]??"",t[r+2]??""),r+=2;continue}if(!d.raw&&c==="$"&&t[r+1]==="{"){e.push({kind:"code",opener:null,interpolation:!0}),r+=2;continue}const f=d.triple?3:1;if(c===d.quote&&t.slice(r,r+f)===d.quote.repeat(f)){n.push({start:d.startIndex,end:r+f}),e.pop(),r+=f;continue}s(c,t[r+1]),r++;continue}if(c==="/"&&t[r+1]==="/"){e.push({kind:"line-comment",startIndex:r}),r+=2;continue}if(c==="/"&&t[r+1]==="*"){e.push({kind:"block-comment",startIndex:r,openedLine:i,depth:1}),r+=2;continue}if(c==="'"||c==='"'){const f=t.slice(r,r+3)===c.repeat(3),h=r>0?t[r-1]:"",p=r>1?t[r-2]:"",g=(h==="r"||h==="R")&&!E_.test(p);e.push({kind:"string",quote:c,triple:f,raw:g,startIndex:r,openedLine:i}),r+=f?3:1;continue}if(Nu[c]){e.push({kind:"code",opener:c,openedLine:i}),r++;continue}if(b_[c]){if(d.interpolation&&c==="}"){e.pop(),r++;continue}if(d.opener&&Nu[d.opener]===c){e.pop(),r++;continue}return d.opener?(a(),{error:o??`line ${i}: "${c}" closes nothing - "${d.opener}" opened on line ${d.openedLine} is still open`,commentAndStringRanges:n}):(a(),{error:o??`line ${i}: unexpected "${c}" with no matching opener`,commentAndStringRanges:n})}s(c,t[r+1]),r++}a();let l=e.length-1;for(;l>0&&e[l].kind==="line-comment";)l--;let u=o;if(!u){const c=e[l];if(!(c.kind==="code"&&!c.opener&&!c.interpolation))if(c.kind==="string")u=`unclosed ${c.triple?"triple-quoted ":""}string starting on line ${c.openedLine} was never closed`;else if(c.kind==="block-comment")u=`unterminated /* comment starting on line ${c.openedLine}`;else if(c.interpolation){const d=e.findLast(h=>h.opener);u=`unclosed "\${" expression${d?` opened on line ${d.openedLine}`:""} was never closed`}else u=`"${c.opener}" opened on line ${c.openedLine} is never closed`}return{error:u,commentAndStringRanges:n}}function S_(t){return La(String(t??"")).error}function Ou(t,e){return e.some(({start:n,end:i})=>t>=n&&ttypeof n=="string"?n:n?.errorMessage).filter(Boolean);return e.length>0?e.join("; "):JSON.stringify(t)}return t&&typeof t=="object"?t.errorMessage||JSON.stringify(t):String(t??"")}const x_=["gmail.com","googlemail.com","outlook.com","hotmail.com","live.com","msn.com"],I_="MAGIC_LINK_SENT",k_="PLUS_ALIAS_REJECTED",C_="Please enter your primary email address. Plus aliases (such as {email}) are not allowed for {domain} accounts.",Fs={allowlistedDomains:x_,successCode:I_,validationCode:k_,messageTemplate:C_},A_=new Set(Fs.allowlistedDomains),P_=Fs.successCode,fh=Fs.validationCode;function Rs(t){return typeof t=="string"?t.trim():""}function F_(t){const e=Rs(t),n=e.lastIndexOf("@");if(n<=0||n===e.length-1)return!1;const i=e.slice(0,n),r=e.slice(n+1).toLowerCase();return A_.has(r)?i.includes("+"):!1}function R_(t,e){return Fs.messageTemplate.replaceAll("{email}",t).replaceAll("{domain}",e)}function hh(t){if(!F_(t))return null;const e=Rs(t),n=e.lastIndexOf("@"),i=e.slice(n+1).toLowerCase();return R_(e,i)}function ph(t,e){return t?.code===fh?t.message||hh(e)||"Please enter your primary email address.":t?.code===P_||!t?.code?`Check your email — we sent a link to ${Rs(e)}`:t.message||"Something went wrong. Please try again."}const T_="ccc_auth_session",$_="ccc_subscription",M_=Object.freeze(["hasSeenWalkthrough"]);function L_(t){const e=[];for(const n of M_)t.getItem(n)!==null&&(t.removeItem(n),e.push(n));return e}function N_(){return[T_,$_]}function O_({storage:t,onIdentityChanged:e,onPlanChanged:n}){for(const i of N_())t.removeItem(i);typeof e=="function"&&e(),typeof n=="function"&&n()}function B_({sendLink:t,getEmail:e,onState:n}){let i=!1;return async function(){if(i)return{status:"busy"};i=!0;let s;try{n({status:"pending",error:null});const o=await t(e());return s={status:"sent",data:o},n({status:"sent",data:o}),s}catch(o){return s={status:"error",error:o},n({status:"error",error:o}),s}finally{i=!1}}}const D_=/^dependencies\s*:\s*(?:#.*)?$/,j_=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function Ts(t){const e=t.match(j_);return e?e[1]??e[2]??e[3]:null}function ar(t){const e=t.trim();return e===""||e.startsWith("#")}function fi(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function xl(t,e){const n=t.findIndex(s=>e.test(s));if(n===-1)return null;let i=n,r=null;for(let s=n+1;s=0.0.0"}`}function z_(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([u])=>u&&u!=="flutter");if(i.length===0)return{yaml:n,added:[],alreadyPresent:[]};const r=n.split(` +`),s=new Set(mh(n)),o=[],a=[];for(const[u,c]of i)s.has(u)?a.push(u):(o.push([u,c]),s.add(u));if(o.length===0)return{yaml:n,added:[],alreadyPresent:a};const l=Il(r);if(l){const u=o.map(([c,d])=>Bu(l.childIndent,c,d));r.splice(l.endIndex,0,...u)}else r.length>0&&r[r.length-1].trim()!==""&&r.push(""),r.push("dependencies:"),o.forEach(([u,c])=>{r.push(Bu(" ",u,c))});return{yaml:r.join(` `),added:o.map(([u])=>u),alreadyPresent:a}}function q_(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([l])=>l&&l!=="flutter");if(i.length===0)return{yaml:n,overridden:[],skipped:[]};const r=n.split(` -`),s=$s(n),o=[],a=[];for(const[l,u]of i){const c=s.get(l);if(!c||!c.isScalar||!String(u||"").trim()){a.push(l);continue}const d=" ".repeat(fi(r[c.lineIndex]));r[c.lineIndex]=`${d}${l}: ${vh(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:r.join(` -`),overridden:o,skipped:a}}function _h(t){const e=String(t||""),n=[];return e.trim()?(/^name:\s*\S+/m.test(e)||n.push("pubspec.yaml missing name field"),xl(e.split(` -`))||n.push("pubspec.yaml missing dependencies section"),gh(e).includes("flutter")||n.push("pubspec.yaml missing Flutter SDK dependency"),{valid:n.length===0,errors:n}):(n.push("pubspec.yaml is empty"),{valid:!1,errors:n})}const V_=">=3.0.0 <4.0.0";function La(t){const e=String(t||"").trim(),n=e[0];return n!=="'"&&n!=='"'||e[e.length-1]!==n?e:e.slice(1,-1).replaceAll(`${n}${n}`,n)}function G_(t=""){const e=Yv(t).filter(n=>!n.startsWith("dart:")&&!n.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function Bu(t,e,n){const i=[];for(const[r,s]of t){if(s.isScalar){e[r]=La(s.constraint);continue}if(s.sourceKey==="sdk"){n.add(r);continue}if(s.sourceKey===null&&s.version){e[r]=La(s.version);continue}i.push(r)}return i}function K_(t){const e=new Set,n={},i={},r=Bu($s(t),n,e);r.push(...Bu(H_(t,"dependency_overrides"),i,e));const s=new Set([...Object.keys(n),...e]),{sdk:o}=mh(t);return{sdkConstraint:La(o)||V_,dependencies:n,overrides:i,sdkPackages:[...e].sort(),availablePackages:s,unrepresentable:r}}function Y_(t,e,n){return e.length>0?`${t} imports ${e.join(", ")}, which FlutterFlow only generates once the app is built, so it could not be compiled before the deploy.`:`${t} imports ${n.join(", ")}, which your project's pubspec.yaml does not declare with a version constraint, so it could not be compiled before the deploy.`}function J_(t,e){const{sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s,availablePackages:o,unrepresentable:a}=K_(e),l={sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s},u=[],c=[],d=a.map(h=>`Your project declares ${h} from a source that cannot be reproduced outside it, so the pre-deploy compile check runs against a scratch package graph that omits ${h}. Classes that do not import ${h} directly are still checked, but against that reduced graph, so their transitive package resolution may differ from your project's and the check is approximate for them.`);for(const h of t){const{className:f,content:p}=h,g=wl(p),m=g.filter(S=>a.includes(S));if(m.length>0){c.push({className:f,reason:`${f} was not compiled before deploying: it imports ${m.join(", ")}, which your project declares from a source that cannot be reproduced outside it, so package resolution could not be matched exactly.`});continue}const{unresolvableImports:v}=G_(p),E=g.filter(S=>!o.has(S));if(v.length>0||E.length>0){c.push({className:f,reason:Y_(f,v,E)});continue}u.push({fileName:`${yl(f)}.dart`,content:p})}return{manifest:l,sources:u,skipped:c,approximate:d}}function Du(t,e){const n=`${t}${e}`.split(` -`),i=n.pop()??"",r=[];for(const s of n){const o=yh(s);o&&r.push(o)}return{events:r,buffer:i}}function Z_(t){const e=yh(t);return e?[e]:[]}function yh(t){const e=t.trim();if(!e)return null;try{const n=JSON.parse(e);return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}const Le=Object.freeze({COMMITTED:"committed",PARTIAL:"partial",FAILED:"failed",UNCONFIRMED:"unconfirmed"}),wh=12e4;function bh(t){return t?.unconfirmed===!0||t?.outcome===Le.UNCONFIRMED?Le.UNCONFIRMED:t?.partial===!0||t?.outcome===Le.PARTIAL?Le.PARTIAL:t?.success===!0?Le.COMMITTED:Le.FAILED}class Qe extends Error{constructor(e){super(e),this.name="UnconfirmedDeployError",this.outcome=Le.UNCONFIRMED}}function ju({httpStatus:t}={}){return new Qe(`Every FlutterFlow sync endpoint lost its response or ended in a server error${t?` (last: HTTP ${t})`:""} — neither can prove the push was refused, so it may already have been applied. Open the FlutterFlow project to reconcile before retrying.`)}async function X_(t,e={}){const{onPhase:n,onLog:i}=e;let r=null,s=null,o="";const a=u=>{if(u.event==="phase"){u.phase&&(s=u.phase),u.message&&n&&n(u.message);return}if(u.event==="log"){u.message&&i&&i(u.message);return}r=u};let l=null;try{if(t.body?.getReader){const u=t.body.getReader(),c=new TextDecoder;for(;;){const{done:d,value:h}=await u.read();if(d)break;const f=Du(o,c.decode(h,{stream:!0}));o=f.buffer,f.events.forEach(a)}}else{const u=Du("",await t.text());o=u.buffer,u.events.forEach(a)}}catch(u){l=u}return Z_(o).forEach(a),r?{...r,success:r.success===!0||r.success===void 0&&t.ok,finalResultReceived:!0,runnerPhase:s,httpStatus:t.status}:{success:!1,finalResultReceived:!1,httpRejected:!t.ok,httpStatus:t.status,runnerPhase:s,error:t.ok?l?"The connection to the FlutterFlow deploy runner dropped before it reported a result.":"The FlutterFlow deploy runner closed the connection before it finished.":`FlutterFlow custom class provisioning failed (HTTP ${t.status}).`}}const Q_=new Set(["connected","workspace_init","workspace_ready","verifying"]);function ey(t){return t?.preWrite===!0||Array.isArray(t?.analyzerErrors)&&t.analyzerErrors.length>0?!0:typeof t?.runnerPhase=="string"?Q_.has(t.runnerPhase):typeof t?.httpStatus=="number"?t.httpStatus>=400&&t.httpStatus<500:!1}function Uu(t){if(t?.finalResultReceived){const e=bh(t);return e===Le.FAILED&&!ey(t)?Le.UNCONFIRMED:e}return t?.httpRejected?Le.FAILED:Le.UNCONFIRMED}function ty(){let t=document.getElementById("fx-grid");if(!t)return null;const e=window.matchMedia("(prefers-reduced-motion: reduce)"),n=window.matchMedia("(pointer: none)");let i=t.getContext("webgl2",{alpha:!0,antialias:!1,depth:!1,stencil:!1,premultipliedAlpha:!0,powerPreference:"low-power"}),r=i?null:t.getContext("2d");if(!i&&!r)return null;const s='',o=`#version 300 es +`),s=Ms(n),o=[],a=[];for(const[l,u]of i){const c=s.get(l);if(!c||!c.isScalar||!String(u||"").trim()){a.push(l);continue}const d=" ".repeat(fi(r[c.lineIndex]));r[c.lineIndex]=`${d}${l}: ${_h(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:r.join(` +`),overridden:o,skipped:a}}function yh(t){const e=String(t||""),n=[];return e.trim()?(/^name:\s*\S+/m.test(e)||n.push("pubspec.yaml missing name field"),Il(e.split(` +`))||n.push("pubspec.yaml missing dependencies section"),mh(e).includes("flutter")||n.push("pubspec.yaml missing Flutter SDK dependency"),{valid:n.length===0,errors:n}):(n.push("pubspec.yaml is empty"),{valid:!1,errors:n})}const V_=">=3.0.0 <4.0.0";function Na(t){const e=String(t||"").trim(),n=e[0];return n!=="'"&&n!=='"'||e[e.length-1]!==n?e:e.slice(1,-1).replaceAll(`${n}${n}`,n)}function G_(t=""){const e=Yv(t).filter(n=>!n.startsWith("dart:")&&!n.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function Du(t,e,n){const i=[];for(const[r,s]of t){if(s.isScalar){e[r]=Na(s.constraint);continue}if(s.sourceKey==="sdk"){n.add(r);continue}if(s.sourceKey===null&&s.version){e[r]=Na(s.version);continue}i.push(r)}return i}function K_(t){const e=new Set,n={},i={},r=Du(Ms(t),n,e);r.push(...Du(H_(t,"dependency_overrides"),i,e));const s=new Set([...Object.keys(n),...e]),{sdk:o}=vh(t);return{sdkConstraint:Na(o)||V_,dependencies:n,overrides:i,sdkPackages:[...e].sort(),availablePackages:s,unrepresentable:r}}function Y_(t,e,n){return e.length>0?`${t} imports ${e.join(", ")}, which FlutterFlow only generates once the app is built, so it could not be compiled before the deploy.`:`${t} imports ${n.join(", ")}, which your project's pubspec.yaml does not declare with a version constraint, so it could not be compiled before the deploy.`}function J_(t,e){const{sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s,availablePackages:o,unrepresentable:a}=K_(e),l={sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s},u=[],c=[],d=a.map(f=>`Your project declares ${f} from a source that cannot be reproduced outside it, so the pre-deploy compile check runs against a scratch package graph that omits ${f}. Classes that do not import ${f} directly are still checked, but against that reduced graph, so their transitive package resolution may differ from your project's and the check is approximate for them.`);for(const f of t){const{className:h,content:p}=f,g=bl(p),m=g.filter(S=>a.includes(S));if(m.length>0){c.push({className:h,reason:`${h} was not compiled before deploying: it imports ${m.join(", ")}, which your project declares from a source that cannot be reproduced outside it, so package resolution could not be matched exactly.`});continue}const{unresolvableImports:v}=G_(p),E=g.filter(S=>!o.has(S));if(v.length>0||E.length>0){c.push({className:h,reason:Y_(h,v,E)});continue}u.push({fileName:`${wl(h)}.dart`,content:p})}return{manifest:l,sources:u,skipped:c,approximate:d}}function ju(t,e){const n=`${t}${e}`.split(` +`),i=n.pop()??"",r=[];for(const s of n){const o=wh(s);o&&r.push(o)}return{events:r,buffer:i}}function Z_(t){const e=wh(t);return e?[e]:[]}function wh(t){const e=t.trim();if(!e)return null;try{const n=JSON.parse(e);return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}const Le=Object.freeze({COMMITTED:"committed",PARTIAL:"partial",FAILED:"failed",UNCONFIRMED:"unconfirmed"}),bh=12e4,X_=1e4;function Eh(t){return t?.unconfirmed===!0||t?.outcome===Le.UNCONFIRMED?Le.UNCONFIRMED:t?.partial===!0||t?.outcome===Le.PARTIAL?Le.PARTIAL:t?.success===!0?Le.COMMITTED:Le.FAILED}class Qe extends Error{constructor(e){super(e),this.name="UnconfirmedDeployError",this.outcome=Le.UNCONFIRMED}}function Uu({httpStatus:t}={}){return new Qe(`Every FlutterFlow sync endpoint lost its response or ended in a server error${t?` (last: HTTP ${t})`:""} — neither can prove the push was refused, so it may already have been applied. Open the FlutterFlow project to reconcile before retrying.`)}async function Q_(t,e={}){const{onPhase:n,onLog:i}=e;let r=null,s=null,o="";const a=u=>{if(u.event==="phase"){u.phase&&(s=u.phase),u.message&&n&&n(u.message);return}if(u.event==="log"){u.message&&i&&i(u.message);return}r=u};let l=null;try{if(t.body?.getReader){const u=t.body.getReader(),c=new TextDecoder;for(;;){const{done:d,value:f}=await u.read();if(d)break;const h=ju(o,c.decode(f,{stream:!0}));o=h.buffer,h.events.forEach(a)}}else{const u=ju("",await t.text());o=u.buffer,u.events.forEach(a)}}catch(u){l=u}return Z_(o).forEach(a),r?{...r,success:r.success===!0||r.success===void 0&&t.ok,finalResultReceived:!0,runnerPhase:s,httpStatus:t.status}:{success:!1,finalResultReceived:!1,httpRejected:!t.ok,httpStatus:t.status,runnerPhase:s,error:t.ok?l?"The connection to the FlutterFlow deploy runner dropped before it reported a result.":"The FlutterFlow deploy runner closed the connection before it finished.":`FlutterFlow custom class provisioning failed (HTTP ${t.status}).`}}const ey=new Set(["connected","workspace_init","workspace_ready","verifying"]);function ty(t){return t?.preWrite===!0||Array.isArray(t?.analyzerErrors)&&t.analyzerErrors.length>0?!0:typeof t?.runnerPhase=="string"?ey.has(t.runnerPhase):typeof t?.httpStatus=="number"?t.httpStatus>=400&&t.httpStatus<500:!1}function Hu(t){if(t?.finalResultReceived){const e=Eh(t);return e===Le.FAILED&&!ty(t)?Le.UNCONFIRMED:e}return t?.httpRejected?Le.FAILED:Le.UNCONFIRMED}function ny(){let t=document.getElementById("fx-grid");if(!t)return null;const e=window.matchMedia("(prefers-reduced-motion: reduce)"),n=window.matchMedia("(pointer: none)");let i=t.getContext("webgl2",{alpha:!0,antialias:!1,depth:!1,stencil:!1,premultipliedAlpha:!0,powerPreference:"low-power"}),r=i?null:t.getContext("2d");if(!i&&!r)return null;const s='',o=`#version 300 es in vec2 p; void main(){ gl_Position = vec4(p, 0.0, 1.0); }`;function a(){return["#version 300 es","precision highp float;","out vec4 o;","uniform vec2 res;","uniform vec2 design;","uniform vec2 mouse;","uniform float energy;","uniform float parallax;","uniform float t;","uniform vec3 ink;","uniform sampler2D mark;","uniform vec2 rot;","const float WARP_A = 0.0032;","void main(){"," vec2 px = gl_FragCoord.xy * (design / res);"," vec2 p = vec2(px.x, design.y - px.y);"," vec2 off = vec2(0.0, -parallax) + vec2(sin(t * 0.11), cos(t * 0.09)) * 7.0;"," vec2 g = p + off;"," vec2 gm = mouse + off;"," float base = min(design.x, design.y);"," float spacing = clamp(base / 10.0, 64.0, 118.0);"," vec2 rel = g - gm;"," float rho = length(rel) + 1e-5;"," vec2 dir = rel / rho;"," vec2 pw = gm + dir * (rho + WARP_A * rho * rho);"," vec2 cell = floor(pw / spacing);"," vec2 cw = (cell + 0.5) * spacing - gm;"," float Rc = length(cw) + 1e-5;"," float rhoC = (-1.0 + sqrt(1.0 + 4.0 * WARP_A * Rc)) / (2.0 * WARP_A);"," vec2 c = gm + (cw / Rc) * rhoC;"," float cellSize = spacing / (1.0 + 2.0 * WARP_A * rhoC);"," float sigma = spacing * 2.9;"," float f = exp(-(rhoC * rhoC) / (2.0 * sigma * sigma));"," float scale = mix(0.32, 1.42, f);"," float weight = smoothstep(0.06, 0.80, f);"," float hs = cellSize * 0.26 * scale;"," vec2 uv = (g - c) / hs;"," vec2 ruv = mat2(rot.x, rot.y, -rot.y, rot.x) * uv;"," float cov = 0.0;"," if (abs(ruv.x) <= 1.0 && abs(ruv.y) <= 1.0) cov = texture(mark, ruv * 0.5 + 0.5).a;"," float s = cov * weight * energy * 0.26;"," o = vec4(ink * s, s);","}"].join(` -`)}let l=null,u,c,d,h,f,p,g,m,v;function E(Y,W){if(!i)return null;const D=i.createShader(Y);return i.shaderSource(D,W),i.compileShader(D),i.getShaderParameter(D,i.COMPILE_STATUS)?D:(window.console&&console.warn("fx-grid shader: "+i.getShaderInfoLog(D)),null)}if(i){const Y=E(i.VERTEX_SHADER,o),W=E(i.FRAGMENT_SHADER,a());if(Y&&W&&(l=i.createProgram(),i.attachShader(l,Y),i.attachShader(l,W),i.linkProgram(l),i.getProgramParameter(l,i.LINK_STATUS)||(window.console&&console.warn("fx-grid link: "+i.getProgramInfoLog(l)),l=null)),l){i.useProgram(l),i.bindBuffer(i.ARRAY_BUFFER,i.createBuffer()),i.bufferData(i.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),i.STATIC_DRAW);const D=i.getAttribLocation(l,"p");i.enableVertexAttribArray(D),i.vertexAttribPointer(D,2,i.FLOAT,!1,0,0),u=i.getUniformLocation(l,"res"),c=i.getUniformLocation(l,"design"),d=i.getUniformLocation(l,"mouse"),h=i.getUniformLocation(l,"energy"),f=i.getUniformLocation(l,"parallax"),p=i.getUniformLocation(l,"t"),g=i.getUniformLocation(l,"ink"),m=i.getUniformLocation(l,"mark"),v=i.getUniformLocation(l,"rot"),i.enable(i.BLEND),i.blendFunc(i.ONE,i.ONE_MINUS_SRC_ALPHA),i.clearColor(0,0,0,0)}else{i=null;const D=t.cloneNode(!1);if(t.parentNode.replaceChild(D,t),t=D,r=t.getContext("2d"),!r)return null}}function S(Y){if(!Y)return null;const W=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(Y);if(W){let D=W[1];return D.length===3&&(D=D[0]+D[0]+D[1]+D[1]+D[2]+D[2]),[parseInt(D.slice(0,2),16)/255,parseInt(D.slice(2,4),16)/255,parseInt(D.slice(4,6),16)/255]}try{const D=document.createElement("canvas");D.width=1,D.height=1;const ue=D.getContext("2d");ue.fillStyle="rgb(9, 8, 7)";const xe=String(ue.fillStyle);ue.fillStyle=Y;const Fe=String(ue.fillStyle);if(Fe===xe)return null;const dt=/^#([0-9a-f]{6})$/i.exec(Fe);if(dt){const ft=dt[1];return[parseInt(ft.slice(0,2),16)/255,parseInt(ft.slice(2,4),16)/255,parseInt(ft.slice(4,6),16)/255]}const Nt=/rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i.exec(Fe);if(Nt)return[Number(Nt[1])/255,Number(Nt[2])/255,Number(Nt[3])/255]}catch{}return null}function _(){let Y="";try{const W=getComputedStyle(document.documentElement);Y=(W.getPropertyValue("--fx-ink")||"").trim()||(W.getPropertyValue("--fg")||"").trim()}catch{}return S(Y)||[.56,.68,.88]}const b=_();let k=1920,T=1080,x=960,F=540,$=960,O=540,L=.66,N=0,K=-1e9,V=!1,M=0,R=0,Z=null,Ce=!1,oe=!1,ye=!1;const $e=64,ae=15.2;let Ie=0,Se=0;const De=.0032,wt=0,ge=.56,Je=.26,bt=.32,mn=.16,Re=.349;let Pe=wt;function $t(){const Y=t.getBoundingClientRect(),W=t.clientWidth,D=t.clientHeight;if(!Y.width||!W||!D)return;const ue=Math.min(window.devicePixelRatio||1,2),xe=Math.max(.2,Math.min(2,Y.width/W*ue)),Fe=Math.max(2,Math.round(W*xe)),dt=Math.max(2,Math.round(D*xe));(Fe!==t.width||dt!==t.height)&&(t.width=Fe,t.height=dt,i&&i.viewport(0,0,Fe,dt)),k=W,T=D,V||(x=$=k/2,F=O=T/2,V=!0)}function Bn(Y){!l||!Ce||!i||(i.uniform2f(u,t.width,t.height),i.uniform2f(c,k,T),i.uniform2f(d,x,F),i.uniform1f(h,L),i.uniform1f(f,N),i.uniform2f(v,Math.cos(Pe),Math.sin(Pe)),i.uniform1f(p,Y),i.uniform3f(g,b[0],b[1],b[2]),i.clear(i.COLOR_BUFFER_BIT),i.drawArrays(i.TRIANGLES,0,3))}function qe(Y,W,D){const ue=Math.max(0,Math.min(1,(D-Y)/(W-Y)));return ue*ue*(3-2*ue)}function Dn(Y){if(!Z||!r)return;const W=r;W.setTransform(1,0,0,1,0,0),W.clearRect(0,0,t.width,t.height);const D=t.width/k;W.setTransform(D,0,0,D,0,0),W.globalAlpha=1;const ue=Math.min(k,T),xe=Math.max(64,Math.min(118,ue/10)),Fe=xe*2.9,dt=2*Fe*Fe,Nt=Math.sin(Y*.11)*7,ft=Math.cos(Y*.09)*7-N,dr=x+Nt,fr=F+ft,no=Fe*Math.sqrt(2*Math.log(1/.06)),mi=no+De*no*no+xe,Pp=Math.floor((dr-mi)/xe)-1,Fp=Math.ceil((dr+mi)/xe)+1,Rp=Math.floor((fr-mi)/xe)-1,Tp=Math.ceil((fr+mi)/xe)+1;for(let io=Rp;io<=Tp;io++){const $p=(io+.5)*xe;for(let ro=Pp;ro<=Fp;ro++){const so=(ro+.5)*xe-dr,oo=$p-fr,ao=Math.sqrt(so*so+oo*oo)+1e-5;if(ao>mi)continue;const hr=(-1+Math.sqrt(1+4*De*ao))/(2*De),ac=Math.exp(-(hr*hr)/dt),lc=qe(.06,.8,ac)*L*.26;if(lc<.004)continue;const on=xe/(1+2*De*hr)*.26*(.32+1.1*ac),cc=hr/ao,lo=dr+so*cc,co=fr+oo*cc;lo<-on*1.6||lo>k+on*1.6||co<-on*1.6||co>T+on*1.6||(W.globalAlpha=lc,W.save(),W.translate(lo,co),W.rotate(Pe),W.drawImage(Z,-on,-on,on*2,on*2),W.restore())}}W.globalAlpha=1}function Mt(Y){if(!oe)return;const W=R?Math.min(.05,(Y-R)/1e3):.016;R=Y;const ue=Y-K>2400?.6:1;L+=(ue-L)*Math.min(1,W*3.2);const xe=Math.min(.05,W);Ie+=(($-x)*$e-Ie*ae)*xe,Se+=((O-F)*$e-Se*ae)*xe,x+=Ie*xe,F+=Se*xe,N=(window.scrollY||window.pageYOffset||0)*.55;const Fe=Y/1e3,dt=x/(k||1)-.5,Nt=F/(T||1)-.5;let ft=dt*(dt>=0?ge:Je)+Nt*(Nt>=0?bt:mn);ft>Re?ft=Re:ft<-Re&&(ft=-Re),Pe=wt+ft-N*6e-4,$t(),i?Bn(Fe):Dn(Fe),M=requestAnimationFrame(Mt)}function Lt(Y){if(!oe)return;const W=t.getBoundingClientRect();!W.width||!k||!T||($=(Y.clientX-W.left)/W.width*k,O=(Y.clientY-W.top)/W.height*T,K=performance.now())}function ut(){oe||to||e.matches||n.matches||!ye||document.hidden||(oe=!0,R=0,M=requestAnimationFrame(Mt))}function sn(){oe=!1,M&&(cancelAnimationFrame(M),M=0),R=0}function gi(){e.matches?(sn(),t.classList.remove("is-ready")):ye&&ut()}function jn(){n.matches?sn():ye&&ut()}function rc(){document.hidden?sn():ye&&ut()}const sc=new IntersectionObserver(Y=>{ye=Y[0]?.isIntersecting||!1,ye?ut():sn()},{threshold:0});sc.observe(t),window.addEventListener("pointermove",Lt,{passive:!0,capture:!0}),window.addEventListener("resize",$t),e.addEventListener("change",gi),n.addEventListener("change",jn),document.addEventListener("visibilitychange",rc);function Ap(){const Y=(s.match(/\sd="([^"]+)"/)||[])[1],W=document.createElement("canvas");W.width=256,W.height=256;const D=W.getContext("2d");if(Y&&window.Path2D){const ue=Math.min(8.533333333333333,8.421052631578947);D.setTransform(ue,0,0,ue,ue+(256-30*ue)/2,-6.4*ue),D.fillStyle="rgb(255,255,255)",D.fill(new Path2D(Y),"evenodd"),D.setTransform(1,0,0,1,0,0)}try{const ue=D.getImageData(0,0,256,256),xe=ue.data;for(let Fe=3;Feoe}}const ny=120;function iy(t,e,n){return tn?n:t}function de(t,e,n){return iy((t-e)/(n-e),0,1)}function ry(t){return t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2}function Uo(t){return 1-Math.pow(1-t,3)}function Ve(t,e){return e=e===void 0?1.7:e,1+(e+1)*Math.pow(t-1,3)+e*Math.pow(t-1,2)}function Hu(t){return 1-Math.pow(2,-9*t)*Math.cos(t*15)}function te(t,e){if(t<=e[0].t)return e[0].v;for(let n=1;n8.2&&_<9.4&&(s*=1-.07*Math.sin(de(_,8.2,9.4)*Math.PI))}else if(t<53){const _=t-42;g=te(_,[{t:0,v:1},{t:2,v:0},{t:4.2,v:0},{t:4.6,v:1},{t:6.8,v:1},{t:7.4,v:0},{t:9.4,v:0},{t:10.6,v:1}]),p=te(_,[{t:0,v:1},{t:2,v:.3},{t:4.6,v:1,e:Ve}]),d=te(_,[{t:0,v:0},{t:2,v:.3},{t:4.6,v:.16,e:Ve},{t:10.6,v:0}]),f=te(_,[{t:0,v:0},{t:2,v:-40},{t:4.6,v:0,e:Ve}]),o=te(_,[{t:0,v:0},{t:4.6,v:-.12},{t:10.6,v:0}])}else if(t<60){const _=t-53;c=te(_,[{t:0,v:1},{t:.35,v:0},{t:.45,v:0},{t:.7,v:1}]);const b=de(_,.45,2.2);a=b>0?-2.6*(1-Hu(b)):0,g=te(_,[{t:0,v:1},{t:.57,v:0},{t:.67,v:0},{t:.92,v:1}]);const k=de(_,.67,2.42);h=k>0?-2.6*(1-Hu(k)):0,s=1-.05*(Math.sin(de(_,1.9,2.5)*Math.PI)+Math.sin(de(_,2.5,3.1)*Math.PI))}else if(t<74){let b=function(F){return[te(F,[{t:0,v:0},{t:.25,v:1},{t:.5,v:1},{t:.72,v:.14},{t:.82,v:.14},{t:1,v:0}]),te(F,[{t:0,v:0},{t:.08,v:-.62},{t:.25,v:-.62},{t:.33,v:.62},{t:.7,v:.62},{t:.82,v:-.62},{t:1,v:-.62}])]};var S=b;const _=t-60,k=1-de(_,12,14),T=b(de(_,0,12)),x=b(de(_-.5,0,12));n=T[0]*k,i=(T[1]+.05*Math.sin(_*7))*k,o=(x[0]-T[0])*.6*k,a=(x[1]-T[1])*.6*k,f=(x[0]-T[0])*30*k,E=de(_,0,.4)*k}else if(t<85.4){const _=t-74,b=te(_,[{t:0,v:0},{t:4,v:1},{t:8,v:.24},{t:9.6,v:1,e:Ve},{t:11.4,v:0}]);o=b*.5,d=-b*.5,l=te(_,[{t:0,v:0},{t:4,v:6},{t:8,v:20},{t:9.6,v:38,e:Ve},{t:11.4,v:0}]),f=-l*.7,a=te(_,[{t:0,v:0},{t:8,v:0},{t:9.6,v:.4},{t:11.4,v:0}])}else if(t<96.4){const _=t-85.4,b=de(_,0,5.6),k=de(_,5.6,7.6),T=.72*Math.min(1,_/.6)*(1-k);d=Math.cos(b*Math.PI*2)*T,h=Math.sin(b*Math.PI*2)*T*.55,f=b*360*(1-k);const x=te(_,[{t:0,v:0},{t:7.6,v:0},{t:8.2,v:1,e:Uo},{t:8.6,v:.55},{t:9.4,v:0}]);o=-.16*x,d+=.16*x,l=-6*x,f+=6*x,s=1+.05*x,m=1+.9*x}else if(t<108.6){const _=t-96.4,b=de(_,9.6,12.2);n=te(_,[{t:0,v:0},{t:2.1,v:1},{t:4.8,v:.08},{t:7.5,v:1},{t:9.6,v:0}])*(1-b),i=-.35*Math.abs(Math.sin(de(_,0,9.6)*Math.PI*3))*(1-b);const k=Math.sin(_*6.2)*(1-b);u=1+.12*k,p=1-.12*k,l=k*8,f=-k*8,o=.06*k,d=-.06*k,E=de(_,0,.4)*(1-b)}else{const _=t-108.6,b=Math.sin(de(_,0,8)*Math.PI),k=1-de(_,8,11.4);s=1+.04*b*k,i=-.1*b*k,r=2*b*k,m=1+.5*Math.sin(de(_,0,6)*Math.PI),v=1+.1*Math.sin(de(_,0,6)*Math.PI)}return e.x=n,e.y=i,e.rot=r,e.scale=s,e.ax=o,e.ay=a,e.ar=l,e.asc=u,e.afade=c,e.bx=d,e.by=h,e.br=f,e.bsc=p,e.bfade=g,e.hfade=m,e.hsc=v,e.shd=E,e}function sy(t={}){const e=t.arena||document.querySelector(".pipeline-glyph.logo-loop");if(!e)return null;const n=e.querySelector(".loop-mark"),i=e.querySelector(".loop-piece-a"),r=e.querySelector(".loop-piece-b"),s=e.querySelector(".loop-halo"),o=e.querySelector(".loop-shadow");if(!n||!i||!r||!s||!o)return null;const a=t.reducedMotion||window.matchMedia("(prefers-reduced-motion: reduce)"),l=ny;let u=34,c=0,d=0;function h(){u=n.offsetWidth||34,c=Math.max(0,e.offsetWidth-u-4),d=Math.max(0,(e.offsetHeight-u)/2-2),e.style.setProperty("--mark-c",u/2+"px")}function f(M){const R=Math.min(1,Math.max(0,M.x))*c,Z=M.y*d;n.style.transform="translate3d("+R.toFixed(2)+"px,"+Z.toFixed(2)+"px,0) rotate("+M.rot.toFixed(2)+"deg) scale("+M.scale.toFixed(3)+")",i.style.transform="translate3d("+(M.ax*u).toFixed(2)+"px,"+(M.ay*u).toFixed(2)+"px,0) rotate("+M.ar.toFixed(2)+"deg) scale("+M.asc.toFixed(3)+")",i.style.opacity=M.afade.toFixed(3),r.style.transform="translate3d("+(M.bx*u).toFixed(2)+"px,"+(M.by*u).toFixed(2)+"px,0) rotate("+M.br.toFixed(2)+"deg) scale("+M.bsc.toFixed(3)+")",r.style.opacity=M.bfade.toFixed(3),s.style.transform="scale("+M.hsc.toFixed(3)+")",s.style.opacity=(.09*M.hfade).toFixed(3),o.style.transform="translateX("+R.toFixed(2)+"px) scaleX("+(.75+.4*Math.abs(M.x)).toFixed(3)+")",o.style.opacity=(M.shd*.5).toFixed(3)}let p=0,g=0,m=0,v=!1,E=!1,S=!1,_=0;function b(){return S||a.matches||document.hidden||!e.offsetParent?!1:E}function k(M){if(!v)return;if(m=requestAnimationFrame(k),!b()){x();return}const R=g?(M-g)/1e3:0;g=M,p=(p+Math.min(R,.1))%l,_+=1,f(Ai(p))}function T(){v||S||b()&&(v=!0,g=0,m=requestAnimationFrame(k))}function x(){v=!1,m&&(cancelAnimationFrame(m),m=0),g=0}function F(){b()?T():x()}function $(){a.matches?(x(),f(Ai(0))):F()}function O(){h(),v&&f(Ai(p))}function L(){g=0,F()}const N=new IntersectionObserver(M=>{E=M[0]?M[0].isIntersecting:!1,F()},{threshold:0});N.observe(e),window.addEventListener("resize",O),a.addEventListener("change",$),document.addEventListener("visibilitychange",L);function K(){S||(S=!0,x(),N.disconnect(),window.removeEventListener("resize",O),a.removeEventListener("change",$),document.removeEventListener("visibilitychange",L))}window.addEventListener("pagehide",K);function V(M){p=(M%l+l)%l,f(Ai(p))}return h(),f(Ai(0)),F(),{isRunning:()=>v,currentTime:()=>p,frameCount:()=>_,seek:V,dispose:K}}const oy=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function Xt(t){const e=String(t||"").trim().match(oy);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function ay(t,e){if(t.length===0&&e.length===0)return 0;if(t.length===0)return 1;if(e.length===0)return-1;for(let n=0;n0)}function cy(t){const e=Xt(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function Il(t){let e=String(t??"").trim();if((e.startsWith("'")||e.startsWith('"'))&&(e=e.slice(1,-1).trim()),e===""||e==="any"||e==="*")return{min:null,minInclusive:!1,max:null,maxInclusive:!1};if(e.startsWith("^")){const o=e.slice(1).trim();return Xt(o)?{min:o,minInclusive:!0,max:cy(o),maxInclusive:!1}:null}if(Xt(e))return{min:e,minInclusive:!0,max:e,maxInclusive:!0};const n={min:null,minInclusive:!1,max:null,maxInclusive:!1},i=/(>=|<=|>|<)\s*([0-9][0-9A-Za-z.+-]*)/g;let r=!1,s;for(;(s=i.exec(e))!==null;){const[,o,a]=s;if(!Xt(a))return null;r=!0,o===">="||o===">"?(n.min=a,n.minInclusive=o===">="):(n.max=a,n.maxInclusive=o==="<=")}return r?n:null}function Wu(t,e){const n=Il(t);if(!n||!Xt(e))return!1;if(n.min!==null){const i=fs(e,n.min);if(i<0||i===0&&!n.minInclusive)return!1}if(n.max!==null){const i=fs(e,n.max);if(i>0||i===0&&!n.maxInclusive)return!1}return!0}function uy(t,e){const n=Il(t);if(!n||!Xt(e))return!1;if(n.max===null)return!0;const i=fs(n.max,e);return i>0?!0:i===0&&n.maxInclusive}function qn(t){const e=Il(t);return e?e.min:null}const dy="https://pub.dev/api/packages/",fy=8e3;function hy(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null}=e,r=Array.isArray(t?.versions)?t.versions:[];let s=null;for(const o of r){const a=o?.version;if(!a||o.retracted||ly(a))continue;const l=o.pubspec?.environment||{};n&&l.sdk&&!Wu(l.sdk,n)||i&&l.flutter&&!Wu(l.flutter,i)||(!s||fs(a,s)>0)&&(s=a)}return s?{version:s,constraint:`^${s}`}:null}async function py(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null,fetchImpl:r=fetch}=e;let s;try{const a=await r(`${dy}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(fy)});if(!a.ok)return{name:t,constraint:null,version:null,error:a.status===404?`"${t}" was not found on pub.dev`:`pub.dev returned ${a.status} for "${t}"`};s=await a.json()}catch(a){return{name:t,constraint:null,version:null,error:`could not reach pub.dev for "${t}" (${a.message})`}}const o=hy(s,{dartSdkFloor:n,flutterSdkFloor:i});return o?{name:t,...o,error:null}:{name:t,constraint:null,version:null,error:n?`no published "${t}" release supports Dart ${n}`:`no published "${t}" release could be read`}}async function gy(t,e={}){const n=await Promise.all(t.map(i=>py(i,e)));return new Map(n.map(({name:i,...r})=>[i,r]))}async function my(t,e={},n={}){const{resolveVersions:i=gy}=n,r=Object.entries(e).filter(([c])=>c&&c!=="flutter"),s=mh(t),o={dartSdkFloor:qn(s.sdk),flutterSdkFloor:qn(s.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(r.length===0)return a;const l=$s(t),u=[];for(const[c,d]of r){const h=l.get(c);if(!h){u.push(c);continue}const f=qn(d);if(!f){a.kept.push({name:c,constraint:h.constraint});continue}if(!h.isScalar){a.warnings.push(`"${c}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${f}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:c,constraint:h.constraint});continue}if(uy(h.constraint,f)){a.kept.push({name:c,constraint:h.constraint});continue}a.overrides[c]=`^${f}`,a.warnings.push(`"${c}" was pinned to ${h.constraint} in your project, which cannot resolve the ${f} the generated code needs. Raising it to ^${f} — this changes a dependency the rest of your app also uses.`)}if(u.length>0){const c=await i(u,o);for(const d of u){const h=c.get(d);if(h?.constraint){a.additions[d]=h.constraint;continue}const f=e[d]||"";if(qn(f)){a.additions[d]=`^${qn(f)}`,a.warnings.push(`Could not confirm "${d}" version on pub.dev (${h?.error||"lookup failed"}). Using ^${qn(f)} from the AI's recommendation — verify this is current.`);continue}a.additions[d]=">=0.0.0",a.warnings.push(`Could not determine a version for "${d}" (${h?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const vy={"&":"&","<":"<",">":">",'"':""","'":"'"};function Qt(t){return String(t??"").replace(/[&<>"']/g,e=>vy[e])}function z(t){return t?Qt(t).replace(/\n/g,"
    "):""}function Jt(t){return Qt(t).replace(/\r?\n/g," ")}function Ms(t,e={}){const n=t?.pipelineStep;if(n!=null&&e[n]!=null)return e[n];const i=t?.message||"";return i.includes("Code Generator")?2:i.includes("Code Review")?3:1}function Sh(t){if(!t)return{kind:"generic",title:"Generation failed",message:"An unknown error occurred. Please try again.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1};if(t.isModelArmor){const n=t.code==="MODEL_ARMOR_BLOCKED";return{kind:"safety",title:t.userTitle||"Request blocked for safety",message:t.userMessage||t.message,detail:t.retryExplanation||"",canRetry:!n,canEdit:!0,canUpgrade:!1}}if(t.isUsageLimit)return{kind:"quota",title:"Monthly limit reached",message:t.message||"You've used all your generations for this period.",detail:"",canRetry:!1,canEdit:!1,canUpgrade:!0};const e=t.message||"";return/timed out after/i.test(e)?{kind:"timeout",title:"Request timed out",message:"The generation service took too long to respond.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:/unreachable|failed to fetch|load failed|cors/i.test(e)?{kind:"network",title:"Connection problem",message:"We couldn't reach the generation service. Check your connection and try again.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:{kind:"generic",title:"Generation failed",message:e||"An unexpected error occurred.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1}}function _y(t){const e={"Integration Audit Report":"📋","Critical Issues":"❌",Warnings:"⚠️",Recommendations:"✅","Overall Score":"📊"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📄"}function yy(t){const e={critical:"❌",warning:"⚠️",recommendation:"✅",score:"📊",issue:"🔍",fix:"🔧"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📝"}function wy(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 li(t){if(!t)return"";if(typeof t!="string")return String(t);const e=/```(?:\w+)?\n?([\s\S]*?)```/,n=t.match(e);return n?n[1].trim():t.trim()}function zu(t){return t=Qt(t),t=t.replace(/\*\*(.*?)\*\*/g,'$1'),t=t.replace(/\*(.*?)\*/g,'$1'),t=t.replace(/`(.*?)`/g,'$1'),t=t.replace(/\b(FAIL|ERROR|CRITICAL)\b/g,'$1'),t=t.replace(/\b(WARN|WARNING)\b/g,'$1'),t=t.replace(/\b(PASS|SUCCESS|OK)\b/g,'$1'),t}function xh(t,e="dart",n=globalThis.hljs){if(!t)return"";const i=li(t);try{return n.highlight(i,{language:e}).value}catch(r){console.warn("Syntax highlighting failed:",r);try{return n.highlight(i,{language:"json"}).value}catch{return Qt(i)}}}function Ls(t,e={}){const{highlighter:n=globalThis.hljs}=e;let i='
    ';const r=String(t??"").split(` -`);let s=!1,o="";for(const a of r){if(a.startsWith("```")){if(s){const l=wy(o),u=xh(o.trim(),l,n);i+=`
    +`)}let l=null,u,c,d,f,h,p,g,m,v;function E(Y,W){if(!i)return null;const D=i.createShader(Y);return i.shaderSource(D,W),i.compileShader(D),i.getShaderParameter(D,i.COMPILE_STATUS)?D:(window.console&&console.warn("fx-grid shader: "+i.getShaderInfoLog(D)),null)}if(i){const Y=E(i.VERTEX_SHADER,o),W=E(i.FRAGMENT_SHADER,a());if(Y&&W&&(l=i.createProgram(),i.attachShader(l,Y),i.attachShader(l,W),i.linkProgram(l),i.getProgramParameter(l,i.LINK_STATUS)||(window.console&&console.warn("fx-grid link: "+i.getProgramInfoLog(l)),l=null)),l){i.useProgram(l),i.bindBuffer(i.ARRAY_BUFFER,i.createBuffer()),i.bufferData(i.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),i.STATIC_DRAW);const D=i.getAttribLocation(l,"p");i.enableVertexAttribArray(D),i.vertexAttribPointer(D,2,i.FLOAT,!1,0,0),u=i.getUniformLocation(l,"res"),c=i.getUniformLocation(l,"design"),d=i.getUniformLocation(l,"mouse"),f=i.getUniformLocation(l,"energy"),h=i.getUniformLocation(l,"parallax"),p=i.getUniformLocation(l,"t"),g=i.getUniformLocation(l,"ink"),m=i.getUniformLocation(l,"mark"),v=i.getUniformLocation(l,"rot"),i.enable(i.BLEND),i.blendFunc(i.ONE,i.ONE_MINUS_SRC_ALPHA),i.clearColor(0,0,0,0)}else{i=null;const D=t.cloneNode(!1);if(t.parentNode.replaceChild(D,t),t=D,r=t.getContext("2d"),!r)return null}}function S(Y){if(!Y)return null;const W=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(Y);if(W){let D=W[1];return D.length===3&&(D=D[0]+D[0]+D[1]+D[1]+D[2]+D[2]),[parseInt(D.slice(0,2),16)/255,parseInt(D.slice(2,4),16)/255,parseInt(D.slice(4,6),16)/255]}try{const D=document.createElement("canvas");D.width=1,D.height=1;const ue=D.getContext("2d");ue.fillStyle="rgb(9, 8, 7)";const xe=String(ue.fillStyle);ue.fillStyle=Y;const Fe=String(ue.fillStyle);if(Fe===xe)return null;const dt=/^#([0-9a-f]{6})$/i.exec(Fe);if(dt){const ft=dt[1];return[parseInt(ft.slice(0,2),16)/255,parseInt(ft.slice(2,4),16)/255,parseInt(ft.slice(4,6),16)/255]}const Nt=/rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i.exec(Fe);if(Nt)return[Number(Nt[1])/255,Number(Nt[2])/255,Number(Nt[3])/255]}catch{}return null}function _(){let Y="";try{const W=getComputedStyle(document.documentElement);Y=(W.getPropertyValue("--fx-ink")||"").trim()||(W.getPropertyValue("--fg")||"").trim()}catch{}return S(Y)||[.56,.68,.88]}const b=_();let k=1920,T=1080,x=960,F=540,$=960,O=540,L=.66,N=0,K=-1e9,V=!1,M=0,R=0,Z=null,Ce=!1,oe=!1,ye=!1;const $e=64,ae=15.2;let Ie=0,Se=0;const De=.0032,wt=0,ge=.56,Je=.26,bt=.32,mn=.16,Re=.349;let Pe=wt;function $t(){const Y=t.getBoundingClientRect(),W=t.clientWidth,D=t.clientHeight;if(!Y.width||!W||!D)return;const ue=Math.min(window.devicePixelRatio||1,2),xe=Math.max(.2,Math.min(2,Y.width/W*ue)),Fe=Math.max(2,Math.round(W*xe)),dt=Math.max(2,Math.round(D*xe));(Fe!==t.width||dt!==t.height)&&(t.width=Fe,t.height=dt,i&&i.viewport(0,0,Fe,dt)),k=W,T=D,V||(x=$=k/2,F=O=T/2,V=!0)}function Bn(Y){!l||!Ce||!i||(i.uniform2f(u,t.width,t.height),i.uniform2f(c,k,T),i.uniform2f(d,x,F),i.uniform1f(f,L),i.uniform1f(h,N),i.uniform2f(v,Math.cos(Pe),Math.sin(Pe)),i.uniform1f(p,Y),i.uniform3f(g,b[0],b[1],b[2]),i.clear(i.COLOR_BUFFER_BIT),i.drawArrays(i.TRIANGLES,0,3))}function qe(Y,W,D){const ue=Math.max(0,Math.min(1,(D-Y)/(W-Y)));return ue*ue*(3-2*ue)}function Dn(Y){if(!Z||!r)return;const W=r;W.setTransform(1,0,0,1,0,0),W.clearRect(0,0,t.width,t.height);const D=t.width/k;W.setTransform(D,0,0,D,0,0),W.globalAlpha=1;const ue=Math.min(k,T),xe=Math.max(64,Math.min(118,ue/10)),Fe=xe*2.9,dt=2*Fe*Fe,Nt=Math.sin(Y*.11)*7,ft=Math.cos(Y*.09)*7-N,dr=x+Nt,fr=F+ft,io=Fe*Math.sqrt(2*Math.log(1/.06)),mi=io+De*io*io+xe,Pp=Math.floor((dr-mi)/xe)-1,Fp=Math.ceil((dr+mi)/xe)+1,Rp=Math.floor((fr-mi)/xe)-1,Tp=Math.ceil((fr+mi)/xe)+1;for(let ro=Rp;ro<=Tp;ro++){const $p=(ro+.5)*xe;for(let so=Pp;so<=Fp;so++){const oo=(so+.5)*xe-dr,ao=$p-fr,lo=Math.sqrt(oo*oo+ao*ao)+1e-5;if(lo>mi)continue;const hr=(-1+Math.sqrt(1+4*De*lo))/(2*De),lc=Math.exp(-(hr*hr)/dt),cc=qe(.06,.8,lc)*L*.26;if(cc<.004)continue;const on=xe/(1+2*De*hr)*.26*(.32+1.1*lc),uc=hr/lo,co=dr+oo*uc,uo=fr+ao*uc;co<-on*1.6||co>k+on*1.6||uo<-on*1.6||uo>T+on*1.6||(W.globalAlpha=cc,W.save(),W.translate(co,uo),W.rotate(Pe),W.drawImage(Z,-on,-on,on*2,on*2),W.restore())}}W.globalAlpha=1}function Mt(Y){if(!oe)return;const W=R?Math.min(.05,(Y-R)/1e3):.016;R=Y;const ue=Y-K>2400?.6:1;L+=(ue-L)*Math.min(1,W*3.2);const xe=Math.min(.05,W);Ie+=(($-x)*$e-Ie*ae)*xe,Se+=((O-F)*$e-Se*ae)*xe,x+=Ie*xe,F+=Se*xe,N=(window.scrollY||window.pageYOffset||0)*.55;const Fe=Y/1e3,dt=x/(k||1)-.5,Nt=F/(T||1)-.5;let ft=dt*(dt>=0?ge:Je)+Nt*(Nt>=0?bt:mn);ft>Re?ft=Re:ft<-Re&&(ft=-Re),Pe=wt+ft-N*6e-4,$t(),i?Bn(Fe):Dn(Fe),M=requestAnimationFrame(Mt)}function Lt(Y){if(!oe)return;const W=t.getBoundingClientRect();!W.width||!k||!T||($=(Y.clientX-W.left)/W.width*k,O=(Y.clientY-W.top)/W.height*T,K=performance.now())}function ut(){oe||no||e.matches||n.matches||!ye||document.hidden||(oe=!0,R=0,M=requestAnimationFrame(Mt))}function sn(){oe=!1,M&&(cancelAnimationFrame(M),M=0),R=0}function gi(){e.matches?(sn(),t.classList.remove("is-ready")):ye&&ut()}function jn(){n.matches?sn():ye&&ut()}function sc(){document.hidden?sn():ye&&ut()}const oc=new IntersectionObserver(Y=>{ye=Y[0]?.isIntersecting||!1,ye?ut():sn()},{threshold:0});oc.observe(t),window.addEventListener("pointermove",Lt,{passive:!0,capture:!0}),window.addEventListener("resize",$t),e.addEventListener("change",gi),n.addEventListener("change",jn),document.addEventListener("visibilitychange",sc);function Ap(){const Y=(s.match(/\sd="([^"]+)"/)||[])[1],W=document.createElement("canvas");W.width=256,W.height=256;const D=W.getContext("2d");if(Y&&window.Path2D){const ue=Math.min(8.533333333333333,8.421052631578947);D.setTransform(ue,0,0,ue,ue+(256-30*ue)/2,-6.4*ue),D.fillStyle="rgb(255,255,255)",D.fill(new Path2D(Y),"evenodd"),D.setTransform(1,0,0,1,0,0)}try{const ue=D.getImageData(0,0,256,256),xe=ue.data;for(let Fe=3;Feoe}}const iy=120;function ry(t,e,n){return tn?n:t}function de(t,e,n){return ry((t-e)/(n-e),0,1)}function sy(t){return t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2}function Ho(t){return 1-Math.pow(1-t,3)}function Ve(t,e){return e=e===void 0?1.7:e,1+(e+1)*Math.pow(t-1,3)+e*Math.pow(t-1,2)}function Wu(t){return 1-Math.pow(2,-9*t)*Math.cos(t*15)}function te(t,e){if(t<=e[0].t)return e[0].v;for(let n=1;n8.2&&_<9.4&&(s*=1-.07*Math.sin(de(_,8.2,9.4)*Math.PI))}else if(t<53){const _=t-42;g=te(_,[{t:0,v:1},{t:2,v:0},{t:4.2,v:0},{t:4.6,v:1},{t:6.8,v:1},{t:7.4,v:0},{t:9.4,v:0},{t:10.6,v:1}]),p=te(_,[{t:0,v:1},{t:2,v:.3},{t:4.6,v:1,e:Ve}]),d=te(_,[{t:0,v:0},{t:2,v:.3},{t:4.6,v:.16,e:Ve},{t:10.6,v:0}]),h=te(_,[{t:0,v:0},{t:2,v:-40},{t:4.6,v:0,e:Ve}]),o=te(_,[{t:0,v:0},{t:4.6,v:-.12},{t:10.6,v:0}])}else if(t<60){const _=t-53;c=te(_,[{t:0,v:1},{t:.35,v:0},{t:.45,v:0},{t:.7,v:1}]);const b=de(_,.45,2.2);a=b>0?-2.6*(1-Wu(b)):0,g=te(_,[{t:0,v:1},{t:.57,v:0},{t:.67,v:0},{t:.92,v:1}]);const k=de(_,.67,2.42);f=k>0?-2.6*(1-Wu(k)):0,s=1-.05*(Math.sin(de(_,1.9,2.5)*Math.PI)+Math.sin(de(_,2.5,3.1)*Math.PI))}else if(t<74){let b=function(F){return[te(F,[{t:0,v:0},{t:.25,v:1},{t:.5,v:1},{t:.72,v:.14},{t:.82,v:.14},{t:1,v:0}]),te(F,[{t:0,v:0},{t:.08,v:-.62},{t:.25,v:-.62},{t:.33,v:.62},{t:.7,v:.62},{t:.82,v:-.62},{t:1,v:-.62}])]};var S=b;const _=t-60,k=1-de(_,12,14),T=b(de(_,0,12)),x=b(de(_-.5,0,12));n=T[0]*k,i=(T[1]+.05*Math.sin(_*7))*k,o=(x[0]-T[0])*.6*k,a=(x[1]-T[1])*.6*k,h=(x[0]-T[0])*30*k,E=de(_,0,.4)*k}else if(t<85.4){const _=t-74,b=te(_,[{t:0,v:0},{t:4,v:1},{t:8,v:.24},{t:9.6,v:1,e:Ve},{t:11.4,v:0}]);o=b*.5,d=-b*.5,l=te(_,[{t:0,v:0},{t:4,v:6},{t:8,v:20},{t:9.6,v:38,e:Ve},{t:11.4,v:0}]),h=-l*.7,a=te(_,[{t:0,v:0},{t:8,v:0},{t:9.6,v:.4},{t:11.4,v:0}])}else if(t<96.4){const _=t-85.4,b=de(_,0,5.6),k=de(_,5.6,7.6),T=.72*Math.min(1,_/.6)*(1-k);d=Math.cos(b*Math.PI*2)*T,f=Math.sin(b*Math.PI*2)*T*.55,h=b*360*(1-k);const x=te(_,[{t:0,v:0},{t:7.6,v:0},{t:8.2,v:1,e:Ho},{t:8.6,v:.55},{t:9.4,v:0}]);o=-.16*x,d+=.16*x,l=-6*x,h+=6*x,s=1+.05*x,m=1+.9*x}else if(t<108.6){const _=t-96.4,b=de(_,9.6,12.2);n=te(_,[{t:0,v:0},{t:2.1,v:1},{t:4.8,v:.08},{t:7.5,v:1},{t:9.6,v:0}])*(1-b),i=-.35*Math.abs(Math.sin(de(_,0,9.6)*Math.PI*3))*(1-b);const k=Math.sin(_*6.2)*(1-b);u=1+.12*k,p=1-.12*k,l=k*8,h=-k*8,o=.06*k,d=-.06*k,E=de(_,0,.4)*(1-b)}else{const _=t-108.6,b=Math.sin(de(_,0,8)*Math.PI),k=1-de(_,8,11.4);s=1+.04*b*k,i=-.1*b*k,r=2*b*k,m=1+.5*Math.sin(de(_,0,6)*Math.PI),v=1+.1*Math.sin(de(_,0,6)*Math.PI)}return e.x=n,e.y=i,e.rot=r,e.scale=s,e.ax=o,e.ay=a,e.ar=l,e.asc=u,e.afade=c,e.bx=d,e.by=f,e.br=h,e.bsc=p,e.bfade=g,e.hfade=m,e.hsc=v,e.shd=E,e}function oy(t={}){const e=t.arena||document.querySelector(".pipeline-glyph.logo-loop");if(!e)return null;const n=e.querySelector(".loop-mark"),i=e.querySelector(".loop-piece-a"),r=e.querySelector(".loop-piece-b"),s=e.querySelector(".loop-halo"),o=e.querySelector(".loop-shadow");if(!n||!i||!r||!s||!o)return null;const a=t.reducedMotion||window.matchMedia("(prefers-reduced-motion: reduce)"),l=iy;let u=34,c=0,d=0;function f(){u=n.offsetWidth||34,c=Math.max(0,e.offsetWidth-u-4),d=Math.max(0,(e.offsetHeight-u)/2-2),e.style.setProperty("--mark-c",u/2+"px")}function h(M){const R=Math.min(1,Math.max(0,M.x))*c,Z=M.y*d;n.style.transform="translate3d("+R.toFixed(2)+"px,"+Z.toFixed(2)+"px,0) rotate("+M.rot.toFixed(2)+"deg) scale("+M.scale.toFixed(3)+")",i.style.transform="translate3d("+(M.ax*u).toFixed(2)+"px,"+(M.ay*u).toFixed(2)+"px,0) rotate("+M.ar.toFixed(2)+"deg) scale("+M.asc.toFixed(3)+")",i.style.opacity=M.afade.toFixed(3),r.style.transform="translate3d("+(M.bx*u).toFixed(2)+"px,"+(M.by*u).toFixed(2)+"px,0) rotate("+M.br.toFixed(2)+"deg) scale("+M.bsc.toFixed(3)+")",r.style.opacity=M.bfade.toFixed(3),s.style.transform="scale("+M.hsc.toFixed(3)+")",s.style.opacity=(.09*M.hfade).toFixed(3),o.style.transform="translateX("+R.toFixed(2)+"px) scaleX("+(.75+.4*Math.abs(M.x)).toFixed(3)+")",o.style.opacity=(M.shd*.5).toFixed(3)}let p=0,g=0,m=0,v=!1,E=!1,S=!1,_=0;function b(){return S||a.matches||document.hidden||!e.offsetParent?!1:E}function k(M){if(!v)return;if(m=requestAnimationFrame(k),!b()){x();return}const R=g?(M-g)/1e3:0;g=M,p=(p+Math.min(R,.1))%l,_+=1,h(Ai(p))}function T(){v||S||b()&&(v=!0,g=0,m=requestAnimationFrame(k))}function x(){v=!1,m&&(cancelAnimationFrame(m),m=0),g=0}function F(){b()?T():x()}function $(){a.matches?(x(),h(Ai(0))):F()}function O(){f(),v&&h(Ai(p))}function L(){g=0,F()}const N=new IntersectionObserver(M=>{E=M[0]?M[0].isIntersecting:!1,F()},{threshold:0});N.observe(e),window.addEventListener("resize",O),a.addEventListener("change",$),document.addEventListener("visibilitychange",L);function K(){S||(S=!0,x(),N.disconnect(),window.removeEventListener("resize",O),a.removeEventListener("change",$),document.removeEventListener("visibilitychange",L))}window.addEventListener("pagehide",K);function V(M){p=(M%l+l)%l,h(Ai(p))}return f(),h(Ai(0)),F(),{isRunning:()=>v,currentTime:()=>p,frameCount:()=>_,seek:V,dispose:K}}const ay=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function Xt(t){const e=String(t||"").trim().match(ay);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function ly(t,e){if(t.length===0&&e.length===0)return 0;if(t.length===0)return 1;if(e.length===0)return-1;for(let n=0;n0)}function uy(t){const e=Xt(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function kl(t){let e=String(t??"").trim();if((e.startsWith("'")||e.startsWith('"'))&&(e=e.slice(1,-1).trim()),e===""||e==="any"||e==="*")return{min:null,minInclusive:!1,max:null,maxInclusive:!1};if(e.startsWith("^")){const o=e.slice(1).trim();return Xt(o)?{min:o,minInclusive:!0,max:uy(o),maxInclusive:!1}:null}if(Xt(e))return{min:e,minInclusive:!0,max:e,maxInclusive:!0};const n={min:null,minInclusive:!1,max:null,maxInclusive:!1},i=/(>=|<=|>|<)\s*([0-9][0-9A-Za-z.+-]*)/g;let r=!1,s;for(;(s=i.exec(e))!==null;){const[,o,a]=s;if(!Xt(a))return null;r=!0,o===">="||o===">"?(n.min=a,n.minInclusive=o===">="):(n.max=a,n.maxInclusive=o==="<=")}return r?n:null}function zu(t,e){const n=kl(t);if(!n||!Xt(e))return!1;if(n.min!==null){const i=fs(e,n.min);if(i<0||i===0&&!n.minInclusive)return!1}if(n.max!==null){const i=fs(e,n.max);if(i>0||i===0&&!n.maxInclusive)return!1}return!0}function dy(t,e){const n=kl(t);if(!n||!Xt(e))return!1;if(n.max===null)return!0;const i=fs(n.max,e);return i>0?!0:i===0&&n.maxInclusive}function qn(t){const e=kl(t);return e?e.min:null}const fy="https://pub.dev/api/packages/",hy=8e3;function py(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null}=e,r=Array.isArray(t?.versions)?t.versions:[];let s=null;for(const o of r){const a=o?.version;if(!a||o.retracted||cy(a))continue;const l=o.pubspec?.environment||{};n&&l.sdk&&!zu(l.sdk,n)||i&&l.flutter&&!zu(l.flutter,i)||(!s||fs(a,s)>0)&&(s=a)}return s?{version:s,constraint:`^${s}`}:null}async function gy(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null,fetchImpl:r=fetch}=e;let s;try{const a=await r(`${fy}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(hy)});if(!a.ok)return{name:t,constraint:null,version:null,error:a.status===404?`"${t}" was not found on pub.dev`:`pub.dev returned ${a.status} for "${t}"`};s=await a.json()}catch(a){return{name:t,constraint:null,version:null,error:`could not reach pub.dev for "${t}" (${a.message})`}}const o=py(s,{dartSdkFloor:n,flutterSdkFloor:i});return o?{name:t,...o,error:null}:{name:t,constraint:null,version:null,error:n?`no published "${t}" release supports Dart ${n}`:`no published "${t}" release could be read`}}async function my(t,e={}){const n=await Promise.all(t.map(i=>gy(i,e)));return new Map(n.map(({name:i,...r})=>[i,r]))}async function vy(t,e={},n={}){const{resolveVersions:i=my}=n,r=Object.entries(e).filter(([c])=>c&&c!=="flutter"),s=vh(t),o={dartSdkFloor:qn(s.sdk),flutterSdkFloor:qn(s.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(r.length===0)return a;const l=Ms(t),u=[];for(const[c,d]of r){const f=l.get(c);if(!f){u.push(c);continue}const h=qn(d);if(!h){a.kept.push({name:c,constraint:f.constraint});continue}if(!f.isScalar){a.warnings.push(`"${c}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${h}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:c,constraint:f.constraint});continue}if(dy(f.constraint,h)){a.kept.push({name:c,constraint:f.constraint});continue}a.overrides[c]=`^${h}`,a.warnings.push(`"${c}" was pinned to ${f.constraint} in your project, which cannot resolve the ${h} the generated code needs. Raising it to ^${h} — this changes a dependency the rest of your app also uses.`)}if(u.length>0){const c=await i(u,o);for(const d of u){const f=c.get(d);if(f?.constraint){a.additions[d]=f.constraint;continue}const h=e[d]||"";if(qn(h)){a.additions[d]=`^${qn(h)}`,a.warnings.push(`Could not confirm "${d}" version on pub.dev (${f?.error||"lookup failed"}). Using ^${qn(h)} from the AI's recommendation — verify this is current.`);continue}a.additions[d]=">=0.0.0",a.warnings.push(`Could not determine a version for "${d}" (${f?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const _y={"&":"&","<":"<",">":">",'"':""","'":"'"};function Qt(t){return String(t??"").replace(/[&<>"']/g,e=>_y[e])}function z(t){return t?Qt(t).replace(/\n/g,"
    "):""}function Jt(t){return Qt(t).replace(/\r?\n/g," ")}function Ls(t,e={}){const n=t?.pipelineStep;if(n!=null&&e[n]!=null)return e[n];const i=t?.message||"";return i.includes("Code Generator")?2:i.includes("Code Review")?3:1}function xh(t){if(!t)return{kind:"generic",title:"Generation failed",message:"An unknown error occurred. Please try again.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1};if(t.isModelArmor){const n=t.code==="MODEL_ARMOR_BLOCKED";return{kind:"safety",title:t.userTitle||"Request blocked for safety",message:t.userMessage||t.message,detail:t.retryExplanation||"",canRetry:!n,canEdit:!0,canUpgrade:!1}}if(t.isUsageLimit)return{kind:"quota",title:"Monthly limit reached",message:t.message||"You've used all your generations for this period.",detail:"",canRetry:!1,canEdit:!1,canUpgrade:!0};const e=t.message||"";return/timed out after/i.test(e)?{kind:"timeout",title:"Request timed out",message:"The generation service took too long to respond.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:/unreachable|failed to fetch|load failed|cors/i.test(e)?{kind:"network",title:"Connection problem",message:"We couldn't reach the generation service. Check your connection and try again.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:{kind:"generic",title:"Generation failed",message:e||"An unexpected error occurred.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1}}function yy(t){const e={"Integration Audit Report":"📋","Critical Issues":"❌",Warnings:"⚠️",Recommendations:"✅","Overall Score":"📊"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📄"}function wy(t){const e={critical:"❌",warning:"⚠️",recommendation:"✅",score:"📊",issue:"🔍",fix:"🔧"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📝"}function by(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 li(t){if(!t)return"";if(typeof t!="string")return String(t);const e=/```(?:\w+)?\n?([\s\S]*?)```/,n=t.match(e);return n?n[1].trim():t.trim()}function qu(t){return t=Qt(t),t=t.replace(/\*\*(.*?)\*\*/g,'$1'),t=t.replace(/\*(.*?)\*/g,'$1'),t=t.replace(/`(.*?)`/g,'$1'),t=t.replace(/\b(FAIL|ERROR|CRITICAL)\b/g,'$1'),t=t.replace(/\b(WARN|WARNING)\b/g,'$1'),t=t.replace(/\b(PASS|SUCCESS|OK)\b/g,'$1'),t}function Ih(t,e="dart",n=globalThis.hljs){if(!t)return"";const i=li(t);try{return n.highlight(i,{language:e}).value}catch(r){console.warn("Syntax highlighting failed:",r);try{return n.highlight(i,{language:"json"}).value}catch{return Qt(i)}}}function Ns(t,e={}){const{highlighter:n=globalThis.hljs}=e;let i='
    ';const r=String(t??"").split(` +`);let s=!1,o="";for(const a of r){if(a.startsWith("```")){if(s){const l=by(o),u=Ih(o.trim(),l,n);i+=`
    ${u}
    `,o="",s=!1}else s=!0;continue}if(s){o+=a+` `;continue}if(a.startsWith("# ")){const l=a.substring(2).trim();i+=`

    - ${_y(l)} + ${yy(l)} ${Qt(l)}

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

    - ${yy(l)} + ${wy(l)} ${Qt(l)}

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

    ${zu(a)}

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

    ${qu(a)}

    `)}return i+="
    ",`
    @@ -78,14 +78,14 @@ in vec2 p; void main(){ gl_Position = vec4(p, 0.0, 1.0); }`;function a(){return[
    ${i}
    - `}const by=[[/gradient stroke\s*$/i," and an animated percentage label"],[/gauge\s*$/i," with a gradient stroke and animated fill"],[/rating\s*(bar|widget)?\s*$/i," with half-star support and haptic feedback"],[/list\s*$/i," with swipe-to-delete and an undo snackbar"],[/pad\s*$/i," that exports a transparent PNG"],[/carousel\s*$/i," with parallax cards and page indicators"],[/(button|cta)\s*$/i," with a loading spinner and success state"],[/(chart|graph)\s*$/i," that animates from a Firestore stream"],[/action\s*(that|to)?\s*$/i," uploads an image to Firebase Storage and returns the URL"],[/timer\s*$/i," with pause, resume and a completion callback"],[/map\s*$/i," with clustered markers and a custom info window"],[/^a\s+\w*$/i," widget that"],[/(picker|selector)\s*$/i," with search and multi-select"]],Ey=220,Sy=6;function qu(t,e){return!!(t&&t.trim())&&!e}function xy(t,e=""){if(typeof t!="string"||!t||t===e||t.trim().lengthi.test(t));return n?n[1]:null}function Iy(){let t="",e="";return{get active(){return t},resolve(n){return t=xy(n,e)??"",t},dismiss(){t=""},accept(n){if(!t)return null;const i=n+t;return e=i,t="",i}}}function ky({onSubmit:t}){const e=document.getElementById("composer"),n=document.getElementById("pipeline-input"),i=document.getElementById("hero-send");if(!e||!n||!i||typeof t!="function")return;const r=e.querySelector(".ghost .typed"),s=e.querySelector(".ghost .suggest"),o=document.getElementById("tab-hint"),a=document.getElementById("suggest-status"),l=Array.from(document.querySelectorAll("#example-chips .chip")),u=document.getElementById("btn-add-images"),c=document.getElementById("prompt-image-input"),d=window.matchMedia("(prefers-reduced-motion: reduce)"),h=Iy();let f=!1,p=!1,g=!1,m=!1,v=null,E=null;function S(){i.disabled=!qu(n.value,p||g||m)}function _(){r&&(r.textContent=n.value)}function b(){s&&(s.textContent=""),_(),e.classList.remove("has-suggest"),o&&(o.hidden=!0,o.tabIndex=-1),a&&(a.textContent="")}function k(R){s&&(s.textContent=R),_(),e.classList.add("has-suggest"),o&&(o.hidden=!1,o.tabIndex=0,o.setAttribute("aria-label","Accept suggestion: "+R.trim())),a&&(a.textContent="Suggestion: "+R+". Press Tab to accept.")}function T(){h.dismiss(),b()}function x(){if(f||p)return;const R=h.resolve(n.value);R&&k(R)}function F(){clearTimeout(v),!f&&(v=setTimeout(x,Ey))}function $(){const R=h.accept(n.value);return R===null?!1:(n.value=R,b(),S(),!0)}function O(R){p=R,e.classList.toggle("is-busy",R),i.classList.toggle("is-busy",R),i.setAttribute("aria-label",R?"Generating":"Generate"),n.readOnly=R,l.forEach(Z=>{Z.disabled=R}),u&&(u.disabled=R),c&&(c.disabled=R),S()}async function L(){if(qu(n.value,p||g||m)){T(),O(!0);try{await t()}finally{O(!1)}}}function N(){g=!1,E&&(clearInterval(E),E=null),e.classList.remove("is-demo-typing"),S()}function K(){l.forEach(R=>{R.classList.remove("is-active"),R.setAttribute("aria-pressed","false")})}function V(){try{n.focus({preventScroll:!0}),n.setSelectionRange(n.value.length,n.value.length)}catch{}}function M(R){const Z=R.dataset.prompt||"";if(N(),clearTimeout(v),v=null,T(),l.forEach(oe=>{const ye=oe===R;oe.classList.toggle("is-active",ye),oe.setAttribute("aria-pressed",String(ye))}),d.matches||!Z){n.value=Z,_(),S(),V();return}n.value="",_(),g=!0,S(),e.classList.add("is-demo-typing");let Ce=0;E=setInterval(()=>{Ce+=1,n.value=Z.slice(0,Ce),_(),Ce>=Z.length?(N(),V()):S()},22)}return l.forEach(R=>{R.setAttribute("aria-pressed","false"),R.addEventListener("click",()=>M(R))}),n.addEventListener("keydown",R=>{if(g&&R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!f){R.preventDefault();return}N(),R.key==="Tab"&&!R.shiftKey&&h.active?(R.preventDefault(),$()):R.key==="Escape"?(clearTimeout(v),v=null,T()):R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!f&&(R.preventDefault(),L())}),n.addEventListener("input",()=>{N(),K(),T(),S(),F()}),n.addEventListener("compositionstart",()=>{f=!0}),n.addEventListener("compositionend",()=>{f=!1,T(),S(),F()}),n.addEventListener("scroll",()=>{r&&r.parentNode&&(r.parentNode.scrollTop=n.scrollTop)}),o&&o.addEventListener("click",()=>{$(),n.focus({preventScroll:!0})}),i.addEventListener("click",L),n.addEventListener("pointerdown",()=>{N(),K()}),_(),S(),{setAttachmentsPending(R){m=!!R,S()}}}const Cy="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses";const _t="https://4tgke4.buildship.run",Ih={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},hs="ccc_auth_session",Na="ccc_signin_return",Ay=1800*1e3,Vu=new WeakSet;let q={email:null,sessionToken:null,isVerified:!1};function Mn(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let ce=Mn({isResolved:!0}),Oa=Promise.resolve();const Py=`${_t}/service/runpipeline`,Fy="bs_user_id",Ry="bs_identity_token",Ty=`${_t}/authUserCheck`;let ht={userId:null,token:null,status:null,resolved:!1};const ps=cv,gs="ccc_subscription",Gu=3,$y=new Set(["active","trialing","paid"]),ms="google/gemini-3.7-flash",Nr=["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"],My={"google/gemini-3.7-flash":"Gemini 3.7 Flash","anthropic/claude-opus-5":"Claude Opus 5","openai/gpt-5.6-sol":"GPT-5.6 Sol","z-ai/glm-5.2":"GLM 5.2","moonshotai/kimi-k3":"Kimi K3","openrouter/auto-beta":"OpenRouter: Auto Router","openrouter/free":"OpenRouter: Free Models","openrouter/deepseek/deepseek-v4-pro":"DeepSeek v4 Pro"};function Gt(t){return My[t]||t}const Ly=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 kh(t){return Ly.has(t)}const Ba=4,Ho=8*1024*1024,Ny="https://4tgke4.buildship.run/service/runpipeline-image";let Oe=[];const pn=[],Oy=3e4;let Ch=null;function By(t){return new Promise(e=>{const n=new FileReader;n.onload=()=>e(n.result),n.onerror=()=>e(null),n.readAsDataURL(t)})}async function Dy(t,e){const n=new FormData;return n.append("file",t),(await fetch(Ny,{method:"POST",body:n,signal:e})).json()}function jy(t){if(Array.isArray(t)){const e=t[0];if(e&&typeof e=="object")for(const n of Object.keys(e)){if(n==="item"||n==="index")continue;const i=e[n];if(i&&typeof i=="object"){if(typeof i.file=="string")return i.file;if(typeof i.url=="string")return i.url}if(typeof i=="string")return i}return""}return typeof t=="string"?t:t&&typeof t=="object"&&(t.url||t.fileUrl||t.file_url||t.downloadUrl||t.imageUrl||t.image_url||t.file)||""}async function Uy(t,e,n){const i=await By(t);i&&Oe.includes(e)&&(e.dataUrl=i,cn());let r="";if(i)try{r=jy(await Dy(t,n))}catch{r=""}return Oe.includes(e)?!i||!r?(Oe.splice(Oe.indexOf(e),1),cn(),"failed"):(e.url=r,cn(),"added"):"dropped"}function Ah(t){const e=pn.indexOf(t);e>=0&&pn.splice(e,1),Fh()}function Ph(t){t.controller.abort(),Ah(t);const e=Oe.indexOf(t.slot);e>=0&&(Oe.splice(e,1),cn())}function Fh(){Ch?.setAttachmentsPending(pn.length>0)}async function Hy(t){const e=Array.from(t.target.files||[]);if(!e.length)return;if(t.target.value="",y.isRunning){Ee("Wait for the current generation to finish before attaching images.","info");return}const n=e.filter(u=>u.size>Ho);n.length&&Ee(`Skipped ${n.length} image(s) over the ${(Ho/1024/1024).toFixed(0)} MB limit.`,"warning");const i=e.filter(u=>u.size<=Ho);if(!i.length)return;const r=Ba-Oe.length,s=i.slice(0,r);if(i.length>r&&Ee(`You can attach up to ${Ba} images.`,"info"),!s.length)return;const o=s.map(u=>{const c={dataUrl:null,name:u.name,url:null};Oe.push(c);const d={slot:c,controller:new AbortController},h=setTimeout(()=>d.controller.abort(),Oy);return d.job=Uy(u,c,d.controller.signal),pn.push(d),d.job.finally(()=>{clearTimeout(h),Ah(d)}),d.job});cn(),Fh();const l=(await Promise.all(o)).filter(u=>u==="failed").length;l&&Ee(`${l} image(s) could not be uploaded and were not attached.`,"error")}function Wy(t){const e=Oe[t],n=pn.find(i=>i.slot===e);if(n){Ph(n);return}Oe.splice(t,1),cn()}function cn(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",Oe.forEach((n,i)=>{const r=document.createElement("div");r.className="prompt-img-thumb"+(n.url?"":" is-pending"),r.innerHTML=(n.dataUrl?`Prompt image`:"")+``,t.appendChild(r)}),e&&(e.textContent=Oe.length>=Ba?"Image limit reached":"Add images"))}function kl(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),n=kh(e?.value);t.classList.toggle("hidden",!n),!n&&Oe.length&&(pn.slice().forEach(Ph),Oe=[],cn())}const Fn="ccc_usage",Rh="google/gemini-3.7-flash",Th="google/gemini-3.7-flash",kr="google/gemini-3.7-flash",Ni={professional:11,power:49},Da={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"},Or={AUD:1,USD:.65,EUR:.6,GBP:.52,CAD:.88,NZD:1.08,JPY:97,KRW:870,INR:54,SGD:.87,HKD:5.08,BRL:3.18,CNY:4.7,TWD:20.5,THB:22.5,VND:16200,IDR:10200,MYR:2.88,SEK:6.8,NOK:6.95,DKK:4.48,PLN:2.6,CZK:15.2,HUF:238,RON:2.98,TRY:20.9,AED:2.39,ILS:2.38,PHP:36.4,ZAR:11.8,RUB:58,UAH:26.8,CHF:.57,MXN:11.1,ARS:580,CLP:610,COP:2700,PEN:2.44};let Br={...Or};async function zy(){const t=new AbortController,e=setTimeout(()=>t.abort(),5e3);try{const n=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:t.signal});if(!n.ok)return;const i=await n.json();if(i.result!=="success"||!i.rates)return;const r=i.rates,s={AUD:1},o=new Set([...Object.keys(Or),...Object.values(ja),...Object.values(Da)]);for(const a of o)a!=="AUD"&&(typeof r[a]=="number"&&r[a]>0?s[a]=r[a]:Or[a]&&(s[a]=Or[a]));Br=s}catch{}finally{clearTimeout(e)}}const ja={"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 Cl(){try{const s=Intl.DateTimeFormat().resolvedOptions().timeZone;if(s&&ja[s])return ja[s]}catch{}const e=(navigator.language||"en-US").replace("-","_"),n=Da[e];if(n)return n;const i=e.split("_")[0],r=Da[i];return r||"USD"}function Oi(t,e){const n=Br[e]??Br.USD,i=t*n,r=Math.round(i*100)/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:r>=100||r%1===0?0:2}).format(r)}catch{return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(t*Br.USD)}}const gt="ccc_api_key_",Pt="ccc_session_api_key_",Rt="ccc_encryption_key",tr="ccc_encryption_key_scope",qy="ccc_keystore",vs="keys",nr="ccc_encryption_key_version";let Ua=null,_s=null,ir=!1,ys=!1,Ku=!1;class ws extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function Yu(){if(Ku)return;Ku=!0;const t="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(t),document.body&&Ee(t,"warning")}function $h(){return localStorage.getItem(nr)||""}function Ha(){return crypto.randomUUID?.()||Lh(crypto.getRandomValues(new Uint8Array(16)))}function Vy(){const t=$h();if(t)return t;const e=Ha();return localStorage.setItem(nr,e),e}function ci(){Ua=null,_s=null,ir=!1,ys=!1}window.addEventListener("storage",t=>{t.key===nr&&ci()});function Gy(){return new Promise((t,e)=>{const n=indexedDB.open(qy,1);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(vs)||i.createObjectStore(vs)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function Al(t,e){const n=await Gy();return new Promise((i,r)=>{const s=n.transaction(vs,t);let o;try{o=e(s.objectStore(vs))}catch(l){n.close(),r(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>r(o.error),s.oncomplete=()=>{n.close(),i(a)},s.onerror=()=>{n.close(),r(s.error||new Error("Encryption key transaction failed."))},s.onabort=()=>{n.close(),r(s.error||new Error("Encryption key transaction aborted."))}})}function Ky(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function Yy(){const t=await Al("readonly",e=>e.get(Rt));return Ky(t)?t:null}async function Mh(t){await Al("readwrite",e=>e.put(t,Rt))}async function Jy(){ci();try{await Al("readwrite",t=>t.delete(Rt))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function Zy(){const t=sessionStorage.getItem(Rt);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Mh(e),sessionStorage.removeItem(Rt),sessionStorage.removeItem(tr),localStorage.removeItem(gt+"salt"),e}async function Ju(t){const e=sessionStorage.getItem(Rt);if(e)return ys=sessionStorage.getItem(tr)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new ws;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),i=await crypto.subtle.exportKey("jwk",n);return sessionStorage.setItem(Rt,JSON.stringify(i)),sessionStorage.setItem(tr,"session"),ys=!1,crypto.subtle.importKey("jwk",i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function Xy(t){if(sessionStorage.getItem(tr)==="session"&&sessionStorage.getItem(Rt))return Yu(),ir=!0,Ju(t);try{const e=await Yy();if(e)return e;const n=await Zy();if(n)return n;const i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Mh(i),i}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),Yu(),ir=!0,Ju(t)}}async function Pl(t={}){const{allowSessionFallbackCreation:e=!0}=t,n=Vy();_s!==n&&ci();const i=Ua||Xy(e);Ua=i,_s=n;try{return await i}catch(r){throw ci(),r}}async function Qy(t){const e=await Pl(),n=_s,i=new TextEncoder,r=crypto.getRandomValues(new Uint8Array(12)),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},e,i.encode(t)),o=new Uint8Array(r.length+s.byteLength);return o.set(r),o.set(new Uint8Array(s),r.length),{ciphertext:Lh(o),keyVersion:n,sessionFallback:ir}}async function e0(t,e={}){const{isSessionCredential:n=!1}=e;try{const i=await Pl({allowSessionFallbackCreation:!1});if(ir&&!n&&!ys)throw new ws;const r=t0(t),s=r.slice(0,12),o=r.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},i,o);return new TextDecoder().decode(a)}catch(i){if(i instanceof ws)throw i;return console.error("Decryption failed:",i),null}}function Lh(t){const e=new Uint8Array(t);let n="";for(let i=0;i0}let Ln="",ui="",zi=null,Xu=0,nt="not-configured";async function Fl(){sessionStorage.getItem(Rt)&&await Pl(),Ln=await Te("flutterflow"),ui=await Te("flutterflow_project_id"),c0(),rn(),Ln?Ml():(nt="not-configured",vt())}let rr=!1;function Nh(){const t=document.getElementById("api-keys-modal");We(t),$l(),Ln&&Ll(Ln)}function Rl(){rr=!1,Nh()}function i0(){rr=!0;const t=document.getElementById("walkthrough-modal");t&&ze(t),Nh()}let Qu=!1;function ed(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-settings-model");if(!t||!e)return;e.value=t.value;const n=Array.from(t.options);Array.from(e.options).forEach((r,s)=>{const o=n[s];o&&(r.textContent=o.textContent)});const i=document.getElementById("composer-settings-free-notice");i&&(document.getElementById("model-selector-free-notice")?(i.hidden=!1,i.innerHTML='Free plan — Gemini only. '):i.hidden=!0)}function td(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-image-capability"),n=document.getElementById("composer-image-capability-note");if(!t)return;const i=Gt(t.value),r=kh(t.value);e&&(e.textContent=r?"Supported":"Not supported"),n&&(n.textContent=r?`${i} accepts reference images you attach to the prompt.`:`Images can't be attached with ${i}. Attached images are removed when you switch to it.`),kl()}function r0(){if(rr=!1,ed(),td(),!Qu){const e=document.getElementById("composer-settings-model");e&&e.addEventListener("change",()=>{const n=document.getElementById("code-generator-model");n.value=e.value,n.dispatchEvent(new Event("change")),ed(),td()}),Qu=!0}const t=document.querySelector('.composer [aria-label="Generation settings"]');We("composer-settings-modal",{trigger:t})}function s0(t){t&&t.target!==t.currentTarget||ze("composer-settings-modal")}function Oh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&ze(e);const n=rr;if(rr=!1,n){const i=document.getElementById("walkthrough-modal");i&&(nt==="connected"&&Tl(),We(i))}}let en=1;function Bh(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function Ns(){const t=Bh();t.length&&t.forEach((e,n)=>{const i=n+1;e.classList.remove("wt-current","wt-done","wt-pending");const r=e.querySelector(".wt-step-num");i===en?(e.classList.add("wt-current"),r&&(r.textContent=i)):i0&&en<=t&&(en++,Ns())}function o0(){const t=document.getElementById("walkthrough-modal");t&&(en=1,Ns(),We(t))}function a0(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&ze(e);const n=document.getElementById("walkthrough-dont-show");n&&n.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function Dh(){if(q.isVerified&&Tt()&&ce.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(en=1,Ns(),We(e))}}async function $l(){const t=document.getElementById("flutterflow-api-key-input");Ln?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",l0()}function l0(){nd("flutterflow","flutterflow-key-status"),nd("flutterflow_project_id","flutterflow-project-status")}function nd(t,e){const n=document.getElementById(e);if(!n)return;const i=n.querySelector(".key-status-dot"),r=n.querySelector("span");Ct(t)?(i.className="key-status-dot configured",r.className="text-green-600",r.textContent="User key configured"):(i.className="key-status-dot missing",r.className="text-gray-500",r.textContent="Not configured")}function rn(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff");e&&e.classList.toggle("hidden",!t)}function c0(){const t=document.getElementById("api-keys-status");if(!t)return;const e=t.querySelectorAll(".key-status-dot"),n=["flutterflow"];e.forEach((i,r)=>{const s=n[r];s==="flutterflow"?Ct("flutterflow")&&Ct("flutterflow_project_id")?(i.className="key-status-dot configured",i.title="FlutterFlow (Fully configured)"):Ct("flutterflow")||Ct("flutterflow_project_id")?(i.className="key-status-dot env",i.title="FlutterFlow (Partially configured)"):(i.className="key-status-dot missing",i.title="FlutterFlow (Not configured)"):Ct(s)?(i.className="key-status-dot configured",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (User key)"):(i.className="key-status-dot missing",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (Not configured)")}),rn()}async function u0(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select"),n=t.value.trim();n&&await Zu("flutterflow",n);const i=e?.value.trim()||"";if(i){if(!Os(i)){Ee("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await Zu("flutterflow_project_id",i)}await Fl(),n&&await Ml(),$l();const r=document.querySelector("#api-keys-modal .bg-blue-500"),s=r.textContent;r.textContent="Saved!",r.classList.remove("bg-blue-500","hover:bg-blue-600"),r.classList.add("bg-green-500"),setTimeout(()=>{r.textContent=s,r.classList.remove("bg-green-500"),r.classList.add("bg-blue-500","hover:bg-blue-600"),Oh()},1e3)}async function d0(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(nr,Ha()),ci(),localStorage.removeItem(gt+"flutterflow"),localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow"),sessionStorage.removeItem(Pt+"flutterflow_project_id"),sessionStorage.removeItem(Rt),sessionStorage.removeItem(tr),localStorage.removeItem(gt+"salt"),await Jy(),localStorage.setItem(nr,Ha()),localStorage.removeItem(gt+"flutterflow"),localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow"),sessionStorage.removeItem(Pt+"flutterflow_project_id"),await Fl();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),$l()}function Os(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function vt(){const t=document.getElementById("acct-ff-dot"),e=document.getElementById("acct-ff-status"),n=document.getElementById("acct-ff-endpoint"),i=document.getElementById("acct-ff-project");if(n){const o=yt();n.textContent=o.includes("staging")?"Staging":"Production"}if(i&&(i.textContent=ui||"—"),!e)return;let r,s;if(!Ct("flutterflow"))r="Not connected — add your FlutterFlow API key",s="";else switch(nt){case"connected":r="Connected to FlutterFlow",s="ok";break;case"no-projects":r="Key accepted — no projects found",s="warn";break;case"unauthorized":r="API key rejected (401/403) — re-enter your key",s="bad";break;case"network-error":r="Could not reach FlutterFlow — check your network",s="bad";break;default:r="Checking connection…",s="warn";break}e.textContent=r,t&&(t.className=`acct-dot${s?" "+s:""}`)}async function Ml(){const t=await Te("flutterflow");if(!t||!Ct("flutterflow"))return nt="not-configured",vt(),null;nt="validating",vt();try{const n=await new hi(t,"","main",yt()).listProjects();return nt=n&&n.length>0?"connected":"no-projects",vt(),n}catch(e){const n=String(e&&e.message||"");return nt=/(401|403)|denied|unauthorized|scoped|list permission/i.test(n)?"unauthorized":"network-error",vt(),null}}function f0(){ui="",localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow_project_id")}function h0(){f0();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML='',t.value=""),Ct("flutterflow")?(nt="validating",Ll(Ln)):nt="not-configured",vt()}function p0(t,e){const n=document.getElementById(t);n&&(n.value?e?n.style.borderColor="#22c55e":n.style.borderColor="#ef4444":n.style.borderColor="")}function g0(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const n=e.target.value.trim().length>0;p0("flutterflow-api-key-input",n)}),t.addEventListener("blur",m0(async e=>{const n=e.target.value.trim();n&&await Ll(n)},500)))}function m0(t,e){let n;return function(...r){const s=()=>{clearTimeout(n),t(...r)};clearTimeout(n),n=setTimeout(s,e)}}async function Ll(t){const e=document.getElementById("flutterflow-projects-select"),n=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',n&&n.classList.add("hidden"),(Ct("flutterflow")||t)&&(nt="validating"),vt();try{const r=await new hi(t,"","main",yt()).listProjects();if(!r||r.length===0){nt="no-projects",vt(),e.innerHTML='';return}nt="connected",vt(),e.innerHTML='',r.forEach(s=>{const o=document.createElement("option");o.value=s.id||s.projectId||"",o.textContent=s.name||s.projectName||`Project ${s.id}`,e.appendChild(o)}),ui&&(e.value=ui)}catch(i){console.error("Failed to fetch projects:",i);const r=String(i&&i.message||"");nt=/(401|403)|denied|unauthorized|scoped|list permission/i.test(r)?"unauthorized":"network-error",vt(),e.innerHTML='',n&&(n.textContent=`Failed to load projects: ${i.message}`,n.classList.remove("hidden"))}}function v0(t){const e=document.getElementById(t),i=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",i.innerHTML=` + `}const Ey=[[/gradient stroke\s*$/i," and an animated percentage label"],[/gauge\s*$/i," with a gradient stroke and animated fill"],[/rating\s*(bar|widget)?\s*$/i," with half-star support and haptic feedback"],[/list\s*$/i," with swipe-to-delete and an undo snackbar"],[/pad\s*$/i," that exports a transparent PNG"],[/carousel\s*$/i," with parallax cards and page indicators"],[/(button|cta)\s*$/i," with a loading spinner and success state"],[/(chart|graph)\s*$/i," that animates from a Firestore stream"],[/action\s*(that|to)?\s*$/i," uploads an image to Firebase Storage and returns the URL"],[/timer\s*$/i," with pause, resume and a completion callback"],[/map\s*$/i," with clustered markers and a custom info window"],[/^a\s+\w*$/i," widget that"],[/(picker|selector)\s*$/i," with search and multi-select"]],Sy=220,xy=6;function Vu(t,e){return!!(t&&t.trim())&&!e}function Iy(t,e=""){if(typeof t!="string"||!t||t===e||t.trim().lengthi.test(t));return n?n[1]:null}function ky(){let t="",e="";return{get active(){return t},resolve(n){return t=Iy(n,e)??"",t},dismiss(){t=""},accept(n){if(!t)return null;const i=n+t;return e=i,t="",i}}}function Cy({onSubmit:t}){const e=document.getElementById("composer"),n=document.getElementById("pipeline-input"),i=document.getElementById("hero-send");if(!e||!n||!i||typeof t!="function")return;const r=e.querySelector(".ghost .typed"),s=e.querySelector(".ghost .suggest"),o=document.getElementById("tab-hint"),a=document.getElementById("suggest-status"),l=Array.from(document.querySelectorAll("#example-chips .chip")),u=document.getElementById("btn-add-images"),c=document.getElementById("prompt-image-input"),d=window.matchMedia("(prefers-reduced-motion: reduce)"),f=ky();let h=!1,p=!1,g=!1,m=!1,v=null,E=null;function S(){i.disabled=!Vu(n.value,p||g||m)}function _(){r&&(r.textContent=n.value)}function b(){s&&(s.textContent=""),_(),e.classList.remove("has-suggest"),o&&(o.hidden=!0,o.tabIndex=-1),a&&(a.textContent="")}function k(R){s&&(s.textContent=R),_(),e.classList.add("has-suggest"),o&&(o.hidden=!1,o.tabIndex=0,o.setAttribute("aria-label","Accept suggestion: "+R.trim())),a&&(a.textContent="Suggestion: "+R+". Press Tab to accept.")}function T(){f.dismiss(),b()}function x(){if(h||p)return;const R=f.resolve(n.value);R&&k(R)}function F(){clearTimeout(v),!h&&(v=setTimeout(x,Sy))}function $(){const R=f.accept(n.value);return R===null?!1:(n.value=R,b(),S(),!0)}function O(R){p=R,e.classList.toggle("is-busy",R),i.classList.toggle("is-busy",R),i.setAttribute("aria-label",R?"Generating":"Generate"),n.readOnly=R,l.forEach(Z=>{Z.disabled=R}),u&&(u.disabled=R),c&&(c.disabled=R),S()}async function L(){if(Vu(n.value,p||g||m)){T(),O(!0);try{await t()}finally{O(!1)}}}function N(){g=!1,E&&(clearInterval(E),E=null),e.classList.remove("is-demo-typing"),S()}function K(){l.forEach(R=>{R.classList.remove("is-active"),R.setAttribute("aria-pressed","false")})}function V(){try{n.focus({preventScroll:!0}),n.setSelectionRange(n.value.length,n.value.length)}catch{}}function M(R){const Z=R.dataset.prompt||"";if(N(),clearTimeout(v),v=null,T(),l.forEach(oe=>{const ye=oe===R;oe.classList.toggle("is-active",ye),oe.setAttribute("aria-pressed",String(ye))}),d.matches||!Z){n.value=Z,_(),S(),V();return}n.value="",_(),g=!0,S(),e.classList.add("is-demo-typing");let Ce=0;E=setInterval(()=>{Ce+=1,n.value=Z.slice(0,Ce),_(),Ce>=Z.length?(N(),V()):S()},22)}return l.forEach(R=>{R.setAttribute("aria-pressed","false"),R.addEventListener("click",()=>M(R))}),n.addEventListener("keydown",R=>{if(g&&R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!h){R.preventDefault();return}N(),R.key==="Tab"&&!R.shiftKey&&f.active?(R.preventDefault(),$()):R.key==="Escape"?(clearTimeout(v),v=null,T()):R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!h&&(R.preventDefault(),L())}),n.addEventListener("input",()=>{N(),K(),T(),S(),F()}),n.addEventListener("compositionstart",()=>{h=!0}),n.addEventListener("compositionend",()=>{h=!1,T(),S(),F()}),n.addEventListener("scroll",()=>{r&&r.parentNode&&(r.parentNode.scrollTop=n.scrollTop)}),o&&o.addEventListener("click",()=>{$(),n.focus({preventScroll:!0})}),i.addEventListener("click",L),n.addEventListener("pointerdown",()=>{N(),K()}),_(),S(),{setAttachmentsPending(R){m=!!R,S()}}}const Ay="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses";const _t="https://4tgke4.buildship.run",kh={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},hs="ccc_auth_session",Oa="ccc_signin_return",Py=1800*1e3,Gu=new WeakSet;let q={email:null,sessionToken:null,isVerified:!1};function Mn(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let ce=Mn({isResolved:!0}),Ba=Promise.resolve();const Fy=`${_t}/service/runpipeline`,Ry="bs_user_id",Ty="bs_identity_token",$y=`${_t}/authUserCheck`;let ht={userId:null,token:null,status:null,resolved:!1};const ps=cv,gs="ccc_subscription",Ku=3,My=new Set(["active","trialing","paid"]),ms="google/gemini-3.7-flash",Nr=["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"],Ly={"google/gemini-3.7-flash":"Gemini 3.7 Flash","anthropic/claude-opus-5":"Claude Opus 5","openai/gpt-5.6-sol":"GPT-5.6 Sol","z-ai/glm-5.2":"GLM 5.2","moonshotai/kimi-k3":"Kimi K3","openrouter/auto-beta":"OpenRouter: Auto Router","openrouter/free":"OpenRouter: Free Models","openrouter/deepseek/deepseek-v4-pro":"DeepSeek v4 Pro"};function Gt(t){return Ly[t]||t}const Ny=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 Ch(t){return Ny.has(t)}const Da=4,Wo=8*1024*1024,Oy="https://4tgke4.buildship.run/service/runpipeline-image";let Oe=[];const pn=[],By=3e4;let Ah=null;function Dy(t){return new Promise(e=>{const n=new FileReader;n.onload=()=>e(n.result),n.onerror=()=>e(null),n.readAsDataURL(t)})}async function jy(t,e){const n=new FormData;return n.append("file",t),(await fetch(Oy,{method:"POST",body:n,signal:e})).json()}function Uy(t){if(Array.isArray(t)){const e=t[0];if(e&&typeof e=="object")for(const n of Object.keys(e)){if(n==="item"||n==="index")continue;const i=e[n];if(i&&typeof i=="object"){if(typeof i.file=="string")return i.file;if(typeof i.url=="string")return i.url}if(typeof i=="string")return i}return""}return typeof t=="string"?t:t&&typeof t=="object"&&(t.url||t.fileUrl||t.file_url||t.downloadUrl||t.imageUrl||t.image_url||t.file)||""}async function Hy(t,e,n){const i=await Dy(t);i&&Oe.includes(e)&&(e.dataUrl=i,cn());let r="";if(i)try{r=Uy(await jy(t,n))}catch{r=""}return Oe.includes(e)?!i||!r?(Oe.splice(Oe.indexOf(e),1),cn(),"failed"):(e.url=r,cn(),"added"):"dropped"}function Ph(t){const e=pn.indexOf(t);e>=0&&pn.splice(e,1),Rh()}function Fh(t){t.controller.abort(),Ph(t);const e=Oe.indexOf(t.slot);e>=0&&(Oe.splice(e,1),cn())}function Rh(){Ah?.setAttachmentsPending(pn.length>0)}async function Wy(t){const e=Array.from(t.target.files||[]);if(!e.length)return;if(t.target.value="",y.isRunning){Ee("Wait for the current generation to finish before attaching images.","info");return}const n=e.filter(u=>u.size>Wo);n.length&&Ee(`Skipped ${n.length} image(s) over the ${(Wo/1024/1024).toFixed(0)} MB limit.`,"warning");const i=e.filter(u=>u.size<=Wo);if(!i.length)return;const r=Da-Oe.length,s=i.slice(0,r);if(i.length>r&&Ee(`You can attach up to ${Da} images.`,"info"),!s.length)return;const o=s.map(u=>{const c={dataUrl:null,name:u.name,url:null};Oe.push(c);const d={slot:c,controller:new AbortController},f=setTimeout(()=>d.controller.abort(),By);return d.job=Hy(u,c,d.controller.signal),pn.push(d),d.job.finally(()=>{clearTimeout(f),Ph(d)}),d.job});cn(),Rh();const l=(await Promise.all(o)).filter(u=>u==="failed").length;l&&Ee(`${l} image(s) could not be uploaded and were not attached.`,"error")}function zy(t){const e=Oe[t],n=pn.find(i=>i.slot===e);if(n){Fh(n);return}Oe.splice(t,1),cn()}function cn(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",Oe.forEach((n,i)=>{const r=document.createElement("div");r.className="prompt-img-thumb"+(n.url?"":" is-pending"),r.innerHTML=(n.dataUrl?`Prompt image`:"")+``,t.appendChild(r)}),e&&(e.textContent=Oe.length>=Da?"Image limit reached":"Add images"))}function Cl(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),n=Ch(e?.value);t.classList.toggle("hidden",!n),!n&&Oe.length&&(pn.slice().forEach(Fh),Oe=[],cn())}const Fn="ccc_usage",Th="google/gemini-3.7-flash",$h="google/gemini-3.7-flash",kr="google/gemini-3.7-flash",Ni={professional:11,power:49},ja={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"},Or={AUD:1,USD:.65,EUR:.6,GBP:.52,CAD:.88,NZD:1.08,JPY:97,KRW:870,INR:54,SGD:.87,HKD:5.08,BRL:3.18,CNY:4.7,TWD:20.5,THB:22.5,VND:16200,IDR:10200,MYR:2.88,SEK:6.8,NOK:6.95,DKK:4.48,PLN:2.6,CZK:15.2,HUF:238,RON:2.98,TRY:20.9,AED:2.39,ILS:2.38,PHP:36.4,ZAR:11.8,RUB:58,UAH:26.8,CHF:.57,MXN:11.1,ARS:580,CLP:610,COP:2700,PEN:2.44};let Br={...Or};async function qy(){const t=new AbortController,e=setTimeout(()=>t.abort(),5e3);try{const n=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:t.signal});if(!n.ok)return;const i=await n.json();if(i.result!=="success"||!i.rates)return;const r=i.rates,s={AUD:1},o=new Set([...Object.keys(Or),...Object.values(Ua),...Object.values(ja)]);for(const a of o)a!=="AUD"&&(typeof r[a]=="number"&&r[a]>0?s[a]=r[a]:Or[a]&&(s[a]=Or[a]));Br=s}catch{}finally{clearTimeout(e)}}const Ua={"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 Al(){try{const s=Intl.DateTimeFormat().resolvedOptions().timeZone;if(s&&Ua[s])return Ua[s]}catch{}const e=(navigator.language||"en-US").replace("-","_"),n=ja[e];if(n)return n;const i=e.split("_")[0],r=ja[i];return r||"USD"}function Oi(t,e){const n=Br[e]??Br.USD,i=t*n,r=Math.round(i*100)/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:r>=100||r%1===0?0:2}).format(r)}catch{return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(t*Br.USD)}}const gt="ccc_api_key_",Pt="ccc_session_api_key_",Rt="ccc_encryption_key",tr="ccc_encryption_key_scope",Vy="ccc_keystore",vs="keys",nr="ccc_encryption_key_version";let Ha=null,_s=null,ir=!1,ys=!1,Yu=!1;class ws extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function Ju(){if(Yu)return;Yu=!0;const t="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(t),document.body&&Ee(t,"warning")}function Mh(){return localStorage.getItem(nr)||""}function Wa(){return crypto.randomUUID?.()||Nh(crypto.getRandomValues(new Uint8Array(16)))}function Gy(){const t=Mh();if(t)return t;const e=Wa();return localStorage.setItem(nr,e),e}function ci(){Ha=null,_s=null,ir=!1,ys=!1}window.addEventListener("storage",t=>{t.key===nr&&ci()});function Ky(){return new Promise((t,e)=>{const n=indexedDB.open(Vy,1);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(vs)||i.createObjectStore(vs)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function Pl(t,e){const n=await Ky();return new Promise((i,r)=>{const s=n.transaction(vs,t);let o;try{o=e(s.objectStore(vs))}catch(l){n.close(),r(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>r(o.error),s.oncomplete=()=>{n.close(),i(a)},s.onerror=()=>{n.close(),r(s.error||new Error("Encryption key transaction failed."))},s.onabort=()=>{n.close(),r(s.error||new Error("Encryption key transaction aborted."))}})}function Yy(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function Jy(){const t=await Pl("readonly",e=>e.get(Rt));return Yy(t)?t:null}async function Lh(t){await Pl("readwrite",e=>e.put(t,Rt))}async function Zy(){ci();try{await Pl("readwrite",t=>t.delete(Rt))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function Xy(){const t=sessionStorage.getItem(Rt);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Lh(e),sessionStorage.removeItem(Rt),sessionStorage.removeItem(tr),localStorage.removeItem(gt+"salt"),e}async function Zu(t){const e=sessionStorage.getItem(Rt);if(e)return ys=sessionStorage.getItem(tr)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new ws;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),i=await crypto.subtle.exportKey("jwk",n);return sessionStorage.setItem(Rt,JSON.stringify(i)),sessionStorage.setItem(tr,"session"),ys=!1,crypto.subtle.importKey("jwk",i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function Qy(t){if(sessionStorage.getItem(tr)==="session"&&sessionStorage.getItem(Rt))return Ju(),ir=!0,Zu(t);try{const e=await Jy();if(e)return e;const n=await Xy();if(n)return n;const i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Lh(i),i}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),Ju(),ir=!0,Zu(t)}}async function Fl(t={}){const{allowSessionFallbackCreation:e=!0}=t,n=Gy();_s!==n&&ci();const i=Ha||Qy(e);Ha=i,_s=n;try{return await i}catch(r){throw ci(),r}}async function e0(t){const e=await Fl(),n=_s,i=new TextEncoder,r=crypto.getRandomValues(new Uint8Array(12)),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},e,i.encode(t)),o=new Uint8Array(r.length+s.byteLength);return o.set(r),o.set(new Uint8Array(s),r.length),{ciphertext:Nh(o),keyVersion:n,sessionFallback:ir}}async function t0(t,e={}){const{isSessionCredential:n=!1}=e;try{const i=await Fl({allowSessionFallbackCreation:!1});if(ir&&!n&&!ys)throw new ws;const r=n0(t),s=r.slice(0,12),o=r.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},i,o);return new TextDecoder().decode(a)}catch(i){if(i instanceof ws)throw i;return console.error("Decryption failed:",i),null}}function Nh(t){const e=new Uint8Array(t);let n="";for(let i=0;i0}let Ln="",ui="",zi=null,Qu=0,nt="not-configured";async function Rl(){sessionStorage.getItem(Rt)&&await Fl(),Ln=await Te("flutterflow"),ui=await Te("flutterflow_project_id"),u0(),rn(),Ln?Ll():(nt="not-configured",vt())}let rr=!1;function Oh(){const t=document.getElementById("api-keys-modal");We(t),Ml(),Ln&&Nl(Ln)}function Tl(){rr=!1,Oh()}function r0(){rr=!0;const t=document.getElementById("walkthrough-modal");t&&ze(t),Oh()}let ed=!1;function td(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-settings-model");if(!t||!e)return;e.value=t.value;const n=Array.from(t.options);Array.from(e.options).forEach((r,s)=>{const o=n[s];o&&(r.textContent=o.textContent)});const i=document.getElementById("composer-settings-free-notice");i&&(document.getElementById("model-selector-free-notice")?(i.hidden=!1,i.innerHTML='Free plan — Gemini only. '):i.hidden=!0)}function nd(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-image-capability"),n=document.getElementById("composer-image-capability-note");if(!t)return;const i=Gt(t.value),r=Ch(t.value);e&&(e.textContent=r?"Supported":"Not supported"),n&&(n.textContent=r?`${i} accepts reference images you attach to the prompt.`:`Images can't be attached with ${i}. Attached images are removed when you switch to it.`),Cl()}function s0(){if(rr=!1,td(),nd(),!ed){const e=document.getElementById("composer-settings-model");e&&e.addEventListener("change",()=>{const n=document.getElementById("code-generator-model");n.value=e.value,n.dispatchEvent(new Event("change")),td(),nd()}),ed=!0}const t=document.querySelector('.composer [aria-label="Generation settings"]');We("composer-settings-modal",{trigger:t})}function o0(t){t&&t.target!==t.currentTarget||ze("composer-settings-modal")}function Bh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&ze(e);const n=rr;if(rr=!1,n){const i=document.getElementById("walkthrough-modal");i&&(nt==="connected"&&$l(),We(i))}}let en=1;function Dh(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function Os(){const t=Dh();t.length&&t.forEach((e,n)=>{const i=n+1;e.classList.remove("wt-current","wt-done","wt-pending");const r=e.querySelector(".wt-step-num");i===en?(e.classList.add("wt-current"),r&&(r.textContent=i)):i0&&en<=t&&(en++,Os())}function a0(){const t=document.getElementById("walkthrough-modal");t&&(en=1,Os(),We(t))}function l0(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&ze(e);const n=document.getElementById("walkthrough-dont-show");n&&n.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function jh(){if(q.isVerified&&Tt()&&ce.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(en=1,Os(),We(e))}}async function Ml(){const t=document.getElementById("flutterflow-api-key-input");Ln?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",c0()}function c0(){id("flutterflow","flutterflow-key-status"),id("flutterflow_project_id","flutterflow-project-status")}function id(t,e){const n=document.getElementById(e);if(!n)return;const i=n.querySelector(".key-status-dot"),r=n.querySelector("span");Ct(t)?(i.className="key-status-dot configured",r.className="text-green-600",r.textContent="User key configured"):(i.className="key-status-dot missing",r.className="text-gray-500",r.textContent="Not configured")}function rn(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff");e&&e.classList.toggle("hidden",!t)}function u0(){const t=document.getElementById("api-keys-status");if(!t)return;const e=t.querySelectorAll(".key-status-dot"),n=["flutterflow"];e.forEach((i,r)=>{const s=n[r];s==="flutterflow"?Ct("flutterflow")&&Ct("flutterflow_project_id")?(i.className="key-status-dot configured",i.title="FlutterFlow (Fully configured)"):Ct("flutterflow")||Ct("flutterflow_project_id")?(i.className="key-status-dot env",i.title="FlutterFlow (Partially configured)"):(i.className="key-status-dot missing",i.title="FlutterFlow (Not configured)"):Ct(s)?(i.className="key-status-dot configured",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (User key)"):(i.className="key-status-dot missing",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (Not configured)")}),rn()}async function d0(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select"),n=t.value.trim();n&&await Xu("flutterflow",n);const i=e?.value.trim()||"";if(i){if(!Bs(i)){Ee("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await Xu("flutterflow_project_id",i)}await Rl(),n&&await Ll(),Ml();const r=document.querySelector("#api-keys-modal .bg-blue-500"),s=r.textContent;r.textContent="Saved!",r.classList.remove("bg-blue-500","hover:bg-blue-600"),r.classList.add("bg-green-500"),setTimeout(()=>{r.textContent=s,r.classList.remove("bg-green-500"),r.classList.add("bg-blue-500","hover:bg-blue-600"),Bh()},1e3)}async function f0(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(nr,Wa()),ci(),localStorage.removeItem(gt+"flutterflow"),localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow"),sessionStorage.removeItem(Pt+"flutterflow_project_id"),sessionStorage.removeItem(Rt),sessionStorage.removeItem(tr),localStorage.removeItem(gt+"salt"),await Zy(),localStorage.setItem(nr,Wa()),localStorage.removeItem(gt+"flutterflow"),localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow"),sessionStorage.removeItem(Pt+"flutterflow_project_id"),await Rl();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),Ml()}function Bs(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function vt(){const t=document.getElementById("acct-ff-dot"),e=document.getElementById("acct-ff-status"),n=document.getElementById("acct-ff-endpoint"),i=document.getElementById("acct-ff-project");if(n){const o=yt();n.textContent=o.includes("staging")?"Staging":"Production"}if(i&&(i.textContent=ui||"—"),!e)return;let r,s;if(!Ct("flutterflow"))r="Not connected — add your FlutterFlow API key",s="";else switch(nt){case"connected":r="Connected to FlutterFlow",s="ok";break;case"no-projects":r="Key accepted — no projects found",s="warn";break;case"unauthorized":r="API key rejected (401/403) — re-enter your key",s="bad";break;case"network-error":r="Could not reach FlutterFlow — check your network",s="bad";break;default:r="Checking connection…",s="warn";break}e.textContent=r,t&&(t.className=`acct-dot${s?" "+s:""}`)}async function Ll(){const t=await Te("flutterflow");if(!t||!Ct("flutterflow"))return nt="not-configured",vt(),null;nt="validating",vt();try{const n=await new hi(t,"","main",yt()).listProjects();return nt=n&&n.length>0?"connected":"no-projects",vt(),n}catch(e){const n=String(e&&e.message||"");return nt=/(401|403)|denied|unauthorized|scoped|list permission/i.test(n)?"unauthorized":"network-error",vt(),null}}function h0(){ui="",localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow_project_id")}function p0(){h0();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML='',t.value=""),Ct("flutterflow")?(nt="validating",Nl(Ln)):nt="not-configured",vt()}function g0(t,e){const n=document.getElementById(t);n&&(n.value?e?n.style.borderColor="#22c55e":n.style.borderColor="#ef4444":n.style.borderColor="")}function m0(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const n=e.target.value.trim().length>0;g0("flutterflow-api-key-input",n)}),t.addEventListener("blur",v0(async e=>{const n=e.target.value.trim();n&&await Nl(n)},500)))}function v0(t,e){let n;return function(...r){const s=()=>{clearTimeout(n),t(...r)};clearTimeout(n),n=setTimeout(s,e)}}async function Nl(t){const e=document.getElementById("flutterflow-projects-select"),n=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',n&&n.classList.add("hidden"),(Ct("flutterflow")||t)&&(nt="validating"),vt();try{const r=await new hi(t,"","main",yt()).listProjects();if(!r||r.length===0){nt="no-projects",vt(),e.innerHTML='';return}nt="connected",vt(),e.innerHTML='',r.forEach(s=>{const o=document.createElement("option");o.value=s.id||s.projectId||"",o.textContent=s.name||s.projectName||`Project ${s.id}`,e.appendChild(o)}),ui&&(e.value=ui)}catch(i){console.error("Failed to fetch projects:",i);const r=String(i&&i.message||"");nt=/(401|403)|denied|unauthorized|scoped|list permission/i.test(r)?"unauthorized":"network-error",vt(),e.innerHTML='',n&&(n.textContent=`Failed to load projects: ${i.message}`,n.classList.remove("hidden"))}}function _0(t){const e=document.getElementById(t),i=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",i.innerHTML=` `):(e.type="password",i.innerHTML=` - `)}let y={step1Result:null,step2Result:null,step3Result:null,bundleSpec:null,artifactBundle:null,bundleReview:null,selectedArtifactId:null,resultsViewMode:"summary",currentStep:0,isRunning:!1,runId:0,submittedPrompt:"",submittedImages:[]};function _0(){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 y0(){y.bundleSpec=Qi(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function Bs(){const t=oi(y.bundleSpec);y.artifactBundle=Qi(y.step2Result,{id:y.bundleSpec?.id,title:y.bundleSpec?.title,description:y.bundleSpec?.description,artifactType:t.artifactType,artifactName:t.artifactName,fileName:t.fileName,dependencies:t.dependencies,relationships:y.bundleSpec?.relationships,code:y.step2Result||""});const e=zv(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(n=>n.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=oi(y.artifactBundle).id}function Ds(){const t=Qi(y.step3Result,{id:y.artifactBundle?.id,title:y.artifactBundle?.title}),e=new Map(t.artifacts.map(i=>[i.id,i.review])),n=new Map(t.artifacts.filter(i=>{const r=i.review;return r&&typeof r.fixedSource=="string"&&r.fixedSource.trim()}).map(i=>[i.id,i.review.fixedSource.trim()]));y.bundleReview=Qi({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(i=>{const r=n.get(i.id)||null;return{...i,review:e.get(i.id)||i.review||y.step3Result||null,...r?{fixedCode:r}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function jh(){const t=Nl();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function Nl(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(n=>n.id===y.selectedArtifactId)||oi(t)}function Ol(){return Nl().code||y.step2Result||""}async function w0(){try{await Fl()}catch(t){return console.error("checkConnection: initializeApiKeys failed:",t),!1}return!0}const Dr={production:"https://api.flutterflow.io/v2/",staging:"https://api.flutterflow.io/v2-staging/"};function b0(t,e){const n=e?.trim()?` (${e.trim().slice(0,200)})`:"";return t===401?`Your FlutterFlow API key was rejected (401 Unauthorized)${n}. Re-enter a current key under API Keys settings, then try again.`:`Listing FlutterFlow projects was denied (403)${n}. The key may be scoped to sync a single project without list permission - verify the key's access in FlutterFlow, re-enter it under API Keys settings, then retry.`}class hi{constructor(e,n,i="main",r=Dr.production){this.apiKey=e,this.baseUrl=r,this._projectId=n,this._branchName=i,this._endpoint=r}get projectId(){return this._projectId}get branchName(){return this._branchName==="main"?"":this._branchName}async exportProjectZip(){console.log(`Exporting code from FlutterFlow project: ${this.projectId}, branch: ${this.branchName||"main"}`);const e=[{project:{path:`projects/${this.projectId}`},...this.branchName?{branch_name:this.branchName}:{},export_as_module:!1,include_assets_map:!1,format:!1,export_as_debug:!1},{project_id:this.projectId,branch_name:this.branchName,include_assets:!1,export_as_module:!1}];let n=null;for(const i of e)try{const r=await fetch(`${this.baseUrl}exportCode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(i)});if(!r.ok){const a=await r.text();n=new Error(`Export failed: ${r.status} - ${a}`);continue}const s=await r.json(),o=s?.value?.project_zip||s?.project_zip;if(!o){n=new Error("Export response did not include project source.");continue}return o}catch(r){n=r}throw n||new Error("Export failed for an unknown reason.")}async fetchProjectSource(){const e=await this.exportProjectZip(),n=await JSZip.loadAsync(e,{base64:!0}),i=Object.keys(n.files).filter(a=>!n.files[a].dir&&(a==="pubspec.yaml"||a.endsWith("/pubspec.yaml"))).sort((a,l)=>a.split("/").length-l.split("/").length)[0];if(!i)throw new Error("Export did not contain a pubspec.yaml.");const r=i.slice(0,i.length-12),s=new Map,o=Object.keys(n.files).filter(a=>{if(n.files[a].dir||!a.startsWith(r))return!1;const l=a.slice(r.length);return l==="lib/flutter_flow/custom_functions.dart"||l.startsWith("lib/custom_code/")&&l.endsWith(".dart")});return await Promise.all(o.map(async a=>{s.set(a.slice(r.length),await n.files[a].async("string"))})),{pubspecYaml:await n.files[i].async("string"),files:s}}async pushCodeWithRetry(e,n=3,i=null){const r=[Dr.production,Dr.staging],s=Math.max(0,r.indexOf(this._endpoint));let o=!1,a=null;for(let l=0;lsetTimeout(p,1e3*(l+1)));continue}if(d.ok)return console.log(`Push to ${c} succeeded!`),d;a=d.status;let h;try{h=await d.clone().text()}catch{h="(unreadable response body)"}if(console.log(`Push to ${c} returned ${d.status}: ${h}`),d.status>=500&&(o=!0),d.status===500){console.warn(`Endpoint ${c} returned 500, trying next...`),await new Promise(f=>setTimeout(f,1e3*(l+1)));continue}if(d.status>=500)throw new Qe(`FlutterFlow reported a server error (HTTP ${d.status}), which cannot prove the push was refused — the write may have been applied before the failure. Open your FlutterFlow project to reconcile before retrying.`);if(o)throw new Qe(`The push was refused (HTTP ${d.status}), but an earlier sync attempt may already have applied it — server errors and dropped responses cannot prove a refusal. Open your FlutterFlow project to reconcile before retrying.`);return d}throw ju({httpStatus:a})}async pushCode(e,n=null){return this.pushCodeWithRetry(e,3,n)}parseProjectsResponse(e){if(e?.success&&typeof e.value=="string")try{const i=JSON.parse(e.value);if(i&&Array.isArray(i.entries))return i.entries.map(r=>({id:r.id,name:r.project?.name||r.id}))}catch(i){console.error("Failed to parse stringified project value:",i)}const n=e?.projects||e?.items||e?.entries||(Array.isArray(e)?e:[]);return Array.isArray(n)?n:[]}async listProjects(){console.log("Listing projects for API key");const e=[`${this.baseUrl}listProjects`,"https://api.flutterflow.io/v2/l/listProjects"];let n=0,i="";for(const r of e){const s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({project_type:"ALL",deserialize_response:!0})});if(s.ok)return r!==e[0]&&console.log(`listProjects answered on legacy path ${r}`),this.parseProjectsResponse(await s.json());if(n=s.status,i=await s.text(),console.warn(`listProjects via ${r} returned ${n}: ${i}`),s.status===401||s.status===403)throw new Error(b0(s.status,i));if(s.status!==404)throw new Error(`List projects failed: ${s.status} - ${i}`)}throw new Error(`List projects failed: ${n} - ${i}`)}}async function E0(t){const e=t.clone();let n;try{n=await t.json()}catch{let s="";try{s=await e.text()}catch{}if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:s||`HTTP ${t.status}`,errorMap:new Map};throw new Qe(`FlutterFlow accepted the sync but returned an unreadable response${s?`: ${s.slice(0,200)}`:"."}`)}if(!t.ok){let r=n.message||`HTTP ${t.status}`,s=new Map;if(n.errors)s=new Map(Object.entries(n.errors));else if(!n.message&&typeof n=="object"){const o=Object.keys(n).filter(a=>a.endsWith(".dart")&&Array.isArray(n[a]));o.length>0&&(s=new Map(Object.entries(n)),r=o.flatMap(l=>n[l].map(u=>`${l}: ${u.errorMessage}`)).join(` -`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:r,errorMap:s}}let i={};if(n.value)try{i=typeof n.value=="string"?JSON.parse(n.value):n.value}catch(r){console.warn("Ignoring malformed push response value:",r)}return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(i))}}function Bl(t,e){return{401:"Authentication failed. Please check your FlutterFlow API key.",403:"Access denied. You may not have permission to modify this project.",404:"Project not found. Please check your Project ID.",409:"Conflict detected. The project may have been modified elsewhere.",422:"Validation failed: Invalid request format",429:"Rate limit exceeded. Please try again in a few minutes.",500:"FlutterFlow server error. Please try again later.",503:"FlutterFlow service temporarily unavailable."}[t]||`FlutterFlow API error: ${`HTTP ${t}`}`}const J={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},Uh=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,Hh=/extends\s+State<\w+>/;function S0(t,e=""){if(t==="pubspec.yaml")return J.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return J.OTHER;if(t==="custom_functions.dart")return J.FUNCTION;if(e){const n=Uh.test(e),i=Hh.test(e);if(n||i)return J.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return J.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return J.FUNCTION}return J.CODE_FILE}function Wh(t,e){switch(e){case J.ACTION:return`lib/custom_code/actions/${t}`;case J.WIDGET:return`lib/custom_code/widgets/${t}`;case J.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case J.CODE_FILE:return`lib/custom_code/${t}`;case J.DEPENDENCIES:return"pubspec.yaml";case J.OTHER:return`lib/custom_code/${t}`;default:return t}}async function Dl(t,e=new Map){return kv(t,e)}const Wa=new Map;function zh(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function sr(t){Wa.delete(zh(t))}function qh(t,e,n){return new Promise((i,r)=>{let s=!1;const o=(l,u,c)=>{s||(s=!0,c==="resolve"?i(u):r(u))},a=setTimeout(()=>{s||(s=!0,n(i,r))},e);t.then(l=>{clearTimeout(a),o(i,l,"resolve")},l=>{clearTimeout(a),o(r,l,"reject")})})}async function jl(t,e,n=wh){const i={stop:!1};return qh((async()=>{const r=await t.pushCode(e,i);return E0(r)})(),n,(r,s)=>{i.stop=!0,s(new Qe("FlutterFlow did not answer the sync in time — the push may still have been applied. The outcome is not yet known: open your FlutterFlow project to reconcile before retrying the deploy."))})}async function Ul(t,e,n,i,r="",s=wh){const o=r_(e,n);if(o.length===0)return{remoteFiles:n,syncFileMap:e,unverified:[],approximate:[]};const a=J_(o,r),l={...a.manifest,sources:a.sources},u=a.skipped.map(f=>f.reason);u.forEach(f=>console.warn(`[custom class deploy] ${f}`));const c=a.approximate;c.forEach(f=>console.warn(`[custom class deploy] ${f}`)),console.log(`Provisioning ${o.length} new FlutterFlow custom code file(s) before sync.`),Be.set("provision");let d=!0,h;try{if(h=await qh((async()=>{let f;try{f=await fetch(Cy,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:i,customClasses:o,verification:l,stream:!0})})}catch{throw new Qe("The provisioning request did not return a response. The deploy may have reached the FlutterFlow server — open your FlutterFlow project to reconcile before retrying.")}return X_(f,{onPhase:p=>{d&&Be.setSubstatus(p)},onLog:p=>{d&&console.log(`[custom class deploy] ${p}`)}})})(),s,(f,p)=>{d=!1,p(new Qe("The deploy is still working on the FlutterFlow server, but this browser tab has stopped waiting. Your custom classes may or may not have been written — the outcome is not yet known. Open your FlutterFlow project to reconcile before retrying the deploy."))}),!h.finalResultReceived){if(Uu(h)===Le.FAILED){const f=new Error(h.error||`FlutterFlow custom class provisioning failed (HTTP ${h.httpStatus}).`);throw f.remoteRefusal=!0,f}throw new Qe("The connection to the FlutterFlow deploy runner dropped before it reported a result. The deploy may still be finishing on the server; open your FlutterFlow project to reconcile before retrying.")}}catch(f){throw f instanceof Qe&&sr(t),f}if(!h.success){const f=h.details?` ${h.details}`:"",p=`${h.error||"FlutterFlow custom class provisioning failed."}${f}`;if(Uu(h)===Le.UNCONFIRMED)throw new Qe(`${p} The failure arrived after the deploy began — custom classes may already be written. Open your FlutterFlow project to reconcile before retrying.`);const g=new Error(p);throw g.remoteRefusal=!0,g}return sr(t),h.verificationSkipped&&(console.warn(`[custom class deploy] ${h.verificationSkipped}`),u.push(h.verificationSkipped)),{remoteFiles:n,syncFileMap:s_(e,o),unverified:u,approximate:c,provisionSucceeded:!0}}async function Hl(t,e={}){const n=zh(t);let i=Wa.get(n);if(i===void 0){try{i=await t.fetchProjectSource()}catch(l){throw new Error(`Could not read your project's pubspec.yaml (${l.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=_h(i.pubspecYaml);if(!a.valid)throw new Error(`Your project's pubspec.yaml could not be read reliably (${a.errors.join("; ")}). Deploy was stopped so your existing package dependencies aren't overwritten.`);Wa.set(n,i)}const r=await my(i.pubspecYaml,e),s=q_(i.pubspecYaml,r.overrides),o=z_(s.yaml,r.additions);return r.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>`${a}: ${r.additions[a]||"any"}`).join(", "),r.sdk.dartSdkFloor?`(resolved for Dart ${r.sdk.dartSdkFloor})`:""),r.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:s.overridden,warnings:r.warnings,remoteFiles:i.files}}function x0(t){const e=[],n=[];t.content.length>5e4&&n.push("Code file is large (>50KB). This may take longer to commit."),t.content.length>1e5&&e.push("Code file is too large (>100KB). Consider splitting into smaller components.");const i=t.content.split(` -`).length;i>500&&n.push(`Code has ${i} lines. Consider breaking it into smaller widgets.`),t.content.includes("setState")&&t.codeType===J.ACTION&&n.push("Using setState in a Custom Action may not work as expected. Consider using a Custom Widget."),t.content.includes("dynamic")&&!t.content.includes("?")&&n.push('Code uses "dynamic" types. Consider adding explicit types for better null safety.'),t.content.match(/Color\(0xFF[0-9A-Fa-f]{6}\)/)&&n.push("Code contains hardcoded colors. Consider using FlutterFlowTheme.of(context) for theme consistency.");const r=t.content.match(/print\s*\(/g);r&&r.length>3&&n.push(`Code contains ${r.length} print statements. Consider removing debug prints before committing.`);const s=S_(t.content);if(s&&e.push(`FlutterFlow cannot format this code - ${s}. Fix or regenerate before committing.`),t.codeType===J.WIDGET){const o=ch(t.content),a=w_(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=`${uh(o[0])}`;e.push(`Widget class name "${o[0]}" does not match the file name "${t.fileName}". FlutterFlow derives the widget from the file name, so it will report "No widget ${a} found". Rename the file to "${l}" or the class to match before committing.`)}}return{canProceed:e.length===0,issues:e,warnings:n}}function Vh(t,e={}){const{artifactType:n="CustomWidget",artifactName:i="GeneratedCode",fileName:r}=e,s=__(t);let o=r||i;if(n==="CustomFunction")o="custom_functions.dart";else if(n==="CustomWidget"){const u=ch(s)[0],c=u?uh(u):null;c&&o!==c?(console.warn(`Commit file name "${o}" does not match declared widget class "${u}"; renaming to "${c}" so FlutterFlow can find the widget.`),o=c):o.endsWith(".dart")||(o+=".dart")}else o.endsWith(".dart")||(o+=".dart");let a=J.CODE_FILE;switch(n){case"CustomAction":a=J.ACTION;break;case"CustomWidget":a=J.WIDGET;break;case"CustomFunction":a=J.FUNCTION;break;case"CustomClass":case"CodeFile":a=J.CODE_FILE;break}let l="";return a===J.WIDGET?l=`// Automatic FlutterFlow imports + `)}let y={step1Result:null,step2Result:null,step3Result:null,bundleSpec:null,artifactBundle:null,bundleReview:null,selectedArtifactId:null,resultsViewMode:"summary",currentStep:0,isRunning:!1,runId:0,submittedPrompt:"",submittedImages:[]};function y0(){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 w0(){y.bundleSpec=Qi(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function Ds(){const t=oi(y.bundleSpec);y.artifactBundle=Qi(y.step2Result,{id:y.bundleSpec?.id,title:y.bundleSpec?.title,description:y.bundleSpec?.description,artifactType:t.artifactType,artifactName:t.artifactName,fileName:t.fileName,dependencies:t.dependencies,relationships:y.bundleSpec?.relationships,code:y.step2Result||""});const e=zv(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(n=>n.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=oi(y.artifactBundle).id}function js(){const t=Qi(y.step3Result,{id:y.artifactBundle?.id,title:y.artifactBundle?.title}),e=new Map(t.artifacts.map(i=>[i.id,i.review])),n=new Map(t.artifacts.filter(i=>{const r=i.review;return r&&typeof r.fixedSource=="string"&&r.fixedSource.trim()}).map(i=>[i.id,i.review.fixedSource.trim()]));y.bundleReview=Qi({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(i=>{const r=n.get(i.id)||null;return{...i,review:e.get(i.id)||i.review||y.step3Result||null,...r?{fixedCode:r}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function Uh(){const t=Ol();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function Ol(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(n=>n.id===y.selectedArtifactId)||oi(t)}function Bl(){return Ol().code||y.step2Result||""}async function b0(){try{await Rl()}catch(t){return console.error("checkConnection: initializeApiKeys failed:",t),!1}return!0}const Dr={production:"https://api.flutterflow.io/v2/",staging:"https://api.flutterflow.io/v2-staging/"};function E0(t,e){const n=e?.trim()?` (${e.trim().slice(0,200)})`:"";return t===401?`Your FlutterFlow API key was rejected (401 Unauthorized)${n}. Re-enter a current key under API Keys settings, then try again.`:`Listing FlutterFlow projects was denied (403)${n}. The key may be scoped to sync a single project without list permission - verify the key's access in FlutterFlow, re-enter it under API Keys settings, then retry.`}class hi{constructor(e,n,i="main",r=Dr.production){this.apiKey=e,this.baseUrl=r,this._projectId=n,this._branchName=i,this._endpoint=r}get projectId(){return this._projectId}get branchName(){return this._branchName==="main"?"":this._branchName}async exportProjectZip(){console.log(`Exporting code from FlutterFlow project: ${this.projectId}, branch: ${this.branchName||"main"}`);const e=[{project:{path:`projects/${this.projectId}`},...this.branchName?{branch_name:this.branchName}:{},export_as_module:!1,include_assets_map:!1,format:!1,export_as_debug:!1},{project_id:this.projectId,branch_name:this.branchName,include_assets:!1,export_as_module:!1}];let n=null;for(const i of e)try{const r=await fetch(`${this.baseUrl}exportCode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(i)});if(!r.ok){const a=await r.text();n=new Error(`Export failed: ${r.status} - ${a}`);continue}const s=await r.json(),o=s?.value?.project_zip||s?.project_zip;if(!o){n=new Error("Export response did not include project source.");continue}return o}catch(r){n=r}throw n||new Error("Export failed for an unknown reason.")}async fetchProjectSource(){const e=await this.exportProjectZip(),n=await JSZip.loadAsync(e,{base64:!0}),i=Object.keys(n.files).filter(a=>!n.files[a].dir&&(a==="pubspec.yaml"||a.endsWith("/pubspec.yaml"))).sort((a,l)=>a.split("/").length-l.split("/").length)[0];if(!i)throw new Error("Export did not contain a pubspec.yaml.");const r=i.slice(0,i.length-12),s=new Map,o=Object.keys(n.files).filter(a=>{if(n.files[a].dir||!a.startsWith(r))return!1;const l=a.slice(r.length);return l==="lib/flutter_flow/custom_functions.dart"||l.startsWith("lib/custom_code/")&&l.endsWith(".dart")});return await Promise.all(o.map(async a=>{s.set(a.slice(r.length),await n.files[a].async("string"))})),{pubspecYaml:await n.files[i].async("string"),files:s}}async pushCodeWithRetry(e,n=3,i=null){const r=[Dr.production,Dr.staging],s=Math.max(0,r.indexOf(this._endpoint));let o=!1,a=null;for(let l=0;lsetTimeout(h,1e3*(l+1)));continue}if(d.ok)return console.log(`Push to ${c} succeeded!`),d;if(a=d.status,d.clone().text().then(f=>console.log(`Push to ${c} returned ${d.status}: ${f}`),()=>console.log(`Push to ${c} returned ${d.status} (unreadable response body)`)),d.status>=500&&(o=!0),d.status===500){console.warn(`Endpoint ${c} returned 500, trying next...`),await new Promise(f=>setTimeout(f,1e3*(l+1)));continue}if(d.status>=500)throw new Qe(`FlutterFlow reported a server error (HTTP ${d.status}), which cannot prove the push was refused — the write may have been applied before the failure. Open your FlutterFlow project to reconcile before retrying.`);if(o)throw new Qe(`The push was refused (HTTP ${d.status}), but an earlier sync attempt may already have applied it — server errors and dropped responses cannot prove a refusal. Open your FlutterFlow project to reconcile before retrying.`);return d}throw Uu({httpStatus:a})}async pushCode(e,n=null){return this.pushCodeWithRetry(e,3,n)}parseProjectsResponse(e){if(e?.success&&typeof e.value=="string")try{const i=JSON.parse(e.value);if(i&&Array.isArray(i.entries))return i.entries.map(r=>({id:r.id,name:r.project?.name||r.id}))}catch(i){console.error("Failed to parse stringified project value:",i)}const n=e?.projects||e?.items||e?.entries||(Array.isArray(e)?e:[]);return Array.isArray(n)?n:[]}async listProjects(){console.log("Listing projects for API key");const e=[`${this.baseUrl}listProjects`,"https://api.flutterflow.io/v2/l/listProjects"];let n=0,i="";for(const r of e){const s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({project_type:"ALL",deserialize_response:!0})});if(s.ok)return r!==e[0]&&console.log(`listProjects answered on legacy path ${r}`),this.parseProjectsResponse(await s.json());if(n=s.status,i=await s.text(),console.warn(`listProjects via ${r} returned ${n}: ${i}`),s.status===401||s.status===403)throw new Error(E0(s.status,i));if(s.status!==404)throw new Error(`List projects failed: ${s.status} - ${i}`)}throw new Error(`List projects failed: ${n} - ${i}`)}}async function S0(t,e=X_){const n=t.clone();let i;try{i=await bs(t.json(),e,(s,o)=>o(new Error("The push response body stalled before it finished.")))}catch{let o="";try{o=await bs(n.text(),e,(a,l)=>l(new Error("stalled")))}catch{}if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:o||`HTTP ${t.status}`,errorMap:new Map};throw new Qe(`FlutterFlow accepted the sync but returned an unreadable response${o?`: ${o.slice(0,200)}`:"."}`)}if(!t.ok){let s=i.message||`HTTP ${t.status}`,o=new Map;if(i.errors)o=new Map(Object.entries(i.errors));else if(!i.message&&typeof i=="object"){const a=Object.keys(i).filter(l=>l.endsWith(".dart")&&Array.isArray(i[l]));a.length>0&&(o=new Map(Object.entries(i)),s=a.flatMap(u=>i[u].map(c=>`${u}: ${c.errorMessage}`)).join(` +`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:s,errorMap:o}}let r={};if(i.value)try{r=typeof i.value=="string"?JSON.parse(i.value):i.value}catch(s){console.warn("Ignoring malformed push response value:",s)}return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(r))}}function Dl(t,e){return{401:"Authentication failed. Please check your FlutterFlow API key.",403:"Access denied. You may not have permission to modify this project.",404:"Project not found. Please check your Project ID.",409:"Conflict detected. The project may have been modified elsewhere.",422:"Validation failed: Invalid request format",429:"Rate limit exceeded. Please try again in a few minutes.",500:"FlutterFlow server error. Please try again later.",503:"FlutterFlow service temporarily unavailable."}[t]||`FlutterFlow API error: ${`HTTP ${t}`}`}const J={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},Hh=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,Wh=/extends\s+State<\w+>/;function x0(t,e=""){if(t==="pubspec.yaml")return J.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return J.OTHER;if(t==="custom_functions.dart")return J.FUNCTION;if(e){const n=Hh.test(e),i=Wh.test(e);if(n||i)return J.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return J.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return J.FUNCTION}return J.CODE_FILE}function zh(t,e){switch(e){case J.ACTION:return`lib/custom_code/actions/${t}`;case J.WIDGET:return`lib/custom_code/widgets/${t}`;case J.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case J.CODE_FILE:return`lib/custom_code/${t}`;case J.DEPENDENCIES:return"pubspec.yaml";case J.OTHER:return`lib/custom_code/${t}`;default:return t}}async function jl(t,e=new Map){return kv(t,e)}const za=new Map;function qh(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function sr(t){za.delete(qh(t))}function bs(t,e,n){return new Promise((i,r)=>{let s=!1;const o=(l,u,c)=>{s||(s=!0,c==="resolve"?i(u):r(u))},a=setTimeout(()=>{s||(s=!0,n(i,r))},e);t.then(l=>{clearTimeout(a),o(i,l,"resolve")},l=>{clearTimeout(a),o(r,l,"reject")})})}async function Ul(t,e,n=bh){const i={stop:!1};return bs((async()=>{const r=await t.pushCode(e,i);return S0(r)})(),n,(r,s)=>{i.stop=!0,s(new Qe("FlutterFlow did not answer the sync in time — the push may still have been applied. The outcome is not yet known: open your FlutterFlow project to reconcile before retrying the deploy."))})}async function Hl(t,e,n,i,r="",s=bh){const o=r_(e,n);if(o.length===0)return{remoteFiles:n,syncFileMap:e,unverified:[],approximate:[]};const a=J_(o,r),l={...a.manifest,sources:a.sources},u=a.skipped.map(h=>h.reason);u.forEach(h=>console.warn(`[custom class deploy] ${h}`));const c=a.approximate;c.forEach(h=>console.warn(`[custom class deploy] ${h}`)),console.log(`Provisioning ${o.length} new FlutterFlow custom code file(s) before sync.`),Be.set("provision");let d=!0,f;try{if(f=await bs((async()=>{let h;try{h=await fetch(Ay,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:i,customClasses:o,verification:l,stream:!0})})}catch{throw new Qe("The provisioning request did not return a response. The deploy may have reached the FlutterFlow server — open your FlutterFlow project to reconcile before retrying.")}return Q_(h,{onPhase:p=>{d&&Be.setSubstatus(p)},onLog:p=>{d&&console.log(`[custom class deploy] ${p}`)}})})(),s,(h,p)=>{d=!1,p(new Qe("The deploy is still working on the FlutterFlow server, but this browser tab has stopped waiting. Your custom classes may or may not have been written — the outcome is not yet known. Open your FlutterFlow project to reconcile before retrying the deploy."))}),!f.finalResultReceived)throw Hu(f)===Le.FAILED?new Error(f.error||`FlutterFlow custom class provisioning failed (HTTP ${f.httpStatus}).`):new Qe("The connection to the FlutterFlow deploy runner dropped before it reported a result. The deploy may still be finishing on the server; open your FlutterFlow project to reconcile before retrying.");if(!f.success){const h=f.details?` ${f.details}`:"",p=`${f.error||"FlutterFlow custom class provisioning failed."}${h}`;throw Hu(f)===Le.UNCONFIRMED?new Qe(`${p} The failure arrived after the deploy began — custom classes may already be written. Open your FlutterFlow project to reconcile before retrying.`):new Error(p)}}catch(h){throw h instanceof Qe&&sr(t),h}return sr(t),f.verificationSkipped&&(console.warn(`[custom class deploy] ${f.verificationSkipped}`),u.push(f.verificationSkipped)),{remoteFiles:n,syncFileMap:s_(e,o),unverified:u,approximate:c,provisionSucceeded:!0}}async function Wl(t,e={}){const n=qh(t);let i=za.get(n);if(i===void 0){try{i=await t.fetchProjectSource()}catch(l){throw new Error(`Could not read your project's pubspec.yaml (${l.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=yh(i.pubspecYaml);if(!a.valid)throw new Error(`Your project's pubspec.yaml could not be read reliably (${a.errors.join("; ")}). Deploy was stopped so your existing package dependencies aren't overwritten.`);za.set(n,i)}const r=await vy(i.pubspecYaml,e),s=q_(i.pubspecYaml,r.overrides),o=z_(s.yaml,r.additions);return r.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>`${a}: ${r.additions[a]||"any"}`).join(", "),r.sdk.dartSdkFloor?`(resolved for Dart ${r.sdk.dartSdkFloor})`:""),r.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:s.overridden,warnings:r.warnings,remoteFiles:i.files}}function I0(t){const e=[],n=[];t.content.length>5e4&&n.push("Code file is large (>50KB). This may take longer to commit."),t.content.length>1e5&&e.push("Code file is too large (>100KB). Consider splitting into smaller components.");const i=t.content.split(` +`).length;i>500&&n.push(`Code has ${i} lines. Consider breaking it into smaller widgets.`),t.content.includes("setState")&&t.codeType===J.ACTION&&n.push("Using setState in a Custom Action may not work as expected. Consider using a Custom Widget."),t.content.includes("dynamic")&&!t.content.includes("?")&&n.push('Code uses "dynamic" types. Consider adding explicit types for better null safety.'),t.content.match(/Color\(0xFF[0-9A-Fa-f]{6}\)/)&&n.push("Code contains hardcoded colors. Consider using FlutterFlowTheme.of(context) for theme consistency.");const r=t.content.match(/print\s*\(/g);r&&r.length>3&&n.push(`Code contains ${r.length} print statements. Consider removing debug prints before committing.`);const s=S_(t.content);if(s&&e.push(`FlutterFlow cannot format this code - ${s}. Fix or regenerate before committing.`),t.codeType===J.WIDGET){const o=uh(t.content),a=w_(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=`${dh(o[0])}`;e.push(`Widget class name "${o[0]}" does not match the file name "${t.fileName}". FlutterFlow derives the widget from the file name, so it will report "No widget ${a} found". Rename the file to "${l}" or the class to match before committing.`)}}return{canProceed:e.length===0,issues:e,warnings:n}}function Vh(t,e={}){const{artifactType:n="CustomWidget",artifactName:i="GeneratedCode",fileName:r}=e,s=__(t);let o=r||i;if(n==="CustomFunction")o="custom_functions.dart";else if(n==="CustomWidget"){const u=uh(s)[0],c=u?dh(u):null;c&&o!==c?(console.warn(`Commit file name "${o}" does not match declared widget class "${u}"; renaming to "${c}" so FlutterFlow can find the widget.`),o=c):o.endsWith(".dart")||(o+=".dart")}else o.endsWith(".dart")||(o+=".dart");let a=J.CODE_FILE;switch(n){case"CustomAction":a=J.ACTION;break;case"CustomWidget":a=J.WIDGET;break;case"CustomFunction":a=J.FUNCTION;break;case"CustomClass":case"CodeFile":a=J.CODE_FILE;break}let l="";return a===J.WIDGET?l=`// Automatic FlutterFlow imports import '/flutter_flow/flutter_flow_theme.dart'; import '/flutter_flow/flutter_flow_util.dart'; import 'package:flutter/material.dart'; @@ -111,15 +111,15 @@ import '/flutter_flow/lat_lng.dart'; import '/flutter_flow/place.dart'; import '/flutter_flow/uploaded_file.dart'; -`),{content:Gv(s,l),fileName:o,codeType:a,artifactType:n,artifactName:i}}function I0(t){const e={};for(const n of wl(t))e[n]="";return e}function k0(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 C0(t,e,n,i=new Set,r=""){const s=[],o=Uh.test(e),a=Hh.test(e);return n===J.WIDGET&&!o&&!a&&s.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:s.length===0,errors:s}}function js(t){const e=[],n=[];if(!t||t.size===0)return e.push("No files to commit"),{valid:!1,errors:e,warnings:n};const i=new Set(Array.from(t.values()).flatMap(r=>As(r.content||"")));for(const[r,s]of t.entries()){if((!s.content||s.content.trim().length===0)&&e.push(`File ${r} is empty`),s.content&&s.content.length>1e5&&n.push(`File ${r} is very large (>100KB)`),r.endsWith(".dart")){const o=C0(r,s.content,s.type,i,s.artifactName);o.valid||e.push(...o.errors.map(a=>`${r}: ${a}`))}if(r==="pubspec.yaml"){const o=_h(s.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:n}}const ee={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},G={currentState:ee.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=ee.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(ee).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===ee.PREPARING&&(this.startTime=Date.now()),(t===ee.SUCCESS||t===ee.ERROR)&&(this.endTime=Date.now()),typeof window<"u"&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("commitStateChange",{detail:{state:t,commitState:this}})),console.log(`Commit state changed to: ${t}`)},setError(t){this.error=t,this.setState(ee.ERROR)},setSuccess(t){this.result=t,this.setState(ee.SUCCESS)},setProgress(t,e){this.filesProcessed=t,this.totalFiles=e},getElapsedTime(){return this.startTime?(this.endTime||Date.now())-this.startTime:null},isInProgress(){return this.currentState===ee.PREPARING||this.currentState===ee.VALIDATING||this.currentState===ee.PUSHING}};async function A0(t,e,n={}){let{codeType:i="W"}=n;const{pubspecDeps:r={},artifactName:s=e}=n;i==="CustomWidget"&&(i=J.WIDGET),i==="CustomAction"&&(i=J.ACTION),i==="CustomFunction"&&(i=J.FUNCTION),i==="CustomClass"&&(i=J.CODE_FILE),i==="CodeFile"&&(i=J.CODE_FILE),G.reset(),G.setState(ee.PREPARING);try{const o=await Te("flutterflow"),a=await Te("flutterflow_project_id");if(!o||!a)throw new Error("FlutterFlow credentials not configured. Please set your API key and Project ID in the API Keys settings.");if(!Os(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=yt(),u=new hi(o,a,"main",l);G.setState(ee.VALIDATING);const c=new Map,d=i||S0(e,t),h=Wh(e,d);c.set(e,{artifactName:s,content:t,type:d,path:h}),G.setProgress(0,c.size);const f=js(c);if(!f.valid)throw new Error(`Validation failed: -${f.errors.join(` -`)}`);const p=await Hl(u,r),g=p.yaml,m=await Ul(u,c,p.remoteFiles,`Provision ${s} custom class`,g),v=await Dl(m.syncFileMap,m.remoteFiles),E=new Map(m.syncFileMap);E.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),Be.set("package");const S=await Wl(E),_={project_id:a,zipped_custom_code:S,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};G.setState(ee.PUSHING),G.setProgress(1,c.size),sr(u),Be.set("push");const b=await jl(u,_);if(b.success)G.setSuccess({fileCount:c.size,projectId:a,warnings:b.errorMap&&b.errorMap.size>0?Array.from(b.errorMap.entries()):[]});else{const k=b.errorMessage||Bl(b.responseCode),T=new Error(k);throw T.remoteRefusal=!0,T}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:p.added,unverified:m.unverified,approximate:m.approximate,warnings:b.errorMap?Array.from(b.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),G.setError(o),o instanceof Qe?{success:!1,unconfirmed:!0,error:o.message,state:G.currentState}:{success:!1,error:o.message,remoteRefusal:o.remoteRefusal===!0,state:G.currentState}}}async function Wl(t){const e=new JSZip;for(const[n,i]of t.entries())e.file(n,i.content);return e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}async function P0(t,e={}){const{artifactType:n,artifactName:i,fileName:r,pipelineResult:s}=e;console.log(`Starting commit for ${i} (${n})`);let o=!1;const a={projectId:null,endpoint:yt(),artifactType:n,artifactName:i,fileName:r};try{G.setState(ee.PREPARING);const l=Vh(t,{artifactType:n,artifactName:i,fileName:r}),u=I0(l.content);console.log("Detected dependencies:",u),G.setState(ee.VALIDATING);const c=await Te("flutterflow"),d=zi||await Te("flutterflow_project_id");if(!c)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!d)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Os(d))throw new Error("Invalid FlutterFlow Project ID format.");a.projectId=d;const h=new Map;h.set(l.fileName,{artifactName:i,content:l.content,type:l.codeType,path:Wh(l.fileName,l.codeType),functionName:l.codeType===J.FUNCTION?i:void 0}),G.setProgress(0,h.size);const f=js(h);if(!f.valid)throw new Error(`File validation failed: -${f.errors.join(` -`)}`);f.warnings.length>0&&console.warn("Validation warnings:",f.warnings),G.setState(ee.PUSHING);const p=yt(),g=new hi(c,d,"main",p),m=await Hl(g,u),v=m.yaml,E=await Ul(g,h,m.remoteFiles,`Provision ${i} custom class`,v);o=E.provisionSucceeded===!0;const S=await Dl(E.syncFileMap,E.remoteFiles),_=new Map(E.syncFileMap);_.set("pubspec.yaml",{content:v,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Be.set("package");const b=await Wl(_),k={project_id:d,zipped_custom_code:b,uid:`web_${Date.now()}`,branch_name:g.branchName,serialized_yaml:v,file_map:S.fileMapContents,functions_map:S.functionsMapContents};G.setProgress(1,h.size),sr(g),Be.set("push");const T=await jl(g,k);if(T.success){const x={...k0(l,s),projectId:d};return G.setSuccess({...x,fileCount:h.size,warnings:T.errorMap?Array.from(T.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${l.fileName} to FlutterFlow`,metadata:x,targetIdentity:a,addedDependencies:m.added,unverified:E.unverified,approximate:E.approximate,warnings:T.errorMap?Array.from(T.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}else{const x=T.errorMessage||Bl(T.responseCode),F=new Error(x);throw F.errorMap=T.errorMap,F.remoteRefusal=!0,F}}catch(l){console.error("Commit execution failed:",l),G.setError(l);let u=new Map;if(l.errorMap)u=l.errorMap;else if(l.message&&l.message.includes("{"))try{const c=l.message.match(/\{[\s\S]*\}/);if(c){const d=JSON.parse(c[0]);u=new Map(Object.entries(d))}}catch(c){console.warn("Failed to parse error map from commit response:",c)}return l instanceof Qe?{success:!1,unconfirmed:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:o?{success:!1,partial:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:l.message,errorMap:u,remoteRefusal:l.remoteRefusal===!0,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function F0(t,e={}){const{pipelineResult:n}=e;let i=!1;const r={projectId:null,endpoint:yt(),artifactType:"Bundle",artifactName:t?.title,fileName:t?.fileEntries?`${t.fileEntries.length} artifacts`:"bundle"};try{if(G.setState(ee.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: +`),{content:Gv(s,l),fileName:o,codeType:a,artifactType:n,artifactName:i}}function k0(t){const e={};for(const n of bl(t))e[n]="";return e}function C0(t,e={}){return{timestamp:new Date().toISOString(),artifactType:t.artifactType,artifactName:t.artifactName,codeType:t.codeType,fileName:t.fileName,generatedFrom:e.step1Result?"pipeline":"direct",model:e.selectedModel||"unknown",codeSize:t.content.length}}function A0(t,e,n,i=new Set,r=""){const s=[],o=Hh.test(e),a=Wh.test(e);return n===J.WIDGET&&!o&&!a&&s.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:s.length===0,errors:s}}function Us(t){const e=[],n=[];if(!t||t.size===0)return e.push("No files to commit"),{valid:!1,errors:e,warnings:n};const i=new Set(Array.from(t.values()).flatMap(r=>Ps(r.content||"")));for(const[r,s]of t.entries()){if((!s.content||s.content.trim().length===0)&&e.push(`File ${r} is empty`),s.content&&s.content.length>1e5&&n.push(`File ${r} is very large (>100KB)`),r.endsWith(".dart")){const o=A0(r,s.content,s.type,i,s.artifactName);o.valid||e.push(...o.errors.map(a=>`${r}: ${a}`))}if(r==="pubspec.yaml"){const o=yh(s.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:n}}const ee={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},G={currentState:ee.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=ee.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(ee).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===ee.PREPARING&&(this.startTime=Date.now()),(t===ee.SUCCESS||t===ee.ERROR)&&(this.endTime=Date.now()),typeof window<"u"&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("commitStateChange",{detail:{state:t,commitState:this}})),console.log(`Commit state changed to: ${t}`)},setError(t){this.error=t,this.setState(ee.ERROR)},setSuccess(t){this.result=t,this.setState(ee.SUCCESS)},setProgress(t,e){this.filesProcessed=t,this.totalFiles=e},getElapsedTime(){return this.startTime?(this.endTime||Date.now())-this.startTime:null},isInProgress(){return this.currentState===ee.PREPARING||this.currentState===ee.VALIDATING||this.currentState===ee.PUSHING}};async function P0(t,e,n={}){let{codeType:i="W"}=n;const{pubspecDeps:r={},artifactName:s=e}=n;i==="CustomWidget"&&(i=J.WIDGET),i==="CustomAction"&&(i=J.ACTION),i==="CustomFunction"&&(i=J.FUNCTION),i==="CustomClass"&&(i=J.CODE_FILE),i==="CodeFile"&&(i=J.CODE_FILE),G.reset(),G.setState(ee.PREPARING);try{const o=await Te("flutterflow"),a=await Te("flutterflow_project_id");if(!o||!a)throw new Error("FlutterFlow credentials not configured. Please set your API key and Project ID in the API Keys settings.");if(!Bs(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=yt(),u=new hi(o,a,"main",l);G.setState(ee.VALIDATING);const c=new Map,d=i||x0(e,t),f=zh(e,d);c.set(e,{artifactName:s,content:t,type:d,path:f}),G.setProgress(0,c.size);const h=Us(c);if(!h.valid)throw new Error(`Validation failed: +${h.errors.join(` +`)}`);const p=await Wl(u,r),g=p.yaml,m=await Hl(u,c,p.remoteFiles,`Provision ${s} custom class`,g),v=await jl(m.syncFileMap,m.remoteFiles),E=new Map(m.syncFileMap);E.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),Be.set("package");const S=await zl(E),_={project_id:a,zipped_custom_code:S,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};G.setState(ee.PUSHING),G.setProgress(1,c.size),sr(u),Be.set("push");const b=await Ul(u,_);if(b.success)G.setSuccess({fileCount:c.size,projectId:a,warnings:b.errorMap&&b.errorMap.size>0?Array.from(b.errorMap.entries()):[]});else{const k=b.errorMessage||Dl(b.responseCode),T=new Error(k);throw T.remoteRefusal=!0,T}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:p.added,unverified:m.unverified,approximate:m.approximate,warnings:b.errorMap?Array.from(b.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),G.setError(o),o instanceof Qe?{success:!1,unconfirmed:!0,error:o.message,state:G.currentState}:{success:!1,error:o.message,remoteRefusal:o.remoteRefusal===!0,state:G.currentState}}}async function zl(t){const e=new JSZip;for(const[n,i]of t.entries())e.file(n,i.content);return e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}async function F0(t,e={}){const{artifactType:n,artifactName:i,fileName:r,pipelineResult:s}=e;console.log(`Starting commit for ${i} (${n})`);let o=!1;const a={projectId:null,endpoint:yt(),artifactType:n,artifactName:i,fileName:r};try{G.setState(ee.PREPARING);const l=Vh(t,{artifactType:n,artifactName:i,fileName:r}),u=k0(l.content);console.log("Detected dependencies:",u),G.setState(ee.VALIDATING);const c=await Te("flutterflow"),d=zi||await Te("flutterflow_project_id");if(!c)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!d)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Bs(d))throw new Error("Invalid FlutterFlow Project ID format.");a.projectId=d;const f=new Map;f.set(l.fileName,{artifactName:i,content:l.content,type:l.codeType,path:zh(l.fileName,l.codeType),functionName:l.codeType===J.FUNCTION?i:void 0}),G.setProgress(0,f.size);const h=Us(f);if(!h.valid)throw new Error(`File validation failed: +${h.errors.join(` +`)}`);h.warnings.length>0&&console.warn("Validation warnings:",h.warnings),G.setState(ee.PUSHING);const p=yt(),g=new hi(c,d,"main",p),m=await Wl(g,u),v=m.yaml,E=await Hl(g,f,m.remoteFiles,`Provision ${i} custom class`,v);o=E.provisionSucceeded===!0;const S=await jl(E.syncFileMap,E.remoteFiles),_=new Map(E.syncFileMap);_.set("pubspec.yaml",{content:v,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Be.set("package");const b=await zl(_),k={project_id:d,zipped_custom_code:b,uid:`web_${Date.now()}`,branch_name:g.branchName,serialized_yaml:v,file_map:S.fileMapContents,functions_map:S.functionsMapContents};G.setProgress(1,f.size),sr(g),Be.set("push");const T=await Ul(g,k);if(T.success){const x={...C0(l,s),projectId:d};return G.setSuccess({...x,fileCount:f.size,warnings:T.errorMap?Array.from(T.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${l.fileName} to FlutterFlow`,metadata:x,targetIdentity:a,addedDependencies:m.added,unverified:E.unverified,approximate:E.approximate,warnings:T.errorMap?Array.from(T.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}else{const x=T.errorMessage||Dl(T.responseCode),F=new Error(x);throw F.errorMap=T.errorMap,F.remoteRefusal=!0,F}}catch(l){console.error("Commit execution failed:",l),G.setError(l);let u=new Map;if(l.errorMap)u=l.errorMap;else if(l.message&&l.message.includes("{"))try{const c=l.message.match(/\{[\s\S]*\}/);if(c){const d=JSON.parse(c[0]);u=new Map(Object.entries(d))}}catch(c){console.warn("Failed to parse error map from commit response:",c)}return l instanceof Qe?{success:!1,unconfirmed:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:o?{success:!1,partial:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:l.message,errorMap:u,remoteRefusal:l.remoteRefusal===!0,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function R0(t,e={}){const{pipelineResult:n}=e;let i=!1;const r={projectId:null,endpoint:yt(),artifactType:"Bundle",artifactName:t?.title,fileName:t?.fileEntries?`${t.fileEntries.length} artifacts`:"bundle"};try{if(G.setState(ee.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: ${t.errors.join(` -`)}`);const s=new Map(t.fileEntries.map(b=>[b.fileName,{artifactId:b.artifactId,artifactName:b.artifactName,content:b.content,type:b.type,path:b.path,functionName:b.type===J.FUNCTION?b.artifactName:void 0}]));G.setProgress(0,s.size);const o=js(s);if(!o.valid)throw new Error(`File validation failed: +`)}`);const s=new Map(t.fileEntries.map(b=>[b.fileName,{artifactId:b.artifactId,artifactName:b.artifactName,content:b.content,type:b.type,path:b.path,functionName:b.type===J.FUNCTION?b.artifactName:void 0}]));G.setProgress(0,s.size);const o=Us(s);if(!o.valid)throw new Error(`File validation failed: ${o.errors.join(` -`)}`);G.setState(ee.VALIDATING);const a=await Te("flutterflow"),l=zi||await Te("flutterflow_project_id");if(!a)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!l)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Os(l))throw new Error("Invalid FlutterFlow Project ID format.");r.projectId=l,G.setState(ee.PUSHING);const u=yt(),c=new hi(a,l,"main",u),d=await Hl(c,t.dependencies),h=d.yaml,f=await Ul(c,s,d.remoteFiles,`Provision ${t.title} custom classes`,h);i=f.provisionSucceeded===!0;const p=await Dl(f.syncFileMap,f.remoteFiles),g=new Map(f.syncFileMap);g.set("pubspec.yaml",{content:h,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Be.set("package");const m=await Wl(g),v={project_id:l,zipped_custom_code:m,uid:`web_${Date.now()}`,branch_name:c.branchName,serialized_yaml:h,file_map:p.fileMapContents,functions_map:p.functionsMapContents};G.setProgress(1,s.size),sr(c),Be.set("push");const E=await jl(c,v);if(E.success){const b={...n,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((k,T)=>k+T.content.length,0),projectId:l};return G.setSuccess({...b,fileCount:s.size,warnings:E.errorMap?Array.from(E.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:b,targetIdentity:r,addedDependencies:d.added,unverified:f.unverified,approximate:f.approximate,warnings:E.errorMap?Array.from(E.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}const S=E.errorMessage||Bl(E.responseCode),_=new Error(S);throw _.errorMap=E.errorMap,_.remoteRefusal=!0,_}catch(s){console.error("Bundle commit execution failed:",s),G.setError(s);const o=s.errorMap||new Map;return s instanceof Qe?{success:!1,unconfirmed:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:i?{success:!1,partial:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function R0(t,e=[]){const n=ml("architect");try{return await Ss("architect",Rh,pv(t),n,e)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Prompt Architect failed: ${i.message}`)}}async function Us(t,e,n=[],i){const r=gv(t),s=ml("generator",y.bundleSpec);try{return await Ss("generator",e,r,s,n)}catch(o){if(o.isModelArmor||o.isUsageLimit||o.isPipelineCancel)throw o;if(e!==kr){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,o.message),Nw(e,kr,i);try{return await Ss("generator",kr,r,s,n)}catch(a){throw a.isModelArmor||a.isUsageLimit||a.isPipelineCancel?a:new Error(`Code Generator failed: primary (${e}): ${o.message} | fallback (${kr}): ${a.message}`)}}throw new Error(`Code Generator failed: ${o.message}`)}}async function Hs(t,e=null){const n={...ml("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await Ss("review",Th,mv(t),n)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Code Review failed: ${i.message}`)}}function bs(t,e){const n=document.getElementById(`step${t}-item`),i=document.getElementById(`step${t}-status`);!n||!i||(n.classList.remove("active","completed","error"),i.classList.remove("running","completed","error"),e==="active"?(n.classList.add("active"),i.classList.add("running"),i.innerHTML=` +`)}`);G.setState(ee.VALIDATING);const a=await Te("flutterflow"),l=zi||await Te("flutterflow_project_id");if(!a)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!l)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Bs(l))throw new Error("Invalid FlutterFlow Project ID format.");r.projectId=l,G.setState(ee.PUSHING);const u=yt(),c=new hi(a,l,"main",u),d=await Wl(c,t.dependencies),f=d.yaml,h=await Hl(c,s,d.remoteFiles,`Provision ${t.title} custom classes`,f);i=h.provisionSucceeded===!0;const p=await jl(h.syncFileMap,h.remoteFiles),g=new Map(h.syncFileMap);g.set("pubspec.yaml",{content:f,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Be.set("package");const m=await zl(g),v={project_id:l,zipped_custom_code:m,uid:`web_${Date.now()}`,branch_name:c.branchName,serialized_yaml:f,file_map:p.fileMapContents,functions_map:p.functionsMapContents};G.setProgress(1,s.size),sr(c),Be.set("push");const E=await Ul(c,v);if(E.success){const b={...n,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((k,T)=>k+T.content.length,0),projectId:l};return G.setSuccess({...b,fileCount:s.size,warnings:E.errorMap?Array.from(E.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:b,targetIdentity:r,addedDependencies:d.added,unverified:h.unverified,approximate:h.approximate,warnings:E.errorMap?Array.from(E.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}const S=E.errorMessage||Dl(E.responseCode),_=new Error(S);throw _.errorMap=E.errorMap,_.remoteRefusal=!0,_}catch(s){console.error("Bundle commit execution failed:",s),G.setError(s);const o=s.errorMap||new Map;return s instanceof Qe?{success:!1,unconfirmed:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:i?{success:!1,partial:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function T0(t,e=[]){const n=vl("architect");try{return await xs("architect",Th,pv(t),n,e)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Prompt Architect failed: ${i.message}`)}}async function Hs(t,e,n=[],i){const r=gv(t),s=vl("generator",y.bundleSpec);try{return await xs("generator",e,r,s,n)}catch(o){if(o.isModelArmor||o.isUsageLimit||o.isPipelineCancel)throw o;if(e!==kr){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,o.message),Ow(e,kr,i);try{return await xs("generator",kr,r,s,n)}catch(a){throw a.isModelArmor||a.isUsageLimit||a.isPipelineCancel?a:new Error(`Code Generator failed: primary (${e}): ${o.message} | fallback (${kr}): ${a.message}`)}}throw new Error(`Code Generator failed: ${o.message}`)}}async function Ws(t,e=null){const n={...vl("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await xs("review",$h,mv(t),n)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Code Review failed: ${i.message}`)}}function Es(t,e){const n=document.getElementById(`step${t}-item`),i=document.getElementById(`step${t}-status`);!n||!i||(n.classList.remove("active","completed","error"),i.classList.remove("running","completed","error"),e==="active"?(n.classList.add("active"),i.classList.add("running"),i.innerHTML=` `):e==="completed"?(n.classList.add("completed"),i.classList.add("completed"),i.innerHTML=` @@ -127,12 +127,12 @@ ${o.errors.join(` `):i.innerHTML=` - `)}function Ae(t,e){const n=document.getElementById(`step${t}-loading`),i=document.getElementById(`step${t}-result`);e?(n.classList.remove("hidden"),i.classList.add("hidden"),bs(t,"active")):(n.classList.add("hidden"),i.classList.remove("hidden"),bs(t,"completed"))}function T0(t){const e=document.getElementById(`${t}-content`),n=document.getElementById(`${t}-chevron`);e.classList.contains("open")?(e.classList.remove("open"),n&&(n.style.transform="rotate(0deg)")):(e.classList.add("open"),n&&(n.style.transform="rotate(180deg)"))}function $0(t){it(parseInt(t.replace("step","")))}function it(t){for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-item`);a&&a.classList.remove("active")}const e=document.getElementById(`step${t}-item`);e&&e.classList.add("active"),Nn();const n=document.getElementById("ready-state");n&&n.classList.add("hidden");for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-content`);a&&a.classList.add("hidden")}const i=document.getElementById(`step${t}-content`);i&&i.classList.remove("hidden");const r=document.getElementById("stage-title"),s={1:"Prompt Architect",2:"Code Generator",3:"Code Review"};r&&(r.textContent=s[t]||"Active Workflow Stage")}function M0(t){const e=document.getElementById(t);if(!e)return;const n=e.dataset.raw||e.textContent;navigator.clipboard.writeText(n).then(()=>{const r=e.closest(".code-container")?.querySelector(".copy-btn");r&&(r.classList.add("copied"),r.innerHTML=' Copied!',setTimeout(()=>{r.classList.remove("copied"),r.innerHTML=' Copy'},2e3))}).catch(i=>{console.warn("Failed to copy to clipboard:",i)})}function za(t){const e=qa(t);console.log(`Step 1 (Prompt Architect): ${Gt(Rh)}`),console.log(e!==t?`Step 2 (Code Generator): ${Gt(t)} → ${Gt(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${Gt(t)}`),console.log(`Step 3 (Code Review): ${Gt(Th)}`)}function Gh(){return{step1Result:y.step1Result,step2Result:y.step2Result,step3Result:y.step3Result,artifactBundle:y.artifactBundle,bundleReview:y.bundleReview,selectedArtifactId:y.selectedArtifactId}}function L0(t){if(!t)return;Object.assign(y,t),new Set((y.artifactBundle?.artifacts||[]).map(n=>n.id)).has(y.selectedArtifactId)||(y.selectedArtifactId=oi(y.artifactBundle)?.id||null)}const Kh="results-replacement-error";function N0(t,{stage:e=2,runId:n,retry:i}){if(!re(n))return;const r=document.getElementById(Kh);if(!r)return;const s=Sh(t),o=document.getElementById("results-replacement-error-title"),a=document.getElementById("results-replacement-error-message"),l=document.getElementById("results-replacement-error-retry"),u=document.getElementById("results-replacement-error-upgrade");o&&(o.textContent=`${Vs[e]||"Regeneration"}: ${s.title}`),a&&(a.textContent=s.message),r.hidden=!1;let c=null;u&&(u.hidden=!s.canUpgrade,s.canUpgrade&&(u.textContent="View plans",u.onclick=()=>di(),c=u)),l&&(l.hidden=s.canUpgrade,s.canUpgrade||(l.onclick=()=>{zl(),typeof i=="function"&&i()},l.textContent="Retry",c=l)),(c||r).focus({preventScroll:!0})}function zl(){const t=document.getElementById(Kh);t&&(t.hidden=!0)}function Yh(t,{previous:e,stage:n,runId:i,retry:r}){re(i)&&(t.isUsageLimit&&un(),L0(e),cr(),nn(!0),ur(),eo(),N0(t,{stage:n,runId:i,retry:r}),rn())}async function Jh(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0;const e=Gs();ql("standardRegenerate",y.step2Result,y.step1Result);const n=document.querySelectorAll(".btn-refine-action"),i=Gh();n.forEach(r=>{r.disabled=!0,r.innerHTML=` + `)}function Ae(t,e){const n=document.getElementById(`step${t}-loading`),i=document.getElementById(`step${t}-result`);e?(n.classList.remove("hidden"),i.classList.add("hidden"),Es(t,"active")):(n.classList.add("hidden"),i.classList.remove("hidden"),Es(t,"completed"))}function $0(t){const e=document.getElementById(`${t}-content`),n=document.getElementById(`${t}-chevron`);e.classList.contains("open")?(e.classList.remove("open"),n&&(n.style.transform="rotate(0deg)")):(e.classList.add("open"),n&&(n.style.transform="rotate(180deg)"))}function M0(t){it(parseInt(t.replace("step","")))}function it(t){for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-item`);a&&a.classList.remove("active")}const e=document.getElementById(`step${t}-item`);e&&e.classList.add("active"),Nn();const n=document.getElementById("ready-state");n&&n.classList.add("hidden");for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-content`);a&&a.classList.add("hidden")}const i=document.getElementById(`step${t}-content`);i&&i.classList.remove("hidden");const r=document.getElementById("stage-title"),s={1:"Prompt Architect",2:"Code Generator",3:"Code Review"};r&&(r.textContent=s[t]||"Active Workflow Stage")}function L0(t){const e=document.getElementById(t);if(!e)return;const n=e.dataset.raw||e.textContent;navigator.clipboard.writeText(n).then(()=>{const r=e.closest(".code-container")?.querySelector(".copy-btn");r&&(r.classList.add("copied"),r.innerHTML=' Copied!',setTimeout(()=>{r.classList.remove("copied"),r.innerHTML=' Copy'},2e3))}).catch(i=>{console.warn("Failed to copy to clipboard:",i)})}function qa(t){const e=Va(t);console.log(`Step 1 (Prompt Architect): ${Gt(Th)}`),console.log(e!==t?`Step 2 (Code Generator): ${Gt(t)} → ${Gt(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${Gt(t)}`),console.log(`Step 3 (Code Review): ${Gt($h)}`)}function Gh(){return{step1Result:y.step1Result,step2Result:y.step2Result,step3Result:y.step3Result,artifactBundle:y.artifactBundle,bundleReview:y.bundleReview,selectedArtifactId:y.selectedArtifactId}}function N0(t){if(!t)return;Object.assign(y,t),new Set((y.artifactBundle?.artifacts||[]).map(n=>n.id)).has(y.selectedArtifactId)||(y.selectedArtifactId=oi(y.artifactBundle)?.id||null)}const Kh="results-replacement-error";function O0(t,{stage:e=2,runId:n,retry:i}){if(!re(n))return;const r=document.getElementById(Kh);if(!r)return;const s=xh(t),o=document.getElementById("results-replacement-error-title"),a=document.getElementById("results-replacement-error-message"),l=document.getElementById("results-replacement-error-retry"),u=document.getElementById("results-replacement-error-upgrade");o&&(o.textContent=`${Gs[e]||"Regeneration"}: ${s.title}`),a&&(a.textContent=s.message),r.hidden=!1;let c=null;u&&(u.hidden=!s.canUpgrade,s.canUpgrade&&(u.textContent="View plans",u.onclick=()=>di(),c=u)),l&&(l.hidden=s.canUpgrade,s.canUpgrade||(l.onclick=()=>{ql(),typeof i=="function"&&i()},l.textContent="Retry",c=l)),(c||r).focus({preventScroll:!0})}function ql(){const t=document.getElementById(Kh);t&&(t.hidden=!0)}function Yh(t,{previous:e,stage:n,runId:i,retry:r}){re(i)&&(t.isUsageLimit&&un(),N0(e),cr(),nn(!0),ur(),to(),O0(t,{stage:n,runId:i,retry:r}),rn())}async function Jh(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0;const e=Ks();Vl("standardRegenerate",y.step2Result,y.step1Result);const n=document.querySelectorAll(".btn-refine-action"),i=Gh();n.forEach(r=>{r.disabled=!0,r.innerHTML=` - Refining...`});try{zl();const r=Nl(),s=r.id,o=vv({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,artifactId:r.id,userFeedback:"Fix the issues listed in the audit report."});Zs({runId:e}),Ft(2,e),it(2),Ae(2,!0);const a=await Us(o,t,[],e);if(!re(e))return;y.step2Result=a,Bs(),tn(2,e);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),it(3),Ft(3,e),Ae(3,!0);const c=await Hs(y.step2Result,y.step1Result);if(!re(e))return;y.step3Result=c,Ds(),tn(3,e),y.artifactBundle?.artifacts?.some(f=>f.id===s)?y.selectedArtifactId=s:y.selectedArtifactId=oi(y.artifactBundle)?.id||null;const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const h=Ls(y.step3Result);ur(u,h)}catch(r){if(console.error("Refinement failed:",r),!re(e))return;const s=Ms(r,{architect:2,generator:2,review:3});Yh(r,{previous:i,stage:s,runId:e,retry:Jh})}finally{n.forEach(r=>{r.disabled=!1,r.textContent="Refine & Regenerate"}),re(e)&&(y.isRunning=!1,rn())}}async function ql(t,e,n){const i=`${_t}/connectFeedback`,r={type:t,code:e,input:n};try{const s=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok){const a=await s.text();return console.error(`callEndpoint failed: ${s.status} ${s.statusText}`,a),{success:!1,status:s.status,error:a}}const o=await s.json();return console.log("Telemetry success:",o),o}catch(s){return console.error("callEndpoint failed:",s),{success:!1,error:s.message}}}function O0(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function Zh(){const t=document.getElementById("ff-error-paste-input"),e=t?.value?.trim();if(!e){t?.focus(),t?.classList.add("ring-2","ring-red-400","border-red-300"),setTimeout(()=>t?.classList.remove("ring-2","ring-red-400","border-red-300"),2e3);return}if(!y.step2Result){Ee("No generated code found. Please run the full pipeline first.","warning");return}if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=Gs();ql("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` + Refining...`});try{ql();const r=Ol(),s=r.id,o=vv({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,artifactId:r.id,userFeedback:"Fix the issues listed in the audit report."});Xs({runId:e}),Ft(2,e),it(2),Ae(2,!0);const a=await Hs(o,t,[],e);if(!re(e))return;y.step2Result=a,Ds(),tn(2,e);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),it(3),Ft(3,e),Ae(3,!0);const c=await Ws(y.step2Result,y.step1Result);if(!re(e))return;y.step3Result=c,js(),tn(3,e),y.artifactBundle?.artifacts?.some(h=>h.id===s)?y.selectedArtifactId=s:y.selectedArtifactId=oi(y.artifactBundle)?.id||null;const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const f=Ns(y.step3Result);ur(u,f)}catch(r){if(console.error("Refinement failed:",r),!re(e))return;const s=Ls(r,{architect:2,generator:2,review:3});Yh(r,{previous:i,stage:s,runId:e,retry:Jh})}finally{n.forEach(r=>{r.disabled=!1,r.textContent="Refine & Regenerate"}),re(e)&&(y.isRunning=!1,rn())}}async function Vl(t,e,n){const i=`${_t}/connectFeedback`,r={type:t,code:e,input:n};try{const s=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok){const a=await s.text();return console.error(`callEndpoint failed: ${s.status} ${s.statusText}`,a),{success:!1,status:s.status,error:a}}const o=await s.json();return console.log("Telemetry success:",o),o}catch(s){return console.error("callEndpoint failed:",s),{success:!1,error:s.message}}}function B0(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function Zh(){const t=document.getElementById("ff-error-paste-input"),e=t?.value?.trim();if(!e){t?.focus(),t?.classList.add("ring-2","ring-red-400","border-red-300"),setTimeout(()=>t?.classList.remove("ring-2","ring-red-400","border-red-300"),2e3);return}if(!y.step2Result){Ee("No generated code found. Please run the full pipeline first.","warning");return}if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=Ks();Vl("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` - Fixing…`);const s=Gh();try{zl();const o=rh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});Ip(),Zs({runId:i}),Ft(2,i),it(2),Ae(2,!0);const a=await Us(o,n,[],i);if(!re(i))return;y.step2Result=a,Bs(),tn(2,i);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),it(3),Ft(3,i),Ae(3,!0);const c=await Hs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,Ds(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const h=Ls(y.step3Result);ur(u,h),t&&(t.value="")}catch(o){if(console.error("Fix from errors failed:",o),!re(i))return;const a=Ms(o,{architect:2,generator:2,review:3});Yh(o,{previous:s,stage:a,runId:i,retry:Zh})}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function or(){if(console.log("runThinkingPipeline called"),y.isRunning)return;localStorage.setItem("hasSeenWalkthrough","true");const t=document.getElementById("pipeline-input").value,e=document.getElementById("code-generator-model").value,n=Oe.slice();if(!t.trim()){Ee("Please describe your FlutterFlow widget first.","warning");return}y.isRunning=!0;const i=Gs();try{if(await Oa,!re(i)||(pn.length&&await Promise.allSettled(pn.map(v=>v.job)),!re(i))||!await aw()||!re(i)||(await tw(),!re(i)))return;const r=qa(e);t.length,_0(),y.submittedPrompt=t,y.submittedImages=n.filter(v=>v.url),Ka(!0),za(r),Nn();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const o=document.getElementById("paywall-exhausted");o&&o.classList.add("hidden"),Zs({prompt:t,runId:i}),jw(),it(1),Ft(1,i),Ae(1,!0);const a=y.submittedImages.map(v=>({url:v.url})),l=await R0(t,a);if(!re(i))return;y.step1Result=l,y0(),tn(1,i);const u=document.getElementById("step1-output"),c=li(y.step1Result);u.textContent=c,u.dataset.raw=c,Ae(1,!1),it(2),Ft(2,i),Ae(2,!0);const d=await Us(y.step1Result,r,a,i);if(!re(i))return;y.step2Result=d,Bs(),tn(2,i);const h=document.getElementById("step2-output"),f=li(y.step2Result);h.textContent=f,h.dataset.raw=f,Ae(2,!1),it(3),Ft(3,i),Ae(3,!0);const p=await Hs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=p,Ds(),tn(3,i);const g=document.getElementById("step3-output");g.textContent=y.step3Result,Ae(3,!1),cr();const m=Ls(y.step3Result);Uw(),ur(f,m)}catch(r){if(r.isPipelineCancel||console.error("Pipeline failed:",r),!re(i))return;const s=Ms(r,{architect:1,generator:2,review:3});r.isUsageLimit?un():(r.message,qa(document.getElementById("code-generator-model").value),void 0),it(s),Ae(s,!1),bp(r,{stage:s,runId:i}),bs(s,"error")}finally{re(i)&&(y.isRunning=!1,Ka(!1),rn())}}function B0(){const t=document.getElementById("code-generator-model").value,e=[ms,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(i=>i!==t),n=prompt(`Retry with different model? + Fixing…`);const s=Gh();try{ql();const o=sh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});Ip(),Xs({runId:i}),Ft(2,i),it(2),Ae(2,!0);const a=await Hs(o,n,[],i);if(!re(i))return;y.step2Result=a,Ds(),tn(2,i);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),it(3),Ft(3,i),Ae(3,!0);const c=await Ws(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,js(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const f=Ns(y.step3Result);ur(u,f),t&&(t.value="")}catch(o){if(console.error("Fix from errors failed:",o),!re(i))return;const a=Ls(o,{architect:2,generator:2,review:3});Yh(o,{previous:s,stage:a,runId:i,retry:Zh})}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function or(){if(console.log("runThinkingPipeline called"),y.isRunning)return;localStorage.setItem("hasSeenWalkthrough","true");const t=document.getElementById("pipeline-input").value,e=document.getElementById("code-generator-model").value,n=Oe.slice();if(!t.trim()){Ee("Please describe your FlutterFlow widget first.","warning");return}y.isRunning=!0;const i=Ks();try{if(await Ba,!re(i)||(pn.length&&await Promise.allSettled(pn.map(v=>v.job)),!re(i))||!await lw()||!re(i)||(await nw(),!re(i)))return;const r=Va(e);t.length,y0(),y.submittedPrompt=t,y.submittedImages=n.filter(v=>v.url),Ya(!0),qa(r),Nn();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const o=document.getElementById("paywall-exhausted");o&&o.classList.add("hidden"),Xs({prompt:t,runId:i}),Uw(),it(1),Ft(1,i),Ae(1,!0);const a=y.submittedImages.map(v=>({url:v.url})),l=await T0(t,a);if(!re(i))return;y.step1Result=l,w0(),tn(1,i);const u=document.getElementById("step1-output"),c=li(y.step1Result);u.textContent=c,u.dataset.raw=c,Ae(1,!1),it(2),Ft(2,i),Ae(2,!0);const d=await Hs(y.step1Result,r,a,i);if(!re(i))return;y.step2Result=d,Ds(),tn(2,i);const f=document.getElementById("step2-output"),h=li(y.step2Result);f.textContent=h,f.dataset.raw=h,Ae(2,!1),it(3),Ft(3,i),Ae(3,!0);const p=await Ws(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=p,js(),tn(3,i);const g=document.getElementById("step3-output");g.textContent=y.step3Result,Ae(3,!1),cr();const m=Ns(y.step3Result);Hw(),ur(h,m)}catch(r){if(r.isPipelineCancel||console.error("Pipeline failed:",r),!re(i))return;const s=Ls(r,{architect:1,generator:2,review:3});r.isUsageLimit?un():(r.message,Va(document.getElementById("code-generator-model").value),void 0),it(s),Ae(s,!1),bp(r,{stage:s,runId:i}),Es(s,"error")}finally{re(i)&&(y.isRunning=!1,Ya(!1),rn())}}function D0(){const t=document.getElementById("code-generator-model").value,e=[ms,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(i=>i!==t),n=prompt(`Retry with different model? Current: ${t} @@ -140,14 +140,14 @@ Options: 1. ${e[0]} 2. ${e[1]} -Enter 1 or 2:`);n==="1"?(document.getElementById("code-generator-model").value=e[0],or()):n==="2"&&(document.getElementById("code-generator-model").value=e[1],or())}async function D0(){const t=Ol();if(!t){Ee("No code to commit. Please run the pipeline first.","warning");return}const e=await Te("flutterflow"),n=await Te("flutterflow_project_id");if(!e||!n){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),Rl();return}if(y.artifactBundle?.artifacts?.length>1){await j0();return}const{artifactType:i,artifactName:r,fileName:s}=jh(),o=Vh(t,{artifactType:i,artifactName:r,fileName:s}),a=x0(o);if(!a.canProceed){Ee(`Pre-commit checks failed: ${a.issues.join("; ")}`,"error");return}Kl(o,a,null,null)}async function j0(){const t=await Te("flutterflow"),e=await Te("flutterflow_project_id");if(!t||!e){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),Rl();return}const n=e_(y.artifactBundle);if(n.errors.length>0){Ee(`Bundle validation failed: ${n.errors.join("; ")}`,"error");return}const i=new Map(n.fileEntries.map(a=>[a.fileName,{content:a.content,type:a.type,path:a.path}])),r=js(i),s={canProceed:r.valid&&n.errors.length===0,issues:[...n.errors,...r.errors],warnings:[...n.warnings,...r.warnings]};if(!s.canProceed){Ee(`Bundle validation failed: ${s.issues.join("; ")}`,"error");return}const o={content:n.fileEntries.map(a=>`// ${a.fileName} +Enter 1 or 2:`);n==="1"?(document.getElementById("code-generator-model").value=e[0],or()):n==="2"&&(document.getElementById("code-generator-model").value=e[1],or())}async function j0(){const t=Bl();if(!t){Ee("No code to commit. Please run the pipeline first.","warning");return}const e=await Te("flutterflow"),n=await Te("flutterflow_project_id");if(!e||!n){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),Tl();return}if(y.artifactBundle?.artifacts?.length>1){await U0();return}const{artifactType:i,artifactName:r,fileName:s}=Uh(),o=Vh(t,{artifactType:i,artifactName:r,fileName:s}),a=I0(o);if(!a.canProceed){Ee(`Pre-commit checks failed: ${a.issues.join("; ")}`,"error");return}Yl(o,a,null,null)}async function U0(){const t=await Te("flutterflow"),e=await Te("flutterflow_project_id");if(!t||!e){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),Tl();return}const n=e_(y.artifactBundle);if(n.errors.length>0){Ee(`Bundle validation failed: ${n.errors.join("; ")}`,"error");return}const i=new Map(n.fileEntries.map(a=>[a.fileName,{content:a.content,type:a.type,path:a.path}])),r=Us(i),s={canProceed:r.valid&&n.errors.length===0,issues:[...n.errors,...r.errors],warnings:[...n.warnings,...r.warnings]};if(!s.canProceed){Ee(`Bundle validation failed: ${s.issues.join("; ")}`,"error");return}const o={content:n.fileEntries.map(a=>`// ${a.fileName} ${a.content}`).join(` -`),fileName:`${n.fileEntries.length} files`,codeType:"bundle",artifactType:"Bundle",artifactName:n.title};Kl(o,s,n.dependencies,n)}function U0(t){let e=t.errorMap||new Map;!(e instanceof Map)&&typeof e=="object"&&(e=new Map(Object.entries(e)));let n=`
    +`),fileName:`${n.fileEntries.length} files`,codeType:"bundle",artifactType:"Bundle",artifactName:n.title};Yl(o,s,n.dependencies,n)}function H0(t){let e=t.errorMap||new Map;!(e instanceof Map)&&typeof e=="object"&&(e=new Map(Object.entries(e)));let n=`

    FlutterFlow Commit Failed

    ${z(t.error)}

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

    Errors:

    -
      `;for(const[r,s]of e.entries()){const o=El(s);n+=`
    • +
        `;for(const[r,s]of e.entries()){const o=Sl(s);n+=`
      • ${z(r)}: ${z(o)}
      • `}n+="
    "}n+="
    ",n+=`
    -
    `;const i=document.getElementById("step3-output");i&&(i.innerHTML=n,document.getElementById("btn-regenerate-from-error")?.addEventListener("click",()=>{Xh(t.error,e)}))}async function Xh(t,e){if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=Gs(),r=document.getElementById("btn-regenerate-from-error");r&&(r.disabled=!0,r.innerHTML=` +
    `;const i=document.getElementById("step3-output");i&&(i.innerHTML=n,document.getElementById("btn-regenerate-from-error")?.addEventListener("click",()=>{Xh(t.error,e)}))}async function Xh(t,e){if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=Ks(),r=document.getElementById("btn-regenerate-from-error");r&&(r.disabled=!0,r.innerHTML=` Fixing...`);try{let s=`The previous code had the following errors when committing to FlutterFlow: -`;if(e&&e.size>0)for(const[f,p]of e.entries()){const g=El(p);s+=`File: ${f} +`;if(e&&e.size>0)for(const[h,p]of e.entries()){const g=Sl(p);s+=`File: ${h} Error: ${g} `}else s+=`${t} -`;const o=rh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:s});Zs({runId:i}),Ft(2,i),it(2),Ae(2,!0);const a=await Us(o,n,[],i);if(!re(i))return;y.step2Result=a,Bs(),tn(2,i);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),it(3),Ft(3,i),Ae(3,!0);const c=await Hs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,Ds(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const h=Ls(y.step3Result);ur(u,h)}catch(s){if(console.error("Regeneration failed:",s),!re(i))return;const o=Ms(s,{architect:2,generator:2,review:3});s.isUsageLimit&&un(),it(o),Ae(o,!1),bp(s,{stage:o,runId:i,retry:()=>Xh(t,e)}),bs(o,"error")}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function H0(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const n=await Te("flutterflow"),i=await Te("flutterflow_project_id");n&&i?(t.className="w-2 h-2 rounded-full bg-green-500",e.textContent="FlutterFlow credentials configured",e.className="text-green-600"):n||i?(t.className="w-2 h-2 rounded-full bg-yellow-500",e.textContent="FlutterFlow credentials incomplete",e.className="text-yellow-600"):(t.className="w-2 h-2 rounded-full bg-red-500",e.textContent="FlutterFlow credentials not configured",e.className="text-red-600")}async function Qh(t){try{const e=await fetch(`${_t}/auth/send-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:t})});if(!e.ok)throw new Error(`Failed to send magic link: HTTP ${e.status}`);return e.json()}catch(e){throw console.error("sendMagicLink failed:",{email:t,message:e.message,stack:e.stack}),e}}async function W0(t){try{const n=await(await fetch(`${_t}/auth/verify-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})})).json();if(n.error||!n.email||!n.sessionToken)throw new Error(n.error||"Invalid or expired link");return n}catch(e){throw console.error("verifyMagicLink failed:",{message:e.message,stack:e.stack}),e}}async function z0(t){try{const e=await fetch(`${_t}/auth/refresh-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:t})});if(!e.ok)return console.error("refreshSession: non-OK response",{url:`${_t}/auth/refresh-session`,status:e.status}),null;const n=await e.json();return n.error||!n.email||!n.sessionToken?(console.warn("refreshSession: validation failed",{error:n.error,hasEmail:!!n.email,hasToken:!!n.sessionToken}),null):n}catch(e){return console.error("refreshSession: fetch failed",{url:`${_t}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function id(t,e){const n=tp(),i=(q.email||n.email)!==t;q.email=t,q.sessionToken=e,q.isVerified=!0,ce=Mn({isLoading:!0}),localStorage.setItem(hs,JSON.stringify({email:t,sessionToken:e})),i&&ap()}function ep(){q.email=null,q.sessionToken=null,q.isVerified=!1,ce=Mn({isResolved:!0}),localStorage.removeItem(hs),localStorage.removeItem(gs)}function tp(){try{const t=localStorage.getItem(hs);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(hs),{email:null,sessionToken:null}}}async function q0(){const e=new URLSearchParams(window.location.search).get("token");if(e){window.history.replaceState({},"",window.location.pathname+window.location.hash);try{const{email:n,sessionToken:i}=await W0(e);id(n,i),np();const r=rd();r&&!window.location.hash&&(window.location.hash=r)}catch(n){rd();const i=n.message||"Sign-in link invalid or expired.";Ee(i,"error"),Ws(),Jn(i,"error")}}else{const{email:n,sessionToken:i}=tp();if(n&&i){const r=await z0(i);r?id(r.email,r.sessionToken):ep()}}Vl()}function V0(){try{localStorage.setItem(Na,JSON.stringify({hash:window.location.hash||"#home",ts:Date.now()}))}catch(t){console.warn("rememberSignInReturnSurface: failed to persist return surface:",t)}}function rd(){try{const t=localStorage.getItem(Na);if(localStorage.removeItem(Na),!t)return null;const{hash:e,ts:n}=JSON.parse(t);return!e||typeof n!="number"||Date.now()-n>Ay?null:e}catch(t){return console.warn("consumeSignInReturnSurface: failed to read return surface:",t),null}}function Ws(){const t=document.getElementById("signin-modal");if(!t)return;V0(),document.getElementById("signin-email-input")?.removeAttribute("aria-invalid"),Jn(""),We(t)}function np(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&ze(e)}function Jn(t,e){const n=document.getElementById("signin-message");n&&(n.textContent=t||"",n.classList.remove("signin-message-success","signin-message-error"),e&&n.classList.add(`signin-message-${e}`))}async function G0(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),n=Fs(t?.value);if(!n||!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(n)||n.length>254){t?.setAttribute("aria-invalid","true"),Jn("Please enter a valid email address.","error");return}t?.removeAttribute("aria-invalid"),e&&(e.disabled=!0,e.textContent="Sending…");const r=fh(n);r&&Jn(r,"error");try{const s=await Qh(n),o=s?.code===dh;t&&!o&&(t.value=""),t?.setAttribute("aria-invalid",String(o)),Jn(hh(s,n),o?"error":"success"),e&&(e.disabled=!1,e.textContent=o?"Send Sign-in Link":"Sent!",o||setTimeout(()=>{e.textContent==="Sent!"&&(e.textContent="Send Sign-in Link")},2500))}catch(s){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:n,err:s}),Jn("Something went wrong. Please try again.","error"),e&&(e.disabled=!1,e.textContent="Send Sign-in Link")}}function K0(){q.email=null,q.sessionToken=null,q.isVerified=!1,ce=Mn({isResolved:!0}),O_({storage:window.localStorage,onIdentityChanged:Vl,onPlanChanged:qs})}const Y0=B_({sendLink:Qh,getEmail:()=>q.email||"",onState:J0});function J0(t){const e=document.getElementById("send-new-link-btn"),n=document.getElementById("send-new-link-msg");if(!e||!n)return;if(t.status==="pending"){e.disabled=!0,e.textContent="Sending…",n.className="acct-access-msg",n.textContent="Sending a fresh sign-in link…";return}if(t.status==="sent"){e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg",n.textContent=hh(t.data,q.email||"")||"Link sent — check your email.";return}e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg error";const i=t.error?.message?`Couldn't send a link right now. ${t.error.message}`:"Couldn't send a link right now. Please try again.";n.textContent=i}async function Z0(){await Y0()}function X0(){const t=L_(window.localStorage),e=t.length?`Cleared disposable UI caches: ${t.join(", ")}.`:"Nothing disposable to clear.";Ee(`${e} Your run count, identity and stored keys are kept.`,"info")}function Q0(){const t=document.getElementById("delete-unavailable-modal");t&&We(t,{trigger:document.activeElement})}function ew(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("delete-unavailable-modal");e&&ze(e)}function Vl(){const t=q.isVerified&&!!q.email,e=document.getElementById("auth-signedout"),n=document.getElementById("auth-signedin"),i=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),n&&n.classList.toggle("hidden",!t),i&&i.classList.toggle("hidden",t);const r=document.getElementById("auth-user-email");r&&(r.textContent=q.email||"");const s=document.getElementById("access-signed-email");s&&(s.textContent=q.email||""),uw(),qs()}async function ip(){try{if(typeof FingerprintJS>"u"){console.warn("resolveIdentity: FingerprintJS not loaded, skipping");return}const e=await(await FingerprintJS.load()).get(),n=e.visitorId,i=await fetch(Ty,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fingerprint:e.visitorId,cookie_id:n})});if(!i.ok)throw new Error(`Identity check HTTP ${i.status}`);const r=await i.json();if(ht.userId=r.user_id,ht.token=r.identity_token||null,ht.status=r.status,ht.resolved=!0,sessionStorage.setItem(Fy,r.user_id),ht.token&&sessionStorage.setItem(Ry,ht.token),r.usage_count!==void 0){const s=gn(),a=(r.usage_month||s)===s?r.usage_count:0;localStorage.setItem(Fn,JSON.stringify({count:a,month:s})),un()}console.log(`Identity resolved: ${r.status} (${r.user_id.slice(0,8)}...) usage: ${r.usage_count??"n/a"}`)}catch(t){console.error("resolveIdentity failed:",t)}}let Wo=null;function tw(t=5e3){return ht.resolved?Promise.resolve():(Wo||(Wo=ip().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([Wo,new Promise(e=>setTimeout(e,t))]))}function rp(){const t=gn();try{const e=localStorage.getItem(Fn);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Fn,month:t,err:e}),localStorage.removeItem(Fn),{count:0,month:t}}}function gn(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function lr(){const t=rp();return t.month!==gn()?{count:0,month:gn()}:t}function nw(){const e={count:lr().count+1,month:gn()};return localStorage.setItem(Fn,JSON.stringify(e)),e}function pi(){return!!ce.isLoading}function Tt(){return!!ce.isResolved}function iw(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(ps,e)?e:null}function rw(t){return t&&Object.entries(Ih).find(([,e])=>e===t)?.[0]||null}function Cr(...t){return t.find(e=>e!=null&&e!=="")}function sw(...t){return t.find(e=>e&&typeof e=="object")||{}}function ow(t){const e=t.data&&typeof t.data=="object"?t.data:t,n=sw(e.subscription,e.stripeSubscription,e.currentSubscription,e.customer?.subscriptions?.data?.[0],e.subscriptions?.data?.[0],e.subscriptions?.[0]),i=e.metadata||n.metadata||e.customer?.metadata||{},r=Cr(e.priceId,e.price_id,e.stripePriceId,e.stripe_price_id,n.priceId,n.price_id,n.plan?.id,n.price?.id,n.items?.data?.[0]?.price?.id,n.items?.[0]?.price?.id,n.lines?.data?.[0]?.price?.id),s=Cr(e.status,e.subscriptionStatus,e.subscription_status,n.status,"none"),o=iw(Cr(e.tier,e.plan,e.planId,e.plan_id,e.subscriptionTier,e.subscription_tier,e.product,e.productName,n.tier,n.plan,i.tier,i.plan)),a=$y.has(String(s).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||rw(r)||(a||l?"professional":"free");return Mn({tier:u,status:s,periodEnd:Cr(e.periodEnd,e.currentPeriodEnd,e.current_period_end,n.current_period_end,n.periodEnd,null),isResolved:!0})}function zs(){return ps[ce.tier]??ps.free}async function aw(){if(q.isVerified&&(!Tt()||pi())&&(await op({force:!0}),qs()),q.isVerified&&!Tt())return Ee("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=lr(),e=zs();if(t>=e)return sp(t,e,{openModal:!0}),!1;const n=Math.floor(e*.8);if(t>=n){const i=e-t;Ee(`${i} run${i===1?"":"s"} remaining this month.`,"warning")}return!0}function sd(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function sp(t,e,n={}){nn(!0);const i=document.getElementById("walkthrough-modal");i&&ze(i,{restoreFocus:!1});const r=document.getElementById("ready-state");r&&r.classList.add("hidden");const s=document.getElementById("preview-frame-container");s&&(s.style.display="none");const o=document.getElementById("main-stage-container");o&&o.classList.add("visible");const a=document.getElementById("results-view");a&&a.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar");const l=document.getElementById("pipeline-progress");l&&l.classList.remove("visible");const u=document.getElementById("paywall-exhausted");if(!u){Ee(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),di();return}const c=document.getElementById("paywall-exhausted-text");if(c){const h=ce.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"),n.openModal&&di()}function qa(t){return ce.tier==="free"&&Nr.includes(t)?ms:t}function lw(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const n=ce.tier,r=!(q.isVerified&&!Tt())&&n==="free";Array.from(e.options).forEach(o=>{const a=Gt(o.value),l=Nr.includes(o.value);o.textContent=l&&r?`${a} (PRO)`:a,o.disabled=!1}),r&&Nr.includes(e.value)&&(e.value=ms),e.disabled=!1,Vu.has(e)||(e.addEventListener("change",()=>{Tt()&&ce.tier==="free"&&Nr.includes(e.value)&&(e.value=ms,di()),za(e.value),kl()}),Vu.add(e));let s=document.getElementById("model-selector-free-notice");r?(s||(s=document.createElement("p"),s.id="model-selector-free-notice",s.className="text-xs text-gray-400 mt-1",t.appendChild(s)),s.innerHTML='Free plan — Gemini only. '):s&&s.remove(),za(e.value)}function Gl(){const t=q.isVerified&&!!q.email,e=t&&pi(),n=!t||Tt(),i=lr(),r=n?i.count:0,s=n?zs():0,o=Math.max(0,s-r),a=`${r} / ${s} runs this month`,l=gl,u=n?ce.tier||"free":null,c=document.getElementById("topbar-credits-count");c&&(e?c.textContent="…":n?c.textContent=String(o):c.textContent="—");const d=document.getElementById("credits-balance");d&&(e?d.textContent="Checking plan…":n?d.textContent=a:d.textContent="Plan check failed");const h=document.getElementById("usage-dialog-tier");h&&(e?h.textContent="Checking…":n?h.textContent=l[u]||"Free":h.textContent="Unavailable");const f=document.getElementById("usage-dialog-status");f&&(e?f.textContent="Verifying your subscription…":n?f.textContent="Runs reset at the start of each month.":f.textContent="Could not verify your subscription. Try again or sign out.");const p=document.getElementById("usage-counter");if(p)if(e&&t)p.textContent="Checking plan…",p.className="text-xs text-gray-500";else if(!n&&t)p.textContent="Plan check failed",p.className="text-xs text-red-600 font-medium";else{p.textContent=a;const g=s>0?r/s:0;p.className=g>=1?"text-xs text-red-600 font-medium":g>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500"}if(!t){const g=document.getElementById("guest-usage-text");if(g){const m=rp(),v=m.month===gn()?m.count??0:0;g.textContent=`${v} / ${ps.free} generations used`}}cw()}function cw(){if(!(q.isVerified&&!!q.email))return;const e=pi(),n=Tt(),i=lr(),r=n?i.count:0,s=n?zs():0,o=Math.max(0,s-r),a=n?ce.tier||"free":null,l={free:"Free",professional:"Pro",power:"Power"}[a]||"Free",u=q.email||"",c=u.split("@")[0]||u,d=document.getElementById("acct-avatar");d&&(d.textContent=(u[0]||"?").toUpperCase());const h=document.getElementById("acct-name");h&&(h.textContent=c||"—");const f=document.getElementById("acct-plan-tier"),p=document.getElementById("acct-plan-price"),g=document.getElementById("acct-plan-note"),m=document.getElementById("acct-renewal");if(f&&(f.textContent=e?"Checking…":n?l:"Plan unavailable"),p)if(e)p.textContent="—";else if(!n)p.textContent="—";else if(a==="free")p.textContent="$0 / month";else{const x=Oi(Ni[a]??0,Cl());p.textContent=`${x} / month`}if(g&&(e?g.textContent="Verifying your subscription…":n?a==="free"?g.textContent="No subscription. Upgrade for more generations.":g.textContent="billed monthly through Stripe":g.textContent="Could not verify your subscription. Check billing or sign out."),m){const x=Date.parse(ce.periodEnd||""),F=n&&a!=="free"&&!!ce.periodEnd&&!Number.isNaN(x);if(e)m.textContent="";else if(!n)m.textContent="";else if(a==="free")m.textContent="";else if(F){const $=new Date(x).toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"});m.textContent=`Renews ${$} · reset at the start of each month.`}else m.textContent="Renewal date is not available for this period."}const v=document.getElementById("acct-left-count"),E=document.getElementById("acct-left-limit"),S=document.getElementById("acct-reset-note");v&&(v.textContent=e?"…":n?String(o):"—"),E&&(E.textContent=e?"…":n?String(s):"—"),S&&(e?S.textContent="Checking plan…":n?S.textContent="Runs reset at the start of each month.":S.textContent="Plan check failed. Refresh or manage billing.");const _=document.getElementById("acct-used-count"),b=document.getElementById("acct-meter-fill"),k=document.getElementById("acct-meter-meta"),T=document.getElementById("acct-meter-track");if(_&&(_.textContent=e?"…":n?String(r):"—"),b){const x=n&&s>0?Math.min(100,Math.round(r/s*100)):0;b.style.width=`${x}%`}if(k)if(e)k.textContent="Checking…";else if(!n)k.textContent="Plan check failed";else if(s===0)k.textContent=`${r} of ${s}`;else{const x=Math.round(r/s*100);k.textContent=`${r} of ${s} · ${x}%`}T&&(e?T.setAttribute("aria-label","Checking usage…"):n?T.setAttribute("aria-label",`${r} of ${s} generations used`):T.setAttribute("aria-label","Usage unavailable")),vt()}function un(){if(Gl(),q.isVerified&&(pi()||!Tt())){sd();return}const{count:t}=lr(),e=zs();t>=e&&!y.isRunning?sp(t,e):sd()}function uw(){Gl()}async function op(t={}){const e=t.force===!0;if(!q.isVerified||!q.sessionToken){ce=Mn({isResolved:!0});return}ce={...ce,isLoading:!0,error:null};const n=localStorage.getItem(gs);if(!e&&n)try{const{data:i,email:r,ts:s,version:o}=JSON.parse(n);if(o===Gu&&r===q.email&&Date.now()-s<300*1e3){ce={...i,isLoading:!1,isResolved:i.isResolved!==!1};return}}catch(i){console.warn("Failed to parse subscription cache:",i,"| raw value:",n)}try{const r=await(await fetch(`${_t}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:q.sessionToken,user_id:ht.userId})})).json();if(r.error){if(["unauthorized","invalid session","expired session"].some(o=>String(r.error).toLowerCase().includes(o))){ep(),Vl();return}ce=Mn({isResolved:!1,error:r.error});return}ce=ow(r),localStorage.setItem(gs,JSON.stringify({version:Gu,data:ce,email:q.email,ts:Date.now()}))}catch(i){console.error("fetchSubscription failed:",i),ce={...ce,isLoading:!1,isResolved:!1,error:i.message}}}function ap(){localStorage.removeItem(gs)}async function dw(t){if(!q.isVerified||!q.sessionToken){lp(),Ws();return}if(!Ih[t]){Ee("Invalid plan selected.","error");return}const e=document.getElementById(`checkout-btn-${t}`);e&&(e.disabled=!0,e.textContent="Redirecting…");try{const i=await(await fetch(`${_t}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:q.sessionToken,currency:Cl()})})).json();if(i.error||!i.url)throw new Error(i.error||"Failed to create checkout session");const{url:r}=i;window.location.href=r}catch(n){console.error("startCheckout failed:",n),e&&(e.disabled=!1,e.textContent="Subscribe"),Ee("Could not start checkout. Please try again.","error")}}async function fw(t){if(!q.isVerified||!q.sessionToken){Ws();return}const e=t||document.getElementById("manage-billing-btn"),n=e?e.textContent:"";e&&(e.disabled=!0,e.textContent="Loading…");try{const r=await(await fetch(`${_t}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:q.sessionToken})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to open billing portal");const{url:s}=r;window.location.href=s}catch(i){console.error("openCustomerPortal failed:",i),e&&(e.disabled=!1,e.textContent=n),Ee("Could not open billing portal. Please try again.","error")}}const Es=new Set;function hw(){Es.forEach(t=>t.abort()),Es.clear()}async function Ss(t,e,n,i={},r=[]){const o=new AbortController;Es.add(o);let a=!1;const l=setTimeout(()=>{a=!0,o.abort()},12e4);try{const u=await fetch(Py,{method:"POST",headers:{"Content-Type":"application/json",...ht.token?{Authorization:`Bearer ${ht.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:ht.userId,step:t,model:e,prompt:n,images:r,context:i})}),c=await u.text();let d={};try{d=c?JSON.parse(c):{}}catch{d={}}if(u.status===429){d.serverCount!==void 0&&(localStorage.setItem(Fn,JSON.stringify({count:d.serverCount,month:gn()})),un());const p=new Error(d.message||"Monthly usage limit reached. Upgrade to continue.");throw p.isUsageLimit=!0,p.pipelineStep=t,p}const h=xv(d,t);if(h)throw h;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(d),"content type:",typeof d.content),!u.ok)throw new Error(`${d.message||d.error||"BuildShip pipeline error"} (HTTP ${u.status})`);if(t==="generator")if(d.usage_status==="success"&&Number.isFinite(d.usage_count)){const p=gn();(d.usage_month||p)===p&&(localStorage.setItem(Fn,JSON.stringify({count:d.usage_count,month:p})),un())}else nw(),un();let f=d.output||d.content;if(!f){const p=c?` (body: ${c.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${p}`)}return Array.isArray(f)&&(f=f.map(p=>typeof p=="string"?p:p.text||"").join("")),typeof f!="string"&&(f=JSON.stringify(f)),f}catch(u){if(u.name==="AbortError"){if(a)throw new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`);const c=new Error(`BuildShip ${t} request cancelled`);throw c.isPipelineCancel=!0,c}throw u instanceof TypeError?new Error(`BuildShip unreachable: ${u.message}`):u}finally{clearTimeout(l),Es.delete(o)}}let Va=!1;function pw(){const e=new URLSearchParams(window.location.search).get("checkout");return e==="success"?(window.history.replaceState({},"",window.location.pathname+window.location.hash),ap(),Va=!0):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname+window.location.hash),Ee("Checkout cancelled.","info")),e}function gw(){if(!Va)return;Va=!1;const t=ce.tier!=="free";Ee(t?"Subscription active! Your plan is live.":"Checkout complete — confirming your subscription. Check Manage billing if it does not update.",t?"success":"info")}function qs(){const t=q.isVerified&&!!q.email,e=ce.tier,n=t&&pi(),i=!t||Tt(),r=document.getElementById("subscription-tier-badge");if(r){const a=gl,l={free:"bg-gray-100 text-gray-600",professional:"bg-indigo-100 text-indigo-700",power:"bg-purple-100 text-purple-700",unresolved:"bg-red-50 text-red-600"};r.textContent=n?"Checking…":i?a[e]||"Free":"Plan unavailable",r.className=`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${i?l[e]||l.free:l.unresolved}`}const s=document.getElementById("upgrade-prompt");s&&s.classList.toggle("hidden",!t||n||!i||e!=="free");const o=document.getElementById("manage-billing-btn");o&&o.classList.toggle("hidden",!t||n||i&&e==="free"),mw(i?e:null),lw(),kl(),un(),kp()}function mw(t){const e=["bg-gray-100","text-gray-500","cursor-default"];Object.entries({professional:{btnId:"checkout-btn-professional",defaultText:"Subscribe"},power:{btnId:"checkout-btn-power",defaultText:"Subscribe"}}).forEach(([r,{btnId:s,defaultText:o}])=>{const a=document.getElementById(s);a&&(r===t?(a.disabled=!0,a.textContent="Current plan",a.classList.add(...e)):(a.disabled=!1,a.textContent=o,a.classList.remove(...e)))});const i=document.getElementById("free-tier-current");i&&i.classList.toggle("hidden",t!=="free")}function vw(){document.querySelectorAll(".pm-card[data-tier]").forEach(t=>{const e=t.dataset.tier,n=dv[e];if(!n)return;const i=t.querySelector("ul.pm-features");if(i){i.innerHTML="";for(const r of n){const s=document.createElement("li");s.textContent=r,i.appendChild(s)}}})}function Ga(){const t=Cl(),e=document.getElementById("pro-price"),n=document.getElementById("power-price"),i=document.getElementById("plans-pro-price"),r=document.getElementById("plans-power-price"),s=document.getElementById("pro-price-note"),o=document.getElementById("power-price-note"),a=document.getElementById("plans-pro-price-note"),l=document.getElementById("plans-power-price-note");e&&(e.textContent=Oi(Ni.professional,t)),n&&(n.textContent=Oi(Ni.power,t)),i&&(i.textContent=Oi(Ni.professional,t)),r&&(r.textContent=Oi(Ni.power,t));const u="billed monthly";s&&(s.textContent=u),o&&(o.textContent=u),a&&(a.textContent=u),l&&(l.textContent=u)}function di(){Ga();const t=document.getElementById("pricing-modal");t&&We(t),zy().then(()=>Ga())}function lp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&ze(e)}function Ee(t,e="info"){const n={success:"bg-green-600 text-white",error:"bg-red-600 text-white",warning:"bg-amber-500 text-white",info:"bg-gray-800 text-white"},i=document.createElement("div");i.className=`fixed bottom-6 left-1/2 -translate-x-1/2 px-5 py-3 rounded-lg text-sm font-medium shadow-lg z-50 transition-opacity duration-300 ${n[e]||n.info}`,i.textContent=t,document.body.appendChild(i),setTimeout(()=>{i.style.opacity="0",setTimeout(()=>i.remove(),300)},3500)}document.addEventListener("DOMContentLoaded",async()=>{lv(),hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),_w(),window.__heroField=ty(),window.__pipelineLogo=sy(),Ch=ky({onSubmit:or}),Oa=(async()=>{try{await q0(),pw(),await op()}catch(n){console.warn("Startup auth/subscription initialization failed:",n)}})(),await Oa,gw(),qs(),Ga(),vw(),await w0(),g0();const t=document.getElementById("flutterflow-endpoint-select");if(t){const n=yt();t.value=n}Dh(),ip();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{en===2&&e.value.trim().length>0&&(Tl(),Ns())}),e.addEventListener("blur",()=>{const n=document.getElementById("walkthrough-modal");en===2&&n&&We(n)}),e.addEventListener("keydown",n=>{if(n.key==="Tab"){const i=document.getElementById("walkthrough-modal");en===2&&i&&setTimeout(()=>{We(i)},100)}})),window.addEventListener("commitStateChange",n=>{const{state:i}=n.detail;i===ee.PREPARING||i===ee.VALIDATING||i===ee.PUSHING?(Be.phaseId||pp(),ad(i)):(i===ee.SUCCESS||i===ee.ERROR)&&(ad(i),setTimeout(Jl,1e3))}),ic()});function _w(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function yw(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Nn),document.addEventListener("keydown",Nn))}function Nn(){const t=document.getElementById("preview-frame-container"),e=document.getElementById("main-stage-container"),n=document.getElementById("ready-state");t&&(t.style.display="none"),e&&e.classList.add("visible"),n&&n.classList.remove("hidden");const i=document.getElementById("welcome-video-player");i&&i.removeEventListener("click",Nn),document.removeEventListener("keydown",Nn),Dh()}let qi=null;async function ww(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++Xu,n=()=>e===Xu,i=await Te("flutterflow"),r=await Te("flutterflow_project_id");if(n()){if(!i){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const o=await new hi(i,"","main",yt()).listProjects();if(!n())return;if(!o||o.length===0){t.innerHTML='';return}t.innerHTML='',o.forEach(a=>{const l=document.createElement("option");l.value=a.id||a.projectId||"",l.textContent=a.name||a.projectName||`Project ${a.id}`,t.appendChild(l)}),r&&(t.value=r)}catch(s){if(!n())return;console.error("Failed to load projects for deploy:",s),t.innerHTML=''}}}function bw(){return document.getElementById("confirm-project-select")?.value?.trim()||null}function Kl(t,e,n,i=null){qi={codeInfo:t,checks:e,deps:n,bundlePlan:i},document.getElementById("confirm-file-name").textContent=t.fileName,document.getElementById("confirm-artifact-type").textContent=t.artifactType,document.getElementById("confirm-file-size").textContent=`${(t.content.length/1024).toFixed(1)} KB`,document.getElementById("confirm-line-count").textContent=i?`${i.fileEntries.length} files`:t.content.split(` -`).length,ww();const r=document.getElementById("confirm-deps-list"),s=document.getElementById("confirm-deps-section");n&&Object.keys(n).length>0?(r.innerHTML=Object.entries(n).map(([u,c])=>{const d=c?`at least ${Qt(c)}`:"version resolved from your project";return`
  • • ${Qt(u)}: ${d}
  • `}).join(""),s.classList.remove("hidden")):s.classList.add("hidden");const o=document.getElementById("confirm-warnings-list"),a=document.getElementById("confirm-warnings-section");e.warnings&&e.warnings.length>0?(o.innerHTML=e.warnings.map(u=>`
  • • ${Qt(u)}
  • `).join(""),a.classList.remove("hidden")):a.classList.add("hidden"),document.getElementById("confirm-code-preview").textContent=t.content,document.getElementById("code-preview-content").classList.add("hidden"),document.getElementById("code-preview-chevron").style.transform="rotate(0deg)";const l=document.getElementById("commit-confirm-modal");l&&We(l)}function cp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&ze(e),qi=null}function Ew(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&ze(e);const n=["success-message","success-project-id","success-file-name","success-artifact-type","success-time","success-size"];for(const s of n){const o=document.getElementById(s);o&&(o.textContent="")}const i=document.getElementById("success-warnings-section");i&&i.classList.add("hidden");const r=document.getElementById("success-warnings-list");r&&(r.innerHTML="")}function up(t){const e=(m,v)=>{const E=document.getElementById(m);E&&(E.textContent=v||"")},n=t.metadata?.fileName||"",i=t.metadata?.projectId||"",r=t.metadata?.artifactType||"",s=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",i),e("success-file-name",n),e("success-artifact-type",r),e("success-time",s),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&i&&(u.href=`https://app.flutterflow.io/project/${i}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),h=t.unverified||[],f=t.approximate||[],p=t.warnings||[];(p.length>0||h.length>0||f.length>0)&&c&&d&&(d.innerHTML=[...h.map(m=>`
  • Not verified before deploying: ${z(String(m))}
  • `),...f.map(m=>`
  • Verified approximately: ${z(String(m))}
  • `),...p.map(([m,v])=>`
  • ${z(m)}: ${z(String(v))}
  • `)].join(""),c.classList.remove("hidden"));const g=document.getElementById("commit-success-modal");g&&We(g)}function dp(t){Jl(),U0(t);const e=t.remoteRefusal===!0;Yl(t,{heading:"Deploy failed",title:e?"FlutterFlow refused this deploy — nothing was confirmed written.":"The deploy failed before FlutterFlow confirmed anything.",guidance:e?"Review the error and any per-file outcomes above, fix them in your code or in FlutterFlow, then deploy again. A refusal is definitive: no part of this deploy was applied, so retrying is safe once the problem is fixed.":"Review the error above, fix it, then deploy again. The deploy stopped before a write was confirmed, so nothing was applied."})}function Yl(t,{heading:e,title:n,guidance:i}){const r=t.targetIdentity||{},s=document.getElementById("commit-terminal-modal");if(!s)return!1;const o=(f,p)=>{const g=document.getElementById(f);g&&(g.textContent=p||"")};o("terminal-heading",e),o("terminal-title",n),o("terminal-message",t.error||t.message||"");const a=document.getElementById("terminal-identity-list");if(a){const f=[["Project",r.projectId||t.metadata?.projectId],["Endpoint",r.endpoint],["File",r.fileName||t.metadata?.fileName],["Artifact",r.artifactType||t.metadata?.artifactType]];a.innerHTML=f.map(([p,g])=>`
    ${z(p)}:${z(String(g??"—"))}
    `).join("")}const l=document.getElementById("terminal-file-outcomes");let u=t.errorMap;u&&!(u instanceof Map)&&(u=new Map(Object.entries(u))),l&&u&&u.size>0?(l.innerHTML=[...u.entries()].map(([f,p])=>`
  • ${z(f)}: ${z(El(p))}
  • `).join(""),l.classList.remove("hidden")):l&&l.classList.add("hidden");const c=document.getElementById("terminal-guidance");c&&(c.innerHTML=i);const d=document.getElementById("terminal-open-ff-link"),h=r.projectId||t.metadata?.projectId;return d&&(d.href=h?`https://app.flutterflow.io/project/${h}`:"https://app.flutterflow.io/"),We(s),!0}function fp(t){Yl(t,{heading:"Deploy partially applied",title:"Some custom classes reached FlutterFlow, but the deploy did not fully complete.",guidance:"The custom classes the runner confirmed are already in your project and are not lost. Review the per-file errors above, fix them in FlutterFlow or regenerate, then deploy again. Open the project to see exactly what landed."})}function hp(t){Yl(t,{heading:"Deploy outcome not yet known",title:"This browser stopped waiting before the FlutterFlow server reported a result.",guidance:"The deploy may still be finishing on the server — it was not cancelled. Open your FlutterFlow project and confirm whether the class landed before retrying, so you do not push a duplicate or build on top of an unknown state."})}function Sw(t){t&&t.target!==t.currentTarget||ze(document.getElementById("commit-terminal-modal"))}function xw(){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 od={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}},Iw=[{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&&(Eu(e,!0,"Deploying to FlutterFlow"),We(e)),this.set("prepare")},set(t,e=null){if(!(!od[t]||t===this.phaseId)){if(!this.sequence.includes(t)){const n=this.sequence.indexOf("package");this.sequence.splice(n===-1?this.sequence.length:n,0,t)}this.phaseId=t,this.phaseStartedAt=Date.now(),this.substatus=e,this.liveSubstatus=!1,this.render(),this.timer&&clearInterval(this.timer),t!=="done"&&(this.timer=setInterval(()=>this.render(),500))}},setSubstatus(t){t&&(this.liveSubstatus=!0,this.substatus=t,this.render())},render(){const t=od[this.phaseId];if(!t)return;const e=(Date.now()-this.phaseStartedAt)/1e3,n=t.start+(t.end-t.start)*(1-Math.exp(-e/25));if(this.phaseId==="provision"&&!this.liveSubstatus){const o=Iw.filter(a=>e>=a.after).pop();o&&(this.substatus=o.text)}const i=this.sequence.indexOf(this.phaseId),s=[`Step ${i===-1?1:i+1} of ${this.sequence.length}`];e>=5&&s.push(kw(e)),gp(this.phaseId==="done"?100:n,t.message,s.join(" · "),this.substatus)},stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.phaseId=null;const t=document.getElementById("commit-progress-overlay");t&&(Eu(t,!1),ze(t,{force:!0,restoreFocus:!1}))}};function kw(t){const e=Math.floor(t);return e<60?`${e}s elapsed`:`${Math.floor(e/60)}m ${String(e%60).padStart(2,"0")}s elapsed`}function pp(t){Be.start(t)}function Jl(){Be.stop()}function gp(t,e,n,i=null){const r=document.getElementById("commit-progress-bar"),s=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");r&&(r.style.width=`${Math.round(t*10)/10}%`),s&&(s.textContent=e),o&&(o.textContent=n),a&&(a.textContent=i||"",a.classList.toggle("hidden",!i))}function ad(t){const e={[ee.PREPARING]:"prepare",[ee.VALIDATING]:"validate",[ee.PUSHING]:"project",[ee.SUCCESS]:"done"};if(t===ee.ERROR){Be.timer&&clearInterval(Be.timer),Be.timer=null,gp(100,"Failed","Error occurred");return}const n=e[t];n&&Be.set(n)}function Cw(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===J.CODE_FILE):t.codeInfo?.codeType===J.CODE_FILE}let mp=!1;function vp(t){mp=t;const e=document.querySelector("#commit-confirm-modal button[data-deploy-confirm]");e&&(e.disabled=t),[...document.querySelectorAll("[data-deploy-start]"),...document.querySelectorAll("#btn-deploy-to-ff")].forEach(i=>{i.disabled=t})}function ld(t){Jl(),vp(!1);const e=bh(t);e===Le.COMMITTED?up(t):e===Le.PARTIAL?fp(t):e===Le.UNCONFIRMED?hp(t):dp(t)}async function Aw(){if(!qi){console.error("No pending commit data");return}if(mp){console.warn("Deploy already in flight; ignoring duplicate confirm.");return}const t=qi;if(qi=null,zi=bw(),cp(),vp(!0),pp({withProvisioning:Cw(t)}),t.bundlePlan){const o=await F0(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});zi=null,ld(o);return}const{codeInfo:e}=t,{artifactType:n,artifactName:i,fileName:r}=jh(),s=await P0(e.content,{artifactType:n,artifactName:i,fileName:r,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});zi=null,ld(s)}window.runThinkingPipeline=or;window.toggleStep=$0;window.toggleSection=T0;window.selectWorkflowStep=it;window.copyCode=M0;window.retryWithDifferentModel=B0;window.openApiKeysModal=Rl;window.closeApiKeysModal=Oh;window.openComposerSettings=r0;window.closeComposerSettings=s0;window.walkthroughConnectAccount=i0;window.closeWalkthroughModal=a0;window.openWalkthroughModal=o0;window.advanceWalkthrough=Tl;window.commitToFlutterFlow=A0;function Pw(){const t=document.getElementById("pipeline-input");t&&t.focus()}function Fw(){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=Pw;window.openModelSelector=Fw;window.handlePromptImageSelect=Hy;window.removePromptImage=Wy;window.saveApiKeys=u0;window.validateFlutterFlowConnection=Ml;window.clearAllApiKeys=d0;window.toggleKeyVisibility=v0;window.handleWelcomeVideoEnd=yw;window.dismissWelcomeVideo=Nn;window.initiateCommitToFlutterFlow=D0;window.updateFlutterFlowCredentialStatus=H0;window.openCommitConfirmModal=Kl;window.closeCommitConfirmModal=cp;window.closeCommitSuccessModal=Ew;window.closeCommitTerminalModal=Sw;window.showCommitPartialModal=fp;window.showCommitUnconfirmedModal=hp;window.showCommitSuccessModal=up;window.showCommitFailureModal=dp;window.toggleCodePreview=xw;window.confirmCommitToFlutterFlow=Aw;window.runRefinement=Jh;window.regenerateFromPastedErrors=Zh;window.clearErrorInput=O0;window.setFlutterFlowEndpoint=n0;window.getFlutterFlowEndpoint=yt;window.commitProgress=Be;window.openSignInModal=Ws;window.closeSignInModal=np;window.handleMagicLinkRequest=G0;window.handleSignOut=K0;window.handleSendNewLink=Z0;window.handleClearCache=X0;window.handleDeleteAccount=Q0;window.closeDeleteUnavailableModal=ew;window.startCheckout=dw;window.openCustomerPortal=fw;window.openPricingModal=di;window.closePricingModal=lp;let jr=null,_p=null,On={1:"pending",2:"pending",3:"pending"},Zl=1,Xl=null;const Vs={1:"Prompt Architect",2:"Code Generator",3:"Code Review"},Rw={1:"Understanding your prompt",2:"Generating Dart code",3:"Running the code audit"},Tw={1:"Prompt understood",2:"Dart code generated",3:"Code audit complete"};function Gs(){return y.runId+=1,y.runId}function re(t){return t===void 0||t===y.runId}function $w(){y.runId+=1}function Ql(t){return document.getElementById(`pdot-${t}`)}function Ka(t){const e=document.getElementById("btn-run-pipeline")||document.getElementById("hero-send");e&&(e.disabled=t,e.classList.toggle("is-busy",t),t?e.setAttribute("aria-busy","true"):e.removeAttribute("aria-busy"))}function Ks(t){const e=document.getElementById("pipeline-progress");e&&(e.dataset.runState=t)}function Rn(t,e){On[t]=e;const n=Ql(t);if(!n)return;n.dataset.state=e,n.disabled=e==="pending"||e==="skipped";const i=Vs[t],r={pending:"not started",active:"in progress",done:"complete",failed:"failed",skipped:"not run"};n.setAttribute("aria-label",`Step ${t} of 3, ${i}: ${r[e]||e}`),e==="active"?n.setAttribute("aria-current","step"):n.removeAttribute("aria-current")}function Mw(){return[1,2,3].filter(t=>On[t]==="done").length}function Ys(){const t=document.getElementById("pipeline-progress-fill");t&&(t.style.width=`${Mw()/3*100}%`);const e=document.getElementById("progress-stage-count");e&&(e.textContent=`Step ${Zl} of 3`)}function Js(t,{done:e=!1}={}){const n=document.getElementById("progress-title-text"),i=document.getElementById("progress-substep-text"),r=On[t],s=e||r==="done";if(n&&(n.textContent=s?Tw[t]:Rw[t]),i){const o=s?" — complete":r==="failed"?" — stopped":"";i.textContent=`Step ${t} of 3 — ${Vs[t]}${o}`}}function Lw(t){On[t]==="pending"||On[t]==="skipped"||(Xl=t,[1,2,3].forEach(e=>{const n=Ql(e);n&&n.setAttribute("aria-pressed",String(e===t))}),Js(t))}function ec(){Xl=null,[1,2,3].forEach(t=>{const e=Ql(t);e&&e.removeAttribute("aria-pressed")})}function yp(t){const e=document.getElementById("pipeline-note");e&&(e.textContent=t||"",e.hidden=!t)}function Nw(t,e,n){re(n)&&yp(`${Gt(t)} did not answer. Continuing on ${Gt(e)}.`)}function tc(){const t=document.getElementById("pipeline-failure");if(!t)return;t.hidden=!0;const e=document.getElementById("pipeline-failure-actions");e&&e.replaceChildren()}const Ow=1120;function Bw(){const t=getComputedStyle(document.documentElement).getPropertyValue("--t-morph").trim(),e=Number.parseFloat(t);return Number.isFinite(e)&&e>0?e:Ow}let Qn=null,Ur=null;function Dw(){return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0}function dn(){if(Ur){try{Ur.cancel()}catch{}Ur=null}Qn&&(Qn.remove(),Qn=null),window.removeEventListener("resize",dn)}function wp(t,e){if(dn(),Dw()||!t||!e||!document.body||typeof Element.prototype.animate!="function")return;const n=t.getBoundingClientRect(),i=e.getBoundingClientRect();if(!n.width||!n.height||!i.width||!i.height)return;const r=document.createElement("div");r.className="composer-morph",r.setAttribute("aria-hidden","true"),r.style.cssText=`left:${i.left}px;top:${i.top}px;width:${i.width}px;height:${i.height}px;opacity:0;`,document.body.appendChild(r);const s=n.left+n.width/2-(i.left+i.width/2),o=n.top+n.height/2-(i.top+i.height/2),a=n.width/i.width,l=n.height/i.height,u=`translate(${s}px,${o}px) scale(${a},${l})`,c=r.animate([{transform:u,opacity:0,offset:0,easing:"cubic-bezier(.2,0,0,1)"},{transform:u,opacity:1,offset:.14,easing:"cubic-bezier(.4,0,.2,1)"},{transform:`translate(${s}px,${o}px) scale(${a*.93},${l*.93})`,opacity:1,offset:.28,easing:"cubic-bezier(.32,1.38,.5,1)"},{transform:"translate(0px,0px) scale(1,1)",opacity:1,offset:1}],{duration:Bw(),fill:"both"});Qn=r,Ur=c,window.addEventListener("resize",dn),c.onfinish=()=>{if(Qn!==r)return;const d=r.animate([{opacity:1},{opacity:0}],{duration:260,fill:"forwards"});d.onfinish=()=>{Qn===r&&dn()}}}function jw(){const e=document.getElementById("composer")?.getBoundingClientRect();e&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{wp({getBoundingClientRect:()=>e},document.getElementById("main-stage-container"))})})}function Uw(){wp(document.getElementById("pipeline-progress"),document.getElementById("main-stage-container"))}window.addEventListener("hashchange",dn);window.addEventListener("popstate",dn);function Zs(t={}){const{prompt:e=null,runId:n}=t;if(!re(n))return;Qs(),nn(!0);const i=document.getElementById("pipeline-progress"),r=document.getElementById("results-view"),s=document.getElementById("ready-state");if(s&&s.classList.add("hidden"),r&&r.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),i&&i.classList.add("visible"),Ks("running"),e!==null){const a=document.getElementById("pipeline-submitted-prompt");a&&(a.textContent=e)}_p=Date.now();const o=document.getElementById("progress-elapsed");o&&(o.textContent="0s"),On={1:"pending",2:"pending",3:"pending"},ec(),tc(),yp(""),[1,2,3].forEach(a=>Rn(a,"pending")),Ft(1,n),Hw()}function Ft(t,e){re(e)&&(Zl=t,ec(),[1,2,3].forEach(n=>{n===t?Rn(n,"active"):nt&&Rn(n,"pending")}),Js(t),Ys())}function tn(t,e){re(e)&&(Rn(t,"done"),Xl===null&&Js(t,{done:!0}),Ys())}function bp(t,{stage:e=1,runId:n,retry:i=Ep}={}){if(!re(n))return;Xs(),Qs(),dn(),Ks("failed"),nn(!0);const r=document.getElementById("pipeline-progress");r&&r.classList.add("visible");const s=document.getElementById("results-view");s&&s.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),Rn(e,"failed"),[1,2,3].forEach(p=>{p>e&&Rn(p,"pending")}),Zl=e,ec(),Js(e),Ys();const o=Sh(t),a=document.getElementById("pipeline-failure"),l=document.getElementById("pipeline-failure-title"),u=document.getElementById("pipeline-failure-message"),c=document.getElementById("pipeline-failure-hint"),d=document.getElementById("pipeline-failure-actions");if(!a||!l||!u||!d)return;if(a.dataset.kind=o.kind,l.textContent=`${Vs[e]}: ${o.title}`,u.textContent=o.message,c){const p=o.detail&&o.detail!==o.message?o.detail:"";c.textContent=p,c.hidden=!p}d.replaceChildren();const h=[o.canUpgrade&&{id:"upgrade",label:"View plans",variant:"primary",onClick:()=>di()},o.canRetry&&{id:"retry",label:"Retry",variant:o.canUpgrade?"secondary":"primary",onClick:i},o.canEdit&&{id:"edit",label:"Edit prompt",variant:"secondary",onClick:Ya}].filter(Boolean);!o.canEdit&&!o.canRetry&&h.push({id:"edit",label:"Back to prompt",variant:"secondary",onClick:Ya}),h.forEach(p=>{const g=document.createElement("button");g.type="button",g.textContent=p.label,g.dataset.action=p.id,g.dataset.variant=p.variant,g.addEventListener("click",p.onClick),d.appendChild(g)}),a.hidden=!1;const f=d.querySelector("button");f&&f.focus({preventScroll:!0})}function Ya(){$w(),hw(),y.isRunning=!1,Ka(!1),rn(),Ks("settled"),dn(),Xs(),Qs(),tc();const t=document.getElementById("pipeline-progress");t&&t.classList.remove("visible"),nn(!1);const e=document.getElementById("pipeline-input");e&&(y.submittedPrompt&&(e.value=y.submittedPrompt,e.dispatchEvent(new Event("input",{bubbles:!0}))),e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length))}function Ep(){const t=document.getElementById("pipeline-input");t&&y.submittedPrompt&&(t.value=y.submittedPrompt,t.dispatchEvent(new Event("input",{bubbles:!0}))),Oe=y.submittedImages.slice(),cn(),tc(),or()}function Hw(){Xs(),jr=setInterval(()=>{const t=(Date.now()-_p)/1e3,e=document.getElementById("progress-elapsed");e&&(e.textContent=`${Math.floor(t)}s`)},250)}function Xs(){jr&&(clearInterval(jr),jr=null)}let Vi=null;function Qs(){Vi&&(clearTimeout(Vi),Vi=null)}function cr(){Xs(),Qs(),Ks("settled"),Ys();const t=document.getElementById("pipeline-progress-fill");Vi=setTimeout(()=>{Vi=null;const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function Tn(t,e=""){const n={pass:'',warning:'',fail:'',info:''};return``}function Sp(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function Ww(){return m_({bundle:y.artifactBundle,reviewResult:y.step3Result})}function zw(t){return` +`;const o=sh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:s});Xs({runId:i}),Ft(2,i),it(2),Ae(2,!0);const a=await Hs(o,n,[],i);if(!re(i))return;y.step2Result=a,Ds(),tn(2,i);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),it(3),Ft(3,i),Ae(3,!0);const c=await Ws(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,js(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const f=Ns(y.step3Result);ur(u,f)}catch(s){if(console.error("Regeneration failed:",s),!re(i))return;const o=Ls(s,{architect:2,generator:2,review:3});s.isUsageLimit&&un(),it(o),Ae(o,!1),bp(s,{stage:o,runId:i,retry:()=>Xh(t,e)}),Es(o,"error")}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function W0(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const n=await Te("flutterflow"),i=await Te("flutterflow_project_id");n&&i?(t.className="w-2 h-2 rounded-full bg-green-500",e.textContent="FlutterFlow credentials configured",e.className="text-green-600"):n||i?(t.className="w-2 h-2 rounded-full bg-yellow-500",e.textContent="FlutterFlow credentials incomplete",e.className="text-yellow-600"):(t.className="w-2 h-2 rounded-full bg-red-500",e.textContent="FlutterFlow credentials not configured",e.className="text-red-600")}async function Qh(t){try{const e=await fetch(`${_t}/auth/send-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:t})});if(!e.ok)throw new Error(`Failed to send magic link: HTTP ${e.status}`);return e.json()}catch(e){throw console.error("sendMagicLink failed:",{email:t,message:e.message,stack:e.stack}),e}}async function z0(t){try{const n=await(await fetch(`${_t}/auth/verify-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})})).json();if(n.error||!n.email||!n.sessionToken)throw new Error(n.error||"Invalid or expired link");return n}catch(e){throw console.error("verifyMagicLink failed:",{message:e.message,stack:e.stack}),e}}async function q0(t){try{const e=await fetch(`${_t}/auth/refresh-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:t})});if(!e.ok)return console.error("refreshSession: non-OK response",{url:`${_t}/auth/refresh-session`,status:e.status}),null;const n=await e.json();return n.error||!n.email||!n.sessionToken?(console.warn("refreshSession: validation failed",{error:n.error,hasEmail:!!n.email,hasToken:!!n.sessionToken}),null):n}catch(e){return console.error("refreshSession: fetch failed",{url:`${_t}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function rd(t,e){const n=tp(),i=(q.email||n.email)!==t;q.email=t,q.sessionToken=e,q.isVerified=!0,ce=Mn({isLoading:!0}),localStorage.setItem(hs,JSON.stringify({email:t,sessionToken:e})),i&&ap()}function ep(){q.email=null,q.sessionToken=null,q.isVerified=!1,ce=Mn({isResolved:!0}),localStorage.removeItem(hs),localStorage.removeItem(gs)}function tp(){try{const t=localStorage.getItem(hs);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(hs),{email:null,sessionToken:null}}}async function V0(){const e=new URLSearchParams(window.location.search).get("token");if(e){window.history.replaceState({},"",window.location.pathname+window.location.hash);try{const{email:n,sessionToken:i}=await z0(e);rd(n,i),np();const r=sd();r&&!window.location.hash&&(window.location.hash=r)}catch(n){sd();const i=n.message||"Sign-in link invalid or expired.";Ee(i,"error"),zs(),Jn(i,"error")}}else{const{email:n,sessionToken:i}=tp();if(n&&i){const r=await q0(i);r?rd(r.email,r.sessionToken):ep()}}Gl()}function G0(){try{localStorage.setItem(Oa,JSON.stringify({hash:window.location.hash||"#home",ts:Date.now()}))}catch(t){console.warn("rememberSignInReturnSurface: failed to persist return surface:",t)}}function sd(){try{const t=localStorage.getItem(Oa);if(localStorage.removeItem(Oa),!t)return null;const{hash:e,ts:n}=JSON.parse(t);return!e||typeof n!="number"||Date.now()-n>Py?null:e}catch(t){return console.warn("consumeSignInReturnSurface: failed to read return surface:",t),null}}function zs(){const t=document.getElementById("signin-modal");if(!t)return;G0(),document.getElementById("signin-email-input")?.removeAttribute("aria-invalid"),Jn(""),We(t)}function np(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&ze(e)}function Jn(t,e){const n=document.getElementById("signin-message");n&&(n.textContent=t||"",n.classList.remove("signin-message-success","signin-message-error"),e&&n.classList.add(`signin-message-${e}`))}async function K0(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),n=Rs(t?.value);if(!n||!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(n)||n.length>254){t?.setAttribute("aria-invalid","true"),Jn("Please enter a valid email address.","error");return}t?.removeAttribute("aria-invalid"),e&&(e.disabled=!0,e.textContent="Sending…");const r=hh(n);r&&Jn(r,"error");try{const s=await Qh(n),o=s?.code===fh;t&&!o&&(t.value=""),t?.setAttribute("aria-invalid",String(o)),Jn(ph(s,n),o?"error":"success"),e&&(e.disabled=!1,e.textContent=o?"Send Sign-in Link":"Sent!",o||setTimeout(()=>{e.textContent==="Sent!"&&(e.textContent="Send Sign-in Link")},2500))}catch(s){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:n,err:s}),Jn("Something went wrong. Please try again.","error"),e&&(e.disabled=!1,e.textContent="Send Sign-in Link")}}function Y0(){q.email=null,q.sessionToken=null,q.isVerified=!1,ce=Mn({isResolved:!0}),O_({storage:window.localStorage,onIdentityChanged:Gl,onPlanChanged:Vs})}const J0=B_({sendLink:Qh,getEmail:()=>q.email||"",onState:Z0});function Z0(t){const e=document.getElementById("send-new-link-btn"),n=document.getElementById("send-new-link-msg");if(!e||!n)return;if(t.status==="pending"){e.disabled=!0,e.textContent="Sending…",n.className="acct-access-msg",n.textContent="Sending a fresh sign-in link…";return}if(t.status==="sent"){e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg",n.textContent=ph(t.data,q.email||"")||"Link sent — check your email.";return}e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg error";const i=t.error?.message?`Couldn't send a link right now. ${t.error.message}`:"Couldn't send a link right now. Please try again.";n.textContent=i}async function X0(){await J0()}function Q0(){const t=L_(window.localStorage),e=t.length?`Cleared disposable UI caches: ${t.join(", ")}.`:"Nothing disposable to clear.";Ee(`${e} Your run count, identity and stored keys are kept.`,"info")}function ew(){const t=document.getElementById("delete-unavailable-modal");t&&We(t,{trigger:document.activeElement})}function tw(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("delete-unavailable-modal");e&&ze(e)}function Gl(){const t=q.isVerified&&!!q.email,e=document.getElementById("auth-signedout"),n=document.getElementById("auth-signedin"),i=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),n&&n.classList.toggle("hidden",!t),i&&i.classList.toggle("hidden",t);const r=document.getElementById("auth-user-email");r&&(r.textContent=q.email||"");const s=document.getElementById("access-signed-email");s&&(s.textContent=q.email||""),dw(),Vs()}async function ip(){try{if(typeof FingerprintJS>"u"){console.warn("resolveIdentity: FingerprintJS not loaded, skipping");return}const e=await(await FingerprintJS.load()).get(),n=e.visitorId,i=await fetch($y,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fingerprint:e.visitorId,cookie_id:n})});if(!i.ok)throw new Error(`Identity check HTTP ${i.status}`);const r=await i.json();if(ht.userId=r.user_id,ht.token=r.identity_token||null,ht.status=r.status,ht.resolved=!0,sessionStorage.setItem(Ry,r.user_id),ht.token&&sessionStorage.setItem(Ty,ht.token),r.usage_count!==void 0){const s=gn(),a=(r.usage_month||s)===s?r.usage_count:0;localStorage.setItem(Fn,JSON.stringify({count:a,month:s})),un()}console.log(`Identity resolved: ${r.status} (${r.user_id.slice(0,8)}...) usage: ${r.usage_count??"n/a"}`)}catch(t){console.error("resolveIdentity failed:",t)}}let zo=null;function nw(t=5e3){return ht.resolved?Promise.resolve():(zo||(zo=ip().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([zo,new Promise(e=>setTimeout(e,t))]))}function rp(){const t=gn();try{const e=localStorage.getItem(Fn);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Fn,month:t,err:e}),localStorage.removeItem(Fn),{count:0,month:t}}}function gn(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function lr(){const t=rp();return t.month!==gn()?{count:0,month:gn()}:t}function iw(){const e={count:lr().count+1,month:gn()};return localStorage.setItem(Fn,JSON.stringify(e)),e}function pi(){return!!ce.isLoading}function Tt(){return!!ce.isResolved}function rw(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(ps,e)?e:null}function sw(t){return t&&Object.entries(kh).find(([,e])=>e===t)?.[0]||null}function Cr(...t){return t.find(e=>e!=null&&e!=="")}function ow(...t){return t.find(e=>e&&typeof e=="object")||{}}function aw(t){const e=t.data&&typeof t.data=="object"?t.data:t,n=ow(e.subscription,e.stripeSubscription,e.currentSubscription,e.customer?.subscriptions?.data?.[0],e.subscriptions?.data?.[0],e.subscriptions?.[0]),i=e.metadata||n.metadata||e.customer?.metadata||{},r=Cr(e.priceId,e.price_id,e.stripePriceId,e.stripe_price_id,n.priceId,n.price_id,n.plan?.id,n.price?.id,n.items?.data?.[0]?.price?.id,n.items?.[0]?.price?.id,n.lines?.data?.[0]?.price?.id),s=Cr(e.status,e.subscriptionStatus,e.subscription_status,n.status,"none"),o=rw(Cr(e.tier,e.plan,e.planId,e.plan_id,e.subscriptionTier,e.subscription_tier,e.product,e.productName,n.tier,n.plan,i.tier,i.plan)),a=My.has(String(s).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||sw(r)||(a||l?"professional":"free");return Mn({tier:u,status:s,periodEnd:Cr(e.periodEnd,e.currentPeriodEnd,e.current_period_end,n.current_period_end,n.periodEnd,null),isResolved:!0})}function qs(){return ps[ce.tier]??ps.free}async function lw(){if(q.isVerified&&(!Tt()||pi())&&(await op({force:!0}),Vs()),q.isVerified&&!Tt())return Ee("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=lr(),e=qs();if(t>=e)return sp(t,e,{openModal:!0}),!1;const n=Math.floor(e*.8);if(t>=n){const i=e-t;Ee(`${i} run${i===1?"":"s"} remaining this month.`,"warning")}return!0}function od(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function sp(t,e,n={}){nn(!0);const i=document.getElementById("walkthrough-modal");i&&ze(i,{restoreFocus:!1});const r=document.getElementById("ready-state");r&&r.classList.add("hidden");const s=document.getElementById("preview-frame-container");s&&(s.style.display="none");const o=document.getElementById("main-stage-container");o&&o.classList.add("visible");const a=document.getElementById("results-view");a&&a.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar");const l=document.getElementById("pipeline-progress");l&&l.classList.remove("visible");const u=document.getElementById("paywall-exhausted");if(!u){Ee(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),di();return}const c=document.getElementById("paywall-exhausted-text");if(c){const f=ce.tier;f==="free"?c.textContent=`You've used all ${e} free generations this month. Upgrade to Pro for 50 generations/month and access to all AI models.`:c.textContent=`You've used all ${e} generations this month on your ${f} plan. Your limit resets next month.`}const d=document.getElementById("paywall-signin-btn");d&&d.classList.toggle("hidden",q.isVerified),u.classList.remove("hidden"),n.openModal&&di()}function Va(t){return ce.tier==="free"&&Nr.includes(t)?ms:t}function cw(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const n=ce.tier,r=!(q.isVerified&&!Tt())&&n==="free";Array.from(e.options).forEach(o=>{const a=Gt(o.value),l=Nr.includes(o.value);o.textContent=l&&r?`${a} (PRO)`:a,o.disabled=!1}),r&&Nr.includes(e.value)&&(e.value=ms),e.disabled=!1,Gu.has(e)||(e.addEventListener("change",()=>{Tt()&&ce.tier==="free"&&Nr.includes(e.value)&&(e.value=ms,di()),qa(e.value),Cl()}),Gu.add(e));let s=document.getElementById("model-selector-free-notice");r?(s||(s=document.createElement("p"),s.id="model-selector-free-notice",s.className="text-xs text-gray-400 mt-1",t.appendChild(s)),s.innerHTML='Free plan — Gemini only. '):s&&s.remove(),qa(e.value)}function Kl(){const t=q.isVerified&&!!q.email,e=t&&pi(),n=!t||Tt(),i=lr(),r=n?i.count:0,s=n?qs():0,o=Math.max(0,s-r),a=`${r} / ${s} runs this month`,l=ml,u=n?ce.tier||"free":null,c=document.getElementById("topbar-credits-count");c&&(e?c.textContent="…":n?c.textContent=String(o):c.textContent="—");const d=document.getElementById("credits-balance");d&&(e?d.textContent="Checking plan…":n?d.textContent=a:d.textContent="Plan check failed");const f=document.getElementById("usage-dialog-tier");f&&(e?f.textContent="Checking…":n?f.textContent=l[u]||"Free":f.textContent="Unavailable");const h=document.getElementById("usage-dialog-status");h&&(e?h.textContent="Verifying your subscription…":n?h.textContent="Runs reset at the start of each month.":h.textContent="Could not verify your subscription. Try again or sign out.");const p=document.getElementById("usage-counter");if(p)if(e&&t)p.textContent="Checking plan…",p.className="text-xs text-gray-500";else if(!n&&t)p.textContent="Plan check failed",p.className="text-xs text-red-600 font-medium";else{p.textContent=a;const g=s>0?r/s:0;p.className=g>=1?"text-xs text-red-600 font-medium":g>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500"}if(!t){const g=document.getElementById("guest-usage-text");if(g){const m=rp(),v=m.month===gn()?m.count??0:0;g.textContent=`${v} / ${ps.free} generations used`}}uw()}function uw(){if(!(q.isVerified&&!!q.email))return;const e=pi(),n=Tt(),i=lr(),r=n?i.count:0,s=n?qs():0,o=Math.max(0,s-r),a=n?ce.tier||"free":null,l={free:"Free",professional:"Pro",power:"Power"}[a]||"Free",u=q.email||"",c=u.split("@")[0]||u,d=document.getElementById("acct-avatar");d&&(d.textContent=(u[0]||"?").toUpperCase());const f=document.getElementById("acct-name");f&&(f.textContent=c||"—");const h=document.getElementById("acct-plan-tier"),p=document.getElementById("acct-plan-price"),g=document.getElementById("acct-plan-note"),m=document.getElementById("acct-renewal");if(h&&(h.textContent=e?"Checking…":n?l:"Plan unavailable"),p)if(e)p.textContent="—";else if(!n)p.textContent="—";else if(a==="free")p.textContent="$0 / month";else{const x=Oi(Ni[a]??0,Al());p.textContent=`${x} / month`}if(g&&(e?g.textContent="Verifying your subscription…":n?a==="free"?g.textContent="No subscription. Upgrade for more generations.":g.textContent="billed monthly through Stripe":g.textContent="Could not verify your subscription. Check billing or sign out."),m){const x=Date.parse(ce.periodEnd||""),F=n&&a!=="free"&&!!ce.periodEnd&&!Number.isNaN(x);if(e)m.textContent="";else if(!n)m.textContent="";else if(a==="free")m.textContent="";else if(F){const $=new Date(x).toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"});m.textContent=`Renews ${$} · reset at the start of each month.`}else m.textContent="Renewal date is not available for this period."}const v=document.getElementById("acct-left-count"),E=document.getElementById("acct-left-limit"),S=document.getElementById("acct-reset-note");v&&(v.textContent=e?"…":n?String(o):"—"),E&&(E.textContent=e?"…":n?String(s):"—"),S&&(e?S.textContent="Checking plan…":n?S.textContent="Runs reset at the start of each month.":S.textContent="Plan check failed. Refresh or manage billing.");const _=document.getElementById("acct-used-count"),b=document.getElementById("acct-meter-fill"),k=document.getElementById("acct-meter-meta"),T=document.getElementById("acct-meter-track");if(_&&(_.textContent=e?"…":n?String(r):"—"),b){const x=n&&s>0?Math.min(100,Math.round(r/s*100)):0;b.style.width=`${x}%`}if(k)if(e)k.textContent="Checking…";else if(!n)k.textContent="Plan check failed";else if(s===0)k.textContent=`${r} of ${s}`;else{const x=Math.round(r/s*100);k.textContent=`${r} of ${s} · ${x}%`}T&&(e?T.setAttribute("aria-label","Checking usage…"):n?T.setAttribute("aria-label",`${r} of ${s} generations used`):T.setAttribute("aria-label","Usage unavailable")),vt()}function un(){if(Kl(),q.isVerified&&(pi()||!Tt())){od();return}const{count:t}=lr(),e=qs();t>=e&&!y.isRunning?sp(t,e):od()}function dw(){Kl()}async function op(t={}){const e=t.force===!0;if(!q.isVerified||!q.sessionToken){ce=Mn({isResolved:!0});return}ce={...ce,isLoading:!0,error:null};const n=localStorage.getItem(gs);if(!e&&n)try{const{data:i,email:r,ts:s,version:o}=JSON.parse(n);if(o===Ku&&r===q.email&&Date.now()-s<300*1e3){ce={...i,isLoading:!1,isResolved:i.isResolved!==!1};return}}catch(i){console.warn("Failed to parse subscription cache:",i,"| raw value:",n)}try{const r=await(await fetch(`${_t}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:q.sessionToken,user_id:ht.userId})})).json();if(r.error){if(["unauthorized","invalid session","expired session"].some(o=>String(r.error).toLowerCase().includes(o))){ep(),Gl();return}ce=Mn({isResolved:!1,error:r.error});return}ce=aw(r),localStorage.setItem(gs,JSON.stringify({version:Ku,data:ce,email:q.email,ts:Date.now()}))}catch(i){console.error("fetchSubscription failed:",i),ce={...ce,isLoading:!1,isResolved:!1,error:i.message}}}function ap(){localStorage.removeItem(gs)}async function fw(t){if(!q.isVerified||!q.sessionToken){lp(),zs();return}if(!kh[t]){Ee("Invalid plan selected.","error");return}const e=document.getElementById(`checkout-btn-${t}`);e&&(e.disabled=!0,e.textContent="Redirecting…");try{const i=await(await fetch(`${_t}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:q.sessionToken,currency:Al()})})).json();if(i.error||!i.url)throw new Error(i.error||"Failed to create checkout session");const{url:r}=i;window.location.href=r}catch(n){console.error("startCheckout failed:",n),e&&(e.disabled=!1,e.textContent="Subscribe"),Ee("Could not start checkout. Please try again.","error")}}async function hw(t){if(!q.isVerified||!q.sessionToken){zs();return}const e=t||document.getElementById("manage-billing-btn"),n=e?e.textContent:"";e&&(e.disabled=!0,e.textContent="Loading…");try{const r=await(await fetch(`${_t}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:q.sessionToken})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to open billing portal");const{url:s}=r;window.location.href=s}catch(i){console.error("openCustomerPortal failed:",i),e&&(e.disabled=!1,e.textContent=n),Ee("Could not open billing portal. Please try again.","error")}}const Ss=new Set;function pw(){Ss.forEach(t=>t.abort()),Ss.clear()}async function xs(t,e,n,i={},r=[]){const o=new AbortController;Ss.add(o);let a=!1;const l=setTimeout(()=>{a=!0,o.abort()},12e4);try{const u=await fetch(Fy,{method:"POST",headers:{"Content-Type":"application/json",...ht.token?{Authorization:`Bearer ${ht.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:ht.userId,step:t,model:e,prompt:n,images:r,context:i})}),c=await u.text();let d={};try{d=c?JSON.parse(c):{}}catch{d={}}if(u.status===429){d.serverCount!==void 0&&(localStorage.setItem(Fn,JSON.stringify({count:d.serverCount,month:gn()})),un());const p=new Error(d.message||"Monthly usage limit reached. Upgrade to continue.");throw p.isUsageLimit=!0,p.pipelineStep=t,p}const f=xv(d,t);if(f)throw f;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(d),"content type:",typeof d.content),!u.ok)throw new Error(`${d.message||d.error||"BuildShip pipeline error"} (HTTP ${u.status})`);if(t==="generator")if(d.usage_status==="success"&&Number.isFinite(d.usage_count)){const p=gn();(d.usage_month||p)===p&&(localStorage.setItem(Fn,JSON.stringify({count:d.usage_count,month:p})),un())}else iw(),un();let h=d.output||d.content;if(!h){const p=c?` (body: ${c.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${p}`)}return Array.isArray(h)&&(h=h.map(p=>typeof p=="string"?p:p.text||"").join("")),typeof h!="string"&&(h=JSON.stringify(h)),h}catch(u){if(u.name==="AbortError"){if(a)throw new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`);const c=new Error(`BuildShip ${t} request cancelled`);throw c.isPipelineCancel=!0,c}throw u instanceof TypeError?new Error(`BuildShip unreachable: ${u.message}`):u}finally{clearTimeout(l),Ss.delete(o)}}let Ga=!1;function gw(){const e=new URLSearchParams(window.location.search).get("checkout");return e==="success"?(window.history.replaceState({},"",window.location.pathname+window.location.hash),ap(),Ga=!0):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname+window.location.hash),Ee("Checkout cancelled.","info")),e}function mw(){if(!Ga)return;Ga=!1;const t=ce.tier!=="free";Ee(t?"Subscription active! Your plan is live.":"Checkout complete — confirming your subscription. Check Manage billing if it does not update.",t?"success":"info")}function Vs(){const t=q.isVerified&&!!q.email,e=ce.tier,n=t&&pi(),i=!t||Tt(),r=document.getElementById("subscription-tier-badge");if(r){const a=ml,l={free:"bg-gray-100 text-gray-600",professional:"bg-indigo-100 text-indigo-700",power:"bg-purple-100 text-purple-700",unresolved:"bg-red-50 text-red-600"};r.textContent=n?"Checking…":i?a[e]||"Free":"Plan unavailable",r.className=`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${i?l[e]||l.free:l.unresolved}`}const s=document.getElementById("upgrade-prompt");s&&s.classList.toggle("hidden",!t||n||!i||e!=="free");const o=document.getElementById("manage-billing-btn");o&&o.classList.toggle("hidden",!t||n||i&&e==="free"),vw(i?e:null),cw(),Cl(),un(),kp()}function vw(t){const e=["bg-gray-100","text-gray-500","cursor-default"];Object.entries({professional:{btnId:"checkout-btn-professional",defaultText:"Subscribe"},power:{btnId:"checkout-btn-power",defaultText:"Subscribe"}}).forEach(([r,{btnId:s,defaultText:o}])=>{const a=document.getElementById(s);a&&(r===t?(a.disabled=!0,a.textContent="Current plan",a.classList.add(...e)):(a.disabled=!1,a.textContent=o,a.classList.remove(...e)))});const i=document.getElementById("free-tier-current");i&&i.classList.toggle("hidden",t!=="free")}function _w(){document.querySelectorAll(".pm-card[data-tier]").forEach(t=>{const e=t.dataset.tier,n=dv[e];if(!n)return;const i=t.querySelector("ul.pm-features");if(i){i.innerHTML="";for(const r of n){const s=document.createElement("li");s.textContent=r,i.appendChild(s)}}})}function Ka(){const t=Al(),e=document.getElementById("pro-price"),n=document.getElementById("power-price"),i=document.getElementById("plans-pro-price"),r=document.getElementById("plans-power-price"),s=document.getElementById("pro-price-note"),o=document.getElementById("power-price-note"),a=document.getElementById("plans-pro-price-note"),l=document.getElementById("plans-power-price-note");e&&(e.textContent=Oi(Ni.professional,t)),n&&(n.textContent=Oi(Ni.power,t)),i&&(i.textContent=Oi(Ni.professional,t)),r&&(r.textContent=Oi(Ni.power,t));const u="billed monthly";s&&(s.textContent=u),o&&(o.textContent=u),a&&(a.textContent=u),l&&(l.textContent=u)}function di(){Ka();const t=document.getElementById("pricing-modal");t&&We(t),qy().then(()=>Ka())}function lp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&ze(e)}function Ee(t,e="info"){const n={success:"bg-green-600 text-white",error:"bg-red-600 text-white",warning:"bg-amber-500 text-white",info:"bg-gray-800 text-white"},i=document.createElement("div");i.className=`fixed bottom-6 left-1/2 -translate-x-1/2 px-5 py-3 rounded-lg text-sm font-medium shadow-lg z-50 transition-opacity duration-300 ${n[e]||n.info}`,i.textContent=t,document.body.appendChild(i),setTimeout(()=>{i.style.opacity="0",setTimeout(()=>i.remove(),300)},3500)}document.addEventListener("DOMContentLoaded",async()=>{lv(),hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),yw(),window.__heroField=ny(),window.__pipelineLogo=oy(),Ah=Cy({onSubmit:or}),Ba=(async()=>{try{await V0(),gw(),await op()}catch(n){console.warn("Startup auth/subscription initialization failed:",n)}})(),await Ba,mw(),Vs(),Ka(),_w(),await b0(),m0();const t=document.getElementById("flutterflow-endpoint-select");if(t){const n=yt();t.value=n}jh(),ip();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{en===2&&e.value.trim().length>0&&($l(),Os())}),e.addEventListener("blur",()=>{const n=document.getElementById("walkthrough-modal");en===2&&n&&We(n)}),e.addEventListener("keydown",n=>{if(n.key==="Tab"){const i=document.getElementById("walkthrough-modal");en===2&&i&&setTimeout(()=>{We(i)},100)}})),window.addEventListener("commitStateChange",n=>{const{state:i}=n.detail;i===ee.PREPARING||i===ee.VALIDATING||i===ee.PUSHING?(Be.phaseId||pp(),ld(i)):(i===ee.SUCCESS||i===ee.ERROR)&&(ld(i),setTimeout(Zl,1e3))}),rc()});function yw(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function ww(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Nn),document.addEventListener("keydown",Nn))}function Nn(){const t=document.getElementById("preview-frame-container"),e=document.getElementById("main-stage-container"),n=document.getElementById("ready-state");t&&(t.style.display="none"),e&&e.classList.add("visible"),n&&n.classList.remove("hidden");const i=document.getElementById("welcome-video-player");i&&i.removeEventListener("click",Nn),document.removeEventListener("keydown",Nn),jh()}let qi=null;async function bw(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++Qu,n=()=>e===Qu,i=await Te("flutterflow"),r=await Te("flutterflow_project_id");if(n()){if(!i){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const o=await new hi(i,"","main",yt()).listProjects();if(!n())return;if(!o||o.length===0){t.innerHTML='';return}t.innerHTML='',o.forEach(a=>{const l=document.createElement("option");l.value=a.id||a.projectId||"",l.textContent=a.name||a.projectName||`Project ${a.id}`,t.appendChild(l)}),r&&(t.value=r)}catch(s){if(!n())return;console.error("Failed to load projects for deploy:",s),t.innerHTML=''}}}function Ew(){return document.getElementById("confirm-project-select")?.value?.trim()||null}function Yl(t,e,n,i=null){qi={codeInfo:t,checks:e,deps:n,bundlePlan:i},document.getElementById("confirm-file-name").textContent=t.fileName,document.getElementById("confirm-artifact-type").textContent=t.artifactType,document.getElementById("confirm-file-size").textContent=`${(t.content.length/1024).toFixed(1)} KB`,document.getElementById("confirm-line-count").textContent=i?`${i.fileEntries.length} files`:t.content.split(` +`).length,bw();const r=document.getElementById("confirm-deps-list"),s=document.getElementById("confirm-deps-section");n&&Object.keys(n).length>0?(r.innerHTML=Object.entries(n).map(([u,c])=>{const d=c?`at least ${Qt(c)}`:"version resolved from your project";return`
  • • ${Qt(u)}: ${d}
  • `}).join(""),s.classList.remove("hidden")):s.classList.add("hidden");const o=document.getElementById("confirm-warnings-list"),a=document.getElementById("confirm-warnings-section");e.warnings&&e.warnings.length>0?(o.innerHTML=e.warnings.map(u=>`
  • • ${Qt(u)}
  • `).join(""),a.classList.remove("hidden")):a.classList.add("hidden"),document.getElementById("confirm-code-preview").textContent=t.content,document.getElementById("code-preview-content").classList.add("hidden"),document.getElementById("code-preview-chevron").style.transform="rotate(0deg)";const l=document.getElementById("commit-confirm-modal");l&&We(l)}function cp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&ze(e),qi=null}function Sw(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&ze(e);const n=["success-message","success-project-id","success-file-name","success-artifact-type","success-time","success-size"];for(const s of n){const o=document.getElementById(s);o&&(o.textContent="")}const i=document.getElementById("success-warnings-section");i&&i.classList.add("hidden");const r=document.getElementById("success-warnings-list");r&&(r.innerHTML="")}function up(t){const e=(m,v)=>{const E=document.getElementById(m);E&&(E.textContent=v||"")},n=t.metadata?.fileName||"",i=t.metadata?.projectId||"",r=t.metadata?.artifactType||"",s=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",i),e("success-file-name",n),e("success-artifact-type",r),e("success-time",s),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&i&&(u.href=`https://app.flutterflow.io/project/${i}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),f=t.unverified||[],h=t.approximate||[],p=t.warnings||[];(p.length>0||f.length>0||h.length>0)&&c&&d&&(d.innerHTML=[...f.map(m=>`
  • Not verified before deploying: ${z(String(m))}
  • `),...h.map(m=>`
  • Verified approximately: ${z(String(m))}
  • `),...p.map(([m,v])=>`
  • ${z(m)}: ${z(String(v))}
  • `)].join(""),c.classList.remove("hidden"));const g=document.getElementById("commit-success-modal");g&&We(g)}function dp(t){Zl(),H0(t);const e=t.remoteRefusal===!0;Jl(t,{heading:"Deploy failed",title:e?"FlutterFlow refused this deploy — nothing was confirmed written.":"The deploy failed before FlutterFlow confirmed anything.",guidance:e?"Review the error and any per-file outcomes above, fix them in your code or in FlutterFlow, then deploy again. A refusal is definitive: no part of this deploy was applied, so retrying is safe once the problem is fixed.":"Review the error above, fix it, then deploy again. The deploy stopped before a write was confirmed, so nothing was applied."})}function Jl(t,{heading:e,title:n,guidance:i}){const r=t.targetIdentity||{},s=document.getElementById("commit-terminal-modal");if(!s)return!1;const o=(h,p)=>{const g=document.getElementById(h);g&&(g.textContent=p||"")};o("terminal-heading",e),o("terminal-title",n),o("terminal-message",t.error||t.message||"");const a=document.getElementById("terminal-identity-list");if(a){const h=[["Project",r.projectId||t.metadata?.projectId],["Endpoint",r.endpoint],["File",r.fileName||t.metadata?.fileName],["Artifact",r.artifactType||t.metadata?.artifactType]];a.innerHTML=h.map(([p,g])=>`
    ${z(p)}:${z(String(g??"—"))}
    `).join("")}const l=document.getElementById("terminal-file-outcomes");let u=t.errorMap;u&&!(u instanceof Map)&&(u=new Map(Object.entries(u))),l&&u&&u.size>0?(l.innerHTML=[...u.entries()].map(([h,p])=>`
  • ${z(h)}: ${z(Sl(p))}
  • `).join(""),l.classList.remove("hidden")):l&&l.classList.add("hidden");const c=document.getElementById("terminal-guidance");c&&(c.innerHTML=i);const d=document.getElementById("terminal-open-ff-link"),f=r.projectId||t.metadata?.projectId;return d&&(d.href=f?`https://app.flutterflow.io/project/${f}`:"https://app.flutterflow.io/"),We(s),!0}function fp(t){Jl(t,{heading:"Deploy partially applied",title:"Some custom classes reached FlutterFlow, but the deploy did not fully complete.",guidance:"The custom classes the runner confirmed are already in your project and are not lost. Review the per-file errors above, fix them in FlutterFlow or regenerate, then deploy again. Open the project to see exactly what landed."})}function hp(t){Jl(t,{heading:"Deploy outcome not yet known",title:"This browser stopped waiting before the FlutterFlow server reported a result.",guidance:"The deploy may still be finishing on the server — it was not cancelled. Open your FlutterFlow project and confirm whether the class landed before retrying, so you do not push a duplicate or build on top of an unknown state."})}function xw(t){t&&t.target!==t.currentTarget||ze(document.getElementById("commit-terminal-modal"))}function Iw(){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 ad={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}},kw=[{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&&(Su(e,!0,"Deploying to FlutterFlow"),We(e)),this.set("prepare")},set(t,e=null){if(!(!ad[t]||t===this.phaseId)){if(!this.sequence.includes(t)){const n=this.sequence.indexOf("package");this.sequence.splice(n===-1?this.sequence.length:n,0,t)}this.phaseId=t,this.phaseStartedAt=Date.now(),this.substatus=e,this.liveSubstatus=!1,this.render(),this.timer&&clearInterval(this.timer),t!=="done"&&(this.timer=setInterval(()=>this.render(),500))}},setSubstatus(t){t&&(this.liveSubstatus=!0,this.substatus=t,this.render())},render(){const t=ad[this.phaseId];if(!t)return;const e=(Date.now()-this.phaseStartedAt)/1e3,n=t.start+(t.end-t.start)*(1-Math.exp(-e/25));if(this.phaseId==="provision"&&!this.liveSubstatus){const o=kw.filter(a=>e>=a.after).pop();o&&(this.substatus=o.text)}const i=this.sequence.indexOf(this.phaseId),s=[`Step ${i===-1?1:i+1} of ${this.sequence.length}`];e>=5&&s.push(Cw(e)),gp(this.phaseId==="done"?100:n,t.message,s.join(" · "),this.substatus)},stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.phaseId=null;const t=document.getElementById("commit-progress-overlay");t&&(Su(t,!1),ze(t,{force:!0,restoreFocus:!1}))}};function Cw(t){const e=Math.floor(t);return e<60?`${e}s elapsed`:`${Math.floor(e/60)}m ${String(e%60).padStart(2,"0")}s elapsed`}function pp(t){Be.start(t)}function Zl(){Be.stop()}function gp(t,e,n,i=null){const r=document.getElementById("commit-progress-bar"),s=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");r&&(r.style.width=`${Math.round(t*10)/10}%`),s&&(s.textContent=e),o&&(o.textContent=n),a&&(a.textContent=i||"",a.classList.toggle("hidden",!i))}function ld(t){const e={[ee.PREPARING]:"prepare",[ee.VALIDATING]:"validate",[ee.PUSHING]:"project",[ee.SUCCESS]:"done"};if(t===ee.ERROR){Be.timer&&clearInterval(Be.timer),Be.timer=null,gp(100,"Failed","Error occurred");return}const n=e[t];n&&Be.set(n)}function Aw(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===J.CODE_FILE):t.codeInfo?.codeType===J.CODE_FILE}let mp=!1;function vp(t){mp=t;const e=document.querySelector("#commit-confirm-modal button[data-deploy-confirm]");e&&(e.disabled=t),[...document.querySelectorAll("[data-deploy-start]"),...document.querySelectorAll("#btn-deploy-to-ff")].forEach(i=>{i.disabled=t})}function cd(t){Zl(),vp(!1);const e=Eh(t);e===Le.COMMITTED?up(t):e===Le.PARTIAL?fp(t):e===Le.UNCONFIRMED?hp(t):dp(t)}async function Pw(){if(!qi){console.error("No pending commit data");return}if(mp){console.warn("Deploy already in flight; ignoring duplicate confirm.");return}const t=qi;if(qi=null,zi=Ew(),cp(),vp(!0),pp({withProvisioning:Aw(t)}),t.bundlePlan){const o=await R0(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});zi=null,cd(o);return}const{codeInfo:e}=t,{artifactType:n,artifactName:i,fileName:r}=Uh(),s=await F0(e.content,{artifactType:n,artifactName:i,fileName:r,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});zi=null,cd(s)}window.runThinkingPipeline=or;window.toggleStep=M0;window.toggleSection=$0;window.selectWorkflowStep=it;window.copyCode=L0;window.retryWithDifferentModel=D0;window.openApiKeysModal=Tl;window.closeApiKeysModal=Bh;window.openComposerSettings=s0;window.closeComposerSettings=o0;window.walkthroughConnectAccount=r0;window.closeWalkthroughModal=l0;window.openWalkthroughModal=a0;window.advanceWalkthrough=$l;window.commitToFlutterFlow=P0;function Fw(){const t=document.getElementById("pipeline-input");t&&t.focus()}function Rw(){const t=document.getElementById("advanced-settings");t&&(t.open=!0);const e=document.getElementById("code-generator-model");e&&(e.scrollIntoView({behavior:"smooth",block:"center"}),e.focus(),e.click())}window.focusPromptInput=Fw;window.openModelSelector=Rw;window.handlePromptImageSelect=Wy;window.removePromptImage=zy;window.saveApiKeys=d0;window.validateFlutterFlowConnection=Ll;window.clearAllApiKeys=f0;window.toggleKeyVisibility=_0;window.handleWelcomeVideoEnd=ww;window.dismissWelcomeVideo=Nn;window.initiateCommitToFlutterFlow=j0;window.updateFlutterFlowCredentialStatus=W0;window.openCommitConfirmModal=Yl;window.closeCommitConfirmModal=cp;window.closeCommitSuccessModal=Sw;window.closeCommitTerminalModal=xw;window.showCommitPartialModal=fp;window.showCommitUnconfirmedModal=hp;window.showCommitSuccessModal=up;window.showCommitFailureModal=dp;window.toggleCodePreview=Iw;window.confirmCommitToFlutterFlow=Pw;window.runRefinement=Jh;window.regenerateFromPastedErrors=Zh;window.clearErrorInput=B0;window.setFlutterFlowEndpoint=i0;window.getFlutterFlowEndpoint=yt;window.commitProgress=Be;window.openSignInModal=zs;window.closeSignInModal=np;window.handleMagicLinkRequest=K0;window.handleSignOut=Y0;window.handleSendNewLink=X0;window.handleClearCache=Q0;window.handleDeleteAccount=ew;window.closeDeleteUnavailableModal=tw;window.startCheckout=fw;window.openCustomerPortal=hw;window.openPricingModal=di;window.closePricingModal=lp;let jr=null,_p=null,On={1:"pending",2:"pending",3:"pending"},Xl=1,Ql=null;const Gs={1:"Prompt Architect",2:"Code Generator",3:"Code Review"},Tw={1:"Understanding your prompt",2:"Generating Dart code",3:"Running the code audit"},$w={1:"Prompt understood",2:"Dart code generated",3:"Code audit complete"};function Ks(){return y.runId+=1,y.runId}function re(t){return t===void 0||t===y.runId}function Mw(){y.runId+=1}function ec(t){return document.getElementById(`pdot-${t}`)}function Ya(t){const e=document.getElementById("btn-run-pipeline")||document.getElementById("hero-send");e&&(e.disabled=t,e.classList.toggle("is-busy",t),t?e.setAttribute("aria-busy","true"):e.removeAttribute("aria-busy"))}function Ys(t){const e=document.getElementById("pipeline-progress");e&&(e.dataset.runState=t)}function Rn(t,e){On[t]=e;const n=ec(t);if(!n)return;n.dataset.state=e,n.disabled=e==="pending"||e==="skipped";const i=Gs[t],r={pending:"not started",active:"in progress",done:"complete",failed:"failed",skipped:"not run"};n.setAttribute("aria-label",`Step ${t} of 3, ${i}: ${r[e]||e}`),e==="active"?n.setAttribute("aria-current","step"):n.removeAttribute("aria-current")}function Lw(){return[1,2,3].filter(t=>On[t]==="done").length}function Js(){const t=document.getElementById("pipeline-progress-fill");t&&(t.style.width=`${Lw()/3*100}%`);const e=document.getElementById("progress-stage-count");e&&(e.textContent=`Step ${Xl} of 3`)}function Zs(t,{done:e=!1}={}){const n=document.getElementById("progress-title-text"),i=document.getElementById("progress-substep-text"),r=On[t],s=e||r==="done";if(n&&(n.textContent=s?$w[t]:Tw[t]),i){const o=s?" — complete":r==="failed"?" — stopped":"";i.textContent=`Step ${t} of 3 — ${Gs[t]}${o}`}}function Nw(t){On[t]==="pending"||On[t]==="skipped"||(Ql=t,[1,2,3].forEach(e=>{const n=ec(e);n&&n.setAttribute("aria-pressed",String(e===t))}),Zs(t))}function tc(){Ql=null,[1,2,3].forEach(t=>{const e=ec(t);e&&e.removeAttribute("aria-pressed")})}function yp(t){const e=document.getElementById("pipeline-note");e&&(e.textContent=t||"",e.hidden=!t)}function Ow(t,e,n){re(n)&&yp(`${Gt(t)} did not answer. Continuing on ${Gt(e)}.`)}function nc(){const t=document.getElementById("pipeline-failure");if(!t)return;t.hidden=!0;const e=document.getElementById("pipeline-failure-actions");e&&e.replaceChildren()}const Bw=1120;function Dw(){const t=getComputedStyle(document.documentElement).getPropertyValue("--t-morph").trim(),e=Number.parseFloat(t);return Number.isFinite(e)&&e>0?e:Bw}let Qn=null,Ur=null;function jw(){return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0}function dn(){if(Ur){try{Ur.cancel()}catch{}Ur=null}Qn&&(Qn.remove(),Qn=null),window.removeEventListener("resize",dn)}function wp(t,e){if(dn(),jw()||!t||!e||!document.body||typeof Element.prototype.animate!="function")return;const n=t.getBoundingClientRect(),i=e.getBoundingClientRect();if(!n.width||!n.height||!i.width||!i.height)return;const r=document.createElement("div");r.className="composer-morph",r.setAttribute("aria-hidden","true"),r.style.cssText=`left:${i.left}px;top:${i.top}px;width:${i.width}px;height:${i.height}px;opacity:0;`,document.body.appendChild(r);const s=n.left+n.width/2-(i.left+i.width/2),o=n.top+n.height/2-(i.top+i.height/2),a=n.width/i.width,l=n.height/i.height,u=`translate(${s}px,${o}px) scale(${a},${l})`,c=r.animate([{transform:u,opacity:0,offset:0,easing:"cubic-bezier(.2,0,0,1)"},{transform:u,opacity:1,offset:.14,easing:"cubic-bezier(.4,0,.2,1)"},{transform:`translate(${s}px,${o}px) scale(${a*.93},${l*.93})`,opacity:1,offset:.28,easing:"cubic-bezier(.32,1.38,.5,1)"},{transform:"translate(0px,0px) scale(1,1)",opacity:1,offset:1}],{duration:Dw(),fill:"both"});Qn=r,Ur=c,window.addEventListener("resize",dn),c.onfinish=()=>{if(Qn!==r)return;const d=r.animate([{opacity:1},{opacity:0}],{duration:260,fill:"forwards"});d.onfinish=()=>{Qn===r&&dn()}}}function Uw(){const e=document.getElementById("composer")?.getBoundingClientRect();e&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{wp({getBoundingClientRect:()=>e},document.getElementById("main-stage-container"))})})}function Hw(){wp(document.getElementById("pipeline-progress"),document.getElementById("main-stage-container"))}window.addEventListener("hashchange",dn);window.addEventListener("popstate",dn);function Xs(t={}){const{prompt:e=null,runId:n}=t;if(!re(n))return;eo(),nn(!0);const i=document.getElementById("pipeline-progress"),r=document.getElementById("results-view"),s=document.getElementById("ready-state");if(s&&s.classList.add("hidden"),r&&r.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),i&&i.classList.add("visible"),Ys("running"),e!==null){const a=document.getElementById("pipeline-submitted-prompt");a&&(a.textContent=e)}_p=Date.now();const o=document.getElementById("progress-elapsed");o&&(o.textContent="0s"),On={1:"pending",2:"pending",3:"pending"},tc(),nc(),yp(""),[1,2,3].forEach(a=>Rn(a,"pending")),Ft(1,n),Ww()}function Ft(t,e){re(e)&&(Xl=t,tc(),[1,2,3].forEach(n=>{n===t?Rn(n,"active"):nt&&Rn(n,"pending")}),Zs(t),Js())}function tn(t,e){re(e)&&(Rn(t,"done"),Ql===null&&Zs(t,{done:!0}),Js())}function bp(t,{stage:e=1,runId:n,retry:i=Ep}={}){if(!re(n))return;Qs(),eo(),dn(),Ys("failed"),nn(!0);const r=document.getElementById("pipeline-progress");r&&r.classList.add("visible");const s=document.getElementById("results-view");s&&s.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),Rn(e,"failed"),[1,2,3].forEach(p=>{p>e&&Rn(p,"pending")}),Xl=e,tc(),Zs(e),Js();const o=xh(t),a=document.getElementById("pipeline-failure"),l=document.getElementById("pipeline-failure-title"),u=document.getElementById("pipeline-failure-message"),c=document.getElementById("pipeline-failure-hint"),d=document.getElementById("pipeline-failure-actions");if(!a||!l||!u||!d)return;if(a.dataset.kind=o.kind,l.textContent=`${Gs[e]}: ${o.title}`,u.textContent=o.message,c){const p=o.detail&&o.detail!==o.message?o.detail:"";c.textContent=p,c.hidden=!p}d.replaceChildren();const f=[o.canUpgrade&&{id:"upgrade",label:"View plans",variant:"primary",onClick:()=>di()},o.canRetry&&{id:"retry",label:"Retry",variant:o.canUpgrade?"secondary":"primary",onClick:i},o.canEdit&&{id:"edit",label:"Edit prompt",variant:"secondary",onClick:Ja}].filter(Boolean);!o.canEdit&&!o.canRetry&&f.push({id:"edit",label:"Back to prompt",variant:"secondary",onClick:Ja}),f.forEach(p=>{const g=document.createElement("button");g.type="button",g.textContent=p.label,g.dataset.action=p.id,g.dataset.variant=p.variant,g.addEventListener("click",p.onClick),d.appendChild(g)}),a.hidden=!1;const h=d.querySelector("button");h&&h.focus({preventScroll:!0})}function Ja(){Mw(),pw(),y.isRunning=!1,Ya(!1),rn(),Ys("settled"),dn(),Qs(),eo(),nc();const t=document.getElementById("pipeline-progress");t&&t.classList.remove("visible"),nn(!1);const e=document.getElementById("pipeline-input");e&&(y.submittedPrompt&&(e.value=y.submittedPrompt,e.dispatchEvent(new Event("input",{bubbles:!0}))),e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length))}function Ep(){const t=document.getElementById("pipeline-input");t&&y.submittedPrompt&&(t.value=y.submittedPrompt,t.dispatchEvent(new Event("input",{bubbles:!0}))),Oe=y.submittedImages.slice(),cn(),nc(),or()}function Ww(){Qs(),jr=setInterval(()=>{const t=(Date.now()-_p)/1e3,e=document.getElementById("progress-elapsed");e&&(e.textContent=`${Math.floor(t)}s`)},250)}function Qs(){jr&&(clearInterval(jr),jr=null)}let Vi=null;function eo(){Vi&&(clearTimeout(Vi),Vi=null)}function cr(){Qs(),eo(),Ys("settled"),Js();const t=document.getElementById("pipeline-progress-fill");Vi=setTimeout(()=>{Vi=null;const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function Tn(t,e=""){const n={pass:'',warning:'',fail:'',info:''};return``}function Sp(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function zw(){return m_({bundle:y.artifactBundle,reviewResult:y.step3Result})}function qw(t){return`
    ${Tn(t.severity)}
    @@ -174,14 +174,14 @@ Error: ${g} ${z(t.source)}
    - `}function qw(t){return` + `}function Vw(t){return`
  • ${z(t.title)} ${t.detail&&t.detail!==t.title?`

    ${z(t.detail)}

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

      ${z(l.reason)}

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

      ${z(l.description)}

      `:""}
    • @@ -265,7 +265,7 @@ Error: ${g} ${e.manualSteps.length?`

      Manual FlutterFlow steps for this file

      -
        ${e.manualSteps.map(qw).join("")}
      +
        ${e.manualSteps.map(Vw).join("")}
      `:""}
      @@ -297,7 +297,7 @@ Error: ${g}
        ${a}
      - `}function Kw(t){const e=document.getElementById("bundle-strip"),n=document.getElementById("results-summary-tab"),i=document.getElementById("artifact-tabs"),r=document.getElementById("results-file-count");if(n){const s=y.resultsViewMode==="summary";n.classList.toggle("active",s),n.setAttribute("role","tab"),n.setAttribute("aria-selected",String(s)),n.setAttribute("aria-controls","results-summary-detail"),n.tabIndex=s?0:-1}if(i&&(i.setAttribute("role","tablist"),i.setAttribute("aria-label","Artifacts in this bundle")),!t.artifacts.length){r&&(r.textContent="0 files"),e&&e.classList.remove("visible"),i&&(i.innerHTML=""),cd();return}if(r){const s=t.artifacts.length;r.textContent=`${s} ${s===1?"file":"files"}`}i&&(i.innerHTML=t.artifacts.map(s=>{const o=y.resultsViewMode==="file"&&s.id===y.selectedArtifactId;return` + `}function Yw(t){const e=document.getElementById("bundle-strip"),n=document.getElementById("results-summary-tab"),i=document.getElementById("artifact-tabs"),r=document.getElementById("results-file-count");if(n){const s=y.resultsViewMode==="summary";n.classList.toggle("active",s),n.setAttribute("role","tab"),n.setAttribute("aria-selected",String(s)),n.setAttribute("aria-controls","results-summary-detail"),n.tabIndex=s?0:-1}if(i&&(i.setAttribute("role","tablist"),i.setAttribute("aria-label","Artifacts in this bundle")),!t.artifacts.length){r&&(r.textContent="0 files"),e&&e.classList.remove("visible"),i&&(i.innerHTML=""),ud();return}if(r){const s=t.artifacts.length;r.textContent=`${s} ${s===1?"file":"files"}`}i&&(i.innerHTML=t.artifacts.map(s=>{const o=y.resultsViewMode==="file"&&s.id===y.selectedArtifactId;return` - `}).join(""),i.onclick=s=>{const o=s.target.closest(".artifact-tab");o?.dataset?.artifactId&&nc(o.dataset.artifactId)},cd()),e&&e.classList.add("visible")}function cd(){const t=document.getElementById("bundle-strip");!t||t.dataset.tabKeyboard==="bound"||(t.dataset.tabKeyboard="bound",t.addEventListener("keydown",e=>{if(e.defaultPrevented)return;const n=[document.getElementById("results-summary-tab"),...Array.from(document.querySelectorAll("#artifact-tabs .artifact-tab"))].filter(Boolean);if(!n.length||!n.includes(document.activeElement))return;let i=-1;const r=n.indexOf(document.activeElement);if(e.key==="ArrowRight")i=(r+1)%n.length;else if(e.key==="ArrowLeft")i=(r-1+n.length)%n.length;else if(e.key==="Home")i=0;else if(e.key==="End")i=n.length-1;else return;e.preventDefault();const s=n[i];if(!s)return;if(s.id==="results-summary-tab")xp();else{const a=s.dataset.artifactId;a&&nc(a)}const o=s.id==="results-summary-tab"?document.getElementById("results-summary-tab"):document.querySelector(`#artifact-tabs .artifact-tab[data-artifact-id="${s.dataset.artifactId}"]`);o&&o.focus()}))}function eo(){document.body.classList.add("results-fullscreen"),document.body.classList.add("results-with-sidebar");const t=document.getElementById("results-view"),e=document.getElementById("results-code-output"),n=document.getElementById("results-audit-output"),i=document.getElementById("results-summary-detail"),r=document.getElementById("artifact-results-split"),s=Ww(),o=Ol();if(i&&(i.setAttribute("role","tabpanel"),i.setAttribute("aria-labelledby","results-summary-tab")),r){r.setAttribute("role","tabpanel");const a=s?.artifacts?.find(l=>l.id===y.selectedArtifactId);r.setAttribute("aria-labelledby",a?`artifact-tab-${a.id}`:"results-summary-tab")}if(Vw(s),Kw(s),e&&(e.textContent=""),e){const a=xh(o);e.innerHTML=a}n&&(n.innerHTML=Gw(s)),i&&i.classList.toggle("hidden",y.resultsViewMode!=="summary"),r&&r.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function ur(t,e){nn(!0),y.selectedArtifactId||(y.selectedArtifactId=oi(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const n=document.getElementById("step3-output");n&&(n.textContent=""),eo(),rn(),Yw()}function Yw(){const t=document.getElementById("btn-feedback-up"),e=document.getElementById("btn-feedback-down"),n=document.getElementById("results-feedback-status");t&&(t.className="feedback-btn",t.setAttribute("aria-pressed","false"),t.disabled=!1,t.removeAttribute("aria-disabled")),e&&(e.className="feedback-btn",e.setAttribute("aria-pressed","false"),e.disabled=!1,e.removeAttribute("aria-disabled")),n&&(n.textContent=""),Ja=!1}function nc(t){y.selectedArtifactId=t,y.resultsViewMode="file",eo()}function xp(){y.resultsViewMode="summary",eo()}function Jw(){const t=document.getElementById("btn-copy-results"),e=document.getElementById("results-copy-status"),n=Ol(),i=(r,s)=>{e&&(e.textContent=r,e.classList.toggle("ok",!!s),e.classList.toggle("fail",!s))};if(!navigator.clipboard?.writeText){i("Copying isn't supported in this browser.",!1);return}navigator.clipboard.writeText(n).then(()=>{if(i("Copied to clipboard",!0),t){t.classList.add("copied");const r=t.querySelector("span");if(r){const s=r.textContent;r.textContent="Copied!",setTimeout(()=>{t.classList.remove("copied"),r.textContent=s},2e3)}}}).catch(()=>{i("Clipboard permission was denied. Select the code to copy it manually.",!1)})}let Ja=!1;async function Zw(t){const e=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down"),i=document.getElementById("results-feedback-status");if(!e||!n||Ja)return;const r=l=>{i&&(i.textContent="",i.offsetWidth,i.textContent=l)},s=l=>{Ja=l,[e,n].forEach(u=>{u.disabled=l,u.setAttribute("aria-disabled",String(l))})},o=t==="up"?"thumbsUp":"thumbsDown";s(!0),r("Submitting review feedback…");const a={type:o,code:y.step2Result,input:y.step1Result};try{const l=await ql(a.type,a.code,a.input);if(!l||l.success!==!0){s(!1),r("Review feedback could not be sent. Tap again to retry.");return}e.classList.toggle("active-up",t==="up"),n.classList.toggle("active-down",t==="down"),e.setAttribute("aria-pressed",String(t==="up")),n.setAttribute("aria-pressed",String(t==="down")),s(!1),r("Review feedback saved.")}catch{s(!1),r("Review feedback could not be sent. Tap again to retry.")}}function Xw(){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 Ip(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}function nn(t){const e=document.getElementById("generation-stage");e&&(t?(e.hidden=!1,e.inert=!1,requestAnimationFrame(()=>e.classList.add("is-active"))):(e.classList.remove("is-active"),e.inert=!0,setTimeout(()=>{e.classList.contains("is-active")||(e.hidden=!0)},260)))}function kp(){const t=q.isVerified&&!!q.email,e=ce.tier||"free",n=t&&pi(),i=!t||Tt(),s=n?"Checking…":i?gl[e]||"Free":"—",o=document.getElementById("topbar-plan");o&&(o.textContent=s);const a=document.getElementById("topbar-avatar");a&&(a.textContent=(q.email||"?")[0].toUpperCase()),Gl();const l=document.getElementById("plans-free-current");l&&l.classList.toggle("hidden",e!=="free"||!i);const u=document.getElementById("plans-checkout-btn-professional");if(u){const d=e==="professional"&&i;u.disabled=d,u.textContent=d?"Current plan":"Subscribe"}const c=document.getElementById("plans-checkout-btn-power");if(c){const d=e==="power"&&i;c.disabled=d,c.textContent=d?"Current plan":"Subscribe"}}function Qw(){kp();const t=document.getElementById("credits-modal");t&&We(t)}function eb(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("credits-modal");e&&ze(e)}function Cp(t,e=!0,n=!0){if(t=["home","account","plans"].includes(t)?t:"home",document.querySelectorAll(".view[data-view]").forEach(r=>{r.dataset.view===t?(r.hidden=!1,r.removeAttribute("inert"),requestAnimationFrame(()=>{r.classList.add("is-active"),n&&r.focus({preventScroll:!0})})):(r.classList.remove("is-active"),r.setAttribute("inert","true"),setTimeout(()=>{r.classList.contains("is-active")||(r.hidden=!0)},260))}),t!=="home")nn(!1);else{const r=document.getElementById("main-stage-container");r&&r.classList.contains("visible")&&nn(!0)}if(document.querySelectorAll(".nav-link[data-view]").forEach(r=>{const s=r.dataset.view===t;r.setAttribute("aria-current",s?"page":null),s||r.removeAttribute("aria-current")}),e){const r=t==="home"?"":`#${t}`;window.location.hash!==r&&window.history.pushState({view:t},"",r||"#")}}let ud=!1;function ic(){const t=window.location.hash.replace(/^#/,"");Cp(t||"home",!1,ud),ud=!0}window.addEventListener("popstate",t=>{ic()});window.addEventListener("hashchange",()=>{ic()});window.copyResultsCode=Jw;window.selectArtifact=nc;window.selectResultsSummary=xp;window.submitResultsFeedback=Zw;window.showErrorInputPanel=Xw;window.hideErrorInputPanel=Ip;window.setGenerationStageVisible=nn;window.switchView=Cp;window.selectPipelineStage=Lw;window.editPipelinePrompt=Ya;window.retryPipelineRun=Ep;window.openCreditsModal=Qw;window.closeCreditsModal=eb; + `}).join(""),i.onclick=s=>{const o=s.target.closest(".artifact-tab");o?.dataset?.artifactId&&ic(o.dataset.artifactId)},ud()),e&&e.classList.add("visible")}function ud(){const t=document.getElementById("bundle-strip");!t||t.dataset.tabKeyboard==="bound"||(t.dataset.tabKeyboard="bound",t.addEventListener("keydown",e=>{if(e.defaultPrevented)return;const n=[document.getElementById("results-summary-tab"),...Array.from(document.querySelectorAll("#artifact-tabs .artifact-tab"))].filter(Boolean);if(!n.length||!n.includes(document.activeElement))return;let i=-1;const r=n.indexOf(document.activeElement);if(e.key==="ArrowRight")i=(r+1)%n.length;else if(e.key==="ArrowLeft")i=(r-1+n.length)%n.length;else if(e.key==="Home")i=0;else if(e.key==="End")i=n.length-1;else return;e.preventDefault();const s=n[i];if(!s)return;if(s.id==="results-summary-tab")xp();else{const a=s.dataset.artifactId;a&&ic(a)}const o=s.id==="results-summary-tab"?document.getElementById("results-summary-tab"):document.querySelector(`#artifact-tabs .artifact-tab[data-artifact-id="${s.dataset.artifactId}"]`);o&&o.focus()}))}function to(){document.body.classList.add("results-fullscreen"),document.body.classList.add("results-with-sidebar");const t=document.getElementById("results-view"),e=document.getElementById("results-code-output"),n=document.getElementById("results-audit-output"),i=document.getElementById("results-summary-detail"),r=document.getElementById("artifact-results-split"),s=zw(),o=Bl();if(i&&(i.setAttribute("role","tabpanel"),i.setAttribute("aria-labelledby","results-summary-tab")),r){r.setAttribute("role","tabpanel");const a=s?.artifacts?.find(l=>l.id===y.selectedArtifactId);r.setAttribute("aria-labelledby",a?`artifact-tab-${a.id}`:"results-summary-tab")}if(Gw(s),Yw(s),e&&(e.textContent=""),e){const a=Ih(o);e.innerHTML=a}n&&(n.innerHTML=Kw(s)),i&&i.classList.toggle("hidden",y.resultsViewMode!=="summary"),r&&r.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function ur(t,e){nn(!0),y.selectedArtifactId||(y.selectedArtifactId=oi(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const n=document.getElementById("step3-output");n&&(n.textContent=""),to(),rn(),Jw()}function Jw(){const t=document.getElementById("btn-feedback-up"),e=document.getElementById("btn-feedback-down"),n=document.getElementById("results-feedback-status");t&&(t.className="feedback-btn",t.setAttribute("aria-pressed","false"),t.disabled=!1,t.removeAttribute("aria-disabled")),e&&(e.className="feedback-btn",e.setAttribute("aria-pressed","false"),e.disabled=!1,e.removeAttribute("aria-disabled")),n&&(n.textContent=""),Za=!1}function ic(t){y.selectedArtifactId=t,y.resultsViewMode="file",to()}function xp(){y.resultsViewMode="summary",to()}function Zw(){const t=document.getElementById("btn-copy-results"),e=document.getElementById("results-copy-status"),n=Bl(),i=(r,s)=>{e&&(e.textContent=r,e.classList.toggle("ok",!!s),e.classList.toggle("fail",!s))};if(!navigator.clipboard?.writeText){i("Copying isn't supported in this browser.",!1);return}navigator.clipboard.writeText(n).then(()=>{if(i("Copied to clipboard",!0),t){t.classList.add("copied");const r=t.querySelector("span");if(r){const s=r.textContent;r.textContent="Copied!",setTimeout(()=>{t.classList.remove("copied"),r.textContent=s},2e3)}}}).catch(()=>{i("Clipboard permission was denied. Select the code to copy it manually.",!1)})}let Za=!1;async function Xw(t){const e=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down"),i=document.getElementById("results-feedback-status");if(!e||!n||Za)return;const r=l=>{i&&(i.textContent="",i.offsetWidth,i.textContent=l)},s=l=>{Za=l,[e,n].forEach(u=>{u.disabled=l,u.setAttribute("aria-disabled",String(l))})},o=t==="up"?"thumbsUp":"thumbsDown";s(!0),r("Submitting review feedback…");const a={type:o,code:y.step2Result,input:y.step1Result};try{const l=await Vl(a.type,a.code,a.input);if(!l||l.success!==!0){s(!1),r("Review feedback could not be sent. Tap again to retry.");return}e.classList.toggle("active-up",t==="up"),n.classList.toggle("active-down",t==="down"),e.setAttribute("aria-pressed",String(t==="up")),n.setAttribute("aria-pressed",String(t==="down")),s(!1),r("Review feedback saved.")}catch{s(!1),r("Review feedback could not be sent. Tap again to retry.")}}function Qw(){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 Ip(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}function nn(t){const e=document.getElementById("generation-stage");e&&(t?(e.hidden=!1,e.inert=!1,requestAnimationFrame(()=>e.classList.add("is-active"))):(e.classList.remove("is-active"),e.inert=!0,setTimeout(()=>{e.classList.contains("is-active")||(e.hidden=!0)},260)))}function kp(){const t=q.isVerified&&!!q.email,e=ce.tier||"free",n=t&&pi(),i=!t||Tt(),s=n?"Checking…":i?ml[e]||"Free":"—",o=document.getElementById("topbar-plan");o&&(o.textContent=s);const a=document.getElementById("topbar-avatar");a&&(a.textContent=(q.email||"?")[0].toUpperCase()),Kl();const l=document.getElementById("plans-free-current");l&&l.classList.toggle("hidden",e!=="free"||!i);const u=document.getElementById("plans-checkout-btn-professional");if(u){const d=e==="professional"&&i;u.disabled=d,u.textContent=d?"Current plan":"Subscribe"}const c=document.getElementById("plans-checkout-btn-power");if(c){const d=e==="power"&&i;c.disabled=d,c.textContent=d?"Current plan":"Subscribe"}}function eb(){kp();const t=document.getElementById("credits-modal");t&&We(t)}function tb(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("credits-modal");e&&ze(e)}function Cp(t,e=!0,n=!0){if(t=["home","account","plans"].includes(t)?t:"home",document.querySelectorAll(".view[data-view]").forEach(r=>{r.dataset.view===t?(r.hidden=!1,r.removeAttribute("inert"),requestAnimationFrame(()=>{r.classList.add("is-active"),n&&r.focus({preventScroll:!0})})):(r.classList.remove("is-active"),r.setAttribute("inert","true"),setTimeout(()=>{r.classList.contains("is-active")||(r.hidden=!0)},260))}),t!=="home")nn(!1);else{const r=document.getElementById("main-stage-container");r&&r.classList.contains("visible")&&nn(!0)}if(document.querySelectorAll(".nav-link[data-view]").forEach(r=>{const s=r.dataset.view===t;r.setAttribute("aria-current",s?"page":null),s||r.removeAttribute("aria-current")}),e){const r=t==="home"?"":`#${t}`;window.location.hash!==r&&window.history.pushState({view:t},"",r||"#")}}let dd=!1;function rc(){const t=window.location.hash.replace(/^#/,"");Cp(t||"home",!1,dd),dd=!0}window.addEventListener("popstate",t=>{rc()});window.addEventListener("hashchange",()=>{rc()});window.copyResultsCode=Zw;window.selectArtifact=ic;window.selectResultsSummary=xp;window.submitResultsFeedback=Xw;window.showErrorInputPanel=Qw;window.hideErrorInputPanel=Ip;window.setGenerationStageVisible=nn;window.switchView=Cp;window.selectPipelineStage=Nw;window.editPipelinePrompt=Ja;window.retryPipelineRun=Ep;window.openCreditsModal=eb;window.closeCreditsModal=tb; diff --git a/dist/index.html b/dist/index.html index 3218e9f..8609b4f 100644 --- a/dist/index.html +++ b/dist/index.html @@ -3313,7 +3313,7 @@ .send.is-busy .send-spin { animation: none; opacity: 0.6; } } - + diff --git a/e2e/stu380-deploy.spec.js b/e2e/stu380-deploy.spec.js index 0ac1595..6545648 100644 --- a/e2e/stu380-deploy.spec.js +++ b/e2e/stu380-deploy.spec.js @@ -755,6 +755,35 @@ test.describe("STU-380 transport outcome regressions", () => { expect(outcome.parsed.responseCode).toBe(403); }); + test("a refusal whose body stalls still reports its status inside the bound", async ({ page }) => { + await loadDeployHooks(page); + + // A 4xx that sends a byte then keeps the body open is still a definitive + // refusal — the status alone decides, so the parse must not wait on the + // body past the diagnostic bound. + const outcome = await page.evaluate(async () => { + const body = new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode("{")); + // Never closes — the stalled body must not block classification. + }, + }); + try { + const parsed = await window.__CCC_PARSE_PUSH_RESPONSE__( + new Response(body, { status: 403 }), + 50, + ); + return { settled: "resolved", parsed }; + } catch (error) { + return { settled: "rejected", name: error.name, message: error.message }; + } + }); + + expect(outcome.settled).toBe("resolved"); + expect(outcome.parsed.success).toBe(false); + expect(outcome.parsed.responseCode).toBe(403); + }); + test("a server error with an unreadable body still lands as unconfirmed", async ({ page }) => { await loadDeployHooks(page); @@ -866,4 +895,51 @@ test.describe("STU-380 transport outcome regressions", () => { await page.evaluate(() => window.__CCC_RESOLVE_PROJECT_PUBSPEC__({})); expect(exportCalls).toBe(2); }); + + test("a runner failure after deploy began also drops the cached snapshot", async ({ page }) => { + await loadDeployHooks(page); + + const zip = new JSZip(); + zip.file( + "pubspec.yaml", + "name: my_app\n\ndependencies:\n flutter:\n sdk: flutter\n", + ); + const projectZip = await zip.generateAsync({ type: "base64" }); + + let exportCalls = 0; + await page.route("**/exportCode", async (route) => { + exportCalls += 1; + await route.fulfill({ + status: 200, + contentType: "application/json", + body: JSON.stringify({ value: { project_zip: projectZip } }), + }); + }); + // The runner answers definitively, but only after the deploy phase began — + // classes may have been written, so the snapshot is stale too. + await page.route(ENDPOINTS.deployCustomClasses, async (route) => { + await route.fulfill({ + status: 200, + contentType: "application/x-ndjson", + body: + '{"event":"phase","phase":"deploy_start","message":"Deploying 1 custom class to FlutterFlow..."}\n' + + '{"event":"result","success":false,"error":"FlutterFlow AI DSL deploy failed.","exitCode":1}\n', + }); + }); + + const seeded = await page.evaluate(() => + window.__CCC_RESOLVE_PROJECT_PUBSPEC__({}), + ); + expect(exportCalls).toBe(1); + + const outcome = await settleAsOutcome( + page, + "__CCC_PROVISION_CUSTOM_CLASSES__", + [{ fileMap: newClassFileMap }], + ); + expect(outcome.name).toBe("UnconfirmedDeployError"); + + await page.evaluate(() => window.__CCC_RESOLVE_PROJECT_PUBSPEC__({})); + expect(exportCalls).toBe(2); + }); }); diff --git a/src/deployOutcome.js b/src/deployOutcome.js index c0997fa..ebf62d7 100644 --- a/src/deployOutcome.js +++ b/src/deployOutcome.js @@ -39,6 +39,11 @@ export const DeployOutcome = Object.freeze({ */ export const DEPLOY_UI_TIMEOUT_MS = 120_000; +// A response's status alone classifies it; the body only carries detail. +// A stalled error body must therefore never hold up a definitive refusal — +// diagnostic/detail reads give up after this bound and classify on status. +export const PUSH_BODY_READ_TIMEOUT_MS = 10_000; + /** * Maps a deploy result to its single truthful terminal outcome. * From 5fff0ffaffaf750b9dad53d90ad6f228195fd757 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Sun, 27 Sep 2026 17:58:22 +0000 Subject: [PATCH 12/16] fix(deploy): cancel stalled diagnostic body reads instead of leaking them MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The detached error-body log read in pushCodeWithRetry and the bounded reads in parsePushCodeResponse settled their waiters but left the underlying stream reader pending — each stalled body held its connection open past the UI bound. readBodyBounded keeps the reader handle so the bound expiry cancels the stream for real (reader.cancel() works where body.cancel() rejects on the locked stream). Covered by asserting the source stream's cancel() fires on a stalled refusal body. Co-Authored-By: Stuart Gardoll --- app.js | 78 +++++++----- .../{index-DXRCh_lW.js => index-DuMP9yQl.js} | 114 +++++++++--------- dist/index.html | 2 +- e2e/stu380-deploy.spec.js | 17 ++- 4 files changed, 122 insertions(+), 89 deletions(-) rename dist/assets/{index-DXRCh_lW.js => index-DuMP9yQl.js} (77%) diff --git a/app.js b/app.js index 1f7e9df..68343b4 100644 --- a/app.js +++ b/app.js @@ -2230,21 +2230,19 @@ class FlutterFlowApiClient { lastHttpStatus = response.status; // The status alone classifies this response — the body read is - // diagnostic only, so it runs detached: a stalled error body must - // not hide a definitive refusal behind the UI bound. - response - .clone() - .text() - .then( - (responseText) => - console.log( - `Push to ${baseUrl} returned ${response.status}: ${responseText}`, - ), - () => - console.log( - `Push to ${baseUrl} returned ${response.status} (unreadable response body)`, - ), - ); + // diagnostic only: detached so it can't block the refusal path, and + // bounded+cancelled so a stalled body can't leave a reader (and its + // connection) open past the bound. + readBodyBounded(response.clone(), PUSH_BODY_READ_TIMEOUT_MS).then( + (responseText) => + console.log( + `Push to ${baseUrl} returned ${response.status}: ${responseText}`, + ), + () => + console.log( + `Push to ${baseUrl} returned ${response.status} (unreadable response body)`, + ), + ); // A 5xx is the server's own failure report: it can be raised after // the write was applied, so it can never prove a refusal. @@ -2377,6 +2375,38 @@ class FlutterFlowApiClient { } } +/** + * Reads a response body to text under a bound. Unlike `text()`, it keeps the + * reader so that on expiry the stream is cancelled for real — `body.cancel()` + * rejects while a `text()`/`json()` read holds the lock, but `reader.cancel()` + * is valid even mid-read, so a stalled body releases its connection instead + * of leaving a pending reader alive after the waiter settled. + * @param {Response} response - Response whose body to read + * @param {number} ms - How long to wait for the body + * @returns {Promise} Rejects when the body stalls or the read fails + */ +function readBodyBounded(response, ms) { + const reader = response.body?.getReader?.(); + const work = reader + ? (async () => { + const decoder = new TextDecoder(); + let text = ""; + while (true) { + const { done, value } = await reader.read(); + if (done) break; + text += decoder.decode(value, { stream: true }); + } + return text + decoder.decode(); + })() + : Promise.resolve(""); + return withUiTimeout(work, ms, (resolve, reject) => { + try { + reader?.cancel()?.catch?.(() => {}); + } catch {} + reject(new Error("The response body stalled before it finished.")); + }); +} + /** * Parses the response from pushCode API call. * @param {Response} response - Fetch response object @@ -2391,14 +2421,10 @@ async function parsePushCodeResponse( try { // The status alone classifies the response — the body only carries the - // error detail, so this read is bounded: a stalled body must not hide a - // definitive refusal (or an acceptance) behind the outer UI bound. - jsonResult = await withUiTimeout( - response.json(), - bodyTimeoutMs, - (resolve, reject) => - reject(new Error("The push response body stalled before it finished.")), - ); + // error detail, so this read is bounded and cancellable: a stalled body + // must not hide a definitive refusal (or an acceptance) behind the outer + // UI bound nor leave a pending reader behind. + jsonResult = JSON.parse(await readBodyBounded(response, bodyTimeoutMs)); } catch (error) { // Both reads share the same connection: a body dropped mid-flight makes // the clone reject too. The received status is still definitive — a non-ok @@ -2406,11 +2432,7 @@ async function parsePushCodeResponse( // before the body was lost. let text = ""; try { - text = await withUiTimeout( - originalResponse.text(), - bodyTimeoutMs, - (resolve, reject) => reject(new Error("stalled")), - ); + text = await readBodyBounded(originalResponse, bodyTimeoutMs); } catch (readError) { // The body never arrived; classify on the status alone. } diff --git a/dist/assets/index-DXRCh_lW.js b/dist/assets/index-DuMP9yQl.js similarity index 77% rename from dist/assets/index-DXRCh_lW.js rename to dist/assets/index-DuMP9yQl.js index 2013dac..d1bbd39 100644 --- a/dist/assets/index-DXRCh_lW.js +++ b/dist/assets/index-DuMP9yQl.js @@ -1,8 +1,8 @@ -(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const s of r)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function n(r){const s={};return r.integrity&&(s.integrity=r.integrity),r.referrerPolicy&&(s.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?s.credentials="include":r.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function i(r){if(r.ep)return;r.ep=!0;const s=n(r);fetch(r.href,s)}})();var w=typeof window<"u"?window:void 0,Ne=typeof globalThis<"u"?globalThis:w,He=Ne?.navigator,P=Ne?.document,me=Ne?.location,Xa=Ne?.fetch,qo=Ne!=null&&Ne.XMLHttpRequest&&"withCredentials"in new Ne.XMLHttpRequest?Ne.XMLHttpRequest:void 0,dc=Ne?.AbortController,Mp=Ne?.CompressionStream,Ge=He?.userAgent;function fd(){return!(!w||w.navigator.onLine===!1)}var vi=typeof globalThis<"u"?globalThis:w;vi&&typeof self>"u"&&(vi.self=vi),vi&&typeof File>"u"&&(vi.File=function(){});var B=w??{},ne={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function fc(t,e,n,i,r,s,o){try{var a=t[s](o),l=a.value}catch(u){return void n(u)}a.done?e(l):Promise.resolve(l).then(i,r)}function se(t){return function(){var e=this,n=arguments;return new Promise((function(i,r){var s=t.apply(e,n);function o(l){fc(s,i,r,o,a,"next",l)}function a(l){fc(s,i,r,o,a,"throw",l)}o(void 0)}))}}function I(){return I=Object.assign?Object.assign.bind():function(t){for(var e=1;arguments.length>e;e++){var n=arguments[e];for(var i in n)({}).hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},I.apply(null,arguments)}function hd(t,e){if(t==null)return{};var n={};for(var i in t)if({}.hasOwnProperty.call(t,i)){if(e.indexOf(i)!==-1)continue;n[i]=t[i]}return n}var hc=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function pc(t){return typeof t=="string"||t}function gc(t){return typeof t=="string"?t:void 0}var _i,Lp=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],Ut=(function(t){return t.AnonymousId="anonymous_id",t.DistinctId="distinct_id",t.Props="props",t.EnablePersonProcessing="enable_person_processing",t.PersonMode="person_mode",t.FeatureFlagDetails="feature_flag_details",t.FeatureFlags="feature_flags",t.FeatureFlagPayloads="feature_flag_payloads",t.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",t.BootstrapFeatureFlags="bootstrap_feature_flags",t.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",t.OverrideFeatureFlags="override_feature_flags",t.Queue="queue",t.AiQueue="ai_queue",t.LogsQueue="logs_queue",t.OptedOut="opted_out",t.SessionId="session_id",t.SessionStartTimestamp="session_start_timestamp",t.SessionLastTimestamp="session_timestamp",t.PersonProperties="person_properties",t.GroupProperties="group_properties",t.InstalledAppBuild="installed_app_build",t.InstalledAppVersion="installed_app_version",t.SessionReplay="session_replay",t.PushRegistered="push_registered",t.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",t.SurveyLastSeenDate="survey_last_seen_date",t.SurveysSeen="surveys_seen",t.Surveys="surveys",t.RemoteConfig="remote_config",t.FlagsEndpointWasHit="flags_endpoint_was_hit",t.DeviceId="device_id",t})({}),mc=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),Np=["$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"],Op=["token"],pd="NativeGzipValidationError",Vo=t=>t.length>=2&&t[0]===31&&t[1]===139,vc=(t,e)=>t===mc.GZipJS||e===mc.GZipJS||e==="gzip",_c=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",pr=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=pd,e},Bp=(function(){var t=se((function*(e,n){18>e.size&&pr("too-short");var i=new Uint8Array(yield e.slice(0,10).arrayBuffer());Vo(i)&&i[2]===8||pr("invalid-header");var r=new DataView(yield e.slice(e.size-8).arrayBuffer());r.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(_i)return _i;_i=[];for(var c=0;256>c;c++){for(var d=c,f=0;8>f;f++)d=1&d?3988292384^d>>>1:d>>>1;_i[c]=d>>>0}return _i})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(n)&&pr("invalid-crc");var s=n.length>>>0;r.getUint32(4,!0)!==s&&pr("invalid-size")}));return function(e,n){return t.apply(this,arguments)}})();function Go(){return Go=se((function*(t,e,n){e===void 0&&(e=!0);try{var i=new TextEncoder().encode(t),r=new globalThis.CompressionStream("gzip"),s=r.writable.getWriter(),o=s.write(i).then((()=>s.close())).catch((function(){var u=se((function*(c){try{yield s.abort(c)}catch{}throw c}));return function(c){return u.apply(this,arguments)}})()),a=new Response(r.readable).blob(),l=(yield Promise.all([a,o]))[0];return yield Bp(l,i),l}catch(u){if(n!=null&&n.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),Go.apply(this,arguments)}var Dp=["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"],yc=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var n=t.toLowerCase();return Dp.concat(e).some((i=>{var r=i.toLowerCase();return n.indexOf(r)!==-1}))};function j(t,e){return t.indexOf(e)!==-1}var Is=function(t){return t.trim()},Ko=function(t){return t.replace(/^\$/,"")};function gd(t){var e,n=[];return(e=JSON.stringify(t,(function(i,r){if(typeof r=="bigint")return r.toString();if(typeof r!="function"&&typeof r!="symbol"){if(r instanceof Error)return{name:r.name,message:r.message,stack:r.stack};if(r&&typeof r=="object"){for(;n.length>0&&n[n.length-1]!==this;)n.pop();if(n.includes(r))return"[Circular]";n.push(r)}return r}})))!==null&&e!==void 0?e:"null"}var md=Object.prototype,vd=md.hasOwnProperty,ks=md.toString,U=Array.isArray||function(t){return ks.call(t)==="[object Array]"},je=t=>typeof t=="function",he=t=>t===Object(t)&&!U(t),Kt=t=>{if(he(t)){for(var e in t)if(vd.call(t,e))return!1;return!0}return!1},C=t=>t===void 0,X=t=>ks.call(t)=="[object String]",Yo=t=>X(t)&&t.trim().length===0,Ye=t=>t===null,H=t=>C(t)||Ye(t),ke=t=>ks.call(t)=="[object Number]"&&t==t,Dt=t=>ke(t)&&t>0,mt=t=>ks.call(t)==="[object Boolean]",jp=t=>t instanceof FormData,Up=t=>j(Np,t),Hp=t=>j(Op,t);function _d(t){return t===null||typeof t!="object"}function Hr(t,e){return{}.toString.call(t)==="[object "+e+"]"}function Qa(t){return typeof Event<"u"&&yd(t,Event)}function yd(t,e){try{return t instanceof e}catch{return!1}}var Wp=[!0,"true",1,"1","yes"],fo=t=>j(Wp,t),zp=[!1,"false",0,"0","no"];function At(t,e,n,i,r){return e>n&&(i.warn("min cannot be greater than max."),e=n),ke(t)?t>n?(i.warn(" cannot be greater than max: "+n+". Using max value instead."),n):e>t?(i.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(i.warn(" must be a number. using max or fallback. max: "+n+", fallback: "+r),At(r||n,e,n,i))}class qp{constructor(e){this.tt={},this.et=e.et,this.it=At(e.bucketSize,0,100,e.rt),this.nt=At(e.refillRate,0,this.it,e.rt),this.st=At(e.refillInterval,0,864e5,e.rt)}ot(e,n){var i=Math.floor((n-e.lastAccess)/this.st);i>0&&(e.tokens=Math.min(e.tokens+i*this.nt,this.it),e.lastAccess=e.lastAccess+i*this.st)}consumeRateLimit(e){var n,i=Date.now(),r=String(e),s=this.tt[r];return s?this.ot(s,i):this.tt[r]=s={tokens:this.it,lastAccess:i},s.tokens===0||(s.tokens--,s.tokens===0&&((n=this.et)==null||n.call(this,e)),s.tokens===0)}stop(){this.tt={}}}var rt="Mobile",Wr="iOS",Yt="Android",ei="Tablet",wd=Yt+" "+ei,bd="iPad",Ed="Apple",Sd=Ed+" Watch",Bi="Safari",ti="BlackBerry",xd="Samsung",Id=xd+"Browser",kd=xd+" Internet",Pn="Chrome",Vp=Pn+" OS",Cd=Pn+" "+Wr,el="Internet Explorer",Ad=el+" "+rt,tl="Opera",Gp=tl+" Mini",nl="Edge",Pd="Microsoft "+nl,Zn="Firefox",Fd=Zn+" "+Wr,Gi="Nintendo",Ki="PlayStation",Xn="Xbox",Rd=Yt+" "+rt,Td=rt+" "+Bi,Pi="Windows",Jo=Pi+" Phone",wc="Nokia",Zo="Ouya",$d="Generic",Kp=$d+" "+rt.toLowerCase(),Md=$d+" "+ei.toLowerCase(),Xo="Konqueror",Ld="Oculus Browser",zr="Vivaldi",Nd="Yandex",qr="Whale",Qo="DuckDuckGo",Od="Pale Moon",Vr="Waterfox",Di="Brave",Bd="Google Search App",we="(\\d+(\\.\\d+)?)",ho=new RegExp("Version/"+we),Yp=new RegExp(Xn,"i"),Jp=new RegExp(Ki+" \\w+","i"),Zp=new RegExp(Gi+" \\w+","i"),il=new RegExp(ti+"|PlayBook|BB10","i"),Xp={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000",5.1:"XP",5.2:"XP","6.0":"Vista",6.1:"7",6.2:"8",6.3:"8.1",6.4:"10","10.0":"10"},Dd=function(t,e,n,i){e=e||"";var r=(function(s){return s!=null&&s.brave?Di:null})(n);return r||(i!=null&&i.detectGoogleSearchApp&&j(t,"GSA/")?Bd:j(t," OPR/")&&j(t,"Mini")?Gp:j(t," OPR/")?tl:il.test(t)?ti:j(t,"IE"+rt)||j(t,"WPDesktop")?Ad:j(t,"OculusBrowser")?Ld:j(t,Id)?kd:j(t,nl)||j(t,"Edg/")?Pd:j(t,zr+"/")?zr:j(t,"YaBrowser/")?Nd:j(t,qr+"/")?qr:j(t,Qo+"/")||j(t,"Ddg/")?Qo:j(t,"FBIOS")?"Facebook "+rt:j(t,"UCWEB")||j(t,"UCBrowser")?"UC Browser":j(t,"CriOS")?Cd:j(t,"CrMo")||j(t,Pn)?Pn:j(t,Yt)&&j(t,Bi)?Rd:j(t,"FxiOS")?Fd:j(t.toLowerCase(),Xo.toLowerCase())?Xo:j(t,Di+"/")?Di:((s,o)=>o&&j(o,Ed)||(function(a){return j(a,Bi)&&!j(a,Pn)&&!j(a,Yt)})(s))(t,e)?j(t,rt)?Td:Bi:j(t,"PaleMoon/")?Od:j(t,Vr+"/")?Vr:j(t,Zn)?Zn:j(t,"MSIE")||j(t,"Trident/")?el:j(t,"Gecko")?Zn:"")},Qp={[Ad]:[new RegExp("rv:"+we)],[Pd]:[new RegExp(nl+"?\\/"+we)],[Pn]:[new RegExp("("+Pn+"|CrMo)\\/"+we)],[Cd]:[new RegExp("CriOS\\/"+we)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+we)],[Bi]:[ho],[Td]:[ho],[tl]:[new RegExp("(Opera|OPR)\\/"+we)],[Zn]:[new RegExp(Zn+"\\/"+we)],[Fd]:[new RegExp("FxiOS\\/"+we)],[Xo]:[new RegExp("Konqueror[:/]?"+we,"i")],[ti]:[new RegExp(ti+" "+we),ho],[Rd]:[new RegExp("android\\s"+we,"i")],[kd]:[new RegExp(Id+"\\/"+we)],[Ld]:[new RegExp("OculusBrowser\\/"+we)],[zr]:[new RegExp(zr+"\\/"+we)],[Nd]:[new RegExp("YaBrowser\\/"+we)],[qr]:[new RegExp(qr+"\\/"+we)],[Di]:[new RegExp(Di+"\\/"+we)],[Qo]:[new RegExp("(DuckDuckGo|Ddg)\\/"+we)],[Od]:[new RegExp("PaleMoon\\/"+we)],[Vr]:[new RegExp(Vr+"\\/"+we)],[Bd]:[new RegExp("GSA\\/"+we)],[el]:[new RegExp("(rv:|MSIE )"+we)],Mozilla:[new RegExp("rv:"+we)]},eg=function(t,e,n,i){var r=Dd(t,e,n,i),s=Qp[r];if(C(s))return null;for(var o=0;s.length>o;o++){var a=t.match(s[o]);if(a)return parseFloat(a[a.length-2])}return null},bc=[[new RegExp(Xn+"; "+Xn+" (.*?)[);]","i"),t=>[Xn,t&&t[1]||""]],[new RegExp(Gi,"i"),[Gi,""]],[new RegExp(Ki,"i"),[Ki,""]],[il,[ti,""]],[new RegExp(Pi,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Jo,""];if(new RegExp(rt).test(e)&&!/IEMobile\b/.test(e))return[Pi+" "+rt,""];var n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){var i=Xp[n[1]]||"";return/arm/i.test(e)&&(i="RT"),[Pi,i]}return[Pi,""]}],[/((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=C(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+Yt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Yt+")","i"),t=>t&&t[2]?[Yt,[t[2],t[3],t[4]||"0"].join(".")]:[Yt,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{var e=["Mac OS X",""];return t&&t[1]&&(e[1]=[t[1],t[2],t[3]||"0"].join(".")),e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[Vp,""]],[/Linux|debian/i,["Linux",""]]],Ec=function(t){return Zp.test(t)?Gi:Jp.test(t)?Ki:Yp.test(t)?Xn:new RegExp(Zo,"i").test(t)?Zo:new RegExp("("+Jo+"|WPDesktop)","i").test(t)?Jo:/iPad/.test(t)?bd:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?Sd:il.test(t)?ti:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(wc,"i").test(t)?wc:/(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(rt).test(t)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(t)||/pixel[\daxl ]{1,6}/i.test(t)&&!/pixel c/i.test(t)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(t)||/lmy47v/i.test(t)&&!/QTAQZ3/i.test(t)?Yt:wd:new RegExp("(pda|"+rt+")","i").test(t)?Kp:new RegExp(ei,"i").test(t)&&!new RegExp(ei+" pc","i").test(t)?Md:""},tg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Sc(t,e){return typeof(n=t)=="string"&&tg.test(n)?t:e();var n}function fn(t){return t&&t.split("#")[0]}function rl(t,e){var n=setTimeout(t,e);return n?.unref&&n?.unref(),n}function xc(t,e,n){return jd.apply(this,arguments)}function jd(){return(jd=se((function*(t,e,n){var i;try{return yield Promise.race([t,new Promise(((r,s)=>{i=rl((()=>{try{n?.(),r()}catch(o){s(o)}}),e)}))])}finally{clearTimeout(i)}}))).apply(this,arguments)}var ng=t=>t instanceof Error,Ud={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}},ig=Ud.info;function Hd(t){if(mt(t))return{boolValue:t};if(typeof t=="number")return Number.isFinite(t)?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:{stringValue:String(t)};if(typeof t=="string")return{stringValue:t};if(U(t))return{arrayValue:{values:t.map((e=>Hd(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function Gr(t){var e=[];for(var n in t){var i=t[n];Ye(i)||C(i)||e.push({key:n,value:Hd(i)})}return e}function rg(t,e){var n=Ud[t.level||"info"]||ig,i=n.text,r=n.number,s=String(Date.now())+"000000",o={};e.distinctId&&(o.posthogDistinctId=e.distinctId),e.sessionId&&(o.sessionId=e.sessionId),e.windowId&&(o["window.id"]=e.windowId),H(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),H(e.lastActivityTimestamp)||(o.lastActivityTimestamp=String(e.lastActivityTimestamp)),e.currentUrl&&(o["url.full"]=e.currentUrl),e.screenName&&(o["screen.name"]=e.screenName),e.appState&&(o["app.state"]=e.appState),e.activeFeatureFlags&&e.activeFeatureFlags.length>0&&(o.feature_flags=e.activeFeatureFlags);var a=I({},o,t.attributes||{}),l={timeUnixNano:s,observedTimeUnixNano:s,severityNumber:r,severityText:i,body:{stringValue:t.body},attributes:Gr(a)};return t.trace_id&&(l.traceId=t.trace_id),t.span_id&&(l.spanId=t.span_id),C(t.trace_flags)||(l.flags=t.trace_flags),l}function Wd(t,e,n){return I({},t.resourceAttributes,{"service.name":t.serviceName||"unknown_service"},t.environment&&{"deployment.environment":t.environment},t.serviceVersion&&{"service.version":t.serviceVersion},{"telemetry.sdk.name":e,"telemetry.sdk.version":n})}function zd(t,e,n,i){return{resourceLogs:[{resource:{attributes:Gr(e)},scopeLogs:[{scope:{name:n,version:i},logRecords:t}]}]}}let sg=class{constructor(t,e,n,i,r,s,o){var a;s===void 0&&(s=()=>Promise.resolve()),this._instance=t,this.Ne=e,this.rt=n,this.ut=i,this.ht=r,this.dt=s,this.vt=o,this.ct=null,this.ft=0,this.yt=0,this.bt=0,this._t=0,this.wt=!1,this.kt=e.maxBufferSize,this.xt=Math.max((a=e.maxQueueSize)!==null&&a!==void 0?a:e.maxBufferSize,e.maxBufferSize),this.St=e.flushIntervalMs,this.Ct=e.maxBatchRecordsPerPost,this.Mt=e.rateCapWindowMs,this.Tt=e.maxLogsPerInterval}reset(){this.Et(),this.ct=null,this.bt=0,this._t=0,this.wt=!1,this.ft=0,this.yt=0,this.Ct=this.Ne.maxBatchRecordsPerPost}onReconnect(){this.yt=0,this.It()}captureLog(t){if(!this._instance.isDisabled&&!this._instance.optedOut&&t!=null&&t.body){var e=this.Pt(t);if(e!==null)if(e.body){if(this.Rt()){var n={record:rg(e,this.ut())};this.ht((()=>this.At(n)))}}else this.rt.info("Log was rejected in beforeSend function")}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Log was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for log:",o),null}return i}Rt(){if(this.Tt===void 0)return!0;var t=Date.now(),e=t-this.bt;return this.Mt>e&&e>=0||(this.bt=t,this._t=0,this.wt=!1),this.Tt>this._t?(this._t++,!0):(this.wt||(this.rt.warn("captureLog dropping logs: exceeded "+this.Tt+" logs per "+this.Mt+"ms"),this.wt=!0),!1)}flush(){var t=this;return se((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return se((function*(){var e;t.Et();var n=(e=t._instance.getPersistedProperty(Ut.LogsQueue))!==null&&e!==void 0?e:[];if(n.length!==0)for(var i=n.length,r=0;n.length>0&&i>r;){var s,o;t.ft=0;var a=Math.min(n.length,t.Ct),l=n.slice(0,a),u=zd(l.map((d=>d.record)),t.Lt(),(s=t.vt)!==null&&s!==void 0?s:t._instance.getLibraryId(),t._instance.getLibraryVersion()),c=yield t._instance.Ot(u);if(c.kind==="too-large"&&l.length>1)t.Ct=Math.max(1,Math.floor(l.length/2)),t.rt.warn("Received 413 when sending logs batch of size "+l.length+", reducing batch size to "+t.Ct);else if(c.kind==="retry-later"||(c.kind==="too-large"?t.rt.warn("Dropping a single log record after 413 with batch size 1 — the record is larger than the server cap and cannot be split further."):c.kind==="ok"&&t.Ne.maxBatchRecordsPerPost>t.Ct&&(t.Ct=Math.min(t.Ne.maxBatchRecordsPerPost,t.Ct+1)),yield t.Dt(l.length),n=(o=t._instance.getPersistedProperty(Ut.LogsQueue))!==null&&o!==void 0?o:[],r+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return se((function*(){var n,i=Math.max(0,t-e.ft),r=(n=e._instance.getPersistedProperty(Ut.LogsQueue))!==null&&n!==void 0?n:[];e._instance.setPersistedProperty(Ut.LogsQueue,r.slice(i)),yield e.dt()}))()}Lt(){return Wd(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var n=(e=this._instance.getPersistedProperty(Ut.LogsQueue))!==null&&e!==void 0?e:[];this.xt>n.length||(n.shift(),this.ft++,this.rt.info("Logs queue is full, dropping oldest record.")),n.push(t),this._instance.setPersistedProperty(Ut.LogsQueue,n),this.kt>n.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=rl((()=>{this.Nt=void 0,this.It()}),t))}qt(){var t=Math.min(Math.max(0,this.yt-1),6);return this.St*Math.pow(2,t)}jt(){var t=this._instance.getPersistedProperty(Ut.LogsQueue);return!!t&&t.length>0}shutdown(t){var e=this;return se((function*(){e.Et();var n=e.flush().catch((()=>{}));t!==void 0?yield xc(n,t):yield n}))()}flushWithTimeout(t){var e=this;return se((function*(){var n=e.flush();yield xc(n,t,(()=>{n.catch((()=>{}))}))}))()}It(){this.flush().then((()=>{this.yt=0}),(t=>{this.yt++,this.rt.error("PostHog logs flush failed:",t)})).finally((()=>{!this._instance.isDisabled&&this.jt()&&this.$t(this.qt())}))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}};var po=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function Ic(t){return String(t)+"000000"}function kc(t,e,n,i){var r="";return i&&(r=Object.keys(i).sort().map((s=>JSON.stringify(s)+":"+JSON.stringify(i[s]))).join(",")),t+"\0"+e+"\0"+(n??"")+"\0"+r}let og=class{constructor(t,e,n){this._instance=t,this.Ne=e,this.rt=n,this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Wt=0}count(t,e,n){e===void 0&&(e=1),this.Vt({name:t,type:"count",value:e,unit:n?.unit,attributes:n?.attributes})}gauge(t,e,n){this.Vt({name:t,type:"gauge",value:e,unit:n?.unit,attributes:n?.attributes})}histogram(t,e,n){this.Vt({name:t,type:"histogram",value:e,unit:n?.unit,attributes:n?.attributes})}flush(){var t=this,e=this.ct,n=(function(){var r=se((function*(){e&&(yield e.catch((()=>{}))),yield t.Zt()}));return function(){return r.apply(this,arguments)}})(),i=n().finally((()=>{this.ct===i&&(this.ct=null)}));return this.ct=i,i}drainWindow(){if(this.Bt.size===0)return null;var t=this.Bt;return this.Bt=new Map,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Gt(t)}reset(){this.Wt++,this.Et(),this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set}Vt(t){if(!this._instance.isDisabled&&!this._instance.optedOut){var e=this.Pt(t);if(e!==null)if(e.name&&typeof e.name=="string")if(typeof e.value=="number"&&Number.isFinite(e.value))if(e.type==="count"&&0>e.value)this.rt.warn("Dropping count '"+e.name+"': counters are monotonic, value must be >= 0");else{var n,i;try{n=e.attributes?I({},e.attributes):void 0,i=kc(e.type,e.name,e.unit,n)}catch(o){return void this.rt.warn("Dropping metric '"+e.name+"': attributes could not be serialized",o)}var r=this.Bt.get(i);if(!r){if(!this.Qt())return;r={name:e.name,type:e.type,unit:e.unit,attributes:n,windowStartMs:Date.now()},this.Bt.set(i,r)}var s=this.Ut.get(e.name);s===void 0?this.Ut.set(e.name,e.type):s===e.type||this.zt.has(e.name)||(this.zt.add(e.name),this.rt.warn("Metric name '"+e.name+"' is already used as a "+s+"; recording it as a "+e.type+" too will blend both series in charts. Use a distinct name.")),this.Kt(r,e.value),this.$t()}else this.rt.warn("Dropping metric '"+e.name+"': value must be a finite number");else this.rt.warn("Dropping metric with empty name")}}Qt(){return this.Ne.maxSeriesPerFlush>this.Bt.size||(this.Ht||(this.Ht=!0,this.rt.warn("Metric series cap reached ("+this.Ne.maxSeriesPerFlush+" per flush window); dropping new series until the next flush. Reduce attribute cardinality.")),!1)}Kt(t,e){var n;switch(t.type){case"count":t.total=((n=t.total)!==null&&n!==void 0?n:0)+e;break;case"gauge":t.last=e;break;case"histogram":t.hist||(t.hist={count:0,sum:0,min:e,max:e,bucketCounts:new Array(po.length+1).fill(0)});var i=t.hist;i.count+=1,i.sum+=e,i.min=Math.min(i.min,e),i.max=Math.max(i.max,e),i.bucketCounts[(function(r,s){for(var o=0;s.length>o;o++)if(s[o]>=r)return o;return s.length})(e,po)]+=1}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Metric was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for metric:",o),null}return i}$t(){this.Nt||(this.Nt=rl((()=>{this.Nt=void 0,this.flush().catch((t=>{this.rt.error("Metrics flush failed:",t)}))}),this.Ne.flushIntervalMs))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}Zt(){var t=this;return se((function*(){if(t.Bt.size!==0){var e=t.Bt;t.Bt=new Map,t.Ht=!1,t.Ut=new Map,t.zt=new Set;var n=t.Wt,i=yield t._instance.Jt(t.Gt(e));if(n===t.Wt)switch(i.kind){case"ok":return;case"retry-later":return t.Yt(e),void t.$t();case"too-large":return void t.rt.warn("Metrics batch exceeded the server size limit and was dropped");case"fatal":return void t.rt.error("Failed to send metrics batch:",i.error)}}}))()}Gt(t){return e=this.Xt(t),n=(function(s,o,a){return I({},s.resourceAttributes,{"service.name":s.serviceName||"unknown_service"},s.environment&&{"deployment.environment":s.environment},s.serviceVersion&&{"service.version":s.serviceVersion},{"telemetry.sdk.name":o,"telemetry.sdk.version":a})})(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion()),i=this._instance.getLibraryId(),r=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:Gr(n)},scopeMetrics:[{scope:{name:i,version:r},metrics:e}]}]};var e,n,i,r}Xt(t){var e=Ic(Date.now()),n=new Map;for(var i of t.values()){var r,s=kc(i.type,i.name,i.unit,void 0),o=n.get(s);o||(o=I({name:i.name},i.unit&&{unit:i.unit}),i.type==="count"?o.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:i.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:1,dataPoints:[]},n.set(s,o));var a=Gr((r=i.attributes)!==null&&r!==void 0?r:{}),l=Ic(i.windowStartMs);if(i.type==="count"){var u,c={attributes:a,startTimeUnixNano:l,timeUnixNano:e,asDouble:(u=i.total)!==null&&u!==void 0?u:0};o.sum.dataPoints.push(c)}else if(i.type==="gauge"){var d,f={attributes:a,timeUnixNano:e,asDouble:(d=i.last)!==null&&d!==void 0?d:0};o.gauge.dataPoints.push(f)}else i.hist&&o.histogram.dataPoints.push({attributes:a,startTimeUnixNano:l,timeUnixNano:e,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:po})}return Array.from(n.values())}Yt(t){var e,n;for(var i of t){var r=i[0],s=i[1],o=this.Bt.get(r);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,s.windowStartMs),o.type){case"count":o.total=((e=o.total)!==null&&e!==void 0?e:0)+((n=s.total)!==null&&n!==void 0?n:0);break;case"gauge":break;case"histogram":if(s.hist)if(o.hist){o.hist.count+=s.hist.count,o.hist.sum+=s.hist.sum,o.hist.min=Math.min(o.hist.min,s.hist.min),o.hist.max=Math.max(o.hist.max,s.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=s.hist.bucketCounts[a]}else o.hist=s.hist}else this.Qt()&&this.Bt.set(r,s)}}};var gr,Cc,go;function ag(t){var e=globalThis._posthogChunkIds;if(e){var n=Object.keys(e);return go&&n.length===Cc||(Cc=n.length,go=n.reduce(((i,r)=>{gr||(gr={});var s=gr[r];if(s)i[s[0]]=s[1];else for(var o=t(r),a=o.length-1;a>=0;a--){var l=o[a],u=l?.filename,c=e[r];if(u&&c){i[u]=c,gr[r]=[u,c];break}}return i}),{})),go}}class lg{constructor(e,n,i){i===void 0&&(i=[]),this.coercers=e,this.stackParser=n,this.modifiers=i}buildFromUnknown(e,n){n===void 0&&(n={});var i=n&&n.mechanism||{handled:!0,type:"generic"},r=this.buildCoercingContext(i,n,0).apply(e),s=this.buildParsingContext(n),o=this.parseStacktrace(r,s);return{$exception_list:this.convertToExceptionList(o,i),$exception_level:"error"}}modifyFrames(e){var n=this;return se((function*(){for(var i of e)i.stacktrace&&i.stacktrace.frames&&U(i.stacktrace.frames)&&(i.stacktrace.frames=yield n.applyModifiers(i.stacktrace.frames));return e}))()}coerceFallback(e){var n;return{type:"Error",value:"Unknown error",stack:(n=e.syntheticException)==null?void 0:n.stack,synthetic:!0}}parseStacktrace(e,n){var i,r;return e.cause!=null&&(i=this.parseStacktrace(e.cause,n)),e.stack!=""&&e.stack!=null&&(r=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?n.skipFirstLines:0),n.chunkIdMap)),I({},e,{cause:i,stack:r})}applyChunkIds(e,n){return e.map((i=>(i.filename&&n&&(i.chunk_id=n[i.filename]),i)))}applyCoercers(e,n){for(var i of this.coercers)if(i.match(e))return i.coerce(e,n);return this.coerceFallback(n)}applyModifiers(e){var n=this;return se((function*(){var i=e;for(var r of n.modifiers)i=yield r(i);return i}))()}convertToExceptionList(e,n){var i,r,s,o={type:e.type,value:e.value,mechanism:{type:(i=n.type)!==null&&i!==void 0?i:"generic",handled:(r=n.handled)===null||r===void 0||r,synthetic:(s=e.synthetic)!==null&&s!==void 0&&s}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,I({},n,{handled:!0}))),a}buildParsingContext(e){var n;return{chunkIdMap:ag(this.stackParser),skipFirstLines:(n=e.skipFirstLines)!==null&&n!==void 0?n:1}}buildCoercingContext(e,n,i){i===void 0&&(i=0);var r=(s,o)=>{if(4>=o){var a=this.buildCoercingContext(e,n,o);return this.applyCoercers(s,a)}};return I({},n,{syntheticException:i==0?n.syntheticException:void 0,mechanism:e,apply:s=>r(s,i),next:s=>r(s,i+1)})}}var ni="?";function ea(t,e,n,i,r){var s={platform:t,filename:e,function:n===""?ni:n,in_app:!0};return C(i)||(s.lineno=i),C(r)||(s.colno=r),s}var qd=(t,e)=>{var n=t.indexOf("safari-extension")!==-1,i=t.indexOf("safari-web-extension")!==-1;return n||i?[t.indexOf("@")!==-1?t.split("@")[0]:ni,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},cg=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,ug=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,dg=/\((\S*)(?::(\d+))(?::(\d+))\)/,fg=(t,e)=>{var n=cg.exec(t);if(n)return ea(e,n[1],ni,+n[2],+n[3]);var i=ug.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var r=dg.exec(i[2]);r&&(i[2]=r[1],i[3]=r[2],i[4]=r[3])}var s=qd(i[1]||ni,i[2]);return ea(e,s[1],s[0],i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},hg=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,pg=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,gg=(t,e)=>{var n=hg.exec(t);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){var i=pg.exec(n[3]);i&&(n[1]=n[1]||"eval",n[3]=i[1],n[4]=i[2],n[5]="")}var r=n[3],s=n[1]||ni,o=qd(s,r);return ea(e,r=o[1],s=o[0],n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},Ac=/\(error: (.*)\)/;class mg{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,n){var i=X(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:i?e.stack:void 0,cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var n=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?n+": "+e.message:n}isDOMException(e){return Hr(e,"DOMException")}isDOMError(e){return Hr(e,"DOMError")}}class vg{match(e){return(function(n){switch({}.toString.call(n)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return yd(n,Error)}})(e)}coerce(e,n){return{type:this.getType(e),value:this.getMessage(e,n),stack:this.getStack(e),cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,n){var i=e.message;return String(i.error&&typeof i.error.message=="string"?i.error.message:i)}getStack(e){return e.stacktrace||e.stack||void 0}}class _g{constructor(){}match(e){return!!Hr(e,"ErrorEvent")&&(e.error!=null||this.fe(e))}coerce(e,n){var i;if(e.error!=null)return n.apply(e.error);var r=n.apply(e.message);return I({},r,{stack:(i=this.pe(e))!==null&&i!==void 0?i:r.stack,synthetic:!0})}fe(e){return X(e.message)&&e.message.length>0}pe(e){var n=e;if(X(n.filename)&&n.filename.length>0){var i,r,s=(i=n.lineno)!==null&&i!==void 0?i:0,o=(r=n.colno)!==null&&r!==void 0?r:0;return`Error - at `+n.filename+":"+s+":"+o}}}var yg=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class wg{match(e){return typeof e=="string"}coerce(e,n){var i,r=this.getInfos(e),s=r[0],o=r[1];return{type:s??"Error",value:o??e,stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}getInfos(e){var n="Error",i=e,r=e.match(yg);return r&&(n=r[1],i=r[2]),[n,i]}}var bg=["fatal","error","warning","log","info","debug"];function Vd(t,e){e===void 0&&(e=40);var n=Object.keys(t);if(n.sort(),!n.length)return"[object has no keys]";for(var i=n.length;i>0;i--){var r=n.slice(0,i).join(", ");if(e>=r.length)return i===n.length?r:r.length>e?r.slice(0,e)+"...":r}return""}class Eg{match(e){return typeof e=="object"&&e!==null}coerce(e,n){var i,r,s=this.getErrorPropertyFromObject(e);return s?n.apply(s):{type:this.getType(e),value:this.getValue(e),stack:(i=this.getStack(e))!==null&&i!==void 0?i:(r=n.syntheticException)==null?void 0:r.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return Qa(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var n="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(n+=" with message: '"+e.message+"'"),n}if("message"in e&&typeof e.message=="string")return e.message;var i=this.getObjectClassName(e);return(i&&i!=="Object"?"'"+i+"'":"Object")+" captured as exception with keys: "+Vd(e)}isSeverityLevel(e){return X(e)&&!Yo(e)&&bg.indexOf(e)>=0}getStack(e){try{return X(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:X(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(var n in e)if({}.hasOwnProperty.call(e,n)){var i=e[n];if(ng(i))return i}}getObjectClassName(e){try{var n=Object.getPrototypeOf(e);return n?n.constructor.name:void 0}catch{return}}}class Sg{match(e){return Qa(e)}coerce(e,n){var i,r=e.constructor.name;return{type:r,value:r+" captured as exception with keys: "+Vd(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class xg{match(e){return _d(e)}coerce(e,n){var i;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class Ig{match(e){return Hr(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Qa(e))return!1;try{var n=e.detail;return n!=null&&typeof n=="object"&&"reason"in n}catch{return!1}}coerce(e,n){var i,r=this.getUnhandledRejectionReason(e);return _d(r)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(r),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}:n.apply(r)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}}var Kr="$message",Yr="$timestamp",kg=new Set([Kr,Yr]),mo={enabled:!0,max_bytes:32768};function Jr(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:mo.enabled,max_bytes:Ag(t.max_bytes,mo.max_bytes)}:I({},mo)}class Cg{constructor(e){this.Ke=[],this.Je=0,this.Ne=Jr(e)}setConfig(e){this.Ne=Jr(e),this.Xe()}add(e){var n=(function(r){var s;try{s=gd(r)}catch{return}try{var o=JSON.parse(s);if(!he(o))return;var a=o,l=a[Kr],u=a[Yr];return!X(l)||l.trim().length===0||!X(u)&&!ke(u)?void 0:{step:a,json:s}}catch{return}})(e);if(n){var i=(function(r){if(typeof TextEncoder<"u")return new TextEncoder().encode(r).length;for(var s=encodeURIComponent(r),o=0,a=0;s.length>a;a++)s[a]==="%"?(o+=1,a+=2):o+=1;return o})(n.json);i>this.Ne.max_bytes||(this.Ke.push({step:n.step,bytes:i}),this.Je+=i,this.Xe())}}getAttachable(){return this.Ke.map((e=>e.step))}clear(){this.Ke=[],this.Je=0}size(){return this.Ke.length}Xe(){for(;this.Je>this.Ne.max_bytes&&this.Ke.length>0;){var e=this.Ke.shift();e&&(this.Je-=e.bytes)}}}function Ag(t,e){if(!ke(t)||t===1/0||t===-1/0)return e;var n=Math.floor(t);return 0>n?e:n}var Gd=function(t,e){var n=(e===void 0?{}:e).debugEnabled,i={k(r){if(w&&(ne.DEBUG||w.POSTHOG_DEBUG||n)&&!C(w.console)&&w.console){for(var s=("__rrweb_original__"in w.console[r])?w.console[r].__rrweb_original__:w.console[r],o=arguments.length,a=new Array(o>1?o-1:0),l=1;o>l;l++)a[l-1]=arguments[l];s(t,...a)}},debug(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("debug",...s)},info(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("log",...s)},warn(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("warn",...s)},error(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("error",...s)},critical(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];console.error(t,...s)},uninitializedWarning(r){i.error("You must initialize PostHog before calling "+r)},createLogger:(r,s)=>Gd(t+" "+r,s)};return i},A=Gd("[PostHog.js]"),pe=A.createLogger,Pg=pe("[ExternalScriptsLoader]"),vo=(t,e,n)=>{if(t.config.disable_external_dependency_loading)return Pg.warn(e+" was requested but loading of external scripts is disabled."),n("Loading of external scripts is disabled");var i=P?.querySelectorAll("script");if(i){for(var r,s=function(){if(i[o].src===e){var l=i[o];return l.__posthog_loading_callback_fired?{v:n()}:(l.addEventListener("load",(u=>{l.__posthog_loading_callback_fired=!0,n(void 0,u)})),l.onerror=u=>n(u),{v:void 0})}},o=0;i.length>o;o++)if(r=s())return r.v}var a=()=>{if(!P)return n("document not found");var l=P.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=d=>{l.__posthog_loading_callback_fired=!0,n(void 0,d)},l.onerror=d=>n(d),t.config.prepare_external_dependency_script&&(l=t.config.prepare_external_dependency_script(l)),!l)return n("prepare_external_dependency_script returned null");if(t.config.external_scripts_inject_target==="head")P.head.appendChild(l);else{var u,c=P.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):P.body.appendChild(l)}};P!=null&&P.body?a():P?.addEventListener("DOMContentLoaded",a)};B.__PosthogExtensions__=B.__PosthogExtensions__||{},B.__PosthogExtensions__.loadExternalDependency=(t,e,n)=>{if(e!=="remote-config"){var i;if(t.config.strict_script_versioning)i=t.requestRouter.endpointFor("assets","/static/"+t.version+"/"+e+".js");else{var r="/static/"+e+".js?v="+t.version;if(e==="toolbar"){var s=3e5;r=r+"&t="+Math.floor(Date.now()/s)*s}i=t.requestRouter.endpointFor("assets",r)}vo(t,i,n)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");vo(t,o,n)}},B.__PosthogExtensions__.loadSiteApp=(t,e,n)=>{var i=t.requestRouter.endpointFor("api",e);vo(t,i,n)};ne.DEBUG=!1,ne.LIB_VERSION="1.415.7",ne.LIB_NAME="web";var Kd="$people_distinct_id",Yi="$device_id",_o="$device_model",Fi="__alias",Ri="__timers",ta="$autocapture_disabled_server_side",na="$heatmaps_enabled_server_side",ia="$exception_capture_enabled_server_side",ra="$error_tracking_suppression_rules",sa="$error_tracking_capture_extension_exceptions",oa="$web_vitals_enabled_server_side",sl="$dead_clicks_enabled_server_side",ol="$product_tours_enabled_server_side",aa="$web_vitals_allowed_metrics",An="$session_recording_remote_config",Yd="$replay_sample_rate",Jd="$replay_override_sampling",Zd="$replay_override_linked_flag",Xd="$replay_override_url_trigger",Qd="$replay_override_event_trigger",Kn="$sesid",al="$session_is_sampled",Sn="$enabled_feature_flags",Ti="$active_feature_flags",Ar="$early_access_features",la="$feature_flag_details",$i="$feature_flag_payloads",Pr="$feature_flag_request_id",Zr="$minimal_flag_called_events",It="$override_feature_flags",xn="$override_feature_flag_payloads",jt="$stored_person_properties",In="$stored_group_properties",ca="$surveys",Xr="$surveys_loaded_at",ua="$surveys_activated",Fr="$surveys_activated_session",Rr="$surveys_activated_timestamps",Mi="ph_product_tours",Cn="$flag_call_reported",Li="$flag_call_reported_session_id",Tr="$feature_flag_errors",ji="$feature_flag_evaluated_at",at="$user_state",da="$client_session_props",fa="$capture_rate_limit",ha="$initial_campaign_params",pa="$initial_referrer_info",Qr="$initial_person_info",es="$epp",mr="$posthog_cookieless",ef="$cookieless_mode",tf="$sdk_debug_extensions_init_method",nf="$sdk_debug_extensions_init_time_ms",rf="$sdk_debug_recording_script_not_loaded",ll="PostHog loadExternalDependency extension not found.",kn="on_reject",Wt="always",Un="anonymous",vn="identified",ga="identified_only",ts="visibilitychange",ns="beforeunload",Vn="$pageview",yo="$pageleave",wo="$identify",Pc="$groupidentify";function vr(t,e){U(t)&&t.forEach(e)}function ie(t,e){if(!H(t))if(U(t))t.forEach(e);else if(jp(t))t.forEach(((i,r)=>e(i,r)));else for(var n in t)vd.call(t,n)&&e(t[n],n)}var fe=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;e>i;i++)n[i-1]=arguments[i];for(var r of n)for(var s in r)r[s]!==void 0&&(t[s]=r[s]);return t};function $r(t){for(var e=Object.keys(t),n=e.length,i=new Array(n);n--;)i[n]=[e[n],t[e[n]]];return i}var Fc=function(t){try{return t()}catch{return}},Fg=function(t){return function(){try{for(var e=arguments.length,n=new Array(e),i=0;e>i;i++)n[i]=arguments[i];return t.apply(this,n)}catch(r){A.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),A.critical(r)}}},cl=function(t){var e={};return ie(t,(function(n,i){(X(n)&&n.length>0||ke(n))&&(e[i]=n)})),e},Rg=["herokuapp.com","vercel.app","netlify.app"];function Tg(t){var e=t?.hostname;if(!X(e))return!1;var n=e.split(".").slice(-2).join(".");for(var i of Rg)if(n===i)return!1;return!0}function ve(t,e,n,i){var r=i??{},s=r.capture,o=r.passive;t?.addEventListener(e,n,{capture:s!==void 0&&s,passive:o===void 0||o})}function ma(t){return t.name==="ph_toolbar_internal"}var sf=t=>{if(P){try{for(var e=t+"=",n=P.cookie.split(";").filter((s=>s.length)),i=0;n.length>i;i++){for(var r=n[i];r.charAt(0)==" ";)r=r.substring(1,r.length);if(r.indexOf(e)===0)return decodeURIComponent(r.substring(e.length,r.length))}}catch{}return null}};Math.trunc||(Math.trunc=function(t){return 0>t?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return ke(t)&&isFinite(t)&&Math.floor(t)===t});class is{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,n,i,r){if(!Number.isInteger(e)||!Number.isInteger(n)||!Number.isInteger(i)||!Number.isInteger(r)||0>e||0>n||0>i||0>r||e>0xffffffffffff||n>4095||i>1073741823||r>4294967295)throw new RangeError("invalid field value");var s=new Uint8Array(16);return s[0]=e/Math.pow(2,40),s[1]=e/Math.pow(2,32),s[2]=e/Math.pow(2,24),s[3]=e/Math.pow(2,16),s[4]=e/256,s[5]=e,s[6]=112|n>>>8,s[7]=n,s[8]=128|i>>>24,s[9]=i>>>16,s[10]=i>>>8,s[11]=i,s[12]=r>>>24,s[13]=r>>>16,s[14]=r>>>8,s[15]=r,new is(s)}toString(){for(var e="",n=0;this.bytes.length>n;n++)e=e+(this.bytes[n]>>>4).toString(16)+(15&this.bytes[n]).toString(16),n!==3&&n!==5&&n!==7&&n!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new is(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var n=0;16>n;n++){var i=this.bytes[n]-e.bytes[n];if(i!==0)return Math.sign(i)}return 0}}class $g{generate(){var e=this.generateOrAbort();if(!C(e))return e;this.S=0;var n=this.generateOrAbort();if(C(n))throw new Error("Could not generate UUID after timestamp reset");return n}generateOrAbort(){var e=Date.now();if(e>this.S)this.S=e,this.C();else{if(this.S>=e+1e4)return;this.I++,this.I>4398046511103&&(this.S++,this.C())}return is.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 Mg}}var Rc,of=t=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;t.length>e;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};w&&!C(w.crypto)&&crypto.getRandomValues&&(of=t=>crypto.getRandomValues(t));class Mg{nextUint32(){return this.R.length>this.O||(of(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var Ht=()=>Lg().toString(),Lg=()=>(Rc||(Rc=new $g)).generate(),yi="",Ng=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,zt={N:()=>!!P,j(t){A.error("cookieStore error: "+t)},P:sf,H(t){var e;try{e=JSON.parse(zt.P(t))||{}}catch{}return e},F(t,e,n,i,r){if(!P)return!1;try{var s="",o="",a=(function(c,d){if(d){var f=(function(p,g){if(g===void 0&&(g=P),yi)return yi;if(!g||["localhost","127.0.0.1"].includes(p))return"";for(var m=p.split("."),v=Math.min(m.length,8),E="dmn_chk_"+Ht();!yi&&v--;){var S=m.slice(v).join("."),_=E+"=1;domain=."+S+";path=/";g.cookie=_+";max-age=3",g.cookie.includes(E)&&(g.cookie=_+";max-age=0",yi=S)}return yi})(c);if(!f){var h=(p=>{var g=p.match(Ng);return g?g[0]:""})(c);h!==f&&A.info("Warning: cookie subdomain discovery mismatch",h,f),f=h}return f?"; domain=."+f:""}return""})(P.location.hostname,i);if(n){var l=new Date;l.setTime(l.getTime()+864e5*n),s="; expires="+l.toUTCString()}r&&(o="; secure");var u=t+"="+encodeURIComponent(JSON.stringify(e))+s+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&A.warn("cookieStore warning: large cookie, len="+u.length),P.cookie=u,!0}catch{return!1}},q(t,e){if(P!=null&&P.cookie)try{zt.F(t,"",-1,e)}catch{return}}},bo=null,le={N(){if(!Ye(bo))return bo;var t=!0;if(C(w))t=!1;else try{var e="__mplssupport__";le.F(e,"xyz"),le.P(e)!=='"xyz"'&&(t=!1),le.q(e)}catch{t=!1}return t||A.error("localStorage unsupported; falling back to cookie store"),bo=t,t},j(t){A.error("localStorage error: "+t)},P(t){try{return w?.localStorage.getItem(t)}catch(e){le.j(e)}return null},H(t){try{return JSON.parse(le.P(t))||{}}catch{}return null},F(t,e){try{return w?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(n){le.j(n)}return!1},q(t){try{w?.localStorage.removeItem(t)}catch(e){le.j(e)}}},Og=[Yi,"distinct_id",Kn,al,es,Qr,at],_r={},Bg={N:()=>!0,j(t){A.error("memoryStorage error: "+t)},P:t=>_r[t]||null,H:t=>_r[t]||null,F:(t,e)=>(_r[t]=e,!0),q(t){delete _r[t]}},_n=null,be={N(){if(!Ye(_n))return _n;if(_n=!0,C(w))_n=!1;else try{var t="__support__";be.F(t,"xyz"),be.P(t)!=='"xyz"'&&(_n=!1),be.q(t)}catch{_n=!1}return _n},j(t){A.error("sessionStorage error: ",t)},P(t){try{return w?.sessionStorage.getItem(t)}catch(e){be.j(e)}return null},H(t){try{return JSON.parse(be.P(t))||null}catch{}return null},F(t,e){try{return w?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(n){be.j(n)}return!1},q(t){try{w?.sessionStorage.removeItem(t)}catch(e){be.j(e)}}};class Dg{constructor(e){this._instance=e}get Ne(){return this._instance.config}get consent(){return this.ti()?0:this.ei}isOptedOut(){return this.Ne.cookieless_mode===Wt||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===kn}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===0}isRejected(){return this.consent===0||this.consent===-1&&this.Ne.opt_out_capturing_by_default}optInOut(e){this.ii.F(this.ri,e?1:0,this.Ne.cookie_expiration,this.Ne.cross_subdomain_cookie,this.Ne.secure_cookie)}reset(){this.ii.q(this.ri,this.Ne.cross_subdomain_cookie)}get ri(){var e=this._instance.config,n=e.token,i=e.opt_out_capturing_cookie_prefix;return e.consent_persistence_name||(i?i+n:"__ph_opt_in_out_"+n)}get ei(){var e=this.ii.P(this.ri);return fo(e)?1:j(zp,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,n=e==="localStorage"?le:zt;if(!this.ni||this.ni!==n){this.ni=n;var i=e==="localStorage"?zt:le;i.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(fo(i.P(this.ri))),i.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[He?.doNotTrack,He?.msDoNotTrack,B.doNotTrack].some((e=>fo(e)))}}function af(t,e){var n,i=t==null||(n=t.config)==null?void 0:n.get_current_url;if(!je(i))return e;try{var r=i(e);return X(r)&&r?r:e}catch(s){return A.error("Error in get_current_url, falling back to window.location.href",s),e}}var lf="__POSTHOG_TOOLBAR__",jg=1,Ug=3,Hg=11;function Tc(t){return t instanceof Element&&(t.id===lf||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function hn(t){return!!t&&t.nodeType===jg}function et(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function cf(t){return!!t&&t.nodeType===Ug}function uf(t){return!!t&&t.nodeType===Hg&&hn(t.host)}var df=1e3;function ul(t){return t?Is(t).split(/\s+/):[]}function $c(t,e){var n=(function(i){var r,s=w==null||(r=w.location)==null?void 0:r.href;return C(s)?void 0:af(i,s)})(e);return!!(n&&t&&t.some((i=>n.match(i))))}function rs(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 ul(e)}function ff(t){return H(t)?null:Is(t).split(/(\s+)/).filter((e=>Ui(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function Ji(t){var e="";return _a(t)&&!mf(t)&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;cf(n)&&n.textContent&&(e+=(i=ff(n.textContent))!==null&&i!==void 0?i:"")})),Is(e)}function Eo(t){var e;return C(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var dl=["a","button","form","input","select","textarea","label"];function va(t,e){if(C(e))return!0;var n,i=function(s){if(e.some((o=>(function(a,l){var u=a.matches||a.matchesSelector||a.msMatchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.oMatchesSelector;try{return!!u&&u.call(a,l)}catch{return!1}})(s,o))))return{v:!0}};for(var r of t)if(n=i(r))return n.v;return!1}function hf(t){var e=t.parentNode;return!(!e||!hn(e))&&e}var Wg=[".ph-no-autocapture","[data-ph-no-autocapture]"],pf=["next","previous","prev",">","<"],zg=[...pf,"+","-","−","–"],Mc=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,Lc=[".ph-no-rageclick",".ph-no-capture"],qg=["","text","search","email","password","url","tel","number"];function Nc(t,e){if(!w||fl(t))return!1;var n,i,r,s,o;if(mt(e)?(n=!!e&&Lc,i=void 0,r=!1):(n=(s=e?.css_selector_ignorelist)!==null&&s!==void 0?s:Lc,i=e?.content_ignorelist,r=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),n===!1||r&&(function(l){return!(!l||!hn(l))&&(!!et(l,"textarea")||(et(l,"input")?j(qg,(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=gf(t,!1).targetElementList;return!(function(l,u){if(l===!1||C(l))return!1;var c;if(l===!0)c=pf;else{if(!U(l))return!1;if(l.length>10)return A.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var f=d.safeText,h=d.ariaLabel;return c.some((p=>Mc(f,p)||Mc(h,p)))}))})(i,a.map((l=>{var u;return{safeText:Ji(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!va(a,n)}var fl=t=>!t||et(t,"html")||!hn(t),gf=(t,e)=>{if(!w||fl(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,i=[t],r=t;r.parentNode&&!et(r,"body");)if(uf(r.parentNode))i.push(r.parentNode.host),r=r.parentNode.host;else{var s=hf(r);if(!s)break;if(e||dl.indexOf(s.tagName.toLowerCase())>-1)n=!0;else try{var o=w.getComputedStyle(s);o&&o.getPropertyValue("cursor")==="pointer"&&(n=!0)}catch{}i.push(s),r=s}return{parentIsUsefulElement:n,targetElementList:i}};function _a(t){for(var e=new Set,n=0,i=t;i.parentNode&&!et(i,"body");i=i.parentNode){if(n++>=df||e.has(i))return!1;e.add(i);var r=rs(i);if(j(r,"ph-sensitive")||j(r,"ph-no-capture"))return!1}if(j(rs(t),"ph-include"))return!0;var s=t.type||"";if(X(s))switch(s.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!X(o)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(o.replace(/[^a-zA-Z0-9]/g,""))}function mf(t){return!!(et(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||et(t,"select")||et(t,"textarea")||t.getAttribute("contenteditable")==="true")}var Oc=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}))$"),Bc=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,Vg=[16,15,14,13],Gg=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),Dc=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),jc=/[0-9A-Za-z_]/;function Kg(t){for(var e=0,n=!1,i=t.length-1;i>=0;i--){var r=t.charCodeAt(i)-48;n&&(r*=2)>9&&(r-=9),e+=r,n=!n}return e%10==0}function Ui(t,e){if(e===void 0&&(e=!0),H(t))return!1;if(X(t)){t=Is(t);var n=e?Oc.test((t||"").replace(/[- ]/g,"")):(function(r){var s;for(Bc.lastIndex=0;s=Bc.exec(r);){var o=s[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of Vg){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(Oc.test(d)&&Kg(d))return!0}}}return!1})(t);if(n)return!1;var i=e?Gg.test(t):(function(r){var s;for(Dc.lastIndex=0;s=Dc.exec(r);){var o=s[1],a=s[3];if(!(o&&a&&jc.test(o)&&jc.test(a)))return!0}return!1})(t);if(i)return!1}return!0}function Uc(t){var e=Ji(t);return Ui(e=(e+" "+vf(t)).trim())?e:""}function vf(t){var e="";return t&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;if(n&&((i=n.tagName)==null?void 0:i.toLowerCase())==="span")try{var r=Ji(n);e=(e+" "+r).trim(),n.childNodes&&n.childNodes.length&&(e=(e+" "+vf(n)).trim())}catch(s){A.error("[AutoCapture]",s)}})),e}function Hc(t){return t.replace(/"|\\"/g,'\\"')}function Yg(t){var e=t.attr__class;if(e)return U(e)?e:ul(e)}var yr=pe("[Dead Clicks]"),Jg=()=>!0,Zg=t=>{var e,n=!((e=t.instance.persistence)==null||!e.get_property(sl)),i=t.instance.config.capture_dead_clicks;return mt(i)?i:!!he(i)||n};class Wc{get lazyLoadedDeadClicksAutocapture(){return this.si}constructor(e,n,i){this.instance=e,this.isEnabled=n,this.onCapture=i,this.startIfEnabledOrStop()}onRemoteConfig(e){if(e.ok){var n=e.config;"captureDeadClicks"in n&&(this.instance.persistence&&this.instance.persistence.register({[sl]:n.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var n,i;(n=B.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture?e():(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"dead-clicks-autocapture",(r=>{r?yr.error("failed to load script",r):e()}))}oi(){var e;if(P){if(!this.si&&(e=B.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var n=he(this.instance.config.capture_dead_clicks)?I({},this.instance.config.capture_dead_clicks):{};n.__onCapture=this.onCapture,this.onCapture&&(n.capture_dead_swipes=!1),this.si=B.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.si.start(P),yr.info("starting...")}}else yr.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,yr.info("stopping..."))}}var So=pe("[SegmentIntegration]"),_f="posthog-js";function yf(t,e){var n=e===void 0?{}:e,i=n.organization,r=n.projectId,s=n.prefix,o=n.severityAllowList,a=o===void 0?["error"]:o,l=n.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,f,h,p,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var v,E=((d=c.exception)==null?void 0:d.values)||[],S=E.map((b=>I({},b,{stacktrace:b.stacktrace?I({},b.stacktrace,{type:"raw",frames:(b.stacktrace.frames||[]).map((k=>I({},k,{platform:"web:javascript"})))}):void 0}))),_={$exception_message:((f=E[0])==null?void 0:f.value)||c.message,$exception_type:(h=E[0])==null?void 0:h.type,$exception_level:c.level,$exception_list:S,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((p=E[0])==null?void 0:p.value)||c.message,$sentry_exception_type:(g=E[0])==null?void 0:g.type,$sentry_tags:c.tags};return i&&r&&(_.$sentry_url=(s||"https://sentry.io/organizations/")+i+"/issues/?project="+r+"&query="+c.event_id),u&&((v=t.exceptions)==null||v.sendExceptionEvent(_)),c}}class Xg{constructor(e,n,i,r,s,o){this.name=_f,this.setupOnce=function(a){a(yf(e,{organization:n,projectId:i,prefix:r,severityAllowList:s,sendExceptionsToPostHog:o==null||o}))}}}class zc{constructor(e){this.li=(n,i,r)=>{r&&(r.noSessionId||r.activityTimeout||r.sessionPastMaximumLength||r.crossTabAdoption)&&(A.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:n,changeReason:r}),this.ui=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.hi()}hi(){var e;this.di=(e=this._instance.sessionManager)==null?void 0:e.onSessionId(this.li)}destroy(){var e;(e=this.di)==null||e.call(this),this.di=void 0}doPageView(e,n){var i,r=this.vi(e,n);return this.ui={pathname:(i=w?.location.pathname)!==null&&i!==void 0?i:"",pageViewId:n,timestamp:e},this._instance.scrollManager.resetContext(),r}doPageLeave(e){var n;return this.vi(e,(n=this.ui)==null?void 0:n.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.ui)==null?void 0:e.pageViewId}}vi(e,n){var i=this.ui;if(!i)return{$pageview_id:n};var r={$pageview_id:n,$prev_pageview_id:i.pageViewId},s=this._instance.scrollManager.getContext();if(s&&!this._instance.config.disable_scroll_properties){var o=s.maxScrollHeight,a=s.lastScrollY,l=s.maxScrollY,u=s.maxContentHeight,c=s.lastContentY,d=s.maxContentY;if(!(C(o)||C(a)||C(l)||C(u)||C(c)||C(d))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),d=Math.ceil(d);var f=o>1?At(a/o,0,1,A):1,h=o>1?At(l/o,0,1,A):1,p=u>1?At(c/u,0,1,A):1,g=u>1?At(d/u,0,1,A):1;r=fe(r,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:f,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:h,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:p,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return i.pathname&&(r.$prev_pageview_pathname=i.pathname),i.timestamp&&(r.$prev_pageview_duration=(e.getTime()-i.timestamp.getTime())/1e3),r}}var xo=["flags","surveys"],Qg={[Kd]:{exposure:"hidden"},[Fi]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[Ri]:{exposure:"hidden"},[ta]:{exposure:"event"},[na]:{exposure:"hidden"},[ia]:{exposure:"event"},[ra]:{exposure:"hidden"},[sa]:{exposure:"event"},[oa]:{exposure:"event"},[sl]:{exposure:"event"},[ol]:{exposure:"hidden"},[aa]:{exposure:"event"},[An]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[Kn]:{exposure:"hidden"},[al]:{exposure:"event"},[Yd]:{exposure:"event",shouldSkipFromEventProperties:t=>Ye(t)},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},$sess_rec_flush_size:{exposure:"hidden"},[Sn]:{exposure:"hidden",storageGroup:"flags"},[Ti]:{exposure:"hidden",storageGroup:"flags"},[Ar]:{exposure:"hidden"},[la]:{exposure:"hidden",storageGroup:"flags"},[$i]:{exposure:"hidden",storageGroup:"flags"},[Pr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[Zr]:{exposure:"hidden",storageGroup:"flags"},[It]:{exposure:"hidden"},[xn]:{exposure:"hidden"},[jt]:{exposure:"hidden"},[In]:{exposure:"hidden"},[ca]:{exposure:"hidden",storageGroup:"surveys"},[Xr]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[ua]:{exposure:"event"},[Fr]:{exposure:"hidden"},[Rr]:{exposure:"hidden"},[Mi]:{exposure:"hidden"},$product_tours_activated:{exposure:"hidden"},$product_tours_activated_session:{exposure:"hidden"},$conversations_widget_session_id:{exposure:"event"},$conversations_ticket_id:{exposure:"event"},$conversations_widget_state:{exposure:"event"},$conversations_user_traits:{exposure:"event"},[Cn]:{exposure:"hidden"},[Li]:{exposure:"hidden"},[Tr]:{exposure:"hidden"},[ji]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[at]:{exposure:"hidden"},[da]:{exposure:"hidden"},[fa]:{exposure:"hidden"},[ha]:{exposure:"hidden"},[pa]:{exposure:"hidden"},[Qr]:{exposure:"hidden"},[es]:{exposure:"hidden"},[Jd]:{exposure:"event"},[Zd]:{exposure:"event"},[Xd]:{exposure:"event"},[Qd]:{exposure:"event"},[tf]:{exposure:"event"},[nf]:{exposure:"event"},[rf]:{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"}},em=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],yn=t=>{var e=Qg[t];if(e)return e;for(var n of em){var i=n[1];if(t.indexOf(n[0])===0)return i}},Yn=(t,e)=>{try{return JSON.stringify(t,((n,i)=>typeof i=="bigint"?i.toString():i),e)}catch{return gd(t)}},ss=t=>{var e=P?.createElement("a");return C(e)?null:(e.href=t,e)},ii=function(t,e){for(var n,i=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),r=0;i.length>r;r++){var s=i[r].split("=");if(s[0]===e){n=s;break}}if(!U(n)||2>n.length)return"";var o=n[1];try{o=decodeURIComponent(o)}catch{A.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},Zi=function(t,e,n){if(!t||!e||!e.length)return t;for(var i=t.split("#"),r=i[1],s=(i[0]||"").split("?"),o=s[1],a=s[0],l=(o||"").split("&"),u=[],c=0;l.length>c;c++){var d=l[c].split("=");U(d)&&(e.includes(d[0])?u.push(d[0]+"="+n):u.push(l[c]))}var f=a;return o!=null&&(f+="?"+u.join("&")),r!=null&&(f+="#"+r),f},os=function(t,e){var n=t.match(new RegExp(e+"=([^&]*)"));return n?n[1]:null},wf=(t,e)=>t>=e&&fd(),bf=(t,e,n,i)=>{if(t===0){if(fd()){var r=e+1;return r===n&&i(),r}return e}return 0},wr="https?://(.*)",ri=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],tm=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...ri],Xi="",nm=["li_fat_id"];function Ef(t,e,n){if(!P)return{};var i,r=e?[...ri,...n||[]]:[],s=Sf(Zi(P.URL,r,Xi),t),o=(i={},ie(nm,(function(a){var l=sf(a);i[a]=l||null})),i);return fe(o,s)}function Sf(t,e){var n=tm.concat(e||[]),i={};return ie(n,(function(r){var s=ii(t,r);i[r]=s||null})),i}function xf(t){var e=(function(s){return s?s.search(wr+"google.([^/?]*)")===0?"google":s.search(wr+"bing.com")===0?"bing":s.search(wr+"yahoo.com")===0?"yahoo":s.search(wr+"duckduckgo.com")===0?"duckduckgo":null:null})(t),n=e!="yahoo"?"q":"p",i={};if(!Ye(e)){i.$search_engine=e;var r=P?ii(P.referrer,n):"";r.length&&(i.ph_keyword=r)}return i}function qc(){return navigator.language||navigator.userLanguage}var as="$direct";function If(){return P?.referrer||as}function kf(t,e,n){n===void 0&&(n=!1);var i=t?[...ri,...e||[]]:[],r=n?fn(me?.href):me?.href,s=r?.substring(0,1e3);return{r:If().substring(0,1e3),u:s?Zi(s,i,Xi):void 0}}function Cf(t,e){var n;e===void 0&&(e=!1);var i=t.r,r=t.u,s=e?fn(r):r,o={$referrer:i,$referring_domain:i==null?void 0:i==as?as:(n=ss(i))==null?void 0:n.host};if(s){o.$current_url=s;var a=ss(s);o.$host=a?.host,o.$pathname=a?.pathname;var l=Sf(s);fe(o,l)}if(i){var u=xf(i);fe(o,u)}return o}function Af(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function im(){try{return new Date().getTimezoneOffset()}catch{return}}var rm={flags:ji,surveys:Xr},sm=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],Hn="main";class Io{constructor(e,n,i){if(i===void 0&&(i=!0),this.ci={},this.fi=!1,this.pi=!1,this.Ne=e,this.gi=i,this.props={},this.mi=void 0,this.yi=(s=>{var o="";return s.token&&(o=s.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),s.persistence_name?"ph_"+s.persistence_name:"ph_"+o+"_posthog"})(e),this.ii=this.bi(e),this.pi=this.wi(e),this.load(),e.debug&&A.info("Persistence loaded",e.persistence,I({},this.props)),this.update_config(e,e,n),this.save(),w){var r=()=>this.flush();ve(w,"beforeunload",r,{capture:!1}),ve(w,"pagehide",r,{capture:!1})}}ki(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return ke(n)&&n>0?n:0}isDisabled(){return!!this.xi}bi(e){sm.indexOf(e.persistence.toLowerCase())===-1&&(A.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var n,i=(function(o,a){o===void 0&&(o=[]),a===void 0&&(a=!1);var l=[...Og,...o];return I({},le,{H(u){try{var c={};try{c=zt.H(u)||{}}catch{}var d,f=JSON.parse(le.P(u)||"{}");if(a){var h={};for(var p in c){var g=c[p];Ye(g)||g===""||(h[p]=g)}d=fe(f,h)}else d=fe(c,f);return le.F(u,d),d}catch{}return null},F(u,c,d,f,h,p){var g=le.F(u,c,void 0,void 0,p);try{var m={};l.forEach((v=>{c[v]&&(m[v]=c[v])})),Object.keys(m).length&&zt.F(u,m,d,f,h,p)}catch(v){le.j(v)}return g},q(u,c){try{w?.localStorage.removeItem(u),zt.q(u,c)}catch(d){le.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),r=!1,s=e.persistence.toLowerCase();return s==="localstorage"&&le.N()?(n=le,r=!0):s==="localstorage+cookie"&&i.N()?(n=i,r=!0):s==="sessionstorage"&&be.N()?n=be:s==="memory"?n=Bg:s==="cookie"?n=zt:i.N()?(n=i,r=!0):n=zt,this.fi=r,n}Si(e){return this.yi+"__"+e}wi(e){return this.fi&&!!e.split_storage}properties(){var e={};return ie(this.props,((n,i)=>{var r=yn(i);if(!r||r.exposure==="event"){if(r!=null&&r.shouldSkipFromEventProperties!=null&&r.shouldSkipFromEventProperties(n))return;e[i]=n}})),e}load(){if(!this.xi){var e=this.ii.H(this.yi);e&&(this.props=fe({},e)),this.pi&&this.Ci()}}Ci(){for(var e of xo){var n=le.H(this.Si(e));if(n&&!Kt(n)){var i=this.Mi(e);i.persisted=!0,this.Ti(e)||(i.fingerprint=this.Ei(n,e)),this.Ii(e,n)||fe(this.props,n)}}}Ti(e){return Object.keys(this.props).some((n=>{var i;return((i=yn(n))==null?void 0:i.storageGroup)===e}))}Ii(e,n){var i=rm[e];if(!i)return!1;var r=n[i],s=this.props[i];return ke(r)&&ke(s)&&s>r}refreshKey(e){var n;if(!this.xi){var i=this.pi?(n=yn(e))==null?void 0:n.storageGroup:void 0,r=i?le.H(this.Si(i)):this.ii.H(this.yi);if(r&&e in r)this.Pi(e,r[e]);else{if(i){var s=this.ii.H(this.yi);if(s&&e in s)return void this.Pi(e,s[e])}this.Ri(e)}}}save(){if(!this.xi){var e=this.ki();e>0?C(this.Ai)&&(this.Ai=setTimeout((()=>{this.Ai=void 0,this.Fi()}),e)):this.Fi()}}flush(){C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0,this.Fi())}Fi(){this.xi||(this.pi?this.Li():this.Oi(this.ii,this.yi,this.props,Hn))}Li(){var e=this.Di(),n=e.main,i=e.groups;for(var r of(this.Oi(this.ii,this.yi,n,Hn),xo)){var s,o=i[r];(!Kt(o)||(s=this.ci[r])!=null&&s.persisted)&&this.Oi(le,this.Si(r),o,r)}}Di(){var e={},n={flags:{},surveys:{}};return ie(this.props,((i,r)=>{var s,o=(s=yn(r))==null?void 0:s.storageGroup;o?n[o][r]=i:e[r]=i})),{main:e,groups:n}}Ei(e,n){if(n===Hn)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var i={};return ie(e,((r,s)=>{var o;i[s]=(o=yn(s))!=null&&o.volatile?"__volatile__":r})),JSON.stringify(i)}Oi(e,n,i,r){var s=this.Mi(r);if(r===Hn||s.dirty||C(s.fingerprint)){var o;try{if((o=this.Ei(i,r))===s.fingerprint)return void(s.dirty=!1)}catch{o=void 0}e.F(n,i,this.$i,this.Ni,this.qi,this.Ne.debug)?(s.dirty=!1,r!==Hn&&(s.persisted=!0),C(o)||(s.fingerprint=o)):this.Ne.debug&&A.warn('failed to persist storage entry "'+n+'"; will retry on next save')}}remove(e){var n=(e===void 0?{}:e).keepGroupEntries,i=n!==void 0&&n;if(C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0),this.ii.q(this.yi,!1),this.ii.q(this.yi,!0),!i&&this.gi)for(var r of xo)le.q(this.Si(r));i?delete this.ci[Hn]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,n,i){if(he(e)){C(n)&&(n="None"),this.$i=C(i)?this.ji:i;var r=!1;if(ie(e,((s,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==n||(this.Pi(o,s),r=!0)})),r)return this.save(),!0}return!1}register(e,n){if(he(e)){this.$i=C(n)?this.ji:n;var i=!1;if(ie(e,((r,s)=>{e.hasOwnProperty(s)&&(this.props[s]!==r||he(r)||U(r))&&(this.Pi(s,r),i=!0)})),i)return this.save(),!0}return!1}unregister(e){var n=typeof e=="string"?[e]:e,i=!1;for(var r of n)r in this.props&&(this.Ri(r),i=!0);i&&this.save()}update_campaign_params(){var e=P?.URL;if(e!==this.mi){var n=Ef(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);Kt(cl(n))||this.register(n),this.mi=e}}update_search_keyword(){var e;this.register((e=P?.referrer)?xf(e):{})}update_referrer_info(){var e;this.register_once({$referrer:If(),$referring_domain:P!=null&&P.referrer&&((e=ss(P.referrer))==null?void 0:e.host)||as},void 0)}set_initial_person_info(){this.props[ha]||this.props[pa]||this.register_once({[Qr]:kf(this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties,this.Ne.disable_capture_url_hashes)},void 0)}get_initial_props(){var e={};ie([pa,ha],(r=>{var s=this.props[r];s&&ie(s,(function(o,a){e["$initial_"+Ko(a)]=o}))}));var n=this.props[Qr];if(n){var i=(function(r,s){s===void 0&&(s=!1);var o=Cf(r,s),a={};return ie(o,(function(l,u){a["$initial_"+Ko(u)]=l})),a})(n,this.Ne.disable_capture_url_hashes);fe(e,i)}return e}safe_merge(e){return ie(this.props,(function(n,i){i in e||(e[i]=n)})),e}update_config(e,n,i){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!i),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var r=e.persistence!==n.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((f,h)=>f===d[h]))})(e.cookie_persisted_properties||[],n.cookie_persisted_properties||[]),s=r?this.bi(e):this.ii,o=this.wi(e);if(r||o!==this.pi){var a=this.props;this.clear(),this.ii=s,this.pi=o,this.props=a,this.save()}}set_disabled(e){this.xi=e,this.xi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ni&&(this.Ni=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this.qi&&(this.qi=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,n){var i=this.props[Ri]||{};i[e]=n,this.Pi(Ri,i),this.save()}remove_event_timer(e){var n=this.props[Ri]||{},i=n[e];return C(i)||(delete n[e],this.Pi(Ri,n),this.save()),i}get_property(e){return this.props[e]}set_property(e,n){this.Pi(e,n),this.save()}Pi(e,n){var i;this.props[e]=n,(i=yn(e))!=null&&i.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var n,i=(n=yn(e))==null?void 0:n.storageGroup;i&&(this.Mi(i).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function br(t){var e=!0;return{dispose(){if(e){e=!1;var n=t();n&&je(n.then)&&n.then(void 0,(()=>{}))}}}}var Ue={GZipJS:"gzip-js",Base64:"base64"},wi={Activation:"events",Cancellation:"cancelEvents"},ko={Popover:"popover",API:"api",Widget:"widget"},qt={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},Co={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},ya={Popover:"popover",Inline:"inline"},om={SHOWN:"product tour shown"},Vc={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},Gc=pe("[RateLimiter]");class am{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=n=>{var i=n.text;if(i&&i.length)try{(JSON.parse(i).quota_limited||[]).forEach((r=>{Gc.info((r||"events")+" is quota limited."),this.serverLimits[r]=new Date().getTime()+6e4}))}catch(r){return void Gc.warn('could not rate limit - continuing. Error: "'+r?.message+'"',{text:i})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var n,i,r;e===void 0&&(e=!1);var s=this.captureEventsBurstLimit,o=this.captureEventsPerSecond,a=new Date().getTime(),l=(n=(i=this.instance.persistence)==null?void 0:i.get_property(fa))!==null&&n!==void 0?n:{tokens:s,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>s&&(l.tokens=s);var u=1>l.tokens;if(u||e||(l.tokens=Math.max(0,l.tokens-1)),u&&!e){var c=(ke(l.dropped)?l.dropped:0)+1;l.dropped=c,!this.lastEventRateLimited&&this.Hi(c)&&(l.dropped=0)}return this.lastEventRateLimited=u,(r=this.instance.persistence)==null||r.set_property(fa,l),{isRateLimited:u,remainingTokens:l.tokens}}Ui(e){var n=this.instance.config.property_denylist;return!U(n)||!n.includes(e)}zi(){var e;if(this.Ui("$current_url")&&this.Ui("$pathname")&&me!=null&&me.pathname)return""+((e=me.origin)!==null&&e!==void 0?e:"")+me.pathname}Hi(e){var n,i,r=this.captureEventsBurstLimit,s=this.captureEventsPerSecond,o=this.zi(),a=this.Ui("$session_id")?(n=(i=this.instance).get_session_id)==null?void 0:n.call(i):void 0,l=[e+" event(s) dropped since the last warning",o?"triggered on "+o:void 0,a?"session "+a:void 0].filter(Boolean).join(", ");return!!this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited: "+l+". Config is set to "+s+" events per second and "+r+" events burst limit."},{skip_client_rate_limiting:!0})}isServerRateLimited(e){var n=this.serverLimits[e||"events"]||!1;return n!==!1&&new Date().getTime()e(this.remoteConfig))):e()}Vi(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:e})}load(){try{if(this.remoteConfig)return an.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void an.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return an.info("No config found after loading remote JS config. Falling back to JSON."),void this.Vi((n=>{this.Zi(n.json,n),this.Gi()}));this.Zi(e),this.Gi()}))}catch(e){an.error("Error loading remote config",e),this.Zi()}}stop(){this.Ki&&(clearInterval(this.Ki),this.Ki=void 0)}refresh(){!this._instance.Qi()&&P&&P.visibilityState!=="hidden"&&this._instance.reloadFeatureFlags()}Gi(){var e;if(!this.Ki){var n=(e=this._instance.config.remote_config_refresh_interval_ms)!==null&&e!==void 0?e:3e5;n!==0&&(this.Ki=setInterval((()=>{this.refresh()}),n))}}Zi(e,n){!e&&n&&(n.statusCode===0?n.error||an.warn("Failed to fetch remote config from PostHog."):an.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(r){an.error("Error applying remote config",r)}if(e?.hasFeatureFlags!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var i;(i=this._instance.featureFlags)==null||i.ensureFlagsLoaded()}catch(r){an.error("Error loading feature flags",r)}}}var ct=Uint8Array,Ke=Uint16Array,si=Uint32Array,hl=new ct([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]),pl=new ct([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]),Kc=new ct([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ff=function(t,e){for(var n=new Ke(31),i=0;31>i;++i)n[i]=e+=1<i;++i)for(var s=n[i];n[i+1]>s;++s)r[s]=s-n[i]<<5|i;return[n,r]},Rf=Ff(hl,2),wa=Rf[1];Rf[0][28]=258,wa[258]=28;for(var Yc=Ff(pl,0)[1],Tf=new Ke(32768),_e=0;32768>_e;++_e){var Wn=(43690&_e)>>>1|(21845&_e)<<1;Tf[_e]=((65280&(Wn=(61680&(Wn=(52428&Wn)>>>2|(13107&Wn)<<2))>>>4|(3855&Wn)<<4))>>>8|(255&Wn)<<8)>>>1}var Hi=function(t,e,n){for(var i=t.length,r=0,s=new Ke(e);i>r;++r)++s[t[r]-1];var o,a=new Ke(e);for(r=0;e>r;++r)a[r]=a[r-1]+s[r-1]<<1;for(o=new Ke(i),r=0;i>r;++r)o[r]=Tf[a[t[r]-1]++]>>>15-t[r];return o},$n=new ct(288);for(_e=0;144>_e;++_e)$n[_e]=8;for(_e=144;256>_e;++_e)$n[_e]=9;for(_e=256;280>_e;++_e)$n[_e]=7;for(_e=280;288>_e;++_e)$n[_e]=8;var ls=new ct(32);for(_e=0;32>_e;++_e)ls[_e]=5;var lm=Hi($n,9),cm=Hi(ls,5),$f=function(t){return(t/8>>0)+(7&t&&1)},Mf=function(t,e,n){(n==null||n>t.length)&&(n=t.length);var i=new(t instanceof Ke?Ke:t instanceof si?si:ct)(n-e);return i.set(t.subarray(e,n)),i},Ot=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8},bi=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8,t[i+2]|=n>>>16},Ao=function(t,e){for(var n=[],i=0;t.length>i;++i)t[i]&&n.push({s:i,f:t[i]});var r=n.length,s=n.slice();if(!r)return[new ct(0),0];if(r==1){var o=new ct(n[0].s+1);return o[n[0].s]=1,[o,1]}n.sort((function(b,k){return b.f-k.f})),n.push({s:-1,f:25001});var a=n[0],l=n[1],u=0,c=1,d=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=r-1;)a=n[n[d].f>n[u].f?u++:d++],l=n[u!=c&&n[d].f>n[u].f?u++:d++],n[c++]={s:-1,f:a.f+l.f,l:a,r:l};var f=s[0].s;for(i=1;r>i;++i)s[i].s>f&&(f=s[i].s);var h=new Ke(f+1),p=ba(n[c-1],h,0);if(p>e){i=0;var g=0,m=p-e,v=1<i;++i){var E=s[i].s;if(e>=h[E])break;g+=v-(1<>>=m;g>0;){var S=s[i].s;e>h[S]?g-=1<=0&&g;--i){var _=s[i].s;h[_]==e&&(--h[_],++g)}p=e}return[new ct(h),p]},ba=function(t,e,n){return t.s==-1?Math.max(ba(t.l,e,n+1),ba(t.r,e,n+1)):e[t.s]=n},Jc=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new Ke(++e),i=0,r=t[0],s=1,o=function(l){n[i++]=l},a=1;e>=a;++a)if(t[a]==r&&a!=e)++s;else{if(!r&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(r),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(r);s=1,r=t[a]}return[n.subarray(0,i),e]},Ei=function(t,e){for(var n=0,i=0;e.length>i;++i)n+=t[i]*e[i];return n},Ea=function(t,e,n){var i=n.length,r=$f(e+2);t[r]=255&i,t[r+1]=i>>>8,t[r+2]=255^t[r],t[r+3]=255^t[r+1];for(var s=0;i>s;++s)t[r+s+4]=n[s];return 8*(r+4+i)},Zc=function(t,e,n,i,r,s,o,a,l,u,c){Ot(e,c++,n),++r[256];for(var d=Ao(r,15),f=d[0],h=d[1],p=Ao(s,15),g=p[0],m=p[1],v=Jc(f),E=v[0],S=v[1],_=Jc(g),b=_[0],k=_[1],T=new Ke(19),x=0;E.length>x;++x)T[31&E[x]]++;for(x=0;b.length>x;++x)T[31&b[x]]++;for(var F=Ao(T,7),$=F[0],O=F[1],L=19;L>4&&!$[Kc[L-1]];--L);var N,K,V,M,R=u+5<<3,Z=Ei(r,$n)+Ei(s,ls)+o,Ce=Ei(r,f)+Ei(s,g)+o+14+3*L+Ei(T,$)+(2*T[16]+3*T[17]+7*T[18]);if(Z>=R&&Ce>=R)return Ea(e,c,t.subarray(l,l+u));if(Ot(e,c,1+(Z>Ce)),c+=2,Z>Ce){N=Hi(f,h),K=f,V=Hi(g,m),M=g;var oe=Hi($,O);for(Ot(e,c,S-257),Ot(e,c+5,k-1),Ot(e,c+10,L-4),c+=14,x=0;L>x;++x)Ot(e,c+3*x,$[Kc[x]]);c+=3*L;for(var ye=[E,b],$e=0;2>$e;++$e){var ae=ye[$e];for(x=0;ae.length>x;++x)Ot(e,c,oe[Ie=31&ae[x]]),c+=$[Ie],Ie>15&&(Ot(e,c,ae[x]>>>5&127),c+=ae[x]>>>12)}}else N=lm,K=$n,V=cm,M=ls;for(x=0;a>x;++x)if(i[x]>255){var Ie;bi(e,c,N[257+(Ie=i[x]>>>18&31)]),c+=K[Ie+257],Ie>7&&(Ot(e,c,i[x]>>>23&31),c+=hl[Ie]);var Se=31&i[x];bi(e,c,V[Se]),c+=M[Se],Se>3&&(bi(e,c,i[x]>>>5&8191),c+=pl[Se])}else bi(e,c,N[i[x]]),c+=K[i[x]];return bi(e,c,N[256]),c+K[256]},um=new si([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),dm=(function(){for(var t=new si(256),e=0;256>e;++e){for(var n=e,i=9;--i;)n=(1&n&&3988292384)^n>>>1;t[e]=n}return t})(),Po=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8};function fm(t,e){e===void 0&&(e={});var n=(function(){var d=4294967295;return{p(f){for(var h=d,p=0;f.length>p;++p)h=dm[255&h^f[p]]^h>>>8;d=h},d(){return 4294967295^d}}})(),i=t.length;n.p(t);var r,s,o,a,l,u=(a=10+((r=e).filename&&r.filename.length+1||0),l=8,(function(d,f,h,p,g,m){var v=d.length,E=new ct(p+v+5*(1+Math.floor(v/7e3))+g),S=E.subarray(p,E.length-g),_=0;if(!f||8>v)for(var b=0;v>=b;b+=65535){var k=b+65535;v>k?_=Ea(S,_,d.subarray(b,k)):(S[b]=!0,_=Ea(S,_,d.subarray(b,v)))}else{for(var T=um[f-1],x=T>>>13,F=8191&T,$=(1<b;++b){var Ie=V(b),Se=32767&b,De=L[Ie];if(O[Se]=De,L[Ie]=Se,b>=$e){var wt=v-b;if((Ce>7e3||ye>24576)&&wt>423){_=Zc(d,S,0,M,R,Z,oe,ye,ae,b-ae,_),ye=Ce=oe=0,ae=b;for(var ge=0;286>ge;++ge)R[ge]=0;for(ge=0;30>ge;++ge)Z[ge]=0}var Je=2,bt=0,mn=F,Re=Se-De&32767;if(wt>2&&Ie==V(b-Re))for(var Pe=Math.min(x,wt)-1,$t=Math.min(32767,b),Bn=Math.min(258,wt);$t>=Re&&--mn&&Se!=De;){if(d[b+Je]==d[b+Je-Re]){for(var qe=0;Bn>qe&&d[b+qe]==d[b+qe-Re];++qe);if(qe>Je){if(Je=qe,bt=Re,qe>Pe)break;var Dn=Math.min(Re,qe-2),Mt=0;for(ge=0;Dn>ge;++ge){var Lt=b-Re+ge+32768&32767,ut=Lt-O[Lt]+32768&32767;ut>Mt&&(Mt=ut,De=Lt)}}}Re+=(Se=De)-(De=O[Se])+32768&32767}if(bt){M[ye++]=268435456|wa[Je]<<18|Yc[bt];var sn=31&wa[Je],gi=31&Yc[bt];oe+=hl[sn]+pl[gi],++R[257+sn],++Z[gi],$e=b+Je,++Ce}else M[ye++]=d[b],++R[d[b]]}}_=Zc(d,S,!0,M,R,Z,oe,ye,ae,b-ae,_)}return Mf(E,0,p+$f(_)+g)})(s=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):12+o.mem,a,l)),c=u.length;return(function(d,f){var h=f.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>f.level?4:f.level==9?2:0,d[9]=3,f.mtime!=0&&Po(d,4,Math.floor(new Date(f.mtime||Date.now())/1e3)),h){d[3]=8;for(var p=0;h.length>=p;++p)d[p+10]=h.charCodeAt(p)}})(u,e),Po(u,c-8,n.d()),Po(u,c-4,i),u}var hm=!!qo||!!Xa,Lf="text/plain",Mr=!1,Nf=(t,e)=>{var n=t.split("#"),i=n[1],r=n[0].split("?"),s=r[0],o=r[1];if(!o)return t;var a=o.split("&").filter((l=>l.split("=")[0]!==e)).join("&");return s+(a?"?"+a:"")+(i?"#"+i:"")},Cs=function(t,e,n){var i;n===void 0&&(n=!0);var r=t.split("?"),s=r[0],o=r[1],a=I({},e),l=(i=o?.split("&").map((c=>{var d,f=c.split("="),h=f[0],p=n&&(d=a[h])!==null&&d!==void 0?d:f[1];return delete a[h],h+"="+p})))!==null&&i!==void 0?i:[],u=(function(c,d){var f,h;d===void 0&&(d="&");var p=[];return ie(c,(function(g,m){C(g)||C(m)||m==="undefined"||(f=encodeURIComponent((v=>v instanceof File)(g)?g.name:g.toString()),h=encodeURIComponent(m),p[p.length]=h+"="+f)})),p.join(d)})(a);return u&&l.push(u),l.length>0?s+"?"+l.join("&"):s},Fo=t=>{if(t.Ji)return t.Ji;var e=t.data,n=t.compression;if(e){if(n===Ue.GZipJS){var i=fm((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new ct(a.length+(a.length>>>1)),d=0,f=function(m){c[d++]=m},h=0;u>h;++h){if(d+5>c.length){var p=new ct(d+8+(u-h<<1));p.set(c),c=p}var g=a.charCodeAt(h);128>g?f(g):2048>g?(f(192|g>>>6),f(128|63&g)):g>55295&&57344>g?(f(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++h))>>>18),f(128|g>>>12&63),f(128|g>>>6&63),f(128|63&g)):(f(224|g>>>12),f(128|g>>>6&63),f(128|63&g))}return Mf(c,0,d)})(Yn(e)),{mtime:0});return{contentType:Lf,body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),estimatedSize:i.byteLength}}if(n===Ue.Base64){var r=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(Yn(e)),s=(a=>"data="+encodeURIComponent(typeof a=="string"?a:Yn(a)))(r);return{contentType:"application/x-www-form-urlencoded",body:s,estimatedSize:new Blob([s]).size}}var o=Yn(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},Of=t=>{var e,n,i=()=>t.transport==="sendBeacon"?{url:Cs(t.url,{compression:Ue.Base64}),encodedBody:Fo(I({},t,{compression:Ue.Base64,Ji:void 0}))}:{url:Nf(t.url,"compression"),encodedBody:Fo(I({},t,{compression:void 0,Ji:void 0}))};try{e=Fo(t)}catch(r){if(vc(t.compression,ii(t.url,"compression")))return A.error("Failed to gzip request body, sending uncompressed payload",r),i();throw r}return e&&vc(t.compression,ii(t.url,"compression"))&&!((n=e.body)instanceof ArrayBuffer?Vo(new Uint8Array(n)):ArrayBuffer.isView(n)&&Vo(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)))?(Mr=!0,i()):{url:t.url,encodedBody:e}},Bf=t=>{try{return Of(t)}catch(e){return A.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},pm=(function(){var t=se((function*(e){var n=Yn(e.data),i=yield(function(s,o,a){return Go.apply(this,arguments)})(n,ne.DEBUG,{rethrow:!0});if(!i)return e;var r=yield i.arrayBuffer();return I({},e,{Ji:{contentType:Lf,body:r,estimatedSize:r.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),gm=/Failed to fetch|NetworkError|Load failed/i,Df=t=>t?.name==="TypeError"&&gm.test(t?.message||""),jf=t=>{var e=Bf(t);if(e){var n=e.url,i=e.encodedBody,r=i??{},s=r.contentType,o=r.body,a=r.estimatedSize,l=new Headers;ie(t.headers,(function(p,g){l.append(g,p)})),s&&l.append("Content-Type",s);var u=null,c=!1;if(dc){var d=new dc;u={signal:d.signal,timeout:setTimeout((()=>{var p,g;c=!0,d.abort((p=t.timeout,(g=new Error("PostHog request timed out"+(p?" after "+p+"ms":""))).name="AbortError",g))}),t.timeout)}}var f=p=>{c&&p?.name==="AbortError"||Df(p)?A.warn(p):A.error(p),t.callback==null||t.callback({statusCode:0,error:p})};try{var h;Xa(n,I({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(h=u)==null?void 0:h.signal},t.fetchOptions)).then((p=>p.text().then((g=>{var m={statusCode:p.status,text:g};if(p.status===200)try{m.json=JSON.parse(g)}catch(v){A.error(v)}t.callback==null||t.callback(m)})))).catch(f).finally((()=>u?clearTimeout(u.timeout):null))}catch(p){u&&clearTimeout(u.timeout),f(p)}}},Sa=t=>{try{var e,n=Of(t),i=n.url,r=n.encodedBody,s=r??{},o=s.body,a=s.estimatedSize;if(!o)return;var l=o instanceof Blob?o:new Blob([o],{type:s.contentType});if(He.sendBeacon(i,l))return;var u=U(t.data)?t.data:(e=t.data)==null?void 0:e.batch;if(U(u)&&u.length>1&&(a??0)>16384){var c=Math.ceil(u.length/2),d=f=>U(t.data)?f:I({},t.data,{batch:f});return Sa(I({},t,{data:d(u.slice(0,c))})),void Sa(I({},t,{data:d(u.slice(c))}))}A.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),jf(I({},t,{Yi:!0}))}catch(f){A.warn("Beacon send failed",f)}},Xc=(t,e,n,i)=>{var r=i==="query"?e==="POST"?"sent_at":"_":void 0;return Cs(n===Ue.GZipJS?Nf(t,"compression"):t,I({},r?{[r]:Date.now().toString()}:{},n===Ue.GZipJS?{}:{compression:n}))},Lr=[];Xa&&Lr.push({transport:"fetch",method:jf}),qo&&Lr.push({transport:"XHR",method(t){var e=Bf(t);if(e){var n=new qo,i=e.encodedBody;n.open(t.method||"GET",e.url,!0);var r=i??{},s=r.contentType,o=r.body;ie(t.headers,(function(a,l){n.setRequestHeader(l,a)})),s&&n.setRequestHeader("Content-Type",s),t.timeout&&(n.timeout=t.timeout),n.onreadystatechange=()=>{if(n.readyState===4){var a={statusCode:n.status,text:n.responseText};if(n.status===200)try{a.json=JSON.parse(n.responseText)}catch{}t.callback==null||t.callback(a)}},n.send(o)}}}),He!=null&&He.sendBeacon&&Lr.push({transport:"sendBeacon",method:Sa});var xa=3e3;class mm{constructor(e,n){this.Xi=!0,this.tr=[],this.er=At(n?.flush_interval_ms||xa,250,5e3,A.createLogger("flush interval"),xa),this.ir=e}enqueue(e){this.tr.push(e),this.rr||this.nr()}unload(){this.sr();var e=this.tr.length>0?this.ar():{},n=Object.values(e);[...n.filter((i=>i.url.indexOf("/e")===0)),...n.filter((i=>i.url.indexOf("/e")!==0))].map((i=>{this.lr(I({},i,{transport:"sendBeacon"}))}))}enable(){this.Xi=!1,this.nr()}nr(){var e=this;this.Xi||(this.rr=setTimeout((()=>{if(this.sr(),this.tr.length>0){var n=this.ar(),i=function(){var s=n[r],o=new Date().getTime();s.data&&U(s.data)&&ie(s.data,(a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp})),e.lr(s)};for(var r in n)i()}}),this.er))}lr(e){try{this.ir(e)}catch(n){A.error(n)}}sr(){clearTimeout(this.rr),this.rr=void 0}ar(){var e={};return ie(this.tr,(n=>{var i,r=n,s=(r?r.batchKey:null)||r.url;C(e[s])&&(e[s]=I({},r,{data:[]})),(i=e[s].data)==null||i.push(r.data)})),this.tr=[],e}}var vm=["retriesPerformedSoFar"];class _m{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!C(w)&&"onLine"in w.navigator&&(this.dr=w.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},ve(w,"online",this.vr),ve(w,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var n=e.retriesPerformedSoFar,i=hd(e,vm);Dt(n)&&(i.url=Cs(i.url,{retry_count:n})),this._instance._send_request(I({},i,{callback:r=>{if(r.statusCode!==200&&(400>r.statusCode||r.statusCode>=500)){if((r.statusCode===0?3:10)>(n??0))return void this.At(I({retriesPerformedSoFar:n},i));r.statusCode===0&&A.warn("Request failed before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped retrying after "+(n??0)+" retries.")}i.callback==null||i.callback(r)}}))}At(e){var n=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=n+1;var i=(function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),c=Math.random()-.5;return Math.ceil(u+c*(u-l))})(n),r=Date.now()+i;this.tr.push({retryAt:r,requestOptions:e});var s="Enqueued failed request for retry in "+i;navigator.onLine||(s+=" (Browser is offline)"),A.warn(s),this.ur||(this.ur=!0,this.gr())}gr(){if(this.mr&&clearTimeout(this.mr),this.tr.length===0)return this.ur=!1,void(this.mr=void 0);this.mr=setTimeout((()=>{this.dr&&this.tr.length>0&&this.cr(),this.gr()}),this.hr)}cr(){var e=Date.now(),n=[],i=this.tr.filter((s=>e>s.retryAt||(n.push(s),!1)));if(this.tr=n,i.length>0)for(var r of i)this.retriableRequest(r.requestOptions)}unload(){for(var e of(this.mr&&(clearTimeout(this.mr),this.mr=void 0),this.ur=!1,C(w)||(this.vr&&(w.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(w.removeEventListener("offline",this.pr),this.pr=void 0)),this.tr)){var n=e.requestOptions;try{this._instance._send_request(I({},n,{transport:"sendBeacon"}))}catch(i){A.error(i)}}this.tr=[]}}class ym{constructor(e){this.yr=()=>{var n,i,r,s;this.br||(this.br={});var o=this.scrollElement(),a=this.scrollY(),l=o?Math.max(0,o.scrollHeight-o.clientHeight):0,u=a+(o?.clientHeight||0),c=o?.scrollHeight||0;this.br.lastScrollY=Math.ceil(a),this.br.maxScrollY=Math.max(a,(n=this.br.maxScrollY)!==null&&n!==void 0?n:0),this.br.maxScrollHeight=Math.max(l,(i=this.br.maxScrollHeight)!==null&&i!==void 0?i:0),this.br.lastContentY=u,this.br.maxContentY=Math.max(u,(r=this.br.maxContentY)!==null&&r!==void 0?r:0),this.br.maxContentHeight=Math.max(c,(s=this.br.maxContentHeight)!==null&&s!==void 0?s:0)},this._instance=e}get _r(){return this._instance.config.scroll_root_selector}getContext(){return this.br}resetContext(){var e=this.br;return setTimeout(this.yr,0),e}startMeasuringScrollPosition(){ve(w,"scroll",this.yr,{capture:!0}),ve(w,"scrollend",this.yr,{capture:!0}),ve(w,"resize",this.yr)}scrollElement(){if(!this._r)return w?.document.documentElement;var e=U(this._r)?this._r:[this._r];for(var n of e){var i=w?.document.querySelector(n);if(i)return i}}wr(e){var n=e==="y"?"scrollTop":"scrollLeft";if(this._r){var i=this.scrollElement();return i&&i[n]||0}return w?e==="y"?w.scrollY||w.pageYOffset||w.document.documentElement.scrollTop||0:w.scrollX||w.pageXOffset||w.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var wm=t=>kf(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class Qc{constructor(e,n,i,r){this.kr=s=>{var o=this.Sr();if(!o||o.sessionId!==s){var a={sessionId:s,props:this.Cr(this._instance)};this.Mr.register({[da]:a})}},this._instance=e,this.Tr=n,this.Mr=i,this.Cr=r||wm,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[da]}getSetOnceProps(){var e,n=(e=this.Sr())==null?void 0:e.props;return n?"r"in n?Cf(n,this._instance.config.disable_capture_url_hashes):{$referring_domain:n.referringDomain,$pathname:n.initialPathName,utm_source:n.utm_source,utm_campaign:n.utm_campaign,utm_medium:n.utm_medium,utm_content:n.utm_content,utm_term:n.utm_term}:{}}getSessionProps(){var e={};return ie(cl(this.getSetOnceProps()),((n,i)=>{i==="$current_url"&&(i="url"),e["$session_entry_"+Ko(i)]=n})),e}}class gl{on(e,n){return this.Er[e]||(this.Er[e]=[]),this.Er[e].push(n),()=>{this.Er[e]=this.Er[e].filter((i=>i!==n))}}emit(e,n){for(var i of this.Er[e]||[])i(n);for(var r of this.Er["*"]||[])r(e,n)}constructor(){this.Er={}}}var Si=pe("[SessionId]");class eu{on(e,n){return this.Ir.on(e,n)}constructor(e,n,i){var r;if(this.Pr=null,this.Rr=[],this.Ar=void 0,this.Fr=!1,this.Ir=new gl,this.Lr=(u,c)=>!(!Dt(u)||!Dt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===Wt)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Ne=e.config,this.Mr=e.persistence,this.Or=void 0,this.Dr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.$r=n||Ht,this.Nr=i||Ht;var s=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*At(this.Ne.session_idle_timeout_seconds||1800,60,36e3,Si.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.qr(),this.jr="ph_"+s+"_window_id",this.Br="ph_"+s+"_primary_window_exists",this.Hr()){var o=be.H(this.jr),a=be.H(this.Br);o&&!a?this.Or=o:be.q(this.jr),be.F(this.Br,!0)}if((r=this.Ne.bootstrap)!=null&&r.sessionID)try{var l=(u=>{var c=this.Ne.bootstrap.sessionID.replace(/-/g,"");if(c.length!==32)throw new Error("Not a valid UUID");if(c[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(c.substring(0,12),16)})();this.Ur(this.Ne.bootstrap.sessionID,new Date().getTime(),l)}catch(u){Si.error("Invalid sessionID in bootstrap",u)}this.zr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return C(this.Rr)&&(this.Rr=[]),this.Rr.push(e),this.Dr&&e(this.Dr,this.Or),()=>{this.Rr=this.Rr.filter((n=>n!==e))}}Hr(){return this.Ne.persistence!=="memory"&&!this.Mr.xi&&be.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&be.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?be.H(this.jr):null}Zr(e){var n=this.Pr;return!Ye(n)&&!Ye(e)&&5e3>Math.abs(e-n)}Ur(e,n,i){var r=n!==this._sessionActivityTimestamp,s=!(e!==this.Dr||i!==this._sessionStartTimestamp);this._sessionStartTimestamp=i,this._sessionActivityTimestamp=n,this.Dr=e,s&&!r||s&&this.Zr(n)||(this.Pr=n,this.Mr.register({[Kn]:[n,e,i]}))}Gr(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return Dt(n)&&n>0}Qr(){this.Gr()?this.Mr.refreshKey(Kn):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!Ye(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this.Pr){this.Qr();var n=this.Jr();n[1]===this.Dr&&n[2]===this._sessionStartTimestamp&&(this.Pr=this._sessionActivityTimestamp,this.Mr.register({[Kn]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],n=Dt(e)?e:0,i=Dt(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(n,i)}Xr(e){return this.Qr(),this.Lr(e,this.Yr())}Jr(){var e=this.Mr.props[Kn];return U(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Pr=null,clearTimeout(this.tn),this.tn=void 0,this.Ur(null,null,null)}destroy(){this.Fr=!0,this.Kr(),clearTimeout(this.tn),this.tn=void 0,this.Ar&&w&&(w.removeEventListener(ns,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&be.q(this.Br)},ve(w,ns,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=null),this.Ne.cookieless_mode===Wt)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var i=n||new Date().getTime(),r=this.Jr(),s=r[1],o=r[2],a=this.Yr(),l=this.Vr(),u=Dt(o)&&Math.abs(i-o)>864e5,c=!1,d=!1,f=!s,h=s,p=!f&&!e&&this.Lr(i,a);if(p){(p=this.Xr(i))||Si.info("cross-tab refresh kept the session alive",{sessionId:s});var g=this.Jr();s=g[1],o=g[2]}f||p||u?(s=this.$r(),l=this.Nr(),Si.info("new session ID generated",{sessionId:s,windowId:l,changeReason:{noSessionId:f,activityTimeout:p,sessionPastMaximumLength:u}}),o=i,c=!0):(l||(l=this.Nr(),c=!0),(d=s!==h)&&(Si.info("adopted cross-tab session id",{sessionId:s,windowId:l}),c=!0));var m=Dt(a)&&e&&!u?a:i,v=Dt(o)?o:new Date().getTime();this.Wr(l),this.Ur(s,m,v),e||this.qr();var E={noSessionId:f,activityTimeout:p,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((S=>S(s,l,E))),{sessionId:s,windowId:l,sessionStartTimestamp:v,changeReason:c?E:void 0,lastActivityTimestamp:a}}qr(){this.Fr||(clearTimeout(this.tn),this.tn=setTimeout((()=>{if(!this.Fr)if(this.Xr(new Date().getTime())){var e=this.Dr;this.resetSessionId(),this.Ir.emit("forcedIdleReset",{idleSessionId:e})}else this.qr()}),1.1*this.sessionTimeoutMs))}}var Uf=function(t,e){if(!t)return!1;var n=t.userAgent;if(n&&yc(n,e))return!0;try{var i=t?.userAgentData;if(i!=null&&i.brands&&i.brands.some((r=>yc(r?.brand,e))))return!0}catch{}return!!t.webdriver};function Hf(){return(Hf=se((function*(){var t=He?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),n=e?.model;return X(n)&&n.length>0?n:void 0}catch(i){return void A.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",i)}}))).apply(this,arguments)}var cs=function(t,e){if(!(function(n){try{new RegExp(n)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function Ro(t,e,n){return Yn({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}var Wf={exact:(t,e)=>e.some((n=>t.some((i=>n===i)))),is_not:(t,e)=>e.every((n=>t.every((i=>n!==i)))),regex:(t,e)=>e.some((n=>t.some((i=>cs(n,i))))),not_regex:(t,e)=>e.every((n=>t.every((i=>!cs(n,i))))),icontains:(t,e)=>e.map(Er).some((n=>t.map(Er).some((i=>n.includes(i))))),not_icontains:(t,e)=>e.map(Er).every((n=>t.map(Er).every((i=>!n.includes(i))))),gt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>i>parseFloat(r)))})),lt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>it.toLowerCase();function zf(t,e){return!t||Object.entries(t).every((n=>{var i=n[1],r=e?.[n[0]];if(C(r)||Ye(r))return!1;var s=[String(r)],o=Wf[i.operator];return!!o&&o(i.values,s)}))}var Ia="custom",tu="i.posthog.com",bm=/^\/static\//;class Em{constructor(e){this.en={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,n=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return n||(n=this.apiHost.replace("."+tu,".posthog.com")),n==="https://app.posthog.com"?"https://us.posthog.com":n}get region(){return this.en[this.apiHost]||(this.en[this.apiHost]=/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"us":/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"eu":Ia),this.en[this.apiHost]}rn(e){if(bm.test(e)){var n=this.instance.config.asset_host;if(typeof n=="string")return n.trim().replace(/\/$/,"")||void 0}}endpointFor(e,n){if(n===void 0&&(n=""),n&&(n=n[0]==="/"?n:"/"+n),e==="ui")return this.uiHost+n;if(e==="flags")return this.flagsApiHost+n;if(e==="assets"){var i=this.rn(n);if(i)return""+i+n}if(this.region===Ia)return this.apiHost+n;var r=tu+n;switch(e){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}}function qf(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var Q=pe("[Surveys]"),Vf="seenSurvey_",Gf=t=>{try{var e=(n=>((i,r)=>""+Vf+(function(s){return s.current_iteration&&s.current_iteration>0?s.id+"_"+s.current_iteration:s.id})(r))(0,n))(t);if(localStorage.getItem(e))return;localStorage.setItem(e,"true")}catch(n){Q.error("Failed to persist survey seen state",n)}},Sm=[ko.Popover,ko.Widget,ko.API],xm={ignoreConditions:!1,ignoreDelay:!1,displayType:ya.Popover},Im=pe("[PostHog ExternalIntegrations]"),km={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class Cm{constructor(e){this._instance=e}ai(e,n){var i;(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,e,(r=>{if(r)return Im.error("failed to load script",r);n()}))}startIfEnabledOrStop(){var e=this,n=function(){var s,o,a,l=i[0],u=i[1];!u||(s=B.__PosthogExtensions__)!=null&&(s=s.integrations)!=null&&s[l]||e.ai(km[l],(()=>{var c;(c=B.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=B.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=B.__PosthogExtensions__)==null||(a=a.integrations)==null||(a=a[l])==null||a.stop())};for(var i of Object.entries((r=this._instance.config.integrations)!==null&&r!==void 0?r:{})){var r;n()}}}class Am{constructor(e,n){this.rt=e,this.nn=n,this.sn=new Map,this.an=!1}add(e){var n=this;return se((function*(){if(n.an)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(n.sn.has(e.name))throw new Error('Browser extension "'+e.name+'" is already registered');n.sn.set(e.name,e);try{var i=e.setup(n.nn);i&&(yield i)}catch(s){var r=n.sn.get(e.name)===e;r&&n.sn.delete(e.name),n.rt.error('Failed to set up browser extension "'+e.name+'"',s),r&&n.ln(e)}}))()}dispose(){if(!this.an){this.an=!0;var e=Array.from(this.sn.values()).reverse();for(var n of(this.sn.clear(),e))this.ln(n)}}ln(e){try{var n=e.dispose==null?void 0:e.dispose();n&&je(n.then)&&n.then(void 0,(i=>{this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}))}catch(i){this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}}}class Pm{constructor(e){this._instance=e}initialize(){}get(e){var n=this._instance.persistence;if(typeof e=="string")return n?.get_property(e);var i={};for(var r of e){var s=n?.get_property(r);C(s)||(i[r]=s)}return i}set(e,n){var i;(i=this._instance.persistence)==null||i.register(typeof e=="string"?{[e]:n}:e)}remove(e){var n;(n=this._instance.persistence)==null||n.unregister(e)}}var nu="extensionsRemoteConfig";class Fm{constructor(e){this.an=!1,this.instance=e,this.rt=A,this.un=e.hn,this.kv=new Pm(e),this.onEvent=n=>br(this.instance.on("eventCaptured",(i=>{try{n({event:i.event,properties:i.properties})}catch(r){this.rt.error("Browser extension event listener failed",r)}}))),this.onRemoteConfig=n=>{if(this.an)return br((()=>{}));var i=s=>{try{n(s)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},r=this.instance.dn.on(nu,i);return this.un&&i(this.un),br(r)},this.vn=new Am(A.createLogger("[BrowserExtensions]"),this)}get logger(){return this.rt}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return(e=this.instance.get_property(Yi))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(Yi);return typeof e=="string"?e:void 0}get library(){return{name:ne.LIB_NAME,version:ne.LIB_VERSION}}get initialPersonProperties(){var e,n;return(e=(n=this.instance.persistence)==null?void 0:n.get_initial_props())!==null&&e!==void 0?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,n,i,r,s=(e=this.instance.sessionManager)==null?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:(n=s?.sessionId)!==null&&n!==void 0?n:"",windowId:(i=s?.windowId)!==null&&i!==void 0?i:"",sessionStartTimestamp:(r=s?.sessionStartTimestamp)!==null&&r!==void 0?r:0}}catch{return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get projectToken(){return this.instance.config.token}add(e){return this.vn.add(e)}capture(e,n,i){var r=this;return se((function*(){i?r.instance.capture(e,n,{timestamp:i.timestamp,uuid:i.uuid,$set:i.set,$set_once:i.setOnce}):r.instance.capture(e,n)}))()}registerDynamicEventProperties(e){return br(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(nu,e))}sendRequest(e,n){var i=this;return se((function*(){var r;n===void 0&&(n={});var s=i.instance.requestRouter.endpointFor((r=n.target)!==null&&r!==void 0?r:"api",e),o={method:n.method,url:n.query?Cs(s,n.query):s,data:n.body,headers:n.headers,timeout:n.timeoutMs,fireCallbackOnDrop:!0,transport:n.transport,compression:n.compression,timestampMode:n.sentAt};return n.transport==="sendBeacon"?(i.instance._send_request(o),{statusCode:202}):new Promise((a=>{o.callback=a,i.instance._send_request(o)}))}))()}dispose(){this.an||(this.an=!0,this.vn.dispose())}}var Wi={},To=0,us=()=>{},iu='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',xi="Surveys module not available",ru="sanitize_properties is deprecated. Use before_send instead",Kf="Invalid value for property_denylist config: ",Rm=["token","distinct_id",ef],Gn="posthog",Yf=!hm&&Ge?.indexOf("MSIE")===-1&&Ge?.indexOf("Mozilla")===-1,$o=t=>{var e;return I({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:Tg(P?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:us,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:t??"unset",__preview_deferred_init_extensions:!1,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:me&&X(me?.search)&&me.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disableDeviceModel:!1,disable_external_dependency_loading:!1,strict_script_versioning:!1,enable_recording_console_log:void 0,secure_cookie:(w==null||(e=w.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(n){A.error("Bad HTTP status: "+n.statusCode+" "+n.text)},get_device_id:n=>n,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:ga,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:xa},error_tracking:{},_onCapture:us},(n=>({rageclick:n&&n>="2026-05-30"?{content_ignorelist:zg,ignore_text_selection:!0}:!n||"2025-11-30">n||{content_ignorelist:!0},capture_pageview:!n||"2025-05-24">n||"history_change",session_recording:n&&n>="2026-06-25"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6},streamNetworkBody:!0}:n&&n>="2026-05-30"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6}}:n&&n>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:n&&n>="2026-01-30"?"head":"body",internal_or_test_user_hostname:n&&n>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:n&&n>="2026-05-30"?250:0,split_storage:!(!n||"2026-05-30">n),detect_google_search_app:!(!n||"2026-05-30">n),disable_capture_url_hashes:!(!n||"2026-06-25">n)}))(t))},Tm=[["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"]],su=t=>{var e={};for(var n of Tm){var i=n[0],r=n[1];C(t[i])||(e[r]=t[i])}var s=fe({},e,t),o=t.__preview_external_dependency_versioned_paths;return C(o)||(C(t.strict_script_versioning)&&(s.strict_script_versioning=!!o),X(o)&&C(t.asset_host)&&(s.asset_host=o)),U(t.property_blacklist)&&(C(t.property_denylist)?s.property_denylist=t.property_blacklist:U(t.property_denylist)?s.property_denylist=[...t.property_blacklist,...t.property_denylist]:A.error(Kf+t.property_denylist)),s};class $m{constructor(){this.__forceAllowLocalhost=!1}get fn(){return this.__forceAllowLocalhost}set fn(e){A.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class Ze{pn(e,n){if(e){var i=this.sn.indexOf(e);i!==-1&&this.sn.splice(i,1)}return this.sn.push(n),n.initialize==null||n.initialize(),n}gn(){return this.config.cookieless_mode===Wt||this.config.cookieless_mode===kn&&this.consent.isRejected()}get decideEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){var e;this.webPerformance=new $m,this.mn=!1,this.version=ne.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new gl,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=$o(),this.SentryIntegration=Xg,this.sentryIntegration=i=>(function(r,s){var o=yf(r,s);return{name:_f,processEvent:a=>o(a)}})(this,i),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.wn=!1,this.kn=null,this.xn=null,this.Sn=null,this.scrollManager=new ym(this),this.pageViewManager=new zc(this),this.rateLimiter=new am(this),this.requestRouter=new Em(this),this.consent=new Dg(this),this.externalIntegrations=new Cm(this);var n=(e=Ze.__defaultExtensionClasses)!==null&&e!==void 0?e:{};this.featureFlags=n.featureFlags&&new n.featureFlags(this),this.toolbar=n.toolbar&&new n.toolbar(this),this.surveys=n.surveys&&new n.surveys(this),this.conversations=n.conversations&&new n.conversations(this),this.logs=n.logs&&new n.logs(this),this.metrics=n.metrics&&new n.metrics(this),this.experiments=n.experiments&&new n.experiments(this),this.exceptions=n.exceptions&&new n.exceptions(this),this.people={set:(i,r,s)=>{var o=X(i)?{[i]:r}:i;this.setPersonProperties(o),s?.({})},set_once:(i,r,s)=>{var o=X(i)?{[i]:r}:i;this.setPersonProperties(void 0,o),s?.({})}},this.on("eventCaptured",(i=>A.info('send "'+i?.event+'"',i)))}init(e,n,i){if(i&&i!==Gn){var r,s=(r=Wi[i])!==null&&r!==void 0?r:new Ze;return s._init(e,n,i),Wi[i]=s,Wi[Gn][i]=s,s}return this._init(e,n,i)}_init(e,n,i){var r,s;n===void 0&&(n={});var o,a=X(e)?e.trim():"";if(!a)return A.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return a!==((o=this.config)==null?void 0:o.token)?console.warn("[PostHog.js]","You have already initialized PostHog with a different project token! Re-initializing is a no-op, so events will keep going to the project this instance was initialized with. To capture into a second project, load PostHog once, then initialize a named instance after the SDK has loaded, e.g. posthog.init('"+a+"', { ... }, 'project2')"):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=$o(n.defaults),n.debug=this.Cn(n.debug),this.Mn=n,this.Tn=[],n.person_profiles?this.xn=n.person_profiles:n.process_person&&(this.xn=n.process_person);var l=$o(n.defaults),u=su(n),c=fe({},l,u,{name:i,token:a});he(l.rageclick)&&he(u.rageclick)&&(c.rageclick=fe({},l.rageclick,u.rageclick)),he(l.session_recording)&&he(u.session_recording)&&(c.session_recording=fe({},l.session_recording,u.session_recording)),this.set_config(c),this.config.on_xhr_error&&A.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=n.disable_compression?void 0:Ue.GZipJS;var d=this.En();if(this.persistence=new Io(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Io(I({},this.config,{persistence:"sessionStorage"}),d,!1),this.bn="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&be.N()){var f=be.H(this.bn);U(f)&&f.forEach((k=>{X(k)&&this.yn.add(k)}))}else be.q(this.bn);var h=I({},this.persistence.props),p=I({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new mm((k=>this.Pn(k)),this.config.request_queue_config),this.Rn=new _m(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new eu(this),this.sessionPropsManager=new Qc(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((k,T,x)=>{(x!=null&&x.activityTimeout||x!=null&&x.sessionPastMaximumLength||x!=null&&x.crossTabAdoption)&&this.An()}))),this.Fn(),this.config.__preview_deferred_init_extensions?(A.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Ln(g)}),0)):(A.info("Initializing extensions synchronously"),this.Ln(g)),ne.DEBUG=ne.DEBUG||this.config.debug,ne.DEBUG&&A.info("Starting in debug mode",{this:this,config:n,thisC:I({},this.config),p:h,s:p}),!this.config.identity_distinct_id||(r=n.bootstrap)!=null&&r.distinctID||(n.bootstrap=I({},n.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((s=n.bootstrap)==null?void 0:s.distinctID)!==void 0){var m=n.bootstrap.distinctID,v=this.get_distinct_id(),E=this.persistence.get_property(at);if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&E===Un)this.identify(m);else if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&E===vn)A.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{var S=this.config.get_device_id(Ht()),_=n.bootstrap.isIdentifiedID?S:m;this.persistence.set_property(at,n.bootstrap.isIdentifiedID?vn:Un),this.register({distinct_id:m,$device_id:_})}}if(g)this.register_once({distinct_id:mr,$device_id:null},"");else if(!this.get_distinct_id()){var b=this.config.get_device_id(Ht());this.register_once({distinct_id:b,$device_id:b},""),this.persistence.set_property(at,Un)}return ve(w,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),n.segment?(function(k,T){var x=k.config.segment;if(!x)return T();(function(F,$){var O=F.config.segment;if(!O)return $();var L=K=>{var V=()=>K.anonymousId()||Ht();F.config.get_device_id=V,K.id()&&(F.register({distinct_id:K.id(),$device_id:V()}),F.persistence.set_property(at,vn)),$()},N=O.user();"then"in N&&je(N.then)?N.then(L):L(N)})(k,(()=>{x.register((F=>{typeof Promise<"u"&&Promise.resolve||So.warn("This browser does not have Promise support, and can not use the segment integration");var $=(O,L)=>{if(!L)return O;O.event.userId||O.event.anonymousId===F.get_distinct_id()||(So.info("No userId set, resetting PostHog"),F.reset()),O.event.userId&&O.event.userId!==F.get_distinct_id()&&(So.info("UserId set, identifying with PostHog"),F.identify(O.event.userId));var N=F.calculateEventProperties(L,O.event.properties);return O.event.properties=Object.assign({},N,O.event.properties),O};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:O=>$(O,O.event.event),page:O=>$(O,Vn),identify:O=>$(O,wo),screen:O=>$(O,"$screen")}})(k)).then((()=>{T()}))}))})(this,(()=>this.On())):this.On(),je(this.config._onCapture)&&this.config._onCapture!==us&&(A.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(k=>this.config._onCapture(k.event,k)))),this.config.ip&&A.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this.config.disableDeviceModel||(function(){return Hf.apply(this,arguments)})().then((k=>{k&&this.register({[_o]:k})})).catch(us),this}Fn(){var e,n,i,r,s,o,a=(e=(n=this.config.__extensionClasses)==null?void 0:n.featureFlags)!==null&&e!==void 0?e:(i=Ze.__defaultExtensionClasses)==null?void 0:i.featureFlags;a&&(this.featureFlags&&this.featureFlags instanceof a||((r=this.Dn)==null||r.call(this),this.Dn=void 0,this.featureFlags=new a(this)),je(this.featureFlags.onReloading)&&je(this.featureFlags.setup)?this.Dn||(this.Dn=this.featureFlags.onReloading((()=>{this.dn.emit("featureFlagsReloading",!0)})),this.$n().add(this.featureFlags)):(s=(o=this.featureFlags).initialize)==null||s.call(o))}Ln(e){var n,i,r,s,o,a,l,u=performance.now(),c=I({},Ze.__defaultExtensionClasses,this.config.__extensionClasses),d=[];c.exceptions&&this.sn.push(this.exceptions=(n=this.exceptions)!==null&&n!==void 0?n:new c.exceptions(this)),c.historyAutocapture&&this.sn.push(this.historyAutocapture=new c.historyAutocapture(this)),c.tracingHeaders&&this.sn.push(this.tracingHeaders=new c.tracingHeaders(this)),c.siteApps&&this.sn.push(this.siteApps=new c.siteApps(this)),c.sessionRecording&&!e&&this.sn.push(this.sessionRecording=new c.sessionRecording(this)),this.config.disable_scroll_properties||d.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),c.autocapture&&this.sn.push(this.autocapture=new c.autocapture(this)),c.surveys&&this.sn.push(this.surveys=(i=this.surveys)!==null&&i!==void 0?i:new c.surveys(this)),c.logs&&this.sn.push(this.logs=(r=this.logs)!==null&&r!==void 0?r:new c.logs(this)),c.metrics&&this.sn.push(this.metrics=(s=this.metrics)!==null&&s!==void 0?s:new c.metrics(this)),c.conversations&&this.sn.push(this.conversations=(o=this.conversations)!==null&&o!==void 0?o:new c.conversations(this)),c.productTours&&this.sn.push(this.productTours=new c.productTours(this)),c.heatmaps&&this.sn.push(this.heatmaps=new c.heatmaps(this)),c.webVitalsAutocapture&&this.sn.push(this.webVitalsAutocapture=new c.webVitalsAutocapture(this)),c.exceptionObserver&&this.sn.push(this.exceptionObserver=new c.exceptionObserver(this)),c.deadClicksAutocapture&&this.sn.push(this.deadClicksAutocapture=new c.deadClicksAutocapture(this,Zg)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((f=>{f.initialize&&d.push((()=>{f.initialize==null||f.initialize()}))})),d.push((()=>{if(this.Nn){var f=this.Nn;this.Nn=void 0,this.sn.forEach((h=>h.onRemoteConfig==null?void 0:h.onRemoteConfig(f)))}})),this.qn(d,u)}qn(e,n){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,n)}),0);var i=e.shift();if(i)try{i()}catch(s){A.error("Error initializing extension:",s)}}var r=Math.round(performance.now()-n);this.register_for_session({[tf]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[nf]:r}),this.config.__preview_deferred_init_extensions&&A.info("PostHog extensions initialized ("+r+"ms)")}Zi(e){var n;if(!P||!P.body)return A.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.Zi(e)}),500);if(this.config.__preview_deferred_init_extensions&&(this.Nn=e),this.hn=e,this.compression=void 0,e.ok){var i,r=e.config;r.supportedCompression&&!this.config.disable_compression&&(this.compression=j(r.supportedCompression,Ue.GZipJS)?Ue.GZipJS:j(r.supportedCompression,Ue.Base64)?Ue.Base64:void 0),(i=r.analytics)!=null&&i.endpoint&&(this.analyticsDefaultEndpoint=r.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:ga}),(n=this.jn)==null||n.handleRemoteConfig(e),this.sn.forEach((s=>s.onRemoteConfig==null?void 0:s.onRemoteConfig(e)))}On(){try{this.config.loaded(this)}catch(i){A.critical("`loaded` function failed",i)}if(this.Bn(),this.config.internal_or_test_user_hostname&&me!=null&&me.hostname){var e=me.hostname,n=this.config.internal_or_test_user_hostname;(typeof n=="string"?e===n:n.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.gn())&&this.Hn()}),1),this.Un=new Pf(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()&&vr(this.__request_queue,(e=>this.Pn(e))),this.__request_queue=[],this.Bn()}_handle_unload(){var e,n,i,r,s;(e=this.surveys)==null||e.handlePageUnload==null||e.handlePageUnload(),(n=this.metrics)==null||n.flush("sendBeacon"),this.config.request_batching?(this.zn()&&this.capture(yo),(i=this.logs)==null||i.flushLogs("sendBeacon"),(r=this.In)==null||r.unload(),(s=this.Rn)==null||s.unload()):this.zn()&&this.capture(yo,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?Yf?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)?e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:429})):(e.transport=e.transport||this.config.api_transport,e.headers=I({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,(C(this.config.disable_beacon)?this.config.__preview_disable_beacon:this.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(n=>{var i,r,s,o=I({},n);o.timeout=o.timeout||6e4;var a,l,u,c,d,f=(i=o.transport)!==null&&i!==void 0?i:"fetch";f==="sendBeacon"&&C(o.compression)&&o.data&&(o.compression=Ue.Base64),o.method==="POST"&&o.data&&(o.timestampMode==="capture-body"?o.data={api_key:(l=(d=(c=U(a=o.data)?a:[a])[0])==null||(u=d.properties)==null?void 0:u.token)!==null&&l!==void 0?l:d?.token,batch:c,sent_at:new Date().toISOString()}:o.timestampMode==="body"&&(o.data=(function(m,v){return v===void 0&&(v=new Date().toISOString()),U(m)?m.map((E=>I({},E,{sent_at:v}))):I({},m,{sent_at:v})})(o.data))),o.url=Xc(o.url,o.method,o.compression,o.timestampMode);var h=Lr.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),p=(r=(s=(function(m,v){for(var E=0;m.length>E;E++)if(m[E].transport===f)return m[E]})(h))==null?void 0:s.method)!==null&&r!==void 0?r:h[0].method;if(!p)throw new Error("No available transport method");var g=m=>{try{p(m)}catch(v){Df(v)?A.warn(v):A.error(v),o.callback==null||o.callback({statusCode:0,error:v})}};f!=="sendBeacon"&&o.data&&o.compression===Ue.GZipJS&&Mp&&typeof Promise<"u"&&!Mr?pm(o).then((m=>{g(m)})).catch((m=>{if(_c(m))return Mr=!0,void g(I({},o,{compression:void 0,url:Xc(n.url,n.method,void 0,n.timestampMode)}));(v=>{if(!v||typeof v!="object")return!1;var E="name"in v?String(v.name):"";return _c(v)||E===pd})(m)&&(Mr=!0),g(o)})):p(o)})(I({},e,{callback:n=>{var i,r;this.rateLimiter.checkForLimiting(n),400>n.statusCode||(i=(r=this.config).on_request_error)==null||i.call(r,n),e.callback==null||e.callback(n)}}))):e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:0}))}Pn(e){this.Rn?this.Rn.retriableRequest(e):this._send_request(e)}_execute_array(e){To++;try{var n,i=[],r=[],s=[];vr(e,(a=>{if(a)if(U(n=a[0]))s.push(a);else if(je(a))try{a.call(this)}catch(l){A.error("Error executing queued PostHog call",a,l)}else U(a)&&n==="alias"?i.push(a):U(a)&&n.indexOf("capture")!==-1&&je(this[n])?s.push(a):r.push(a)}));var o=function(a,l){vr(a,(function(u){try{if(U(u[0])){var c=l;ie(u,(function(d){c=c[d[0]].apply(c,d.slice(1))}))}else l[u[0]].apply(l,u.slice(1))}catch(d){A.error("Error executing queued PostHog call",u,d)}}))};o(i,this),o(r,this),o(s,this)}finally{To--}}push(e){if(To>0&&U(e)&&X(e[0])){var n=Ze.prototype[e[0]];je(n)&&n.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,n,i){var r,s,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.In){if(this.is_capturing())if(!C(e)&&X(e)){var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var c=i!=null&&i.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(c==null||!c.isRateLimited){n!=null&&n.$current_url&&!X(n?.$current_url)&&(A.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),n==null||delete n.$current_url),e!=="$exception"||i!=null&&i.Wn||A.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,f=i?.timestamp||d,h=Sc(i?.uuid,Ht),p={uuid:h,event:e,properties:this.calculateEventProperties(e,n||{},f,h)};e===Vn&&this.config.__preview_capture_bot_pageviews&&u&&(p.event="$bot_pageview",p.properties.$browser_type="bot"),c&&(p.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&p.properties.$feature_flag_has_experiment===!1&&this.get_property(Zr)===!0;i?.$set&&!g&&(p.$set=i?.$set);var m=i?.$unset;m&&(p.$unset=m);var v,E,S,_=g?void 0:this.Vn(i?.$set_once,e!==Pc,e===wo);if(_&&(p.$set_once=_),i!=null&&i._noTruncate||(s=this.config.properties_string_max_length,o=p,a=L=>X(L)?L.slice(0,s):L,l=new Set,p=(function L(N,K){if(N!==Object(N))return a?a(N):N;if(!l.has(N)){var V;if(l.add(N),U(N))V=[],vr(N,(R=>{V.push(L(R))}));else{var M={};ie(N,((R,Z)=>{l.has(R)||(M[Z]=L(R))})),V=M}return V}})(o)),p.timestamp=f,C(i?.timestamp)||(p.properties.$event_time_override_provided=!0,p.properties.$event_time_override_system_time=d),g&&(p.properties=(function(L,N){N===void 0&&(N=[]);var K={},V=M=>{L[M]!==void 0&&(K[M]=L[M])};return Lp.forEach(V),N.forEach(V),K})(p.properties,Rm)),e===qt.DISMISSED||e===qt.SENT){var b=n?.[Co.SURVEY_ID],k=n?.[Co.SURVEY_ITERATION];Gf({id:b,current_iteration:k}),p.$set=I({},p.$set,{[(v={id:b,current_iteration:k},E=e===qt.SENT?"responded":"dismissed",S="$survey_"+E+"/"+v.id,v.current_iteration&&v.current_iteration>0&&(S="$survey_"+E+"/"+v.id+"/"+v.current_iteration),S)]:!0})}else e===qt.SHOWN&&(p.$set=I({},p.$set,{[Co.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===om.SHOWN){var T=n?.[Vc.TOUR_TYPE];T&&(p.$set=I({},p.$set,{[Vc.TOUR_LAST_SEEN_DATE+"/"+T]:new Date().toISOString()}))}var x=I({},p.properties.$set,p.$set);if(Kt(x)||this.setPersonPropertiesForFlags(x),!H(this.config.before_send)){var F=this.Pt(p);if(!F)return;(p=F).uuid=Sc(p.uuid,Ht)}this.dn.emit("eventCaptured",p);var $=(r=i?._url)!==null&&r!==void 0?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),O={method:"POST",url:$,data:p,compression:"best-available",timestampMode:i?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test($)?"body":"capture-body",batchKey:i?._batchKey,transport:i?.transport};return!this.config.request_batching||i&&(i==null||!i._batchKey)||i!=null&&i.send_instantly?this.Pn(O):this.In.enqueue(O),p}A.critical("This capture call is ignored due to client rate limiting.")}}else A.error("No event name provided to posthog.capture")}else A.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(n=>e(n.event,n)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new Fm(this)}cn(e){this._n.push(e);var n=!0;return()=>{if(n){n=!1;var i=this._n.indexOf(e);i!==-1&&this._n.splice(i,1)}}}calculateEventProperties(e,n,i,r,s){if(i=i||new Date,!this.persistence||!this.sessionPersistence)return n;var o=s?void 0:this.persistence.remove_event_timer(e),a=I({},n);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.gn()&&(a[ef]=!0),e==="$snapshot"){var l=I({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!X(a.distinct_id)&&!ke(a.distinct_id)||Yo(a.distinct_id))&&A.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=(function(b,k,T,x){var F,$,O,L;if(x===void 0&&(x=!1),!Ge)return{};var N,K=b?[...ri,...k||[]]:[],V=(function(Bn){for(var qe=0;bc.length>qe;qe++){var Dn=bc[qe],Mt=Dn[1],Lt=Dn[0].exec(Bn),ut=Lt&&(je(Mt)?Mt(Lt,Bn):Mt);if(ut)return ut}return["",""]})(Ge),M=V[0],R=V[1],Z=(N=typeof navigator<"u"?navigator:void 0)!=null&&N.brave?{brave:!0}:{},Ce={};C(T)||(Ce.detectGoogleSearchApp=T);var oe={},ye=(F=navigator)==null||(F=F.userAgentData)==null?void 0:F.platform,$e=($=navigator)==null?void 0:$.maxTouchPoints,ae=w==null||(O=w.screen)==null?void 0:O.width,Ie=w==null||(L=w.screen)==null?void 0:L.height,Se=w?.devicePixelRatio;C(ye)||(oe.userAgentDataPlatform=ye),C($e)||(oe.maxTouchPoints=$e),C(ae)||(oe.screenWidth=ae),C(Ie)||(oe.screenHeight=Ie),C(Se)||(oe.devicePixelRatio=Se);var De,wt,ge,Je,bt,mn,Re,Pe,$t=fe(cl({$os:M,$os_version:R,$browser:Dd(Ge,navigator.vendor,Z,Ce),$device:Ec(Ge),$device_type:(wt=Ge,ge=oe,Pe=Ec(wt),Pe===bd||Pe===wd||Pe==="Kobo"||Pe==="Kindle Fire"||Pe===Md?ei:Pe===Gi||Pe===Xn||Pe===Ki||Pe===Zo?"Console":Pe===Sd?"Wearable":Pe?rt:ge?.userAgentDataPlatform==="Android"&&((Je=ge?.maxTouchPoints)!==null&&Je!==void 0?Je:0)>0?600>Math.min((bt=ge?.screenWidth)!==null&&bt!==void 0?bt:0,(mn=ge?.screenHeight)!==null&&mn!==void 0?mn:0)/((Re=ge?.devicePixelRatio)!==null&&Re!==void 0?Re:1)?rt:ei:"Desktop"),$timezone:Af(),$timezone_offset:im()}),{$current_url:Zi(x?fn(me?.href):me?.href,K,Xi),$host:me?.host,$pathname:me?.pathname,$raw_user_agent:Ge.length>1e3?Ge.substring(0,997)+"...":Ge,$browser_version:eg(Ge,navigator.vendor,Z,Ce),$browser_language:qc(),$browser_language_prefix:(De=qc(),typeof De=="string"?De.split("-")[0]:void 0),$screen_height:w?.screen.height,$screen_width:w?.screen.width,$viewport_height:w?.innerHeight,$viewport_width:w?.innerWidth,$lib:ne.LIB_NAME,$lib_version:ne.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return ne.SDK_DIST_CHANNEL&&($t.$sdk_dist_channel=ne.SDK_DIST_CHANNEL),$t})(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties,this.config.detect_google_search_app,this.config.disable_capture_url_hashes);if(this.sessionManager){var d=this.sessionManager.checkAndGetSessionAndWindowId(s,i.getTime()),f=d.windowId;a.$session_id=d.sessionId,a.$window_id=f}this.sessionPropsManager&&fe(a,this.sessionPropsManager.getSessionProps());try{var h;this.sessionRecording&&fe(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(h=this.Rn)==null?void 0:h.length}catch(b){a.$sdk_debug_error_capturing_properties=String(b)}if(this.requestRouter.region===Ia&&(a.$lib_custom_api_host=this.config.api_host),u=e!==Vn||s?e!==yo||s?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(i):this.pageViewManager.doPageView(i,r),a=fe(a,u),e===Vn&&P&&(a.title=P.title),!C(o)){var p=i.getTime()-o;a.$duration=parseFloat((p/1e3).toFixed(3))}Ge&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();ie(["$referrer","$referring_domain"],(b=>{b in g&&delete m[b]}));var v={};if(this._n.length>0)for(var E of this._n.slice())try{fe(v,E())}catch(b){A.error("Failed to produce browser extension event properties",b)}(a=fe({},c,g,m,I({},v,a))).$is_identified=this._isIdentified(),U(this.config.property_denylist)?ie(this.config.property_denylist,(function(b){delete a[b]})):A.error(Kf+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var S=this.config.sanitize_properties;S&&(A.error(ru),a=S(a,e));var _=this.Zn();return a.$process_person_profile=_,_&&!s&&this.Gn("_calculate_event_properties"),a}Vn(e,n,i){var r;if(n===void 0&&(n=!0),i===void 0&&(i=!1),!this.persistence||!this.Zn()||this.mn&&!i)return e;var s=this.persistence.get_initial_props(),o=(r=this.sessionPropsManager)==null?void 0:r.getSetOnceProps(),a=fe({},s,o||{},e||{}),l=this.config.sanitize_properties;return l&&(A.error(ru),a=l(a,"$set_once")),n&&(this.mn=!0),Kt(a)?void 0:a}register(e,n){var i;(i=this.persistence)==null||i.register(e,n)}register_once(e,n,i){var r;(r=this.persistence)==null||r.register_once(e,n,i)}register_for_session(e){var n;(n=this.sessionPersistence)==null||n.register(e),Object.keys(e).forEach((i=>this.yn.add(i))),this.Qn()}unregister(e){var n;(n=this.persistence)==null||n.unregister(e)}unregister_for_session(e){var n;(n=this.sessionPersistence)==null||n.unregister(e),this.yn.delete(e),this.Qn()}Kn(e,n){this.register({[e]:n})}An(){this.yn.forEach((e=>{var n;(n=this.sessionPersistence)==null||n.unregister(e)})),this.yn.clear(),this.Qn()}Qn(){var e;if(this.bn)if(this.config.persistence==="memory"||(e=this.sessionPersistence)!=null&&e.xi||!be.N())be.q(this.bn);else{var n=[];this.yn.forEach((i=>n.push(i))),n.length>0?be.F(this.bn,n):be.q(this.bn)}}getFeatureFlag(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlag(e,n)}getFeatureFlagPayload(e){var n;return(n=this.featureFlags)==null?void 0:n.getFeatureFlagPayload(e)}getFeatureFlagResult(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlagResult(e,n)}getAllFeatureFlags(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.getAllFeatureFlags())!==null&&e!==void 0?e:[]}isFeatureEnabled(e,n){var i,r;return(i=(r=this.featureFlags)==null?void 0:r.isFeatureEnabled(e,n))!==null&&i!==void 0?i:n?.defaultValue}reloadFeatureFlags(){var e;(e=this.featureFlags)==null||e.reloadFeatureFlags()}updateFlags(e,n,i){var r;(r=this.featureFlags)==null||r.updateFlags(e,n,i)}updateEarlyAccessFeatureEnrollment(e,n,i){var r;(r=this.featureFlags)==null||r.updateEarlyAccessFeatureEnrollment(e,n,i)}getEarlyAccessFeatures(e,n,i){var r;return n===void 0&&(n=!1),(r=this.featureFlags)==null?void 0:r.getEarlyAccessFeatures(e,n,i)}on(e,n){return this.dn.on(e,n)}onFeatureFlags(e){return this.featureFlags?this.featureFlags.onFeatureFlags(e):(e([],{},{errorsLoading:!0}),()=>{})}onSurveysLoaded(e){return this.surveys?this.surveys.onSurveysLoaded(e):(e([],{isLoaded:!1,error:xi}),()=>{})}onSessionId(e){var n,i;return(n=(i=this.sessionManager)==null?void 0:i.onSessionId(e))!==null&&n!==void 0?n:()=>{}}getSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getSurveys(e,n):e([],{isLoaded:!1,error:xi})}getActiveMatchingSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,n):e([],{isLoaded:!1,error:xi})}renderSurvey(e,n){var i;(i=this.surveys)==null||i.renderSurvey(e,n)}displaySurvey(e,n){var i;n===void 0&&(n=xm),(i=this.surveys)==null||i.displaySurvey(e,n)}cancelPendingSurvey(e){var n;(n=this.surveys)==null||n.cancelPendingSurvey(e)}canRenderSurvey(e){var n,i;return(n=(i=this.surveys)==null?void 0:i.canRenderSurvey(e))!==null&&n!==void 0?n:{visible:!1,disabledReason:xi}}canRenderSurveyAsync(e,n){var i,r;return n===void 0&&(n=!1),(i=(r=this.surveys)==null?void 0:r.canRenderSurveyAsync(e,n))!==null&&i!==void 0?i:Promise.resolve({visible:!1,disabledReason:xi})}Jn(e){return!e||Yo(e)?(A.critical("Unique user id has not been set in posthog.identify"),!1):e===mr?(A.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.'),!1):!["distinct_id","distinctid"].includes(e.toLowerCase())&&!["undefined","null"].includes(e.toLowerCase())||(A.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.'),!1)}identify(e,n,i){if(!this.__loaded||!this.persistence)return A.uninitializedWarning("posthog.identify");if(ke(e)&&(e=e.toString(),A.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.Jn(e)&&this.Gn("posthog.identify")){var r=this.get_distinct_id();this.register({$user_id:e}),this.get_property(Yi)||this.register_once({$had_persisted_distinct_id:!0,$device_id:r},""),e!==r&&e!==this.get_property(Fi)&&(this.unregister(Fi),this.register({distinct_id:e}));var s,o=(this.persistence.get_property(at)||Un)===Un,a=e!==r,l=!a&&o;if(a&&o)this.persistence.set_property(at,vn),this.setPersonPropertiesForFlags({$set:n||{},$set_once:i||{}},!1),this.capture(wo,{distinct_id:e,$anon_distinct_id:r},{$set:n||{},$set_once:i||{}}),this.Sn=Ro(e,n,i),(s=this.featureFlags)==null||s.setAnonymousDistinctId(r);else if(l){this.persistence.set_property(at,vn);var u=n||{},c=i||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=Ro(e,n,i)}else(n||i)&&this.setPersonProperties(n,i);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Cn)):l&&(n||i)&&this.reloadFeatureFlags()}}setPersonProperties(e,n){if((e||n)&&this.Gn("posthog.setPersonProperties")){var i=Ro(this.get_distinct_id(),e,n);this.Sn!==i?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:n||{}},!0),this.capture("$set",{$set:e||{},$set_once:n||{}}),this.Sn=i):A.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}unsetPersonProperties(e){var n,i=(U(e)?e:[e]).filter((r=>X(r)&&r.length>0));i.length!==0&&this.Gn("posthog.unsetPersonProperties")&&((n=this.featureFlags)==null||n.unsetPersonPropertiesForFlags(i,!0),this.capture("$set",{$unset:i}),this.Sn=null)}group(e,n,i){if(e&&n){var r=this.getGroups(),s=r[e]!==n;if(s&&this.resetGroupPropertiesForFlags(e),this.register({$groups:I({},r,{[e]:n})}),s||i){var o={$group_type:e,$group_key:n};i&&(o.$group_set=i),this.capture(Pc,o)}i&&this.setGroupPropertiesForFlags({[e]:i}),s&&!i&&this.reloadFeatureFlags()}else A.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),(i=this.featureFlags)==null||i.setPersonPropertiesForFlags(e,n)}resetPersonPropertiesForFlags(e){var n;e===void 0&&(e=!0),(n=this.featureFlags)==null||n.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((i=this.featureFlags)==null||i.setGroupPropertiesForFlags(e,n))}resetGroupPropertiesForFlags(e){var n;(n=this.featureFlags)==null||n.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,n){var i,r,s,o,a,l,u,c,d,f;if(n===void 0&&(n=!1),A.info("reset"),!this.__loaded)return A.uninitializedWarning("posthog.reset");var h,p=this.get_property(Yi),g=this.get_property(_o),m=this.get_property(An),v=this.is_capturing();if(this.consent.reset(),n||!v||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after."),(i=this.persistence)==null||i.clear(),(r=this.sessionPersistence)==null||r.clear(),this.yn.clear(),this.Qn(),C(m)||(h=this.persistence)==null||h.register({[An]:m}),(s=this.surveys)==null||s.reset(),(o=this.Un)==null||o.stop(),(a=this.featureFlags)==null||a.reset(),(l=this.conversations)==null||l.reset(),(u=this.logs)==null||u.reset(),(c=this.metrics)==null||c.reset(),(d=this.persistence)==null||d.set_property(at,Un),(f=this.sessionManager)==null||f.resetSessionId(),this.Sn=null,this.config.cookieless_mode===Wt)this.register_once({distinct_id:mr,$device_id:null},"");else{var E=this.config.get_device_id(Ht());this.register_once({distinct_id:E,$device_id:e?E:p},""),e||C(g)||this.register({[_o]:g})}this.register({$last_posthog_reset:new Date().toISOString()},1),delete this.config.identity_distinct_id,delete this.config.identity_hash,this.reloadFeatureFlags()}shutdown(e){var n=this;return se((function*(){var i,r,s,o,a,l,u;if(n.__loaded){(i=n.Un)==null||i.stop(),(r=n.jn)==null||r.dispose(),(s=n.sessionRecording)==null||s.dispose(),(o=n.logs)==null||o.flushLogs("sendBeacon"),(a=n.metrics)==null||a.flush("sendBeacon"),(l=n.In)==null||l.unload(),(u=n.Rn)==null||u.unload();try{var c;(c=n.featureFlags)==null||c.destroy()}catch(d){A.error("Error while destroying feature flags",d)}}else A.uninitializedWarning("posthog.shutdown")}))()}setIdentity(e,n){var i;this.config.identity_distinct_id=e,this.config.identity_hash=n,this.alias(e),(i=this.conversations)==null||i.Xn()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,(e=this.conversations)==null||e.ts()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,n;return(e=(n=this.sessionManager)==null?void 0:n.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var n=this.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.sessionStartTimestamp,r=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+n.sessionId);if(e!=null&&e.withTimestamp&&i){var s,o=(s=e.timestampLookBack)!==null&&s!==void 0?s:10;if(!i)return r;r+="?t="+Math.max(Math.floor((new Date().getTime()-i)/1e3)-o,0)}return r}alias(e,n){return e===this.get_property(Kd)?(A.critical("Attempting to create alias for existing People user - aborting."),-2):this.Gn("posthog.alias")?(C(n)&&(n=this.get_distinct_id()),e!==n?(this.Kn(Fi,e),this.capture("$create_alias",{alias:e,distinct_id:n})):(A.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var n=I({},this.config);if(he(e)){var i,r,s,o,a,l,u,c,d,f,h,p;fe(this.config,su(e));var g=this.En();(i=this.persistence)==null||i.update_config(this.config,n,g),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Io(I({},this.config,{persistence:"sessionStorage"}),g,!1);var m=this.Cn(this.config.debug);mt(m)&&(this.config.debug=m),mt(this.config.debug)&&(this.config.debug?(ne.DEBUG=!0,le.N()&&le.F("ph_debug",!0),A.info("set_config",{config:e,oldConfig:n,newConfig:I({},this.config)})):(ne.DEBUG=!1,le.N()&&le.q("ph_debug"))),(r=this.featureFlags)==null||r.updateConfig==null||r.updateConfig(this.config,this.Qi()),(s=this.exceptionObserver)==null||s.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(f=this.deadClicksAutocapture)==null||f.startIfEnabledOrStop(),(h=this.surveys)==null||h.loadIfEnabled(),this.es(),(p=this.externalIntegrations)==null||p.startIfEnabledOrStop()}}_overrideSDKInfo(e,n){ne.LIB_NAME=e,ne.LIB_VERSION=n}startSessionRecording(e){var n,i,r,s,o,a=e===!0,l={sampling:a||!(e==null||!e.sampling),linked_flag:a||!(e==null||!e.linked_flag),url_trigger:a||!(e==null||!e.url_trigger),event_trigger:a||!(e==null||!e.event_trigger)};Object.values(l).some(Boolean)&&((n=this.sessionManager)==null||n.checkAndGetSessionAndWindowId(),l.sampling&&((i=this.sessionRecording)==null||i.overrideSampling()),l.linked_flag&&((r=this.sessionRecording)==null||r.overrideLinkedFlag()),l.url_trigger&&((s=this.sessionRecording)==null||s.overrideTrigger("url")),l.event_trigger&&((o=this.sessionRecording)==null||o.overrideTrigger("event"))),this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,n){if(this.exceptions){var i=new Error("PostHog syntheticException"),r=this.exceptions.buildProperties(e,{handled:!0,syntheticException:i});return this.exceptions.sendExceptionEvent(I({},r,n))}}addExceptionStep(e,n){var i;(i=this.exceptions)==null||i.addExceptionStep(e,n)}captureLog(e){var n;(n=this.logs)==null||n.captureLog(e)}get logger(){var e,n;return(e=(n=this.logs)==null?void 0:n.logger)!==null&&e!==void 0?e:Ze.rs}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var n,i;return(n=(i=this.toolbar)==null?void 0:i.loadToolbar(e))!==null&&n!==void 0&&n}get_property(e){var n;return(n=this.persistence)==null?void 0:n.props[e]}getSessionProperty(e){var n;return(n=this.sessionPersistence)==null?void 0:n.props[e]}toString(){var e,n=(e=this.config.name)!==null&&e!==void 0?e:Gn;return n!==Gn&&(n=Gn+"."+n),n}_isIdentified(){var e,n;return((e=this.persistence)==null?void 0:e.get_property(at))===vn||((n=this.sessionPersistence)==null?void 0:n.get_property(at))===vn}Zn(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles===ga&&!this._isIdentified()&&Kt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[Fi])&&((n=this.persistence)==null||(n=n.props)==null||!n[es]))}zn(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Zn()||this.Gn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.Gn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}Gn(e){return this.config.person_profiles==="never"?(A.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Kn(es,!0),!0)}En(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut();return this.config.disable_persistence||e&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!==kn)}es(){var e,n,i,r,s=this.En();return((e=this.persistence)==null?void 0:e.xi)!==s&&((i=this.persistence)==null||i.set_disabled(s)),((n=this.sessionPersistence)==null?void 0:n.xi)!==s&&((r=this.sessionPersistence)==null||r.set_disabled(s)),s&&(this.yn.clear(),this.Qn()),s}opt_in_capturing(e){var n;if(this.config.cookieless_mode!==Wt){if(this.gn()){var i,r,s,o,a;this.Yn(!0,!0),(i=this.sessionManager)==null||i.destroy(),(r=this.pageViewManager)==null||r.destroy(),this.sessionManager=new eu(this),this.pageViewManager=new zc(this),this.persistence&&(this.sessionPropsManager=new Qc(this,this.sessionManager,this.persistence));var l,u=(s=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&s!==void 0?s:(a=Ze.__defaultExtensionClasses)==null?void 0:a.sessionRecording;u&&(this.sessionRecording=this.pn(this.sessionRecording,new u(this)),this.hn&&((l=this.sessionRecording)==null||l.onRemoteConfig==null||l.onRemoteConfig(this.hn)))}var c,d;this.consent.optInOut(!0),this.es(),this.Bn(),(n=this.sessionRecording)==null||n.startIfEnabledOrStop(),this.config.cookieless_mode==kn&&((c=this.surveys)==null||c.loadIfEnabled()),(C(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((d=e?.captureEventName)!==null&&d!==void 0?d:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hn()}else A.warn(iu)}opt_out_capturing(){var e,n,i;this.config.cookieless_mode!==Wt?(this.config.cookieless_mode===kn&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===kn&&(this.register({distinct_id:mr,$device_id:null}),(e=this.sessionRecording)==null||e.stopRecording(),this.sessionRecording=void 0,(n=this.sessionManager)==null||n.destroy(),(i=this.pageViewManager)==null||i.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.Hn(),this.Bn())):A.warn(iu)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===Wt||(this.config.cookieless_mode===kn?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return He?Uf(He,this.config.custom_blocked_useragents):void 0}Hn(){P&&(P.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(Vn,{title:P.title},{send_instantly:!0}),this.kn&&(P.removeEventListener(ts,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),ve(P,ts,this.kn)))}debug(e){e===!1?(w?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(w?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}Qi(){var e=this.Mn||{};return"advanced_disable_flags"in e?!!e.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(A.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(function(n,i,r,s,o){var a=i in n&&!H(n[i]),l=r in n&&!H(n[r]);return a?n[i]:!!l&&(o&&o.warn("Config field '"+r+"' is deprecated. Please use '"+i+"' instead. The old field will be removed in a future major version."),n[r])})(e,"advanced_disable_flags","advanced_disable_decide",0,A)}Pt(e){var n;if(H(this.config.before_send))return e;var i=Object.keys((n=e.properties)!==null&&n!==void 0?n:{}).filter(Hp),r=U(this.config.before_send)?this.config.before_send:[this.config.before_send],s=e;for(var o of r){if(s=o(s),H(s)){var a="Event '"+e.event+"' was rejected in beforeSend function";return Up(e.event)?A.warn(a+". This can cause unexpected behavior."):A.info(a),null}s.properties&&!Kt(s.properties)||A.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}for(var l of i)if(s.properties&&H(s.properties[l]))return A.warn("Event '"+e.event+"' had its '"+l+"' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped."),null;return s}getPageViewId(){var e;return(e=this.pageViewManager.ui)==null?void 0:e.pageViewId}captureTraceFeedback(e,n){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:n})}captureTraceMetric(e,n,i){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:n,$ai_metric_value:String(i)})}Cn(e){var n=mt(e)&&!e,i=le.N()&&le.P("ph_debug")==="true";return!n&&(!!i||e)}}Ze.__defaultExtensionClasses={},Ze.rs=(()=>{var t=()=>{};return{trace:t,debug:t,info:t,warn:t,error:t,fatal:t}})(),(function(t,e){for(var n=0;e.length>n;n++)t.prototype[e[n]]=Fg(t.prototype[e[n]])})(Ze,["identify"]);class ou{constructor(e){this.disabled=e===!1;var n=he(e)?e:{};this.thresholdPx=n.threshold_px||30,this.timeoutMs=n.timeout_ms||1e3,this.clickCount=n.click_count||3,this.clicks=[]}isRageClick(e,n,i){if(this.disabled)return!1;var r=this.clicks[this.clicks.length-1];if(r&&Math.abs(e-r.x)+Math.abs(n-r.y)i-r.timestamp){if(this.clicks.push({x:e,y:n,timestamp:i}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:n,timestamp:i}];return!1}}var Mo="$copy_autocapture",Lo=pe("[AutoCapture]");function No(t,e){return e.length>t?e.slice(0,t)+"...":e}function Mm(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!hn(e));return e}function Lm(t,e){var n,i,r=e.e,s=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!hn(t))return{props:{}};for(var c=[t],d=new Set([t]),f=t;f.parentNode&&!et(f,"body")&&df>c.length;)if(uf(f.parentNode)){var h=f.parentNode.host;if(d.has(h))break;d.add(h),c.push(h),f=h}else{if(!hn(f.parentNode)||d.has(f.parentNode))break;d.add(f.parentNode),c.push(f.parentNode),f=f.parentNode}var p,g,m=[],v={},E=!1,S=!1;if(ie(c,(x=>{var F=_a(x);if(et(x,"a")){var $=x.getAttribute("href");E=!!(F&&$&&Ui($))&&(u?fn($):$)}j(rs(x),"ph-no-capture")&&(S=!0),m.push((function(L,N,K,V,M){M===void 0&&(M=!1);var R=L.tagName.toLowerCase(),Z={tag_name:R};dl.indexOf(R)>-1&&!K&&(Z.$el_text=R.toLowerCase()==="a"||R.toLowerCase()==="button"?No(1024,Uc(L)):No(1024,Ji(L)));var Ce=rs(L);Ce.length>0&&(Z.classes=Ce.filter((function(ae){return ae!==""}))),ie(L.attributes,(function(ae){var Ie;if((!mf(L)||["name","id","class","aria-label"].indexOf(ae.name)!==-1)&&(V==null||!V.includes(ae.name))&&!N&&Ui(ae.value)&&(!X(Ie=ae.name)||Ie.substring(0,10)!=="_ngcontent"&&Ie.substring(0,7)!=="_nghost")){var Se=ae.value;ae.name==="class"&&(Se=ul(Se).join(" ")),Z["attr__"+ae.name]=No(1024,ae.name==="href"&&M?fn(Se):Se)}}));for(var oe=1,ye=1,$e=L;$e=Mm($e);)oe++,$e.tagName===L.tagName&&ye++;return Z.nth_child=oe,Z.nth_of_type=ye,Z})(x,s,o,a,u));var O=(function(L){if(!_a(L))return{};var N={};return ie(L.attributes,(function(K){if(K.name&&K.name.indexOf("data-ph-capture-attribute")===0){var V=K.name.replace("data-ph-capture-attribute-",""),M=K.value;V&&M&&Ui(M)&&(N[V]=M)}})),N})(x);fe(v,O)})),S)return{props:{},explicitNoCapture:S};if(o||(m[0].$el_text=et(t,"a")||et(t,"button")?Uc(t):Ji(t)),E){var _,b;m[0].attr__href=E;var k=(_=ss(E))==null?void 0:_.host,T=w==null||(b=w.location)==null?void 0:b.host;k&&T&&k!==T&&(p=E)}return{props:fe({$event_type:r.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(x){return x.map((F=>{var $,O,L="";if(F.tag_name&&(L+=F.tag_name),F.attr_class)for(var N of(F.attr_class.sort(),F.attr_class))L+="."+N.replace(/"/g,"");var K=I({},F.text?{text:F.text}:{},{"nth-child":($=F.nth_child)!==null&&$!==void 0?$:0,"nth-of-type":(O=F.nth_of_type)!==null&&O!==void 0?O:0},F.href?{href:F.href}:{},F.attr_id?{attr_id:F.attr_id}:{},F.attributes),V={};return $r(K).sort(((M,R)=>M[0].localeCompare(R[0]))).forEach((M=>{var R=M[1];return V[Hc(M[0].toString())]=Hc(R.toString())})),(L+=":")+$r(V).map((M=>M[0]+'="'+M[1]+'"')).join("")})).join(";")})((function(x){return x.map((F=>{var $,O,L={text:($=F.$el_text)==null?void 0:$.slice(0,400),tag_name:F.tag_name,href:(O=F.attr__href)==null?void 0:O.slice(0,2048),attr_class:Yg(F),attr_id:F.attr__id,nth_child:F.nth_child,nth_of_type:F.nth_of_type,attributes:{}};return $r(F).filter((N=>N[0].indexOf("attr__")===0)).forEach((N=>L.attributes[N[0]]=N[1])),L}))})(g)))},(n=m[0])!=null&&n.$el_text?{$el_text:(i=m[0])==null?void 0:i.$el_text}:{},p&&r.type==="click"?{$external_click_url:p}:{},v)}}var Ii=pe("[ExceptionAutocapture]"),au=()=>{},Nm=pe("[TracingHeaders]"),wn=pe("[Web Vitals]"),lu=9e5,cu="disabled",uu="lazy_loading",ki="awaiting_config",Sr="missing_config";pe("[SessionRecording]"),pe("[SessionRecording]");var ka="[SessionRecording]",Bt=pe(ka),Om=pe("[Heatmaps]");function Oo(t){return he(t)&&"clientX"in t&&"clientY"in t&&ke(t.clientX)&&ke(t.clientY)}var xr=pe("[Product Tours]"),Bo=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(ol))},Bm=["$set_once","$set"],Et=pe("[SiteApps]"),du="Error while initializing PostHog app with config id ";function zn(t,e,n){if(H(t))return!1;switch(n){case"exact":return t===e;case"contains":var i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(i,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}class Dm{constructor(e){this.ns=new gl,this.ss=(n,i)=>this.os(n,i)&&this.ls(n,i)&&this.us(n,i)&&this.hs(n,i),this.os=(n,i)=>i==null||!i.event||n?.event===i?.event,this._instance=e,this.ds=new Set,this.vs=new Set}init(){var e,n;C((e=this._instance)==null?void 0:e._addCaptureHook)||(n=this._instance)==null||n._addCaptureHook(((i,r)=>{this.on(i,r)}))}register(e){var n,i;if(!C((n=this._instance)==null?void 0:n._addCaptureHook)&&(e.forEach((o=>{var a,l;(a=this.vs)==null||a.add(o),(l=o.steps)==null||l.forEach((u=>{var c;(c=this.ds)==null||c.add(u?.event||"")}))})),(i=this._instance)!=null&&i.autocapture)){var r,s=new Set;e.forEach((o=>{var a;(a=o.steps)==null||a.forEach((l=>{l!=null&&l.selector&&s.add(l?.selector)}))})),(r=this._instance)==null||r.autocapture.setElementSelectors(s)}}on(e,n){var i;n!=null&&e.length!=0&&(this.ds.has(e)||this.ds.has(n.event))&&this.vs&&((i=this.vs)==null?void 0:i.size)>0&&this.vs.forEach((r=>{this.cs(n,r)&&this.ns.emit("actionCaptured",r.name)}))}fs(e){this.onAction("actionCaptured",(n=>e(n)))}cs(e,n){if(n?.steps==null)return!1;for(var i of n.steps)if(this.ss(e,i))return!0;return!1}onAction(e,n){return this.ns.on(e,n)}ls(e,n){if(n!=null&&n.url){var i,r=e==null||(i=e.properties)==null?void 0:i.$current_url;if(!r||typeof r!="string"||!zn(r,n.url,n.url_matching||"contains"))return!1}return!0}us(e,n){return!!this.ps(e,n)&&!!this.gs(e,n)&&!!this.ys(e,n)}ps(e,n){var i;if(n==null||!n.href)return!0;var r=this.bs(e);if(r.length>0)return r.some((a=>zn(a.href,n.href,n.href_matching||"exact")));var s,o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!o&&zn((s=o.match(/(?::|")href="(.*?)"/))?s[1]:"",n.href,n.href_matching||"exact")}gs(e,n){var i;if(n==null||!n.text)return!0;var r=this.bs(e);if(r.length>0)return r.some((u=>zn(u.text,n.text,n.text_matching||"exact")||zn(u.$el_text,n.text,n.text_matching||"exact")));var s,o,a,l=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!l&&(s=(function(u){for(var c,d=[],f=/(?::|")text="(.*?)"/g;!H(c=f.exec(u));)d.includes(c[1])||d.push(c[1]);return d})(l),o=n.text,a=n.text_matching||"exact",s.some((u=>zn(u,o,a))))}ys(e,n){var i,r;if(n==null||!n.selector)return!0;var s=e==null||(i=e.properties)==null?void 0:i.$element_selectors;if(s!=null&&s.includes(n.selector))return!0;var o=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";if(n.selector_regex&&o)try{return new RegExp(n.selector_regex).test(o)}catch{return!1}return!1}bs(e){var n;return(e==null||(n=e.properties)==null?void 0:n.$elements)==null?[]:e?.properties.$elements}hs(e,n){return n==null||!n.properties||n.properties.length===0||zf(n.properties.reduce(((i,r)=>{var s=U(r.value)?r.value.map(String):r.value!=null?[String(r.value)]:[];return i[r.key]={values:s,operator:r.operator||"exact"},i}),{}),e?.properties)}}class jm{constructor(e){var n;this._s=[],this._instance=e,this.ws=new Map,this.ks=new Map,this.xs=new Map,(n=this._instance)==null||n.onSessionId==null||n.onSessionId((i=>this.Ss(i)))}Cs(e){return!1}Ms(){return null}Ts(e){}Es(){}Is(e,n){return!!e&&zf(e.propertyFilters,n?.properties)}Ps(e,n){var i=new Map;return e.forEach((r=>{var s;(s=r.conditions)==null||(s=s[n])==null||(s=s.values)==null||s.forEach((o=>{if(o!=null&&o.name){var a=i.get(o.name)||[];a.push(r.id),i.set(o.name,a)}}))})),i}Rs(e,n,i){var r=(i===wi.Activation?this.ws:this.ks).get(e),s=[];return this.As((o=>{s=o.filter((a=>r?.includes(a.id)))})),s.filter((o=>{var a,l=(a=o.conditions)==null||(a=a[i])==null||(a=a.values)==null?void 0:a.find((u=>u.name===e));return this.Is(l,n)}))}register(e){var n;C((n=this._instance)==null?void 0:n._addCaptureHook)||(this.Fs(e),this.Ls(e))}Ls(e){var n=e.filter((i=>{var r,s;return((r=i.conditions)==null?void 0:r.actions)&&((s=i.conditions)==null||(s=s.actions)==null||(s=s.values)==null?void 0:s.length)>0}));n.length!==0&&(this.Os==null&&(this.Os=new Dm(this._instance),this.Os.init(),this.Os.fs((i=>{this.onAction(i)}))),n.forEach((i=>{var r,s,o,a,l;i.conditions&&(r=i.conditions)!=null&&r.actions&&(s=i.conditions)!=null&&(s=s.actions)!=null&&s.values&&((o=i.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.Os)==null||a.register(i.conditions.actions.values),(l=i.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var c=this.xs.get(u.name);c&&c.push(i.id),this.xs.set(u.name,c||[i.id])}})))})))}Fs(e){var n,i=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.events)&&((a=s.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0})),r=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.cancelEvents)&&((a=s.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0}));i.length===0&&r.length===0||((n=this._instance)==null||n._addCaptureHook(((s,o)=>{this.onEvent(s,o)})),this.ws=this.Ps(e,wi.Activation),this.ks=this.Ps(e,wi.Cancellation))}onEvent(e,n){var i,r,s=this.Ds(),o=(n==null||(i=n.properties)==null?void 0:i.$survey_id)||(n==null||(r=n.properties)==null?void 0:r.$product_tour_id);if(o&&this.getActivatedIds().includes(o)){var a=this.$s(e,o);if(a==="consume")return s.info("event consumed activated item, removing it",{event:e,itemId:o}),void this.Ns([o]);if(a==="persist")return s.info("shown item promoted to persisted activation",{event:e,itemId:o}),this.qs(o),void this.js([o])}if(this.ks.has(e)){var l=this.Rs(e,n,wi.Cancellation);l.length>0&&(s.info("cancel event matched, cancelling items",{event:e,itemsToCancel:l.map((c=>c.id))}),this.Ns(l.map((c=>c.id))),l.forEach((c=>this.Bs(c.id))))}if(this.ws.has(e)){s.info("event name matched",{event:e,eventPayload:n,items:this.ws.get(e)});var u=this.Rs(e,n,wi.Activation);this.Hs(u.map((c=>c.id)))}}onAction(e){this.xs.has(e)&&this.Hs(this.xs.get(e)||[])}Hs(e){var n;if(e.length!==0){var i=!((n=this._instance)==null||n.get_session_id==null||!n.get_session_id()),r=[];for(var s of e)i&&this.Cs(s)?this.qs(s)&&this.Us(s):r.push(s);r.length>0&&(this._s=[...new Set([...this._s,...r])]),this.Ds().info("updating activated items",{activatedItems:this.getActivatedIds()})}}qs(e){this._s=this._s.filter((i=>i!==e));var n=this.zs();return!n.includes(e)&&(this.Ws([...n,e]),this.Vs(),!0)}Ns(e){var n=new Set(e);this._s=this._s.filter((s=>!n.has(s)));var i=this.Zs(),r=i.filter((s=>!n.has(s)));r.length!==i.length&&(this.Ws(r),r.length===0&&this.Gs()),this.js(e)}Qs(){var e,n=this.Ms();if(!n)return{};var i=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n];return i&&typeof i=="object"?i:{}}Us(e){if(this.Ms()){var n=this.Qs();this.Ts(I({},n,{[e]:Date.now()}))}}js(e){if(this.Ms()){var n=this.Qs(),i={},r=!1;for(var s of Object.entries(n)){var o=s[0],a=s[1];e.includes(o)?r=!0:i[o]=a}r&&(Kt(i)?this.Es():this.Ts(i))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var n=this.Qs()[e];return ke(n)?n:void 0}}Zs(){var e,n=this.Js();return((e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n])||[]}zs(){var e,n,i=this.Zs();if(i.length===0)return[];var r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[this.Ys()],s=(n=this._instance)==null||n.get_session_id==null?void 0:n.get_session_id();return s&&r===s?i:[]}Vs(){var e,n=(e=this._instance)==null||e.get_session_id==null?void 0:e.get_session_id();n&&this.Xs(n)}Gs(){this.ta()}Ss(e){var n,i=(n=this._instance)==null||(n=n.persistence)==null?void 0:n.props[this.Ys()];if(i&&i!==e){var r=this.Zs(),s=this.Qs();r.length>0&&(this.Ws([]),r.filter((o=>ke(s[o]))).forEach((o=>this.Bs(o)))),this.Gs(),this.Ks()}}getActivatedIds(){return[...new Set([...this.zs(),...this._s])].filter((e=>!this.ea(e)))}reset(){this._s=[],this.Zs().length>0&&this.Ws([]),this.Gs(),this.Ks()}getEventToItemsMap(){return this.ws}ia(){return this.Os}}class Um extends jm{constructor(e){super(e)}Js(){return ua}Ys(){return Fr}Ms(){return Rr}Ts(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Rr]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Rr)}Cs(e){var n,i;this.As((s=>{i=s.find((o=>o.id===e))}));var r=(n=i)==null||(n=n.appearance)==null?void 0:n.surveyPopupDelaySeconds;return ke(r)&&r>0}ra(){return qt.SHOWN}As(e){var n;(n=this._instance)==null||n.getSurveys(e)}Bs(e){var n;(n=this._instance)==null||n.cancelPendingSurvey(e)}Ds(){return Q}Ws(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[ua]:e})}Xs(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Fr]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Fr)}ea(){return!1}$s(e,n){var i;this.As((s=>{i=s.find((o=>o.id===n))}));var r=!i||(function(s){var o;return qf(s)&&!((o=s.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||s.schedule==="always"})(i);return r?e===qt.SHOWN?"consume":"ignore":e===qt.SHOWN?"persist":e===qt.DISMISSED||e===qt.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var Ir="SDK is not enabled or survey functionality is not yet loaded",fu="Disabled. Not loading surveys.",Hm=w!=null&&w.location?os(w.location.hash,"__posthog")||os(location.hash,"state"):null,hu="_postHogToolbarParams",pu=pe("[Toolbar]"),gu=pe("[FeatureFlags]");class Wm{constructor(e,n){n===void 0&&(n=!1),this.na=!1,this.update(e,n)}update(e,n){this.sa=((i,r)=>{var s,o,a,l;return{bootstrap:{featureFlags:(s=i.bootstrap)==null?void 0:s.featureFlags,featureFlagPayloads:(o=i.bootstrap)==null?void 0:o.featureFlagPayloads},remoteRequestsDisabled:r,featureFlagsDisabled:!!i.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!i.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!i.advanced_feature_flags_dedup_per_session,cacheTtlMs:i.feature_flag_cache_ttl_ms,requestTimeoutMs:i.feature_flag_request_timeout_ms,compression:i.disable_compression?"none":"base64",evaluationContexts:(a=(l=i.evaluation_contexts)!==null&&l!==void 0?l:i.evaluation_environments)!==null&&a!==void 0?a:[],flagKeys:U(i.flag_keys)?i.flag_keys:void 0}})(e,n),!e.evaluation_environments||e.evaluation_contexts||this.na||(gu.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.na=!0),C(e.flag_keys)||U(e.flag_keys)||gu.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var mu=pe("[FeatureFlags]"),bn=pe("[FeatureFlags]",{debugEnabled:!0}),Do=`" failed. Feature flags didn't load in time.`,vu="connection_error",_u=t=>{for(var e={},n=0;t.length>n;n++)e[t[n]]=!0;return e},yu=t=>{var e={};for(var n of $r(t||{})){var i=n[1];i&&(e[n[0]]=i)}return e},St=pe("[Error tracking]"),wu="Refusing to render web experiment since the viewer is a likely bot",zm={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>cs(e,t),not_regex:(t,e)=>!cs(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class Me{get Ne(){return this._instance.config}constructor(e){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(i){i===void 0&&(i=!1),n.getWebExperiments((r=>{Me.aa("retrieved web experiments from the server"),n.oa=new Map,r.forEach((s=>{if(s.feature_flag_key){var o;n.oa&&(Me.aa("setting flag key ",s.feature_flag_key," to web experiment ",s),(o=n.oa)==null||o.set(s.feature_flag_key,s));var a=n._instance.getFeatureFlag(s.feature_flag_key);X(a)&&s.variants[a]&&n.la(s.name,a,s.variants[a].transforms)}else if(s.variants)for(var l in s.variants){var u=s.variants[l];Me.ua(u,n._instance)&&n.la(s.name,l,u.transforms)}}))}),i)},this._instance=e,this._instance.onFeatureFlags((i=>{this.onFeatureFlags(i)}))}initialize(){}onFeatureFlags(e){if(this._is_bot())Me.aa(wu);else if(!this.Ne.disable_web_experiments){if(H(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();Me.aa("applying feature flags",e),e.forEach((n=>{var i;if(this.oa&&(i=this.oa)!=null&&i.has(n)){var r,s=this._instance.getFeatureFlag(n),o=(r=this.oa)==null?void 0:r.get(n);s&&o!=null&&o.variants[s]&&this.la(o.name,s,o.variants[s].transforms)}}))}}previewWebExperiment(){var e=Me.getWindowLocation();if(e!=null&&e.search){var n=ii(e?.search,"__experiment_id"),i=ii(e?.search,"__experiment_variant");n&&i&&(Me.aa("previewing web experiments "+n+" && "+i),this.getWebExperiments((r=>{this.ha(parseInt(n),i,r)}),!1,!0))}}loadIfEnabled(){this.Ne.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,n,i){if(this.Ne.disable_web_experiments&&!i)return e([]);var r=this._instance.get_property("$web_experiments");if(r&&!n)return e(r);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this.Ne.token),method:"GET",timestampMode:"query",callback:s=>e(s.statusCode===200&&s.json&&s.json.experiments||[])})}ha(e,n,i){var r=i.filter((s=>s.id===e));r&&r.length>0&&(Me.aa("Previewing web experiment ["+r[0].name+"] with variant ["+n+"]"),this.la(r[0].name,n,r[0].variants[n].transforms))}static ua(e,n){return!H(e.conditions)&&Me.da(e,n)&&Me.va(e)}static da(e,n){var i;if(H(e.conditions)||H((i=e.conditions)==null?void 0:i.url))return!0;var r=Me.getWindowLocation();if(r){var s,o,a,l=af(n,r.href);return(s=e.conditions)==null||!s.url||zm[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return w?.location}static va(e){var n;if(H(e.conditions)||H((n=e.conditions)==null?void 0:n.utm))return!0;var i=Ef();if(i.utm_source){var r,s,o,a,l,u,c,d,f=(r=e.conditions)==null||(r=r.utm)==null||!r.utm_campaign||((s=e.conditions)==null||(s=s.utm)==null?void 0:s.utm_campaign)==i.utm_campaign,h=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==i.utm_source,p=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==i.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==i.utm_term;return f&&p&&g&&h}return!1}static aa(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;n>r;r++)i[r-1]=arguments[r];A.info("[WebExperiments] "+e,i)}la(e,n,i){this._is_bot()?Me.aa(wu):n!=="control"?i.forEach((r=>{if(r.selector){var s;Me.aa("applying transform of variant "+n+" for experiment "+e+" ",r);var o=(s=document)==null?void 0:s.querySelectorAll(r.selector);o?.forEach((a=>{var l=a;r.html&&(l.innerHTML=r.html),r.css&&l.setAttribute("style",r.css)}))}})):Me.aa("Control variants leave the page unmodified.")}_is_bot(){return He&&this._instance?Uf(He,this.Ne.custom_blocked_useragents):void 0}}var ot=pe("[Conversations]"),En="Conversations not available yet.",bu="console",Jf="__posthogHandledLogsRequestError",jo=(t,e)=>{var n=t instanceof Error?t:new Error(e);return n[Jf]=!0,n},Eu=t=>!!t&&typeof t=="object"&&t[Jf]===!0,As={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=mu,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 Wm(t.config,t.Qi()),this.Ta=this.Ea)}updateConfig(t,e){var n;(n=this.Ea)==null||n.update(t,e)}setup(t){return this.Ia=t,this.rt=t.logger.createLogger("[FeatureFlags]"),n=()=>{this.Ia===t&&(this.Ia=void 0,this.nn=t,this.Pa(t))},(e=t.kv.initialize())!=null&&e.then?e.then(n):n();var e,n}Pa(t){if(this.nn===t)return w&&ve(w,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){w?.removeEventListener("online",this.Ca)}dispose(){var t;this.ba++,this.wa=!1,this.Ia=void 0,this.nn&&(this.La(),(t=this.Ra)==null||t.dispose(),this.Ra=void 0,this.ga=[],w?.removeEventListener("online",this.Ca),this.nn=void 0)}get Ne(){return this.Ta.get()}Oa(t){var e;return(e=this.nn)==null?void 0:e.kv.get(t)}F(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.set(t)}))}q(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.remove(t)}))}Da(t){try{t()}catch(e){this.rt.error("Failed to update feature flag persistence",e)}}Fa(){var t={};for(var e of[Ti,$i,Pr,It]){var n=this.Oa(e);C(n)||(t[e]=n)}this.fa=t;var i=I({},t),r=this.Oa(Sn);if(r)for(var s of Object.entries(r))i["$feature/"+s[0]]=s[1];this.pa=i}Aa(){var t=this.Ne.cacheTtlMs;if(!t||0>=t)return!1;var e=this.Oa(ji);return typeof e!="number"||Date.now()-e>t}$a(){return!!this.Aa()&&(this.xa||this.ya||(this.xa=!0,this.rt.warn("Feature flag cache is stale, triggering refresh..."),this.reloadFeatureFlags()),!0)}Na(){var t=this.Ne.evaluationContexts;return t!=null&&t.length?t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid evaluation context found:",e,"Expected non-empty string"),n})):[]}qa(){var t=this.Ne.flagKeys;if(!C(t))return t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid flag key found:",e,"Expected non-empty string"),n}))}initialize(){var t,e,n=this.Ne,i=(t=(e=n.bootstrap)==null?void 0:e.featureFlags)!==null&&t!==void 0?t:{};if(Object.keys(i).length){var r,s,o=(r=(s=n.bootstrap)==null?void 0:s.featureFlagPayloads)!==null&&r!==void 0?r:{},a=Object.keys(i).filter((u=>!!i[u])).reduce(((u,c)=>(u[c]=i[c]||!1,u)),{}),l=Object.keys(o).filter((u=>a[u])).reduce(((u,c)=>(o[c]&&(u[c]=o[c]),u)),{});return this.ja({featureFlags:a,featureFlagPayloads:l})}}updateFlags(t,e,n){var i,r,s=n!=null&&n.merge&&(i=this.Oa(Sn))!==null&&i!==void 0?i:{},o=n!=null&&n.merge&&(r=this.Oa($i))!==null&&r!==void 0?r:{},a=I({},s,t),l=I({},o,e),u={};for(var c of Object.entries(a)){var d=c[0],f=c[1];u[d]={key:d,enabled:pc(f),variant:gc(f),reason:void 0,metadata:C(l?.[d])?void 0:{id:0,version:void 0,description:void 0,payload:l[d]}}}this.ja({flags:u})}get hasLoadedFlags(){return this.ma}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var t=this.Oa(la),e=this.Oa(It),n=this.Oa(xn);if(!n&&!e)return t||{};var i=fe({},t||{}),r=[...new Set([...Object.keys(n||{}),...Object.keys(e||{})])];for(var s of r){var o,a,l=i[s],u=e?.[s],c=C(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=C(u)?l?.variant:typeof u=="string"?u:void 0,f=n?.[s],h=I({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(h.original_enabled=l?.enabled),d!==l?.variant&&(h.original_variant=l?.variant),f&&(h.metadata=I({},l?.metadata,{payload:f,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),i[s]=h}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:n,finalDetails:i}),this.ca=!0),i}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((n=>{var i=t[n];return{key:n,enabled:pc(i),variant:gc(i),payload:hc(e[n])}}))}getFlagVariants(){var t=this.Oa(Sn),e=this.Oa(It);if(!e)return t||{};for(var n=fe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:e,finalFlags:n}),this.ca=!0),n}getFlagPayloads(){var t=this.Oa($i),e=this.Oa(xn);if(!e)return t||{};for(var n=fe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flag payloads!",{flagPayloads:t,overriddenPayloads:e,finalPayloads:n}),this.ca=!0),n}reloadFeatureFlags(){this._a||this.Ne.featureFlagsDisabled||this.Ma()||this.Ba||(this.ga.slice().forEach((t=>{try{t()}catch(e){this.rt.error("Error while running feature flags reloading callback",e)}})),this.Ba=setTimeout((()=>{this.Ha()}),5))}La(){clearTimeout(this.Ba),this.Ba=void 0}onReloading(t){return this.ga.push(t),()=>{this.ga=this.ga.filter((e=>e!==t))}}ensureFlagsLoaded(){this.ma||this.ya||this.Ba||this.reloadFeatureFlags()}setAnonymousDistinctId(t){this.$anon_distinct_id=t}setReloadingPaused(t){this._a=t}resetFlagCallReported(){this.q(Cn)}Ha(t){this.La();var e=this.nn;if(e&&!this.Ne.remoteRequestsDisabled&&!this.Ma())if(this.ya)this.wa=!0;else{var n={token:e.projectToken,distinct_id:e.distinctId,groups:e.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:I({},e.initialPersonProperties,this.Oa(jt)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(In),timezone:Af()};C(e.deviceId)||(n.$device_id=e.deviceId),(t!=null&&t.disableFlags||this.Ne.featureFlagsDisabled)&&(n.disable_flags=!0);var i=this.Na();i.length&&(n.evaluation_contexts=i);var r=this.qa();C(r)||(n.flag_keys=r);var s=this.Ne.onlyEvaluateSurveyFeatureFlags,o="/flags/?v=2"+(s?"&only_evaluate_survey_feature_flags=true":""),a=this.ba;this.ya=!0;var l=()=>{this.wa&&(this.wa=!1,this.Ha())},u=c=>{this.ya=!1,a===this.ba&&(this.F({[Tr]:[vu]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:n,compression:this.Ne.compression==="base64"?Ue.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,f,h=(d=c.json)!==null&&d!==void 0?d:{},p=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),p||this.wa||(this.$anon_distinct_id=void 0),!n.disable_flags||this.wa){this.ka=!p;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?vu:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),h.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((f=h.quotaLimited)==null||!f.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[Tr]:g}),m?this.rt.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more."):n.disable_flags||this.ja(h,p,{partialResponse:s}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return wf(this.Sa,3)}Ua(t){this.Sa=bf(t,this.Sa,3,(()=>this.rt.warn("Feature flag requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped refreshing feature flags; will try again when connectivity changes.")))}getFeatureFlag(t,e){var n;if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var i=this.getFeatureFlagResult(t,e);return(n=i?.variant)!==null&&n!==void 0?n:i?.enabled}}else this.rt.warn('getFeatureFlag for key "'+t+Do)}getFeatureFlagDetails(t){return this.getFlagsWithDetails()[t]}getFeatureFlagPayload(t){var e=this.getFeatureFlagResult(t,{send_event:!1});return e?.payload}getFeatureFlagResult(t,e){if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var n,i=this.getFlagVariants(),r=t in i,s=i[t],o=this.getFlagPayloads()[t],a=String(s),l=this.Oa(Pr)||void 0,u=this.Oa(ji)||void 0,c=this.Oa(Cn)||{};if(this.Ne.deduplicateCallsPerSession){var d,f=(d=this.nn)==null?void 0:d.session.sessionId,h=this.Oa(Li);f&&f!==h&&(c={},n=f)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))n&&this.F({[Cn]:c,[Li]:n});else{var p,g,m,v,E,S,_,b,k,T;U(c[t])?c[t].push(a):c[t]=[a],this.F(I({[Cn]:c},n?{[Li]:n}:{}));var x=this.getFeatureFlagDetails(t),F=[...(p=this.Oa(Tr))!==null&&p!==void 0?p:[]];C(s)&&F.push("flag_missing");var $={$feature_flag:t,$feature_flag_response:s,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((g=this.Ne.bootstrap)==null||(g=g.featureFlags)==null?void 0:g[t])||null,$feature_flag_bootstrapped_payload:((m=this.Ne.bootstrap)==null||(m=m.featureFlagPayloads)==null?void 0:m[t])||null,$used_bootstrap_value:!this.ka};C(x==null||(v=x.metadata)==null?void 0:v.has_experiment)||($.$feature_flag_has_experiment=x.metadata.has_experiment),C(x==null||(E=x.metadata)==null?void 0:E.version)||($.$feature_flag_version=x.metadata.version);var O,L=(S=x==null||(_=x.reason)==null?void 0:_.description)!==null&&S!==void 0?S:x==null||(b=x.reason)==null?void 0:b.code;L&&($.$feature_flag_reason=L),x!=null&&(k=x.metadata)!=null&&k.id&&($.$feature_flag_id=x.metadata.id),C(x?.original_variant)&&C(x?.original_enabled)||($.$feature_flag_original_response=C(x.original_variant)?x.original_enabled:x.original_variant),x!=null&&(T=x.metadata)!=null&&T.original_payload&&($.$feature_flag_original_payload=x==null||(O=x.metadata)==null?void 0:O.original_payload),F.length&&($.$feature_flag_error=F.join(",")),this.za($)}else n&&this.F({[Cn]:c,[Li]:n});if(r)return{key:t,enabled:!!s,variant:typeof s=="string"?s:void 0,payload:hc(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+Do)}za(t){try{var e;(e=this.nn)==null||e.capture("$feature_flag_called",t).catch((n=>{this.rt.error("Failed to capture feature flag call",n)}))}catch(n){this.rt.error("Failed to capture feature flag call",n)}}getRemoteConfigPayload(t,e){this.Wa(t,e)}Wa(t,e){var n=this;return se((function*(){var i=n.nn;if(i){var r={distinct_id:i.distinctId,token:i.projectToken,person_properties:{$lib:i.library.name,$lib_version:i.library.version}},s=n.Na();s.length&&(r.evaluation_contexts=s);var o,a=n.qa();C(a)||(r.flag_keys=a);try{var l,u=(l=(yield i.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:r,compression:n.Ne.compression==="base64"?Ue.Base64:void 0,sentAt:"body",timeoutMs:n.Ne.requestTimeoutMs})).json)==null?void 0:l.featureFlagPayloads;o=u?.[t]||void 0}catch(c){return void n.rt.error("Remote config feature flag request failed",c)}try{e(o)}catch(c){n.rt.error("Remote config feature flag callback failed",c)}}}))()}isFeatureEnabled(t,e){if(e===void 0&&(e={}),e.fresh&&!this.ka)return e.defaultValue;if(!(this.ma||this.getFlags()&&this.getFlags().length>0))return this.rt.warn('isFeatureEnabled for key "'+t+Do),e.defaultValue;var n=this.getFeatureFlag(t,e);return C(n)?e.defaultValue:!!n}addFeatureFlagsHandler(t){this.featureFlagEventHandlers.push(t)}removeFeatureFlagsHandler(t){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((e=>e!==t))}receivedFeatureFlags(t,e,n){this.ja(t,e,n)}ja(t,e,n){if(this.nn){this.ma=!0;var i=(function(r,s,o,a,l,u){s===void 0&&(s={}),o===void 0&&(o={}),a===void 0&&(a={}),u===void 0&&(u=mu);var c=((k,T)=>{var x=k.flags;return x?I({},k,{featureFlags:Object.fromEntries(Object.keys(x).map((F=>{var $;return[F,($=x[F].variant)!==null&&$!==void 0?$:x[F].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(x).filter((F=>x[F].enabled)).filter((F=>{var $;return($=x[F].metadata)==null?void 0:$.payload})).map((F=>{var $;return[F,($=x[F].metadata)==null?void 0:$.payload]})))}):(k.featureFlags&&T.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),k)})(r,u),d=c.flags,f=c.featureFlags,h=c.featureFlagPayloads;if(f){var p=r.requestId,g=r.evaluatedAt;if(U(f)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(f)for(var v=0;f.length>v;v++)m[f[v]]=!0;return{[Ti]:f,[Sn]:m,[Zr]:!1}}var E=f,S=h,_=d;if(l!=null&&l.partialResponse)E=I({},s,E),S=I({},o,S),_=I({},a,_);else if(r.errorsWhileComputingFlags)if(d){var b=new Set(Object.keys(d).filter((k=>{var T;return!((T=d[k])!=null&&T.failed)})));E=I({},s,Object.fromEntries(Object.entries(E).filter((k=>b.has(k[0]))))),S=I({},o,Object.fromEntries(Object.entries(S||{}).filter((k=>b.has(k[0]))))),_=I({},a,Object.fromEntries(Object.entries(_||{}).filter((k=>b.has(k[0])))))}else E=I({},s,E),S=I({},o,S),_=I({},a,_);return I({[Ti]:Object.keys(yu(E)),[Sn]:E||{},[$i]:S||{},[la]:_||{},[Zr]:r.minimalFlagCalledEvents===!0},p?{[Pr]:p}:{},g?{[ji]:g}:{})}})(t,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),n,this.rt);i&&this.F(i),e||(this.xa=!1),this.Va(e)}}override(t,e){e===void 0&&(e=!1),this.rt.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:t,suppressWarning:e})}overrideFeatureFlags(t){this.Za(t)}Za(t){if(this.nn){if(t===!1)return this.q([It,xn]),this.Va(),void bn.info("All overrides cleared");if(U(t))return this.F({[It]:_u(t)}),this.Va(),void bn.info("Flag overrides set",{flags:t});if(t&&typeof t=="object"&&("flags"in t||"payloads"in t)){var e,n=t;this.ca=!!((e=n.suppressWarning)!==null&&e!==void 0&&e);var i={},r=n.flags,s=n.payloads;return r&&(i[It]=U(r)?_u(r):r),s&&(i[xn]=s),Object.keys(i).length&&this.F(i),r===!1&&s===!1?this.q([It,xn]):r===!1?this.q(It):s===!1&&this.q(xn),this.Va(),r===!1?bn.info("Flag overrides cleared"):r&&bn.info("Flag overrides set",{flags:r}),void(s===!1?bn.info("Payload overrides cleared"):s&&bn.info("Payload overrides set",{payloads:s}))}if(t&&typeof t=="object")return this.F({[It]:t}),this.Va(),void bn.info("Flag overrides set",{flags:t});this.rt.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:t})}else this.rt.warn("posthog.featureFlags.overrideFeatureFlags called before feature flags were ready")}onFeatureFlags(t){if(this.addFeatureFlagsHandler(t),this.ma){var e=this.Ga(),n=e.flags,i=e.flagVariants;try{t(n,i)}catch(r){this.rt.error("Error while running feature flags callback",r)}}return()=>this.removeFeatureFlagsHandler(t)}updateEarlyAccessFeatureEnrollment(t,e,n){var i=(this.Oa(Ar)||[]).find((l=>l.flagKey===t)),r={["$feature_enrollment/"+t]:e},s={$feature_flag:t,$feature_enrollment:e,$set:r};i&&(s.$early_access_feature_name=i.name),n&&(s.$feature_enrollment_stage=n);var o=I({},this.getFlagVariants(),{[t]:e});this.F({[Ti]:Object.keys(yu(o)),[Sn]:o,[jt]:I({},this.Oa(jt)||{},r)}),this.Va();try{var a;(a=this.nn)==null||a.capture("$feature_enrollment_update",s).catch((l=>{this.rt.error("Failed to capture early access feature enrollment",l)}))}catch(l){this.rt.error("Failed to capture early access feature enrollment",l)}}getEarlyAccessFeatures(t,e,n){e===void 0&&(e=!1);var i=this.Oa(Ar);!i||e?this.Qa(t,n):t(i)}Qa(t,e){var n=this;return se((function*(){var i=n.nn;if(i){var r,s=e?"&"+e.map((a=>"stage="+a)).join("&"):"";try{var o=yield i.sendRequest("/api/early_access_features/?token="+i.projectToken+s,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;n.F({[Ar]:r=o.json.earlyAccessFeatures})}catch(a){return void n.rt.error("Early access feature request failed",a)}try{t(r)}catch(a){n.rt.error("Early access feature callback failed",a)}}}))()}Ga(){var t=this.getFlags(),e=this.getFlagVariants();return{flags:t.filter((n=>e[n])),flagVariants:Object.keys(e).filter((n=>e[n])).reduce(((n,i)=>(n[i]=e[i],n)),{})}}Va(t){this.Fa();var e=this.Ga(),n=e.flags,i=e.flagVariants;this.featureFlagEventHandlers.forEach((r=>{try{r(n,i,{errorsLoading:t})}catch(s){this.rt.error("Error while running feature flags callback",s)}}))}setPersonPropertiesForFlags(t,e){e===void 0&&(e=!0),this.Ka(t,e)}Ka(t,e){e===void 0&&(e=!0);var n=this.Oa(jt)||{},i=t?.$set||(t!=null&&t.$set_once?{}:t),r=t?.$set_once,s={};if(r)for(var o in r)({}).hasOwnProperty.call(r,o)&&(o in n||(s[o]=r[o]));this.F({[jt]:I({},n,s,i)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=I({},this.Oa(jt)||{});t.forEach((i=>{delete n[i]})),this.F({[jt]:n}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(jt),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=this.Oa(In)||{},i=I({},n);for(var r of Object.keys(t))i[r]=I({},n[r],t[r]);this.F({[In]:i}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(In)||{};this.F({[In]:I({},e,{[t]:{}})})}else this.q(In)}reset(){this.ba++,this.wa=!1,this.Fa(),this.ma=!1,this._a=!1,this.ka=!1,this.$anon_distinct_id=void 0,this.La(),this.ca=!1,this.Sa=0}}},qm={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===ki||this.Ya===Sr?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=cu,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(P==null||!P.visibilityState||P.visibilityState==="visible")return!0;var n=w==null||(e=w.performance)==null||e.getEntriesByType==null?void 0:e.getEntriesByType("visibility-state");return!(n!=null&&n.length)||n.some((i=>i.name==="visible"))})(),this.Ie=()=>{var e;P?.visibilityState==="visible"&&(this.io=!0,(e=this.Ja)==null||e.setDocumentWasEverVisible==null||e.setDocumentWasEverVisible(!0))},this._instance=t,!this._instance.sessionManager)throw Bt.error("started without valid sessionManager"),new Error(ka+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===Wt)throw new Error(ka+' cannot be used with cookieless_mode="always"');P!=null&&P.addEventListener&&ve(P,"visibilitychange",this.Ie)}initialize(){this.startIfEnabledOrStop()}dispose(){this.eo=!0,P==null||P.removeEventListener==null||P.removeEventListener("visibilitychange",this.Ie),this.stopRecording()}get ro(){var t,e=!((t=this._instance.get_property(An))==null||!t.enabled),n=!this.Ne.disable_session_recording,i=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return w&&e&&n&&!i}startIfEnabledOrStop(t){var e;if(!(this.eo||this.ro&&(e=this.Ja)!=null&&e.isStarted)){var n=!C(Object.assign)&&!C(Array.from);this.ro&&n?(this.no(t),Bt.info("starting")):(this.Ya=cu,this.stopRecording())}}no(t){var e,n,i;this.ro&&(this.Ya!==ki&&this.Ya!==Sr&&(this.Ya=uu),B!=null&&(e=B.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(n=B.__PosthogExtensions__)!=null&&n.initSessionRecording?this.so(t):(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,this.ao,(r=>{if(r)return Bt.error("could not load recorder",r);this.so(t)})))}stopRecording(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.stop()}oo(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.discard()}lo(){var t,e;(t=this.Mr)==null||t.unregister(al),(e=this.Mr)==null||e.unregister(Yd)}uo(t,e){if(H(t))return null;var n,i=ke(t)?t:parseFloat(t);return typeof(n=i)!="number"||!Number.isFinite(n)||0>n||n>1?(Bt.warn(e+" must be between 0 and 1. Ignoring invalid value:",t),null):i}ho(t){if(this.Mr){var e,n,i=this.Mr,r=()=>{var s,o=t.sessionRecording===!1?void 0:t.sessionRecording,a=this.uo((s=this.Ne.session_recording)==null?void 0:s.sampleRate,"session_recording.sampleRate"),l=this.uo(o?.sampleRate,"remote config sampleRate"),u=a??l;H(u)&&this.lo();var c=o?.minimumDurationMilliseconds;i.register({[An]:I({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:I({capturePerformance:t.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:u,minimumDurationMilliseconds:C(c)?null:c,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers,version:o?.version,triggerGroups:o?.triggerGroups})})};r(),(e=this.Xa)==null||e.call(this),this.Xa=(n=this._instance.sessionManager)==null?void 0:n.onSessionId(r)}}onRemoteConfig(t){var e=t.ok?t.config:void 0;return e&&"sessionRecording"in e?e.sessionRecording===!1?(this.ho(e),void this.oo()):(this.ho(e),void this.startIfEnabledOrStop()):(this.Ya===ki&&(this.Ya=Sr,Bt.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(t,e){var n;e===void 0&&(e="log"),(n=this.Ja)!=null&&n.log?this.Ja.log(t,e):Bt.warn("log called before recorder was ready")}get ao(){var t,e,n=(t=this._instance)==null||(t=t.persistence)==null?void 0:t.get_property(An);return(n==null||(e=n.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(An);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(n){return Bt.warn("persisted remote config for session recording is invalid and will be ignored",n),!1}return!H(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,n,i;if(!this.eo){if((e=B.__PosthogExtensions__)==null||!e.initSessionRecording)return Bt.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[rf]:!0});var r;if(this.Ja||(this.Ja=(r=B.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===Sr||this.Ya===ki?void 0:(this.Ya=ki,Bt.info("persisted remote config is stale, requesting fresh config before starting"),void new Pf(this._instance).load());this.Ya=uu,(n=(i=this.Ja).setDocumentWasEverVisible)==null||n.call(i,this.io),this.Ja.start(t)}}onRRwebEmit(t){var e;(e=this.Ja)==null||e.onRRwebEmit==null||e.onRRwebEmit(t)}overrideLinkedFlag(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Zd]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Jd]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,n;this.Ja||(n=this.Mr)==null||n.register({[t==="url"?Xd:Qd]:!0}),(e=this.Ja)==null||e.overrideTrigger(t)}get sdkDebugProperties(){var t;return((t=this.Ja)==null?void 0:t.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(t,e){var n;return!((n=this.Ja)==null||!n.tryAddCustomEvent(t,e))}}},Vm={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new ou(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,n=he(this.instance.config.autocapture)?this.instance.config.autocapture:{};return n.url_allowlist=(t=n.url_allowlist)==null?void 0:t.map((i=>new RegExp(i))),n.url_ignorelist=(e=n.url_ignorelist)==null?void 0:e.map((i=>new RegExp(i))),n}yo(){if(this.isBrowserSupported()){if(w&&P){var t=n=>{n=n||w?.event;try{this.bo(n)}catch(i){Lo.error("Failed to capture event",i)}};if(ve(P,"submit",t,{capture:!0}),ve(P,"change",t,{capture:!0}),ve(P,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=n=>{n=n||w?.event;try{this.bo(n,Mo)}catch(i){Lo.error("Failed to capture copy/cut event",i)}};ve(P,"copy",e,{capture:!0}),ve(P,"cut",e,{capture:!0})}}}else Lo.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.vo&&(this.yo(),this.vo=!0)}onRemoteConfig(t){if(this.fo=!0,t.ok){var e=t.config;e.elementsChainAsString&&(this.po=e.elementsChainAsString);var n=e.autocapture_opt_out;mt(n)&&(this.instance.persistence&&this.instance.persistence.register({[ta]:n}),this.co=n),this.startIfEnabled()}else this.startIfEnabled()}setElementSelectors(t){this.mo=t}getElementSelectors(t){var e,n=[];return(e=this.mo)==null||e.forEach((i=>{var r=P?.querySelectorAll(i);r?.forEach((s=>{t===s&&n.push(i)}))})),n}get isEnabled(){var t,e,n=(t=this.instance.persistence)==null?void 0:t.props[ta],i=this.co,r=this.instance.Qi()&&!this.fo;if(Ye(i)&&!mt(n)&&!r)return!1;var s=(e=this.co)!==null&&e!==void 0?e:!!n;return!!this.instance.config.autocapture&&!s}bo(t,e){if(e===void 0&&(e="$autocapture"),this.isEnabled){var n,i=Eo(t);cf(i)&&(i=i.parentNode||null),e==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&this.instance.config.rageclick&&(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,t.timeStamp||new Date().getTime())&&Nc(i,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var r=e===Mo;if(i&&(function(d,f,h,p,g,m){var v;if(!w||fl(d)||h!=null&&h.url_allowlist&&!$c(h.url_allowlist,m)||h!=null&&h.url_ignorelist&&$c(h.url_ignorelist,m))return!1;if(h!=null&&h.dom_event_allowlist){var E=h.dom_event_allowlist;if(E&&!E.some((x=>f.type===x)))return!1}var S=gf(d,p),_=S.parentIsUsefulElement,b=S.targetElementList;if(!(function(x,F){var $=F?.element_allowlist;if(C($))return!0;var O,L=function(K){if($.some((V=>K.tagName.toLowerCase()===V)))return{v:!0}};for(var N of x)if(O=L(N))return O.v;return!1})(b,h)||!va(b,h?.css_selector_allowlist)||va(b,(v=h?.css_selector_ignorelist)!==null&&v!==void 0?v:Wg))return!1;try{var k=w.getComputedStyle(d);if(k&&k.getPropertyValue("cursor")==="pointer"&&f.type==="click")return!0}catch{}var T=d.tagName.toLowerCase();switch(T){case"html":return!1;case"form":return(g||["submit"]).indexOf(f.type)>=0;case"input":case"select":case"textarea":return(g||["change","click"]).indexOf(f.type)>=0;default:return _?(g||["click"]).indexOf(f.type)>=0:(g||["click"]).indexOf(f.type)>=0&&(dl.indexOf(T)>-1||d.getAttribute("contenteditable")==="true")}})(i,t,this.Ne,r,r?["copy","cut"]:void 0,this.instance)){var s=Lm(i,{e:t,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.Ne.element_attribute_ignorelist,elementsChainAsString:this.po,disableCaptureUrlHashes:this.instance.config.disable_capture_url_hashes}),o=s.props;if(s.explicitNoCapture)return!1;var a=this.getElementSelectors(i);if(a&&a.length>0&&(o.$element_selectors=a),e===Mo){var l,u=ff(w==null||(l=w.getSelection())==null?void 0:l.toString()),c=t.type||"clipboard";if(!u)return!1;o.$selected_content=u,o.$copy_type=c}return this.instance.capture(e,o),!0}}}isBrowserSupported(){return je(P?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(w==null||(e=w.location)==null?void 0:e.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(A.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.wo&&this.wo(),this.wo=void 0,A.info("History API monitoring stopped")}monitorHistoryChanges(){w&&w.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(w&&((e=w.history[t])==null||!e.__posthog_wrapped__)){var n=this;(function(i,r,s){try{if(!(r in i))return au;var o={next:i[r]},a=s((function(){for(var l=arguments.length,u=new Array(l),c=0;l>c;c++)u[c]=arguments[c];return o.next.apply(this,u)}));return je(a)&&(a.prototype=a.prototype||{},Object.defineProperties(a,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:o}})),i[r]=a,()=>{if(i[r]!==a)for(var l=i[r];je(l)&&l.__posthog_layer__;){var u=l.__posthog_layer__;if(u.next===a)return void(u.next=o.next);l=u.next}else i[r]=o.next}}catch{return au}})(w.history,t,(i=>function(r,s,o){i.call(this,r,s,o),n.So(t)}))}}So(t){try{var e,n=w==null||(e=w.location)==null?void 0:e.pathname;if(!n)return;n!==this._o&&this.isEnabled&&this._instance.capture(Vn,{navigation_type:t}),this._o=n}catch(i){A.error("Error capturing "+t+" pageview",i)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};ve(w,"popstate",t),this.wo=()=>{w&&w.removeEventListener("popstate",t)}}}},heatmaps:class{get Ne(){return this.instance.config}constructor(t){var e;this.Co=!1,this.vo=!1,this.Mo=null,this.instance=t,this.Co=!((e=this.instance.persistence)==null||!e.props[na]),this.rageclicks=new ou(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return he(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return H(this.Ne.capture_heatmaps)?H(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;Om.info("starting..."),this.To(),this.Ie()}else{var t;clearInterval((t=this.Mo)!==null&&t!==void 0?t:void 0),this.Eo(),this.getAndClearBuffer()}}onRemoteConfig(t){if(t.ok){var e=t.config;if("heatmaps"in e){var n=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[na]:n}),this.Co=n,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){Oo(t.originalEvent)&&this.ke(t.originalEvent,"deadclick")}Ie(){this.Mo&&clearInterval(this.Mo),this.Mo=P?.visibilityState==="visible"?setInterval(this.cr.bind(this),this.flushIntervalMilliseconds):null}To(){w&&P&&(this.Po=this.cr.bind(this),ve(w,ns,this.Po),this.Ro=t=>this.ke(t||w?.event),ve(P,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||w?.event),ve(P,"mousemove",this.Ao,{capture:!0}),this.Lo=new Wc(this.instance,Jg,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),ve(P,ts,this.Oo),this.vo=!0)}Eo(){var t;w&&P&&(this.Po&&w.removeEventListener(ns,this.Po),this.Ro&&P.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&P.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&P.removeEventListener(ts,this.Oo),clearTimeout(this.Do),(t=this.Lo)==null||t.stop(),this.vo=!1)}$o(t,e){var n=this.instance.scrollManager.scrollY(),i=this.instance.scrollManager.scrollX(),r=this.instance.scrollManager.scrollElement(),s=(function(o,a,l){for(var u=o;u&&hn(u)&&!et(u,"body");){if(u===l)return!1;var c=void 0;try{var d,f,h;c=(d=(f=(h=u.ownerDocument)==null?void 0:h.defaultView)!==null&&f!==void 0?f:w)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(j(a,c))return!0;u=hf(u)}return!1})(Eo(t),["fixed","sticky"],r);return{x:t.clientX+(s?0:i),y:t.clientY+(s?0:n),target_fixed:s,type:e}}ke(t,e){var n;if(e===void 0&&(e="click"),!Tc(t.target)&&Oo(t)){var i=this.$o(t,e);(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,new Date().getTime())&&Nc(Eo(t),this.instance.config.rageclick)&&this.Vt(I({},i,{type:"rageclick"})),this.Vt(i)}}Fo(t){!Tc(t.target)&&Oo(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(w){var e=this.Ne.disable_capture_url_hashes?fn(w.location.href):w.location.href,n=this.Ne.custom_personal_data_properties,i=this.Ne.mask_personal_data_properties?[...ri,...n||[]]:[],r=Zi(e,i,Xi);this.R=this.R||{},this.R[r]||(this.R[r]=[]),this.R[r].push(t)}}cr(){this.R&&!Kt(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:Wc,webVitalsAutocapture:class{constructor(t){var e;this.Co=!1,this.vo=!1,this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this.No=()=>{clearTimeout(this.qo),this.qo=void 0,this.R.metrics.length!==0&&(this._instance.capture("$web_vitals",I({$current_url:this.R.url},this.R.metrics.reduce(((n,i)=>I({},n,{["$web_vitals_"+i.name+"_event"]:I({},i),["$web_vitals_"+i.name+"_value"]:i.value})),{}))),this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.jo=n=>{var i;if(this.R=this.R||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},H(n?.name)||H(n?.value))wn.error("Invalid metric received",n);else{var r=typeof n.navigationURL=="string"?n.navigationURL:void 0,s=this.Bo(r);if(!C(s)){var o=ke(n.navigationId)||typeof n.navigationId=="string"?"navigation:"+n.navigationId:"url:"+s;if(!this.Ho||this.Ho>n.value){this.R.navigationKey!==o&&(this.No(),this.qo=setTimeout(this.No,this.flushToCaptureTimeoutMs)),C(this.R.navigationKey)&&(this.R.navigationKey=o,this.R.url=s),this.R.firstMetricTimestamp=C(this.R.firstMetricTimestamp)?Date.now():this.R.firstMetricTimestamp,n.attribution&&n.attribution.interactionTargetElement&&(n.attribution.interactionTargetElement=void 0);var a=(i=this._instance.sessionManager)==null?void 0:i.checkAndGetSessionAndWindowId(!0),l=I({},n,r?{navigationURL:s}:{},{$current_url:s,timestamp:Date.now()});C(a)||(l.$session_id=a.sessionId,l.$window_id=a.windowId),this.R.metrics.push(l),this.R.metrics.length===this.allowedMetrics.length&&this.No()}else wn.error("Ignoring metric with value >= "+this.Ho,n)}}},this.Uo=()=>{if(!this.vo){var n,i,r,s,o=B.__PosthogExtensions__,a=o?.postHogWebVitalsCallbacksByFlavor,l=a?.[this.zo]||(this.zo==="web-vitals"&&C(a)?o?.postHogWebVitalsCallbacks:void 0);if(C(l)||(n=l.onLCP,i=l.onCLS,r=l.onFCP,s=l.onINP),n&&i&&r&&s){var u={reportSoftNavs:this.useSoftNavs};this.allowedMetrics.indexOf("LCP")>-1&&n(this.jo.bind(this),u),this.allowedMetrics.indexOf("CLS")>-1&&i(this.jo.bind(this),u),this.allowedMetrics.indexOf("FCP")>-1&&r(this.jo.bind(this),u),this.allowedMetrics.indexOf("INP")>-1&&s(this.jo.bind(this),u),this.vo=!0}else wn.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[oa]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,n=he(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return H(n)?((e=this._instance.persistence)==null?void 0:e.props[aa])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(he(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=he(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=he(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=he(this.Wo)&&ke(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:lu;return t>0&&6e4>=t?lu:t}get isEnabled(){var t=me?.protocol;if(t!=="http:"&&t!=="https:")return wn.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=he(this.Wo)?this.Wo.web_vitals:mt(this.Wo)?this.Wo:void 0;return mt(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(wn.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var n=he(e.capturePerformance)&&!!e.capturePerformance.web_vitals,i=he(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[oa]:n}),this._instance.persistence.register({[aa]:i})),this.Co=n,this.startIfEnabled()}}}get zo(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}ai(t){var e=B.__PosthogExtensions__,n=this.zo,i=e?.postHogWebVitalsCallbacksByFlavor;i!=null&&i[n]||n==="web-vitals"&&C(i)&&e!=null&&e.postHogWebVitalsCallbacks?t():e==null||e.loadExternalDependency==null||e.loadExternalDependency(this._instance,n,(r=>{r?wn.error("failed to load script",r):t()}))}Bo(t){var e=t||w?.location.href;if(e){var n=this._instance.config.disable_capture_url_hashes?fn(e):e,i=this._instance.config.custom_personal_data_properties,r=this._instance.config.mask_personal_data_properties?[...ri,...i||[]]:[];return Zi(n,r,Xi)}wn.error("Could not determine current URL")}}},Gm={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var n;if(w&&this.isEnabled&&(n=B.__PosthogExtensions__)!=null&&n.errorWrappingFunctions){var i=B.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,r=B.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,s=B.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.Vo&&this.Ne.capture_unhandled_errors&&(this.Vo=i(this.captureException.bind(this))),!this.Zo&&this.Ne.capture_unhandled_rejections&&(this.Zo=r(this.captureException.bind(this))),!this.Go&&this.Ne.capture_console_errors&&(this.Go=s(this.captureException.bind(this)))}catch(o){Ii.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[ia]),this.Jo=new qp(I({},(function(n){var i,r,s,o;return n===void 0&&(n={}),{refillRate:(i=(r=n.exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:n.__exceptionRateLimiterRefillRate)!==null&&i!==void 0?i:1,bucketSize:(s=(o=n.exceptionRateLimiterBucketSize)!==null&&o!==void 0?o:n.__exceptionRateLimiterBucketSize)!==null&&s!==void 0?s:10}})(this._instance.config.error_tracking),{refillInterval:1e4,rt:Ii})),this.Ne=this.Yo(),this.startIfEnabledOrStop()}Yo(){var t=this._instance.config.capture_exceptions,e={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return he(t)?e=I({},e,t):(C(t)?this.Ko:t)&&(e=I({},e,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),e}get isEnabled(){return this.Ne.capture_console_errors||this.Ne.capture_unhandled_errors||this.Ne.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(Ii.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",(i=>{if(i)return Ii.error("failed to load script",i);t()}))}Qo(){var t,e,n;(t=this.Vo)==null||t.call(this),this.Vo=void 0,(e=this.Zo)==null||e.call(this),this.Zo=void 0,(n=this.Go)==null||n.call(this),this.Go=void 0}onRemoteConfig(t){if(t.ok){var e=t.config;"autocaptureExceptions"in e&&(this.Ko=!!e.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[ia]:this.Ko}),this.Ne=this.Yo(),this.startIfEnabledOrStop())}}onConfigChange(){this.Ne=this.Yo()}captureException(t){var e,n,i,r=(e=t==null||(n=t.$exception_list)==null||(n=n[0])==null?void 0:n.type)!==null&&e!==void 0?e:"Exception";this.Jo.consumeRateLimit(r)?Ii.info("Skipping exception capture because of client rate limiting.",{exception:r}):(i=this._instance.exceptions)==null||i.sendExceptionEvent(t)}},exceptions:class{constructor(t){var e,n;this.Xo=[],this.tl=new lg([new mg,new Ig,new _g,new vg,new Sg,new Eg,new wg,new xg],(function(i){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;r>o;o++)s[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` -`),d=l;c.length>d;d++){var f=c[d];if(1024>=f.length){var h=Ac.test(f)?f.replace(Ac,"$1"):f;if(!h.match(/\S*Error: /)){for(var p of s){var g=p(h,i);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var v=Array.from(m);return v.reverse(),v.slice(0,50).map((E=>{return I({},E,{filename:E.filename||(S=v,S[S.length-1]||{}).filename,function:E.function||ni});var S}))})(u)}})("web:javascript",fg,gg)),this._instance=t,this.Xo=(e=(n=this._instance.persistence)==null?void 0:n.get_property(ra))!==null&&e!==void 0?e:[],this.el=Jr(this.il()),this.rl=new Cg(this.el)}onConfigChange(){this.el=Jr(this.il()),this.rl.setConfig(this.el)}onRemoteConfig(t){var e,n,i;if(t.ok){var r=t.config;if("errorTracking"in r){var s=(e=(n=r.errorTracking)==null?void 0:n.suppressionRules)!==null&&e!==void 0?e:[],o=(i=r.errorTracking)==null?void 0:i.captureExtensionExceptions;this.Xo=s,this._instance.persistence&&this._instance.persistence.register({[ra]:this.Xo,[sa]:o})}}}get nl(){var t,e=!!this._instance.get_property(sa),n=this._instance.config.error_tracking.captureExtensionExceptions;return(t=n??e)!==null&&t!==void 0&&t}buildProperties(t,e){return this.tl.buildFromUnknown(t,{syntheticException:e?.syntheticException,mechanism:{handled:e?.handled}})}addExceptionStep(t,e){if(this.el.enabled)try{if(!X(t)||t.trim().length===0)return void St.warn("Ignoring exception step because message must be a non-empty string");var n=(function(s){if(!s)return{sanitizedProperties:{},droppedKeys:[]};var o=[];return{sanitizedProperties:Object.keys(s).reduce(((a,l)=>kg.has(l)?(o.push(l),a):(a[l]=s[l],a)),{}),droppedKeys:o}})(this.sl(e)),i=n.sanitizedProperties,r=n.droppedKeys;r.length>0&&St.warn("Ignoring reserved exception step fields",{droppedKeys:r}),this.rl.add(I({[Kr]:t,[Yr]:new Date().toISOString()},i))}catch(s){St.error("Failed to add exception step. Ignoring breadcrumb.",s)}}sendExceptionEvent(t){try{var e=t.$exception_list;if(this.al(e)){if(this.ol(e))return this.ll("Exception dropped: matched a suppression rule"),void St.info("Skipping exception capture because a suppression rule matched");if(!this.nl&&this.ul(e))return this.ll("Exception dropped: thrown by a browser extension"),void St.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.hl(e))return this.ll("Exception dropped: thrown by the PostHog SDK"),void St.info("Skipping exception capture because it was thrown by the PostHog SDK")}var n=this.el.enabled&&H(t.$exception_steps)?this.dl(t):t,i=typeof(s=globalThis._posthogReleaseId)=="string"&&s.length>0?s:void 0;i&&(n.$release_id=i);try{var r=this._instance.capture("$exception",n,{_noTruncate:!0,_batchKey:"exceptionEvent",Wn:!0});return r&&this.rl.clear(),r}catch(o){return St.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void St.error("Failed to process exception event. Ignoring this exception.",o)}var s}dl(t){try{var e=this.rl.getAttachable();return e.length===0?t:I({},t,{$exception_steps:e})}catch(n){return St.error("Failed to read buffered exception steps. Capturing exception without steps.",n),t}}ll(t){this.el.enabled&&this.rl.add({[Kr]:t,[Yr]:new Date().toISOString()})}sl(t){return he(t)?I({},t):{}}il(){var t,e;return(t=(e=this._instance.config.error_tracking)==null?void 0:e.exception_steps)!==null&&t!==void 0?t:{}}ol(t){if(t.length===0)return!1;try{var e=t.reduce(((n,i)=>{var r=i.type,s=i.value;return X(r)&&r.length>0&&n.$exception_types.push(r),X(s)&&s.length>0&&n.$exception_values.push(s),n}),{$exception_types:[],$exception_values:[]});return this.Xo.some((n=>{var i=n.values.map((r=>{var s=Wf[r.operator],o=e[r.key];if(!s||!o)return!1;var a=U(r.value)?r.value:[r.value];return a.length>0&&s(a,o)}));return n.type==="OR"?i.some(Boolean):i.every(Boolean)}))}catch(n){return St.warn("Failed to evaluate suppression rules. Capturing the exception.",n),!1}}ul(t){return t.flatMap((e=>{var n,i;return(n=(i=e.stacktrace)==null?void 0:i.frames)!==null&&n!==void 0?n:[]})).some((e=>e.filename&&e.filename.startsWith("chrome-extension://")))}hl(t){if(t.length>0){var e,n,i,r,s=(e=(n=t[0].stacktrace)==null?void 0:n.frames)!==null&&e!==void 0?e:[],o=s[s.length-1];return(i=o==null||(r=o.filename)==null?void 0:r.includes("posthog.com/static"))!==null&&i!==void 0&&i}return!1}al(t){return!H(t)&&U(t)}}},Km=I({productTours:class{get Mr(){return this._instance.persistence}constructor(t){this.vl=null,this.cl=null,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(t.ok){var e=t.config;if("productTours"in e){var n,i;if(this.Mr&&this.Mr.register({[ol]:!!e.productTours}),!Bo(this._instance))return!this.vl&&H((n=this.Mr)==null?void 0:n.props[Mi])||xr.info("product tours disabled; stopping and clearing cached tours"),(i=this.vl)==null||i.stop(),this.vl=null,void this.clearCache();this.loadIfEnabled()}}}loadIfEnabled(){!this.vl&&Bo(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.generateProductTours?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",(i=>{i?xr.error("Could not load product tours script",i):t()}))}fl(){var t;!this.vl&&(t=B.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=B.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(t,e){if(e===void 0&&(e=!1),!U(this.cl)||e){var n=this.Mr;if(n){var i=n.props[Mi];if(U(i)&&!e)return this.cl=i,void t(i,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",timestampMode:"query",callback:r=>{if(Bo(this._instance)){var s=r.statusCode;if(s!==200||!r.json){var o="Product Tours API could not be loaded, status: "+s;return s===0?r.error||xr.warn(o):xr.error(o),void t([],{isLoaded:!1,error:o})}var a=U(r.json.product_tours)?r.json.product_tours:[];this.cl=a,n&&n.register({[Mi]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){H(this.vl)?t([],{isLoaded:!1,error:"Product tours not loaded"}):this.vl.getActiveProductTours(t)}showProductTour(t){var e;(e=this.vl)==null||e.showTourById(t)}previewTour(t){this.vl?this.vl.previewTour(t):this.ai((()=>{var e;this.fl(),(e=this.vl)==null||e.previewTour(t)}))}dismissProductTour(){var t;(t=this.vl)==null||t.dismissTour("user_clicked_skip")}nextStep(){var t;(t=this.vl)==null||t.nextStep()}previousStep(){var t;(t=this.vl)==null||t.previousStep()}clearCache(){var t;this.cl=null,(t=this.Mr)==null||t.unregister(Mi)}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)}}},As),Ym={siteApps:class{constructor(t){this.pl=0,this._instance=t,this.gl=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}ml(t,e){if(e){var n=this.globalsForEvent(e);this.gl.push(n),this.gl.length>1e3&&(this.gl=this.gl.slice(10))}}get siteAppLoaders(){var t;return(t=B._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,n,i,r,s,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var f=d[0];l[f]={id:u[f],type:f,properties:d[1]}}var h=t.$set_once,p=t.$set;return{event:I({},hd(t,Bm),{properties:I({},t.properties,p?{$set:I({},(e=(n=t.properties)==null?void 0:n.$set)!==null&&e!==void 0?e:{},p)}:{},h?{$set_once:I({},(i=(r=t.properties)==null?void 0:r.$set_once)!==null&&i!==void 0?i:{},h)}:{}),elements_chain:(s=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&s!==void 0?s:"",distinct_id:(a=t.properties)==null?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}bl(t){var e,n=(e=t.tagName)==null?void 0:e.toLowerCase();return n==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(Et.error("prepare_external_dependency_stylesheet returned null"),null):n==="script"&&this._instance.config.prepare_external_dependency_script?this._instance.config.prepare_external_dependency_script(t)||(Et.error("prepare_external_dependency_script returned null"),null):t}_l(){var t,e,n,i,r,s,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=P?.defaultView,u=l==null||(t=l.Node)==null?void 0:t.prototype;if(!l||!u)return()=>{};if(this.pl++,this.wl)return this.kl();var c=[],d=this,f=new WeakSet,h=(m,v,E)=>{if(m!=null&&m[v]){var S=m[v];m[v]=E(S),c.push((()=>{m[v]=S}))}},p=m=>{if(f.has(m))return m;var v=d.bl(m);return v&&f.add(v),v},g=m=>m.map((v=>typeof v=="string"?v:p(v))).filter((v=>!Ye(v)));return h(u,"appendChild",(m=>function(v){var E=p(v);return E?m.call(this,E):v})),h(u,"insertBefore",(m=>function(v,E){var S=p(v);return S?m.call(this,S,E):v})),h(u,"replaceChild",(m=>function(v,E){var S=p(v);return S?m.call(this,S,E):E})),[(e=l.Element)==null?void 0:e.prototype,(n=l.Document)==null?void 0:n.prototype,(i=l.DocumentFragment)==null?void 0:i.prototype].forEach((m=>{h(m,"append",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),h(m,"prepend",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))}))})),[(r=l.Element)==null?void 0:r.prototype,(s=l.CharacterData)==null?void 0:s.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((m=>{h(m,"before",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),h(m,"after",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),h(m,"replaceWith",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];var b=g(S);return S.length&&!b.length?void 0:v.apply(this,b)}))})),h((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(v,E){var S=p(E);return S?m.call(this,v,S):null})),this.wl=()=>{c.forEach((m=>m())),this.wl=void 0},this.kl()}kl(){var t=!1;return()=>{var e;t||(t=!0,this.pl--,this.pl===0&&((e=this.wl)==null||e.call(this)))}}xl(t,e){e===void 0&&(e=!0);var n=this._l();try{var i=t(n);return e&&n(),i}catch(r){throw n(),r}}setupSiteApp(t){var e=this.apps[t.id],n=()=>{var o;!e.errored&&this.gl.length&&(Et.info("Processing "+this.gl.length+" events for site app with id "+t.id),this.gl.forEach((a=>this.xl((()=>e.processEvent==null?void 0:e.processEvent(a))))),e.processedBuffer=!0),Object.values(this.apps).every((a=>a.processedBuffer||a.errored))&&((o=this.yl)==null||o.call(this))},i=!1,r=o=>{e.errored=!o,e.loaded=!0,Et.info("Site app with id "+t.id+" "+(o?"loaded":"errored")),i&&n()};try{var s=this.xl((o=>t.init({posthog:this._instance,callback(a){o(),r(a)}})),!1).processEvent;s&&(e.processEvent=s),i=!0}catch(o){Et.error(du+t.id,o),r(!1)}if(i&&e.loaded)try{n()}catch(o){Et.error("Error while processing buffered events PostHog app with config id "+t.id,o),e.errored=!0}}Sl(){var t=this.siteAppLoaders||[];for(var e of t)this.apps[e.id]={id:e.id,loaded:!1,errored:!1,processedBuffer:!1};for(var n of t)this.setupSiteApp(n)}Cl(t){var e=this;if(Object.keys(this.apps).length!==0){var n=this.globalsForEvent(t),i=function(s){try{e.xl((()=>s.processEvent==null?void 0:s.processEvent(n)))}catch(o){Et.error("Error while processing event "+t.event+" for site app "+s.id,o)}};for(var r of Object.values(this.apps))i(r)}}onRemoteConfig(t){var e,n,i,r=this;if((e=this.siteAppLoaders)!=null&&e.length)return this.isEnabled?(this.Sl(),void this._instance.on("eventCaptured",(l=>this.Cl(l)))):void Et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((n=this.yl)==null||n.call(this),t.ok){var s=t.config;if((i=s.siteApps)!=null&&i.length)if(this.isEnabled){var o=function(){var l,u=a.id,c=a.url;B["__$$ph_site_app_"+u]=r._instance,(l=B.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(r._instance,c,(d=>{if(d)return Et.error(du+u,d)}))};for(var a of s.siteApps)o()}else Et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},Jm={tracingHeaders:class{constructor(t){this.Ml=void 0,this.Tl=void 0,this.El=void 0,this.Uo=()=>{var e,n,i=this.Il();i?(C(this.Ml)&&(this.Ml=(e=B.__PosthogExtensions__)==null||(e=e.tracingHeadersPatchFns)==null?void 0:e._patchXHR(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager)),C(this.Tl)&&(this.Tl=(n=B.__PosthogExtensions__)==null||(n=n.tracingHeadersPatchFns)==null?void 0:n._patchFetch(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager))):this.Qo()},this._instance=t}initialize(){this.startIfEnabledOrStop()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",(i=>{if(i)return Nm.error("failed to load script",i);t()}))}Pl(){var t,e;return(t=(e=this._instance.config.tracing_headers)!==null&&e!==void 0?e:this._instance.config.addTracingHeaders)!==null&&t!==void 0?t:this._instance.config.__add_tracing_headers}Il(){var t=this.Pl();return U(t)?(U(this.El)?this.El.splice(0,this.El.length,...t):this.El=[...t],t.length>0?this.El:void 0):(U(this.El)&&this.El.splice(0),this.El=t||void 0,this.El)}Qo(){var t,e;(t=this.Ml)==null||t.call(this),(e=this.Tl)==null||e.call(this),this.Ml=void 0,this.Tl=void 0}startIfEnabledOrStop(){this.Il()?this.ai(this.Uo):this.Qo()}}},Zm=I({surveys:class{get Ne(){return this._instance.config}constructor(t){this.Rl=void 0,this._surveyManager=null,this.Al=!1,this.Fl=[],this.Ll=null,this.Ol=null,this._instance=t,this._surveyEventReceiver=null}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this.Ne.disable_surveys){if(!t.ok)return Q.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(H(e))return Q.warn("Flags not loaded yet. Not loading surveys.");var n=U(e);this.Rl=n?e.length>0:e,Q.info("flags response received, isSurveysEnabled: "+this.Rl),this.loadIfEnabled()}}reset(){try{var t;(t=this._surveyEventReceiver)==null||t.reset(),localStorage.removeItem("lastSeenSurveyDate");for(var e=[],n=0;nlocalStorage.removeItem(r)))}catch{}}loadIfEnabled(){if(!this._surveyManager)if(this.Al)Q.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)Q.info(fu);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())Q.info("Not loading surveys in cookieless mode without consent.");else{var t=B?.__PosthogExtensions__;if(t){if(!C(this.Rl)||this.Ne.advanced_enable_surveys){var e=this.Rl||this.Ne.advanced_enable_surveys;this.Al=!0;try{var n=t.generateSurveys;if(n)return void this.Dl(n,e);var i=t.loadExternalDependency;if(!i)return void this.$l(ll);i(this._instance,"surveys",(r=>{r||!t.generateSurveys?this.$l("Could not load surveys script",r):this.Dl(t.generateSurveys,e)}))}catch(r){throw this.$l("Error initializing surveys",r),r}finally{this.Al=!1}}}else Q.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new Um(this._instance),Q.info("Surveys loaded successfully"),this.Nl({isLoaded:!0})}$l(t,e){Q.error(t,e),this.Nl({isLoaded:!1,error:t})}onSurveysLoaded(t){return this.Fl.push(t),this._surveyManager&&this.Nl({isLoaded:!0}),()=>{this.Fl=this.Fl.filter((e=>e!==t))}}getSurveys(t,e){if(e===void 0&&(e=!1),this.Ne.disable_surveys)return Q.info(fu),t([]);var n,i=this._instance.get_property(ca);if(i&&!e)return t(i,{isLoaded:!0}),void(this.ql()&&this.getSurveys((()=>{}),!0));typeof Promise<"u"&&this.Ll?this.Ll.then((r=>t(r.surveys,r.context))):(typeof Promise<"u"&&(this.Ll=new Promise((r=>{n=r}))),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this.Ne.token),method:"GET",timestampMode:"query",timeout:this.Ne.surveys_request_timeout_ms,callback:r=>{var s;this.Ll=null;var o=r.statusCode;if(o!==200||!r.json){var a="Surveys API could not be loaded, status: "+o;o!==0?Q.error(a):r.error||Q.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(n==null||n({surveys:[],context:l}))}this.Ol=null;var u,c=r.json.surveys||[],d=c.filter((h=>(function(p){return!(!p.start_date||p.end_date)})(h)&&(qf(h)||(function(p){var g;return!((g=p.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(h))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(s=this._instance.persistence)==null||s.register({[ca]:c,[Xr]:Date.now()});var f={isLoaded:!0};t(c,f),n?.({surveys:c,context:f})}}))}ql(){return this.jl()&&!this.Ll&&!this.Bl()}jl(){var t=this._instance.get_property(Xr);return ke(t)&&Date.now()-t>3e5}Bl(){return ke(this.Ol)&&3e5>Date.now()-this.Ol}markSurveyAsSeen(t,e){var n,i={id:t,current_iteration:(n=e?.iteration)!==null&&n!==void 0?n:null};Gf(i);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}}Nl(t){for(var e of this.Fl)try{if(!t.isLoaded)return e([],t);this.getSurveys(e)}catch(n){Q.error("Error in survey callback",n)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!H(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);Q.warn("init was not called")}Hl(t){var e=null;return this.getSurveys((n=>{var i;e=(i=n.find((r=>r.id===t)))!==null&&i!==void 0?i:null})),e}Ul(t){if(H(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(H(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(H(this._surveyManager))return Q.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 H(this._surveyManager)?(Q.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Ir})):new Promise((n=>{this.getSurveys((i=>{var r,s=(r=i.find((a=>a.id===t)))!==null&&r!==void 0?r:null;if(s){var o=this.zl(s);n({visible:o.eligible,disabledReason:o.reason})}else n({visible:!1,disabledReason:"Survey not found"})}),e)}))}renderSurvey(t,e,n){var i;if(H(this._surveyManager))Q.warn("init was not called");else{var r=typeof t=="string"?this.Hl(t):t;if(r!=null&&r.id)if(Sm.includes(r.type)){var s=P?.querySelector(e);if(s)return(i=r.appearance)!=null&&i.surveyPopupDelaySeconds?(Q.info("Rendering survey "+r.id+" with delay of "+r.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;Q.info("Rendering survey "+r.id+" with delay of "+((o=r.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(a=this._surveyManager)==null||a.renderSurvey(r,s,n),Q.info("Survey "+r.id+" rendered")}),1e3*r.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(r,s,n);Q.warn("Survey element not found")}else Q.warn("Surveys of type "+r.type+" cannot be rendered in the app");else Q.warn("Survey not found")}}displaySurvey(t,e){var n;if(H(this._surveyManager))Q.warn("init was not called");else{var i=this.Hl(t);if(i){var r=i;if((n=i.appearance)!=null&&n.surveyPopupDelaySeconds&&e.ignoreDelay&&(r=I({},i,{appearance:I({},i.appearance,{surveyPopupDelaySeconds:0})})),e.displayType!==ya.Popover&&e.initialResponses&&Q.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),e.ignoreConditions===!1){var s=this.Ul(i);if(!s.eligible)return void Q.warn("Survey is not eligible to be displayed: ",s.reason)}e.displayType!==ya.Inline?this._surveyManager.handlePopoverSurvey(r,e):this.renderSurvey(r,e.selector,e.properties)}else Q.warn("Survey not found")}}cancelPendingSurvey(t){H(this._surveyManager)?Q.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},As),Xm={toolbar:class{constructor(t){this.instance=t}Wl(t){B.ph_toolbar_state=t}Vl(){var t;return(t=B.ph_toolbar_state)!==null&&t!==void 0?t:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(t,e,n){if(t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),ma(this.instance.config)||!w||!P)return!1;t=t??w.location,n=n??w.history;try{if(!e){try{w.localStorage.setItem("test","test"),w.localStorage.removeItem("test")}catch{return!1}e=w?.localStorage}var i,r=Hm||os(t.hash,"__posthog")||os(t.hash,"state"),s=r?Fc((()=>JSON.parse(atob(decodeURIComponent(r)))))||Fc((()=>JSON.parse(decodeURIComponent(r)))):null;return s&&s.action==="ph_authorize"?((i=s).source="url",i&&Object.keys(i).length>0&&(s.desiredHash?t.hash=s.desiredHash:n?n.replaceState(n.state,"",t.pathname+t.search):t.hash="")):((i=JSON.parse(e.getItem(hu)||"{}")).source="localstorage",delete i.userIntent),!(!i.token||this.instance.config.token!==i.token||(this.loadToolbar(i),0))}catch{return!1}}Zl(t){var e=B.ph_load_toolbar||B.ph_load_editor;!H(e)&&je(e)?e(t,this.instance):pu.warn("No toolbar load function found")}loadToolbar(t){var e=!(P==null||!P.getElementById(lf));if(!w||e)return!1;var n=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,i=I({token:this.instance.config.token},t,{apiURL:this.instance.requestRouter.endpointFor("ui")},n?{instrument:!1}:{});if(w.localStorage.setItem(hu,JSON.stringify(I({},i,{source:void 0}))),this.Vl()===2)this.Zl(i);else if(this.Vl()===0){var r;this.Wl(1),(r=B.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"toolbar",(s=>{if(s)return pu.error("[Toolbar] Failed to load",s),void this.Wl(0);this.Wl(2),this.Zl(i)})),ve(w,"turbolinks:load",(()=>{this.Wl(0),this.loadToolbar(i)}))}return!0}Gl(t){return this.loadToolbar(t)}maybeLoadEditor(t,e,n){return t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),this.maybeLoadToolbar(t,e,n)}}},Qm=I({experiments:Me},As),ev={conversations:class{constructor(t){this.Ql=void 0,this._conversationsManager=null,this.Kl=!1,this.Jl=null,this.Yl=!1,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this._instance.config.disable_conversations&&(this.Xl=t.ok,t.ok)){var e=t.config.conversations;H(e)||(mt(e)?this.Ql=e:(this.Ql=e.enabled,this.Jl=e),this.loadIfEnabled())}}reset(){var t;(t=this._conversationsManager)==null||t.reset(),this._conversationsManager=null,this.Ql=void 0,this.Jl=null,this.Xl=void 0,this.Yl=!1}loadIfEnabled(){if(!(this._conversationsManager||this.Kl||this._instance.config.disable_conversations||ma(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=B?.__PosthogExtensions__;if(t&&!C(this.Ql)&&this.Ql)if(this.Jl&&this.Jl.token){this.Kl=!0;try{var e=t.initConversations;if(e)return this.tu(e),void(this.Kl=!1);var n=t.loadExternalDependency;if(!n)return void this.eu(ll);n(this._instance,"conversations",(i=>{i||!t.initConversations?this.eu("Could not load conversations script",i):this.tu(t.initConversations),this.Kl=!1}))}catch(i){this.eu("Error initializing conversations",i),this.Kl=!1}}else ot.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,ot.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else ot.error("Cannot complete initialization: remote config is null")}eu(t,e){ot.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():ot.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!Ye(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":ma(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.Xl===!1?"remote_config_failed":C(this.Ql)?this.Xl?"disabled_in_project":"remote_config_pending":this.Ql?H(this.Jl)||!this.Jl.token?"missing_token":B!=null&&B.__PosthogExtensions__?this.Kl?"initializing":this.Yl?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.isVisible())!==null&&t!==void 0&&t}sendMessage(t,e,n){var i=this;return se((function*(){return i._conversationsManager?i._conversationsManager.sendMessage(t,e,n):(ot.warn(En),null)}))()}getMessages(t,e){var n=this;return se((function*(){return n._conversationsManager?n._conversationsManager.getMessages(t,e):(ot.warn(En),null)}))()}markAsRead(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(ot.warn(En),null)}))()}getTickets(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(ot.warn(En),null)}))()}requestRestoreLink(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(ot.warn(En),null)}))()}restoreFromToken(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(ot.warn(En),null)}))()}restoreFromUrlToken(){var t=this;return se((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(ot.warn(En),null)}))()}getCurrentTicketId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getCurrentTicketId())!==null&&t!==void 0?t:null}getWidgetSessionId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getWidgetSessionId())!==null&&t!==void 0?t:null}Xn(){var t;(t=this._conversationsManager)==null||t.setIdentity()}ts(){var t;(t=this._conversationsManager)==null||t.clearIdentity()}}},tv={logs:class{constructor(t){var e,n=this;this.iu=!1,this.ru=!1,this.rt=pe("[logs]"),this.nu=I({},this.rt,{error(){for(var i=arguments.length,r=new Array(i),s=0;i>s;s++)r[s]=arguments[s];r.some(Eu)||n.rt.error(...r)}}),this.tr=[],this.su=[],this.Sa=0,this.au=()=>{var i,r;this.Sa=0,(i=this.ou)==null||i.onReconnect(),(r=this.lu)==null||r.onReconnect()},this._instance=t,this._instance&&(e=this._instance.config.logs)!=null&&e.captureConsoleLogs&&(this.iu=!0),w&&ve(w,"online",this.au)}uu(t,e,n,i){var r,s=(function(o,a){var l,u,c,d,f,h,p,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,v=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,E=C(v)?Math.max(m,2048):Math.max(m,v),S=o?.resourceAttributes;return{serviceName:(d=(f=S?.["service.name"])!==null&&f!==void 0?f:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(h=S?.["service.version"])!==null&&h!==void 0?h:o?.serviceVersion,environment:(p=S?.["deployment.environment"])!==null&&p!==void 0?p:o?.environment,resourceAttributes:S,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:E,maxBatchRecordsPerPost:100,rateCapWindowMs:g,maxLogsPerInterval:v,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}})((r=this._instance)==null||(r=r.config)==null?void 0:r.logs,n);return[new sg(this.hu(t,e),s,this.nu,(()=>this.du()),(o=>o()),void 0,i),s]}vu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.ou||this.cu!==e){var n;(n=this.ou)==null||n.reset(),this.cu=e;var i=this.uu((()=>this.tr),(r=>{this.tr=r}));this.ou=i[0],this.fu=i[1]}return this.ou}pu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.lu||this.gu!==e){var n;(n=this.lu)==null||n.reset(),this.gu=e;var i=this.uu((()=>this.su),(r=>{this.su=r}),{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},bu);this.lu=i[0],this.mu=i[1]}return this.lu}initialize(){this.loadIfEnabled()}onRemoteConfig(t){var e;if(t.ok){var n=(e=t.config.logs)==null?void 0:e.captureConsoleLogs;!H(n)&&n&&(this.iu=!0,this.loadIfEnabled())}}reset(){var t,e;this.tr=[],(t=this.ou)==null||t.reset(),this.su=[],(e=this.lu)==null||e.reset(),this.Sa=0}captureLog(t){this.vu().captureLog(t)}he(t){this.pu().captureLog(t)}get logger(){return this.yu||(this.yu={trace:(t,e)=>this.captureLog({body:t,level:"trace",attributes:e}),debug:(t,e)=>this.captureLog({body:t,level:"debug",attributes:e}),info:(t,e)=>this.captureLog({body:t,level:"info",attributes:e}),warn:(t,e)=>this.captureLog({body:t,level:"warn",attributes:e}),error:(t,e)=>this.captureLog({body:t,level:"error",attributes:e}),fatal:(t,e)=>this.captureLog({body:t,level:"fatal",attributes:e})}),this.yu}flushLogs(t){t?this.bu(t):(this.ou&&this.ou.flush().catch((e=>this._u(e))),this.lu&&this.lu.flush().catch((e=>this._u(e))))}_u(t){Eu(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=B?.__PosthogExtensions__;if(t){var e=t.loadExternalDependency;e?e(this._instance,"logs",(n=>{var i;n||(i=t.logs)==null||!i.initializeLogs?this.rt.error("Could not load logs script",n):(t.logs.initializeLogs(this._instance),this.ru=!0)})):this.rt.error(ll)}else this.rt.error("PostHog Extensions not found.")}}hu(t,e){var n=this._instance;return{get isDisabled(){return!1},get optedOut(){return!n.is_capturing()},getPersistedProperty:i=>i===Ut.LogsQueue?t():void 0,setPersistedProperty(i,r){var s;i===Ut.LogsQueue&&e((s=r)!==null&&s!==void 0?s:[])},Ot:i=>this.Ot(i),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Ot(t){return new Promise((e=>{if(wf(this.Sa,3))e({kind:"fatal",error:jo(void 0,"logs endpoint is unreachable, dropping batch")});else{var n=!1,i=s=>{n||(n=!0,clearTimeout(r),e(s))},r=setTimeout((()=>{this.rt.warn("Logs request timed out before receiving a response"),i({kind:"retry-later",error:jo(void 0,"logs request timed out")})}),9e4);this._instance._send_request({method:"POST",url:this.wu(),data:t,compression:"best-available",batchKey:"logs",fireCallbackOnDrop:!0,callback:s=>{var o=s.statusCode;if(this.ku(o),o>=200&&300>o)i({kind:"ok"});else if(o===413)i({kind:"too-large"});else if(o!==0&&o!==429&&500>o)i({kind:"fatal",error:new Error("logs request failed with status "+o)});else{var a;o===0?(s.error||this.rt.warn("Logs request failed before receiving an HTTP response"),i({kind:"retry-later",error:jo(s.error,"logs request failed before receiving an HTTP response")})):i({kind:"retry-later",error:(a=s.error)!==null&&a!==void 0?a:new Error("logs request failed with status "+o)})}}})}}))}ku(t){(t!==0||this._instance.__loaded)&&(this.Sa=bf(t,this.Sa,3,(()=>this.rt.warn("Log requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped sending logs; will try again when connectivity changes."))))}bu(t){this.tr.length>0&&this.xu(t,this.tr,this.fu,ne.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,bu,(e=>{this.su=e}))}xu(t,e,n,i,r){if(e.length!==0){var s=e.map((a=>a.record));r([]);var o=zd(s,Wd(n,ne.LIB_NAME,ne.LIB_VERSION),i,ne.LIB_VERSION);this._instance._send_request({method:"POST",url:this.wu(),data:o,compression:"best-available",batchKey:"logs",transport:t})}}wu(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}du(){var t,e={};if(e.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var n=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.windowId,r=n.sessionStartTimestamp,s=n.lastActivityTimestamp;e.sessionId=n.sessionId,e.windowId=i,H(r)||(e.sessionStartTimestamp=r),H(s)||(e.lastActivityTimestamp=s)}if(B!=null&&(t=B.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?fn(B.location.href):B.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},nv={metrics:class{constructor(t){this.rt=pe("[metrics]"),this._instance=t}initialize(){}vu(){var t,e,n=(t=this._instance)==null||(t=t.config)==null?void 0:t.metrics;return this.ou&&this.cu===n||((e=this.ou)==null||e.reset(),this.cu=n,this.ou=new og(this.hu(),(function(i){var r,s,o,a,l,u=i?.resourceAttributes;return{serviceName:(r=u?.["service.name"])!==null&&r!==void 0?r:i?.serviceName,serviceVersion:(s=u?.["service.version"])!==null&&s!==void 0?s:i?.serviceVersion,environment:(o=u?.["deployment.environment"])!==null&&o!==void 0?o:i?.environment,resourceAttributes:u,beforeSend:i?.beforeSend,flushIntervalMs:(a=i?.flushIntervalMs)!==null&&a!==void 0?a:1e4,maxSeriesPerFlush:(l=i?.maxSeriesPerFlush)!==null&&l!==void 0?l:1e3}})(n),this.rt)),this.ou}count(t,e,n){e===void 0&&(e=1),this.vu().count(t,e,n)}gauge(t,e,n){this.vu().gauge(t,e,n)}histogram(t,e,n){this.vu().histogram(t,e,n)}flush(t){if(!this.ou)return Promise.resolve();if(t){var e=this.ou.drainWindow();return e&&this.Jt(e,t),Promise.resolve()}return this.ou.flush().catch((n=>this.rt.error("PostHog metrics flush failed:",n)))}reset(){var t;(t=this.ou)==null||t.reset()}hu(){var t=this._instance,e=this;return{get isDisabled(){return!1},get optedOut(){return!t.is_capturing()},Jt:n=>e.Jt(n),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Jt(t,e){return new Promise((n=>{var i=!1,r=o=>{i||(i=!0,clearTimeout(s),n(o))},s=setTimeout((()=>r({kind:"retry-later",error:new Error("metrics request timed out")})),9e4);this._instance._send_request(I({method:"POST",url:this.Su(),data:t,compression:"best-available",batchKey:"metrics"},e&&{transport:e},{fireCallbackOnDrop:!0,callback(o){var a=o.statusCode;if(a>=200&&300>a)r({kind:"ok"});else if(a===413)r({kind:"too-large"});else if(a!==0&&a!==429&&500>a)r({kind:"fatal",error:new Error("metrics request failed with status "+a)});else{var l;r({kind:"retry-later",error:(l=o.error)!==null&&l!==void 0?l:new Error("metrics request failed with status "+a)})}}}))}))}Su(){return this._instance.requestRouter.endpointFor("api","/i/v1/metrics")+"?token="+encodeURIComponent(this._instance.config.token)}}},iv=I({},As,qm,Vm,Gm,Km,Ym,Zm,Jm,Xm,Qm,ev,tv,nv);Ze.__defaultExtensionClasses=I({},iv);(function(){ne.SDK_DIST_CHANNEL="npm";var t=Wi[Gn]=new Ze;return(function(){function e(){e.done||(e.done=!0,Yf=!1,ie(Wi,(function(n){n._dom_loaded()})))}P!=null&&P.addEventListener?P.readyState==="complete"?e():ve(P,"DOMContentLoaded",e,{capture:!1}):w&&A.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const rv=["a[href]","button:not([disabled])","input:not([disabled]):not([type='hidden'])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(",");let pt=null,Ca=null,Zf="";const Aa=new Map;function Xf(t){return[...t.querySelectorAll(rv)].filter(e=>!e.hidden&&e.getAttribute("aria-hidden")!=="true"&&e.getClientRects().length>0)}function sv(t){for(const e of document.body.children)e===t||e.tagName==="SCRIPT"||(Aa.set(e,{inert:e.inert,ariaHidden:e.getAttribute("aria-hidden")}),e.inert=!0,e.setAttribute("aria-hidden","true"))}function ov(){for(const[t,e]of Aa)t.inert=e.inert,e.ariaHidden===null?t.removeAttribute("aria-hidden"):t.setAttribute("aria-hidden",e.ariaHidden);Aa.clear()}function Qf(t){return t?.dataset.modalDismissible!=="false"&&t?.getAttribute("aria-busy")!=="true"}function We(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n)return!1;pt&&pt!==n&&ze(pt,{restoreFocus:!1,force:!0}),Ca=e.trigger||document.activeElement,pt=n,Zf=document.body.style.overflow,sv(n),document.body.style.overflow="hidden",n.classList.add("open"),n.setAttribute("aria-hidden","false");const i=n.querySelector(".modal-content");i&&(i.style.transform="scale(1) translateY(0)");const r=()=>{if(pt!==n)return;((e.initialFocus?n.querySelector(e.initialFocus):n.querySelector("[data-modal-initial-focus]"))||Xf(n)[0]||n.querySelector(".modal-content")||n).focus({preventScroll:!0})};return requestAnimationFrame(r),setTimeout(r,260),!0}function ze(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n||!e.force&&!Qf(n))return!1;n.classList.remove("open"),n.setAttribute("aria-hidden","true"),ov(),document.body.style.overflow=Zf,pt=null;const i=Ca;return Ca=null,e.restoreFocus!==!1&&i?.isConnected&&i.focus({preventScroll:!0}),!0}function Su(t,e,n="Operation in progress"){const i=typeof t=="string"?document.getElementById(t):t;i&&(i.dataset.modalDismissible=e?"false":"true",i.setAttribute("aria-busy",String(!!e)),e?i.setAttribute("aria-label",n):i.removeAttribute("aria-label"))}function av(t){if(!Qf(t))return;const e=t.dataset.modalCloseHandler;e&&typeof window[e]=="function"?window[e]():ze(t)}document.addEventListener("keydown",t=>{if(!pt)return;if(t.key==="Escape"){t.preventDefault(),t.stopImmediatePropagation(),av(pt);return}if(t.key!=="Tab"){t.stopPropagation();return}const e=Xf(pt);if(!e.length){t.preventDefault(),(pt.querySelector(".modal-content")||pt).focus();return}const n=e[0],i=e[e.length-1];t.shiftKey&&document.activeElement===n?(t.preventDefault(),i.focus()):!t.shiftKey&&document.activeElement===i&&(t.preventDefault(),n.focus())},!0);function lv(){document.querySelectorAll(".modal-overlay").forEach(t=>{t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-hidden",t.classList.contains("open")?"false":"true");const e=t.querySelector(".modal-content");e&&!e.hasAttribute("tabindex")&&(e.tabIndex=-1);const n=t.querySelector("h1, h2, h3");n&&(n.id||(n.id=`${t.id}-title`),t.setAttribute("aria-labelledby",n.id)),t.querySelectorAll(".modal-close").forEach(i=>{i.getAttribute("aria-label")||i.setAttribute("aria-label","Close dialog")})})}const ml=Object.freeze({free:"Free",professional:"Pro",power:"Power"}),cv=Object.freeze({free:2,professional:50,power:2e3}),uv="(contact us)",dv=Object.freeze({free:Object.freeze(["2 generations/month","Gemini model only","Code Review"]),professional:Object.freeze(["50 generations/month","All models","Code Regeneration","Code Review"]),power:Object.freeze(["2000 generations/month","All models","Code Regeneration","Bring your own key (BYOK)","Code Review","All models + early access",`API & MCP access ${uv}`])}),eh="CodeFile",th="GeneratedCode",fv={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function ln(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Pa(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function hv(t={},e=0){const n=Pa(t.artifactType||t.type||eh),i=Pa(t.artifactName||t.name||t.fileName||`${th}-${e+1}`);return`${n||"artifact"}-${i||e+1}`}function nh(t={},e=0){const n=ln(t),i=n.artifactType||n.type||eh,r=n.artifactName||n.name||th;let s=n.fileName||r;return s.endsWith(".dart")||(s+=".dart"),{id:Pa(n.id)||hv({...n,artifactType:i,artifactName:r,fileName:s},e),artifactType:i,artifactName:r,fileName:s,deployPath:n.deployPath||"",description:n.description||"",code:n.code||n.content||"",dependencies:ih(n.dependencies),imports:Array.isArray(n.imports)?n.imports:[],publicApi:Array.isArray(n.publicApi)?n.publicApi:[],relationships:rh(n.relationships),deployStatus:n.deployStatus||"pending",review:n.review||null,metadata:ln(n.metadata),codeType:n.codeType||fv[i]||"O"}}function ih(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const n=ln(e),i=n.name||n.package;return i?{name:i,version:n.version||null,versionRequired:!!(n.versionRequired||n.required),inferred:!!n.inferred,...n.reason?{reason:n.reason}:{}}:null}).filter(Boolean):Object.entries(ln(t)).map(([e,n])=>({name:e,version:n||null,inferred:!1})):[]}function rh(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const n=ln(e);return!n.from&&!n.to?null:{from:n.from||null,to:n.to||null,type:n.type||"uses",description:n.description||""}}).filter(Boolean):[]}function Fa(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;try{return JSON.parse(e)}catch{const n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(!n)return null;try{return JSON.parse(n[1].trim())}catch{return null}}}function Qi(t,e={}){const n=[],i=typeof t=="string"?Fa(t):t,s=ln(i||{});!i&&typeof t=="string"&&n.push("Structured bundle parse failed; using legacy single-artifact fallback.");const o=Array.isArray(s.artifacts)?s.artifacts:[{artifactType:s.artifactType||e.artifactType,artifactName:s.artifactName||e.artifactName,fileName:s.fileName||e.fileName,description:s.description,code:s.code||e.code||(typeof t=="string"?t:""),dependencies:s.dependencies||e.dependencies,relationships:s.relationships||e.relationships}];o.forEach((d,f)=>{!d?.artifactType&&!d?.type&&n.push(`Artifact ${f+1} has no artifactType; it will deploy as a standalone code file under lib/custom_code/ root.`)});const a=o.map((d,f)=>nh(d,f)),l=new Map(o.map((d,f)=>[ln(d).id,a[f]?.id]).filter(([d,f])=>d&&f)),u=d=>l.get(d)||d,c=rh(s.relationships||e.relationships).map(d=>({...d,from:d.from?u(d.from):d.from,to:d.to?u(d.to):d.to}));return{schemaVersion:s.schemaVersion||e.schemaVersion||null,id:s.id||e.id||"bundle-current",title:s.title||s.name||e.title||"Generated artifact bundle",description:s.description||e.description||"",artifacts:a,dependencies:ih(s.dependencies||e.dependencies),relationships:c,deployOrder:Array.isArray(s.deployOrder)?s.deployOrder.map(u):a.map(d=>d.id),warnings:[...n,...Array.isArray(s.warnings)?s.warnings:[]],metadata:ln(s.metadata)}}function oi(t){return Qi(t).artifacts[0]||nh()}function Zt(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function ai(t){return JSON.stringify(t,null,2)}function pv(t){return ai({task:"architect",userRequest:String(t??"")})}function gv(t){const e=Zt(t);return e&&typeof e=="object"&&typeof e.task=="string"?ai(e):ai({task:"generate_bundle",bundleSpec:e})}function mv(t){return ai({task:"review_bundle",generatedBundle:Zt(t),outputRequirements:{bundleReview:["status","score","summary","manualActions","findings"],scoreRange:[0,100],eachArtifact:["id","review.status","review.findings"],manualActions:{definition:"Setup the developer must perform by hand in the FlutterFlow editor that FlutterFlow will NOT do for them.",exclude:["creating the Custom Action, Widget or Code File itself - deploying the code creates it","declaring parameters or return values FlutterFlow derives from the function signature","anything that resolves as a side effect of using the action or widget in the editor","generic advice such as testing, reviewing or rebuilding the app"],preferEmpty:"Return an empty array when nothing qualifies - an empty list is the expected result for most bundles."}}})}function vl(t,e=null){const n={stage:t};return e!=null&&(n.bundle=Zt(e)),n}function vv({bundleSpec:t,artifactBundle:e,bundleReview:n,artifactId:i,userFeedback:r}){return ai({task:"regenerate_artifact",artifactId:i,bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(r)})}function sh({bundleSpec:t,artifactBundle:e,bundleReview:n,userFeedback:i}){return ai({task:"regenerate_bundle",bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(i??"")})}const xu={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"},_v=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function tt(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function yv(t){return tt(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||tt(t.filterSummary)||tt(t.filterResults):!1}function oh(t,e=0){if(!tt(t)||e>3)return null;if(yv(t))return t;for(const n of _v){const i=t[n];if(tt(i)){const r=oh(i,e+1);if(r)return r}}return null}function ds(t){return Array.isArray(t)?t.some(ds):tt(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(ds):!1}function Ra(t){return Array.isArray(t)?t.some(Ra):tt(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(Ra):!1}function ah(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function wv(t,e){if(tt(t))for(const[n,i]of Object.entries(t)){if(!tt(i))continue;const r=tt(i.categories)?i.categories:{},s=Object.entries(r).filter(([,o])=>tt(o)&&o.matched===!0).map(([o])=>o);s.length>0?s.forEach(o=>e.add(o)):i.matched===!0&&e.add(ah(n))}}function bv(t,e){if(!t)return;const n=Array.isArray(t)?t.flatMap(i=>tt(i)?Object.entries(i):[]):Object.entries(t);for(const[i,r]of n){if(!ds(r))continue;const s=ah(i),o=r?.raiFilterResult?.raiFilterTypeResults||(s==="rai"?r?.raiFilterTypeResults:null),a=tt(o)?Object.entries(o).filter(([,l])=>ds(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(s)}}function Ev(t){return xu[t]?xu[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function Iu(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 Sv(t){const e=oh(t);if(!e)return null;const n=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);wv(e.filterSummary,n),bv(e.filterResults,n);const i=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||n.size>0,r=e.invocationResult||null,s=Ra(e.filterSummary||e.filterResults);return!i&&!s&&!["PARTIAL","FAILURE"].includes(r)?null:{kind:i?"blocked":"unavailable",invocationResult:r,matchedFilters:[...n]}}function xv(t,e){const n=Sv(t);if(!n)return null;const i=[...new Set(n.matchedFilters.map(Ev))],r=n.kind==="blocked",s=new Error(r?`Safety screening blocked this pipeline step for ${Iu(i)}.`:"Safety screening could not be completed. Please try again.");return s.name="ModelArmorError",s.code=r?"MODEL_ARMOR_BLOCKED":"MODEL_ARMOR_UNAVAILABLE",s.isModelArmor=!0,s.pipelineStep=e,s.userTitle=r?"Request blocked for safety":"Safety check unavailable",s.userMessage=r?`The safety check detected ${Iu(i)}. Edit your request to remove or rephrase the flagged content, then run the pipeline again.`:"The safety service did not finish all of its checks. Please wait a moment and run the pipeline again.",s.retryExplanation=r?"Trying another model would not change this safety decision.":"A fallback model was not attempted because safety screening must complete first.",s.matchedFilters=n.matchedFilters,s}function Iv(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function ku(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,n=[];for(const i of Iv(t).split(` -`)){if(!/^[A-Za-z_$]/.test(i)||e.test(i))continue;const r=i.match(/^[\w$<>,?\s[\]]+?\s([a-zA-Z_$][\w$]*)\s*\(/);r&&n.push(r[1])}return n}function _l(t,e){const n=t.replace(/\.dart$/,"");if(e==="W")return n.replace(/(^|_)(\w)/g,(i,r,s)=>s.toUpperCase());if(e==="A"){const i=n.replace(/(^|_)(\w)/g,(r,s,o)=>o.toUpperCase());return i.charAt(0).toLowerCase()+i.slice(1)}return e==="F"?"CustomFunctions":e==="C"?t.endsWith(".dart")?t:`${t}.dart`:n}async function Cu(t){const e=new TextEncoder().encode(String(t||"")),n=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n),i=>i.toString(16).padStart(2,"0")).join("")}async function kv(t,e=new Map){const n={},i=new Set;for(const[o,a]of t.entries()){if(a.type==="D"||a.type==="O")continue;const l=_l(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await Cu(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await Cu(c)),n[o]=u,a.type==="F"){const d=ku(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(h=>i.add(h))}}const r=new Set(ku(e.get("lib/flutter_flow/custom_functions.dart")||"")),s={functions_to_rename:[],functions_to_delete:[],functions_to_add:Array.from(i).filter(o=>!r.has(o))};return{fileMapContents:JSON.stringify(n),functionsMapContents:JSON.stringify(s)}}const Cv=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),Au={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},Av=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),Pv=["Struct","Record"],Fv=[{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=>Uo(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=>Uo(t).some(e=>{const n=/^\s*final\s+(?:double|int|String|bool|Color|num)\s+(\w+)\s*;/gm;let i;for(;(i=n.exec(e))!==null;){const r=i[1];if(!(new RegExp(`this\\.${r}\\s*=(?!=)`).test(e)||new RegExp(`[:,]\\s*${r}\\s*=(?!=)`).test(e)))return!0}return!1}),pos:`class W extends StatefulWidget { +(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const s of r)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function n(r){const s={};return r.integrity&&(s.integrity=r.integrity),r.referrerPolicy&&(s.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?s.credentials="include":r.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function i(r){if(r.ep)return;r.ep=!0;const s=n(r);fetch(r.href,s)}})();var w=typeof window<"u"?window:void 0,Ne=typeof globalThis<"u"?globalThis:w,He=Ne?.navigator,P=Ne?.document,me=Ne?.location,Xa=Ne?.fetch,zo=Ne!=null&&Ne.XMLHttpRequest&&"withCredentials"in new Ne.XMLHttpRequest?Ne.XMLHttpRequest:void 0,fc=Ne?.AbortController,Np=Ne?.CompressionStream,Ge=He?.userAgent;function hd(){return!(!w||w.navigator.onLine===!1)}var vi=typeof globalThis<"u"?globalThis:w;vi&&typeof self>"u"&&(vi.self=vi),vi&&typeof File>"u"&&(vi.File=function(){});var B=w??{},ne={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function hc(t,e,n,i,r,s,o){try{var a=t[s](o),l=a.value}catch(u){return void n(u)}a.done?e(l):Promise.resolve(l).then(i,r)}function se(t){return function(){var e=this,n=arguments;return new Promise((function(i,r){var s=t.apply(e,n);function o(l){hc(s,i,r,o,a,"next",l)}function a(l){hc(s,i,r,o,a,"throw",l)}o(void 0)}))}}function I(){return I=Object.assign?Object.assign.bind():function(t){for(var e=1;arguments.length>e;e++){var n=arguments[e];for(var i in n)({}).hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},I.apply(null,arguments)}function pd(t,e){if(t==null)return{};var n={};for(var i in t)if({}.hasOwnProperty.call(t,i)){if(e.indexOf(i)!==-1)continue;n[i]=t[i]}return n}var pc=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function gc(t){return typeof t=="string"||t}function mc(t){return typeof t=="string"?t:void 0}var _i,Op=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],Ut=(function(t){return t.AnonymousId="anonymous_id",t.DistinctId="distinct_id",t.Props="props",t.EnablePersonProcessing="enable_person_processing",t.PersonMode="person_mode",t.FeatureFlagDetails="feature_flag_details",t.FeatureFlags="feature_flags",t.FeatureFlagPayloads="feature_flag_payloads",t.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",t.BootstrapFeatureFlags="bootstrap_feature_flags",t.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",t.OverrideFeatureFlags="override_feature_flags",t.Queue="queue",t.AiQueue="ai_queue",t.LogsQueue="logs_queue",t.OptedOut="opted_out",t.SessionId="session_id",t.SessionStartTimestamp="session_start_timestamp",t.SessionLastTimestamp="session_timestamp",t.PersonProperties="person_properties",t.GroupProperties="group_properties",t.InstalledAppBuild="installed_app_build",t.InstalledAppVersion="installed_app_version",t.SessionReplay="session_replay",t.PushRegistered="push_registered",t.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",t.SurveyLastSeenDate="survey_last_seen_date",t.SurveysSeen="surveys_seen",t.Surveys="surveys",t.RemoteConfig="remote_config",t.FlagsEndpointWasHit="flags_endpoint_was_hit",t.DeviceId="device_id",t})({}),vc=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),Bp=["$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"],Dp=["token"],gd="NativeGzipValidationError",qo=t=>t.length>=2&&t[0]===31&&t[1]===139,_c=(t,e)=>t===vc.GZipJS||e===vc.GZipJS||e==="gzip",yc=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",pr=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=gd,e},jp=(function(){var t=se((function*(e,n){18>e.size&&pr("too-short");var i=new Uint8Array(yield e.slice(0,10).arrayBuffer());qo(i)&&i[2]===8||pr("invalid-header");var r=new DataView(yield e.slice(e.size-8).arrayBuffer());r.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(_i)return _i;_i=[];for(var c=0;256>c;c++){for(var d=c,f=0;8>f;f++)d=1&d?3988292384^d>>>1:d>>>1;_i[c]=d>>>0}return _i})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(n)&&pr("invalid-crc");var s=n.length>>>0;r.getUint32(4,!0)!==s&&pr("invalid-size")}));return function(e,n){return t.apply(this,arguments)}})();function Vo(){return Vo=se((function*(t,e,n){e===void 0&&(e=!0);try{var i=new TextEncoder().encode(t),r=new globalThis.CompressionStream("gzip"),s=r.writable.getWriter(),o=s.write(i).then((()=>s.close())).catch((function(){var u=se((function*(c){try{yield s.abort(c)}catch{}throw c}));return function(c){return u.apply(this,arguments)}})()),a=new Response(r.readable).blob(),l=(yield Promise.all([a,o]))[0];return yield jp(l,i),l}catch(u){if(n!=null&&n.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),Vo.apply(this,arguments)}var Up=["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"],wc=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var n=t.toLowerCase();return Up.concat(e).some((i=>{var r=i.toLowerCase();return n.indexOf(r)!==-1}))};function j(t,e){return t.indexOf(e)!==-1}var xs=function(t){return t.trim()},Go=function(t){return t.replace(/^\$/,"")};function md(t){var e,n=[];return(e=JSON.stringify(t,(function(i,r){if(typeof r=="bigint")return r.toString();if(typeof r!="function"&&typeof r!="symbol"){if(r instanceof Error)return{name:r.name,message:r.message,stack:r.stack};if(r&&typeof r=="object"){for(;n.length>0&&n[n.length-1]!==this;)n.pop();if(n.includes(r))return"[Circular]";n.push(r)}return r}})))!==null&&e!==void 0?e:"null"}var vd=Object.prototype,_d=vd.hasOwnProperty,Is=vd.toString,U=Array.isArray||function(t){return Is.call(t)==="[object Array]"},je=t=>typeof t=="function",he=t=>t===Object(t)&&!U(t),Kt=t=>{if(he(t)){for(var e in t)if(_d.call(t,e))return!1;return!0}return!1},C=t=>t===void 0,X=t=>Is.call(t)=="[object String]",Ko=t=>X(t)&&t.trim().length===0,Ye=t=>t===null,H=t=>C(t)||Ye(t),ke=t=>Is.call(t)=="[object Number]"&&t==t,Dt=t=>ke(t)&&t>0,mt=t=>Is.call(t)==="[object Boolean]",Hp=t=>t instanceof FormData,Wp=t=>j(Bp,t),zp=t=>j(Dp,t);function yd(t){return t===null||typeof t!="object"}function Hr(t,e){return{}.toString.call(t)==="[object "+e+"]"}function Qa(t){return typeof Event<"u"&&wd(t,Event)}function wd(t,e){try{return t instanceof e}catch{return!1}}var qp=[!0,"true",1,"1","yes"],uo=t=>j(qp,t),Vp=[!1,"false",0,"0","no"];function At(t,e,n,i,r){return e>n&&(i.warn("min cannot be greater than max."),e=n),ke(t)?t>n?(i.warn(" cannot be greater than max: "+n+". Using max value instead."),n):e>t?(i.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(i.warn(" must be a number. using max or fallback. max: "+n+", fallback: "+r),At(r||n,e,n,i))}class Gp{constructor(e){this.tt={},this.et=e.et,this.it=At(e.bucketSize,0,100,e.rt),this.nt=At(e.refillRate,0,this.it,e.rt),this.st=At(e.refillInterval,0,864e5,e.rt)}ot(e,n){var i=Math.floor((n-e.lastAccess)/this.st);i>0&&(e.tokens=Math.min(e.tokens+i*this.nt,this.it),e.lastAccess=e.lastAccess+i*this.st)}consumeRateLimit(e){var n,i=Date.now(),r=String(e),s=this.tt[r];return s?this.ot(s,i):this.tt[r]=s={tokens:this.it,lastAccess:i},s.tokens===0||(s.tokens--,s.tokens===0&&((n=this.et)==null||n.call(this,e)),s.tokens===0)}stop(){this.tt={}}}var rt="Mobile",Wr="iOS",Yt="Android",ei="Tablet",bd=Yt+" "+ei,Ed="iPad",Sd="Apple",xd=Sd+" Watch",Bi="Safari",ti="BlackBerry",Id="Samsung",kd=Id+"Browser",Cd=Id+" Internet",Pn="Chrome",Kp=Pn+" OS",Ad=Pn+" "+Wr,el="Internet Explorer",Pd=el+" "+rt,tl="Opera",Yp=tl+" Mini",nl="Edge",Fd="Microsoft "+nl,Zn="Firefox",Rd=Zn+" "+Wr,Gi="Nintendo",Ki="PlayStation",Xn="Xbox",Td=Yt+" "+rt,$d=rt+" "+Bi,Pi="Windows",Yo=Pi+" Phone",bc="Nokia",Jo="Ouya",Md="Generic",Jp=Md+" "+rt.toLowerCase(),Ld=Md+" "+ei.toLowerCase(),Zo="Konqueror",Nd="Oculus Browser",zr="Vivaldi",Od="Yandex",qr="Whale",Xo="DuckDuckGo",Bd="Pale Moon",Vr="Waterfox",Di="Brave",Dd="Google Search App",we="(\\d+(\\.\\d+)?)",fo=new RegExp("Version/"+we),Zp=new RegExp(Xn,"i"),Xp=new RegExp(Ki+" \\w+","i"),Qp=new RegExp(Gi+" \\w+","i"),il=new RegExp(ti+"|PlayBook|BB10","i"),eg={"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"},jd=function(t,e,n,i){e=e||"";var r=(function(s){return s!=null&&s.brave?Di:null})(n);return r||(i!=null&&i.detectGoogleSearchApp&&j(t,"GSA/")?Dd:j(t," OPR/")&&j(t,"Mini")?Yp:j(t," OPR/")?tl:il.test(t)?ti:j(t,"IE"+rt)||j(t,"WPDesktop")?Pd:j(t,"OculusBrowser")?Nd:j(t,kd)?Cd:j(t,nl)||j(t,"Edg/")?Fd:j(t,zr+"/")?zr:j(t,"YaBrowser/")?Od:j(t,qr+"/")?qr:j(t,Xo+"/")||j(t,"Ddg/")?Xo:j(t,"FBIOS")?"Facebook "+rt:j(t,"UCWEB")||j(t,"UCBrowser")?"UC Browser":j(t,"CriOS")?Ad:j(t,"CrMo")||j(t,Pn)?Pn:j(t,Yt)&&j(t,Bi)?Td:j(t,"FxiOS")?Rd:j(t.toLowerCase(),Zo.toLowerCase())?Zo:j(t,Di+"/")?Di:((s,o)=>o&&j(o,Sd)||(function(a){return j(a,Bi)&&!j(a,Pn)&&!j(a,Yt)})(s))(t,e)?j(t,rt)?$d:Bi:j(t,"PaleMoon/")?Bd:j(t,Vr+"/")?Vr:j(t,Zn)?Zn:j(t,"MSIE")||j(t,"Trident/")?el:j(t,"Gecko")?Zn:"")},tg={[Pd]:[new RegExp("rv:"+we)],[Fd]:[new RegExp(nl+"?\\/"+we)],[Pn]:[new RegExp("("+Pn+"|CrMo)\\/"+we)],[Ad]:[new RegExp("CriOS\\/"+we)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+we)],[Bi]:[fo],[$d]:[fo],[tl]:[new RegExp("(Opera|OPR)\\/"+we)],[Zn]:[new RegExp(Zn+"\\/"+we)],[Rd]:[new RegExp("FxiOS\\/"+we)],[Zo]:[new RegExp("Konqueror[:/]?"+we,"i")],[ti]:[new RegExp(ti+" "+we),fo],[Td]:[new RegExp("android\\s"+we,"i")],[Cd]:[new RegExp(kd+"\\/"+we)],[Nd]:[new RegExp("OculusBrowser\\/"+we)],[zr]:[new RegExp(zr+"\\/"+we)],[Od]:[new RegExp("YaBrowser\\/"+we)],[qr]:[new RegExp(qr+"\\/"+we)],[Di]:[new RegExp(Di+"\\/"+we)],[Xo]:[new RegExp("(DuckDuckGo|Ddg)\\/"+we)],[Bd]:[new RegExp("PaleMoon\\/"+we)],[Vr]:[new RegExp(Vr+"\\/"+we)],[Dd]:[new RegExp("GSA\\/"+we)],[el]:[new RegExp("(rv:|MSIE )"+we)],Mozilla:[new RegExp("rv:"+we)]},ng=function(t,e,n,i){var r=jd(t,e,n,i),s=tg[r];if(C(s))return null;for(var o=0;s.length>o;o++){var a=t.match(s[o]);if(a)return parseFloat(a[a.length-2])}return null},Ec=[[new RegExp(Xn+"; "+Xn+" (.*?)[);]","i"),t=>[Xn,t&&t[1]||""]],[new RegExp(Gi,"i"),[Gi,""]],[new RegExp(Ki,"i"),[Ki,""]],[il,[ti,""]],[new RegExp(Pi,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Yo,""];if(new RegExp(rt).test(e)&&!/IEMobile\b/.test(e))return[Pi+" "+rt,""];var n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){var i=eg[n[1]]||"";return/arm/i.test(e)&&(i="RT"),[Pi,i]}return[Pi,""]}],[/((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=C(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+Yt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Yt+")","i"),t=>t&&t[2]?[Yt,[t[2],t[3],t[4]||"0"].join(".")]:[Yt,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{var e=["Mac OS X",""];return t&&t[1]&&(e[1]=[t[1],t[2],t[3]||"0"].join(".")),e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[Kp,""]],[/Linux|debian/i,["Linux",""]]],Sc=function(t){return Qp.test(t)?Gi:Xp.test(t)?Ki:Zp.test(t)?Xn:new RegExp(Jo,"i").test(t)?Jo:new RegExp("("+Yo+"|WPDesktop)","i").test(t)?Yo:/iPad/.test(t)?Ed:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?xd:il.test(t)?ti:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(bc,"i").test(t)?bc:/(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(rt).test(t)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(t)||/pixel[\daxl ]{1,6}/i.test(t)&&!/pixel c/i.test(t)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(t)||/lmy47v/i.test(t)&&!/QTAQZ3/i.test(t)?Yt:bd:new RegExp("(pda|"+rt+")","i").test(t)?Jp:new RegExp(ei,"i").test(t)&&!new RegExp(ei+" pc","i").test(t)?Ld:""},ig=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function xc(t,e){return typeof(n=t)=="string"&&ig.test(n)?t:e();var n}function fn(t){return t&&t.split("#")[0]}function rl(t,e){var n=setTimeout(t,e);return n?.unref&&n?.unref(),n}function Ic(t,e,n){return Ud.apply(this,arguments)}function Ud(){return(Ud=se((function*(t,e,n){var i;try{return yield Promise.race([t,new Promise(((r,s)=>{i=rl((()=>{try{n?.(),r()}catch(o){s(o)}}),e)}))])}finally{clearTimeout(i)}}))).apply(this,arguments)}var rg=t=>t instanceof Error,Hd={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}},sg=Hd.info;function Wd(t){if(mt(t))return{boolValue:t};if(typeof t=="number")return Number.isFinite(t)?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:{stringValue:String(t)};if(typeof t=="string")return{stringValue:t};if(U(t))return{arrayValue:{values:t.map((e=>Wd(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function Gr(t){var e=[];for(var n in t){var i=t[n];Ye(i)||C(i)||e.push({key:n,value:Wd(i)})}return e}function og(t,e){var n=Hd[t.level||"info"]||sg,i=n.text,r=n.number,s=String(Date.now())+"000000",o={};e.distinctId&&(o.posthogDistinctId=e.distinctId),e.sessionId&&(o.sessionId=e.sessionId),e.windowId&&(o["window.id"]=e.windowId),H(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),H(e.lastActivityTimestamp)||(o.lastActivityTimestamp=String(e.lastActivityTimestamp)),e.currentUrl&&(o["url.full"]=e.currentUrl),e.screenName&&(o["screen.name"]=e.screenName),e.appState&&(o["app.state"]=e.appState),e.activeFeatureFlags&&e.activeFeatureFlags.length>0&&(o.feature_flags=e.activeFeatureFlags);var a=I({},o,t.attributes||{}),l={timeUnixNano:s,observedTimeUnixNano:s,severityNumber:r,severityText:i,body:{stringValue:t.body},attributes:Gr(a)};return t.trace_id&&(l.traceId=t.trace_id),t.span_id&&(l.spanId=t.span_id),C(t.trace_flags)||(l.flags=t.trace_flags),l}function zd(t,e,n){return I({},t.resourceAttributes,{"service.name":t.serviceName||"unknown_service"},t.environment&&{"deployment.environment":t.environment},t.serviceVersion&&{"service.version":t.serviceVersion},{"telemetry.sdk.name":e,"telemetry.sdk.version":n})}function qd(t,e,n,i){return{resourceLogs:[{resource:{attributes:Gr(e)},scopeLogs:[{scope:{name:n,version:i},logRecords:t}]}]}}let ag=class{constructor(t,e,n,i,r,s,o){var a;s===void 0&&(s=()=>Promise.resolve()),this._instance=t,this.Ne=e,this.rt=n,this.ut=i,this.ht=r,this.dt=s,this.vt=o,this.ct=null,this.ft=0,this.yt=0,this.bt=0,this._t=0,this.wt=!1,this.kt=e.maxBufferSize,this.xt=Math.max((a=e.maxQueueSize)!==null&&a!==void 0?a:e.maxBufferSize,e.maxBufferSize),this.St=e.flushIntervalMs,this.Ct=e.maxBatchRecordsPerPost,this.Mt=e.rateCapWindowMs,this.Tt=e.maxLogsPerInterval}reset(){this.Et(),this.ct=null,this.bt=0,this._t=0,this.wt=!1,this.ft=0,this.yt=0,this.Ct=this.Ne.maxBatchRecordsPerPost}onReconnect(){this.yt=0,this.It()}captureLog(t){if(!this._instance.isDisabled&&!this._instance.optedOut&&t!=null&&t.body){var e=this.Pt(t);if(e!==null)if(e.body){if(this.Rt()){var n={record:og(e,this.ut())};this.ht((()=>this.At(n)))}}else this.rt.info("Log was rejected in beforeSend function")}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Log was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for log:",o),null}return i}Rt(){if(this.Tt===void 0)return!0;var t=Date.now(),e=t-this.bt;return this.Mt>e&&e>=0||(this.bt=t,this._t=0,this.wt=!1),this.Tt>this._t?(this._t++,!0):(this.wt||(this.rt.warn("captureLog dropping logs: exceeded "+this.Tt+" logs per "+this.Mt+"ms"),this.wt=!0),!1)}flush(){var t=this;return se((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return se((function*(){var e;t.Et();var n=(e=t._instance.getPersistedProperty(Ut.LogsQueue))!==null&&e!==void 0?e:[];if(n.length!==0)for(var i=n.length,r=0;n.length>0&&i>r;){var s,o;t.ft=0;var a=Math.min(n.length,t.Ct),l=n.slice(0,a),u=qd(l.map((d=>d.record)),t.Lt(),(s=t.vt)!==null&&s!==void 0?s:t._instance.getLibraryId(),t._instance.getLibraryVersion()),c=yield t._instance.Ot(u);if(c.kind==="too-large"&&l.length>1)t.Ct=Math.max(1,Math.floor(l.length/2)),t.rt.warn("Received 413 when sending logs batch of size "+l.length+", reducing batch size to "+t.Ct);else if(c.kind==="retry-later"||(c.kind==="too-large"?t.rt.warn("Dropping a single log record after 413 with batch size 1 — the record is larger than the server cap and cannot be split further."):c.kind==="ok"&&t.Ne.maxBatchRecordsPerPost>t.Ct&&(t.Ct=Math.min(t.Ne.maxBatchRecordsPerPost,t.Ct+1)),yield t.Dt(l.length),n=(o=t._instance.getPersistedProperty(Ut.LogsQueue))!==null&&o!==void 0?o:[],r+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return se((function*(){var n,i=Math.max(0,t-e.ft),r=(n=e._instance.getPersistedProperty(Ut.LogsQueue))!==null&&n!==void 0?n:[];e._instance.setPersistedProperty(Ut.LogsQueue,r.slice(i)),yield e.dt()}))()}Lt(){return zd(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var n=(e=this._instance.getPersistedProperty(Ut.LogsQueue))!==null&&e!==void 0?e:[];this.xt>n.length||(n.shift(),this.ft++,this.rt.info("Logs queue is full, dropping oldest record.")),n.push(t),this._instance.setPersistedProperty(Ut.LogsQueue,n),this.kt>n.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=rl((()=>{this.Nt=void 0,this.It()}),t))}qt(){var t=Math.min(Math.max(0,this.yt-1),6);return this.St*Math.pow(2,t)}jt(){var t=this._instance.getPersistedProperty(Ut.LogsQueue);return!!t&&t.length>0}shutdown(t){var e=this;return se((function*(){e.Et();var n=e.flush().catch((()=>{}));t!==void 0?yield Ic(n,t):yield n}))()}flushWithTimeout(t){var e=this;return se((function*(){var n=e.flush();yield Ic(n,t,(()=>{n.catch((()=>{}))}))}))()}It(){this.flush().then((()=>{this.yt=0}),(t=>{this.yt++,this.rt.error("PostHog logs flush failed:",t)})).finally((()=>{!this._instance.isDisabled&&this.jt()&&this.$t(this.qt())}))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}};var ho=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function kc(t){return String(t)+"000000"}function Cc(t,e,n,i){var r="";return i&&(r=Object.keys(i).sort().map((s=>JSON.stringify(s)+":"+JSON.stringify(i[s]))).join(",")),t+"\0"+e+"\0"+(n??"")+"\0"+r}let lg=class{constructor(t,e,n){this._instance=t,this.Ne=e,this.rt=n,this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Wt=0}count(t,e,n){e===void 0&&(e=1),this.Vt({name:t,type:"count",value:e,unit:n?.unit,attributes:n?.attributes})}gauge(t,e,n){this.Vt({name:t,type:"gauge",value:e,unit:n?.unit,attributes:n?.attributes})}histogram(t,e,n){this.Vt({name:t,type:"histogram",value:e,unit:n?.unit,attributes:n?.attributes})}flush(){var t=this,e=this.ct,n=(function(){var r=se((function*(){e&&(yield e.catch((()=>{}))),yield t.Zt()}));return function(){return r.apply(this,arguments)}})(),i=n().finally((()=>{this.ct===i&&(this.ct=null)}));return this.ct=i,i}drainWindow(){if(this.Bt.size===0)return null;var t=this.Bt;return this.Bt=new Map,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Gt(t)}reset(){this.Wt++,this.Et(),this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set}Vt(t){if(!this._instance.isDisabled&&!this._instance.optedOut){var e=this.Pt(t);if(e!==null)if(e.name&&typeof e.name=="string")if(typeof e.value=="number"&&Number.isFinite(e.value))if(e.type==="count"&&0>e.value)this.rt.warn("Dropping count '"+e.name+"': counters are monotonic, value must be >= 0");else{var n,i;try{n=e.attributes?I({},e.attributes):void 0,i=Cc(e.type,e.name,e.unit,n)}catch(o){return void this.rt.warn("Dropping metric '"+e.name+"': attributes could not be serialized",o)}var r=this.Bt.get(i);if(!r){if(!this.Qt())return;r={name:e.name,type:e.type,unit:e.unit,attributes:n,windowStartMs:Date.now()},this.Bt.set(i,r)}var s=this.Ut.get(e.name);s===void 0?this.Ut.set(e.name,e.type):s===e.type||this.zt.has(e.name)||(this.zt.add(e.name),this.rt.warn("Metric name '"+e.name+"' is already used as a "+s+"; recording it as a "+e.type+" too will blend both series in charts. Use a distinct name.")),this.Kt(r,e.value),this.$t()}else this.rt.warn("Dropping metric '"+e.name+"': value must be a finite number");else this.rt.warn("Dropping metric with empty name")}}Qt(){return this.Ne.maxSeriesPerFlush>this.Bt.size||(this.Ht||(this.Ht=!0,this.rt.warn("Metric series cap reached ("+this.Ne.maxSeriesPerFlush+" per flush window); dropping new series until the next flush. Reduce attribute cardinality.")),!1)}Kt(t,e){var n;switch(t.type){case"count":t.total=((n=t.total)!==null&&n!==void 0?n:0)+e;break;case"gauge":t.last=e;break;case"histogram":t.hist||(t.hist={count:0,sum:0,min:e,max:e,bucketCounts:new Array(ho.length+1).fill(0)});var i=t.hist;i.count+=1,i.sum+=e,i.min=Math.min(i.min,e),i.max=Math.max(i.max,e),i.bucketCounts[(function(r,s){for(var o=0;s.length>o;o++)if(s[o]>=r)return o;return s.length})(e,ho)]+=1}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Metric was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for metric:",o),null}return i}$t(){this.Nt||(this.Nt=rl((()=>{this.Nt=void 0,this.flush().catch((t=>{this.rt.error("Metrics flush failed:",t)}))}),this.Ne.flushIntervalMs))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}Zt(){var t=this;return se((function*(){if(t.Bt.size!==0){var e=t.Bt;t.Bt=new Map,t.Ht=!1,t.Ut=new Map,t.zt=new Set;var n=t.Wt,i=yield t._instance.Jt(t.Gt(e));if(n===t.Wt)switch(i.kind){case"ok":return;case"retry-later":return t.Yt(e),void t.$t();case"too-large":return void t.rt.warn("Metrics batch exceeded the server size limit and was dropped");case"fatal":return void t.rt.error("Failed to send metrics batch:",i.error)}}}))()}Gt(t){return e=this.Xt(t),n=(function(s,o,a){return I({},s.resourceAttributes,{"service.name":s.serviceName||"unknown_service"},s.environment&&{"deployment.environment":s.environment},s.serviceVersion&&{"service.version":s.serviceVersion},{"telemetry.sdk.name":o,"telemetry.sdk.version":a})})(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion()),i=this._instance.getLibraryId(),r=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:Gr(n)},scopeMetrics:[{scope:{name:i,version:r},metrics:e}]}]};var e,n,i,r}Xt(t){var e=kc(Date.now()),n=new Map;for(var i of t.values()){var r,s=Cc(i.type,i.name,i.unit,void 0),o=n.get(s);o||(o=I({name:i.name},i.unit&&{unit:i.unit}),i.type==="count"?o.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:i.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:1,dataPoints:[]},n.set(s,o));var a=Gr((r=i.attributes)!==null&&r!==void 0?r:{}),l=kc(i.windowStartMs);if(i.type==="count"){var u,c={attributes:a,startTimeUnixNano:l,timeUnixNano:e,asDouble:(u=i.total)!==null&&u!==void 0?u:0};o.sum.dataPoints.push(c)}else if(i.type==="gauge"){var d,f={attributes:a,timeUnixNano:e,asDouble:(d=i.last)!==null&&d!==void 0?d:0};o.gauge.dataPoints.push(f)}else i.hist&&o.histogram.dataPoints.push({attributes:a,startTimeUnixNano:l,timeUnixNano:e,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:ho})}return Array.from(n.values())}Yt(t){var e,n;for(var i of t){var r=i[0],s=i[1],o=this.Bt.get(r);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,s.windowStartMs),o.type){case"count":o.total=((e=o.total)!==null&&e!==void 0?e:0)+((n=s.total)!==null&&n!==void 0?n:0);break;case"gauge":break;case"histogram":if(s.hist)if(o.hist){o.hist.count+=s.hist.count,o.hist.sum+=s.hist.sum,o.hist.min=Math.min(o.hist.min,s.hist.min),o.hist.max=Math.max(o.hist.max,s.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=s.hist.bucketCounts[a]}else o.hist=s.hist}else this.Qt()&&this.Bt.set(r,s)}}};var gr,Ac,po;function cg(t){var e=globalThis._posthogChunkIds;if(e){var n=Object.keys(e);return po&&n.length===Ac||(Ac=n.length,po=n.reduce(((i,r)=>{gr||(gr={});var s=gr[r];if(s)i[s[0]]=s[1];else for(var o=t(r),a=o.length-1;a>=0;a--){var l=o[a],u=l?.filename,c=e[r];if(u&&c){i[u]=c,gr[r]=[u,c];break}}return i}),{})),po}}class ug{constructor(e,n,i){i===void 0&&(i=[]),this.coercers=e,this.stackParser=n,this.modifiers=i}buildFromUnknown(e,n){n===void 0&&(n={});var i=n&&n.mechanism||{handled:!0,type:"generic"},r=this.buildCoercingContext(i,n,0).apply(e),s=this.buildParsingContext(n),o=this.parseStacktrace(r,s);return{$exception_list:this.convertToExceptionList(o,i),$exception_level:"error"}}modifyFrames(e){var n=this;return se((function*(){for(var i of e)i.stacktrace&&i.stacktrace.frames&&U(i.stacktrace.frames)&&(i.stacktrace.frames=yield n.applyModifiers(i.stacktrace.frames));return e}))()}coerceFallback(e){var n;return{type:"Error",value:"Unknown error",stack:(n=e.syntheticException)==null?void 0:n.stack,synthetic:!0}}parseStacktrace(e,n){var i,r;return e.cause!=null&&(i=this.parseStacktrace(e.cause,n)),e.stack!=""&&e.stack!=null&&(r=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?n.skipFirstLines:0),n.chunkIdMap)),I({},e,{cause:i,stack:r})}applyChunkIds(e,n){return e.map((i=>(i.filename&&n&&(i.chunk_id=n[i.filename]),i)))}applyCoercers(e,n){for(var i of this.coercers)if(i.match(e))return i.coerce(e,n);return this.coerceFallback(n)}applyModifiers(e){var n=this;return se((function*(){var i=e;for(var r of n.modifiers)i=yield r(i);return i}))()}convertToExceptionList(e,n){var i,r,s,o={type:e.type,value:e.value,mechanism:{type:(i=n.type)!==null&&i!==void 0?i:"generic",handled:(r=n.handled)===null||r===void 0||r,synthetic:(s=e.synthetic)!==null&&s!==void 0&&s}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,I({},n,{handled:!0}))),a}buildParsingContext(e){var n;return{chunkIdMap:cg(this.stackParser),skipFirstLines:(n=e.skipFirstLines)!==null&&n!==void 0?n:1}}buildCoercingContext(e,n,i){i===void 0&&(i=0);var r=(s,o)=>{if(4>=o){var a=this.buildCoercingContext(e,n,o);return this.applyCoercers(s,a)}};return I({},n,{syntheticException:i==0?n.syntheticException:void 0,mechanism:e,apply:s=>r(s,i),next:s=>r(s,i+1)})}}var ni="?";function Qo(t,e,n,i,r){var s={platform:t,filename:e,function:n===""?ni:n,in_app:!0};return C(i)||(s.lineno=i),C(r)||(s.colno=r),s}var Vd=(t,e)=>{var n=t.indexOf("safari-extension")!==-1,i=t.indexOf("safari-web-extension")!==-1;return n||i?[t.indexOf("@")!==-1?t.split("@")[0]:ni,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},dg=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,fg=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,hg=/\((\S*)(?::(\d+))(?::(\d+))\)/,pg=(t,e)=>{var n=dg.exec(t);if(n)return Qo(e,n[1],ni,+n[2],+n[3]);var i=fg.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var r=hg.exec(i[2]);r&&(i[2]=r[1],i[3]=r[2],i[4]=r[3])}var s=Vd(i[1]||ni,i[2]);return Qo(e,s[1],s[0],i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},gg=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,mg=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,vg=(t,e)=>{var n=gg.exec(t);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){var i=mg.exec(n[3]);i&&(n[1]=n[1]||"eval",n[3]=i[1],n[4]=i[2],n[5]="")}var r=n[3],s=n[1]||ni,o=Vd(s,r);return Qo(e,r=o[1],s=o[0],n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},Pc=/\(error: (.*)\)/;class _g{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,n){var i=X(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:i?e.stack:void 0,cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var n=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?n+": "+e.message:n}isDOMException(e){return Hr(e,"DOMException")}isDOMError(e){return Hr(e,"DOMError")}}class yg{match(e){return(function(n){switch({}.toString.call(n)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return wd(n,Error)}})(e)}coerce(e,n){return{type:this.getType(e),value:this.getMessage(e,n),stack:this.getStack(e),cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,n){var i=e.message;return String(i.error&&typeof i.error.message=="string"?i.error.message:i)}getStack(e){return e.stacktrace||e.stack||void 0}}class wg{constructor(){}match(e){return!!Hr(e,"ErrorEvent")&&(e.error!=null||this.fe(e))}coerce(e,n){var i;if(e.error!=null)return n.apply(e.error);var r=n.apply(e.message);return I({},r,{stack:(i=this.pe(e))!==null&&i!==void 0?i:r.stack,synthetic:!0})}fe(e){return X(e.message)&&e.message.length>0}pe(e){var n=e;if(X(n.filename)&&n.filename.length>0){var i,r,s=(i=n.lineno)!==null&&i!==void 0?i:0,o=(r=n.colno)!==null&&r!==void 0?r:0;return`Error + at `+n.filename+":"+s+":"+o}}}var bg=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class Eg{match(e){return typeof e=="string"}coerce(e,n){var i,r=this.getInfos(e),s=r[0],o=r[1];return{type:s??"Error",value:o??e,stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}getInfos(e){var n="Error",i=e,r=e.match(bg);return r&&(n=r[1],i=r[2]),[n,i]}}var Sg=["fatal","error","warning","log","info","debug"];function Gd(t,e){e===void 0&&(e=40);var n=Object.keys(t);if(n.sort(),!n.length)return"[object has no keys]";for(var i=n.length;i>0;i--){var r=n.slice(0,i).join(", ");if(e>=r.length)return i===n.length?r:r.length>e?r.slice(0,e)+"...":r}return""}class xg{match(e){return typeof e=="object"&&e!==null}coerce(e,n){var i,r,s=this.getErrorPropertyFromObject(e);return s?n.apply(s):{type:this.getType(e),value:this.getValue(e),stack:(i=this.getStack(e))!==null&&i!==void 0?i:(r=n.syntheticException)==null?void 0:r.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return Qa(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var n="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(n+=" with message: '"+e.message+"'"),n}if("message"in e&&typeof e.message=="string")return e.message;var i=this.getObjectClassName(e);return(i&&i!=="Object"?"'"+i+"'":"Object")+" captured as exception with keys: "+Gd(e)}isSeverityLevel(e){return X(e)&&!Ko(e)&&Sg.indexOf(e)>=0}getStack(e){try{return X(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:X(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(var n in e)if({}.hasOwnProperty.call(e,n)){var i=e[n];if(rg(i))return i}}getObjectClassName(e){try{var n=Object.getPrototypeOf(e);return n?n.constructor.name:void 0}catch{return}}}class Ig{match(e){return Qa(e)}coerce(e,n){var i,r=e.constructor.name;return{type:r,value:r+" captured as exception with keys: "+Gd(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class kg{match(e){return yd(e)}coerce(e,n){var i;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class Cg{match(e){return Hr(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Qa(e))return!1;try{var n=e.detail;return n!=null&&typeof n=="object"&&"reason"in n}catch{return!1}}coerce(e,n){var i,r=this.getUnhandledRejectionReason(e);return yd(r)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(r),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}:n.apply(r)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}}var Kr="$message",Yr="$timestamp",Ag=new Set([Kr,Yr]),go={enabled:!0,max_bytes:32768};function Jr(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:go.enabled,max_bytes:Fg(t.max_bytes,go.max_bytes)}:I({},go)}class Pg{constructor(e){this.Ke=[],this.Je=0,this.Ne=Jr(e)}setConfig(e){this.Ne=Jr(e),this.Xe()}add(e){var n=(function(r){var s;try{s=md(r)}catch{return}try{var o=JSON.parse(s);if(!he(o))return;var a=o,l=a[Kr],u=a[Yr];return!X(l)||l.trim().length===0||!X(u)&&!ke(u)?void 0:{step:a,json:s}}catch{return}})(e);if(n){var i=(function(r){if(typeof TextEncoder<"u")return new TextEncoder().encode(r).length;for(var s=encodeURIComponent(r),o=0,a=0;s.length>a;a++)s[a]==="%"?(o+=1,a+=2):o+=1;return o})(n.json);i>this.Ne.max_bytes||(this.Ke.push({step:n.step,bytes:i}),this.Je+=i,this.Xe())}}getAttachable(){return this.Ke.map((e=>e.step))}clear(){this.Ke=[],this.Je=0}size(){return this.Ke.length}Xe(){for(;this.Je>this.Ne.max_bytes&&this.Ke.length>0;){var e=this.Ke.shift();e&&(this.Je-=e.bytes)}}}function Fg(t,e){if(!ke(t)||t===1/0||t===-1/0)return e;var n=Math.floor(t);return 0>n?e:n}var Kd=function(t,e){var n=(e===void 0?{}:e).debugEnabled,i={k(r){if(w&&(ne.DEBUG||w.POSTHOG_DEBUG||n)&&!C(w.console)&&w.console){for(var s=("__rrweb_original__"in w.console[r])?w.console[r].__rrweb_original__:w.console[r],o=arguments.length,a=new Array(o>1?o-1:0),l=1;o>l;l++)a[l-1]=arguments[l];s(t,...a)}},debug(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("debug",...s)},info(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("log",...s)},warn(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("warn",...s)},error(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("error",...s)},critical(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];console.error(t,...s)},uninitializedWarning(r){i.error("You must initialize PostHog before calling "+r)},createLogger:(r,s)=>Kd(t+" "+r,s)};return i},A=Kd("[PostHog.js]"),pe=A.createLogger,Rg=pe("[ExternalScriptsLoader]"),mo=(t,e,n)=>{if(t.config.disable_external_dependency_loading)return Rg.warn(e+" was requested but loading of external scripts is disabled."),n("Loading of external scripts is disabled");var i=P?.querySelectorAll("script");if(i){for(var r,s=function(){if(i[o].src===e){var l=i[o];return l.__posthog_loading_callback_fired?{v:n()}:(l.addEventListener("load",(u=>{l.__posthog_loading_callback_fired=!0,n(void 0,u)})),l.onerror=u=>n(u),{v:void 0})}},o=0;i.length>o;o++)if(r=s())return r.v}var a=()=>{if(!P)return n("document not found");var l=P.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=d=>{l.__posthog_loading_callback_fired=!0,n(void 0,d)},l.onerror=d=>n(d),t.config.prepare_external_dependency_script&&(l=t.config.prepare_external_dependency_script(l)),!l)return n("prepare_external_dependency_script returned null");if(t.config.external_scripts_inject_target==="head")P.head.appendChild(l);else{var u,c=P.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):P.body.appendChild(l)}};P!=null&&P.body?a():P?.addEventListener("DOMContentLoaded",a)};B.__PosthogExtensions__=B.__PosthogExtensions__||{},B.__PosthogExtensions__.loadExternalDependency=(t,e,n)=>{if(e!=="remote-config"){var i;if(t.config.strict_script_versioning)i=t.requestRouter.endpointFor("assets","/static/"+t.version+"/"+e+".js");else{var r="/static/"+e+".js?v="+t.version;if(e==="toolbar"){var s=3e5;r=r+"&t="+Math.floor(Date.now()/s)*s}i=t.requestRouter.endpointFor("assets",r)}mo(t,i,n)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");mo(t,o,n)}},B.__PosthogExtensions__.loadSiteApp=(t,e,n)=>{var i=t.requestRouter.endpointFor("api",e);mo(t,i,n)};ne.DEBUG=!1,ne.LIB_VERSION="1.415.7",ne.LIB_NAME="web";var Yd="$people_distinct_id",Yi="$device_id",vo="$device_model",Fi="__alias",Ri="__timers",ea="$autocapture_disabled_server_side",ta="$heatmaps_enabled_server_side",na="$exception_capture_enabled_server_side",ia="$error_tracking_suppression_rules",ra="$error_tracking_capture_extension_exceptions",sa="$web_vitals_enabled_server_side",sl="$dead_clicks_enabled_server_side",ol="$product_tours_enabled_server_side",oa="$web_vitals_allowed_metrics",An="$session_recording_remote_config",Jd="$replay_sample_rate",Zd="$replay_override_sampling",Xd="$replay_override_linked_flag",Qd="$replay_override_url_trigger",ef="$replay_override_event_trigger",Kn="$sesid",al="$session_is_sampled",Sn="$enabled_feature_flags",Ti="$active_feature_flags",Ar="$early_access_features",aa="$feature_flag_details",$i="$feature_flag_payloads",Pr="$feature_flag_request_id",Zr="$minimal_flag_called_events",It="$override_feature_flags",xn="$override_feature_flag_payloads",jt="$stored_person_properties",In="$stored_group_properties",la="$surveys",Xr="$surveys_loaded_at",ca="$surveys_activated",Fr="$surveys_activated_session",Rr="$surveys_activated_timestamps",Mi="ph_product_tours",Cn="$flag_call_reported",Li="$flag_call_reported_session_id",Tr="$feature_flag_errors",ji="$feature_flag_evaluated_at",at="$user_state",ua="$client_session_props",da="$capture_rate_limit",fa="$initial_campaign_params",ha="$initial_referrer_info",Qr="$initial_person_info",es="$epp",mr="$posthog_cookieless",tf="$cookieless_mode",nf="$sdk_debug_extensions_init_method",rf="$sdk_debug_extensions_init_time_ms",sf="$sdk_debug_recording_script_not_loaded",ll="PostHog loadExternalDependency extension not found.",kn="on_reject",Wt="always",Un="anonymous",vn="identified",pa="identified_only",ts="visibilitychange",ns="beforeunload",Vn="$pageview",_o="$pageleave",yo="$identify",Fc="$groupidentify";function vr(t,e){U(t)&&t.forEach(e)}function ie(t,e){if(!H(t))if(U(t))t.forEach(e);else if(Hp(t))t.forEach(((i,r)=>e(i,r)));else for(var n in t)_d.call(t,n)&&e(t[n],n)}var fe=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;e>i;i++)n[i-1]=arguments[i];for(var r of n)for(var s in r)r[s]!==void 0&&(t[s]=r[s]);return t};function $r(t){for(var e=Object.keys(t),n=e.length,i=new Array(n);n--;)i[n]=[e[n],t[e[n]]];return i}var Rc=function(t){try{return t()}catch{return}},Tg=function(t){return function(){try{for(var e=arguments.length,n=new Array(e),i=0;e>i;i++)n[i]=arguments[i];return t.apply(this,n)}catch(r){A.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),A.critical(r)}}},cl=function(t){var e={};return ie(t,(function(n,i){(X(n)&&n.length>0||ke(n))&&(e[i]=n)})),e},$g=["herokuapp.com","vercel.app","netlify.app"];function Mg(t){var e=t?.hostname;if(!X(e))return!1;var n=e.split(".").slice(-2).join(".");for(var i of $g)if(n===i)return!1;return!0}function ve(t,e,n,i){var r=i??{},s=r.capture,o=r.passive;t?.addEventListener(e,n,{capture:s!==void 0&&s,passive:o===void 0||o})}function ga(t){return t.name==="ph_toolbar_internal"}var of=t=>{if(P){try{for(var e=t+"=",n=P.cookie.split(";").filter((s=>s.length)),i=0;n.length>i;i++){for(var r=n[i];r.charAt(0)==" ";)r=r.substring(1,r.length);if(r.indexOf(e)===0)return decodeURIComponent(r.substring(e.length,r.length))}}catch{}return null}};Math.trunc||(Math.trunc=function(t){return 0>t?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return ke(t)&&isFinite(t)&&Math.floor(t)===t});class is{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,n,i,r){if(!Number.isInteger(e)||!Number.isInteger(n)||!Number.isInteger(i)||!Number.isInteger(r)||0>e||0>n||0>i||0>r||e>0xffffffffffff||n>4095||i>1073741823||r>4294967295)throw new RangeError("invalid field value");var s=new Uint8Array(16);return s[0]=e/Math.pow(2,40),s[1]=e/Math.pow(2,32),s[2]=e/Math.pow(2,24),s[3]=e/Math.pow(2,16),s[4]=e/256,s[5]=e,s[6]=112|n>>>8,s[7]=n,s[8]=128|i>>>24,s[9]=i>>>16,s[10]=i>>>8,s[11]=i,s[12]=r>>>24,s[13]=r>>>16,s[14]=r>>>8,s[15]=r,new is(s)}toString(){for(var e="",n=0;this.bytes.length>n;n++)e=e+(this.bytes[n]>>>4).toString(16)+(15&this.bytes[n]).toString(16),n!==3&&n!==5&&n!==7&&n!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new is(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var n=0;16>n;n++){var i=this.bytes[n]-e.bytes[n];if(i!==0)return Math.sign(i)}return 0}}class Lg{generate(){var e=this.generateOrAbort();if(!C(e))return e;this.S=0;var n=this.generateOrAbort();if(C(n))throw new Error("Could not generate UUID after timestamp reset");return n}generateOrAbort(){var e=Date.now();if(e>this.S)this.S=e,this.C();else{if(this.S>=e+1e4)return;this.I++,this.I>4398046511103&&(this.S++,this.C())}return is.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 Ng}}var Tc,af=t=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;t.length>e;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};w&&!C(w.crypto)&&crypto.getRandomValues&&(af=t=>crypto.getRandomValues(t));class Ng{nextUint32(){return this.R.length>this.O||(af(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var Ht=()=>Og().toString(),Og=()=>(Tc||(Tc=new Lg)).generate(),yi="",Bg=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,zt={N:()=>!!P,j(t){A.error("cookieStore error: "+t)},P:of,H(t){var e;try{e=JSON.parse(zt.P(t))||{}}catch{}return e},F(t,e,n,i,r){if(!P)return!1;try{var s="",o="",a=(function(c,d){if(d){var f=(function(p,g){if(g===void 0&&(g=P),yi)return yi;if(!g||["localhost","127.0.0.1"].includes(p))return"";for(var m=p.split("."),v=Math.min(m.length,8),E="dmn_chk_"+Ht();!yi&&v--;){var S=m.slice(v).join("."),_=E+"=1;domain=."+S+";path=/";g.cookie=_+";max-age=3",g.cookie.includes(E)&&(g.cookie=_+";max-age=0",yi=S)}return yi})(c);if(!f){var h=(p=>{var g=p.match(Bg);return g?g[0]:""})(c);h!==f&&A.info("Warning: cookie subdomain discovery mismatch",h,f),f=h}return f?"; domain=."+f:""}return""})(P.location.hostname,i);if(n){var l=new Date;l.setTime(l.getTime()+864e5*n),s="; expires="+l.toUTCString()}r&&(o="; secure");var u=t+"="+encodeURIComponent(JSON.stringify(e))+s+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&A.warn("cookieStore warning: large cookie, len="+u.length),P.cookie=u,!0}catch{return!1}},q(t,e){if(P!=null&&P.cookie)try{zt.F(t,"",-1,e)}catch{return}}},wo=null,le={N(){if(!Ye(wo))return wo;var t=!0;if(C(w))t=!1;else try{var e="__mplssupport__";le.F(e,"xyz"),le.P(e)!=='"xyz"'&&(t=!1),le.q(e)}catch{t=!1}return t||A.error("localStorage unsupported; falling back to cookie store"),wo=t,t},j(t){A.error("localStorage error: "+t)},P(t){try{return w?.localStorage.getItem(t)}catch(e){le.j(e)}return null},H(t){try{return JSON.parse(le.P(t))||{}}catch{}return null},F(t,e){try{return w?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(n){le.j(n)}return!1},q(t){try{w?.localStorage.removeItem(t)}catch(e){le.j(e)}}},Dg=[Yi,"distinct_id",Kn,al,es,Qr,at],_r={},jg={N:()=>!0,j(t){A.error("memoryStorage error: "+t)},P:t=>_r[t]||null,H:t=>_r[t]||null,F:(t,e)=>(_r[t]=e,!0),q(t){delete _r[t]}},_n=null,be={N(){if(!Ye(_n))return _n;if(_n=!0,C(w))_n=!1;else try{var t="__support__";be.F(t,"xyz"),be.P(t)!=='"xyz"'&&(_n=!1),be.q(t)}catch{_n=!1}return _n},j(t){A.error("sessionStorage error: ",t)},P(t){try{return w?.sessionStorage.getItem(t)}catch(e){be.j(e)}return null},H(t){try{return JSON.parse(be.P(t))||null}catch{}return null},F(t,e){try{return w?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(n){be.j(n)}return!1},q(t){try{w?.sessionStorage.removeItem(t)}catch(e){be.j(e)}}};class Ug{constructor(e){this._instance=e}get Ne(){return this._instance.config}get consent(){return this.ti()?0:this.ei}isOptedOut(){return this.Ne.cookieless_mode===Wt||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===kn}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===0}isRejected(){return this.consent===0||this.consent===-1&&this.Ne.opt_out_capturing_by_default}optInOut(e){this.ii.F(this.ri,e?1:0,this.Ne.cookie_expiration,this.Ne.cross_subdomain_cookie,this.Ne.secure_cookie)}reset(){this.ii.q(this.ri,this.Ne.cross_subdomain_cookie)}get ri(){var e=this._instance.config,n=e.token,i=e.opt_out_capturing_cookie_prefix;return e.consent_persistence_name||(i?i+n:"__ph_opt_in_out_"+n)}get ei(){var e=this.ii.P(this.ri);return uo(e)?1:j(Vp,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,n=e==="localStorage"?le:zt;if(!this.ni||this.ni!==n){this.ni=n;var i=e==="localStorage"?zt:le;i.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(uo(i.P(this.ri))),i.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[He?.doNotTrack,He?.msDoNotTrack,B.doNotTrack].some((e=>uo(e)))}}function lf(t,e){var n,i=t==null||(n=t.config)==null?void 0:n.get_current_url;if(!je(i))return e;try{var r=i(e);return X(r)&&r?r:e}catch(s){return A.error("Error in get_current_url, falling back to window.location.href",s),e}}var cf="__POSTHOG_TOOLBAR__",Hg=1,Wg=3,zg=11;function $c(t){return t instanceof Element&&(t.id===cf||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function hn(t){return!!t&&t.nodeType===Hg}function et(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function uf(t){return!!t&&t.nodeType===Wg}function df(t){return!!t&&t.nodeType===zg&&hn(t.host)}var ff=1e3;function ul(t){return t?xs(t).split(/\s+/):[]}function Mc(t,e){var n=(function(i){var r,s=w==null||(r=w.location)==null?void 0:r.href;return C(s)?void 0:lf(i,s)})(e);return!!(n&&t&&t.some((i=>n.match(i))))}function rs(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 ul(e)}function hf(t){return H(t)?null:xs(t).split(/(\s+)/).filter((e=>Ui(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function Ji(t){var e="";return va(t)&&!vf(t)&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;uf(n)&&n.textContent&&(e+=(i=hf(n.textContent))!==null&&i!==void 0?i:"")})),xs(e)}function bo(t){var e;return C(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var dl=["a","button","form","input","select","textarea","label"];function ma(t,e){if(C(e))return!0;var n,i=function(s){if(e.some((o=>(function(a,l){var u=a.matches||a.matchesSelector||a.msMatchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.oMatchesSelector;try{return!!u&&u.call(a,l)}catch{return!1}})(s,o))))return{v:!0}};for(var r of t)if(n=i(r))return n.v;return!1}function pf(t){var e=t.parentNode;return!(!e||!hn(e))&&e}var qg=[".ph-no-autocapture","[data-ph-no-autocapture]"],gf=["next","previous","prev",">","<"],Vg=[...gf,"+","-","−","–"],Lc=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,Nc=[".ph-no-rageclick",".ph-no-capture"],Gg=["","text","search","email","password","url","tel","number"];function Oc(t,e){if(!w||fl(t))return!1;var n,i,r,s,o;if(mt(e)?(n=!!e&&Nc,i=void 0,r=!1):(n=(s=e?.css_selector_ignorelist)!==null&&s!==void 0?s:Nc,i=e?.content_ignorelist,r=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),n===!1||r&&(function(l){return!(!l||!hn(l))&&(!!et(l,"textarea")||(et(l,"input")?j(Gg,(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=mf(t,!1).targetElementList;return!(function(l,u){if(l===!1||C(l))return!1;var c;if(l===!0)c=gf;else{if(!U(l))return!1;if(l.length>10)return A.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var f=d.safeText,h=d.ariaLabel;return c.some((p=>Lc(f,p)||Lc(h,p)))}))})(i,a.map((l=>{var u;return{safeText:Ji(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!ma(a,n)}var fl=t=>!t||et(t,"html")||!hn(t),mf=(t,e)=>{if(!w||fl(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,i=[t],r=t;r.parentNode&&!et(r,"body");)if(df(r.parentNode))i.push(r.parentNode.host),r=r.parentNode.host;else{var s=pf(r);if(!s)break;if(e||dl.indexOf(s.tagName.toLowerCase())>-1)n=!0;else try{var o=w.getComputedStyle(s);o&&o.getPropertyValue("cursor")==="pointer"&&(n=!0)}catch{}i.push(s),r=s}return{parentIsUsefulElement:n,targetElementList:i}};function va(t){for(var e=new Set,n=0,i=t;i.parentNode&&!et(i,"body");i=i.parentNode){if(n++>=ff||e.has(i))return!1;e.add(i);var r=rs(i);if(j(r,"ph-sensitive")||j(r,"ph-no-capture"))return!1}if(j(rs(t),"ph-include"))return!0;var s=t.type||"";if(X(s))switch(s.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!X(o)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(o.replace(/[^a-zA-Z0-9]/g,""))}function vf(t){return!!(et(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||et(t,"select")||et(t,"textarea")||t.getAttribute("contenteditable")==="true")}var Bc=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}))$"),Dc=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,Kg=[16,15,14,13],Yg=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),jc=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),Uc=/[0-9A-Za-z_]/;function Jg(t){for(var e=0,n=!1,i=t.length-1;i>=0;i--){var r=t.charCodeAt(i)-48;n&&(r*=2)>9&&(r-=9),e+=r,n=!n}return e%10==0}function Ui(t,e){if(e===void 0&&(e=!0),H(t))return!1;if(X(t)){t=xs(t);var n=e?Bc.test((t||"").replace(/[- ]/g,"")):(function(r){var s;for(Dc.lastIndex=0;s=Dc.exec(r);){var o=s[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of Kg){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(Bc.test(d)&&Jg(d))return!0}}}return!1})(t);if(n)return!1;var i=e?Yg.test(t):(function(r){var s;for(jc.lastIndex=0;s=jc.exec(r);){var o=s[1],a=s[3];if(!(o&&a&&Uc.test(o)&&Uc.test(a)))return!0}return!1})(t);if(i)return!1}return!0}function Hc(t){var e=Ji(t);return Ui(e=(e+" "+_f(t)).trim())?e:""}function _f(t){var e="";return t&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;if(n&&((i=n.tagName)==null?void 0:i.toLowerCase())==="span")try{var r=Ji(n);e=(e+" "+r).trim(),n.childNodes&&n.childNodes.length&&(e=(e+" "+_f(n)).trim())}catch(s){A.error("[AutoCapture]",s)}})),e}function Wc(t){return t.replace(/"|\\"/g,'\\"')}function Zg(t){var e=t.attr__class;if(e)return U(e)?e:ul(e)}var yr=pe("[Dead Clicks]"),Xg=()=>!0,Qg=t=>{var e,n=!((e=t.instance.persistence)==null||!e.get_property(sl)),i=t.instance.config.capture_dead_clicks;return mt(i)?i:!!he(i)||n};class zc{get lazyLoadedDeadClicksAutocapture(){return this.si}constructor(e,n,i){this.instance=e,this.isEnabled=n,this.onCapture=i,this.startIfEnabledOrStop()}onRemoteConfig(e){if(e.ok){var n=e.config;"captureDeadClicks"in n&&(this.instance.persistence&&this.instance.persistence.register({[sl]:n.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var n,i;(n=B.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture?e():(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"dead-clicks-autocapture",(r=>{r?yr.error("failed to load script",r):e()}))}oi(){var e;if(P){if(!this.si&&(e=B.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var n=he(this.instance.config.capture_dead_clicks)?I({},this.instance.config.capture_dead_clicks):{};n.__onCapture=this.onCapture,this.onCapture&&(n.capture_dead_swipes=!1),this.si=B.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.si.start(P),yr.info("starting...")}}else yr.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,yr.info("stopping..."))}}var Eo=pe("[SegmentIntegration]"),yf="posthog-js";function wf(t,e){var n=e===void 0?{}:e,i=n.organization,r=n.projectId,s=n.prefix,o=n.severityAllowList,a=o===void 0?["error"]:o,l=n.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,f,h,p,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var v,E=((d=c.exception)==null?void 0:d.values)||[],S=E.map((b=>I({},b,{stacktrace:b.stacktrace?I({},b.stacktrace,{type:"raw",frames:(b.stacktrace.frames||[]).map((k=>I({},k,{platform:"web:javascript"})))}):void 0}))),_={$exception_message:((f=E[0])==null?void 0:f.value)||c.message,$exception_type:(h=E[0])==null?void 0:h.type,$exception_level:c.level,$exception_list:S,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((p=E[0])==null?void 0:p.value)||c.message,$sentry_exception_type:(g=E[0])==null?void 0:g.type,$sentry_tags:c.tags};return i&&r&&(_.$sentry_url=(s||"https://sentry.io/organizations/")+i+"/issues/?project="+r+"&query="+c.event_id),u&&((v=t.exceptions)==null||v.sendExceptionEvent(_)),c}}class em{constructor(e,n,i,r,s,o){this.name=yf,this.setupOnce=function(a){a(wf(e,{organization:n,projectId:i,prefix:r,severityAllowList:s,sendExceptionsToPostHog:o==null||o}))}}}class qc{constructor(e){this.li=(n,i,r)=>{r&&(r.noSessionId||r.activityTimeout||r.sessionPastMaximumLength||r.crossTabAdoption)&&(A.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:n,changeReason:r}),this.ui=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.hi()}hi(){var e;this.di=(e=this._instance.sessionManager)==null?void 0:e.onSessionId(this.li)}destroy(){var e;(e=this.di)==null||e.call(this),this.di=void 0}doPageView(e,n){var i,r=this.vi(e,n);return this.ui={pathname:(i=w?.location.pathname)!==null&&i!==void 0?i:"",pageViewId:n,timestamp:e},this._instance.scrollManager.resetContext(),r}doPageLeave(e){var n;return this.vi(e,(n=this.ui)==null?void 0:n.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.ui)==null?void 0:e.pageViewId}}vi(e,n){var i=this.ui;if(!i)return{$pageview_id:n};var r={$pageview_id:n,$prev_pageview_id:i.pageViewId},s=this._instance.scrollManager.getContext();if(s&&!this._instance.config.disable_scroll_properties){var o=s.maxScrollHeight,a=s.lastScrollY,l=s.maxScrollY,u=s.maxContentHeight,c=s.lastContentY,d=s.maxContentY;if(!(C(o)||C(a)||C(l)||C(u)||C(c)||C(d))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),d=Math.ceil(d);var f=o>1?At(a/o,0,1,A):1,h=o>1?At(l/o,0,1,A):1,p=u>1?At(c/u,0,1,A):1,g=u>1?At(d/u,0,1,A):1;r=fe(r,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:f,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:h,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:p,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return i.pathname&&(r.$prev_pageview_pathname=i.pathname),i.timestamp&&(r.$prev_pageview_duration=(e.getTime()-i.timestamp.getTime())/1e3),r}}var So=["flags","surveys"],tm={[Yd]:{exposure:"hidden"},[Fi]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[Ri]:{exposure:"hidden"},[ea]:{exposure:"event"},[ta]:{exposure:"hidden"},[na]:{exposure:"event"},[ia]:{exposure:"hidden"},[ra]:{exposure:"event"},[sa]:{exposure:"event"},[sl]:{exposure:"event"},[ol]:{exposure:"hidden"},[oa]:{exposure:"event"},[An]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[Kn]:{exposure:"hidden"},[al]:{exposure:"event"},[Jd]:{exposure:"event",shouldSkipFromEventProperties:t=>Ye(t)},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},$sess_rec_flush_size:{exposure:"hidden"},[Sn]:{exposure:"hidden",storageGroup:"flags"},[Ti]:{exposure:"hidden",storageGroup:"flags"},[Ar]:{exposure:"hidden"},[aa]:{exposure:"hidden",storageGroup:"flags"},[$i]:{exposure:"hidden",storageGroup:"flags"},[Pr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[Zr]:{exposure:"hidden",storageGroup:"flags"},[It]:{exposure:"hidden"},[xn]:{exposure:"hidden"},[jt]:{exposure:"hidden"},[In]:{exposure:"hidden"},[la]:{exposure:"hidden",storageGroup:"surveys"},[Xr]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[ca]:{exposure:"event"},[Fr]:{exposure:"hidden"},[Rr]:{exposure:"hidden"},[Mi]:{exposure:"hidden"},$product_tours_activated:{exposure:"hidden"},$product_tours_activated_session:{exposure:"hidden"},$conversations_widget_session_id:{exposure:"event"},$conversations_ticket_id:{exposure:"event"},$conversations_widget_state:{exposure:"event"},$conversations_user_traits:{exposure:"event"},[Cn]:{exposure:"hidden"},[Li]:{exposure:"hidden"},[Tr]:{exposure:"hidden"},[ji]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[at]:{exposure:"hidden"},[ua]:{exposure:"hidden"},[da]:{exposure:"hidden"},[fa]:{exposure:"hidden"},[ha]:{exposure:"hidden"},[Qr]:{exposure:"hidden"},[es]:{exposure:"hidden"},[Zd]:{exposure:"event"},[Xd]:{exposure:"event"},[Qd]:{exposure:"event"},[ef]:{exposure:"event"},[nf]:{exposure:"event"},[rf]:{exposure:"event"},[sf]:{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"}},nm=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],yn=t=>{var e=tm[t];if(e)return e;for(var n of nm){var i=n[1];if(t.indexOf(n[0])===0)return i}},Yn=(t,e)=>{try{return JSON.stringify(t,((n,i)=>typeof i=="bigint"?i.toString():i),e)}catch{return md(t)}},ss=t=>{var e=P?.createElement("a");return C(e)?null:(e.href=t,e)},ii=function(t,e){for(var n,i=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),r=0;i.length>r;r++){var s=i[r].split("=");if(s[0]===e){n=s;break}}if(!U(n)||2>n.length)return"";var o=n[1];try{o=decodeURIComponent(o)}catch{A.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},Zi=function(t,e,n){if(!t||!e||!e.length)return t;for(var i=t.split("#"),r=i[1],s=(i[0]||"").split("?"),o=s[1],a=s[0],l=(o||"").split("&"),u=[],c=0;l.length>c;c++){var d=l[c].split("=");U(d)&&(e.includes(d[0])?u.push(d[0]+"="+n):u.push(l[c]))}var f=a;return o!=null&&(f+="?"+u.join("&")),r!=null&&(f+="#"+r),f},os=function(t,e){var n=t.match(new RegExp(e+"=([^&]*)"));return n?n[1]:null},bf=(t,e)=>t>=e&&hd(),Ef=(t,e,n,i)=>{if(t===0){if(hd()){var r=e+1;return r===n&&i(),r}return e}return 0},wr="https?://(.*)",ri=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],im=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...ri],Xi="",rm=["li_fat_id"];function Sf(t,e,n){if(!P)return{};var i,r=e?[...ri,...n||[]]:[],s=xf(Zi(P.URL,r,Xi),t),o=(i={},ie(rm,(function(a){var l=of(a);i[a]=l||null})),i);return fe(o,s)}function xf(t,e){var n=im.concat(e||[]),i={};return ie(n,(function(r){var s=ii(t,r);i[r]=s||null})),i}function If(t){var e=(function(s){return s?s.search(wr+"google.([^/?]*)")===0?"google":s.search(wr+"bing.com")===0?"bing":s.search(wr+"yahoo.com")===0?"yahoo":s.search(wr+"duckduckgo.com")===0?"duckduckgo":null:null})(t),n=e!="yahoo"?"q":"p",i={};if(!Ye(e)){i.$search_engine=e;var r=P?ii(P.referrer,n):"";r.length&&(i.ph_keyword=r)}return i}function Vc(){return navigator.language||navigator.userLanguage}var as="$direct";function kf(){return P?.referrer||as}function Cf(t,e,n){n===void 0&&(n=!1);var i=t?[...ri,...e||[]]:[],r=n?fn(me?.href):me?.href,s=r?.substring(0,1e3);return{r:kf().substring(0,1e3),u:s?Zi(s,i,Xi):void 0}}function Af(t,e){var n;e===void 0&&(e=!1);var i=t.r,r=t.u,s=e?fn(r):r,o={$referrer:i,$referring_domain:i==null?void 0:i==as?as:(n=ss(i))==null?void 0:n.host};if(s){o.$current_url=s;var a=ss(s);o.$host=a?.host,o.$pathname=a?.pathname;var l=xf(s);fe(o,l)}if(i){var u=If(i);fe(o,u)}return o}function Pf(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function sm(){try{return new Date().getTimezoneOffset()}catch{return}}var om={flags:ji,surveys:Xr},am=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],Hn="main";class xo{constructor(e,n,i){if(i===void 0&&(i=!0),this.ci={},this.fi=!1,this.pi=!1,this.Ne=e,this.gi=i,this.props={},this.mi=void 0,this.yi=(s=>{var o="";return s.token&&(o=s.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),s.persistence_name?"ph_"+s.persistence_name:"ph_"+o+"_posthog"})(e),this.ii=this.bi(e),this.pi=this.wi(e),this.load(),e.debug&&A.info("Persistence loaded",e.persistence,I({},this.props)),this.update_config(e,e,n),this.save(),w){var r=()=>this.flush();ve(w,"beforeunload",r,{capture:!1}),ve(w,"pagehide",r,{capture:!1})}}ki(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return ke(n)&&n>0?n:0}isDisabled(){return!!this.xi}bi(e){am.indexOf(e.persistence.toLowerCase())===-1&&(A.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var n,i=(function(o,a){o===void 0&&(o=[]),a===void 0&&(a=!1);var l=[...Dg,...o];return I({},le,{H(u){try{var c={};try{c=zt.H(u)||{}}catch{}var d,f=JSON.parse(le.P(u)||"{}");if(a){var h={};for(var p in c){var g=c[p];Ye(g)||g===""||(h[p]=g)}d=fe(f,h)}else d=fe(c,f);return le.F(u,d),d}catch{}return null},F(u,c,d,f,h,p){var g=le.F(u,c,void 0,void 0,p);try{var m={};l.forEach((v=>{c[v]&&(m[v]=c[v])})),Object.keys(m).length&&zt.F(u,m,d,f,h,p)}catch(v){le.j(v)}return g},q(u,c){try{w?.localStorage.removeItem(u),zt.q(u,c)}catch(d){le.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),r=!1,s=e.persistence.toLowerCase();return s==="localstorage"&&le.N()?(n=le,r=!0):s==="localstorage+cookie"&&i.N()?(n=i,r=!0):s==="sessionstorage"&&be.N()?n=be:s==="memory"?n=jg:s==="cookie"?n=zt:i.N()?(n=i,r=!0):n=zt,this.fi=r,n}Si(e){return this.yi+"__"+e}wi(e){return this.fi&&!!e.split_storage}properties(){var e={};return ie(this.props,((n,i)=>{var r=yn(i);if(!r||r.exposure==="event"){if(r!=null&&r.shouldSkipFromEventProperties!=null&&r.shouldSkipFromEventProperties(n))return;e[i]=n}})),e}load(){if(!this.xi){var e=this.ii.H(this.yi);e&&(this.props=fe({},e)),this.pi&&this.Ci()}}Ci(){for(var e of So){var n=le.H(this.Si(e));if(n&&!Kt(n)){var i=this.Mi(e);i.persisted=!0,this.Ti(e)||(i.fingerprint=this.Ei(n,e)),this.Ii(e,n)||fe(this.props,n)}}}Ti(e){return Object.keys(this.props).some((n=>{var i;return((i=yn(n))==null?void 0:i.storageGroup)===e}))}Ii(e,n){var i=om[e];if(!i)return!1;var r=n[i],s=this.props[i];return ke(r)&&ke(s)&&s>r}refreshKey(e){var n;if(!this.xi){var i=this.pi?(n=yn(e))==null?void 0:n.storageGroup:void 0,r=i?le.H(this.Si(i)):this.ii.H(this.yi);if(r&&e in r)this.Pi(e,r[e]);else{if(i){var s=this.ii.H(this.yi);if(s&&e in s)return void this.Pi(e,s[e])}this.Ri(e)}}}save(){if(!this.xi){var e=this.ki();e>0?C(this.Ai)&&(this.Ai=setTimeout((()=>{this.Ai=void 0,this.Fi()}),e)):this.Fi()}}flush(){C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0,this.Fi())}Fi(){this.xi||(this.pi?this.Li():this.Oi(this.ii,this.yi,this.props,Hn))}Li(){var e=this.Di(),n=e.main,i=e.groups;for(var r of(this.Oi(this.ii,this.yi,n,Hn),So)){var s,o=i[r];(!Kt(o)||(s=this.ci[r])!=null&&s.persisted)&&this.Oi(le,this.Si(r),o,r)}}Di(){var e={},n={flags:{},surveys:{}};return ie(this.props,((i,r)=>{var s,o=(s=yn(r))==null?void 0:s.storageGroup;o?n[o][r]=i:e[r]=i})),{main:e,groups:n}}Ei(e,n){if(n===Hn)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var i={};return ie(e,((r,s)=>{var o;i[s]=(o=yn(s))!=null&&o.volatile?"__volatile__":r})),JSON.stringify(i)}Oi(e,n,i,r){var s=this.Mi(r);if(r===Hn||s.dirty||C(s.fingerprint)){var o;try{if((o=this.Ei(i,r))===s.fingerprint)return void(s.dirty=!1)}catch{o=void 0}e.F(n,i,this.$i,this.Ni,this.qi,this.Ne.debug)?(s.dirty=!1,r!==Hn&&(s.persisted=!0),C(o)||(s.fingerprint=o)):this.Ne.debug&&A.warn('failed to persist storage entry "'+n+'"; will retry on next save')}}remove(e){var n=(e===void 0?{}:e).keepGroupEntries,i=n!==void 0&&n;if(C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0),this.ii.q(this.yi,!1),this.ii.q(this.yi,!0),!i&&this.gi)for(var r of So)le.q(this.Si(r));i?delete this.ci[Hn]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,n,i){if(he(e)){C(n)&&(n="None"),this.$i=C(i)?this.ji:i;var r=!1;if(ie(e,((s,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==n||(this.Pi(o,s),r=!0)})),r)return this.save(),!0}return!1}register(e,n){if(he(e)){this.$i=C(n)?this.ji:n;var i=!1;if(ie(e,((r,s)=>{e.hasOwnProperty(s)&&(this.props[s]!==r||he(r)||U(r))&&(this.Pi(s,r),i=!0)})),i)return this.save(),!0}return!1}unregister(e){var n=typeof e=="string"?[e]:e,i=!1;for(var r of n)r in this.props&&(this.Ri(r),i=!0);i&&this.save()}update_campaign_params(){var e=P?.URL;if(e!==this.mi){var n=Sf(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);Kt(cl(n))||this.register(n),this.mi=e}}update_search_keyword(){var e;this.register((e=P?.referrer)?If(e):{})}update_referrer_info(){var e;this.register_once({$referrer:kf(),$referring_domain:P!=null&&P.referrer&&((e=ss(P.referrer))==null?void 0:e.host)||as},void 0)}set_initial_person_info(){this.props[fa]||this.props[ha]||this.register_once({[Qr]:Cf(this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties,this.Ne.disable_capture_url_hashes)},void 0)}get_initial_props(){var e={};ie([ha,fa],(r=>{var s=this.props[r];s&&ie(s,(function(o,a){e["$initial_"+Go(a)]=o}))}));var n=this.props[Qr];if(n){var i=(function(r,s){s===void 0&&(s=!1);var o=Af(r,s),a={};return ie(o,(function(l,u){a["$initial_"+Go(u)]=l})),a})(n,this.Ne.disable_capture_url_hashes);fe(e,i)}return e}safe_merge(e){return ie(this.props,(function(n,i){i in e||(e[i]=n)})),e}update_config(e,n,i){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!i),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var r=e.persistence!==n.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((f,h)=>f===d[h]))})(e.cookie_persisted_properties||[],n.cookie_persisted_properties||[]),s=r?this.bi(e):this.ii,o=this.wi(e);if(r||o!==this.pi){var a=this.props;this.clear(),this.ii=s,this.pi=o,this.props=a,this.save()}}set_disabled(e){this.xi=e,this.xi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ni&&(this.Ni=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this.qi&&(this.qi=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,n){var i=this.props[Ri]||{};i[e]=n,this.Pi(Ri,i),this.save()}remove_event_timer(e){var n=this.props[Ri]||{},i=n[e];return C(i)||(delete n[e],this.Pi(Ri,n),this.save()),i}get_property(e){return this.props[e]}set_property(e,n){this.Pi(e,n),this.save()}Pi(e,n){var i;this.props[e]=n,(i=yn(e))!=null&&i.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var n,i=(n=yn(e))==null?void 0:n.storageGroup;i&&(this.Mi(i).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function br(t){var e=!0;return{dispose(){if(e){e=!1;var n=t();n&&je(n.then)&&n.then(void 0,(()=>{}))}}}}var Ue={GZipJS:"gzip-js",Base64:"base64"},wi={Activation:"events",Cancellation:"cancelEvents"},Io={Popover:"popover",API:"api",Widget:"widget"},qt={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},ko={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},_a={Popover:"popover",Inline:"inline"},lm={SHOWN:"product tour shown"},Gc={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},Kc=pe("[RateLimiter]");class cm{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=n=>{var i=n.text;if(i&&i.length)try{(JSON.parse(i).quota_limited||[]).forEach((r=>{Kc.info((r||"events")+" is quota limited."),this.serverLimits[r]=new Date().getTime()+6e4}))}catch(r){return void Kc.warn('could not rate limit - continuing. Error: "'+r?.message+'"',{text:i})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var n,i,r;e===void 0&&(e=!1);var s=this.captureEventsBurstLimit,o=this.captureEventsPerSecond,a=new Date().getTime(),l=(n=(i=this.instance.persistence)==null?void 0:i.get_property(da))!==null&&n!==void 0?n:{tokens:s,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>s&&(l.tokens=s);var u=1>l.tokens;if(u||e||(l.tokens=Math.max(0,l.tokens-1)),u&&!e){var c=(ke(l.dropped)?l.dropped:0)+1;l.dropped=c,!this.lastEventRateLimited&&this.Hi(c)&&(l.dropped=0)}return this.lastEventRateLimited=u,(r=this.instance.persistence)==null||r.set_property(da,l),{isRateLimited:u,remainingTokens:l.tokens}}Ui(e){var n=this.instance.config.property_denylist;return!U(n)||!n.includes(e)}zi(){var e;if(this.Ui("$current_url")&&this.Ui("$pathname")&&me!=null&&me.pathname)return""+((e=me.origin)!==null&&e!==void 0?e:"")+me.pathname}Hi(e){var n,i,r=this.captureEventsBurstLimit,s=this.captureEventsPerSecond,o=this.zi(),a=this.Ui("$session_id")?(n=(i=this.instance).get_session_id)==null?void 0:n.call(i):void 0,l=[e+" event(s) dropped since the last warning",o?"triggered on "+o:void 0,a?"session "+a:void 0].filter(Boolean).join(", ");return!!this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited: "+l+". Config is set to "+s+" events per second and "+r+" events burst limit."},{skip_client_rate_limiting:!0})}isServerRateLimited(e){var n=this.serverLimits[e||"events"]||!1;return n!==!1&&new Date().getTime()e(this.remoteConfig))):e()}Vi(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:e})}load(){try{if(this.remoteConfig)return an.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void an.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return an.info("No config found after loading remote JS config. Falling back to JSON."),void this.Vi((n=>{this.Zi(n.json,n),this.Gi()}));this.Zi(e),this.Gi()}))}catch(e){an.error("Error loading remote config",e),this.Zi()}}stop(){this.Ki&&(clearInterval(this.Ki),this.Ki=void 0)}refresh(){!this._instance.Qi()&&P&&P.visibilityState!=="hidden"&&this._instance.reloadFeatureFlags()}Gi(){var e;if(!this.Ki){var n=(e=this._instance.config.remote_config_refresh_interval_ms)!==null&&e!==void 0?e:3e5;n!==0&&(this.Ki=setInterval((()=>{this.refresh()}),n))}}Zi(e,n){!e&&n&&(n.statusCode===0?n.error||an.warn("Failed to fetch remote config from PostHog."):an.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(r){an.error("Error applying remote config",r)}if(e?.hasFeatureFlags!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var i;(i=this._instance.featureFlags)==null||i.ensureFlagsLoaded()}catch(r){an.error("Error loading feature flags",r)}}}var ct=Uint8Array,Ke=Uint16Array,si=Uint32Array,hl=new ct([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]),pl=new ct([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]),Yc=new ct([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Rf=function(t,e){for(var n=new Ke(31),i=0;31>i;++i)n[i]=e+=1<i;++i)for(var s=n[i];n[i+1]>s;++s)r[s]=s-n[i]<<5|i;return[n,r]},Tf=Rf(hl,2),ya=Tf[1];Tf[0][28]=258,ya[258]=28;for(var Jc=Rf(pl,0)[1],$f=new Ke(32768),_e=0;32768>_e;++_e){var Wn=(43690&_e)>>>1|(21845&_e)<<1;$f[_e]=((65280&(Wn=(61680&(Wn=(52428&Wn)>>>2|(13107&Wn)<<2))>>>4|(3855&Wn)<<4))>>>8|(255&Wn)<<8)>>>1}var Hi=function(t,e,n){for(var i=t.length,r=0,s=new Ke(e);i>r;++r)++s[t[r]-1];var o,a=new Ke(e);for(r=0;e>r;++r)a[r]=a[r-1]+s[r-1]<<1;for(o=new Ke(i),r=0;i>r;++r)o[r]=$f[a[t[r]-1]++]>>>15-t[r];return o},$n=new ct(288);for(_e=0;144>_e;++_e)$n[_e]=8;for(_e=144;256>_e;++_e)$n[_e]=9;for(_e=256;280>_e;++_e)$n[_e]=7;for(_e=280;288>_e;++_e)$n[_e]=8;var ls=new ct(32);for(_e=0;32>_e;++_e)ls[_e]=5;var um=Hi($n,9),dm=Hi(ls,5),Mf=function(t){return(t/8>>0)+(7&t&&1)},Lf=function(t,e,n){(n==null||n>t.length)&&(n=t.length);var i=new(t instanceof Ke?Ke:t instanceof si?si:ct)(n-e);return i.set(t.subarray(e,n)),i},Ot=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8},bi=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8,t[i+2]|=n>>>16},Co=function(t,e){for(var n=[],i=0;t.length>i;++i)t[i]&&n.push({s:i,f:t[i]});var r=n.length,s=n.slice();if(!r)return[new ct(0),0];if(r==1){var o=new ct(n[0].s+1);return o[n[0].s]=1,[o,1]}n.sort((function(b,k){return b.f-k.f})),n.push({s:-1,f:25001});var a=n[0],l=n[1],u=0,c=1,d=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=r-1;)a=n[n[d].f>n[u].f?u++:d++],l=n[u!=c&&n[d].f>n[u].f?u++:d++],n[c++]={s:-1,f:a.f+l.f,l:a,r:l};var f=s[0].s;for(i=1;r>i;++i)s[i].s>f&&(f=s[i].s);var h=new Ke(f+1),p=wa(n[c-1],h,0);if(p>e){i=0;var g=0,m=p-e,v=1<i;++i){var E=s[i].s;if(e>=h[E])break;g+=v-(1<>>=m;g>0;){var S=s[i].s;e>h[S]?g-=1<=0&&g;--i){var _=s[i].s;h[_]==e&&(--h[_],++g)}p=e}return[new ct(h),p]},wa=function(t,e,n){return t.s==-1?Math.max(wa(t.l,e,n+1),wa(t.r,e,n+1)):e[t.s]=n},Zc=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new Ke(++e),i=0,r=t[0],s=1,o=function(l){n[i++]=l},a=1;e>=a;++a)if(t[a]==r&&a!=e)++s;else{if(!r&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(r),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(r);s=1,r=t[a]}return[n.subarray(0,i),e]},Ei=function(t,e){for(var n=0,i=0;e.length>i;++i)n+=t[i]*e[i];return n},ba=function(t,e,n){var i=n.length,r=Mf(e+2);t[r]=255&i,t[r+1]=i>>>8,t[r+2]=255^t[r],t[r+3]=255^t[r+1];for(var s=0;i>s;++s)t[r+s+4]=n[s];return 8*(r+4+i)},Xc=function(t,e,n,i,r,s,o,a,l,u,c){Ot(e,c++,n),++r[256];for(var d=Co(r,15),f=d[0],h=d[1],p=Co(s,15),g=p[0],m=p[1],v=Zc(f),E=v[0],S=v[1],_=Zc(g),b=_[0],k=_[1],T=new Ke(19),x=0;E.length>x;++x)T[31&E[x]]++;for(x=0;b.length>x;++x)T[31&b[x]]++;for(var F=Co(T,7),$=F[0],O=F[1],L=19;L>4&&!$[Yc[L-1]];--L);var N,K,V,M,R=u+5<<3,Z=Ei(r,$n)+Ei(s,ls)+o,Ce=Ei(r,f)+Ei(s,g)+o+14+3*L+Ei(T,$)+(2*T[16]+3*T[17]+7*T[18]);if(Z>=R&&Ce>=R)return ba(e,c,t.subarray(l,l+u));if(Ot(e,c,1+(Z>Ce)),c+=2,Z>Ce){N=Hi(f,h),K=f,V=Hi(g,m),M=g;var oe=Hi($,O);for(Ot(e,c,S-257),Ot(e,c+5,k-1),Ot(e,c+10,L-4),c+=14,x=0;L>x;++x)Ot(e,c+3*x,$[Yc[x]]);c+=3*L;for(var ye=[E,b],$e=0;2>$e;++$e){var ae=ye[$e];for(x=0;ae.length>x;++x)Ot(e,c,oe[Ie=31&ae[x]]),c+=$[Ie],Ie>15&&(Ot(e,c,ae[x]>>>5&127),c+=ae[x]>>>12)}}else N=um,K=$n,V=dm,M=ls;for(x=0;a>x;++x)if(i[x]>255){var Ie;bi(e,c,N[257+(Ie=i[x]>>>18&31)]),c+=K[Ie+257],Ie>7&&(Ot(e,c,i[x]>>>23&31),c+=hl[Ie]);var Se=31&i[x];bi(e,c,V[Se]),c+=M[Se],Se>3&&(bi(e,c,i[x]>>>5&8191),c+=pl[Se])}else bi(e,c,N[i[x]]),c+=K[i[x]];return bi(e,c,N[256]),c+K[256]},fm=new si([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),hm=(function(){for(var t=new si(256),e=0;256>e;++e){for(var n=e,i=9;--i;)n=(1&n&&3988292384)^n>>>1;t[e]=n}return t})(),Ao=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8};function pm(t,e){e===void 0&&(e={});var n=(function(){var d=4294967295;return{p(f){for(var h=d,p=0;f.length>p;++p)h=hm[255&h^f[p]]^h>>>8;d=h},d(){return 4294967295^d}}})(),i=t.length;n.p(t);var r,s,o,a,l,u=(a=10+((r=e).filename&&r.filename.length+1||0),l=8,(function(d,f,h,p,g,m){var v=d.length,E=new ct(p+v+5*(1+Math.floor(v/7e3))+g),S=E.subarray(p,E.length-g),_=0;if(!f||8>v)for(var b=0;v>=b;b+=65535){var k=b+65535;v>k?_=ba(S,_,d.subarray(b,k)):(S[b]=!0,_=ba(S,_,d.subarray(b,v)))}else{for(var T=fm[f-1],x=T>>>13,F=8191&T,$=(1<b;++b){var Ie=V(b),Se=32767&b,De=L[Ie];if(O[Se]=De,L[Ie]=Se,b>=$e){var wt=v-b;if((Ce>7e3||ye>24576)&&wt>423){_=Xc(d,S,0,M,R,Z,oe,ye,ae,b-ae,_),ye=Ce=oe=0,ae=b;for(var ge=0;286>ge;++ge)R[ge]=0;for(ge=0;30>ge;++ge)Z[ge]=0}var Je=2,bt=0,mn=F,Re=Se-De&32767;if(wt>2&&Ie==V(b-Re))for(var Pe=Math.min(x,wt)-1,$t=Math.min(32767,b),Bn=Math.min(258,wt);$t>=Re&&--mn&&Se!=De;){if(d[b+Je]==d[b+Je-Re]){for(var qe=0;Bn>qe&&d[b+qe]==d[b+qe-Re];++qe);if(qe>Je){if(Je=qe,bt=Re,qe>Pe)break;var Dn=Math.min(Re,qe-2),Mt=0;for(ge=0;Dn>ge;++ge){var Lt=b-Re+ge+32768&32767,ut=Lt-O[Lt]+32768&32767;ut>Mt&&(Mt=ut,De=Lt)}}}Re+=(Se=De)-(De=O[Se])+32768&32767}if(bt){M[ye++]=268435456|ya[Je]<<18|Jc[bt];var sn=31&ya[Je],gi=31&Jc[bt];oe+=hl[sn]+pl[gi],++R[257+sn],++Z[gi],$e=b+Je,++Ce}else M[ye++]=d[b],++R[d[b]]}}_=Xc(d,S,!0,M,R,Z,oe,ye,ae,b-ae,_)}return Lf(E,0,p+Mf(_)+g)})(s=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):12+o.mem,a,l)),c=u.length;return(function(d,f){var h=f.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>f.level?4:f.level==9?2:0,d[9]=3,f.mtime!=0&&Ao(d,4,Math.floor(new Date(f.mtime||Date.now())/1e3)),h){d[3]=8;for(var p=0;h.length>=p;++p)d[p+10]=h.charCodeAt(p)}})(u,e),Ao(u,c-8,n.d()),Ao(u,c-4,i),u}var gm=!!zo||!!Xa,Nf="text/plain",Mr=!1,Of=(t,e)=>{var n=t.split("#"),i=n[1],r=n[0].split("?"),s=r[0],o=r[1];if(!o)return t;var a=o.split("&").filter((l=>l.split("=")[0]!==e)).join("&");return s+(a?"?"+a:"")+(i?"#"+i:"")},ks=function(t,e,n){var i;n===void 0&&(n=!0);var r=t.split("?"),s=r[0],o=r[1],a=I({},e),l=(i=o?.split("&").map((c=>{var d,f=c.split("="),h=f[0],p=n&&(d=a[h])!==null&&d!==void 0?d:f[1];return delete a[h],h+"="+p})))!==null&&i!==void 0?i:[],u=(function(c,d){var f,h;d===void 0&&(d="&");var p=[];return ie(c,(function(g,m){C(g)||C(m)||m==="undefined"||(f=encodeURIComponent((v=>v instanceof File)(g)?g.name:g.toString()),h=encodeURIComponent(m),p[p.length]=h+"="+f)})),p.join(d)})(a);return u&&l.push(u),l.length>0?s+"?"+l.join("&"):s},Po=t=>{if(t.Ji)return t.Ji;var e=t.data,n=t.compression;if(e){if(n===Ue.GZipJS){var i=pm((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new ct(a.length+(a.length>>>1)),d=0,f=function(m){c[d++]=m},h=0;u>h;++h){if(d+5>c.length){var p=new ct(d+8+(u-h<<1));p.set(c),c=p}var g=a.charCodeAt(h);128>g?f(g):2048>g?(f(192|g>>>6),f(128|63&g)):g>55295&&57344>g?(f(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++h))>>>18),f(128|g>>>12&63),f(128|g>>>6&63),f(128|63&g)):(f(224|g>>>12),f(128|g>>>6&63),f(128|63&g))}return Lf(c,0,d)})(Yn(e)),{mtime:0});return{contentType:Nf,body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),estimatedSize:i.byteLength}}if(n===Ue.Base64){var r=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(Yn(e)),s=(a=>"data="+encodeURIComponent(typeof a=="string"?a:Yn(a)))(r);return{contentType:"application/x-www-form-urlencoded",body:s,estimatedSize:new Blob([s]).size}}var o=Yn(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},Bf=t=>{var e,n,i=()=>t.transport==="sendBeacon"?{url:ks(t.url,{compression:Ue.Base64}),encodedBody:Po(I({},t,{compression:Ue.Base64,Ji:void 0}))}:{url:Of(t.url,"compression"),encodedBody:Po(I({},t,{compression:void 0,Ji:void 0}))};try{e=Po(t)}catch(r){if(_c(t.compression,ii(t.url,"compression")))return A.error("Failed to gzip request body, sending uncompressed payload",r),i();throw r}return e&&_c(t.compression,ii(t.url,"compression"))&&!((n=e.body)instanceof ArrayBuffer?qo(new Uint8Array(n)):ArrayBuffer.isView(n)&&qo(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)))?(Mr=!0,i()):{url:t.url,encodedBody:e}},Df=t=>{try{return Bf(t)}catch(e){return A.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},mm=(function(){var t=se((function*(e){var n=Yn(e.data),i=yield(function(s,o,a){return Vo.apply(this,arguments)})(n,ne.DEBUG,{rethrow:!0});if(!i)return e;var r=yield i.arrayBuffer();return I({},e,{Ji:{contentType:Nf,body:r,estimatedSize:r.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),vm=/Failed to fetch|NetworkError|Load failed/i,jf=t=>t?.name==="TypeError"&&vm.test(t?.message||""),Uf=t=>{var e=Df(t);if(e){var n=e.url,i=e.encodedBody,r=i??{},s=r.contentType,o=r.body,a=r.estimatedSize,l=new Headers;ie(t.headers,(function(p,g){l.append(g,p)})),s&&l.append("Content-Type",s);var u=null,c=!1;if(fc){var d=new fc;u={signal:d.signal,timeout:setTimeout((()=>{var p,g;c=!0,d.abort((p=t.timeout,(g=new Error("PostHog request timed out"+(p?" after "+p+"ms":""))).name="AbortError",g))}),t.timeout)}}var f=p=>{c&&p?.name==="AbortError"||jf(p)?A.warn(p):A.error(p),t.callback==null||t.callback({statusCode:0,error:p})};try{var h;Xa(n,I({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(h=u)==null?void 0:h.signal},t.fetchOptions)).then((p=>p.text().then((g=>{var m={statusCode:p.status,text:g};if(p.status===200)try{m.json=JSON.parse(g)}catch(v){A.error(v)}t.callback==null||t.callback(m)})))).catch(f).finally((()=>u?clearTimeout(u.timeout):null))}catch(p){u&&clearTimeout(u.timeout),f(p)}}},Ea=t=>{try{var e,n=Bf(t),i=n.url,r=n.encodedBody,s=r??{},o=s.body,a=s.estimatedSize;if(!o)return;var l=o instanceof Blob?o:new Blob([o],{type:s.contentType});if(He.sendBeacon(i,l))return;var u=U(t.data)?t.data:(e=t.data)==null?void 0:e.batch;if(U(u)&&u.length>1&&(a??0)>16384){var c=Math.ceil(u.length/2),d=f=>U(t.data)?f:I({},t.data,{batch:f});return Ea(I({},t,{data:d(u.slice(0,c))})),void Ea(I({},t,{data:d(u.slice(c))}))}A.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),Uf(I({},t,{Yi:!0}))}catch(f){A.warn("Beacon send failed",f)}},Qc=(t,e,n,i)=>{var r=i==="query"?e==="POST"?"sent_at":"_":void 0;return ks(n===Ue.GZipJS?Of(t,"compression"):t,I({},r?{[r]:Date.now().toString()}:{},n===Ue.GZipJS?{}:{compression:n}))},Lr=[];Xa&&Lr.push({transport:"fetch",method:Uf}),zo&&Lr.push({transport:"XHR",method(t){var e=Df(t);if(e){var n=new zo,i=e.encodedBody;n.open(t.method||"GET",e.url,!0);var r=i??{},s=r.contentType,o=r.body;ie(t.headers,(function(a,l){n.setRequestHeader(l,a)})),s&&n.setRequestHeader("Content-Type",s),t.timeout&&(n.timeout=t.timeout),n.onreadystatechange=()=>{if(n.readyState===4){var a={statusCode:n.status,text:n.responseText};if(n.status===200)try{a.json=JSON.parse(n.responseText)}catch{}t.callback==null||t.callback(a)}},n.send(o)}}}),He!=null&&He.sendBeacon&&Lr.push({transport:"sendBeacon",method:Ea});var Sa=3e3;class _m{constructor(e,n){this.Xi=!0,this.tr=[],this.er=At(n?.flush_interval_ms||Sa,250,5e3,A.createLogger("flush interval"),Sa),this.ir=e}enqueue(e){this.tr.push(e),this.rr||this.nr()}unload(){this.sr();var e=this.tr.length>0?this.ar():{},n=Object.values(e);[...n.filter((i=>i.url.indexOf("/e")===0)),...n.filter((i=>i.url.indexOf("/e")!==0))].map((i=>{this.lr(I({},i,{transport:"sendBeacon"}))}))}enable(){this.Xi=!1,this.nr()}nr(){var e=this;this.Xi||(this.rr=setTimeout((()=>{if(this.sr(),this.tr.length>0){var n=this.ar(),i=function(){var s=n[r],o=new Date().getTime();s.data&&U(s.data)&&ie(s.data,(a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp})),e.lr(s)};for(var r in n)i()}}),this.er))}lr(e){try{this.ir(e)}catch(n){A.error(n)}}sr(){clearTimeout(this.rr),this.rr=void 0}ar(){var e={};return ie(this.tr,(n=>{var i,r=n,s=(r?r.batchKey:null)||r.url;C(e[s])&&(e[s]=I({},r,{data:[]})),(i=e[s].data)==null||i.push(r.data)})),this.tr=[],e}}var ym=["retriesPerformedSoFar"];class wm{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!C(w)&&"onLine"in w.navigator&&(this.dr=w.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},ve(w,"online",this.vr),ve(w,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var n=e.retriesPerformedSoFar,i=pd(e,ym);Dt(n)&&(i.url=ks(i.url,{retry_count:n})),this._instance._send_request(I({},i,{callback:r=>{if(r.statusCode!==200&&(400>r.statusCode||r.statusCode>=500)){if((r.statusCode===0?3:10)>(n??0))return void this.At(I({retriesPerformedSoFar:n},i));r.statusCode===0&&A.warn("Request failed before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped retrying after "+(n??0)+" retries.")}i.callback==null||i.callback(r)}}))}At(e){var n=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=n+1;var i=(function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),c=Math.random()-.5;return Math.ceil(u+c*(u-l))})(n),r=Date.now()+i;this.tr.push({retryAt:r,requestOptions:e});var s="Enqueued failed request for retry in "+i;navigator.onLine||(s+=" (Browser is offline)"),A.warn(s),this.ur||(this.ur=!0,this.gr())}gr(){if(this.mr&&clearTimeout(this.mr),this.tr.length===0)return this.ur=!1,void(this.mr=void 0);this.mr=setTimeout((()=>{this.dr&&this.tr.length>0&&this.cr(),this.gr()}),this.hr)}cr(){var e=Date.now(),n=[],i=this.tr.filter((s=>e>s.retryAt||(n.push(s),!1)));if(this.tr=n,i.length>0)for(var r of i)this.retriableRequest(r.requestOptions)}unload(){for(var e of(this.mr&&(clearTimeout(this.mr),this.mr=void 0),this.ur=!1,C(w)||(this.vr&&(w.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(w.removeEventListener("offline",this.pr),this.pr=void 0)),this.tr)){var n=e.requestOptions;try{this._instance._send_request(I({},n,{transport:"sendBeacon"}))}catch(i){A.error(i)}}this.tr=[]}}class bm{constructor(e){this.yr=()=>{var n,i,r,s;this.br||(this.br={});var o=this.scrollElement(),a=this.scrollY(),l=o?Math.max(0,o.scrollHeight-o.clientHeight):0,u=a+(o?.clientHeight||0),c=o?.scrollHeight||0;this.br.lastScrollY=Math.ceil(a),this.br.maxScrollY=Math.max(a,(n=this.br.maxScrollY)!==null&&n!==void 0?n:0),this.br.maxScrollHeight=Math.max(l,(i=this.br.maxScrollHeight)!==null&&i!==void 0?i:0),this.br.lastContentY=u,this.br.maxContentY=Math.max(u,(r=this.br.maxContentY)!==null&&r!==void 0?r:0),this.br.maxContentHeight=Math.max(c,(s=this.br.maxContentHeight)!==null&&s!==void 0?s:0)},this._instance=e}get _r(){return this._instance.config.scroll_root_selector}getContext(){return this.br}resetContext(){var e=this.br;return setTimeout(this.yr,0),e}startMeasuringScrollPosition(){ve(w,"scroll",this.yr,{capture:!0}),ve(w,"scrollend",this.yr,{capture:!0}),ve(w,"resize",this.yr)}scrollElement(){if(!this._r)return w?.document.documentElement;var e=U(this._r)?this._r:[this._r];for(var n of e){var i=w?.document.querySelector(n);if(i)return i}}wr(e){var n=e==="y"?"scrollTop":"scrollLeft";if(this._r){var i=this.scrollElement();return i&&i[n]||0}return w?e==="y"?w.scrollY||w.pageYOffset||w.document.documentElement.scrollTop||0:w.scrollX||w.pageXOffset||w.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var Em=t=>Cf(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class eu{constructor(e,n,i,r){this.kr=s=>{var o=this.Sr();if(!o||o.sessionId!==s){var a={sessionId:s,props:this.Cr(this._instance)};this.Mr.register({[ua]:a})}},this._instance=e,this.Tr=n,this.Mr=i,this.Cr=r||Em,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[ua]}getSetOnceProps(){var e,n=(e=this.Sr())==null?void 0:e.props;return n?"r"in n?Af(n,this._instance.config.disable_capture_url_hashes):{$referring_domain:n.referringDomain,$pathname:n.initialPathName,utm_source:n.utm_source,utm_campaign:n.utm_campaign,utm_medium:n.utm_medium,utm_content:n.utm_content,utm_term:n.utm_term}:{}}getSessionProps(){var e={};return ie(cl(this.getSetOnceProps()),((n,i)=>{i==="$current_url"&&(i="url"),e["$session_entry_"+Go(i)]=n})),e}}class gl{on(e,n){return this.Er[e]||(this.Er[e]=[]),this.Er[e].push(n),()=>{this.Er[e]=this.Er[e].filter((i=>i!==n))}}emit(e,n){for(var i of this.Er[e]||[])i(n);for(var r of this.Er["*"]||[])r(e,n)}constructor(){this.Er={}}}var Si=pe("[SessionId]");class tu{on(e,n){return this.Ir.on(e,n)}constructor(e,n,i){var r;if(this.Pr=null,this.Rr=[],this.Ar=void 0,this.Fr=!1,this.Ir=new gl,this.Lr=(u,c)=>!(!Dt(u)||!Dt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===Wt)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Ne=e.config,this.Mr=e.persistence,this.Or=void 0,this.Dr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.$r=n||Ht,this.Nr=i||Ht;var s=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*At(this.Ne.session_idle_timeout_seconds||1800,60,36e3,Si.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.qr(),this.jr="ph_"+s+"_window_id",this.Br="ph_"+s+"_primary_window_exists",this.Hr()){var o=be.H(this.jr),a=be.H(this.Br);o&&!a?this.Or=o:be.q(this.jr),be.F(this.Br,!0)}if((r=this.Ne.bootstrap)!=null&&r.sessionID)try{var l=(u=>{var c=this.Ne.bootstrap.sessionID.replace(/-/g,"");if(c.length!==32)throw new Error("Not a valid UUID");if(c[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(c.substring(0,12),16)})();this.Ur(this.Ne.bootstrap.sessionID,new Date().getTime(),l)}catch(u){Si.error("Invalid sessionID in bootstrap",u)}this.zr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return C(this.Rr)&&(this.Rr=[]),this.Rr.push(e),this.Dr&&e(this.Dr,this.Or),()=>{this.Rr=this.Rr.filter((n=>n!==e))}}Hr(){return this.Ne.persistence!=="memory"&&!this.Mr.xi&&be.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&be.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?be.H(this.jr):null}Zr(e){var n=this.Pr;return!Ye(n)&&!Ye(e)&&5e3>Math.abs(e-n)}Ur(e,n,i){var r=n!==this._sessionActivityTimestamp,s=!(e!==this.Dr||i!==this._sessionStartTimestamp);this._sessionStartTimestamp=i,this._sessionActivityTimestamp=n,this.Dr=e,s&&!r||s&&this.Zr(n)||(this.Pr=n,this.Mr.register({[Kn]:[n,e,i]}))}Gr(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return Dt(n)&&n>0}Qr(){this.Gr()?this.Mr.refreshKey(Kn):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!Ye(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this.Pr){this.Qr();var n=this.Jr();n[1]===this.Dr&&n[2]===this._sessionStartTimestamp&&(this.Pr=this._sessionActivityTimestamp,this.Mr.register({[Kn]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],n=Dt(e)?e:0,i=Dt(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(n,i)}Xr(e){return this.Qr(),this.Lr(e,this.Yr())}Jr(){var e=this.Mr.props[Kn];return U(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Pr=null,clearTimeout(this.tn),this.tn=void 0,this.Ur(null,null,null)}destroy(){this.Fr=!0,this.Kr(),clearTimeout(this.tn),this.tn=void 0,this.Ar&&w&&(w.removeEventListener(ns,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&be.q(this.Br)},ve(w,ns,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=null),this.Ne.cookieless_mode===Wt)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var i=n||new Date().getTime(),r=this.Jr(),s=r[1],o=r[2],a=this.Yr(),l=this.Vr(),u=Dt(o)&&Math.abs(i-o)>864e5,c=!1,d=!1,f=!s,h=s,p=!f&&!e&&this.Lr(i,a);if(p){(p=this.Xr(i))||Si.info("cross-tab refresh kept the session alive",{sessionId:s});var g=this.Jr();s=g[1],o=g[2]}f||p||u?(s=this.$r(),l=this.Nr(),Si.info("new session ID generated",{sessionId:s,windowId:l,changeReason:{noSessionId:f,activityTimeout:p,sessionPastMaximumLength:u}}),o=i,c=!0):(l||(l=this.Nr(),c=!0),(d=s!==h)&&(Si.info("adopted cross-tab session id",{sessionId:s,windowId:l}),c=!0));var m=Dt(a)&&e&&!u?a:i,v=Dt(o)?o:new Date().getTime();this.Wr(l),this.Ur(s,m,v),e||this.qr();var E={noSessionId:f,activityTimeout:p,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((S=>S(s,l,E))),{sessionId:s,windowId:l,sessionStartTimestamp:v,changeReason:c?E:void 0,lastActivityTimestamp:a}}qr(){this.Fr||(clearTimeout(this.tn),this.tn=setTimeout((()=>{if(!this.Fr)if(this.Xr(new Date().getTime())){var e=this.Dr;this.resetSessionId(),this.Ir.emit("forcedIdleReset",{idleSessionId:e})}else this.qr()}),1.1*this.sessionTimeoutMs))}}var Hf=function(t,e){if(!t)return!1;var n=t.userAgent;if(n&&wc(n,e))return!0;try{var i=t?.userAgentData;if(i!=null&&i.brands&&i.brands.some((r=>wc(r?.brand,e))))return!0}catch{}return!!t.webdriver};function Wf(){return(Wf=se((function*(){var t=He?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),n=e?.model;return X(n)&&n.length>0?n:void 0}catch(i){return void A.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",i)}}))).apply(this,arguments)}var cs=function(t,e){if(!(function(n){try{new RegExp(n)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function Fo(t,e,n){return Yn({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}var zf={exact:(t,e)=>e.some((n=>t.some((i=>n===i)))),is_not:(t,e)=>e.every((n=>t.every((i=>n!==i)))),regex:(t,e)=>e.some((n=>t.some((i=>cs(n,i))))),not_regex:(t,e)=>e.every((n=>t.every((i=>!cs(n,i))))),icontains:(t,e)=>e.map(Er).some((n=>t.map(Er).some((i=>n.includes(i))))),not_icontains:(t,e)=>e.map(Er).every((n=>t.map(Er).every((i=>!n.includes(i))))),gt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>i>parseFloat(r)))})),lt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>it.toLowerCase();function qf(t,e){return!t||Object.entries(t).every((n=>{var i=n[1],r=e?.[n[0]];if(C(r)||Ye(r))return!1;var s=[String(r)],o=zf[i.operator];return!!o&&o(i.values,s)}))}var xa="custom",nu="i.posthog.com",Sm=/^\/static\//;class xm{constructor(e){this.en={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,n=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return n||(n=this.apiHost.replace("."+nu,".posthog.com")),n==="https://app.posthog.com"?"https://us.posthog.com":n}get region(){return this.en[this.apiHost]||(this.en[this.apiHost]=/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"us":/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"eu":xa),this.en[this.apiHost]}rn(e){if(Sm.test(e)){var n=this.instance.config.asset_host;if(typeof n=="string")return n.trim().replace(/\/$/,"")||void 0}}endpointFor(e,n){if(n===void 0&&(n=""),n&&(n=n[0]==="/"?n:"/"+n),e==="ui")return this.uiHost+n;if(e==="flags")return this.flagsApiHost+n;if(e==="assets"){var i=this.rn(n);if(i)return""+i+n}if(this.region===xa)return this.apiHost+n;var r=nu+n;switch(e){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}}function Vf(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var Q=pe("[Surveys]"),Gf="seenSurvey_",Kf=t=>{try{var e=(n=>((i,r)=>""+Gf+(function(s){return s.current_iteration&&s.current_iteration>0?s.id+"_"+s.current_iteration:s.id})(r))(0,n))(t);if(localStorage.getItem(e))return;localStorage.setItem(e,"true")}catch(n){Q.error("Failed to persist survey seen state",n)}},Im=[Io.Popover,Io.Widget,Io.API],km={ignoreConditions:!1,ignoreDelay:!1,displayType:_a.Popover},Cm=pe("[PostHog ExternalIntegrations]"),Am={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class Pm{constructor(e){this._instance=e}ai(e,n){var i;(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,e,(r=>{if(r)return Cm.error("failed to load script",r);n()}))}startIfEnabledOrStop(){var e=this,n=function(){var s,o,a,l=i[0],u=i[1];!u||(s=B.__PosthogExtensions__)!=null&&(s=s.integrations)!=null&&s[l]||e.ai(Am[l],(()=>{var c;(c=B.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=B.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=B.__PosthogExtensions__)==null||(a=a.integrations)==null||(a=a[l])==null||a.stop())};for(var i of Object.entries((r=this._instance.config.integrations)!==null&&r!==void 0?r:{})){var r;n()}}}class Fm{constructor(e,n){this.rt=e,this.nn=n,this.sn=new Map,this.an=!1}add(e){var n=this;return se((function*(){if(n.an)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(n.sn.has(e.name))throw new Error('Browser extension "'+e.name+'" is already registered');n.sn.set(e.name,e);try{var i=e.setup(n.nn);i&&(yield i)}catch(s){var r=n.sn.get(e.name)===e;r&&n.sn.delete(e.name),n.rt.error('Failed to set up browser extension "'+e.name+'"',s),r&&n.ln(e)}}))()}dispose(){if(!this.an){this.an=!0;var e=Array.from(this.sn.values()).reverse();for(var n of(this.sn.clear(),e))this.ln(n)}}ln(e){try{var n=e.dispose==null?void 0:e.dispose();n&&je(n.then)&&n.then(void 0,(i=>{this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}))}catch(i){this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}}}class Rm{constructor(e){this._instance=e}initialize(){}get(e){var n=this._instance.persistence;if(typeof e=="string")return n?.get_property(e);var i={};for(var r of e){var s=n?.get_property(r);C(s)||(i[r]=s)}return i}set(e,n){var i;(i=this._instance.persistence)==null||i.register(typeof e=="string"?{[e]:n}:e)}remove(e){var n;(n=this._instance.persistence)==null||n.unregister(e)}}var iu="extensionsRemoteConfig";class Tm{constructor(e){this.an=!1,this.instance=e,this.rt=A,this.un=e.hn,this.kv=new Rm(e),this.onEvent=n=>br(this.instance.on("eventCaptured",(i=>{try{n({event:i.event,properties:i.properties})}catch(r){this.rt.error("Browser extension event listener failed",r)}}))),this.onRemoteConfig=n=>{if(this.an)return br((()=>{}));var i=s=>{try{n(s)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},r=this.instance.dn.on(iu,i);return this.un&&i(this.un),br(r)},this.vn=new Fm(A.createLogger("[BrowserExtensions]"),this)}get logger(){return this.rt}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return(e=this.instance.get_property(Yi))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(Yi);return typeof e=="string"?e:void 0}get library(){return{name:ne.LIB_NAME,version:ne.LIB_VERSION}}get initialPersonProperties(){var e,n;return(e=(n=this.instance.persistence)==null?void 0:n.get_initial_props())!==null&&e!==void 0?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,n,i,r,s=(e=this.instance.sessionManager)==null?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:(n=s?.sessionId)!==null&&n!==void 0?n:"",windowId:(i=s?.windowId)!==null&&i!==void 0?i:"",sessionStartTimestamp:(r=s?.sessionStartTimestamp)!==null&&r!==void 0?r:0}}catch{return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get projectToken(){return this.instance.config.token}add(e){return this.vn.add(e)}capture(e,n,i){var r=this;return se((function*(){i?r.instance.capture(e,n,{timestamp:i.timestamp,uuid:i.uuid,$set:i.set,$set_once:i.setOnce}):r.instance.capture(e,n)}))()}registerDynamicEventProperties(e){return br(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(iu,e))}sendRequest(e,n){var i=this;return se((function*(){var r;n===void 0&&(n={});var s=i.instance.requestRouter.endpointFor((r=n.target)!==null&&r!==void 0?r:"api",e),o={method:n.method,url:n.query?ks(s,n.query):s,data:n.body,headers:n.headers,timeout:n.timeoutMs,fireCallbackOnDrop:!0,transport:n.transport,compression:n.compression,timestampMode:n.sentAt};return n.transport==="sendBeacon"?(i.instance._send_request(o),{statusCode:202}):new Promise((a=>{o.callback=a,i.instance._send_request(o)}))}))()}dispose(){this.an||(this.an=!0,this.vn.dispose())}}var Wi={},Ro=0,us=()=>{},ru='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',xi="Surveys module not available",su="sanitize_properties is deprecated. Use before_send instead",Yf="Invalid value for property_denylist config: ",$m=["token","distinct_id",tf],Gn="posthog",Jf=!gm&&Ge?.indexOf("MSIE")===-1&&Ge?.indexOf("Mozilla")===-1,To=t=>{var e;return I({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:Mg(P?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:us,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:t??"unset",__preview_deferred_init_extensions:!1,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:me&&X(me?.search)&&me.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disableDeviceModel:!1,disable_external_dependency_loading:!1,strict_script_versioning:!1,enable_recording_console_log:void 0,secure_cookie:(w==null||(e=w.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(n){A.error("Bad HTTP status: "+n.statusCode+" "+n.text)},get_device_id:n=>n,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:pa,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:Sa},error_tracking:{},_onCapture:us},(n=>({rageclick:n&&n>="2026-05-30"?{content_ignorelist:Vg,ignore_text_selection:!0}:!n||"2025-11-30">n||{content_ignorelist:!0},capture_pageview:!n||"2025-05-24">n||"history_change",session_recording:n&&n>="2026-06-25"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6},streamNetworkBody:!0}:n&&n>="2026-05-30"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6}}:n&&n>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:n&&n>="2026-01-30"?"head":"body",internal_or_test_user_hostname:n&&n>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:n&&n>="2026-05-30"?250:0,split_storage:!(!n||"2026-05-30">n),detect_google_search_app:!(!n||"2026-05-30">n),disable_capture_url_hashes:!(!n||"2026-06-25">n)}))(t))},Mm=[["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"]],ou=t=>{var e={};for(var n of Mm){var i=n[0],r=n[1];C(t[i])||(e[r]=t[i])}var s=fe({},e,t),o=t.__preview_external_dependency_versioned_paths;return C(o)||(C(t.strict_script_versioning)&&(s.strict_script_versioning=!!o),X(o)&&C(t.asset_host)&&(s.asset_host=o)),U(t.property_blacklist)&&(C(t.property_denylist)?s.property_denylist=t.property_blacklist:U(t.property_denylist)?s.property_denylist=[...t.property_blacklist,...t.property_denylist]:A.error(Yf+t.property_denylist)),s};class Lm{constructor(){this.__forceAllowLocalhost=!1}get fn(){return this.__forceAllowLocalhost}set fn(e){A.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class Ze{pn(e,n){if(e){var i=this.sn.indexOf(e);i!==-1&&this.sn.splice(i,1)}return this.sn.push(n),n.initialize==null||n.initialize(),n}gn(){return this.config.cookieless_mode===Wt||this.config.cookieless_mode===kn&&this.consent.isRejected()}get decideEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){var e;this.webPerformance=new Lm,this.mn=!1,this.version=ne.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new gl,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=To(),this.SentryIntegration=em,this.sentryIntegration=i=>(function(r,s){var o=wf(r,s);return{name:yf,processEvent:a=>o(a)}})(this,i),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.wn=!1,this.kn=null,this.xn=null,this.Sn=null,this.scrollManager=new bm(this),this.pageViewManager=new qc(this),this.rateLimiter=new cm(this),this.requestRouter=new xm(this),this.consent=new Ug(this),this.externalIntegrations=new Pm(this);var n=(e=Ze.__defaultExtensionClasses)!==null&&e!==void 0?e:{};this.featureFlags=n.featureFlags&&new n.featureFlags(this),this.toolbar=n.toolbar&&new n.toolbar(this),this.surveys=n.surveys&&new n.surveys(this),this.conversations=n.conversations&&new n.conversations(this),this.logs=n.logs&&new n.logs(this),this.metrics=n.metrics&&new n.metrics(this),this.experiments=n.experiments&&new n.experiments(this),this.exceptions=n.exceptions&&new n.exceptions(this),this.people={set:(i,r,s)=>{var o=X(i)?{[i]:r}:i;this.setPersonProperties(o),s?.({})},set_once:(i,r,s)=>{var o=X(i)?{[i]:r}:i;this.setPersonProperties(void 0,o),s?.({})}},this.on("eventCaptured",(i=>A.info('send "'+i?.event+'"',i)))}init(e,n,i){if(i&&i!==Gn){var r,s=(r=Wi[i])!==null&&r!==void 0?r:new Ze;return s._init(e,n,i),Wi[i]=s,Wi[Gn][i]=s,s}return this._init(e,n,i)}_init(e,n,i){var r,s;n===void 0&&(n={});var o,a=X(e)?e.trim():"";if(!a)return A.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return a!==((o=this.config)==null?void 0:o.token)?console.warn("[PostHog.js]","You have already initialized PostHog with a different project token! Re-initializing is a no-op, so events will keep going to the project this instance was initialized with. To capture into a second project, load PostHog once, then initialize a named instance after the SDK has loaded, e.g. posthog.init('"+a+"', { ... }, 'project2')"):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=To(n.defaults),n.debug=this.Cn(n.debug),this.Mn=n,this.Tn=[],n.person_profiles?this.xn=n.person_profiles:n.process_person&&(this.xn=n.process_person);var l=To(n.defaults),u=ou(n),c=fe({},l,u,{name:i,token:a});he(l.rageclick)&&he(u.rageclick)&&(c.rageclick=fe({},l.rageclick,u.rageclick)),he(l.session_recording)&&he(u.session_recording)&&(c.session_recording=fe({},l.session_recording,u.session_recording)),this.set_config(c),this.config.on_xhr_error&&A.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=n.disable_compression?void 0:Ue.GZipJS;var d=this.En();if(this.persistence=new xo(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new xo(I({},this.config,{persistence:"sessionStorage"}),d,!1),this.bn="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&be.N()){var f=be.H(this.bn);U(f)&&f.forEach((k=>{X(k)&&this.yn.add(k)}))}else be.q(this.bn);var h=I({},this.persistence.props),p=I({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new _m((k=>this.Pn(k)),this.config.request_queue_config),this.Rn=new wm(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new tu(this),this.sessionPropsManager=new eu(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((k,T,x)=>{(x!=null&&x.activityTimeout||x!=null&&x.sessionPastMaximumLength||x!=null&&x.crossTabAdoption)&&this.An()}))),this.Fn(),this.config.__preview_deferred_init_extensions?(A.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Ln(g)}),0)):(A.info("Initializing extensions synchronously"),this.Ln(g)),ne.DEBUG=ne.DEBUG||this.config.debug,ne.DEBUG&&A.info("Starting in debug mode",{this:this,config:n,thisC:I({},this.config),p:h,s:p}),!this.config.identity_distinct_id||(r=n.bootstrap)!=null&&r.distinctID||(n.bootstrap=I({},n.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((s=n.bootstrap)==null?void 0:s.distinctID)!==void 0){var m=n.bootstrap.distinctID,v=this.get_distinct_id(),E=this.persistence.get_property(at);if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&E===Un)this.identify(m);else if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&E===vn)A.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{var S=this.config.get_device_id(Ht()),_=n.bootstrap.isIdentifiedID?S:m;this.persistence.set_property(at,n.bootstrap.isIdentifiedID?vn:Un),this.register({distinct_id:m,$device_id:_})}}if(g)this.register_once({distinct_id:mr,$device_id:null},"");else if(!this.get_distinct_id()){var b=this.config.get_device_id(Ht());this.register_once({distinct_id:b,$device_id:b},""),this.persistence.set_property(at,Un)}return ve(w,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),n.segment?(function(k,T){var x=k.config.segment;if(!x)return T();(function(F,$){var O=F.config.segment;if(!O)return $();var L=K=>{var V=()=>K.anonymousId()||Ht();F.config.get_device_id=V,K.id()&&(F.register({distinct_id:K.id(),$device_id:V()}),F.persistence.set_property(at,vn)),$()},N=O.user();"then"in N&&je(N.then)?N.then(L):L(N)})(k,(()=>{x.register((F=>{typeof Promise<"u"&&Promise.resolve||Eo.warn("This browser does not have Promise support, and can not use the segment integration");var $=(O,L)=>{if(!L)return O;O.event.userId||O.event.anonymousId===F.get_distinct_id()||(Eo.info("No userId set, resetting PostHog"),F.reset()),O.event.userId&&O.event.userId!==F.get_distinct_id()&&(Eo.info("UserId set, identifying with PostHog"),F.identify(O.event.userId));var N=F.calculateEventProperties(L,O.event.properties);return O.event.properties=Object.assign({},N,O.event.properties),O};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:O=>$(O,O.event.event),page:O=>$(O,Vn),identify:O=>$(O,yo),screen:O=>$(O,"$screen")}})(k)).then((()=>{T()}))}))})(this,(()=>this.On())):this.On(),je(this.config._onCapture)&&this.config._onCapture!==us&&(A.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(k=>this.config._onCapture(k.event,k)))),this.config.ip&&A.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this.config.disableDeviceModel||(function(){return Wf.apply(this,arguments)})().then((k=>{k&&this.register({[vo]:k})})).catch(us),this}Fn(){var e,n,i,r,s,o,a=(e=(n=this.config.__extensionClasses)==null?void 0:n.featureFlags)!==null&&e!==void 0?e:(i=Ze.__defaultExtensionClasses)==null?void 0:i.featureFlags;a&&(this.featureFlags&&this.featureFlags instanceof a||((r=this.Dn)==null||r.call(this),this.Dn=void 0,this.featureFlags=new a(this)),je(this.featureFlags.onReloading)&&je(this.featureFlags.setup)?this.Dn||(this.Dn=this.featureFlags.onReloading((()=>{this.dn.emit("featureFlagsReloading",!0)})),this.$n().add(this.featureFlags)):(s=(o=this.featureFlags).initialize)==null||s.call(o))}Ln(e){var n,i,r,s,o,a,l,u=performance.now(),c=I({},Ze.__defaultExtensionClasses,this.config.__extensionClasses),d=[];c.exceptions&&this.sn.push(this.exceptions=(n=this.exceptions)!==null&&n!==void 0?n:new c.exceptions(this)),c.historyAutocapture&&this.sn.push(this.historyAutocapture=new c.historyAutocapture(this)),c.tracingHeaders&&this.sn.push(this.tracingHeaders=new c.tracingHeaders(this)),c.siteApps&&this.sn.push(this.siteApps=new c.siteApps(this)),c.sessionRecording&&!e&&this.sn.push(this.sessionRecording=new c.sessionRecording(this)),this.config.disable_scroll_properties||d.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),c.autocapture&&this.sn.push(this.autocapture=new c.autocapture(this)),c.surveys&&this.sn.push(this.surveys=(i=this.surveys)!==null&&i!==void 0?i:new c.surveys(this)),c.logs&&this.sn.push(this.logs=(r=this.logs)!==null&&r!==void 0?r:new c.logs(this)),c.metrics&&this.sn.push(this.metrics=(s=this.metrics)!==null&&s!==void 0?s:new c.metrics(this)),c.conversations&&this.sn.push(this.conversations=(o=this.conversations)!==null&&o!==void 0?o:new c.conversations(this)),c.productTours&&this.sn.push(this.productTours=new c.productTours(this)),c.heatmaps&&this.sn.push(this.heatmaps=new c.heatmaps(this)),c.webVitalsAutocapture&&this.sn.push(this.webVitalsAutocapture=new c.webVitalsAutocapture(this)),c.exceptionObserver&&this.sn.push(this.exceptionObserver=new c.exceptionObserver(this)),c.deadClicksAutocapture&&this.sn.push(this.deadClicksAutocapture=new c.deadClicksAutocapture(this,Qg)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((f=>{f.initialize&&d.push((()=>{f.initialize==null||f.initialize()}))})),d.push((()=>{if(this.Nn){var f=this.Nn;this.Nn=void 0,this.sn.forEach((h=>h.onRemoteConfig==null?void 0:h.onRemoteConfig(f)))}})),this.qn(d,u)}qn(e,n){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,n)}),0);var i=e.shift();if(i)try{i()}catch(s){A.error("Error initializing extension:",s)}}var r=Math.round(performance.now()-n);this.register_for_session({[nf]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[rf]:r}),this.config.__preview_deferred_init_extensions&&A.info("PostHog extensions initialized ("+r+"ms)")}Zi(e){var n;if(!P||!P.body)return A.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.Zi(e)}),500);if(this.config.__preview_deferred_init_extensions&&(this.Nn=e),this.hn=e,this.compression=void 0,e.ok){var i,r=e.config;r.supportedCompression&&!this.config.disable_compression&&(this.compression=j(r.supportedCompression,Ue.GZipJS)?Ue.GZipJS:j(r.supportedCompression,Ue.Base64)?Ue.Base64:void 0),(i=r.analytics)!=null&&i.endpoint&&(this.analyticsDefaultEndpoint=r.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:pa}),(n=this.jn)==null||n.handleRemoteConfig(e),this.sn.forEach((s=>s.onRemoteConfig==null?void 0:s.onRemoteConfig(e)))}On(){try{this.config.loaded(this)}catch(i){A.critical("`loaded` function failed",i)}if(this.Bn(),this.config.internal_or_test_user_hostname&&me!=null&&me.hostname){var e=me.hostname,n=this.config.internal_or_test_user_hostname;(typeof n=="string"?e===n:n.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.gn())&&this.Hn()}),1),this.Un=new Ff(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()&&vr(this.__request_queue,(e=>this.Pn(e))),this.__request_queue=[],this.Bn()}_handle_unload(){var e,n,i,r,s;(e=this.surveys)==null||e.handlePageUnload==null||e.handlePageUnload(),(n=this.metrics)==null||n.flush("sendBeacon"),this.config.request_batching?(this.zn()&&this.capture(_o),(i=this.logs)==null||i.flushLogs("sendBeacon"),(r=this.In)==null||r.unload(),(s=this.Rn)==null||s.unload()):this.zn()&&this.capture(_o,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?Jf?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)?e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:429})):(e.transport=e.transport||this.config.api_transport,e.headers=I({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,(C(this.config.disable_beacon)?this.config.__preview_disable_beacon:this.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(n=>{var i,r,s,o=I({},n);o.timeout=o.timeout||6e4;var a,l,u,c,d,f=(i=o.transport)!==null&&i!==void 0?i:"fetch";f==="sendBeacon"&&C(o.compression)&&o.data&&(o.compression=Ue.Base64),o.method==="POST"&&o.data&&(o.timestampMode==="capture-body"?o.data={api_key:(l=(d=(c=U(a=o.data)?a:[a])[0])==null||(u=d.properties)==null?void 0:u.token)!==null&&l!==void 0?l:d?.token,batch:c,sent_at:new Date().toISOString()}:o.timestampMode==="body"&&(o.data=(function(m,v){return v===void 0&&(v=new Date().toISOString()),U(m)?m.map((E=>I({},E,{sent_at:v}))):I({},m,{sent_at:v})})(o.data))),o.url=Qc(o.url,o.method,o.compression,o.timestampMode);var h=Lr.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),p=(r=(s=(function(m,v){for(var E=0;m.length>E;E++)if(m[E].transport===f)return m[E]})(h))==null?void 0:s.method)!==null&&r!==void 0?r:h[0].method;if(!p)throw new Error("No available transport method");var g=m=>{try{p(m)}catch(v){jf(v)?A.warn(v):A.error(v),o.callback==null||o.callback({statusCode:0,error:v})}};f!=="sendBeacon"&&o.data&&o.compression===Ue.GZipJS&&Np&&typeof Promise<"u"&&!Mr?mm(o).then((m=>{g(m)})).catch((m=>{if(yc(m))return Mr=!0,void g(I({},o,{compression:void 0,url:Qc(n.url,n.method,void 0,n.timestampMode)}));(v=>{if(!v||typeof v!="object")return!1;var E="name"in v?String(v.name):"";return yc(v)||E===gd})(m)&&(Mr=!0),g(o)})):p(o)})(I({},e,{callback:n=>{var i,r;this.rateLimiter.checkForLimiting(n),400>n.statusCode||(i=(r=this.config).on_request_error)==null||i.call(r,n),e.callback==null||e.callback(n)}}))):e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:0}))}Pn(e){this.Rn?this.Rn.retriableRequest(e):this._send_request(e)}_execute_array(e){Ro++;try{var n,i=[],r=[],s=[];vr(e,(a=>{if(a)if(U(n=a[0]))s.push(a);else if(je(a))try{a.call(this)}catch(l){A.error("Error executing queued PostHog call",a,l)}else U(a)&&n==="alias"?i.push(a):U(a)&&n.indexOf("capture")!==-1&&je(this[n])?s.push(a):r.push(a)}));var o=function(a,l){vr(a,(function(u){try{if(U(u[0])){var c=l;ie(u,(function(d){c=c[d[0]].apply(c,d.slice(1))}))}else l[u[0]].apply(l,u.slice(1))}catch(d){A.error("Error executing queued PostHog call",u,d)}}))};o(i,this),o(r,this),o(s,this)}finally{Ro--}}push(e){if(Ro>0&&U(e)&&X(e[0])){var n=Ze.prototype[e[0]];je(n)&&n.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,n,i){var r,s,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.In){if(this.is_capturing())if(!C(e)&&X(e)){var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var c=i!=null&&i.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(c==null||!c.isRateLimited){n!=null&&n.$current_url&&!X(n?.$current_url)&&(A.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),n==null||delete n.$current_url),e!=="$exception"||i!=null&&i.Wn||A.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,f=i?.timestamp||d,h=xc(i?.uuid,Ht),p={uuid:h,event:e,properties:this.calculateEventProperties(e,n||{},f,h)};e===Vn&&this.config.__preview_capture_bot_pageviews&&u&&(p.event="$bot_pageview",p.properties.$browser_type="bot"),c&&(p.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&p.properties.$feature_flag_has_experiment===!1&&this.get_property(Zr)===!0;i?.$set&&!g&&(p.$set=i?.$set);var m=i?.$unset;m&&(p.$unset=m);var v,E,S,_=g?void 0:this.Vn(i?.$set_once,e!==Fc,e===yo);if(_&&(p.$set_once=_),i!=null&&i._noTruncate||(s=this.config.properties_string_max_length,o=p,a=L=>X(L)?L.slice(0,s):L,l=new Set,p=(function L(N,K){if(N!==Object(N))return a?a(N):N;if(!l.has(N)){var V;if(l.add(N),U(N))V=[],vr(N,(R=>{V.push(L(R))}));else{var M={};ie(N,((R,Z)=>{l.has(R)||(M[Z]=L(R))})),V=M}return V}})(o)),p.timestamp=f,C(i?.timestamp)||(p.properties.$event_time_override_provided=!0,p.properties.$event_time_override_system_time=d),g&&(p.properties=(function(L,N){N===void 0&&(N=[]);var K={},V=M=>{L[M]!==void 0&&(K[M]=L[M])};return Op.forEach(V),N.forEach(V),K})(p.properties,$m)),e===qt.DISMISSED||e===qt.SENT){var b=n?.[ko.SURVEY_ID],k=n?.[ko.SURVEY_ITERATION];Kf({id:b,current_iteration:k}),p.$set=I({},p.$set,{[(v={id:b,current_iteration:k},E=e===qt.SENT?"responded":"dismissed",S="$survey_"+E+"/"+v.id,v.current_iteration&&v.current_iteration>0&&(S="$survey_"+E+"/"+v.id+"/"+v.current_iteration),S)]:!0})}else e===qt.SHOWN&&(p.$set=I({},p.$set,{[ko.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===lm.SHOWN){var T=n?.[Gc.TOUR_TYPE];T&&(p.$set=I({},p.$set,{[Gc.TOUR_LAST_SEEN_DATE+"/"+T]:new Date().toISOString()}))}var x=I({},p.properties.$set,p.$set);if(Kt(x)||this.setPersonPropertiesForFlags(x),!H(this.config.before_send)){var F=this.Pt(p);if(!F)return;(p=F).uuid=xc(p.uuid,Ht)}this.dn.emit("eventCaptured",p);var $=(r=i?._url)!==null&&r!==void 0?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),O={method:"POST",url:$,data:p,compression:"best-available",timestampMode:i?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test($)?"body":"capture-body",batchKey:i?._batchKey,transport:i?.transport};return!this.config.request_batching||i&&(i==null||!i._batchKey)||i!=null&&i.send_instantly?this.Pn(O):this.In.enqueue(O),p}A.critical("This capture call is ignored due to client rate limiting.")}}else A.error("No event name provided to posthog.capture")}else A.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(n=>e(n.event,n)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new Tm(this)}cn(e){this._n.push(e);var n=!0;return()=>{if(n){n=!1;var i=this._n.indexOf(e);i!==-1&&this._n.splice(i,1)}}}calculateEventProperties(e,n,i,r,s){if(i=i||new Date,!this.persistence||!this.sessionPersistence)return n;var o=s?void 0:this.persistence.remove_event_timer(e),a=I({},n);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.gn()&&(a[tf]=!0),e==="$snapshot"){var l=I({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!X(a.distinct_id)&&!ke(a.distinct_id)||Ko(a.distinct_id))&&A.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=(function(b,k,T,x){var F,$,O,L;if(x===void 0&&(x=!1),!Ge)return{};var N,K=b?[...ri,...k||[]]:[],V=(function(Bn){for(var qe=0;Ec.length>qe;qe++){var Dn=Ec[qe],Mt=Dn[1],Lt=Dn[0].exec(Bn),ut=Lt&&(je(Mt)?Mt(Lt,Bn):Mt);if(ut)return ut}return["",""]})(Ge),M=V[0],R=V[1],Z=(N=typeof navigator<"u"?navigator:void 0)!=null&&N.brave?{brave:!0}:{},Ce={};C(T)||(Ce.detectGoogleSearchApp=T);var oe={},ye=(F=navigator)==null||(F=F.userAgentData)==null?void 0:F.platform,$e=($=navigator)==null?void 0:$.maxTouchPoints,ae=w==null||(O=w.screen)==null?void 0:O.width,Ie=w==null||(L=w.screen)==null?void 0:L.height,Se=w?.devicePixelRatio;C(ye)||(oe.userAgentDataPlatform=ye),C($e)||(oe.maxTouchPoints=$e),C(ae)||(oe.screenWidth=ae),C(Ie)||(oe.screenHeight=Ie),C(Se)||(oe.devicePixelRatio=Se);var De,wt,ge,Je,bt,mn,Re,Pe,$t=fe(cl({$os:M,$os_version:R,$browser:jd(Ge,navigator.vendor,Z,Ce),$device:Sc(Ge),$device_type:(wt=Ge,ge=oe,Pe=Sc(wt),Pe===Ed||Pe===bd||Pe==="Kobo"||Pe==="Kindle Fire"||Pe===Ld?ei:Pe===Gi||Pe===Xn||Pe===Ki||Pe===Jo?"Console":Pe===xd?"Wearable":Pe?rt:ge?.userAgentDataPlatform==="Android"&&((Je=ge?.maxTouchPoints)!==null&&Je!==void 0?Je:0)>0?600>Math.min((bt=ge?.screenWidth)!==null&&bt!==void 0?bt:0,(mn=ge?.screenHeight)!==null&&mn!==void 0?mn:0)/((Re=ge?.devicePixelRatio)!==null&&Re!==void 0?Re:1)?rt:ei:"Desktop"),$timezone:Pf(),$timezone_offset:sm()}),{$current_url:Zi(x?fn(me?.href):me?.href,K,Xi),$host:me?.host,$pathname:me?.pathname,$raw_user_agent:Ge.length>1e3?Ge.substring(0,997)+"...":Ge,$browser_version:ng(Ge,navigator.vendor,Z,Ce),$browser_language:Vc(),$browser_language_prefix:(De=Vc(),typeof De=="string"?De.split("-")[0]:void 0),$screen_height:w?.screen.height,$screen_width:w?.screen.width,$viewport_height:w?.innerHeight,$viewport_width:w?.innerWidth,$lib:ne.LIB_NAME,$lib_version:ne.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return ne.SDK_DIST_CHANNEL&&($t.$sdk_dist_channel=ne.SDK_DIST_CHANNEL),$t})(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties,this.config.detect_google_search_app,this.config.disable_capture_url_hashes);if(this.sessionManager){var d=this.sessionManager.checkAndGetSessionAndWindowId(s,i.getTime()),f=d.windowId;a.$session_id=d.sessionId,a.$window_id=f}this.sessionPropsManager&&fe(a,this.sessionPropsManager.getSessionProps());try{var h;this.sessionRecording&&fe(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(h=this.Rn)==null?void 0:h.length}catch(b){a.$sdk_debug_error_capturing_properties=String(b)}if(this.requestRouter.region===xa&&(a.$lib_custom_api_host=this.config.api_host),u=e!==Vn||s?e!==_o||s?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(i):this.pageViewManager.doPageView(i,r),a=fe(a,u),e===Vn&&P&&(a.title=P.title),!C(o)){var p=i.getTime()-o;a.$duration=parseFloat((p/1e3).toFixed(3))}Ge&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();ie(["$referrer","$referring_domain"],(b=>{b in g&&delete m[b]}));var v={};if(this._n.length>0)for(var E of this._n.slice())try{fe(v,E())}catch(b){A.error("Failed to produce browser extension event properties",b)}(a=fe({},c,g,m,I({},v,a))).$is_identified=this._isIdentified(),U(this.config.property_denylist)?ie(this.config.property_denylist,(function(b){delete a[b]})):A.error(Yf+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var S=this.config.sanitize_properties;S&&(A.error(su),a=S(a,e));var _=this.Zn();return a.$process_person_profile=_,_&&!s&&this.Gn("_calculate_event_properties"),a}Vn(e,n,i){var r;if(n===void 0&&(n=!0),i===void 0&&(i=!1),!this.persistence||!this.Zn()||this.mn&&!i)return e;var s=this.persistence.get_initial_props(),o=(r=this.sessionPropsManager)==null?void 0:r.getSetOnceProps(),a=fe({},s,o||{},e||{}),l=this.config.sanitize_properties;return l&&(A.error(su),a=l(a,"$set_once")),n&&(this.mn=!0),Kt(a)?void 0:a}register(e,n){var i;(i=this.persistence)==null||i.register(e,n)}register_once(e,n,i){var r;(r=this.persistence)==null||r.register_once(e,n,i)}register_for_session(e){var n;(n=this.sessionPersistence)==null||n.register(e),Object.keys(e).forEach((i=>this.yn.add(i))),this.Qn()}unregister(e){var n;(n=this.persistence)==null||n.unregister(e)}unregister_for_session(e){var n;(n=this.sessionPersistence)==null||n.unregister(e),this.yn.delete(e),this.Qn()}Kn(e,n){this.register({[e]:n})}An(){this.yn.forEach((e=>{var n;(n=this.sessionPersistence)==null||n.unregister(e)})),this.yn.clear(),this.Qn()}Qn(){var e;if(this.bn)if(this.config.persistence==="memory"||(e=this.sessionPersistence)!=null&&e.xi||!be.N())be.q(this.bn);else{var n=[];this.yn.forEach((i=>n.push(i))),n.length>0?be.F(this.bn,n):be.q(this.bn)}}getFeatureFlag(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlag(e,n)}getFeatureFlagPayload(e){var n;return(n=this.featureFlags)==null?void 0:n.getFeatureFlagPayload(e)}getFeatureFlagResult(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlagResult(e,n)}getAllFeatureFlags(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.getAllFeatureFlags())!==null&&e!==void 0?e:[]}isFeatureEnabled(e,n){var i,r;return(i=(r=this.featureFlags)==null?void 0:r.isFeatureEnabled(e,n))!==null&&i!==void 0?i:n?.defaultValue}reloadFeatureFlags(){var e;(e=this.featureFlags)==null||e.reloadFeatureFlags()}updateFlags(e,n,i){var r;(r=this.featureFlags)==null||r.updateFlags(e,n,i)}updateEarlyAccessFeatureEnrollment(e,n,i){var r;(r=this.featureFlags)==null||r.updateEarlyAccessFeatureEnrollment(e,n,i)}getEarlyAccessFeatures(e,n,i){var r;return n===void 0&&(n=!1),(r=this.featureFlags)==null?void 0:r.getEarlyAccessFeatures(e,n,i)}on(e,n){return this.dn.on(e,n)}onFeatureFlags(e){return this.featureFlags?this.featureFlags.onFeatureFlags(e):(e([],{},{errorsLoading:!0}),()=>{})}onSurveysLoaded(e){return this.surveys?this.surveys.onSurveysLoaded(e):(e([],{isLoaded:!1,error:xi}),()=>{})}onSessionId(e){var n,i;return(n=(i=this.sessionManager)==null?void 0:i.onSessionId(e))!==null&&n!==void 0?n:()=>{}}getSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getSurveys(e,n):e([],{isLoaded:!1,error:xi})}getActiveMatchingSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,n):e([],{isLoaded:!1,error:xi})}renderSurvey(e,n){var i;(i=this.surveys)==null||i.renderSurvey(e,n)}displaySurvey(e,n){var i;n===void 0&&(n=km),(i=this.surveys)==null||i.displaySurvey(e,n)}cancelPendingSurvey(e){var n;(n=this.surveys)==null||n.cancelPendingSurvey(e)}canRenderSurvey(e){var n,i;return(n=(i=this.surveys)==null?void 0:i.canRenderSurvey(e))!==null&&n!==void 0?n:{visible:!1,disabledReason:xi}}canRenderSurveyAsync(e,n){var i,r;return n===void 0&&(n=!1),(i=(r=this.surveys)==null?void 0:r.canRenderSurveyAsync(e,n))!==null&&i!==void 0?i:Promise.resolve({visible:!1,disabledReason:xi})}Jn(e){return!e||Ko(e)?(A.critical("Unique user id has not been set in posthog.identify"),!1):e===mr?(A.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.'),!1):!["distinct_id","distinctid"].includes(e.toLowerCase())&&!["undefined","null"].includes(e.toLowerCase())||(A.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.'),!1)}identify(e,n,i){if(!this.__loaded||!this.persistence)return A.uninitializedWarning("posthog.identify");if(ke(e)&&(e=e.toString(),A.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.Jn(e)&&this.Gn("posthog.identify")){var r=this.get_distinct_id();this.register({$user_id:e}),this.get_property(Yi)||this.register_once({$had_persisted_distinct_id:!0,$device_id:r},""),e!==r&&e!==this.get_property(Fi)&&(this.unregister(Fi),this.register({distinct_id:e}));var s,o=(this.persistence.get_property(at)||Un)===Un,a=e!==r,l=!a&&o;if(a&&o)this.persistence.set_property(at,vn),this.setPersonPropertiesForFlags({$set:n||{},$set_once:i||{}},!1),this.capture(yo,{distinct_id:e,$anon_distinct_id:r},{$set:n||{},$set_once:i||{}}),this.Sn=Fo(e,n,i),(s=this.featureFlags)==null||s.setAnonymousDistinctId(r);else if(l){this.persistence.set_property(at,vn);var u=n||{},c=i||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=Fo(e,n,i)}else(n||i)&&this.setPersonProperties(n,i);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Cn)):l&&(n||i)&&this.reloadFeatureFlags()}}setPersonProperties(e,n){if((e||n)&&this.Gn("posthog.setPersonProperties")){var i=Fo(this.get_distinct_id(),e,n);this.Sn!==i?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:n||{}},!0),this.capture("$set",{$set:e||{},$set_once:n||{}}),this.Sn=i):A.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}unsetPersonProperties(e){var n,i=(U(e)?e:[e]).filter((r=>X(r)&&r.length>0));i.length!==0&&this.Gn("posthog.unsetPersonProperties")&&((n=this.featureFlags)==null||n.unsetPersonPropertiesForFlags(i,!0),this.capture("$set",{$unset:i}),this.Sn=null)}group(e,n,i){if(e&&n){var r=this.getGroups(),s=r[e]!==n;if(s&&this.resetGroupPropertiesForFlags(e),this.register({$groups:I({},r,{[e]:n})}),s||i){var o={$group_type:e,$group_key:n};i&&(o.$group_set=i),this.capture(Fc,o)}i&&this.setGroupPropertiesForFlags({[e]:i}),s&&!i&&this.reloadFeatureFlags()}else A.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),(i=this.featureFlags)==null||i.setPersonPropertiesForFlags(e,n)}resetPersonPropertiesForFlags(e){var n;e===void 0&&(e=!0),(n=this.featureFlags)==null||n.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((i=this.featureFlags)==null||i.setGroupPropertiesForFlags(e,n))}resetGroupPropertiesForFlags(e){var n;(n=this.featureFlags)==null||n.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,n){var i,r,s,o,a,l,u,c,d,f;if(n===void 0&&(n=!1),A.info("reset"),!this.__loaded)return A.uninitializedWarning("posthog.reset");var h,p=this.get_property(Yi),g=this.get_property(vo),m=this.get_property(An),v=this.is_capturing();if(this.consent.reset(),n||!v||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after."),(i=this.persistence)==null||i.clear(),(r=this.sessionPersistence)==null||r.clear(),this.yn.clear(),this.Qn(),C(m)||(h=this.persistence)==null||h.register({[An]:m}),(s=this.surveys)==null||s.reset(),(o=this.Un)==null||o.stop(),(a=this.featureFlags)==null||a.reset(),(l=this.conversations)==null||l.reset(),(u=this.logs)==null||u.reset(),(c=this.metrics)==null||c.reset(),(d=this.persistence)==null||d.set_property(at,Un),(f=this.sessionManager)==null||f.resetSessionId(),this.Sn=null,this.config.cookieless_mode===Wt)this.register_once({distinct_id:mr,$device_id:null},"");else{var E=this.config.get_device_id(Ht());this.register_once({distinct_id:E,$device_id:e?E:p},""),e||C(g)||this.register({[vo]:g})}this.register({$last_posthog_reset:new Date().toISOString()},1),delete this.config.identity_distinct_id,delete this.config.identity_hash,this.reloadFeatureFlags()}shutdown(e){var n=this;return se((function*(){var i,r,s,o,a,l,u;if(n.__loaded){(i=n.Un)==null||i.stop(),(r=n.jn)==null||r.dispose(),(s=n.sessionRecording)==null||s.dispose(),(o=n.logs)==null||o.flushLogs("sendBeacon"),(a=n.metrics)==null||a.flush("sendBeacon"),(l=n.In)==null||l.unload(),(u=n.Rn)==null||u.unload();try{var c;(c=n.featureFlags)==null||c.destroy()}catch(d){A.error("Error while destroying feature flags",d)}}else A.uninitializedWarning("posthog.shutdown")}))()}setIdentity(e,n){var i;this.config.identity_distinct_id=e,this.config.identity_hash=n,this.alias(e),(i=this.conversations)==null||i.Xn()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,(e=this.conversations)==null||e.ts()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,n;return(e=(n=this.sessionManager)==null?void 0:n.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var n=this.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.sessionStartTimestamp,r=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+n.sessionId);if(e!=null&&e.withTimestamp&&i){var s,o=(s=e.timestampLookBack)!==null&&s!==void 0?s:10;if(!i)return r;r+="?t="+Math.max(Math.floor((new Date().getTime()-i)/1e3)-o,0)}return r}alias(e,n){return e===this.get_property(Yd)?(A.critical("Attempting to create alias for existing People user - aborting."),-2):this.Gn("posthog.alias")?(C(n)&&(n=this.get_distinct_id()),e!==n?(this.Kn(Fi,e),this.capture("$create_alias",{alias:e,distinct_id:n})):(A.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var n=I({},this.config);if(he(e)){var i,r,s,o,a,l,u,c,d,f,h,p;fe(this.config,ou(e));var g=this.En();(i=this.persistence)==null||i.update_config(this.config,n,g),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new xo(I({},this.config,{persistence:"sessionStorage"}),g,!1);var m=this.Cn(this.config.debug);mt(m)&&(this.config.debug=m),mt(this.config.debug)&&(this.config.debug?(ne.DEBUG=!0,le.N()&&le.F("ph_debug",!0),A.info("set_config",{config:e,oldConfig:n,newConfig:I({},this.config)})):(ne.DEBUG=!1,le.N()&&le.q("ph_debug"))),(r=this.featureFlags)==null||r.updateConfig==null||r.updateConfig(this.config,this.Qi()),(s=this.exceptionObserver)==null||s.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(f=this.deadClicksAutocapture)==null||f.startIfEnabledOrStop(),(h=this.surveys)==null||h.loadIfEnabled(),this.es(),(p=this.externalIntegrations)==null||p.startIfEnabledOrStop()}}_overrideSDKInfo(e,n){ne.LIB_NAME=e,ne.LIB_VERSION=n}startSessionRecording(e){var n,i,r,s,o,a=e===!0,l={sampling:a||!(e==null||!e.sampling),linked_flag:a||!(e==null||!e.linked_flag),url_trigger:a||!(e==null||!e.url_trigger),event_trigger:a||!(e==null||!e.event_trigger)};Object.values(l).some(Boolean)&&((n=this.sessionManager)==null||n.checkAndGetSessionAndWindowId(),l.sampling&&((i=this.sessionRecording)==null||i.overrideSampling()),l.linked_flag&&((r=this.sessionRecording)==null||r.overrideLinkedFlag()),l.url_trigger&&((s=this.sessionRecording)==null||s.overrideTrigger("url")),l.event_trigger&&((o=this.sessionRecording)==null||o.overrideTrigger("event"))),this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,n){if(this.exceptions){var i=new Error("PostHog syntheticException"),r=this.exceptions.buildProperties(e,{handled:!0,syntheticException:i});return this.exceptions.sendExceptionEvent(I({},r,n))}}addExceptionStep(e,n){var i;(i=this.exceptions)==null||i.addExceptionStep(e,n)}captureLog(e){var n;(n=this.logs)==null||n.captureLog(e)}get logger(){var e,n;return(e=(n=this.logs)==null?void 0:n.logger)!==null&&e!==void 0?e:Ze.rs}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var n,i;return(n=(i=this.toolbar)==null?void 0:i.loadToolbar(e))!==null&&n!==void 0&&n}get_property(e){var n;return(n=this.persistence)==null?void 0:n.props[e]}getSessionProperty(e){var n;return(n=this.sessionPersistence)==null?void 0:n.props[e]}toString(){var e,n=(e=this.config.name)!==null&&e!==void 0?e:Gn;return n!==Gn&&(n=Gn+"."+n),n}_isIdentified(){var e,n;return((e=this.persistence)==null?void 0:e.get_property(at))===vn||((n=this.sessionPersistence)==null?void 0:n.get_property(at))===vn}Zn(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles===pa&&!this._isIdentified()&&Kt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[Fi])&&((n=this.persistence)==null||(n=n.props)==null||!n[es]))}zn(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Zn()||this.Gn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.Gn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}Gn(e){return this.config.person_profiles==="never"?(A.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Kn(es,!0),!0)}En(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut();return this.config.disable_persistence||e&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!==kn)}es(){var e,n,i,r,s=this.En();return((e=this.persistence)==null?void 0:e.xi)!==s&&((i=this.persistence)==null||i.set_disabled(s)),((n=this.sessionPersistence)==null?void 0:n.xi)!==s&&((r=this.sessionPersistence)==null||r.set_disabled(s)),s&&(this.yn.clear(),this.Qn()),s}opt_in_capturing(e){var n;if(this.config.cookieless_mode!==Wt){if(this.gn()){var i,r,s,o,a;this.Yn(!0,!0),(i=this.sessionManager)==null||i.destroy(),(r=this.pageViewManager)==null||r.destroy(),this.sessionManager=new tu(this),this.pageViewManager=new qc(this),this.persistence&&(this.sessionPropsManager=new eu(this,this.sessionManager,this.persistence));var l,u=(s=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&s!==void 0?s:(a=Ze.__defaultExtensionClasses)==null?void 0:a.sessionRecording;u&&(this.sessionRecording=this.pn(this.sessionRecording,new u(this)),this.hn&&((l=this.sessionRecording)==null||l.onRemoteConfig==null||l.onRemoteConfig(this.hn)))}var c,d;this.consent.optInOut(!0),this.es(),this.Bn(),(n=this.sessionRecording)==null||n.startIfEnabledOrStop(),this.config.cookieless_mode==kn&&((c=this.surveys)==null||c.loadIfEnabled()),(C(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((d=e?.captureEventName)!==null&&d!==void 0?d:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hn()}else A.warn(ru)}opt_out_capturing(){var e,n,i;this.config.cookieless_mode!==Wt?(this.config.cookieless_mode===kn&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===kn&&(this.register({distinct_id:mr,$device_id:null}),(e=this.sessionRecording)==null||e.stopRecording(),this.sessionRecording=void 0,(n=this.sessionManager)==null||n.destroy(),(i=this.pageViewManager)==null||i.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.Hn(),this.Bn())):A.warn(ru)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===Wt||(this.config.cookieless_mode===kn?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return He?Hf(He,this.config.custom_blocked_useragents):void 0}Hn(){P&&(P.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(Vn,{title:P.title},{send_instantly:!0}),this.kn&&(P.removeEventListener(ts,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),ve(P,ts,this.kn)))}debug(e){e===!1?(w?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(w?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}Qi(){var e=this.Mn||{};return"advanced_disable_flags"in e?!!e.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(A.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(function(n,i,r,s,o){var a=i in n&&!H(n[i]),l=r in n&&!H(n[r]);return a?n[i]:!!l&&(o&&o.warn("Config field '"+r+"' is deprecated. Please use '"+i+"' instead. The old field will be removed in a future major version."),n[r])})(e,"advanced_disable_flags","advanced_disable_decide",0,A)}Pt(e){var n;if(H(this.config.before_send))return e;var i=Object.keys((n=e.properties)!==null&&n!==void 0?n:{}).filter(zp),r=U(this.config.before_send)?this.config.before_send:[this.config.before_send],s=e;for(var o of r){if(s=o(s),H(s)){var a="Event '"+e.event+"' was rejected in beforeSend function";return Wp(e.event)?A.warn(a+". This can cause unexpected behavior."):A.info(a),null}s.properties&&!Kt(s.properties)||A.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}for(var l of i)if(s.properties&&H(s.properties[l]))return A.warn("Event '"+e.event+"' had its '"+l+"' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped."),null;return s}getPageViewId(){var e;return(e=this.pageViewManager.ui)==null?void 0:e.pageViewId}captureTraceFeedback(e,n){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:n})}captureTraceMetric(e,n,i){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:n,$ai_metric_value:String(i)})}Cn(e){var n=mt(e)&&!e,i=le.N()&&le.P("ph_debug")==="true";return!n&&(!!i||e)}}Ze.__defaultExtensionClasses={},Ze.rs=(()=>{var t=()=>{};return{trace:t,debug:t,info:t,warn:t,error:t,fatal:t}})(),(function(t,e){for(var n=0;e.length>n;n++)t.prototype[e[n]]=Tg(t.prototype[e[n]])})(Ze,["identify"]);class au{constructor(e){this.disabled=e===!1;var n=he(e)?e:{};this.thresholdPx=n.threshold_px||30,this.timeoutMs=n.timeout_ms||1e3,this.clickCount=n.click_count||3,this.clicks=[]}isRageClick(e,n,i){if(this.disabled)return!1;var r=this.clicks[this.clicks.length-1];if(r&&Math.abs(e-r.x)+Math.abs(n-r.y)i-r.timestamp){if(this.clicks.push({x:e,y:n,timestamp:i}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:n,timestamp:i}];return!1}}var $o="$copy_autocapture",Mo=pe("[AutoCapture]");function Lo(t,e){return e.length>t?e.slice(0,t)+"...":e}function Nm(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!hn(e));return e}function Om(t,e){var n,i,r=e.e,s=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!hn(t))return{props:{}};for(var c=[t],d=new Set([t]),f=t;f.parentNode&&!et(f,"body")&&ff>c.length;)if(df(f.parentNode)){var h=f.parentNode.host;if(d.has(h))break;d.add(h),c.push(h),f=h}else{if(!hn(f.parentNode)||d.has(f.parentNode))break;d.add(f.parentNode),c.push(f.parentNode),f=f.parentNode}var p,g,m=[],v={},E=!1,S=!1;if(ie(c,(x=>{var F=va(x);if(et(x,"a")){var $=x.getAttribute("href");E=!!(F&&$&&Ui($))&&(u?fn($):$)}j(rs(x),"ph-no-capture")&&(S=!0),m.push((function(L,N,K,V,M){M===void 0&&(M=!1);var R=L.tagName.toLowerCase(),Z={tag_name:R};dl.indexOf(R)>-1&&!K&&(Z.$el_text=R.toLowerCase()==="a"||R.toLowerCase()==="button"?Lo(1024,Hc(L)):Lo(1024,Ji(L)));var Ce=rs(L);Ce.length>0&&(Z.classes=Ce.filter((function(ae){return ae!==""}))),ie(L.attributes,(function(ae){var Ie;if((!vf(L)||["name","id","class","aria-label"].indexOf(ae.name)!==-1)&&(V==null||!V.includes(ae.name))&&!N&&Ui(ae.value)&&(!X(Ie=ae.name)||Ie.substring(0,10)!=="_ngcontent"&&Ie.substring(0,7)!=="_nghost")){var Se=ae.value;ae.name==="class"&&(Se=ul(Se).join(" ")),Z["attr__"+ae.name]=Lo(1024,ae.name==="href"&&M?fn(Se):Se)}}));for(var oe=1,ye=1,$e=L;$e=Nm($e);)oe++,$e.tagName===L.tagName&&ye++;return Z.nth_child=oe,Z.nth_of_type=ye,Z})(x,s,o,a,u));var O=(function(L){if(!va(L))return{};var N={};return ie(L.attributes,(function(K){if(K.name&&K.name.indexOf("data-ph-capture-attribute")===0){var V=K.name.replace("data-ph-capture-attribute-",""),M=K.value;V&&M&&Ui(M)&&(N[V]=M)}})),N})(x);fe(v,O)})),S)return{props:{},explicitNoCapture:S};if(o||(m[0].$el_text=et(t,"a")||et(t,"button")?Hc(t):Ji(t)),E){var _,b;m[0].attr__href=E;var k=(_=ss(E))==null?void 0:_.host,T=w==null||(b=w.location)==null?void 0:b.host;k&&T&&k!==T&&(p=E)}return{props:fe({$event_type:r.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(x){return x.map((F=>{var $,O,L="";if(F.tag_name&&(L+=F.tag_name),F.attr_class)for(var N of(F.attr_class.sort(),F.attr_class))L+="."+N.replace(/"/g,"");var K=I({},F.text?{text:F.text}:{},{"nth-child":($=F.nth_child)!==null&&$!==void 0?$:0,"nth-of-type":(O=F.nth_of_type)!==null&&O!==void 0?O:0},F.href?{href:F.href}:{},F.attr_id?{attr_id:F.attr_id}:{},F.attributes),V={};return $r(K).sort(((M,R)=>M[0].localeCompare(R[0]))).forEach((M=>{var R=M[1];return V[Wc(M[0].toString())]=Wc(R.toString())})),(L+=":")+$r(V).map((M=>M[0]+'="'+M[1]+'"')).join("")})).join(";")})((function(x){return x.map((F=>{var $,O,L={text:($=F.$el_text)==null?void 0:$.slice(0,400),tag_name:F.tag_name,href:(O=F.attr__href)==null?void 0:O.slice(0,2048),attr_class:Zg(F),attr_id:F.attr__id,nth_child:F.nth_child,nth_of_type:F.nth_of_type,attributes:{}};return $r(F).filter((N=>N[0].indexOf("attr__")===0)).forEach((N=>L.attributes[N[0]]=N[1])),L}))})(g)))},(n=m[0])!=null&&n.$el_text?{$el_text:(i=m[0])==null?void 0:i.$el_text}:{},p&&r.type==="click"?{$external_click_url:p}:{},v)}}var Ii=pe("[ExceptionAutocapture]"),lu=()=>{},Bm=pe("[TracingHeaders]"),wn=pe("[Web Vitals]"),cu=9e5,uu="disabled",du="lazy_loading",ki="awaiting_config",Sr="missing_config";pe("[SessionRecording]"),pe("[SessionRecording]");var Ia="[SessionRecording]",Bt=pe(Ia),Dm=pe("[Heatmaps]");function No(t){return he(t)&&"clientX"in t&&"clientY"in t&&ke(t.clientX)&&ke(t.clientY)}var xr=pe("[Product Tours]"),Oo=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(ol))},jm=["$set_once","$set"],Et=pe("[SiteApps]"),fu="Error while initializing PostHog app with config id ";function zn(t,e,n){if(H(t))return!1;switch(n){case"exact":return t===e;case"contains":var i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(i,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}class Um{constructor(e){this.ns=new gl,this.ss=(n,i)=>this.os(n,i)&&this.ls(n,i)&&this.us(n,i)&&this.hs(n,i),this.os=(n,i)=>i==null||!i.event||n?.event===i?.event,this._instance=e,this.ds=new Set,this.vs=new Set}init(){var e,n;C((e=this._instance)==null?void 0:e._addCaptureHook)||(n=this._instance)==null||n._addCaptureHook(((i,r)=>{this.on(i,r)}))}register(e){var n,i;if(!C((n=this._instance)==null?void 0:n._addCaptureHook)&&(e.forEach((o=>{var a,l;(a=this.vs)==null||a.add(o),(l=o.steps)==null||l.forEach((u=>{var c;(c=this.ds)==null||c.add(u?.event||"")}))})),(i=this._instance)!=null&&i.autocapture)){var r,s=new Set;e.forEach((o=>{var a;(a=o.steps)==null||a.forEach((l=>{l!=null&&l.selector&&s.add(l?.selector)}))})),(r=this._instance)==null||r.autocapture.setElementSelectors(s)}}on(e,n){var i;n!=null&&e.length!=0&&(this.ds.has(e)||this.ds.has(n.event))&&this.vs&&((i=this.vs)==null?void 0:i.size)>0&&this.vs.forEach((r=>{this.cs(n,r)&&this.ns.emit("actionCaptured",r.name)}))}fs(e){this.onAction("actionCaptured",(n=>e(n)))}cs(e,n){if(n?.steps==null)return!1;for(var i of n.steps)if(this.ss(e,i))return!0;return!1}onAction(e,n){return this.ns.on(e,n)}ls(e,n){if(n!=null&&n.url){var i,r=e==null||(i=e.properties)==null?void 0:i.$current_url;if(!r||typeof r!="string"||!zn(r,n.url,n.url_matching||"contains"))return!1}return!0}us(e,n){return!!this.ps(e,n)&&!!this.gs(e,n)&&!!this.ys(e,n)}ps(e,n){var i;if(n==null||!n.href)return!0;var r=this.bs(e);if(r.length>0)return r.some((a=>zn(a.href,n.href,n.href_matching||"exact")));var s,o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!o&&zn((s=o.match(/(?::|")href="(.*?)"/))?s[1]:"",n.href,n.href_matching||"exact")}gs(e,n){var i;if(n==null||!n.text)return!0;var r=this.bs(e);if(r.length>0)return r.some((u=>zn(u.text,n.text,n.text_matching||"exact")||zn(u.$el_text,n.text,n.text_matching||"exact")));var s,o,a,l=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!l&&(s=(function(u){for(var c,d=[],f=/(?::|")text="(.*?)"/g;!H(c=f.exec(u));)d.includes(c[1])||d.push(c[1]);return d})(l),o=n.text,a=n.text_matching||"exact",s.some((u=>zn(u,o,a))))}ys(e,n){var i,r;if(n==null||!n.selector)return!0;var s=e==null||(i=e.properties)==null?void 0:i.$element_selectors;if(s!=null&&s.includes(n.selector))return!0;var o=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";if(n.selector_regex&&o)try{return new RegExp(n.selector_regex).test(o)}catch{return!1}return!1}bs(e){var n;return(e==null||(n=e.properties)==null?void 0:n.$elements)==null?[]:e?.properties.$elements}hs(e,n){return n==null||!n.properties||n.properties.length===0||qf(n.properties.reduce(((i,r)=>{var s=U(r.value)?r.value.map(String):r.value!=null?[String(r.value)]:[];return i[r.key]={values:s,operator:r.operator||"exact"},i}),{}),e?.properties)}}class Hm{constructor(e){var n;this._s=[],this._instance=e,this.ws=new Map,this.ks=new Map,this.xs=new Map,(n=this._instance)==null||n.onSessionId==null||n.onSessionId((i=>this.Ss(i)))}Cs(e){return!1}Ms(){return null}Ts(e){}Es(){}Is(e,n){return!!e&&qf(e.propertyFilters,n?.properties)}Ps(e,n){var i=new Map;return e.forEach((r=>{var s;(s=r.conditions)==null||(s=s[n])==null||(s=s.values)==null||s.forEach((o=>{if(o!=null&&o.name){var a=i.get(o.name)||[];a.push(r.id),i.set(o.name,a)}}))})),i}Rs(e,n,i){var r=(i===wi.Activation?this.ws:this.ks).get(e),s=[];return this.As((o=>{s=o.filter((a=>r?.includes(a.id)))})),s.filter((o=>{var a,l=(a=o.conditions)==null||(a=a[i])==null||(a=a.values)==null?void 0:a.find((u=>u.name===e));return this.Is(l,n)}))}register(e){var n;C((n=this._instance)==null?void 0:n._addCaptureHook)||(this.Fs(e),this.Ls(e))}Ls(e){var n=e.filter((i=>{var r,s;return((r=i.conditions)==null?void 0:r.actions)&&((s=i.conditions)==null||(s=s.actions)==null||(s=s.values)==null?void 0:s.length)>0}));n.length!==0&&(this.Os==null&&(this.Os=new Um(this._instance),this.Os.init(),this.Os.fs((i=>{this.onAction(i)}))),n.forEach((i=>{var r,s,o,a,l;i.conditions&&(r=i.conditions)!=null&&r.actions&&(s=i.conditions)!=null&&(s=s.actions)!=null&&s.values&&((o=i.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.Os)==null||a.register(i.conditions.actions.values),(l=i.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var c=this.xs.get(u.name);c&&c.push(i.id),this.xs.set(u.name,c||[i.id])}})))})))}Fs(e){var n,i=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.events)&&((a=s.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0})),r=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.cancelEvents)&&((a=s.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0}));i.length===0&&r.length===0||((n=this._instance)==null||n._addCaptureHook(((s,o)=>{this.onEvent(s,o)})),this.ws=this.Ps(e,wi.Activation),this.ks=this.Ps(e,wi.Cancellation))}onEvent(e,n){var i,r,s=this.Ds(),o=(n==null||(i=n.properties)==null?void 0:i.$survey_id)||(n==null||(r=n.properties)==null?void 0:r.$product_tour_id);if(o&&this.getActivatedIds().includes(o)){var a=this.$s(e,o);if(a==="consume")return s.info("event consumed activated item, removing it",{event:e,itemId:o}),void this.Ns([o]);if(a==="persist")return s.info("shown item promoted to persisted activation",{event:e,itemId:o}),this.qs(o),void this.js([o])}if(this.ks.has(e)){var l=this.Rs(e,n,wi.Cancellation);l.length>0&&(s.info("cancel event matched, cancelling items",{event:e,itemsToCancel:l.map((c=>c.id))}),this.Ns(l.map((c=>c.id))),l.forEach((c=>this.Bs(c.id))))}if(this.ws.has(e)){s.info("event name matched",{event:e,eventPayload:n,items:this.ws.get(e)});var u=this.Rs(e,n,wi.Activation);this.Hs(u.map((c=>c.id)))}}onAction(e){this.xs.has(e)&&this.Hs(this.xs.get(e)||[])}Hs(e){var n;if(e.length!==0){var i=!((n=this._instance)==null||n.get_session_id==null||!n.get_session_id()),r=[];for(var s of e)i&&this.Cs(s)?this.qs(s)&&this.Us(s):r.push(s);r.length>0&&(this._s=[...new Set([...this._s,...r])]),this.Ds().info("updating activated items",{activatedItems:this.getActivatedIds()})}}qs(e){this._s=this._s.filter((i=>i!==e));var n=this.zs();return!n.includes(e)&&(this.Ws([...n,e]),this.Vs(),!0)}Ns(e){var n=new Set(e);this._s=this._s.filter((s=>!n.has(s)));var i=this.Zs(),r=i.filter((s=>!n.has(s)));r.length!==i.length&&(this.Ws(r),r.length===0&&this.Gs()),this.js(e)}Qs(){var e,n=this.Ms();if(!n)return{};var i=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n];return i&&typeof i=="object"?i:{}}Us(e){if(this.Ms()){var n=this.Qs();this.Ts(I({},n,{[e]:Date.now()}))}}js(e){if(this.Ms()){var n=this.Qs(),i={},r=!1;for(var s of Object.entries(n)){var o=s[0],a=s[1];e.includes(o)?r=!0:i[o]=a}r&&(Kt(i)?this.Es():this.Ts(i))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var n=this.Qs()[e];return ke(n)?n:void 0}}Zs(){var e,n=this.Js();return((e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n])||[]}zs(){var e,n,i=this.Zs();if(i.length===0)return[];var r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[this.Ys()],s=(n=this._instance)==null||n.get_session_id==null?void 0:n.get_session_id();return s&&r===s?i:[]}Vs(){var e,n=(e=this._instance)==null||e.get_session_id==null?void 0:e.get_session_id();n&&this.Xs(n)}Gs(){this.ta()}Ss(e){var n,i=(n=this._instance)==null||(n=n.persistence)==null?void 0:n.props[this.Ys()];if(i&&i!==e){var r=this.Zs(),s=this.Qs();r.length>0&&(this.Ws([]),r.filter((o=>ke(s[o]))).forEach((o=>this.Bs(o)))),this.Gs(),this.Ks()}}getActivatedIds(){return[...new Set([...this.zs(),...this._s])].filter((e=>!this.ea(e)))}reset(){this._s=[],this.Zs().length>0&&this.Ws([]),this.Gs(),this.Ks()}getEventToItemsMap(){return this.ws}ia(){return this.Os}}class Wm extends Hm{constructor(e){super(e)}Js(){return ca}Ys(){return Fr}Ms(){return Rr}Ts(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Rr]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Rr)}Cs(e){var n,i;this.As((s=>{i=s.find((o=>o.id===e))}));var r=(n=i)==null||(n=n.appearance)==null?void 0:n.surveyPopupDelaySeconds;return ke(r)&&r>0}ra(){return qt.SHOWN}As(e){var n;(n=this._instance)==null||n.getSurveys(e)}Bs(e){var n;(n=this._instance)==null||n.cancelPendingSurvey(e)}Ds(){return Q}Ws(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[ca]:e})}Xs(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Fr]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Fr)}ea(){return!1}$s(e,n){var i;this.As((s=>{i=s.find((o=>o.id===n))}));var r=!i||(function(s){var o;return Vf(s)&&!((o=s.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||s.schedule==="always"})(i);return r?e===qt.SHOWN?"consume":"ignore":e===qt.SHOWN?"persist":e===qt.DISMISSED||e===qt.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var Ir="SDK is not enabled or survey functionality is not yet loaded",hu="Disabled. Not loading surveys.",zm=w!=null&&w.location?os(w.location.hash,"__posthog")||os(location.hash,"state"):null,pu="_postHogToolbarParams",gu=pe("[Toolbar]"),mu=pe("[FeatureFlags]");class qm{constructor(e,n){n===void 0&&(n=!1),this.na=!1,this.update(e,n)}update(e,n){this.sa=((i,r)=>{var s,o,a,l;return{bootstrap:{featureFlags:(s=i.bootstrap)==null?void 0:s.featureFlags,featureFlagPayloads:(o=i.bootstrap)==null?void 0:o.featureFlagPayloads},remoteRequestsDisabled:r,featureFlagsDisabled:!!i.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!i.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!i.advanced_feature_flags_dedup_per_session,cacheTtlMs:i.feature_flag_cache_ttl_ms,requestTimeoutMs:i.feature_flag_request_timeout_ms,compression:i.disable_compression?"none":"base64",evaluationContexts:(a=(l=i.evaluation_contexts)!==null&&l!==void 0?l:i.evaluation_environments)!==null&&a!==void 0?a:[],flagKeys:U(i.flag_keys)?i.flag_keys:void 0}})(e,n),!e.evaluation_environments||e.evaluation_contexts||this.na||(mu.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.na=!0),C(e.flag_keys)||U(e.flag_keys)||mu.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var vu=pe("[FeatureFlags]"),bn=pe("[FeatureFlags]",{debugEnabled:!0}),Bo=`" failed. Feature flags didn't load in time.`,_u="connection_error",yu=t=>{for(var e={},n=0;t.length>n;n++)e[t[n]]=!0;return e},wu=t=>{var e={};for(var n of $r(t||{})){var i=n[1];i&&(e[n[0]]=i)}return e},St=pe("[Error tracking]"),bu="Refusing to render web experiment since the viewer is a likely bot",Vm={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>cs(e,t),not_regex:(t,e)=>!cs(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class Me{get Ne(){return this._instance.config}constructor(e){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(i){i===void 0&&(i=!1),n.getWebExperiments((r=>{Me.aa("retrieved web experiments from the server"),n.oa=new Map,r.forEach((s=>{if(s.feature_flag_key){var o;n.oa&&(Me.aa("setting flag key ",s.feature_flag_key," to web experiment ",s),(o=n.oa)==null||o.set(s.feature_flag_key,s));var a=n._instance.getFeatureFlag(s.feature_flag_key);X(a)&&s.variants[a]&&n.la(s.name,a,s.variants[a].transforms)}else if(s.variants)for(var l in s.variants){var u=s.variants[l];Me.ua(u,n._instance)&&n.la(s.name,l,u.transforms)}}))}),i)},this._instance=e,this._instance.onFeatureFlags((i=>{this.onFeatureFlags(i)}))}initialize(){}onFeatureFlags(e){if(this._is_bot())Me.aa(bu);else if(!this.Ne.disable_web_experiments){if(H(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();Me.aa("applying feature flags",e),e.forEach((n=>{var i;if(this.oa&&(i=this.oa)!=null&&i.has(n)){var r,s=this._instance.getFeatureFlag(n),o=(r=this.oa)==null?void 0:r.get(n);s&&o!=null&&o.variants[s]&&this.la(o.name,s,o.variants[s].transforms)}}))}}previewWebExperiment(){var e=Me.getWindowLocation();if(e!=null&&e.search){var n=ii(e?.search,"__experiment_id"),i=ii(e?.search,"__experiment_variant");n&&i&&(Me.aa("previewing web experiments "+n+" && "+i),this.getWebExperiments((r=>{this.ha(parseInt(n),i,r)}),!1,!0))}}loadIfEnabled(){this.Ne.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,n,i){if(this.Ne.disable_web_experiments&&!i)return e([]);var r=this._instance.get_property("$web_experiments");if(r&&!n)return e(r);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this.Ne.token),method:"GET",timestampMode:"query",callback:s=>e(s.statusCode===200&&s.json&&s.json.experiments||[])})}ha(e,n,i){var r=i.filter((s=>s.id===e));r&&r.length>0&&(Me.aa("Previewing web experiment ["+r[0].name+"] with variant ["+n+"]"),this.la(r[0].name,n,r[0].variants[n].transforms))}static ua(e,n){return!H(e.conditions)&&Me.da(e,n)&&Me.va(e)}static da(e,n){var i;if(H(e.conditions)||H((i=e.conditions)==null?void 0:i.url))return!0;var r=Me.getWindowLocation();if(r){var s,o,a,l=lf(n,r.href);return(s=e.conditions)==null||!s.url||Vm[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return w?.location}static va(e){var n;if(H(e.conditions)||H((n=e.conditions)==null?void 0:n.utm))return!0;var i=Sf();if(i.utm_source){var r,s,o,a,l,u,c,d,f=(r=e.conditions)==null||(r=r.utm)==null||!r.utm_campaign||((s=e.conditions)==null||(s=s.utm)==null?void 0:s.utm_campaign)==i.utm_campaign,h=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==i.utm_source,p=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==i.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==i.utm_term;return f&&p&&g&&h}return!1}static aa(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;n>r;r++)i[r-1]=arguments[r];A.info("[WebExperiments] "+e,i)}la(e,n,i){this._is_bot()?Me.aa(bu):n!=="control"?i.forEach((r=>{if(r.selector){var s;Me.aa("applying transform of variant "+n+" for experiment "+e+" ",r);var o=(s=document)==null?void 0:s.querySelectorAll(r.selector);o?.forEach((a=>{var l=a;r.html&&(l.innerHTML=r.html),r.css&&l.setAttribute("style",r.css)}))}})):Me.aa("Control variants leave the page unmodified.")}_is_bot(){return He&&this._instance?Hf(He,this.Ne.custom_blocked_useragents):void 0}}var ot=pe("[Conversations]"),En="Conversations not available yet.",Eu="console",Zf="__posthogHandledLogsRequestError",Do=(t,e)=>{var n=t instanceof Error?t:new Error(e);return n[Zf]=!0,n},Su=t=>!!t&&typeof t=="object"&&t[Zf]===!0,Cs={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=vu,this.fa={},this.pa={},this.ga=[],this.ma=!1,this.ya=!1,this.ba=0,this._a=!1,this.wa=!1,this.ka=!1,this.xa=!1,this.Sa=0,this.Ca=()=>{var e=this.Ma();this.Sa=0,e&&this.reloadFeatureFlags()},"get"in t?this.Ta=t:(this.Ea=new qm(t.config,t.Qi()),this.Ta=this.Ea)}updateConfig(t,e){var n;(n=this.Ea)==null||n.update(t,e)}setup(t){return this.Ia=t,this.rt=t.logger.createLogger("[FeatureFlags]"),n=()=>{this.Ia===t&&(this.Ia=void 0,this.nn=t,this.Pa(t))},(e=t.kv.initialize())!=null&&e.then?e.then(n):n();var e,n}Pa(t){if(this.nn===t)return w&&ve(w,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){w?.removeEventListener("online",this.Ca)}dispose(){var t;this.ba++,this.wa=!1,this.Ia=void 0,this.nn&&(this.La(),(t=this.Ra)==null||t.dispose(),this.Ra=void 0,this.ga=[],w?.removeEventListener("online",this.Ca),this.nn=void 0)}get Ne(){return this.Ta.get()}Oa(t){var e;return(e=this.nn)==null?void 0:e.kv.get(t)}F(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.set(t)}))}q(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.remove(t)}))}Da(t){try{t()}catch(e){this.rt.error("Failed to update feature flag persistence",e)}}Fa(){var t={};for(var e of[Ti,$i,Pr,It]){var n=this.Oa(e);C(n)||(t[e]=n)}this.fa=t;var i=I({},t),r=this.Oa(Sn);if(r)for(var s of Object.entries(r))i["$feature/"+s[0]]=s[1];this.pa=i}Aa(){var t=this.Ne.cacheTtlMs;if(!t||0>=t)return!1;var e=this.Oa(ji);return typeof e!="number"||Date.now()-e>t}$a(){return!!this.Aa()&&(this.xa||this.ya||(this.xa=!0,this.rt.warn("Feature flag cache is stale, triggering refresh..."),this.reloadFeatureFlags()),!0)}Na(){var t=this.Ne.evaluationContexts;return t!=null&&t.length?t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid evaluation context found:",e,"Expected non-empty string"),n})):[]}qa(){var t=this.Ne.flagKeys;if(!C(t))return t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid flag key found:",e,"Expected non-empty string"),n}))}initialize(){var t,e,n=this.Ne,i=(t=(e=n.bootstrap)==null?void 0:e.featureFlags)!==null&&t!==void 0?t:{};if(Object.keys(i).length){var r,s,o=(r=(s=n.bootstrap)==null?void 0:s.featureFlagPayloads)!==null&&r!==void 0?r:{},a=Object.keys(i).filter((u=>!!i[u])).reduce(((u,c)=>(u[c]=i[c]||!1,u)),{}),l=Object.keys(o).filter((u=>a[u])).reduce(((u,c)=>(o[c]&&(u[c]=o[c]),u)),{});return this.ja({featureFlags:a,featureFlagPayloads:l})}}updateFlags(t,e,n){var i,r,s=n!=null&&n.merge&&(i=this.Oa(Sn))!==null&&i!==void 0?i:{},o=n!=null&&n.merge&&(r=this.Oa($i))!==null&&r!==void 0?r:{},a=I({},s,t),l=I({},o,e),u={};for(var c of Object.entries(a)){var d=c[0],f=c[1];u[d]={key:d,enabled:gc(f),variant:mc(f),reason:void 0,metadata:C(l?.[d])?void 0:{id:0,version:void 0,description:void 0,payload:l[d]}}}this.ja({flags:u})}get hasLoadedFlags(){return this.ma}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var t=this.Oa(aa),e=this.Oa(It),n=this.Oa(xn);if(!n&&!e)return t||{};var i=fe({},t||{}),r=[...new Set([...Object.keys(n||{}),...Object.keys(e||{})])];for(var s of r){var o,a,l=i[s],u=e?.[s],c=C(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=C(u)?l?.variant:typeof u=="string"?u:void 0,f=n?.[s],h=I({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(h.original_enabled=l?.enabled),d!==l?.variant&&(h.original_variant=l?.variant),f&&(h.metadata=I({},l?.metadata,{payload:f,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),i[s]=h}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:n,finalDetails:i}),this.ca=!0),i}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((n=>{var i=t[n];return{key:n,enabled:gc(i),variant:mc(i),payload:pc(e[n])}}))}getFlagVariants(){var t=this.Oa(Sn),e=this.Oa(It);if(!e)return t||{};for(var n=fe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:e,finalFlags:n}),this.ca=!0),n}getFlagPayloads(){var t=this.Oa($i),e=this.Oa(xn);if(!e)return t||{};for(var n=fe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flag payloads!",{flagPayloads:t,overriddenPayloads:e,finalPayloads:n}),this.ca=!0),n}reloadFeatureFlags(){this._a||this.Ne.featureFlagsDisabled||this.Ma()||this.Ba||(this.ga.slice().forEach((t=>{try{t()}catch(e){this.rt.error("Error while running feature flags reloading callback",e)}})),this.Ba=setTimeout((()=>{this.Ha()}),5))}La(){clearTimeout(this.Ba),this.Ba=void 0}onReloading(t){return this.ga.push(t),()=>{this.ga=this.ga.filter((e=>e!==t))}}ensureFlagsLoaded(){this.ma||this.ya||this.Ba||this.reloadFeatureFlags()}setAnonymousDistinctId(t){this.$anon_distinct_id=t}setReloadingPaused(t){this._a=t}resetFlagCallReported(){this.q(Cn)}Ha(t){this.La();var e=this.nn;if(e&&!this.Ne.remoteRequestsDisabled&&!this.Ma())if(this.ya)this.wa=!0;else{var n={token:e.projectToken,distinct_id:e.distinctId,groups:e.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:I({},e.initialPersonProperties,this.Oa(jt)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(In),timezone:Pf()};C(e.deviceId)||(n.$device_id=e.deviceId),(t!=null&&t.disableFlags||this.Ne.featureFlagsDisabled)&&(n.disable_flags=!0);var i=this.Na();i.length&&(n.evaluation_contexts=i);var r=this.qa();C(r)||(n.flag_keys=r);var s=this.Ne.onlyEvaluateSurveyFeatureFlags,o="/flags/?v=2"+(s?"&only_evaluate_survey_feature_flags=true":""),a=this.ba;this.ya=!0;var l=()=>{this.wa&&(this.wa=!1,this.Ha())},u=c=>{this.ya=!1,a===this.ba&&(this.F({[Tr]:[_u]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:n,compression:this.Ne.compression==="base64"?Ue.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,f,h=(d=c.json)!==null&&d!==void 0?d:{},p=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),p||this.wa||(this.$anon_distinct_id=void 0),!n.disable_flags||this.wa){this.ka=!p;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?_u:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),h.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((f=h.quotaLimited)==null||!f.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[Tr]:g}),m?this.rt.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more."):n.disable_flags||this.ja(h,p,{partialResponse:s}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return bf(this.Sa,3)}Ua(t){this.Sa=Ef(t,this.Sa,3,(()=>this.rt.warn("Feature flag requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped refreshing feature flags; will try again when connectivity changes.")))}getFeatureFlag(t,e){var n;if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var i=this.getFeatureFlagResult(t,e);return(n=i?.variant)!==null&&n!==void 0?n:i?.enabled}}else this.rt.warn('getFeatureFlag for key "'+t+Bo)}getFeatureFlagDetails(t){return this.getFlagsWithDetails()[t]}getFeatureFlagPayload(t){var e=this.getFeatureFlagResult(t,{send_event:!1});return e?.payload}getFeatureFlagResult(t,e){if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var n,i=this.getFlagVariants(),r=t in i,s=i[t],o=this.getFlagPayloads()[t],a=String(s),l=this.Oa(Pr)||void 0,u=this.Oa(ji)||void 0,c=this.Oa(Cn)||{};if(this.Ne.deduplicateCallsPerSession){var d,f=(d=this.nn)==null?void 0:d.session.sessionId,h=this.Oa(Li);f&&f!==h&&(c={},n=f)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))n&&this.F({[Cn]:c,[Li]:n});else{var p,g,m,v,E,S,_,b,k,T;U(c[t])?c[t].push(a):c[t]=[a],this.F(I({[Cn]:c},n?{[Li]:n}:{}));var x=this.getFeatureFlagDetails(t),F=[...(p=this.Oa(Tr))!==null&&p!==void 0?p:[]];C(s)&&F.push("flag_missing");var $={$feature_flag:t,$feature_flag_response:s,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((g=this.Ne.bootstrap)==null||(g=g.featureFlags)==null?void 0:g[t])||null,$feature_flag_bootstrapped_payload:((m=this.Ne.bootstrap)==null||(m=m.featureFlagPayloads)==null?void 0:m[t])||null,$used_bootstrap_value:!this.ka};C(x==null||(v=x.metadata)==null?void 0:v.has_experiment)||($.$feature_flag_has_experiment=x.metadata.has_experiment),C(x==null||(E=x.metadata)==null?void 0:E.version)||($.$feature_flag_version=x.metadata.version);var O,L=(S=x==null||(_=x.reason)==null?void 0:_.description)!==null&&S!==void 0?S:x==null||(b=x.reason)==null?void 0:b.code;L&&($.$feature_flag_reason=L),x!=null&&(k=x.metadata)!=null&&k.id&&($.$feature_flag_id=x.metadata.id),C(x?.original_variant)&&C(x?.original_enabled)||($.$feature_flag_original_response=C(x.original_variant)?x.original_enabled:x.original_variant),x!=null&&(T=x.metadata)!=null&&T.original_payload&&($.$feature_flag_original_payload=x==null||(O=x.metadata)==null?void 0:O.original_payload),F.length&&($.$feature_flag_error=F.join(",")),this.za($)}else n&&this.F({[Cn]:c,[Li]:n});if(r)return{key:t,enabled:!!s,variant:typeof s=="string"?s:void 0,payload:pc(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+Bo)}za(t){try{var e;(e=this.nn)==null||e.capture("$feature_flag_called",t).catch((n=>{this.rt.error("Failed to capture feature flag call",n)}))}catch(n){this.rt.error("Failed to capture feature flag call",n)}}getRemoteConfigPayload(t,e){this.Wa(t,e)}Wa(t,e){var n=this;return se((function*(){var i=n.nn;if(i){var r={distinct_id:i.distinctId,token:i.projectToken,person_properties:{$lib:i.library.name,$lib_version:i.library.version}},s=n.Na();s.length&&(r.evaluation_contexts=s);var o,a=n.qa();C(a)||(r.flag_keys=a);try{var l,u=(l=(yield i.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:r,compression:n.Ne.compression==="base64"?Ue.Base64:void 0,sentAt:"body",timeoutMs:n.Ne.requestTimeoutMs})).json)==null?void 0:l.featureFlagPayloads;o=u?.[t]||void 0}catch(c){return void n.rt.error("Remote config feature flag request failed",c)}try{e(o)}catch(c){n.rt.error("Remote config feature flag callback failed",c)}}}))()}isFeatureEnabled(t,e){if(e===void 0&&(e={}),e.fresh&&!this.ka)return e.defaultValue;if(!(this.ma||this.getFlags()&&this.getFlags().length>0))return this.rt.warn('isFeatureEnabled for key "'+t+Bo),e.defaultValue;var n=this.getFeatureFlag(t,e);return C(n)?e.defaultValue:!!n}addFeatureFlagsHandler(t){this.featureFlagEventHandlers.push(t)}removeFeatureFlagsHandler(t){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((e=>e!==t))}receivedFeatureFlags(t,e,n){this.ja(t,e,n)}ja(t,e,n){if(this.nn){this.ma=!0;var i=(function(r,s,o,a,l,u){s===void 0&&(s={}),o===void 0&&(o={}),a===void 0&&(a={}),u===void 0&&(u=vu);var c=((k,T)=>{var x=k.flags;return x?I({},k,{featureFlags:Object.fromEntries(Object.keys(x).map((F=>{var $;return[F,($=x[F].variant)!==null&&$!==void 0?$:x[F].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(x).filter((F=>x[F].enabled)).filter((F=>{var $;return($=x[F].metadata)==null?void 0:$.payload})).map((F=>{var $;return[F,($=x[F].metadata)==null?void 0:$.payload]})))}):(k.featureFlags&&T.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),k)})(r,u),d=c.flags,f=c.featureFlags,h=c.featureFlagPayloads;if(f){var p=r.requestId,g=r.evaluatedAt;if(U(f)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(f)for(var v=0;f.length>v;v++)m[f[v]]=!0;return{[Ti]:f,[Sn]:m,[Zr]:!1}}var E=f,S=h,_=d;if(l!=null&&l.partialResponse)E=I({},s,E),S=I({},o,S),_=I({},a,_);else if(r.errorsWhileComputingFlags)if(d){var b=new Set(Object.keys(d).filter((k=>{var T;return!((T=d[k])!=null&&T.failed)})));E=I({},s,Object.fromEntries(Object.entries(E).filter((k=>b.has(k[0]))))),S=I({},o,Object.fromEntries(Object.entries(S||{}).filter((k=>b.has(k[0]))))),_=I({},a,Object.fromEntries(Object.entries(_||{}).filter((k=>b.has(k[0])))))}else E=I({},s,E),S=I({},o,S),_=I({},a,_);return I({[Ti]:Object.keys(wu(E)),[Sn]:E||{},[$i]:S||{},[aa]:_||{},[Zr]:r.minimalFlagCalledEvents===!0},p?{[Pr]:p}:{},g?{[ji]:g}:{})}})(t,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),n,this.rt);i&&this.F(i),e||(this.xa=!1),this.Va(e)}}override(t,e){e===void 0&&(e=!1),this.rt.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:t,suppressWarning:e})}overrideFeatureFlags(t){this.Za(t)}Za(t){if(this.nn){if(t===!1)return this.q([It,xn]),this.Va(),void bn.info("All overrides cleared");if(U(t))return this.F({[It]:yu(t)}),this.Va(),void bn.info("Flag overrides set",{flags:t});if(t&&typeof t=="object"&&("flags"in t||"payloads"in t)){var e,n=t;this.ca=!!((e=n.suppressWarning)!==null&&e!==void 0&&e);var i={},r=n.flags,s=n.payloads;return r&&(i[It]=U(r)?yu(r):r),s&&(i[xn]=s),Object.keys(i).length&&this.F(i),r===!1&&s===!1?this.q([It,xn]):r===!1?this.q(It):s===!1&&this.q(xn),this.Va(),r===!1?bn.info("Flag overrides cleared"):r&&bn.info("Flag overrides set",{flags:r}),void(s===!1?bn.info("Payload overrides cleared"):s&&bn.info("Payload overrides set",{payloads:s}))}if(t&&typeof t=="object")return this.F({[It]:t}),this.Va(),void bn.info("Flag overrides set",{flags:t});this.rt.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:t})}else this.rt.warn("posthog.featureFlags.overrideFeatureFlags called before feature flags were ready")}onFeatureFlags(t){if(this.addFeatureFlagsHandler(t),this.ma){var e=this.Ga(),n=e.flags,i=e.flagVariants;try{t(n,i)}catch(r){this.rt.error("Error while running feature flags callback",r)}}return()=>this.removeFeatureFlagsHandler(t)}updateEarlyAccessFeatureEnrollment(t,e,n){var i=(this.Oa(Ar)||[]).find((l=>l.flagKey===t)),r={["$feature_enrollment/"+t]:e},s={$feature_flag:t,$feature_enrollment:e,$set:r};i&&(s.$early_access_feature_name=i.name),n&&(s.$feature_enrollment_stage=n);var o=I({},this.getFlagVariants(),{[t]:e});this.F({[Ti]:Object.keys(wu(o)),[Sn]:o,[jt]:I({},this.Oa(jt)||{},r)}),this.Va();try{var a;(a=this.nn)==null||a.capture("$feature_enrollment_update",s).catch((l=>{this.rt.error("Failed to capture early access feature enrollment",l)}))}catch(l){this.rt.error("Failed to capture early access feature enrollment",l)}}getEarlyAccessFeatures(t,e,n){e===void 0&&(e=!1);var i=this.Oa(Ar);!i||e?this.Qa(t,n):t(i)}Qa(t,e){var n=this;return se((function*(){var i=n.nn;if(i){var r,s=e?"&"+e.map((a=>"stage="+a)).join("&"):"";try{var o=yield i.sendRequest("/api/early_access_features/?token="+i.projectToken+s,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;n.F({[Ar]:r=o.json.earlyAccessFeatures})}catch(a){return void n.rt.error("Early access feature request failed",a)}try{t(r)}catch(a){n.rt.error("Early access feature callback failed",a)}}}))()}Ga(){var t=this.getFlags(),e=this.getFlagVariants();return{flags:t.filter((n=>e[n])),flagVariants:Object.keys(e).filter((n=>e[n])).reduce(((n,i)=>(n[i]=e[i],n)),{})}}Va(t){this.Fa();var e=this.Ga(),n=e.flags,i=e.flagVariants;this.featureFlagEventHandlers.forEach((r=>{try{r(n,i,{errorsLoading:t})}catch(s){this.rt.error("Error while running feature flags callback",s)}}))}setPersonPropertiesForFlags(t,e){e===void 0&&(e=!0),this.Ka(t,e)}Ka(t,e){e===void 0&&(e=!0);var n=this.Oa(jt)||{},i=t?.$set||(t!=null&&t.$set_once?{}:t),r=t?.$set_once,s={};if(r)for(var o in r)({}).hasOwnProperty.call(r,o)&&(o in n||(s[o]=r[o]));this.F({[jt]:I({},n,s,i)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=I({},this.Oa(jt)||{});t.forEach((i=>{delete n[i]})),this.F({[jt]:n}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(jt),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=this.Oa(In)||{},i=I({},n);for(var r of Object.keys(t))i[r]=I({},n[r],t[r]);this.F({[In]:i}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(In)||{};this.F({[In]:I({},e,{[t]:{}})})}else this.q(In)}reset(){this.ba++,this.wa=!1,this.Fa(),this.ma=!1,this._a=!1,this.ka=!1,this.$anon_distinct_id=void 0,this.La(),this.ca=!1,this.Sa=0}}},Gm={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===ki||this.Ya===Sr?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=uu,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(P==null||!P.visibilityState||P.visibilityState==="visible")return!0;var n=w==null||(e=w.performance)==null||e.getEntriesByType==null?void 0:e.getEntriesByType("visibility-state");return!(n!=null&&n.length)||n.some((i=>i.name==="visible"))})(),this.Ie=()=>{var e;P?.visibilityState==="visible"&&(this.io=!0,(e=this.Ja)==null||e.setDocumentWasEverVisible==null||e.setDocumentWasEverVisible(!0))},this._instance=t,!this._instance.sessionManager)throw Bt.error("started without valid sessionManager"),new Error(Ia+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===Wt)throw new Error(Ia+' cannot be used with cookieless_mode="always"');P!=null&&P.addEventListener&&ve(P,"visibilitychange",this.Ie)}initialize(){this.startIfEnabledOrStop()}dispose(){this.eo=!0,P==null||P.removeEventListener==null||P.removeEventListener("visibilitychange",this.Ie),this.stopRecording()}get ro(){var t,e=!((t=this._instance.get_property(An))==null||!t.enabled),n=!this.Ne.disable_session_recording,i=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return w&&e&&n&&!i}startIfEnabledOrStop(t){var e;if(!(this.eo||this.ro&&(e=this.Ja)!=null&&e.isStarted)){var n=!C(Object.assign)&&!C(Array.from);this.ro&&n?(this.no(t),Bt.info("starting")):(this.Ya=uu,this.stopRecording())}}no(t){var e,n,i;this.ro&&(this.Ya!==ki&&this.Ya!==Sr&&(this.Ya=du),B!=null&&(e=B.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(n=B.__PosthogExtensions__)!=null&&n.initSessionRecording?this.so(t):(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,this.ao,(r=>{if(r)return Bt.error("could not load recorder",r);this.so(t)})))}stopRecording(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.stop()}oo(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.discard()}lo(){var t,e;(t=this.Mr)==null||t.unregister(al),(e=this.Mr)==null||e.unregister(Jd)}uo(t,e){if(H(t))return null;var n,i=ke(t)?t:parseFloat(t);return typeof(n=i)!="number"||!Number.isFinite(n)||0>n||n>1?(Bt.warn(e+" must be between 0 and 1. Ignoring invalid value:",t),null):i}ho(t){if(this.Mr){var e,n,i=this.Mr,r=()=>{var s,o=t.sessionRecording===!1?void 0:t.sessionRecording,a=this.uo((s=this.Ne.session_recording)==null?void 0:s.sampleRate,"session_recording.sampleRate"),l=this.uo(o?.sampleRate,"remote config sampleRate"),u=a??l;H(u)&&this.lo();var c=o?.minimumDurationMilliseconds;i.register({[An]:I({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:I({capturePerformance:t.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:u,minimumDurationMilliseconds:C(c)?null:c,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers,version:o?.version,triggerGroups:o?.triggerGroups})})};r(),(e=this.Xa)==null||e.call(this),this.Xa=(n=this._instance.sessionManager)==null?void 0:n.onSessionId(r)}}onRemoteConfig(t){var e=t.ok?t.config:void 0;return e&&"sessionRecording"in e?e.sessionRecording===!1?(this.ho(e),void this.oo()):(this.ho(e),void this.startIfEnabledOrStop()):(this.Ya===ki&&(this.Ya=Sr,Bt.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(t,e){var n;e===void 0&&(e="log"),(n=this.Ja)!=null&&n.log?this.Ja.log(t,e):Bt.warn("log called before recorder was ready")}get ao(){var t,e,n=(t=this._instance)==null||(t=t.persistence)==null?void 0:t.get_property(An);return(n==null||(e=n.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(An);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(n){return Bt.warn("persisted remote config for session recording is invalid and will be ignored",n),!1}return!H(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,n,i;if(!this.eo){if((e=B.__PosthogExtensions__)==null||!e.initSessionRecording)return Bt.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[sf]:!0});var r;if(this.Ja||(this.Ja=(r=B.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===Sr||this.Ya===ki?void 0:(this.Ya=ki,Bt.info("persisted remote config is stale, requesting fresh config before starting"),void new Ff(this._instance).load());this.Ya=du,(n=(i=this.Ja).setDocumentWasEverVisible)==null||n.call(i,this.io),this.Ja.start(t)}}onRRwebEmit(t){var e;(e=this.Ja)==null||e.onRRwebEmit==null||e.onRRwebEmit(t)}overrideLinkedFlag(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Xd]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Zd]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,n;this.Ja||(n=this.Mr)==null||n.register({[t==="url"?Qd:ef]:!0}),(e=this.Ja)==null||e.overrideTrigger(t)}get sdkDebugProperties(){var t;return((t=this.Ja)==null?void 0:t.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(t,e){var n;return!((n=this.Ja)==null||!n.tryAddCustomEvent(t,e))}}},Km={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new au(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,n=he(this.instance.config.autocapture)?this.instance.config.autocapture:{};return n.url_allowlist=(t=n.url_allowlist)==null?void 0:t.map((i=>new RegExp(i))),n.url_ignorelist=(e=n.url_ignorelist)==null?void 0:e.map((i=>new RegExp(i))),n}yo(){if(this.isBrowserSupported()){if(w&&P){var t=n=>{n=n||w?.event;try{this.bo(n)}catch(i){Mo.error("Failed to capture event",i)}};if(ve(P,"submit",t,{capture:!0}),ve(P,"change",t,{capture:!0}),ve(P,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=n=>{n=n||w?.event;try{this.bo(n,$o)}catch(i){Mo.error("Failed to capture copy/cut event",i)}};ve(P,"copy",e,{capture:!0}),ve(P,"cut",e,{capture:!0})}}}else Mo.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.vo&&(this.yo(),this.vo=!0)}onRemoteConfig(t){if(this.fo=!0,t.ok){var e=t.config;e.elementsChainAsString&&(this.po=e.elementsChainAsString);var n=e.autocapture_opt_out;mt(n)&&(this.instance.persistence&&this.instance.persistence.register({[ea]:n}),this.co=n),this.startIfEnabled()}else this.startIfEnabled()}setElementSelectors(t){this.mo=t}getElementSelectors(t){var e,n=[];return(e=this.mo)==null||e.forEach((i=>{var r=P?.querySelectorAll(i);r?.forEach((s=>{t===s&&n.push(i)}))})),n}get isEnabled(){var t,e,n=(t=this.instance.persistence)==null?void 0:t.props[ea],i=this.co,r=this.instance.Qi()&&!this.fo;if(Ye(i)&&!mt(n)&&!r)return!1;var s=(e=this.co)!==null&&e!==void 0?e:!!n;return!!this.instance.config.autocapture&&!s}bo(t,e){if(e===void 0&&(e="$autocapture"),this.isEnabled){var n,i=bo(t);uf(i)&&(i=i.parentNode||null),e==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&this.instance.config.rageclick&&(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,t.timeStamp||new Date().getTime())&&Oc(i,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var r=e===$o;if(i&&(function(d,f,h,p,g,m){var v;if(!w||fl(d)||h!=null&&h.url_allowlist&&!Mc(h.url_allowlist,m)||h!=null&&h.url_ignorelist&&Mc(h.url_ignorelist,m))return!1;if(h!=null&&h.dom_event_allowlist){var E=h.dom_event_allowlist;if(E&&!E.some((x=>f.type===x)))return!1}var S=mf(d,p),_=S.parentIsUsefulElement,b=S.targetElementList;if(!(function(x,F){var $=F?.element_allowlist;if(C($))return!0;var O,L=function(K){if($.some((V=>K.tagName.toLowerCase()===V)))return{v:!0}};for(var N of x)if(O=L(N))return O.v;return!1})(b,h)||!ma(b,h?.css_selector_allowlist)||ma(b,(v=h?.css_selector_ignorelist)!==null&&v!==void 0?v:qg))return!1;try{var k=w.getComputedStyle(d);if(k&&k.getPropertyValue("cursor")==="pointer"&&f.type==="click")return!0}catch{}var T=d.tagName.toLowerCase();switch(T){case"html":return!1;case"form":return(g||["submit"]).indexOf(f.type)>=0;case"input":case"select":case"textarea":return(g||["change","click"]).indexOf(f.type)>=0;default:return _?(g||["click"]).indexOf(f.type)>=0:(g||["click"]).indexOf(f.type)>=0&&(dl.indexOf(T)>-1||d.getAttribute("contenteditable")==="true")}})(i,t,this.Ne,r,r?["copy","cut"]:void 0,this.instance)){var s=Om(i,{e:t,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.Ne.element_attribute_ignorelist,elementsChainAsString:this.po,disableCaptureUrlHashes:this.instance.config.disable_capture_url_hashes}),o=s.props;if(s.explicitNoCapture)return!1;var a=this.getElementSelectors(i);if(a&&a.length>0&&(o.$element_selectors=a),e===$o){var l,u=hf(w==null||(l=w.getSelection())==null?void 0:l.toString()),c=t.type||"clipboard";if(!u)return!1;o.$selected_content=u,o.$copy_type=c}return this.instance.capture(e,o),!0}}}isBrowserSupported(){return je(P?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(w==null||(e=w.location)==null?void 0:e.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(A.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.wo&&this.wo(),this.wo=void 0,A.info("History API monitoring stopped")}monitorHistoryChanges(){w&&w.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(w&&((e=w.history[t])==null||!e.__posthog_wrapped__)){var n=this;(function(i,r,s){try{if(!(r in i))return lu;var o={next:i[r]},a=s((function(){for(var l=arguments.length,u=new Array(l),c=0;l>c;c++)u[c]=arguments[c];return o.next.apply(this,u)}));return je(a)&&(a.prototype=a.prototype||{},Object.defineProperties(a,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:o}})),i[r]=a,()=>{if(i[r]!==a)for(var l=i[r];je(l)&&l.__posthog_layer__;){var u=l.__posthog_layer__;if(u.next===a)return void(u.next=o.next);l=u.next}else i[r]=o.next}}catch{return lu}})(w.history,t,(i=>function(r,s,o){i.call(this,r,s,o),n.So(t)}))}}So(t){try{var e,n=w==null||(e=w.location)==null?void 0:e.pathname;if(!n)return;n!==this._o&&this.isEnabled&&this._instance.capture(Vn,{navigation_type:t}),this._o=n}catch(i){A.error("Error capturing "+t+" pageview",i)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};ve(w,"popstate",t),this.wo=()=>{w&&w.removeEventListener("popstate",t)}}}},heatmaps:class{get Ne(){return this.instance.config}constructor(t){var e;this.Co=!1,this.vo=!1,this.Mo=null,this.instance=t,this.Co=!((e=this.instance.persistence)==null||!e.props[ta]),this.rageclicks=new au(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return he(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return H(this.Ne.capture_heatmaps)?H(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;Dm.info("starting..."),this.To(),this.Ie()}else{var t;clearInterval((t=this.Mo)!==null&&t!==void 0?t:void 0),this.Eo(),this.getAndClearBuffer()}}onRemoteConfig(t){if(t.ok){var e=t.config;if("heatmaps"in e){var n=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[ta]:n}),this.Co=n,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){No(t.originalEvent)&&this.ke(t.originalEvent,"deadclick")}Ie(){this.Mo&&clearInterval(this.Mo),this.Mo=P?.visibilityState==="visible"?setInterval(this.cr.bind(this),this.flushIntervalMilliseconds):null}To(){w&&P&&(this.Po=this.cr.bind(this),ve(w,ns,this.Po),this.Ro=t=>this.ke(t||w?.event),ve(P,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||w?.event),ve(P,"mousemove",this.Ao,{capture:!0}),this.Lo=new zc(this.instance,Xg,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),ve(P,ts,this.Oo),this.vo=!0)}Eo(){var t;w&&P&&(this.Po&&w.removeEventListener(ns,this.Po),this.Ro&&P.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&P.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&P.removeEventListener(ts,this.Oo),clearTimeout(this.Do),(t=this.Lo)==null||t.stop(),this.vo=!1)}$o(t,e){var n=this.instance.scrollManager.scrollY(),i=this.instance.scrollManager.scrollX(),r=this.instance.scrollManager.scrollElement(),s=(function(o,a,l){for(var u=o;u&&hn(u)&&!et(u,"body");){if(u===l)return!1;var c=void 0;try{var d,f,h;c=(d=(f=(h=u.ownerDocument)==null?void 0:h.defaultView)!==null&&f!==void 0?f:w)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(j(a,c))return!0;u=pf(u)}return!1})(bo(t),["fixed","sticky"],r);return{x:t.clientX+(s?0:i),y:t.clientY+(s?0:n),target_fixed:s,type:e}}ke(t,e){var n;if(e===void 0&&(e="click"),!$c(t.target)&&No(t)){var i=this.$o(t,e);(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,new Date().getTime())&&Oc(bo(t),this.instance.config.rageclick)&&this.Vt(I({},i,{type:"rageclick"})),this.Vt(i)}}Fo(t){!$c(t.target)&&No(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(w){var e=this.Ne.disable_capture_url_hashes?fn(w.location.href):w.location.href,n=this.Ne.custom_personal_data_properties,i=this.Ne.mask_personal_data_properties?[...ri,...n||[]]:[],r=Zi(e,i,Xi);this.R=this.R||{},this.R[r]||(this.R[r]=[]),this.R[r].push(t)}}cr(){this.R&&!Kt(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:zc,webVitalsAutocapture:class{constructor(t){var e;this.Co=!1,this.vo=!1,this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this.No=()=>{clearTimeout(this.qo),this.qo=void 0,this.R.metrics.length!==0&&(this._instance.capture("$web_vitals",I({$current_url:this.R.url},this.R.metrics.reduce(((n,i)=>I({},n,{["$web_vitals_"+i.name+"_event"]:I({},i),["$web_vitals_"+i.name+"_value"]:i.value})),{}))),this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.jo=n=>{var i;if(this.R=this.R||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},H(n?.name)||H(n?.value))wn.error("Invalid metric received",n);else{var r=typeof n.navigationURL=="string"?n.navigationURL:void 0,s=this.Bo(r);if(!C(s)){var o=ke(n.navigationId)||typeof n.navigationId=="string"?"navigation:"+n.navigationId:"url:"+s;if(!this.Ho||this.Ho>n.value){this.R.navigationKey!==o&&(this.No(),this.qo=setTimeout(this.No,this.flushToCaptureTimeoutMs)),C(this.R.navigationKey)&&(this.R.navigationKey=o,this.R.url=s),this.R.firstMetricTimestamp=C(this.R.firstMetricTimestamp)?Date.now():this.R.firstMetricTimestamp,n.attribution&&n.attribution.interactionTargetElement&&(n.attribution.interactionTargetElement=void 0);var a=(i=this._instance.sessionManager)==null?void 0:i.checkAndGetSessionAndWindowId(!0),l=I({},n,r?{navigationURL:s}:{},{$current_url:s,timestamp:Date.now()});C(a)||(l.$session_id=a.sessionId,l.$window_id=a.windowId),this.R.metrics.push(l),this.R.metrics.length===this.allowedMetrics.length&&this.No()}else wn.error("Ignoring metric with value >= "+this.Ho,n)}}},this.Uo=()=>{if(!this.vo){var n,i,r,s,o=B.__PosthogExtensions__,a=o?.postHogWebVitalsCallbacksByFlavor,l=a?.[this.zo]||(this.zo==="web-vitals"&&C(a)?o?.postHogWebVitalsCallbacks:void 0);if(C(l)||(n=l.onLCP,i=l.onCLS,r=l.onFCP,s=l.onINP),n&&i&&r&&s){var u={reportSoftNavs:this.useSoftNavs};this.allowedMetrics.indexOf("LCP")>-1&&n(this.jo.bind(this),u),this.allowedMetrics.indexOf("CLS")>-1&&i(this.jo.bind(this),u),this.allowedMetrics.indexOf("FCP")>-1&&r(this.jo.bind(this),u),this.allowedMetrics.indexOf("INP")>-1&&s(this.jo.bind(this),u),this.vo=!0}else wn.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[sa]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,n=he(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return H(n)?((e=this._instance.persistence)==null?void 0:e.props[oa])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(he(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=he(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=he(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=he(this.Wo)&&ke(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:cu;return t>0&&6e4>=t?cu:t}get isEnabled(){var t=me?.protocol;if(t!=="http:"&&t!=="https:")return wn.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=he(this.Wo)?this.Wo.web_vitals:mt(this.Wo)?this.Wo:void 0;return mt(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(wn.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var n=he(e.capturePerformance)&&!!e.capturePerformance.web_vitals,i=he(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[sa]:n}),this._instance.persistence.register({[oa]:i})),this.Co=n,this.startIfEnabled()}}}get zo(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}ai(t){var e=B.__PosthogExtensions__,n=this.zo,i=e?.postHogWebVitalsCallbacksByFlavor;i!=null&&i[n]||n==="web-vitals"&&C(i)&&e!=null&&e.postHogWebVitalsCallbacks?t():e==null||e.loadExternalDependency==null||e.loadExternalDependency(this._instance,n,(r=>{r?wn.error("failed to load script",r):t()}))}Bo(t){var e=t||w?.location.href;if(e){var n=this._instance.config.disable_capture_url_hashes?fn(e):e,i=this._instance.config.custom_personal_data_properties,r=this._instance.config.mask_personal_data_properties?[...ri,...i||[]]:[];return Zi(n,r,Xi)}wn.error("Could not determine current URL")}}},Ym={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var n;if(w&&this.isEnabled&&(n=B.__PosthogExtensions__)!=null&&n.errorWrappingFunctions){var i=B.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,r=B.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,s=B.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.Vo&&this.Ne.capture_unhandled_errors&&(this.Vo=i(this.captureException.bind(this))),!this.Zo&&this.Ne.capture_unhandled_rejections&&(this.Zo=r(this.captureException.bind(this))),!this.Go&&this.Ne.capture_console_errors&&(this.Go=s(this.captureException.bind(this)))}catch(o){Ii.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[na]),this.Jo=new Gp(I({},(function(n){var i,r,s,o;return n===void 0&&(n={}),{refillRate:(i=(r=n.exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:n.__exceptionRateLimiterRefillRate)!==null&&i!==void 0?i:1,bucketSize:(s=(o=n.exceptionRateLimiterBucketSize)!==null&&o!==void 0?o:n.__exceptionRateLimiterBucketSize)!==null&&s!==void 0?s:10}})(this._instance.config.error_tracking),{refillInterval:1e4,rt:Ii})),this.Ne=this.Yo(),this.startIfEnabledOrStop()}Yo(){var t=this._instance.config.capture_exceptions,e={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return he(t)?e=I({},e,t):(C(t)?this.Ko:t)&&(e=I({},e,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),e}get isEnabled(){return this.Ne.capture_console_errors||this.Ne.capture_unhandled_errors||this.Ne.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(Ii.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",(i=>{if(i)return Ii.error("failed to load script",i);t()}))}Qo(){var t,e,n;(t=this.Vo)==null||t.call(this),this.Vo=void 0,(e=this.Zo)==null||e.call(this),this.Zo=void 0,(n=this.Go)==null||n.call(this),this.Go=void 0}onRemoteConfig(t){if(t.ok){var e=t.config;"autocaptureExceptions"in e&&(this.Ko=!!e.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[na]:this.Ko}),this.Ne=this.Yo(),this.startIfEnabledOrStop())}}onConfigChange(){this.Ne=this.Yo()}captureException(t){var e,n,i,r=(e=t==null||(n=t.$exception_list)==null||(n=n[0])==null?void 0:n.type)!==null&&e!==void 0?e:"Exception";this.Jo.consumeRateLimit(r)?Ii.info("Skipping exception capture because of client rate limiting.",{exception:r}):(i=this._instance.exceptions)==null||i.sendExceptionEvent(t)}},exceptions:class{constructor(t){var e,n;this.Xo=[],this.tl=new ug([new _g,new Cg,new wg,new yg,new Ig,new xg,new Eg,new kg],(function(i){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;r>o;o++)s[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` +`),d=l;c.length>d;d++){var f=c[d];if(1024>=f.length){var h=Pc.test(f)?f.replace(Pc,"$1"):f;if(!h.match(/\S*Error: /)){for(var p of s){var g=p(h,i);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var v=Array.from(m);return v.reverse(),v.slice(0,50).map((E=>{return I({},E,{filename:E.filename||(S=v,S[S.length-1]||{}).filename,function:E.function||ni});var S}))})(u)}})("web:javascript",pg,vg)),this._instance=t,this.Xo=(e=(n=this._instance.persistence)==null?void 0:n.get_property(ia))!==null&&e!==void 0?e:[],this.el=Jr(this.il()),this.rl=new Pg(this.el)}onConfigChange(){this.el=Jr(this.il()),this.rl.setConfig(this.el)}onRemoteConfig(t){var e,n,i;if(t.ok){var r=t.config;if("errorTracking"in r){var s=(e=(n=r.errorTracking)==null?void 0:n.suppressionRules)!==null&&e!==void 0?e:[],o=(i=r.errorTracking)==null?void 0:i.captureExtensionExceptions;this.Xo=s,this._instance.persistence&&this._instance.persistence.register({[ia]:this.Xo,[ra]:o})}}}get nl(){var t,e=!!this._instance.get_property(ra),n=this._instance.config.error_tracking.captureExtensionExceptions;return(t=n??e)!==null&&t!==void 0&&t}buildProperties(t,e){return this.tl.buildFromUnknown(t,{syntheticException:e?.syntheticException,mechanism:{handled:e?.handled}})}addExceptionStep(t,e){if(this.el.enabled)try{if(!X(t)||t.trim().length===0)return void St.warn("Ignoring exception step because message must be a non-empty string");var n=(function(s){if(!s)return{sanitizedProperties:{},droppedKeys:[]};var o=[];return{sanitizedProperties:Object.keys(s).reduce(((a,l)=>Ag.has(l)?(o.push(l),a):(a[l]=s[l],a)),{}),droppedKeys:o}})(this.sl(e)),i=n.sanitizedProperties,r=n.droppedKeys;r.length>0&&St.warn("Ignoring reserved exception step fields",{droppedKeys:r}),this.rl.add(I({[Kr]:t,[Yr]:new Date().toISOString()},i))}catch(s){St.error("Failed to add exception step. Ignoring breadcrumb.",s)}}sendExceptionEvent(t){try{var e=t.$exception_list;if(this.al(e)){if(this.ol(e))return this.ll("Exception dropped: matched a suppression rule"),void St.info("Skipping exception capture because a suppression rule matched");if(!this.nl&&this.ul(e))return this.ll("Exception dropped: thrown by a browser extension"),void St.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.hl(e))return this.ll("Exception dropped: thrown by the PostHog SDK"),void St.info("Skipping exception capture because it was thrown by the PostHog SDK")}var n=this.el.enabled&&H(t.$exception_steps)?this.dl(t):t,i=typeof(s=globalThis._posthogReleaseId)=="string"&&s.length>0?s:void 0;i&&(n.$release_id=i);try{var r=this._instance.capture("$exception",n,{_noTruncate:!0,_batchKey:"exceptionEvent",Wn:!0});return r&&this.rl.clear(),r}catch(o){return St.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void St.error("Failed to process exception event. Ignoring this exception.",o)}var s}dl(t){try{var e=this.rl.getAttachable();return e.length===0?t:I({},t,{$exception_steps:e})}catch(n){return St.error("Failed to read buffered exception steps. Capturing exception without steps.",n),t}}ll(t){this.el.enabled&&this.rl.add({[Kr]:t,[Yr]:new Date().toISOString()})}sl(t){return he(t)?I({},t):{}}il(){var t,e;return(t=(e=this._instance.config.error_tracking)==null?void 0:e.exception_steps)!==null&&t!==void 0?t:{}}ol(t){if(t.length===0)return!1;try{var e=t.reduce(((n,i)=>{var r=i.type,s=i.value;return X(r)&&r.length>0&&n.$exception_types.push(r),X(s)&&s.length>0&&n.$exception_values.push(s),n}),{$exception_types:[],$exception_values:[]});return this.Xo.some((n=>{var i=n.values.map((r=>{var s=zf[r.operator],o=e[r.key];if(!s||!o)return!1;var a=U(r.value)?r.value:[r.value];return a.length>0&&s(a,o)}));return n.type==="OR"?i.some(Boolean):i.every(Boolean)}))}catch(n){return St.warn("Failed to evaluate suppression rules. Capturing the exception.",n),!1}}ul(t){return t.flatMap((e=>{var n,i;return(n=(i=e.stacktrace)==null?void 0:i.frames)!==null&&n!==void 0?n:[]})).some((e=>e.filename&&e.filename.startsWith("chrome-extension://")))}hl(t){if(t.length>0){var e,n,i,r,s=(e=(n=t[0].stacktrace)==null?void 0:n.frames)!==null&&e!==void 0?e:[],o=s[s.length-1];return(i=o==null||(r=o.filename)==null?void 0:r.includes("posthog.com/static"))!==null&&i!==void 0&&i}return!1}al(t){return!H(t)&&U(t)}}},Jm=I({productTours:class{get Mr(){return this._instance.persistence}constructor(t){this.vl=null,this.cl=null,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(t.ok){var e=t.config;if("productTours"in e){var n,i;if(this.Mr&&this.Mr.register({[ol]:!!e.productTours}),!Oo(this._instance))return!this.vl&&H((n=this.Mr)==null?void 0:n.props[Mi])||xr.info("product tours disabled; stopping and clearing cached tours"),(i=this.vl)==null||i.stop(),this.vl=null,void this.clearCache();this.loadIfEnabled()}}}loadIfEnabled(){!this.vl&&Oo(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.generateProductTours?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",(i=>{i?xr.error("Could not load product tours script",i):t()}))}fl(){var t;!this.vl&&(t=B.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=B.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(t,e){if(e===void 0&&(e=!1),!U(this.cl)||e){var n=this.Mr;if(n){var i=n.props[Mi];if(U(i)&&!e)return this.cl=i,void t(i,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",timestampMode:"query",callback:r=>{if(Oo(this._instance)){var s=r.statusCode;if(s!==200||!r.json){var o="Product Tours API could not be loaded, status: "+s;return s===0?r.error||xr.warn(o):xr.error(o),void t([],{isLoaded:!1,error:o})}var a=U(r.json.product_tours)?r.json.product_tours:[];this.cl=a,n&&n.register({[Mi]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){H(this.vl)?t([],{isLoaded:!1,error:"Product tours not loaded"}):this.vl.getActiveProductTours(t)}showProductTour(t){var e;(e=this.vl)==null||e.showTourById(t)}previewTour(t){this.vl?this.vl.previewTour(t):this.ai((()=>{var e;this.fl(),(e=this.vl)==null||e.previewTour(t)}))}dismissProductTour(){var t;(t=this.vl)==null||t.dismissTour("user_clicked_skip")}nextStep(){var t;(t=this.vl)==null||t.nextStep()}previousStep(){var t;(t=this.vl)==null||t.previousStep()}clearCache(){var t;this.cl=null,(t=this.Mr)==null||t.unregister(Mi)}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)}}},Cs),Zm={siteApps:class{constructor(t){this.pl=0,this._instance=t,this.gl=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}ml(t,e){if(e){var n=this.globalsForEvent(e);this.gl.push(n),this.gl.length>1e3&&(this.gl=this.gl.slice(10))}}get siteAppLoaders(){var t;return(t=B._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,n,i,r,s,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var f=d[0];l[f]={id:u[f],type:f,properties:d[1]}}var h=t.$set_once,p=t.$set;return{event:I({},pd(t,jm),{properties:I({},t.properties,p?{$set:I({},(e=(n=t.properties)==null?void 0:n.$set)!==null&&e!==void 0?e:{},p)}:{},h?{$set_once:I({},(i=(r=t.properties)==null?void 0:r.$set_once)!==null&&i!==void 0?i:{},h)}:{}),elements_chain:(s=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&s!==void 0?s:"",distinct_id:(a=t.properties)==null?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}bl(t){var e,n=(e=t.tagName)==null?void 0:e.toLowerCase();return n==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(Et.error("prepare_external_dependency_stylesheet returned null"),null):n==="script"&&this._instance.config.prepare_external_dependency_script?this._instance.config.prepare_external_dependency_script(t)||(Et.error("prepare_external_dependency_script returned null"),null):t}_l(){var t,e,n,i,r,s,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=P?.defaultView,u=l==null||(t=l.Node)==null?void 0:t.prototype;if(!l||!u)return()=>{};if(this.pl++,this.wl)return this.kl();var c=[],d=this,f=new WeakSet,h=(m,v,E)=>{if(m!=null&&m[v]){var S=m[v];m[v]=E(S),c.push((()=>{m[v]=S}))}},p=m=>{if(f.has(m))return m;var v=d.bl(m);return v&&f.add(v),v},g=m=>m.map((v=>typeof v=="string"?v:p(v))).filter((v=>!Ye(v)));return h(u,"appendChild",(m=>function(v){var E=p(v);return E?m.call(this,E):v})),h(u,"insertBefore",(m=>function(v,E){var S=p(v);return S?m.call(this,S,E):v})),h(u,"replaceChild",(m=>function(v,E){var S=p(v);return S?m.call(this,S,E):E})),[(e=l.Element)==null?void 0:e.prototype,(n=l.Document)==null?void 0:n.prototype,(i=l.DocumentFragment)==null?void 0:i.prototype].forEach((m=>{h(m,"append",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),h(m,"prepend",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))}))})),[(r=l.Element)==null?void 0:r.prototype,(s=l.CharacterData)==null?void 0:s.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((m=>{h(m,"before",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),h(m,"after",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),h(m,"replaceWith",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];var b=g(S);return S.length&&!b.length?void 0:v.apply(this,b)}))})),h((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(v,E){var S=p(E);return S?m.call(this,v,S):null})),this.wl=()=>{c.forEach((m=>m())),this.wl=void 0},this.kl()}kl(){var t=!1;return()=>{var e;t||(t=!0,this.pl--,this.pl===0&&((e=this.wl)==null||e.call(this)))}}xl(t,e){e===void 0&&(e=!0);var n=this._l();try{var i=t(n);return e&&n(),i}catch(r){throw n(),r}}setupSiteApp(t){var e=this.apps[t.id],n=()=>{var o;!e.errored&&this.gl.length&&(Et.info("Processing "+this.gl.length+" events for site app with id "+t.id),this.gl.forEach((a=>this.xl((()=>e.processEvent==null?void 0:e.processEvent(a))))),e.processedBuffer=!0),Object.values(this.apps).every((a=>a.processedBuffer||a.errored))&&((o=this.yl)==null||o.call(this))},i=!1,r=o=>{e.errored=!o,e.loaded=!0,Et.info("Site app with id "+t.id+" "+(o?"loaded":"errored")),i&&n()};try{var s=this.xl((o=>t.init({posthog:this._instance,callback(a){o(),r(a)}})),!1).processEvent;s&&(e.processEvent=s),i=!0}catch(o){Et.error(fu+t.id,o),r(!1)}if(i&&e.loaded)try{n()}catch(o){Et.error("Error while processing buffered events PostHog app with config id "+t.id,o),e.errored=!0}}Sl(){var t=this.siteAppLoaders||[];for(var e of t)this.apps[e.id]={id:e.id,loaded:!1,errored:!1,processedBuffer:!1};for(var n of t)this.setupSiteApp(n)}Cl(t){var e=this;if(Object.keys(this.apps).length!==0){var n=this.globalsForEvent(t),i=function(s){try{e.xl((()=>s.processEvent==null?void 0:s.processEvent(n)))}catch(o){Et.error("Error while processing event "+t.event+" for site app "+s.id,o)}};for(var r of Object.values(this.apps))i(r)}}onRemoteConfig(t){var e,n,i,r=this;if((e=this.siteAppLoaders)!=null&&e.length)return this.isEnabled?(this.Sl(),void this._instance.on("eventCaptured",(l=>this.Cl(l)))):void Et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((n=this.yl)==null||n.call(this),t.ok){var s=t.config;if((i=s.siteApps)!=null&&i.length)if(this.isEnabled){var o=function(){var l,u=a.id,c=a.url;B["__$$ph_site_app_"+u]=r._instance,(l=B.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(r._instance,c,(d=>{if(d)return Et.error(fu+u,d)}))};for(var a of s.siteApps)o()}else Et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},Xm={tracingHeaders:class{constructor(t){this.Ml=void 0,this.Tl=void 0,this.El=void 0,this.Uo=()=>{var e,n,i=this.Il();i?(C(this.Ml)&&(this.Ml=(e=B.__PosthogExtensions__)==null||(e=e.tracingHeadersPatchFns)==null?void 0:e._patchXHR(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager)),C(this.Tl)&&(this.Tl=(n=B.__PosthogExtensions__)==null||(n=n.tracingHeadersPatchFns)==null?void 0:n._patchFetch(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager))):this.Qo()},this._instance=t}initialize(){this.startIfEnabledOrStop()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",(i=>{if(i)return Bm.error("failed to load script",i);t()}))}Pl(){var t,e;return(t=(e=this._instance.config.tracing_headers)!==null&&e!==void 0?e:this._instance.config.addTracingHeaders)!==null&&t!==void 0?t:this._instance.config.__add_tracing_headers}Il(){var t=this.Pl();return U(t)?(U(this.El)?this.El.splice(0,this.El.length,...t):this.El=[...t],t.length>0?this.El:void 0):(U(this.El)&&this.El.splice(0),this.El=t||void 0,this.El)}Qo(){var t,e;(t=this.Ml)==null||t.call(this),(e=this.Tl)==null||e.call(this),this.Ml=void 0,this.Tl=void 0}startIfEnabledOrStop(){this.Il()?this.ai(this.Uo):this.Qo()}}},Qm=I({surveys:class{get Ne(){return this._instance.config}constructor(t){this.Rl=void 0,this._surveyManager=null,this.Al=!1,this.Fl=[],this.Ll=null,this.Ol=null,this._instance=t,this._surveyEventReceiver=null}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this.Ne.disable_surveys){if(!t.ok)return Q.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(H(e))return Q.warn("Flags not loaded yet. Not loading surveys.");var n=U(e);this.Rl=n?e.length>0:e,Q.info("flags response received, isSurveysEnabled: "+this.Rl),this.loadIfEnabled()}}reset(){try{var t;(t=this._surveyEventReceiver)==null||t.reset(),localStorage.removeItem("lastSeenSurveyDate");for(var e=[],n=0;nlocalStorage.removeItem(r)))}catch{}}loadIfEnabled(){if(!this._surveyManager)if(this.Al)Q.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)Q.info(hu);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())Q.info("Not loading surveys in cookieless mode without consent.");else{var t=B?.__PosthogExtensions__;if(t){if(!C(this.Rl)||this.Ne.advanced_enable_surveys){var e=this.Rl||this.Ne.advanced_enable_surveys;this.Al=!0;try{var n=t.generateSurveys;if(n)return void this.Dl(n,e);var i=t.loadExternalDependency;if(!i)return void this.$l(ll);i(this._instance,"surveys",(r=>{r||!t.generateSurveys?this.$l("Could not load surveys script",r):this.Dl(t.generateSurveys,e)}))}catch(r){throw this.$l("Error initializing surveys",r),r}finally{this.Al=!1}}}else Q.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new Wm(this._instance),Q.info("Surveys loaded successfully"),this.Nl({isLoaded:!0})}$l(t,e){Q.error(t,e),this.Nl({isLoaded:!1,error:t})}onSurveysLoaded(t){return this.Fl.push(t),this._surveyManager&&this.Nl({isLoaded:!0}),()=>{this.Fl=this.Fl.filter((e=>e!==t))}}getSurveys(t,e){if(e===void 0&&(e=!1),this.Ne.disable_surveys)return Q.info(hu),t([]);var n,i=this._instance.get_property(la);if(i&&!e)return t(i,{isLoaded:!0}),void(this.ql()&&this.getSurveys((()=>{}),!0));typeof Promise<"u"&&this.Ll?this.Ll.then((r=>t(r.surveys,r.context))):(typeof Promise<"u"&&(this.Ll=new Promise((r=>{n=r}))),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this.Ne.token),method:"GET",timestampMode:"query",timeout:this.Ne.surveys_request_timeout_ms,callback:r=>{var s;this.Ll=null;var o=r.statusCode;if(o!==200||!r.json){var a="Surveys API could not be loaded, status: "+o;o!==0?Q.error(a):r.error||Q.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(n==null||n({surveys:[],context:l}))}this.Ol=null;var u,c=r.json.surveys||[],d=c.filter((h=>(function(p){return!(!p.start_date||p.end_date)})(h)&&(Vf(h)||(function(p){var g;return!((g=p.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(h))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(s=this._instance.persistence)==null||s.register({[la]:c,[Xr]:Date.now()});var f={isLoaded:!0};t(c,f),n?.({surveys:c,context:f})}}))}ql(){return this.jl()&&!this.Ll&&!this.Bl()}jl(){var t=this._instance.get_property(Xr);return ke(t)&&Date.now()-t>3e5}Bl(){return ke(this.Ol)&&3e5>Date.now()-this.Ol}markSurveyAsSeen(t,e){var n,i={id:t,current_iteration:(n=e?.iteration)!==null&&n!==void 0?n:null};Kf(i);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}}Nl(t){for(var e of this.Fl)try{if(!t.isLoaded)return e([],t);this.getSurveys(e)}catch(n){Q.error("Error in survey callback",n)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!H(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);Q.warn("init was not called")}Hl(t){var e=null;return this.getSurveys((n=>{var i;e=(i=n.find((r=>r.id===t)))!==null&&i!==void 0?i:null})),e}Ul(t){if(H(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(H(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(H(this._surveyManager))return Q.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 H(this._surveyManager)?(Q.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Ir})):new Promise((n=>{this.getSurveys((i=>{var r,s=(r=i.find((a=>a.id===t)))!==null&&r!==void 0?r:null;if(s){var o=this.zl(s);n({visible:o.eligible,disabledReason:o.reason})}else n({visible:!1,disabledReason:"Survey not found"})}),e)}))}renderSurvey(t,e,n){var i;if(H(this._surveyManager))Q.warn("init was not called");else{var r=typeof t=="string"?this.Hl(t):t;if(r!=null&&r.id)if(Im.includes(r.type)){var s=P?.querySelector(e);if(s)return(i=r.appearance)!=null&&i.surveyPopupDelaySeconds?(Q.info("Rendering survey "+r.id+" with delay of "+r.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;Q.info("Rendering survey "+r.id+" with delay of "+((o=r.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(a=this._surveyManager)==null||a.renderSurvey(r,s,n),Q.info("Survey "+r.id+" rendered")}),1e3*r.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(r,s,n);Q.warn("Survey element not found")}else Q.warn("Surveys of type "+r.type+" cannot be rendered in the app");else Q.warn("Survey not found")}}displaySurvey(t,e){var n;if(H(this._surveyManager))Q.warn("init was not called");else{var i=this.Hl(t);if(i){var r=i;if((n=i.appearance)!=null&&n.surveyPopupDelaySeconds&&e.ignoreDelay&&(r=I({},i,{appearance:I({},i.appearance,{surveyPopupDelaySeconds:0})})),e.displayType!==_a.Popover&&e.initialResponses&&Q.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),e.ignoreConditions===!1){var s=this.Ul(i);if(!s.eligible)return void Q.warn("Survey is not eligible to be displayed: ",s.reason)}e.displayType!==_a.Inline?this._surveyManager.handlePopoverSurvey(r,e):this.renderSurvey(r,e.selector,e.properties)}else Q.warn("Survey not found")}}cancelPendingSurvey(t){H(this._surveyManager)?Q.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},Cs),ev={toolbar:class{constructor(t){this.instance=t}Wl(t){B.ph_toolbar_state=t}Vl(){var t;return(t=B.ph_toolbar_state)!==null&&t!==void 0?t:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(t,e,n){if(t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),ga(this.instance.config)||!w||!P)return!1;t=t??w.location,n=n??w.history;try{if(!e){try{w.localStorage.setItem("test","test"),w.localStorage.removeItem("test")}catch{return!1}e=w?.localStorage}var i,r=zm||os(t.hash,"__posthog")||os(t.hash,"state"),s=r?Rc((()=>JSON.parse(atob(decodeURIComponent(r)))))||Rc((()=>JSON.parse(decodeURIComponent(r)))):null;return s&&s.action==="ph_authorize"?((i=s).source="url",i&&Object.keys(i).length>0&&(s.desiredHash?t.hash=s.desiredHash:n?n.replaceState(n.state,"",t.pathname+t.search):t.hash="")):((i=JSON.parse(e.getItem(pu)||"{}")).source="localstorage",delete i.userIntent),!(!i.token||this.instance.config.token!==i.token||(this.loadToolbar(i),0))}catch{return!1}}Zl(t){var e=B.ph_load_toolbar||B.ph_load_editor;!H(e)&&je(e)?e(t,this.instance):gu.warn("No toolbar load function found")}loadToolbar(t){var e=!(P==null||!P.getElementById(cf));if(!w||e)return!1;var n=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,i=I({token:this.instance.config.token},t,{apiURL:this.instance.requestRouter.endpointFor("ui")},n?{instrument:!1}:{});if(w.localStorage.setItem(pu,JSON.stringify(I({},i,{source:void 0}))),this.Vl()===2)this.Zl(i);else if(this.Vl()===0){var r;this.Wl(1),(r=B.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"toolbar",(s=>{if(s)return gu.error("[Toolbar] Failed to load",s),void this.Wl(0);this.Wl(2),this.Zl(i)})),ve(w,"turbolinks:load",(()=>{this.Wl(0),this.loadToolbar(i)}))}return!0}Gl(t){return this.loadToolbar(t)}maybeLoadEditor(t,e,n){return t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),this.maybeLoadToolbar(t,e,n)}}},tv=I({experiments:Me},Cs),nv={conversations:class{constructor(t){this.Ql=void 0,this._conversationsManager=null,this.Kl=!1,this.Jl=null,this.Yl=!1,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this._instance.config.disable_conversations&&(this.Xl=t.ok,t.ok)){var e=t.config.conversations;H(e)||(mt(e)?this.Ql=e:(this.Ql=e.enabled,this.Jl=e),this.loadIfEnabled())}}reset(){var t;(t=this._conversationsManager)==null||t.reset(),this._conversationsManager=null,this.Ql=void 0,this.Jl=null,this.Xl=void 0,this.Yl=!1}loadIfEnabled(){if(!(this._conversationsManager||this.Kl||this._instance.config.disable_conversations||ga(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=B?.__PosthogExtensions__;if(t&&!C(this.Ql)&&this.Ql)if(this.Jl&&this.Jl.token){this.Kl=!0;try{var e=t.initConversations;if(e)return this.tu(e),void(this.Kl=!1);var n=t.loadExternalDependency;if(!n)return void this.eu(ll);n(this._instance,"conversations",(i=>{i||!t.initConversations?this.eu("Could not load conversations script",i):this.tu(t.initConversations),this.Kl=!1}))}catch(i){this.eu("Error initializing conversations",i),this.Kl=!1}}else ot.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,ot.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else ot.error("Cannot complete initialization: remote config is null")}eu(t,e){ot.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():ot.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!Ye(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":ga(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.Xl===!1?"remote_config_failed":C(this.Ql)?this.Xl?"disabled_in_project":"remote_config_pending":this.Ql?H(this.Jl)||!this.Jl.token?"missing_token":B!=null&&B.__PosthogExtensions__?this.Kl?"initializing":this.Yl?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.isVisible())!==null&&t!==void 0&&t}sendMessage(t,e,n){var i=this;return se((function*(){return i._conversationsManager?i._conversationsManager.sendMessage(t,e,n):(ot.warn(En),null)}))()}getMessages(t,e){var n=this;return se((function*(){return n._conversationsManager?n._conversationsManager.getMessages(t,e):(ot.warn(En),null)}))()}markAsRead(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(ot.warn(En),null)}))()}getTickets(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(ot.warn(En),null)}))()}requestRestoreLink(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(ot.warn(En),null)}))()}restoreFromToken(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(ot.warn(En),null)}))()}restoreFromUrlToken(){var t=this;return se((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(ot.warn(En),null)}))()}getCurrentTicketId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getCurrentTicketId())!==null&&t!==void 0?t:null}getWidgetSessionId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getWidgetSessionId())!==null&&t!==void 0?t:null}Xn(){var t;(t=this._conversationsManager)==null||t.setIdentity()}ts(){var t;(t=this._conversationsManager)==null||t.clearIdentity()}}},iv={logs:class{constructor(t){var e,n=this;this.iu=!1,this.ru=!1,this.rt=pe("[logs]"),this.nu=I({},this.rt,{error(){for(var i=arguments.length,r=new Array(i),s=0;i>s;s++)r[s]=arguments[s];r.some(Su)||n.rt.error(...r)}}),this.tr=[],this.su=[],this.Sa=0,this.au=()=>{var i,r;this.Sa=0,(i=this.ou)==null||i.onReconnect(),(r=this.lu)==null||r.onReconnect()},this._instance=t,this._instance&&(e=this._instance.config.logs)!=null&&e.captureConsoleLogs&&(this.iu=!0),w&&ve(w,"online",this.au)}uu(t,e,n,i){var r,s=(function(o,a){var l,u,c,d,f,h,p,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,v=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,E=C(v)?Math.max(m,2048):Math.max(m,v),S=o?.resourceAttributes;return{serviceName:(d=(f=S?.["service.name"])!==null&&f!==void 0?f:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(h=S?.["service.version"])!==null&&h!==void 0?h:o?.serviceVersion,environment:(p=S?.["deployment.environment"])!==null&&p!==void 0?p:o?.environment,resourceAttributes:S,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:E,maxBatchRecordsPerPost:100,rateCapWindowMs:g,maxLogsPerInterval:v,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}})((r=this._instance)==null||(r=r.config)==null?void 0:r.logs,n);return[new ag(this.hu(t,e),s,this.nu,(()=>this.du()),(o=>o()),void 0,i),s]}vu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.ou||this.cu!==e){var n;(n=this.ou)==null||n.reset(),this.cu=e;var i=this.uu((()=>this.tr),(r=>{this.tr=r}));this.ou=i[0],this.fu=i[1]}return this.ou}pu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.lu||this.gu!==e){var n;(n=this.lu)==null||n.reset(),this.gu=e;var i=this.uu((()=>this.su),(r=>{this.su=r}),{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},Eu);this.lu=i[0],this.mu=i[1]}return this.lu}initialize(){this.loadIfEnabled()}onRemoteConfig(t){var e;if(t.ok){var n=(e=t.config.logs)==null?void 0:e.captureConsoleLogs;!H(n)&&n&&(this.iu=!0,this.loadIfEnabled())}}reset(){var t,e;this.tr=[],(t=this.ou)==null||t.reset(),this.su=[],(e=this.lu)==null||e.reset(),this.Sa=0}captureLog(t){this.vu().captureLog(t)}he(t){this.pu().captureLog(t)}get logger(){return this.yu||(this.yu={trace:(t,e)=>this.captureLog({body:t,level:"trace",attributes:e}),debug:(t,e)=>this.captureLog({body:t,level:"debug",attributes:e}),info:(t,e)=>this.captureLog({body:t,level:"info",attributes:e}),warn:(t,e)=>this.captureLog({body:t,level:"warn",attributes:e}),error:(t,e)=>this.captureLog({body:t,level:"error",attributes:e}),fatal:(t,e)=>this.captureLog({body:t,level:"fatal",attributes:e})}),this.yu}flushLogs(t){t?this.bu(t):(this.ou&&this.ou.flush().catch((e=>this._u(e))),this.lu&&this.lu.flush().catch((e=>this._u(e))))}_u(t){Su(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=B?.__PosthogExtensions__;if(t){var e=t.loadExternalDependency;e?e(this._instance,"logs",(n=>{var i;n||(i=t.logs)==null||!i.initializeLogs?this.rt.error("Could not load logs script",n):(t.logs.initializeLogs(this._instance),this.ru=!0)})):this.rt.error(ll)}else this.rt.error("PostHog Extensions not found.")}}hu(t,e){var n=this._instance;return{get isDisabled(){return!1},get optedOut(){return!n.is_capturing()},getPersistedProperty:i=>i===Ut.LogsQueue?t():void 0,setPersistedProperty(i,r){var s;i===Ut.LogsQueue&&e((s=r)!==null&&s!==void 0?s:[])},Ot:i=>this.Ot(i),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Ot(t){return new Promise((e=>{if(bf(this.Sa,3))e({kind:"fatal",error:Do(void 0,"logs endpoint is unreachable, dropping batch")});else{var n=!1,i=s=>{n||(n=!0,clearTimeout(r),e(s))},r=setTimeout((()=>{this.rt.warn("Logs request timed out before receiving a response"),i({kind:"retry-later",error:Do(void 0,"logs request timed out")})}),9e4);this._instance._send_request({method:"POST",url:this.wu(),data:t,compression:"best-available",batchKey:"logs",fireCallbackOnDrop:!0,callback:s=>{var o=s.statusCode;if(this.ku(o),o>=200&&300>o)i({kind:"ok"});else if(o===413)i({kind:"too-large"});else if(o!==0&&o!==429&&500>o)i({kind:"fatal",error:new Error("logs request failed with status "+o)});else{var a;o===0?(s.error||this.rt.warn("Logs request failed before receiving an HTTP response"),i({kind:"retry-later",error:Do(s.error,"logs request failed before receiving an HTTP response")})):i({kind:"retry-later",error:(a=s.error)!==null&&a!==void 0?a:new Error("logs request failed with status "+o)})}}})}}))}ku(t){(t!==0||this._instance.__loaded)&&(this.Sa=Ef(t,this.Sa,3,(()=>this.rt.warn("Log requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped sending logs; will try again when connectivity changes."))))}bu(t){this.tr.length>0&&this.xu(t,this.tr,this.fu,ne.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,Eu,(e=>{this.su=e}))}xu(t,e,n,i,r){if(e.length!==0){var s=e.map((a=>a.record));r([]);var o=qd(s,zd(n,ne.LIB_NAME,ne.LIB_VERSION),i,ne.LIB_VERSION);this._instance._send_request({method:"POST",url:this.wu(),data:o,compression:"best-available",batchKey:"logs",transport:t})}}wu(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}du(){var t,e={};if(e.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var n=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.windowId,r=n.sessionStartTimestamp,s=n.lastActivityTimestamp;e.sessionId=n.sessionId,e.windowId=i,H(r)||(e.sessionStartTimestamp=r),H(s)||(e.lastActivityTimestamp=s)}if(B!=null&&(t=B.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?fn(B.location.href):B.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},rv={metrics:class{constructor(t){this.rt=pe("[metrics]"),this._instance=t}initialize(){}vu(){var t,e,n=(t=this._instance)==null||(t=t.config)==null?void 0:t.metrics;return this.ou&&this.cu===n||((e=this.ou)==null||e.reset(),this.cu=n,this.ou=new lg(this.hu(),(function(i){var r,s,o,a,l,u=i?.resourceAttributes;return{serviceName:(r=u?.["service.name"])!==null&&r!==void 0?r:i?.serviceName,serviceVersion:(s=u?.["service.version"])!==null&&s!==void 0?s:i?.serviceVersion,environment:(o=u?.["deployment.environment"])!==null&&o!==void 0?o:i?.environment,resourceAttributes:u,beforeSend:i?.beforeSend,flushIntervalMs:(a=i?.flushIntervalMs)!==null&&a!==void 0?a:1e4,maxSeriesPerFlush:(l=i?.maxSeriesPerFlush)!==null&&l!==void 0?l:1e3}})(n),this.rt)),this.ou}count(t,e,n){e===void 0&&(e=1),this.vu().count(t,e,n)}gauge(t,e,n){this.vu().gauge(t,e,n)}histogram(t,e,n){this.vu().histogram(t,e,n)}flush(t){if(!this.ou)return Promise.resolve();if(t){var e=this.ou.drainWindow();return e&&this.Jt(e,t),Promise.resolve()}return this.ou.flush().catch((n=>this.rt.error("PostHog metrics flush failed:",n)))}reset(){var t;(t=this.ou)==null||t.reset()}hu(){var t=this._instance,e=this;return{get isDisabled(){return!1},get optedOut(){return!t.is_capturing()},Jt:n=>e.Jt(n),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Jt(t,e){return new Promise((n=>{var i=!1,r=o=>{i||(i=!0,clearTimeout(s),n(o))},s=setTimeout((()=>r({kind:"retry-later",error:new Error("metrics request timed out")})),9e4);this._instance._send_request(I({method:"POST",url:this.Su(),data:t,compression:"best-available",batchKey:"metrics"},e&&{transport:e},{fireCallbackOnDrop:!0,callback(o){var a=o.statusCode;if(a>=200&&300>a)r({kind:"ok"});else if(a===413)r({kind:"too-large"});else if(a!==0&&a!==429&&500>a)r({kind:"fatal",error:new Error("metrics request failed with status "+a)});else{var l;r({kind:"retry-later",error:(l=o.error)!==null&&l!==void 0?l:new Error("metrics request failed with status "+a)})}}}))}))}Su(){return this._instance.requestRouter.endpointFor("api","/i/v1/metrics")+"?token="+encodeURIComponent(this._instance.config.token)}}},sv=I({},Cs,Gm,Km,Ym,Jm,Zm,Qm,Xm,ev,tv,nv,iv,rv);Ze.__defaultExtensionClasses=I({},sv);(function(){ne.SDK_DIST_CHANNEL="npm";var t=Wi[Gn]=new Ze;return(function(){function e(){e.done||(e.done=!0,Jf=!1,ie(Wi,(function(n){n._dom_loaded()})))}P!=null&&P.addEventListener?P.readyState==="complete"?e():ve(P,"DOMContentLoaded",e,{capture:!1}):w&&A.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const ov=["a[href]","button:not([disabled])","input:not([disabled]):not([type='hidden'])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(",");let pt=null,ka=null,Xf="";const Ca=new Map;function Qf(t){return[...t.querySelectorAll(ov)].filter(e=>!e.hidden&&e.getAttribute("aria-hidden")!=="true"&&e.getClientRects().length>0)}function av(t){for(const e of document.body.children)e===t||e.tagName==="SCRIPT"||(Ca.set(e,{inert:e.inert,ariaHidden:e.getAttribute("aria-hidden")}),e.inert=!0,e.setAttribute("aria-hidden","true"))}function lv(){for(const[t,e]of Ca)t.inert=e.inert,e.ariaHidden===null?t.removeAttribute("aria-hidden"):t.setAttribute("aria-hidden",e.ariaHidden);Ca.clear()}function eh(t){return t?.dataset.modalDismissible!=="false"&&t?.getAttribute("aria-busy")!=="true"}function We(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n)return!1;pt&&pt!==n&&ze(pt,{restoreFocus:!1,force:!0}),ka=e.trigger||document.activeElement,pt=n,Xf=document.body.style.overflow,av(n),document.body.style.overflow="hidden",n.classList.add("open"),n.setAttribute("aria-hidden","false");const i=n.querySelector(".modal-content");i&&(i.style.transform="scale(1) translateY(0)");const r=()=>{if(pt!==n)return;((e.initialFocus?n.querySelector(e.initialFocus):n.querySelector("[data-modal-initial-focus]"))||Qf(n)[0]||n.querySelector(".modal-content")||n).focus({preventScroll:!0})};return requestAnimationFrame(r),setTimeout(r,260),!0}function ze(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n||!e.force&&!eh(n))return!1;n.classList.remove("open"),n.setAttribute("aria-hidden","true"),lv(),document.body.style.overflow=Xf,pt=null;const i=ka;return ka=null,e.restoreFocus!==!1&&i?.isConnected&&i.focus({preventScroll:!0}),!0}function xu(t,e,n="Operation in progress"){const i=typeof t=="string"?document.getElementById(t):t;i&&(i.dataset.modalDismissible=e?"false":"true",i.setAttribute("aria-busy",String(!!e)),e?i.setAttribute("aria-label",n):i.removeAttribute("aria-label"))}function cv(t){if(!eh(t))return;const e=t.dataset.modalCloseHandler;e&&typeof window[e]=="function"?window[e]():ze(t)}document.addEventListener("keydown",t=>{if(!pt)return;if(t.key==="Escape"){t.preventDefault(),t.stopImmediatePropagation(),cv(pt);return}if(t.key!=="Tab"){t.stopPropagation();return}const e=Qf(pt);if(!e.length){t.preventDefault(),(pt.querySelector(".modal-content")||pt).focus();return}const n=e[0],i=e[e.length-1];t.shiftKey&&document.activeElement===n?(t.preventDefault(),i.focus()):!t.shiftKey&&document.activeElement===i&&(t.preventDefault(),n.focus())},!0);function uv(){document.querySelectorAll(".modal-overlay").forEach(t=>{t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-hidden",t.classList.contains("open")?"false":"true");const e=t.querySelector(".modal-content");e&&!e.hasAttribute("tabindex")&&(e.tabIndex=-1);const n=t.querySelector("h1, h2, h3");n&&(n.id||(n.id=`${t.id}-title`),t.setAttribute("aria-labelledby",n.id)),t.querySelectorAll(".modal-close").forEach(i=>{i.getAttribute("aria-label")||i.setAttribute("aria-label","Close dialog")})})}const ml=Object.freeze({free:"Free",professional:"Pro",power:"Power"}),dv=Object.freeze({free:2,professional:50,power:2e3}),fv="(contact us)",hv=Object.freeze({free:Object.freeze(["2 generations/month","Gemini model only","Code Review"]),professional:Object.freeze(["50 generations/month","All models","Code Regeneration","Code Review"]),power:Object.freeze(["2000 generations/month","All models","Code Regeneration","Bring your own key (BYOK)","Code Review","All models + early access",`API & MCP access ${fv}`])}),th="CodeFile",nh="GeneratedCode",pv={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function ln(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Aa(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function gv(t={},e=0){const n=Aa(t.artifactType||t.type||th),i=Aa(t.artifactName||t.name||t.fileName||`${nh}-${e+1}`);return`${n||"artifact"}-${i||e+1}`}function ih(t={},e=0){const n=ln(t),i=n.artifactType||n.type||th,r=n.artifactName||n.name||nh;let s=n.fileName||r;return s.endsWith(".dart")||(s+=".dart"),{id:Aa(n.id)||gv({...n,artifactType:i,artifactName:r,fileName:s},e),artifactType:i,artifactName:r,fileName:s,deployPath:n.deployPath||"",description:n.description||"",code:n.code||n.content||"",dependencies:rh(n.dependencies),imports:Array.isArray(n.imports)?n.imports:[],publicApi:Array.isArray(n.publicApi)?n.publicApi:[],relationships:sh(n.relationships),deployStatus:n.deployStatus||"pending",review:n.review||null,metadata:ln(n.metadata),codeType:n.codeType||pv[i]||"O"}}function rh(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const n=ln(e),i=n.name||n.package;return i?{name:i,version:n.version||null,versionRequired:!!(n.versionRequired||n.required),inferred:!!n.inferred,...n.reason?{reason:n.reason}:{}}:null}).filter(Boolean):Object.entries(ln(t)).map(([e,n])=>({name:e,version:n||null,inferred:!1})):[]}function sh(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const n=ln(e);return!n.from&&!n.to?null:{from:n.from||null,to:n.to||null,type:n.type||"uses",description:n.description||""}}).filter(Boolean):[]}function Pa(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;try{return JSON.parse(e)}catch{const n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(!n)return null;try{return JSON.parse(n[1].trim())}catch{return null}}}function Qi(t,e={}){const n=[],i=typeof t=="string"?Pa(t):t,s=ln(i||{});!i&&typeof t=="string"&&n.push("Structured bundle parse failed; using legacy single-artifact fallback.");const o=Array.isArray(s.artifacts)?s.artifacts:[{artifactType:s.artifactType||e.artifactType,artifactName:s.artifactName||e.artifactName,fileName:s.fileName||e.fileName,description:s.description,code:s.code||e.code||(typeof t=="string"?t:""),dependencies:s.dependencies||e.dependencies,relationships:s.relationships||e.relationships}];o.forEach((d,f)=>{!d?.artifactType&&!d?.type&&n.push(`Artifact ${f+1} has no artifactType; it will deploy as a standalone code file under lib/custom_code/ root.`)});const a=o.map((d,f)=>ih(d,f)),l=new Map(o.map((d,f)=>[ln(d).id,a[f]?.id]).filter(([d,f])=>d&&f)),u=d=>l.get(d)||d,c=sh(s.relationships||e.relationships).map(d=>({...d,from:d.from?u(d.from):d.from,to:d.to?u(d.to):d.to}));return{schemaVersion:s.schemaVersion||e.schemaVersion||null,id:s.id||e.id||"bundle-current",title:s.title||s.name||e.title||"Generated artifact bundle",description:s.description||e.description||"",artifacts:a,dependencies:rh(s.dependencies||e.dependencies),relationships:c,deployOrder:Array.isArray(s.deployOrder)?s.deployOrder.map(u):a.map(d=>d.id),warnings:[...n,...Array.isArray(s.warnings)?s.warnings:[]],metadata:ln(s.metadata)}}function oi(t){return Qi(t).artifacts[0]||ih()}function Zt(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function ai(t){return JSON.stringify(t,null,2)}function mv(t){return ai({task:"architect",userRequest:String(t??"")})}function vv(t){const e=Zt(t);return e&&typeof e=="object"&&typeof e.task=="string"?ai(e):ai({task:"generate_bundle",bundleSpec:e})}function _v(t){return ai({task:"review_bundle",generatedBundle:Zt(t),outputRequirements:{bundleReview:["status","score","summary","manualActions","findings"],scoreRange:[0,100],eachArtifact:["id","review.status","review.findings"],manualActions:{definition:"Setup the developer must perform by hand in the FlutterFlow editor that FlutterFlow will NOT do for them.",exclude:["creating the Custom Action, Widget or Code File itself - deploying the code creates it","declaring parameters or return values FlutterFlow derives from the function signature","anything that resolves as a side effect of using the action or widget in the editor","generic advice such as testing, reviewing or rebuilding the app"],preferEmpty:"Return an empty array when nothing qualifies - an empty list is the expected result for most bundles."}}})}function vl(t,e=null){const n={stage:t};return e!=null&&(n.bundle=Zt(e)),n}function yv({bundleSpec:t,artifactBundle:e,bundleReview:n,artifactId:i,userFeedback:r}){return ai({task:"regenerate_artifact",artifactId:i,bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(r)})}function oh({bundleSpec:t,artifactBundle:e,bundleReview:n,userFeedback:i}){return ai({task:"regenerate_bundle",bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(i??"")})}const Iu={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"},wv=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function tt(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function bv(t){return tt(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||tt(t.filterSummary)||tt(t.filterResults):!1}function ah(t,e=0){if(!tt(t)||e>3)return null;if(bv(t))return t;for(const n of wv){const i=t[n];if(tt(i)){const r=ah(i,e+1);if(r)return r}}return null}function ds(t){return Array.isArray(t)?t.some(ds):tt(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(ds):!1}function Fa(t){return Array.isArray(t)?t.some(Fa):tt(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(Fa):!1}function lh(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function Ev(t,e){if(tt(t))for(const[n,i]of Object.entries(t)){if(!tt(i))continue;const r=tt(i.categories)?i.categories:{},s=Object.entries(r).filter(([,o])=>tt(o)&&o.matched===!0).map(([o])=>o);s.length>0?s.forEach(o=>e.add(o)):i.matched===!0&&e.add(lh(n))}}function Sv(t,e){if(!t)return;const n=Array.isArray(t)?t.flatMap(i=>tt(i)?Object.entries(i):[]):Object.entries(t);for(const[i,r]of n){if(!ds(r))continue;const s=lh(i),o=r?.raiFilterResult?.raiFilterTypeResults||(s==="rai"?r?.raiFilterTypeResults:null),a=tt(o)?Object.entries(o).filter(([,l])=>ds(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(s)}}function xv(t){return Iu[t]?Iu[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function ku(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 Iv(t){const e=ah(t);if(!e)return null;const n=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);Ev(e.filterSummary,n),Sv(e.filterResults,n);const i=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||n.size>0,r=e.invocationResult||null,s=Fa(e.filterSummary||e.filterResults);return!i&&!s&&!["PARTIAL","FAILURE"].includes(r)?null:{kind:i?"blocked":"unavailable",invocationResult:r,matchedFilters:[...n]}}function kv(t,e){const n=Iv(t);if(!n)return null;const i=[...new Set(n.matchedFilters.map(xv))],r=n.kind==="blocked",s=new Error(r?`Safety screening blocked this pipeline step for ${ku(i)}.`:"Safety screening could not be completed. Please try again.");return s.name="ModelArmorError",s.code=r?"MODEL_ARMOR_BLOCKED":"MODEL_ARMOR_UNAVAILABLE",s.isModelArmor=!0,s.pipelineStep=e,s.userTitle=r?"Request blocked for safety":"Safety check unavailable",s.userMessage=r?`The safety check detected ${ku(i)}. Edit your request to remove or rephrase the flagged content, then run the pipeline again.`:"The safety service did not finish all of its checks. Please wait a moment and run the pipeline again.",s.retryExplanation=r?"Trying another model would not change this safety decision.":"A fallback model was not attempted because safety screening must complete first.",s.matchedFilters=n.matchedFilters,s}function Cv(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function Cu(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,n=[];for(const i of Cv(t).split(` +`)){if(!/^[A-Za-z_$]/.test(i)||e.test(i))continue;const r=i.match(/^[\w$<>,?\s[\]]+?\s([a-zA-Z_$][\w$]*)\s*\(/);r&&n.push(r[1])}return n}function _l(t,e){const n=t.replace(/\.dart$/,"");if(e==="W")return n.replace(/(^|_)(\w)/g,(i,r,s)=>s.toUpperCase());if(e==="A"){const i=n.replace(/(^|_)(\w)/g,(r,s,o)=>o.toUpperCase());return i.charAt(0).toLowerCase()+i.slice(1)}return e==="F"?"CustomFunctions":e==="C"?t.endsWith(".dart")?t:`${t}.dart`:n}async function Au(t){const e=new TextEncoder().encode(String(t||"")),n=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n),i=>i.toString(16).padStart(2,"0")).join("")}async function Av(t,e=new Map){const n={},i=new Set;for(const[o,a]of t.entries()){if(a.type==="D"||a.type==="O")continue;const l=_l(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await Au(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await Au(c)),n[o]=u,a.type==="F"){const d=Cu(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(h=>i.add(h))}}const r=new Set(Cu(e.get("lib/flutter_flow/custom_functions.dart")||"")),s={functions_to_rename:[],functions_to_delete:[],functions_to_add:Array.from(i).filter(o=>!r.has(o))};return{fileMapContents:JSON.stringify(n),functionsMapContents:JSON.stringify(s)}}const Pv=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),Pu={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},Fv=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),Rv=["Struct","Record"],Tv=[{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=>jo(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=>jo(t).some(e=>{const n=/^\s*final\s+(?:double|int|String|bool|Color|num)\s+(\w+)\s*;/gm;let i;for(;(i=n.exec(e))!==null;){const r=i[1];if(!(new RegExp(`this\\.${r}\\s*=(?!=)`).test(e)||new RegExp(`[:,]\\s*${r}\\s*=(?!=)`).test(e)))return!0}return!1}),pos:`class W extends StatefulWidget { const W({required this.value}); final double value; }`,neg:`class _P { @@ -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=>Uo(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=>jo(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,52 +25,52 @@ class _S extends State { @override Widget build(BuildContext c) => const Size @override _S createState() => _S(); } class _S extends State { @override Widget build(BuildContext c) => Padding(padding: const EdgeInsets.all(8), child: const SizedBox()); }`}];function xt(t,e,n){return{artifactId:t.id,artifactName:t.artifactName,artifactType:t.artifactType,severity:e,message:n}}function er(t){let e="",n=0;for(;n"&&(n--,n===0))return{inner:t.slice(e+1,i),end:i+1};return null}function Tv(t,e){const n=new RegExp(`class\\s+${e}\\b[^{]*\\{`).exec(t);if(!n)return null;let i=0;for(let r=n.index+n[0].length-1;r$v(t).usable);function Lv(t=""){const e=er(t);return Mv.filter(n=>n.detect(e)).map(({id:n,severity:i,message:r})=>({id:n,severity:i,message:r}))}function Nv(t){const e=[],n=t.matchAll(/\bFuture\b/g);for(const i of n){let r=i.index+6,s=null;const o=r;for(;ro;if(t[r]==="<"){const u=Rv(t,r);if(!u||(s=u.inner.replace(/\s+/g," ").trim(),r=u.end,!/\s/.test(t[r]||"")))continue;for(;rPu(o.functionName)===i);if(r)return r;const s=o=>!o.functionName.startsWith("_");return n.find(s)||n[0]}function Ps(t=""){return Array.from(er(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function Ov(t="",e=""){return yl(t,e)?.returnType||null}function Fu(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 Bv(t,e){const n=Ps(e);if(n.length===0)return null;const r=String(t||"").split("/").pop().replace(/\.dart$/,"");if(n.some(l=>Fu(l)===r)||n.length>1)return null;const[o]=n,a=`${Fu(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 wl(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function Dv(t,e,n=""){const i=yl(e,n)?.functionName;if(!i)return null;const r=String(t||"").split("/").pop(),s=_l(r,"A");if(s===i)return null;const o=`${wl(i)}.dart`;return`File name "${r}" does not match Action "${i}". FlutterFlow derives the action from the file name, so it looks for "${s}" and reports Action "${s}" declaration not found. Rename the file to "${o}" - FlutterFlow puts an underscore before every capital - or rename the function to "${s}".`}function jv(t="",e=""){return yl(t,e)!==null}function Uv(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(i=>Av.has(i)?!1:!Pv.some(s=>i.endsWith(s))||e.has(i))}function Hv(t,{functionName:e="",declaredTypes:n=new Set}={}){const i=Ov(t,e),r=Uv(i,n);if(r.length===0)return null;const[s]=r;let o;return n.has(s)?o=`uses Code File type "${s}", which FlutterFlow cannot process as an Action Return Value`:i===s?o="is not a FlutterFlow Action Return Value":o=`uses type "${s}", which is not a FlutterFlow Action Return Value`,`CustomAction return type "${i}" ${o}. Return JSON (Future) or an existing FlutterFlow Data Type (*Struct) instead.`}function Wv(t,e={}){const n=[],i=t.fileName||"",r=t.code||"";if(Cv.has(t.artifactType)||n.push(xt(t,"error",`Unsupported artifact type "${t.artifactType}".`)),i.endsWith(".dart")||n.push(xt(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!r.trim())return n.push(xt(t,"warning","Generated artifact has no Dart code yet.")),n;if(t.artifactType==="CustomWidget"){/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)||n.push(xt(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const s of Lv(r))n.push(xt(t,s.severity,s.message))}if(t.artifactType==="CustomAction"&&!jv(r,t.artifactName)&&n.push(xt(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const s=e.declaredTypes||new Set(Ps(r)),o=Hv(r,{functionName:t.artifactName,declaredTypes:s});o&&n.push(xt(t,"error",o));const a=Dv(i,r,t.artifactName);a&&n.push(xt(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)&&n.push(xt(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const s=Bv(i,r);s&&n.push(xt(t,"info",s))}return n}function zv(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],n=new Set(e.flatMap(s=>Ps(s.code||""))),i=e.flatMap(s=>Wv(s,{declaredTypes:n})),r=e.map(s=>({artifactId:s.id,fileName:s.fileName,pathHint:Au[s.artifactType]||Au.CodeFile}));return{valid:i.every(s=>s.severity!=="error"),findings:i,deployHints:r}}const Ru="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function Tu(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function qv(t=""){const e=t.indexOf(Ru);return e===-1?t:t.slice(e+Ru.length).replace(/^\s*\n/,"")}const Vv=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function Gv(t="",e=""){const n=qv(t),i=new Set((e.match(/^\s*import .*$/gm)||[]).map(Tu).filter(Boolean)),r=n.split(` -`).filter(s=>{const o=Tu(s);return o===null||!i.has(o)?!0:!Vv.test(s)}).join(` -`).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+r}const Kv=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations"]);function lh(t){let e="",n=0;for(;n{const i=n.name||n.package;if(!i||i==="flutter")return e;const r=n.versionRequired||n.required;return e[i]=r&&n.version||"",e},{})}function Qv(t){const e=new Map,n=new Map,i=[];for(const r of t)e.has(r.fileName)?i.push(`Duplicate deploy file name "${r.fileName}" for artifacts "${e.get(r.fileName)}" and "${r.artifactId}".`):e.set(r.fileName,r.artifactId),n.has(r.path)?i.push(`Duplicate deploy path "${r.path}" for artifacts "${n.get(r.path)}" and "${r.artifactId}".`):n.set(r.path,r.artifactId);return i}function e_(t,e={}){const n=Array.isArray(t?.artifacts)?t.artifacts:[],r=(e.selectedArtifactIds||t?.deployOrder||n.map(h=>h.id)).map(h=>n.find(p=>p.id===h)).filter(Boolean),s=[...t?.warnings||[]];let o=[];r.forEach(h=>{const p=Xv(h),g=h.fixedCode||h.code||"",m=h.codeType||Jv[h.artifactType]||Xe.OTHER;g.trim()||s.push(`${h.artifactName||h.id} has no generated code.`),o.push({artifactId:h.id,artifactName:h.artifactName,artifactType:h.artifactType,fileName:p,content:g,type:m,path:h.deployPath||Zv(p,m),deployPath:h.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((h,p)=>({entry:h,index:p})).filter(({entry:h})=>h.type===Xe.FUNCTION&&h.path===a);if(l.length>1){const h=l[0],p={...h.entry,artifactId:l.map(({entry:m})=>m.artifactId).join("+"),artifactName:h.entry.artifactName,content:l.map(({entry:m})=>`// ${m.artifactId} +`;)n++;e+=" "}else if(i==="/*"){for(n+=2;n"&&(n--,n===0))return{inner:t.slice(e+1,i),end:i+1};return null}function Mv(t,e){const n=new RegExp(`class\\s+${e}\\b[^{]*\\{`).exec(t);if(!n)return null;let i=0;for(let r=n.index+n[0].length-1;rLv(t).usable);function Ov(t=""){const e=er(t);return Nv.filter(n=>n.detect(e)).map(({id:n,severity:i,message:r})=>({id:n,severity:i,message:r}))}function Bv(t){const e=[],n=t.matchAll(/\bFuture\b/g);for(const i of n){let r=i.index+6,s=null;const o=r;for(;ro;if(t[r]==="<"){const u=$v(t,r);if(!u||(s=u.inner.replace(/\s+/g," ").trim(),r=u.end,!/\s/.test(t[r]||"")))continue;for(;rFu(o.functionName)===i);if(r)return r;const s=o=>!o.functionName.startsWith("_");return n.find(s)||n[0]}function As(t=""){return Array.from(er(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function Dv(t="",e=""){return yl(t,e)?.returnType||null}function Ru(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 jv(t,e){const n=As(e);if(n.length===0)return null;const r=String(t||"").split("/").pop().replace(/\.dart$/,"");if(n.some(l=>Ru(l)===r)||n.length>1)return null;const[o]=n,a=`${Ru(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 wl(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function Uv(t,e,n=""){const i=yl(e,n)?.functionName;if(!i)return null;const r=String(t||"").split("/").pop(),s=_l(r,"A");if(s===i)return null;const o=`${wl(i)}.dart`;return`File name "${r}" does not match Action "${i}". FlutterFlow derives the action from the file name, so it looks for "${s}" and reports Action "${s}" declaration not found. Rename the file to "${o}" - FlutterFlow puts an underscore before every capital - or rename the function to "${s}".`}function Hv(t="",e=""){return yl(t,e)!==null}function Wv(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(i=>Fv.has(i)?!1:!Rv.some(s=>i.endsWith(s))||e.has(i))}function zv(t,{functionName:e="",declaredTypes:n=new Set}={}){const i=Dv(t,e),r=Wv(i,n);if(r.length===0)return null;const[s]=r;let o;return n.has(s)?o=`uses Code File type "${s}", which FlutterFlow cannot process as an Action Return Value`:i===s?o="is not a FlutterFlow Action Return Value":o=`uses type "${s}", which is not a FlutterFlow Action Return Value`,`CustomAction return type "${i}" ${o}. Return JSON (Future) or an existing FlutterFlow Data Type (*Struct) instead.`}function qv(t,e={}){const n=[],i=t.fileName||"",r=t.code||"";if(Pv.has(t.artifactType)||n.push(xt(t,"error",`Unsupported artifact type "${t.artifactType}".`)),i.endsWith(".dart")||n.push(xt(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!r.trim())return n.push(xt(t,"warning","Generated artifact has no Dart code yet.")),n;if(t.artifactType==="CustomWidget"){/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)||n.push(xt(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const s of Ov(r))n.push(xt(t,s.severity,s.message))}if(t.artifactType==="CustomAction"&&!Hv(r,t.artifactName)&&n.push(xt(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const s=e.declaredTypes||new Set(As(r)),o=zv(r,{functionName:t.artifactName,declaredTypes:s});o&&n.push(xt(t,"error",o));const a=Uv(i,r,t.artifactName);a&&n.push(xt(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)&&n.push(xt(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const s=jv(i,r);s&&n.push(xt(t,"info",s))}return n}function Vv(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],n=new Set(e.flatMap(s=>As(s.code||""))),i=e.flatMap(s=>qv(s,{declaredTypes:n})),r=e.map(s=>({artifactId:s.id,fileName:s.fileName,pathHint:Pu[s.artifactType]||Pu.CodeFile}));return{valid:i.every(s=>s.severity!=="error"),findings:i,deployHints:r}}const Tu="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function $u(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function Gv(t=""){const e=t.indexOf(Tu);return e===-1?t:t.slice(e+Tu.length).replace(/^\s*\n/,"")}const Kv=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function Yv(t="",e=""){const n=Gv(t),i=new Set((e.match(/^\s*import .*$/gm)||[]).map($u).filter(Boolean)),r=n.split(` +`).filter(s=>{const o=$u(s);return o===null||!i.has(o)?!0:!Kv.test(s)}).join(` +`).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+r}const Jv=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations"]);function ch(t){let e="",n=0;for(;n{const i=n.name||n.package;if(!i||i==="flutter")return e;const r=n.versionRequired||n.required;return e[i]=r&&n.version||"",e},{})}function t_(t){const e=new Map,n=new Map,i=[];for(const r of t)e.has(r.fileName)?i.push(`Duplicate deploy file name "${r.fileName}" for artifacts "${e.get(r.fileName)}" and "${r.artifactId}".`):e.set(r.fileName,r.artifactId),n.has(r.path)?i.push(`Duplicate deploy path "${r.path}" for artifacts "${n.get(r.path)}" and "${r.artifactId}".`):n.set(r.path,r.artifactId);return i}function n_(t,e={}){const n=Array.isArray(t?.artifacts)?t.artifacts:[],r=(e.selectedArtifactIds||t?.deployOrder||n.map(h=>h.id)).map(h=>n.find(p=>p.id===h)).filter(Boolean),s=[...t?.warnings||[]];let o=[];r.forEach(h=>{const p=e_(h),g=h.fixedCode||h.code||"",m=h.codeType||Xv[h.artifactType]||Xe.OTHER;g.trim()||s.push(`${h.artifactName||h.id} has no generated code.`),o.push({artifactId:h.id,artifactName:h.artifactName,artifactType:h.artifactType,fileName:p,content:g,type:m,path:h.deployPath||Qv(p,m),deployPath:h.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((h,p)=>({entry:h,index:p})).filter(({entry:h})=>h.type===Xe.FUNCTION&&h.path===a);if(l.length>1){const h=l[0],p={...h.entry,artifactId:l.map(({entry:m})=>m.artifactId).join("+"),artifactName:h.entry.artifactName,content:l.map(({entry:m})=>`// ${m.artifactId} ${m.content}`).join(` -`)},g=new Set(l.slice(1).map(({index:m})=>m));o=o.filter((m,v)=>!g.has(v)),o[h.index]=p}const u={...$u(t?.dependencies),...r.reduce((h,p)=>({...h,...$u(p.dependencies)}),{})},c={};r.forEach(h=>{bl(h.code||"").forEach(p=>{p in u||(c[p]="")})});const d={...c,...u},f=Qv(o);return{bundleId:t?.id||"bundle-current",title:t?.title||"Generated artifact bundle",fileEntries:o,dependencies:d,relationships:t?.relationships||[],warnings:s,errors:f}}function t_(t){return String(t||"").match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/)?.[1]}function n_(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 i_(t,e){const i=[n_(t),t_(e.content),e.artifactName].find(r=>/^[A-Z][A-Za-z0-9_]*$/.test(String(r||"")));if(!i)throw new Error(`Cannot derive a FlutterFlow custom class name for ${t}.`);return i}function r_(t,e=new Map){const n=[];for(const[i,r]of t.entries())r.type!=="C"||e.has(r.path)||n.push({artifactId:r.artifactId||i,className:i_(i,r),content:r.content,fileName:i,path:r.path});return n}function s_(t,e){const n=new Set(e.map(i=>i.path));return new Map(Array.from(t.entries()).filter(([,i])=>!n.has(i.path)))}const Mu={pass:0,warning:1,fail:2},o_=["manualActions"];function st(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Vt(...t){for(const e of t){if(typeof e=="string"&&e.trim())return e.trim();if(Array.isArray(e)&&e.length>0){const n=e.filter(i=>typeof i=="string").join(` -`);if(n)return n}}return""}function kt(t){return t==null?[]:Array.isArray(t)?t:[t]}function a_(t){const e=st(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const n=Number(e);if(Number.isFinite(n))return Lu(n);const i=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return i?Lu(Number(i[1])):null}function Lu(t){return t>=0&&t<=100?t:null}function lt(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function El(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 Ta(...t){return t.filter(Boolean).reduce((e,n)=>Mu[n]>Mu[e]?n:e,"pass")}function ch(t,e="warning",n="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:n};const i=st(t),r=Vt(i.message,i.title,i.issue,i.description,i.summary);return r?{severity:El(i.severity||i.status||i.level)||e,message:r,suggestion:Vt(i.suggestion,i.fix,i.recommendation,i.action),source:i.source||n}:null}function $a(t,e="review"){const n=st(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([r,s])=>kt(n[r]).map(o=>ch(o,s,e)).filter(Boolean))}function l_(t,e,n=null){if(typeof t=="string")return{id:`${n||"bundle"}-manual-${e+1}`,title:t,detail:"",location:"",timing:"unspecified",artifactId:n,source:"Code Review"};const i=st(t),r=Vt(i.title,i.action,i.step,i.message,i.name,i.description);return r?{id:i.id||`${n||"bundle"}-manual-${e+1}`,title:r,detail:Vt(i.detail,i.instructions,i.description),location:Vt(i.location,i.flutterFlowPath,i.path),timing:Vt(i.timing,i.phase)||"unspecified",artifactId:n,source:Vt(i.source)||"Code Review"}:null}function Ma(t,e=null){const n=st(t);return o_.flatMap(i=>kt(n[i])).map((i,r)=>l_(i,r,e)).filter(Boolean)}function c_(t){let e=typeof t=="string"?Fa(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const n=st(e);typeof n.content=="string"&&(e=Fa(n.content)||e);const i=st(e),r=st(i.reviewResult||i.codeReview||i.result);return{rawText:"",root:Object.keys(r).length?r:i}}function u_(t,e){const n=[e.id,e.fileName,e.artifactName].map(lt);return t.find(i=>{const r=st(i);return[r.id,r.fileName,r.artifactName,r.name].map(lt).some(s=>s&&n.includes(s))})||null}function d_(t,e){return kt(t?.metadata?.compatibility?.deployHints).find(r=>lt(r?.artifactId)===lt(e.id)||lt(r?.fileName)===lt(e.fileName))?.pathHint||""}function f_(t,e){return kt(t?.relationships).filter(n=>lt(n?.from)===lt(e.id)||lt(n?.to)===lt(e.id))}function h_(t,e){return kt(t?.metadata?.compatibility?.findings).filter(n=>!n?.artifactId||lt(n.artifactId)===lt(e.id)).map(n=>ch(n,"warning","Compatibility check")).filter(Boolean)}function p_(t,e,n,i){const r=u_(e,n),s=st(r?.review||r||n.review),o=Object.keys(s).length>0,a=[...$a(s),...h_(t,n)],l=Ma(s,n.id),u=El(s.status||s.verdict||s.outcome||s.result),c=a.length?Ta(...a.map(f=>f.severity)):null,d=Ta(u,c,o?null:"warning");return{...n,index:i,status:d,statusReason:o?Vt(s.summary,s.overview,s.assessment,s.conclusion)||(a.length?`${a.length} review finding${a.length===1?"":"s"}`:"No file-level findings"):"No file-level verdict was returned",reviewComplete:o,findings:a,manualSteps:l,fixedSource:typeof s.fixedSource=="string"&&s.fixedSource.trim()?s.fixedSource.trim():null,pathHint:d_(t,n),relationships:f_(t,n)}}function g_({status:t,score:e,artifactPresentations:n,manualSteps:i}){const r=n.length;if(r===0&&i.length===0)return e==null?"Code review returned no overall summary and no score.":`Reviewed bundle with score ${e}/100.`;const s=n.reduce((a,l)=>(a[l.status]+=1,a),{pass:0,warning:0,fail:0}),o=[];return t&&o.push(`Overall verdict: ${t}.`),r&&o.push(`${r} artifact${r===1?"":"s"}: ${s.pass} pass, ${s.warning} warn, ${s.fail} fail.`),i.length&&o.push(`Do before deploy: ${i.map(a=>a.title).join("; ")}.`),e==null&&o.push("No numeric score (0-100) was returned."),o.join(" ")}function m_({bundle:t,reviewResult:e}){const n=st(t),i=kt(n.artifacts),{root:r,rawText:s}=c_(e),o=[r.bundleReview,r.overallReview,r.overall,r.bundleSummary,r.summaryReview,r.review].map(st).find(S=>Object.keys(S).length)||{},a=kt(r.artifacts||r.files||r.reviews),l=i.map((S,_)=>p_(n,a,S,_)),u=$a(r),d=[...$a(o),...u],f=[...Ma(o),...Ma(r),...l.flatMap(S=>S.manualSteps)].filter((S,_,b)=>b.findIndex(k=>k.title===S.title&&k.artifactId===S.artifactId)===_),h=El(o.status||o.verdict||o.overallStatus||r.status||r.verdict||r.overallStatus||r.outcome),p=Ta(h,...d.map(S=>S.severity),...l.map(S=>S.status)),g=o.score??r.score??r.overallScore??s,m=a_(g),v=Vt(o.headline,o.summary,o.executiveSummary,o.overview,o.assessment,o.conclusion,r.overallSummary,r.headline,r.summary,r.executiveSummary,r.overview,r.assessment,r.conclusion,s)||g_({status:p,score:m,artifactPresentations:l,manualSteps:f}),E=l.reduce((S,_)=>(S[_.status]+=1,S),{pass:0,warning:0,fail:0});return{title:n.title||"Generated artifact bundle",description:n.description||"",status:p,score:m,summary:v,findings:d,manualSteps:f,artifacts:l,counts:E,reviewCoverage:{reviewed:l.filter(S=>S.reviewComplete).length,total:l.length},deployOrder:kt(n.deployOrder),relationships:kt(n.relationships),warnings:kt(n.warnings),compatibility:st(n.metadata?.compatibility)}}const v_=/^\uFEFF/;function Ci(t){let e=0,n=t.length;for(;ee&&!t[n-1].trim();)n--;return t.slice(e,n).join(` -`)}function __(t){const e=String(t??"").replace(v_,"");if(!e.trim())return"";const n=e.split(` -`),i=c=>{const d=c.trim();return/^`{3,}[A-Za-z0-9+#_.-]*$/.test(d)?c.length-c.trimStart().length:-1};let r=0,s=-1;const o=[];{let c=0;for(let d=0;d=0&&(r++,s<0&&(s=d),o.push(c+f)),c+=n[d].length+1}}if(r===0)return Ci(n);{const c=La(e);if(!c.error&&o.every(f=>Ou(f,c.commentAndStringRanges)))return Ci(n)}if(r===1){const c=Ci(n.slice(0,s)),d=Ci(n.slice(s+1));return d.length>=c.length?d:c}const a=[];let l=null;for(let c=0;cm));o=o.filter((m,v)=>!g.has(v)),o[h.index]=p}const u={...Mu(t?.dependencies),...r.reduce((h,p)=>({...h,...Mu(p.dependencies)}),{})},c={};r.forEach(h=>{bl(h.code||"").forEach(p=>{p in u||(c[p]="")})});const d={...c,...u},f=t_(o);return{bundleId:t?.id||"bundle-current",title:t?.title||"Generated artifact bundle",fileEntries:o,dependencies:d,relationships:t?.relationships||[],warnings:s,errors:f}}function i_(t){return String(t||"").match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/)?.[1]}function r_(t){return String(t||"").split("/").pop().replace(/\.dart$/,"").split(/[^A-Za-z0-9]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function s_(t,e){const i=[r_(t),i_(e.content),e.artifactName].find(r=>/^[A-Z][A-Za-z0-9_]*$/.test(String(r||"")));if(!i)throw new Error(`Cannot derive a FlutterFlow custom class name for ${t}.`);return i}function o_(t,e=new Map){const n=[];for(const[i,r]of t.entries())r.type!=="C"||e.has(r.path)||n.push({artifactId:r.artifactId||i,className:s_(i,r),content:r.content,fileName:i,path:r.path});return n}function a_(t,e){const n=new Set(e.map(i=>i.path));return new Map(Array.from(t.entries()).filter(([,i])=>!n.has(i.path)))}const Lu={pass:0,warning:1,fail:2},l_=["manualActions"];function st(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Vt(...t){for(const e of t){if(typeof e=="string"&&e.trim())return e.trim();if(Array.isArray(e)&&e.length>0){const n=e.filter(i=>typeof i=="string").join(` +`);if(n)return n}}return""}function kt(t){return t==null?[]:Array.isArray(t)?t:[t]}function c_(t){const e=st(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const n=Number(e);if(Number.isFinite(n))return Nu(n);const i=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return i?Nu(Number(i[1])):null}function Nu(t){return t>=0&&t<=100?t:null}function lt(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function El(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 Ra(...t){return t.filter(Boolean).reduce((e,n)=>Lu[n]>Lu[e]?n:e,"pass")}function uh(t,e="warning",n="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:n};const i=st(t),r=Vt(i.message,i.title,i.issue,i.description,i.summary);return r?{severity:El(i.severity||i.status||i.level)||e,message:r,suggestion:Vt(i.suggestion,i.fix,i.recommendation,i.action),source:i.source||n}:null}function Ta(t,e="review"){const n=st(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([r,s])=>kt(n[r]).map(o=>uh(o,s,e)).filter(Boolean))}function u_(t,e,n=null){if(typeof t=="string")return{id:`${n||"bundle"}-manual-${e+1}`,title:t,detail:"",location:"",timing:"unspecified",artifactId:n,source:"Code Review"};const i=st(t),r=Vt(i.title,i.action,i.step,i.message,i.name,i.description);return r?{id:i.id||`${n||"bundle"}-manual-${e+1}`,title:r,detail:Vt(i.detail,i.instructions,i.description),location:Vt(i.location,i.flutterFlowPath,i.path),timing:Vt(i.timing,i.phase)||"unspecified",artifactId:n,source:Vt(i.source)||"Code Review"}:null}function $a(t,e=null){const n=st(t);return l_.flatMap(i=>kt(n[i])).map((i,r)=>u_(i,r,e)).filter(Boolean)}function d_(t){let e=typeof t=="string"?Pa(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const n=st(e);typeof n.content=="string"&&(e=Pa(n.content)||e);const i=st(e),r=st(i.reviewResult||i.codeReview||i.result);return{rawText:"",root:Object.keys(r).length?r:i}}function f_(t,e){const n=[e.id,e.fileName,e.artifactName].map(lt);return t.find(i=>{const r=st(i);return[r.id,r.fileName,r.artifactName,r.name].map(lt).some(s=>s&&n.includes(s))})||null}function h_(t,e){return kt(t?.metadata?.compatibility?.deployHints).find(r=>lt(r?.artifactId)===lt(e.id)||lt(r?.fileName)===lt(e.fileName))?.pathHint||""}function p_(t,e){return kt(t?.relationships).filter(n=>lt(n?.from)===lt(e.id)||lt(n?.to)===lt(e.id))}function g_(t,e){return kt(t?.metadata?.compatibility?.findings).filter(n=>!n?.artifactId||lt(n.artifactId)===lt(e.id)).map(n=>uh(n,"warning","Compatibility check")).filter(Boolean)}function m_(t,e,n,i){const r=f_(e,n),s=st(r?.review||r||n.review),o=Object.keys(s).length>0,a=[...Ta(s),...g_(t,n)],l=$a(s,n.id),u=El(s.status||s.verdict||s.outcome||s.result),c=a.length?Ra(...a.map(f=>f.severity)):null,d=Ra(u,c,o?null:"warning");return{...n,index:i,status:d,statusReason:o?Vt(s.summary,s.overview,s.assessment,s.conclusion)||(a.length?`${a.length} review finding${a.length===1?"":"s"}`:"No file-level findings"):"No file-level verdict was returned",reviewComplete:o,findings:a,manualSteps:l,fixedSource:typeof s.fixedSource=="string"&&s.fixedSource.trim()?s.fixedSource.trim():null,pathHint:h_(t,n),relationships:p_(t,n)}}function v_({status:t,score:e,artifactPresentations:n,manualSteps:i}){const r=n.length;if(r===0&&i.length===0)return e==null?"Code review returned no overall summary and no score.":`Reviewed bundle with score ${e}/100.`;const s=n.reduce((a,l)=>(a[l.status]+=1,a),{pass:0,warning:0,fail:0}),o=[];return t&&o.push(`Overall verdict: ${t}.`),r&&o.push(`${r} artifact${r===1?"":"s"}: ${s.pass} pass, ${s.warning} warn, ${s.fail} fail.`),i.length&&o.push(`Do before deploy: ${i.map(a=>a.title).join("; ")}.`),e==null&&o.push("No numeric score (0-100) was returned."),o.join(" ")}function __({bundle:t,reviewResult:e}){const n=st(t),i=kt(n.artifacts),{root:r,rawText:s}=d_(e),o=[r.bundleReview,r.overallReview,r.overall,r.bundleSummary,r.summaryReview,r.review].map(st).find(S=>Object.keys(S).length)||{},a=kt(r.artifacts||r.files||r.reviews),l=i.map((S,_)=>m_(n,a,S,_)),u=Ta(r),d=[...Ta(o),...u],f=[...$a(o),...$a(r),...l.flatMap(S=>S.manualSteps)].filter((S,_,b)=>b.findIndex(k=>k.title===S.title&&k.artifactId===S.artifactId)===_),h=El(o.status||o.verdict||o.overallStatus||r.status||r.verdict||r.overallStatus||r.outcome),p=Ra(h,...d.map(S=>S.severity),...l.map(S=>S.status)),g=o.score??r.score??r.overallScore??s,m=c_(g),v=Vt(o.headline,o.summary,o.executiveSummary,o.overview,o.assessment,o.conclusion,r.overallSummary,r.headline,r.summary,r.executiveSummary,r.overview,r.assessment,r.conclusion,s)||v_({status:p,score:m,artifactPresentations:l,manualSteps:f}),E=l.reduce((S,_)=>(S[_.status]+=1,S),{pass:0,warning:0,fail:0});return{title:n.title||"Generated artifact bundle",description:n.description||"",status:p,score:m,summary:v,findings:d,manualSteps:f,artifacts:l,counts:E,reviewCoverage:{reviewed:l.filter(S=>S.reviewComplete).length,total:l.length},deployOrder:kt(n.deployOrder),relationships:kt(n.relationships),warnings:kt(n.warnings),compatibility:st(n.metadata?.compatibility)}}const y_=/^\uFEFF/;function Ci(t){let e=0,n=t.length;for(;ee&&!t[n-1].trim();)n--;return t.slice(e,n).join(` +`)}function w_(t){const e=String(t??"").replace(y_,"");if(!e.trim())return"";const n=e.split(` +`),i=c=>{const d=c.trim();return/^`{3,}[A-Za-z0-9+#_.-]*$/.test(d)?c.length-c.trimStart().length:-1};let r=0,s=-1;const o=[];{let c=0;for(let d=0;d=0&&(r++,s<0&&(s=d),o.push(c+f)),c+=n[d].length+1}}if(r===0)return Ci(n);{const c=Ma(e);if(!c.error&&o.every(f=>Bu(f,c.commentAndStringRanges)))return Ci(n)}if(r===1){const c=Ci(n.slice(0,s)),d=Ci(n.slice(s+1));return d.length>=c.length?d:c}const a=[];let l=null;for(let c=0;cc.length>0);return u.length===0?"":u.join(` +${d}`,{commentAndStringRanges:g}=Ma(p),m=h.length+1+f;if(Bu(m,g)){l.push(d);continue}a.push(Ci(l)),l=null}const u=a.filter(c=>c.length>0);return u.length===0?"":u.join(` -`)}function y_(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 uh(t){const e=y_(t);return Array.from(e.matchAll(/class\s+([A-Z]\w*)\s+extends\s+[A-Za-z_]\w*Widget\b/g),n=>n[1])}function dh(t){return`${wl(t)}.dart`}function w_(t){return _l(t,"W")}const Nu={"(":")","[":"]","{":"}"},b_={")":"(","]":"[","}":"{"},E_=/[A-Za-z0-9_]/;function La(t){const e=[{kind:"code",opener:null,openedLine:0}],n=[];let i=1,r=0;const s=(c,d)=>{(c===` +`)}function b_(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 dh(t){const e=b_(t);return Array.from(e.matchAll(/class\s+([A-Z]\w*)\s+extends\s+[A-Za-z_]\w*Widget\b/g),n=>n[1])}function fh(t){return`${wl(t)}.dart`}function E_(t){return _l(t,"W")}const Ou={"(":")","[":"]","{":"}"},S_={")":"(","]":"[","}":"{"},x_=/[A-Za-z0-9_]/;function Ma(t){const e=[{kind:"code",opener:null,openedLine:0}],n=[];let i=1,r=0;const s=(c,d)=>{(c===` `||c==="\r"&&d!==` `)&&i++};let o=null;const a=()=>{for(const c of e)(c.kind==="string"||c.kind==="block-comment"||c.kind==="line-comment")&&n.push({start:c.startIndex,end:t.length})};for(;r0?t[r-1]:"",p=r>1?t[r-2]:"",g=(h==="r"||h==="R")&&!E_.test(p);e.push({kind:"string",quote:c,triple:f,raw:g,startIndex:r,openedLine:i}),r+=f?3:1;continue}if(Nu[c]){e.push({kind:"code",opener:c,openedLine:i}),r++;continue}if(b_[c]){if(d.interpolation&&c==="}"){e.pop(),r++;continue}if(d.opener&&Nu[d.opener]===c){e.pop(),r++;continue}return d.opener?(a(),{error:o??`line ${i}: "${c}" closes nothing - "${d.opener}" opened on line ${d.openedLine} is still open`,commentAndStringRanges:n}):(a(),{error:o??`line ${i}: unexpected "${c}" with no matching opener`,commentAndStringRanges:n})}s(c,t[r+1]),r++}a();let l=e.length-1;for(;l>0&&e[l].kind==="line-comment";)l--;let u=o;if(!u){const c=e[l];if(!(c.kind==="code"&&!c.opener&&!c.interpolation))if(c.kind==="string")u=`unclosed ${c.triple?"triple-quoted ":""}string starting on line ${c.openedLine} was never closed`;else if(c.kind==="block-comment")u=`unterminated /* comment starting on line ${c.openedLine}`;else if(c.interpolation){const d=e.findLast(h=>h.opener);u=`unclosed "\${" expression${d?` opened on line ${d.openedLine}`:""} was never closed`}else u=`"${c.opener}" opened on line ${c.openedLine} is never closed`}return{error:u,commentAndStringRanges:n}}function S_(t){return La(String(t??"")).error}function Ou(t,e){return e.some(({start:n,end:i})=>t>=n&&ttypeof n=="string"?n:n?.errorMessage).filter(Boolean);return e.length>0?e.join("; "):JSON.stringify(t)}return t&&typeof t=="object"?t.errorMessage||JSON.stringify(t):String(t??"")}const x_=["gmail.com","googlemail.com","outlook.com","hotmail.com","live.com","msn.com"],I_="MAGIC_LINK_SENT",k_="PLUS_ALIAS_REJECTED",C_="Please enter your primary email address. Plus aliases (such as {email}) are not allowed for {domain} accounts.",Fs={allowlistedDomains:x_,successCode:I_,validationCode:k_,messageTemplate:C_},A_=new Set(Fs.allowlistedDomains),P_=Fs.successCode,fh=Fs.validationCode;function Rs(t){return typeof t=="string"?t.trim():""}function F_(t){const e=Rs(t),n=e.lastIndexOf("@");if(n<=0||n===e.length-1)return!1;const i=e.slice(0,n),r=e.slice(n+1).toLowerCase();return A_.has(r)?i.includes("+"):!1}function R_(t,e){return Fs.messageTemplate.replaceAll("{email}",t).replaceAll("{domain}",e)}function hh(t){if(!F_(t))return null;const e=Rs(t),n=e.lastIndexOf("@"),i=e.slice(n+1).toLowerCase();return R_(e,i)}function ph(t,e){return t?.code===fh?t.message||hh(e)||"Please enter your primary email address.":t?.code===P_||!t?.code?`Check your email — we sent a link to ${Rs(e)}`:t.message||"Something went wrong. Please try again."}const T_="ccc_auth_session",$_="ccc_subscription",M_=Object.freeze(["hasSeenWalkthrough"]);function L_(t){const e=[];for(const n of M_)t.getItem(n)!==null&&(t.removeItem(n),e.push(n));return e}function N_(){return[T_,$_]}function O_({storage:t,onIdentityChanged:e,onPlanChanged:n}){for(const i of N_())t.removeItem(i);typeof e=="function"&&e(),typeof n=="function"&&n()}function B_({sendLink:t,getEmail:e,onState:n}){let i=!1;return async function(){if(i)return{status:"busy"};i=!0;let s;try{n({status:"pending",error:null});const o=await t(e());return s={status:"sent",data:o},n({status:"sent",data:o}),s}catch(o){return s={status:"error",error:o},n({status:"error",error:o}),s}finally{i=!1}}}const D_=/^dependencies\s*:\s*(?:#.*)?$/,j_=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function Ts(t){const e=t.match(j_);return e?e[1]??e[2]??e[3]:null}function ar(t){const e=t.trim();return e===""||e.startsWith("#")}function fi(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function xl(t,e){const n=t.findIndex(s=>e.test(s));if(n===-1)return null;let i=n,r=null;for(let s=n+1;s=0.0.0"}`}function z_(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([u])=>u&&u!=="flutter");if(i.length===0)return{yaml:n,added:[],alreadyPresent:[]};const r=n.split(` -`),s=new Set(mh(n)),o=[],a=[];for(const[u,c]of i)s.has(u)?a.push(u):(o.push([u,c]),s.add(u));if(o.length===0)return{yaml:n,added:[],alreadyPresent:a};const l=Il(r);if(l){const u=o.map(([c,d])=>Bu(l.childIndent,c,d));r.splice(l.endIndex,0,...u)}else r.length>0&&r[r.length-1].trim()!==""&&r.push(""),r.push("dependencies:"),o.forEach(([u,c])=>{r.push(Bu(" ",u,c))});return{yaml:r.join(` -`),added:o.map(([u])=>u),alreadyPresent:a}}function q_(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([l])=>l&&l!=="flutter");if(i.length===0)return{yaml:n,overridden:[],skipped:[]};const r=n.split(` -`),s=Ms(n),o=[],a=[];for(const[l,u]of i){const c=s.get(l);if(!c||!c.isScalar||!String(u||"").trim()){a.push(l);continue}const d=" ".repeat(fi(r[c.lineIndex]));r[c.lineIndex]=`${d}${l}: ${_h(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:r.join(` -`),overridden:o,skipped:a}}function yh(t){const e=String(t||""),n=[];return e.trim()?(/^name:\s*\S+/m.test(e)||n.push("pubspec.yaml missing name field"),Il(e.split(` -`))||n.push("pubspec.yaml missing dependencies section"),mh(e).includes("flutter")||n.push("pubspec.yaml missing Flutter SDK dependency"),{valid:n.length===0,errors:n}):(n.push("pubspec.yaml is empty"),{valid:!1,errors:n})}const V_=">=3.0.0 <4.0.0";function Na(t){const e=String(t||"").trim(),n=e[0];return n!=="'"&&n!=='"'||e[e.length-1]!==n?e:e.slice(1,-1).replaceAll(`${n}${n}`,n)}function G_(t=""){const e=Yv(t).filter(n=>!n.startsWith("dart:")&&!n.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function Du(t,e,n){const i=[];for(const[r,s]of t){if(s.isScalar){e[r]=Na(s.constraint);continue}if(s.sourceKey==="sdk"){n.add(r);continue}if(s.sourceKey===null&&s.version){e[r]=Na(s.version);continue}i.push(r)}return i}function K_(t){const e=new Set,n={},i={},r=Du(Ms(t),n,e);r.push(...Du(H_(t,"dependency_overrides"),i,e));const s=new Set([...Object.keys(n),...e]),{sdk:o}=vh(t);return{sdkConstraint:Na(o)||V_,dependencies:n,overrides:i,sdkPackages:[...e].sort(),availablePackages:s,unrepresentable:r}}function Y_(t,e,n){return e.length>0?`${t} imports ${e.join(", ")}, which FlutterFlow only generates once the app is built, so it could not be compiled before the deploy.`:`${t} imports ${n.join(", ")}, which your project's pubspec.yaml does not declare with a version constraint, so it could not be compiled before the deploy.`}function J_(t,e){const{sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s,availablePackages:o,unrepresentable:a}=K_(e),l={sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s},u=[],c=[],d=a.map(f=>`Your project declares ${f} from a source that cannot be reproduced outside it, so the pre-deploy compile check runs against a scratch package graph that omits ${f}. Classes that do not import ${f} directly are still checked, but against that reduced graph, so their transitive package resolution may differ from your project's and the check is approximate for them.`);for(const f of t){const{className:h,content:p}=f,g=bl(p),m=g.filter(S=>a.includes(S));if(m.length>0){c.push({className:h,reason:`${h} was not compiled before deploying: it imports ${m.join(", ")}, which your project declares from a source that cannot be reproduced outside it, so package resolution could not be matched exactly.`});continue}const{unresolvableImports:v}=G_(p),E=g.filter(S=>!o.has(S));if(v.length>0||E.length>0){c.push({className:h,reason:Y_(h,v,E)});continue}u.push({fileName:`${wl(h)}.dart`,content:p})}return{manifest:l,sources:u,skipped:c,approximate:d}}function ju(t,e){const n=`${t}${e}`.split(` -`),i=n.pop()??"",r=[];for(const s of n){const o=wh(s);o&&r.push(o)}return{events:r,buffer:i}}function Z_(t){const e=wh(t);return e?[e]:[]}function wh(t){const e=t.trim();if(!e)return null;try{const n=JSON.parse(e);return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}const Le=Object.freeze({COMMITTED:"committed",PARTIAL:"partial",FAILED:"failed",UNCONFIRMED:"unconfirmed"}),bh=12e4,X_=1e4;function Eh(t){return t?.unconfirmed===!0||t?.outcome===Le.UNCONFIRMED?Le.UNCONFIRMED:t?.partial===!0||t?.outcome===Le.PARTIAL?Le.PARTIAL:t?.success===!0?Le.COMMITTED:Le.FAILED}class Qe extends Error{constructor(e){super(e),this.name="UnconfirmedDeployError",this.outcome=Le.UNCONFIRMED}}function Uu({httpStatus:t}={}){return new Qe(`Every FlutterFlow sync endpoint lost its response or ended in a server error${t?` (last: HTTP ${t})`:""} — neither can prove the push was refused, so it may already have been applied. Open the FlutterFlow project to reconcile before retrying.`)}async function Q_(t,e={}){const{onPhase:n,onLog:i}=e;let r=null,s=null,o="";const a=u=>{if(u.event==="phase"){u.phase&&(s=u.phase),u.message&&n&&n(u.message);return}if(u.event==="log"){u.message&&i&&i(u.message);return}r=u};let l=null;try{if(t.body?.getReader){const u=t.body.getReader(),c=new TextDecoder;for(;;){const{done:d,value:f}=await u.read();if(d)break;const h=ju(o,c.decode(f,{stream:!0}));o=h.buffer,h.events.forEach(a)}}else{const u=ju("",await t.text());o=u.buffer,u.events.forEach(a)}}catch(u){l=u}return Z_(o).forEach(a),r?{...r,success:r.success===!0||r.success===void 0&&t.ok,finalResultReceived:!0,runnerPhase:s,httpStatus:t.status}:{success:!1,finalResultReceived:!1,httpRejected:!t.ok,httpStatus:t.status,runnerPhase:s,error:t.ok?l?"The connection to the FlutterFlow deploy runner dropped before it reported a result.":"The FlutterFlow deploy runner closed the connection before it finished.":`FlutterFlow custom class provisioning failed (HTTP ${t.status}).`}}const ey=new Set(["connected","workspace_init","workspace_ready","verifying"]);function ty(t){return t?.preWrite===!0||Array.isArray(t?.analyzerErrors)&&t.analyzerErrors.length>0?!0:typeof t?.runnerPhase=="string"?ey.has(t.runnerPhase):typeof t?.httpStatus=="number"?t.httpStatus>=400&&t.httpStatus<500:!1}function Hu(t){if(t?.finalResultReceived){const e=Eh(t);return e===Le.FAILED&&!ty(t)?Le.UNCONFIRMED:e}return t?.httpRejected?Le.FAILED:Le.UNCONFIRMED}function ny(){let t=document.getElementById("fx-grid");if(!t)return null;const e=window.matchMedia("(prefers-reduced-motion: reduce)"),n=window.matchMedia("(pointer: none)");let i=t.getContext("webgl2",{alpha:!0,antialias:!1,depth:!1,stencil:!1,premultipliedAlpha:!0,powerPreference:"low-power"}),r=i?null:t.getContext("2d");if(!i&&!r)return null;const s='',o=`#version 300 es +`){n.push({start:d.startIndex,end:r}),o??=`line ${i}: string starting on line ${d.openedLine} is never closed`,e.pop();continue}if(!d.raw&&c==="\\"){s(t[r+1]??"",t[r+2]??""),r+=2;continue}if(!d.raw&&c==="$"&&t[r+1]==="{"){e.push({kind:"code",opener:null,interpolation:!0}),r+=2;continue}const f=d.triple?3:1;if(c===d.quote&&t.slice(r,r+f)===d.quote.repeat(f)){n.push({start:d.startIndex,end:r+f}),e.pop(),r+=f;continue}s(c,t[r+1]),r++;continue}if(c==="/"&&t[r+1]==="/"){e.push({kind:"line-comment",startIndex:r}),r+=2;continue}if(c==="/"&&t[r+1]==="*"){e.push({kind:"block-comment",startIndex:r,openedLine:i,depth:1}),r+=2;continue}if(c==="'"||c==='"'){const f=t.slice(r,r+3)===c.repeat(3),h=r>0?t[r-1]:"",p=r>1?t[r-2]:"",g=(h==="r"||h==="R")&&!x_.test(p);e.push({kind:"string",quote:c,triple:f,raw:g,startIndex:r,openedLine:i}),r+=f?3:1;continue}if(Ou[c]){e.push({kind:"code",opener:c,openedLine:i}),r++;continue}if(S_[c]){if(d.interpolation&&c==="}"){e.pop(),r++;continue}if(d.opener&&Ou[d.opener]===c){e.pop(),r++;continue}return d.opener?(a(),{error:o??`line ${i}: "${c}" closes nothing - "${d.opener}" opened on line ${d.openedLine} is still open`,commentAndStringRanges:n}):(a(),{error:o??`line ${i}: unexpected "${c}" with no matching opener`,commentAndStringRanges:n})}s(c,t[r+1]),r++}a();let l=e.length-1;for(;l>0&&e[l].kind==="line-comment";)l--;let u=o;if(!u){const c=e[l];if(!(c.kind==="code"&&!c.opener&&!c.interpolation))if(c.kind==="string")u=`unclosed ${c.triple?"triple-quoted ":""}string starting on line ${c.openedLine} was never closed`;else if(c.kind==="block-comment")u=`unterminated /* comment starting on line ${c.openedLine}`;else if(c.interpolation){const d=e.findLast(h=>h.opener);u=`unclosed "\${" expression${d?` opened on line ${d.openedLine}`:""} was never closed`}else u=`"${c.opener}" opened on line ${c.openedLine} is never closed`}return{error:u,commentAndStringRanges:n}}function I_(t){return Ma(String(t??"")).error}function Bu(t,e){return e.some(({start:n,end:i})=>t>=n&&ttypeof n=="string"?n:n?.errorMessage).filter(Boolean);return e.length>0?e.join("; "):JSON.stringify(t)}return t&&typeof t=="object"?t.errorMessage||JSON.stringify(t):String(t??"")}const k_=["gmail.com","googlemail.com","outlook.com","hotmail.com","live.com","msn.com"],C_="MAGIC_LINK_SENT",A_="PLUS_ALIAS_REJECTED",P_="Please enter your primary email address. Plus aliases (such as {email}) are not allowed for {domain} accounts.",Ps={allowlistedDomains:k_,successCode:C_,validationCode:A_,messageTemplate:P_},F_=new Set(Ps.allowlistedDomains),R_=Ps.successCode,hh=Ps.validationCode;function Fs(t){return typeof t=="string"?t.trim():""}function T_(t){const e=Fs(t),n=e.lastIndexOf("@");if(n<=0||n===e.length-1)return!1;const i=e.slice(0,n),r=e.slice(n+1).toLowerCase();return F_.has(r)?i.includes("+"):!1}function $_(t,e){return Ps.messageTemplate.replaceAll("{email}",t).replaceAll("{domain}",e)}function ph(t){if(!T_(t))return null;const e=Fs(t),n=e.lastIndexOf("@"),i=e.slice(n+1).toLowerCase();return $_(e,i)}function gh(t,e){return t?.code===hh?t.message||ph(e)||"Please enter your primary email address.":t?.code===R_||!t?.code?`Check your email — we sent a link to ${Fs(e)}`:t.message||"Something went wrong. Please try again."}const M_="ccc_auth_session",L_="ccc_subscription",N_=Object.freeze(["hasSeenWalkthrough"]);function O_(t){const e=[];for(const n of N_)t.getItem(n)!==null&&(t.removeItem(n),e.push(n));return e}function B_(){return[M_,L_]}function D_({storage:t,onIdentityChanged:e,onPlanChanged:n}){for(const i of B_())t.removeItem(i);typeof e=="function"&&e(),typeof n=="function"&&n()}function j_({sendLink:t,getEmail:e,onState:n}){let i=!1;return async function(){if(i)return{status:"busy"};i=!0;let s;try{n({status:"pending",error:null});const o=await t(e());return s={status:"sent",data:o},n({status:"sent",data:o}),s}catch(o){return s={status:"error",error:o},n({status:"error",error:o}),s}finally{i=!1}}}const U_=/^dependencies\s*:\s*(?:#.*)?$/,H_=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function Rs(t){const e=t.match(H_);return e?e[1]??e[2]??e[3]:null}function ar(t){const e=t.trim();return e===""||e.startsWith("#")}function fi(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function xl(t,e){const n=t.findIndex(s=>e.test(s));if(n===-1)return null;let i=n,r=null;for(let s=n+1;s=0.0.0"}`}function V_(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([u])=>u&&u!=="flutter");if(i.length===0)return{yaml:n,added:[],alreadyPresent:[]};const r=n.split(` +`),s=new Set(vh(n)),o=[],a=[];for(const[u,c]of i)s.has(u)?a.push(u):(o.push([u,c]),s.add(u));if(o.length===0)return{yaml:n,added:[],alreadyPresent:a};const l=Il(r);if(l){const u=o.map(([c,d])=>Du(l.childIndent,c,d));r.splice(l.endIndex,0,...u)}else r.length>0&&r[r.length-1].trim()!==""&&r.push(""),r.push("dependencies:"),o.forEach(([u,c])=>{r.push(Du(" ",u,c))});return{yaml:r.join(` +`),added:o.map(([u])=>u),alreadyPresent:a}}function G_(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([l])=>l&&l!=="flutter");if(i.length===0)return{yaml:n,overridden:[],skipped:[]};const r=n.split(` +`),s=$s(n),o=[],a=[];for(const[l,u]of i){const c=s.get(l);if(!c||!c.isScalar||!String(u||"").trim()){a.push(l);continue}const d=" ".repeat(fi(r[c.lineIndex]));r[c.lineIndex]=`${d}${l}: ${yh(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:r.join(` +`),overridden:o,skipped:a}}function wh(t){const e=String(t||""),n=[];return e.trim()?(/^name:\s*\S+/m.test(e)||n.push("pubspec.yaml missing name field"),Il(e.split(` +`))||n.push("pubspec.yaml missing dependencies section"),vh(e).includes("flutter")||n.push("pubspec.yaml missing Flutter SDK dependency"),{valid:n.length===0,errors:n}):(n.push("pubspec.yaml is empty"),{valid:!1,errors:n})}const K_=">=3.0.0 <4.0.0";function La(t){const e=String(t||"").trim(),n=e[0];return n!=="'"&&n!=='"'||e[e.length-1]!==n?e:e.slice(1,-1).replaceAll(`${n}${n}`,n)}function Y_(t=""){const e=Zv(t).filter(n=>!n.startsWith("dart:")&&!n.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function ju(t,e,n){const i=[];for(const[r,s]of t){if(s.isScalar){e[r]=La(s.constraint);continue}if(s.sourceKey==="sdk"){n.add(r);continue}if(s.sourceKey===null&&s.version){e[r]=La(s.version);continue}i.push(r)}return i}function J_(t){const e=new Set,n={},i={},r=ju($s(t),n,e);r.push(...ju(z_(t,"dependency_overrides"),i,e));const s=new Set([...Object.keys(n),...e]),{sdk:o}=_h(t);return{sdkConstraint:La(o)||K_,dependencies:n,overrides:i,sdkPackages:[...e].sort(),availablePackages:s,unrepresentable:r}}function Z_(t,e,n){return e.length>0?`${t} imports ${e.join(", ")}, which FlutterFlow only generates once the app is built, so it could not be compiled before the deploy.`:`${t} imports ${n.join(", ")}, which your project's pubspec.yaml does not declare with a version constraint, so it could not be compiled before the deploy.`}function X_(t,e){const{sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s,availablePackages:o,unrepresentable:a}=J_(e),l={sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s},u=[],c=[],d=a.map(f=>`Your project declares ${f} from a source that cannot be reproduced outside it, so the pre-deploy compile check runs against a scratch package graph that omits ${f}. Classes that do not import ${f} directly are still checked, but against that reduced graph, so their transitive package resolution may differ from your project's and the check is approximate for them.`);for(const f of t){const{className:h,content:p}=f,g=bl(p),m=g.filter(S=>a.includes(S));if(m.length>0){c.push({className:h,reason:`${h} was not compiled before deploying: it imports ${m.join(", ")}, which your project declares from a source that cannot be reproduced outside it, so package resolution could not be matched exactly.`});continue}const{unresolvableImports:v}=Y_(p),E=g.filter(S=>!o.has(S));if(v.length>0||E.length>0){c.push({className:h,reason:Z_(h,v,E)});continue}u.push({fileName:`${wl(h)}.dart`,content:p})}return{manifest:l,sources:u,skipped:c,approximate:d}}function Uu(t,e){const n=`${t}${e}`.split(` +`),i=n.pop()??"",r=[];for(const s of n){const o=bh(s);o&&r.push(o)}return{events:r,buffer:i}}function Q_(t){const e=bh(t);return e?[e]:[]}function bh(t){const e=t.trim();if(!e)return null;try{const n=JSON.parse(e);return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}const Le=Object.freeze({COMMITTED:"committed",PARTIAL:"partial",FAILED:"failed",UNCONFIRMED:"unconfirmed"}),Eh=12e4,Sh=1e4;function xh(t){return t?.unconfirmed===!0||t?.outcome===Le.UNCONFIRMED?Le.UNCONFIRMED:t?.partial===!0||t?.outcome===Le.PARTIAL?Le.PARTIAL:t?.success===!0?Le.COMMITTED:Le.FAILED}class Qe extends Error{constructor(e){super(e),this.name="UnconfirmedDeployError",this.outcome=Le.UNCONFIRMED}}function Hu({httpStatus:t}={}){return new Qe(`Every FlutterFlow sync endpoint lost its response or ended in a server error${t?` (last: HTTP ${t})`:""} — neither can prove the push was refused, so it may already have been applied. Open the FlutterFlow project to reconcile before retrying.`)}async function ey(t,e={}){const{onPhase:n,onLog:i}=e;let r=null,s=null,o="";const a=u=>{if(u.event==="phase"){u.phase&&(s=u.phase),u.message&&n&&n(u.message);return}if(u.event==="log"){u.message&&i&&i(u.message);return}r=u};let l=null;try{if(t.body?.getReader){const u=t.body.getReader(),c=new TextDecoder;for(;;){const{done:d,value:f}=await u.read();if(d)break;const h=Uu(o,c.decode(f,{stream:!0}));o=h.buffer,h.events.forEach(a)}}else{const u=Uu("",await t.text());o=u.buffer,u.events.forEach(a)}}catch(u){l=u}return Q_(o).forEach(a),r?{...r,success:r.success===!0||r.success===void 0&&t.ok,finalResultReceived:!0,runnerPhase:s,httpStatus:t.status}:{success:!1,finalResultReceived:!1,httpRejected:!t.ok,httpStatus:t.status,runnerPhase:s,error:t.ok?l?"The connection to the FlutterFlow deploy runner dropped before it reported a result.":"The FlutterFlow deploy runner closed the connection before it finished.":`FlutterFlow custom class provisioning failed (HTTP ${t.status}).`}}const ty=new Set(["connected","workspace_init","workspace_ready","verifying"]);function ny(t){return t?.preWrite===!0||Array.isArray(t?.analyzerErrors)&&t.analyzerErrors.length>0?!0:typeof t?.runnerPhase=="string"?ty.has(t.runnerPhase):typeof t?.httpStatus=="number"?t.httpStatus>=400&&t.httpStatus<500:!1}function Wu(t){if(t?.finalResultReceived){const e=xh(t);return e===Le.FAILED&&!ny(t)?Le.UNCONFIRMED:e}return t?.httpRejected?Le.FAILED:Le.UNCONFIRMED}function iy(){let t=document.getElementById("fx-grid");if(!t)return null;const e=window.matchMedia("(prefers-reduced-motion: reduce)"),n=window.matchMedia("(pointer: none)");let i=t.getContext("webgl2",{alpha:!0,antialias:!1,depth:!1,stencil:!1,premultipliedAlpha:!0,powerPreference:"low-power"}),r=i?null:t.getContext("2d");if(!i&&!r)return null;const s='',o=`#version 300 es in vec2 p; void main(){ gl_Position = vec4(p, 0.0, 1.0); }`;function a(){return["#version 300 es","precision highp float;","out vec4 o;","uniform vec2 res;","uniform vec2 design;","uniform vec2 mouse;","uniform float energy;","uniform float parallax;","uniform float t;","uniform vec3 ink;","uniform sampler2D mark;","uniform vec2 rot;","const float WARP_A = 0.0032;","void main(){"," vec2 px = gl_FragCoord.xy * (design / res);"," vec2 p = vec2(px.x, design.y - px.y);"," vec2 off = vec2(0.0, -parallax) + vec2(sin(t * 0.11), cos(t * 0.09)) * 7.0;"," vec2 g = p + off;"," vec2 gm = mouse + off;"," float base = min(design.x, design.y);"," float spacing = clamp(base / 10.0, 64.0, 118.0);"," vec2 rel = g - gm;"," float rho = length(rel) + 1e-5;"," vec2 dir = rel / rho;"," vec2 pw = gm + dir * (rho + WARP_A * rho * rho);"," vec2 cell = floor(pw / spacing);"," vec2 cw = (cell + 0.5) * spacing - gm;"," float Rc = length(cw) + 1e-5;"," float rhoC = (-1.0 + sqrt(1.0 + 4.0 * WARP_A * Rc)) / (2.0 * WARP_A);"," vec2 c = gm + (cw / Rc) * rhoC;"," float cellSize = spacing / (1.0 + 2.0 * WARP_A * rhoC);"," float sigma = spacing * 2.9;"," float f = exp(-(rhoC * rhoC) / (2.0 * sigma * sigma));"," float scale = mix(0.32, 1.42, f);"," float weight = smoothstep(0.06, 0.80, f);"," float hs = cellSize * 0.26 * scale;"," vec2 uv = (g - c) / hs;"," vec2 ruv = mat2(rot.x, rot.y, -rot.y, rot.x) * uv;"," float cov = 0.0;"," if (abs(ruv.x) <= 1.0 && abs(ruv.y) <= 1.0) cov = texture(mark, ruv * 0.5 + 0.5).a;"," float s = cov * weight * energy * 0.26;"," o = vec4(ink * s, s);","}"].join(` -`)}let l=null,u,c,d,f,h,p,g,m,v;function E(Y,W){if(!i)return null;const D=i.createShader(Y);return i.shaderSource(D,W),i.compileShader(D),i.getShaderParameter(D,i.COMPILE_STATUS)?D:(window.console&&console.warn("fx-grid shader: "+i.getShaderInfoLog(D)),null)}if(i){const Y=E(i.VERTEX_SHADER,o),W=E(i.FRAGMENT_SHADER,a());if(Y&&W&&(l=i.createProgram(),i.attachShader(l,Y),i.attachShader(l,W),i.linkProgram(l),i.getProgramParameter(l,i.LINK_STATUS)||(window.console&&console.warn("fx-grid link: "+i.getProgramInfoLog(l)),l=null)),l){i.useProgram(l),i.bindBuffer(i.ARRAY_BUFFER,i.createBuffer()),i.bufferData(i.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),i.STATIC_DRAW);const D=i.getAttribLocation(l,"p");i.enableVertexAttribArray(D),i.vertexAttribPointer(D,2,i.FLOAT,!1,0,0),u=i.getUniformLocation(l,"res"),c=i.getUniformLocation(l,"design"),d=i.getUniformLocation(l,"mouse"),f=i.getUniformLocation(l,"energy"),h=i.getUniformLocation(l,"parallax"),p=i.getUniformLocation(l,"t"),g=i.getUniformLocation(l,"ink"),m=i.getUniformLocation(l,"mark"),v=i.getUniformLocation(l,"rot"),i.enable(i.BLEND),i.blendFunc(i.ONE,i.ONE_MINUS_SRC_ALPHA),i.clearColor(0,0,0,0)}else{i=null;const D=t.cloneNode(!1);if(t.parentNode.replaceChild(D,t),t=D,r=t.getContext("2d"),!r)return null}}function S(Y){if(!Y)return null;const W=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(Y);if(W){let D=W[1];return D.length===3&&(D=D[0]+D[0]+D[1]+D[1]+D[2]+D[2]),[parseInt(D.slice(0,2),16)/255,parseInt(D.slice(2,4),16)/255,parseInt(D.slice(4,6),16)/255]}try{const D=document.createElement("canvas");D.width=1,D.height=1;const ue=D.getContext("2d");ue.fillStyle="rgb(9, 8, 7)";const xe=String(ue.fillStyle);ue.fillStyle=Y;const Fe=String(ue.fillStyle);if(Fe===xe)return null;const dt=/^#([0-9a-f]{6})$/i.exec(Fe);if(dt){const ft=dt[1];return[parseInt(ft.slice(0,2),16)/255,parseInt(ft.slice(2,4),16)/255,parseInt(ft.slice(4,6),16)/255]}const Nt=/rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i.exec(Fe);if(Nt)return[Number(Nt[1])/255,Number(Nt[2])/255,Number(Nt[3])/255]}catch{}return null}function _(){let Y="";try{const W=getComputedStyle(document.documentElement);Y=(W.getPropertyValue("--fx-ink")||"").trim()||(W.getPropertyValue("--fg")||"").trim()}catch{}return S(Y)||[.56,.68,.88]}const b=_();let k=1920,T=1080,x=960,F=540,$=960,O=540,L=.66,N=0,K=-1e9,V=!1,M=0,R=0,Z=null,Ce=!1,oe=!1,ye=!1;const $e=64,ae=15.2;let Ie=0,Se=0;const De=.0032,wt=0,ge=.56,Je=.26,bt=.32,mn=.16,Re=.349;let Pe=wt;function $t(){const Y=t.getBoundingClientRect(),W=t.clientWidth,D=t.clientHeight;if(!Y.width||!W||!D)return;const ue=Math.min(window.devicePixelRatio||1,2),xe=Math.max(.2,Math.min(2,Y.width/W*ue)),Fe=Math.max(2,Math.round(W*xe)),dt=Math.max(2,Math.round(D*xe));(Fe!==t.width||dt!==t.height)&&(t.width=Fe,t.height=dt,i&&i.viewport(0,0,Fe,dt)),k=W,T=D,V||(x=$=k/2,F=O=T/2,V=!0)}function Bn(Y){!l||!Ce||!i||(i.uniform2f(u,t.width,t.height),i.uniform2f(c,k,T),i.uniform2f(d,x,F),i.uniform1f(f,L),i.uniform1f(h,N),i.uniform2f(v,Math.cos(Pe),Math.sin(Pe)),i.uniform1f(p,Y),i.uniform3f(g,b[0],b[1],b[2]),i.clear(i.COLOR_BUFFER_BIT),i.drawArrays(i.TRIANGLES,0,3))}function qe(Y,W,D){const ue=Math.max(0,Math.min(1,(D-Y)/(W-Y)));return ue*ue*(3-2*ue)}function Dn(Y){if(!Z||!r)return;const W=r;W.setTransform(1,0,0,1,0,0),W.clearRect(0,0,t.width,t.height);const D=t.width/k;W.setTransform(D,0,0,D,0,0),W.globalAlpha=1;const ue=Math.min(k,T),xe=Math.max(64,Math.min(118,ue/10)),Fe=xe*2.9,dt=2*Fe*Fe,Nt=Math.sin(Y*.11)*7,ft=Math.cos(Y*.09)*7-N,dr=x+Nt,fr=F+ft,io=Fe*Math.sqrt(2*Math.log(1/.06)),mi=io+De*io*io+xe,Pp=Math.floor((dr-mi)/xe)-1,Fp=Math.ceil((dr+mi)/xe)+1,Rp=Math.floor((fr-mi)/xe)-1,Tp=Math.ceil((fr+mi)/xe)+1;for(let ro=Rp;ro<=Tp;ro++){const $p=(ro+.5)*xe;for(let so=Pp;so<=Fp;so++){const oo=(so+.5)*xe-dr,ao=$p-fr,lo=Math.sqrt(oo*oo+ao*ao)+1e-5;if(lo>mi)continue;const hr=(-1+Math.sqrt(1+4*De*lo))/(2*De),lc=Math.exp(-(hr*hr)/dt),cc=qe(.06,.8,lc)*L*.26;if(cc<.004)continue;const on=xe/(1+2*De*hr)*.26*(.32+1.1*lc),uc=hr/lo,co=dr+oo*uc,uo=fr+ao*uc;co<-on*1.6||co>k+on*1.6||uo<-on*1.6||uo>T+on*1.6||(W.globalAlpha=cc,W.save(),W.translate(co,uo),W.rotate(Pe),W.drawImage(Z,-on,-on,on*2,on*2),W.restore())}}W.globalAlpha=1}function Mt(Y){if(!oe)return;const W=R?Math.min(.05,(Y-R)/1e3):.016;R=Y;const ue=Y-K>2400?.6:1;L+=(ue-L)*Math.min(1,W*3.2);const xe=Math.min(.05,W);Ie+=(($-x)*$e-Ie*ae)*xe,Se+=((O-F)*$e-Se*ae)*xe,x+=Ie*xe,F+=Se*xe,N=(window.scrollY||window.pageYOffset||0)*.55;const Fe=Y/1e3,dt=x/(k||1)-.5,Nt=F/(T||1)-.5;let ft=dt*(dt>=0?ge:Je)+Nt*(Nt>=0?bt:mn);ft>Re?ft=Re:ft<-Re&&(ft=-Re),Pe=wt+ft-N*6e-4,$t(),i?Bn(Fe):Dn(Fe),M=requestAnimationFrame(Mt)}function Lt(Y){if(!oe)return;const W=t.getBoundingClientRect();!W.width||!k||!T||($=(Y.clientX-W.left)/W.width*k,O=(Y.clientY-W.top)/W.height*T,K=performance.now())}function ut(){oe||no||e.matches||n.matches||!ye||document.hidden||(oe=!0,R=0,M=requestAnimationFrame(Mt))}function sn(){oe=!1,M&&(cancelAnimationFrame(M),M=0),R=0}function gi(){e.matches?(sn(),t.classList.remove("is-ready")):ye&&ut()}function jn(){n.matches?sn():ye&&ut()}function sc(){document.hidden?sn():ye&&ut()}const oc=new IntersectionObserver(Y=>{ye=Y[0]?.isIntersecting||!1,ye?ut():sn()},{threshold:0});oc.observe(t),window.addEventListener("pointermove",Lt,{passive:!0,capture:!0}),window.addEventListener("resize",$t),e.addEventListener("change",gi),n.addEventListener("change",jn),document.addEventListener("visibilitychange",sc);function Ap(){const Y=(s.match(/\sd="([^"]+)"/)||[])[1],W=document.createElement("canvas");W.width=256,W.height=256;const D=W.getContext("2d");if(Y&&window.Path2D){const ue=Math.min(8.533333333333333,8.421052631578947);D.setTransform(ue,0,0,ue,ue+(256-30*ue)/2,-6.4*ue),D.fillStyle="rgb(255,255,255)",D.fill(new Path2D(Y),"evenodd"),D.setTransform(1,0,0,1,0,0)}try{const ue=D.getImageData(0,0,256,256),xe=ue.data;for(let Fe=3;Feoe}}const iy=120;function ry(t,e,n){return tn?n:t}function de(t,e,n){return ry((t-e)/(n-e),0,1)}function sy(t){return t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2}function Ho(t){return 1-Math.pow(1-t,3)}function Ve(t,e){return e=e===void 0?1.7:e,1+(e+1)*Math.pow(t-1,3)+e*Math.pow(t-1,2)}function Wu(t){return 1-Math.pow(2,-9*t)*Math.cos(t*15)}function te(t,e){if(t<=e[0].t)return e[0].v;for(let n=1;n8.2&&_<9.4&&(s*=1-.07*Math.sin(de(_,8.2,9.4)*Math.PI))}else if(t<53){const _=t-42;g=te(_,[{t:0,v:1},{t:2,v:0},{t:4.2,v:0},{t:4.6,v:1},{t:6.8,v:1},{t:7.4,v:0},{t:9.4,v:0},{t:10.6,v:1}]),p=te(_,[{t:0,v:1},{t:2,v:.3},{t:4.6,v:1,e:Ve}]),d=te(_,[{t:0,v:0},{t:2,v:.3},{t:4.6,v:.16,e:Ve},{t:10.6,v:0}]),h=te(_,[{t:0,v:0},{t:2,v:-40},{t:4.6,v:0,e:Ve}]),o=te(_,[{t:0,v:0},{t:4.6,v:-.12},{t:10.6,v:0}])}else if(t<60){const _=t-53;c=te(_,[{t:0,v:1},{t:.35,v:0},{t:.45,v:0},{t:.7,v:1}]);const b=de(_,.45,2.2);a=b>0?-2.6*(1-Wu(b)):0,g=te(_,[{t:0,v:1},{t:.57,v:0},{t:.67,v:0},{t:.92,v:1}]);const k=de(_,.67,2.42);f=k>0?-2.6*(1-Wu(k)):0,s=1-.05*(Math.sin(de(_,1.9,2.5)*Math.PI)+Math.sin(de(_,2.5,3.1)*Math.PI))}else if(t<74){let b=function(F){return[te(F,[{t:0,v:0},{t:.25,v:1},{t:.5,v:1},{t:.72,v:.14},{t:.82,v:.14},{t:1,v:0}]),te(F,[{t:0,v:0},{t:.08,v:-.62},{t:.25,v:-.62},{t:.33,v:.62},{t:.7,v:.62},{t:.82,v:-.62},{t:1,v:-.62}])]};var S=b;const _=t-60,k=1-de(_,12,14),T=b(de(_,0,12)),x=b(de(_-.5,0,12));n=T[0]*k,i=(T[1]+.05*Math.sin(_*7))*k,o=(x[0]-T[0])*.6*k,a=(x[1]-T[1])*.6*k,h=(x[0]-T[0])*30*k,E=de(_,0,.4)*k}else if(t<85.4){const _=t-74,b=te(_,[{t:0,v:0},{t:4,v:1},{t:8,v:.24},{t:9.6,v:1,e:Ve},{t:11.4,v:0}]);o=b*.5,d=-b*.5,l=te(_,[{t:0,v:0},{t:4,v:6},{t:8,v:20},{t:9.6,v:38,e:Ve},{t:11.4,v:0}]),h=-l*.7,a=te(_,[{t:0,v:0},{t:8,v:0},{t:9.6,v:.4},{t:11.4,v:0}])}else if(t<96.4){const _=t-85.4,b=de(_,0,5.6),k=de(_,5.6,7.6),T=.72*Math.min(1,_/.6)*(1-k);d=Math.cos(b*Math.PI*2)*T,f=Math.sin(b*Math.PI*2)*T*.55,h=b*360*(1-k);const x=te(_,[{t:0,v:0},{t:7.6,v:0},{t:8.2,v:1,e:Ho},{t:8.6,v:.55},{t:9.4,v:0}]);o=-.16*x,d+=.16*x,l=-6*x,h+=6*x,s=1+.05*x,m=1+.9*x}else if(t<108.6){const _=t-96.4,b=de(_,9.6,12.2);n=te(_,[{t:0,v:0},{t:2.1,v:1},{t:4.8,v:.08},{t:7.5,v:1},{t:9.6,v:0}])*(1-b),i=-.35*Math.abs(Math.sin(de(_,0,9.6)*Math.PI*3))*(1-b);const k=Math.sin(_*6.2)*(1-b);u=1+.12*k,p=1-.12*k,l=k*8,h=-k*8,o=.06*k,d=-.06*k,E=de(_,0,.4)*(1-b)}else{const _=t-108.6,b=Math.sin(de(_,0,8)*Math.PI),k=1-de(_,8,11.4);s=1+.04*b*k,i=-.1*b*k,r=2*b*k,m=1+.5*Math.sin(de(_,0,6)*Math.PI),v=1+.1*Math.sin(de(_,0,6)*Math.PI)}return e.x=n,e.y=i,e.rot=r,e.scale=s,e.ax=o,e.ay=a,e.ar=l,e.asc=u,e.afade=c,e.bx=d,e.by=f,e.br=h,e.bsc=p,e.bfade=g,e.hfade=m,e.hsc=v,e.shd=E,e}function oy(t={}){const e=t.arena||document.querySelector(".pipeline-glyph.logo-loop");if(!e)return null;const n=e.querySelector(".loop-mark"),i=e.querySelector(".loop-piece-a"),r=e.querySelector(".loop-piece-b"),s=e.querySelector(".loop-halo"),o=e.querySelector(".loop-shadow");if(!n||!i||!r||!s||!o)return null;const a=t.reducedMotion||window.matchMedia("(prefers-reduced-motion: reduce)"),l=iy;let u=34,c=0,d=0;function f(){u=n.offsetWidth||34,c=Math.max(0,e.offsetWidth-u-4),d=Math.max(0,(e.offsetHeight-u)/2-2),e.style.setProperty("--mark-c",u/2+"px")}function h(M){const R=Math.min(1,Math.max(0,M.x))*c,Z=M.y*d;n.style.transform="translate3d("+R.toFixed(2)+"px,"+Z.toFixed(2)+"px,0) rotate("+M.rot.toFixed(2)+"deg) scale("+M.scale.toFixed(3)+")",i.style.transform="translate3d("+(M.ax*u).toFixed(2)+"px,"+(M.ay*u).toFixed(2)+"px,0) rotate("+M.ar.toFixed(2)+"deg) scale("+M.asc.toFixed(3)+")",i.style.opacity=M.afade.toFixed(3),r.style.transform="translate3d("+(M.bx*u).toFixed(2)+"px,"+(M.by*u).toFixed(2)+"px,0) rotate("+M.br.toFixed(2)+"deg) scale("+M.bsc.toFixed(3)+")",r.style.opacity=M.bfade.toFixed(3),s.style.transform="scale("+M.hsc.toFixed(3)+")",s.style.opacity=(.09*M.hfade).toFixed(3),o.style.transform="translateX("+R.toFixed(2)+"px) scaleX("+(.75+.4*Math.abs(M.x)).toFixed(3)+")",o.style.opacity=(M.shd*.5).toFixed(3)}let p=0,g=0,m=0,v=!1,E=!1,S=!1,_=0;function b(){return S||a.matches||document.hidden||!e.offsetParent?!1:E}function k(M){if(!v)return;if(m=requestAnimationFrame(k),!b()){x();return}const R=g?(M-g)/1e3:0;g=M,p=(p+Math.min(R,.1))%l,_+=1,h(Ai(p))}function T(){v||S||b()&&(v=!0,g=0,m=requestAnimationFrame(k))}function x(){v=!1,m&&(cancelAnimationFrame(m),m=0),g=0}function F(){b()?T():x()}function $(){a.matches?(x(),h(Ai(0))):F()}function O(){f(),v&&h(Ai(p))}function L(){g=0,F()}const N=new IntersectionObserver(M=>{E=M[0]?M[0].isIntersecting:!1,F()},{threshold:0});N.observe(e),window.addEventListener("resize",O),a.addEventListener("change",$),document.addEventListener("visibilitychange",L);function K(){S||(S=!0,x(),N.disconnect(),window.removeEventListener("resize",O),a.removeEventListener("change",$),document.removeEventListener("visibilitychange",L))}window.addEventListener("pagehide",K);function V(M){p=(M%l+l)%l,h(Ai(p))}return f(),h(Ai(0)),F(),{isRunning:()=>v,currentTime:()=>p,frameCount:()=>_,seek:V,dispose:K}}const ay=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function Xt(t){const e=String(t||"").trim().match(ay);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function ly(t,e){if(t.length===0&&e.length===0)return 0;if(t.length===0)return 1;if(e.length===0)return-1;for(let n=0;n0)}function uy(t){const e=Xt(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function kl(t){let e=String(t??"").trim();if((e.startsWith("'")||e.startsWith('"'))&&(e=e.slice(1,-1).trim()),e===""||e==="any"||e==="*")return{min:null,minInclusive:!1,max:null,maxInclusive:!1};if(e.startsWith("^")){const o=e.slice(1).trim();return Xt(o)?{min:o,minInclusive:!0,max:uy(o),maxInclusive:!1}:null}if(Xt(e))return{min:e,minInclusive:!0,max:e,maxInclusive:!0};const n={min:null,minInclusive:!1,max:null,maxInclusive:!1},i=/(>=|<=|>|<)\s*([0-9][0-9A-Za-z.+-]*)/g;let r=!1,s;for(;(s=i.exec(e))!==null;){const[,o,a]=s;if(!Xt(a))return null;r=!0,o===">="||o===">"?(n.min=a,n.minInclusive=o===">="):(n.max=a,n.maxInclusive=o==="<=")}return r?n:null}function zu(t,e){const n=kl(t);if(!n||!Xt(e))return!1;if(n.min!==null){const i=fs(e,n.min);if(i<0||i===0&&!n.minInclusive)return!1}if(n.max!==null){const i=fs(e,n.max);if(i>0||i===0&&!n.maxInclusive)return!1}return!0}function dy(t,e){const n=kl(t);if(!n||!Xt(e))return!1;if(n.max===null)return!0;const i=fs(n.max,e);return i>0?!0:i===0&&n.maxInclusive}function qn(t){const e=kl(t);return e?e.min:null}const fy="https://pub.dev/api/packages/",hy=8e3;function py(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null}=e,r=Array.isArray(t?.versions)?t.versions:[];let s=null;for(const o of r){const a=o?.version;if(!a||o.retracted||cy(a))continue;const l=o.pubspec?.environment||{};n&&l.sdk&&!zu(l.sdk,n)||i&&l.flutter&&!zu(l.flutter,i)||(!s||fs(a,s)>0)&&(s=a)}return s?{version:s,constraint:`^${s}`}:null}async function gy(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null,fetchImpl:r=fetch}=e;let s;try{const a=await r(`${fy}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(hy)});if(!a.ok)return{name:t,constraint:null,version:null,error:a.status===404?`"${t}" was not found on pub.dev`:`pub.dev returned ${a.status} for "${t}"`};s=await a.json()}catch(a){return{name:t,constraint:null,version:null,error:`could not reach pub.dev for "${t}" (${a.message})`}}const o=py(s,{dartSdkFloor:n,flutterSdkFloor:i});return o?{name:t,...o,error:null}:{name:t,constraint:null,version:null,error:n?`no published "${t}" release supports Dart ${n}`:`no published "${t}" release could be read`}}async function my(t,e={}){const n=await Promise.all(t.map(i=>gy(i,e)));return new Map(n.map(({name:i,...r})=>[i,r]))}async function vy(t,e={},n={}){const{resolveVersions:i=my}=n,r=Object.entries(e).filter(([c])=>c&&c!=="flutter"),s=vh(t),o={dartSdkFloor:qn(s.sdk),flutterSdkFloor:qn(s.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(r.length===0)return a;const l=Ms(t),u=[];for(const[c,d]of r){const f=l.get(c);if(!f){u.push(c);continue}const h=qn(d);if(!h){a.kept.push({name:c,constraint:f.constraint});continue}if(!f.isScalar){a.warnings.push(`"${c}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${h}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:c,constraint:f.constraint});continue}if(dy(f.constraint,h)){a.kept.push({name:c,constraint:f.constraint});continue}a.overrides[c]=`^${h}`,a.warnings.push(`"${c}" was pinned to ${f.constraint} in your project, which cannot resolve the ${h} the generated code needs. Raising it to ^${h} — this changes a dependency the rest of your app also uses.`)}if(u.length>0){const c=await i(u,o);for(const d of u){const f=c.get(d);if(f?.constraint){a.additions[d]=f.constraint;continue}const h=e[d]||"";if(qn(h)){a.additions[d]=`^${qn(h)}`,a.warnings.push(`Could not confirm "${d}" version on pub.dev (${f?.error||"lookup failed"}). Using ^${qn(h)} from the AI's recommendation — verify this is current.`);continue}a.additions[d]=">=0.0.0",a.warnings.push(`Could not determine a version for "${d}" (${f?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const _y={"&":"&","<":"<",">":">",'"':""","'":"'"};function Qt(t){return String(t??"").replace(/[&<>"']/g,e=>_y[e])}function z(t){return t?Qt(t).replace(/\n/g,"
      "):""}function Jt(t){return Qt(t).replace(/\r?\n/g," ")}function Ls(t,e={}){const n=t?.pipelineStep;if(n!=null&&e[n]!=null)return e[n];const i=t?.message||"";return i.includes("Code Generator")?2:i.includes("Code Review")?3:1}function xh(t){if(!t)return{kind:"generic",title:"Generation failed",message:"An unknown error occurred. Please try again.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1};if(t.isModelArmor){const n=t.code==="MODEL_ARMOR_BLOCKED";return{kind:"safety",title:t.userTitle||"Request blocked for safety",message:t.userMessage||t.message,detail:t.retryExplanation||"",canRetry:!n,canEdit:!0,canUpgrade:!1}}if(t.isUsageLimit)return{kind:"quota",title:"Monthly limit reached",message:t.message||"You've used all your generations for this period.",detail:"",canRetry:!1,canEdit:!1,canUpgrade:!0};const e=t.message||"";return/timed out after/i.test(e)?{kind:"timeout",title:"Request timed out",message:"The generation service took too long to respond.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:/unreachable|failed to fetch|load failed|cors/i.test(e)?{kind:"network",title:"Connection problem",message:"We couldn't reach the generation service. Check your connection and try again.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:{kind:"generic",title:"Generation failed",message:e||"An unexpected error occurred.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1}}function yy(t){const e={"Integration Audit Report":"📋","Critical Issues":"❌",Warnings:"⚠️",Recommendations:"✅","Overall Score":"📊"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📄"}function wy(t){const e={critical:"❌",warning:"⚠️",recommendation:"✅",score:"📊",issue:"🔍",fix:"🔧"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📝"}function by(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 li(t){if(!t)return"";if(typeof t!="string")return String(t);const e=/```(?:\w+)?\n?([\s\S]*?)```/,n=t.match(e);return n?n[1].trim():t.trim()}function qu(t){return t=Qt(t),t=t.replace(/\*\*(.*?)\*\*/g,'$1'),t=t.replace(/\*(.*?)\*/g,'$1'),t=t.replace(/`(.*?)`/g,'$1'),t=t.replace(/\b(FAIL|ERROR|CRITICAL)\b/g,'$1'),t=t.replace(/\b(WARN|WARNING)\b/g,'$1'),t=t.replace(/\b(PASS|SUCCESS|OK)\b/g,'$1'),t}function Ih(t,e="dart",n=globalThis.hljs){if(!t)return"";const i=li(t);try{return n.highlight(i,{language:e}).value}catch(r){console.warn("Syntax highlighting failed:",r);try{return n.highlight(i,{language:"json"}).value}catch{return Qt(i)}}}function Ns(t,e={}){const{highlighter:n=globalThis.hljs}=e;let i='
      ';const r=String(t??"").split(` -`);let s=!1,o="";for(const a of r){if(a.startsWith("```")){if(s){const l=by(o),u=Ih(o.trim(),l,n);i+=`
      +`)}let l=null,u,c,d,f,h,p,g,m,v;function E(Y,W){if(!i)return null;const D=i.createShader(Y);return i.shaderSource(D,W),i.compileShader(D),i.getShaderParameter(D,i.COMPILE_STATUS)?D:(window.console&&console.warn("fx-grid shader: "+i.getShaderInfoLog(D)),null)}if(i){const Y=E(i.VERTEX_SHADER,o),W=E(i.FRAGMENT_SHADER,a());if(Y&&W&&(l=i.createProgram(),i.attachShader(l,Y),i.attachShader(l,W),i.linkProgram(l),i.getProgramParameter(l,i.LINK_STATUS)||(window.console&&console.warn("fx-grid link: "+i.getProgramInfoLog(l)),l=null)),l){i.useProgram(l),i.bindBuffer(i.ARRAY_BUFFER,i.createBuffer()),i.bufferData(i.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),i.STATIC_DRAW);const D=i.getAttribLocation(l,"p");i.enableVertexAttribArray(D),i.vertexAttribPointer(D,2,i.FLOAT,!1,0,0),u=i.getUniformLocation(l,"res"),c=i.getUniformLocation(l,"design"),d=i.getUniformLocation(l,"mouse"),f=i.getUniformLocation(l,"energy"),h=i.getUniformLocation(l,"parallax"),p=i.getUniformLocation(l,"t"),g=i.getUniformLocation(l,"ink"),m=i.getUniformLocation(l,"mark"),v=i.getUniformLocation(l,"rot"),i.enable(i.BLEND),i.blendFunc(i.ONE,i.ONE_MINUS_SRC_ALPHA),i.clearColor(0,0,0,0)}else{i=null;const D=t.cloneNode(!1);if(t.parentNode.replaceChild(D,t),t=D,r=t.getContext("2d"),!r)return null}}function S(Y){if(!Y)return null;const W=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(Y);if(W){let D=W[1];return D.length===3&&(D=D[0]+D[0]+D[1]+D[1]+D[2]+D[2]),[parseInt(D.slice(0,2),16)/255,parseInt(D.slice(2,4),16)/255,parseInt(D.slice(4,6),16)/255]}try{const D=document.createElement("canvas");D.width=1,D.height=1;const ue=D.getContext("2d");ue.fillStyle="rgb(9, 8, 7)";const xe=String(ue.fillStyle);ue.fillStyle=Y;const Fe=String(ue.fillStyle);if(Fe===xe)return null;const dt=/^#([0-9a-f]{6})$/i.exec(Fe);if(dt){const ft=dt[1];return[parseInt(ft.slice(0,2),16)/255,parseInt(ft.slice(2,4),16)/255,parseInt(ft.slice(4,6),16)/255]}const Nt=/rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i.exec(Fe);if(Nt)return[Number(Nt[1])/255,Number(Nt[2])/255,Number(Nt[3])/255]}catch{}return null}function _(){let Y="";try{const W=getComputedStyle(document.documentElement);Y=(W.getPropertyValue("--fx-ink")||"").trim()||(W.getPropertyValue("--fg")||"").trim()}catch{}return S(Y)||[.56,.68,.88]}const b=_();let k=1920,T=1080,x=960,F=540,$=960,O=540,L=.66,N=0,K=-1e9,V=!1,M=0,R=0,Z=null,Ce=!1,oe=!1,ye=!1;const $e=64,ae=15.2;let Ie=0,Se=0;const De=.0032,wt=0,ge=.56,Je=.26,bt=.32,mn=.16,Re=.349;let Pe=wt;function $t(){const Y=t.getBoundingClientRect(),W=t.clientWidth,D=t.clientHeight;if(!Y.width||!W||!D)return;const ue=Math.min(window.devicePixelRatio||1,2),xe=Math.max(.2,Math.min(2,Y.width/W*ue)),Fe=Math.max(2,Math.round(W*xe)),dt=Math.max(2,Math.round(D*xe));(Fe!==t.width||dt!==t.height)&&(t.width=Fe,t.height=dt,i&&i.viewport(0,0,Fe,dt)),k=W,T=D,V||(x=$=k/2,F=O=T/2,V=!0)}function Bn(Y){!l||!Ce||!i||(i.uniform2f(u,t.width,t.height),i.uniform2f(c,k,T),i.uniform2f(d,x,F),i.uniform1f(f,L),i.uniform1f(h,N),i.uniform2f(v,Math.cos(Pe),Math.sin(Pe)),i.uniform1f(p,Y),i.uniform3f(g,b[0],b[1],b[2]),i.clear(i.COLOR_BUFFER_BIT),i.drawArrays(i.TRIANGLES,0,3))}function qe(Y,W,D){const ue=Math.max(0,Math.min(1,(D-Y)/(W-Y)));return ue*ue*(3-2*ue)}function Dn(Y){if(!Z||!r)return;const W=r;W.setTransform(1,0,0,1,0,0),W.clearRect(0,0,t.width,t.height);const D=t.width/k;W.setTransform(D,0,0,D,0,0),W.globalAlpha=1;const ue=Math.min(k,T),xe=Math.max(64,Math.min(118,ue/10)),Fe=xe*2.9,dt=2*Fe*Fe,Nt=Math.sin(Y*.11)*7,ft=Math.cos(Y*.09)*7-N,dr=x+Nt,fr=F+ft,no=Fe*Math.sqrt(2*Math.log(1/.06)),mi=no+De*no*no+xe,Rp=Math.floor((dr-mi)/xe)-1,Tp=Math.ceil((dr+mi)/xe)+1,$p=Math.floor((fr-mi)/xe)-1,Mp=Math.ceil((fr+mi)/xe)+1;for(let io=$p;io<=Mp;io++){const Lp=(io+.5)*xe;for(let ro=Rp;ro<=Tp;ro++){const so=(ro+.5)*xe-dr,oo=Lp-fr,ao=Math.sqrt(so*so+oo*oo)+1e-5;if(ao>mi)continue;const hr=(-1+Math.sqrt(1+4*De*ao))/(2*De),cc=Math.exp(-(hr*hr)/dt),uc=qe(.06,.8,cc)*L*.26;if(uc<.004)continue;const on=xe/(1+2*De*hr)*.26*(.32+1.1*cc),dc=hr/ao,lo=dr+so*dc,co=fr+oo*dc;lo<-on*1.6||lo>k+on*1.6||co<-on*1.6||co>T+on*1.6||(W.globalAlpha=uc,W.save(),W.translate(lo,co),W.rotate(Pe),W.drawImage(Z,-on,-on,on*2,on*2),W.restore())}}W.globalAlpha=1}function Mt(Y){if(!oe)return;const W=R?Math.min(.05,(Y-R)/1e3):.016;R=Y;const ue=Y-K>2400?.6:1;L+=(ue-L)*Math.min(1,W*3.2);const xe=Math.min(.05,W);Ie+=(($-x)*$e-Ie*ae)*xe,Se+=((O-F)*$e-Se*ae)*xe,x+=Ie*xe,F+=Se*xe,N=(window.scrollY||window.pageYOffset||0)*.55;const Fe=Y/1e3,dt=x/(k||1)-.5,Nt=F/(T||1)-.5;let ft=dt*(dt>=0?ge:Je)+Nt*(Nt>=0?bt:mn);ft>Re?ft=Re:ft<-Re&&(ft=-Re),Pe=wt+ft-N*6e-4,$t(),i?Bn(Fe):Dn(Fe),M=requestAnimationFrame(Mt)}function Lt(Y){if(!oe)return;const W=t.getBoundingClientRect();!W.width||!k||!T||($=(Y.clientX-W.left)/W.width*k,O=(Y.clientY-W.top)/W.height*T,K=performance.now())}function ut(){oe||to||e.matches||n.matches||!ye||document.hidden||(oe=!0,R=0,M=requestAnimationFrame(Mt))}function sn(){oe=!1,M&&(cancelAnimationFrame(M),M=0),R=0}function gi(){e.matches?(sn(),t.classList.remove("is-ready")):ye&&ut()}function jn(){n.matches?sn():ye&&ut()}function oc(){document.hidden?sn():ye&&ut()}const ac=new IntersectionObserver(Y=>{ye=Y[0]?.isIntersecting||!1,ye?ut():sn()},{threshold:0});ac.observe(t),window.addEventListener("pointermove",Lt,{passive:!0,capture:!0}),window.addEventListener("resize",$t),e.addEventListener("change",gi),n.addEventListener("change",jn),document.addEventListener("visibilitychange",oc);function Fp(){const Y=(s.match(/\sd="([^"]+)"/)||[])[1],W=document.createElement("canvas");W.width=256,W.height=256;const D=W.getContext("2d");if(Y&&window.Path2D){const ue=Math.min(8.533333333333333,8.421052631578947);D.setTransform(ue,0,0,ue,ue+(256-30*ue)/2,-6.4*ue),D.fillStyle="rgb(255,255,255)",D.fill(new Path2D(Y),"evenodd"),D.setTransform(1,0,0,1,0,0)}try{const ue=D.getImageData(0,0,256,256),xe=ue.data;for(let Fe=3;Feoe}}const ry=120;function sy(t,e,n){return tn?n:t}function de(t,e,n){return sy((t-e)/(n-e),0,1)}function oy(t){return t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2}function Uo(t){return 1-Math.pow(1-t,3)}function Ve(t,e){return e=e===void 0?1.7:e,1+(e+1)*Math.pow(t-1,3)+e*Math.pow(t-1,2)}function zu(t){return 1-Math.pow(2,-9*t)*Math.cos(t*15)}function te(t,e){if(t<=e[0].t)return e[0].v;for(let n=1;n8.2&&_<9.4&&(s*=1-.07*Math.sin(de(_,8.2,9.4)*Math.PI))}else if(t<53){const _=t-42;g=te(_,[{t:0,v:1},{t:2,v:0},{t:4.2,v:0},{t:4.6,v:1},{t:6.8,v:1},{t:7.4,v:0},{t:9.4,v:0},{t:10.6,v:1}]),p=te(_,[{t:0,v:1},{t:2,v:.3},{t:4.6,v:1,e:Ve}]),d=te(_,[{t:0,v:0},{t:2,v:.3},{t:4.6,v:.16,e:Ve},{t:10.6,v:0}]),h=te(_,[{t:0,v:0},{t:2,v:-40},{t:4.6,v:0,e:Ve}]),o=te(_,[{t:0,v:0},{t:4.6,v:-.12},{t:10.6,v:0}])}else if(t<60){const _=t-53;c=te(_,[{t:0,v:1},{t:.35,v:0},{t:.45,v:0},{t:.7,v:1}]);const b=de(_,.45,2.2);a=b>0?-2.6*(1-zu(b)):0,g=te(_,[{t:0,v:1},{t:.57,v:0},{t:.67,v:0},{t:.92,v:1}]);const k=de(_,.67,2.42);f=k>0?-2.6*(1-zu(k)):0,s=1-.05*(Math.sin(de(_,1.9,2.5)*Math.PI)+Math.sin(de(_,2.5,3.1)*Math.PI))}else if(t<74){let b=function(F){return[te(F,[{t:0,v:0},{t:.25,v:1},{t:.5,v:1},{t:.72,v:.14},{t:.82,v:.14},{t:1,v:0}]),te(F,[{t:0,v:0},{t:.08,v:-.62},{t:.25,v:-.62},{t:.33,v:.62},{t:.7,v:.62},{t:.82,v:-.62},{t:1,v:-.62}])]};var S=b;const _=t-60,k=1-de(_,12,14),T=b(de(_,0,12)),x=b(de(_-.5,0,12));n=T[0]*k,i=(T[1]+.05*Math.sin(_*7))*k,o=(x[0]-T[0])*.6*k,a=(x[1]-T[1])*.6*k,h=(x[0]-T[0])*30*k,E=de(_,0,.4)*k}else if(t<85.4){const _=t-74,b=te(_,[{t:0,v:0},{t:4,v:1},{t:8,v:.24},{t:9.6,v:1,e:Ve},{t:11.4,v:0}]);o=b*.5,d=-b*.5,l=te(_,[{t:0,v:0},{t:4,v:6},{t:8,v:20},{t:9.6,v:38,e:Ve},{t:11.4,v:0}]),h=-l*.7,a=te(_,[{t:0,v:0},{t:8,v:0},{t:9.6,v:.4},{t:11.4,v:0}])}else if(t<96.4){const _=t-85.4,b=de(_,0,5.6),k=de(_,5.6,7.6),T=.72*Math.min(1,_/.6)*(1-k);d=Math.cos(b*Math.PI*2)*T,f=Math.sin(b*Math.PI*2)*T*.55,h=b*360*(1-k);const x=te(_,[{t:0,v:0},{t:7.6,v:0},{t:8.2,v:1,e:Uo},{t:8.6,v:.55},{t:9.4,v:0}]);o=-.16*x,d+=.16*x,l=-6*x,h+=6*x,s=1+.05*x,m=1+.9*x}else if(t<108.6){const _=t-96.4,b=de(_,9.6,12.2);n=te(_,[{t:0,v:0},{t:2.1,v:1},{t:4.8,v:.08},{t:7.5,v:1},{t:9.6,v:0}])*(1-b),i=-.35*Math.abs(Math.sin(de(_,0,9.6)*Math.PI*3))*(1-b);const k=Math.sin(_*6.2)*(1-b);u=1+.12*k,p=1-.12*k,l=k*8,h=-k*8,o=.06*k,d=-.06*k,E=de(_,0,.4)*(1-b)}else{const _=t-108.6,b=Math.sin(de(_,0,8)*Math.PI),k=1-de(_,8,11.4);s=1+.04*b*k,i=-.1*b*k,r=2*b*k,m=1+.5*Math.sin(de(_,0,6)*Math.PI),v=1+.1*Math.sin(de(_,0,6)*Math.PI)}return e.x=n,e.y=i,e.rot=r,e.scale=s,e.ax=o,e.ay=a,e.ar=l,e.asc=u,e.afade=c,e.bx=d,e.by=f,e.br=h,e.bsc=p,e.bfade=g,e.hfade=m,e.hsc=v,e.shd=E,e}function ay(t={}){const e=t.arena||document.querySelector(".pipeline-glyph.logo-loop");if(!e)return null;const n=e.querySelector(".loop-mark"),i=e.querySelector(".loop-piece-a"),r=e.querySelector(".loop-piece-b"),s=e.querySelector(".loop-halo"),o=e.querySelector(".loop-shadow");if(!n||!i||!r||!s||!o)return null;const a=t.reducedMotion||window.matchMedia("(prefers-reduced-motion: reduce)"),l=ry;let u=34,c=0,d=0;function f(){u=n.offsetWidth||34,c=Math.max(0,e.offsetWidth-u-4),d=Math.max(0,(e.offsetHeight-u)/2-2),e.style.setProperty("--mark-c",u/2+"px")}function h(M){const R=Math.min(1,Math.max(0,M.x))*c,Z=M.y*d;n.style.transform="translate3d("+R.toFixed(2)+"px,"+Z.toFixed(2)+"px,0) rotate("+M.rot.toFixed(2)+"deg) scale("+M.scale.toFixed(3)+")",i.style.transform="translate3d("+(M.ax*u).toFixed(2)+"px,"+(M.ay*u).toFixed(2)+"px,0) rotate("+M.ar.toFixed(2)+"deg) scale("+M.asc.toFixed(3)+")",i.style.opacity=M.afade.toFixed(3),r.style.transform="translate3d("+(M.bx*u).toFixed(2)+"px,"+(M.by*u).toFixed(2)+"px,0) rotate("+M.br.toFixed(2)+"deg) scale("+M.bsc.toFixed(3)+")",r.style.opacity=M.bfade.toFixed(3),s.style.transform="scale("+M.hsc.toFixed(3)+")",s.style.opacity=(.09*M.hfade).toFixed(3),o.style.transform="translateX("+R.toFixed(2)+"px) scaleX("+(.75+.4*Math.abs(M.x)).toFixed(3)+")",o.style.opacity=(M.shd*.5).toFixed(3)}let p=0,g=0,m=0,v=!1,E=!1,S=!1,_=0;function b(){return S||a.matches||document.hidden||!e.offsetParent?!1:E}function k(M){if(!v)return;if(m=requestAnimationFrame(k),!b()){x();return}const R=g?(M-g)/1e3:0;g=M,p=(p+Math.min(R,.1))%l,_+=1,h(Ai(p))}function T(){v||S||b()&&(v=!0,g=0,m=requestAnimationFrame(k))}function x(){v=!1,m&&(cancelAnimationFrame(m),m=0),g=0}function F(){b()?T():x()}function $(){a.matches?(x(),h(Ai(0))):F()}function O(){f(),v&&h(Ai(p))}function L(){g=0,F()}const N=new IntersectionObserver(M=>{E=M[0]?M[0].isIntersecting:!1,F()},{threshold:0});N.observe(e),window.addEventListener("resize",O),a.addEventListener("change",$),document.addEventListener("visibilitychange",L);function K(){S||(S=!0,x(),N.disconnect(),window.removeEventListener("resize",O),a.removeEventListener("change",$),document.removeEventListener("visibilitychange",L))}window.addEventListener("pagehide",K);function V(M){p=(M%l+l)%l,h(Ai(p))}return f(),h(Ai(0)),F(),{isRunning:()=>v,currentTime:()=>p,frameCount:()=>_,seek:V,dispose:K}}const ly=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function Xt(t){const e=String(t||"").trim().match(ly);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function cy(t,e){if(t.length===0&&e.length===0)return 0;if(t.length===0)return 1;if(e.length===0)return-1;for(let n=0;n0)}function dy(t){const e=Xt(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function kl(t){let e=String(t??"").trim();if((e.startsWith("'")||e.startsWith('"'))&&(e=e.slice(1,-1).trim()),e===""||e==="any"||e==="*")return{min:null,minInclusive:!1,max:null,maxInclusive:!1};if(e.startsWith("^")){const o=e.slice(1).trim();return Xt(o)?{min:o,minInclusive:!0,max:dy(o),maxInclusive:!1}:null}if(Xt(e))return{min:e,minInclusive:!0,max:e,maxInclusive:!0};const n={min:null,minInclusive:!1,max:null,maxInclusive:!1},i=/(>=|<=|>|<)\s*([0-9][0-9A-Za-z.+-]*)/g;let r=!1,s;for(;(s=i.exec(e))!==null;){const[,o,a]=s;if(!Xt(a))return null;r=!0,o===">="||o===">"?(n.min=a,n.minInclusive=o===">="):(n.max=a,n.maxInclusive=o==="<=")}return r?n:null}function qu(t,e){const n=kl(t);if(!n||!Xt(e))return!1;if(n.min!==null){const i=fs(e,n.min);if(i<0||i===0&&!n.minInclusive)return!1}if(n.max!==null){const i=fs(e,n.max);if(i>0||i===0&&!n.maxInclusive)return!1}return!0}function fy(t,e){const n=kl(t);if(!n||!Xt(e))return!1;if(n.max===null)return!0;const i=fs(n.max,e);return i>0?!0:i===0&&n.maxInclusive}function qn(t){const e=kl(t);return e?e.min:null}const hy="https://pub.dev/api/packages/",py=8e3;function gy(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null}=e,r=Array.isArray(t?.versions)?t.versions:[];let s=null;for(const o of r){const a=o?.version;if(!a||o.retracted||uy(a))continue;const l=o.pubspec?.environment||{};n&&l.sdk&&!qu(l.sdk,n)||i&&l.flutter&&!qu(l.flutter,i)||(!s||fs(a,s)>0)&&(s=a)}return s?{version:s,constraint:`^${s}`}:null}async function my(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null,fetchImpl:r=fetch}=e;let s;try{const a=await r(`${hy}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(py)});if(!a.ok)return{name:t,constraint:null,version:null,error:a.status===404?`"${t}" was not found on pub.dev`:`pub.dev returned ${a.status} for "${t}"`};s=await a.json()}catch(a){return{name:t,constraint:null,version:null,error:`could not reach pub.dev for "${t}" (${a.message})`}}const o=gy(s,{dartSdkFloor:n,flutterSdkFloor:i});return o?{name:t,...o,error:null}:{name:t,constraint:null,version:null,error:n?`no published "${t}" release supports Dart ${n}`:`no published "${t}" release could be read`}}async function vy(t,e={}){const n=await Promise.all(t.map(i=>my(i,e)));return new Map(n.map(({name:i,...r})=>[i,r]))}async function _y(t,e={},n={}){const{resolveVersions:i=vy}=n,r=Object.entries(e).filter(([c])=>c&&c!=="flutter"),s=_h(t),o={dartSdkFloor:qn(s.sdk),flutterSdkFloor:qn(s.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(r.length===0)return a;const l=$s(t),u=[];for(const[c,d]of r){const f=l.get(c);if(!f){u.push(c);continue}const h=qn(d);if(!h){a.kept.push({name:c,constraint:f.constraint});continue}if(!f.isScalar){a.warnings.push(`"${c}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${h}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:c,constraint:f.constraint});continue}if(fy(f.constraint,h)){a.kept.push({name:c,constraint:f.constraint});continue}a.overrides[c]=`^${h}`,a.warnings.push(`"${c}" was pinned to ${f.constraint} in your project, which cannot resolve the ${h} the generated code needs. Raising it to ^${h} — this changes a dependency the rest of your app also uses.`)}if(u.length>0){const c=await i(u,o);for(const d of u){const f=c.get(d);if(f?.constraint){a.additions[d]=f.constraint;continue}const h=e[d]||"";if(qn(h)){a.additions[d]=`^${qn(h)}`,a.warnings.push(`Could not confirm "${d}" version on pub.dev (${f?.error||"lookup failed"}). Using ^${qn(h)} from the AI's recommendation — verify this is current.`);continue}a.additions[d]=">=0.0.0",a.warnings.push(`Could not determine a version for "${d}" (${f?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const yy={"&":"&","<":"<",">":">",'"':""","'":"'"};function Qt(t){return String(t??"").replace(/[&<>"']/g,e=>yy[e])}function z(t){return t?Qt(t).replace(/\n/g,"
      "):""}function Jt(t){return Qt(t).replace(/\r?\n/g," ")}function Ms(t,e={}){const n=t?.pipelineStep;if(n!=null&&e[n]!=null)return e[n];const i=t?.message||"";return i.includes("Code Generator")?2:i.includes("Code Review")?3:1}function kh(t){if(!t)return{kind:"generic",title:"Generation failed",message:"An unknown error occurred. Please try again.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1};if(t.isModelArmor){const n=t.code==="MODEL_ARMOR_BLOCKED";return{kind:"safety",title:t.userTitle||"Request blocked for safety",message:t.userMessage||t.message,detail:t.retryExplanation||"",canRetry:!n,canEdit:!0,canUpgrade:!1}}if(t.isUsageLimit)return{kind:"quota",title:"Monthly limit reached",message:t.message||"You've used all your generations for this period.",detail:"",canRetry:!1,canEdit:!1,canUpgrade:!0};const e=t.message||"";return/timed out after/i.test(e)?{kind:"timeout",title:"Request timed out",message:"The generation service took too long to respond.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:/unreachable|failed to fetch|load failed|cors/i.test(e)?{kind:"network",title:"Connection problem",message:"We couldn't reach the generation service. Check your connection and try again.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:{kind:"generic",title:"Generation failed",message:e||"An unexpected error occurred.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1}}function wy(t){const e={"Integration Audit Report":"📋","Critical Issues":"❌",Warnings:"⚠️",Recommendations:"✅","Overall Score":"📊"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📄"}function by(t){const e={critical:"❌",warning:"⚠️",recommendation:"✅",score:"📊",issue:"🔍",fix:"🔧"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📝"}function Ey(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 li(t){if(!t)return"";if(typeof t!="string")return String(t);const e=/```(?:\w+)?\n?([\s\S]*?)```/,n=t.match(e);return n?n[1].trim():t.trim()}function Vu(t){return t=Qt(t),t=t.replace(/\*\*(.*?)\*\*/g,'$1'),t=t.replace(/\*(.*?)\*/g,'$1'),t=t.replace(/`(.*?)`/g,'$1'),t=t.replace(/\b(FAIL|ERROR|CRITICAL)\b/g,'$1'),t=t.replace(/\b(WARN|WARNING)\b/g,'$1'),t=t.replace(/\b(PASS|SUCCESS|OK)\b/g,'$1'),t}function Ch(t,e="dart",n=globalThis.hljs){if(!t)return"";const i=li(t);try{return n.highlight(i,{language:e}).value}catch(r){console.warn("Syntax highlighting failed:",r);try{return n.highlight(i,{language:"json"}).value}catch{return Qt(i)}}}function Ls(t,e={}){const{highlighter:n=globalThis.hljs}=e;let i='
      ';const r=String(t??"").split(` +`);let s=!1,o="";for(const a of r){if(a.startsWith("```")){if(s){const l=Ey(o),u=Ch(o.trim(),l,n);i+=`
      ${u}
      `,o="",s=!1}else s=!0;continue}if(s){o+=a+` `;continue}if(a.startsWith("# ")){const l=a.substring(2).trim();i+=`

      - ${yy(l)} + ${wy(l)} ${Qt(l)}

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

      - ${wy(l)} + ${by(l)} ${Qt(l)}

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

      ${qu(a)}

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

      ${Vu(a)}

      `)}return i+="
      ",`
      @@ -78,14 +78,14 @@ in vec2 p; void main(){ gl_Position = vec4(p, 0.0, 1.0); }`;function a(){return[
      ${i}
      - `}const Ey=[[/gradient stroke\s*$/i," and an animated percentage label"],[/gauge\s*$/i," with a gradient stroke and animated fill"],[/rating\s*(bar|widget)?\s*$/i," with half-star support and haptic feedback"],[/list\s*$/i," with swipe-to-delete and an undo snackbar"],[/pad\s*$/i," that exports a transparent PNG"],[/carousel\s*$/i," with parallax cards and page indicators"],[/(button|cta)\s*$/i," with a loading spinner and success state"],[/(chart|graph)\s*$/i," that animates from a Firestore stream"],[/action\s*(that|to)?\s*$/i," uploads an image to Firebase Storage and returns the URL"],[/timer\s*$/i," with pause, resume and a completion callback"],[/map\s*$/i," with clustered markers and a custom info window"],[/^a\s+\w*$/i," widget that"],[/(picker|selector)\s*$/i," with search and multi-select"]],Sy=220,xy=6;function Vu(t,e){return!!(t&&t.trim())&&!e}function Iy(t,e=""){if(typeof t!="string"||!t||t===e||t.trim().lengthi.test(t));return n?n[1]:null}function ky(){let t="",e="";return{get active(){return t},resolve(n){return t=Iy(n,e)??"",t},dismiss(){t=""},accept(n){if(!t)return null;const i=n+t;return e=i,t="",i}}}function Cy({onSubmit:t}){const e=document.getElementById("composer"),n=document.getElementById("pipeline-input"),i=document.getElementById("hero-send");if(!e||!n||!i||typeof t!="function")return;const r=e.querySelector(".ghost .typed"),s=e.querySelector(".ghost .suggest"),o=document.getElementById("tab-hint"),a=document.getElementById("suggest-status"),l=Array.from(document.querySelectorAll("#example-chips .chip")),u=document.getElementById("btn-add-images"),c=document.getElementById("prompt-image-input"),d=window.matchMedia("(prefers-reduced-motion: reduce)"),f=ky();let h=!1,p=!1,g=!1,m=!1,v=null,E=null;function S(){i.disabled=!Vu(n.value,p||g||m)}function _(){r&&(r.textContent=n.value)}function b(){s&&(s.textContent=""),_(),e.classList.remove("has-suggest"),o&&(o.hidden=!0,o.tabIndex=-1),a&&(a.textContent="")}function k(R){s&&(s.textContent=R),_(),e.classList.add("has-suggest"),o&&(o.hidden=!1,o.tabIndex=0,o.setAttribute("aria-label","Accept suggestion: "+R.trim())),a&&(a.textContent="Suggestion: "+R+". Press Tab to accept.")}function T(){f.dismiss(),b()}function x(){if(h||p)return;const R=f.resolve(n.value);R&&k(R)}function F(){clearTimeout(v),!h&&(v=setTimeout(x,Sy))}function $(){const R=f.accept(n.value);return R===null?!1:(n.value=R,b(),S(),!0)}function O(R){p=R,e.classList.toggle("is-busy",R),i.classList.toggle("is-busy",R),i.setAttribute("aria-label",R?"Generating":"Generate"),n.readOnly=R,l.forEach(Z=>{Z.disabled=R}),u&&(u.disabled=R),c&&(c.disabled=R),S()}async function L(){if(Vu(n.value,p||g||m)){T(),O(!0);try{await t()}finally{O(!1)}}}function N(){g=!1,E&&(clearInterval(E),E=null),e.classList.remove("is-demo-typing"),S()}function K(){l.forEach(R=>{R.classList.remove("is-active"),R.setAttribute("aria-pressed","false")})}function V(){try{n.focus({preventScroll:!0}),n.setSelectionRange(n.value.length,n.value.length)}catch{}}function M(R){const Z=R.dataset.prompt||"";if(N(),clearTimeout(v),v=null,T(),l.forEach(oe=>{const ye=oe===R;oe.classList.toggle("is-active",ye),oe.setAttribute("aria-pressed",String(ye))}),d.matches||!Z){n.value=Z,_(),S(),V();return}n.value="",_(),g=!0,S(),e.classList.add("is-demo-typing");let Ce=0;E=setInterval(()=>{Ce+=1,n.value=Z.slice(0,Ce),_(),Ce>=Z.length?(N(),V()):S()},22)}return l.forEach(R=>{R.setAttribute("aria-pressed","false"),R.addEventListener("click",()=>M(R))}),n.addEventListener("keydown",R=>{if(g&&R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!h){R.preventDefault();return}N(),R.key==="Tab"&&!R.shiftKey&&f.active?(R.preventDefault(),$()):R.key==="Escape"?(clearTimeout(v),v=null,T()):R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!h&&(R.preventDefault(),L())}),n.addEventListener("input",()=>{N(),K(),T(),S(),F()}),n.addEventListener("compositionstart",()=>{h=!0}),n.addEventListener("compositionend",()=>{h=!1,T(),S(),F()}),n.addEventListener("scroll",()=>{r&&r.parentNode&&(r.parentNode.scrollTop=n.scrollTop)}),o&&o.addEventListener("click",()=>{$(),n.focus({preventScroll:!0})}),i.addEventListener("click",L),n.addEventListener("pointerdown",()=>{N(),K()}),_(),S(),{setAttachmentsPending(R){m=!!R,S()}}}const Ay="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses";const _t="https://4tgke4.buildship.run",kh={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},hs="ccc_auth_session",Oa="ccc_signin_return",Py=1800*1e3,Gu=new WeakSet;let q={email:null,sessionToken:null,isVerified:!1};function Mn(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let ce=Mn({isResolved:!0}),Ba=Promise.resolve();const Fy=`${_t}/service/runpipeline`,Ry="bs_user_id",Ty="bs_identity_token",$y=`${_t}/authUserCheck`;let ht={userId:null,token:null,status:null,resolved:!1};const ps=cv,gs="ccc_subscription",Ku=3,My=new Set(["active","trialing","paid"]),ms="google/gemini-3.7-flash",Nr=["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"],Ly={"google/gemini-3.7-flash":"Gemini 3.7 Flash","anthropic/claude-opus-5":"Claude Opus 5","openai/gpt-5.6-sol":"GPT-5.6 Sol","z-ai/glm-5.2":"GLM 5.2","moonshotai/kimi-k3":"Kimi K3","openrouter/auto-beta":"OpenRouter: Auto Router","openrouter/free":"OpenRouter: Free Models","openrouter/deepseek/deepseek-v4-pro":"DeepSeek v4 Pro"};function Gt(t){return Ly[t]||t}const Ny=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 Ch(t){return Ny.has(t)}const Da=4,Wo=8*1024*1024,Oy="https://4tgke4.buildship.run/service/runpipeline-image";let Oe=[];const pn=[],By=3e4;let Ah=null;function Dy(t){return new Promise(e=>{const n=new FileReader;n.onload=()=>e(n.result),n.onerror=()=>e(null),n.readAsDataURL(t)})}async function jy(t,e){const n=new FormData;return n.append("file",t),(await fetch(Oy,{method:"POST",body:n,signal:e})).json()}function Uy(t){if(Array.isArray(t)){const e=t[0];if(e&&typeof e=="object")for(const n of Object.keys(e)){if(n==="item"||n==="index")continue;const i=e[n];if(i&&typeof i=="object"){if(typeof i.file=="string")return i.file;if(typeof i.url=="string")return i.url}if(typeof i=="string")return i}return""}return typeof t=="string"?t:t&&typeof t=="object"&&(t.url||t.fileUrl||t.file_url||t.downloadUrl||t.imageUrl||t.image_url||t.file)||""}async function Hy(t,e,n){const i=await Dy(t);i&&Oe.includes(e)&&(e.dataUrl=i,cn());let r="";if(i)try{r=Uy(await jy(t,n))}catch{r=""}return Oe.includes(e)?!i||!r?(Oe.splice(Oe.indexOf(e),1),cn(),"failed"):(e.url=r,cn(),"added"):"dropped"}function Ph(t){const e=pn.indexOf(t);e>=0&&pn.splice(e,1),Rh()}function Fh(t){t.controller.abort(),Ph(t);const e=Oe.indexOf(t.slot);e>=0&&(Oe.splice(e,1),cn())}function Rh(){Ah?.setAttachmentsPending(pn.length>0)}async function Wy(t){const e=Array.from(t.target.files||[]);if(!e.length)return;if(t.target.value="",y.isRunning){Ee("Wait for the current generation to finish before attaching images.","info");return}const n=e.filter(u=>u.size>Wo);n.length&&Ee(`Skipped ${n.length} image(s) over the ${(Wo/1024/1024).toFixed(0)} MB limit.`,"warning");const i=e.filter(u=>u.size<=Wo);if(!i.length)return;const r=Da-Oe.length,s=i.slice(0,r);if(i.length>r&&Ee(`You can attach up to ${Da} images.`,"info"),!s.length)return;const o=s.map(u=>{const c={dataUrl:null,name:u.name,url:null};Oe.push(c);const d={slot:c,controller:new AbortController},f=setTimeout(()=>d.controller.abort(),By);return d.job=Hy(u,c,d.controller.signal),pn.push(d),d.job.finally(()=>{clearTimeout(f),Ph(d)}),d.job});cn(),Rh();const l=(await Promise.all(o)).filter(u=>u==="failed").length;l&&Ee(`${l} image(s) could not be uploaded and were not attached.`,"error")}function zy(t){const e=Oe[t],n=pn.find(i=>i.slot===e);if(n){Fh(n);return}Oe.splice(t,1),cn()}function cn(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",Oe.forEach((n,i)=>{const r=document.createElement("div");r.className="prompt-img-thumb"+(n.url?"":" is-pending"),r.innerHTML=(n.dataUrl?`Prompt image`:"")+``,t.appendChild(r)}),e&&(e.textContent=Oe.length>=Da?"Image limit reached":"Add images"))}function Cl(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),n=Ch(e?.value);t.classList.toggle("hidden",!n),!n&&Oe.length&&(pn.slice().forEach(Fh),Oe=[],cn())}const Fn="ccc_usage",Th="google/gemini-3.7-flash",$h="google/gemini-3.7-flash",kr="google/gemini-3.7-flash",Ni={professional:11,power:49},ja={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"},Or={AUD:1,USD:.65,EUR:.6,GBP:.52,CAD:.88,NZD:1.08,JPY:97,KRW:870,INR:54,SGD:.87,HKD:5.08,BRL:3.18,CNY:4.7,TWD:20.5,THB:22.5,VND:16200,IDR:10200,MYR:2.88,SEK:6.8,NOK:6.95,DKK:4.48,PLN:2.6,CZK:15.2,HUF:238,RON:2.98,TRY:20.9,AED:2.39,ILS:2.38,PHP:36.4,ZAR:11.8,RUB:58,UAH:26.8,CHF:.57,MXN:11.1,ARS:580,CLP:610,COP:2700,PEN:2.44};let Br={...Or};async function qy(){const t=new AbortController,e=setTimeout(()=>t.abort(),5e3);try{const n=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:t.signal});if(!n.ok)return;const i=await n.json();if(i.result!=="success"||!i.rates)return;const r=i.rates,s={AUD:1},o=new Set([...Object.keys(Or),...Object.values(Ua),...Object.values(ja)]);for(const a of o)a!=="AUD"&&(typeof r[a]=="number"&&r[a]>0?s[a]=r[a]:Or[a]&&(s[a]=Or[a]));Br=s}catch{}finally{clearTimeout(e)}}const Ua={"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 Al(){try{const s=Intl.DateTimeFormat().resolvedOptions().timeZone;if(s&&Ua[s])return Ua[s]}catch{}const e=(navigator.language||"en-US").replace("-","_"),n=ja[e];if(n)return n;const i=e.split("_")[0],r=ja[i];return r||"USD"}function Oi(t,e){const n=Br[e]??Br.USD,i=t*n,r=Math.round(i*100)/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:r>=100||r%1===0?0:2}).format(r)}catch{return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(t*Br.USD)}}const gt="ccc_api_key_",Pt="ccc_session_api_key_",Rt="ccc_encryption_key",tr="ccc_encryption_key_scope",Vy="ccc_keystore",vs="keys",nr="ccc_encryption_key_version";let Ha=null,_s=null,ir=!1,ys=!1,Yu=!1;class ws extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function Ju(){if(Yu)return;Yu=!0;const t="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(t),document.body&&Ee(t,"warning")}function Mh(){return localStorage.getItem(nr)||""}function Wa(){return crypto.randomUUID?.()||Nh(crypto.getRandomValues(new Uint8Array(16)))}function Gy(){const t=Mh();if(t)return t;const e=Wa();return localStorage.setItem(nr,e),e}function ci(){Ha=null,_s=null,ir=!1,ys=!1}window.addEventListener("storage",t=>{t.key===nr&&ci()});function Ky(){return new Promise((t,e)=>{const n=indexedDB.open(Vy,1);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(vs)||i.createObjectStore(vs)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function Pl(t,e){const n=await Ky();return new Promise((i,r)=>{const s=n.transaction(vs,t);let o;try{o=e(s.objectStore(vs))}catch(l){n.close(),r(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>r(o.error),s.oncomplete=()=>{n.close(),i(a)},s.onerror=()=>{n.close(),r(s.error||new Error("Encryption key transaction failed."))},s.onabort=()=>{n.close(),r(s.error||new Error("Encryption key transaction aborted."))}})}function Yy(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function Jy(){const t=await Pl("readonly",e=>e.get(Rt));return Yy(t)?t:null}async function Lh(t){await Pl("readwrite",e=>e.put(t,Rt))}async function Zy(){ci();try{await Pl("readwrite",t=>t.delete(Rt))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function Xy(){const t=sessionStorage.getItem(Rt);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Lh(e),sessionStorage.removeItem(Rt),sessionStorage.removeItem(tr),localStorage.removeItem(gt+"salt"),e}async function Zu(t){const e=sessionStorage.getItem(Rt);if(e)return ys=sessionStorage.getItem(tr)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new ws;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),i=await crypto.subtle.exportKey("jwk",n);return sessionStorage.setItem(Rt,JSON.stringify(i)),sessionStorage.setItem(tr,"session"),ys=!1,crypto.subtle.importKey("jwk",i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function Qy(t){if(sessionStorage.getItem(tr)==="session"&&sessionStorage.getItem(Rt))return Ju(),ir=!0,Zu(t);try{const e=await Jy();if(e)return e;const n=await Xy();if(n)return n;const i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Lh(i),i}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),Ju(),ir=!0,Zu(t)}}async function Fl(t={}){const{allowSessionFallbackCreation:e=!0}=t,n=Gy();_s!==n&&ci();const i=Ha||Qy(e);Ha=i,_s=n;try{return await i}catch(r){throw ci(),r}}async function e0(t){const e=await Fl(),n=_s,i=new TextEncoder,r=crypto.getRandomValues(new Uint8Array(12)),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},e,i.encode(t)),o=new Uint8Array(r.length+s.byteLength);return o.set(r),o.set(new Uint8Array(s),r.length),{ciphertext:Nh(o),keyVersion:n,sessionFallback:ir}}async function t0(t,e={}){const{isSessionCredential:n=!1}=e;try{const i=await Fl({allowSessionFallbackCreation:!1});if(ir&&!n&&!ys)throw new ws;const r=n0(t),s=r.slice(0,12),o=r.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},i,o);return new TextDecoder().decode(a)}catch(i){if(i instanceof ws)throw i;return console.error("Decryption failed:",i),null}}function Nh(t){const e=new Uint8Array(t);let n="";for(let i=0;i0}let Ln="",ui="",zi=null,Qu=0,nt="not-configured";async function Rl(){sessionStorage.getItem(Rt)&&await Fl(),Ln=await Te("flutterflow"),ui=await Te("flutterflow_project_id"),u0(),rn(),Ln?Ll():(nt="not-configured",vt())}let rr=!1;function Oh(){const t=document.getElementById("api-keys-modal");We(t),Ml(),Ln&&Nl(Ln)}function Tl(){rr=!1,Oh()}function r0(){rr=!0;const t=document.getElementById("walkthrough-modal");t&&ze(t),Oh()}let ed=!1;function td(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-settings-model");if(!t||!e)return;e.value=t.value;const n=Array.from(t.options);Array.from(e.options).forEach((r,s)=>{const o=n[s];o&&(r.textContent=o.textContent)});const i=document.getElementById("composer-settings-free-notice");i&&(document.getElementById("model-selector-free-notice")?(i.hidden=!1,i.innerHTML='Free plan — Gemini only. '):i.hidden=!0)}function nd(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-image-capability"),n=document.getElementById("composer-image-capability-note");if(!t)return;const i=Gt(t.value),r=Ch(t.value);e&&(e.textContent=r?"Supported":"Not supported"),n&&(n.textContent=r?`${i} accepts reference images you attach to the prompt.`:`Images can't be attached with ${i}. Attached images are removed when you switch to it.`),Cl()}function s0(){if(rr=!1,td(),nd(),!ed){const e=document.getElementById("composer-settings-model");e&&e.addEventListener("change",()=>{const n=document.getElementById("code-generator-model");n.value=e.value,n.dispatchEvent(new Event("change")),td(),nd()}),ed=!0}const t=document.querySelector('.composer [aria-label="Generation settings"]');We("composer-settings-modal",{trigger:t})}function o0(t){t&&t.target!==t.currentTarget||ze("composer-settings-modal")}function Bh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&ze(e);const n=rr;if(rr=!1,n){const i=document.getElementById("walkthrough-modal");i&&(nt==="connected"&&$l(),We(i))}}let en=1;function Dh(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function Os(){const t=Dh();t.length&&t.forEach((e,n)=>{const i=n+1;e.classList.remove("wt-current","wt-done","wt-pending");const r=e.querySelector(".wt-step-num");i===en?(e.classList.add("wt-current"),r&&(r.textContent=i)):i0&&en<=t&&(en++,Os())}function a0(){const t=document.getElementById("walkthrough-modal");t&&(en=1,Os(),We(t))}function l0(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&ze(e);const n=document.getElementById("walkthrough-dont-show");n&&n.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function jh(){if(q.isVerified&&Tt()&&ce.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(en=1,Os(),We(e))}}async function Ml(){const t=document.getElementById("flutterflow-api-key-input");Ln?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",c0()}function c0(){id("flutterflow","flutterflow-key-status"),id("flutterflow_project_id","flutterflow-project-status")}function id(t,e){const n=document.getElementById(e);if(!n)return;const i=n.querySelector(".key-status-dot"),r=n.querySelector("span");Ct(t)?(i.className="key-status-dot configured",r.className="text-green-600",r.textContent="User key configured"):(i.className="key-status-dot missing",r.className="text-gray-500",r.textContent="Not configured")}function rn(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff");e&&e.classList.toggle("hidden",!t)}function u0(){const t=document.getElementById("api-keys-status");if(!t)return;const e=t.querySelectorAll(".key-status-dot"),n=["flutterflow"];e.forEach((i,r)=>{const s=n[r];s==="flutterflow"?Ct("flutterflow")&&Ct("flutterflow_project_id")?(i.className="key-status-dot configured",i.title="FlutterFlow (Fully configured)"):Ct("flutterflow")||Ct("flutterflow_project_id")?(i.className="key-status-dot env",i.title="FlutterFlow (Partially configured)"):(i.className="key-status-dot missing",i.title="FlutterFlow (Not configured)"):Ct(s)?(i.className="key-status-dot configured",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (User key)"):(i.className="key-status-dot missing",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (Not configured)")}),rn()}async function d0(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select"),n=t.value.trim();n&&await Xu("flutterflow",n);const i=e?.value.trim()||"";if(i){if(!Bs(i)){Ee("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await Xu("flutterflow_project_id",i)}await Rl(),n&&await Ll(),Ml();const r=document.querySelector("#api-keys-modal .bg-blue-500"),s=r.textContent;r.textContent="Saved!",r.classList.remove("bg-blue-500","hover:bg-blue-600"),r.classList.add("bg-green-500"),setTimeout(()=>{r.textContent=s,r.classList.remove("bg-green-500"),r.classList.add("bg-blue-500","hover:bg-blue-600"),Bh()},1e3)}async function f0(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(nr,Wa()),ci(),localStorage.removeItem(gt+"flutterflow"),localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow"),sessionStorage.removeItem(Pt+"flutterflow_project_id"),sessionStorage.removeItem(Rt),sessionStorage.removeItem(tr),localStorage.removeItem(gt+"salt"),await Zy(),localStorage.setItem(nr,Wa()),localStorage.removeItem(gt+"flutterflow"),localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow"),sessionStorage.removeItem(Pt+"flutterflow_project_id"),await Rl();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),Ml()}function Bs(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function vt(){const t=document.getElementById("acct-ff-dot"),e=document.getElementById("acct-ff-status"),n=document.getElementById("acct-ff-endpoint"),i=document.getElementById("acct-ff-project");if(n){const o=yt();n.textContent=o.includes("staging")?"Staging":"Production"}if(i&&(i.textContent=ui||"—"),!e)return;let r,s;if(!Ct("flutterflow"))r="Not connected — add your FlutterFlow API key",s="";else switch(nt){case"connected":r="Connected to FlutterFlow",s="ok";break;case"no-projects":r="Key accepted — no projects found",s="warn";break;case"unauthorized":r="API key rejected (401/403) — re-enter your key",s="bad";break;case"network-error":r="Could not reach FlutterFlow — check your network",s="bad";break;default:r="Checking connection…",s="warn";break}e.textContent=r,t&&(t.className=`acct-dot${s?" "+s:""}`)}async function Ll(){const t=await Te("flutterflow");if(!t||!Ct("flutterflow"))return nt="not-configured",vt(),null;nt="validating",vt();try{const n=await new hi(t,"","main",yt()).listProjects();return nt=n&&n.length>0?"connected":"no-projects",vt(),n}catch(e){const n=String(e&&e.message||"");return nt=/(401|403)|denied|unauthorized|scoped|list permission/i.test(n)?"unauthorized":"network-error",vt(),null}}function h0(){ui="",localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow_project_id")}function p0(){h0();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML='',t.value=""),Ct("flutterflow")?(nt="validating",Nl(Ln)):nt="not-configured",vt()}function g0(t,e){const n=document.getElementById(t);n&&(n.value?e?n.style.borderColor="#22c55e":n.style.borderColor="#ef4444":n.style.borderColor="")}function m0(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const n=e.target.value.trim().length>0;g0("flutterflow-api-key-input",n)}),t.addEventListener("blur",v0(async e=>{const n=e.target.value.trim();n&&await Nl(n)},500)))}function v0(t,e){let n;return function(...r){const s=()=>{clearTimeout(n),t(...r)};clearTimeout(n),n=setTimeout(s,e)}}async function Nl(t){const e=document.getElementById("flutterflow-projects-select"),n=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',n&&n.classList.add("hidden"),(Ct("flutterflow")||t)&&(nt="validating"),vt();try{const r=await new hi(t,"","main",yt()).listProjects();if(!r||r.length===0){nt="no-projects",vt(),e.innerHTML='';return}nt="connected",vt(),e.innerHTML='',r.forEach(s=>{const o=document.createElement("option");o.value=s.id||s.projectId||"",o.textContent=s.name||s.projectName||`Project ${s.id}`,e.appendChild(o)}),ui&&(e.value=ui)}catch(i){console.error("Failed to fetch projects:",i);const r=String(i&&i.message||"");nt=/(401|403)|denied|unauthorized|scoped|list permission/i.test(r)?"unauthorized":"network-error",vt(),e.innerHTML='',n&&(n.textContent=`Failed to load projects: ${i.message}`,n.classList.remove("hidden"))}}function _0(t){const e=document.getElementById(t),i=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",i.innerHTML=` + `}const Sy=[[/gradient stroke\s*$/i," and an animated percentage label"],[/gauge\s*$/i," with a gradient stroke and animated fill"],[/rating\s*(bar|widget)?\s*$/i," with half-star support and haptic feedback"],[/list\s*$/i," with swipe-to-delete and an undo snackbar"],[/pad\s*$/i," that exports a transparent PNG"],[/carousel\s*$/i," with parallax cards and page indicators"],[/(button|cta)\s*$/i," with a loading spinner and success state"],[/(chart|graph)\s*$/i," that animates from a Firestore stream"],[/action\s*(that|to)?\s*$/i," uploads an image to Firebase Storage and returns the URL"],[/timer\s*$/i," with pause, resume and a completion callback"],[/map\s*$/i," with clustered markers and a custom info window"],[/^a\s+\w*$/i," widget that"],[/(picker|selector)\s*$/i," with search and multi-select"]],xy=220,Iy=6;function Gu(t,e){return!!(t&&t.trim())&&!e}function ky(t,e=""){if(typeof t!="string"||!t||t===e||t.trim().lengthi.test(t));return n?n[1]:null}function Cy(){let t="",e="";return{get active(){return t},resolve(n){return t=ky(n,e)??"",t},dismiss(){t=""},accept(n){if(!t)return null;const i=n+t;return e=i,t="",i}}}function Ay({onSubmit:t}){const e=document.getElementById("composer"),n=document.getElementById("pipeline-input"),i=document.getElementById("hero-send");if(!e||!n||!i||typeof t!="function")return;const r=e.querySelector(".ghost .typed"),s=e.querySelector(".ghost .suggest"),o=document.getElementById("tab-hint"),a=document.getElementById("suggest-status"),l=Array.from(document.querySelectorAll("#example-chips .chip")),u=document.getElementById("btn-add-images"),c=document.getElementById("prompt-image-input"),d=window.matchMedia("(prefers-reduced-motion: reduce)"),f=Cy();let h=!1,p=!1,g=!1,m=!1,v=null,E=null;function S(){i.disabled=!Gu(n.value,p||g||m)}function _(){r&&(r.textContent=n.value)}function b(){s&&(s.textContent=""),_(),e.classList.remove("has-suggest"),o&&(o.hidden=!0,o.tabIndex=-1),a&&(a.textContent="")}function k(R){s&&(s.textContent=R),_(),e.classList.add("has-suggest"),o&&(o.hidden=!1,o.tabIndex=0,o.setAttribute("aria-label","Accept suggestion: "+R.trim())),a&&(a.textContent="Suggestion: "+R+". Press Tab to accept.")}function T(){f.dismiss(),b()}function x(){if(h||p)return;const R=f.resolve(n.value);R&&k(R)}function F(){clearTimeout(v),!h&&(v=setTimeout(x,xy))}function $(){const R=f.accept(n.value);return R===null?!1:(n.value=R,b(),S(),!0)}function O(R){p=R,e.classList.toggle("is-busy",R),i.classList.toggle("is-busy",R),i.setAttribute("aria-label",R?"Generating":"Generate"),n.readOnly=R,l.forEach(Z=>{Z.disabled=R}),u&&(u.disabled=R),c&&(c.disabled=R),S()}async function L(){if(Gu(n.value,p||g||m)){T(),O(!0);try{await t()}finally{O(!1)}}}function N(){g=!1,E&&(clearInterval(E),E=null),e.classList.remove("is-demo-typing"),S()}function K(){l.forEach(R=>{R.classList.remove("is-active"),R.setAttribute("aria-pressed","false")})}function V(){try{n.focus({preventScroll:!0}),n.setSelectionRange(n.value.length,n.value.length)}catch{}}function M(R){const Z=R.dataset.prompt||"";if(N(),clearTimeout(v),v=null,T(),l.forEach(oe=>{const ye=oe===R;oe.classList.toggle("is-active",ye),oe.setAttribute("aria-pressed",String(ye))}),d.matches||!Z){n.value=Z,_(),S(),V();return}n.value="",_(),g=!0,S(),e.classList.add("is-demo-typing");let Ce=0;E=setInterval(()=>{Ce+=1,n.value=Z.slice(0,Ce),_(),Ce>=Z.length?(N(),V()):S()},22)}return l.forEach(R=>{R.setAttribute("aria-pressed","false"),R.addEventListener("click",()=>M(R))}),n.addEventListener("keydown",R=>{if(g&&R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!h){R.preventDefault();return}N(),R.key==="Tab"&&!R.shiftKey&&f.active?(R.preventDefault(),$()):R.key==="Escape"?(clearTimeout(v),v=null,T()):R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!h&&(R.preventDefault(),L())}),n.addEventListener("input",()=>{N(),K(),T(),S(),F()}),n.addEventListener("compositionstart",()=>{h=!0}),n.addEventListener("compositionend",()=>{h=!1,T(),S(),F()}),n.addEventListener("scroll",()=>{r&&r.parentNode&&(r.parentNode.scrollTop=n.scrollTop)}),o&&o.addEventListener("click",()=>{$(),n.focus({preventScroll:!0})}),i.addEventListener("click",L),n.addEventListener("pointerdown",()=>{N(),K()}),_(),S(),{setAttachmentsPending(R){m=!!R,S()}}}const Py="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses";const _t="https://4tgke4.buildship.run",Ah={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},hs="ccc_auth_session",Na="ccc_signin_return",Fy=1800*1e3,Ku=new WeakSet;let q={email:null,sessionToken:null,isVerified:!1};function Mn(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let ce=Mn({isResolved:!0}),Oa=Promise.resolve();const Ry=`${_t}/service/runpipeline`,Ty="bs_user_id",$y="bs_identity_token",My=`${_t}/authUserCheck`;let ht={userId:null,token:null,status:null,resolved:!1};const ps=dv,gs="ccc_subscription",Yu=3,Ly=new Set(["active","trialing","paid"]),ms="google/gemini-3.7-flash",Nr=["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"],Ny={"google/gemini-3.7-flash":"Gemini 3.7 Flash","anthropic/claude-opus-5":"Claude Opus 5","openai/gpt-5.6-sol":"GPT-5.6 Sol","z-ai/glm-5.2":"GLM 5.2","moonshotai/kimi-k3":"Kimi K3","openrouter/auto-beta":"OpenRouter: Auto Router","openrouter/free":"OpenRouter: Free Models","openrouter/deepseek/deepseek-v4-pro":"DeepSeek v4 Pro"};function Gt(t){return Ny[t]||t}const Oy=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 Ph(t){return Oy.has(t)}const Ba=4,Ho=8*1024*1024,By="https://4tgke4.buildship.run/service/runpipeline-image";let Oe=[];const pn=[],Dy=3e4;let Fh=null;function jy(t){return new Promise(e=>{const n=new FileReader;n.onload=()=>e(n.result),n.onerror=()=>e(null),n.readAsDataURL(t)})}async function Uy(t,e){const n=new FormData;return n.append("file",t),(await fetch(By,{method:"POST",body:n,signal:e})).json()}function Hy(t){if(Array.isArray(t)){const e=t[0];if(e&&typeof e=="object")for(const n of Object.keys(e)){if(n==="item"||n==="index")continue;const i=e[n];if(i&&typeof i=="object"){if(typeof i.file=="string")return i.file;if(typeof i.url=="string")return i.url}if(typeof i=="string")return i}return""}return typeof t=="string"?t:t&&typeof t=="object"&&(t.url||t.fileUrl||t.file_url||t.downloadUrl||t.imageUrl||t.image_url||t.file)||""}async function Wy(t,e,n){const i=await jy(t);i&&Oe.includes(e)&&(e.dataUrl=i,cn());let r="";if(i)try{r=Hy(await Uy(t,n))}catch{r=""}return Oe.includes(e)?!i||!r?(Oe.splice(Oe.indexOf(e),1),cn(),"failed"):(e.url=r,cn(),"added"):"dropped"}function Rh(t){const e=pn.indexOf(t);e>=0&&pn.splice(e,1),$h()}function Th(t){t.controller.abort(),Rh(t);const e=Oe.indexOf(t.slot);e>=0&&(Oe.splice(e,1),cn())}function $h(){Fh?.setAttachmentsPending(pn.length>0)}async function zy(t){const e=Array.from(t.target.files||[]);if(!e.length)return;if(t.target.value="",y.isRunning){Ee("Wait for the current generation to finish before attaching images.","info");return}const n=e.filter(u=>u.size>Ho);n.length&&Ee(`Skipped ${n.length} image(s) over the ${(Ho/1024/1024).toFixed(0)} MB limit.`,"warning");const i=e.filter(u=>u.size<=Ho);if(!i.length)return;const r=Ba-Oe.length,s=i.slice(0,r);if(i.length>r&&Ee(`You can attach up to ${Ba} images.`,"info"),!s.length)return;const o=s.map(u=>{const c={dataUrl:null,name:u.name,url:null};Oe.push(c);const d={slot:c,controller:new AbortController},f=setTimeout(()=>d.controller.abort(),Dy);return d.job=Wy(u,c,d.controller.signal),pn.push(d),d.job.finally(()=>{clearTimeout(f),Rh(d)}),d.job});cn(),$h();const l=(await Promise.all(o)).filter(u=>u==="failed").length;l&&Ee(`${l} image(s) could not be uploaded and were not attached.`,"error")}function qy(t){const e=Oe[t],n=pn.find(i=>i.slot===e);if(n){Th(n);return}Oe.splice(t,1),cn()}function cn(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",Oe.forEach((n,i)=>{const r=document.createElement("div");r.className="prompt-img-thumb"+(n.url?"":" is-pending"),r.innerHTML=(n.dataUrl?`Prompt image`:"")+``,t.appendChild(r)}),e&&(e.textContent=Oe.length>=Ba?"Image limit reached":"Add images"))}function Cl(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),n=Ph(e?.value);t.classList.toggle("hidden",!n),!n&&Oe.length&&(pn.slice().forEach(Th),Oe=[],cn())}const Fn="ccc_usage",Mh="google/gemini-3.7-flash",Lh="google/gemini-3.7-flash",kr="google/gemini-3.7-flash",Ni={professional:11,power:49},Da={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"},Or={AUD:1,USD:.65,EUR:.6,GBP:.52,CAD:.88,NZD:1.08,JPY:97,KRW:870,INR:54,SGD:.87,HKD:5.08,BRL:3.18,CNY:4.7,TWD:20.5,THB:22.5,VND:16200,IDR:10200,MYR:2.88,SEK:6.8,NOK:6.95,DKK:4.48,PLN:2.6,CZK:15.2,HUF:238,RON:2.98,TRY:20.9,AED:2.39,ILS:2.38,PHP:36.4,ZAR:11.8,RUB:58,UAH:26.8,CHF:.57,MXN:11.1,ARS:580,CLP:610,COP:2700,PEN:2.44};let Br={...Or};async function Vy(){const t=new AbortController,e=setTimeout(()=>t.abort(),5e3);try{const n=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:t.signal});if(!n.ok)return;const i=await n.json();if(i.result!=="success"||!i.rates)return;const r=i.rates,s={AUD:1},o=new Set([...Object.keys(Or),...Object.values(ja),...Object.values(Da)]);for(const a of o)a!=="AUD"&&(typeof r[a]=="number"&&r[a]>0?s[a]=r[a]:Or[a]&&(s[a]=Or[a]));Br=s}catch{}finally{clearTimeout(e)}}const ja={"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 Al(){try{const s=Intl.DateTimeFormat().resolvedOptions().timeZone;if(s&&ja[s])return ja[s]}catch{}const e=(navigator.language||"en-US").replace("-","_"),n=Da[e];if(n)return n;const i=e.split("_")[0],r=Da[i];return r||"USD"}function Oi(t,e){const n=Br[e]??Br.USD,i=t*n,r=Math.round(i*100)/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:r>=100||r%1===0?0:2}).format(r)}catch{return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(t*Br.USD)}}const gt="ccc_api_key_",Pt="ccc_session_api_key_",Rt="ccc_encryption_key",tr="ccc_encryption_key_scope",Gy="ccc_keystore",vs="keys",nr="ccc_encryption_key_version";let Ua=null,_s=null,ir=!1,ys=!1,Ju=!1;class ws extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function Zu(){if(Ju)return;Ju=!0;const t="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(t),document.body&&Ee(t,"warning")}function Nh(){return localStorage.getItem(nr)||""}function Ha(){return crypto.randomUUID?.()||Bh(crypto.getRandomValues(new Uint8Array(16)))}function Ky(){const t=Nh();if(t)return t;const e=Ha();return localStorage.setItem(nr,e),e}function ci(){Ua=null,_s=null,ir=!1,ys=!1}window.addEventListener("storage",t=>{t.key===nr&&ci()});function Yy(){return new Promise((t,e)=>{const n=indexedDB.open(Gy,1);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(vs)||i.createObjectStore(vs)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function Pl(t,e){const n=await Yy();return new Promise((i,r)=>{const s=n.transaction(vs,t);let o;try{o=e(s.objectStore(vs))}catch(l){n.close(),r(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>r(o.error),s.oncomplete=()=>{n.close(),i(a)},s.onerror=()=>{n.close(),r(s.error||new Error("Encryption key transaction failed."))},s.onabort=()=>{n.close(),r(s.error||new Error("Encryption key transaction aborted."))}})}function Jy(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function Zy(){const t=await Pl("readonly",e=>e.get(Rt));return Jy(t)?t:null}async function Oh(t){await Pl("readwrite",e=>e.put(t,Rt))}async function Xy(){ci();try{await Pl("readwrite",t=>t.delete(Rt))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function Qy(){const t=sessionStorage.getItem(Rt);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Oh(e),sessionStorage.removeItem(Rt),sessionStorage.removeItem(tr),localStorage.removeItem(gt+"salt"),e}async function Xu(t){const e=sessionStorage.getItem(Rt);if(e)return ys=sessionStorage.getItem(tr)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new ws;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),i=await crypto.subtle.exportKey("jwk",n);return sessionStorage.setItem(Rt,JSON.stringify(i)),sessionStorage.setItem(tr,"session"),ys=!1,crypto.subtle.importKey("jwk",i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function e0(t){if(sessionStorage.getItem(tr)==="session"&&sessionStorage.getItem(Rt))return Zu(),ir=!0,Xu(t);try{const e=await Zy();if(e)return e;const n=await Qy();if(n)return n;const i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Oh(i),i}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),Zu(),ir=!0,Xu(t)}}async function Fl(t={}){const{allowSessionFallbackCreation:e=!0}=t,n=Ky();_s!==n&&ci();const i=Ua||e0(e);Ua=i,_s=n;try{return await i}catch(r){throw ci(),r}}async function t0(t){const e=await Fl(),n=_s,i=new TextEncoder,r=crypto.getRandomValues(new Uint8Array(12)),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},e,i.encode(t)),o=new Uint8Array(r.length+s.byteLength);return o.set(r),o.set(new Uint8Array(s),r.length),{ciphertext:Bh(o),keyVersion:n,sessionFallback:ir}}async function n0(t,e={}){const{isSessionCredential:n=!1}=e;try{const i=await Fl({allowSessionFallbackCreation:!1});if(ir&&!n&&!ys)throw new ws;const r=i0(t),s=r.slice(0,12),o=r.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},i,o);return new TextDecoder().decode(a)}catch(i){if(i instanceof ws)throw i;return console.error("Decryption failed:",i),null}}function Bh(t){const e=new Uint8Array(t);let n="";for(let i=0;i0}let Ln="",ui="",zi=null,ed=0,nt="not-configured";async function Rl(){sessionStorage.getItem(Rt)&&await Fl(),Ln=await Te("flutterflow"),ui=await Te("flutterflow_project_id"),d0(),rn(),Ln?Ll():(nt="not-configured",vt())}let rr=!1;function Dh(){const t=document.getElementById("api-keys-modal");We(t),Ml(),Ln&&Nl(Ln)}function Tl(){rr=!1,Dh()}function s0(){rr=!0;const t=document.getElementById("walkthrough-modal");t&&ze(t),Dh()}let td=!1;function nd(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-settings-model");if(!t||!e)return;e.value=t.value;const n=Array.from(t.options);Array.from(e.options).forEach((r,s)=>{const o=n[s];o&&(r.textContent=o.textContent)});const i=document.getElementById("composer-settings-free-notice");i&&(document.getElementById("model-selector-free-notice")?(i.hidden=!1,i.innerHTML='Free plan — Gemini only. '):i.hidden=!0)}function id(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-image-capability"),n=document.getElementById("composer-image-capability-note");if(!t)return;const i=Gt(t.value),r=Ph(t.value);e&&(e.textContent=r?"Supported":"Not supported"),n&&(n.textContent=r?`${i} accepts reference images you attach to the prompt.`:`Images can't be attached with ${i}. Attached images are removed when you switch to it.`),Cl()}function o0(){if(rr=!1,nd(),id(),!td){const e=document.getElementById("composer-settings-model");e&&e.addEventListener("change",()=>{const n=document.getElementById("code-generator-model");n.value=e.value,n.dispatchEvent(new Event("change")),nd(),id()}),td=!0}const t=document.querySelector('.composer [aria-label="Generation settings"]');We("composer-settings-modal",{trigger:t})}function a0(t){t&&t.target!==t.currentTarget||ze("composer-settings-modal")}function jh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&ze(e);const n=rr;if(rr=!1,n){const i=document.getElementById("walkthrough-modal");i&&(nt==="connected"&&$l(),We(i))}}let en=1;function Uh(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function Ns(){const t=Uh();t.length&&t.forEach((e,n)=>{const i=n+1;e.classList.remove("wt-current","wt-done","wt-pending");const r=e.querySelector(".wt-step-num");i===en?(e.classList.add("wt-current"),r&&(r.textContent=i)):i0&&en<=t&&(en++,Ns())}function l0(){const t=document.getElementById("walkthrough-modal");t&&(en=1,Ns(),We(t))}function c0(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&ze(e);const n=document.getElementById("walkthrough-dont-show");n&&n.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function Hh(){if(q.isVerified&&Tt()&&ce.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(en=1,Ns(),We(e))}}async function Ml(){const t=document.getElementById("flutterflow-api-key-input");Ln?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",u0()}function u0(){rd("flutterflow","flutterflow-key-status"),rd("flutterflow_project_id","flutterflow-project-status")}function rd(t,e){const n=document.getElementById(e);if(!n)return;const i=n.querySelector(".key-status-dot"),r=n.querySelector("span");Ct(t)?(i.className="key-status-dot configured",r.className="text-green-600",r.textContent="User key configured"):(i.className="key-status-dot missing",r.className="text-gray-500",r.textContent="Not configured")}function rn(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff");e&&e.classList.toggle("hidden",!t)}function d0(){const t=document.getElementById("api-keys-status");if(!t)return;const e=t.querySelectorAll(".key-status-dot"),n=["flutterflow"];e.forEach((i,r)=>{const s=n[r];s==="flutterflow"?Ct("flutterflow")&&Ct("flutterflow_project_id")?(i.className="key-status-dot configured",i.title="FlutterFlow (Fully configured)"):Ct("flutterflow")||Ct("flutterflow_project_id")?(i.className="key-status-dot env",i.title="FlutterFlow (Partially configured)"):(i.className="key-status-dot missing",i.title="FlutterFlow (Not configured)"):Ct(s)?(i.className="key-status-dot configured",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (User key)"):(i.className="key-status-dot missing",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (Not configured)")}),rn()}async function f0(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select"),n=t.value.trim();n&&await Qu("flutterflow",n);const i=e?.value.trim()||"";if(i){if(!Os(i)){Ee("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await Qu("flutterflow_project_id",i)}await Rl(),n&&await Ll(),Ml();const r=document.querySelector("#api-keys-modal .bg-blue-500"),s=r.textContent;r.textContent="Saved!",r.classList.remove("bg-blue-500","hover:bg-blue-600"),r.classList.add("bg-green-500"),setTimeout(()=>{r.textContent=s,r.classList.remove("bg-green-500"),r.classList.add("bg-blue-500","hover:bg-blue-600"),jh()},1e3)}async function h0(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(nr,Ha()),ci(),localStorage.removeItem(gt+"flutterflow"),localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow"),sessionStorage.removeItem(Pt+"flutterflow_project_id"),sessionStorage.removeItem(Rt),sessionStorage.removeItem(tr),localStorage.removeItem(gt+"salt"),await Xy(),localStorage.setItem(nr,Ha()),localStorage.removeItem(gt+"flutterflow"),localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow"),sessionStorage.removeItem(Pt+"flutterflow_project_id"),await Rl();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),Ml()}function Os(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function vt(){const t=document.getElementById("acct-ff-dot"),e=document.getElementById("acct-ff-status"),n=document.getElementById("acct-ff-endpoint"),i=document.getElementById("acct-ff-project");if(n){const o=yt();n.textContent=o.includes("staging")?"Staging":"Production"}if(i&&(i.textContent=ui||"—"),!e)return;let r,s;if(!Ct("flutterflow"))r="Not connected — add your FlutterFlow API key",s="";else switch(nt){case"connected":r="Connected to FlutterFlow",s="ok";break;case"no-projects":r="Key accepted — no projects found",s="warn";break;case"unauthorized":r="API key rejected (401/403) — re-enter your key",s="bad";break;case"network-error":r="Could not reach FlutterFlow — check your network",s="bad";break;default:r="Checking connection…",s="warn";break}e.textContent=r,t&&(t.className=`acct-dot${s?" "+s:""}`)}async function Ll(){const t=await Te("flutterflow");if(!t||!Ct("flutterflow"))return nt="not-configured",vt(),null;nt="validating",vt();try{const n=await new hi(t,"","main",yt()).listProjects();return nt=n&&n.length>0?"connected":"no-projects",vt(),n}catch(e){const n=String(e&&e.message||"");return nt=/(401|403)|denied|unauthorized|scoped|list permission/i.test(n)?"unauthorized":"network-error",vt(),null}}function p0(){ui="",localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow_project_id")}function g0(){p0();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML='',t.value=""),Ct("flutterflow")?(nt="validating",Nl(Ln)):nt="not-configured",vt()}function m0(t,e){const n=document.getElementById(t);n&&(n.value?e?n.style.borderColor="#22c55e":n.style.borderColor="#ef4444":n.style.borderColor="")}function v0(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const n=e.target.value.trim().length>0;m0("flutterflow-api-key-input",n)}),t.addEventListener("blur",_0(async e=>{const n=e.target.value.trim();n&&await Nl(n)},500)))}function _0(t,e){let n;return function(...r){const s=()=>{clearTimeout(n),t(...r)};clearTimeout(n),n=setTimeout(s,e)}}async function Nl(t){const e=document.getElementById("flutterflow-projects-select"),n=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',n&&n.classList.add("hidden"),(Ct("flutterflow")||t)&&(nt="validating"),vt();try{const r=await new hi(t,"","main",yt()).listProjects();if(!r||r.length===0){nt="no-projects",vt(),e.innerHTML='';return}nt="connected",vt(),e.innerHTML='',r.forEach(s=>{const o=document.createElement("option");o.value=s.id||s.projectId||"",o.textContent=s.name||s.projectName||`Project ${s.id}`,e.appendChild(o)}),ui&&(e.value=ui)}catch(i){console.error("Failed to fetch projects:",i);const r=String(i&&i.message||"");nt=/(401|403)|denied|unauthorized|scoped|list permission/i.test(r)?"unauthorized":"network-error",vt(),e.innerHTML='',n&&(n.textContent=`Failed to load projects: ${i.message}`,n.classList.remove("hidden"))}}function y0(t){const e=document.getElementById(t),i=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",i.innerHTML=` `):(e.type="password",i.innerHTML=` - `)}let y={step1Result:null,step2Result:null,step3Result:null,bundleSpec:null,artifactBundle:null,bundleReview:null,selectedArtifactId:null,resultsViewMode:"summary",currentStep:0,isRunning:!1,runId:0,submittedPrompt:"",submittedImages:[]};function y0(){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 w0(){y.bundleSpec=Qi(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function Ds(){const t=oi(y.bundleSpec);y.artifactBundle=Qi(y.step2Result,{id:y.bundleSpec?.id,title:y.bundleSpec?.title,description:y.bundleSpec?.description,artifactType:t.artifactType,artifactName:t.artifactName,fileName:t.fileName,dependencies:t.dependencies,relationships:y.bundleSpec?.relationships,code:y.step2Result||""});const e=zv(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(n=>n.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=oi(y.artifactBundle).id}function js(){const t=Qi(y.step3Result,{id:y.artifactBundle?.id,title:y.artifactBundle?.title}),e=new Map(t.artifacts.map(i=>[i.id,i.review])),n=new Map(t.artifacts.filter(i=>{const r=i.review;return r&&typeof r.fixedSource=="string"&&r.fixedSource.trim()}).map(i=>[i.id,i.review.fixedSource.trim()]));y.bundleReview=Qi({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(i=>{const r=n.get(i.id)||null;return{...i,review:e.get(i.id)||i.review||y.step3Result||null,...r?{fixedCode:r}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function Uh(){const t=Ol();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function Ol(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(n=>n.id===y.selectedArtifactId)||oi(t)}function Bl(){return Ol().code||y.step2Result||""}async function b0(){try{await Rl()}catch(t){return console.error("checkConnection: initializeApiKeys failed:",t),!1}return!0}const Dr={production:"https://api.flutterflow.io/v2/",staging:"https://api.flutterflow.io/v2-staging/"};function E0(t,e){const n=e?.trim()?` (${e.trim().slice(0,200)})`:"";return t===401?`Your FlutterFlow API key was rejected (401 Unauthorized)${n}. Re-enter a current key under API Keys settings, then try again.`:`Listing FlutterFlow projects was denied (403)${n}. The key may be scoped to sync a single project without list permission - verify the key's access in FlutterFlow, re-enter it under API Keys settings, then retry.`}class hi{constructor(e,n,i="main",r=Dr.production){this.apiKey=e,this.baseUrl=r,this._projectId=n,this._branchName=i,this._endpoint=r}get projectId(){return this._projectId}get branchName(){return this._branchName==="main"?"":this._branchName}async exportProjectZip(){console.log(`Exporting code from FlutterFlow project: ${this.projectId}, branch: ${this.branchName||"main"}`);const e=[{project:{path:`projects/${this.projectId}`},...this.branchName?{branch_name:this.branchName}:{},export_as_module:!1,include_assets_map:!1,format:!1,export_as_debug:!1},{project_id:this.projectId,branch_name:this.branchName,include_assets:!1,export_as_module:!1}];let n=null;for(const i of e)try{const r=await fetch(`${this.baseUrl}exportCode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(i)});if(!r.ok){const a=await r.text();n=new Error(`Export failed: ${r.status} - ${a}`);continue}const s=await r.json(),o=s?.value?.project_zip||s?.project_zip;if(!o){n=new Error("Export response did not include project source.");continue}return o}catch(r){n=r}throw n||new Error("Export failed for an unknown reason.")}async fetchProjectSource(){const e=await this.exportProjectZip(),n=await JSZip.loadAsync(e,{base64:!0}),i=Object.keys(n.files).filter(a=>!n.files[a].dir&&(a==="pubspec.yaml"||a.endsWith("/pubspec.yaml"))).sort((a,l)=>a.split("/").length-l.split("/").length)[0];if(!i)throw new Error("Export did not contain a pubspec.yaml.");const r=i.slice(0,i.length-12),s=new Map,o=Object.keys(n.files).filter(a=>{if(n.files[a].dir||!a.startsWith(r))return!1;const l=a.slice(r.length);return l==="lib/flutter_flow/custom_functions.dart"||l.startsWith("lib/custom_code/")&&l.endsWith(".dart")});return await Promise.all(o.map(async a=>{s.set(a.slice(r.length),await n.files[a].async("string"))})),{pubspecYaml:await n.files[i].async("string"),files:s}}async pushCodeWithRetry(e,n=3,i=null){const r=[Dr.production,Dr.staging],s=Math.max(0,r.indexOf(this._endpoint));let o=!1,a=null;for(let l=0;lsetTimeout(h,1e3*(l+1)));continue}if(d.ok)return console.log(`Push to ${c} succeeded!`),d;if(a=d.status,d.clone().text().then(f=>console.log(`Push to ${c} returned ${d.status}: ${f}`),()=>console.log(`Push to ${c} returned ${d.status} (unreadable response body)`)),d.status>=500&&(o=!0),d.status===500){console.warn(`Endpoint ${c} returned 500, trying next...`),await new Promise(f=>setTimeout(f,1e3*(l+1)));continue}if(d.status>=500)throw new Qe(`FlutterFlow reported a server error (HTTP ${d.status}), which cannot prove the push was refused — the write may have been applied before the failure. Open your FlutterFlow project to reconcile before retrying.`);if(o)throw new Qe(`The push was refused (HTTP ${d.status}), but an earlier sync attempt may already have applied it — server errors and dropped responses cannot prove a refusal. Open your FlutterFlow project to reconcile before retrying.`);return d}throw Uu({httpStatus:a})}async pushCode(e,n=null){return this.pushCodeWithRetry(e,3,n)}parseProjectsResponse(e){if(e?.success&&typeof e.value=="string")try{const i=JSON.parse(e.value);if(i&&Array.isArray(i.entries))return i.entries.map(r=>({id:r.id,name:r.project?.name||r.id}))}catch(i){console.error("Failed to parse stringified project value:",i)}const n=e?.projects||e?.items||e?.entries||(Array.isArray(e)?e:[]);return Array.isArray(n)?n:[]}async listProjects(){console.log("Listing projects for API key");const e=[`${this.baseUrl}listProjects`,"https://api.flutterflow.io/v2/l/listProjects"];let n=0,i="";for(const r of e){const s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({project_type:"ALL",deserialize_response:!0})});if(s.ok)return r!==e[0]&&console.log(`listProjects answered on legacy path ${r}`),this.parseProjectsResponse(await s.json());if(n=s.status,i=await s.text(),console.warn(`listProjects via ${r} returned ${n}: ${i}`),s.status===401||s.status===403)throw new Error(E0(s.status,i));if(s.status!==404)throw new Error(`List projects failed: ${s.status} - ${i}`)}throw new Error(`List projects failed: ${n} - ${i}`)}}async function S0(t,e=X_){const n=t.clone();let i;try{i=await bs(t.json(),e,(s,o)=>o(new Error("The push response body stalled before it finished.")))}catch{let o="";try{o=await bs(n.text(),e,(a,l)=>l(new Error("stalled")))}catch{}if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:o||`HTTP ${t.status}`,errorMap:new Map};throw new Qe(`FlutterFlow accepted the sync but returned an unreadable response${o?`: ${o.slice(0,200)}`:"."}`)}if(!t.ok){let s=i.message||`HTTP ${t.status}`,o=new Map;if(i.errors)o=new Map(Object.entries(i.errors));else if(!i.message&&typeof i=="object"){const a=Object.keys(i).filter(l=>l.endsWith(".dart")&&Array.isArray(i[l]));a.length>0&&(o=new Map(Object.entries(i)),s=a.flatMap(u=>i[u].map(c=>`${u}: ${c.errorMessage}`)).join(` -`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:s,errorMap:o}}let r={};if(i.value)try{r=typeof i.value=="string"?JSON.parse(i.value):i.value}catch(s){console.warn("Ignoring malformed push response value:",s)}return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(r))}}function Dl(t,e){return{401:"Authentication failed. Please check your FlutterFlow API key.",403:"Access denied. You may not have permission to modify this project.",404:"Project not found. Please check your Project ID.",409:"Conflict detected. The project may have been modified elsewhere.",422:"Validation failed: Invalid request format",429:"Rate limit exceeded. Please try again in a few minutes.",500:"FlutterFlow server error. Please try again later.",503:"FlutterFlow service temporarily unavailable."}[t]||`FlutterFlow API error: ${`HTTP ${t}`}`}const J={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},Hh=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,Wh=/extends\s+State<\w+>/;function x0(t,e=""){if(t==="pubspec.yaml")return J.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return J.OTHER;if(t==="custom_functions.dart")return J.FUNCTION;if(e){const n=Hh.test(e),i=Wh.test(e);if(n||i)return J.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return J.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return J.FUNCTION}return J.CODE_FILE}function zh(t,e){switch(e){case J.ACTION:return`lib/custom_code/actions/${t}`;case J.WIDGET:return`lib/custom_code/widgets/${t}`;case J.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case J.CODE_FILE:return`lib/custom_code/${t}`;case J.DEPENDENCIES:return"pubspec.yaml";case J.OTHER:return`lib/custom_code/${t}`;default:return t}}async function jl(t,e=new Map){return kv(t,e)}const za=new Map;function qh(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function sr(t){za.delete(qh(t))}function bs(t,e,n){return new Promise((i,r)=>{let s=!1;const o=(l,u,c)=>{s||(s=!0,c==="resolve"?i(u):r(u))},a=setTimeout(()=>{s||(s=!0,n(i,r))},e);t.then(l=>{clearTimeout(a),o(i,l,"resolve")},l=>{clearTimeout(a),o(r,l,"reject")})})}async function Ul(t,e,n=bh){const i={stop:!1};return bs((async()=>{const r=await t.pushCode(e,i);return S0(r)})(),n,(r,s)=>{i.stop=!0,s(new Qe("FlutterFlow did not answer the sync in time — the push may still have been applied. The outcome is not yet known: open your FlutterFlow project to reconcile before retrying the deploy."))})}async function Hl(t,e,n,i,r="",s=bh){const o=r_(e,n);if(o.length===0)return{remoteFiles:n,syncFileMap:e,unverified:[],approximate:[]};const a=J_(o,r),l={...a.manifest,sources:a.sources},u=a.skipped.map(h=>h.reason);u.forEach(h=>console.warn(`[custom class deploy] ${h}`));const c=a.approximate;c.forEach(h=>console.warn(`[custom class deploy] ${h}`)),console.log(`Provisioning ${o.length} new FlutterFlow custom code file(s) before sync.`),Be.set("provision");let d=!0,f;try{if(f=await bs((async()=>{let h;try{h=await fetch(Ay,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:i,customClasses:o,verification:l,stream:!0})})}catch{throw new Qe("The provisioning request did not return a response. The deploy may have reached the FlutterFlow server — open your FlutterFlow project to reconcile before retrying.")}return Q_(h,{onPhase:p=>{d&&Be.setSubstatus(p)},onLog:p=>{d&&console.log(`[custom class deploy] ${p}`)}})})(),s,(h,p)=>{d=!1,p(new Qe("The deploy is still working on the FlutterFlow server, but this browser tab has stopped waiting. Your custom classes may or may not have been written — the outcome is not yet known. Open your FlutterFlow project to reconcile before retrying the deploy."))}),!f.finalResultReceived)throw Hu(f)===Le.FAILED?new Error(f.error||`FlutterFlow custom class provisioning failed (HTTP ${f.httpStatus}).`):new Qe("The connection to the FlutterFlow deploy runner dropped before it reported a result. The deploy may still be finishing on the server; open your FlutterFlow project to reconcile before retrying.");if(!f.success){const h=f.details?` ${f.details}`:"",p=`${f.error||"FlutterFlow custom class provisioning failed."}${h}`;throw Hu(f)===Le.UNCONFIRMED?new Qe(`${p} The failure arrived after the deploy began — custom classes may already be written. Open your FlutterFlow project to reconcile before retrying.`):new Error(p)}}catch(h){throw h instanceof Qe&&sr(t),h}return sr(t),f.verificationSkipped&&(console.warn(`[custom class deploy] ${f.verificationSkipped}`),u.push(f.verificationSkipped)),{remoteFiles:n,syncFileMap:s_(e,o),unverified:u,approximate:c,provisionSucceeded:!0}}async function Wl(t,e={}){const n=qh(t);let i=za.get(n);if(i===void 0){try{i=await t.fetchProjectSource()}catch(l){throw new Error(`Could not read your project's pubspec.yaml (${l.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=yh(i.pubspecYaml);if(!a.valid)throw new Error(`Your project's pubspec.yaml could not be read reliably (${a.errors.join("; ")}). Deploy was stopped so your existing package dependencies aren't overwritten.`);za.set(n,i)}const r=await vy(i.pubspecYaml,e),s=q_(i.pubspecYaml,r.overrides),o=z_(s.yaml,r.additions);return r.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>`${a}: ${r.additions[a]||"any"}`).join(", "),r.sdk.dartSdkFloor?`(resolved for Dart ${r.sdk.dartSdkFloor})`:""),r.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:s.overridden,warnings:r.warnings,remoteFiles:i.files}}function I0(t){const e=[],n=[];t.content.length>5e4&&n.push("Code file is large (>50KB). This may take longer to commit."),t.content.length>1e5&&e.push("Code file is too large (>100KB). Consider splitting into smaller components.");const i=t.content.split(` -`).length;i>500&&n.push(`Code has ${i} lines. Consider breaking it into smaller widgets.`),t.content.includes("setState")&&t.codeType===J.ACTION&&n.push("Using setState in a Custom Action may not work as expected. Consider using a Custom Widget."),t.content.includes("dynamic")&&!t.content.includes("?")&&n.push('Code uses "dynamic" types. Consider adding explicit types for better null safety.'),t.content.match(/Color\(0xFF[0-9A-Fa-f]{6}\)/)&&n.push("Code contains hardcoded colors. Consider using FlutterFlowTheme.of(context) for theme consistency.");const r=t.content.match(/print\s*\(/g);r&&r.length>3&&n.push(`Code contains ${r.length} print statements. Consider removing debug prints before committing.`);const s=S_(t.content);if(s&&e.push(`FlutterFlow cannot format this code - ${s}. Fix or regenerate before committing.`),t.codeType===J.WIDGET){const o=uh(t.content),a=w_(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=`${dh(o[0])}`;e.push(`Widget class name "${o[0]}" does not match the file name "${t.fileName}". FlutterFlow derives the widget from the file name, so it will report "No widget ${a} found". Rename the file to "${l}" or the class to match before committing.`)}}return{canProceed:e.length===0,issues:e,warnings:n}}function Vh(t,e={}){const{artifactType:n="CustomWidget",artifactName:i="GeneratedCode",fileName:r}=e,s=__(t);let o=r||i;if(n==="CustomFunction")o="custom_functions.dart";else if(n==="CustomWidget"){const u=uh(s)[0],c=u?dh(u):null;c&&o!==c?(console.warn(`Commit file name "${o}" does not match declared widget class "${u}"; renaming to "${c}" so FlutterFlow can find the widget.`),o=c):o.endsWith(".dart")||(o+=".dart")}else o.endsWith(".dart")||(o+=".dart");let a=J.CODE_FILE;switch(n){case"CustomAction":a=J.ACTION;break;case"CustomWidget":a=J.WIDGET;break;case"CustomFunction":a=J.FUNCTION;break;case"CustomClass":case"CodeFile":a=J.CODE_FILE;break}let l="";return a===J.WIDGET?l=`// Automatic FlutterFlow imports + `)}let y={step1Result:null,step2Result:null,step3Result:null,bundleSpec:null,artifactBundle:null,bundleReview:null,selectedArtifactId:null,resultsViewMode:"summary",currentStep:0,isRunning:!1,runId:0,submittedPrompt:"",submittedImages:[]};function w0(){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 b0(){y.bundleSpec=Qi(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function Bs(){const t=oi(y.bundleSpec);y.artifactBundle=Qi(y.step2Result,{id:y.bundleSpec?.id,title:y.bundleSpec?.title,description:y.bundleSpec?.description,artifactType:t.artifactType,artifactName:t.artifactName,fileName:t.fileName,dependencies:t.dependencies,relationships:y.bundleSpec?.relationships,code:y.step2Result||""});const e=Vv(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(n=>n.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=oi(y.artifactBundle).id}function Ds(){const t=Qi(y.step3Result,{id:y.artifactBundle?.id,title:y.artifactBundle?.title}),e=new Map(t.artifacts.map(i=>[i.id,i.review])),n=new Map(t.artifacts.filter(i=>{const r=i.review;return r&&typeof r.fixedSource=="string"&&r.fixedSource.trim()}).map(i=>[i.id,i.review.fixedSource.trim()]));y.bundleReview=Qi({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(i=>{const r=n.get(i.id)||null;return{...i,review:e.get(i.id)||i.review||y.step3Result||null,...r?{fixedCode:r}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function Wh(){const t=Ol();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function Ol(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(n=>n.id===y.selectedArtifactId)||oi(t)}function Bl(){return Ol().code||y.step2Result||""}async function E0(){try{await Rl()}catch(t){return console.error("checkConnection: initializeApiKeys failed:",t),!1}return!0}const Dr={production:"https://api.flutterflow.io/v2/",staging:"https://api.flutterflow.io/v2-staging/"};function S0(t,e){const n=e?.trim()?` (${e.trim().slice(0,200)})`:"";return t===401?`Your FlutterFlow API key was rejected (401 Unauthorized)${n}. Re-enter a current key under API Keys settings, then try again.`:`Listing FlutterFlow projects was denied (403)${n}. The key may be scoped to sync a single project without list permission - verify the key's access in FlutterFlow, re-enter it under API Keys settings, then retry.`}class hi{constructor(e,n,i="main",r=Dr.production){this.apiKey=e,this.baseUrl=r,this._projectId=n,this._branchName=i,this._endpoint=r}get projectId(){return this._projectId}get branchName(){return this._branchName==="main"?"":this._branchName}async exportProjectZip(){console.log(`Exporting code from FlutterFlow project: ${this.projectId}, branch: ${this.branchName||"main"}`);const e=[{project:{path:`projects/${this.projectId}`},...this.branchName?{branch_name:this.branchName}:{},export_as_module:!1,include_assets_map:!1,format:!1,export_as_debug:!1},{project_id:this.projectId,branch_name:this.branchName,include_assets:!1,export_as_module:!1}];let n=null;for(const i of e)try{const r=await fetch(`${this.baseUrl}exportCode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(i)});if(!r.ok){const a=await r.text();n=new Error(`Export failed: ${r.status} - ${a}`);continue}const s=await r.json(),o=s?.value?.project_zip||s?.project_zip;if(!o){n=new Error("Export response did not include project source.");continue}return o}catch(r){n=r}throw n||new Error("Export failed for an unknown reason.")}async fetchProjectSource(){const e=await this.exportProjectZip(),n=await JSZip.loadAsync(e,{base64:!0}),i=Object.keys(n.files).filter(a=>!n.files[a].dir&&(a==="pubspec.yaml"||a.endsWith("/pubspec.yaml"))).sort((a,l)=>a.split("/").length-l.split("/").length)[0];if(!i)throw new Error("Export did not contain a pubspec.yaml.");const r=i.slice(0,i.length-12),s=new Map,o=Object.keys(n.files).filter(a=>{if(n.files[a].dir||!a.startsWith(r))return!1;const l=a.slice(r.length);return l==="lib/flutter_flow/custom_functions.dart"||l.startsWith("lib/custom_code/")&&l.endsWith(".dart")});return await Promise.all(o.map(async a=>{s.set(a.slice(r.length),await n.files[a].async("string"))})),{pubspecYaml:await n.files[i].async("string"),files:s}}async pushCodeWithRetry(e,n=3,i=null){const r=[Dr.production,Dr.staging],s=Math.max(0,r.indexOf(this._endpoint));let o=!1,a=null;for(let l=0;lsetTimeout(h,1e3*(l+1)));continue}if(d.ok)return console.log(`Push to ${c} succeeded!`),d;if(a=d.status,Wa(d.clone(),Sh).then(f=>console.log(`Push to ${c} returned ${d.status}: ${f}`),()=>console.log(`Push to ${c} returned ${d.status} (unreadable response body)`)),d.status>=500&&(o=!0),d.status===500){console.warn(`Endpoint ${c} returned 500, trying next...`),await new Promise(f=>setTimeout(f,1e3*(l+1)));continue}if(d.status>=500)throw new Qe(`FlutterFlow reported a server error (HTTP ${d.status}), which cannot prove the push was refused — the write may have been applied before the failure. Open your FlutterFlow project to reconcile before retrying.`);if(o)throw new Qe(`The push was refused (HTTP ${d.status}), but an earlier sync attempt may already have applied it — server errors and dropped responses cannot prove a refusal. Open your FlutterFlow project to reconcile before retrying.`);return d}throw Hu({httpStatus:a})}async pushCode(e,n=null){return this.pushCodeWithRetry(e,3,n)}parseProjectsResponse(e){if(e?.success&&typeof e.value=="string")try{const i=JSON.parse(e.value);if(i&&Array.isArray(i.entries))return i.entries.map(r=>({id:r.id,name:r.project?.name||r.id}))}catch(i){console.error("Failed to parse stringified project value:",i)}const n=e?.projects||e?.items||e?.entries||(Array.isArray(e)?e:[]);return Array.isArray(n)?n:[]}async listProjects(){console.log("Listing projects for API key");const e=[`${this.baseUrl}listProjects`,"https://api.flutterflow.io/v2/l/listProjects"];let n=0,i="";for(const r of e){const s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({project_type:"ALL",deserialize_response:!0})});if(s.ok)return r!==e[0]&&console.log(`listProjects answered on legacy path ${r}`),this.parseProjectsResponse(await s.json());if(n=s.status,i=await s.text(),console.warn(`listProjects via ${r} returned ${n}: ${i}`),s.status===401||s.status===403)throw new Error(S0(s.status,i));if(s.status!==404)throw new Error(`List projects failed: ${s.status} - ${i}`)}throw new Error(`List projects failed: ${n} - ${i}`)}}function Wa(t,e){const n=t.body?.getReader?.(),i=n?(async()=>{const r=new TextDecoder;let s="";for(;;){const{done:o,value:a}=await n.read();if(o)break;s+=r.decode(a,{stream:!0})}return s+r.decode()})():Promise.resolve("");return Ul(i,e,(r,s)=>{try{n?.cancel()?.catch?.(()=>{})}catch{}s(new Error("The response body stalled before it finished."))})}async function x0(t,e=Sh){const n=t.clone();let i;try{i=JSON.parse(await Wa(t,e))}catch{let o="";try{o=await Wa(n,e)}catch{}if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:o||`HTTP ${t.status}`,errorMap:new Map};throw new Qe(`FlutterFlow accepted the sync but returned an unreadable response${o?`: ${o.slice(0,200)}`:"."}`)}if(!t.ok){let s=i.message||`HTTP ${t.status}`,o=new Map;if(i.errors)o=new Map(Object.entries(i.errors));else if(!i.message&&typeof i=="object"){const a=Object.keys(i).filter(l=>l.endsWith(".dart")&&Array.isArray(i[l]));a.length>0&&(o=new Map(Object.entries(i)),s=a.flatMap(u=>i[u].map(c=>`${u}: ${c.errorMessage}`)).join(` +`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:s,errorMap:o}}let r={};if(i.value)try{r=typeof i.value=="string"?JSON.parse(i.value):i.value}catch(s){console.warn("Ignoring malformed push response value:",s)}return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(r))}}function Dl(t,e){return{401:"Authentication failed. Please check your FlutterFlow API key.",403:"Access denied. You may not have permission to modify this project.",404:"Project not found. Please check your Project ID.",409:"Conflict detected. The project may have been modified elsewhere.",422:"Validation failed: Invalid request format",429:"Rate limit exceeded. Please try again in a few minutes.",500:"FlutterFlow server error. Please try again later.",503:"FlutterFlow service temporarily unavailable."}[t]||`FlutterFlow API error: ${`HTTP ${t}`}`}const J={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},zh=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,qh=/extends\s+State<\w+>/;function I0(t,e=""){if(t==="pubspec.yaml")return J.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return J.OTHER;if(t==="custom_functions.dart")return J.FUNCTION;if(e){const n=zh.test(e),i=qh.test(e);if(n||i)return J.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return J.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return J.FUNCTION}return J.CODE_FILE}function Vh(t,e){switch(e){case J.ACTION:return`lib/custom_code/actions/${t}`;case J.WIDGET:return`lib/custom_code/widgets/${t}`;case J.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case J.CODE_FILE:return`lib/custom_code/${t}`;case J.DEPENDENCIES:return"pubspec.yaml";case J.OTHER:return`lib/custom_code/${t}`;default:return t}}async function jl(t,e=new Map){return Av(t,e)}const za=new Map;function Gh(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function sr(t){za.delete(Gh(t))}function Ul(t,e,n){return new Promise((i,r)=>{let s=!1;const o=(l,u,c)=>{s||(s=!0,c==="resolve"?i(u):r(u))},a=setTimeout(()=>{s||(s=!0,n(i,r))},e);t.then(l=>{clearTimeout(a),o(i,l,"resolve")},l=>{clearTimeout(a),o(r,l,"reject")})})}async function Hl(t,e,n=Eh){const i={stop:!1};return Ul((async()=>{const r=await t.pushCode(e,i);return x0(r)})(),n,(r,s)=>{i.stop=!0,s(new Qe("FlutterFlow did not answer the sync in time — the push may still have been applied. The outcome is not yet known: open your FlutterFlow project to reconcile before retrying the deploy."))})}async function Wl(t,e,n,i,r="",s=Eh){const o=o_(e,n);if(o.length===0)return{remoteFiles:n,syncFileMap:e,unverified:[],approximate:[]};const a=X_(o,r),l={...a.manifest,sources:a.sources},u=a.skipped.map(h=>h.reason);u.forEach(h=>console.warn(`[custom class deploy] ${h}`));const c=a.approximate;c.forEach(h=>console.warn(`[custom class deploy] ${h}`)),console.log(`Provisioning ${o.length} new FlutterFlow custom code file(s) before sync.`),Be.set("provision");let d=!0,f;try{if(f=await Ul((async()=>{let h;try{h=await fetch(Py,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:i,customClasses:o,verification:l,stream:!0})})}catch{throw new Qe("The provisioning request did not return a response. The deploy may have reached the FlutterFlow server — open your FlutterFlow project to reconcile before retrying.")}return ey(h,{onPhase:p=>{d&&Be.setSubstatus(p)},onLog:p=>{d&&console.log(`[custom class deploy] ${p}`)}})})(),s,(h,p)=>{d=!1,p(new Qe("The deploy is still working on the FlutterFlow server, but this browser tab has stopped waiting. Your custom classes may or may not have been written — the outcome is not yet known. Open your FlutterFlow project to reconcile before retrying the deploy."))}),!f.finalResultReceived)throw Wu(f)===Le.FAILED?new Error(f.error||`FlutterFlow custom class provisioning failed (HTTP ${f.httpStatus}).`):new Qe("The connection to the FlutterFlow deploy runner dropped before it reported a result. The deploy may still be finishing on the server; open your FlutterFlow project to reconcile before retrying.");if(!f.success){const h=f.details?` ${f.details}`:"",p=`${f.error||"FlutterFlow custom class provisioning failed."}${h}`;throw Wu(f)===Le.UNCONFIRMED?new Qe(`${p} The failure arrived after the deploy began — custom classes may already be written. Open your FlutterFlow project to reconcile before retrying.`):new Error(p)}}catch(h){throw h instanceof Qe&&sr(t),h}return sr(t),f.verificationSkipped&&(console.warn(`[custom class deploy] ${f.verificationSkipped}`),u.push(f.verificationSkipped)),{remoteFiles:n,syncFileMap:a_(e,o),unverified:u,approximate:c,provisionSucceeded:!0}}async function zl(t,e={}){const n=Gh(t);let i=za.get(n);if(i===void 0){try{i=await t.fetchProjectSource()}catch(l){throw new Error(`Could not read your project's pubspec.yaml (${l.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=wh(i.pubspecYaml);if(!a.valid)throw new Error(`Your project's pubspec.yaml could not be read reliably (${a.errors.join("; ")}). Deploy was stopped so your existing package dependencies aren't overwritten.`);za.set(n,i)}const r=await _y(i.pubspecYaml,e),s=G_(i.pubspecYaml,r.overrides),o=V_(s.yaml,r.additions);return r.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>`${a}: ${r.additions[a]||"any"}`).join(", "),r.sdk.dartSdkFloor?`(resolved for Dart ${r.sdk.dartSdkFloor})`:""),r.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:s.overridden,warnings:r.warnings,remoteFiles:i.files}}function k0(t){const e=[],n=[];t.content.length>5e4&&n.push("Code file is large (>50KB). This may take longer to commit."),t.content.length>1e5&&e.push("Code file is too large (>100KB). Consider splitting into smaller components.");const i=t.content.split(` +`).length;i>500&&n.push(`Code has ${i} lines. Consider breaking it into smaller widgets.`),t.content.includes("setState")&&t.codeType===J.ACTION&&n.push("Using setState in a Custom Action may not work as expected. Consider using a Custom Widget."),t.content.includes("dynamic")&&!t.content.includes("?")&&n.push('Code uses "dynamic" types. Consider adding explicit types for better null safety.'),t.content.match(/Color\(0xFF[0-9A-Fa-f]{6}\)/)&&n.push("Code contains hardcoded colors. Consider using FlutterFlowTheme.of(context) for theme consistency.");const r=t.content.match(/print\s*\(/g);r&&r.length>3&&n.push(`Code contains ${r.length} print statements. Consider removing debug prints before committing.`);const s=I_(t.content);if(s&&e.push(`FlutterFlow cannot format this code - ${s}. Fix or regenerate before committing.`),t.codeType===J.WIDGET){const o=dh(t.content),a=E_(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=`${fh(o[0])}`;e.push(`Widget class name "${o[0]}" does not match the file name "${t.fileName}". FlutterFlow derives the widget from the file name, so it will report "No widget ${a} found". Rename the file to "${l}" or the class to match before committing.`)}}return{canProceed:e.length===0,issues:e,warnings:n}}function Kh(t,e={}){const{artifactType:n="CustomWidget",artifactName:i="GeneratedCode",fileName:r}=e,s=w_(t);let o=r||i;if(n==="CustomFunction")o="custom_functions.dart";else if(n==="CustomWidget"){const u=dh(s)[0],c=u?fh(u):null;c&&o!==c?(console.warn(`Commit file name "${o}" does not match declared widget class "${u}"; renaming to "${c}" so FlutterFlow can find the widget.`),o=c):o.endsWith(".dart")||(o+=".dart")}else o.endsWith(".dart")||(o+=".dart");let a=J.CODE_FILE;switch(n){case"CustomAction":a=J.ACTION;break;case"CustomWidget":a=J.WIDGET;break;case"CustomFunction":a=J.FUNCTION;break;case"CustomClass":case"CodeFile":a=J.CODE_FILE;break}let l="";return a===J.WIDGET?l=`// Automatic FlutterFlow imports import '/flutter_flow/flutter_flow_theme.dart'; import '/flutter_flow/flutter_flow_util.dart'; import 'package:flutter/material.dart'; @@ -111,15 +111,15 @@ import '/flutter_flow/lat_lng.dart'; import '/flutter_flow/place.dart'; import '/flutter_flow/uploaded_file.dart'; -`),{content:Gv(s,l),fileName:o,codeType:a,artifactType:n,artifactName:i}}function k0(t){const e={};for(const n of bl(t))e[n]="";return e}function C0(t,e={}){return{timestamp:new Date().toISOString(),artifactType:t.artifactType,artifactName:t.artifactName,codeType:t.codeType,fileName:t.fileName,generatedFrom:e.step1Result?"pipeline":"direct",model:e.selectedModel||"unknown",codeSize:t.content.length}}function A0(t,e,n,i=new Set,r=""){const s=[],o=Hh.test(e),a=Wh.test(e);return n===J.WIDGET&&!o&&!a&&s.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:s.length===0,errors:s}}function Us(t){const e=[],n=[];if(!t||t.size===0)return e.push("No files to commit"),{valid:!1,errors:e,warnings:n};const i=new Set(Array.from(t.values()).flatMap(r=>Ps(r.content||"")));for(const[r,s]of t.entries()){if((!s.content||s.content.trim().length===0)&&e.push(`File ${r} is empty`),s.content&&s.content.length>1e5&&n.push(`File ${r} is very large (>100KB)`),r.endsWith(".dart")){const o=A0(r,s.content,s.type,i,s.artifactName);o.valid||e.push(...o.errors.map(a=>`${r}: ${a}`))}if(r==="pubspec.yaml"){const o=yh(s.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:n}}const ee={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},G={currentState:ee.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=ee.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(ee).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===ee.PREPARING&&(this.startTime=Date.now()),(t===ee.SUCCESS||t===ee.ERROR)&&(this.endTime=Date.now()),typeof window<"u"&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("commitStateChange",{detail:{state:t,commitState:this}})),console.log(`Commit state changed to: ${t}`)},setError(t){this.error=t,this.setState(ee.ERROR)},setSuccess(t){this.result=t,this.setState(ee.SUCCESS)},setProgress(t,e){this.filesProcessed=t,this.totalFiles=e},getElapsedTime(){return this.startTime?(this.endTime||Date.now())-this.startTime:null},isInProgress(){return this.currentState===ee.PREPARING||this.currentState===ee.VALIDATING||this.currentState===ee.PUSHING}};async function P0(t,e,n={}){let{codeType:i="W"}=n;const{pubspecDeps:r={},artifactName:s=e}=n;i==="CustomWidget"&&(i=J.WIDGET),i==="CustomAction"&&(i=J.ACTION),i==="CustomFunction"&&(i=J.FUNCTION),i==="CustomClass"&&(i=J.CODE_FILE),i==="CodeFile"&&(i=J.CODE_FILE),G.reset(),G.setState(ee.PREPARING);try{const o=await Te("flutterflow"),a=await Te("flutterflow_project_id");if(!o||!a)throw new Error("FlutterFlow credentials not configured. Please set your API key and Project ID in the API Keys settings.");if(!Bs(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=yt(),u=new hi(o,a,"main",l);G.setState(ee.VALIDATING);const c=new Map,d=i||x0(e,t),f=zh(e,d);c.set(e,{artifactName:s,content:t,type:d,path:f}),G.setProgress(0,c.size);const h=Us(c);if(!h.valid)throw new Error(`Validation failed: +`),{content:Yv(s,l),fileName:o,codeType:a,artifactType:n,artifactName:i}}function C0(t){const e={};for(const n of bl(t))e[n]="";return e}function A0(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 P0(t,e,n,i=new Set,r=""){const s=[],o=zh.test(e),a=qh.test(e);return n===J.WIDGET&&!o&&!a&&s.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:s.length===0,errors:s}}function js(t){const e=[],n=[];if(!t||t.size===0)return e.push("No files to commit"),{valid:!1,errors:e,warnings:n};const i=new Set(Array.from(t.values()).flatMap(r=>As(r.content||"")));for(const[r,s]of t.entries()){if((!s.content||s.content.trim().length===0)&&e.push(`File ${r} is empty`),s.content&&s.content.length>1e5&&n.push(`File ${r} is very large (>100KB)`),r.endsWith(".dart")){const o=P0(r,s.content,s.type,i,s.artifactName);o.valid||e.push(...o.errors.map(a=>`${r}: ${a}`))}if(r==="pubspec.yaml"){const o=wh(s.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:n}}const ee={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},G={currentState:ee.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=ee.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(ee).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===ee.PREPARING&&(this.startTime=Date.now()),(t===ee.SUCCESS||t===ee.ERROR)&&(this.endTime=Date.now()),typeof window<"u"&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("commitStateChange",{detail:{state:t,commitState:this}})),console.log(`Commit state changed to: ${t}`)},setError(t){this.error=t,this.setState(ee.ERROR)},setSuccess(t){this.result=t,this.setState(ee.SUCCESS)},setProgress(t,e){this.filesProcessed=t,this.totalFiles=e},getElapsedTime(){return this.startTime?(this.endTime||Date.now())-this.startTime:null},isInProgress(){return this.currentState===ee.PREPARING||this.currentState===ee.VALIDATING||this.currentState===ee.PUSHING}};async function F0(t,e,n={}){let{codeType:i="W"}=n;const{pubspecDeps:r={},artifactName:s=e}=n;i==="CustomWidget"&&(i=J.WIDGET),i==="CustomAction"&&(i=J.ACTION),i==="CustomFunction"&&(i=J.FUNCTION),i==="CustomClass"&&(i=J.CODE_FILE),i==="CodeFile"&&(i=J.CODE_FILE),G.reset(),G.setState(ee.PREPARING);try{const o=await Te("flutterflow"),a=await Te("flutterflow_project_id");if(!o||!a)throw new Error("FlutterFlow credentials not configured. Please set your API key and Project ID in the API Keys settings.");if(!Os(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=yt(),u=new hi(o,a,"main",l);G.setState(ee.VALIDATING);const c=new Map,d=i||I0(e,t),f=Vh(e,d);c.set(e,{artifactName:s,content:t,type:d,path:f}),G.setProgress(0,c.size);const h=js(c);if(!h.valid)throw new Error(`Validation failed: ${h.errors.join(` -`)}`);const p=await Wl(u,r),g=p.yaml,m=await Hl(u,c,p.remoteFiles,`Provision ${s} custom class`,g),v=await jl(m.syncFileMap,m.remoteFiles),E=new Map(m.syncFileMap);E.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),Be.set("package");const S=await zl(E),_={project_id:a,zipped_custom_code:S,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};G.setState(ee.PUSHING),G.setProgress(1,c.size),sr(u),Be.set("push");const b=await Ul(u,_);if(b.success)G.setSuccess({fileCount:c.size,projectId:a,warnings:b.errorMap&&b.errorMap.size>0?Array.from(b.errorMap.entries()):[]});else{const k=b.errorMessage||Dl(b.responseCode),T=new Error(k);throw T.remoteRefusal=!0,T}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:p.added,unverified:m.unverified,approximate:m.approximate,warnings:b.errorMap?Array.from(b.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),G.setError(o),o instanceof Qe?{success:!1,unconfirmed:!0,error:o.message,state:G.currentState}:{success:!1,error:o.message,remoteRefusal:o.remoteRefusal===!0,state:G.currentState}}}async function zl(t){const e=new JSZip;for(const[n,i]of t.entries())e.file(n,i.content);return e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}async function F0(t,e={}){const{artifactType:n,artifactName:i,fileName:r,pipelineResult:s}=e;console.log(`Starting commit for ${i} (${n})`);let o=!1;const a={projectId:null,endpoint:yt(),artifactType:n,artifactName:i,fileName:r};try{G.setState(ee.PREPARING);const l=Vh(t,{artifactType:n,artifactName:i,fileName:r}),u=k0(l.content);console.log("Detected dependencies:",u),G.setState(ee.VALIDATING);const c=await Te("flutterflow"),d=zi||await Te("flutterflow_project_id");if(!c)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!d)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Bs(d))throw new Error("Invalid FlutterFlow Project ID format.");a.projectId=d;const f=new Map;f.set(l.fileName,{artifactName:i,content:l.content,type:l.codeType,path:zh(l.fileName,l.codeType),functionName:l.codeType===J.FUNCTION?i:void 0}),G.setProgress(0,f.size);const h=Us(f);if(!h.valid)throw new Error(`File validation failed: +`)}`);const p=await zl(u,r),g=p.yaml,m=await Wl(u,c,p.remoteFiles,`Provision ${s} custom class`,g),v=await jl(m.syncFileMap,m.remoteFiles),E=new Map(m.syncFileMap);E.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),Be.set("package");const S=await ql(E),_={project_id:a,zipped_custom_code:S,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};G.setState(ee.PUSHING),G.setProgress(1,c.size),sr(u),Be.set("push");const b=await Hl(u,_);if(b.success)G.setSuccess({fileCount:c.size,projectId:a,warnings:b.errorMap&&b.errorMap.size>0?Array.from(b.errorMap.entries()):[]});else{const k=b.errorMessage||Dl(b.responseCode),T=new Error(k);throw T.remoteRefusal=!0,T}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:p.added,unverified:m.unverified,approximate:m.approximate,warnings:b.errorMap?Array.from(b.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),G.setError(o),o instanceof Qe?{success:!1,unconfirmed:!0,error:o.message,state:G.currentState}:{success:!1,error:o.message,remoteRefusal:o.remoteRefusal===!0,state:G.currentState}}}async function ql(t){const e=new JSZip;for(const[n,i]of t.entries())e.file(n,i.content);return e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}async function R0(t,e={}){const{artifactType:n,artifactName:i,fileName:r,pipelineResult:s}=e;console.log(`Starting commit for ${i} (${n})`);let o=!1;const a={projectId:null,endpoint:yt(),artifactType:n,artifactName:i,fileName:r};try{G.setState(ee.PREPARING);const l=Kh(t,{artifactType:n,artifactName:i,fileName:r}),u=C0(l.content);console.log("Detected dependencies:",u),G.setState(ee.VALIDATING);const c=await Te("flutterflow"),d=zi||await Te("flutterflow_project_id");if(!c)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!d)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Os(d))throw new Error("Invalid FlutterFlow Project ID format.");a.projectId=d;const f=new Map;f.set(l.fileName,{artifactName:i,content:l.content,type:l.codeType,path:Vh(l.fileName,l.codeType),functionName:l.codeType===J.FUNCTION?i:void 0}),G.setProgress(0,f.size);const h=js(f);if(!h.valid)throw new Error(`File validation failed: ${h.errors.join(` -`)}`);h.warnings.length>0&&console.warn("Validation warnings:",h.warnings),G.setState(ee.PUSHING);const p=yt(),g=new hi(c,d,"main",p),m=await Wl(g,u),v=m.yaml,E=await Hl(g,f,m.remoteFiles,`Provision ${i} custom class`,v);o=E.provisionSucceeded===!0;const S=await jl(E.syncFileMap,E.remoteFiles),_=new Map(E.syncFileMap);_.set("pubspec.yaml",{content:v,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Be.set("package");const b=await zl(_),k={project_id:d,zipped_custom_code:b,uid:`web_${Date.now()}`,branch_name:g.branchName,serialized_yaml:v,file_map:S.fileMapContents,functions_map:S.functionsMapContents};G.setProgress(1,f.size),sr(g),Be.set("push");const T=await Ul(g,k);if(T.success){const x={...C0(l,s),projectId:d};return G.setSuccess({...x,fileCount:f.size,warnings:T.errorMap?Array.from(T.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${l.fileName} to FlutterFlow`,metadata:x,targetIdentity:a,addedDependencies:m.added,unverified:E.unverified,approximate:E.approximate,warnings:T.errorMap?Array.from(T.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}else{const x=T.errorMessage||Dl(T.responseCode),F=new Error(x);throw F.errorMap=T.errorMap,F.remoteRefusal=!0,F}}catch(l){console.error("Commit execution failed:",l),G.setError(l);let u=new Map;if(l.errorMap)u=l.errorMap;else if(l.message&&l.message.includes("{"))try{const c=l.message.match(/\{[\s\S]*\}/);if(c){const d=JSON.parse(c[0]);u=new Map(Object.entries(d))}}catch(c){console.warn("Failed to parse error map from commit response:",c)}return l instanceof Qe?{success:!1,unconfirmed:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:o?{success:!1,partial:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:l.message,errorMap:u,remoteRefusal:l.remoteRefusal===!0,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function R0(t,e={}){const{pipelineResult:n}=e;let i=!1;const r={projectId:null,endpoint:yt(),artifactType:"Bundle",artifactName:t?.title,fileName:t?.fileEntries?`${t.fileEntries.length} artifacts`:"bundle"};try{if(G.setState(ee.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: +`)}`);h.warnings.length>0&&console.warn("Validation warnings:",h.warnings),G.setState(ee.PUSHING);const p=yt(),g=new hi(c,d,"main",p),m=await zl(g,u),v=m.yaml,E=await Wl(g,f,m.remoteFiles,`Provision ${i} custom class`,v);o=E.provisionSucceeded===!0;const S=await jl(E.syncFileMap,E.remoteFiles),_=new Map(E.syncFileMap);_.set("pubspec.yaml",{content:v,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Be.set("package");const b=await ql(_),k={project_id:d,zipped_custom_code:b,uid:`web_${Date.now()}`,branch_name:g.branchName,serialized_yaml:v,file_map:S.fileMapContents,functions_map:S.functionsMapContents};G.setProgress(1,f.size),sr(g),Be.set("push");const T=await Hl(g,k);if(T.success){const x={...A0(l,s),projectId:d};return G.setSuccess({...x,fileCount:f.size,warnings:T.errorMap?Array.from(T.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${l.fileName} to FlutterFlow`,metadata:x,targetIdentity:a,addedDependencies:m.added,unverified:E.unverified,approximate:E.approximate,warnings:T.errorMap?Array.from(T.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}else{const x=T.errorMessage||Dl(T.responseCode),F=new Error(x);throw F.errorMap=T.errorMap,F.remoteRefusal=!0,F}}catch(l){console.error("Commit execution failed:",l),G.setError(l);let u=new Map;if(l.errorMap)u=l.errorMap;else if(l.message&&l.message.includes("{"))try{const c=l.message.match(/\{[\s\S]*\}/);if(c){const d=JSON.parse(c[0]);u=new Map(Object.entries(d))}}catch(c){console.warn("Failed to parse error map from commit response:",c)}return l instanceof Qe?{success:!1,unconfirmed:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:o?{success:!1,partial:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:l.message,errorMap:u,remoteRefusal:l.remoteRefusal===!0,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function T0(t,e={}){const{pipelineResult:n}=e;let i=!1;const r={projectId:null,endpoint:yt(),artifactType:"Bundle",artifactName:t?.title,fileName:t?.fileEntries?`${t.fileEntries.length} artifacts`:"bundle"};try{if(G.setState(ee.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: ${t.errors.join(` -`)}`);const s=new Map(t.fileEntries.map(b=>[b.fileName,{artifactId:b.artifactId,artifactName:b.artifactName,content:b.content,type:b.type,path:b.path,functionName:b.type===J.FUNCTION?b.artifactName:void 0}]));G.setProgress(0,s.size);const o=Us(s);if(!o.valid)throw new Error(`File validation failed: +`)}`);const s=new Map(t.fileEntries.map(b=>[b.fileName,{artifactId:b.artifactId,artifactName:b.artifactName,content:b.content,type:b.type,path:b.path,functionName:b.type===J.FUNCTION?b.artifactName:void 0}]));G.setProgress(0,s.size);const o=js(s);if(!o.valid)throw new Error(`File validation failed: ${o.errors.join(` -`)}`);G.setState(ee.VALIDATING);const a=await Te("flutterflow"),l=zi||await Te("flutterflow_project_id");if(!a)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!l)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Bs(l))throw new Error("Invalid FlutterFlow Project ID format.");r.projectId=l,G.setState(ee.PUSHING);const u=yt(),c=new hi(a,l,"main",u),d=await Wl(c,t.dependencies),f=d.yaml,h=await Hl(c,s,d.remoteFiles,`Provision ${t.title} custom classes`,f);i=h.provisionSucceeded===!0;const p=await jl(h.syncFileMap,h.remoteFiles),g=new Map(h.syncFileMap);g.set("pubspec.yaml",{content:f,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Be.set("package");const m=await zl(g),v={project_id:l,zipped_custom_code:m,uid:`web_${Date.now()}`,branch_name:c.branchName,serialized_yaml:f,file_map:p.fileMapContents,functions_map:p.functionsMapContents};G.setProgress(1,s.size),sr(c),Be.set("push");const E=await Ul(c,v);if(E.success){const b={...n,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((k,T)=>k+T.content.length,0),projectId:l};return G.setSuccess({...b,fileCount:s.size,warnings:E.errorMap?Array.from(E.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:b,targetIdentity:r,addedDependencies:d.added,unverified:h.unverified,approximate:h.approximate,warnings:E.errorMap?Array.from(E.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}const S=E.errorMessage||Dl(E.responseCode),_=new Error(S);throw _.errorMap=E.errorMap,_.remoteRefusal=!0,_}catch(s){console.error("Bundle commit execution failed:",s),G.setError(s);const o=s.errorMap||new Map;return s instanceof Qe?{success:!1,unconfirmed:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:i?{success:!1,partial:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function T0(t,e=[]){const n=vl("architect");try{return await xs("architect",Th,pv(t),n,e)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Prompt Architect failed: ${i.message}`)}}async function Hs(t,e,n=[],i){const r=gv(t),s=vl("generator",y.bundleSpec);try{return await xs("generator",e,r,s,n)}catch(o){if(o.isModelArmor||o.isUsageLimit||o.isPipelineCancel)throw o;if(e!==kr){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,o.message),Ow(e,kr,i);try{return await xs("generator",kr,r,s,n)}catch(a){throw a.isModelArmor||a.isUsageLimit||a.isPipelineCancel?a:new Error(`Code Generator failed: primary (${e}): ${o.message} | fallback (${kr}): ${a.message}`)}}throw new Error(`Code Generator failed: ${o.message}`)}}async function Ws(t,e=null){const n={...vl("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await xs("review",$h,mv(t),n)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Code Review failed: ${i.message}`)}}function Es(t,e){const n=document.getElementById(`step${t}-item`),i=document.getElementById(`step${t}-status`);!n||!i||(n.classList.remove("active","completed","error"),i.classList.remove("running","completed","error"),e==="active"?(n.classList.add("active"),i.classList.add("running"),i.innerHTML=` +`)}`);G.setState(ee.VALIDATING);const a=await Te("flutterflow"),l=zi||await Te("flutterflow_project_id");if(!a)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!l)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Os(l))throw new Error("Invalid FlutterFlow Project ID format.");r.projectId=l,G.setState(ee.PUSHING);const u=yt(),c=new hi(a,l,"main",u),d=await zl(c,t.dependencies),f=d.yaml,h=await Wl(c,s,d.remoteFiles,`Provision ${t.title} custom classes`,f);i=h.provisionSucceeded===!0;const p=await jl(h.syncFileMap,h.remoteFiles),g=new Map(h.syncFileMap);g.set("pubspec.yaml",{content:f,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Be.set("package");const m=await ql(g),v={project_id:l,zipped_custom_code:m,uid:`web_${Date.now()}`,branch_name:c.branchName,serialized_yaml:f,file_map:p.fileMapContents,functions_map:p.functionsMapContents};G.setProgress(1,s.size),sr(c),Be.set("push");const E=await Hl(c,v);if(E.success){const b={...n,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((k,T)=>k+T.content.length,0),projectId:l};return G.setSuccess({...b,fileCount:s.size,warnings:E.errorMap?Array.from(E.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:b,targetIdentity:r,addedDependencies:d.added,unverified:h.unverified,approximate:h.approximate,warnings:E.errorMap?Array.from(E.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}const S=E.errorMessage||Dl(E.responseCode),_=new Error(S);throw _.errorMap=E.errorMap,_.remoteRefusal=!0,_}catch(s){console.error("Bundle commit execution failed:",s),G.setError(s);const o=s.errorMap||new Map;return s instanceof Qe?{success:!1,unconfirmed:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:i?{success:!1,partial:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function $0(t,e=[]){const n=vl("architect");try{return await Ss("architect",Mh,mv(t),n,e)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Prompt Architect failed: ${i.message}`)}}async function Us(t,e,n=[],i){const r=vv(t),s=vl("generator",y.bundleSpec);try{return await Ss("generator",e,r,s,n)}catch(o){if(o.isModelArmor||o.isUsageLimit||o.isPipelineCancel)throw o;if(e!==kr){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,o.message),Bw(e,kr,i);try{return await Ss("generator",kr,r,s,n)}catch(a){throw a.isModelArmor||a.isUsageLimit||a.isPipelineCancel?a:new Error(`Code Generator failed: primary (${e}): ${o.message} | fallback (${kr}): ${a.message}`)}}throw new Error(`Code Generator failed: ${o.message}`)}}async function Hs(t,e=null){const n={...vl("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await Ss("review",Lh,_v(t),n)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Code Review failed: ${i.message}`)}}function bs(t,e){const n=document.getElementById(`step${t}-item`),i=document.getElementById(`step${t}-status`);!n||!i||(n.classList.remove("active","completed","error"),i.classList.remove("running","completed","error"),e==="active"?(n.classList.add("active"),i.classList.add("running"),i.innerHTML=` `):e==="completed"?(n.classList.add("completed"),i.classList.add("completed"),i.innerHTML=` @@ -127,12 +127,12 @@ ${o.errors.join(` `):i.innerHTML=` - `)}function Ae(t,e){const n=document.getElementById(`step${t}-loading`),i=document.getElementById(`step${t}-result`);e?(n.classList.remove("hidden"),i.classList.add("hidden"),Es(t,"active")):(n.classList.add("hidden"),i.classList.remove("hidden"),Es(t,"completed"))}function $0(t){const e=document.getElementById(`${t}-content`),n=document.getElementById(`${t}-chevron`);e.classList.contains("open")?(e.classList.remove("open"),n&&(n.style.transform="rotate(0deg)")):(e.classList.add("open"),n&&(n.style.transform="rotate(180deg)"))}function M0(t){it(parseInt(t.replace("step","")))}function it(t){for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-item`);a&&a.classList.remove("active")}const e=document.getElementById(`step${t}-item`);e&&e.classList.add("active"),Nn();const n=document.getElementById("ready-state");n&&n.classList.add("hidden");for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-content`);a&&a.classList.add("hidden")}const i=document.getElementById(`step${t}-content`);i&&i.classList.remove("hidden");const r=document.getElementById("stage-title"),s={1:"Prompt Architect",2:"Code Generator",3:"Code Review"};r&&(r.textContent=s[t]||"Active Workflow Stage")}function L0(t){const e=document.getElementById(t);if(!e)return;const n=e.dataset.raw||e.textContent;navigator.clipboard.writeText(n).then(()=>{const r=e.closest(".code-container")?.querySelector(".copy-btn");r&&(r.classList.add("copied"),r.innerHTML=' Copied!',setTimeout(()=>{r.classList.remove("copied"),r.innerHTML=' Copy'},2e3))}).catch(i=>{console.warn("Failed to copy to clipboard:",i)})}function qa(t){const e=Va(t);console.log(`Step 1 (Prompt Architect): ${Gt(Th)}`),console.log(e!==t?`Step 2 (Code Generator): ${Gt(t)} → ${Gt(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${Gt(t)}`),console.log(`Step 3 (Code Review): ${Gt($h)}`)}function Gh(){return{step1Result:y.step1Result,step2Result:y.step2Result,step3Result:y.step3Result,artifactBundle:y.artifactBundle,bundleReview:y.bundleReview,selectedArtifactId:y.selectedArtifactId}}function N0(t){if(!t)return;Object.assign(y,t),new Set((y.artifactBundle?.artifacts||[]).map(n=>n.id)).has(y.selectedArtifactId)||(y.selectedArtifactId=oi(y.artifactBundle)?.id||null)}const Kh="results-replacement-error";function O0(t,{stage:e=2,runId:n,retry:i}){if(!re(n))return;const r=document.getElementById(Kh);if(!r)return;const s=xh(t),o=document.getElementById("results-replacement-error-title"),a=document.getElementById("results-replacement-error-message"),l=document.getElementById("results-replacement-error-retry"),u=document.getElementById("results-replacement-error-upgrade");o&&(o.textContent=`${Gs[e]||"Regeneration"}: ${s.title}`),a&&(a.textContent=s.message),r.hidden=!1;let c=null;u&&(u.hidden=!s.canUpgrade,s.canUpgrade&&(u.textContent="View plans",u.onclick=()=>di(),c=u)),l&&(l.hidden=s.canUpgrade,s.canUpgrade||(l.onclick=()=>{ql(),typeof i=="function"&&i()},l.textContent="Retry",c=l)),(c||r).focus({preventScroll:!0})}function ql(){const t=document.getElementById(Kh);t&&(t.hidden=!0)}function Yh(t,{previous:e,stage:n,runId:i,retry:r}){re(i)&&(t.isUsageLimit&&un(),N0(e),cr(),nn(!0),ur(),to(),O0(t,{stage:n,runId:i,retry:r}),rn())}async function Jh(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0;const e=Ks();Vl("standardRegenerate",y.step2Result,y.step1Result);const n=document.querySelectorAll(".btn-refine-action"),i=Gh();n.forEach(r=>{r.disabled=!0,r.innerHTML=` + `)}function Ae(t,e){const n=document.getElementById(`step${t}-loading`),i=document.getElementById(`step${t}-result`);e?(n.classList.remove("hidden"),i.classList.add("hidden"),bs(t,"active")):(n.classList.add("hidden"),i.classList.remove("hidden"),bs(t,"completed"))}function M0(t){const e=document.getElementById(`${t}-content`),n=document.getElementById(`${t}-chevron`);e.classList.contains("open")?(e.classList.remove("open"),n&&(n.style.transform="rotate(0deg)")):(e.classList.add("open"),n&&(n.style.transform="rotate(180deg)"))}function L0(t){it(parseInt(t.replace("step","")))}function it(t){for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-item`);a&&a.classList.remove("active")}const e=document.getElementById(`step${t}-item`);e&&e.classList.add("active"),Nn();const n=document.getElementById("ready-state");n&&n.classList.add("hidden");for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-content`);a&&a.classList.add("hidden")}const i=document.getElementById(`step${t}-content`);i&&i.classList.remove("hidden");const r=document.getElementById("stage-title"),s={1:"Prompt Architect",2:"Code Generator",3:"Code Review"};r&&(r.textContent=s[t]||"Active Workflow Stage")}function N0(t){const e=document.getElementById(t);if(!e)return;const n=e.dataset.raw||e.textContent;navigator.clipboard.writeText(n).then(()=>{const r=e.closest(".code-container")?.querySelector(".copy-btn");r&&(r.classList.add("copied"),r.innerHTML=' Copied!',setTimeout(()=>{r.classList.remove("copied"),r.innerHTML=' Copy'},2e3))}).catch(i=>{console.warn("Failed to copy to clipboard:",i)})}function qa(t){const e=Va(t);console.log(`Step 1 (Prompt Architect): ${Gt(Mh)}`),console.log(e!==t?`Step 2 (Code Generator): ${Gt(t)} → ${Gt(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${Gt(t)}`),console.log(`Step 3 (Code Review): ${Gt(Lh)}`)}function Yh(){return{step1Result:y.step1Result,step2Result:y.step2Result,step3Result:y.step3Result,artifactBundle:y.artifactBundle,bundleReview:y.bundleReview,selectedArtifactId:y.selectedArtifactId}}function O0(t){if(!t)return;Object.assign(y,t),new Set((y.artifactBundle?.artifacts||[]).map(n=>n.id)).has(y.selectedArtifactId)||(y.selectedArtifactId=oi(y.artifactBundle)?.id||null)}const Jh="results-replacement-error";function B0(t,{stage:e=2,runId:n,retry:i}){if(!re(n))return;const r=document.getElementById(Jh);if(!r)return;const s=kh(t),o=document.getElementById("results-replacement-error-title"),a=document.getElementById("results-replacement-error-message"),l=document.getElementById("results-replacement-error-retry"),u=document.getElementById("results-replacement-error-upgrade");o&&(o.textContent=`${Vs[e]||"Regeneration"}: ${s.title}`),a&&(a.textContent=s.message),r.hidden=!1;let c=null;u&&(u.hidden=!s.canUpgrade,s.canUpgrade&&(u.textContent="View plans",u.onclick=()=>di(),c=u)),l&&(l.hidden=s.canUpgrade,s.canUpgrade||(l.onclick=()=>{Vl(),typeof i=="function"&&i()},l.textContent="Retry",c=l)),(c||r).focus({preventScroll:!0})}function Vl(){const t=document.getElementById(Jh);t&&(t.hidden=!0)}function Zh(t,{previous:e,stage:n,runId:i,retry:r}){re(i)&&(t.isUsageLimit&&un(),O0(e),cr(),nn(!0),ur(),eo(),B0(t,{stage:n,runId:i,retry:r}),rn())}async function Xh(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0;const e=Gs();Gl("standardRegenerate",y.step2Result,y.step1Result);const n=document.querySelectorAll(".btn-refine-action"),i=Yh();n.forEach(r=>{r.disabled=!0,r.innerHTML=` - Refining...`});try{ql();const r=Ol(),s=r.id,o=vv({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,artifactId:r.id,userFeedback:"Fix the issues listed in the audit report."});Xs({runId:e}),Ft(2,e),it(2),Ae(2,!0);const a=await Hs(o,t,[],e);if(!re(e))return;y.step2Result=a,Ds(),tn(2,e);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),it(3),Ft(3,e),Ae(3,!0);const c=await Ws(y.step2Result,y.step1Result);if(!re(e))return;y.step3Result=c,js(),tn(3,e),y.artifactBundle?.artifacts?.some(h=>h.id===s)?y.selectedArtifactId=s:y.selectedArtifactId=oi(y.artifactBundle)?.id||null;const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const f=Ns(y.step3Result);ur(u,f)}catch(r){if(console.error("Refinement failed:",r),!re(e))return;const s=Ls(r,{architect:2,generator:2,review:3});Yh(r,{previous:i,stage:s,runId:e,retry:Jh})}finally{n.forEach(r=>{r.disabled=!1,r.textContent="Refine & Regenerate"}),re(e)&&(y.isRunning=!1,rn())}}async function Vl(t,e,n){const i=`${_t}/connectFeedback`,r={type:t,code:e,input:n};try{const s=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok){const a=await s.text();return console.error(`callEndpoint failed: ${s.status} ${s.statusText}`,a),{success:!1,status:s.status,error:a}}const o=await s.json();return console.log("Telemetry success:",o),o}catch(s){return console.error("callEndpoint failed:",s),{success:!1,error:s.message}}}function B0(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function Zh(){const t=document.getElementById("ff-error-paste-input"),e=t?.value?.trim();if(!e){t?.focus(),t?.classList.add("ring-2","ring-red-400","border-red-300"),setTimeout(()=>t?.classList.remove("ring-2","ring-red-400","border-red-300"),2e3);return}if(!y.step2Result){Ee("No generated code found. Please run the full pipeline first.","warning");return}if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=Ks();Vl("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` + Refining...`});try{Vl();const r=Ol(),s=r.id,o=yv({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,artifactId:r.id,userFeedback:"Fix the issues listed in the audit report."});Zs({runId:e}),Ft(2,e),it(2),Ae(2,!0);const a=await Us(o,t,[],e);if(!re(e))return;y.step2Result=a,Bs(),tn(2,e);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),it(3),Ft(3,e),Ae(3,!0);const c=await Hs(y.step2Result,y.step1Result);if(!re(e))return;y.step3Result=c,Ds(),tn(3,e),y.artifactBundle?.artifacts?.some(h=>h.id===s)?y.selectedArtifactId=s:y.selectedArtifactId=oi(y.artifactBundle)?.id||null;const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const f=Ls(y.step3Result);ur(u,f)}catch(r){if(console.error("Refinement failed:",r),!re(e))return;const s=Ms(r,{architect:2,generator:2,review:3});Zh(r,{previous:i,stage:s,runId:e,retry:Xh})}finally{n.forEach(r=>{r.disabled=!1,r.textContent="Refine & Regenerate"}),re(e)&&(y.isRunning=!1,rn())}}async function Gl(t,e,n){const i=`${_t}/connectFeedback`,r={type:t,code:e,input:n};try{const s=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok){const a=await s.text();return console.error(`callEndpoint failed: ${s.status} ${s.statusText}`,a),{success:!1,status:s.status,error:a}}const o=await s.json();return console.log("Telemetry success:",o),o}catch(s){return console.error("callEndpoint failed:",s),{success:!1,error:s.message}}}function D0(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function Qh(){const t=document.getElementById("ff-error-paste-input"),e=t?.value?.trim();if(!e){t?.focus(),t?.classList.add("ring-2","ring-red-400","border-red-300"),setTimeout(()=>t?.classList.remove("ring-2","ring-red-400","border-red-300"),2e3);return}if(!y.step2Result){Ee("No generated code found. Please run the full pipeline first.","warning");return}if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=Gs();Gl("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` - Fixing…`);const s=Gh();try{ql();const o=sh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});Ip(),Xs({runId:i}),Ft(2,i),it(2),Ae(2,!0);const a=await Hs(o,n,[],i);if(!re(i))return;y.step2Result=a,Ds(),tn(2,i);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),it(3),Ft(3,i),Ae(3,!0);const c=await Ws(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,js(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const f=Ns(y.step3Result);ur(u,f),t&&(t.value="")}catch(o){if(console.error("Fix from errors failed:",o),!re(i))return;const a=Ls(o,{architect:2,generator:2,review:3});Yh(o,{previous:s,stage:a,runId:i,retry:Zh})}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function or(){if(console.log("runThinkingPipeline called"),y.isRunning)return;localStorage.setItem("hasSeenWalkthrough","true");const t=document.getElementById("pipeline-input").value,e=document.getElementById("code-generator-model").value,n=Oe.slice();if(!t.trim()){Ee("Please describe your FlutterFlow widget first.","warning");return}y.isRunning=!0;const i=Ks();try{if(await Ba,!re(i)||(pn.length&&await Promise.allSettled(pn.map(v=>v.job)),!re(i))||!await lw()||!re(i)||(await nw(),!re(i)))return;const r=Va(e);t.length,y0(),y.submittedPrompt=t,y.submittedImages=n.filter(v=>v.url),Ya(!0),qa(r),Nn();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const o=document.getElementById("paywall-exhausted");o&&o.classList.add("hidden"),Xs({prompt:t,runId:i}),Uw(),it(1),Ft(1,i),Ae(1,!0);const a=y.submittedImages.map(v=>({url:v.url})),l=await T0(t,a);if(!re(i))return;y.step1Result=l,w0(),tn(1,i);const u=document.getElementById("step1-output"),c=li(y.step1Result);u.textContent=c,u.dataset.raw=c,Ae(1,!1),it(2),Ft(2,i),Ae(2,!0);const d=await Hs(y.step1Result,r,a,i);if(!re(i))return;y.step2Result=d,Ds(),tn(2,i);const f=document.getElementById("step2-output"),h=li(y.step2Result);f.textContent=h,f.dataset.raw=h,Ae(2,!1),it(3),Ft(3,i),Ae(3,!0);const p=await Ws(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=p,js(),tn(3,i);const g=document.getElementById("step3-output");g.textContent=y.step3Result,Ae(3,!1),cr();const m=Ns(y.step3Result);Hw(),ur(h,m)}catch(r){if(r.isPipelineCancel||console.error("Pipeline failed:",r),!re(i))return;const s=Ls(r,{architect:1,generator:2,review:3});r.isUsageLimit?un():(r.message,Va(document.getElementById("code-generator-model").value),void 0),it(s),Ae(s,!1),bp(r,{stage:s,runId:i}),Es(s,"error")}finally{re(i)&&(y.isRunning=!1,Ya(!1),rn())}}function D0(){const t=document.getElementById("code-generator-model").value,e=[ms,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(i=>i!==t),n=prompt(`Retry with different model? + Fixing…`);const s=Yh();try{Vl();const o=oh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});Cp(),Zs({runId:i}),Ft(2,i),it(2),Ae(2,!0);const a=await Us(o,n,[],i);if(!re(i))return;y.step2Result=a,Bs(),tn(2,i);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),it(3),Ft(3,i),Ae(3,!0);const c=await Hs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,Ds(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const f=Ls(y.step3Result);ur(u,f),t&&(t.value="")}catch(o){if(console.error("Fix from errors failed:",o),!re(i))return;const a=Ms(o,{architect:2,generator:2,review:3});Zh(o,{previous:s,stage:a,runId:i,retry:Qh})}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function or(){if(console.log("runThinkingPipeline called"),y.isRunning)return;localStorage.setItem("hasSeenWalkthrough","true");const t=document.getElementById("pipeline-input").value,e=document.getElementById("code-generator-model").value,n=Oe.slice();if(!t.trim()){Ee("Please describe your FlutterFlow widget first.","warning");return}y.isRunning=!0;const i=Gs();try{if(await Oa,!re(i)||(pn.length&&await Promise.allSettled(pn.map(v=>v.job)),!re(i))||!await cw()||!re(i)||(await iw(),!re(i)))return;const r=Va(e);t.length,w0(),y.submittedPrompt=t,y.submittedImages=n.filter(v=>v.url),Ya(!0),qa(r),Nn();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const o=document.getElementById("paywall-exhausted");o&&o.classList.add("hidden"),Zs({prompt:t,runId:i}),Hw(),it(1),Ft(1,i),Ae(1,!0);const a=y.submittedImages.map(v=>({url:v.url})),l=await $0(t,a);if(!re(i))return;y.step1Result=l,b0(),tn(1,i);const u=document.getElementById("step1-output"),c=li(y.step1Result);u.textContent=c,u.dataset.raw=c,Ae(1,!1),it(2),Ft(2,i),Ae(2,!0);const d=await Us(y.step1Result,r,a,i);if(!re(i))return;y.step2Result=d,Bs(),tn(2,i);const f=document.getElementById("step2-output"),h=li(y.step2Result);f.textContent=h,f.dataset.raw=h,Ae(2,!1),it(3),Ft(3,i),Ae(3,!0);const p=await Hs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=p,Ds(),tn(3,i);const g=document.getElementById("step3-output");g.textContent=y.step3Result,Ae(3,!1),cr();const m=Ls(y.step3Result);Ww(),ur(h,m)}catch(r){if(r.isPipelineCancel||console.error("Pipeline failed:",r),!re(i))return;const s=Ms(r,{architect:1,generator:2,review:3});r.isUsageLimit?un():(r.message,Va(document.getElementById("code-generator-model").value),void 0),it(s),Ae(s,!1),Sp(r,{stage:s,runId:i}),bs(s,"error")}finally{re(i)&&(y.isRunning=!1,Ya(!1),rn())}}function j0(){const t=document.getElementById("code-generator-model").value,e=[ms,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(i=>i!==t),n=prompt(`Retry with different model? Current: ${t} @@ -140,10 +140,10 @@ Options: 1. ${e[0]} 2. ${e[1]} -Enter 1 or 2:`);n==="1"?(document.getElementById("code-generator-model").value=e[0],or()):n==="2"&&(document.getElementById("code-generator-model").value=e[1],or())}async function j0(){const t=Bl();if(!t){Ee("No code to commit. Please run the pipeline first.","warning");return}const e=await Te("flutterflow"),n=await Te("flutterflow_project_id");if(!e||!n){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),Tl();return}if(y.artifactBundle?.artifacts?.length>1){await U0();return}const{artifactType:i,artifactName:r,fileName:s}=Uh(),o=Vh(t,{artifactType:i,artifactName:r,fileName:s}),a=I0(o);if(!a.canProceed){Ee(`Pre-commit checks failed: ${a.issues.join("; ")}`,"error");return}Yl(o,a,null,null)}async function U0(){const t=await Te("flutterflow"),e=await Te("flutterflow_project_id");if(!t||!e){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),Tl();return}const n=e_(y.artifactBundle);if(n.errors.length>0){Ee(`Bundle validation failed: ${n.errors.join("; ")}`,"error");return}const i=new Map(n.fileEntries.map(a=>[a.fileName,{content:a.content,type:a.type,path:a.path}])),r=Us(i),s={canProceed:r.valid&&n.errors.length===0,issues:[...n.errors,...r.errors],warnings:[...n.warnings,...r.warnings]};if(!s.canProceed){Ee(`Bundle validation failed: ${s.issues.join("; ")}`,"error");return}const o={content:n.fileEntries.map(a=>`// ${a.fileName} +Enter 1 or 2:`);n==="1"?(document.getElementById("code-generator-model").value=e[0],or()):n==="2"&&(document.getElementById("code-generator-model").value=e[1],or())}async function U0(){const t=Bl();if(!t){Ee("No code to commit. Please run the pipeline first.","warning");return}const e=await Te("flutterflow"),n=await Te("flutterflow_project_id");if(!e||!n){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),Tl();return}if(y.artifactBundle?.artifacts?.length>1){await H0();return}const{artifactType:i,artifactName:r,fileName:s}=Wh(),o=Kh(t,{artifactType:i,artifactName:r,fileName:s}),a=k0(o);if(!a.canProceed){Ee(`Pre-commit checks failed: ${a.issues.join("; ")}`,"error");return}Jl(o,a,null,null)}async function H0(){const t=await Te("flutterflow"),e=await Te("flutterflow_project_id");if(!t||!e){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),Tl();return}const n=n_(y.artifactBundle);if(n.errors.length>0){Ee(`Bundle validation failed: ${n.errors.join("; ")}`,"error");return}const i=new Map(n.fileEntries.map(a=>[a.fileName,{content:a.content,type:a.type,path:a.path}])),r=js(i),s={canProceed:r.valid&&n.errors.length===0,issues:[...n.errors,...r.errors],warnings:[...n.warnings,...r.warnings]};if(!s.canProceed){Ee(`Bundle validation failed: ${s.issues.join("; ")}`,"error");return}const o={content:n.fileEntries.map(a=>`// ${a.fileName} ${a.content}`).join(` -`),fileName:`${n.fileEntries.length} files`,codeType:"bundle",artifactType:"Bundle",artifactName:n.title};Yl(o,s,n.dependencies,n)}function H0(t){let e=t.errorMap||new Map;!(e instanceof Map)&&typeof e=="object"&&(e=new Map(Object.entries(e)));let n=`
      +`),fileName:`${n.fileEntries.length} files`,codeType:"bundle",artifactType:"Bundle",artifactName:n.title};Jl(o,s,n.dependencies,n)}function W0(t){let e=t.errorMap||new Map;!(e instanceof Map)&&typeof e=="object"&&(e=new Map(Object.entries(e)));let n=`

      FlutterFlow Commit Failed

      ${z(t.error)}

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

      Errors:

      @@ -156,7 +156,7 @@ ${a.content}`).join(` Fix Errors & Regenerate -
      `;const i=document.getElementById("step3-output");i&&(i.innerHTML=n,document.getElementById("btn-regenerate-from-error")?.addEventListener("click",()=>{Xh(t.error,e)}))}async function Xh(t,e){if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=Ks(),r=document.getElementById("btn-regenerate-from-error");r&&(r.disabled=!0,r.innerHTML=` +
      `;const i=document.getElementById("step3-output");i&&(i.innerHTML=n,document.getElementById("btn-regenerate-from-error")?.addEventListener("click",()=>{ep(t.error,e)}))}async function ep(t,e){if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=Gs(),r=document.getElementById("btn-regenerate-from-error");r&&(r.disabled=!0,r.innerHTML=` Fixing...`);try{let s=`The previous code had the following errors when committing to FlutterFlow: @@ -164,8 +164,8 @@ ${a.content}`).join(` Error: ${g} `}else s+=`${t} -`;const o=sh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:s});Xs({runId:i}),Ft(2,i),it(2),Ae(2,!0);const a=await Hs(o,n,[],i);if(!re(i))return;y.step2Result=a,Ds(),tn(2,i);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),it(3),Ft(3,i),Ae(3,!0);const c=await Ws(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,js(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const f=Ns(y.step3Result);ur(u,f)}catch(s){if(console.error("Regeneration failed:",s),!re(i))return;const o=Ls(s,{architect:2,generator:2,review:3});s.isUsageLimit&&un(),it(o),Ae(o,!1),bp(s,{stage:o,runId:i,retry:()=>Xh(t,e)}),Es(o,"error")}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function W0(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const n=await Te("flutterflow"),i=await Te("flutterflow_project_id");n&&i?(t.className="w-2 h-2 rounded-full bg-green-500",e.textContent="FlutterFlow credentials configured",e.className="text-green-600"):n||i?(t.className="w-2 h-2 rounded-full bg-yellow-500",e.textContent="FlutterFlow credentials incomplete",e.className="text-yellow-600"):(t.className="w-2 h-2 rounded-full bg-red-500",e.textContent="FlutterFlow credentials not configured",e.className="text-red-600")}async function Qh(t){try{const e=await fetch(`${_t}/auth/send-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:t})});if(!e.ok)throw new Error(`Failed to send magic link: HTTP ${e.status}`);return e.json()}catch(e){throw console.error("sendMagicLink failed:",{email:t,message:e.message,stack:e.stack}),e}}async function z0(t){try{const n=await(await fetch(`${_t}/auth/verify-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})})).json();if(n.error||!n.email||!n.sessionToken)throw new Error(n.error||"Invalid or expired link");return n}catch(e){throw console.error("verifyMagicLink failed:",{message:e.message,stack:e.stack}),e}}async function q0(t){try{const e=await fetch(`${_t}/auth/refresh-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:t})});if(!e.ok)return console.error("refreshSession: non-OK response",{url:`${_t}/auth/refresh-session`,status:e.status}),null;const n=await e.json();return n.error||!n.email||!n.sessionToken?(console.warn("refreshSession: validation failed",{error:n.error,hasEmail:!!n.email,hasToken:!!n.sessionToken}),null):n}catch(e){return console.error("refreshSession: fetch failed",{url:`${_t}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function rd(t,e){const n=tp(),i=(q.email||n.email)!==t;q.email=t,q.sessionToken=e,q.isVerified=!0,ce=Mn({isLoading:!0}),localStorage.setItem(hs,JSON.stringify({email:t,sessionToken:e})),i&&ap()}function ep(){q.email=null,q.sessionToken=null,q.isVerified=!1,ce=Mn({isResolved:!0}),localStorage.removeItem(hs),localStorage.removeItem(gs)}function tp(){try{const t=localStorage.getItem(hs);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(hs),{email:null,sessionToken:null}}}async function V0(){const e=new URLSearchParams(window.location.search).get("token");if(e){window.history.replaceState({},"",window.location.pathname+window.location.hash);try{const{email:n,sessionToken:i}=await z0(e);rd(n,i),np();const r=sd();r&&!window.location.hash&&(window.location.hash=r)}catch(n){sd();const i=n.message||"Sign-in link invalid or expired.";Ee(i,"error"),zs(),Jn(i,"error")}}else{const{email:n,sessionToken:i}=tp();if(n&&i){const r=await q0(i);r?rd(r.email,r.sessionToken):ep()}}Gl()}function G0(){try{localStorage.setItem(Oa,JSON.stringify({hash:window.location.hash||"#home",ts:Date.now()}))}catch(t){console.warn("rememberSignInReturnSurface: failed to persist return surface:",t)}}function sd(){try{const t=localStorage.getItem(Oa);if(localStorage.removeItem(Oa),!t)return null;const{hash:e,ts:n}=JSON.parse(t);return!e||typeof n!="number"||Date.now()-n>Py?null:e}catch(t){return console.warn("consumeSignInReturnSurface: failed to read return surface:",t),null}}function zs(){const t=document.getElementById("signin-modal");if(!t)return;G0(),document.getElementById("signin-email-input")?.removeAttribute("aria-invalid"),Jn(""),We(t)}function np(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&ze(e)}function Jn(t,e){const n=document.getElementById("signin-message");n&&(n.textContent=t||"",n.classList.remove("signin-message-success","signin-message-error"),e&&n.classList.add(`signin-message-${e}`))}async function K0(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),n=Rs(t?.value);if(!n||!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(n)||n.length>254){t?.setAttribute("aria-invalid","true"),Jn("Please enter a valid email address.","error");return}t?.removeAttribute("aria-invalid"),e&&(e.disabled=!0,e.textContent="Sending…");const r=hh(n);r&&Jn(r,"error");try{const s=await Qh(n),o=s?.code===fh;t&&!o&&(t.value=""),t?.setAttribute("aria-invalid",String(o)),Jn(ph(s,n),o?"error":"success"),e&&(e.disabled=!1,e.textContent=o?"Send Sign-in Link":"Sent!",o||setTimeout(()=>{e.textContent==="Sent!"&&(e.textContent="Send Sign-in Link")},2500))}catch(s){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:n,err:s}),Jn("Something went wrong. Please try again.","error"),e&&(e.disabled=!1,e.textContent="Send Sign-in Link")}}function Y0(){q.email=null,q.sessionToken=null,q.isVerified=!1,ce=Mn({isResolved:!0}),O_({storage:window.localStorage,onIdentityChanged:Gl,onPlanChanged:Vs})}const J0=B_({sendLink:Qh,getEmail:()=>q.email||"",onState:Z0});function Z0(t){const e=document.getElementById("send-new-link-btn"),n=document.getElementById("send-new-link-msg");if(!e||!n)return;if(t.status==="pending"){e.disabled=!0,e.textContent="Sending…",n.className="acct-access-msg",n.textContent="Sending a fresh sign-in link…";return}if(t.status==="sent"){e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg",n.textContent=ph(t.data,q.email||"")||"Link sent — check your email.";return}e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg error";const i=t.error?.message?`Couldn't send a link right now. ${t.error.message}`:"Couldn't send a link right now. Please try again.";n.textContent=i}async function X0(){await J0()}function Q0(){const t=L_(window.localStorage),e=t.length?`Cleared disposable UI caches: ${t.join(", ")}.`:"Nothing disposable to clear.";Ee(`${e} Your run count, identity and stored keys are kept.`,"info")}function ew(){const t=document.getElementById("delete-unavailable-modal");t&&We(t,{trigger:document.activeElement})}function tw(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("delete-unavailable-modal");e&&ze(e)}function Gl(){const t=q.isVerified&&!!q.email,e=document.getElementById("auth-signedout"),n=document.getElementById("auth-signedin"),i=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),n&&n.classList.toggle("hidden",!t),i&&i.classList.toggle("hidden",t);const r=document.getElementById("auth-user-email");r&&(r.textContent=q.email||"");const s=document.getElementById("access-signed-email");s&&(s.textContent=q.email||""),dw(),Vs()}async function ip(){try{if(typeof FingerprintJS>"u"){console.warn("resolveIdentity: FingerprintJS not loaded, skipping");return}const e=await(await FingerprintJS.load()).get(),n=e.visitorId,i=await fetch($y,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fingerprint:e.visitorId,cookie_id:n})});if(!i.ok)throw new Error(`Identity check HTTP ${i.status}`);const r=await i.json();if(ht.userId=r.user_id,ht.token=r.identity_token||null,ht.status=r.status,ht.resolved=!0,sessionStorage.setItem(Ry,r.user_id),ht.token&&sessionStorage.setItem(Ty,ht.token),r.usage_count!==void 0){const s=gn(),a=(r.usage_month||s)===s?r.usage_count:0;localStorage.setItem(Fn,JSON.stringify({count:a,month:s})),un()}console.log(`Identity resolved: ${r.status} (${r.user_id.slice(0,8)}...) usage: ${r.usage_count??"n/a"}`)}catch(t){console.error("resolveIdentity failed:",t)}}let zo=null;function nw(t=5e3){return ht.resolved?Promise.resolve():(zo||(zo=ip().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([zo,new Promise(e=>setTimeout(e,t))]))}function rp(){const t=gn();try{const e=localStorage.getItem(Fn);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Fn,month:t,err:e}),localStorage.removeItem(Fn),{count:0,month:t}}}function gn(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function lr(){const t=rp();return t.month!==gn()?{count:0,month:gn()}:t}function iw(){const e={count:lr().count+1,month:gn()};return localStorage.setItem(Fn,JSON.stringify(e)),e}function pi(){return!!ce.isLoading}function Tt(){return!!ce.isResolved}function rw(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(ps,e)?e:null}function sw(t){return t&&Object.entries(kh).find(([,e])=>e===t)?.[0]||null}function Cr(...t){return t.find(e=>e!=null&&e!=="")}function ow(...t){return t.find(e=>e&&typeof e=="object")||{}}function aw(t){const e=t.data&&typeof t.data=="object"?t.data:t,n=ow(e.subscription,e.stripeSubscription,e.currentSubscription,e.customer?.subscriptions?.data?.[0],e.subscriptions?.data?.[0],e.subscriptions?.[0]),i=e.metadata||n.metadata||e.customer?.metadata||{},r=Cr(e.priceId,e.price_id,e.stripePriceId,e.stripe_price_id,n.priceId,n.price_id,n.plan?.id,n.price?.id,n.items?.data?.[0]?.price?.id,n.items?.[0]?.price?.id,n.lines?.data?.[0]?.price?.id),s=Cr(e.status,e.subscriptionStatus,e.subscription_status,n.status,"none"),o=rw(Cr(e.tier,e.plan,e.planId,e.plan_id,e.subscriptionTier,e.subscription_tier,e.product,e.productName,n.tier,n.plan,i.tier,i.plan)),a=My.has(String(s).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||sw(r)||(a||l?"professional":"free");return Mn({tier:u,status:s,periodEnd:Cr(e.periodEnd,e.currentPeriodEnd,e.current_period_end,n.current_period_end,n.periodEnd,null),isResolved:!0})}function qs(){return ps[ce.tier]??ps.free}async function lw(){if(q.isVerified&&(!Tt()||pi())&&(await op({force:!0}),Vs()),q.isVerified&&!Tt())return Ee("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=lr(),e=qs();if(t>=e)return sp(t,e,{openModal:!0}),!1;const n=Math.floor(e*.8);if(t>=n){const i=e-t;Ee(`${i} run${i===1?"":"s"} remaining this month.`,"warning")}return!0}function od(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function sp(t,e,n={}){nn(!0);const i=document.getElementById("walkthrough-modal");i&&ze(i,{restoreFocus:!1});const r=document.getElementById("ready-state");r&&r.classList.add("hidden");const s=document.getElementById("preview-frame-container");s&&(s.style.display="none");const o=document.getElementById("main-stage-container");o&&o.classList.add("visible");const a=document.getElementById("results-view");a&&a.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar");const l=document.getElementById("pipeline-progress");l&&l.classList.remove("visible");const u=document.getElementById("paywall-exhausted");if(!u){Ee(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),di();return}const c=document.getElementById("paywall-exhausted-text");if(c){const f=ce.tier;f==="free"?c.textContent=`You've used all ${e} free generations this month. Upgrade to Pro for 50 generations/month and access to all AI models.`:c.textContent=`You've used all ${e} generations this month on your ${f} plan. Your limit resets next month.`}const d=document.getElementById("paywall-signin-btn");d&&d.classList.toggle("hidden",q.isVerified),u.classList.remove("hidden"),n.openModal&&di()}function Va(t){return ce.tier==="free"&&Nr.includes(t)?ms:t}function cw(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const n=ce.tier,r=!(q.isVerified&&!Tt())&&n==="free";Array.from(e.options).forEach(o=>{const a=Gt(o.value),l=Nr.includes(o.value);o.textContent=l&&r?`${a} (PRO)`:a,o.disabled=!1}),r&&Nr.includes(e.value)&&(e.value=ms),e.disabled=!1,Gu.has(e)||(e.addEventListener("change",()=>{Tt()&&ce.tier==="free"&&Nr.includes(e.value)&&(e.value=ms,di()),qa(e.value),Cl()}),Gu.add(e));let s=document.getElementById("model-selector-free-notice");r?(s||(s=document.createElement("p"),s.id="model-selector-free-notice",s.className="text-xs text-gray-400 mt-1",t.appendChild(s)),s.innerHTML='Free plan — Gemini only. '):s&&s.remove(),qa(e.value)}function Kl(){const t=q.isVerified&&!!q.email,e=t&&pi(),n=!t||Tt(),i=lr(),r=n?i.count:0,s=n?qs():0,o=Math.max(0,s-r),a=`${r} / ${s} runs this month`,l=ml,u=n?ce.tier||"free":null,c=document.getElementById("topbar-credits-count");c&&(e?c.textContent="…":n?c.textContent=String(o):c.textContent="—");const d=document.getElementById("credits-balance");d&&(e?d.textContent="Checking plan…":n?d.textContent=a:d.textContent="Plan check failed");const f=document.getElementById("usage-dialog-tier");f&&(e?f.textContent="Checking…":n?f.textContent=l[u]||"Free":f.textContent="Unavailable");const h=document.getElementById("usage-dialog-status");h&&(e?h.textContent="Verifying your subscription…":n?h.textContent="Runs reset at the start of each month.":h.textContent="Could not verify your subscription. Try again or sign out.");const p=document.getElementById("usage-counter");if(p)if(e&&t)p.textContent="Checking plan…",p.className="text-xs text-gray-500";else if(!n&&t)p.textContent="Plan check failed",p.className="text-xs text-red-600 font-medium";else{p.textContent=a;const g=s>0?r/s:0;p.className=g>=1?"text-xs text-red-600 font-medium":g>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500"}if(!t){const g=document.getElementById("guest-usage-text");if(g){const m=rp(),v=m.month===gn()?m.count??0:0;g.textContent=`${v} / ${ps.free} generations used`}}uw()}function uw(){if(!(q.isVerified&&!!q.email))return;const e=pi(),n=Tt(),i=lr(),r=n?i.count:0,s=n?qs():0,o=Math.max(0,s-r),a=n?ce.tier||"free":null,l={free:"Free",professional:"Pro",power:"Power"}[a]||"Free",u=q.email||"",c=u.split("@")[0]||u,d=document.getElementById("acct-avatar");d&&(d.textContent=(u[0]||"?").toUpperCase());const f=document.getElementById("acct-name");f&&(f.textContent=c||"—");const h=document.getElementById("acct-plan-tier"),p=document.getElementById("acct-plan-price"),g=document.getElementById("acct-plan-note"),m=document.getElementById("acct-renewal");if(h&&(h.textContent=e?"Checking…":n?l:"Plan unavailable"),p)if(e)p.textContent="—";else if(!n)p.textContent="—";else if(a==="free")p.textContent="$0 / month";else{const x=Oi(Ni[a]??0,Al());p.textContent=`${x} / month`}if(g&&(e?g.textContent="Verifying your subscription…":n?a==="free"?g.textContent="No subscription. Upgrade for more generations.":g.textContent="billed monthly through Stripe":g.textContent="Could not verify your subscription. Check billing or sign out."),m){const x=Date.parse(ce.periodEnd||""),F=n&&a!=="free"&&!!ce.periodEnd&&!Number.isNaN(x);if(e)m.textContent="";else if(!n)m.textContent="";else if(a==="free")m.textContent="";else if(F){const $=new Date(x).toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"});m.textContent=`Renews ${$} · reset at the start of each month.`}else m.textContent="Renewal date is not available for this period."}const v=document.getElementById("acct-left-count"),E=document.getElementById("acct-left-limit"),S=document.getElementById("acct-reset-note");v&&(v.textContent=e?"…":n?String(o):"—"),E&&(E.textContent=e?"…":n?String(s):"—"),S&&(e?S.textContent="Checking plan…":n?S.textContent="Runs reset at the start of each month.":S.textContent="Plan check failed. Refresh or manage billing.");const _=document.getElementById("acct-used-count"),b=document.getElementById("acct-meter-fill"),k=document.getElementById("acct-meter-meta"),T=document.getElementById("acct-meter-track");if(_&&(_.textContent=e?"…":n?String(r):"—"),b){const x=n&&s>0?Math.min(100,Math.round(r/s*100)):0;b.style.width=`${x}%`}if(k)if(e)k.textContent="Checking…";else if(!n)k.textContent="Plan check failed";else if(s===0)k.textContent=`${r} of ${s}`;else{const x=Math.round(r/s*100);k.textContent=`${r} of ${s} · ${x}%`}T&&(e?T.setAttribute("aria-label","Checking usage…"):n?T.setAttribute("aria-label",`${r} of ${s} generations used`):T.setAttribute("aria-label","Usage unavailable")),vt()}function un(){if(Kl(),q.isVerified&&(pi()||!Tt())){od();return}const{count:t}=lr(),e=qs();t>=e&&!y.isRunning?sp(t,e):od()}function dw(){Kl()}async function op(t={}){const e=t.force===!0;if(!q.isVerified||!q.sessionToken){ce=Mn({isResolved:!0});return}ce={...ce,isLoading:!0,error:null};const n=localStorage.getItem(gs);if(!e&&n)try{const{data:i,email:r,ts:s,version:o}=JSON.parse(n);if(o===Ku&&r===q.email&&Date.now()-s<300*1e3){ce={...i,isLoading:!1,isResolved:i.isResolved!==!1};return}}catch(i){console.warn("Failed to parse subscription cache:",i,"| raw value:",n)}try{const r=await(await fetch(`${_t}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:q.sessionToken,user_id:ht.userId})})).json();if(r.error){if(["unauthorized","invalid session","expired session"].some(o=>String(r.error).toLowerCase().includes(o))){ep(),Gl();return}ce=Mn({isResolved:!1,error:r.error});return}ce=aw(r),localStorage.setItem(gs,JSON.stringify({version:Ku,data:ce,email:q.email,ts:Date.now()}))}catch(i){console.error("fetchSubscription failed:",i),ce={...ce,isLoading:!1,isResolved:!1,error:i.message}}}function ap(){localStorage.removeItem(gs)}async function fw(t){if(!q.isVerified||!q.sessionToken){lp(),zs();return}if(!kh[t]){Ee("Invalid plan selected.","error");return}const e=document.getElementById(`checkout-btn-${t}`);e&&(e.disabled=!0,e.textContent="Redirecting…");try{const i=await(await fetch(`${_t}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:q.sessionToken,currency:Al()})})).json();if(i.error||!i.url)throw new Error(i.error||"Failed to create checkout session");const{url:r}=i;window.location.href=r}catch(n){console.error("startCheckout failed:",n),e&&(e.disabled=!1,e.textContent="Subscribe"),Ee("Could not start checkout. Please try again.","error")}}async function hw(t){if(!q.isVerified||!q.sessionToken){zs();return}const e=t||document.getElementById("manage-billing-btn"),n=e?e.textContent:"";e&&(e.disabled=!0,e.textContent="Loading…");try{const r=await(await fetch(`${_t}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:q.sessionToken})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to open billing portal");const{url:s}=r;window.location.href=s}catch(i){console.error("openCustomerPortal failed:",i),e&&(e.disabled=!1,e.textContent=n),Ee("Could not open billing portal. Please try again.","error")}}const Ss=new Set;function pw(){Ss.forEach(t=>t.abort()),Ss.clear()}async function xs(t,e,n,i={},r=[]){const o=new AbortController;Ss.add(o);let a=!1;const l=setTimeout(()=>{a=!0,o.abort()},12e4);try{const u=await fetch(Fy,{method:"POST",headers:{"Content-Type":"application/json",...ht.token?{Authorization:`Bearer ${ht.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:ht.userId,step:t,model:e,prompt:n,images:r,context:i})}),c=await u.text();let d={};try{d=c?JSON.parse(c):{}}catch{d={}}if(u.status===429){d.serverCount!==void 0&&(localStorage.setItem(Fn,JSON.stringify({count:d.serverCount,month:gn()})),un());const p=new Error(d.message||"Monthly usage limit reached. Upgrade to continue.");throw p.isUsageLimit=!0,p.pipelineStep=t,p}const f=xv(d,t);if(f)throw f;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(d),"content type:",typeof d.content),!u.ok)throw new Error(`${d.message||d.error||"BuildShip pipeline error"} (HTTP ${u.status})`);if(t==="generator")if(d.usage_status==="success"&&Number.isFinite(d.usage_count)){const p=gn();(d.usage_month||p)===p&&(localStorage.setItem(Fn,JSON.stringify({count:d.usage_count,month:p})),un())}else iw(),un();let h=d.output||d.content;if(!h){const p=c?` (body: ${c.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${p}`)}return Array.isArray(h)&&(h=h.map(p=>typeof p=="string"?p:p.text||"").join("")),typeof h!="string"&&(h=JSON.stringify(h)),h}catch(u){if(u.name==="AbortError"){if(a)throw new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`);const c=new Error(`BuildShip ${t} request cancelled`);throw c.isPipelineCancel=!0,c}throw u instanceof TypeError?new Error(`BuildShip unreachable: ${u.message}`):u}finally{clearTimeout(l),Ss.delete(o)}}let Ga=!1;function gw(){const e=new URLSearchParams(window.location.search).get("checkout");return e==="success"?(window.history.replaceState({},"",window.location.pathname+window.location.hash),ap(),Ga=!0):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname+window.location.hash),Ee("Checkout cancelled.","info")),e}function mw(){if(!Ga)return;Ga=!1;const t=ce.tier!=="free";Ee(t?"Subscription active! Your plan is live.":"Checkout complete — confirming your subscription. Check Manage billing if it does not update.",t?"success":"info")}function Vs(){const t=q.isVerified&&!!q.email,e=ce.tier,n=t&&pi(),i=!t||Tt(),r=document.getElementById("subscription-tier-badge");if(r){const a=ml,l={free:"bg-gray-100 text-gray-600",professional:"bg-indigo-100 text-indigo-700",power:"bg-purple-100 text-purple-700",unresolved:"bg-red-50 text-red-600"};r.textContent=n?"Checking…":i?a[e]||"Free":"Plan unavailable",r.className=`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${i?l[e]||l.free:l.unresolved}`}const s=document.getElementById("upgrade-prompt");s&&s.classList.toggle("hidden",!t||n||!i||e!=="free");const o=document.getElementById("manage-billing-btn");o&&o.classList.toggle("hidden",!t||n||i&&e==="free"),vw(i?e:null),cw(),Cl(),un(),kp()}function vw(t){const e=["bg-gray-100","text-gray-500","cursor-default"];Object.entries({professional:{btnId:"checkout-btn-professional",defaultText:"Subscribe"},power:{btnId:"checkout-btn-power",defaultText:"Subscribe"}}).forEach(([r,{btnId:s,defaultText:o}])=>{const a=document.getElementById(s);a&&(r===t?(a.disabled=!0,a.textContent="Current plan",a.classList.add(...e)):(a.disabled=!1,a.textContent=o,a.classList.remove(...e)))});const i=document.getElementById("free-tier-current");i&&i.classList.toggle("hidden",t!=="free")}function _w(){document.querySelectorAll(".pm-card[data-tier]").forEach(t=>{const e=t.dataset.tier,n=dv[e];if(!n)return;const i=t.querySelector("ul.pm-features");if(i){i.innerHTML="";for(const r of n){const s=document.createElement("li");s.textContent=r,i.appendChild(s)}}})}function Ka(){const t=Al(),e=document.getElementById("pro-price"),n=document.getElementById("power-price"),i=document.getElementById("plans-pro-price"),r=document.getElementById("plans-power-price"),s=document.getElementById("pro-price-note"),o=document.getElementById("power-price-note"),a=document.getElementById("plans-pro-price-note"),l=document.getElementById("plans-power-price-note");e&&(e.textContent=Oi(Ni.professional,t)),n&&(n.textContent=Oi(Ni.power,t)),i&&(i.textContent=Oi(Ni.professional,t)),r&&(r.textContent=Oi(Ni.power,t));const u="billed monthly";s&&(s.textContent=u),o&&(o.textContent=u),a&&(a.textContent=u),l&&(l.textContent=u)}function di(){Ka();const t=document.getElementById("pricing-modal");t&&We(t),qy().then(()=>Ka())}function lp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&ze(e)}function Ee(t,e="info"){const n={success:"bg-green-600 text-white",error:"bg-red-600 text-white",warning:"bg-amber-500 text-white",info:"bg-gray-800 text-white"},i=document.createElement("div");i.className=`fixed bottom-6 left-1/2 -translate-x-1/2 px-5 py-3 rounded-lg text-sm font-medium shadow-lg z-50 transition-opacity duration-300 ${n[e]||n.info}`,i.textContent=t,document.body.appendChild(i),setTimeout(()=>{i.style.opacity="0",setTimeout(()=>i.remove(),300)},3500)}document.addEventListener("DOMContentLoaded",async()=>{lv(),hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),yw(),window.__heroField=ny(),window.__pipelineLogo=oy(),Ah=Cy({onSubmit:or}),Ba=(async()=>{try{await V0(),gw(),await op()}catch(n){console.warn("Startup auth/subscription initialization failed:",n)}})(),await Ba,mw(),Vs(),Ka(),_w(),await b0(),m0();const t=document.getElementById("flutterflow-endpoint-select");if(t){const n=yt();t.value=n}jh(),ip();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{en===2&&e.value.trim().length>0&&($l(),Os())}),e.addEventListener("blur",()=>{const n=document.getElementById("walkthrough-modal");en===2&&n&&We(n)}),e.addEventListener("keydown",n=>{if(n.key==="Tab"){const i=document.getElementById("walkthrough-modal");en===2&&i&&setTimeout(()=>{We(i)},100)}})),window.addEventListener("commitStateChange",n=>{const{state:i}=n.detail;i===ee.PREPARING||i===ee.VALIDATING||i===ee.PUSHING?(Be.phaseId||pp(),ld(i)):(i===ee.SUCCESS||i===ee.ERROR)&&(ld(i),setTimeout(Zl,1e3))}),rc()});function yw(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function ww(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Nn),document.addEventListener("keydown",Nn))}function Nn(){const t=document.getElementById("preview-frame-container"),e=document.getElementById("main-stage-container"),n=document.getElementById("ready-state");t&&(t.style.display="none"),e&&e.classList.add("visible"),n&&n.classList.remove("hidden");const i=document.getElementById("welcome-video-player");i&&i.removeEventListener("click",Nn),document.removeEventListener("keydown",Nn),jh()}let qi=null;async function bw(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++Qu,n=()=>e===Qu,i=await Te("flutterflow"),r=await Te("flutterflow_project_id");if(n()){if(!i){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const o=await new hi(i,"","main",yt()).listProjects();if(!n())return;if(!o||o.length===0){t.innerHTML='';return}t.innerHTML='',o.forEach(a=>{const l=document.createElement("option");l.value=a.id||a.projectId||"",l.textContent=a.name||a.projectName||`Project ${a.id}`,t.appendChild(l)}),r&&(t.value=r)}catch(s){if(!n())return;console.error("Failed to load projects for deploy:",s),t.innerHTML=''}}}function Ew(){return document.getElementById("confirm-project-select")?.value?.trim()||null}function Yl(t,e,n,i=null){qi={codeInfo:t,checks:e,deps:n,bundlePlan:i},document.getElementById("confirm-file-name").textContent=t.fileName,document.getElementById("confirm-artifact-type").textContent=t.artifactType,document.getElementById("confirm-file-size").textContent=`${(t.content.length/1024).toFixed(1)} KB`,document.getElementById("confirm-line-count").textContent=i?`${i.fileEntries.length} files`:t.content.split(` -`).length,bw();const r=document.getElementById("confirm-deps-list"),s=document.getElementById("confirm-deps-section");n&&Object.keys(n).length>0?(r.innerHTML=Object.entries(n).map(([u,c])=>{const d=c?`at least ${Qt(c)}`:"version resolved from your project";return`
    • • ${Qt(u)}: ${d}
    • `}).join(""),s.classList.remove("hidden")):s.classList.add("hidden");const o=document.getElementById("confirm-warnings-list"),a=document.getElementById("confirm-warnings-section");e.warnings&&e.warnings.length>0?(o.innerHTML=e.warnings.map(u=>`
    • • ${Qt(u)}
    • `).join(""),a.classList.remove("hidden")):a.classList.add("hidden"),document.getElementById("confirm-code-preview").textContent=t.content,document.getElementById("code-preview-content").classList.add("hidden"),document.getElementById("code-preview-chevron").style.transform="rotate(0deg)";const l=document.getElementById("commit-confirm-modal");l&&We(l)}function cp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&ze(e),qi=null}function Sw(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&ze(e);const n=["success-message","success-project-id","success-file-name","success-artifact-type","success-time","success-size"];for(const s of n){const o=document.getElementById(s);o&&(o.textContent="")}const i=document.getElementById("success-warnings-section");i&&i.classList.add("hidden");const r=document.getElementById("success-warnings-list");r&&(r.innerHTML="")}function up(t){const e=(m,v)=>{const E=document.getElementById(m);E&&(E.textContent=v||"")},n=t.metadata?.fileName||"",i=t.metadata?.projectId||"",r=t.metadata?.artifactType||"",s=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",i),e("success-file-name",n),e("success-artifact-type",r),e("success-time",s),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&i&&(u.href=`https://app.flutterflow.io/project/${i}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),f=t.unverified||[],h=t.approximate||[],p=t.warnings||[];(p.length>0||f.length>0||h.length>0)&&c&&d&&(d.innerHTML=[...f.map(m=>`
    • Not verified before deploying: ${z(String(m))}
    • `),...h.map(m=>`
    • Verified approximately: ${z(String(m))}
    • `),...p.map(([m,v])=>`
    • ${z(m)}: ${z(String(v))}
    • `)].join(""),c.classList.remove("hidden"));const g=document.getElementById("commit-success-modal");g&&We(g)}function dp(t){Zl(),H0(t);const e=t.remoteRefusal===!0;Jl(t,{heading:"Deploy failed",title:e?"FlutterFlow refused this deploy — nothing was confirmed written.":"The deploy failed before FlutterFlow confirmed anything.",guidance:e?"Review the error and any per-file outcomes above, fix them in your code or in FlutterFlow, then deploy again. A refusal is definitive: no part of this deploy was applied, so retrying is safe once the problem is fixed.":"Review the error above, fix it, then deploy again. The deploy stopped before a write was confirmed, so nothing was applied."})}function Jl(t,{heading:e,title:n,guidance:i}){const r=t.targetIdentity||{},s=document.getElementById("commit-terminal-modal");if(!s)return!1;const o=(h,p)=>{const g=document.getElementById(h);g&&(g.textContent=p||"")};o("terminal-heading",e),o("terminal-title",n),o("terminal-message",t.error||t.message||"");const a=document.getElementById("terminal-identity-list");if(a){const h=[["Project",r.projectId||t.metadata?.projectId],["Endpoint",r.endpoint],["File",r.fileName||t.metadata?.fileName],["Artifact",r.artifactType||t.metadata?.artifactType]];a.innerHTML=h.map(([p,g])=>`
      ${z(p)}:${z(String(g??"—"))}
      `).join("")}const l=document.getElementById("terminal-file-outcomes");let u=t.errorMap;u&&!(u instanceof Map)&&(u=new Map(Object.entries(u))),l&&u&&u.size>0?(l.innerHTML=[...u.entries()].map(([h,p])=>`
    • ${z(h)}: ${z(Sl(p))}
    • `).join(""),l.classList.remove("hidden")):l&&l.classList.add("hidden");const c=document.getElementById("terminal-guidance");c&&(c.innerHTML=i);const d=document.getElementById("terminal-open-ff-link"),f=r.projectId||t.metadata?.projectId;return d&&(d.href=f?`https://app.flutterflow.io/project/${f}`:"https://app.flutterflow.io/"),We(s),!0}function fp(t){Jl(t,{heading:"Deploy partially applied",title:"Some custom classes reached FlutterFlow, but the deploy did not fully complete.",guidance:"The custom classes the runner confirmed are already in your project and are not lost. Review the per-file errors above, fix them in FlutterFlow or regenerate, then deploy again. Open the project to see exactly what landed."})}function hp(t){Jl(t,{heading:"Deploy outcome not yet known",title:"This browser stopped waiting before the FlutterFlow server reported a result.",guidance:"The deploy may still be finishing on the server — it was not cancelled. Open your FlutterFlow project and confirm whether the class landed before retrying, so you do not push a duplicate or build on top of an unknown state."})}function xw(t){t&&t.target!==t.currentTarget||ze(document.getElementById("commit-terminal-modal"))}function Iw(){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 ad={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}},kw=[{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&&(Su(e,!0,"Deploying to FlutterFlow"),We(e)),this.set("prepare")},set(t,e=null){if(!(!ad[t]||t===this.phaseId)){if(!this.sequence.includes(t)){const n=this.sequence.indexOf("package");this.sequence.splice(n===-1?this.sequence.length:n,0,t)}this.phaseId=t,this.phaseStartedAt=Date.now(),this.substatus=e,this.liveSubstatus=!1,this.render(),this.timer&&clearInterval(this.timer),t!=="done"&&(this.timer=setInterval(()=>this.render(),500))}},setSubstatus(t){t&&(this.liveSubstatus=!0,this.substatus=t,this.render())},render(){const t=ad[this.phaseId];if(!t)return;const e=(Date.now()-this.phaseStartedAt)/1e3,n=t.start+(t.end-t.start)*(1-Math.exp(-e/25));if(this.phaseId==="provision"&&!this.liveSubstatus){const o=kw.filter(a=>e>=a.after).pop();o&&(this.substatus=o.text)}const i=this.sequence.indexOf(this.phaseId),s=[`Step ${i===-1?1:i+1} of ${this.sequence.length}`];e>=5&&s.push(Cw(e)),gp(this.phaseId==="done"?100:n,t.message,s.join(" · "),this.substatus)},stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.phaseId=null;const t=document.getElementById("commit-progress-overlay");t&&(Su(t,!1),ze(t,{force:!0,restoreFocus:!1}))}};function Cw(t){const e=Math.floor(t);return e<60?`${e}s elapsed`:`${Math.floor(e/60)}m ${String(e%60).padStart(2,"0")}s elapsed`}function pp(t){Be.start(t)}function Zl(){Be.stop()}function gp(t,e,n,i=null){const r=document.getElementById("commit-progress-bar"),s=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");r&&(r.style.width=`${Math.round(t*10)/10}%`),s&&(s.textContent=e),o&&(o.textContent=n),a&&(a.textContent=i||"",a.classList.toggle("hidden",!i))}function ld(t){const e={[ee.PREPARING]:"prepare",[ee.VALIDATING]:"validate",[ee.PUSHING]:"project",[ee.SUCCESS]:"done"};if(t===ee.ERROR){Be.timer&&clearInterval(Be.timer),Be.timer=null,gp(100,"Failed","Error occurred");return}const n=e[t];n&&Be.set(n)}function Aw(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===J.CODE_FILE):t.codeInfo?.codeType===J.CODE_FILE}let mp=!1;function vp(t){mp=t;const e=document.querySelector("#commit-confirm-modal button[data-deploy-confirm]");e&&(e.disabled=t),[...document.querySelectorAll("[data-deploy-start]"),...document.querySelectorAll("#btn-deploy-to-ff")].forEach(i=>{i.disabled=t})}function cd(t){Zl(),vp(!1);const e=Eh(t);e===Le.COMMITTED?up(t):e===Le.PARTIAL?fp(t):e===Le.UNCONFIRMED?hp(t):dp(t)}async function Pw(){if(!qi){console.error("No pending commit data");return}if(mp){console.warn("Deploy already in flight; ignoring duplicate confirm.");return}const t=qi;if(qi=null,zi=Ew(),cp(),vp(!0),pp({withProvisioning:Aw(t)}),t.bundlePlan){const o=await R0(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});zi=null,cd(o);return}const{codeInfo:e}=t,{artifactType:n,artifactName:i,fileName:r}=Uh(),s=await F0(e.content,{artifactType:n,artifactName:i,fileName:r,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});zi=null,cd(s)}window.runThinkingPipeline=or;window.toggleStep=M0;window.toggleSection=$0;window.selectWorkflowStep=it;window.copyCode=L0;window.retryWithDifferentModel=D0;window.openApiKeysModal=Tl;window.closeApiKeysModal=Bh;window.openComposerSettings=s0;window.closeComposerSettings=o0;window.walkthroughConnectAccount=r0;window.closeWalkthroughModal=l0;window.openWalkthroughModal=a0;window.advanceWalkthrough=$l;window.commitToFlutterFlow=P0;function Fw(){const t=document.getElementById("pipeline-input");t&&t.focus()}function Rw(){const t=document.getElementById("advanced-settings");t&&(t.open=!0);const e=document.getElementById("code-generator-model");e&&(e.scrollIntoView({behavior:"smooth",block:"center"}),e.focus(),e.click())}window.focusPromptInput=Fw;window.openModelSelector=Rw;window.handlePromptImageSelect=Wy;window.removePromptImage=zy;window.saveApiKeys=d0;window.validateFlutterFlowConnection=Ll;window.clearAllApiKeys=f0;window.toggleKeyVisibility=_0;window.handleWelcomeVideoEnd=ww;window.dismissWelcomeVideo=Nn;window.initiateCommitToFlutterFlow=j0;window.updateFlutterFlowCredentialStatus=W0;window.openCommitConfirmModal=Yl;window.closeCommitConfirmModal=cp;window.closeCommitSuccessModal=Sw;window.closeCommitTerminalModal=xw;window.showCommitPartialModal=fp;window.showCommitUnconfirmedModal=hp;window.showCommitSuccessModal=up;window.showCommitFailureModal=dp;window.toggleCodePreview=Iw;window.confirmCommitToFlutterFlow=Pw;window.runRefinement=Jh;window.regenerateFromPastedErrors=Zh;window.clearErrorInput=B0;window.setFlutterFlowEndpoint=i0;window.getFlutterFlowEndpoint=yt;window.commitProgress=Be;window.openSignInModal=zs;window.closeSignInModal=np;window.handleMagicLinkRequest=K0;window.handleSignOut=Y0;window.handleSendNewLink=X0;window.handleClearCache=Q0;window.handleDeleteAccount=ew;window.closeDeleteUnavailableModal=tw;window.startCheckout=fw;window.openCustomerPortal=hw;window.openPricingModal=di;window.closePricingModal=lp;let jr=null,_p=null,On={1:"pending",2:"pending",3:"pending"},Xl=1,Ql=null;const Gs={1:"Prompt Architect",2:"Code Generator",3:"Code Review"},Tw={1:"Understanding your prompt",2:"Generating Dart code",3:"Running the code audit"},$w={1:"Prompt understood",2:"Dart code generated",3:"Code audit complete"};function Ks(){return y.runId+=1,y.runId}function re(t){return t===void 0||t===y.runId}function Mw(){y.runId+=1}function ec(t){return document.getElementById(`pdot-${t}`)}function Ya(t){const e=document.getElementById("btn-run-pipeline")||document.getElementById("hero-send");e&&(e.disabled=t,e.classList.toggle("is-busy",t),t?e.setAttribute("aria-busy","true"):e.removeAttribute("aria-busy"))}function Ys(t){const e=document.getElementById("pipeline-progress");e&&(e.dataset.runState=t)}function Rn(t,e){On[t]=e;const n=ec(t);if(!n)return;n.dataset.state=e,n.disabled=e==="pending"||e==="skipped";const i=Gs[t],r={pending:"not started",active:"in progress",done:"complete",failed:"failed",skipped:"not run"};n.setAttribute("aria-label",`Step ${t} of 3, ${i}: ${r[e]||e}`),e==="active"?n.setAttribute("aria-current","step"):n.removeAttribute("aria-current")}function Lw(){return[1,2,3].filter(t=>On[t]==="done").length}function Js(){const t=document.getElementById("pipeline-progress-fill");t&&(t.style.width=`${Lw()/3*100}%`);const e=document.getElementById("progress-stage-count");e&&(e.textContent=`Step ${Xl} of 3`)}function Zs(t,{done:e=!1}={}){const n=document.getElementById("progress-title-text"),i=document.getElementById("progress-substep-text"),r=On[t],s=e||r==="done";if(n&&(n.textContent=s?$w[t]:Tw[t]),i){const o=s?" — complete":r==="failed"?" — stopped":"";i.textContent=`Step ${t} of 3 — ${Gs[t]}${o}`}}function Nw(t){On[t]==="pending"||On[t]==="skipped"||(Ql=t,[1,2,3].forEach(e=>{const n=ec(e);n&&n.setAttribute("aria-pressed",String(e===t))}),Zs(t))}function tc(){Ql=null,[1,2,3].forEach(t=>{const e=ec(t);e&&e.removeAttribute("aria-pressed")})}function yp(t){const e=document.getElementById("pipeline-note");e&&(e.textContent=t||"",e.hidden=!t)}function Ow(t,e,n){re(n)&&yp(`${Gt(t)} did not answer. Continuing on ${Gt(e)}.`)}function nc(){const t=document.getElementById("pipeline-failure");if(!t)return;t.hidden=!0;const e=document.getElementById("pipeline-failure-actions");e&&e.replaceChildren()}const Bw=1120;function Dw(){const t=getComputedStyle(document.documentElement).getPropertyValue("--t-morph").trim(),e=Number.parseFloat(t);return Number.isFinite(e)&&e>0?e:Bw}let Qn=null,Ur=null;function jw(){return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0}function dn(){if(Ur){try{Ur.cancel()}catch{}Ur=null}Qn&&(Qn.remove(),Qn=null),window.removeEventListener("resize",dn)}function wp(t,e){if(dn(),jw()||!t||!e||!document.body||typeof Element.prototype.animate!="function")return;const n=t.getBoundingClientRect(),i=e.getBoundingClientRect();if(!n.width||!n.height||!i.width||!i.height)return;const r=document.createElement("div");r.className="composer-morph",r.setAttribute("aria-hidden","true"),r.style.cssText=`left:${i.left}px;top:${i.top}px;width:${i.width}px;height:${i.height}px;opacity:0;`,document.body.appendChild(r);const s=n.left+n.width/2-(i.left+i.width/2),o=n.top+n.height/2-(i.top+i.height/2),a=n.width/i.width,l=n.height/i.height,u=`translate(${s}px,${o}px) scale(${a},${l})`,c=r.animate([{transform:u,opacity:0,offset:0,easing:"cubic-bezier(.2,0,0,1)"},{transform:u,opacity:1,offset:.14,easing:"cubic-bezier(.4,0,.2,1)"},{transform:`translate(${s}px,${o}px) scale(${a*.93},${l*.93})`,opacity:1,offset:.28,easing:"cubic-bezier(.32,1.38,.5,1)"},{transform:"translate(0px,0px) scale(1,1)",opacity:1,offset:1}],{duration:Dw(),fill:"both"});Qn=r,Ur=c,window.addEventListener("resize",dn),c.onfinish=()=>{if(Qn!==r)return;const d=r.animate([{opacity:1},{opacity:0}],{duration:260,fill:"forwards"});d.onfinish=()=>{Qn===r&&dn()}}}function Uw(){const e=document.getElementById("composer")?.getBoundingClientRect();e&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{wp({getBoundingClientRect:()=>e},document.getElementById("main-stage-container"))})})}function Hw(){wp(document.getElementById("pipeline-progress"),document.getElementById("main-stage-container"))}window.addEventListener("hashchange",dn);window.addEventListener("popstate",dn);function Xs(t={}){const{prompt:e=null,runId:n}=t;if(!re(n))return;eo(),nn(!0);const i=document.getElementById("pipeline-progress"),r=document.getElementById("results-view"),s=document.getElementById("ready-state");if(s&&s.classList.add("hidden"),r&&r.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),i&&i.classList.add("visible"),Ys("running"),e!==null){const a=document.getElementById("pipeline-submitted-prompt");a&&(a.textContent=e)}_p=Date.now();const o=document.getElementById("progress-elapsed");o&&(o.textContent="0s"),On={1:"pending",2:"pending",3:"pending"},tc(),nc(),yp(""),[1,2,3].forEach(a=>Rn(a,"pending")),Ft(1,n),Ww()}function Ft(t,e){re(e)&&(Xl=t,tc(),[1,2,3].forEach(n=>{n===t?Rn(n,"active"):nt&&Rn(n,"pending")}),Zs(t),Js())}function tn(t,e){re(e)&&(Rn(t,"done"),Ql===null&&Zs(t,{done:!0}),Js())}function bp(t,{stage:e=1,runId:n,retry:i=Ep}={}){if(!re(n))return;Qs(),eo(),dn(),Ys("failed"),nn(!0);const r=document.getElementById("pipeline-progress");r&&r.classList.add("visible");const s=document.getElementById("results-view");s&&s.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),Rn(e,"failed"),[1,2,3].forEach(p=>{p>e&&Rn(p,"pending")}),Xl=e,tc(),Zs(e),Js();const o=xh(t),a=document.getElementById("pipeline-failure"),l=document.getElementById("pipeline-failure-title"),u=document.getElementById("pipeline-failure-message"),c=document.getElementById("pipeline-failure-hint"),d=document.getElementById("pipeline-failure-actions");if(!a||!l||!u||!d)return;if(a.dataset.kind=o.kind,l.textContent=`${Gs[e]}: ${o.title}`,u.textContent=o.message,c){const p=o.detail&&o.detail!==o.message?o.detail:"";c.textContent=p,c.hidden=!p}d.replaceChildren();const f=[o.canUpgrade&&{id:"upgrade",label:"View plans",variant:"primary",onClick:()=>di()},o.canRetry&&{id:"retry",label:"Retry",variant:o.canUpgrade?"secondary":"primary",onClick:i},o.canEdit&&{id:"edit",label:"Edit prompt",variant:"secondary",onClick:Ja}].filter(Boolean);!o.canEdit&&!o.canRetry&&f.push({id:"edit",label:"Back to prompt",variant:"secondary",onClick:Ja}),f.forEach(p=>{const g=document.createElement("button");g.type="button",g.textContent=p.label,g.dataset.action=p.id,g.dataset.variant=p.variant,g.addEventListener("click",p.onClick),d.appendChild(g)}),a.hidden=!1;const h=d.querySelector("button");h&&h.focus({preventScroll:!0})}function Ja(){Mw(),pw(),y.isRunning=!1,Ya(!1),rn(),Ys("settled"),dn(),Qs(),eo(),nc();const t=document.getElementById("pipeline-progress");t&&t.classList.remove("visible"),nn(!1);const e=document.getElementById("pipeline-input");e&&(y.submittedPrompt&&(e.value=y.submittedPrompt,e.dispatchEvent(new Event("input",{bubbles:!0}))),e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length))}function Ep(){const t=document.getElementById("pipeline-input");t&&y.submittedPrompt&&(t.value=y.submittedPrompt,t.dispatchEvent(new Event("input",{bubbles:!0}))),Oe=y.submittedImages.slice(),cn(),nc(),or()}function Ww(){Qs(),jr=setInterval(()=>{const t=(Date.now()-_p)/1e3,e=document.getElementById("progress-elapsed");e&&(e.textContent=`${Math.floor(t)}s`)},250)}function Qs(){jr&&(clearInterval(jr),jr=null)}let Vi=null;function eo(){Vi&&(clearTimeout(Vi),Vi=null)}function cr(){Qs(),eo(),Ys("settled"),Js();const t=document.getElementById("pipeline-progress-fill");Vi=setTimeout(()=>{Vi=null;const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function Tn(t,e=""){const n={pass:'',warning:'',fail:'',info:''};return``}function Sp(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function zw(){return m_({bundle:y.artifactBundle,reviewResult:y.step3Result})}function qw(t){return` +`;const o=oh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:s});Zs({runId:i}),Ft(2,i),it(2),Ae(2,!0);const a=await Us(o,n,[],i);if(!re(i))return;y.step2Result=a,Bs(),tn(2,i);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),it(3),Ft(3,i),Ae(3,!0);const c=await Hs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,Ds(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const f=Ls(y.step3Result);ur(u,f)}catch(s){if(console.error("Regeneration failed:",s),!re(i))return;const o=Ms(s,{architect:2,generator:2,review:3});s.isUsageLimit&&un(),it(o),Ae(o,!1),Sp(s,{stage:o,runId:i,retry:()=>ep(t,e)}),bs(o,"error")}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function z0(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const n=await Te("flutterflow"),i=await Te("flutterflow_project_id");n&&i?(t.className="w-2 h-2 rounded-full bg-green-500",e.textContent="FlutterFlow credentials configured",e.className="text-green-600"):n||i?(t.className="w-2 h-2 rounded-full bg-yellow-500",e.textContent="FlutterFlow credentials incomplete",e.className="text-yellow-600"):(t.className="w-2 h-2 rounded-full bg-red-500",e.textContent="FlutterFlow credentials not configured",e.className="text-red-600")}async function tp(t){try{const e=await fetch(`${_t}/auth/send-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:t})});if(!e.ok)throw new Error(`Failed to send magic link: HTTP ${e.status}`);return e.json()}catch(e){throw console.error("sendMagicLink failed:",{email:t,message:e.message,stack:e.stack}),e}}async function q0(t){try{const n=await(await fetch(`${_t}/auth/verify-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})})).json();if(n.error||!n.email||!n.sessionToken)throw new Error(n.error||"Invalid or expired link");return n}catch(e){throw console.error("verifyMagicLink failed:",{message:e.message,stack:e.stack}),e}}async function V0(t){try{const e=await fetch(`${_t}/auth/refresh-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:t})});if(!e.ok)return console.error("refreshSession: non-OK response",{url:`${_t}/auth/refresh-session`,status:e.status}),null;const n=await e.json();return n.error||!n.email||!n.sessionToken?(console.warn("refreshSession: validation failed",{error:n.error,hasEmail:!!n.email,hasToken:!!n.sessionToken}),null):n}catch(e){return console.error("refreshSession: fetch failed",{url:`${_t}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function sd(t,e){const n=ip(),i=(q.email||n.email)!==t;q.email=t,q.sessionToken=e,q.isVerified=!0,ce=Mn({isLoading:!0}),localStorage.setItem(hs,JSON.stringify({email:t,sessionToken:e})),i&&cp()}function np(){q.email=null,q.sessionToken=null,q.isVerified=!1,ce=Mn({isResolved:!0}),localStorage.removeItem(hs),localStorage.removeItem(gs)}function ip(){try{const t=localStorage.getItem(hs);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(hs),{email:null,sessionToken:null}}}async function G0(){const e=new URLSearchParams(window.location.search).get("token");if(e){window.history.replaceState({},"",window.location.pathname+window.location.hash);try{const{email:n,sessionToken:i}=await q0(e);sd(n,i),rp();const r=od();r&&!window.location.hash&&(window.location.hash=r)}catch(n){od();const i=n.message||"Sign-in link invalid or expired.";Ee(i,"error"),Ws(),Jn(i,"error")}}else{const{email:n,sessionToken:i}=ip();if(n&&i){const r=await V0(i);r?sd(r.email,r.sessionToken):np()}}Kl()}function K0(){try{localStorage.setItem(Na,JSON.stringify({hash:window.location.hash||"#home",ts:Date.now()}))}catch(t){console.warn("rememberSignInReturnSurface: failed to persist return surface:",t)}}function od(){try{const t=localStorage.getItem(Na);if(localStorage.removeItem(Na),!t)return null;const{hash:e,ts:n}=JSON.parse(t);return!e||typeof n!="number"||Date.now()-n>Fy?null:e}catch(t){return console.warn("consumeSignInReturnSurface: failed to read return surface:",t),null}}function Ws(){const t=document.getElementById("signin-modal");if(!t)return;K0(),document.getElementById("signin-email-input")?.removeAttribute("aria-invalid"),Jn(""),We(t)}function rp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&ze(e)}function Jn(t,e){const n=document.getElementById("signin-message");n&&(n.textContent=t||"",n.classList.remove("signin-message-success","signin-message-error"),e&&n.classList.add(`signin-message-${e}`))}async function Y0(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),n=Fs(t?.value);if(!n||!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(n)||n.length>254){t?.setAttribute("aria-invalid","true"),Jn("Please enter a valid email address.","error");return}t?.removeAttribute("aria-invalid"),e&&(e.disabled=!0,e.textContent="Sending…");const r=ph(n);r&&Jn(r,"error");try{const s=await tp(n),o=s?.code===hh;t&&!o&&(t.value=""),t?.setAttribute("aria-invalid",String(o)),Jn(gh(s,n),o?"error":"success"),e&&(e.disabled=!1,e.textContent=o?"Send Sign-in Link":"Sent!",o||setTimeout(()=>{e.textContent==="Sent!"&&(e.textContent="Send Sign-in Link")},2500))}catch(s){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:n,err:s}),Jn("Something went wrong. Please try again.","error"),e&&(e.disabled=!1,e.textContent="Send Sign-in Link")}}function J0(){q.email=null,q.sessionToken=null,q.isVerified=!1,ce=Mn({isResolved:!0}),D_({storage:window.localStorage,onIdentityChanged:Kl,onPlanChanged:qs})}const Z0=j_({sendLink:tp,getEmail:()=>q.email||"",onState:X0});function X0(t){const e=document.getElementById("send-new-link-btn"),n=document.getElementById("send-new-link-msg");if(!e||!n)return;if(t.status==="pending"){e.disabled=!0,e.textContent="Sending…",n.className="acct-access-msg",n.textContent="Sending a fresh sign-in link…";return}if(t.status==="sent"){e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg",n.textContent=gh(t.data,q.email||"")||"Link sent — check your email.";return}e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg error";const i=t.error?.message?`Couldn't send a link right now. ${t.error.message}`:"Couldn't send a link right now. Please try again.";n.textContent=i}async function Q0(){await Z0()}function ew(){const t=O_(window.localStorage),e=t.length?`Cleared disposable UI caches: ${t.join(", ")}.`:"Nothing disposable to clear.";Ee(`${e} Your run count, identity and stored keys are kept.`,"info")}function tw(){const t=document.getElementById("delete-unavailable-modal");t&&We(t,{trigger:document.activeElement})}function nw(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("delete-unavailable-modal");e&&ze(e)}function Kl(){const t=q.isVerified&&!!q.email,e=document.getElementById("auth-signedout"),n=document.getElementById("auth-signedin"),i=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),n&&n.classList.toggle("hidden",!t),i&&i.classList.toggle("hidden",t);const r=document.getElementById("auth-user-email");r&&(r.textContent=q.email||"");const s=document.getElementById("access-signed-email");s&&(s.textContent=q.email||""),fw(),qs()}async function sp(){try{if(typeof FingerprintJS>"u"){console.warn("resolveIdentity: FingerprintJS not loaded, skipping");return}const e=await(await FingerprintJS.load()).get(),n=e.visitorId,i=await fetch(My,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fingerprint:e.visitorId,cookie_id:n})});if(!i.ok)throw new Error(`Identity check HTTP ${i.status}`);const r=await i.json();if(ht.userId=r.user_id,ht.token=r.identity_token||null,ht.status=r.status,ht.resolved=!0,sessionStorage.setItem(Ty,r.user_id),ht.token&&sessionStorage.setItem($y,ht.token),r.usage_count!==void 0){const s=gn(),a=(r.usage_month||s)===s?r.usage_count:0;localStorage.setItem(Fn,JSON.stringify({count:a,month:s})),un()}console.log(`Identity resolved: ${r.status} (${r.user_id.slice(0,8)}...) usage: ${r.usage_count??"n/a"}`)}catch(t){console.error("resolveIdentity failed:",t)}}let Wo=null;function iw(t=5e3){return ht.resolved?Promise.resolve():(Wo||(Wo=sp().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([Wo,new Promise(e=>setTimeout(e,t))]))}function op(){const t=gn();try{const e=localStorage.getItem(Fn);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Fn,month:t,err:e}),localStorage.removeItem(Fn),{count:0,month:t}}}function gn(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function lr(){const t=op();return t.month!==gn()?{count:0,month:gn()}:t}function rw(){const e={count:lr().count+1,month:gn()};return localStorage.setItem(Fn,JSON.stringify(e)),e}function pi(){return!!ce.isLoading}function Tt(){return!!ce.isResolved}function sw(t){if(!t)return null;const e=String(t).toLowerCase().replace(/[^a-z0-9]+/g,"_");return e==="pro"||e==="professional_plan"?"professional":e==="power_developer"||e==="power_plan"?"power":Object.prototype.hasOwnProperty.call(ps,e)?e:null}function ow(t){return t&&Object.entries(Ah).find(([,e])=>e===t)?.[0]||null}function Cr(...t){return t.find(e=>e!=null&&e!=="")}function aw(...t){return t.find(e=>e&&typeof e=="object")||{}}function lw(t){const e=t.data&&typeof t.data=="object"?t.data:t,n=aw(e.subscription,e.stripeSubscription,e.currentSubscription,e.customer?.subscriptions?.data?.[0],e.subscriptions?.data?.[0],e.subscriptions?.[0]),i=e.metadata||n.metadata||e.customer?.metadata||{},r=Cr(e.priceId,e.price_id,e.stripePriceId,e.stripe_price_id,n.priceId,n.price_id,n.plan?.id,n.price?.id,n.items?.data?.[0]?.price?.id,n.items?.[0]?.price?.id,n.lines?.data?.[0]?.price?.id),s=Cr(e.status,e.subscriptionStatus,e.subscription_status,n.status,"none"),o=sw(Cr(e.tier,e.plan,e.planId,e.plan_id,e.subscriptionTier,e.subscription_tier,e.product,e.productName,n.tier,n.plan,i.tier,i.plan)),a=Ly.has(String(s).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||ow(r)||(a||l?"professional":"free");return Mn({tier:u,status:s,periodEnd:Cr(e.periodEnd,e.currentPeriodEnd,e.current_period_end,n.current_period_end,n.periodEnd,null),isResolved:!0})}function zs(){return ps[ce.tier]??ps.free}async function cw(){if(q.isVerified&&(!Tt()||pi())&&(await lp({force:!0}),qs()),q.isVerified&&!Tt())return Ee("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=lr(),e=zs();if(t>=e)return ap(t,e,{openModal:!0}),!1;const n=Math.floor(e*.8);if(t>=n){const i=e-t;Ee(`${i} run${i===1?"":"s"} remaining this month.`,"warning")}return!0}function ad(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function ap(t,e,n={}){nn(!0);const i=document.getElementById("walkthrough-modal");i&&ze(i,{restoreFocus:!1});const r=document.getElementById("ready-state");r&&r.classList.add("hidden");const s=document.getElementById("preview-frame-container");s&&(s.style.display="none");const o=document.getElementById("main-stage-container");o&&o.classList.add("visible");const a=document.getElementById("results-view");a&&a.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar");const l=document.getElementById("pipeline-progress");l&&l.classList.remove("visible");const u=document.getElementById("paywall-exhausted");if(!u){Ee(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),di();return}const c=document.getElementById("paywall-exhausted-text");if(c){const f=ce.tier;f==="free"?c.textContent=`You've used all ${e} free generations this month. Upgrade to Pro for 50 generations/month and access to all AI models.`:c.textContent=`You've used all ${e} generations this month on your ${f} plan. Your limit resets next month.`}const d=document.getElementById("paywall-signin-btn");d&&d.classList.toggle("hidden",q.isVerified),u.classList.remove("hidden"),n.openModal&&di()}function Va(t){return ce.tier==="free"&&Nr.includes(t)?ms:t}function uw(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const n=ce.tier,r=!(q.isVerified&&!Tt())&&n==="free";Array.from(e.options).forEach(o=>{const a=Gt(o.value),l=Nr.includes(o.value);o.textContent=l&&r?`${a} (PRO)`:a,o.disabled=!1}),r&&Nr.includes(e.value)&&(e.value=ms),e.disabled=!1,Ku.has(e)||(e.addEventListener("change",()=>{Tt()&&ce.tier==="free"&&Nr.includes(e.value)&&(e.value=ms,di()),qa(e.value),Cl()}),Ku.add(e));let s=document.getElementById("model-selector-free-notice");r?(s||(s=document.createElement("p"),s.id="model-selector-free-notice",s.className="text-xs text-gray-400 mt-1",t.appendChild(s)),s.innerHTML='Free plan — Gemini only. '):s&&s.remove(),qa(e.value)}function Yl(){const t=q.isVerified&&!!q.email,e=t&&pi(),n=!t||Tt(),i=lr(),r=n?i.count:0,s=n?zs():0,o=Math.max(0,s-r),a=`${r} / ${s} runs this month`,l=ml,u=n?ce.tier||"free":null,c=document.getElementById("topbar-credits-count");c&&(e?c.textContent="…":n?c.textContent=String(o):c.textContent="—");const d=document.getElementById("credits-balance");d&&(e?d.textContent="Checking plan…":n?d.textContent=a:d.textContent="Plan check failed");const f=document.getElementById("usage-dialog-tier");f&&(e?f.textContent="Checking…":n?f.textContent=l[u]||"Free":f.textContent="Unavailable");const h=document.getElementById("usage-dialog-status");h&&(e?h.textContent="Verifying your subscription…":n?h.textContent="Runs reset at the start of each month.":h.textContent="Could not verify your subscription. Try again or sign out.");const p=document.getElementById("usage-counter");if(p)if(e&&t)p.textContent="Checking plan…",p.className="text-xs text-gray-500";else if(!n&&t)p.textContent="Plan check failed",p.className="text-xs text-red-600 font-medium";else{p.textContent=a;const g=s>0?r/s:0;p.className=g>=1?"text-xs text-red-600 font-medium":g>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500"}if(!t){const g=document.getElementById("guest-usage-text");if(g){const m=op(),v=m.month===gn()?m.count??0:0;g.textContent=`${v} / ${ps.free} generations used`}}dw()}function dw(){if(!(q.isVerified&&!!q.email))return;const e=pi(),n=Tt(),i=lr(),r=n?i.count:0,s=n?zs():0,o=Math.max(0,s-r),a=n?ce.tier||"free":null,l={free:"Free",professional:"Pro",power:"Power"}[a]||"Free",u=q.email||"",c=u.split("@")[0]||u,d=document.getElementById("acct-avatar");d&&(d.textContent=(u[0]||"?").toUpperCase());const f=document.getElementById("acct-name");f&&(f.textContent=c||"—");const h=document.getElementById("acct-plan-tier"),p=document.getElementById("acct-plan-price"),g=document.getElementById("acct-plan-note"),m=document.getElementById("acct-renewal");if(h&&(h.textContent=e?"Checking…":n?l:"Plan unavailable"),p)if(e)p.textContent="—";else if(!n)p.textContent="—";else if(a==="free")p.textContent="$0 / month";else{const x=Oi(Ni[a]??0,Al());p.textContent=`${x} / month`}if(g&&(e?g.textContent="Verifying your subscription…":n?a==="free"?g.textContent="No subscription. Upgrade for more generations.":g.textContent="billed monthly through Stripe":g.textContent="Could not verify your subscription. Check billing or sign out."),m){const x=Date.parse(ce.periodEnd||""),F=n&&a!=="free"&&!!ce.periodEnd&&!Number.isNaN(x);if(e)m.textContent="";else if(!n)m.textContent="";else if(a==="free")m.textContent="";else if(F){const $=new Date(x).toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"});m.textContent=`Renews ${$} · reset at the start of each month.`}else m.textContent="Renewal date is not available for this period."}const v=document.getElementById("acct-left-count"),E=document.getElementById("acct-left-limit"),S=document.getElementById("acct-reset-note");v&&(v.textContent=e?"…":n?String(o):"—"),E&&(E.textContent=e?"…":n?String(s):"—"),S&&(e?S.textContent="Checking plan…":n?S.textContent="Runs reset at the start of each month.":S.textContent="Plan check failed. Refresh or manage billing.");const _=document.getElementById("acct-used-count"),b=document.getElementById("acct-meter-fill"),k=document.getElementById("acct-meter-meta"),T=document.getElementById("acct-meter-track");if(_&&(_.textContent=e?"…":n?String(r):"—"),b){const x=n&&s>0?Math.min(100,Math.round(r/s*100)):0;b.style.width=`${x}%`}if(k)if(e)k.textContent="Checking…";else if(!n)k.textContent="Plan check failed";else if(s===0)k.textContent=`${r} of ${s}`;else{const x=Math.round(r/s*100);k.textContent=`${r} of ${s} · ${x}%`}T&&(e?T.setAttribute("aria-label","Checking usage…"):n?T.setAttribute("aria-label",`${r} of ${s} generations used`):T.setAttribute("aria-label","Usage unavailable")),vt()}function un(){if(Yl(),q.isVerified&&(pi()||!Tt())){ad();return}const{count:t}=lr(),e=zs();t>=e&&!y.isRunning?ap(t,e):ad()}function fw(){Yl()}async function lp(t={}){const e=t.force===!0;if(!q.isVerified||!q.sessionToken){ce=Mn({isResolved:!0});return}ce={...ce,isLoading:!0,error:null};const n=localStorage.getItem(gs);if(!e&&n)try{const{data:i,email:r,ts:s,version:o}=JSON.parse(n);if(o===Yu&&r===q.email&&Date.now()-s<300*1e3){ce={...i,isLoading:!1,isResolved:i.isResolved!==!1};return}}catch(i){console.warn("Failed to parse subscription cache:",i,"| raw value:",n)}try{const r=await(await fetch(`${_t}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:q.sessionToken,user_id:ht.userId})})).json();if(r.error){if(["unauthorized","invalid session","expired session"].some(o=>String(r.error).toLowerCase().includes(o))){np(),Kl();return}ce=Mn({isResolved:!1,error:r.error});return}ce=lw(r),localStorage.setItem(gs,JSON.stringify({version:Yu,data:ce,email:q.email,ts:Date.now()}))}catch(i){console.error("fetchSubscription failed:",i),ce={...ce,isLoading:!1,isResolved:!1,error:i.message}}}function cp(){localStorage.removeItem(gs)}async function hw(t){if(!q.isVerified||!q.sessionToken){up(),Ws();return}if(!Ah[t]){Ee("Invalid plan selected.","error");return}const e=document.getElementById(`checkout-btn-${t}`);e&&(e.disabled=!0,e.textContent="Redirecting…");try{const i=await(await fetch(`${_t}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:q.sessionToken,currency:Al()})})).json();if(i.error||!i.url)throw new Error(i.error||"Failed to create checkout session");const{url:r}=i;window.location.href=r}catch(n){console.error("startCheckout failed:",n),e&&(e.disabled=!1,e.textContent="Subscribe"),Ee("Could not start checkout. Please try again.","error")}}async function pw(t){if(!q.isVerified||!q.sessionToken){Ws();return}const e=t||document.getElementById("manage-billing-btn"),n=e?e.textContent:"";e&&(e.disabled=!0,e.textContent="Loading…");try{const r=await(await fetch(`${_t}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:q.sessionToken})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to open billing portal");const{url:s}=r;window.location.href=s}catch(i){console.error("openCustomerPortal failed:",i),e&&(e.disabled=!1,e.textContent=n),Ee("Could not open billing portal. Please try again.","error")}}const Es=new Set;function gw(){Es.forEach(t=>t.abort()),Es.clear()}async function Ss(t,e,n,i={},r=[]){const o=new AbortController;Es.add(o);let a=!1;const l=setTimeout(()=>{a=!0,o.abort()},12e4);try{const u=await fetch(Ry,{method:"POST",headers:{"Content-Type":"application/json",...ht.token?{Authorization:`Bearer ${ht.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:ht.userId,step:t,model:e,prompt:n,images:r,context:i})}),c=await u.text();let d={};try{d=c?JSON.parse(c):{}}catch{d={}}if(u.status===429){d.serverCount!==void 0&&(localStorage.setItem(Fn,JSON.stringify({count:d.serverCount,month:gn()})),un());const p=new Error(d.message||"Monthly usage limit reached. Upgrade to continue.");throw p.isUsageLimit=!0,p.pipelineStep=t,p}const f=kv(d,t);if(f)throw f;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(d),"content type:",typeof d.content),!u.ok)throw new Error(`${d.message||d.error||"BuildShip pipeline error"} (HTTP ${u.status})`);if(t==="generator")if(d.usage_status==="success"&&Number.isFinite(d.usage_count)){const p=gn();(d.usage_month||p)===p&&(localStorage.setItem(Fn,JSON.stringify({count:d.usage_count,month:p})),un())}else rw(),un();let h=d.output||d.content;if(!h){const p=c?` (body: ${c.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${p}`)}return Array.isArray(h)&&(h=h.map(p=>typeof p=="string"?p:p.text||"").join("")),typeof h!="string"&&(h=JSON.stringify(h)),h}catch(u){if(u.name==="AbortError"){if(a)throw new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`);const c=new Error(`BuildShip ${t} request cancelled`);throw c.isPipelineCancel=!0,c}throw u instanceof TypeError?new Error(`BuildShip unreachable: ${u.message}`):u}finally{clearTimeout(l),Es.delete(o)}}let Ga=!1;function mw(){const e=new URLSearchParams(window.location.search).get("checkout");return e==="success"?(window.history.replaceState({},"",window.location.pathname+window.location.hash),cp(),Ga=!0):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname+window.location.hash),Ee("Checkout cancelled.","info")),e}function vw(){if(!Ga)return;Ga=!1;const t=ce.tier!=="free";Ee(t?"Subscription active! Your plan is live.":"Checkout complete — confirming your subscription. Check Manage billing if it does not update.",t?"success":"info")}function qs(){const t=q.isVerified&&!!q.email,e=ce.tier,n=t&&pi(),i=!t||Tt(),r=document.getElementById("subscription-tier-badge");if(r){const a=ml,l={free:"bg-gray-100 text-gray-600",professional:"bg-indigo-100 text-indigo-700",power:"bg-purple-100 text-purple-700",unresolved:"bg-red-50 text-red-600"};r.textContent=n?"Checking…":i?a[e]||"Free":"Plan unavailable",r.className=`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${i?l[e]||l.free:l.unresolved}`}const s=document.getElementById("upgrade-prompt");s&&s.classList.toggle("hidden",!t||n||!i||e!=="free");const o=document.getElementById("manage-billing-btn");o&&o.classList.toggle("hidden",!t||n||i&&e==="free"),_w(i?e:null),uw(),Cl(),un(),Ap()}function _w(t){const e=["bg-gray-100","text-gray-500","cursor-default"];Object.entries({professional:{btnId:"checkout-btn-professional",defaultText:"Subscribe"},power:{btnId:"checkout-btn-power",defaultText:"Subscribe"}}).forEach(([r,{btnId:s,defaultText:o}])=>{const a=document.getElementById(s);a&&(r===t?(a.disabled=!0,a.textContent="Current plan",a.classList.add(...e)):(a.disabled=!1,a.textContent=o,a.classList.remove(...e)))});const i=document.getElementById("free-tier-current");i&&i.classList.toggle("hidden",t!=="free")}function yw(){document.querySelectorAll(".pm-card[data-tier]").forEach(t=>{const e=t.dataset.tier,n=hv[e];if(!n)return;const i=t.querySelector("ul.pm-features");if(i){i.innerHTML="";for(const r of n){const s=document.createElement("li");s.textContent=r,i.appendChild(s)}}})}function Ka(){const t=Al(),e=document.getElementById("pro-price"),n=document.getElementById("power-price"),i=document.getElementById("plans-pro-price"),r=document.getElementById("plans-power-price"),s=document.getElementById("pro-price-note"),o=document.getElementById("power-price-note"),a=document.getElementById("plans-pro-price-note"),l=document.getElementById("plans-power-price-note");e&&(e.textContent=Oi(Ni.professional,t)),n&&(n.textContent=Oi(Ni.power,t)),i&&(i.textContent=Oi(Ni.professional,t)),r&&(r.textContent=Oi(Ni.power,t));const u="billed monthly";s&&(s.textContent=u),o&&(o.textContent=u),a&&(a.textContent=u),l&&(l.textContent=u)}function di(){Ka();const t=document.getElementById("pricing-modal");t&&We(t),Vy().then(()=>Ka())}function up(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&ze(e)}function Ee(t,e="info"){const n={success:"bg-green-600 text-white",error:"bg-red-600 text-white",warning:"bg-amber-500 text-white",info:"bg-gray-800 text-white"},i=document.createElement("div");i.className=`fixed bottom-6 left-1/2 -translate-x-1/2 px-5 py-3 rounded-lg text-sm font-medium shadow-lg z-50 transition-opacity duration-300 ${n[e]||n.info}`,i.textContent=t,document.body.appendChild(i),setTimeout(()=>{i.style.opacity="0",setTimeout(()=>i.remove(),300)},3500)}document.addEventListener("DOMContentLoaded",async()=>{uv(),hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),ww(),window.__heroField=iy(),window.__pipelineLogo=ay(),Fh=Ay({onSubmit:or}),Oa=(async()=>{try{await G0(),mw(),await lp()}catch(n){console.warn("Startup auth/subscription initialization failed:",n)}})(),await Oa,vw(),qs(),Ka(),yw(),await E0(),v0();const t=document.getElementById("flutterflow-endpoint-select");if(t){const n=yt();t.value=n}Hh(),sp();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{en===2&&e.value.trim().length>0&&($l(),Ns())}),e.addEventListener("blur",()=>{const n=document.getElementById("walkthrough-modal");en===2&&n&&We(n)}),e.addEventListener("keydown",n=>{if(n.key==="Tab"){const i=document.getElementById("walkthrough-modal");en===2&&i&&setTimeout(()=>{We(i)},100)}})),window.addEventListener("commitStateChange",n=>{const{state:i}=n.detail;i===ee.PREPARING||i===ee.VALIDATING||i===ee.PUSHING?(Be.phaseId||mp(),cd(i)):(i===ee.SUCCESS||i===ee.ERROR)&&(cd(i),setTimeout(Xl,1e3))}),sc()});function ww(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function bw(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Nn),document.addEventListener("keydown",Nn))}function Nn(){const t=document.getElementById("preview-frame-container"),e=document.getElementById("main-stage-container"),n=document.getElementById("ready-state");t&&(t.style.display="none"),e&&e.classList.add("visible"),n&&n.classList.remove("hidden");const i=document.getElementById("welcome-video-player");i&&i.removeEventListener("click",Nn),document.removeEventListener("keydown",Nn),Hh()}let qi=null;async function Ew(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++ed,n=()=>e===ed,i=await Te("flutterflow"),r=await Te("flutterflow_project_id");if(n()){if(!i){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const o=await new hi(i,"","main",yt()).listProjects();if(!n())return;if(!o||o.length===0){t.innerHTML='';return}t.innerHTML='',o.forEach(a=>{const l=document.createElement("option");l.value=a.id||a.projectId||"",l.textContent=a.name||a.projectName||`Project ${a.id}`,t.appendChild(l)}),r&&(t.value=r)}catch(s){if(!n())return;console.error("Failed to load projects for deploy:",s),t.innerHTML=''}}}function Sw(){return document.getElementById("confirm-project-select")?.value?.trim()||null}function Jl(t,e,n,i=null){qi={codeInfo:t,checks:e,deps:n,bundlePlan:i},document.getElementById("confirm-file-name").textContent=t.fileName,document.getElementById("confirm-artifact-type").textContent=t.artifactType,document.getElementById("confirm-file-size").textContent=`${(t.content.length/1024).toFixed(1)} KB`,document.getElementById("confirm-line-count").textContent=i?`${i.fileEntries.length} files`:t.content.split(` +`).length,Ew();const r=document.getElementById("confirm-deps-list"),s=document.getElementById("confirm-deps-section");n&&Object.keys(n).length>0?(r.innerHTML=Object.entries(n).map(([u,c])=>{const d=c?`at least ${Qt(c)}`:"version resolved from your project";return`
    • • ${Qt(u)}: ${d}
    • `}).join(""),s.classList.remove("hidden")):s.classList.add("hidden");const o=document.getElementById("confirm-warnings-list"),a=document.getElementById("confirm-warnings-section");e.warnings&&e.warnings.length>0?(o.innerHTML=e.warnings.map(u=>`
    • • ${Qt(u)}
    • `).join(""),a.classList.remove("hidden")):a.classList.add("hidden"),document.getElementById("confirm-code-preview").textContent=t.content,document.getElementById("code-preview-content").classList.add("hidden"),document.getElementById("code-preview-chevron").style.transform="rotate(0deg)";const l=document.getElementById("commit-confirm-modal");l&&We(l)}function dp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&ze(e),qi=null}function xw(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&ze(e);const n=["success-message","success-project-id","success-file-name","success-artifact-type","success-time","success-size"];for(const s of n){const o=document.getElementById(s);o&&(o.textContent="")}const i=document.getElementById("success-warnings-section");i&&i.classList.add("hidden");const r=document.getElementById("success-warnings-list");r&&(r.innerHTML="")}function fp(t){const e=(m,v)=>{const E=document.getElementById(m);E&&(E.textContent=v||"")},n=t.metadata?.fileName||"",i=t.metadata?.projectId||"",r=t.metadata?.artifactType||"",s=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",i),e("success-file-name",n),e("success-artifact-type",r),e("success-time",s),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&i&&(u.href=`https://app.flutterflow.io/project/${i}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),f=t.unverified||[],h=t.approximate||[],p=t.warnings||[];(p.length>0||f.length>0||h.length>0)&&c&&d&&(d.innerHTML=[...f.map(m=>`
    • Not verified before deploying: ${z(String(m))}
    • `),...h.map(m=>`
    • Verified approximately: ${z(String(m))}
    • `),...p.map(([m,v])=>`
    • ${z(m)}: ${z(String(v))}
    • `)].join(""),c.classList.remove("hidden"));const g=document.getElementById("commit-success-modal");g&&We(g)}function hp(t){Xl(),W0(t);const e=t.remoteRefusal===!0;Zl(t,{heading:"Deploy failed",title:e?"FlutterFlow refused this deploy — nothing was confirmed written.":"The deploy failed before FlutterFlow confirmed anything.",guidance:e?"Review the error and any per-file outcomes above, fix them in your code or in FlutterFlow, then deploy again. A refusal is definitive: no part of this deploy was applied, so retrying is safe once the problem is fixed.":"Review the error above, fix it, then deploy again. The deploy stopped before a write was confirmed, so nothing was applied."})}function Zl(t,{heading:e,title:n,guidance:i}){const r=t.targetIdentity||{},s=document.getElementById("commit-terminal-modal");if(!s)return!1;const o=(h,p)=>{const g=document.getElementById(h);g&&(g.textContent=p||"")};o("terminal-heading",e),o("terminal-title",n),o("terminal-message",t.error||t.message||"");const a=document.getElementById("terminal-identity-list");if(a){const h=[["Project",r.projectId||t.metadata?.projectId],["Endpoint",r.endpoint],["File",r.fileName||t.metadata?.fileName],["Artifact",r.artifactType||t.metadata?.artifactType]];a.innerHTML=h.map(([p,g])=>`
      ${z(p)}:${z(String(g??"—"))}
      `).join("")}const l=document.getElementById("terminal-file-outcomes");let u=t.errorMap;u&&!(u instanceof Map)&&(u=new Map(Object.entries(u))),l&&u&&u.size>0?(l.innerHTML=[...u.entries()].map(([h,p])=>`
    • ${z(h)}: ${z(Sl(p))}
    • `).join(""),l.classList.remove("hidden")):l&&l.classList.add("hidden");const c=document.getElementById("terminal-guidance");c&&(c.innerHTML=i);const d=document.getElementById("terminal-open-ff-link"),f=r.projectId||t.metadata?.projectId;return d&&(d.href=f?`https://app.flutterflow.io/project/${f}`:"https://app.flutterflow.io/"),We(s),!0}function pp(t){Zl(t,{heading:"Deploy partially applied",title:"Some custom classes reached FlutterFlow, but the deploy did not fully complete.",guidance:"The custom classes the runner confirmed are already in your project and are not lost. Review the per-file errors above, fix them in FlutterFlow or regenerate, then deploy again. Open the project to see exactly what landed."})}function gp(t){Zl(t,{heading:"Deploy outcome not yet known",title:"This browser stopped waiting before the FlutterFlow server reported a result.",guidance:"The deploy may still be finishing on the server — it was not cancelled. Open your FlutterFlow project and confirm whether the class landed before retrying, so you do not push a duplicate or build on top of an unknown state."})}function Iw(t){t&&t.target!==t.currentTarget||ze(document.getElementById("commit-terminal-modal"))}function kw(){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 ld={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}},Cw=[{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&&(xu(e,!0,"Deploying to FlutterFlow"),We(e)),this.set("prepare")},set(t,e=null){if(!(!ld[t]||t===this.phaseId)){if(!this.sequence.includes(t)){const n=this.sequence.indexOf("package");this.sequence.splice(n===-1?this.sequence.length:n,0,t)}this.phaseId=t,this.phaseStartedAt=Date.now(),this.substatus=e,this.liveSubstatus=!1,this.render(),this.timer&&clearInterval(this.timer),t!=="done"&&(this.timer=setInterval(()=>this.render(),500))}},setSubstatus(t){t&&(this.liveSubstatus=!0,this.substatus=t,this.render())},render(){const t=ld[this.phaseId];if(!t)return;const e=(Date.now()-this.phaseStartedAt)/1e3,n=t.start+(t.end-t.start)*(1-Math.exp(-e/25));if(this.phaseId==="provision"&&!this.liveSubstatus){const o=Cw.filter(a=>e>=a.after).pop();o&&(this.substatus=o.text)}const i=this.sequence.indexOf(this.phaseId),s=[`Step ${i===-1?1:i+1} of ${this.sequence.length}`];e>=5&&s.push(Aw(e)),vp(this.phaseId==="done"?100:n,t.message,s.join(" · "),this.substatus)},stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.phaseId=null;const t=document.getElementById("commit-progress-overlay");t&&(xu(t,!1),ze(t,{force:!0,restoreFocus:!1}))}};function Aw(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 mp(t){Be.start(t)}function Xl(){Be.stop()}function vp(t,e,n,i=null){const r=document.getElementById("commit-progress-bar"),s=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");r&&(r.style.width=`${Math.round(t*10)/10}%`),s&&(s.textContent=e),o&&(o.textContent=n),a&&(a.textContent=i||"",a.classList.toggle("hidden",!i))}function cd(t){const e={[ee.PREPARING]:"prepare",[ee.VALIDATING]:"validate",[ee.PUSHING]:"project",[ee.SUCCESS]:"done"};if(t===ee.ERROR){Be.timer&&clearInterval(Be.timer),Be.timer=null,vp(100,"Failed","Error occurred");return}const n=e[t];n&&Be.set(n)}function Pw(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===J.CODE_FILE):t.codeInfo?.codeType===J.CODE_FILE}let _p=!1;function yp(t){_p=t;const e=document.querySelector("#commit-confirm-modal button[data-deploy-confirm]");e&&(e.disabled=t),[...document.querySelectorAll("[data-deploy-start]"),...document.querySelectorAll("#btn-deploy-to-ff")].forEach(i=>{i.disabled=t})}function ud(t){Xl(),yp(!1);const e=xh(t);e===Le.COMMITTED?fp(t):e===Le.PARTIAL?pp(t):e===Le.UNCONFIRMED?gp(t):hp(t)}async function Fw(){if(!qi){console.error("No pending commit data");return}if(_p){console.warn("Deploy already in flight; ignoring duplicate confirm.");return}const t=qi;if(qi=null,zi=Sw(),dp(),yp(!0),mp({withProvisioning:Pw(t)}),t.bundlePlan){const o=await T0(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});zi=null,ud(o);return}const{codeInfo:e}=t,{artifactType:n,artifactName:i,fileName:r}=Wh(),s=await R0(e.content,{artifactType:n,artifactName:i,fileName:r,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});zi=null,ud(s)}window.runThinkingPipeline=or;window.toggleStep=L0;window.toggleSection=M0;window.selectWorkflowStep=it;window.copyCode=N0;window.retryWithDifferentModel=j0;window.openApiKeysModal=Tl;window.closeApiKeysModal=jh;window.openComposerSettings=o0;window.closeComposerSettings=a0;window.walkthroughConnectAccount=s0;window.closeWalkthroughModal=c0;window.openWalkthroughModal=l0;window.advanceWalkthrough=$l;window.commitToFlutterFlow=F0;function Rw(){const t=document.getElementById("pipeline-input");t&&t.focus()}function Tw(){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=Rw;window.openModelSelector=Tw;window.handlePromptImageSelect=zy;window.removePromptImage=qy;window.saveApiKeys=f0;window.validateFlutterFlowConnection=Ll;window.clearAllApiKeys=h0;window.toggleKeyVisibility=y0;window.handleWelcomeVideoEnd=bw;window.dismissWelcomeVideo=Nn;window.initiateCommitToFlutterFlow=U0;window.updateFlutterFlowCredentialStatus=z0;window.openCommitConfirmModal=Jl;window.closeCommitConfirmModal=dp;window.closeCommitSuccessModal=xw;window.closeCommitTerminalModal=Iw;window.showCommitPartialModal=pp;window.showCommitUnconfirmedModal=gp;window.showCommitSuccessModal=fp;window.showCommitFailureModal=hp;window.toggleCodePreview=kw;window.confirmCommitToFlutterFlow=Fw;window.runRefinement=Xh;window.regenerateFromPastedErrors=Qh;window.clearErrorInput=D0;window.setFlutterFlowEndpoint=r0;window.getFlutterFlowEndpoint=yt;window.commitProgress=Be;window.openSignInModal=Ws;window.closeSignInModal=rp;window.handleMagicLinkRequest=Y0;window.handleSignOut=J0;window.handleSendNewLink=Q0;window.handleClearCache=ew;window.handleDeleteAccount=tw;window.closeDeleteUnavailableModal=nw;window.startCheckout=hw;window.openCustomerPortal=pw;window.openPricingModal=di;window.closePricingModal=up;let jr=null,wp=null,On={1:"pending",2:"pending",3:"pending"},Ql=1,ec=null;const Vs={1:"Prompt Architect",2:"Code Generator",3:"Code Review"},$w={1:"Understanding your prompt",2:"Generating Dart code",3:"Running the code audit"},Mw={1:"Prompt understood",2:"Dart code generated",3:"Code audit complete"};function Gs(){return y.runId+=1,y.runId}function re(t){return t===void 0||t===y.runId}function Lw(){y.runId+=1}function tc(t){return document.getElementById(`pdot-${t}`)}function Ya(t){const e=document.getElementById("btn-run-pipeline")||document.getElementById("hero-send");e&&(e.disabled=t,e.classList.toggle("is-busy",t),t?e.setAttribute("aria-busy","true"):e.removeAttribute("aria-busy"))}function Ks(t){const e=document.getElementById("pipeline-progress");e&&(e.dataset.runState=t)}function Rn(t,e){On[t]=e;const n=tc(t);if(!n)return;n.dataset.state=e,n.disabled=e==="pending"||e==="skipped";const i=Vs[t],r={pending:"not started",active:"in progress",done:"complete",failed:"failed",skipped:"not run"};n.setAttribute("aria-label",`Step ${t} of 3, ${i}: ${r[e]||e}`),e==="active"?n.setAttribute("aria-current","step"):n.removeAttribute("aria-current")}function Nw(){return[1,2,3].filter(t=>On[t]==="done").length}function Ys(){const t=document.getElementById("pipeline-progress-fill");t&&(t.style.width=`${Nw()/3*100}%`);const e=document.getElementById("progress-stage-count");e&&(e.textContent=`Step ${Ql} of 3`)}function Js(t,{done:e=!1}={}){const n=document.getElementById("progress-title-text"),i=document.getElementById("progress-substep-text"),r=On[t],s=e||r==="done";if(n&&(n.textContent=s?Mw[t]:$w[t]),i){const o=s?" — complete":r==="failed"?" — stopped":"";i.textContent=`Step ${t} of 3 — ${Vs[t]}${o}`}}function Ow(t){On[t]==="pending"||On[t]==="skipped"||(ec=t,[1,2,3].forEach(e=>{const n=tc(e);n&&n.setAttribute("aria-pressed",String(e===t))}),Js(t))}function nc(){ec=null,[1,2,3].forEach(t=>{const e=tc(t);e&&e.removeAttribute("aria-pressed")})}function bp(t){const e=document.getElementById("pipeline-note");e&&(e.textContent=t||"",e.hidden=!t)}function Bw(t,e,n){re(n)&&bp(`${Gt(t)} did not answer. Continuing on ${Gt(e)}.`)}function ic(){const t=document.getElementById("pipeline-failure");if(!t)return;t.hidden=!0;const e=document.getElementById("pipeline-failure-actions");e&&e.replaceChildren()}const Dw=1120;function jw(){const t=getComputedStyle(document.documentElement).getPropertyValue("--t-morph").trim(),e=Number.parseFloat(t);return Number.isFinite(e)&&e>0?e:Dw}let Qn=null,Ur=null;function Uw(){return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0}function dn(){if(Ur){try{Ur.cancel()}catch{}Ur=null}Qn&&(Qn.remove(),Qn=null),window.removeEventListener("resize",dn)}function Ep(t,e){if(dn(),Uw()||!t||!e||!document.body||typeof Element.prototype.animate!="function")return;const n=t.getBoundingClientRect(),i=e.getBoundingClientRect();if(!n.width||!n.height||!i.width||!i.height)return;const r=document.createElement("div");r.className="composer-morph",r.setAttribute("aria-hidden","true"),r.style.cssText=`left:${i.left}px;top:${i.top}px;width:${i.width}px;height:${i.height}px;opacity:0;`,document.body.appendChild(r);const s=n.left+n.width/2-(i.left+i.width/2),o=n.top+n.height/2-(i.top+i.height/2),a=n.width/i.width,l=n.height/i.height,u=`translate(${s}px,${o}px) scale(${a},${l})`,c=r.animate([{transform:u,opacity:0,offset:0,easing:"cubic-bezier(.2,0,0,1)"},{transform:u,opacity:1,offset:.14,easing:"cubic-bezier(.4,0,.2,1)"},{transform:`translate(${s}px,${o}px) scale(${a*.93},${l*.93})`,opacity:1,offset:.28,easing:"cubic-bezier(.32,1.38,.5,1)"},{transform:"translate(0px,0px) scale(1,1)",opacity:1,offset:1}],{duration:jw(),fill:"both"});Qn=r,Ur=c,window.addEventListener("resize",dn),c.onfinish=()=>{if(Qn!==r)return;const d=r.animate([{opacity:1},{opacity:0}],{duration:260,fill:"forwards"});d.onfinish=()=>{Qn===r&&dn()}}}function Hw(){const e=document.getElementById("composer")?.getBoundingClientRect();e&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{Ep({getBoundingClientRect:()=>e},document.getElementById("main-stage-container"))})})}function Ww(){Ep(document.getElementById("pipeline-progress"),document.getElementById("main-stage-container"))}window.addEventListener("hashchange",dn);window.addEventListener("popstate",dn);function Zs(t={}){const{prompt:e=null,runId:n}=t;if(!re(n))return;Qs(),nn(!0);const i=document.getElementById("pipeline-progress"),r=document.getElementById("results-view"),s=document.getElementById("ready-state");if(s&&s.classList.add("hidden"),r&&r.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),i&&i.classList.add("visible"),Ks("running"),e!==null){const a=document.getElementById("pipeline-submitted-prompt");a&&(a.textContent=e)}wp=Date.now();const o=document.getElementById("progress-elapsed");o&&(o.textContent="0s"),On={1:"pending",2:"pending",3:"pending"},nc(),ic(),bp(""),[1,2,3].forEach(a=>Rn(a,"pending")),Ft(1,n),zw()}function Ft(t,e){re(e)&&(Ql=t,nc(),[1,2,3].forEach(n=>{n===t?Rn(n,"active"):nt&&Rn(n,"pending")}),Js(t),Ys())}function tn(t,e){re(e)&&(Rn(t,"done"),ec===null&&Js(t,{done:!0}),Ys())}function Sp(t,{stage:e=1,runId:n,retry:i=xp}={}){if(!re(n))return;Xs(),Qs(),dn(),Ks("failed"),nn(!0);const r=document.getElementById("pipeline-progress");r&&r.classList.add("visible");const s=document.getElementById("results-view");s&&s.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),Rn(e,"failed"),[1,2,3].forEach(p=>{p>e&&Rn(p,"pending")}),Ql=e,nc(),Js(e),Ys();const o=kh(t),a=document.getElementById("pipeline-failure"),l=document.getElementById("pipeline-failure-title"),u=document.getElementById("pipeline-failure-message"),c=document.getElementById("pipeline-failure-hint"),d=document.getElementById("pipeline-failure-actions");if(!a||!l||!u||!d)return;if(a.dataset.kind=o.kind,l.textContent=`${Vs[e]}: ${o.title}`,u.textContent=o.message,c){const p=o.detail&&o.detail!==o.message?o.detail:"";c.textContent=p,c.hidden=!p}d.replaceChildren();const f=[o.canUpgrade&&{id:"upgrade",label:"View plans",variant:"primary",onClick:()=>di()},o.canRetry&&{id:"retry",label:"Retry",variant:o.canUpgrade?"secondary":"primary",onClick:i},o.canEdit&&{id:"edit",label:"Edit prompt",variant:"secondary",onClick:Ja}].filter(Boolean);!o.canEdit&&!o.canRetry&&f.push({id:"edit",label:"Back to prompt",variant:"secondary",onClick:Ja}),f.forEach(p=>{const g=document.createElement("button");g.type="button",g.textContent=p.label,g.dataset.action=p.id,g.dataset.variant=p.variant,g.addEventListener("click",p.onClick),d.appendChild(g)}),a.hidden=!1;const h=d.querySelector("button");h&&h.focus({preventScroll:!0})}function Ja(){Lw(),gw(),y.isRunning=!1,Ya(!1),rn(),Ks("settled"),dn(),Xs(),Qs(),ic();const t=document.getElementById("pipeline-progress");t&&t.classList.remove("visible"),nn(!1);const e=document.getElementById("pipeline-input");e&&(y.submittedPrompt&&(e.value=y.submittedPrompt,e.dispatchEvent(new Event("input",{bubbles:!0}))),e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length))}function xp(){const t=document.getElementById("pipeline-input");t&&y.submittedPrompt&&(t.value=y.submittedPrompt,t.dispatchEvent(new Event("input",{bubbles:!0}))),Oe=y.submittedImages.slice(),cn(),ic(),or()}function zw(){Xs(),jr=setInterval(()=>{const t=(Date.now()-wp)/1e3,e=document.getElementById("progress-elapsed");e&&(e.textContent=`${Math.floor(t)}s`)},250)}function Xs(){jr&&(clearInterval(jr),jr=null)}let Vi=null;function Qs(){Vi&&(clearTimeout(Vi),Vi=null)}function cr(){Xs(),Qs(),Ks("settled"),Ys();const t=document.getElementById("pipeline-progress-fill");Vi=setTimeout(()=>{Vi=null;const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function Tn(t,e=""){const n={pass:'',warning:'',fail:'',info:''};return``}function Ip(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function qw(){return __({bundle:y.artifactBundle,reviewResult:y.step3Result})}function Vw(t){return`
      ${Tn(t.severity)}
      @@ -174,14 +174,14 @@ Error: ${g} ${z(t.source)}
      - `}function Vw(t){return` + `}function Gw(t){return`
    • ${z(t.title)} ${t.detail&&t.detail!==t.title?`

      ${z(t.detail)}

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

      ${z(l.reason)}

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

      ${z(l.description)}

      `:""}
    • `).join(""):'
    • No relationships for this file
    • ';return`
      - ${Tn(e.status)} ${z(Sp(e.status))} + ${Tn(e.status)} ${z(Ip(e.status))}

      ${z(e.artifactName)}

      ${e.description?`

      ${z(e.description)}

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

      Manual FlutterFlow steps for this file

      -
        ${e.manualSteps.map(Vw).join("")}
      +
        ${e.manualSteps.map(Gw).join("")}
      `:""}
      @@ -297,7 +297,7 @@ Error: ${g}
        ${a}
      - `}function Yw(t){const e=document.getElementById("bundle-strip"),n=document.getElementById("results-summary-tab"),i=document.getElementById("artifact-tabs"),r=document.getElementById("results-file-count");if(n){const s=y.resultsViewMode==="summary";n.classList.toggle("active",s),n.setAttribute("role","tab"),n.setAttribute("aria-selected",String(s)),n.setAttribute("aria-controls","results-summary-detail"),n.tabIndex=s?0:-1}if(i&&(i.setAttribute("role","tablist"),i.setAttribute("aria-label","Artifacts in this bundle")),!t.artifacts.length){r&&(r.textContent="0 files"),e&&e.classList.remove("visible"),i&&(i.innerHTML=""),ud();return}if(r){const s=t.artifacts.length;r.textContent=`${s} ${s===1?"file":"files"}`}i&&(i.innerHTML=t.artifacts.map(s=>{const o=y.resultsViewMode==="file"&&s.id===y.selectedArtifactId;return` + `}function Jw(t){const e=document.getElementById("bundle-strip"),n=document.getElementById("results-summary-tab"),i=document.getElementById("artifact-tabs"),r=document.getElementById("results-file-count");if(n){const s=y.resultsViewMode==="summary";n.classList.toggle("active",s),n.setAttribute("role","tab"),n.setAttribute("aria-selected",String(s)),n.setAttribute("aria-controls","results-summary-detail"),n.tabIndex=s?0:-1}if(i&&(i.setAttribute("role","tablist"),i.setAttribute("aria-label","Artifacts in this bundle")),!t.artifacts.length){r&&(r.textContent="0 files"),e&&e.classList.remove("visible"),i&&(i.innerHTML=""),dd();return}if(r){const s=t.artifacts.length;r.textContent=`${s} ${s===1?"file":"files"}`}i&&(i.innerHTML=t.artifacts.map(s=>{const o=y.resultsViewMode==="file"&&s.id===y.selectedArtifactId;return` - `}).join(""),i.onclick=s=>{const o=s.target.closest(".artifact-tab");o?.dataset?.artifactId&&ic(o.dataset.artifactId)},ud()),e&&e.classList.add("visible")}function ud(){const t=document.getElementById("bundle-strip");!t||t.dataset.tabKeyboard==="bound"||(t.dataset.tabKeyboard="bound",t.addEventListener("keydown",e=>{if(e.defaultPrevented)return;const n=[document.getElementById("results-summary-tab"),...Array.from(document.querySelectorAll("#artifact-tabs .artifact-tab"))].filter(Boolean);if(!n.length||!n.includes(document.activeElement))return;let i=-1;const r=n.indexOf(document.activeElement);if(e.key==="ArrowRight")i=(r+1)%n.length;else if(e.key==="ArrowLeft")i=(r-1+n.length)%n.length;else if(e.key==="Home")i=0;else if(e.key==="End")i=n.length-1;else return;e.preventDefault();const s=n[i];if(!s)return;if(s.id==="results-summary-tab")xp();else{const a=s.dataset.artifactId;a&&ic(a)}const o=s.id==="results-summary-tab"?document.getElementById("results-summary-tab"):document.querySelector(`#artifact-tabs .artifact-tab[data-artifact-id="${s.dataset.artifactId}"]`);o&&o.focus()}))}function to(){document.body.classList.add("results-fullscreen"),document.body.classList.add("results-with-sidebar");const t=document.getElementById("results-view"),e=document.getElementById("results-code-output"),n=document.getElementById("results-audit-output"),i=document.getElementById("results-summary-detail"),r=document.getElementById("artifact-results-split"),s=zw(),o=Bl();if(i&&(i.setAttribute("role","tabpanel"),i.setAttribute("aria-labelledby","results-summary-tab")),r){r.setAttribute("role","tabpanel");const a=s?.artifacts?.find(l=>l.id===y.selectedArtifactId);r.setAttribute("aria-labelledby",a?`artifact-tab-${a.id}`:"results-summary-tab")}if(Gw(s),Yw(s),e&&(e.textContent=""),e){const a=Ih(o);e.innerHTML=a}n&&(n.innerHTML=Kw(s)),i&&i.classList.toggle("hidden",y.resultsViewMode!=="summary"),r&&r.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function ur(t,e){nn(!0),y.selectedArtifactId||(y.selectedArtifactId=oi(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const n=document.getElementById("step3-output");n&&(n.textContent=""),to(),rn(),Jw()}function Jw(){const t=document.getElementById("btn-feedback-up"),e=document.getElementById("btn-feedback-down"),n=document.getElementById("results-feedback-status");t&&(t.className="feedback-btn",t.setAttribute("aria-pressed","false"),t.disabled=!1,t.removeAttribute("aria-disabled")),e&&(e.className="feedback-btn",e.setAttribute("aria-pressed","false"),e.disabled=!1,e.removeAttribute("aria-disabled")),n&&(n.textContent=""),Za=!1}function ic(t){y.selectedArtifactId=t,y.resultsViewMode="file",to()}function xp(){y.resultsViewMode="summary",to()}function Zw(){const t=document.getElementById("btn-copy-results"),e=document.getElementById("results-copy-status"),n=Bl(),i=(r,s)=>{e&&(e.textContent=r,e.classList.toggle("ok",!!s),e.classList.toggle("fail",!s))};if(!navigator.clipboard?.writeText){i("Copying isn't supported in this browser.",!1);return}navigator.clipboard.writeText(n).then(()=>{if(i("Copied to clipboard",!0),t){t.classList.add("copied");const r=t.querySelector("span");if(r){const s=r.textContent;r.textContent="Copied!",setTimeout(()=>{t.classList.remove("copied"),r.textContent=s},2e3)}}}).catch(()=>{i("Clipboard permission was denied. Select the code to copy it manually.",!1)})}let Za=!1;async function Xw(t){const e=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down"),i=document.getElementById("results-feedback-status");if(!e||!n||Za)return;const r=l=>{i&&(i.textContent="",i.offsetWidth,i.textContent=l)},s=l=>{Za=l,[e,n].forEach(u=>{u.disabled=l,u.setAttribute("aria-disabled",String(l))})},o=t==="up"?"thumbsUp":"thumbsDown";s(!0),r("Submitting review feedback…");const a={type:o,code:y.step2Result,input:y.step1Result};try{const l=await Vl(a.type,a.code,a.input);if(!l||l.success!==!0){s(!1),r("Review feedback could not be sent. Tap again to retry.");return}e.classList.toggle("active-up",t==="up"),n.classList.toggle("active-down",t==="down"),e.setAttribute("aria-pressed",String(t==="up")),n.setAttribute("aria-pressed",String(t==="down")),s(!1),r("Review feedback saved.")}catch{s(!1),r("Review feedback could not be sent. Tap again to retry.")}}function Qw(){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 Ip(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}function nn(t){const e=document.getElementById("generation-stage");e&&(t?(e.hidden=!1,e.inert=!1,requestAnimationFrame(()=>e.classList.add("is-active"))):(e.classList.remove("is-active"),e.inert=!0,setTimeout(()=>{e.classList.contains("is-active")||(e.hidden=!0)},260)))}function kp(){const t=q.isVerified&&!!q.email,e=ce.tier||"free",n=t&&pi(),i=!t||Tt(),s=n?"Checking…":i?ml[e]||"Free":"—",o=document.getElementById("topbar-plan");o&&(o.textContent=s);const a=document.getElementById("topbar-avatar");a&&(a.textContent=(q.email||"?")[0].toUpperCase()),Kl();const l=document.getElementById("plans-free-current");l&&l.classList.toggle("hidden",e!=="free"||!i);const u=document.getElementById("plans-checkout-btn-professional");if(u){const d=e==="professional"&&i;u.disabled=d,u.textContent=d?"Current plan":"Subscribe"}const c=document.getElementById("plans-checkout-btn-power");if(c){const d=e==="power"&&i;c.disabled=d,c.textContent=d?"Current plan":"Subscribe"}}function eb(){kp();const t=document.getElementById("credits-modal");t&&We(t)}function tb(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("credits-modal");e&&ze(e)}function Cp(t,e=!0,n=!0){if(t=["home","account","plans"].includes(t)?t:"home",document.querySelectorAll(".view[data-view]").forEach(r=>{r.dataset.view===t?(r.hidden=!1,r.removeAttribute("inert"),requestAnimationFrame(()=>{r.classList.add("is-active"),n&&r.focus({preventScroll:!0})})):(r.classList.remove("is-active"),r.setAttribute("inert","true"),setTimeout(()=>{r.classList.contains("is-active")||(r.hidden=!0)},260))}),t!=="home")nn(!1);else{const r=document.getElementById("main-stage-container");r&&r.classList.contains("visible")&&nn(!0)}if(document.querySelectorAll(".nav-link[data-view]").forEach(r=>{const s=r.dataset.view===t;r.setAttribute("aria-current",s?"page":null),s||r.removeAttribute("aria-current")}),e){const r=t==="home"?"":`#${t}`;window.location.hash!==r&&window.history.pushState({view:t},"",r||"#")}}let dd=!1;function rc(){const t=window.location.hash.replace(/^#/,"");Cp(t||"home",!1,dd),dd=!0}window.addEventListener("popstate",t=>{rc()});window.addEventListener("hashchange",()=>{rc()});window.copyResultsCode=Zw;window.selectArtifact=ic;window.selectResultsSummary=xp;window.submitResultsFeedback=Xw;window.showErrorInputPanel=Qw;window.hideErrorInputPanel=Ip;window.setGenerationStageVisible=nn;window.switchView=Cp;window.selectPipelineStage=Nw;window.editPipelinePrompt=Ja;window.retryPipelineRun=Ep;window.openCreditsModal=eb;window.closeCreditsModal=tb; + `}).join(""),i.onclick=s=>{const o=s.target.closest(".artifact-tab");o?.dataset?.artifactId&&rc(o.dataset.artifactId)},dd()),e&&e.classList.add("visible")}function dd(){const t=document.getElementById("bundle-strip");!t||t.dataset.tabKeyboard==="bound"||(t.dataset.tabKeyboard="bound",t.addEventListener("keydown",e=>{if(e.defaultPrevented)return;const n=[document.getElementById("results-summary-tab"),...Array.from(document.querySelectorAll("#artifact-tabs .artifact-tab"))].filter(Boolean);if(!n.length||!n.includes(document.activeElement))return;let i=-1;const r=n.indexOf(document.activeElement);if(e.key==="ArrowRight")i=(r+1)%n.length;else if(e.key==="ArrowLeft")i=(r-1+n.length)%n.length;else if(e.key==="Home")i=0;else if(e.key==="End")i=n.length-1;else return;e.preventDefault();const s=n[i];if(!s)return;if(s.id==="results-summary-tab")kp();else{const a=s.dataset.artifactId;a&&rc(a)}const o=s.id==="results-summary-tab"?document.getElementById("results-summary-tab"):document.querySelector(`#artifact-tabs .artifact-tab[data-artifact-id="${s.dataset.artifactId}"]`);o&&o.focus()}))}function eo(){document.body.classList.add("results-fullscreen"),document.body.classList.add("results-with-sidebar");const t=document.getElementById("results-view"),e=document.getElementById("results-code-output"),n=document.getElementById("results-audit-output"),i=document.getElementById("results-summary-detail"),r=document.getElementById("artifact-results-split"),s=qw(),o=Bl();if(i&&(i.setAttribute("role","tabpanel"),i.setAttribute("aria-labelledby","results-summary-tab")),r){r.setAttribute("role","tabpanel");const a=s?.artifacts?.find(l=>l.id===y.selectedArtifactId);r.setAttribute("aria-labelledby",a?`artifact-tab-${a.id}`:"results-summary-tab")}if(Kw(s),Jw(s),e&&(e.textContent=""),e){const a=Ch(o);e.innerHTML=a}n&&(n.innerHTML=Yw(s)),i&&i.classList.toggle("hidden",y.resultsViewMode!=="summary"),r&&r.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function ur(t,e){nn(!0),y.selectedArtifactId||(y.selectedArtifactId=oi(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const n=document.getElementById("step3-output");n&&(n.textContent=""),eo(),rn(),Zw()}function Zw(){const t=document.getElementById("btn-feedback-up"),e=document.getElementById("btn-feedback-down"),n=document.getElementById("results-feedback-status");t&&(t.className="feedback-btn",t.setAttribute("aria-pressed","false"),t.disabled=!1,t.removeAttribute("aria-disabled")),e&&(e.className="feedback-btn",e.setAttribute("aria-pressed","false"),e.disabled=!1,e.removeAttribute("aria-disabled")),n&&(n.textContent=""),Za=!1}function rc(t){y.selectedArtifactId=t,y.resultsViewMode="file",eo()}function kp(){y.resultsViewMode="summary",eo()}function Xw(){const t=document.getElementById("btn-copy-results"),e=document.getElementById("results-copy-status"),n=Bl(),i=(r,s)=>{e&&(e.textContent=r,e.classList.toggle("ok",!!s),e.classList.toggle("fail",!s))};if(!navigator.clipboard?.writeText){i("Copying isn't supported in this browser.",!1);return}navigator.clipboard.writeText(n).then(()=>{if(i("Copied to clipboard",!0),t){t.classList.add("copied");const r=t.querySelector("span");if(r){const s=r.textContent;r.textContent="Copied!",setTimeout(()=>{t.classList.remove("copied"),r.textContent=s},2e3)}}}).catch(()=>{i("Clipboard permission was denied. Select the code to copy it manually.",!1)})}let Za=!1;async function Qw(t){const e=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down"),i=document.getElementById("results-feedback-status");if(!e||!n||Za)return;const r=l=>{i&&(i.textContent="",i.offsetWidth,i.textContent=l)},s=l=>{Za=l,[e,n].forEach(u=>{u.disabled=l,u.setAttribute("aria-disabled",String(l))})},o=t==="up"?"thumbsUp":"thumbsDown";s(!0),r("Submitting review feedback…");const a={type:o,code:y.step2Result,input:y.step1Result};try{const l=await Gl(a.type,a.code,a.input);if(!l||l.success!==!0){s(!1),r("Review feedback could not be sent. Tap again to retry.");return}e.classList.toggle("active-up",t==="up"),n.classList.toggle("active-down",t==="down"),e.setAttribute("aria-pressed",String(t==="up")),n.setAttribute("aria-pressed",String(t==="down")),s(!1),r("Review feedback saved.")}catch{s(!1),r("Review feedback could not be sent. Tap again to retry.")}}function eb(){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 Cp(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}function nn(t){const e=document.getElementById("generation-stage");e&&(t?(e.hidden=!1,e.inert=!1,requestAnimationFrame(()=>e.classList.add("is-active"))):(e.classList.remove("is-active"),e.inert=!0,setTimeout(()=>{e.classList.contains("is-active")||(e.hidden=!0)},260)))}function Ap(){const t=q.isVerified&&!!q.email,e=ce.tier||"free",n=t&&pi(),i=!t||Tt(),s=n?"Checking…":i?ml[e]||"Free":"—",o=document.getElementById("topbar-plan");o&&(o.textContent=s);const a=document.getElementById("topbar-avatar");a&&(a.textContent=(q.email||"?")[0].toUpperCase()),Yl();const l=document.getElementById("plans-free-current");l&&l.classList.toggle("hidden",e!=="free"||!i);const u=document.getElementById("plans-checkout-btn-professional");if(u){const d=e==="professional"&&i;u.disabled=d,u.textContent=d?"Current plan":"Subscribe"}const c=document.getElementById("plans-checkout-btn-power");if(c){const d=e==="power"&&i;c.disabled=d,c.textContent=d?"Current plan":"Subscribe"}}function tb(){Ap();const t=document.getElementById("credits-modal");t&&We(t)}function nb(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("credits-modal");e&&ze(e)}function Pp(t,e=!0,n=!0){if(t=["home","account","plans"].includes(t)?t:"home",document.querySelectorAll(".view[data-view]").forEach(r=>{r.dataset.view===t?(r.hidden=!1,r.removeAttribute("inert"),requestAnimationFrame(()=>{r.classList.add("is-active"),n&&r.focus({preventScroll:!0})})):(r.classList.remove("is-active"),r.setAttribute("inert","true"),setTimeout(()=>{r.classList.contains("is-active")||(r.hidden=!0)},260))}),t!=="home")nn(!1);else{const r=document.getElementById("main-stage-container");r&&r.classList.contains("visible")&&nn(!0)}if(document.querySelectorAll(".nav-link[data-view]").forEach(r=>{const s=r.dataset.view===t;r.setAttribute("aria-current",s?"page":null),s||r.removeAttribute("aria-current")}),e){const r=t==="home"?"":`#${t}`;window.location.hash!==r&&window.history.pushState({view:t},"",r||"#")}}let fd=!1;function sc(){const t=window.location.hash.replace(/^#/,"");Pp(t||"home",!1,fd),fd=!0}window.addEventListener("popstate",t=>{sc()});window.addEventListener("hashchange",()=>{sc()});window.copyResultsCode=Xw;window.selectArtifact=rc;window.selectResultsSummary=kp;window.submitResultsFeedback=Qw;window.showErrorInputPanel=eb;window.hideErrorInputPanel=Cp;window.setGenerationStageVisible=nn;window.switchView=Pp;window.selectPipelineStage=Ow;window.editPipelinePrompt=Ja;window.retryPipelineRun=xp;window.openCreditsModal=tb;window.closeCreditsModal=nb; diff --git a/dist/index.html b/dist/index.html index 8609b4f..84fe68c 100644 --- a/dist/index.html +++ b/dist/index.html @@ -3313,7 +3313,7 @@ .send.is-busy .send-spin { animation: none; opacity: 0.6; } } - + diff --git a/e2e/stu380-deploy.spec.js b/e2e/stu380-deploy.spec.js index 6545648..c979347 100644 --- a/e2e/stu380-deploy.spec.js +++ b/e2e/stu380-deploy.spec.js @@ -760,28 +760,39 @@ test.describe("STU-380 transport outcome regressions", () => { // A 4xx that sends a byte then keeps the body open is still a definitive // refusal — the status alone decides, so the parse must not wait on the - // body past the diagnostic bound. + // body past the diagnostic bound. And the bounded read must cancel the + // stream, not leave a pending reader holding the connection. const outcome = await page.evaluate(async () => { + let streamCancelled = false; const body = new ReadableStream({ start(controller) { controller.enqueue(new TextEncoder().encode("{")); // Never closes — the stalled body must not block classification. }, + cancel() { + streamCancelled = true; + }, }); try { const parsed = await window.__CCC_PARSE_PUSH_RESPONSE__( new Response(body, { status: 403 }), 50, ); - return { settled: "resolved", parsed }; + return { settled: "resolved", parsed, streamCancelled }; } catch (error) { - return { settled: "rejected", name: error.name, message: error.message }; + return { + settled: "rejected", + name: error.name, + message: error.message, + streamCancelled, + }; } }); expect(outcome.settled).toBe("resolved"); expect(outcome.parsed.success).toBe(false); expect(outcome.parsed.responseCode).toBe(403); + expect(outcome.streamCancelled).toBe(true); }); test("a server error with an unreadable body still lands as unconfirmed", async ({ page }) => { From c32e91ca24cfe7290034faa34797538d12d15464 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Sun, 27 Sep 2026 18:06:42 +0000 Subject: [PATCH 13/16] fix(deploy): scope preWrite to parse errors, drain discarded bodies, re-invalidate on late settle MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Runner: FormatException from request validation is pre-write, but the same exception decoding CLI output can fire after deploy_start — it now falls to the generic catch (preWrite:false) instead of masking a write. - pushCodeWithRetry: the diagnostic read consumes the response itself when the loop won't return it (500-retry, 5xx/uncertain throws) — clone() would tee the body and leave the original branch's connection open; only the definitive-refusal path logs a clone since its original body goes to parsePushCodeResponse. - provisionMissingCodeFiles: an unconfirmed provision's underlying work keeps running past the UI bound; it now invalidates the project-source cache again when that work actually settles, so a snapshot exported mid-write by a later deploy can't survive to provision the class twice. Co-Authored-By: Stuart Gardoll --- app.js | 90 ++++++++------ cloud-run/ffai-runner/bin/server.dart | 59 ++++++---- .../{index-DuMP9yQl.js => index-Cltjl6vK.js} | 68 +++++------ dist/index.html | 2 +- e2e/stu380-deploy.spec.js | 111 ++++++++++++++++++ 5 files changed, 241 insertions(+), 89 deletions(-) rename dist/assets/{index-DuMP9yQl.js => index-Cltjl6vK.js} (92%) diff --git a/app.js b/app.js index 68343b4..9aeed9a 100644 --- a/app.js +++ b/app.js @@ -2232,8 +2232,17 @@ class FlutterFlowApiClient { // The status alone classifies this response — the body read is // diagnostic only: detached so it can't block the refusal path, and // bounded+cancelled so a stalled body can't leave a reader (and its - // connection) open past the bound. - readBodyBounded(response.clone(), PUSH_BODY_READ_TIMEOUT_MS).then( + // connection) open past the bound. A response this loop will not + // hand back to the caller is read directly — teeing it with clone() + // would leave the original branch (and its connection) feeding a + // reader that doesn't exist; only the definitive-refusal path keeps + // the original body for parsePushCodeResponse, so it logs a clone. + const returnedToCaller = + response.status < 500 && !sawUncertainAttempt; + readBodyBounded( + returnedToCaller ? response.clone() : response, + PUSH_BODY_READ_TIMEOUT_MS, + ).then( (responseText) => console.log( `Push to ${baseUrl} returned ${response.status}: ${responseText}`, @@ -2795,39 +2804,44 @@ async function provisionMissingCodeFiles( // any response is still an unknown outcome — the POST may have reached the // server — so it maps to unconfirmed, not failed. let result; + // Kept outside the try: when the UI bound expires the work keeps running on + // the runner, and its eventual settlement needs to invalidate the cache a + // second time (a snapshot exported mid-write is still stale). + let provisionWork; try { - result = await withUiTimeout( - (async () => { - let response; - try { - response = await fetch(FLUTTERFLOW_CLASS_PROVISION_ENDPOINT, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ - apiKey: apiClient.apiKey, - projectId: apiClient.projectId, - baseUrl: apiClient.baseUrl, - commitMessage, - customClasses: missingCodeFiles, - verification, - stream: true, - }), - }); - } catch (fetchError) { - throw new UnconfirmedDeployError( - "The provisioning request did not return a response. The deploy may have reached the " + - "FlutterFlow server — open your FlutterFlow project to reconcile before retrying.", - ); - } - return readProvisionResponse(response, { - onPhase: (message) => { - if (progressLive) commitProgress.setSubstatus(message); - }, - onLog: (message) => { - if (progressLive) console.log(`[custom class deploy] ${message}`); - }, + provisionWork = (async () => { + let response; + try { + response = await fetch(FLUTTERFLOW_CLASS_PROVISION_ENDPOINT, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + apiKey: apiClient.apiKey, + projectId: apiClient.projectId, + baseUrl: apiClient.baseUrl, + commitMessage, + customClasses: missingCodeFiles, + verification, + stream: true, + }), }); - })(), + } catch (fetchError) { + throw new UnconfirmedDeployError( + "The provisioning request did not return a response. The deploy may have reached the " + + "FlutterFlow server — open your FlutterFlow project to reconcile before retrying.", + ); + } + return readProvisionResponse(response, { + onPhase: (message) => { + if (progressLive) commitProgress.setSubstatus(message); + }, + onLog: (message) => { + if (progressLive) console.log(`[custom class deploy] ${message}`); + }, + }); + })(); + result = await withUiTimeout( + provisionWork, uiTimeoutMs, (resolve, reject) => { progressLive = false; @@ -2890,6 +2904,16 @@ async function provisionMissingCodeFiles( // the same classes a second time. if (error instanceof UnconfirmedDeployError) { invalidateProjectSourceCache(apiClient); + // The runner can still be writing after this browser stopped waiting. + // A deploy that starts in the meantime exports and caches a snapshot + // taken mid-write — stale the moment the runner's write lands. Drop the + // cache again when this request actually settles; snapshots cached + // after settlement postdate the write and are left alone. At worst a + // correct snapshot is dropped and the next deploy re-exports once. + provisionWork?.then( + () => invalidateProjectSourceCache(apiClient), + () => invalidateProjectSourceCache(apiClient), + ); } throw error; } diff --git a/cloud-run/ffai-runner/bin/server.dart b/cloud-run/ffai-runner/bin/server.dart index 99181c2..44e5525 100644 --- a/cloud-run/ffai-runner/bin/server.dart +++ b/cloud-run/ffai-runner/bin/server.dart @@ -57,19 +57,41 @@ Future _handle(HttpRequest request) async { return; } - final payload = await _readJson(request); - final apiKey = _stringField(payload, 'apiKey', maxLength: 10000); - final projectId = _stringField(payload, 'projectId', maxLength: 200); - final baseUrl = _stringField(payload, 'baseUrl', maxLength: 500, required: false); - final commitMessage = _stringField( - payload, - 'commitMessage', - maxLength: 300, - required: false, - ); - final dryRun = payload['dryRun'] == true; - final classes = _normalizeClasses(payload['customClasses']); - final verification = _normalizeVerification(payload['verification']); + // Only request parsing/validation throws FormatException here — those are + // provably pre-write. Decoding CLI output can raise the same exception + // AFTER the deploy began, so it must fall to the generic catch below, + // which does not claim preWrite. + Map payload; + String apiKey; + String projectId; + String baseUrl; + String commitMessage; + bool dryRun; + List classes; + _VerificationRequest? verification; + try { + payload = await _readJson(request); + apiKey = _stringField(payload, 'apiKey', maxLength: 10000); + projectId = _stringField(payload, 'projectId', maxLength: 200); + baseUrl = _stringField(payload, 'baseUrl', maxLength: 500, required: false); + commitMessage = _stringField( + payload, + 'commitMessage', + maxLength: 300, + required: false, + ); + dryRun = payload['dryRun'] == true; + classes = _normalizeClasses(payload['customClasses']); + verification = _normalizeVerification(payload['verification']); + } on FormatException catch (error) { + await channel.result(HttpStatus.badRequest, { + 'success': false, + 'error': error.message, + // Request validation precedes any work against the project. + 'preWrite': true, + }); + return; + } // Only stream for callers that asked for it, so older clients keep getting // the single JSON response they parse. @@ -188,20 +210,15 @@ Future _handle(HttpRequest request) async { 'verified': analysis?.verifiedFiles ?? const [], 'verificationSkipped': analysis?.skippedReason, }); - } on FormatException catch (error) { - await channel.result(HttpStatus.badRequest, { - 'success': false, - 'error': error.message, - // Request validation precedes any work against the project. - 'preWrite': true, - }); } catch (error, stackTrace) { stderr.writeln(error); stderr.writeln(stackTrace); await channel.result(HttpStatus.internalServerError, { 'success': false, 'error': '$error', - // The stage is unknown, so the write cannot be proven not to have run. + // The stage is unknown — a FormatException from decoding CLI output can + // land here after the upload began — so the write cannot be proven not + // to have run. 'preWrite': false, }); } diff --git a/dist/assets/index-DuMP9yQl.js b/dist/assets/index-Cltjl6vK.js similarity index 92% rename from dist/assets/index-DuMP9yQl.js rename to dist/assets/index-Cltjl6vK.js index d1bbd39..80fc518 100644 --- a/dist/assets/index-DuMP9yQl.js +++ b/dist/assets/index-Cltjl6vK.js @@ -1,6 +1,6 @@ -(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const s of r)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function n(r){const s={};return r.integrity&&(s.integrity=r.integrity),r.referrerPolicy&&(s.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?s.credentials="include":r.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function i(r){if(r.ep)return;r.ep=!0;const s=n(r);fetch(r.href,s)}})();var w=typeof window<"u"?window:void 0,Ne=typeof globalThis<"u"?globalThis:w,He=Ne?.navigator,P=Ne?.document,me=Ne?.location,Xa=Ne?.fetch,zo=Ne!=null&&Ne.XMLHttpRequest&&"withCredentials"in new Ne.XMLHttpRequest?Ne.XMLHttpRequest:void 0,fc=Ne?.AbortController,Np=Ne?.CompressionStream,Ge=He?.userAgent;function hd(){return!(!w||w.navigator.onLine===!1)}var vi=typeof globalThis<"u"?globalThis:w;vi&&typeof self>"u"&&(vi.self=vi),vi&&typeof File>"u"&&(vi.File=function(){});var B=w??{},ne={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function hc(t,e,n,i,r,s,o){try{var a=t[s](o),l=a.value}catch(u){return void n(u)}a.done?e(l):Promise.resolve(l).then(i,r)}function se(t){return function(){var e=this,n=arguments;return new Promise((function(i,r){var s=t.apply(e,n);function o(l){hc(s,i,r,o,a,"next",l)}function a(l){hc(s,i,r,o,a,"throw",l)}o(void 0)}))}}function I(){return I=Object.assign?Object.assign.bind():function(t){for(var e=1;arguments.length>e;e++){var n=arguments[e];for(var i in n)({}).hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},I.apply(null,arguments)}function pd(t,e){if(t==null)return{};var n={};for(var i in t)if({}.hasOwnProperty.call(t,i)){if(e.indexOf(i)!==-1)continue;n[i]=t[i]}return n}var pc=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function gc(t){return typeof t=="string"||t}function mc(t){return typeof t=="string"?t:void 0}var _i,Op=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],Ut=(function(t){return t.AnonymousId="anonymous_id",t.DistinctId="distinct_id",t.Props="props",t.EnablePersonProcessing="enable_person_processing",t.PersonMode="person_mode",t.FeatureFlagDetails="feature_flag_details",t.FeatureFlags="feature_flags",t.FeatureFlagPayloads="feature_flag_payloads",t.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",t.BootstrapFeatureFlags="bootstrap_feature_flags",t.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",t.OverrideFeatureFlags="override_feature_flags",t.Queue="queue",t.AiQueue="ai_queue",t.LogsQueue="logs_queue",t.OptedOut="opted_out",t.SessionId="session_id",t.SessionStartTimestamp="session_start_timestamp",t.SessionLastTimestamp="session_timestamp",t.PersonProperties="person_properties",t.GroupProperties="group_properties",t.InstalledAppBuild="installed_app_build",t.InstalledAppVersion="installed_app_version",t.SessionReplay="session_replay",t.PushRegistered="push_registered",t.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",t.SurveyLastSeenDate="survey_last_seen_date",t.SurveysSeen="surveys_seen",t.Surveys="surveys",t.RemoteConfig="remote_config",t.FlagsEndpointWasHit="flags_endpoint_was_hit",t.DeviceId="device_id",t})({}),vc=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),Bp=["$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"],Dp=["token"],gd="NativeGzipValidationError",qo=t=>t.length>=2&&t[0]===31&&t[1]===139,_c=(t,e)=>t===vc.GZipJS||e===vc.GZipJS||e==="gzip",yc=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",pr=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=gd,e},jp=(function(){var t=se((function*(e,n){18>e.size&&pr("too-short");var i=new Uint8Array(yield e.slice(0,10).arrayBuffer());qo(i)&&i[2]===8||pr("invalid-header");var r=new DataView(yield e.slice(e.size-8).arrayBuffer());r.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(_i)return _i;_i=[];for(var c=0;256>c;c++){for(var d=c,f=0;8>f;f++)d=1&d?3988292384^d>>>1:d>>>1;_i[c]=d>>>0}return _i})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(n)&&pr("invalid-crc");var s=n.length>>>0;r.getUint32(4,!0)!==s&&pr("invalid-size")}));return function(e,n){return t.apply(this,arguments)}})();function Vo(){return Vo=se((function*(t,e,n){e===void 0&&(e=!0);try{var i=new TextEncoder().encode(t),r=new globalThis.CompressionStream("gzip"),s=r.writable.getWriter(),o=s.write(i).then((()=>s.close())).catch((function(){var u=se((function*(c){try{yield s.abort(c)}catch{}throw c}));return function(c){return u.apply(this,arguments)}})()),a=new Response(r.readable).blob(),l=(yield Promise.all([a,o]))[0];return yield jp(l,i),l}catch(u){if(n!=null&&n.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),Vo.apply(this,arguments)}var Up=["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"],wc=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var n=t.toLowerCase();return Up.concat(e).some((i=>{var r=i.toLowerCase();return n.indexOf(r)!==-1}))};function j(t,e){return t.indexOf(e)!==-1}var xs=function(t){return t.trim()},Go=function(t){return t.replace(/^\$/,"")};function md(t){var e,n=[];return(e=JSON.stringify(t,(function(i,r){if(typeof r=="bigint")return r.toString();if(typeof r!="function"&&typeof r!="symbol"){if(r instanceof Error)return{name:r.name,message:r.message,stack:r.stack};if(r&&typeof r=="object"){for(;n.length>0&&n[n.length-1]!==this;)n.pop();if(n.includes(r))return"[Circular]";n.push(r)}return r}})))!==null&&e!==void 0?e:"null"}var vd=Object.prototype,_d=vd.hasOwnProperty,Is=vd.toString,U=Array.isArray||function(t){return Is.call(t)==="[object Array]"},je=t=>typeof t=="function",he=t=>t===Object(t)&&!U(t),Kt=t=>{if(he(t)){for(var e in t)if(_d.call(t,e))return!1;return!0}return!1},C=t=>t===void 0,X=t=>Is.call(t)=="[object String]",Ko=t=>X(t)&&t.trim().length===0,Ye=t=>t===null,H=t=>C(t)||Ye(t),ke=t=>Is.call(t)=="[object Number]"&&t==t,Dt=t=>ke(t)&&t>0,mt=t=>Is.call(t)==="[object Boolean]",Hp=t=>t instanceof FormData,Wp=t=>j(Bp,t),zp=t=>j(Dp,t);function yd(t){return t===null||typeof t!="object"}function Hr(t,e){return{}.toString.call(t)==="[object "+e+"]"}function Qa(t){return typeof Event<"u"&&wd(t,Event)}function wd(t,e){try{return t instanceof e}catch{return!1}}var qp=[!0,"true",1,"1","yes"],uo=t=>j(qp,t),Vp=[!1,"false",0,"0","no"];function At(t,e,n,i,r){return e>n&&(i.warn("min cannot be greater than max."),e=n),ke(t)?t>n?(i.warn(" cannot be greater than max: "+n+". Using max value instead."),n):e>t?(i.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(i.warn(" must be a number. using max or fallback. max: "+n+", fallback: "+r),At(r||n,e,n,i))}class Gp{constructor(e){this.tt={},this.et=e.et,this.it=At(e.bucketSize,0,100,e.rt),this.nt=At(e.refillRate,0,this.it,e.rt),this.st=At(e.refillInterval,0,864e5,e.rt)}ot(e,n){var i=Math.floor((n-e.lastAccess)/this.st);i>0&&(e.tokens=Math.min(e.tokens+i*this.nt,this.it),e.lastAccess=e.lastAccess+i*this.st)}consumeRateLimit(e){var n,i=Date.now(),r=String(e),s=this.tt[r];return s?this.ot(s,i):this.tt[r]=s={tokens:this.it,lastAccess:i},s.tokens===0||(s.tokens--,s.tokens===0&&((n=this.et)==null||n.call(this,e)),s.tokens===0)}stop(){this.tt={}}}var rt="Mobile",Wr="iOS",Yt="Android",ei="Tablet",bd=Yt+" "+ei,Ed="iPad",Sd="Apple",xd=Sd+" Watch",Bi="Safari",ti="BlackBerry",Id="Samsung",kd=Id+"Browser",Cd=Id+" Internet",Pn="Chrome",Kp=Pn+" OS",Ad=Pn+" "+Wr,el="Internet Explorer",Pd=el+" "+rt,tl="Opera",Yp=tl+" Mini",nl="Edge",Fd="Microsoft "+nl,Zn="Firefox",Rd=Zn+" "+Wr,Gi="Nintendo",Ki="PlayStation",Xn="Xbox",Td=Yt+" "+rt,$d=rt+" "+Bi,Pi="Windows",Yo=Pi+" Phone",bc="Nokia",Jo="Ouya",Md="Generic",Jp=Md+" "+rt.toLowerCase(),Ld=Md+" "+ei.toLowerCase(),Zo="Konqueror",Nd="Oculus Browser",zr="Vivaldi",Od="Yandex",qr="Whale",Xo="DuckDuckGo",Bd="Pale Moon",Vr="Waterfox",Di="Brave",Dd="Google Search App",we="(\\d+(\\.\\d+)?)",fo=new RegExp("Version/"+we),Zp=new RegExp(Xn,"i"),Xp=new RegExp(Ki+" \\w+","i"),Qp=new RegExp(Gi+" \\w+","i"),il=new RegExp(ti+"|PlayBook|BB10","i"),eg={"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"},jd=function(t,e,n,i){e=e||"";var r=(function(s){return s!=null&&s.brave?Di:null})(n);return r||(i!=null&&i.detectGoogleSearchApp&&j(t,"GSA/")?Dd:j(t," OPR/")&&j(t,"Mini")?Yp:j(t," OPR/")?tl:il.test(t)?ti:j(t,"IE"+rt)||j(t,"WPDesktop")?Pd:j(t,"OculusBrowser")?Nd:j(t,kd)?Cd:j(t,nl)||j(t,"Edg/")?Fd:j(t,zr+"/")?zr:j(t,"YaBrowser/")?Od:j(t,qr+"/")?qr:j(t,Xo+"/")||j(t,"Ddg/")?Xo:j(t,"FBIOS")?"Facebook "+rt:j(t,"UCWEB")||j(t,"UCBrowser")?"UC Browser":j(t,"CriOS")?Ad:j(t,"CrMo")||j(t,Pn)?Pn:j(t,Yt)&&j(t,Bi)?Td:j(t,"FxiOS")?Rd:j(t.toLowerCase(),Zo.toLowerCase())?Zo:j(t,Di+"/")?Di:((s,o)=>o&&j(o,Sd)||(function(a){return j(a,Bi)&&!j(a,Pn)&&!j(a,Yt)})(s))(t,e)?j(t,rt)?$d:Bi:j(t,"PaleMoon/")?Bd:j(t,Vr+"/")?Vr:j(t,Zn)?Zn:j(t,"MSIE")||j(t,"Trident/")?el:j(t,"Gecko")?Zn:"")},tg={[Pd]:[new RegExp("rv:"+we)],[Fd]:[new RegExp(nl+"?\\/"+we)],[Pn]:[new RegExp("("+Pn+"|CrMo)\\/"+we)],[Ad]:[new RegExp("CriOS\\/"+we)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+we)],[Bi]:[fo],[$d]:[fo],[tl]:[new RegExp("(Opera|OPR)\\/"+we)],[Zn]:[new RegExp(Zn+"\\/"+we)],[Rd]:[new RegExp("FxiOS\\/"+we)],[Zo]:[new RegExp("Konqueror[:/]?"+we,"i")],[ti]:[new RegExp(ti+" "+we),fo],[Td]:[new RegExp("android\\s"+we,"i")],[Cd]:[new RegExp(kd+"\\/"+we)],[Nd]:[new RegExp("OculusBrowser\\/"+we)],[zr]:[new RegExp(zr+"\\/"+we)],[Od]:[new RegExp("YaBrowser\\/"+we)],[qr]:[new RegExp(qr+"\\/"+we)],[Di]:[new RegExp(Di+"\\/"+we)],[Xo]:[new RegExp("(DuckDuckGo|Ddg)\\/"+we)],[Bd]:[new RegExp("PaleMoon\\/"+we)],[Vr]:[new RegExp(Vr+"\\/"+we)],[Dd]:[new RegExp("GSA\\/"+we)],[el]:[new RegExp("(rv:|MSIE )"+we)],Mozilla:[new RegExp("rv:"+we)]},ng=function(t,e,n,i){var r=jd(t,e,n,i),s=tg[r];if(C(s))return null;for(var o=0;s.length>o;o++){var a=t.match(s[o]);if(a)return parseFloat(a[a.length-2])}return null},Ec=[[new RegExp(Xn+"; "+Xn+" (.*?)[);]","i"),t=>[Xn,t&&t[1]||""]],[new RegExp(Gi,"i"),[Gi,""]],[new RegExp(Ki,"i"),[Ki,""]],[il,[ti,""]],[new RegExp(Pi,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Yo,""];if(new RegExp(rt).test(e)&&!/IEMobile\b/.test(e))return[Pi+" "+rt,""];var n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){var i=eg[n[1]]||"";return/arm/i.test(e)&&(i="RT"),[Pi,i]}return[Pi,""]}],[/((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=C(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+Yt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Yt+")","i"),t=>t&&t[2]?[Yt,[t[2],t[3],t[4]||"0"].join(".")]:[Yt,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{var e=["Mac OS X",""];return t&&t[1]&&(e[1]=[t[1],t[2],t[3]||"0"].join(".")),e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[Kp,""]],[/Linux|debian/i,["Linux",""]]],Sc=function(t){return Qp.test(t)?Gi:Xp.test(t)?Ki:Zp.test(t)?Xn:new RegExp(Jo,"i").test(t)?Jo:new RegExp("("+Yo+"|WPDesktop)","i").test(t)?Yo:/iPad/.test(t)?Ed:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?xd:il.test(t)?ti:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(bc,"i").test(t)?bc:/(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(rt).test(t)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(t)||/pixel[\daxl ]{1,6}/i.test(t)&&!/pixel c/i.test(t)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(t)||/lmy47v/i.test(t)&&!/QTAQZ3/i.test(t)?Yt:bd:new RegExp("(pda|"+rt+")","i").test(t)?Jp:new RegExp(ei,"i").test(t)&&!new RegExp(ei+" pc","i").test(t)?Ld:""},ig=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function xc(t,e){return typeof(n=t)=="string"&&ig.test(n)?t:e();var n}function fn(t){return t&&t.split("#")[0]}function rl(t,e){var n=setTimeout(t,e);return n?.unref&&n?.unref(),n}function Ic(t,e,n){return Ud.apply(this,arguments)}function Ud(){return(Ud=se((function*(t,e,n){var i;try{return yield Promise.race([t,new Promise(((r,s)=>{i=rl((()=>{try{n?.(),r()}catch(o){s(o)}}),e)}))])}finally{clearTimeout(i)}}))).apply(this,arguments)}var rg=t=>t instanceof Error,Hd={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}},sg=Hd.info;function Wd(t){if(mt(t))return{boolValue:t};if(typeof t=="number")return Number.isFinite(t)?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:{stringValue:String(t)};if(typeof t=="string")return{stringValue:t};if(U(t))return{arrayValue:{values:t.map((e=>Wd(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function Gr(t){var e=[];for(var n in t){var i=t[n];Ye(i)||C(i)||e.push({key:n,value:Wd(i)})}return e}function og(t,e){var n=Hd[t.level||"info"]||sg,i=n.text,r=n.number,s=String(Date.now())+"000000",o={};e.distinctId&&(o.posthogDistinctId=e.distinctId),e.sessionId&&(o.sessionId=e.sessionId),e.windowId&&(o["window.id"]=e.windowId),H(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),H(e.lastActivityTimestamp)||(o.lastActivityTimestamp=String(e.lastActivityTimestamp)),e.currentUrl&&(o["url.full"]=e.currentUrl),e.screenName&&(o["screen.name"]=e.screenName),e.appState&&(o["app.state"]=e.appState),e.activeFeatureFlags&&e.activeFeatureFlags.length>0&&(o.feature_flags=e.activeFeatureFlags);var a=I({},o,t.attributes||{}),l={timeUnixNano:s,observedTimeUnixNano:s,severityNumber:r,severityText:i,body:{stringValue:t.body},attributes:Gr(a)};return t.trace_id&&(l.traceId=t.trace_id),t.span_id&&(l.spanId=t.span_id),C(t.trace_flags)||(l.flags=t.trace_flags),l}function zd(t,e,n){return I({},t.resourceAttributes,{"service.name":t.serviceName||"unknown_service"},t.environment&&{"deployment.environment":t.environment},t.serviceVersion&&{"service.version":t.serviceVersion},{"telemetry.sdk.name":e,"telemetry.sdk.version":n})}function qd(t,e,n,i){return{resourceLogs:[{resource:{attributes:Gr(e)},scopeLogs:[{scope:{name:n,version:i},logRecords:t}]}]}}let ag=class{constructor(t,e,n,i,r,s,o){var a;s===void 0&&(s=()=>Promise.resolve()),this._instance=t,this.Ne=e,this.rt=n,this.ut=i,this.ht=r,this.dt=s,this.vt=o,this.ct=null,this.ft=0,this.yt=0,this.bt=0,this._t=0,this.wt=!1,this.kt=e.maxBufferSize,this.xt=Math.max((a=e.maxQueueSize)!==null&&a!==void 0?a:e.maxBufferSize,e.maxBufferSize),this.St=e.flushIntervalMs,this.Ct=e.maxBatchRecordsPerPost,this.Mt=e.rateCapWindowMs,this.Tt=e.maxLogsPerInterval}reset(){this.Et(),this.ct=null,this.bt=0,this._t=0,this.wt=!1,this.ft=0,this.yt=0,this.Ct=this.Ne.maxBatchRecordsPerPost}onReconnect(){this.yt=0,this.It()}captureLog(t){if(!this._instance.isDisabled&&!this._instance.optedOut&&t!=null&&t.body){var e=this.Pt(t);if(e!==null)if(e.body){if(this.Rt()){var n={record:og(e,this.ut())};this.ht((()=>this.At(n)))}}else this.rt.info("Log was rejected in beforeSend function")}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Log was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for log:",o),null}return i}Rt(){if(this.Tt===void 0)return!0;var t=Date.now(),e=t-this.bt;return this.Mt>e&&e>=0||(this.bt=t,this._t=0,this.wt=!1),this.Tt>this._t?(this._t++,!0):(this.wt||(this.rt.warn("captureLog dropping logs: exceeded "+this.Tt+" logs per "+this.Mt+"ms"),this.wt=!0),!1)}flush(){var t=this;return se((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return se((function*(){var e;t.Et();var n=(e=t._instance.getPersistedProperty(Ut.LogsQueue))!==null&&e!==void 0?e:[];if(n.length!==0)for(var i=n.length,r=0;n.length>0&&i>r;){var s,o;t.ft=0;var a=Math.min(n.length,t.Ct),l=n.slice(0,a),u=qd(l.map((d=>d.record)),t.Lt(),(s=t.vt)!==null&&s!==void 0?s:t._instance.getLibraryId(),t._instance.getLibraryVersion()),c=yield t._instance.Ot(u);if(c.kind==="too-large"&&l.length>1)t.Ct=Math.max(1,Math.floor(l.length/2)),t.rt.warn("Received 413 when sending logs batch of size "+l.length+", reducing batch size to "+t.Ct);else if(c.kind==="retry-later"||(c.kind==="too-large"?t.rt.warn("Dropping a single log record after 413 with batch size 1 — the record is larger than the server cap and cannot be split further."):c.kind==="ok"&&t.Ne.maxBatchRecordsPerPost>t.Ct&&(t.Ct=Math.min(t.Ne.maxBatchRecordsPerPost,t.Ct+1)),yield t.Dt(l.length),n=(o=t._instance.getPersistedProperty(Ut.LogsQueue))!==null&&o!==void 0?o:[],r+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return se((function*(){var n,i=Math.max(0,t-e.ft),r=(n=e._instance.getPersistedProperty(Ut.LogsQueue))!==null&&n!==void 0?n:[];e._instance.setPersistedProperty(Ut.LogsQueue,r.slice(i)),yield e.dt()}))()}Lt(){return zd(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var n=(e=this._instance.getPersistedProperty(Ut.LogsQueue))!==null&&e!==void 0?e:[];this.xt>n.length||(n.shift(),this.ft++,this.rt.info("Logs queue is full, dropping oldest record.")),n.push(t),this._instance.setPersistedProperty(Ut.LogsQueue,n),this.kt>n.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=rl((()=>{this.Nt=void 0,this.It()}),t))}qt(){var t=Math.min(Math.max(0,this.yt-1),6);return this.St*Math.pow(2,t)}jt(){var t=this._instance.getPersistedProperty(Ut.LogsQueue);return!!t&&t.length>0}shutdown(t){var e=this;return se((function*(){e.Et();var n=e.flush().catch((()=>{}));t!==void 0?yield Ic(n,t):yield n}))()}flushWithTimeout(t){var e=this;return se((function*(){var n=e.flush();yield Ic(n,t,(()=>{n.catch((()=>{}))}))}))()}It(){this.flush().then((()=>{this.yt=0}),(t=>{this.yt++,this.rt.error("PostHog logs flush failed:",t)})).finally((()=>{!this._instance.isDisabled&&this.jt()&&this.$t(this.qt())}))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}};var ho=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function kc(t){return String(t)+"000000"}function Cc(t,e,n,i){var r="";return i&&(r=Object.keys(i).sort().map((s=>JSON.stringify(s)+":"+JSON.stringify(i[s]))).join(",")),t+"\0"+e+"\0"+(n??"")+"\0"+r}let lg=class{constructor(t,e,n){this._instance=t,this.Ne=e,this.rt=n,this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Wt=0}count(t,e,n){e===void 0&&(e=1),this.Vt({name:t,type:"count",value:e,unit:n?.unit,attributes:n?.attributes})}gauge(t,e,n){this.Vt({name:t,type:"gauge",value:e,unit:n?.unit,attributes:n?.attributes})}histogram(t,e,n){this.Vt({name:t,type:"histogram",value:e,unit:n?.unit,attributes:n?.attributes})}flush(){var t=this,e=this.ct,n=(function(){var r=se((function*(){e&&(yield e.catch((()=>{}))),yield t.Zt()}));return function(){return r.apply(this,arguments)}})(),i=n().finally((()=>{this.ct===i&&(this.ct=null)}));return this.ct=i,i}drainWindow(){if(this.Bt.size===0)return null;var t=this.Bt;return this.Bt=new Map,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Gt(t)}reset(){this.Wt++,this.Et(),this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set}Vt(t){if(!this._instance.isDisabled&&!this._instance.optedOut){var e=this.Pt(t);if(e!==null)if(e.name&&typeof e.name=="string")if(typeof e.value=="number"&&Number.isFinite(e.value))if(e.type==="count"&&0>e.value)this.rt.warn("Dropping count '"+e.name+"': counters are monotonic, value must be >= 0");else{var n,i;try{n=e.attributes?I({},e.attributes):void 0,i=Cc(e.type,e.name,e.unit,n)}catch(o){return void this.rt.warn("Dropping metric '"+e.name+"': attributes could not be serialized",o)}var r=this.Bt.get(i);if(!r){if(!this.Qt())return;r={name:e.name,type:e.type,unit:e.unit,attributes:n,windowStartMs:Date.now()},this.Bt.set(i,r)}var s=this.Ut.get(e.name);s===void 0?this.Ut.set(e.name,e.type):s===e.type||this.zt.has(e.name)||(this.zt.add(e.name),this.rt.warn("Metric name '"+e.name+"' is already used as a "+s+"; recording it as a "+e.type+" too will blend both series in charts. Use a distinct name.")),this.Kt(r,e.value),this.$t()}else this.rt.warn("Dropping metric '"+e.name+"': value must be a finite number");else this.rt.warn("Dropping metric with empty name")}}Qt(){return this.Ne.maxSeriesPerFlush>this.Bt.size||(this.Ht||(this.Ht=!0,this.rt.warn("Metric series cap reached ("+this.Ne.maxSeriesPerFlush+" per flush window); dropping new series until the next flush. Reduce attribute cardinality.")),!1)}Kt(t,e){var n;switch(t.type){case"count":t.total=((n=t.total)!==null&&n!==void 0?n:0)+e;break;case"gauge":t.last=e;break;case"histogram":t.hist||(t.hist={count:0,sum:0,min:e,max:e,bucketCounts:new Array(ho.length+1).fill(0)});var i=t.hist;i.count+=1,i.sum+=e,i.min=Math.min(i.min,e),i.max=Math.max(i.max,e),i.bucketCounts[(function(r,s){for(var o=0;s.length>o;o++)if(s[o]>=r)return o;return s.length})(e,ho)]+=1}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Metric was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for metric:",o),null}return i}$t(){this.Nt||(this.Nt=rl((()=>{this.Nt=void 0,this.flush().catch((t=>{this.rt.error("Metrics flush failed:",t)}))}),this.Ne.flushIntervalMs))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}Zt(){var t=this;return se((function*(){if(t.Bt.size!==0){var e=t.Bt;t.Bt=new Map,t.Ht=!1,t.Ut=new Map,t.zt=new Set;var n=t.Wt,i=yield t._instance.Jt(t.Gt(e));if(n===t.Wt)switch(i.kind){case"ok":return;case"retry-later":return t.Yt(e),void t.$t();case"too-large":return void t.rt.warn("Metrics batch exceeded the server size limit and was dropped");case"fatal":return void t.rt.error("Failed to send metrics batch:",i.error)}}}))()}Gt(t){return e=this.Xt(t),n=(function(s,o,a){return I({},s.resourceAttributes,{"service.name":s.serviceName||"unknown_service"},s.environment&&{"deployment.environment":s.environment},s.serviceVersion&&{"service.version":s.serviceVersion},{"telemetry.sdk.name":o,"telemetry.sdk.version":a})})(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion()),i=this._instance.getLibraryId(),r=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:Gr(n)},scopeMetrics:[{scope:{name:i,version:r},metrics:e}]}]};var e,n,i,r}Xt(t){var e=kc(Date.now()),n=new Map;for(var i of t.values()){var r,s=Cc(i.type,i.name,i.unit,void 0),o=n.get(s);o||(o=I({name:i.name},i.unit&&{unit:i.unit}),i.type==="count"?o.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:i.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:1,dataPoints:[]},n.set(s,o));var a=Gr((r=i.attributes)!==null&&r!==void 0?r:{}),l=kc(i.windowStartMs);if(i.type==="count"){var u,c={attributes:a,startTimeUnixNano:l,timeUnixNano:e,asDouble:(u=i.total)!==null&&u!==void 0?u:0};o.sum.dataPoints.push(c)}else if(i.type==="gauge"){var d,f={attributes:a,timeUnixNano:e,asDouble:(d=i.last)!==null&&d!==void 0?d:0};o.gauge.dataPoints.push(f)}else i.hist&&o.histogram.dataPoints.push({attributes:a,startTimeUnixNano:l,timeUnixNano:e,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:ho})}return Array.from(n.values())}Yt(t){var e,n;for(var i of t){var r=i[0],s=i[1],o=this.Bt.get(r);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,s.windowStartMs),o.type){case"count":o.total=((e=o.total)!==null&&e!==void 0?e:0)+((n=s.total)!==null&&n!==void 0?n:0);break;case"gauge":break;case"histogram":if(s.hist)if(o.hist){o.hist.count+=s.hist.count,o.hist.sum+=s.hist.sum,o.hist.min=Math.min(o.hist.min,s.hist.min),o.hist.max=Math.max(o.hist.max,s.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=s.hist.bucketCounts[a]}else o.hist=s.hist}else this.Qt()&&this.Bt.set(r,s)}}};var gr,Ac,po;function cg(t){var e=globalThis._posthogChunkIds;if(e){var n=Object.keys(e);return po&&n.length===Ac||(Ac=n.length,po=n.reduce(((i,r)=>{gr||(gr={});var s=gr[r];if(s)i[s[0]]=s[1];else for(var o=t(r),a=o.length-1;a>=0;a--){var l=o[a],u=l?.filename,c=e[r];if(u&&c){i[u]=c,gr[r]=[u,c];break}}return i}),{})),po}}class ug{constructor(e,n,i){i===void 0&&(i=[]),this.coercers=e,this.stackParser=n,this.modifiers=i}buildFromUnknown(e,n){n===void 0&&(n={});var i=n&&n.mechanism||{handled:!0,type:"generic"},r=this.buildCoercingContext(i,n,0).apply(e),s=this.buildParsingContext(n),o=this.parseStacktrace(r,s);return{$exception_list:this.convertToExceptionList(o,i),$exception_level:"error"}}modifyFrames(e){var n=this;return se((function*(){for(var i of e)i.stacktrace&&i.stacktrace.frames&&U(i.stacktrace.frames)&&(i.stacktrace.frames=yield n.applyModifiers(i.stacktrace.frames));return e}))()}coerceFallback(e){var n;return{type:"Error",value:"Unknown error",stack:(n=e.syntheticException)==null?void 0:n.stack,synthetic:!0}}parseStacktrace(e,n){var i,r;return e.cause!=null&&(i=this.parseStacktrace(e.cause,n)),e.stack!=""&&e.stack!=null&&(r=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?n.skipFirstLines:0),n.chunkIdMap)),I({},e,{cause:i,stack:r})}applyChunkIds(e,n){return e.map((i=>(i.filename&&n&&(i.chunk_id=n[i.filename]),i)))}applyCoercers(e,n){for(var i of this.coercers)if(i.match(e))return i.coerce(e,n);return this.coerceFallback(n)}applyModifiers(e){var n=this;return se((function*(){var i=e;for(var r of n.modifiers)i=yield r(i);return i}))()}convertToExceptionList(e,n){var i,r,s,o={type:e.type,value:e.value,mechanism:{type:(i=n.type)!==null&&i!==void 0?i:"generic",handled:(r=n.handled)===null||r===void 0||r,synthetic:(s=e.synthetic)!==null&&s!==void 0&&s}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,I({},n,{handled:!0}))),a}buildParsingContext(e){var n;return{chunkIdMap:cg(this.stackParser),skipFirstLines:(n=e.skipFirstLines)!==null&&n!==void 0?n:1}}buildCoercingContext(e,n,i){i===void 0&&(i=0);var r=(s,o)=>{if(4>=o){var a=this.buildCoercingContext(e,n,o);return this.applyCoercers(s,a)}};return I({},n,{syntheticException:i==0?n.syntheticException:void 0,mechanism:e,apply:s=>r(s,i),next:s=>r(s,i+1)})}}var ni="?";function Qo(t,e,n,i,r){var s={platform:t,filename:e,function:n===""?ni:n,in_app:!0};return C(i)||(s.lineno=i),C(r)||(s.colno=r),s}var Vd=(t,e)=>{var n=t.indexOf("safari-extension")!==-1,i=t.indexOf("safari-web-extension")!==-1;return n||i?[t.indexOf("@")!==-1?t.split("@")[0]:ni,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},dg=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,fg=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,hg=/\((\S*)(?::(\d+))(?::(\d+))\)/,pg=(t,e)=>{var n=dg.exec(t);if(n)return Qo(e,n[1],ni,+n[2],+n[3]);var i=fg.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var r=hg.exec(i[2]);r&&(i[2]=r[1],i[3]=r[2],i[4]=r[3])}var s=Vd(i[1]||ni,i[2]);return Qo(e,s[1],s[0],i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},gg=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,mg=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,vg=(t,e)=>{var n=gg.exec(t);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){var i=mg.exec(n[3]);i&&(n[1]=n[1]||"eval",n[3]=i[1],n[4]=i[2],n[5]="")}var r=n[3],s=n[1]||ni,o=Vd(s,r);return Qo(e,r=o[1],s=o[0],n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},Pc=/\(error: (.*)\)/;class _g{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,n){var i=X(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:i?e.stack:void 0,cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var n=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?n+": "+e.message:n}isDOMException(e){return Hr(e,"DOMException")}isDOMError(e){return Hr(e,"DOMError")}}class yg{match(e){return(function(n){switch({}.toString.call(n)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return wd(n,Error)}})(e)}coerce(e,n){return{type:this.getType(e),value:this.getMessage(e,n),stack:this.getStack(e),cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,n){var i=e.message;return String(i.error&&typeof i.error.message=="string"?i.error.message:i)}getStack(e){return e.stacktrace||e.stack||void 0}}class wg{constructor(){}match(e){return!!Hr(e,"ErrorEvent")&&(e.error!=null||this.fe(e))}coerce(e,n){var i;if(e.error!=null)return n.apply(e.error);var r=n.apply(e.message);return I({},r,{stack:(i=this.pe(e))!==null&&i!==void 0?i:r.stack,synthetic:!0})}fe(e){return X(e.message)&&e.message.length>0}pe(e){var n=e;if(X(n.filename)&&n.filename.length>0){var i,r,s=(i=n.lineno)!==null&&i!==void 0?i:0,o=(r=n.colno)!==null&&r!==void 0?r:0;return`Error - at `+n.filename+":"+s+":"+o}}}var bg=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class Eg{match(e){return typeof e=="string"}coerce(e,n){var i,r=this.getInfos(e),s=r[0],o=r[1];return{type:s??"Error",value:o??e,stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}getInfos(e){var n="Error",i=e,r=e.match(bg);return r&&(n=r[1],i=r[2]),[n,i]}}var Sg=["fatal","error","warning","log","info","debug"];function Gd(t,e){e===void 0&&(e=40);var n=Object.keys(t);if(n.sort(),!n.length)return"[object has no keys]";for(var i=n.length;i>0;i--){var r=n.slice(0,i).join(", ");if(e>=r.length)return i===n.length?r:r.length>e?r.slice(0,e)+"...":r}return""}class xg{match(e){return typeof e=="object"&&e!==null}coerce(e,n){var i,r,s=this.getErrorPropertyFromObject(e);return s?n.apply(s):{type:this.getType(e),value:this.getValue(e),stack:(i=this.getStack(e))!==null&&i!==void 0?i:(r=n.syntheticException)==null?void 0:r.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return Qa(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var n="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(n+=" with message: '"+e.message+"'"),n}if("message"in e&&typeof e.message=="string")return e.message;var i=this.getObjectClassName(e);return(i&&i!=="Object"?"'"+i+"'":"Object")+" captured as exception with keys: "+Gd(e)}isSeverityLevel(e){return X(e)&&!Ko(e)&&Sg.indexOf(e)>=0}getStack(e){try{return X(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:X(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(var n in e)if({}.hasOwnProperty.call(e,n)){var i=e[n];if(rg(i))return i}}getObjectClassName(e){try{var n=Object.getPrototypeOf(e);return n?n.constructor.name:void 0}catch{return}}}class Ig{match(e){return Qa(e)}coerce(e,n){var i,r=e.constructor.name;return{type:r,value:r+" captured as exception with keys: "+Gd(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class kg{match(e){return yd(e)}coerce(e,n){var i;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class Cg{match(e){return Hr(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Qa(e))return!1;try{var n=e.detail;return n!=null&&typeof n=="object"&&"reason"in n}catch{return!1}}coerce(e,n){var i,r=this.getUnhandledRejectionReason(e);return yd(r)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(r),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}:n.apply(r)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}}var Kr="$message",Yr="$timestamp",Ag=new Set([Kr,Yr]),go={enabled:!0,max_bytes:32768};function Jr(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:go.enabled,max_bytes:Fg(t.max_bytes,go.max_bytes)}:I({},go)}class Pg{constructor(e){this.Ke=[],this.Je=0,this.Ne=Jr(e)}setConfig(e){this.Ne=Jr(e),this.Xe()}add(e){var n=(function(r){var s;try{s=md(r)}catch{return}try{var o=JSON.parse(s);if(!he(o))return;var a=o,l=a[Kr],u=a[Yr];return!X(l)||l.trim().length===0||!X(u)&&!ke(u)?void 0:{step:a,json:s}}catch{return}})(e);if(n){var i=(function(r){if(typeof TextEncoder<"u")return new TextEncoder().encode(r).length;for(var s=encodeURIComponent(r),o=0,a=0;s.length>a;a++)s[a]==="%"?(o+=1,a+=2):o+=1;return o})(n.json);i>this.Ne.max_bytes||(this.Ke.push({step:n.step,bytes:i}),this.Je+=i,this.Xe())}}getAttachable(){return this.Ke.map((e=>e.step))}clear(){this.Ke=[],this.Je=0}size(){return this.Ke.length}Xe(){for(;this.Je>this.Ne.max_bytes&&this.Ke.length>0;){var e=this.Ke.shift();e&&(this.Je-=e.bytes)}}}function Fg(t,e){if(!ke(t)||t===1/0||t===-1/0)return e;var n=Math.floor(t);return 0>n?e:n}var Kd=function(t,e){var n=(e===void 0?{}:e).debugEnabled,i={k(r){if(w&&(ne.DEBUG||w.POSTHOG_DEBUG||n)&&!C(w.console)&&w.console){for(var s=("__rrweb_original__"in w.console[r])?w.console[r].__rrweb_original__:w.console[r],o=arguments.length,a=new Array(o>1?o-1:0),l=1;o>l;l++)a[l-1]=arguments[l];s(t,...a)}},debug(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("debug",...s)},info(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("log",...s)},warn(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("warn",...s)},error(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("error",...s)},critical(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];console.error(t,...s)},uninitializedWarning(r){i.error("You must initialize PostHog before calling "+r)},createLogger:(r,s)=>Kd(t+" "+r,s)};return i},A=Kd("[PostHog.js]"),pe=A.createLogger,Rg=pe("[ExternalScriptsLoader]"),mo=(t,e,n)=>{if(t.config.disable_external_dependency_loading)return Rg.warn(e+" was requested but loading of external scripts is disabled."),n("Loading of external scripts is disabled");var i=P?.querySelectorAll("script");if(i){for(var r,s=function(){if(i[o].src===e){var l=i[o];return l.__posthog_loading_callback_fired?{v:n()}:(l.addEventListener("load",(u=>{l.__posthog_loading_callback_fired=!0,n(void 0,u)})),l.onerror=u=>n(u),{v:void 0})}},o=0;i.length>o;o++)if(r=s())return r.v}var a=()=>{if(!P)return n("document not found");var l=P.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=d=>{l.__posthog_loading_callback_fired=!0,n(void 0,d)},l.onerror=d=>n(d),t.config.prepare_external_dependency_script&&(l=t.config.prepare_external_dependency_script(l)),!l)return n("prepare_external_dependency_script returned null");if(t.config.external_scripts_inject_target==="head")P.head.appendChild(l);else{var u,c=P.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):P.body.appendChild(l)}};P!=null&&P.body?a():P?.addEventListener("DOMContentLoaded",a)};B.__PosthogExtensions__=B.__PosthogExtensions__||{},B.__PosthogExtensions__.loadExternalDependency=(t,e,n)=>{if(e!=="remote-config"){var i;if(t.config.strict_script_versioning)i=t.requestRouter.endpointFor("assets","/static/"+t.version+"/"+e+".js");else{var r="/static/"+e+".js?v="+t.version;if(e==="toolbar"){var s=3e5;r=r+"&t="+Math.floor(Date.now()/s)*s}i=t.requestRouter.endpointFor("assets",r)}mo(t,i,n)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");mo(t,o,n)}},B.__PosthogExtensions__.loadSiteApp=(t,e,n)=>{var i=t.requestRouter.endpointFor("api",e);mo(t,i,n)};ne.DEBUG=!1,ne.LIB_VERSION="1.415.7",ne.LIB_NAME="web";var Yd="$people_distinct_id",Yi="$device_id",vo="$device_model",Fi="__alias",Ri="__timers",ea="$autocapture_disabled_server_side",ta="$heatmaps_enabled_server_side",na="$exception_capture_enabled_server_side",ia="$error_tracking_suppression_rules",ra="$error_tracking_capture_extension_exceptions",sa="$web_vitals_enabled_server_side",sl="$dead_clicks_enabled_server_side",ol="$product_tours_enabled_server_side",oa="$web_vitals_allowed_metrics",An="$session_recording_remote_config",Jd="$replay_sample_rate",Zd="$replay_override_sampling",Xd="$replay_override_linked_flag",Qd="$replay_override_url_trigger",ef="$replay_override_event_trigger",Kn="$sesid",al="$session_is_sampled",Sn="$enabled_feature_flags",Ti="$active_feature_flags",Ar="$early_access_features",aa="$feature_flag_details",$i="$feature_flag_payloads",Pr="$feature_flag_request_id",Zr="$minimal_flag_called_events",It="$override_feature_flags",xn="$override_feature_flag_payloads",jt="$stored_person_properties",In="$stored_group_properties",la="$surveys",Xr="$surveys_loaded_at",ca="$surveys_activated",Fr="$surveys_activated_session",Rr="$surveys_activated_timestamps",Mi="ph_product_tours",Cn="$flag_call_reported",Li="$flag_call_reported_session_id",Tr="$feature_flag_errors",ji="$feature_flag_evaluated_at",at="$user_state",ua="$client_session_props",da="$capture_rate_limit",fa="$initial_campaign_params",ha="$initial_referrer_info",Qr="$initial_person_info",es="$epp",mr="$posthog_cookieless",tf="$cookieless_mode",nf="$sdk_debug_extensions_init_method",rf="$sdk_debug_extensions_init_time_ms",sf="$sdk_debug_recording_script_not_loaded",ll="PostHog loadExternalDependency extension not found.",kn="on_reject",Wt="always",Un="anonymous",vn="identified",pa="identified_only",ts="visibilitychange",ns="beforeunload",Vn="$pageview",_o="$pageleave",yo="$identify",Fc="$groupidentify";function vr(t,e){U(t)&&t.forEach(e)}function ie(t,e){if(!H(t))if(U(t))t.forEach(e);else if(Hp(t))t.forEach(((i,r)=>e(i,r)));else for(var n in t)_d.call(t,n)&&e(t[n],n)}var fe=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;e>i;i++)n[i-1]=arguments[i];for(var r of n)for(var s in r)r[s]!==void 0&&(t[s]=r[s]);return t};function $r(t){for(var e=Object.keys(t),n=e.length,i=new Array(n);n--;)i[n]=[e[n],t[e[n]]];return i}var Rc=function(t){try{return t()}catch{return}},Tg=function(t){return function(){try{for(var e=arguments.length,n=new Array(e),i=0;e>i;i++)n[i]=arguments[i];return t.apply(this,n)}catch(r){A.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),A.critical(r)}}},cl=function(t){var e={};return ie(t,(function(n,i){(X(n)&&n.length>0||ke(n))&&(e[i]=n)})),e},$g=["herokuapp.com","vercel.app","netlify.app"];function Mg(t){var e=t?.hostname;if(!X(e))return!1;var n=e.split(".").slice(-2).join(".");for(var i of $g)if(n===i)return!1;return!0}function ve(t,e,n,i){var r=i??{},s=r.capture,o=r.passive;t?.addEventListener(e,n,{capture:s!==void 0&&s,passive:o===void 0||o})}function ga(t){return t.name==="ph_toolbar_internal"}var of=t=>{if(P){try{for(var e=t+"=",n=P.cookie.split(";").filter((s=>s.length)),i=0;n.length>i;i++){for(var r=n[i];r.charAt(0)==" ";)r=r.substring(1,r.length);if(r.indexOf(e)===0)return decodeURIComponent(r.substring(e.length,r.length))}}catch{}return null}};Math.trunc||(Math.trunc=function(t){return 0>t?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return ke(t)&&isFinite(t)&&Math.floor(t)===t});class is{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,n,i,r){if(!Number.isInteger(e)||!Number.isInteger(n)||!Number.isInteger(i)||!Number.isInteger(r)||0>e||0>n||0>i||0>r||e>0xffffffffffff||n>4095||i>1073741823||r>4294967295)throw new RangeError("invalid field value");var s=new Uint8Array(16);return s[0]=e/Math.pow(2,40),s[1]=e/Math.pow(2,32),s[2]=e/Math.pow(2,24),s[3]=e/Math.pow(2,16),s[4]=e/256,s[5]=e,s[6]=112|n>>>8,s[7]=n,s[8]=128|i>>>24,s[9]=i>>>16,s[10]=i>>>8,s[11]=i,s[12]=r>>>24,s[13]=r>>>16,s[14]=r>>>8,s[15]=r,new is(s)}toString(){for(var e="",n=0;this.bytes.length>n;n++)e=e+(this.bytes[n]>>>4).toString(16)+(15&this.bytes[n]).toString(16),n!==3&&n!==5&&n!==7&&n!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new is(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var n=0;16>n;n++){var i=this.bytes[n]-e.bytes[n];if(i!==0)return Math.sign(i)}return 0}}class Lg{generate(){var e=this.generateOrAbort();if(!C(e))return e;this.S=0;var n=this.generateOrAbort();if(C(n))throw new Error("Could not generate UUID after timestamp reset");return n}generateOrAbort(){var e=Date.now();if(e>this.S)this.S=e,this.C();else{if(this.S>=e+1e4)return;this.I++,this.I>4398046511103&&(this.S++,this.C())}return is.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 Ng}}var Tc,af=t=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;t.length>e;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};w&&!C(w.crypto)&&crypto.getRandomValues&&(af=t=>crypto.getRandomValues(t));class Ng{nextUint32(){return this.R.length>this.O||(af(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var Ht=()=>Og().toString(),Og=()=>(Tc||(Tc=new Lg)).generate(),yi="",Bg=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,zt={N:()=>!!P,j(t){A.error("cookieStore error: "+t)},P:of,H(t){var e;try{e=JSON.parse(zt.P(t))||{}}catch{}return e},F(t,e,n,i,r){if(!P)return!1;try{var s="",o="",a=(function(c,d){if(d){var f=(function(p,g){if(g===void 0&&(g=P),yi)return yi;if(!g||["localhost","127.0.0.1"].includes(p))return"";for(var m=p.split("."),v=Math.min(m.length,8),E="dmn_chk_"+Ht();!yi&&v--;){var S=m.slice(v).join("."),_=E+"=1;domain=."+S+";path=/";g.cookie=_+";max-age=3",g.cookie.includes(E)&&(g.cookie=_+";max-age=0",yi=S)}return yi})(c);if(!f){var h=(p=>{var g=p.match(Bg);return g?g[0]:""})(c);h!==f&&A.info("Warning: cookie subdomain discovery mismatch",h,f),f=h}return f?"; domain=."+f:""}return""})(P.location.hostname,i);if(n){var l=new Date;l.setTime(l.getTime()+864e5*n),s="; expires="+l.toUTCString()}r&&(o="; secure");var u=t+"="+encodeURIComponent(JSON.stringify(e))+s+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&A.warn("cookieStore warning: large cookie, len="+u.length),P.cookie=u,!0}catch{return!1}},q(t,e){if(P!=null&&P.cookie)try{zt.F(t,"",-1,e)}catch{return}}},wo=null,le={N(){if(!Ye(wo))return wo;var t=!0;if(C(w))t=!1;else try{var e="__mplssupport__";le.F(e,"xyz"),le.P(e)!=='"xyz"'&&(t=!1),le.q(e)}catch{t=!1}return t||A.error("localStorage unsupported; falling back to cookie store"),wo=t,t},j(t){A.error("localStorage error: "+t)},P(t){try{return w?.localStorage.getItem(t)}catch(e){le.j(e)}return null},H(t){try{return JSON.parse(le.P(t))||{}}catch{}return null},F(t,e){try{return w?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(n){le.j(n)}return!1},q(t){try{w?.localStorage.removeItem(t)}catch(e){le.j(e)}}},Dg=[Yi,"distinct_id",Kn,al,es,Qr,at],_r={},jg={N:()=>!0,j(t){A.error("memoryStorage error: "+t)},P:t=>_r[t]||null,H:t=>_r[t]||null,F:(t,e)=>(_r[t]=e,!0),q(t){delete _r[t]}},_n=null,be={N(){if(!Ye(_n))return _n;if(_n=!0,C(w))_n=!1;else try{var t="__support__";be.F(t,"xyz"),be.P(t)!=='"xyz"'&&(_n=!1),be.q(t)}catch{_n=!1}return _n},j(t){A.error("sessionStorage error: ",t)},P(t){try{return w?.sessionStorage.getItem(t)}catch(e){be.j(e)}return null},H(t){try{return JSON.parse(be.P(t))||null}catch{}return null},F(t,e){try{return w?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(n){be.j(n)}return!1},q(t){try{w?.sessionStorage.removeItem(t)}catch(e){be.j(e)}}};class Ug{constructor(e){this._instance=e}get Ne(){return this._instance.config}get consent(){return this.ti()?0:this.ei}isOptedOut(){return this.Ne.cookieless_mode===Wt||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===kn}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===0}isRejected(){return this.consent===0||this.consent===-1&&this.Ne.opt_out_capturing_by_default}optInOut(e){this.ii.F(this.ri,e?1:0,this.Ne.cookie_expiration,this.Ne.cross_subdomain_cookie,this.Ne.secure_cookie)}reset(){this.ii.q(this.ri,this.Ne.cross_subdomain_cookie)}get ri(){var e=this._instance.config,n=e.token,i=e.opt_out_capturing_cookie_prefix;return e.consent_persistence_name||(i?i+n:"__ph_opt_in_out_"+n)}get ei(){var e=this.ii.P(this.ri);return uo(e)?1:j(Vp,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,n=e==="localStorage"?le:zt;if(!this.ni||this.ni!==n){this.ni=n;var i=e==="localStorage"?zt:le;i.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(uo(i.P(this.ri))),i.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[He?.doNotTrack,He?.msDoNotTrack,B.doNotTrack].some((e=>uo(e)))}}function lf(t,e){var n,i=t==null||(n=t.config)==null?void 0:n.get_current_url;if(!je(i))return e;try{var r=i(e);return X(r)&&r?r:e}catch(s){return A.error("Error in get_current_url, falling back to window.location.href",s),e}}var cf="__POSTHOG_TOOLBAR__",Hg=1,Wg=3,zg=11;function $c(t){return t instanceof Element&&(t.id===cf||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function hn(t){return!!t&&t.nodeType===Hg}function et(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function uf(t){return!!t&&t.nodeType===Wg}function df(t){return!!t&&t.nodeType===zg&&hn(t.host)}var ff=1e3;function ul(t){return t?xs(t).split(/\s+/):[]}function Mc(t,e){var n=(function(i){var r,s=w==null||(r=w.location)==null?void 0:r.href;return C(s)?void 0:lf(i,s)})(e);return!!(n&&t&&t.some((i=>n.match(i))))}function rs(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 ul(e)}function hf(t){return H(t)?null:xs(t).split(/(\s+)/).filter((e=>Ui(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function Ji(t){var e="";return va(t)&&!vf(t)&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;uf(n)&&n.textContent&&(e+=(i=hf(n.textContent))!==null&&i!==void 0?i:"")})),xs(e)}function bo(t){var e;return C(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var dl=["a","button","form","input","select","textarea","label"];function ma(t,e){if(C(e))return!0;var n,i=function(s){if(e.some((o=>(function(a,l){var u=a.matches||a.matchesSelector||a.msMatchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.oMatchesSelector;try{return!!u&&u.call(a,l)}catch{return!1}})(s,o))))return{v:!0}};for(var r of t)if(n=i(r))return n.v;return!1}function pf(t){var e=t.parentNode;return!(!e||!hn(e))&&e}var qg=[".ph-no-autocapture","[data-ph-no-autocapture]"],gf=["next","previous","prev",">","<"],Vg=[...gf,"+","-","−","–"],Lc=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,Nc=[".ph-no-rageclick",".ph-no-capture"],Gg=["","text","search","email","password","url","tel","number"];function Oc(t,e){if(!w||fl(t))return!1;var n,i,r,s,o;if(mt(e)?(n=!!e&&Nc,i=void 0,r=!1):(n=(s=e?.css_selector_ignorelist)!==null&&s!==void 0?s:Nc,i=e?.content_ignorelist,r=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),n===!1||r&&(function(l){return!(!l||!hn(l))&&(!!et(l,"textarea")||(et(l,"input")?j(Gg,(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=mf(t,!1).targetElementList;return!(function(l,u){if(l===!1||C(l))return!1;var c;if(l===!0)c=gf;else{if(!U(l))return!1;if(l.length>10)return A.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var f=d.safeText,h=d.ariaLabel;return c.some((p=>Lc(f,p)||Lc(h,p)))}))})(i,a.map((l=>{var u;return{safeText:Ji(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!ma(a,n)}var fl=t=>!t||et(t,"html")||!hn(t),mf=(t,e)=>{if(!w||fl(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,i=[t],r=t;r.parentNode&&!et(r,"body");)if(df(r.parentNode))i.push(r.parentNode.host),r=r.parentNode.host;else{var s=pf(r);if(!s)break;if(e||dl.indexOf(s.tagName.toLowerCase())>-1)n=!0;else try{var o=w.getComputedStyle(s);o&&o.getPropertyValue("cursor")==="pointer"&&(n=!0)}catch{}i.push(s),r=s}return{parentIsUsefulElement:n,targetElementList:i}};function va(t){for(var e=new Set,n=0,i=t;i.parentNode&&!et(i,"body");i=i.parentNode){if(n++>=ff||e.has(i))return!1;e.add(i);var r=rs(i);if(j(r,"ph-sensitive")||j(r,"ph-no-capture"))return!1}if(j(rs(t),"ph-include"))return!0;var s=t.type||"";if(X(s))switch(s.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!X(o)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(o.replace(/[^a-zA-Z0-9]/g,""))}function vf(t){return!!(et(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||et(t,"select")||et(t,"textarea")||t.getAttribute("contenteditable")==="true")}var Bc=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}))$"),Dc=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,Kg=[16,15,14,13],Yg=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),jc=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),Uc=/[0-9A-Za-z_]/;function Jg(t){for(var e=0,n=!1,i=t.length-1;i>=0;i--){var r=t.charCodeAt(i)-48;n&&(r*=2)>9&&(r-=9),e+=r,n=!n}return e%10==0}function Ui(t,e){if(e===void 0&&(e=!0),H(t))return!1;if(X(t)){t=xs(t);var n=e?Bc.test((t||"").replace(/[- ]/g,"")):(function(r){var s;for(Dc.lastIndex=0;s=Dc.exec(r);){var o=s[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of Kg){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(Bc.test(d)&&Jg(d))return!0}}}return!1})(t);if(n)return!1;var i=e?Yg.test(t):(function(r){var s;for(jc.lastIndex=0;s=jc.exec(r);){var o=s[1],a=s[3];if(!(o&&a&&Uc.test(o)&&Uc.test(a)))return!0}return!1})(t);if(i)return!1}return!0}function Hc(t){var e=Ji(t);return Ui(e=(e+" "+_f(t)).trim())?e:""}function _f(t){var e="";return t&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;if(n&&((i=n.tagName)==null?void 0:i.toLowerCase())==="span")try{var r=Ji(n);e=(e+" "+r).trim(),n.childNodes&&n.childNodes.length&&(e=(e+" "+_f(n)).trim())}catch(s){A.error("[AutoCapture]",s)}})),e}function Wc(t){return t.replace(/"|\\"/g,'\\"')}function Zg(t){var e=t.attr__class;if(e)return U(e)?e:ul(e)}var yr=pe("[Dead Clicks]"),Xg=()=>!0,Qg=t=>{var e,n=!((e=t.instance.persistence)==null||!e.get_property(sl)),i=t.instance.config.capture_dead_clicks;return mt(i)?i:!!he(i)||n};class zc{get lazyLoadedDeadClicksAutocapture(){return this.si}constructor(e,n,i){this.instance=e,this.isEnabled=n,this.onCapture=i,this.startIfEnabledOrStop()}onRemoteConfig(e){if(e.ok){var n=e.config;"captureDeadClicks"in n&&(this.instance.persistence&&this.instance.persistence.register({[sl]:n.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var n,i;(n=B.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture?e():(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"dead-clicks-autocapture",(r=>{r?yr.error("failed to load script",r):e()}))}oi(){var e;if(P){if(!this.si&&(e=B.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var n=he(this.instance.config.capture_dead_clicks)?I({},this.instance.config.capture_dead_clicks):{};n.__onCapture=this.onCapture,this.onCapture&&(n.capture_dead_swipes=!1),this.si=B.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.si.start(P),yr.info("starting...")}}else yr.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,yr.info("stopping..."))}}var Eo=pe("[SegmentIntegration]"),yf="posthog-js";function wf(t,e){var n=e===void 0?{}:e,i=n.organization,r=n.projectId,s=n.prefix,o=n.severityAllowList,a=o===void 0?["error"]:o,l=n.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,f,h,p,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var v,E=((d=c.exception)==null?void 0:d.values)||[],S=E.map((b=>I({},b,{stacktrace:b.stacktrace?I({},b.stacktrace,{type:"raw",frames:(b.stacktrace.frames||[]).map((k=>I({},k,{platform:"web:javascript"})))}):void 0}))),_={$exception_message:((f=E[0])==null?void 0:f.value)||c.message,$exception_type:(h=E[0])==null?void 0:h.type,$exception_level:c.level,$exception_list:S,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((p=E[0])==null?void 0:p.value)||c.message,$sentry_exception_type:(g=E[0])==null?void 0:g.type,$sentry_tags:c.tags};return i&&r&&(_.$sentry_url=(s||"https://sentry.io/organizations/")+i+"/issues/?project="+r+"&query="+c.event_id),u&&((v=t.exceptions)==null||v.sendExceptionEvent(_)),c}}class em{constructor(e,n,i,r,s,o){this.name=yf,this.setupOnce=function(a){a(wf(e,{organization:n,projectId:i,prefix:r,severityAllowList:s,sendExceptionsToPostHog:o==null||o}))}}}class qc{constructor(e){this.li=(n,i,r)=>{r&&(r.noSessionId||r.activityTimeout||r.sessionPastMaximumLength||r.crossTabAdoption)&&(A.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:n,changeReason:r}),this.ui=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.hi()}hi(){var e;this.di=(e=this._instance.sessionManager)==null?void 0:e.onSessionId(this.li)}destroy(){var e;(e=this.di)==null||e.call(this),this.di=void 0}doPageView(e,n){var i,r=this.vi(e,n);return this.ui={pathname:(i=w?.location.pathname)!==null&&i!==void 0?i:"",pageViewId:n,timestamp:e},this._instance.scrollManager.resetContext(),r}doPageLeave(e){var n;return this.vi(e,(n=this.ui)==null?void 0:n.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.ui)==null?void 0:e.pageViewId}}vi(e,n){var i=this.ui;if(!i)return{$pageview_id:n};var r={$pageview_id:n,$prev_pageview_id:i.pageViewId},s=this._instance.scrollManager.getContext();if(s&&!this._instance.config.disable_scroll_properties){var o=s.maxScrollHeight,a=s.lastScrollY,l=s.maxScrollY,u=s.maxContentHeight,c=s.lastContentY,d=s.maxContentY;if(!(C(o)||C(a)||C(l)||C(u)||C(c)||C(d))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),d=Math.ceil(d);var f=o>1?At(a/o,0,1,A):1,h=o>1?At(l/o,0,1,A):1,p=u>1?At(c/u,0,1,A):1,g=u>1?At(d/u,0,1,A):1;r=fe(r,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:f,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:h,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:p,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return i.pathname&&(r.$prev_pageview_pathname=i.pathname),i.timestamp&&(r.$prev_pageview_duration=(e.getTime()-i.timestamp.getTime())/1e3),r}}var So=["flags","surveys"],tm={[Yd]:{exposure:"hidden"},[Fi]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[Ri]:{exposure:"hidden"},[ea]:{exposure:"event"},[ta]:{exposure:"hidden"},[na]:{exposure:"event"},[ia]:{exposure:"hidden"},[ra]:{exposure:"event"},[sa]:{exposure:"event"},[sl]:{exposure:"event"},[ol]:{exposure:"hidden"},[oa]:{exposure:"event"},[An]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[Kn]:{exposure:"hidden"},[al]:{exposure:"event"},[Jd]:{exposure:"event",shouldSkipFromEventProperties:t=>Ye(t)},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},$sess_rec_flush_size:{exposure:"hidden"},[Sn]:{exposure:"hidden",storageGroup:"flags"},[Ti]:{exposure:"hidden",storageGroup:"flags"},[Ar]:{exposure:"hidden"},[aa]:{exposure:"hidden",storageGroup:"flags"},[$i]:{exposure:"hidden",storageGroup:"flags"},[Pr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[Zr]:{exposure:"hidden",storageGroup:"flags"},[It]:{exposure:"hidden"},[xn]:{exposure:"hidden"},[jt]:{exposure:"hidden"},[In]:{exposure:"hidden"},[la]:{exposure:"hidden",storageGroup:"surveys"},[Xr]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[ca]:{exposure:"event"},[Fr]:{exposure:"hidden"},[Rr]:{exposure:"hidden"},[Mi]:{exposure:"hidden"},$product_tours_activated:{exposure:"hidden"},$product_tours_activated_session:{exposure:"hidden"},$conversations_widget_session_id:{exposure:"event"},$conversations_ticket_id:{exposure:"event"},$conversations_widget_state:{exposure:"event"},$conversations_user_traits:{exposure:"event"},[Cn]:{exposure:"hidden"},[Li]:{exposure:"hidden"},[Tr]:{exposure:"hidden"},[ji]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[at]:{exposure:"hidden"},[ua]:{exposure:"hidden"},[da]:{exposure:"hidden"},[fa]:{exposure:"hidden"},[ha]:{exposure:"hidden"},[Qr]:{exposure:"hidden"},[es]:{exposure:"hidden"},[Zd]:{exposure:"event"},[Xd]:{exposure:"event"},[Qd]:{exposure:"event"},[ef]:{exposure:"event"},[nf]:{exposure:"event"},[rf]:{exposure:"event"},[sf]:{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"}},nm=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],yn=t=>{var e=tm[t];if(e)return e;for(var n of nm){var i=n[1];if(t.indexOf(n[0])===0)return i}},Yn=(t,e)=>{try{return JSON.stringify(t,((n,i)=>typeof i=="bigint"?i.toString():i),e)}catch{return md(t)}},ss=t=>{var e=P?.createElement("a");return C(e)?null:(e.href=t,e)},ii=function(t,e){for(var n,i=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),r=0;i.length>r;r++){var s=i[r].split("=");if(s[0]===e){n=s;break}}if(!U(n)||2>n.length)return"";var o=n[1];try{o=decodeURIComponent(o)}catch{A.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},Zi=function(t,e,n){if(!t||!e||!e.length)return t;for(var i=t.split("#"),r=i[1],s=(i[0]||"").split("?"),o=s[1],a=s[0],l=(o||"").split("&"),u=[],c=0;l.length>c;c++){var d=l[c].split("=");U(d)&&(e.includes(d[0])?u.push(d[0]+"="+n):u.push(l[c]))}var f=a;return o!=null&&(f+="?"+u.join("&")),r!=null&&(f+="#"+r),f},os=function(t,e){var n=t.match(new RegExp(e+"=([^&]*)"));return n?n[1]:null},bf=(t,e)=>t>=e&&hd(),Ef=(t,e,n,i)=>{if(t===0){if(hd()){var r=e+1;return r===n&&i(),r}return e}return 0},wr="https?://(.*)",ri=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],im=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...ri],Xi="",rm=["li_fat_id"];function Sf(t,e,n){if(!P)return{};var i,r=e?[...ri,...n||[]]:[],s=xf(Zi(P.URL,r,Xi),t),o=(i={},ie(rm,(function(a){var l=of(a);i[a]=l||null})),i);return fe(o,s)}function xf(t,e){var n=im.concat(e||[]),i={};return ie(n,(function(r){var s=ii(t,r);i[r]=s||null})),i}function If(t){var e=(function(s){return s?s.search(wr+"google.([^/?]*)")===0?"google":s.search(wr+"bing.com")===0?"bing":s.search(wr+"yahoo.com")===0?"yahoo":s.search(wr+"duckduckgo.com")===0?"duckduckgo":null:null})(t),n=e!="yahoo"?"q":"p",i={};if(!Ye(e)){i.$search_engine=e;var r=P?ii(P.referrer,n):"";r.length&&(i.ph_keyword=r)}return i}function Vc(){return navigator.language||navigator.userLanguage}var as="$direct";function kf(){return P?.referrer||as}function Cf(t,e,n){n===void 0&&(n=!1);var i=t?[...ri,...e||[]]:[],r=n?fn(me?.href):me?.href,s=r?.substring(0,1e3);return{r:kf().substring(0,1e3),u:s?Zi(s,i,Xi):void 0}}function Af(t,e){var n;e===void 0&&(e=!1);var i=t.r,r=t.u,s=e?fn(r):r,o={$referrer:i,$referring_domain:i==null?void 0:i==as?as:(n=ss(i))==null?void 0:n.host};if(s){o.$current_url=s;var a=ss(s);o.$host=a?.host,o.$pathname=a?.pathname;var l=xf(s);fe(o,l)}if(i){var u=If(i);fe(o,u)}return o}function Pf(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function sm(){try{return new Date().getTimezoneOffset()}catch{return}}var om={flags:ji,surveys:Xr},am=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],Hn="main";class xo{constructor(e,n,i){if(i===void 0&&(i=!0),this.ci={},this.fi=!1,this.pi=!1,this.Ne=e,this.gi=i,this.props={},this.mi=void 0,this.yi=(s=>{var o="";return s.token&&(o=s.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),s.persistence_name?"ph_"+s.persistence_name:"ph_"+o+"_posthog"})(e),this.ii=this.bi(e),this.pi=this.wi(e),this.load(),e.debug&&A.info("Persistence loaded",e.persistence,I({},this.props)),this.update_config(e,e,n),this.save(),w){var r=()=>this.flush();ve(w,"beforeunload",r,{capture:!1}),ve(w,"pagehide",r,{capture:!1})}}ki(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return ke(n)&&n>0?n:0}isDisabled(){return!!this.xi}bi(e){am.indexOf(e.persistence.toLowerCase())===-1&&(A.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var n,i=(function(o,a){o===void 0&&(o=[]),a===void 0&&(a=!1);var l=[...Dg,...o];return I({},le,{H(u){try{var c={};try{c=zt.H(u)||{}}catch{}var d,f=JSON.parse(le.P(u)||"{}");if(a){var h={};for(var p in c){var g=c[p];Ye(g)||g===""||(h[p]=g)}d=fe(f,h)}else d=fe(c,f);return le.F(u,d),d}catch{}return null},F(u,c,d,f,h,p){var g=le.F(u,c,void 0,void 0,p);try{var m={};l.forEach((v=>{c[v]&&(m[v]=c[v])})),Object.keys(m).length&&zt.F(u,m,d,f,h,p)}catch(v){le.j(v)}return g},q(u,c){try{w?.localStorage.removeItem(u),zt.q(u,c)}catch(d){le.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),r=!1,s=e.persistence.toLowerCase();return s==="localstorage"&&le.N()?(n=le,r=!0):s==="localstorage+cookie"&&i.N()?(n=i,r=!0):s==="sessionstorage"&&be.N()?n=be:s==="memory"?n=jg:s==="cookie"?n=zt:i.N()?(n=i,r=!0):n=zt,this.fi=r,n}Si(e){return this.yi+"__"+e}wi(e){return this.fi&&!!e.split_storage}properties(){var e={};return ie(this.props,((n,i)=>{var r=yn(i);if(!r||r.exposure==="event"){if(r!=null&&r.shouldSkipFromEventProperties!=null&&r.shouldSkipFromEventProperties(n))return;e[i]=n}})),e}load(){if(!this.xi){var e=this.ii.H(this.yi);e&&(this.props=fe({},e)),this.pi&&this.Ci()}}Ci(){for(var e of So){var n=le.H(this.Si(e));if(n&&!Kt(n)){var i=this.Mi(e);i.persisted=!0,this.Ti(e)||(i.fingerprint=this.Ei(n,e)),this.Ii(e,n)||fe(this.props,n)}}}Ti(e){return Object.keys(this.props).some((n=>{var i;return((i=yn(n))==null?void 0:i.storageGroup)===e}))}Ii(e,n){var i=om[e];if(!i)return!1;var r=n[i],s=this.props[i];return ke(r)&&ke(s)&&s>r}refreshKey(e){var n;if(!this.xi){var i=this.pi?(n=yn(e))==null?void 0:n.storageGroup:void 0,r=i?le.H(this.Si(i)):this.ii.H(this.yi);if(r&&e in r)this.Pi(e,r[e]);else{if(i){var s=this.ii.H(this.yi);if(s&&e in s)return void this.Pi(e,s[e])}this.Ri(e)}}}save(){if(!this.xi){var e=this.ki();e>0?C(this.Ai)&&(this.Ai=setTimeout((()=>{this.Ai=void 0,this.Fi()}),e)):this.Fi()}}flush(){C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0,this.Fi())}Fi(){this.xi||(this.pi?this.Li():this.Oi(this.ii,this.yi,this.props,Hn))}Li(){var e=this.Di(),n=e.main,i=e.groups;for(var r of(this.Oi(this.ii,this.yi,n,Hn),So)){var s,o=i[r];(!Kt(o)||(s=this.ci[r])!=null&&s.persisted)&&this.Oi(le,this.Si(r),o,r)}}Di(){var e={},n={flags:{},surveys:{}};return ie(this.props,((i,r)=>{var s,o=(s=yn(r))==null?void 0:s.storageGroup;o?n[o][r]=i:e[r]=i})),{main:e,groups:n}}Ei(e,n){if(n===Hn)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var i={};return ie(e,((r,s)=>{var o;i[s]=(o=yn(s))!=null&&o.volatile?"__volatile__":r})),JSON.stringify(i)}Oi(e,n,i,r){var s=this.Mi(r);if(r===Hn||s.dirty||C(s.fingerprint)){var o;try{if((o=this.Ei(i,r))===s.fingerprint)return void(s.dirty=!1)}catch{o=void 0}e.F(n,i,this.$i,this.Ni,this.qi,this.Ne.debug)?(s.dirty=!1,r!==Hn&&(s.persisted=!0),C(o)||(s.fingerprint=o)):this.Ne.debug&&A.warn('failed to persist storage entry "'+n+'"; will retry on next save')}}remove(e){var n=(e===void 0?{}:e).keepGroupEntries,i=n!==void 0&&n;if(C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0),this.ii.q(this.yi,!1),this.ii.q(this.yi,!0),!i&&this.gi)for(var r of So)le.q(this.Si(r));i?delete this.ci[Hn]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,n,i){if(he(e)){C(n)&&(n="None"),this.$i=C(i)?this.ji:i;var r=!1;if(ie(e,((s,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==n||(this.Pi(o,s),r=!0)})),r)return this.save(),!0}return!1}register(e,n){if(he(e)){this.$i=C(n)?this.ji:n;var i=!1;if(ie(e,((r,s)=>{e.hasOwnProperty(s)&&(this.props[s]!==r||he(r)||U(r))&&(this.Pi(s,r),i=!0)})),i)return this.save(),!0}return!1}unregister(e){var n=typeof e=="string"?[e]:e,i=!1;for(var r of n)r in this.props&&(this.Ri(r),i=!0);i&&this.save()}update_campaign_params(){var e=P?.URL;if(e!==this.mi){var n=Sf(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);Kt(cl(n))||this.register(n),this.mi=e}}update_search_keyword(){var e;this.register((e=P?.referrer)?If(e):{})}update_referrer_info(){var e;this.register_once({$referrer:kf(),$referring_domain:P!=null&&P.referrer&&((e=ss(P.referrer))==null?void 0:e.host)||as},void 0)}set_initial_person_info(){this.props[fa]||this.props[ha]||this.register_once({[Qr]:Cf(this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties,this.Ne.disable_capture_url_hashes)},void 0)}get_initial_props(){var e={};ie([ha,fa],(r=>{var s=this.props[r];s&&ie(s,(function(o,a){e["$initial_"+Go(a)]=o}))}));var n=this.props[Qr];if(n){var i=(function(r,s){s===void 0&&(s=!1);var o=Af(r,s),a={};return ie(o,(function(l,u){a["$initial_"+Go(u)]=l})),a})(n,this.Ne.disable_capture_url_hashes);fe(e,i)}return e}safe_merge(e){return ie(this.props,(function(n,i){i in e||(e[i]=n)})),e}update_config(e,n,i){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!i),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var r=e.persistence!==n.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((f,h)=>f===d[h]))})(e.cookie_persisted_properties||[],n.cookie_persisted_properties||[]),s=r?this.bi(e):this.ii,o=this.wi(e);if(r||o!==this.pi){var a=this.props;this.clear(),this.ii=s,this.pi=o,this.props=a,this.save()}}set_disabled(e){this.xi=e,this.xi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ni&&(this.Ni=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this.qi&&(this.qi=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,n){var i=this.props[Ri]||{};i[e]=n,this.Pi(Ri,i),this.save()}remove_event_timer(e){var n=this.props[Ri]||{},i=n[e];return C(i)||(delete n[e],this.Pi(Ri,n),this.save()),i}get_property(e){return this.props[e]}set_property(e,n){this.Pi(e,n),this.save()}Pi(e,n){var i;this.props[e]=n,(i=yn(e))!=null&&i.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var n,i=(n=yn(e))==null?void 0:n.storageGroup;i&&(this.Mi(i).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function br(t){var e=!0;return{dispose(){if(e){e=!1;var n=t();n&&je(n.then)&&n.then(void 0,(()=>{}))}}}}var Ue={GZipJS:"gzip-js",Base64:"base64"},wi={Activation:"events",Cancellation:"cancelEvents"},Io={Popover:"popover",API:"api",Widget:"widget"},qt={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},ko={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},_a={Popover:"popover",Inline:"inline"},lm={SHOWN:"product tour shown"},Gc={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},Kc=pe("[RateLimiter]");class cm{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=n=>{var i=n.text;if(i&&i.length)try{(JSON.parse(i).quota_limited||[]).forEach((r=>{Kc.info((r||"events")+" is quota limited."),this.serverLimits[r]=new Date().getTime()+6e4}))}catch(r){return void Kc.warn('could not rate limit - continuing. Error: "'+r?.message+'"',{text:i})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var n,i,r;e===void 0&&(e=!1);var s=this.captureEventsBurstLimit,o=this.captureEventsPerSecond,a=new Date().getTime(),l=(n=(i=this.instance.persistence)==null?void 0:i.get_property(da))!==null&&n!==void 0?n:{tokens:s,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>s&&(l.tokens=s);var u=1>l.tokens;if(u||e||(l.tokens=Math.max(0,l.tokens-1)),u&&!e){var c=(ke(l.dropped)?l.dropped:0)+1;l.dropped=c,!this.lastEventRateLimited&&this.Hi(c)&&(l.dropped=0)}return this.lastEventRateLimited=u,(r=this.instance.persistence)==null||r.set_property(da,l),{isRateLimited:u,remainingTokens:l.tokens}}Ui(e){var n=this.instance.config.property_denylist;return!U(n)||!n.includes(e)}zi(){var e;if(this.Ui("$current_url")&&this.Ui("$pathname")&&me!=null&&me.pathname)return""+((e=me.origin)!==null&&e!==void 0?e:"")+me.pathname}Hi(e){var n,i,r=this.captureEventsBurstLimit,s=this.captureEventsPerSecond,o=this.zi(),a=this.Ui("$session_id")?(n=(i=this.instance).get_session_id)==null?void 0:n.call(i):void 0,l=[e+" event(s) dropped since the last warning",o?"triggered on "+o:void 0,a?"session "+a:void 0].filter(Boolean).join(", ");return!!this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited: "+l+". Config is set to "+s+" events per second and "+r+" events burst limit."},{skip_client_rate_limiting:!0})}isServerRateLimited(e){var n=this.serverLimits[e||"events"]||!1;return n!==!1&&new Date().getTime()e(this.remoteConfig))):e()}Vi(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:e})}load(){try{if(this.remoteConfig)return an.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void an.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return an.info("No config found after loading remote JS config. Falling back to JSON."),void this.Vi((n=>{this.Zi(n.json,n),this.Gi()}));this.Zi(e),this.Gi()}))}catch(e){an.error("Error loading remote config",e),this.Zi()}}stop(){this.Ki&&(clearInterval(this.Ki),this.Ki=void 0)}refresh(){!this._instance.Qi()&&P&&P.visibilityState!=="hidden"&&this._instance.reloadFeatureFlags()}Gi(){var e;if(!this.Ki){var n=(e=this._instance.config.remote_config_refresh_interval_ms)!==null&&e!==void 0?e:3e5;n!==0&&(this.Ki=setInterval((()=>{this.refresh()}),n))}}Zi(e,n){!e&&n&&(n.statusCode===0?n.error||an.warn("Failed to fetch remote config from PostHog."):an.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(r){an.error("Error applying remote config",r)}if(e?.hasFeatureFlags!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var i;(i=this._instance.featureFlags)==null||i.ensureFlagsLoaded()}catch(r){an.error("Error loading feature flags",r)}}}var ct=Uint8Array,Ke=Uint16Array,si=Uint32Array,hl=new ct([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]),pl=new ct([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]),Yc=new ct([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Rf=function(t,e){for(var n=new Ke(31),i=0;31>i;++i)n[i]=e+=1<i;++i)for(var s=n[i];n[i+1]>s;++s)r[s]=s-n[i]<<5|i;return[n,r]},Tf=Rf(hl,2),ya=Tf[1];Tf[0][28]=258,ya[258]=28;for(var Jc=Rf(pl,0)[1],$f=new Ke(32768),_e=0;32768>_e;++_e){var Wn=(43690&_e)>>>1|(21845&_e)<<1;$f[_e]=((65280&(Wn=(61680&(Wn=(52428&Wn)>>>2|(13107&Wn)<<2))>>>4|(3855&Wn)<<4))>>>8|(255&Wn)<<8)>>>1}var Hi=function(t,e,n){for(var i=t.length,r=0,s=new Ke(e);i>r;++r)++s[t[r]-1];var o,a=new Ke(e);for(r=0;e>r;++r)a[r]=a[r-1]+s[r-1]<<1;for(o=new Ke(i),r=0;i>r;++r)o[r]=$f[a[t[r]-1]++]>>>15-t[r];return o},$n=new ct(288);for(_e=0;144>_e;++_e)$n[_e]=8;for(_e=144;256>_e;++_e)$n[_e]=9;for(_e=256;280>_e;++_e)$n[_e]=7;for(_e=280;288>_e;++_e)$n[_e]=8;var ls=new ct(32);for(_e=0;32>_e;++_e)ls[_e]=5;var um=Hi($n,9),dm=Hi(ls,5),Mf=function(t){return(t/8>>0)+(7&t&&1)},Lf=function(t,e,n){(n==null||n>t.length)&&(n=t.length);var i=new(t instanceof Ke?Ke:t instanceof si?si:ct)(n-e);return i.set(t.subarray(e,n)),i},Ot=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8},bi=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8,t[i+2]|=n>>>16},Co=function(t,e){for(var n=[],i=0;t.length>i;++i)t[i]&&n.push({s:i,f:t[i]});var r=n.length,s=n.slice();if(!r)return[new ct(0),0];if(r==1){var o=new ct(n[0].s+1);return o[n[0].s]=1,[o,1]}n.sort((function(b,k){return b.f-k.f})),n.push({s:-1,f:25001});var a=n[0],l=n[1],u=0,c=1,d=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=r-1;)a=n[n[d].f>n[u].f?u++:d++],l=n[u!=c&&n[d].f>n[u].f?u++:d++],n[c++]={s:-1,f:a.f+l.f,l:a,r:l};var f=s[0].s;for(i=1;r>i;++i)s[i].s>f&&(f=s[i].s);var h=new Ke(f+1),p=wa(n[c-1],h,0);if(p>e){i=0;var g=0,m=p-e,v=1<i;++i){var E=s[i].s;if(e>=h[E])break;g+=v-(1<>>=m;g>0;){var S=s[i].s;e>h[S]?g-=1<=0&&g;--i){var _=s[i].s;h[_]==e&&(--h[_],++g)}p=e}return[new ct(h),p]},wa=function(t,e,n){return t.s==-1?Math.max(wa(t.l,e,n+1),wa(t.r,e,n+1)):e[t.s]=n},Zc=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new Ke(++e),i=0,r=t[0],s=1,o=function(l){n[i++]=l},a=1;e>=a;++a)if(t[a]==r&&a!=e)++s;else{if(!r&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(r),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(r);s=1,r=t[a]}return[n.subarray(0,i),e]},Ei=function(t,e){for(var n=0,i=0;e.length>i;++i)n+=t[i]*e[i];return n},ba=function(t,e,n){var i=n.length,r=Mf(e+2);t[r]=255&i,t[r+1]=i>>>8,t[r+2]=255^t[r],t[r+3]=255^t[r+1];for(var s=0;i>s;++s)t[r+s+4]=n[s];return 8*(r+4+i)},Xc=function(t,e,n,i,r,s,o,a,l,u,c){Ot(e,c++,n),++r[256];for(var d=Co(r,15),f=d[0],h=d[1],p=Co(s,15),g=p[0],m=p[1],v=Zc(f),E=v[0],S=v[1],_=Zc(g),b=_[0],k=_[1],T=new Ke(19),x=0;E.length>x;++x)T[31&E[x]]++;for(x=0;b.length>x;++x)T[31&b[x]]++;for(var F=Co(T,7),$=F[0],O=F[1],L=19;L>4&&!$[Yc[L-1]];--L);var N,K,V,M,R=u+5<<3,Z=Ei(r,$n)+Ei(s,ls)+o,Ce=Ei(r,f)+Ei(s,g)+o+14+3*L+Ei(T,$)+(2*T[16]+3*T[17]+7*T[18]);if(Z>=R&&Ce>=R)return ba(e,c,t.subarray(l,l+u));if(Ot(e,c,1+(Z>Ce)),c+=2,Z>Ce){N=Hi(f,h),K=f,V=Hi(g,m),M=g;var oe=Hi($,O);for(Ot(e,c,S-257),Ot(e,c+5,k-1),Ot(e,c+10,L-4),c+=14,x=0;L>x;++x)Ot(e,c+3*x,$[Yc[x]]);c+=3*L;for(var ye=[E,b],$e=0;2>$e;++$e){var ae=ye[$e];for(x=0;ae.length>x;++x)Ot(e,c,oe[Ie=31&ae[x]]),c+=$[Ie],Ie>15&&(Ot(e,c,ae[x]>>>5&127),c+=ae[x]>>>12)}}else N=um,K=$n,V=dm,M=ls;for(x=0;a>x;++x)if(i[x]>255){var Ie;bi(e,c,N[257+(Ie=i[x]>>>18&31)]),c+=K[Ie+257],Ie>7&&(Ot(e,c,i[x]>>>23&31),c+=hl[Ie]);var Se=31&i[x];bi(e,c,V[Se]),c+=M[Se],Se>3&&(bi(e,c,i[x]>>>5&8191),c+=pl[Se])}else bi(e,c,N[i[x]]),c+=K[i[x]];return bi(e,c,N[256]),c+K[256]},fm=new si([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),hm=(function(){for(var t=new si(256),e=0;256>e;++e){for(var n=e,i=9;--i;)n=(1&n&&3988292384)^n>>>1;t[e]=n}return t})(),Ao=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8};function pm(t,e){e===void 0&&(e={});var n=(function(){var d=4294967295;return{p(f){for(var h=d,p=0;f.length>p;++p)h=hm[255&h^f[p]]^h>>>8;d=h},d(){return 4294967295^d}}})(),i=t.length;n.p(t);var r,s,o,a,l,u=(a=10+((r=e).filename&&r.filename.length+1||0),l=8,(function(d,f,h,p,g,m){var v=d.length,E=new ct(p+v+5*(1+Math.floor(v/7e3))+g),S=E.subarray(p,E.length-g),_=0;if(!f||8>v)for(var b=0;v>=b;b+=65535){var k=b+65535;v>k?_=ba(S,_,d.subarray(b,k)):(S[b]=!0,_=ba(S,_,d.subarray(b,v)))}else{for(var T=fm[f-1],x=T>>>13,F=8191&T,$=(1<b;++b){var Ie=V(b),Se=32767&b,De=L[Ie];if(O[Se]=De,L[Ie]=Se,b>=$e){var wt=v-b;if((Ce>7e3||ye>24576)&&wt>423){_=Xc(d,S,0,M,R,Z,oe,ye,ae,b-ae,_),ye=Ce=oe=0,ae=b;for(var ge=0;286>ge;++ge)R[ge]=0;for(ge=0;30>ge;++ge)Z[ge]=0}var Je=2,bt=0,mn=F,Re=Se-De&32767;if(wt>2&&Ie==V(b-Re))for(var Pe=Math.min(x,wt)-1,$t=Math.min(32767,b),Bn=Math.min(258,wt);$t>=Re&&--mn&&Se!=De;){if(d[b+Je]==d[b+Je-Re]){for(var qe=0;Bn>qe&&d[b+qe]==d[b+qe-Re];++qe);if(qe>Je){if(Je=qe,bt=Re,qe>Pe)break;var Dn=Math.min(Re,qe-2),Mt=0;for(ge=0;Dn>ge;++ge){var Lt=b-Re+ge+32768&32767,ut=Lt-O[Lt]+32768&32767;ut>Mt&&(Mt=ut,De=Lt)}}}Re+=(Se=De)-(De=O[Se])+32768&32767}if(bt){M[ye++]=268435456|ya[Je]<<18|Jc[bt];var sn=31&ya[Je],gi=31&Jc[bt];oe+=hl[sn]+pl[gi],++R[257+sn],++Z[gi],$e=b+Je,++Ce}else M[ye++]=d[b],++R[d[b]]}}_=Xc(d,S,!0,M,R,Z,oe,ye,ae,b-ae,_)}return Lf(E,0,p+Mf(_)+g)})(s=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):12+o.mem,a,l)),c=u.length;return(function(d,f){var h=f.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>f.level?4:f.level==9?2:0,d[9]=3,f.mtime!=0&&Ao(d,4,Math.floor(new Date(f.mtime||Date.now())/1e3)),h){d[3]=8;for(var p=0;h.length>=p;++p)d[p+10]=h.charCodeAt(p)}})(u,e),Ao(u,c-8,n.d()),Ao(u,c-4,i),u}var gm=!!zo||!!Xa,Nf="text/plain",Mr=!1,Of=(t,e)=>{var n=t.split("#"),i=n[1],r=n[0].split("?"),s=r[0],o=r[1];if(!o)return t;var a=o.split("&").filter((l=>l.split("=")[0]!==e)).join("&");return s+(a?"?"+a:"")+(i?"#"+i:"")},ks=function(t,e,n){var i;n===void 0&&(n=!0);var r=t.split("?"),s=r[0],o=r[1],a=I({},e),l=(i=o?.split("&").map((c=>{var d,f=c.split("="),h=f[0],p=n&&(d=a[h])!==null&&d!==void 0?d:f[1];return delete a[h],h+"="+p})))!==null&&i!==void 0?i:[],u=(function(c,d){var f,h;d===void 0&&(d="&");var p=[];return ie(c,(function(g,m){C(g)||C(m)||m==="undefined"||(f=encodeURIComponent((v=>v instanceof File)(g)?g.name:g.toString()),h=encodeURIComponent(m),p[p.length]=h+"="+f)})),p.join(d)})(a);return u&&l.push(u),l.length>0?s+"?"+l.join("&"):s},Po=t=>{if(t.Ji)return t.Ji;var e=t.data,n=t.compression;if(e){if(n===Ue.GZipJS){var i=pm((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new ct(a.length+(a.length>>>1)),d=0,f=function(m){c[d++]=m},h=0;u>h;++h){if(d+5>c.length){var p=new ct(d+8+(u-h<<1));p.set(c),c=p}var g=a.charCodeAt(h);128>g?f(g):2048>g?(f(192|g>>>6),f(128|63&g)):g>55295&&57344>g?(f(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++h))>>>18),f(128|g>>>12&63),f(128|g>>>6&63),f(128|63&g)):(f(224|g>>>12),f(128|g>>>6&63),f(128|63&g))}return Lf(c,0,d)})(Yn(e)),{mtime:0});return{contentType:Nf,body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),estimatedSize:i.byteLength}}if(n===Ue.Base64){var r=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(Yn(e)),s=(a=>"data="+encodeURIComponent(typeof a=="string"?a:Yn(a)))(r);return{contentType:"application/x-www-form-urlencoded",body:s,estimatedSize:new Blob([s]).size}}var o=Yn(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},Bf=t=>{var e,n,i=()=>t.transport==="sendBeacon"?{url:ks(t.url,{compression:Ue.Base64}),encodedBody:Po(I({},t,{compression:Ue.Base64,Ji:void 0}))}:{url:Of(t.url,"compression"),encodedBody:Po(I({},t,{compression:void 0,Ji:void 0}))};try{e=Po(t)}catch(r){if(_c(t.compression,ii(t.url,"compression")))return A.error("Failed to gzip request body, sending uncompressed payload",r),i();throw r}return e&&_c(t.compression,ii(t.url,"compression"))&&!((n=e.body)instanceof ArrayBuffer?qo(new Uint8Array(n)):ArrayBuffer.isView(n)&&qo(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)))?(Mr=!0,i()):{url:t.url,encodedBody:e}},Df=t=>{try{return Bf(t)}catch(e){return A.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},mm=(function(){var t=se((function*(e){var n=Yn(e.data),i=yield(function(s,o,a){return Vo.apply(this,arguments)})(n,ne.DEBUG,{rethrow:!0});if(!i)return e;var r=yield i.arrayBuffer();return I({},e,{Ji:{contentType:Nf,body:r,estimatedSize:r.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),vm=/Failed to fetch|NetworkError|Load failed/i,jf=t=>t?.name==="TypeError"&&vm.test(t?.message||""),Uf=t=>{var e=Df(t);if(e){var n=e.url,i=e.encodedBody,r=i??{},s=r.contentType,o=r.body,a=r.estimatedSize,l=new Headers;ie(t.headers,(function(p,g){l.append(g,p)})),s&&l.append("Content-Type",s);var u=null,c=!1;if(fc){var d=new fc;u={signal:d.signal,timeout:setTimeout((()=>{var p,g;c=!0,d.abort((p=t.timeout,(g=new Error("PostHog request timed out"+(p?" after "+p+"ms":""))).name="AbortError",g))}),t.timeout)}}var f=p=>{c&&p?.name==="AbortError"||jf(p)?A.warn(p):A.error(p),t.callback==null||t.callback({statusCode:0,error:p})};try{var h;Xa(n,I({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(h=u)==null?void 0:h.signal},t.fetchOptions)).then((p=>p.text().then((g=>{var m={statusCode:p.status,text:g};if(p.status===200)try{m.json=JSON.parse(g)}catch(v){A.error(v)}t.callback==null||t.callback(m)})))).catch(f).finally((()=>u?clearTimeout(u.timeout):null))}catch(p){u&&clearTimeout(u.timeout),f(p)}}},Ea=t=>{try{var e,n=Bf(t),i=n.url,r=n.encodedBody,s=r??{},o=s.body,a=s.estimatedSize;if(!o)return;var l=o instanceof Blob?o:new Blob([o],{type:s.contentType});if(He.sendBeacon(i,l))return;var u=U(t.data)?t.data:(e=t.data)==null?void 0:e.batch;if(U(u)&&u.length>1&&(a??0)>16384){var c=Math.ceil(u.length/2),d=f=>U(t.data)?f:I({},t.data,{batch:f});return Ea(I({},t,{data:d(u.slice(0,c))})),void Ea(I({},t,{data:d(u.slice(c))}))}A.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),Uf(I({},t,{Yi:!0}))}catch(f){A.warn("Beacon send failed",f)}},Qc=(t,e,n,i)=>{var r=i==="query"?e==="POST"?"sent_at":"_":void 0;return ks(n===Ue.GZipJS?Of(t,"compression"):t,I({},r?{[r]:Date.now().toString()}:{},n===Ue.GZipJS?{}:{compression:n}))},Lr=[];Xa&&Lr.push({transport:"fetch",method:Uf}),zo&&Lr.push({transport:"XHR",method(t){var e=Df(t);if(e){var n=new zo,i=e.encodedBody;n.open(t.method||"GET",e.url,!0);var r=i??{},s=r.contentType,o=r.body;ie(t.headers,(function(a,l){n.setRequestHeader(l,a)})),s&&n.setRequestHeader("Content-Type",s),t.timeout&&(n.timeout=t.timeout),n.onreadystatechange=()=>{if(n.readyState===4){var a={statusCode:n.status,text:n.responseText};if(n.status===200)try{a.json=JSON.parse(n.responseText)}catch{}t.callback==null||t.callback(a)}},n.send(o)}}}),He!=null&&He.sendBeacon&&Lr.push({transport:"sendBeacon",method:Ea});var Sa=3e3;class _m{constructor(e,n){this.Xi=!0,this.tr=[],this.er=At(n?.flush_interval_ms||Sa,250,5e3,A.createLogger("flush interval"),Sa),this.ir=e}enqueue(e){this.tr.push(e),this.rr||this.nr()}unload(){this.sr();var e=this.tr.length>0?this.ar():{},n=Object.values(e);[...n.filter((i=>i.url.indexOf("/e")===0)),...n.filter((i=>i.url.indexOf("/e")!==0))].map((i=>{this.lr(I({},i,{transport:"sendBeacon"}))}))}enable(){this.Xi=!1,this.nr()}nr(){var e=this;this.Xi||(this.rr=setTimeout((()=>{if(this.sr(),this.tr.length>0){var n=this.ar(),i=function(){var s=n[r],o=new Date().getTime();s.data&&U(s.data)&&ie(s.data,(a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp})),e.lr(s)};for(var r in n)i()}}),this.er))}lr(e){try{this.ir(e)}catch(n){A.error(n)}}sr(){clearTimeout(this.rr),this.rr=void 0}ar(){var e={};return ie(this.tr,(n=>{var i,r=n,s=(r?r.batchKey:null)||r.url;C(e[s])&&(e[s]=I({},r,{data:[]})),(i=e[s].data)==null||i.push(r.data)})),this.tr=[],e}}var ym=["retriesPerformedSoFar"];class wm{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!C(w)&&"onLine"in w.navigator&&(this.dr=w.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},ve(w,"online",this.vr),ve(w,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var n=e.retriesPerformedSoFar,i=pd(e,ym);Dt(n)&&(i.url=ks(i.url,{retry_count:n})),this._instance._send_request(I({},i,{callback:r=>{if(r.statusCode!==200&&(400>r.statusCode||r.statusCode>=500)){if((r.statusCode===0?3:10)>(n??0))return void this.At(I({retriesPerformedSoFar:n},i));r.statusCode===0&&A.warn("Request failed before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped retrying after "+(n??0)+" retries.")}i.callback==null||i.callback(r)}}))}At(e){var n=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=n+1;var i=(function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),c=Math.random()-.5;return Math.ceil(u+c*(u-l))})(n),r=Date.now()+i;this.tr.push({retryAt:r,requestOptions:e});var s="Enqueued failed request for retry in "+i;navigator.onLine||(s+=" (Browser is offline)"),A.warn(s),this.ur||(this.ur=!0,this.gr())}gr(){if(this.mr&&clearTimeout(this.mr),this.tr.length===0)return this.ur=!1,void(this.mr=void 0);this.mr=setTimeout((()=>{this.dr&&this.tr.length>0&&this.cr(),this.gr()}),this.hr)}cr(){var e=Date.now(),n=[],i=this.tr.filter((s=>e>s.retryAt||(n.push(s),!1)));if(this.tr=n,i.length>0)for(var r of i)this.retriableRequest(r.requestOptions)}unload(){for(var e of(this.mr&&(clearTimeout(this.mr),this.mr=void 0),this.ur=!1,C(w)||(this.vr&&(w.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(w.removeEventListener("offline",this.pr),this.pr=void 0)),this.tr)){var n=e.requestOptions;try{this._instance._send_request(I({},n,{transport:"sendBeacon"}))}catch(i){A.error(i)}}this.tr=[]}}class bm{constructor(e){this.yr=()=>{var n,i,r,s;this.br||(this.br={});var o=this.scrollElement(),a=this.scrollY(),l=o?Math.max(0,o.scrollHeight-o.clientHeight):0,u=a+(o?.clientHeight||0),c=o?.scrollHeight||0;this.br.lastScrollY=Math.ceil(a),this.br.maxScrollY=Math.max(a,(n=this.br.maxScrollY)!==null&&n!==void 0?n:0),this.br.maxScrollHeight=Math.max(l,(i=this.br.maxScrollHeight)!==null&&i!==void 0?i:0),this.br.lastContentY=u,this.br.maxContentY=Math.max(u,(r=this.br.maxContentY)!==null&&r!==void 0?r:0),this.br.maxContentHeight=Math.max(c,(s=this.br.maxContentHeight)!==null&&s!==void 0?s:0)},this._instance=e}get _r(){return this._instance.config.scroll_root_selector}getContext(){return this.br}resetContext(){var e=this.br;return setTimeout(this.yr,0),e}startMeasuringScrollPosition(){ve(w,"scroll",this.yr,{capture:!0}),ve(w,"scrollend",this.yr,{capture:!0}),ve(w,"resize",this.yr)}scrollElement(){if(!this._r)return w?.document.documentElement;var e=U(this._r)?this._r:[this._r];for(var n of e){var i=w?.document.querySelector(n);if(i)return i}}wr(e){var n=e==="y"?"scrollTop":"scrollLeft";if(this._r){var i=this.scrollElement();return i&&i[n]||0}return w?e==="y"?w.scrollY||w.pageYOffset||w.document.documentElement.scrollTop||0:w.scrollX||w.pageXOffset||w.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var Em=t=>Cf(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class eu{constructor(e,n,i,r){this.kr=s=>{var o=this.Sr();if(!o||o.sessionId!==s){var a={sessionId:s,props:this.Cr(this._instance)};this.Mr.register({[ua]:a})}},this._instance=e,this.Tr=n,this.Mr=i,this.Cr=r||Em,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[ua]}getSetOnceProps(){var e,n=(e=this.Sr())==null?void 0:e.props;return n?"r"in n?Af(n,this._instance.config.disable_capture_url_hashes):{$referring_domain:n.referringDomain,$pathname:n.initialPathName,utm_source:n.utm_source,utm_campaign:n.utm_campaign,utm_medium:n.utm_medium,utm_content:n.utm_content,utm_term:n.utm_term}:{}}getSessionProps(){var e={};return ie(cl(this.getSetOnceProps()),((n,i)=>{i==="$current_url"&&(i="url"),e["$session_entry_"+Go(i)]=n})),e}}class gl{on(e,n){return this.Er[e]||(this.Er[e]=[]),this.Er[e].push(n),()=>{this.Er[e]=this.Er[e].filter((i=>i!==n))}}emit(e,n){for(var i of this.Er[e]||[])i(n);for(var r of this.Er["*"]||[])r(e,n)}constructor(){this.Er={}}}var Si=pe("[SessionId]");class tu{on(e,n){return this.Ir.on(e,n)}constructor(e,n,i){var r;if(this.Pr=null,this.Rr=[],this.Ar=void 0,this.Fr=!1,this.Ir=new gl,this.Lr=(u,c)=>!(!Dt(u)||!Dt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===Wt)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Ne=e.config,this.Mr=e.persistence,this.Or=void 0,this.Dr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.$r=n||Ht,this.Nr=i||Ht;var s=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*At(this.Ne.session_idle_timeout_seconds||1800,60,36e3,Si.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.qr(),this.jr="ph_"+s+"_window_id",this.Br="ph_"+s+"_primary_window_exists",this.Hr()){var o=be.H(this.jr),a=be.H(this.Br);o&&!a?this.Or=o:be.q(this.jr),be.F(this.Br,!0)}if((r=this.Ne.bootstrap)!=null&&r.sessionID)try{var l=(u=>{var c=this.Ne.bootstrap.sessionID.replace(/-/g,"");if(c.length!==32)throw new Error("Not a valid UUID");if(c[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(c.substring(0,12),16)})();this.Ur(this.Ne.bootstrap.sessionID,new Date().getTime(),l)}catch(u){Si.error("Invalid sessionID in bootstrap",u)}this.zr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return C(this.Rr)&&(this.Rr=[]),this.Rr.push(e),this.Dr&&e(this.Dr,this.Or),()=>{this.Rr=this.Rr.filter((n=>n!==e))}}Hr(){return this.Ne.persistence!=="memory"&&!this.Mr.xi&&be.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&be.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?be.H(this.jr):null}Zr(e){var n=this.Pr;return!Ye(n)&&!Ye(e)&&5e3>Math.abs(e-n)}Ur(e,n,i){var r=n!==this._sessionActivityTimestamp,s=!(e!==this.Dr||i!==this._sessionStartTimestamp);this._sessionStartTimestamp=i,this._sessionActivityTimestamp=n,this.Dr=e,s&&!r||s&&this.Zr(n)||(this.Pr=n,this.Mr.register({[Kn]:[n,e,i]}))}Gr(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return Dt(n)&&n>0}Qr(){this.Gr()?this.Mr.refreshKey(Kn):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!Ye(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this.Pr){this.Qr();var n=this.Jr();n[1]===this.Dr&&n[2]===this._sessionStartTimestamp&&(this.Pr=this._sessionActivityTimestamp,this.Mr.register({[Kn]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],n=Dt(e)?e:0,i=Dt(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(n,i)}Xr(e){return this.Qr(),this.Lr(e,this.Yr())}Jr(){var e=this.Mr.props[Kn];return U(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Pr=null,clearTimeout(this.tn),this.tn=void 0,this.Ur(null,null,null)}destroy(){this.Fr=!0,this.Kr(),clearTimeout(this.tn),this.tn=void 0,this.Ar&&w&&(w.removeEventListener(ns,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&be.q(this.Br)},ve(w,ns,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=null),this.Ne.cookieless_mode===Wt)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var i=n||new Date().getTime(),r=this.Jr(),s=r[1],o=r[2],a=this.Yr(),l=this.Vr(),u=Dt(o)&&Math.abs(i-o)>864e5,c=!1,d=!1,f=!s,h=s,p=!f&&!e&&this.Lr(i,a);if(p){(p=this.Xr(i))||Si.info("cross-tab refresh kept the session alive",{sessionId:s});var g=this.Jr();s=g[1],o=g[2]}f||p||u?(s=this.$r(),l=this.Nr(),Si.info("new session ID generated",{sessionId:s,windowId:l,changeReason:{noSessionId:f,activityTimeout:p,sessionPastMaximumLength:u}}),o=i,c=!0):(l||(l=this.Nr(),c=!0),(d=s!==h)&&(Si.info("adopted cross-tab session id",{sessionId:s,windowId:l}),c=!0));var m=Dt(a)&&e&&!u?a:i,v=Dt(o)?o:new Date().getTime();this.Wr(l),this.Ur(s,m,v),e||this.qr();var E={noSessionId:f,activityTimeout:p,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((S=>S(s,l,E))),{sessionId:s,windowId:l,sessionStartTimestamp:v,changeReason:c?E:void 0,lastActivityTimestamp:a}}qr(){this.Fr||(clearTimeout(this.tn),this.tn=setTimeout((()=>{if(!this.Fr)if(this.Xr(new Date().getTime())){var e=this.Dr;this.resetSessionId(),this.Ir.emit("forcedIdleReset",{idleSessionId:e})}else this.qr()}),1.1*this.sessionTimeoutMs))}}var Hf=function(t,e){if(!t)return!1;var n=t.userAgent;if(n&&wc(n,e))return!0;try{var i=t?.userAgentData;if(i!=null&&i.brands&&i.brands.some((r=>wc(r?.brand,e))))return!0}catch{}return!!t.webdriver};function Wf(){return(Wf=se((function*(){var t=He?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),n=e?.model;return X(n)&&n.length>0?n:void 0}catch(i){return void A.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",i)}}))).apply(this,arguments)}var cs=function(t,e){if(!(function(n){try{new RegExp(n)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function Fo(t,e,n){return Yn({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}var zf={exact:(t,e)=>e.some((n=>t.some((i=>n===i)))),is_not:(t,e)=>e.every((n=>t.every((i=>n!==i)))),regex:(t,e)=>e.some((n=>t.some((i=>cs(n,i))))),not_regex:(t,e)=>e.every((n=>t.every((i=>!cs(n,i))))),icontains:(t,e)=>e.map(Er).some((n=>t.map(Er).some((i=>n.includes(i))))),not_icontains:(t,e)=>e.map(Er).every((n=>t.map(Er).every((i=>!n.includes(i))))),gt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>i>parseFloat(r)))})),lt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>it.toLowerCase();function qf(t,e){return!t||Object.entries(t).every((n=>{var i=n[1],r=e?.[n[0]];if(C(r)||Ye(r))return!1;var s=[String(r)],o=zf[i.operator];return!!o&&o(i.values,s)}))}var xa="custom",nu="i.posthog.com",Sm=/^\/static\//;class xm{constructor(e){this.en={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,n=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return n||(n=this.apiHost.replace("."+nu,".posthog.com")),n==="https://app.posthog.com"?"https://us.posthog.com":n}get region(){return this.en[this.apiHost]||(this.en[this.apiHost]=/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"us":/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"eu":xa),this.en[this.apiHost]}rn(e){if(Sm.test(e)){var n=this.instance.config.asset_host;if(typeof n=="string")return n.trim().replace(/\/$/,"")||void 0}}endpointFor(e,n){if(n===void 0&&(n=""),n&&(n=n[0]==="/"?n:"/"+n),e==="ui")return this.uiHost+n;if(e==="flags")return this.flagsApiHost+n;if(e==="assets"){var i=this.rn(n);if(i)return""+i+n}if(this.region===xa)return this.apiHost+n;var r=nu+n;switch(e){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}}function Vf(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var Q=pe("[Surveys]"),Gf="seenSurvey_",Kf=t=>{try{var e=(n=>((i,r)=>""+Gf+(function(s){return s.current_iteration&&s.current_iteration>0?s.id+"_"+s.current_iteration:s.id})(r))(0,n))(t);if(localStorage.getItem(e))return;localStorage.setItem(e,"true")}catch(n){Q.error("Failed to persist survey seen state",n)}},Im=[Io.Popover,Io.Widget,Io.API],km={ignoreConditions:!1,ignoreDelay:!1,displayType:_a.Popover},Cm=pe("[PostHog ExternalIntegrations]"),Am={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class Pm{constructor(e){this._instance=e}ai(e,n){var i;(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,e,(r=>{if(r)return Cm.error("failed to load script",r);n()}))}startIfEnabledOrStop(){var e=this,n=function(){var s,o,a,l=i[0],u=i[1];!u||(s=B.__PosthogExtensions__)!=null&&(s=s.integrations)!=null&&s[l]||e.ai(Am[l],(()=>{var c;(c=B.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=B.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=B.__PosthogExtensions__)==null||(a=a.integrations)==null||(a=a[l])==null||a.stop())};for(var i of Object.entries((r=this._instance.config.integrations)!==null&&r!==void 0?r:{})){var r;n()}}}class Fm{constructor(e,n){this.rt=e,this.nn=n,this.sn=new Map,this.an=!1}add(e){var n=this;return se((function*(){if(n.an)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(n.sn.has(e.name))throw new Error('Browser extension "'+e.name+'" is already registered');n.sn.set(e.name,e);try{var i=e.setup(n.nn);i&&(yield i)}catch(s){var r=n.sn.get(e.name)===e;r&&n.sn.delete(e.name),n.rt.error('Failed to set up browser extension "'+e.name+'"',s),r&&n.ln(e)}}))()}dispose(){if(!this.an){this.an=!0;var e=Array.from(this.sn.values()).reverse();for(var n of(this.sn.clear(),e))this.ln(n)}}ln(e){try{var n=e.dispose==null?void 0:e.dispose();n&&je(n.then)&&n.then(void 0,(i=>{this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}))}catch(i){this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}}}class Rm{constructor(e){this._instance=e}initialize(){}get(e){var n=this._instance.persistence;if(typeof e=="string")return n?.get_property(e);var i={};for(var r of e){var s=n?.get_property(r);C(s)||(i[r]=s)}return i}set(e,n){var i;(i=this._instance.persistence)==null||i.register(typeof e=="string"?{[e]:n}:e)}remove(e){var n;(n=this._instance.persistence)==null||n.unregister(e)}}var iu="extensionsRemoteConfig";class Tm{constructor(e){this.an=!1,this.instance=e,this.rt=A,this.un=e.hn,this.kv=new Rm(e),this.onEvent=n=>br(this.instance.on("eventCaptured",(i=>{try{n({event:i.event,properties:i.properties})}catch(r){this.rt.error("Browser extension event listener failed",r)}}))),this.onRemoteConfig=n=>{if(this.an)return br((()=>{}));var i=s=>{try{n(s)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},r=this.instance.dn.on(iu,i);return this.un&&i(this.un),br(r)},this.vn=new Fm(A.createLogger("[BrowserExtensions]"),this)}get logger(){return this.rt}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return(e=this.instance.get_property(Yi))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(Yi);return typeof e=="string"?e:void 0}get library(){return{name:ne.LIB_NAME,version:ne.LIB_VERSION}}get initialPersonProperties(){var e,n;return(e=(n=this.instance.persistence)==null?void 0:n.get_initial_props())!==null&&e!==void 0?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,n,i,r,s=(e=this.instance.sessionManager)==null?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:(n=s?.sessionId)!==null&&n!==void 0?n:"",windowId:(i=s?.windowId)!==null&&i!==void 0?i:"",sessionStartTimestamp:(r=s?.sessionStartTimestamp)!==null&&r!==void 0?r:0}}catch{return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get projectToken(){return this.instance.config.token}add(e){return this.vn.add(e)}capture(e,n,i){var r=this;return se((function*(){i?r.instance.capture(e,n,{timestamp:i.timestamp,uuid:i.uuid,$set:i.set,$set_once:i.setOnce}):r.instance.capture(e,n)}))()}registerDynamicEventProperties(e){return br(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(iu,e))}sendRequest(e,n){var i=this;return se((function*(){var r;n===void 0&&(n={});var s=i.instance.requestRouter.endpointFor((r=n.target)!==null&&r!==void 0?r:"api",e),o={method:n.method,url:n.query?ks(s,n.query):s,data:n.body,headers:n.headers,timeout:n.timeoutMs,fireCallbackOnDrop:!0,transport:n.transport,compression:n.compression,timestampMode:n.sentAt};return n.transport==="sendBeacon"?(i.instance._send_request(o),{statusCode:202}):new Promise((a=>{o.callback=a,i.instance._send_request(o)}))}))()}dispose(){this.an||(this.an=!0,this.vn.dispose())}}var Wi={},Ro=0,us=()=>{},ru='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',xi="Surveys module not available",su="sanitize_properties is deprecated. Use before_send instead",Yf="Invalid value for property_denylist config: ",$m=["token","distinct_id",tf],Gn="posthog",Jf=!gm&&Ge?.indexOf("MSIE")===-1&&Ge?.indexOf("Mozilla")===-1,To=t=>{var e;return I({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:Mg(P?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:us,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:t??"unset",__preview_deferred_init_extensions:!1,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:me&&X(me?.search)&&me.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disableDeviceModel:!1,disable_external_dependency_loading:!1,strict_script_versioning:!1,enable_recording_console_log:void 0,secure_cookie:(w==null||(e=w.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(n){A.error("Bad HTTP status: "+n.statusCode+" "+n.text)},get_device_id:n=>n,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:pa,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:Sa},error_tracking:{},_onCapture:us},(n=>({rageclick:n&&n>="2026-05-30"?{content_ignorelist:Vg,ignore_text_selection:!0}:!n||"2025-11-30">n||{content_ignorelist:!0},capture_pageview:!n||"2025-05-24">n||"history_change",session_recording:n&&n>="2026-06-25"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6},streamNetworkBody:!0}:n&&n>="2026-05-30"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6}}:n&&n>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:n&&n>="2026-01-30"?"head":"body",internal_or_test_user_hostname:n&&n>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:n&&n>="2026-05-30"?250:0,split_storage:!(!n||"2026-05-30">n),detect_google_search_app:!(!n||"2026-05-30">n),disable_capture_url_hashes:!(!n||"2026-06-25">n)}))(t))},Mm=[["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"]],ou=t=>{var e={};for(var n of Mm){var i=n[0],r=n[1];C(t[i])||(e[r]=t[i])}var s=fe({},e,t),o=t.__preview_external_dependency_versioned_paths;return C(o)||(C(t.strict_script_versioning)&&(s.strict_script_versioning=!!o),X(o)&&C(t.asset_host)&&(s.asset_host=o)),U(t.property_blacklist)&&(C(t.property_denylist)?s.property_denylist=t.property_blacklist:U(t.property_denylist)?s.property_denylist=[...t.property_blacklist,...t.property_denylist]:A.error(Yf+t.property_denylist)),s};class Lm{constructor(){this.__forceAllowLocalhost=!1}get fn(){return this.__forceAllowLocalhost}set fn(e){A.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class Ze{pn(e,n){if(e){var i=this.sn.indexOf(e);i!==-1&&this.sn.splice(i,1)}return this.sn.push(n),n.initialize==null||n.initialize(),n}gn(){return this.config.cookieless_mode===Wt||this.config.cookieless_mode===kn&&this.consent.isRejected()}get decideEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){var e;this.webPerformance=new Lm,this.mn=!1,this.version=ne.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new gl,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=To(),this.SentryIntegration=em,this.sentryIntegration=i=>(function(r,s){var o=wf(r,s);return{name:yf,processEvent:a=>o(a)}})(this,i),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.wn=!1,this.kn=null,this.xn=null,this.Sn=null,this.scrollManager=new bm(this),this.pageViewManager=new qc(this),this.rateLimiter=new cm(this),this.requestRouter=new xm(this),this.consent=new Ug(this),this.externalIntegrations=new Pm(this);var n=(e=Ze.__defaultExtensionClasses)!==null&&e!==void 0?e:{};this.featureFlags=n.featureFlags&&new n.featureFlags(this),this.toolbar=n.toolbar&&new n.toolbar(this),this.surveys=n.surveys&&new n.surveys(this),this.conversations=n.conversations&&new n.conversations(this),this.logs=n.logs&&new n.logs(this),this.metrics=n.metrics&&new n.metrics(this),this.experiments=n.experiments&&new n.experiments(this),this.exceptions=n.exceptions&&new n.exceptions(this),this.people={set:(i,r,s)=>{var o=X(i)?{[i]:r}:i;this.setPersonProperties(o),s?.({})},set_once:(i,r,s)=>{var o=X(i)?{[i]:r}:i;this.setPersonProperties(void 0,o),s?.({})}},this.on("eventCaptured",(i=>A.info('send "'+i?.event+'"',i)))}init(e,n,i){if(i&&i!==Gn){var r,s=(r=Wi[i])!==null&&r!==void 0?r:new Ze;return s._init(e,n,i),Wi[i]=s,Wi[Gn][i]=s,s}return this._init(e,n,i)}_init(e,n,i){var r,s;n===void 0&&(n={});var o,a=X(e)?e.trim():"";if(!a)return A.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return a!==((o=this.config)==null?void 0:o.token)?console.warn("[PostHog.js]","You have already initialized PostHog with a different project token! Re-initializing is a no-op, so events will keep going to the project this instance was initialized with. To capture into a second project, load PostHog once, then initialize a named instance after the SDK has loaded, e.g. posthog.init('"+a+"', { ... }, 'project2')"):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=To(n.defaults),n.debug=this.Cn(n.debug),this.Mn=n,this.Tn=[],n.person_profiles?this.xn=n.person_profiles:n.process_person&&(this.xn=n.process_person);var l=To(n.defaults),u=ou(n),c=fe({},l,u,{name:i,token:a});he(l.rageclick)&&he(u.rageclick)&&(c.rageclick=fe({},l.rageclick,u.rageclick)),he(l.session_recording)&&he(u.session_recording)&&(c.session_recording=fe({},l.session_recording,u.session_recording)),this.set_config(c),this.config.on_xhr_error&&A.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=n.disable_compression?void 0:Ue.GZipJS;var d=this.En();if(this.persistence=new xo(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new xo(I({},this.config,{persistence:"sessionStorage"}),d,!1),this.bn="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&be.N()){var f=be.H(this.bn);U(f)&&f.forEach((k=>{X(k)&&this.yn.add(k)}))}else be.q(this.bn);var h=I({},this.persistence.props),p=I({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new _m((k=>this.Pn(k)),this.config.request_queue_config),this.Rn=new wm(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new tu(this),this.sessionPropsManager=new eu(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((k,T,x)=>{(x!=null&&x.activityTimeout||x!=null&&x.sessionPastMaximumLength||x!=null&&x.crossTabAdoption)&&this.An()}))),this.Fn(),this.config.__preview_deferred_init_extensions?(A.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Ln(g)}),0)):(A.info("Initializing extensions synchronously"),this.Ln(g)),ne.DEBUG=ne.DEBUG||this.config.debug,ne.DEBUG&&A.info("Starting in debug mode",{this:this,config:n,thisC:I({},this.config),p:h,s:p}),!this.config.identity_distinct_id||(r=n.bootstrap)!=null&&r.distinctID||(n.bootstrap=I({},n.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((s=n.bootstrap)==null?void 0:s.distinctID)!==void 0){var m=n.bootstrap.distinctID,v=this.get_distinct_id(),E=this.persistence.get_property(at);if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&E===Un)this.identify(m);else if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&E===vn)A.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{var S=this.config.get_device_id(Ht()),_=n.bootstrap.isIdentifiedID?S:m;this.persistence.set_property(at,n.bootstrap.isIdentifiedID?vn:Un),this.register({distinct_id:m,$device_id:_})}}if(g)this.register_once({distinct_id:mr,$device_id:null},"");else if(!this.get_distinct_id()){var b=this.config.get_device_id(Ht());this.register_once({distinct_id:b,$device_id:b},""),this.persistence.set_property(at,Un)}return ve(w,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),n.segment?(function(k,T){var x=k.config.segment;if(!x)return T();(function(F,$){var O=F.config.segment;if(!O)return $();var L=K=>{var V=()=>K.anonymousId()||Ht();F.config.get_device_id=V,K.id()&&(F.register({distinct_id:K.id(),$device_id:V()}),F.persistence.set_property(at,vn)),$()},N=O.user();"then"in N&&je(N.then)?N.then(L):L(N)})(k,(()=>{x.register((F=>{typeof Promise<"u"&&Promise.resolve||Eo.warn("This browser does not have Promise support, and can not use the segment integration");var $=(O,L)=>{if(!L)return O;O.event.userId||O.event.anonymousId===F.get_distinct_id()||(Eo.info("No userId set, resetting PostHog"),F.reset()),O.event.userId&&O.event.userId!==F.get_distinct_id()&&(Eo.info("UserId set, identifying with PostHog"),F.identify(O.event.userId));var N=F.calculateEventProperties(L,O.event.properties);return O.event.properties=Object.assign({},N,O.event.properties),O};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:O=>$(O,O.event.event),page:O=>$(O,Vn),identify:O=>$(O,yo),screen:O=>$(O,"$screen")}})(k)).then((()=>{T()}))}))})(this,(()=>this.On())):this.On(),je(this.config._onCapture)&&this.config._onCapture!==us&&(A.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(k=>this.config._onCapture(k.event,k)))),this.config.ip&&A.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this.config.disableDeviceModel||(function(){return Wf.apply(this,arguments)})().then((k=>{k&&this.register({[vo]:k})})).catch(us),this}Fn(){var e,n,i,r,s,o,a=(e=(n=this.config.__extensionClasses)==null?void 0:n.featureFlags)!==null&&e!==void 0?e:(i=Ze.__defaultExtensionClasses)==null?void 0:i.featureFlags;a&&(this.featureFlags&&this.featureFlags instanceof a||((r=this.Dn)==null||r.call(this),this.Dn=void 0,this.featureFlags=new a(this)),je(this.featureFlags.onReloading)&&je(this.featureFlags.setup)?this.Dn||(this.Dn=this.featureFlags.onReloading((()=>{this.dn.emit("featureFlagsReloading",!0)})),this.$n().add(this.featureFlags)):(s=(o=this.featureFlags).initialize)==null||s.call(o))}Ln(e){var n,i,r,s,o,a,l,u=performance.now(),c=I({},Ze.__defaultExtensionClasses,this.config.__extensionClasses),d=[];c.exceptions&&this.sn.push(this.exceptions=(n=this.exceptions)!==null&&n!==void 0?n:new c.exceptions(this)),c.historyAutocapture&&this.sn.push(this.historyAutocapture=new c.historyAutocapture(this)),c.tracingHeaders&&this.sn.push(this.tracingHeaders=new c.tracingHeaders(this)),c.siteApps&&this.sn.push(this.siteApps=new c.siteApps(this)),c.sessionRecording&&!e&&this.sn.push(this.sessionRecording=new c.sessionRecording(this)),this.config.disable_scroll_properties||d.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),c.autocapture&&this.sn.push(this.autocapture=new c.autocapture(this)),c.surveys&&this.sn.push(this.surveys=(i=this.surveys)!==null&&i!==void 0?i:new c.surveys(this)),c.logs&&this.sn.push(this.logs=(r=this.logs)!==null&&r!==void 0?r:new c.logs(this)),c.metrics&&this.sn.push(this.metrics=(s=this.metrics)!==null&&s!==void 0?s:new c.metrics(this)),c.conversations&&this.sn.push(this.conversations=(o=this.conversations)!==null&&o!==void 0?o:new c.conversations(this)),c.productTours&&this.sn.push(this.productTours=new c.productTours(this)),c.heatmaps&&this.sn.push(this.heatmaps=new c.heatmaps(this)),c.webVitalsAutocapture&&this.sn.push(this.webVitalsAutocapture=new c.webVitalsAutocapture(this)),c.exceptionObserver&&this.sn.push(this.exceptionObserver=new c.exceptionObserver(this)),c.deadClicksAutocapture&&this.sn.push(this.deadClicksAutocapture=new c.deadClicksAutocapture(this,Qg)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((f=>{f.initialize&&d.push((()=>{f.initialize==null||f.initialize()}))})),d.push((()=>{if(this.Nn){var f=this.Nn;this.Nn=void 0,this.sn.forEach((h=>h.onRemoteConfig==null?void 0:h.onRemoteConfig(f)))}})),this.qn(d,u)}qn(e,n){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,n)}),0);var i=e.shift();if(i)try{i()}catch(s){A.error("Error initializing extension:",s)}}var r=Math.round(performance.now()-n);this.register_for_session({[nf]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[rf]:r}),this.config.__preview_deferred_init_extensions&&A.info("PostHog extensions initialized ("+r+"ms)")}Zi(e){var n;if(!P||!P.body)return A.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.Zi(e)}),500);if(this.config.__preview_deferred_init_extensions&&(this.Nn=e),this.hn=e,this.compression=void 0,e.ok){var i,r=e.config;r.supportedCompression&&!this.config.disable_compression&&(this.compression=j(r.supportedCompression,Ue.GZipJS)?Ue.GZipJS:j(r.supportedCompression,Ue.Base64)?Ue.Base64:void 0),(i=r.analytics)!=null&&i.endpoint&&(this.analyticsDefaultEndpoint=r.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:pa}),(n=this.jn)==null||n.handleRemoteConfig(e),this.sn.forEach((s=>s.onRemoteConfig==null?void 0:s.onRemoteConfig(e)))}On(){try{this.config.loaded(this)}catch(i){A.critical("`loaded` function failed",i)}if(this.Bn(),this.config.internal_or_test_user_hostname&&me!=null&&me.hostname){var e=me.hostname,n=this.config.internal_or_test_user_hostname;(typeof n=="string"?e===n:n.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.gn())&&this.Hn()}),1),this.Un=new Ff(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()&&vr(this.__request_queue,(e=>this.Pn(e))),this.__request_queue=[],this.Bn()}_handle_unload(){var e,n,i,r,s;(e=this.surveys)==null||e.handlePageUnload==null||e.handlePageUnload(),(n=this.metrics)==null||n.flush("sendBeacon"),this.config.request_batching?(this.zn()&&this.capture(_o),(i=this.logs)==null||i.flushLogs("sendBeacon"),(r=this.In)==null||r.unload(),(s=this.Rn)==null||s.unload()):this.zn()&&this.capture(_o,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?Jf?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)?e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:429})):(e.transport=e.transport||this.config.api_transport,e.headers=I({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,(C(this.config.disable_beacon)?this.config.__preview_disable_beacon:this.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(n=>{var i,r,s,o=I({},n);o.timeout=o.timeout||6e4;var a,l,u,c,d,f=(i=o.transport)!==null&&i!==void 0?i:"fetch";f==="sendBeacon"&&C(o.compression)&&o.data&&(o.compression=Ue.Base64),o.method==="POST"&&o.data&&(o.timestampMode==="capture-body"?o.data={api_key:(l=(d=(c=U(a=o.data)?a:[a])[0])==null||(u=d.properties)==null?void 0:u.token)!==null&&l!==void 0?l:d?.token,batch:c,sent_at:new Date().toISOString()}:o.timestampMode==="body"&&(o.data=(function(m,v){return v===void 0&&(v=new Date().toISOString()),U(m)?m.map((E=>I({},E,{sent_at:v}))):I({},m,{sent_at:v})})(o.data))),o.url=Qc(o.url,o.method,o.compression,o.timestampMode);var h=Lr.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),p=(r=(s=(function(m,v){for(var E=0;m.length>E;E++)if(m[E].transport===f)return m[E]})(h))==null?void 0:s.method)!==null&&r!==void 0?r:h[0].method;if(!p)throw new Error("No available transport method");var g=m=>{try{p(m)}catch(v){jf(v)?A.warn(v):A.error(v),o.callback==null||o.callback({statusCode:0,error:v})}};f!=="sendBeacon"&&o.data&&o.compression===Ue.GZipJS&&Np&&typeof Promise<"u"&&!Mr?mm(o).then((m=>{g(m)})).catch((m=>{if(yc(m))return Mr=!0,void g(I({},o,{compression:void 0,url:Qc(n.url,n.method,void 0,n.timestampMode)}));(v=>{if(!v||typeof v!="object")return!1;var E="name"in v?String(v.name):"";return yc(v)||E===gd})(m)&&(Mr=!0),g(o)})):p(o)})(I({},e,{callback:n=>{var i,r;this.rateLimiter.checkForLimiting(n),400>n.statusCode||(i=(r=this.config).on_request_error)==null||i.call(r,n),e.callback==null||e.callback(n)}}))):e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:0}))}Pn(e){this.Rn?this.Rn.retriableRequest(e):this._send_request(e)}_execute_array(e){Ro++;try{var n,i=[],r=[],s=[];vr(e,(a=>{if(a)if(U(n=a[0]))s.push(a);else if(je(a))try{a.call(this)}catch(l){A.error("Error executing queued PostHog call",a,l)}else U(a)&&n==="alias"?i.push(a):U(a)&&n.indexOf("capture")!==-1&&je(this[n])?s.push(a):r.push(a)}));var o=function(a,l){vr(a,(function(u){try{if(U(u[0])){var c=l;ie(u,(function(d){c=c[d[0]].apply(c,d.slice(1))}))}else l[u[0]].apply(l,u.slice(1))}catch(d){A.error("Error executing queued PostHog call",u,d)}}))};o(i,this),o(r,this),o(s,this)}finally{Ro--}}push(e){if(Ro>0&&U(e)&&X(e[0])){var n=Ze.prototype[e[0]];je(n)&&n.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,n,i){var r,s,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.In){if(this.is_capturing())if(!C(e)&&X(e)){var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var c=i!=null&&i.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(c==null||!c.isRateLimited){n!=null&&n.$current_url&&!X(n?.$current_url)&&(A.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),n==null||delete n.$current_url),e!=="$exception"||i!=null&&i.Wn||A.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,f=i?.timestamp||d,h=xc(i?.uuid,Ht),p={uuid:h,event:e,properties:this.calculateEventProperties(e,n||{},f,h)};e===Vn&&this.config.__preview_capture_bot_pageviews&&u&&(p.event="$bot_pageview",p.properties.$browser_type="bot"),c&&(p.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&p.properties.$feature_flag_has_experiment===!1&&this.get_property(Zr)===!0;i?.$set&&!g&&(p.$set=i?.$set);var m=i?.$unset;m&&(p.$unset=m);var v,E,S,_=g?void 0:this.Vn(i?.$set_once,e!==Fc,e===yo);if(_&&(p.$set_once=_),i!=null&&i._noTruncate||(s=this.config.properties_string_max_length,o=p,a=L=>X(L)?L.slice(0,s):L,l=new Set,p=(function L(N,K){if(N!==Object(N))return a?a(N):N;if(!l.has(N)){var V;if(l.add(N),U(N))V=[],vr(N,(R=>{V.push(L(R))}));else{var M={};ie(N,((R,Z)=>{l.has(R)||(M[Z]=L(R))})),V=M}return V}})(o)),p.timestamp=f,C(i?.timestamp)||(p.properties.$event_time_override_provided=!0,p.properties.$event_time_override_system_time=d),g&&(p.properties=(function(L,N){N===void 0&&(N=[]);var K={},V=M=>{L[M]!==void 0&&(K[M]=L[M])};return Op.forEach(V),N.forEach(V),K})(p.properties,$m)),e===qt.DISMISSED||e===qt.SENT){var b=n?.[ko.SURVEY_ID],k=n?.[ko.SURVEY_ITERATION];Kf({id:b,current_iteration:k}),p.$set=I({},p.$set,{[(v={id:b,current_iteration:k},E=e===qt.SENT?"responded":"dismissed",S="$survey_"+E+"/"+v.id,v.current_iteration&&v.current_iteration>0&&(S="$survey_"+E+"/"+v.id+"/"+v.current_iteration),S)]:!0})}else e===qt.SHOWN&&(p.$set=I({},p.$set,{[ko.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===lm.SHOWN){var T=n?.[Gc.TOUR_TYPE];T&&(p.$set=I({},p.$set,{[Gc.TOUR_LAST_SEEN_DATE+"/"+T]:new Date().toISOString()}))}var x=I({},p.properties.$set,p.$set);if(Kt(x)||this.setPersonPropertiesForFlags(x),!H(this.config.before_send)){var F=this.Pt(p);if(!F)return;(p=F).uuid=xc(p.uuid,Ht)}this.dn.emit("eventCaptured",p);var $=(r=i?._url)!==null&&r!==void 0?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),O={method:"POST",url:$,data:p,compression:"best-available",timestampMode:i?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test($)?"body":"capture-body",batchKey:i?._batchKey,transport:i?.transport};return!this.config.request_batching||i&&(i==null||!i._batchKey)||i!=null&&i.send_instantly?this.Pn(O):this.In.enqueue(O),p}A.critical("This capture call is ignored due to client rate limiting.")}}else A.error("No event name provided to posthog.capture")}else A.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(n=>e(n.event,n)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new Tm(this)}cn(e){this._n.push(e);var n=!0;return()=>{if(n){n=!1;var i=this._n.indexOf(e);i!==-1&&this._n.splice(i,1)}}}calculateEventProperties(e,n,i,r,s){if(i=i||new Date,!this.persistence||!this.sessionPersistence)return n;var o=s?void 0:this.persistence.remove_event_timer(e),a=I({},n);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.gn()&&(a[tf]=!0),e==="$snapshot"){var l=I({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!X(a.distinct_id)&&!ke(a.distinct_id)||Ko(a.distinct_id))&&A.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=(function(b,k,T,x){var F,$,O,L;if(x===void 0&&(x=!1),!Ge)return{};var N,K=b?[...ri,...k||[]]:[],V=(function(Bn){for(var qe=0;Ec.length>qe;qe++){var Dn=Ec[qe],Mt=Dn[1],Lt=Dn[0].exec(Bn),ut=Lt&&(je(Mt)?Mt(Lt,Bn):Mt);if(ut)return ut}return["",""]})(Ge),M=V[0],R=V[1],Z=(N=typeof navigator<"u"?navigator:void 0)!=null&&N.brave?{brave:!0}:{},Ce={};C(T)||(Ce.detectGoogleSearchApp=T);var oe={},ye=(F=navigator)==null||(F=F.userAgentData)==null?void 0:F.platform,$e=($=navigator)==null?void 0:$.maxTouchPoints,ae=w==null||(O=w.screen)==null?void 0:O.width,Ie=w==null||(L=w.screen)==null?void 0:L.height,Se=w?.devicePixelRatio;C(ye)||(oe.userAgentDataPlatform=ye),C($e)||(oe.maxTouchPoints=$e),C(ae)||(oe.screenWidth=ae),C(Ie)||(oe.screenHeight=Ie),C(Se)||(oe.devicePixelRatio=Se);var De,wt,ge,Je,bt,mn,Re,Pe,$t=fe(cl({$os:M,$os_version:R,$browser:jd(Ge,navigator.vendor,Z,Ce),$device:Sc(Ge),$device_type:(wt=Ge,ge=oe,Pe=Sc(wt),Pe===Ed||Pe===bd||Pe==="Kobo"||Pe==="Kindle Fire"||Pe===Ld?ei:Pe===Gi||Pe===Xn||Pe===Ki||Pe===Jo?"Console":Pe===xd?"Wearable":Pe?rt:ge?.userAgentDataPlatform==="Android"&&((Je=ge?.maxTouchPoints)!==null&&Je!==void 0?Je:0)>0?600>Math.min((bt=ge?.screenWidth)!==null&&bt!==void 0?bt:0,(mn=ge?.screenHeight)!==null&&mn!==void 0?mn:0)/((Re=ge?.devicePixelRatio)!==null&&Re!==void 0?Re:1)?rt:ei:"Desktop"),$timezone:Pf(),$timezone_offset:sm()}),{$current_url:Zi(x?fn(me?.href):me?.href,K,Xi),$host:me?.host,$pathname:me?.pathname,$raw_user_agent:Ge.length>1e3?Ge.substring(0,997)+"...":Ge,$browser_version:ng(Ge,navigator.vendor,Z,Ce),$browser_language:Vc(),$browser_language_prefix:(De=Vc(),typeof De=="string"?De.split("-")[0]:void 0),$screen_height:w?.screen.height,$screen_width:w?.screen.width,$viewport_height:w?.innerHeight,$viewport_width:w?.innerWidth,$lib:ne.LIB_NAME,$lib_version:ne.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return ne.SDK_DIST_CHANNEL&&($t.$sdk_dist_channel=ne.SDK_DIST_CHANNEL),$t})(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties,this.config.detect_google_search_app,this.config.disable_capture_url_hashes);if(this.sessionManager){var d=this.sessionManager.checkAndGetSessionAndWindowId(s,i.getTime()),f=d.windowId;a.$session_id=d.sessionId,a.$window_id=f}this.sessionPropsManager&&fe(a,this.sessionPropsManager.getSessionProps());try{var h;this.sessionRecording&&fe(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(h=this.Rn)==null?void 0:h.length}catch(b){a.$sdk_debug_error_capturing_properties=String(b)}if(this.requestRouter.region===xa&&(a.$lib_custom_api_host=this.config.api_host),u=e!==Vn||s?e!==_o||s?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(i):this.pageViewManager.doPageView(i,r),a=fe(a,u),e===Vn&&P&&(a.title=P.title),!C(o)){var p=i.getTime()-o;a.$duration=parseFloat((p/1e3).toFixed(3))}Ge&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();ie(["$referrer","$referring_domain"],(b=>{b in g&&delete m[b]}));var v={};if(this._n.length>0)for(var E of this._n.slice())try{fe(v,E())}catch(b){A.error("Failed to produce browser extension event properties",b)}(a=fe({},c,g,m,I({},v,a))).$is_identified=this._isIdentified(),U(this.config.property_denylist)?ie(this.config.property_denylist,(function(b){delete a[b]})):A.error(Yf+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var S=this.config.sanitize_properties;S&&(A.error(su),a=S(a,e));var _=this.Zn();return a.$process_person_profile=_,_&&!s&&this.Gn("_calculate_event_properties"),a}Vn(e,n,i){var r;if(n===void 0&&(n=!0),i===void 0&&(i=!1),!this.persistence||!this.Zn()||this.mn&&!i)return e;var s=this.persistence.get_initial_props(),o=(r=this.sessionPropsManager)==null?void 0:r.getSetOnceProps(),a=fe({},s,o||{},e||{}),l=this.config.sanitize_properties;return l&&(A.error(su),a=l(a,"$set_once")),n&&(this.mn=!0),Kt(a)?void 0:a}register(e,n){var i;(i=this.persistence)==null||i.register(e,n)}register_once(e,n,i){var r;(r=this.persistence)==null||r.register_once(e,n,i)}register_for_session(e){var n;(n=this.sessionPersistence)==null||n.register(e),Object.keys(e).forEach((i=>this.yn.add(i))),this.Qn()}unregister(e){var n;(n=this.persistence)==null||n.unregister(e)}unregister_for_session(e){var n;(n=this.sessionPersistence)==null||n.unregister(e),this.yn.delete(e),this.Qn()}Kn(e,n){this.register({[e]:n})}An(){this.yn.forEach((e=>{var n;(n=this.sessionPersistence)==null||n.unregister(e)})),this.yn.clear(),this.Qn()}Qn(){var e;if(this.bn)if(this.config.persistence==="memory"||(e=this.sessionPersistence)!=null&&e.xi||!be.N())be.q(this.bn);else{var n=[];this.yn.forEach((i=>n.push(i))),n.length>0?be.F(this.bn,n):be.q(this.bn)}}getFeatureFlag(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlag(e,n)}getFeatureFlagPayload(e){var n;return(n=this.featureFlags)==null?void 0:n.getFeatureFlagPayload(e)}getFeatureFlagResult(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlagResult(e,n)}getAllFeatureFlags(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.getAllFeatureFlags())!==null&&e!==void 0?e:[]}isFeatureEnabled(e,n){var i,r;return(i=(r=this.featureFlags)==null?void 0:r.isFeatureEnabled(e,n))!==null&&i!==void 0?i:n?.defaultValue}reloadFeatureFlags(){var e;(e=this.featureFlags)==null||e.reloadFeatureFlags()}updateFlags(e,n,i){var r;(r=this.featureFlags)==null||r.updateFlags(e,n,i)}updateEarlyAccessFeatureEnrollment(e,n,i){var r;(r=this.featureFlags)==null||r.updateEarlyAccessFeatureEnrollment(e,n,i)}getEarlyAccessFeatures(e,n,i){var r;return n===void 0&&(n=!1),(r=this.featureFlags)==null?void 0:r.getEarlyAccessFeatures(e,n,i)}on(e,n){return this.dn.on(e,n)}onFeatureFlags(e){return this.featureFlags?this.featureFlags.onFeatureFlags(e):(e([],{},{errorsLoading:!0}),()=>{})}onSurveysLoaded(e){return this.surveys?this.surveys.onSurveysLoaded(e):(e([],{isLoaded:!1,error:xi}),()=>{})}onSessionId(e){var n,i;return(n=(i=this.sessionManager)==null?void 0:i.onSessionId(e))!==null&&n!==void 0?n:()=>{}}getSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getSurveys(e,n):e([],{isLoaded:!1,error:xi})}getActiveMatchingSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,n):e([],{isLoaded:!1,error:xi})}renderSurvey(e,n){var i;(i=this.surveys)==null||i.renderSurvey(e,n)}displaySurvey(e,n){var i;n===void 0&&(n=km),(i=this.surveys)==null||i.displaySurvey(e,n)}cancelPendingSurvey(e){var n;(n=this.surveys)==null||n.cancelPendingSurvey(e)}canRenderSurvey(e){var n,i;return(n=(i=this.surveys)==null?void 0:i.canRenderSurvey(e))!==null&&n!==void 0?n:{visible:!1,disabledReason:xi}}canRenderSurveyAsync(e,n){var i,r;return n===void 0&&(n=!1),(i=(r=this.surveys)==null?void 0:r.canRenderSurveyAsync(e,n))!==null&&i!==void 0?i:Promise.resolve({visible:!1,disabledReason:xi})}Jn(e){return!e||Ko(e)?(A.critical("Unique user id has not been set in posthog.identify"),!1):e===mr?(A.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.'),!1):!["distinct_id","distinctid"].includes(e.toLowerCase())&&!["undefined","null"].includes(e.toLowerCase())||(A.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.'),!1)}identify(e,n,i){if(!this.__loaded||!this.persistence)return A.uninitializedWarning("posthog.identify");if(ke(e)&&(e=e.toString(),A.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.Jn(e)&&this.Gn("posthog.identify")){var r=this.get_distinct_id();this.register({$user_id:e}),this.get_property(Yi)||this.register_once({$had_persisted_distinct_id:!0,$device_id:r},""),e!==r&&e!==this.get_property(Fi)&&(this.unregister(Fi),this.register({distinct_id:e}));var s,o=(this.persistence.get_property(at)||Un)===Un,a=e!==r,l=!a&&o;if(a&&o)this.persistence.set_property(at,vn),this.setPersonPropertiesForFlags({$set:n||{},$set_once:i||{}},!1),this.capture(yo,{distinct_id:e,$anon_distinct_id:r},{$set:n||{},$set_once:i||{}}),this.Sn=Fo(e,n,i),(s=this.featureFlags)==null||s.setAnonymousDistinctId(r);else if(l){this.persistence.set_property(at,vn);var u=n||{},c=i||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=Fo(e,n,i)}else(n||i)&&this.setPersonProperties(n,i);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Cn)):l&&(n||i)&&this.reloadFeatureFlags()}}setPersonProperties(e,n){if((e||n)&&this.Gn("posthog.setPersonProperties")){var i=Fo(this.get_distinct_id(),e,n);this.Sn!==i?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:n||{}},!0),this.capture("$set",{$set:e||{},$set_once:n||{}}),this.Sn=i):A.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}unsetPersonProperties(e){var n,i=(U(e)?e:[e]).filter((r=>X(r)&&r.length>0));i.length!==0&&this.Gn("posthog.unsetPersonProperties")&&((n=this.featureFlags)==null||n.unsetPersonPropertiesForFlags(i,!0),this.capture("$set",{$unset:i}),this.Sn=null)}group(e,n,i){if(e&&n){var r=this.getGroups(),s=r[e]!==n;if(s&&this.resetGroupPropertiesForFlags(e),this.register({$groups:I({},r,{[e]:n})}),s||i){var o={$group_type:e,$group_key:n};i&&(o.$group_set=i),this.capture(Fc,o)}i&&this.setGroupPropertiesForFlags({[e]:i}),s&&!i&&this.reloadFeatureFlags()}else A.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),(i=this.featureFlags)==null||i.setPersonPropertiesForFlags(e,n)}resetPersonPropertiesForFlags(e){var n;e===void 0&&(e=!0),(n=this.featureFlags)==null||n.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((i=this.featureFlags)==null||i.setGroupPropertiesForFlags(e,n))}resetGroupPropertiesForFlags(e){var n;(n=this.featureFlags)==null||n.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,n){var i,r,s,o,a,l,u,c,d,f;if(n===void 0&&(n=!1),A.info("reset"),!this.__loaded)return A.uninitializedWarning("posthog.reset");var h,p=this.get_property(Yi),g=this.get_property(vo),m=this.get_property(An),v=this.is_capturing();if(this.consent.reset(),n||!v||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after."),(i=this.persistence)==null||i.clear(),(r=this.sessionPersistence)==null||r.clear(),this.yn.clear(),this.Qn(),C(m)||(h=this.persistence)==null||h.register({[An]:m}),(s=this.surveys)==null||s.reset(),(o=this.Un)==null||o.stop(),(a=this.featureFlags)==null||a.reset(),(l=this.conversations)==null||l.reset(),(u=this.logs)==null||u.reset(),(c=this.metrics)==null||c.reset(),(d=this.persistence)==null||d.set_property(at,Un),(f=this.sessionManager)==null||f.resetSessionId(),this.Sn=null,this.config.cookieless_mode===Wt)this.register_once({distinct_id:mr,$device_id:null},"");else{var E=this.config.get_device_id(Ht());this.register_once({distinct_id:E,$device_id:e?E:p},""),e||C(g)||this.register({[vo]:g})}this.register({$last_posthog_reset:new Date().toISOString()},1),delete this.config.identity_distinct_id,delete this.config.identity_hash,this.reloadFeatureFlags()}shutdown(e){var n=this;return se((function*(){var i,r,s,o,a,l,u;if(n.__loaded){(i=n.Un)==null||i.stop(),(r=n.jn)==null||r.dispose(),(s=n.sessionRecording)==null||s.dispose(),(o=n.logs)==null||o.flushLogs("sendBeacon"),(a=n.metrics)==null||a.flush("sendBeacon"),(l=n.In)==null||l.unload(),(u=n.Rn)==null||u.unload();try{var c;(c=n.featureFlags)==null||c.destroy()}catch(d){A.error("Error while destroying feature flags",d)}}else A.uninitializedWarning("posthog.shutdown")}))()}setIdentity(e,n){var i;this.config.identity_distinct_id=e,this.config.identity_hash=n,this.alias(e),(i=this.conversations)==null||i.Xn()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,(e=this.conversations)==null||e.ts()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,n;return(e=(n=this.sessionManager)==null?void 0:n.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var n=this.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.sessionStartTimestamp,r=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+n.sessionId);if(e!=null&&e.withTimestamp&&i){var s,o=(s=e.timestampLookBack)!==null&&s!==void 0?s:10;if(!i)return r;r+="?t="+Math.max(Math.floor((new Date().getTime()-i)/1e3)-o,0)}return r}alias(e,n){return e===this.get_property(Yd)?(A.critical("Attempting to create alias for existing People user - aborting."),-2):this.Gn("posthog.alias")?(C(n)&&(n=this.get_distinct_id()),e!==n?(this.Kn(Fi,e),this.capture("$create_alias",{alias:e,distinct_id:n})):(A.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var n=I({},this.config);if(he(e)){var i,r,s,o,a,l,u,c,d,f,h,p;fe(this.config,ou(e));var g=this.En();(i=this.persistence)==null||i.update_config(this.config,n,g),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new xo(I({},this.config,{persistence:"sessionStorage"}),g,!1);var m=this.Cn(this.config.debug);mt(m)&&(this.config.debug=m),mt(this.config.debug)&&(this.config.debug?(ne.DEBUG=!0,le.N()&&le.F("ph_debug",!0),A.info("set_config",{config:e,oldConfig:n,newConfig:I({},this.config)})):(ne.DEBUG=!1,le.N()&&le.q("ph_debug"))),(r=this.featureFlags)==null||r.updateConfig==null||r.updateConfig(this.config,this.Qi()),(s=this.exceptionObserver)==null||s.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(f=this.deadClicksAutocapture)==null||f.startIfEnabledOrStop(),(h=this.surveys)==null||h.loadIfEnabled(),this.es(),(p=this.externalIntegrations)==null||p.startIfEnabledOrStop()}}_overrideSDKInfo(e,n){ne.LIB_NAME=e,ne.LIB_VERSION=n}startSessionRecording(e){var n,i,r,s,o,a=e===!0,l={sampling:a||!(e==null||!e.sampling),linked_flag:a||!(e==null||!e.linked_flag),url_trigger:a||!(e==null||!e.url_trigger),event_trigger:a||!(e==null||!e.event_trigger)};Object.values(l).some(Boolean)&&((n=this.sessionManager)==null||n.checkAndGetSessionAndWindowId(),l.sampling&&((i=this.sessionRecording)==null||i.overrideSampling()),l.linked_flag&&((r=this.sessionRecording)==null||r.overrideLinkedFlag()),l.url_trigger&&((s=this.sessionRecording)==null||s.overrideTrigger("url")),l.event_trigger&&((o=this.sessionRecording)==null||o.overrideTrigger("event"))),this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,n){if(this.exceptions){var i=new Error("PostHog syntheticException"),r=this.exceptions.buildProperties(e,{handled:!0,syntheticException:i});return this.exceptions.sendExceptionEvent(I({},r,n))}}addExceptionStep(e,n){var i;(i=this.exceptions)==null||i.addExceptionStep(e,n)}captureLog(e){var n;(n=this.logs)==null||n.captureLog(e)}get logger(){var e,n;return(e=(n=this.logs)==null?void 0:n.logger)!==null&&e!==void 0?e:Ze.rs}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var n,i;return(n=(i=this.toolbar)==null?void 0:i.loadToolbar(e))!==null&&n!==void 0&&n}get_property(e){var n;return(n=this.persistence)==null?void 0:n.props[e]}getSessionProperty(e){var n;return(n=this.sessionPersistence)==null?void 0:n.props[e]}toString(){var e,n=(e=this.config.name)!==null&&e!==void 0?e:Gn;return n!==Gn&&(n=Gn+"."+n),n}_isIdentified(){var e,n;return((e=this.persistence)==null?void 0:e.get_property(at))===vn||((n=this.sessionPersistence)==null?void 0:n.get_property(at))===vn}Zn(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles===pa&&!this._isIdentified()&&Kt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[Fi])&&((n=this.persistence)==null||(n=n.props)==null||!n[es]))}zn(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Zn()||this.Gn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.Gn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}Gn(e){return this.config.person_profiles==="never"?(A.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Kn(es,!0),!0)}En(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut();return this.config.disable_persistence||e&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!==kn)}es(){var e,n,i,r,s=this.En();return((e=this.persistence)==null?void 0:e.xi)!==s&&((i=this.persistence)==null||i.set_disabled(s)),((n=this.sessionPersistence)==null?void 0:n.xi)!==s&&((r=this.sessionPersistence)==null||r.set_disabled(s)),s&&(this.yn.clear(),this.Qn()),s}opt_in_capturing(e){var n;if(this.config.cookieless_mode!==Wt){if(this.gn()){var i,r,s,o,a;this.Yn(!0,!0),(i=this.sessionManager)==null||i.destroy(),(r=this.pageViewManager)==null||r.destroy(),this.sessionManager=new tu(this),this.pageViewManager=new qc(this),this.persistence&&(this.sessionPropsManager=new eu(this,this.sessionManager,this.persistence));var l,u=(s=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&s!==void 0?s:(a=Ze.__defaultExtensionClasses)==null?void 0:a.sessionRecording;u&&(this.sessionRecording=this.pn(this.sessionRecording,new u(this)),this.hn&&((l=this.sessionRecording)==null||l.onRemoteConfig==null||l.onRemoteConfig(this.hn)))}var c,d;this.consent.optInOut(!0),this.es(),this.Bn(),(n=this.sessionRecording)==null||n.startIfEnabledOrStop(),this.config.cookieless_mode==kn&&((c=this.surveys)==null||c.loadIfEnabled()),(C(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((d=e?.captureEventName)!==null&&d!==void 0?d:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hn()}else A.warn(ru)}opt_out_capturing(){var e,n,i;this.config.cookieless_mode!==Wt?(this.config.cookieless_mode===kn&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===kn&&(this.register({distinct_id:mr,$device_id:null}),(e=this.sessionRecording)==null||e.stopRecording(),this.sessionRecording=void 0,(n=this.sessionManager)==null||n.destroy(),(i=this.pageViewManager)==null||i.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.Hn(),this.Bn())):A.warn(ru)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===Wt||(this.config.cookieless_mode===kn?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return He?Hf(He,this.config.custom_blocked_useragents):void 0}Hn(){P&&(P.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(Vn,{title:P.title},{send_instantly:!0}),this.kn&&(P.removeEventListener(ts,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),ve(P,ts,this.kn)))}debug(e){e===!1?(w?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(w?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}Qi(){var e=this.Mn||{};return"advanced_disable_flags"in e?!!e.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(A.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(function(n,i,r,s,o){var a=i in n&&!H(n[i]),l=r in n&&!H(n[r]);return a?n[i]:!!l&&(o&&o.warn("Config field '"+r+"' is deprecated. Please use '"+i+"' instead. The old field will be removed in a future major version."),n[r])})(e,"advanced_disable_flags","advanced_disable_decide",0,A)}Pt(e){var n;if(H(this.config.before_send))return e;var i=Object.keys((n=e.properties)!==null&&n!==void 0?n:{}).filter(zp),r=U(this.config.before_send)?this.config.before_send:[this.config.before_send],s=e;for(var o of r){if(s=o(s),H(s)){var a="Event '"+e.event+"' was rejected in beforeSend function";return Wp(e.event)?A.warn(a+". This can cause unexpected behavior."):A.info(a),null}s.properties&&!Kt(s.properties)||A.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}for(var l of i)if(s.properties&&H(s.properties[l]))return A.warn("Event '"+e.event+"' had its '"+l+"' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped."),null;return s}getPageViewId(){var e;return(e=this.pageViewManager.ui)==null?void 0:e.pageViewId}captureTraceFeedback(e,n){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:n})}captureTraceMetric(e,n,i){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:n,$ai_metric_value:String(i)})}Cn(e){var n=mt(e)&&!e,i=le.N()&&le.P("ph_debug")==="true";return!n&&(!!i||e)}}Ze.__defaultExtensionClasses={},Ze.rs=(()=>{var t=()=>{};return{trace:t,debug:t,info:t,warn:t,error:t,fatal:t}})(),(function(t,e){for(var n=0;e.length>n;n++)t.prototype[e[n]]=Tg(t.prototype[e[n]])})(Ze,["identify"]);class au{constructor(e){this.disabled=e===!1;var n=he(e)?e:{};this.thresholdPx=n.threshold_px||30,this.timeoutMs=n.timeout_ms||1e3,this.clickCount=n.click_count||3,this.clicks=[]}isRageClick(e,n,i){if(this.disabled)return!1;var r=this.clicks[this.clicks.length-1];if(r&&Math.abs(e-r.x)+Math.abs(n-r.y)i-r.timestamp){if(this.clicks.push({x:e,y:n,timestamp:i}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:n,timestamp:i}];return!1}}var $o="$copy_autocapture",Mo=pe("[AutoCapture]");function Lo(t,e){return e.length>t?e.slice(0,t)+"...":e}function Nm(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!hn(e));return e}function Om(t,e){var n,i,r=e.e,s=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!hn(t))return{props:{}};for(var c=[t],d=new Set([t]),f=t;f.parentNode&&!et(f,"body")&&ff>c.length;)if(df(f.parentNode)){var h=f.parentNode.host;if(d.has(h))break;d.add(h),c.push(h),f=h}else{if(!hn(f.parentNode)||d.has(f.parentNode))break;d.add(f.parentNode),c.push(f.parentNode),f=f.parentNode}var p,g,m=[],v={},E=!1,S=!1;if(ie(c,(x=>{var F=va(x);if(et(x,"a")){var $=x.getAttribute("href");E=!!(F&&$&&Ui($))&&(u?fn($):$)}j(rs(x),"ph-no-capture")&&(S=!0),m.push((function(L,N,K,V,M){M===void 0&&(M=!1);var R=L.tagName.toLowerCase(),Z={tag_name:R};dl.indexOf(R)>-1&&!K&&(Z.$el_text=R.toLowerCase()==="a"||R.toLowerCase()==="button"?Lo(1024,Hc(L)):Lo(1024,Ji(L)));var Ce=rs(L);Ce.length>0&&(Z.classes=Ce.filter((function(ae){return ae!==""}))),ie(L.attributes,(function(ae){var Ie;if((!vf(L)||["name","id","class","aria-label"].indexOf(ae.name)!==-1)&&(V==null||!V.includes(ae.name))&&!N&&Ui(ae.value)&&(!X(Ie=ae.name)||Ie.substring(0,10)!=="_ngcontent"&&Ie.substring(0,7)!=="_nghost")){var Se=ae.value;ae.name==="class"&&(Se=ul(Se).join(" ")),Z["attr__"+ae.name]=Lo(1024,ae.name==="href"&&M?fn(Se):Se)}}));for(var oe=1,ye=1,$e=L;$e=Nm($e);)oe++,$e.tagName===L.tagName&&ye++;return Z.nth_child=oe,Z.nth_of_type=ye,Z})(x,s,o,a,u));var O=(function(L){if(!va(L))return{};var N={};return ie(L.attributes,(function(K){if(K.name&&K.name.indexOf("data-ph-capture-attribute")===0){var V=K.name.replace("data-ph-capture-attribute-",""),M=K.value;V&&M&&Ui(M)&&(N[V]=M)}})),N})(x);fe(v,O)})),S)return{props:{},explicitNoCapture:S};if(o||(m[0].$el_text=et(t,"a")||et(t,"button")?Hc(t):Ji(t)),E){var _,b;m[0].attr__href=E;var k=(_=ss(E))==null?void 0:_.host,T=w==null||(b=w.location)==null?void 0:b.host;k&&T&&k!==T&&(p=E)}return{props:fe({$event_type:r.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(x){return x.map((F=>{var $,O,L="";if(F.tag_name&&(L+=F.tag_name),F.attr_class)for(var N of(F.attr_class.sort(),F.attr_class))L+="."+N.replace(/"/g,"");var K=I({},F.text?{text:F.text}:{},{"nth-child":($=F.nth_child)!==null&&$!==void 0?$:0,"nth-of-type":(O=F.nth_of_type)!==null&&O!==void 0?O:0},F.href?{href:F.href}:{},F.attr_id?{attr_id:F.attr_id}:{},F.attributes),V={};return $r(K).sort(((M,R)=>M[0].localeCompare(R[0]))).forEach((M=>{var R=M[1];return V[Wc(M[0].toString())]=Wc(R.toString())})),(L+=":")+$r(V).map((M=>M[0]+'="'+M[1]+'"')).join("")})).join(";")})((function(x){return x.map((F=>{var $,O,L={text:($=F.$el_text)==null?void 0:$.slice(0,400),tag_name:F.tag_name,href:(O=F.attr__href)==null?void 0:O.slice(0,2048),attr_class:Zg(F),attr_id:F.attr__id,nth_child:F.nth_child,nth_of_type:F.nth_of_type,attributes:{}};return $r(F).filter((N=>N[0].indexOf("attr__")===0)).forEach((N=>L.attributes[N[0]]=N[1])),L}))})(g)))},(n=m[0])!=null&&n.$el_text?{$el_text:(i=m[0])==null?void 0:i.$el_text}:{},p&&r.type==="click"?{$external_click_url:p}:{},v)}}var Ii=pe("[ExceptionAutocapture]"),lu=()=>{},Bm=pe("[TracingHeaders]"),wn=pe("[Web Vitals]"),cu=9e5,uu="disabled",du="lazy_loading",ki="awaiting_config",Sr="missing_config";pe("[SessionRecording]"),pe("[SessionRecording]");var Ia="[SessionRecording]",Bt=pe(Ia),Dm=pe("[Heatmaps]");function No(t){return he(t)&&"clientX"in t&&"clientY"in t&&ke(t.clientX)&&ke(t.clientY)}var xr=pe("[Product Tours]"),Oo=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(ol))},jm=["$set_once","$set"],Et=pe("[SiteApps]"),fu="Error while initializing PostHog app with config id ";function zn(t,e,n){if(H(t))return!1;switch(n){case"exact":return t===e;case"contains":var i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(i,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}class Um{constructor(e){this.ns=new gl,this.ss=(n,i)=>this.os(n,i)&&this.ls(n,i)&&this.us(n,i)&&this.hs(n,i),this.os=(n,i)=>i==null||!i.event||n?.event===i?.event,this._instance=e,this.ds=new Set,this.vs=new Set}init(){var e,n;C((e=this._instance)==null?void 0:e._addCaptureHook)||(n=this._instance)==null||n._addCaptureHook(((i,r)=>{this.on(i,r)}))}register(e){var n,i;if(!C((n=this._instance)==null?void 0:n._addCaptureHook)&&(e.forEach((o=>{var a,l;(a=this.vs)==null||a.add(o),(l=o.steps)==null||l.forEach((u=>{var c;(c=this.ds)==null||c.add(u?.event||"")}))})),(i=this._instance)!=null&&i.autocapture)){var r,s=new Set;e.forEach((o=>{var a;(a=o.steps)==null||a.forEach((l=>{l!=null&&l.selector&&s.add(l?.selector)}))})),(r=this._instance)==null||r.autocapture.setElementSelectors(s)}}on(e,n){var i;n!=null&&e.length!=0&&(this.ds.has(e)||this.ds.has(n.event))&&this.vs&&((i=this.vs)==null?void 0:i.size)>0&&this.vs.forEach((r=>{this.cs(n,r)&&this.ns.emit("actionCaptured",r.name)}))}fs(e){this.onAction("actionCaptured",(n=>e(n)))}cs(e,n){if(n?.steps==null)return!1;for(var i of n.steps)if(this.ss(e,i))return!0;return!1}onAction(e,n){return this.ns.on(e,n)}ls(e,n){if(n!=null&&n.url){var i,r=e==null||(i=e.properties)==null?void 0:i.$current_url;if(!r||typeof r!="string"||!zn(r,n.url,n.url_matching||"contains"))return!1}return!0}us(e,n){return!!this.ps(e,n)&&!!this.gs(e,n)&&!!this.ys(e,n)}ps(e,n){var i;if(n==null||!n.href)return!0;var r=this.bs(e);if(r.length>0)return r.some((a=>zn(a.href,n.href,n.href_matching||"exact")));var s,o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!o&&zn((s=o.match(/(?::|")href="(.*?)"/))?s[1]:"",n.href,n.href_matching||"exact")}gs(e,n){var i;if(n==null||!n.text)return!0;var r=this.bs(e);if(r.length>0)return r.some((u=>zn(u.text,n.text,n.text_matching||"exact")||zn(u.$el_text,n.text,n.text_matching||"exact")));var s,o,a,l=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!l&&(s=(function(u){for(var c,d=[],f=/(?::|")text="(.*?)"/g;!H(c=f.exec(u));)d.includes(c[1])||d.push(c[1]);return d})(l),o=n.text,a=n.text_matching||"exact",s.some((u=>zn(u,o,a))))}ys(e,n){var i,r;if(n==null||!n.selector)return!0;var s=e==null||(i=e.properties)==null?void 0:i.$element_selectors;if(s!=null&&s.includes(n.selector))return!0;var o=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";if(n.selector_regex&&o)try{return new RegExp(n.selector_regex).test(o)}catch{return!1}return!1}bs(e){var n;return(e==null||(n=e.properties)==null?void 0:n.$elements)==null?[]:e?.properties.$elements}hs(e,n){return n==null||!n.properties||n.properties.length===0||qf(n.properties.reduce(((i,r)=>{var s=U(r.value)?r.value.map(String):r.value!=null?[String(r.value)]:[];return i[r.key]={values:s,operator:r.operator||"exact"},i}),{}),e?.properties)}}class Hm{constructor(e){var n;this._s=[],this._instance=e,this.ws=new Map,this.ks=new Map,this.xs=new Map,(n=this._instance)==null||n.onSessionId==null||n.onSessionId((i=>this.Ss(i)))}Cs(e){return!1}Ms(){return null}Ts(e){}Es(){}Is(e,n){return!!e&&qf(e.propertyFilters,n?.properties)}Ps(e,n){var i=new Map;return e.forEach((r=>{var s;(s=r.conditions)==null||(s=s[n])==null||(s=s.values)==null||s.forEach((o=>{if(o!=null&&o.name){var a=i.get(o.name)||[];a.push(r.id),i.set(o.name,a)}}))})),i}Rs(e,n,i){var r=(i===wi.Activation?this.ws:this.ks).get(e),s=[];return this.As((o=>{s=o.filter((a=>r?.includes(a.id)))})),s.filter((o=>{var a,l=(a=o.conditions)==null||(a=a[i])==null||(a=a.values)==null?void 0:a.find((u=>u.name===e));return this.Is(l,n)}))}register(e){var n;C((n=this._instance)==null?void 0:n._addCaptureHook)||(this.Fs(e),this.Ls(e))}Ls(e){var n=e.filter((i=>{var r,s;return((r=i.conditions)==null?void 0:r.actions)&&((s=i.conditions)==null||(s=s.actions)==null||(s=s.values)==null?void 0:s.length)>0}));n.length!==0&&(this.Os==null&&(this.Os=new Um(this._instance),this.Os.init(),this.Os.fs((i=>{this.onAction(i)}))),n.forEach((i=>{var r,s,o,a,l;i.conditions&&(r=i.conditions)!=null&&r.actions&&(s=i.conditions)!=null&&(s=s.actions)!=null&&s.values&&((o=i.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.Os)==null||a.register(i.conditions.actions.values),(l=i.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var c=this.xs.get(u.name);c&&c.push(i.id),this.xs.set(u.name,c||[i.id])}})))})))}Fs(e){var n,i=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.events)&&((a=s.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0})),r=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.cancelEvents)&&((a=s.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0}));i.length===0&&r.length===0||((n=this._instance)==null||n._addCaptureHook(((s,o)=>{this.onEvent(s,o)})),this.ws=this.Ps(e,wi.Activation),this.ks=this.Ps(e,wi.Cancellation))}onEvent(e,n){var i,r,s=this.Ds(),o=(n==null||(i=n.properties)==null?void 0:i.$survey_id)||(n==null||(r=n.properties)==null?void 0:r.$product_tour_id);if(o&&this.getActivatedIds().includes(o)){var a=this.$s(e,o);if(a==="consume")return s.info("event consumed activated item, removing it",{event:e,itemId:o}),void this.Ns([o]);if(a==="persist")return s.info("shown item promoted to persisted activation",{event:e,itemId:o}),this.qs(o),void this.js([o])}if(this.ks.has(e)){var l=this.Rs(e,n,wi.Cancellation);l.length>0&&(s.info("cancel event matched, cancelling items",{event:e,itemsToCancel:l.map((c=>c.id))}),this.Ns(l.map((c=>c.id))),l.forEach((c=>this.Bs(c.id))))}if(this.ws.has(e)){s.info("event name matched",{event:e,eventPayload:n,items:this.ws.get(e)});var u=this.Rs(e,n,wi.Activation);this.Hs(u.map((c=>c.id)))}}onAction(e){this.xs.has(e)&&this.Hs(this.xs.get(e)||[])}Hs(e){var n;if(e.length!==0){var i=!((n=this._instance)==null||n.get_session_id==null||!n.get_session_id()),r=[];for(var s of e)i&&this.Cs(s)?this.qs(s)&&this.Us(s):r.push(s);r.length>0&&(this._s=[...new Set([...this._s,...r])]),this.Ds().info("updating activated items",{activatedItems:this.getActivatedIds()})}}qs(e){this._s=this._s.filter((i=>i!==e));var n=this.zs();return!n.includes(e)&&(this.Ws([...n,e]),this.Vs(),!0)}Ns(e){var n=new Set(e);this._s=this._s.filter((s=>!n.has(s)));var i=this.Zs(),r=i.filter((s=>!n.has(s)));r.length!==i.length&&(this.Ws(r),r.length===0&&this.Gs()),this.js(e)}Qs(){var e,n=this.Ms();if(!n)return{};var i=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n];return i&&typeof i=="object"?i:{}}Us(e){if(this.Ms()){var n=this.Qs();this.Ts(I({},n,{[e]:Date.now()}))}}js(e){if(this.Ms()){var n=this.Qs(),i={},r=!1;for(var s of Object.entries(n)){var o=s[0],a=s[1];e.includes(o)?r=!0:i[o]=a}r&&(Kt(i)?this.Es():this.Ts(i))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var n=this.Qs()[e];return ke(n)?n:void 0}}Zs(){var e,n=this.Js();return((e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n])||[]}zs(){var e,n,i=this.Zs();if(i.length===0)return[];var r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[this.Ys()],s=(n=this._instance)==null||n.get_session_id==null?void 0:n.get_session_id();return s&&r===s?i:[]}Vs(){var e,n=(e=this._instance)==null||e.get_session_id==null?void 0:e.get_session_id();n&&this.Xs(n)}Gs(){this.ta()}Ss(e){var n,i=(n=this._instance)==null||(n=n.persistence)==null?void 0:n.props[this.Ys()];if(i&&i!==e){var r=this.Zs(),s=this.Qs();r.length>0&&(this.Ws([]),r.filter((o=>ke(s[o]))).forEach((o=>this.Bs(o)))),this.Gs(),this.Ks()}}getActivatedIds(){return[...new Set([...this.zs(),...this._s])].filter((e=>!this.ea(e)))}reset(){this._s=[],this.Zs().length>0&&this.Ws([]),this.Gs(),this.Ks()}getEventToItemsMap(){return this.ws}ia(){return this.Os}}class Wm extends Hm{constructor(e){super(e)}Js(){return ca}Ys(){return Fr}Ms(){return Rr}Ts(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Rr]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Rr)}Cs(e){var n,i;this.As((s=>{i=s.find((o=>o.id===e))}));var r=(n=i)==null||(n=n.appearance)==null?void 0:n.surveyPopupDelaySeconds;return ke(r)&&r>0}ra(){return qt.SHOWN}As(e){var n;(n=this._instance)==null||n.getSurveys(e)}Bs(e){var n;(n=this._instance)==null||n.cancelPendingSurvey(e)}Ds(){return Q}Ws(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[ca]:e})}Xs(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Fr]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Fr)}ea(){return!1}$s(e,n){var i;this.As((s=>{i=s.find((o=>o.id===n))}));var r=!i||(function(s){var o;return Vf(s)&&!((o=s.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||s.schedule==="always"})(i);return r?e===qt.SHOWN?"consume":"ignore":e===qt.SHOWN?"persist":e===qt.DISMISSED||e===qt.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var Ir="SDK is not enabled or survey functionality is not yet loaded",hu="Disabled. Not loading surveys.",zm=w!=null&&w.location?os(w.location.hash,"__posthog")||os(location.hash,"state"):null,pu="_postHogToolbarParams",gu=pe("[Toolbar]"),mu=pe("[FeatureFlags]");class qm{constructor(e,n){n===void 0&&(n=!1),this.na=!1,this.update(e,n)}update(e,n){this.sa=((i,r)=>{var s,o,a,l;return{bootstrap:{featureFlags:(s=i.bootstrap)==null?void 0:s.featureFlags,featureFlagPayloads:(o=i.bootstrap)==null?void 0:o.featureFlagPayloads},remoteRequestsDisabled:r,featureFlagsDisabled:!!i.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!i.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!i.advanced_feature_flags_dedup_per_session,cacheTtlMs:i.feature_flag_cache_ttl_ms,requestTimeoutMs:i.feature_flag_request_timeout_ms,compression:i.disable_compression?"none":"base64",evaluationContexts:(a=(l=i.evaluation_contexts)!==null&&l!==void 0?l:i.evaluation_environments)!==null&&a!==void 0?a:[],flagKeys:U(i.flag_keys)?i.flag_keys:void 0}})(e,n),!e.evaluation_environments||e.evaluation_contexts||this.na||(mu.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.na=!0),C(e.flag_keys)||U(e.flag_keys)||mu.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var vu=pe("[FeatureFlags]"),bn=pe("[FeatureFlags]",{debugEnabled:!0}),Bo=`" failed. Feature flags didn't load in time.`,_u="connection_error",yu=t=>{for(var e={},n=0;t.length>n;n++)e[t[n]]=!0;return e},wu=t=>{var e={};for(var n of $r(t||{})){var i=n[1];i&&(e[n[0]]=i)}return e},St=pe("[Error tracking]"),bu="Refusing to render web experiment since the viewer is a likely bot",Vm={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>cs(e,t),not_regex:(t,e)=>!cs(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class Me{get Ne(){return this._instance.config}constructor(e){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(i){i===void 0&&(i=!1),n.getWebExperiments((r=>{Me.aa("retrieved web experiments from the server"),n.oa=new Map,r.forEach((s=>{if(s.feature_flag_key){var o;n.oa&&(Me.aa("setting flag key ",s.feature_flag_key," to web experiment ",s),(o=n.oa)==null||o.set(s.feature_flag_key,s));var a=n._instance.getFeatureFlag(s.feature_flag_key);X(a)&&s.variants[a]&&n.la(s.name,a,s.variants[a].transforms)}else if(s.variants)for(var l in s.variants){var u=s.variants[l];Me.ua(u,n._instance)&&n.la(s.name,l,u.transforms)}}))}),i)},this._instance=e,this._instance.onFeatureFlags((i=>{this.onFeatureFlags(i)}))}initialize(){}onFeatureFlags(e){if(this._is_bot())Me.aa(bu);else if(!this.Ne.disable_web_experiments){if(H(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();Me.aa("applying feature flags",e),e.forEach((n=>{var i;if(this.oa&&(i=this.oa)!=null&&i.has(n)){var r,s=this._instance.getFeatureFlag(n),o=(r=this.oa)==null?void 0:r.get(n);s&&o!=null&&o.variants[s]&&this.la(o.name,s,o.variants[s].transforms)}}))}}previewWebExperiment(){var e=Me.getWindowLocation();if(e!=null&&e.search){var n=ii(e?.search,"__experiment_id"),i=ii(e?.search,"__experiment_variant");n&&i&&(Me.aa("previewing web experiments "+n+" && "+i),this.getWebExperiments((r=>{this.ha(parseInt(n),i,r)}),!1,!0))}}loadIfEnabled(){this.Ne.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,n,i){if(this.Ne.disable_web_experiments&&!i)return e([]);var r=this._instance.get_property("$web_experiments");if(r&&!n)return e(r);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this.Ne.token),method:"GET",timestampMode:"query",callback:s=>e(s.statusCode===200&&s.json&&s.json.experiments||[])})}ha(e,n,i){var r=i.filter((s=>s.id===e));r&&r.length>0&&(Me.aa("Previewing web experiment ["+r[0].name+"] with variant ["+n+"]"),this.la(r[0].name,n,r[0].variants[n].transforms))}static ua(e,n){return!H(e.conditions)&&Me.da(e,n)&&Me.va(e)}static da(e,n){var i;if(H(e.conditions)||H((i=e.conditions)==null?void 0:i.url))return!0;var r=Me.getWindowLocation();if(r){var s,o,a,l=lf(n,r.href);return(s=e.conditions)==null||!s.url||Vm[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return w?.location}static va(e){var n;if(H(e.conditions)||H((n=e.conditions)==null?void 0:n.utm))return!0;var i=Sf();if(i.utm_source){var r,s,o,a,l,u,c,d,f=(r=e.conditions)==null||(r=r.utm)==null||!r.utm_campaign||((s=e.conditions)==null||(s=s.utm)==null?void 0:s.utm_campaign)==i.utm_campaign,h=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==i.utm_source,p=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==i.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==i.utm_term;return f&&p&&g&&h}return!1}static aa(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;n>r;r++)i[r-1]=arguments[r];A.info("[WebExperiments] "+e,i)}la(e,n,i){this._is_bot()?Me.aa(bu):n!=="control"?i.forEach((r=>{if(r.selector){var s;Me.aa("applying transform of variant "+n+" for experiment "+e+" ",r);var o=(s=document)==null?void 0:s.querySelectorAll(r.selector);o?.forEach((a=>{var l=a;r.html&&(l.innerHTML=r.html),r.css&&l.setAttribute("style",r.css)}))}})):Me.aa("Control variants leave the page unmodified.")}_is_bot(){return He&&this._instance?Hf(He,this.Ne.custom_blocked_useragents):void 0}}var ot=pe("[Conversations]"),En="Conversations not available yet.",Eu="console",Zf="__posthogHandledLogsRequestError",Do=(t,e)=>{var n=t instanceof Error?t:new Error(e);return n[Zf]=!0,n},Su=t=>!!t&&typeof t=="object"&&t[Zf]===!0,Cs={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=vu,this.fa={},this.pa={},this.ga=[],this.ma=!1,this.ya=!1,this.ba=0,this._a=!1,this.wa=!1,this.ka=!1,this.xa=!1,this.Sa=0,this.Ca=()=>{var e=this.Ma();this.Sa=0,e&&this.reloadFeatureFlags()},"get"in t?this.Ta=t:(this.Ea=new qm(t.config,t.Qi()),this.Ta=this.Ea)}updateConfig(t,e){var n;(n=this.Ea)==null||n.update(t,e)}setup(t){return this.Ia=t,this.rt=t.logger.createLogger("[FeatureFlags]"),n=()=>{this.Ia===t&&(this.Ia=void 0,this.nn=t,this.Pa(t))},(e=t.kv.initialize())!=null&&e.then?e.then(n):n();var e,n}Pa(t){if(this.nn===t)return w&&ve(w,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){w?.removeEventListener("online",this.Ca)}dispose(){var t;this.ba++,this.wa=!1,this.Ia=void 0,this.nn&&(this.La(),(t=this.Ra)==null||t.dispose(),this.Ra=void 0,this.ga=[],w?.removeEventListener("online",this.Ca),this.nn=void 0)}get Ne(){return this.Ta.get()}Oa(t){var e;return(e=this.nn)==null?void 0:e.kv.get(t)}F(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.set(t)}))}q(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.remove(t)}))}Da(t){try{t()}catch(e){this.rt.error("Failed to update feature flag persistence",e)}}Fa(){var t={};for(var e of[Ti,$i,Pr,It]){var n=this.Oa(e);C(n)||(t[e]=n)}this.fa=t;var i=I({},t),r=this.Oa(Sn);if(r)for(var s of Object.entries(r))i["$feature/"+s[0]]=s[1];this.pa=i}Aa(){var t=this.Ne.cacheTtlMs;if(!t||0>=t)return!1;var e=this.Oa(ji);return typeof e!="number"||Date.now()-e>t}$a(){return!!this.Aa()&&(this.xa||this.ya||(this.xa=!0,this.rt.warn("Feature flag cache is stale, triggering refresh..."),this.reloadFeatureFlags()),!0)}Na(){var t=this.Ne.evaluationContexts;return t!=null&&t.length?t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid evaluation context found:",e,"Expected non-empty string"),n})):[]}qa(){var t=this.Ne.flagKeys;if(!C(t))return t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid flag key found:",e,"Expected non-empty string"),n}))}initialize(){var t,e,n=this.Ne,i=(t=(e=n.bootstrap)==null?void 0:e.featureFlags)!==null&&t!==void 0?t:{};if(Object.keys(i).length){var r,s,o=(r=(s=n.bootstrap)==null?void 0:s.featureFlagPayloads)!==null&&r!==void 0?r:{},a=Object.keys(i).filter((u=>!!i[u])).reduce(((u,c)=>(u[c]=i[c]||!1,u)),{}),l=Object.keys(o).filter((u=>a[u])).reduce(((u,c)=>(o[c]&&(u[c]=o[c]),u)),{});return this.ja({featureFlags:a,featureFlagPayloads:l})}}updateFlags(t,e,n){var i,r,s=n!=null&&n.merge&&(i=this.Oa(Sn))!==null&&i!==void 0?i:{},o=n!=null&&n.merge&&(r=this.Oa($i))!==null&&r!==void 0?r:{},a=I({},s,t),l=I({},o,e),u={};for(var c of Object.entries(a)){var d=c[0],f=c[1];u[d]={key:d,enabled:gc(f),variant:mc(f),reason:void 0,metadata:C(l?.[d])?void 0:{id:0,version:void 0,description:void 0,payload:l[d]}}}this.ja({flags:u})}get hasLoadedFlags(){return this.ma}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var t=this.Oa(aa),e=this.Oa(It),n=this.Oa(xn);if(!n&&!e)return t||{};var i=fe({},t||{}),r=[...new Set([...Object.keys(n||{}),...Object.keys(e||{})])];for(var s of r){var o,a,l=i[s],u=e?.[s],c=C(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=C(u)?l?.variant:typeof u=="string"?u:void 0,f=n?.[s],h=I({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(h.original_enabled=l?.enabled),d!==l?.variant&&(h.original_variant=l?.variant),f&&(h.metadata=I({},l?.metadata,{payload:f,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),i[s]=h}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:n,finalDetails:i}),this.ca=!0),i}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((n=>{var i=t[n];return{key:n,enabled:gc(i),variant:mc(i),payload:pc(e[n])}}))}getFlagVariants(){var t=this.Oa(Sn),e=this.Oa(It);if(!e)return t||{};for(var n=fe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:e,finalFlags:n}),this.ca=!0),n}getFlagPayloads(){var t=this.Oa($i),e=this.Oa(xn);if(!e)return t||{};for(var n=fe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flag payloads!",{flagPayloads:t,overriddenPayloads:e,finalPayloads:n}),this.ca=!0),n}reloadFeatureFlags(){this._a||this.Ne.featureFlagsDisabled||this.Ma()||this.Ba||(this.ga.slice().forEach((t=>{try{t()}catch(e){this.rt.error("Error while running feature flags reloading callback",e)}})),this.Ba=setTimeout((()=>{this.Ha()}),5))}La(){clearTimeout(this.Ba),this.Ba=void 0}onReloading(t){return this.ga.push(t),()=>{this.ga=this.ga.filter((e=>e!==t))}}ensureFlagsLoaded(){this.ma||this.ya||this.Ba||this.reloadFeatureFlags()}setAnonymousDistinctId(t){this.$anon_distinct_id=t}setReloadingPaused(t){this._a=t}resetFlagCallReported(){this.q(Cn)}Ha(t){this.La();var e=this.nn;if(e&&!this.Ne.remoteRequestsDisabled&&!this.Ma())if(this.ya)this.wa=!0;else{var n={token:e.projectToken,distinct_id:e.distinctId,groups:e.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:I({},e.initialPersonProperties,this.Oa(jt)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(In),timezone:Pf()};C(e.deviceId)||(n.$device_id=e.deviceId),(t!=null&&t.disableFlags||this.Ne.featureFlagsDisabled)&&(n.disable_flags=!0);var i=this.Na();i.length&&(n.evaluation_contexts=i);var r=this.qa();C(r)||(n.flag_keys=r);var s=this.Ne.onlyEvaluateSurveyFeatureFlags,o="/flags/?v=2"+(s?"&only_evaluate_survey_feature_flags=true":""),a=this.ba;this.ya=!0;var l=()=>{this.wa&&(this.wa=!1,this.Ha())},u=c=>{this.ya=!1,a===this.ba&&(this.F({[Tr]:[_u]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:n,compression:this.Ne.compression==="base64"?Ue.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,f,h=(d=c.json)!==null&&d!==void 0?d:{},p=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),p||this.wa||(this.$anon_distinct_id=void 0),!n.disable_flags||this.wa){this.ka=!p;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?_u:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),h.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((f=h.quotaLimited)==null||!f.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[Tr]:g}),m?this.rt.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more."):n.disable_flags||this.ja(h,p,{partialResponse:s}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return bf(this.Sa,3)}Ua(t){this.Sa=Ef(t,this.Sa,3,(()=>this.rt.warn("Feature flag requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped refreshing feature flags; will try again when connectivity changes.")))}getFeatureFlag(t,e){var n;if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var i=this.getFeatureFlagResult(t,e);return(n=i?.variant)!==null&&n!==void 0?n:i?.enabled}}else this.rt.warn('getFeatureFlag for key "'+t+Bo)}getFeatureFlagDetails(t){return this.getFlagsWithDetails()[t]}getFeatureFlagPayload(t){var e=this.getFeatureFlagResult(t,{send_event:!1});return e?.payload}getFeatureFlagResult(t,e){if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var n,i=this.getFlagVariants(),r=t in i,s=i[t],o=this.getFlagPayloads()[t],a=String(s),l=this.Oa(Pr)||void 0,u=this.Oa(ji)||void 0,c=this.Oa(Cn)||{};if(this.Ne.deduplicateCallsPerSession){var d,f=(d=this.nn)==null?void 0:d.session.sessionId,h=this.Oa(Li);f&&f!==h&&(c={},n=f)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))n&&this.F({[Cn]:c,[Li]:n});else{var p,g,m,v,E,S,_,b,k,T;U(c[t])?c[t].push(a):c[t]=[a],this.F(I({[Cn]:c},n?{[Li]:n}:{}));var x=this.getFeatureFlagDetails(t),F=[...(p=this.Oa(Tr))!==null&&p!==void 0?p:[]];C(s)&&F.push("flag_missing");var $={$feature_flag:t,$feature_flag_response:s,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((g=this.Ne.bootstrap)==null||(g=g.featureFlags)==null?void 0:g[t])||null,$feature_flag_bootstrapped_payload:((m=this.Ne.bootstrap)==null||(m=m.featureFlagPayloads)==null?void 0:m[t])||null,$used_bootstrap_value:!this.ka};C(x==null||(v=x.metadata)==null?void 0:v.has_experiment)||($.$feature_flag_has_experiment=x.metadata.has_experiment),C(x==null||(E=x.metadata)==null?void 0:E.version)||($.$feature_flag_version=x.metadata.version);var O,L=(S=x==null||(_=x.reason)==null?void 0:_.description)!==null&&S!==void 0?S:x==null||(b=x.reason)==null?void 0:b.code;L&&($.$feature_flag_reason=L),x!=null&&(k=x.metadata)!=null&&k.id&&($.$feature_flag_id=x.metadata.id),C(x?.original_variant)&&C(x?.original_enabled)||($.$feature_flag_original_response=C(x.original_variant)?x.original_enabled:x.original_variant),x!=null&&(T=x.metadata)!=null&&T.original_payload&&($.$feature_flag_original_payload=x==null||(O=x.metadata)==null?void 0:O.original_payload),F.length&&($.$feature_flag_error=F.join(",")),this.za($)}else n&&this.F({[Cn]:c,[Li]:n});if(r)return{key:t,enabled:!!s,variant:typeof s=="string"?s:void 0,payload:pc(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+Bo)}za(t){try{var e;(e=this.nn)==null||e.capture("$feature_flag_called",t).catch((n=>{this.rt.error("Failed to capture feature flag call",n)}))}catch(n){this.rt.error("Failed to capture feature flag call",n)}}getRemoteConfigPayload(t,e){this.Wa(t,e)}Wa(t,e){var n=this;return se((function*(){var i=n.nn;if(i){var r={distinct_id:i.distinctId,token:i.projectToken,person_properties:{$lib:i.library.name,$lib_version:i.library.version}},s=n.Na();s.length&&(r.evaluation_contexts=s);var o,a=n.qa();C(a)||(r.flag_keys=a);try{var l,u=(l=(yield i.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:r,compression:n.Ne.compression==="base64"?Ue.Base64:void 0,sentAt:"body",timeoutMs:n.Ne.requestTimeoutMs})).json)==null?void 0:l.featureFlagPayloads;o=u?.[t]||void 0}catch(c){return void n.rt.error("Remote config feature flag request failed",c)}try{e(o)}catch(c){n.rt.error("Remote config feature flag callback failed",c)}}}))()}isFeatureEnabled(t,e){if(e===void 0&&(e={}),e.fresh&&!this.ka)return e.defaultValue;if(!(this.ma||this.getFlags()&&this.getFlags().length>0))return this.rt.warn('isFeatureEnabled for key "'+t+Bo),e.defaultValue;var n=this.getFeatureFlag(t,e);return C(n)?e.defaultValue:!!n}addFeatureFlagsHandler(t){this.featureFlagEventHandlers.push(t)}removeFeatureFlagsHandler(t){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((e=>e!==t))}receivedFeatureFlags(t,e,n){this.ja(t,e,n)}ja(t,e,n){if(this.nn){this.ma=!0;var i=(function(r,s,o,a,l,u){s===void 0&&(s={}),o===void 0&&(o={}),a===void 0&&(a={}),u===void 0&&(u=vu);var c=((k,T)=>{var x=k.flags;return x?I({},k,{featureFlags:Object.fromEntries(Object.keys(x).map((F=>{var $;return[F,($=x[F].variant)!==null&&$!==void 0?$:x[F].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(x).filter((F=>x[F].enabled)).filter((F=>{var $;return($=x[F].metadata)==null?void 0:$.payload})).map((F=>{var $;return[F,($=x[F].metadata)==null?void 0:$.payload]})))}):(k.featureFlags&&T.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),k)})(r,u),d=c.flags,f=c.featureFlags,h=c.featureFlagPayloads;if(f){var p=r.requestId,g=r.evaluatedAt;if(U(f)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(f)for(var v=0;f.length>v;v++)m[f[v]]=!0;return{[Ti]:f,[Sn]:m,[Zr]:!1}}var E=f,S=h,_=d;if(l!=null&&l.partialResponse)E=I({},s,E),S=I({},o,S),_=I({},a,_);else if(r.errorsWhileComputingFlags)if(d){var b=new Set(Object.keys(d).filter((k=>{var T;return!((T=d[k])!=null&&T.failed)})));E=I({},s,Object.fromEntries(Object.entries(E).filter((k=>b.has(k[0]))))),S=I({},o,Object.fromEntries(Object.entries(S||{}).filter((k=>b.has(k[0]))))),_=I({},a,Object.fromEntries(Object.entries(_||{}).filter((k=>b.has(k[0])))))}else E=I({},s,E),S=I({},o,S),_=I({},a,_);return I({[Ti]:Object.keys(wu(E)),[Sn]:E||{},[$i]:S||{},[aa]:_||{},[Zr]:r.minimalFlagCalledEvents===!0},p?{[Pr]:p}:{},g?{[ji]:g}:{})}})(t,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),n,this.rt);i&&this.F(i),e||(this.xa=!1),this.Va(e)}}override(t,e){e===void 0&&(e=!1),this.rt.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:t,suppressWarning:e})}overrideFeatureFlags(t){this.Za(t)}Za(t){if(this.nn){if(t===!1)return this.q([It,xn]),this.Va(),void bn.info("All overrides cleared");if(U(t))return this.F({[It]:yu(t)}),this.Va(),void bn.info("Flag overrides set",{flags:t});if(t&&typeof t=="object"&&("flags"in t||"payloads"in t)){var e,n=t;this.ca=!!((e=n.suppressWarning)!==null&&e!==void 0&&e);var i={},r=n.flags,s=n.payloads;return r&&(i[It]=U(r)?yu(r):r),s&&(i[xn]=s),Object.keys(i).length&&this.F(i),r===!1&&s===!1?this.q([It,xn]):r===!1?this.q(It):s===!1&&this.q(xn),this.Va(),r===!1?bn.info("Flag overrides cleared"):r&&bn.info("Flag overrides set",{flags:r}),void(s===!1?bn.info("Payload overrides cleared"):s&&bn.info("Payload overrides set",{payloads:s}))}if(t&&typeof t=="object")return this.F({[It]:t}),this.Va(),void bn.info("Flag overrides set",{flags:t});this.rt.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:t})}else this.rt.warn("posthog.featureFlags.overrideFeatureFlags called before feature flags were ready")}onFeatureFlags(t){if(this.addFeatureFlagsHandler(t),this.ma){var e=this.Ga(),n=e.flags,i=e.flagVariants;try{t(n,i)}catch(r){this.rt.error("Error while running feature flags callback",r)}}return()=>this.removeFeatureFlagsHandler(t)}updateEarlyAccessFeatureEnrollment(t,e,n){var i=(this.Oa(Ar)||[]).find((l=>l.flagKey===t)),r={["$feature_enrollment/"+t]:e},s={$feature_flag:t,$feature_enrollment:e,$set:r};i&&(s.$early_access_feature_name=i.name),n&&(s.$feature_enrollment_stage=n);var o=I({},this.getFlagVariants(),{[t]:e});this.F({[Ti]:Object.keys(wu(o)),[Sn]:o,[jt]:I({},this.Oa(jt)||{},r)}),this.Va();try{var a;(a=this.nn)==null||a.capture("$feature_enrollment_update",s).catch((l=>{this.rt.error("Failed to capture early access feature enrollment",l)}))}catch(l){this.rt.error("Failed to capture early access feature enrollment",l)}}getEarlyAccessFeatures(t,e,n){e===void 0&&(e=!1);var i=this.Oa(Ar);!i||e?this.Qa(t,n):t(i)}Qa(t,e){var n=this;return se((function*(){var i=n.nn;if(i){var r,s=e?"&"+e.map((a=>"stage="+a)).join("&"):"";try{var o=yield i.sendRequest("/api/early_access_features/?token="+i.projectToken+s,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;n.F({[Ar]:r=o.json.earlyAccessFeatures})}catch(a){return void n.rt.error("Early access feature request failed",a)}try{t(r)}catch(a){n.rt.error("Early access feature callback failed",a)}}}))()}Ga(){var t=this.getFlags(),e=this.getFlagVariants();return{flags:t.filter((n=>e[n])),flagVariants:Object.keys(e).filter((n=>e[n])).reduce(((n,i)=>(n[i]=e[i],n)),{})}}Va(t){this.Fa();var e=this.Ga(),n=e.flags,i=e.flagVariants;this.featureFlagEventHandlers.forEach((r=>{try{r(n,i,{errorsLoading:t})}catch(s){this.rt.error("Error while running feature flags callback",s)}}))}setPersonPropertiesForFlags(t,e){e===void 0&&(e=!0),this.Ka(t,e)}Ka(t,e){e===void 0&&(e=!0);var n=this.Oa(jt)||{},i=t?.$set||(t!=null&&t.$set_once?{}:t),r=t?.$set_once,s={};if(r)for(var o in r)({}).hasOwnProperty.call(r,o)&&(o in n||(s[o]=r[o]));this.F({[jt]:I({},n,s,i)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=I({},this.Oa(jt)||{});t.forEach((i=>{delete n[i]})),this.F({[jt]:n}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(jt),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=this.Oa(In)||{},i=I({},n);for(var r of Object.keys(t))i[r]=I({},n[r],t[r]);this.F({[In]:i}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(In)||{};this.F({[In]:I({},e,{[t]:{}})})}else this.q(In)}reset(){this.ba++,this.wa=!1,this.Fa(),this.ma=!1,this._a=!1,this.ka=!1,this.$anon_distinct_id=void 0,this.La(),this.ca=!1,this.Sa=0}}},Gm={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===ki||this.Ya===Sr?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=uu,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(P==null||!P.visibilityState||P.visibilityState==="visible")return!0;var n=w==null||(e=w.performance)==null||e.getEntriesByType==null?void 0:e.getEntriesByType("visibility-state");return!(n!=null&&n.length)||n.some((i=>i.name==="visible"))})(),this.Ie=()=>{var e;P?.visibilityState==="visible"&&(this.io=!0,(e=this.Ja)==null||e.setDocumentWasEverVisible==null||e.setDocumentWasEverVisible(!0))},this._instance=t,!this._instance.sessionManager)throw Bt.error("started without valid sessionManager"),new Error(Ia+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===Wt)throw new Error(Ia+' cannot be used with cookieless_mode="always"');P!=null&&P.addEventListener&&ve(P,"visibilitychange",this.Ie)}initialize(){this.startIfEnabledOrStop()}dispose(){this.eo=!0,P==null||P.removeEventListener==null||P.removeEventListener("visibilitychange",this.Ie),this.stopRecording()}get ro(){var t,e=!((t=this._instance.get_property(An))==null||!t.enabled),n=!this.Ne.disable_session_recording,i=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return w&&e&&n&&!i}startIfEnabledOrStop(t){var e;if(!(this.eo||this.ro&&(e=this.Ja)!=null&&e.isStarted)){var n=!C(Object.assign)&&!C(Array.from);this.ro&&n?(this.no(t),Bt.info("starting")):(this.Ya=uu,this.stopRecording())}}no(t){var e,n,i;this.ro&&(this.Ya!==ki&&this.Ya!==Sr&&(this.Ya=du),B!=null&&(e=B.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(n=B.__PosthogExtensions__)!=null&&n.initSessionRecording?this.so(t):(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,this.ao,(r=>{if(r)return Bt.error("could not load recorder",r);this.so(t)})))}stopRecording(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.stop()}oo(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.discard()}lo(){var t,e;(t=this.Mr)==null||t.unregister(al),(e=this.Mr)==null||e.unregister(Jd)}uo(t,e){if(H(t))return null;var n,i=ke(t)?t:parseFloat(t);return typeof(n=i)!="number"||!Number.isFinite(n)||0>n||n>1?(Bt.warn(e+" must be between 0 and 1. Ignoring invalid value:",t),null):i}ho(t){if(this.Mr){var e,n,i=this.Mr,r=()=>{var s,o=t.sessionRecording===!1?void 0:t.sessionRecording,a=this.uo((s=this.Ne.session_recording)==null?void 0:s.sampleRate,"session_recording.sampleRate"),l=this.uo(o?.sampleRate,"remote config sampleRate"),u=a??l;H(u)&&this.lo();var c=o?.minimumDurationMilliseconds;i.register({[An]:I({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:I({capturePerformance:t.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:u,minimumDurationMilliseconds:C(c)?null:c,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers,version:o?.version,triggerGroups:o?.triggerGroups})})};r(),(e=this.Xa)==null||e.call(this),this.Xa=(n=this._instance.sessionManager)==null?void 0:n.onSessionId(r)}}onRemoteConfig(t){var e=t.ok?t.config:void 0;return e&&"sessionRecording"in e?e.sessionRecording===!1?(this.ho(e),void this.oo()):(this.ho(e),void this.startIfEnabledOrStop()):(this.Ya===ki&&(this.Ya=Sr,Bt.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(t,e){var n;e===void 0&&(e="log"),(n=this.Ja)!=null&&n.log?this.Ja.log(t,e):Bt.warn("log called before recorder was ready")}get ao(){var t,e,n=(t=this._instance)==null||(t=t.persistence)==null?void 0:t.get_property(An);return(n==null||(e=n.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(An);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(n){return Bt.warn("persisted remote config for session recording is invalid and will be ignored",n),!1}return!H(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,n,i;if(!this.eo){if((e=B.__PosthogExtensions__)==null||!e.initSessionRecording)return Bt.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[sf]:!0});var r;if(this.Ja||(this.Ja=(r=B.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===Sr||this.Ya===ki?void 0:(this.Ya=ki,Bt.info("persisted remote config is stale, requesting fresh config before starting"),void new Ff(this._instance).load());this.Ya=du,(n=(i=this.Ja).setDocumentWasEverVisible)==null||n.call(i,this.io),this.Ja.start(t)}}onRRwebEmit(t){var e;(e=this.Ja)==null||e.onRRwebEmit==null||e.onRRwebEmit(t)}overrideLinkedFlag(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Xd]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Zd]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,n;this.Ja||(n=this.Mr)==null||n.register({[t==="url"?Qd:ef]:!0}),(e=this.Ja)==null||e.overrideTrigger(t)}get sdkDebugProperties(){var t;return((t=this.Ja)==null?void 0:t.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(t,e){var n;return!((n=this.Ja)==null||!n.tryAddCustomEvent(t,e))}}},Km={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new au(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,n=he(this.instance.config.autocapture)?this.instance.config.autocapture:{};return n.url_allowlist=(t=n.url_allowlist)==null?void 0:t.map((i=>new RegExp(i))),n.url_ignorelist=(e=n.url_ignorelist)==null?void 0:e.map((i=>new RegExp(i))),n}yo(){if(this.isBrowserSupported()){if(w&&P){var t=n=>{n=n||w?.event;try{this.bo(n)}catch(i){Mo.error("Failed to capture event",i)}};if(ve(P,"submit",t,{capture:!0}),ve(P,"change",t,{capture:!0}),ve(P,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=n=>{n=n||w?.event;try{this.bo(n,$o)}catch(i){Mo.error("Failed to capture copy/cut event",i)}};ve(P,"copy",e,{capture:!0}),ve(P,"cut",e,{capture:!0})}}}else Mo.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.vo&&(this.yo(),this.vo=!0)}onRemoteConfig(t){if(this.fo=!0,t.ok){var e=t.config;e.elementsChainAsString&&(this.po=e.elementsChainAsString);var n=e.autocapture_opt_out;mt(n)&&(this.instance.persistence&&this.instance.persistence.register({[ea]:n}),this.co=n),this.startIfEnabled()}else this.startIfEnabled()}setElementSelectors(t){this.mo=t}getElementSelectors(t){var e,n=[];return(e=this.mo)==null||e.forEach((i=>{var r=P?.querySelectorAll(i);r?.forEach((s=>{t===s&&n.push(i)}))})),n}get isEnabled(){var t,e,n=(t=this.instance.persistence)==null?void 0:t.props[ea],i=this.co,r=this.instance.Qi()&&!this.fo;if(Ye(i)&&!mt(n)&&!r)return!1;var s=(e=this.co)!==null&&e!==void 0?e:!!n;return!!this.instance.config.autocapture&&!s}bo(t,e){if(e===void 0&&(e="$autocapture"),this.isEnabled){var n,i=bo(t);uf(i)&&(i=i.parentNode||null),e==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&this.instance.config.rageclick&&(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,t.timeStamp||new Date().getTime())&&Oc(i,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var r=e===$o;if(i&&(function(d,f,h,p,g,m){var v;if(!w||fl(d)||h!=null&&h.url_allowlist&&!Mc(h.url_allowlist,m)||h!=null&&h.url_ignorelist&&Mc(h.url_ignorelist,m))return!1;if(h!=null&&h.dom_event_allowlist){var E=h.dom_event_allowlist;if(E&&!E.some((x=>f.type===x)))return!1}var S=mf(d,p),_=S.parentIsUsefulElement,b=S.targetElementList;if(!(function(x,F){var $=F?.element_allowlist;if(C($))return!0;var O,L=function(K){if($.some((V=>K.tagName.toLowerCase()===V)))return{v:!0}};for(var N of x)if(O=L(N))return O.v;return!1})(b,h)||!ma(b,h?.css_selector_allowlist)||ma(b,(v=h?.css_selector_ignorelist)!==null&&v!==void 0?v:qg))return!1;try{var k=w.getComputedStyle(d);if(k&&k.getPropertyValue("cursor")==="pointer"&&f.type==="click")return!0}catch{}var T=d.tagName.toLowerCase();switch(T){case"html":return!1;case"form":return(g||["submit"]).indexOf(f.type)>=0;case"input":case"select":case"textarea":return(g||["change","click"]).indexOf(f.type)>=0;default:return _?(g||["click"]).indexOf(f.type)>=0:(g||["click"]).indexOf(f.type)>=0&&(dl.indexOf(T)>-1||d.getAttribute("contenteditable")==="true")}})(i,t,this.Ne,r,r?["copy","cut"]:void 0,this.instance)){var s=Om(i,{e:t,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.Ne.element_attribute_ignorelist,elementsChainAsString:this.po,disableCaptureUrlHashes:this.instance.config.disable_capture_url_hashes}),o=s.props;if(s.explicitNoCapture)return!1;var a=this.getElementSelectors(i);if(a&&a.length>0&&(o.$element_selectors=a),e===$o){var l,u=hf(w==null||(l=w.getSelection())==null?void 0:l.toString()),c=t.type||"clipboard";if(!u)return!1;o.$selected_content=u,o.$copy_type=c}return this.instance.capture(e,o),!0}}}isBrowserSupported(){return je(P?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(w==null||(e=w.location)==null?void 0:e.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(A.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.wo&&this.wo(),this.wo=void 0,A.info("History API monitoring stopped")}monitorHistoryChanges(){w&&w.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(w&&((e=w.history[t])==null||!e.__posthog_wrapped__)){var n=this;(function(i,r,s){try{if(!(r in i))return lu;var o={next:i[r]},a=s((function(){for(var l=arguments.length,u=new Array(l),c=0;l>c;c++)u[c]=arguments[c];return o.next.apply(this,u)}));return je(a)&&(a.prototype=a.prototype||{},Object.defineProperties(a,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:o}})),i[r]=a,()=>{if(i[r]!==a)for(var l=i[r];je(l)&&l.__posthog_layer__;){var u=l.__posthog_layer__;if(u.next===a)return void(u.next=o.next);l=u.next}else i[r]=o.next}}catch{return lu}})(w.history,t,(i=>function(r,s,o){i.call(this,r,s,o),n.So(t)}))}}So(t){try{var e,n=w==null||(e=w.location)==null?void 0:e.pathname;if(!n)return;n!==this._o&&this.isEnabled&&this._instance.capture(Vn,{navigation_type:t}),this._o=n}catch(i){A.error("Error capturing "+t+" pageview",i)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};ve(w,"popstate",t),this.wo=()=>{w&&w.removeEventListener("popstate",t)}}}},heatmaps:class{get Ne(){return this.instance.config}constructor(t){var e;this.Co=!1,this.vo=!1,this.Mo=null,this.instance=t,this.Co=!((e=this.instance.persistence)==null||!e.props[ta]),this.rageclicks=new au(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return he(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return H(this.Ne.capture_heatmaps)?H(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;Dm.info("starting..."),this.To(),this.Ie()}else{var t;clearInterval((t=this.Mo)!==null&&t!==void 0?t:void 0),this.Eo(),this.getAndClearBuffer()}}onRemoteConfig(t){if(t.ok){var e=t.config;if("heatmaps"in e){var n=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[ta]:n}),this.Co=n,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){No(t.originalEvent)&&this.ke(t.originalEvent,"deadclick")}Ie(){this.Mo&&clearInterval(this.Mo),this.Mo=P?.visibilityState==="visible"?setInterval(this.cr.bind(this),this.flushIntervalMilliseconds):null}To(){w&&P&&(this.Po=this.cr.bind(this),ve(w,ns,this.Po),this.Ro=t=>this.ke(t||w?.event),ve(P,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||w?.event),ve(P,"mousemove",this.Ao,{capture:!0}),this.Lo=new zc(this.instance,Xg,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),ve(P,ts,this.Oo),this.vo=!0)}Eo(){var t;w&&P&&(this.Po&&w.removeEventListener(ns,this.Po),this.Ro&&P.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&P.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&P.removeEventListener(ts,this.Oo),clearTimeout(this.Do),(t=this.Lo)==null||t.stop(),this.vo=!1)}$o(t,e){var n=this.instance.scrollManager.scrollY(),i=this.instance.scrollManager.scrollX(),r=this.instance.scrollManager.scrollElement(),s=(function(o,a,l){for(var u=o;u&&hn(u)&&!et(u,"body");){if(u===l)return!1;var c=void 0;try{var d,f,h;c=(d=(f=(h=u.ownerDocument)==null?void 0:h.defaultView)!==null&&f!==void 0?f:w)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(j(a,c))return!0;u=pf(u)}return!1})(bo(t),["fixed","sticky"],r);return{x:t.clientX+(s?0:i),y:t.clientY+(s?0:n),target_fixed:s,type:e}}ke(t,e){var n;if(e===void 0&&(e="click"),!$c(t.target)&&No(t)){var i=this.$o(t,e);(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,new Date().getTime())&&Oc(bo(t),this.instance.config.rageclick)&&this.Vt(I({},i,{type:"rageclick"})),this.Vt(i)}}Fo(t){!$c(t.target)&&No(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(w){var e=this.Ne.disable_capture_url_hashes?fn(w.location.href):w.location.href,n=this.Ne.custom_personal_data_properties,i=this.Ne.mask_personal_data_properties?[...ri,...n||[]]:[],r=Zi(e,i,Xi);this.R=this.R||{},this.R[r]||(this.R[r]=[]),this.R[r].push(t)}}cr(){this.R&&!Kt(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:zc,webVitalsAutocapture:class{constructor(t){var e;this.Co=!1,this.vo=!1,this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this.No=()=>{clearTimeout(this.qo),this.qo=void 0,this.R.metrics.length!==0&&(this._instance.capture("$web_vitals",I({$current_url:this.R.url},this.R.metrics.reduce(((n,i)=>I({},n,{["$web_vitals_"+i.name+"_event"]:I({},i),["$web_vitals_"+i.name+"_value"]:i.value})),{}))),this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.jo=n=>{var i;if(this.R=this.R||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},H(n?.name)||H(n?.value))wn.error("Invalid metric received",n);else{var r=typeof n.navigationURL=="string"?n.navigationURL:void 0,s=this.Bo(r);if(!C(s)){var o=ke(n.navigationId)||typeof n.navigationId=="string"?"navigation:"+n.navigationId:"url:"+s;if(!this.Ho||this.Ho>n.value){this.R.navigationKey!==o&&(this.No(),this.qo=setTimeout(this.No,this.flushToCaptureTimeoutMs)),C(this.R.navigationKey)&&(this.R.navigationKey=o,this.R.url=s),this.R.firstMetricTimestamp=C(this.R.firstMetricTimestamp)?Date.now():this.R.firstMetricTimestamp,n.attribution&&n.attribution.interactionTargetElement&&(n.attribution.interactionTargetElement=void 0);var a=(i=this._instance.sessionManager)==null?void 0:i.checkAndGetSessionAndWindowId(!0),l=I({},n,r?{navigationURL:s}:{},{$current_url:s,timestamp:Date.now()});C(a)||(l.$session_id=a.sessionId,l.$window_id=a.windowId),this.R.metrics.push(l),this.R.metrics.length===this.allowedMetrics.length&&this.No()}else wn.error("Ignoring metric with value >= "+this.Ho,n)}}},this.Uo=()=>{if(!this.vo){var n,i,r,s,o=B.__PosthogExtensions__,a=o?.postHogWebVitalsCallbacksByFlavor,l=a?.[this.zo]||(this.zo==="web-vitals"&&C(a)?o?.postHogWebVitalsCallbacks:void 0);if(C(l)||(n=l.onLCP,i=l.onCLS,r=l.onFCP,s=l.onINP),n&&i&&r&&s){var u={reportSoftNavs:this.useSoftNavs};this.allowedMetrics.indexOf("LCP")>-1&&n(this.jo.bind(this),u),this.allowedMetrics.indexOf("CLS")>-1&&i(this.jo.bind(this),u),this.allowedMetrics.indexOf("FCP")>-1&&r(this.jo.bind(this),u),this.allowedMetrics.indexOf("INP")>-1&&s(this.jo.bind(this),u),this.vo=!0}else wn.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[sa]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,n=he(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return H(n)?((e=this._instance.persistence)==null?void 0:e.props[oa])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(he(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=he(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=he(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=he(this.Wo)&&ke(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:cu;return t>0&&6e4>=t?cu:t}get isEnabled(){var t=me?.protocol;if(t!=="http:"&&t!=="https:")return wn.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=he(this.Wo)?this.Wo.web_vitals:mt(this.Wo)?this.Wo:void 0;return mt(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(wn.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var n=he(e.capturePerformance)&&!!e.capturePerformance.web_vitals,i=he(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[sa]:n}),this._instance.persistence.register({[oa]:i})),this.Co=n,this.startIfEnabled()}}}get zo(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}ai(t){var e=B.__PosthogExtensions__,n=this.zo,i=e?.postHogWebVitalsCallbacksByFlavor;i!=null&&i[n]||n==="web-vitals"&&C(i)&&e!=null&&e.postHogWebVitalsCallbacks?t():e==null||e.loadExternalDependency==null||e.loadExternalDependency(this._instance,n,(r=>{r?wn.error("failed to load script",r):t()}))}Bo(t){var e=t||w?.location.href;if(e){var n=this._instance.config.disable_capture_url_hashes?fn(e):e,i=this._instance.config.custom_personal_data_properties,r=this._instance.config.mask_personal_data_properties?[...ri,...i||[]]:[];return Zi(n,r,Xi)}wn.error("Could not determine current URL")}}},Ym={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var n;if(w&&this.isEnabled&&(n=B.__PosthogExtensions__)!=null&&n.errorWrappingFunctions){var i=B.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,r=B.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,s=B.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.Vo&&this.Ne.capture_unhandled_errors&&(this.Vo=i(this.captureException.bind(this))),!this.Zo&&this.Ne.capture_unhandled_rejections&&(this.Zo=r(this.captureException.bind(this))),!this.Go&&this.Ne.capture_console_errors&&(this.Go=s(this.captureException.bind(this)))}catch(o){Ii.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[na]),this.Jo=new Gp(I({},(function(n){var i,r,s,o;return n===void 0&&(n={}),{refillRate:(i=(r=n.exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:n.__exceptionRateLimiterRefillRate)!==null&&i!==void 0?i:1,bucketSize:(s=(o=n.exceptionRateLimiterBucketSize)!==null&&o!==void 0?o:n.__exceptionRateLimiterBucketSize)!==null&&s!==void 0?s:10}})(this._instance.config.error_tracking),{refillInterval:1e4,rt:Ii})),this.Ne=this.Yo(),this.startIfEnabledOrStop()}Yo(){var t=this._instance.config.capture_exceptions,e={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return he(t)?e=I({},e,t):(C(t)?this.Ko:t)&&(e=I({},e,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),e}get isEnabled(){return this.Ne.capture_console_errors||this.Ne.capture_unhandled_errors||this.Ne.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(Ii.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",(i=>{if(i)return Ii.error("failed to load script",i);t()}))}Qo(){var t,e,n;(t=this.Vo)==null||t.call(this),this.Vo=void 0,(e=this.Zo)==null||e.call(this),this.Zo=void 0,(n=this.Go)==null||n.call(this),this.Go=void 0}onRemoteConfig(t){if(t.ok){var e=t.config;"autocaptureExceptions"in e&&(this.Ko=!!e.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[na]:this.Ko}),this.Ne=this.Yo(),this.startIfEnabledOrStop())}}onConfigChange(){this.Ne=this.Yo()}captureException(t){var e,n,i,r=(e=t==null||(n=t.$exception_list)==null||(n=n[0])==null?void 0:n.type)!==null&&e!==void 0?e:"Exception";this.Jo.consumeRateLimit(r)?Ii.info("Skipping exception capture because of client rate limiting.",{exception:r}):(i=this._instance.exceptions)==null||i.sendExceptionEvent(t)}},exceptions:class{constructor(t){var e,n;this.Xo=[],this.tl=new ug([new _g,new Cg,new wg,new yg,new Ig,new xg,new Eg,new kg],(function(i){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;r>o;o++)s[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` -`),d=l;c.length>d;d++){var f=c[d];if(1024>=f.length){var h=Pc.test(f)?f.replace(Pc,"$1"):f;if(!h.match(/\S*Error: /)){for(var p of s){var g=p(h,i);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var v=Array.from(m);return v.reverse(),v.slice(0,50).map((E=>{return I({},E,{filename:E.filename||(S=v,S[S.length-1]||{}).filename,function:E.function||ni});var S}))})(u)}})("web:javascript",pg,vg)),this._instance=t,this.Xo=(e=(n=this._instance.persistence)==null?void 0:n.get_property(ia))!==null&&e!==void 0?e:[],this.el=Jr(this.il()),this.rl=new Pg(this.el)}onConfigChange(){this.el=Jr(this.il()),this.rl.setConfig(this.el)}onRemoteConfig(t){var e,n,i;if(t.ok){var r=t.config;if("errorTracking"in r){var s=(e=(n=r.errorTracking)==null?void 0:n.suppressionRules)!==null&&e!==void 0?e:[],o=(i=r.errorTracking)==null?void 0:i.captureExtensionExceptions;this.Xo=s,this._instance.persistence&&this._instance.persistence.register({[ia]:this.Xo,[ra]:o})}}}get nl(){var t,e=!!this._instance.get_property(ra),n=this._instance.config.error_tracking.captureExtensionExceptions;return(t=n??e)!==null&&t!==void 0&&t}buildProperties(t,e){return this.tl.buildFromUnknown(t,{syntheticException:e?.syntheticException,mechanism:{handled:e?.handled}})}addExceptionStep(t,e){if(this.el.enabled)try{if(!X(t)||t.trim().length===0)return void St.warn("Ignoring exception step because message must be a non-empty string");var n=(function(s){if(!s)return{sanitizedProperties:{},droppedKeys:[]};var o=[];return{sanitizedProperties:Object.keys(s).reduce(((a,l)=>Ag.has(l)?(o.push(l),a):(a[l]=s[l],a)),{}),droppedKeys:o}})(this.sl(e)),i=n.sanitizedProperties,r=n.droppedKeys;r.length>0&&St.warn("Ignoring reserved exception step fields",{droppedKeys:r}),this.rl.add(I({[Kr]:t,[Yr]:new Date().toISOString()},i))}catch(s){St.error("Failed to add exception step. Ignoring breadcrumb.",s)}}sendExceptionEvent(t){try{var e=t.$exception_list;if(this.al(e)){if(this.ol(e))return this.ll("Exception dropped: matched a suppression rule"),void St.info("Skipping exception capture because a suppression rule matched");if(!this.nl&&this.ul(e))return this.ll("Exception dropped: thrown by a browser extension"),void St.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.hl(e))return this.ll("Exception dropped: thrown by the PostHog SDK"),void St.info("Skipping exception capture because it was thrown by the PostHog SDK")}var n=this.el.enabled&&H(t.$exception_steps)?this.dl(t):t,i=typeof(s=globalThis._posthogReleaseId)=="string"&&s.length>0?s:void 0;i&&(n.$release_id=i);try{var r=this._instance.capture("$exception",n,{_noTruncate:!0,_batchKey:"exceptionEvent",Wn:!0});return r&&this.rl.clear(),r}catch(o){return St.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void St.error("Failed to process exception event. Ignoring this exception.",o)}var s}dl(t){try{var e=this.rl.getAttachable();return e.length===0?t:I({},t,{$exception_steps:e})}catch(n){return St.error("Failed to read buffered exception steps. Capturing exception without steps.",n),t}}ll(t){this.el.enabled&&this.rl.add({[Kr]:t,[Yr]:new Date().toISOString()})}sl(t){return he(t)?I({},t):{}}il(){var t,e;return(t=(e=this._instance.config.error_tracking)==null?void 0:e.exception_steps)!==null&&t!==void 0?t:{}}ol(t){if(t.length===0)return!1;try{var e=t.reduce(((n,i)=>{var r=i.type,s=i.value;return X(r)&&r.length>0&&n.$exception_types.push(r),X(s)&&s.length>0&&n.$exception_values.push(s),n}),{$exception_types:[],$exception_values:[]});return this.Xo.some((n=>{var i=n.values.map((r=>{var s=zf[r.operator],o=e[r.key];if(!s||!o)return!1;var a=U(r.value)?r.value:[r.value];return a.length>0&&s(a,o)}));return n.type==="OR"?i.some(Boolean):i.every(Boolean)}))}catch(n){return St.warn("Failed to evaluate suppression rules. Capturing the exception.",n),!1}}ul(t){return t.flatMap((e=>{var n,i;return(n=(i=e.stacktrace)==null?void 0:i.frames)!==null&&n!==void 0?n:[]})).some((e=>e.filename&&e.filename.startsWith("chrome-extension://")))}hl(t){if(t.length>0){var e,n,i,r,s=(e=(n=t[0].stacktrace)==null?void 0:n.frames)!==null&&e!==void 0?e:[],o=s[s.length-1];return(i=o==null||(r=o.filename)==null?void 0:r.includes("posthog.com/static"))!==null&&i!==void 0&&i}return!1}al(t){return!H(t)&&U(t)}}},Jm=I({productTours:class{get Mr(){return this._instance.persistence}constructor(t){this.vl=null,this.cl=null,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(t.ok){var e=t.config;if("productTours"in e){var n,i;if(this.Mr&&this.Mr.register({[ol]:!!e.productTours}),!Oo(this._instance))return!this.vl&&H((n=this.Mr)==null?void 0:n.props[Mi])||xr.info("product tours disabled; stopping and clearing cached tours"),(i=this.vl)==null||i.stop(),this.vl=null,void this.clearCache();this.loadIfEnabled()}}}loadIfEnabled(){!this.vl&&Oo(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.generateProductTours?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",(i=>{i?xr.error("Could not load product tours script",i):t()}))}fl(){var t;!this.vl&&(t=B.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=B.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(t,e){if(e===void 0&&(e=!1),!U(this.cl)||e){var n=this.Mr;if(n){var i=n.props[Mi];if(U(i)&&!e)return this.cl=i,void t(i,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",timestampMode:"query",callback:r=>{if(Oo(this._instance)){var s=r.statusCode;if(s!==200||!r.json){var o="Product Tours API could not be loaded, status: "+s;return s===0?r.error||xr.warn(o):xr.error(o),void t([],{isLoaded:!1,error:o})}var a=U(r.json.product_tours)?r.json.product_tours:[];this.cl=a,n&&n.register({[Mi]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){H(this.vl)?t([],{isLoaded:!1,error:"Product tours not loaded"}):this.vl.getActiveProductTours(t)}showProductTour(t){var e;(e=this.vl)==null||e.showTourById(t)}previewTour(t){this.vl?this.vl.previewTour(t):this.ai((()=>{var e;this.fl(),(e=this.vl)==null||e.previewTour(t)}))}dismissProductTour(){var t;(t=this.vl)==null||t.dismissTour("user_clicked_skip")}nextStep(){var t;(t=this.vl)==null||t.nextStep()}previousStep(){var t;(t=this.vl)==null||t.previousStep()}clearCache(){var t;this.cl=null,(t=this.Mr)==null||t.unregister(Mi)}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)}}},Cs),Zm={siteApps:class{constructor(t){this.pl=0,this._instance=t,this.gl=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}ml(t,e){if(e){var n=this.globalsForEvent(e);this.gl.push(n),this.gl.length>1e3&&(this.gl=this.gl.slice(10))}}get siteAppLoaders(){var t;return(t=B._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,n,i,r,s,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var f=d[0];l[f]={id:u[f],type:f,properties:d[1]}}var h=t.$set_once,p=t.$set;return{event:I({},pd(t,jm),{properties:I({},t.properties,p?{$set:I({},(e=(n=t.properties)==null?void 0:n.$set)!==null&&e!==void 0?e:{},p)}:{},h?{$set_once:I({},(i=(r=t.properties)==null?void 0:r.$set_once)!==null&&i!==void 0?i:{},h)}:{}),elements_chain:(s=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&s!==void 0?s:"",distinct_id:(a=t.properties)==null?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}bl(t){var e,n=(e=t.tagName)==null?void 0:e.toLowerCase();return n==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(Et.error("prepare_external_dependency_stylesheet returned null"),null):n==="script"&&this._instance.config.prepare_external_dependency_script?this._instance.config.prepare_external_dependency_script(t)||(Et.error("prepare_external_dependency_script returned null"),null):t}_l(){var t,e,n,i,r,s,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=P?.defaultView,u=l==null||(t=l.Node)==null?void 0:t.prototype;if(!l||!u)return()=>{};if(this.pl++,this.wl)return this.kl();var c=[],d=this,f=new WeakSet,h=(m,v,E)=>{if(m!=null&&m[v]){var S=m[v];m[v]=E(S),c.push((()=>{m[v]=S}))}},p=m=>{if(f.has(m))return m;var v=d.bl(m);return v&&f.add(v),v},g=m=>m.map((v=>typeof v=="string"?v:p(v))).filter((v=>!Ye(v)));return h(u,"appendChild",(m=>function(v){var E=p(v);return E?m.call(this,E):v})),h(u,"insertBefore",(m=>function(v,E){var S=p(v);return S?m.call(this,S,E):v})),h(u,"replaceChild",(m=>function(v,E){var S=p(v);return S?m.call(this,S,E):E})),[(e=l.Element)==null?void 0:e.prototype,(n=l.Document)==null?void 0:n.prototype,(i=l.DocumentFragment)==null?void 0:i.prototype].forEach((m=>{h(m,"append",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),h(m,"prepend",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))}))})),[(r=l.Element)==null?void 0:r.prototype,(s=l.CharacterData)==null?void 0:s.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((m=>{h(m,"before",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),h(m,"after",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),h(m,"replaceWith",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];var b=g(S);return S.length&&!b.length?void 0:v.apply(this,b)}))})),h((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(v,E){var S=p(E);return S?m.call(this,v,S):null})),this.wl=()=>{c.forEach((m=>m())),this.wl=void 0},this.kl()}kl(){var t=!1;return()=>{var e;t||(t=!0,this.pl--,this.pl===0&&((e=this.wl)==null||e.call(this)))}}xl(t,e){e===void 0&&(e=!0);var n=this._l();try{var i=t(n);return e&&n(),i}catch(r){throw n(),r}}setupSiteApp(t){var e=this.apps[t.id],n=()=>{var o;!e.errored&&this.gl.length&&(Et.info("Processing "+this.gl.length+" events for site app with id "+t.id),this.gl.forEach((a=>this.xl((()=>e.processEvent==null?void 0:e.processEvent(a))))),e.processedBuffer=!0),Object.values(this.apps).every((a=>a.processedBuffer||a.errored))&&((o=this.yl)==null||o.call(this))},i=!1,r=o=>{e.errored=!o,e.loaded=!0,Et.info("Site app with id "+t.id+" "+(o?"loaded":"errored")),i&&n()};try{var s=this.xl((o=>t.init({posthog:this._instance,callback(a){o(),r(a)}})),!1).processEvent;s&&(e.processEvent=s),i=!0}catch(o){Et.error(fu+t.id,o),r(!1)}if(i&&e.loaded)try{n()}catch(o){Et.error("Error while processing buffered events PostHog app with config id "+t.id,o),e.errored=!0}}Sl(){var t=this.siteAppLoaders||[];for(var e of t)this.apps[e.id]={id:e.id,loaded:!1,errored:!1,processedBuffer:!1};for(var n of t)this.setupSiteApp(n)}Cl(t){var e=this;if(Object.keys(this.apps).length!==0){var n=this.globalsForEvent(t),i=function(s){try{e.xl((()=>s.processEvent==null?void 0:s.processEvent(n)))}catch(o){Et.error("Error while processing event "+t.event+" for site app "+s.id,o)}};for(var r of Object.values(this.apps))i(r)}}onRemoteConfig(t){var e,n,i,r=this;if((e=this.siteAppLoaders)!=null&&e.length)return this.isEnabled?(this.Sl(),void this._instance.on("eventCaptured",(l=>this.Cl(l)))):void Et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((n=this.yl)==null||n.call(this),t.ok){var s=t.config;if((i=s.siteApps)!=null&&i.length)if(this.isEnabled){var o=function(){var l,u=a.id,c=a.url;B["__$$ph_site_app_"+u]=r._instance,(l=B.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(r._instance,c,(d=>{if(d)return Et.error(fu+u,d)}))};for(var a of s.siteApps)o()}else Et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},Xm={tracingHeaders:class{constructor(t){this.Ml=void 0,this.Tl=void 0,this.El=void 0,this.Uo=()=>{var e,n,i=this.Il();i?(C(this.Ml)&&(this.Ml=(e=B.__PosthogExtensions__)==null||(e=e.tracingHeadersPatchFns)==null?void 0:e._patchXHR(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager)),C(this.Tl)&&(this.Tl=(n=B.__PosthogExtensions__)==null||(n=n.tracingHeadersPatchFns)==null?void 0:n._patchFetch(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager))):this.Qo()},this._instance=t}initialize(){this.startIfEnabledOrStop()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",(i=>{if(i)return Bm.error("failed to load script",i);t()}))}Pl(){var t,e;return(t=(e=this._instance.config.tracing_headers)!==null&&e!==void 0?e:this._instance.config.addTracingHeaders)!==null&&t!==void 0?t:this._instance.config.__add_tracing_headers}Il(){var t=this.Pl();return U(t)?(U(this.El)?this.El.splice(0,this.El.length,...t):this.El=[...t],t.length>0?this.El:void 0):(U(this.El)&&this.El.splice(0),this.El=t||void 0,this.El)}Qo(){var t,e;(t=this.Ml)==null||t.call(this),(e=this.Tl)==null||e.call(this),this.Ml=void 0,this.Tl=void 0}startIfEnabledOrStop(){this.Il()?this.ai(this.Uo):this.Qo()}}},Qm=I({surveys:class{get Ne(){return this._instance.config}constructor(t){this.Rl=void 0,this._surveyManager=null,this.Al=!1,this.Fl=[],this.Ll=null,this.Ol=null,this._instance=t,this._surveyEventReceiver=null}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this.Ne.disable_surveys){if(!t.ok)return Q.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(H(e))return Q.warn("Flags not loaded yet. Not loading surveys.");var n=U(e);this.Rl=n?e.length>0:e,Q.info("flags response received, isSurveysEnabled: "+this.Rl),this.loadIfEnabled()}}reset(){try{var t;(t=this._surveyEventReceiver)==null||t.reset(),localStorage.removeItem("lastSeenSurveyDate");for(var e=[],n=0;nlocalStorage.removeItem(r)))}catch{}}loadIfEnabled(){if(!this._surveyManager)if(this.Al)Q.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)Q.info(hu);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())Q.info("Not loading surveys in cookieless mode without consent.");else{var t=B?.__PosthogExtensions__;if(t){if(!C(this.Rl)||this.Ne.advanced_enable_surveys){var e=this.Rl||this.Ne.advanced_enable_surveys;this.Al=!0;try{var n=t.generateSurveys;if(n)return void this.Dl(n,e);var i=t.loadExternalDependency;if(!i)return void this.$l(ll);i(this._instance,"surveys",(r=>{r||!t.generateSurveys?this.$l("Could not load surveys script",r):this.Dl(t.generateSurveys,e)}))}catch(r){throw this.$l("Error initializing surveys",r),r}finally{this.Al=!1}}}else Q.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new Wm(this._instance),Q.info("Surveys loaded successfully"),this.Nl({isLoaded:!0})}$l(t,e){Q.error(t,e),this.Nl({isLoaded:!1,error:t})}onSurveysLoaded(t){return this.Fl.push(t),this._surveyManager&&this.Nl({isLoaded:!0}),()=>{this.Fl=this.Fl.filter((e=>e!==t))}}getSurveys(t,e){if(e===void 0&&(e=!1),this.Ne.disable_surveys)return Q.info(hu),t([]);var n,i=this._instance.get_property(la);if(i&&!e)return t(i,{isLoaded:!0}),void(this.ql()&&this.getSurveys((()=>{}),!0));typeof Promise<"u"&&this.Ll?this.Ll.then((r=>t(r.surveys,r.context))):(typeof Promise<"u"&&(this.Ll=new Promise((r=>{n=r}))),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this.Ne.token),method:"GET",timestampMode:"query",timeout:this.Ne.surveys_request_timeout_ms,callback:r=>{var s;this.Ll=null;var o=r.statusCode;if(o!==200||!r.json){var a="Surveys API could not be loaded, status: "+o;o!==0?Q.error(a):r.error||Q.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(n==null||n({surveys:[],context:l}))}this.Ol=null;var u,c=r.json.surveys||[],d=c.filter((h=>(function(p){return!(!p.start_date||p.end_date)})(h)&&(Vf(h)||(function(p){var g;return!((g=p.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(h))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(s=this._instance.persistence)==null||s.register({[la]:c,[Xr]:Date.now()});var f={isLoaded:!0};t(c,f),n?.({surveys:c,context:f})}}))}ql(){return this.jl()&&!this.Ll&&!this.Bl()}jl(){var t=this._instance.get_property(Xr);return ke(t)&&Date.now()-t>3e5}Bl(){return ke(this.Ol)&&3e5>Date.now()-this.Ol}markSurveyAsSeen(t,e){var n,i={id:t,current_iteration:(n=e?.iteration)!==null&&n!==void 0?n:null};Kf(i);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}}Nl(t){for(var e of this.Fl)try{if(!t.isLoaded)return e([],t);this.getSurveys(e)}catch(n){Q.error("Error in survey callback",n)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!H(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);Q.warn("init was not called")}Hl(t){var e=null;return this.getSurveys((n=>{var i;e=(i=n.find((r=>r.id===t)))!==null&&i!==void 0?i:null})),e}Ul(t){if(H(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(H(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(H(this._surveyManager))return Q.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 H(this._surveyManager)?(Q.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Ir})):new Promise((n=>{this.getSurveys((i=>{var r,s=(r=i.find((a=>a.id===t)))!==null&&r!==void 0?r:null;if(s){var o=this.zl(s);n({visible:o.eligible,disabledReason:o.reason})}else n({visible:!1,disabledReason:"Survey not found"})}),e)}))}renderSurvey(t,e,n){var i;if(H(this._surveyManager))Q.warn("init was not called");else{var r=typeof t=="string"?this.Hl(t):t;if(r!=null&&r.id)if(Im.includes(r.type)){var s=P?.querySelector(e);if(s)return(i=r.appearance)!=null&&i.surveyPopupDelaySeconds?(Q.info("Rendering survey "+r.id+" with delay of "+r.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;Q.info("Rendering survey "+r.id+" with delay of "+((o=r.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(a=this._surveyManager)==null||a.renderSurvey(r,s,n),Q.info("Survey "+r.id+" rendered")}),1e3*r.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(r,s,n);Q.warn("Survey element not found")}else Q.warn("Surveys of type "+r.type+" cannot be rendered in the app");else Q.warn("Survey not found")}}displaySurvey(t,e){var n;if(H(this._surveyManager))Q.warn("init was not called");else{var i=this.Hl(t);if(i){var r=i;if((n=i.appearance)!=null&&n.surveyPopupDelaySeconds&&e.ignoreDelay&&(r=I({},i,{appearance:I({},i.appearance,{surveyPopupDelaySeconds:0})})),e.displayType!==_a.Popover&&e.initialResponses&&Q.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),e.ignoreConditions===!1){var s=this.Ul(i);if(!s.eligible)return void Q.warn("Survey is not eligible to be displayed: ",s.reason)}e.displayType!==_a.Inline?this._surveyManager.handlePopoverSurvey(r,e):this.renderSurvey(r,e.selector,e.properties)}else Q.warn("Survey not found")}}cancelPendingSurvey(t){H(this._surveyManager)?Q.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},Cs),ev={toolbar:class{constructor(t){this.instance=t}Wl(t){B.ph_toolbar_state=t}Vl(){var t;return(t=B.ph_toolbar_state)!==null&&t!==void 0?t:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(t,e,n){if(t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),ga(this.instance.config)||!w||!P)return!1;t=t??w.location,n=n??w.history;try{if(!e){try{w.localStorage.setItem("test","test"),w.localStorage.removeItem("test")}catch{return!1}e=w?.localStorage}var i,r=zm||os(t.hash,"__posthog")||os(t.hash,"state"),s=r?Rc((()=>JSON.parse(atob(decodeURIComponent(r)))))||Rc((()=>JSON.parse(decodeURIComponent(r)))):null;return s&&s.action==="ph_authorize"?((i=s).source="url",i&&Object.keys(i).length>0&&(s.desiredHash?t.hash=s.desiredHash:n?n.replaceState(n.state,"",t.pathname+t.search):t.hash="")):((i=JSON.parse(e.getItem(pu)||"{}")).source="localstorage",delete i.userIntent),!(!i.token||this.instance.config.token!==i.token||(this.loadToolbar(i),0))}catch{return!1}}Zl(t){var e=B.ph_load_toolbar||B.ph_load_editor;!H(e)&&je(e)?e(t,this.instance):gu.warn("No toolbar load function found")}loadToolbar(t){var e=!(P==null||!P.getElementById(cf));if(!w||e)return!1;var n=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,i=I({token:this.instance.config.token},t,{apiURL:this.instance.requestRouter.endpointFor("ui")},n?{instrument:!1}:{});if(w.localStorage.setItem(pu,JSON.stringify(I({},i,{source:void 0}))),this.Vl()===2)this.Zl(i);else if(this.Vl()===0){var r;this.Wl(1),(r=B.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"toolbar",(s=>{if(s)return gu.error("[Toolbar] Failed to load",s),void this.Wl(0);this.Wl(2),this.Zl(i)})),ve(w,"turbolinks:load",(()=>{this.Wl(0),this.loadToolbar(i)}))}return!0}Gl(t){return this.loadToolbar(t)}maybeLoadEditor(t,e,n){return t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),this.maybeLoadToolbar(t,e,n)}}},tv=I({experiments:Me},Cs),nv={conversations:class{constructor(t){this.Ql=void 0,this._conversationsManager=null,this.Kl=!1,this.Jl=null,this.Yl=!1,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this._instance.config.disable_conversations&&(this.Xl=t.ok,t.ok)){var e=t.config.conversations;H(e)||(mt(e)?this.Ql=e:(this.Ql=e.enabled,this.Jl=e),this.loadIfEnabled())}}reset(){var t;(t=this._conversationsManager)==null||t.reset(),this._conversationsManager=null,this.Ql=void 0,this.Jl=null,this.Xl=void 0,this.Yl=!1}loadIfEnabled(){if(!(this._conversationsManager||this.Kl||this._instance.config.disable_conversations||ga(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=B?.__PosthogExtensions__;if(t&&!C(this.Ql)&&this.Ql)if(this.Jl&&this.Jl.token){this.Kl=!0;try{var e=t.initConversations;if(e)return this.tu(e),void(this.Kl=!1);var n=t.loadExternalDependency;if(!n)return void this.eu(ll);n(this._instance,"conversations",(i=>{i||!t.initConversations?this.eu("Could not load conversations script",i):this.tu(t.initConversations),this.Kl=!1}))}catch(i){this.eu("Error initializing conversations",i),this.Kl=!1}}else ot.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,ot.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else ot.error("Cannot complete initialization: remote config is null")}eu(t,e){ot.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():ot.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!Ye(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":ga(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.Xl===!1?"remote_config_failed":C(this.Ql)?this.Xl?"disabled_in_project":"remote_config_pending":this.Ql?H(this.Jl)||!this.Jl.token?"missing_token":B!=null&&B.__PosthogExtensions__?this.Kl?"initializing":this.Yl?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.isVisible())!==null&&t!==void 0&&t}sendMessage(t,e,n){var i=this;return se((function*(){return i._conversationsManager?i._conversationsManager.sendMessage(t,e,n):(ot.warn(En),null)}))()}getMessages(t,e){var n=this;return se((function*(){return n._conversationsManager?n._conversationsManager.getMessages(t,e):(ot.warn(En),null)}))()}markAsRead(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(ot.warn(En),null)}))()}getTickets(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(ot.warn(En),null)}))()}requestRestoreLink(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(ot.warn(En),null)}))()}restoreFromToken(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(ot.warn(En),null)}))()}restoreFromUrlToken(){var t=this;return se((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(ot.warn(En),null)}))()}getCurrentTicketId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getCurrentTicketId())!==null&&t!==void 0?t:null}getWidgetSessionId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getWidgetSessionId())!==null&&t!==void 0?t:null}Xn(){var t;(t=this._conversationsManager)==null||t.setIdentity()}ts(){var t;(t=this._conversationsManager)==null||t.clearIdentity()}}},iv={logs:class{constructor(t){var e,n=this;this.iu=!1,this.ru=!1,this.rt=pe("[logs]"),this.nu=I({},this.rt,{error(){for(var i=arguments.length,r=new Array(i),s=0;i>s;s++)r[s]=arguments[s];r.some(Su)||n.rt.error(...r)}}),this.tr=[],this.su=[],this.Sa=0,this.au=()=>{var i,r;this.Sa=0,(i=this.ou)==null||i.onReconnect(),(r=this.lu)==null||r.onReconnect()},this._instance=t,this._instance&&(e=this._instance.config.logs)!=null&&e.captureConsoleLogs&&(this.iu=!0),w&&ve(w,"online",this.au)}uu(t,e,n,i){var r,s=(function(o,a){var l,u,c,d,f,h,p,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,v=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,E=C(v)?Math.max(m,2048):Math.max(m,v),S=o?.resourceAttributes;return{serviceName:(d=(f=S?.["service.name"])!==null&&f!==void 0?f:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(h=S?.["service.version"])!==null&&h!==void 0?h:o?.serviceVersion,environment:(p=S?.["deployment.environment"])!==null&&p!==void 0?p:o?.environment,resourceAttributes:S,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:E,maxBatchRecordsPerPost:100,rateCapWindowMs:g,maxLogsPerInterval:v,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}})((r=this._instance)==null||(r=r.config)==null?void 0:r.logs,n);return[new ag(this.hu(t,e),s,this.nu,(()=>this.du()),(o=>o()),void 0,i),s]}vu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.ou||this.cu!==e){var n;(n=this.ou)==null||n.reset(),this.cu=e;var i=this.uu((()=>this.tr),(r=>{this.tr=r}));this.ou=i[0],this.fu=i[1]}return this.ou}pu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.lu||this.gu!==e){var n;(n=this.lu)==null||n.reset(),this.gu=e;var i=this.uu((()=>this.su),(r=>{this.su=r}),{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},Eu);this.lu=i[0],this.mu=i[1]}return this.lu}initialize(){this.loadIfEnabled()}onRemoteConfig(t){var e;if(t.ok){var n=(e=t.config.logs)==null?void 0:e.captureConsoleLogs;!H(n)&&n&&(this.iu=!0,this.loadIfEnabled())}}reset(){var t,e;this.tr=[],(t=this.ou)==null||t.reset(),this.su=[],(e=this.lu)==null||e.reset(),this.Sa=0}captureLog(t){this.vu().captureLog(t)}he(t){this.pu().captureLog(t)}get logger(){return this.yu||(this.yu={trace:(t,e)=>this.captureLog({body:t,level:"trace",attributes:e}),debug:(t,e)=>this.captureLog({body:t,level:"debug",attributes:e}),info:(t,e)=>this.captureLog({body:t,level:"info",attributes:e}),warn:(t,e)=>this.captureLog({body:t,level:"warn",attributes:e}),error:(t,e)=>this.captureLog({body:t,level:"error",attributes:e}),fatal:(t,e)=>this.captureLog({body:t,level:"fatal",attributes:e})}),this.yu}flushLogs(t){t?this.bu(t):(this.ou&&this.ou.flush().catch((e=>this._u(e))),this.lu&&this.lu.flush().catch((e=>this._u(e))))}_u(t){Su(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=B?.__PosthogExtensions__;if(t){var e=t.loadExternalDependency;e?e(this._instance,"logs",(n=>{var i;n||(i=t.logs)==null||!i.initializeLogs?this.rt.error("Could not load logs script",n):(t.logs.initializeLogs(this._instance),this.ru=!0)})):this.rt.error(ll)}else this.rt.error("PostHog Extensions not found.")}}hu(t,e){var n=this._instance;return{get isDisabled(){return!1},get optedOut(){return!n.is_capturing()},getPersistedProperty:i=>i===Ut.LogsQueue?t():void 0,setPersistedProperty(i,r){var s;i===Ut.LogsQueue&&e((s=r)!==null&&s!==void 0?s:[])},Ot:i=>this.Ot(i),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Ot(t){return new Promise((e=>{if(bf(this.Sa,3))e({kind:"fatal",error:Do(void 0,"logs endpoint is unreachable, dropping batch")});else{var n=!1,i=s=>{n||(n=!0,clearTimeout(r),e(s))},r=setTimeout((()=>{this.rt.warn("Logs request timed out before receiving a response"),i({kind:"retry-later",error:Do(void 0,"logs request timed out")})}),9e4);this._instance._send_request({method:"POST",url:this.wu(),data:t,compression:"best-available",batchKey:"logs",fireCallbackOnDrop:!0,callback:s=>{var o=s.statusCode;if(this.ku(o),o>=200&&300>o)i({kind:"ok"});else if(o===413)i({kind:"too-large"});else if(o!==0&&o!==429&&500>o)i({kind:"fatal",error:new Error("logs request failed with status "+o)});else{var a;o===0?(s.error||this.rt.warn("Logs request failed before receiving an HTTP response"),i({kind:"retry-later",error:Do(s.error,"logs request failed before receiving an HTTP response")})):i({kind:"retry-later",error:(a=s.error)!==null&&a!==void 0?a:new Error("logs request failed with status "+o)})}}})}}))}ku(t){(t!==0||this._instance.__loaded)&&(this.Sa=Ef(t,this.Sa,3,(()=>this.rt.warn("Log requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped sending logs; will try again when connectivity changes."))))}bu(t){this.tr.length>0&&this.xu(t,this.tr,this.fu,ne.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,Eu,(e=>{this.su=e}))}xu(t,e,n,i,r){if(e.length!==0){var s=e.map((a=>a.record));r([]);var o=qd(s,zd(n,ne.LIB_NAME,ne.LIB_VERSION),i,ne.LIB_VERSION);this._instance._send_request({method:"POST",url:this.wu(),data:o,compression:"best-available",batchKey:"logs",transport:t})}}wu(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}du(){var t,e={};if(e.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var n=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.windowId,r=n.sessionStartTimestamp,s=n.lastActivityTimestamp;e.sessionId=n.sessionId,e.windowId=i,H(r)||(e.sessionStartTimestamp=r),H(s)||(e.lastActivityTimestamp=s)}if(B!=null&&(t=B.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?fn(B.location.href):B.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},rv={metrics:class{constructor(t){this.rt=pe("[metrics]"),this._instance=t}initialize(){}vu(){var t,e,n=(t=this._instance)==null||(t=t.config)==null?void 0:t.metrics;return this.ou&&this.cu===n||((e=this.ou)==null||e.reset(),this.cu=n,this.ou=new lg(this.hu(),(function(i){var r,s,o,a,l,u=i?.resourceAttributes;return{serviceName:(r=u?.["service.name"])!==null&&r!==void 0?r:i?.serviceName,serviceVersion:(s=u?.["service.version"])!==null&&s!==void 0?s:i?.serviceVersion,environment:(o=u?.["deployment.environment"])!==null&&o!==void 0?o:i?.environment,resourceAttributes:u,beforeSend:i?.beforeSend,flushIntervalMs:(a=i?.flushIntervalMs)!==null&&a!==void 0?a:1e4,maxSeriesPerFlush:(l=i?.maxSeriesPerFlush)!==null&&l!==void 0?l:1e3}})(n),this.rt)),this.ou}count(t,e,n){e===void 0&&(e=1),this.vu().count(t,e,n)}gauge(t,e,n){this.vu().gauge(t,e,n)}histogram(t,e,n){this.vu().histogram(t,e,n)}flush(t){if(!this.ou)return Promise.resolve();if(t){var e=this.ou.drainWindow();return e&&this.Jt(e,t),Promise.resolve()}return this.ou.flush().catch((n=>this.rt.error("PostHog metrics flush failed:",n)))}reset(){var t;(t=this.ou)==null||t.reset()}hu(){var t=this._instance,e=this;return{get isDisabled(){return!1},get optedOut(){return!t.is_capturing()},Jt:n=>e.Jt(n),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Jt(t,e){return new Promise((n=>{var i=!1,r=o=>{i||(i=!0,clearTimeout(s),n(o))},s=setTimeout((()=>r({kind:"retry-later",error:new Error("metrics request timed out")})),9e4);this._instance._send_request(I({method:"POST",url:this.Su(),data:t,compression:"best-available",batchKey:"metrics"},e&&{transport:e},{fireCallbackOnDrop:!0,callback(o){var a=o.statusCode;if(a>=200&&300>a)r({kind:"ok"});else if(a===413)r({kind:"too-large"});else if(a!==0&&a!==429&&500>a)r({kind:"fatal",error:new Error("metrics request failed with status "+a)});else{var l;r({kind:"retry-later",error:(l=o.error)!==null&&l!==void 0?l:new Error("metrics request failed with status "+a)})}}}))}))}Su(){return this._instance.requestRouter.endpointFor("api","/i/v1/metrics")+"?token="+encodeURIComponent(this._instance.config.token)}}},sv=I({},Cs,Gm,Km,Ym,Jm,Zm,Qm,Xm,ev,tv,nv,iv,rv);Ze.__defaultExtensionClasses=I({},sv);(function(){ne.SDK_DIST_CHANNEL="npm";var t=Wi[Gn]=new Ze;return(function(){function e(){e.done||(e.done=!0,Jf=!1,ie(Wi,(function(n){n._dom_loaded()})))}P!=null&&P.addEventListener?P.readyState==="complete"?e():ve(P,"DOMContentLoaded",e,{capture:!1}):w&&A.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const ov=["a[href]","button:not([disabled])","input:not([disabled]):not([type='hidden'])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(",");let pt=null,ka=null,Xf="";const Ca=new Map;function Qf(t){return[...t.querySelectorAll(ov)].filter(e=>!e.hidden&&e.getAttribute("aria-hidden")!=="true"&&e.getClientRects().length>0)}function av(t){for(const e of document.body.children)e===t||e.tagName==="SCRIPT"||(Ca.set(e,{inert:e.inert,ariaHidden:e.getAttribute("aria-hidden")}),e.inert=!0,e.setAttribute("aria-hidden","true"))}function lv(){for(const[t,e]of Ca)t.inert=e.inert,e.ariaHidden===null?t.removeAttribute("aria-hidden"):t.setAttribute("aria-hidden",e.ariaHidden);Ca.clear()}function eh(t){return t?.dataset.modalDismissible!=="false"&&t?.getAttribute("aria-busy")!=="true"}function We(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n)return!1;pt&&pt!==n&&ze(pt,{restoreFocus:!1,force:!0}),ka=e.trigger||document.activeElement,pt=n,Xf=document.body.style.overflow,av(n),document.body.style.overflow="hidden",n.classList.add("open"),n.setAttribute("aria-hidden","false");const i=n.querySelector(".modal-content");i&&(i.style.transform="scale(1) translateY(0)");const r=()=>{if(pt!==n)return;((e.initialFocus?n.querySelector(e.initialFocus):n.querySelector("[data-modal-initial-focus]"))||Qf(n)[0]||n.querySelector(".modal-content")||n).focus({preventScroll:!0})};return requestAnimationFrame(r),setTimeout(r,260),!0}function ze(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n||!e.force&&!eh(n))return!1;n.classList.remove("open"),n.setAttribute("aria-hidden","true"),lv(),document.body.style.overflow=Xf,pt=null;const i=ka;return ka=null,e.restoreFocus!==!1&&i?.isConnected&&i.focus({preventScroll:!0}),!0}function xu(t,e,n="Operation in progress"){const i=typeof t=="string"?document.getElementById(t):t;i&&(i.dataset.modalDismissible=e?"false":"true",i.setAttribute("aria-busy",String(!!e)),e?i.setAttribute("aria-label",n):i.removeAttribute("aria-label"))}function cv(t){if(!eh(t))return;const e=t.dataset.modalCloseHandler;e&&typeof window[e]=="function"?window[e]():ze(t)}document.addEventListener("keydown",t=>{if(!pt)return;if(t.key==="Escape"){t.preventDefault(),t.stopImmediatePropagation(),cv(pt);return}if(t.key!=="Tab"){t.stopPropagation();return}const e=Qf(pt);if(!e.length){t.preventDefault(),(pt.querySelector(".modal-content")||pt).focus();return}const n=e[0],i=e[e.length-1];t.shiftKey&&document.activeElement===n?(t.preventDefault(),i.focus()):!t.shiftKey&&document.activeElement===i&&(t.preventDefault(),n.focus())},!0);function uv(){document.querySelectorAll(".modal-overlay").forEach(t=>{t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-hidden",t.classList.contains("open")?"false":"true");const e=t.querySelector(".modal-content");e&&!e.hasAttribute("tabindex")&&(e.tabIndex=-1);const n=t.querySelector("h1, h2, h3");n&&(n.id||(n.id=`${t.id}-title`),t.setAttribute("aria-labelledby",n.id)),t.querySelectorAll(".modal-close").forEach(i=>{i.getAttribute("aria-label")||i.setAttribute("aria-label","Close dialog")})})}const ml=Object.freeze({free:"Free",professional:"Pro",power:"Power"}),dv=Object.freeze({free:2,professional:50,power:2e3}),fv="(contact us)",hv=Object.freeze({free:Object.freeze(["2 generations/month","Gemini model only","Code Review"]),professional:Object.freeze(["50 generations/month","All models","Code Regeneration","Code Review"]),power:Object.freeze(["2000 generations/month","All models","Code Regeneration","Bring your own key (BYOK)","Code Review","All models + early access",`API & MCP access ${fv}`])}),th="CodeFile",nh="GeneratedCode",pv={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function ln(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Aa(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function gv(t={},e=0){const n=Aa(t.artifactType||t.type||th),i=Aa(t.artifactName||t.name||t.fileName||`${nh}-${e+1}`);return`${n||"artifact"}-${i||e+1}`}function ih(t={},e=0){const n=ln(t),i=n.artifactType||n.type||th,r=n.artifactName||n.name||nh;let s=n.fileName||r;return s.endsWith(".dart")||(s+=".dart"),{id:Aa(n.id)||gv({...n,artifactType:i,artifactName:r,fileName:s},e),artifactType:i,artifactName:r,fileName:s,deployPath:n.deployPath||"",description:n.description||"",code:n.code||n.content||"",dependencies:rh(n.dependencies),imports:Array.isArray(n.imports)?n.imports:[],publicApi:Array.isArray(n.publicApi)?n.publicApi:[],relationships:sh(n.relationships),deployStatus:n.deployStatus||"pending",review:n.review||null,metadata:ln(n.metadata),codeType:n.codeType||pv[i]||"O"}}function rh(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const n=ln(e),i=n.name||n.package;return i?{name:i,version:n.version||null,versionRequired:!!(n.versionRequired||n.required),inferred:!!n.inferred,...n.reason?{reason:n.reason}:{}}:null}).filter(Boolean):Object.entries(ln(t)).map(([e,n])=>({name:e,version:n||null,inferred:!1})):[]}function sh(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const n=ln(e);return!n.from&&!n.to?null:{from:n.from||null,to:n.to||null,type:n.type||"uses",description:n.description||""}}).filter(Boolean):[]}function Pa(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;try{return JSON.parse(e)}catch{const n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(!n)return null;try{return JSON.parse(n[1].trim())}catch{return null}}}function Qi(t,e={}){const n=[],i=typeof t=="string"?Pa(t):t,s=ln(i||{});!i&&typeof t=="string"&&n.push("Structured bundle parse failed; using legacy single-artifact fallback.");const o=Array.isArray(s.artifacts)?s.artifacts:[{artifactType:s.artifactType||e.artifactType,artifactName:s.artifactName||e.artifactName,fileName:s.fileName||e.fileName,description:s.description,code:s.code||e.code||(typeof t=="string"?t:""),dependencies:s.dependencies||e.dependencies,relationships:s.relationships||e.relationships}];o.forEach((d,f)=>{!d?.artifactType&&!d?.type&&n.push(`Artifact ${f+1} has no artifactType; it will deploy as a standalone code file under lib/custom_code/ root.`)});const a=o.map((d,f)=>ih(d,f)),l=new Map(o.map((d,f)=>[ln(d).id,a[f]?.id]).filter(([d,f])=>d&&f)),u=d=>l.get(d)||d,c=sh(s.relationships||e.relationships).map(d=>({...d,from:d.from?u(d.from):d.from,to:d.to?u(d.to):d.to}));return{schemaVersion:s.schemaVersion||e.schemaVersion||null,id:s.id||e.id||"bundle-current",title:s.title||s.name||e.title||"Generated artifact bundle",description:s.description||e.description||"",artifacts:a,dependencies:rh(s.dependencies||e.dependencies),relationships:c,deployOrder:Array.isArray(s.deployOrder)?s.deployOrder.map(u):a.map(d=>d.id),warnings:[...n,...Array.isArray(s.warnings)?s.warnings:[]],metadata:ln(s.metadata)}}function oi(t){return Qi(t).artifacts[0]||ih()}function Zt(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function ai(t){return JSON.stringify(t,null,2)}function mv(t){return ai({task:"architect",userRequest:String(t??"")})}function vv(t){const e=Zt(t);return e&&typeof e=="object"&&typeof e.task=="string"?ai(e):ai({task:"generate_bundle",bundleSpec:e})}function _v(t){return ai({task:"review_bundle",generatedBundle:Zt(t),outputRequirements:{bundleReview:["status","score","summary","manualActions","findings"],scoreRange:[0,100],eachArtifact:["id","review.status","review.findings"],manualActions:{definition:"Setup the developer must perform by hand in the FlutterFlow editor that FlutterFlow will NOT do for them.",exclude:["creating the Custom Action, Widget or Code File itself - deploying the code creates it","declaring parameters or return values FlutterFlow derives from the function signature","anything that resolves as a side effect of using the action or widget in the editor","generic advice such as testing, reviewing or rebuilding the app"],preferEmpty:"Return an empty array when nothing qualifies - an empty list is the expected result for most bundles."}}})}function vl(t,e=null){const n={stage:t};return e!=null&&(n.bundle=Zt(e)),n}function yv({bundleSpec:t,artifactBundle:e,bundleReview:n,artifactId:i,userFeedback:r}){return ai({task:"regenerate_artifact",artifactId:i,bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(r)})}function oh({bundleSpec:t,artifactBundle:e,bundleReview:n,userFeedback:i}){return ai({task:"regenerate_bundle",bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(i??"")})}const Iu={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"},wv=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function tt(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function bv(t){return tt(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||tt(t.filterSummary)||tt(t.filterResults):!1}function ah(t,e=0){if(!tt(t)||e>3)return null;if(bv(t))return t;for(const n of wv){const i=t[n];if(tt(i)){const r=ah(i,e+1);if(r)return r}}return null}function ds(t){return Array.isArray(t)?t.some(ds):tt(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(ds):!1}function Fa(t){return Array.isArray(t)?t.some(Fa):tt(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(Fa):!1}function lh(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function Ev(t,e){if(tt(t))for(const[n,i]of Object.entries(t)){if(!tt(i))continue;const r=tt(i.categories)?i.categories:{},s=Object.entries(r).filter(([,o])=>tt(o)&&o.matched===!0).map(([o])=>o);s.length>0?s.forEach(o=>e.add(o)):i.matched===!0&&e.add(lh(n))}}function Sv(t,e){if(!t)return;const n=Array.isArray(t)?t.flatMap(i=>tt(i)?Object.entries(i):[]):Object.entries(t);for(const[i,r]of n){if(!ds(r))continue;const s=lh(i),o=r?.raiFilterResult?.raiFilterTypeResults||(s==="rai"?r?.raiFilterTypeResults:null),a=tt(o)?Object.entries(o).filter(([,l])=>ds(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(s)}}function xv(t){return Iu[t]?Iu[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function ku(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 Iv(t){const e=ah(t);if(!e)return null;const n=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);Ev(e.filterSummary,n),Sv(e.filterResults,n);const i=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||n.size>0,r=e.invocationResult||null,s=Fa(e.filterSummary||e.filterResults);return!i&&!s&&!["PARTIAL","FAILURE"].includes(r)?null:{kind:i?"blocked":"unavailable",invocationResult:r,matchedFilters:[...n]}}function kv(t,e){const n=Iv(t);if(!n)return null;const i=[...new Set(n.matchedFilters.map(xv))],r=n.kind==="blocked",s=new Error(r?`Safety screening blocked this pipeline step for ${ku(i)}.`:"Safety screening could not be completed. Please try again.");return s.name="ModelArmorError",s.code=r?"MODEL_ARMOR_BLOCKED":"MODEL_ARMOR_UNAVAILABLE",s.isModelArmor=!0,s.pipelineStep=e,s.userTitle=r?"Request blocked for safety":"Safety check unavailable",s.userMessage=r?`The safety check detected ${ku(i)}. Edit your request to remove or rephrase the flagged content, then run the pipeline again.`:"The safety service did not finish all of its checks. Please wait a moment and run the pipeline again.",s.retryExplanation=r?"Trying another model would not change this safety decision.":"A fallback model was not attempted because safety screening must complete first.",s.matchedFilters=n.matchedFilters,s}function Cv(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function Cu(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,n=[];for(const i of Cv(t).split(` +(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const s of r)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function n(r){const s={};return r.integrity&&(s.integrity=r.integrity),r.referrerPolicy&&(s.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?s.credentials="include":r.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function i(r){if(r.ep)return;r.ep=!0;const s=n(r);fetch(r.href,s)}})();var w=typeof window<"u"?window:void 0,Ne=typeof globalThis<"u"?globalThis:w,He=Ne?.navigator,P=Ne?.document,me=Ne?.location,Xa=Ne?.fetch,zo=Ne!=null&&Ne.XMLHttpRequest&&"withCredentials"in new Ne.XMLHttpRequest?Ne.XMLHttpRequest:void 0,fc=Ne?.AbortController,Np=Ne?.CompressionStream,Ge=He?.userAgent;function hd(){return!(!w||w.navigator.onLine===!1)}var _i=typeof globalThis<"u"?globalThis:w;_i&&typeof self>"u"&&(_i.self=_i),_i&&typeof File>"u"&&(_i.File=function(){});var B=w??{},ne={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function hc(t,e,n,i,r,s,o){try{var a=t[s](o),l=a.value}catch(u){return void n(u)}a.done?e(l):Promise.resolve(l).then(i,r)}function se(t){return function(){var e=this,n=arguments;return new Promise((function(i,r){var s=t.apply(e,n);function o(l){hc(s,i,r,o,a,"next",l)}function a(l){hc(s,i,r,o,a,"throw",l)}o(void 0)}))}}function I(){return I=Object.assign?Object.assign.bind():function(t){for(var e=1;arguments.length>e;e++){var n=arguments[e];for(var i in n)({}).hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},I.apply(null,arguments)}function pd(t,e){if(t==null)return{};var n={};for(var i in t)if({}.hasOwnProperty.call(t,i)){if(e.indexOf(i)!==-1)continue;n[i]=t[i]}return n}var pc=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function gc(t){return typeof t=="string"||t}function mc(t){return typeof t=="string"?t:void 0}var yi,Op=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],Ut=(function(t){return t.AnonymousId="anonymous_id",t.DistinctId="distinct_id",t.Props="props",t.EnablePersonProcessing="enable_person_processing",t.PersonMode="person_mode",t.FeatureFlagDetails="feature_flag_details",t.FeatureFlags="feature_flags",t.FeatureFlagPayloads="feature_flag_payloads",t.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",t.BootstrapFeatureFlags="bootstrap_feature_flags",t.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",t.OverrideFeatureFlags="override_feature_flags",t.Queue="queue",t.AiQueue="ai_queue",t.LogsQueue="logs_queue",t.OptedOut="opted_out",t.SessionId="session_id",t.SessionStartTimestamp="session_start_timestamp",t.SessionLastTimestamp="session_timestamp",t.PersonProperties="person_properties",t.GroupProperties="group_properties",t.InstalledAppBuild="installed_app_build",t.InstalledAppVersion="installed_app_version",t.SessionReplay="session_replay",t.PushRegistered="push_registered",t.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",t.SurveyLastSeenDate="survey_last_seen_date",t.SurveysSeen="surveys_seen",t.Surveys="surveys",t.RemoteConfig="remote_config",t.FlagsEndpointWasHit="flags_endpoint_was_hit",t.DeviceId="device_id",t})({}),vc=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),Bp=["$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"],Dp=["token"],gd="NativeGzipValidationError",qo=t=>t.length>=2&&t[0]===31&&t[1]===139,_c=(t,e)=>t===vc.GZipJS||e===vc.GZipJS||e==="gzip",yc=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",pr=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=gd,e},jp=(function(){var t=se((function*(e,n){18>e.size&&pr("too-short");var i=new Uint8Array(yield e.slice(0,10).arrayBuffer());qo(i)&&i[2]===8||pr("invalid-header");var r=new DataView(yield e.slice(e.size-8).arrayBuffer());r.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(yi)return yi;yi=[];for(var c=0;256>c;c++){for(var d=c,f=0;8>f;f++)d=1&d?3988292384^d>>>1:d>>>1;yi[c]=d>>>0}return yi})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(n)&&pr("invalid-crc");var s=n.length>>>0;r.getUint32(4,!0)!==s&&pr("invalid-size")}));return function(e,n){return t.apply(this,arguments)}})();function Vo(){return Vo=se((function*(t,e,n){e===void 0&&(e=!0);try{var i=new TextEncoder().encode(t),r=new globalThis.CompressionStream("gzip"),s=r.writable.getWriter(),o=s.write(i).then((()=>s.close())).catch((function(){var u=se((function*(c){try{yield s.abort(c)}catch{}throw c}));return function(c){return u.apply(this,arguments)}})()),a=new Response(r.readable).blob(),l=(yield Promise.all([a,o]))[0];return yield jp(l,i),l}catch(u){if(n!=null&&n.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),Vo.apply(this,arguments)}var Up=["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"],wc=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var n=t.toLowerCase();return Up.concat(e).some((i=>{var r=i.toLowerCase();return n.indexOf(r)!==-1}))};function j(t,e){return t.indexOf(e)!==-1}var xs=function(t){return t.trim()},Go=function(t){return t.replace(/^\$/,"")};function md(t){var e,n=[];return(e=JSON.stringify(t,(function(i,r){if(typeof r=="bigint")return r.toString();if(typeof r!="function"&&typeof r!="symbol"){if(r instanceof Error)return{name:r.name,message:r.message,stack:r.stack};if(r&&typeof r=="object"){for(;n.length>0&&n[n.length-1]!==this;)n.pop();if(n.includes(r))return"[Circular]";n.push(r)}return r}})))!==null&&e!==void 0?e:"null"}var vd=Object.prototype,_d=vd.hasOwnProperty,Is=vd.toString,U=Array.isArray||function(t){return Is.call(t)==="[object Array]"},je=t=>typeof t=="function",he=t=>t===Object(t)&&!U(t),Kt=t=>{if(he(t)){for(var e in t)if(_d.call(t,e))return!1;return!0}return!1},C=t=>t===void 0,X=t=>Is.call(t)=="[object String]",Ko=t=>X(t)&&t.trim().length===0,Ye=t=>t===null,H=t=>C(t)||Ye(t),ke=t=>Is.call(t)=="[object Number]"&&t==t,Dt=t=>ke(t)&&t>0,mt=t=>Is.call(t)==="[object Boolean]",Hp=t=>t instanceof FormData,Wp=t=>j(Bp,t),zp=t=>j(Dp,t);function yd(t){return t===null||typeof t!="object"}function Hr(t,e){return{}.toString.call(t)==="[object "+e+"]"}function Qa(t){return typeof Event<"u"&&wd(t,Event)}function wd(t,e){try{return t instanceof e}catch{return!1}}var qp=[!0,"true",1,"1","yes"],uo=t=>j(qp,t),Vp=[!1,"false",0,"0","no"];function At(t,e,n,i,r){return e>n&&(i.warn("min cannot be greater than max."),e=n),ke(t)?t>n?(i.warn(" cannot be greater than max: "+n+". Using max value instead."),n):e>t?(i.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(i.warn(" must be a number. using max or fallback. max: "+n+", fallback: "+r),At(r||n,e,n,i))}class Gp{constructor(e){this.tt={},this.et=e.et,this.it=At(e.bucketSize,0,100,e.rt),this.nt=At(e.refillRate,0,this.it,e.rt),this.st=At(e.refillInterval,0,864e5,e.rt)}ot(e,n){var i=Math.floor((n-e.lastAccess)/this.st);i>0&&(e.tokens=Math.min(e.tokens+i*this.nt,this.it),e.lastAccess=e.lastAccess+i*this.st)}consumeRateLimit(e){var n,i=Date.now(),r=String(e),s=this.tt[r];return s?this.ot(s,i):this.tt[r]=s={tokens:this.it,lastAccess:i},s.tokens===0||(s.tokens--,s.tokens===0&&((n=this.et)==null||n.call(this,e)),s.tokens===0)}stop(){this.tt={}}}var rt="Mobile",Wr="iOS",Yt="Android",ti="Tablet",bd=Yt+" "+ti,Ed="iPad",Sd="Apple",xd=Sd+" Watch",Di="Safari",ni="BlackBerry",Id="Samsung",kd=Id+"Browser",Cd=Id+" Internet",Fn="Chrome",Kp=Fn+" OS",Ad=Fn+" "+Wr,el="Internet Explorer",Pd=el+" "+rt,tl="Opera",Yp=tl+" Mini",nl="Edge",Fd="Microsoft "+nl,Xn="Firefox",Rd=Xn+" "+Wr,Ki="Nintendo",Yi="PlayStation",Qn="Xbox",Td=Yt+" "+rt,$d=rt+" "+Di,Fi="Windows",Yo=Fi+" Phone",bc="Nokia",Jo="Ouya",Md="Generic",Jp=Md+" "+rt.toLowerCase(),Ld=Md+" "+ti.toLowerCase(),Zo="Konqueror",Nd="Oculus Browser",zr="Vivaldi",Od="Yandex",qr="Whale",Xo="DuckDuckGo",Bd="Pale Moon",Vr="Waterfox",ji="Brave",Dd="Google Search App",we="(\\d+(\\.\\d+)?)",fo=new RegExp("Version/"+we),Zp=new RegExp(Qn,"i"),Xp=new RegExp(Yi+" \\w+","i"),Qp=new RegExp(Ki+" \\w+","i"),il=new RegExp(ni+"|PlayBook|BB10","i"),eg={"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"},jd=function(t,e,n,i){e=e||"";var r=(function(s){return s!=null&&s.brave?ji:null})(n);return r||(i!=null&&i.detectGoogleSearchApp&&j(t,"GSA/")?Dd:j(t," OPR/")&&j(t,"Mini")?Yp:j(t," OPR/")?tl:il.test(t)?ni:j(t,"IE"+rt)||j(t,"WPDesktop")?Pd:j(t,"OculusBrowser")?Nd:j(t,kd)?Cd:j(t,nl)||j(t,"Edg/")?Fd:j(t,zr+"/")?zr:j(t,"YaBrowser/")?Od:j(t,qr+"/")?qr:j(t,Xo+"/")||j(t,"Ddg/")?Xo:j(t,"FBIOS")?"Facebook "+rt:j(t,"UCWEB")||j(t,"UCBrowser")?"UC Browser":j(t,"CriOS")?Ad:j(t,"CrMo")||j(t,Fn)?Fn:j(t,Yt)&&j(t,Di)?Td:j(t,"FxiOS")?Rd:j(t.toLowerCase(),Zo.toLowerCase())?Zo:j(t,ji+"/")?ji:((s,o)=>o&&j(o,Sd)||(function(a){return j(a,Di)&&!j(a,Fn)&&!j(a,Yt)})(s))(t,e)?j(t,rt)?$d:Di:j(t,"PaleMoon/")?Bd:j(t,Vr+"/")?Vr:j(t,Xn)?Xn:j(t,"MSIE")||j(t,"Trident/")?el:j(t,"Gecko")?Xn:"")},tg={[Pd]:[new RegExp("rv:"+we)],[Fd]:[new RegExp(nl+"?\\/"+we)],[Fn]:[new RegExp("("+Fn+"|CrMo)\\/"+we)],[Ad]:[new RegExp("CriOS\\/"+we)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+we)],[Di]:[fo],[$d]:[fo],[tl]:[new RegExp("(Opera|OPR)\\/"+we)],[Xn]:[new RegExp(Xn+"\\/"+we)],[Rd]:[new RegExp("FxiOS\\/"+we)],[Zo]:[new RegExp("Konqueror[:/]?"+we,"i")],[ni]:[new RegExp(ni+" "+we),fo],[Td]:[new RegExp("android\\s"+we,"i")],[Cd]:[new RegExp(kd+"\\/"+we)],[Nd]:[new RegExp("OculusBrowser\\/"+we)],[zr]:[new RegExp(zr+"\\/"+we)],[Od]:[new RegExp("YaBrowser\\/"+we)],[qr]:[new RegExp(qr+"\\/"+we)],[ji]:[new RegExp(ji+"\\/"+we)],[Xo]:[new RegExp("(DuckDuckGo|Ddg)\\/"+we)],[Bd]:[new RegExp("PaleMoon\\/"+we)],[Vr]:[new RegExp(Vr+"\\/"+we)],[Dd]:[new RegExp("GSA\\/"+we)],[el]:[new RegExp("(rv:|MSIE )"+we)],Mozilla:[new RegExp("rv:"+we)]},ng=function(t,e,n,i){var r=jd(t,e,n,i),s=tg[r];if(C(s))return null;for(var o=0;s.length>o;o++){var a=t.match(s[o]);if(a)return parseFloat(a[a.length-2])}return null},Ec=[[new RegExp(Qn+"; "+Qn+" (.*?)[);]","i"),t=>[Qn,t&&t[1]||""]],[new RegExp(Ki,"i"),[Ki,""]],[new RegExp(Yi,"i"),[Yi,""]],[il,[ni,""]],[new RegExp(Fi,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Yo,""];if(new RegExp(rt).test(e)&&!/IEMobile\b/.test(e))return[Fi+" "+rt,""];var n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){var i=eg[n[1]]||"";return/arm/i.test(e)&&(i="RT"),[Fi,i]}return[Fi,""]}],[/((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=C(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+Yt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Yt+")","i"),t=>t&&t[2]?[Yt,[t[2],t[3],t[4]||"0"].join(".")]:[Yt,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{var e=["Mac OS X",""];return t&&t[1]&&(e[1]=[t[1],t[2],t[3]||"0"].join(".")),e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[Kp,""]],[/Linux|debian/i,["Linux",""]]],Sc=function(t){return Qp.test(t)?Ki:Xp.test(t)?Yi:Zp.test(t)?Qn:new RegExp(Jo,"i").test(t)?Jo:new RegExp("("+Yo+"|WPDesktop)","i").test(t)?Yo:/iPad/.test(t)?Ed:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?xd:il.test(t)?ni:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(bc,"i").test(t)?bc:/(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(rt).test(t)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(t)||/pixel[\daxl ]{1,6}/i.test(t)&&!/pixel c/i.test(t)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(t)||/lmy47v/i.test(t)&&!/QTAQZ3/i.test(t)?Yt:bd:new RegExp("(pda|"+rt+")","i").test(t)?Jp:new RegExp(ti,"i").test(t)&&!new RegExp(ti+" pc","i").test(t)?Ld:""},ig=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function xc(t,e){return typeof(n=t)=="string"&&ig.test(n)?t:e();var n}function fn(t){return t&&t.split("#")[0]}function rl(t,e){var n=setTimeout(t,e);return n?.unref&&n?.unref(),n}function Ic(t,e,n){return Ud.apply(this,arguments)}function Ud(){return(Ud=se((function*(t,e,n){var i;try{return yield Promise.race([t,new Promise(((r,s)=>{i=rl((()=>{try{n?.(),r()}catch(o){s(o)}}),e)}))])}finally{clearTimeout(i)}}))).apply(this,arguments)}var rg=t=>t instanceof Error,Hd={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}},sg=Hd.info;function Wd(t){if(mt(t))return{boolValue:t};if(typeof t=="number")return Number.isFinite(t)?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:{stringValue:String(t)};if(typeof t=="string")return{stringValue:t};if(U(t))return{arrayValue:{values:t.map((e=>Wd(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function Gr(t){var e=[];for(var n in t){var i=t[n];Ye(i)||C(i)||e.push({key:n,value:Wd(i)})}return e}function og(t,e){var n=Hd[t.level||"info"]||sg,i=n.text,r=n.number,s=String(Date.now())+"000000",o={};e.distinctId&&(o.posthogDistinctId=e.distinctId),e.sessionId&&(o.sessionId=e.sessionId),e.windowId&&(o["window.id"]=e.windowId),H(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),H(e.lastActivityTimestamp)||(o.lastActivityTimestamp=String(e.lastActivityTimestamp)),e.currentUrl&&(o["url.full"]=e.currentUrl),e.screenName&&(o["screen.name"]=e.screenName),e.appState&&(o["app.state"]=e.appState),e.activeFeatureFlags&&e.activeFeatureFlags.length>0&&(o.feature_flags=e.activeFeatureFlags);var a=I({},o,t.attributes||{}),l={timeUnixNano:s,observedTimeUnixNano:s,severityNumber:r,severityText:i,body:{stringValue:t.body},attributes:Gr(a)};return t.trace_id&&(l.traceId=t.trace_id),t.span_id&&(l.spanId=t.span_id),C(t.trace_flags)||(l.flags=t.trace_flags),l}function zd(t,e,n){return I({},t.resourceAttributes,{"service.name":t.serviceName||"unknown_service"},t.environment&&{"deployment.environment":t.environment},t.serviceVersion&&{"service.version":t.serviceVersion},{"telemetry.sdk.name":e,"telemetry.sdk.version":n})}function qd(t,e,n,i){return{resourceLogs:[{resource:{attributes:Gr(e)},scopeLogs:[{scope:{name:n,version:i},logRecords:t}]}]}}let ag=class{constructor(t,e,n,i,r,s,o){var a;s===void 0&&(s=()=>Promise.resolve()),this._instance=t,this.Ne=e,this.rt=n,this.ut=i,this.ht=r,this.dt=s,this.vt=o,this.ct=null,this.ft=0,this.yt=0,this.bt=0,this._t=0,this.wt=!1,this.kt=e.maxBufferSize,this.xt=Math.max((a=e.maxQueueSize)!==null&&a!==void 0?a:e.maxBufferSize,e.maxBufferSize),this.St=e.flushIntervalMs,this.Ct=e.maxBatchRecordsPerPost,this.Mt=e.rateCapWindowMs,this.Tt=e.maxLogsPerInterval}reset(){this.Et(),this.ct=null,this.bt=0,this._t=0,this.wt=!1,this.ft=0,this.yt=0,this.Ct=this.Ne.maxBatchRecordsPerPost}onReconnect(){this.yt=0,this.It()}captureLog(t){if(!this._instance.isDisabled&&!this._instance.optedOut&&t!=null&&t.body){var e=this.Pt(t);if(e!==null)if(e.body){if(this.Rt()){var n={record:og(e,this.ut())};this.ht((()=>this.At(n)))}}else this.rt.info("Log was rejected in beforeSend function")}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Log was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for log:",o),null}return i}Rt(){if(this.Tt===void 0)return!0;var t=Date.now(),e=t-this.bt;return this.Mt>e&&e>=0||(this.bt=t,this._t=0,this.wt=!1),this.Tt>this._t?(this._t++,!0):(this.wt||(this.rt.warn("captureLog dropping logs: exceeded "+this.Tt+" logs per "+this.Mt+"ms"),this.wt=!0),!1)}flush(){var t=this;return se((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return se((function*(){var e;t.Et();var n=(e=t._instance.getPersistedProperty(Ut.LogsQueue))!==null&&e!==void 0?e:[];if(n.length!==0)for(var i=n.length,r=0;n.length>0&&i>r;){var s,o;t.ft=0;var a=Math.min(n.length,t.Ct),l=n.slice(0,a),u=qd(l.map((d=>d.record)),t.Lt(),(s=t.vt)!==null&&s!==void 0?s:t._instance.getLibraryId(),t._instance.getLibraryVersion()),c=yield t._instance.Ot(u);if(c.kind==="too-large"&&l.length>1)t.Ct=Math.max(1,Math.floor(l.length/2)),t.rt.warn("Received 413 when sending logs batch of size "+l.length+", reducing batch size to "+t.Ct);else if(c.kind==="retry-later"||(c.kind==="too-large"?t.rt.warn("Dropping a single log record after 413 with batch size 1 — the record is larger than the server cap and cannot be split further."):c.kind==="ok"&&t.Ne.maxBatchRecordsPerPost>t.Ct&&(t.Ct=Math.min(t.Ne.maxBatchRecordsPerPost,t.Ct+1)),yield t.Dt(l.length),n=(o=t._instance.getPersistedProperty(Ut.LogsQueue))!==null&&o!==void 0?o:[],r+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return se((function*(){var n,i=Math.max(0,t-e.ft),r=(n=e._instance.getPersistedProperty(Ut.LogsQueue))!==null&&n!==void 0?n:[];e._instance.setPersistedProperty(Ut.LogsQueue,r.slice(i)),yield e.dt()}))()}Lt(){return zd(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var n=(e=this._instance.getPersistedProperty(Ut.LogsQueue))!==null&&e!==void 0?e:[];this.xt>n.length||(n.shift(),this.ft++,this.rt.info("Logs queue is full, dropping oldest record.")),n.push(t),this._instance.setPersistedProperty(Ut.LogsQueue,n),this.kt>n.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=rl((()=>{this.Nt=void 0,this.It()}),t))}qt(){var t=Math.min(Math.max(0,this.yt-1),6);return this.St*Math.pow(2,t)}jt(){var t=this._instance.getPersistedProperty(Ut.LogsQueue);return!!t&&t.length>0}shutdown(t){var e=this;return se((function*(){e.Et();var n=e.flush().catch((()=>{}));t!==void 0?yield Ic(n,t):yield n}))()}flushWithTimeout(t){var e=this;return se((function*(){var n=e.flush();yield Ic(n,t,(()=>{n.catch((()=>{}))}))}))()}It(){this.flush().then((()=>{this.yt=0}),(t=>{this.yt++,this.rt.error("PostHog logs flush failed:",t)})).finally((()=>{!this._instance.isDisabled&&this.jt()&&this.$t(this.qt())}))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}};var ho=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function kc(t){return String(t)+"000000"}function Cc(t,e,n,i){var r="";return i&&(r=Object.keys(i).sort().map((s=>JSON.stringify(s)+":"+JSON.stringify(i[s]))).join(",")),t+"\0"+e+"\0"+(n??"")+"\0"+r}let lg=class{constructor(t,e,n){this._instance=t,this.Ne=e,this.rt=n,this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Wt=0}count(t,e,n){e===void 0&&(e=1),this.Vt({name:t,type:"count",value:e,unit:n?.unit,attributes:n?.attributes})}gauge(t,e,n){this.Vt({name:t,type:"gauge",value:e,unit:n?.unit,attributes:n?.attributes})}histogram(t,e,n){this.Vt({name:t,type:"histogram",value:e,unit:n?.unit,attributes:n?.attributes})}flush(){var t=this,e=this.ct,n=(function(){var r=se((function*(){e&&(yield e.catch((()=>{}))),yield t.Zt()}));return function(){return r.apply(this,arguments)}})(),i=n().finally((()=>{this.ct===i&&(this.ct=null)}));return this.ct=i,i}drainWindow(){if(this.Bt.size===0)return null;var t=this.Bt;return this.Bt=new Map,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Gt(t)}reset(){this.Wt++,this.Et(),this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set}Vt(t){if(!this._instance.isDisabled&&!this._instance.optedOut){var e=this.Pt(t);if(e!==null)if(e.name&&typeof e.name=="string")if(typeof e.value=="number"&&Number.isFinite(e.value))if(e.type==="count"&&0>e.value)this.rt.warn("Dropping count '"+e.name+"': counters are monotonic, value must be >= 0");else{var n,i;try{n=e.attributes?I({},e.attributes):void 0,i=Cc(e.type,e.name,e.unit,n)}catch(o){return void this.rt.warn("Dropping metric '"+e.name+"': attributes could not be serialized",o)}var r=this.Bt.get(i);if(!r){if(!this.Qt())return;r={name:e.name,type:e.type,unit:e.unit,attributes:n,windowStartMs:Date.now()},this.Bt.set(i,r)}var s=this.Ut.get(e.name);s===void 0?this.Ut.set(e.name,e.type):s===e.type||this.zt.has(e.name)||(this.zt.add(e.name),this.rt.warn("Metric name '"+e.name+"' is already used as a "+s+"; recording it as a "+e.type+" too will blend both series in charts. Use a distinct name.")),this.Kt(r,e.value),this.$t()}else this.rt.warn("Dropping metric '"+e.name+"': value must be a finite number");else this.rt.warn("Dropping metric with empty name")}}Qt(){return this.Ne.maxSeriesPerFlush>this.Bt.size||(this.Ht||(this.Ht=!0,this.rt.warn("Metric series cap reached ("+this.Ne.maxSeriesPerFlush+" per flush window); dropping new series until the next flush. Reduce attribute cardinality.")),!1)}Kt(t,e){var n;switch(t.type){case"count":t.total=((n=t.total)!==null&&n!==void 0?n:0)+e;break;case"gauge":t.last=e;break;case"histogram":t.hist||(t.hist={count:0,sum:0,min:e,max:e,bucketCounts:new Array(ho.length+1).fill(0)});var i=t.hist;i.count+=1,i.sum+=e,i.min=Math.min(i.min,e),i.max=Math.max(i.max,e),i.bucketCounts[(function(r,s){for(var o=0;s.length>o;o++)if(s[o]>=r)return o;return s.length})(e,ho)]+=1}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Metric was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for metric:",o),null}return i}$t(){this.Nt||(this.Nt=rl((()=>{this.Nt=void 0,this.flush().catch((t=>{this.rt.error("Metrics flush failed:",t)}))}),this.Ne.flushIntervalMs))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}Zt(){var t=this;return se((function*(){if(t.Bt.size!==0){var e=t.Bt;t.Bt=new Map,t.Ht=!1,t.Ut=new Map,t.zt=new Set;var n=t.Wt,i=yield t._instance.Jt(t.Gt(e));if(n===t.Wt)switch(i.kind){case"ok":return;case"retry-later":return t.Yt(e),void t.$t();case"too-large":return void t.rt.warn("Metrics batch exceeded the server size limit and was dropped");case"fatal":return void t.rt.error("Failed to send metrics batch:",i.error)}}}))()}Gt(t){return e=this.Xt(t),n=(function(s,o,a){return I({},s.resourceAttributes,{"service.name":s.serviceName||"unknown_service"},s.environment&&{"deployment.environment":s.environment},s.serviceVersion&&{"service.version":s.serviceVersion},{"telemetry.sdk.name":o,"telemetry.sdk.version":a})})(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion()),i=this._instance.getLibraryId(),r=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:Gr(n)},scopeMetrics:[{scope:{name:i,version:r},metrics:e}]}]};var e,n,i,r}Xt(t){var e=kc(Date.now()),n=new Map;for(var i of t.values()){var r,s=Cc(i.type,i.name,i.unit,void 0),o=n.get(s);o||(o=I({name:i.name},i.unit&&{unit:i.unit}),i.type==="count"?o.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:i.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:1,dataPoints:[]},n.set(s,o));var a=Gr((r=i.attributes)!==null&&r!==void 0?r:{}),l=kc(i.windowStartMs);if(i.type==="count"){var u,c={attributes:a,startTimeUnixNano:l,timeUnixNano:e,asDouble:(u=i.total)!==null&&u!==void 0?u:0};o.sum.dataPoints.push(c)}else if(i.type==="gauge"){var d,f={attributes:a,timeUnixNano:e,asDouble:(d=i.last)!==null&&d!==void 0?d:0};o.gauge.dataPoints.push(f)}else i.hist&&o.histogram.dataPoints.push({attributes:a,startTimeUnixNano:l,timeUnixNano:e,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:ho})}return Array.from(n.values())}Yt(t){var e,n;for(var i of t){var r=i[0],s=i[1],o=this.Bt.get(r);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,s.windowStartMs),o.type){case"count":o.total=((e=o.total)!==null&&e!==void 0?e:0)+((n=s.total)!==null&&n!==void 0?n:0);break;case"gauge":break;case"histogram":if(s.hist)if(o.hist){o.hist.count+=s.hist.count,o.hist.sum+=s.hist.sum,o.hist.min=Math.min(o.hist.min,s.hist.min),o.hist.max=Math.max(o.hist.max,s.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=s.hist.bucketCounts[a]}else o.hist=s.hist}else this.Qt()&&this.Bt.set(r,s)}}};var gr,Ac,po;function cg(t){var e=globalThis._posthogChunkIds;if(e){var n=Object.keys(e);return po&&n.length===Ac||(Ac=n.length,po=n.reduce(((i,r)=>{gr||(gr={});var s=gr[r];if(s)i[s[0]]=s[1];else for(var o=t(r),a=o.length-1;a>=0;a--){var l=o[a],u=l?.filename,c=e[r];if(u&&c){i[u]=c,gr[r]=[u,c];break}}return i}),{})),po}}class ug{constructor(e,n,i){i===void 0&&(i=[]),this.coercers=e,this.stackParser=n,this.modifiers=i}buildFromUnknown(e,n){n===void 0&&(n={});var i=n&&n.mechanism||{handled:!0,type:"generic"},r=this.buildCoercingContext(i,n,0).apply(e),s=this.buildParsingContext(n),o=this.parseStacktrace(r,s);return{$exception_list:this.convertToExceptionList(o,i),$exception_level:"error"}}modifyFrames(e){var n=this;return se((function*(){for(var i of e)i.stacktrace&&i.stacktrace.frames&&U(i.stacktrace.frames)&&(i.stacktrace.frames=yield n.applyModifiers(i.stacktrace.frames));return e}))()}coerceFallback(e){var n;return{type:"Error",value:"Unknown error",stack:(n=e.syntheticException)==null?void 0:n.stack,synthetic:!0}}parseStacktrace(e,n){var i,r;return e.cause!=null&&(i=this.parseStacktrace(e.cause,n)),e.stack!=""&&e.stack!=null&&(r=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?n.skipFirstLines:0),n.chunkIdMap)),I({},e,{cause:i,stack:r})}applyChunkIds(e,n){return e.map((i=>(i.filename&&n&&(i.chunk_id=n[i.filename]),i)))}applyCoercers(e,n){for(var i of this.coercers)if(i.match(e))return i.coerce(e,n);return this.coerceFallback(n)}applyModifiers(e){var n=this;return se((function*(){var i=e;for(var r of n.modifiers)i=yield r(i);return i}))()}convertToExceptionList(e,n){var i,r,s,o={type:e.type,value:e.value,mechanism:{type:(i=n.type)!==null&&i!==void 0?i:"generic",handled:(r=n.handled)===null||r===void 0||r,synthetic:(s=e.synthetic)!==null&&s!==void 0&&s}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,I({},n,{handled:!0}))),a}buildParsingContext(e){var n;return{chunkIdMap:cg(this.stackParser),skipFirstLines:(n=e.skipFirstLines)!==null&&n!==void 0?n:1}}buildCoercingContext(e,n,i){i===void 0&&(i=0);var r=(s,o)=>{if(4>=o){var a=this.buildCoercingContext(e,n,o);return this.applyCoercers(s,a)}};return I({},n,{syntheticException:i==0?n.syntheticException:void 0,mechanism:e,apply:s=>r(s,i),next:s=>r(s,i+1)})}}var ii="?";function Qo(t,e,n,i,r){var s={platform:t,filename:e,function:n===""?ii:n,in_app:!0};return C(i)||(s.lineno=i),C(r)||(s.colno=r),s}var Vd=(t,e)=>{var n=t.indexOf("safari-extension")!==-1,i=t.indexOf("safari-web-extension")!==-1;return n||i?[t.indexOf("@")!==-1?t.split("@")[0]:ii,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},dg=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,fg=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,hg=/\((\S*)(?::(\d+))(?::(\d+))\)/,pg=(t,e)=>{var n=dg.exec(t);if(n)return Qo(e,n[1],ii,+n[2],+n[3]);var i=fg.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var r=hg.exec(i[2]);r&&(i[2]=r[1],i[3]=r[2],i[4]=r[3])}var s=Vd(i[1]||ii,i[2]);return Qo(e,s[1],s[0],i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},gg=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,mg=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,vg=(t,e)=>{var n=gg.exec(t);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){var i=mg.exec(n[3]);i&&(n[1]=n[1]||"eval",n[3]=i[1],n[4]=i[2],n[5]="")}var r=n[3],s=n[1]||ii,o=Vd(s,r);return Qo(e,r=o[1],s=o[0],n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},Pc=/\(error: (.*)\)/;class _g{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,n){var i=X(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:i?e.stack:void 0,cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var n=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?n+": "+e.message:n}isDOMException(e){return Hr(e,"DOMException")}isDOMError(e){return Hr(e,"DOMError")}}class yg{match(e){return(function(n){switch({}.toString.call(n)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return wd(n,Error)}})(e)}coerce(e,n){return{type:this.getType(e),value:this.getMessage(e,n),stack:this.getStack(e),cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,n){var i=e.message;return String(i.error&&typeof i.error.message=="string"?i.error.message:i)}getStack(e){return e.stacktrace||e.stack||void 0}}class wg{constructor(){}match(e){return!!Hr(e,"ErrorEvent")&&(e.error!=null||this.fe(e))}coerce(e,n){var i;if(e.error!=null)return n.apply(e.error);var r=n.apply(e.message);return I({},r,{stack:(i=this.pe(e))!==null&&i!==void 0?i:r.stack,synthetic:!0})}fe(e){return X(e.message)&&e.message.length>0}pe(e){var n=e;if(X(n.filename)&&n.filename.length>0){var i,r,s=(i=n.lineno)!==null&&i!==void 0?i:0,o=(r=n.colno)!==null&&r!==void 0?r:0;return`Error + at `+n.filename+":"+s+":"+o}}}var bg=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class Eg{match(e){return typeof e=="string"}coerce(e,n){var i,r=this.getInfos(e),s=r[0],o=r[1];return{type:s??"Error",value:o??e,stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}getInfos(e){var n="Error",i=e,r=e.match(bg);return r&&(n=r[1],i=r[2]),[n,i]}}var Sg=["fatal","error","warning","log","info","debug"];function Gd(t,e){e===void 0&&(e=40);var n=Object.keys(t);if(n.sort(),!n.length)return"[object has no keys]";for(var i=n.length;i>0;i--){var r=n.slice(0,i).join(", ");if(e>=r.length)return i===n.length?r:r.length>e?r.slice(0,e)+"...":r}return""}class xg{match(e){return typeof e=="object"&&e!==null}coerce(e,n){var i,r,s=this.getErrorPropertyFromObject(e);return s?n.apply(s):{type:this.getType(e),value:this.getValue(e),stack:(i=this.getStack(e))!==null&&i!==void 0?i:(r=n.syntheticException)==null?void 0:r.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return Qa(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var n="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(n+=" with message: '"+e.message+"'"),n}if("message"in e&&typeof e.message=="string")return e.message;var i=this.getObjectClassName(e);return(i&&i!=="Object"?"'"+i+"'":"Object")+" captured as exception with keys: "+Gd(e)}isSeverityLevel(e){return X(e)&&!Ko(e)&&Sg.indexOf(e)>=0}getStack(e){try{return X(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:X(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(var n in e)if({}.hasOwnProperty.call(e,n)){var i=e[n];if(rg(i))return i}}getObjectClassName(e){try{var n=Object.getPrototypeOf(e);return n?n.constructor.name:void 0}catch{return}}}class Ig{match(e){return Qa(e)}coerce(e,n){var i,r=e.constructor.name;return{type:r,value:r+" captured as exception with keys: "+Gd(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class kg{match(e){return yd(e)}coerce(e,n){var i;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class Cg{match(e){return Hr(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Qa(e))return!1;try{var n=e.detail;return n!=null&&typeof n=="object"&&"reason"in n}catch{return!1}}coerce(e,n){var i,r=this.getUnhandledRejectionReason(e);return yd(r)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(r),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}:n.apply(r)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}}var Kr="$message",Yr="$timestamp",Ag=new Set([Kr,Yr]),go={enabled:!0,max_bytes:32768};function Jr(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:go.enabled,max_bytes:Fg(t.max_bytes,go.max_bytes)}:I({},go)}class Pg{constructor(e){this.Ke=[],this.Je=0,this.Ne=Jr(e)}setConfig(e){this.Ne=Jr(e),this.Xe()}add(e){var n=(function(r){var s;try{s=md(r)}catch{return}try{var o=JSON.parse(s);if(!he(o))return;var a=o,l=a[Kr],u=a[Yr];return!X(l)||l.trim().length===0||!X(u)&&!ke(u)?void 0:{step:a,json:s}}catch{return}})(e);if(n){var i=(function(r){if(typeof TextEncoder<"u")return new TextEncoder().encode(r).length;for(var s=encodeURIComponent(r),o=0,a=0;s.length>a;a++)s[a]==="%"?(o+=1,a+=2):o+=1;return o})(n.json);i>this.Ne.max_bytes||(this.Ke.push({step:n.step,bytes:i}),this.Je+=i,this.Xe())}}getAttachable(){return this.Ke.map((e=>e.step))}clear(){this.Ke=[],this.Je=0}size(){return this.Ke.length}Xe(){for(;this.Je>this.Ne.max_bytes&&this.Ke.length>0;){var e=this.Ke.shift();e&&(this.Je-=e.bytes)}}}function Fg(t,e){if(!ke(t)||t===1/0||t===-1/0)return e;var n=Math.floor(t);return 0>n?e:n}var Kd=function(t,e){var n=(e===void 0?{}:e).debugEnabled,i={k(r){if(w&&(ne.DEBUG||w.POSTHOG_DEBUG||n)&&!C(w.console)&&w.console){for(var s=("__rrweb_original__"in w.console[r])?w.console[r].__rrweb_original__:w.console[r],o=arguments.length,a=new Array(o>1?o-1:0),l=1;o>l;l++)a[l-1]=arguments[l];s(t,...a)}},debug(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("debug",...s)},info(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("log",...s)},warn(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("warn",...s)},error(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("error",...s)},critical(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];console.error(t,...s)},uninitializedWarning(r){i.error("You must initialize PostHog before calling "+r)},createLogger:(r,s)=>Kd(t+" "+r,s)};return i},A=Kd("[PostHog.js]"),pe=A.createLogger,Rg=pe("[ExternalScriptsLoader]"),mo=(t,e,n)=>{if(t.config.disable_external_dependency_loading)return Rg.warn(e+" was requested but loading of external scripts is disabled."),n("Loading of external scripts is disabled");var i=P?.querySelectorAll("script");if(i){for(var r,s=function(){if(i[o].src===e){var l=i[o];return l.__posthog_loading_callback_fired?{v:n()}:(l.addEventListener("load",(u=>{l.__posthog_loading_callback_fired=!0,n(void 0,u)})),l.onerror=u=>n(u),{v:void 0})}},o=0;i.length>o;o++)if(r=s())return r.v}var a=()=>{if(!P)return n("document not found");var l=P.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=d=>{l.__posthog_loading_callback_fired=!0,n(void 0,d)},l.onerror=d=>n(d),t.config.prepare_external_dependency_script&&(l=t.config.prepare_external_dependency_script(l)),!l)return n("prepare_external_dependency_script returned null");if(t.config.external_scripts_inject_target==="head")P.head.appendChild(l);else{var u,c=P.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):P.body.appendChild(l)}};P!=null&&P.body?a():P?.addEventListener("DOMContentLoaded",a)};B.__PosthogExtensions__=B.__PosthogExtensions__||{},B.__PosthogExtensions__.loadExternalDependency=(t,e,n)=>{if(e!=="remote-config"){var i;if(t.config.strict_script_versioning)i=t.requestRouter.endpointFor("assets","/static/"+t.version+"/"+e+".js");else{var r="/static/"+e+".js?v="+t.version;if(e==="toolbar"){var s=3e5;r=r+"&t="+Math.floor(Date.now()/s)*s}i=t.requestRouter.endpointFor("assets",r)}mo(t,i,n)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");mo(t,o,n)}},B.__PosthogExtensions__.loadSiteApp=(t,e,n)=>{var i=t.requestRouter.endpointFor("api",e);mo(t,i,n)};ne.DEBUG=!1,ne.LIB_VERSION="1.415.7",ne.LIB_NAME="web";var Yd="$people_distinct_id",Ji="$device_id",vo="$device_model",Ri="__alias",Ti="__timers",ea="$autocapture_disabled_server_side",ta="$heatmaps_enabled_server_side",na="$exception_capture_enabled_server_side",ia="$error_tracking_suppression_rules",ra="$error_tracking_capture_extension_exceptions",sa="$web_vitals_enabled_server_side",sl="$dead_clicks_enabled_server_side",ol="$product_tours_enabled_server_side",oa="$web_vitals_allowed_metrics",An="$session_recording_remote_config",Jd="$replay_sample_rate",Zd="$replay_override_sampling",Xd="$replay_override_linked_flag",Qd="$replay_override_url_trigger",ef="$replay_override_event_trigger",Yn="$sesid",al="$session_is_sampled",Sn="$enabled_feature_flags",$i="$active_feature_flags",Ar="$early_access_features",aa="$feature_flag_details",Mi="$feature_flag_payloads",Pr="$feature_flag_request_id",Zr="$minimal_flag_called_events",It="$override_feature_flags",xn="$override_feature_flag_payloads",jt="$stored_person_properties",In="$stored_group_properties",la="$surveys",Xr="$surveys_loaded_at",ca="$surveys_activated",Fr="$surveys_activated_session",Rr="$surveys_activated_timestamps",Li="ph_product_tours",Cn="$flag_call_reported",Ni="$flag_call_reported_session_id",Tr="$feature_flag_errors",Ui="$feature_flag_evaluated_at",at="$user_state",ua="$client_session_props",da="$capture_rate_limit",fa="$initial_campaign_params",ha="$initial_referrer_info",Qr="$initial_person_info",es="$epp",mr="$posthog_cookieless",tf="$cookieless_mode",nf="$sdk_debug_extensions_init_method",rf="$sdk_debug_extensions_init_time_ms",sf="$sdk_debug_recording_script_not_loaded",ll="PostHog loadExternalDependency extension not found.",kn="on_reject",Wt="always",Hn="anonymous",vn="identified",pa="identified_only",ts="visibilitychange",ns="beforeunload",Gn="$pageview",_o="$pageleave",yo="$identify",Fc="$groupidentify";function vr(t,e){U(t)&&t.forEach(e)}function ie(t,e){if(!H(t))if(U(t))t.forEach(e);else if(Hp(t))t.forEach(((i,r)=>e(i,r)));else for(var n in t)_d.call(t,n)&&e(t[n],n)}var fe=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;e>i;i++)n[i-1]=arguments[i];for(var r of n)for(var s in r)r[s]!==void 0&&(t[s]=r[s]);return t};function $r(t){for(var e=Object.keys(t),n=e.length,i=new Array(n);n--;)i[n]=[e[n],t[e[n]]];return i}var Rc=function(t){try{return t()}catch{return}},Tg=function(t){return function(){try{for(var e=arguments.length,n=new Array(e),i=0;e>i;i++)n[i]=arguments[i];return t.apply(this,n)}catch(r){A.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),A.critical(r)}}},cl=function(t){var e={};return ie(t,(function(n,i){(X(n)&&n.length>0||ke(n))&&(e[i]=n)})),e},$g=["herokuapp.com","vercel.app","netlify.app"];function Mg(t){var e=t?.hostname;if(!X(e))return!1;var n=e.split(".").slice(-2).join(".");for(var i of $g)if(n===i)return!1;return!0}function ve(t,e,n,i){var r=i??{},s=r.capture,o=r.passive;t?.addEventListener(e,n,{capture:s!==void 0&&s,passive:o===void 0||o})}function ga(t){return t.name==="ph_toolbar_internal"}var of=t=>{if(P){try{for(var e=t+"=",n=P.cookie.split(";").filter((s=>s.length)),i=0;n.length>i;i++){for(var r=n[i];r.charAt(0)==" ";)r=r.substring(1,r.length);if(r.indexOf(e)===0)return decodeURIComponent(r.substring(e.length,r.length))}}catch{}return null}};Math.trunc||(Math.trunc=function(t){return 0>t?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return ke(t)&&isFinite(t)&&Math.floor(t)===t});class is{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,n,i,r){if(!Number.isInteger(e)||!Number.isInteger(n)||!Number.isInteger(i)||!Number.isInteger(r)||0>e||0>n||0>i||0>r||e>0xffffffffffff||n>4095||i>1073741823||r>4294967295)throw new RangeError("invalid field value");var s=new Uint8Array(16);return s[0]=e/Math.pow(2,40),s[1]=e/Math.pow(2,32),s[2]=e/Math.pow(2,24),s[3]=e/Math.pow(2,16),s[4]=e/256,s[5]=e,s[6]=112|n>>>8,s[7]=n,s[8]=128|i>>>24,s[9]=i>>>16,s[10]=i>>>8,s[11]=i,s[12]=r>>>24,s[13]=r>>>16,s[14]=r>>>8,s[15]=r,new is(s)}toString(){for(var e="",n=0;this.bytes.length>n;n++)e=e+(this.bytes[n]>>>4).toString(16)+(15&this.bytes[n]).toString(16),n!==3&&n!==5&&n!==7&&n!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new is(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var n=0;16>n;n++){var i=this.bytes[n]-e.bytes[n];if(i!==0)return Math.sign(i)}return 0}}class Lg{generate(){var e=this.generateOrAbort();if(!C(e))return e;this.S=0;var n=this.generateOrAbort();if(C(n))throw new Error("Could not generate UUID after timestamp reset");return n}generateOrAbort(){var e=Date.now();if(e>this.S)this.S=e,this.C();else{if(this.S>=e+1e4)return;this.I++,this.I>4398046511103&&(this.S++,this.C())}return is.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 Ng}}var Tc,af=t=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;t.length>e;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};w&&!C(w.crypto)&&crypto.getRandomValues&&(af=t=>crypto.getRandomValues(t));class Ng{nextUint32(){return this.R.length>this.O||(af(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var Ht=()=>Og().toString(),Og=()=>(Tc||(Tc=new Lg)).generate(),wi="",Bg=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,zt={N:()=>!!P,j(t){A.error("cookieStore error: "+t)},P:of,H(t){var e;try{e=JSON.parse(zt.P(t))||{}}catch{}return e},F(t,e,n,i,r){if(!P)return!1;try{var s="",o="",a=(function(c,d){if(d){var f=(function(p,g){if(g===void 0&&(g=P),wi)return wi;if(!g||["localhost","127.0.0.1"].includes(p))return"";for(var m=p.split("."),v=Math.min(m.length,8),E="dmn_chk_"+Ht();!wi&&v--;){var S=m.slice(v).join("."),_=E+"=1;domain=."+S+";path=/";g.cookie=_+";max-age=3",g.cookie.includes(E)&&(g.cookie=_+";max-age=0",wi=S)}return wi})(c);if(!f){var h=(p=>{var g=p.match(Bg);return g?g[0]:""})(c);h!==f&&A.info("Warning: cookie subdomain discovery mismatch",h,f),f=h}return f?"; domain=."+f:""}return""})(P.location.hostname,i);if(n){var l=new Date;l.setTime(l.getTime()+864e5*n),s="; expires="+l.toUTCString()}r&&(o="; secure");var u=t+"="+encodeURIComponent(JSON.stringify(e))+s+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&A.warn("cookieStore warning: large cookie, len="+u.length),P.cookie=u,!0}catch{return!1}},q(t,e){if(P!=null&&P.cookie)try{zt.F(t,"",-1,e)}catch{return}}},wo=null,le={N(){if(!Ye(wo))return wo;var t=!0;if(C(w))t=!1;else try{var e="__mplssupport__";le.F(e,"xyz"),le.P(e)!=='"xyz"'&&(t=!1),le.q(e)}catch{t=!1}return t||A.error("localStorage unsupported; falling back to cookie store"),wo=t,t},j(t){A.error("localStorage error: "+t)},P(t){try{return w?.localStorage.getItem(t)}catch(e){le.j(e)}return null},H(t){try{return JSON.parse(le.P(t))||{}}catch{}return null},F(t,e){try{return w?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(n){le.j(n)}return!1},q(t){try{w?.localStorage.removeItem(t)}catch(e){le.j(e)}}},Dg=[Ji,"distinct_id",Yn,al,es,Qr,at],_r={},jg={N:()=>!0,j(t){A.error("memoryStorage error: "+t)},P:t=>_r[t]||null,H:t=>_r[t]||null,F:(t,e)=>(_r[t]=e,!0),q(t){delete _r[t]}},_n=null,be={N(){if(!Ye(_n))return _n;if(_n=!0,C(w))_n=!1;else try{var t="__support__";be.F(t,"xyz"),be.P(t)!=='"xyz"'&&(_n=!1),be.q(t)}catch{_n=!1}return _n},j(t){A.error("sessionStorage error: ",t)},P(t){try{return w?.sessionStorage.getItem(t)}catch(e){be.j(e)}return null},H(t){try{return JSON.parse(be.P(t))||null}catch{}return null},F(t,e){try{return w?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(n){be.j(n)}return!1},q(t){try{w?.sessionStorage.removeItem(t)}catch(e){be.j(e)}}};class Ug{constructor(e){this._instance=e}get Ne(){return this._instance.config}get consent(){return this.ti()?0:this.ei}isOptedOut(){return this.Ne.cookieless_mode===Wt||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===kn}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===0}isRejected(){return this.consent===0||this.consent===-1&&this.Ne.opt_out_capturing_by_default}optInOut(e){this.ii.F(this.ri,e?1:0,this.Ne.cookie_expiration,this.Ne.cross_subdomain_cookie,this.Ne.secure_cookie)}reset(){this.ii.q(this.ri,this.Ne.cross_subdomain_cookie)}get ri(){var e=this._instance.config,n=e.token,i=e.opt_out_capturing_cookie_prefix;return e.consent_persistence_name||(i?i+n:"__ph_opt_in_out_"+n)}get ei(){var e=this.ii.P(this.ri);return uo(e)?1:j(Vp,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,n=e==="localStorage"?le:zt;if(!this.ni||this.ni!==n){this.ni=n;var i=e==="localStorage"?zt:le;i.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(uo(i.P(this.ri))),i.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[He?.doNotTrack,He?.msDoNotTrack,B.doNotTrack].some((e=>uo(e)))}}function lf(t,e){var n,i=t==null||(n=t.config)==null?void 0:n.get_current_url;if(!je(i))return e;try{var r=i(e);return X(r)&&r?r:e}catch(s){return A.error("Error in get_current_url, falling back to window.location.href",s),e}}var cf="__POSTHOG_TOOLBAR__",Hg=1,Wg=3,zg=11;function $c(t){return t instanceof Element&&(t.id===cf||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function hn(t){return!!t&&t.nodeType===Hg}function et(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function uf(t){return!!t&&t.nodeType===Wg}function df(t){return!!t&&t.nodeType===zg&&hn(t.host)}var ff=1e3;function ul(t){return t?xs(t).split(/\s+/):[]}function Mc(t,e){var n=(function(i){var r,s=w==null||(r=w.location)==null?void 0:r.href;return C(s)?void 0:lf(i,s)})(e);return!!(n&&t&&t.some((i=>n.match(i))))}function rs(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 ul(e)}function hf(t){return H(t)?null:xs(t).split(/(\s+)/).filter((e=>Hi(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function Zi(t){var e="";return va(t)&&!vf(t)&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;uf(n)&&n.textContent&&(e+=(i=hf(n.textContent))!==null&&i!==void 0?i:"")})),xs(e)}function bo(t){var e;return C(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var dl=["a","button","form","input","select","textarea","label"];function ma(t,e){if(C(e))return!0;var n,i=function(s){if(e.some((o=>(function(a,l){var u=a.matches||a.matchesSelector||a.msMatchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.oMatchesSelector;try{return!!u&&u.call(a,l)}catch{return!1}})(s,o))))return{v:!0}};for(var r of t)if(n=i(r))return n.v;return!1}function pf(t){var e=t.parentNode;return!(!e||!hn(e))&&e}var qg=[".ph-no-autocapture","[data-ph-no-autocapture]"],gf=["next","previous","prev",">","<"],Vg=[...gf,"+","-","−","–"],Lc=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,Nc=[".ph-no-rageclick",".ph-no-capture"],Gg=["","text","search","email","password","url","tel","number"];function Oc(t,e){if(!w||fl(t))return!1;var n,i,r,s,o;if(mt(e)?(n=!!e&&Nc,i=void 0,r=!1):(n=(s=e?.css_selector_ignorelist)!==null&&s!==void 0?s:Nc,i=e?.content_ignorelist,r=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),n===!1||r&&(function(l){return!(!l||!hn(l))&&(!!et(l,"textarea")||(et(l,"input")?j(Gg,(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=mf(t,!1).targetElementList;return!(function(l,u){if(l===!1||C(l))return!1;var c;if(l===!0)c=gf;else{if(!U(l))return!1;if(l.length>10)return A.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var f=d.safeText,h=d.ariaLabel;return c.some((p=>Lc(f,p)||Lc(h,p)))}))})(i,a.map((l=>{var u;return{safeText:Zi(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!ma(a,n)}var fl=t=>!t||et(t,"html")||!hn(t),mf=(t,e)=>{if(!w||fl(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,i=[t],r=t;r.parentNode&&!et(r,"body");)if(df(r.parentNode))i.push(r.parentNode.host),r=r.parentNode.host;else{var s=pf(r);if(!s)break;if(e||dl.indexOf(s.tagName.toLowerCase())>-1)n=!0;else try{var o=w.getComputedStyle(s);o&&o.getPropertyValue("cursor")==="pointer"&&(n=!0)}catch{}i.push(s),r=s}return{parentIsUsefulElement:n,targetElementList:i}};function va(t){for(var e=new Set,n=0,i=t;i.parentNode&&!et(i,"body");i=i.parentNode){if(n++>=ff||e.has(i))return!1;e.add(i);var r=rs(i);if(j(r,"ph-sensitive")||j(r,"ph-no-capture"))return!1}if(j(rs(t),"ph-include"))return!0;var s=t.type||"";if(X(s))switch(s.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!X(o)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(o.replace(/[^a-zA-Z0-9]/g,""))}function vf(t){return!!(et(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||et(t,"select")||et(t,"textarea")||t.getAttribute("contenteditable")==="true")}var Bc=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}))$"),Dc=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,Kg=[16,15,14,13],Yg=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),jc=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),Uc=/[0-9A-Za-z_]/;function Jg(t){for(var e=0,n=!1,i=t.length-1;i>=0;i--){var r=t.charCodeAt(i)-48;n&&(r*=2)>9&&(r-=9),e+=r,n=!n}return e%10==0}function Hi(t,e){if(e===void 0&&(e=!0),H(t))return!1;if(X(t)){t=xs(t);var n=e?Bc.test((t||"").replace(/[- ]/g,"")):(function(r){var s;for(Dc.lastIndex=0;s=Dc.exec(r);){var o=s[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of Kg){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(Bc.test(d)&&Jg(d))return!0}}}return!1})(t);if(n)return!1;var i=e?Yg.test(t):(function(r){var s;for(jc.lastIndex=0;s=jc.exec(r);){var o=s[1],a=s[3];if(!(o&&a&&Uc.test(o)&&Uc.test(a)))return!0}return!1})(t);if(i)return!1}return!0}function Hc(t){var e=Zi(t);return Hi(e=(e+" "+_f(t)).trim())?e:""}function _f(t){var e="";return t&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;if(n&&((i=n.tagName)==null?void 0:i.toLowerCase())==="span")try{var r=Zi(n);e=(e+" "+r).trim(),n.childNodes&&n.childNodes.length&&(e=(e+" "+_f(n)).trim())}catch(s){A.error("[AutoCapture]",s)}})),e}function Wc(t){return t.replace(/"|\\"/g,'\\"')}function Zg(t){var e=t.attr__class;if(e)return U(e)?e:ul(e)}var yr=pe("[Dead Clicks]"),Xg=()=>!0,Qg=t=>{var e,n=!((e=t.instance.persistence)==null||!e.get_property(sl)),i=t.instance.config.capture_dead_clicks;return mt(i)?i:!!he(i)||n};class zc{get lazyLoadedDeadClicksAutocapture(){return this.si}constructor(e,n,i){this.instance=e,this.isEnabled=n,this.onCapture=i,this.startIfEnabledOrStop()}onRemoteConfig(e){if(e.ok){var n=e.config;"captureDeadClicks"in n&&(this.instance.persistence&&this.instance.persistence.register({[sl]:n.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var n,i;(n=B.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture?e():(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"dead-clicks-autocapture",(r=>{r?yr.error("failed to load script",r):e()}))}oi(){var e;if(P){if(!this.si&&(e=B.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var n=he(this.instance.config.capture_dead_clicks)?I({},this.instance.config.capture_dead_clicks):{};n.__onCapture=this.onCapture,this.onCapture&&(n.capture_dead_swipes=!1),this.si=B.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.si.start(P),yr.info("starting...")}}else yr.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,yr.info("stopping..."))}}var Eo=pe("[SegmentIntegration]"),yf="posthog-js";function wf(t,e){var n=e===void 0?{}:e,i=n.organization,r=n.projectId,s=n.prefix,o=n.severityAllowList,a=o===void 0?["error"]:o,l=n.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,f,h,p,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var v,E=((d=c.exception)==null?void 0:d.values)||[],S=E.map((b=>I({},b,{stacktrace:b.stacktrace?I({},b.stacktrace,{type:"raw",frames:(b.stacktrace.frames||[]).map((k=>I({},k,{platform:"web:javascript"})))}):void 0}))),_={$exception_message:((f=E[0])==null?void 0:f.value)||c.message,$exception_type:(h=E[0])==null?void 0:h.type,$exception_level:c.level,$exception_list:S,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((p=E[0])==null?void 0:p.value)||c.message,$sentry_exception_type:(g=E[0])==null?void 0:g.type,$sentry_tags:c.tags};return i&&r&&(_.$sentry_url=(s||"https://sentry.io/organizations/")+i+"/issues/?project="+r+"&query="+c.event_id),u&&((v=t.exceptions)==null||v.sendExceptionEvent(_)),c}}class em{constructor(e,n,i,r,s,o){this.name=yf,this.setupOnce=function(a){a(wf(e,{organization:n,projectId:i,prefix:r,severityAllowList:s,sendExceptionsToPostHog:o==null||o}))}}}class qc{constructor(e){this.li=(n,i,r)=>{r&&(r.noSessionId||r.activityTimeout||r.sessionPastMaximumLength||r.crossTabAdoption)&&(A.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:n,changeReason:r}),this.ui=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.hi()}hi(){var e;this.di=(e=this._instance.sessionManager)==null?void 0:e.onSessionId(this.li)}destroy(){var e;(e=this.di)==null||e.call(this),this.di=void 0}doPageView(e,n){var i,r=this.vi(e,n);return this.ui={pathname:(i=w?.location.pathname)!==null&&i!==void 0?i:"",pageViewId:n,timestamp:e},this._instance.scrollManager.resetContext(),r}doPageLeave(e){var n;return this.vi(e,(n=this.ui)==null?void 0:n.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.ui)==null?void 0:e.pageViewId}}vi(e,n){var i=this.ui;if(!i)return{$pageview_id:n};var r={$pageview_id:n,$prev_pageview_id:i.pageViewId},s=this._instance.scrollManager.getContext();if(s&&!this._instance.config.disable_scroll_properties){var o=s.maxScrollHeight,a=s.lastScrollY,l=s.maxScrollY,u=s.maxContentHeight,c=s.lastContentY,d=s.maxContentY;if(!(C(o)||C(a)||C(l)||C(u)||C(c)||C(d))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),d=Math.ceil(d);var f=o>1?At(a/o,0,1,A):1,h=o>1?At(l/o,0,1,A):1,p=u>1?At(c/u,0,1,A):1,g=u>1?At(d/u,0,1,A):1;r=fe(r,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:f,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:h,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:p,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return i.pathname&&(r.$prev_pageview_pathname=i.pathname),i.timestamp&&(r.$prev_pageview_duration=(e.getTime()-i.timestamp.getTime())/1e3),r}}var So=["flags","surveys"],tm={[Yd]:{exposure:"hidden"},[Ri]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[Ti]:{exposure:"hidden"},[ea]:{exposure:"event"},[ta]:{exposure:"hidden"},[na]:{exposure:"event"},[ia]:{exposure:"hidden"},[ra]:{exposure:"event"},[sa]:{exposure:"event"},[sl]:{exposure:"event"},[ol]:{exposure:"hidden"},[oa]:{exposure:"event"},[An]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[Yn]:{exposure:"hidden"},[al]:{exposure:"event"},[Jd]:{exposure:"event",shouldSkipFromEventProperties:t=>Ye(t)},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},$sess_rec_flush_size:{exposure:"hidden"},[Sn]:{exposure:"hidden",storageGroup:"flags"},[$i]:{exposure:"hidden",storageGroup:"flags"},[Ar]:{exposure:"hidden"},[aa]:{exposure:"hidden",storageGroup:"flags"},[Mi]:{exposure:"hidden",storageGroup:"flags"},[Pr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[Zr]:{exposure:"hidden",storageGroup:"flags"},[It]:{exposure:"hidden"},[xn]:{exposure:"hidden"},[jt]:{exposure:"hidden"},[In]:{exposure:"hidden"},[la]:{exposure:"hidden",storageGroup:"surveys"},[Xr]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[ca]:{exposure:"event"},[Fr]:{exposure:"hidden"},[Rr]:{exposure:"hidden"},[Li]:{exposure:"hidden"},$product_tours_activated:{exposure:"hidden"},$product_tours_activated_session:{exposure:"hidden"},$conversations_widget_session_id:{exposure:"event"},$conversations_ticket_id:{exposure:"event"},$conversations_widget_state:{exposure:"event"},$conversations_user_traits:{exposure:"event"},[Cn]:{exposure:"hidden"},[Ni]:{exposure:"hidden"},[Tr]:{exposure:"hidden"},[Ui]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[at]:{exposure:"hidden"},[ua]:{exposure:"hidden"},[da]:{exposure:"hidden"},[fa]:{exposure:"hidden"},[ha]:{exposure:"hidden"},[Qr]:{exposure:"hidden"},[es]:{exposure:"hidden"},[Zd]:{exposure:"event"},[Xd]:{exposure:"event"},[Qd]:{exposure:"event"},[ef]:{exposure:"event"},[nf]:{exposure:"event"},[rf]:{exposure:"event"},[sf]:{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"}},nm=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],yn=t=>{var e=tm[t];if(e)return e;for(var n of nm){var i=n[1];if(t.indexOf(n[0])===0)return i}},Jn=(t,e)=>{try{return JSON.stringify(t,((n,i)=>typeof i=="bigint"?i.toString():i),e)}catch{return md(t)}},ss=t=>{var e=P?.createElement("a");return C(e)?null:(e.href=t,e)},ri=function(t,e){for(var n,i=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),r=0;i.length>r;r++){var s=i[r].split("=");if(s[0]===e){n=s;break}}if(!U(n)||2>n.length)return"";var o=n[1];try{o=decodeURIComponent(o)}catch{A.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},Xi=function(t,e,n){if(!t||!e||!e.length)return t;for(var i=t.split("#"),r=i[1],s=(i[0]||"").split("?"),o=s[1],a=s[0],l=(o||"").split("&"),u=[],c=0;l.length>c;c++){var d=l[c].split("=");U(d)&&(e.includes(d[0])?u.push(d[0]+"="+n):u.push(l[c]))}var f=a;return o!=null&&(f+="?"+u.join("&")),r!=null&&(f+="#"+r),f},os=function(t,e){var n=t.match(new RegExp(e+"=([^&]*)"));return n?n[1]:null},bf=(t,e)=>t>=e&&hd(),Ef=(t,e,n,i)=>{if(t===0){if(hd()){var r=e+1;return r===n&&i(),r}return e}return 0},wr="https?://(.*)",si=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],im=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...si],Qi="",rm=["li_fat_id"];function Sf(t,e,n){if(!P)return{};var i,r=e?[...si,...n||[]]:[],s=xf(Xi(P.URL,r,Qi),t),o=(i={},ie(rm,(function(a){var l=of(a);i[a]=l||null})),i);return fe(o,s)}function xf(t,e){var n=im.concat(e||[]),i={};return ie(n,(function(r){var s=ri(t,r);i[r]=s||null})),i}function If(t){var e=(function(s){return s?s.search(wr+"google.([^/?]*)")===0?"google":s.search(wr+"bing.com")===0?"bing":s.search(wr+"yahoo.com")===0?"yahoo":s.search(wr+"duckduckgo.com")===0?"duckduckgo":null:null})(t),n=e!="yahoo"?"q":"p",i={};if(!Ye(e)){i.$search_engine=e;var r=P?ri(P.referrer,n):"";r.length&&(i.ph_keyword=r)}return i}function Vc(){return navigator.language||navigator.userLanguage}var as="$direct";function kf(){return P?.referrer||as}function Cf(t,e,n){n===void 0&&(n=!1);var i=t?[...si,...e||[]]:[],r=n?fn(me?.href):me?.href,s=r?.substring(0,1e3);return{r:kf().substring(0,1e3),u:s?Xi(s,i,Qi):void 0}}function Af(t,e){var n;e===void 0&&(e=!1);var i=t.r,r=t.u,s=e?fn(r):r,o={$referrer:i,$referring_domain:i==null?void 0:i==as?as:(n=ss(i))==null?void 0:n.host};if(s){o.$current_url=s;var a=ss(s);o.$host=a?.host,o.$pathname=a?.pathname;var l=xf(s);fe(o,l)}if(i){var u=If(i);fe(o,u)}return o}function Pf(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function sm(){try{return new Date().getTimezoneOffset()}catch{return}}var om={flags:Ui,surveys:Xr},am=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],Wn="main";class xo{constructor(e,n,i){if(i===void 0&&(i=!0),this.ci={},this.fi=!1,this.pi=!1,this.Ne=e,this.gi=i,this.props={},this.mi=void 0,this.yi=(s=>{var o="";return s.token&&(o=s.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),s.persistence_name?"ph_"+s.persistence_name:"ph_"+o+"_posthog"})(e),this.ii=this.bi(e),this.pi=this.wi(e),this.load(),e.debug&&A.info("Persistence loaded",e.persistence,I({},this.props)),this.update_config(e,e,n),this.save(),w){var r=()=>this.flush();ve(w,"beforeunload",r,{capture:!1}),ve(w,"pagehide",r,{capture:!1})}}ki(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return ke(n)&&n>0?n:0}isDisabled(){return!!this.xi}bi(e){am.indexOf(e.persistence.toLowerCase())===-1&&(A.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var n,i=(function(o,a){o===void 0&&(o=[]),a===void 0&&(a=!1);var l=[...Dg,...o];return I({},le,{H(u){try{var c={};try{c=zt.H(u)||{}}catch{}var d,f=JSON.parse(le.P(u)||"{}");if(a){var h={};for(var p in c){var g=c[p];Ye(g)||g===""||(h[p]=g)}d=fe(f,h)}else d=fe(c,f);return le.F(u,d),d}catch{}return null},F(u,c,d,f,h,p){var g=le.F(u,c,void 0,void 0,p);try{var m={};l.forEach((v=>{c[v]&&(m[v]=c[v])})),Object.keys(m).length&&zt.F(u,m,d,f,h,p)}catch(v){le.j(v)}return g},q(u,c){try{w?.localStorage.removeItem(u),zt.q(u,c)}catch(d){le.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),r=!1,s=e.persistence.toLowerCase();return s==="localstorage"&&le.N()?(n=le,r=!0):s==="localstorage+cookie"&&i.N()?(n=i,r=!0):s==="sessionstorage"&&be.N()?n=be:s==="memory"?n=jg:s==="cookie"?n=zt:i.N()?(n=i,r=!0):n=zt,this.fi=r,n}Si(e){return this.yi+"__"+e}wi(e){return this.fi&&!!e.split_storage}properties(){var e={};return ie(this.props,((n,i)=>{var r=yn(i);if(!r||r.exposure==="event"){if(r!=null&&r.shouldSkipFromEventProperties!=null&&r.shouldSkipFromEventProperties(n))return;e[i]=n}})),e}load(){if(!this.xi){var e=this.ii.H(this.yi);e&&(this.props=fe({},e)),this.pi&&this.Ci()}}Ci(){for(var e of So){var n=le.H(this.Si(e));if(n&&!Kt(n)){var i=this.Mi(e);i.persisted=!0,this.Ti(e)||(i.fingerprint=this.Ei(n,e)),this.Ii(e,n)||fe(this.props,n)}}}Ti(e){return Object.keys(this.props).some((n=>{var i;return((i=yn(n))==null?void 0:i.storageGroup)===e}))}Ii(e,n){var i=om[e];if(!i)return!1;var r=n[i],s=this.props[i];return ke(r)&&ke(s)&&s>r}refreshKey(e){var n;if(!this.xi){var i=this.pi?(n=yn(e))==null?void 0:n.storageGroup:void 0,r=i?le.H(this.Si(i)):this.ii.H(this.yi);if(r&&e in r)this.Pi(e,r[e]);else{if(i){var s=this.ii.H(this.yi);if(s&&e in s)return void this.Pi(e,s[e])}this.Ri(e)}}}save(){if(!this.xi){var e=this.ki();e>0?C(this.Ai)&&(this.Ai=setTimeout((()=>{this.Ai=void 0,this.Fi()}),e)):this.Fi()}}flush(){C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0,this.Fi())}Fi(){this.xi||(this.pi?this.Li():this.Oi(this.ii,this.yi,this.props,Wn))}Li(){var e=this.Di(),n=e.main,i=e.groups;for(var r of(this.Oi(this.ii,this.yi,n,Wn),So)){var s,o=i[r];(!Kt(o)||(s=this.ci[r])!=null&&s.persisted)&&this.Oi(le,this.Si(r),o,r)}}Di(){var e={},n={flags:{},surveys:{}};return ie(this.props,((i,r)=>{var s,o=(s=yn(r))==null?void 0:s.storageGroup;o?n[o][r]=i:e[r]=i})),{main:e,groups:n}}Ei(e,n){if(n===Wn)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var i={};return ie(e,((r,s)=>{var o;i[s]=(o=yn(s))!=null&&o.volatile?"__volatile__":r})),JSON.stringify(i)}Oi(e,n,i,r){var s=this.Mi(r);if(r===Wn||s.dirty||C(s.fingerprint)){var o;try{if((o=this.Ei(i,r))===s.fingerprint)return void(s.dirty=!1)}catch{o=void 0}e.F(n,i,this.$i,this.Ni,this.qi,this.Ne.debug)?(s.dirty=!1,r!==Wn&&(s.persisted=!0),C(o)||(s.fingerprint=o)):this.Ne.debug&&A.warn('failed to persist storage entry "'+n+'"; will retry on next save')}}remove(e){var n=(e===void 0?{}:e).keepGroupEntries,i=n!==void 0&&n;if(C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0),this.ii.q(this.yi,!1),this.ii.q(this.yi,!0),!i&&this.gi)for(var r of So)le.q(this.Si(r));i?delete this.ci[Wn]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,n,i){if(he(e)){C(n)&&(n="None"),this.$i=C(i)?this.ji:i;var r=!1;if(ie(e,((s,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==n||(this.Pi(o,s),r=!0)})),r)return this.save(),!0}return!1}register(e,n){if(he(e)){this.$i=C(n)?this.ji:n;var i=!1;if(ie(e,((r,s)=>{e.hasOwnProperty(s)&&(this.props[s]!==r||he(r)||U(r))&&(this.Pi(s,r),i=!0)})),i)return this.save(),!0}return!1}unregister(e){var n=typeof e=="string"?[e]:e,i=!1;for(var r of n)r in this.props&&(this.Ri(r),i=!0);i&&this.save()}update_campaign_params(){var e=P?.URL;if(e!==this.mi){var n=Sf(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);Kt(cl(n))||this.register(n),this.mi=e}}update_search_keyword(){var e;this.register((e=P?.referrer)?If(e):{})}update_referrer_info(){var e;this.register_once({$referrer:kf(),$referring_domain:P!=null&&P.referrer&&((e=ss(P.referrer))==null?void 0:e.host)||as},void 0)}set_initial_person_info(){this.props[fa]||this.props[ha]||this.register_once({[Qr]:Cf(this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties,this.Ne.disable_capture_url_hashes)},void 0)}get_initial_props(){var e={};ie([ha,fa],(r=>{var s=this.props[r];s&&ie(s,(function(o,a){e["$initial_"+Go(a)]=o}))}));var n=this.props[Qr];if(n){var i=(function(r,s){s===void 0&&(s=!1);var o=Af(r,s),a={};return ie(o,(function(l,u){a["$initial_"+Go(u)]=l})),a})(n,this.Ne.disable_capture_url_hashes);fe(e,i)}return e}safe_merge(e){return ie(this.props,(function(n,i){i in e||(e[i]=n)})),e}update_config(e,n,i){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!i),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var r=e.persistence!==n.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((f,h)=>f===d[h]))})(e.cookie_persisted_properties||[],n.cookie_persisted_properties||[]),s=r?this.bi(e):this.ii,o=this.wi(e);if(r||o!==this.pi){var a=this.props;this.clear(),this.ii=s,this.pi=o,this.props=a,this.save()}}set_disabled(e){this.xi=e,this.xi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ni&&(this.Ni=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this.qi&&(this.qi=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,n){var i=this.props[Ti]||{};i[e]=n,this.Pi(Ti,i),this.save()}remove_event_timer(e){var n=this.props[Ti]||{},i=n[e];return C(i)||(delete n[e],this.Pi(Ti,n),this.save()),i}get_property(e){return this.props[e]}set_property(e,n){this.Pi(e,n),this.save()}Pi(e,n){var i;this.props[e]=n,(i=yn(e))!=null&&i.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var n,i=(n=yn(e))==null?void 0:n.storageGroup;i&&(this.Mi(i).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function br(t){var e=!0;return{dispose(){if(e){e=!1;var n=t();n&&je(n.then)&&n.then(void 0,(()=>{}))}}}}var Ue={GZipJS:"gzip-js",Base64:"base64"},bi={Activation:"events",Cancellation:"cancelEvents"},Io={Popover:"popover",API:"api",Widget:"widget"},qt={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},ko={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},_a={Popover:"popover",Inline:"inline"},lm={SHOWN:"product tour shown"},Gc={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},Kc=pe("[RateLimiter]");class cm{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=n=>{var i=n.text;if(i&&i.length)try{(JSON.parse(i).quota_limited||[]).forEach((r=>{Kc.info((r||"events")+" is quota limited."),this.serverLimits[r]=new Date().getTime()+6e4}))}catch(r){return void Kc.warn('could not rate limit - continuing. Error: "'+r?.message+'"',{text:i})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var n,i,r;e===void 0&&(e=!1);var s=this.captureEventsBurstLimit,o=this.captureEventsPerSecond,a=new Date().getTime(),l=(n=(i=this.instance.persistence)==null?void 0:i.get_property(da))!==null&&n!==void 0?n:{tokens:s,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>s&&(l.tokens=s);var u=1>l.tokens;if(u||e||(l.tokens=Math.max(0,l.tokens-1)),u&&!e){var c=(ke(l.dropped)?l.dropped:0)+1;l.dropped=c,!this.lastEventRateLimited&&this.Hi(c)&&(l.dropped=0)}return this.lastEventRateLimited=u,(r=this.instance.persistence)==null||r.set_property(da,l),{isRateLimited:u,remainingTokens:l.tokens}}Ui(e){var n=this.instance.config.property_denylist;return!U(n)||!n.includes(e)}zi(){var e;if(this.Ui("$current_url")&&this.Ui("$pathname")&&me!=null&&me.pathname)return""+((e=me.origin)!==null&&e!==void 0?e:"")+me.pathname}Hi(e){var n,i,r=this.captureEventsBurstLimit,s=this.captureEventsPerSecond,o=this.zi(),a=this.Ui("$session_id")?(n=(i=this.instance).get_session_id)==null?void 0:n.call(i):void 0,l=[e+" event(s) dropped since the last warning",o?"triggered on "+o:void 0,a?"session "+a:void 0].filter(Boolean).join(", ");return!!this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited: "+l+". Config is set to "+s+" events per second and "+r+" events burst limit."},{skip_client_rate_limiting:!0})}isServerRateLimited(e){var n=this.serverLimits[e||"events"]||!1;return n!==!1&&new Date().getTime()e(this.remoteConfig))):e()}Vi(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:e})}load(){try{if(this.remoteConfig)return an.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void an.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return an.info("No config found after loading remote JS config. Falling back to JSON."),void this.Vi((n=>{this.Zi(n.json,n),this.Gi()}));this.Zi(e),this.Gi()}))}catch(e){an.error("Error loading remote config",e),this.Zi()}}stop(){this.Ki&&(clearInterval(this.Ki),this.Ki=void 0)}refresh(){!this._instance.Qi()&&P&&P.visibilityState!=="hidden"&&this._instance.reloadFeatureFlags()}Gi(){var e;if(!this.Ki){var n=(e=this._instance.config.remote_config_refresh_interval_ms)!==null&&e!==void 0?e:3e5;n!==0&&(this.Ki=setInterval((()=>{this.refresh()}),n))}}Zi(e,n){!e&&n&&(n.statusCode===0?n.error||an.warn("Failed to fetch remote config from PostHog."):an.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(r){an.error("Error applying remote config",r)}if(e?.hasFeatureFlags!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var i;(i=this._instance.featureFlags)==null||i.ensureFlagsLoaded()}catch(r){an.error("Error loading feature flags",r)}}}var ct=Uint8Array,Ke=Uint16Array,oi=Uint32Array,hl=new ct([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]),pl=new ct([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]),Yc=new ct([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Rf=function(t,e){for(var n=new Ke(31),i=0;31>i;++i)n[i]=e+=1<i;++i)for(var s=n[i];n[i+1]>s;++s)r[s]=s-n[i]<<5|i;return[n,r]},Tf=Rf(hl,2),ya=Tf[1];Tf[0][28]=258,ya[258]=28;for(var Jc=Rf(pl,0)[1],$f=new Ke(32768),_e=0;32768>_e;++_e){var zn=(43690&_e)>>>1|(21845&_e)<<1;$f[_e]=((65280&(zn=(61680&(zn=(52428&zn)>>>2|(13107&zn)<<2))>>>4|(3855&zn)<<4))>>>8|(255&zn)<<8)>>>1}var Wi=function(t,e,n){for(var i=t.length,r=0,s=new Ke(e);i>r;++r)++s[t[r]-1];var o,a=new Ke(e);for(r=0;e>r;++r)a[r]=a[r-1]+s[r-1]<<1;for(o=new Ke(i),r=0;i>r;++r)o[r]=$f[a[t[r]-1]++]>>>15-t[r];return o},Mn=new ct(288);for(_e=0;144>_e;++_e)Mn[_e]=8;for(_e=144;256>_e;++_e)Mn[_e]=9;for(_e=256;280>_e;++_e)Mn[_e]=7;for(_e=280;288>_e;++_e)Mn[_e]=8;var ls=new ct(32);for(_e=0;32>_e;++_e)ls[_e]=5;var um=Wi(Mn,9),dm=Wi(ls,5),Mf=function(t){return(t/8>>0)+(7&t&&1)},Lf=function(t,e,n){(n==null||n>t.length)&&(n=t.length);var i=new(t instanceof Ke?Ke:t instanceof oi?oi:ct)(n-e);return i.set(t.subarray(e,n)),i},Ot=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8},Ei=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8,t[i+2]|=n>>>16},Co=function(t,e){for(var n=[],i=0;t.length>i;++i)t[i]&&n.push({s:i,f:t[i]});var r=n.length,s=n.slice();if(!r)return[new ct(0),0];if(r==1){var o=new ct(n[0].s+1);return o[n[0].s]=1,[o,1]}n.sort((function(b,k){return b.f-k.f})),n.push({s:-1,f:25001});var a=n[0],l=n[1],u=0,c=1,d=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=r-1;)a=n[n[d].f>n[u].f?u++:d++],l=n[u!=c&&n[d].f>n[u].f?u++:d++],n[c++]={s:-1,f:a.f+l.f,l:a,r:l};var f=s[0].s;for(i=1;r>i;++i)s[i].s>f&&(f=s[i].s);var h=new Ke(f+1),p=wa(n[c-1],h,0);if(p>e){i=0;var g=0,m=p-e,v=1<i;++i){var E=s[i].s;if(e>=h[E])break;g+=v-(1<>>=m;g>0;){var S=s[i].s;e>h[S]?g-=1<=0&&g;--i){var _=s[i].s;h[_]==e&&(--h[_],++g)}p=e}return[new ct(h),p]},wa=function(t,e,n){return t.s==-1?Math.max(wa(t.l,e,n+1),wa(t.r,e,n+1)):e[t.s]=n},Zc=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new Ke(++e),i=0,r=t[0],s=1,o=function(l){n[i++]=l},a=1;e>=a;++a)if(t[a]==r&&a!=e)++s;else{if(!r&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(r),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(r);s=1,r=t[a]}return[n.subarray(0,i),e]},Si=function(t,e){for(var n=0,i=0;e.length>i;++i)n+=t[i]*e[i];return n},ba=function(t,e,n){var i=n.length,r=Mf(e+2);t[r]=255&i,t[r+1]=i>>>8,t[r+2]=255^t[r],t[r+3]=255^t[r+1];for(var s=0;i>s;++s)t[r+s+4]=n[s];return 8*(r+4+i)},Xc=function(t,e,n,i,r,s,o,a,l,u,c){Ot(e,c++,n),++r[256];for(var d=Co(r,15),f=d[0],h=d[1],p=Co(s,15),g=p[0],m=p[1],v=Zc(f),E=v[0],S=v[1],_=Zc(g),b=_[0],k=_[1],T=new Ke(19),x=0;E.length>x;++x)T[31&E[x]]++;for(x=0;b.length>x;++x)T[31&b[x]]++;for(var F=Co(T,7),$=F[0],O=F[1],L=19;L>4&&!$[Yc[L-1]];--L);var N,K,V,M,R=u+5<<3,Z=Si(r,Mn)+Si(s,ls)+o,Ce=Si(r,f)+Si(s,g)+o+14+3*L+Si(T,$)+(2*T[16]+3*T[17]+7*T[18]);if(Z>=R&&Ce>=R)return ba(e,c,t.subarray(l,l+u));if(Ot(e,c,1+(Z>Ce)),c+=2,Z>Ce){N=Wi(f,h),K=f,V=Wi(g,m),M=g;var oe=Wi($,O);for(Ot(e,c,S-257),Ot(e,c+5,k-1),Ot(e,c+10,L-4),c+=14,x=0;L>x;++x)Ot(e,c+3*x,$[Yc[x]]);c+=3*L;for(var ye=[E,b],$e=0;2>$e;++$e){var ae=ye[$e];for(x=0;ae.length>x;++x)Ot(e,c,oe[Ie=31&ae[x]]),c+=$[Ie],Ie>15&&(Ot(e,c,ae[x]>>>5&127),c+=ae[x]>>>12)}}else N=um,K=Mn,V=dm,M=ls;for(x=0;a>x;++x)if(i[x]>255){var Ie;Ei(e,c,N[257+(Ie=i[x]>>>18&31)]),c+=K[Ie+257],Ie>7&&(Ot(e,c,i[x]>>>23&31),c+=hl[Ie]);var Se=31&i[x];Ei(e,c,V[Se]),c+=M[Se],Se>3&&(Ei(e,c,i[x]>>>5&8191),c+=pl[Se])}else Ei(e,c,N[i[x]]),c+=K[i[x]];return Ei(e,c,N[256]),c+K[256]},fm=new oi([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),hm=(function(){for(var t=new oi(256),e=0;256>e;++e){for(var n=e,i=9;--i;)n=(1&n&&3988292384)^n>>>1;t[e]=n}return t})(),Ao=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8};function pm(t,e){e===void 0&&(e={});var n=(function(){var d=4294967295;return{p(f){for(var h=d,p=0;f.length>p;++p)h=hm[255&h^f[p]]^h>>>8;d=h},d(){return 4294967295^d}}})(),i=t.length;n.p(t);var r,s,o,a,l,u=(a=10+((r=e).filename&&r.filename.length+1||0),l=8,(function(d,f,h,p,g,m){var v=d.length,E=new ct(p+v+5*(1+Math.floor(v/7e3))+g),S=E.subarray(p,E.length-g),_=0;if(!f||8>v)for(var b=0;v>=b;b+=65535){var k=b+65535;v>k?_=ba(S,_,d.subarray(b,k)):(S[b]=!0,_=ba(S,_,d.subarray(b,v)))}else{for(var T=fm[f-1],x=T>>>13,F=8191&T,$=(1<b;++b){var Ie=V(b),Se=32767&b,De=L[Ie];if(O[Se]=De,L[Ie]=Se,b>=$e){var wt=v-b;if((Ce>7e3||ye>24576)&&wt>423){_=Xc(d,S,0,M,R,Z,oe,ye,ae,b-ae,_),ye=Ce=oe=0,ae=b;for(var ge=0;286>ge;++ge)R[ge]=0;for(ge=0;30>ge;++ge)Z[ge]=0}var Je=2,bt=0,mn=F,Re=Se-De&32767;if(wt>2&&Ie==V(b-Re))for(var Pe=Math.min(x,wt)-1,$t=Math.min(32767,b),Dn=Math.min(258,wt);$t>=Re&&--mn&&Se!=De;){if(d[b+Je]==d[b+Je-Re]){for(var qe=0;Dn>qe&&d[b+qe]==d[b+qe-Re];++qe);if(qe>Je){if(Je=qe,bt=Re,qe>Pe)break;var jn=Math.min(Re,qe-2),Mt=0;for(ge=0;jn>ge;++ge){var Lt=b-Re+ge+32768&32767,ut=Lt-O[Lt]+32768&32767;ut>Mt&&(Mt=ut,De=Lt)}}}Re+=(Se=De)-(De=O[Se])+32768&32767}if(bt){M[ye++]=268435456|ya[Je]<<18|Jc[bt];var sn=31&ya[Je],mi=31&Jc[bt];oe+=hl[sn]+pl[mi],++R[257+sn],++Z[mi],$e=b+Je,++Ce}else M[ye++]=d[b],++R[d[b]]}}_=Xc(d,S,!0,M,R,Z,oe,ye,ae,b-ae,_)}return Lf(E,0,p+Mf(_)+g)})(s=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):12+o.mem,a,l)),c=u.length;return(function(d,f){var h=f.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>f.level?4:f.level==9?2:0,d[9]=3,f.mtime!=0&&Ao(d,4,Math.floor(new Date(f.mtime||Date.now())/1e3)),h){d[3]=8;for(var p=0;h.length>=p;++p)d[p+10]=h.charCodeAt(p)}})(u,e),Ao(u,c-8,n.d()),Ao(u,c-4,i),u}var gm=!!zo||!!Xa,Nf="text/plain",Mr=!1,Of=(t,e)=>{var n=t.split("#"),i=n[1],r=n[0].split("?"),s=r[0],o=r[1];if(!o)return t;var a=o.split("&").filter((l=>l.split("=")[0]!==e)).join("&");return s+(a?"?"+a:"")+(i?"#"+i:"")},ks=function(t,e,n){var i;n===void 0&&(n=!0);var r=t.split("?"),s=r[0],o=r[1],a=I({},e),l=(i=o?.split("&").map((c=>{var d,f=c.split("="),h=f[0],p=n&&(d=a[h])!==null&&d!==void 0?d:f[1];return delete a[h],h+"="+p})))!==null&&i!==void 0?i:[],u=(function(c,d){var f,h;d===void 0&&(d="&");var p=[];return ie(c,(function(g,m){C(g)||C(m)||m==="undefined"||(f=encodeURIComponent((v=>v instanceof File)(g)?g.name:g.toString()),h=encodeURIComponent(m),p[p.length]=h+"="+f)})),p.join(d)})(a);return u&&l.push(u),l.length>0?s+"?"+l.join("&"):s},Po=t=>{if(t.Ji)return t.Ji;var e=t.data,n=t.compression;if(e){if(n===Ue.GZipJS){var i=pm((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new ct(a.length+(a.length>>>1)),d=0,f=function(m){c[d++]=m},h=0;u>h;++h){if(d+5>c.length){var p=new ct(d+8+(u-h<<1));p.set(c),c=p}var g=a.charCodeAt(h);128>g?f(g):2048>g?(f(192|g>>>6),f(128|63&g)):g>55295&&57344>g?(f(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++h))>>>18),f(128|g>>>12&63),f(128|g>>>6&63),f(128|63&g)):(f(224|g>>>12),f(128|g>>>6&63),f(128|63&g))}return Lf(c,0,d)})(Jn(e)),{mtime:0});return{contentType:Nf,body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),estimatedSize:i.byteLength}}if(n===Ue.Base64){var r=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(Jn(e)),s=(a=>"data="+encodeURIComponent(typeof a=="string"?a:Jn(a)))(r);return{contentType:"application/x-www-form-urlencoded",body:s,estimatedSize:new Blob([s]).size}}var o=Jn(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},Bf=t=>{var e,n,i=()=>t.transport==="sendBeacon"?{url:ks(t.url,{compression:Ue.Base64}),encodedBody:Po(I({},t,{compression:Ue.Base64,Ji:void 0}))}:{url:Of(t.url,"compression"),encodedBody:Po(I({},t,{compression:void 0,Ji:void 0}))};try{e=Po(t)}catch(r){if(_c(t.compression,ri(t.url,"compression")))return A.error("Failed to gzip request body, sending uncompressed payload",r),i();throw r}return e&&_c(t.compression,ri(t.url,"compression"))&&!((n=e.body)instanceof ArrayBuffer?qo(new Uint8Array(n)):ArrayBuffer.isView(n)&&qo(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)))?(Mr=!0,i()):{url:t.url,encodedBody:e}},Df=t=>{try{return Bf(t)}catch(e){return A.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},mm=(function(){var t=se((function*(e){var n=Jn(e.data),i=yield(function(s,o,a){return Vo.apply(this,arguments)})(n,ne.DEBUG,{rethrow:!0});if(!i)return e;var r=yield i.arrayBuffer();return I({},e,{Ji:{contentType:Nf,body:r,estimatedSize:r.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),vm=/Failed to fetch|NetworkError|Load failed/i,jf=t=>t?.name==="TypeError"&&vm.test(t?.message||""),Uf=t=>{var e=Df(t);if(e){var n=e.url,i=e.encodedBody,r=i??{},s=r.contentType,o=r.body,a=r.estimatedSize,l=new Headers;ie(t.headers,(function(p,g){l.append(g,p)})),s&&l.append("Content-Type",s);var u=null,c=!1;if(fc){var d=new fc;u={signal:d.signal,timeout:setTimeout((()=>{var p,g;c=!0,d.abort((p=t.timeout,(g=new Error("PostHog request timed out"+(p?" after "+p+"ms":""))).name="AbortError",g))}),t.timeout)}}var f=p=>{c&&p?.name==="AbortError"||jf(p)?A.warn(p):A.error(p),t.callback==null||t.callback({statusCode:0,error:p})};try{var h;Xa(n,I({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(h=u)==null?void 0:h.signal},t.fetchOptions)).then((p=>p.text().then((g=>{var m={statusCode:p.status,text:g};if(p.status===200)try{m.json=JSON.parse(g)}catch(v){A.error(v)}t.callback==null||t.callback(m)})))).catch(f).finally((()=>u?clearTimeout(u.timeout):null))}catch(p){u&&clearTimeout(u.timeout),f(p)}}},Ea=t=>{try{var e,n=Bf(t),i=n.url,r=n.encodedBody,s=r??{},o=s.body,a=s.estimatedSize;if(!o)return;var l=o instanceof Blob?o:new Blob([o],{type:s.contentType});if(He.sendBeacon(i,l))return;var u=U(t.data)?t.data:(e=t.data)==null?void 0:e.batch;if(U(u)&&u.length>1&&(a??0)>16384){var c=Math.ceil(u.length/2),d=f=>U(t.data)?f:I({},t.data,{batch:f});return Ea(I({},t,{data:d(u.slice(0,c))})),void Ea(I({},t,{data:d(u.slice(c))}))}A.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),Uf(I({},t,{Yi:!0}))}catch(f){A.warn("Beacon send failed",f)}},Qc=(t,e,n,i)=>{var r=i==="query"?e==="POST"?"sent_at":"_":void 0;return ks(n===Ue.GZipJS?Of(t,"compression"):t,I({},r?{[r]:Date.now().toString()}:{},n===Ue.GZipJS?{}:{compression:n}))},Lr=[];Xa&&Lr.push({transport:"fetch",method:Uf}),zo&&Lr.push({transport:"XHR",method(t){var e=Df(t);if(e){var n=new zo,i=e.encodedBody;n.open(t.method||"GET",e.url,!0);var r=i??{},s=r.contentType,o=r.body;ie(t.headers,(function(a,l){n.setRequestHeader(l,a)})),s&&n.setRequestHeader("Content-Type",s),t.timeout&&(n.timeout=t.timeout),n.onreadystatechange=()=>{if(n.readyState===4){var a={statusCode:n.status,text:n.responseText};if(n.status===200)try{a.json=JSON.parse(n.responseText)}catch{}t.callback==null||t.callback(a)}},n.send(o)}}}),He!=null&&He.sendBeacon&&Lr.push({transport:"sendBeacon",method:Ea});var Sa=3e3;class _m{constructor(e,n){this.Xi=!0,this.tr=[],this.er=At(n?.flush_interval_ms||Sa,250,5e3,A.createLogger("flush interval"),Sa),this.ir=e}enqueue(e){this.tr.push(e),this.rr||this.nr()}unload(){this.sr();var e=this.tr.length>0?this.ar():{},n=Object.values(e);[...n.filter((i=>i.url.indexOf("/e")===0)),...n.filter((i=>i.url.indexOf("/e")!==0))].map((i=>{this.lr(I({},i,{transport:"sendBeacon"}))}))}enable(){this.Xi=!1,this.nr()}nr(){var e=this;this.Xi||(this.rr=setTimeout((()=>{if(this.sr(),this.tr.length>0){var n=this.ar(),i=function(){var s=n[r],o=new Date().getTime();s.data&&U(s.data)&&ie(s.data,(a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp})),e.lr(s)};for(var r in n)i()}}),this.er))}lr(e){try{this.ir(e)}catch(n){A.error(n)}}sr(){clearTimeout(this.rr),this.rr=void 0}ar(){var e={};return ie(this.tr,(n=>{var i,r=n,s=(r?r.batchKey:null)||r.url;C(e[s])&&(e[s]=I({},r,{data:[]})),(i=e[s].data)==null||i.push(r.data)})),this.tr=[],e}}var ym=["retriesPerformedSoFar"];class wm{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!C(w)&&"onLine"in w.navigator&&(this.dr=w.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},ve(w,"online",this.vr),ve(w,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var n=e.retriesPerformedSoFar,i=pd(e,ym);Dt(n)&&(i.url=ks(i.url,{retry_count:n})),this._instance._send_request(I({},i,{callback:r=>{if(r.statusCode!==200&&(400>r.statusCode||r.statusCode>=500)){if((r.statusCode===0?3:10)>(n??0))return void this.At(I({retriesPerformedSoFar:n},i));r.statusCode===0&&A.warn("Request failed before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped retrying after "+(n??0)+" retries.")}i.callback==null||i.callback(r)}}))}At(e){var n=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=n+1;var i=(function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),c=Math.random()-.5;return Math.ceil(u+c*(u-l))})(n),r=Date.now()+i;this.tr.push({retryAt:r,requestOptions:e});var s="Enqueued failed request for retry in "+i;navigator.onLine||(s+=" (Browser is offline)"),A.warn(s),this.ur||(this.ur=!0,this.gr())}gr(){if(this.mr&&clearTimeout(this.mr),this.tr.length===0)return this.ur=!1,void(this.mr=void 0);this.mr=setTimeout((()=>{this.dr&&this.tr.length>0&&this.cr(),this.gr()}),this.hr)}cr(){var e=Date.now(),n=[],i=this.tr.filter((s=>e>s.retryAt||(n.push(s),!1)));if(this.tr=n,i.length>0)for(var r of i)this.retriableRequest(r.requestOptions)}unload(){for(var e of(this.mr&&(clearTimeout(this.mr),this.mr=void 0),this.ur=!1,C(w)||(this.vr&&(w.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(w.removeEventListener("offline",this.pr),this.pr=void 0)),this.tr)){var n=e.requestOptions;try{this._instance._send_request(I({},n,{transport:"sendBeacon"}))}catch(i){A.error(i)}}this.tr=[]}}class bm{constructor(e){this.yr=()=>{var n,i,r,s;this.br||(this.br={});var o=this.scrollElement(),a=this.scrollY(),l=o?Math.max(0,o.scrollHeight-o.clientHeight):0,u=a+(o?.clientHeight||0),c=o?.scrollHeight||0;this.br.lastScrollY=Math.ceil(a),this.br.maxScrollY=Math.max(a,(n=this.br.maxScrollY)!==null&&n!==void 0?n:0),this.br.maxScrollHeight=Math.max(l,(i=this.br.maxScrollHeight)!==null&&i!==void 0?i:0),this.br.lastContentY=u,this.br.maxContentY=Math.max(u,(r=this.br.maxContentY)!==null&&r!==void 0?r:0),this.br.maxContentHeight=Math.max(c,(s=this.br.maxContentHeight)!==null&&s!==void 0?s:0)},this._instance=e}get _r(){return this._instance.config.scroll_root_selector}getContext(){return this.br}resetContext(){var e=this.br;return setTimeout(this.yr,0),e}startMeasuringScrollPosition(){ve(w,"scroll",this.yr,{capture:!0}),ve(w,"scrollend",this.yr,{capture:!0}),ve(w,"resize",this.yr)}scrollElement(){if(!this._r)return w?.document.documentElement;var e=U(this._r)?this._r:[this._r];for(var n of e){var i=w?.document.querySelector(n);if(i)return i}}wr(e){var n=e==="y"?"scrollTop":"scrollLeft";if(this._r){var i=this.scrollElement();return i&&i[n]||0}return w?e==="y"?w.scrollY||w.pageYOffset||w.document.documentElement.scrollTop||0:w.scrollX||w.pageXOffset||w.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var Em=t=>Cf(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class eu{constructor(e,n,i,r){this.kr=s=>{var o=this.Sr();if(!o||o.sessionId!==s){var a={sessionId:s,props:this.Cr(this._instance)};this.Mr.register({[ua]:a})}},this._instance=e,this.Tr=n,this.Mr=i,this.Cr=r||Em,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[ua]}getSetOnceProps(){var e,n=(e=this.Sr())==null?void 0:e.props;return n?"r"in n?Af(n,this._instance.config.disable_capture_url_hashes):{$referring_domain:n.referringDomain,$pathname:n.initialPathName,utm_source:n.utm_source,utm_campaign:n.utm_campaign,utm_medium:n.utm_medium,utm_content:n.utm_content,utm_term:n.utm_term}:{}}getSessionProps(){var e={};return ie(cl(this.getSetOnceProps()),((n,i)=>{i==="$current_url"&&(i="url"),e["$session_entry_"+Go(i)]=n})),e}}class gl{on(e,n){return this.Er[e]||(this.Er[e]=[]),this.Er[e].push(n),()=>{this.Er[e]=this.Er[e].filter((i=>i!==n))}}emit(e,n){for(var i of this.Er[e]||[])i(n);for(var r of this.Er["*"]||[])r(e,n)}constructor(){this.Er={}}}var xi=pe("[SessionId]");class tu{on(e,n){return this.Ir.on(e,n)}constructor(e,n,i){var r;if(this.Pr=null,this.Rr=[],this.Ar=void 0,this.Fr=!1,this.Ir=new gl,this.Lr=(u,c)=>!(!Dt(u)||!Dt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===Wt)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Ne=e.config,this.Mr=e.persistence,this.Or=void 0,this.Dr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.$r=n||Ht,this.Nr=i||Ht;var s=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*At(this.Ne.session_idle_timeout_seconds||1800,60,36e3,xi.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.qr(),this.jr="ph_"+s+"_window_id",this.Br="ph_"+s+"_primary_window_exists",this.Hr()){var o=be.H(this.jr),a=be.H(this.Br);o&&!a?this.Or=o:be.q(this.jr),be.F(this.Br,!0)}if((r=this.Ne.bootstrap)!=null&&r.sessionID)try{var l=(u=>{var c=this.Ne.bootstrap.sessionID.replace(/-/g,"");if(c.length!==32)throw new Error("Not a valid UUID");if(c[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(c.substring(0,12),16)})();this.Ur(this.Ne.bootstrap.sessionID,new Date().getTime(),l)}catch(u){xi.error("Invalid sessionID in bootstrap",u)}this.zr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return C(this.Rr)&&(this.Rr=[]),this.Rr.push(e),this.Dr&&e(this.Dr,this.Or),()=>{this.Rr=this.Rr.filter((n=>n!==e))}}Hr(){return this.Ne.persistence!=="memory"&&!this.Mr.xi&&be.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&be.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?be.H(this.jr):null}Zr(e){var n=this.Pr;return!Ye(n)&&!Ye(e)&&5e3>Math.abs(e-n)}Ur(e,n,i){var r=n!==this._sessionActivityTimestamp,s=!(e!==this.Dr||i!==this._sessionStartTimestamp);this._sessionStartTimestamp=i,this._sessionActivityTimestamp=n,this.Dr=e,s&&!r||s&&this.Zr(n)||(this.Pr=n,this.Mr.register({[Yn]:[n,e,i]}))}Gr(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return Dt(n)&&n>0}Qr(){this.Gr()?this.Mr.refreshKey(Yn):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!Ye(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this.Pr){this.Qr();var n=this.Jr();n[1]===this.Dr&&n[2]===this._sessionStartTimestamp&&(this.Pr=this._sessionActivityTimestamp,this.Mr.register({[Yn]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],n=Dt(e)?e:0,i=Dt(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(n,i)}Xr(e){return this.Qr(),this.Lr(e,this.Yr())}Jr(){var e=this.Mr.props[Yn];return U(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Pr=null,clearTimeout(this.tn),this.tn=void 0,this.Ur(null,null,null)}destroy(){this.Fr=!0,this.Kr(),clearTimeout(this.tn),this.tn=void 0,this.Ar&&w&&(w.removeEventListener(ns,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&be.q(this.Br)},ve(w,ns,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=null),this.Ne.cookieless_mode===Wt)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var i=n||new Date().getTime(),r=this.Jr(),s=r[1],o=r[2],a=this.Yr(),l=this.Vr(),u=Dt(o)&&Math.abs(i-o)>864e5,c=!1,d=!1,f=!s,h=s,p=!f&&!e&&this.Lr(i,a);if(p){(p=this.Xr(i))||xi.info("cross-tab refresh kept the session alive",{sessionId:s});var g=this.Jr();s=g[1],o=g[2]}f||p||u?(s=this.$r(),l=this.Nr(),xi.info("new session ID generated",{sessionId:s,windowId:l,changeReason:{noSessionId:f,activityTimeout:p,sessionPastMaximumLength:u}}),o=i,c=!0):(l||(l=this.Nr(),c=!0),(d=s!==h)&&(xi.info("adopted cross-tab session id",{sessionId:s,windowId:l}),c=!0));var m=Dt(a)&&e&&!u?a:i,v=Dt(o)?o:new Date().getTime();this.Wr(l),this.Ur(s,m,v),e||this.qr();var E={noSessionId:f,activityTimeout:p,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((S=>S(s,l,E))),{sessionId:s,windowId:l,sessionStartTimestamp:v,changeReason:c?E:void 0,lastActivityTimestamp:a}}qr(){this.Fr||(clearTimeout(this.tn),this.tn=setTimeout((()=>{if(!this.Fr)if(this.Xr(new Date().getTime())){var e=this.Dr;this.resetSessionId(),this.Ir.emit("forcedIdleReset",{idleSessionId:e})}else this.qr()}),1.1*this.sessionTimeoutMs))}}var Hf=function(t,e){if(!t)return!1;var n=t.userAgent;if(n&&wc(n,e))return!0;try{var i=t?.userAgentData;if(i!=null&&i.brands&&i.brands.some((r=>wc(r?.brand,e))))return!0}catch{}return!!t.webdriver};function Wf(){return(Wf=se((function*(){var t=He?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),n=e?.model;return X(n)&&n.length>0?n:void 0}catch(i){return void A.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",i)}}))).apply(this,arguments)}var cs=function(t,e){if(!(function(n){try{new RegExp(n)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function Fo(t,e,n){return Jn({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}var zf={exact:(t,e)=>e.some((n=>t.some((i=>n===i)))),is_not:(t,e)=>e.every((n=>t.every((i=>n!==i)))),regex:(t,e)=>e.some((n=>t.some((i=>cs(n,i))))),not_regex:(t,e)=>e.every((n=>t.every((i=>!cs(n,i))))),icontains:(t,e)=>e.map(Er).some((n=>t.map(Er).some((i=>n.includes(i))))),not_icontains:(t,e)=>e.map(Er).every((n=>t.map(Er).every((i=>!n.includes(i))))),gt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>i>parseFloat(r)))})),lt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>it.toLowerCase();function qf(t,e){return!t||Object.entries(t).every((n=>{var i=n[1],r=e?.[n[0]];if(C(r)||Ye(r))return!1;var s=[String(r)],o=zf[i.operator];return!!o&&o(i.values,s)}))}var xa="custom",nu="i.posthog.com",Sm=/^\/static\//;class xm{constructor(e){this.en={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,n=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return n||(n=this.apiHost.replace("."+nu,".posthog.com")),n==="https://app.posthog.com"?"https://us.posthog.com":n}get region(){return this.en[this.apiHost]||(this.en[this.apiHost]=/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"us":/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"eu":xa),this.en[this.apiHost]}rn(e){if(Sm.test(e)){var n=this.instance.config.asset_host;if(typeof n=="string")return n.trim().replace(/\/$/,"")||void 0}}endpointFor(e,n){if(n===void 0&&(n=""),n&&(n=n[0]==="/"?n:"/"+n),e==="ui")return this.uiHost+n;if(e==="flags")return this.flagsApiHost+n;if(e==="assets"){var i=this.rn(n);if(i)return""+i+n}if(this.region===xa)return this.apiHost+n;var r=nu+n;switch(e){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}}function Vf(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var Q=pe("[Surveys]"),Gf="seenSurvey_",Kf=t=>{try{var e=(n=>((i,r)=>""+Gf+(function(s){return s.current_iteration&&s.current_iteration>0?s.id+"_"+s.current_iteration:s.id})(r))(0,n))(t);if(localStorage.getItem(e))return;localStorage.setItem(e,"true")}catch(n){Q.error("Failed to persist survey seen state",n)}},Im=[Io.Popover,Io.Widget,Io.API],km={ignoreConditions:!1,ignoreDelay:!1,displayType:_a.Popover},Cm=pe("[PostHog ExternalIntegrations]"),Am={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class Pm{constructor(e){this._instance=e}ai(e,n){var i;(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,e,(r=>{if(r)return Cm.error("failed to load script",r);n()}))}startIfEnabledOrStop(){var e=this,n=function(){var s,o,a,l=i[0],u=i[1];!u||(s=B.__PosthogExtensions__)!=null&&(s=s.integrations)!=null&&s[l]||e.ai(Am[l],(()=>{var c;(c=B.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=B.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=B.__PosthogExtensions__)==null||(a=a.integrations)==null||(a=a[l])==null||a.stop())};for(var i of Object.entries((r=this._instance.config.integrations)!==null&&r!==void 0?r:{})){var r;n()}}}class Fm{constructor(e,n){this.rt=e,this.nn=n,this.sn=new Map,this.an=!1}add(e){var n=this;return se((function*(){if(n.an)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(n.sn.has(e.name))throw new Error('Browser extension "'+e.name+'" is already registered');n.sn.set(e.name,e);try{var i=e.setup(n.nn);i&&(yield i)}catch(s){var r=n.sn.get(e.name)===e;r&&n.sn.delete(e.name),n.rt.error('Failed to set up browser extension "'+e.name+'"',s),r&&n.ln(e)}}))()}dispose(){if(!this.an){this.an=!0;var e=Array.from(this.sn.values()).reverse();for(var n of(this.sn.clear(),e))this.ln(n)}}ln(e){try{var n=e.dispose==null?void 0:e.dispose();n&&je(n.then)&&n.then(void 0,(i=>{this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}))}catch(i){this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}}}class Rm{constructor(e){this._instance=e}initialize(){}get(e){var n=this._instance.persistence;if(typeof e=="string")return n?.get_property(e);var i={};for(var r of e){var s=n?.get_property(r);C(s)||(i[r]=s)}return i}set(e,n){var i;(i=this._instance.persistence)==null||i.register(typeof e=="string"?{[e]:n}:e)}remove(e){var n;(n=this._instance.persistence)==null||n.unregister(e)}}var iu="extensionsRemoteConfig";class Tm{constructor(e){this.an=!1,this.instance=e,this.rt=A,this.un=e.hn,this.kv=new Rm(e),this.onEvent=n=>br(this.instance.on("eventCaptured",(i=>{try{n({event:i.event,properties:i.properties})}catch(r){this.rt.error("Browser extension event listener failed",r)}}))),this.onRemoteConfig=n=>{if(this.an)return br((()=>{}));var i=s=>{try{n(s)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},r=this.instance.dn.on(iu,i);return this.un&&i(this.un),br(r)},this.vn=new Fm(A.createLogger("[BrowserExtensions]"),this)}get logger(){return this.rt}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return(e=this.instance.get_property(Ji))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(Ji);return typeof e=="string"?e:void 0}get library(){return{name:ne.LIB_NAME,version:ne.LIB_VERSION}}get initialPersonProperties(){var e,n;return(e=(n=this.instance.persistence)==null?void 0:n.get_initial_props())!==null&&e!==void 0?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,n,i,r,s=(e=this.instance.sessionManager)==null?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:(n=s?.sessionId)!==null&&n!==void 0?n:"",windowId:(i=s?.windowId)!==null&&i!==void 0?i:"",sessionStartTimestamp:(r=s?.sessionStartTimestamp)!==null&&r!==void 0?r:0}}catch{return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get projectToken(){return this.instance.config.token}add(e){return this.vn.add(e)}capture(e,n,i){var r=this;return se((function*(){i?r.instance.capture(e,n,{timestamp:i.timestamp,uuid:i.uuid,$set:i.set,$set_once:i.setOnce}):r.instance.capture(e,n)}))()}registerDynamicEventProperties(e){return br(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(iu,e))}sendRequest(e,n){var i=this;return se((function*(){var r;n===void 0&&(n={});var s=i.instance.requestRouter.endpointFor((r=n.target)!==null&&r!==void 0?r:"api",e),o={method:n.method,url:n.query?ks(s,n.query):s,data:n.body,headers:n.headers,timeout:n.timeoutMs,fireCallbackOnDrop:!0,transport:n.transport,compression:n.compression,timestampMode:n.sentAt};return n.transport==="sendBeacon"?(i.instance._send_request(o),{statusCode:202}):new Promise((a=>{o.callback=a,i.instance._send_request(o)}))}))()}dispose(){this.an||(this.an=!0,this.vn.dispose())}}var zi={},Ro=0,us=()=>{},ru='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',Ii="Surveys module not available",su="sanitize_properties is deprecated. Use before_send instead",Yf="Invalid value for property_denylist config: ",$m=["token","distinct_id",tf],Kn="posthog",Jf=!gm&&Ge?.indexOf("MSIE")===-1&&Ge?.indexOf("Mozilla")===-1,To=t=>{var e;return I({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:Mg(P?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:us,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:t??"unset",__preview_deferred_init_extensions:!1,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:me&&X(me?.search)&&me.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disableDeviceModel:!1,disable_external_dependency_loading:!1,strict_script_versioning:!1,enable_recording_console_log:void 0,secure_cookie:(w==null||(e=w.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(n){A.error("Bad HTTP status: "+n.statusCode+" "+n.text)},get_device_id:n=>n,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:pa,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:Sa},error_tracking:{},_onCapture:us},(n=>({rageclick:n&&n>="2026-05-30"?{content_ignorelist:Vg,ignore_text_selection:!0}:!n||"2025-11-30">n||{content_ignorelist:!0},capture_pageview:!n||"2025-05-24">n||"history_change",session_recording:n&&n>="2026-06-25"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6},streamNetworkBody:!0}:n&&n>="2026-05-30"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6}}:n&&n>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:n&&n>="2026-01-30"?"head":"body",internal_or_test_user_hostname:n&&n>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:n&&n>="2026-05-30"?250:0,split_storage:!(!n||"2026-05-30">n),detect_google_search_app:!(!n||"2026-05-30">n),disable_capture_url_hashes:!(!n||"2026-06-25">n)}))(t))},Mm=[["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"]],ou=t=>{var e={};for(var n of Mm){var i=n[0],r=n[1];C(t[i])||(e[r]=t[i])}var s=fe({},e,t),o=t.__preview_external_dependency_versioned_paths;return C(o)||(C(t.strict_script_versioning)&&(s.strict_script_versioning=!!o),X(o)&&C(t.asset_host)&&(s.asset_host=o)),U(t.property_blacklist)&&(C(t.property_denylist)?s.property_denylist=t.property_blacklist:U(t.property_denylist)?s.property_denylist=[...t.property_blacklist,...t.property_denylist]:A.error(Yf+t.property_denylist)),s};class Lm{constructor(){this.__forceAllowLocalhost=!1}get fn(){return this.__forceAllowLocalhost}set fn(e){A.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class Ze{pn(e,n){if(e){var i=this.sn.indexOf(e);i!==-1&&this.sn.splice(i,1)}return this.sn.push(n),n.initialize==null||n.initialize(),n}gn(){return this.config.cookieless_mode===Wt||this.config.cookieless_mode===kn&&this.consent.isRejected()}get decideEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){var e;this.webPerformance=new Lm,this.mn=!1,this.version=ne.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new gl,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=To(),this.SentryIntegration=em,this.sentryIntegration=i=>(function(r,s){var o=wf(r,s);return{name:yf,processEvent:a=>o(a)}})(this,i),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.wn=!1,this.kn=null,this.xn=null,this.Sn=null,this.scrollManager=new bm(this),this.pageViewManager=new qc(this),this.rateLimiter=new cm(this),this.requestRouter=new xm(this),this.consent=new Ug(this),this.externalIntegrations=new Pm(this);var n=(e=Ze.__defaultExtensionClasses)!==null&&e!==void 0?e:{};this.featureFlags=n.featureFlags&&new n.featureFlags(this),this.toolbar=n.toolbar&&new n.toolbar(this),this.surveys=n.surveys&&new n.surveys(this),this.conversations=n.conversations&&new n.conversations(this),this.logs=n.logs&&new n.logs(this),this.metrics=n.metrics&&new n.metrics(this),this.experiments=n.experiments&&new n.experiments(this),this.exceptions=n.exceptions&&new n.exceptions(this),this.people={set:(i,r,s)=>{var o=X(i)?{[i]:r}:i;this.setPersonProperties(o),s?.({})},set_once:(i,r,s)=>{var o=X(i)?{[i]:r}:i;this.setPersonProperties(void 0,o),s?.({})}},this.on("eventCaptured",(i=>A.info('send "'+i?.event+'"',i)))}init(e,n,i){if(i&&i!==Kn){var r,s=(r=zi[i])!==null&&r!==void 0?r:new Ze;return s._init(e,n,i),zi[i]=s,zi[Kn][i]=s,s}return this._init(e,n,i)}_init(e,n,i){var r,s;n===void 0&&(n={});var o,a=X(e)?e.trim():"";if(!a)return A.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return a!==((o=this.config)==null?void 0:o.token)?console.warn("[PostHog.js]","You have already initialized PostHog with a different project token! Re-initializing is a no-op, so events will keep going to the project this instance was initialized with. To capture into a second project, load PostHog once, then initialize a named instance after the SDK has loaded, e.g. posthog.init('"+a+"', { ... }, 'project2')"):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=To(n.defaults),n.debug=this.Cn(n.debug),this.Mn=n,this.Tn=[],n.person_profiles?this.xn=n.person_profiles:n.process_person&&(this.xn=n.process_person);var l=To(n.defaults),u=ou(n),c=fe({},l,u,{name:i,token:a});he(l.rageclick)&&he(u.rageclick)&&(c.rageclick=fe({},l.rageclick,u.rageclick)),he(l.session_recording)&&he(u.session_recording)&&(c.session_recording=fe({},l.session_recording,u.session_recording)),this.set_config(c),this.config.on_xhr_error&&A.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=n.disable_compression?void 0:Ue.GZipJS;var d=this.En();if(this.persistence=new xo(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new xo(I({},this.config,{persistence:"sessionStorage"}),d,!1),this.bn="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&be.N()){var f=be.H(this.bn);U(f)&&f.forEach((k=>{X(k)&&this.yn.add(k)}))}else be.q(this.bn);var h=I({},this.persistence.props),p=I({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new _m((k=>this.Pn(k)),this.config.request_queue_config),this.Rn=new wm(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new tu(this),this.sessionPropsManager=new eu(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((k,T,x)=>{(x!=null&&x.activityTimeout||x!=null&&x.sessionPastMaximumLength||x!=null&&x.crossTabAdoption)&&this.An()}))),this.Fn(),this.config.__preview_deferred_init_extensions?(A.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Ln(g)}),0)):(A.info("Initializing extensions synchronously"),this.Ln(g)),ne.DEBUG=ne.DEBUG||this.config.debug,ne.DEBUG&&A.info("Starting in debug mode",{this:this,config:n,thisC:I({},this.config),p:h,s:p}),!this.config.identity_distinct_id||(r=n.bootstrap)!=null&&r.distinctID||(n.bootstrap=I({},n.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((s=n.bootstrap)==null?void 0:s.distinctID)!==void 0){var m=n.bootstrap.distinctID,v=this.get_distinct_id(),E=this.persistence.get_property(at);if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&E===Hn)this.identify(m);else if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&E===vn)A.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{var S=this.config.get_device_id(Ht()),_=n.bootstrap.isIdentifiedID?S:m;this.persistence.set_property(at,n.bootstrap.isIdentifiedID?vn:Hn),this.register({distinct_id:m,$device_id:_})}}if(g)this.register_once({distinct_id:mr,$device_id:null},"");else if(!this.get_distinct_id()){var b=this.config.get_device_id(Ht());this.register_once({distinct_id:b,$device_id:b},""),this.persistence.set_property(at,Hn)}return ve(w,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),n.segment?(function(k,T){var x=k.config.segment;if(!x)return T();(function(F,$){var O=F.config.segment;if(!O)return $();var L=K=>{var V=()=>K.anonymousId()||Ht();F.config.get_device_id=V,K.id()&&(F.register({distinct_id:K.id(),$device_id:V()}),F.persistence.set_property(at,vn)),$()},N=O.user();"then"in N&&je(N.then)?N.then(L):L(N)})(k,(()=>{x.register((F=>{typeof Promise<"u"&&Promise.resolve||Eo.warn("This browser does not have Promise support, and can not use the segment integration");var $=(O,L)=>{if(!L)return O;O.event.userId||O.event.anonymousId===F.get_distinct_id()||(Eo.info("No userId set, resetting PostHog"),F.reset()),O.event.userId&&O.event.userId!==F.get_distinct_id()&&(Eo.info("UserId set, identifying with PostHog"),F.identify(O.event.userId));var N=F.calculateEventProperties(L,O.event.properties);return O.event.properties=Object.assign({},N,O.event.properties),O};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:O=>$(O,O.event.event),page:O=>$(O,Gn),identify:O=>$(O,yo),screen:O=>$(O,"$screen")}})(k)).then((()=>{T()}))}))})(this,(()=>this.On())):this.On(),je(this.config._onCapture)&&this.config._onCapture!==us&&(A.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(k=>this.config._onCapture(k.event,k)))),this.config.ip&&A.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this.config.disableDeviceModel||(function(){return Wf.apply(this,arguments)})().then((k=>{k&&this.register({[vo]:k})})).catch(us),this}Fn(){var e,n,i,r,s,o,a=(e=(n=this.config.__extensionClasses)==null?void 0:n.featureFlags)!==null&&e!==void 0?e:(i=Ze.__defaultExtensionClasses)==null?void 0:i.featureFlags;a&&(this.featureFlags&&this.featureFlags instanceof a||((r=this.Dn)==null||r.call(this),this.Dn=void 0,this.featureFlags=new a(this)),je(this.featureFlags.onReloading)&&je(this.featureFlags.setup)?this.Dn||(this.Dn=this.featureFlags.onReloading((()=>{this.dn.emit("featureFlagsReloading",!0)})),this.$n().add(this.featureFlags)):(s=(o=this.featureFlags).initialize)==null||s.call(o))}Ln(e){var n,i,r,s,o,a,l,u=performance.now(),c=I({},Ze.__defaultExtensionClasses,this.config.__extensionClasses),d=[];c.exceptions&&this.sn.push(this.exceptions=(n=this.exceptions)!==null&&n!==void 0?n:new c.exceptions(this)),c.historyAutocapture&&this.sn.push(this.historyAutocapture=new c.historyAutocapture(this)),c.tracingHeaders&&this.sn.push(this.tracingHeaders=new c.tracingHeaders(this)),c.siteApps&&this.sn.push(this.siteApps=new c.siteApps(this)),c.sessionRecording&&!e&&this.sn.push(this.sessionRecording=new c.sessionRecording(this)),this.config.disable_scroll_properties||d.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),c.autocapture&&this.sn.push(this.autocapture=new c.autocapture(this)),c.surveys&&this.sn.push(this.surveys=(i=this.surveys)!==null&&i!==void 0?i:new c.surveys(this)),c.logs&&this.sn.push(this.logs=(r=this.logs)!==null&&r!==void 0?r:new c.logs(this)),c.metrics&&this.sn.push(this.metrics=(s=this.metrics)!==null&&s!==void 0?s:new c.metrics(this)),c.conversations&&this.sn.push(this.conversations=(o=this.conversations)!==null&&o!==void 0?o:new c.conversations(this)),c.productTours&&this.sn.push(this.productTours=new c.productTours(this)),c.heatmaps&&this.sn.push(this.heatmaps=new c.heatmaps(this)),c.webVitalsAutocapture&&this.sn.push(this.webVitalsAutocapture=new c.webVitalsAutocapture(this)),c.exceptionObserver&&this.sn.push(this.exceptionObserver=new c.exceptionObserver(this)),c.deadClicksAutocapture&&this.sn.push(this.deadClicksAutocapture=new c.deadClicksAutocapture(this,Qg)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((f=>{f.initialize&&d.push((()=>{f.initialize==null||f.initialize()}))})),d.push((()=>{if(this.Nn){var f=this.Nn;this.Nn=void 0,this.sn.forEach((h=>h.onRemoteConfig==null?void 0:h.onRemoteConfig(f)))}})),this.qn(d,u)}qn(e,n){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,n)}),0);var i=e.shift();if(i)try{i()}catch(s){A.error("Error initializing extension:",s)}}var r=Math.round(performance.now()-n);this.register_for_session({[nf]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[rf]:r}),this.config.__preview_deferred_init_extensions&&A.info("PostHog extensions initialized ("+r+"ms)")}Zi(e){var n;if(!P||!P.body)return A.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.Zi(e)}),500);if(this.config.__preview_deferred_init_extensions&&(this.Nn=e),this.hn=e,this.compression=void 0,e.ok){var i,r=e.config;r.supportedCompression&&!this.config.disable_compression&&(this.compression=j(r.supportedCompression,Ue.GZipJS)?Ue.GZipJS:j(r.supportedCompression,Ue.Base64)?Ue.Base64:void 0),(i=r.analytics)!=null&&i.endpoint&&(this.analyticsDefaultEndpoint=r.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:pa}),(n=this.jn)==null||n.handleRemoteConfig(e),this.sn.forEach((s=>s.onRemoteConfig==null?void 0:s.onRemoteConfig(e)))}On(){try{this.config.loaded(this)}catch(i){A.critical("`loaded` function failed",i)}if(this.Bn(),this.config.internal_or_test_user_hostname&&me!=null&&me.hostname){var e=me.hostname,n=this.config.internal_or_test_user_hostname;(typeof n=="string"?e===n:n.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.gn())&&this.Hn()}),1),this.Un=new Ff(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()&&vr(this.__request_queue,(e=>this.Pn(e))),this.__request_queue=[],this.Bn()}_handle_unload(){var e,n,i,r,s;(e=this.surveys)==null||e.handlePageUnload==null||e.handlePageUnload(),(n=this.metrics)==null||n.flush("sendBeacon"),this.config.request_batching?(this.zn()&&this.capture(_o),(i=this.logs)==null||i.flushLogs("sendBeacon"),(r=this.In)==null||r.unload(),(s=this.Rn)==null||s.unload()):this.zn()&&this.capture(_o,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?Jf?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)?e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:429})):(e.transport=e.transport||this.config.api_transport,e.headers=I({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,(C(this.config.disable_beacon)?this.config.__preview_disable_beacon:this.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(n=>{var i,r,s,o=I({},n);o.timeout=o.timeout||6e4;var a,l,u,c,d,f=(i=o.transport)!==null&&i!==void 0?i:"fetch";f==="sendBeacon"&&C(o.compression)&&o.data&&(o.compression=Ue.Base64),o.method==="POST"&&o.data&&(o.timestampMode==="capture-body"?o.data={api_key:(l=(d=(c=U(a=o.data)?a:[a])[0])==null||(u=d.properties)==null?void 0:u.token)!==null&&l!==void 0?l:d?.token,batch:c,sent_at:new Date().toISOString()}:o.timestampMode==="body"&&(o.data=(function(m,v){return v===void 0&&(v=new Date().toISOString()),U(m)?m.map((E=>I({},E,{sent_at:v}))):I({},m,{sent_at:v})})(o.data))),o.url=Qc(o.url,o.method,o.compression,o.timestampMode);var h=Lr.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),p=(r=(s=(function(m,v){for(var E=0;m.length>E;E++)if(m[E].transport===f)return m[E]})(h))==null?void 0:s.method)!==null&&r!==void 0?r:h[0].method;if(!p)throw new Error("No available transport method");var g=m=>{try{p(m)}catch(v){jf(v)?A.warn(v):A.error(v),o.callback==null||o.callback({statusCode:0,error:v})}};f!=="sendBeacon"&&o.data&&o.compression===Ue.GZipJS&&Np&&typeof Promise<"u"&&!Mr?mm(o).then((m=>{g(m)})).catch((m=>{if(yc(m))return Mr=!0,void g(I({},o,{compression:void 0,url:Qc(n.url,n.method,void 0,n.timestampMode)}));(v=>{if(!v||typeof v!="object")return!1;var E="name"in v?String(v.name):"";return yc(v)||E===gd})(m)&&(Mr=!0),g(o)})):p(o)})(I({},e,{callback:n=>{var i,r;this.rateLimiter.checkForLimiting(n),400>n.statusCode||(i=(r=this.config).on_request_error)==null||i.call(r,n),e.callback==null||e.callback(n)}}))):e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:0}))}Pn(e){this.Rn?this.Rn.retriableRequest(e):this._send_request(e)}_execute_array(e){Ro++;try{var n,i=[],r=[],s=[];vr(e,(a=>{if(a)if(U(n=a[0]))s.push(a);else if(je(a))try{a.call(this)}catch(l){A.error("Error executing queued PostHog call",a,l)}else U(a)&&n==="alias"?i.push(a):U(a)&&n.indexOf("capture")!==-1&&je(this[n])?s.push(a):r.push(a)}));var o=function(a,l){vr(a,(function(u){try{if(U(u[0])){var c=l;ie(u,(function(d){c=c[d[0]].apply(c,d.slice(1))}))}else l[u[0]].apply(l,u.slice(1))}catch(d){A.error("Error executing queued PostHog call",u,d)}}))};o(i,this),o(r,this),o(s,this)}finally{Ro--}}push(e){if(Ro>0&&U(e)&&X(e[0])){var n=Ze.prototype[e[0]];je(n)&&n.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,n,i){var r,s,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.In){if(this.is_capturing())if(!C(e)&&X(e)){var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var c=i!=null&&i.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(c==null||!c.isRateLimited){n!=null&&n.$current_url&&!X(n?.$current_url)&&(A.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),n==null||delete n.$current_url),e!=="$exception"||i!=null&&i.Wn||A.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,f=i?.timestamp||d,h=xc(i?.uuid,Ht),p={uuid:h,event:e,properties:this.calculateEventProperties(e,n||{},f,h)};e===Gn&&this.config.__preview_capture_bot_pageviews&&u&&(p.event="$bot_pageview",p.properties.$browser_type="bot"),c&&(p.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&p.properties.$feature_flag_has_experiment===!1&&this.get_property(Zr)===!0;i?.$set&&!g&&(p.$set=i?.$set);var m=i?.$unset;m&&(p.$unset=m);var v,E,S,_=g?void 0:this.Vn(i?.$set_once,e!==Fc,e===yo);if(_&&(p.$set_once=_),i!=null&&i._noTruncate||(s=this.config.properties_string_max_length,o=p,a=L=>X(L)?L.slice(0,s):L,l=new Set,p=(function L(N,K){if(N!==Object(N))return a?a(N):N;if(!l.has(N)){var V;if(l.add(N),U(N))V=[],vr(N,(R=>{V.push(L(R))}));else{var M={};ie(N,((R,Z)=>{l.has(R)||(M[Z]=L(R))})),V=M}return V}})(o)),p.timestamp=f,C(i?.timestamp)||(p.properties.$event_time_override_provided=!0,p.properties.$event_time_override_system_time=d),g&&(p.properties=(function(L,N){N===void 0&&(N=[]);var K={},V=M=>{L[M]!==void 0&&(K[M]=L[M])};return Op.forEach(V),N.forEach(V),K})(p.properties,$m)),e===qt.DISMISSED||e===qt.SENT){var b=n?.[ko.SURVEY_ID],k=n?.[ko.SURVEY_ITERATION];Kf({id:b,current_iteration:k}),p.$set=I({},p.$set,{[(v={id:b,current_iteration:k},E=e===qt.SENT?"responded":"dismissed",S="$survey_"+E+"/"+v.id,v.current_iteration&&v.current_iteration>0&&(S="$survey_"+E+"/"+v.id+"/"+v.current_iteration),S)]:!0})}else e===qt.SHOWN&&(p.$set=I({},p.$set,{[ko.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===lm.SHOWN){var T=n?.[Gc.TOUR_TYPE];T&&(p.$set=I({},p.$set,{[Gc.TOUR_LAST_SEEN_DATE+"/"+T]:new Date().toISOString()}))}var x=I({},p.properties.$set,p.$set);if(Kt(x)||this.setPersonPropertiesForFlags(x),!H(this.config.before_send)){var F=this.Pt(p);if(!F)return;(p=F).uuid=xc(p.uuid,Ht)}this.dn.emit("eventCaptured",p);var $=(r=i?._url)!==null&&r!==void 0?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),O={method:"POST",url:$,data:p,compression:"best-available",timestampMode:i?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test($)?"body":"capture-body",batchKey:i?._batchKey,transport:i?.transport};return!this.config.request_batching||i&&(i==null||!i._batchKey)||i!=null&&i.send_instantly?this.Pn(O):this.In.enqueue(O),p}A.critical("This capture call is ignored due to client rate limiting.")}}else A.error("No event name provided to posthog.capture")}else A.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(n=>e(n.event,n)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new Tm(this)}cn(e){this._n.push(e);var n=!0;return()=>{if(n){n=!1;var i=this._n.indexOf(e);i!==-1&&this._n.splice(i,1)}}}calculateEventProperties(e,n,i,r,s){if(i=i||new Date,!this.persistence||!this.sessionPersistence)return n;var o=s?void 0:this.persistence.remove_event_timer(e),a=I({},n);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.gn()&&(a[tf]=!0),e==="$snapshot"){var l=I({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!X(a.distinct_id)&&!ke(a.distinct_id)||Ko(a.distinct_id))&&A.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=(function(b,k,T,x){var F,$,O,L;if(x===void 0&&(x=!1),!Ge)return{};var N,K=b?[...si,...k||[]]:[],V=(function(Dn){for(var qe=0;Ec.length>qe;qe++){var jn=Ec[qe],Mt=jn[1],Lt=jn[0].exec(Dn),ut=Lt&&(je(Mt)?Mt(Lt,Dn):Mt);if(ut)return ut}return["",""]})(Ge),M=V[0],R=V[1],Z=(N=typeof navigator<"u"?navigator:void 0)!=null&&N.brave?{brave:!0}:{},Ce={};C(T)||(Ce.detectGoogleSearchApp=T);var oe={},ye=(F=navigator)==null||(F=F.userAgentData)==null?void 0:F.platform,$e=($=navigator)==null?void 0:$.maxTouchPoints,ae=w==null||(O=w.screen)==null?void 0:O.width,Ie=w==null||(L=w.screen)==null?void 0:L.height,Se=w?.devicePixelRatio;C(ye)||(oe.userAgentDataPlatform=ye),C($e)||(oe.maxTouchPoints=$e),C(ae)||(oe.screenWidth=ae),C(Ie)||(oe.screenHeight=Ie),C(Se)||(oe.devicePixelRatio=Se);var De,wt,ge,Je,bt,mn,Re,Pe,$t=fe(cl({$os:M,$os_version:R,$browser:jd(Ge,navigator.vendor,Z,Ce),$device:Sc(Ge),$device_type:(wt=Ge,ge=oe,Pe=Sc(wt),Pe===Ed||Pe===bd||Pe==="Kobo"||Pe==="Kindle Fire"||Pe===Ld?ti:Pe===Ki||Pe===Qn||Pe===Yi||Pe===Jo?"Console":Pe===xd?"Wearable":Pe?rt:ge?.userAgentDataPlatform==="Android"&&((Je=ge?.maxTouchPoints)!==null&&Je!==void 0?Je:0)>0?600>Math.min((bt=ge?.screenWidth)!==null&&bt!==void 0?bt:0,(mn=ge?.screenHeight)!==null&&mn!==void 0?mn:0)/((Re=ge?.devicePixelRatio)!==null&&Re!==void 0?Re:1)?rt:ti:"Desktop"),$timezone:Pf(),$timezone_offset:sm()}),{$current_url:Xi(x?fn(me?.href):me?.href,K,Qi),$host:me?.host,$pathname:me?.pathname,$raw_user_agent:Ge.length>1e3?Ge.substring(0,997)+"...":Ge,$browser_version:ng(Ge,navigator.vendor,Z,Ce),$browser_language:Vc(),$browser_language_prefix:(De=Vc(),typeof De=="string"?De.split("-")[0]:void 0),$screen_height:w?.screen.height,$screen_width:w?.screen.width,$viewport_height:w?.innerHeight,$viewport_width:w?.innerWidth,$lib:ne.LIB_NAME,$lib_version:ne.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return ne.SDK_DIST_CHANNEL&&($t.$sdk_dist_channel=ne.SDK_DIST_CHANNEL),$t})(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties,this.config.detect_google_search_app,this.config.disable_capture_url_hashes);if(this.sessionManager){var d=this.sessionManager.checkAndGetSessionAndWindowId(s,i.getTime()),f=d.windowId;a.$session_id=d.sessionId,a.$window_id=f}this.sessionPropsManager&&fe(a,this.sessionPropsManager.getSessionProps());try{var h;this.sessionRecording&&fe(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(h=this.Rn)==null?void 0:h.length}catch(b){a.$sdk_debug_error_capturing_properties=String(b)}if(this.requestRouter.region===xa&&(a.$lib_custom_api_host=this.config.api_host),u=e!==Gn||s?e!==_o||s?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(i):this.pageViewManager.doPageView(i,r),a=fe(a,u),e===Gn&&P&&(a.title=P.title),!C(o)){var p=i.getTime()-o;a.$duration=parseFloat((p/1e3).toFixed(3))}Ge&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();ie(["$referrer","$referring_domain"],(b=>{b in g&&delete m[b]}));var v={};if(this._n.length>0)for(var E of this._n.slice())try{fe(v,E())}catch(b){A.error("Failed to produce browser extension event properties",b)}(a=fe({},c,g,m,I({},v,a))).$is_identified=this._isIdentified(),U(this.config.property_denylist)?ie(this.config.property_denylist,(function(b){delete a[b]})):A.error(Yf+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var S=this.config.sanitize_properties;S&&(A.error(su),a=S(a,e));var _=this.Zn();return a.$process_person_profile=_,_&&!s&&this.Gn("_calculate_event_properties"),a}Vn(e,n,i){var r;if(n===void 0&&(n=!0),i===void 0&&(i=!1),!this.persistence||!this.Zn()||this.mn&&!i)return e;var s=this.persistence.get_initial_props(),o=(r=this.sessionPropsManager)==null?void 0:r.getSetOnceProps(),a=fe({},s,o||{},e||{}),l=this.config.sanitize_properties;return l&&(A.error(su),a=l(a,"$set_once")),n&&(this.mn=!0),Kt(a)?void 0:a}register(e,n){var i;(i=this.persistence)==null||i.register(e,n)}register_once(e,n,i){var r;(r=this.persistence)==null||r.register_once(e,n,i)}register_for_session(e){var n;(n=this.sessionPersistence)==null||n.register(e),Object.keys(e).forEach((i=>this.yn.add(i))),this.Qn()}unregister(e){var n;(n=this.persistence)==null||n.unregister(e)}unregister_for_session(e){var n;(n=this.sessionPersistence)==null||n.unregister(e),this.yn.delete(e),this.Qn()}Kn(e,n){this.register({[e]:n})}An(){this.yn.forEach((e=>{var n;(n=this.sessionPersistence)==null||n.unregister(e)})),this.yn.clear(),this.Qn()}Qn(){var e;if(this.bn)if(this.config.persistence==="memory"||(e=this.sessionPersistence)!=null&&e.xi||!be.N())be.q(this.bn);else{var n=[];this.yn.forEach((i=>n.push(i))),n.length>0?be.F(this.bn,n):be.q(this.bn)}}getFeatureFlag(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlag(e,n)}getFeatureFlagPayload(e){var n;return(n=this.featureFlags)==null?void 0:n.getFeatureFlagPayload(e)}getFeatureFlagResult(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlagResult(e,n)}getAllFeatureFlags(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.getAllFeatureFlags())!==null&&e!==void 0?e:[]}isFeatureEnabled(e,n){var i,r;return(i=(r=this.featureFlags)==null?void 0:r.isFeatureEnabled(e,n))!==null&&i!==void 0?i:n?.defaultValue}reloadFeatureFlags(){var e;(e=this.featureFlags)==null||e.reloadFeatureFlags()}updateFlags(e,n,i){var r;(r=this.featureFlags)==null||r.updateFlags(e,n,i)}updateEarlyAccessFeatureEnrollment(e,n,i){var r;(r=this.featureFlags)==null||r.updateEarlyAccessFeatureEnrollment(e,n,i)}getEarlyAccessFeatures(e,n,i){var r;return n===void 0&&(n=!1),(r=this.featureFlags)==null?void 0:r.getEarlyAccessFeatures(e,n,i)}on(e,n){return this.dn.on(e,n)}onFeatureFlags(e){return this.featureFlags?this.featureFlags.onFeatureFlags(e):(e([],{},{errorsLoading:!0}),()=>{})}onSurveysLoaded(e){return this.surveys?this.surveys.onSurveysLoaded(e):(e([],{isLoaded:!1,error:Ii}),()=>{})}onSessionId(e){var n,i;return(n=(i=this.sessionManager)==null?void 0:i.onSessionId(e))!==null&&n!==void 0?n:()=>{}}getSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getSurveys(e,n):e([],{isLoaded:!1,error:Ii})}getActiveMatchingSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,n):e([],{isLoaded:!1,error:Ii})}renderSurvey(e,n){var i;(i=this.surveys)==null||i.renderSurvey(e,n)}displaySurvey(e,n){var i;n===void 0&&(n=km),(i=this.surveys)==null||i.displaySurvey(e,n)}cancelPendingSurvey(e){var n;(n=this.surveys)==null||n.cancelPendingSurvey(e)}canRenderSurvey(e){var n,i;return(n=(i=this.surveys)==null?void 0:i.canRenderSurvey(e))!==null&&n!==void 0?n:{visible:!1,disabledReason:Ii}}canRenderSurveyAsync(e,n){var i,r;return n===void 0&&(n=!1),(i=(r=this.surveys)==null?void 0:r.canRenderSurveyAsync(e,n))!==null&&i!==void 0?i:Promise.resolve({visible:!1,disabledReason:Ii})}Jn(e){return!e||Ko(e)?(A.critical("Unique user id has not been set in posthog.identify"),!1):e===mr?(A.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.'),!1):!["distinct_id","distinctid"].includes(e.toLowerCase())&&!["undefined","null"].includes(e.toLowerCase())||(A.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.'),!1)}identify(e,n,i){if(!this.__loaded||!this.persistence)return A.uninitializedWarning("posthog.identify");if(ke(e)&&(e=e.toString(),A.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.Jn(e)&&this.Gn("posthog.identify")){var r=this.get_distinct_id();this.register({$user_id:e}),this.get_property(Ji)||this.register_once({$had_persisted_distinct_id:!0,$device_id:r},""),e!==r&&e!==this.get_property(Ri)&&(this.unregister(Ri),this.register({distinct_id:e}));var s,o=(this.persistence.get_property(at)||Hn)===Hn,a=e!==r,l=!a&&o;if(a&&o)this.persistence.set_property(at,vn),this.setPersonPropertiesForFlags({$set:n||{},$set_once:i||{}},!1),this.capture(yo,{distinct_id:e,$anon_distinct_id:r},{$set:n||{},$set_once:i||{}}),this.Sn=Fo(e,n,i),(s=this.featureFlags)==null||s.setAnonymousDistinctId(r);else if(l){this.persistence.set_property(at,vn);var u=n||{},c=i||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=Fo(e,n,i)}else(n||i)&&this.setPersonProperties(n,i);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Cn)):l&&(n||i)&&this.reloadFeatureFlags()}}setPersonProperties(e,n){if((e||n)&&this.Gn("posthog.setPersonProperties")){var i=Fo(this.get_distinct_id(),e,n);this.Sn!==i?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:n||{}},!0),this.capture("$set",{$set:e||{},$set_once:n||{}}),this.Sn=i):A.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}unsetPersonProperties(e){var n,i=(U(e)?e:[e]).filter((r=>X(r)&&r.length>0));i.length!==0&&this.Gn("posthog.unsetPersonProperties")&&((n=this.featureFlags)==null||n.unsetPersonPropertiesForFlags(i,!0),this.capture("$set",{$unset:i}),this.Sn=null)}group(e,n,i){if(e&&n){var r=this.getGroups(),s=r[e]!==n;if(s&&this.resetGroupPropertiesForFlags(e),this.register({$groups:I({},r,{[e]:n})}),s||i){var o={$group_type:e,$group_key:n};i&&(o.$group_set=i),this.capture(Fc,o)}i&&this.setGroupPropertiesForFlags({[e]:i}),s&&!i&&this.reloadFeatureFlags()}else A.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),(i=this.featureFlags)==null||i.setPersonPropertiesForFlags(e,n)}resetPersonPropertiesForFlags(e){var n;e===void 0&&(e=!0),(n=this.featureFlags)==null||n.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((i=this.featureFlags)==null||i.setGroupPropertiesForFlags(e,n))}resetGroupPropertiesForFlags(e){var n;(n=this.featureFlags)==null||n.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,n){var i,r,s,o,a,l,u,c,d,f;if(n===void 0&&(n=!1),A.info("reset"),!this.__loaded)return A.uninitializedWarning("posthog.reset");var h,p=this.get_property(Ji),g=this.get_property(vo),m=this.get_property(An),v=this.is_capturing();if(this.consent.reset(),n||!v||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after."),(i=this.persistence)==null||i.clear(),(r=this.sessionPersistence)==null||r.clear(),this.yn.clear(),this.Qn(),C(m)||(h=this.persistence)==null||h.register({[An]:m}),(s=this.surveys)==null||s.reset(),(o=this.Un)==null||o.stop(),(a=this.featureFlags)==null||a.reset(),(l=this.conversations)==null||l.reset(),(u=this.logs)==null||u.reset(),(c=this.metrics)==null||c.reset(),(d=this.persistence)==null||d.set_property(at,Hn),(f=this.sessionManager)==null||f.resetSessionId(),this.Sn=null,this.config.cookieless_mode===Wt)this.register_once({distinct_id:mr,$device_id:null},"");else{var E=this.config.get_device_id(Ht());this.register_once({distinct_id:E,$device_id:e?E:p},""),e||C(g)||this.register({[vo]:g})}this.register({$last_posthog_reset:new Date().toISOString()},1),delete this.config.identity_distinct_id,delete this.config.identity_hash,this.reloadFeatureFlags()}shutdown(e){var n=this;return se((function*(){var i,r,s,o,a,l,u;if(n.__loaded){(i=n.Un)==null||i.stop(),(r=n.jn)==null||r.dispose(),(s=n.sessionRecording)==null||s.dispose(),(o=n.logs)==null||o.flushLogs("sendBeacon"),(a=n.metrics)==null||a.flush("sendBeacon"),(l=n.In)==null||l.unload(),(u=n.Rn)==null||u.unload();try{var c;(c=n.featureFlags)==null||c.destroy()}catch(d){A.error("Error while destroying feature flags",d)}}else A.uninitializedWarning("posthog.shutdown")}))()}setIdentity(e,n){var i;this.config.identity_distinct_id=e,this.config.identity_hash=n,this.alias(e),(i=this.conversations)==null||i.Xn()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,(e=this.conversations)==null||e.ts()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,n;return(e=(n=this.sessionManager)==null?void 0:n.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var n=this.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.sessionStartTimestamp,r=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+n.sessionId);if(e!=null&&e.withTimestamp&&i){var s,o=(s=e.timestampLookBack)!==null&&s!==void 0?s:10;if(!i)return r;r+="?t="+Math.max(Math.floor((new Date().getTime()-i)/1e3)-o,0)}return r}alias(e,n){return e===this.get_property(Yd)?(A.critical("Attempting to create alias for existing People user - aborting."),-2):this.Gn("posthog.alias")?(C(n)&&(n=this.get_distinct_id()),e!==n?(this.Kn(Ri,e),this.capture("$create_alias",{alias:e,distinct_id:n})):(A.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var n=I({},this.config);if(he(e)){var i,r,s,o,a,l,u,c,d,f,h,p;fe(this.config,ou(e));var g=this.En();(i=this.persistence)==null||i.update_config(this.config,n,g),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new xo(I({},this.config,{persistence:"sessionStorage"}),g,!1);var m=this.Cn(this.config.debug);mt(m)&&(this.config.debug=m),mt(this.config.debug)&&(this.config.debug?(ne.DEBUG=!0,le.N()&&le.F("ph_debug",!0),A.info("set_config",{config:e,oldConfig:n,newConfig:I({},this.config)})):(ne.DEBUG=!1,le.N()&&le.q("ph_debug"))),(r=this.featureFlags)==null||r.updateConfig==null||r.updateConfig(this.config,this.Qi()),(s=this.exceptionObserver)==null||s.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(f=this.deadClicksAutocapture)==null||f.startIfEnabledOrStop(),(h=this.surveys)==null||h.loadIfEnabled(),this.es(),(p=this.externalIntegrations)==null||p.startIfEnabledOrStop()}}_overrideSDKInfo(e,n){ne.LIB_NAME=e,ne.LIB_VERSION=n}startSessionRecording(e){var n,i,r,s,o,a=e===!0,l={sampling:a||!(e==null||!e.sampling),linked_flag:a||!(e==null||!e.linked_flag),url_trigger:a||!(e==null||!e.url_trigger),event_trigger:a||!(e==null||!e.event_trigger)};Object.values(l).some(Boolean)&&((n=this.sessionManager)==null||n.checkAndGetSessionAndWindowId(),l.sampling&&((i=this.sessionRecording)==null||i.overrideSampling()),l.linked_flag&&((r=this.sessionRecording)==null||r.overrideLinkedFlag()),l.url_trigger&&((s=this.sessionRecording)==null||s.overrideTrigger("url")),l.event_trigger&&((o=this.sessionRecording)==null||o.overrideTrigger("event"))),this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,n){if(this.exceptions){var i=new Error("PostHog syntheticException"),r=this.exceptions.buildProperties(e,{handled:!0,syntheticException:i});return this.exceptions.sendExceptionEvent(I({},r,n))}}addExceptionStep(e,n){var i;(i=this.exceptions)==null||i.addExceptionStep(e,n)}captureLog(e){var n;(n=this.logs)==null||n.captureLog(e)}get logger(){var e,n;return(e=(n=this.logs)==null?void 0:n.logger)!==null&&e!==void 0?e:Ze.rs}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var n,i;return(n=(i=this.toolbar)==null?void 0:i.loadToolbar(e))!==null&&n!==void 0&&n}get_property(e){var n;return(n=this.persistence)==null?void 0:n.props[e]}getSessionProperty(e){var n;return(n=this.sessionPersistence)==null?void 0:n.props[e]}toString(){var e,n=(e=this.config.name)!==null&&e!==void 0?e:Kn;return n!==Kn&&(n=Kn+"."+n),n}_isIdentified(){var e,n;return((e=this.persistence)==null?void 0:e.get_property(at))===vn||((n=this.sessionPersistence)==null?void 0:n.get_property(at))===vn}Zn(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles===pa&&!this._isIdentified()&&Kt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[Ri])&&((n=this.persistence)==null||(n=n.props)==null||!n[es]))}zn(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Zn()||this.Gn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.Gn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}Gn(e){return this.config.person_profiles==="never"?(A.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Kn(es,!0),!0)}En(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut();return this.config.disable_persistence||e&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!==kn)}es(){var e,n,i,r,s=this.En();return((e=this.persistence)==null?void 0:e.xi)!==s&&((i=this.persistence)==null||i.set_disabled(s)),((n=this.sessionPersistence)==null?void 0:n.xi)!==s&&((r=this.sessionPersistence)==null||r.set_disabled(s)),s&&(this.yn.clear(),this.Qn()),s}opt_in_capturing(e){var n;if(this.config.cookieless_mode!==Wt){if(this.gn()){var i,r,s,o,a;this.Yn(!0,!0),(i=this.sessionManager)==null||i.destroy(),(r=this.pageViewManager)==null||r.destroy(),this.sessionManager=new tu(this),this.pageViewManager=new qc(this),this.persistence&&(this.sessionPropsManager=new eu(this,this.sessionManager,this.persistence));var l,u=(s=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&s!==void 0?s:(a=Ze.__defaultExtensionClasses)==null?void 0:a.sessionRecording;u&&(this.sessionRecording=this.pn(this.sessionRecording,new u(this)),this.hn&&((l=this.sessionRecording)==null||l.onRemoteConfig==null||l.onRemoteConfig(this.hn)))}var c,d;this.consent.optInOut(!0),this.es(),this.Bn(),(n=this.sessionRecording)==null||n.startIfEnabledOrStop(),this.config.cookieless_mode==kn&&((c=this.surveys)==null||c.loadIfEnabled()),(C(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((d=e?.captureEventName)!==null&&d!==void 0?d:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hn()}else A.warn(ru)}opt_out_capturing(){var e,n,i;this.config.cookieless_mode!==Wt?(this.config.cookieless_mode===kn&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===kn&&(this.register({distinct_id:mr,$device_id:null}),(e=this.sessionRecording)==null||e.stopRecording(),this.sessionRecording=void 0,(n=this.sessionManager)==null||n.destroy(),(i=this.pageViewManager)==null||i.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.Hn(),this.Bn())):A.warn(ru)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===Wt||(this.config.cookieless_mode===kn?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return He?Hf(He,this.config.custom_blocked_useragents):void 0}Hn(){P&&(P.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(Gn,{title:P.title},{send_instantly:!0}),this.kn&&(P.removeEventListener(ts,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),ve(P,ts,this.kn)))}debug(e){e===!1?(w?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(w?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}Qi(){var e=this.Mn||{};return"advanced_disable_flags"in e?!!e.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(A.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(function(n,i,r,s,o){var a=i in n&&!H(n[i]),l=r in n&&!H(n[r]);return a?n[i]:!!l&&(o&&o.warn("Config field '"+r+"' is deprecated. Please use '"+i+"' instead. The old field will be removed in a future major version."),n[r])})(e,"advanced_disable_flags","advanced_disable_decide",0,A)}Pt(e){var n;if(H(this.config.before_send))return e;var i=Object.keys((n=e.properties)!==null&&n!==void 0?n:{}).filter(zp),r=U(this.config.before_send)?this.config.before_send:[this.config.before_send],s=e;for(var o of r){if(s=o(s),H(s)){var a="Event '"+e.event+"' was rejected in beforeSend function";return Wp(e.event)?A.warn(a+". This can cause unexpected behavior."):A.info(a),null}s.properties&&!Kt(s.properties)||A.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}for(var l of i)if(s.properties&&H(s.properties[l]))return A.warn("Event '"+e.event+"' had its '"+l+"' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped."),null;return s}getPageViewId(){var e;return(e=this.pageViewManager.ui)==null?void 0:e.pageViewId}captureTraceFeedback(e,n){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:n})}captureTraceMetric(e,n,i){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:n,$ai_metric_value:String(i)})}Cn(e){var n=mt(e)&&!e,i=le.N()&&le.P("ph_debug")==="true";return!n&&(!!i||e)}}Ze.__defaultExtensionClasses={},Ze.rs=(()=>{var t=()=>{};return{trace:t,debug:t,info:t,warn:t,error:t,fatal:t}})(),(function(t,e){for(var n=0;e.length>n;n++)t.prototype[e[n]]=Tg(t.prototype[e[n]])})(Ze,["identify"]);class au{constructor(e){this.disabled=e===!1;var n=he(e)?e:{};this.thresholdPx=n.threshold_px||30,this.timeoutMs=n.timeout_ms||1e3,this.clickCount=n.click_count||3,this.clicks=[]}isRageClick(e,n,i){if(this.disabled)return!1;var r=this.clicks[this.clicks.length-1];if(r&&Math.abs(e-r.x)+Math.abs(n-r.y)i-r.timestamp){if(this.clicks.push({x:e,y:n,timestamp:i}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:n,timestamp:i}];return!1}}var $o="$copy_autocapture",Mo=pe("[AutoCapture]");function Lo(t,e){return e.length>t?e.slice(0,t)+"...":e}function Nm(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!hn(e));return e}function Om(t,e){var n,i,r=e.e,s=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!hn(t))return{props:{}};for(var c=[t],d=new Set([t]),f=t;f.parentNode&&!et(f,"body")&&ff>c.length;)if(df(f.parentNode)){var h=f.parentNode.host;if(d.has(h))break;d.add(h),c.push(h),f=h}else{if(!hn(f.parentNode)||d.has(f.parentNode))break;d.add(f.parentNode),c.push(f.parentNode),f=f.parentNode}var p,g,m=[],v={},E=!1,S=!1;if(ie(c,(x=>{var F=va(x);if(et(x,"a")){var $=x.getAttribute("href");E=!!(F&&$&&Hi($))&&(u?fn($):$)}j(rs(x),"ph-no-capture")&&(S=!0),m.push((function(L,N,K,V,M){M===void 0&&(M=!1);var R=L.tagName.toLowerCase(),Z={tag_name:R};dl.indexOf(R)>-1&&!K&&(Z.$el_text=R.toLowerCase()==="a"||R.toLowerCase()==="button"?Lo(1024,Hc(L)):Lo(1024,Zi(L)));var Ce=rs(L);Ce.length>0&&(Z.classes=Ce.filter((function(ae){return ae!==""}))),ie(L.attributes,(function(ae){var Ie;if((!vf(L)||["name","id","class","aria-label"].indexOf(ae.name)!==-1)&&(V==null||!V.includes(ae.name))&&!N&&Hi(ae.value)&&(!X(Ie=ae.name)||Ie.substring(0,10)!=="_ngcontent"&&Ie.substring(0,7)!=="_nghost")){var Se=ae.value;ae.name==="class"&&(Se=ul(Se).join(" ")),Z["attr__"+ae.name]=Lo(1024,ae.name==="href"&&M?fn(Se):Se)}}));for(var oe=1,ye=1,$e=L;$e=Nm($e);)oe++,$e.tagName===L.tagName&&ye++;return Z.nth_child=oe,Z.nth_of_type=ye,Z})(x,s,o,a,u));var O=(function(L){if(!va(L))return{};var N={};return ie(L.attributes,(function(K){if(K.name&&K.name.indexOf("data-ph-capture-attribute")===0){var V=K.name.replace("data-ph-capture-attribute-",""),M=K.value;V&&M&&Hi(M)&&(N[V]=M)}})),N})(x);fe(v,O)})),S)return{props:{},explicitNoCapture:S};if(o||(m[0].$el_text=et(t,"a")||et(t,"button")?Hc(t):Zi(t)),E){var _,b;m[0].attr__href=E;var k=(_=ss(E))==null?void 0:_.host,T=w==null||(b=w.location)==null?void 0:b.host;k&&T&&k!==T&&(p=E)}return{props:fe({$event_type:r.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(x){return x.map((F=>{var $,O,L="";if(F.tag_name&&(L+=F.tag_name),F.attr_class)for(var N of(F.attr_class.sort(),F.attr_class))L+="."+N.replace(/"/g,"");var K=I({},F.text?{text:F.text}:{},{"nth-child":($=F.nth_child)!==null&&$!==void 0?$:0,"nth-of-type":(O=F.nth_of_type)!==null&&O!==void 0?O:0},F.href?{href:F.href}:{},F.attr_id?{attr_id:F.attr_id}:{},F.attributes),V={};return $r(K).sort(((M,R)=>M[0].localeCompare(R[0]))).forEach((M=>{var R=M[1];return V[Wc(M[0].toString())]=Wc(R.toString())})),(L+=":")+$r(V).map((M=>M[0]+'="'+M[1]+'"')).join("")})).join(";")})((function(x){return x.map((F=>{var $,O,L={text:($=F.$el_text)==null?void 0:$.slice(0,400),tag_name:F.tag_name,href:(O=F.attr__href)==null?void 0:O.slice(0,2048),attr_class:Zg(F),attr_id:F.attr__id,nth_child:F.nth_child,nth_of_type:F.nth_of_type,attributes:{}};return $r(F).filter((N=>N[0].indexOf("attr__")===0)).forEach((N=>L.attributes[N[0]]=N[1])),L}))})(g)))},(n=m[0])!=null&&n.$el_text?{$el_text:(i=m[0])==null?void 0:i.$el_text}:{},p&&r.type==="click"?{$external_click_url:p}:{},v)}}var ki=pe("[ExceptionAutocapture]"),lu=()=>{},Bm=pe("[TracingHeaders]"),wn=pe("[Web Vitals]"),cu=9e5,uu="disabled",du="lazy_loading",Ci="awaiting_config",Sr="missing_config";pe("[SessionRecording]"),pe("[SessionRecording]");var Ia="[SessionRecording]",Bt=pe(Ia),Dm=pe("[Heatmaps]");function No(t){return he(t)&&"clientX"in t&&"clientY"in t&&ke(t.clientX)&&ke(t.clientY)}var xr=pe("[Product Tours]"),Oo=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(ol))},jm=["$set_once","$set"],Et=pe("[SiteApps]"),fu="Error while initializing PostHog app with config id ";function qn(t,e,n){if(H(t))return!1;switch(n){case"exact":return t===e;case"contains":var i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(i,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}class Um{constructor(e){this.ns=new gl,this.ss=(n,i)=>this.os(n,i)&&this.ls(n,i)&&this.us(n,i)&&this.hs(n,i),this.os=(n,i)=>i==null||!i.event||n?.event===i?.event,this._instance=e,this.ds=new Set,this.vs=new Set}init(){var e,n;C((e=this._instance)==null?void 0:e._addCaptureHook)||(n=this._instance)==null||n._addCaptureHook(((i,r)=>{this.on(i,r)}))}register(e){var n,i;if(!C((n=this._instance)==null?void 0:n._addCaptureHook)&&(e.forEach((o=>{var a,l;(a=this.vs)==null||a.add(o),(l=o.steps)==null||l.forEach((u=>{var c;(c=this.ds)==null||c.add(u?.event||"")}))})),(i=this._instance)!=null&&i.autocapture)){var r,s=new Set;e.forEach((o=>{var a;(a=o.steps)==null||a.forEach((l=>{l!=null&&l.selector&&s.add(l?.selector)}))})),(r=this._instance)==null||r.autocapture.setElementSelectors(s)}}on(e,n){var i;n!=null&&e.length!=0&&(this.ds.has(e)||this.ds.has(n.event))&&this.vs&&((i=this.vs)==null?void 0:i.size)>0&&this.vs.forEach((r=>{this.cs(n,r)&&this.ns.emit("actionCaptured",r.name)}))}fs(e){this.onAction("actionCaptured",(n=>e(n)))}cs(e,n){if(n?.steps==null)return!1;for(var i of n.steps)if(this.ss(e,i))return!0;return!1}onAction(e,n){return this.ns.on(e,n)}ls(e,n){if(n!=null&&n.url){var i,r=e==null||(i=e.properties)==null?void 0:i.$current_url;if(!r||typeof r!="string"||!qn(r,n.url,n.url_matching||"contains"))return!1}return!0}us(e,n){return!!this.ps(e,n)&&!!this.gs(e,n)&&!!this.ys(e,n)}ps(e,n){var i;if(n==null||!n.href)return!0;var r=this.bs(e);if(r.length>0)return r.some((a=>qn(a.href,n.href,n.href_matching||"exact")));var s,o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!o&&qn((s=o.match(/(?::|")href="(.*?)"/))?s[1]:"",n.href,n.href_matching||"exact")}gs(e,n){var i;if(n==null||!n.text)return!0;var r=this.bs(e);if(r.length>0)return r.some((u=>qn(u.text,n.text,n.text_matching||"exact")||qn(u.$el_text,n.text,n.text_matching||"exact")));var s,o,a,l=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!l&&(s=(function(u){for(var c,d=[],f=/(?::|")text="(.*?)"/g;!H(c=f.exec(u));)d.includes(c[1])||d.push(c[1]);return d})(l),o=n.text,a=n.text_matching||"exact",s.some((u=>qn(u,o,a))))}ys(e,n){var i,r;if(n==null||!n.selector)return!0;var s=e==null||(i=e.properties)==null?void 0:i.$element_selectors;if(s!=null&&s.includes(n.selector))return!0;var o=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";if(n.selector_regex&&o)try{return new RegExp(n.selector_regex).test(o)}catch{return!1}return!1}bs(e){var n;return(e==null||(n=e.properties)==null?void 0:n.$elements)==null?[]:e?.properties.$elements}hs(e,n){return n==null||!n.properties||n.properties.length===0||qf(n.properties.reduce(((i,r)=>{var s=U(r.value)?r.value.map(String):r.value!=null?[String(r.value)]:[];return i[r.key]={values:s,operator:r.operator||"exact"},i}),{}),e?.properties)}}class Hm{constructor(e){var n;this._s=[],this._instance=e,this.ws=new Map,this.ks=new Map,this.xs=new Map,(n=this._instance)==null||n.onSessionId==null||n.onSessionId((i=>this.Ss(i)))}Cs(e){return!1}Ms(){return null}Ts(e){}Es(){}Is(e,n){return!!e&&qf(e.propertyFilters,n?.properties)}Ps(e,n){var i=new Map;return e.forEach((r=>{var s;(s=r.conditions)==null||(s=s[n])==null||(s=s.values)==null||s.forEach((o=>{if(o!=null&&o.name){var a=i.get(o.name)||[];a.push(r.id),i.set(o.name,a)}}))})),i}Rs(e,n,i){var r=(i===bi.Activation?this.ws:this.ks).get(e),s=[];return this.As((o=>{s=o.filter((a=>r?.includes(a.id)))})),s.filter((o=>{var a,l=(a=o.conditions)==null||(a=a[i])==null||(a=a.values)==null?void 0:a.find((u=>u.name===e));return this.Is(l,n)}))}register(e){var n;C((n=this._instance)==null?void 0:n._addCaptureHook)||(this.Fs(e),this.Ls(e))}Ls(e){var n=e.filter((i=>{var r,s;return((r=i.conditions)==null?void 0:r.actions)&&((s=i.conditions)==null||(s=s.actions)==null||(s=s.values)==null?void 0:s.length)>0}));n.length!==0&&(this.Os==null&&(this.Os=new Um(this._instance),this.Os.init(),this.Os.fs((i=>{this.onAction(i)}))),n.forEach((i=>{var r,s,o,a,l;i.conditions&&(r=i.conditions)!=null&&r.actions&&(s=i.conditions)!=null&&(s=s.actions)!=null&&s.values&&((o=i.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.Os)==null||a.register(i.conditions.actions.values),(l=i.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var c=this.xs.get(u.name);c&&c.push(i.id),this.xs.set(u.name,c||[i.id])}})))})))}Fs(e){var n,i=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.events)&&((a=s.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0})),r=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.cancelEvents)&&((a=s.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0}));i.length===0&&r.length===0||((n=this._instance)==null||n._addCaptureHook(((s,o)=>{this.onEvent(s,o)})),this.ws=this.Ps(e,bi.Activation),this.ks=this.Ps(e,bi.Cancellation))}onEvent(e,n){var i,r,s=this.Ds(),o=(n==null||(i=n.properties)==null?void 0:i.$survey_id)||(n==null||(r=n.properties)==null?void 0:r.$product_tour_id);if(o&&this.getActivatedIds().includes(o)){var a=this.$s(e,o);if(a==="consume")return s.info("event consumed activated item, removing it",{event:e,itemId:o}),void this.Ns([o]);if(a==="persist")return s.info("shown item promoted to persisted activation",{event:e,itemId:o}),this.qs(o),void this.js([o])}if(this.ks.has(e)){var l=this.Rs(e,n,bi.Cancellation);l.length>0&&(s.info("cancel event matched, cancelling items",{event:e,itemsToCancel:l.map((c=>c.id))}),this.Ns(l.map((c=>c.id))),l.forEach((c=>this.Bs(c.id))))}if(this.ws.has(e)){s.info("event name matched",{event:e,eventPayload:n,items:this.ws.get(e)});var u=this.Rs(e,n,bi.Activation);this.Hs(u.map((c=>c.id)))}}onAction(e){this.xs.has(e)&&this.Hs(this.xs.get(e)||[])}Hs(e){var n;if(e.length!==0){var i=!((n=this._instance)==null||n.get_session_id==null||!n.get_session_id()),r=[];for(var s of e)i&&this.Cs(s)?this.qs(s)&&this.Us(s):r.push(s);r.length>0&&(this._s=[...new Set([...this._s,...r])]),this.Ds().info("updating activated items",{activatedItems:this.getActivatedIds()})}}qs(e){this._s=this._s.filter((i=>i!==e));var n=this.zs();return!n.includes(e)&&(this.Ws([...n,e]),this.Vs(),!0)}Ns(e){var n=new Set(e);this._s=this._s.filter((s=>!n.has(s)));var i=this.Zs(),r=i.filter((s=>!n.has(s)));r.length!==i.length&&(this.Ws(r),r.length===0&&this.Gs()),this.js(e)}Qs(){var e,n=this.Ms();if(!n)return{};var i=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n];return i&&typeof i=="object"?i:{}}Us(e){if(this.Ms()){var n=this.Qs();this.Ts(I({},n,{[e]:Date.now()}))}}js(e){if(this.Ms()){var n=this.Qs(),i={},r=!1;for(var s of Object.entries(n)){var o=s[0],a=s[1];e.includes(o)?r=!0:i[o]=a}r&&(Kt(i)?this.Es():this.Ts(i))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var n=this.Qs()[e];return ke(n)?n:void 0}}Zs(){var e,n=this.Js();return((e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n])||[]}zs(){var e,n,i=this.Zs();if(i.length===0)return[];var r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[this.Ys()],s=(n=this._instance)==null||n.get_session_id==null?void 0:n.get_session_id();return s&&r===s?i:[]}Vs(){var e,n=(e=this._instance)==null||e.get_session_id==null?void 0:e.get_session_id();n&&this.Xs(n)}Gs(){this.ta()}Ss(e){var n,i=(n=this._instance)==null||(n=n.persistence)==null?void 0:n.props[this.Ys()];if(i&&i!==e){var r=this.Zs(),s=this.Qs();r.length>0&&(this.Ws([]),r.filter((o=>ke(s[o]))).forEach((o=>this.Bs(o)))),this.Gs(),this.Ks()}}getActivatedIds(){return[...new Set([...this.zs(),...this._s])].filter((e=>!this.ea(e)))}reset(){this._s=[],this.Zs().length>0&&this.Ws([]),this.Gs(),this.Ks()}getEventToItemsMap(){return this.ws}ia(){return this.Os}}class Wm extends Hm{constructor(e){super(e)}Js(){return ca}Ys(){return Fr}Ms(){return Rr}Ts(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Rr]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Rr)}Cs(e){var n,i;this.As((s=>{i=s.find((o=>o.id===e))}));var r=(n=i)==null||(n=n.appearance)==null?void 0:n.surveyPopupDelaySeconds;return ke(r)&&r>0}ra(){return qt.SHOWN}As(e){var n;(n=this._instance)==null||n.getSurveys(e)}Bs(e){var n;(n=this._instance)==null||n.cancelPendingSurvey(e)}Ds(){return Q}Ws(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[ca]:e})}Xs(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Fr]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Fr)}ea(){return!1}$s(e,n){var i;this.As((s=>{i=s.find((o=>o.id===n))}));var r=!i||(function(s){var o;return Vf(s)&&!((o=s.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||s.schedule==="always"})(i);return r?e===qt.SHOWN?"consume":"ignore":e===qt.SHOWN?"persist":e===qt.DISMISSED||e===qt.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var Ir="SDK is not enabled or survey functionality is not yet loaded",hu="Disabled. Not loading surveys.",zm=w!=null&&w.location?os(w.location.hash,"__posthog")||os(location.hash,"state"):null,pu="_postHogToolbarParams",gu=pe("[Toolbar]"),mu=pe("[FeatureFlags]");class qm{constructor(e,n){n===void 0&&(n=!1),this.na=!1,this.update(e,n)}update(e,n){this.sa=((i,r)=>{var s,o,a,l;return{bootstrap:{featureFlags:(s=i.bootstrap)==null?void 0:s.featureFlags,featureFlagPayloads:(o=i.bootstrap)==null?void 0:o.featureFlagPayloads},remoteRequestsDisabled:r,featureFlagsDisabled:!!i.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!i.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!i.advanced_feature_flags_dedup_per_session,cacheTtlMs:i.feature_flag_cache_ttl_ms,requestTimeoutMs:i.feature_flag_request_timeout_ms,compression:i.disable_compression?"none":"base64",evaluationContexts:(a=(l=i.evaluation_contexts)!==null&&l!==void 0?l:i.evaluation_environments)!==null&&a!==void 0?a:[],flagKeys:U(i.flag_keys)?i.flag_keys:void 0}})(e,n),!e.evaluation_environments||e.evaluation_contexts||this.na||(mu.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.na=!0),C(e.flag_keys)||U(e.flag_keys)||mu.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var vu=pe("[FeatureFlags]"),bn=pe("[FeatureFlags]",{debugEnabled:!0}),Bo=`" failed. Feature flags didn't load in time.`,_u="connection_error",yu=t=>{for(var e={},n=0;t.length>n;n++)e[t[n]]=!0;return e},wu=t=>{var e={};for(var n of $r(t||{})){var i=n[1];i&&(e[n[0]]=i)}return e},St=pe("[Error tracking]"),bu="Refusing to render web experiment since the viewer is a likely bot",Vm={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>cs(e,t),not_regex:(t,e)=>!cs(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class Me{get Ne(){return this._instance.config}constructor(e){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(i){i===void 0&&(i=!1),n.getWebExperiments((r=>{Me.aa("retrieved web experiments from the server"),n.oa=new Map,r.forEach((s=>{if(s.feature_flag_key){var o;n.oa&&(Me.aa("setting flag key ",s.feature_flag_key," to web experiment ",s),(o=n.oa)==null||o.set(s.feature_flag_key,s));var a=n._instance.getFeatureFlag(s.feature_flag_key);X(a)&&s.variants[a]&&n.la(s.name,a,s.variants[a].transforms)}else if(s.variants)for(var l in s.variants){var u=s.variants[l];Me.ua(u,n._instance)&&n.la(s.name,l,u.transforms)}}))}),i)},this._instance=e,this._instance.onFeatureFlags((i=>{this.onFeatureFlags(i)}))}initialize(){}onFeatureFlags(e){if(this._is_bot())Me.aa(bu);else if(!this.Ne.disable_web_experiments){if(H(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();Me.aa("applying feature flags",e),e.forEach((n=>{var i;if(this.oa&&(i=this.oa)!=null&&i.has(n)){var r,s=this._instance.getFeatureFlag(n),o=(r=this.oa)==null?void 0:r.get(n);s&&o!=null&&o.variants[s]&&this.la(o.name,s,o.variants[s].transforms)}}))}}previewWebExperiment(){var e=Me.getWindowLocation();if(e!=null&&e.search){var n=ri(e?.search,"__experiment_id"),i=ri(e?.search,"__experiment_variant");n&&i&&(Me.aa("previewing web experiments "+n+" && "+i),this.getWebExperiments((r=>{this.ha(parseInt(n),i,r)}),!1,!0))}}loadIfEnabled(){this.Ne.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,n,i){if(this.Ne.disable_web_experiments&&!i)return e([]);var r=this._instance.get_property("$web_experiments");if(r&&!n)return e(r);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this.Ne.token),method:"GET",timestampMode:"query",callback:s=>e(s.statusCode===200&&s.json&&s.json.experiments||[])})}ha(e,n,i){var r=i.filter((s=>s.id===e));r&&r.length>0&&(Me.aa("Previewing web experiment ["+r[0].name+"] with variant ["+n+"]"),this.la(r[0].name,n,r[0].variants[n].transforms))}static ua(e,n){return!H(e.conditions)&&Me.da(e,n)&&Me.va(e)}static da(e,n){var i;if(H(e.conditions)||H((i=e.conditions)==null?void 0:i.url))return!0;var r=Me.getWindowLocation();if(r){var s,o,a,l=lf(n,r.href);return(s=e.conditions)==null||!s.url||Vm[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return w?.location}static va(e){var n;if(H(e.conditions)||H((n=e.conditions)==null?void 0:n.utm))return!0;var i=Sf();if(i.utm_source){var r,s,o,a,l,u,c,d,f=(r=e.conditions)==null||(r=r.utm)==null||!r.utm_campaign||((s=e.conditions)==null||(s=s.utm)==null?void 0:s.utm_campaign)==i.utm_campaign,h=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==i.utm_source,p=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==i.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==i.utm_term;return f&&p&&g&&h}return!1}static aa(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;n>r;r++)i[r-1]=arguments[r];A.info("[WebExperiments] "+e,i)}la(e,n,i){this._is_bot()?Me.aa(bu):n!=="control"?i.forEach((r=>{if(r.selector){var s;Me.aa("applying transform of variant "+n+" for experiment "+e+" ",r);var o=(s=document)==null?void 0:s.querySelectorAll(r.selector);o?.forEach((a=>{var l=a;r.html&&(l.innerHTML=r.html),r.css&&l.setAttribute("style",r.css)}))}})):Me.aa("Control variants leave the page unmodified.")}_is_bot(){return He&&this._instance?Hf(He,this.Ne.custom_blocked_useragents):void 0}}var ot=pe("[Conversations]"),En="Conversations not available yet.",Eu="console",Zf="__posthogHandledLogsRequestError",Do=(t,e)=>{var n=t instanceof Error?t:new Error(e);return n[Zf]=!0,n},Su=t=>!!t&&typeof t=="object"&&t[Zf]===!0,Cs={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=vu,this.fa={},this.pa={},this.ga=[],this.ma=!1,this.ya=!1,this.ba=0,this._a=!1,this.wa=!1,this.ka=!1,this.xa=!1,this.Sa=0,this.Ca=()=>{var e=this.Ma();this.Sa=0,e&&this.reloadFeatureFlags()},"get"in t?this.Ta=t:(this.Ea=new qm(t.config,t.Qi()),this.Ta=this.Ea)}updateConfig(t,e){var n;(n=this.Ea)==null||n.update(t,e)}setup(t){return this.Ia=t,this.rt=t.logger.createLogger("[FeatureFlags]"),n=()=>{this.Ia===t&&(this.Ia=void 0,this.nn=t,this.Pa(t))},(e=t.kv.initialize())!=null&&e.then?e.then(n):n();var e,n}Pa(t){if(this.nn===t)return w&&ve(w,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){w?.removeEventListener("online",this.Ca)}dispose(){var t;this.ba++,this.wa=!1,this.Ia=void 0,this.nn&&(this.La(),(t=this.Ra)==null||t.dispose(),this.Ra=void 0,this.ga=[],w?.removeEventListener("online",this.Ca),this.nn=void 0)}get Ne(){return this.Ta.get()}Oa(t){var e;return(e=this.nn)==null?void 0:e.kv.get(t)}F(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.set(t)}))}q(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.remove(t)}))}Da(t){try{t()}catch(e){this.rt.error("Failed to update feature flag persistence",e)}}Fa(){var t={};for(var e of[$i,Mi,Pr,It]){var n=this.Oa(e);C(n)||(t[e]=n)}this.fa=t;var i=I({},t),r=this.Oa(Sn);if(r)for(var s of Object.entries(r))i["$feature/"+s[0]]=s[1];this.pa=i}Aa(){var t=this.Ne.cacheTtlMs;if(!t||0>=t)return!1;var e=this.Oa(Ui);return typeof e!="number"||Date.now()-e>t}$a(){return!!this.Aa()&&(this.xa||this.ya||(this.xa=!0,this.rt.warn("Feature flag cache is stale, triggering refresh..."),this.reloadFeatureFlags()),!0)}Na(){var t=this.Ne.evaluationContexts;return t!=null&&t.length?t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid evaluation context found:",e,"Expected non-empty string"),n})):[]}qa(){var t=this.Ne.flagKeys;if(!C(t))return t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid flag key found:",e,"Expected non-empty string"),n}))}initialize(){var t,e,n=this.Ne,i=(t=(e=n.bootstrap)==null?void 0:e.featureFlags)!==null&&t!==void 0?t:{};if(Object.keys(i).length){var r,s,o=(r=(s=n.bootstrap)==null?void 0:s.featureFlagPayloads)!==null&&r!==void 0?r:{},a=Object.keys(i).filter((u=>!!i[u])).reduce(((u,c)=>(u[c]=i[c]||!1,u)),{}),l=Object.keys(o).filter((u=>a[u])).reduce(((u,c)=>(o[c]&&(u[c]=o[c]),u)),{});return this.ja({featureFlags:a,featureFlagPayloads:l})}}updateFlags(t,e,n){var i,r,s=n!=null&&n.merge&&(i=this.Oa(Sn))!==null&&i!==void 0?i:{},o=n!=null&&n.merge&&(r=this.Oa(Mi))!==null&&r!==void 0?r:{},a=I({},s,t),l=I({},o,e),u={};for(var c of Object.entries(a)){var d=c[0],f=c[1];u[d]={key:d,enabled:gc(f),variant:mc(f),reason:void 0,metadata:C(l?.[d])?void 0:{id:0,version:void 0,description:void 0,payload:l[d]}}}this.ja({flags:u})}get hasLoadedFlags(){return this.ma}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var t=this.Oa(aa),e=this.Oa(It),n=this.Oa(xn);if(!n&&!e)return t||{};var i=fe({},t||{}),r=[...new Set([...Object.keys(n||{}),...Object.keys(e||{})])];for(var s of r){var o,a,l=i[s],u=e?.[s],c=C(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=C(u)?l?.variant:typeof u=="string"?u:void 0,f=n?.[s],h=I({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(h.original_enabled=l?.enabled),d!==l?.variant&&(h.original_variant=l?.variant),f&&(h.metadata=I({},l?.metadata,{payload:f,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),i[s]=h}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:n,finalDetails:i}),this.ca=!0),i}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((n=>{var i=t[n];return{key:n,enabled:gc(i),variant:mc(i),payload:pc(e[n])}}))}getFlagVariants(){var t=this.Oa(Sn),e=this.Oa(It);if(!e)return t||{};for(var n=fe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:e,finalFlags:n}),this.ca=!0),n}getFlagPayloads(){var t=this.Oa(Mi),e=this.Oa(xn);if(!e)return t||{};for(var n=fe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flag payloads!",{flagPayloads:t,overriddenPayloads:e,finalPayloads:n}),this.ca=!0),n}reloadFeatureFlags(){this._a||this.Ne.featureFlagsDisabled||this.Ma()||this.Ba||(this.ga.slice().forEach((t=>{try{t()}catch(e){this.rt.error("Error while running feature flags reloading callback",e)}})),this.Ba=setTimeout((()=>{this.Ha()}),5))}La(){clearTimeout(this.Ba),this.Ba=void 0}onReloading(t){return this.ga.push(t),()=>{this.ga=this.ga.filter((e=>e!==t))}}ensureFlagsLoaded(){this.ma||this.ya||this.Ba||this.reloadFeatureFlags()}setAnonymousDistinctId(t){this.$anon_distinct_id=t}setReloadingPaused(t){this._a=t}resetFlagCallReported(){this.q(Cn)}Ha(t){this.La();var e=this.nn;if(e&&!this.Ne.remoteRequestsDisabled&&!this.Ma())if(this.ya)this.wa=!0;else{var n={token:e.projectToken,distinct_id:e.distinctId,groups:e.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:I({},e.initialPersonProperties,this.Oa(jt)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(In),timezone:Pf()};C(e.deviceId)||(n.$device_id=e.deviceId),(t!=null&&t.disableFlags||this.Ne.featureFlagsDisabled)&&(n.disable_flags=!0);var i=this.Na();i.length&&(n.evaluation_contexts=i);var r=this.qa();C(r)||(n.flag_keys=r);var s=this.Ne.onlyEvaluateSurveyFeatureFlags,o="/flags/?v=2"+(s?"&only_evaluate_survey_feature_flags=true":""),a=this.ba;this.ya=!0;var l=()=>{this.wa&&(this.wa=!1,this.Ha())},u=c=>{this.ya=!1,a===this.ba&&(this.F({[Tr]:[_u]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:n,compression:this.Ne.compression==="base64"?Ue.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,f,h=(d=c.json)!==null&&d!==void 0?d:{},p=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),p||this.wa||(this.$anon_distinct_id=void 0),!n.disable_flags||this.wa){this.ka=!p;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?_u:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),h.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((f=h.quotaLimited)==null||!f.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[Tr]:g}),m?this.rt.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more."):n.disable_flags||this.ja(h,p,{partialResponse:s}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return bf(this.Sa,3)}Ua(t){this.Sa=Ef(t,this.Sa,3,(()=>this.rt.warn("Feature flag requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped refreshing feature flags; will try again when connectivity changes.")))}getFeatureFlag(t,e){var n;if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var i=this.getFeatureFlagResult(t,e);return(n=i?.variant)!==null&&n!==void 0?n:i?.enabled}}else this.rt.warn('getFeatureFlag for key "'+t+Bo)}getFeatureFlagDetails(t){return this.getFlagsWithDetails()[t]}getFeatureFlagPayload(t){var e=this.getFeatureFlagResult(t,{send_event:!1});return e?.payload}getFeatureFlagResult(t,e){if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var n,i=this.getFlagVariants(),r=t in i,s=i[t],o=this.getFlagPayloads()[t],a=String(s),l=this.Oa(Pr)||void 0,u=this.Oa(Ui)||void 0,c=this.Oa(Cn)||{};if(this.Ne.deduplicateCallsPerSession){var d,f=(d=this.nn)==null?void 0:d.session.sessionId,h=this.Oa(Ni);f&&f!==h&&(c={},n=f)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))n&&this.F({[Cn]:c,[Ni]:n});else{var p,g,m,v,E,S,_,b,k,T;U(c[t])?c[t].push(a):c[t]=[a],this.F(I({[Cn]:c},n?{[Ni]:n}:{}));var x=this.getFeatureFlagDetails(t),F=[...(p=this.Oa(Tr))!==null&&p!==void 0?p:[]];C(s)&&F.push("flag_missing");var $={$feature_flag:t,$feature_flag_response:s,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((g=this.Ne.bootstrap)==null||(g=g.featureFlags)==null?void 0:g[t])||null,$feature_flag_bootstrapped_payload:((m=this.Ne.bootstrap)==null||(m=m.featureFlagPayloads)==null?void 0:m[t])||null,$used_bootstrap_value:!this.ka};C(x==null||(v=x.metadata)==null?void 0:v.has_experiment)||($.$feature_flag_has_experiment=x.metadata.has_experiment),C(x==null||(E=x.metadata)==null?void 0:E.version)||($.$feature_flag_version=x.metadata.version);var O,L=(S=x==null||(_=x.reason)==null?void 0:_.description)!==null&&S!==void 0?S:x==null||(b=x.reason)==null?void 0:b.code;L&&($.$feature_flag_reason=L),x!=null&&(k=x.metadata)!=null&&k.id&&($.$feature_flag_id=x.metadata.id),C(x?.original_variant)&&C(x?.original_enabled)||($.$feature_flag_original_response=C(x.original_variant)?x.original_enabled:x.original_variant),x!=null&&(T=x.metadata)!=null&&T.original_payload&&($.$feature_flag_original_payload=x==null||(O=x.metadata)==null?void 0:O.original_payload),F.length&&($.$feature_flag_error=F.join(",")),this.za($)}else n&&this.F({[Cn]:c,[Ni]:n});if(r)return{key:t,enabled:!!s,variant:typeof s=="string"?s:void 0,payload:pc(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+Bo)}za(t){try{var e;(e=this.nn)==null||e.capture("$feature_flag_called",t).catch((n=>{this.rt.error("Failed to capture feature flag call",n)}))}catch(n){this.rt.error("Failed to capture feature flag call",n)}}getRemoteConfigPayload(t,e){this.Wa(t,e)}Wa(t,e){var n=this;return se((function*(){var i=n.nn;if(i){var r={distinct_id:i.distinctId,token:i.projectToken,person_properties:{$lib:i.library.name,$lib_version:i.library.version}},s=n.Na();s.length&&(r.evaluation_contexts=s);var o,a=n.qa();C(a)||(r.flag_keys=a);try{var l,u=(l=(yield i.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:r,compression:n.Ne.compression==="base64"?Ue.Base64:void 0,sentAt:"body",timeoutMs:n.Ne.requestTimeoutMs})).json)==null?void 0:l.featureFlagPayloads;o=u?.[t]||void 0}catch(c){return void n.rt.error("Remote config feature flag request failed",c)}try{e(o)}catch(c){n.rt.error("Remote config feature flag callback failed",c)}}}))()}isFeatureEnabled(t,e){if(e===void 0&&(e={}),e.fresh&&!this.ka)return e.defaultValue;if(!(this.ma||this.getFlags()&&this.getFlags().length>0))return this.rt.warn('isFeatureEnabled for key "'+t+Bo),e.defaultValue;var n=this.getFeatureFlag(t,e);return C(n)?e.defaultValue:!!n}addFeatureFlagsHandler(t){this.featureFlagEventHandlers.push(t)}removeFeatureFlagsHandler(t){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((e=>e!==t))}receivedFeatureFlags(t,e,n){this.ja(t,e,n)}ja(t,e,n){if(this.nn){this.ma=!0;var i=(function(r,s,o,a,l,u){s===void 0&&(s={}),o===void 0&&(o={}),a===void 0&&(a={}),u===void 0&&(u=vu);var c=((k,T)=>{var x=k.flags;return x?I({},k,{featureFlags:Object.fromEntries(Object.keys(x).map((F=>{var $;return[F,($=x[F].variant)!==null&&$!==void 0?$:x[F].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(x).filter((F=>x[F].enabled)).filter((F=>{var $;return($=x[F].metadata)==null?void 0:$.payload})).map((F=>{var $;return[F,($=x[F].metadata)==null?void 0:$.payload]})))}):(k.featureFlags&&T.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),k)})(r,u),d=c.flags,f=c.featureFlags,h=c.featureFlagPayloads;if(f){var p=r.requestId,g=r.evaluatedAt;if(U(f)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(f)for(var v=0;f.length>v;v++)m[f[v]]=!0;return{[$i]:f,[Sn]:m,[Zr]:!1}}var E=f,S=h,_=d;if(l!=null&&l.partialResponse)E=I({},s,E),S=I({},o,S),_=I({},a,_);else if(r.errorsWhileComputingFlags)if(d){var b=new Set(Object.keys(d).filter((k=>{var T;return!((T=d[k])!=null&&T.failed)})));E=I({},s,Object.fromEntries(Object.entries(E).filter((k=>b.has(k[0]))))),S=I({},o,Object.fromEntries(Object.entries(S||{}).filter((k=>b.has(k[0]))))),_=I({},a,Object.fromEntries(Object.entries(_||{}).filter((k=>b.has(k[0])))))}else E=I({},s,E),S=I({},o,S),_=I({},a,_);return I({[$i]:Object.keys(wu(E)),[Sn]:E||{},[Mi]:S||{},[aa]:_||{},[Zr]:r.minimalFlagCalledEvents===!0},p?{[Pr]:p}:{},g?{[Ui]:g}:{})}})(t,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),n,this.rt);i&&this.F(i),e||(this.xa=!1),this.Va(e)}}override(t,e){e===void 0&&(e=!1),this.rt.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:t,suppressWarning:e})}overrideFeatureFlags(t){this.Za(t)}Za(t){if(this.nn){if(t===!1)return this.q([It,xn]),this.Va(),void bn.info("All overrides cleared");if(U(t))return this.F({[It]:yu(t)}),this.Va(),void bn.info("Flag overrides set",{flags:t});if(t&&typeof t=="object"&&("flags"in t||"payloads"in t)){var e,n=t;this.ca=!!((e=n.suppressWarning)!==null&&e!==void 0&&e);var i={},r=n.flags,s=n.payloads;return r&&(i[It]=U(r)?yu(r):r),s&&(i[xn]=s),Object.keys(i).length&&this.F(i),r===!1&&s===!1?this.q([It,xn]):r===!1?this.q(It):s===!1&&this.q(xn),this.Va(),r===!1?bn.info("Flag overrides cleared"):r&&bn.info("Flag overrides set",{flags:r}),void(s===!1?bn.info("Payload overrides cleared"):s&&bn.info("Payload overrides set",{payloads:s}))}if(t&&typeof t=="object")return this.F({[It]:t}),this.Va(),void bn.info("Flag overrides set",{flags:t});this.rt.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:t})}else this.rt.warn("posthog.featureFlags.overrideFeatureFlags called before feature flags were ready")}onFeatureFlags(t){if(this.addFeatureFlagsHandler(t),this.ma){var e=this.Ga(),n=e.flags,i=e.flagVariants;try{t(n,i)}catch(r){this.rt.error("Error while running feature flags callback",r)}}return()=>this.removeFeatureFlagsHandler(t)}updateEarlyAccessFeatureEnrollment(t,e,n){var i=(this.Oa(Ar)||[]).find((l=>l.flagKey===t)),r={["$feature_enrollment/"+t]:e},s={$feature_flag:t,$feature_enrollment:e,$set:r};i&&(s.$early_access_feature_name=i.name),n&&(s.$feature_enrollment_stage=n);var o=I({},this.getFlagVariants(),{[t]:e});this.F({[$i]:Object.keys(wu(o)),[Sn]:o,[jt]:I({},this.Oa(jt)||{},r)}),this.Va();try{var a;(a=this.nn)==null||a.capture("$feature_enrollment_update",s).catch((l=>{this.rt.error("Failed to capture early access feature enrollment",l)}))}catch(l){this.rt.error("Failed to capture early access feature enrollment",l)}}getEarlyAccessFeatures(t,e,n){e===void 0&&(e=!1);var i=this.Oa(Ar);!i||e?this.Qa(t,n):t(i)}Qa(t,e){var n=this;return se((function*(){var i=n.nn;if(i){var r,s=e?"&"+e.map((a=>"stage="+a)).join("&"):"";try{var o=yield i.sendRequest("/api/early_access_features/?token="+i.projectToken+s,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;n.F({[Ar]:r=o.json.earlyAccessFeatures})}catch(a){return void n.rt.error("Early access feature request failed",a)}try{t(r)}catch(a){n.rt.error("Early access feature callback failed",a)}}}))()}Ga(){var t=this.getFlags(),e=this.getFlagVariants();return{flags:t.filter((n=>e[n])),flagVariants:Object.keys(e).filter((n=>e[n])).reduce(((n,i)=>(n[i]=e[i],n)),{})}}Va(t){this.Fa();var e=this.Ga(),n=e.flags,i=e.flagVariants;this.featureFlagEventHandlers.forEach((r=>{try{r(n,i,{errorsLoading:t})}catch(s){this.rt.error("Error while running feature flags callback",s)}}))}setPersonPropertiesForFlags(t,e){e===void 0&&(e=!0),this.Ka(t,e)}Ka(t,e){e===void 0&&(e=!0);var n=this.Oa(jt)||{},i=t?.$set||(t!=null&&t.$set_once?{}:t),r=t?.$set_once,s={};if(r)for(var o in r)({}).hasOwnProperty.call(r,o)&&(o in n||(s[o]=r[o]));this.F({[jt]:I({},n,s,i)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=I({},this.Oa(jt)||{});t.forEach((i=>{delete n[i]})),this.F({[jt]:n}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(jt),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=this.Oa(In)||{},i=I({},n);for(var r of Object.keys(t))i[r]=I({},n[r],t[r]);this.F({[In]:i}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(In)||{};this.F({[In]:I({},e,{[t]:{}})})}else this.q(In)}reset(){this.ba++,this.wa=!1,this.Fa(),this.ma=!1,this._a=!1,this.ka=!1,this.$anon_distinct_id=void 0,this.La(),this.ca=!1,this.Sa=0}}},Gm={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===Ci||this.Ya===Sr?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=uu,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(P==null||!P.visibilityState||P.visibilityState==="visible")return!0;var n=w==null||(e=w.performance)==null||e.getEntriesByType==null?void 0:e.getEntriesByType("visibility-state");return!(n!=null&&n.length)||n.some((i=>i.name==="visible"))})(),this.Ie=()=>{var e;P?.visibilityState==="visible"&&(this.io=!0,(e=this.Ja)==null||e.setDocumentWasEverVisible==null||e.setDocumentWasEverVisible(!0))},this._instance=t,!this._instance.sessionManager)throw Bt.error("started without valid sessionManager"),new Error(Ia+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===Wt)throw new Error(Ia+' cannot be used with cookieless_mode="always"');P!=null&&P.addEventListener&&ve(P,"visibilitychange",this.Ie)}initialize(){this.startIfEnabledOrStop()}dispose(){this.eo=!0,P==null||P.removeEventListener==null||P.removeEventListener("visibilitychange",this.Ie),this.stopRecording()}get ro(){var t,e=!((t=this._instance.get_property(An))==null||!t.enabled),n=!this.Ne.disable_session_recording,i=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return w&&e&&n&&!i}startIfEnabledOrStop(t){var e;if(!(this.eo||this.ro&&(e=this.Ja)!=null&&e.isStarted)){var n=!C(Object.assign)&&!C(Array.from);this.ro&&n?(this.no(t),Bt.info("starting")):(this.Ya=uu,this.stopRecording())}}no(t){var e,n,i;this.ro&&(this.Ya!==Ci&&this.Ya!==Sr&&(this.Ya=du),B!=null&&(e=B.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(n=B.__PosthogExtensions__)!=null&&n.initSessionRecording?this.so(t):(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,this.ao,(r=>{if(r)return Bt.error("could not load recorder",r);this.so(t)})))}stopRecording(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.stop()}oo(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.discard()}lo(){var t,e;(t=this.Mr)==null||t.unregister(al),(e=this.Mr)==null||e.unregister(Jd)}uo(t,e){if(H(t))return null;var n,i=ke(t)?t:parseFloat(t);return typeof(n=i)!="number"||!Number.isFinite(n)||0>n||n>1?(Bt.warn(e+" must be between 0 and 1. Ignoring invalid value:",t),null):i}ho(t){if(this.Mr){var e,n,i=this.Mr,r=()=>{var s,o=t.sessionRecording===!1?void 0:t.sessionRecording,a=this.uo((s=this.Ne.session_recording)==null?void 0:s.sampleRate,"session_recording.sampleRate"),l=this.uo(o?.sampleRate,"remote config sampleRate"),u=a??l;H(u)&&this.lo();var c=o?.minimumDurationMilliseconds;i.register({[An]:I({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:I({capturePerformance:t.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:u,minimumDurationMilliseconds:C(c)?null:c,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers,version:o?.version,triggerGroups:o?.triggerGroups})})};r(),(e=this.Xa)==null||e.call(this),this.Xa=(n=this._instance.sessionManager)==null?void 0:n.onSessionId(r)}}onRemoteConfig(t){var e=t.ok?t.config:void 0;return e&&"sessionRecording"in e?e.sessionRecording===!1?(this.ho(e),void this.oo()):(this.ho(e),void this.startIfEnabledOrStop()):(this.Ya===Ci&&(this.Ya=Sr,Bt.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(t,e){var n;e===void 0&&(e="log"),(n=this.Ja)!=null&&n.log?this.Ja.log(t,e):Bt.warn("log called before recorder was ready")}get ao(){var t,e,n=(t=this._instance)==null||(t=t.persistence)==null?void 0:t.get_property(An);return(n==null||(e=n.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(An);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(n){return Bt.warn("persisted remote config for session recording is invalid and will be ignored",n),!1}return!H(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,n,i;if(!this.eo){if((e=B.__PosthogExtensions__)==null||!e.initSessionRecording)return Bt.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[sf]:!0});var r;if(this.Ja||(this.Ja=(r=B.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===Sr||this.Ya===Ci?void 0:(this.Ya=Ci,Bt.info("persisted remote config is stale, requesting fresh config before starting"),void new Ff(this._instance).load());this.Ya=du,(n=(i=this.Ja).setDocumentWasEverVisible)==null||n.call(i,this.io),this.Ja.start(t)}}onRRwebEmit(t){var e;(e=this.Ja)==null||e.onRRwebEmit==null||e.onRRwebEmit(t)}overrideLinkedFlag(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Xd]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Zd]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,n;this.Ja||(n=this.Mr)==null||n.register({[t==="url"?Qd:ef]:!0}),(e=this.Ja)==null||e.overrideTrigger(t)}get sdkDebugProperties(){var t;return((t=this.Ja)==null?void 0:t.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(t,e){var n;return!((n=this.Ja)==null||!n.tryAddCustomEvent(t,e))}}},Km={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new au(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,n=he(this.instance.config.autocapture)?this.instance.config.autocapture:{};return n.url_allowlist=(t=n.url_allowlist)==null?void 0:t.map((i=>new RegExp(i))),n.url_ignorelist=(e=n.url_ignorelist)==null?void 0:e.map((i=>new RegExp(i))),n}yo(){if(this.isBrowserSupported()){if(w&&P){var t=n=>{n=n||w?.event;try{this.bo(n)}catch(i){Mo.error("Failed to capture event",i)}};if(ve(P,"submit",t,{capture:!0}),ve(P,"change",t,{capture:!0}),ve(P,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=n=>{n=n||w?.event;try{this.bo(n,$o)}catch(i){Mo.error("Failed to capture copy/cut event",i)}};ve(P,"copy",e,{capture:!0}),ve(P,"cut",e,{capture:!0})}}}else Mo.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.vo&&(this.yo(),this.vo=!0)}onRemoteConfig(t){if(this.fo=!0,t.ok){var e=t.config;e.elementsChainAsString&&(this.po=e.elementsChainAsString);var n=e.autocapture_opt_out;mt(n)&&(this.instance.persistence&&this.instance.persistence.register({[ea]:n}),this.co=n),this.startIfEnabled()}else this.startIfEnabled()}setElementSelectors(t){this.mo=t}getElementSelectors(t){var e,n=[];return(e=this.mo)==null||e.forEach((i=>{var r=P?.querySelectorAll(i);r?.forEach((s=>{t===s&&n.push(i)}))})),n}get isEnabled(){var t,e,n=(t=this.instance.persistence)==null?void 0:t.props[ea],i=this.co,r=this.instance.Qi()&&!this.fo;if(Ye(i)&&!mt(n)&&!r)return!1;var s=(e=this.co)!==null&&e!==void 0?e:!!n;return!!this.instance.config.autocapture&&!s}bo(t,e){if(e===void 0&&(e="$autocapture"),this.isEnabled){var n,i=bo(t);uf(i)&&(i=i.parentNode||null),e==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&this.instance.config.rageclick&&(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,t.timeStamp||new Date().getTime())&&Oc(i,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var r=e===$o;if(i&&(function(d,f,h,p,g,m){var v;if(!w||fl(d)||h!=null&&h.url_allowlist&&!Mc(h.url_allowlist,m)||h!=null&&h.url_ignorelist&&Mc(h.url_ignorelist,m))return!1;if(h!=null&&h.dom_event_allowlist){var E=h.dom_event_allowlist;if(E&&!E.some((x=>f.type===x)))return!1}var S=mf(d,p),_=S.parentIsUsefulElement,b=S.targetElementList;if(!(function(x,F){var $=F?.element_allowlist;if(C($))return!0;var O,L=function(K){if($.some((V=>K.tagName.toLowerCase()===V)))return{v:!0}};for(var N of x)if(O=L(N))return O.v;return!1})(b,h)||!ma(b,h?.css_selector_allowlist)||ma(b,(v=h?.css_selector_ignorelist)!==null&&v!==void 0?v:qg))return!1;try{var k=w.getComputedStyle(d);if(k&&k.getPropertyValue("cursor")==="pointer"&&f.type==="click")return!0}catch{}var T=d.tagName.toLowerCase();switch(T){case"html":return!1;case"form":return(g||["submit"]).indexOf(f.type)>=0;case"input":case"select":case"textarea":return(g||["change","click"]).indexOf(f.type)>=0;default:return _?(g||["click"]).indexOf(f.type)>=0:(g||["click"]).indexOf(f.type)>=0&&(dl.indexOf(T)>-1||d.getAttribute("contenteditable")==="true")}})(i,t,this.Ne,r,r?["copy","cut"]:void 0,this.instance)){var s=Om(i,{e:t,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.Ne.element_attribute_ignorelist,elementsChainAsString:this.po,disableCaptureUrlHashes:this.instance.config.disable_capture_url_hashes}),o=s.props;if(s.explicitNoCapture)return!1;var a=this.getElementSelectors(i);if(a&&a.length>0&&(o.$element_selectors=a),e===$o){var l,u=hf(w==null||(l=w.getSelection())==null?void 0:l.toString()),c=t.type||"clipboard";if(!u)return!1;o.$selected_content=u,o.$copy_type=c}return this.instance.capture(e,o),!0}}}isBrowserSupported(){return je(P?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(w==null||(e=w.location)==null?void 0:e.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(A.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.wo&&this.wo(),this.wo=void 0,A.info("History API monitoring stopped")}monitorHistoryChanges(){w&&w.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(w&&((e=w.history[t])==null||!e.__posthog_wrapped__)){var n=this;(function(i,r,s){try{if(!(r in i))return lu;var o={next:i[r]},a=s((function(){for(var l=arguments.length,u=new Array(l),c=0;l>c;c++)u[c]=arguments[c];return o.next.apply(this,u)}));return je(a)&&(a.prototype=a.prototype||{},Object.defineProperties(a,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:o}})),i[r]=a,()=>{if(i[r]!==a)for(var l=i[r];je(l)&&l.__posthog_layer__;){var u=l.__posthog_layer__;if(u.next===a)return void(u.next=o.next);l=u.next}else i[r]=o.next}}catch{return lu}})(w.history,t,(i=>function(r,s,o){i.call(this,r,s,o),n.So(t)}))}}So(t){try{var e,n=w==null||(e=w.location)==null?void 0:e.pathname;if(!n)return;n!==this._o&&this.isEnabled&&this._instance.capture(Gn,{navigation_type:t}),this._o=n}catch(i){A.error("Error capturing "+t+" pageview",i)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};ve(w,"popstate",t),this.wo=()=>{w&&w.removeEventListener("popstate",t)}}}},heatmaps:class{get Ne(){return this.instance.config}constructor(t){var e;this.Co=!1,this.vo=!1,this.Mo=null,this.instance=t,this.Co=!((e=this.instance.persistence)==null||!e.props[ta]),this.rageclicks=new au(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return he(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return H(this.Ne.capture_heatmaps)?H(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;Dm.info("starting..."),this.To(),this.Ie()}else{var t;clearInterval((t=this.Mo)!==null&&t!==void 0?t:void 0),this.Eo(),this.getAndClearBuffer()}}onRemoteConfig(t){if(t.ok){var e=t.config;if("heatmaps"in e){var n=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[ta]:n}),this.Co=n,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){No(t.originalEvent)&&this.ke(t.originalEvent,"deadclick")}Ie(){this.Mo&&clearInterval(this.Mo),this.Mo=P?.visibilityState==="visible"?setInterval(this.cr.bind(this),this.flushIntervalMilliseconds):null}To(){w&&P&&(this.Po=this.cr.bind(this),ve(w,ns,this.Po),this.Ro=t=>this.ke(t||w?.event),ve(P,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||w?.event),ve(P,"mousemove",this.Ao,{capture:!0}),this.Lo=new zc(this.instance,Xg,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),ve(P,ts,this.Oo),this.vo=!0)}Eo(){var t;w&&P&&(this.Po&&w.removeEventListener(ns,this.Po),this.Ro&&P.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&P.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&P.removeEventListener(ts,this.Oo),clearTimeout(this.Do),(t=this.Lo)==null||t.stop(),this.vo=!1)}$o(t,e){var n=this.instance.scrollManager.scrollY(),i=this.instance.scrollManager.scrollX(),r=this.instance.scrollManager.scrollElement(),s=(function(o,a,l){for(var u=o;u&&hn(u)&&!et(u,"body");){if(u===l)return!1;var c=void 0;try{var d,f,h;c=(d=(f=(h=u.ownerDocument)==null?void 0:h.defaultView)!==null&&f!==void 0?f:w)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(j(a,c))return!0;u=pf(u)}return!1})(bo(t),["fixed","sticky"],r);return{x:t.clientX+(s?0:i),y:t.clientY+(s?0:n),target_fixed:s,type:e}}ke(t,e){var n;if(e===void 0&&(e="click"),!$c(t.target)&&No(t)){var i=this.$o(t,e);(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,new Date().getTime())&&Oc(bo(t),this.instance.config.rageclick)&&this.Vt(I({},i,{type:"rageclick"})),this.Vt(i)}}Fo(t){!$c(t.target)&&No(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(w){var e=this.Ne.disable_capture_url_hashes?fn(w.location.href):w.location.href,n=this.Ne.custom_personal_data_properties,i=this.Ne.mask_personal_data_properties?[...si,...n||[]]:[],r=Xi(e,i,Qi);this.R=this.R||{},this.R[r]||(this.R[r]=[]),this.R[r].push(t)}}cr(){this.R&&!Kt(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:zc,webVitalsAutocapture:class{constructor(t){var e;this.Co=!1,this.vo=!1,this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this.No=()=>{clearTimeout(this.qo),this.qo=void 0,this.R.metrics.length!==0&&(this._instance.capture("$web_vitals",I({$current_url:this.R.url},this.R.metrics.reduce(((n,i)=>I({},n,{["$web_vitals_"+i.name+"_event"]:I({},i),["$web_vitals_"+i.name+"_value"]:i.value})),{}))),this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.jo=n=>{var i;if(this.R=this.R||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},H(n?.name)||H(n?.value))wn.error("Invalid metric received",n);else{var r=typeof n.navigationURL=="string"?n.navigationURL:void 0,s=this.Bo(r);if(!C(s)){var o=ke(n.navigationId)||typeof n.navigationId=="string"?"navigation:"+n.navigationId:"url:"+s;if(!this.Ho||this.Ho>n.value){this.R.navigationKey!==o&&(this.No(),this.qo=setTimeout(this.No,this.flushToCaptureTimeoutMs)),C(this.R.navigationKey)&&(this.R.navigationKey=o,this.R.url=s),this.R.firstMetricTimestamp=C(this.R.firstMetricTimestamp)?Date.now():this.R.firstMetricTimestamp,n.attribution&&n.attribution.interactionTargetElement&&(n.attribution.interactionTargetElement=void 0);var a=(i=this._instance.sessionManager)==null?void 0:i.checkAndGetSessionAndWindowId(!0),l=I({},n,r?{navigationURL:s}:{},{$current_url:s,timestamp:Date.now()});C(a)||(l.$session_id=a.sessionId,l.$window_id=a.windowId),this.R.metrics.push(l),this.R.metrics.length===this.allowedMetrics.length&&this.No()}else wn.error("Ignoring metric with value >= "+this.Ho,n)}}},this.Uo=()=>{if(!this.vo){var n,i,r,s,o=B.__PosthogExtensions__,a=o?.postHogWebVitalsCallbacksByFlavor,l=a?.[this.zo]||(this.zo==="web-vitals"&&C(a)?o?.postHogWebVitalsCallbacks:void 0);if(C(l)||(n=l.onLCP,i=l.onCLS,r=l.onFCP,s=l.onINP),n&&i&&r&&s){var u={reportSoftNavs:this.useSoftNavs};this.allowedMetrics.indexOf("LCP")>-1&&n(this.jo.bind(this),u),this.allowedMetrics.indexOf("CLS")>-1&&i(this.jo.bind(this),u),this.allowedMetrics.indexOf("FCP")>-1&&r(this.jo.bind(this),u),this.allowedMetrics.indexOf("INP")>-1&&s(this.jo.bind(this),u),this.vo=!0}else wn.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[sa]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,n=he(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return H(n)?((e=this._instance.persistence)==null?void 0:e.props[oa])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(he(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=he(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=he(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=he(this.Wo)&&ke(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:cu;return t>0&&6e4>=t?cu:t}get isEnabled(){var t=me?.protocol;if(t!=="http:"&&t!=="https:")return wn.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=he(this.Wo)?this.Wo.web_vitals:mt(this.Wo)?this.Wo:void 0;return mt(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(wn.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var n=he(e.capturePerformance)&&!!e.capturePerformance.web_vitals,i=he(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[sa]:n}),this._instance.persistence.register({[oa]:i})),this.Co=n,this.startIfEnabled()}}}get zo(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}ai(t){var e=B.__PosthogExtensions__,n=this.zo,i=e?.postHogWebVitalsCallbacksByFlavor;i!=null&&i[n]||n==="web-vitals"&&C(i)&&e!=null&&e.postHogWebVitalsCallbacks?t():e==null||e.loadExternalDependency==null||e.loadExternalDependency(this._instance,n,(r=>{r?wn.error("failed to load script",r):t()}))}Bo(t){var e=t||w?.location.href;if(e){var n=this._instance.config.disable_capture_url_hashes?fn(e):e,i=this._instance.config.custom_personal_data_properties,r=this._instance.config.mask_personal_data_properties?[...si,...i||[]]:[];return Xi(n,r,Qi)}wn.error("Could not determine current URL")}}},Ym={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var n;if(w&&this.isEnabled&&(n=B.__PosthogExtensions__)!=null&&n.errorWrappingFunctions){var i=B.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,r=B.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,s=B.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.Vo&&this.Ne.capture_unhandled_errors&&(this.Vo=i(this.captureException.bind(this))),!this.Zo&&this.Ne.capture_unhandled_rejections&&(this.Zo=r(this.captureException.bind(this))),!this.Go&&this.Ne.capture_console_errors&&(this.Go=s(this.captureException.bind(this)))}catch(o){ki.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[na]),this.Jo=new Gp(I({},(function(n){var i,r,s,o;return n===void 0&&(n={}),{refillRate:(i=(r=n.exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:n.__exceptionRateLimiterRefillRate)!==null&&i!==void 0?i:1,bucketSize:(s=(o=n.exceptionRateLimiterBucketSize)!==null&&o!==void 0?o:n.__exceptionRateLimiterBucketSize)!==null&&s!==void 0?s:10}})(this._instance.config.error_tracking),{refillInterval:1e4,rt:ki})),this.Ne=this.Yo(),this.startIfEnabledOrStop()}Yo(){var t=this._instance.config.capture_exceptions,e={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return he(t)?e=I({},e,t):(C(t)?this.Ko:t)&&(e=I({},e,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),e}get isEnabled(){return this.Ne.capture_console_errors||this.Ne.capture_unhandled_errors||this.Ne.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(ki.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",(i=>{if(i)return ki.error("failed to load script",i);t()}))}Qo(){var t,e,n;(t=this.Vo)==null||t.call(this),this.Vo=void 0,(e=this.Zo)==null||e.call(this),this.Zo=void 0,(n=this.Go)==null||n.call(this),this.Go=void 0}onRemoteConfig(t){if(t.ok){var e=t.config;"autocaptureExceptions"in e&&(this.Ko=!!e.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[na]:this.Ko}),this.Ne=this.Yo(),this.startIfEnabledOrStop())}}onConfigChange(){this.Ne=this.Yo()}captureException(t){var e,n,i,r=(e=t==null||(n=t.$exception_list)==null||(n=n[0])==null?void 0:n.type)!==null&&e!==void 0?e:"Exception";this.Jo.consumeRateLimit(r)?ki.info("Skipping exception capture because of client rate limiting.",{exception:r}):(i=this._instance.exceptions)==null||i.sendExceptionEvent(t)}},exceptions:class{constructor(t){var e,n;this.Xo=[],this.tl=new ug([new _g,new Cg,new wg,new yg,new Ig,new xg,new Eg,new kg],(function(i){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;r>o;o++)s[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` +`),d=l;c.length>d;d++){var f=c[d];if(1024>=f.length){var h=Pc.test(f)?f.replace(Pc,"$1"):f;if(!h.match(/\S*Error: /)){for(var p of s){var g=p(h,i);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var v=Array.from(m);return v.reverse(),v.slice(0,50).map((E=>{return I({},E,{filename:E.filename||(S=v,S[S.length-1]||{}).filename,function:E.function||ii});var S}))})(u)}})("web:javascript",pg,vg)),this._instance=t,this.Xo=(e=(n=this._instance.persistence)==null?void 0:n.get_property(ia))!==null&&e!==void 0?e:[],this.el=Jr(this.il()),this.rl=new Pg(this.el)}onConfigChange(){this.el=Jr(this.il()),this.rl.setConfig(this.el)}onRemoteConfig(t){var e,n,i;if(t.ok){var r=t.config;if("errorTracking"in r){var s=(e=(n=r.errorTracking)==null?void 0:n.suppressionRules)!==null&&e!==void 0?e:[],o=(i=r.errorTracking)==null?void 0:i.captureExtensionExceptions;this.Xo=s,this._instance.persistence&&this._instance.persistence.register({[ia]:this.Xo,[ra]:o})}}}get nl(){var t,e=!!this._instance.get_property(ra),n=this._instance.config.error_tracking.captureExtensionExceptions;return(t=n??e)!==null&&t!==void 0&&t}buildProperties(t,e){return this.tl.buildFromUnknown(t,{syntheticException:e?.syntheticException,mechanism:{handled:e?.handled}})}addExceptionStep(t,e){if(this.el.enabled)try{if(!X(t)||t.trim().length===0)return void St.warn("Ignoring exception step because message must be a non-empty string");var n=(function(s){if(!s)return{sanitizedProperties:{},droppedKeys:[]};var o=[];return{sanitizedProperties:Object.keys(s).reduce(((a,l)=>Ag.has(l)?(o.push(l),a):(a[l]=s[l],a)),{}),droppedKeys:o}})(this.sl(e)),i=n.sanitizedProperties,r=n.droppedKeys;r.length>0&&St.warn("Ignoring reserved exception step fields",{droppedKeys:r}),this.rl.add(I({[Kr]:t,[Yr]:new Date().toISOString()},i))}catch(s){St.error("Failed to add exception step. Ignoring breadcrumb.",s)}}sendExceptionEvent(t){try{var e=t.$exception_list;if(this.al(e)){if(this.ol(e))return this.ll("Exception dropped: matched a suppression rule"),void St.info("Skipping exception capture because a suppression rule matched");if(!this.nl&&this.ul(e))return this.ll("Exception dropped: thrown by a browser extension"),void St.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.hl(e))return this.ll("Exception dropped: thrown by the PostHog SDK"),void St.info("Skipping exception capture because it was thrown by the PostHog SDK")}var n=this.el.enabled&&H(t.$exception_steps)?this.dl(t):t,i=typeof(s=globalThis._posthogReleaseId)=="string"&&s.length>0?s:void 0;i&&(n.$release_id=i);try{var r=this._instance.capture("$exception",n,{_noTruncate:!0,_batchKey:"exceptionEvent",Wn:!0});return r&&this.rl.clear(),r}catch(o){return St.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void St.error("Failed to process exception event. Ignoring this exception.",o)}var s}dl(t){try{var e=this.rl.getAttachable();return e.length===0?t:I({},t,{$exception_steps:e})}catch(n){return St.error("Failed to read buffered exception steps. Capturing exception without steps.",n),t}}ll(t){this.el.enabled&&this.rl.add({[Kr]:t,[Yr]:new Date().toISOString()})}sl(t){return he(t)?I({},t):{}}il(){var t,e;return(t=(e=this._instance.config.error_tracking)==null?void 0:e.exception_steps)!==null&&t!==void 0?t:{}}ol(t){if(t.length===0)return!1;try{var e=t.reduce(((n,i)=>{var r=i.type,s=i.value;return X(r)&&r.length>0&&n.$exception_types.push(r),X(s)&&s.length>0&&n.$exception_values.push(s),n}),{$exception_types:[],$exception_values:[]});return this.Xo.some((n=>{var i=n.values.map((r=>{var s=zf[r.operator],o=e[r.key];if(!s||!o)return!1;var a=U(r.value)?r.value:[r.value];return a.length>0&&s(a,o)}));return n.type==="OR"?i.some(Boolean):i.every(Boolean)}))}catch(n){return St.warn("Failed to evaluate suppression rules. Capturing the exception.",n),!1}}ul(t){return t.flatMap((e=>{var n,i;return(n=(i=e.stacktrace)==null?void 0:i.frames)!==null&&n!==void 0?n:[]})).some((e=>e.filename&&e.filename.startsWith("chrome-extension://")))}hl(t){if(t.length>0){var e,n,i,r,s=(e=(n=t[0].stacktrace)==null?void 0:n.frames)!==null&&e!==void 0?e:[],o=s[s.length-1];return(i=o==null||(r=o.filename)==null?void 0:r.includes("posthog.com/static"))!==null&&i!==void 0&&i}return!1}al(t){return!H(t)&&U(t)}}},Jm=I({productTours:class{get Mr(){return this._instance.persistence}constructor(t){this.vl=null,this.cl=null,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(t.ok){var e=t.config;if("productTours"in e){var n,i;if(this.Mr&&this.Mr.register({[ol]:!!e.productTours}),!Oo(this._instance))return!this.vl&&H((n=this.Mr)==null?void 0:n.props[Li])||xr.info("product tours disabled; stopping and clearing cached tours"),(i=this.vl)==null||i.stop(),this.vl=null,void this.clearCache();this.loadIfEnabled()}}}loadIfEnabled(){!this.vl&&Oo(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.generateProductTours?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",(i=>{i?xr.error("Could not load product tours script",i):t()}))}fl(){var t;!this.vl&&(t=B.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=B.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(t,e){if(e===void 0&&(e=!1),!U(this.cl)||e){var n=this.Mr;if(n){var i=n.props[Li];if(U(i)&&!e)return this.cl=i,void t(i,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",timestampMode:"query",callback:r=>{if(Oo(this._instance)){var s=r.statusCode;if(s!==200||!r.json){var o="Product Tours API could not be loaded, status: "+s;return s===0?r.error||xr.warn(o):xr.error(o),void t([],{isLoaded:!1,error:o})}var a=U(r.json.product_tours)?r.json.product_tours:[];this.cl=a,n&&n.register({[Li]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){H(this.vl)?t([],{isLoaded:!1,error:"Product tours not loaded"}):this.vl.getActiveProductTours(t)}showProductTour(t){var e;(e=this.vl)==null||e.showTourById(t)}previewTour(t){this.vl?this.vl.previewTour(t):this.ai((()=>{var e;this.fl(),(e=this.vl)==null||e.previewTour(t)}))}dismissProductTour(){var t;(t=this.vl)==null||t.dismissTour("user_clicked_skip")}nextStep(){var t;(t=this.vl)==null||t.nextStep()}previousStep(){var t;(t=this.vl)==null||t.previousStep()}clearCache(){var t;this.cl=null,(t=this.Mr)==null||t.unregister(Li)}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)}}},Cs),Zm={siteApps:class{constructor(t){this.pl=0,this._instance=t,this.gl=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}ml(t,e){if(e){var n=this.globalsForEvent(e);this.gl.push(n),this.gl.length>1e3&&(this.gl=this.gl.slice(10))}}get siteAppLoaders(){var t;return(t=B._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,n,i,r,s,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var f=d[0];l[f]={id:u[f],type:f,properties:d[1]}}var h=t.$set_once,p=t.$set;return{event:I({},pd(t,jm),{properties:I({},t.properties,p?{$set:I({},(e=(n=t.properties)==null?void 0:n.$set)!==null&&e!==void 0?e:{},p)}:{},h?{$set_once:I({},(i=(r=t.properties)==null?void 0:r.$set_once)!==null&&i!==void 0?i:{},h)}:{}),elements_chain:(s=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&s!==void 0?s:"",distinct_id:(a=t.properties)==null?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}bl(t){var e,n=(e=t.tagName)==null?void 0:e.toLowerCase();return n==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(Et.error("prepare_external_dependency_stylesheet returned null"),null):n==="script"&&this._instance.config.prepare_external_dependency_script?this._instance.config.prepare_external_dependency_script(t)||(Et.error("prepare_external_dependency_script returned null"),null):t}_l(){var t,e,n,i,r,s,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=P?.defaultView,u=l==null||(t=l.Node)==null?void 0:t.prototype;if(!l||!u)return()=>{};if(this.pl++,this.wl)return this.kl();var c=[],d=this,f=new WeakSet,h=(m,v,E)=>{if(m!=null&&m[v]){var S=m[v];m[v]=E(S),c.push((()=>{m[v]=S}))}},p=m=>{if(f.has(m))return m;var v=d.bl(m);return v&&f.add(v),v},g=m=>m.map((v=>typeof v=="string"?v:p(v))).filter((v=>!Ye(v)));return h(u,"appendChild",(m=>function(v){var E=p(v);return E?m.call(this,E):v})),h(u,"insertBefore",(m=>function(v,E){var S=p(v);return S?m.call(this,S,E):v})),h(u,"replaceChild",(m=>function(v,E){var S=p(v);return S?m.call(this,S,E):E})),[(e=l.Element)==null?void 0:e.prototype,(n=l.Document)==null?void 0:n.prototype,(i=l.DocumentFragment)==null?void 0:i.prototype].forEach((m=>{h(m,"append",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),h(m,"prepend",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))}))})),[(r=l.Element)==null?void 0:r.prototype,(s=l.CharacterData)==null?void 0:s.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((m=>{h(m,"before",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),h(m,"after",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),h(m,"replaceWith",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];var b=g(S);return S.length&&!b.length?void 0:v.apply(this,b)}))})),h((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(v,E){var S=p(E);return S?m.call(this,v,S):null})),this.wl=()=>{c.forEach((m=>m())),this.wl=void 0},this.kl()}kl(){var t=!1;return()=>{var e;t||(t=!0,this.pl--,this.pl===0&&((e=this.wl)==null||e.call(this)))}}xl(t,e){e===void 0&&(e=!0);var n=this._l();try{var i=t(n);return e&&n(),i}catch(r){throw n(),r}}setupSiteApp(t){var e=this.apps[t.id],n=()=>{var o;!e.errored&&this.gl.length&&(Et.info("Processing "+this.gl.length+" events for site app with id "+t.id),this.gl.forEach((a=>this.xl((()=>e.processEvent==null?void 0:e.processEvent(a))))),e.processedBuffer=!0),Object.values(this.apps).every((a=>a.processedBuffer||a.errored))&&((o=this.yl)==null||o.call(this))},i=!1,r=o=>{e.errored=!o,e.loaded=!0,Et.info("Site app with id "+t.id+" "+(o?"loaded":"errored")),i&&n()};try{var s=this.xl((o=>t.init({posthog:this._instance,callback(a){o(),r(a)}})),!1).processEvent;s&&(e.processEvent=s),i=!0}catch(o){Et.error(fu+t.id,o),r(!1)}if(i&&e.loaded)try{n()}catch(o){Et.error("Error while processing buffered events PostHog app with config id "+t.id,o),e.errored=!0}}Sl(){var t=this.siteAppLoaders||[];for(var e of t)this.apps[e.id]={id:e.id,loaded:!1,errored:!1,processedBuffer:!1};for(var n of t)this.setupSiteApp(n)}Cl(t){var e=this;if(Object.keys(this.apps).length!==0){var n=this.globalsForEvent(t),i=function(s){try{e.xl((()=>s.processEvent==null?void 0:s.processEvent(n)))}catch(o){Et.error("Error while processing event "+t.event+" for site app "+s.id,o)}};for(var r of Object.values(this.apps))i(r)}}onRemoteConfig(t){var e,n,i,r=this;if((e=this.siteAppLoaders)!=null&&e.length)return this.isEnabled?(this.Sl(),void this._instance.on("eventCaptured",(l=>this.Cl(l)))):void Et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((n=this.yl)==null||n.call(this),t.ok){var s=t.config;if((i=s.siteApps)!=null&&i.length)if(this.isEnabled){var o=function(){var l,u=a.id,c=a.url;B["__$$ph_site_app_"+u]=r._instance,(l=B.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(r._instance,c,(d=>{if(d)return Et.error(fu+u,d)}))};for(var a of s.siteApps)o()}else Et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},Xm={tracingHeaders:class{constructor(t){this.Ml=void 0,this.Tl=void 0,this.El=void 0,this.Uo=()=>{var e,n,i=this.Il();i?(C(this.Ml)&&(this.Ml=(e=B.__PosthogExtensions__)==null||(e=e.tracingHeadersPatchFns)==null?void 0:e._patchXHR(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager)),C(this.Tl)&&(this.Tl=(n=B.__PosthogExtensions__)==null||(n=n.tracingHeadersPatchFns)==null?void 0:n._patchFetch(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager))):this.Qo()},this._instance=t}initialize(){this.startIfEnabledOrStop()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",(i=>{if(i)return Bm.error("failed to load script",i);t()}))}Pl(){var t,e;return(t=(e=this._instance.config.tracing_headers)!==null&&e!==void 0?e:this._instance.config.addTracingHeaders)!==null&&t!==void 0?t:this._instance.config.__add_tracing_headers}Il(){var t=this.Pl();return U(t)?(U(this.El)?this.El.splice(0,this.El.length,...t):this.El=[...t],t.length>0?this.El:void 0):(U(this.El)&&this.El.splice(0),this.El=t||void 0,this.El)}Qo(){var t,e;(t=this.Ml)==null||t.call(this),(e=this.Tl)==null||e.call(this),this.Ml=void 0,this.Tl=void 0}startIfEnabledOrStop(){this.Il()?this.ai(this.Uo):this.Qo()}}},Qm=I({surveys:class{get Ne(){return this._instance.config}constructor(t){this.Rl=void 0,this._surveyManager=null,this.Al=!1,this.Fl=[],this.Ll=null,this.Ol=null,this._instance=t,this._surveyEventReceiver=null}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this.Ne.disable_surveys){if(!t.ok)return Q.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(H(e))return Q.warn("Flags not loaded yet. Not loading surveys.");var n=U(e);this.Rl=n?e.length>0:e,Q.info("flags response received, isSurveysEnabled: "+this.Rl),this.loadIfEnabled()}}reset(){try{var t;(t=this._surveyEventReceiver)==null||t.reset(),localStorage.removeItem("lastSeenSurveyDate");for(var e=[],n=0;nlocalStorage.removeItem(r)))}catch{}}loadIfEnabled(){if(!this._surveyManager)if(this.Al)Q.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)Q.info(hu);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())Q.info("Not loading surveys in cookieless mode without consent.");else{var t=B?.__PosthogExtensions__;if(t){if(!C(this.Rl)||this.Ne.advanced_enable_surveys){var e=this.Rl||this.Ne.advanced_enable_surveys;this.Al=!0;try{var n=t.generateSurveys;if(n)return void this.Dl(n,e);var i=t.loadExternalDependency;if(!i)return void this.$l(ll);i(this._instance,"surveys",(r=>{r||!t.generateSurveys?this.$l("Could not load surveys script",r):this.Dl(t.generateSurveys,e)}))}catch(r){throw this.$l("Error initializing surveys",r),r}finally{this.Al=!1}}}else Q.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new Wm(this._instance),Q.info("Surveys loaded successfully"),this.Nl({isLoaded:!0})}$l(t,e){Q.error(t,e),this.Nl({isLoaded:!1,error:t})}onSurveysLoaded(t){return this.Fl.push(t),this._surveyManager&&this.Nl({isLoaded:!0}),()=>{this.Fl=this.Fl.filter((e=>e!==t))}}getSurveys(t,e){if(e===void 0&&(e=!1),this.Ne.disable_surveys)return Q.info(hu),t([]);var n,i=this._instance.get_property(la);if(i&&!e)return t(i,{isLoaded:!0}),void(this.ql()&&this.getSurveys((()=>{}),!0));typeof Promise<"u"&&this.Ll?this.Ll.then((r=>t(r.surveys,r.context))):(typeof Promise<"u"&&(this.Ll=new Promise((r=>{n=r}))),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this.Ne.token),method:"GET",timestampMode:"query",timeout:this.Ne.surveys_request_timeout_ms,callback:r=>{var s;this.Ll=null;var o=r.statusCode;if(o!==200||!r.json){var a="Surveys API could not be loaded, status: "+o;o!==0?Q.error(a):r.error||Q.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(n==null||n({surveys:[],context:l}))}this.Ol=null;var u,c=r.json.surveys||[],d=c.filter((h=>(function(p){return!(!p.start_date||p.end_date)})(h)&&(Vf(h)||(function(p){var g;return!((g=p.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(h))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(s=this._instance.persistence)==null||s.register({[la]:c,[Xr]:Date.now()});var f={isLoaded:!0};t(c,f),n?.({surveys:c,context:f})}}))}ql(){return this.jl()&&!this.Ll&&!this.Bl()}jl(){var t=this._instance.get_property(Xr);return ke(t)&&Date.now()-t>3e5}Bl(){return ke(this.Ol)&&3e5>Date.now()-this.Ol}markSurveyAsSeen(t,e){var n,i={id:t,current_iteration:(n=e?.iteration)!==null&&n!==void 0?n:null};Kf(i);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}}Nl(t){for(var e of this.Fl)try{if(!t.isLoaded)return e([],t);this.getSurveys(e)}catch(n){Q.error("Error in survey callback",n)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!H(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);Q.warn("init was not called")}Hl(t){var e=null;return this.getSurveys((n=>{var i;e=(i=n.find((r=>r.id===t)))!==null&&i!==void 0?i:null})),e}Ul(t){if(H(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(H(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(H(this._surveyManager))return Q.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 H(this._surveyManager)?(Q.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Ir})):new Promise((n=>{this.getSurveys((i=>{var r,s=(r=i.find((a=>a.id===t)))!==null&&r!==void 0?r:null;if(s){var o=this.zl(s);n({visible:o.eligible,disabledReason:o.reason})}else n({visible:!1,disabledReason:"Survey not found"})}),e)}))}renderSurvey(t,e,n){var i;if(H(this._surveyManager))Q.warn("init was not called");else{var r=typeof t=="string"?this.Hl(t):t;if(r!=null&&r.id)if(Im.includes(r.type)){var s=P?.querySelector(e);if(s)return(i=r.appearance)!=null&&i.surveyPopupDelaySeconds?(Q.info("Rendering survey "+r.id+" with delay of "+r.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;Q.info("Rendering survey "+r.id+" with delay of "+((o=r.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(a=this._surveyManager)==null||a.renderSurvey(r,s,n),Q.info("Survey "+r.id+" rendered")}),1e3*r.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(r,s,n);Q.warn("Survey element not found")}else Q.warn("Surveys of type "+r.type+" cannot be rendered in the app");else Q.warn("Survey not found")}}displaySurvey(t,e){var n;if(H(this._surveyManager))Q.warn("init was not called");else{var i=this.Hl(t);if(i){var r=i;if((n=i.appearance)!=null&&n.surveyPopupDelaySeconds&&e.ignoreDelay&&(r=I({},i,{appearance:I({},i.appearance,{surveyPopupDelaySeconds:0})})),e.displayType!==_a.Popover&&e.initialResponses&&Q.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),e.ignoreConditions===!1){var s=this.Ul(i);if(!s.eligible)return void Q.warn("Survey is not eligible to be displayed: ",s.reason)}e.displayType!==_a.Inline?this._surveyManager.handlePopoverSurvey(r,e):this.renderSurvey(r,e.selector,e.properties)}else Q.warn("Survey not found")}}cancelPendingSurvey(t){H(this._surveyManager)?Q.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},Cs),ev={toolbar:class{constructor(t){this.instance=t}Wl(t){B.ph_toolbar_state=t}Vl(){var t;return(t=B.ph_toolbar_state)!==null&&t!==void 0?t:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(t,e,n){if(t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),ga(this.instance.config)||!w||!P)return!1;t=t??w.location,n=n??w.history;try{if(!e){try{w.localStorage.setItem("test","test"),w.localStorage.removeItem("test")}catch{return!1}e=w?.localStorage}var i,r=zm||os(t.hash,"__posthog")||os(t.hash,"state"),s=r?Rc((()=>JSON.parse(atob(decodeURIComponent(r)))))||Rc((()=>JSON.parse(decodeURIComponent(r)))):null;return s&&s.action==="ph_authorize"?((i=s).source="url",i&&Object.keys(i).length>0&&(s.desiredHash?t.hash=s.desiredHash:n?n.replaceState(n.state,"",t.pathname+t.search):t.hash="")):((i=JSON.parse(e.getItem(pu)||"{}")).source="localstorage",delete i.userIntent),!(!i.token||this.instance.config.token!==i.token||(this.loadToolbar(i),0))}catch{return!1}}Zl(t){var e=B.ph_load_toolbar||B.ph_load_editor;!H(e)&&je(e)?e(t,this.instance):gu.warn("No toolbar load function found")}loadToolbar(t){var e=!(P==null||!P.getElementById(cf));if(!w||e)return!1;var n=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,i=I({token:this.instance.config.token},t,{apiURL:this.instance.requestRouter.endpointFor("ui")},n?{instrument:!1}:{});if(w.localStorage.setItem(pu,JSON.stringify(I({},i,{source:void 0}))),this.Vl()===2)this.Zl(i);else if(this.Vl()===0){var r;this.Wl(1),(r=B.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"toolbar",(s=>{if(s)return gu.error("[Toolbar] Failed to load",s),void this.Wl(0);this.Wl(2),this.Zl(i)})),ve(w,"turbolinks:load",(()=>{this.Wl(0),this.loadToolbar(i)}))}return!0}Gl(t){return this.loadToolbar(t)}maybeLoadEditor(t,e,n){return t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),this.maybeLoadToolbar(t,e,n)}}},tv=I({experiments:Me},Cs),nv={conversations:class{constructor(t){this.Ql=void 0,this._conversationsManager=null,this.Kl=!1,this.Jl=null,this.Yl=!1,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this._instance.config.disable_conversations&&(this.Xl=t.ok,t.ok)){var e=t.config.conversations;H(e)||(mt(e)?this.Ql=e:(this.Ql=e.enabled,this.Jl=e),this.loadIfEnabled())}}reset(){var t;(t=this._conversationsManager)==null||t.reset(),this._conversationsManager=null,this.Ql=void 0,this.Jl=null,this.Xl=void 0,this.Yl=!1}loadIfEnabled(){if(!(this._conversationsManager||this.Kl||this._instance.config.disable_conversations||ga(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=B?.__PosthogExtensions__;if(t&&!C(this.Ql)&&this.Ql)if(this.Jl&&this.Jl.token){this.Kl=!0;try{var e=t.initConversations;if(e)return this.tu(e),void(this.Kl=!1);var n=t.loadExternalDependency;if(!n)return void this.eu(ll);n(this._instance,"conversations",(i=>{i||!t.initConversations?this.eu("Could not load conversations script",i):this.tu(t.initConversations),this.Kl=!1}))}catch(i){this.eu("Error initializing conversations",i),this.Kl=!1}}else ot.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,ot.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else ot.error("Cannot complete initialization: remote config is null")}eu(t,e){ot.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():ot.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!Ye(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":ga(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.Xl===!1?"remote_config_failed":C(this.Ql)?this.Xl?"disabled_in_project":"remote_config_pending":this.Ql?H(this.Jl)||!this.Jl.token?"missing_token":B!=null&&B.__PosthogExtensions__?this.Kl?"initializing":this.Yl?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.isVisible())!==null&&t!==void 0&&t}sendMessage(t,e,n){var i=this;return se((function*(){return i._conversationsManager?i._conversationsManager.sendMessage(t,e,n):(ot.warn(En),null)}))()}getMessages(t,e){var n=this;return se((function*(){return n._conversationsManager?n._conversationsManager.getMessages(t,e):(ot.warn(En),null)}))()}markAsRead(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(ot.warn(En),null)}))()}getTickets(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(ot.warn(En),null)}))()}requestRestoreLink(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(ot.warn(En),null)}))()}restoreFromToken(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(ot.warn(En),null)}))()}restoreFromUrlToken(){var t=this;return se((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(ot.warn(En),null)}))()}getCurrentTicketId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getCurrentTicketId())!==null&&t!==void 0?t:null}getWidgetSessionId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getWidgetSessionId())!==null&&t!==void 0?t:null}Xn(){var t;(t=this._conversationsManager)==null||t.setIdentity()}ts(){var t;(t=this._conversationsManager)==null||t.clearIdentity()}}},iv={logs:class{constructor(t){var e,n=this;this.iu=!1,this.ru=!1,this.rt=pe("[logs]"),this.nu=I({},this.rt,{error(){for(var i=arguments.length,r=new Array(i),s=0;i>s;s++)r[s]=arguments[s];r.some(Su)||n.rt.error(...r)}}),this.tr=[],this.su=[],this.Sa=0,this.au=()=>{var i,r;this.Sa=0,(i=this.ou)==null||i.onReconnect(),(r=this.lu)==null||r.onReconnect()},this._instance=t,this._instance&&(e=this._instance.config.logs)!=null&&e.captureConsoleLogs&&(this.iu=!0),w&&ve(w,"online",this.au)}uu(t,e,n,i){var r,s=(function(o,a){var l,u,c,d,f,h,p,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,v=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,E=C(v)?Math.max(m,2048):Math.max(m,v),S=o?.resourceAttributes;return{serviceName:(d=(f=S?.["service.name"])!==null&&f!==void 0?f:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(h=S?.["service.version"])!==null&&h!==void 0?h:o?.serviceVersion,environment:(p=S?.["deployment.environment"])!==null&&p!==void 0?p:o?.environment,resourceAttributes:S,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:E,maxBatchRecordsPerPost:100,rateCapWindowMs:g,maxLogsPerInterval:v,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}})((r=this._instance)==null||(r=r.config)==null?void 0:r.logs,n);return[new ag(this.hu(t,e),s,this.nu,(()=>this.du()),(o=>o()),void 0,i),s]}vu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.ou||this.cu!==e){var n;(n=this.ou)==null||n.reset(),this.cu=e;var i=this.uu((()=>this.tr),(r=>{this.tr=r}));this.ou=i[0],this.fu=i[1]}return this.ou}pu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.lu||this.gu!==e){var n;(n=this.lu)==null||n.reset(),this.gu=e;var i=this.uu((()=>this.su),(r=>{this.su=r}),{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},Eu);this.lu=i[0],this.mu=i[1]}return this.lu}initialize(){this.loadIfEnabled()}onRemoteConfig(t){var e;if(t.ok){var n=(e=t.config.logs)==null?void 0:e.captureConsoleLogs;!H(n)&&n&&(this.iu=!0,this.loadIfEnabled())}}reset(){var t,e;this.tr=[],(t=this.ou)==null||t.reset(),this.su=[],(e=this.lu)==null||e.reset(),this.Sa=0}captureLog(t){this.vu().captureLog(t)}he(t){this.pu().captureLog(t)}get logger(){return this.yu||(this.yu={trace:(t,e)=>this.captureLog({body:t,level:"trace",attributes:e}),debug:(t,e)=>this.captureLog({body:t,level:"debug",attributes:e}),info:(t,e)=>this.captureLog({body:t,level:"info",attributes:e}),warn:(t,e)=>this.captureLog({body:t,level:"warn",attributes:e}),error:(t,e)=>this.captureLog({body:t,level:"error",attributes:e}),fatal:(t,e)=>this.captureLog({body:t,level:"fatal",attributes:e})}),this.yu}flushLogs(t){t?this.bu(t):(this.ou&&this.ou.flush().catch((e=>this._u(e))),this.lu&&this.lu.flush().catch((e=>this._u(e))))}_u(t){Su(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=B?.__PosthogExtensions__;if(t){var e=t.loadExternalDependency;e?e(this._instance,"logs",(n=>{var i;n||(i=t.logs)==null||!i.initializeLogs?this.rt.error("Could not load logs script",n):(t.logs.initializeLogs(this._instance),this.ru=!0)})):this.rt.error(ll)}else this.rt.error("PostHog Extensions not found.")}}hu(t,e){var n=this._instance;return{get isDisabled(){return!1},get optedOut(){return!n.is_capturing()},getPersistedProperty:i=>i===Ut.LogsQueue?t():void 0,setPersistedProperty(i,r){var s;i===Ut.LogsQueue&&e((s=r)!==null&&s!==void 0?s:[])},Ot:i=>this.Ot(i),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Ot(t){return new Promise((e=>{if(bf(this.Sa,3))e({kind:"fatal",error:Do(void 0,"logs endpoint is unreachable, dropping batch")});else{var n=!1,i=s=>{n||(n=!0,clearTimeout(r),e(s))},r=setTimeout((()=>{this.rt.warn("Logs request timed out before receiving a response"),i({kind:"retry-later",error:Do(void 0,"logs request timed out")})}),9e4);this._instance._send_request({method:"POST",url:this.wu(),data:t,compression:"best-available",batchKey:"logs",fireCallbackOnDrop:!0,callback:s=>{var o=s.statusCode;if(this.ku(o),o>=200&&300>o)i({kind:"ok"});else if(o===413)i({kind:"too-large"});else if(o!==0&&o!==429&&500>o)i({kind:"fatal",error:new Error("logs request failed with status "+o)});else{var a;o===0?(s.error||this.rt.warn("Logs request failed before receiving an HTTP response"),i({kind:"retry-later",error:Do(s.error,"logs request failed before receiving an HTTP response")})):i({kind:"retry-later",error:(a=s.error)!==null&&a!==void 0?a:new Error("logs request failed with status "+o)})}}})}}))}ku(t){(t!==0||this._instance.__loaded)&&(this.Sa=Ef(t,this.Sa,3,(()=>this.rt.warn("Log requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped sending logs; will try again when connectivity changes."))))}bu(t){this.tr.length>0&&this.xu(t,this.tr,this.fu,ne.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,Eu,(e=>{this.su=e}))}xu(t,e,n,i,r){if(e.length!==0){var s=e.map((a=>a.record));r([]);var o=qd(s,zd(n,ne.LIB_NAME,ne.LIB_VERSION),i,ne.LIB_VERSION);this._instance._send_request({method:"POST",url:this.wu(),data:o,compression:"best-available",batchKey:"logs",transport:t})}}wu(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}du(){var t,e={};if(e.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var n=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.windowId,r=n.sessionStartTimestamp,s=n.lastActivityTimestamp;e.sessionId=n.sessionId,e.windowId=i,H(r)||(e.sessionStartTimestamp=r),H(s)||(e.lastActivityTimestamp=s)}if(B!=null&&(t=B.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?fn(B.location.href):B.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},rv={metrics:class{constructor(t){this.rt=pe("[metrics]"),this._instance=t}initialize(){}vu(){var t,e,n=(t=this._instance)==null||(t=t.config)==null?void 0:t.metrics;return this.ou&&this.cu===n||((e=this.ou)==null||e.reset(),this.cu=n,this.ou=new lg(this.hu(),(function(i){var r,s,o,a,l,u=i?.resourceAttributes;return{serviceName:(r=u?.["service.name"])!==null&&r!==void 0?r:i?.serviceName,serviceVersion:(s=u?.["service.version"])!==null&&s!==void 0?s:i?.serviceVersion,environment:(o=u?.["deployment.environment"])!==null&&o!==void 0?o:i?.environment,resourceAttributes:u,beforeSend:i?.beforeSend,flushIntervalMs:(a=i?.flushIntervalMs)!==null&&a!==void 0?a:1e4,maxSeriesPerFlush:(l=i?.maxSeriesPerFlush)!==null&&l!==void 0?l:1e3}})(n),this.rt)),this.ou}count(t,e,n){e===void 0&&(e=1),this.vu().count(t,e,n)}gauge(t,e,n){this.vu().gauge(t,e,n)}histogram(t,e,n){this.vu().histogram(t,e,n)}flush(t){if(!this.ou)return Promise.resolve();if(t){var e=this.ou.drainWindow();return e&&this.Jt(e,t),Promise.resolve()}return this.ou.flush().catch((n=>this.rt.error("PostHog metrics flush failed:",n)))}reset(){var t;(t=this.ou)==null||t.reset()}hu(){var t=this._instance,e=this;return{get isDisabled(){return!1},get optedOut(){return!t.is_capturing()},Jt:n=>e.Jt(n),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Jt(t,e){return new Promise((n=>{var i=!1,r=o=>{i||(i=!0,clearTimeout(s),n(o))},s=setTimeout((()=>r({kind:"retry-later",error:new Error("metrics request timed out")})),9e4);this._instance._send_request(I({method:"POST",url:this.Su(),data:t,compression:"best-available",batchKey:"metrics"},e&&{transport:e},{fireCallbackOnDrop:!0,callback(o){var a=o.statusCode;if(a>=200&&300>a)r({kind:"ok"});else if(a===413)r({kind:"too-large"});else if(a!==0&&a!==429&&500>a)r({kind:"fatal",error:new Error("metrics request failed with status "+a)});else{var l;r({kind:"retry-later",error:(l=o.error)!==null&&l!==void 0?l:new Error("metrics request failed with status "+a)})}}}))}))}Su(){return this._instance.requestRouter.endpointFor("api","/i/v1/metrics")+"?token="+encodeURIComponent(this._instance.config.token)}}},sv=I({},Cs,Gm,Km,Ym,Jm,Zm,Qm,Xm,ev,tv,nv,iv,rv);Ze.__defaultExtensionClasses=I({},sv);(function(){ne.SDK_DIST_CHANNEL="npm";var t=zi[Kn]=new Ze;return(function(){function e(){e.done||(e.done=!0,Jf=!1,ie(zi,(function(n){n._dom_loaded()})))}P!=null&&P.addEventListener?P.readyState==="complete"?e():ve(P,"DOMContentLoaded",e,{capture:!1}):w&&A.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const ov=["a[href]","button:not([disabled])","input:not([disabled]):not([type='hidden'])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(",");let pt=null,ka=null,Xf="";const Ca=new Map;function Qf(t){return[...t.querySelectorAll(ov)].filter(e=>!e.hidden&&e.getAttribute("aria-hidden")!=="true"&&e.getClientRects().length>0)}function av(t){for(const e of document.body.children)e===t||e.tagName==="SCRIPT"||(Ca.set(e,{inert:e.inert,ariaHidden:e.getAttribute("aria-hidden")}),e.inert=!0,e.setAttribute("aria-hidden","true"))}function lv(){for(const[t,e]of Ca)t.inert=e.inert,e.ariaHidden===null?t.removeAttribute("aria-hidden"):t.setAttribute("aria-hidden",e.ariaHidden);Ca.clear()}function eh(t){return t?.dataset.modalDismissible!=="false"&&t?.getAttribute("aria-busy")!=="true"}function We(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n)return!1;pt&&pt!==n&&ze(pt,{restoreFocus:!1,force:!0}),ka=e.trigger||document.activeElement,pt=n,Xf=document.body.style.overflow,av(n),document.body.style.overflow="hidden",n.classList.add("open"),n.setAttribute("aria-hidden","false");const i=n.querySelector(".modal-content");i&&(i.style.transform="scale(1) translateY(0)");const r=()=>{if(pt!==n)return;((e.initialFocus?n.querySelector(e.initialFocus):n.querySelector("[data-modal-initial-focus]"))||Qf(n)[0]||n.querySelector(".modal-content")||n).focus({preventScroll:!0})};return requestAnimationFrame(r),setTimeout(r,260),!0}function ze(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n||!e.force&&!eh(n))return!1;n.classList.remove("open"),n.setAttribute("aria-hidden","true"),lv(),document.body.style.overflow=Xf,pt=null;const i=ka;return ka=null,e.restoreFocus!==!1&&i?.isConnected&&i.focus({preventScroll:!0}),!0}function xu(t,e,n="Operation in progress"){const i=typeof t=="string"?document.getElementById(t):t;i&&(i.dataset.modalDismissible=e?"false":"true",i.setAttribute("aria-busy",String(!!e)),e?i.setAttribute("aria-label",n):i.removeAttribute("aria-label"))}function cv(t){if(!eh(t))return;const e=t.dataset.modalCloseHandler;e&&typeof window[e]=="function"?window[e]():ze(t)}document.addEventListener("keydown",t=>{if(!pt)return;if(t.key==="Escape"){t.preventDefault(),t.stopImmediatePropagation(),cv(pt);return}if(t.key!=="Tab"){t.stopPropagation();return}const e=Qf(pt);if(!e.length){t.preventDefault(),(pt.querySelector(".modal-content")||pt).focus();return}const n=e[0],i=e[e.length-1];t.shiftKey&&document.activeElement===n?(t.preventDefault(),i.focus()):!t.shiftKey&&document.activeElement===i&&(t.preventDefault(),n.focus())},!0);function uv(){document.querySelectorAll(".modal-overlay").forEach(t=>{t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-hidden",t.classList.contains("open")?"false":"true");const e=t.querySelector(".modal-content");e&&!e.hasAttribute("tabindex")&&(e.tabIndex=-1);const n=t.querySelector("h1, h2, h3");n&&(n.id||(n.id=`${t.id}-title`),t.setAttribute("aria-labelledby",n.id)),t.querySelectorAll(".modal-close").forEach(i=>{i.getAttribute("aria-label")||i.setAttribute("aria-label","Close dialog")})})}const ml=Object.freeze({free:"Free",professional:"Pro",power:"Power"}),dv=Object.freeze({free:2,professional:50,power:2e3}),fv="(contact us)",hv=Object.freeze({free:Object.freeze(["2 generations/month","Gemini model only","Code Review"]),professional:Object.freeze(["50 generations/month","All models","Code Regeneration","Code Review"]),power:Object.freeze(["2000 generations/month","All models","Code Regeneration","Bring your own key (BYOK)","Code Review","All models + early access",`API & MCP access ${fv}`])}),th="CodeFile",nh="GeneratedCode",pv={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function ln(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Aa(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function gv(t={},e=0){const n=Aa(t.artifactType||t.type||th),i=Aa(t.artifactName||t.name||t.fileName||`${nh}-${e+1}`);return`${n||"artifact"}-${i||e+1}`}function ih(t={},e=0){const n=ln(t),i=n.artifactType||n.type||th,r=n.artifactName||n.name||nh;let s=n.fileName||r;return s.endsWith(".dart")||(s+=".dart"),{id:Aa(n.id)||gv({...n,artifactType:i,artifactName:r,fileName:s},e),artifactType:i,artifactName:r,fileName:s,deployPath:n.deployPath||"",description:n.description||"",code:n.code||n.content||"",dependencies:rh(n.dependencies),imports:Array.isArray(n.imports)?n.imports:[],publicApi:Array.isArray(n.publicApi)?n.publicApi:[],relationships:sh(n.relationships),deployStatus:n.deployStatus||"pending",review:n.review||null,metadata:ln(n.metadata),codeType:n.codeType||pv[i]||"O"}}function rh(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const n=ln(e),i=n.name||n.package;return i?{name:i,version:n.version||null,versionRequired:!!(n.versionRequired||n.required),inferred:!!n.inferred,...n.reason?{reason:n.reason}:{}}:null}).filter(Boolean):Object.entries(ln(t)).map(([e,n])=>({name:e,version:n||null,inferred:!1})):[]}function sh(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const n=ln(e);return!n.from&&!n.to?null:{from:n.from||null,to:n.to||null,type:n.type||"uses",description:n.description||""}}).filter(Boolean):[]}function Pa(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;try{return JSON.parse(e)}catch{const n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(!n)return null;try{return JSON.parse(n[1].trim())}catch{return null}}}function er(t,e={}){const n=[],i=typeof t=="string"?Pa(t):t,s=ln(i||{});!i&&typeof t=="string"&&n.push("Structured bundle parse failed; using legacy single-artifact fallback.");const o=Array.isArray(s.artifacts)?s.artifacts:[{artifactType:s.artifactType||e.artifactType,artifactName:s.artifactName||e.artifactName,fileName:s.fileName||e.fileName,description:s.description,code:s.code||e.code||(typeof t=="string"?t:""),dependencies:s.dependencies||e.dependencies,relationships:s.relationships||e.relationships}];o.forEach((d,f)=>{!d?.artifactType&&!d?.type&&n.push(`Artifact ${f+1} has no artifactType; it will deploy as a standalone code file under lib/custom_code/ root.`)});const a=o.map((d,f)=>ih(d,f)),l=new Map(o.map((d,f)=>[ln(d).id,a[f]?.id]).filter(([d,f])=>d&&f)),u=d=>l.get(d)||d,c=sh(s.relationships||e.relationships).map(d=>({...d,from:d.from?u(d.from):d.from,to:d.to?u(d.to):d.to}));return{schemaVersion:s.schemaVersion||e.schemaVersion||null,id:s.id||e.id||"bundle-current",title:s.title||s.name||e.title||"Generated artifact bundle",description:s.description||e.description||"",artifacts:a,dependencies:rh(s.dependencies||e.dependencies),relationships:c,deployOrder:Array.isArray(s.deployOrder)?s.deployOrder.map(u):a.map(d=>d.id),warnings:[...n,...Array.isArray(s.warnings)?s.warnings:[]],metadata:ln(s.metadata)}}function ai(t){return er(t).artifacts[0]||ih()}function Zt(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function li(t){return JSON.stringify(t,null,2)}function mv(t){return li({task:"architect",userRequest:String(t??"")})}function vv(t){const e=Zt(t);return e&&typeof e=="object"&&typeof e.task=="string"?li(e):li({task:"generate_bundle",bundleSpec:e})}function _v(t){return li({task:"review_bundle",generatedBundle:Zt(t),outputRequirements:{bundleReview:["status","score","summary","manualActions","findings"],scoreRange:[0,100],eachArtifact:["id","review.status","review.findings"],manualActions:{definition:"Setup the developer must perform by hand in the FlutterFlow editor that FlutterFlow will NOT do for them.",exclude:["creating the Custom Action, Widget or Code File itself - deploying the code creates it","declaring parameters or return values FlutterFlow derives from the function signature","anything that resolves as a side effect of using the action or widget in the editor","generic advice such as testing, reviewing or rebuilding the app"],preferEmpty:"Return an empty array when nothing qualifies - an empty list is the expected result for most bundles."}}})}function vl(t,e=null){const n={stage:t};return e!=null&&(n.bundle=Zt(e)),n}function yv({bundleSpec:t,artifactBundle:e,bundleReview:n,artifactId:i,userFeedback:r}){return li({task:"regenerate_artifact",artifactId:i,bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(r)})}function oh({bundleSpec:t,artifactBundle:e,bundleReview:n,userFeedback:i}){return li({task:"regenerate_bundle",bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(i??"")})}const Iu={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"},wv=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function tt(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function bv(t){return tt(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||tt(t.filterSummary)||tt(t.filterResults):!1}function ah(t,e=0){if(!tt(t)||e>3)return null;if(bv(t))return t;for(const n of wv){const i=t[n];if(tt(i)){const r=ah(i,e+1);if(r)return r}}return null}function ds(t){return Array.isArray(t)?t.some(ds):tt(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(ds):!1}function Fa(t){return Array.isArray(t)?t.some(Fa):tt(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(Fa):!1}function lh(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function Ev(t,e){if(tt(t))for(const[n,i]of Object.entries(t)){if(!tt(i))continue;const r=tt(i.categories)?i.categories:{},s=Object.entries(r).filter(([,o])=>tt(o)&&o.matched===!0).map(([o])=>o);s.length>0?s.forEach(o=>e.add(o)):i.matched===!0&&e.add(lh(n))}}function Sv(t,e){if(!t)return;const n=Array.isArray(t)?t.flatMap(i=>tt(i)?Object.entries(i):[]):Object.entries(t);for(const[i,r]of n){if(!ds(r))continue;const s=lh(i),o=r?.raiFilterResult?.raiFilterTypeResults||(s==="rai"?r?.raiFilterTypeResults:null),a=tt(o)?Object.entries(o).filter(([,l])=>ds(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(s)}}function xv(t){return Iu[t]?Iu[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function ku(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 Iv(t){const e=ah(t);if(!e)return null;const n=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);Ev(e.filterSummary,n),Sv(e.filterResults,n);const i=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||n.size>0,r=e.invocationResult||null,s=Fa(e.filterSummary||e.filterResults);return!i&&!s&&!["PARTIAL","FAILURE"].includes(r)?null:{kind:i?"blocked":"unavailable",invocationResult:r,matchedFilters:[...n]}}function kv(t,e){const n=Iv(t);if(!n)return null;const i=[...new Set(n.matchedFilters.map(xv))],r=n.kind==="blocked",s=new Error(r?`Safety screening blocked this pipeline step for ${ku(i)}.`:"Safety screening could not be completed. Please try again.");return s.name="ModelArmorError",s.code=r?"MODEL_ARMOR_BLOCKED":"MODEL_ARMOR_UNAVAILABLE",s.isModelArmor=!0,s.pipelineStep=e,s.userTitle=r?"Request blocked for safety":"Safety check unavailable",s.userMessage=r?`The safety check detected ${ku(i)}. Edit your request to remove or rephrase the flagged content, then run the pipeline again.`:"The safety service did not finish all of its checks. Please wait a moment and run the pipeline again.",s.retryExplanation=r?"Trying another model would not change this safety decision.":"A fallback model was not attempted because safety screening must complete first.",s.matchedFilters=n.matchedFilters,s}function Cv(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function Cu(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,n=[];for(const i of Cv(t).split(` `)){if(!/^[A-Za-z_$]/.test(i)||e.test(i))continue;const r=i.match(/^[\w$<>,?\s[\]]+?\s([a-zA-Z_$][\w$]*)\s*\(/);r&&n.push(r[1])}return n}function _l(t,e){const n=t.replace(/\.dart$/,"");if(e==="W")return n.replace(/(^|_)(\w)/g,(i,r,s)=>s.toUpperCase());if(e==="A"){const i=n.replace(/(^|_)(\w)/g,(r,s,o)=>o.toUpperCase());return i.charAt(0).toLowerCase()+i.slice(1)}return e==="F"?"CustomFunctions":e==="C"?t.endsWith(".dart")?t:`${t}.dart`:n}async function Au(t){const e=new TextEncoder().encode(String(t||"")),n=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n),i=>i.toString(16).padStart(2,"0")).join("")}async function Av(t,e=new Map){const n={},i=new Set;for(const[o,a]of t.entries()){if(a.type==="D"||a.type==="O")continue;const l=_l(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await Au(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await Au(c)),n[o]=u,a.type==="F"){const d=Cu(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(h=>i.add(h))}}const r=new Set(Cu(e.get("lib/flutter_flow/custom_functions.dart")||"")),s={functions_to_rename:[],functions_to_delete:[],functions_to_add:Array.from(i).filter(o=>!r.has(o))};return{fileMapContents:JSON.stringify(n),functionsMapContents:JSON.stringify(s)}}const Pv=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),Pu={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},Fv=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),Rv=["Struct","Record"],Tv=[{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=>jo(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=>jo(t).some(e=>{const n=/^\s*final\s+(?:double|int|String|bool|Color|num)\s+(\w+)\s*;/gm;let i;for(;(i=n.exec(e))!==null;){const r=i[1];if(!(new RegExp(`this\\.${r}\\s*=(?!=)`).test(e)||new RegExp(`[:,]\\s*${r}\\s*=(?!=)`).test(e)))return!0}return!1}),pos:`class W extends StatefulWidget { const W({required this.value}); @@ -24,36 +24,36 @@ class _S extends State { @override Widget build(BuildContext c) => const Size final double? width; @override _S createState() => _S(); } -class _S extends State { @override Widget build(BuildContext c) => Padding(padding: const EdgeInsets.all(8), child: const SizedBox()); }`}];function xt(t,e,n){return{artifactId:t.id,artifactName:t.artifactName,artifactType:t.artifactType,severity:e,message:n}}function er(t){let e="",n=0;for(;n"&&(n--,n===0))return{inner:t.slice(e+1,i),end:i+1};return null}function Mv(t,e){const n=new RegExp(`class\\s+${e}\\b[^{]*\\{`).exec(t);if(!n)return null;let i=0;for(let r=n.index+n[0].length-1;rLv(t).usable);function Ov(t=""){const e=er(t);return Nv.filter(n=>n.detect(e)).map(({id:n,severity:i,message:r})=>({id:n,severity:i,message:r}))}function Bv(t){const e=[],n=t.matchAll(/\bFuture\b/g);for(const i of n){let r=i.index+6,s=null;const o=r;for(;ro;if(t[r]==="<"){const u=$v(t,r);if(!u||(s=u.inner.replace(/\s+/g," ").trim(),r=u.end,!/\s/.test(t[r]||"")))continue;for(;rFu(o.functionName)===i);if(r)return r;const s=o=>!o.functionName.startsWith("_");return n.find(s)||n[0]}function As(t=""){return Array.from(er(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function Dv(t="",e=""){return yl(t,e)?.returnType||null}function Ru(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 jv(t,e){const n=As(e);if(n.length===0)return null;const r=String(t||"").split("/").pop().replace(/\.dart$/,"");if(n.some(l=>Ru(l)===r)||n.length>1)return null;const[o]=n,a=`${Ru(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 wl(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function Uv(t,e,n=""){const i=yl(e,n)?.functionName;if(!i)return null;const r=String(t||"").split("/").pop(),s=_l(r,"A");if(s===i)return null;const o=`${wl(i)}.dart`;return`File name "${r}" does not match Action "${i}". FlutterFlow derives the action from the file name, so it looks for "${s}" and reports Action "${s}" declaration not found. Rename the file to "${o}" - FlutterFlow puts an underscore before every capital - or rename the function to "${s}".`}function Hv(t="",e=""){return yl(t,e)!==null}function Wv(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(i=>Fv.has(i)?!1:!Rv.some(s=>i.endsWith(s))||e.has(i))}function zv(t,{functionName:e="",declaredTypes:n=new Set}={}){const i=Dv(t,e),r=Wv(i,n);if(r.length===0)return null;const[s]=r;let o;return n.has(s)?o=`uses Code File type "${s}", which FlutterFlow cannot process as an Action Return Value`:i===s?o="is not a FlutterFlow Action Return Value":o=`uses type "${s}", which is not a FlutterFlow Action Return Value`,`CustomAction return type "${i}" ${o}. Return JSON (Future) or an existing FlutterFlow Data Type (*Struct) instead.`}function qv(t,e={}){const n=[],i=t.fileName||"",r=t.code||"";if(Pv.has(t.artifactType)||n.push(xt(t,"error",`Unsupported artifact type "${t.artifactType}".`)),i.endsWith(".dart")||n.push(xt(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!r.trim())return n.push(xt(t,"warning","Generated artifact has no Dart code yet.")),n;if(t.artifactType==="CustomWidget"){/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)||n.push(xt(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const s of Ov(r))n.push(xt(t,s.severity,s.message))}if(t.artifactType==="CustomAction"&&!Hv(r,t.artifactName)&&n.push(xt(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const s=e.declaredTypes||new Set(As(r)),o=zv(r,{functionName:t.artifactName,declaredTypes:s});o&&n.push(xt(t,"error",o));const a=Uv(i,r,t.artifactName);a&&n.push(xt(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)&&n.push(xt(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const s=jv(i,r);s&&n.push(xt(t,"info",s))}return n}function Vv(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],n=new Set(e.flatMap(s=>As(s.code||""))),i=e.flatMap(s=>qv(s,{declaredTypes:n})),r=e.map(s=>({artifactId:s.id,fileName:s.fileName,pathHint:Pu[s.artifactType]||Pu.CodeFile}));return{valid:i.every(s=>s.severity!=="error"),findings:i,deployHints:r}}const Tu="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function $u(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function Gv(t=""){const e=t.indexOf(Tu);return e===-1?t:t.slice(e+Tu.length).replace(/^\s*\n/,"")}const Kv=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function Yv(t="",e=""){const n=Gv(t),i=new Set((e.match(/^\s*import .*$/gm)||[]).map($u).filter(Boolean)),r=n.split(` +class _S extends State { @override Widget build(BuildContext c) => Padding(padding: const EdgeInsets.all(8), child: const SizedBox()); }`}];function xt(t,e,n){return{artifactId:t.id,artifactName:t.artifactName,artifactType:t.artifactType,severity:e,message:n}}function tr(t){let e="",n=0;for(;n"&&(n--,n===0))return{inner:t.slice(e+1,i),end:i+1};return null}function Mv(t,e){const n=new RegExp(`class\\s+${e}\\b[^{]*\\{`).exec(t);if(!n)return null;let i=0;for(let r=n.index+n[0].length-1;rLv(t).usable);function Ov(t=""){const e=tr(t);return Nv.filter(n=>n.detect(e)).map(({id:n,severity:i,message:r})=>({id:n,severity:i,message:r}))}function Bv(t){const e=[],n=t.matchAll(/\bFuture\b/g);for(const i of n){let r=i.index+6,s=null;const o=r;for(;ro;if(t[r]==="<"){const u=$v(t,r);if(!u||(s=u.inner.replace(/\s+/g," ").trim(),r=u.end,!/\s/.test(t[r]||"")))continue;for(;rFu(o.functionName)===i);if(r)return r;const s=o=>!o.functionName.startsWith("_");return n.find(s)||n[0]}function As(t=""){return Array.from(tr(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function Dv(t="",e=""){return yl(t,e)?.returnType||null}function Ru(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 jv(t,e){const n=As(e);if(n.length===0)return null;const r=String(t||"").split("/").pop().replace(/\.dart$/,"");if(n.some(l=>Ru(l)===r)||n.length>1)return null;const[o]=n,a=`${Ru(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 wl(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function Uv(t,e,n=""){const i=yl(e,n)?.functionName;if(!i)return null;const r=String(t||"").split("/").pop(),s=_l(r,"A");if(s===i)return null;const o=`${wl(i)}.dart`;return`File name "${r}" does not match Action "${i}". FlutterFlow derives the action from the file name, so it looks for "${s}" and reports Action "${s}" declaration not found. Rename the file to "${o}" - FlutterFlow puts an underscore before every capital - or rename the function to "${s}".`}function Hv(t="",e=""){return yl(t,e)!==null}function Wv(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(i=>Fv.has(i)?!1:!Rv.some(s=>i.endsWith(s))||e.has(i))}function zv(t,{functionName:e="",declaredTypes:n=new Set}={}){const i=Dv(t,e),r=Wv(i,n);if(r.length===0)return null;const[s]=r;let o;return n.has(s)?o=`uses Code File type "${s}", which FlutterFlow cannot process as an Action Return Value`:i===s?o="is not a FlutterFlow Action Return Value":o=`uses type "${s}", which is not a FlutterFlow Action Return Value`,`CustomAction return type "${i}" ${o}. Return JSON (Future) or an existing FlutterFlow Data Type (*Struct) instead.`}function qv(t,e={}){const n=[],i=t.fileName||"",r=t.code||"";if(Pv.has(t.artifactType)||n.push(xt(t,"error",`Unsupported artifact type "${t.artifactType}".`)),i.endsWith(".dart")||n.push(xt(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!r.trim())return n.push(xt(t,"warning","Generated artifact has no Dart code yet.")),n;if(t.artifactType==="CustomWidget"){/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)||n.push(xt(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const s of Ov(r))n.push(xt(t,s.severity,s.message))}if(t.artifactType==="CustomAction"&&!Hv(r,t.artifactName)&&n.push(xt(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const s=e.declaredTypes||new Set(As(r)),o=zv(r,{functionName:t.artifactName,declaredTypes:s});o&&n.push(xt(t,"error",o));const a=Uv(i,r,t.artifactName);a&&n.push(xt(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)&&n.push(xt(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const s=jv(i,r);s&&n.push(xt(t,"info",s))}return n}function Vv(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],n=new Set(e.flatMap(s=>As(s.code||""))),i=e.flatMap(s=>qv(s,{declaredTypes:n})),r=e.map(s=>({artifactId:s.id,fileName:s.fileName,pathHint:Pu[s.artifactType]||Pu.CodeFile}));return{valid:i.every(s=>s.severity!=="error"),findings:i,deployHints:r}}const Tu="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function $u(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function Gv(t=""){const e=t.indexOf(Tu);return e===-1?t:t.slice(e+Tu.length).replace(/^\s*\n/,"")}const Kv=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function Yv(t="",e=""){const n=Gv(t),i=new Set((e.match(/^\s*import .*$/gm)||[]).map($u).filter(Boolean)),r=n.split(` `).filter(s=>{const o=$u(s);return o===null||!i.has(o)?!0:!Kv.test(s)}).join(` `).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+r}const Jv=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations"]);function ch(t){let e="",n=0;for(;n{const i=n.name||n.package;if(!i||i==="flutter")return e;const r=n.versionRequired||n.required;return e[i]=r&&n.version||"",e},{})}function t_(t){const e=new Map,n=new Map,i=[];for(const r of t)e.has(r.fileName)?i.push(`Duplicate deploy file name "${r.fileName}" for artifacts "${e.get(r.fileName)}" and "${r.artifactId}".`):e.set(r.fileName,r.artifactId),n.has(r.path)?i.push(`Duplicate deploy path "${r.path}" for artifacts "${n.get(r.path)}" and "${r.artifactId}".`):n.set(r.path,r.artifactId);return i}function n_(t,e={}){const n=Array.isArray(t?.artifacts)?t.artifacts:[],r=(e.selectedArtifactIds||t?.deployOrder||n.map(h=>h.id)).map(h=>n.find(p=>p.id===h)).filter(Boolean),s=[...t?.warnings||[]];let o=[];r.forEach(h=>{const p=e_(h),g=h.fixedCode||h.code||"",m=h.codeType||Xv[h.artifactType]||Xe.OTHER;g.trim()||s.push(`${h.artifactName||h.id} has no generated code.`),o.push({artifactId:h.id,artifactName:h.artifactName,artifactType:h.artifactType,fileName:p,content:g,type:m,path:h.deployPath||Qv(p,m),deployPath:h.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((h,p)=>({entry:h,index:p})).filter(({entry:h})=>h.type===Xe.FUNCTION&&h.path===a);if(l.length>1){const h=l[0],p={...h.entry,artifactId:l.map(({entry:m})=>m.artifactId).join("+"),artifactName:h.entry.artifactName,content:l.map(({entry:m})=>`// ${m.artifactId} ${m.content}`).join(` `)},g=new Set(l.slice(1).map(({index:m})=>m));o=o.filter((m,v)=>!g.has(v)),o[h.index]=p}const u={...Mu(t?.dependencies),...r.reduce((h,p)=>({...h,...Mu(p.dependencies)}),{})},c={};r.forEach(h=>{bl(h.code||"").forEach(p=>{p in u||(c[p]="")})});const d={...c,...u},f=t_(o);return{bundleId:t?.id||"bundle-current",title:t?.title||"Generated artifact bundle",fileEntries:o,dependencies:d,relationships:t?.relationships||[],warnings:s,errors:f}}function i_(t){return String(t||"").match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/)?.[1]}function r_(t){return String(t||"").split("/").pop().replace(/\.dart$/,"").split(/[^A-Za-z0-9]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function s_(t,e){const i=[r_(t),i_(e.content),e.artifactName].find(r=>/^[A-Z][A-Za-z0-9_]*$/.test(String(r||"")));if(!i)throw new Error(`Cannot derive a FlutterFlow custom class name for ${t}.`);return i}function o_(t,e=new Map){const n=[];for(const[i,r]of t.entries())r.type!=="C"||e.has(r.path)||n.push({artifactId:r.artifactId||i,className:s_(i,r),content:r.content,fileName:i,path:r.path});return n}function a_(t,e){const n=new Set(e.map(i=>i.path));return new Map(Array.from(t.entries()).filter(([,i])=>!n.has(i.path)))}const Lu={pass:0,warning:1,fail:2},l_=["manualActions"];function st(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Vt(...t){for(const e of t){if(typeof e=="string"&&e.trim())return e.trim();if(Array.isArray(e)&&e.length>0){const n=e.filter(i=>typeof i=="string").join(` -`);if(n)return n}}return""}function kt(t){return t==null?[]:Array.isArray(t)?t:[t]}function c_(t){const e=st(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const n=Number(e);if(Number.isFinite(n))return Nu(n);const i=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return i?Nu(Number(i[1])):null}function Nu(t){return t>=0&&t<=100?t:null}function lt(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function El(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 Ra(...t){return t.filter(Boolean).reduce((e,n)=>Lu[n]>Lu[e]?n:e,"pass")}function uh(t,e="warning",n="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:n};const i=st(t),r=Vt(i.message,i.title,i.issue,i.description,i.summary);return r?{severity:El(i.severity||i.status||i.level)||e,message:r,suggestion:Vt(i.suggestion,i.fix,i.recommendation,i.action),source:i.source||n}:null}function Ta(t,e="review"){const n=st(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([r,s])=>kt(n[r]).map(o=>uh(o,s,e)).filter(Boolean))}function u_(t,e,n=null){if(typeof t=="string")return{id:`${n||"bundle"}-manual-${e+1}`,title:t,detail:"",location:"",timing:"unspecified",artifactId:n,source:"Code Review"};const i=st(t),r=Vt(i.title,i.action,i.step,i.message,i.name,i.description);return r?{id:i.id||`${n||"bundle"}-manual-${e+1}`,title:r,detail:Vt(i.detail,i.instructions,i.description),location:Vt(i.location,i.flutterFlowPath,i.path),timing:Vt(i.timing,i.phase)||"unspecified",artifactId:n,source:Vt(i.source)||"Code Review"}:null}function $a(t,e=null){const n=st(t);return l_.flatMap(i=>kt(n[i])).map((i,r)=>u_(i,r,e)).filter(Boolean)}function d_(t){let e=typeof t=="string"?Pa(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const n=st(e);typeof n.content=="string"&&(e=Pa(n.content)||e);const i=st(e),r=st(i.reviewResult||i.codeReview||i.result);return{rawText:"",root:Object.keys(r).length?r:i}}function f_(t,e){const n=[e.id,e.fileName,e.artifactName].map(lt);return t.find(i=>{const r=st(i);return[r.id,r.fileName,r.artifactName,r.name].map(lt).some(s=>s&&n.includes(s))})||null}function h_(t,e){return kt(t?.metadata?.compatibility?.deployHints).find(r=>lt(r?.artifactId)===lt(e.id)||lt(r?.fileName)===lt(e.fileName))?.pathHint||""}function p_(t,e){return kt(t?.relationships).filter(n=>lt(n?.from)===lt(e.id)||lt(n?.to)===lt(e.id))}function g_(t,e){return kt(t?.metadata?.compatibility?.findings).filter(n=>!n?.artifactId||lt(n.artifactId)===lt(e.id)).map(n=>uh(n,"warning","Compatibility check")).filter(Boolean)}function m_(t,e,n,i){const r=f_(e,n),s=st(r?.review||r||n.review),o=Object.keys(s).length>0,a=[...Ta(s),...g_(t,n)],l=$a(s,n.id),u=El(s.status||s.verdict||s.outcome||s.result),c=a.length?Ra(...a.map(f=>f.severity)):null,d=Ra(u,c,o?null:"warning");return{...n,index:i,status:d,statusReason:o?Vt(s.summary,s.overview,s.assessment,s.conclusion)||(a.length?`${a.length} review finding${a.length===1?"":"s"}`:"No file-level findings"):"No file-level verdict was returned",reviewComplete:o,findings:a,manualSteps:l,fixedSource:typeof s.fixedSource=="string"&&s.fixedSource.trim()?s.fixedSource.trim():null,pathHint:h_(t,n),relationships:p_(t,n)}}function v_({status:t,score:e,artifactPresentations:n,manualSteps:i}){const r=n.length;if(r===0&&i.length===0)return e==null?"Code review returned no overall summary and no score.":`Reviewed bundle with score ${e}/100.`;const s=n.reduce((a,l)=>(a[l.status]+=1,a),{pass:0,warning:0,fail:0}),o=[];return t&&o.push(`Overall verdict: ${t}.`),r&&o.push(`${r} artifact${r===1?"":"s"}: ${s.pass} pass, ${s.warning} warn, ${s.fail} fail.`),i.length&&o.push(`Do before deploy: ${i.map(a=>a.title).join("; ")}.`),e==null&&o.push("No numeric score (0-100) was returned."),o.join(" ")}function __({bundle:t,reviewResult:e}){const n=st(t),i=kt(n.artifacts),{root:r,rawText:s}=d_(e),o=[r.bundleReview,r.overallReview,r.overall,r.bundleSummary,r.summaryReview,r.review].map(st).find(S=>Object.keys(S).length)||{},a=kt(r.artifacts||r.files||r.reviews),l=i.map((S,_)=>m_(n,a,S,_)),u=Ta(r),d=[...Ta(o),...u],f=[...$a(o),...$a(r),...l.flatMap(S=>S.manualSteps)].filter((S,_,b)=>b.findIndex(k=>k.title===S.title&&k.artifactId===S.artifactId)===_),h=El(o.status||o.verdict||o.overallStatus||r.status||r.verdict||r.overallStatus||r.outcome),p=Ra(h,...d.map(S=>S.severity),...l.map(S=>S.status)),g=o.score??r.score??r.overallScore??s,m=c_(g),v=Vt(o.headline,o.summary,o.executiveSummary,o.overview,o.assessment,o.conclusion,r.overallSummary,r.headline,r.summary,r.executiveSummary,r.overview,r.assessment,r.conclusion,s)||v_({status:p,score:m,artifactPresentations:l,manualSteps:f}),E=l.reduce((S,_)=>(S[_.status]+=1,S),{pass:0,warning:0,fail:0});return{title:n.title||"Generated artifact bundle",description:n.description||"",status:p,score:m,summary:v,findings:d,manualSteps:f,artifacts:l,counts:E,reviewCoverage:{reviewed:l.filter(S=>S.reviewComplete).length,total:l.length},deployOrder:kt(n.deployOrder),relationships:kt(n.relationships),warnings:kt(n.warnings),compatibility:st(n.metadata?.compatibility)}}const y_=/^\uFEFF/;function Ci(t){let e=0,n=t.length;for(;ee&&!t[n-1].trim();)n--;return t.slice(e,n).join(` +`);if(n)return n}}return""}function kt(t){return t==null?[]:Array.isArray(t)?t:[t]}function c_(t){const e=st(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const n=Number(e);if(Number.isFinite(n))return Nu(n);const i=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return i?Nu(Number(i[1])):null}function Nu(t){return t>=0&&t<=100?t:null}function lt(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function El(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 Ra(...t){return t.filter(Boolean).reduce((e,n)=>Lu[n]>Lu[e]?n:e,"pass")}function uh(t,e="warning",n="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:n};const i=st(t),r=Vt(i.message,i.title,i.issue,i.description,i.summary);return r?{severity:El(i.severity||i.status||i.level)||e,message:r,suggestion:Vt(i.suggestion,i.fix,i.recommendation,i.action),source:i.source||n}:null}function Ta(t,e="review"){const n=st(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([r,s])=>kt(n[r]).map(o=>uh(o,s,e)).filter(Boolean))}function u_(t,e,n=null){if(typeof t=="string")return{id:`${n||"bundle"}-manual-${e+1}`,title:t,detail:"",location:"",timing:"unspecified",artifactId:n,source:"Code Review"};const i=st(t),r=Vt(i.title,i.action,i.step,i.message,i.name,i.description);return r?{id:i.id||`${n||"bundle"}-manual-${e+1}`,title:r,detail:Vt(i.detail,i.instructions,i.description),location:Vt(i.location,i.flutterFlowPath,i.path),timing:Vt(i.timing,i.phase)||"unspecified",artifactId:n,source:Vt(i.source)||"Code Review"}:null}function $a(t,e=null){const n=st(t);return l_.flatMap(i=>kt(n[i])).map((i,r)=>u_(i,r,e)).filter(Boolean)}function d_(t){let e=typeof t=="string"?Pa(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const n=st(e);typeof n.content=="string"&&(e=Pa(n.content)||e);const i=st(e),r=st(i.reviewResult||i.codeReview||i.result);return{rawText:"",root:Object.keys(r).length?r:i}}function f_(t,e){const n=[e.id,e.fileName,e.artifactName].map(lt);return t.find(i=>{const r=st(i);return[r.id,r.fileName,r.artifactName,r.name].map(lt).some(s=>s&&n.includes(s))})||null}function h_(t,e){return kt(t?.metadata?.compatibility?.deployHints).find(r=>lt(r?.artifactId)===lt(e.id)||lt(r?.fileName)===lt(e.fileName))?.pathHint||""}function p_(t,e){return kt(t?.relationships).filter(n=>lt(n?.from)===lt(e.id)||lt(n?.to)===lt(e.id))}function g_(t,e){return kt(t?.metadata?.compatibility?.findings).filter(n=>!n?.artifactId||lt(n.artifactId)===lt(e.id)).map(n=>uh(n,"warning","Compatibility check")).filter(Boolean)}function m_(t,e,n,i){const r=f_(e,n),s=st(r?.review||r||n.review),o=Object.keys(s).length>0,a=[...Ta(s),...g_(t,n)],l=$a(s,n.id),u=El(s.status||s.verdict||s.outcome||s.result),c=a.length?Ra(...a.map(f=>f.severity)):null,d=Ra(u,c,o?null:"warning");return{...n,index:i,status:d,statusReason:o?Vt(s.summary,s.overview,s.assessment,s.conclusion)||(a.length?`${a.length} review finding${a.length===1?"":"s"}`:"No file-level findings"):"No file-level verdict was returned",reviewComplete:o,findings:a,manualSteps:l,fixedSource:typeof s.fixedSource=="string"&&s.fixedSource.trim()?s.fixedSource.trim():null,pathHint:h_(t,n),relationships:p_(t,n)}}function v_({status:t,score:e,artifactPresentations:n,manualSteps:i}){const r=n.length;if(r===0&&i.length===0)return e==null?"Code review returned no overall summary and no score.":`Reviewed bundle with score ${e}/100.`;const s=n.reduce((a,l)=>(a[l.status]+=1,a),{pass:0,warning:0,fail:0}),o=[];return t&&o.push(`Overall verdict: ${t}.`),r&&o.push(`${r} artifact${r===1?"":"s"}: ${s.pass} pass, ${s.warning} warn, ${s.fail} fail.`),i.length&&o.push(`Do before deploy: ${i.map(a=>a.title).join("; ")}.`),e==null&&o.push("No numeric score (0-100) was returned."),o.join(" ")}function __({bundle:t,reviewResult:e}){const n=st(t),i=kt(n.artifacts),{root:r,rawText:s}=d_(e),o=[r.bundleReview,r.overallReview,r.overall,r.bundleSummary,r.summaryReview,r.review].map(st).find(S=>Object.keys(S).length)||{},a=kt(r.artifacts||r.files||r.reviews),l=i.map((S,_)=>m_(n,a,S,_)),u=Ta(r),d=[...Ta(o),...u],f=[...$a(o),...$a(r),...l.flatMap(S=>S.manualSteps)].filter((S,_,b)=>b.findIndex(k=>k.title===S.title&&k.artifactId===S.artifactId)===_),h=El(o.status||o.verdict||o.overallStatus||r.status||r.verdict||r.overallStatus||r.outcome),p=Ra(h,...d.map(S=>S.severity),...l.map(S=>S.status)),g=o.score??r.score??r.overallScore??s,m=c_(g),v=Vt(o.headline,o.summary,o.executiveSummary,o.overview,o.assessment,o.conclusion,r.overallSummary,r.headline,r.summary,r.executiveSummary,r.overview,r.assessment,r.conclusion,s)||v_({status:p,score:m,artifactPresentations:l,manualSteps:f}),E=l.reduce((S,_)=>(S[_.status]+=1,S),{pass:0,warning:0,fail:0});return{title:n.title||"Generated artifact bundle",description:n.description||"",status:p,score:m,summary:v,findings:d,manualSteps:f,artifacts:l,counts:E,reviewCoverage:{reviewed:l.filter(S=>S.reviewComplete).length,total:l.length},deployOrder:kt(n.deployOrder),relationships:kt(n.relationships),warnings:kt(n.warnings),compatibility:st(n.metadata?.compatibility)}}const y_=/^\uFEFF/;function Ai(t){let e=0,n=t.length;for(;ee&&!t[n-1].trim();)n--;return t.slice(e,n).join(` `)}function w_(t){const e=String(t??"").replace(y_,"");if(!e.trim())return"";const n=e.split(` -`),i=c=>{const d=c.trim();return/^`{3,}[A-Za-z0-9+#_.-]*$/.test(d)?c.length-c.trimStart().length:-1};let r=0,s=-1;const o=[];{let c=0;for(let d=0;d=0&&(r++,s<0&&(s=d),o.push(c+f)),c+=n[d].length+1}}if(r===0)return Ci(n);{const c=Ma(e);if(!c.error&&o.every(f=>Bu(f,c.commentAndStringRanges)))return Ci(n)}if(r===1){const c=Ci(n.slice(0,s)),d=Ci(n.slice(s+1));return d.length>=c.length?d:c}const a=[];let l=null;for(let c=0;c{const d=c.trim();return/^`{3,}[A-Za-z0-9+#_.-]*$/.test(d)?c.length-c.trimStart().length:-1};let r=0,s=-1;const o=[];{let c=0;for(let d=0;d=0&&(r++,s<0&&(s=d),o.push(c+f)),c+=n[d].length+1}}if(r===0)return Ai(n);{const c=Ma(e);if(!c.error&&o.every(f=>Bu(f,c.commentAndStringRanges)))return Ai(n)}if(r===1){const c=Ai(n.slice(0,s)),d=Ai(n.slice(s+1));return d.length>=c.length?d:c}const a=[];let l=null;for(let c=0;cc.length>0);return u.length===0?"":u.join(` +${d}`,{commentAndStringRanges:g}=Ma(p),m=h.length+1+f;if(Bu(m,g)){l.push(d);continue}a.push(Ai(l)),l=null}const u=a.filter(c=>c.length>0);return u.length===0?"":u.join(` `)}function b_(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 dh(t){const e=b_(t);return Array.from(e.matchAll(/class\s+([A-Z]\w*)\s+extends\s+[A-Za-z_]\w*Widget\b/g),n=>n[1])}function fh(t){return`${wl(t)}.dart`}function E_(t){return _l(t,"W")}const Ou={"(":")","[":"]","{":"}"},S_={")":"(","]":"[","}":"{"},x_=/[A-Za-z0-9_]/;function Ma(t){const e=[{kind:"code",opener:null,openedLine:0}],n=[];let i=1,r=0;const s=(c,d)=>{(c===` `||c==="\r"&&d!==` `)&&i++};let o=null;const a=()=>{for(const c of e)(c.kind==="string"||c.kind==="block-comment"||c.kind==="line-comment")&&n.push({start:c.startIndex,end:t.length})};for(;r0?t[r-1]:"",p=r>1?t[r-2]:"",g=(h==="r"||h==="R")&&!x_.test(p);e.push({kind:"string",quote:c,triple:f,raw:g,startIndex:r,openedLine:i}),r+=f?3:1;continue}if(Ou[c]){e.push({kind:"code",opener:c,openedLine:i}),r++;continue}if(S_[c]){if(d.interpolation&&c==="}"){e.pop(),r++;continue}if(d.opener&&Ou[d.opener]===c){e.pop(),r++;continue}return d.opener?(a(),{error:o??`line ${i}: "${c}" closes nothing - "${d.opener}" opened on line ${d.openedLine} is still open`,commentAndStringRanges:n}):(a(),{error:o??`line ${i}: unexpected "${c}" with no matching opener`,commentAndStringRanges:n})}s(c,t[r+1]),r++}a();let l=e.length-1;for(;l>0&&e[l].kind==="line-comment";)l--;let u=o;if(!u){const c=e[l];if(!(c.kind==="code"&&!c.opener&&!c.interpolation))if(c.kind==="string")u=`unclosed ${c.triple?"triple-quoted ":""}string starting on line ${c.openedLine} was never closed`;else if(c.kind==="block-comment")u=`unterminated /* comment starting on line ${c.openedLine}`;else if(c.interpolation){const d=e.findLast(h=>h.opener);u=`unclosed "\${" expression${d?` opened on line ${d.openedLine}`:""} was never closed`}else u=`"${c.opener}" opened on line ${c.openedLine} is never closed`}return{error:u,commentAndStringRanges:n}}function I_(t){return Ma(String(t??"")).error}function Bu(t,e){return e.some(({start:n,end:i})=>t>=n&&ttypeof n=="string"?n:n?.errorMessage).filter(Boolean);return e.length>0?e.join("; "):JSON.stringify(t)}return t&&typeof t=="object"?t.errorMessage||JSON.stringify(t):String(t??"")}const k_=["gmail.com","googlemail.com","outlook.com","hotmail.com","live.com","msn.com"],C_="MAGIC_LINK_SENT",A_="PLUS_ALIAS_REJECTED",P_="Please enter your primary email address. Plus aliases (such as {email}) are not allowed for {domain} accounts.",Ps={allowlistedDomains:k_,successCode:C_,validationCode:A_,messageTemplate:P_},F_=new Set(Ps.allowlistedDomains),R_=Ps.successCode,hh=Ps.validationCode;function Fs(t){return typeof t=="string"?t.trim():""}function T_(t){const e=Fs(t),n=e.lastIndexOf("@");if(n<=0||n===e.length-1)return!1;const i=e.slice(0,n),r=e.slice(n+1).toLowerCase();return F_.has(r)?i.includes("+"):!1}function $_(t,e){return Ps.messageTemplate.replaceAll("{email}",t).replaceAll("{domain}",e)}function ph(t){if(!T_(t))return null;const e=Fs(t),n=e.lastIndexOf("@"),i=e.slice(n+1).toLowerCase();return $_(e,i)}function gh(t,e){return t?.code===hh?t.message||ph(e)||"Please enter your primary email address.":t?.code===R_||!t?.code?`Check your email — we sent a link to ${Fs(e)}`:t.message||"Something went wrong. Please try again."}const M_="ccc_auth_session",L_="ccc_subscription",N_=Object.freeze(["hasSeenWalkthrough"]);function O_(t){const e=[];for(const n of N_)t.getItem(n)!==null&&(t.removeItem(n),e.push(n));return e}function B_(){return[M_,L_]}function D_({storage:t,onIdentityChanged:e,onPlanChanged:n}){for(const i of B_())t.removeItem(i);typeof e=="function"&&e(),typeof n=="function"&&n()}function j_({sendLink:t,getEmail:e,onState:n}){let i=!1;return async function(){if(i)return{status:"busy"};i=!0;let s;try{n({status:"pending",error:null});const o=await t(e());return s={status:"sent",data:o},n({status:"sent",data:o}),s}catch(o){return s={status:"error",error:o},n({status:"error",error:o}),s}finally{i=!1}}}const U_=/^dependencies\s*:\s*(?:#.*)?$/,H_=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function Rs(t){const e=t.match(H_);return e?e[1]??e[2]??e[3]:null}function ar(t){const e=t.trim();return e===""||e.startsWith("#")}function fi(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function xl(t,e){const n=t.findIndex(s=>e.test(s));if(n===-1)return null;let i=n,r=null;for(let s=n+1;s=0.0.0"}`}function V_(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([u])=>u&&u!=="flutter");if(i.length===0)return{yaml:n,added:[],alreadyPresent:[]};const r=n.split(` +`){n.push({start:d.startIndex,end:r}),o??=`line ${i}: string starting on line ${d.openedLine} is never closed`,e.pop();continue}if(!d.raw&&c==="\\"){s(t[r+1]??"",t[r+2]??""),r+=2;continue}if(!d.raw&&c==="$"&&t[r+1]==="{"){e.push({kind:"code",opener:null,interpolation:!0}),r+=2;continue}const f=d.triple?3:1;if(c===d.quote&&t.slice(r,r+f)===d.quote.repeat(f)){n.push({start:d.startIndex,end:r+f}),e.pop(),r+=f;continue}s(c,t[r+1]),r++;continue}if(c==="/"&&t[r+1]==="/"){e.push({kind:"line-comment",startIndex:r}),r+=2;continue}if(c==="/"&&t[r+1]==="*"){e.push({kind:"block-comment",startIndex:r,openedLine:i,depth:1}),r+=2;continue}if(c==="'"||c==='"'){const f=t.slice(r,r+3)===c.repeat(3),h=r>0?t[r-1]:"",p=r>1?t[r-2]:"",g=(h==="r"||h==="R")&&!x_.test(p);e.push({kind:"string",quote:c,triple:f,raw:g,startIndex:r,openedLine:i}),r+=f?3:1;continue}if(Ou[c]){e.push({kind:"code",opener:c,openedLine:i}),r++;continue}if(S_[c]){if(d.interpolation&&c==="}"){e.pop(),r++;continue}if(d.opener&&Ou[d.opener]===c){e.pop(),r++;continue}return d.opener?(a(),{error:o??`line ${i}: "${c}" closes nothing - "${d.opener}" opened on line ${d.openedLine} is still open`,commentAndStringRanges:n}):(a(),{error:o??`line ${i}: unexpected "${c}" with no matching opener`,commentAndStringRanges:n})}s(c,t[r+1]),r++}a();let l=e.length-1;for(;l>0&&e[l].kind==="line-comment";)l--;let u=o;if(!u){const c=e[l];if(!(c.kind==="code"&&!c.opener&&!c.interpolation))if(c.kind==="string")u=`unclosed ${c.triple?"triple-quoted ":""}string starting on line ${c.openedLine} was never closed`;else if(c.kind==="block-comment")u=`unterminated /* comment starting on line ${c.openedLine}`;else if(c.interpolation){const d=e.findLast(h=>h.opener);u=`unclosed "\${" expression${d?` opened on line ${d.openedLine}`:""} was never closed`}else u=`"${c.opener}" opened on line ${c.openedLine} is never closed`}return{error:u,commentAndStringRanges:n}}function I_(t){return Ma(String(t??"")).error}function Bu(t,e){return e.some(({start:n,end:i})=>t>=n&&ttypeof n=="string"?n:n?.errorMessage).filter(Boolean);return e.length>0?e.join("; "):JSON.stringify(t)}return t&&typeof t=="object"?t.errorMessage||JSON.stringify(t):String(t??"")}const k_=["gmail.com","googlemail.com","outlook.com","hotmail.com","live.com","msn.com"],C_="MAGIC_LINK_SENT",A_="PLUS_ALIAS_REJECTED",P_="Please enter your primary email address. Plus aliases (such as {email}) are not allowed for {domain} accounts.",Ps={allowlistedDomains:k_,successCode:C_,validationCode:A_,messageTemplate:P_},F_=new Set(Ps.allowlistedDomains),R_=Ps.successCode,hh=Ps.validationCode;function Fs(t){return typeof t=="string"?t.trim():""}function T_(t){const e=Fs(t),n=e.lastIndexOf("@");if(n<=0||n===e.length-1)return!1;const i=e.slice(0,n),r=e.slice(n+1).toLowerCase();return F_.has(r)?i.includes("+"):!1}function $_(t,e){return Ps.messageTemplate.replaceAll("{email}",t).replaceAll("{domain}",e)}function ph(t){if(!T_(t))return null;const e=Fs(t),n=e.lastIndexOf("@"),i=e.slice(n+1).toLowerCase();return $_(e,i)}function gh(t,e){return t?.code===hh?t.message||ph(e)||"Please enter your primary email address.":t?.code===R_||!t?.code?`Check your email — we sent a link to ${Fs(e)}`:t.message||"Something went wrong. Please try again."}const M_="ccc_auth_session",L_="ccc_subscription",N_=Object.freeze(["hasSeenWalkthrough"]);function O_(t){const e=[];for(const n of N_)t.getItem(n)!==null&&(t.removeItem(n),e.push(n));return e}function B_(){return[M_,L_]}function D_({storage:t,onIdentityChanged:e,onPlanChanged:n}){for(const i of B_())t.removeItem(i);typeof e=="function"&&e(),typeof n=="function"&&n()}function j_({sendLink:t,getEmail:e,onState:n}){let i=!1;return async function(){if(i)return{status:"busy"};i=!0;let s;try{n({status:"pending",error:null});const o=await t(e());return s={status:"sent",data:o},n({status:"sent",data:o}),s}catch(o){return s={status:"error",error:o},n({status:"error",error:o}),s}finally{i=!1}}}const U_=/^dependencies\s*:\s*(?:#.*)?$/,H_=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function Rs(t){const e=t.match(H_);return e?e[1]??e[2]??e[3]:null}function ar(t){const e=t.trim();return e===""||e.startsWith("#")}function hi(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function xl(t,e){const n=t.findIndex(s=>e.test(s));if(n===-1)return null;let i=n,r=null;for(let s=n+1;s=0.0.0"}`}function V_(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([u])=>u&&u!=="flutter");if(i.length===0)return{yaml:n,added:[],alreadyPresent:[]};const r=n.split(` `),s=new Set(vh(n)),o=[],a=[];for(const[u,c]of i)s.has(u)?a.push(u):(o.push([u,c]),s.add(u));if(o.length===0)return{yaml:n,added:[],alreadyPresent:a};const l=Il(r);if(l){const u=o.map(([c,d])=>Du(l.childIndent,c,d));r.splice(l.endIndex,0,...u)}else r.length>0&&r[r.length-1].trim()!==""&&r.push(""),r.push("dependencies:"),o.forEach(([u,c])=>{r.push(Du(" ",u,c))});return{yaml:r.join(` `),added:o.map(([u])=>u),alreadyPresent:a}}function G_(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([l])=>l&&l!=="flutter");if(i.length===0)return{yaml:n,overridden:[],skipped:[]};const r=n.split(` -`),s=$s(n),o=[],a=[];for(const[l,u]of i){const c=s.get(l);if(!c||!c.isScalar||!String(u||"").trim()){a.push(l);continue}const d=" ".repeat(fi(r[c.lineIndex]));r[c.lineIndex]=`${d}${l}: ${yh(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:r.join(` +`),s=$s(n),o=[],a=[];for(const[l,u]of i){const c=s.get(l);if(!c||!c.isScalar||!String(u||"").trim()){a.push(l);continue}const d=" ".repeat(hi(r[c.lineIndex]));r[c.lineIndex]=`${d}${l}: ${yh(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:r.join(` `),overridden:o,skipped:a}}function wh(t){const e=String(t||""),n=[];return e.trim()?(/^name:\s*\S+/m.test(e)||n.push("pubspec.yaml missing name field"),Il(e.split(` `))||n.push("pubspec.yaml missing dependencies section"),vh(e).includes("flutter")||n.push("pubspec.yaml missing Flutter SDK dependency"),{valid:n.length===0,errors:n}):(n.push("pubspec.yaml is empty"),{valid:!1,errors:n})}const K_=">=3.0.0 <4.0.0";function La(t){const e=String(t||"").trim(),n=e[0];return n!=="'"&&n!=='"'||e[e.length-1]!==n?e:e.slice(1,-1).replaceAll(`${n}${n}`,n)}function Y_(t=""){const e=Zv(t).filter(n=>!n.startsWith("dart:")&&!n.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function ju(t,e,n){const i=[];for(const[r,s]of t){if(s.isScalar){e[r]=La(s.constraint);continue}if(s.sourceKey==="sdk"){n.add(r);continue}if(s.sourceKey===null&&s.version){e[r]=La(s.version);continue}i.push(r)}return i}function J_(t){const e=new Set,n={},i={},r=ju($s(t),n,e);r.push(...ju(z_(t,"dependency_overrides"),i,e));const s=new Set([...Object.keys(n),...e]),{sdk:o}=_h(t);return{sdkConstraint:La(o)||K_,dependencies:n,overrides:i,sdkPackages:[...e].sort(),availablePackages:s,unrepresentable:r}}function Z_(t,e,n){return e.length>0?`${t} imports ${e.join(", ")}, which FlutterFlow only generates once the app is built, so it could not be compiled before the deploy.`:`${t} imports ${n.join(", ")}, which your project's pubspec.yaml does not declare with a version constraint, so it could not be compiled before the deploy.`}function X_(t,e){const{sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s,availablePackages:o,unrepresentable:a}=J_(e),l={sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s},u=[],c=[],d=a.map(f=>`Your project declares ${f} from a source that cannot be reproduced outside it, so the pre-deploy compile check runs against a scratch package graph that omits ${f}. Classes that do not import ${f} directly are still checked, but against that reduced graph, so their transitive package resolution may differ from your project's and the check is approximate for them.`);for(const f of t){const{className:h,content:p}=f,g=bl(p),m=g.filter(S=>a.includes(S));if(m.length>0){c.push({className:h,reason:`${h} was not compiled before deploying: it imports ${m.join(", ")}, which your project declares from a source that cannot be reproduced outside it, so package resolution could not be matched exactly.`});continue}const{unresolvableImports:v}=Y_(p),E=g.filter(S=>!o.has(S));if(v.length>0||E.length>0){c.push({className:h,reason:Z_(h,v,E)});continue}u.push({fileName:`${wl(h)}.dart`,content:p})}return{manifest:l,sources:u,skipped:c,approximate:d}}function Uu(t,e){const n=`${t}${e}`.split(` `),i=n.pop()??"",r=[];for(const s of n){const o=bh(s);o&&r.push(o)}return{events:r,buffer:i}}function Q_(t){const e=bh(t);return e?[e]:[]}function bh(t){const e=t.trim();if(!e)return null;try{const n=JSON.parse(e);return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}const Le=Object.freeze({COMMITTED:"committed",PARTIAL:"partial",FAILED:"failed",UNCONFIRMED:"unconfirmed"}),Eh=12e4,Sh=1e4;function xh(t){return t?.unconfirmed===!0||t?.outcome===Le.UNCONFIRMED?Le.UNCONFIRMED:t?.partial===!0||t?.outcome===Le.PARTIAL?Le.PARTIAL:t?.success===!0?Le.COMMITTED:Le.FAILED}class Qe extends Error{constructor(e){super(e),this.name="UnconfirmedDeployError",this.outcome=Le.UNCONFIRMED}}function Hu({httpStatus:t}={}){return new Qe(`Every FlutterFlow sync endpoint lost its response or ended in a server error${t?` (last: HTTP ${t})`:""} — neither can prove the push was refused, so it may already have been applied. Open the FlutterFlow project to reconcile before retrying.`)}async function ey(t,e={}){const{onPhase:n,onLog:i}=e;let r=null,s=null,o="";const a=u=>{if(u.event==="phase"){u.phase&&(s=u.phase),u.message&&n&&n(u.message);return}if(u.event==="log"){u.message&&i&&i(u.message);return}r=u};let l=null;try{if(t.body?.getReader){const u=t.body.getReader(),c=new TextDecoder;for(;;){const{done:d,value:f}=await u.read();if(d)break;const h=Uu(o,c.decode(f,{stream:!0}));o=h.buffer,h.events.forEach(a)}}else{const u=Uu("",await t.text());o=u.buffer,u.events.forEach(a)}}catch(u){l=u}return Q_(o).forEach(a),r?{...r,success:r.success===!0||r.success===void 0&&t.ok,finalResultReceived:!0,runnerPhase:s,httpStatus:t.status}:{success:!1,finalResultReceived:!1,httpRejected:!t.ok,httpStatus:t.status,runnerPhase:s,error:t.ok?l?"The connection to the FlutterFlow deploy runner dropped before it reported a result.":"The FlutterFlow deploy runner closed the connection before it finished.":`FlutterFlow custom class provisioning failed (HTTP ${t.status}).`}}const ty=new Set(["connected","workspace_init","workspace_ready","verifying"]);function ny(t){return t?.preWrite===!0||Array.isArray(t?.analyzerErrors)&&t.analyzerErrors.length>0?!0:typeof t?.runnerPhase=="string"?ty.has(t.runnerPhase):typeof t?.httpStatus=="number"?t.httpStatus>=400&&t.httpStatus<500:!1}function Wu(t){if(t?.finalResultReceived){const e=xh(t);return e===Le.FAILED&&!ny(t)?Le.UNCONFIRMED:e}return t?.httpRejected?Le.FAILED:Le.UNCONFIRMED}function iy(){let t=document.getElementById("fx-grid");if(!t)return null;const e=window.matchMedia("(prefers-reduced-motion: reduce)"),n=window.matchMedia("(pointer: none)");let i=t.getContext("webgl2",{alpha:!0,antialias:!1,depth:!1,stencil:!1,premultipliedAlpha:!0,powerPreference:"low-power"}),r=i?null:t.getContext("2d");if(!i&&!r)return null;const s='',o=`#version 300 es in vec2 p; void main(){ gl_Position = vec4(p, 0.0, 1.0); }`;function a(){return["#version 300 es","precision highp float;","out vec4 o;","uniform vec2 res;","uniform vec2 design;","uniform vec2 mouse;","uniform float energy;","uniform float parallax;","uniform float t;","uniform vec3 ink;","uniform sampler2D mark;","uniform vec2 rot;","const float WARP_A = 0.0032;","void main(){"," vec2 px = gl_FragCoord.xy * (design / res);"," vec2 p = vec2(px.x, design.y - px.y);"," vec2 off = vec2(0.0, -parallax) + vec2(sin(t * 0.11), cos(t * 0.09)) * 7.0;"," vec2 g = p + off;"," vec2 gm = mouse + off;"," float base = min(design.x, design.y);"," float spacing = clamp(base / 10.0, 64.0, 118.0);"," vec2 rel = g - gm;"," float rho = length(rel) + 1e-5;"," vec2 dir = rel / rho;"," vec2 pw = gm + dir * (rho + WARP_A * rho * rho);"," vec2 cell = floor(pw / spacing);"," vec2 cw = (cell + 0.5) * spacing - gm;"," float Rc = length(cw) + 1e-5;"," float rhoC = (-1.0 + sqrt(1.0 + 4.0 * WARP_A * Rc)) / (2.0 * WARP_A);"," vec2 c = gm + (cw / Rc) * rhoC;"," float cellSize = spacing / (1.0 + 2.0 * WARP_A * rhoC);"," float sigma = spacing * 2.9;"," float f = exp(-(rhoC * rhoC) / (2.0 * sigma * sigma));"," float scale = mix(0.32, 1.42, f);"," float weight = smoothstep(0.06, 0.80, f);"," float hs = cellSize * 0.26 * scale;"," vec2 uv = (g - c) / hs;"," vec2 ruv = mat2(rot.x, rot.y, -rot.y, rot.x) * uv;"," float cov = 0.0;"," if (abs(ruv.x) <= 1.0 && abs(ruv.y) <= 1.0) cov = texture(mark, ruv * 0.5 + 0.5).a;"," float s = cov * weight * energy * 0.26;"," o = vec4(ink * s, s);","}"].join(` -`)}let l=null,u,c,d,f,h,p,g,m,v;function E(Y,W){if(!i)return null;const D=i.createShader(Y);return i.shaderSource(D,W),i.compileShader(D),i.getShaderParameter(D,i.COMPILE_STATUS)?D:(window.console&&console.warn("fx-grid shader: "+i.getShaderInfoLog(D)),null)}if(i){const Y=E(i.VERTEX_SHADER,o),W=E(i.FRAGMENT_SHADER,a());if(Y&&W&&(l=i.createProgram(),i.attachShader(l,Y),i.attachShader(l,W),i.linkProgram(l),i.getProgramParameter(l,i.LINK_STATUS)||(window.console&&console.warn("fx-grid link: "+i.getProgramInfoLog(l)),l=null)),l){i.useProgram(l),i.bindBuffer(i.ARRAY_BUFFER,i.createBuffer()),i.bufferData(i.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),i.STATIC_DRAW);const D=i.getAttribLocation(l,"p");i.enableVertexAttribArray(D),i.vertexAttribPointer(D,2,i.FLOAT,!1,0,0),u=i.getUniformLocation(l,"res"),c=i.getUniformLocation(l,"design"),d=i.getUniformLocation(l,"mouse"),f=i.getUniformLocation(l,"energy"),h=i.getUniformLocation(l,"parallax"),p=i.getUniformLocation(l,"t"),g=i.getUniformLocation(l,"ink"),m=i.getUniformLocation(l,"mark"),v=i.getUniformLocation(l,"rot"),i.enable(i.BLEND),i.blendFunc(i.ONE,i.ONE_MINUS_SRC_ALPHA),i.clearColor(0,0,0,0)}else{i=null;const D=t.cloneNode(!1);if(t.parentNode.replaceChild(D,t),t=D,r=t.getContext("2d"),!r)return null}}function S(Y){if(!Y)return null;const W=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(Y);if(W){let D=W[1];return D.length===3&&(D=D[0]+D[0]+D[1]+D[1]+D[2]+D[2]),[parseInt(D.slice(0,2),16)/255,parseInt(D.slice(2,4),16)/255,parseInt(D.slice(4,6),16)/255]}try{const D=document.createElement("canvas");D.width=1,D.height=1;const ue=D.getContext("2d");ue.fillStyle="rgb(9, 8, 7)";const xe=String(ue.fillStyle);ue.fillStyle=Y;const Fe=String(ue.fillStyle);if(Fe===xe)return null;const dt=/^#([0-9a-f]{6})$/i.exec(Fe);if(dt){const ft=dt[1];return[parseInt(ft.slice(0,2),16)/255,parseInt(ft.slice(2,4),16)/255,parseInt(ft.slice(4,6),16)/255]}const Nt=/rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i.exec(Fe);if(Nt)return[Number(Nt[1])/255,Number(Nt[2])/255,Number(Nt[3])/255]}catch{}return null}function _(){let Y="";try{const W=getComputedStyle(document.documentElement);Y=(W.getPropertyValue("--fx-ink")||"").trim()||(W.getPropertyValue("--fg")||"").trim()}catch{}return S(Y)||[.56,.68,.88]}const b=_();let k=1920,T=1080,x=960,F=540,$=960,O=540,L=.66,N=0,K=-1e9,V=!1,M=0,R=0,Z=null,Ce=!1,oe=!1,ye=!1;const $e=64,ae=15.2;let Ie=0,Se=0;const De=.0032,wt=0,ge=.56,Je=.26,bt=.32,mn=.16,Re=.349;let Pe=wt;function $t(){const Y=t.getBoundingClientRect(),W=t.clientWidth,D=t.clientHeight;if(!Y.width||!W||!D)return;const ue=Math.min(window.devicePixelRatio||1,2),xe=Math.max(.2,Math.min(2,Y.width/W*ue)),Fe=Math.max(2,Math.round(W*xe)),dt=Math.max(2,Math.round(D*xe));(Fe!==t.width||dt!==t.height)&&(t.width=Fe,t.height=dt,i&&i.viewport(0,0,Fe,dt)),k=W,T=D,V||(x=$=k/2,F=O=T/2,V=!0)}function Bn(Y){!l||!Ce||!i||(i.uniform2f(u,t.width,t.height),i.uniform2f(c,k,T),i.uniform2f(d,x,F),i.uniform1f(f,L),i.uniform1f(h,N),i.uniform2f(v,Math.cos(Pe),Math.sin(Pe)),i.uniform1f(p,Y),i.uniform3f(g,b[0],b[1],b[2]),i.clear(i.COLOR_BUFFER_BIT),i.drawArrays(i.TRIANGLES,0,3))}function qe(Y,W,D){const ue=Math.max(0,Math.min(1,(D-Y)/(W-Y)));return ue*ue*(3-2*ue)}function Dn(Y){if(!Z||!r)return;const W=r;W.setTransform(1,0,0,1,0,0),W.clearRect(0,0,t.width,t.height);const D=t.width/k;W.setTransform(D,0,0,D,0,0),W.globalAlpha=1;const ue=Math.min(k,T),xe=Math.max(64,Math.min(118,ue/10)),Fe=xe*2.9,dt=2*Fe*Fe,Nt=Math.sin(Y*.11)*7,ft=Math.cos(Y*.09)*7-N,dr=x+Nt,fr=F+ft,no=Fe*Math.sqrt(2*Math.log(1/.06)),mi=no+De*no*no+xe,Rp=Math.floor((dr-mi)/xe)-1,Tp=Math.ceil((dr+mi)/xe)+1,$p=Math.floor((fr-mi)/xe)-1,Mp=Math.ceil((fr+mi)/xe)+1;for(let io=$p;io<=Mp;io++){const Lp=(io+.5)*xe;for(let ro=Rp;ro<=Tp;ro++){const so=(ro+.5)*xe-dr,oo=Lp-fr,ao=Math.sqrt(so*so+oo*oo)+1e-5;if(ao>mi)continue;const hr=(-1+Math.sqrt(1+4*De*ao))/(2*De),cc=Math.exp(-(hr*hr)/dt),uc=qe(.06,.8,cc)*L*.26;if(uc<.004)continue;const on=xe/(1+2*De*hr)*.26*(.32+1.1*cc),dc=hr/ao,lo=dr+so*dc,co=fr+oo*dc;lo<-on*1.6||lo>k+on*1.6||co<-on*1.6||co>T+on*1.6||(W.globalAlpha=uc,W.save(),W.translate(lo,co),W.rotate(Pe),W.drawImage(Z,-on,-on,on*2,on*2),W.restore())}}W.globalAlpha=1}function Mt(Y){if(!oe)return;const W=R?Math.min(.05,(Y-R)/1e3):.016;R=Y;const ue=Y-K>2400?.6:1;L+=(ue-L)*Math.min(1,W*3.2);const xe=Math.min(.05,W);Ie+=(($-x)*$e-Ie*ae)*xe,Se+=((O-F)*$e-Se*ae)*xe,x+=Ie*xe,F+=Se*xe,N=(window.scrollY||window.pageYOffset||0)*.55;const Fe=Y/1e3,dt=x/(k||1)-.5,Nt=F/(T||1)-.5;let ft=dt*(dt>=0?ge:Je)+Nt*(Nt>=0?bt:mn);ft>Re?ft=Re:ft<-Re&&(ft=-Re),Pe=wt+ft-N*6e-4,$t(),i?Bn(Fe):Dn(Fe),M=requestAnimationFrame(Mt)}function Lt(Y){if(!oe)return;const W=t.getBoundingClientRect();!W.width||!k||!T||($=(Y.clientX-W.left)/W.width*k,O=(Y.clientY-W.top)/W.height*T,K=performance.now())}function ut(){oe||to||e.matches||n.matches||!ye||document.hidden||(oe=!0,R=0,M=requestAnimationFrame(Mt))}function sn(){oe=!1,M&&(cancelAnimationFrame(M),M=0),R=0}function gi(){e.matches?(sn(),t.classList.remove("is-ready")):ye&&ut()}function jn(){n.matches?sn():ye&&ut()}function oc(){document.hidden?sn():ye&&ut()}const ac=new IntersectionObserver(Y=>{ye=Y[0]?.isIntersecting||!1,ye?ut():sn()},{threshold:0});ac.observe(t),window.addEventListener("pointermove",Lt,{passive:!0,capture:!0}),window.addEventListener("resize",$t),e.addEventListener("change",gi),n.addEventListener("change",jn),document.addEventListener("visibilitychange",oc);function Fp(){const Y=(s.match(/\sd="([^"]+)"/)||[])[1],W=document.createElement("canvas");W.width=256,W.height=256;const D=W.getContext("2d");if(Y&&window.Path2D){const ue=Math.min(8.533333333333333,8.421052631578947);D.setTransform(ue,0,0,ue,ue+(256-30*ue)/2,-6.4*ue),D.fillStyle="rgb(255,255,255)",D.fill(new Path2D(Y),"evenodd"),D.setTransform(1,0,0,1,0,0)}try{const ue=D.getImageData(0,0,256,256),xe=ue.data;for(let Fe=3;Feoe}}const ry=120;function sy(t,e,n){return tn?n:t}function de(t,e,n){return sy((t-e)/(n-e),0,1)}function oy(t){return t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2}function Uo(t){return 1-Math.pow(1-t,3)}function Ve(t,e){return e=e===void 0?1.7:e,1+(e+1)*Math.pow(t-1,3)+e*Math.pow(t-1,2)}function zu(t){return 1-Math.pow(2,-9*t)*Math.cos(t*15)}function te(t,e){if(t<=e[0].t)return e[0].v;for(let n=1;n8.2&&_<9.4&&(s*=1-.07*Math.sin(de(_,8.2,9.4)*Math.PI))}else if(t<53){const _=t-42;g=te(_,[{t:0,v:1},{t:2,v:0},{t:4.2,v:0},{t:4.6,v:1},{t:6.8,v:1},{t:7.4,v:0},{t:9.4,v:0},{t:10.6,v:1}]),p=te(_,[{t:0,v:1},{t:2,v:.3},{t:4.6,v:1,e:Ve}]),d=te(_,[{t:0,v:0},{t:2,v:.3},{t:4.6,v:.16,e:Ve},{t:10.6,v:0}]),h=te(_,[{t:0,v:0},{t:2,v:-40},{t:4.6,v:0,e:Ve}]),o=te(_,[{t:0,v:0},{t:4.6,v:-.12},{t:10.6,v:0}])}else if(t<60){const _=t-53;c=te(_,[{t:0,v:1},{t:.35,v:0},{t:.45,v:0},{t:.7,v:1}]);const b=de(_,.45,2.2);a=b>0?-2.6*(1-zu(b)):0,g=te(_,[{t:0,v:1},{t:.57,v:0},{t:.67,v:0},{t:.92,v:1}]);const k=de(_,.67,2.42);f=k>0?-2.6*(1-zu(k)):0,s=1-.05*(Math.sin(de(_,1.9,2.5)*Math.PI)+Math.sin(de(_,2.5,3.1)*Math.PI))}else if(t<74){let b=function(F){return[te(F,[{t:0,v:0},{t:.25,v:1},{t:.5,v:1},{t:.72,v:.14},{t:.82,v:.14},{t:1,v:0}]),te(F,[{t:0,v:0},{t:.08,v:-.62},{t:.25,v:-.62},{t:.33,v:.62},{t:.7,v:.62},{t:.82,v:-.62},{t:1,v:-.62}])]};var S=b;const _=t-60,k=1-de(_,12,14),T=b(de(_,0,12)),x=b(de(_-.5,0,12));n=T[0]*k,i=(T[1]+.05*Math.sin(_*7))*k,o=(x[0]-T[0])*.6*k,a=(x[1]-T[1])*.6*k,h=(x[0]-T[0])*30*k,E=de(_,0,.4)*k}else if(t<85.4){const _=t-74,b=te(_,[{t:0,v:0},{t:4,v:1},{t:8,v:.24},{t:9.6,v:1,e:Ve},{t:11.4,v:0}]);o=b*.5,d=-b*.5,l=te(_,[{t:0,v:0},{t:4,v:6},{t:8,v:20},{t:9.6,v:38,e:Ve},{t:11.4,v:0}]),h=-l*.7,a=te(_,[{t:0,v:0},{t:8,v:0},{t:9.6,v:.4},{t:11.4,v:0}])}else if(t<96.4){const _=t-85.4,b=de(_,0,5.6),k=de(_,5.6,7.6),T=.72*Math.min(1,_/.6)*(1-k);d=Math.cos(b*Math.PI*2)*T,f=Math.sin(b*Math.PI*2)*T*.55,h=b*360*(1-k);const x=te(_,[{t:0,v:0},{t:7.6,v:0},{t:8.2,v:1,e:Uo},{t:8.6,v:.55},{t:9.4,v:0}]);o=-.16*x,d+=.16*x,l=-6*x,h+=6*x,s=1+.05*x,m=1+.9*x}else if(t<108.6){const _=t-96.4,b=de(_,9.6,12.2);n=te(_,[{t:0,v:0},{t:2.1,v:1},{t:4.8,v:.08},{t:7.5,v:1},{t:9.6,v:0}])*(1-b),i=-.35*Math.abs(Math.sin(de(_,0,9.6)*Math.PI*3))*(1-b);const k=Math.sin(_*6.2)*(1-b);u=1+.12*k,p=1-.12*k,l=k*8,h=-k*8,o=.06*k,d=-.06*k,E=de(_,0,.4)*(1-b)}else{const _=t-108.6,b=Math.sin(de(_,0,8)*Math.PI),k=1-de(_,8,11.4);s=1+.04*b*k,i=-.1*b*k,r=2*b*k,m=1+.5*Math.sin(de(_,0,6)*Math.PI),v=1+.1*Math.sin(de(_,0,6)*Math.PI)}return e.x=n,e.y=i,e.rot=r,e.scale=s,e.ax=o,e.ay=a,e.ar=l,e.asc=u,e.afade=c,e.bx=d,e.by=f,e.br=h,e.bsc=p,e.bfade=g,e.hfade=m,e.hsc=v,e.shd=E,e}function ay(t={}){const e=t.arena||document.querySelector(".pipeline-glyph.logo-loop");if(!e)return null;const n=e.querySelector(".loop-mark"),i=e.querySelector(".loop-piece-a"),r=e.querySelector(".loop-piece-b"),s=e.querySelector(".loop-halo"),o=e.querySelector(".loop-shadow");if(!n||!i||!r||!s||!o)return null;const a=t.reducedMotion||window.matchMedia("(prefers-reduced-motion: reduce)"),l=ry;let u=34,c=0,d=0;function f(){u=n.offsetWidth||34,c=Math.max(0,e.offsetWidth-u-4),d=Math.max(0,(e.offsetHeight-u)/2-2),e.style.setProperty("--mark-c",u/2+"px")}function h(M){const R=Math.min(1,Math.max(0,M.x))*c,Z=M.y*d;n.style.transform="translate3d("+R.toFixed(2)+"px,"+Z.toFixed(2)+"px,0) rotate("+M.rot.toFixed(2)+"deg) scale("+M.scale.toFixed(3)+")",i.style.transform="translate3d("+(M.ax*u).toFixed(2)+"px,"+(M.ay*u).toFixed(2)+"px,0) rotate("+M.ar.toFixed(2)+"deg) scale("+M.asc.toFixed(3)+")",i.style.opacity=M.afade.toFixed(3),r.style.transform="translate3d("+(M.bx*u).toFixed(2)+"px,"+(M.by*u).toFixed(2)+"px,0) rotate("+M.br.toFixed(2)+"deg) scale("+M.bsc.toFixed(3)+")",r.style.opacity=M.bfade.toFixed(3),s.style.transform="scale("+M.hsc.toFixed(3)+")",s.style.opacity=(.09*M.hfade).toFixed(3),o.style.transform="translateX("+R.toFixed(2)+"px) scaleX("+(.75+.4*Math.abs(M.x)).toFixed(3)+")",o.style.opacity=(M.shd*.5).toFixed(3)}let p=0,g=0,m=0,v=!1,E=!1,S=!1,_=0;function b(){return S||a.matches||document.hidden||!e.offsetParent?!1:E}function k(M){if(!v)return;if(m=requestAnimationFrame(k),!b()){x();return}const R=g?(M-g)/1e3:0;g=M,p=(p+Math.min(R,.1))%l,_+=1,h(Ai(p))}function T(){v||S||b()&&(v=!0,g=0,m=requestAnimationFrame(k))}function x(){v=!1,m&&(cancelAnimationFrame(m),m=0),g=0}function F(){b()?T():x()}function $(){a.matches?(x(),h(Ai(0))):F()}function O(){f(),v&&h(Ai(p))}function L(){g=0,F()}const N=new IntersectionObserver(M=>{E=M[0]?M[0].isIntersecting:!1,F()},{threshold:0});N.observe(e),window.addEventListener("resize",O),a.addEventListener("change",$),document.addEventListener("visibilitychange",L);function K(){S||(S=!0,x(),N.disconnect(),window.removeEventListener("resize",O),a.removeEventListener("change",$),document.removeEventListener("visibilitychange",L))}window.addEventListener("pagehide",K);function V(M){p=(M%l+l)%l,h(Ai(p))}return f(),h(Ai(0)),F(),{isRunning:()=>v,currentTime:()=>p,frameCount:()=>_,seek:V,dispose:K}}const ly=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function Xt(t){const e=String(t||"").trim().match(ly);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function cy(t,e){if(t.length===0&&e.length===0)return 0;if(t.length===0)return 1;if(e.length===0)return-1;for(let n=0;n0)}function dy(t){const e=Xt(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function kl(t){let e=String(t??"").trim();if((e.startsWith("'")||e.startsWith('"'))&&(e=e.slice(1,-1).trim()),e===""||e==="any"||e==="*")return{min:null,minInclusive:!1,max:null,maxInclusive:!1};if(e.startsWith("^")){const o=e.slice(1).trim();return Xt(o)?{min:o,minInclusive:!0,max:dy(o),maxInclusive:!1}:null}if(Xt(e))return{min:e,minInclusive:!0,max:e,maxInclusive:!0};const n={min:null,minInclusive:!1,max:null,maxInclusive:!1},i=/(>=|<=|>|<)\s*([0-9][0-9A-Za-z.+-]*)/g;let r=!1,s;for(;(s=i.exec(e))!==null;){const[,o,a]=s;if(!Xt(a))return null;r=!0,o===">="||o===">"?(n.min=a,n.minInclusive=o===">="):(n.max=a,n.maxInclusive=o==="<=")}return r?n:null}function qu(t,e){const n=kl(t);if(!n||!Xt(e))return!1;if(n.min!==null){const i=fs(e,n.min);if(i<0||i===0&&!n.minInclusive)return!1}if(n.max!==null){const i=fs(e,n.max);if(i>0||i===0&&!n.maxInclusive)return!1}return!0}function fy(t,e){const n=kl(t);if(!n||!Xt(e))return!1;if(n.max===null)return!0;const i=fs(n.max,e);return i>0?!0:i===0&&n.maxInclusive}function qn(t){const e=kl(t);return e?e.min:null}const hy="https://pub.dev/api/packages/",py=8e3;function gy(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null}=e,r=Array.isArray(t?.versions)?t.versions:[];let s=null;for(const o of r){const a=o?.version;if(!a||o.retracted||uy(a))continue;const l=o.pubspec?.environment||{};n&&l.sdk&&!qu(l.sdk,n)||i&&l.flutter&&!qu(l.flutter,i)||(!s||fs(a,s)>0)&&(s=a)}return s?{version:s,constraint:`^${s}`}:null}async function my(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null,fetchImpl:r=fetch}=e;let s;try{const a=await r(`${hy}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(py)});if(!a.ok)return{name:t,constraint:null,version:null,error:a.status===404?`"${t}" was not found on pub.dev`:`pub.dev returned ${a.status} for "${t}"`};s=await a.json()}catch(a){return{name:t,constraint:null,version:null,error:`could not reach pub.dev for "${t}" (${a.message})`}}const o=gy(s,{dartSdkFloor:n,flutterSdkFloor:i});return o?{name:t,...o,error:null}:{name:t,constraint:null,version:null,error:n?`no published "${t}" release supports Dart ${n}`:`no published "${t}" release could be read`}}async function vy(t,e={}){const n=await Promise.all(t.map(i=>my(i,e)));return new Map(n.map(({name:i,...r})=>[i,r]))}async function _y(t,e={},n={}){const{resolveVersions:i=vy}=n,r=Object.entries(e).filter(([c])=>c&&c!=="flutter"),s=_h(t),o={dartSdkFloor:qn(s.sdk),flutterSdkFloor:qn(s.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(r.length===0)return a;const l=$s(t),u=[];for(const[c,d]of r){const f=l.get(c);if(!f){u.push(c);continue}const h=qn(d);if(!h){a.kept.push({name:c,constraint:f.constraint});continue}if(!f.isScalar){a.warnings.push(`"${c}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${h}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:c,constraint:f.constraint});continue}if(fy(f.constraint,h)){a.kept.push({name:c,constraint:f.constraint});continue}a.overrides[c]=`^${h}`,a.warnings.push(`"${c}" was pinned to ${f.constraint} in your project, which cannot resolve the ${h} the generated code needs. Raising it to ^${h} — this changes a dependency the rest of your app also uses.`)}if(u.length>0){const c=await i(u,o);for(const d of u){const f=c.get(d);if(f?.constraint){a.additions[d]=f.constraint;continue}const h=e[d]||"";if(qn(h)){a.additions[d]=`^${qn(h)}`,a.warnings.push(`Could not confirm "${d}" version on pub.dev (${f?.error||"lookup failed"}). Using ^${qn(h)} from the AI's recommendation — verify this is current.`);continue}a.additions[d]=">=0.0.0",a.warnings.push(`Could not determine a version for "${d}" (${f?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const yy={"&":"&","<":"<",">":">",'"':""","'":"'"};function Qt(t){return String(t??"").replace(/[&<>"']/g,e=>yy[e])}function z(t){return t?Qt(t).replace(/\n/g,"
      "):""}function Jt(t){return Qt(t).replace(/\r?\n/g," ")}function Ms(t,e={}){const n=t?.pipelineStep;if(n!=null&&e[n]!=null)return e[n];const i=t?.message||"";return i.includes("Code Generator")?2:i.includes("Code Review")?3:1}function kh(t){if(!t)return{kind:"generic",title:"Generation failed",message:"An unknown error occurred. Please try again.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1};if(t.isModelArmor){const n=t.code==="MODEL_ARMOR_BLOCKED";return{kind:"safety",title:t.userTitle||"Request blocked for safety",message:t.userMessage||t.message,detail:t.retryExplanation||"",canRetry:!n,canEdit:!0,canUpgrade:!1}}if(t.isUsageLimit)return{kind:"quota",title:"Monthly limit reached",message:t.message||"You've used all your generations for this period.",detail:"",canRetry:!1,canEdit:!1,canUpgrade:!0};const e=t.message||"";return/timed out after/i.test(e)?{kind:"timeout",title:"Request timed out",message:"The generation service took too long to respond.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:/unreachable|failed to fetch|load failed|cors/i.test(e)?{kind:"network",title:"Connection problem",message:"We couldn't reach the generation service. Check your connection and try again.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:{kind:"generic",title:"Generation failed",message:e||"An unexpected error occurred.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1}}function wy(t){const e={"Integration Audit Report":"📋","Critical Issues":"❌",Warnings:"⚠️",Recommendations:"✅","Overall Score":"📊"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📄"}function by(t){const e={critical:"❌",warning:"⚠️",recommendation:"✅",score:"📊",issue:"🔍",fix:"🔧"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📝"}function Ey(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 li(t){if(!t)return"";if(typeof t!="string")return String(t);const e=/```(?:\w+)?\n?([\s\S]*?)```/,n=t.match(e);return n?n[1].trim():t.trim()}function Vu(t){return t=Qt(t),t=t.replace(/\*\*(.*?)\*\*/g,'$1'),t=t.replace(/\*(.*?)\*/g,'$1'),t=t.replace(/`(.*?)`/g,'$1'),t=t.replace(/\b(FAIL|ERROR|CRITICAL)\b/g,'$1'),t=t.replace(/\b(WARN|WARNING)\b/g,'$1'),t=t.replace(/\b(PASS|SUCCESS|OK)\b/g,'$1'),t}function Ch(t,e="dart",n=globalThis.hljs){if(!t)return"";const i=li(t);try{return n.highlight(i,{language:e}).value}catch(r){console.warn("Syntax highlighting failed:",r);try{return n.highlight(i,{language:"json"}).value}catch{return Qt(i)}}}function Ls(t,e={}){const{highlighter:n=globalThis.hljs}=e;let i='
      ';const r=String(t??"").split(` +`)}let l=null,u,c,d,f,h,p,g,m,v;function E(Y,W){if(!i)return null;const D=i.createShader(Y);return i.shaderSource(D,W),i.compileShader(D),i.getShaderParameter(D,i.COMPILE_STATUS)?D:(window.console&&console.warn("fx-grid shader: "+i.getShaderInfoLog(D)),null)}if(i){const Y=E(i.VERTEX_SHADER,o),W=E(i.FRAGMENT_SHADER,a());if(Y&&W&&(l=i.createProgram(),i.attachShader(l,Y),i.attachShader(l,W),i.linkProgram(l),i.getProgramParameter(l,i.LINK_STATUS)||(window.console&&console.warn("fx-grid link: "+i.getProgramInfoLog(l)),l=null)),l){i.useProgram(l),i.bindBuffer(i.ARRAY_BUFFER,i.createBuffer()),i.bufferData(i.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),i.STATIC_DRAW);const D=i.getAttribLocation(l,"p");i.enableVertexAttribArray(D),i.vertexAttribPointer(D,2,i.FLOAT,!1,0,0),u=i.getUniformLocation(l,"res"),c=i.getUniformLocation(l,"design"),d=i.getUniformLocation(l,"mouse"),f=i.getUniformLocation(l,"energy"),h=i.getUniformLocation(l,"parallax"),p=i.getUniformLocation(l,"t"),g=i.getUniformLocation(l,"ink"),m=i.getUniformLocation(l,"mark"),v=i.getUniformLocation(l,"rot"),i.enable(i.BLEND),i.blendFunc(i.ONE,i.ONE_MINUS_SRC_ALPHA),i.clearColor(0,0,0,0)}else{i=null;const D=t.cloneNode(!1);if(t.parentNode.replaceChild(D,t),t=D,r=t.getContext("2d"),!r)return null}}function S(Y){if(!Y)return null;const W=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(Y);if(W){let D=W[1];return D.length===3&&(D=D[0]+D[0]+D[1]+D[1]+D[2]+D[2]),[parseInt(D.slice(0,2),16)/255,parseInt(D.slice(2,4),16)/255,parseInt(D.slice(4,6),16)/255]}try{const D=document.createElement("canvas");D.width=1,D.height=1;const ue=D.getContext("2d");ue.fillStyle="rgb(9, 8, 7)";const xe=String(ue.fillStyle);ue.fillStyle=Y;const Fe=String(ue.fillStyle);if(Fe===xe)return null;const dt=/^#([0-9a-f]{6})$/i.exec(Fe);if(dt){const ft=dt[1];return[parseInt(ft.slice(0,2),16)/255,parseInt(ft.slice(2,4),16)/255,parseInt(ft.slice(4,6),16)/255]}const Nt=/rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i.exec(Fe);if(Nt)return[Number(Nt[1])/255,Number(Nt[2])/255,Number(Nt[3])/255]}catch{}return null}function _(){let Y="";try{const W=getComputedStyle(document.documentElement);Y=(W.getPropertyValue("--fx-ink")||"").trim()||(W.getPropertyValue("--fg")||"").trim()}catch{}return S(Y)||[.56,.68,.88]}const b=_();let k=1920,T=1080,x=960,F=540,$=960,O=540,L=.66,N=0,K=-1e9,V=!1,M=0,R=0,Z=null,Ce=!1,oe=!1,ye=!1;const $e=64,ae=15.2;let Ie=0,Se=0;const De=.0032,wt=0,ge=.56,Je=.26,bt=.32,mn=.16,Re=.349;let Pe=wt;function $t(){const Y=t.getBoundingClientRect(),W=t.clientWidth,D=t.clientHeight;if(!Y.width||!W||!D)return;const ue=Math.min(window.devicePixelRatio||1,2),xe=Math.max(.2,Math.min(2,Y.width/W*ue)),Fe=Math.max(2,Math.round(W*xe)),dt=Math.max(2,Math.round(D*xe));(Fe!==t.width||dt!==t.height)&&(t.width=Fe,t.height=dt,i&&i.viewport(0,0,Fe,dt)),k=W,T=D,V||(x=$=k/2,F=O=T/2,V=!0)}function Dn(Y){!l||!Ce||!i||(i.uniform2f(u,t.width,t.height),i.uniform2f(c,k,T),i.uniform2f(d,x,F),i.uniform1f(f,L),i.uniform1f(h,N),i.uniform2f(v,Math.cos(Pe),Math.sin(Pe)),i.uniform1f(p,Y),i.uniform3f(g,b[0],b[1],b[2]),i.clear(i.COLOR_BUFFER_BIT),i.drawArrays(i.TRIANGLES,0,3))}function qe(Y,W,D){const ue=Math.max(0,Math.min(1,(D-Y)/(W-Y)));return ue*ue*(3-2*ue)}function jn(Y){if(!Z||!r)return;const W=r;W.setTransform(1,0,0,1,0,0),W.clearRect(0,0,t.width,t.height);const D=t.width/k;W.setTransform(D,0,0,D,0,0),W.globalAlpha=1;const ue=Math.min(k,T),xe=Math.max(64,Math.min(118,ue/10)),Fe=xe*2.9,dt=2*Fe*Fe,Nt=Math.sin(Y*.11)*7,ft=Math.cos(Y*.09)*7-N,dr=x+Nt,fr=F+ft,no=Fe*Math.sqrt(2*Math.log(1/.06)),vi=no+De*no*no+xe,Rp=Math.floor((dr-vi)/xe)-1,Tp=Math.ceil((dr+vi)/xe)+1,$p=Math.floor((fr-vi)/xe)-1,Mp=Math.ceil((fr+vi)/xe)+1;for(let io=$p;io<=Mp;io++){const Lp=(io+.5)*xe;for(let ro=Rp;ro<=Tp;ro++){const so=(ro+.5)*xe-dr,oo=Lp-fr,ao=Math.sqrt(so*so+oo*oo)+1e-5;if(ao>vi)continue;const hr=(-1+Math.sqrt(1+4*De*ao))/(2*De),cc=Math.exp(-(hr*hr)/dt),uc=qe(.06,.8,cc)*L*.26;if(uc<.004)continue;const on=xe/(1+2*De*hr)*.26*(.32+1.1*cc),dc=hr/ao,lo=dr+so*dc,co=fr+oo*dc;lo<-on*1.6||lo>k+on*1.6||co<-on*1.6||co>T+on*1.6||(W.globalAlpha=uc,W.save(),W.translate(lo,co),W.rotate(Pe),W.drawImage(Z,-on,-on,on*2,on*2),W.restore())}}W.globalAlpha=1}function Mt(Y){if(!oe)return;const W=R?Math.min(.05,(Y-R)/1e3):.016;R=Y;const ue=Y-K>2400?.6:1;L+=(ue-L)*Math.min(1,W*3.2);const xe=Math.min(.05,W);Ie+=(($-x)*$e-Ie*ae)*xe,Se+=((O-F)*$e-Se*ae)*xe,x+=Ie*xe,F+=Se*xe,N=(window.scrollY||window.pageYOffset||0)*.55;const Fe=Y/1e3,dt=x/(k||1)-.5,Nt=F/(T||1)-.5;let ft=dt*(dt>=0?ge:Je)+Nt*(Nt>=0?bt:mn);ft>Re?ft=Re:ft<-Re&&(ft=-Re),Pe=wt+ft-N*6e-4,$t(),i?Dn(Fe):jn(Fe),M=requestAnimationFrame(Mt)}function Lt(Y){if(!oe)return;const W=t.getBoundingClientRect();!W.width||!k||!T||($=(Y.clientX-W.left)/W.width*k,O=(Y.clientY-W.top)/W.height*T,K=performance.now())}function ut(){oe||to||e.matches||n.matches||!ye||document.hidden||(oe=!0,R=0,M=requestAnimationFrame(Mt))}function sn(){oe=!1,M&&(cancelAnimationFrame(M),M=0),R=0}function mi(){e.matches?(sn(),t.classList.remove("is-ready")):ye&&ut()}function Un(){n.matches?sn():ye&&ut()}function oc(){document.hidden?sn():ye&&ut()}const ac=new IntersectionObserver(Y=>{ye=Y[0]?.isIntersecting||!1,ye?ut():sn()},{threshold:0});ac.observe(t),window.addEventListener("pointermove",Lt,{passive:!0,capture:!0}),window.addEventListener("resize",$t),e.addEventListener("change",mi),n.addEventListener("change",Un),document.addEventListener("visibilitychange",oc);function Fp(){const Y=(s.match(/\sd="([^"]+)"/)||[])[1],W=document.createElement("canvas");W.width=256,W.height=256;const D=W.getContext("2d");if(Y&&window.Path2D){const ue=Math.min(8.533333333333333,8.421052631578947);D.setTransform(ue,0,0,ue,ue+(256-30*ue)/2,-6.4*ue),D.fillStyle="rgb(255,255,255)",D.fill(new Path2D(Y),"evenodd"),D.setTransform(1,0,0,1,0,0)}try{const ue=D.getImageData(0,0,256,256),xe=ue.data;for(let Fe=3;Feoe}}const ry=120;function sy(t,e,n){return tn?n:t}function de(t,e,n){return sy((t-e)/(n-e),0,1)}function oy(t){return t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2}function Uo(t){return 1-Math.pow(1-t,3)}function Ve(t,e){return e=e===void 0?1.7:e,1+(e+1)*Math.pow(t-1,3)+e*Math.pow(t-1,2)}function zu(t){return 1-Math.pow(2,-9*t)*Math.cos(t*15)}function te(t,e){if(t<=e[0].t)return e[0].v;for(let n=1;n8.2&&_<9.4&&(s*=1-.07*Math.sin(de(_,8.2,9.4)*Math.PI))}else if(t<53){const _=t-42;g=te(_,[{t:0,v:1},{t:2,v:0},{t:4.2,v:0},{t:4.6,v:1},{t:6.8,v:1},{t:7.4,v:0},{t:9.4,v:0},{t:10.6,v:1}]),p=te(_,[{t:0,v:1},{t:2,v:.3},{t:4.6,v:1,e:Ve}]),d=te(_,[{t:0,v:0},{t:2,v:.3},{t:4.6,v:.16,e:Ve},{t:10.6,v:0}]),h=te(_,[{t:0,v:0},{t:2,v:-40},{t:4.6,v:0,e:Ve}]),o=te(_,[{t:0,v:0},{t:4.6,v:-.12},{t:10.6,v:0}])}else if(t<60){const _=t-53;c=te(_,[{t:0,v:1},{t:.35,v:0},{t:.45,v:0},{t:.7,v:1}]);const b=de(_,.45,2.2);a=b>0?-2.6*(1-zu(b)):0,g=te(_,[{t:0,v:1},{t:.57,v:0},{t:.67,v:0},{t:.92,v:1}]);const k=de(_,.67,2.42);f=k>0?-2.6*(1-zu(k)):0,s=1-.05*(Math.sin(de(_,1.9,2.5)*Math.PI)+Math.sin(de(_,2.5,3.1)*Math.PI))}else if(t<74){let b=function(F){return[te(F,[{t:0,v:0},{t:.25,v:1},{t:.5,v:1},{t:.72,v:.14},{t:.82,v:.14},{t:1,v:0}]),te(F,[{t:0,v:0},{t:.08,v:-.62},{t:.25,v:-.62},{t:.33,v:.62},{t:.7,v:.62},{t:.82,v:-.62},{t:1,v:-.62}])]};var S=b;const _=t-60,k=1-de(_,12,14),T=b(de(_,0,12)),x=b(de(_-.5,0,12));n=T[0]*k,i=(T[1]+.05*Math.sin(_*7))*k,o=(x[0]-T[0])*.6*k,a=(x[1]-T[1])*.6*k,h=(x[0]-T[0])*30*k,E=de(_,0,.4)*k}else if(t<85.4){const _=t-74,b=te(_,[{t:0,v:0},{t:4,v:1},{t:8,v:.24},{t:9.6,v:1,e:Ve},{t:11.4,v:0}]);o=b*.5,d=-b*.5,l=te(_,[{t:0,v:0},{t:4,v:6},{t:8,v:20},{t:9.6,v:38,e:Ve},{t:11.4,v:0}]),h=-l*.7,a=te(_,[{t:0,v:0},{t:8,v:0},{t:9.6,v:.4},{t:11.4,v:0}])}else if(t<96.4){const _=t-85.4,b=de(_,0,5.6),k=de(_,5.6,7.6),T=.72*Math.min(1,_/.6)*(1-k);d=Math.cos(b*Math.PI*2)*T,f=Math.sin(b*Math.PI*2)*T*.55,h=b*360*(1-k);const x=te(_,[{t:0,v:0},{t:7.6,v:0},{t:8.2,v:1,e:Uo},{t:8.6,v:.55},{t:9.4,v:0}]);o=-.16*x,d+=.16*x,l=-6*x,h+=6*x,s=1+.05*x,m=1+.9*x}else if(t<108.6){const _=t-96.4,b=de(_,9.6,12.2);n=te(_,[{t:0,v:0},{t:2.1,v:1},{t:4.8,v:.08},{t:7.5,v:1},{t:9.6,v:0}])*(1-b),i=-.35*Math.abs(Math.sin(de(_,0,9.6)*Math.PI*3))*(1-b);const k=Math.sin(_*6.2)*(1-b);u=1+.12*k,p=1-.12*k,l=k*8,h=-k*8,o=.06*k,d=-.06*k,E=de(_,0,.4)*(1-b)}else{const _=t-108.6,b=Math.sin(de(_,0,8)*Math.PI),k=1-de(_,8,11.4);s=1+.04*b*k,i=-.1*b*k,r=2*b*k,m=1+.5*Math.sin(de(_,0,6)*Math.PI),v=1+.1*Math.sin(de(_,0,6)*Math.PI)}return e.x=n,e.y=i,e.rot=r,e.scale=s,e.ax=o,e.ay=a,e.ar=l,e.asc=u,e.afade=c,e.bx=d,e.by=f,e.br=h,e.bsc=p,e.bfade=g,e.hfade=m,e.hsc=v,e.shd=E,e}function ay(t={}){const e=t.arena||document.querySelector(".pipeline-glyph.logo-loop");if(!e)return null;const n=e.querySelector(".loop-mark"),i=e.querySelector(".loop-piece-a"),r=e.querySelector(".loop-piece-b"),s=e.querySelector(".loop-halo"),o=e.querySelector(".loop-shadow");if(!n||!i||!r||!s||!o)return null;const a=t.reducedMotion||window.matchMedia("(prefers-reduced-motion: reduce)"),l=ry;let u=34,c=0,d=0;function f(){u=n.offsetWidth||34,c=Math.max(0,e.offsetWidth-u-4),d=Math.max(0,(e.offsetHeight-u)/2-2),e.style.setProperty("--mark-c",u/2+"px")}function h(M){const R=Math.min(1,Math.max(0,M.x))*c,Z=M.y*d;n.style.transform="translate3d("+R.toFixed(2)+"px,"+Z.toFixed(2)+"px,0) rotate("+M.rot.toFixed(2)+"deg) scale("+M.scale.toFixed(3)+")",i.style.transform="translate3d("+(M.ax*u).toFixed(2)+"px,"+(M.ay*u).toFixed(2)+"px,0) rotate("+M.ar.toFixed(2)+"deg) scale("+M.asc.toFixed(3)+")",i.style.opacity=M.afade.toFixed(3),r.style.transform="translate3d("+(M.bx*u).toFixed(2)+"px,"+(M.by*u).toFixed(2)+"px,0) rotate("+M.br.toFixed(2)+"deg) scale("+M.bsc.toFixed(3)+")",r.style.opacity=M.bfade.toFixed(3),s.style.transform="scale("+M.hsc.toFixed(3)+")",s.style.opacity=(.09*M.hfade).toFixed(3),o.style.transform="translateX("+R.toFixed(2)+"px) scaleX("+(.75+.4*Math.abs(M.x)).toFixed(3)+")",o.style.opacity=(M.shd*.5).toFixed(3)}let p=0,g=0,m=0,v=!1,E=!1,S=!1,_=0;function b(){return S||a.matches||document.hidden||!e.offsetParent?!1:E}function k(M){if(!v)return;if(m=requestAnimationFrame(k),!b()){x();return}const R=g?(M-g)/1e3:0;g=M,p=(p+Math.min(R,.1))%l,_+=1,h(Pi(p))}function T(){v||S||b()&&(v=!0,g=0,m=requestAnimationFrame(k))}function x(){v=!1,m&&(cancelAnimationFrame(m),m=0),g=0}function F(){b()?T():x()}function $(){a.matches?(x(),h(Pi(0))):F()}function O(){f(),v&&h(Pi(p))}function L(){g=0,F()}const N=new IntersectionObserver(M=>{E=M[0]?M[0].isIntersecting:!1,F()},{threshold:0});N.observe(e),window.addEventListener("resize",O),a.addEventListener("change",$),document.addEventListener("visibilitychange",L);function K(){S||(S=!0,x(),N.disconnect(),window.removeEventListener("resize",O),a.removeEventListener("change",$),document.removeEventListener("visibilitychange",L))}window.addEventListener("pagehide",K);function V(M){p=(M%l+l)%l,h(Pi(p))}return f(),h(Pi(0)),F(),{isRunning:()=>v,currentTime:()=>p,frameCount:()=>_,seek:V,dispose:K}}const ly=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function Xt(t){const e=String(t||"").trim().match(ly);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function cy(t,e){if(t.length===0&&e.length===0)return 0;if(t.length===0)return 1;if(e.length===0)return-1;for(let n=0;n0)}function dy(t){const e=Xt(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function kl(t){let e=String(t??"").trim();if((e.startsWith("'")||e.startsWith('"'))&&(e=e.slice(1,-1).trim()),e===""||e==="any"||e==="*")return{min:null,minInclusive:!1,max:null,maxInclusive:!1};if(e.startsWith("^")){const o=e.slice(1).trim();return Xt(o)?{min:o,minInclusive:!0,max:dy(o),maxInclusive:!1}:null}if(Xt(e))return{min:e,minInclusive:!0,max:e,maxInclusive:!0};const n={min:null,minInclusive:!1,max:null,maxInclusive:!1},i=/(>=|<=|>|<)\s*([0-9][0-9A-Za-z.+-]*)/g;let r=!1,s;for(;(s=i.exec(e))!==null;){const[,o,a]=s;if(!Xt(a))return null;r=!0,o===">="||o===">"?(n.min=a,n.minInclusive=o===">="):(n.max=a,n.maxInclusive=o==="<=")}return r?n:null}function qu(t,e){const n=kl(t);if(!n||!Xt(e))return!1;if(n.min!==null){const i=fs(e,n.min);if(i<0||i===0&&!n.minInclusive)return!1}if(n.max!==null){const i=fs(e,n.max);if(i>0||i===0&&!n.maxInclusive)return!1}return!0}function fy(t,e){const n=kl(t);if(!n||!Xt(e))return!1;if(n.max===null)return!0;const i=fs(n.max,e);return i>0?!0:i===0&&n.maxInclusive}function Vn(t){const e=kl(t);return e?e.min:null}const hy="https://pub.dev/api/packages/",py=8e3;function gy(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null}=e,r=Array.isArray(t?.versions)?t.versions:[];let s=null;for(const o of r){const a=o?.version;if(!a||o.retracted||uy(a))continue;const l=o.pubspec?.environment||{};n&&l.sdk&&!qu(l.sdk,n)||i&&l.flutter&&!qu(l.flutter,i)||(!s||fs(a,s)>0)&&(s=a)}return s?{version:s,constraint:`^${s}`}:null}async function my(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null,fetchImpl:r=fetch}=e;let s;try{const a=await r(`${hy}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(py)});if(!a.ok)return{name:t,constraint:null,version:null,error:a.status===404?`"${t}" was not found on pub.dev`:`pub.dev returned ${a.status} for "${t}"`};s=await a.json()}catch(a){return{name:t,constraint:null,version:null,error:`could not reach pub.dev for "${t}" (${a.message})`}}const o=gy(s,{dartSdkFloor:n,flutterSdkFloor:i});return o?{name:t,...o,error:null}:{name:t,constraint:null,version:null,error:n?`no published "${t}" release supports Dart ${n}`:`no published "${t}" release could be read`}}async function vy(t,e={}){const n=await Promise.all(t.map(i=>my(i,e)));return new Map(n.map(({name:i,...r})=>[i,r]))}async function _y(t,e={},n={}){const{resolveVersions:i=vy}=n,r=Object.entries(e).filter(([c])=>c&&c!=="flutter"),s=_h(t),o={dartSdkFloor:Vn(s.sdk),flutterSdkFloor:Vn(s.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(r.length===0)return a;const l=$s(t),u=[];for(const[c,d]of r){const f=l.get(c);if(!f){u.push(c);continue}const h=Vn(d);if(!h){a.kept.push({name:c,constraint:f.constraint});continue}if(!f.isScalar){a.warnings.push(`"${c}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${h}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:c,constraint:f.constraint});continue}if(fy(f.constraint,h)){a.kept.push({name:c,constraint:f.constraint});continue}a.overrides[c]=`^${h}`,a.warnings.push(`"${c}" was pinned to ${f.constraint} in your project, which cannot resolve the ${h} the generated code needs. Raising it to ^${h} — this changes a dependency the rest of your app also uses.`)}if(u.length>0){const c=await i(u,o);for(const d of u){const f=c.get(d);if(f?.constraint){a.additions[d]=f.constraint;continue}const h=e[d]||"";if(Vn(h)){a.additions[d]=`^${Vn(h)}`,a.warnings.push(`Could not confirm "${d}" version on pub.dev (${f?.error||"lookup failed"}). Using ^${Vn(h)} from the AI's recommendation — verify this is current.`);continue}a.additions[d]=">=0.0.0",a.warnings.push(`Could not determine a version for "${d}" (${f?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const yy={"&":"&","<":"<",">":">",'"':""","'":"'"};function Qt(t){return String(t??"").replace(/[&<>"']/g,e=>yy[e])}function z(t){return t?Qt(t).replace(/\n/g,"
      "):""}function Jt(t){return Qt(t).replace(/\r?\n/g," ")}function Ms(t,e={}){const n=t?.pipelineStep;if(n!=null&&e[n]!=null)return e[n];const i=t?.message||"";return i.includes("Code Generator")?2:i.includes("Code Review")?3:1}function kh(t){if(!t)return{kind:"generic",title:"Generation failed",message:"An unknown error occurred. Please try again.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1};if(t.isModelArmor){const n=t.code==="MODEL_ARMOR_BLOCKED";return{kind:"safety",title:t.userTitle||"Request blocked for safety",message:t.userMessage||t.message,detail:t.retryExplanation||"",canRetry:!n,canEdit:!0,canUpgrade:!1}}if(t.isUsageLimit)return{kind:"quota",title:"Monthly limit reached",message:t.message||"You've used all your generations for this period.",detail:"",canRetry:!1,canEdit:!1,canUpgrade:!0};const e=t.message||"";return/timed out after/i.test(e)?{kind:"timeout",title:"Request timed out",message:"The generation service took too long to respond.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:/unreachable|failed to fetch|load failed|cors/i.test(e)?{kind:"network",title:"Connection problem",message:"We couldn't reach the generation service. Check your connection and try again.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:{kind:"generic",title:"Generation failed",message:e||"An unexpected error occurred.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1}}function wy(t){const e={"Integration Audit Report":"📋","Critical Issues":"❌",Warnings:"⚠️",Recommendations:"✅","Overall Score":"📊"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📄"}function by(t){const e={critical:"❌",warning:"⚠️",recommendation:"✅",score:"📊",issue:"🔍",fix:"🔧"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📝"}function Ey(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 ci(t){if(!t)return"";if(typeof t!="string")return String(t);const e=/```(?:\w+)?\n?([\s\S]*?)```/,n=t.match(e);return n?n[1].trim():t.trim()}function Vu(t){return t=Qt(t),t=t.replace(/\*\*(.*?)\*\*/g,'$1'),t=t.replace(/\*(.*?)\*/g,'$1'),t=t.replace(/`(.*?)`/g,'$1'),t=t.replace(/\b(FAIL|ERROR|CRITICAL)\b/g,'$1'),t=t.replace(/\b(WARN|WARNING)\b/g,'$1'),t=t.replace(/\b(PASS|SUCCESS|OK)\b/g,'$1'),t}function Ch(t,e="dart",n=globalThis.hljs){if(!t)return"";const i=ci(t);try{return n.highlight(i,{language:e}).value}catch(r){console.warn("Syntax highlighting failed:",r);try{return n.highlight(i,{language:"json"}).value}catch{return Qt(i)}}}function Ls(t,e={}){const{highlighter:n=globalThis.hljs}=e;let i='
      ';const r=String(t??"").split(` `);let s=!1,o="";for(const a of r){if(a.startsWith("```")){if(s){const l=Ey(o),u=Ch(o.trim(),l,n);i+=`
      ${u}
      `,o="",s=!1}else s=!0;continue}if(s){o+=a+` @@ -78,13 +78,13 @@ in vec2 p; void main(){ gl_Position = vec4(p, 0.0, 1.0); }`;function a(){return[
      ${i}
      - `}const Sy=[[/gradient stroke\s*$/i," and an animated percentage label"],[/gauge\s*$/i," with a gradient stroke and animated fill"],[/rating\s*(bar|widget)?\s*$/i," with half-star support and haptic feedback"],[/list\s*$/i," with swipe-to-delete and an undo snackbar"],[/pad\s*$/i," that exports a transparent PNG"],[/carousel\s*$/i," with parallax cards and page indicators"],[/(button|cta)\s*$/i," with a loading spinner and success state"],[/(chart|graph)\s*$/i," that animates from a Firestore stream"],[/action\s*(that|to)?\s*$/i," uploads an image to Firebase Storage and returns the URL"],[/timer\s*$/i," with pause, resume and a completion callback"],[/map\s*$/i," with clustered markers and a custom info window"],[/^a\s+\w*$/i," widget that"],[/(picker|selector)\s*$/i," with search and multi-select"]],xy=220,Iy=6;function Gu(t,e){return!!(t&&t.trim())&&!e}function ky(t,e=""){if(typeof t!="string"||!t||t===e||t.trim().lengthi.test(t));return n?n[1]:null}function Cy(){let t="",e="";return{get active(){return t},resolve(n){return t=ky(n,e)??"",t},dismiss(){t=""},accept(n){if(!t)return null;const i=n+t;return e=i,t="",i}}}function Ay({onSubmit:t}){const e=document.getElementById("composer"),n=document.getElementById("pipeline-input"),i=document.getElementById("hero-send");if(!e||!n||!i||typeof t!="function")return;const r=e.querySelector(".ghost .typed"),s=e.querySelector(".ghost .suggest"),o=document.getElementById("tab-hint"),a=document.getElementById("suggest-status"),l=Array.from(document.querySelectorAll("#example-chips .chip")),u=document.getElementById("btn-add-images"),c=document.getElementById("prompt-image-input"),d=window.matchMedia("(prefers-reduced-motion: reduce)"),f=Cy();let h=!1,p=!1,g=!1,m=!1,v=null,E=null;function S(){i.disabled=!Gu(n.value,p||g||m)}function _(){r&&(r.textContent=n.value)}function b(){s&&(s.textContent=""),_(),e.classList.remove("has-suggest"),o&&(o.hidden=!0,o.tabIndex=-1),a&&(a.textContent="")}function k(R){s&&(s.textContent=R),_(),e.classList.add("has-suggest"),o&&(o.hidden=!1,o.tabIndex=0,o.setAttribute("aria-label","Accept suggestion: "+R.trim())),a&&(a.textContent="Suggestion: "+R+". Press Tab to accept.")}function T(){f.dismiss(),b()}function x(){if(h||p)return;const R=f.resolve(n.value);R&&k(R)}function F(){clearTimeout(v),!h&&(v=setTimeout(x,xy))}function $(){const R=f.accept(n.value);return R===null?!1:(n.value=R,b(),S(),!0)}function O(R){p=R,e.classList.toggle("is-busy",R),i.classList.toggle("is-busy",R),i.setAttribute("aria-label",R?"Generating":"Generate"),n.readOnly=R,l.forEach(Z=>{Z.disabled=R}),u&&(u.disabled=R),c&&(c.disabled=R),S()}async function L(){if(Gu(n.value,p||g||m)){T(),O(!0);try{await t()}finally{O(!1)}}}function N(){g=!1,E&&(clearInterval(E),E=null),e.classList.remove("is-demo-typing"),S()}function K(){l.forEach(R=>{R.classList.remove("is-active"),R.setAttribute("aria-pressed","false")})}function V(){try{n.focus({preventScroll:!0}),n.setSelectionRange(n.value.length,n.value.length)}catch{}}function M(R){const Z=R.dataset.prompt||"";if(N(),clearTimeout(v),v=null,T(),l.forEach(oe=>{const ye=oe===R;oe.classList.toggle("is-active",ye),oe.setAttribute("aria-pressed",String(ye))}),d.matches||!Z){n.value=Z,_(),S(),V();return}n.value="",_(),g=!0,S(),e.classList.add("is-demo-typing");let Ce=0;E=setInterval(()=>{Ce+=1,n.value=Z.slice(0,Ce),_(),Ce>=Z.length?(N(),V()):S()},22)}return l.forEach(R=>{R.setAttribute("aria-pressed","false"),R.addEventListener("click",()=>M(R))}),n.addEventListener("keydown",R=>{if(g&&R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!h){R.preventDefault();return}N(),R.key==="Tab"&&!R.shiftKey&&f.active?(R.preventDefault(),$()):R.key==="Escape"?(clearTimeout(v),v=null,T()):R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!h&&(R.preventDefault(),L())}),n.addEventListener("input",()=>{N(),K(),T(),S(),F()}),n.addEventListener("compositionstart",()=>{h=!0}),n.addEventListener("compositionend",()=>{h=!1,T(),S(),F()}),n.addEventListener("scroll",()=>{r&&r.parentNode&&(r.parentNode.scrollTop=n.scrollTop)}),o&&o.addEventListener("click",()=>{$(),n.focus({preventScroll:!0})}),i.addEventListener("click",L),n.addEventListener("pointerdown",()=>{N(),K()}),_(),S(),{setAttachmentsPending(R){m=!!R,S()}}}const Py="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses";const _t="https://4tgke4.buildship.run",Ah={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},hs="ccc_auth_session",Na="ccc_signin_return",Fy=1800*1e3,Ku=new WeakSet;let q={email:null,sessionToken:null,isVerified:!1};function Mn(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let ce=Mn({isResolved:!0}),Oa=Promise.resolve();const Ry=`${_t}/service/runpipeline`,Ty="bs_user_id",$y="bs_identity_token",My=`${_t}/authUserCheck`;let ht={userId:null,token:null,status:null,resolved:!1};const ps=dv,gs="ccc_subscription",Yu=3,Ly=new Set(["active","trialing","paid"]),ms="google/gemini-3.7-flash",Nr=["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"],Ny={"google/gemini-3.7-flash":"Gemini 3.7 Flash","anthropic/claude-opus-5":"Claude Opus 5","openai/gpt-5.6-sol":"GPT-5.6 Sol","z-ai/glm-5.2":"GLM 5.2","moonshotai/kimi-k3":"Kimi K3","openrouter/auto-beta":"OpenRouter: Auto Router","openrouter/free":"OpenRouter: Free Models","openrouter/deepseek/deepseek-v4-pro":"DeepSeek v4 Pro"};function Gt(t){return Ny[t]||t}const Oy=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 Ph(t){return Oy.has(t)}const Ba=4,Ho=8*1024*1024,By="https://4tgke4.buildship.run/service/runpipeline-image";let Oe=[];const pn=[],Dy=3e4;let Fh=null;function jy(t){return new Promise(e=>{const n=new FileReader;n.onload=()=>e(n.result),n.onerror=()=>e(null),n.readAsDataURL(t)})}async function Uy(t,e){const n=new FormData;return n.append("file",t),(await fetch(By,{method:"POST",body:n,signal:e})).json()}function Hy(t){if(Array.isArray(t)){const e=t[0];if(e&&typeof e=="object")for(const n of Object.keys(e)){if(n==="item"||n==="index")continue;const i=e[n];if(i&&typeof i=="object"){if(typeof i.file=="string")return i.file;if(typeof i.url=="string")return i.url}if(typeof i=="string")return i}return""}return typeof t=="string"?t:t&&typeof t=="object"&&(t.url||t.fileUrl||t.file_url||t.downloadUrl||t.imageUrl||t.image_url||t.file)||""}async function Wy(t,e,n){const i=await jy(t);i&&Oe.includes(e)&&(e.dataUrl=i,cn());let r="";if(i)try{r=Hy(await Uy(t,n))}catch{r=""}return Oe.includes(e)?!i||!r?(Oe.splice(Oe.indexOf(e),1),cn(),"failed"):(e.url=r,cn(),"added"):"dropped"}function Rh(t){const e=pn.indexOf(t);e>=0&&pn.splice(e,1),$h()}function Th(t){t.controller.abort(),Rh(t);const e=Oe.indexOf(t.slot);e>=0&&(Oe.splice(e,1),cn())}function $h(){Fh?.setAttachmentsPending(pn.length>0)}async function zy(t){const e=Array.from(t.target.files||[]);if(!e.length)return;if(t.target.value="",y.isRunning){Ee("Wait for the current generation to finish before attaching images.","info");return}const n=e.filter(u=>u.size>Ho);n.length&&Ee(`Skipped ${n.length} image(s) over the ${(Ho/1024/1024).toFixed(0)} MB limit.`,"warning");const i=e.filter(u=>u.size<=Ho);if(!i.length)return;const r=Ba-Oe.length,s=i.slice(0,r);if(i.length>r&&Ee(`You can attach up to ${Ba} images.`,"info"),!s.length)return;const o=s.map(u=>{const c={dataUrl:null,name:u.name,url:null};Oe.push(c);const d={slot:c,controller:new AbortController},f=setTimeout(()=>d.controller.abort(),Dy);return d.job=Wy(u,c,d.controller.signal),pn.push(d),d.job.finally(()=>{clearTimeout(f),Rh(d)}),d.job});cn(),$h();const l=(await Promise.all(o)).filter(u=>u==="failed").length;l&&Ee(`${l} image(s) could not be uploaded and were not attached.`,"error")}function qy(t){const e=Oe[t],n=pn.find(i=>i.slot===e);if(n){Th(n);return}Oe.splice(t,1),cn()}function cn(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",Oe.forEach((n,i)=>{const r=document.createElement("div");r.className="prompt-img-thumb"+(n.url?"":" is-pending"),r.innerHTML=(n.dataUrl?`Prompt image`:"")+``,t.appendChild(r)}),e&&(e.textContent=Oe.length>=Ba?"Image limit reached":"Add images"))}function Cl(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),n=Ph(e?.value);t.classList.toggle("hidden",!n),!n&&Oe.length&&(pn.slice().forEach(Th),Oe=[],cn())}const Fn="ccc_usage",Mh="google/gemini-3.7-flash",Lh="google/gemini-3.7-flash",kr="google/gemini-3.7-flash",Ni={professional:11,power:49},Da={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"},Or={AUD:1,USD:.65,EUR:.6,GBP:.52,CAD:.88,NZD:1.08,JPY:97,KRW:870,INR:54,SGD:.87,HKD:5.08,BRL:3.18,CNY:4.7,TWD:20.5,THB:22.5,VND:16200,IDR:10200,MYR:2.88,SEK:6.8,NOK:6.95,DKK:4.48,PLN:2.6,CZK:15.2,HUF:238,RON:2.98,TRY:20.9,AED:2.39,ILS:2.38,PHP:36.4,ZAR:11.8,RUB:58,UAH:26.8,CHF:.57,MXN:11.1,ARS:580,CLP:610,COP:2700,PEN:2.44};let Br={...Or};async function Vy(){const t=new AbortController,e=setTimeout(()=>t.abort(),5e3);try{const n=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:t.signal});if(!n.ok)return;const i=await n.json();if(i.result!=="success"||!i.rates)return;const r=i.rates,s={AUD:1},o=new Set([...Object.keys(Or),...Object.values(ja),...Object.values(Da)]);for(const a of o)a!=="AUD"&&(typeof r[a]=="number"&&r[a]>0?s[a]=r[a]:Or[a]&&(s[a]=Or[a]));Br=s}catch{}finally{clearTimeout(e)}}const ja={"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 Al(){try{const s=Intl.DateTimeFormat().resolvedOptions().timeZone;if(s&&ja[s])return ja[s]}catch{}const e=(navigator.language||"en-US").replace("-","_"),n=Da[e];if(n)return n;const i=e.split("_")[0],r=Da[i];return r||"USD"}function Oi(t,e){const n=Br[e]??Br.USD,i=t*n,r=Math.round(i*100)/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:r>=100||r%1===0?0:2}).format(r)}catch{return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(t*Br.USD)}}const gt="ccc_api_key_",Pt="ccc_session_api_key_",Rt="ccc_encryption_key",tr="ccc_encryption_key_scope",Gy="ccc_keystore",vs="keys",nr="ccc_encryption_key_version";let Ua=null,_s=null,ir=!1,ys=!1,Ju=!1;class ws extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function Zu(){if(Ju)return;Ju=!0;const t="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(t),document.body&&Ee(t,"warning")}function Nh(){return localStorage.getItem(nr)||""}function Ha(){return crypto.randomUUID?.()||Bh(crypto.getRandomValues(new Uint8Array(16)))}function Ky(){const t=Nh();if(t)return t;const e=Ha();return localStorage.setItem(nr,e),e}function ci(){Ua=null,_s=null,ir=!1,ys=!1}window.addEventListener("storage",t=>{t.key===nr&&ci()});function Yy(){return new Promise((t,e)=>{const n=indexedDB.open(Gy,1);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(vs)||i.createObjectStore(vs)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function Pl(t,e){const n=await Yy();return new Promise((i,r)=>{const s=n.transaction(vs,t);let o;try{o=e(s.objectStore(vs))}catch(l){n.close(),r(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>r(o.error),s.oncomplete=()=>{n.close(),i(a)},s.onerror=()=>{n.close(),r(s.error||new Error("Encryption key transaction failed."))},s.onabort=()=>{n.close(),r(s.error||new Error("Encryption key transaction aborted."))}})}function Jy(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function Zy(){const t=await Pl("readonly",e=>e.get(Rt));return Jy(t)?t:null}async function Oh(t){await Pl("readwrite",e=>e.put(t,Rt))}async function Xy(){ci();try{await Pl("readwrite",t=>t.delete(Rt))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function Qy(){const t=sessionStorage.getItem(Rt);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Oh(e),sessionStorage.removeItem(Rt),sessionStorage.removeItem(tr),localStorage.removeItem(gt+"salt"),e}async function Xu(t){const e=sessionStorage.getItem(Rt);if(e)return ys=sessionStorage.getItem(tr)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new ws;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),i=await crypto.subtle.exportKey("jwk",n);return sessionStorage.setItem(Rt,JSON.stringify(i)),sessionStorage.setItem(tr,"session"),ys=!1,crypto.subtle.importKey("jwk",i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function e0(t){if(sessionStorage.getItem(tr)==="session"&&sessionStorage.getItem(Rt))return Zu(),ir=!0,Xu(t);try{const e=await Zy();if(e)return e;const n=await Qy();if(n)return n;const i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Oh(i),i}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),Zu(),ir=!0,Xu(t)}}async function Fl(t={}){const{allowSessionFallbackCreation:e=!0}=t,n=Ky();_s!==n&&ci();const i=Ua||e0(e);Ua=i,_s=n;try{return await i}catch(r){throw ci(),r}}async function t0(t){const e=await Fl(),n=_s,i=new TextEncoder,r=crypto.getRandomValues(new Uint8Array(12)),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},e,i.encode(t)),o=new Uint8Array(r.length+s.byteLength);return o.set(r),o.set(new Uint8Array(s),r.length),{ciphertext:Bh(o),keyVersion:n,sessionFallback:ir}}async function n0(t,e={}){const{isSessionCredential:n=!1}=e;try{const i=await Fl({allowSessionFallbackCreation:!1});if(ir&&!n&&!ys)throw new ws;const r=i0(t),s=r.slice(0,12),o=r.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},i,o);return new TextDecoder().decode(a)}catch(i){if(i instanceof ws)throw i;return console.error("Decryption failed:",i),null}}function Bh(t){const e=new Uint8Array(t);let n="";for(let i=0;i0}let Ln="",ui="",zi=null,ed=0,nt="not-configured";async function Rl(){sessionStorage.getItem(Rt)&&await Fl(),Ln=await Te("flutterflow"),ui=await Te("flutterflow_project_id"),d0(),rn(),Ln?Ll():(nt="not-configured",vt())}let rr=!1;function Dh(){const t=document.getElementById("api-keys-modal");We(t),Ml(),Ln&&Nl(Ln)}function Tl(){rr=!1,Dh()}function s0(){rr=!0;const t=document.getElementById("walkthrough-modal");t&&ze(t),Dh()}let td=!1;function nd(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-settings-model");if(!t||!e)return;e.value=t.value;const n=Array.from(t.options);Array.from(e.options).forEach((r,s)=>{const o=n[s];o&&(r.textContent=o.textContent)});const i=document.getElementById("composer-settings-free-notice");i&&(document.getElementById("model-selector-free-notice")?(i.hidden=!1,i.innerHTML='Free plan — Gemini only. '):i.hidden=!0)}function id(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-image-capability"),n=document.getElementById("composer-image-capability-note");if(!t)return;const i=Gt(t.value),r=Ph(t.value);e&&(e.textContent=r?"Supported":"Not supported"),n&&(n.textContent=r?`${i} accepts reference images you attach to the prompt.`:`Images can't be attached with ${i}. Attached images are removed when you switch to it.`),Cl()}function o0(){if(rr=!1,nd(),id(),!td){const e=document.getElementById("composer-settings-model");e&&e.addEventListener("change",()=>{const n=document.getElementById("code-generator-model");n.value=e.value,n.dispatchEvent(new Event("change")),nd(),id()}),td=!0}const t=document.querySelector('.composer [aria-label="Generation settings"]');We("composer-settings-modal",{trigger:t})}function a0(t){t&&t.target!==t.currentTarget||ze("composer-settings-modal")}function jh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&ze(e);const n=rr;if(rr=!1,n){const i=document.getElementById("walkthrough-modal");i&&(nt==="connected"&&$l(),We(i))}}let en=1;function Uh(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function Ns(){const t=Uh();t.length&&t.forEach((e,n)=>{const i=n+1;e.classList.remove("wt-current","wt-done","wt-pending");const r=e.querySelector(".wt-step-num");i===en?(e.classList.add("wt-current"),r&&(r.textContent=i)):i0&&en<=t&&(en++,Ns())}function l0(){const t=document.getElementById("walkthrough-modal");t&&(en=1,Ns(),We(t))}function c0(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&ze(e);const n=document.getElementById("walkthrough-dont-show");n&&n.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function Hh(){if(q.isVerified&&Tt()&&ce.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(en=1,Ns(),We(e))}}async function Ml(){const t=document.getElementById("flutterflow-api-key-input");Ln?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",u0()}function u0(){rd("flutterflow","flutterflow-key-status"),rd("flutterflow_project_id","flutterflow-project-status")}function rd(t,e){const n=document.getElementById(e);if(!n)return;const i=n.querySelector(".key-status-dot"),r=n.querySelector("span");Ct(t)?(i.className="key-status-dot configured",r.className="text-green-600",r.textContent="User key configured"):(i.className="key-status-dot missing",r.className="text-gray-500",r.textContent="Not configured")}function rn(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff");e&&e.classList.toggle("hidden",!t)}function d0(){const t=document.getElementById("api-keys-status");if(!t)return;const e=t.querySelectorAll(".key-status-dot"),n=["flutterflow"];e.forEach((i,r)=>{const s=n[r];s==="flutterflow"?Ct("flutterflow")&&Ct("flutterflow_project_id")?(i.className="key-status-dot configured",i.title="FlutterFlow (Fully configured)"):Ct("flutterflow")||Ct("flutterflow_project_id")?(i.className="key-status-dot env",i.title="FlutterFlow (Partially configured)"):(i.className="key-status-dot missing",i.title="FlutterFlow (Not configured)"):Ct(s)?(i.className="key-status-dot configured",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (User key)"):(i.className="key-status-dot missing",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (Not configured)")}),rn()}async function f0(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select"),n=t.value.trim();n&&await Qu("flutterflow",n);const i=e?.value.trim()||"";if(i){if(!Os(i)){Ee("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await Qu("flutterflow_project_id",i)}await Rl(),n&&await Ll(),Ml();const r=document.querySelector("#api-keys-modal .bg-blue-500"),s=r.textContent;r.textContent="Saved!",r.classList.remove("bg-blue-500","hover:bg-blue-600"),r.classList.add("bg-green-500"),setTimeout(()=>{r.textContent=s,r.classList.remove("bg-green-500"),r.classList.add("bg-blue-500","hover:bg-blue-600"),jh()},1e3)}async function h0(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(nr,Ha()),ci(),localStorage.removeItem(gt+"flutterflow"),localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow"),sessionStorage.removeItem(Pt+"flutterflow_project_id"),sessionStorage.removeItem(Rt),sessionStorage.removeItem(tr),localStorage.removeItem(gt+"salt"),await Xy(),localStorage.setItem(nr,Ha()),localStorage.removeItem(gt+"flutterflow"),localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow"),sessionStorage.removeItem(Pt+"flutterflow_project_id"),await Rl();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),Ml()}function Os(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function vt(){const t=document.getElementById("acct-ff-dot"),e=document.getElementById("acct-ff-status"),n=document.getElementById("acct-ff-endpoint"),i=document.getElementById("acct-ff-project");if(n){const o=yt();n.textContent=o.includes("staging")?"Staging":"Production"}if(i&&(i.textContent=ui||"—"),!e)return;let r,s;if(!Ct("flutterflow"))r="Not connected — add your FlutterFlow API key",s="";else switch(nt){case"connected":r="Connected to FlutterFlow",s="ok";break;case"no-projects":r="Key accepted — no projects found",s="warn";break;case"unauthorized":r="API key rejected (401/403) — re-enter your key",s="bad";break;case"network-error":r="Could not reach FlutterFlow — check your network",s="bad";break;default:r="Checking connection…",s="warn";break}e.textContent=r,t&&(t.className=`acct-dot${s?" "+s:""}`)}async function Ll(){const t=await Te("flutterflow");if(!t||!Ct("flutterflow"))return nt="not-configured",vt(),null;nt="validating",vt();try{const n=await new hi(t,"","main",yt()).listProjects();return nt=n&&n.length>0?"connected":"no-projects",vt(),n}catch(e){const n=String(e&&e.message||"");return nt=/(401|403)|denied|unauthorized|scoped|list permission/i.test(n)?"unauthorized":"network-error",vt(),null}}function p0(){ui="",localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow_project_id")}function g0(){p0();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML='',t.value=""),Ct("flutterflow")?(nt="validating",Nl(Ln)):nt="not-configured",vt()}function m0(t,e){const n=document.getElementById(t);n&&(n.value?e?n.style.borderColor="#22c55e":n.style.borderColor="#ef4444":n.style.borderColor="")}function v0(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const n=e.target.value.trim().length>0;m0("flutterflow-api-key-input",n)}),t.addEventListener("blur",_0(async e=>{const n=e.target.value.trim();n&&await Nl(n)},500)))}function _0(t,e){let n;return function(...r){const s=()=>{clearTimeout(n),t(...r)};clearTimeout(n),n=setTimeout(s,e)}}async function Nl(t){const e=document.getElementById("flutterflow-projects-select"),n=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',n&&n.classList.add("hidden"),(Ct("flutterflow")||t)&&(nt="validating"),vt();try{const r=await new hi(t,"","main",yt()).listProjects();if(!r||r.length===0){nt="no-projects",vt(),e.innerHTML='';return}nt="connected",vt(),e.innerHTML='',r.forEach(s=>{const o=document.createElement("option");o.value=s.id||s.projectId||"",o.textContent=s.name||s.projectName||`Project ${s.id}`,e.appendChild(o)}),ui&&(e.value=ui)}catch(i){console.error("Failed to fetch projects:",i);const r=String(i&&i.message||"");nt=/(401|403)|denied|unauthorized|scoped|list permission/i.test(r)?"unauthorized":"network-error",vt(),e.innerHTML='',n&&(n.textContent=`Failed to load projects: ${i.message}`,n.classList.remove("hidden"))}}function y0(t){const e=document.getElementById(t),i=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",i.innerHTML=` + `}const Sy=[[/gradient stroke\s*$/i," and an animated percentage label"],[/gauge\s*$/i," with a gradient stroke and animated fill"],[/rating\s*(bar|widget)?\s*$/i," with half-star support and haptic feedback"],[/list\s*$/i," with swipe-to-delete and an undo snackbar"],[/pad\s*$/i," that exports a transparent PNG"],[/carousel\s*$/i," with parallax cards and page indicators"],[/(button|cta)\s*$/i," with a loading spinner and success state"],[/(chart|graph)\s*$/i," that animates from a Firestore stream"],[/action\s*(that|to)?\s*$/i," uploads an image to Firebase Storage and returns the URL"],[/timer\s*$/i," with pause, resume and a completion callback"],[/map\s*$/i," with clustered markers and a custom info window"],[/^a\s+\w*$/i," widget that"],[/(picker|selector)\s*$/i," with search and multi-select"]],xy=220,Iy=6;function Gu(t,e){return!!(t&&t.trim())&&!e}function ky(t,e=""){if(typeof t!="string"||!t||t===e||t.trim().lengthi.test(t));return n?n[1]:null}function Cy(){let t="",e="";return{get active(){return t},resolve(n){return t=ky(n,e)??"",t},dismiss(){t=""},accept(n){if(!t)return null;const i=n+t;return e=i,t="",i}}}function Ay({onSubmit:t}){const e=document.getElementById("composer"),n=document.getElementById("pipeline-input"),i=document.getElementById("hero-send");if(!e||!n||!i||typeof t!="function")return;const r=e.querySelector(".ghost .typed"),s=e.querySelector(".ghost .suggest"),o=document.getElementById("tab-hint"),a=document.getElementById("suggest-status"),l=Array.from(document.querySelectorAll("#example-chips .chip")),u=document.getElementById("btn-add-images"),c=document.getElementById("prompt-image-input"),d=window.matchMedia("(prefers-reduced-motion: reduce)"),f=Cy();let h=!1,p=!1,g=!1,m=!1,v=null,E=null;function S(){i.disabled=!Gu(n.value,p||g||m)}function _(){r&&(r.textContent=n.value)}function b(){s&&(s.textContent=""),_(),e.classList.remove("has-suggest"),o&&(o.hidden=!0,o.tabIndex=-1),a&&(a.textContent="")}function k(R){s&&(s.textContent=R),_(),e.classList.add("has-suggest"),o&&(o.hidden=!1,o.tabIndex=0,o.setAttribute("aria-label","Accept suggestion: "+R.trim())),a&&(a.textContent="Suggestion: "+R+". Press Tab to accept.")}function T(){f.dismiss(),b()}function x(){if(h||p)return;const R=f.resolve(n.value);R&&k(R)}function F(){clearTimeout(v),!h&&(v=setTimeout(x,xy))}function $(){const R=f.accept(n.value);return R===null?!1:(n.value=R,b(),S(),!0)}function O(R){p=R,e.classList.toggle("is-busy",R),i.classList.toggle("is-busy",R),i.setAttribute("aria-label",R?"Generating":"Generate"),n.readOnly=R,l.forEach(Z=>{Z.disabled=R}),u&&(u.disabled=R),c&&(c.disabled=R),S()}async function L(){if(Gu(n.value,p||g||m)){T(),O(!0);try{await t()}finally{O(!1)}}}function N(){g=!1,E&&(clearInterval(E),E=null),e.classList.remove("is-demo-typing"),S()}function K(){l.forEach(R=>{R.classList.remove("is-active"),R.setAttribute("aria-pressed","false")})}function V(){try{n.focus({preventScroll:!0}),n.setSelectionRange(n.value.length,n.value.length)}catch{}}function M(R){const Z=R.dataset.prompt||"";if(N(),clearTimeout(v),v=null,T(),l.forEach(oe=>{const ye=oe===R;oe.classList.toggle("is-active",ye),oe.setAttribute("aria-pressed",String(ye))}),d.matches||!Z){n.value=Z,_(),S(),V();return}n.value="",_(),g=!0,S(),e.classList.add("is-demo-typing");let Ce=0;E=setInterval(()=>{Ce+=1,n.value=Z.slice(0,Ce),_(),Ce>=Z.length?(N(),V()):S()},22)}return l.forEach(R=>{R.setAttribute("aria-pressed","false"),R.addEventListener("click",()=>M(R))}),n.addEventListener("keydown",R=>{if(g&&R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!h){R.preventDefault();return}N(),R.key==="Tab"&&!R.shiftKey&&f.active?(R.preventDefault(),$()):R.key==="Escape"?(clearTimeout(v),v=null,T()):R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!h&&(R.preventDefault(),L())}),n.addEventListener("input",()=>{N(),K(),T(),S(),F()}),n.addEventListener("compositionstart",()=>{h=!0}),n.addEventListener("compositionend",()=>{h=!1,T(),S(),F()}),n.addEventListener("scroll",()=>{r&&r.parentNode&&(r.parentNode.scrollTop=n.scrollTop)}),o&&o.addEventListener("click",()=>{$(),n.focus({preventScroll:!0})}),i.addEventListener("click",L),n.addEventListener("pointerdown",()=>{N(),K()}),_(),S(),{setAttachmentsPending(R){m=!!R,S()}}}const Py="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses";const _t="https://4tgke4.buildship.run",Ah={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},hs="ccc_auth_session",Na="ccc_signin_return",Fy=1800*1e3,Ku=new WeakSet;let q={email:null,sessionToken:null,isVerified:!1};function Ln(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let ce=Ln({isResolved:!0}),Oa=Promise.resolve();const Ry=`${_t}/service/runpipeline`,Ty="bs_user_id",$y="bs_identity_token",My=`${_t}/authUserCheck`;let ht={userId:null,token:null,status:null,resolved:!1};const ps=dv,gs="ccc_subscription",Yu=3,Ly=new Set(["active","trialing","paid"]),ms="google/gemini-3.7-flash",Nr=["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"],Ny={"google/gemini-3.7-flash":"Gemini 3.7 Flash","anthropic/claude-opus-5":"Claude Opus 5","openai/gpt-5.6-sol":"GPT-5.6 Sol","z-ai/glm-5.2":"GLM 5.2","moonshotai/kimi-k3":"Kimi K3","openrouter/auto-beta":"OpenRouter: Auto Router","openrouter/free":"OpenRouter: Free Models","openrouter/deepseek/deepseek-v4-pro":"DeepSeek v4 Pro"};function Gt(t){return Ny[t]||t}const Oy=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 Ph(t){return Oy.has(t)}const Ba=4,Ho=8*1024*1024,By="https://4tgke4.buildship.run/service/runpipeline-image";let Oe=[];const pn=[],Dy=3e4;let Fh=null;function jy(t){return new Promise(e=>{const n=new FileReader;n.onload=()=>e(n.result),n.onerror=()=>e(null),n.readAsDataURL(t)})}async function Uy(t,e){const n=new FormData;return n.append("file",t),(await fetch(By,{method:"POST",body:n,signal:e})).json()}function Hy(t){if(Array.isArray(t)){const e=t[0];if(e&&typeof e=="object")for(const n of Object.keys(e)){if(n==="item"||n==="index")continue;const i=e[n];if(i&&typeof i=="object"){if(typeof i.file=="string")return i.file;if(typeof i.url=="string")return i.url}if(typeof i=="string")return i}return""}return typeof t=="string"?t:t&&typeof t=="object"&&(t.url||t.fileUrl||t.file_url||t.downloadUrl||t.imageUrl||t.image_url||t.file)||""}async function Wy(t,e,n){const i=await jy(t);i&&Oe.includes(e)&&(e.dataUrl=i,cn());let r="";if(i)try{r=Hy(await Uy(t,n))}catch{r=""}return Oe.includes(e)?!i||!r?(Oe.splice(Oe.indexOf(e),1),cn(),"failed"):(e.url=r,cn(),"added"):"dropped"}function Rh(t){const e=pn.indexOf(t);e>=0&&pn.splice(e,1),$h()}function Th(t){t.controller.abort(),Rh(t);const e=Oe.indexOf(t.slot);e>=0&&(Oe.splice(e,1),cn())}function $h(){Fh?.setAttachmentsPending(pn.length>0)}async function zy(t){const e=Array.from(t.target.files||[]);if(!e.length)return;if(t.target.value="",y.isRunning){Ee("Wait for the current generation to finish before attaching images.","info");return}const n=e.filter(u=>u.size>Ho);n.length&&Ee(`Skipped ${n.length} image(s) over the ${(Ho/1024/1024).toFixed(0)} MB limit.`,"warning");const i=e.filter(u=>u.size<=Ho);if(!i.length)return;const r=Ba-Oe.length,s=i.slice(0,r);if(i.length>r&&Ee(`You can attach up to ${Ba} images.`,"info"),!s.length)return;const o=s.map(u=>{const c={dataUrl:null,name:u.name,url:null};Oe.push(c);const d={slot:c,controller:new AbortController},f=setTimeout(()=>d.controller.abort(),Dy);return d.job=Wy(u,c,d.controller.signal),pn.push(d),d.job.finally(()=>{clearTimeout(f),Rh(d)}),d.job});cn(),$h();const l=(await Promise.all(o)).filter(u=>u==="failed").length;l&&Ee(`${l} image(s) could not be uploaded and were not attached.`,"error")}function qy(t){const e=Oe[t],n=pn.find(i=>i.slot===e);if(n){Th(n);return}Oe.splice(t,1),cn()}function cn(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",Oe.forEach((n,i)=>{const r=document.createElement("div");r.className="prompt-img-thumb"+(n.url?"":" is-pending"),r.innerHTML=(n.dataUrl?`Prompt image`:"")+``,t.appendChild(r)}),e&&(e.textContent=Oe.length>=Ba?"Image limit reached":"Add images"))}function Cl(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),n=Ph(e?.value);t.classList.toggle("hidden",!n),!n&&Oe.length&&(pn.slice().forEach(Th),Oe=[],cn())}const Rn="ccc_usage",Mh="google/gemini-3.7-flash",Lh="google/gemini-3.7-flash",kr="google/gemini-3.7-flash",Oi={professional:11,power:49},Da={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"},Or={AUD:1,USD:.65,EUR:.6,GBP:.52,CAD:.88,NZD:1.08,JPY:97,KRW:870,INR:54,SGD:.87,HKD:5.08,BRL:3.18,CNY:4.7,TWD:20.5,THB:22.5,VND:16200,IDR:10200,MYR:2.88,SEK:6.8,NOK:6.95,DKK:4.48,PLN:2.6,CZK:15.2,HUF:238,RON:2.98,TRY:20.9,AED:2.39,ILS:2.38,PHP:36.4,ZAR:11.8,RUB:58,UAH:26.8,CHF:.57,MXN:11.1,ARS:580,CLP:610,COP:2700,PEN:2.44};let Br={...Or};async function Vy(){const t=new AbortController,e=setTimeout(()=>t.abort(),5e3);try{const n=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:t.signal});if(!n.ok)return;const i=await n.json();if(i.result!=="success"||!i.rates)return;const r=i.rates,s={AUD:1},o=new Set([...Object.keys(Or),...Object.values(ja),...Object.values(Da)]);for(const a of o)a!=="AUD"&&(typeof r[a]=="number"&&r[a]>0?s[a]=r[a]:Or[a]&&(s[a]=Or[a]));Br=s}catch{}finally{clearTimeout(e)}}const ja={"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 Al(){try{const s=Intl.DateTimeFormat().resolvedOptions().timeZone;if(s&&ja[s])return ja[s]}catch{}const e=(navigator.language||"en-US").replace("-","_"),n=Da[e];if(n)return n;const i=e.split("_")[0],r=Da[i];return r||"USD"}function Bi(t,e){const n=Br[e]??Br.USD,i=t*n,r=Math.round(i*100)/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:r>=100||r%1===0?0:2}).format(r)}catch{return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(t*Br.USD)}}const gt="ccc_api_key_",Pt="ccc_session_api_key_",Rt="ccc_encryption_key",nr="ccc_encryption_key_scope",Gy="ccc_keystore",vs="keys",ir="ccc_encryption_key_version";let Ua=null,_s=null,rr=!1,ys=!1,Ju=!1;class ws extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function Zu(){if(Ju)return;Ju=!0;const t="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(t),document.body&&Ee(t,"warning")}function Nh(){return localStorage.getItem(ir)||""}function Ha(){return crypto.randomUUID?.()||Bh(crypto.getRandomValues(new Uint8Array(16)))}function Ky(){const t=Nh();if(t)return t;const e=Ha();return localStorage.setItem(ir,e),e}function ui(){Ua=null,_s=null,rr=!1,ys=!1}window.addEventListener("storage",t=>{t.key===ir&&ui()});function Yy(){return new Promise((t,e)=>{const n=indexedDB.open(Gy,1);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(vs)||i.createObjectStore(vs)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function Pl(t,e){const n=await Yy();return new Promise((i,r)=>{const s=n.transaction(vs,t);let o;try{o=e(s.objectStore(vs))}catch(l){n.close(),r(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>r(o.error),s.oncomplete=()=>{n.close(),i(a)},s.onerror=()=>{n.close(),r(s.error||new Error("Encryption key transaction failed."))},s.onabort=()=>{n.close(),r(s.error||new Error("Encryption key transaction aborted."))}})}function Jy(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function Zy(){const t=await Pl("readonly",e=>e.get(Rt));return Jy(t)?t:null}async function Oh(t){await Pl("readwrite",e=>e.put(t,Rt))}async function Xy(){ui();try{await Pl("readwrite",t=>t.delete(Rt))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function Qy(){const t=sessionStorage.getItem(Rt);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Oh(e),sessionStorage.removeItem(Rt),sessionStorage.removeItem(nr),localStorage.removeItem(gt+"salt"),e}async function Xu(t){const e=sessionStorage.getItem(Rt);if(e)return ys=sessionStorage.getItem(nr)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new ws;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),i=await crypto.subtle.exportKey("jwk",n);return sessionStorage.setItem(Rt,JSON.stringify(i)),sessionStorage.setItem(nr,"session"),ys=!1,crypto.subtle.importKey("jwk",i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function e0(t){if(sessionStorage.getItem(nr)==="session"&&sessionStorage.getItem(Rt))return Zu(),rr=!0,Xu(t);try{const e=await Zy();if(e)return e;const n=await Qy();if(n)return n;const i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Oh(i),i}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),Zu(),rr=!0,Xu(t)}}async function Fl(t={}){const{allowSessionFallbackCreation:e=!0}=t,n=Ky();_s!==n&&ui();const i=Ua||e0(e);Ua=i,_s=n;try{return await i}catch(r){throw ui(),r}}async function t0(t){const e=await Fl(),n=_s,i=new TextEncoder,r=crypto.getRandomValues(new Uint8Array(12)),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},e,i.encode(t)),o=new Uint8Array(r.length+s.byteLength);return o.set(r),o.set(new Uint8Array(s),r.length),{ciphertext:Bh(o),keyVersion:n,sessionFallback:rr}}async function n0(t,e={}){const{isSessionCredential:n=!1}=e;try{const i=await Fl({allowSessionFallbackCreation:!1});if(rr&&!n&&!ys)throw new ws;const r=i0(t),s=r.slice(0,12),o=r.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},i,o);return new TextDecoder().decode(a)}catch(i){if(i instanceof ws)throw i;return console.error("Decryption failed:",i),null}}function Bh(t){const e=new Uint8Array(t);let n="";for(let i=0;i0}let Nn="",di="",qi=null,ed=0,nt="not-configured";async function Rl(){sessionStorage.getItem(Rt)&&await Fl(),Nn=await Te("flutterflow"),di=await Te("flutterflow_project_id"),d0(),rn(),Nn?Ll():(nt="not-configured",vt())}let sr=!1;function Dh(){const t=document.getElementById("api-keys-modal");We(t),Ml(),Nn&&Nl(Nn)}function Tl(){sr=!1,Dh()}function s0(){sr=!0;const t=document.getElementById("walkthrough-modal");t&&ze(t),Dh()}let td=!1;function nd(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-settings-model");if(!t||!e)return;e.value=t.value;const n=Array.from(t.options);Array.from(e.options).forEach((r,s)=>{const o=n[s];o&&(r.textContent=o.textContent)});const i=document.getElementById("composer-settings-free-notice");i&&(document.getElementById("model-selector-free-notice")?(i.hidden=!1,i.innerHTML='Free plan — Gemini only. '):i.hidden=!0)}function id(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-image-capability"),n=document.getElementById("composer-image-capability-note");if(!t)return;const i=Gt(t.value),r=Ph(t.value);e&&(e.textContent=r?"Supported":"Not supported"),n&&(n.textContent=r?`${i} accepts reference images you attach to the prompt.`:`Images can't be attached with ${i}. Attached images are removed when you switch to it.`),Cl()}function o0(){if(sr=!1,nd(),id(),!td){const e=document.getElementById("composer-settings-model");e&&e.addEventListener("change",()=>{const n=document.getElementById("code-generator-model");n.value=e.value,n.dispatchEvent(new Event("change")),nd(),id()}),td=!0}const t=document.querySelector('.composer [aria-label="Generation settings"]');We("composer-settings-modal",{trigger:t})}function a0(t){t&&t.target!==t.currentTarget||ze("composer-settings-modal")}function jh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&ze(e);const n=sr;if(sr=!1,n){const i=document.getElementById("walkthrough-modal");i&&(nt==="connected"&&$l(),We(i))}}let en=1;function Uh(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function Ns(){const t=Uh();t.length&&t.forEach((e,n)=>{const i=n+1;e.classList.remove("wt-current","wt-done","wt-pending");const r=e.querySelector(".wt-step-num");i===en?(e.classList.add("wt-current"),r&&(r.textContent=i)):i0&&en<=t&&(en++,Ns())}function l0(){const t=document.getElementById("walkthrough-modal");t&&(en=1,Ns(),We(t))}function c0(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&ze(e);const n=document.getElementById("walkthrough-dont-show");n&&n.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function Hh(){if(q.isVerified&&Tt()&&ce.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(en=1,Ns(),We(e))}}async function Ml(){const t=document.getElementById("flutterflow-api-key-input");Nn?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",u0()}function u0(){rd("flutterflow","flutterflow-key-status"),rd("flutterflow_project_id","flutterflow-project-status")}function rd(t,e){const n=document.getElementById(e);if(!n)return;const i=n.querySelector(".key-status-dot"),r=n.querySelector("span");Ct(t)?(i.className="key-status-dot configured",r.className="text-green-600",r.textContent="User key configured"):(i.className="key-status-dot missing",r.className="text-gray-500",r.textContent="Not configured")}function rn(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff");e&&e.classList.toggle("hidden",!t)}function d0(){const t=document.getElementById("api-keys-status");if(!t)return;const e=t.querySelectorAll(".key-status-dot"),n=["flutterflow"];e.forEach((i,r)=>{const s=n[r];s==="flutterflow"?Ct("flutterflow")&&Ct("flutterflow_project_id")?(i.className="key-status-dot configured",i.title="FlutterFlow (Fully configured)"):Ct("flutterflow")||Ct("flutterflow_project_id")?(i.className="key-status-dot env",i.title="FlutterFlow (Partially configured)"):(i.className="key-status-dot missing",i.title="FlutterFlow (Not configured)"):Ct(s)?(i.className="key-status-dot configured",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (User key)"):(i.className="key-status-dot missing",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (Not configured)")}),rn()}async function f0(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select"),n=t.value.trim();n&&await Qu("flutterflow",n);const i=e?.value.trim()||"";if(i){if(!Os(i)){Ee("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await Qu("flutterflow_project_id",i)}await Rl(),n&&await Ll(),Ml();const r=document.querySelector("#api-keys-modal .bg-blue-500"),s=r.textContent;r.textContent="Saved!",r.classList.remove("bg-blue-500","hover:bg-blue-600"),r.classList.add("bg-green-500"),setTimeout(()=>{r.textContent=s,r.classList.remove("bg-green-500"),r.classList.add("bg-blue-500","hover:bg-blue-600"),jh()},1e3)}async function h0(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(ir,Ha()),ui(),localStorage.removeItem(gt+"flutterflow"),localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow"),sessionStorage.removeItem(Pt+"flutterflow_project_id"),sessionStorage.removeItem(Rt),sessionStorage.removeItem(nr),localStorage.removeItem(gt+"salt"),await Xy(),localStorage.setItem(ir,Ha()),localStorage.removeItem(gt+"flutterflow"),localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow"),sessionStorage.removeItem(Pt+"flutterflow_project_id"),await Rl();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),Ml()}function Os(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function vt(){const t=document.getElementById("acct-ff-dot"),e=document.getElementById("acct-ff-status"),n=document.getElementById("acct-ff-endpoint"),i=document.getElementById("acct-ff-project");if(n){const o=yt();n.textContent=o.includes("staging")?"Staging":"Production"}if(i&&(i.textContent=di||"—"),!e)return;let r,s;if(!Ct("flutterflow"))r="Not connected — add your FlutterFlow API key",s="";else switch(nt){case"connected":r="Connected to FlutterFlow",s="ok";break;case"no-projects":r="Key accepted — no projects found",s="warn";break;case"unauthorized":r="API key rejected (401/403) — re-enter your key",s="bad";break;case"network-error":r="Could not reach FlutterFlow — check your network",s="bad";break;default:r="Checking connection…",s="warn";break}e.textContent=r,t&&(t.className=`acct-dot${s?" "+s:""}`)}async function Ll(){const t=await Te("flutterflow");if(!t||!Ct("flutterflow"))return nt="not-configured",vt(),null;nt="validating",vt();try{const n=await new pi(t,"","main",yt()).listProjects();return nt=n&&n.length>0?"connected":"no-projects",vt(),n}catch(e){const n=String(e&&e.message||"");return nt=/(401|403)|denied|unauthorized|scoped|list permission/i.test(n)?"unauthorized":"network-error",vt(),null}}function p0(){di="",localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow_project_id")}function g0(){p0();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML='',t.value=""),Ct("flutterflow")?(nt="validating",Nl(Nn)):nt="not-configured",vt()}function m0(t,e){const n=document.getElementById(t);n&&(n.value?e?n.style.borderColor="#22c55e":n.style.borderColor="#ef4444":n.style.borderColor="")}function v0(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const n=e.target.value.trim().length>0;m0("flutterflow-api-key-input",n)}),t.addEventListener("blur",_0(async e=>{const n=e.target.value.trim();n&&await Nl(n)},500)))}function _0(t,e){let n;return function(...r){const s=()=>{clearTimeout(n),t(...r)};clearTimeout(n),n=setTimeout(s,e)}}async function Nl(t){const e=document.getElementById("flutterflow-projects-select"),n=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',n&&n.classList.add("hidden"),(Ct("flutterflow")||t)&&(nt="validating"),vt();try{const r=await new pi(t,"","main",yt()).listProjects();if(!r||r.length===0){nt="no-projects",vt(),e.innerHTML='';return}nt="connected",vt(),e.innerHTML='',r.forEach(s=>{const o=document.createElement("option");o.value=s.id||s.projectId||"",o.textContent=s.name||s.projectName||`Project ${s.id}`,e.appendChild(o)}),di&&(e.value=di)}catch(i){console.error("Failed to fetch projects:",i);const r=String(i&&i.message||"");nt=/(401|403)|denied|unauthorized|scoped|list permission/i.test(r)?"unauthorized":"network-error",vt(),e.innerHTML='',n&&(n.textContent=`Failed to load projects: ${i.message}`,n.classList.remove("hidden"))}}function y0(t){const e=document.getElementById(t),i=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",i.innerHTML=` `):(e.type="password",i.innerHTML=` - `)}let y={step1Result:null,step2Result:null,step3Result:null,bundleSpec:null,artifactBundle:null,bundleReview:null,selectedArtifactId:null,resultsViewMode:"summary",currentStep:0,isRunning:!1,runId:0,submittedPrompt:"",submittedImages:[]};function w0(){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 b0(){y.bundleSpec=Qi(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function Bs(){const t=oi(y.bundleSpec);y.artifactBundle=Qi(y.step2Result,{id:y.bundleSpec?.id,title:y.bundleSpec?.title,description:y.bundleSpec?.description,artifactType:t.artifactType,artifactName:t.artifactName,fileName:t.fileName,dependencies:t.dependencies,relationships:y.bundleSpec?.relationships,code:y.step2Result||""});const e=Vv(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(n=>n.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=oi(y.artifactBundle).id}function Ds(){const t=Qi(y.step3Result,{id:y.artifactBundle?.id,title:y.artifactBundle?.title}),e=new Map(t.artifacts.map(i=>[i.id,i.review])),n=new Map(t.artifacts.filter(i=>{const r=i.review;return r&&typeof r.fixedSource=="string"&&r.fixedSource.trim()}).map(i=>[i.id,i.review.fixedSource.trim()]));y.bundleReview=Qi({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(i=>{const r=n.get(i.id)||null;return{...i,review:e.get(i.id)||i.review||y.step3Result||null,...r?{fixedCode:r}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function Wh(){const t=Ol();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function Ol(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(n=>n.id===y.selectedArtifactId)||oi(t)}function Bl(){return Ol().code||y.step2Result||""}async function E0(){try{await Rl()}catch(t){return console.error("checkConnection: initializeApiKeys failed:",t),!1}return!0}const Dr={production:"https://api.flutterflow.io/v2/",staging:"https://api.flutterflow.io/v2-staging/"};function S0(t,e){const n=e?.trim()?` (${e.trim().slice(0,200)})`:"";return t===401?`Your FlutterFlow API key was rejected (401 Unauthorized)${n}. Re-enter a current key under API Keys settings, then try again.`:`Listing FlutterFlow projects was denied (403)${n}. The key may be scoped to sync a single project without list permission - verify the key's access in FlutterFlow, re-enter it under API Keys settings, then retry.`}class hi{constructor(e,n,i="main",r=Dr.production){this.apiKey=e,this.baseUrl=r,this._projectId=n,this._branchName=i,this._endpoint=r}get projectId(){return this._projectId}get branchName(){return this._branchName==="main"?"":this._branchName}async exportProjectZip(){console.log(`Exporting code from FlutterFlow project: ${this.projectId}, branch: ${this.branchName||"main"}`);const e=[{project:{path:`projects/${this.projectId}`},...this.branchName?{branch_name:this.branchName}:{},export_as_module:!1,include_assets_map:!1,format:!1,export_as_debug:!1},{project_id:this.projectId,branch_name:this.branchName,include_assets:!1,export_as_module:!1}];let n=null;for(const i of e)try{const r=await fetch(`${this.baseUrl}exportCode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(i)});if(!r.ok){const a=await r.text();n=new Error(`Export failed: ${r.status} - ${a}`);continue}const s=await r.json(),o=s?.value?.project_zip||s?.project_zip;if(!o){n=new Error("Export response did not include project source.");continue}return o}catch(r){n=r}throw n||new Error("Export failed for an unknown reason.")}async fetchProjectSource(){const e=await this.exportProjectZip(),n=await JSZip.loadAsync(e,{base64:!0}),i=Object.keys(n.files).filter(a=>!n.files[a].dir&&(a==="pubspec.yaml"||a.endsWith("/pubspec.yaml"))).sort((a,l)=>a.split("/").length-l.split("/").length)[0];if(!i)throw new Error("Export did not contain a pubspec.yaml.");const r=i.slice(0,i.length-12),s=new Map,o=Object.keys(n.files).filter(a=>{if(n.files[a].dir||!a.startsWith(r))return!1;const l=a.slice(r.length);return l==="lib/flutter_flow/custom_functions.dart"||l.startsWith("lib/custom_code/")&&l.endsWith(".dart")});return await Promise.all(o.map(async a=>{s.set(a.slice(r.length),await n.files[a].async("string"))})),{pubspecYaml:await n.files[i].async("string"),files:s}}async pushCodeWithRetry(e,n=3,i=null){const r=[Dr.production,Dr.staging],s=Math.max(0,r.indexOf(this._endpoint));let o=!1,a=null;for(let l=0;lsetTimeout(h,1e3*(l+1)));continue}if(d.ok)return console.log(`Push to ${c} succeeded!`),d;if(a=d.status,Wa(d.clone(),Sh).then(f=>console.log(`Push to ${c} returned ${d.status}: ${f}`),()=>console.log(`Push to ${c} returned ${d.status} (unreadable response body)`)),d.status>=500&&(o=!0),d.status===500){console.warn(`Endpoint ${c} returned 500, trying next...`),await new Promise(f=>setTimeout(f,1e3*(l+1)));continue}if(d.status>=500)throw new Qe(`FlutterFlow reported a server error (HTTP ${d.status}), which cannot prove the push was refused — the write may have been applied before the failure. Open your FlutterFlow project to reconcile before retrying.`);if(o)throw new Qe(`The push was refused (HTTP ${d.status}), but an earlier sync attempt may already have applied it — server errors and dropped responses cannot prove a refusal. Open your FlutterFlow project to reconcile before retrying.`);return d}throw Hu({httpStatus:a})}async pushCode(e,n=null){return this.pushCodeWithRetry(e,3,n)}parseProjectsResponse(e){if(e?.success&&typeof e.value=="string")try{const i=JSON.parse(e.value);if(i&&Array.isArray(i.entries))return i.entries.map(r=>({id:r.id,name:r.project?.name||r.id}))}catch(i){console.error("Failed to parse stringified project value:",i)}const n=e?.projects||e?.items||e?.entries||(Array.isArray(e)?e:[]);return Array.isArray(n)?n:[]}async listProjects(){console.log("Listing projects for API key");const e=[`${this.baseUrl}listProjects`,"https://api.flutterflow.io/v2/l/listProjects"];let n=0,i="";for(const r of e){const s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({project_type:"ALL",deserialize_response:!0})});if(s.ok)return r!==e[0]&&console.log(`listProjects answered on legacy path ${r}`),this.parseProjectsResponse(await s.json());if(n=s.status,i=await s.text(),console.warn(`listProjects via ${r} returned ${n}: ${i}`),s.status===401||s.status===403)throw new Error(S0(s.status,i));if(s.status!==404)throw new Error(`List projects failed: ${s.status} - ${i}`)}throw new Error(`List projects failed: ${n} - ${i}`)}}function Wa(t,e){const n=t.body?.getReader?.(),i=n?(async()=>{const r=new TextDecoder;let s="";for(;;){const{done:o,value:a}=await n.read();if(o)break;s+=r.decode(a,{stream:!0})}return s+r.decode()})():Promise.resolve("");return Ul(i,e,(r,s)=>{try{n?.cancel()?.catch?.(()=>{})}catch{}s(new Error("The response body stalled before it finished."))})}async function x0(t,e=Sh){const n=t.clone();let i;try{i=JSON.parse(await Wa(t,e))}catch{let o="";try{o=await Wa(n,e)}catch{}if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:o||`HTTP ${t.status}`,errorMap:new Map};throw new Qe(`FlutterFlow accepted the sync but returned an unreadable response${o?`: ${o.slice(0,200)}`:"."}`)}if(!t.ok){let s=i.message||`HTTP ${t.status}`,o=new Map;if(i.errors)o=new Map(Object.entries(i.errors));else if(!i.message&&typeof i=="object"){const a=Object.keys(i).filter(l=>l.endsWith(".dart")&&Array.isArray(i[l]));a.length>0&&(o=new Map(Object.entries(i)),s=a.flatMap(u=>i[u].map(c=>`${u}: ${c.errorMessage}`)).join(` -`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:s,errorMap:o}}let r={};if(i.value)try{r=typeof i.value=="string"?JSON.parse(i.value):i.value}catch(s){console.warn("Ignoring malformed push response value:",s)}return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(r))}}function Dl(t,e){return{401:"Authentication failed. Please check your FlutterFlow API key.",403:"Access denied. You may not have permission to modify this project.",404:"Project not found. Please check your Project ID.",409:"Conflict detected. The project may have been modified elsewhere.",422:"Validation failed: Invalid request format",429:"Rate limit exceeded. Please try again in a few minutes.",500:"FlutterFlow server error. Please try again later.",503:"FlutterFlow service temporarily unavailable."}[t]||`FlutterFlow API error: ${`HTTP ${t}`}`}const J={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},zh=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,qh=/extends\s+State<\w+>/;function I0(t,e=""){if(t==="pubspec.yaml")return J.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return J.OTHER;if(t==="custom_functions.dart")return J.FUNCTION;if(e){const n=zh.test(e),i=qh.test(e);if(n||i)return J.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return J.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return J.FUNCTION}return J.CODE_FILE}function Vh(t,e){switch(e){case J.ACTION:return`lib/custom_code/actions/${t}`;case J.WIDGET:return`lib/custom_code/widgets/${t}`;case J.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case J.CODE_FILE:return`lib/custom_code/${t}`;case J.DEPENDENCIES:return"pubspec.yaml";case J.OTHER:return`lib/custom_code/${t}`;default:return t}}async function jl(t,e=new Map){return Av(t,e)}const za=new Map;function Gh(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function sr(t){za.delete(Gh(t))}function Ul(t,e,n){return new Promise((i,r)=>{let s=!1;const o=(l,u,c)=>{s||(s=!0,c==="resolve"?i(u):r(u))},a=setTimeout(()=>{s||(s=!0,n(i,r))},e);t.then(l=>{clearTimeout(a),o(i,l,"resolve")},l=>{clearTimeout(a),o(r,l,"reject")})})}async function Hl(t,e,n=Eh){const i={stop:!1};return Ul((async()=>{const r=await t.pushCode(e,i);return x0(r)})(),n,(r,s)=>{i.stop=!0,s(new Qe("FlutterFlow did not answer the sync in time — the push may still have been applied. The outcome is not yet known: open your FlutterFlow project to reconcile before retrying the deploy."))})}async function Wl(t,e,n,i,r="",s=Eh){const o=o_(e,n);if(o.length===0)return{remoteFiles:n,syncFileMap:e,unverified:[],approximate:[]};const a=X_(o,r),l={...a.manifest,sources:a.sources},u=a.skipped.map(h=>h.reason);u.forEach(h=>console.warn(`[custom class deploy] ${h}`));const c=a.approximate;c.forEach(h=>console.warn(`[custom class deploy] ${h}`)),console.log(`Provisioning ${o.length} new FlutterFlow custom code file(s) before sync.`),Be.set("provision");let d=!0,f;try{if(f=await Ul((async()=>{let h;try{h=await fetch(Py,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:i,customClasses:o,verification:l,stream:!0})})}catch{throw new Qe("The provisioning request did not return a response. The deploy may have reached the FlutterFlow server — open your FlutterFlow project to reconcile before retrying.")}return ey(h,{onPhase:p=>{d&&Be.setSubstatus(p)},onLog:p=>{d&&console.log(`[custom class deploy] ${p}`)}})})(),s,(h,p)=>{d=!1,p(new Qe("The deploy is still working on the FlutterFlow server, but this browser tab has stopped waiting. Your custom classes may or may not have been written — the outcome is not yet known. Open your FlutterFlow project to reconcile before retrying the deploy."))}),!f.finalResultReceived)throw Wu(f)===Le.FAILED?new Error(f.error||`FlutterFlow custom class provisioning failed (HTTP ${f.httpStatus}).`):new Qe("The connection to the FlutterFlow deploy runner dropped before it reported a result. The deploy may still be finishing on the server; open your FlutterFlow project to reconcile before retrying.");if(!f.success){const h=f.details?` ${f.details}`:"",p=`${f.error||"FlutterFlow custom class provisioning failed."}${h}`;throw Wu(f)===Le.UNCONFIRMED?new Qe(`${p} The failure arrived after the deploy began — custom classes may already be written. Open your FlutterFlow project to reconcile before retrying.`):new Error(p)}}catch(h){throw h instanceof Qe&&sr(t),h}return sr(t),f.verificationSkipped&&(console.warn(`[custom class deploy] ${f.verificationSkipped}`),u.push(f.verificationSkipped)),{remoteFiles:n,syncFileMap:a_(e,o),unverified:u,approximate:c,provisionSucceeded:!0}}async function zl(t,e={}){const n=Gh(t);let i=za.get(n);if(i===void 0){try{i=await t.fetchProjectSource()}catch(l){throw new Error(`Could not read your project's pubspec.yaml (${l.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=wh(i.pubspecYaml);if(!a.valid)throw new Error(`Your project's pubspec.yaml could not be read reliably (${a.errors.join("; ")}). Deploy was stopped so your existing package dependencies aren't overwritten.`);za.set(n,i)}const r=await _y(i.pubspecYaml,e),s=G_(i.pubspecYaml,r.overrides),o=V_(s.yaml,r.additions);return r.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>`${a}: ${r.additions[a]||"any"}`).join(", "),r.sdk.dartSdkFloor?`(resolved for Dart ${r.sdk.dartSdkFloor})`:""),r.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:s.overridden,warnings:r.warnings,remoteFiles:i.files}}function k0(t){const e=[],n=[];t.content.length>5e4&&n.push("Code file is large (>50KB). This may take longer to commit."),t.content.length>1e5&&e.push("Code file is too large (>100KB). Consider splitting into smaller components.");const i=t.content.split(` + `)}let y={step1Result:null,step2Result:null,step3Result:null,bundleSpec:null,artifactBundle:null,bundleReview:null,selectedArtifactId:null,resultsViewMode:"summary",currentStep:0,isRunning:!1,runId:0,submittedPrompt:"",submittedImages:[]};function w0(){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 b0(){y.bundleSpec=er(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function Bs(){const t=ai(y.bundleSpec);y.artifactBundle=er(y.step2Result,{id:y.bundleSpec?.id,title:y.bundleSpec?.title,description:y.bundleSpec?.description,artifactType:t.artifactType,artifactName:t.artifactName,fileName:t.fileName,dependencies:t.dependencies,relationships:y.bundleSpec?.relationships,code:y.step2Result||""});const e=Vv(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(n=>n.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=ai(y.artifactBundle).id}function Ds(){const t=er(y.step3Result,{id:y.artifactBundle?.id,title:y.artifactBundle?.title}),e=new Map(t.artifacts.map(i=>[i.id,i.review])),n=new Map(t.artifacts.filter(i=>{const r=i.review;return r&&typeof r.fixedSource=="string"&&r.fixedSource.trim()}).map(i=>[i.id,i.review.fixedSource.trim()]));y.bundleReview=er({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(i=>{const r=n.get(i.id)||null;return{...i,review:e.get(i.id)||i.review||y.step3Result||null,...r?{fixedCode:r}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function Wh(){const t=Ol();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function Ol(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(n=>n.id===y.selectedArtifactId)||ai(t)}function Bl(){return Ol().code||y.step2Result||""}async function E0(){try{await Rl()}catch(t){return console.error("checkConnection: initializeApiKeys failed:",t),!1}return!0}const Dr={production:"https://api.flutterflow.io/v2/",staging:"https://api.flutterflow.io/v2-staging/"};function S0(t,e){const n=e?.trim()?` (${e.trim().slice(0,200)})`:"";return t===401?`Your FlutterFlow API key was rejected (401 Unauthorized)${n}. Re-enter a current key under API Keys settings, then try again.`:`Listing FlutterFlow projects was denied (403)${n}. The key may be scoped to sync a single project without list permission - verify the key's access in FlutterFlow, re-enter it under API Keys settings, then retry.`}class pi{constructor(e,n,i="main",r=Dr.production){this.apiKey=e,this.baseUrl=r,this._projectId=n,this._branchName=i,this._endpoint=r}get projectId(){return this._projectId}get branchName(){return this._branchName==="main"?"":this._branchName}async exportProjectZip(){console.log(`Exporting code from FlutterFlow project: ${this.projectId}, branch: ${this.branchName||"main"}`);const e=[{project:{path:`projects/${this.projectId}`},...this.branchName?{branch_name:this.branchName}:{},export_as_module:!1,include_assets_map:!1,format:!1,export_as_debug:!1},{project_id:this.projectId,branch_name:this.branchName,include_assets:!1,export_as_module:!1}];let n=null;for(const i of e)try{const r=await fetch(`${this.baseUrl}exportCode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(i)});if(!r.ok){const a=await r.text();n=new Error(`Export failed: ${r.status} - ${a}`);continue}const s=await r.json(),o=s?.value?.project_zip||s?.project_zip;if(!o){n=new Error("Export response did not include project source.");continue}return o}catch(r){n=r}throw n||new Error("Export failed for an unknown reason.")}async fetchProjectSource(){const e=await this.exportProjectZip(),n=await JSZip.loadAsync(e,{base64:!0}),i=Object.keys(n.files).filter(a=>!n.files[a].dir&&(a==="pubspec.yaml"||a.endsWith("/pubspec.yaml"))).sort((a,l)=>a.split("/").length-l.split("/").length)[0];if(!i)throw new Error("Export did not contain a pubspec.yaml.");const r=i.slice(0,i.length-12),s=new Map,o=Object.keys(n.files).filter(a=>{if(n.files[a].dir||!a.startsWith(r))return!1;const l=a.slice(r.length);return l==="lib/flutter_flow/custom_functions.dart"||l.startsWith("lib/custom_code/")&&l.endsWith(".dart")});return await Promise.all(o.map(async a=>{s.set(a.slice(r.length),await n.files[a].async("string"))})),{pubspecYaml:await n.files[i].async("string"),files:s}}async pushCodeWithRetry(e,n=3,i=null){const r=[Dr.production,Dr.staging],s=Math.max(0,r.indexOf(this._endpoint));let o=!1,a=null;for(let l=0;lsetTimeout(p,1e3*(l+1)));continue}if(d.ok)return console.log(`Push to ${c} succeeded!`),d;a=d.status;const f=d.status<500&&!o;if(Wa(f?d.clone():d,Sh).then(h=>console.log(`Push to ${c} returned ${d.status}: ${h}`),()=>console.log(`Push to ${c} returned ${d.status} (unreadable response body)`)),d.status>=500&&(o=!0),d.status===500){console.warn(`Endpoint ${c} returned 500, trying next...`),await new Promise(h=>setTimeout(h,1e3*(l+1)));continue}if(d.status>=500)throw new Qe(`FlutterFlow reported a server error (HTTP ${d.status}), which cannot prove the push was refused — the write may have been applied before the failure. Open your FlutterFlow project to reconcile before retrying.`);if(o)throw new Qe(`The push was refused (HTTP ${d.status}), but an earlier sync attempt may already have applied it — server errors and dropped responses cannot prove a refusal. Open your FlutterFlow project to reconcile before retrying.`);return d}throw Hu({httpStatus:a})}async pushCode(e,n=null){return this.pushCodeWithRetry(e,3,n)}parseProjectsResponse(e){if(e?.success&&typeof e.value=="string")try{const i=JSON.parse(e.value);if(i&&Array.isArray(i.entries))return i.entries.map(r=>({id:r.id,name:r.project?.name||r.id}))}catch(i){console.error("Failed to parse stringified project value:",i)}const n=e?.projects||e?.items||e?.entries||(Array.isArray(e)?e:[]);return Array.isArray(n)?n:[]}async listProjects(){console.log("Listing projects for API key");const e=[`${this.baseUrl}listProjects`,"https://api.flutterflow.io/v2/l/listProjects"];let n=0,i="";for(const r of e){const s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({project_type:"ALL",deserialize_response:!0})});if(s.ok)return r!==e[0]&&console.log(`listProjects answered on legacy path ${r}`),this.parseProjectsResponse(await s.json());if(n=s.status,i=await s.text(),console.warn(`listProjects via ${r} returned ${n}: ${i}`),s.status===401||s.status===403)throw new Error(S0(s.status,i));if(s.status!==404)throw new Error(`List projects failed: ${s.status} - ${i}`)}throw new Error(`List projects failed: ${n} - ${i}`)}}function Wa(t,e){const n=t.body?.getReader?.(),i=n?(async()=>{const r=new TextDecoder;let s="";for(;;){const{done:o,value:a}=await n.read();if(o)break;s+=r.decode(a,{stream:!0})}return s+r.decode()})():Promise.resolve("");return Ul(i,e,(r,s)=>{try{n?.cancel()?.catch?.(()=>{})}catch{}s(new Error("The response body stalled before it finished."))})}async function x0(t,e=Sh){const n=t.clone();let i;try{i=JSON.parse(await Wa(t,e))}catch{let o="";try{o=await Wa(n,e)}catch{}if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:o||`HTTP ${t.status}`,errorMap:new Map};throw new Qe(`FlutterFlow accepted the sync but returned an unreadable response${o?`: ${o.slice(0,200)}`:"."}`)}if(!t.ok){let s=i.message||`HTTP ${t.status}`,o=new Map;if(i.errors)o=new Map(Object.entries(i.errors));else if(!i.message&&typeof i=="object"){const a=Object.keys(i).filter(l=>l.endsWith(".dart")&&Array.isArray(i[l]));a.length>0&&(o=new Map(Object.entries(i)),s=a.flatMap(u=>i[u].map(c=>`${u}: ${c.errorMessage}`)).join(` +`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:s,errorMap:o}}let r={};if(i.value)try{r=typeof i.value=="string"?JSON.parse(i.value):i.value}catch(s){console.warn("Ignoring malformed push response value:",s)}return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(r))}}function Dl(t,e){return{401:"Authentication failed. Please check your FlutterFlow API key.",403:"Access denied. You may not have permission to modify this project.",404:"Project not found. Please check your Project ID.",409:"Conflict detected. The project may have been modified elsewhere.",422:"Validation failed: Invalid request format",429:"Rate limit exceeded. Please try again in a few minutes.",500:"FlutterFlow server error. Please try again later.",503:"FlutterFlow service temporarily unavailable."}[t]||`FlutterFlow API error: ${`HTTP ${t}`}`}const J={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},zh=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,qh=/extends\s+State<\w+>/;function I0(t,e=""){if(t==="pubspec.yaml")return J.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return J.OTHER;if(t==="custom_functions.dart")return J.FUNCTION;if(e){const n=zh.test(e),i=qh.test(e);if(n||i)return J.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return J.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return J.FUNCTION}return J.CODE_FILE}function Vh(t,e){switch(e){case J.ACTION:return`lib/custom_code/actions/${t}`;case J.WIDGET:return`lib/custom_code/widgets/${t}`;case J.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case J.CODE_FILE:return`lib/custom_code/${t}`;case J.DEPENDENCIES:return"pubspec.yaml";case J.OTHER:return`lib/custom_code/${t}`;default:return t}}async function jl(t,e=new Map){return Av(t,e)}const za=new Map;function Gh(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function Pn(t){za.delete(Gh(t))}function Ul(t,e,n){return new Promise((i,r)=>{let s=!1;const o=(l,u,c)=>{s||(s=!0,c==="resolve"?i(u):r(u))},a=setTimeout(()=>{s||(s=!0,n(i,r))},e);t.then(l=>{clearTimeout(a),o(i,l,"resolve")},l=>{clearTimeout(a),o(r,l,"reject")})})}async function Hl(t,e,n=Eh){const i={stop:!1};return Ul((async()=>{const r=await t.pushCode(e,i);return x0(r)})(),n,(r,s)=>{i.stop=!0,s(new Qe("FlutterFlow did not answer the sync in time — the push may still have been applied. The outcome is not yet known: open your FlutterFlow project to reconcile before retrying the deploy."))})}async function Wl(t,e,n,i,r="",s=Eh){const o=o_(e,n);if(o.length===0)return{remoteFiles:n,syncFileMap:e,unverified:[],approximate:[]};const a=X_(o,r),l={...a.manifest,sources:a.sources},u=a.skipped.map(p=>p.reason);u.forEach(p=>console.warn(`[custom class deploy] ${p}`));const c=a.approximate;c.forEach(p=>console.warn(`[custom class deploy] ${p}`)),console.log(`Provisioning ${o.length} new FlutterFlow custom code file(s) before sync.`),Be.set("provision");let d=!0,f,h;try{if(h=(async()=>{let p;try{p=await fetch(Py,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:i,customClasses:o,verification:l,stream:!0})})}catch{throw new Qe("The provisioning request did not return a response. The deploy may have reached the FlutterFlow server — open your FlutterFlow project to reconcile before retrying.")}return ey(p,{onPhase:g=>{d&&Be.setSubstatus(g)},onLog:g=>{d&&console.log(`[custom class deploy] ${g}`)}})})(),f=await Ul(h,s,(p,g)=>{d=!1,g(new Qe("The deploy is still working on the FlutterFlow server, but this browser tab has stopped waiting. Your custom classes may or may not have been written — the outcome is not yet known. Open your FlutterFlow project to reconcile before retrying the deploy."))}),!f.finalResultReceived)throw Wu(f)===Le.FAILED?new Error(f.error||`FlutterFlow custom class provisioning failed (HTTP ${f.httpStatus}).`):new Qe("The connection to the FlutterFlow deploy runner dropped before it reported a result. The deploy may still be finishing on the server; open your FlutterFlow project to reconcile before retrying.");if(!f.success){const p=f.details?` ${f.details}`:"",g=`${f.error||"FlutterFlow custom class provisioning failed."}${p}`;throw Wu(f)===Le.UNCONFIRMED?new Qe(`${g} The failure arrived after the deploy began — custom classes may already be written. Open your FlutterFlow project to reconcile before retrying.`):new Error(g)}}catch(p){throw p instanceof Qe&&(Pn(t),h?.then(()=>Pn(t),()=>Pn(t))),p}return Pn(t),f.verificationSkipped&&(console.warn(`[custom class deploy] ${f.verificationSkipped}`),u.push(f.verificationSkipped)),{remoteFiles:n,syncFileMap:a_(e,o),unverified:u,approximate:c,provisionSucceeded:!0}}async function zl(t,e={}){const n=Gh(t);let i=za.get(n);if(i===void 0){try{i=await t.fetchProjectSource()}catch(l){throw new Error(`Could not read your project's pubspec.yaml (${l.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=wh(i.pubspecYaml);if(!a.valid)throw new Error(`Your project's pubspec.yaml could not be read reliably (${a.errors.join("; ")}). Deploy was stopped so your existing package dependencies aren't overwritten.`);za.set(n,i)}const r=await _y(i.pubspecYaml,e),s=G_(i.pubspecYaml,r.overrides),o=V_(s.yaml,r.additions);return r.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>`${a}: ${r.additions[a]||"any"}`).join(", "),r.sdk.dartSdkFloor?`(resolved for Dart ${r.sdk.dartSdkFloor})`:""),r.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:s.overridden,warnings:r.warnings,remoteFiles:i.files}}function k0(t){const e=[],n=[];t.content.length>5e4&&n.push("Code file is large (>50KB). This may take longer to commit."),t.content.length>1e5&&e.push("Code file is too large (>100KB). Consider splitting into smaller components.");const i=t.content.split(` `).length;i>500&&n.push(`Code has ${i} lines. Consider breaking it into smaller widgets.`),t.content.includes("setState")&&t.codeType===J.ACTION&&n.push("Using setState in a Custom Action may not work as expected. Consider using a Custom Widget."),t.content.includes("dynamic")&&!t.content.includes("?")&&n.push('Code uses "dynamic" types. Consider adding explicit types for better null safety.'),t.content.match(/Color\(0xFF[0-9A-Fa-f]{6}\)/)&&n.push("Code contains hardcoded colors. Consider using FlutterFlowTheme.of(context) for theme consistency.");const r=t.content.match(/print\s*\(/g);r&&r.length>3&&n.push(`Code contains ${r.length} print statements. Consider removing debug prints before committing.`);const s=I_(t.content);if(s&&e.push(`FlutterFlow cannot format this code - ${s}. Fix or regenerate before committing.`),t.codeType===J.WIDGET){const o=dh(t.content),a=E_(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=`${fh(o[0])}`;e.push(`Widget class name "${o[0]}" does not match the file name "${t.fileName}". FlutterFlow derives the widget from the file name, so it will report "No widget ${a} found". Rename the file to "${l}" or the class to match before committing.`)}}return{canProceed:e.length===0,issues:e,warnings:n}}function Kh(t,e={}){const{artifactType:n="CustomWidget",artifactName:i="GeneratedCode",fileName:r}=e,s=w_(t);let o=r||i;if(n==="CustomFunction")o="custom_functions.dart";else if(n==="CustomWidget"){const u=dh(s)[0],c=u?fh(u):null;c&&o!==c?(console.warn(`Commit file name "${o}" does not match declared widget class "${u}"; renaming to "${c}" so FlutterFlow can find the widget.`),o=c):o.endsWith(".dart")||(o+=".dart")}else o.endsWith(".dart")||(o+=".dart");let a=J.CODE_FILE;switch(n){case"CustomAction":a=J.ACTION;break;case"CustomWidget":a=J.WIDGET;break;case"CustomFunction":a=J.FUNCTION;break;case"CustomClass":case"CodeFile":a=J.CODE_FILE;break}let l="";return a===J.WIDGET?l=`// Automatic FlutterFlow imports import '/flutter_flow/flutter_flow_theme.dart'; import '/flutter_flow/flutter_flow_util.dart'; @@ -111,15 +111,15 @@ import '/flutter_flow/lat_lng.dart'; import '/flutter_flow/place.dart'; import '/flutter_flow/uploaded_file.dart'; -`),{content:Yv(s,l),fileName:o,codeType:a,artifactType:n,artifactName:i}}function C0(t){const e={};for(const n of bl(t))e[n]="";return e}function A0(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 P0(t,e,n,i=new Set,r=""){const s=[],o=zh.test(e),a=qh.test(e);return n===J.WIDGET&&!o&&!a&&s.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:s.length===0,errors:s}}function js(t){const e=[],n=[];if(!t||t.size===0)return e.push("No files to commit"),{valid:!1,errors:e,warnings:n};const i=new Set(Array.from(t.values()).flatMap(r=>As(r.content||"")));for(const[r,s]of t.entries()){if((!s.content||s.content.trim().length===0)&&e.push(`File ${r} is empty`),s.content&&s.content.length>1e5&&n.push(`File ${r} is very large (>100KB)`),r.endsWith(".dart")){const o=P0(r,s.content,s.type,i,s.artifactName);o.valid||e.push(...o.errors.map(a=>`${r}: ${a}`))}if(r==="pubspec.yaml"){const o=wh(s.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:n}}const ee={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},G={currentState:ee.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=ee.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(ee).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===ee.PREPARING&&(this.startTime=Date.now()),(t===ee.SUCCESS||t===ee.ERROR)&&(this.endTime=Date.now()),typeof window<"u"&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("commitStateChange",{detail:{state:t,commitState:this}})),console.log(`Commit state changed to: ${t}`)},setError(t){this.error=t,this.setState(ee.ERROR)},setSuccess(t){this.result=t,this.setState(ee.SUCCESS)},setProgress(t,e){this.filesProcessed=t,this.totalFiles=e},getElapsedTime(){return this.startTime?(this.endTime||Date.now())-this.startTime:null},isInProgress(){return this.currentState===ee.PREPARING||this.currentState===ee.VALIDATING||this.currentState===ee.PUSHING}};async function F0(t,e,n={}){let{codeType:i="W"}=n;const{pubspecDeps:r={},artifactName:s=e}=n;i==="CustomWidget"&&(i=J.WIDGET),i==="CustomAction"&&(i=J.ACTION),i==="CustomFunction"&&(i=J.FUNCTION),i==="CustomClass"&&(i=J.CODE_FILE),i==="CodeFile"&&(i=J.CODE_FILE),G.reset(),G.setState(ee.PREPARING);try{const o=await Te("flutterflow"),a=await Te("flutterflow_project_id");if(!o||!a)throw new Error("FlutterFlow credentials not configured. Please set your API key and Project ID in the API Keys settings.");if(!Os(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=yt(),u=new hi(o,a,"main",l);G.setState(ee.VALIDATING);const c=new Map,d=i||I0(e,t),f=Vh(e,d);c.set(e,{artifactName:s,content:t,type:d,path:f}),G.setProgress(0,c.size);const h=js(c);if(!h.valid)throw new Error(`Validation failed: +`),{content:Yv(s,l),fileName:o,codeType:a,artifactType:n,artifactName:i}}function C0(t){const e={};for(const n of bl(t))e[n]="";return e}function A0(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 P0(t,e,n,i=new Set,r=""){const s=[],o=zh.test(e),a=qh.test(e);return n===J.WIDGET&&!o&&!a&&s.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:s.length===0,errors:s}}function js(t){const e=[],n=[];if(!t||t.size===0)return e.push("No files to commit"),{valid:!1,errors:e,warnings:n};const i=new Set(Array.from(t.values()).flatMap(r=>As(r.content||"")));for(const[r,s]of t.entries()){if((!s.content||s.content.trim().length===0)&&e.push(`File ${r} is empty`),s.content&&s.content.length>1e5&&n.push(`File ${r} is very large (>100KB)`),r.endsWith(".dart")){const o=P0(r,s.content,s.type,i,s.artifactName);o.valid||e.push(...o.errors.map(a=>`${r}: ${a}`))}if(r==="pubspec.yaml"){const o=wh(s.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:n}}const ee={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},G={currentState:ee.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=ee.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(ee).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===ee.PREPARING&&(this.startTime=Date.now()),(t===ee.SUCCESS||t===ee.ERROR)&&(this.endTime=Date.now()),typeof window<"u"&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("commitStateChange",{detail:{state:t,commitState:this}})),console.log(`Commit state changed to: ${t}`)},setError(t){this.error=t,this.setState(ee.ERROR)},setSuccess(t){this.result=t,this.setState(ee.SUCCESS)},setProgress(t,e){this.filesProcessed=t,this.totalFiles=e},getElapsedTime(){return this.startTime?(this.endTime||Date.now())-this.startTime:null},isInProgress(){return this.currentState===ee.PREPARING||this.currentState===ee.VALIDATING||this.currentState===ee.PUSHING}};async function F0(t,e,n={}){let{codeType:i="W"}=n;const{pubspecDeps:r={},artifactName:s=e}=n;i==="CustomWidget"&&(i=J.WIDGET),i==="CustomAction"&&(i=J.ACTION),i==="CustomFunction"&&(i=J.FUNCTION),i==="CustomClass"&&(i=J.CODE_FILE),i==="CodeFile"&&(i=J.CODE_FILE),G.reset(),G.setState(ee.PREPARING);try{const o=await Te("flutterflow"),a=await Te("flutterflow_project_id");if(!o||!a)throw new Error("FlutterFlow credentials not configured. Please set your API key and Project ID in the API Keys settings.");if(!Os(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=yt(),u=new pi(o,a,"main",l);G.setState(ee.VALIDATING);const c=new Map,d=i||I0(e,t),f=Vh(e,d);c.set(e,{artifactName:s,content:t,type:d,path:f}),G.setProgress(0,c.size);const h=js(c);if(!h.valid)throw new Error(`Validation failed: ${h.errors.join(` -`)}`);const p=await zl(u,r),g=p.yaml,m=await Wl(u,c,p.remoteFiles,`Provision ${s} custom class`,g),v=await jl(m.syncFileMap,m.remoteFiles),E=new Map(m.syncFileMap);E.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),Be.set("package");const S=await ql(E),_={project_id:a,zipped_custom_code:S,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};G.setState(ee.PUSHING),G.setProgress(1,c.size),sr(u),Be.set("push");const b=await Hl(u,_);if(b.success)G.setSuccess({fileCount:c.size,projectId:a,warnings:b.errorMap&&b.errorMap.size>0?Array.from(b.errorMap.entries()):[]});else{const k=b.errorMessage||Dl(b.responseCode),T=new Error(k);throw T.remoteRefusal=!0,T}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:p.added,unverified:m.unverified,approximate:m.approximate,warnings:b.errorMap?Array.from(b.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),G.setError(o),o instanceof Qe?{success:!1,unconfirmed:!0,error:o.message,state:G.currentState}:{success:!1,error:o.message,remoteRefusal:o.remoteRefusal===!0,state:G.currentState}}}async function ql(t){const e=new JSZip;for(const[n,i]of t.entries())e.file(n,i.content);return e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}async function R0(t,e={}){const{artifactType:n,artifactName:i,fileName:r,pipelineResult:s}=e;console.log(`Starting commit for ${i} (${n})`);let o=!1;const a={projectId:null,endpoint:yt(),artifactType:n,artifactName:i,fileName:r};try{G.setState(ee.PREPARING);const l=Kh(t,{artifactType:n,artifactName:i,fileName:r}),u=C0(l.content);console.log("Detected dependencies:",u),G.setState(ee.VALIDATING);const c=await Te("flutterflow"),d=zi||await Te("flutterflow_project_id");if(!c)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!d)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Os(d))throw new Error("Invalid FlutterFlow Project ID format.");a.projectId=d;const f=new Map;f.set(l.fileName,{artifactName:i,content:l.content,type:l.codeType,path:Vh(l.fileName,l.codeType),functionName:l.codeType===J.FUNCTION?i:void 0}),G.setProgress(0,f.size);const h=js(f);if(!h.valid)throw new Error(`File validation failed: +`)}`);const p=await zl(u,r),g=p.yaml,m=await Wl(u,c,p.remoteFiles,`Provision ${s} custom class`,g),v=await jl(m.syncFileMap,m.remoteFiles),E=new Map(m.syncFileMap);E.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),Be.set("package");const S=await ql(E),_={project_id:a,zipped_custom_code:S,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};G.setState(ee.PUSHING),G.setProgress(1,c.size),Pn(u),Be.set("push");const b=await Hl(u,_);if(b.success)G.setSuccess({fileCount:c.size,projectId:a,warnings:b.errorMap&&b.errorMap.size>0?Array.from(b.errorMap.entries()):[]});else{const k=b.errorMessage||Dl(b.responseCode),T=new Error(k);throw T.remoteRefusal=!0,T}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:p.added,unverified:m.unverified,approximate:m.approximate,warnings:b.errorMap?Array.from(b.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),G.setError(o),o instanceof Qe?{success:!1,unconfirmed:!0,error:o.message,state:G.currentState}:{success:!1,error:o.message,remoteRefusal:o.remoteRefusal===!0,state:G.currentState}}}async function ql(t){const e=new JSZip;for(const[n,i]of t.entries())e.file(n,i.content);return e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}async function R0(t,e={}){const{artifactType:n,artifactName:i,fileName:r,pipelineResult:s}=e;console.log(`Starting commit for ${i} (${n})`);let o=!1;const a={projectId:null,endpoint:yt(),artifactType:n,artifactName:i,fileName:r};try{G.setState(ee.PREPARING);const l=Kh(t,{artifactType:n,artifactName:i,fileName:r}),u=C0(l.content);console.log("Detected dependencies:",u),G.setState(ee.VALIDATING);const c=await Te("flutterflow"),d=qi||await Te("flutterflow_project_id");if(!c)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!d)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Os(d))throw new Error("Invalid FlutterFlow Project ID format.");a.projectId=d;const f=new Map;f.set(l.fileName,{artifactName:i,content:l.content,type:l.codeType,path:Vh(l.fileName,l.codeType),functionName:l.codeType===J.FUNCTION?i:void 0}),G.setProgress(0,f.size);const h=js(f);if(!h.valid)throw new Error(`File validation failed: ${h.errors.join(` -`)}`);h.warnings.length>0&&console.warn("Validation warnings:",h.warnings),G.setState(ee.PUSHING);const p=yt(),g=new hi(c,d,"main",p),m=await zl(g,u),v=m.yaml,E=await Wl(g,f,m.remoteFiles,`Provision ${i} custom class`,v);o=E.provisionSucceeded===!0;const S=await jl(E.syncFileMap,E.remoteFiles),_=new Map(E.syncFileMap);_.set("pubspec.yaml",{content:v,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Be.set("package");const b=await ql(_),k={project_id:d,zipped_custom_code:b,uid:`web_${Date.now()}`,branch_name:g.branchName,serialized_yaml:v,file_map:S.fileMapContents,functions_map:S.functionsMapContents};G.setProgress(1,f.size),sr(g),Be.set("push");const T=await Hl(g,k);if(T.success){const x={...A0(l,s),projectId:d};return G.setSuccess({...x,fileCount:f.size,warnings:T.errorMap?Array.from(T.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${l.fileName} to FlutterFlow`,metadata:x,targetIdentity:a,addedDependencies:m.added,unverified:E.unverified,approximate:E.approximate,warnings:T.errorMap?Array.from(T.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}else{const x=T.errorMessage||Dl(T.responseCode),F=new Error(x);throw F.errorMap=T.errorMap,F.remoteRefusal=!0,F}}catch(l){console.error("Commit execution failed:",l),G.setError(l);let u=new Map;if(l.errorMap)u=l.errorMap;else if(l.message&&l.message.includes("{"))try{const c=l.message.match(/\{[\s\S]*\}/);if(c){const d=JSON.parse(c[0]);u=new Map(Object.entries(d))}}catch(c){console.warn("Failed to parse error map from commit response:",c)}return l instanceof Qe?{success:!1,unconfirmed:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:o?{success:!1,partial:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:l.message,errorMap:u,remoteRefusal:l.remoteRefusal===!0,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function T0(t,e={}){const{pipelineResult:n}=e;let i=!1;const r={projectId:null,endpoint:yt(),artifactType:"Bundle",artifactName:t?.title,fileName:t?.fileEntries?`${t.fileEntries.length} artifacts`:"bundle"};try{if(G.setState(ee.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: +`)}`);h.warnings.length>0&&console.warn("Validation warnings:",h.warnings),G.setState(ee.PUSHING);const p=yt(),g=new pi(c,d,"main",p),m=await zl(g,u),v=m.yaml,E=await Wl(g,f,m.remoteFiles,`Provision ${i} custom class`,v);o=E.provisionSucceeded===!0;const S=await jl(E.syncFileMap,E.remoteFiles),_=new Map(E.syncFileMap);_.set("pubspec.yaml",{content:v,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Be.set("package");const b=await ql(_),k={project_id:d,zipped_custom_code:b,uid:`web_${Date.now()}`,branch_name:g.branchName,serialized_yaml:v,file_map:S.fileMapContents,functions_map:S.functionsMapContents};G.setProgress(1,f.size),Pn(g),Be.set("push");const T=await Hl(g,k);if(T.success){const x={...A0(l,s),projectId:d};return G.setSuccess({...x,fileCount:f.size,warnings:T.errorMap?Array.from(T.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${l.fileName} to FlutterFlow`,metadata:x,targetIdentity:a,addedDependencies:m.added,unverified:E.unverified,approximate:E.approximate,warnings:T.errorMap?Array.from(T.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}else{const x=T.errorMessage||Dl(T.responseCode),F=new Error(x);throw F.errorMap=T.errorMap,F.remoteRefusal=!0,F}}catch(l){console.error("Commit execution failed:",l),G.setError(l);let u=new Map;if(l.errorMap)u=l.errorMap;else if(l.message&&l.message.includes("{"))try{const c=l.message.match(/\{[\s\S]*\}/);if(c){const d=JSON.parse(c[0]);u=new Map(Object.entries(d))}}catch(c){console.warn("Failed to parse error map from commit response:",c)}return l instanceof Qe?{success:!1,unconfirmed:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:o?{success:!1,partial:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:l.message,errorMap:u,remoteRefusal:l.remoteRefusal===!0,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function T0(t,e={}){const{pipelineResult:n}=e;let i=!1;const r={projectId:null,endpoint:yt(),artifactType:"Bundle",artifactName:t?.title,fileName:t?.fileEntries?`${t.fileEntries.length} artifacts`:"bundle"};try{if(G.setState(ee.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: ${t.errors.join(` `)}`);const s=new Map(t.fileEntries.map(b=>[b.fileName,{artifactId:b.artifactId,artifactName:b.artifactName,content:b.content,type:b.type,path:b.path,functionName:b.type===J.FUNCTION?b.artifactName:void 0}]));G.setProgress(0,s.size);const o=js(s);if(!o.valid)throw new Error(`File validation failed: ${o.errors.join(` -`)}`);G.setState(ee.VALIDATING);const a=await Te("flutterflow"),l=zi||await Te("flutterflow_project_id");if(!a)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!l)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Os(l))throw new Error("Invalid FlutterFlow Project ID format.");r.projectId=l,G.setState(ee.PUSHING);const u=yt(),c=new hi(a,l,"main",u),d=await zl(c,t.dependencies),f=d.yaml,h=await Wl(c,s,d.remoteFiles,`Provision ${t.title} custom classes`,f);i=h.provisionSucceeded===!0;const p=await jl(h.syncFileMap,h.remoteFiles),g=new Map(h.syncFileMap);g.set("pubspec.yaml",{content:f,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Be.set("package");const m=await ql(g),v={project_id:l,zipped_custom_code:m,uid:`web_${Date.now()}`,branch_name:c.branchName,serialized_yaml:f,file_map:p.fileMapContents,functions_map:p.functionsMapContents};G.setProgress(1,s.size),sr(c),Be.set("push");const E=await Hl(c,v);if(E.success){const b={...n,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((k,T)=>k+T.content.length,0),projectId:l};return G.setSuccess({...b,fileCount:s.size,warnings:E.errorMap?Array.from(E.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:b,targetIdentity:r,addedDependencies:d.added,unverified:h.unverified,approximate:h.approximate,warnings:E.errorMap?Array.from(E.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}const S=E.errorMessage||Dl(E.responseCode),_=new Error(S);throw _.errorMap=E.errorMap,_.remoteRefusal=!0,_}catch(s){console.error("Bundle commit execution failed:",s),G.setError(s);const o=s.errorMap||new Map;return s instanceof Qe?{success:!1,unconfirmed:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:i?{success:!1,partial:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function $0(t,e=[]){const n=vl("architect");try{return await Ss("architect",Mh,mv(t),n,e)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Prompt Architect failed: ${i.message}`)}}async function Us(t,e,n=[],i){const r=vv(t),s=vl("generator",y.bundleSpec);try{return await Ss("generator",e,r,s,n)}catch(o){if(o.isModelArmor||o.isUsageLimit||o.isPipelineCancel)throw o;if(e!==kr){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,o.message),Bw(e,kr,i);try{return await Ss("generator",kr,r,s,n)}catch(a){throw a.isModelArmor||a.isUsageLimit||a.isPipelineCancel?a:new Error(`Code Generator failed: primary (${e}): ${o.message} | fallback (${kr}): ${a.message}`)}}throw new Error(`Code Generator failed: ${o.message}`)}}async function Hs(t,e=null){const n={...vl("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await Ss("review",Lh,_v(t),n)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Code Review failed: ${i.message}`)}}function bs(t,e){const n=document.getElementById(`step${t}-item`),i=document.getElementById(`step${t}-status`);!n||!i||(n.classList.remove("active","completed","error"),i.classList.remove("running","completed","error"),e==="active"?(n.classList.add("active"),i.classList.add("running"),i.innerHTML=` +`)}`);G.setState(ee.VALIDATING);const a=await Te("flutterflow"),l=qi||await Te("flutterflow_project_id");if(!a)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!l)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Os(l))throw new Error("Invalid FlutterFlow Project ID format.");r.projectId=l,G.setState(ee.PUSHING);const u=yt(),c=new pi(a,l,"main",u),d=await zl(c,t.dependencies),f=d.yaml,h=await Wl(c,s,d.remoteFiles,`Provision ${t.title} custom classes`,f);i=h.provisionSucceeded===!0;const p=await jl(h.syncFileMap,h.remoteFiles),g=new Map(h.syncFileMap);g.set("pubspec.yaml",{content:f,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Be.set("package");const m=await ql(g),v={project_id:l,zipped_custom_code:m,uid:`web_${Date.now()}`,branch_name:c.branchName,serialized_yaml:f,file_map:p.fileMapContents,functions_map:p.functionsMapContents};G.setProgress(1,s.size),Pn(c),Be.set("push");const E=await Hl(c,v);if(E.success){const b={...n,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((k,T)=>k+T.content.length,0),projectId:l};return G.setSuccess({...b,fileCount:s.size,warnings:E.errorMap?Array.from(E.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:b,targetIdentity:r,addedDependencies:d.added,unverified:h.unverified,approximate:h.approximate,warnings:E.errorMap?Array.from(E.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}const S=E.errorMessage||Dl(E.responseCode),_=new Error(S);throw _.errorMap=E.errorMap,_.remoteRefusal=!0,_}catch(s){console.error("Bundle commit execution failed:",s),G.setError(s);const o=s.errorMap||new Map;return s instanceof Qe?{success:!1,unconfirmed:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:i?{success:!1,partial:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function $0(t,e=[]){const n=vl("architect");try{return await Ss("architect",Mh,mv(t),n,e)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Prompt Architect failed: ${i.message}`)}}async function Us(t,e,n=[],i){const r=vv(t),s=vl("generator",y.bundleSpec);try{return await Ss("generator",e,r,s,n)}catch(o){if(o.isModelArmor||o.isUsageLimit||o.isPipelineCancel)throw o;if(e!==kr){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,o.message),Bw(e,kr,i);try{return await Ss("generator",kr,r,s,n)}catch(a){throw a.isModelArmor||a.isUsageLimit||a.isPipelineCancel?a:new Error(`Code Generator failed: primary (${e}): ${o.message} | fallback (${kr}): ${a.message}`)}}throw new Error(`Code Generator failed: ${o.message}`)}}async function Hs(t,e=null){const n={...vl("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await Ss("review",Lh,_v(t),n)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Code Review failed: ${i.message}`)}}function bs(t,e){const n=document.getElementById(`step${t}-item`),i=document.getElementById(`step${t}-status`);!n||!i||(n.classList.remove("active","completed","error"),i.classList.remove("running","completed","error"),e==="active"?(n.classList.add("active"),i.classList.add("running"),i.innerHTML=` `):e==="completed"?(n.classList.add("completed"),i.classList.add("completed"),i.innerHTML=` @@ -127,12 +127,12 @@ ${o.errors.join(` `):i.innerHTML=` - `)}function Ae(t,e){const n=document.getElementById(`step${t}-loading`),i=document.getElementById(`step${t}-result`);e?(n.classList.remove("hidden"),i.classList.add("hidden"),bs(t,"active")):(n.classList.add("hidden"),i.classList.remove("hidden"),bs(t,"completed"))}function M0(t){const e=document.getElementById(`${t}-content`),n=document.getElementById(`${t}-chevron`);e.classList.contains("open")?(e.classList.remove("open"),n&&(n.style.transform="rotate(0deg)")):(e.classList.add("open"),n&&(n.style.transform="rotate(180deg)"))}function L0(t){it(parseInt(t.replace("step","")))}function it(t){for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-item`);a&&a.classList.remove("active")}const e=document.getElementById(`step${t}-item`);e&&e.classList.add("active"),Nn();const n=document.getElementById("ready-state");n&&n.classList.add("hidden");for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-content`);a&&a.classList.add("hidden")}const i=document.getElementById(`step${t}-content`);i&&i.classList.remove("hidden");const r=document.getElementById("stage-title"),s={1:"Prompt Architect",2:"Code Generator",3:"Code Review"};r&&(r.textContent=s[t]||"Active Workflow Stage")}function N0(t){const e=document.getElementById(t);if(!e)return;const n=e.dataset.raw||e.textContent;navigator.clipboard.writeText(n).then(()=>{const r=e.closest(".code-container")?.querySelector(".copy-btn");r&&(r.classList.add("copied"),r.innerHTML=' Copied!',setTimeout(()=>{r.classList.remove("copied"),r.innerHTML=' Copy'},2e3))}).catch(i=>{console.warn("Failed to copy to clipboard:",i)})}function qa(t){const e=Va(t);console.log(`Step 1 (Prompt Architect): ${Gt(Mh)}`),console.log(e!==t?`Step 2 (Code Generator): ${Gt(t)} → ${Gt(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${Gt(t)}`),console.log(`Step 3 (Code Review): ${Gt(Lh)}`)}function Yh(){return{step1Result:y.step1Result,step2Result:y.step2Result,step3Result:y.step3Result,artifactBundle:y.artifactBundle,bundleReview:y.bundleReview,selectedArtifactId:y.selectedArtifactId}}function O0(t){if(!t)return;Object.assign(y,t),new Set((y.artifactBundle?.artifacts||[]).map(n=>n.id)).has(y.selectedArtifactId)||(y.selectedArtifactId=oi(y.artifactBundle)?.id||null)}const Jh="results-replacement-error";function B0(t,{stage:e=2,runId:n,retry:i}){if(!re(n))return;const r=document.getElementById(Jh);if(!r)return;const s=kh(t),o=document.getElementById("results-replacement-error-title"),a=document.getElementById("results-replacement-error-message"),l=document.getElementById("results-replacement-error-retry"),u=document.getElementById("results-replacement-error-upgrade");o&&(o.textContent=`${Vs[e]||"Regeneration"}: ${s.title}`),a&&(a.textContent=s.message),r.hidden=!1;let c=null;u&&(u.hidden=!s.canUpgrade,s.canUpgrade&&(u.textContent="View plans",u.onclick=()=>di(),c=u)),l&&(l.hidden=s.canUpgrade,s.canUpgrade||(l.onclick=()=>{Vl(),typeof i=="function"&&i()},l.textContent="Retry",c=l)),(c||r).focus({preventScroll:!0})}function Vl(){const t=document.getElementById(Jh);t&&(t.hidden=!0)}function Zh(t,{previous:e,stage:n,runId:i,retry:r}){re(i)&&(t.isUsageLimit&&un(),O0(e),cr(),nn(!0),ur(),eo(),B0(t,{stage:n,runId:i,retry:r}),rn())}async function Xh(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0;const e=Gs();Gl("standardRegenerate",y.step2Result,y.step1Result);const n=document.querySelectorAll(".btn-refine-action"),i=Yh();n.forEach(r=>{r.disabled=!0,r.innerHTML=` + `)}function Ae(t,e){const n=document.getElementById(`step${t}-loading`),i=document.getElementById(`step${t}-result`);e?(n.classList.remove("hidden"),i.classList.add("hidden"),bs(t,"active")):(n.classList.add("hidden"),i.classList.remove("hidden"),bs(t,"completed"))}function M0(t){const e=document.getElementById(`${t}-content`),n=document.getElementById(`${t}-chevron`);e.classList.contains("open")?(e.classList.remove("open"),n&&(n.style.transform="rotate(0deg)")):(e.classList.add("open"),n&&(n.style.transform="rotate(180deg)"))}function L0(t){it(parseInt(t.replace("step","")))}function it(t){for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-item`);a&&a.classList.remove("active")}const e=document.getElementById(`step${t}-item`);e&&e.classList.add("active"),On();const n=document.getElementById("ready-state");n&&n.classList.add("hidden");for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-content`);a&&a.classList.add("hidden")}const i=document.getElementById(`step${t}-content`);i&&i.classList.remove("hidden");const r=document.getElementById("stage-title"),s={1:"Prompt Architect",2:"Code Generator",3:"Code Review"};r&&(r.textContent=s[t]||"Active Workflow Stage")}function N0(t){const e=document.getElementById(t);if(!e)return;const n=e.dataset.raw||e.textContent;navigator.clipboard.writeText(n).then(()=>{const r=e.closest(".code-container")?.querySelector(".copy-btn");r&&(r.classList.add("copied"),r.innerHTML=' Copied!',setTimeout(()=>{r.classList.remove("copied"),r.innerHTML=' Copy'},2e3))}).catch(i=>{console.warn("Failed to copy to clipboard:",i)})}function qa(t){const e=Va(t);console.log(`Step 1 (Prompt Architect): ${Gt(Mh)}`),console.log(e!==t?`Step 2 (Code Generator): ${Gt(t)} → ${Gt(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${Gt(t)}`),console.log(`Step 3 (Code Review): ${Gt(Lh)}`)}function Yh(){return{step1Result:y.step1Result,step2Result:y.step2Result,step3Result:y.step3Result,artifactBundle:y.artifactBundle,bundleReview:y.bundleReview,selectedArtifactId:y.selectedArtifactId}}function O0(t){if(!t)return;Object.assign(y,t),new Set((y.artifactBundle?.artifacts||[]).map(n=>n.id)).has(y.selectedArtifactId)||(y.selectedArtifactId=ai(y.artifactBundle)?.id||null)}const Jh="results-replacement-error";function B0(t,{stage:e=2,runId:n,retry:i}){if(!re(n))return;const r=document.getElementById(Jh);if(!r)return;const s=kh(t),o=document.getElementById("results-replacement-error-title"),a=document.getElementById("results-replacement-error-message"),l=document.getElementById("results-replacement-error-retry"),u=document.getElementById("results-replacement-error-upgrade");o&&(o.textContent=`${Vs[e]||"Regeneration"}: ${s.title}`),a&&(a.textContent=s.message),r.hidden=!1;let c=null;u&&(u.hidden=!s.canUpgrade,s.canUpgrade&&(u.textContent="View plans",u.onclick=()=>fi(),c=u)),l&&(l.hidden=s.canUpgrade,s.canUpgrade||(l.onclick=()=>{Vl(),typeof i=="function"&&i()},l.textContent="Retry",c=l)),(c||r).focus({preventScroll:!0})}function Vl(){const t=document.getElementById(Jh);t&&(t.hidden=!0)}function Zh(t,{previous:e,stage:n,runId:i,retry:r}){re(i)&&(t.isUsageLimit&&un(),O0(e),cr(),nn(!0),ur(),eo(),B0(t,{stage:n,runId:i,retry:r}),rn())}async function Xh(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0;const e=Gs();Gl("standardRegenerate",y.step2Result,y.step1Result);const n=document.querySelectorAll(".btn-refine-action"),i=Yh();n.forEach(r=>{r.disabled=!0,r.innerHTML=` - Refining...`});try{Vl();const r=Ol(),s=r.id,o=yv({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,artifactId:r.id,userFeedback:"Fix the issues listed in the audit report."});Zs({runId:e}),Ft(2,e),it(2),Ae(2,!0);const a=await Us(o,t,[],e);if(!re(e))return;y.step2Result=a,Bs(),tn(2,e);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),it(3),Ft(3,e),Ae(3,!0);const c=await Hs(y.step2Result,y.step1Result);if(!re(e))return;y.step3Result=c,Ds(),tn(3,e),y.artifactBundle?.artifacts?.some(h=>h.id===s)?y.selectedArtifactId=s:y.selectedArtifactId=oi(y.artifactBundle)?.id||null;const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const f=Ls(y.step3Result);ur(u,f)}catch(r){if(console.error("Refinement failed:",r),!re(e))return;const s=Ms(r,{architect:2,generator:2,review:3});Zh(r,{previous:i,stage:s,runId:e,retry:Xh})}finally{n.forEach(r=>{r.disabled=!1,r.textContent="Refine & Regenerate"}),re(e)&&(y.isRunning=!1,rn())}}async function Gl(t,e,n){const i=`${_t}/connectFeedback`,r={type:t,code:e,input:n};try{const s=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok){const a=await s.text();return console.error(`callEndpoint failed: ${s.status} ${s.statusText}`,a),{success:!1,status:s.status,error:a}}const o=await s.json();return console.log("Telemetry success:",o),o}catch(s){return console.error("callEndpoint failed:",s),{success:!1,error:s.message}}}function D0(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function Qh(){const t=document.getElementById("ff-error-paste-input"),e=t?.value?.trim();if(!e){t?.focus(),t?.classList.add("ring-2","ring-red-400","border-red-300"),setTimeout(()=>t?.classList.remove("ring-2","ring-red-400","border-red-300"),2e3);return}if(!y.step2Result){Ee("No generated code found. Please run the full pipeline first.","warning");return}if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=Gs();Gl("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` + Refining...`});try{Vl();const r=Ol(),s=r.id,o=yv({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,artifactId:r.id,userFeedback:"Fix the issues listed in the audit report."});Zs({runId:e}),Ft(2,e),it(2),Ae(2,!0);const a=await Us(o,t,[],e);if(!re(e))return;y.step2Result=a,Bs(),tn(2,e);const l=document.getElementById("step2-output"),u=ci(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),it(3),Ft(3,e),Ae(3,!0);const c=await Hs(y.step2Result,y.step1Result);if(!re(e))return;y.step3Result=c,Ds(),tn(3,e),y.artifactBundle?.artifacts?.some(h=>h.id===s)?y.selectedArtifactId=s:y.selectedArtifactId=ai(y.artifactBundle)?.id||null;const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const f=Ls(y.step3Result);ur(u,f)}catch(r){if(console.error("Refinement failed:",r),!re(e))return;const s=Ms(r,{architect:2,generator:2,review:3});Zh(r,{previous:i,stage:s,runId:e,retry:Xh})}finally{n.forEach(r=>{r.disabled=!1,r.textContent="Refine & Regenerate"}),re(e)&&(y.isRunning=!1,rn())}}async function Gl(t,e,n){const i=`${_t}/connectFeedback`,r={type:t,code:e,input:n};try{const s=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok){const a=await s.text();return console.error(`callEndpoint failed: ${s.status} ${s.statusText}`,a),{success:!1,status:s.status,error:a}}const o=await s.json();return console.log("Telemetry success:",o),o}catch(s){return console.error("callEndpoint failed:",s),{success:!1,error:s.message}}}function D0(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function Qh(){const t=document.getElementById("ff-error-paste-input"),e=t?.value?.trim();if(!e){t?.focus(),t?.classList.add("ring-2","ring-red-400","border-red-300"),setTimeout(()=>t?.classList.remove("ring-2","ring-red-400","border-red-300"),2e3);return}if(!y.step2Result){Ee("No generated code found. Please run the full pipeline first.","warning");return}if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=Gs();Gl("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` - Fixing…`);const s=Yh();try{Vl();const o=oh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});Cp(),Zs({runId:i}),Ft(2,i),it(2),Ae(2,!0);const a=await Us(o,n,[],i);if(!re(i))return;y.step2Result=a,Bs(),tn(2,i);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),it(3),Ft(3,i),Ae(3,!0);const c=await Hs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,Ds(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const f=Ls(y.step3Result);ur(u,f),t&&(t.value="")}catch(o){if(console.error("Fix from errors failed:",o),!re(i))return;const a=Ms(o,{architect:2,generator:2,review:3});Zh(o,{previous:s,stage:a,runId:i,retry:Qh})}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function or(){if(console.log("runThinkingPipeline called"),y.isRunning)return;localStorage.setItem("hasSeenWalkthrough","true");const t=document.getElementById("pipeline-input").value,e=document.getElementById("code-generator-model").value,n=Oe.slice();if(!t.trim()){Ee("Please describe your FlutterFlow widget first.","warning");return}y.isRunning=!0;const i=Gs();try{if(await Oa,!re(i)||(pn.length&&await Promise.allSettled(pn.map(v=>v.job)),!re(i))||!await cw()||!re(i)||(await iw(),!re(i)))return;const r=Va(e);t.length,w0(),y.submittedPrompt=t,y.submittedImages=n.filter(v=>v.url),Ya(!0),qa(r),Nn();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const o=document.getElementById("paywall-exhausted");o&&o.classList.add("hidden"),Zs({prompt:t,runId:i}),Hw(),it(1),Ft(1,i),Ae(1,!0);const a=y.submittedImages.map(v=>({url:v.url})),l=await $0(t,a);if(!re(i))return;y.step1Result=l,b0(),tn(1,i);const u=document.getElementById("step1-output"),c=li(y.step1Result);u.textContent=c,u.dataset.raw=c,Ae(1,!1),it(2),Ft(2,i),Ae(2,!0);const d=await Us(y.step1Result,r,a,i);if(!re(i))return;y.step2Result=d,Bs(),tn(2,i);const f=document.getElementById("step2-output"),h=li(y.step2Result);f.textContent=h,f.dataset.raw=h,Ae(2,!1),it(3),Ft(3,i),Ae(3,!0);const p=await Hs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=p,Ds(),tn(3,i);const g=document.getElementById("step3-output");g.textContent=y.step3Result,Ae(3,!1),cr();const m=Ls(y.step3Result);Ww(),ur(h,m)}catch(r){if(r.isPipelineCancel||console.error("Pipeline failed:",r),!re(i))return;const s=Ms(r,{architect:1,generator:2,review:3});r.isUsageLimit?un():(r.message,Va(document.getElementById("code-generator-model").value),void 0),it(s),Ae(s,!1),Sp(r,{stage:s,runId:i}),bs(s,"error")}finally{re(i)&&(y.isRunning=!1,Ya(!1),rn())}}function j0(){const t=document.getElementById("code-generator-model").value,e=[ms,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(i=>i!==t),n=prompt(`Retry with different model? + Fixing…`);const s=Yh();try{Vl();const o=oh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});Cp(),Zs({runId:i}),Ft(2,i),it(2),Ae(2,!0);const a=await Us(o,n,[],i);if(!re(i))return;y.step2Result=a,Bs(),tn(2,i);const l=document.getElementById("step2-output"),u=ci(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),it(3),Ft(3,i),Ae(3,!0);const c=await Hs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,Ds(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const f=Ls(y.step3Result);ur(u,f),t&&(t.value="")}catch(o){if(console.error("Fix from errors failed:",o),!re(i))return;const a=Ms(o,{architect:2,generator:2,review:3});Zh(o,{previous:s,stage:a,runId:i,retry:Qh})}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function or(){if(console.log("runThinkingPipeline called"),y.isRunning)return;localStorage.setItem("hasSeenWalkthrough","true");const t=document.getElementById("pipeline-input").value,e=document.getElementById("code-generator-model").value,n=Oe.slice();if(!t.trim()){Ee("Please describe your FlutterFlow widget first.","warning");return}y.isRunning=!0;const i=Gs();try{if(await Oa,!re(i)||(pn.length&&await Promise.allSettled(pn.map(v=>v.job)),!re(i))||!await cw()||!re(i)||(await iw(),!re(i)))return;const r=Va(e);t.length,w0(),y.submittedPrompt=t,y.submittedImages=n.filter(v=>v.url),Ya(!0),qa(r),On();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const o=document.getElementById("paywall-exhausted");o&&o.classList.add("hidden"),Zs({prompt:t,runId:i}),Hw(),it(1),Ft(1,i),Ae(1,!0);const a=y.submittedImages.map(v=>({url:v.url})),l=await $0(t,a);if(!re(i))return;y.step1Result=l,b0(),tn(1,i);const u=document.getElementById("step1-output"),c=ci(y.step1Result);u.textContent=c,u.dataset.raw=c,Ae(1,!1),it(2),Ft(2,i),Ae(2,!0);const d=await Us(y.step1Result,r,a,i);if(!re(i))return;y.step2Result=d,Bs(),tn(2,i);const f=document.getElementById("step2-output"),h=ci(y.step2Result);f.textContent=h,f.dataset.raw=h,Ae(2,!1),it(3),Ft(3,i),Ae(3,!0);const p=await Hs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=p,Ds(),tn(3,i);const g=document.getElementById("step3-output");g.textContent=y.step3Result,Ae(3,!1),cr();const m=Ls(y.step3Result);Ww(),ur(h,m)}catch(r){if(r.isPipelineCancel||console.error("Pipeline failed:",r),!re(i))return;const s=Ms(r,{architect:1,generator:2,review:3});r.isUsageLimit?un():(r.message,Va(document.getElementById("code-generator-model").value),void 0),it(s),Ae(s,!1),Sp(r,{stage:s,runId:i}),bs(s,"error")}finally{re(i)&&(y.isRunning=!1,Ya(!1),rn())}}function j0(){const t=document.getElementById("code-generator-model").value,e=[ms,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(i=>i!==t),n=prompt(`Retry with different model? Current: ${t} @@ -164,10 +164,10 @@ ${a.content}`).join(` Error: ${g} `}else s+=`${t} -`;const o=oh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:s});Zs({runId:i}),Ft(2,i),it(2),Ae(2,!0);const a=await Us(o,n,[],i);if(!re(i))return;y.step2Result=a,Bs(),tn(2,i);const l=document.getElementById("step2-output"),u=li(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),it(3),Ft(3,i),Ae(3,!0);const c=await Hs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,Ds(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const f=Ls(y.step3Result);ur(u,f)}catch(s){if(console.error("Regeneration failed:",s),!re(i))return;const o=Ms(s,{architect:2,generator:2,review:3});s.isUsageLimit&&un(),it(o),Ae(o,!1),Sp(s,{stage:o,runId:i,retry:()=>ep(t,e)}),bs(o,"error")}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function z0(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const n=await Te("flutterflow"),i=await Te("flutterflow_project_id");n&&i?(t.className="w-2 h-2 rounded-full bg-green-500",e.textContent="FlutterFlow credentials configured",e.className="text-green-600"):n||i?(t.className="w-2 h-2 rounded-full bg-yellow-500",e.textContent="FlutterFlow credentials incomplete",e.className="text-yellow-600"):(t.className="w-2 h-2 rounded-full bg-red-500",e.textContent="FlutterFlow credentials not configured",e.className="text-red-600")}async function tp(t){try{const e=await fetch(`${_t}/auth/send-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:t})});if(!e.ok)throw new Error(`Failed to send magic link: HTTP ${e.status}`);return e.json()}catch(e){throw console.error("sendMagicLink failed:",{email:t,message:e.message,stack:e.stack}),e}}async function q0(t){try{const n=await(await fetch(`${_t}/auth/verify-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})})).json();if(n.error||!n.email||!n.sessionToken)throw new Error(n.error||"Invalid or expired link");return n}catch(e){throw console.error("verifyMagicLink failed:",{message:e.message,stack:e.stack}),e}}async function V0(t){try{const e=await fetch(`${_t}/auth/refresh-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:t})});if(!e.ok)return console.error("refreshSession: non-OK response",{url:`${_t}/auth/refresh-session`,status:e.status}),null;const n=await e.json();return n.error||!n.email||!n.sessionToken?(console.warn("refreshSession: validation failed",{error:n.error,hasEmail:!!n.email,hasToken:!!n.sessionToken}),null):n}catch(e){return console.error("refreshSession: fetch failed",{url:`${_t}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function sd(t,e){const n=ip(),i=(q.email||n.email)!==t;q.email=t,q.sessionToken=e,q.isVerified=!0,ce=Mn({isLoading:!0}),localStorage.setItem(hs,JSON.stringify({email:t,sessionToken:e})),i&&cp()}function np(){q.email=null,q.sessionToken=null,q.isVerified=!1,ce=Mn({isResolved:!0}),localStorage.removeItem(hs),localStorage.removeItem(gs)}function ip(){try{const t=localStorage.getItem(hs);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(hs),{email:null,sessionToken:null}}}async function G0(){const e=new URLSearchParams(window.location.search).get("token");if(e){window.history.replaceState({},"",window.location.pathname+window.location.hash);try{const{email:n,sessionToken:i}=await q0(e);sd(n,i),rp();const r=od();r&&!window.location.hash&&(window.location.hash=r)}catch(n){od();const i=n.message||"Sign-in link invalid or expired.";Ee(i,"error"),Ws(),Jn(i,"error")}}else{const{email:n,sessionToken:i}=ip();if(n&&i){const r=await V0(i);r?sd(r.email,r.sessionToken):np()}}Kl()}function K0(){try{localStorage.setItem(Na,JSON.stringify({hash:window.location.hash||"#home",ts:Date.now()}))}catch(t){console.warn("rememberSignInReturnSurface: failed to persist return surface:",t)}}function od(){try{const t=localStorage.getItem(Na);if(localStorage.removeItem(Na),!t)return null;const{hash:e,ts:n}=JSON.parse(t);return!e||typeof n!="number"||Date.now()-n>Fy?null:e}catch(t){return console.warn("consumeSignInReturnSurface: failed to read return surface:",t),null}}function Ws(){const t=document.getElementById("signin-modal");if(!t)return;K0(),document.getElementById("signin-email-input")?.removeAttribute("aria-invalid"),Jn(""),We(t)}function rp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&ze(e)}function Jn(t,e){const n=document.getElementById("signin-message");n&&(n.textContent=t||"",n.classList.remove("signin-message-success","signin-message-error"),e&&n.classList.add(`signin-message-${e}`))}async function Y0(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),n=Fs(t?.value);if(!n||!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(n)||n.length>254){t?.setAttribute("aria-invalid","true"),Jn("Please enter a valid email address.","error");return}t?.removeAttribute("aria-invalid"),e&&(e.disabled=!0,e.textContent="Sending…");const r=ph(n);r&&Jn(r,"error");try{const s=await tp(n),o=s?.code===hh;t&&!o&&(t.value=""),t?.setAttribute("aria-invalid",String(o)),Jn(gh(s,n),o?"error":"success"),e&&(e.disabled=!1,e.textContent=o?"Send Sign-in Link":"Sent!",o||setTimeout(()=>{e.textContent==="Sent!"&&(e.textContent="Send Sign-in Link")},2500))}catch(s){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:n,err:s}),Jn("Something went wrong. Please try again.","error"),e&&(e.disabled=!1,e.textContent="Send Sign-in Link")}}function J0(){q.email=null,q.sessionToken=null,q.isVerified=!1,ce=Mn({isResolved:!0}),D_({storage:window.localStorage,onIdentityChanged:Kl,onPlanChanged:qs})}const Z0=j_({sendLink:tp,getEmail:()=>q.email||"",onState:X0});function X0(t){const e=document.getElementById("send-new-link-btn"),n=document.getElementById("send-new-link-msg");if(!e||!n)return;if(t.status==="pending"){e.disabled=!0,e.textContent="Sending…",n.className="acct-access-msg",n.textContent="Sending a fresh sign-in link…";return}if(t.status==="sent"){e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg",n.textContent=gh(t.data,q.email||"")||"Link sent — check your email.";return}e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg error";const i=t.error?.message?`Couldn't send a link right now. ${t.error.message}`:"Couldn't send a link right now. Please try again.";n.textContent=i}async function Q0(){await Z0()}function ew(){const t=O_(window.localStorage),e=t.length?`Cleared disposable UI caches: ${t.join(", ")}.`:"Nothing disposable to clear.";Ee(`${e} Your run count, identity and stored keys are kept.`,"info")}function tw(){const t=document.getElementById("delete-unavailable-modal");t&&We(t,{trigger:document.activeElement})}function nw(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("delete-unavailable-modal");e&&ze(e)}function Kl(){const t=q.isVerified&&!!q.email,e=document.getElementById("auth-signedout"),n=document.getElementById("auth-signedin"),i=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),n&&n.classList.toggle("hidden",!t),i&&i.classList.toggle("hidden",t);const r=document.getElementById("auth-user-email");r&&(r.textContent=q.email||"");const s=document.getElementById("access-signed-email");s&&(s.textContent=q.email||""),fw(),qs()}async function sp(){try{if(typeof FingerprintJS>"u"){console.warn("resolveIdentity: FingerprintJS not loaded, skipping");return}const e=await(await FingerprintJS.load()).get(),n=e.visitorId,i=await fetch(My,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fingerprint:e.visitorId,cookie_id:n})});if(!i.ok)throw new Error(`Identity check HTTP ${i.status}`);const r=await i.json();if(ht.userId=r.user_id,ht.token=r.identity_token||null,ht.status=r.status,ht.resolved=!0,sessionStorage.setItem(Ty,r.user_id),ht.token&&sessionStorage.setItem($y,ht.token),r.usage_count!==void 0){const s=gn(),a=(r.usage_month||s)===s?r.usage_count:0;localStorage.setItem(Fn,JSON.stringify({count:a,month:s})),un()}console.log(`Identity resolved: ${r.status} (${r.user_id.slice(0,8)}...) usage: ${r.usage_count??"n/a"}`)}catch(t){console.error("resolveIdentity failed:",t)}}let Wo=null;function iw(t=5e3){return ht.resolved?Promise.resolve():(Wo||(Wo=sp().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([Wo,new Promise(e=>setTimeout(e,t))]))}function op(){const t=gn();try{const e=localStorage.getItem(Fn);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Fn,month:t,err:e}),localStorage.removeItem(Fn),{count:0,month:t}}}function gn(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function lr(){const t=op();return t.month!==gn()?{count:0,month:gn()}:t}function rw(){const e={count:lr().count+1,month:gn()};return localStorage.setItem(Fn,JSON.stringify(e)),e}function pi(){return!!ce.isLoading}function Tt(){return!!ce.isResolved}function sw(t){if(!t)return null;const e=String(t).toLowerCase().replace(/[^a-z0-9]+/g,"_");return e==="pro"||e==="professional_plan"?"professional":e==="power_developer"||e==="power_plan"?"power":Object.prototype.hasOwnProperty.call(ps,e)?e:null}function ow(t){return t&&Object.entries(Ah).find(([,e])=>e===t)?.[0]||null}function Cr(...t){return t.find(e=>e!=null&&e!=="")}function aw(...t){return t.find(e=>e&&typeof e=="object")||{}}function lw(t){const e=t.data&&typeof t.data=="object"?t.data:t,n=aw(e.subscription,e.stripeSubscription,e.currentSubscription,e.customer?.subscriptions?.data?.[0],e.subscriptions?.data?.[0],e.subscriptions?.[0]),i=e.metadata||n.metadata||e.customer?.metadata||{},r=Cr(e.priceId,e.price_id,e.stripePriceId,e.stripe_price_id,n.priceId,n.price_id,n.plan?.id,n.price?.id,n.items?.data?.[0]?.price?.id,n.items?.[0]?.price?.id,n.lines?.data?.[0]?.price?.id),s=Cr(e.status,e.subscriptionStatus,e.subscription_status,n.status,"none"),o=sw(Cr(e.tier,e.plan,e.planId,e.plan_id,e.subscriptionTier,e.subscription_tier,e.product,e.productName,n.tier,n.plan,i.tier,i.plan)),a=Ly.has(String(s).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||ow(r)||(a||l?"professional":"free");return Mn({tier:u,status:s,periodEnd:Cr(e.periodEnd,e.currentPeriodEnd,e.current_period_end,n.current_period_end,n.periodEnd,null),isResolved:!0})}function zs(){return ps[ce.tier]??ps.free}async function cw(){if(q.isVerified&&(!Tt()||pi())&&(await lp({force:!0}),qs()),q.isVerified&&!Tt())return Ee("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=lr(),e=zs();if(t>=e)return ap(t,e,{openModal:!0}),!1;const n=Math.floor(e*.8);if(t>=n){const i=e-t;Ee(`${i} run${i===1?"":"s"} remaining this month.`,"warning")}return!0}function ad(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function ap(t,e,n={}){nn(!0);const i=document.getElementById("walkthrough-modal");i&&ze(i,{restoreFocus:!1});const r=document.getElementById("ready-state");r&&r.classList.add("hidden");const s=document.getElementById("preview-frame-container");s&&(s.style.display="none");const o=document.getElementById("main-stage-container");o&&o.classList.add("visible");const a=document.getElementById("results-view");a&&a.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar");const l=document.getElementById("pipeline-progress");l&&l.classList.remove("visible");const u=document.getElementById("paywall-exhausted");if(!u){Ee(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),di();return}const c=document.getElementById("paywall-exhausted-text");if(c){const f=ce.tier;f==="free"?c.textContent=`You've used all ${e} free generations this month. Upgrade to Pro for 50 generations/month and access to all AI models.`:c.textContent=`You've used all ${e} generations this month on your ${f} plan. Your limit resets next month.`}const d=document.getElementById("paywall-signin-btn");d&&d.classList.toggle("hidden",q.isVerified),u.classList.remove("hidden"),n.openModal&&di()}function Va(t){return ce.tier==="free"&&Nr.includes(t)?ms:t}function uw(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const n=ce.tier,r=!(q.isVerified&&!Tt())&&n==="free";Array.from(e.options).forEach(o=>{const a=Gt(o.value),l=Nr.includes(o.value);o.textContent=l&&r?`${a} (PRO)`:a,o.disabled=!1}),r&&Nr.includes(e.value)&&(e.value=ms),e.disabled=!1,Ku.has(e)||(e.addEventListener("change",()=>{Tt()&&ce.tier==="free"&&Nr.includes(e.value)&&(e.value=ms,di()),qa(e.value),Cl()}),Ku.add(e));let s=document.getElementById("model-selector-free-notice");r?(s||(s=document.createElement("p"),s.id="model-selector-free-notice",s.className="text-xs text-gray-400 mt-1",t.appendChild(s)),s.innerHTML='Free plan — Gemini only. '):s&&s.remove(),qa(e.value)}function Yl(){const t=q.isVerified&&!!q.email,e=t&&pi(),n=!t||Tt(),i=lr(),r=n?i.count:0,s=n?zs():0,o=Math.max(0,s-r),a=`${r} / ${s} runs this month`,l=ml,u=n?ce.tier||"free":null,c=document.getElementById("topbar-credits-count");c&&(e?c.textContent="…":n?c.textContent=String(o):c.textContent="—");const d=document.getElementById("credits-balance");d&&(e?d.textContent="Checking plan…":n?d.textContent=a:d.textContent="Plan check failed");const f=document.getElementById("usage-dialog-tier");f&&(e?f.textContent="Checking…":n?f.textContent=l[u]||"Free":f.textContent="Unavailable");const h=document.getElementById("usage-dialog-status");h&&(e?h.textContent="Verifying your subscription…":n?h.textContent="Runs reset at the start of each month.":h.textContent="Could not verify your subscription. Try again or sign out.");const p=document.getElementById("usage-counter");if(p)if(e&&t)p.textContent="Checking plan…",p.className="text-xs text-gray-500";else if(!n&&t)p.textContent="Plan check failed",p.className="text-xs text-red-600 font-medium";else{p.textContent=a;const g=s>0?r/s:0;p.className=g>=1?"text-xs text-red-600 font-medium":g>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500"}if(!t){const g=document.getElementById("guest-usage-text");if(g){const m=op(),v=m.month===gn()?m.count??0:0;g.textContent=`${v} / ${ps.free} generations used`}}dw()}function dw(){if(!(q.isVerified&&!!q.email))return;const e=pi(),n=Tt(),i=lr(),r=n?i.count:0,s=n?zs():0,o=Math.max(0,s-r),a=n?ce.tier||"free":null,l={free:"Free",professional:"Pro",power:"Power"}[a]||"Free",u=q.email||"",c=u.split("@")[0]||u,d=document.getElementById("acct-avatar");d&&(d.textContent=(u[0]||"?").toUpperCase());const f=document.getElementById("acct-name");f&&(f.textContent=c||"—");const h=document.getElementById("acct-plan-tier"),p=document.getElementById("acct-plan-price"),g=document.getElementById("acct-plan-note"),m=document.getElementById("acct-renewal");if(h&&(h.textContent=e?"Checking…":n?l:"Plan unavailable"),p)if(e)p.textContent="—";else if(!n)p.textContent="—";else if(a==="free")p.textContent="$0 / month";else{const x=Oi(Ni[a]??0,Al());p.textContent=`${x} / month`}if(g&&(e?g.textContent="Verifying your subscription…":n?a==="free"?g.textContent="No subscription. Upgrade for more generations.":g.textContent="billed monthly through Stripe":g.textContent="Could not verify your subscription. Check billing or sign out."),m){const x=Date.parse(ce.periodEnd||""),F=n&&a!=="free"&&!!ce.periodEnd&&!Number.isNaN(x);if(e)m.textContent="";else if(!n)m.textContent="";else if(a==="free")m.textContent="";else if(F){const $=new Date(x).toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"});m.textContent=`Renews ${$} · reset at the start of each month.`}else m.textContent="Renewal date is not available for this period."}const v=document.getElementById("acct-left-count"),E=document.getElementById("acct-left-limit"),S=document.getElementById("acct-reset-note");v&&(v.textContent=e?"…":n?String(o):"—"),E&&(E.textContent=e?"…":n?String(s):"—"),S&&(e?S.textContent="Checking plan…":n?S.textContent="Runs reset at the start of each month.":S.textContent="Plan check failed. Refresh or manage billing.");const _=document.getElementById("acct-used-count"),b=document.getElementById("acct-meter-fill"),k=document.getElementById("acct-meter-meta"),T=document.getElementById("acct-meter-track");if(_&&(_.textContent=e?"…":n?String(r):"—"),b){const x=n&&s>0?Math.min(100,Math.round(r/s*100)):0;b.style.width=`${x}%`}if(k)if(e)k.textContent="Checking…";else if(!n)k.textContent="Plan check failed";else if(s===0)k.textContent=`${r} of ${s}`;else{const x=Math.round(r/s*100);k.textContent=`${r} of ${s} · ${x}%`}T&&(e?T.setAttribute("aria-label","Checking usage…"):n?T.setAttribute("aria-label",`${r} of ${s} generations used`):T.setAttribute("aria-label","Usage unavailable")),vt()}function un(){if(Yl(),q.isVerified&&(pi()||!Tt())){ad();return}const{count:t}=lr(),e=zs();t>=e&&!y.isRunning?ap(t,e):ad()}function fw(){Yl()}async function lp(t={}){const e=t.force===!0;if(!q.isVerified||!q.sessionToken){ce=Mn({isResolved:!0});return}ce={...ce,isLoading:!0,error:null};const n=localStorage.getItem(gs);if(!e&&n)try{const{data:i,email:r,ts:s,version:o}=JSON.parse(n);if(o===Yu&&r===q.email&&Date.now()-s<300*1e3){ce={...i,isLoading:!1,isResolved:i.isResolved!==!1};return}}catch(i){console.warn("Failed to parse subscription cache:",i,"| raw value:",n)}try{const r=await(await fetch(`${_t}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:q.sessionToken,user_id:ht.userId})})).json();if(r.error){if(["unauthorized","invalid session","expired session"].some(o=>String(r.error).toLowerCase().includes(o))){np(),Kl();return}ce=Mn({isResolved:!1,error:r.error});return}ce=lw(r),localStorage.setItem(gs,JSON.stringify({version:Yu,data:ce,email:q.email,ts:Date.now()}))}catch(i){console.error("fetchSubscription failed:",i),ce={...ce,isLoading:!1,isResolved:!1,error:i.message}}}function cp(){localStorage.removeItem(gs)}async function hw(t){if(!q.isVerified||!q.sessionToken){up(),Ws();return}if(!Ah[t]){Ee("Invalid plan selected.","error");return}const e=document.getElementById(`checkout-btn-${t}`);e&&(e.disabled=!0,e.textContent="Redirecting…");try{const i=await(await fetch(`${_t}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:q.sessionToken,currency:Al()})})).json();if(i.error||!i.url)throw new Error(i.error||"Failed to create checkout session");const{url:r}=i;window.location.href=r}catch(n){console.error("startCheckout failed:",n),e&&(e.disabled=!1,e.textContent="Subscribe"),Ee("Could not start checkout. Please try again.","error")}}async function pw(t){if(!q.isVerified||!q.sessionToken){Ws();return}const e=t||document.getElementById("manage-billing-btn"),n=e?e.textContent:"";e&&(e.disabled=!0,e.textContent="Loading…");try{const r=await(await fetch(`${_t}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:q.sessionToken})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to open billing portal");const{url:s}=r;window.location.href=s}catch(i){console.error("openCustomerPortal failed:",i),e&&(e.disabled=!1,e.textContent=n),Ee("Could not open billing portal. Please try again.","error")}}const Es=new Set;function gw(){Es.forEach(t=>t.abort()),Es.clear()}async function Ss(t,e,n,i={},r=[]){const o=new AbortController;Es.add(o);let a=!1;const l=setTimeout(()=>{a=!0,o.abort()},12e4);try{const u=await fetch(Ry,{method:"POST",headers:{"Content-Type":"application/json",...ht.token?{Authorization:`Bearer ${ht.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:ht.userId,step:t,model:e,prompt:n,images:r,context:i})}),c=await u.text();let d={};try{d=c?JSON.parse(c):{}}catch{d={}}if(u.status===429){d.serverCount!==void 0&&(localStorage.setItem(Fn,JSON.stringify({count:d.serverCount,month:gn()})),un());const p=new Error(d.message||"Monthly usage limit reached. Upgrade to continue.");throw p.isUsageLimit=!0,p.pipelineStep=t,p}const f=kv(d,t);if(f)throw f;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(d),"content type:",typeof d.content),!u.ok)throw new Error(`${d.message||d.error||"BuildShip pipeline error"} (HTTP ${u.status})`);if(t==="generator")if(d.usage_status==="success"&&Number.isFinite(d.usage_count)){const p=gn();(d.usage_month||p)===p&&(localStorage.setItem(Fn,JSON.stringify({count:d.usage_count,month:p})),un())}else rw(),un();let h=d.output||d.content;if(!h){const p=c?` (body: ${c.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${p}`)}return Array.isArray(h)&&(h=h.map(p=>typeof p=="string"?p:p.text||"").join("")),typeof h!="string"&&(h=JSON.stringify(h)),h}catch(u){if(u.name==="AbortError"){if(a)throw new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`);const c=new Error(`BuildShip ${t} request cancelled`);throw c.isPipelineCancel=!0,c}throw u instanceof TypeError?new Error(`BuildShip unreachable: ${u.message}`):u}finally{clearTimeout(l),Es.delete(o)}}let Ga=!1;function mw(){const e=new URLSearchParams(window.location.search).get("checkout");return e==="success"?(window.history.replaceState({},"",window.location.pathname+window.location.hash),cp(),Ga=!0):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname+window.location.hash),Ee("Checkout cancelled.","info")),e}function vw(){if(!Ga)return;Ga=!1;const t=ce.tier!=="free";Ee(t?"Subscription active! Your plan is live.":"Checkout complete — confirming your subscription. Check Manage billing if it does not update.",t?"success":"info")}function qs(){const t=q.isVerified&&!!q.email,e=ce.tier,n=t&&pi(),i=!t||Tt(),r=document.getElementById("subscription-tier-badge");if(r){const a=ml,l={free:"bg-gray-100 text-gray-600",professional:"bg-indigo-100 text-indigo-700",power:"bg-purple-100 text-purple-700",unresolved:"bg-red-50 text-red-600"};r.textContent=n?"Checking…":i?a[e]||"Free":"Plan unavailable",r.className=`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${i?l[e]||l.free:l.unresolved}`}const s=document.getElementById("upgrade-prompt");s&&s.classList.toggle("hidden",!t||n||!i||e!=="free");const o=document.getElementById("manage-billing-btn");o&&o.classList.toggle("hidden",!t||n||i&&e==="free"),_w(i?e:null),uw(),Cl(),un(),Ap()}function _w(t){const e=["bg-gray-100","text-gray-500","cursor-default"];Object.entries({professional:{btnId:"checkout-btn-professional",defaultText:"Subscribe"},power:{btnId:"checkout-btn-power",defaultText:"Subscribe"}}).forEach(([r,{btnId:s,defaultText:o}])=>{const a=document.getElementById(s);a&&(r===t?(a.disabled=!0,a.textContent="Current plan",a.classList.add(...e)):(a.disabled=!1,a.textContent=o,a.classList.remove(...e)))});const i=document.getElementById("free-tier-current");i&&i.classList.toggle("hidden",t!=="free")}function yw(){document.querySelectorAll(".pm-card[data-tier]").forEach(t=>{const e=t.dataset.tier,n=hv[e];if(!n)return;const i=t.querySelector("ul.pm-features");if(i){i.innerHTML="";for(const r of n){const s=document.createElement("li");s.textContent=r,i.appendChild(s)}}})}function Ka(){const t=Al(),e=document.getElementById("pro-price"),n=document.getElementById("power-price"),i=document.getElementById("plans-pro-price"),r=document.getElementById("plans-power-price"),s=document.getElementById("pro-price-note"),o=document.getElementById("power-price-note"),a=document.getElementById("plans-pro-price-note"),l=document.getElementById("plans-power-price-note");e&&(e.textContent=Oi(Ni.professional,t)),n&&(n.textContent=Oi(Ni.power,t)),i&&(i.textContent=Oi(Ni.professional,t)),r&&(r.textContent=Oi(Ni.power,t));const u="billed monthly";s&&(s.textContent=u),o&&(o.textContent=u),a&&(a.textContent=u),l&&(l.textContent=u)}function di(){Ka();const t=document.getElementById("pricing-modal");t&&We(t),Vy().then(()=>Ka())}function up(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&ze(e)}function Ee(t,e="info"){const n={success:"bg-green-600 text-white",error:"bg-red-600 text-white",warning:"bg-amber-500 text-white",info:"bg-gray-800 text-white"},i=document.createElement("div");i.className=`fixed bottom-6 left-1/2 -translate-x-1/2 px-5 py-3 rounded-lg text-sm font-medium shadow-lg z-50 transition-opacity duration-300 ${n[e]||n.info}`,i.textContent=t,document.body.appendChild(i),setTimeout(()=>{i.style.opacity="0",setTimeout(()=>i.remove(),300)},3500)}document.addEventListener("DOMContentLoaded",async()=>{uv(),hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),ww(),window.__heroField=iy(),window.__pipelineLogo=ay(),Fh=Ay({onSubmit:or}),Oa=(async()=>{try{await G0(),mw(),await lp()}catch(n){console.warn("Startup auth/subscription initialization failed:",n)}})(),await Oa,vw(),qs(),Ka(),yw(),await E0(),v0();const t=document.getElementById("flutterflow-endpoint-select");if(t){const n=yt();t.value=n}Hh(),sp();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{en===2&&e.value.trim().length>0&&($l(),Ns())}),e.addEventListener("blur",()=>{const n=document.getElementById("walkthrough-modal");en===2&&n&&We(n)}),e.addEventListener("keydown",n=>{if(n.key==="Tab"){const i=document.getElementById("walkthrough-modal");en===2&&i&&setTimeout(()=>{We(i)},100)}})),window.addEventListener("commitStateChange",n=>{const{state:i}=n.detail;i===ee.PREPARING||i===ee.VALIDATING||i===ee.PUSHING?(Be.phaseId||mp(),cd(i)):(i===ee.SUCCESS||i===ee.ERROR)&&(cd(i),setTimeout(Xl,1e3))}),sc()});function ww(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function bw(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Nn),document.addEventListener("keydown",Nn))}function Nn(){const t=document.getElementById("preview-frame-container"),e=document.getElementById("main-stage-container"),n=document.getElementById("ready-state");t&&(t.style.display="none"),e&&e.classList.add("visible"),n&&n.classList.remove("hidden");const i=document.getElementById("welcome-video-player");i&&i.removeEventListener("click",Nn),document.removeEventListener("keydown",Nn),Hh()}let qi=null;async function Ew(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++ed,n=()=>e===ed,i=await Te("flutterflow"),r=await Te("flutterflow_project_id");if(n()){if(!i){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const o=await new hi(i,"","main",yt()).listProjects();if(!n())return;if(!o||o.length===0){t.innerHTML='';return}t.innerHTML='',o.forEach(a=>{const l=document.createElement("option");l.value=a.id||a.projectId||"",l.textContent=a.name||a.projectName||`Project ${a.id}`,t.appendChild(l)}),r&&(t.value=r)}catch(s){if(!n())return;console.error("Failed to load projects for deploy:",s),t.innerHTML=''}}}function Sw(){return document.getElementById("confirm-project-select")?.value?.trim()||null}function Jl(t,e,n,i=null){qi={codeInfo:t,checks:e,deps:n,bundlePlan:i},document.getElementById("confirm-file-name").textContent=t.fileName,document.getElementById("confirm-artifact-type").textContent=t.artifactType,document.getElementById("confirm-file-size").textContent=`${(t.content.length/1024).toFixed(1)} KB`,document.getElementById("confirm-line-count").textContent=i?`${i.fileEntries.length} files`:t.content.split(` -`).length,Ew();const r=document.getElementById("confirm-deps-list"),s=document.getElementById("confirm-deps-section");n&&Object.keys(n).length>0?(r.innerHTML=Object.entries(n).map(([u,c])=>{const d=c?`at least ${Qt(c)}`:"version resolved from your project";return`
    • • ${Qt(u)}: ${d}
    • `}).join(""),s.classList.remove("hidden")):s.classList.add("hidden");const o=document.getElementById("confirm-warnings-list"),a=document.getElementById("confirm-warnings-section");e.warnings&&e.warnings.length>0?(o.innerHTML=e.warnings.map(u=>`
    • • ${Qt(u)}
    • `).join(""),a.classList.remove("hidden")):a.classList.add("hidden"),document.getElementById("confirm-code-preview").textContent=t.content,document.getElementById("code-preview-content").classList.add("hidden"),document.getElementById("code-preview-chevron").style.transform="rotate(0deg)";const l=document.getElementById("commit-confirm-modal");l&&We(l)}function dp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&ze(e),qi=null}function xw(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&ze(e);const n=["success-message","success-project-id","success-file-name","success-artifact-type","success-time","success-size"];for(const s of n){const o=document.getElementById(s);o&&(o.textContent="")}const i=document.getElementById("success-warnings-section");i&&i.classList.add("hidden");const r=document.getElementById("success-warnings-list");r&&(r.innerHTML="")}function fp(t){const e=(m,v)=>{const E=document.getElementById(m);E&&(E.textContent=v||"")},n=t.metadata?.fileName||"",i=t.metadata?.projectId||"",r=t.metadata?.artifactType||"",s=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",i),e("success-file-name",n),e("success-artifact-type",r),e("success-time",s),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&i&&(u.href=`https://app.flutterflow.io/project/${i}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),f=t.unverified||[],h=t.approximate||[],p=t.warnings||[];(p.length>0||f.length>0||h.length>0)&&c&&d&&(d.innerHTML=[...f.map(m=>`
    • Not verified before deploying: ${z(String(m))}
    • `),...h.map(m=>`
    • Verified approximately: ${z(String(m))}
    • `),...p.map(([m,v])=>`
    • ${z(m)}: ${z(String(v))}
    • `)].join(""),c.classList.remove("hidden"));const g=document.getElementById("commit-success-modal");g&&We(g)}function hp(t){Xl(),W0(t);const e=t.remoteRefusal===!0;Zl(t,{heading:"Deploy failed",title:e?"FlutterFlow refused this deploy — nothing was confirmed written.":"The deploy failed before FlutterFlow confirmed anything.",guidance:e?"Review the error and any per-file outcomes above, fix them in your code or in FlutterFlow, then deploy again. A refusal is definitive: no part of this deploy was applied, so retrying is safe once the problem is fixed.":"Review the error above, fix it, then deploy again. The deploy stopped before a write was confirmed, so nothing was applied."})}function Zl(t,{heading:e,title:n,guidance:i}){const r=t.targetIdentity||{},s=document.getElementById("commit-terminal-modal");if(!s)return!1;const o=(h,p)=>{const g=document.getElementById(h);g&&(g.textContent=p||"")};o("terminal-heading",e),o("terminal-title",n),o("terminal-message",t.error||t.message||"");const a=document.getElementById("terminal-identity-list");if(a){const h=[["Project",r.projectId||t.metadata?.projectId],["Endpoint",r.endpoint],["File",r.fileName||t.metadata?.fileName],["Artifact",r.artifactType||t.metadata?.artifactType]];a.innerHTML=h.map(([p,g])=>`
      ${z(p)}:${z(String(g??"—"))}
      `).join("")}const l=document.getElementById("terminal-file-outcomes");let u=t.errorMap;u&&!(u instanceof Map)&&(u=new Map(Object.entries(u))),l&&u&&u.size>0?(l.innerHTML=[...u.entries()].map(([h,p])=>`
    • ${z(h)}: ${z(Sl(p))}
    • `).join(""),l.classList.remove("hidden")):l&&l.classList.add("hidden");const c=document.getElementById("terminal-guidance");c&&(c.innerHTML=i);const d=document.getElementById("terminal-open-ff-link"),f=r.projectId||t.metadata?.projectId;return d&&(d.href=f?`https://app.flutterflow.io/project/${f}`:"https://app.flutterflow.io/"),We(s),!0}function pp(t){Zl(t,{heading:"Deploy partially applied",title:"Some custom classes reached FlutterFlow, but the deploy did not fully complete.",guidance:"The custom classes the runner confirmed are already in your project and are not lost. Review the per-file errors above, fix them in FlutterFlow or regenerate, then deploy again. Open the project to see exactly what landed."})}function gp(t){Zl(t,{heading:"Deploy outcome not yet known",title:"This browser stopped waiting before the FlutterFlow server reported a result.",guidance:"The deploy may still be finishing on the server — it was not cancelled. Open your FlutterFlow project and confirm whether the class landed before retrying, so you do not push a duplicate or build on top of an unknown state."})}function Iw(t){t&&t.target!==t.currentTarget||ze(document.getElementById("commit-terminal-modal"))}function kw(){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 ld={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}},Cw=[{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&&(xu(e,!0,"Deploying to FlutterFlow"),We(e)),this.set("prepare")},set(t,e=null){if(!(!ld[t]||t===this.phaseId)){if(!this.sequence.includes(t)){const n=this.sequence.indexOf("package");this.sequence.splice(n===-1?this.sequence.length:n,0,t)}this.phaseId=t,this.phaseStartedAt=Date.now(),this.substatus=e,this.liveSubstatus=!1,this.render(),this.timer&&clearInterval(this.timer),t!=="done"&&(this.timer=setInterval(()=>this.render(),500))}},setSubstatus(t){t&&(this.liveSubstatus=!0,this.substatus=t,this.render())},render(){const t=ld[this.phaseId];if(!t)return;const e=(Date.now()-this.phaseStartedAt)/1e3,n=t.start+(t.end-t.start)*(1-Math.exp(-e/25));if(this.phaseId==="provision"&&!this.liveSubstatus){const o=Cw.filter(a=>e>=a.after).pop();o&&(this.substatus=o.text)}const i=this.sequence.indexOf(this.phaseId),s=[`Step ${i===-1?1:i+1} of ${this.sequence.length}`];e>=5&&s.push(Aw(e)),vp(this.phaseId==="done"?100:n,t.message,s.join(" · "),this.substatus)},stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.phaseId=null;const t=document.getElementById("commit-progress-overlay");t&&(xu(t,!1),ze(t,{force:!0,restoreFocus:!1}))}};function Aw(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 mp(t){Be.start(t)}function Xl(){Be.stop()}function vp(t,e,n,i=null){const r=document.getElementById("commit-progress-bar"),s=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");r&&(r.style.width=`${Math.round(t*10)/10}%`),s&&(s.textContent=e),o&&(o.textContent=n),a&&(a.textContent=i||"",a.classList.toggle("hidden",!i))}function cd(t){const e={[ee.PREPARING]:"prepare",[ee.VALIDATING]:"validate",[ee.PUSHING]:"project",[ee.SUCCESS]:"done"};if(t===ee.ERROR){Be.timer&&clearInterval(Be.timer),Be.timer=null,vp(100,"Failed","Error occurred");return}const n=e[t];n&&Be.set(n)}function Pw(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===J.CODE_FILE):t.codeInfo?.codeType===J.CODE_FILE}let _p=!1;function yp(t){_p=t;const e=document.querySelector("#commit-confirm-modal button[data-deploy-confirm]");e&&(e.disabled=t),[...document.querySelectorAll("[data-deploy-start]"),...document.querySelectorAll("#btn-deploy-to-ff")].forEach(i=>{i.disabled=t})}function ud(t){Xl(),yp(!1);const e=xh(t);e===Le.COMMITTED?fp(t):e===Le.PARTIAL?pp(t):e===Le.UNCONFIRMED?gp(t):hp(t)}async function Fw(){if(!qi){console.error("No pending commit data");return}if(_p){console.warn("Deploy already in flight; ignoring duplicate confirm.");return}const t=qi;if(qi=null,zi=Sw(),dp(),yp(!0),mp({withProvisioning:Pw(t)}),t.bundlePlan){const o=await T0(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});zi=null,ud(o);return}const{codeInfo:e}=t,{artifactType:n,artifactName:i,fileName:r}=Wh(),s=await R0(e.content,{artifactType:n,artifactName:i,fileName:r,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});zi=null,ud(s)}window.runThinkingPipeline=or;window.toggleStep=L0;window.toggleSection=M0;window.selectWorkflowStep=it;window.copyCode=N0;window.retryWithDifferentModel=j0;window.openApiKeysModal=Tl;window.closeApiKeysModal=jh;window.openComposerSettings=o0;window.closeComposerSettings=a0;window.walkthroughConnectAccount=s0;window.closeWalkthroughModal=c0;window.openWalkthroughModal=l0;window.advanceWalkthrough=$l;window.commitToFlutterFlow=F0;function Rw(){const t=document.getElementById("pipeline-input");t&&t.focus()}function Tw(){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=Rw;window.openModelSelector=Tw;window.handlePromptImageSelect=zy;window.removePromptImage=qy;window.saveApiKeys=f0;window.validateFlutterFlowConnection=Ll;window.clearAllApiKeys=h0;window.toggleKeyVisibility=y0;window.handleWelcomeVideoEnd=bw;window.dismissWelcomeVideo=Nn;window.initiateCommitToFlutterFlow=U0;window.updateFlutterFlowCredentialStatus=z0;window.openCommitConfirmModal=Jl;window.closeCommitConfirmModal=dp;window.closeCommitSuccessModal=xw;window.closeCommitTerminalModal=Iw;window.showCommitPartialModal=pp;window.showCommitUnconfirmedModal=gp;window.showCommitSuccessModal=fp;window.showCommitFailureModal=hp;window.toggleCodePreview=kw;window.confirmCommitToFlutterFlow=Fw;window.runRefinement=Xh;window.regenerateFromPastedErrors=Qh;window.clearErrorInput=D0;window.setFlutterFlowEndpoint=r0;window.getFlutterFlowEndpoint=yt;window.commitProgress=Be;window.openSignInModal=Ws;window.closeSignInModal=rp;window.handleMagicLinkRequest=Y0;window.handleSignOut=J0;window.handleSendNewLink=Q0;window.handleClearCache=ew;window.handleDeleteAccount=tw;window.closeDeleteUnavailableModal=nw;window.startCheckout=hw;window.openCustomerPortal=pw;window.openPricingModal=di;window.closePricingModal=up;let jr=null,wp=null,On={1:"pending",2:"pending",3:"pending"},Ql=1,ec=null;const Vs={1:"Prompt Architect",2:"Code Generator",3:"Code Review"},$w={1:"Understanding your prompt",2:"Generating Dart code",3:"Running the code audit"},Mw={1:"Prompt understood",2:"Dart code generated",3:"Code audit complete"};function Gs(){return y.runId+=1,y.runId}function re(t){return t===void 0||t===y.runId}function Lw(){y.runId+=1}function tc(t){return document.getElementById(`pdot-${t}`)}function Ya(t){const e=document.getElementById("btn-run-pipeline")||document.getElementById("hero-send");e&&(e.disabled=t,e.classList.toggle("is-busy",t),t?e.setAttribute("aria-busy","true"):e.removeAttribute("aria-busy"))}function Ks(t){const e=document.getElementById("pipeline-progress");e&&(e.dataset.runState=t)}function Rn(t,e){On[t]=e;const n=tc(t);if(!n)return;n.dataset.state=e,n.disabled=e==="pending"||e==="skipped";const i=Vs[t],r={pending:"not started",active:"in progress",done:"complete",failed:"failed",skipped:"not run"};n.setAttribute("aria-label",`Step ${t} of 3, ${i}: ${r[e]||e}`),e==="active"?n.setAttribute("aria-current","step"):n.removeAttribute("aria-current")}function Nw(){return[1,2,3].filter(t=>On[t]==="done").length}function Ys(){const t=document.getElementById("pipeline-progress-fill");t&&(t.style.width=`${Nw()/3*100}%`);const e=document.getElementById("progress-stage-count");e&&(e.textContent=`Step ${Ql} of 3`)}function Js(t,{done:e=!1}={}){const n=document.getElementById("progress-title-text"),i=document.getElementById("progress-substep-text"),r=On[t],s=e||r==="done";if(n&&(n.textContent=s?Mw[t]:$w[t]),i){const o=s?" — complete":r==="failed"?" — stopped":"";i.textContent=`Step ${t} of 3 — ${Vs[t]}${o}`}}function Ow(t){On[t]==="pending"||On[t]==="skipped"||(ec=t,[1,2,3].forEach(e=>{const n=tc(e);n&&n.setAttribute("aria-pressed",String(e===t))}),Js(t))}function nc(){ec=null,[1,2,3].forEach(t=>{const e=tc(t);e&&e.removeAttribute("aria-pressed")})}function bp(t){const e=document.getElementById("pipeline-note");e&&(e.textContent=t||"",e.hidden=!t)}function Bw(t,e,n){re(n)&&bp(`${Gt(t)} did not answer. Continuing on ${Gt(e)}.`)}function ic(){const t=document.getElementById("pipeline-failure");if(!t)return;t.hidden=!0;const e=document.getElementById("pipeline-failure-actions");e&&e.replaceChildren()}const Dw=1120;function jw(){const t=getComputedStyle(document.documentElement).getPropertyValue("--t-morph").trim(),e=Number.parseFloat(t);return Number.isFinite(e)&&e>0?e:Dw}let Qn=null,Ur=null;function Uw(){return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0}function dn(){if(Ur){try{Ur.cancel()}catch{}Ur=null}Qn&&(Qn.remove(),Qn=null),window.removeEventListener("resize",dn)}function Ep(t,e){if(dn(),Uw()||!t||!e||!document.body||typeof Element.prototype.animate!="function")return;const n=t.getBoundingClientRect(),i=e.getBoundingClientRect();if(!n.width||!n.height||!i.width||!i.height)return;const r=document.createElement("div");r.className="composer-morph",r.setAttribute("aria-hidden","true"),r.style.cssText=`left:${i.left}px;top:${i.top}px;width:${i.width}px;height:${i.height}px;opacity:0;`,document.body.appendChild(r);const s=n.left+n.width/2-(i.left+i.width/2),o=n.top+n.height/2-(i.top+i.height/2),a=n.width/i.width,l=n.height/i.height,u=`translate(${s}px,${o}px) scale(${a},${l})`,c=r.animate([{transform:u,opacity:0,offset:0,easing:"cubic-bezier(.2,0,0,1)"},{transform:u,opacity:1,offset:.14,easing:"cubic-bezier(.4,0,.2,1)"},{transform:`translate(${s}px,${o}px) scale(${a*.93},${l*.93})`,opacity:1,offset:.28,easing:"cubic-bezier(.32,1.38,.5,1)"},{transform:"translate(0px,0px) scale(1,1)",opacity:1,offset:1}],{duration:jw(),fill:"both"});Qn=r,Ur=c,window.addEventListener("resize",dn),c.onfinish=()=>{if(Qn!==r)return;const d=r.animate([{opacity:1},{opacity:0}],{duration:260,fill:"forwards"});d.onfinish=()=>{Qn===r&&dn()}}}function Hw(){const e=document.getElementById("composer")?.getBoundingClientRect();e&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{Ep({getBoundingClientRect:()=>e},document.getElementById("main-stage-container"))})})}function Ww(){Ep(document.getElementById("pipeline-progress"),document.getElementById("main-stage-container"))}window.addEventListener("hashchange",dn);window.addEventListener("popstate",dn);function Zs(t={}){const{prompt:e=null,runId:n}=t;if(!re(n))return;Qs(),nn(!0);const i=document.getElementById("pipeline-progress"),r=document.getElementById("results-view"),s=document.getElementById("ready-state");if(s&&s.classList.add("hidden"),r&&r.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),i&&i.classList.add("visible"),Ks("running"),e!==null){const a=document.getElementById("pipeline-submitted-prompt");a&&(a.textContent=e)}wp=Date.now();const o=document.getElementById("progress-elapsed");o&&(o.textContent="0s"),On={1:"pending",2:"pending",3:"pending"},nc(),ic(),bp(""),[1,2,3].forEach(a=>Rn(a,"pending")),Ft(1,n),zw()}function Ft(t,e){re(e)&&(Ql=t,nc(),[1,2,3].forEach(n=>{n===t?Rn(n,"active"):nt&&Rn(n,"pending")}),Js(t),Ys())}function tn(t,e){re(e)&&(Rn(t,"done"),ec===null&&Js(t,{done:!0}),Ys())}function Sp(t,{stage:e=1,runId:n,retry:i=xp}={}){if(!re(n))return;Xs(),Qs(),dn(),Ks("failed"),nn(!0);const r=document.getElementById("pipeline-progress");r&&r.classList.add("visible");const s=document.getElementById("results-view");s&&s.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),Rn(e,"failed"),[1,2,3].forEach(p=>{p>e&&Rn(p,"pending")}),Ql=e,nc(),Js(e),Ys();const o=kh(t),a=document.getElementById("pipeline-failure"),l=document.getElementById("pipeline-failure-title"),u=document.getElementById("pipeline-failure-message"),c=document.getElementById("pipeline-failure-hint"),d=document.getElementById("pipeline-failure-actions");if(!a||!l||!u||!d)return;if(a.dataset.kind=o.kind,l.textContent=`${Vs[e]}: ${o.title}`,u.textContent=o.message,c){const p=o.detail&&o.detail!==o.message?o.detail:"";c.textContent=p,c.hidden=!p}d.replaceChildren();const f=[o.canUpgrade&&{id:"upgrade",label:"View plans",variant:"primary",onClick:()=>di()},o.canRetry&&{id:"retry",label:"Retry",variant:o.canUpgrade?"secondary":"primary",onClick:i},o.canEdit&&{id:"edit",label:"Edit prompt",variant:"secondary",onClick:Ja}].filter(Boolean);!o.canEdit&&!o.canRetry&&f.push({id:"edit",label:"Back to prompt",variant:"secondary",onClick:Ja}),f.forEach(p=>{const g=document.createElement("button");g.type="button",g.textContent=p.label,g.dataset.action=p.id,g.dataset.variant=p.variant,g.addEventListener("click",p.onClick),d.appendChild(g)}),a.hidden=!1;const h=d.querySelector("button");h&&h.focus({preventScroll:!0})}function Ja(){Lw(),gw(),y.isRunning=!1,Ya(!1),rn(),Ks("settled"),dn(),Xs(),Qs(),ic();const t=document.getElementById("pipeline-progress");t&&t.classList.remove("visible"),nn(!1);const e=document.getElementById("pipeline-input");e&&(y.submittedPrompt&&(e.value=y.submittedPrompt,e.dispatchEvent(new Event("input",{bubbles:!0}))),e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length))}function xp(){const t=document.getElementById("pipeline-input");t&&y.submittedPrompt&&(t.value=y.submittedPrompt,t.dispatchEvent(new Event("input",{bubbles:!0}))),Oe=y.submittedImages.slice(),cn(),ic(),or()}function zw(){Xs(),jr=setInterval(()=>{const t=(Date.now()-wp)/1e3,e=document.getElementById("progress-elapsed");e&&(e.textContent=`${Math.floor(t)}s`)},250)}function Xs(){jr&&(clearInterval(jr),jr=null)}let Vi=null;function Qs(){Vi&&(clearTimeout(Vi),Vi=null)}function cr(){Xs(),Qs(),Ks("settled"),Ys();const t=document.getElementById("pipeline-progress-fill");Vi=setTimeout(()=>{Vi=null;const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function Tn(t,e=""){const n={pass:'',warning:'',fail:'',info:''};return``}function Ip(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function qw(){return __({bundle:y.artifactBundle,reviewResult:y.step3Result})}function Vw(t){return` +`;const o=oh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:s});Zs({runId:i}),Ft(2,i),it(2),Ae(2,!0);const a=await Us(o,n,[],i);if(!re(i))return;y.step2Result=a,Bs(),tn(2,i);const l=document.getElementById("step2-output"),u=ci(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),it(3),Ft(3,i),Ae(3,!0);const c=await Hs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,Ds(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const f=Ls(y.step3Result);ur(u,f)}catch(s){if(console.error("Regeneration failed:",s),!re(i))return;const o=Ms(s,{architect:2,generator:2,review:3});s.isUsageLimit&&un(),it(o),Ae(o,!1),Sp(s,{stage:o,runId:i,retry:()=>ep(t,e)}),bs(o,"error")}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function z0(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const n=await Te("flutterflow"),i=await Te("flutterflow_project_id");n&&i?(t.className="w-2 h-2 rounded-full bg-green-500",e.textContent="FlutterFlow credentials configured",e.className="text-green-600"):n||i?(t.className="w-2 h-2 rounded-full bg-yellow-500",e.textContent="FlutterFlow credentials incomplete",e.className="text-yellow-600"):(t.className="w-2 h-2 rounded-full bg-red-500",e.textContent="FlutterFlow credentials not configured",e.className="text-red-600")}async function tp(t){try{const e=await fetch(`${_t}/auth/send-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:t})});if(!e.ok)throw new Error(`Failed to send magic link: HTTP ${e.status}`);return e.json()}catch(e){throw console.error("sendMagicLink failed:",{email:t,message:e.message,stack:e.stack}),e}}async function q0(t){try{const n=await(await fetch(`${_t}/auth/verify-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})})).json();if(n.error||!n.email||!n.sessionToken)throw new Error(n.error||"Invalid or expired link");return n}catch(e){throw console.error("verifyMagicLink failed:",{message:e.message,stack:e.stack}),e}}async function V0(t){try{const e=await fetch(`${_t}/auth/refresh-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:t})});if(!e.ok)return console.error("refreshSession: non-OK response",{url:`${_t}/auth/refresh-session`,status:e.status}),null;const n=await e.json();return n.error||!n.email||!n.sessionToken?(console.warn("refreshSession: validation failed",{error:n.error,hasEmail:!!n.email,hasToken:!!n.sessionToken}),null):n}catch(e){return console.error("refreshSession: fetch failed",{url:`${_t}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function sd(t,e){const n=ip(),i=(q.email||n.email)!==t;q.email=t,q.sessionToken=e,q.isVerified=!0,ce=Ln({isLoading:!0}),localStorage.setItem(hs,JSON.stringify({email:t,sessionToken:e})),i&&cp()}function np(){q.email=null,q.sessionToken=null,q.isVerified=!1,ce=Ln({isResolved:!0}),localStorage.removeItem(hs),localStorage.removeItem(gs)}function ip(){try{const t=localStorage.getItem(hs);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(hs),{email:null,sessionToken:null}}}async function G0(){const e=new URLSearchParams(window.location.search).get("token");if(e){window.history.replaceState({},"",window.location.pathname+window.location.hash);try{const{email:n,sessionToken:i}=await q0(e);sd(n,i),rp();const r=od();r&&!window.location.hash&&(window.location.hash=r)}catch(n){od();const i=n.message||"Sign-in link invalid or expired.";Ee(i,"error"),Ws(),Zn(i,"error")}}else{const{email:n,sessionToken:i}=ip();if(n&&i){const r=await V0(i);r?sd(r.email,r.sessionToken):np()}}Kl()}function K0(){try{localStorage.setItem(Na,JSON.stringify({hash:window.location.hash||"#home",ts:Date.now()}))}catch(t){console.warn("rememberSignInReturnSurface: failed to persist return surface:",t)}}function od(){try{const t=localStorage.getItem(Na);if(localStorage.removeItem(Na),!t)return null;const{hash:e,ts:n}=JSON.parse(t);return!e||typeof n!="number"||Date.now()-n>Fy?null:e}catch(t){return console.warn("consumeSignInReturnSurface: failed to read return surface:",t),null}}function Ws(){const t=document.getElementById("signin-modal");if(!t)return;K0(),document.getElementById("signin-email-input")?.removeAttribute("aria-invalid"),Zn(""),We(t)}function rp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&ze(e)}function Zn(t,e){const n=document.getElementById("signin-message");n&&(n.textContent=t||"",n.classList.remove("signin-message-success","signin-message-error"),e&&n.classList.add(`signin-message-${e}`))}async function Y0(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),n=Fs(t?.value);if(!n||!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(n)||n.length>254){t?.setAttribute("aria-invalid","true"),Zn("Please enter a valid email address.","error");return}t?.removeAttribute("aria-invalid"),e&&(e.disabled=!0,e.textContent="Sending…");const r=ph(n);r&&Zn(r,"error");try{const s=await tp(n),o=s?.code===hh;t&&!o&&(t.value=""),t?.setAttribute("aria-invalid",String(o)),Zn(gh(s,n),o?"error":"success"),e&&(e.disabled=!1,e.textContent=o?"Send Sign-in Link":"Sent!",o||setTimeout(()=>{e.textContent==="Sent!"&&(e.textContent="Send Sign-in Link")},2500))}catch(s){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:n,err:s}),Zn("Something went wrong. Please try again.","error"),e&&(e.disabled=!1,e.textContent="Send Sign-in Link")}}function J0(){q.email=null,q.sessionToken=null,q.isVerified=!1,ce=Ln({isResolved:!0}),D_({storage:window.localStorage,onIdentityChanged:Kl,onPlanChanged:qs})}const Z0=j_({sendLink:tp,getEmail:()=>q.email||"",onState:X0});function X0(t){const e=document.getElementById("send-new-link-btn"),n=document.getElementById("send-new-link-msg");if(!e||!n)return;if(t.status==="pending"){e.disabled=!0,e.textContent="Sending…",n.className="acct-access-msg",n.textContent="Sending a fresh sign-in link…";return}if(t.status==="sent"){e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg",n.textContent=gh(t.data,q.email||"")||"Link sent — check your email.";return}e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg error";const i=t.error?.message?`Couldn't send a link right now. ${t.error.message}`:"Couldn't send a link right now. Please try again.";n.textContent=i}async function Q0(){await Z0()}function ew(){const t=O_(window.localStorage),e=t.length?`Cleared disposable UI caches: ${t.join(", ")}.`:"Nothing disposable to clear.";Ee(`${e} Your run count, identity and stored keys are kept.`,"info")}function tw(){const t=document.getElementById("delete-unavailable-modal");t&&We(t,{trigger:document.activeElement})}function nw(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("delete-unavailable-modal");e&&ze(e)}function Kl(){const t=q.isVerified&&!!q.email,e=document.getElementById("auth-signedout"),n=document.getElementById("auth-signedin"),i=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),n&&n.classList.toggle("hidden",!t),i&&i.classList.toggle("hidden",t);const r=document.getElementById("auth-user-email");r&&(r.textContent=q.email||"");const s=document.getElementById("access-signed-email");s&&(s.textContent=q.email||""),fw(),qs()}async function sp(){try{if(typeof FingerprintJS>"u"){console.warn("resolveIdentity: FingerprintJS not loaded, skipping");return}const e=await(await FingerprintJS.load()).get(),n=e.visitorId,i=await fetch(My,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fingerprint:e.visitorId,cookie_id:n})});if(!i.ok)throw new Error(`Identity check HTTP ${i.status}`);const r=await i.json();if(ht.userId=r.user_id,ht.token=r.identity_token||null,ht.status=r.status,ht.resolved=!0,sessionStorage.setItem(Ty,r.user_id),ht.token&&sessionStorage.setItem($y,ht.token),r.usage_count!==void 0){const s=gn(),a=(r.usage_month||s)===s?r.usage_count:0;localStorage.setItem(Rn,JSON.stringify({count:a,month:s})),un()}console.log(`Identity resolved: ${r.status} (${r.user_id.slice(0,8)}...) usage: ${r.usage_count??"n/a"}`)}catch(t){console.error("resolveIdentity failed:",t)}}let Wo=null;function iw(t=5e3){return ht.resolved?Promise.resolve():(Wo||(Wo=sp().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([Wo,new Promise(e=>setTimeout(e,t))]))}function op(){const t=gn();try{const e=localStorage.getItem(Rn);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Rn,month:t,err:e}),localStorage.removeItem(Rn),{count:0,month:t}}}function gn(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function lr(){const t=op();return t.month!==gn()?{count:0,month:gn()}:t}function rw(){const e={count:lr().count+1,month:gn()};return localStorage.setItem(Rn,JSON.stringify(e)),e}function gi(){return!!ce.isLoading}function Tt(){return!!ce.isResolved}function sw(t){if(!t)return null;const e=String(t).toLowerCase().replace(/[^a-z0-9]+/g,"_");return e==="pro"||e==="professional_plan"?"professional":e==="power_developer"||e==="power_plan"?"power":Object.prototype.hasOwnProperty.call(ps,e)?e:null}function ow(t){return t&&Object.entries(Ah).find(([,e])=>e===t)?.[0]||null}function Cr(...t){return t.find(e=>e!=null&&e!=="")}function aw(...t){return t.find(e=>e&&typeof e=="object")||{}}function lw(t){const e=t.data&&typeof t.data=="object"?t.data:t,n=aw(e.subscription,e.stripeSubscription,e.currentSubscription,e.customer?.subscriptions?.data?.[0],e.subscriptions?.data?.[0],e.subscriptions?.[0]),i=e.metadata||n.metadata||e.customer?.metadata||{},r=Cr(e.priceId,e.price_id,e.stripePriceId,e.stripe_price_id,n.priceId,n.price_id,n.plan?.id,n.price?.id,n.items?.data?.[0]?.price?.id,n.items?.[0]?.price?.id,n.lines?.data?.[0]?.price?.id),s=Cr(e.status,e.subscriptionStatus,e.subscription_status,n.status,"none"),o=sw(Cr(e.tier,e.plan,e.planId,e.plan_id,e.subscriptionTier,e.subscription_tier,e.product,e.productName,n.tier,n.plan,i.tier,i.plan)),a=Ly.has(String(s).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||ow(r)||(a||l?"professional":"free");return Ln({tier:u,status:s,periodEnd:Cr(e.periodEnd,e.currentPeriodEnd,e.current_period_end,n.current_period_end,n.periodEnd,null),isResolved:!0})}function zs(){return ps[ce.tier]??ps.free}async function cw(){if(q.isVerified&&(!Tt()||gi())&&(await lp({force:!0}),qs()),q.isVerified&&!Tt())return Ee("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=lr(),e=zs();if(t>=e)return ap(t,e,{openModal:!0}),!1;const n=Math.floor(e*.8);if(t>=n){const i=e-t;Ee(`${i} run${i===1?"":"s"} remaining this month.`,"warning")}return!0}function ad(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function ap(t,e,n={}){nn(!0);const i=document.getElementById("walkthrough-modal");i&&ze(i,{restoreFocus:!1});const r=document.getElementById("ready-state");r&&r.classList.add("hidden");const s=document.getElementById("preview-frame-container");s&&(s.style.display="none");const o=document.getElementById("main-stage-container");o&&o.classList.add("visible");const a=document.getElementById("results-view");a&&a.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar");const l=document.getElementById("pipeline-progress");l&&l.classList.remove("visible");const u=document.getElementById("paywall-exhausted");if(!u){Ee(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),fi();return}const c=document.getElementById("paywall-exhausted-text");if(c){const f=ce.tier;f==="free"?c.textContent=`You've used all ${e} free generations this month. Upgrade to Pro for 50 generations/month and access to all AI models.`:c.textContent=`You've used all ${e} generations this month on your ${f} plan. Your limit resets next month.`}const d=document.getElementById("paywall-signin-btn");d&&d.classList.toggle("hidden",q.isVerified),u.classList.remove("hidden"),n.openModal&&fi()}function Va(t){return ce.tier==="free"&&Nr.includes(t)?ms:t}function uw(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const n=ce.tier,r=!(q.isVerified&&!Tt())&&n==="free";Array.from(e.options).forEach(o=>{const a=Gt(o.value),l=Nr.includes(o.value);o.textContent=l&&r?`${a} (PRO)`:a,o.disabled=!1}),r&&Nr.includes(e.value)&&(e.value=ms),e.disabled=!1,Ku.has(e)||(e.addEventListener("change",()=>{Tt()&&ce.tier==="free"&&Nr.includes(e.value)&&(e.value=ms,fi()),qa(e.value),Cl()}),Ku.add(e));let s=document.getElementById("model-selector-free-notice");r?(s||(s=document.createElement("p"),s.id="model-selector-free-notice",s.className="text-xs text-gray-400 mt-1",t.appendChild(s)),s.innerHTML='Free plan — Gemini only. '):s&&s.remove(),qa(e.value)}function Yl(){const t=q.isVerified&&!!q.email,e=t&&gi(),n=!t||Tt(),i=lr(),r=n?i.count:0,s=n?zs():0,o=Math.max(0,s-r),a=`${r} / ${s} runs this month`,l=ml,u=n?ce.tier||"free":null,c=document.getElementById("topbar-credits-count");c&&(e?c.textContent="…":n?c.textContent=String(o):c.textContent="—");const d=document.getElementById("credits-balance");d&&(e?d.textContent="Checking plan…":n?d.textContent=a:d.textContent="Plan check failed");const f=document.getElementById("usage-dialog-tier");f&&(e?f.textContent="Checking…":n?f.textContent=l[u]||"Free":f.textContent="Unavailable");const h=document.getElementById("usage-dialog-status");h&&(e?h.textContent="Verifying your subscription…":n?h.textContent="Runs reset at the start of each month.":h.textContent="Could not verify your subscription. Try again or sign out.");const p=document.getElementById("usage-counter");if(p)if(e&&t)p.textContent="Checking plan…",p.className="text-xs text-gray-500";else if(!n&&t)p.textContent="Plan check failed",p.className="text-xs text-red-600 font-medium";else{p.textContent=a;const g=s>0?r/s:0;p.className=g>=1?"text-xs text-red-600 font-medium":g>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500"}if(!t){const g=document.getElementById("guest-usage-text");if(g){const m=op(),v=m.month===gn()?m.count??0:0;g.textContent=`${v} / ${ps.free} generations used`}}dw()}function dw(){if(!(q.isVerified&&!!q.email))return;const e=gi(),n=Tt(),i=lr(),r=n?i.count:0,s=n?zs():0,o=Math.max(0,s-r),a=n?ce.tier||"free":null,l={free:"Free",professional:"Pro",power:"Power"}[a]||"Free",u=q.email||"",c=u.split("@")[0]||u,d=document.getElementById("acct-avatar");d&&(d.textContent=(u[0]||"?").toUpperCase());const f=document.getElementById("acct-name");f&&(f.textContent=c||"—");const h=document.getElementById("acct-plan-tier"),p=document.getElementById("acct-plan-price"),g=document.getElementById("acct-plan-note"),m=document.getElementById("acct-renewal");if(h&&(h.textContent=e?"Checking…":n?l:"Plan unavailable"),p)if(e)p.textContent="—";else if(!n)p.textContent="—";else if(a==="free")p.textContent="$0 / month";else{const x=Bi(Oi[a]??0,Al());p.textContent=`${x} / month`}if(g&&(e?g.textContent="Verifying your subscription…":n?a==="free"?g.textContent="No subscription. Upgrade for more generations.":g.textContent="billed monthly through Stripe":g.textContent="Could not verify your subscription. Check billing or sign out."),m){const x=Date.parse(ce.periodEnd||""),F=n&&a!=="free"&&!!ce.periodEnd&&!Number.isNaN(x);if(e)m.textContent="";else if(!n)m.textContent="";else if(a==="free")m.textContent="";else if(F){const $=new Date(x).toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"});m.textContent=`Renews ${$} · reset at the start of each month.`}else m.textContent="Renewal date is not available for this period."}const v=document.getElementById("acct-left-count"),E=document.getElementById("acct-left-limit"),S=document.getElementById("acct-reset-note");v&&(v.textContent=e?"…":n?String(o):"—"),E&&(E.textContent=e?"…":n?String(s):"—"),S&&(e?S.textContent="Checking plan…":n?S.textContent="Runs reset at the start of each month.":S.textContent="Plan check failed. Refresh or manage billing.");const _=document.getElementById("acct-used-count"),b=document.getElementById("acct-meter-fill"),k=document.getElementById("acct-meter-meta"),T=document.getElementById("acct-meter-track");if(_&&(_.textContent=e?"…":n?String(r):"—"),b){const x=n&&s>0?Math.min(100,Math.round(r/s*100)):0;b.style.width=`${x}%`}if(k)if(e)k.textContent="Checking…";else if(!n)k.textContent="Plan check failed";else if(s===0)k.textContent=`${r} of ${s}`;else{const x=Math.round(r/s*100);k.textContent=`${r} of ${s} · ${x}%`}T&&(e?T.setAttribute("aria-label","Checking usage…"):n?T.setAttribute("aria-label",`${r} of ${s} generations used`):T.setAttribute("aria-label","Usage unavailable")),vt()}function un(){if(Yl(),q.isVerified&&(gi()||!Tt())){ad();return}const{count:t}=lr(),e=zs();t>=e&&!y.isRunning?ap(t,e):ad()}function fw(){Yl()}async function lp(t={}){const e=t.force===!0;if(!q.isVerified||!q.sessionToken){ce=Ln({isResolved:!0});return}ce={...ce,isLoading:!0,error:null};const n=localStorage.getItem(gs);if(!e&&n)try{const{data:i,email:r,ts:s,version:o}=JSON.parse(n);if(o===Yu&&r===q.email&&Date.now()-s<300*1e3){ce={...i,isLoading:!1,isResolved:i.isResolved!==!1};return}}catch(i){console.warn("Failed to parse subscription cache:",i,"| raw value:",n)}try{const r=await(await fetch(`${_t}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:q.sessionToken,user_id:ht.userId})})).json();if(r.error){if(["unauthorized","invalid session","expired session"].some(o=>String(r.error).toLowerCase().includes(o))){np(),Kl();return}ce=Ln({isResolved:!1,error:r.error});return}ce=lw(r),localStorage.setItem(gs,JSON.stringify({version:Yu,data:ce,email:q.email,ts:Date.now()}))}catch(i){console.error("fetchSubscription failed:",i),ce={...ce,isLoading:!1,isResolved:!1,error:i.message}}}function cp(){localStorage.removeItem(gs)}async function hw(t){if(!q.isVerified||!q.sessionToken){up(),Ws();return}if(!Ah[t]){Ee("Invalid plan selected.","error");return}const e=document.getElementById(`checkout-btn-${t}`);e&&(e.disabled=!0,e.textContent="Redirecting…");try{const i=await(await fetch(`${_t}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:q.sessionToken,currency:Al()})})).json();if(i.error||!i.url)throw new Error(i.error||"Failed to create checkout session");const{url:r}=i;window.location.href=r}catch(n){console.error("startCheckout failed:",n),e&&(e.disabled=!1,e.textContent="Subscribe"),Ee("Could not start checkout. Please try again.","error")}}async function pw(t){if(!q.isVerified||!q.sessionToken){Ws();return}const e=t||document.getElementById("manage-billing-btn"),n=e?e.textContent:"";e&&(e.disabled=!0,e.textContent="Loading…");try{const r=await(await fetch(`${_t}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:q.sessionToken})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to open billing portal");const{url:s}=r;window.location.href=s}catch(i){console.error("openCustomerPortal failed:",i),e&&(e.disabled=!1,e.textContent=n),Ee("Could not open billing portal. Please try again.","error")}}const Es=new Set;function gw(){Es.forEach(t=>t.abort()),Es.clear()}async function Ss(t,e,n,i={},r=[]){const o=new AbortController;Es.add(o);let a=!1;const l=setTimeout(()=>{a=!0,o.abort()},12e4);try{const u=await fetch(Ry,{method:"POST",headers:{"Content-Type":"application/json",...ht.token?{Authorization:`Bearer ${ht.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:ht.userId,step:t,model:e,prompt:n,images:r,context:i})}),c=await u.text();let d={};try{d=c?JSON.parse(c):{}}catch{d={}}if(u.status===429){d.serverCount!==void 0&&(localStorage.setItem(Rn,JSON.stringify({count:d.serverCount,month:gn()})),un());const p=new Error(d.message||"Monthly usage limit reached. Upgrade to continue.");throw p.isUsageLimit=!0,p.pipelineStep=t,p}const f=kv(d,t);if(f)throw f;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(d),"content type:",typeof d.content),!u.ok)throw new Error(`${d.message||d.error||"BuildShip pipeline error"} (HTTP ${u.status})`);if(t==="generator")if(d.usage_status==="success"&&Number.isFinite(d.usage_count)){const p=gn();(d.usage_month||p)===p&&(localStorage.setItem(Rn,JSON.stringify({count:d.usage_count,month:p})),un())}else rw(),un();let h=d.output||d.content;if(!h){const p=c?` (body: ${c.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${p}`)}return Array.isArray(h)&&(h=h.map(p=>typeof p=="string"?p:p.text||"").join("")),typeof h!="string"&&(h=JSON.stringify(h)),h}catch(u){if(u.name==="AbortError"){if(a)throw new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`);const c=new Error(`BuildShip ${t} request cancelled`);throw c.isPipelineCancel=!0,c}throw u instanceof TypeError?new Error(`BuildShip unreachable: ${u.message}`):u}finally{clearTimeout(l),Es.delete(o)}}let Ga=!1;function mw(){const e=new URLSearchParams(window.location.search).get("checkout");return e==="success"?(window.history.replaceState({},"",window.location.pathname+window.location.hash),cp(),Ga=!0):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname+window.location.hash),Ee("Checkout cancelled.","info")),e}function vw(){if(!Ga)return;Ga=!1;const t=ce.tier!=="free";Ee(t?"Subscription active! Your plan is live.":"Checkout complete — confirming your subscription. Check Manage billing if it does not update.",t?"success":"info")}function qs(){const t=q.isVerified&&!!q.email,e=ce.tier,n=t&&gi(),i=!t||Tt(),r=document.getElementById("subscription-tier-badge");if(r){const a=ml,l={free:"bg-gray-100 text-gray-600",professional:"bg-indigo-100 text-indigo-700",power:"bg-purple-100 text-purple-700",unresolved:"bg-red-50 text-red-600"};r.textContent=n?"Checking…":i?a[e]||"Free":"Plan unavailable",r.className=`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${i?l[e]||l.free:l.unresolved}`}const s=document.getElementById("upgrade-prompt");s&&s.classList.toggle("hidden",!t||n||!i||e!=="free");const o=document.getElementById("manage-billing-btn");o&&o.classList.toggle("hidden",!t||n||i&&e==="free"),_w(i?e:null),uw(),Cl(),un(),Ap()}function _w(t){const e=["bg-gray-100","text-gray-500","cursor-default"];Object.entries({professional:{btnId:"checkout-btn-professional",defaultText:"Subscribe"},power:{btnId:"checkout-btn-power",defaultText:"Subscribe"}}).forEach(([r,{btnId:s,defaultText:o}])=>{const a=document.getElementById(s);a&&(r===t?(a.disabled=!0,a.textContent="Current plan",a.classList.add(...e)):(a.disabled=!1,a.textContent=o,a.classList.remove(...e)))});const i=document.getElementById("free-tier-current");i&&i.classList.toggle("hidden",t!=="free")}function yw(){document.querySelectorAll(".pm-card[data-tier]").forEach(t=>{const e=t.dataset.tier,n=hv[e];if(!n)return;const i=t.querySelector("ul.pm-features");if(i){i.innerHTML="";for(const r of n){const s=document.createElement("li");s.textContent=r,i.appendChild(s)}}})}function Ka(){const t=Al(),e=document.getElementById("pro-price"),n=document.getElementById("power-price"),i=document.getElementById("plans-pro-price"),r=document.getElementById("plans-power-price"),s=document.getElementById("pro-price-note"),o=document.getElementById("power-price-note"),a=document.getElementById("plans-pro-price-note"),l=document.getElementById("plans-power-price-note");e&&(e.textContent=Bi(Oi.professional,t)),n&&(n.textContent=Bi(Oi.power,t)),i&&(i.textContent=Bi(Oi.professional,t)),r&&(r.textContent=Bi(Oi.power,t));const u="billed monthly";s&&(s.textContent=u),o&&(o.textContent=u),a&&(a.textContent=u),l&&(l.textContent=u)}function fi(){Ka();const t=document.getElementById("pricing-modal");t&&We(t),Vy().then(()=>Ka())}function up(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&ze(e)}function Ee(t,e="info"){const n={success:"bg-green-600 text-white",error:"bg-red-600 text-white",warning:"bg-amber-500 text-white",info:"bg-gray-800 text-white"},i=document.createElement("div");i.className=`fixed bottom-6 left-1/2 -translate-x-1/2 px-5 py-3 rounded-lg text-sm font-medium shadow-lg z-50 transition-opacity duration-300 ${n[e]||n.info}`,i.textContent=t,document.body.appendChild(i),setTimeout(()=>{i.style.opacity="0",setTimeout(()=>i.remove(),300)},3500)}document.addEventListener("DOMContentLoaded",async()=>{uv(),hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),ww(),window.__heroField=iy(),window.__pipelineLogo=ay(),Fh=Ay({onSubmit:or}),Oa=(async()=>{try{await G0(),mw(),await lp()}catch(n){console.warn("Startup auth/subscription initialization failed:",n)}})(),await Oa,vw(),qs(),Ka(),yw(),await E0(),v0();const t=document.getElementById("flutterflow-endpoint-select");if(t){const n=yt();t.value=n}Hh(),sp();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{en===2&&e.value.trim().length>0&&($l(),Ns())}),e.addEventListener("blur",()=>{const n=document.getElementById("walkthrough-modal");en===2&&n&&We(n)}),e.addEventListener("keydown",n=>{if(n.key==="Tab"){const i=document.getElementById("walkthrough-modal");en===2&&i&&setTimeout(()=>{We(i)},100)}})),window.addEventListener("commitStateChange",n=>{const{state:i}=n.detail;i===ee.PREPARING||i===ee.VALIDATING||i===ee.PUSHING?(Be.phaseId||mp(),cd(i)):(i===ee.SUCCESS||i===ee.ERROR)&&(cd(i),setTimeout(Xl,1e3))}),sc()});function ww(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function bw(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",On),document.addEventListener("keydown",On))}function On(){const t=document.getElementById("preview-frame-container"),e=document.getElementById("main-stage-container"),n=document.getElementById("ready-state");t&&(t.style.display="none"),e&&e.classList.add("visible"),n&&n.classList.remove("hidden");const i=document.getElementById("welcome-video-player");i&&i.removeEventListener("click",On),document.removeEventListener("keydown",On),Hh()}let Vi=null;async function Ew(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++ed,n=()=>e===ed,i=await Te("flutterflow"),r=await Te("flutterflow_project_id");if(n()){if(!i){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const o=await new pi(i,"","main",yt()).listProjects();if(!n())return;if(!o||o.length===0){t.innerHTML='';return}t.innerHTML='',o.forEach(a=>{const l=document.createElement("option");l.value=a.id||a.projectId||"",l.textContent=a.name||a.projectName||`Project ${a.id}`,t.appendChild(l)}),r&&(t.value=r)}catch(s){if(!n())return;console.error("Failed to load projects for deploy:",s),t.innerHTML=''}}}function Sw(){return document.getElementById("confirm-project-select")?.value?.trim()||null}function Jl(t,e,n,i=null){Vi={codeInfo:t,checks:e,deps:n,bundlePlan:i},document.getElementById("confirm-file-name").textContent=t.fileName,document.getElementById("confirm-artifact-type").textContent=t.artifactType,document.getElementById("confirm-file-size").textContent=`${(t.content.length/1024).toFixed(1)} KB`,document.getElementById("confirm-line-count").textContent=i?`${i.fileEntries.length} files`:t.content.split(` +`).length,Ew();const r=document.getElementById("confirm-deps-list"),s=document.getElementById("confirm-deps-section");n&&Object.keys(n).length>0?(r.innerHTML=Object.entries(n).map(([u,c])=>{const d=c?`at least ${Qt(c)}`:"version resolved from your project";return`
    • • ${Qt(u)}: ${d}
    • `}).join(""),s.classList.remove("hidden")):s.classList.add("hidden");const o=document.getElementById("confirm-warnings-list"),a=document.getElementById("confirm-warnings-section");e.warnings&&e.warnings.length>0?(o.innerHTML=e.warnings.map(u=>`
    • • ${Qt(u)}
    • `).join(""),a.classList.remove("hidden")):a.classList.add("hidden"),document.getElementById("confirm-code-preview").textContent=t.content,document.getElementById("code-preview-content").classList.add("hidden"),document.getElementById("code-preview-chevron").style.transform="rotate(0deg)";const l=document.getElementById("commit-confirm-modal");l&&We(l)}function dp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&ze(e),Vi=null}function xw(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&ze(e);const n=["success-message","success-project-id","success-file-name","success-artifact-type","success-time","success-size"];for(const s of n){const o=document.getElementById(s);o&&(o.textContent="")}const i=document.getElementById("success-warnings-section");i&&i.classList.add("hidden");const r=document.getElementById("success-warnings-list");r&&(r.innerHTML="")}function fp(t){const e=(m,v)=>{const E=document.getElementById(m);E&&(E.textContent=v||"")},n=t.metadata?.fileName||"",i=t.metadata?.projectId||"",r=t.metadata?.artifactType||"",s=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",i),e("success-file-name",n),e("success-artifact-type",r),e("success-time",s),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&i&&(u.href=`https://app.flutterflow.io/project/${i}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),f=t.unverified||[],h=t.approximate||[],p=t.warnings||[];(p.length>0||f.length>0||h.length>0)&&c&&d&&(d.innerHTML=[...f.map(m=>`
    • Not verified before deploying: ${z(String(m))}
    • `),...h.map(m=>`
    • Verified approximately: ${z(String(m))}
    • `),...p.map(([m,v])=>`
    • ${z(m)}: ${z(String(v))}
    • `)].join(""),c.classList.remove("hidden"));const g=document.getElementById("commit-success-modal");g&&We(g)}function hp(t){Xl(),W0(t);const e=t.remoteRefusal===!0;Zl(t,{heading:"Deploy failed",title:e?"FlutterFlow refused this deploy — nothing was confirmed written.":"The deploy failed before FlutterFlow confirmed anything.",guidance:e?"Review the error and any per-file outcomes above, fix them in your code or in FlutterFlow, then deploy again. A refusal is definitive: no part of this deploy was applied, so retrying is safe once the problem is fixed.":"Review the error above, fix it, then deploy again. The deploy stopped before a write was confirmed, so nothing was applied."})}function Zl(t,{heading:e,title:n,guidance:i}){const r=t.targetIdentity||{},s=document.getElementById("commit-terminal-modal");if(!s)return!1;const o=(h,p)=>{const g=document.getElementById(h);g&&(g.textContent=p||"")};o("terminal-heading",e),o("terminal-title",n),o("terminal-message",t.error||t.message||"");const a=document.getElementById("terminal-identity-list");if(a){const h=[["Project",r.projectId||t.metadata?.projectId],["Endpoint",r.endpoint],["File",r.fileName||t.metadata?.fileName],["Artifact",r.artifactType||t.metadata?.artifactType]];a.innerHTML=h.map(([p,g])=>`
      ${z(p)}:${z(String(g??"—"))}
      `).join("")}const l=document.getElementById("terminal-file-outcomes");let u=t.errorMap;u&&!(u instanceof Map)&&(u=new Map(Object.entries(u))),l&&u&&u.size>0?(l.innerHTML=[...u.entries()].map(([h,p])=>`
    • ${z(h)}: ${z(Sl(p))}
    • `).join(""),l.classList.remove("hidden")):l&&l.classList.add("hidden");const c=document.getElementById("terminal-guidance");c&&(c.innerHTML=i);const d=document.getElementById("terminal-open-ff-link"),f=r.projectId||t.metadata?.projectId;return d&&(d.href=f?`https://app.flutterflow.io/project/${f}`:"https://app.flutterflow.io/"),We(s),!0}function pp(t){Zl(t,{heading:"Deploy partially applied",title:"Some custom classes reached FlutterFlow, but the deploy did not fully complete.",guidance:"The custom classes the runner confirmed are already in your project and are not lost. Review the per-file errors above, fix them in FlutterFlow or regenerate, then deploy again. Open the project to see exactly what landed."})}function gp(t){Zl(t,{heading:"Deploy outcome not yet known",title:"This browser stopped waiting before the FlutterFlow server reported a result.",guidance:"The deploy may still be finishing on the server — it was not cancelled. Open your FlutterFlow project and confirm whether the class landed before retrying, so you do not push a duplicate or build on top of an unknown state."})}function Iw(t){t&&t.target!==t.currentTarget||ze(document.getElementById("commit-terminal-modal"))}function kw(){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 ld={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}},Cw=[{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&&(xu(e,!0,"Deploying to FlutterFlow"),We(e)),this.set("prepare")},set(t,e=null){if(!(!ld[t]||t===this.phaseId)){if(!this.sequence.includes(t)){const n=this.sequence.indexOf("package");this.sequence.splice(n===-1?this.sequence.length:n,0,t)}this.phaseId=t,this.phaseStartedAt=Date.now(),this.substatus=e,this.liveSubstatus=!1,this.render(),this.timer&&clearInterval(this.timer),t!=="done"&&(this.timer=setInterval(()=>this.render(),500))}},setSubstatus(t){t&&(this.liveSubstatus=!0,this.substatus=t,this.render())},render(){const t=ld[this.phaseId];if(!t)return;const e=(Date.now()-this.phaseStartedAt)/1e3,n=t.start+(t.end-t.start)*(1-Math.exp(-e/25));if(this.phaseId==="provision"&&!this.liveSubstatus){const o=Cw.filter(a=>e>=a.after).pop();o&&(this.substatus=o.text)}const i=this.sequence.indexOf(this.phaseId),s=[`Step ${i===-1?1:i+1} of ${this.sequence.length}`];e>=5&&s.push(Aw(e)),vp(this.phaseId==="done"?100:n,t.message,s.join(" · "),this.substatus)},stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.phaseId=null;const t=document.getElementById("commit-progress-overlay");t&&(xu(t,!1),ze(t,{force:!0,restoreFocus:!1}))}};function Aw(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 mp(t){Be.start(t)}function Xl(){Be.stop()}function vp(t,e,n,i=null){const r=document.getElementById("commit-progress-bar"),s=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");r&&(r.style.width=`${Math.round(t*10)/10}%`),s&&(s.textContent=e),o&&(o.textContent=n),a&&(a.textContent=i||"",a.classList.toggle("hidden",!i))}function cd(t){const e={[ee.PREPARING]:"prepare",[ee.VALIDATING]:"validate",[ee.PUSHING]:"project",[ee.SUCCESS]:"done"};if(t===ee.ERROR){Be.timer&&clearInterval(Be.timer),Be.timer=null,vp(100,"Failed","Error occurred");return}const n=e[t];n&&Be.set(n)}function Pw(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===J.CODE_FILE):t.codeInfo?.codeType===J.CODE_FILE}let _p=!1;function yp(t){_p=t;const e=document.querySelector("#commit-confirm-modal button[data-deploy-confirm]");e&&(e.disabled=t),[...document.querySelectorAll("[data-deploy-start]"),...document.querySelectorAll("#btn-deploy-to-ff")].forEach(i=>{i.disabled=t})}function ud(t){Xl(),yp(!1);const e=xh(t);e===Le.COMMITTED?fp(t):e===Le.PARTIAL?pp(t):e===Le.UNCONFIRMED?gp(t):hp(t)}async function Fw(){if(!Vi){console.error("No pending commit data");return}if(_p){console.warn("Deploy already in flight; ignoring duplicate confirm.");return}const t=Vi;if(Vi=null,qi=Sw(),dp(),yp(!0),mp({withProvisioning:Pw(t)}),t.bundlePlan){const o=await T0(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});qi=null,ud(o);return}const{codeInfo:e}=t,{artifactType:n,artifactName:i,fileName:r}=Wh(),s=await R0(e.content,{artifactType:n,artifactName:i,fileName:r,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});qi=null,ud(s)}window.runThinkingPipeline=or;window.toggleStep=L0;window.toggleSection=M0;window.selectWorkflowStep=it;window.copyCode=N0;window.retryWithDifferentModel=j0;window.openApiKeysModal=Tl;window.closeApiKeysModal=jh;window.openComposerSettings=o0;window.closeComposerSettings=a0;window.walkthroughConnectAccount=s0;window.closeWalkthroughModal=c0;window.openWalkthroughModal=l0;window.advanceWalkthrough=$l;window.commitToFlutterFlow=F0;function Rw(){const t=document.getElementById("pipeline-input");t&&t.focus()}function Tw(){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=Rw;window.openModelSelector=Tw;window.handlePromptImageSelect=zy;window.removePromptImage=qy;window.saveApiKeys=f0;window.validateFlutterFlowConnection=Ll;window.clearAllApiKeys=h0;window.toggleKeyVisibility=y0;window.handleWelcomeVideoEnd=bw;window.dismissWelcomeVideo=On;window.initiateCommitToFlutterFlow=U0;window.updateFlutterFlowCredentialStatus=z0;window.openCommitConfirmModal=Jl;window.closeCommitConfirmModal=dp;window.closeCommitSuccessModal=xw;window.closeCommitTerminalModal=Iw;window.showCommitPartialModal=pp;window.showCommitUnconfirmedModal=gp;window.showCommitSuccessModal=fp;window.showCommitFailureModal=hp;window.toggleCodePreview=kw;window.confirmCommitToFlutterFlow=Fw;window.runRefinement=Xh;window.regenerateFromPastedErrors=Qh;window.clearErrorInput=D0;window.setFlutterFlowEndpoint=r0;window.getFlutterFlowEndpoint=yt;window.commitProgress=Be;window.openSignInModal=Ws;window.closeSignInModal=rp;window.handleMagicLinkRequest=Y0;window.handleSignOut=J0;window.handleSendNewLink=Q0;window.handleClearCache=ew;window.handleDeleteAccount=tw;window.closeDeleteUnavailableModal=nw;window.startCheckout=hw;window.openCustomerPortal=pw;window.openPricingModal=fi;window.closePricingModal=up;let jr=null,wp=null,Bn={1:"pending",2:"pending",3:"pending"},Ql=1,ec=null;const Vs={1:"Prompt Architect",2:"Code Generator",3:"Code Review"},$w={1:"Understanding your prompt",2:"Generating Dart code",3:"Running the code audit"},Mw={1:"Prompt understood",2:"Dart code generated",3:"Code audit complete"};function Gs(){return y.runId+=1,y.runId}function re(t){return t===void 0||t===y.runId}function Lw(){y.runId+=1}function tc(t){return document.getElementById(`pdot-${t}`)}function Ya(t){const e=document.getElementById("btn-run-pipeline")||document.getElementById("hero-send");e&&(e.disabled=t,e.classList.toggle("is-busy",t),t?e.setAttribute("aria-busy","true"):e.removeAttribute("aria-busy"))}function Ks(t){const e=document.getElementById("pipeline-progress");e&&(e.dataset.runState=t)}function Tn(t,e){Bn[t]=e;const n=tc(t);if(!n)return;n.dataset.state=e,n.disabled=e==="pending"||e==="skipped";const i=Vs[t],r={pending:"not started",active:"in progress",done:"complete",failed:"failed",skipped:"not run"};n.setAttribute("aria-label",`Step ${t} of 3, ${i}: ${r[e]||e}`),e==="active"?n.setAttribute("aria-current","step"):n.removeAttribute("aria-current")}function Nw(){return[1,2,3].filter(t=>Bn[t]==="done").length}function Ys(){const t=document.getElementById("pipeline-progress-fill");t&&(t.style.width=`${Nw()/3*100}%`);const e=document.getElementById("progress-stage-count");e&&(e.textContent=`Step ${Ql} of 3`)}function Js(t,{done:e=!1}={}){const n=document.getElementById("progress-title-text"),i=document.getElementById("progress-substep-text"),r=Bn[t],s=e||r==="done";if(n&&(n.textContent=s?Mw[t]:$w[t]),i){const o=s?" — complete":r==="failed"?" — stopped":"";i.textContent=`Step ${t} of 3 — ${Vs[t]}${o}`}}function Ow(t){Bn[t]==="pending"||Bn[t]==="skipped"||(ec=t,[1,2,3].forEach(e=>{const n=tc(e);n&&n.setAttribute("aria-pressed",String(e===t))}),Js(t))}function nc(){ec=null,[1,2,3].forEach(t=>{const e=tc(t);e&&e.removeAttribute("aria-pressed")})}function bp(t){const e=document.getElementById("pipeline-note");e&&(e.textContent=t||"",e.hidden=!t)}function Bw(t,e,n){re(n)&&bp(`${Gt(t)} did not answer. Continuing on ${Gt(e)}.`)}function ic(){const t=document.getElementById("pipeline-failure");if(!t)return;t.hidden=!0;const e=document.getElementById("pipeline-failure-actions");e&&e.replaceChildren()}const Dw=1120;function jw(){const t=getComputedStyle(document.documentElement).getPropertyValue("--t-morph").trim(),e=Number.parseFloat(t);return Number.isFinite(e)&&e>0?e:Dw}let ei=null,Ur=null;function Uw(){return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0}function dn(){if(Ur){try{Ur.cancel()}catch{}Ur=null}ei&&(ei.remove(),ei=null),window.removeEventListener("resize",dn)}function Ep(t,e){if(dn(),Uw()||!t||!e||!document.body||typeof Element.prototype.animate!="function")return;const n=t.getBoundingClientRect(),i=e.getBoundingClientRect();if(!n.width||!n.height||!i.width||!i.height)return;const r=document.createElement("div");r.className="composer-morph",r.setAttribute("aria-hidden","true"),r.style.cssText=`left:${i.left}px;top:${i.top}px;width:${i.width}px;height:${i.height}px;opacity:0;`,document.body.appendChild(r);const s=n.left+n.width/2-(i.left+i.width/2),o=n.top+n.height/2-(i.top+i.height/2),a=n.width/i.width,l=n.height/i.height,u=`translate(${s}px,${o}px) scale(${a},${l})`,c=r.animate([{transform:u,opacity:0,offset:0,easing:"cubic-bezier(.2,0,0,1)"},{transform:u,opacity:1,offset:.14,easing:"cubic-bezier(.4,0,.2,1)"},{transform:`translate(${s}px,${o}px) scale(${a*.93},${l*.93})`,opacity:1,offset:.28,easing:"cubic-bezier(.32,1.38,.5,1)"},{transform:"translate(0px,0px) scale(1,1)",opacity:1,offset:1}],{duration:jw(),fill:"both"});ei=r,Ur=c,window.addEventListener("resize",dn),c.onfinish=()=>{if(ei!==r)return;const d=r.animate([{opacity:1},{opacity:0}],{duration:260,fill:"forwards"});d.onfinish=()=>{ei===r&&dn()}}}function Hw(){const e=document.getElementById("composer")?.getBoundingClientRect();e&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{Ep({getBoundingClientRect:()=>e},document.getElementById("main-stage-container"))})})}function Ww(){Ep(document.getElementById("pipeline-progress"),document.getElementById("main-stage-container"))}window.addEventListener("hashchange",dn);window.addEventListener("popstate",dn);function Zs(t={}){const{prompt:e=null,runId:n}=t;if(!re(n))return;Qs(),nn(!0);const i=document.getElementById("pipeline-progress"),r=document.getElementById("results-view"),s=document.getElementById("ready-state");if(s&&s.classList.add("hidden"),r&&r.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),i&&i.classList.add("visible"),Ks("running"),e!==null){const a=document.getElementById("pipeline-submitted-prompt");a&&(a.textContent=e)}wp=Date.now();const o=document.getElementById("progress-elapsed");o&&(o.textContent="0s"),Bn={1:"pending",2:"pending",3:"pending"},nc(),ic(),bp(""),[1,2,3].forEach(a=>Tn(a,"pending")),Ft(1,n),zw()}function Ft(t,e){re(e)&&(Ql=t,nc(),[1,2,3].forEach(n=>{n===t?Tn(n,"active"):nt&&Tn(n,"pending")}),Js(t),Ys())}function tn(t,e){re(e)&&(Tn(t,"done"),ec===null&&Js(t,{done:!0}),Ys())}function Sp(t,{stage:e=1,runId:n,retry:i=xp}={}){if(!re(n))return;Xs(),Qs(),dn(),Ks("failed"),nn(!0);const r=document.getElementById("pipeline-progress");r&&r.classList.add("visible");const s=document.getElementById("results-view");s&&s.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),Tn(e,"failed"),[1,2,3].forEach(p=>{p>e&&Tn(p,"pending")}),Ql=e,nc(),Js(e),Ys();const o=kh(t),a=document.getElementById("pipeline-failure"),l=document.getElementById("pipeline-failure-title"),u=document.getElementById("pipeline-failure-message"),c=document.getElementById("pipeline-failure-hint"),d=document.getElementById("pipeline-failure-actions");if(!a||!l||!u||!d)return;if(a.dataset.kind=o.kind,l.textContent=`${Vs[e]}: ${o.title}`,u.textContent=o.message,c){const p=o.detail&&o.detail!==o.message?o.detail:"";c.textContent=p,c.hidden=!p}d.replaceChildren();const f=[o.canUpgrade&&{id:"upgrade",label:"View plans",variant:"primary",onClick:()=>fi()},o.canRetry&&{id:"retry",label:"Retry",variant:o.canUpgrade?"secondary":"primary",onClick:i},o.canEdit&&{id:"edit",label:"Edit prompt",variant:"secondary",onClick:Ja}].filter(Boolean);!o.canEdit&&!o.canRetry&&f.push({id:"edit",label:"Back to prompt",variant:"secondary",onClick:Ja}),f.forEach(p=>{const g=document.createElement("button");g.type="button",g.textContent=p.label,g.dataset.action=p.id,g.dataset.variant=p.variant,g.addEventListener("click",p.onClick),d.appendChild(g)}),a.hidden=!1;const h=d.querySelector("button");h&&h.focus({preventScroll:!0})}function Ja(){Lw(),gw(),y.isRunning=!1,Ya(!1),rn(),Ks("settled"),dn(),Xs(),Qs(),ic();const t=document.getElementById("pipeline-progress");t&&t.classList.remove("visible"),nn(!1);const e=document.getElementById("pipeline-input");e&&(y.submittedPrompt&&(e.value=y.submittedPrompt,e.dispatchEvent(new Event("input",{bubbles:!0}))),e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length))}function xp(){const t=document.getElementById("pipeline-input");t&&y.submittedPrompt&&(t.value=y.submittedPrompt,t.dispatchEvent(new Event("input",{bubbles:!0}))),Oe=y.submittedImages.slice(),cn(),ic(),or()}function zw(){Xs(),jr=setInterval(()=>{const t=(Date.now()-wp)/1e3,e=document.getElementById("progress-elapsed");e&&(e.textContent=`${Math.floor(t)}s`)},250)}function Xs(){jr&&(clearInterval(jr),jr=null)}let Gi=null;function Qs(){Gi&&(clearTimeout(Gi),Gi=null)}function cr(){Xs(),Qs(),Ks("settled"),Ys();const t=document.getElementById("pipeline-progress-fill");Gi=setTimeout(()=>{Gi=null;const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function $n(t,e=""){const n={pass:'',warning:'',fail:'',info:''};return``}function Ip(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function qw(){return __({bundle:y.artifactBundle,reviewResult:y.step3Result})}function Vw(t){return`
      - ${Tn(t.severity)} + ${$n(t.severity)}
      ${z(t.message)}
      ${t.suggestion?`
      ${z(t.suggestion)}
      `:""} @@ -185,7 +185,7 @@ Error: ${g}
        ${t.findings.map(u=>`
      • - ${Tn(u.severity)} + ${$n(u.severity)} ${z(u.message)} ${u.suggestion?`${z(u.suggestion)}`:""} @@ -195,14 +195,14 @@ Error: ${g}
      `:"",a=t.warnings.length?`
      -

      ${Tn("warning")} Bundle

      +

      ${$n("warning")} Bundle

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

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

      +

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

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

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

      ${z(l.reason)}

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

      ${z(l.description)}

      `:""}
    • `).join(""):'
    • No relationships for this file
    • ';return`
      - ${Tn(e.status)} ${z(Ip(e.status))} + ${$n(e.status)} ${z(Ip(e.status))}

      ${z(e.artifactName)}

      ${e.description?`

      ${z(e.description)}

      `:""}
      @@ -309,10 +309,10 @@ Error: ${g} tabindex="${o?0:-1}" title="${Jt(`${Ip(s.status)} · ${s.fileName||s.artifactName}`)}" > - ${Tn(s.status)} + ${$n(s.status)} ${z(s.artifactName)} ${z(s.artifactType)} - `}).join(""),i.onclick=s=>{const o=s.target.closest(".artifact-tab");o?.dataset?.artifactId&&rc(o.dataset.artifactId)},dd()),e&&e.classList.add("visible")}function dd(){const t=document.getElementById("bundle-strip");!t||t.dataset.tabKeyboard==="bound"||(t.dataset.tabKeyboard="bound",t.addEventListener("keydown",e=>{if(e.defaultPrevented)return;const n=[document.getElementById("results-summary-tab"),...Array.from(document.querySelectorAll("#artifact-tabs .artifact-tab"))].filter(Boolean);if(!n.length||!n.includes(document.activeElement))return;let i=-1;const r=n.indexOf(document.activeElement);if(e.key==="ArrowRight")i=(r+1)%n.length;else if(e.key==="ArrowLeft")i=(r-1+n.length)%n.length;else if(e.key==="Home")i=0;else if(e.key==="End")i=n.length-1;else return;e.preventDefault();const s=n[i];if(!s)return;if(s.id==="results-summary-tab")kp();else{const a=s.dataset.artifactId;a&&rc(a)}const o=s.id==="results-summary-tab"?document.getElementById("results-summary-tab"):document.querySelector(`#artifact-tabs .artifact-tab[data-artifact-id="${s.dataset.artifactId}"]`);o&&o.focus()}))}function eo(){document.body.classList.add("results-fullscreen"),document.body.classList.add("results-with-sidebar");const t=document.getElementById("results-view"),e=document.getElementById("results-code-output"),n=document.getElementById("results-audit-output"),i=document.getElementById("results-summary-detail"),r=document.getElementById("artifact-results-split"),s=qw(),o=Bl();if(i&&(i.setAttribute("role","tabpanel"),i.setAttribute("aria-labelledby","results-summary-tab")),r){r.setAttribute("role","tabpanel");const a=s?.artifacts?.find(l=>l.id===y.selectedArtifactId);r.setAttribute("aria-labelledby",a?`artifact-tab-${a.id}`:"results-summary-tab")}if(Kw(s),Jw(s),e&&(e.textContent=""),e){const a=Ch(o);e.innerHTML=a}n&&(n.innerHTML=Yw(s)),i&&i.classList.toggle("hidden",y.resultsViewMode!=="summary"),r&&r.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function ur(t,e){nn(!0),y.selectedArtifactId||(y.selectedArtifactId=oi(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const n=document.getElementById("step3-output");n&&(n.textContent=""),eo(),rn(),Zw()}function Zw(){const t=document.getElementById("btn-feedback-up"),e=document.getElementById("btn-feedback-down"),n=document.getElementById("results-feedback-status");t&&(t.className="feedback-btn",t.setAttribute("aria-pressed","false"),t.disabled=!1,t.removeAttribute("aria-disabled")),e&&(e.className="feedback-btn",e.setAttribute("aria-pressed","false"),e.disabled=!1,e.removeAttribute("aria-disabled")),n&&(n.textContent=""),Za=!1}function rc(t){y.selectedArtifactId=t,y.resultsViewMode="file",eo()}function kp(){y.resultsViewMode="summary",eo()}function Xw(){const t=document.getElementById("btn-copy-results"),e=document.getElementById("results-copy-status"),n=Bl(),i=(r,s)=>{e&&(e.textContent=r,e.classList.toggle("ok",!!s),e.classList.toggle("fail",!s))};if(!navigator.clipboard?.writeText){i("Copying isn't supported in this browser.",!1);return}navigator.clipboard.writeText(n).then(()=>{if(i("Copied to clipboard",!0),t){t.classList.add("copied");const r=t.querySelector("span");if(r){const s=r.textContent;r.textContent="Copied!",setTimeout(()=>{t.classList.remove("copied"),r.textContent=s},2e3)}}}).catch(()=>{i("Clipboard permission was denied. Select the code to copy it manually.",!1)})}let Za=!1;async function Qw(t){const e=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down"),i=document.getElementById("results-feedback-status");if(!e||!n||Za)return;const r=l=>{i&&(i.textContent="",i.offsetWidth,i.textContent=l)},s=l=>{Za=l,[e,n].forEach(u=>{u.disabled=l,u.setAttribute("aria-disabled",String(l))})},o=t==="up"?"thumbsUp":"thumbsDown";s(!0),r("Submitting review feedback…");const a={type:o,code:y.step2Result,input:y.step1Result};try{const l=await Gl(a.type,a.code,a.input);if(!l||l.success!==!0){s(!1),r("Review feedback could not be sent. Tap again to retry.");return}e.classList.toggle("active-up",t==="up"),n.classList.toggle("active-down",t==="down"),e.setAttribute("aria-pressed",String(t==="up")),n.setAttribute("aria-pressed",String(t==="down")),s(!1),r("Review feedback saved.")}catch{s(!1),r("Review feedback could not be sent. Tap again to retry.")}}function eb(){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 Cp(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}function nn(t){const e=document.getElementById("generation-stage");e&&(t?(e.hidden=!1,e.inert=!1,requestAnimationFrame(()=>e.classList.add("is-active"))):(e.classList.remove("is-active"),e.inert=!0,setTimeout(()=>{e.classList.contains("is-active")||(e.hidden=!0)},260)))}function Ap(){const t=q.isVerified&&!!q.email,e=ce.tier||"free",n=t&&pi(),i=!t||Tt(),s=n?"Checking…":i?ml[e]||"Free":"—",o=document.getElementById("topbar-plan");o&&(o.textContent=s);const a=document.getElementById("topbar-avatar");a&&(a.textContent=(q.email||"?")[0].toUpperCase()),Yl();const l=document.getElementById("plans-free-current");l&&l.classList.toggle("hidden",e!=="free"||!i);const u=document.getElementById("plans-checkout-btn-professional");if(u){const d=e==="professional"&&i;u.disabled=d,u.textContent=d?"Current plan":"Subscribe"}const c=document.getElementById("plans-checkout-btn-power");if(c){const d=e==="power"&&i;c.disabled=d,c.textContent=d?"Current plan":"Subscribe"}}function tb(){Ap();const t=document.getElementById("credits-modal");t&&We(t)}function nb(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("credits-modal");e&&ze(e)}function Pp(t,e=!0,n=!0){if(t=["home","account","plans"].includes(t)?t:"home",document.querySelectorAll(".view[data-view]").forEach(r=>{r.dataset.view===t?(r.hidden=!1,r.removeAttribute("inert"),requestAnimationFrame(()=>{r.classList.add("is-active"),n&&r.focus({preventScroll:!0})})):(r.classList.remove("is-active"),r.setAttribute("inert","true"),setTimeout(()=>{r.classList.contains("is-active")||(r.hidden=!0)},260))}),t!=="home")nn(!1);else{const r=document.getElementById("main-stage-container");r&&r.classList.contains("visible")&&nn(!0)}if(document.querySelectorAll(".nav-link[data-view]").forEach(r=>{const s=r.dataset.view===t;r.setAttribute("aria-current",s?"page":null),s||r.removeAttribute("aria-current")}),e){const r=t==="home"?"":`#${t}`;window.location.hash!==r&&window.history.pushState({view:t},"",r||"#")}}let fd=!1;function sc(){const t=window.location.hash.replace(/^#/,"");Pp(t||"home",!1,fd),fd=!0}window.addEventListener("popstate",t=>{sc()});window.addEventListener("hashchange",()=>{sc()});window.copyResultsCode=Xw;window.selectArtifact=rc;window.selectResultsSummary=kp;window.submitResultsFeedback=Qw;window.showErrorInputPanel=eb;window.hideErrorInputPanel=Cp;window.setGenerationStageVisible=nn;window.switchView=Pp;window.selectPipelineStage=Ow;window.editPipelinePrompt=Ja;window.retryPipelineRun=xp;window.openCreditsModal=tb;window.closeCreditsModal=nb; + `}).join(""),i.onclick=s=>{const o=s.target.closest(".artifact-tab");o?.dataset?.artifactId&&rc(o.dataset.artifactId)},dd()),e&&e.classList.add("visible")}function dd(){const t=document.getElementById("bundle-strip");!t||t.dataset.tabKeyboard==="bound"||(t.dataset.tabKeyboard="bound",t.addEventListener("keydown",e=>{if(e.defaultPrevented)return;const n=[document.getElementById("results-summary-tab"),...Array.from(document.querySelectorAll("#artifact-tabs .artifact-tab"))].filter(Boolean);if(!n.length||!n.includes(document.activeElement))return;let i=-1;const r=n.indexOf(document.activeElement);if(e.key==="ArrowRight")i=(r+1)%n.length;else if(e.key==="ArrowLeft")i=(r-1+n.length)%n.length;else if(e.key==="Home")i=0;else if(e.key==="End")i=n.length-1;else return;e.preventDefault();const s=n[i];if(!s)return;if(s.id==="results-summary-tab")kp();else{const a=s.dataset.artifactId;a&&rc(a)}const o=s.id==="results-summary-tab"?document.getElementById("results-summary-tab"):document.querySelector(`#artifact-tabs .artifact-tab[data-artifact-id="${s.dataset.artifactId}"]`);o&&o.focus()}))}function eo(){document.body.classList.add("results-fullscreen"),document.body.classList.add("results-with-sidebar");const t=document.getElementById("results-view"),e=document.getElementById("results-code-output"),n=document.getElementById("results-audit-output"),i=document.getElementById("results-summary-detail"),r=document.getElementById("artifact-results-split"),s=qw(),o=Bl();if(i&&(i.setAttribute("role","tabpanel"),i.setAttribute("aria-labelledby","results-summary-tab")),r){r.setAttribute("role","tabpanel");const a=s?.artifacts?.find(l=>l.id===y.selectedArtifactId);r.setAttribute("aria-labelledby",a?`artifact-tab-${a.id}`:"results-summary-tab")}if(Kw(s),Jw(s),e&&(e.textContent=""),e){const a=Ch(o);e.innerHTML=a}n&&(n.innerHTML=Yw(s)),i&&i.classList.toggle("hidden",y.resultsViewMode!=="summary"),r&&r.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function ur(t,e){nn(!0),y.selectedArtifactId||(y.selectedArtifactId=ai(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const n=document.getElementById("step3-output");n&&(n.textContent=""),eo(),rn(),Zw()}function Zw(){const t=document.getElementById("btn-feedback-up"),e=document.getElementById("btn-feedback-down"),n=document.getElementById("results-feedback-status");t&&(t.className="feedback-btn",t.setAttribute("aria-pressed","false"),t.disabled=!1,t.removeAttribute("aria-disabled")),e&&(e.className="feedback-btn",e.setAttribute("aria-pressed","false"),e.disabled=!1,e.removeAttribute("aria-disabled")),n&&(n.textContent=""),Za=!1}function rc(t){y.selectedArtifactId=t,y.resultsViewMode="file",eo()}function kp(){y.resultsViewMode="summary",eo()}function Xw(){const t=document.getElementById("btn-copy-results"),e=document.getElementById("results-copy-status"),n=Bl(),i=(r,s)=>{e&&(e.textContent=r,e.classList.toggle("ok",!!s),e.classList.toggle("fail",!s))};if(!navigator.clipboard?.writeText){i("Copying isn't supported in this browser.",!1);return}navigator.clipboard.writeText(n).then(()=>{if(i("Copied to clipboard",!0),t){t.classList.add("copied");const r=t.querySelector("span");if(r){const s=r.textContent;r.textContent="Copied!",setTimeout(()=>{t.classList.remove("copied"),r.textContent=s},2e3)}}}).catch(()=>{i("Clipboard permission was denied. Select the code to copy it manually.",!1)})}let Za=!1;async function Qw(t){const e=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down"),i=document.getElementById("results-feedback-status");if(!e||!n||Za)return;const r=l=>{i&&(i.textContent="",i.offsetWidth,i.textContent=l)},s=l=>{Za=l,[e,n].forEach(u=>{u.disabled=l,u.setAttribute("aria-disabled",String(l))})},o=t==="up"?"thumbsUp":"thumbsDown";s(!0),r("Submitting review feedback…");const a={type:o,code:y.step2Result,input:y.step1Result};try{const l=await Gl(a.type,a.code,a.input);if(!l||l.success!==!0){s(!1),r("Review feedback could not be sent. Tap again to retry.");return}e.classList.toggle("active-up",t==="up"),n.classList.toggle("active-down",t==="down"),e.setAttribute("aria-pressed",String(t==="up")),n.setAttribute("aria-pressed",String(t==="down")),s(!1),r("Review feedback saved.")}catch{s(!1),r("Review feedback could not be sent. Tap again to retry.")}}function eb(){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 Cp(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}function nn(t){const e=document.getElementById("generation-stage");e&&(t?(e.hidden=!1,e.inert=!1,requestAnimationFrame(()=>e.classList.add("is-active"))):(e.classList.remove("is-active"),e.inert=!0,setTimeout(()=>{e.classList.contains("is-active")||(e.hidden=!0)},260)))}function Ap(){const t=q.isVerified&&!!q.email,e=ce.tier||"free",n=t&&gi(),i=!t||Tt(),s=n?"Checking…":i?ml[e]||"Free":"—",o=document.getElementById("topbar-plan");o&&(o.textContent=s);const a=document.getElementById("topbar-avatar");a&&(a.textContent=(q.email||"?")[0].toUpperCase()),Yl();const l=document.getElementById("plans-free-current");l&&l.classList.toggle("hidden",e!=="free"||!i);const u=document.getElementById("plans-checkout-btn-professional");if(u){const d=e==="professional"&&i;u.disabled=d,u.textContent=d?"Current plan":"Subscribe"}const c=document.getElementById("plans-checkout-btn-power");if(c){const d=e==="power"&&i;c.disabled=d,c.textContent=d?"Current plan":"Subscribe"}}function tb(){Ap();const t=document.getElementById("credits-modal");t&&We(t)}function nb(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("credits-modal");e&&ze(e)}function Pp(t,e=!0,n=!0){if(t=["home","account","plans"].includes(t)?t:"home",document.querySelectorAll(".view[data-view]").forEach(r=>{r.dataset.view===t?(r.hidden=!1,r.removeAttribute("inert"),requestAnimationFrame(()=>{r.classList.add("is-active"),n&&r.focus({preventScroll:!0})})):(r.classList.remove("is-active"),r.setAttribute("inert","true"),setTimeout(()=>{r.classList.contains("is-active")||(r.hidden=!0)},260))}),t!=="home")nn(!1);else{const r=document.getElementById("main-stage-container");r&&r.classList.contains("visible")&&nn(!0)}if(document.querySelectorAll(".nav-link[data-view]").forEach(r=>{const s=r.dataset.view===t;r.setAttribute("aria-current",s?"page":null),s||r.removeAttribute("aria-current")}),e){const r=t==="home"?"":`#${t}`;window.location.hash!==r&&window.history.pushState({view:t},"",r||"#")}}let fd=!1;function sc(){const t=window.location.hash.replace(/^#/,"");Pp(t||"home",!1,fd),fd=!0}window.addEventListener("popstate",t=>{sc()});window.addEventListener("hashchange",()=>{sc()});window.copyResultsCode=Xw;window.selectArtifact=rc;window.selectResultsSummary=kp;window.submitResultsFeedback=Qw;window.showErrorInputPanel=eb;window.hideErrorInputPanel=Cp;window.setGenerationStageVisible=nn;window.switchView=Pp;window.selectPipelineStage=Ow;window.editPipelinePrompt=Ja;window.retryPipelineRun=xp;window.openCreditsModal=tb;window.closeCreditsModal=nb; diff --git a/dist/index.html b/dist/index.html index 84fe68c..3ead2a9 100644 --- a/dist/index.html +++ b/dist/index.html @@ -3313,7 +3313,7 @@ .send.is-busy .send-spin { animation: none; opacity: 0.6; } } - + diff --git a/e2e/stu380-deploy.spec.js b/e2e/stu380-deploy.spec.js index c979347..b3340ab 100644 --- a/e2e/stu380-deploy.spec.js +++ b/e2e/stu380-deploy.spec.js @@ -593,6 +593,46 @@ test.describe("STU-380 transport outcome regressions", () => { expect(outcome.message).toContain("HTTP 502"); }); + test("a discarded 500 response's diagnostic read consumes its own stream", async ({ page }) => { + await loadDeployHooks(page); + // Teeing a stalled body with clone() would leave the ORIGINAL branch + // feeding a reader that doesn't exist — a locked original proves the + // diagnostic read (and its bound-cancel) releases the real connection. + const outcome = await page.evaluate(async () => { + const pushed = []; + window.fetch = (url) => { + if (!String(url).includes("syncCustomCodeChanges")) { + return Promise.resolve(new Response("{}", { status: 200 })); + } + const response = new Response( + new ReadableStream({ start() {} }), // never emits, never closes + { status: 500 }, + ); + pushed.push(response); + return Promise.resolve(response); + }; + try { + await window.__CCC_PUSH_CODE_WITH_RETRY__( + { project_id: "ff-proj-0007", zipped_custom_code: "eA==" }, + 1, + ); + return { settled: "resolved" }; + } catch (error) { + return { + settled: "rejected", + name: error.name, + locked: pushed.map((r) => r.body.locked), + count: pushed.length, + }; + } + }); + + expect(outcome.settled).toBe("rejected"); + expect(outcome.name).toBe("UnconfirmedDeployError"); + expect(outcome.count).toBe(2); // production + staging + expect(outcome.locked).toEqual([true, true]); + }); + test("a push that never answers settles unconfirmed instead of hanging", async ({ page }) => { await loadDeployHooks(page); @@ -953,4 +993,75 @@ test.describe("STU-380 transport outcome regressions", () => { await page.evaluate(() => window.__CCC_RESOLVE_PROJECT_PUBSPEC__({})); expect(exportCalls).toBe(2); }); + + test("a late-settling provision invalidates a snapshot cached mid-write", async ({ page }) => { + await loadDeployHooks(page); + + const zip = new JSZip(); + zip.file( + "pubspec.yaml", + "name: my_app\n\ndependencies:\n flutter:\n sdk: flutter\n", + ); + const projectZip = await zip.generateAsync({ type: "base64" }); + + let exportCalls = 0; + await page.route("**/exportCode", async (route) => { + exportCalls += 1; + await route.fulfill({ + status: 200, + contentType: "application/json", + body: JSON.stringify({ value: { project_zip: projectZip } }), + }); + }); + // The runner's stream opens but stays open past the UI bound — the + // underlying request keeps running (it may still write server-side). + // The test closes the stream afterwards to simulate late settlement. + await page.evaluate(() => { + const realFetch = window.fetch; + window.fetch = (url, ...args) => { + if (String(url).includes("deployCustomClasses")) { + const body = new ReadableStream({ + start(controller) { + window.__CCC_PROVISION_STREAM__ = controller; + }, + }); + return Promise.resolve( + new Response(body, { + status: 200, + headers: { "Content-Type": "application/x-ndjson" }, + }), + ); + } + return realFetch(url, ...args); + }; + }); + + const seeded = await page.evaluate(() => + window.__CCC_RESOLVE_PROJECT_PUBSPEC__({}), + ); + expect(exportCalls).toBe(1); + + const outcome = await settleAsOutcome( + page, + "__CCC_PROVISION_CUSTOM_CLASSES__", + [{ fileMap: newClassFileMap, uiTimeoutMs: 60 }], + ); + expect(outcome.name).toBe("UnconfirmedDeployError"); + + // A deploy that starts while the runner is still working re-exports and + // caches a snapshot that can predate the write. + await page.evaluate(() => window.__CCC_RESOLVE_PROJECT_PUBSPEC__({})); + expect(exportCalls).toBe(2); + + // When the provision request finally settles (runner finished, stream + // closed), that mid-write snapshot is dropped — the next deploy re-reads + // the project instead of provisioning the same class twice. + await page.evaluate(() => window.__CCC_PROVISION_STREAM__.close()); + await expect + .poll(async () => { + await page.evaluate(() => window.__CCC_RESOLVE_PROJECT_PUBSPEC__({})); + return exportCalls; + }) + .toBe(3); + }); }); From f6649b6b17d76b0c68b079c6c9e4c4ed25ed959d Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Sun, 27 Sep 2026 18:13:19 +0000 Subject: [PATCH 14/16] fix(deploy): track possibly-written files as dirty until an export proves them MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A provision request settling — stream closed, timeout, dropped connection — is not evidence the runner finished writing; a disconnect can precede the write. Settlement-time cache invalidation could still leave a snapshot exported mid-write permanently cached. Instead, each file an unconfirmed provision may have written is marked dirty per project: while any dirty path is outstanding, fresh exports are never cached, and the dirty path clears only when an export actually contains the file (the authoritative read). A confirmed provisioning result clears the paths it verified. Co-Authored-By: Stuart Gardoll --- app.js | 65 ++++++--- .../{index-Cltjl6vK.js => index-Bnh0pNOg.js} | 124 +++++++++--------- dist/index.html | 2 +- e2e/stu380-deploy.spec.js | 47 ++++--- 4 files changed, 141 insertions(+), 97 deletions(-) rename dist/assets/{index-Cltjl6vK.js => index-Bnh0pNOg.js} (69%) diff --git a/app.js b/app.js index 9aeed9a..4e5caf5 100644 --- a/app.js +++ b/app.js @@ -2669,6 +2669,16 @@ function getFileNameFromPath(filePath) { // the session. Fetching them means one full project export. const projectSourceCache = new Map(); +// File paths whose provisioning outcome is unconfirmed, per cache key — the +// request ended without a verified answer, so the runner may still be writing +// them. While any dirty path is outstanding, fresh exports must not be +// cached: a snapshot taken mid-write would keep telling later deploys the +// file is missing and provision it again. A fresh export that contains a +// dirty path proves the write landed, and is the only signal that clears it — +// the request settling is not proof (a disconnected stream can precede the +// write). +const projectSourceDirtyPaths = new Map(); + function projectSourceCacheKey(apiClient) { return `${apiClient.baseUrl}|${apiClient.projectId}|${apiClient.branchName}`; } @@ -2677,6 +2687,20 @@ function invalidateProjectSourceCache(apiClient) { projectSourceCache.delete(projectSourceCacheKey(apiClient)); } +function markProjectSourceDirty(apiClient, paths) { + const key = projectSourceCacheKey(apiClient); + const dirty = projectSourceDirtyPaths.get(key) ?? new Set(); + for (const path of paths) dirty.add(path); + projectSourceDirtyPaths.set(key, dirty); +} + +function clearProjectSourceDirty(apiClient, paths) { + const dirty = projectSourceDirtyPaths.get(projectSourceCacheKey(apiClient)); + if (!dirty) return; + for (const path of paths) dirty.delete(path); + if (dirty.size === 0) projectSourceDirtyPaths.delete(projectSourceCacheKey(apiClient)); +} + /** * Bounded waiting for a remote write. The UI shows live progress only while * this promise settles; once the bound expires the waiter stops claiming @@ -2804,12 +2828,8 @@ async function provisionMissingCodeFiles( // any response is still an unknown outcome — the POST may have reached the // server — so it maps to unconfirmed, not failed. let result; - // Kept outside the try: when the UI bound expires the work keeps running on - // the runner, and its eventual settlement needs to invalidate the cache a - // second time (a snapshot exported mid-write is still stale). - let provisionWork; try { - provisionWork = (async () => { + const provisionWork = (async () => { let response; try { response = await fetch(FLUTTERFLOW_CLASS_PROVISION_ENDPOINT, { @@ -2904,21 +2924,25 @@ async function provisionMissingCodeFiles( // the same classes a second time. if (error instanceof UnconfirmedDeployError) { invalidateProjectSourceCache(apiClient); - // The runner can still be writing after this browser stopped waiting. - // A deploy that starts in the meantime exports and caches a snapshot - // taken mid-write — stale the moment the runner's write lands. Drop the - // cache again when this request actually settles; snapshots cached - // after settlement postdate the write and are left alone. At worst a - // correct snapshot is dropped and the next deploy re-exports once. - provisionWork?.then( - () => invalidateProjectSourceCache(apiClient), - () => invalidateProjectSourceCache(apiClient), + // Every file this request may have written stays dirty until a fresh + // export shows it — the runner can keep working after the request is + // lost or the bound expires, and its settlement is not proof the write + // finished (or started). While dirty, exports are never cached. + markProjectSourceDirty( + apiClient, + missingCodeFiles.map((entry) => entry.path), ); } throw error; } invalidateProjectSourceCache(apiClient); + // A confirmed result proves these files were written — they are no longer + // dirty even if they were provisioned uncertainly in an earlier deploy. + clearProjectSourceDirty( + apiClient, + missingCodeFiles.map((entry) => entry.path), + ); if (result.verificationSkipped) { console.warn(`[custom class deploy] ${result.verificationSkipped}`); @@ -2986,7 +3010,18 @@ async function resolveProjectPubspec(apiClient, newDependencies = {}) { ); } - projectSourceCache.set(cacheKey, projectSource); + const dirtyPaths = projectSourceDirtyPaths.get(cacheKey); + if (dirtyPaths) { + // This fresh export is the authoritative read: every dirty path it + // shows is proven written and clears; the rest keep exports uncached. + for (const path of [...dirtyPaths]) { + if (projectSource.files.has(path)) dirtyPaths.delete(path); + } + if (dirtyPaths.size === 0) projectSourceDirtyPaths.delete(cacheKey); + } + if (!projectSourceDirtyPaths.has(cacheKey)) { + projectSourceCache.set(cacheKey, projectSource); + } } const plan = await planDependencyChanges( diff --git a/dist/assets/index-Cltjl6vK.js b/dist/assets/index-Bnh0pNOg.js similarity index 69% rename from dist/assets/index-Cltjl6vK.js rename to dist/assets/index-Bnh0pNOg.js index 80fc518..e1dbe66 100644 --- a/dist/assets/index-Cltjl6vK.js +++ b/dist/assets/index-Bnh0pNOg.js @@ -1,8 +1,8 @@ -(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const s of r)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function n(r){const s={};return r.integrity&&(s.integrity=r.integrity),r.referrerPolicy&&(s.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?s.credentials="include":r.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function i(r){if(r.ep)return;r.ep=!0;const s=n(r);fetch(r.href,s)}})();var w=typeof window<"u"?window:void 0,Ne=typeof globalThis<"u"?globalThis:w,He=Ne?.navigator,P=Ne?.document,me=Ne?.location,Xa=Ne?.fetch,zo=Ne!=null&&Ne.XMLHttpRequest&&"withCredentials"in new Ne.XMLHttpRequest?Ne.XMLHttpRequest:void 0,fc=Ne?.AbortController,Np=Ne?.CompressionStream,Ge=He?.userAgent;function hd(){return!(!w||w.navigator.onLine===!1)}var _i=typeof globalThis<"u"?globalThis:w;_i&&typeof self>"u"&&(_i.self=_i),_i&&typeof File>"u"&&(_i.File=function(){});var B=w??{},ne={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function hc(t,e,n,i,r,s,o){try{var a=t[s](o),l=a.value}catch(u){return void n(u)}a.done?e(l):Promise.resolve(l).then(i,r)}function se(t){return function(){var e=this,n=arguments;return new Promise((function(i,r){var s=t.apply(e,n);function o(l){hc(s,i,r,o,a,"next",l)}function a(l){hc(s,i,r,o,a,"throw",l)}o(void 0)}))}}function I(){return I=Object.assign?Object.assign.bind():function(t){for(var e=1;arguments.length>e;e++){var n=arguments[e];for(var i in n)({}).hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},I.apply(null,arguments)}function pd(t,e){if(t==null)return{};var n={};for(var i in t)if({}.hasOwnProperty.call(t,i)){if(e.indexOf(i)!==-1)continue;n[i]=t[i]}return n}var pc=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function gc(t){return typeof t=="string"||t}function mc(t){return typeof t=="string"?t:void 0}var yi,Op=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],Ut=(function(t){return t.AnonymousId="anonymous_id",t.DistinctId="distinct_id",t.Props="props",t.EnablePersonProcessing="enable_person_processing",t.PersonMode="person_mode",t.FeatureFlagDetails="feature_flag_details",t.FeatureFlags="feature_flags",t.FeatureFlagPayloads="feature_flag_payloads",t.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",t.BootstrapFeatureFlags="bootstrap_feature_flags",t.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",t.OverrideFeatureFlags="override_feature_flags",t.Queue="queue",t.AiQueue="ai_queue",t.LogsQueue="logs_queue",t.OptedOut="opted_out",t.SessionId="session_id",t.SessionStartTimestamp="session_start_timestamp",t.SessionLastTimestamp="session_timestamp",t.PersonProperties="person_properties",t.GroupProperties="group_properties",t.InstalledAppBuild="installed_app_build",t.InstalledAppVersion="installed_app_version",t.SessionReplay="session_replay",t.PushRegistered="push_registered",t.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",t.SurveyLastSeenDate="survey_last_seen_date",t.SurveysSeen="surveys_seen",t.Surveys="surveys",t.RemoteConfig="remote_config",t.FlagsEndpointWasHit="flags_endpoint_was_hit",t.DeviceId="device_id",t})({}),vc=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),Bp=["$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"],Dp=["token"],gd="NativeGzipValidationError",qo=t=>t.length>=2&&t[0]===31&&t[1]===139,_c=(t,e)=>t===vc.GZipJS||e===vc.GZipJS||e==="gzip",yc=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",pr=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=gd,e},jp=(function(){var t=se((function*(e,n){18>e.size&&pr("too-short");var i=new Uint8Array(yield e.slice(0,10).arrayBuffer());qo(i)&&i[2]===8||pr("invalid-header");var r=new DataView(yield e.slice(e.size-8).arrayBuffer());r.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(yi)return yi;yi=[];for(var c=0;256>c;c++){for(var d=c,f=0;8>f;f++)d=1&d?3988292384^d>>>1:d>>>1;yi[c]=d>>>0}return yi})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(n)&&pr("invalid-crc");var s=n.length>>>0;r.getUint32(4,!0)!==s&&pr("invalid-size")}));return function(e,n){return t.apply(this,arguments)}})();function Vo(){return Vo=se((function*(t,e,n){e===void 0&&(e=!0);try{var i=new TextEncoder().encode(t),r=new globalThis.CompressionStream("gzip"),s=r.writable.getWriter(),o=s.write(i).then((()=>s.close())).catch((function(){var u=se((function*(c){try{yield s.abort(c)}catch{}throw c}));return function(c){return u.apply(this,arguments)}})()),a=new Response(r.readable).blob(),l=(yield Promise.all([a,o]))[0];return yield jp(l,i),l}catch(u){if(n!=null&&n.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),Vo.apply(this,arguments)}var Up=["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"],wc=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var n=t.toLowerCase();return Up.concat(e).some((i=>{var r=i.toLowerCase();return n.indexOf(r)!==-1}))};function j(t,e){return t.indexOf(e)!==-1}var xs=function(t){return t.trim()},Go=function(t){return t.replace(/^\$/,"")};function md(t){var e,n=[];return(e=JSON.stringify(t,(function(i,r){if(typeof r=="bigint")return r.toString();if(typeof r!="function"&&typeof r!="symbol"){if(r instanceof Error)return{name:r.name,message:r.message,stack:r.stack};if(r&&typeof r=="object"){for(;n.length>0&&n[n.length-1]!==this;)n.pop();if(n.includes(r))return"[Circular]";n.push(r)}return r}})))!==null&&e!==void 0?e:"null"}var vd=Object.prototype,_d=vd.hasOwnProperty,Is=vd.toString,U=Array.isArray||function(t){return Is.call(t)==="[object Array]"},je=t=>typeof t=="function",he=t=>t===Object(t)&&!U(t),Kt=t=>{if(he(t)){for(var e in t)if(_d.call(t,e))return!1;return!0}return!1},C=t=>t===void 0,X=t=>Is.call(t)=="[object String]",Ko=t=>X(t)&&t.trim().length===0,Ye=t=>t===null,H=t=>C(t)||Ye(t),ke=t=>Is.call(t)=="[object Number]"&&t==t,Dt=t=>ke(t)&&t>0,mt=t=>Is.call(t)==="[object Boolean]",Hp=t=>t instanceof FormData,Wp=t=>j(Bp,t),zp=t=>j(Dp,t);function yd(t){return t===null||typeof t!="object"}function Hr(t,e){return{}.toString.call(t)==="[object "+e+"]"}function Qa(t){return typeof Event<"u"&&wd(t,Event)}function wd(t,e){try{return t instanceof e}catch{return!1}}var qp=[!0,"true",1,"1","yes"],uo=t=>j(qp,t),Vp=[!1,"false",0,"0","no"];function At(t,e,n,i,r){return e>n&&(i.warn("min cannot be greater than max."),e=n),ke(t)?t>n?(i.warn(" cannot be greater than max: "+n+". Using max value instead."),n):e>t?(i.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(i.warn(" must be a number. using max or fallback. max: "+n+", fallback: "+r),At(r||n,e,n,i))}class Gp{constructor(e){this.tt={},this.et=e.et,this.it=At(e.bucketSize,0,100,e.rt),this.nt=At(e.refillRate,0,this.it,e.rt),this.st=At(e.refillInterval,0,864e5,e.rt)}ot(e,n){var i=Math.floor((n-e.lastAccess)/this.st);i>0&&(e.tokens=Math.min(e.tokens+i*this.nt,this.it),e.lastAccess=e.lastAccess+i*this.st)}consumeRateLimit(e){var n,i=Date.now(),r=String(e),s=this.tt[r];return s?this.ot(s,i):this.tt[r]=s={tokens:this.it,lastAccess:i},s.tokens===0||(s.tokens--,s.tokens===0&&((n=this.et)==null||n.call(this,e)),s.tokens===0)}stop(){this.tt={}}}var rt="Mobile",Wr="iOS",Yt="Android",ti="Tablet",bd=Yt+" "+ti,Ed="iPad",Sd="Apple",xd=Sd+" Watch",Di="Safari",ni="BlackBerry",Id="Samsung",kd=Id+"Browser",Cd=Id+" Internet",Fn="Chrome",Kp=Fn+" OS",Ad=Fn+" "+Wr,el="Internet Explorer",Pd=el+" "+rt,tl="Opera",Yp=tl+" Mini",nl="Edge",Fd="Microsoft "+nl,Xn="Firefox",Rd=Xn+" "+Wr,Ki="Nintendo",Yi="PlayStation",Qn="Xbox",Td=Yt+" "+rt,$d=rt+" "+Di,Fi="Windows",Yo=Fi+" Phone",bc="Nokia",Jo="Ouya",Md="Generic",Jp=Md+" "+rt.toLowerCase(),Ld=Md+" "+ti.toLowerCase(),Zo="Konqueror",Nd="Oculus Browser",zr="Vivaldi",Od="Yandex",qr="Whale",Xo="DuckDuckGo",Bd="Pale Moon",Vr="Waterfox",ji="Brave",Dd="Google Search App",we="(\\d+(\\.\\d+)?)",fo=new RegExp("Version/"+we),Zp=new RegExp(Qn,"i"),Xp=new RegExp(Yi+" \\w+","i"),Qp=new RegExp(Ki+" \\w+","i"),il=new RegExp(ni+"|PlayBook|BB10","i"),eg={"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"},jd=function(t,e,n,i){e=e||"";var r=(function(s){return s!=null&&s.brave?ji:null})(n);return r||(i!=null&&i.detectGoogleSearchApp&&j(t,"GSA/")?Dd:j(t," OPR/")&&j(t,"Mini")?Yp:j(t," OPR/")?tl:il.test(t)?ni:j(t,"IE"+rt)||j(t,"WPDesktop")?Pd:j(t,"OculusBrowser")?Nd:j(t,kd)?Cd:j(t,nl)||j(t,"Edg/")?Fd:j(t,zr+"/")?zr:j(t,"YaBrowser/")?Od:j(t,qr+"/")?qr:j(t,Xo+"/")||j(t,"Ddg/")?Xo:j(t,"FBIOS")?"Facebook "+rt:j(t,"UCWEB")||j(t,"UCBrowser")?"UC Browser":j(t,"CriOS")?Ad:j(t,"CrMo")||j(t,Fn)?Fn:j(t,Yt)&&j(t,Di)?Td:j(t,"FxiOS")?Rd:j(t.toLowerCase(),Zo.toLowerCase())?Zo:j(t,ji+"/")?ji:((s,o)=>o&&j(o,Sd)||(function(a){return j(a,Di)&&!j(a,Fn)&&!j(a,Yt)})(s))(t,e)?j(t,rt)?$d:Di:j(t,"PaleMoon/")?Bd:j(t,Vr+"/")?Vr:j(t,Xn)?Xn:j(t,"MSIE")||j(t,"Trident/")?el:j(t,"Gecko")?Xn:"")},tg={[Pd]:[new RegExp("rv:"+we)],[Fd]:[new RegExp(nl+"?\\/"+we)],[Fn]:[new RegExp("("+Fn+"|CrMo)\\/"+we)],[Ad]:[new RegExp("CriOS\\/"+we)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+we)],[Di]:[fo],[$d]:[fo],[tl]:[new RegExp("(Opera|OPR)\\/"+we)],[Xn]:[new RegExp(Xn+"\\/"+we)],[Rd]:[new RegExp("FxiOS\\/"+we)],[Zo]:[new RegExp("Konqueror[:/]?"+we,"i")],[ni]:[new RegExp(ni+" "+we),fo],[Td]:[new RegExp("android\\s"+we,"i")],[Cd]:[new RegExp(kd+"\\/"+we)],[Nd]:[new RegExp("OculusBrowser\\/"+we)],[zr]:[new RegExp(zr+"\\/"+we)],[Od]:[new RegExp("YaBrowser\\/"+we)],[qr]:[new RegExp(qr+"\\/"+we)],[ji]:[new RegExp(ji+"\\/"+we)],[Xo]:[new RegExp("(DuckDuckGo|Ddg)\\/"+we)],[Bd]:[new RegExp("PaleMoon\\/"+we)],[Vr]:[new RegExp(Vr+"\\/"+we)],[Dd]:[new RegExp("GSA\\/"+we)],[el]:[new RegExp("(rv:|MSIE )"+we)],Mozilla:[new RegExp("rv:"+we)]},ng=function(t,e,n,i){var r=jd(t,e,n,i),s=tg[r];if(C(s))return null;for(var o=0;s.length>o;o++){var a=t.match(s[o]);if(a)return parseFloat(a[a.length-2])}return null},Ec=[[new RegExp(Qn+"; "+Qn+" (.*?)[);]","i"),t=>[Qn,t&&t[1]||""]],[new RegExp(Ki,"i"),[Ki,""]],[new RegExp(Yi,"i"),[Yi,""]],[il,[ni,""]],[new RegExp(Fi,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Yo,""];if(new RegExp(rt).test(e)&&!/IEMobile\b/.test(e))return[Fi+" "+rt,""];var n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){var i=eg[n[1]]||"";return/arm/i.test(e)&&(i="RT"),[Fi,i]}return[Fi,""]}],[/((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=C(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+Yt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Yt+")","i"),t=>t&&t[2]?[Yt,[t[2],t[3],t[4]||"0"].join(".")]:[Yt,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{var e=["Mac OS X",""];return t&&t[1]&&(e[1]=[t[1],t[2],t[3]||"0"].join(".")),e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[Kp,""]],[/Linux|debian/i,["Linux",""]]],Sc=function(t){return Qp.test(t)?Ki:Xp.test(t)?Yi:Zp.test(t)?Qn:new RegExp(Jo,"i").test(t)?Jo:new RegExp("("+Yo+"|WPDesktop)","i").test(t)?Yo:/iPad/.test(t)?Ed:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?xd:il.test(t)?ni:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(bc,"i").test(t)?bc:/(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(rt).test(t)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(t)||/pixel[\daxl ]{1,6}/i.test(t)&&!/pixel c/i.test(t)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(t)||/lmy47v/i.test(t)&&!/QTAQZ3/i.test(t)?Yt:bd:new RegExp("(pda|"+rt+")","i").test(t)?Jp:new RegExp(ti,"i").test(t)&&!new RegExp(ti+" pc","i").test(t)?Ld:""},ig=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function xc(t,e){return typeof(n=t)=="string"&&ig.test(n)?t:e();var n}function fn(t){return t&&t.split("#")[0]}function rl(t,e){var n=setTimeout(t,e);return n?.unref&&n?.unref(),n}function Ic(t,e,n){return Ud.apply(this,arguments)}function Ud(){return(Ud=se((function*(t,e,n){var i;try{return yield Promise.race([t,new Promise(((r,s)=>{i=rl((()=>{try{n?.(),r()}catch(o){s(o)}}),e)}))])}finally{clearTimeout(i)}}))).apply(this,arguments)}var rg=t=>t instanceof Error,Hd={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}},sg=Hd.info;function Wd(t){if(mt(t))return{boolValue:t};if(typeof t=="number")return Number.isFinite(t)?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:{stringValue:String(t)};if(typeof t=="string")return{stringValue:t};if(U(t))return{arrayValue:{values:t.map((e=>Wd(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function Gr(t){var e=[];for(var n in t){var i=t[n];Ye(i)||C(i)||e.push({key:n,value:Wd(i)})}return e}function og(t,e){var n=Hd[t.level||"info"]||sg,i=n.text,r=n.number,s=String(Date.now())+"000000",o={};e.distinctId&&(o.posthogDistinctId=e.distinctId),e.sessionId&&(o.sessionId=e.sessionId),e.windowId&&(o["window.id"]=e.windowId),H(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),H(e.lastActivityTimestamp)||(o.lastActivityTimestamp=String(e.lastActivityTimestamp)),e.currentUrl&&(o["url.full"]=e.currentUrl),e.screenName&&(o["screen.name"]=e.screenName),e.appState&&(o["app.state"]=e.appState),e.activeFeatureFlags&&e.activeFeatureFlags.length>0&&(o.feature_flags=e.activeFeatureFlags);var a=I({},o,t.attributes||{}),l={timeUnixNano:s,observedTimeUnixNano:s,severityNumber:r,severityText:i,body:{stringValue:t.body},attributes:Gr(a)};return t.trace_id&&(l.traceId=t.trace_id),t.span_id&&(l.spanId=t.span_id),C(t.trace_flags)||(l.flags=t.trace_flags),l}function zd(t,e,n){return I({},t.resourceAttributes,{"service.name":t.serviceName||"unknown_service"},t.environment&&{"deployment.environment":t.environment},t.serviceVersion&&{"service.version":t.serviceVersion},{"telemetry.sdk.name":e,"telemetry.sdk.version":n})}function qd(t,e,n,i){return{resourceLogs:[{resource:{attributes:Gr(e)},scopeLogs:[{scope:{name:n,version:i},logRecords:t}]}]}}let ag=class{constructor(t,e,n,i,r,s,o){var a;s===void 0&&(s=()=>Promise.resolve()),this._instance=t,this.Ne=e,this.rt=n,this.ut=i,this.ht=r,this.dt=s,this.vt=o,this.ct=null,this.ft=0,this.yt=0,this.bt=0,this._t=0,this.wt=!1,this.kt=e.maxBufferSize,this.xt=Math.max((a=e.maxQueueSize)!==null&&a!==void 0?a:e.maxBufferSize,e.maxBufferSize),this.St=e.flushIntervalMs,this.Ct=e.maxBatchRecordsPerPost,this.Mt=e.rateCapWindowMs,this.Tt=e.maxLogsPerInterval}reset(){this.Et(),this.ct=null,this.bt=0,this._t=0,this.wt=!1,this.ft=0,this.yt=0,this.Ct=this.Ne.maxBatchRecordsPerPost}onReconnect(){this.yt=0,this.It()}captureLog(t){if(!this._instance.isDisabled&&!this._instance.optedOut&&t!=null&&t.body){var e=this.Pt(t);if(e!==null)if(e.body){if(this.Rt()){var n={record:og(e,this.ut())};this.ht((()=>this.At(n)))}}else this.rt.info("Log was rejected in beforeSend function")}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Log was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for log:",o),null}return i}Rt(){if(this.Tt===void 0)return!0;var t=Date.now(),e=t-this.bt;return this.Mt>e&&e>=0||(this.bt=t,this._t=0,this.wt=!1),this.Tt>this._t?(this._t++,!0):(this.wt||(this.rt.warn("captureLog dropping logs: exceeded "+this.Tt+" logs per "+this.Mt+"ms"),this.wt=!0),!1)}flush(){var t=this;return se((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return se((function*(){var e;t.Et();var n=(e=t._instance.getPersistedProperty(Ut.LogsQueue))!==null&&e!==void 0?e:[];if(n.length!==0)for(var i=n.length,r=0;n.length>0&&i>r;){var s,o;t.ft=0;var a=Math.min(n.length,t.Ct),l=n.slice(0,a),u=qd(l.map((d=>d.record)),t.Lt(),(s=t.vt)!==null&&s!==void 0?s:t._instance.getLibraryId(),t._instance.getLibraryVersion()),c=yield t._instance.Ot(u);if(c.kind==="too-large"&&l.length>1)t.Ct=Math.max(1,Math.floor(l.length/2)),t.rt.warn("Received 413 when sending logs batch of size "+l.length+", reducing batch size to "+t.Ct);else if(c.kind==="retry-later"||(c.kind==="too-large"?t.rt.warn("Dropping a single log record after 413 with batch size 1 — the record is larger than the server cap and cannot be split further."):c.kind==="ok"&&t.Ne.maxBatchRecordsPerPost>t.Ct&&(t.Ct=Math.min(t.Ne.maxBatchRecordsPerPost,t.Ct+1)),yield t.Dt(l.length),n=(o=t._instance.getPersistedProperty(Ut.LogsQueue))!==null&&o!==void 0?o:[],r+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return se((function*(){var n,i=Math.max(0,t-e.ft),r=(n=e._instance.getPersistedProperty(Ut.LogsQueue))!==null&&n!==void 0?n:[];e._instance.setPersistedProperty(Ut.LogsQueue,r.slice(i)),yield e.dt()}))()}Lt(){return zd(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var n=(e=this._instance.getPersistedProperty(Ut.LogsQueue))!==null&&e!==void 0?e:[];this.xt>n.length||(n.shift(),this.ft++,this.rt.info("Logs queue is full, dropping oldest record.")),n.push(t),this._instance.setPersistedProperty(Ut.LogsQueue,n),this.kt>n.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=rl((()=>{this.Nt=void 0,this.It()}),t))}qt(){var t=Math.min(Math.max(0,this.yt-1),6);return this.St*Math.pow(2,t)}jt(){var t=this._instance.getPersistedProperty(Ut.LogsQueue);return!!t&&t.length>0}shutdown(t){var e=this;return se((function*(){e.Et();var n=e.flush().catch((()=>{}));t!==void 0?yield Ic(n,t):yield n}))()}flushWithTimeout(t){var e=this;return se((function*(){var n=e.flush();yield Ic(n,t,(()=>{n.catch((()=>{}))}))}))()}It(){this.flush().then((()=>{this.yt=0}),(t=>{this.yt++,this.rt.error("PostHog logs flush failed:",t)})).finally((()=>{!this._instance.isDisabled&&this.jt()&&this.$t(this.qt())}))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}};var ho=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function kc(t){return String(t)+"000000"}function Cc(t,e,n,i){var r="";return i&&(r=Object.keys(i).sort().map((s=>JSON.stringify(s)+":"+JSON.stringify(i[s]))).join(",")),t+"\0"+e+"\0"+(n??"")+"\0"+r}let lg=class{constructor(t,e,n){this._instance=t,this.Ne=e,this.rt=n,this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Wt=0}count(t,e,n){e===void 0&&(e=1),this.Vt({name:t,type:"count",value:e,unit:n?.unit,attributes:n?.attributes})}gauge(t,e,n){this.Vt({name:t,type:"gauge",value:e,unit:n?.unit,attributes:n?.attributes})}histogram(t,e,n){this.Vt({name:t,type:"histogram",value:e,unit:n?.unit,attributes:n?.attributes})}flush(){var t=this,e=this.ct,n=(function(){var r=se((function*(){e&&(yield e.catch((()=>{}))),yield t.Zt()}));return function(){return r.apply(this,arguments)}})(),i=n().finally((()=>{this.ct===i&&(this.ct=null)}));return this.ct=i,i}drainWindow(){if(this.Bt.size===0)return null;var t=this.Bt;return this.Bt=new Map,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Gt(t)}reset(){this.Wt++,this.Et(),this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set}Vt(t){if(!this._instance.isDisabled&&!this._instance.optedOut){var e=this.Pt(t);if(e!==null)if(e.name&&typeof e.name=="string")if(typeof e.value=="number"&&Number.isFinite(e.value))if(e.type==="count"&&0>e.value)this.rt.warn("Dropping count '"+e.name+"': counters are monotonic, value must be >= 0");else{var n,i;try{n=e.attributes?I({},e.attributes):void 0,i=Cc(e.type,e.name,e.unit,n)}catch(o){return void this.rt.warn("Dropping metric '"+e.name+"': attributes could not be serialized",o)}var r=this.Bt.get(i);if(!r){if(!this.Qt())return;r={name:e.name,type:e.type,unit:e.unit,attributes:n,windowStartMs:Date.now()},this.Bt.set(i,r)}var s=this.Ut.get(e.name);s===void 0?this.Ut.set(e.name,e.type):s===e.type||this.zt.has(e.name)||(this.zt.add(e.name),this.rt.warn("Metric name '"+e.name+"' is already used as a "+s+"; recording it as a "+e.type+" too will blend both series in charts. Use a distinct name.")),this.Kt(r,e.value),this.$t()}else this.rt.warn("Dropping metric '"+e.name+"': value must be a finite number");else this.rt.warn("Dropping metric with empty name")}}Qt(){return this.Ne.maxSeriesPerFlush>this.Bt.size||(this.Ht||(this.Ht=!0,this.rt.warn("Metric series cap reached ("+this.Ne.maxSeriesPerFlush+" per flush window); dropping new series until the next flush. Reduce attribute cardinality.")),!1)}Kt(t,e){var n;switch(t.type){case"count":t.total=((n=t.total)!==null&&n!==void 0?n:0)+e;break;case"gauge":t.last=e;break;case"histogram":t.hist||(t.hist={count:0,sum:0,min:e,max:e,bucketCounts:new Array(ho.length+1).fill(0)});var i=t.hist;i.count+=1,i.sum+=e,i.min=Math.min(i.min,e),i.max=Math.max(i.max,e),i.bucketCounts[(function(r,s){for(var o=0;s.length>o;o++)if(s[o]>=r)return o;return s.length})(e,ho)]+=1}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Metric was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for metric:",o),null}return i}$t(){this.Nt||(this.Nt=rl((()=>{this.Nt=void 0,this.flush().catch((t=>{this.rt.error("Metrics flush failed:",t)}))}),this.Ne.flushIntervalMs))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}Zt(){var t=this;return se((function*(){if(t.Bt.size!==0){var e=t.Bt;t.Bt=new Map,t.Ht=!1,t.Ut=new Map,t.zt=new Set;var n=t.Wt,i=yield t._instance.Jt(t.Gt(e));if(n===t.Wt)switch(i.kind){case"ok":return;case"retry-later":return t.Yt(e),void t.$t();case"too-large":return void t.rt.warn("Metrics batch exceeded the server size limit and was dropped");case"fatal":return void t.rt.error("Failed to send metrics batch:",i.error)}}}))()}Gt(t){return e=this.Xt(t),n=(function(s,o,a){return I({},s.resourceAttributes,{"service.name":s.serviceName||"unknown_service"},s.environment&&{"deployment.environment":s.environment},s.serviceVersion&&{"service.version":s.serviceVersion},{"telemetry.sdk.name":o,"telemetry.sdk.version":a})})(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion()),i=this._instance.getLibraryId(),r=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:Gr(n)},scopeMetrics:[{scope:{name:i,version:r},metrics:e}]}]};var e,n,i,r}Xt(t){var e=kc(Date.now()),n=new Map;for(var i of t.values()){var r,s=Cc(i.type,i.name,i.unit,void 0),o=n.get(s);o||(o=I({name:i.name},i.unit&&{unit:i.unit}),i.type==="count"?o.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:i.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:1,dataPoints:[]},n.set(s,o));var a=Gr((r=i.attributes)!==null&&r!==void 0?r:{}),l=kc(i.windowStartMs);if(i.type==="count"){var u,c={attributes:a,startTimeUnixNano:l,timeUnixNano:e,asDouble:(u=i.total)!==null&&u!==void 0?u:0};o.sum.dataPoints.push(c)}else if(i.type==="gauge"){var d,f={attributes:a,timeUnixNano:e,asDouble:(d=i.last)!==null&&d!==void 0?d:0};o.gauge.dataPoints.push(f)}else i.hist&&o.histogram.dataPoints.push({attributes:a,startTimeUnixNano:l,timeUnixNano:e,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:ho})}return Array.from(n.values())}Yt(t){var e,n;for(var i of t){var r=i[0],s=i[1],o=this.Bt.get(r);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,s.windowStartMs),o.type){case"count":o.total=((e=o.total)!==null&&e!==void 0?e:0)+((n=s.total)!==null&&n!==void 0?n:0);break;case"gauge":break;case"histogram":if(s.hist)if(o.hist){o.hist.count+=s.hist.count,o.hist.sum+=s.hist.sum,o.hist.min=Math.min(o.hist.min,s.hist.min),o.hist.max=Math.max(o.hist.max,s.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=s.hist.bucketCounts[a]}else o.hist=s.hist}else this.Qt()&&this.Bt.set(r,s)}}};var gr,Ac,po;function cg(t){var e=globalThis._posthogChunkIds;if(e){var n=Object.keys(e);return po&&n.length===Ac||(Ac=n.length,po=n.reduce(((i,r)=>{gr||(gr={});var s=gr[r];if(s)i[s[0]]=s[1];else for(var o=t(r),a=o.length-1;a>=0;a--){var l=o[a],u=l?.filename,c=e[r];if(u&&c){i[u]=c,gr[r]=[u,c];break}}return i}),{})),po}}class ug{constructor(e,n,i){i===void 0&&(i=[]),this.coercers=e,this.stackParser=n,this.modifiers=i}buildFromUnknown(e,n){n===void 0&&(n={});var i=n&&n.mechanism||{handled:!0,type:"generic"},r=this.buildCoercingContext(i,n,0).apply(e),s=this.buildParsingContext(n),o=this.parseStacktrace(r,s);return{$exception_list:this.convertToExceptionList(o,i),$exception_level:"error"}}modifyFrames(e){var n=this;return se((function*(){for(var i of e)i.stacktrace&&i.stacktrace.frames&&U(i.stacktrace.frames)&&(i.stacktrace.frames=yield n.applyModifiers(i.stacktrace.frames));return e}))()}coerceFallback(e){var n;return{type:"Error",value:"Unknown error",stack:(n=e.syntheticException)==null?void 0:n.stack,synthetic:!0}}parseStacktrace(e,n){var i,r;return e.cause!=null&&(i=this.parseStacktrace(e.cause,n)),e.stack!=""&&e.stack!=null&&(r=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?n.skipFirstLines:0),n.chunkIdMap)),I({},e,{cause:i,stack:r})}applyChunkIds(e,n){return e.map((i=>(i.filename&&n&&(i.chunk_id=n[i.filename]),i)))}applyCoercers(e,n){for(var i of this.coercers)if(i.match(e))return i.coerce(e,n);return this.coerceFallback(n)}applyModifiers(e){var n=this;return se((function*(){var i=e;for(var r of n.modifiers)i=yield r(i);return i}))()}convertToExceptionList(e,n){var i,r,s,o={type:e.type,value:e.value,mechanism:{type:(i=n.type)!==null&&i!==void 0?i:"generic",handled:(r=n.handled)===null||r===void 0||r,synthetic:(s=e.synthetic)!==null&&s!==void 0&&s}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,I({},n,{handled:!0}))),a}buildParsingContext(e){var n;return{chunkIdMap:cg(this.stackParser),skipFirstLines:(n=e.skipFirstLines)!==null&&n!==void 0?n:1}}buildCoercingContext(e,n,i){i===void 0&&(i=0);var r=(s,o)=>{if(4>=o){var a=this.buildCoercingContext(e,n,o);return this.applyCoercers(s,a)}};return I({},n,{syntheticException:i==0?n.syntheticException:void 0,mechanism:e,apply:s=>r(s,i),next:s=>r(s,i+1)})}}var ii="?";function Qo(t,e,n,i,r){var s={platform:t,filename:e,function:n===""?ii:n,in_app:!0};return C(i)||(s.lineno=i),C(r)||(s.colno=r),s}var Vd=(t,e)=>{var n=t.indexOf("safari-extension")!==-1,i=t.indexOf("safari-web-extension")!==-1;return n||i?[t.indexOf("@")!==-1?t.split("@")[0]:ii,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},dg=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,fg=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,hg=/\((\S*)(?::(\d+))(?::(\d+))\)/,pg=(t,e)=>{var n=dg.exec(t);if(n)return Qo(e,n[1],ii,+n[2],+n[3]);var i=fg.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var r=hg.exec(i[2]);r&&(i[2]=r[1],i[3]=r[2],i[4]=r[3])}var s=Vd(i[1]||ii,i[2]);return Qo(e,s[1],s[0],i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},gg=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,mg=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,vg=(t,e)=>{var n=gg.exec(t);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){var i=mg.exec(n[3]);i&&(n[1]=n[1]||"eval",n[3]=i[1],n[4]=i[2],n[5]="")}var r=n[3],s=n[1]||ii,o=Vd(s,r);return Qo(e,r=o[1],s=o[0],n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},Pc=/\(error: (.*)\)/;class _g{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,n){var i=X(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:i?e.stack:void 0,cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var n=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?n+": "+e.message:n}isDOMException(e){return Hr(e,"DOMException")}isDOMError(e){return Hr(e,"DOMError")}}class yg{match(e){return(function(n){switch({}.toString.call(n)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return wd(n,Error)}})(e)}coerce(e,n){return{type:this.getType(e),value:this.getMessage(e,n),stack:this.getStack(e),cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,n){var i=e.message;return String(i.error&&typeof i.error.message=="string"?i.error.message:i)}getStack(e){return e.stacktrace||e.stack||void 0}}class wg{constructor(){}match(e){return!!Hr(e,"ErrorEvent")&&(e.error!=null||this.fe(e))}coerce(e,n){var i;if(e.error!=null)return n.apply(e.error);var r=n.apply(e.message);return I({},r,{stack:(i=this.pe(e))!==null&&i!==void 0?i:r.stack,synthetic:!0})}fe(e){return X(e.message)&&e.message.length>0}pe(e){var n=e;if(X(n.filename)&&n.filename.length>0){var i,r,s=(i=n.lineno)!==null&&i!==void 0?i:0,o=(r=n.colno)!==null&&r!==void 0?r:0;return`Error - at `+n.filename+":"+s+":"+o}}}var bg=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class Eg{match(e){return typeof e=="string"}coerce(e,n){var i,r=this.getInfos(e),s=r[0],o=r[1];return{type:s??"Error",value:o??e,stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}getInfos(e){var n="Error",i=e,r=e.match(bg);return r&&(n=r[1],i=r[2]),[n,i]}}var Sg=["fatal","error","warning","log","info","debug"];function Gd(t,e){e===void 0&&(e=40);var n=Object.keys(t);if(n.sort(),!n.length)return"[object has no keys]";for(var i=n.length;i>0;i--){var r=n.slice(0,i).join(", ");if(e>=r.length)return i===n.length?r:r.length>e?r.slice(0,e)+"...":r}return""}class xg{match(e){return typeof e=="object"&&e!==null}coerce(e,n){var i,r,s=this.getErrorPropertyFromObject(e);return s?n.apply(s):{type:this.getType(e),value:this.getValue(e),stack:(i=this.getStack(e))!==null&&i!==void 0?i:(r=n.syntheticException)==null?void 0:r.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return Qa(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var n="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(n+=" with message: '"+e.message+"'"),n}if("message"in e&&typeof e.message=="string")return e.message;var i=this.getObjectClassName(e);return(i&&i!=="Object"?"'"+i+"'":"Object")+" captured as exception with keys: "+Gd(e)}isSeverityLevel(e){return X(e)&&!Ko(e)&&Sg.indexOf(e)>=0}getStack(e){try{return X(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:X(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(var n in e)if({}.hasOwnProperty.call(e,n)){var i=e[n];if(rg(i))return i}}getObjectClassName(e){try{var n=Object.getPrototypeOf(e);return n?n.constructor.name:void 0}catch{return}}}class Ig{match(e){return Qa(e)}coerce(e,n){var i,r=e.constructor.name;return{type:r,value:r+" captured as exception with keys: "+Gd(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class kg{match(e){return yd(e)}coerce(e,n){var i;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class Cg{match(e){return Hr(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Qa(e))return!1;try{var n=e.detail;return n!=null&&typeof n=="object"&&"reason"in n}catch{return!1}}coerce(e,n){var i,r=this.getUnhandledRejectionReason(e);return yd(r)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(r),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}:n.apply(r)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}}var Kr="$message",Yr="$timestamp",Ag=new Set([Kr,Yr]),go={enabled:!0,max_bytes:32768};function Jr(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:go.enabled,max_bytes:Fg(t.max_bytes,go.max_bytes)}:I({},go)}class Pg{constructor(e){this.Ke=[],this.Je=0,this.Ne=Jr(e)}setConfig(e){this.Ne=Jr(e),this.Xe()}add(e){var n=(function(r){var s;try{s=md(r)}catch{return}try{var o=JSON.parse(s);if(!he(o))return;var a=o,l=a[Kr],u=a[Yr];return!X(l)||l.trim().length===0||!X(u)&&!ke(u)?void 0:{step:a,json:s}}catch{return}})(e);if(n){var i=(function(r){if(typeof TextEncoder<"u")return new TextEncoder().encode(r).length;for(var s=encodeURIComponent(r),o=0,a=0;s.length>a;a++)s[a]==="%"?(o+=1,a+=2):o+=1;return o})(n.json);i>this.Ne.max_bytes||(this.Ke.push({step:n.step,bytes:i}),this.Je+=i,this.Xe())}}getAttachable(){return this.Ke.map((e=>e.step))}clear(){this.Ke=[],this.Je=0}size(){return this.Ke.length}Xe(){for(;this.Je>this.Ne.max_bytes&&this.Ke.length>0;){var e=this.Ke.shift();e&&(this.Je-=e.bytes)}}}function Fg(t,e){if(!ke(t)||t===1/0||t===-1/0)return e;var n=Math.floor(t);return 0>n?e:n}var Kd=function(t,e){var n=(e===void 0?{}:e).debugEnabled,i={k(r){if(w&&(ne.DEBUG||w.POSTHOG_DEBUG||n)&&!C(w.console)&&w.console){for(var s=("__rrweb_original__"in w.console[r])?w.console[r].__rrweb_original__:w.console[r],o=arguments.length,a=new Array(o>1?o-1:0),l=1;o>l;l++)a[l-1]=arguments[l];s(t,...a)}},debug(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("debug",...s)},info(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("log",...s)},warn(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("warn",...s)},error(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("error",...s)},critical(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];console.error(t,...s)},uninitializedWarning(r){i.error("You must initialize PostHog before calling "+r)},createLogger:(r,s)=>Kd(t+" "+r,s)};return i},A=Kd("[PostHog.js]"),pe=A.createLogger,Rg=pe("[ExternalScriptsLoader]"),mo=(t,e,n)=>{if(t.config.disable_external_dependency_loading)return Rg.warn(e+" was requested but loading of external scripts is disabled."),n("Loading of external scripts is disabled");var i=P?.querySelectorAll("script");if(i){for(var r,s=function(){if(i[o].src===e){var l=i[o];return l.__posthog_loading_callback_fired?{v:n()}:(l.addEventListener("load",(u=>{l.__posthog_loading_callback_fired=!0,n(void 0,u)})),l.onerror=u=>n(u),{v:void 0})}},o=0;i.length>o;o++)if(r=s())return r.v}var a=()=>{if(!P)return n("document not found");var l=P.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=d=>{l.__posthog_loading_callback_fired=!0,n(void 0,d)},l.onerror=d=>n(d),t.config.prepare_external_dependency_script&&(l=t.config.prepare_external_dependency_script(l)),!l)return n("prepare_external_dependency_script returned null");if(t.config.external_scripts_inject_target==="head")P.head.appendChild(l);else{var u,c=P.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):P.body.appendChild(l)}};P!=null&&P.body?a():P?.addEventListener("DOMContentLoaded",a)};B.__PosthogExtensions__=B.__PosthogExtensions__||{},B.__PosthogExtensions__.loadExternalDependency=(t,e,n)=>{if(e!=="remote-config"){var i;if(t.config.strict_script_versioning)i=t.requestRouter.endpointFor("assets","/static/"+t.version+"/"+e+".js");else{var r="/static/"+e+".js?v="+t.version;if(e==="toolbar"){var s=3e5;r=r+"&t="+Math.floor(Date.now()/s)*s}i=t.requestRouter.endpointFor("assets",r)}mo(t,i,n)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");mo(t,o,n)}},B.__PosthogExtensions__.loadSiteApp=(t,e,n)=>{var i=t.requestRouter.endpointFor("api",e);mo(t,i,n)};ne.DEBUG=!1,ne.LIB_VERSION="1.415.7",ne.LIB_NAME="web";var Yd="$people_distinct_id",Ji="$device_id",vo="$device_model",Ri="__alias",Ti="__timers",ea="$autocapture_disabled_server_side",ta="$heatmaps_enabled_server_side",na="$exception_capture_enabled_server_side",ia="$error_tracking_suppression_rules",ra="$error_tracking_capture_extension_exceptions",sa="$web_vitals_enabled_server_side",sl="$dead_clicks_enabled_server_side",ol="$product_tours_enabled_server_side",oa="$web_vitals_allowed_metrics",An="$session_recording_remote_config",Jd="$replay_sample_rate",Zd="$replay_override_sampling",Xd="$replay_override_linked_flag",Qd="$replay_override_url_trigger",ef="$replay_override_event_trigger",Yn="$sesid",al="$session_is_sampled",Sn="$enabled_feature_flags",$i="$active_feature_flags",Ar="$early_access_features",aa="$feature_flag_details",Mi="$feature_flag_payloads",Pr="$feature_flag_request_id",Zr="$minimal_flag_called_events",It="$override_feature_flags",xn="$override_feature_flag_payloads",jt="$stored_person_properties",In="$stored_group_properties",la="$surveys",Xr="$surveys_loaded_at",ca="$surveys_activated",Fr="$surveys_activated_session",Rr="$surveys_activated_timestamps",Li="ph_product_tours",Cn="$flag_call_reported",Ni="$flag_call_reported_session_id",Tr="$feature_flag_errors",Ui="$feature_flag_evaluated_at",at="$user_state",ua="$client_session_props",da="$capture_rate_limit",fa="$initial_campaign_params",ha="$initial_referrer_info",Qr="$initial_person_info",es="$epp",mr="$posthog_cookieless",tf="$cookieless_mode",nf="$sdk_debug_extensions_init_method",rf="$sdk_debug_extensions_init_time_ms",sf="$sdk_debug_recording_script_not_loaded",ll="PostHog loadExternalDependency extension not found.",kn="on_reject",Wt="always",Hn="anonymous",vn="identified",pa="identified_only",ts="visibilitychange",ns="beforeunload",Gn="$pageview",_o="$pageleave",yo="$identify",Fc="$groupidentify";function vr(t,e){U(t)&&t.forEach(e)}function ie(t,e){if(!H(t))if(U(t))t.forEach(e);else if(Hp(t))t.forEach(((i,r)=>e(i,r)));else for(var n in t)_d.call(t,n)&&e(t[n],n)}var fe=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;e>i;i++)n[i-1]=arguments[i];for(var r of n)for(var s in r)r[s]!==void 0&&(t[s]=r[s]);return t};function $r(t){for(var e=Object.keys(t),n=e.length,i=new Array(n);n--;)i[n]=[e[n],t[e[n]]];return i}var Rc=function(t){try{return t()}catch{return}},Tg=function(t){return function(){try{for(var e=arguments.length,n=new Array(e),i=0;e>i;i++)n[i]=arguments[i];return t.apply(this,n)}catch(r){A.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),A.critical(r)}}},cl=function(t){var e={};return ie(t,(function(n,i){(X(n)&&n.length>0||ke(n))&&(e[i]=n)})),e},$g=["herokuapp.com","vercel.app","netlify.app"];function Mg(t){var e=t?.hostname;if(!X(e))return!1;var n=e.split(".").slice(-2).join(".");for(var i of $g)if(n===i)return!1;return!0}function ve(t,e,n,i){var r=i??{},s=r.capture,o=r.passive;t?.addEventListener(e,n,{capture:s!==void 0&&s,passive:o===void 0||o})}function ga(t){return t.name==="ph_toolbar_internal"}var of=t=>{if(P){try{for(var e=t+"=",n=P.cookie.split(";").filter((s=>s.length)),i=0;n.length>i;i++){for(var r=n[i];r.charAt(0)==" ";)r=r.substring(1,r.length);if(r.indexOf(e)===0)return decodeURIComponent(r.substring(e.length,r.length))}}catch{}return null}};Math.trunc||(Math.trunc=function(t){return 0>t?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return ke(t)&&isFinite(t)&&Math.floor(t)===t});class is{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,n,i,r){if(!Number.isInteger(e)||!Number.isInteger(n)||!Number.isInteger(i)||!Number.isInteger(r)||0>e||0>n||0>i||0>r||e>0xffffffffffff||n>4095||i>1073741823||r>4294967295)throw new RangeError("invalid field value");var s=new Uint8Array(16);return s[0]=e/Math.pow(2,40),s[1]=e/Math.pow(2,32),s[2]=e/Math.pow(2,24),s[3]=e/Math.pow(2,16),s[4]=e/256,s[5]=e,s[6]=112|n>>>8,s[7]=n,s[8]=128|i>>>24,s[9]=i>>>16,s[10]=i>>>8,s[11]=i,s[12]=r>>>24,s[13]=r>>>16,s[14]=r>>>8,s[15]=r,new is(s)}toString(){for(var e="",n=0;this.bytes.length>n;n++)e=e+(this.bytes[n]>>>4).toString(16)+(15&this.bytes[n]).toString(16),n!==3&&n!==5&&n!==7&&n!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new is(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var n=0;16>n;n++){var i=this.bytes[n]-e.bytes[n];if(i!==0)return Math.sign(i)}return 0}}class Lg{generate(){var e=this.generateOrAbort();if(!C(e))return e;this.S=0;var n=this.generateOrAbort();if(C(n))throw new Error("Could not generate UUID after timestamp reset");return n}generateOrAbort(){var e=Date.now();if(e>this.S)this.S=e,this.C();else{if(this.S>=e+1e4)return;this.I++,this.I>4398046511103&&(this.S++,this.C())}return is.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 Ng}}var Tc,af=t=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;t.length>e;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};w&&!C(w.crypto)&&crypto.getRandomValues&&(af=t=>crypto.getRandomValues(t));class Ng{nextUint32(){return this.R.length>this.O||(af(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var Ht=()=>Og().toString(),Og=()=>(Tc||(Tc=new Lg)).generate(),wi="",Bg=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,zt={N:()=>!!P,j(t){A.error("cookieStore error: "+t)},P:of,H(t){var e;try{e=JSON.parse(zt.P(t))||{}}catch{}return e},F(t,e,n,i,r){if(!P)return!1;try{var s="",o="",a=(function(c,d){if(d){var f=(function(p,g){if(g===void 0&&(g=P),wi)return wi;if(!g||["localhost","127.0.0.1"].includes(p))return"";for(var m=p.split("."),v=Math.min(m.length,8),E="dmn_chk_"+Ht();!wi&&v--;){var S=m.slice(v).join("."),_=E+"=1;domain=."+S+";path=/";g.cookie=_+";max-age=3",g.cookie.includes(E)&&(g.cookie=_+";max-age=0",wi=S)}return wi})(c);if(!f){var h=(p=>{var g=p.match(Bg);return g?g[0]:""})(c);h!==f&&A.info("Warning: cookie subdomain discovery mismatch",h,f),f=h}return f?"; domain=."+f:""}return""})(P.location.hostname,i);if(n){var l=new Date;l.setTime(l.getTime()+864e5*n),s="; expires="+l.toUTCString()}r&&(o="; secure");var u=t+"="+encodeURIComponent(JSON.stringify(e))+s+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&A.warn("cookieStore warning: large cookie, len="+u.length),P.cookie=u,!0}catch{return!1}},q(t,e){if(P!=null&&P.cookie)try{zt.F(t,"",-1,e)}catch{return}}},wo=null,le={N(){if(!Ye(wo))return wo;var t=!0;if(C(w))t=!1;else try{var e="__mplssupport__";le.F(e,"xyz"),le.P(e)!=='"xyz"'&&(t=!1),le.q(e)}catch{t=!1}return t||A.error("localStorage unsupported; falling back to cookie store"),wo=t,t},j(t){A.error("localStorage error: "+t)},P(t){try{return w?.localStorage.getItem(t)}catch(e){le.j(e)}return null},H(t){try{return JSON.parse(le.P(t))||{}}catch{}return null},F(t,e){try{return w?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(n){le.j(n)}return!1},q(t){try{w?.localStorage.removeItem(t)}catch(e){le.j(e)}}},Dg=[Ji,"distinct_id",Yn,al,es,Qr,at],_r={},jg={N:()=>!0,j(t){A.error("memoryStorage error: "+t)},P:t=>_r[t]||null,H:t=>_r[t]||null,F:(t,e)=>(_r[t]=e,!0),q(t){delete _r[t]}},_n=null,be={N(){if(!Ye(_n))return _n;if(_n=!0,C(w))_n=!1;else try{var t="__support__";be.F(t,"xyz"),be.P(t)!=='"xyz"'&&(_n=!1),be.q(t)}catch{_n=!1}return _n},j(t){A.error("sessionStorage error: ",t)},P(t){try{return w?.sessionStorage.getItem(t)}catch(e){be.j(e)}return null},H(t){try{return JSON.parse(be.P(t))||null}catch{}return null},F(t,e){try{return w?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(n){be.j(n)}return!1},q(t){try{w?.sessionStorage.removeItem(t)}catch(e){be.j(e)}}};class Ug{constructor(e){this._instance=e}get Ne(){return this._instance.config}get consent(){return this.ti()?0:this.ei}isOptedOut(){return this.Ne.cookieless_mode===Wt||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===kn}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===0}isRejected(){return this.consent===0||this.consent===-1&&this.Ne.opt_out_capturing_by_default}optInOut(e){this.ii.F(this.ri,e?1:0,this.Ne.cookie_expiration,this.Ne.cross_subdomain_cookie,this.Ne.secure_cookie)}reset(){this.ii.q(this.ri,this.Ne.cross_subdomain_cookie)}get ri(){var e=this._instance.config,n=e.token,i=e.opt_out_capturing_cookie_prefix;return e.consent_persistence_name||(i?i+n:"__ph_opt_in_out_"+n)}get ei(){var e=this.ii.P(this.ri);return uo(e)?1:j(Vp,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,n=e==="localStorage"?le:zt;if(!this.ni||this.ni!==n){this.ni=n;var i=e==="localStorage"?zt:le;i.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(uo(i.P(this.ri))),i.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[He?.doNotTrack,He?.msDoNotTrack,B.doNotTrack].some((e=>uo(e)))}}function lf(t,e){var n,i=t==null||(n=t.config)==null?void 0:n.get_current_url;if(!je(i))return e;try{var r=i(e);return X(r)&&r?r:e}catch(s){return A.error("Error in get_current_url, falling back to window.location.href",s),e}}var cf="__POSTHOG_TOOLBAR__",Hg=1,Wg=3,zg=11;function $c(t){return t instanceof Element&&(t.id===cf||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function hn(t){return!!t&&t.nodeType===Hg}function et(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function uf(t){return!!t&&t.nodeType===Wg}function df(t){return!!t&&t.nodeType===zg&&hn(t.host)}var ff=1e3;function ul(t){return t?xs(t).split(/\s+/):[]}function Mc(t,e){var n=(function(i){var r,s=w==null||(r=w.location)==null?void 0:r.href;return C(s)?void 0:lf(i,s)})(e);return!!(n&&t&&t.some((i=>n.match(i))))}function rs(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 ul(e)}function hf(t){return H(t)?null:xs(t).split(/(\s+)/).filter((e=>Hi(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function Zi(t){var e="";return va(t)&&!vf(t)&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;uf(n)&&n.textContent&&(e+=(i=hf(n.textContent))!==null&&i!==void 0?i:"")})),xs(e)}function bo(t){var e;return C(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var dl=["a","button","form","input","select","textarea","label"];function ma(t,e){if(C(e))return!0;var n,i=function(s){if(e.some((o=>(function(a,l){var u=a.matches||a.matchesSelector||a.msMatchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.oMatchesSelector;try{return!!u&&u.call(a,l)}catch{return!1}})(s,o))))return{v:!0}};for(var r of t)if(n=i(r))return n.v;return!1}function pf(t){var e=t.parentNode;return!(!e||!hn(e))&&e}var qg=[".ph-no-autocapture","[data-ph-no-autocapture]"],gf=["next","previous","prev",">","<"],Vg=[...gf,"+","-","−","–"],Lc=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,Nc=[".ph-no-rageclick",".ph-no-capture"],Gg=["","text","search","email","password","url","tel","number"];function Oc(t,e){if(!w||fl(t))return!1;var n,i,r,s,o;if(mt(e)?(n=!!e&&Nc,i=void 0,r=!1):(n=(s=e?.css_selector_ignorelist)!==null&&s!==void 0?s:Nc,i=e?.content_ignorelist,r=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),n===!1||r&&(function(l){return!(!l||!hn(l))&&(!!et(l,"textarea")||(et(l,"input")?j(Gg,(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=mf(t,!1).targetElementList;return!(function(l,u){if(l===!1||C(l))return!1;var c;if(l===!0)c=gf;else{if(!U(l))return!1;if(l.length>10)return A.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var f=d.safeText,h=d.ariaLabel;return c.some((p=>Lc(f,p)||Lc(h,p)))}))})(i,a.map((l=>{var u;return{safeText:Zi(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!ma(a,n)}var fl=t=>!t||et(t,"html")||!hn(t),mf=(t,e)=>{if(!w||fl(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,i=[t],r=t;r.parentNode&&!et(r,"body");)if(df(r.parentNode))i.push(r.parentNode.host),r=r.parentNode.host;else{var s=pf(r);if(!s)break;if(e||dl.indexOf(s.tagName.toLowerCase())>-1)n=!0;else try{var o=w.getComputedStyle(s);o&&o.getPropertyValue("cursor")==="pointer"&&(n=!0)}catch{}i.push(s),r=s}return{parentIsUsefulElement:n,targetElementList:i}};function va(t){for(var e=new Set,n=0,i=t;i.parentNode&&!et(i,"body");i=i.parentNode){if(n++>=ff||e.has(i))return!1;e.add(i);var r=rs(i);if(j(r,"ph-sensitive")||j(r,"ph-no-capture"))return!1}if(j(rs(t),"ph-include"))return!0;var s=t.type||"";if(X(s))switch(s.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!X(o)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(o.replace(/[^a-zA-Z0-9]/g,""))}function vf(t){return!!(et(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||et(t,"select")||et(t,"textarea")||t.getAttribute("contenteditable")==="true")}var Bc=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}))$"),Dc=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,Kg=[16,15,14,13],Yg=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),jc=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),Uc=/[0-9A-Za-z_]/;function Jg(t){for(var e=0,n=!1,i=t.length-1;i>=0;i--){var r=t.charCodeAt(i)-48;n&&(r*=2)>9&&(r-=9),e+=r,n=!n}return e%10==0}function Hi(t,e){if(e===void 0&&(e=!0),H(t))return!1;if(X(t)){t=xs(t);var n=e?Bc.test((t||"").replace(/[- ]/g,"")):(function(r){var s;for(Dc.lastIndex=0;s=Dc.exec(r);){var o=s[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of Kg){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(Bc.test(d)&&Jg(d))return!0}}}return!1})(t);if(n)return!1;var i=e?Yg.test(t):(function(r){var s;for(jc.lastIndex=0;s=jc.exec(r);){var o=s[1],a=s[3];if(!(o&&a&&Uc.test(o)&&Uc.test(a)))return!0}return!1})(t);if(i)return!1}return!0}function Hc(t){var e=Zi(t);return Hi(e=(e+" "+_f(t)).trim())?e:""}function _f(t){var e="";return t&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;if(n&&((i=n.tagName)==null?void 0:i.toLowerCase())==="span")try{var r=Zi(n);e=(e+" "+r).trim(),n.childNodes&&n.childNodes.length&&(e=(e+" "+_f(n)).trim())}catch(s){A.error("[AutoCapture]",s)}})),e}function Wc(t){return t.replace(/"|\\"/g,'\\"')}function Zg(t){var e=t.attr__class;if(e)return U(e)?e:ul(e)}var yr=pe("[Dead Clicks]"),Xg=()=>!0,Qg=t=>{var e,n=!((e=t.instance.persistence)==null||!e.get_property(sl)),i=t.instance.config.capture_dead_clicks;return mt(i)?i:!!he(i)||n};class zc{get lazyLoadedDeadClicksAutocapture(){return this.si}constructor(e,n,i){this.instance=e,this.isEnabled=n,this.onCapture=i,this.startIfEnabledOrStop()}onRemoteConfig(e){if(e.ok){var n=e.config;"captureDeadClicks"in n&&(this.instance.persistence&&this.instance.persistence.register({[sl]:n.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var n,i;(n=B.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture?e():(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"dead-clicks-autocapture",(r=>{r?yr.error("failed to load script",r):e()}))}oi(){var e;if(P){if(!this.si&&(e=B.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var n=he(this.instance.config.capture_dead_clicks)?I({},this.instance.config.capture_dead_clicks):{};n.__onCapture=this.onCapture,this.onCapture&&(n.capture_dead_swipes=!1),this.si=B.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.si.start(P),yr.info("starting...")}}else yr.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,yr.info("stopping..."))}}var Eo=pe("[SegmentIntegration]"),yf="posthog-js";function wf(t,e){var n=e===void 0?{}:e,i=n.organization,r=n.projectId,s=n.prefix,o=n.severityAllowList,a=o===void 0?["error"]:o,l=n.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,f,h,p,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var v,E=((d=c.exception)==null?void 0:d.values)||[],S=E.map((b=>I({},b,{stacktrace:b.stacktrace?I({},b.stacktrace,{type:"raw",frames:(b.stacktrace.frames||[]).map((k=>I({},k,{platform:"web:javascript"})))}):void 0}))),_={$exception_message:((f=E[0])==null?void 0:f.value)||c.message,$exception_type:(h=E[0])==null?void 0:h.type,$exception_level:c.level,$exception_list:S,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((p=E[0])==null?void 0:p.value)||c.message,$sentry_exception_type:(g=E[0])==null?void 0:g.type,$sentry_tags:c.tags};return i&&r&&(_.$sentry_url=(s||"https://sentry.io/organizations/")+i+"/issues/?project="+r+"&query="+c.event_id),u&&((v=t.exceptions)==null||v.sendExceptionEvent(_)),c}}class em{constructor(e,n,i,r,s,o){this.name=yf,this.setupOnce=function(a){a(wf(e,{organization:n,projectId:i,prefix:r,severityAllowList:s,sendExceptionsToPostHog:o==null||o}))}}}class qc{constructor(e){this.li=(n,i,r)=>{r&&(r.noSessionId||r.activityTimeout||r.sessionPastMaximumLength||r.crossTabAdoption)&&(A.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:n,changeReason:r}),this.ui=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.hi()}hi(){var e;this.di=(e=this._instance.sessionManager)==null?void 0:e.onSessionId(this.li)}destroy(){var e;(e=this.di)==null||e.call(this),this.di=void 0}doPageView(e,n){var i,r=this.vi(e,n);return this.ui={pathname:(i=w?.location.pathname)!==null&&i!==void 0?i:"",pageViewId:n,timestamp:e},this._instance.scrollManager.resetContext(),r}doPageLeave(e){var n;return this.vi(e,(n=this.ui)==null?void 0:n.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.ui)==null?void 0:e.pageViewId}}vi(e,n){var i=this.ui;if(!i)return{$pageview_id:n};var r={$pageview_id:n,$prev_pageview_id:i.pageViewId},s=this._instance.scrollManager.getContext();if(s&&!this._instance.config.disable_scroll_properties){var o=s.maxScrollHeight,a=s.lastScrollY,l=s.maxScrollY,u=s.maxContentHeight,c=s.lastContentY,d=s.maxContentY;if(!(C(o)||C(a)||C(l)||C(u)||C(c)||C(d))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),d=Math.ceil(d);var f=o>1?At(a/o,0,1,A):1,h=o>1?At(l/o,0,1,A):1,p=u>1?At(c/u,0,1,A):1,g=u>1?At(d/u,0,1,A):1;r=fe(r,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:f,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:h,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:p,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return i.pathname&&(r.$prev_pageview_pathname=i.pathname),i.timestamp&&(r.$prev_pageview_duration=(e.getTime()-i.timestamp.getTime())/1e3),r}}var So=["flags","surveys"],tm={[Yd]:{exposure:"hidden"},[Ri]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[Ti]:{exposure:"hidden"},[ea]:{exposure:"event"},[ta]:{exposure:"hidden"},[na]:{exposure:"event"},[ia]:{exposure:"hidden"},[ra]:{exposure:"event"},[sa]:{exposure:"event"},[sl]:{exposure:"event"},[ol]:{exposure:"hidden"},[oa]:{exposure:"event"},[An]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[Yn]:{exposure:"hidden"},[al]:{exposure:"event"},[Jd]:{exposure:"event",shouldSkipFromEventProperties:t=>Ye(t)},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},$sess_rec_flush_size:{exposure:"hidden"},[Sn]:{exposure:"hidden",storageGroup:"flags"},[$i]:{exposure:"hidden",storageGroup:"flags"},[Ar]:{exposure:"hidden"},[aa]:{exposure:"hidden",storageGroup:"flags"},[Mi]:{exposure:"hidden",storageGroup:"flags"},[Pr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[Zr]:{exposure:"hidden",storageGroup:"flags"},[It]:{exposure:"hidden"},[xn]:{exposure:"hidden"},[jt]:{exposure:"hidden"},[In]:{exposure:"hidden"},[la]:{exposure:"hidden",storageGroup:"surveys"},[Xr]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[ca]:{exposure:"event"},[Fr]:{exposure:"hidden"},[Rr]:{exposure:"hidden"},[Li]:{exposure:"hidden"},$product_tours_activated:{exposure:"hidden"},$product_tours_activated_session:{exposure:"hidden"},$conversations_widget_session_id:{exposure:"event"},$conversations_ticket_id:{exposure:"event"},$conversations_widget_state:{exposure:"event"},$conversations_user_traits:{exposure:"event"},[Cn]:{exposure:"hidden"},[Ni]:{exposure:"hidden"},[Tr]:{exposure:"hidden"},[Ui]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[at]:{exposure:"hidden"},[ua]:{exposure:"hidden"},[da]:{exposure:"hidden"},[fa]:{exposure:"hidden"},[ha]:{exposure:"hidden"},[Qr]:{exposure:"hidden"},[es]:{exposure:"hidden"},[Zd]:{exposure:"event"},[Xd]:{exposure:"event"},[Qd]:{exposure:"event"},[ef]:{exposure:"event"},[nf]:{exposure:"event"},[rf]:{exposure:"event"},[sf]:{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"}},nm=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],yn=t=>{var e=tm[t];if(e)return e;for(var n of nm){var i=n[1];if(t.indexOf(n[0])===0)return i}},Jn=(t,e)=>{try{return JSON.stringify(t,((n,i)=>typeof i=="bigint"?i.toString():i),e)}catch{return md(t)}},ss=t=>{var e=P?.createElement("a");return C(e)?null:(e.href=t,e)},ri=function(t,e){for(var n,i=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),r=0;i.length>r;r++){var s=i[r].split("=");if(s[0]===e){n=s;break}}if(!U(n)||2>n.length)return"";var o=n[1];try{o=decodeURIComponent(o)}catch{A.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},Xi=function(t,e,n){if(!t||!e||!e.length)return t;for(var i=t.split("#"),r=i[1],s=(i[0]||"").split("?"),o=s[1],a=s[0],l=(o||"").split("&"),u=[],c=0;l.length>c;c++){var d=l[c].split("=");U(d)&&(e.includes(d[0])?u.push(d[0]+"="+n):u.push(l[c]))}var f=a;return o!=null&&(f+="?"+u.join("&")),r!=null&&(f+="#"+r),f},os=function(t,e){var n=t.match(new RegExp(e+"=([^&]*)"));return n?n[1]:null},bf=(t,e)=>t>=e&&hd(),Ef=(t,e,n,i)=>{if(t===0){if(hd()){var r=e+1;return r===n&&i(),r}return e}return 0},wr="https?://(.*)",si=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],im=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...si],Qi="",rm=["li_fat_id"];function Sf(t,e,n){if(!P)return{};var i,r=e?[...si,...n||[]]:[],s=xf(Xi(P.URL,r,Qi),t),o=(i={},ie(rm,(function(a){var l=of(a);i[a]=l||null})),i);return fe(o,s)}function xf(t,e){var n=im.concat(e||[]),i={};return ie(n,(function(r){var s=ri(t,r);i[r]=s||null})),i}function If(t){var e=(function(s){return s?s.search(wr+"google.([^/?]*)")===0?"google":s.search(wr+"bing.com")===0?"bing":s.search(wr+"yahoo.com")===0?"yahoo":s.search(wr+"duckduckgo.com")===0?"duckduckgo":null:null})(t),n=e!="yahoo"?"q":"p",i={};if(!Ye(e)){i.$search_engine=e;var r=P?ri(P.referrer,n):"";r.length&&(i.ph_keyword=r)}return i}function Vc(){return navigator.language||navigator.userLanguage}var as="$direct";function kf(){return P?.referrer||as}function Cf(t,e,n){n===void 0&&(n=!1);var i=t?[...si,...e||[]]:[],r=n?fn(me?.href):me?.href,s=r?.substring(0,1e3);return{r:kf().substring(0,1e3),u:s?Xi(s,i,Qi):void 0}}function Af(t,e){var n;e===void 0&&(e=!1);var i=t.r,r=t.u,s=e?fn(r):r,o={$referrer:i,$referring_domain:i==null?void 0:i==as?as:(n=ss(i))==null?void 0:n.host};if(s){o.$current_url=s;var a=ss(s);o.$host=a?.host,o.$pathname=a?.pathname;var l=xf(s);fe(o,l)}if(i){var u=If(i);fe(o,u)}return o}function Pf(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function sm(){try{return new Date().getTimezoneOffset()}catch{return}}var om={flags:Ui,surveys:Xr},am=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],Wn="main";class xo{constructor(e,n,i){if(i===void 0&&(i=!0),this.ci={},this.fi=!1,this.pi=!1,this.Ne=e,this.gi=i,this.props={},this.mi=void 0,this.yi=(s=>{var o="";return s.token&&(o=s.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),s.persistence_name?"ph_"+s.persistence_name:"ph_"+o+"_posthog"})(e),this.ii=this.bi(e),this.pi=this.wi(e),this.load(),e.debug&&A.info("Persistence loaded",e.persistence,I({},this.props)),this.update_config(e,e,n),this.save(),w){var r=()=>this.flush();ve(w,"beforeunload",r,{capture:!1}),ve(w,"pagehide",r,{capture:!1})}}ki(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return ke(n)&&n>0?n:0}isDisabled(){return!!this.xi}bi(e){am.indexOf(e.persistence.toLowerCase())===-1&&(A.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var n,i=(function(o,a){o===void 0&&(o=[]),a===void 0&&(a=!1);var l=[...Dg,...o];return I({},le,{H(u){try{var c={};try{c=zt.H(u)||{}}catch{}var d,f=JSON.parse(le.P(u)||"{}");if(a){var h={};for(var p in c){var g=c[p];Ye(g)||g===""||(h[p]=g)}d=fe(f,h)}else d=fe(c,f);return le.F(u,d),d}catch{}return null},F(u,c,d,f,h,p){var g=le.F(u,c,void 0,void 0,p);try{var m={};l.forEach((v=>{c[v]&&(m[v]=c[v])})),Object.keys(m).length&&zt.F(u,m,d,f,h,p)}catch(v){le.j(v)}return g},q(u,c){try{w?.localStorage.removeItem(u),zt.q(u,c)}catch(d){le.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),r=!1,s=e.persistence.toLowerCase();return s==="localstorage"&&le.N()?(n=le,r=!0):s==="localstorage+cookie"&&i.N()?(n=i,r=!0):s==="sessionstorage"&&be.N()?n=be:s==="memory"?n=jg:s==="cookie"?n=zt:i.N()?(n=i,r=!0):n=zt,this.fi=r,n}Si(e){return this.yi+"__"+e}wi(e){return this.fi&&!!e.split_storage}properties(){var e={};return ie(this.props,((n,i)=>{var r=yn(i);if(!r||r.exposure==="event"){if(r!=null&&r.shouldSkipFromEventProperties!=null&&r.shouldSkipFromEventProperties(n))return;e[i]=n}})),e}load(){if(!this.xi){var e=this.ii.H(this.yi);e&&(this.props=fe({},e)),this.pi&&this.Ci()}}Ci(){for(var e of So){var n=le.H(this.Si(e));if(n&&!Kt(n)){var i=this.Mi(e);i.persisted=!0,this.Ti(e)||(i.fingerprint=this.Ei(n,e)),this.Ii(e,n)||fe(this.props,n)}}}Ti(e){return Object.keys(this.props).some((n=>{var i;return((i=yn(n))==null?void 0:i.storageGroup)===e}))}Ii(e,n){var i=om[e];if(!i)return!1;var r=n[i],s=this.props[i];return ke(r)&&ke(s)&&s>r}refreshKey(e){var n;if(!this.xi){var i=this.pi?(n=yn(e))==null?void 0:n.storageGroup:void 0,r=i?le.H(this.Si(i)):this.ii.H(this.yi);if(r&&e in r)this.Pi(e,r[e]);else{if(i){var s=this.ii.H(this.yi);if(s&&e in s)return void this.Pi(e,s[e])}this.Ri(e)}}}save(){if(!this.xi){var e=this.ki();e>0?C(this.Ai)&&(this.Ai=setTimeout((()=>{this.Ai=void 0,this.Fi()}),e)):this.Fi()}}flush(){C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0,this.Fi())}Fi(){this.xi||(this.pi?this.Li():this.Oi(this.ii,this.yi,this.props,Wn))}Li(){var e=this.Di(),n=e.main,i=e.groups;for(var r of(this.Oi(this.ii,this.yi,n,Wn),So)){var s,o=i[r];(!Kt(o)||(s=this.ci[r])!=null&&s.persisted)&&this.Oi(le,this.Si(r),o,r)}}Di(){var e={},n={flags:{},surveys:{}};return ie(this.props,((i,r)=>{var s,o=(s=yn(r))==null?void 0:s.storageGroup;o?n[o][r]=i:e[r]=i})),{main:e,groups:n}}Ei(e,n){if(n===Wn)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var i={};return ie(e,((r,s)=>{var o;i[s]=(o=yn(s))!=null&&o.volatile?"__volatile__":r})),JSON.stringify(i)}Oi(e,n,i,r){var s=this.Mi(r);if(r===Wn||s.dirty||C(s.fingerprint)){var o;try{if((o=this.Ei(i,r))===s.fingerprint)return void(s.dirty=!1)}catch{o=void 0}e.F(n,i,this.$i,this.Ni,this.qi,this.Ne.debug)?(s.dirty=!1,r!==Wn&&(s.persisted=!0),C(o)||(s.fingerprint=o)):this.Ne.debug&&A.warn('failed to persist storage entry "'+n+'"; will retry on next save')}}remove(e){var n=(e===void 0?{}:e).keepGroupEntries,i=n!==void 0&&n;if(C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0),this.ii.q(this.yi,!1),this.ii.q(this.yi,!0),!i&&this.gi)for(var r of So)le.q(this.Si(r));i?delete this.ci[Wn]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,n,i){if(he(e)){C(n)&&(n="None"),this.$i=C(i)?this.ji:i;var r=!1;if(ie(e,((s,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==n||(this.Pi(o,s),r=!0)})),r)return this.save(),!0}return!1}register(e,n){if(he(e)){this.$i=C(n)?this.ji:n;var i=!1;if(ie(e,((r,s)=>{e.hasOwnProperty(s)&&(this.props[s]!==r||he(r)||U(r))&&(this.Pi(s,r),i=!0)})),i)return this.save(),!0}return!1}unregister(e){var n=typeof e=="string"?[e]:e,i=!1;for(var r of n)r in this.props&&(this.Ri(r),i=!0);i&&this.save()}update_campaign_params(){var e=P?.URL;if(e!==this.mi){var n=Sf(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);Kt(cl(n))||this.register(n),this.mi=e}}update_search_keyword(){var e;this.register((e=P?.referrer)?If(e):{})}update_referrer_info(){var e;this.register_once({$referrer:kf(),$referring_domain:P!=null&&P.referrer&&((e=ss(P.referrer))==null?void 0:e.host)||as},void 0)}set_initial_person_info(){this.props[fa]||this.props[ha]||this.register_once({[Qr]:Cf(this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties,this.Ne.disable_capture_url_hashes)},void 0)}get_initial_props(){var e={};ie([ha,fa],(r=>{var s=this.props[r];s&&ie(s,(function(o,a){e["$initial_"+Go(a)]=o}))}));var n=this.props[Qr];if(n){var i=(function(r,s){s===void 0&&(s=!1);var o=Af(r,s),a={};return ie(o,(function(l,u){a["$initial_"+Go(u)]=l})),a})(n,this.Ne.disable_capture_url_hashes);fe(e,i)}return e}safe_merge(e){return ie(this.props,(function(n,i){i in e||(e[i]=n)})),e}update_config(e,n,i){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!i),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var r=e.persistence!==n.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((f,h)=>f===d[h]))})(e.cookie_persisted_properties||[],n.cookie_persisted_properties||[]),s=r?this.bi(e):this.ii,o=this.wi(e);if(r||o!==this.pi){var a=this.props;this.clear(),this.ii=s,this.pi=o,this.props=a,this.save()}}set_disabled(e){this.xi=e,this.xi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ni&&(this.Ni=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this.qi&&(this.qi=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,n){var i=this.props[Ti]||{};i[e]=n,this.Pi(Ti,i),this.save()}remove_event_timer(e){var n=this.props[Ti]||{},i=n[e];return C(i)||(delete n[e],this.Pi(Ti,n),this.save()),i}get_property(e){return this.props[e]}set_property(e,n){this.Pi(e,n),this.save()}Pi(e,n){var i;this.props[e]=n,(i=yn(e))!=null&&i.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var n,i=(n=yn(e))==null?void 0:n.storageGroup;i&&(this.Mi(i).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function br(t){var e=!0;return{dispose(){if(e){e=!1;var n=t();n&&je(n.then)&&n.then(void 0,(()=>{}))}}}}var Ue={GZipJS:"gzip-js",Base64:"base64"},bi={Activation:"events",Cancellation:"cancelEvents"},Io={Popover:"popover",API:"api",Widget:"widget"},qt={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},ko={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},_a={Popover:"popover",Inline:"inline"},lm={SHOWN:"product tour shown"},Gc={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},Kc=pe("[RateLimiter]");class cm{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=n=>{var i=n.text;if(i&&i.length)try{(JSON.parse(i).quota_limited||[]).forEach((r=>{Kc.info((r||"events")+" is quota limited."),this.serverLimits[r]=new Date().getTime()+6e4}))}catch(r){return void Kc.warn('could not rate limit - continuing. Error: "'+r?.message+'"',{text:i})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var n,i,r;e===void 0&&(e=!1);var s=this.captureEventsBurstLimit,o=this.captureEventsPerSecond,a=new Date().getTime(),l=(n=(i=this.instance.persistence)==null?void 0:i.get_property(da))!==null&&n!==void 0?n:{tokens:s,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>s&&(l.tokens=s);var u=1>l.tokens;if(u||e||(l.tokens=Math.max(0,l.tokens-1)),u&&!e){var c=(ke(l.dropped)?l.dropped:0)+1;l.dropped=c,!this.lastEventRateLimited&&this.Hi(c)&&(l.dropped=0)}return this.lastEventRateLimited=u,(r=this.instance.persistence)==null||r.set_property(da,l),{isRateLimited:u,remainingTokens:l.tokens}}Ui(e){var n=this.instance.config.property_denylist;return!U(n)||!n.includes(e)}zi(){var e;if(this.Ui("$current_url")&&this.Ui("$pathname")&&me!=null&&me.pathname)return""+((e=me.origin)!==null&&e!==void 0?e:"")+me.pathname}Hi(e){var n,i,r=this.captureEventsBurstLimit,s=this.captureEventsPerSecond,o=this.zi(),a=this.Ui("$session_id")?(n=(i=this.instance).get_session_id)==null?void 0:n.call(i):void 0,l=[e+" event(s) dropped since the last warning",o?"triggered on "+o:void 0,a?"session "+a:void 0].filter(Boolean).join(", ");return!!this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited: "+l+". Config is set to "+s+" events per second and "+r+" events burst limit."},{skip_client_rate_limiting:!0})}isServerRateLimited(e){var n=this.serverLimits[e||"events"]||!1;return n!==!1&&new Date().getTime()e(this.remoteConfig))):e()}Vi(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:e})}load(){try{if(this.remoteConfig)return an.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void an.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return an.info("No config found after loading remote JS config. Falling back to JSON."),void this.Vi((n=>{this.Zi(n.json,n),this.Gi()}));this.Zi(e),this.Gi()}))}catch(e){an.error("Error loading remote config",e),this.Zi()}}stop(){this.Ki&&(clearInterval(this.Ki),this.Ki=void 0)}refresh(){!this._instance.Qi()&&P&&P.visibilityState!=="hidden"&&this._instance.reloadFeatureFlags()}Gi(){var e;if(!this.Ki){var n=(e=this._instance.config.remote_config_refresh_interval_ms)!==null&&e!==void 0?e:3e5;n!==0&&(this.Ki=setInterval((()=>{this.refresh()}),n))}}Zi(e,n){!e&&n&&(n.statusCode===0?n.error||an.warn("Failed to fetch remote config from PostHog."):an.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(r){an.error("Error applying remote config",r)}if(e?.hasFeatureFlags!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var i;(i=this._instance.featureFlags)==null||i.ensureFlagsLoaded()}catch(r){an.error("Error loading feature flags",r)}}}var ct=Uint8Array,Ke=Uint16Array,oi=Uint32Array,hl=new ct([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]),pl=new ct([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]),Yc=new ct([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Rf=function(t,e){for(var n=new Ke(31),i=0;31>i;++i)n[i]=e+=1<i;++i)for(var s=n[i];n[i+1]>s;++s)r[s]=s-n[i]<<5|i;return[n,r]},Tf=Rf(hl,2),ya=Tf[1];Tf[0][28]=258,ya[258]=28;for(var Jc=Rf(pl,0)[1],$f=new Ke(32768),_e=0;32768>_e;++_e){var zn=(43690&_e)>>>1|(21845&_e)<<1;$f[_e]=((65280&(zn=(61680&(zn=(52428&zn)>>>2|(13107&zn)<<2))>>>4|(3855&zn)<<4))>>>8|(255&zn)<<8)>>>1}var Wi=function(t,e,n){for(var i=t.length,r=0,s=new Ke(e);i>r;++r)++s[t[r]-1];var o,a=new Ke(e);for(r=0;e>r;++r)a[r]=a[r-1]+s[r-1]<<1;for(o=new Ke(i),r=0;i>r;++r)o[r]=$f[a[t[r]-1]++]>>>15-t[r];return o},Mn=new ct(288);for(_e=0;144>_e;++_e)Mn[_e]=8;for(_e=144;256>_e;++_e)Mn[_e]=9;for(_e=256;280>_e;++_e)Mn[_e]=7;for(_e=280;288>_e;++_e)Mn[_e]=8;var ls=new ct(32);for(_e=0;32>_e;++_e)ls[_e]=5;var um=Wi(Mn,9),dm=Wi(ls,5),Mf=function(t){return(t/8>>0)+(7&t&&1)},Lf=function(t,e,n){(n==null||n>t.length)&&(n=t.length);var i=new(t instanceof Ke?Ke:t instanceof oi?oi:ct)(n-e);return i.set(t.subarray(e,n)),i},Ot=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8},Ei=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8,t[i+2]|=n>>>16},Co=function(t,e){for(var n=[],i=0;t.length>i;++i)t[i]&&n.push({s:i,f:t[i]});var r=n.length,s=n.slice();if(!r)return[new ct(0),0];if(r==1){var o=new ct(n[0].s+1);return o[n[0].s]=1,[o,1]}n.sort((function(b,k){return b.f-k.f})),n.push({s:-1,f:25001});var a=n[0],l=n[1],u=0,c=1,d=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=r-1;)a=n[n[d].f>n[u].f?u++:d++],l=n[u!=c&&n[d].f>n[u].f?u++:d++],n[c++]={s:-1,f:a.f+l.f,l:a,r:l};var f=s[0].s;for(i=1;r>i;++i)s[i].s>f&&(f=s[i].s);var h=new Ke(f+1),p=wa(n[c-1],h,0);if(p>e){i=0;var g=0,m=p-e,v=1<i;++i){var E=s[i].s;if(e>=h[E])break;g+=v-(1<>>=m;g>0;){var S=s[i].s;e>h[S]?g-=1<=0&&g;--i){var _=s[i].s;h[_]==e&&(--h[_],++g)}p=e}return[new ct(h),p]},wa=function(t,e,n){return t.s==-1?Math.max(wa(t.l,e,n+1),wa(t.r,e,n+1)):e[t.s]=n},Zc=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new Ke(++e),i=0,r=t[0],s=1,o=function(l){n[i++]=l},a=1;e>=a;++a)if(t[a]==r&&a!=e)++s;else{if(!r&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(r),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(r);s=1,r=t[a]}return[n.subarray(0,i),e]},Si=function(t,e){for(var n=0,i=0;e.length>i;++i)n+=t[i]*e[i];return n},ba=function(t,e,n){var i=n.length,r=Mf(e+2);t[r]=255&i,t[r+1]=i>>>8,t[r+2]=255^t[r],t[r+3]=255^t[r+1];for(var s=0;i>s;++s)t[r+s+4]=n[s];return 8*(r+4+i)},Xc=function(t,e,n,i,r,s,o,a,l,u,c){Ot(e,c++,n),++r[256];for(var d=Co(r,15),f=d[0],h=d[1],p=Co(s,15),g=p[0],m=p[1],v=Zc(f),E=v[0],S=v[1],_=Zc(g),b=_[0],k=_[1],T=new Ke(19),x=0;E.length>x;++x)T[31&E[x]]++;for(x=0;b.length>x;++x)T[31&b[x]]++;for(var F=Co(T,7),$=F[0],O=F[1],L=19;L>4&&!$[Yc[L-1]];--L);var N,K,V,M,R=u+5<<3,Z=Si(r,Mn)+Si(s,ls)+o,Ce=Si(r,f)+Si(s,g)+o+14+3*L+Si(T,$)+(2*T[16]+3*T[17]+7*T[18]);if(Z>=R&&Ce>=R)return ba(e,c,t.subarray(l,l+u));if(Ot(e,c,1+(Z>Ce)),c+=2,Z>Ce){N=Wi(f,h),K=f,V=Wi(g,m),M=g;var oe=Wi($,O);for(Ot(e,c,S-257),Ot(e,c+5,k-1),Ot(e,c+10,L-4),c+=14,x=0;L>x;++x)Ot(e,c+3*x,$[Yc[x]]);c+=3*L;for(var ye=[E,b],$e=0;2>$e;++$e){var ae=ye[$e];for(x=0;ae.length>x;++x)Ot(e,c,oe[Ie=31&ae[x]]),c+=$[Ie],Ie>15&&(Ot(e,c,ae[x]>>>5&127),c+=ae[x]>>>12)}}else N=um,K=Mn,V=dm,M=ls;for(x=0;a>x;++x)if(i[x]>255){var Ie;Ei(e,c,N[257+(Ie=i[x]>>>18&31)]),c+=K[Ie+257],Ie>7&&(Ot(e,c,i[x]>>>23&31),c+=hl[Ie]);var Se=31&i[x];Ei(e,c,V[Se]),c+=M[Se],Se>3&&(Ei(e,c,i[x]>>>5&8191),c+=pl[Se])}else Ei(e,c,N[i[x]]),c+=K[i[x]];return Ei(e,c,N[256]),c+K[256]},fm=new oi([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),hm=(function(){for(var t=new oi(256),e=0;256>e;++e){for(var n=e,i=9;--i;)n=(1&n&&3988292384)^n>>>1;t[e]=n}return t})(),Ao=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8};function pm(t,e){e===void 0&&(e={});var n=(function(){var d=4294967295;return{p(f){for(var h=d,p=0;f.length>p;++p)h=hm[255&h^f[p]]^h>>>8;d=h},d(){return 4294967295^d}}})(),i=t.length;n.p(t);var r,s,o,a,l,u=(a=10+((r=e).filename&&r.filename.length+1||0),l=8,(function(d,f,h,p,g,m){var v=d.length,E=new ct(p+v+5*(1+Math.floor(v/7e3))+g),S=E.subarray(p,E.length-g),_=0;if(!f||8>v)for(var b=0;v>=b;b+=65535){var k=b+65535;v>k?_=ba(S,_,d.subarray(b,k)):(S[b]=!0,_=ba(S,_,d.subarray(b,v)))}else{for(var T=fm[f-1],x=T>>>13,F=8191&T,$=(1<b;++b){var Ie=V(b),Se=32767&b,De=L[Ie];if(O[Se]=De,L[Ie]=Se,b>=$e){var wt=v-b;if((Ce>7e3||ye>24576)&&wt>423){_=Xc(d,S,0,M,R,Z,oe,ye,ae,b-ae,_),ye=Ce=oe=0,ae=b;for(var ge=0;286>ge;++ge)R[ge]=0;for(ge=0;30>ge;++ge)Z[ge]=0}var Je=2,bt=0,mn=F,Re=Se-De&32767;if(wt>2&&Ie==V(b-Re))for(var Pe=Math.min(x,wt)-1,$t=Math.min(32767,b),Dn=Math.min(258,wt);$t>=Re&&--mn&&Se!=De;){if(d[b+Je]==d[b+Je-Re]){for(var qe=0;Dn>qe&&d[b+qe]==d[b+qe-Re];++qe);if(qe>Je){if(Je=qe,bt=Re,qe>Pe)break;var jn=Math.min(Re,qe-2),Mt=0;for(ge=0;jn>ge;++ge){var Lt=b-Re+ge+32768&32767,ut=Lt-O[Lt]+32768&32767;ut>Mt&&(Mt=ut,De=Lt)}}}Re+=(Se=De)-(De=O[Se])+32768&32767}if(bt){M[ye++]=268435456|ya[Je]<<18|Jc[bt];var sn=31&ya[Je],mi=31&Jc[bt];oe+=hl[sn]+pl[mi],++R[257+sn],++Z[mi],$e=b+Je,++Ce}else M[ye++]=d[b],++R[d[b]]}}_=Xc(d,S,!0,M,R,Z,oe,ye,ae,b-ae,_)}return Lf(E,0,p+Mf(_)+g)})(s=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):12+o.mem,a,l)),c=u.length;return(function(d,f){var h=f.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>f.level?4:f.level==9?2:0,d[9]=3,f.mtime!=0&&Ao(d,4,Math.floor(new Date(f.mtime||Date.now())/1e3)),h){d[3]=8;for(var p=0;h.length>=p;++p)d[p+10]=h.charCodeAt(p)}})(u,e),Ao(u,c-8,n.d()),Ao(u,c-4,i),u}var gm=!!zo||!!Xa,Nf="text/plain",Mr=!1,Of=(t,e)=>{var n=t.split("#"),i=n[1],r=n[0].split("?"),s=r[0],o=r[1];if(!o)return t;var a=o.split("&").filter((l=>l.split("=")[0]!==e)).join("&");return s+(a?"?"+a:"")+(i?"#"+i:"")},ks=function(t,e,n){var i;n===void 0&&(n=!0);var r=t.split("?"),s=r[0],o=r[1],a=I({},e),l=(i=o?.split("&").map((c=>{var d,f=c.split("="),h=f[0],p=n&&(d=a[h])!==null&&d!==void 0?d:f[1];return delete a[h],h+"="+p})))!==null&&i!==void 0?i:[],u=(function(c,d){var f,h;d===void 0&&(d="&");var p=[];return ie(c,(function(g,m){C(g)||C(m)||m==="undefined"||(f=encodeURIComponent((v=>v instanceof File)(g)?g.name:g.toString()),h=encodeURIComponent(m),p[p.length]=h+"="+f)})),p.join(d)})(a);return u&&l.push(u),l.length>0?s+"?"+l.join("&"):s},Po=t=>{if(t.Ji)return t.Ji;var e=t.data,n=t.compression;if(e){if(n===Ue.GZipJS){var i=pm((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new ct(a.length+(a.length>>>1)),d=0,f=function(m){c[d++]=m},h=0;u>h;++h){if(d+5>c.length){var p=new ct(d+8+(u-h<<1));p.set(c),c=p}var g=a.charCodeAt(h);128>g?f(g):2048>g?(f(192|g>>>6),f(128|63&g)):g>55295&&57344>g?(f(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++h))>>>18),f(128|g>>>12&63),f(128|g>>>6&63),f(128|63&g)):(f(224|g>>>12),f(128|g>>>6&63),f(128|63&g))}return Lf(c,0,d)})(Jn(e)),{mtime:0});return{contentType:Nf,body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),estimatedSize:i.byteLength}}if(n===Ue.Base64){var r=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(Jn(e)),s=(a=>"data="+encodeURIComponent(typeof a=="string"?a:Jn(a)))(r);return{contentType:"application/x-www-form-urlencoded",body:s,estimatedSize:new Blob([s]).size}}var o=Jn(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},Bf=t=>{var e,n,i=()=>t.transport==="sendBeacon"?{url:ks(t.url,{compression:Ue.Base64}),encodedBody:Po(I({},t,{compression:Ue.Base64,Ji:void 0}))}:{url:Of(t.url,"compression"),encodedBody:Po(I({},t,{compression:void 0,Ji:void 0}))};try{e=Po(t)}catch(r){if(_c(t.compression,ri(t.url,"compression")))return A.error("Failed to gzip request body, sending uncompressed payload",r),i();throw r}return e&&_c(t.compression,ri(t.url,"compression"))&&!((n=e.body)instanceof ArrayBuffer?qo(new Uint8Array(n)):ArrayBuffer.isView(n)&&qo(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)))?(Mr=!0,i()):{url:t.url,encodedBody:e}},Df=t=>{try{return Bf(t)}catch(e){return A.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},mm=(function(){var t=se((function*(e){var n=Jn(e.data),i=yield(function(s,o,a){return Vo.apply(this,arguments)})(n,ne.DEBUG,{rethrow:!0});if(!i)return e;var r=yield i.arrayBuffer();return I({},e,{Ji:{contentType:Nf,body:r,estimatedSize:r.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),vm=/Failed to fetch|NetworkError|Load failed/i,jf=t=>t?.name==="TypeError"&&vm.test(t?.message||""),Uf=t=>{var e=Df(t);if(e){var n=e.url,i=e.encodedBody,r=i??{},s=r.contentType,o=r.body,a=r.estimatedSize,l=new Headers;ie(t.headers,(function(p,g){l.append(g,p)})),s&&l.append("Content-Type",s);var u=null,c=!1;if(fc){var d=new fc;u={signal:d.signal,timeout:setTimeout((()=>{var p,g;c=!0,d.abort((p=t.timeout,(g=new Error("PostHog request timed out"+(p?" after "+p+"ms":""))).name="AbortError",g))}),t.timeout)}}var f=p=>{c&&p?.name==="AbortError"||jf(p)?A.warn(p):A.error(p),t.callback==null||t.callback({statusCode:0,error:p})};try{var h;Xa(n,I({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(h=u)==null?void 0:h.signal},t.fetchOptions)).then((p=>p.text().then((g=>{var m={statusCode:p.status,text:g};if(p.status===200)try{m.json=JSON.parse(g)}catch(v){A.error(v)}t.callback==null||t.callback(m)})))).catch(f).finally((()=>u?clearTimeout(u.timeout):null))}catch(p){u&&clearTimeout(u.timeout),f(p)}}},Ea=t=>{try{var e,n=Bf(t),i=n.url,r=n.encodedBody,s=r??{},o=s.body,a=s.estimatedSize;if(!o)return;var l=o instanceof Blob?o:new Blob([o],{type:s.contentType});if(He.sendBeacon(i,l))return;var u=U(t.data)?t.data:(e=t.data)==null?void 0:e.batch;if(U(u)&&u.length>1&&(a??0)>16384){var c=Math.ceil(u.length/2),d=f=>U(t.data)?f:I({},t.data,{batch:f});return Ea(I({},t,{data:d(u.slice(0,c))})),void Ea(I({},t,{data:d(u.slice(c))}))}A.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),Uf(I({},t,{Yi:!0}))}catch(f){A.warn("Beacon send failed",f)}},Qc=(t,e,n,i)=>{var r=i==="query"?e==="POST"?"sent_at":"_":void 0;return ks(n===Ue.GZipJS?Of(t,"compression"):t,I({},r?{[r]:Date.now().toString()}:{},n===Ue.GZipJS?{}:{compression:n}))},Lr=[];Xa&&Lr.push({transport:"fetch",method:Uf}),zo&&Lr.push({transport:"XHR",method(t){var e=Df(t);if(e){var n=new zo,i=e.encodedBody;n.open(t.method||"GET",e.url,!0);var r=i??{},s=r.contentType,o=r.body;ie(t.headers,(function(a,l){n.setRequestHeader(l,a)})),s&&n.setRequestHeader("Content-Type",s),t.timeout&&(n.timeout=t.timeout),n.onreadystatechange=()=>{if(n.readyState===4){var a={statusCode:n.status,text:n.responseText};if(n.status===200)try{a.json=JSON.parse(n.responseText)}catch{}t.callback==null||t.callback(a)}},n.send(o)}}}),He!=null&&He.sendBeacon&&Lr.push({transport:"sendBeacon",method:Ea});var Sa=3e3;class _m{constructor(e,n){this.Xi=!0,this.tr=[],this.er=At(n?.flush_interval_ms||Sa,250,5e3,A.createLogger("flush interval"),Sa),this.ir=e}enqueue(e){this.tr.push(e),this.rr||this.nr()}unload(){this.sr();var e=this.tr.length>0?this.ar():{},n=Object.values(e);[...n.filter((i=>i.url.indexOf("/e")===0)),...n.filter((i=>i.url.indexOf("/e")!==0))].map((i=>{this.lr(I({},i,{transport:"sendBeacon"}))}))}enable(){this.Xi=!1,this.nr()}nr(){var e=this;this.Xi||(this.rr=setTimeout((()=>{if(this.sr(),this.tr.length>0){var n=this.ar(),i=function(){var s=n[r],o=new Date().getTime();s.data&&U(s.data)&&ie(s.data,(a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp})),e.lr(s)};for(var r in n)i()}}),this.er))}lr(e){try{this.ir(e)}catch(n){A.error(n)}}sr(){clearTimeout(this.rr),this.rr=void 0}ar(){var e={};return ie(this.tr,(n=>{var i,r=n,s=(r?r.batchKey:null)||r.url;C(e[s])&&(e[s]=I({},r,{data:[]})),(i=e[s].data)==null||i.push(r.data)})),this.tr=[],e}}var ym=["retriesPerformedSoFar"];class wm{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!C(w)&&"onLine"in w.navigator&&(this.dr=w.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},ve(w,"online",this.vr),ve(w,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var n=e.retriesPerformedSoFar,i=pd(e,ym);Dt(n)&&(i.url=ks(i.url,{retry_count:n})),this._instance._send_request(I({},i,{callback:r=>{if(r.statusCode!==200&&(400>r.statusCode||r.statusCode>=500)){if((r.statusCode===0?3:10)>(n??0))return void this.At(I({retriesPerformedSoFar:n},i));r.statusCode===0&&A.warn("Request failed before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped retrying after "+(n??0)+" retries.")}i.callback==null||i.callback(r)}}))}At(e){var n=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=n+1;var i=(function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),c=Math.random()-.5;return Math.ceil(u+c*(u-l))})(n),r=Date.now()+i;this.tr.push({retryAt:r,requestOptions:e});var s="Enqueued failed request for retry in "+i;navigator.onLine||(s+=" (Browser is offline)"),A.warn(s),this.ur||(this.ur=!0,this.gr())}gr(){if(this.mr&&clearTimeout(this.mr),this.tr.length===0)return this.ur=!1,void(this.mr=void 0);this.mr=setTimeout((()=>{this.dr&&this.tr.length>0&&this.cr(),this.gr()}),this.hr)}cr(){var e=Date.now(),n=[],i=this.tr.filter((s=>e>s.retryAt||(n.push(s),!1)));if(this.tr=n,i.length>0)for(var r of i)this.retriableRequest(r.requestOptions)}unload(){for(var e of(this.mr&&(clearTimeout(this.mr),this.mr=void 0),this.ur=!1,C(w)||(this.vr&&(w.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(w.removeEventListener("offline",this.pr),this.pr=void 0)),this.tr)){var n=e.requestOptions;try{this._instance._send_request(I({},n,{transport:"sendBeacon"}))}catch(i){A.error(i)}}this.tr=[]}}class bm{constructor(e){this.yr=()=>{var n,i,r,s;this.br||(this.br={});var o=this.scrollElement(),a=this.scrollY(),l=o?Math.max(0,o.scrollHeight-o.clientHeight):0,u=a+(o?.clientHeight||0),c=o?.scrollHeight||0;this.br.lastScrollY=Math.ceil(a),this.br.maxScrollY=Math.max(a,(n=this.br.maxScrollY)!==null&&n!==void 0?n:0),this.br.maxScrollHeight=Math.max(l,(i=this.br.maxScrollHeight)!==null&&i!==void 0?i:0),this.br.lastContentY=u,this.br.maxContentY=Math.max(u,(r=this.br.maxContentY)!==null&&r!==void 0?r:0),this.br.maxContentHeight=Math.max(c,(s=this.br.maxContentHeight)!==null&&s!==void 0?s:0)},this._instance=e}get _r(){return this._instance.config.scroll_root_selector}getContext(){return this.br}resetContext(){var e=this.br;return setTimeout(this.yr,0),e}startMeasuringScrollPosition(){ve(w,"scroll",this.yr,{capture:!0}),ve(w,"scrollend",this.yr,{capture:!0}),ve(w,"resize",this.yr)}scrollElement(){if(!this._r)return w?.document.documentElement;var e=U(this._r)?this._r:[this._r];for(var n of e){var i=w?.document.querySelector(n);if(i)return i}}wr(e){var n=e==="y"?"scrollTop":"scrollLeft";if(this._r){var i=this.scrollElement();return i&&i[n]||0}return w?e==="y"?w.scrollY||w.pageYOffset||w.document.documentElement.scrollTop||0:w.scrollX||w.pageXOffset||w.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var Em=t=>Cf(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class eu{constructor(e,n,i,r){this.kr=s=>{var o=this.Sr();if(!o||o.sessionId!==s){var a={sessionId:s,props:this.Cr(this._instance)};this.Mr.register({[ua]:a})}},this._instance=e,this.Tr=n,this.Mr=i,this.Cr=r||Em,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[ua]}getSetOnceProps(){var e,n=(e=this.Sr())==null?void 0:e.props;return n?"r"in n?Af(n,this._instance.config.disable_capture_url_hashes):{$referring_domain:n.referringDomain,$pathname:n.initialPathName,utm_source:n.utm_source,utm_campaign:n.utm_campaign,utm_medium:n.utm_medium,utm_content:n.utm_content,utm_term:n.utm_term}:{}}getSessionProps(){var e={};return ie(cl(this.getSetOnceProps()),((n,i)=>{i==="$current_url"&&(i="url"),e["$session_entry_"+Go(i)]=n})),e}}class gl{on(e,n){return this.Er[e]||(this.Er[e]=[]),this.Er[e].push(n),()=>{this.Er[e]=this.Er[e].filter((i=>i!==n))}}emit(e,n){for(var i of this.Er[e]||[])i(n);for(var r of this.Er["*"]||[])r(e,n)}constructor(){this.Er={}}}var xi=pe("[SessionId]");class tu{on(e,n){return this.Ir.on(e,n)}constructor(e,n,i){var r;if(this.Pr=null,this.Rr=[],this.Ar=void 0,this.Fr=!1,this.Ir=new gl,this.Lr=(u,c)=>!(!Dt(u)||!Dt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===Wt)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Ne=e.config,this.Mr=e.persistence,this.Or=void 0,this.Dr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.$r=n||Ht,this.Nr=i||Ht;var s=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*At(this.Ne.session_idle_timeout_seconds||1800,60,36e3,xi.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.qr(),this.jr="ph_"+s+"_window_id",this.Br="ph_"+s+"_primary_window_exists",this.Hr()){var o=be.H(this.jr),a=be.H(this.Br);o&&!a?this.Or=o:be.q(this.jr),be.F(this.Br,!0)}if((r=this.Ne.bootstrap)!=null&&r.sessionID)try{var l=(u=>{var c=this.Ne.bootstrap.sessionID.replace(/-/g,"");if(c.length!==32)throw new Error("Not a valid UUID");if(c[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(c.substring(0,12),16)})();this.Ur(this.Ne.bootstrap.sessionID,new Date().getTime(),l)}catch(u){xi.error("Invalid sessionID in bootstrap",u)}this.zr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return C(this.Rr)&&(this.Rr=[]),this.Rr.push(e),this.Dr&&e(this.Dr,this.Or),()=>{this.Rr=this.Rr.filter((n=>n!==e))}}Hr(){return this.Ne.persistence!=="memory"&&!this.Mr.xi&&be.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&be.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?be.H(this.jr):null}Zr(e){var n=this.Pr;return!Ye(n)&&!Ye(e)&&5e3>Math.abs(e-n)}Ur(e,n,i){var r=n!==this._sessionActivityTimestamp,s=!(e!==this.Dr||i!==this._sessionStartTimestamp);this._sessionStartTimestamp=i,this._sessionActivityTimestamp=n,this.Dr=e,s&&!r||s&&this.Zr(n)||(this.Pr=n,this.Mr.register({[Yn]:[n,e,i]}))}Gr(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return Dt(n)&&n>0}Qr(){this.Gr()?this.Mr.refreshKey(Yn):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!Ye(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this.Pr){this.Qr();var n=this.Jr();n[1]===this.Dr&&n[2]===this._sessionStartTimestamp&&(this.Pr=this._sessionActivityTimestamp,this.Mr.register({[Yn]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],n=Dt(e)?e:0,i=Dt(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(n,i)}Xr(e){return this.Qr(),this.Lr(e,this.Yr())}Jr(){var e=this.Mr.props[Yn];return U(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Pr=null,clearTimeout(this.tn),this.tn=void 0,this.Ur(null,null,null)}destroy(){this.Fr=!0,this.Kr(),clearTimeout(this.tn),this.tn=void 0,this.Ar&&w&&(w.removeEventListener(ns,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&be.q(this.Br)},ve(w,ns,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=null),this.Ne.cookieless_mode===Wt)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var i=n||new Date().getTime(),r=this.Jr(),s=r[1],o=r[2],a=this.Yr(),l=this.Vr(),u=Dt(o)&&Math.abs(i-o)>864e5,c=!1,d=!1,f=!s,h=s,p=!f&&!e&&this.Lr(i,a);if(p){(p=this.Xr(i))||xi.info("cross-tab refresh kept the session alive",{sessionId:s});var g=this.Jr();s=g[1],o=g[2]}f||p||u?(s=this.$r(),l=this.Nr(),xi.info("new session ID generated",{sessionId:s,windowId:l,changeReason:{noSessionId:f,activityTimeout:p,sessionPastMaximumLength:u}}),o=i,c=!0):(l||(l=this.Nr(),c=!0),(d=s!==h)&&(xi.info("adopted cross-tab session id",{sessionId:s,windowId:l}),c=!0));var m=Dt(a)&&e&&!u?a:i,v=Dt(o)?o:new Date().getTime();this.Wr(l),this.Ur(s,m,v),e||this.qr();var E={noSessionId:f,activityTimeout:p,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((S=>S(s,l,E))),{sessionId:s,windowId:l,sessionStartTimestamp:v,changeReason:c?E:void 0,lastActivityTimestamp:a}}qr(){this.Fr||(clearTimeout(this.tn),this.tn=setTimeout((()=>{if(!this.Fr)if(this.Xr(new Date().getTime())){var e=this.Dr;this.resetSessionId(),this.Ir.emit("forcedIdleReset",{idleSessionId:e})}else this.qr()}),1.1*this.sessionTimeoutMs))}}var Hf=function(t,e){if(!t)return!1;var n=t.userAgent;if(n&&wc(n,e))return!0;try{var i=t?.userAgentData;if(i!=null&&i.brands&&i.brands.some((r=>wc(r?.brand,e))))return!0}catch{}return!!t.webdriver};function Wf(){return(Wf=se((function*(){var t=He?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),n=e?.model;return X(n)&&n.length>0?n:void 0}catch(i){return void A.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",i)}}))).apply(this,arguments)}var cs=function(t,e){if(!(function(n){try{new RegExp(n)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function Fo(t,e,n){return Jn({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}var zf={exact:(t,e)=>e.some((n=>t.some((i=>n===i)))),is_not:(t,e)=>e.every((n=>t.every((i=>n!==i)))),regex:(t,e)=>e.some((n=>t.some((i=>cs(n,i))))),not_regex:(t,e)=>e.every((n=>t.every((i=>!cs(n,i))))),icontains:(t,e)=>e.map(Er).some((n=>t.map(Er).some((i=>n.includes(i))))),not_icontains:(t,e)=>e.map(Er).every((n=>t.map(Er).every((i=>!n.includes(i))))),gt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>i>parseFloat(r)))})),lt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>it.toLowerCase();function qf(t,e){return!t||Object.entries(t).every((n=>{var i=n[1],r=e?.[n[0]];if(C(r)||Ye(r))return!1;var s=[String(r)],o=zf[i.operator];return!!o&&o(i.values,s)}))}var xa="custom",nu="i.posthog.com",Sm=/^\/static\//;class xm{constructor(e){this.en={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,n=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return n||(n=this.apiHost.replace("."+nu,".posthog.com")),n==="https://app.posthog.com"?"https://us.posthog.com":n}get region(){return this.en[this.apiHost]||(this.en[this.apiHost]=/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"us":/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"eu":xa),this.en[this.apiHost]}rn(e){if(Sm.test(e)){var n=this.instance.config.asset_host;if(typeof n=="string")return n.trim().replace(/\/$/,"")||void 0}}endpointFor(e,n){if(n===void 0&&(n=""),n&&(n=n[0]==="/"?n:"/"+n),e==="ui")return this.uiHost+n;if(e==="flags")return this.flagsApiHost+n;if(e==="assets"){var i=this.rn(n);if(i)return""+i+n}if(this.region===xa)return this.apiHost+n;var r=nu+n;switch(e){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}}function Vf(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var Q=pe("[Surveys]"),Gf="seenSurvey_",Kf=t=>{try{var e=(n=>((i,r)=>""+Gf+(function(s){return s.current_iteration&&s.current_iteration>0?s.id+"_"+s.current_iteration:s.id})(r))(0,n))(t);if(localStorage.getItem(e))return;localStorage.setItem(e,"true")}catch(n){Q.error("Failed to persist survey seen state",n)}},Im=[Io.Popover,Io.Widget,Io.API],km={ignoreConditions:!1,ignoreDelay:!1,displayType:_a.Popover},Cm=pe("[PostHog ExternalIntegrations]"),Am={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class Pm{constructor(e){this._instance=e}ai(e,n){var i;(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,e,(r=>{if(r)return Cm.error("failed to load script",r);n()}))}startIfEnabledOrStop(){var e=this,n=function(){var s,o,a,l=i[0],u=i[1];!u||(s=B.__PosthogExtensions__)!=null&&(s=s.integrations)!=null&&s[l]||e.ai(Am[l],(()=>{var c;(c=B.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=B.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=B.__PosthogExtensions__)==null||(a=a.integrations)==null||(a=a[l])==null||a.stop())};for(var i of Object.entries((r=this._instance.config.integrations)!==null&&r!==void 0?r:{})){var r;n()}}}class Fm{constructor(e,n){this.rt=e,this.nn=n,this.sn=new Map,this.an=!1}add(e){var n=this;return se((function*(){if(n.an)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(n.sn.has(e.name))throw new Error('Browser extension "'+e.name+'" is already registered');n.sn.set(e.name,e);try{var i=e.setup(n.nn);i&&(yield i)}catch(s){var r=n.sn.get(e.name)===e;r&&n.sn.delete(e.name),n.rt.error('Failed to set up browser extension "'+e.name+'"',s),r&&n.ln(e)}}))()}dispose(){if(!this.an){this.an=!0;var e=Array.from(this.sn.values()).reverse();for(var n of(this.sn.clear(),e))this.ln(n)}}ln(e){try{var n=e.dispose==null?void 0:e.dispose();n&&je(n.then)&&n.then(void 0,(i=>{this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}))}catch(i){this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}}}class Rm{constructor(e){this._instance=e}initialize(){}get(e){var n=this._instance.persistence;if(typeof e=="string")return n?.get_property(e);var i={};for(var r of e){var s=n?.get_property(r);C(s)||(i[r]=s)}return i}set(e,n){var i;(i=this._instance.persistence)==null||i.register(typeof e=="string"?{[e]:n}:e)}remove(e){var n;(n=this._instance.persistence)==null||n.unregister(e)}}var iu="extensionsRemoteConfig";class Tm{constructor(e){this.an=!1,this.instance=e,this.rt=A,this.un=e.hn,this.kv=new Rm(e),this.onEvent=n=>br(this.instance.on("eventCaptured",(i=>{try{n({event:i.event,properties:i.properties})}catch(r){this.rt.error("Browser extension event listener failed",r)}}))),this.onRemoteConfig=n=>{if(this.an)return br((()=>{}));var i=s=>{try{n(s)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},r=this.instance.dn.on(iu,i);return this.un&&i(this.un),br(r)},this.vn=new Fm(A.createLogger("[BrowserExtensions]"),this)}get logger(){return this.rt}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return(e=this.instance.get_property(Ji))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(Ji);return typeof e=="string"?e:void 0}get library(){return{name:ne.LIB_NAME,version:ne.LIB_VERSION}}get initialPersonProperties(){var e,n;return(e=(n=this.instance.persistence)==null?void 0:n.get_initial_props())!==null&&e!==void 0?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,n,i,r,s=(e=this.instance.sessionManager)==null?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:(n=s?.sessionId)!==null&&n!==void 0?n:"",windowId:(i=s?.windowId)!==null&&i!==void 0?i:"",sessionStartTimestamp:(r=s?.sessionStartTimestamp)!==null&&r!==void 0?r:0}}catch{return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get projectToken(){return this.instance.config.token}add(e){return this.vn.add(e)}capture(e,n,i){var r=this;return se((function*(){i?r.instance.capture(e,n,{timestamp:i.timestamp,uuid:i.uuid,$set:i.set,$set_once:i.setOnce}):r.instance.capture(e,n)}))()}registerDynamicEventProperties(e){return br(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(iu,e))}sendRequest(e,n){var i=this;return se((function*(){var r;n===void 0&&(n={});var s=i.instance.requestRouter.endpointFor((r=n.target)!==null&&r!==void 0?r:"api",e),o={method:n.method,url:n.query?ks(s,n.query):s,data:n.body,headers:n.headers,timeout:n.timeoutMs,fireCallbackOnDrop:!0,transport:n.transport,compression:n.compression,timestampMode:n.sentAt};return n.transport==="sendBeacon"?(i.instance._send_request(o),{statusCode:202}):new Promise((a=>{o.callback=a,i.instance._send_request(o)}))}))()}dispose(){this.an||(this.an=!0,this.vn.dispose())}}var zi={},Ro=0,us=()=>{},ru='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',Ii="Surveys module not available",su="sanitize_properties is deprecated. Use before_send instead",Yf="Invalid value for property_denylist config: ",$m=["token","distinct_id",tf],Kn="posthog",Jf=!gm&&Ge?.indexOf("MSIE")===-1&&Ge?.indexOf("Mozilla")===-1,To=t=>{var e;return I({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:Mg(P?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:us,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:t??"unset",__preview_deferred_init_extensions:!1,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:me&&X(me?.search)&&me.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disableDeviceModel:!1,disable_external_dependency_loading:!1,strict_script_versioning:!1,enable_recording_console_log:void 0,secure_cookie:(w==null||(e=w.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(n){A.error("Bad HTTP status: "+n.statusCode+" "+n.text)},get_device_id:n=>n,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:pa,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:Sa},error_tracking:{},_onCapture:us},(n=>({rageclick:n&&n>="2026-05-30"?{content_ignorelist:Vg,ignore_text_selection:!0}:!n||"2025-11-30">n||{content_ignorelist:!0},capture_pageview:!n||"2025-05-24">n||"history_change",session_recording:n&&n>="2026-06-25"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6},streamNetworkBody:!0}:n&&n>="2026-05-30"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6}}:n&&n>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:n&&n>="2026-01-30"?"head":"body",internal_or_test_user_hostname:n&&n>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:n&&n>="2026-05-30"?250:0,split_storage:!(!n||"2026-05-30">n),detect_google_search_app:!(!n||"2026-05-30">n),disable_capture_url_hashes:!(!n||"2026-06-25">n)}))(t))},Mm=[["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"]],ou=t=>{var e={};for(var n of Mm){var i=n[0],r=n[1];C(t[i])||(e[r]=t[i])}var s=fe({},e,t),o=t.__preview_external_dependency_versioned_paths;return C(o)||(C(t.strict_script_versioning)&&(s.strict_script_versioning=!!o),X(o)&&C(t.asset_host)&&(s.asset_host=o)),U(t.property_blacklist)&&(C(t.property_denylist)?s.property_denylist=t.property_blacklist:U(t.property_denylist)?s.property_denylist=[...t.property_blacklist,...t.property_denylist]:A.error(Yf+t.property_denylist)),s};class Lm{constructor(){this.__forceAllowLocalhost=!1}get fn(){return this.__forceAllowLocalhost}set fn(e){A.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class Ze{pn(e,n){if(e){var i=this.sn.indexOf(e);i!==-1&&this.sn.splice(i,1)}return this.sn.push(n),n.initialize==null||n.initialize(),n}gn(){return this.config.cookieless_mode===Wt||this.config.cookieless_mode===kn&&this.consent.isRejected()}get decideEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){var e;this.webPerformance=new Lm,this.mn=!1,this.version=ne.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new gl,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=To(),this.SentryIntegration=em,this.sentryIntegration=i=>(function(r,s){var o=wf(r,s);return{name:yf,processEvent:a=>o(a)}})(this,i),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.wn=!1,this.kn=null,this.xn=null,this.Sn=null,this.scrollManager=new bm(this),this.pageViewManager=new qc(this),this.rateLimiter=new cm(this),this.requestRouter=new xm(this),this.consent=new Ug(this),this.externalIntegrations=new Pm(this);var n=(e=Ze.__defaultExtensionClasses)!==null&&e!==void 0?e:{};this.featureFlags=n.featureFlags&&new n.featureFlags(this),this.toolbar=n.toolbar&&new n.toolbar(this),this.surveys=n.surveys&&new n.surveys(this),this.conversations=n.conversations&&new n.conversations(this),this.logs=n.logs&&new n.logs(this),this.metrics=n.metrics&&new n.metrics(this),this.experiments=n.experiments&&new n.experiments(this),this.exceptions=n.exceptions&&new n.exceptions(this),this.people={set:(i,r,s)=>{var o=X(i)?{[i]:r}:i;this.setPersonProperties(o),s?.({})},set_once:(i,r,s)=>{var o=X(i)?{[i]:r}:i;this.setPersonProperties(void 0,o),s?.({})}},this.on("eventCaptured",(i=>A.info('send "'+i?.event+'"',i)))}init(e,n,i){if(i&&i!==Kn){var r,s=(r=zi[i])!==null&&r!==void 0?r:new Ze;return s._init(e,n,i),zi[i]=s,zi[Kn][i]=s,s}return this._init(e,n,i)}_init(e,n,i){var r,s;n===void 0&&(n={});var o,a=X(e)?e.trim():"";if(!a)return A.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return a!==((o=this.config)==null?void 0:o.token)?console.warn("[PostHog.js]","You have already initialized PostHog with a different project token! Re-initializing is a no-op, so events will keep going to the project this instance was initialized with. To capture into a second project, load PostHog once, then initialize a named instance after the SDK has loaded, e.g. posthog.init('"+a+"', { ... }, 'project2')"):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=To(n.defaults),n.debug=this.Cn(n.debug),this.Mn=n,this.Tn=[],n.person_profiles?this.xn=n.person_profiles:n.process_person&&(this.xn=n.process_person);var l=To(n.defaults),u=ou(n),c=fe({},l,u,{name:i,token:a});he(l.rageclick)&&he(u.rageclick)&&(c.rageclick=fe({},l.rageclick,u.rageclick)),he(l.session_recording)&&he(u.session_recording)&&(c.session_recording=fe({},l.session_recording,u.session_recording)),this.set_config(c),this.config.on_xhr_error&&A.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=n.disable_compression?void 0:Ue.GZipJS;var d=this.En();if(this.persistence=new xo(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new xo(I({},this.config,{persistence:"sessionStorage"}),d,!1),this.bn="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&be.N()){var f=be.H(this.bn);U(f)&&f.forEach((k=>{X(k)&&this.yn.add(k)}))}else be.q(this.bn);var h=I({},this.persistence.props),p=I({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new _m((k=>this.Pn(k)),this.config.request_queue_config),this.Rn=new wm(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new tu(this),this.sessionPropsManager=new eu(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((k,T,x)=>{(x!=null&&x.activityTimeout||x!=null&&x.sessionPastMaximumLength||x!=null&&x.crossTabAdoption)&&this.An()}))),this.Fn(),this.config.__preview_deferred_init_extensions?(A.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Ln(g)}),0)):(A.info("Initializing extensions synchronously"),this.Ln(g)),ne.DEBUG=ne.DEBUG||this.config.debug,ne.DEBUG&&A.info("Starting in debug mode",{this:this,config:n,thisC:I({},this.config),p:h,s:p}),!this.config.identity_distinct_id||(r=n.bootstrap)!=null&&r.distinctID||(n.bootstrap=I({},n.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((s=n.bootstrap)==null?void 0:s.distinctID)!==void 0){var m=n.bootstrap.distinctID,v=this.get_distinct_id(),E=this.persistence.get_property(at);if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&E===Hn)this.identify(m);else if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&E===vn)A.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{var S=this.config.get_device_id(Ht()),_=n.bootstrap.isIdentifiedID?S:m;this.persistence.set_property(at,n.bootstrap.isIdentifiedID?vn:Hn),this.register({distinct_id:m,$device_id:_})}}if(g)this.register_once({distinct_id:mr,$device_id:null},"");else if(!this.get_distinct_id()){var b=this.config.get_device_id(Ht());this.register_once({distinct_id:b,$device_id:b},""),this.persistence.set_property(at,Hn)}return ve(w,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),n.segment?(function(k,T){var x=k.config.segment;if(!x)return T();(function(F,$){var O=F.config.segment;if(!O)return $();var L=K=>{var V=()=>K.anonymousId()||Ht();F.config.get_device_id=V,K.id()&&(F.register({distinct_id:K.id(),$device_id:V()}),F.persistence.set_property(at,vn)),$()},N=O.user();"then"in N&&je(N.then)?N.then(L):L(N)})(k,(()=>{x.register((F=>{typeof Promise<"u"&&Promise.resolve||Eo.warn("This browser does not have Promise support, and can not use the segment integration");var $=(O,L)=>{if(!L)return O;O.event.userId||O.event.anonymousId===F.get_distinct_id()||(Eo.info("No userId set, resetting PostHog"),F.reset()),O.event.userId&&O.event.userId!==F.get_distinct_id()&&(Eo.info("UserId set, identifying with PostHog"),F.identify(O.event.userId));var N=F.calculateEventProperties(L,O.event.properties);return O.event.properties=Object.assign({},N,O.event.properties),O};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:O=>$(O,O.event.event),page:O=>$(O,Gn),identify:O=>$(O,yo),screen:O=>$(O,"$screen")}})(k)).then((()=>{T()}))}))})(this,(()=>this.On())):this.On(),je(this.config._onCapture)&&this.config._onCapture!==us&&(A.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(k=>this.config._onCapture(k.event,k)))),this.config.ip&&A.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this.config.disableDeviceModel||(function(){return Wf.apply(this,arguments)})().then((k=>{k&&this.register({[vo]:k})})).catch(us),this}Fn(){var e,n,i,r,s,o,a=(e=(n=this.config.__extensionClasses)==null?void 0:n.featureFlags)!==null&&e!==void 0?e:(i=Ze.__defaultExtensionClasses)==null?void 0:i.featureFlags;a&&(this.featureFlags&&this.featureFlags instanceof a||((r=this.Dn)==null||r.call(this),this.Dn=void 0,this.featureFlags=new a(this)),je(this.featureFlags.onReloading)&&je(this.featureFlags.setup)?this.Dn||(this.Dn=this.featureFlags.onReloading((()=>{this.dn.emit("featureFlagsReloading",!0)})),this.$n().add(this.featureFlags)):(s=(o=this.featureFlags).initialize)==null||s.call(o))}Ln(e){var n,i,r,s,o,a,l,u=performance.now(),c=I({},Ze.__defaultExtensionClasses,this.config.__extensionClasses),d=[];c.exceptions&&this.sn.push(this.exceptions=(n=this.exceptions)!==null&&n!==void 0?n:new c.exceptions(this)),c.historyAutocapture&&this.sn.push(this.historyAutocapture=new c.historyAutocapture(this)),c.tracingHeaders&&this.sn.push(this.tracingHeaders=new c.tracingHeaders(this)),c.siteApps&&this.sn.push(this.siteApps=new c.siteApps(this)),c.sessionRecording&&!e&&this.sn.push(this.sessionRecording=new c.sessionRecording(this)),this.config.disable_scroll_properties||d.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),c.autocapture&&this.sn.push(this.autocapture=new c.autocapture(this)),c.surveys&&this.sn.push(this.surveys=(i=this.surveys)!==null&&i!==void 0?i:new c.surveys(this)),c.logs&&this.sn.push(this.logs=(r=this.logs)!==null&&r!==void 0?r:new c.logs(this)),c.metrics&&this.sn.push(this.metrics=(s=this.metrics)!==null&&s!==void 0?s:new c.metrics(this)),c.conversations&&this.sn.push(this.conversations=(o=this.conversations)!==null&&o!==void 0?o:new c.conversations(this)),c.productTours&&this.sn.push(this.productTours=new c.productTours(this)),c.heatmaps&&this.sn.push(this.heatmaps=new c.heatmaps(this)),c.webVitalsAutocapture&&this.sn.push(this.webVitalsAutocapture=new c.webVitalsAutocapture(this)),c.exceptionObserver&&this.sn.push(this.exceptionObserver=new c.exceptionObserver(this)),c.deadClicksAutocapture&&this.sn.push(this.deadClicksAutocapture=new c.deadClicksAutocapture(this,Qg)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((f=>{f.initialize&&d.push((()=>{f.initialize==null||f.initialize()}))})),d.push((()=>{if(this.Nn){var f=this.Nn;this.Nn=void 0,this.sn.forEach((h=>h.onRemoteConfig==null?void 0:h.onRemoteConfig(f)))}})),this.qn(d,u)}qn(e,n){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,n)}),0);var i=e.shift();if(i)try{i()}catch(s){A.error("Error initializing extension:",s)}}var r=Math.round(performance.now()-n);this.register_for_session({[nf]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[rf]:r}),this.config.__preview_deferred_init_extensions&&A.info("PostHog extensions initialized ("+r+"ms)")}Zi(e){var n;if(!P||!P.body)return A.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.Zi(e)}),500);if(this.config.__preview_deferred_init_extensions&&(this.Nn=e),this.hn=e,this.compression=void 0,e.ok){var i,r=e.config;r.supportedCompression&&!this.config.disable_compression&&(this.compression=j(r.supportedCompression,Ue.GZipJS)?Ue.GZipJS:j(r.supportedCompression,Ue.Base64)?Ue.Base64:void 0),(i=r.analytics)!=null&&i.endpoint&&(this.analyticsDefaultEndpoint=r.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:pa}),(n=this.jn)==null||n.handleRemoteConfig(e),this.sn.forEach((s=>s.onRemoteConfig==null?void 0:s.onRemoteConfig(e)))}On(){try{this.config.loaded(this)}catch(i){A.critical("`loaded` function failed",i)}if(this.Bn(),this.config.internal_or_test_user_hostname&&me!=null&&me.hostname){var e=me.hostname,n=this.config.internal_or_test_user_hostname;(typeof n=="string"?e===n:n.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.gn())&&this.Hn()}),1),this.Un=new Ff(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()&&vr(this.__request_queue,(e=>this.Pn(e))),this.__request_queue=[],this.Bn()}_handle_unload(){var e,n,i,r,s;(e=this.surveys)==null||e.handlePageUnload==null||e.handlePageUnload(),(n=this.metrics)==null||n.flush("sendBeacon"),this.config.request_batching?(this.zn()&&this.capture(_o),(i=this.logs)==null||i.flushLogs("sendBeacon"),(r=this.In)==null||r.unload(),(s=this.Rn)==null||s.unload()):this.zn()&&this.capture(_o,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?Jf?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)?e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:429})):(e.transport=e.transport||this.config.api_transport,e.headers=I({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,(C(this.config.disable_beacon)?this.config.__preview_disable_beacon:this.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(n=>{var i,r,s,o=I({},n);o.timeout=o.timeout||6e4;var a,l,u,c,d,f=(i=o.transport)!==null&&i!==void 0?i:"fetch";f==="sendBeacon"&&C(o.compression)&&o.data&&(o.compression=Ue.Base64),o.method==="POST"&&o.data&&(o.timestampMode==="capture-body"?o.data={api_key:(l=(d=(c=U(a=o.data)?a:[a])[0])==null||(u=d.properties)==null?void 0:u.token)!==null&&l!==void 0?l:d?.token,batch:c,sent_at:new Date().toISOString()}:o.timestampMode==="body"&&(o.data=(function(m,v){return v===void 0&&(v=new Date().toISOString()),U(m)?m.map((E=>I({},E,{sent_at:v}))):I({},m,{sent_at:v})})(o.data))),o.url=Qc(o.url,o.method,o.compression,o.timestampMode);var h=Lr.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),p=(r=(s=(function(m,v){for(var E=0;m.length>E;E++)if(m[E].transport===f)return m[E]})(h))==null?void 0:s.method)!==null&&r!==void 0?r:h[0].method;if(!p)throw new Error("No available transport method");var g=m=>{try{p(m)}catch(v){jf(v)?A.warn(v):A.error(v),o.callback==null||o.callback({statusCode:0,error:v})}};f!=="sendBeacon"&&o.data&&o.compression===Ue.GZipJS&&Np&&typeof Promise<"u"&&!Mr?mm(o).then((m=>{g(m)})).catch((m=>{if(yc(m))return Mr=!0,void g(I({},o,{compression:void 0,url:Qc(n.url,n.method,void 0,n.timestampMode)}));(v=>{if(!v||typeof v!="object")return!1;var E="name"in v?String(v.name):"";return yc(v)||E===gd})(m)&&(Mr=!0),g(o)})):p(o)})(I({},e,{callback:n=>{var i,r;this.rateLimiter.checkForLimiting(n),400>n.statusCode||(i=(r=this.config).on_request_error)==null||i.call(r,n),e.callback==null||e.callback(n)}}))):e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:0}))}Pn(e){this.Rn?this.Rn.retriableRequest(e):this._send_request(e)}_execute_array(e){Ro++;try{var n,i=[],r=[],s=[];vr(e,(a=>{if(a)if(U(n=a[0]))s.push(a);else if(je(a))try{a.call(this)}catch(l){A.error("Error executing queued PostHog call",a,l)}else U(a)&&n==="alias"?i.push(a):U(a)&&n.indexOf("capture")!==-1&&je(this[n])?s.push(a):r.push(a)}));var o=function(a,l){vr(a,(function(u){try{if(U(u[0])){var c=l;ie(u,(function(d){c=c[d[0]].apply(c,d.slice(1))}))}else l[u[0]].apply(l,u.slice(1))}catch(d){A.error("Error executing queued PostHog call",u,d)}}))};o(i,this),o(r,this),o(s,this)}finally{Ro--}}push(e){if(Ro>0&&U(e)&&X(e[0])){var n=Ze.prototype[e[0]];je(n)&&n.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,n,i){var r,s,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.In){if(this.is_capturing())if(!C(e)&&X(e)){var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var c=i!=null&&i.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(c==null||!c.isRateLimited){n!=null&&n.$current_url&&!X(n?.$current_url)&&(A.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),n==null||delete n.$current_url),e!=="$exception"||i!=null&&i.Wn||A.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,f=i?.timestamp||d,h=xc(i?.uuid,Ht),p={uuid:h,event:e,properties:this.calculateEventProperties(e,n||{},f,h)};e===Gn&&this.config.__preview_capture_bot_pageviews&&u&&(p.event="$bot_pageview",p.properties.$browser_type="bot"),c&&(p.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&p.properties.$feature_flag_has_experiment===!1&&this.get_property(Zr)===!0;i?.$set&&!g&&(p.$set=i?.$set);var m=i?.$unset;m&&(p.$unset=m);var v,E,S,_=g?void 0:this.Vn(i?.$set_once,e!==Fc,e===yo);if(_&&(p.$set_once=_),i!=null&&i._noTruncate||(s=this.config.properties_string_max_length,o=p,a=L=>X(L)?L.slice(0,s):L,l=new Set,p=(function L(N,K){if(N!==Object(N))return a?a(N):N;if(!l.has(N)){var V;if(l.add(N),U(N))V=[],vr(N,(R=>{V.push(L(R))}));else{var M={};ie(N,((R,Z)=>{l.has(R)||(M[Z]=L(R))})),V=M}return V}})(o)),p.timestamp=f,C(i?.timestamp)||(p.properties.$event_time_override_provided=!0,p.properties.$event_time_override_system_time=d),g&&(p.properties=(function(L,N){N===void 0&&(N=[]);var K={},V=M=>{L[M]!==void 0&&(K[M]=L[M])};return Op.forEach(V),N.forEach(V),K})(p.properties,$m)),e===qt.DISMISSED||e===qt.SENT){var b=n?.[ko.SURVEY_ID],k=n?.[ko.SURVEY_ITERATION];Kf({id:b,current_iteration:k}),p.$set=I({},p.$set,{[(v={id:b,current_iteration:k},E=e===qt.SENT?"responded":"dismissed",S="$survey_"+E+"/"+v.id,v.current_iteration&&v.current_iteration>0&&(S="$survey_"+E+"/"+v.id+"/"+v.current_iteration),S)]:!0})}else e===qt.SHOWN&&(p.$set=I({},p.$set,{[ko.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===lm.SHOWN){var T=n?.[Gc.TOUR_TYPE];T&&(p.$set=I({},p.$set,{[Gc.TOUR_LAST_SEEN_DATE+"/"+T]:new Date().toISOString()}))}var x=I({},p.properties.$set,p.$set);if(Kt(x)||this.setPersonPropertiesForFlags(x),!H(this.config.before_send)){var F=this.Pt(p);if(!F)return;(p=F).uuid=xc(p.uuid,Ht)}this.dn.emit("eventCaptured",p);var $=(r=i?._url)!==null&&r!==void 0?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),O={method:"POST",url:$,data:p,compression:"best-available",timestampMode:i?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test($)?"body":"capture-body",batchKey:i?._batchKey,transport:i?.transport};return!this.config.request_batching||i&&(i==null||!i._batchKey)||i!=null&&i.send_instantly?this.Pn(O):this.In.enqueue(O),p}A.critical("This capture call is ignored due to client rate limiting.")}}else A.error("No event name provided to posthog.capture")}else A.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(n=>e(n.event,n)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new Tm(this)}cn(e){this._n.push(e);var n=!0;return()=>{if(n){n=!1;var i=this._n.indexOf(e);i!==-1&&this._n.splice(i,1)}}}calculateEventProperties(e,n,i,r,s){if(i=i||new Date,!this.persistence||!this.sessionPersistence)return n;var o=s?void 0:this.persistence.remove_event_timer(e),a=I({},n);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.gn()&&(a[tf]=!0),e==="$snapshot"){var l=I({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!X(a.distinct_id)&&!ke(a.distinct_id)||Ko(a.distinct_id))&&A.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=(function(b,k,T,x){var F,$,O,L;if(x===void 0&&(x=!1),!Ge)return{};var N,K=b?[...si,...k||[]]:[],V=(function(Dn){for(var qe=0;Ec.length>qe;qe++){var jn=Ec[qe],Mt=jn[1],Lt=jn[0].exec(Dn),ut=Lt&&(je(Mt)?Mt(Lt,Dn):Mt);if(ut)return ut}return["",""]})(Ge),M=V[0],R=V[1],Z=(N=typeof navigator<"u"?navigator:void 0)!=null&&N.brave?{brave:!0}:{},Ce={};C(T)||(Ce.detectGoogleSearchApp=T);var oe={},ye=(F=navigator)==null||(F=F.userAgentData)==null?void 0:F.platform,$e=($=navigator)==null?void 0:$.maxTouchPoints,ae=w==null||(O=w.screen)==null?void 0:O.width,Ie=w==null||(L=w.screen)==null?void 0:L.height,Se=w?.devicePixelRatio;C(ye)||(oe.userAgentDataPlatform=ye),C($e)||(oe.maxTouchPoints=$e),C(ae)||(oe.screenWidth=ae),C(Ie)||(oe.screenHeight=Ie),C(Se)||(oe.devicePixelRatio=Se);var De,wt,ge,Je,bt,mn,Re,Pe,$t=fe(cl({$os:M,$os_version:R,$browser:jd(Ge,navigator.vendor,Z,Ce),$device:Sc(Ge),$device_type:(wt=Ge,ge=oe,Pe=Sc(wt),Pe===Ed||Pe===bd||Pe==="Kobo"||Pe==="Kindle Fire"||Pe===Ld?ti:Pe===Ki||Pe===Qn||Pe===Yi||Pe===Jo?"Console":Pe===xd?"Wearable":Pe?rt:ge?.userAgentDataPlatform==="Android"&&((Je=ge?.maxTouchPoints)!==null&&Je!==void 0?Je:0)>0?600>Math.min((bt=ge?.screenWidth)!==null&&bt!==void 0?bt:0,(mn=ge?.screenHeight)!==null&&mn!==void 0?mn:0)/((Re=ge?.devicePixelRatio)!==null&&Re!==void 0?Re:1)?rt:ti:"Desktop"),$timezone:Pf(),$timezone_offset:sm()}),{$current_url:Xi(x?fn(me?.href):me?.href,K,Qi),$host:me?.host,$pathname:me?.pathname,$raw_user_agent:Ge.length>1e3?Ge.substring(0,997)+"...":Ge,$browser_version:ng(Ge,navigator.vendor,Z,Ce),$browser_language:Vc(),$browser_language_prefix:(De=Vc(),typeof De=="string"?De.split("-")[0]:void 0),$screen_height:w?.screen.height,$screen_width:w?.screen.width,$viewport_height:w?.innerHeight,$viewport_width:w?.innerWidth,$lib:ne.LIB_NAME,$lib_version:ne.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return ne.SDK_DIST_CHANNEL&&($t.$sdk_dist_channel=ne.SDK_DIST_CHANNEL),$t})(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties,this.config.detect_google_search_app,this.config.disable_capture_url_hashes);if(this.sessionManager){var d=this.sessionManager.checkAndGetSessionAndWindowId(s,i.getTime()),f=d.windowId;a.$session_id=d.sessionId,a.$window_id=f}this.sessionPropsManager&&fe(a,this.sessionPropsManager.getSessionProps());try{var h;this.sessionRecording&&fe(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(h=this.Rn)==null?void 0:h.length}catch(b){a.$sdk_debug_error_capturing_properties=String(b)}if(this.requestRouter.region===xa&&(a.$lib_custom_api_host=this.config.api_host),u=e!==Gn||s?e!==_o||s?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(i):this.pageViewManager.doPageView(i,r),a=fe(a,u),e===Gn&&P&&(a.title=P.title),!C(o)){var p=i.getTime()-o;a.$duration=parseFloat((p/1e3).toFixed(3))}Ge&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();ie(["$referrer","$referring_domain"],(b=>{b in g&&delete m[b]}));var v={};if(this._n.length>0)for(var E of this._n.slice())try{fe(v,E())}catch(b){A.error("Failed to produce browser extension event properties",b)}(a=fe({},c,g,m,I({},v,a))).$is_identified=this._isIdentified(),U(this.config.property_denylist)?ie(this.config.property_denylist,(function(b){delete a[b]})):A.error(Yf+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var S=this.config.sanitize_properties;S&&(A.error(su),a=S(a,e));var _=this.Zn();return a.$process_person_profile=_,_&&!s&&this.Gn("_calculate_event_properties"),a}Vn(e,n,i){var r;if(n===void 0&&(n=!0),i===void 0&&(i=!1),!this.persistence||!this.Zn()||this.mn&&!i)return e;var s=this.persistence.get_initial_props(),o=(r=this.sessionPropsManager)==null?void 0:r.getSetOnceProps(),a=fe({},s,o||{},e||{}),l=this.config.sanitize_properties;return l&&(A.error(su),a=l(a,"$set_once")),n&&(this.mn=!0),Kt(a)?void 0:a}register(e,n){var i;(i=this.persistence)==null||i.register(e,n)}register_once(e,n,i){var r;(r=this.persistence)==null||r.register_once(e,n,i)}register_for_session(e){var n;(n=this.sessionPersistence)==null||n.register(e),Object.keys(e).forEach((i=>this.yn.add(i))),this.Qn()}unregister(e){var n;(n=this.persistence)==null||n.unregister(e)}unregister_for_session(e){var n;(n=this.sessionPersistence)==null||n.unregister(e),this.yn.delete(e),this.Qn()}Kn(e,n){this.register({[e]:n})}An(){this.yn.forEach((e=>{var n;(n=this.sessionPersistence)==null||n.unregister(e)})),this.yn.clear(),this.Qn()}Qn(){var e;if(this.bn)if(this.config.persistence==="memory"||(e=this.sessionPersistence)!=null&&e.xi||!be.N())be.q(this.bn);else{var n=[];this.yn.forEach((i=>n.push(i))),n.length>0?be.F(this.bn,n):be.q(this.bn)}}getFeatureFlag(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlag(e,n)}getFeatureFlagPayload(e){var n;return(n=this.featureFlags)==null?void 0:n.getFeatureFlagPayload(e)}getFeatureFlagResult(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlagResult(e,n)}getAllFeatureFlags(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.getAllFeatureFlags())!==null&&e!==void 0?e:[]}isFeatureEnabled(e,n){var i,r;return(i=(r=this.featureFlags)==null?void 0:r.isFeatureEnabled(e,n))!==null&&i!==void 0?i:n?.defaultValue}reloadFeatureFlags(){var e;(e=this.featureFlags)==null||e.reloadFeatureFlags()}updateFlags(e,n,i){var r;(r=this.featureFlags)==null||r.updateFlags(e,n,i)}updateEarlyAccessFeatureEnrollment(e,n,i){var r;(r=this.featureFlags)==null||r.updateEarlyAccessFeatureEnrollment(e,n,i)}getEarlyAccessFeatures(e,n,i){var r;return n===void 0&&(n=!1),(r=this.featureFlags)==null?void 0:r.getEarlyAccessFeatures(e,n,i)}on(e,n){return this.dn.on(e,n)}onFeatureFlags(e){return this.featureFlags?this.featureFlags.onFeatureFlags(e):(e([],{},{errorsLoading:!0}),()=>{})}onSurveysLoaded(e){return this.surveys?this.surveys.onSurveysLoaded(e):(e([],{isLoaded:!1,error:Ii}),()=>{})}onSessionId(e){var n,i;return(n=(i=this.sessionManager)==null?void 0:i.onSessionId(e))!==null&&n!==void 0?n:()=>{}}getSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getSurveys(e,n):e([],{isLoaded:!1,error:Ii})}getActiveMatchingSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,n):e([],{isLoaded:!1,error:Ii})}renderSurvey(e,n){var i;(i=this.surveys)==null||i.renderSurvey(e,n)}displaySurvey(e,n){var i;n===void 0&&(n=km),(i=this.surveys)==null||i.displaySurvey(e,n)}cancelPendingSurvey(e){var n;(n=this.surveys)==null||n.cancelPendingSurvey(e)}canRenderSurvey(e){var n,i;return(n=(i=this.surveys)==null?void 0:i.canRenderSurvey(e))!==null&&n!==void 0?n:{visible:!1,disabledReason:Ii}}canRenderSurveyAsync(e,n){var i,r;return n===void 0&&(n=!1),(i=(r=this.surveys)==null?void 0:r.canRenderSurveyAsync(e,n))!==null&&i!==void 0?i:Promise.resolve({visible:!1,disabledReason:Ii})}Jn(e){return!e||Ko(e)?(A.critical("Unique user id has not been set in posthog.identify"),!1):e===mr?(A.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.'),!1):!["distinct_id","distinctid"].includes(e.toLowerCase())&&!["undefined","null"].includes(e.toLowerCase())||(A.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.'),!1)}identify(e,n,i){if(!this.__loaded||!this.persistence)return A.uninitializedWarning("posthog.identify");if(ke(e)&&(e=e.toString(),A.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.Jn(e)&&this.Gn("posthog.identify")){var r=this.get_distinct_id();this.register({$user_id:e}),this.get_property(Ji)||this.register_once({$had_persisted_distinct_id:!0,$device_id:r},""),e!==r&&e!==this.get_property(Ri)&&(this.unregister(Ri),this.register({distinct_id:e}));var s,o=(this.persistence.get_property(at)||Hn)===Hn,a=e!==r,l=!a&&o;if(a&&o)this.persistence.set_property(at,vn),this.setPersonPropertiesForFlags({$set:n||{},$set_once:i||{}},!1),this.capture(yo,{distinct_id:e,$anon_distinct_id:r},{$set:n||{},$set_once:i||{}}),this.Sn=Fo(e,n,i),(s=this.featureFlags)==null||s.setAnonymousDistinctId(r);else if(l){this.persistence.set_property(at,vn);var u=n||{},c=i||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=Fo(e,n,i)}else(n||i)&&this.setPersonProperties(n,i);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Cn)):l&&(n||i)&&this.reloadFeatureFlags()}}setPersonProperties(e,n){if((e||n)&&this.Gn("posthog.setPersonProperties")){var i=Fo(this.get_distinct_id(),e,n);this.Sn!==i?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:n||{}},!0),this.capture("$set",{$set:e||{},$set_once:n||{}}),this.Sn=i):A.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}unsetPersonProperties(e){var n,i=(U(e)?e:[e]).filter((r=>X(r)&&r.length>0));i.length!==0&&this.Gn("posthog.unsetPersonProperties")&&((n=this.featureFlags)==null||n.unsetPersonPropertiesForFlags(i,!0),this.capture("$set",{$unset:i}),this.Sn=null)}group(e,n,i){if(e&&n){var r=this.getGroups(),s=r[e]!==n;if(s&&this.resetGroupPropertiesForFlags(e),this.register({$groups:I({},r,{[e]:n})}),s||i){var o={$group_type:e,$group_key:n};i&&(o.$group_set=i),this.capture(Fc,o)}i&&this.setGroupPropertiesForFlags({[e]:i}),s&&!i&&this.reloadFeatureFlags()}else A.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),(i=this.featureFlags)==null||i.setPersonPropertiesForFlags(e,n)}resetPersonPropertiesForFlags(e){var n;e===void 0&&(e=!0),(n=this.featureFlags)==null||n.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((i=this.featureFlags)==null||i.setGroupPropertiesForFlags(e,n))}resetGroupPropertiesForFlags(e){var n;(n=this.featureFlags)==null||n.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,n){var i,r,s,o,a,l,u,c,d,f;if(n===void 0&&(n=!1),A.info("reset"),!this.__loaded)return A.uninitializedWarning("posthog.reset");var h,p=this.get_property(Ji),g=this.get_property(vo),m=this.get_property(An),v=this.is_capturing();if(this.consent.reset(),n||!v||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after."),(i=this.persistence)==null||i.clear(),(r=this.sessionPersistence)==null||r.clear(),this.yn.clear(),this.Qn(),C(m)||(h=this.persistence)==null||h.register({[An]:m}),(s=this.surveys)==null||s.reset(),(o=this.Un)==null||o.stop(),(a=this.featureFlags)==null||a.reset(),(l=this.conversations)==null||l.reset(),(u=this.logs)==null||u.reset(),(c=this.metrics)==null||c.reset(),(d=this.persistence)==null||d.set_property(at,Hn),(f=this.sessionManager)==null||f.resetSessionId(),this.Sn=null,this.config.cookieless_mode===Wt)this.register_once({distinct_id:mr,$device_id:null},"");else{var E=this.config.get_device_id(Ht());this.register_once({distinct_id:E,$device_id:e?E:p},""),e||C(g)||this.register({[vo]:g})}this.register({$last_posthog_reset:new Date().toISOString()},1),delete this.config.identity_distinct_id,delete this.config.identity_hash,this.reloadFeatureFlags()}shutdown(e){var n=this;return se((function*(){var i,r,s,o,a,l,u;if(n.__loaded){(i=n.Un)==null||i.stop(),(r=n.jn)==null||r.dispose(),(s=n.sessionRecording)==null||s.dispose(),(o=n.logs)==null||o.flushLogs("sendBeacon"),(a=n.metrics)==null||a.flush("sendBeacon"),(l=n.In)==null||l.unload(),(u=n.Rn)==null||u.unload();try{var c;(c=n.featureFlags)==null||c.destroy()}catch(d){A.error("Error while destroying feature flags",d)}}else A.uninitializedWarning("posthog.shutdown")}))()}setIdentity(e,n){var i;this.config.identity_distinct_id=e,this.config.identity_hash=n,this.alias(e),(i=this.conversations)==null||i.Xn()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,(e=this.conversations)==null||e.ts()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,n;return(e=(n=this.sessionManager)==null?void 0:n.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var n=this.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.sessionStartTimestamp,r=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+n.sessionId);if(e!=null&&e.withTimestamp&&i){var s,o=(s=e.timestampLookBack)!==null&&s!==void 0?s:10;if(!i)return r;r+="?t="+Math.max(Math.floor((new Date().getTime()-i)/1e3)-o,0)}return r}alias(e,n){return e===this.get_property(Yd)?(A.critical("Attempting to create alias for existing People user - aborting."),-2):this.Gn("posthog.alias")?(C(n)&&(n=this.get_distinct_id()),e!==n?(this.Kn(Ri,e),this.capture("$create_alias",{alias:e,distinct_id:n})):(A.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var n=I({},this.config);if(he(e)){var i,r,s,o,a,l,u,c,d,f,h,p;fe(this.config,ou(e));var g=this.En();(i=this.persistence)==null||i.update_config(this.config,n,g),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new xo(I({},this.config,{persistence:"sessionStorage"}),g,!1);var m=this.Cn(this.config.debug);mt(m)&&(this.config.debug=m),mt(this.config.debug)&&(this.config.debug?(ne.DEBUG=!0,le.N()&&le.F("ph_debug",!0),A.info("set_config",{config:e,oldConfig:n,newConfig:I({},this.config)})):(ne.DEBUG=!1,le.N()&&le.q("ph_debug"))),(r=this.featureFlags)==null||r.updateConfig==null||r.updateConfig(this.config,this.Qi()),(s=this.exceptionObserver)==null||s.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(f=this.deadClicksAutocapture)==null||f.startIfEnabledOrStop(),(h=this.surveys)==null||h.loadIfEnabled(),this.es(),(p=this.externalIntegrations)==null||p.startIfEnabledOrStop()}}_overrideSDKInfo(e,n){ne.LIB_NAME=e,ne.LIB_VERSION=n}startSessionRecording(e){var n,i,r,s,o,a=e===!0,l={sampling:a||!(e==null||!e.sampling),linked_flag:a||!(e==null||!e.linked_flag),url_trigger:a||!(e==null||!e.url_trigger),event_trigger:a||!(e==null||!e.event_trigger)};Object.values(l).some(Boolean)&&((n=this.sessionManager)==null||n.checkAndGetSessionAndWindowId(),l.sampling&&((i=this.sessionRecording)==null||i.overrideSampling()),l.linked_flag&&((r=this.sessionRecording)==null||r.overrideLinkedFlag()),l.url_trigger&&((s=this.sessionRecording)==null||s.overrideTrigger("url")),l.event_trigger&&((o=this.sessionRecording)==null||o.overrideTrigger("event"))),this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,n){if(this.exceptions){var i=new Error("PostHog syntheticException"),r=this.exceptions.buildProperties(e,{handled:!0,syntheticException:i});return this.exceptions.sendExceptionEvent(I({},r,n))}}addExceptionStep(e,n){var i;(i=this.exceptions)==null||i.addExceptionStep(e,n)}captureLog(e){var n;(n=this.logs)==null||n.captureLog(e)}get logger(){var e,n;return(e=(n=this.logs)==null?void 0:n.logger)!==null&&e!==void 0?e:Ze.rs}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var n,i;return(n=(i=this.toolbar)==null?void 0:i.loadToolbar(e))!==null&&n!==void 0&&n}get_property(e){var n;return(n=this.persistence)==null?void 0:n.props[e]}getSessionProperty(e){var n;return(n=this.sessionPersistence)==null?void 0:n.props[e]}toString(){var e,n=(e=this.config.name)!==null&&e!==void 0?e:Kn;return n!==Kn&&(n=Kn+"."+n),n}_isIdentified(){var e,n;return((e=this.persistence)==null?void 0:e.get_property(at))===vn||((n=this.sessionPersistence)==null?void 0:n.get_property(at))===vn}Zn(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles===pa&&!this._isIdentified()&&Kt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[Ri])&&((n=this.persistence)==null||(n=n.props)==null||!n[es]))}zn(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Zn()||this.Gn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.Gn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}Gn(e){return this.config.person_profiles==="never"?(A.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Kn(es,!0),!0)}En(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut();return this.config.disable_persistence||e&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!==kn)}es(){var e,n,i,r,s=this.En();return((e=this.persistence)==null?void 0:e.xi)!==s&&((i=this.persistence)==null||i.set_disabled(s)),((n=this.sessionPersistence)==null?void 0:n.xi)!==s&&((r=this.sessionPersistence)==null||r.set_disabled(s)),s&&(this.yn.clear(),this.Qn()),s}opt_in_capturing(e){var n;if(this.config.cookieless_mode!==Wt){if(this.gn()){var i,r,s,o,a;this.Yn(!0,!0),(i=this.sessionManager)==null||i.destroy(),(r=this.pageViewManager)==null||r.destroy(),this.sessionManager=new tu(this),this.pageViewManager=new qc(this),this.persistence&&(this.sessionPropsManager=new eu(this,this.sessionManager,this.persistence));var l,u=(s=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&s!==void 0?s:(a=Ze.__defaultExtensionClasses)==null?void 0:a.sessionRecording;u&&(this.sessionRecording=this.pn(this.sessionRecording,new u(this)),this.hn&&((l=this.sessionRecording)==null||l.onRemoteConfig==null||l.onRemoteConfig(this.hn)))}var c,d;this.consent.optInOut(!0),this.es(),this.Bn(),(n=this.sessionRecording)==null||n.startIfEnabledOrStop(),this.config.cookieless_mode==kn&&((c=this.surveys)==null||c.loadIfEnabled()),(C(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((d=e?.captureEventName)!==null&&d!==void 0?d:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hn()}else A.warn(ru)}opt_out_capturing(){var e,n,i;this.config.cookieless_mode!==Wt?(this.config.cookieless_mode===kn&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===kn&&(this.register({distinct_id:mr,$device_id:null}),(e=this.sessionRecording)==null||e.stopRecording(),this.sessionRecording=void 0,(n=this.sessionManager)==null||n.destroy(),(i=this.pageViewManager)==null||i.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.Hn(),this.Bn())):A.warn(ru)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===Wt||(this.config.cookieless_mode===kn?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return He?Hf(He,this.config.custom_blocked_useragents):void 0}Hn(){P&&(P.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(Gn,{title:P.title},{send_instantly:!0}),this.kn&&(P.removeEventListener(ts,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),ve(P,ts,this.kn)))}debug(e){e===!1?(w?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(w?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}Qi(){var e=this.Mn||{};return"advanced_disable_flags"in e?!!e.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(A.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(function(n,i,r,s,o){var a=i in n&&!H(n[i]),l=r in n&&!H(n[r]);return a?n[i]:!!l&&(o&&o.warn("Config field '"+r+"' is deprecated. Please use '"+i+"' instead. The old field will be removed in a future major version."),n[r])})(e,"advanced_disable_flags","advanced_disable_decide",0,A)}Pt(e){var n;if(H(this.config.before_send))return e;var i=Object.keys((n=e.properties)!==null&&n!==void 0?n:{}).filter(zp),r=U(this.config.before_send)?this.config.before_send:[this.config.before_send],s=e;for(var o of r){if(s=o(s),H(s)){var a="Event '"+e.event+"' was rejected in beforeSend function";return Wp(e.event)?A.warn(a+". This can cause unexpected behavior."):A.info(a),null}s.properties&&!Kt(s.properties)||A.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}for(var l of i)if(s.properties&&H(s.properties[l]))return A.warn("Event '"+e.event+"' had its '"+l+"' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped."),null;return s}getPageViewId(){var e;return(e=this.pageViewManager.ui)==null?void 0:e.pageViewId}captureTraceFeedback(e,n){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:n})}captureTraceMetric(e,n,i){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:n,$ai_metric_value:String(i)})}Cn(e){var n=mt(e)&&!e,i=le.N()&&le.P("ph_debug")==="true";return!n&&(!!i||e)}}Ze.__defaultExtensionClasses={},Ze.rs=(()=>{var t=()=>{};return{trace:t,debug:t,info:t,warn:t,error:t,fatal:t}})(),(function(t,e){for(var n=0;e.length>n;n++)t.prototype[e[n]]=Tg(t.prototype[e[n]])})(Ze,["identify"]);class au{constructor(e){this.disabled=e===!1;var n=he(e)?e:{};this.thresholdPx=n.threshold_px||30,this.timeoutMs=n.timeout_ms||1e3,this.clickCount=n.click_count||3,this.clicks=[]}isRageClick(e,n,i){if(this.disabled)return!1;var r=this.clicks[this.clicks.length-1];if(r&&Math.abs(e-r.x)+Math.abs(n-r.y)i-r.timestamp){if(this.clicks.push({x:e,y:n,timestamp:i}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:n,timestamp:i}];return!1}}var $o="$copy_autocapture",Mo=pe("[AutoCapture]");function Lo(t,e){return e.length>t?e.slice(0,t)+"...":e}function Nm(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!hn(e));return e}function Om(t,e){var n,i,r=e.e,s=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!hn(t))return{props:{}};for(var c=[t],d=new Set([t]),f=t;f.parentNode&&!et(f,"body")&&ff>c.length;)if(df(f.parentNode)){var h=f.parentNode.host;if(d.has(h))break;d.add(h),c.push(h),f=h}else{if(!hn(f.parentNode)||d.has(f.parentNode))break;d.add(f.parentNode),c.push(f.parentNode),f=f.parentNode}var p,g,m=[],v={},E=!1,S=!1;if(ie(c,(x=>{var F=va(x);if(et(x,"a")){var $=x.getAttribute("href");E=!!(F&&$&&Hi($))&&(u?fn($):$)}j(rs(x),"ph-no-capture")&&(S=!0),m.push((function(L,N,K,V,M){M===void 0&&(M=!1);var R=L.tagName.toLowerCase(),Z={tag_name:R};dl.indexOf(R)>-1&&!K&&(Z.$el_text=R.toLowerCase()==="a"||R.toLowerCase()==="button"?Lo(1024,Hc(L)):Lo(1024,Zi(L)));var Ce=rs(L);Ce.length>0&&(Z.classes=Ce.filter((function(ae){return ae!==""}))),ie(L.attributes,(function(ae){var Ie;if((!vf(L)||["name","id","class","aria-label"].indexOf(ae.name)!==-1)&&(V==null||!V.includes(ae.name))&&!N&&Hi(ae.value)&&(!X(Ie=ae.name)||Ie.substring(0,10)!=="_ngcontent"&&Ie.substring(0,7)!=="_nghost")){var Se=ae.value;ae.name==="class"&&(Se=ul(Se).join(" ")),Z["attr__"+ae.name]=Lo(1024,ae.name==="href"&&M?fn(Se):Se)}}));for(var oe=1,ye=1,$e=L;$e=Nm($e);)oe++,$e.tagName===L.tagName&&ye++;return Z.nth_child=oe,Z.nth_of_type=ye,Z})(x,s,o,a,u));var O=(function(L){if(!va(L))return{};var N={};return ie(L.attributes,(function(K){if(K.name&&K.name.indexOf("data-ph-capture-attribute")===0){var V=K.name.replace("data-ph-capture-attribute-",""),M=K.value;V&&M&&Hi(M)&&(N[V]=M)}})),N})(x);fe(v,O)})),S)return{props:{},explicitNoCapture:S};if(o||(m[0].$el_text=et(t,"a")||et(t,"button")?Hc(t):Zi(t)),E){var _,b;m[0].attr__href=E;var k=(_=ss(E))==null?void 0:_.host,T=w==null||(b=w.location)==null?void 0:b.host;k&&T&&k!==T&&(p=E)}return{props:fe({$event_type:r.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(x){return x.map((F=>{var $,O,L="";if(F.tag_name&&(L+=F.tag_name),F.attr_class)for(var N of(F.attr_class.sort(),F.attr_class))L+="."+N.replace(/"/g,"");var K=I({},F.text?{text:F.text}:{},{"nth-child":($=F.nth_child)!==null&&$!==void 0?$:0,"nth-of-type":(O=F.nth_of_type)!==null&&O!==void 0?O:0},F.href?{href:F.href}:{},F.attr_id?{attr_id:F.attr_id}:{},F.attributes),V={};return $r(K).sort(((M,R)=>M[0].localeCompare(R[0]))).forEach((M=>{var R=M[1];return V[Wc(M[0].toString())]=Wc(R.toString())})),(L+=":")+$r(V).map((M=>M[0]+'="'+M[1]+'"')).join("")})).join(";")})((function(x){return x.map((F=>{var $,O,L={text:($=F.$el_text)==null?void 0:$.slice(0,400),tag_name:F.tag_name,href:(O=F.attr__href)==null?void 0:O.slice(0,2048),attr_class:Zg(F),attr_id:F.attr__id,nth_child:F.nth_child,nth_of_type:F.nth_of_type,attributes:{}};return $r(F).filter((N=>N[0].indexOf("attr__")===0)).forEach((N=>L.attributes[N[0]]=N[1])),L}))})(g)))},(n=m[0])!=null&&n.$el_text?{$el_text:(i=m[0])==null?void 0:i.$el_text}:{},p&&r.type==="click"?{$external_click_url:p}:{},v)}}var ki=pe("[ExceptionAutocapture]"),lu=()=>{},Bm=pe("[TracingHeaders]"),wn=pe("[Web Vitals]"),cu=9e5,uu="disabled",du="lazy_loading",Ci="awaiting_config",Sr="missing_config";pe("[SessionRecording]"),pe("[SessionRecording]");var Ia="[SessionRecording]",Bt=pe(Ia),Dm=pe("[Heatmaps]");function No(t){return he(t)&&"clientX"in t&&"clientY"in t&&ke(t.clientX)&&ke(t.clientY)}var xr=pe("[Product Tours]"),Oo=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(ol))},jm=["$set_once","$set"],Et=pe("[SiteApps]"),fu="Error while initializing PostHog app with config id ";function qn(t,e,n){if(H(t))return!1;switch(n){case"exact":return t===e;case"contains":var i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(i,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}class Um{constructor(e){this.ns=new gl,this.ss=(n,i)=>this.os(n,i)&&this.ls(n,i)&&this.us(n,i)&&this.hs(n,i),this.os=(n,i)=>i==null||!i.event||n?.event===i?.event,this._instance=e,this.ds=new Set,this.vs=new Set}init(){var e,n;C((e=this._instance)==null?void 0:e._addCaptureHook)||(n=this._instance)==null||n._addCaptureHook(((i,r)=>{this.on(i,r)}))}register(e){var n,i;if(!C((n=this._instance)==null?void 0:n._addCaptureHook)&&(e.forEach((o=>{var a,l;(a=this.vs)==null||a.add(o),(l=o.steps)==null||l.forEach((u=>{var c;(c=this.ds)==null||c.add(u?.event||"")}))})),(i=this._instance)!=null&&i.autocapture)){var r,s=new Set;e.forEach((o=>{var a;(a=o.steps)==null||a.forEach((l=>{l!=null&&l.selector&&s.add(l?.selector)}))})),(r=this._instance)==null||r.autocapture.setElementSelectors(s)}}on(e,n){var i;n!=null&&e.length!=0&&(this.ds.has(e)||this.ds.has(n.event))&&this.vs&&((i=this.vs)==null?void 0:i.size)>0&&this.vs.forEach((r=>{this.cs(n,r)&&this.ns.emit("actionCaptured",r.name)}))}fs(e){this.onAction("actionCaptured",(n=>e(n)))}cs(e,n){if(n?.steps==null)return!1;for(var i of n.steps)if(this.ss(e,i))return!0;return!1}onAction(e,n){return this.ns.on(e,n)}ls(e,n){if(n!=null&&n.url){var i,r=e==null||(i=e.properties)==null?void 0:i.$current_url;if(!r||typeof r!="string"||!qn(r,n.url,n.url_matching||"contains"))return!1}return!0}us(e,n){return!!this.ps(e,n)&&!!this.gs(e,n)&&!!this.ys(e,n)}ps(e,n){var i;if(n==null||!n.href)return!0;var r=this.bs(e);if(r.length>0)return r.some((a=>qn(a.href,n.href,n.href_matching||"exact")));var s,o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!o&&qn((s=o.match(/(?::|")href="(.*?)"/))?s[1]:"",n.href,n.href_matching||"exact")}gs(e,n){var i;if(n==null||!n.text)return!0;var r=this.bs(e);if(r.length>0)return r.some((u=>qn(u.text,n.text,n.text_matching||"exact")||qn(u.$el_text,n.text,n.text_matching||"exact")));var s,o,a,l=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!l&&(s=(function(u){for(var c,d=[],f=/(?::|")text="(.*?)"/g;!H(c=f.exec(u));)d.includes(c[1])||d.push(c[1]);return d})(l),o=n.text,a=n.text_matching||"exact",s.some((u=>qn(u,o,a))))}ys(e,n){var i,r;if(n==null||!n.selector)return!0;var s=e==null||(i=e.properties)==null?void 0:i.$element_selectors;if(s!=null&&s.includes(n.selector))return!0;var o=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";if(n.selector_regex&&o)try{return new RegExp(n.selector_regex).test(o)}catch{return!1}return!1}bs(e){var n;return(e==null||(n=e.properties)==null?void 0:n.$elements)==null?[]:e?.properties.$elements}hs(e,n){return n==null||!n.properties||n.properties.length===0||qf(n.properties.reduce(((i,r)=>{var s=U(r.value)?r.value.map(String):r.value!=null?[String(r.value)]:[];return i[r.key]={values:s,operator:r.operator||"exact"},i}),{}),e?.properties)}}class Hm{constructor(e){var n;this._s=[],this._instance=e,this.ws=new Map,this.ks=new Map,this.xs=new Map,(n=this._instance)==null||n.onSessionId==null||n.onSessionId((i=>this.Ss(i)))}Cs(e){return!1}Ms(){return null}Ts(e){}Es(){}Is(e,n){return!!e&&qf(e.propertyFilters,n?.properties)}Ps(e,n){var i=new Map;return e.forEach((r=>{var s;(s=r.conditions)==null||(s=s[n])==null||(s=s.values)==null||s.forEach((o=>{if(o!=null&&o.name){var a=i.get(o.name)||[];a.push(r.id),i.set(o.name,a)}}))})),i}Rs(e,n,i){var r=(i===bi.Activation?this.ws:this.ks).get(e),s=[];return this.As((o=>{s=o.filter((a=>r?.includes(a.id)))})),s.filter((o=>{var a,l=(a=o.conditions)==null||(a=a[i])==null||(a=a.values)==null?void 0:a.find((u=>u.name===e));return this.Is(l,n)}))}register(e){var n;C((n=this._instance)==null?void 0:n._addCaptureHook)||(this.Fs(e),this.Ls(e))}Ls(e){var n=e.filter((i=>{var r,s;return((r=i.conditions)==null?void 0:r.actions)&&((s=i.conditions)==null||(s=s.actions)==null||(s=s.values)==null?void 0:s.length)>0}));n.length!==0&&(this.Os==null&&(this.Os=new Um(this._instance),this.Os.init(),this.Os.fs((i=>{this.onAction(i)}))),n.forEach((i=>{var r,s,o,a,l;i.conditions&&(r=i.conditions)!=null&&r.actions&&(s=i.conditions)!=null&&(s=s.actions)!=null&&s.values&&((o=i.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.Os)==null||a.register(i.conditions.actions.values),(l=i.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var c=this.xs.get(u.name);c&&c.push(i.id),this.xs.set(u.name,c||[i.id])}})))})))}Fs(e){var n,i=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.events)&&((a=s.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0})),r=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.cancelEvents)&&((a=s.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0}));i.length===0&&r.length===0||((n=this._instance)==null||n._addCaptureHook(((s,o)=>{this.onEvent(s,o)})),this.ws=this.Ps(e,bi.Activation),this.ks=this.Ps(e,bi.Cancellation))}onEvent(e,n){var i,r,s=this.Ds(),o=(n==null||(i=n.properties)==null?void 0:i.$survey_id)||(n==null||(r=n.properties)==null?void 0:r.$product_tour_id);if(o&&this.getActivatedIds().includes(o)){var a=this.$s(e,o);if(a==="consume")return s.info("event consumed activated item, removing it",{event:e,itemId:o}),void this.Ns([o]);if(a==="persist")return s.info("shown item promoted to persisted activation",{event:e,itemId:o}),this.qs(o),void this.js([o])}if(this.ks.has(e)){var l=this.Rs(e,n,bi.Cancellation);l.length>0&&(s.info("cancel event matched, cancelling items",{event:e,itemsToCancel:l.map((c=>c.id))}),this.Ns(l.map((c=>c.id))),l.forEach((c=>this.Bs(c.id))))}if(this.ws.has(e)){s.info("event name matched",{event:e,eventPayload:n,items:this.ws.get(e)});var u=this.Rs(e,n,bi.Activation);this.Hs(u.map((c=>c.id)))}}onAction(e){this.xs.has(e)&&this.Hs(this.xs.get(e)||[])}Hs(e){var n;if(e.length!==0){var i=!((n=this._instance)==null||n.get_session_id==null||!n.get_session_id()),r=[];for(var s of e)i&&this.Cs(s)?this.qs(s)&&this.Us(s):r.push(s);r.length>0&&(this._s=[...new Set([...this._s,...r])]),this.Ds().info("updating activated items",{activatedItems:this.getActivatedIds()})}}qs(e){this._s=this._s.filter((i=>i!==e));var n=this.zs();return!n.includes(e)&&(this.Ws([...n,e]),this.Vs(),!0)}Ns(e){var n=new Set(e);this._s=this._s.filter((s=>!n.has(s)));var i=this.Zs(),r=i.filter((s=>!n.has(s)));r.length!==i.length&&(this.Ws(r),r.length===0&&this.Gs()),this.js(e)}Qs(){var e,n=this.Ms();if(!n)return{};var i=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n];return i&&typeof i=="object"?i:{}}Us(e){if(this.Ms()){var n=this.Qs();this.Ts(I({},n,{[e]:Date.now()}))}}js(e){if(this.Ms()){var n=this.Qs(),i={},r=!1;for(var s of Object.entries(n)){var o=s[0],a=s[1];e.includes(o)?r=!0:i[o]=a}r&&(Kt(i)?this.Es():this.Ts(i))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var n=this.Qs()[e];return ke(n)?n:void 0}}Zs(){var e,n=this.Js();return((e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n])||[]}zs(){var e,n,i=this.Zs();if(i.length===0)return[];var r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[this.Ys()],s=(n=this._instance)==null||n.get_session_id==null?void 0:n.get_session_id();return s&&r===s?i:[]}Vs(){var e,n=(e=this._instance)==null||e.get_session_id==null?void 0:e.get_session_id();n&&this.Xs(n)}Gs(){this.ta()}Ss(e){var n,i=(n=this._instance)==null||(n=n.persistence)==null?void 0:n.props[this.Ys()];if(i&&i!==e){var r=this.Zs(),s=this.Qs();r.length>0&&(this.Ws([]),r.filter((o=>ke(s[o]))).forEach((o=>this.Bs(o)))),this.Gs(),this.Ks()}}getActivatedIds(){return[...new Set([...this.zs(),...this._s])].filter((e=>!this.ea(e)))}reset(){this._s=[],this.Zs().length>0&&this.Ws([]),this.Gs(),this.Ks()}getEventToItemsMap(){return this.ws}ia(){return this.Os}}class Wm extends Hm{constructor(e){super(e)}Js(){return ca}Ys(){return Fr}Ms(){return Rr}Ts(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Rr]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Rr)}Cs(e){var n,i;this.As((s=>{i=s.find((o=>o.id===e))}));var r=(n=i)==null||(n=n.appearance)==null?void 0:n.surveyPopupDelaySeconds;return ke(r)&&r>0}ra(){return qt.SHOWN}As(e){var n;(n=this._instance)==null||n.getSurveys(e)}Bs(e){var n;(n=this._instance)==null||n.cancelPendingSurvey(e)}Ds(){return Q}Ws(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[ca]:e})}Xs(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Fr]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Fr)}ea(){return!1}$s(e,n){var i;this.As((s=>{i=s.find((o=>o.id===n))}));var r=!i||(function(s){var o;return Vf(s)&&!((o=s.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||s.schedule==="always"})(i);return r?e===qt.SHOWN?"consume":"ignore":e===qt.SHOWN?"persist":e===qt.DISMISSED||e===qt.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var Ir="SDK is not enabled or survey functionality is not yet loaded",hu="Disabled. Not loading surveys.",zm=w!=null&&w.location?os(w.location.hash,"__posthog")||os(location.hash,"state"):null,pu="_postHogToolbarParams",gu=pe("[Toolbar]"),mu=pe("[FeatureFlags]");class qm{constructor(e,n){n===void 0&&(n=!1),this.na=!1,this.update(e,n)}update(e,n){this.sa=((i,r)=>{var s,o,a,l;return{bootstrap:{featureFlags:(s=i.bootstrap)==null?void 0:s.featureFlags,featureFlagPayloads:(o=i.bootstrap)==null?void 0:o.featureFlagPayloads},remoteRequestsDisabled:r,featureFlagsDisabled:!!i.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!i.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!i.advanced_feature_flags_dedup_per_session,cacheTtlMs:i.feature_flag_cache_ttl_ms,requestTimeoutMs:i.feature_flag_request_timeout_ms,compression:i.disable_compression?"none":"base64",evaluationContexts:(a=(l=i.evaluation_contexts)!==null&&l!==void 0?l:i.evaluation_environments)!==null&&a!==void 0?a:[],flagKeys:U(i.flag_keys)?i.flag_keys:void 0}})(e,n),!e.evaluation_environments||e.evaluation_contexts||this.na||(mu.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.na=!0),C(e.flag_keys)||U(e.flag_keys)||mu.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var vu=pe("[FeatureFlags]"),bn=pe("[FeatureFlags]",{debugEnabled:!0}),Bo=`" failed. Feature flags didn't load in time.`,_u="connection_error",yu=t=>{for(var e={},n=0;t.length>n;n++)e[t[n]]=!0;return e},wu=t=>{var e={};for(var n of $r(t||{})){var i=n[1];i&&(e[n[0]]=i)}return e},St=pe("[Error tracking]"),bu="Refusing to render web experiment since the viewer is a likely bot",Vm={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>cs(e,t),not_regex:(t,e)=>!cs(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class Me{get Ne(){return this._instance.config}constructor(e){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(i){i===void 0&&(i=!1),n.getWebExperiments((r=>{Me.aa("retrieved web experiments from the server"),n.oa=new Map,r.forEach((s=>{if(s.feature_flag_key){var o;n.oa&&(Me.aa("setting flag key ",s.feature_flag_key," to web experiment ",s),(o=n.oa)==null||o.set(s.feature_flag_key,s));var a=n._instance.getFeatureFlag(s.feature_flag_key);X(a)&&s.variants[a]&&n.la(s.name,a,s.variants[a].transforms)}else if(s.variants)for(var l in s.variants){var u=s.variants[l];Me.ua(u,n._instance)&&n.la(s.name,l,u.transforms)}}))}),i)},this._instance=e,this._instance.onFeatureFlags((i=>{this.onFeatureFlags(i)}))}initialize(){}onFeatureFlags(e){if(this._is_bot())Me.aa(bu);else if(!this.Ne.disable_web_experiments){if(H(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();Me.aa("applying feature flags",e),e.forEach((n=>{var i;if(this.oa&&(i=this.oa)!=null&&i.has(n)){var r,s=this._instance.getFeatureFlag(n),o=(r=this.oa)==null?void 0:r.get(n);s&&o!=null&&o.variants[s]&&this.la(o.name,s,o.variants[s].transforms)}}))}}previewWebExperiment(){var e=Me.getWindowLocation();if(e!=null&&e.search){var n=ri(e?.search,"__experiment_id"),i=ri(e?.search,"__experiment_variant");n&&i&&(Me.aa("previewing web experiments "+n+" && "+i),this.getWebExperiments((r=>{this.ha(parseInt(n),i,r)}),!1,!0))}}loadIfEnabled(){this.Ne.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,n,i){if(this.Ne.disable_web_experiments&&!i)return e([]);var r=this._instance.get_property("$web_experiments");if(r&&!n)return e(r);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this.Ne.token),method:"GET",timestampMode:"query",callback:s=>e(s.statusCode===200&&s.json&&s.json.experiments||[])})}ha(e,n,i){var r=i.filter((s=>s.id===e));r&&r.length>0&&(Me.aa("Previewing web experiment ["+r[0].name+"] with variant ["+n+"]"),this.la(r[0].name,n,r[0].variants[n].transforms))}static ua(e,n){return!H(e.conditions)&&Me.da(e,n)&&Me.va(e)}static da(e,n){var i;if(H(e.conditions)||H((i=e.conditions)==null?void 0:i.url))return!0;var r=Me.getWindowLocation();if(r){var s,o,a,l=lf(n,r.href);return(s=e.conditions)==null||!s.url||Vm[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return w?.location}static va(e){var n;if(H(e.conditions)||H((n=e.conditions)==null?void 0:n.utm))return!0;var i=Sf();if(i.utm_source){var r,s,o,a,l,u,c,d,f=(r=e.conditions)==null||(r=r.utm)==null||!r.utm_campaign||((s=e.conditions)==null||(s=s.utm)==null?void 0:s.utm_campaign)==i.utm_campaign,h=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==i.utm_source,p=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==i.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==i.utm_term;return f&&p&&g&&h}return!1}static aa(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;n>r;r++)i[r-1]=arguments[r];A.info("[WebExperiments] "+e,i)}la(e,n,i){this._is_bot()?Me.aa(bu):n!=="control"?i.forEach((r=>{if(r.selector){var s;Me.aa("applying transform of variant "+n+" for experiment "+e+" ",r);var o=(s=document)==null?void 0:s.querySelectorAll(r.selector);o?.forEach((a=>{var l=a;r.html&&(l.innerHTML=r.html),r.css&&l.setAttribute("style",r.css)}))}})):Me.aa("Control variants leave the page unmodified.")}_is_bot(){return He&&this._instance?Hf(He,this.Ne.custom_blocked_useragents):void 0}}var ot=pe("[Conversations]"),En="Conversations not available yet.",Eu="console",Zf="__posthogHandledLogsRequestError",Do=(t,e)=>{var n=t instanceof Error?t:new Error(e);return n[Zf]=!0,n},Su=t=>!!t&&typeof t=="object"&&t[Zf]===!0,Cs={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=vu,this.fa={},this.pa={},this.ga=[],this.ma=!1,this.ya=!1,this.ba=0,this._a=!1,this.wa=!1,this.ka=!1,this.xa=!1,this.Sa=0,this.Ca=()=>{var e=this.Ma();this.Sa=0,e&&this.reloadFeatureFlags()},"get"in t?this.Ta=t:(this.Ea=new qm(t.config,t.Qi()),this.Ta=this.Ea)}updateConfig(t,e){var n;(n=this.Ea)==null||n.update(t,e)}setup(t){return this.Ia=t,this.rt=t.logger.createLogger("[FeatureFlags]"),n=()=>{this.Ia===t&&(this.Ia=void 0,this.nn=t,this.Pa(t))},(e=t.kv.initialize())!=null&&e.then?e.then(n):n();var e,n}Pa(t){if(this.nn===t)return w&&ve(w,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){w?.removeEventListener("online",this.Ca)}dispose(){var t;this.ba++,this.wa=!1,this.Ia=void 0,this.nn&&(this.La(),(t=this.Ra)==null||t.dispose(),this.Ra=void 0,this.ga=[],w?.removeEventListener("online",this.Ca),this.nn=void 0)}get Ne(){return this.Ta.get()}Oa(t){var e;return(e=this.nn)==null?void 0:e.kv.get(t)}F(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.set(t)}))}q(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.remove(t)}))}Da(t){try{t()}catch(e){this.rt.error("Failed to update feature flag persistence",e)}}Fa(){var t={};for(var e of[$i,Mi,Pr,It]){var n=this.Oa(e);C(n)||(t[e]=n)}this.fa=t;var i=I({},t),r=this.Oa(Sn);if(r)for(var s of Object.entries(r))i["$feature/"+s[0]]=s[1];this.pa=i}Aa(){var t=this.Ne.cacheTtlMs;if(!t||0>=t)return!1;var e=this.Oa(Ui);return typeof e!="number"||Date.now()-e>t}$a(){return!!this.Aa()&&(this.xa||this.ya||(this.xa=!0,this.rt.warn("Feature flag cache is stale, triggering refresh..."),this.reloadFeatureFlags()),!0)}Na(){var t=this.Ne.evaluationContexts;return t!=null&&t.length?t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid evaluation context found:",e,"Expected non-empty string"),n})):[]}qa(){var t=this.Ne.flagKeys;if(!C(t))return t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid flag key found:",e,"Expected non-empty string"),n}))}initialize(){var t,e,n=this.Ne,i=(t=(e=n.bootstrap)==null?void 0:e.featureFlags)!==null&&t!==void 0?t:{};if(Object.keys(i).length){var r,s,o=(r=(s=n.bootstrap)==null?void 0:s.featureFlagPayloads)!==null&&r!==void 0?r:{},a=Object.keys(i).filter((u=>!!i[u])).reduce(((u,c)=>(u[c]=i[c]||!1,u)),{}),l=Object.keys(o).filter((u=>a[u])).reduce(((u,c)=>(o[c]&&(u[c]=o[c]),u)),{});return this.ja({featureFlags:a,featureFlagPayloads:l})}}updateFlags(t,e,n){var i,r,s=n!=null&&n.merge&&(i=this.Oa(Sn))!==null&&i!==void 0?i:{},o=n!=null&&n.merge&&(r=this.Oa(Mi))!==null&&r!==void 0?r:{},a=I({},s,t),l=I({},o,e),u={};for(var c of Object.entries(a)){var d=c[0],f=c[1];u[d]={key:d,enabled:gc(f),variant:mc(f),reason:void 0,metadata:C(l?.[d])?void 0:{id:0,version:void 0,description:void 0,payload:l[d]}}}this.ja({flags:u})}get hasLoadedFlags(){return this.ma}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var t=this.Oa(aa),e=this.Oa(It),n=this.Oa(xn);if(!n&&!e)return t||{};var i=fe({},t||{}),r=[...new Set([...Object.keys(n||{}),...Object.keys(e||{})])];for(var s of r){var o,a,l=i[s],u=e?.[s],c=C(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=C(u)?l?.variant:typeof u=="string"?u:void 0,f=n?.[s],h=I({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(h.original_enabled=l?.enabled),d!==l?.variant&&(h.original_variant=l?.variant),f&&(h.metadata=I({},l?.metadata,{payload:f,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),i[s]=h}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:n,finalDetails:i}),this.ca=!0),i}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((n=>{var i=t[n];return{key:n,enabled:gc(i),variant:mc(i),payload:pc(e[n])}}))}getFlagVariants(){var t=this.Oa(Sn),e=this.Oa(It);if(!e)return t||{};for(var n=fe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:e,finalFlags:n}),this.ca=!0),n}getFlagPayloads(){var t=this.Oa(Mi),e=this.Oa(xn);if(!e)return t||{};for(var n=fe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flag payloads!",{flagPayloads:t,overriddenPayloads:e,finalPayloads:n}),this.ca=!0),n}reloadFeatureFlags(){this._a||this.Ne.featureFlagsDisabled||this.Ma()||this.Ba||(this.ga.slice().forEach((t=>{try{t()}catch(e){this.rt.error("Error while running feature flags reloading callback",e)}})),this.Ba=setTimeout((()=>{this.Ha()}),5))}La(){clearTimeout(this.Ba),this.Ba=void 0}onReloading(t){return this.ga.push(t),()=>{this.ga=this.ga.filter((e=>e!==t))}}ensureFlagsLoaded(){this.ma||this.ya||this.Ba||this.reloadFeatureFlags()}setAnonymousDistinctId(t){this.$anon_distinct_id=t}setReloadingPaused(t){this._a=t}resetFlagCallReported(){this.q(Cn)}Ha(t){this.La();var e=this.nn;if(e&&!this.Ne.remoteRequestsDisabled&&!this.Ma())if(this.ya)this.wa=!0;else{var n={token:e.projectToken,distinct_id:e.distinctId,groups:e.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:I({},e.initialPersonProperties,this.Oa(jt)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(In),timezone:Pf()};C(e.deviceId)||(n.$device_id=e.deviceId),(t!=null&&t.disableFlags||this.Ne.featureFlagsDisabled)&&(n.disable_flags=!0);var i=this.Na();i.length&&(n.evaluation_contexts=i);var r=this.qa();C(r)||(n.flag_keys=r);var s=this.Ne.onlyEvaluateSurveyFeatureFlags,o="/flags/?v=2"+(s?"&only_evaluate_survey_feature_flags=true":""),a=this.ba;this.ya=!0;var l=()=>{this.wa&&(this.wa=!1,this.Ha())},u=c=>{this.ya=!1,a===this.ba&&(this.F({[Tr]:[_u]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:n,compression:this.Ne.compression==="base64"?Ue.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,f,h=(d=c.json)!==null&&d!==void 0?d:{},p=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),p||this.wa||(this.$anon_distinct_id=void 0),!n.disable_flags||this.wa){this.ka=!p;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?_u:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),h.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((f=h.quotaLimited)==null||!f.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[Tr]:g}),m?this.rt.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more."):n.disable_flags||this.ja(h,p,{partialResponse:s}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return bf(this.Sa,3)}Ua(t){this.Sa=Ef(t,this.Sa,3,(()=>this.rt.warn("Feature flag requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped refreshing feature flags; will try again when connectivity changes.")))}getFeatureFlag(t,e){var n;if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var i=this.getFeatureFlagResult(t,e);return(n=i?.variant)!==null&&n!==void 0?n:i?.enabled}}else this.rt.warn('getFeatureFlag for key "'+t+Bo)}getFeatureFlagDetails(t){return this.getFlagsWithDetails()[t]}getFeatureFlagPayload(t){var e=this.getFeatureFlagResult(t,{send_event:!1});return e?.payload}getFeatureFlagResult(t,e){if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var n,i=this.getFlagVariants(),r=t in i,s=i[t],o=this.getFlagPayloads()[t],a=String(s),l=this.Oa(Pr)||void 0,u=this.Oa(Ui)||void 0,c=this.Oa(Cn)||{};if(this.Ne.deduplicateCallsPerSession){var d,f=(d=this.nn)==null?void 0:d.session.sessionId,h=this.Oa(Ni);f&&f!==h&&(c={},n=f)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))n&&this.F({[Cn]:c,[Ni]:n});else{var p,g,m,v,E,S,_,b,k,T;U(c[t])?c[t].push(a):c[t]=[a],this.F(I({[Cn]:c},n?{[Ni]:n}:{}));var x=this.getFeatureFlagDetails(t),F=[...(p=this.Oa(Tr))!==null&&p!==void 0?p:[]];C(s)&&F.push("flag_missing");var $={$feature_flag:t,$feature_flag_response:s,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((g=this.Ne.bootstrap)==null||(g=g.featureFlags)==null?void 0:g[t])||null,$feature_flag_bootstrapped_payload:((m=this.Ne.bootstrap)==null||(m=m.featureFlagPayloads)==null?void 0:m[t])||null,$used_bootstrap_value:!this.ka};C(x==null||(v=x.metadata)==null?void 0:v.has_experiment)||($.$feature_flag_has_experiment=x.metadata.has_experiment),C(x==null||(E=x.metadata)==null?void 0:E.version)||($.$feature_flag_version=x.metadata.version);var O,L=(S=x==null||(_=x.reason)==null?void 0:_.description)!==null&&S!==void 0?S:x==null||(b=x.reason)==null?void 0:b.code;L&&($.$feature_flag_reason=L),x!=null&&(k=x.metadata)!=null&&k.id&&($.$feature_flag_id=x.metadata.id),C(x?.original_variant)&&C(x?.original_enabled)||($.$feature_flag_original_response=C(x.original_variant)?x.original_enabled:x.original_variant),x!=null&&(T=x.metadata)!=null&&T.original_payload&&($.$feature_flag_original_payload=x==null||(O=x.metadata)==null?void 0:O.original_payload),F.length&&($.$feature_flag_error=F.join(",")),this.za($)}else n&&this.F({[Cn]:c,[Ni]:n});if(r)return{key:t,enabled:!!s,variant:typeof s=="string"?s:void 0,payload:pc(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+Bo)}za(t){try{var e;(e=this.nn)==null||e.capture("$feature_flag_called",t).catch((n=>{this.rt.error("Failed to capture feature flag call",n)}))}catch(n){this.rt.error("Failed to capture feature flag call",n)}}getRemoteConfigPayload(t,e){this.Wa(t,e)}Wa(t,e){var n=this;return se((function*(){var i=n.nn;if(i){var r={distinct_id:i.distinctId,token:i.projectToken,person_properties:{$lib:i.library.name,$lib_version:i.library.version}},s=n.Na();s.length&&(r.evaluation_contexts=s);var o,a=n.qa();C(a)||(r.flag_keys=a);try{var l,u=(l=(yield i.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:r,compression:n.Ne.compression==="base64"?Ue.Base64:void 0,sentAt:"body",timeoutMs:n.Ne.requestTimeoutMs})).json)==null?void 0:l.featureFlagPayloads;o=u?.[t]||void 0}catch(c){return void n.rt.error("Remote config feature flag request failed",c)}try{e(o)}catch(c){n.rt.error("Remote config feature flag callback failed",c)}}}))()}isFeatureEnabled(t,e){if(e===void 0&&(e={}),e.fresh&&!this.ka)return e.defaultValue;if(!(this.ma||this.getFlags()&&this.getFlags().length>0))return this.rt.warn('isFeatureEnabled for key "'+t+Bo),e.defaultValue;var n=this.getFeatureFlag(t,e);return C(n)?e.defaultValue:!!n}addFeatureFlagsHandler(t){this.featureFlagEventHandlers.push(t)}removeFeatureFlagsHandler(t){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((e=>e!==t))}receivedFeatureFlags(t,e,n){this.ja(t,e,n)}ja(t,e,n){if(this.nn){this.ma=!0;var i=(function(r,s,o,a,l,u){s===void 0&&(s={}),o===void 0&&(o={}),a===void 0&&(a={}),u===void 0&&(u=vu);var c=((k,T)=>{var x=k.flags;return x?I({},k,{featureFlags:Object.fromEntries(Object.keys(x).map((F=>{var $;return[F,($=x[F].variant)!==null&&$!==void 0?$:x[F].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(x).filter((F=>x[F].enabled)).filter((F=>{var $;return($=x[F].metadata)==null?void 0:$.payload})).map((F=>{var $;return[F,($=x[F].metadata)==null?void 0:$.payload]})))}):(k.featureFlags&&T.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),k)})(r,u),d=c.flags,f=c.featureFlags,h=c.featureFlagPayloads;if(f){var p=r.requestId,g=r.evaluatedAt;if(U(f)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(f)for(var v=0;f.length>v;v++)m[f[v]]=!0;return{[$i]:f,[Sn]:m,[Zr]:!1}}var E=f,S=h,_=d;if(l!=null&&l.partialResponse)E=I({},s,E),S=I({},o,S),_=I({},a,_);else if(r.errorsWhileComputingFlags)if(d){var b=new Set(Object.keys(d).filter((k=>{var T;return!((T=d[k])!=null&&T.failed)})));E=I({},s,Object.fromEntries(Object.entries(E).filter((k=>b.has(k[0]))))),S=I({},o,Object.fromEntries(Object.entries(S||{}).filter((k=>b.has(k[0]))))),_=I({},a,Object.fromEntries(Object.entries(_||{}).filter((k=>b.has(k[0])))))}else E=I({},s,E),S=I({},o,S),_=I({},a,_);return I({[$i]:Object.keys(wu(E)),[Sn]:E||{},[Mi]:S||{},[aa]:_||{},[Zr]:r.minimalFlagCalledEvents===!0},p?{[Pr]:p}:{},g?{[Ui]:g}:{})}})(t,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),n,this.rt);i&&this.F(i),e||(this.xa=!1),this.Va(e)}}override(t,e){e===void 0&&(e=!1),this.rt.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:t,suppressWarning:e})}overrideFeatureFlags(t){this.Za(t)}Za(t){if(this.nn){if(t===!1)return this.q([It,xn]),this.Va(),void bn.info("All overrides cleared");if(U(t))return this.F({[It]:yu(t)}),this.Va(),void bn.info("Flag overrides set",{flags:t});if(t&&typeof t=="object"&&("flags"in t||"payloads"in t)){var e,n=t;this.ca=!!((e=n.suppressWarning)!==null&&e!==void 0&&e);var i={},r=n.flags,s=n.payloads;return r&&(i[It]=U(r)?yu(r):r),s&&(i[xn]=s),Object.keys(i).length&&this.F(i),r===!1&&s===!1?this.q([It,xn]):r===!1?this.q(It):s===!1&&this.q(xn),this.Va(),r===!1?bn.info("Flag overrides cleared"):r&&bn.info("Flag overrides set",{flags:r}),void(s===!1?bn.info("Payload overrides cleared"):s&&bn.info("Payload overrides set",{payloads:s}))}if(t&&typeof t=="object")return this.F({[It]:t}),this.Va(),void bn.info("Flag overrides set",{flags:t});this.rt.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:t})}else this.rt.warn("posthog.featureFlags.overrideFeatureFlags called before feature flags were ready")}onFeatureFlags(t){if(this.addFeatureFlagsHandler(t),this.ma){var e=this.Ga(),n=e.flags,i=e.flagVariants;try{t(n,i)}catch(r){this.rt.error("Error while running feature flags callback",r)}}return()=>this.removeFeatureFlagsHandler(t)}updateEarlyAccessFeatureEnrollment(t,e,n){var i=(this.Oa(Ar)||[]).find((l=>l.flagKey===t)),r={["$feature_enrollment/"+t]:e},s={$feature_flag:t,$feature_enrollment:e,$set:r};i&&(s.$early_access_feature_name=i.name),n&&(s.$feature_enrollment_stage=n);var o=I({},this.getFlagVariants(),{[t]:e});this.F({[$i]:Object.keys(wu(o)),[Sn]:o,[jt]:I({},this.Oa(jt)||{},r)}),this.Va();try{var a;(a=this.nn)==null||a.capture("$feature_enrollment_update",s).catch((l=>{this.rt.error("Failed to capture early access feature enrollment",l)}))}catch(l){this.rt.error("Failed to capture early access feature enrollment",l)}}getEarlyAccessFeatures(t,e,n){e===void 0&&(e=!1);var i=this.Oa(Ar);!i||e?this.Qa(t,n):t(i)}Qa(t,e){var n=this;return se((function*(){var i=n.nn;if(i){var r,s=e?"&"+e.map((a=>"stage="+a)).join("&"):"";try{var o=yield i.sendRequest("/api/early_access_features/?token="+i.projectToken+s,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;n.F({[Ar]:r=o.json.earlyAccessFeatures})}catch(a){return void n.rt.error("Early access feature request failed",a)}try{t(r)}catch(a){n.rt.error("Early access feature callback failed",a)}}}))()}Ga(){var t=this.getFlags(),e=this.getFlagVariants();return{flags:t.filter((n=>e[n])),flagVariants:Object.keys(e).filter((n=>e[n])).reduce(((n,i)=>(n[i]=e[i],n)),{})}}Va(t){this.Fa();var e=this.Ga(),n=e.flags,i=e.flagVariants;this.featureFlagEventHandlers.forEach((r=>{try{r(n,i,{errorsLoading:t})}catch(s){this.rt.error("Error while running feature flags callback",s)}}))}setPersonPropertiesForFlags(t,e){e===void 0&&(e=!0),this.Ka(t,e)}Ka(t,e){e===void 0&&(e=!0);var n=this.Oa(jt)||{},i=t?.$set||(t!=null&&t.$set_once?{}:t),r=t?.$set_once,s={};if(r)for(var o in r)({}).hasOwnProperty.call(r,o)&&(o in n||(s[o]=r[o]));this.F({[jt]:I({},n,s,i)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=I({},this.Oa(jt)||{});t.forEach((i=>{delete n[i]})),this.F({[jt]:n}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(jt),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=this.Oa(In)||{},i=I({},n);for(var r of Object.keys(t))i[r]=I({},n[r],t[r]);this.F({[In]:i}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(In)||{};this.F({[In]:I({},e,{[t]:{}})})}else this.q(In)}reset(){this.ba++,this.wa=!1,this.Fa(),this.ma=!1,this._a=!1,this.ka=!1,this.$anon_distinct_id=void 0,this.La(),this.ca=!1,this.Sa=0}}},Gm={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===Ci||this.Ya===Sr?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=uu,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(P==null||!P.visibilityState||P.visibilityState==="visible")return!0;var n=w==null||(e=w.performance)==null||e.getEntriesByType==null?void 0:e.getEntriesByType("visibility-state");return!(n!=null&&n.length)||n.some((i=>i.name==="visible"))})(),this.Ie=()=>{var e;P?.visibilityState==="visible"&&(this.io=!0,(e=this.Ja)==null||e.setDocumentWasEverVisible==null||e.setDocumentWasEverVisible(!0))},this._instance=t,!this._instance.sessionManager)throw Bt.error("started without valid sessionManager"),new Error(Ia+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===Wt)throw new Error(Ia+' cannot be used with cookieless_mode="always"');P!=null&&P.addEventListener&&ve(P,"visibilitychange",this.Ie)}initialize(){this.startIfEnabledOrStop()}dispose(){this.eo=!0,P==null||P.removeEventListener==null||P.removeEventListener("visibilitychange",this.Ie),this.stopRecording()}get ro(){var t,e=!((t=this._instance.get_property(An))==null||!t.enabled),n=!this.Ne.disable_session_recording,i=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return w&&e&&n&&!i}startIfEnabledOrStop(t){var e;if(!(this.eo||this.ro&&(e=this.Ja)!=null&&e.isStarted)){var n=!C(Object.assign)&&!C(Array.from);this.ro&&n?(this.no(t),Bt.info("starting")):(this.Ya=uu,this.stopRecording())}}no(t){var e,n,i;this.ro&&(this.Ya!==Ci&&this.Ya!==Sr&&(this.Ya=du),B!=null&&(e=B.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(n=B.__PosthogExtensions__)!=null&&n.initSessionRecording?this.so(t):(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,this.ao,(r=>{if(r)return Bt.error("could not load recorder",r);this.so(t)})))}stopRecording(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.stop()}oo(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.discard()}lo(){var t,e;(t=this.Mr)==null||t.unregister(al),(e=this.Mr)==null||e.unregister(Jd)}uo(t,e){if(H(t))return null;var n,i=ke(t)?t:parseFloat(t);return typeof(n=i)!="number"||!Number.isFinite(n)||0>n||n>1?(Bt.warn(e+" must be between 0 and 1. Ignoring invalid value:",t),null):i}ho(t){if(this.Mr){var e,n,i=this.Mr,r=()=>{var s,o=t.sessionRecording===!1?void 0:t.sessionRecording,a=this.uo((s=this.Ne.session_recording)==null?void 0:s.sampleRate,"session_recording.sampleRate"),l=this.uo(o?.sampleRate,"remote config sampleRate"),u=a??l;H(u)&&this.lo();var c=o?.minimumDurationMilliseconds;i.register({[An]:I({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:I({capturePerformance:t.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:u,minimumDurationMilliseconds:C(c)?null:c,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers,version:o?.version,triggerGroups:o?.triggerGroups})})};r(),(e=this.Xa)==null||e.call(this),this.Xa=(n=this._instance.sessionManager)==null?void 0:n.onSessionId(r)}}onRemoteConfig(t){var e=t.ok?t.config:void 0;return e&&"sessionRecording"in e?e.sessionRecording===!1?(this.ho(e),void this.oo()):(this.ho(e),void this.startIfEnabledOrStop()):(this.Ya===Ci&&(this.Ya=Sr,Bt.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(t,e){var n;e===void 0&&(e="log"),(n=this.Ja)!=null&&n.log?this.Ja.log(t,e):Bt.warn("log called before recorder was ready")}get ao(){var t,e,n=(t=this._instance)==null||(t=t.persistence)==null?void 0:t.get_property(An);return(n==null||(e=n.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(An);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(n){return Bt.warn("persisted remote config for session recording is invalid and will be ignored",n),!1}return!H(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,n,i;if(!this.eo){if((e=B.__PosthogExtensions__)==null||!e.initSessionRecording)return Bt.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[sf]:!0});var r;if(this.Ja||(this.Ja=(r=B.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===Sr||this.Ya===Ci?void 0:(this.Ya=Ci,Bt.info("persisted remote config is stale, requesting fresh config before starting"),void new Ff(this._instance).load());this.Ya=du,(n=(i=this.Ja).setDocumentWasEverVisible)==null||n.call(i,this.io),this.Ja.start(t)}}onRRwebEmit(t){var e;(e=this.Ja)==null||e.onRRwebEmit==null||e.onRRwebEmit(t)}overrideLinkedFlag(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Xd]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Zd]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,n;this.Ja||(n=this.Mr)==null||n.register({[t==="url"?Qd:ef]:!0}),(e=this.Ja)==null||e.overrideTrigger(t)}get sdkDebugProperties(){var t;return((t=this.Ja)==null?void 0:t.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(t,e){var n;return!((n=this.Ja)==null||!n.tryAddCustomEvent(t,e))}}},Km={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new au(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,n=he(this.instance.config.autocapture)?this.instance.config.autocapture:{};return n.url_allowlist=(t=n.url_allowlist)==null?void 0:t.map((i=>new RegExp(i))),n.url_ignorelist=(e=n.url_ignorelist)==null?void 0:e.map((i=>new RegExp(i))),n}yo(){if(this.isBrowserSupported()){if(w&&P){var t=n=>{n=n||w?.event;try{this.bo(n)}catch(i){Mo.error("Failed to capture event",i)}};if(ve(P,"submit",t,{capture:!0}),ve(P,"change",t,{capture:!0}),ve(P,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=n=>{n=n||w?.event;try{this.bo(n,$o)}catch(i){Mo.error("Failed to capture copy/cut event",i)}};ve(P,"copy",e,{capture:!0}),ve(P,"cut",e,{capture:!0})}}}else Mo.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.vo&&(this.yo(),this.vo=!0)}onRemoteConfig(t){if(this.fo=!0,t.ok){var e=t.config;e.elementsChainAsString&&(this.po=e.elementsChainAsString);var n=e.autocapture_opt_out;mt(n)&&(this.instance.persistence&&this.instance.persistence.register({[ea]:n}),this.co=n),this.startIfEnabled()}else this.startIfEnabled()}setElementSelectors(t){this.mo=t}getElementSelectors(t){var e,n=[];return(e=this.mo)==null||e.forEach((i=>{var r=P?.querySelectorAll(i);r?.forEach((s=>{t===s&&n.push(i)}))})),n}get isEnabled(){var t,e,n=(t=this.instance.persistence)==null?void 0:t.props[ea],i=this.co,r=this.instance.Qi()&&!this.fo;if(Ye(i)&&!mt(n)&&!r)return!1;var s=(e=this.co)!==null&&e!==void 0?e:!!n;return!!this.instance.config.autocapture&&!s}bo(t,e){if(e===void 0&&(e="$autocapture"),this.isEnabled){var n,i=bo(t);uf(i)&&(i=i.parentNode||null),e==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&this.instance.config.rageclick&&(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,t.timeStamp||new Date().getTime())&&Oc(i,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var r=e===$o;if(i&&(function(d,f,h,p,g,m){var v;if(!w||fl(d)||h!=null&&h.url_allowlist&&!Mc(h.url_allowlist,m)||h!=null&&h.url_ignorelist&&Mc(h.url_ignorelist,m))return!1;if(h!=null&&h.dom_event_allowlist){var E=h.dom_event_allowlist;if(E&&!E.some((x=>f.type===x)))return!1}var S=mf(d,p),_=S.parentIsUsefulElement,b=S.targetElementList;if(!(function(x,F){var $=F?.element_allowlist;if(C($))return!0;var O,L=function(K){if($.some((V=>K.tagName.toLowerCase()===V)))return{v:!0}};for(var N of x)if(O=L(N))return O.v;return!1})(b,h)||!ma(b,h?.css_selector_allowlist)||ma(b,(v=h?.css_selector_ignorelist)!==null&&v!==void 0?v:qg))return!1;try{var k=w.getComputedStyle(d);if(k&&k.getPropertyValue("cursor")==="pointer"&&f.type==="click")return!0}catch{}var T=d.tagName.toLowerCase();switch(T){case"html":return!1;case"form":return(g||["submit"]).indexOf(f.type)>=0;case"input":case"select":case"textarea":return(g||["change","click"]).indexOf(f.type)>=0;default:return _?(g||["click"]).indexOf(f.type)>=0:(g||["click"]).indexOf(f.type)>=0&&(dl.indexOf(T)>-1||d.getAttribute("contenteditable")==="true")}})(i,t,this.Ne,r,r?["copy","cut"]:void 0,this.instance)){var s=Om(i,{e:t,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.Ne.element_attribute_ignorelist,elementsChainAsString:this.po,disableCaptureUrlHashes:this.instance.config.disable_capture_url_hashes}),o=s.props;if(s.explicitNoCapture)return!1;var a=this.getElementSelectors(i);if(a&&a.length>0&&(o.$element_selectors=a),e===$o){var l,u=hf(w==null||(l=w.getSelection())==null?void 0:l.toString()),c=t.type||"clipboard";if(!u)return!1;o.$selected_content=u,o.$copy_type=c}return this.instance.capture(e,o),!0}}}isBrowserSupported(){return je(P?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(w==null||(e=w.location)==null?void 0:e.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(A.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.wo&&this.wo(),this.wo=void 0,A.info("History API monitoring stopped")}monitorHistoryChanges(){w&&w.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(w&&((e=w.history[t])==null||!e.__posthog_wrapped__)){var n=this;(function(i,r,s){try{if(!(r in i))return lu;var o={next:i[r]},a=s((function(){for(var l=arguments.length,u=new Array(l),c=0;l>c;c++)u[c]=arguments[c];return o.next.apply(this,u)}));return je(a)&&(a.prototype=a.prototype||{},Object.defineProperties(a,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:o}})),i[r]=a,()=>{if(i[r]!==a)for(var l=i[r];je(l)&&l.__posthog_layer__;){var u=l.__posthog_layer__;if(u.next===a)return void(u.next=o.next);l=u.next}else i[r]=o.next}}catch{return lu}})(w.history,t,(i=>function(r,s,o){i.call(this,r,s,o),n.So(t)}))}}So(t){try{var e,n=w==null||(e=w.location)==null?void 0:e.pathname;if(!n)return;n!==this._o&&this.isEnabled&&this._instance.capture(Gn,{navigation_type:t}),this._o=n}catch(i){A.error("Error capturing "+t+" pageview",i)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};ve(w,"popstate",t),this.wo=()=>{w&&w.removeEventListener("popstate",t)}}}},heatmaps:class{get Ne(){return this.instance.config}constructor(t){var e;this.Co=!1,this.vo=!1,this.Mo=null,this.instance=t,this.Co=!((e=this.instance.persistence)==null||!e.props[ta]),this.rageclicks=new au(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return he(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return H(this.Ne.capture_heatmaps)?H(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;Dm.info("starting..."),this.To(),this.Ie()}else{var t;clearInterval((t=this.Mo)!==null&&t!==void 0?t:void 0),this.Eo(),this.getAndClearBuffer()}}onRemoteConfig(t){if(t.ok){var e=t.config;if("heatmaps"in e){var n=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[ta]:n}),this.Co=n,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){No(t.originalEvent)&&this.ke(t.originalEvent,"deadclick")}Ie(){this.Mo&&clearInterval(this.Mo),this.Mo=P?.visibilityState==="visible"?setInterval(this.cr.bind(this),this.flushIntervalMilliseconds):null}To(){w&&P&&(this.Po=this.cr.bind(this),ve(w,ns,this.Po),this.Ro=t=>this.ke(t||w?.event),ve(P,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||w?.event),ve(P,"mousemove",this.Ao,{capture:!0}),this.Lo=new zc(this.instance,Xg,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),ve(P,ts,this.Oo),this.vo=!0)}Eo(){var t;w&&P&&(this.Po&&w.removeEventListener(ns,this.Po),this.Ro&&P.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&P.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&P.removeEventListener(ts,this.Oo),clearTimeout(this.Do),(t=this.Lo)==null||t.stop(),this.vo=!1)}$o(t,e){var n=this.instance.scrollManager.scrollY(),i=this.instance.scrollManager.scrollX(),r=this.instance.scrollManager.scrollElement(),s=(function(o,a,l){for(var u=o;u&&hn(u)&&!et(u,"body");){if(u===l)return!1;var c=void 0;try{var d,f,h;c=(d=(f=(h=u.ownerDocument)==null?void 0:h.defaultView)!==null&&f!==void 0?f:w)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(j(a,c))return!0;u=pf(u)}return!1})(bo(t),["fixed","sticky"],r);return{x:t.clientX+(s?0:i),y:t.clientY+(s?0:n),target_fixed:s,type:e}}ke(t,e){var n;if(e===void 0&&(e="click"),!$c(t.target)&&No(t)){var i=this.$o(t,e);(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,new Date().getTime())&&Oc(bo(t),this.instance.config.rageclick)&&this.Vt(I({},i,{type:"rageclick"})),this.Vt(i)}}Fo(t){!$c(t.target)&&No(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(w){var e=this.Ne.disable_capture_url_hashes?fn(w.location.href):w.location.href,n=this.Ne.custom_personal_data_properties,i=this.Ne.mask_personal_data_properties?[...si,...n||[]]:[],r=Xi(e,i,Qi);this.R=this.R||{},this.R[r]||(this.R[r]=[]),this.R[r].push(t)}}cr(){this.R&&!Kt(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:zc,webVitalsAutocapture:class{constructor(t){var e;this.Co=!1,this.vo=!1,this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this.No=()=>{clearTimeout(this.qo),this.qo=void 0,this.R.metrics.length!==0&&(this._instance.capture("$web_vitals",I({$current_url:this.R.url},this.R.metrics.reduce(((n,i)=>I({},n,{["$web_vitals_"+i.name+"_event"]:I({},i),["$web_vitals_"+i.name+"_value"]:i.value})),{}))),this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.jo=n=>{var i;if(this.R=this.R||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},H(n?.name)||H(n?.value))wn.error("Invalid metric received",n);else{var r=typeof n.navigationURL=="string"?n.navigationURL:void 0,s=this.Bo(r);if(!C(s)){var o=ke(n.navigationId)||typeof n.navigationId=="string"?"navigation:"+n.navigationId:"url:"+s;if(!this.Ho||this.Ho>n.value){this.R.navigationKey!==o&&(this.No(),this.qo=setTimeout(this.No,this.flushToCaptureTimeoutMs)),C(this.R.navigationKey)&&(this.R.navigationKey=o,this.R.url=s),this.R.firstMetricTimestamp=C(this.R.firstMetricTimestamp)?Date.now():this.R.firstMetricTimestamp,n.attribution&&n.attribution.interactionTargetElement&&(n.attribution.interactionTargetElement=void 0);var a=(i=this._instance.sessionManager)==null?void 0:i.checkAndGetSessionAndWindowId(!0),l=I({},n,r?{navigationURL:s}:{},{$current_url:s,timestamp:Date.now()});C(a)||(l.$session_id=a.sessionId,l.$window_id=a.windowId),this.R.metrics.push(l),this.R.metrics.length===this.allowedMetrics.length&&this.No()}else wn.error("Ignoring metric with value >= "+this.Ho,n)}}},this.Uo=()=>{if(!this.vo){var n,i,r,s,o=B.__PosthogExtensions__,a=o?.postHogWebVitalsCallbacksByFlavor,l=a?.[this.zo]||(this.zo==="web-vitals"&&C(a)?o?.postHogWebVitalsCallbacks:void 0);if(C(l)||(n=l.onLCP,i=l.onCLS,r=l.onFCP,s=l.onINP),n&&i&&r&&s){var u={reportSoftNavs:this.useSoftNavs};this.allowedMetrics.indexOf("LCP")>-1&&n(this.jo.bind(this),u),this.allowedMetrics.indexOf("CLS")>-1&&i(this.jo.bind(this),u),this.allowedMetrics.indexOf("FCP")>-1&&r(this.jo.bind(this),u),this.allowedMetrics.indexOf("INP")>-1&&s(this.jo.bind(this),u),this.vo=!0}else wn.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[sa]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,n=he(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return H(n)?((e=this._instance.persistence)==null?void 0:e.props[oa])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(he(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=he(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=he(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=he(this.Wo)&&ke(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:cu;return t>0&&6e4>=t?cu:t}get isEnabled(){var t=me?.protocol;if(t!=="http:"&&t!=="https:")return wn.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=he(this.Wo)?this.Wo.web_vitals:mt(this.Wo)?this.Wo:void 0;return mt(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(wn.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var n=he(e.capturePerformance)&&!!e.capturePerformance.web_vitals,i=he(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[sa]:n}),this._instance.persistence.register({[oa]:i})),this.Co=n,this.startIfEnabled()}}}get zo(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}ai(t){var e=B.__PosthogExtensions__,n=this.zo,i=e?.postHogWebVitalsCallbacksByFlavor;i!=null&&i[n]||n==="web-vitals"&&C(i)&&e!=null&&e.postHogWebVitalsCallbacks?t():e==null||e.loadExternalDependency==null||e.loadExternalDependency(this._instance,n,(r=>{r?wn.error("failed to load script",r):t()}))}Bo(t){var e=t||w?.location.href;if(e){var n=this._instance.config.disable_capture_url_hashes?fn(e):e,i=this._instance.config.custom_personal_data_properties,r=this._instance.config.mask_personal_data_properties?[...si,...i||[]]:[];return Xi(n,r,Qi)}wn.error("Could not determine current URL")}}},Ym={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var n;if(w&&this.isEnabled&&(n=B.__PosthogExtensions__)!=null&&n.errorWrappingFunctions){var i=B.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,r=B.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,s=B.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.Vo&&this.Ne.capture_unhandled_errors&&(this.Vo=i(this.captureException.bind(this))),!this.Zo&&this.Ne.capture_unhandled_rejections&&(this.Zo=r(this.captureException.bind(this))),!this.Go&&this.Ne.capture_console_errors&&(this.Go=s(this.captureException.bind(this)))}catch(o){ki.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[na]),this.Jo=new Gp(I({},(function(n){var i,r,s,o;return n===void 0&&(n={}),{refillRate:(i=(r=n.exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:n.__exceptionRateLimiterRefillRate)!==null&&i!==void 0?i:1,bucketSize:(s=(o=n.exceptionRateLimiterBucketSize)!==null&&o!==void 0?o:n.__exceptionRateLimiterBucketSize)!==null&&s!==void 0?s:10}})(this._instance.config.error_tracking),{refillInterval:1e4,rt:ki})),this.Ne=this.Yo(),this.startIfEnabledOrStop()}Yo(){var t=this._instance.config.capture_exceptions,e={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return he(t)?e=I({},e,t):(C(t)?this.Ko:t)&&(e=I({},e,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),e}get isEnabled(){return this.Ne.capture_console_errors||this.Ne.capture_unhandled_errors||this.Ne.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(ki.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",(i=>{if(i)return ki.error("failed to load script",i);t()}))}Qo(){var t,e,n;(t=this.Vo)==null||t.call(this),this.Vo=void 0,(e=this.Zo)==null||e.call(this),this.Zo=void 0,(n=this.Go)==null||n.call(this),this.Go=void 0}onRemoteConfig(t){if(t.ok){var e=t.config;"autocaptureExceptions"in e&&(this.Ko=!!e.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[na]:this.Ko}),this.Ne=this.Yo(),this.startIfEnabledOrStop())}}onConfigChange(){this.Ne=this.Yo()}captureException(t){var e,n,i,r=(e=t==null||(n=t.$exception_list)==null||(n=n[0])==null?void 0:n.type)!==null&&e!==void 0?e:"Exception";this.Jo.consumeRateLimit(r)?ki.info("Skipping exception capture because of client rate limiting.",{exception:r}):(i=this._instance.exceptions)==null||i.sendExceptionEvent(t)}},exceptions:class{constructor(t){var e,n;this.Xo=[],this.tl=new ug([new _g,new Cg,new wg,new yg,new Ig,new xg,new Eg,new kg],(function(i){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;r>o;o++)s[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` -`),d=l;c.length>d;d++){var f=c[d];if(1024>=f.length){var h=Pc.test(f)?f.replace(Pc,"$1"):f;if(!h.match(/\S*Error: /)){for(var p of s){var g=p(h,i);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var v=Array.from(m);return v.reverse(),v.slice(0,50).map((E=>{return I({},E,{filename:E.filename||(S=v,S[S.length-1]||{}).filename,function:E.function||ii});var S}))})(u)}})("web:javascript",pg,vg)),this._instance=t,this.Xo=(e=(n=this._instance.persistence)==null?void 0:n.get_property(ia))!==null&&e!==void 0?e:[],this.el=Jr(this.il()),this.rl=new Pg(this.el)}onConfigChange(){this.el=Jr(this.il()),this.rl.setConfig(this.el)}onRemoteConfig(t){var e,n,i;if(t.ok){var r=t.config;if("errorTracking"in r){var s=(e=(n=r.errorTracking)==null?void 0:n.suppressionRules)!==null&&e!==void 0?e:[],o=(i=r.errorTracking)==null?void 0:i.captureExtensionExceptions;this.Xo=s,this._instance.persistence&&this._instance.persistence.register({[ia]:this.Xo,[ra]:o})}}}get nl(){var t,e=!!this._instance.get_property(ra),n=this._instance.config.error_tracking.captureExtensionExceptions;return(t=n??e)!==null&&t!==void 0&&t}buildProperties(t,e){return this.tl.buildFromUnknown(t,{syntheticException:e?.syntheticException,mechanism:{handled:e?.handled}})}addExceptionStep(t,e){if(this.el.enabled)try{if(!X(t)||t.trim().length===0)return void St.warn("Ignoring exception step because message must be a non-empty string");var n=(function(s){if(!s)return{sanitizedProperties:{},droppedKeys:[]};var o=[];return{sanitizedProperties:Object.keys(s).reduce(((a,l)=>Ag.has(l)?(o.push(l),a):(a[l]=s[l],a)),{}),droppedKeys:o}})(this.sl(e)),i=n.sanitizedProperties,r=n.droppedKeys;r.length>0&&St.warn("Ignoring reserved exception step fields",{droppedKeys:r}),this.rl.add(I({[Kr]:t,[Yr]:new Date().toISOString()},i))}catch(s){St.error("Failed to add exception step. Ignoring breadcrumb.",s)}}sendExceptionEvent(t){try{var e=t.$exception_list;if(this.al(e)){if(this.ol(e))return this.ll("Exception dropped: matched a suppression rule"),void St.info("Skipping exception capture because a suppression rule matched");if(!this.nl&&this.ul(e))return this.ll("Exception dropped: thrown by a browser extension"),void St.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.hl(e))return this.ll("Exception dropped: thrown by the PostHog SDK"),void St.info("Skipping exception capture because it was thrown by the PostHog SDK")}var n=this.el.enabled&&H(t.$exception_steps)?this.dl(t):t,i=typeof(s=globalThis._posthogReleaseId)=="string"&&s.length>0?s:void 0;i&&(n.$release_id=i);try{var r=this._instance.capture("$exception",n,{_noTruncate:!0,_batchKey:"exceptionEvent",Wn:!0});return r&&this.rl.clear(),r}catch(o){return St.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void St.error("Failed to process exception event. Ignoring this exception.",o)}var s}dl(t){try{var e=this.rl.getAttachable();return e.length===0?t:I({},t,{$exception_steps:e})}catch(n){return St.error("Failed to read buffered exception steps. Capturing exception without steps.",n),t}}ll(t){this.el.enabled&&this.rl.add({[Kr]:t,[Yr]:new Date().toISOString()})}sl(t){return he(t)?I({},t):{}}il(){var t,e;return(t=(e=this._instance.config.error_tracking)==null?void 0:e.exception_steps)!==null&&t!==void 0?t:{}}ol(t){if(t.length===0)return!1;try{var e=t.reduce(((n,i)=>{var r=i.type,s=i.value;return X(r)&&r.length>0&&n.$exception_types.push(r),X(s)&&s.length>0&&n.$exception_values.push(s),n}),{$exception_types:[],$exception_values:[]});return this.Xo.some((n=>{var i=n.values.map((r=>{var s=zf[r.operator],o=e[r.key];if(!s||!o)return!1;var a=U(r.value)?r.value:[r.value];return a.length>0&&s(a,o)}));return n.type==="OR"?i.some(Boolean):i.every(Boolean)}))}catch(n){return St.warn("Failed to evaluate suppression rules. Capturing the exception.",n),!1}}ul(t){return t.flatMap((e=>{var n,i;return(n=(i=e.stacktrace)==null?void 0:i.frames)!==null&&n!==void 0?n:[]})).some((e=>e.filename&&e.filename.startsWith("chrome-extension://")))}hl(t){if(t.length>0){var e,n,i,r,s=(e=(n=t[0].stacktrace)==null?void 0:n.frames)!==null&&e!==void 0?e:[],o=s[s.length-1];return(i=o==null||(r=o.filename)==null?void 0:r.includes("posthog.com/static"))!==null&&i!==void 0&&i}return!1}al(t){return!H(t)&&U(t)}}},Jm=I({productTours:class{get Mr(){return this._instance.persistence}constructor(t){this.vl=null,this.cl=null,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(t.ok){var e=t.config;if("productTours"in e){var n,i;if(this.Mr&&this.Mr.register({[ol]:!!e.productTours}),!Oo(this._instance))return!this.vl&&H((n=this.Mr)==null?void 0:n.props[Li])||xr.info("product tours disabled; stopping and clearing cached tours"),(i=this.vl)==null||i.stop(),this.vl=null,void this.clearCache();this.loadIfEnabled()}}}loadIfEnabled(){!this.vl&&Oo(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.generateProductTours?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",(i=>{i?xr.error("Could not load product tours script",i):t()}))}fl(){var t;!this.vl&&(t=B.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=B.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(t,e){if(e===void 0&&(e=!1),!U(this.cl)||e){var n=this.Mr;if(n){var i=n.props[Li];if(U(i)&&!e)return this.cl=i,void t(i,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",timestampMode:"query",callback:r=>{if(Oo(this._instance)){var s=r.statusCode;if(s!==200||!r.json){var o="Product Tours API could not be loaded, status: "+s;return s===0?r.error||xr.warn(o):xr.error(o),void t([],{isLoaded:!1,error:o})}var a=U(r.json.product_tours)?r.json.product_tours:[];this.cl=a,n&&n.register({[Li]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){H(this.vl)?t([],{isLoaded:!1,error:"Product tours not loaded"}):this.vl.getActiveProductTours(t)}showProductTour(t){var e;(e=this.vl)==null||e.showTourById(t)}previewTour(t){this.vl?this.vl.previewTour(t):this.ai((()=>{var e;this.fl(),(e=this.vl)==null||e.previewTour(t)}))}dismissProductTour(){var t;(t=this.vl)==null||t.dismissTour("user_clicked_skip")}nextStep(){var t;(t=this.vl)==null||t.nextStep()}previousStep(){var t;(t=this.vl)==null||t.previousStep()}clearCache(){var t;this.cl=null,(t=this.Mr)==null||t.unregister(Li)}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)}}},Cs),Zm={siteApps:class{constructor(t){this.pl=0,this._instance=t,this.gl=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}ml(t,e){if(e){var n=this.globalsForEvent(e);this.gl.push(n),this.gl.length>1e3&&(this.gl=this.gl.slice(10))}}get siteAppLoaders(){var t;return(t=B._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,n,i,r,s,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var f=d[0];l[f]={id:u[f],type:f,properties:d[1]}}var h=t.$set_once,p=t.$set;return{event:I({},pd(t,jm),{properties:I({},t.properties,p?{$set:I({},(e=(n=t.properties)==null?void 0:n.$set)!==null&&e!==void 0?e:{},p)}:{},h?{$set_once:I({},(i=(r=t.properties)==null?void 0:r.$set_once)!==null&&i!==void 0?i:{},h)}:{}),elements_chain:(s=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&s!==void 0?s:"",distinct_id:(a=t.properties)==null?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}bl(t){var e,n=(e=t.tagName)==null?void 0:e.toLowerCase();return n==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(Et.error("prepare_external_dependency_stylesheet returned null"),null):n==="script"&&this._instance.config.prepare_external_dependency_script?this._instance.config.prepare_external_dependency_script(t)||(Et.error("prepare_external_dependency_script returned null"),null):t}_l(){var t,e,n,i,r,s,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=P?.defaultView,u=l==null||(t=l.Node)==null?void 0:t.prototype;if(!l||!u)return()=>{};if(this.pl++,this.wl)return this.kl();var c=[],d=this,f=new WeakSet,h=(m,v,E)=>{if(m!=null&&m[v]){var S=m[v];m[v]=E(S),c.push((()=>{m[v]=S}))}},p=m=>{if(f.has(m))return m;var v=d.bl(m);return v&&f.add(v),v},g=m=>m.map((v=>typeof v=="string"?v:p(v))).filter((v=>!Ye(v)));return h(u,"appendChild",(m=>function(v){var E=p(v);return E?m.call(this,E):v})),h(u,"insertBefore",(m=>function(v,E){var S=p(v);return S?m.call(this,S,E):v})),h(u,"replaceChild",(m=>function(v,E){var S=p(v);return S?m.call(this,S,E):E})),[(e=l.Element)==null?void 0:e.prototype,(n=l.Document)==null?void 0:n.prototype,(i=l.DocumentFragment)==null?void 0:i.prototype].forEach((m=>{h(m,"append",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),h(m,"prepend",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))}))})),[(r=l.Element)==null?void 0:r.prototype,(s=l.CharacterData)==null?void 0:s.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((m=>{h(m,"before",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),h(m,"after",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),h(m,"replaceWith",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];var b=g(S);return S.length&&!b.length?void 0:v.apply(this,b)}))})),h((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(v,E){var S=p(E);return S?m.call(this,v,S):null})),this.wl=()=>{c.forEach((m=>m())),this.wl=void 0},this.kl()}kl(){var t=!1;return()=>{var e;t||(t=!0,this.pl--,this.pl===0&&((e=this.wl)==null||e.call(this)))}}xl(t,e){e===void 0&&(e=!0);var n=this._l();try{var i=t(n);return e&&n(),i}catch(r){throw n(),r}}setupSiteApp(t){var e=this.apps[t.id],n=()=>{var o;!e.errored&&this.gl.length&&(Et.info("Processing "+this.gl.length+" events for site app with id "+t.id),this.gl.forEach((a=>this.xl((()=>e.processEvent==null?void 0:e.processEvent(a))))),e.processedBuffer=!0),Object.values(this.apps).every((a=>a.processedBuffer||a.errored))&&((o=this.yl)==null||o.call(this))},i=!1,r=o=>{e.errored=!o,e.loaded=!0,Et.info("Site app with id "+t.id+" "+(o?"loaded":"errored")),i&&n()};try{var s=this.xl((o=>t.init({posthog:this._instance,callback(a){o(),r(a)}})),!1).processEvent;s&&(e.processEvent=s),i=!0}catch(o){Et.error(fu+t.id,o),r(!1)}if(i&&e.loaded)try{n()}catch(o){Et.error("Error while processing buffered events PostHog app with config id "+t.id,o),e.errored=!0}}Sl(){var t=this.siteAppLoaders||[];for(var e of t)this.apps[e.id]={id:e.id,loaded:!1,errored:!1,processedBuffer:!1};for(var n of t)this.setupSiteApp(n)}Cl(t){var e=this;if(Object.keys(this.apps).length!==0){var n=this.globalsForEvent(t),i=function(s){try{e.xl((()=>s.processEvent==null?void 0:s.processEvent(n)))}catch(o){Et.error("Error while processing event "+t.event+" for site app "+s.id,o)}};for(var r of Object.values(this.apps))i(r)}}onRemoteConfig(t){var e,n,i,r=this;if((e=this.siteAppLoaders)!=null&&e.length)return this.isEnabled?(this.Sl(),void this._instance.on("eventCaptured",(l=>this.Cl(l)))):void Et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((n=this.yl)==null||n.call(this),t.ok){var s=t.config;if((i=s.siteApps)!=null&&i.length)if(this.isEnabled){var o=function(){var l,u=a.id,c=a.url;B["__$$ph_site_app_"+u]=r._instance,(l=B.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(r._instance,c,(d=>{if(d)return Et.error(fu+u,d)}))};for(var a of s.siteApps)o()}else Et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},Xm={tracingHeaders:class{constructor(t){this.Ml=void 0,this.Tl=void 0,this.El=void 0,this.Uo=()=>{var e,n,i=this.Il();i?(C(this.Ml)&&(this.Ml=(e=B.__PosthogExtensions__)==null||(e=e.tracingHeadersPatchFns)==null?void 0:e._patchXHR(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager)),C(this.Tl)&&(this.Tl=(n=B.__PosthogExtensions__)==null||(n=n.tracingHeadersPatchFns)==null?void 0:n._patchFetch(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager))):this.Qo()},this._instance=t}initialize(){this.startIfEnabledOrStop()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",(i=>{if(i)return Bm.error("failed to load script",i);t()}))}Pl(){var t,e;return(t=(e=this._instance.config.tracing_headers)!==null&&e!==void 0?e:this._instance.config.addTracingHeaders)!==null&&t!==void 0?t:this._instance.config.__add_tracing_headers}Il(){var t=this.Pl();return U(t)?(U(this.El)?this.El.splice(0,this.El.length,...t):this.El=[...t],t.length>0?this.El:void 0):(U(this.El)&&this.El.splice(0),this.El=t||void 0,this.El)}Qo(){var t,e;(t=this.Ml)==null||t.call(this),(e=this.Tl)==null||e.call(this),this.Ml=void 0,this.Tl=void 0}startIfEnabledOrStop(){this.Il()?this.ai(this.Uo):this.Qo()}}},Qm=I({surveys:class{get Ne(){return this._instance.config}constructor(t){this.Rl=void 0,this._surveyManager=null,this.Al=!1,this.Fl=[],this.Ll=null,this.Ol=null,this._instance=t,this._surveyEventReceiver=null}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this.Ne.disable_surveys){if(!t.ok)return Q.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(H(e))return Q.warn("Flags not loaded yet. Not loading surveys.");var n=U(e);this.Rl=n?e.length>0:e,Q.info("flags response received, isSurveysEnabled: "+this.Rl),this.loadIfEnabled()}}reset(){try{var t;(t=this._surveyEventReceiver)==null||t.reset(),localStorage.removeItem("lastSeenSurveyDate");for(var e=[],n=0;nlocalStorage.removeItem(r)))}catch{}}loadIfEnabled(){if(!this._surveyManager)if(this.Al)Q.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)Q.info(hu);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())Q.info("Not loading surveys in cookieless mode without consent.");else{var t=B?.__PosthogExtensions__;if(t){if(!C(this.Rl)||this.Ne.advanced_enable_surveys){var e=this.Rl||this.Ne.advanced_enable_surveys;this.Al=!0;try{var n=t.generateSurveys;if(n)return void this.Dl(n,e);var i=t.loadExternalDependency;if(!i)return void this.$l(ll);i(this._instance,"surveys",(r=>{r||!t.generateSurveys?this.$l("Could not load surveys script",r):this.Dl(t.generateSurveys,e)}))}catch(r){throw this.$l("Error initializing surveys",r),r}finally{this.Al=!1}}}else Q.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new Wm(this._instance),Q.info("Surveys loaded successfully"),this.Nl({isLoaded:!0})}$l(t,e){Q.error(t,e),this.Nl({isLoaded:!1,error:t})}onSurveysLoaded(t){return this.Fl.push(t),this._surveyManager&&this.Nl({isLoaded:!0}),()=>{this.Fl=this.Fl.filter((e=>e!==t))}}getSurveys(t,e){if(e===void 0&&(e=!1),this.Ne.disable_surveys)return Q.info(hu),t([]);var n,i=this._instance.get_property(la);if(i&&!e)return t(i,{isLoaded:!0}),void(this.ql()&&this.getSurveys((()=>{}),!0));typeof Promise<"u"&&this.Ll?this.Ll.then((r=>t(r.surveys,r.context))):(typeof Promise<"u"&&(this.Ll=new Promise((r=>{n=r}))),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this.Ne.token),method:"GET",timestampMode:"query",timeout:this.Ne.surveys_request_timeout_ms,callback:r=>{var s;this.Ll=null;var o=r.statusCode;if(o!==200||!r.json){var a="Surveys API could not be loaded, status: "+o;o!==0?Q.error(a):r.error||Q.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(n==null||n({surveys:[],context:l}))}this.Ol=null;var u,c=r.json.surveys||[],d=c.filter((h=>(function(p){return!(!p.start_date||p.end_date)})(h)&&(Vf(h)||(function(p){var g;return!((g=p.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(h))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(s=this._instance.persistence)==null||s.register({[la]:c,[Xr]:Date.now()});var f={isLoaded:!0};t(c,f),n?.({surveys:c,context:f})}}))}ql(){return this.jl()&&!this.Ll&&!this.Bl()}jl(){var t=this._instance.get_property(Xr);return ke(t)&&Date.now()-t>3e5}Bl(){return ke(this.Ol)&&3e5>Date.now()-this.Ol}markSurveyAsSeen(t,e){var n,i={id:t,current_iteration:(n=e?.iteration)!==null&&n!==void 0?n:null};Kf(i);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}}Nl(t){for(var e of this.Fl)try{if(!t.isLoaded)return e([],t);this.getSurveys(e)}catch(n){Q.error("Error in survey callback",n)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!H(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);Q.warn("init was not called")}Hl(t){var e=null;return this.getSurveys((n=>{var i;e=(i=n.find((r=>r.id===t)))!==null&&i!==void 0?i:null})),e}Ul(t){if(H(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(H(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(H(this._surveyManager))return Q.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 H(this._surveyManager)?(Q.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Ir})):new Promise((n=>{this.getSurveys((i=>{var r,s=(r=i.find((a=>a.id===t)))!==null&&r!==void 0?r:null;if(s){var o=this.zl(s);n({visible:o.eligible,disabledReason:o.reason})}else n({visible:!1,disabledReason:"Survey not found"})}),e)}))}renderSurvey(t,e,n){var i;if(H(this._surveyManager))Q.warn("init was not called");else{var r=typeof t=="string"?this.Hl(t):t;if(r!=null&&r.id)if(Im.includes(r.type)){var s=P?.querySelector(e);if(s)return(i=r.appearance)!=null&&i.surveyPopupDelaySeconds?(Q.info("Rendering survey "+r.id+" with delay of "+r.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;Q.info("Rendering survey "+r.id+" with delay of "+((o=r.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(a=this._surveyManager)==null||a.renderSurvey(r,s,n),Q.info("Survey "+r.id+" rendered")}),1e3*r.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(r,s,n);Q.warn("Survey element not found")}else Q.warn("Surveys of type "+r.type+" cannot be rendered in the app");else Q.warn("Survey not found")}}displaySurvey(t,e){var n;if(H(this._surveyManager))Q.warn("init was not called");else{var i=this.Hl(t);if(i){var r=i;if((n=i.appearance)!=null&&n.surveyPopupDelaySeconds&&e.ignoreDelay&&(r=I({},i,{appearance:I({},i.appearance,{surveyPopupDelaySeconds:0})})),e.displayType!==_a.Popover&&e.initialResponses&&Q.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),e.ignoreConditions===!1){var s=this.Ul(i);if(!s.eligible)return void Q.warn("Survey is not eligible to be displayed: ",s.reason)}e.displayType!==_a.Inline?this._surveyManager.handlePopoverSurvey(r,e):this.renderSurvey(r,e.selector,e.properties)}else Q.warn("Survey not found")}}cancelPendingSurvey(t){H(this._surveyManager)?Q.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},Cs),ev={toolbar:class{constructor(t){this.instance=t}Wl(t){B.ph_toolbar_state=t}Vl(){var t;return(t=B.ph_toolbar_state)!==null&&t!==void 0?t:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(t,e,n){if(t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),ga(this.instance.config)||!w||!P)return!1;t=t??w.location,n=n??w.history;try{if(!e){try{w.localStorage.setItem("test","test"),w.localStorage.removeItem("test")}catch{return!1}e=w?.localStorage}var i,r=zm||os(t.hash,"__posthog")||os(t.hash,"state"),s=r?Rc((()=>JSON.parse(atob(decodeURIComponent(r)))))||Rc((()=>JSON.parse(decodeURIComponent(r)))):null;return s&&s.action==="ph_authorize"?((i=s).source="url",i&&Object.keys(i).length>0&&(s.desiredHash?t.hash=s.desiredHash:n?n.replaceState(n.state,"",t.pathname+t.search):t.hash="")):((i=JSON.parse(e.getItem(pu)||"{}")).source="localstorage",delete i.userIntent),!(!i.token||this.instance.config.token!==i.token||(this.loadToolbar(i),0))}catch{return!1}}Zl(t){var e=B.ph_load_toolbar||B.ph_load_editor;!H(e)&&je(e)?e(t,this.instance):gu.warn("No toolbar load function found")}loadToolbar(t){var e=!(P==null||!P.getElementById(cf));if(!w||e)return!1;var n=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,i=I({token:this.instance.config.token},t,{apiURL:this.instance.requestRouter.endpointFor("ui")},n?{instrument:!1}:{});if(w.localStorage.setItem(pu,JSON.stringify(I({},i,{source:void 0}))),this.Vl()===2)this.Zl(i);else if(this.Vl()===0){var r;this.Wl(1),(r=B.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"toolbar",(s=>{if(s)return gu.error("[Toolbar] Failed to load",s),void this.Wl(0);this.Wl(2),this.Zl(i)})),ve(w,"turbolinks:load",(()=>{this.Wl(0),this.loadToolbar(i)}))}return!0}Gl(t){return this.loadToolbar(t)}maybeLoadEditor(t,e,n){return t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),this.maybeLoadToolbar(t,e,n)}}},tv=I({experiments:Me},Cs),nv={conversations:class{constructor(t){this.Ql=void 0,this._conversationsManager=null,this.Kl=!1,this.Jl=null,this.Yl=!1,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this._instance.config.disable_conversations&&(this.Xl=t.ok,t.ok)){var e=t.config.conversations;H(e)||(mt(e)?this.Ql=e:(this.Ql=e.enabled,this.Jl=e),this.loadIfEnabled())}}reset(){var t;(t=this._conversationsManager)==null||t.reset(),this._conversationsManager=null,this.Ql=void 0,this.Jl=null,this.Xl=void 0,this.Yl=!1}loadIfEnabled(){if(!(this._conversationsManager||this.Kl||this._instance.config.disable_conversations||ga(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=B?.__PosthogExtensions__;if(t&&!C(this.Ql)&&this.Ql)if(this.Jl&&this.Jl.token){this.Kl=!0;try{var e=t.initConversations;if(e)return this.tu(e),void(this.Kl=!1);var n=t.loadExternalDependency;if(!n)return void this.eu(ll);n(this._instance,"conversations",(i=>{i||!t.initConversations?this.eu("Could not load conversations script",i):this.tu(t.initConversations),this.Kl=!1}))}catch(i){this.eu("Error initializing conversations",i),this.Kl=!1}}else ot.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,ot.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else ot.error("Cannot complete initialization: remote config is null")}eu(t,e){ot.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():ot.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!Ye(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":ga(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.Xl===!1?"remote_config_failed":C(this.Ql)?this.Xl?"disabled_in_project":"remote_config_pending":this.Ql?H(this.Jl)||!this.Jl.token?"missing_token":B!=null&&B.__PosthogExtensions__?this.Kl?"initializing":this.Yl?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.isVisible())!==null&&t!==void 0&&t}sendMessage(t,e,n){var i=this;return se((function*(){return i._conversationsManager?i._conversationsManager.sendMessage(t,e,n):(ot.warn(En),null)}))()}getMessages(t,e){var n=this;return se((function*(){return n._conversationsManager?n._conversationsManager.getMessages(t,e):(ot.warn(En),null)}))()}markAsRead(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(ot.warn(En),null)}))()}getTickets(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(ot.warn(En),null)}))()}requestRestoreLink(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(ot.warn(En),null)}))()}restoreFromToken(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(ot.warn(En),null)}))()}restoreFromUrlToken(){var t=this;return se((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(ot.warn(En),null)}))()}getCurrentTicketId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getCurrentTicketId())!==null&&t!==void 0?t:null}getWidgetSessionId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getWidgetSessionId())!==null&&t!==void 0?t:null}Xn(){var t;(t=this._conversationsManager)==null||t.setIdentity()}ts(){var t;(t=this._conversationsManager)==null||t.clearIdentity()}}},iv={logs:class{constructor(t){var e,n=this;this.iu=!1,this.ru=!1,this.rt=pe("[logs]"),this.nu=I({},this.rt,{error(){for(var i=arguments.length,r=new Array(i),s=0;i>s;s++)r[s]=arguments[s];r.some(Su)||n.rt.error(...r)}}),this.tr=[],this.su=[],this.Sa=0,this.au=()=>{var i,r;this.Sa=0,(i=this.ou)==null||i.onReconnect(),(r=this.lu)==null||r.onReconnect()},this._instance=t,this._instance&&(e=this._instance.config.logs)!=null&&e.captureConsoleLogs&&(this.iu=!0),w&&ve(w,"online",this.au)}uu(t,e,n,i){var r,s=(function(o,a){var l,u,c,d,f,h,p,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,v=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,E=C(v)?Math.max(m,2048):Math.max(m,v),S=o?.resourceAttributes;return{serviceName:(d=(f=S?.["service.name"])!==null&&f!==void 0?f:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(h=S?.["service.version"])!==null&&h!==void 0?h:o?.serviceVersion,environment:(p=S?.["deployment.environment"])!==null&&p!==void 0?p:o?.environment,resourceAttributes:S,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:E,maxBatchRecordsPerPost:100,rateCapWindowMs:g,maxLogsPerInterval:v,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}})((r=this._instance)==null||(r=r.config)==null?void 0:r.logs,n);return[new ag(this.hu(t,e),s,this.nu,(()=>this.du()),(o=>o()),void 0,i),s]}vu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.ou||this.cu!==e){var n;(n=this.ou)==null||n.reset(),this.cu=e;var i=this.uu((()=>this.tr),(r=>{this.tr=r}));this.ou=i[0],this.fu=i[1]}return this.ou}pu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.lu||this.gu!==e){var n;(n=this.lu)==null||n.reset(),this.gu=e;var i=this.uu((()=>this.su),(r=>{this.su=r}),{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},Eu);this.lu=i[0],this.mu=i[1]}return this.lu}initialize(){this.loadIfEnabled()}onRemoteConfig(t){var e;if(t.ok){var n=(e=t.config.logs)==null?void 0:e.captureConsoleLogs;!H(n)&&n&&(this.iu=!0,this.loadIfEnabled())}}reset(){var t,e;this.tr=[],(t=this.ou)==null||t.reset(),this.su=[],(e=this.lu)==null||e.reset(),this.Sa=0}captureLog(t){this.vu().captureLog(t)}he(t){this.pu().captureLog(t)}get logger(){return this.yu||(this.yu={trace:(t,e)=>this.captureLog({body:t,level:"trace",attributes:e}),debug:(t,e)=>this.captureLog({body:t,level:"debug",attributes:e}),info:(t,e)=>this.captureLog({body:t,level:"info",attributes:e}),warn:(t,e)=>this.captureLog({body:t,level:"warn",attributes:e}),error:(t,e)=>this.captureLog({body:t,level:"error",attributes:e}),fatal:(t,e)=>this.captureLog({body:t,level:"fatal",attributes:e})}),this.yu}flushLogs(t){t?this.bu(t):(this.ou&&this.ou.flush().catch((e=>this._u(e))),this.lu&&this.lu.flush().catch((e=>this._u(e))))}_u(t){Su(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=B?.__PosthogExtensions__;if(t){var e=t.loadExternalDependency;e?e(this._instance,"logs",(n=>{var i;n||(i=t.logs)==null||!i.initializeLogs?this.rt.error("Could not load logs script",n):(t.logs.initializeLogs(this._instance),this.ru=!0)})):this.rt.error(ll)}else this.rt.error("PostHog Extensions not found.")}}hu(t,e){var n=this._instance;return{get isDisabled(){return!1},get optedOut(){return!n.is_capturing()},getPersistedProperty:i=>i===Ut.LogsQueue?t():void 0,setPersistedProperty(i,r){var s;i===Ut.LogsQueue&&e((s=r)!==null&&s!==void 0?s:[])},Ot:i=>this.Ot(i),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Ot(t){return new Promise((e=>{if(bf(this.Sa,3))e({kind:"fatal",error:Do(void 0,"logs endpoint is unreachable, dropping batch")});else{var n=!1,i=s=>{n||(n=!0,clearTimeout(r),e(s))},r=setTimeout((()=>{this.rt.warn("Logs request timed out before receiving a response"),i({kind:"retry-later",error:Do(void 0,"logs request timed out")})}),9e4);this._instance._send_request({method:"POST",url:this.wu(),data:t,compression:"best-available",batchKey:"logs",fireCallbackOnDrop:!0,callback:s=>{var o=s.statusCode;if(this.ku(o),o>=200&&300>o)i({kind:"ok"});else if(o===413)i({kind:"too-large"});else if(o!==0&&o!==429&&500>o)i({kind:"fatal",error:new Error("logs request failed with status "+o)});else{var a;o===0?(s.error||this.rt.warn("Logs request failed before receiving an HTTP response"),i({kind:"retry-later",error:Do(s.error,"logs request failed before receiving an HTTP response")})):i({kind:"retry-later",error:(a=s.error)!==null&&a!==void 0?a:new Error("logs request failed with status "+o)})}}})}}))}ku(t){(t!==0||this._instance.__loaded)&&(this.Sa=Ef(t,this.Sa,3,(()=>this.rt.warn("Log requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped sending logs; will try again when connectivity changes."))))}bu(t){this.tr.length>0&&this.xu(t,this.tr,this.fu,ne.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,Eu,(e=>{this.su=e}))}xu(t,e,n,i,r){if(e.length!==0){var s=e.map((a=>a.record));r([]);var o=qd(s,zd(n,ne.LIB_NAME,ne.LIB_VERSION),i,ne.LIB_VERSION);this._instance._send_request({method:"POST",url:this.wu(),data:o,compression:"best-available",batchKey:"logs",transport:t})}}wu(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}du(){var t,e={};if(e.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var n=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.windowId,r=n.sessionStartTimestamp,s=n.lastActivityTimestamp;e.sessionId=n.sessionId,e.windowId=i,H(r)||(e.sessionStartTimestamp=r),H(s)||(e.lastActivityTimestamp=s)}if(B!=null&&(t=B.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?fn(B.location.href):B.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},rv={metrics:class{constructor(t){this.rt=pe("[metrics]"),this._instance=t}initialize(){}vu(){var t,e,n=(t=this._instance)==null||(t=t.config)==null?void 0:t.metrics;return this.ou&&this.cu===n||((e=this.ou)==null||e.reset(),this.cu=n,this.ou=new lg(this.hu(),(function(i){var r,s,o,a,l,u=i?.resourceAttributes;return{serviceName:(r=u?.["service.name"])!==null&&r!==void 0?r:i?.serviceName,serviceVersion:(s=u?.["service.version"])!==null&&s!==void 0?s:i?.serviceVersion,environment:(o=u?.["deployment.environment"])!==null&&o!==void 0?o:i?.environment,resourceAttributes:u,beforeSend:i?.beforeSend,flushIntervalMs:(a=i?.flushIntervalMs)!==null&&a!==void 0?a:1e4,maxSeriesPerFlush:(l=i?.maxSeriesPerFlush)!==null&&l!==void 0?l:1e3}})(n),this.rt)),this.ou}count(t,e,n){e===void 0&&(e=1),this.vu().count(t,e,n)}gauge(t,e,n){this.vu().gauge(t,e,n)}histogram(t,e,n){this.vu().histogram(t,e,n)}flush(t){if(!this.ou)return Promise.resolve();if(t){var e=this.ou.drainWindow();return e&&this.Jt(e,t),Promise.resolve()}return this.ou.flush().catch((n=>this.rt.error("PostHog metrics flush failed:",n)))}reset(){var t;(t=this.ou)==null||t.reset()}hu(){var t=this._instance,e=this;return{get isDisabled(){return!1},get optedOut(){return!t.is_capturing()},Jt:n=>e.Jt(n),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Jt(t,e){return new Promise((n=>{var i=!1,r=o=>{i||(i=!0,clearTimeout(s),n(o))},s=setTimeout((()=>r({kind:"retry-later",error:new Error("metrics request timed out")})),9e4);this._instance._send_request(I({method:"POST",url:this.Su(),data:t,compression:"best-available",batchKey:"metrics"},e&&{transport:e},{fireCallbackOnDrop:!0,callback(o){var a=o.statusCode;if(a>=200&&300>a)r({kind:"ok"});else if(a===413)r({kind:"too-large"});else if(a!==0&&a!==429&&500>a)r({kind:"fatal",error:new Error("metrics request failed with status "+a)});else{var l;r({kind:"retry-later",error:(l=o.error)!==null&&l!==void 0?l:new Error("metrics request failed with status "+a)})}}}))}))}Su(){return this._instance.requestRouter.endpointFor("api","/i/v1/metrics")+"?token="+encodeURIComponent(this._instance.config.token)}}},sv=I({},Cs,Gm,Km,Ym,Jm,Zm,Qm,Xm,ev,tv,nv,iv,rv);Ze.__defaultExtensionClasses=I({},sv);(function(){ne.SDK_DIST_CHANNEL="npm";var t=zi[Kn]=new Ze;return(function(){function e(){e.done||(e.done=!0,Jf=!1,ie(zi,(function(n){n._dom_loaded()})))}P!=null&&P.addEventListener?P.readyState==="complete"?e():ve(P,"DOMContentLoaded",e,{capture:!1}):w&&A.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const ov=["a[href]","button:not([disabled])","input:not([disabled]):not([type='hidden'])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(",");let pt=null,ka=null,Xf="";const Ca=new Map;function Qf(t){return[...t.querySelectorAll(ov)].filter(e=>!e.hidden&&e.getAttribute("aria-hidden")!=="true"&&e.getClientRects().length>0)}function av(t){for(const e of document.body.children)e===t||e.tagName==="SCRIPT"||(Ca.set(e,{inert:e.inert,ariaHidden:e.getAttribute("aria-hidden")}),e.inert=!0,e.setAttribute("aria-hidden","true"))}function lv(){for(const[t,e]of Ca)t.inert=e.inert,e.ariaHidden===null?t.removeAttribute("aria-hidden"):t.setAttribute("aria-hidden",e.ariaHidden);Ca.clear()}function eh(t){return t?.dataset.modalDismissible!=="false"&&t?.getAttribute("aria-busy")!=="true"}function We(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n)return!1;pt&&pt!==n&&ze(pt,{restoreFocus:!1,force:!0}),ka=e.trigger||document.activeElement,pt=n,Xf=document.body.style.overflow,av(n),document.body.style.overflow="hidden",n.classList.add("open"),n.setAttribute("aria-hidden","false");const i=n.querySelector(".modal-content");i&&(i.style.transform="scale(1) translateY(0)");const r=()=>{if(pt!==n)return;((e.initialFocus?n.querySelector(e.initialFocus):n.querySelector("[data-modal-initial-focus]"))||Qf(n)[0]||n.querySelector(".modal-content")||n).focus({preventScroll:!0})};return requestAnimationFrame(r),setTimeout(r,260),!0}function ze(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n||!e.force&&!eh(n))return!1;n.classList.remove("open"),n.setAttribute("aria-hidden","true"),lv(),document.body.style.overflow=Xf,pt=null;const i=ka;return ka=null,e.restoreFocus!==!1&&i?.isConnected&&i.focus({preventScroll:!0}),!0}function xu(t,e,n="Operation in progress"){const i=typeof t=="string"?document.getElementById(t):t;i&&(i.dataset.modalDismissible=e?"false":"true",i.setAttribute("aria-busy",String(!!e)),e?i.setAttribute("aria-label",n):i.removeAttribute("aria-label"))}function cv(t){if(!eh(t))return;const e=t.dataset.modalCloseHandler;e&&typeof window[e]=="function"?window[e]():ze(t)}document.addEventListener("keydown",t=>{if(!pt)return;if(t.key==="Escape"){t.preventDefault(),t.stopImmediatePropagation(),cv(pt);return}if(t.key!=="Tab"){t.stopPropagation();return}const e=Qf(pt);if(!e.length){t.preventDefault(),(pt.querySelector(".modal-content")||pt).focus();return}const n=e[0],i=e[e.length-1];t.shiftKey&&document.activeElement===n?(t.preventDefault(),i.focus()):!t.shiftKey&&document.activeElement===i&&(t.preventDefault(),n.focus())},!0);function uv(){document.querySelectorAll(".modal-overlay").forEach(t=>{t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-hidden",t.classList.contains("open")?"false":"true");const e=t.querySelector(".modal-content");e&&!e.hasAttribute("tabindex")&&(e.tabIndex=-1);const n=t.querySelector("h1, h2, h3");n&&(n.id||(n.id=`${t.id}-title`),t.setAttribute("aria-labelledby",n.id)),t.querySelectorAll(".modal-close").forEach(i=>{i.getAttribute("aria-label")||i.setAttribute("aria-label","Close dialog")})})}const ml=Object.freeze({free:"Free",professional:"Pro",power:"Power"}),dv=Object.freeze({free:2,professional:50,power:2e3}),fv="(contact us)",hv=Object.freeze({free:Object.freeze(["2 generations/month","Gemini model only","Code Review"]),professional:Object.freeze(["50 generations/month","All models","Code Regeneration","Code Review"]),power:Object.freeze(["2000 generations/month","All models","Code Regeneration","Bring your own key (BYOK)","Code Review","All models + early access",`API & MCP access ${fv}`])}),th="CodeFile",nh="GeneratedCode",pv={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function ln(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Aa(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function gv(t={},e=0){const n=Aa(t.artifactType||t.type||th),i=Aa(t.artifactName||t.name||t.fileName||`${nh}-${e+1}`);return`${n||"artifact"}-${i||e+1}`}function ih(t={},e=0){const n=ln(t),i=n.artifactType||n.type||th,r=n.artifactName||n.name||nh;let s=n.fileName||r;return s.endsWith(".dart")||(s+=".dart"),{id:Aa(n.id)||gv({...n,artifactType:i,artifactName:r,fileName:s},e),artifactType:i,artifactName:r,fileName:s,deployPath:n.deployPath||"",description:n.description||"",code:n.code||n.content||"",dependencies:rh(n.dependencies),imports:Array.isArray(n.imports)?n.imports:[],publicApi:Array.isArray(n.publicApi)?n.publicApi:[],relationships:sh(n.relationships),deployStatus:n.deployStatus||"pending",review:n.review||null,metadata:ln(n.metadata),codeType:n.codeType||pv[i]||"O"}}function rh(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const n=ln(e),i=n.name||n.package;return i?{name:i,version:n.version||null,versionRequired:!!(n.versionRequired||n.required),inferred:!!n.inferred,...n.reason?{reason:n.reason}:{}}:null}).filter(Boolean):Object.entries(ln(t)).map(([e,n])=>({name:e,version:n||null,inferred:!1})):[]}function sh(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const n=ln(e);return!n.from&&!n.to?null:{from:n.from||null,to:n.to||null,type:n.type||"uses",description:n.description||""}}).filter(Boolean):[]}function Pa(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;try{return JSON.parse(e)}catch{const n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(!n)return null;try{return JSON.parse(n[1].trim())}catch{return null}}}function er(t,e={}){const n=[],i=typeof t=="string"?Pa(t):t,s=ln(i||{});!i&&typeof t=="string"&&n.push("Structured bundle parse failed; using legacy single-artifact fallback.");const o=Array.isArray(s.artifacts)?s.artifacts:[{artifactType:s.artifactType||e.artifactType,artifactName:s.artifactName||e.artifactName,fileName:s.fileName||e.fileName,description:s.description,code:s.code||e.code||(typeof t=="string"?t:""),dependencies:s.dependencies||e.dependencies,relationships:s.relationships||e.relationships}];o.forEach((d,f)=>{!d?.artifactType&&!d?.type&&n.push(`Artifact ${f+1} has no artifactType; it will deploy as a standalone code file under lib/custom_code/ root.`)});const a=o.map((d,f)=>ih(d,f)),l=new Map(o.map((d,f)=>[ln(d).id,a[f]?.id]).filter(([d,f])=>d&&f)),u=d=>l.get(d)||d,c=sh(s.relationships||e.relationships).map(d=>({...d,from:d.from?u(d.from):d.from,to:d.to?u(d.to):d.to}));return{schemaVersion:s.schemaVersion||e.schemaVersion||null,id:s.id||e.id||"bundle-current",title:s.title||s.name||e.title||"Generated artifact bundle",description:s.description||e.description||"",artifacts:a,dependencies:rh(s.dependencies||e.dependencies),relationships:c,deployOrder:Array.isArray(s.deployOrder)?s.deployOrder.map(u):a.map(d=>d.id),warnings:[...n,...Array.isArray(s.warnings)?s.warnings:[]],metadata:ln(s.metadata)}}function ai(t){return er(t).artifacts[0]||ih()}function Zt(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function li(t){return JSON.stringify(t,null,2)}function mv(t){return li({task:"architect",userRequest:String(t??"")})}function vv(t){const e=Zt(t);return e&&typeof e=="object"&&typeof e.task=="string"?li(e):li({task:"generate_bundle",bundleSpec:e})}function _v(t){return li({task:"review_bundle",generatedBundle:Zt(t),outputRequirements:{bundleReview:["status","score","summary","manualActions","findings"],scoreRange:[0,100],eachArtifact:["id","review.status","review.findings"],manualActions:{definition:"Setup the developer must perform by hand in the FlutterFlow editor that FlutterFlow will NOT do for them.",exclude:["creating the Custom Action, Widget or Code File itself - deploying the code creates it","declaring parameters or return values FlutterFlow derives from the function signature","anything that resolves as a side effect of using the action or widget in the editor","generic advice such as testing, reviewing or rebuilding the app"],preferEmpty:"Return an empty array when nothing qualifies - an empty list is the expected result for most bundles."}}})}function vl(t,e=null){const n={stage:t};return e!=null&&(n.bundle=Zt(e)),n}function yv({bundleSpec:t,artifactBundle:e,bundleReview:n,artifactId:i,userFeedback:r}){return li({task:"regenerate_artifact",artifactId:i,bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(r)})}function oh({bundleSpec:t,artifactBundle:e,bundleReview:n,userFeedback:i}){return li({task:"regenerate_bundle",bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(i??"")})}const Iu={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"},wv=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function tt(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function bv(t){return tt(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||tt(t.filterSummary)||tt(t.filterResults):!1}function ah(t,e=0){if(!tt(t)||e>3)return null;if(bv(t))return t;for(const n of wv){const i=t[n];if(tt(i)){const r=ah(i,e+1);if(r)return r}}return null}function ds(t){return Array.isArray(t)?t.some(ds):tt(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(ds):!1}function Fa(t){return Array.isArray(t)?t.some(Fa):tt(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(Fa):!1}function lh(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function Ev(t,e){if(tt(t))for(const[n,i]of Object.entries(t)){if(!tt(i))continue;const r=tt(i.categories)?i.categories:{},s=Object.entries(r).filter(([,o])=>tt(o)&&o.matched===!0).map(([o])=>o);s.length>0?s.forEach(o=>e.add(o)):i.matched===!0&&e.add(lh(n))}}function Sv(t,e){if(!t)return;const n=Array.isArray(t)?t.flatMap(i=>tt(i)?Object.entries(i):[]):Object.entries(t);for(const[i,r]of n){if(!ds(r))continue;const s=lh(i),o=r?.raiFilterResult?.raiFilterTypeResults||(s==="rai"?r?.raiFilterTypeResults:null),a=tt(o)?Object.entries(o).filter(([,l])=>ds(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(s)}}function xv(t){return Iu[t]?Iu[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function ku(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 Iv(t){const e=ah(t);if(!e)return null;const n=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);Ev(e.filterSummary,n),Sv(e.filterResults,n);const i=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||n.size>0,r=e.invocationResult||null,s=Fa(e.filterSummary||e.filterResults);return!i&&!s&&!["PARTIAL","FAILURE"].includes(r)?null:{kind:i?"blocked":"unavailable",invocationResult:r,matchedFilters:[...n]}}function kv(t,e){const n=Iv(t);if(!n)return null;const i=[...new Set(n.matchedFilters.map(xv))],r=n.kind==="blocked",s=new Error(r?`Safety screening blocked this pipeline step for ${ku(i)}.`:"Safety screening could not be completed. Please try again.");return s.name="ModelArmorError",s.code=r?"MODEL_ARMOR_BLOCKED":"MODEL_ARMOR_UNAVAILABLE",s.isModelArmor=!0,s.pipelineStep=e,s.userTitle=r?"Request blocked for safety":"Safety check unavailable",s.userMessage=r?`The safety check detected ${ku(i)}. Edit your request to remove or rephrase the flagged content, then run the pipeline again.`:"The safety service did not finish all of its checks. Please wait a moment and run the pipeline again.",s.retryExplanation=r?"Trying another model would not change this safety decision.":"A fallback model was not attempted because safety screening must complete first.",s.matchedFilters=n.matchedFilters,s}function Cv(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function Cu(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,n=[];for(const i of Cv(t).split(` -`)){if(!/^[A-Za-z_$]/.test(i)||e.test(i))continue;const r=i.match(/^[\w$<>,?\s[\]]+?\s([a-zA-Z_$][\w$]*)\s*\(/);r&&n.push(r[1])}return n}function _l(t,e){const n=t.replace(/\.dart$/,"");if(e==="W")return n.replace(/(^|_)(\w)/g,(i,r,s)=>s.toUpperCase());if(e==="A"){const i=n.replace(/(^|_)(\w)/g,(r,s,o)=>o.toUpperCase());return i.charAt(0).toLowerCase()+i.slice(1)}return e==="F"?"CustomFunctions":e==="C"?t.endsWith(".dart")?t:`${t}.dart`:n}async function Au(t){const e=new TextEncoder().encode(String(t||"")),n=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n),i=>i.toString(16).padStart(2,"0")).join("")}async function Av(t,e=new Map){const n={},i=new Set;for(const[o,a]of t.entries()){if(a.type==="D"||a.type==="O")continue;const l=_l(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await Au(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await Au(c)),n[o]=u,a.type==="F"){const d=Cu(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(h=>i.add(h))}}const r=new Set(Cu(e.get("lib/flutter_flow/custom_functions.dart")||"")),s={functions_to_rename:[],functions_to_delete:[],functions_to_add:Array.from(i).filter(o=>!r.has(o))};return{fileMapContents:JSON.stringify(n),functionsMapContents:JSON.stringify(s)}}const Pv=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),Pu={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},Fv=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),Rv=["Struct","Record"],Tv=[{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=>jo(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=>jo(t).some(e=>{const n=/^\s*final\s+(?:double|int|String|bool|Color|num)\s+(\w+)\s*;/gm;let i;for(;(i=n.exec(e))!==null;){const r=i[1];if(!(new RegExp(`this\\.${r}\\s*=(?!=)`).test(e)||new RegExp(`[:,]\\s*${r}\\s*=(?!=)`).test(e)))return!0}return!1}),pos:`class W extends StatefulWidget { +(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const s of r)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function n(r){const s={};return r.integrity&&(s.integrity=r.integrity),r.referrerPolicy&&(s.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?s.credentials="include":r.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function i(r){if(r.ep)return;r.ep=!0;const s=n(r);fetch(r.href,s)}})();var w=typeof window<"u"?window:void 0,Ne=typeof globalThis<"u"?globalThis:w,He=Ne?.navigator,P=Ne?.document,me=Ne?.location,el=Ne?.fetch,Vo=Ne!=null&&Ne.XMLHttpRequest&&"withCredentials"in new Ne.XMLHttpRequest?Ne.XMLHttpRequest:void 0,pc=Ne?.AbortController,Op=Ne?.CompressionStream,Ge=He?.userAgent;function gd(){return!(!w||w.navigator.onLine===!1)}var _i=typeof globalThis<"u"?globalThis:w;_i&&typeof self>"u"&&(_i.self=_i),_i&&typeof File>"u"&&(_i.File=function(){});var B=w??{},ne={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function gc(t,e,n,i,r,s,o){try{var a=t[s](o),l=a.value}catch(u){return void n(u)}a.done?e(l):Promise.resolve(l).then(i,r)}function se(t){return function(){var e=this,n=arguments;return new Promise((function(i,r){var s=t.apply(e,n);function o(l){gc(s,i,r,o,a,"next",l)}function a(l){gc(s,i,r,o,a,"throw",l)}o(void 0)}))}}function I(){return I=Object.assign?Object.assign.bind():function(t){for(var e=1;arguments.length>e;e++){var n=arguments[e];for(var i in n)({}).hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},I.apply(null,arguments)}function md(t,e){if(t==null)return{};var n={};for(var i in t)if({}.hasOwnProperty.call(t,i)){if(e.indexOf(i)!==-1)continue;n[i]=t[i]}return n}var mc=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function vc(t){return typeof t=="string"||t}function _c(t){return typeof t=="string"?t:void 0}var yi,Bp=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],Ut=(function(t){return t.AnonymousId="anonymous_id",t.DistinctId="distinct_id",t.Props="props",t.EnablePersonProcessing="enable_person_processing",t.PersonMode="person_mode",t.FeatureFlagDetails="feature_flag_details",t.FeatureFlags="feature_flags",t.FeatureFlagPayloads="feature_flag_payloads",t.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",t.BootstrapFeatureFlags="bootstrap_feature_flags",t.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",t.OverrideFeatureFlags="override_feature_flags",t.Queue="queue",t.AiQueue="ai_queue",t.LogsQueue="logs_queue",t.OptedOut="opted_out",t.SessionId="session_id",t.SessionStartTimestamp="session_start_timestamp",t.SessionLastTimestamp="session_timestamp",t.PersonProperties="person_properties",t.GroupProperties="group_properties",t.InstalledAppBuild="installed_app_build",t.InstalledAppVersion="installed_app_version",t.SessionReplay="session_replay",t.PushRegistered="push_registered",t.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",t.SurveyLastSeenDate="survey_last_seen_date",t.SurveysSeen="surveys_seen",t.Surveys="surveys",t.RemoteConfig="remote_config",t.FlagsEndpointWasHit="flags_endpoint_was_hit",t.DeviceId="device_id",t})({}),yc=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),Dp=["$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"],jp=["token"],vd="NativeGzipValidationError",Go=t=>t.length>=2&&t[0]===31&&t[1]===139,wc=(t,e)=>t===yc.GZipJS||e===yc.GZipJS||e==="gzip",bc=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",mr=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=vd,e},Up=(function(){var t=se((function*(e,n){18>e.size&&mr("too-short");var i=new Uint8Array(yield e.slice(0,10).arrayBuffer());Go(i)&&i[2]===8||mr("invalid-header");var r=new DataView(yield e.slice(e.size-8).arrayBuffer());r.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(yi)return yi;yi=[];for(var c=0;256>c;c++){for(var d=c,h=0;8>h;h++)d=1&d?3988292384^d>>>1:d>>>1;yi[c]=d>>>0}return yi})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(n)&&mr("invalid-crc");var s=n.length>>>0;r.getUint32(4,!0)!==s&&mr("invalid-size")}));return function(e,n){return t.apply(this,arguments)}})();function Ko(){return Ko=se((function*(t,e,n){e===void 0&&(e=!0);try{var i=new TextEncoder().encode(t),r=new globalThis.CompressionStream("gzip"),s=r.writable.getWriter(),o=s.write(i).then((()=>s.close())).catch((function(){var u=se((function*(c){try{yield s.abort(c)}catch{}throw c}));return function(c){return u.apply(this,arguments)}})()),a=new Response(r.readable).blob(),l=(yield Promise.all([a,o]))[0];return yield Up(l,i),l}catch(u){if(n!=null&&n.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),Ko.apply(this,arguments)}var Hp=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],Ec=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var n=t.toLowerCase();return Hp.concat(e).some((i=>{var r=i.toLowerCase();return n.indexOf(r)!==-1}))};function j(t,e){return t.indexOf(e)!==-1}var ks=function(t){return t.trim()},Yo=function(t){return t.replace(/^\$/,"")};function _d(t){var e,n=[];return(e=JSON.stringify(t,(function(i,r){if(typeof r=="bigint")return r.toString();if(typeof r!="function"&&typeof r!="symbol"){if(r instanceof Error)return{name:r.name,message:r.message,stack:r.stack};if(r&&typeof r=="object"){for(;n.length>0&&n[n.length-1]!==this;)n.pop();if(n.includes(r))return"[Circular]";n.push(r)}return r}})))!==null&&e!==void 0?e:"null"}var yd=Object.prototype,wd=yd.hasOwnProperty,Cs=yd.toString,U=Array.isArray||function(t){return Cs.call(t)==="[object Array]"},je=t=>typeof t=="function",he=t=>t===Object(t)&&!U(t),Kt=t=>{if(he(t)){for(var e in t)if(wd.call(t,e))return!1;return!0}return!1},C=t=>t===void 0,X=t=>Cs.call(t)=="[object String]",Jo=t=>X(t)&&t.trim().length===0,Ye=t=>t===null,H=t=>C(t)||Ye(t),ke=t=>Cs.call(t)=="[object Number]"&&t==t,Dt=t=>ke(t)&&t>0,mt=t=>Cs.call(t)==="[object Boolean]",Wp=t=>t instanceof FormData,zp=t=>j(Dp,t),qp=t=>j(jp,t);function bd(t){return t===null||typeof t!="object"}function zr(t,e){return{}.toString.call(t)==="[object "+e+"]"}function tl(t){return typeof Event<"u"&&Ed(t,Event)}function Ed(t,e){try{return t instanceof e}catch{return!1}}var Vp=[!0,"true",1,"1","yes"],ho=t=>j(Vp,t),Gp=[!1,"false",0,"0","no"];function At(t,e,n,i,r){return e>n&&(i.warn("min cannot be greater than max."),e=n),ke(t)?t>n?(i.warn(" cannot be greater than max: "+n+". Using max value instead."),n):e>t?(i.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(i.warn(" must be a number. using max or fallback. max: "+n+", fallback: "+r),At(r||n,e,n,i))}class Kp{constructor(e){this.tt={},this.et=e.et,this.it=At(e.bucketSize,0,100,e.rt),this.nt=At(e.refillRate,0,this.it,e.rt),this.st=At(e.refillInterval,0,864e5,e.rt)}ot(e,n){var i=Math.floor((n-e.lastAccess)/this.st);i>0&&(e.tokens=Math.min(e.tokens+i*this.nt,this.it),e.lastAccess=e.lastAccess+i*this.st)}consumeRateLimit(e){var n,i=Date.now(),r=String(e),s=this.tt[r];return s?this.ot(s,i):this.tt[r]=s={tokens:this.it,lastAccess:i},s.tokens===0||(s.tokens--,s.tokens===0&&((n=this.et)==null||n.call(this,e)),s.tokens===0)}stop(){this.tt={}}}var rt="Mobile",qr="iOS",Yt="Android",ti="Tablet",Sd=Yt+" "+ti,xd="iPad",Id="Apple",kd=Id+" Watch",Di="Safari",ni="BlackBerry",Cd="Samsung",Ad=Cd+"Browser",Pd=Cd+" Internet",Pn="Chrome",Yp=Pn+" OS",Fd=Pn+" "+qr,nl="Internet Explorer",Rd=nl+" "+rt,il="Opera",Jp=il+" Mini",rl="Edge",Td="Microsoft "+rl,Xn="Firefox",$d=Xn+" "+qr,Ki="Nintendo",Yi="PlayStation",Qn="Xbox",Md=Yt+" "+rt,Ld=rt+" "+Di,Fi="Windows",Zo=Fi+" Phone",Sc="Nokia",Xo="Ouya",Nd="Generic",Zp=Nd+" "+rt.toLowerCase(),Od=Nd+" "+ti.toLowerCase(),Qo="Konqueror",Bd="Oculus Browser",Vr="Vivaldi",Dd="Yandex",Gr="Whale",ea="DuckDuckGo",jd="Pale Moon",Kr="Waterfox",ji="Brave",Ud="Google Search App",we="(\\d+(\\.\\d+)?)",po=new RegExp("Version/"+we),Xp=new RegExp(Qn,"i"),Qp=new RegExp(Yi+" \\w+","i"),eg=new RegExp(Ki+" \\w+","i"),sl=new RegExp(ni+"|PlayBook|BB10","i"),tg={"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"},Hd=function(t,e,n,i){e=e||"";var r=(function(s){return s!=null&&s.brave?ji:null})(n);return r||(i!=null&&i.detectGoogleSearchApp&&j(t,"GSA/")?Ud:j(t," OPR/")&&j(t,"Mini")?Jp:j(t," OPR/")?il:sl.test(t)?ni:j(t,"IE"+rt)||j(t,"WPDesktop")?Rd:j(t,"OculusBrowser")?Bd:j(t,Ad)?Pd:j(t,rl)||j(t,"Edg/")?Td:j(t,Vr+"/")?Vr:j(t,"YaBrowser/")?Dd:j(t,Gr+"/")?Gr:j(t,ea+"/")||j(t,"Ddg/")?ea:j(t,"FBIOS")?"Facebook "+rt:j(t,"UCWEB")||j(t,"UCBrowser")?"UC Browser":j(t,"CriOS")?Fd:j(t,"CrMo")||j(t,Pn)?Pn:j(t,Yt)&&j(t,Di)?Md:j(t,"FxiOS")?$d:j(t.toLowerCase(),Qo.toLowerCase())?Qo:j(t,ji+"/")?ji:((s,o)=>o&&j(o,Id)||(function(a){return j(a,Di)&&!j(a,Pn)&&!j(a,Yt)})(s))(t,e)?j(t,rt)?Ld:Di:j(t,"PaleMoon/")?jd:j(t,Kr+"/")?Kr:j(t,Xn)?Xn:j(t,"MSIE")||j(t,"Trident/")?nl:j(t,"Gecko")?Xn:"")},ng={[Rd]:[new RegExp("rv:"+we)],[Td]:[new RegExp(rl+"?\\/"+we)],[Pn]:[new RegExp("("+Pn+"|CrMo)\\/"+we)],[Fd]:[new RegExp("CriOS\\/"+we)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+we)],[Di]:[po],[Ld]:[po],[il]:[new RegExp("(Opera|OPR)\\/"+we)],[Xn]:[new RegExp(Xn+"\\/"+we)],[$d]:[new RegExp("FxiOS\\/"+we)],[Qo]:[new RegExp("Konqueror[:/]?"+we,"i")],[ni]:[new RegExp(ni+" "+we),po],[Md]:[new RegExp("android\\s"+we,"i")],[Pd]:[new RegExp(Ad+"\\/"+we)],[Bd]:[new RegExp("OculusBrowser\\/"+we)],[Vr]:[new RegExp(Vr+"\\/"+we)],[Dd]:[new RegExp("YaBrowser\\/"+we)],[Gr]:[new RegExp(Gr+"\\/"+we)],[ji]:[new RegExp(ji+"\\/"+we)],[ea]:[new RegExp("(DuckDuckGo|Ddg)\\/"+we)],[jd]:[new RegExp("PaleMoon\\/"+we)],[Kr]:[new RegExp(Kr+"\\/"+we)],[Ud]:[new RegExp("GSA\\/"+we)],[nl]:[new RegExp("(rv:|MSIE )"+we)],Mozilla:[new RegExp("rv:"+we)]},ig=function(t,e,n,i){var r=Hd(t,e,n,i),s=ng[r];if(C(s))return null;for(var o=0;s.length>o;o++){var a=t.match(s[o]);if(a)return parseFloat(a[a.length-2])}return null},xc=[[new RegExp(Qn+"; "+Qn+" (.*?)[);]","i"),t=>[Qn,t&&t[1]||""]],[new RegExp(Ki,"i"),[Ki,""]],[new RegExp(Yi,"i"),[Yi,""]],[sl,[ni,""]],[new RegExp(Fi,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Zo,""];if(new RegExp(rt).test(e)&&!/IEMobile\b/.test(e))return[Fi+" "+rt,""];var n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){var i=tg[n[1]]||"";return/arm/i.test(e)&&(i="RT"),[Fi,i]}return[Fi,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>t&&t[3]?[qr,[t[3],t[4],t[5]||"0"].join(".")]:[qr,""]],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{var e="";return t&&t.length>=3&&(e=C(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+Yt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Yt+")","i"),t=>t&&t[2]?[Yt,[t[2],t[3],t[4]||"0"].join(".")]:[Yt,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{var e=["Mac OS X",""];return t&&t[1]&&(e[1]=[t[1],t[2],t[3]||"0"].join(".")),e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[Yp,""]],[/Linux|debian/i,["Linux",""]]],Ic=function(t){return eg.test(t)?Ki:Qp.test(t)?Yi:Xp.test(t)?Qn:new RegExp(Xo,"i").test(t)?Xo:new RegExp("("+Zo+"|WPDesktop)","i").test(t)?Zo:/iPad/.test(t)?xd:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?kd:sl.test(t)?ni:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(Sc,"i").test(t)?Sc:/(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(rt).test(t)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(t)||/pixel[\daxl ]{1,6}/i.test(t)&&!/pixel c/i.test(t)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(t)||/lmy47v/i.test(t)&&!/QTAQZ3/i.test(t)?Yt:Sd:new RegExp("(pda|"+rt+")","i").test(t)?Zp:new RegExp(ti,"i").test(t)&&!new RegExp(ti+" pc","i").test(t)?Od:""},rg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function kc(t,e){return typeof(n=t)=="string"&&rg.test(n)?t:e();var n}function fn(t){return t&&t.split("#")[0]}function ol(t,e){var n=setTimeout(t,e);return n?.unref&&n?.unref(),n}function Cc(t,e,n){return Wd.apply(this,arguments)}function Wd(){return(Wd=se((function*(t,e,n){var i;try{return yield Promise.race([t,new Promise(((r,s)=>{i=ol((()=>{try{n?.(),r()}catch(o){s(o)}}),e)}))])}finally{clearTimeout(i)}}))).apply(this,arguments)}var sg=t=>t instanceof Error,zd={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}},og=zd.info;function qd(t){if(mt(t))return{boolValue:t};if(typeof t=="number")return Number.isFinite(t)?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:{stringValue:String(t)};if(typeof t=="string")return{stringValue:t};if(U(t))return{arrayValue:{values:t.map((e=>qd(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function Yr(t){var e=[];for(var n in t){var i=t[n];Ye(i)||C(i)||e.push({key:n,value:qd(i)})}return e}function ag(t,e){var n=zd[t.level||"info"]||og,i=n.text,r=n.number,s=String(Date.now())+"000000",o={};e.distinctId&&(o.posthogDistinctId=e.distinctId),e.sessionId&&(o.sessionId=e.sessionId),e.windowId&&(o["window.id"]=e.windowId),H(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),H(e.lastActivityTimestamp)||(o.lastActivityTimestamp=String(e.lastActivityTimestamp)),e.currentUrl&&(o["url.full"]=e.currentUrl),e.screenName&&(o["screen.name"]=e.screenName),e.appState&&(o["app.state"]=e.appState),e.activeFeatureFlags&&e.activeFeatureFlags.length>0&&(o.feature_flags=e.activeFeatureFlags);var a=I({},o,t.attributes||{}),l={timeUnixNano:s,observedTimeUnixNano:s,severityNumber:r,severityText:i,body:{stringValue:t.body},attributes:Yr(a)};return t.trace_id&&(l.traceId=t.trace_id),t.span_id&&(l.spanId=t.span_id),C(t.trace_flags)||(l.flags=t.trace_flags),l}function Vd(t,e,n){return I({},t.resourceAttributes,{"service.name":t.serviceName||"unknown_service"},t.environment&&{"deployment.environment":t.environment},t.serviceVersion&&{"service.version":t.serviceVersion},{"telemetry.sdk.name":e,"telemetry.sdk.version":n})}function Gd(t,e,n,i){return{resourceLogs:[{resource:{attributes:Yr(e)},scopeLogs:[{scope:{name:n,version:i},logRecords:t}]}]}}let lg=class{constructor(t,e,n,i,r,s,o){var a;s===void 0&&(s=()=>Promise.resolve()),this._instance=t,this.Ne=e,this.rt=n,this.ut=i,this.ht=r,this.dt=s,this.vt=o,this.ct=null,this.ft=0,this.yt=0,this.bt=0,this._t=0,this.wt=!1,this.kt=e.maxBufferSize,this.xt=Math.max((a=e.maxQueueSize)!==null&&a!==void 0?a:e.maxBufferSize,e.maxBufferSize),this.St=e.flushIntervalMs,this.Ct=e.maxBatchRecordsPerPost,this.Mt=e.rateCapWindowMs,this.Tt=e.maxLogsPerInterval}reset(){this.Et(),this.ct=null,this.bt=0,this._t=0,this.wt=!1,this.ft=0,this.yt=0,this.Ct=this.Ne.maxBatchRecordsPerPost}onReconnect(){this.yt=0,this.It()}captureLog(t){if(!this._instance.isDisabled&&!this._instance.optedOut&&t!=null&&t.body){var e=this.Pt(t);if(e!==null)if(e.body){if(this.Rt()){var n={record:ag(e,this.ut())};this.ht((()=>this.At(n)))}}else this.rt.info("Log was rejected in beforeSend function")}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Log was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for log:",o),null}return i}Rt(){if(this.Tt===void 0)return!0;var t=Date.now(),e=t-this.bt;return this.Mt>e&&e>=0||(this.bt=t,this._t=0,this.wt=!1),this.Tt>this._t?(this._t++,!0):(this.wt||(this.rt.warn("captureLog dropping logs: exceeded "+this.Tt+" logs per "+this.Mt+"ms"),this.wt=!0),!1)}flush(){var t=this;return se((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return se((function*(){var e;t.Et();var n=(e=t._instance.getPersistedProperty(Ut.LogsQueue))!==null&&e!==void 0?e:[];if(n.length!==0)for(var i=n.length,r=0;n.length>0&&i>r;){var s,o;t.ft=0;var a=Math.min(n.length,t.Ct),l=n.slice(0,a),u=Gd(l.map((d=>d.record)),t.Lt(),(s=t.vt)!==null&&s!==void 0?s:t._instance.getLibraryId(),t._instance.getLibraryVersion()),c=yield t._instance.Ot(u);if(c.kind==="too-large"&&l.length>1)t.Ct=Math.max(1,Math.floor(l.length/2)),t.rt.warn("Received 413 when sending logs batch of size "+l.length+", reducing batch size to "+t.Ct);else if(c.kind==="retry-later"||(c.kind==="too-large"?t.rt.warn("Dropping a single log record after 413 with batch size 1 — the record is larger than the server cap and cannot be split further."):c.kind==="ok"&&t.Ne.maxBatchRecordsPerPost>t.Ct&&(t.Ct=Math.min(t.Ne.maxBatchRecordsPerPost,t.Ct+1)),yield t.Dt(l.length),n=(o=t._instance.getPersistedProperty(Ut.LogsQueue))!==null&&o!==void 0?o:[],r+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return se((function*(){var n,i=Math.max(0,t-e.ft),r=(n=e._instance.getPersistedProperty(Ut.LogsQueue))!==null&&n!==void 0?n:[];e._instance.setPersistedProperty(Ut.LogsQueue,r.slice(i)),yield e.dt()}))()}Lt(){return Vd(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var n=(e=this._instance.getPersistedProperty(Ut.LogsQueue))!==null&&e!==void 0?e:[];this.xt>n.length||(n.shift(),this.ft++,this.rt.info("Logs queue is full, dropping oldest record.")),n.push(t),this._instance.setPersistedProperty(Ut.LogsQueue,n),this.kt>n.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=ol((()=>{this.Nt=void 0,this.It()}),t))}qt(){var t=Math.min(Math.max(0,this.yt-1),6);return this.St*Math.pow(2,t)}jt(){var t=this._instance.getPersistedProperty(Ut.LogsQueue);return!!t&&t.length>0}shutdown(t){var e=this;return se((function*(){e.Et();var n=e.flush().catch((()=>{}));t!==void 0?yield Cc(n,t):yield n}))()}flushWithTimeout(t){var e=this;return se((function*(){var n=e.flush();yield Cc(n,t,(()=>{n.catch((()=>{}))}))}))()}It(){this.flush().then((()=>{this.yt=0}),(t=>{this.yt++,this.rt.error("PostHog logs flush failed:",t)})).finally((()=>{!this._instance.isDisabled&&this.jt()&&this.$t(this.qt())}))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}};var go=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function Ac(t){return String(t)+"000000"}function Pc(t,e,n,i){var r="";return i&&(r=Object.keys(i).sort().map((s=>JSON.stringify(s)+":"+JSON.stringify(i[s]))).join(",")),t+"\0"+e+"\0"+(n??"")+"\0"+r}let cg=class{constructor(t,e,n){this._instance=t,this.Ne=e,this.rt=n,this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Wt=0}count(t,e,n){e===void 0&&(e=1),this.Vt({name:t,type:"count",value:e,unit:n?.unit,attributes:n?.attributes})}gauge(t,e,n){this.Vt({name:t,type:"gauge",value:e,unit:n?.unit,attributes:n?.attributes})}histogram(t,e,n){this.Vt({name:t,type:"histogram",value:e,unit:n?.unit,attributes:n?.attributes})}flush(){var t=this,e=this.ct,n=(function(){var r=se((function*(){e&&(yield e.catch((()=>{}))),yield t.Zt()}));return function(){return r.apply(this,arguments)}})(),i=n().finally((()=>{this.ct===i&&(this.ct=null)}));return this.ct=i,i}drainWindow(){if(this.Bt.size===0)return null;var t=this.Bt;return this.Bt=new Map,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Gt(t)}reset(){this.Wt++,this.Et(),this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set}Vt(t){if(!this._instance.isDisabled&&!this._instance.optedOut){var e=this.Pt(t);if(e!==null)if(e.name&&typeof e.name=="string")if(typeof e.value=="number"&&Number.isFinite(e.value))if(e.type==="count"&&0>e.value)this.rt.warn("Dropping count '"+e.name+"': counters are monotonic, value must be >= 0");else{var n,i;try{n=e.attributes?I({},e.attributes):void 0,i=Pc(e.type,e.name,e.unit,n)}catch(o){return void this.rt.warn("Dropping metric '"+e.name+"': attributes could not be serialized",o)}var r=this.Bt.get(i);if(!r){if(!this.Qt())return;r={name:e.name,type:e.type,unit:e.unit,attributes:n,windowStartMs:Date.now()},this.Bt.set(i,r)}var s=this.Ut.get(e.name);s===void 0?this.Ut.set(e.name,e.type):s===e.type||this.zt.has(e.name)||(this.zt.add(e.name),this.rt.warn("Metric name '"+e.name+"' is already used as a "+s+"; recording it as a "+e.type+" too will blend both series in charts. Use a distinct name.")),this.Kt(r,e.value),this.$t()}else this.rt.warn("Dropping metric '"+e.name+"': value must be a finite number");else this.rt.warn("Dropping metric with empty name")}}Qt(){return this.Ne.maxSeriesPerFlush>this.Bt.size||(this.Ht||(this.Ht=!0,this.rt.warn("Metric series cap reached ("+this.Ne.maxSeriesPerFlush+" per flush window); dropping new series until the next flush. Reduce attribute cardinality.")),!1)}Kt(t,e){var n;switch(t.type){case"count":t.total=((n=t.total)!==null&&n!==void 0?n:0)+e;break;case"gauge":t.last=e;break;case"histogram":t.hist||(t.hist={count:0,sum:0,min:e,max:e,bucketCounts:new Array(go.length+1).fill(0)});var i=t.hist;i.count+=1,i.sum+=e,i.min=Math.min(i.min,e),i.max=Math.max(i.max,e),i.bucketCounts[(function(r,s){for(var o=0;s.length>o;o++)if(s[o]>=r)return o;return s.length})(e,go)]+=1}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Metric was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for metric:",o),null}return i}$t(){this.Nt||(this.Nt=ol((()=>{this.Nt=void 0,this.flush().catch((t=>{this.rt.error("Metrics flush failed:",t)}))}),this.Ne.flushIntervalMs))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}Zt(){var t=this;return se((function*(){if(t.Bt.size!==0){var e=t.Bt;t.Bt=new Map,t.Ht=!1,t.Ut=new Map,t.zt=new Set;var n=t.Wt,i=yield t._instance.Jt(t.Gt(e));if(n===t.Wt)switch(i.kind){case"ok":return;case"retry-later":return t.Yt(e),void t.$t();case"too-large":return void t.rt.warn("Metrics batch exceeded the server size limit and was dropped");case"fatal":return void t.rt.error("Failed to send metrics batch:",i.error)}}}))()}Gt(t){return e=this.Xt(t),n=(function(s,o,a){return I({},s.resourceAttributes,{"service.name":s.serviceName||"unknown_service"},s.environment&&{"deployment.environment":s.environment},s.serviceVersion&&{"service.version":s.serviceVersion},{"telemetry.sdk.name":o,"telemetry.sdk.version":a})})(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion()),i=this._instance.getLibraryId(),r=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:Yr(n)},scopeMetrics:[{scope:{name:i,version:r},metrics:e}]}]};var e,n,i,r}Xt(t){var e=Ac(Date.now()),n=new Map;for(var i of t.values()){var r,s=Pc(i.type,i.name,i.unit,void 0),o=n.get(s);o||(o=I({name:i.name},i.unit&&{unit:i.unit}),i.type==="count"?o.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:i.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:1,dataPoints:[]},n.set(s,o));var a=Yr((r=i.attributes)!==null&&r!==void 0?r:{}),l=Ac(i.windowStartMs);if(i.type==="count"){var u,c={attributes:a,startTimeUnixNano:l,timeUnixNano:e,asDouble:(u=i.total)!==null&&u!==void 0?u:0};o.sum.dataPoints.push(c)}else if(i.type==="gauge"){var d,h={attributes:a,timeUnixNano:e,asDouble:(d=i.last)!==null&&d!==void 0?d:0};o.gauge.dataPoints.push(h)}else i.hist&&o.histogram.dataPoints.push({attributes:a,startTimeUnixNano:l,timeUnixNano:e,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:go})}return Array.from(n.values())}Yt(t){var e,n;for(var i of t){var r=i[0],s=i[1],o=this.Bt.get(r);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,s.windowStartMs),o.type){case"count":o.total=((e=o.total)!==null&&e!==void 0?e:0)+((n=s.total)!==null&&n!==void 0?n:0);break;case"gauge":break;case"histogram":if(s.hist)if(o.hist){o.hist.count+=s.hist.count,o.hist.sum+=s.hist.sum,o.hist.min=Math.min(o.hist.min,s.hist.min),o.hist.max=Math.max(o.hist.max,s.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=s.hist.bucketCounts[a]}else o.hist=s.hist}else this.Qt()&&this.Bt.set(r,s)}}};var vr,Fc,mo;function ug(t){var e=globalThis._posthogChunkIds;if(e){var n=Object.keys(e);return mo&&n.length===Fc||(Fc=n.length,mo=n.reduce(((i,r)=>{vr||(vr={});var s=vr[r];if(s)i[s[0]]=s[1];else for(var o=t(r),a=o.length-1;a>=0;a--){var l=o[a],u=l?.filename,c=e[r];if(u&&c){i[u]=c,vr[r]=[u,c];break}}return i}),{})),mo}}class dg{constructor(e,n,i){i===void 0&&(i=[]),this.coercers=e,this.stackParser=n,this.modifiers=i}buildFromUnknown(e,n){n===void 0&&(n={});var i=n&&n.mechanism||{handled:!0,type:"generic"},r=this.buildCoercingContext(i,n,0).apply(e),s=this.buildParsingContext(n),o=this.parseStacktrace(r,s);return{$exception_list:this.convertToExceptionList(o,i),$exception_level:"error"}}modifyFrames(e){var n=this;return se((function*(){for(var i of e)i.stacktrace&&i.stacktrace.frames&&U(i.stacktrace.frames)&&(i.stacktrace.frames=yield n.applyModifiers(i.stacktrace.frames));return e}))()}coerceFallback(e){var n;return{type:"Error",value:"Unknown error",stack:(n=e.syntheticException)==null?void 0:n.stack,synthetic:!0}}parseStacktrace(e,n){var i,r;return e.cause!=null&&(i=this.parseStacktrace(e.cause,n)),e.stack!=""&&e.stack!=null&&(r=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?n.skipFirstLines:0),n.chunkIdMap)),I({},e,{cause:i,stack:r})}applyChunkIds(e,n){return e.map((i=>(i.filename&&n&&(i.chunk_id=n[i.filename]),i)))}applyCoercers(e,n){for(var i of this.coercers)if(i.match(e))return i.coerce(e,n);return this.coerceFallback(n)}applyModifiers(e){var n=this;return se((function*(){var i=e;for(var r of n.modifiers)i=yield r(i);return i}))()}convertToExceptionList(e,n){var i,r,s,o={type:e.type,value:e.value,mechanism:{type:(i=n.type)!==null&&i!==void 0?i:"generic",handled:(r=n.handled)===null||r===void 0||r,synthetic:(s=e.synthetic)!==null&&s!==void 0&&s}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,I({},n,{handled:!0}))),a}buildParsingContext(e){var n;return{chunkIdMap:ug(this.stackParser),skipFirstLines:(n=e.skipFirstLines)!==null&&n!==void 0?n:1}}buildCoercingContext(e,n,i){i===void 0&&(i=0);var r=(s,o)=>{if(4>=o){var a=this.buildCoercingContext(e,n,o);return this.applyCoercers(s,a)}};return I({},n,{syntheticException:i==0?n.syntheticException:void 0,mechanism:e,apply:s=>r(s,i),next:s=>r(s,i+1)})}}var ii="?";function ta(t,e,n,i,r){var s={platform:t,filename:e,function:n===""?ii:n,in_app:!0};return C(i)||(s.lineno=i),C(r)||(s.colno=r),s}var Kd=(t,e)=>{var n=t.indexOf("safari-extension")!==-1,i=t.indexOf("safari-web-extension")!==-1;return n||i?[t.indexOf("@")!==-1?t.split("@")[0]:ii,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},fg=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,hg=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,pg=/\((\S*)(?::(\d+))(?::(\d+))\)/,gg=(t,e)=>{var n=fg.exec(t);if(n)return ta(e,n[1],ii,+n[2],+n[3]);var i=hg.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var r=pg.exec(i[2]);r&&(i[2]=r[1],i[3]=r[2],i[4]=r[3])}var s=Kd(i[1]||ii,i[2]);return ta(e,s[1],s[0],i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},mg=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,vg=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,_g=(t,e)=>{var n=mg.exec(t);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){var i=vg.exec(n[3]);i&&(n[1]=n[1]||"eval",n[3]=i[1],n[4]=i[2],n[5]="")}var r=n[3],s=n[1]||ii,o=Kd(s,r);return ta(e,r=o[1],s=o[0],n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},Rc=/\(error: (.*)\)/;class yg{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,n){var i=X(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:i?e.stack:void 0,cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var n=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?n+": "+e.message:n}isDOMException(e){return zr(e,"DOMException")}isDOMError(e){return zr(e,"DOMError")}}class wg{match(e){return(function(n){switch({}.toString.call(n)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return Ed(n,Error)}})(e)}coerce(e,n){return{type:this.getType(e),value:this.getMessage(e,n),stack:this.getStack(e),cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,n){var i=e.message;return String(i.error&&typeof i.error.message=="string"?i.error.message:i)}getStack(e){return e.stacktrace||e.stack||void 0}}class bg{constructor(){}match(e){return!!zr(e,"ErrorEvent")&&(e.error!=null||this.fe(e))}coerce(e,n){var i;if(e.error!=null)return n.apply(e.error);var r=n.apply(e.message);return I({},r,{stack:(i=this.pe(e))!==null&&i!==void 0?i:r.stack,synthetic:!0})}fe(e){return X(e.message)&&e.message.length>0}pe(e){var n=e;if(X(n.filename)&&n.filename.length>0){var i,r,s=(i=n.lineno)!==null&&i!==void 0?i:0,o=(r=n.colno)!==null&&r!==void 0?r:0;return`Error + at `+n.filename+":"+s+":"+o}}}var Eg=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class Sg{match(e){return typeof e=="string"}coerce(e,n){var i,r=this.getInfos(e),s=r[0],o=r[1];return{type:s??"Error",value:o??e,stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}getInfos(e){var n="Error",i=e,r=e.match(Eg);return r&&(n=r[1],i=r[2]),[n,i]}}var xg=["fatal","error","warning","log","info","debug"];function Yd(t,e){e===void 0&&(e=40);var n=Object.keys(t);if(n.sort(),!n.length)return"[object has no keys]";for(var i=n.length;i>0;i--){var r=n.slice(0,i).join(", ");if(e>=r.length)return i===n.length?r:r.length>e?r.slice(0,e)+"...":r}return""}class Ig{match(e){return typeof e=="object"&&e!==null}coerce(e,n){var i,r,s=this.getErrorPropertyFromObject(e);return s?n.apply(s):{type:this.getType(e),value:this.getValue(e),stack:(i=this.getStack(e))!==null&&i!==void 0?i:(r=n.syntheticException)==null?void 0:r.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return tl(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var n="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(n+=" with message: '"+e.message+"'"),n}if("message"in e&&typeof e.message=="string")return e.message;var i=this.getObjectClassName(e);return(i&&i!=="Object"?"'"+i+"'":"Object")+" captured as exception with keys: "+Yd(e)}isSeverityLevel(e){return X(e)&&!Jo(e)&&xg.indexOf(e)>=0}getStack(e){try{return X(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:X(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(var n in e)if({}.hasOwnProperty.call(e,n)){var i=e[n];if(sg(i))return i}}getObjectClassName(e){try{var n=Object.getPrototypeOf(e);return n?n.constructor.name:void 0}catch{return}}}class kg{match(e){return tl(e)}coerce(e,n){var i,r=e.constructor.name;return{type:r,value:r+" captured as exception with keys: "+Yd(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class Cg{match(e){return bd(e)}coerce(e,n){var i;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class Ag{match(e){return zr(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!tl(e))return!1;try{var n=e.detail;return n!=null&&typeof n=="object"&&"reason"in n}catch{return!1}}coerce(e,n){var i,r=this.getUnhandledRejectionReason(e);return bd(r)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(r),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}:n.apply(r)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}}var Jr="$message",Zr="$timestamp",Pg=new Set([Jr,Zr]),vo={enabled:!0,max_bytes:32768};function Xr(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:vo.enabled,max_bytes:Rg(t.max_bytes,vo.max_bytes)}:I({},vo)}class Fg{constructor(e){this.Ke=[],this.Je=0,this.Ne=Xr(e)}setConfig(e){this.Ne=Xr(e),this.Xe()}add(e){var n=(function(r){var s;try{s=_d(r)}catch{return}try{var o=JSON.parse(s);if(!he(o))return;var a=o,l=a[Jr],u=a[Zr];return!X(l)||l.trim().length===0||!X(u)&&!ke(u)?void 0:{step:a,json:s}}catch{return}})(e);if(n){var i=(function(r){if(typeof TextEncoder<"u")return new TextEncoder().encode(r).length;for(var s=encodeURIComponent(r),o=0,a=0;s.length>a;a++)s[a]==="%"?(o+=1,a+=2):o+=1;return o})(n.json);i>this.Ne.max_bytes||(this.Ke.push({step:n.step,bytes:i}),this.Je+=i,this.Xe())}}getAttachable(){return this.Ke.map((e=>e.step))}clear(){this.Ke=[],this.Je=0}size(){return this.Ke.length}Xe(){for(;this.Je>this.Ne.max_bytes&&this.Ke.length>0;){var e=this.Ke.shift();e&&(this.Je-=e.bytes)}}}function Rg(t,e){if(!ke(t)||t===1/0||t===-1/0)return e;var n=Math.floor(t);return 0>n?e:n}var Jd=function(t,e){var n=(e===void 0?{}:e).debugEnabled,i={k(r){if(w&&(ne.DEBUG||w.POSTHOG_DEBUG||n)&&!C(w.console)&&w.console){for(var s=("__rrweb_original__"in w.console[r])?w.console[r].__rrweb_original__:w.console[r],o=arguments.length,a=new Array(o>1?o-1:0),l=1;o>l;l++)a[l-1]=arguments[l];s(t,...a)}},debug(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("debug",...s)},info(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("log",...s)},warn(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("warn",...s)},error(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("error",...s)},critical(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];console.error(t,...s)},uninitializedWarning(r){i.error("You must initialize PostHog before calling "+r)},createLogger:(r,s)=>Jd(t+" "+r,s)};return i},A=Jd("[PostHog.js]"),pe=A.createLogger,Tg=pe("[ExternalScriptsLoader]"),_o=(t,e,n)=>{if(t.config.disable_external_dependency_loading)return Tg.warn(e+" was requested but loading of external scripts is disabled."),n("Loading of external scripts is disabled");var i=P?.querySelectorAll("script");if(i){for(var r,s=function(){if(i[o].src===e){var l=i[o];return l.__posthog_loading_callback_fired?{v:n()}:(l.addEventListener("load",(u=>{l.__posthog_loading_callback_fired=!0,n(void 0,u)})),l.onerror=u=>n(u),{v:void 0})}},o=0;i.length>o;o++)if(r=s())return r.v}var a=()=>{if(!P)return n("document not found");var l=P.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=d=>{l.__posthog_loading_callback_fired=!0,n(void 0,d)},l.onerror=d=>n(d),t.config.prepare_external_dependency_script&&(l=t.config.prepare_external_dependency_script(l)),!l)return n("prepare_external_dependency_script returned null");if(t.config.external_scripts_inject_target==="head")P.head.appendChild(l);else{var u,c=P.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):P.body.appendChild(l)}};P!=null&&P.body?a():P?.addEventListener("DOMContentLoaded",a)};B.__PosthogExtensions__=B.__PosthogExtensions__||{},B.__PosthogExtensions__.loadExternalDependency=(t,e,n)=>{if(e!=="remote-config"){var i;if(t.config.strict_script_versioning)i=t.requestRouter.endpointFor("assets","/static/"+t.version+"/"+e+".js");else{var r="/static/"+e+".js?v="+t.version;if(e==="toolbar"){var s=3e5;r=r+"&t="+Math.floor(Date.now()/s)*s}i=t.requestRouter.endpointFor("assets",r)}_o(t,i,n)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");_o(t,o,n)}},B.__PosthogExtensions__.loadSiteApp=(t,e,n)=>{var i=t.requestRouter.endpointFor("api",e);_o(t,i,n)};ne.DEBUG=!1,ne.LIB_VERSION="1.415.7",ne.LIB_NAME="web";var Zd="$people_distinct_id",Ji="$device_id",yo="$device_model",Ri="__alias",Ti="__timers",na="$autocapture_disabled_server_side",ia="$heatmaps_enabled_server_side",ra="$exception_capture_enabled_server_side",sa="$error_tracking_suppression_rules",oa="$error_tracking_capture_extension_exceptions",aa="$web_vitals_enabled_server_side",al="$dead_clicks_enabled_server_side",ll="$product_tours_enabled_server_side",la="$web_vitals_allowed_metrics",An="$session_recording_remote_config",Xd="$replay_sample_rate",Qd="$replay_override_sampling",ef="$replay_override_linked_flag",tf="$replay_override_url_trigger",nf="$replay_override_event_trigger",Yn="$sesid",cl="$session_is_sampled",Sn="$enabled_feature_flags",$i="$active_feature_flags",Fr="$early_access_features",ca="$feature_flag_details",Mi="$feature_flag_payloads",Rr="$feature_flag_request_id",Qr="$minimal_flag_called_events",It="$override_feature_flags",xn="$override_feature_flag_payloads",jt="$stored_person_properties",In="$stored_group_properties",ua="$surveys",es="$surveys_loaded_at",da="$surveys_activated",Tr="$surveys_activated_session",$r="$surveys_activated_timestamps",Li="ph_product_tours",Cn="$flag_call_reported",Ni="$flag_call_reported_session_id",Mr="$feature_flag_errors",Ui="$feature_flag_evaluated_at",at="$user_state",fa="$client_session_props",ha="$capture_rate_limit",pa="$initial_campaign_params",ga="$initial_referrer_info",ts="$initial_person_info",ns="$epp",_r="$posthog_cookieless",rf="$cookieless_mode",sf="$sdk_debug_extensions_init_method",of="$sdk_debug_extensions_init_time_ms",af="$sdk_debug_recording_script_not_loaded",ul="PostHog loadExternalDependency extension not found.",kn="on_reject",Wt="always",Hn="anonymous",vn="identified",ma="identified_only",is="visibilitychange",rs="beforeunload",Gn="$pageview",wo="$pageleave",bo="$identify",Tc="$groupidentify";function yr(t,e){U(t)&&t.forEach(e)}function ie(t,e){if(!H(t))if(U(t))t.forEach(e);else if(Wp(t))t.forEach(((i,r)=>e(i,r)));else for(var n in t)wd.call(t,n)&&e(t[n],n)}var fe=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;e>i;i++)n[i-1]=arguments[i];for(var r of n)for(var s in r)r[s]!==void 0&&(t[s]=r[s]);return t};function Lr(t){for(var e=Object.keys(t),n=e.length,i=new Array(n);n--;)i[n]=[e[n],t[e[n]]];return i}var $c=function(t){try{return t()}catch{return}},$g=function(t){return function(){try{for(var e=arguments.length,n=new Array(e),i=0;e>i;i++)n[i]=arguments[i];return t.apply(this,n)}catch(r){A.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),A.critical(r)}}},dl=function(t){var e={};return ie(t,(function(n,i){(X(n)&&n.length>0||ke(n))&&(e[i]=n)})),e},Mg=["herokuapp.com","vercel.app","netlify.app"];function Lg(t){var e=t?.hostname;if(!X(e))return!1;var n=e.split(".").slice(-2).join(".");for(var i of Mg)if(n===i)return!1;return!0}function ve(t,e,n,i){var r=i??{},s=r.capture,o=r.passive;t?.addEventListener(e,n,{capture:s!==void 0&&s,passive:o===void 0||o})}function va(t){return t.name==="ph_toolbar_internal"}var lf=t=>{if(P){try{for(var e=t+"=",n=P.cookie.split(";").filter((s=>s.length)),i=0;n.length>i;i++){for(var r=n[i];r.charAt(0)==" ";)r=r.substring(1,r.length);if(r.indexOf(e)===0)return decodeURIComponent(r.substring(e.length,r.length))}}catch{}return null}};Math.trunc||(Math.trunc=function(t){return 0>t?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return ke(t)&&isFinite(t)&&Math.floor(t)===t});class ss{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,n,i,r){if(!Number.isInteger(e)||!Number.isInteger(n)||!Number.isInteger(i)||!Number.isInteger(r)||0>e||0>n||0>i||0>r||e>0xffffffffffff||n>4095||i>1073741823||r>4294967295)throw new RangeError("invalid field value");var s=new Uint8Array(16);return s[0]=e/Math.pow(2,40),s[1]=e/Math.pow(2,32),s[2]=e/Math.pow(2,24),s[3]=e/Math.pow(2,16),s[4]=e/256,s[5]=e,s[6]=112|n>>>8,s[7]=n,s[8]=128|i>>>24,s[9]=i>>>16,s[10]=i>>>8,s[11]=i,s[12]=r>>>24,s[13]=r>>>16,s[14]=r>>>8,s[15]=r,new ss(s)}toString(){for(var e="",n=0;this.bytes.length>n;n++)e=e+(this.bytes[n]>>>4).toString(16)+(15&this.bytes[n]).toString(16),n!==3&&n!==5&&n!==7&&n!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new ss(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var n=0;16>n;n++){var i=this.bytes[n]-e.bytes[n];if(i!==0)return Math.sign(i)}return 0}}class Ng{generate(){var e=this.generateOrAbort();if(!C(e))return e;this.S=0;var n=this.generateOrAbort();if(C(n))throw new Error("Could not generate UUID after timestamp reset");return n}generateOrAbort(){var e=Date.now();if(e>this.S)this.S=e,this.C();else{if(this.S>=e+1e4)return;this.I++,this.I>4398046511103&&(this.S++,this.C())}return ss.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 Og}}var Mc,cf=t=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;t.length>e;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};w&&!C(w.crypto)&&crypto.getRandomValues&&(cf=t=>crypto.getRandomValues(t));class Og{nextUint32(){return this.R.length>this.O||(cf(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var Ht=()=>Bg().toString(),Bg=()=>(Mc||(Mc=new Ng)).generate(),wi="",Dg=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,zt={N:()=>!!P,j(t){A.error("cookieStore error: "+t)},P:lf,H(t){var e;try{e=JSON.parse(zt.P(t))||{}}catch{}return e},F(t,e,n,i,r){if(!P)return!1;try{var s="",o="",a=(function(c,d){if(d){var h=(function(p,g){if(g===void 0&&(g=P),wi)return wi;if(!g||["localhost","127.0.0.1"].includes(p))return"";for(var m=p.split("."),v=Math.min(m.length,8),E="dmn_chk_"+Ht();!wi&&v--;){var S=m.slice(v).join("."),_=E+"=1;domain=."+S+";path=/";g.cookie=_+";max-age=3",g.cookie.includes(E)&&(g.cookie=_+";max-age=0",wi=S)}return wi})(c);if(!h){var f=(p=>{var g=p.match(Dg);return g?g[0]:""})(c);f!==h&&A.info("Warning: cookie subdomain discovery mismatch",f,h),h=f}return h?"; domain=."+h:""}return""})(P.location.hostname,i);if(n){var l=new Date;l.setTime(l.getTime()+864e5*n),s="; expires="+l.toUTCString()}r&&(o="; secure");var u=t+"="+encodeURIComponent(JSON.stringify(e))+s+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&A.warn("cookieStore warning: large cookie, len="+u.length),P.cookie=u,!0}catch{return!1}},q(t,e){if(P!=null&&P.cookie)try{zt.F(t,"",-1,e)}catch{return}}},Eo=null,le={N(){if(!Ye(Eo))return Eo;var t=!0;if(C(w))t=!1;else try{var e="__mplssupport__";le.F(e,"xyz"),le.P(e)!=='"xyz"'&&(t=!1),le.q(e)}catch{t=!1}return t||A.error("localStorage unsupported; falling back to cookie store"),Eo=t,t},j(t){A.error("localStorage error: "+t)},P(t){try{return w?.localStorage.getItem(t)}catch(e){le.j(e)}return null},H(t){try{return JSON.parse(le.P(t))||{}}catch{}return null},F(t,e){try{return w?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(n){le.j(n)}return!1},q(t){try{w?.localStorage.removeItem(t)}catch(e){le.j(e)}}},jg=[Ji,"distinct_id",Yn,cl,ns,ts,at],wr={},Ug={N:()=>!0,j(t){A.error("memoryStorage error: "+t)},P:t=>wr[t]||null,H:t=>wr[t]||null,F:(t,e)=>(wr[t]=e,!0),q(t){delete wr[t]}},_n=null,be={N(){if(!Ye(_n))return _n;if(_n=!0,C(w))_n=!1;else try{var t="__support__";be.F(t,"xyz"),be.P(t)!=='"xyz"'&&(_n=!1),be.q(t)}catch{_n=!1}return _n},j(t){A.error("sessionStorage error: ",t)},P(t){try{return w?.sessionStorage.getItem(t)}catch(e){be.j(e)}return null},H(t){try{return JSON.parse(be.P(t))||null}catch{}return null},F(t,e){try{return w?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(n){be.j(n)}return!1},q(t){try{w?.sessionStorage.removeItem(t)}catch(e){be.j(e)}}};class Hg{constructor(e){this._instance=e}get Ne(){return this._instance.config}get consent(){return this.ti()?0:this.ei}isOptedOut(){return this.Ne.cookieless_mode===Wt||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===kn}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===0}isRejected(){return this.consent===0||this.consent===-1&&this.Ne.opt_out_capturing_by_default}optInOut(e){this.ii.F(this.ri,e?1:0,this.Ne.cookie_expiration,this.Ne.cross_subdomain_cookie,this.Ne.secure_cookie)}reset(){this.ii.q(this.ri,this.Ne.cross_subdomain_cookie)}get ri(){var e=this._instance.config,n=e.token,i=e.opt_out_capturing_cookie_prefix;return e.consent_persistence_name||(i?i+n:"__ph_opt_in_out_"+n)}get ei(){var e=this.ii.P(this.ri);return ho(e)?1:j(Gp,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,n=e==="localStorage"?le:zt;if(!this.ni||this.ni!==n){this.ni=n;var i=e==="localStorage"?zt:le;i.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(ho(i.P(this.ri))),i.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[He?.doNotTrack,He?.msDoNotTrack,B.doNotTrack].some((e=>ho(e)))}}function uf(t,e){var n,i=t==null||(n=t.config)==null?void 0:n.get_current_url;if(!je(i))return e;try{var r=i(e);return X(r)&&r?r:e}catch(s){return A.error("Error in get_current_url, falling back to window.location.href",s),e}}var df="__POSTHOG_TOOLBAR__",Wg=1,zg=3,qg=11;function Lc(t){return t instanceof Element&&(t.id===df||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function hn(t){return!!t&&t.nodeType===Wg}function et(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function ff(t){return!!t&&t.nodeType===zg}function hf(t){return!!t&&t.nodeType===qg&&hn(t.host)}var pf=1e3;function fl(t){return t?ks(t).split(/\s+/):[]}function Nc(t,e){var n=(function(i){var r,s=w==null||(r=w.location)==null?void 0:r.href;return C(s)?void 0:uf(i,s)})(e);return!!(n&&t&&t.some((i=>n.match(i))))}function os(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 fl(e)}function gf(t){return H(t)?null:ks(t).split(/(\s+)/).filter((e=>Hi(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function Zi(t){var e="";return ya(t)&&!yf(t)&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;ff(n)&&n.textContent&&(e+=(i=gf(n.textContent))!==null&&i!==void 0?i:"")})),ks(e)}function So(t){var e;return C(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var hl=["a","button","form","input","select","textarea","label"];function _a(t,e){if(C(e))return!0;var n,i=function(s){if(e.some((o=>(function(a,l){var u=a.matches||a.matchesSelector||a.msMatchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.oMatchesSelector;try{return!!u&&u.call(a,l)}catch{return!1}})(s,o))))return{v:!0}};for(var r of t)if(n=i(r))return n.v;return!1}function mf(t){var e=t.parentNode;return!(!e||!hn(e))&&e}var Vg=[".ph-no-autocapture","[data-ph-no-autocapture]"],vf=["next","previous","prev",">","<"],Gg=[...vf,"+","-","−","–"],Oc=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,Bc=[".ph-no-rageclick",".ph-no-capture"],Kg=["","text","search","email","password","url","tel","number"];function Dc(t,e){if(!w||pl(t))return!1;var n,i,r,s,o;if(mt(e)?(n=!!e&&Bc,i=void 0,r=!1):(n=(s=e?.css_selector_ignorelist)!==null&&s!==void 0?s:Bc,i=e?.content_ignorelist,r=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),n===!1||r&&(function(l){return!(!l||!hn(l))&&(!!et(l,"textarea")||(et(l,"input")?j(Kg,(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=_f(t,!1).targetElementList;return!(function(l,u){if(l===!1||C(l))return!1;var c;if(l===!0)c=vf;else{if(!U(l))return!1;if(l.length>10)return A.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var h=d.safeText,f=d.ariaLabel;return c.some((p=>Oc(h,p)||Oc(f,p)))}))})(i,a.map((l=>{var u;return{safeText:Zi(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!_a(a,n)}var pl=t=>!t||et(t,"html")||!hn(t),_f=(t,e)=>{if(!w||pl(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,i=[t],r=t;r.parentNode&&!et(r,"body");)if(hf(r.parentNode))i.push(r.parentNode.host),r=r.parentNode.host;else{var s=mf(r);if(!s)break;if(e||hl.indexOf(s.tagName.toLowerCase())>-1)n=!0;else try{var o=w.getComputedStyle(s);o&&o.getPropertyValue("cursor")==="pointer"&&(n=!0)}catch{}i.push(s),r=s}return{parentIsUsefulElement:n,targetElementList:i}};function ya(t){for(var e=new Set,n=0,i=t;i.parentNode&&!et(i,"body");i=i.parentNode){if(n++>=pf||e.has(i))return!1;e.add(i);var r=os(i);if(j(r,"ph-sensitive")||j(r,"ph-no-capture"))return!1}if(j(os(t),"ph-include"))return!0;var s=t.type||"";if(X(s))switch(s.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!X(o)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(o.replace(/[^a-zA-Z0-9]/g,""))}function yf(t){return!!(et(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||et(t,"select")||et(t,"textarea")||t.getAttribute("contenteditable")==="true")}var jc=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}))$"),Uc=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,Yg=[16,15,14,13],Jg=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),Hc=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),Wc=/[0-9A-Za-z_]/;function Zg(t){for(var e=0,n=!1,i=t.length-1;i>=0;i--){var r=t.charCodeAt(i)-48;n&&(r*=2)>9&&(r-=9),e+=r,n=!n}return e%10==0}function Hi(t,e){if(e===void 0&&(e=!0),H(t))return!1;if(X(t)){t=ks(t);var n=e?jc.test((t||"").replace(/[- ]/g,"")):(function(r){var s;for(Uc.lastIndex=0;s=Uc.exec(r);){var o=s[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of Yg){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(jc.test(d)&&Zg(d))return!0}}}return!1})(t);if(n)return!1;var i=e?Jg.test(t):(function(r){var s;for(Hc.lastIndex=0;s=Hc.exec(r);){var o=s[1],a=s[3];if(!(o&&a&&Wc.test(o)&&Wc.test(a)))return!0}return!1})(t);if(i)return!1}return!0}function zc(t){var e=Zi(t);return Hi(e=(e+" "+wf(t)).trim())?e:""}function wf(t){var e="";return t&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;if(n&&((i=n.tagName)==null?void 0:i.toLowerCase())==="span")try{var r=Zi(n);e=(e+" "+r).trim(),n.childNodes&&n.childNodes.length&&(e=(e+" "+wf(n)).trim())}catch(s){A.error("[AutoCapture]",s)}})),e}function qc(t){return t.replace(/"|\\"/g,'\\"')}function Xg(t){var e=t.attr__class;if(e)return U(e)?e:fl(e)}var br=pe("[Dead Clicks]"),Qg=()=>!0,em=t=>{var e,n=!((e=t.instance.persistence)==null||!e.get_property(al)),i=t.instance.config.capture_dead_clicks;return mt(i)?i:!!he(i)||n};class Vc{get lazyLoadedDeadClicksAutocapture(){return this.si}constructor(e,n,i){this.instance=e,this.isEnabled=n,this.onCapture=i,this.startIfEnabledOrStop()}onRemoteConfig(e){if(e.ok){var n=e.config;"captureDeadClicks"in n&&(this.instance.persistence&&this.instance.persistence.register({[al]:n.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var n,i;(n=B.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture?e():(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"dead-clicks-autocapture",(r=>{r?br.error("failed to load script",r):e()}))}oi(){var e;if(P){if(!this.si&&(e=B.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var n=he(this.instance.config.capture_dead_clicks)?I({},this.instance.config.capture_dead_clicks):{};n.__onCapture=this.onCapture,this.onCapture&&(n.capture_dead_swipes=!1),this.si=B.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.si.start(P),br.info("starting...")}}else br.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,br.info("stopping..."))}}var xo=pe("[SegmentIntegration]"),bf="posthog-js";function Ef(t,e){var n=e===void 0?{}:e,i=n.organization,r=n.projectId,s=n.prefix,o=n.severityAllowList,a=o===void 0?["error"]:o,l=n.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,h,f,p,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var v,E=((d=c.exception)==null?void 0:d.values)||[],S=E.map((b=>I({},b,{stacktrace:b.stacktrace?I({},b.stacktrace,{type:"raw",frames:(b.stacktrace.frames||[]).map((k=>I({},k,{platform:"web:javascript"})))}):void 0}))),_={$exception_message:((h=E[0])==null?void 0:h.value)||c.message,$exception_type:(f=E[0])==null?void 0:f.type,$exception_level:c.level,$exception_list:S,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((p=E[0])==null?void 0:p.value)||c.message,$sentry_exception_type:(g=E[0])==null?void 0:g.type,$sentry_tags:c.tags};return i&&r&&(_.$sentry_url=(s||"https://sentry.io/organizations/")+i+"/issues/?project="+r+"&query="+c.event_id),u&&((v=t.exceptions)==null||v.sendExceptionEvent(_)),c}}class tm{constructor(e,n,i,r,s,o){this.name=bf,this.setupOnce=function(a){a(Ef(e,{organization:n,projectId:i,prefix:r,severityAllowList:s,sendExceptionsToPostHog:o==null||o}))}}}class Gc{constructor(e){this.li=(n,i,r)=>{r&&(r.noSessionId||r.activityTimeout||r.sessionPastMaximumLength||r.crossTabAdoption)&&(A.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:n,changeReason:r}),this.ui=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.hi()}hi(){var e;this.di=(e=this._instance.sessionManager)==null?void 0:e.onSessionId(this.li)}destroy(){var e;(e=this.di)==null||e.call(this),this.di=void 0}doPageView(e,n){var i,r=this.vi(e,n);return this.ui={pathname:(i=w?.location.pathname)!==null&&i!==void 0?i:"",pageViewId:n,timestamp:e},this._instance.scrollManager.resetContext(),r}doPageLeave(e){var n;return this.vi(e,(n=this.ui)==null?void 0:n.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.ui)==null?void 0:e.pageViewId}}vi(e,n){var i=this.ui;if(!i)return{$pageview_id:n};var r={$pageview_id:n,$prev_pageview_id:i.pageViewId},s=this._instance.scrollManager.getContext();if(s&&!this._instance.config.disable_scroll_properties){var o=s.maxScrollHeight,a=s.lastScrollY,l=s.maxScrollY,u=s.maxContentHeight,c=s.lastContentY,d=s.maxContentY;if(!(C(o)||C(a)||C(l)||C(u)||C(c)||C(d))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),d=Math.ceil(d);var h=o>1?At(a/o,0,1,A):1,f=o>1?At(l/o,0,1,A):1,p=u>1?At(c/u,0,1,A):1,g=u>1?At(d/u,0,1,A):1;r=fe(r,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:h,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:f,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:p,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return i.pathname&&(r.$prev_pageview_pathname=i.pathname),i.timestamp&&(r.$prev_pageview_duration=(e.getTime()-i.timestamp.getTime())/1e3),r}}var Io=["flags","surveys"],nm={[Zd]:{exposure:"hidden"},[Ri]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[Ti]:{exposure:"hidden"},[na]:{exposure:"event"},[ia]:{exposure:"hidden"},[ra]:{exposure:"event"},[sa]:{exposure:"hidden"},[oa]:{exposure:"event"},[aa]:{exposure:"event"},[al]:{exposure:"event"},[ll]:{exposure:"hidden"},[la]:{exposure:"event"},[An]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[Yn]:{exposure:"hidden"},[cl]:{exposure:"event"},[Xd]:{exposure:"event",shouldSkipFromEventProperties:t=>Ye(t)},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},$sess_rec_flush_size:{exposure:"hidden"},[Sn]:{exposure:"hidden",storageGroup:"flags"},[$i]:{exposure:"hidden",storageGroup:"flags"},[Fr]:{exposure:"hidden"},[ca]:{exposure:"hidden",storageGroup:"flags"},[Mi]:{exposure:"hidden",storageGroup:"flags"},[Rr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[Qr]:{exposure:"hidden",storageGroup:"flags"},[It]:{exposure:"hidden"},[xn]:{exposure:"hidden"},[jt]:{exposure:"hidden"},[In]:{exposure:"hidden"},[ua]:{exposure:"hidden",storageGroup:"surveys"},[es]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[da]:{exposure:"event"},[Tr]:{exposure:"hidden"},[$r]:{exposure:"hidden"},[Li]:{exposure:"hidden"},$product_tours_activated:{exposure:"hidden"},$product_tours_activated_session:{exposure:"hidden"},$conversations_widget_session_id:{exposure:"event"},$conversations_ticket_id:{exposure:"event"},$conversations_widget_state:{exposure:"event"},$conversations_user_traits:{exposure:"event"},[Cn]:{exposure:"hidden"},[Ni]:{exposure:"hidden"},[Mr]:{exposure:"hidden"},[Ui]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[at]:{exposure:"hidden"},[fa]:{exposure:"hidden"},[ha]:{exposure:"hidden"},[pa]:{exposure:"hidden"},[ga]:{exposure:"hidden"},[ts]:{exposure:"hidden"},[ns]:{exposure:"hidden"},[Qd]:{exposure:"event"},[ef]:{exposure:"event"},[tf]:{exposure:"event"},[nf]:{exposure:"event"},[sf]:{exposure:"event"},[of]:{exposure:"event"},[af]:{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"}},im=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],yn=t=>{var e=nm[t];if(e)return e;for(var n of im){var i=n[1];if(t.indexOf(n[0])===0)return i}},Jn=(t,e)=>{try{return JSON.stringify(t,((n,i)=>typeof i=="bigint"?i.toString():i),e)}catch{return _d(t)}},as=t=>{var e=P?.createElement("a");return C(e)?null:(e.href=t,e)},ri=function(t,e){for(var n,i=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),r=0;i.length>r;r++){var s=i[r].split("=");if(s[0]===e){n=s;break}}if(!U(n)||2>n.length)return"";var o=n[1];try{o=decodeURIComponent(o)}catch{A.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},Xi=function(t,e,n){if(!t||!e||!e.length)return t;for(var i=t.split("#"),r=i[1],s=(i[0]||"").split("?"),o=s[1],a=s[0],l=(o||"").split("&"),u=[],c=0;l.length>c;c++){var d=l[c].split("=");U(d)&&(e.includes(d[0])?u.push(d[0]+"="+n):u.push(l[c]))}var h=a;return o!=null&&(h+="?"+u.join("&")),r!=null&&(h+="#"+r),h},ls=function(t,e){var n=t.match(new RegExp(e+"=([^&]*)"));return n?n[1]:null},Sf=(t,e)=>t>=e&&gd(),xf=(t,e,n,i)=>{if(t===0){if(gd()){var r=e+1;return r===n&&i(),r}return e}return 0},Er="https?://(.*)",si=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],rm=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...si],Qi="",sm=["li_fat_id"];function If(t,e,n){if(!P)return{};var i,r=e?[...si,...n||[]]:[],s=kf(Xi(P.URL,r,Qi),t),o=(i={},ie(sm,(function(a){var l=lf(a);i[a]=l||null})),i);return fe(o,s)}function kf(t,e){var n=rm.concat(e||[]),i={};return ie(n,(function(r){var s=ri(t,r);i[r]=s||null})),i}function Cf(t){var e=(function(s){return s?s.search(Er+"google.([^/?]*)")===0?"google":s.search(Er+"bing.com")===0?"bing":s.search(Er+"yahoo.com")===0?"yahoo":s.search(Er+"duckduckgo.com")===0?"duckduckgo":null:null})(t),n=e!="yahoo"?"q":"p",i={};if(!Ye(e)){i.$search_engine=e;var r=P?ri(P.referrer,n):"";r.length&&(i.ph_keyword=r)}return i}function Kc(){return navigator.language||navigator.userLanguage}var cs="$direct";function Af(){return P?.referrer||cs}function Pf(t,e,n){n===void 0&&(n=!1);var i=t?[...si,...e||[]]:[],r=n?fn(me?.href):me?.href,s=r?.substring(0,1e3);return{r:Af().substring(0,1e3),u:s?Xi(s,i,Qi):void 0}}function Ff(t,e){var n;e===void 0&&(e=!1);var i=t.r,r=t.u,s=e?fn(r):r,o={$referrer:i,$referring_domain:i==null?void 0:i==cs?cs:(n=as(i))==null?void 0:n.host};if(s){o.$current_url=s;var a=as(s);o.$host=a?.host,o.$pathname=a?.pathname;var l=kf(s);fe(o,l)}if(i){var u=Cf(i);fe(o,u)}return o}function Rf(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function om(){try{return new Date().getTimezoneOffset()}catch{return}}var am={flags:Ui,surveys:es},lm=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],Wn="main";class ko{constructor(e,n,i){if(i===void 0&&(i=!0),this.ci={},this.fi=!1,this.pi=!1,this.Ne=e,this.gi=i,this.props={},this.mi=void 0,this.yi=(s=>{var o="";return s.token&&(o=s.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),s.persistence_name?"ph_"+s.persistence_name:"ph_"+o+"_posthog"})(e),this.ii=this.bi(e),this.pi=this.wi(e),this.load(),e.debug&&A.info("Persistence loaded",e.persistence,I({},this.props)),this.update_config(e,e,n),this.save(),w){var r=()=>this.flush();ve(w,"beforeunload",r,{capture:!1}),ve(w,"pagehide",r,{capture:!1})}}ki(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return ke(n)&&n>0?n:0}isDisabled(){return!!this.xi}bi(e){lm.indexOf(e.persistence.toLowerCase())===-1&&(A.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var n,i=(function(o,a){o===void 0&&(o=[]),a===void 0&&(a=!1);var l=[...jg,...o];return I({},le,{H(u){try{var c={};try{c=zt.H(u)||{}}catch{}var d,h=JSON.parse(le.P(u)||"{}");if(a){var f={};for(var p in c){var g=c[p];Ye(g)||g===""||(f[p]=g)}d=fe(h,f)}else d=fe(c,h);return le.F(u,d),d}catch{}return null},F(u,c,d,h,f,p){var g=le.F(u,c,void 0,void 0,p);try{var m={};l.forEach((v=>{c[v]&&(m[v]=c[v])})),Object.keys(m).length&&zt.F(u,m,d,h,f,p)}catch(v){le.j(v)}return g},q(u,c){try{w?.localStorage.removeItem(u),zt.q(u,c)}catch(d){le.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),r=!1,s=e.persistence.toLowerCase();return s==="localstorage"&&le.N()?(n=le,r=!0):s==="localstorage+cookie"&&i.N()?(n=i,r=!0):s==="sessionstorage"&&be.N()?n=be:s==="memory"?n=Ug:s==="cookie"?n=zt:i.N()?(n=i,r=!0):n=zt,this.fi=r,n}Si(e){return this.yi+"__"+e}wi(e){return this.fi&&!!e.split_storage}properties(){var e={};return ie(this.props,((n,i)=>{var r=yn(i);if(!r||r.exposure==="event"){if(r!=null&&r.shouldSkipFromEventProperties!=null&&r.shouldSkipFromEventProperties(n))return;e[i]=n}})),e}load(){if(!this.xi){var e=this.ii.H(this.yi);e&&(this.props=fe({},e)),this.pi&&this.Ci()}}Ci(){for(var e of Io){var n=le.H(this.Si(e));if(n&&!Kt(n)){var i=this.Mi(e);i.persisted=!0,this.Ti(e)||(i.fingerprint=this.Ei(n,e)),this.Ii(e,n)||fe(this.props,n)}}}Ti(e){return Object.keys(this.props).some((n=>{var i;return((i=yn(n))==null?void 0:i.storageGroup)===e}))}Ii(e,n){var i=am[e];if(!i)return!1;var r=n[i],s=this.props[i];return ke(r)&&ke(s)&&s>r}refreshKey(e){var n;if(!this.xi){var i=this.pi?(n=yn(e))==null?void 0:n.storageGroup:void 0,r=i?le.H(this.Si(i)):this.ii.H(this.yi);if(r&&e in r)this.Pi(e,r[e]);else{if(i){var s=this.ii.H(this.yi);if(s&&e in s)return void this.Pi(e,s[e])}this.Ri(e)}}}save(){if(!this.xi){var e=this.ki();e>0?C(this.Ai)&&(this.Ai=setTimeout((()=>{this.Ai=void 0,this.Fi()}),e)):this.Fi()}}flush(){C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0,this.Fi())}Fi(){this.xi||(this.pi?this.Li():this.Oi(this.ii,this.yi,this.props,Wn))}Li(){var e=this.Di(),n=e.main,i=e.groups;for(var r of(this.Oi(this.ii,this.yi,n,Wn),Io)){var s,o=i[r];(!Kt(o)||(s=this.ci[r])!=null&&s.persisted)&&this.Oi(le,this.Si(r),o,r)}}Di(){var e={},n={flags:{},surveys:{}};return ie(this.props,((i,r)=>{var s,o=(s=yn(r))==null?void 0:s.storageGroup;o?n[o][r]=i:e[r]=i})),{main:e,groups:n}}Ei(e,n){if(n===Wn)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var i={};return ie(e,((r,s)=>{var o;i[s]=(o=yn(s))!=null&&o.volatile?"__volatile__":r})),JSON.stringify(i)}Oi(e,n,i,r){var s=this.Mi(r);if(r===Wn||s.dirty||C(s.fingerprint)){var o;try{if((o=this.Ei(i,r))===s.fingerprint)return void(s.dirty=!1)}catch{o=void 0}e.F(n,i,this.$i,this.Ni,this.qi,this.Ne.debug)?(s.dirty=!1,r!==Wn&&(s.persisted=!0),C(o)||(s.fingerprint=o)):this.Ne.debug&&A.warn('failed to persist storage entry "'+n+'"; will retry on next save')}}remove(e){var n=(e===void 0?{}:e).keepGroupEntries,i=n!==void 0&&n;if(C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0),this.ii.q(this.yi,!1),this.ii.q(this.yi,!0),!i&&this.gi)for(var r of Io)le.q(this.Si(r));i?delete this.ci[Wn]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,n,i){if(he(e)){C(n)&&(n="None"),this.$i=C(i)?this.ji:i;var r=!1;if(ie(e,((s,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==n||(this.Pi(o,s),r=!0)})),r)return this.save(),!0}return!1}register(e,n){if(he(e)){this.$i=C(n)?this.ji:n;var i=!1;if(ie(e,((r,s)=>{e.hasOwnProperty(s)&&(this.props[s]!==r||he(r)||U(r))&&(this.Pi(s,r),i=!0)})),i)return this.save(),!0}return!1}unregister(e){var n=typeof e=="string"?[e]:e,i=!1;for(var r of n)r in this.props&&(this.Ri(r),i=!0);i&&this.save()}update_campaign_params(){var e=P?.URL;if(e!==this.mi){var n=If(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);Kt(dl(n))||this.register(n),this.mi=e}}update_search_keyword(){var e;this.register((e=P?.referrer)?Cf(e):{})}update_referrer_info(){var e;this.register_once({$referrer:Af(),$referring_domain:P!=null&&P.referrer&&((e=as(P.referrer))==null?void 0:e.host)||cs},void 0)}set_initial_person_info(){this.props[pa]||this.props[ga]||this.register_once({[ts]:Pf(this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties,this.Ne.disable_capture_url_hashes)},void 0)}get_initial_props(){var e={};ie([ga,pa],(r=>{var s=this.props[r];s&&ie(s,(function(o,a){e["$initial_"+Yo(a)]=o}))}));var n=this.props[ts];if(n){var i=(function(r,s){s===void 0&&(s=!1);var o=Ff(r,s),a={};return ie(o,(function(l,u){a["$initial_"+Yo(u)]=l})),a})(n,this.Ne.disable_capture_url_hashes);fe(e,i)}return e}safe_merge(e){return ie(this.props,(function(n,i){i in e||(e[i]=n)})),e}update_config(e,n,i){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!i),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var r=e.persistence!==n.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((h,f)=>h===d[f]))})(e.cookie_persisted_properties||[],n.cookie_persisted_properties||[]),s=r?this.bi(e):this.ii,o=this.wi(e);if(r||o!==this.pi){var a=this.props;this.clear(),this.ii=s,this.pi=o,this.props=a,this.save()}}set_disabled(e){this.xi=e,this.xi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ni&&(this.Ni=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this.qi&&(this.qi=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,n){var i=this.props[Ti]||{};i[e]=n,this.Pi(Ti,i),this.save()}remove_event_timer(e){var n=this.props[Ti]||{},i=n[e];return C(i)||(delete n[e],this.Pi(Ti,n),this.save()),i}get_property(e){return this.props[e]}set_property(e,n){this.Pi(e,n),this.save()}Pi(e,n){var i;this.props[e]=n,(i=yn(e))!=null&&i.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var n,i=(n=yn(e))==null?void 0:n.storageGroup;i&&(this.Mi(i).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function Sr(t){var e=!0;return{dispose(){if(e){e=!1;var n=t();n&&je(n.then)&&n.then(void 0,(()=>{}))}}}}var Ue={GZipJS:"gzip-js",Base64:"base64"},bi={Activation:"events",Cancellation:"cancelEvents"},Co={Popover:"popover",API:"api",Widget:"widget"},qt={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},Ao={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},wa={Popover:"popover",Inline:"inline"},cm={SHOWN:"product tour shown"},Yc={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},Jc=pe("[RateLimiter]");class um{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=n=>{var i=n.text;if(i&&i.length)try{(JSON.parse(i).quota_limited||[]).forEach((r=>{Jc.info((r||"events")+" is quota limited."),this.serverLimits[r]=new Date().getTime()+6e4}))}catch(r){return void Jc.warn('could not rate limit - continuing. Error: "'+r?.message+'"',{text:i})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var n,i,r;e===void 0&&(e=!1);var s=this.captureEventsBurstLimit,o=this.captureEventsPerSecond,a=new Date().getTime(),l=(n=(i=this.instance.persistence)==null?void 0:i.get_property(ha))!==null&&n!==void 0?n:{tokens:s,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>s&&(l.tokens=s);var u=1>l.tokens;if(u||e||(l.tokens=Math.max(0,l.tokens-1)),u&&!e){var c=(ke(l.dropped)?l.dropped:0)+1;l.dropped=c,!this.lastEventRateLimited&&this.Hi(c)&&(l.dropped=0)}return this.lastEventRateLimited=u,(r=this.instance.persistence)==null||r.set_property(ha,l),{isRateLimited:u,remainingTokens:l.tokens}}Ui(e){var n=this.instance.config.property_denylist;return!U(n)||!n.includes(e)}zi(){var e;if(this.Ui("$current_url")&&this.Ui("$pathname")&&me!=null&&me.pathname)return""+((e=me.origin)!==null&&e!==void 0?e:"")+me.pathname}Hi(e){var n,i,r=this.captureEventsBurstLimit,s=this.captureEventsPerSecond,o=this.zi(),a=this.Ui("$session_id")?(n=(i=this.instance).get_session_id)==null?void 0:n.call(i):void 0,l=[e+" event(s) dropped since the last warning",o?"triggered on "+o:void 0,a?"session "+a:void 0].filter(Boolean).join(", ");return!!this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited: "+l+". Config is set to "+s+" events per second and "+r+" events burst limit."},{skip_client_rate_limiting:!0})}isServerRateLimited(e){var n=this.serverLimits[e||"events"]||!1;return n!==!1&&new Date().getTime()e(this.remoteConfig))):e()}Vi(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:e})}load(){try{if(this.remoteConfig)return an.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void an.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return an.info("No config found after loading remote JS config. Falling back to JSON."),void this.Vi((n=>{this.Zi(n.json,n),this.Gi()}));this.Zi(e),this.Gi()}))}catch(e){an.error("Error loading remote config",e),this.Zi()}}stop(){this.Ki&&(clearInterval(this.Ki),this.Ki=void 0)}refresh(){!this._instance.Qi()&&P&&P.visibilityState!=="hidden"&&this._instance.reloadFeatureFlags()}Gi(){var e;if(!this.Ki){var n=(e=this._instance.config.remote_config_refresh_interval_ms)!==null&&e!==void 0?e:3e5;n!==0&&(this.Ki=setInterval((()=>{this.refresh()}),n))}}Zi(e,n){!e&&n&&(n.statusCode===0?n.error||an.warn("Failed to fetch remote config from PostHog."):an.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(r){an.error("Error applying remote config",r)}if(e?.hasFeatureFlags!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var i;(i=this._instance.featureFlags)==null||i.ensureFlagsLoaded()}catch(r){an.error("Error loading feature flags",r)}}}var ct=Uint8Array,Ke=Uint16Array,oi=Uint32Array,gl=new ct([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]),ml=new ct([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]),Zc=new ct([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),$f=function(t,e){for(var n=new Ke(31),i=0;31>i;++i)n[i]=e+=1<i;++i)for(var s=n[i];n[i+1]>s;++s)r[s]=s-n[i]<<5|i;return[n,r]},Mf=$f(gl,2),ba=Mf[1];Mf[0][28]=258,ba[258]=28;for(var Xc=$f(ml,0)[1],Lf=new Ke(32768),_e=0;32768>_e;++_e){var zn=(43690&_e)>>>1|(21845&_e)<<1;Lf[_e]=((65280&(zn=(61680&(zn=(52428&zn)>>>2|(13107&zn)<<2))>>>4|(3855&zn)<<4))>>>8|(255&zn)<<8)>>>1}var Wi=function(t,e,n){for(var i=t.length,r=0,s=new Ke(e);i>r;++r)++s[t[r]-1];var o,a=new Ke(e);for(r=0;e>r;++r)a[r]=a[r-1]+s[r-1]<<1;for(o=new Ke(i),r=0;i>r;++r)o[r]=Lf[a[t[r]-1]++]>>>15-t[r];return o},Mn=new ct(288);for(_e=0;144>_e;++_e)Mn[_e]=8;for(_e=144;256>_e;++_e)Mn[_e]=9;for(_e=256;280>_e;++_e)Mn[_e]=7;for(_e=280;288>_e;++_e)Mn[_e]=8;var us=new ct(32);for(_e=0;32>_e;++_e)us[_e]=5;var dm=Wi(Mn,9),fm=Wi(us,5),Nf=function(t){return(t/8>>0)+(7&t&&1)},Of=function(t,e,n){(n==null||n>t.length)&&(n=t.length);var i=new(t instanceof Ke?Ke:t instanceof oi?oi:ct)(n-e);return i.set(t.subarray(e,n)),i},Ot=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8},Ei=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8,t[i+2]|=n>>>16},Po=function(t,e){for(var n=[],i=0;t.length>i;++i)t[i]&&n.push({s:i,f:t[i]});var r=n.length,s=n.slice();if(!r)return[new ct(0),0];if(r==1){var o=new ct(n[0].s+1);return o[n[0].s]=1,[o,1]}n.sort((function(b,k){return b.f-k.f})),n.push({s:-1,f:25001});var a=n[0],l=n[1],u=0,c=1,d=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=r-1;)a=n[n[d].f>n[u].f?u++:d++],l=n[u!=c&&n[d].f>n[u].f?u++:d++],n[c++]={s:-1,f:a.f+l.f,l:a,r:l};var h=s[0].s;for(i=1;r>i;++i)s[i].s>h&&(h=s[i].s);var f=new Ke(h+1),p=Ea(n[c-1],f,0);if(p>e){i=0;var g=0,m=p-e,v=1<i;++i){var E=s[i].s;if(e>=f[E])break;g+=v-(1<>>=m;g>0;){var S=s[i].s;e>f[S]?g-=1<=0&&g;--i){var _=s[i].s;f[_]==e&&(--f[_],++g)}p=e}return[new ct(f),p]},Ea=function(t,e,n){return t.s==-1?Math.max(Ea(t.l,e,n+1),Ea(t.r,e,n+1)):e[t.s]=n},Qc=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new Ke(++e),i=0,r=t[0],s=1,o=function(l){n[i++]=l},a=1;e>=a;++a)if(t[a]==r&&a!=e)++s;else{if(!r&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(r),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(r);s=1,r=t[a]}return[n.subarray(0,i),e]},Si=function(t,e){for(var n=0,i=0;e.length>i;++i)n+=t[i]*e[i];return n},Sa=function(t,e,n){var i=n.length,r=Nf(e+2);t[r]=255&i,t[r+1]=i>>>8,t[r+2]=255^t[r],t[r+3]=255^t[r+1];for(var s=0;i>s;++s)t[r+s+4]=n[s];return 8*(r+4+i)},eu=function(t,e,n,i,r,s,o,a,l,u,c){Ot(e,c++,n),++r[256];for(var d=Po(r,15),h=d[0],f=d[1],p=Po(s,15),g=p[0],m=p[1],v=Qc(h),E=v[0],S=v[1],_=Qc(g),b=_[0],k=_[1],T=new Ke(19),x=0;E.length>x;++x)T[31&E[x]]++;for(x=0;b.length>x;++x)T[31&b[x]]++;for(var F=Po(T,7),$=F[0],O=F[1],L=19;L>4&&!$[Zc[L-1]];--L);var N,K,V,M,R=u+5<<3,Z=Si(r,Mn)+Si(s,us)+o,Ce=Si(r,h)+Si(s,g)+o+14+3*L+Si(T,$)+(2*T[16]+3*T[17]+7*T[18]);if(Z>=R&&Ce>=R)return Sa(e,c,t.subarray(l,l+u));if(Ot(e,c,1+(Z>Ce)),c+=2,Z>Ce){N=Wi(h,f),K=h,V=Wi(g,m),M=g;var oe=Wi($,O);for(Ot(e,c,S-257),Ot(e,c+5,k-1),Ot(e,c+10,L-4),c+=14,x=0;L>x;++x)Ot(e,c+3*x,$[Zc[x]]);c+=3*L;for(var ye=[E,b],$e=0;2>$e;++$e){var ae=ye[$e];for(x=0;ae.length>x;++x)Ot(e,c,oe[Ie=31&ae[x]]),c+=$[Ie],Ie>15&&(Ot(e,c,ae[x]>>>5&127),c+=ae[x]>>>12)}}else N=dm,K=Mn,V=fm,M=us;for(x=0;a>x;++x)if(i[x]>255){var Ie;Ei(e,c,N[257+(Ie=i[x]>>>18&31)]),c+=K[Ie+257],Ie>7&&(Ot(e,c,i[x]>>>23&31),c+=gl[Ie]);var Se=31&i[x];Ei(e,c,V[Se]),c+=M[Se],Se>3&&(Ei(e,c,i[x]>>>5&8191),c+=ml[Se])}else Ei(e,c,N[i[x]]),c+=K[i[x]];return Ei(e,c,N[256]),c+K[256]},hm=new oi([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),pm=(function(){for(var t=new oi(256),e=0;256>e;++e){for(var n=e,i=9;--i;)n=(1&n&&3988292384)^n>>>1;t[e]=n}return t})(),Fo=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8};function gm(t,e){e===void 0&&(e={});var n=(function(){var d=4294967295;return{p(h){for(var f=d,p=0;h.length>p;++p)f=pm[255&f^h[p]]^f>>>8;d=f},d(){return 4294967295^d}}})(),i=t.length;n.p(t);var r,s,o,a,l,u=(a=10+((r=e).filename&&r.filename.length+1||0),l=8,(function(d,h,f,p,g,m){var v=d.length,E=new ct(p+v+5*(1+Math.floor(v/7e3))+g),S=E.subarray(p,E.length-g),_=0;if(!h||8>v)for(var b=0;v>=b;b+=65535){var k=b+65535;v>k?_=Sa(S,_,d.subarray(b,k)):(S[b]=!0,_=Sa(S,_,d.subarray(b,v)))}else{for(var T=hm[h-1],x=T>>>13,F=8191&T,$=(1<b;++b){var Ie=V(b),Se=32767&b,De=L[Ie];if(O[Se]=De,L[Ie]=Se,b>=$e){var wt=v-b;if((Ce>7e3||ye>24576)&&wt>423){_=eu(d,S,0,M,R,Z,oe,ye,ae,b-ae,_),ye=Ce=oe=0,ae=b;for(var ge=0;286>ge;++ge)R[ge]=0;for(ge=0;30>ge;++ge)Z[ge]=0}var Je=2,bt=0,mn=F,Re=Se-De&32767;if(wt>2&&Ie==V(b-Re))for(var Pe=Math.min(x,wt)-1,$t=Math.min(32767,b),Dn=Math.min(258,wt);$t>=Re&&--mn&&Se!=De;){if(d[b+Je]==d[b+Je-Re]){for(var qe=0;Dn>qe&&d[b+qe]==d[b+qe-Re];++qe);if(qe>Je){if(Je=qe,bt=Re,qe>Pe)break;var jn=Math.min(Re,qe-2),Mt=0;for(ge=0;jn>ge;++ge){var Lt=b-Re+ge+32768&32767,ut=Lt-O[Lt]+32768&32767;ut>Mt&&(Mt=ut,De=Lt)}}}Re+=(Se=De)-(De=O[Se])+32768&32767}if(bt){M[ye++]=268435456|ba[Je]<<18|Xc[bt];var sn=31&ba[Je],mi=31&Xc[bt];oe+=gl[sn]+ml[mi],++R[257+sn],++Z[mi],$e=b+Je,++Ce}else M[ye++]=d[b],++R[d[b]]}}_=eu(d,S,!0,M,R,Z,oe,ye,ae,b-ae,_)}return Of(E,0,p+Nf(_)+g)})(s=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):12+o.mem,a,l)),c=u.length;return(function(d,h){var f=h.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>h.level?4:h.level==9?2:0,d[9]=3,h.mtime!=0&&Fo(d,4,Math.floor(new Date(h.mtime||Date.now())/1e3)),f){d[3]=8;for(var p=0;f.length>=p;++p)d[p+10]=f.charCodeAt(p)}})(u,e),Fo(u,c-8,n.d()),Fo(u,c-4,i),u}var mm=!!Vo||!!el,Bf="text/plain",Nr=!1,Df=(t,e)=>{var n=t.split("#"),i=n[1],r=n[0].split("?"),s=r[0],o=r[1];if(!o)return t;var a=o.split("&").filter((l=>l.split("=")[0]!==e)).join("&");return s+(a?"?"+a:"")+(i?"#"+i:"")},As=function(t,e,n){var i;n===void 0&&(n=!0);var r=t.split("?"),s=r[0],o=r[1],a=I({},e),l=(i=o?.split("&").map((c=>{var d,h=c.split("="),f=h[0],p=n&&(d=a[f])!==null&&d!==void 0?d:h[1];return delete a[f],f+"="+p})))!==null&&i!==void 0?i:[],u=(function(c,d){var h,f;d===void 0&&(d="&");var p=[];return ie(c,(function(g,m){C(g)||C(m)||m==="undefined"||(h=encodeURIComponent((v=>v instanceof File)(g)?g.name:g.toString()),f=encodeURIComponent(m),p[p.length]=f+"="+h)})),p.join(d)})(a);return u&&l.push(u),l.length>0?s+"?"+l.join("&"):s},Ro=t=>{if(t.Ji)return t.Ji;var e=t.data,n=t.compression;if(e){if(n===Ue.GZipJS){var i=gm((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new ct(a.length+(a.length>>>1)),d=0,h=function(m){c[d++]=m},f=0;u>f;++f){if(d+5>c.length){var p=new ct(d+8+(u-f<<1));p.set(c),c=p}var g=a.charCodeAt(f);128>g?h(g):2048>g?(h(192|g>>>6),h(128|63&g)):g>55295&&57344>g?(h(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++f))>>>18),h(128|g>>>12&63),h(128|g>>>6&63),h(128|63&g)):(h(224|g>>>12),h(128|g>>>6&63),h(128|63&g))}return Of(c,0,d)})(Jn(e)),{mtime:0});return{contentType:Bf,body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),estimatedSize:i.byteLength}}if(n===Ue.Base64){var r=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(Jn(e)),s=(a=>"data="+encodeURIComponent(typeof a=="string"?a:Jn(a)))(r);return{contentType:"application/x-www-form-urlencoded",body:s,estimatedSize:new Blob([s]).size}}var o=Jn(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},jf=t=>{var e,n,i=()=>t.transport==="sendBeacon"?{url:As(t.url,{compression:Ue.Base64}),encodedBody:Ro(I({},t,{compression:Ue.Base64,Ji:void 0}))}:{url:Df(t.url,"compression"),encodedBody:Ro(I({},t,{compression:void 0,Ji:void 0}))};try{e=Ro(t)}catch(r){if(wc(t.compression,ri(t.url,"compression")))return A.error("Failed to gzip request body, sending uncompressed payload",r),i();throw r}return e&&wc(t.compression,ri(t.url,"compression"))&&!((n=e.body)instanceof ArrayBuffer?Go(new Uint8Array(n)):ArrayBuffer.isView(n)&&Go(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)))?(Nr=!0,i()):{url:t.url,encodedBody:e}},Uf=t=>{try{return jf(t)}catch(e){return A.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},vm=(function(){var t=se((function*(e){var n=Jn(e.data),i=yield(function(s,o,a){return Ko.apply(this,arguments)})(n,ne.DEBUG,{rethrow:!0});if(!i)return e;var r=yield i.arrayBuffer();return I({},e,{Ji:{contentType:Bf,body:r,estimatedSize:r.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),_m=/Failed to fetch|NetworkError|Load failed/i,Hf=t=>t?.name==="TypeError"&&_m.test(t?.message||""),Wf=t=>{var e=Uf(t);if(e){var n=e.url,i=e.encodedBody,r=i??{},s=r.contentType,o=r.body,a=r.estimatedSize,l=new Headers;ie(t.headers,(function(p,g){l.append(g,p)})),s&&l.append("Content-Type",s);var u=null,c=!1;if(pc){var d=new pc;u={signal:d.signal,timeout:setTimeout((()=>{var p,g;c=!0,d.abort((p=t.timeout,(g=new Error("PostHog request timed out"+(p?" after "+p+"ms":""))).name="AbortError",g))}),t.timeout)}}var h=p=>{c&&p?.name==="AbortError"||Hf(p)?A.warn(p):A.error(p),t.callback==null||t.callback({statusCode:0,error:p})};try{var f;el(n,I({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(f=u)==null?void 0:f.signal},t.fetchOptions)).then((p=>p.text().then((g=>{var m={statusCode:p.status,text:g};if(p.status===200)try{m.json=JSON.parse(g)}catch(v){A.error(v)}t.callback==null||t.callback(m)})))).catch(h).finally((()=>u?clearTimeout(u.timeout):null))}catch(p){u&&clearTimeout(u.timeout),h(p)}}},xa=t=>{try{var e,n=jf(t),i=n.url,r=n.encodedBody,s=r??{},o=s.body,a=s.estimatedSize;if(!o)return;var l=o instanceof Blob?o:new Blob([o],{type:s.contentType});if(He.sendBeacon(i,l))return;var u=U(t.data)?t.data:(e=t.data)==null?void 0:e.batch;if(U(u)&&u.length>1&&(a??0)>16384){var c=Math.ceil(u.length/2),d=h=>U(t.data)?h:I({},t.data,{batch:h});return xa(I({},t,{data:d(u.slice(0,c))})),void xa(I({},t,{data:d(u.slice(c))}))}A.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),Wf(I({},t,{Yi:!0}))}catch(h){A.warn("Beacon send failed",h)}},tu=(t,e,n,i)=>{var r=i==="query"?e==="POST"?"sent_at":"_":void 0;return As(n===Ue.GZipJS?Df(t,"compression"):t,I({},r?{[r]:Date.now().toString()}:{},n===Ue.GZipJS?{}:{compression:n}))},Or=[];el&&Or.push({transport:"fetch",method:Wf}),Vo&&Or.push({transport:"XHR",method(t){var e=Uf(t);if(e){var n=new Vo,i=e.encodedBody;n.open(t.method||"GET",e.url,!0);var r=i??{},s=r.contentType,o=r.body;ie(t.headers,(function(a,l){n.setRequestHeader(l,a)})),s&&n.setRequestHeader("Content-Type",s),t.timeout&&(n.timeout=t.timeout),n.onreadystatechange=()=>{if(n.readyState===4){var a={statusCode:n.status,text:n.responseText};if(n.status===200)try{a.json=JSON.parse(n.responseText)}catch{}t.callback==null||t.callback(a)}},n.send(o)}}}),He!=null&&He.sendBeacon&&Or.push({transport:"sendBeacon",method:xa});var Ia=3e3;class ym{constructor(e,n){this.Xi=!0,this.tr=[],this.er=At(n?.flush_interval_ms||Ia,250,5e3,A.createLogger("flush interval"),Ia),this.ir=e}enqueue(e){this.tr.push(e),this.rr||this.nr()}unload(){this.sr();var e=this.tr.length>0?this.ar():{},n=Object.values(e);[...n.filter((i=>i.url.indexOf("/e")===0)),...n.filter((i=>i.url.indexOf("/e")!==0))].map((i=>{this.lr(I({},i,{transport:"sendBeacon"}))}))}enable(){this.Xi=!1,this.nr()}nr(){var e=this;this.Xi||(this.rr=setTimeout((()=>{if(this.sr(),this.tr.length>0){var n=this.ar(),i=function(){var s=n[r],o=new Date().getTime();s.data&&U(s.data)&&ie(s.data,(a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp})),e.lr(s)};for(var r in n)i()}}),this.er))}lr(e){try{this.ir(e)}catch(n){A.error(n)}}sr(){clearTimeout(this.rr),this.rr=void 0}ar(){var e={};return ie(this.tr,(n=>{var i,r=n,s=(r?r.batchKey:null)||r.url;C(e[s])&&(e[s]=I({},r,{data:[]})),(i=e[s].data)==null||i.push(r.data)})),this.tr=[],e}}var wm=["retriesPerformedSoFar"];class bm{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!C(w)&&"onLine"in w.navigator&&(this.dr=w.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},ve(w,"online",this.vr),ve(w,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var n=e.retriesPerformedSoFar,i=md(e,wm);Dt(n)&&(i.url=As(i.url,{retry_count:n})),this._instance._send_request(I({},i,{callback:r=>{if(r.statusCode!==200&&(400>r.statusCode||r.statusCode>=500)){if((r.statusCode===0?3:10)>(n??0))return void this.At(I({retriesPerformedSoFar:n},i));r.statusCode===0&&A.warn("Request failed before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped retrying after "+(n??0)+" retries.")}i.callback==null||i.callback(r)}}))}At(e){var n=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=n+1;var i=(function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),c=Math.random()-.5;return Math.ceil(u+c*(u-l))})(n),r=Date.now()+i;this.tr.push({retryAt:r,requestOptions:e});var s="Enqueued failed request for retry in "+i;navigator.onLine||(s+=" (Browser is offline)"),A.warn(s),this.ur||(this.ur=!0,this.gr())}gr(){if(this.mr&&clearTimeout(this.mr),this.tr.length===0)return this.ur=!1,void(this.mr=void 0);this.mr=setTimeout((()=>{this.dr&&this.tr.length>0&&this.cr(),this.gr()}),this.hr)}cr(){var e=Date.now(),n=[],i=this.tr.filter((s=>e>s.retryAt||(n.push(s),!1)));if(this.tr=n,i.length>0)for(var r of i)this.retriableRequest(r.requestOptions)}unload(){for(var e of(this.mr&&(clearTimeout(this.mr),this.mr=void 0),this.ur=!1,C(w)||(this.vr&&(w.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(w.removeEventListener("offline",this.pr),this.pr=void 0)),this.tr)){var n=e.requestOptions;try{this._instance._send_request(I({},n,{transport:"sendBeacon"}))}catch(i){A.error(i)}}this.tr=[]}}class Em{constructor(e){this.yr=()=>{var n,i,r,s;this.br||(this.br={});var o=this.scrollElement(),a=this.scrollY(),l=o?Math.max(0,o.scrollHeight-o.clientHeight):0,u=a+(o?.clientHeight||0),c=o?.scrollHeight||0;this.br.lastScrollY=Math.ceil(a),this.br.maxScrollY=Math.max(a,(n=this.br.maxScrollY)!==null&&n!==void 0?n:0),this.br.maxScrollHeight=Math.max(l,(i=this.br.maxScrollHeight)!==null&&i!==void 0?i:0),this.br.lastContentY=u,this.br.maxContentY=Math.max(u,(r=this.br.maxContentY)!==null&&r!==void 0?r:0),this.br.maxContentHeight=Math.max(c,(s=this.br.maxContentHeight)!==null&&s!==void 0?s:0)},this._instance=e}get _r(){return this._instance.config.scroll_root_selector}getContext(){return this.br}resetContext(){var e=this.br;return setTimeout(this.yr,0),e}startMeasuringScrollPosition(){ve(w,"scroll",this.yr,{capture:!0}),ve(w,"scrollend",this.yr,{capture:!0}),ve(w,"resize",this.yr)}scrollElement(){if(!this._r)return w?.document.documentElement;var e=U(this._r)?this._r:[this._r];for(var n of e){var i=w?.document.querySelector(n);if(i)return i}}wr(e){var n=e==="y"?"scrollTop":"scrollLeft";if(this._r){var i=this.scrollElement();return i&&i[n]||0}return w?e==="y"?w.scrollY||w.pageYOffset||w.document.documentElement.scrollTop||0:w.scrollX||w.pageXOffset||w.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var Sm=t=>Pf(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class nu{constructor(e,n,i,r){this.kr=s=>{var o=this.Sr();if(!o||o.sessionId!==s){var a={sessionId:s,props:this.Cr(this._instance)};this.Mr.register({[fa]:a})}},this._instance=e,this.Tr=n,this.Mr=i,this.Cr=r||Sm,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[fa]}getSetOnceProps(){var e,n=(e=this.Sr())==null?void 0:e.props;return n?"r"in n?Ff(n,this._instance.config.disable_capture_url_hashes):{$referring_domain:n.referringDomain,$pathname:n.initialPathName,utm_source:n.utm_source,utm_campaign:n.utm_campaign,utm_medium:n.utm_medium,utm_content:n.utm_content,utm_term:n.utm_term}:{}}getSessionProps(){var e={};return ie(dl(this.getSetOnceProps()),((n,i)=>{i==="$current_url"&&(i="url"),e["$session_entry_"+Yo(i)]=n})),e}}class vl{on(e,n){return this.Er[e]||(this.Er[e]=[]),this.Er[e].push(n),()=>{this.Er[e]=this.Er[e].filter((i=>i!==n))}}emit(e,n){for(var i of this.Er[e]||[])i(n);for(var r of this.Er["*"]||[])r(e,n)}constructor(){this.Er={}}}var xi=pe("[SessionId]");class iu{on(e,n){return this.Ir.on(e,n)}constructor(e,n,i){var r;if(this.Pr=null,this.Rr=[],this.Ar=void 0,this.Fr=!1,this.Ir=new vl,this.Lr=(u,c)=>!(!Dt(u)||!Dt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===Wt)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Ne=e.config,this.Mr=e.persistence,this.Or=void 0,this.Dr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.$r=n||Ht,this.Nr=i||Ht;var s=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*At(this.Ne.session_idle_timeout_seconds||1800,60,36e3,xi.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.qr(),this.jr="ph_"+s+"_window_id",this.Br="ph_"+s+"_primary_window_exists",this.Hr()){var o=be.H(this.jr),a=be.H(this.Br);o&&!a?this.Or=o:be.q(this.jr),be.F(this.Br,!0)}if((r=this.Ne.bootstrap)!=null&&r.sessionID)try{var l=(u=>{var c=this.Ne.bootstrap.sessionID.replace(/-/g,"");if(c.length!==32)throw new Error("Not a valid UUID");if(c[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(c.substring(0,12),16)})();this.Ur(this.Ne.bootstrap.sessionID,new Date().getTime(),l)}catch(u){xi.error("Invalid sessionID in bootstrap",u)}this.zr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return C(this.Rr)&&(this.Rr=[]),this.Rr.push(e),this.Dr&&e(this.Dr,this.Or),()=>{this.Rr=this.Rr.filter((n=>n!==e))}}Hr(){return this.Ne.persistence!=="memory"&&!this.Mr.xi&&be.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&be.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?be.H(this.jr):null}Zr(e){var n=this.Pr;return!Ye(n)&&!Ye(e)&&5e3>Math.abs(e-n)}Ur(e,n,i){var r=n!==this._sessionActivityTimestamp,s=!(e!==this.Dr||i!==this._sessionStartTimestamp);this._sessionStartTimestamp=i,this._sessionActivityTimestamp=n,this.Dr=e,s&&!r||s&&this.Zr(n)||(this.Pr=n,this.Mr.register({[Yn]:[n,e,i]}))}Gr(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return Dt(n)&&n>0}Qr(){this.Gr()?this.Mr.refreshKey(Yn):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!Ye(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this.Pr){this.Qr();var n=this.Jr();n[1]===this.Dr&&n[2]===this._sessionStartTimestamp&&(this.Pr=this._sessionActivityTimestamp,this.Mr.register({[Yn]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],n=Dt(e)?e:0,i=Dt(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(n,i)}Xr(e){return this.Qr(),this.Lr(e,this.Yr())}Jr(){var e=this.Mr.props[Yn];return U(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Pr=null,clearTimeout(this.tn),this.tn=void 0,this.Ur(null,null,null)}destroy(){this.Fr=!0,this.Kr(),clearTimeout(this.tn),this.tn=void 0,this.Ar&&w&&(w.removeEventListener(rs,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&be.q(this.Br)},ve(w,rs,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=null),this.Ne.cookieless_mode===Wt)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var i=n||new Date().getTime(),r=this.Jr(),s=r[1],o=r[2],a=this.Yr(),l=this.Vr(),u=Dt(o)&&Math.abs(i-o)>864e5,c=!1,d=!1,h=!s,f=s,p=!h&&!e&&this.Lr(i,a);if(p){(p=this.Xr(i))||xi.info("cross-tab refresh kept the session alive",{sessionId:s});var g=this.Jr();s=g[1],o=g[2]}h||p||u?(s=this.$r(),l=this.Nr(),xi.info("new session ID generated",{sessionId:s,windowId:l,changeReason:{noSessionId:h,activityTimeout:p,sessionPastMaximumLength:u}}),o=i,c=!0):(l||(l=this.Nr(),c=!0),(d=s!==f)&&(xi.info("adopted cross-tab session id",{sessionId:s,windowId:l}),c=!0));var m=Dt(a)&&e&&!u?a:i,v=Dt(o)?o:new Date().getTime();this.Wr(l),this.Ur(s,m,v),e||this.qr();var E={noSessionId:h,activityTimeout:p,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((S=>S(s,l,E))),{sessionId:s,windowId:l,sessionStartTimestamp:v,changeReason:c?E:void 0,lastActivityTimestamp:a}}qr(){this.Fr||(clearTimeout(this.tn),this.tn=setTimeout((()=>{if(!this.Fr)if(this.Xr(new Date().getTime())){var e=this.Dr;this.resetSessionId(),this.Ir.emit("forcedIdleReset",{idleSessionId:e})}else this.qr()}),1.1*this.sessionTimeoutMs))}}var zf=function(t,e){if(!t)return!1;var n=t.userAgent;if(n&&Ec(n,e))return!0;try{var i=t?.userAgentData;if(i!=null&&i.brands&&i.brands.some((r=>Ec(r?.brand,e))))return!0}catch{}return!!t.webdriver};function qf(){return(qf=se((function*(){var t=He?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),n=e?.model;return X(n)&&n.length>0?n:void 0}catch(i){return void A.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",i)}}))).apply(this,arguments)}var ds=function(t,e){if(!(function(n){try{new RegExp(n)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function To(t,e,n){return Jn({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}var Vf={exact:(t,e)=>e.some((n=>t.some((i=>n===i)))),is_not:(t,e)=>e.every((n=>t.every((i=>n!==i)))),regex:(t,e)=>e.some((n=>t.some((i=>ds(n,i))))),not_regex:(t,e)=>e.every((n=>t.every((i=>!ds(n,i))))),icontains:(t,e)=>e.map(xr).some((n=>t.map(xr).some((i=>n.includes(i))))),not_icontains:(t,e)=>e.map(xr).every((n=>t.map(xr).every((i=>!n.includes(i))))),gt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>i>parseFloat(r)))})),lt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>it.toLowerCase();function Gf(t,e){return!t||Object.entries(t).every((n=>{var i=n[1],r=e?.[n[0]];if(C(r)||Ye(r))return!1;var s=[String(r)],o=Vf[i.operator];return!!o&&o(i.values,s)}))}var ka="custom",ru="i.posthog.com",xm=/^\/static\//;class Im{constructor(e){this.en={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,n=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return n||(n=this.apiHost.replace("."+ru,".posthog.com")),n==="https://app.posthog.com"?"https://us.posthog.com":n}get region(){return this.en[this.apiHost]||(this.en[this.apiHost]=/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"us":/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"eu":ka),this.en[this.apiHost]}rn(e){if(xm.test(e)){var n=this.instance.config.asset_host;if(typeof n=="string")return n.trim().replace(/\/$/,"")||void 0}}endpointFor(e,n){if(n===void 0&&(n=""),n&&(n=n[0]==="/"?n:"/"+n),e==="ui")return this.uiHost+n;if(e==="flags")return this.flagsApiHost+n;if(e==="assets"){var i=this.rn(n);if(i)return""+i+n}if(this.region===ka)return this.apiHost+n;var r=ru+n;switch(e){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}}function Kf(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var Q=pe("[Surveys]"),Yf="seenSurvey_",Jf=t=>{try{var e=(n=>((i,r)=>""+Yf+(function(s){return s.current_iteration&&s.current_iteration>0?s.id+"_"+s.current_iteration:s.id})(r))(0,n))(t);if(localStorage.getItem(e))return;localStorage.setItem(e,"true")}catch(n){Q.error("Failed to persist survey seen state",n)}},km=[Co.Popover,Co.Widget,Co.API],Cm={ignoreConditions:!1,ignoreDelay:!1,displayType:wa.Popover},Am=pe("[PostHog ExternalIntegrations]"),Pm={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class Fm{constructor(e){this._instance=e}ai(e,n){var i;(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,e,(r=>{if(r)return Am.error("failed to load script",r);n()}))}startIfEnabledOrStop(){var e=this,n=function(){var s,o,a,l=i[0],u=i[1];!u||(s=B.__PosthogExtensions__)!=null&&(s=s.integrations)!=null&&s[l]||e.ai(Pm[l],(()=>{var c;(c=B.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=B.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=B.__PosthogExtensions__)==null||(a=a.integrations)==null||(a=a[l])==null||a.stop())};for(var i of Object.entries((r=this._instance.config.integrations)!==null&&r!==void 0?r:{})){var r;n()}}}class Rm{constructor(e,n){this.rt=e,this.nn=n,this.sn=new Map,this.an=!1}add(e){var n=this;return se((function*(){if(n.an)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(n.sn.has(e.name))throw new Error('Browser extension "'+e.name+'" is already registered');n.sn.set(e.name,e);try{var i=e.setup(n.nn);i&&(yield i)}catch(s){var r=n.sn.get(e.name)===e;r&&n.sn.delete(e.name),n.rt.error('Failed to set up browser extension "'+e.name+'"',s),r&&n.ln(e)}}))()}dispose(){if(!this.an){this.an=!0;var e=Array.from(this.sn.values()).reverse();for(var n of(this.sn.clear(),e))this.ln(n)}}ln(e){try{var n=e.dispose==null?void 0:e.dispose();n&&je(n.then)&&n.then(void 0,(i=>{this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}))}catch(i){this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}}}class Tm{constructor(e){this._instance=e}initialize(){}get(e){var n=this._instance.persistence;if(typeof e=="string")return n?.get_property(e);var i={};for(var r of e){var s=n?.get_property(r);C(s)||(i[r]=s)}return i}set(e,n){var i;(i=this._instance.persistence)==null||i.register(typeof e=="string"?{[e]:n}:e)}remove(e){var n;(n=this._instance.persistence)==null||n.unregister(e)}}var su="extensionsRemoteConfig";class $m{constructor(e){this.an=!1,this.instance=e,this.rt=A,this.un=e.hn,this.kv=new Tm(e),this.onEvent=n=>Sr(this.instance.on("eventCaptured",(i=>{try{n({event:i.event,properties:i.properties})}catch(r){this.rt.error("Browser extension event listener failed",r)}}))),this.onRemoteConfig=n=>{if(this.an)return Sr((()=>{}));var i=s=>{try{n(s)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},r=this.instance.dn.on(su,i);return this.un&&i(this.un),Sr(r)},this.vn=new Rm(A.createLogger("[BrowserExtensions]"),this)}get logger(){return this.rt}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return(e=this.instance.get_property(Ji))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(Ji);return typeof e=="string"?e:void 0}get library(){return{name:ne.LIB_NAME,version:ne.LIB_VERSION}}get initialPersonProperties(){var e,n;return(e=(n=this.instance.persistence)==null?void 0:n.get_initial_props())!==null&&e!==void 0?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,n,i,r,s=(e=this.instance.sessionManager)==null?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:(n=s?.sessionId)!==null&&n!==void 0?n:"",windowId:(i=s?.windowId)!==null&&i!==void 0?i:"",sessionStartTimestamp:(r=s?.sessionStartTimestamp)!==null&&r!==void 0?r:0}}catch{return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get projectToken(){return this.instance.config.token}add(e){return this.vn.add(e)}capture(e,n,i){var r=this;return se((function*(){i?r.instance.capture(e,n,{timestamp:i.timestamp,uuid:i.uuid,$set:i.set,$set_once:i.setOnce}):r.instance.capture(e,n)}))()}registerDynamicEventProperties(e){return Sr(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(su,e))}sendRequest(e,n){var i=this;return se((function*(){var r;n===void 0&&(n={});var s=i.instance.requestRouter.endpointFor((r=n.target)!==null&&r!==void 0?r:"api",e),o={method:n.method,url:n.query?As(s,n.query):s,data:n.body,headers:n.headers,timeout:n.timeoutMs,fireCallbackOnDrop:!0,transport:n.transport,compression:n.compression,timestampMode:n.sentAt};return n.transport==="sendBeacon"?(i.instance._send_request(o),{statusCode:202}):new Promise((a=>{o.callback=a,i.instance._send_request(o)}))}))()}dispose(){this.an||(this.an=!0,this.vn.dispose())}}var zi={},$o=0,fs=()=>{},ou='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',Ii="Surveys module not available",au="sanitize_properties is deprecated. Use before_send instead",Zf="Invalid value for property_denylist config: ",Mm=["token","distinct_id",rf],Kn="posthog",Xf=!mm&&Ge?.indexOf("MSIE")===-1&&Ge?.indexOf("Mozilla")===-1,Mo=t=>{var e;return I({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:Lg(P?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:fs,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:t??"unset",__preview_deferred_init_extensions:!1,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:me&&X(me?.search)&&me.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disableDeviceModel:!1,disable_external_dependency_loading:!1,strict_script_versioning:!1,enable_recording_console_log:void 0,secure_cookie:(w==null||(e=w.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(n){A.error("Bad HTTP status: "+n.statusCode+" "+n.text)},get_device_id:n=>n,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:ma,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:Ia},error_tracking:{},_onCapture:fs},(n=>({rageclick:n&&n>="2026-05-30"?{content_ignorelist:Gg,ignore_text_selection:!0}:!n||"2025-11-30">n||{content_ignorelist:!0},capture_pageview:!n||"2025-05-24">n||"history_change",session_recording:n&&n>="2026-06-25"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6},streamNetworkBody:!0}:n&&n>="2026-05-30"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6}}:n&&n>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:n&&n>="2026-01-30"?"head":"body",internal_or_test_user_hostname:n&&n>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:n&&n>="2026-05-30"?250:0,split_storage:!(!n||"2026-05-30">n),detect_google_search_app:!(!n||"2026-05-30">n),disable_capture_url_hashes:!(!n||"2026-06-25">n)}))(t))},Lm=[["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"]],lu=t=>{var e={};for(var n of Lm){var i=n[0],r=n[1];C(t[i])||(e[r]=t[i])}var s=fe({},e,t),o=t.__preview_external_dependency_versioned_paths;return C(o)||(C(t.strict_script_versioning)&&(s.strict_script_versioning=!!o),X(o)&&C(t.asset_host)&&(s.asset_host=o)),U(t.property_blacklist)&&(C(t.property_denylist)?s.property_denylist=t.property_blacklist:U(t.property_denylist)?s.property_denylist=[...t.property_blacklist,...t.property_denylist]:A.error(Zf+t.property_denylist)),s};class Nm{constructor(){this.__forceAllowLocalhost=!1}get fn(){return this.__forceAllowLocalhost}set fn(e){A.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class Ze{pn(e,n){if(e){var i=this.sn.indexOf(e);i!==-1&&this.sn.splice(i,1)}return this.sn.push(n),n.initialize==null||n.initialize(),n}gn(){return this.config.cookieless_mode===Wt||this.config.cookieless_mode===kn&&this.consent.isRejected()}get decideEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){var e;this.webPerformance=new Nm,this.mn=!1,this.version=ne.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new vl,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=Mo(),this.SentryIntegration=tm,this.sentryIntegration=i=>(function(r,s){var o=Ef(r,s);return{name:bf,processEvent:a=>o(a)}})(this,i),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.wn=!1,this.kn=null,this.xn=null,this.Sn=null,this.scrollManager=new Em(this),this.pageViewManager=new Gc(this),this.rateLimiter=new um(this),this.requestRouter=new Im(this),this.consent=new Hg(this),this.externalIntegrations=new Fm(this);var n=(e=Ze.__defaultExtensionClasses)!==null&&e!==void 0?e:{};this.featureFlags=n.featureFlags&&new n.featureFlags(this),this.toolbar=n.toolbar&&new n.toolbar(this),this.surveys=n.surveys&&new n.surveys(this),this.conversations=n.conversations&&new n.conversations(this),this.logs=n.logs&&new n.logs(this),this.metrics=n.metrics&&new n.metrics(this),this.experiments=n.experiments&&new n.experiments(this),this.exceptions=n.exceptions&&new n.exceptions(this),this.people={set:(i,r,s)=>{var o=X(i)?{[i]:r}:i;this.setPersonProperties(o),s?.({})},set_once:(i,r,s)=>{var o=X(i)?{[i]:r}:i;this.setPersonProperties(void 0,o),s?.({})}},this.on("eventCaptured",(i=>A.info('send "'+i?.event+'"',i)))}init(e,n,i){if(i&&i!==Kn){var r,s=(r=zi[i])!==null&&r!==void 0?r:new Ze;return s._init(e,n,i),zi[i]=s,zi[Kn][i]=s,s}return this._init(e,n,i)}_init(e,n,i){var r,s;n===void 0&&(n={});var o,a=X(e)?e.trim():"";if(!a)return A.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return a!==((o=this.config)==null?void 0:o.token)?console.warn("[PostHog.js]","You have already initialized PostHog with a different project token! Re-initializing is a no-op, so events will keep going to the project this instance was initialized with. To capture into a second project, load PostHog once, then initialize a named instance after the SDK has loaded, e.g. posthog.init('"+a+"', { ... }, 'project2')"):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=Mo(n.defaults),n.debug=this.Cn(n.debug),this.Mn=n,this.Tn=[],n.person_profiles?this.xn=n.person_profiles:n.process_person&&(this.xn=n.process_person);var l=Mo(n.defaults),u=lu(n),c=fe({},l,u,{name:i,token:a});he(l.rageclick)&&he(u.rageclick)&&(c.rageclick=fe({},l.rageclick,u.rageclick)),he(l.session_recording)&&he(u.session_recording)&&(c.session_recording=fe({},l.session_recording,u.session_recording)),this.set_config(c),this.config.on_xhr_error&&A.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=n.disable_compression?void 0:Ue.GZipJS;var d=this.En();if(this.persistence=new ko(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new ko(I({},this.config,{persistence:"sessionStorage"}),d,!1),this.bn="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&be.N()){var h=be.H(this.bn);U(h)&&h.forEach((k=>{X(k)&&this.yn.add(k)}))}else be.q(this.bn);var f=I({},this.persistence.props),p=I({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new ym((k=>this.Pn(k)),this.config.request_queue_config),this.Rn=new bm(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new iu(this),this.sessionPropsManager=new nu(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((k,T,x)=>{(x!=null&&x.activityTimeout||x!=null&&x.sessionPastMaximumLength||x!=null&&x.crossTabAdoption)&&this.An()}))),this.Fn(),this.config.__preview_deferred_init_extensions?(A.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Ln(g)}),0)):(A.info("Initializing extensions synchronously"),this.Ln(g)),ne.DEBUG=ne.DEBUG||this.config.debug,ne.DEBUG&&A.info("Starting in debug mode",{this:this,config:n,thisC:I({},this.config),p:f,s:p}),!this.config.identity_distinct_id||(r=n.bootstrap)!=null&&r.distinctID||(n.bootstrap=I({},n.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((s=n.bootstrap)==null?void 0:s.distinctID)!==void 0){var m=n.bootstrap.distinctID,v=this.get_distinct_id(),E=this.persistence.get_property(at);if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&E===Hn)this.identify(m);else if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&E===vn)A.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{var S=this.config.get_device_id(Ht()),_=n.bootstrap.isIdentifiedID?S:m;this.persistence.set_property(at,n.bootstrap.isIdentifiedID?vn:Hn),this.register({distinct_id:m,$device_id:_})}}if(g)this.register_once({distinct_id:_r,$device_id:null},"");else if(!this.get_distinct_id()){var b=this.config.get_device_id(Ht());this.register_once({distinct_id:b,$device_id:b},""),this.persistence.set_property(at,Hn)}return ve(w,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),n.segment?(function(k,T){var x=k.config.segment;if(!x)return T();(function(F,$){var O=F.config.segment;if(!O)return $();var L=K=>{var V=()=>K.anonymousId()||Ht();F.config.get_device_id=V,K.id()&&(F.register({distinct_id:K.id(),$device_id:V()}),F.persistence.set_property(at,vn)),$()},N=O.user();"then"in N&&je(N.then)?N.then(L):L(N)})(k,(()=>{x.register((F=>{typeof Promise<"u"&&Promise.resolve||xo.warn("This browser does not have Promise support, and can not use the segment integration");var $=(O,L)=>{if(!L)return O;O.event.userId||O.event.anonymousId===F.get_distinct_id()||(xo.info("No userId set, resetting PostHog"),F.reset()),O.event.userId&&O.event.userId!==F.get_distinct_id()&&(xo.info("UserId set, identifying with PostHog"),F.identify(O.event.userId));var N=F.calculateEventProperties(L,O.event.properties);return O.event.properties=Object.assign({},N,O.event.properties),O};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:O=>$(O,O.event.event),page:O=>$(O,Gn),identify:O=>$(O,bo),screen:O=>$(O,"$screen")}})(k)).then((()=>{T()}))}))})(this,(()=>this.On())):this.On(),je(this.config._onCapture)&&this.config._onCapture!==fs&&(A.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(k=>this.config._onCapture(k.event,k)))),this.config.ip&&A.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this.config.disableDeviceModel||(function(){return qf.apply(this,arguments)})().then((k=>{k&&this.register({[yo]:k})})).catch(fs),this}Fn(){var e,n,i,r,s,o,a=(e=(n=this.config.__extensionClasses)==null?void 0:n.featureFlags)!==null&&e!==void 0?e:(i=Ze.__defaultExtensionClasses)==null?void 0:i.featureFlags;a&&(this.featureFlags&&this.featureFlags instanceof a||((r=this.Dn)==null||r.call(this),this.Dn=void 0,this.featureFlags=new a(this)),je(this.featureFlags.onReloading)&&je(this.featureFlags.setup)?this.Dn||(this.Dn=this.featureFlags.onReloading((()=>{this.dn.emit("featureFlagsReloading",!0)})),this.$n().add(this.featureFlags)):(s=(o=this.featureFlags).initialize)==null||s.call(o))}Ln(e){var n,i,r,s,o,a,l,u=performance.now(),c=I({},Ze.__defaultExtensionClasses,this.config.__extensionClasses),d=[];c.exceptions&&this.sn.push(this.exceptions=(n=this.exceptions)!==null&&n!==void 0?n:new c.exceptions(this)),c.historyAutocapture&&this.sn.push(this.historyAutocapture=new c.historyAutocapture(this)),c.tracingHeaders&&this.sn.push(this.tracingHeaders=new c.tracingHeaders(this)),c.siteApps&&this.sn.push(this.siteApps=new c.siteApps(this)),c.sessionRecording&&!e&&this.sn.push(this.sessionRecording=new c.sessionRecording(this)),this.config.disable_scroll_properties||d.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),c.autocapture&&this.sn.push(this.autocapture=new c.autocapture(this)),c.surveys&&this.sn.push(this.surveys=(i=this.surveys)!==null&&i!==void 0?i:new c.surveys(this)),c.logs&&this.sn.push(this.logs=(r=this.logs)!==null&&r!==void 0?r:new c.logs(this)),c.metrics&&this.sn.push(this.metrics=(s=this.metrics)!==null&&s!==void 0?s:new c.metrics(this)),c.conversations&&this.sn.push(this.conversations=(o=this.conversations)!==null&&o!==void 0?o:new c.conversations(this)),c.productTours&&this.sn.push(this.productTours=new c.productTours(this)),c.heatmaps&&this.sn.push(this.heatmaps=new c.heatmaps(this)),c.webVitalsAutocapture&&this.sn.push(this.webVitalsAutocapture=new c.webVitalsAutocapture(this)),c.exceptionObserver&&this.sn.push(this.exceptionObserver=new c.exceptionObserver(this)),c.deadClicksAutocapture&&this.sn.push(this.deadClicksAutocapture=new c.deadClicksAutocapture(this,em)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((h=>{h.initialize&&d.push((()=>{h.initialize==null||h.initialize()}))})),d.push((()=>{if(this.Nn){var h=this.Nn;this.Nn=void 0,this.sn.forEach((f=>f.onRemoteConfig==null?void 0:f.onRemoteConfig(h)))}})),this.qn(d,u)}qn(e,n){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,n)}),0);var i=e.shift();if(i)try{i()}catch(s){A.error("Error initializing extension:",s)}}var r=Math.round(performance.now()-n);this.register_for_session({[sf]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[of]:r}),this.config.__preview_deferred_init_extensions&&A.info("PostHog extensions initialized ("+r+"ms)")}Zi(e){var n;if(!P||!P.body)return A.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.Zi(e)}),500);if(this.config.__preview_deferred_init_extensions&&(this.Nn=e),this.hn=e,this.compression=void 0,e.ok){var i,r=e.config;r.supportedCompression&&!this.config.disable_compression&&(this.compression=j(r.supportedCompression,Ue.GZipJS)?Ue.GZipJS:j(r.supportedCompression,Ue.Base64)?Ue.Base64:void 0),(i=r.analytics)!=null&&i.endpoint&&(this.analyticsDefaultEndpoint=r.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:ma}),(n=this.jn)==null||n.handleRemoteConfig(e),this.sn.forEach((s=>s.onRemoteConfig==null?void 0:s.onRemoteConfig(e)))}On(){try{this.config.loaded(this)}catch(i){A.critical("`loaded` function failed",i)}if(this.Bn(),this.config.internal_or_test_user_hostname&&me!=null&&me.hostname){var e=me.hostname,n=this.config.internal_or_test_user_hostname;(typeof n=="string"?e===n:n.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.gn())&&this.Hn()}),1),this.Un=new Tf(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()&&yr(this.__request_queue,(e=>this.Pn(e))),this.__request_queue=[],this.Bn()}_handle_unload(){var e,n,i,r,s;(e=this.surveys)==null||e.handlePageUnload==null||e.handlePageUnload(),(n=this.metrics)==null||n.flush("sendBeacon"),this.config.request_batching?(this.zn()&&this.capture(wo),(i=this.logs)==null||i.flushLogs("sendBeacon"),(r=this.In)==null||r.unload(),(s=this.Rn)==null||s.unload()):this.zn()&&this.capture(wo,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?Xf?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)?e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:429})):(e.transport=e.transport||this.config.api_transport,e.headers=I({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,(C(this.config.disable_beacon)?this.config.__preview_disable_beacon:this.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(n=>{var i,r,s,o=I({},n);o.timeout=o.timeout||6e4;var a,l,u,c,d,h=(i=o.transport)!==null&&i!==void 0?i:"fetch";h==="sendBeacon"&&C(o.compression)&&o.data&&(o.compression=Ue.Base64),o.method==="POST"&&o.data&&(o.timestampMode==="capture-body"?o.data={api_key:(l=(d=(c=U(a=o.data)?a:[a])[0])==null||(u=d.properties)==null?void 0:u.token)!==null&&l!==void 0?l:d?.token,batch:c,sent_at:new Date().toISOString()}:o.timestampMode==="body"&&(o.data=(function(m,v){return v===void 0&&(v=new Date().toISOString()),U(m)?m.map((E=>I({},E,{sent_at:v}))):I({},m,{sent_at:v})})(o.data))),o.url=tu(o.url,o.method,o.compression,o.timestampMode);var f=Or.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),p=(r=(s=(function(m,v){for(var E=0;m.length>E;E++)if(m[E].transport===h)return m[E]})(f))==null?void 0:s.method)!==null&&r!==void 0?r:f[0].method;if(!p)throw new Error("No available transport method");var g=m=>{try{p(m)}catch(v){Hf(v)?A.warn(v):A.error(v),o.callback==null||o.callback({statusCode:0,error:v})}};h!=="sendBeacon"&&o.data&&o.compression===Ue.GZipJS&&Op&&typeof Promise<"u"&&!Nr?vm(o).then((m=>{g(m)})).catch((m=>{if(bc(m))return Nr=!0,void g(I({},o,{compression:void 0,url:tu(n.url,n.method,void 0,n.timestampMode)}));(v=>{if(!v||typeof v!="object")return!1;var E="name"in v?String(v.name):"";return bc(v)||E===vd})(m)&&(Nr=!0),g(o)})):p(o)})(I({},e,{callback:n=>{var i,r;this.rateLimiter.checkForLimiting(n),400>n.statusCode||(i=(r=this.config).on_request_error)==null||i.call(r,n),e.callback==null||e.callback(n)}}))):e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:0}))}Pn(e){this.Rn?this.Rn.retriableRequest(e):this._send_request(e)}_execute_array(e){$o++;try{var n,i=[],r=[],s=[];yr(e,(a=>{if(a)if(U(n=a[0]))s.push(a);else if(je(a))try{a.call(this)}catch(l){A.error("Error executing queued PostHog call",a,l)}else U(a)&&n==="alias"?i.push(a):U(a)&&n.indexOf("capture")!==-1&&je(this[n])?s.push(a):r.push(a)}));var o=function(a,l){yr(a,(function(u){try{if(U(u[0])){var c=l;ie(u,(function(d){c=c[d[0]].apply(c,d.slice(1))}))}else l[u[0]].apply(l,u.slice(1))}catch(d){A.error("Error executing queued PostHog call",u,d)}}))};o(i,this),o(r,this),o(s,this)}finally{$o--}}push(e){if($o>0&&U(e)&&X(e[0])){var n=Ze.prototype[e[0]];je(n)&&n.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,n,i){var r,s,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.In){if(this.is_capturing())if(!C(e)&&X(e)){var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var c=i!=null&&i.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(c==null||!c.isRateLimited){n!=null&&n.$current_url&&!X(n?.$current_url)&&(A.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),n==null||delete n.$current_url),e!=="$exception"||i!=null&&i.Wn||A.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,h=i?.timestamp||d,f=kc(i?.uuid,Ht),p={uuid:f,event:e,properties:this.calculateEventProperties(e,n||{},h,f)};e===Gn&&this.config.__preview_capture_bot_pageviews&&u&&(p.event="$bot_pageview",p.properties.$browser_type="bot"),c&&(p.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&p.properties.$feature_flag_has_experiment===!1&&this.get_property(Qr)===!0;i?.$set&&!g&&(p.$set=i?.$set);var m=i?.$unset;m&&(p.$unset=m);var v,E,S,_=g?void 0:this.Vn(i?.$set_once,e!==Tc,e===bo);if(_&&(p.$set_once=_),i!=null&&i._noTruncate||(s=this.config.properties_string_max_length,o=p,a=L=>X(L)?L.slice(0,s):L,l=new Set,p=(function L(N,K){if(N!==Object(N))return a?a(N):N;if(!l.has(N)){var V;if(l.add(N),U(N))V=[],yr(N,(R=>{V.push(L(R))}));else{var M={};ie(N,((R,Z)=>{l.has(R)||(M[Z]=L(R))})),V=M}return V}})(o)),p.timestamp=h,C(i?.timestamp)||(p.properties.$event_time_override_provided=!0,p.properties.$event_time_override_system_time=d),g&&(p.properties=(function(L,N){N===void 0&&(N=[]);var K={},V=M=>{L[M]!==void 0&&(K[M]=L[M])};return Bp.forEach(V),N.forEach(V),K})(p.properties,Mm)),e===qt.DISMISSED||e===qt.SENT){var b=n?.[Ao.SURVEY_ID],k=n?.[Ao.SURVEY_ITERATION];Jf({id:b,current_iteration:k}),p.$set=I({},p.$set,{[(v={id:b,current_iteration:k},E=e===qt.SENT?"responded":"dismissed",S="$survey_"+E+"/"+v.id,v.current_iteration&&v.current_iteration>0&&(S="$survey_"+E+"/"+v.id+"/"+v.current_iteration),S)]:!0})}else e===qt.SHOWN&&(p.$set=I({},p.$set,{[Ao.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===cm.SHOWN){var T=n?.[Yc.TOUR_TYPE];T&&(p.$set=I({},p.$set,{[Yc.TOUR_LAST_SEEN_DATE+"/"+T]:new Date().toISOString()}))}var x=I({},p.properties.$set,p.$set);if(Kt(x)||this.setPersonPropertiesForFlags(x),!H(this.config.before_send)){var F=this.Pt(p);if(!F)return;(p=F).uuid=kc(p.uuid,Ht)}this.dn.emit("eventCaptured",p);var $=(r=i?._url)!==null&&r!==void 0?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),O={method:"POST",url:$,data:p,compression:"best-available",timestampMode:i?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test($)?"body":"capture-body",batchKey:i?._batchKey,transport:i?.transport};return!this.config.request_batching||i&&(i==null||!i._batchKey)||i!=null&&i.send_instantly?this.Pn(O):this.In.enqueue(O),p}A.critical("This capture call is ignored due to client rate limiting.")}}else A.error("No event name provided to posthog.capture")}else A.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(n=>e(n.event,n)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new $m(this)}cn(e){this._n.push(e);var n=!0;return()=>{if(n){n=!1;var i=this._n.indexOf(e);i!==-1&&this._n.splice(i,1)}}}calculateEventProperties(e,n,i,r,s){if(i=i||new Date,!this.persistence||!this.sessionPersistence)return n;var o=s?void 0:this.persistence.remove_event_timer(e),a=I({},n);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.gn()&&(a[rf]=!0),e==="$snapshot"){var l=I({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!X(a.distinct_id)&&!ke(a.distinct_id)||Jo(a.distinct_id))&&A.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=(function(b,k,T,x){var F,$,O,L;if(x===void 0&&(x=!1),!Ge)return{};var N,K=b?[...si,...k||[]]:[],V=(function(Dn){for(var qe=0;xc.length>qe;qe++){var jn=xc[qe],Mt=jn[1],Lt=jn[0].exec(Dn),ut=Lt&&(je(Mt)?Mt(Lt,Dn):Mt);if(ut)return ut}return["",""]})(Ge),M=V[0],R=V[1],Z=(N=typeof navigator<"u"?navigator:void 0)!=null&&N.brave?{brave:!0}:{},Ce={};C(T)||(Ce.detectGoogleSearchApp=T);var oe={},ye=(F=navigator)==null||(F=F.userAgentData)==null?void 0:F.platform,$e=($=navigator)==null?void 0:$.maxTouchPoints,ae=w==null||(O=w.screen)==null?void 0:O.width,Ie=w==null||(L=w.screen)==null?void 0:L.height,Se=w?.devicePixelRatio;C(ye)||(oe.userAgentDataPlatform=ye),C($e)||(oe.maxTouchPoints=$e),C(ae)||(oe.screenWidth=ae),C(Ie)||(oe.screenHeight=Ie),C(Se)||(oe.devicePixelRatio=Se);var De,wt,ge,Je,bt,mn,Re,Pe,$t=fe(dl({$os:M,$os_version:R,$browser:Hd(Ge,navigator.vendor,Z,Ce),$device:Ic(Ge),$device_type:(wt=Ge,ge=oe,Pe=Ic(wt),Pe===xd||Pe===Sd||Pe==="Kobo"||Pe==="Kindle Fire"||Pe===Od?ti:Pe===Ki||Pe===Qn||Pe===Yi||Pe===Xo?"Console":Pe===kd?"Wearable":Pe?rt:ge?.userAgentDataPlatform==="Android"&&((Je=ge?.maxTouchPoints)!==null&&Je!==void 0?Je:0)>0?600>Math.min((bt=ge?.screenWidth)!==null&&bt!==void 0?bt:0,(mn=ge?.screenHeight)!==null&&mn!==void 0?mn:0)/((Re=ge?.devicePixelRatio)!==null&&Re!==void 0?Re:1)?rt:ti:"Desktop"),$timezone:Rf(),$timezone_offset:om()}),{$current_url:Xi(x?fn(me?.href):me?.href,K,Qi),$host:me?.host,$pathname:me?.pathname,$raw_user_agent:Ge.length>1e3?Ge.substring(0,997)+"...":Ge,$browser_version:ig(Ge,navigator.vendor,Z,Ce),$browser_language:Kc(),$browser_language_prefix:(De=Kc(),typeof De=="string"?De.split("-")[0]:void 0),$screen_height:w?.screen.height,$screen_width:w?.screen.width,$viewport_height:w?.innerHeight,$viewport_width:w?.innerWidth,$lib:ne.LIB_NAME,$lib_version:ne.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return ne.SDK_DIST_CHANNEL&&($t.$sdk_dist_channel=ne.SDK_DIST_CHANNEL),$t})(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties,this.config.detect_google_search_app,this.config.disable_capture_url_hashes);if(this.sessionManager){var d=this.sessionManager.checkAndGetSessionAndWindowId(s,i.getTime()),h=d.windowId;a.$session_id=d.sessionId,a.$window_id=h}this.sessionPropsManager&&fe(a,this.sessionPropsManager.getSessionProps());try{var f;this.sessionRecording&&fe(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(f=this.Rn)==null?void 0:f.length}catch(b){a.$sdk_debug_error_capturing_properties=String(b)}if(this.requestRouter.region===ka&&(a.$lib_custom_api_host=this.config.api_host),u=e!==Gn||s?e!==wo||s?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(i):this.pageViewManager.doPageView(i,r),a=fe(a,u),e===Gn&&P&&(a.title=P.title),!C(o)){var p=i.getTime()-o;a.$duration=parseFloat((p/1e3).toFixed(3))}Ge&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();ie(["$referrer","$referring_domain"],(b=>{b in g&&delete m[b]}));var v={};if(this._n.length>0)for(var E of this._n.slice())try{fe(v,E())}catch(b){A.error("Failed to produce browser extension event properties",b)}(a=fe({},c,g,m,I({},v,a))).$is_identified=this._isIdentified(),U(this.config.property_denylist)?ie(this.config.property_denylist,(function(b){delete a[b]})):A.error(Zf+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var S=this.config.sanitize_properties;S&&(A.error(au),a=S(a,e));var _=this.Zn();return a.$process_person_profile=_,_&&!s&&this.Gn("_calculate_event_properties"),a}Vn(e,n,i){var r;if(n===void 0&&(n=!0),i===void 0&&(i=!1),!this.persistence||!this.Zn()||this.mn&&!i)return e;var s=this.persistence.get_initial_props(),o=(r=this.sessionPropsManager)==null?void 0:r.getSetOnceProps(),a=fe({},s,o||{},e||{}),l=this.config.sanitize_properties;return l&&(A.error(au),a=l(a,"$set_once")),n&&(this.mn=!0),Kt(a)?void 0:a}register(e,n){var i;(i=this.persistence)==null||i.register(e,n)}register_once(e,n,i){var r;(r=this.persistence)==null||r.register_once(e,n,i)}register_for_session(e){var n;(n=this.sessionPersistence)==null||n.register(e),Object.keys(e).forEach((i=>this.yn.add(i))),this.Qn()}unregister(e){var n;(n=this.persistence)==null||n.unregister(e)}unregister_for_session(e){var n;(n=this.sessionPersistence)==null||n.unregister(e),this.yn.delete(e),this.Qn()}Kn(e,n){this.register({[e]:n})}An(){this.yn.forEach((e=>{var n;(n=this.sessionPersistence)==null||n.unregister(e)})),this.yn.clear(),this.Qn()}Qn(){var e;if(this.bn)if(this.config.persistence==="memory"||(e=this.sessionPersistence)!=null&&e.xi||!be.N())be.q(this.bn);else{var n=[];this.yn.forEach((i=>n.push(i))),n.length>0?be.F(this.bn,n):be.q(this.bn)}}getFeatureFlag(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlag(e,n)}getFeatureFlagPayload(e){var n;return(n=this.featureFlags)==null?void 0:n.getFeatureFlagPayload(e)}getFeatureFlagResult(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlagResult(e,n)}getAllFeatureFlags(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.getAllFeatureFlags())!==null&&e!==void 0?e:[]}isFeatureEnabled(e,n){var i,r;return(i=(r=this.featureFlags)==null?void 0:r.isFeatureEnabled(e,n))!==null&&i!==void 0?i:n?.defaultValue}reloadFeatureFlags(){var e;(e=this.featureFlags)==null||e.reloadFeatureFlags()}updateFlags(e,n,i){var r;(r=this.featureFlags)==null||r.updateFlags(e,n,i)}updateEarlyAccessFeatureEnrollment(e,n,i){var r;(r=this.featureFlags)==null||r.updateEarlyAccessFeatureEnrollment(e,n,i)}getEarlyAccessFeatures(e,n,i){var r;return n===void 0&&(n=!1),(r=this.featureFlags)==null?void 0:r.getEarlyAccessFeatures(e,n,i)}on(e,n){return this.dn.on(e,n)}onFeatureFlags(e){return this.featureFlags?this.featureFlags.onFeatureFlags(e):(e([],{},{errorsLoading:!0}),()=>{})}onSurveysLoaded(e){return this.surveys?this.surveys.onSurveysLoaded(e):(e([],{isLoaded:!1,error:Ii}),()=>{})}onSessionId(e){var n,i;return(n=(i=this.sessionManager)==null?void 0:i.onSessionId(e))!==null&&n!==void 0?n:()=>{}}getSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getSurveys(e,n):e([],{isLoaded:!1,error:Ii})}getActiveMatchingSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,n):e([],{isLoaded:!1,error:Ii})}renderSurvey(e,n){var i;(i=this.surveys)==null||i.renderSurvey(e,n)}displaySurvey(e,n){var i;n===void 0&&(n=Cm),(i=this.surveys)==null||i.displaySurvey(e,n)}cancelPendingSurvey(e){var n;(n=this.surveys)==null||n.cancelPendingSurvey(e)}canRenderSurvey(e){var n,i;return(n=(i=this.surveys)==null?void 0:i.canRenderSurvey(e))!==null&&n!==void 0?n:{visible:!1,disabledReason:Ii}}canRenderSurveyAsync(e,n){var i,r;return n===void 0&&(n=!1),(i=(r=this.surveys)==null?void 0:r.canRenderSurveyAsync(e,n))!==null&&i!==void 0?i:Promise.resolve({visible:!1,disabledReason:Ii})}Jn(e){return!e||Jo(e)?(A.critical("Unique user id has not been set in posthog.identify"),!1):e===_r?(A.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.'),!1):!["distinct_id","distinctid"].includes(e.toLowerCase())&&!["undefined","null"].includes(e.toLowerCase())||(A.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.'),!1)}identify(e,n,i){if(!this.__loaded||!this.persistence)return A.uninitializedWarning("posthog.identify");if(ke(e)&&(e=e.toString(),A.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.Jn(e)&&this.Gn("posthog.identify")){var r=this.get_distinct_id();this.register({$user_id:e}),this.get_property(Ji)||this.register_once({$had_persisted_distinct_id:!0,$device_id:r},""),e!==r&&e!==this.get_property(Ri)&&(this.unregister(Ri),this.register({distinct_id:e}));var s,o=(this.persistence.get_property(at)||Hn)===Hn,a=e!==r,l=!a&&o;if(a&&o)this.persistence.set_property(at,vn),this.setPersonPropertiesForFlags({$set:n||{},$set_once:i||{}},!1),this.capture(bo,{distinct_id:e,$anon_distinct_id:r},{$set:n||{},$set_once:i||{}}),this.Sn=To(e,n,i),(s=this.featureFlags)==null||s.setAnonymousDistinctId(r);else if(l){this.persistence.set_property(at,vn);var u=n||{},c=i||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=To(e,n,i)}else(n||i)&&this.setPersonProperties(n,i);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Cn)):l&&(n||i)&&this.reloadFeatureFlags()}}setPersonProperties(e,n){if((e||n)&&this.Gn("posthog.setPersonProperties")){var i=To(this.get_distinct_id(),e,n);this.Sn!==i?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:n||{}},!0),this.capture("$set",{$set:e||{},$set_once:n||{}}),this.Sn=i):A.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}unsetPersonProperties(e){var n,i=(U(e)?e:[e]).filter((r=>X(r)&&r.length>0));i.length!==0&&this.Gn("posthog.unsetPersonProperties")&&((n=this.featureFlags)==null||n.unsetPersonPropertiesForFlags(i,!0),this.capture("$set",{$unset:i}),this.Sn=null)}group(e,n,i){if(e&&n){var r=this.getGroups(),s=r[e]!==n;if(s&&this.resetGroupPropertiesForFlags(e),this.register({$groups:I({},r,{[e]:n})}),s||i){var o={$group_type:e,$group_key:n};i&&(o.$group_set=i),this.capture(Tc,o)}i&&this.setGroupPropertiesForFlags({[e]:i}),s&&!i&&this.reloadFeatureFlags()}else A.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),(i=this.featureFlags)==null||i.setPersonPropertiesForFlags(e,n)}resetPersonPropertiesForFlags(e){var n;e===void 0&&(e=!0),(n=this.featureFlags)==null||n.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((i=this.featureFlags)==null||i.setGroupPropertiesForFlags(e,n))}resetGroupPropertiesForFlags(e){var n;(n=this.featureFlags)==null||n.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,n){var i,r,s,o,a,l,u,c,d,h;if(n===void 0&&(n=!1),A.info("reset"),!this.__loaded)return A.uninitializedWarning("posthog.reset");var f,p=this.get_property(Ji),g=this.get_property(yo),m=this.get_property(An),v=this.is_capturing();if(this.consent.reset(),n||!v||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after."),(i=this.persistence)==null||i.clear(),(r=this.sessionPersistence)==null||r.clear(),this.yn.clear(),this.Qn(),C(m)||(f=this.persistence)==null||f.register({[An]:m}),(s=this.surveys)==null||s.reset(),(o=this.Un)==null||o.stop(),(a=this.featureFlags)==null||a.reset(),(l=this.conversations)==null||l.reset(),(u=this.logs)==null||u.reset(),(c=this.metrics)==null||c.reset(),(d=this.persistence)==null||d.set_property(at,Hn),(h=this.sessionManager)==null||h.resetSessionId(),this.Sn=null,this.config.cookieless_mode===Wt)this.register_once({distinct_id:_r,$device_id:null},"");else{var E=this.config.get_device_id(Ht());this.register_once({distinct_id:E,$device_id:e?E:p},""),e||C(g)||this.register({[yo]:g})}this.register({$last_posthog_reset:new Date().toISOString()},1),delete this.config.identity_distinct_id,delete this.config.identity_hash,this.reloadFeatureFlags()}shutdown(e){var n=this;return se((function*(){var i,r,s,o,a,l,u;if(n.__loaded){(i=n.Un)==null||i.stop(),(r=n.jn)==null||r.dispose(),(s=n.sessionRecording)==null||s.dispose(),(o=n.logs)==null||o.flushLogs("sendBeacon"),(a=n.metrics)==null||a.flush("sendBeacon"),(l=n.In)==null||l.unload(),(u=n.Rn)==null||u.unload();try{var c;(c=n.featureFlags)==null||c.destroy()}catch(d){A.error("Error while destroying feature flags",d)}}else A.uninitializedWarning("posthog.shutdown")}))()}setIdentity(e,n){var i;this.config.identity_distinct_id=e,this.config.identity_hash=n,this.alias(e),(i=this.conversations)==null||i.Xn()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,(e=this.conversations)==null||e.ts()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,n;return(e=(n=this.sessionManager)==null?void 0:n.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var n=this.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.sessionStartTimestamp,r=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+n.sessionId);if(e!=null&&e.withTimestamp&&i){var s,o=(s=e.timestampLookBack)!==null&&s!==void 0?s:10;if(!i)return r;r+="?t="+Math.max(Math.floor((new Date().getTime()-i)/1e3)-o,0)}return r}alias(e,n){return e===this.get_property(Zd)?(A.critical("Attempting to create alias for existing People user - aborting."),-2):this.Gn("posthog.alias")?(C(n)&&(n=this.get_distinct_id()),e!==n?(this.Kn(Ri,e),this.capture("$create_alias",{alias:e,distinct_id:n})):(A.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var n=I({},this.config);if(he(e)){var i,r,s,o,a,l,u,c,d,h,f,p;fe(this.config,lu(e));var g=this.En();(i=this.persistence)==null||i.update_config(this.config,n,g),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new ko(I({},this.config,{persistence:"sessionStorage"}),g,!1);var m=this.Cn(this.config.debug);mt(m)&&(this.config.debug=m),mt(this.config.debug)&&(this.config.debug?(ne.DEBUG=!0,le.N()&&le.F("ph_debug",!0),A.info("set_config",{config:e,oldConfig:n,newConfig:I({},this.config)})):(ne.DEBUG=!1,le.N()&&le.q("ph_debug"))),(r=this.featureFlags)==null||r.updateConfig==null||r.updateConfig(this.config,this.Qi()),(s=this.exceptionObserver)==null||s.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(h=this.deadClicksAutocapture)==null||h.startIfEnabledOrStop(),(f=this.surveys)==null||f.loadIfEnabled(),this.es(),(p=this.externalIntegrations)==null||p.startIfEnabledOrStop()}}_overrideSDKInfo(e,n){ne.LIB_NAME=e,ne.LIB_VERSION=n}startSessionRecording(e){var n,i,r,s,o,a=e===!0,l={sampling:a||!(e==null||!e.sampling),linked_flag:a||!(e==null||!e.linked_flag),url_trigger:a||!(e==null||!e.url_trigger),event_trigger:a||!(e==null||!e.event_trigger)};Object.values(l).some(Boolean)&&((n=this.sessionManager)==null||n.checkAndGetSessionAndWindowId(),l.sampling&&((i=this.sessionRecording)==null||i.overrideSampling()),l.linked_flag&&((r=this.sessionRecording)==null||r.overrideLinkedFlag()),l.url_trigger&&((s=this.sessionRecording)==null||s.overrideTrigger("url")),l.event_trigger&&((o=this.sessionRecording)==null||o.overrideTrigger("event"))),this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,n){if(this.exceptions){var i=new Error("PostHog syntheticException"),r=this.exceptions.buildProperties(e,{handled:!0,syntheticException:i});return this.exceptions.sendExceptionEvent(I({},r,n))}}addExceptionStep(e,n){var i;(i=this.exceptions)==null||i.addExceptionStep(e,n)}captureLog(e){var n;(n=this.logs)==null||n.captureLog(e)}get logger(){var e,n;return(e=(n=this.logs)==null?void 0:n.logger)!==null&&e!==void 0?e:Ze.rs}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var n,i;return(n=(i=this.toolbar)==null?void 0:i.loadToolbar(e))!==null&&n!==void 0&&n}get_property(e){var n;return(n=this.persistence)==null?void 0:n.props[e]}getSessionProperty(e){var n;return(n=this.sessionPersistence)==null?void 0:n.props[e]}toString(){var e,n=(e=this.config.name)!==null&&e!==void 0?e:Kn;return n!==Kn&&(n=Kn+"."+n),n}_isIdentified(){var e,n;return((e=this.persistence)==null?void 0:e.get_property(at))===vn||((n=this.sessionPersistence)==null?void 0:n.get_property(at))===vn}Zn(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles===ma&&!this._isIdentified()&&Kt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[Ri])&&((n=this.persistence)==null||(n=n.props)==null||!n[ns]))}zn(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Zn()||this.Gn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.Gn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}Gn(e){return this.config.person_profiles==="never"?(A.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Kn(ns,!0),!0)}En(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut();return this.config.disable_persistence||e&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!==kn)}es(){var e,n,i,r,s=this.En();return((e=this.persistence)==null?void 0:e.xi)!==s&&((i=this.persistence)==null||i.set_disabled(s)),((n=this.sessionPersistence)==null?void 0:n.xi)!==s&&((r=this.sessionPersistence)==null||r.set_disabled(s)),s&&(this.yn.clear(),this.Qn()),s}opt_in_capturing(e){var n;if(this.config.cookieless_mode!==Wt){if(this.gn()){var i,r,s,o,a;this.Yn(!0,!0),(i=this.sessionManager)==null||i.destroy(),(r=this.pageViewManager)==null||r.destroy(),this.sessionManager=new iu(this),this.pageViewManager=new Gc(this),this.persistence&&(this.sessionPropsManager=new nu(this,this.sessionManager,this.persistence));var l,u=(s=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&s!==void 0?s:(a=Ze.__defaultExtensionClasses)==null?void 0:a.sessionRecording;u&&(this.sessionRecording=this.pn(this.sessionRecording,new u(this)),this.hn&&((l=this.sessionRecording)==null||l.onRemoteConfig==null||l.onRemoteConfig(this.hn)))}var c,d;this.consent.optInOut(!0),this.es(),this.Bn(),(n=this.sessionRecording)==null||n.startIfEnabledOrStop(),this.config.cookieless_mode==kn&&((c=this.surveys)==null||c.loadIfEnabled()),(C(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((d=e?.captureEventName)!==null&&d!==void 0?d:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hn()}else A.warn(ou)}opt_out_capturing(){var e,n,i;this.config.cookieless_mode!==Wt?(this.config.cookieless_mode===kn&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===kn&&(this.register({distinct_id:_r,$device_id:null}),(e=this.sessionRecording)==null||e.stopRecording(),this.sessionRecording=void 0,(n=this.sessionManager)==null||n.destroy(),(i=this.pageViewManager)==null||i.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.Hn(),this.Bn())):A.warn(ou)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===Wt||(this.config.cookieless_mode===kn?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return He?zf(He,this.config.custom_blocked_useragents):void 0}Hn(){P&&(P.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(Gn,{title:P.title},{send_instantly:!0}),this.kn&&(P.removeEventListener(is,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),ve(P,is,this.kn)))}debug(e){e===!1?(w?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(w?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}Qi(){var e=this.Mn||{};return"advanced_disable_flags"in e?!!e.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(A.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(function(n,i,r,s,o){var a=i in n&&!H(n[i]),l=r in n&&!H(n[r]);return a?n[i]:!!l&&(o&&o.warn("Config field '"+r+"' is deprecated. Please use '"+i+"' instead. The old field will be removed in a future major version."),n[r])})(e,"advanced_disable_flags","advanced_disable_decide",0,A)}Pt(e){var n;if(H(this.config.before_send))return e;var i=Object.keys((n=e.properties)!==null&&n!==void 0?n:{}).filter(qp),r=U(this.config.before_send)?this.config.before_send:[this.config.before_send],s=e;for(var o of r){if(s=o(s),H(s)){var a="Event '"+e.event+"' was rejected in beforeSend function";return zp(e.event)?A.warn(a+". This can cause unexpected behavior."):A.info(a),null}s.properties&&!Kt(s.properties)||A.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}for(var l of i)if(s.properties&&H(s.properties[l]))return A.warn("Event '"+e.event+"' had its '"+l+"' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped."),null;return s}getPageViewId(){var e;return(e=this.pageViewManager.ui)==null?void 0:e.pageViewId}captureTraceFeedback(e,n){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:n})}captureTraceMetric(e,n,i){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:n,$ai_metric_value:String(i)})}Cn(e){var n=mt(e)&&!e,i=le.N()&&le.P("ph_debug")==="true";return!n&&(!!i||e)}}Ze.__defaultExtensionClasses={},Ze.rs=(()=>{var t=()=>{};return{trace:t,debug:t,info:t,warn:t,error:t,fatal:t}})(),(function(t,e){for(var n=0;e.length>n;n++)t.prototype[e[n]]=$g(t.prototype[e[n]])})(Ze,["identify"]);class cu{constructor(e){this.disabled=e===!1;var n=he(e)?e:{};this.thresholdPx=n.threshold_px||30,this.timeoutMs=n.timeout_ms||1e3,this.clickCount=n.click_count||3,this.clicks=[]}isRageClick(e,n,i){if(this.disabled)return!1;var r=this.clicks[this.clicks.length-1];if(r&&Math.abs(e-r.x)+Math.abs(n-r.y)i-r.timestamp){if(this.clicks.push({x:e,y:n,timestamp:i}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:n,timestamp:i}];return!1}}var Lo="$copy_autocapture",No=pe("[AutoCapture]");function Oo(t,e){return e.length>t?e.slice(0,t)+"...":e}function Om(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!hn(e));return e}function Bm(t,e){var n,i,r=e.e,s=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!hn(t))return{props:{}};for(var c=[t],d=new Set([t]),h=t;h.parentNode&&!et(h,"body")&&pf>c.length;)if(hf(h.parentNode)){var f=h.parentNode.host;if(d.has(f))break;d.add(f),c.push(f),h=f}else{if(!hn(h.parentNode)||d.has(h.parentNode))break;d.add(h.parentNode),c.push(h.parentNode),h=h.parentNode}var p,g,m=[],v={},E=!1,S=!1;if(ie(c,(x=>{var F=ya(x);if(et(x,"a")){var $=x.getAttribute("href");E=!!(F&&$&&Hi($))&&(u?fn($):$)}j(os(x),"ph-no-capture")&&(S=!0),m.push((function(L,N,K,V,M){M===void 0&&(M=!1);var R=L.tagName.toLowerCase(),Z={tag_name:R};hl.indexOf(R)>-1&&!K&&(Z.$el_text=R.toLowerCase()==="a"||R.toLowerCase()==="button"?Oo(1024,zc(L)):Oo(1024,Zi(L)));var Ce=os(L);Ce.length>0&&(Z.classes=Ce.filter((function(ae){return ae!==""}))),ie(L.attributes,(function(ae){var Ie;if((!yf(L)||["name","id","class","aria-label"].indexOf(ae.name)!==-1)&&(V==null||!V.includes(ae.name))&&!N&&Hi(ae.value)&&(!X(Ie=ae.name)||Ie.substring(0,10)!=="_ngcontent"&&Ie.substring(0,7)!=="_nghost")){var Se=ae.value;ae.name==="class"&&(Se=fl(Se).join(" ")),Z["attr__"+ae.name]=Oo(1024,ae.name==="href"&&M?fn(Se):Se)}}));for(var oe=1,ye=1,$e=L;$e=Om($e);)oe++,$e.tagName===L.tagName&&ye++;return Z.nth_child=oe,Z.nth_of_type=ye,Z})(x,s,o,a,u));var O=(function(L){if(!ya(L))return{};var N={};return ie(L.attributes,(function(K){if(K.name&&K.name.indexOf("data-ph-capture-attribute")===0){var V=K.name.replace("data-ph-capture-attribute-",""),M=K.value;V&&M&&Hi(M)&&(N[V]=M)}})),N})(x);fe(v,O)})),S)return{props:{},explicitNoCapture:S};if(o||(m[0].$el_text=et(t,"a")||et(t,"button")?zc(t):Zi(t)),E){var _,b;m[0].attr__href=E;var k=(_=as(E))==null?void 0:_.host,T=w==null||(b=w.location)==null?void 0:b.host;k&&T&&k!==T&&(p=E)}return{props:fe({$event_type:r.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(x){return x.map((F=>{var $,O,L="";if(F.tag_name&&(L+=F.tag_name),F.attr_class)for(var N of(F.attr_class.sort(),F.attr_class))L+="."+N.replace(/"/g,"");var K=I({},F.text?{text:F.text}:{},{"nth-child":($=F.nth_child)!==null&&$!==void 0?$:0,"nth-of-type":(O=F.nth_of_type)!==null&&O!==void 0?O:0},F.href?{href:F.href}:{},F.attr_id?{attr_id:F.attr_id}:{},F.attributes),V={};return Lr(K).sort(((M,R)=>M[0].localeCompare(R[0]))).forEach((M=>{var R=M[1];return V[qc(M[0].toString())]=qc(R.toString())})),(L+=":")+Lr(V).map((M=>M[0]+'="'+M[1]+'"')).join("")})).join(";")})((function(x){return x.map((F=>{var $,O,L={text:($=F.$el_text)==null?void 0:$.slice(0,400),tag_name:F.tag_name,href:(O=F.attr__href)==null?void 0:O.slice(0,2048),attr_class:Xg(F),attr_id:F.attr__id,nth_child:F.nth_child,nth_of_type:F.nth_of_type,attributes:{}};return Lr(F).filter((N=>N[0].indexOf("attr__")===0)).forEach((N=>L.attributes[N[0]]=N[1])),L}))})(g)))},(n=m[0])!=null&&n.$el_text?{$el_text:(i=m[0])==null?void 0:i.$el_text}:{},p&&r.type==="click"?{$external_click_url:p}:{},v)}}var ki=pe("[ExceptionAutocapture]"),uu=()=>{},Dm=pe("[TracingHeaders]"),wn=pe("[Web Vitals]"),du=9e5,fu="disabled",hu="lazy_loading",Ci="awaiting_config",Ir="missing_config";pe("[SessionRecording]"),pe("[SessionRecording]");var Ca="[SessionRecording]",Bt=pe(Ca),jm=pe("[Heatmaps]");function Bo(t){return he(t)&&"clientX"in t&&"clientY"in t&&ke(t.clientX)&&ke(t.clientY)}var kr=pe("[Product Tours]"),Do=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(ll))},Um=["$set_once","$set"],Et=pe("[SiteApps]"),pu="Error while initializing PostHog app with config id ";function qn(t,e,n){if(H(t))return!1;switch(n){case"exact":return t===e;case"contains":var i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(i,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}class Hm{constructor(e){this.ns=new vl,this.ss=(n,i)=>this.os(n,i)&&this.ls(n,i)&&this.us(n,i)&&this.hs(n,i),this.os=(n,i)=>i==null||!i.event||n?.event===i?.event,this._instance=e,this.ds=new Set,this.vs=new Set}init(){var e,n;C((e=this._instance)==null?void 0:e._addCaptureHook)||(n=this._instance)==null||n._addCaptureHook(((i,r)=>{this.on(i,r)}))}register(e){var n,i;if(!C((n=this._instance)==null?void 0:n._addCaptureHook)&&(e.forEach((o=>{var a,l;(a=this.vs)==null||a.add(o),(l=o.steps)==null||l.forEach((u=>{var c;(c=this.ds)==null||c.add(u?.event||"")}))})),(i=this._instance)!=null&&i.autocapture)){var r,s=new Set;e.forEach((o=>{var a;(a=o.steps)==null||a.forEach((l=>{l!=null&&l.selector&&s.add(l?.selector)}))})),(r=this._instance)==null||r.autocapture.setElementSelectors(s)}}on(e,n){var i;n!=null&&e.length!=0&&(this.ds.has(e)||this.ds.has(n.event))&&this.vs&&((i=this.vs)==null?void 0:i.size)>0&&this.vs.forEach((r=>{this.cs(n,r)&&this.ns.emit("actionCaptured",r.name)}))}fs(e){this.onAction("actionCaptured",(n=>e(n)))}cs(e,n){if(n?.steps==null)return!1;for(var i of n.steps)if(this.ss(e,i))return!0;return!1}onAction(e,n){return this.ns.on(e,n)}ls(e,n){if(n!=null&&n.url){var i,r=e==null||(i=e.properties)==null?void 0:i.$current_url;if(!r||typeof r!="string"||!qn(r,n.url,n.url_matching||"contains"))return!1}return!0}us(e,n){return!!this.ps(e,n)&&!!this.gs(e,n)&&!!this.ys(e,n)}ps(e,n){var i;if(n==null||!n.href)return!0;var r=this.bs(e);if(r.length>0)return r.some((a=>qn(a.href,n.href,n.href_matching||"exact")));var s,o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!o&&qn((s=o.match(/(?::|")href="(.*?)"/))?s[1]:"",n.href,n.href_matching||"exact")}gs(e,n){var i;if(n==null||!n.text)return!0;var r=this.bs(e);if(r.length>0)return r.some((u=>qn(u.text,n.text,n.text_matching||"exact")||qn(u.$el_text,n.text,n.text_matching||"exact")));var s,o,a,l=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!l&&(s=(function(u){for(var c,d=[],h=/(?::|")text="(.*?)"/g;!H(c=h.exec(u));)d.includes(c[1])||d.push(c[1]);return d})(l),o=n.text,a=n.text_matching||"exact",s.some((u=>qn(u,o,a))))}ys(e,n){var i,r;if(n==null||!n.selector)return!0;var s=e==null||(i=e.properties)==null?void 0:i.$element_selectors;if(s!=null&&s.includes(n.selector))return!0;var o=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";if(n.selector_regex&&o)try{return new RegExp(n.selector_regex).test(o)}catch{return!1}return!1}bs(e){var n;return(e==null||(n=e.properties)==null?void 0:n.$elements)==null?[]:e?.properties.$elements}hs(e,n){return n==null||!n.properties||n.properties.length===0||Gf(n.properties.reduce(((i,r)=>{var s=U(r.value)?r.value.map(String):r.value!=null?[String(r.value)]:[];return i[r.key]={values:s,operator:r.operator||"exact"},i}),{}),e?.properties)}}class Wm{constructor(e){var n;this._s=[],this._instance=e,this.ws=new Map,this.ks=new Map,this.xs=new Map,(n=this._instance)==null||n.onSessionId==null||n.onSessionId((i=>this.Ss(i)))}Cs(e){return!1}Ms(){return null}Ts(e){}Es(){}Is(e,n){return!!e&&Gf(e.propertyFilters,n?.properties)}Ps(e,n){var i=new Map;return e.forEach((r=>{var s;(s=r.conditions)==null||(s=s[n])==null||(s=s.values)==null||s.forEach((o=>{if(o!=null&&o.name){var a=i.get(o.name)||[];a.push(r.id),i.set(o.name,a)}}))})),i}Rs(e,n,i){var r=(i===bi.Activation?this.ws:this.ks).get(e),s=[];return this.As((o=>{s=o.filter((a=>r?.includes(a.id)))})),s.filter((o=>{var a,l=(a=o.conditions)==null||(a=a[i])==null||(a=a.values)==null?void 0:a.find((u=>u.name===e));return this.Is(l,n)}))}register(e){var n;C((n=this._instance)==null?void 0:n._addCaptureHook)||(this.Fs(e),this.Ls(e))}Ls(e){var n=e.filter((i=>{var r,s;return((r=i.conditions)==null?void 0:r.actions)&&((s=i.conditions)==null||(s=s.actions)==null||(s=s.values)==null?void 0:s.length)>0}));n.length!==0&&(this.Os==null&&(this.Os=new Hm(this._instance),this.Os.init(),this.Os.fs((i=>{this.onAction(i)}))),n.forEach((i=>{var r,s,o,a,l;i.conditions&&(r=i.conditions)!=null&&r.actions&&(s=i.conditions)!=null&&(s=s.actions)!=null&&s.values&&((o=i.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.Os)==null||a.register(i.conditions.actions.values),(l=i.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var c=this.xs.get(u.name);c&&c.push(i.id),this.xs.set(u.name,c||[i.id])}})))})))}Fs(e){var n,i=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.events)&&((a=s.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0})),r=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.cancelEvents)&&((a=s.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0}));i.length===0&&r.length===0||((n=this._instance)==null||n._addCaptureHook(((s,o)=>{this.onEvent(s,o)})),this.ws=this.Ps(e,bi.Activation),this.ks=this.Ps(e,bi.Cancellation))}onEvent(e,n){var i,r,s=this.Ds(),o=(n==null||(i=n.properties)==null?void 0:i.$survey_id)||(n==null||(r=n.properties)==null?void 0:r.$product_tour_id);if(o&&this.getActivatedIds().includes(o)){var a=this.$s(e,o);if(a==="consume")return s.info("event consumed activated item, removing it",{event:e,itemId:o}),void this.Ns([o]);if(a==="persist")return s.info("shown item promoted to persisted activation",{event:e,itemId:o}),this.qs(o),void this.js([o])}if(this.ks.has(e)){var l=this.Rs(e,n,bi.Cancellation);l.length>0&&(s.info("cancel event matched, cancelling items",{event:e,itemsToCancel:l.map((c=>c.id))}),this.Ns(l.map((c=>c.id))),l.forEach((c=>this.Bs(c.id))))}if(this.ws.has(e)){s.info("event name matched",{event:e,eventPayload:n,items:this.ws.get(e)});var u=this.Rs(e,n,bi.Activation);this.Hs(u.map((c=>c.id)))}}onAction(e){this.xs.has(e)&&this.Hs(this.xs.get(e)||[])}Hs(e){var n;if(e.length!==0){var i=!((n=this._instance)==null||n.get_session_id==null||!n.get_session_id()),r=[];for(var s of e)i&&this.Cs(s)?this.qs(s)&&this.Us(s):r.push(s);r.length>0&&(this._s=[...new Set([...this._s,...r])]),this.Ds().info("updating activated items",{activatedItems:this.getActivatedIds()})}}qs(e){this._s=this._s.filter((i=>i!==e));var n=this.zs();return!n.includes(e)&&(this.Ws([...n,e]),this.Vs(),!0)}Ns(e){var n=new Set(e);this._s=this._s.filter((s=>!n.has(s)));var i=this.Zs(),r=i.filter((s=>!n.has(s)));r.length!==i.length&&(this.Ws(r),r.length===0&&this.Gs()),this.js(e)}Qs(){var e,n=this.Ms();if(!n)return{};var i=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n];return i&&typeof i=="object"?i:{}}Us(e){if(this.Ms()){var n=this.Qs();this.Ts(I({},n,{[e]:Date.now()}))}}js(e){if(this.Ms()){var n=this.Qs(),i={},r=!1;for(var s of Object.entries(n)){var o=s[0],a=s[1];e.includes(o)?r=!0:i[o]=a}r&&(Kt(i)?this.Es():this.Ts(i))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var n=this.Qs()[e];return ke(n)?n:void 0}}Zs(){var e,n=this.Js();return((e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n])||[]}zs(){var e,n,i=this.Zs();if(i.length===0)return[];var r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[this.Ys()],s=(n=this._instance)==null||n.get_session_id==null?void 0:n.get_session_id();return s&&r===s?i:[]}Vs(){var e,n=(e=this._instance)==null||e.get_session_id==null?void 0:e.get_session_id();n&&this.Xs(n)}Gs(){this.ta()}Ss(e){var n,i=(n=this._instance)==null||(n=n.persistence)==null?void 0:n.props[this.Ys()];if(i&&i!==e){var r=this.Zs(),s=this.Qs();r.length>0&&(this.Ws([]),r.filter((o=>ke(s[o]))).forEach((o=>this.Bs(o)))),this.Gs(),this.Ks()}}getActivatedIds(){return[...new Set([...this.zs(),...this._s])].filter((e=>!this.ea(e)))}reset(){this._s=[],this.Zs().length>0&&this.Ws([]),this.Gs(),this.Ks()}getEventToItemsMap(){return this.ws}ia(){return this.Os}}class zm extends Wm{constructor(e){super(e)}Js(){return da}Ys(){return Tr}Ms(){return $r}Ts(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[$r]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister($r)}Cs(e){var n,i;this.As((s=>{i=s.find((o=>o.id===e))}));var r=(n=i)==null||(n=n.appearance)==null?void 0:n.surveyPopupDelaySeconds;return ke(r)&&r>0}ra(){return qt.SHOWN}As(e){var n;(n=this._instance)==null||n.getSurveys(e)}Bs(e){var n;(n=this._instance)==null||n.cancelPendingSurvey(e)}Ds(){return Q}Ws(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[da]:e})}Xs(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Tr]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Tr)}ea(){return!1}$s(e,n){var i;this.As((s=>{i=s.find((o=>o.id===n))}));var r=!i||(function(s){var o;return Kf(s)&&!((o=s.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||s.schedule==="always"})(i);return r?e===qt.SHOWN?"consume":"ignore":e===qt.SHOWN?"persist":e===qt.DISMISSED||e===qt.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var Cr="SDK is not enabled or survey functionality is not yet loaded",gu="Disabled. Not loading surveys.",qm=w!=null&&w.location?ls(w.location.hash,"__posthog")||ls(location.hash,"state"):null,mu="_postHogToolbarParams",vu=pe("[Toolbar]"),_u=pe("[FeatureFlags]");class Vm{constructor(e,n){n===void 0&&(n=!1),this.na=!1,this.update(e,n)}update(e,n){this.sa=((i,r)=>{var s,o,a,l;return{bootstrap:{featureFlags:(s=i.bootstrap)==null?void 0:s.featureFlags,featureFlagPayloads:(o=i.bootstrap)==null?void 0:o.featureFlagPayloads},remoteRequestsDisabled:r,featureFlagsDisabled:!!i.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!i.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!i.advanced_feature_flags_dedup_per_session,cacheTtlMs:i.feature_flag_cache_ttl_ms,requestTimeoutMs:i.feature_flag_request_timeout_ms,compression:i.disable_compression?"none":"base64",evaluationContexts:(a=(l=i.evaluation_contexts)!==null&&l!==void 0?l:i.evaluation_environments)!==null&&a!==void 0?a:[],flagKeys:U(i.flag_keys)?i.flag_keys:void 0}})(e,n),!e.evaluation_environments||e.evaluation_contexts||this.na||(_u.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.na=!0),C(e.flag_keys)||U(e.flag_keys)||_u.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var yu=pe("[FeatureFlags]"),bn=pe("[FeatureFlags]",{debugEnabled:!0}),jo=`" failed. Feature flags didn't load in time.`,wu="connection_error",bu=t=>{for(var e={},n=0;t.length>n;n++)e[t[n]]=!0;return e},Eu=t=>{var e={};for(var n of Lr(t||{})){var i=n[1];i&&(e[n[0]]=i)}return e},St=pe("[Error tracking]"),Su="Refusing to render web experiment since the viewer is a likely bot",Gm={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>ds(e,t),not_regex:(t,e)=>!ds(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class Me{get Ne(){return this._instance.config}constructor(e){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(i){i===void 0&&(i=!1),n.getWebExperiments((r=>{Me.aa("retrieved web experiments from the server"),n.oa=new Map,r.forEach((s=>{if(s.feature_flag_key){var o;n.oa&&(Me.aa("setting flag key ",s.feature_flag_key," to web experiment ",s),(o=n.oa)==null||o.set(s.feature_flag_key,s));var a=n._instance.getFeatureFlag(s.feature_flag_key);X(a)&&s.variants[a]&&n.la(s.name,a,s.variants[a].transforms)}else if(s.variants)for(var l in s.variants){var u=s.variants[l];Me.ua(u,n._instance)&&n.la(s.name,l,u.transforms)}}))}),i)},this._instance=e,this._instance.onFeatureFlags((i=>{this.onFeatureFlags(i)}))}initialize(){}onFeatureFlags(e){if(this._is_bot())Me.aa(Su);else if(!this.Ne.disable_web_experiments){if(H(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();Me.aa("applying feature flags",e),e.forEach((n=>{var i;if(this.oa&&(i=this.oa)!=null&&i.has(n)){var r,s=this._instance.getFeatureFlag(n),o=(r=this.oa)==null?void 0:r.get(n);s&&o!=null&&o.variants[s]&&this.la(o.name,s,o.variants[s].transforms)}}))}}previewWebExperiment(){var e=Me.getWindowLocation();if(e!=null&&e.search){var n=ri(e?.search,"__experiment_id"),i=ri(e?.search,"__experiment_variant");n&&i&&(Me.aa("previewing web experiments "+n+" && "+i),this.getWebExperiments((r=>{this.ha(parseInt(n),i,r)}),!1,!0))}}loadIfEnabled(){this.Ne.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,n,i){if(this.Ne.disable_web_experiments&&!i)return e([]);var r=this._instance.get_property("$web_experiments");if(r&&!n)return e(r);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this.Ne.token),method:"GET",timestampMode:"query",callback:s=>e(s.statusCode===200&&s.json&&s.json.experiments||[])})}ha(e,n,i){var r=i.filter((s=>s.id===e));r&&r.length>0&&(Me.aa("Previewing web experiment ["+r[0].name+"] with variant ["+n+"]"),this.la(r[0].name,n,r[0].variants[n].transforms))}static ua(e,n){return!H(e.conditions)&&Me.da(e,n)&&Me.va(e)}static da(e,n){var i;if(H(e.conditions)||H((i=e.conditions)==null?void 0:i.url))return!0;var r=Me.getWindowLocation();if(r){var s,o,a,l=uf(n,r.href);return(s=e.conditions)==null||!s.url||Gm[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return w?.location}static va(e){var n;if(H(e.conditions)||H((n=e.conditions)==null?void 0:n.utm))return!0;var i=If();if(i.utm_source){var r,s,o,a,l,u,c,d,h=(r=e.conditions)==null||(r=r.utm)==null||!r.utm_campaign||((s=e.conditions)==null||(s=s.utm)==null?void 0:s.utm_campaign)==i.utm_campaign,f=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==i.utm_source,p=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==i.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==i.utm_term;return h&&p&&g&&f}return!1}static aa(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;n>r;r++)i[r-1]=arguments[r];A.info("[WebExperiments] "+e,i)}la(e,n,i){this._is_bot()?Me.aa(Su):n!=="control"?i.forEach((r=>{if(r.selector){var s;Me.aa("applying transform of variant "+n+" for experiment "+e+" ",r);var o=(s=document)==null?void 0:s.querySelectorAll(r.selector);o?.forEach((a=>{var l=a;r.html&&(l.innerHTML=r.html),r.css&&l.setAttribute("style",r.css)}))}})):Me.aa("Control variants leave the page unmodified.")}_is_bot(){return He&&this._instance?zf(He,this.Ne.custom_blocked_useragents):void 0}}var ot=pe("[Conversations]"),En="Conversations not available yet.",xu="console",Qf="__posthogHandledLogsRequestError",Uo=(t,e)=>{var n=t instanceof Error?t:new Error(e);return n[Qf]=!0,n},Iu=t=>!!t&&typeof t=="object"&&t[Qf]===!0,Ps={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=yu,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 Vm(t.config,t.Qi()),this.Ta=this.Ea)}updateConfig(t,e){var n;(n=this.Ea)==null||n.update(t,e)}setup(t){return this.Ia=t,this.rt=t.logger.createLogger("[FeatureFlags]"),n=()=>{this.Ia===t&&(this.Ia=void 0,this.nn=t,this.Pa(t))},(e=t.kv.initialize())!=null&&e.then?e.then(n):n();var e,n}Pa(t){if(this.nn===t)return w&&ve(w,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){w?.removeEventListener("online",this.Ca)}dispose(){var t;this.ba++,this.wa=!1,this.Ia=void 0,this.nn&&(this.La(),(t=this.Ra)==null||t.dispose(),this.Ra=void 0,this.ga=[],w?.removeEventListener("online",this.Ca),this.nn=void 0)}get Ne(){return this.Ta.get()}Oa(t){var e;return(e=this.nn)==null?void 0:e.kv.get(t)}F(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.set(t)}))}q(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.remove(t)}))}Da(t){try{t()}catch(e){this.rt.error("Failed to update feature flag persistence",e)}}Fa(){var t={};for(var e of[$i,Mi,Rr,It]){var n=this.Oa(e);C(n)||(t[e]=n)}this.fa=t;var i=I({},t),r=this.Oa(Sn);if(r)for(var s of Object.entries(r))i["$feature/"+s[0]]=s[1];this.pa=i}Aa(){var t=this.Ne.cacheTtlMs;if(!t||0>=t)return!1;var e=this.Oa(Ui);return typeof e!="number"||Date.now()-e>t}$a(){return!!this.Aa()&&(this.xa||this.ya||(this.xa=!0,this.rt.warn("Feature flag cache is stale, triggering refresh..."),this.reloadFeatureFlags()),!0)}Na(){var t=this.Ne.evaluationContexts;return t!=null&&t.length?t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid evaluation context found:",e,"Expected non-empty string"),n})):[]}qa(){var t=this.Ne.flagKeys;if(!C(t))return t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid flag key found:",e,"Expected non-empty string"),n}))}initialize(){var t,e,n=this.Ne,i=(t=(e=n.bootstrap)==null?void 0:e.featureFlags)!==null&&t!==void 0?t:{};if(Object.keys(i).length){var r,s,o=(r=(s=n.bootstrap)==null?void 0:s.featureFlagPayloads)!==null&&r!==void 0?r:{},a=Object.keys(i).filter((u=>!!i[u])).reduce(((u,c)=>(u[c]=i[c]||!1,u)),{}),l=Object.keys(o).filter((u=>a[u])).reduce(((u,c)=>(o[c]&&(u[c]=o[c]),u)),{});return this.ja({featureFlags:a,featureFlagPayloads:l})}}updateFlags(t,e,n){var i,r,s=n!=null&&n.merge&&(i=this.Oa(Sn))!==null&&i!==void 0?i:{},o=n!=null&&n.merge&&(r=this.Oa(Mi))!==null&&r!==void 0?r:{},a=I({},s,t),l=I({},o,e),u={};for(var c of Object.entries(a)){var d=c[0],h=c[1];u[d]={key:d,enabled:vc(h),variant:_c(h),reason:void 0,metadata:C(l?.[d])?void 0:{id:0,version:void 0,description:void 0,payload:l[d]}}}this.ja({flags:u})}get hasLoadedFlags(){return this.ma}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var t=this.Oa(ca),e=this.Oa(It),n=this.Oa(xn);if(!n&&!e)return t||{};var i=fe({},t||{}),r=[...new Set([...Object.keys(n||{}),...Object.keys(e||{})])];for(var s of r){var o,a,l=i[s],u=e?.[s],c=C(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=C(u)?l?.variant:typeof u=="string"?u:void 0,h=n?.[s],f=I({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(f.original_enabled=l?.enabled),d!==l?.variant&&(f.original_variant=l?.variant),h&&(f.metadata=I({},l?.metadata,{payload:h,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),i[s]=f}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:n,finalDetails:i}),this.ca=!0),i}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((n=>{var i=t[n];return{key:n,enabled:vc(i),variant:_c(i),payload:mc(e[n])}}))}getFlagVariants(){var t=this.Oa(Sn),e=this.Oa(It);if(!e)return t||{};for(var n=fe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:e,finalFlags:n}),this.ca=!0),n}getFlagPayloads(){var t=this.Oa(Mi),e=this.Oa(xn);if(!e)return t||{};for(var n=fe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flag payloads!",{flagPayloads:t,overriddenPayloads:e,finalPayloads:n}),this.ca=!0),n}reloadFeatureFlags(){this._a||this.Ne.featureFlagsDisabled||this.Ma()||this.Ba||(this.ga.slice().forEach((t=>{try{t()}catch(e){this.rt.error("Error while running feature flags reloading callback",e)}})),this.Ba=setTimeout((()=>{this.Ha()}),5))}La(){clearTimeout(this.Ba),this.Ba=void 0}onReloading(t){return this.ga.push(t),()=>{this.ga=this.ga.filter((e=>e!==t))}}ensureFlagsLoaded(){this.ma||this.ya||this.Ba||this.reloadFeatureFlags()}setAnonymousDistinctId(t){this.$anon_distinct_id=t}setReloadingPaused(t){this._a=t}resetFlagCallReported(){this.q(Cn)}Ha(t){this.La();var e=this.nn;if(e&&!this.Ne.remoteRequestsDisabled&&!this.Ma())if(this.ya)this.wa=!0;else{var n={token:e.projectToken,distinct_id:e.distinctId,groups:e.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:I({},e.initialPersonProperties,this.Oa(jt)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(In),timezone:Rf()};C(e.deviceId)||(n.$device_id=e.deviceId),(t!=null&&t.disableFlags||this.Ne.featureFlagsDisabled)&&(n.disable_flags=!0);var i=this.Na();i.length&&(n.evaluation_contexts=i);var r=this.qa();C(r)||(n.flag_keys=r);var s=this.Ne.onlyEvaluateSurveyFeatureFlags,o="/flags/?v=2"+(s?"&only_evaluate_survey_feature_flags=true":""),a=this.ba;this.ya=!0;var l=()=>{this.wa&&(this.wa=!1,this.Ha())},u=c=>{this.ya=!1,a===this.ba&&(this.F({[Mr]:[wu]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:n,compression:this.Ne.compression==="base64"?Ue.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,h,f=(d=c.json)!==null&&d!==void 0?d:{},p=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),p||this.wa||(this.$anon_distinct_id=void 0),!n.disable_flags||this.wa){this.ka=!p;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?wu:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),f.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((h=f.quotaLimited)==null||!h.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[Mr]:g}),m?this.rt.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more."):n.disable_flags||this.ja(f,p,{partialResponse:s}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return Sf(this.Sa,3)}Ua(t){this.Sa=xf(t,this.Sa,3,(()=>this.rt.warn("Feature flag requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped refreshing feature flags; will try again when connectivity changes.")))}getFeatureFlag(t,e){var n;if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var i=this.getFeatureFlagResult(t,e);return(n=i?.variant)!==null&&n!==void 0?n:i?.enabled}}else this.rt.warn('getFeatureFlag for key "'+t+jo)}getFeatureFlagDetails(t){return this.getFlagsWithDetails()[t]}getFeatureFlagPayload(t){var e=this.getFeatureFlagResult(t,{send_event:!1});return e?.payload}getFeatureFlagResult(t,e){if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var n,i=this.getFlagVariants(),r=t in i,s=i[t],o=this.getFlagPayloads()[t],a=String(s),l=this.Oa(Rr)||void 0,u=this.Oa(Ui)||void 0,c=this.Oa(Cn)||{};if(this.Ne.deduplicateCallsPerSession){var d,h=(d=this.nn)==null?void 0:d.session.sessionId,f=this.Oa(Ni);h&&h!==f&&(c={},n=h)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))n&&this.F({[Cn]:c,[Ni]:n});else{var p,g,m,v,E,S,_,b,k,T;U(c[t])?c[t].push(a):c[t]=[a],this.F(I({[Cn]:c},n?{[Ni]:n}:{}));var x=this.getFeatureFlagDetails(t),F=[...(p=this.Oa(Mr))!==null&&p!==void 0?p:[]];C(s)&&F.push("flag_missing");var $={$feature_flag:t,$feature_flag_response:s,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((g=this.Ne.bootstrap)==null||(g=g.featureFlags)==null?void 0:g[t])||null,$feature_flag_bootstrapped_payload:((m=this.Ne.bootstrap)==null||(m=m.featureFlagPayloads)==null?void 0:m[t])||null,$used_bootstrap_value:!this.ka};C(x==null||(v=x.metadata)==null?void 0:v.has_experiment)||($.$feature_flag_has_experiment=x.metadata.has_experiment),C(x==null||(E=x.metadata)==null?void 0:E.version)||($.$feature_flag_version=x.metadata.version);var O,L=(S=x==null||(_=x.reason)==null?void 0:_.description)!==null&&S!==void 0?S:x==null||(b=x.reason)==null?void 0:b.code;L&&($.$feature_flag_reason=L),x!=null&&(k=x.metadata)!=null&&k.id&&($.$feature_flag_id=x.metadata.id),C(x?.original_variant)&&C(x?.original_enabled)||($.$feature_flag_original_response=C(x.original_variant)?x.original_enabled:x.original_variant),x!=null&&(T=x.metadata)!=null&&T.original_payload&&($.$feature_flag_original_payload=x==null||(O=x.metadata)==null?void 0:O.original_payload),F.length&&($.$feature_flag_error=F.join(",")),this.za($)}else n&&this.F({[Cn]:c,[Ni]:n});if(r)return{key:t,enabled:!!s,variant:typeof s=="string"?s:void 0,payload:mc(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+jo)}za(t){try{var e;(e=this.nn)==null||e.capture("$feature_flag_called",t).catch((n=>{this.rt.error("Failed to capture feature flag call",n)}))}catch(n){this.rt.error("Failed to capture feature flag call",n)}}getRemoteConfigPayload(t,e){this.Wa(t,e)}Wa(t,e){var n=this;return se((function*(){var i=n.nn;if(i){var r={distinct_id:i.distinctId,token:i.projectToken,person_properties:{$lib:i.library.name,$lib_version:i.library.version}},s=n.Na();s.length&&(r.evaluation_contexts=s);var o,a=n.qa();C(a)||(r.flag_keys=a);try{var l,u=(l=(yield i.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:r,compression:n.Ne.compression==="base64"?Ue.Base64:void 0,sentAt:"body",timeoutMs:n.Ne.requestTimeoutMs})).json)==null?void 0:l.featureFlagPayloads;o=u?.[t]||void 0}catch(c){return void n.rt.error("Remote config feature flag request failed",c)}try{e(o)}catch(c){n.rt.error("Remote config feature flag callback failed",c)}}}))()}isFeatureEnabled(t,e){if(e===void 0&&(e={}),e.fresh&&!this.ka)return e.defaultValue;if(!(this.ma||this.getFlags()&&this.getFlags().length>0))return this.rt.warn('isFeatureEnabled for key "'+t+jo),e.defaultValue;var n=this.getFeatureFlag(t,e);return C(n)?e.defaultValue:!!n}addFeatureFlagsHandler(t){this.featureFlagEventHandlers.push(t)}removeFeatureFlagsHandler(t){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((e=>e!==t))}receivedFeatureFlags(t,e,n){this.ja(t,e,n)}ja(t,e,n){if(this.nn){this.ma=!0;var i=(function(r,s,o,a,l,u){s===void 0&&(s={}),o===void 0&&(o={}),a===void 0&&(a={}),u===void 0&&(u=yu);var c=((k,T)=>{var x=k.flags;return x?I({},k,{featureFlags:Object.fromEntries(Object.keys(x).map((F=>{var $;return[F,($=x[F].variant)!==null&&$!==void 0?$:x[F].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(x).filter((F=>x[F].enabled)).filter((F=>{var $;return($=x[F].metadata)==null?void 0:$.payload})).map((F=>{var $;return[F,($=x[F].metadata)==null?void 0:$.payload]})))}):(k.featureFlags&&T.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),k)})(r,u),d=c.flags,h=c.featureFlags,f=c.featureFlagPayloads;if(h){var p=r.requestId,g=r.evaluatedAt;if(U(h)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(h)for(var v=0;h.length>v;v++)m[h[v]]=!0;return{[$i]:h,[Sn]:m,[Qr]:!1}}var E=h,S=f,_=d;if(l!=null&&l.partialResponse)E=I({},s,E),S=I({},o,S),_=I({},a,_);else if(r.errorsWhileComputingFlags)if(d){var b=new Set(Object.keys(d).filter((k=>{var T;return!((T=d[k])!=null&&T.failed)})));E=I({},s,Object.fromEntries(Object.entries(E).filter((k=>b.has(k[0]))))),S=I({},o,Object.fromEntries(Object.entries(S||{}).filter((k=>b.has(k[0]))))),_=I({},a,Object.fromEntries(Object.entries(_||{}).filter((k=>b.has(k[0])))))}else E=I({},s,E),S=I({},o,S),_=I({},a,_);return I({[$i]:Object.keys(Eu(E)),[Sn]:E||{},[Mi]:S||{},[ca]:_||{},[Qr]:r.minimalFlagCalledEvents===!0},p?{[Rr]:p}:{},g?{[Ui]:g}:{})}})(t,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),n,this.rt);i&&this.F(i),e||(this.xa=!1),this.Va(e)}}override(t,e){e===void 0&&(e=!1),this.rt.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:t,suppressWarning:e})}overrideFeatureFlags(t){this.Za(t)}Za(t){if(this.nn){if(t===!1)return this.q([It,xn]),this.Va(),void bn.info("All overrides cleared");if(U(t))return this.F({[It]:bu(t)}),this.Va(),void bn.info("Flag overrides set",{flags:t});if(t&&typeof t=="object"&&("flags"in t||"payloads"in t)){var e,n=t;this.ca=!!((e=n.suppressWarning)!==null&&e!==void 0&&e);var i={},r=n.flags,s=n.payloads;return r&&(i[It]=U(r)?bu(r):r),s&&(i[xn]=s),Object.keys(i).length&&this.F(i),r===!1&&s===!1?this.q([It,xn]):r===!1?this.q(It):s===!1&&this.q(xn),this.Va(),r===!1?bn.info("Flag overrides cleared"):r&&bn.info("Flag overrides set",{flags:r}),void(s===!1?bn.info("Payload overrides cleared"):s&&bn.info("Payload overrides set",{payloads:s}))}if(t&&typeof t=="object")return this.F({[It]:t}),this.Va(),void bn.info("Flag overrides set",{flags:t});this.rt.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:t})}else this.rt.warn("posthog.featureFlags.overrideFeatureFlags called before feature flags were ready")}onFeatureFlags(t){if(this.addFeatureFlagsHandler(t),this.ma){var e=this.Ga(),n=e.flags,i=e.flagVariants;try{t(n,i)}catch(r){this.rt.error("Error while running feature flags callback",r)}}return()=>this.removeFeatureFlagsHandler(t)}updateEarlyAccessFeatureEnrollment(t,e,n){var i=(this.Oa(Fr)||[]).find((l=>l.flagKey===t)),r={["$feature_enrollment/"+t]:e},s={$feature_flag:t,$feature_enrollment:e,$set:r};i&&(s.$early_access_feature_name=i.name),n&&(s.$feature_enrollment_stage=n);var o=I({},this.getFlagVariants(),{[t]:e});this.F({[$i]:Object.keys(Eu(o)),[Sn]:o,[jt]:I({},this.Oa(jt)||{},r)}),this.Va();try{var a;(a=this.nn)==null||a.capture("$feature_enrollment_update",s).catch((l=>{this.rt.error("Failed to capture early access feature enrollment",l)}))}catch(l){this.rt.error("Failed to capture early access feature enrollment",l)}}getEarlyAccessFeatures(t,e,n){e===void 0&&(e=!1);var i=this.Oa(Fr);!i||e?this.Qa(t,n):t(i)}Qa(t,e){var n=this;return se((function*(){var i=n.nn;if(i){var r,s=e?"&"+e.map((a=>"stage="+a)).join("&"):"";try{var o=yield i.sendRequest("/api/early_access_features/?token="+i.projectToken+s,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;n.F({[Fr]:r=o.json.earlyAccessFeatures})}catch(a){return void n.rt.error("Early access feature request failed",a)}try{t(r)}catch(a){n.rt.error("Early access feature callback failed",a)}}}))()}Ga(){var t=this.getFlags(),e=this.getFlagVariants();return{flags:t.filter((n=>e[n])),flagVariants:Object.keys(e).filter((n=>e[n])).reduce(((n,i)=>(n[i]=e[i],n)),{})}}Va(t){this.Fa();var e=this.Ga(),n=e.flags,i=e.flagVariants;this.featureFlagEventHandlers.forEach((r=>{try{r(n,i,{errorsLoading:t})}catch(s){this.rt.error("Error while running feature flags callback",s)}}))}setPersonPropertiesForFlags(t,e){e===void 0&&(e=!0),this.Ka(t,e)}Ka(t,e){e===void 0&&(e=!0);var n=this.Oa(jt)||{},i=t?.$set||(t!=null&&t.$set_once?{}:t),r=t?.$set_once,s={};if(r)for(var o in r)({}).hasOwnProperty.call(r,o)&&(o in n||(s[o]=r[o]));this.F({[jt]:I({},n,s,i)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=I({},this.Oa(jt)||{});t.forEach((i=>{delete n[i]})),this.F({[jt]:n}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(jt),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=this.Oa(In)||{},i=I({},n);for(var r of Object.keys(t))i[r]=I({},n[r],t[r]);this.F({[In]:i}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(In)||{};this.F({[In]:I({},e,{[t]:{}})})}else this.q(In)}reset(){this.ba++,this.wa=!1,this.Fa(),this.ma=!1,this._a=!1,this.ka=!1,this.$anon_distinct_id=void 0,this.La(),this.ca=!1,this.Sa=0}}},Km={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===Ci||this.Ya===Ir?this.Ya:(t=(e=this.Ja)==null?void 0:e.status)!==null&&t!==void 0?t:this.Ya}constructor(t){if(this._forceAllowLocalhostNetworkCapture=!1,this.Ya=fu,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(P==null||!P.visibilityState||P.visibilityState==="visible")return!0;var n=w==null||(e=w.performance)==null||e.getEntriesByType==null?void 0:e.getEntriesByType("visibility-state");return!(n!=null&&n.length)||n.some((i=>i.name==="visible"))})(),this.Ie=()=>{var e;P?.visibilityState==="visible"&&(this.io=!0,(e=this.Ja)==null||e.setDocumentWasEverVisible==null||e.setDocumentWasEverVisible(!0))},this._instance=t,!this._instance.sessionManager)throw Bt.error("started without valid sessionManager"),new Error(Ca+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===Wt)throw new Error(Ca+' cannot be used with cookieless_mode="always"');P!=null&&P.addEventListener&&ve(P,"visibilitychange",this.Ie)}initialize(){this.startIfEnabledOrStop()}dispose(){this.eo=!0,P==null||P.removeEventListener==null||P.removeEventListener("visibilitychange",this.Ie),this.stopRecording()}get ro(){var t,e=!((t=this._instance.get_property(An))==null||!t.enabled),n=!this.Ne.disable_session_recording,i=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return w&&e&&n&&!i}startIfEnabledOrStop(t){var e;if(!(this.eo||this.ro&&(e=this.Ja)!=null&&e.isStarted)){var n=!C(Object.assign)&&!C(Array.from);this.ro&&n?(this.no(t),Bt.info("starting")):(this.Ya=fu,this.stopRecording())}}no(t){var e,n,i;this.ro&&(this.Ya!==Ci&&this.Ya!==Ir&&(this.Ya=hu),B!=null&&(e=B.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(n=B.__PosthogExtensions__)!=null&&n.initSessionRecording?this.so(t):(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,this.ao,(r=>{if(r)return Bt.error("could not load recorder",r);this.so(t)})))}stopRecording(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.stop()}oo(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.discard()}lo(){var t,e;(t=this.Mr)==null||t.unregister(cl),(e=this.Mr)==null||e.unregister(Xd)}uo(t,e){if(H(t))return null;var n,i=ke(t)?t:parseFloat(t);return typeof(n=i)!="number"||!Number.isFinite(n)||0>n||n>1?(Bt.warn(e+" must be between 0 and 1. Ignoring invalid value:",t),null):i}ho(t){if(this.Mr){var e,n,i=this.Mr,r=()=>{var s,o=t.sessionRecording===!1?void 0:t.sessionRecording,a=this.uo((s=this.Ne.session_recording)==null?void 0:s.sampleRate,"session_recording.sampleRate"),l=this.uo(o?.sampleRate,"remote config sampleRate"),u=a??l;H(u)&&this.lo();var c=o?.minimumDurationMilliseconds;i.register({[An]:I({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:I({capturePerformance:t.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:u,minimumDurationMilliseconds:C(c)?null:c,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers,version:o?.version,triggerGroups:o?.triggerGroups})})};r(),(e=this.Xa)==null||e.call(this),this.Xa=(n=this._instance.sessionManager)==null?void 0:n.onSessionId(r)}}onRemoteConfig(t){var e=t.ok?t.config:void 0;return e&&"sessionRecording"in e?e.sessionRecording===!1?(this.ho(e),void this.oo()):(this.ho(e),void this.startIfEnabledOrStop()):(this.Ya===Ci&&(this.Ya=Ir,Bt.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(t,e){var n;e===void 0&&(e="log"),(n=this.Ja)!=null&&n.log?this.Ja.log(t,e):Bt.warn("log called before recorder was ready")}get ao(){var t,e,n=(t=this._instance)==null||(t=t.persistence)==null?void 0:t.get_property(An);return(n==null||(e=n.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(An);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(n){return Bt.warn("persisted remote config for session recording is invalid and will be ignored",n),!1}return!H(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,n,i;if(!this.eo){if((e=B.__PosthogExtensions__)==null||!e.initSessionRecording)return Bt.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[af]:!0});var r;if(this.Ja||(this.Ja=(r=B.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===Ir||this.Ya===Ci?void 0:(this.Ya=Ci,Bt.info("persisted remote config is stale, requesting fresh config before starting"),void new Tf(this._instance).load());this.Ya=hu,(n=(i=this.Ja).setDocumentWasEverVisible)==null||n.call(i,this.io),this.Ja.start(t)}}onRRwebEmit(t){var e;(e=this.Ja)==null||e.onRRwebEmit==null||e.onRRwebEmit(t)}overrideLinkedFlag(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[ef]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Qd]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,n;this.Ja||(n=this.Mr)==null||n.register({[t==="url"?tf:nf]:!0}),(e=this.Ja)==null||e.overrideTrigger(t)}get sdkDebugProperties(){var t;return((t=this.Ja)==null?void 0:t.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(t,e){var n;return!((n=this.Ja)==null||!n.tryAddCustomEvent(t,e))}}},Ym={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new cu(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,n=he(this.instance.config.autocapture)?this.instance.config.autocapture:{};return n.url_allowlist=(t=n.url_allowlist)==null?void 0:t.map((i=>new RegExp(i))),n.url_ignorelist=(e=n.url_ignorelist)==null?void 0:e.map((i=>new RegExp(i))),n}yo(){if(this.isBrowserSupported()){if(w&&P){var t=n=>{n=n||w?.event;try{this.bo(n)}catch(i){No.error("Failed to capture event",i)}};if(ve(P,"submit",t,{capture:!0}),ve(P,"change",t,{capture:!0}),ve(P,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=n=>{n=n||w?.event;try{this.bo(n,Lo)}catch(i){No.error("Failed to capture copy/cut event",i)}};ve(P,"copy",e,{capture:!0}),ve(P,"cut",e,{capture:!0})}}}else No.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.vo&&(this.yo(),this.vo=!0)}onRemoteConfig(t){if(this.fo=!0,t.ok){var e=t.config;e.elementsChainAsString&&(this.po=e.elementsChainAsString);var n=e.autocapture_opt_out;mt(n)&&(this.instance.persistence&&this.instance.persistence.register({[na]:n}),this.co=n),this.startIfEnabled()}else this.startIfEnabled()}setElementSelectors(t){this.mo=t}getElementSelectors(t){var e,n=[];return(e=this.mo)==null||e.forEach((i=>{var r=P?.querySelectorAll(i);r?.forEach((s=>{t===s&&n.push(i)}))})),n}get isEnabled(){var t,e,n=(t=this.instance.persistence)==null?void 0:t.props[na],i=this.co,r=this.instance.Qi()&&!this.fo;if(Ye(i)&&!mt(n)&&!r)return!1;var s=(e=this.co)!==null&&e!==void 0?e:!!n;return!!this.instance.config.autocapture&&!s}bo(t,e){if(e===void 0&&(e="$autocapture"),this.isEnabled){var n,i=So(t);ff(i)&&(i=i.parentNode||null),e==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&this.instance.config.rageclick&&(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,t.timeStamp||new Date().getTime())&&Dc(i,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var r=e===Lo;if(i&&(function(d,h,f,p,g,m){var v;if(!w||pl(d)||f!=null&&f.url_allowlist&&!Nc(f.url_allowlist,m)||f!=null&&f.url_ignorelist&&Nc(f.url_ignorelist,m))return!1;if(f!=null&&f.dom_event_allowlist){var E=f.dom_event_allowlist;if(E&&!E.some((x=>h.type===x)))return!1}var S=_f(d,p),_=S.parentIsUsefulElement,b=S.targetElementList;if(!(function(x,F){var $=F?.element_allowlist;if(C($))return!0;var O,L=function(K){if($.some((V=>K.tagName.toLowerCase()===V)))return{v:!0}};for(var N of x)if(O=L(N))return O.v;return!1})(b,f)||!_a(b,f?.css_selector_allowlist)||_a(b,(v=f?.css_selector_ignorelist)!==null&&v!==void 0?v:Vg))return!1;try{var k=w.getComputedStyle(d);if(k&&k.getPropertyValue("cursor")==="pointer"&&h.type==="click")return!0}catch{}var T=d.tagName.toLowerCase();switch(T){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 _?(g||["click"]).indexOf(h.type)>=0:(g||["click"]).indexOf(h.type)>=0&&(hl.indexOf(T)>-1||d.getAttribute("contenteditable")==="true")}})(i,t,this.Ne,r,r?["copy","cut"]:void 0,this.instance)){var s=Bm(i,{e:t,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.Ne.element_attribute_ignorelist,elementsChainAsString:this.po,disableCaptureUrlHashes:this.instance.config.disable_capture_url_hashes}),o=s.props;if(s.explicitNoCapture)return!1;var a=this.getElementSelectors(i);if(a&&a.length>0&&(o.$element_selectors=a),e===Lo){var l,u=gf(w==null||(l=w.getSelection())==null?void 0:l.toString()),c=t.type||"clipboard";if(!u)return!1;o.$selected_content=u,o.$copy_type=c}return this.instance.capture(e,o),!0}}}isBrowserSupported(){return je(P?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(w==null||(e=w.location)==null?void 0:e.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(A.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.wo&&this.wo(),this.wo=void 0,A.info("History API monitoring stopped")}monitorHistoryChanges(){w&&w.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(w&&((e=w.history[t])==null||!e.__posthog_wrapped__)){var n=this;(function(i,r,s){try{if(!(r in i))return uu;var o={next:i[r]},a=s((function(){for(var l=arguments.length,u=new Array(l),c=0;l>c;c++)u[c]=arguments[c];return o.next.apply(this,u)}));return je(a)&&(a.prototype=a.prototype||{},Object.defineProperties(a,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:o}})),i[r]=a,()=>{if(i[r]!==a)for(var l=i[r];je(l)&&l.__posthog_layer__;){var u=l.__posthog_layer__;if(u.next===a)return void(u.next=o.next);l=u.next}else i[r]=o.next}}catch{return uu}})(w.history,t,(i=>function(r,s,o){i.call(this,r,s,o),n.So(t)}))}}So(t){try{var e,n=w==null||(e=w.location)==null?void 0:e.pathname;if(!n)return;n!==this._o&&this.isEnabled&&this._instance.capture(Gn,{navigation_type:t}),this._o=n}catch(i){A.error("Error capturing "+t+" pageview",i)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};ve(w,"popstate",t),this.wo=()=>{w&&w.removeEventListener("popstate",t)}}}},heatmaps:class{get Ne(){return this.instance.config}constructor(t){var e;this.Co=!1,this.vo=!1,this.Mo=null,this.instance=t,this.Co=!((e=this.instance.persistence)==null||!e.props[ia]),this.rageclicks=new cu(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return he(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return H(this.Ne.capture_heatmaps)?H(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;jm.info("starting..."),this.To(),this.Ie()}else{var t;clearInterval((t=this.Mo)!==null&&t!==void 0?t:void 0),this.Eo(),this.getAndClearBuffer()}}onRemoteConfig(t){if(t.ok){var e=t.config;if("heatmaps"in e){var n=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[ia]:n}),this.Co=n,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){Bo(t.originalEvent)&&this.ke(t.originalEvent,"deadclick")}Ie(){this.Mo&&clearInterval(this.Mo),this.Mo=P?.visibilityState==="visible"?setInterval(this.cr.bind(this),this.flushIntervalMilliseconds):null}To(){w&&P&&(this.Po=this.cr.bind(this),ve(w,rs,this.Po),this.Ro=t=>this.ke(t||w?.event),ve(P,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||w?.event),ve(P,"mousemove",this.Ao,{capture:!0}),this.Lo=new Vc(this.instance,Qg,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),ve(P,is,this.Oo),this.vo=!0)}Eo(){var t;w&&P&&(this.Po&&w.removeEventListener(rs,this.Po),this.Ro&&P.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&P.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&P.removeEventListener(is,this.Oo),clearTimeout(this.Do),(t=this.Lo)==null||t.stop(),this.vo=!1)}$o(t,e){var n=this.instance.scrollManager.scrollY(),i=this.instance.scrollManager.scrollX(),r=this.instance.scrollManager.scrollElement(),s=(function(o,a,l){for(var u=o;u&&hn(u)&&!et(u,"body");){if(u===l)return!1;var c=void 0;try{var d,h,f;c=(d=(h=(f=u.ownerDocument)==null?void 0:f.defaultView)!==null&&h!==void 0?h:w)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(j(a,c))return!0;u=mf(u)}return!1})(So(t),["fixed","sticky"],r);return{x:t.clientX+(s?0:i),y:t.clientY+(s?0:n),target_fixed:s,type:e}}ke(t,e){var n;if(e===void 0&&(e="click"),!Lc(t.target)&&Bo(t)){var i=this.$o(t,e);(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,new Date().getTime())&&Dc(So(t),this.instance.config.rageclick)&&this.Vt(I({},i,{type:"rageclick"})),this.Vt(i)}}Fo(t){!Lc(t.target)&&Bo(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(w){var e=this.Ne.disable_capture_url_hashes?fn(w.location.href):w.location.href,n=this.Ne.custom_personal_data_properties,i=this.Ne.mask_personal_data_properties?[...si,...n||[]]:[],r=Xi(e,i,Qi);this.R=this.R||{},this.R[r]||(this.R[r]=[]),this.R[r].push(t)}}cr(){this.R&&!Kt(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:Vc,webVitalsAutocapture:class{constructor(t){var e;this.Co=!1,this.vo=!1,this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this.No=()=>{clearTimeout(this.qo),this.qo=void 0,this.R.metrics.length!==0&&(this._instance.capture("$web_vitals",I({$current_url:this.R.url},this.R.metrics.reduce(((n,i)=>I({},n,{["$web_vitals_"+i.name+"_event"]:I({},i),["$web_vitals_"+i.name+"_value"]:i.value})),{}))),this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.jo=n=>{var i;if(this.R=this.R||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},H(n?.name)||H(n?.value))wn.error("Invalid metric received",n);else{var r=typeof n.navigationURL=="string"?n.navigationURL:void 0,s=this.Bo(r);if(!C(s)){var o=ke(n.navigationId)||typeof n.navigationId=="string"?"navigation:"+n.navigationId:"url:"+s;if(!this.Ho||this.Ho>n.value){this.R.navigationKey!==o&&(this.No(),this.qo=setTimeout(this.No,this.flushToCaptureTimeoutMs)),C(this.R.navigationKey)&&(this.R.navigationKey=o,this.R.url=s),this.R.firstMetricTimestamp=C(this.R.firstMetricTimestamp)?Date.now():this.R.firstMetricTimestamp,n.attribution&&n.attribution.interactionTargetElement&&(n.attribution.interactionTargetElement=void 0);var a=(i=this._instance.sessionManager)==null?void 0:i.checkAndGetSessionAndWindowId(!0),l=I({},n,r?{navigationURL:s}:{},{$current_url:s,timestamp:Date.now()});C(a)||(l.$session_id=a.sessionId,l.$window_id=a.windowId),this.R.metrics.push(l),this.R.metrics.length===this.allowedMetrics.length&&this.No()}else wn.error("Ignoring metric with value >= "+this.Ho,n)}}},this.Uo=()=>{if(!this.vo){var n,i,r,s,o=B.__PosthogExtensions__,a=o?.postHogWebVitalsCallbacksByFlavor,l=a?.[this.zo]||(this.zo==="web-vitals"&&C(a)?o?.postHogWebVitalsCallbacks:void 0);if(C(l)||(n=l.onLCP,i=l.onCLS,r=l.onFCP,s=l.onINP),n&&i&&r&&s){var u={reportSoftNavs:this.useSoftNavs};this.allowedMetrics.indexOf("LCP")>-1&&n(this.jo.bind(this),u),this.allowedMetrics.indexOf("CLS")>-1&&i(this.jo.bind(this),u),this.allowedMetrics.indexOf("FCP")>-1&&r(this.jo.bind(this),u),this.allowedMetrics.indexOf("INP")>-1&&s(this.jo.bind(this),u),this.vo=!0}else wn.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[aa]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,n=he(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return H(n)?((e=this._instance.persistence)==null?void 0:e.props[la])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(he(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=he(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=he(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=he(this.Wo)&&ke(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:du;return t>0&&6e4>=t?du:t}get isEnabled(){var t=me?.protocol;if(t!=="http:"&&t!=="https:")return wn.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=he(this.Wo)?this.Wo.web_vitals:mt(this.Wo)?this.Wo:void 0;return mt(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(wn.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var n=he(e.capturePerformance)&&!!e.capturePerformance.web_vitals,i=he(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[aa]:n}),this._instance.persistence.register({[la]:i})),this.Co=n,this.startIfEnabled()}}}get zo(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}ai(t){var e=B.__PosthogExtensions__,n=this.zo,i=e?.postHogWebVitalsCallbacksByFlavor;i!=null&&i[n]||n==="web-vitals"&&C(i)&&e!=null&&e.postHogWebVitalsCallbacks?t():e==null||e.loadExternalDependency==null||e.loadExternalDependency(this._instance,n,(r=>{r?wn.error("failed to load script",r):t()}))}Bo(t){var e=t||w?.location.href;if(e){var n=this._instance.config.disable_capture_url_hashes?fn(e):e,i=this._instance.config.custom_personal_data_properties,r=this._instance.config.mask_personal_data_properties?[...si,...i||[]]:[];return Xi(n,r,Qi)}wn.error("Could not determine current URL")}}},Jm={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var n;if(w&&this.isEnabled&&(n=B.__PosthogExtensions__)!=null&&n.errorWrappingFunctions){var i=B.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,r=B.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,s=B.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.Vo&&this.Ne.capture_unhandled_errors&&(this.Vo=i(this.captureException.bind(this))),!this.Zo&&this.Ne.capture_unhandled_rejections&&(this.Zo=r(this.captureException.bind(this))),!this.Go&&this.Ne.capture_console_errors&&(this.Go=s(this.captureException.bind(this)))}catch(o){ki.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[ra]),this.Jo=new Kp(I({},(function(n){var i,r,s,o;return n===void 0&&(n={}),{refillRate:(i=(r=n.exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:n.__exceptionRateLimiterRefillRate)!==null&&i!==void 0?i:1,bucketSize:(s=(o=n.exceptionRateLimiterBucketSize)!==null&&o!==void 0?o:n.__exceptionRateLimiterBucketSize)!==null&&s!==void 0?s:10}})(this._instance.config.error_tracking),{refillInterval:1e4,rt:ki})),this.Ne=this.Yo(),this.startIfEnabledOrStop()}Yo(){var t=this._instance.config.capture_exceptions,e={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return he(t)?e=I({},e,t):(C(t)?this.Ko:t)&&(e=I({},e,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),e}get isEnabled(){return this.Ne.capture_console_errors||this.Ne.capture_unhandled_errors||this.Ne.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(ki.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",(i=>{if(i)return ki.error("failed to load script",i);t()}))}Qo(){var t,e,n;(t=this.Vo)==null||t.call(this),this.Vo=void 0,(e=this.Zo)==null||e.call(this),this.Zo=void 0,(n=this.Go)==null||n.call(this),this.Go=void 0}onRemoteConfig(t){if(t.ok){var e=t.config;"autocaptureExceptions"in e&&(this.Ko=!!e.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[ra]:this.Ko}),this.Ne=this.Yo(),this.startIfEnabledOrStop())}}onConfigChange(){this.Ne=this.Yo()}captureException(t){var e,n,i,r=(e=t==null||(n=t.$exception_list)==null||(n=n[0])==null?void 0:n.type)!==null&&e!==void 0?e:"Exception";this.Jo.consumeRateLimit(r)?ki.info("Skipping exception capture because of client rate limiting.",{exception:r}):(i=this._instance.exceptions)==null||i.sendExceptionEvent(t)}},exceptions:class{constructor(t){var e,n;this.Xo=[],this.tl=new dg([new yg,new Ag,new bg,new wg,new kg,new Ig,new Sg,new Cg],(function(i){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;r>o;o++)s[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` +`),d=l;c.length>d;d++){var h=c[d];if(1024>=h.length){var f=Rc.test(h)?h.replace(Rc,"$1"):h;if(!f.match(/\S*Error: /)){for(var p of s){var g=p(f,i);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var v=Array.from(m);return v.reverse(),v.slice(0,50).map((E=>{return I({},E,{filename:E.filename||(S=v,S[S.length-1]||{}).filename,function:E.function||ii});var S}))})(u)}})("web:javascript",gg,_g)),this._instance=t,this.Xo=(e=(n=this._instance.persistence)==null?void 0:n.get_property(sa))!==null&&e!==void 0?e:[],this.el=Xr(this.il()),this.rl=new Fg(this.el)}onConfigChange(){this.el=Xr(this.il()),this.rl.setConfig(this.el)}onRemoteConfig(t){var e,n,i;if(t.ok){var r=t.config;if("errorTracking"in r){var s=(e=(n=r.errorTracking)==null?void 0:n.suppressionRules)!==null&&e!==void 0?e:[],o=(i=r.errorTracking)==null?void 0:i.captureExtensionExceptions;this.Xo=s,this._instance.persistence&&this._instance.persistence.register({[sa]:this.Xo,[oa]:o})}}}get nl(){var t,e=!!this._instance.get_property(oa),n=this._instance.config.error_tracking.captureExtensionExceptions;return(t=n??e)!==null&&t!==void 0&&t}buildProperties(t,e){return this.tl.buildFromUnknown(t,{syntheticException:e?.syntheticException,mechanism:{handled:e?.handled}})}addExceptionStep(t,e){if(this.el.enabled)try{if(!X(t)||t.trim().length===0)return void St.warn("Ignoring exception step because message must be a non-empty string");var n=(function(s){if(!s)return{sanitizedProperties:{},droppedKeys:[]};var o=[];return{sanitizedProperties:Object.keys(s).reduce(((a,l)=>Pg.has(l)?(o.push(l),a):(a[l]=s[l],a)),{}),droppedKeys:o}})(this.sl(e)),i=n.sanitizedProperties,r=n.droppedKeys;r.length>0&&St.warn("Ignoring reserved exception step fields",{droppedKeys:r}),this.rl.add(I({[Jr]:t,[Zr]:new Date().toISOString()},i))}catch(s){St.error("Failed to add exception step. Ignoring breadcrumb.",s)}}sendExceptionEvent(t){try{var e=t.$exception_list;if(this.al(e)){if(this.ol(e))return this.ll("Exception dropped: matched a suppression rule"),void St.info("Skipping exception capture because a suppression rule matched");if(!this.nl&&this.ul(e))return this.ll("Exception dropped: thrown by a browser extension"),void St.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.hl(e))return this.ll("Exception dropped: thrown by the PostHog SDK"),void St.info("Skipping exception capture because it was thrown by the PostHog SDK")}var n=this.el.enabled&&H(t.$exception_steps)?this.dl(t):t,i=typeof(s=globalThis._posthogReleaseId)=="string"&&s.length>0?s:void 0;i&&(n.$release_id=i);try{var r=this._instance.capture("$exception",n,{_noTruncate:!0,_batchKey:"exceptionEvent",Wn:!0});return r&&this.rl.clear(),r}catch(o){return St.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void St.error("Failed to process exception event. Ignoring this exception.",o)}var s}dl(t){try{var e=this.rl.getAttachable();return e.length===0?t:I({},t,{$exception_steps:e})}catch(n){return St.error("Failed to read buffered exception steps. Capturing exception without steps.",n),t}}ll(t){this.el.enabled&&this.rl.add({[Jr]:t,[Zr]:new Date().toISOString()})}sl(t){return he(t)?I({},t):{}}il(){var t,e;return(t=(e=this._instance.config.error_tracking)==null?void 0:e.exception_steps)!==null&&t!==void 0?t:{}}ol(t){if(t.length===0)return!1;try{var e=t.reduce(((n,i)=>{var r=i.type,s=i.value;return X(r)&&r.length>0&&n.$exception_types.push(r),X(s)&&s.length>0&&n.$exception_values.push(s),n}),{$exception_types:[],$exception_values:[]});return this.Xo.some((n=>{var i=n.values.map((r=>{var s=Vf[r.operator],o=e[r.key];if(!s||!o)return!1;var a=U(r.value)?r.value:[r.value];return a.length>0&&s(a,o)}));return n.type==="OR"?i.some(Boolean):i.every(Boolean)}))}catch(n){return St.warn("Failed to evaluate suppression rules. Capturing the exception.",n),!1}}ul(t){return t.flatMap((e=>{var n,i;return(n=(i=e.stacktrace)==null?void 0:i.frames)!==null&&n!==void 0?n:[]})).some((e=>e.filename&&e.filename.startsWith("chrome-extension://")))}hl(t){if(t.length>0){var e,n,i,r,s=(e=(n=t[0].stacktrace)==null?void 0:n.frames)!==null&&e!==void 0?e:[],o=s[s.length-1];return(i=o==null||(r=o.filename)==null?void 0:r.includes("posthog.com/static"))!==null&&i!==void 0&&i}return!1}al(t){return!H(t)&&U(t)}}},Zm=I({productTours:class{get Mr(){return this._instance.persistence}constructor(t){this.vl=null,this.cl=null,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(t.ok){var e=t.config;if("productTours"in e){var n,i;if(this.Mr&&this.Mr.register({[ll]:!!e.productTours}),!Do(this._instance))return!this.vl&&H((n=this.Mr)==null?void 0:n.props[Li])||kr.info("product tours disabled; stopping and clearing cached tours"),(i=this.vl)==null||i.stop(),this.vl=null,void this.clearCache();this.loadIfEnabled()}}}loadIfEnabled(){!this.vl&&Do(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.generateProductTours?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",(i=>{i?kr.error("Could not load product tours script",i):t()}))}fl(){var t;!this.vl&&(t=B.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=B.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(t,e){if(e===void 0&&(e=!1),!U(this.cl)||e){var n=this.Mr;if(n){var i=n.props[Li];if(U(i)&&!e)return this.cl=i,void t(i,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",timestampMode:"query",callback:r=>{if(Do(this._instance)){var s=r.statusCode;if(s!==200||!r.json){var o="Product Tours API could not be loaded, status: "+s;return s===0?r.error||kr.warn(o):kr.error(o),void t([],{isLoaded:!1,error:o})}var a=U(r.json.product_tours)?r.json.product_tours:[];this.cl=a,n&&n.register({[Li]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){H(this.vl)?t([],{isLoaded:!1,error:"Product tours not loaded"}):this.vl.getActiveProductTours(t)}showProductTour(t){var e;(e=this.vl)==null||e.showTourById(t)}previewTour(t){this.vl?this.vl.previewTour(t):this.ai((()=>{var e;this.fl(),(e=this.vl)==null||e.previewTour(t)}))}dismissProductTour(){var t;(t=this.vl)==null||t.dismissTour("user_clicked_skip")}nextStep(){var t;(t=this.vl)==null||t.nextStep()}previousStep(){var t;(t=this.vl)==null||t.previousStep()}clearCache(){var t;this.cl=null,(t=this.Mr)==null||t.unregister(Li)}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)}}},Ps),Xm={siteApps:class{constructor(t){this.pl=0,this._instance=t,this.gl=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}ml(t,e){if(e){var n=this.globalsForEvent(e);this.gl.push(n),this.gl.length>1e3&&(this.gl=this.gl.slice(10))}}get siteAppLoaders(){var t;return(t=B._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,n,i,r,s,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var h=d[0];l[h]={id:u[h],type:h,properties:d[1]}}var f=t.$set_once,p=t.$set;return{event:I({},md(t,Um),{properties:I({},t.properties,p?{$set:I({},(e=(n=t.properties)==null?void 0:n.$set)!==null&&e!==void 0?e:{},p)}:{},f?{$set_once:I({},(i=(r=t.properties)==null?void 0:r.$set_once)!==null&&i!==void 0?i:{},f)}:{}),elements_chain:(s=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&s!==void 0?s:"",distinct_id:(a=t.properties)==null?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}bl(t){var e,n=(e=t.tagName)==null?void 0:e.toLowerCase();return n==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(Et.error("prepare_external_dependency_stylesheet returned null"),null):n==="script"&&this._instance.config.prepare_external_dependency_script?this._instance.config.prepare_external_dependency_script(t)||(Et.error("prepare_external_dependency_script returned null"),null):t}_l(){var t,e,n,i,r,s,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=P?.defaultView,u=l==null||(t=l.Node)==null?void 0:t.prototype;if(!l||!u)return()=>{};if(this.pl++,this.wl)return this.kl();var c=[],d=this,h=new WeakSet,f=(m,v,E)=>{if(m!=null&&m[v]){var S=m[v];m[v]=E(S),c.push((()=>{m[v]=S}))}},p=m=>{if(h.has(m))return m;var v=d.bl(m);return v&&h.add(v),v},g=m=>m.map((v=>typeof v=="string"?v:p(v))).filter((v=>!Ye(v)));return f(u,"appendChild",(m=>function(v){var E=p(v);return E?m.call(this,E):v})),f(u,"insertBefore",(m=>function(v,E){var S=p(v);return S?m.call(this,S,E):v})),f(u,"replaceChild",(m=>function(v,E){var S=p(v);return S?m.call(this,S,E):E})),[(e=l.Element)==null?void 0:e.prototype,(n=l.Document)==null?void 0:n.prototype,(i=l.DocumentFragment)==null?void 0:i.prototype].forEach((m=>{f(m,"append",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),f(m,"prepend",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))}))})),[(r=l.Element)==null?void 0:r.prototype,(s=l.CharacterData)==null?void 0:s.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((m=>{f(m,"before",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),f(m,"after",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),f(m,"replaceWith",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];var b=g(S);return S.length&&!b.length?void 0:v.apply(this,b)}))})),f((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(v,E){var S=p(E);return S?m.call(this,v,S):null})),this.wl=()=>{c.forEach((m=>m())),this.wl=void 0},this.kl()}kl(){var t=!1;return()=>{var e;t||(t=!0,this.pl--,this.pl===0&&((e=this.wl)==null||e.call(this)))}}xl(t,e){e===void 0&&(e=!0);var n=this._l();try{var i=t(n);return e&&n(),i}catch(r){throw n(),r}}setupSiteApp(t){var e=this.apps[t.id],n=()=>{var o;!e.errored&&this.gl.length&&(Et.info("Processing "+this.gl.length+" events for site app with id "+t.id),this.gl.forEach((a=>this.xl((()=>e.processEvent==null?void 0:e.processEvent(a))))),e.processedBuffer=!0),Object.values(this.apps).every((a=>a.processedBuffer||a.errored))&&((o=this.yl)==null||o.call(this))},i=!1,r=o=>{e.errored=!o,e.loaded=!0,Et.info("Site app with id "+t.id+" "+(o?"loaded":"errored")),i&&n()};try{var s=this.xl((o=>t.init({posthog:this._instance,callback(a){o(),r(a)}})),!1).processEvent;s&&(e.processEvent=s),i=!0}catch(o){Et.error(pu+t.id,o),r(!1)}if(i&&e.loaded)try{n()}catch(o){Et.error("Error while processing buffered events PostHog app with config id "+t.id,o),e.errored=!0}}Sl(){var t=this.siteAppLoaders||[];for(var e of t)this.apps[e.id]={id:e.id,loaded:!1,errored:!1,processedBuffer:!1};for(var n of t)this.setupSiteApp(n)}Cl(t){var e=this;if(Object.keys(this.apps).length!==0){var n=this.globalsForEvent(t),i=function(s){try{e.xl((()=>s.processEvent==null?void 0:s.processEvent(n)))}catch(o){Et.error("Error while processing event "+t.event+" for site app "+s.id,o)}};for(var r of Object.values(this.apps))i(r)}}onRemoteConfig(t){var e,n,i,r=this;if((e=this.siteAppLoaders)!=null&&e.length)return this.isEnabled?(this.Sl(),void this._instance.on("eventCaptured",(l=>this.Cl(l)))):void Et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((n=this.yl)==null||n.call(this),t.ok){var s=t.config;if((i=s.siteApps)!=null&&i.length)if(this.isEnabled){var o=function(){var l,u=a.id,c=a.url;B["__$$ph_site_app_"+u]=r._instance,(l=B.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(r._instance,c,(d=>{if(d)return Et.error(pu+u,d)}))};for(var a of s.siteApps)o()}else Et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},Qm={tracingHeaders:class{constructor(t){this.Ml=void 0,this.Tl=void 0,this.El=void 0,this.Uo=()=>{var e,n,i=this.Il();i?(C(this.Ml)&&(this.Ml=(e=B.__PosthogExtensions__)==null||(e=e.tracingHeadersPatchFns)==null?void 0:e._patchXHR(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager)),C(this.Tl)&&(this.Tl=(n=B.__PosthogExtensions__)==null||(n=n.tracingHeadersPatchFns)==null?void 0:n._patchFetch(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager))):this.Qo()},this._instance=t}initialize(){this.startIfEnabledOrStop()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",(i=>{if(i)return Dm.error("failed to load script",i);t()}))}Pl(){var t,e;return(t=(e=this._instance.config.tracing_headers)!==null&&e!==void 0?e:this._instance.config.addTracingHeaders)!==null&&t!==void 0?t:this._instance.config.__add_tracing_headers}Il(){var t=this.Pl();return U(t)?(U(this.El)?this.El.splice(0,this.El.length,...t):this.El=[...t],t.length>0?this.El:void 0):(U(this.El)&&this.El.splice(0),this.El=t||void 0,this.El)}Qo(){var t,e;(t=this.Ml)==null||t.call(this),(e=this.Tl)==null||e.call(this),this.Ml=void 0,this.Tl=void 0}startIfEnabledOrStop(){this.Il()?this.ai(this.Uo):this.Qo()}}},ev=I({surveys:class{get Ne(){return this._instance.config}constructor(t){this.Rl=void 0,this._surveyManager=null,this.Al=!1,this.Fl=[],this.Ll=null,this.Ol=null,this._instance=t,this._surveyEventReceiver=null}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this.Ne.disable_surveys){if(!t.ok)return Q.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(H(e))return Q.warn("Flags not loaded yet. Not loading surveys.");var n=U(e);this.Rl=n?e.length>0:e,Q.info("flags response received, isSurveysEnabled: "+this.Rl),this.loadIfEnabled()}}reset(){try{var t;(t=this._surveyEventReceiver)==null||t.reset(),localStorage.removeItem("lastSeenSurveyDate");for(var e=[],n=0;nlocalStorage.removeItem(r)))}catch{}}loadIfEnabled(){if(!this._surveyManager)if(this.Al)Q.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)Q.info(gu);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())Q.info("Not loading surveys in cookieless mode without consent.");else{var t=B?.__PosthogExtensions__;if(t){if(!C(this.Rl)||this.Ne.advanced_enable_surveys){var e=this.Rl||this.Ne.advanced_enable_surveys;this.Al=!0;try{var n=t.generateSurveys;if(n)return void this.Dl(n,e);var i=t.loadExternalDependency;if(!i)return void this.$l(ul);i(this._instance,"surveys",(r=>{r||!t.generateSurveys?this.$l("Could not load surveys script",r):this.Dl(t.generateSurveys,e)}))}catch(r){throw this.$l("Error initializing surveys",r),r}finally{this.Al=!1}}}else Q.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new zm(this._instance),Q.info("Surveys loaded successfully"),this.Nl({isLoaded:!0})}$l(t,e){Q.error(t,e),this.Nl({isLoaded:!1,error:t})}onSurveysLoaded(t){return this.Fl.push(t),this._surveyManager&&this.Nl({isLoaded:!0}),()=>{this.Fl=this.Fl.filter((e=>e!==t))}}getSurveys(t,e){if(e===void 0&&(e=!1),this.Ne.disable_surveys)return Q.info(gu),t([]);var n,i=this._instance.get_property(ua);if(i&&!e)return t(i,{isLoaded:!0}),void(this.ql()&&this.getSurveys((()=>{}),!0));typeof Promise<"u"&&this.Ll?this.Ll.then((r=>t(r.surveys,r.context))):(typeof Promise<"u"&&(this.Ll=new Promise((r=>{n=r}))),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this.Ne.token),method:"GET",timestampMode:"query",timeout:this.Ne.surveys_request_timeout_ms,callback:r=>{var s;this.Ll=null;var o=r.statusCode;if(o!==200||!r.json){var a="Surveys API could not be loaded, status: "+o;o!==0?Q.error(a):r.error||Q.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(n==null||n({surveys:[],context:l}))}this.Ol=null;var u,c=r.json.surveys||[],d=c.filter((f=>(function(p){return!(!p.start_date||p.end_date)})(f)&&(Kf(f)||(function(p){var g;return!((g=p.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(f))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(s=this._instance.persistence)==null||s.register({[ua]:c,[es]:Date.now()});var h={isLoaded:!0};t(c,h),n?.({surveys:c,context:h})}}))}ql(){return this.jl()&&!this.Ll&&!this.Bl()}jl(){var t=this._instance.get_property(es);return ke(t)&&Date.now()-t>3e5}Bl(){return ke(this.Ol)&&3e5>Date.now()-this.Ol}markSurveyAsSeen(t,e){var n,i={id:t,current_iteration:(n=e?.iteration)!==null&&n!==void 0?n:null};Jf(i);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}}Nl(t){for(var e of this.Fl)try{if(!t.isLoaded)return e([],t);this.getSurveys(e)}catch(n){Q.error("Error in survey callback",n)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!H(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);Q.warn("init was not called")}Hl(t){var e=null;return this.getSurveys((n=>{var i;e=(i=n.find((r=>r.id===t)))!==null&&i!==void 0?i:null})),e}Ul(t){if(H(this._surveyManager))return{eligible:!1,reason:Cr};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyEligibility(e):{eligible:!1,reason:"Survey not found"}}zl(t){if(H(this._surveyManager))return{eligible:!1,reason:Cr};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyRenderability(e):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(t){if(H(this._surveyManager))return Q.warn("init was not called"),{visible:!1,disabledReason:Cr};var e=this.zl(t);return{visible:e.eligible,disabledReason:e.reason}}canRenderSurveyAsync(t,e){return H(this._surveyManager)?(Q.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Cr})):new Promise((n=>{this.getSurveys((i=>{var r,s=(r=i.find((a=>a.id===t)))!==null&&r!==void 0?r:null;if(s){var o=this.zl(s);n({visible:o.eligible,disabledReason:o.reason})}else n({visible:!1,disabledReason:"Survey not found"})}),e)}))}renderSurvey(t,e,n){var i;if(H(this._surveyManager))Q.warn("init was not called");else{var r=typeof t=="string"?this.Hl(t):t;if(r!=null&&r.id)if(km.includes(r.type)){var s=P?.querySelector(e);if(s)return(i=r.appearance)!=null&&i.surveyPopupDelaySeconds?(Q.info("Rendering survey "+r.id+" with delay of "+r.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;Q.info("Rendering survey "+r.id+" with delay of "+((o=r.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(a=this._surveyManager)==null||a.renderSurvey(r,s,n),Q.info("Survey "+r.id+" rendered")}),1e3*r.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(r,s,n);Q.warn("Survey element not found")}else Q.warn("Surveys of type "+r.type+" cannot be rendered in the app");else Q.warn("Survey not found")}}displaySurvey(t,e){var n;if(H(this._surveyManager))Q.warn("init was not called");else{var i=this.Hl(t);if(i){var r=i;if((n=i.appearance)!=null&&n.surveyPopupDelaySeconds&&e.ignoreDelay&&(r=I({},i,{appearance:I({},i.appearance,{surveyPopupDelaySeconds:0})})),e.displayType!==wa.Popover&&e.initialResponses&&Q.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),e.ignoreConditions===!1){var s=this.Ul(i);if(!s.eligible)return void Q.warn("Survey is not eligible to be displayed: ",s.reason)}e.displayType!==wa.Inline?this._surveyManager.handlePopoverSurvey(r,e):this.renderSurvey(r,e.selector,e.properties)}else Q.warn("Survey not found")}}cancelPendingSurvey(t){H(this._surveyManager)?Q.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},Ps),tv={toolbar:class{constructor(t){this.instance=t}Wl(t){B.ph_toolbar_state=t}Vl(){var t;return(t=B.ph_toolbar_state)!==null&&t!==void 0?t:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(t,e,n){if(t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),va(this.instance.config)||!w||!P)return!1;t=t??w.location,n=n??w.history;try{if(!e){try{w.localStorage.setItem("test","test"),w.localStorage.removeItem("test")}catch{return!1}e=w?.localStorage}var i,r=qm||ls(t.hash,"__posthog")||ls(t.hash,"state"),s=r?$c((()=>JSON.parse(atob(decodeURIComponent(r)))))||$c((()=>JSON.parse(decodeURIComponent(r)))):null;return s&&s.action==="ph_authorize"?((i=s).source="url",i&&Object.keys(i).length>0&&(s.desiredHash?t.hash=s.desiredHash:n?n.replaceState(n.state,"",t.pathname+t.search):t.hash="")):((i=JSON.parse(e.getItem(mu)||"{}")).source="localstorage",delete i.userIntent),!(!i.token||this.instance.config.token!==i.token||(this.loadToolbar(i),0))}catch{return!1}}Zl(t){var e=B.ph_load_toolbar||B.ph_load_editor;!H(e)&&je(e)?e(t,this.instance):vu.warn("No toolbar load function found")}loadToolbar(t){var e=!(P==null||!P.getElementById(df));if(!w||e)return!1;var n=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,i=I({token:this.instance.config.token},t,{apiURL:this.instance.requestRouter.endpointFor("ui")},n?{instrument:!1}:{});if(w.localStorage.setItem(mu,JSON.stringify(I({},i,{source:void 0}))),this.Vl()===2)this.Zl(i);else if(this.Vl()===0){var r;this.Wl(1),(r=B.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"toolbar",(s=>{if(s)return vu.error("[Toolbar] Failed to load",s),void this.Wl(0);this.Wl(2),this.Zl(i)})),ve(w,"turbolinks:load",(()=>{this.Wl(0),this.loadToolbar(i)}))}return!0}Gl(t){return this.loadToolbar(t)}maybeLoadEditor(t,e,n){return t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),this.maybeLoadToolbar(t,e,n)}}},nv=I({experiments:Me},Ps),iv={conversations:class{constructor(t){this.Ql=void 0,this._conversationsManager=null,this.Kl=!1,this.Jl=null,this.Yl=!1,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this._instance.config.disable_conversations&&(this.Xl=t.ok,t.ok)){var e=t.config.conversations;H(e)||(mt(e)?this.Ql=e:(this.Ql=e.enabled,this.Jl=e),this.loadIfEnabled())}}reset(){var t;(t=this._conversationsManager)==null||t.reset(),this._conversationsManager=null,this.Ql=void 0,this.Jl=null,this.Xl=void 0,this.Yl=!1}loadIfEnabled(){if(!(this._conversationsManager||this.Kl||this._instance.config.disable_conversations||va(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=B?.__PosthogExtensions__;if(t&&!C(this.Ql)&&this.Ql)if(this.Jl&&this.Jl.token){this.Kl=!0;try{var e=t.initConversations;if(e)return this.tu(e),void(this.Kl=!1);var n=t.loadExternalDependency;if(!n)return void this.eu(ul);n(this._instance,"conversations",(i=>{i||!t.initConversations?this.eu("Could not load conversations script",i):this.tu(t.initConversations),this.Kl=!1}))}catch(i){this.eu("Error initializing conversations",i),this.Kl=!1}}else ot.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,ot.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else ot.error("Cannot complete initialization: remote config is null")}eu(t,e){ot.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():ot.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!Ye(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":va(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.Xl===!1?"remote_config_failed":C(this.Ql)?this.Xl?"disabled_in_project":"remote_config_pending":this.Ql?H(this.Jl)||!this.Jl.token?"missing_token":B!=null&&B.__PosthogExtensions__?this.Kl?"initializing":this.Yl?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.isVisible())!==null&&t!==void 0&&t}sendMessage(t,e,n){var i=this;return se((function*(){return i._conversationsManager?i._conversationsManager.sendMessage(t,e,n):(ot.warn(En),null)}))()}getMessages(t,e){var n=this;return se((function*(){return n._conversationsManager?n._conversationsManager.getMessages(t,e):(ot.warn(En),null)}))()}markAsRead(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(ot.warn(En),null)}))()}getTickets(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(ot.warn(En),null)}))()}requestRestoreLink(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(ot.warn(En),null)}))()}restoreFromToken(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(ot.warn(En),null)}))()}restoreFromUrlToken(){var t=this;return se((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(ot.warn(En),null)}))()}getCurrentTicketId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getCurrentTicketId())!==null&&t!==void 0?t:null}getWidgetSessionId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getWidgetSessionId())!==null&&t!==void 0?t:null}Xn(){var t;(t=this._conversationsManager)==null||t.setIdentity()}ts(){var t;(t=this._conversationsManager)==null||t.clearIdentity()}}},rv={logs:class{constructor(t){var e,n=this;this.iu=!1,this.ru=!1,this.rt=pe("[logs]"),this.nu=I({},this.rt,{error(){for(var i=arguments.length,r=new Array(i),s=0;i>s;s++)r[s]=arguments[s];r.some(Iu)||n.rt.error(...r)}}),this.tr=[],this.su=[],this.Sa=0,this.au=()=>{var i,r;this.Sa=0,(i=this.ou)==null||i.onReconnect(),(r=this.lu)==null||r.onReconnect()},this._instance=t,this._instance&&(e=this._instance.config.logs)!=null&&e.captureConsoleLogs&&(this.iu=!0),w&&ve(w,"online",this.au)}uu(t,e,n,i){var r,s=(function(o,a){var l,u,c,d,h,f,p,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,v=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,E=C(v)?Math.max(m,2048):Math.max(m,v),S=o?.resourceAttributes;return{serviceName:(d=(h=S?.["service.name"])!==null&&h!==void 0?h:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(f=S?.["service.version"])!==null&&f!==void 0?f:o?.serviceVersion,environment:(p=S?.["deployment.environment"])!==null&&p!==void 0?p:o?.environment,resourceAttributes:S,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:E,maxBatchRecordsPerPost:100,rateCapWindowMs:g,maxLogsPerInterval:v,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}})((r=this._instance)==null||(r=r.config)==null?void 0:r.logs,n);return[new lg(this.hu(t,e),s,this.nu,(()=>this.du()),(o=>o()),void 0,i),s]}vu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.ou||this.cu!==e){var n;(n=this.ou)==null||n.reset(),this.cu=e;var i=this.uu((()=>this.tr),(r=>{this.tr=r}));this.ou=i[0],this.fu=i[1]}return this.ou}pu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.lu||this.gu!==e){var n;(n=this.lu)==null||n.reset(),this.gu=e;var i=this.uu((()=>this.su),(r=>{this.su=r}),{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},xu);this.lu=i[0],this.mu=i[1]}return this.lu}initialize(){this.loadIfEnabled()}onRemoteConfig(t){var e;if(t.ok){var n=(e=t.config.logs)==null?void 0:e.captureConsoleLogs;!H(n)&&n&&(this.iu=!0,this.loadIfEnabled())}}reset(){var t,e;this.tr=[],(t=this.ou)==null||t.reset(),this.su=[],(e=this.lu)==null||e.reset(),this.Sa=0}captureLog(t){this.vu().captureLog(t)}he(t){this.pu().captureLog(t)}get logger(){return this.yu||(this.yu={trace:(t,e)=>this.captureLog({body:t,level:"trace",attributes:e}),debug:(t,e)=>this.captureLog({body:t,level:"debug",attributes:e}),info:(t,e)=>this.captureLog({body:t,level:"info",attributes:e}),warn:(t,e)=>this.captureLog({body:t,level:"warn",attributes:e}),error:(t,e)=>this.captureLog({body:t,level:"error",attributes:e}),fatal:(t,e)=>this.captureLog({body:t,level:"fatal",attributes:e})}),this.yu}flushLogs(t){t?this.bu(t):(this.ou&&this.ou.flush().catch((e=>this._u(e))),this.lu&&this.lu.flush().catch((e=>this._u(e))))}_u(t){Iu(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=B?.__PosthogExtensions__;if(t){var e=t.loadExternalDependency;e?e(this._instance,"logs",(n=>{var i;n||(i=t.logs)==null||!i.initializeLogs?this.rt.error("Could not load logs script",n):(t.logs.initializeLogs(this._instance),this.ru=!0)})):this.rt.error(ul)}else this.rt.error("PostHog Extensions not found.")}}hu(t,e){var n=this._instance;return{get isDisabled(){return!1},get optedOut(){return!n.is_capturing()},getPersistedProperty:i=>i===Ut.LogsQueue?t():void 0,setPersistedProperty(i,r){var s;i===Ut.LogsQueue&&e((s=r)!==null&&s!==void 0?s:[])},Ot:i=>this.Ot(i),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Ot(t){return new Promise((e=>{if(Sf(this.Sa,3))e({kind:"fatal",error:Uo(void 0,"logs endpoint is unreachable, dropping batch")});else{var n=!1,i=s=>{n||(n=!0,clearTimeout(r),e(s))},r=setTimeout((()=>{this.rt.warn("Logs request timed out before receiving a response"),i({kind:"retry-later",error:Uo(void 0,"logs request timed out")})}),9e4);this._instance._send_request({method:"POST",url:this.wu(),data:t,compression:"best-available",batchKey:"logs",fireCallbackOnDrop:!0,callback:s=>{var o=s.statusCode;if(this.ku(o),o>=200&&300>o)i({kind:"ok"});else if(o===413)i({kind:"too-large"});else if(o!==0&&o!==429&&500>o)i({kind:"fatal",error:new Error("logs request failed with status "+o)});else{var a;o===0?(s.error||this.rt.warn("Logs request failed before receiving an HTTP response"),i({kind:"retry-later",error:Uo(s.error,"logs request failed before receiving an HTTP response")})):i({kind:"retry-later",error:(a=s.error)!==null&&a!==void 0?a:new Error("logs request failed with status "+o)})}}})}}))}ku(t){(t!==0||this._instance.__loaded)&&(this.Sa=xf(t,this.Sa,3,(()=>this.rt.warn("Log requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped sending logs; will try again when connectivity changes."))))}bu(t){this.tr.length>0&&this.xu(t,this.tr,this.fu,ne.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,xu,(e=>{this.su=e}))}xu(t,e,n,i,r){if(e.length!==0){var s=e.map((a=>a.record));r([]);var o=Gd(s,Vd(n,ne.LIB_NAME,ne.LIB_VERSION),i,ne.LIB_VERSION);this._instance._send_request({method:"POST",url:this.wu(),data:o,compression:"best-available",batchKey:"logs",transport:t})}}wu(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}du(){var t,e={};if(e.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var n=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.windowId,r=n.sessionStartTimestamp,s=n.lastActivityTimestamp;e.sessionId=n.sessionId,e.windowId=i,H(r)||(e.sessionStartTimestamp=r),H(s)||(e.lastActivityTimestamp=s)}if(B!=null&&(t=B.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?fn(B.location.href):B.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},sv={metrics:class{constructor(t){this.rt=pe("[metrics]"),this._instance=t}initialize(){}vu(){var t,e,n=(t=this._instance)==null||(t=t.config)==null?void 0:t.metrics;return this.ou&&this.cu===n||((e=this.ou)==null||e.reset(),this.cu=n,this.ou=new cg(this.hu(),(function(i){var r,s,o,a,l,u=i?.resourceAttributes;return{serviceName:(r=u?.["service.name"])!==null&&r!==void 0?r:i?.serviceName,serviceVersion:(s=u?.["service.version"])!==null&&s!==void 0?s:i?.serviceVersion,environment:(o=u?.["deployment.environment"])!==null&&o!==void 0?o:i?.environment,resourceAttributes:u,beforeSend:i?.beforeSend,flushIntervalMs:(a=i?.flushIntervalMs)!==null&&a!==void 0?a:1e4,maxSeriesPerFlush:(l=i?.maxSeriesPerFlush)!==null&&l!==void 0?l:1e3}})(n),this.rt)),this.ou}count(t,e,n){e===void 0&&(e=1),this.vu().count(t,e,n)}gauge(t,e,n){this.vu().gauge(t,e,n)}histogram(t,e,n){this.vu().histogram(t,e,n)}flush(t){if(!this.ou)return Promise.resolve();if(t){var e=this.ou.drainWindow();return e&&this.Jt(e,t),Promise.resolve()}return this.ou.flush().catch((n=>this.rt.error("PostHog metrics flush failed:",n)))}reset(){var t;(t=this.ou)==null||t.reset()}hu(){var t=this._instance,e=this;return{get isDisabled(){return!1},get optedOut(){return!t.is_capturing()},Jt:n=>e.Jt(n),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Jt(t,e){return new Promise((n=>{var i=!1,r=o=>{i||(i=!0,clearTimeout(s),n(o))},s=setTimeout((()=>r({kind:"retry-later",error:new Error("metrics request timed out")})),9e4);this._instance._send_request(I({method:"POST",url:this.Su(),data:t,compression:"best-available",batchKey:"metrics"},e&&{transport:e},{fireCallbackOnDrop:!0,callback(o){var a=o.statusCode;if(a>=200&&300>a)r({kind:"ok"});else if(a===413)r({kind:"too-large"});else if(a!==0&&a!==429&&500>a)r({kind:"fatal",error:new Error("metrics request failed with status "+a)});else{var l;r({kind:"retry-later",error:(l=o.error)!==null&&l!==void 0?l:new Error("metrics request failed with status "+a)})}}}))}))}Su(){return this._instance.requestRouter.endpointFor("api","/i/v1/metrics")+"?token="+encodeURIComponent(this._instance.config.token)}}},ov=I({},Ps,Km,Ym,Jm,Zm,Xm,ev,Qm,tv,nv,iv,rv,sv);Ze.__defaultExtensionClasses=I({},ov);(function(){ne.SDK_DIST_CHANNEL="npm";var t=zi[Kn]=new Ze;return(function(){function e(){e.done||(e.done=!0,Xf=!1,ie(zi,(function(n){n._dom_loaded()})))}P!=null&&P.addEventListener?P.readyState==="complete"?e():ve(P,"DOMContentLoaded",e,{capture:!1}):w&&A.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const av=["a[href]","button:not([disabled])","input:not([disabled]):not([type='hidden'])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(",");let pt=null,Aa=null,eh="";const Pa=new Map;function th(t){return[...t.querySelectorAll(av)].filter(e=>!e.hidden&&e.getAttribute("aria-hidden")!=="true"&&e.getClientRects().length>0)}function lv(t){for(const e of document.body.children)e===t||e.tagName==="SCRIPT"||(Pa.set(e,{inert:e.inert,ariaHidden:e.getAttribute("aria-hidden")}),e.inert=!0,e.setAttribute("aria-hidden","true"))}function cv(){for(const[t,e]of Pa)t.inert=e.inert,e.ariaHidden===null?t.removeAttribute("aria-hidden"):t.setAttribute("aria-hidden",e.ariaHidden);Pa.clear()}function nh(t){return t?.dataset.modalDismissible!=="false"&&t?.getAttribute("aria-busy")!=="true"}function We(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n)return!1;pt&&pt!==n&&ze(pt,{restoreFocus:!1,force:!0}),Aa=e.trigger||document.activeElement,pt=n,eh=document.body.style.overflow,lv(n),document.body.style.overflow="hidden",n.classList.add("open"),n.setAttribute("aria-hidden","false");const i=n.querySelector(".modal-content");i&&(i.style.transform="scale(1) translateY(0)");const r=()=>{if(pt!==n)return;((e.initialFocus?n.querySelector(e.initialFocus):n.querySelector("[data-modal-initial-focus]"))||th(n)[0]||n.querySelector(".modal-content")||n).focus({preventScroll:!0})};return requestAnimationFrame(r),setTimeout(r,260),!0}function ze(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n||!e.force&&!nh(n))return!1;n.classList.remove("open"),n.setAttribute("aria-hidden","true"),cv(),document.body.style.overflow=eh,pt=null;const i=Aa;return Aa=null,e.restoreFocus!==!1&&i?.isConnected&&i.focus({preventScroll:!0}),!0}function ku(t,e,n="Operation in progress"){const i=typeof t=="string"?document.getElementById(t):t;i&&(i.dataset.modalDismissible=e?"false":"true",i.setAttribute("aria-busy",String(!!e)),e?i.setAttribute("aria-label",n):i.removeAttribute("aria-label"))}function uv(t){if(!nh(t))return;const e=t.dataset.modalCloseHandler;e&&typeof window[e]=="function"?window[e]():ze(t)}document.addEventListener("keydown",t=>{if(!pt)return;if(t.key==="Escape"){t.preventDefault(),t.stopImmediatePropagation(),uv(pt);return}if(t.key!=="Tab"){t.stopPropagation();return}const e=th(pt);if(!e.length){t.preventDefault(),(pt.querySelector(".modal-content")||pt).focus();return}const n=e[0],i=e[e.length-1];t.shiftKey&&document.activeElement===n?(t.preventDefault(),i.focus()):!t.shiftKey&&document.activeElement===i&&(t.preventDefault(),n.focus())},!0);function dv(){document.querySelectorAll(".modal-overlay").forEach(t=>{t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-hidden",t.classList.contains("open")?"false":"true");const e=t.querySelector(".modal-content");e&&!e.hasAttribute("tabindex")&&(e.tabIndex=-1);const n=t.querySelector("h1, h2, h3");n&&(n.id||(n.id=`${t.id}-title`),t.setAttribute("aria-labelledby",n.id)),t.querySelectorAll(".modal-close").forEach(i=>{i.getAttribute("aria-label")||i.setAttribute("aria-label","Close dialog")})})}const _l=Object.freeze({free:"Free",professional:"Pro",power:"Power"}),fv=Object.freeze({free:2,professional:50,power:2e3}),hv="(contact us)",pv=Object.freeze({free:Object.freeze(["2 generations/month","Gemini model only","Code Review"]),professional:Object.freeze(["50 generations/month","All models","Code Regeneration","Code Review"]),power:Object.freeze(["2000 generations/month","All models","Code Regeneration","Bring your own key (BYOK)","Code Review","All models + early access",`API & MCP access ${hv}`])}),ih="CodeFile",rh="GeneratedCode",gv={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function ln(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Fa(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function mv(t={},e=0){const n=Fa(t.artifactType||t.type||ih),i=Fa(t.artifactName||t.name||t.fileName||`${rh}-${e+1}`);return`${n||"artifact"}-${i||e+1}`}function sh(t={},e=0){const n=ln(t),i=n.artifactType||n.type||ih,r=n.artifactName||n.name||rh;let s=n.fileName||r;return s.endsWith(".dart")||(s+=".dart"),{id:Fa(n.id)||mv({...n,artifactType:i,artifactName:r,fileName:s},e),artifactType:i,artifactName:r,fileName:s,deployPath:n.deployPath||"",description:n.description||"",code:n.code||n.content||"",dependencies:oh(n.dependencies),imports:Array.isArray(n.imports)?n.imports:[],publicApi:Array.isArray(n.publicApi)?n.publicApi:[],relationships:ah(n.relationships),deployStatus:n.deployStatus||"pending",review:n.review||null,metadata:ln(n.metadata),codeType:n.codeType||gv[i]||"O"}}function oh(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const n=ln(e),i=n.name||n.package;return i?{name:i,version:n.version||null,versionRequired:!!(n.versionRequired||n.required),inferred:!!n.inferred,...n.reason?{reason:n.reason}:{}}:null}).filter(Boolean):Object.entries(ln(t)).map(([e,n])=>({name:e,version:n||null,inferred:!1})):[]}function ah(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const n=ln(e);return!n.from&&!n.to?null:{from:n.from||null,to:n.to||null,type:n.type||"uses",description:n.description||""}}).filter(Boolean):[]}function Ra(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;try{return JSON.parse(e)}catch{const n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(!n)return null;try{return JSON.parse(n[1].trim())}catch{return null}}}function er(t,e={}){const n=[],i=typeof t=="string"?Ra(t):t,s=ln(i||{});!i&&typeof t=="string"&&n.push("Structured bundle parse failed; using legacy single-artifact fallback.");const o=Array.isArray(s.artifacts)?s.artifacts:[{artifactType:s.artifactType||e.artifactType,artifactName:s.artifactName||e.artifactName,fileName:s.fileName||e.fileName,description:s.description,code:s.code||e.code||(typeof t=="string"?t:""),dependencies:s.dependencies||e.dependencies,relationships:s.relationships||e.relationships}];o.forEach((d,h)=>{!d?.artifactType&&!d?.type&&n.push(`Artifact ${h+1} has no artifactType; it will deploy as a standalone code file under lib/custom_code/ root.`)});const a=o.map((d,h)=>sh(d,h)),l=new Map(o.map((d,h)=>[ln(d).id,a[h]?.id]).filter(([d,h])=>d&&h)),u=d=>l.get(d)||d,c=ah(s.relationships||e.relationships).map(d=>({...d,from:d.from?u(d.from):d.from,to:d.to?u(d.to):d.to}));return{schemaVersion:s.schemaVersion||e.schemaVersion||null,id:s.id||e.id||"bundle-current",title:s.title||s.name||e.title||"Generated artifact bundle",description:s.description||e.description||"",artifacts:a,dependencies:oh(s.dependencies||e.dependencies),relationships:c,deployOrder:Array.isArray(s.deployOrder)?s.deployOrder.map(u):a.map(d=>d.id),warnings:[...n,...Array.isArray(s.warnings)?s.warnings:[]],metadata:ln(s.metadata)}}function ai(t){return er(t).artifacts[0]||sh()}function Zt(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function li(t){return JSON.stringify(t,null,2)}function vv(t){return li({task:"architect",userRequest:String(t??"")})}function _v(t){const e=Zt(t);return e&&typeof e=="object"&&typeof e.task=="string"?li(e):li({task:"generate_bundle",bundleSpec:e})}function yv(t){return li({task:"review_bundle",generatedBundle:Zt(t),outputRequirements:{bundleReview:["status","score","summary","manualActions","findings"],scoreRange:[0,100],eachArtifact:["id","review.status","review.findings"],manualActions:{definition:"Setup the developer must perform by hand in the FlutterFlow editor that FlutterFlow will NOT do for them.",exclude:["creating the Custom Action, Widget or Code File itself - deploying the code creates it","declaring parameters or return values FlutterFlow derives from the function signature","anything that resolves as a side effect of using the action or widget in the editor","generic advice such as testing, reviewing or rebuilding the app"],preferEmpty:"Return an empty array when nothing qualifies - an empty list is the expected result for most bundles."}}})}function yl(t,e=null){const n={stage:t};return e!=null&&(n.bundle=Zt(e)),n}function wv({bundleSpec:t,artifactBundle:e,bundleReview:n,artifactId:i,userFeedback:r}){return li({task:"regenerate_artifact",artifactId:i,bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(r)})}function lh({bundleSpec:t,artifactBundle:e,bundleReview:n,userFeedback:i}){return li({task:"regenerate_bundle",bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(i??"")})}const Cu={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"},bv=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function tt(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Ev(t){return tt(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||tt(t.filterSummary)||tt(t.filterResults):!1}function ch(t,e=0){if(!tt(t)||e>3)return null;if(Ev(t))return t;for(const n of bv){const i=t[n];if(tt(i)){const r=ch(i,e+1);if(r)return r}}return null}function hs(t){return Array.isArray(t)?t.some(hs):tt(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(hs):!1}function Ta(t){return Array.isArray(t)?t.some(Ta):tt(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(Ta):!1}function uh(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function Sv(t,e){if(tt(t))for(const[n,i]of Object.entries(t)){if(!tt(i))continue;const r=tt(i.categories)?i.categories:{},s=Object.entries(r).filter(([,o])=>tt(o)&&o.matched===!0).map(([o])=>o);s.length>0?s.forEach(o=>e.add(o)):i.matched===!0&&e.add(uh(n))}}function xv(t,e){if(!t)return;const n=Array.isArray(t)?t.flatMap(i=>tt(i)?Object.entries(i):[]):Object.entries(t);for(const[i,r]of n){if(!hs(r))continue;const s=uh(i),o=r?.raiFilterResult?.raiFilterTypeResults||(s==="rai"?r?.raiFilterTypeResults:null),a=tt(o)?Object.entries(o).filter(([,l])=>hs(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(s)}}function Iv(t){return Cu[t]?Cu[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function Au(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 kv(t){const e=ch(t);if(!e)return null;const n=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);Sv(e.filterSummary,n),xv(e.filterResults,n);const i=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||n.size>0,r=e.invocationResult||null,s=Ta(e.filterSummary||e.filterResults);return!i&&!s&&!["PARTIAL","FAILURE"].includes(r)?null:{kind:i?"blocked":"unavailable",invocationResult:r,matchedFilters:[...n]}}function Cv(t,e){const n=kv(t);if(!n)return null;const i=[...new Set(n.matchedFilters.map(Iv))],r=n.kind==="blocked",s=new Error(r?`Safety screening blocked this pipeline step for ${Au(i)}.`:"Safety screening could not be completed. Please try again.");return s.name="ModelArmorError",s.code=r?"MODEL_ARMOR_BLOCKED":"MODEL_ARMOR_UNAVAILABLE",s.isModelArmor=!0,s.pipelineStep=e,s.userTitle=r?"Request blocked for safety":"Safety check unavailable",s.userMessage=r?`The safety check detected ${Au(i)}. Edit your request to remove or rephrase the flagged content, then run the pipeline again.`:"The safety service did not finish all of its checks. Please wait a moment and run the pipeline again.",s.retryExplanation=r?"Trying another model would not change this safety decision.":"A fallback model was not attempted because safety screening must complete first.",s.matchedFilters=n.matchedFilters,s}function Av(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function Pu(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,n=[];for(const i of Av(t).split(` +`)){if(!/^[A-Za-z_$]/.test(i)||e.test(i))continue;const r=i.match(/^[\w$<>,?\s[\]]+?\s([a-zA-Z_$][\w$]*)\s*\(/);r&&n.push(r[1])}return n}function wl(t,e){const n=t.replace(/\.dart$/,"");if(e==="W")return n.replace(/(^|_)(\w)/g,(i,r,s)=>s.toUpperCase());if(e==="A"){const i=n.replace(/(^|_)(\w)/g,(r,s,o)=>o.toUpperCase());return i.charAt(0).toLowerCase()+i.slice(1)}return e==="F"?"CustomFunctions":e==="C"?t.endsWith(".dart")?t:`${t}.dart`:n}async function Fu(t){const e=new TextEncoder().encode(String(t||"")),n=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n),i=>i.toString(16).padStart(2,"0")).join("")}async function Pv(t,e=new Map){const n={},i=new Set;for(const[o,a]of t.entries()){if(a.type==="D"||a.type==="O")continue;const l=wl(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await Fu(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await Fu(c)),n[o]=u,a.type==="F"){const d=Pu(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(f=>i.add(f))}}const r=new Set(Pu(e.get("lib/flutter_flow/custom_functions.dart")||"")),s={functions_to_rename:[],functions_to_delete:[],functions_to_add:Array.from(i).filter(o=>!r.has(o))};return{fileMapContents:JSON.stringify(n),functionsMapContents:JSON.stringify(s)}}const Fv=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),Ru={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},Rv=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),Tv=["Struct","Record"],$v=[{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=>Ho(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=>Ho(t).some(e=>{const n=/^\s*final\s+(?:double|int|String|bool|Color|num)\s+(\w+)\s*;/gm;let i;for(;(i=n.exec(e))!==null;){const r=i[1];if(!(new RegExp(`this\\.${r}\\s*=(?!=)`).test(e)||new RegExp(`[:,]\\s*${r}\\s*=(?!=)`).test(e)))return!0}return!1}),pos:`class W extends StatefulWidget { const W({required this.value}); final double value; }`,neg:`class _P { @@ -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=>jo(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=>Ho(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,52 +25,52 @@ class _S extends State { @override Widget build(BuildContext c) => const Size @override _S createState() => _S(); } class _S extends State { @override Widget build(BuildContext c) => Padding(padding: const EdgeInsets.all(8), child: const SizedBox()); }`}];function xt(t,e,n){return{artifactId:t.id,artifactName:t.artifactName,artifactType:t.artifactType,severity:e,message:n}}function tr(t){let e="",n=0;for(;n"&&(n--,n===0))return{inner:t.slice(e+1,i),end:i+1};return null}function Mv(t,e){const n=new RegExp(`class\\s+${e}\\b[^{]*\\{`).exec(t);if(!n)return null;let i=0;for(let r=n.index+n[0].length-1;rLv(t).usable);function Ov(t=""){const e=tr(t);return Nv.filter(n=>n.detect(e)).map(({id:n,severity:i,message:r})=>({id:n,severity:i,message:r}))}function Bv(t){const e=[],n=t.matchAll(/\bFuture\b/g);for(const i of n){let r=i.index+6,s=null;const o=r;for(;ro;if(t[r]==="<"){const u=$v(t,r);if(!u||(s=u.inner.replace(/\s+/g," ").trim(),r=u.end,!/\s/.test(t[r]||"")))continue;for(;rFu(o.functionName)===i);if(r)return r;const s=o=>!o.functionName.startsWith("_");return n.find(s)||n[0]}function As(t=""){return Array.from(tr(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function Dv(t="",e=""){return yl(t,e)?.returnType||null}function Ru(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 jv(t,e){const n=As(e);if(n.length===0)return null;const r=String(t||"").split("/").pop().replace(/\.dart$/,"");if(n.some(l=>Ru(l)===r)||n.length>1)return null;const[o]=n,a=`${Ru(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 wl(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function Uv(t,e,n=""){const i=yl(e,n)?.functionName;if(!i)return null;const r=String(t||"").split("/").pop(),s=_l(r,"A");if(s===i)return null;const o=`${wl(i)}.dart`;return`File name "${r}" does not match Action "${i}". FlutterFlow derives the action from the file name, so it looks for "${s}" and reports Action "${s}" declaration not found. Rename the file to "${o}" - FlutterFlow puts an underscore before every capital - or rename the function to "${s}".`}function Hv(t="",e=""){return yl(t,e)!==null}function Wv(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(i=>Fv.has(i)?!1:!Rv.some(s=>i.endsWith(s))||e.has(i))}function zv(t,{functionName:e="",declaredTypes:n=new Set}={}){const i=Dv(t,e),r=Wv(i,n);if(r.length===0)return null;const[s]=r;let o;return n.has(s)?o=`uses Code File type "${s}", which FlutterFlow cannot process as an Action Return Value`:i===s?o="is not a FlutterFlow Action Return Value":o=`uses type "${s}", which is not a FlutterFlow Action Return Value`,`CustomAction return type "${i}" ${o}. Return JSON (Future) or an existing FlutterFlow Data Type (*Struct) instead.`}function qv(t,e={}){const n=[],i=t.fileName||"",r=t.code||"";if(Pv.has(t.artifactType)||n.push(xt(t,"error",`Unsupported artifact type "${t.artifactType}".`)),i.endsWith(".dart")||n.push(xt(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!r.trim())return n.push(xt(t,"warning","Generated artifact has no Dart code yet.")),n;if(t.artifactType==="CustomWidget"){/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)||n.push(xt(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const s of Ov(r))n.push(xt(t,s.severity,s.message))}if(t.artifactType==="CustomAction"&&!Hv(r,t.artifactName)&&n.push(xt(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const s=e.declaredTypes||new Set(As(r)),o=zv(r,{functionName:t.artifactName,declaredTypes:s});o&&n.push(xt(t,"error",o));const a=Uv(i,r,t.artifactName);a&&n.push(xt(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)&&n.push(xt(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const s=jv(i,r);s&&n.push(xt(t,"info",s))}return n}function Vv(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],n=new Set(e.flatMap(s=>As(s.code||""))),i=e.flatMap(s=>qv(s,{declaredTypes:n})),r=e.map(s=>({artifactId:s.id,fileName:s.fileName,pathHint:Pu[s.artifactType]||Pu.CodeFile}));return{valid:i.every(s=>s.severity!=="error"),findings:i,deployHints:r}}const Tu="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function $u(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function Gv(t=""){const e=t.indexOf(Tu);return e===-1?t:t.slice(e+Tu.length).replace(/^\s*\n/,"")}const Kv=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function Yv(t="",e=""){const n=Gv(t),i=new Set((e.match(/^\s*import .*$/gm)||[]).map($u).filter(Boolean)),r=n.split(` -`).filter(s=>{const o=$u(s);return o===null||!i.has(o)?!0:!Kv.test(s)}).join(` -`).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+r}const Jv=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations"]);function ch(t){let e="",n=0;for(;n{const i=n.name||n.package;if(!i||i==="flutter")return e;const r=n.versionRequired||n.required;return e[i]=r&&n.version||"",e},{})}function t_(t){const e=new Map,n=new Map,i=[];for(const r of t)e.has(r.fileName)?i.push(`Duplicate deploy file name "${r.fileName}" for artifacts "${e.get(r.fileName)}" and "${r.artifactId}".`):e.set(r.fileName,r.artifactId),n.has(r.path)?i.push(`Duplicate deploy path "${r.path}" for artifacts "${n.get(r.path)}" and "${r.artifactId}".`):n.set(r.path,r.artifactId);return i}function n_(t,e={}){const n=Array.isArray(t?.artifacts)?t.artifacts:[],r=(e.selectedArtifactIds||t?.deployOrder||n.map(h=>h.id)).map(h=>n.find(p=>p.id===h)).filter(Boolean),s=[...t?.warnings||[]];let o=[];r.forEach(h=>{const p=e_(h),g=h.fixedCode||h.code||"",m=h.codeType||Xv[h.artifactType]||Xe.OTHER;g.trim()||s.push(`${h.artifactName||h.id} has no generated code.`),o.push({artifactId:h.id,artifactName:h.artifactName,artifactType:h.artifactType,fileName:p,content:g,type:m,path:h.deployPath||Qv(p,m),deployPath:h.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((h,p)=>({entry:h,index:p})).filter(({entry:h})=>h.type===Xe.FUNCTION&&h.path===a);if(l.length>1){const h=l[0],p={...h.entry,artifactId:l.map(({entry:m})=>m.artifactId).join("+"),artifactName:h.entry.artifactName,content:l.map(({entry:m})=>`// ${m.artifactId} +`;)n++;e+=" "}else if(i==="/*"){for(n+=2;n"&&(n--,n===0))return{inner:t.slice(e+1,i),end:i+1};return null}function Lv(t,e){const n=new RegExp(`class\\s+${e}\\b[^{]*\\{`).exec(t);if(!n)return null;let i=0;for(let r=n.index+n[0].length-1;rNv(t).usable);function Bv(t=""){const e=tr(t);return Ov.filter(n=>n.detect(e)).map(({id:n,severity:i,message:r})=>({id:n,severity:i,message:r}))}function Dv(t){const e=[],n=t.matchAll(/\bFuture\b/g);for(const i of n){let r=i.index+6,s=null;const o=r;for(;ro;if(t[r]==="<"){const u=Mv(t,r);if(!u||(s=u.inner.replace(/\s+/g," ").trim(),r=u.end,!/\s/.test(t[r]||"")))continue;for(;rTu(o.functionName)===i);if(r)return r;const s=o=>!o.functionName.startsWith("_");return n.find(s)||n[0]}function Fs(t=""){return Array.from(tr(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function jv(t="",e=""){return bl(t,e)?.returnType||null}function $u(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 Uv(t,e){const n=Fs(e);if(n.length===0)return null;const r=String(t||"").split("/").pop().replace(/\.dart$/,"");if(n.some(l=>$u(l)===r)||n.length>1)return null;const[o]=n,a=`${$u(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 El(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function Hv(t,e,n=""){const i=bl(e,n)?.functionName;if(!i)return null;const r=String(t||"").split("/").pop(),s=wl(r,"A");if(s===i)return null;const o=`${El(i)}.dart`;return`File name "${r}" does not match Action "${i}". FlutterFlow derives the action from the file name, so it looks for "${s}" and reports Action "${s}" declaration not found. Rename the file to "${o}" - FlutterFlow puts an underscore before every capital - or rename the function to "${s}".`}function Wv(t="",e=""){return bl(t,e)!==null}function zv(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(i=>Rv.has(i)?!1:!Tv.some(s=>i.endsWith(s))||e.has(i))}function qv(t,{functionName:e="",declaredTypes:n=new Set}={}){const i=jv(t,e),r=zv(i,n);if(r.length===0)return null;const[s]=r;let o;return n.has(s)?o=`uses Code File type "${s}", which FlutterFlow cannot process as an Action Return Value`:i===s?o="is not a FlutterFlow Action Return Value":o=`uses type "${s}", which is not a FlutterFlow Action Return Value`,`CustomAction return type "${i}" ${o}. Return JSON (Future) or an existing FlutterFlow Data Type (*Struct) instead.`}function Vv(t,e={}){const n=[],i=t.fileName||"",r=t.code||"";if(Fv.has(t.artifactType)||n.push(xt(t,"error",`Unsupported artifact type "${t.artifactType}".`)),i.endsWith(".dart")||n.push(xt(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!r.trim())return n.push(xt(t,"warning","Generated artifact has no Dart code yet.")),n;if(t.artifactType==="CustomWidget"){/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)||n.push(xt(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const s of Bv(r))n.push(xt(t,s.severity,s.message))}if(t.artifactType==="CustomAction"&&!Wv(r,t.artifactName)&&n.push(xt(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const s=e.declaredTypes||new Set(Fs(r)),o=qv(r,{functionName:t.artifactName,declaredTypes:s});o&&n.push(xt(t,"error",o));const a=Hv(i,r,t.artifactName);a&&n.push(xt(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)&&n.push(xt(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const s=Uv(i,r);s&&n.push(xt(t,"info",s))}return n}function Gv(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],n=new Set(e.flatMap(s=>Fs(s.code||""))),i=e.flatMap(s=>Vv(s,{declaredTypes:n})),r=e.map(s=>({artifactId:s.id,fileName:s.fileName,pathHint:Ru[s.artifactType]||Ru.CodeFile}));return{valid:i.every(s=>s.severity!=="error"),findings:i,deployHints:r}}const Mu="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function Lu(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function Kv(t=""){const e=t.indexOf(Mu);return e===-1?t:t.slice(e+Mu.length).replace(/^\s*\n/,"")}const Yv=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function Jv(t="",e=""){const n=Kv(t),i=new Set((e.match(/^\s*import .*$/gm)||[]).map(Lu).filter(Boolean)),r=n.split(` +`).filter(s=>{const o=Lu(s);return o===null||!i.has(o)?!0:!Yv.test(s)}).join(` +`).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+r}const Zv=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations"]);function dh(t){let e="",n=0;for(;n{const i=n.name||n.package;if(!i||i==="flutter")return e;const r=n.versionRequired||n.required;return e[i]=r&&n.version||"",e},{})}function n_(t){const e=new Map,n=new Map,i=[];for(const r of t)e.has(r.fileName)?i.push(`Duplicate deploy file name "${r.fileName}" for artifacts "${e.get(r.fileName)}" and "${r.artifactId}".`):e.set(r.fileName,r.artifactId),n.has(r.path)?i.push(`Duplicate deploy path "${r.path}" for artifacts "${n.get(r.path)}" and "${r.artifactId}".`):n.set(r.path,r.artifactId);return i}function i_(t,e={}){const n=Array.isArray(t?.artifacts)?t.artifacts:[],r=(e.selectedArtifactIds||t?.deployOrder||n.map(f=>f.id)).map(f=>n.find(p=>p.id===f)).filter(Boolean),s=[...t?.warnings||[]];let o=[];r.forEach(f=>{const p=t_(f),g=f.fixedCode||f.code||"",m=f.codeType||Qv[f.artifactType]||Xe.OTHER;g.trim()||s.push(`${f.artifactName||f.id} has no generated code.`),o.push({artifactId:f.id,artifactName:f.artifactName,artifactType:f.artifactType,fileName:p,content:g,type:m,path:f.deployPath||e_(p,m),deployPath:f.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((f,p)=>({entry:f,index:p})).filter(({entry:f})=>f.type===Xe.FUNCTION&&f.path===a);if(l.length>1){const f=l[0],p={...f.entry,artifactId:l.map(({entry:m})=>m.artifactId).join("+"),artifactName:f.entry.artifactName,content:l.map(({entry:m})=>`// ${m.artifactId} ${m.content}`).join(` -`)},g=new Set(l.slice(1).map(({index:m})=>m));o=o.filter((m,v)=>!g.has(v)),o[h.index]=p}const u={...Mu(t?.dependencies),...r.reduce((h,p)=>({...h,...Mu(p.dependencies)}),{})},c={};r.forEach(h=>{bl(h.code||"").forEach(p=>{p in u||(c[p]="")})});const d={...c,...u},f=t_(o);return{bundleId:t?.id||"bundle-current",title:t?.title||"Generated artifact bundle",fileEntries:o,dependencies:d,relationships:t?.relationships||[],warnings:s,errors:f}}function i_(t){return String(t||"").match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/)?.[1]}function r_(t){return String(t||"").split("/").pop().replace(/\.dart$/,"").split(/[^A-Za-z0-9]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function s_(t,e){const i=[r_(t),i_(e.content),e.artifactName].find(r=>/^[A-Z][A-Za-z0-9_]*$/.test(String(r||"")));if(!i)throw new Error(`Cannot derive a FlutterFlow custom class name for ${t}.`);return i}function o_(t,e=new Map){const n=[];for(const[i,r]of t.entries())r.type!=="C"||e.has(r.path)||n.push({artifactId:r.artifactId||i,className:s_(i,r),content:r.content,fileName:i,path:r.path});return n}function a_(t,e){const n=new Set(e.map(i=>i.path));return new Map(Array.from(t.entries()).filter(([,i])=>!n.has(i.path)))}const Lu={pass:0,warning:1,fail:2},l_=["manualActions"];function st(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Vt(...t){for(const e of t){if(typeof e=="string"&&e.trim())return e.trim();if(Array.isArray(e)&&e.length>0){const n=e.filter(i=>typeof i=="string").join(` -`);if(n)return n}}return""}function kt(t){return t==null?[]:Array.isArray(t)?t:[t]}function c_(t){const e=st(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const n=Number(e);if(Number.isFinite(n))return Nu(n);const i=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return i?Nu(Number(i[1])):null}function Nu(t){return t>=0&&t<=100?t:null}function lt(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function El(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 Ra(...t){return t.filter(Boolean).reduce((e,n)=>Lu[n]>Lu[e]?n:e,"pass")}function uh(t,e="warning",n="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:n};const i=st(t),r=Vt(i.message,i.title,i.issue,i.description,i.summary);return r?{severity:El(i.severity||i.status||i.level)||e,message:r,suggestion:Vt(i.suggestion,i.fix,i.recommendation,i.action),source:i.source||n}:null}function Ta(t,e="review"){const n=st(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([r,s])=>kt(n[r]).map(o=>uh(o,s,e)).filter(Boolean))}function u_(t,e,n=null){if(typeof t=="string")return{id:`${n||"bundle"}-manual-${e+1}`,title:t,detail:"",location:"",timing:"unspecified",artifactId:n,source:"Code Review"};const i=st(t),r=Vt(i.title,i.action,i.step,i.message,i.name,i.description);return r?{id:i.id||`${n||"bundle"}-manual-${e+1}`,title:r,detail:Vt(i.detail,i.instructions,i.description),location:Vt(i.location,i.flutterFlowPath,i.path),timing:Vt(i.timing,i.phase)||"unspecified",artifactId:n,source:Vt(i.source)||"Code Review"}:null}function $a(t,e=null){const n=st(t);return l_.flatMap(i=>kt(n[i])).map((i,r)=>u_(i,r,e)).filter(Boolean)}function d_(t){let e=typeof t=="string"?Pa(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const n=st(e);typeof n.content=="string"&&(e=Pa(n.content)||e);const i=st(e),r=st(i.reviewResult||i.codeReview||i.result);return{rawText:"",root:Object.keys(r).length?r:i}}function f_(t,e){const n=[e.id,e.fileName,e.artifactName].map(lt);return t.find(i=>{const r=st(i);return[r.id,r.fileName,r.artifactName,r.name].map(lt).some(s=>s&&n.includes(s))})||null}function h_(t,e){return kt(t?.metadata?.compatibility?.deployHints).find(r=>lt(r?.artifactId)===lt(e.id)||lt(r?.fileName)===lt(e.fileName))?.pathHint||""}function p_(t,e){return kt(t?.relationships).filter(n=>lt(n?.from)===lt(e.id)||lt(n?.to)===lt(e.id))}function g_(t,e){return kt(t?.metadata?.compatibility?.findings).filter(n=>!n?.artifactId||lt(n.artifactId)===lt(e.id)).map(n=>uh(n,"warning","Compatibility check")).filter(Boolean)}function m_(t,e,n,i){const r=f_(e,n),s=st(r?.review||r||n.review),o=Object.keys(s).length>0,a=[...Ta(s),...g_(t,n)],l=$a(s,n.id),u=El(s.status||s.verdict||s.outcome||s.result),c=a.length?Ra(...a.map(f=>f.severity)):null,d=Ra(u,c,o?null:"warning");return{...n,index:i,status:d,statusReason:o?Vt(s.summary,s.overview,s.assessment,s.conclusion)||(a.length?`${a.length} review finding${a.length===1?"":"s"}`:"No file-level findings"):"No file-level verdict was returned",reviewComplete:o,findings:a,manualSteps:l,fixedSource:typeof s.fixedSource=="string"&&s.fixedSource.trim()?s.fixedSource.trim():null,pathHint:h_(t,n),relationships:p_(t,n)}}function v_({status:t,score:e,artifactPresentations:n,manualSteps:i}){const r=n.length;if(r===0&&i.length===0)return e==null?"Code review returned no overall summary and no score.":`Reviewed bundle with score ${e}/100.`;const s=n.reduce((a,l)=>(a[l.status]+=1,a),{pass:0,warning:0,fail:0}),o=[];return t&&o.push(`Overall verdict: ${t}.`),r&&o.push(`${r} artifact${r===1?"":"s"}: ${s.pass} pass, ${s.warning} warn, ${s.fail} fail.`),i.length&&o.push(`Do before deploy: ${i.map(a=>a.title).join("; ")}.`),e==null&&o.push("No numeric score (0-100) was returned."),o.join(" ")}function __({bundle:t,reviewResult:e}){const n=st(t),i=kt(n.artifacts),{root:r,rawText:s}=d_(e),o=[r.bundleReview,r.overallReview,r.overall,r.bundleSummary,r.summaryReview,r.review].map(st).find(S=>Object.keys(S).length)||{},a=kt(r.artifacts||r.files||r.reviews),l=i.map((S,_)=>m_(n,a,S,_)),u=Ta(r),d=[...Ta(o),...u],f=[...$a(o),...$a(r),...l.flatMap(S=>S.manualSteps)].filter((S,_,b)=>b.findIndex(k=>k.title===S.title&&k.artifactId===S.artifactId)===_),h=El(o.status||o.verdict||o.overallStatus||r.status||r.verdict||r.overallStatus||r.outcome),p=Ra(h,...d.map(S=>S.severity),...l.map(S=>S.status)),g=o.score??r.score??r.overallScore??s,m=c_(g),v=Vt(o.headline,o.summary,o.executiveSummary,o.overview,o.assessment,o.conclusion,r.overallSummary,r.headline,r.summary,r.executiveSummary,r.overview,r.assessment,r.conclusion,s)||v_({status:p,score:m,artifactPresentations:l,manualSteps:f}),E=l.reduce((S,_)=>(S[_.status]+=1,S),{pass:0,warning:0,fail:0});return{title:n.title||"Generated artifact bundle",description:n.description||"",status:p,score:m,summary:v,findings:d,manualSteps:f,artifacts:l,counts:E,reviewCoverage:{reviewed:l.filter(S=>S.reviewComplete).length,total:l.length},deployOrder:kt(n.deployOrder),relationships:kt(n.relationships),warnings:kt(n.warnings),compatibility:st(n.metadata?.compatibility)}}const y_=/^\uFEFF/;function Ai(t){let e=0,n=t.length;for(;ee&&!t[n-1].trim();)n--;return t.slice(e,n).join(` -`)}function w_(t){const e=String(t??"").replace(y_,"");if(!e.trim())return"";const n=e.split(` -`),i=c=>{const d=c.trim();return/^`{3,}[A-Za-z0-9+#_.-]*$/.test(d)?c.length-c.trimStart().length:-1};let r=0,s=-1;const o=[];{let c=0;for(let d=0;d=0&&(r++,s<0&&(s=d),o.push(c+f)),c+=n[d].length+1}}if(r===0)return Ai(n);{const c=Ma(e);if(!c.error&&o.every(f=>Bu(f,c.commentAndStringRanges)))return Ai(n)}if(r===1){const c=Ai(n.slice(0,s)),d=Ai(n.slice(s+1));return d.length>=c.length?d:c}const a=[];let l=null;for(let c=0;cc.length>0);return u.length===0?"":u.join(` +`)},g=new Set(l.slice(1).map(({index:m})=>m));o=o.filter((m,v)=>!g.has(v)),o[f.index]=p}const u={...Nu(t?.dependencies),...r.reduce((f,p)=>({...f,...Nu(p.dependencies)}),{})},c={};r.forEach(f=>{Sl(f.code||"").forEach(p=>{p in u||(c[p]="")})});const d={...c,...u},h=n_(o);return{bundleId:t?.id||"bundle-current",title:t?.title||"Generated artifact bundle",fileEntries:o,dependencies:d,relationships:t?.relationships||[],warnings:s,errors:h}}function r_(t){return String(t||"").match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/)?.[1]}function s_(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 o_(t,e){const i=[s_(t),r_(e.content),e.artifactName].find(r=>/^[A-Z][A-Za-z0-9_]*$/.test(String(r||"")));if(!i)throw new Error(`Cannot derive a FlutterFlow custom class name for ${t}.`);return i}function a_(t,e=new Map){const n=[];for(const[i,r]of t.entries())r.type!=="C"||e.has(r.path)||n.push({artifactId:r.artifactId||i,className:o_(i,r),content:r.content,fileName:i,path:r.path});return n}function l_(t,e){const n=new Set(e.map(i=>i.path));return new Map(Array.from(t.entries()).filter(([,i])=>!n.has(i.path)))}const Ou={pass:0,warning:1,fail:2},c_=["manualActions"];function st(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Vt(...t){for(const e of t){if(typeof e=="string"&&e.trim())return e.trim();if(Array.isArray(e)&&e.length>0){const n=e.filter(i=>typeof i=="string").join(` +`);if(n)return n}}return""}function kt(t){return t==null?[]:Array.isArray(t)?t:[t]}function u_(t){const e=st(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const n=Number(e);if(Number.isFinite(n))return Bu(n);const i=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return i?Bu(Number(i[1])):null}function Bu(t){return t>=0&&t<=100?t:null}function lt(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function xl(t){const e=String(t||"").toLowerCase();return/(fail|error|critical|block|reject|invalid)/.test(e)?"fail":/(warn|attention|manual|partial|incomplete|concern)/.test(e)?"warning":/(pass|success|ready|approve|valid|clean|info|notice)/.test(e)?"pass":null}function $a(...t){return t.filter(Boolean).reduce((e,n)=>Ou[n]>Ou[e]?n:e,"pass")}function fh(t,e="warning",n="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:n};const i=st(t),r=Vt(i.message,i.title,i.issue,i.description,i.summary);return r?{severity:xl(i.severity||i.status||i.level)||e,message:r,suggestion:Vt(i.suggestion,i.fix,i.recommendation,i.action),source:i.source||n}:null}function Ma(t,e="review"){const n=st(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([r,s])=>kt(n[r]).map(o=>fh(o,s,e)).filter(Boolean))}function d_(t,e,n=null){if(typeof t=="string")return{id:`${n||"bundle"}-manual-${e+1}`,title:t,detail:"",location:"",timing:"unspecified",artifactId:n,source:"Code Review"};const i=st(t),r=Vt(i.title,i.action,i.step,i.message,i.name,i.description);return r?{id:i.id||`${n||"bundle"}-manual-${e+1}`,title:r,detail:Vt(i.detail,i.instructions,i.description),location:Vt(i.location,i.flutterFlowPath,i.path),timing:Vt(i.timing,i.phase)||"unspecified",artifactId:n,source:Vt(i.source)||"Code Review"}:null}function La(t,e=null){const n=st(t);return c_.flatMap(i=>kt(n[i])).map((i,r)=>d_(i,r,e)).filter(Boolean)}function f_(t){let e=typeof t=="string"?Ra(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const n=st(e);typeof n.content=="string"&&(e=Ra(n.content)||e);const i=st(e),r=st(i.reviewResult||i.codeReview||i.result);return{rawText:"",root:Object.keys(r).length?r:i}}function h_(t,e){const n=[e.id,e.fileName,e.artifactName].map(lt);return t.find(i=>{const r=st(i);return[r.id,r.fileName,r.artifactName,r.name].map(lt).some(s=>s&&n.includes(s))})||null}function p_(t,e){return kt(t?.metadata?.compatibility?.deployHints).find(r=>lt(r?.artifactId)===lt(e.id)||lt(r?.fileName)===lt(e.fileName))?.pathHint||""}function g_(t,e){return kt(t?.relationships).filter(n=>lt(n?.from)===lt(e.id)||lt(n?.to)===lt(e.id))}function m_(t,e){return kt(t?.metadata?.compatibility?.findings).filter(n=>!n?.artifactId||lt(n.artifactId)===lt(e.id)).map(n=>fh(n,"warning","Compatibility check")).filter(Boolean)}function v_(t,e,n,i){const r=h_(e,n),s=st(r?.review||r||n.review),o=Object.keys(s).length>0,a=[...Ma(s),...m_(t,n)],l=La(s,n.id),u=xl(s.status||s.verdict||s.outcome||s.result),c=a.length?$a(...a.map(h=>h.severity)):null,d=$a(u,c,o?null:"warning");return{...n,index:i,status:d,statusReason:o?Vt(s.summary,s.overview,s.assessment,s.conclusion)||(a.length?`${a.length} review finding${a.length===1?"":"s"}`:"No file-level findings"):"No file-level verdict was returned",reviewComplete:o,findings:a,manualSteps:l,fixedSource:typeof s.fixedSource=="string"&&s.fixedSource.trim()?s.fixedSource.trim():null,pathHint:p_(t,n),relationships:g_(t,n)}}function __({status:t,score:e,artifactPresentations:n,manualSteps:i}){const r=n.length;if(r===0&&i.length===0)return e==null?"Code review returned no overall summary and no score.":`Reviewed bundle with score ${e}/100.`;const s=n.reduce((a,l)=>(a[l.status]+=1,a),{pass:0,warning:0,fail:0}),o=[];return t&&o.push(`Overall verdict: ${t}.`),r&&o.push(`${r} artifact${r===1?"":"s"}: ${s.pass} pass, ${s.warning} warn, ${s.fail} fail.`),i.length&&o.push(`Do before deploy: ${i.map(a=>a.title).join("; ")}.`),e==null&&o.push("No numeric score (0-100) was returned."),o.join(" ")}function y_({bundle:t,reviewResult:e}){const n=st(t),i=kt(n.artifacts),{root:r,rawText:s}=f_(e),o=[r.bundleReview,r.overallReview,r.overall,r.bundleSummary,r.summaryReview,r.review].map(st).find(S=>Object.keys(S).length)||{},a=kt(r.artifacts||r.files||r.reviews),l=i.map((S,_)=>v_(n,a,S,_)),u=Ma(r),d=[...Ma(o),...u],h=[...La(o),...La(r),...l.flatMap(S=>S.manualSteps)].filter((S,_,b)=>b.findIndex(k=>k.title===S.title&&k.artifactId===S.artifactId)===_),f=xl(o.status||o.verdict||o.overallStatus||r.status||r.verdict||r.overallStatus||r.outcome),p=$a(f,...d.map(S=>S.severity),...l.map(S=>S.status)),g=o.score??r.score??r.overallScore??s,m=u_(g),v=Vt(o.headline,o.summary,o.executiveSummary,o.overview,o.assessment,o.conclusion,r.overallSummary,r.headline,r.summary,r.executiveSummary,r.overview,r.assessment,r.conclusion,s)||__({status:p,score:m,artifactPresentations:l,manualSteps:h}),E=l.reduce((S,_)=>(S[_.status]+=1,S),{pass:0,warning:0,fail:0});return{title:n.title||"Generated artifact bundle",description:n.description||"",status:p,score:m,summary:v,findings:d,manualSteps:h,artifacts:l,counts:E,reviewCoverage:{reviewed:l.filter(S=>S.reviewComplete).length,total:l.length},deployOrder:kt(n.deployOrder),relationships:kt(n.relationships),warnings:kt(n.warnings),compatibility:st(n.metadata?.compatibility)}}const w_=/^\uFEFF/;function Ai(t){let e=0,n=t.length;for(;ee&&!t[n-1].trim();)n--;return t.slice(e,n).join(` +`)}function b_(t){const e=String(t??"").replace(w_,"");if(!e.trim())return"";const n=e.split(` +`),i=c=>{const d=c.trim();return/^`{3,}[A-Za-z0-9+#_.-]*$/.test(d)?c.length-c.trimStart().length:-1};let r=0,s=-1;const o=[];{let c=0;for(let d=0;d=0&&(r++,s<0&&(s=d),o.push(c+h)),c+=n[d].length+1}}if(r===0)return Ai(n);{const c=Na(e);if(!c.error&&o.every(h=>ju(h,c.commentAndStringRanges)))return Ai(n)}if(r===1){const c=Ai(n.slice(0,s)),d=Ai(n.slice(s+1));return d.length>=c.length?d:c}const a=[];let l=null;for(let c=0;cc.length>0);return u.length===0?"":u.join(` -`)}function b_(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 dh(t){const e=b_(t);return Array.from(e.matchAll(/class\s+([A-Z]\w*)\s+extends\s+[A-Za-z_]\w*Widget\b/g),n=>n[1])}function fh(t){return`${wl(t)}.dart`}function E_(t){return _l(t,"W")}const Ou={"(":")","[":"]","{":"}"},S_={")":"(","]":"[","}":"{"},x_=/[A-Za-z0-9_]/;function Ma(t){const e=[{kind:"code",opener:null,openedLine:0}],n=[];let i=1,r=0;const s=(c,d)=>{(c===` +`)}function E_(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 hh(t){const e=E_(t);return Array.from(e.matchAll(/class\s+([A-Z]\w*)\s+extends\s+[A-Za-z_]\w*Widget\b/g),n=>n[1])}function ph(t){return`${El(t)}.dart`}function S_(t){return wl(t,"W")}const Du={"(":")","[":"]","{":"}"},x_={")":"(","]":"[","}":"{"},I_=/[A-Za-z0-9_]/;function Na(t){const e=[{kind:"code",opener:null,openedLine:0}],n=[];let i=1,r=0;const s=(c,d)=>{(c===` `||c==="\r"&&d!==` `)&&i++};let o=null;const a=()=>{for(const c of e)(c.kind==="string"||c.kind==="block-comment"||c.kind==="line-comment")&&n.push({start:c.startIndex,end:t.length})};for(;r0?t[r-1]:"",p=r>1?t[r-2]:"",g=(h==="r"||h==="R")&&!x_.test(p);e.push({kind:"string",quote:c,triple:f,raw:g,startIndex:r,openedLine:i}),r+=f?3:1;continue}if(Ou[c]){e.push({kind:"code",opener:c,openedLine:i}),r++;continue}if(S_[c]){if(d.interpolation&&c==="}"){e.pop(),r++;continue}if(d.opener&&Ou[d.opener]===c){e.pop(),r++;continue}return d.opener?(a(),{error:o??`line ${i}: "${c}" closes nothing - "${d.opener}" opened on line ${d.openedLine} is still open`,commentAndStringRanges:n}):(a(),{error:o??`line ${i}: unexpected "${c}" with no matching opener`,commentAndStringRanges:n})}s(c,t[r+1]),r++}a();let l=e.length-1;for(;l>0&&e[l].kind==="line-comment";)l--;let u=o;if(!u){const c=e[l];if(!(c.kind==="code"&&!c.opener&&!c.interpolation))if(c.kind==="string")u=`unclosed ${c.triple?"triple-quoted ":""}string starting on line ${c.openedLine} was never closed`;else if(c.kind==="block-comment")u=`unterminated /* comment starting on line ${c.openedLine}`;else if(c.interpolation){const d=e.findLast(h=>h.opener);u=`unclosed "\${" expression${d?` opened on line ${d.openedLine}`:""} was never closed`}else u=`"${c.opener}" opened on line ${c.openedLine} is never closed`}return{error:u,commentAndStringRanges:n}}function I_(t){return Ma(String(t??"")).error}function Bu(t,e){return e.some(({start:n,end:i})=>t>=n&&ttypeof n=="string"?n:n?.errorMessage).filter(Boolean);return e.length>0?e.join("; "):JSON.stringify(t)}return t&&typeof t=="object"?t.errorMessage||JSON.stringify(t):String(t??"")}const k_=["gmail.com","googlemail.com","outlook.com","hotmail.com","live.com","msn.com"],C_="MAGIC_LINK_SENT",A_="PLUS_ALIAS_REJECTED",P_="Please enter your primary email address. Plus aliases (such as {email}) are not allowed for {domain} accounts.",Ps={allowlistedDomains:k_,successCode:C_,validationCode:A_,messageTemplate:P_},F_=new Set(Ps.allowlistedDomains),R_=Ps.successCode,hh=Ps.validationCode;function Fs(t){return typeof t=="string"?t.trim():""}function T_(t){const e=Fs(t),n=e.lastIndexOf("@");if(n<=0||n===e.length-1)return!1;const i=e.slice(0,n),r=e.slice(n+1).toLowerCase();return F_.has(r)?i.includes("+"):!1}function $_(t,e){return Ps.messageTemplate.replaceAll("{email}",t).replaceAll("{domain}",e)}function ph(t){if(!T_(t))return null;const e=Fs(t),n=e.lastIndexOf("@"),i=e.slice(n+1).toLowerCase();return $_(e,i)}function gh(t,e){return t?.code===hh?t.message||ph(e)||"Please enter your primary email address.":t?.code===R_||!t?.code?`Check your email — we sent a link to ${Fs(e)}`:t.message||"Something went wrong. Please try again."}const M_="ccc_auth_session",L_="ccc_subscription",N_=Object.freeze(["hasSeenWalkthrough"]);function O_(t){const e=[];for(const n of N_)t.getItem(n)!==null&&(t.removeItem(n),e.push(n));return e}function B_(){return[M_,L_]}function D_({storage:t,onIdentityChanged:e,onPlanChanged:n}){for(const i of B_())t.removeItem(i);typeof e=="function"&&e(),typeof n=="function"&&n()}function j_({sendLink:t,getEmail:e,onState:n}){let i=!1;return async function(){if(i)return{status:"busy"};i=!0;let s;try{n({status:"pending",error:null});const o=await t(e());return s={status:"sent",data:o},n({status:"sent",data:o}),s}catch(o){return s={status:"error",error:o},n({status:"error",error:o}),s}finally{i=!1}}}const U_=/^dependencies\s*:\s*(?:#.*)?$/,H_=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function Rs(t){const e=t.match(H_);return e?e[1]??e[2]??e[3]:null}function ar(t){const e=t.trim();return e===""||e.startsWith("#")}function hi(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function xl(t,e){const n=t.findIndex(s=>e.test(s));if(n===-1)return null;let i=n,r=null;for(let s=n+1;s=0.0.0"}`}function V_(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([u])=>u&&u!=="flutter");if(i.length===0)return{yaml:n,added:[],alreadyPresent:[]};const r=n.split(` -`),s=new Set(vh(n)),o=[],a=[];for(const[u,c]of i)s.has(u)?a.push(u):(o.push([u,c]),s.add(u));if(o.length===0)return{yaml:n,added:[],alreadyPresent:a};const l=Il(r);if(l){const u=o.map(([c,d])=>Du(l.childIndent,c,d));r.splice(l.endIndex,0,...u)}else r.length>0&&r[r.length-1].trim()!==""&&r.push(""),r.push("dependencies:"),o.forEach(([u,c])=>{r.push(Du(" ",u,c))});return{yaml:r.join(` -`),added:o.map(([u])=>u),alreadyPresent:a}}function G_(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([l])=>l&&l!=="flutter");if(i.length===0)return{yaml:n,overridden:[],skipped:[]};const r=n.split(` -`),s=$s(n),o=[],a=[];for(const[l,u]of i){const c=s.get(l);if(!c||!c.isScalar||!String(u||"").trim()){a.push(l);continue}const d=" ".repeat(hi(r[c.lineIndex]));r[c.lineIndex]=`${d}${l}: ${yh(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:r.join(` -`),overridden:o,skipped:a}}function wh(t){const e=String(t||""),n=[];return e.trim()?(/^name:\s*\S+/m.test(e)||n.push("pubspec.yaml missing name field"),Il(e.split(` -`))||n.push("pubspec.yaml missing dependencies section"),vh(e).includes("flutter")||n.push("pubspec.yaml missing Flutter SDK dependency"),{valid:n.length===0,errors:n}):(n.push("pubspec.yaml is empty"),{valid:!1,errors:n})}const K_=">=3.0.0 <4.0.0";function La(t){const e=String(t||"").trim(),n=e[0];return n!=="'"&&n!=='"'||e[e.length-1]!==n?e:e.slice(1,-1).replaceAll(`${n}${n}`,n)}function Y_(t=""){const e=Zv(t).filter(n=>!n.startsWith("dart:")&&!n.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function ju(t,e,n){const i=[];for(const[r,s]of t){if(s.isScalar){e[r]=La(s.constraint);continue}if(s.sourceKey==="sdk"){n.add(r);continue}if(s.sourceKey===null&&s.version){e[r]=La(s.version);continue}i.push(r)}return i}function J_(t){const e=new Set,n={},i={},r=ju($s(t),n,e);r.push(...ju(z_(t,"dependency_overrides"),i,e));const s=new Set([...Object.keys(n),...e]),{sdk:o}=_h(t);return{sdkConstraint:La(o)||K_,dependencies:n,overrides:i,sdkPackages:[...e].sort(),availablePackages:s,unrepresentable:r}}function Z_(t,e,n){return e.length>0?`${t} imports ${e.join(", ")}, which FlutterFlow only generates once the app is built, so it could not be compiled before the deploy.`:`${t} imports ${n.join(", ")}, which your project's pubspec.yaml does not declare with a version constraint, so it could not be compiled before the deploy.`}function X_(t,e){const{sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s,availablePackages:o,unrepresentable:a}=J_(e),l={sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s},u=[],c=[],d=a.map(f=>`Your project declares ${f} from a source that cannot be reproduced outside it, so the pre-deploy compile check runs against a scratch package graph that omits ${f}. Classes that do not import ${f} directly are still checked, but against that reduced graph, so their transitive package resolution may differ from your project's and the check is approximate for them.`);for(const f of t){const{className:h,content:p}=f,g=bl(p),m=g.filter(S=>a.includes(S));if(m.length>0){c.push({className:h,reason:`${h} was not compiled before deploying: it imports ${m.join(", ")}, which your project declares from a source that cannot be reproduced outside it, so package resolution could not be matched exactly.`});continue}const{unresolvableImports:v}=Y_(p),E=g.filter(S=>!o.has(S));if(v.length>0||E.length>0){c.push({className:h,reason:Z_(h,v,E)});continue}u.push({fileName:`${wl(h)}.dart`,content:p})}return{manifest:l,sources:u,skipped:c,approximate:d}}function Uu(t,e){const n=`${t}${e}`.split(` -`),i=n.pop()??"",r=[];for(const s of n){const o=bh(s);o&&r.push(o)}return{events:r,buffer:i}}function Q_(t){const e=bh(t);return e?[e]:[]}function bh(t){const e=t.trim();if(!e)return null;try{const n=JSON.parse(e);return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}const Le=Object.freeze({COMMITTED:"committed",PARTIAL:"partial",FAILED:"failed",UNCONFIRMED:"unconfirmed"}),Eh=12e4,Sh=1e4;function xh(t){return t?.unconfirmed===!0||t?.outcome===Le.UNCONFIRMED?Le.UNCONFIRMED:t?.partial===!0||t?.outcome===Le.PARTIAL?Le.PARTIAL:t?.success===!0?Le.COMMITTED:Le.FAILED}class Qe extends Error{constructor(e){super(e),this.name="UnconfirmedDeployError",this.outcome=Le.UNCONFIRMED}}function Hu({httpStatus:t}={}){return new Qe(`Every FlutterFlow sync endpoint lost its response or ended in a server error${t?` (last: HTTP ${t})`:""} — neither can prove the push was refused, so it may already have been applied. Open the FlutterFlow project to reconcile before retrying.`)}async function ey(t,e={}){const{onPhase:n,onLog:i}=e;let r=null,s=null,o="";const a=u=>{if(u.event==="phase"){u.phase&&(s=u.phase),u.message&&n&&n(u.message);return}if(u.event==="log"){u.message&&i&&i(u.message);return}r=u};let l=null;try{if(t.body?.getReader){const u=t.body.getReader(),c=new TextDecoder;for(;;){const{done:d,value:f}=await u.read();if(d)break;const h=Uu(o,c.decode(f,{stream:!0}));o=h.buffer,h.events.forEach(a)}}else{const u=Uu("",await t.text());o=u.buffer,u.events.forEach(a)}}catch(u){l=u}return Q_(o).forEach(a),r?{...r,success:r.success===!0||r.success===void 0&&t.ok,finalResultReceived:!0,runnerPhase:s,httpStatus:t.status}:{success:!1,finalResultReceived:!1,httpRejected:!t.ok,httpStatus:t.status,runnerPhase:s,error:t.ok?l?"The connection to the FlutterFlow deploy runner dropped before it reported a result.":"The FlutterFlow deploy runner closed the connection before it finished.":`FlutterFlow custom class provisioning failed (HTTP ${t.status}).`}}const ty=new Set(["connected","workspace_init","workspace_ready","verifying"]);function ny(t){return t?.preWrite===!0||Array.isArray(t?.analyzerErrors)&&t.analyzerErrors.length>0?!0:typeof t?.runnerPhase=="string"?ty.has(t.runnerPhase):typeof t?.httpStatus=="number"?t.httpStatus>=400&&t.httpStatus<500:!1}function Wu(t){if(t?.finalResultReceived){const e=xh(t);return e===Le.FAILED&&!ny(t)?Le.UNCONFIRMED:e}return t?.httpRejected?Le.FAILED:Le.UNCONFIRMED}function iy(){let t=document.getElementById("fx-grid");if(!t)return null;const e=window.matchMedia("(prefers-reduced-motion: reduce)"),n=window.matchMedia("(pointer: none)");let i=t.getContext("webgl2",{alpha:!0,antialias:!1,depth:!1,stencil:!1,premultipliedAlpha:!0,powerPreference:"low-power"}),r=i?null:t.getContext("2d");if(!i&&!r)return null;const s='',o=`#version 300 es +`){n.push({start:d.startIndex,end:r}),o??=`line ${i}: string starting on line ${d.openedLine} is never closed`,e.pop();continue}if(!d.raw&&c==="\\"){s(t[r+1]??"",t[r+2]??""),r+=2;continue}if(!d.raw&&c==="$"&&t[r+1]==="{"){e.push({kind:"code",opener:null,interpolation:!0}),r+=2;continue}const h=d.triple?3:1;if(c===d.quote&&t.slice(r,r+h)===d.quote.repeat(h)){n.push({start:d.startIndex,end:r+h}),e.pop(),r+=h;continue}s(c,t[r+1]),r++;continue}if(c==="/"&&t[r+1]==="/"){e.push({kind:"line-comment",startIndex:r}),r+=2;continue}if(c==="/"&&t[r+1]==="*"){e.push({kind:"block-comment",startIndex:r,openedLine:i,depth:1}),r+=2;continue}if(c==="'"||c==='"'){const h=t.slice(r,r+3)===c.repeat(3),f=r>0?t[r-1]:"",p=r>1?t[r-2]:"",g=(f==="r"||f==="R")&&!I_.test(p);e.push({kind:"string",quote:c,triple:h,raw:g,startIndex:r,openedLine:i}),r+=h?3:1;continue}if(Du[c]){e.push({kind:"code",opener:c,openedLine:i}),r++;continue}if(x_[c]){if(d.interpolation&&c==="}"){e.pop(),r++;continue}if(d.opener&&Du[d.opener]===c){e.pop(),r++;continue}return d.opener?(a(),{error:o??`line ${i}: "${c}" closes nothing - "${d.opener}" opened on line ${d.openedLine} is still open`,commentAndStringRanges:n}):(a(),{error:o??`line ${i}: unexpected "${c}" with no matching opener`,commentAndStringRanges:n})}s(c,t[r+1]),r++}a();let l=e.length-1;for(;l>0&&e[l].kind==="line-comment";)l--;let u=o;if(!u){const c=e[l];if(!(c.kind==="code"&&!c.opener&&!c.interpolation))if(c.kind==="string")u=`unclosed ${c.triple?"triple-quoted ":""}string starting on line ${c.openedLine} was never closed`;else if(c.kind==="block-comment")u=`unterminated /* comment starting on line ${c.openedLine}`;else if(c.interpolation){const d=e.findLast(f=>f.opener);u=`unclosed "\${" expression${d?` opened on line ${d.openedLine}`:""} was never closed`}else u=`"${c.opener}" opened on line ${c.openedLine} is never closed`}return{error:u,commentAndStringRanges:n}}function k_(t){return Na(String(t??"")).error}function ju(t,e){return e.some(({start:n,end:i})=>t>=n&&ttypeof n=="string"?n:n?.errorMessage).filter(Boolean);return e.length>0?e.join("; "):JSON.stringify(t)}return t&&typeof t=="object"?t.errorMessage||JSON.stringify(t):String(t??"")}const C_=["gmail.com","googlemail.com","outlook.com","hotmail.com","live.com","msn.com"],A_="MAGIC_LINK_SENT",P_="PLUS_ALIAS_REJECTED",F_="Please enter your primary email address. Plus aliases (such as {email}) are not allowed for {domain} accounts.",Rs={allowlistedDomains:C_,successCode:A_,validationCode:P_,messageTemplate:F_},R_=new Set(Rs.allowlistedDomains),T_=Rs.successCode,gh=Rs.validationCode;function Ts(t){return typeof t=="string"?t.trim():""}function $_(t){const e=Ts(t),n=e.lastIndexOf("@");if(n<=0||n===e.length-1)return!1;const i=e.slice(0,n),r=e.slice(n+1).toLowerCase();return R_.has(r)?i.includes("+"):!1}function M_(t,e){return Rs.messageTemplate.replaceAll("{email}",t).replaceAll("{domain}",e)}function mh(t){if(!$_(t))return null;const e=Ts(t),n=e.lastIndexOf("@"),i=e.slice(n+1).toLowerCase();return M_(e,i)}function vh(t,e){return t?.code===gh?t.message||mh(e)||"Please enter your primary email address.":t?.code===T_||!t?.code?`Check your email — we sent a link to ${Ts(e)}`:t.message||"Something went wrong. Please try again."}const L_="ccc_auth_session",N_="ccc_subscription",O_=Object.freeze(["hasSeenWalkthrough"]);function B_(t){const e=[];for(const n of O_)t.getItem(n)!==null&&(t.removeItem(n),e.push(n));return e}function D_(){return[L_,N_]}function j_({storage:t,onIdentityChanged:e,onPlanChanged:n}){for(const i of D_())t.removeItem(i);typeof e=="function"&&e(),typeof n=="function"&&n()}function U_({sendLink:t,getEmail:e,onState:n}){let i=!1;return async function(){if(i)return{status:"busy"};i=!0;let s;try{n({status:"pending",error:null});const o=await t(e());return s={status:"sent",data:o},n({status:"sent",data:o}),s}catch(o){return s={status:"error",error:o},n({status:"error",error:o}),s}finally{i=!1}}}const H_=/^dependencies\s*:\s*(?:#.*)?$/,W_=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function $s(t){const e=t.match(W_);return e?e[1]??e[2]??e[3]:null}function cr(t){const e=t.trim();return e===""||e.startsWith("#")}function hi(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function kl(t,e){const n=t.findIndex(s=>e.test(s));if(n===-1)return null;let i=n,r=null;for(let s=n+1;s=0.0.0"}`}function G_(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([u])=>u&&u!=="flutter");if(i.length===0)return{yaml:n,added:[],alreadyPresent:[]};const r=n.split(` +`),s=new Set(yh(n)),o=[],a=[];for(const[u,c]of i)s.has(u)?a.push(u):(o.push([u,c]),s.add(u));if(o.length===0)return{yaml:n,added:[],alreadyPresent:a};const l=Cl(r);if(l){const u=o.map(([c,d])=>Uu(l.childIndent,c,d));r.splice(l.endIndex,0,...u)}else r.length>0&&r[r.length-1].trim()!==""&&r.push(""),r.push("dependencies:"),o.forEach(([u,c])=>{r.push(Uu(" ",u,c))});return{yaml:r.join(` +`),added:o.map(([u])=>u),alreadyPresent:a}}function K_(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([l])=>l&&l!=="flutter");if(i.length===0)return{yaml:n,overridden:[],skipped:[]};const r=n.split(` +`),s=Ls(n),o=[],a=[];for(const[l,u]of i){const c=s.get(l);if(!c||!c.isScalar||!String(u||"").trim()){a.push(l);continue}const d=" ".repeat(hi(r[c.lineIndex]));r[c.lineIndex]=`${d}${l}: ${bh(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:r.join(` +`),overridden:o,skipped:a}}function Eh(t){const e=String(t||""),n=[];return e.trim()?(/^name:\s*\S+/m.test(e)||n.push("pubspec.yaml missing name field"),Cl(e.split(` +`))||n.push("pubspec.yaml missing dependencies section"),yh(e).includes("flutter")||n.push("pubspec.yaml missing Flutter SDK dependency"),{valid:n.length===0,errors:n}):(n.push("pubspec.yaml is empty"),{valid:!1,errors:n})}const Y_=">=3.0.0 <4.0.0";function Oa(t){const e=String(t||"").trim(),n=e[0];return n!=="'"&&n!=='"'||e[e.length-1]!==n?e:e.slice(1,-1).replaceAll(`${n}${n}`,n)}function J_(t=""){const e=Xv(t).filter(n=>!n.startsWith("dart:")&&!n.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function Hu(t,e,n){const i=[];for(const[r,s]of t){if(s.isScalar){e[r]=Oa(s.constraint);continue}if(s.sourceKey==="sdk"){n.add(r);continue}if(s.sourceKey===null&&s.version){e[r]=Oa(s.version);continue}i.push(r)}return i}function Z_(t){const e=new Set,n={},i={},r=Hu(Ls(t),n,e);r.push(...Hu(q_(t,"dependency_overrides"),i,e));const s=new Set([...Object.keys(n),...e]),{sdk:o}=wh(t);return{sdkConstraint:Oa(o)||Y_,dependencies:n,overrides:i,sdkPackages:[...e].sort(),availablePackages:s,unrepresentable:r}}function X_(t,e,n){return e.length>0?`${t} imports ${e.join(", ")}, which FlutterFlow only generates once the app is built, so it could not be compiled before the deploy.`:`${t} imports ${n.join(", ")}, which your project's pubspec.yaml does not declare with a version constraint, so it could not be compiled before the deploy.`}function Q_(t,e){const{sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s,availablePackages:o,unrepresentable:a}=Z_(e),l={sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s},u=[],c=[],d=a.map(h=>`Your project declares ${h} from a source that cannot be reproduced outside it, so the pre-deploy compile check runs against a scratch package graph that omits ${h}. Classes that do not import ${h} directly are still checked, but against that reduced graph, so their transitive package resolution may differ from your project's and the check is approximate for them.`);for(const h of t){const{className:f,content:p}=h,g=Sl(p),m=g.filter(S=>a.includes(S));if(m.length>0){c.push({className:f,reason:`${f} was not compiled before deploying: it imports ${m.join(", ")}, which your project declares from a source that cannot be reproduced outside it, so package resolution could not be matched exactly.`});continue}const{unresolvableImports:v}=J_(p),E=g.filter(S=>!o.has(S));if(v.length>0||E.length>0){c.push({className:f,reason:X_(f,v,E)});continue}u.push({fileName:`${El(f)}.dart`,content:p})}return{manifest:l,sources:u,skipped:c,approximate:d}}function Wu(t,e){const n=`${t}${e}`.split(` +`),i=n.pop()??"",r=[];for(const s of n){const o=Sh(s);o&&r.push(o)}return{events:r,buffer:i}}function ey(t){const e=Sh(t);return e?[e]:[]}function Sh(t){const e=t.trim();if(!e)return null;try{const n=JSON.parse(e);return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}const Le=Object.freeze({COMMITTED:"committed",PARTIAL:"partial",FAILED:"failed",UNCONFIRMED:"unconfirmed"}),xh=12e4,Ih=1e4;function kh(t){return t?.unconfirmed===!0||t?.outcome===Le.UNCONFIRMED?Le.UNCONFIRMED:t?.partial===!0||t?.outcome===Le.PARTIAL?Le.PARTIAL:t?.success===!0?Le.COMMITTED:Le.FAILED}class Qe extends Error{constructor(e){super(e),this.name="UnconfirmedDeployError",this.outcome=Le.UNCONFIRMED}}function zu({httpStatus:t}={}){return new Qe(`Every FlutterFlow sync endpoint lost its response or ended in a server error${t?` (last: HTTP ${t})`:""} — neither can prove the push was refused, so it may already have been applied. Open the FlutterFlow project to reconcile before retrying.`)}async function ty(t,e={}){const{onPhase:n,onLog:i}=e;let r=null,s=null,o="";const a=u=>{if(u.event==="phase"){u.phase&&(s=u.phase),u.message&&n&&n(u.message);return}if(u.event==="log"){u.message&&i&&i(u.message);return}r=u};let l=null;try{if(t.body?.getReader){const u=t.body.getReader(),c=new TextDecoder;for(;;){const{done:d,value:h}=await u.read();if(d)break;const f=Wu(o,c.decode(h,{stream:!0}));o=f.buffer,f.events.forEach(a)}}else{const u=Wu("",await t.text());o=u.buffer,u.events.forEach(a)}}catch(u){l=u}return ey(o).forEach(a),r?{...r,success:r.success===!0||r.success===void 0&&t.ok,finalResultReceived:!0,runnerPhase:s,httpStatus:t.status}:{success:!1,finalResultReceived:!1,httpRejected:!t.ok,httpStatus:t.status,runnerPhase:s,error:t.ok?l?"The connection to the FlutterFlow deploy runner dropped before it reported a result.":"The FlutterFlow deploy runner closed the connection before it finished.":`FlutterFlow custom class provisioning failed (HTTP ${t.status}).`}}const ny=new Set(["connected","workspace_init","workspace_ready","verifying"]);function iy(t){return t?.preWrite===!0||Array.isArray(t?.analyzerErrors)&&t.analyzerErrors.length>0?!0:typeof t?.runnerPhase=="string"?ny.has(t.runnerPhase):typeof t?.httpStatus=="number"?t.httpStatus>=400&&t.httpStatus<500:!1}function qu(t){if(t?.finalResultReceived){const e=kh(t);return e===Le.FAILED&&!iy(t)?Le.UNCONFIRMED:e}return t?.httpRejected?Le.FAILED:Le.UNCONFIRMED}function ry(){let t=document.getElementById("fx-grid");if(!t)return null;const e=window.matchMedia("(prefers-reduced-motion: reduce)"),n=window.matchMedia("(pointer: none)");let i=t.getContext("webgl2",{alpha:!0,antialias:!1,depth:!1,stencil:!1,premultipliedAlpha:!0,powerPreference:"low-power"}),r=i?null:t.getContext("2d");if(!i&&!r)return null;const s='',o=`#version 300 es in vec2 p; void main(){ gl_Position = vec4(p, 0.0, 1.0); }`;function a(){return["#version 300 es","precision highp float;","out vec4 o;","uniform vec2 res;","uniform vec2 design;","uniform vec2 mouse;","uniform float energy;","uniform float parallax;","uniform float t;","uniform vec3 ink;","uniform sampler2D mark;","uniform vec2 rot;","const float WARP_A = 0.0032;","void main(){"," vec2 px = gl_FragCoord.xy * (design / res);"," vec2 p = vec2(px.x, design.y - px.y);"," vec2 off = vec2(0.0, -parallax) + vec2(sin(t * 0.11), cos(t * 0.09)) * 7.0;"," vec2 g = p + off;"," vec2 gm = mouse + off;"," float base = min(design.x, design.y);"," float spacing = clamp(base / 10.0, 64.0, 118.0);"," vec2 rel = g - gm;"," float rho = length(rel) + 1e-5;"," vec2 dir = rel / rho;"," vec2 pw = gm + dir * (rho + WARP_A * rho * rho);"," vec2 cell = floor(pw / spacing);"," vec2 cw = (cell + 0.5) * spacing - gm;"," float Rc = length(cw) + 1e-5;"," float rhoC = (-1.0 + sqrt(1.0 + 4.0 * WARP_A * Rc)) / (2.0 * WARP_A);"," vec2 c = gm + (cw / Rc) * rhoC;"," float cellSize = spacing / (1.0 + 2.0 * WARP_A * rhoC);"," float sigma = spacing * 2.9;"," float f = exp(-(rhoC * rhoC) / (2.0 * sigma * sigma));"," float scale = mix(0.32, 1.42, f);"," float weight = smoothstep(0.06, 0.80, f);"," float hs = cellSize * 0.26 * scale;"," vec2 uv = (g - c) / hs;"," vec2 ruv = mat2(rot.x, rot.y, -rot.y, rot.x) * uv;"," float cov = 0.0;"," if (abs(ruv.x) <= 1.0 && abs(ruv.y) <= 1.0) cov = texture(mark, ruv * 0.5 + 0.5).a;"," float s = cov * weight * energy * 0.26;"," o = vec4(ink * s, s);","}"].join(` -`)}let l=null,u,c,d,f,h,p,g,m,v;function E(Y,W){if(!i)return null;const D=i.createShader(Y);return i.shaderSource(D,W),i.compileShader(D),i.getShaderParameter(D,i.COMPILE_STATUS)?D:(window.console&&console.warn("fx-grid shader: "+i.getShaderInfoLog(D)),null)}if(i){const Y=E(i.VERTEX_SHADER,o),W=E(i.FRAGMENT_SHADER,a());if(Y&&W&&(l=i.createProgram(),i.attachShader(l,Y),i.attachShader(l,W),i.linkProgram(l),i.getProgramParameter(l,i.LINK_STATUS)||(window.console&&console.warn("fx-grid link: "+i.getProgramInfoLog(l)),l=null)),l){i.useProgram(l),i.bindBuffer(i.ARRAY_BUFFER,i.createBuffer()),i.bufferData(i.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),i.STATIC_DRAW);const D=i.getAttribLocation(l,"p");i.enableVertexAttribArray(D),i.vertexAttribPointer(D,2,i.FLOAT,!1,0,0),u=i.getUniformLocation(l,"res"),c=i.getUniformLocation(l,"design"),d=i.getUniformLocation(l,"mouse"),f=i.getUniformLocation(l,"energy"),h=i.getUniformLocation(l,"parallax"),p=i.getUniformLocation(l,"t"),g=i.getUniformLocation(l,"ink"),m=i.getUniformLocation(l,"mark"),v=i.getUniformLocation(l,"rot"),i.enable(i.BLEND),i.blendFunc(i.ONE,i.ONE_MINUS_SRC_ALPHA),i.clearColor(0,0,0,0)}else{i=null;const D=t.cloneNode(!1);if(t.parentNode.replaceChild(D,t),t=D,r=t.getContext("2d"),!r)return null}}function S(Y){if(!Y)return null;const W=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(Y);if(W){let D=W[1];return D.length===3&&(D=D[0]+D[0]+D[1]+D[1]+D[2]+D[2]),[parseInt(D.slice(0,2),16)/255,parseInt(D.slice(2,4),16)/255,parseInt(D.slice(4,6),16)/255]}try{const D=document.createElement("canvas");D.width=1,D.height=1;const ue=D.getContext("2d");ue.fillStyle="rgb(9, 8, 7)";const xe=String(ue.fillStyle);ue.fillStyle=Y;const Fe=String(ue.fillStyle);if(Fe===xe)return null;const dt=/^#([0-9a-f]{6})$/i.exec(Fe);if(dt){const ft=dt[1];return[parseInt(ft.slice(0,2),16)/255,parseInt(ft.slice(2,4),16)/255,parseInt(ft.slice(4,6),16)/255]}const Nt=/rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i.exec(Fe);if(Nt)return[Number(Nt[1])/255,Number(Nt[2])/255,Number(Nt[3])/255]}catch{}return null}function _(){let Y="";try{const W=getComputedStyle(document.documentElement);Y=(W.getPropertyValue("--fx-ink")||"").trim()||(W.getPropertyValue("--fg")||"").trim()}catch{}return S(Y)||[.56,.68,.88]}const b=_();let k=1920,T=1080,x=960,F=540,$=960,O=540,L=.66,N=0,K=-1e9,V=!1,M=0,R=0,Z=null,Ce=!1,oe=!1,ye=!1;const $e=64,ae=15.2;let Ie=0,Se=0;const De=.0032,wt=0,ge=.56,Je=.26,bt=.32,mn=.16,Re=.349;let Pe=wt;function $t(){const Y=t.getBoundingClientRect(),W=t.clientWidth,D=t.clientHeight;if(!Y.width||!W||!D)return;const ue=Math.min(window.devicePixelRatio||1,2),xe=Math.max(.2,Math.min(2,Y.width/W*ue)),Fe=Math.max(2,Math.round(W*xe)),dt=Math.max(2,Math.round(D*xe));(Fe!==t.width||dt!==t.height)&&(t.width=Fe,t.height=dt,i&&i.viewport(0,0,Fe,dt)),k=W,T=D,V||(x=$=k/2,F=O=T/2,V=!0)}function Dn(Y){!l||!Ce||!i||(i.uniform2f(u,t.width,t.height),i.uniform2f(c,k,T),i.uniform2f(d,x,F),i.uniform1f(f,L),i.uniform1f(h,N),i.uniform2f(v,Math.cos(Pe),Math.sin(Pe)),i.uniform1f(p,Y),i.uniform3f(g,b[0],b[1],b[2]),i.clear(i.COLOR_BUFFER_BIT),i.drawArrays(i.TRIANGLES,0,3))}function qe(Y,W,D){const ue=Math.max(0,Math.min(1,(D-Y)/(W-Y)));return ue*ue*(3-2*ue)}function jn(Y){if(!Z||!r)return;const W=r;W.setTransform(1,0,0,1,0,0),W.clearRect(0,0,t.width,t.height);const D=t.width/k;W.setTransform(D,0,0,D,0,0),W.globalAlpha=1;const ue=Math.min(k,T),xe=Math.max(64,Math.min(118,ue/10)),Fe=xe*2.9,dt=2*Fe*Fe,Nt=Math.sin(Y*.11)*7,ft=Math.cos(Y*.09)*7-N,dr=x+Nt,fr=F+ft,no=Fe*Math.sqrt(2*Math.log(1/.06)),vi=no+De*no*no+xe,Rp=Math.floor((dr-vi)/xe)-1,Tp=Math.ceil((dr+vi)/xe)+1,$p=Math.floor((fr-vi)/xe)-1,Mp=Math.ceil((fr+vi)/xe)+1;for(let io=$p;io<=Mp;io++){const Lp=(io+.5)*xe;for(let ro=Rp;ro<=Tp;ro++){const so=(ro+.5)*xe-dr,oo=Lp-fr,ao=Math.sqrt(so*so+oo*oo)+1e-5;if(ao>vi)continue;const hr=(-1+Math.sqrt(1+4*De*ao))/(2*De),cc=Math.exp(-(hr*hr)/dt),uc=qe(.06,.8,cc)*L*.26;if(uc<.004)continue;const on=xe/(1+2*De*hr)*.26*(.32+1.1*cc),dc=hr/ao,lo=dr+so*dc,co=fr+oo*dc;lo<-on*1.6||lo>k+on*1.6||co<-on*1.6||co>T+on*1.6||(W.globalAlpha=uc,W.save(),W.translate(lo,co),W.rotate(Pe),W.drawImage(Z,-on,-on,on*2,on*2),W.restore())}}W.globalAlpha=1}function Mt(Y){if(!oe)return;const W=R?Math.min(.05,(Y-R)/1e3):.016;R=Y;const ue=Y-K>2400?.6:1;L+=(ue-L)*Math.min(1,W*3.2);const xe=Math.min(.05,W);Ie+=(($-x)*$e-Ie*ae)*xe,Se+=((O-F)*$e-Se*ae)*xe,x+=Ie*xe,F+=Se*xe,N=(window.scrollY||window.pageYOffset||0)*.55;const Fe=Y/1e3,dt=x/(k||1)-.5,Nt=F/(T||1)-.5;let ft=dt*(dt>=0?ge:Je)+Nt*(Nt>=0?bt:mn);ft>Re?ft=Re:ft<-Re&&(ft=-Re),Pe=wt+ft-N*6e-4,$t(),i?Dn(Fe):jn(Fe),M=requestAnimationFrame(Mt)}function Lt(Y){if(!oe)return;const W=t.getBoundingClientRect();!W.width||!k||!T||($=(Y.clientX-W.left)/W.width*k,O=(Y.clientY-W.top)/W.height*T,K=performance.now())}function ut(){oe||to||e.matches||n.matches||!ye||document.hidden||(oe=!0,R=0,M=requestAnimationFrame(Mt))}function sn(){oe=!1,M&&(cancelAnimationFrame(M),M=0),R=0}function mi(){e.matches?(sn(),t.classList.remove("is-ready")):ye&&ut()}function Un(){n.matches?sn():ye&&ut()}function oc(){document.hidden?sn():ye&&ut()}const ac=new IntersectionObserver(Y=>{ye=Y[0]?.isIntersecting||!1,ye?ut():sn()},{threshold:0});ac.observe(t),window.addEventListener("pointermove",Lt,{passive:!0,capture:!0}),window.addEventListener("resize",$t),e.addEventListener("change",mi),n.addEventListener("change",Un),document.addEventListener("visibilitychange",oc);function Fp(){const Y=(s.match(/\sd="([^"]+)"/)||[])[1],W=document.createElement("canvas");W.width=256,W.height=256;const D=W.getContext("2d");if(Y&&window.Path2D){const ue=Math.min(8.533333333333333,8.421052631578947);D.setTransform(ue,0,0,ue,ue+(256-30*ue)/2,-6.4*ue),D.fillStyle="rgb(255,255,255)",D.fill(new Path2D(Y),"evenodd"),D.setTransform(1,0,0,1,0,0)}try{const ue=D.getImageData(0,0,256,256),xe=ue.data;for(let Fe=3;Feoe}}const ry=120;function sy(t,e,n){return tn?n:t}function de(t,e,n){return sy((t-e)/(n-e),0,1)}function oy(t){return t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2}function Uo(t){return 1-Math.pow(1-t,3)}function Ve(t,e){return e=e===void 0?1.7:e,1+(e+1)*Math.pow(t-1,3)+e*Math.pow(t-1,2)}function zu(t){return 1-Math.pow(2,-9*t)*Math.cos(t*15)}function te(t,e){if(t<=e[0].t)return e[0].v;for(let n=1;n8.2&&_<9.4&&(s*=1-.07*Math.sin(de(_,8.2,9.4)*Math.PI))}else if(t<53){const _=t-42;g=te(_,[{t:0,v:1},{t:2,v:0},{t:4.2,v:0},{t:4.6,v:1},{t:6.8,v:1},{t:7.4,v:0},{t:9.4,v:0},{t:10.6,v:1}]),p=te(_,[{t:0,v:1},{t:2,v:.3},{t:4.6,v:1,e:Ve}]),d=te(_,[{t:0,v:0},{t:2,v:.3},{t:4.6,v:.16,e:Ve},{t:10.6,v:0}]),h=te(_,[{t:0,v:0},{t:2,v:-40},{t:4.6,v:0,e:Ve}]),o=te(_,[{t:0,v:0},{t:4.6,v:-.12},{t:10.6,v:0}])}else if(t<60){const _=t-53;c=te(_,[{t:0,v:1},{t:.35,v:0},{t:.45,v:0},{t:.7,v:1}]);const b=de(_,.45,2.2);a=b>0?-2.6*(1-zu(b)):0,g=te(_,[{t:0,v:1},{t:.57,v:0},{t:.67,v:0},{t:.92,v:1}]);const k=de(_,.67,2.42);f=k>0?-2.6*(1-zu(k)):0,s=1-.05*(Math.sin(de(_,1.9,2.5)*Math.PI)+Math.sin(de(_,2.5,3.1)*Math.PI))}else if(t<74){let b=function(F){return[te(F,[{t:0,v:0},{t:.25,v:1},{t:.5,v:1},{t:.72,v:.14},{t:.82,v:.14},{t:1,v:0}]),te(F,[{t:0,v:0},{t:.08,v:-.62},{t:.25,v:-.62},{t:.33,v:.62},{t:.7,v:.62},{t:.82,v:-.62},{t:1,v:-.62}])]};var S=b;const _=t-60,k=1-de(_,12,14),T=b(de(_,0,12)),x=b(de(_-.5,0,12));n=T[0]*k,i=(T[1]+.05*Math.sin(_*7))*k,o=(x[0]-T[0])*.6*k,a=(x[1]-T[1])*.6*k,h=(x[0]-T[0])*30*k,E=de(_,0,.4)*k}else if(t<85.4){const _=t-74,b=te(_,[{t:0,v:0},{t:4,v:1},{t:8,v:.24},{t:9.6,v:1,e:Ve},{t:11.4,v:0}]);o=b*.5,d=-b*.5,l=te(_,[{t:0,v:0},{t:4,v:6},{t:8,v:20},{t:9.6,v:38,e:Ve},{t:11.4,v:0}]),h=-l*.7,a=te(_,[{t:0,v:0},{t:8,v:0},{t:9.6,v:.4},{t:11.4,v:0}])}else if(t<96.4){const _=t-85.4,b=de(_,0,5.6),k=de(_,5.6,7.6),T=.72*Math.min(1,_/.6)*(1-k);d=Math.cos(b*Math.PI*2)*T,f=Math.sin(b*Math.PI*2)*T*.55,h=b*360*(1-k);const x=te(_,[{t:0,v:0},{t:7.6,v:0},{t:8.2,v:1,e:Uo},{t:8.6,v:.55},{t:9.4,v:0}]);o=-.16*x,d+=.16*x,l=-6*x,h+=6*x,s=1+.05*x,m=1+.9*x}else if(t<108.6){const _=t-96.4,b=de(_,9.6,12.2);n=te(_,[{t:0,v:0},{t:2.1,v:1},{t:4.8,v:.08},{t:7.5,v:1},{t:9.6,v:0}])*(1-b),i=-.35*Math.abs(Math.sin(de(_,0,9.6)*Math.PI*3))*(1-b);const k=Math.sin(_*6.2)*(1-b);u=1+.12*k,p=1-.12*k,l=k*8,h=-k*8,o=.06*k,d=-.06*k,E=de(_,0,.4)*(1-b)}else{const _=t-108.6,b=Math.sin(de(_,0,8)*Math.PI),k=1-de(_,8,11.4);s=1+.04*b*k,i=-.1*b*k,r=2*b*k,m=1+.5*Math.sin(de(_,0,6)*Math.PI),v=1+.1*Math.sin(de(_,0,6)*Math.PI)}return e.x=n,e.y=i,e.rot=r,e.scale=s,e.ax=o,e.ay=a,e.ar=l,e.asc=u,e.afade=c,e.bx=d,e.by=f,e.br=h,e.bsc=p,e.bfade=g,e.hfade=m,e.hsc=v,e.shd=E,e}function ay(t={}){const e=t.arena||document.querySelector(".pipeline-glyph.logo-loop");if(!e)return null;const n=e.querySelector(".loop-mark"),i=e.querySelector(".loop-piece-a"),r=e.querySelector(".loop-piece-b"),s=e.querySelector(".loop-halo"),o=e.querySelector(".loop-shadow");if(!n||!i||!r||!s||!o)return null;const a=t.reducedMotion||window.matchMedia("(prefers-reduced-motion: reduce)"),l=ry;let u=34,c=0,d=0;function f(){u=n.offsetWidth||34,c=Math.max(0,e.offsetWidth-u-4),d=Math.max(0,(e.offsetHeight-u)/2-2),e.style.setProperty("--mark-c",u/2+"px")}function h(M){const R=Math.min(1,Math.max(0,M.x))*c,Z=M.y*d;n.style.transform="translate3d("+R.toFixed(2)+"px,"+Z.toFixed(2)+"px,0) rotate("+M.rot.toFixed(2)+"deg) scale("+M.scale.toFixed(3)+")",i.style.transform="translate3d("+(M.ax*u).toFixed(2)+"px,"+(M.ay*u).toFixed(2)+"px,0) rotate("+M.ar.toFixed(2)+"deg) scale("+M.asc.toFixed(3)+")",i.style.opacity=M.afade.toFixed(3),r.style.transform="translate3d("+(M.bx*u).toFixed(2)+"px,"+(M.by*u).toFixed(2)+"px,0) rotate("+M.br.toFixed(2)+"deg) scale("+M.bsc.toFixed(3)+")",r.style.opacity=M.bfade.toFixed(3),s.style.transform="scale("+M.hsc.toFixed(3)+")",s.style.opacity=(.09*M.hfade).toFixed(3),o.style.transform="translateX("+R.toFixed(2)+"px) scaleX("+(.75+.4*Math.abs(M.x)).toFixed(3)+")",o.style.opacity=(M.shd*.5).toFixed(3)}let p=0,g=0,m=0,v=!1,E=!1,S=!1,_=0;function b(){return S||a.matches||document.hidden||!e.offsetParent?!1:E}function k(M){if(!v)return;if(m=requestAnimationFrame(k),!b()){x();return}const R=g?(M-g)/1e3:0;g=M,p=(p+Math.min(R,.1))%l,_+=1,h(Pi(p))}function T(){v||S||b()&&(v=!0,g=0,m=requestAnimationFrame(k))}function x(){v=!1,m&&(cancelAnimationFrame(m),m=0),g=0}function F(){b()?T():x()}function $(){a.matches?(x(),h(Pi(0))):F()}function O(){f(),v&&h(Pi(p))}function L(){g=0,F()}const N=new IntersectionObserver(M=>{E=M[0]?M[0].isIntersecting:!1,F()},{threshold:0});N.observe(e),window.addEventListener("resize",O),a.addEventListener("change",$),document.addEventListener("visibilitychange",L);function K(){S||(S=!0,x(),N.disconnect(),window.removeEventListener("resize",O),a.removeEventListener("change",$),document.removeEventListener("visibilitychange",L))}window.addEventListener("pagehide",K);function V(M){p=(M%l+l)%l,h(Pi(p))}return f(),h(Pi(0)),F(),{isRunning:()=>v,currentTime:()=>p,frameCount:()=>_,seek:V,dispose:K}}const ly=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function Xt(t){const e=String(t||"").trim().match(ly);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function cy(t,e){if(t.length===0&&e.length===0)return 0;if(t.length===0)return 1;if(e.length===0)return-1;for(let n=0;n0)}function dy(t){const e=Xt(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function kl(t){let e=String(t??"").trim();if((e.startsWith("'")||e.startsWith('"'))&&(e=e.slice(1,-1).trim()),e===""||e==="any"||e==="*")return{min:null,minInclusive:!1,max:null,maxInclusive:!1};if(e.startsWith("^")){const o=e.slice(1).trim();return Xt(o)?{min:o,minInclusive:!0,max:dy(o),maxInclusive:!1}:null}if(Xt(e))return{min:e,minInclusive:!0,max:e,maxInclusive:!0};const n={min:null,minInclusive:!1,max:null,maxInclusive:!1},i=/(>=|<=|>|<)\s*([0-9][0-9A-Za-z.+-]*)/g;let r=!1,s;for(;(s=i.exec(e))!==null;){const[,o,a]=s;if(!Xt(a))return null;r=!0,o===">="||o===">"?(n.min=a,n.minInclusive=o===">="):(n.max=a,n.maxInclusive=o==="<=")}return r?n:null}function qu(t,e){const n=kl(t);if(!n||!Xt(e))return!1;if(n.min!==null){const i=fs(e,n.min);if(i<0||i===0&&!n.minInclusive)return!1}if(n.max!==null){const i=fs(e,n.max);if(i>0||i===0&&!n.maxInclusive)return!1}return!0}function fy(t,e){const n=kl(t);if(!n||!Xt(e))return!1;if(n.max===null)return!0;const i=fs(n.max,e);return i>0?!0:i===0&&n.maxInclusive}function Vn(t){const e=kl(t);return e?e.min:null}const hy="https://pub.dev/api/packages/",py=8e3;function gy(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null}=e,r=Array.isArray(t?.versions)?t.versions:[];let s=null;for(const o of r){const a=o?.version;if(!a||o.retracted||uy(a))continue;const l=o.pubspec?.environment||{};n&&l.sdk&&!qu(l.sdk,n)||i&&l.flutter&&!qu(l.flutter,i)||(!s||fs(a,s)>0)&&(s=a)}return s?{version:s,constraint:`^${s}`}:null}async function my(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null,fetchImpl:r=fetch}=e;let s;try{const a=await r(`${hy}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(py)});if(!a.ok)return{name:t,constraint:null,version:null,error:a.status===404?`"${t}" was not found on pub.dev`:`pub.dev returned ${a.status} for "${t}"`};s=await a.json()}catch(a){return{name:t,constraint:null,version:null,error:`could not reach pub.dev for "${t}" (${a.message})`}}const o=gy(s,{dartSdkFloor:n,flutterSdkFloor:i});return o?{name:t,...o,error:null}:{name:t,constraint:null,version:null,error:n?`no published "${t}" release supports Dart ${n}`:`no published "${t}" release could be read`}}async function vy(t,e={}){const n=await Promise.all(t.map(i=>my(i,e)));return new Map(n.map(({name:i,...r})=>[i,r]))}async function _y(t,e={},n={}){const{resolveVersions:i=vy}=n,r=Object.entries(e).filter(([c])=>c&&c!=="flutter"),s=_h(t),o={dartSdkFloor:Vn(s.sdk),flutterSdkFloor:Vn(s.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(r.length===0)return a;const l=$s(t),u=[];for(const[c,d]of r){const f=l.get(c);if(!f){u.push(c);continue}const h=Vn(d);if(!h){a.kept.push({name:c,constraint:f.constraint});continue}if(!f.isScalar){a.warnings.push(`"${c}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${h}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:c,constraint:f.constraint});continue}if(fy(f.constraint,h)){a.kept.push({name:c,constraint:f.constraint});continue}a.overrides[c]=`^${h}`,a.warnings.push(`"${c}" was pinned to ${f.constraint} in your project, which cannot resolve the ${h} the generated code needs. Raising it to ^${h} — this changes a dependency the rest of your app also uses.`)}if(u.length>0){const c=await i(u,o);for(const d of u){const f=c.get(d);if(f?.constraint){a.additions[d]=f.constraint;continue}const h=e[d]||"";if(Vn(h)){a.additions[d]=`^${Vn(h)}`,a.warnings.push(`Could not confirm "${d}" version on pub.dev (${f?.error||"lookup failed"}). Using ^${Vn(h)} from the AI's recommendation — verify this is current.`);continue}a.additions[d]=">=0.0.0",a.warnings.push(`Could not determine a version for "${d}" (${f?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const yy={"&":"&","<":"<",">":">",'"':""","'":"'"};function Qt(t){return String(t??"").replace(/[&<>"']/g,e=>yy[e])}function z(t){return t?Qt(t).replace(/\n/g,"
      "):""}function Jt(t){return Qt(t).replace(/\r?\n/g," ")}function Ms(t,e={}){const n=t?.pipelineStep;if(n!=null&&e[n]!=null)return e[n];const i=t?.message||"";return i.includes("Code Generator")?2:i.includes("Code Review")?3:1}function kh(t){if(!t)return{kind:"generic",title:"Generation failed",message:"An unknown error occurred. Please try again.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1};if(t.isModelArmor){const n=t.code==="MODEL_ARMOR_BLOCKED";return{kind:"safety",title:t.userTitle||"Request blocked for safety",message:t.userMessage||t.message,detail:t.retryExplanation||"",canRetry:!n,canEdit:!0,canUpgrade:!1}}if(t.isUsageLimit)return{kind:"quota",title:"Monthly limit reached",message:t.message||"You've used all your generations for this period.",detail:"",canRetry:!1,canEdit:!1,canUpgrade:!0};const e=t.message||"";return/timed out after/i.test(e)?{kind:"timeout",title:"Request timed out",message:"The generation service took too long to respond.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:/unreachable|failed to fetch|load failed|cors/i.test(e)?{kind:"network",title:"Connection problem",message:"We couldn't reach the generation service. Check your connection and try again.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:{kind:"generic",title:"Generation failed",message:e||"An unexpected error occurred.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1}}function wy(t){const e={"Integration Audit Report":"📋","Critical Issues":"❌",Warnings:"⚠️",Recommendations:"✅","Overall Score":"📊"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📄"}function by(t){const e={critical:"❌",warning:"⚠️",recommendation:"✅",score:"📊",issue:"🔍",fix:"🔧"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📝"}function Ey(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 ci(t){if(!t)return"";if(typeof t!="string")return String(t);const e=/```(?:\w+)?\n?([\s\S]*?)```/,n=t.match(e);return n?n[1].trim():t.trim()}function Vu(t){return t=Qt(t),t=t.replace(/\*\*(.*?)\*\*/g,'$1'),t=t.replace(/\*(.*?)\*/g,'$1'),t=t.replace(/`(.*?)`/g,'$1'),t=t.replace(/\b(FAIL|ERROR|CRITICAL)\b/g,'$1'),t=t.replace(/\b(WARN|WARNING)\b/g,'$1'),t=t.replace(/\b(PASS|SUCCESS|OK)\b/g,'$1'),t}function Ch(t,e="dart",n=globalThis.hljs){if(!t)return"";const i=ci(t);try{return n.highlight(i,{language:e}).value}catch(r){console.warn("Syntax highlighting failed:",r);try{return n.highlight(i,{language:"json"}).value}catch{return Qt(i)}}}function Ls(t,e={}){const{highlighter:n=globalThis.hljs}=e;let i='
      ';const r=String(t??"").split(` -`);let s=!1,o="";for(const a of r){if(a.startsWith("```")){if(s){const l=Ey(o),u=Ch(o.trim(),l,n);i+=`
      +`)}let l=null,u,c,d,h,f,p,g,m,v;function E(Y,W){if(!i)return null;const D=i.createShader(Y);return i.shaderSource(D,W),i.compileShader(D),i.getShaderParameter(D,i.COMPILE_STATUS)?D:(window.console&&console.warn("fx-grid shader: "+i.getShaderInfoLog(D)),null)}if(i){const Y=E(i.VERTEX_SHADER,o),W=E(i.FRAGMENT_SHADER,a());if(Y&&W&&(l=i.createProgram(),i.attachShader(l,Y),i.attachShader(l,W),i.linkProgram(l),i.getProgramParameter(l,i.LINK_STATUS)||(window.console&&console.warn("fx-grid link: "+i.getProgramInfoLog(l)),l=null)),l){i.useProgram(l),i.bindBuffer(i.ARRAY_BUFFER,i.createBuffer()),i.bufferData(i.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),i.STATIC_DRAW);const D=i.getAttribLocation(l,"p");i.enableVertexAttribArray(D),i.vertexAttribPointer(D,2,i.FLOAT,!1,0,0),u=i.getUniformLocation(l,"res"),c=i.getUniformLocation(l,"design"),d=i.getUniformLocation(l,"mouse"),h=i.getUniformLocation(l,"energy"),f=i.getUniformLocation(l,"parallax"),p=i.getUniformLocation(l,"t"),g=i.getUniformLocation(l,"ink"),m=i.getUniformLocation(l,"mark"),v=i.getUniformLocation(l,"rot"),i.enable(i.BLEND),i.blendFunc(i.ONE,i.ONE_MINUS_SRC_ALPHA),i.clearColor(0,0,0,0)}else{i=null;const D=t.cloneNode(!1);if(t.parentNode.replaceChild(D,t),t=D,r=t.getContext("2d"),!r)return null}}function S(Y){if(!Y)return null;const W=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(Y);if(W){let D=W[1];return D.length===3&&(D=D[0]+D[0]+D[1]+D[1]+D[2]+D[2]),[parseInt(D.slice(0,2),16)/255,parseInt(D.slice(2,4),16)/255,parseInt(D.slice(4,6),16)/255]}try{const D=document.createElement("canvas");D.width=1,D.height=1;const ue=D.getContext("2d");ue.fillStyle="rgb(9, 8, 7)";const xe=String(ue.fillStyle);ue.fillStyle=Y;const Fe=String(ue.fillStyle);if(Fe===xe)return null;const dt=/^#([0-9a-f]{6})$/i.exec(Fe);if(dt){const ft=dt[1];return[parseInt(ft.slice(0,2),16)/255,parseInt(ft.slice(2,4),16)/255,parseInt(ft.slice(4,6),16)/255]}const Nt=/rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i.exec(Fe);if(Nt)return[Number(Nt[1])/255,Number(Nt[2])/255,Number(Nt[3])/255]}catch{}return null}function _(){let Y="";try{const W=getComputedStyle(document.documentElement);Y=(W.getPropertyValue("--fx-ink")||"").trim()||(W.getPropertyValue("--fg")||"").trim()}catch{}return S(Y)||[.56,.68,.88]}const b=_();let k=1920,T=1080,x=960,F=540,$=960,O=540,L=.66,N=0,K=-1e9,V=!1,M=0,R=0,Z=null,Ce=!1,oe=!1,ye=!1;const $e=64,ae=15.2;let Ie=0,Se=0;const De=.0032,wt=0,ge=.56,Je=.26,bt=.32,mn=.16,Re=.349;let Pe=wt;function $t(){const Y=t.getBoundingClientRect(),W=t.clientWidth,D=t.clientHeight;if(!Y.width||!W||!D)return;const ue=Math.min(window.devicePixelRatio||1,2),xe=Math.max(.2,Math.min(2,Y.width/W*ue)),Fe=Math.max(2,Math.round(W*xe)),dt=Math.max(2,Math.round(D*xe));(Fe!==t.width||dt!==t.height)&&(t.width=Fe,t.height=dt,i&&i.viewport(0,0,Fe,dt)),k=W,T=D,V||(x=$=k/2,F=O=T/2,V=!0)}function Dn(Y){!l||!Ce||!i||(i.uniform2f(u,t.width,t.height),i.uniform2f(c,k,T),i.uniform2f(d,x,F),i.uniform1f(h,L),i.uniform1f(f,N),i.uniform2f(v,Math.cos(Pe),Math.sin(Pe)),i.uniform1f(p,Y),i.uniform3f(g,b[0],b[1],b[2]),i.clear(i.COLOR_BUFFER_BIT),i.drawArrays(i.TRIANGLES,0,3))}function qe(Y,W,D){const ue=Math.max(0,Math.min(1,(D-Y)/(W-Y)));return ue*ue*(3-2*ue)}function jn(Y){if(!Z||!r)return;const W=r;W.setTransform(1,0,0,1,0,0),W.clearRect(0,0,t.width,t.height);const D=t.width/k;W.setTransform(D,0,0,D,0,0),W.globalAlpha=1;const ue=Math.min(k,T),xe=Math.max(64,Math.min(118,ue/10)),Fe=xe*2.9,dt=2*Fe*Fe,Nt=Math.sin(Y*.11)*7,ft=Math.cos(Y*.09)*7-N,hr=x+Nt,pr=F+ft,ro=Fe*Math.sqrt(2*Math.log(1/.06)),vi=ro+De*ro*ro+xe,Tp=Math.floor((hr-vi)/xe)-1,$p=Math.ceil((hr+vi)/xe)+1,Mp=Math.floor((pr-vi)/xe)-1,Lp=Math.ceil((pr+vi)/xe)+1;for(let so=Mp;so<=Lp;so++){const Np=(so+.5)*xe;for(let oo=Tp;oo<=$p;oo++){const ao=(oo+.5)*xe-hr,lo=Np-pr,co=Math.sqrt(ao*ao+lo*lo)+1e-5;if(co>vi)continue;const gr=(-1+Math.sqrt(1+4*De*co))/(2*De),dc=Math.exp(-(gr*gr)/dt),fc=qe(.06,.8,dc)*L*.26;if(fc<.004)continue;const on=xe/(1+2*De*gr)*.26*(.32+1.1*dc),hc=gr/co,uo=hr+ao*hc,fo=pr+lo*hc;uo<-on*1.6||uo>k+on*1.6||fo<-on*1.6||fo>T+on*1.6||(W.globalAlpha=fc,W.save(),W.translate(uo,fo),W.rotate(Pe),W.drawImage(Z,-on,-on,on*2,on*2),W.restore())}}W.globalAlpha=1}function Mt(Y){if(!oe)return;const W=R?Math.min(.05,(Y-R)/1e3):.016;R=Y;const ue=Y-K>2400?.6:1;L+=(ue-L)*Math.min(1,W*3.2);const xe=Math.min(.05,W);Ie+=(($-x)*$e-Ie*ae)*xe,Se+=((O-F)*$e-Se*ae)*xe,x+=Ie*xe,F+=Se*xe,N=(window.scrollY||window.pageYOffset||0)*.55;const Fe=Y/1e3,dt=x/(k||1)-.5,Nt=F/(T||1)-.5;let ft=dt*(dt>=0?ge:Je)+Nt*(Nt>=0?bt:mn);ft>Re?ft=Re:ft<-Re&&(ft=-Re),Pe=wt+ft-N*6e-4,$t(),i?Dn(Fe):jn(Fe),M=requestAnimationFrame(Mt)}function Lt(Y){if(!oe)return;const W=t.getBoundingClientRect();!W.width||!k||!T||($=(Y.clientX-W.left)/W.width*k,O=(Y.clientY-W.top)/W.height*T,K=performance.now())}function ut(){oe||io||e.matches||n.matches||!ye||document.hidden||(oe=!0,R=0,M=requestAnimationFrame(Mt))}function sn(){oe=!1,M&&(cancelAnimationFrame(M),M=0),R=0}function mi(){e.matches?(sn(),t.classList.remove("is-ready")):ye&&ut()}function Un(){n.matches?sn():ye&&ut()}function lc(){document.hidden?sn():ye&&ut()}const cc=new IntersectionObserver(Y=>{ye=Y[0]?.isIntersecting||!1,ye?ut():sn()},{threshold:0});cc.observe(t),window.addEventListener("pointermove",Lt,{passive:!0,capture:!0}),window.addEventListener("resize",$t),e.addEventListener("change",mi),n.addEventListener("change",Un),document.addEventListener("visibilitychange",lc);function Rp(){const Y=(s.match(/\sd="([^"]+)"/)||[])[1],W=document.createElement("canvas");W.width=256,W.height=256;const D=W.getContext("2d");if(Y&&window.Path2D){const ue=Math.min(8.533333333333333,8.421052631578947);D.setTransform(ue,0,0,ue,ue+(256-30*ue)/2,-6.4*ue),D.fillStyle="rgb(255,255,255)",D.fill(new Path2D(Y),"evenodd"),D.setTransform(1,0,0,1,0,0)}try{const ue=D.getImageData(0,0,256,256),xe=ue.data;for(let Fe=3;Feoe}}const sy=120;function oy(t,e,n){return tn?n:t}function de(t,e,n){return oy((t-e)/(n-e),0,1)}function ay(t){return t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2}function Wo(t){return 1-Math.pow(1-t,3)}function Ve(t,e){return e=e===void 0?1.7:e,1+(e+1)*Math.pow(t-1,3)+e*Math.pow(t-1,2)}function Vu(t){return 1-Math.pow(2,-9*t)*Math.cos(t*15)}function te(t,e){if(t<=e[0].t)return e[0].v;for(let n=1;n8.2&&_<9.4&&(s*=1-.07*Math.sin(de(_,8.2,9.4)*Math.PI))}else if(t<53){const _=t-42;g=te(_,[{t:0,v:1},{t:2,v:0},{t:4.2,v:0},{t:4.6,v:1},{t:6.8,v:1},{t:7.4,v:0},{t:9.4,v:0},{t:10.6,v:1}]),p=te(_,[{t:0,v:1},{t:2,v:.3},{t:4.6,v:1,e:Ve}]),d=te(_,[{t:0,v:0},{t:2,v:.3},{t:4.6,v:.16,e:Ve},{t:10.6,v:0}]),f=te(_,[{t:0,v:0},{t:2,v:-40},{t:4.6,v:0,e:Ve}]),o=te(_,[{t:0,v:0},{t:4.6,v:-.12},{t:10.6,v:0}])}else if(t<60){const _=t-53;c=te(_,[{t:0,v:1},{t:.35,v:0},{t:.45,v:0},{t:.7,v:1}]);const b=de(_,.45,2.2);a=b>0?-2.6*(1-Vu(b)):0,g=te(_,[{t:0,v:1},{t:.57,v:0},{t:.67,v:0},{t:.92,v:1}]);const k=de(_,.67,2.42);h=k>0?-2.6*(1-Vu(k)):0,s=1-.05*(Math.sin(de(_,1.9,2.5)*Math.PI)+Math.sin(de(_,2.5,3.1)*Math.PI))}else if(t<74){let b=function(F){return[te(F,[{t:0,v:0},{t:.25,v:1},{t:.5,v:1},{t:.72,v:.14},{t:.82,v:.14},{t:1,v:0}]),te(F,[{t:0,v:0},{t:.08,v:-.62},{t:.25,v:-.62},{t:.33,v:.62},{t:.7,v:.62},{t:.82,v:-.62},{t:1,v:-.62}])]};var S=b;const _=t-60,k=1-de(_,12,14),T=b(de(_,0,12)),x=b(de(_-.5,0,12));n=T[0]*k,i=(T[1]+.05*Math.sin(_*7))*k,o=(x[0]-T[0])*.6*k,a=(x[1]-T[1])*.6*k,f=(x[0]-T[0])*30*k,E=de(_,0,.4)*k}else if(t<85.4){const _=t-74,b=te(_,[{t:0,v:0},{t:4,v:1},{t:8,v:.24},{t:9.6,v:1,e:Ve},{t:11.4,v:0}]);o=b*.5,d=-b*.5,l=te(_,[{t:0,v:0},{t:4,v:6},{t:8,v:20},{t:9.6,v:38,e:Ve},{t:11.4,v:0}]),f=-l*.7,a=te(_,[{t:0,v:0},{t:8,v:0},{t:9.6,v:.4},{t:11.4,v:0}])}else if(t<96.4){const _=t-85.4,b=de(_,0,5.6),k=de(_,5.6,7.6),T=.72*Math.min(1,_/.6)*(1-k);d=Math.cos(b*Math.PI*2)*T,h=Math.sin(b*Math.PI*2)*T*.55,f=b*360*(1-k);const x=te(_,[{t:0,v:0},{t:7.6,v:0},{t:8.2,v:1,e:Wo},{t:8.6,v:.55},{t:9.4,v:0}]);o=-.16*x,d+=.16*x,l=-6*x,f+=6*x,s=1+.05*x,m=1+.9*x}else if(t<108.6){const _=t-96.4,b=de(_,9.6,12.2);n=te(_,[{t:0,v:0},{t:2.1,v:1},{t:4.8,v:.08},{t:7.5,v:1},{t:9.6,v:0}])*(1-b),i=-.35*Math.abs(Math.sin(de(_,0,9.6)*Math.PI*3))*(1-b);const k=Math.sin(_*6.2)*(1-b);u=1+.12*k,p=1-.12*k,l=k*8,f=-k*8,o=.06*k,d=-.06*k,E=de(_,0,.4)*(1-b)}else{const _=t-108.6,b=Math.sin(de(_,0,8)*Math.PI),k=1-de(_,8,11.4);s=1+.04*b*k,i=-.1*b*k,r=2*b*k,m=1+.5*Math.sin(de(_,0,6)*Math.PI),v=1+.1*Math.sin(de(_,0,6)*Math.PI)}return e.x=n,e.y=i,e.rot=r,e.scale=s,e.ax=o,e.ay=a,e.ar=l,e.asc=u,e.afade=c,e.bx=d,e.by=h,e.br=f,e.bsc=p,e.bfade=g,e.hfade=m,e.hsc=v,e.shd=E,e}function ly(t={}){const e=t.arena||document.querySelector(".pipeline-glyph.logo-loop");if(!e)return null;const n=e.querySelector(".loop-mark"),i=e.querySelector(".loop-piece-a"),r=e.querySelector(".loop-piece-b"),s=e.querySelector(".loop-halo"),o=e.querySelector(".loop-shadow");if(!n||!i||!r||!s||!o)return null;const a=t.reducedMotion||window.matchMedia("(prefers-reduced-motion: reduce)"),l=sy;let u=34,c=0,d=0;function h(){u=n.offsetWidth||34,c=Math.max(0,e.offsetWidth-u-4),d=Math.max(0,(e.offsetHeight-u)/2-2),e.style.setProperty("--mark-c",u/2+"px")}function f(M){const R=Math.min(1,Math.max(0,M.x))*c,Z=M.y*d;n.style.transform="translate3d("+R.toFixed(2)+"px,"+Z.toFixed(2)+"px,0) rotate("+M.rot.toFixed(2)+"deg) scale("+M.scale.toFixed(3)+")",i.style.transform="translate3d("+(M.ax*u).toFixed(2)+"px,"+(M.ay*u).toFixed(2)+"px,0) rotate("+M.ar.toFixed(2)+"deg) scale("+M.asc.toFixed(3)+")",i.style.opacity=M.afade.toFixed(3),r.style.transform="translate3d("+(M.bx*u).toFixed(2)+"px,"+(M.by*u).toFixed(2)+"px,0) rotate("+M.br.toFixed(2)+"deg) scale("+M.bsc.toFixed(3)+")",r.style.opacity=M.bfade.toFixed(3),s.style.transform="scale("+M.hsc.toFixed(3)+")",s.style.opacity=(.09*M.hfade).toFixed(3),o.style.transform="translateX("+R.toFixed(2)+"px) scaleX("+(.75+.4*Math.abs(M.x)).toFixed(3)+")",o.style.opacity=(M.shd*.5).toFixed(3)}let p=0,g=0,m=0,v=!1,E=!1,S=!1,_=0;function b(){return S||a.matches||document.hidden||!e.offsetParent?!1:E}function k(M){if(!v)return;if(m=requestAnimationFrame(k),!b()){x();return}const R=g?(M-g)/1e3:0;g=M,p=(p+Math.min(R,.1))%l,_+=1,f(Pi(p))}function T(){v||S||b()&&(v=!0,g=0,m=requestAnimationFrame(k))}function x(){v=!1,m&&(cancelAnimationFrame(m),m=0),g=0}function F(){b()?T():x()}function $(){a.matches?(x(),f(Pi(0))):F()}function O(){h(),v&&f(Pi(p))}function L(){g=0,F()}const N=new IntersectionObserver(M=>{E=M[0]?M[0].isIntersecting:!1,F()},{threshold:0});N.observe(e),window.addEventListener("resize",O),a.addEventListener("change",$),document.addEventListener("visibilitychange",L);function K(){S||(S=!0,x(),N.disconnect(),window.removeEventListener("resize",O),a.removeEventListener("change",$),document.removeEventListener("visibilitychange",L))}window.addEventListener("pagehide",K);function V(M){p=(M%l+l)%l,f(Pi(p))}return h(),f(Pi(0)),F(),{isRunning:()=>v,currentTime:()=>p,frameCount:()=>_,seek:V,dispose:K}}const cy=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function Xt(t){const e=String(t||"").trim().match(cy);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function uy(t,e){if(t.length===0&&e.length===0)return 0;if(t.length===0)return 1;if(e.length===0)return-1;for(let n=0;n0)}function fy(t){const e=Xt(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function Al(t){let e=String(t??"").trim();if((e.startsWith("'")||e.startsWith('"'))&&(e=e.slice(1,-1).trim()),e===""||e==="any"||e==="*")return{min:null,minInclusive:!1,max:null,maxInclusive:!1};if(e.startsWith("^")){const o=e.slice(1).trim();return Xt(o)?{min:o,minInclusive:!0,max:fy(o),maxInclusive:!1}:null}if(Xt(e))return{min:e,minInclusive:!0,max:e,maxInclusive:!0};const n={min:null,minInclusive:!1,max:null,maxInclusive:!1},i=/(>=|<=|>|<)\s*([0-9][0-9A-Za-z.+-]*)/g;let r=!1,s;for(;(s=i.exec(e))!==null;){const[,o,a]=s;if(!Xt(a))return null;r=!0,o===">="||o===">"?(n.min=a,n.minInclusive=o===">="):(n.max=a,n.maxInclusive=o==="<=")}return r?n:null}function Gu(t,e){const n=Al(t);if(!n||!Xt(e))return!1;if(n.min!==null){const i=ps(e,n.min);if(i<0||i===0&&!n.minInclusive)return!1}if(n.max!==null){const i=ps(e,n.max);if(i>0||i===0&&!n.maxInclusive)return!1}return!0}function hy(t,e){const n=Al(t);if(!n||!Xt(e))return!1;if(n.max===null)return!0;const i=ps(n.max,e);return i>0?!0:i===0&&n.maxInclusive}function Vn(t){const e=Al(t);return e?e.min:null}const py="https://pub.dev/api/packages/",gy=8e3;function my(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null}=e,r=Array.isArray(t?.versions)?t.versions:[];let s=null;for(const o of r){const a=o?.version;if(!a||o.retracted||dy(a))continue;const l=o.pubspec?.environment||{};n&&l.sdk&&!Gu(l.sdk,n)||i&&l.flutter&&!Gu(l.flutter,i)||(!s||ps(a,s)>0)&&(s=a)}return s?{version:s,constraint:`^${s}`}:null}async function vy(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null,fetchImpl:r=fetch}=e;let s;try{const a=await r(`${py}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(gy)});if(!a.ok)return{name:t,constraint:null,version:null,error:a.status===404?`"${t}" was not found on pub.dev`:`pub.dev returned ${a.status} for "${t}"`};s=await a.json()}catch(a){return{name:t,constraint:null,version:null,error:`could not reach pub.dev for "${t}" (${a.message})`}}const o=my(s,{dartSdkFloor:n,flutterSdkFloor:i});return o?{name:t,...o,error:null}:{name:t,constraint:null,version:null,error:n?`no published "${t}" release supports Dart ${n}`:`no published "${t}" release could be read`}}async function _y(t,e={}){const n=await Promise.all(t.map(i=>vy(i,e)));return new Map(n.map(({name:i,...r})=>[i,r]))}async function yy(t,e={},n={}){const{resolveVersions:i=_y}=n,r=Object.entries(e).filter(([c])=>c&&c!=="flutter"),s=wh(t),o={dartSdkFloor:Vn(s.sdk),flutterSdkFloor:Vn(s.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(r.length===0)return a;const l=Ls(t),u=[];for(const[c,d]of r){const h=l.get(c);if(!h){u.push(c);continue}const f=Vn(d);if(!f){a.kept.push({name:c,constraint:h.constraint});continue}if(!h.isScalar){a.warnings.push(`"${c}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${f}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:c,constraint:h.constraint});continue}if(hy(h.constraint,f)){a.kept.push({name:c,constraint:h.constraint});continue}a.overrides[c]=`^${f}`,a.warnings.push(`"${c}" was pinned to ${h.constraint} in your project, which cannot resolve the ${f} the generated code needs. Raising it to ^${f} — this changes a dependency the rest of your app also uses.`)}if(u.length>0){const c=await i(u,o);for(const d of u){const h=c.get(d);if(h?.constraint){a.additions[d]=h.constraint;continue}const f=e[d]||"";if(Vn(f)){a.additions[d]=`^${Vn(f)}`,a.warnings.push(`Could not confirm "${d}" version on pub.dev (${h?.error||"lookup failed"}). Using ^${Vn(f)} from the AI's recommendation — verify this is current.`);continue}a.additions[d]=">=0.0.0",a.warnings.push(`Could not determine a version for "${d}" (${h?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const wy={"&":"&","<":"<",">":">",'"':""","'":"'"};function Qt(t){return String(t??"").replace(/[&<>"']/g,e=>wy[e])}function z(t){return t?Qt(t).replace(/\n/g,"
      "):""}function Jt(t){return Qt(t).replace(/\r?\n/g," ")}function Ns(t,e={}){const n=t?.pipelineStep;if(n!=null&&e[n]!=null)return e[n];const i=t?.message||"";return i.includes("Code Generator")?2:i.includes("Code Review")?3:1}function Ah(t){if(!t)return{kind:"generic",title:"Generation failed",message:"An unknown error occurred. Please try again.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1};if(t.isModelArmor){const n=t.code==="MODEL_ARMOR_BLOCKED";return{kind:"safety",title:t.userTitle||"Request blocked for safety",message:t.userMessage||t.message,detail:t.retryExplanation||"",canRetry:!n,canEdit:!0,canUpgrade:!1}}if(t.isUsageLimit)return{kind:"quota",title:"Monthly limit reached",message:t.message||"You've used all your generations for this period.",detail:"",canRetry:!1,canEdit:!1,canUpgrade:!0};const e=t.message||"";return/timed out after/i.test(e)?{kind:"timeout",title:"Request timed out",message:"The generation service took too long to respond.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:/unreachable|failed to fetch|load failed|cors/i.test(e)?{kind:"network",title:"Connection problem",message:"We couldn't reach the generation service. Check your connection and try again.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:{kind:"generic",title:"Generation failed",message:e||"An unexpected error occurred.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1}}function by(t){const e={"Integration Audit Report":"📋","Critical Issues":"❌",Warnings:"⚠️",Recommendations:"✅","Overall Score":"📊"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📄"}function Ey(t){const e={critical:"❌",warning:"⚠️",recommendation:"✅",score:"📊",issue:"🔍",fix:"🔧"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📝"}function Sy(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 ci(t){if(!t)return"";if(typeof t!="string")return String(t);const e=/```(?:\w+)?\n?([\s\S]*?)```/,n=t.match(e);return n?n[1].trim():t.trim()}function Ku(t){return t=Qt(t),t=t.replace(/\*\*(.*?)\*\*/g,'$1'),t=t.replace(/\*(.*?)\*/g,'$1'),t=t.replace(/`(.*?)`/g,'$1'),t=t.replace(/\b(FAIL|ERROR|CRITICAL)\b/g,'$1'),t=t.replace(/\b(WARN|WARNING)\b/g,'$1'),t=t.replace(/\b(PASS|SUCCESS|OK)\b/g,'$1'),t}function Ph(t,e="dart",n=globalThis.hljs){if(!t)return"";const i=ci(t);try{return n.highlight(i,{language:e}).value}catch(r){console.warn("Syntax highlighting failed:",r);try{return n.highlight(i,{language:"json"}).value}catch{return Qt(i)}}}function Os(t,e={}){const{highlighter:n=globalThis.hljs}=e;let i='
      ';const r=String(t??"").split(` +`);let s=!1,o="";for(const a of r){if(a.startsWith("```")){if(s){const l=Sy(o),u=Ph(o.trim(),l,n);i+=`
      ${u}
      `,o="",s=!1}else s=!0;continue}if(s){o+=a+` `;continue}if(a.startsWith("# ")){const l=a.substring(2).trim();i+=`

      - ${wy(l)} + ${by(l)} ${Qt(l)}

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

      - ${by(l)} + ${Ey(l)} ${Qt(l)}

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

      ${Vu(a)}

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

      ${Ku(a)}

      `)}return i+="
      ",`
      @@ -78,14 +78,14 @@ in vec2 p; void main(){ gl_Position = vec4(p, 0.0, 1.0); }`;function a(){return[
      ${i}
      - `}const Sy=[[/gradient stroke\s*$/i," and an animated percentage label"],[/gauge\s*$/i," with a gradient stroke and animated fill"],[/rating\s*(bar|widget)?\s*$/i," with half-star support and haptic feedback"],[/list\s*$/i," with swipe-to-delete and an undo snackbar"],[/pad\s*$/i," that exports a transparent PNG"],[/carousel\s*$/i," with parallax cards and page indicators"],[/(button|cta)\s*$/i," with a loading spinner and success state"],[/(chart|graph)\s*$/i," that animates from a Firestore stream"],[/action\s*(that|to)?\s*$/i," uploads an image to Firebase Storage and returns the URL"],[/timer\s*$/i," with pause, resume and a completion callback"],[/map\s*$/i," with clustered markers and a custom info window"],[/^a\s+\w*$/i," widget that"],[/(picker|selector)\s*$/i," with search and multi-select"]],xy=220,Iy=6;function Gu(t,e){return!!(t&&t.trim())&&!e}function ky(t,e=""){if(typeof t!="string"||!t||t===e||t.trim().lengthi.test(t));return n?n[1]:null}function Cy(){let t="",e="";return{get active(){return t},resolve(n){return t=ky(n,e)??"",t},dismiss(){t=""},accept(n){if(!t)return null;const i=n+t;return e=i,t="",i}}}function Ay({onSubmit:t}){const e=document.getElementById("composer"),n=document.getElementById("pipeline-input"),i=document.getElementById("hero-send");if(!e||!n||!i||typeof t!="function")return;const r=e.querySelector(".ghost .typed"),s=e.querySelector(".ghost .suggest"),o=document.getElementById("tab-hint"),a=document.getElementById("suggest-status"),l=Array.from(document.querySelectorAll("#example-chips .chip")),u=document.getElementById("btn-add-images"),c=document.getElementById("prompt-image-input"),d=window.matchMedia("(prefers-reduced-motion: reduce)"),f=Cy();let h=!1,p=!1,g=!1,m=!1,v=null,E=null;function S(){i.disabled=!Gu(n.value,p||g||m)}function _(){r&&(r.textContent=n.value)}function b(){s&&(s.textContent=""),_(),e.classList.remove("has-suggest"),o&&(o.hidden=!0,o.tabIndex=-1),a&&(a.textContent="")}function k(R){s&&(s.textContent=R),_(),e.classList.add("has-suggest"),o&&(o.hidden=!1,o.tabIndex=0,o.setAttribute("aria-label","Accept suggestion: "+R.trim())),a&&(a.textContent="Suggestion: "+R+". Press Tab to accept.")}function T(){f.dismiss(),b()}function x(){if(h||p)return;const R=f.resolve(n.value);R&&k(R)}function F(){clearTimeout(v),!h&&(v=setTimeout(x,xy))}function $(){const R=f.accept(n.value);return R===null?!1:(n.value=R,b(),S(),!0)}function O(R){p=R,e.classList.toggle("is-busy",R),i.classList.toggle("is-busy",R),i.setAttribute("aria-label",R?"Generating":"Generate"),n.readOnly=R,l.forEach(Z=>{Z.disabled=R}),u&&(u.disabled=R),c&&(c.disabled=R),S()}async function L(){if(Gu(n.value,p||g||m)){T(),O(!0);try{await t()}finally{O(!1)}}}function N(){g=!1,E&&(clearInterval(E),E=null),e.classList.remove("is-demo-typing"),S()}function K(){l.forEach(R=>{R.classList.remove("is-active"),R.setAttribute("aria-pressed","false")})}function V(){try{n.focus({preventScroll:!0}),n.setSelectionRange(n.value.length,n.value.length)}catch{}}function M(R){const Z=R.dataset.prompt||"";if(N(),clearTimeout(v),v=null,T(),l.forEach(oe=>{const ye=oe===R;oe.classList.toggle("is-active",ye),oe.setAttribute("aria-pressed",String(ye))}),d.matches||!Z){n.value=Z,_(),S(),V();return}n.value="",_(),g=!0,S(),e.classList.add("is-demo-typing");let Ce=0;E=setInterval(()=>{Ce+=1,n.value=Z.slice(0,Ce),_(),Ce>=Z.length?(N(),V()):S()},22)}return l.forEach(R=>{R.setAttribute("aria-pressed","false"),R.addEventListener("click",()=>M(R))}),n.addEventListener("keydown",R=>{if(g&&R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!h){R.preventDefault();return}N(),R.key==="Tab"&&!R.shiftKey&&f.active?(R.preventDefault(),$()):R.key==="Escape"?(clearTimeout(v),v=null,T()):R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!h&&(R.preventDefault(),L())}),n.addEventListener("input",()=>{N(),K(),T(),S(),F()}),n.addEventListener("compositionstart",()=>{h=!0}),n.addEventListener("compositionend",()=>{h=!1,T(),S(),F()}),n.addEventListener("scroll",()=>{r&&r.parentNode&&(r.parentNode.scrollTop=n.scrollTop)}),o&&o.addEventListener("click",()=>{$(),n.focus({preventScroll:!0})}),i.addEventListener("click",L),n.addEventListener("pointerdown",()=>{N(),K()}),_(),S(),{setAttachmentsPending(R){m=!!R,S()}}}const Py="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses";const _t="https://4tgke4.buildship.run",Ah={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},hs="ccc_auth_session",Na="ccc_signin_return",Fy=1800*1e3,Ku=new WeakSet;let q={email:null,sessionToken:null,isVerified:!1};function Ln(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let ce=Ln({isResolved:!0}),Oa=Promise.resolve();const Ry=`${_t}/service/runpipeline`,Ty="bs_user_id",$y="bs_identity_token",My=`${_t}/authUserCheck`;let ht={userId:null,token:null,status:null,resolved:!1};const ps=dv,gs="ccc_subscription",Yu=3,Ly=new Set(["active","trialing","paid"]),ms="google/gemini-3.7-flash",Nr=["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"],Ny={"google/gemini-3.7-flash":"Gemini 3.7 Flash","anthropic/claude-opus-5":"Claude Opus 5","openai/gpt-5.6-sol":"GPT-5.6 Sol","z-ai/glm-5.2":"GLM 5.2","moonshotai/kimi-k3":"Kimi K3","openrouter/auto-beta":"OpenRouter: Auto Router","openrouter/free":"OpenRouter: Free Models","openrouter/deepseek/deepseek-v4-pro":"DeepSeek v4 Pro"};function Gt(t){return Ny[t]||t}const Oy=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 Ph(t){return Oy.has(t)}const Ba=4,Ho=8*1024*1024,By="https://4tgke4.buildship.run/service/runpipeline-image";let Oe=[];const pn=[],Dy=3e4;let Fh=null;function jy(t){return new Promise(e=>{const n=new FileReader;n.onload=()=>e(n.result),n.onerror=()=>e(null),n.readAsDataURL(t)})}async function Uy(t,e){const n=new FormData;return n.append("file",t),(await fetch(By,{method:"POST",body:n,signal:e})).json()}function Hy(t){if(Array.isArray(t)){const e=t[0];if(e&&typeof e=="object")for(const n of Object.keys(e)){if(n==="item"||n==="index")continue;const i=e[n];if(i&&typeof i=="object"){if(typeof i.file=="string")return i.file;if(typeof i.url=="string")return i.url}if(typeof i=="string")return i}return""}return typeof t=="string"?t:t&&typeof t=="object"&&(t.url||t.fileUrl||t.file_url||t.downloadUrl||t.imageUrl||t.image_url||t.file)||""}async function Wy(t,e,n){const i=await jy(t);i&&Oe.includes(e)&&(e.dataUrl=i,cn());let r="";if(i)try{r=Hy(await Uy(t,n))}catch{r=""}return Oe.includes(e)?!i||!r?(Oe.splice(Oe.indexOf(e),1),cn(),"failed"):(e.url=r,cn(),"added"):"dropped"}function Rh(t){const e=pn.indexOf(t);e>=0&&pn.splice(e,1),$h()}function Th(t){t.controller.abort(),Rh(t);const e=Oe.indexOf(t.slot);e>=0&&(Oe.splice(e,1),cn())}function $h(){Fh?.setAttachmentsPending(pn.length>0)}async function zy(t){const e=Array.from(t.target.files||[]);if(!e.length)return;if(t.target.value="",y.isRunning){Ee("Wait for the current generation to finish before attaching images.","info");return}const n=e.filter(u=>u.size>Ho);n.length&&Ee(`Skipped ${n.length} image(s) over the ${(Ho/1024/1024).toFixed(0)} MB limit.`,"warning");const i=e.filter(u=>u.size<=Ho);if(!i.length)return;const r=Ba-Oe.length,s=i.slice(0,r);if(i.length>r&&Ee(`You can attach up to ${Ba} images.`,"info"),!s.length)return;const o=s.map(u=>{const c={dataUrl:null,name:u.name,url:null};Oe.push(c);const d={slot:c,controller:new AbortController},f=setTimeout(()=>d.controller.abort(),Dy);return d.job=Wy(u,c,d.controller.signal),pn.push(d),d.job.finally(()=>{clearTimeout(f),Rh(d)}),d.job});cn(),$h();const l=(await Promise.all(o)).filter(u=>u==="failed").length;l&&Ee(`${l} image(s) could not be uploaded and were not attached.`,"error")}function qy(t){const e=Oe[t],n=pn.find(i=>i.slot===e);if(n){Th(n);return}Oe.splice(t,1),cn()}function cn(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",Oe.forEach((n,i)=>{const r=document.createElement("div");r.className="prompt-img-thumb"+(n.url?"":" is-pending"),r.innerHTML=(n.dataUrl?`Prompt image`:"")+``,t.appendChild(r)}),e&&(e.textContent=Oe.length>=Ba?"Image limit reached":"Add images"))}function Cl(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),n=Ph(e?.value);t.classList.toggle("hidden",!n),!n&&Oe.length&&(pn.slice().forEach(Th),Oe=[],cn())}const Rn="ccc_usage",Mh="google/gemini-3.7-flash",Lh="google/gemini-3.7-flash",kr="google/gemini-3.7-flash",Oi={professional:11,power:49},Da={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"},Or={AUD:1,USD:.65,EUR:.6,GBP:.52,CAD:.88,NZD:1.08,JPY:97,KRW:870,INR:54,SGD:.87,HKD:5.08,BRL:3.18,CNY:4.7,TWD:20.5,THB:22.5,VND:16200,IDR:10200,MYR:2.88,SEK:6.8,NOK:6.95,DKK:4.48,PLN:2.6,CZK:15.2,HUF:238,RON:2.98,TRY:20.9,AED:2.39,ILS:2.38,PHP:36.4,ZAR:11.8,RUB:58,UAH:26.8,CHF:.57,MXN:11.1,ARS:580,CLP:610,COP:2700,PEN:2.44};let Br={...Or};async function Vy(){const t=new AbortController,e=setTimeout(()=>t.abort(),5e3);try{const n=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:t.signal});if(!n.ok)return;const i=await n.json();if(i.result!=="success"||!i.rates)return;const r=i.rates,s={AUD:1},o=new Set([...Object.keys(Or),...Object.values(ja),...Object.values(Da)]);for(const a of o)a!=="AUD"&&(typeof r[a]=="number"&&r[a]>0?s[a]=r[a]:Or[a]&&(s[a]=Or[a]));Br=s}catch{}finally{clearTimeout(e)}}const ja={"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 Al(){try{const s=Intl.DateTimeFormat().resolvedOptions().timeZone;if(s&&ja[s])return ja[s]}catch{}const e=(navigator.language||"en-US").replace("-","_"),n=Da[e];if(n)return n;const i=e.split("_")[0],r=Da[i];return r||"USD"}function Bi(t,e){const n=Br[e]??Br.USD,i=t*n,r=Math.round(i*100)/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:r>=100||r%1===0?0:2}).format(r)}catch{return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(t*Br.USD)}}const gt="ccc_api_key_",Pt="ccc_session_api_key_",Rt="ccc_encryption_key",nr="ccc_encryption_key_scope",Gy="ccc_keystore",vs="keys",ir="ccc_encryption_key_version";let Ua=null,_s=null,rr=!1,ys=!1,Ju=!1;class ws extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function Zu(){if(Ju)return;Ju=!0;const t="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(t),document.body&&Ee(t,"warning")}function Nh(){return localStorage.getItem(ir)||""}function Ha(){return crypto.randomUUID?.()||Bh(crypto.getRandomValues(new Uint8Array(16)))}function Ky(){const t=Nh();if(t)return t;const e=Ha();return localStorage.setItem(ir,e),e}function ui(){Ua=null,_s=null,rr=!1,ys=!1}window.addEventListener("storage",t=>{t.key===ir&&ui()});function Yy(){return new Promise((t,e)=>{const n=indexedDB.open(Gy,1);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(vs)||i.createObjectStore(vs)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function Pl(t,e){const n=await Yy();return new Promise((i,r)=>{const s=n.transaction(vs,t);let o;try{o=e(s.objectStore(vs))}catch(l){n.close(),r(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>r(o.error),s.oncomplete=()=>{n.close(),i(a)},s.onerror=()=>{n.close(),r(s.error||new Error("Encryption key transaction failed."))},s.onabort=()=>{n.close(),r(s.error||new Error("Encryption key transaction aborted."))}})}function Jy(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function Zy(){const t=await Pl("readonly",e=>e.get(Rt));return Jy(t)?t:null}async function Oh(t){await Pl("readwrite",e=>e.put(t,Rt))}async function Xy(){ui();try{await Pl("readwrite",t=>t.delete(Rt))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function Qy(){const t=sessionStorage.getItem(Rt);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Oh(e),sessionStorage.removeItem(Rt),sessionStorage.removeItem(nr),localStorage.removeItem(gt+"salt"),e}async function Xu(t){const e=sessionStorage.getItem(Rt);if(e)return ys=sessionStorage.getItem(nr)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new ws;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),i=await crypto.subtle.exportKey("jwk",n);return sessionStorage.setItem(Rt,JSON.stringify(i)),sessionStorage.setItem(nr,"session"),ys=!1,crypto.subtle.importKey("jwk",i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function e0(t){if(sessionStorage.getItem(nr)==="session"&&sessionStorage.getItem(Rt))return Zu(),rr=!0,Xu(t);try{const e=await Zy();if(e)return e;const n=await Qy();if(n)return n;const i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Oh(i),i}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),Zu(),rr=!0,Xu(t)}}async function Fl(t={}){const{allowSessionFallbackCreation:e=!0}=t,n=Ky();_s!==n&&ui();const i=Ua||e0(e);Ua=i,_s=n;try{return await i}catch(r){throw ui(),r}}async function t0(t){const e=await Fl(),n=_s,i=new TextEncoder,r=crypto.getRandomValues(new Uint8Array(12)),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},e,i.encode(t)),o=new Uint8Array(r.length+s.byteLength);return o.set(r),o.set(new Uint8Array(s),r.length),{ciphertext:Bh(o),keyVersion:n,sessionFallback:rr}}async function n0(t,e={}){const{isSessionCredential:n=!1}=e;try{const i=await Fl({allowSessionFallbackCreation:!1});if(rr&&!n&&!ys)throw new ws;const r=i0(t),s=r.slice(0,12),o=r.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},i,o);return new TextDecoder().decode(a)}catch(i){if(i instanceof ws)throw i;return console.error("Decryption failed:",i),null}}function Bh(t){const e=new Uint8Array(t);let n="";for(let i=0;i0}let Nn="",di="",qi=null,ed=0,nt="not-configured";async function Rl(){sessionStorage.getItem(Rt)&&await Fl(),Nn=await Te("flutterflow"),di=await Te("flutterflow_project_id"),d0(),rn(),Nn?Ll():(nt="not-configured",vt())}let sr=!1;function Dh(){const t=document.getElementById("api-keys-modal");We(t),Ml(),Nn&&Nl(Nn)}function Tl(){sr=!1,Dh()}function s0(){sr=!0;const t=document.getElementById("walkthrough-modal");t&&ze(t),Dh()}let td=!1;function nd(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-settings-model");if(!t||!e)return;e.value=t.value;const n=Array.from(t.options);Array.from(e.options).forEach((r,s)=>{const o=n[s];o&&(r.textContent=o.textContent)});const i=document.getElementById("composer-settings-free-notice");i&&(document.getElementById("model-selector-free-notice")?(i.hidden=!1,i.innerHTML='Free plan — Gemini only. '):i.hidden=!0)}function id(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-image-capability"),n=document.getElementById("composer-image-capability-note");if(!t)return;const i=Gt(t.value),r=Ph(t.value);e&&(e.textContent=r?"Supported":"Not supported"),n&&(n.textContent=r?`${i} accepts reference images you attach to the prompt.`:`Images can't be attached with ${i}. Attached images are removed when you switch to it.`),Cl()}function o0(){if(sr=!1,nd(),id(),!td){const e=document.getElementById("composer-settings-model");e&&e.addEventListener("change",()=>{const n=document.getElementById("code-generator-model");n.value=e.value,n.dispatchEvent(new Event("change")),nd(),id()}),td=!0}const t=document.querySelector('.composer [aria-label="Generation settings"]');We("composer-settings-modal",{trigger:t})}function a0(t){t&&t.target!==t.currentTarget||ze("composer-settings-modal")}function jh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&ze(e);const n=sr;if(sr=!1,n){const i=document.getElementById("walkthrough-modal");i&&(nt==="connected"&&$l(),We(i))}}let en=1;function Uh(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function Ns(){const t=Uh();t.length&&t.forEach((e,n)=>{const i=n+1;e.classList.remove("wt-current","wt-done","wt-pending");const r=e.querySelector(".wt-step-num");i===en?(e.classList.add("wt-current"),r&&(r.textContent=i)):i0&&en<=t&&(en++,Ns())}function l0(){const t=document.getElementById("walkthrough-modal");t&&(en=1,Ns(),We(t))}function c0(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&ze(e);const n=document.getElementById("walkthrough-dont-show");n&&n.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function Hh(){if(q.isVerified&&Tt()&&ce.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(en=1,Ns(),We(e))}}async function Ml(){const t=document.getElementById("flutterflow-api-key-input");Nn?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",u0()}function u0(){rd("flutterflow","flutterflow-key-status"),rd("flutterflow_project_id","flutterflow-project-status")}function rd(t,e){const n=document.getElementById(e);if(!n)return;const i=n.querySelector(".key-status-dot"),r=n.querySelector("span");Ct(t)?(i.className="key-status-dot configured",r.className="text-green-600",r.textContent="User key configured"):(i.className="key-status-dot missing",r.className="text-gray-500",r.textContent="Not configured")}function rn(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff");e&&e.classList.toggle("hidden",!t)}function d0(){const t=document.getElementById("api-keys-status");if(!t)return;const e=t.querySelectorAll(".key-status-dot"),n=["flutterflow"];e.forEach((i,r)=>{const s=n[r];s==="flutterflow"?Ct("flutterflow")&&Ct("flutterflow_project_id")?(i.className="key-status-dot configured",i.title="FlutterFlow (Fully configured)"):Ct("flutterflow")||Ct("flutterflow_project_id")?(i.className="key-status-dot env",i.title="FlutterFlow (Partially configured)"):(i.className="key-status-dot missing",i.title="FlutterFlow (Not configured)"):Ct(s)?(i.className="key-status-dot configured",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (User key)"):(i.className="key-status-dot missing",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (Not configured)")}),rn()}async function f0(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select"),n=t.value.trim();n&&await Qu("flutterflow",n);const i=e?.value.trim()||"";if(i){if(!Os(i)){Ee("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await Qu("flutterflow_project_id",i)}await Rl(),n&&await Ll(),Ml();const r=document.querySelector("#api-keys-modal .bg-blue-500"),s=r.textContent;r.textContent="Saved!",r.classList.remove("bg-blue-500","hover:bg-blue-600"),r.classList.add("bg-green-500"),setTimeout(()=>{r.textContent=s,r.classList.remove("bg-green-500"),r.classList.add("bg-blue-500","hover:bg-blue-600"),jh()},1e3)}async function h0(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(ir,Ha()),ui(),localStorage.removeItem(gt+"flutterflow"),localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow"),sessionStorage.removeItem(Pt+"flutterflow_project_id"),sessionStorage.removeItem(Rt),sessionStorage.removeItem(nr),localStorage.removeItem(gt+"salt"),await Xy(),localStorage.setItem(ir,Ha()),localStorage.removeItem(gt+"flutterflow"),localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow"),sessionStorage.removeItem(Pt+"flutterflow_project_id"),await Rl();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),Ml()}function Os(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function vt(){const t=document.getElementById("acct-ff-dot"),e=document.getElementById("acct-ff-status"),n=document.getElementById("acct-ff-endpoint"),i=document.getElementById("acct-ff-project");if(n){const o=yt();n.textContent=o.includes("staging")?"Staging":"Production"}if(i&&(i.textContent=di||"—"),!e)return;let r,s;if(!Ct("flutterflow"))r="Not connected — add your FlutterFlow API key",s="";else switch(nt){case"connected":r="Connected to FlutterFlow",s="ok";break;case"no-projects":r="Key accepted — no projects found",s="warn";break;case"unauthorized":r="API key rejected (401/403) — re-enter your key",s="bad";break;case"network-error":r="Could not reach FlutterFlow — check your network",s="bad";break;default:r="Checking connection…",s="warn";break}e.textContent=r,t&&(t.className=`acct-dot${s?" "+s:""}`)}async function Ll(){const t=await Te("flutterflow");if(!t||!Ct("flutterflow"))return nt="not-configured",vt(),null;nt="validating",vt();try{const n=await new pi(t,"","main",yt()).listProjects();return nt=n&&n.length>0?"connected":"no-projects",vt(),n}catch(e){const n=String(e&&e.message||"");return nt=/(401|403)|denied|unauthorized|scoped|list permission/i.test(n)?"unauthorized":"network-error",vt(),null}}function p0(){di="",localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow_project_id")}function g0(){p0();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML='',t.value=""),Ct("flutterflow")?(nt="validating",Nl(Nn)):nt="not-configured",vt()}function m0(t,e){const n=document.getElementById(t);n&&(n.value?e?n.style.borderColor="#22c55e":n.style.borderColor="#ef4444":n.style.borderColor="")}function v0(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const n=e.target.value.trim().length>0;m0("flutterflow-api-key-input",n)}),t.addEventListener("blur",_0(async e=>{const n=e.target.value.trim();n&&await Nl(n)},500)))}function _0(t,e){let n;return function(...r){const s=()=>{clearTimeout(n),t(...r)};clearTimeout(n),n=setTimeout(s,e)}}async function Nl(t){const e=document.getElementById("flutterflow-projects-select"),n=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',n&&n.classList.add("hidden"),(Ct("flutterflow")||t)&&(nt="validating"),vt();try{const r=await new pi(t,"","main",yt()).listProjects();if(!r||r.length===0){nt="no-projects",vt(),e.innerHTML='';return}nt="connected",vt(),e.innerHTML='',r.forEach(s=>{const o=document.createElement("option");o.value=s.id||s.projectId||"",o.textContent=s.name||s.projectName||`Project ${s.id}`,e.appendChild(o)}),di&&(e.value=di)}catch(i){console.error("Failed to fetch projects:",i);const r=String(i&&i.message||"");nt=/(401|403)|denied|unauthorized|scoped|list permission/i.test(r)?"unauthorized":"network-error",vt(),e.innerHTML='',n&&(n.textContent=`Failed to load projects: ${i.message}`,n.classList.remove("hidden"))}}function y0(t){const e=document.getElementById(t),i=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",i.innerHTML=` + `}const xy=[[/gradient stroke\s*$/i," and an animated percentage label"],[/gauge\s*$/i," with a gradient stroke and animated fill"],[/rating\s*(bar|widget)?\s*$/i," with half-star support and haptic feedback"],[/list\s*$/i," with swipe-to-delete and an undo snackbar"],[/pad\s*$/i," that exports a transparent PNG"],[/carousel\s*$/i," with parallax cards and page indicators"],[/(button|cta)\s*$/i," with a loading spinner and success state"],[/(chart|graph)\s*$/i," that animates from a Firestore stream"],[/action\s*(that|to)?\s*$/i," uploads an image to Firebase Storage and returns the URL"],[/timer\s*$/i," with pause, resume and a completion callback"],[/map\s*$/i," with clustered markers and a custom info window"],[/^a\s+\w*$/i," widget that"],[/(picker|selector)\s*$/i," with search and multi-select"]],Iy=220,ky=6;function Yu(t,e){return!!(t&&t.trim())&&!e}function Cy(t,e=""){if(typeof t!="string"||!t||t===e||t.trim().lengthi.test(t));return n?n[1]:null}function Ay(){let t="",e="";return{get active(){return t},resolve(n){return t=Cy(n,e)??"",t},dismiss(){t=""},accept(n){if(!t)return null;const i=n+t;return e=i,t="",i}}}function Py({onSubmit:t}){const e=document.getElementById("composer"),n=document.getElementById("pipeline-input"),i=document.getElementById("hero-send");if(!e||!n||!i||typeof t!="function")return;const r=e.querySelector(".ghost .typed"),s=e.querySelector(".ghost .suggest"),o=document.getElementById("tab-hint"),a=document.getElementById("suggest-status"),l=Array.from(document.querySelectorAll("#example-chips .chip")),u=document.getElementById("btn-add-images"),c=document.getElementById("prompt-image-input"),d=window.matchMedia("(prefers-reduced-motion: reduce)"),h=Ay();let f=!1,p=!1,g=!1,m=!1,v=null,E=null;function S(){i.disabled=!Yu(n.value,p||g||m)}function _(){r&&(r.textContent=n.value)}function b(){s&&(s.textContent=""),_(),e.classList.remove("has-suggest"),o&&(o.hidden=!0,o.tabIndex=-1),a&&(a.textContent="")}function k(R){s&&(s.textContent=R),_(),e.classList.add("has-suggest"),o&&(o.hidden=!1,o.tabIndex=0,o.setAttribute("aria-label","Accept suggestion: "+R.trim())),a&&(a.textContent="Suggestion: "+R+". Press Tab to accept.")}function T(){h.dismiss(),b()}function x(){if(f||p)return;const R=h.resolve(n.value);R&&k(R)}function F(){clearTimeout(v),!f&&(v=setTimeout(x,Iy))}function $(){const R=h.accept(n.value);return R===null?!1:(n.value=R,b(),S(),!0)}function O(R){p=R,e.classList.toggle("is-busy",R),i.classList.toggle("is-busy",R),i.setAttribute("aria-label",R?"Generating":"Generate"),n.readOnly=R,l.forEach(Z=>{Z.disabled=R}),u&&(u.disabled=R),c&&(c.disabled=R),S()}async function L(){if(Yu(n.value,p||g||m)){T(),O(!0);try{await t()}finally{O(!1)}}}function N(){g=!1,E&&(clearInterval(E),E=null),e.classList.remove("is-demo-typing"),S()}function K(){l.forEach(R=>{R.classList.remove("is-active"),R.setAttribute("aria-pressed","false")})}function V(){try{n.focus({preventScroll:!0}),n.setSelectionRange(n.value.length,n.value.length)}catch{}}function M(R){const Z=R.dataset.prompt||"";if(N(),clearTimeout(v),v=null,T(),l.forEach(oe=>{const ye=oe===R;oe.classList.toggle("is-active",ye),oe.setAttribute("aria-pressed",String(ye))}),d.matches||!Z){n.value=Z,_(),S(),V();return}n.value="",_(),g=!0,S(),e.classList.add("is-demo-typing");let Ce=0;E=setInterval(()=>{Ce+=1,n.value=Z.slice(0,Ce),_(),Ce>=Z.length?(N(),V()):S()},22)}return l.forEach(R=>{R.setAttribute("aria-pressed","false"),R.addEventListener("click",()=>M(R))}),n.addEventListener("keydown",R=>{if(g&&R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!f){R.preventDefault();return}N(),R.key==="Tab"&&!R.shiftKey&&h.active?(R.preventDefault(),$()):R.key==="Escape"?(clearTimeout(v),v=null,T()):R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!f&&(R.preventDefault(),L())}),n.addEventListener("input",()=>{N(),K(),T(),S(),F()}),n.addEventListener("compositionstart",()=>{f=!0}),n.addEventListener("compositionend",()=>{f=!1,T(),S(),F()}),n.addEventListener("scroll",()=>{r&&r.parentNode&&(r.parentNode.scrollTop=n.scrollTop)}),o&&o.addEventListener("click",()=>{$(),n.focus({preventScroll:!0})}),i.addEventListener("click",L),n.addEventListener("pointerdown",()=>{N(),K()}),_(),S(),{setAttachmentsPending(R){m=!!R,S()}}}const Fy="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses";const _t="https://4tgke4.buildship.run",Fh={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},gs="ccc_auth_session",Ba="ccc_signin_return",Ry=1800*1e3,Ju=new WeakSet;let q={email:null,sessionToken:null,isVerified:!1};function Ln(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let ce=Ln({isResolved:!0}),Da=Promise.resolve();const Ty=`${_t}/service/runpipeline`,$y="bs_user_id",My="bs_identity_token",Ly=`${_t}/authUserCheck`;let ht={userId:null,token:null,status:null,resolved:!1};const ms=fv,vs="ccc_subscription",Zu=3,Ny=new Set(["active","trialing","paid"]),_s="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"],Oy={"google/gemini-3.7-flash":"Gemini 3.7 Flash","anthropic/claude-opus-5":"Claude Opus 5","openai/gpt-5.6-sol":"GPT-5.6 Sol","z-ai/glm-5.2":"GLM 5.2","moonshotai/kimi-k3":"Kimi K3","openrouter/auto-beta":"OpenRouter: Auto Router","openrouter/free":"OpenRouter: Free Models","openrouter/deepseek/deepseek-v4-pro":"DeepSeek v4 Pro"};function Gt(t){return Oy[t]||t}const By=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 Rh(t){return By.has(t)}const ja=4,zo=8*1024*1024,Dy="https://4tgke4.buildship.run/service/runpipeline-image";let Oe=[];const pn=[],jy=3e4;let Th=null;function Uy(t){return new Promise(e=>{const n=new FileReader;n.onload=()=>e(n.result),n.onerror=()=>e(null),n.readAsDataURL(t)})}async function Hy(t,e){const n=new FormData;return n.append("file",t),(await fetch(Dy,{method:"POST",body:n,signal:e})).json()}function Wy(t){if(Array.isArray(t)){const e=t[0];if(e&&typeof e=="object")for(const n of Object.keys(e)){if(n==="item"||n==="index")continue;const i=e[n];if(i&&typeof i=="object"){if(typeof i.file=="string")return i.file;if(typeof i.url=="string")return i.url}if(typeof i=="string")return i}return""}return typeof t=="string"?t:t&&typeof t=="object"&&(t.url||t.fileUrl||t.file_url||t.downloadUrl||t.imageUrl||t.image_url||t.file)||""}async function zy(t,e,n){const i=await Uy(t);i&&Oe.includes(e)&&(e.dataUrl=i,cn());let r="";if(i)try{r=Wy(await Hy(t,n))}catch{r=""}return Oe.includes(e)?!i||!r?(Oe.splice(Oe.indexOf(e),1),cn(),"failed"):(e.url=r,cn(),"added"):"dropped"}function $h(t){const e=pn.indexOf(t);e>=0&&pn.splice(e,1),Lh()}function Mh(t){t.controller.abort(),$h(t);const e=Oe.indexOf(t.slot);e>=0&&(Oe.splice(e,1),cn())}function Lh(){Th?.setAttachmentsPending(pn.length>0)}async function qy(t){const e=Array.from(t.target.files||[]);if(!e.length)return;if(t.target.value="",y.isRunning){Ee("Wait for the current generation to finish before attaching images.","info");return}const n=e.filter(u=>u.size>zo);n.length&&Ee(`Skipped ${n.length} image(s) over the ${(zo/1024/1024).toFixed(0)} MB limit.`,"warning");const i=e.filter(u=>u.size<=zo);if(!i.length)return;const r=ja-Oe.length,s=i.slice(0,r);if(i.length>r&&Ee(`You can attach up to ${ja} images.`,"info"),!s.length)return;const o=s.map(u=>{const c={dataUrl:null,name:u.name,url:null};Oe.push(c);const d={slot:c,controller:new AbortController},h=setTimeout(()=>d.controller.abort(),jy);return d.job=zy(u,c,d.controller.signal),pn.push(d),d.job.finally(()=>{clearTimeout(h),$h(d)}),d.job});cn(),Lh();const l=(await Promise.all(o)).filter(u=>u==="failed").length;l&&Ee(`${l} image(s) could not be uploaded and were not attached.`,"error")}function Vy(t){const e=Oe[t],n=pn.find(i=>i.slot===e);if(n){Mh(n);return}Oe.splice(t,1),cn()}function cn(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",Oe.forEach((n,i)=>{const r=document.createElement("div");r.className="prompt-img-thumb"+(n.url?"":" is-pending"),r.innerHTML=(n.dataUrl?`Prompt image`:"")+``,t.appendChild(r)}),e&&(e.textContent=Oe.length>=ja?"Image limit reached":"Add images"))}function Pl(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),n=Rh(e?.value);t.classList.toggle("hidden",!n),!n&&Oe.length&&(pn.slice().forEach(Mh),Oe=[],cn())}const Fn="ccc_usage",Nh="google/gemini-3.7-flash",Oh="google/gemini-3.7-flash",Ar="google/gemini-3.7-flash",Oi={professional:11,power:49},Ua={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 Gy(){const t=new AbortController,e=setTimeout(()=>t.abort(),5e3);try{const n=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:t.signal});if(!n.ok)return;const i=await n.json();if(i.result!=="success"||!i.rates)return;const r=i.rates,s={AUD:1},o=new Set([...Object.keys(Dr),...Object.values(Ha),...Object.values(Ua)]);for(const a of o)a!=="AUD"&&(typeof r[a]=="number"&&r[a]>0?s[a]=r[a]:Dr[a]&&(s[a]=Dr[a]));jr=s}catch{}finally{clearTimeout(e)}}const Ha={"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 Fl(){try{const s=Intl.DateTimeFormat().resolvedOptions().timeZone;if(s&&Ha[s])return Ha[s]}catch{}const e=(navigator.language||"en-US").replace("-","_"),n=Ua[e];if(n)return n;const i=e.split("_")[0],r=Ua[i];return r||"USD"}function Bi(t,e){const n=jr[e]??jr.USD,i=t*n,r=Math.round(i*100)/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:r>=100||r%1===0?0:2}).format(r)}catch{return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(t*jr.USD)}}const gt="ccc_api_key_",Pt="ccc_session_api_key_",Rt="ccc_encryption_key",nr="ccc_encryption_key_scope",Ky="ccc_keystore",ys="keys",ir="ccc_encryption_key_version";let Wa=null,ws=null,rr=!1,bs=!1,Xu=!1;class Es extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function Qu(){if(Xu)return;Xu=!0;const t="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(t),document.body&&Ee(t,"warning")}function Bh(){return localStorage.getItem(ir)||""}function za(){return crypto.randomUUID?.()||jh(crypto.getRandomValues(new Uint8Array(16)))}function Yy(){const t=Bh();if(t)return t;const e=za();return localStorage.setItem(ir,e),e}function ui(){Wa=null,ws=null,rr=!1,bs=!1}window.addEventListener("storage",t=>{t.key===ir&&ui()});function Jy(){return new Promise((t,e)=>{const n=indexedDB.open(Ky,1);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(ys)||i.createObjectStore(ys)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function Rl(t,e){const n=await Jy();return new Promise((i,r)=>{const s=n.transaction(ys,t);let o;try{o=e(s.objectStore(ys))}catch(l){n.close(),r(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>r(o.error),s.oncomplete=()=>{n.close(),i(a)},s.onerror=()=>{n.close(),r(s.error||new Error("Encryption key transaction failed."))},s.onabort=()=>{n.close(),r(s.error||new Error("Encryption key transaction aborted."))}})}function Zy(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function Xy(){const t=await Rl("readonly",e=>e.get(Rt));return Zy(t)?t:null}async function Dh(t){await Rl("readwrite",e=>e.put(t,Rt))}async function Qy(){ui();try{await Rl("readwrite",t=>t.delete(Rt))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function e0(){const t=sessionStorage.getItem(Rt);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Dh(e),sessionStorage.removeItem(Rt),sessionStorage.removeItem(nr),localStorage.removeItem(gt+"salt"),e}async function ed(t){const e=sessionStorage.getItem(Rt);if(e)return bs=sessionStorage.getItem(nr)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new Es;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),i=await crypto.subtle.exportKey("jwk",n);return sessionStorage.setItem(Rt,JSON.stringify(i)),sessionStorage.setItem(nr,"session"),bs=!1,crypto.subtle.importKey("jwk",i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function t0(t){if(sessionStorage.getItem(nr)==="session"&&sessionStorage.getItem(Rt))return Qu(),rr=!0,ed(t);try{const e=await Xy();if(e)return e;const n=await e0();if(n)return n;const i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Dh(i),i}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),Qu(),rr=!0,ed(t)}}async function Tl(t={}){const{allowSessionFallbackCreation:e=!0}=t,n=Yy();ws!==n&&ui();const i=Wa||t0(e);Wa=i,ws=n;try{return await i}catch(r){throw ui(),r}}async function n0(t){const e=await Tl(),n=ws,i=new TextEncoder,r=crypto.getRandomValues(new Uint8Array(12)),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},e,i.encode(t)),o=new Uint8Array(r.length+s.byteLength);return o.set(r),o.set(new Uint8Array(s),r.length),{ciphertext:jh(o),keyVersion:n,sessionFallback:rr}}async function i0(t,e={}){const{isSessionCredential:n=!1}=e;try{const i=await Tl({allowSessionFallbackCreation:!1});if(rr&&!n&&!bs)throw new Es;const r=r0(t),s=r.slice(0,12),o=r.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},i,o);return new TextDecoder().decode(a)}catch(i){if(i instanceof Es)throw i;return console.error("Decryption failed:",i),null}}function jh(t){const e=new Uint8Array(t);let n="";for(let i=0;i0}let Nn="",di="",qi=null,nd=0,nt="not-configured";async function $l(){sessionStorage.getItem(Rt)&&await Tl(),Nn=await Te("flutterflow"),di=await Te("flutterflow_project_id"),f0(),rn(),Nn?Ol():(nt="not-configured",vt())}let sr=!1;function Uh(){const t=document.getElementById("api-keys-modal");We(t),Nl(),Nn&&Bl(Nn)}function Ml(){sr=!1,Uh()}function o0(){sr=!0;const t=document.getElementById("walkthrough-modal");t&&ze(t),Uh()}let id=!1;function rd(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-settings-model");if(!t||!e)return;e.value=t.value;const n=Array.from(t.options);Array.from(e.options).forEach((r,s)=>{const o=n[s];o&&(r.textContent=o.textContent)});const i=document.getElementById("composer-settings-free-notice");i&&(document.getElementById("model-selector-free-notice")?(i.hidden=!1,i.innerHTML='Free plan — Gemini only. '):i.hidden=!0)}function sd(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-image-capability"),n=document.getElementById("composer-image-capability-note");if(!t)return;const i=Gt(t.value),r=Rh(t.value);e&&(e.textContent=r?"Supported":"Not supported"),n&&(n.textContent=r?`${i} accepts reference images you attach to the prompt.`:`Images can't be attached with ${i}. Attached images are removed when you switch to it.`),Pl()}function a0(){if(sr=!1,rd(),sd(),!id){const e=document.getElementById("composer-settings-model");e&&e.addEventListener("change",()=>{const n=document.getElementById("code-generator-model");n.value=e.value,n.dispatchEvent(new Event("change")),rd(),sd()}),id=!0}const t=document.querySelector('.composer [aria-label="Generation settings"]');We("composer-settings-modal",{trigger:t})}function l0(t){t&&t.target!==t.currentTarget||ze("composer-settings-modal")}function Hh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&ze(e);const n=sr;if(sr=!1,n){const i=document.getElementById("walkthrough-modal");i&&(nt==="connected"&&Ll(),We(i))}}let en=1;function Wh(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function Bs(){const t=Wh();t.length&&t.forEach((e,n)=>{const i=n+1;e.classList.remove("wt-current","wt-done","wt-pending");const r=e.querySelector(".wt-step-num");i===en?(e.classList.add("wt-current"),r&&(r.textContent=i)):i0&&en<=t&&(en++,Bs())}function c0(){const t=document.getElementById("walkthrough-modal");t&&(en=1,Bs(),We(t))}function u0(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&ze(e);const n=document.getElementById("walkthrough-dont-show");n&&n.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function zh(){if(q.isVerified&&Tt()&&ce.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(en=1,Bs(),We(e))}}async function Nl(){const t=document.getElementById("flutterflow-api-key-input");Nn?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",d0()}function d0(){od("flutterflow","flutterflow-key-status"),od("flutterflow_project_id","flutterflow-project-status")}function od(t,e){const n=document.getElementById(e);if(!n)return;const i=n.querySelector(".key-status-dot"),r=n.querySelector("span");Ct(t)?(i.className="key-status-dot configured",r.className="text-green-600",r.textContent="User key configured"):(i.className="key-status-dot missing",r.className="text-gray-500",r.textContent="Not configured")}function rn(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff");e&&e.classList.toggle("hidden",!t)}function f0(){const t=document.getElementById("api-keys-status");if(!t)return;const e=t.querySelectorAll(".key-status-dot"),n=["flutterflow"];e.forEach((i,r)=>{const s=n[r];s==="flutterflow"?Ct("flutterflow")&&Ct("flutterflow_project_id")?(i.className="key-status-dot configured",i.title="FlutterFlow (Fully configured)"):Ct("flutterflow")||Ct("flutterflow_project_id")?(i.className="key-status-dot env",i.title="FlutterFlow (Partially configured)"):(i.className="key-status-dot missing",i.title="FlutterFlow (Not configured)"):Ct(s)?(i.className="key-status-dot configured",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (User key)"):(i.className="key-status-dot missing",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (Not configured)")}),rn()}async function h0(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select"),n=t.value.trim();n&&await td("flutterflow",n);const i=e?.value.trim()||"";if(i){if(!Ds(i)){Ee("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await td("flutterflow_project_id",i)}await $l(),n&&await Ol(),Nl();const r=document.querySelector("#api-keys-modal .bg-blue-500"),s=r.textContent;r.textContent="Saved!",r.classList.remove("bg-blue-500","hover:bg-blue-600"),r.classList.add("bg-green-500"),setTimeout(()=>{r.textContent=s,r.classList.remove("bg-green-500"),r.classList.add("bg-blue-500","hover:bg-blue-600"),Hh()},1e3)}async function p0(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(ir,za()),ui(),localStorage.removeItem(gt+"flutterflow"),localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow"),sessionStorage.removeItem(Pt+"flutterflow_project_id"),sessionStorage.removeItem(Rt),sessionStorage.removeItem(nr),localStorage.removeItem(gt+"salt"),await Qy(),localStorage.setItem(ir,za()),localStorage.removeItem(gt+"flutterflow"),localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow"),sessionStorage.removeItem(Pt+"flutterflow_project_id"),await $l();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),Nl()}function Ds(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function vt(){const t=document.getElementById("acct-ff-dot"),e=document.getElementById("acct-ff-status"),n=document.getElementById("acct-ff-endpoint"),i=document.getElementById("acct-ff-project");if(n){const o=yt();n.textContent=o.includes("staging")?"Staging":"Production"}if(i&&(i.textContent=di||"—"),!e)return;let r,s;if(!Ct("flutterflow"))r="Not connected — add your FlutterFlow API key",s="";else switch(nt){case"connected":r="Connected to FlutterFlow",s="ok";break;case"no-projects":r="Key accepted — no projects found",s="warn";break;case"unauthorized":r="API key rejected (401/403) — re-enter your key",s="bad";break;case"network-error":r="Could not reach FlutterFlow — check your network",s="bad";break;default:r="Checking connection…",s="warn";break}e.textContent=r,t&&(t.className=`acct-dot${s?" "+s:""}`)}async function Ol(){const t=await Te("flutterflow");if(!t||!Ct("flutterflow"))return nt="not-configured",vt(),null;nt="validating",vt();try{const n=await new pi(t,"","main",yt()).listProjects();return nt=n&&n.length>0?"connected":"no-projects",vt(),n}catch(e){const n=String(e&&e.message||"");return nt=/(401|403)|denied|unauthorized|scoped|list permission/i.test(n)?"unauthorized":"network-error",vt(),null}}function g0(){di="",localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow_project_id")}function m0(){g0();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML='',t.value=""),Ct("flutterflow")?(nt="validating",Bl(Nn)):nt="not-configured",vt()}function v0(t,e){const n=document.getElementById(t);n&&(n.value?e?n.style.borderColor="#22c55e":n.style.borderColor="#ef4444":n.style.borderColor="")}function _0(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const n=e.target.value.trim().length>0;v0("flutterflow-api-key-input",n)}),t.addEventListener("blur",y0(async e=>{const n=e.target.value.trim();n&&await Bl(n)},500)))}function y0(t,e){let n;return function(...r){const s=()=>{clearTimeout(n),t(...r)};clearTimeout(n),n=setTimeout(s,e)}}async function Bl(t){const e=document.getElementById("flutterflow-projects-select"),n=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',n&&n.classList.add("hidden"),(Ct("flutterflow")||t)&&(nt="validating"),vt();try{const r=await new pi(t,"","main",yt()).listProjects();if(!r||r.length===0){nt="no-projects",vt(),e.innerHTML='';return}nt="connected",vt(),e.innerHTML='',r.forEach(s=>{const o=document.createElement("option");o.value=s.id||s.projectId||"",o.textContent=s.name||s.projectName||`Project ${s.id}`,e.appendChild(o)}),di&&(e.value=di)}catch(i){console.error("Failed to fetch projects:",i);const r=String(i&&i.message||"");nt=/(401|403)|denied|unauthorized|scoped|list permission/i.test(r)?"unauthorized":"network-error",vt(),e.innerHTML='',n&&(n.textContent=`Failed to load projects: ${i.message}`,n.classList.remove("hidden"))}}function w0(t){const e=document.getElementById(t),i=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",i.innerHTML=` `):(e.type="password",i.innerHTML=` - `)}let y={step1Result:null,step2Result:null,step3Result:null,bundleSpec:null,artifactBundle:null,bundleReview:null,selectedArtifactId:null,resultsViewMode:"summary",currentStep:0,isRunning:!1,runId:0,submittedPrompt:"",submittedImages:[]};function w0(){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 b0(){y.bundleSpec=er(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function Bs(){const t=ai(y.bundleSpec);y.artifactBundle=er(y.step2Result,{id:y.bundleSpec?.id,title:y.bundleSpec?.title,description:y.bundleSpec?.description,artifactType:t.artifactType,artifactName:t.artifactName,fileName:t.fileName,dependencies:t.dependencies,relationships:y.bundleSpec?.relationships,code:y.step2Result||""});const e=Vv(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(n=>n.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=ai(y.artifactBundle).id}function Ds(){const t=er(y.step3Result,{id:y.artifactBundle?.id,title:y.artifactBundle?.title}),e=new Map(t.artifacts.map(i=>[i.id,i.review])),n=new Map(t.artifacts.filter(i=>{const r=i.review;return r&&typeof r.fixedSource=="string"&&r.fixedSource.trim()}).map(i=>[i.id,i.review.fixedSource.trim()]));y.bundleReview=er({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(i=>{const r=n.get(i.id)||null;return{...i,review:e.get(i.id)||i.review||y.step3Result||null,...r?{fixedCode:r}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function Wh(){const t=Ol();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function Ol(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(n=>n.id===y.selectedArtifactId)||ai(t)}function Bl(){return Ol().code||y.step2Result||""}async function E0(){try{await Rl()}catch(t){return console.error("checkConnection: initializeApiKeys failed:",t),!1}return!0}const Dr={production:"https://api.flutterflow.io/v2/",staging:"https://api.flutterflow.io/v2-staging/"};function S0(t,e){const n=e?.trim()?` (${e.trim().slice(0,200)})`:"";return t===401?`Your FlutterFlow API key was rejected (401 Unauthorized)${n}. Re-enter a current key under API Keys settings, then try again.`:`Listing FlutterFlow projects was denied (403)${n}. The key may be scoped to sync a single project without list permission - verify the key's access in FlutterFlow, re-enter it under API Keys settings, then retry.`}class pi{constructor(e,n,i="main",r=Dr.production){this.apiKey=e,this.baseUrl=r,this._projectId=n,this._branchName=i,this._endpoint=r}get projectId(){return this._projectId}get branchName(){return this._branchName==="main"?"":this._branchName}async exportProjectZip(){console.log(`Exporting code from FlutterFlow project: ${this.projectId}, branch: ${this.branchName||"main"}`);const e=[{project:{path:`projects/${this.projectId}`},...this.branchName?{branch_name:this.branchName}:{},export_as_module:!1,include_assets_map:!1,format:!1,export_as_debug:!1},{project_id:this.projectId,branch_name:this.branchName,include_assets:!1,export_as_module:!1}];let n=null;for(const i of e)try{const r=await fetch(`${this.baseUrl}exportCode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(i)});if(!r.ok){const a=await r.text();n=new Error(`Export failed: ${r.status} - ${a}`);continue}const s=await r.json(),o=s?.value?.project_zip||s?.project_zip;if(!o){n=new Error("Export response did not include project source.");continue}return o}catch(r){n=r}throw n||new Error("Export failed for an unknown reason.")}async fetchProjectSource(){const e=await this.exportProjectZip(),n=await JSZip.loadAsync(e,{base64:!0}),i=Object.keys(n.files).filter(a=>!n.files[a].dir&&(a==="pubspec.yaml"||a.endsWith("/pubspec.yaml"))).sort((a,l)=>a.split("/").length-l.split("/").length)[0];if(!i)throw new Error("Export did not contain a pubspec.yaml.");const r=i.slice(0,i.length-12),s=new Map,o=Object.keys(n.files).filter(a=>{if(n.files[a].dir||!a.startsWith(r))return!1;const l=a.slice(r.length);return l==="lib/flutter_flow/custom_functions.dart"||l.startsWith("lib/custom_code/")&&l.endsWith(".dart")});return await Promise.all(o.map(async a=>{s.set(a.slice(r.length),await n.files[a].async("string"))})),{pubspecYaml:await n.files[i].async("string"),files:s}}async pushCodeWithRetry(e,n=3,i=null){const r=[Dr.production,Dr.staging],s=Math.max(0,r.indexOf(this._endpoint));let o=!1,a=null;for(let l=0;lsetTimeout(p,1e3*(l+1)));continue}if(d.ok)return console.log(`Push to ${c} succeeded!`),d;a=d.status;const f=d.status<500&&!o;if(Wa(f?d.clone():d,Sh).then(h=>console.log(`Push to ${c} returned ${d.status}: ${h}`),()=>console.log(`Push to ${c} returned ${d.status} (unreadable response body)`)),d.status>=500&&(o=!0),d.status===500){console.warn(`Endpoint ${c} returned 500, trying next...`),await new Promise(h=>setTimeout(h,1e3*(l+1)));continue}if(d.status>=500)throw new Qe(`FlutterFlow reported a server error (HTTP ${d.status}), which cannot prove the push was refused — the write may have been applied before the failure. Open your FlutterFlow project to reconcile before retrying.`);if(o)throw new Qe(`The push was refused (HTTP ${d.status}), but an earlier sync attempt may already have applied it — server errors and dropped responses cannot prove a refusal. Open your FlutterFlow project to reconcile before retrying.`);return d}throw Hu({httpStatus:a})}async pushCode(e,n=null){return this.pushCodeWithRetry(e,3,n)}parseProjectsResponse(e){if(e?.success&&typeof e.value=="string")try{const i=JSON.parse(e.value);if(i&&Array.isArray(i.entries))return i.entries.map(r=>({id:r.id,name:r.project?.name||r.id}))}catch(i){console.error("Failed to parse stringified project value:",i)}const n=e?.projects||e?.items||e?.entries||(Array.isArray(e)?e:[]);return Array.isArray(n)?n:[]}async listProjects(){console.log("Listing projects for API key");const e=[`${this.baseUrl}listProjects`,"https://api.flutterflow.io/v2/l/listProjects"];let n=0,i="";for(const r of e){const s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({project_type:"ALL",deserialize_response:!0})});if(s.ok)return r!==e[0]&&console.log(`listProjects answered on legacy path ${r}`),this.parseProjectsResponse(await s.json());if(n=s.status,i=await s.text(),console.warn(`listProjects via ${r} returned ${n}: ${i}`),s.status===401||s.status===403)throw new Error(S0(s.status,i));if(s.status!==404)throw new Error(`List projects failed: ${s.status} - ${i}`)}throw new Error(`List projects failed: ${n} - ${i}`)}}function Wa(t,e){const n=t.body?.getReader?.(),i=n?(async()=>{const r=new TextDecoder;let s="";for(;;){const{done:o,value:a}=await n.read();if(o)break;s+=r.decode(a,{stream:!0})}return s+r.decode()})():Promise.resolve("");return Ul(i,e,(r,s)=>{try{n?.cancel()?.catch?.(()=>{})}catch{}s(new Error("The response body stalled before it finished."))})}async function x0(t,e=Sh){const n=t.clone();let i;try{i=JSON.parse(await Wa(t,e))}catch{let o="";try{o=await Wa(n,e)}catch{}if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:o||`HTTP ${t.status}`,errorMap:new Map};throw new Qe(`FlutterFlow accepted the sync but returned an unreadable response${o?`: ${o.slice(0,200)}`:"."}`)}if(!t.ok){let s=i.message||`HTTP ${t.status}`,o=new Map;if(i.errors)o=new Map(Object.entries(i.errors));else if(!i.message&&typeof i=="object"){const a=Object.keys(i).filter(l=>l.endsWith(".dart")&&Array.isArray(i[l]));a.length>0&&(o=new Map(Object.entries(i)),s=a.flatMap(u=>i[u].map(c=>`${u}: ${c.errorMessage}`)).join(` -`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:s,errorMap:o}}let r={};if(i.value)try{r=typeof i.value=="string"?JSON.parse(i.value):i.value}catch(s){console.warn("Ignoring malformed push response value:",s)}return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(r))}}function Dl(t,e){return{401:"Authentication failed. Please check your FlutterFlow API key.",403:"Access denied. You may not have permission to modify this project.",404:"Project not found. Please check your Project ID.",409:"Conflict detected. The project may have been modified elsewhere.",422:"Validation failed: Invalid request format",429:"Rate limit exceeded. Please try again in a few minutes.",500:"FlutterFlow server error. Please try again later.",503:"FlutterFlow service temporarily unavailable."}[t]||`FlutterFlow API error: ${`HTTP ${t}`}`}const J={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},zh=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,qh=/extends\s+State<\w+>/;function I0(t,e=""){if(t==="pubspec.yaml")return J.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return J.OTHER;if(t==="custom_functions.dart")return J.FUNCTION;if(e){const n=zh.test(e),i=qh.test(e);if(n||i)return J.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return J.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return J.FUNCTION}return J.CODE_FILE}function Vh(t,e){switch(e){case J.ACTION:return`lib/custom_code/actions/${t}`;case J.WIDGET:return`lib/custom_code/widgets/${t}`;case J.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case J.CODE_FILE:return`lib/custom_code/${t}`;case J.DEPENDENCIES:return"pubspec.yaml";case J.OTHER:return`lib/custom_code/${t}`;default:return t}}async function jl(t,e=new Map){return Av(t,e)}const za=new Map;function Gh(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function Pn(t){za.delete(Gh(t))}function Ul(t,e,n){return new Promise((i,r)=>{let s=!1;const o=(l,u,c)=>{s||(s=!0,c==="resolve"?i(u):r(u))},a=setTimeout(()=>{s||(s=!0,n(i,r))},e);t.then(l=>{clearTimeout(a),o(i,l,"resolve")},l=>{clearTimeout(a),o(r,l,"reject")})})}async function Hl(t,e,n=Eh){const i={stop:!1};return Ul((async()=>{const r=await t.pushCode(e,i);return x0(r)})(),n,(r,s)=>{i.stop=!0,s(new Qe("FlutterFlow did not answer the sync in time — the push may still have been applied. The outcome is not yet known: open your FlutterFlow project to reconcile before retrying the deploy."))})}async function Wl(t,e,n,i,r="",s=Eh){const o=o_(e,n);if(o.length===0)return{remoteFiles:n,syncFileMap:e,unverified:[],approximate:[]};const a=X_(o,r),l={...a.manifest,sources:a.sources},u=a.skipped.map(p=>p.reason);u.forEach(p=>console.warn(`[custom class deploy] ${p}`));const c=a.approximate;c.forEach(p=>console.warn(`[custom class deploy] ${p}`)),console.log(`Provisioning ${o.length} new FlutterFlow custom code file(s) before sync.`),Be.set("provision");let d=!0,f,h;try{if(h=(async()=>{let p;try{p=await fetch(Py,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:i,customClasses:o,verification:l,stream:!0})})}catch{throw new Qe("The provisioning request did not return a response. The deploy may have reached the FlutterFlow server — open your FlutterFlow project to reconcile before retrying.")}return ey(p,{onPhase:g=>{d&&Be.setSubstatus(g)},onLog:g=>{d&&console.log(`[custom class deploy] ${g}`)}})})(),f=await Ul(h,s,(p,g)=>{d=!1,g(new Qe("The deploy is still working on the FlutterFlow server, but this browser tab has stopped waiting. Your custom classes may or may not have been written — the outcome is not yet known. Open your FlutterFlow project to reconcile before retrying the deploy."))}),!f.finalResultReceived)throw Wu(f)===Le.FAILED?new Error(f.error||`FlutterFlow custom class provisioning failed (HTTP ${f.httpStatus}).`):new Qe("The connection to the FlutterFlow deploy runner dropped before it reported a result. The deploy may still be finishing on the server; open your FlutterFlow project to reconcile before retrying.");if(!f.success){const p=f.details?` ${f.details}`:"",g=`${f.error||"FlutterFlow custom class provisioning failed."}${p}`;throw Wu(f)===Le.UNCONFIRMED?new Qe(`${g} The failure arrived after the deploy began — custom classes may already be written. Open your FlutterFlow project to reconcile before retrying.`):new Error(g)}}catch(p){throw p instanceof Qe&&(Pn(t),h?.then(()=>Pn(t),()=>Pn(t))),p}return Pn(t),f.verificationSkipped&&(console.warn(`[custom class deploy] ${f.verificationSkipped}`),u.push(f.verificationSkipped)),{remoteFiles:n,syncFileMap:a_(e,o),unverified:u,approximate:c,provisionSucceeded:!0}}async function zl(t,e={}){const n=Gh(t);let i=za.get(n);if(i===void 0){try{i=await t.fetchProjectSource()}catch(l){throw new Error(`Could not read your project's pubspec.yaml (${l.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=wh(i.pubspecYaml);if(!a.valid)throw new Error(`Your project's pubspec.yaml could not be read reliably (${a.errors.join("; ")}). Deploy was stopped so your existing package dependencies aren't overwritten.`);za.set(n,i)}const r=await _y(i.pubspecYaml,e),s=G_(i.pubspecYaml,r.overrides),o=V_(s.yaml,r.additions);return r.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>`${a}: ${r.additions[a]||"any"}`).join(", "),r.sdk.dartSdkFloor?`(resolved for Dart ${r.sdk.dartSdkFloor})`:""),r.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:s.overridden,warnings:r.warnings,remoteFiles:i.files}}function k0(t){const e=[],n=[];t.content.length>5e4&&n.push("Code file is large (>50KB). This may take longer to commit."),t.content.length>1e5&&e.push("Code file is too large (>100KB). Consider splitting into smaller components.");const i=t.content.split(` -`).length;i>500&&n.push(`Code has ${i} lines. Consider breaking it into smaller widgets.`),t.content.includes("setState")&&t.codeType===J.ACTION&&n.push("Using setState in a Custom Action may not work as expected. Consider using a Custom Widget."),t.content.includes("dynamic")&&!t.content.includes("?")&&n.push('Code uses "dynamic" types. Consider adding explicit types for better null safety.'),t.content.match(/Color\(0xFF[0-9A-Fa-f]{6}\)/)&&n.push("Code contains hardcoded colors. Consider using FlutterFlowTheme.of(context) for theme consistency.");const r=t.content.match(/print\s*\(/g);r&&r.length>3&&n.push(`Code contains ${r.length} print statements. Consider removing debug prints before committing.`);const s=I_(t.content);if(s&&e.push(`FlutterFlow cannot format this code - ${s}. Fix or regenerate before committing.`),t.codeType===J.WIDGET){const o=dh(t.content),a=E_(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=`${fh(o[0])}`;e.push(`Widget class name "${o[0]}" does not match the file name "${t.fileName}". FlutterFlow derives the widget from the file name, so it will report "No widget ${a} found". Rename the file to "${l}" or the class to match before committing.`)}}return{canProceed:e.length===0,issues:e,warnings:n}}function Kh(t,e={}){const{artifactType:n="CustomWidget",artifactName:i="GeneratedCode",fileName:r}=e,s=w_(t);let o=r||i;if(n==="CustomFunction")o="custom_functions.dart";else if(n==="CustomWidget"){const u=dh(s)[0],c=u?fh(u):null;c&&o!==c?(console.warn(`Commit file name "${o}" does not match declared widget class "${u}"; renaming to "${c}" so FlutterFlow can find the widget.`),o=c):o.endsWith(".dart")||(o+=".dart")}else o.endsWith(".dart")||(o+=".dart");let a=J.CODE_FILE;switch(n){case"CustomAction":a=J.ACTION;break;case"CustomWidget":a=J.WIDGET;break;case"CustomFunction":a=J.FUNCTION;break;case"CustomClass":case"CodeFile":a=J.CODE_FILE;break}let l="";return a===J.WIDGET?l=`// Automatic FlutterFlow imports + `)}let y={step1Result:null,step2Result:null,step3Result:null,bundleSpec:null,artifactBundle:null,bundleReview:null,selectedArtifactId:null,resultsViewMode:"summary",currentStep:0,isRunning:!1,runId:0,submittedPrompt:"",submittedImages:[]};function b0(){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 E0(){y.bundleSpec=er(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function js(){const t=ai(y.bundleSpec);y.artifactBundle=er(y.step2Result,{id:y.bundleSpec?.id,title:y.bundleSpec?.title,description:y.bundleSpec?.description,artifactType:t.artifactType,artifactName:t.artifactName,fileName:t.fileName,dependencies:t.dependencies,relationships:y.bundleSpec?.relationships,code:y.step2Result||""});const e=Gv(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(n=>n.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=ai(y.artifactBundle).id}function Us(){const t=er(y.step3Result,{id:y.artifactBundle?.id,title:y.artifactBundle?.title}),e=new Map(t.artifacts.map(i=>[i.id,i.review])),n=new Map(t.artifacts.filter(i=>{const r=i.review;return r&&typeof r.fixedSource=="string"&&r.fixedSource.trim()}).map(i=>[i.id,i.review.fixedSource.trim()]));y.bundleReview=er({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(i=>{const r=n.get(i.id)||null;return{...i,review:e.get(i.id)||i.review||y.step3Result||null,...r?{fixedCode:r}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function qh(){const t=Dl();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function Dl(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(n=>n.id===y.selectedArtifactId)||ai(t)}function jl(){return Dl().code||y.step2Result||""}async function S0(){try{await $l()}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/"};function x0(t,e){const n=e?.trim()?` (${e.trim().slice(0,200)})`:"";return t===401?`Your FlutterFlow API key was rejected (401 Unauthorized)${n}. Re-enter a current key under API Keys settings, then try again.`:`Listing FlutterFlow projects was denied (403)${n}. The key may be scoped to sync a single project without list permission - verify the key's access in FlutterFlow, re-enter it under API Keys settings, then retry.`}class pi{constructor(e,n,i="main",r=Ur.production){this.apiKey=e,this.baseUrl=r,this._projectId=n,this._branchName=i,this._endpoint=r}get projectId(){return this._projectId}get branchName(){return this._branchName==="main"?"":this._branchName}async exportProjectZip(){console.log(`Exporting code from FlutterFlow project: ${this.projectId}, branch: ${this.branchName||"main"}`);const e=[{project:{path:`projects/${this.projectId}`},...this.branchName?{branch_name:this.branchName}:{},export_as_module:!1,include_assets_map:!1,format:!1,export_as_debug:!1},{project_id:this.projectId,branch_name:this.branchName,include_assets:!1,export_as_module:!1}];let n=null;for(const i of e)try{const r=await fetch(`${this.baseUrl}exportCode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(i)});if(!r.ok){const a=await r.text();n=new Error(`Export failed: ${r.status} - ${a}`);continue}const s=await r.json(),o=s?.value?.project_zip||s?.project_zip;if(!o){n=new Error("Export response did not include project source.");continue}return o}catch(r){n=r}throw n||new Error("Export failed for an unknown reason.")}async fetchProjectSource(){const e=await this.exportProjectZip(),n=await JSZip.loadAsync(e,{base64:!0}),i=Object.keys(n.files).filter(a=>!n.files[a].dir&&(a==="pubspec.yaml"||a.endsWith("/pubspec.yaml"))).sort((a,l)=>a.split("/").length-l.split("/").length)[0];if(!i)throw new Error("Export did not contain a pubspec.yaml.");const r=i.slice(0,i.length-12),s=new Map,o=Object.keys(n.files).filter(a=>{if(n.files[a].dir||!a.startsWith(r))return!1;const l=a.slice(r.length);return l==="lib/flutter_flow/custom_functions.dart"||l.startsWith("lib/custom_code/")&&l.endsWith(".dart")});return await Promise.all(o.map(async a=>{s.set(a.slice(r.length),await n.files[a].async("string"))})),{pubspecYaml:await n.files[i].async("string"),files:s}}async pushCodeWithRetry(e,n=3,i=null){const r=[Ur.production,Ur.staging],s=Math.max(0,r.indexOf(this._endpoint));let o=!1,a=null;for(let l=0;lsetTimeout(p,1e3*(l+1)));continue}if(d.ok)return console.log(`Push to ${c} succeeded!`),d;a=d.status;const h=d.status<500&&!o;if(qa(h?d.clone():d,Ih).then(f=>console.log(`Push to ${c} returned ${d.status}: ${f}`),()=>console.log(`Push to ${c} returned ${d.status} (unreadable response body)`)),d.status>=500&&(o=!0),d.status===500){console.warn(`Endpoint ${c} returned 500, trying next...`),await new Promise(f=>setTimeout(f,1e3*(l+1)));continue}if(d.status>=500)throw new Qe(`FlutterFlow reported a server error (HTTP ${d.status}), which cannot prove the push was refused — the write may have been applied before the failure. Open your FlutterFlow project to reconcile before retrying.`);if(o)throw new Qe(`The push was refused (HTTP ${d.status}), but an earlier sync attempt may already have applied it — server errors and dropped responses cannot prove a refusal. Open your FlutterFlow project to reconcile before retrying.`);return d}throw zu({httpStatus:a})}async pushCode(e,n=null){return this.pushCodeWithRetry(e,3,n)}parseProjectsResponse(e){if(e?.success&&typeof e.value=="string")try{const i=JSON.parse(e.value);if(i&&Array.isArray(i.entries))return i.entries.map(r=>({id:r.id,name:r.project?.name||r.id}))}catch(i){console.error("Failed to parse stringified project value:",i)}const n=e?.projects||e?.items||e?.entries||(Array.isArray(e)?e:[]);return Array.isArray(n)?n:[]}async listProjects(){console.log("Listing projects for API key");const e=[`${this.baseUrl}listProjects`,"https://api.flutterflow.io/v2/l/listProjects"];let n=0,i="";for(const r of e){const s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({project_type:"ALL",deserialize_response:!0})});if(s.ok)return r!==e[0]&&console.log(`listProjects answered on legacy path ${r}`),this.parseProjectsResponse(await s.json());if(n=s.status,i=await s.text(),console.warn(`listProjects via ${r} returned ${n}: ${i}`),s.status===401||s.status===403)throw new Error(x0(s.status,i));if(s.status!==404)throw new Error(`List projects failed: ${s.status} - ${i}`)}throw new Error(`List projects failed: ${n} - ${i}`)}}function qa(t,e){const n=t.body?.getReader?.(),i=n?(async()=>{const r=new TextDecoder;let s="";for(;;){const{done:o,value:a}=await n.read();if(o)break;s+=r.decode(a,{stream:!0})}return s+r.decode()})():Promise.resolve("");return Wl(i,e,(r,s)=>{try{n?.cancel()?.catch?.(()=>{})}catch{}s(new Error("The response body stalled before it finished."))})}async function I0(t,e=Ih){const n=t.clone();let i;try{i=JSON.parse(await qa(t,e))}catch{let o="";try{o=await qa(n,e)}catch{}if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:o||`HTTP ${t.status}`,errorMap:new Map};throw new Qe(`FlutterFlow accepted the sync but returned an unreadable response${o?`: ${o.slice(0,200)}`:"."}`)}if(!t.ok){let s=i.message||`HTTP ${t.status}`,o=new Map;if(i.errors)o=new Map(Object.entries(i.errors));else if(!i.message&&typeof i=="object"){const a=Object.keys(i).filter(l=>l.endsWith(".dart")&&Array.isArray(i[l]));a.length>0&&(o=new Map(Object.entries(i)),s=a.flatMap(u=>i[u].map(c=>`${u}: ${c.errorMessage}`)).join(` +`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:s,errorMap:o}}let r={};if(i.value)try{r=typeof i.value=="string"?JSON.parse(i.value):i.value}catch(s){console.warn("Ignoring malformed push response value:",s)}return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(r))}}function Ul(t,e){return{401:"Authentication failed. Please check your FlutterFlow API key.",403:"Access denied. You may not have permission to modify this project.",404:"Project not found. Please check your Project ID.",409:"Conflict detected. The project may have been modified elsewhere.",422:"Validation failed: Invalid request format",429:"Rate limit exceeded. Please try again in a few minutes.",500:"FlutterFlow server error. Please try again later.",503:"FlutterFlow service temporarily unavailable."}[t]||`FlutterFlow API error: ${`HTTP ${t}`}`}const J={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},Vh=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,Gh=/extends\s+State<\w+>/;function k0(t,e=""){if(t==="pubspec.yaml")return J.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return J.OTHER;if(t==="custom_functions.dart")return J.FUNCTION;if(e){const n=Vh.test(e),i=Gh.test(e);if(n||i)return J.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return J.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return J.FUNCTION}return J.CODE_FILE}function Kh(t,e){switch(e){case J.ACTION:return`lib/custom_code/actions/${t}`;case J.WIDGET:return`lib/custom_code/widgets/${t}`;case J.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case J.CODE_FILE:return`lib/custom_code/${t}`;case J.DEPENDENCIES:return"pubspec.yaml";case J.OTHER:return`lib/custom_code/${t}`;default:return t}}async function Hl(t,e=new Map){return Pv(t,e)}const Va=new Map,Rn=new Map;function or(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function ar(t){Va.delete(or(t))}function C0(t,e){const n=or(t),i=Rn.get(n)??new Set;for(const r of e)i.add(r);Rn.set(n,i)}function A0(t,e){const n=Rn.get(or(t));if(n){for(const i of e)n.delete(i);n.size===0&&Rn.delete(or(t))}}function Wl(t,e,n){return new Promise((i,r)=>{let s=!1;const o=(l,u,c)=>{s||(s=!0,c==="resolve"?i(u):r(u))},a=setTimeout(()=>{s||(s=!0,n(i,r))},e);t.then(l=>{clearTimeout(a),o(i,l,"resolve")},l=>{clearTimeout(a),o(r,l,"reject")})})}async function zl(t,e,n=xh){const i={stop:!1};return Wl((async()=>{const r=await t.pushCode(e,i);return I0(r)})(),n,(r,s)=>{i.stop=!0,s(new Qe("FlutterFlow did not answer the sync in time — the push may still have been applied. The outcome is not yet known: open your FlutterFlow project to reconcile before retrying the deploy."))})}async function ql(t,e,n,i,r="",s=xh){const o=a_(e,n);if(o.length===0)return{remoteFiles:n,syncFileMap:e,unverified:[],approximate:[]};const a=Q_(o,r),l={...a.manifest,sources:a.sources},u=a.skipped.map(f=>f.reason);u.forEach(f=>console.warn(`[custom class deploy] ${f}`));const c=a.approximate;c.forEach(f=>console.warn(`[custom class deploy] ${f}`)),console.log(`Provisioning ${o.length} new FlutterFlow custom code file(s) before sync.`),Be.set("provision");let d=!0,h;try{const f=(async()=>{let p;try{p=await fetch(Fy,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:i,customClasses:o,verification:l,stream:!0})})}catch{throw new Qe("The provisioning request did not return a response. The deploy may have reached the FlutterFlow server — open your FlutterFlow project to reconcile before retrying.")}return ty(p,{onPhase:g=>{d&&Be.setSubstatus(g)},onLog:g=>{d&&console.log(`[custom class deploy] ${g}`)}})})();if(h=await Wl(f,s,(p,g)=>{d=!1,g(new Qe("The deploy is still working on the FlutterFlow server, but this browser tab has stopped waiting. Your custom classes may or may not have been written — the outcome is not yet known. Open your FlutterFlow project to reconcile before retrying the deploy."))}),!h.finalResultReceived)throw qu(h)===Le.FAILED?new Error(h.error||`FlutterFlow custom class provisioning failed (HTTP ${h.httpStatus}).`):new Qe("The connection to the FlutterFlow deploy runner dropped before it reported a result. The deploy may still be finishing on the server; open your FlutterFlow project to reconcile before retrying.");if(!h.success){const p=h.details?` ${h.details}`:"",g=`${h.error||"FlutterFlow custom class provisioning failed."}${p}`;throw qu(h)===Le.UNCONFIRMED?new Qe(`${g} The failure arrived after the deploy began — custom classes may already be written. Open your FlutterFlow project to reconcile before retrying.`):new Error(g)}}catch(f){throw f instanceof Qe&&(ar(t),C0(t,o.map(p=>p.path))),f}return ar(t),A0(t,o.map(f=>f.path)),h.verificationSkipped&&(console.warn(`[custom class deploy] ${h.verificationSkipped}`),u.push(h.verificationSkipped)),{remoteFiles:n,syncFileMap:l_(e,o),unverified:u,approximate:c,provisionSucceeded:!0}}async function Vl(t,e={}){const n=or(t);let i=Va.get(n);if(i===void 0){try{i=await t.fetchProjectSource()}catch(u){throw new Error(`Could not read your project's pubspec.yaml (${u.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=Eh(i.pubspecYaml);if(!a.valid)throw new Error(`Your project's pubspec.yaml could not be read reliably (${a.errors.join("; ")}). Deploy was stopped so your existing package dependencies aren't overwritten.`);const l=Rn.get(n);if(l){for(const u of[...l])i.files.has(u)&&l.delete(u);l.size===0&&Rn.delete(n)}Rn.has(n)||Va.set(n,i)}const r=await yy(i.pubspecYaml,e),s=K_(i.pubspecYaml,r.overrides),o=G_(s.yaml,r.additions);return r.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>`${a}: ${r.additions[a]||"any"}`).join(", "),r.sdk.dartSdkFloor?`(resolved for Dart ${r.sdk.dartSdkFloor})`:""),r.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:s.overridden,warnings:r.warnings,remoteFiles:i.files}}function P0(t){const e=[],n=[];t.content.length>5e4&&n.push("Code file is large (>50KB). This may take longer to commit."),t.content.length>1e5&&e.push("Code file is too large (>100KB). Consider splitting into smaller components.");const i=t.content.split(` +`).length;i>500&&n.push(`Code has ${i} lines. Consider breaking it into smaller widgets.`),t.content.includes("setState")&&t.codeType===J.ACTION&&n.push("Using setState in a Custom Action may not work as expected. Consider using a Custom Widget."),t.content.includes("dynamic")&&!t.content.includes("?")&&n.push('Code uses "dynamic" types. Consider adding explicit types for better null safety.'),t.content.match(/Color\(0xFF[0-9A-Fa-f]{6}\)/)&&n.push("Code contains hardcoded colors. Consider using FlutterFlowTheme.of(context) for theme consistency.");const r=t.content.match(/print\s*\(/g);r&&r.length>3&&n.push(`Code contains ${r.length} print statements. Consider removing debug prints before committing.`);const s=k_(t.content);if(s&&e.push(`FlutterFlow cannot format this code - ${s}. Fix or regenerate before committing.`),t.codeType===J.WIDGET){const o=hh(t.content),a=S_(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=`${ph(o[0])}`;e.push(`Widget class name "${o[0]}" does not match the file name "${t.fileName}". FlutterFlow derives the widget from the file name, so it will report "No widget ${a} found". Rename the file to "${l}" or the class to match before committing.`)}}return{canProceed:e.length===0,issues:e,warnings:n}}function Yh(t,e={}){const{artifactType:n="CustomWidget",artifactName:i="GeneratedCode",fileName:r}=e,s=b_(t);let o=r||i;if(n==="CustomFunction")o="custom_functions.dart";else if(n==="CustomWidget"){const u=hh(s)[0],c=u?ph(u):null;c&&o!==c?(console.warn(`Commit file name "${o}" does not match declared widget class "${u}"; renaming to "${c}" so FlutterFlow can find the widget.`),o=c):o.endsWith(".dart")||(o+=".dart")}else o.endsWith(".dart")||(o+=".dart");let a=J.CODE_FILE;switch(n){case"CustomAction":a=J.ACTION;break;case"CustomWidget":a=J.WIDGET;break;case"CustomFunction":a=J.FUNCTION;break;case"CustomClass":case"CodeFile":a=J.CODE_FILE;break}let l="";return a===J.WIDGET?l=`// Automatic FlutterFlow imports import '/flutter_flow/flutter_flow_theme.dart'; import '/flutter_flow/flutter_flow_util.dart'; import 'package:flutter/material.dart'; @@ -111,15 +111,15 @@ import '/flutter_flow/lat_lng.dart'; import '/flutter_flow/place.dart'; import '/flutter_flow/uploaded_file.dart'; -`),{content:Yv(s,l),fileName:o,codeType:a,artifactType:n,artifactName:i}}function C0(t){const e={};for(const n of bl(t))e[n]="";return e}function A0(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 P0(t,e,n,i=new Set,r=""){const s=[],o=zh.test(e),a=qh.test(e);return n===J.WIDGET&&!o&&!a&&s.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:s.length===0,errors:s}}function js(t){const e=[],n=[];if(!t||t.size===0)return e.push("No files to commit"),{valid:!1,errors:e,warnings:n};const i=new Set(Array.from(t.values()).flatMap(r=>As(r.content||"")));for(const[r,s]of t.entries()){if((!s.content||s.content.trim().length===0)&&e.push(`File ${r} is empty`),s.content&&s.content.length>1e5&&n.push(`File ${r} is very large (>100KB)`),r.endsWith(".dart")){const o=P0(r,s.content,s.type,i,s.artifactName);o.valid||e.push(...o.errors.map(a=>`${r}: ${a}`))}if(r==="pubspec.yaml"){const o=wh(s.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:n}}const ee={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},G={currentState:ee.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=ee.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(ee).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===ee.PREPARING&&(this.startTime=Date.now()),(t===ee.SUCCESS||t===ee.ERROR)&&(this.endTime=Date.now()),typeof window<"u"&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("commitStateChange",{detail:{state:t,commitState:this}})),console.log(`Commit state changed to: ${t}`)},setError(t){this.error=t,this.setState(ee.ERROR)},setSuccess(t){this.result=t,this.setState(ee.SUCCESS)},setProgress(t,e){this.filesProcessed=t,this.totalFiles=e},getElapsedTime(){return this.startTime?(this.endTime||Date.now())-this.startTime:null},isInProgress(){return this.currentState===ee.PREPARING||this.currentState===ee.VALIDATING||this.currentState===ee.PUSHING}};async function F0(t,e,n={}){let{codeType:i="W"}=n;const{pubspecDeps:r={},artifactName:s=e}=n;i==="CustomWidget"&&(i=J.WIDGET),i==="CustomAction"&&(i=J.ACTION),i==="CustomFunction"&&(i=J.FUNCTION),i==="CustomClass"&&(i=J.CODE_FILE),i==="CodeFile"&&(i=J.CODE_FILE),G.reset(),G.setState(ee.PREPARING);try{const o=await Te("flutterflow"),a=await Te("flutterflow_project_id");if(!o||!a)throw new Error("FlutterFlow credentials not configured. Please set your API key and Project ID in the API Keys settings.");if(!Os(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=yt(),u=new pi(o,a,"main",l);G.setState(ee.VALIDATING);const c=new Map,d=i||I0(e,t),f=Vh(e,d);c.set(e,{artifactName:s,content:t,type:d,path:f}),G.setProgress(0,c.size);const h=js(c);if(!h.valid)throw new Error(`Validation failed: -${h.errors.join(` -`)}`);const p=await zl(u,r),g=p.yaml,m=await Wl(u,c,p.remoteFiles,`Provision ${s} custom class`,g),v=await jl(m.syncFileMap,m.remoteFiles),E=new Map(m.syncFileMap);E.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),Be.set("package");const S=await ql(E),_={project_id:a,zipped_custom_code:S,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};G.setState(ee.PUSHING),G.setProgress(1,c.size),Pn(u),Be.set("push");const b=await Hl(u,_);if(b.success)G.setSuccess({fileCount:c.size,projectId:a,warnings:b.errorMap&&b.errorMap.size>0?Array.from(b.errorMap.entries()):[]});else{const k=b.errorMessage||Dl(b.responseCode),T=new Error(k);throw T.remoteRefusal=!0,T}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:p.added,unverified:m.unverified,approximate:m.approximate,warnings:b.errorMap?Array.from(b.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),G.setError(o),o instanceof Qe?{success:!1,unconfirmed:!0,error:o.message,state:G.currentState}:{success:!1,error:o.message,remoteRefusal:o.remoteRefusal===!0,state:G.currentState}}}async function ql(t){const e=new JSZip;for(const[n,i]of t.entries())e.file(n,i.content);return e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}async function R0(t,e={}){const{artifactType:n,artifactName:i,fileName:r,pipelineResult:s}=e;console.log(`Starting commit for ${i} (${n})`);let o=!1;const a={projectId:null,endpoint:yt(),artifactType:n,artifactName:i,fileName:r};try{G.setState(ee.PREPARING);const l=Kh(t,{artifactType:n,artifactName:i,fileName:r}),u=C0(l.content);console.log("Detected dependencies:",u),G.setState(ee.VALIDATING);const c=await Te("flutterflow"),d=qi||await Te("flutterflow_project_id");if(!c)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!d)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Os(d))throw new Error("Invalid FlutterFlow Project ID format.");a.projectId=d;const f=new Map;f.set(l.fileName,{artifactName:i,content:l.content,type:l.codeType,path:Vh(l.fileName,l.codeType),functionName:l.codeType===J.FUNCTION?i:void 0}),G.setProgress(0,f.size);const h=js(f);if(!h.valid)throw new Error(`File validation failed: -${h.errors.join(` -`)}`);h.warnings.length>0&&console.warn("Validation warnings:",h.warnings),G.setState(ee.PUSHING);const p=yt(),g=new pi(c,d,"main",p),m=await zl(g,u),v=m.yaml,E=await Wl(g,f,m.remoteFiles,`Provision ${i} custom class`,v);o=E.provisionSucceeded===!0;const S=await jl(E.syncFileMap,E.remoteFiles),_=new Map(E.syncFileMap);_.set("pubspec.yaml",{content:v,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Be.set("package");const b=await ql(_),k={project_id:d,zipped_custom_code:b,uid:`web_${Date.now()}`,branch_name:g.branchName,serialized_yaml:v,file_map:S.fileMapContents,functions_map:S.functionsMapContents};G.setProgress(1,f.size),Pn(g),Be.set("push");const T=await Hl(g,k);if(T.success){const x={...A0(l,s),projectId:d};return G.setSuccess({...x,fileCount:f.size,warnings:T.errorMap?Array.from(T.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${l.fileName} to FlutterFlow`,metadata:x,targetIdentity:a,addedDependencies:m.added,unverified:E.unverified,approximate:E.approximate,warnings:T.errorMap?Array.from(T.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}else{const x=T.errorMessage||Dl(T.responseCode),F=new Error(x);throw F.errorMap=T.errorMap,F.remoteRefusal=!0,F}}catch(l){console.error("Commit execution failed:",l),G.setError(l);let u=new Map;if(l.errorMap)u=l.errorMap;else if(l.message&&l.message.includes("{"))try{const c=l.message.match(/\{[\s\S]*\}/);if(c){const d=JSON.parse(c[0]);u=new Map(Object.entries(d))}}catch(c){console.warn("Failed to parse error map from commit response:",c)}return l instanceof Qe?{success:!1,unconfirmed:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:o?{success:!1,partial:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:l.message,errorMap:u,remoteRefusal:l.remoteRefusal===!0,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function T0(t,e={}){const{pipelineResult:n}=e;let i=!1;const r={projectId:null,endpoint:yt(),artifactType:"Bundle",artifactName:t?.title,fileName:t?.fileEntries?`${t.fileEntries.length} artifacts`:"bundle"};try{if(G.setState(ee.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: +`),{content:Jv(s,l),fileName:o,codeType:a,artifactType:n,artifactName:i}}function F0(t){const e={};for(const n of Sl(t))e[n]="";return e}function R0(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 T0(t,e,n,i=new Set,r=""){const s=[],o=Vh.test(e),a=Gh.test(e);return n===J.WIDGET&&!o&&!a&&s.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:s.length===0,errors:s}}function Hs(t){const e=[],n=[];if(!t||t.size===0)return e.push("No files to commit"),{valid:!1,errors:e,warnings:n};const i=new Set(Array.from(t.values()).flatMap(r=>Fs(r.content||"")));for(const[r,s]of t.entries()){if((!s.content||s.content.trim().length===0)&&e.push(`File ${r} is empty`),s.content&&s.content.length>1e5&&n.push(`File ${r} is very large (>100KB)`),r.endsWith(".dart")){const o=T0(r,s.content,s.type,i,s.artifactName);o.valid||e.push(...o.errors.map(a=>`${r}: ${a}`))}if(r==="pubspec.yaml"){const o=Eh(s.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:n}}const ee={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},G={currentState:ee.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=ee.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(ee).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===ee.PREPARING&&(this.startTime=Date.now()),(t===ee.SUCCESS||t===ee.ERROR)&&(this.endTime=Date.now()),typeof window<"u"&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("commitStateChange",{detail:{state:t,commitState:this}})),console.log(`Commit state changed to: ${t}`)},setError(t){this.error=t,this.setState(ee.ERROR)},setSuccess(t){this.result=t,this.setState(ee.SUCCESS)},setProgress(t,e){this.filesProcessed=t,this.totalFiles=e},getElapsedTime(){return this.startTime?(this.endTime||Date.now())-this.startTime:null},isInProgress(){return this.currentState===ee.PREPARING||this.currentState===ee.VALIDATING||this.currentState===ee.PUSHING}};async function $0(t,e,n={}){let{codeType:i="W"}=n;const{pubspecDeps:r={},artifactName:s=e}=n;i==="CustomWidget"&&(i=J.WIDGET),i==="CustomAction"&&(i=J.ACTION),i==="CustomFunction"&&(i=J.FUNCTION),i==="CustomClass"&&(i=J.CODE_FILE),i==="CodeFile"&&(i=J.CODE_FILE),G.reset(),G.setState(ee.PREPARING);try{const o=await Te("flutterflow"),a=await Te("flutterflow_project_id");if(!o||!a)throw new Error("FlutterFlow credentials not configured. Please set your API key and Project ID in the API Keys settings.");if(!Ds(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=yt(),u=new pi(o,a,"main",l);G.setState(ee.VALIDATING);const c=new Map,d=i||k0(e,t),h=Kh(e,d);c.set(e,{artifactName:s,content:t,type:d,path:h}),G.setProgress(0,c.size);const f=Hs(c);if(!f.valid)throw new Error(`Validation failed: +${f.errors.join(` +`)}`);const p=await Vl(u,r),g=p.yaml,m=await ql(u,c,p.remoteFiles,`Provision ${s} custom class`,g),v=await Hl(m.syncFileMap,m.remoteFiles),E=new Map(m.syncFileMap);E.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),Be.set("package");const S=await Gl(E),_={project_id:a,zipped_custom_code:S,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};G.setState(ee.PUSHING),G.setProgress(1,c.size),ar(u),Be.set("push");const b=await zl(u,_);if(b.success)G.setSuccess({fileCount:c.size,projectId:a,warnings:b.errorMap&&b.errorMap.size>0?Array.from(b.errorMap.entries()):[]});else{const k=b.errorMessage||Ul(b.responseCode),T=new Error(k);throw T.remoteRefusal=!0,T}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:p.added,unverified:m.unverified,approximate:m.approximate,warnings:b.errorMap?Array.from(b.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),G.setError(o),o instanceof Qe?{success:!1,unconfirmed:!0,error:o.message,state:G.currentState}:{success:!1,error:o.message,remoteRefusal:o.remoteRefusal===!0,state:G.currentState}}}async function Gl(t){const e=new JSZip;for(const[n,i]of t.entries())e.file(n,i.content);return e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}async function M0(t,e={}){const{artifactType:n,artifactName:i,fileName:r,pipelineResult:s}=e;console.log(`Starting commit for ${i} (${n})`);let o=!1;const a={projectId:null,endpoint:yt(),artifactType:n,artifactName:i,fileName:r};try{G.setState(ee.PREPARING);const l=Yh(t,{artifactType:n,artifactName:i,fileName:r}),u=F0(l.content);console.log("Detected dependencies:",u),G.setState(ee.VALIDATING);const c=await Te("flutterflow"),d=qi||await Te("flutterflow_project_id");if(!c)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!d)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Ds(d))throw new Error("Invalid FlutterFlow Project ID format.");a.projectId=d;const h=new Map;h.set(l.fileName,{artifactName:i,content:l.content,type:l.codeType,path:Kh(l.fileName,l.codeType),functionName:l.codeType===J.FUNCTION?i:void 0}),G.setProgress(0,h.size);const f=Hs(h);if(!f.valid)throw new Error(`File validation failed: +${f.errors.join(` +`)}`);f.warnings.length>0&&console.warn("Validation warnings:",f.warnings),G.setState(ee.PUSHING);const p=yt(),g=new pi(c,d,"main",p),m=await Vl(g,u),v=m.yaml,E=await ql(g,h,m.remoteFiles,`Provision ${i} custom class`,v);o=E.provisionSucceeded===!0;const S=await Hl(E.syncFileMap,E.remoteFiles),_=new Map(E.syncFileMap);_.set("pubspec.yaml",{content:v,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Be.set("package");const b=await Gl(_),k={project_id:d,zipped_custom_code:b,uid:`web_${Date.now()}`,branch_name:g.branchName,serialized_yaml:v,file_map:S.fileMapContents,functions_map:S.functionsMapContents};G.setProgress(1,h.size),ar(g),Be.set("push");const T=await zl(g,k);if(T.success){const x={...R0(l,s),projectId:d};return G.setSuccess({...x,fileCount:h.size,warnings:T.errorMap?Array.from(T.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${l.fileName} to FlutterFlow`,metadata:x,targetIdentity:a,addedDependencies:m.added,unverified:E.unverified,approximate:E.approximate,warnings:T.errorMap?Array.from(T.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}else{const x=T.errorMessage||Ul(T.responseCode),F=new Error(x);throw F.errorMap=T.errorMap,F.remoteRefusal=!0,F}}catch(l){console.error("Commit execution failed:",l),G.setError(l);let u=new Map;if(l.errorMap)u=l.errorMap;else if(l.message&&l.message.includes("{"))try{const c=l.message.match(/\{[\s\S]*\}/);if(c){const d=JSON.parse(c[0]);u=new Map(Object.entries(d))}}catch(c){console.warn("Failed to parse error map from commit response:",c)}return l instanceof Qe?{success:!1,unconfirmed:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:o?{success:!1,partial:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:l.message,errorMap:u,remoteRefusal:l.remoteRefusal===!0,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function L0(t,e={}){const{pipelineResult:n}=e;let i=!1;const r={projectId:null,endpoint:yt(),artifactType:"Bundle",artifactName:t?.title,fileName:t?.fileEntries?`${t.fileEntries.length} artifacts`:"bundle"};try{if(G.setState(ee.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: ${t.errors.join(` -`)}`);const s=new Map(t.fileEntries.map(b=>[b.fileName,{artifactId:b.artifactId,artifactName:b.artifactName,content:b.content,type:b.type,path:b.path,functionName:b.type===J.FUNCTION?b.artifactName:void 0}]));G.setProgress(0,s.size);const o=js(s);if(!o.valid)throw new Error(`File validation failed: +`)}`);const s=new Map(t.fileEntries.map(b=>[b.fileName,{artifactId:b.artifactId,artifactName:b.artifactName,content:b.content,type:b.type,path:b.path,functionName:b.type===J.FUNCTION?b.artifactName:void 0}]));G.setProgress(0,s.size);const o=Hs(s);if(!o.valid)throw new Error(`File validation failed: ${o.errors.join(` -`)}`);G.setState(ee.VALIDATING);const a=await Te("flutterflow"),l=qi||await Te("flutterflow_project_id");if(!a)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!l)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Os(l))throw new Error("Invalid FlutterFlow Project ID format.");r.projectId=l,G.setState(ee.PUSHING);const u=yt(),c=new pi(a,l,"main",u),d=await zl(c,t.dependencies),f=d.yaml,h=await Wl(c,s,d.remoteFiles,`Provision ${t.title} custom classes`,f);i=h.provisionSucceeded===!0;const p=await jl(h.syncFileMap,h.remoteFiles),g=new Map(h.syncFileMap);g.set("pubspec.yaml",{content:f,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Be.set("package");const m=await ql(g),v={project_id:l,zipped_custom_code:m,uid:`web_${Date.now()}`,branch_name:c.branchName,serialized_yaml:f,file_map:p.fileMapContents,functions_map:p.functionsMapContents};G.setProgress(1,s.size),Pn(c),Be.set("push");const E=await Hl(c,v);if(E.success){const b={...n,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((k,T)=>k+T.content.length,0),projectId:l};return G.setSuccess({...b,fileCount:s.size,warnings:E.errorMap?Array.from(E.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:b,targetIdentity:r,addedDependencies:d.added,unverified:h.unverified,approximate:h.approximate,warnings:E.errorMap?Array.from(E.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}const S=E.errorMessage||Dl(E.responseCode),_=new Error(S);throw _.errorMap=E.errorMap,_.remoteRefusal=!0,_}catch(s){console.error("Bundle commit execution failed:",s),G.setError(s);const o=s.errorMap||new Map;return s instanceof Qe?{success:!1,unconfirmed:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:i?{success:!1,partial:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function $0(t,e=[]){const n=vl("architect");try{return await Ss("architect",Mh,mv(t),n,e)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Prompt Architect failed: ${i.message}`)}}async function Us(t,e,n=[],i){const r=vv(t),s=vl("generator",y.bundleSpec);try{return await Ss("generator",e,r,s,n)}catch(o){if(o.isModelArmor||o.isUsageLimit||o.isPipelineCancel)throw o;if(e!==kr){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,o.message),Bw(e,kr,i);try{return await Ss("generator",kr,r,s,n)}catch(a){throw a.isModelArmor||a.isUsageLimit||a.isPipelineCancel?a:new Error(`Code Generator failed: primary (${e}): ${o.message} | fallback (${kr}): ${a.message}`)}}throw new Error(`Code Generator failed: ${o.message}`)}}async function Hs(t,e=null){const n={...vl("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await Ss("review",Lh,_v(t),n)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Code Review failed: ${i.message}`)}}function bs(t,e){const n=document.getElementById(`step${t}-item`),i=document.getElementById(`step${t}-status`);!n||!i||(n.classList.remove("active","completed","error"),i.classList.remove("running","completed","error"),e==="active"?(n.classList.add("active"),i.classList.add("running"),i.innerHTML=` +`)}`);G.setState(ee.VALIDATING);const a=await Te("flutterflow"),l=qi||await Te("flutterflow_project_id");if(!a)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!l)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Ds(l))throw new Error("Invalid FlutterFlow Project ID format.");r.projectId=l,G.setState(ee.PUSHING);const u=yt(),c=new pi(a,l,"main",u),d=await Vl(c,t.dependencies),h=d.yaml,f=await ql(c,s,d.remoteFiles,`Provision ${t.title} custom classes`,h);i=f.provisionSucceeded===!0;const p=await Hl(f.syncFileMap,f.remoteFiles),g=new Map(f.syncFileMap);g.set("pubspec.yaml",{content:h,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Be.set("package");const m=await Gl(g),v={project_id:l,zipped_custom_code:m,uid:`web_${Date.now()}`,branch_name:c.branchName,serialized_yaml:h,file_map:p.fileMapContents,functions_map:p.functionsMapContents};G.setProgress(1,s.size),ar(c),Be.set("push");const E=await zl(c,v);if(E.success){const b={...n,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((k,T)=>k+T.content.length,0),projectId:l};return G.setSuccess({...b,fileCount:s.size,warnings:E.errorMap?Array.from(E.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:b,targetIdentity:r,addedDependencies:d.added,unverified:f.unverified,approximate:f.approximate,warnings:E.errorMap?Array.from(E.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}const S=E.errorMessage||Ul(E.responseCode),_=new Error(S);throw _.errorMap=E.errorMap,_.remoteRefusal=!0,_}catch(s){console.error("Bundle commit execution failed:",s),G.setError(s);const o=s.errorMap||new Map;return s instanceof Qe?{success:!1,unconfirmed:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:i?{success:!1,partial:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function N0(t,e=[]){const n=yl("architect");try{return await Is("architect",Nh,vv(t),n,e)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Prompt Architect failed: ${i.message}`)}}async function Ws(t,e,n=[],i){const r=_v(t),s=yl("generator",y.bundleSpec);try{return await Is("generator",e,r,s,n)}catch(o){if(o.isModelArmor||o.isUsageLimit||o.isPipelineCancel)throw o;if(e!==Ar){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,o.message),Uw(e,Ar,i);try{return await Is("generator",Ar,r,s,n)}catch(a){throw a.isModelArmor||a.isUsageLimit||a.isPipelineCancel?a:new Error(`Code Generator failed: primary (${e}): ${o.message} | fallback (${Ar}): ${a.message}`)}}throw new Error(`Code Generator failed: ${o.message}`)}}async function zs(t,e=null){const n={...yl("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await Is("review",Oh,yv(t),n)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Code Review failed: ${i.message}`)}}function Ss(t,e){const n=document.getElementById(`step${t}-item`),i=document.getElementById(`step${t}-status`);!n||!i||(n.classList.remove("active","completed","error"),i.classList.remove("running","completed","error"),e==="active"?(n.classList.add("active"),i.classList.add("running"),i.innerHTML=` `):e==="completed"?(n.classList.add("completed"),i.classList.add("completed"),i.innerHTML=` @@ -127,12 +127,12 @@ ${o.errors.join(` `):i.innerHTML=` - `)}function Ae(t,e){const n=document.getElementById(`step${t}-loading`),i=document.getElementById(`step${t}-result`);e?(n.classList.remove("hidden"),i.classList.add("hidden"),bs(t,"active")):(n.classList.add("hidden"),i.classList.remove("hidden"),bs(t,"completed"))}function M0(t){const e=document.getElementById(`${t}-content`),n=document.getElementById(`${t}-chevron`);e.classList.contains("open")?(e.classList.remove("open"),n&&(n.style.transform="rotate(0deg)")):(e.classList.add("open"),n&&(n.style.transform="rotate(180deg)"))}function L0(t){it(parseInt(t.replace("step","")))}function it(t){for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-item`);a&&a.classList.remove("active")}const e=document.getElementById(`step${t}-item`);e&&e.classList.add("active"),On();const n=document.getElementById("ready-state");n&&n.classList.add("hidden");for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-content`);a&&a.classList.add("hidden")}const i=document.getElementById(`step${t}-content`);i&&i.classList.remove("hidden");const r=document.getElementById("stage-title"),s={1:"Prompt Architect",2:"Code Generator",3:"Code Review"};r&&(r.textContent=s[t]||"Active Workflow Stage")}function N0(t){const e=document.getElementById(t);if(!e)return;const n=e.dataset.raw||e.textContent;navigator.clipboard.writeText(n).then(()=>{const r=e.closest(".code-container")?.querySelector(".copy-btn");r&&(r.classList.add("copied"),r.innerHTML=' Copied!',setTimeout(()=>{r.classList.remove("copied"),r.innerHTML=' Copy'},2e3))}).catch(i=>{console.warn("Failed to copy to clipboard:",i)})}function qa(t){const e=Va(t);console.log(`Step 1 (Prompt Architect): ${Gt(Mh)}`),console.log(e!==t?`Step 2 (Code Generator): ${Gt(t)} → ${Gt(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${Gt(t)}`),console.log(`Step 3 (Code Review): ${Gt(Lh)}`)}function Yh(){return{step1Result:y.step1Result,step2Result:y.step2Result,step3Result:y.step3Result,artifactBundle:y.artifactBundle,bundleReview:y.bundleReview,selectedArtifactId:y.selectedArtifactId}}function O0(t){if(!t)return;Object.assign(y,t),new Set((y.artifactBundle?.artifacts||[]).map(n=>n.id)).has(y.selectedArtifactId)||(y.selectedArtifactId=ai(y.artifactBundle)?.id||null)}const Jh="results-replacement-error";function B0(t,{stage:e=2,runId:n,retry:i}){if(!re(n))return;const r=document.getElementById(Jh);if(!r)return;const s=kh(t),o=document.getElementById("results-replacement-error-title"),a=document.getElementById("results-replacement-error-message"),l=document.getElementById("results-replacement-error-retry"),u=document.getElementById("results-replacement-error-upgrade");o&&(o.textContent=`${Vs[e]||"Regeneration"}: ${s.title}`),a&&(a.textContent=s.message),r.hidden=!1;let c=null;u&&(u.hidden=!s.canUpgrade,s.canUpgrade&&(u.textContent="View plans",u.onclick=()=>fi(),c=u)),l&&(l.hidden=s.canUpgrade,s.canUpgrade||(l.onclick=()=>{Vl(),typeof i=="function"&&i()},l.textContent="Retry",c=l)),(c||r).focus({preventScroll:!0})}function Vl(){const t=document.getElementById(Jh);t&&(t.hidden=!0)}function Zh(t,{previous:e,stage:n,runId:i,retry:r}){re(i)&&(t.isUsageLimit&&un(),O0(e),cr(),nn(!0),ur(),eo(),B0(t,{stage:n,runId:i,retry:r}),rn())}async function Xh(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0;const e=Gs();Gl("standardRegenerate",y.step2Result,y.step1Result);const n=document.querySelectorAll(".btn-refine-action"),i=Yh();n.forEach(r=>{r.disabled=!0,r.innerHTML=` + `)}function Ae(t,e){const n=document.getElementById(`step${t}-loading`),i=document.getElementById(`step${t}-result`);e?(n.classList.remove("hidden"),i.classList.add("hidden"),Ss(t,"active")):(n.classList.add("hidden"),i.classList.remove("hidden"),Ss(t,"completed"))}function O0(t){const e=document.getElementById(`${t}-content`),n=document.getElementById(`${t}-chevron`);e.classList.contains("open")?(e.classList.remove("open"),n&&(n.style.transform="rotate(0deg)")):(e.classList.add("open"),n&&(n.style.transform="rotate(180deg)"))}function B0(t){it(parseInt(t.replace("step","")))}function it(t){for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-item`);a&&a.classList.remove("active")}const e=document.getElementById(`step${t}-item`);e&&e.classList.add("active"),On();const n=document.getElementById("ready-state");n&&n.classList.add("hidden");for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-content`);a&&a.classList.add("hidden")}const i=document.getElementById(`step${t}-content`);i&&i.classList.remove("hidden");const r=document.getElementById("stage-title"),s={1:"Prompt Architect",2:"Code Generator",3:"Code Review"};r&&(r.textContent=s[t]||"Active Workflow Stage")}function D0(t){const e=document.getElementById(t);if(!e)return;const n=e.dataset.raw||e.textContent;navigator.clipboard.writeText(n).then(()=>{const r=e.closest(".code-container")?.querySelector(".copy-btn");r&&(r.classList.add("copied"),r.innerHTML=' Copied!',setTimeout(()=>{r.classList.remove("copied"),r.innerHTML=' Copy'},2e3))}).catch(i=>{console.warn("Failed to copy to clipboard:",i)})}function Ga(t){const e=Ka(t);console.log(`Step 1 (Prompt Architect): ${Gt(Nh)}`),console.log(e!==t?`Step 2 (Code Generator): ${Gt(t)} → ${Gt(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${Gt(t)}`),console.log(`Step 3 (Code Review): ${Gt(Oh)}`)}function Jh(){return{step1Result:y.step1Result,step2Result:y.step2Result,step3Result:y.step3Result,artifactBundle:y.artifactBundle,bundleReview:y.bundleReview,selectedArtifactId:y.selectedArtifactId}}function j0(t){if(!t)return;Object.assign(y,t),new Set((y.artifactBundle?.artifacts||[]).map(n=>n.id)).has(y.selectedArtifactId)||(y.selectedArtifactId=ai(y.artifactBundle)?.id||null)}const Zh="results-replacement-error";function U0(t,{stage:e=2,runId:n,retry:i}){if(!re(n))return;const r=document.getElementById(Zh);if(!r)return;const s=Ah(t),o=document.getElementById("results-replacement-error-title"),a=document.getElementById("results-replacement-error-message"),l=document.getElementById("results-replacement-error-retry"),u=document.getElementById("results-replacement-error-upgrade");o&&(o.textContent=`${Ks[e]||"Regeneration"}: ${s.title}`),a&&(a.textContent=s.message),r.hidden=!1;let c=null;u&&(u.hidden=!s.canUpgrade,s.canUpgrade&&(u.textContent="View plans",u.onclick=()=>fi(),c=u)),l&&(l.hidden=s.canUpgrade,s.canUpgrade||(l.onclick=()=>{Kl(),typeof i=="function"&&i()},l.textContent="Retry",c=l)),(c||r).focus({preventScroll:!0})}function Kl(){const t=document.getElementById(Zh);t&&(t.hidden=!0)}function Xh(t,{previous:e,stage:n,runId:i,retry:r}){re(i)&&(t.isUsageLimit&&un(),j0(e),dr(),nn(!0),fr(),no(),U0(t,{stage:n,runId:i,retry:r}),rn())}async function Qh(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0;const e=Ys();Yl("standardRegenerate",y.step2Result,y.step1Result);const n=document.querySelectorAll(".btn-refine-action"),i=Jh();n.forEach(r=>{r.disabled=!0,r.innerHTML=` - Refining...`});try{Vl();const r=Ol(),s=r.id,o=yv({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,artifactId:r.id,userFeedback:"Fix the issues listed in the audit report."});Zs({runId:e}),Ft(2,e),it(2),Ae(2,!0);const a=await Us(o,t,[],e);if(!re(e))return;y.step2Result=a,Bs(),tn(2,e);const l=document.getElementById("step2-output"),u=ci(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),it(3),Ft(3,e),Ae(3,!0);const c=await Hs(y.step2Result,y.step1Result);if(!re(e))return;y.step3Result=c,Ds(),tn(3,e),y.artifactBundle?.artifacts?.some(h=>h.id===s)?y.selectedArtifactId=s:y.selectedArtifactId=ai(y.artifactBundle)?.id||null;const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const f=Ls(y.step3Result);ur(u,f)}catch(r){if(console.error("Refinement failed:",r),!re(e))return;const s=Ms(r,{architect:2,generator:2,review:3});Zh(r,{previous:i,stage:s,runId:e,retry:Xh})}finally{n.forEach(r=>{r.disabled=!1,r.textContent="Refine & Regenerate"}),re(e)&&(y.isRunning=!1,rn())}}async function Gl(t,e,n){const i=`${_t}/connectFeedback`,r={type:t,code:e,input:n};try{const s=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok){const a=await s.text();return console.error(`callEndpoint failed: ${s.status} ${s.statusText}`,a),{success:!1,status:s.status,error:a}}const o=await s.json();return console.log("Telemetry success:",o),o}catch(s){return console.error("callEndpoint failed:",s),{success:!1,error:s.message}}}function D0(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function Qh(){const t=document.getElementById("ff-error-paste-input"),e=t?.value?.trim();if(!e){t?.focus(),t?.classList.add("ring-2","ring-red-400","border-red-300"),setTimeout(()=>t?.classList.remove("ring-2","ring-red-400","border-red-300"),2e3);return}if(!y.step2Result){Ee("No generated code found. Please run the full pipeline first.","warning");return}if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=Gs();Gl("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` + Refining...`});try{Kl();const r=Dl(),s=r.id,o=wv({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,artifactId:r.id,userFeedback:"Fix the issues listed in the audit report."});Qs({runId:e}),Ft(2,e),it(2),Ae(2,!0);const a=await Ws(o,t,[],e);if(!re(e))return;y.step2Result=a,js(),tn(2,e);const l=document.getElementById("step2-output"),u=ci(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),it(3),Ft(3,e),Ae(3,!0);const c=await zs(y.step2Result,y.step1Result);if(!re(e))return;y.step3Result=c,Us(),tn(3,e),y.artifactBundle?.artifacts?.some(f=>f.id===s)?y.selectedArtifactId=s:y.selectedArtifactId=ai(y.artifactBundle)?.id||null;const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),dr();const h=Os(y.step3Result);fr(u,h)}catch(r){if(console.error("Refinement failed:",r),!re(e))return;const s=Ns(r,{architect:2,generator:2,review:3});Xh(r,{previous:i,stage:s,runId:e,retry:Qh})}finally{n.forEach(r=>{r.disabled=!1,r.textContent="Refine & Regenerate"}),re(e)&&(y.isRunning=!1,rn())}}async function Yl(t,e,n){const i=`${_t}/connectFeedback`,r={type:t,code:e,input:n};try{const s=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok){const a=await s.text();return console.error(`callEndpoint failed: ${s.status} ${s.statusText}`,a),{success:!1,status:s.status,error:a}}const o=await s.json();return console.log("Telemetry success:",o),o}catch(s){return console.error("callEndpoint failed:",s),{success:!1,error:s.message}}}function H0(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function ep(){const t=document.getElementById("ff-error-paste-input"),e=t?.value?.trim();if(!e){t?.focus(),t?.classList.add("ring-2","ring-red-400","border-red-300"),setTimeout(()=>t?.classList.remove("ring-2","ring-red-400","border-red-300"),2e3);return}if(!y.step2Result){Ee("No generated code found. Please run the full pipeline first.","warning");return}if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=Ys();Yl("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` - Fixing…`);const s=Yh();try{Vl();const o=oh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});Cp(),Zs({runId:i}),Ft(2,i),it(2),Ae(2,!0);const a=await Us(o,n,[],i);if(!re(i))return;y.step2Result=a,Bs(),tn(2,i);const l=document.getElementById("step2-output"),u=ci(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),it(3),Ft(3,i),Ae(3,!0);const c=await Hs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,Ds(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const f=Ls(y.step3Result);ur(u,f),t&&(t.value="")}catch(o){if(console.error("Fix from errors failed:",o),!re(i))return;const a=Ms(o,{architect:2,generator:2,review:3});Zh(o,{previous:s,stage:a,runId:i,retry:Qh})}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function or(){if(console.log("runThinkingPipeline called"),y.isRunning)return;localStorage.setItem("hasSeenWalkthrough","true");const t=document.getElementById("pipeline-input").value,e=document.getElementById("code-generator-model").value,n=Oe.slice();if(!t.trim()){Ee("Please describe your FlutterFlow widget first.","warning");return}y.isRunning=!0;const i=Gs();try{if(await Oa,!re(i)||(pn.length&&await Promise.allSettled(pn.map(v=>v.job)),!re(i))||!await cw()||!re(i)||(await iw(),!re(i)))return;const r=Va(e);t.length,w0(),y.submittedPrompt=t,y.submittedImages=n.filter(v=>v.url),Ya(!0),qa(r),On();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const o=document.getElementById("paywall-exhausted");o&&o.classList.add("hidden"),Zs({prompt:t,runId:i}),Hw(),it(1),Ft(1,i),Ae(1,!0);const a=y.submittedImages.map(v=>({url:v.url})),l=await $0(t,a);if(!re(i))return;y.step1Result=l,b0(),tn(1,i);const u=document.getElementById("step1-output"),c=ci(y.step1Result);u.textContent=c,u.dataset.raw=c,Ae(1,!1),it(2),Ft(2,i),Ae(2,!0);const d=await Us(y.step1Result,r,a,i);if(!re(i))return;y.step2Result=d,Bs(),tn(2,i);const f=document.getElementById("step2-output"),h=ci(y.step2Result);f.textContent=h,f.dataset.raw=h,Ae(2,!1),it(3),Ft(3,i),Ae(3,!0);const p=await Hs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=p,Ds(),tn(3,i);const g=document.getElementById("step3-output");g.textContent=y.step3Result,Ae(3,!1),cr();const m=Ls(y.step3Result);Ww(),ur(h,m)}catch(r){if(r.isPipelineCancel||console.error("Pipeline failed:",r),!re(i))return;const s=Ms(r,{architect:1,generator:2,review:3});r.isUsageLimit?un():(r.message,Va(document.getElementById("code-generator-model").value),void 0),it(s),Ae(s,!1),Sp(r,{stage:s,runId:i}),bs(s,"error")}finally{re(i)&&(y.isRunning=!1,Ya(!1),rn())}}function j0(){const t=document.getElementById("code-generator-model").value,e=[ms,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(i=>i!==t),n=prompt(`Retry with different model? + Fixing…`);const s=Jh();try{Kl();const o=lh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});Ap(),Qs({runId:i}),Ft(2,i),it(2),Ae(2,!0);const a=await Ws(o,n,[],i);if(!re(i))return;y.step2Result=a,js(),tn(2,i);const l=document.getElementById("step2-output"),u=ci(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),it(3),Ft(3,i),Ae(3,!0);const c=await zs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,Us(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),dr();const h=Os(y.step3Result);fr(u,h),t&&(t.value="")}catch(o){if(console.error("Fix from errors failed:",o),!re(i))return;const a=Ns(o,{architect:2,generator:2,review:3});Xh(o,{previous:s,stage:a,runId:i,retry:ep})}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function lr(){if(console.log("runThinkingPipeline called"),y.isRunning)return;localStorage.setItem("hasSeenWalkthrough","true");const t=document.getElementById("pipeline-input").value,e=document.getElementById("code-generator-model").value,n=Oe.slice();if(!t.trim()){Ee("Please describe your FlutterFlow widget first.","warning");return}y.isRunning=!0;const i=Ys();try{if(await Da,!re(i)||(pn.length&&await Promise.allSettled(pn.map(v=>v.job)),!re(i))||!await fw()||!re(i)||(await ow(),!re(i)))return;const r=Ka(e);t.length,b0(),y.submittedPrompt=t,y.submittedImages=n.filter(v=>v.url),Za(!0),Ga(r),On();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const o=document.getElementById("paywall-exhausted");o&&o.classList.add("hidden"),Qs({prompt:t,runId:i}),qw(),it(1),Ft(1,i),Ae(1,!0);const a=y.submittedImages.map(v=>({url:v.url})),l=await N0(t,a);if(!re(i))return;y.step1Result=l,E0(),tn(1,i);const u=document.getElementById("step1-output"),c=ci(y.step1Result);u.textContent=c,u.dataset.raw=c,Ae(1,!1),it(2),Ft(2,i),Ae(2,!0);const d=await Ws(y.step1Result,r,a,i);if(!re(i))return;y.step2Result=d,js(),tn(2,i);const h=document.getElementById("step2-output"),f=ci(y.step2Result);h.textContent=f,h.dataset.raw=f,Ae(2,!1),it(3),Ft(3,i),Ae(3,!0);const p=await zs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=p,Us(),tn(3,i);const g=document.getElementById("step3-output");g.textContent=y.step3Result,Ae(3,!1),dr();const m=Os(y.step3Result);Vw(),fr(f,m)}catch(r){if(r.isPipelineCancel||console.error("Pipeline failed:",r),!re(i))return;const s=Ns(r,{architect:1,generator:2,review:3});r.isUsageLimit?un():(r.message,Ka(document.getElementById("code-generator-model").value),void 0),it(s),Ae(s,!1),xp(r,{stage:s,runId:i}),Ss(s,"error")}finally{re(i)&&(y.isRunning=!1,Za(!1),rn())}}function W0(){const t=document.getElementById("code-generator-model").value,e=[_s,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(i=>i!==t),n=prompt(`Retry with different model? Current: ${t} @@ -140,14 +140,14 @@ Options: 1. ${e[0]} 2. ${e[1]} -Enter 1 or 2:`);n==="1"?(document.getElementById("code-generator-model").value=e[0],or()):n==="2"&&(document.getElementById("code-generator-model").value=e[1],or())}async function U0(){const t=Bl();if(!t){Ee("No code to commit. Please run the pipeline first.","warning");return}const e=await Te("flutterflow"),n=await Te("flutterflow_project_id");if(!e||!n){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),Tl();return}if(y.artifactBundle?.artifacts?.length>1){await H0();return}const{artifactType:i,artifactName:r,fileName:s}=Wh(),o=Kh(t,{artifactType:i,artifactName:r,fileName:s}),a=k0(o);if(!a.canProceed){Ee(`Pre-commit checks failed: ${a.issues.join("; ")}`,"error");return}Jl(o,a,null,null)}async function H0(){const t=await Te("flutterflow"),e=await Te("flutterflow_project_id");if(!t||!e){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),Tl();return}const n=n_(y.artifactBundle);if(n.errors.length>0){Ee(`Bundle validation failed: ${n.errors.join("; ")}`,"error");return}const i=new Map(n.fileEntries.map(a=>[a.fileName,{content:a.content,type:a.type,path:a.path}])),r=js(i),s={canProceed:r.valid&&n.errors.length===0,issues:[...n.errors,...r.errors],warnings:[...n.warnings,...r.warnings]};if(!s.canProceed){Ee(`Bundle validation failed: ${s.issues.join("; ")}`,"error");return}const o={content:n.fileEntries.map(a=>`// ${a.fileName} +Enter 1 or 2:`);n==="1"?(document.getElementById("code-generator-model").value=e[0],lr()):n==="2"&&(document.getElementById("code-generator-model").value=e[1],lr())}async function z0(){const t=jl();if(!t){Ee("No code to commit. Please run the pipeline first.","warning");return}const e=await Te("flutterflow"),n=await Te("flutterflow_project_id");if(!e||!n){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),Ml();return}if(y.artifactBundle?.artifacts?.length>1){await q0();return}const{artifactType:i,artifactName:r,fileName:s}=qh(),o=Yh(t,{artifactType:i,artifactName:r,fileName:s}),a=P0(o);if(!a.canProceed){Ee(`Pre-commit checks failed: ${a.issues.join("; ")}`,"error");return}Xl(o,a,null,null)}async function q0(){const t=await Te("flutterflow"),e=await Te("flutterflow_project_id");if(!t||!e){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),Ml();return}const n=i_(y.artifactBundle);if(n.errors.length>0){Ee(`Bundle validation failed: ${n.errors.join("; ")}`,"error");return}const i=new Map(n.fileEntries.map(a=>[a.fileName,{content:a.content,type:a.type,path:a.path}])),r=Hs(i),s={canProceed:r.valid&&n.errors.length===0,issues:[...n.errors,...r.errors],warnings:[...n.warnings,...r.warnings]};if(!s.canProceed){Ee(`Bundle validation failed: ${s.issues.join("; ")}`,"error");return}const o={content:n.fileEntries.map(a=>`// ${a.fileName} ${a.content}`).join(` -`),fileName:`${n.fileEntries.length} files`,codeType:"bundle",artifactType:"Bundle",artifactName:n.title};Jl(o,s,n.dependencies,n)}function W0(t){let e=t.errorMap||new Map;!(e instanceof Map)&&typeof e=="object"&&(e=new Map(Object.entries(e)));let n=`
      +`),fileName:`${n.fileEntries.length} files`,codeType:"bundle",artifactType:"Bundle",artifactName:n.title};Xl(o,s,n.dependencies,n)}function V0(t){let e=t.errorMap||new Map;!(e instanceof Map)&&typeof e=="object"&&(e=new Map(Object.entries(e)));let n=`

      FlutterFlow Commit Failed

      ${z(t.error)}

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

      Errors:

      -
        `;for(const[r,s]of e.entries()){const o=Sl(s);n+=`
      • +
          `;for(const[r,s]of e.entries()){const o=Il(s);n+=`
        • ${z(r)}: ${z(o)}
        • `}n+="
      "}n+="
      ",n+=`
      -
      `;const i=document.getElementById("step3-output");i&&(i.innerHTML=n,document.getElementById("btn-regenerate-from-error")?.addEventListener("click",()=>{ep(t.error,e)}))}async function ep(t,e){if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=Gs(),r=document.getElementById("btn-regenerate-from-error");r&&(r.disabled=!0,r.innerHTML=` +
      `;const i=document.getElementById("step3-output");i&&(i.innerHTML=n,document.getElementById("btn-regenerate-from-error")?.addEventListener("click",()=>{tp(t.error,e)}))}async function tp(t,e){if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=Ys(),r=document.getElementById("btn-regenerate-from-error");r&&(r.disabled=!0,r.innerHTML=` Fixing...`);try{let s=`The previous code had the following errors when committing to FlutterFlow: -`;if(e&&e.size>0)for(const[h,p]of e.entries()){const g=Sl(p);s+=`File: ${h} +`;if(e&&e.size>0)for(const[f,p]of e.entries()){const g=Il(p);s+=`File: ${f} Error: ${g} `}else s+=`${t} -`;const o=oh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:s});Zs({runId:i}),Ft(2,i),it(2),Ae(2,!0);const a=await Us(o,n,[],i);if(!re(i))return;y.step2Result=a,Bs(),tn(2,i);const l=document.getElementById("step2-output"),u=ci(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),it(3),Ft(3,i),Ae(3,!0);const c=await Hs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,Ds(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),cr();const f=Ls(y.step3Result);ur(u,f)}catch(s){if(console.error("Regeneration failed:",s),!re(i))return;const o=Ms(s,{architect:2,generator:2,review:3});s.isUsageLimit&&un(),it(o),Ae(o,!1),Sp(s,{stage:o,runId:i,retry:()=>ep(t,e)}),bs(o,"error")}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function z0(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const n=await Te("flutterflow"),i=await Te("flutterflow_project_id");n&&i?(t.className="w-2 h-2 rounded-full bg-green-500",e.textContent="FlutterFlow credentials configured",e.className="text-green-600"):n||i?(t.className="w-2 h-2 rounded-full bg-yellow-500",e.textContent="FlutterFlow credentials incomplete",e.className="text-yellow-600"):(t.className="w-2 h-2 rounded-full bg-red-500",e.textContent="FlutterFlow credentials not configured",e.className="text-red-600")}async function tp(t){try{const e=await fetch(`${_t}/auth/send-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:t})});if(!e.ok)throw new Error(`Failed to send magic link: HTTP ${e.status}`);return e.json()}catch(e){throw console.error("sendMagicLink failed:",{email:t,message:e.message,stack:e.stack}),e}}async function q0(t){try{const n=await(await fetch(`${_t}/auth/verify-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})})).json();if(n.error||!n.email||!n.sessionToken)throw new Error(n.error||"Invalid or expired link");return n}catch(e){throw console.error("verifyMagicLink failed:",{message:e.message,stack:e.stack}),e}}async function V0(t){try{const e=await fetch(`${_t}/auth/refresh-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:t})});if(!e.ok)return console.error("refreshSession: non-OK response",{url:`${_t}/auth/refresh-session`,status:e.status}),null;const n=await e.json();return n.error||!n.email||!n.sessionToken?(console.warn("refreshSession: validation failed",{error:n.error,hasEmail:!!n.email,hasToken:!!n.sessionToken}),null):n}catch(e){return console.error("refreshSession: fetch failed",{url:`${_t}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function sd(t,e){const n=ip(),i=(q.email||n.email)!==t;q.email=t,q.sessionToken=e,q.isVerified=!0,ce=Ln({isLoading:!0}),localStorage.setItem(hs,JSON.stringify({email:t,sessionToken:e})),i&&cp()}function np(){q.email=null,q.sessionToken=null,q.isVerified=!1,ce=Ln({isResolved:!0}),localStorage.removeItem(hs),localStorage.removeItem(gs)}function ip(){try{const t=localStorage.getItem(hs);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(hs),{email:null,sessionToken:null}}}async function G0(){const e=new URLSearchParams(window.location.search).get("token");if(e){window.history.replaceState({},"",window.location.pathname+window.location.hash);try{const{email:n,sessionToken:i}=await q0(e);sd(n,i),rp();const r=od();r&&!window.location.hash&&(window.location.hash=r)}catch(n){od();const i=n.message||"Sign-in link invalid or expired.";Ee(i,"error"),Ws(),Zn(i,"error")}}else{const{email:n,sessionToken:i}=ip();if(n&&i){const r=await V0(i);r?sd(r.email,r.sessionToken):np()}}Kl()}function K0(){try{localStorage.setItem(Na,JSON.stringify({hash:window.location.hash||"#home",ts:Date.now()}))}catch(t){console.warn("rememberSignInReturnSurface: failed to persist return surface:",t)}}function od(){try{const t=localStorage.getItem(Na);if(localStorage.removeItem(Na),!t)return null;const{hash:e,ts:n}=JSON.parse(t);return!e||typeof n!="number"||Date.now()-n>Fy?null:e}catch(t){return console.warn("consumeSignInReturnSurface: failed to read return surface:",t),null}}function Ws(){const t=document.getElementById("signin-modal");if(!t)return;K0(),document.getElementById("signin-email-input")?.removeAttribute("aria-invalid"),Zn(""),We(t)}function rp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&ze(e)}function Zn(t,e){const n=document.getElementById("signin-message");n&&(n.textContent=t||"",n.classList.remove("signin-message-success","signin-message-error"),e&&n.classList.add(`signin-message-${e}`))}async function Y0(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),n=Fs(t?.value);if(!n||!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(n)||n.length>254){t?.setAttribute("aria-invalid","true"),Zn("Please enter a valid email address.","error");return}t?.removeAttribute("aria-invalid"),e&&(e.disabled=!0,e.textContent="Sending…");const r=ph(n);r&&Zn(r,"error");try{const s=await tp(n),o=s?.code===hh;t&&!o&&(t.value=""),t?.setAttribute("aria-invalid",String(o)),Zn(gh(s,n),o?"error":"success"),e&&(e.disabled=!1,e.textContent=o?"Send Sign-in Link":"Sent!",o||setTimeout(()=>{e.textContent==="Sent!"&&(e.textContent="Send Sign-in Link")},2500))}catch(s){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:n,err:s}),Zn("Something went wrong. Please try again.","error"),e&&(e.disabled=!1,e.textContent="Send Sign-in Link")}}function J0(){q.email=null,q.sessionToken=null,q.isVerified=!1,ce=Ln({isResolved:!0}),D_({storage:window.localStorage,onIdentityChanged:Kl,onPlanChanged:qs})}const Z0=j_({sendLink:tp,getEmail:()=>q.email||"",onState:X0});function X0(t){const e=document.getElementById("send-new-link-btn"),n=document.getElementById("send-new-link-msg");if(!e||!n)return;if(t.status==="pending"){e.disabled=!0,e.textContent="Sending…",n.className="acct-access-msg",n.textContent="Sending a fresh sign-in link…";return}if(t.status==="sent"){e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg",n.textContent=gh(t.data,q.email||"")||"Link sent — check your email.";return}e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg error";const i=t.error?.message?`Couldn't send a link right now. ${t.error.message}`:"Couldn't send a link right now. Please try again.";n.textContent=i}async function Q0(){await Z0()}function ew(){const t=O_(window.localStorage),e=t.length?`Cleared disposable UI caches: ${t.join(", ")}.`:"Nothing disposable to clear.";Ee(`${e} Your run count, identity and stored keys are kept.`,"info")}function tw(){const t=document.getElementById("delete-unavailable-modal");t&&We(t,{trigger:document.activeElement})}function nw(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("delete-unavailable-modal");e&&ze(e)}function Kl(){const t=q.isVerified&&!!q.email,e=document.getElementById("auth-signedout"),n=document.getElementById("auth-signedin"),i=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),n&&n.classList.toggle("hidden",!t),i&&i.classList.toggle("hidden",t);const r=document.getElementById("auth-user-email");r&&(r.textContent=q.email||"");const s=document.getElementById("access-signed-email");s&&(s.textContent=q.email||""),fw(),qs()}async function sp(){try{if(typeof FingerprintJS>"u"){console.warn("resolveIdentity: FingerprintJS not loaded, skipping");return}const e=await(await FingerprintJS.load()).get(),n=e.visitorId,i=await fetch(My,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fingerprint:e.visitorId,cookie_id:n})});if(!i.ok)throw new Error(`Identity check HTTP ${i.status}`);const r=await i.json();if(ht.userId=r.user_id,ht.token=r.identity_token||null,ht.status=r.status,ht.resolved=!0,sessionStorage.setItem(Ty,r.user_id),ht.token&&sessionStorage.setItem($y,ht.token),r.usage_count!==void 0){const s=gn(),a=(r.usage_month||s)===s?r.usage_count:0;localStorage.setItem(Rn,JSON.stringify({count:a,month:s})),un()}console.log(`Identity resolved: ${r.status} (${r.user_id.slice(0,8)}...) usage: ${r.usage_count??"n/a"}`)}catch(t){console.error("resolveIdentity failed:",t)}}let Wo=null;function iw(t=5e3){return ht.resolved?Promise.resolve():(Wo||(Wo=sp().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([Wo,new Promise(e=>setTimeout(e,t))]))}function op(){const t=gn();try{const e=localStorage.getItem(Rn);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Rn,month:t,err:e}),localStorage.removeItem(Rn),{count:0,month:t}}}function gn(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function lr(){const t=op();return t.month!==gn()?{count:0,month:gn()}:t}function rw(){const e={count:lr().count+1,month:gn()};return localStorage.setItem(Rn,JSON.stringify(e)),e}function gi(){return!!ce.isLoading}function Tt(){return!!ce.isResolved}function sw(t){if(!t)return null;const e=String(t).toLowerCase().replace(/[^a-z0-9]+/g,"_");return e==="pro"||e==="professional_plan"?"professional":e==="power_developer"||e==="power_plan"?"power":Object.prototype.hasOwnProperty.call(ps,e)?e:null}function ow(t){return t&&Object.entries(Ah).find(([,e])=>e===t)?.[0]||null}function Cr(...t){return t.find(e=>e!=null&&e!=="")}function aw(...t){return t.find(e=>e&&typeof e=="object")||{}}function lw(t){const e=t.data&&typeof t.data=="object"?t.data:t,n=aw(e.subscription,e.stripeSubscription,e.currentSubscription,e.customer?.subscriptions?.data?.[0],e.subscriptions?.data?.[0],e.subscriptions?.[0]),i=e.metadata||n.metadata||e.customer?.metadata||{},r=Cr(e.priceId,e.price_id,e.stripePriceId,e.stripe_price_id,n.priceId,n.price_id,n.plan?.id,n.price?.id,n.items?.data?.[0]?.price?.id,n.items?.[0]?.price?.id,n.lines?.data?.[0]?.price?.id),s=Cr(e.status,e.subscriptionStatus,e.subscription_status,n.status,"none"),o=sw(Cr(e.tier,e.plan,e.planId,e.plan_id,e.subscriptionTier,e.subscription_tier,e.product,e.productName,n.tier,n.plan,i.tier,i.plan)),a=Ly.has(String(s).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||ow(r)||(a||l?"professional":"free");return Ln({tier:u,status:s,periodEnd:Cr(e.periodEnd,e.currentPeriodEnd,e.current_period_end,n.current_period_end,n.periodEnd,null),isResolved:!0})}function zs(){return ps[ce.tier]??ps.free}async function cw(){if(q.isVerified&&(!Tt()||gi())&&(await lp({force:!0}),qs()),q.isVerified&&!Tt())return Ee("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=lr(),e=zs();if(t>=e)return ap(t,e,{openModal:!0}),!1;const n=Math.floor(e*.8);if(t>=n){const i=e-t;Ee(`${i} run${i===1?"":"s"} remaining this month.`,"warning")}return!0}function ad(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function ap(t,e,n={}){nn(!0);const i=document.getElementById("walkthrough-modal");i&&ze(i,{restoreFocus:!1});const r=document.getElementById("ready-state");r&&r.classList.add("hidden");const s=document.getElementById("preview-frame-container");s&&(s.style.display="none");const o=document.getElementById("main-stage-container");o&&o.classList.add("visible");const a=document.getElementById("results-view");a&&a.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar");const l=document.getElementById("pipeline-progress");l&&l.classList.remove("visible");const u=document.getElementById("paywall-exhausted");if(!u){Ee(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),fi();return}const c=document.getElementById("paywall-exhausted-text");if(c){const f=ce.tier;f==="free"?c.textContent=`You've used all ${e} free generations this month. Upgrade to Pro for 50 generations/month and access to all AI models.`:c.textContent=`You've used all ${e} generations this month on your ${f} plan. Your limit resets next month.`}const d=document.getElementById("paywall-signin-btn");d&&d.classList.toggle("hidden",q.isVerified),u.classList.remove("hidden"),n.openModal&&fi()}function Va(t){return ce.tier==="free"&&Nr.includes(t)?ms:t}function uw(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const n=ce.tier,r=!(q.isVerified&&!Tt())&&n==="free";Array.from(e.options).forEach(o=>{const a=Gt(o.value),l=Nr.includes(o.value);o.textContent=l&&r?`${a} (PRO)`:a,o.disabled=!1}),r&&Nr.includes(e.value)&&(e.value=ms),e.disabled=!1,Ku.has(e)||(e.addEventListener("change",()=>{Tt()&&ce.tier==="free"&&Nr.includes(e.value)&&(e.value=ms,fi()),qa(e.value),Cl()}),Ku.add(e));let s=document.getElementById("model-selector-free-notice");r?(s||(s=document.createElement("p"),s.id="model-selector-free-notice",s.className="text-xs text-gray-400 mt-1",t.appendChild(s)),s.innerHTML='Free plan — Gemini only. '):s&&s.remove(),qa(e.value)}function Yl(){const t=q.isVerified&&!!q.email,e=t&&gi(),n=!t||Tt(),i=lr(),r=n?i.count:0,s=n?zs():0,o=Math.max(0,s-r),a=`${r} / ${s} runs this month`,l=ml,u=n?ce.tier||"free":null,c=document.getElementById("topbar-credits-count");c&&(e?c.textContent="…":n?c.textContent=String(o):c.textContent="—");const d=document.getElementById("credits-balance");d&&(e?d.textContent="Checking plan…":n?d.textContent=a:d.textContent="Plan check failed");const f=document.getElementById("usage-dialog-tier");f&&(e?f.textContent="Checking…":n?f.textContent=l[u]||"Free":f.textContent="Unavailable");const h=document.getElementById("usage-dialog-status");h&&(e?h.textContent="Verifying your subscription…":n?h.textContent="Runs reset at the start of each month.":h.textContent="Could not verify your subscription. Try again or sign out.");const p=document.getElementById("usage-counter");if(p)if(e&&t)p.textContent="Checking plan…",p.className="text-xs text-gray-500";else if(!n&&t)p.textContent="Plan check failed",p.className="text-xs text-red-600 font-medium";else{p.textContent=a;const g=s>0?r/s:0;p.className=g>=1?"text-xs text-red-600 font-medium":g>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500"}if(!t){const g=document.getElementById("guest-usage-text");if(g){const m=op(),v=m.month===gn()?m.count??0:0;g.textContent=`${v} / ${ps.free} generations used`}}dw()}function dw(){if(!(q.isVerified&&!!q.email))return;const e=gi(),n=Tt(),i=lr(),r=n?i.count:0,s=n?zs():0,o=Math.max(0,s-r),a=n?ce.tier||"free":null,l={free:"Free",professional:"Pro",power:"Power"}[a]||"Free",u=q.email||"",c=u.split("@")[0]||u,d=document.getElementById("acct-avatar");d&&(d.textContent=(u[0]||"?").toUpperCase());const f=document.getElementById("acct-name");f&&(f.textContent=c||"—");const h=document.getElementById("acct-plan-tier"),p=document.getElementById("acct-plan-price"),g=document.getElementById("acct-plan-note"),m=document.getElementById("acct-renewal");if(h&&(h.textContent=e?"Checking…":n?l:"Plan unavailable"),p)if(e)p.textContent="—";else if(!n)p.textContent="—";else if(a==="free")p.textContent="$0 / month";else{const x=Bi(Oi[a]??0,Al());p.textContent=`${x} / month`}if(g&&(e?g.textContent="Verifying your subscription…":n?a==="free"?g.textContent="No subscription. Upgrade for more generations.":g.textContent="billed monthly through Stripe":g.textContent="Could not verify your subscription. Check billing or sign out."),m){const x=Date.parse(ce.periodEnd||""),F=n&&a!=="free"&&!!ce.periodEnd&&!Number.isNaN(x);if(e)m.textContent="";else if(!n)m.textContent="";else if(a==="free")m.textContent="";else if(F){const $=new Date(x).toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"});m.textContent=`Renews ${$} · reset at the start of each month.`}else m.textContent="Renewal date is not available for this period."}const v=document.getElementById("acct-left-count"),E=document.getElementById("acct-left-limit"),S=document.getElementById("acct-reset-note");v&&(v.textContent=e?"…":n?String(o):"—"),E&&(E.textContent=e?"…":n?String(s):"—"),S&&(e?S.textContent="Checking plan…":n?S.textContent="Runs reset at the start of each month.":S.textContent="Plan check failed. Refresh or manage billing.");const _=document.getElementById("acct-used-count"),b=document.getElementById("acct-meter-fill"),k=document.getElementById("acct-meter-meta"),T=document.getElementById("acct-meter-track");if(_&&(_.textContent=e?"…":n?String(r):"—"),b){const x=n&&s>0?Math.min(100,Math.round(r/s*100)):0;b.style.width=`${x}%`}if(k)if(e)k.textContent="Checking…";else if(!n)k.textContent="Plan check failed";else if(s===0)k.textContent=`${r} of ${s}`;else{const x=Math.round(r/s*100);k.textContent=`${r} of ${s} · ${x}%`}T&&(e?T.setAttribute("aria-label","Checking usage…"):n?T.setAttribute("aria-label",`${r} of ${s} generations used`):T.setAttribute("aria-label","Usage unavailable")),vt()}function un(){if(Yl(),q.isVerified&&(gi()||!Tt())){ad();return}const{count:t}=lr(),e=zs();t>=e&&!y.isRunning?ap(t,e):ad()}function fw(){Yl()}async function lp(t={}){const e=t.force===!0;if(!q.isVerified||!q.sessionToken){ce=Ln({isResolved:!0});return}ce={...ce,isLoading:!0,error:null};const n=localStorage.getItem(gs);if(!e&&n)try{const{data:i,email:r,ts:s,version:o}=JSON.parse(n);if(o===Yu&&r===q.email&&Date.now()-s<300*1e3){ce={...i,isLoading:!1,isResolved:i.isResolved!==!1};return}}catch(i){console.warn("Failed to parse subscription cache:",i,"| raw value:",n)}try{const r=await(await fetch(`${_t}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:q.sessionToken,user_id:ht.userId})})).json();if(r.error){if(["unauthorized","invalid session","expired session"].some(o=>String(r.error).toLowerCase().includes(o))){np(),Kl();return}ce=Ln({isResolved:!1,error:r.error});return}ce=lw(r),localStorage.setItem(gs,JSON.stringify({version:Yu,data:ce,email:q.email,ts:Date.now()}))}catch(i){console.error("fetchSubscription failed:",i),ce={...ce,isLoading:!1,isResolved:!1,error:i.message}}}function cp(){localStorage.removeItem(gs)}async function hw(t){if(!q.isVerified||!q.sessionToken){up(),Ws();return}if(!Ah[t]){Ee("Invalid plan selected.","error");return}const e=document.getElementById(`checkout-btn-${t}`);e&&(e.disabled=!0,e.textContent="Redirecting…");try{const i=await(await fetch(`${_t}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:q.sessionToken,currency:Al()})})).json();if(i.error||!i.url)throw new Error(i.error||"Failed to create checkout session");const{url:r}=i;window.location.href=r}catch(n){console.error("startCheckout failed:",n),e&&(e.disabled=!1,e.textContent="Subscribe"),Ee("Could not start checkout. Please try again.","error")}}async function pw(t){if(!q.isVerified||!q.sessionToken){Ws();return}const e=t||document.getElementById("manage-billing-btn"),n=e?e.textContent:"";e&&(e.disabled=!0,e.textContent="Loading…");try{const r=await(await fetch(`${_t}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:q.sessionToken})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to open billing portal");const{url:s}=r;window.location.href=s}catch(i){console.error("openCustomerPortal failed:",i),e&&(e.disabled=!1,e.textContent=n),Ee("Could not open billing portal. Please try again.","error")}}const Es=new Set;function gw(){Es.forEach(t=>t.abort()),Es.clear()}async function Ss(t,e,n,i={},r=[]){const o=new AbortController;Es.add(o);let a=!1;const l=setTimeout(()=>{a=!0,o.abort()},12e4);try{const u=await fetch(Ry,{method:"POST",headers:{"Content-Type":"application/json",...ht.token?{Authorization:`Bearer ${ht.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:ht.userId,step:t,model:e,prompt:n,images:r,context:i})}),c=await u.text();let d={};try{d=c?JSON.parse(c):{}}catch{d={}}if(u.status===429){d.serverCount!==void 0&&(localStorage.setItem(Rn,JSON.stringify({count:d.serverCount,month:gn()})),un());const p=new Error(d.message||"Monthly usage limit reached. Upgrade to continue.");throw p.isUsageLimit=!0,p.pipelineStep=t,p}const f=kv(d,t);if(f)throw f;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(d),"content type:",typeof d.content),!u.ok)throw new Error(`${d.message||d.error||"BuildShip pipeline error"} (HTTP ${u.status})`);if(t==="generator")if(d.usage_status==="success"&&Number.isFinite(d.usage_count)){const p=gn();(d.usage_month||p)===p&&(localStorage.setItem(Rn,JSON.stringify({count:d.usage_count,month:p})),un())}else rw(),un();let h=d.output||d.content;if(!h){const p=c?` (body: ${c.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${p}`)}return Array.isArray(h)&&(h=h.map(p=>typeof p=="string"?p:p.text||"").join("")),typeof h!="string"&&(h=JSON.stringify(h)),h}catch(u){if(u.name==="AbortError"){if(a)throw new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`);const c=new Error(`BuildShip ${t} request cancelled`);throw c.isPipelineCancel=!0,c}throw u instanceof TypeError?new Error(`BuildShip unreachable: ${u.message}`):u}finally{clearTimeout(l),Es.delete(o)}}let Ga=!1;function mw(){const e=new URLSearchParams(window.location.search).get("checkout");return e==="success"?(window.history.replaceState({},"",window.location.pathname+window.location.hash),cp(),Ga=!0):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname+window.location.hash),Ee("Checkout cancelled.","info")),e}function vw(){if(!Ga)return;Ga=!1;const t=ce.tier!=="free";Ee(t?"Subscription active! Your plan is live.":"Checkout complete — confirming your subscription. Check Manage billing if it does not update.",t?"success":"info")}function qs(){const t=q.isVerified&&!!q.email,e=ce.tier,n=t&&gi(),i=!t||Tt(),r=document.getElementById("subscription-tier-badge");if(r){const a=ml,l={free:"bg-gray-100 text-gray-600",professional:"bg-indigo-100 text-indigo-700",power:"bg-purple-100 text-purple-700",unresolved:"bg-red-50 text-red-600"};r.textContent=n?"Checking…":i?a[e]||"Free":"Plan unavailable",r.className=`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${i?l[e]||l.free:l.unresolved}`}const s=document.getElementById("upgrade-prompt");s&&s.classList.toggle("hidden",!t||n||!i||e!=="free");const o=document.getElementById("manage-billing-btn");o&&o.classList.toggle("hidden",!t||n||i&&e==="free"),_w(i?e:null),uw(),Cl(),un(),Ap()}function _w(t){const e=["bg-gray-100","text-gray-500","cursor-default"];Object.entries({professional:{btnId:"checkout-btn-professional",defaultText:"Subscribe"},power:{btnId:"checkout-btn-power",defaultText:"Subscribe"}}).forEach(([r,{btnId:s,defaultText:o}])=>{const a=document.getElementById(s);a&&(r===t?(a.disabled=!0,a.textContent="Current plan",a.classList.add(...e)):(a.disabled=!1,a.textContent=o,a.classList.remove(...e)))});const i=document.getElementById("free-tier-current");i&&i.classList.toggle("hidden",t!=="free")}function yw(){document.querySelectorAll(".pm-card[data-tier]").forEach(t=>{const e=t.dataset.tier,n=hv[e];if(!n)return;const i=t.querySelector("ul.pm-features");if(i){i.innerHTML="";for(const r of n){const s=document.createElement("li");s.textContent=r,i.appendChild(s)}}})}function Ka(){const t=Al(),e=document.getElementById("pro-price"),n=document.getElementById("power-price"),i=document.getElementById("plans-pro-price"),r=document.getElementById("plans-power-price"),s=document.getElementById("pro-price-note"),o=document.getElementById("power-price-note"),a=document.getElementById("plans-pro-price-note"),l=document.getElementById("plans-power-price-note");e&&(e.textContent=Bi(Oi.professional,t)),n&&(n.textContent=Bi(Oi.power,t)),i&&(i.textContent=Bi(Oi.professional,t)),r&&(r.textContent=Bi(Oi.power,t));const u="billed monthly";s&&(s.textContent=u),o&&(o.textContent=u),a&&(a.textContent=u),l&&(l.textContent=u)}function fi(){Ka();const t=document.getElementById("pricing-modal");t&&We(t),Vy().then(()=>Ka())}function up(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&ze(e)}function Ee(t,e="info"){const n={success:"bg-green-600 text-white",error:"bg-red-600 text-white",warning:"bg-amber-500 text-white",info:"bg-gray-800 text-white"},i=document.createElement("div");i.className=`fixed bottom-6 left-1/2 -translate-x-1/2 px-5 py-3 rounded-lg text-sm font-medium shadow-lg z-50 transition-opacity duration-300 ${n[e]||n.info}`,i.textContent=t,document.body.appendChild(i),setTimeout(()=>{i.style.opacity="0",setTimeout(()=>i.remove(),300)},3500)}document.addEventListener("DOMContentLoaded",async()=>{uv(),hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),ww(),window.__heroField=iy(),window.__pipelineLogo=ay(),Fh=Ay({onSubmit:or}),Oa=(async()=>{try{await G0(),mw(),await lp()}catch(n){console.warn("Startup auth/subscription initialization failed:",n)}})(),await Oa,vw(),qs(),Ka(),yw(),await E0(),v0();const t=document.getElementById("flutterflow-endpoint-select");if(t){const n=yt();t.value=n}Hh(),sp();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{en===2&&e.value.trim().length>0&&($l(),Ns())}),e.addEventListener("blur",()=>{const n=document.getElementById("walkthrough-modal");en===2&&n&&We(n)}),e.addEventListener("keydown",n=>{if(n.key==="Tab"){const i=document.getElementById("walkthrough-modal");en===2&&i&&setTimeout(()=>{We(i)},100)}})),window.addEventListener("commitStateChange",n=>{const{state:i}=n.detail;i===ee.PREPARING||i===ee.VALIDATING||i===ee.PUSHING?(Be.phaseId||mp(),cd(i)):(i===ee.SUCCESS||i===ee.ERROR)&&(cd(i),setTimeout(Xl,1e3))}),sc()});function ww(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function bw(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",On),document.addEventListener("keydown",On))}function On(){const t=document.getElementById("preview-frame-container"),e=document.getElementById("main-stage-container"),n=document.getElementById("ready-state");t&&(t.style.display="none"),e&&e.classList.add("visible"),n&&n.classList.remove("hidden");const i=document.getElementById("welcome-video-player");i&&i.removeEventListener("click",On),document.removeEventListener("keydown",On),Hh()}let Vi=null;async function Ew(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++ed,n=()=>e===ed,i=await Te("flutterflow"),r=await Te("flutterflow_project_id");if(n()){if(!i){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const o=await new pi(i,"","main",yt()).listProjects();if(!n())return;if(!o||o.length===0){t.innerHTML='';return}t.innerHTML='',o.forEach(a=>{const l=document.createElement("option");l.value=a.id||a.projectId||"",l.textContent=a.name||a.projectName||`Project ${a.id}`,t.appendChild(l)}),r&&(t.value=r)}catch(s){if(!n())return;console.error("Failed to load projects for deploy:",s),t.innerHTML=''}}}function Sw(){return document.getElementById("confirm-project-select")?.value?.trim()||null}function Jl(t,e,n,i=null){Vi={codeInfo:t,checks:e,deps:n,bundlePlan:i},document.getElementById("confirm-file-name").textContent=t.fileName,document.getElementById("confirm-artifact-type").textContent=t.artifactType,document.getElementById("confirm-file-size").textContent=`${(t.content.length/1024).toFixed(1)} KB`,document.getElementById("confirm-line-count").textContent=i?`${i.fileEntries.length} files`:t.content.split(` -`).length,Ew();const r=document.getElementById("confirm-deps-list"),s=document.getElementById("confirm-deps-section");n&&Object.keys(n).length>0?(r.innerHTML=Object.entries(n).map(([u,c])=>{const d=c?`at least ${Qt(c)}`:"version resolved from your project";return`
    • • ${Qt(u)}: ${d}
    • `}).join(""),s.classList.remove("hidden")):s.classList.add("hidden");const o=document.getElementById("confirm-warnings-list"),a=document.getElementById("confirm-warnings-section");e.warnings&&e.warnings.length>0?(o.innerHTML=e.warnings.map(u=>`
    • • ${Qt(u)}
    • `).join(""),a.classList.remove("hidden")):a.classList.add("hidden"),document.getElementById("confirm-code-preview").textContent=t.content,document.getElementById("code-preview-content").classList.add("hidden"),document.getElementById("code-preview-chevron").style.transform="rotate(0deg)";const l=document.getElementById("commit-confirm-modal");l&&We(l)}function dp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&ze(e),Vi=null}function xw(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&ze(e);const n=["success-message","success-project-id","success-file-name","success-artifact-type","success-time","success-size"];for(const s of n){const o=document.getElementById(s);o&&(o.textContent="")}const i=document.getElementById("success-warnings-section");i&&i.classList.add("hidden");const r=document.getElementById("success-warnings-list");r&&(r.innerHTML="")}function fp(t){const e=(m,v)=>{const E=document.getElementById(m);E&&(E.textContent=v||"")},n=t.metadata?.fileName||"",i=t.metadata?.projectId||"",r=t.metadata?.artifactType||"",s=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",i),e("success-file-name",n),e("success-artifact-type",r),e("success-time",s),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&i&&(u.href=`https://app.flutterflow.io/project/${i}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),f=t.unverified||[],h=t.approximate||[],p=t.warnings||[];(p.length>0||f.length>0||h.length>0)&&c&&d&&(d.innerHTML=[...f.map(m=>`
    • Not verified before deploying: ${z(String(m))}
    • `),...h.map(m=>`
    • Verified approximately: ${z(String(m))}
    • `),...p.map(([m,v])=>`
    • ${z(m)}: ${z(String(v))}
    • `)].join(""),c.classList.remove("hidden"));const g=document.getElementById("commit-success-modal");g&&We(g)}function hp(t){Xl(),W0(t);const e=t.remoteRefusal===!0;Zl(t,{heading:"Deploy failed",title:e?"FlutterFlow refused this deploy — nothing was confirmed written.":"The deploy failed before FlutterFlow confirmed anything.",guidance:e?"Review the error and any per-file outcomes above, fix them in your code or in FlutterFlow, then deploy again. A refusal is definitive: no part of this deploy was applied, so retrying is safe once the problem is fixed.":"Review the error above, fix it, then deploy again. The deploy stopped before a write was confirmed, so nothing was applied."})}function Zl(t,{heading:e,title:n,guidance:i}){const r=t.targetIdentity||{},s=document.getElementById("commit-terminal-modal");if(!s)return!1;const o=(h,p)=>{const g=document.getElementById(h);g&&(g.textContent=p||"")};o("terminal-heading",e),o("terminal-title",n),o("terminal-message",t.error||t.message||"");const a=document.getElementById("terminal-identity-list");if(a){const h=[["Project",r.projectId||t.metadata?.projectId],["Endpoint",r.endpoint],["File",r.fileName||t.metadata?.fileName],["Artifact",r.artifactType||t.metadata?.artifactType]];a.innerHTML=h.map(([p,g])=>`
      ${z(p)}:${z(String(g??"—"))}
      `).join("")}const l=document.getElementById("terminal-file-outcomes");let u=t.errorMap;u&&!(u instanceof Map)&&(u=new Map(Object.entries(u))),l&&u&&u.size>0?(l.innerHTML=[...u.entries()].map(([h,p])=>`
    • ${z(h)}: ${z(Sl(p))}
    • `).join(""),l.classList.remove("hidden")):l&&l.classList.add("hidden");const c=document.getElementById("terminal-guidance");c&&(c.innerHTML=i);const d=document.getElementById("terminal-open-ff-link"),f=r.projectId||t.metadata?.projectId;return d&&(d.href=f?`https://app.flutterflow.io/project/${f}`:"https://app.flutterflow.io/"),We(s),!0}function pp(t){Zl(t,{heading:"Deploy partially applied",title:"Some custom classes reached FlutterFlow, but the deploy did not fully complete.",guidance:"The custom classes the runner confirmed are already in your project and are not lost. Review the per-file errors above, fix them in FlutterFlow or regenerate, then deploy again. Open the project to see exactly what landed."})}function gp(t){Zl(t,{heading:"Deploy outcome not yet known",title:"This browser stopped waiting before the FlutterFlow server reported a result.",guidance:"The deploy may still be finishing on the server — it was not cancelled. Open your FlutterFlow project and confirm whether the class landed before retrying, so you do not push a duplicate or build on top of an unknown state."})}function Iw(t){t&&t.target!==t.currentTarget||ze(document.getElementById("commit-terminal-modal"))}function kw(){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 ld={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}},Cw=[{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&&(xu(e,!0,"Deploying to FlutterFlow"),We(e)),this.set("prepare")},set(t,e=null){if(!(!ld[t]||t===this.phaseId)){if(!this.sequence.includes(t)){const n=this.sequence.indexOf("package");this.sequence.splice(n===-1?this.sequence.length:n,0,t)}this.phaseId=t,this.phaseStartedAt=Date.now(),this.substatus=e,this.liveSubstatus=!1,this.render(),this.timer&&clearInterval(this.timer),t!=="done"&&(this.timer=setInterval(()=>this.render(),500))}},setSubstatus(t){t&&(this.liveSubstatus=!0,this.substatus=t,this.render())},render(){const t=ld[this.phaseId];if(!t)return;const e=(Date.now()-this.phaseStartedAt)/1e3,n=t.start+(t.end-t.start)*(1-Math.exp(-e/25));if(this.phaseId==="provision"&&!this.liveSubstatus){const o=Cw.filter(a=>e>=a.after).pop();o&&(this.substatus=o.text)}const i=this.sequence.indexOf(this.phaseId),s=[`Step ${i===-1?1:i+1} of ${this.sequence.length}`];e>=5&&s.push(Aw(e)),vp(this.phaseId==="done"?100:n,t.message,s.join(" · "),this.substatus)},stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.phaseId=null;const t=document.getElementById("commit-progress-overlay");t&&(xu(t,!1),ze(t,{force:!0,restoreFocus:!1}))}};function Aw(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 mp(t){Be.start(t)}function Xl(){Be.stop()}function vp(t,e,n,i=null){const r=document.getElementById("commit-progress-bar"),s=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");r&&(r.style.width=`${Math.round(t*10)/10}%`),s&&(s.textContent=e),o&&(o.textContent=n),a&&(a.textContent=i||"",a.classList.toggle("hidden",!i))}function cd(t){const e={[ee.PREPARING]:"prepare",[ee.VALIDATING]:"validate",[ee.PUSHING]:"project",[ee.SUCCESS]:"done"};if(t===ee.ERROR){Be.timer&&clearInterval(Be.timer),Be.timer=null,vp(100,"Failed","Error occurred");return}const n=e[t];n&&Be.set(n)}function Pw(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===J.CODE_FILE):t.codeInfo?.codeType===J.CODE_FILE}let _p=!1;function yp(t){_p=t;const e=document.querySelector("#commit-confirm-modal button[data-deploy-confirm]");e&&(e.disabled=t),[...document.querySelectorAll("[data-deploy-start]"),...document.querySelectorAll("#btn-deploy-to-ff")].forEach(i=>{i.disabled=t})}function ud(t){Xl(),yp(!1);const e=xh(t);e===Le.COMMITTED?fp(t):e===Le.PARTIAL?pp(t):e===Le.UNCONFIRMED?gp(t):hp(t)}async function Fw(){if(!Vi){console.error("No pending commit data");return}if(_p){console.warn("Deploy already in flight; ignoring duplicate confirm.");return}const t=Vi;if(Vi=null,qi=Sw(),dp(),yp(!0),mp({withProvisioning:Pw(t)}),t.bundlePlan){const o=await T0(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});qi=null,ud(o);return}const{codeInfo:e}=t,{artifactType:n,artifactName:i,fileName:r}=Wh(),s=await R0(e.content,{artifactType:n,artifactName:i,fileName:r,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});qi=null,ud(s)}window.runThinkingPipeline=or;window.toggleStep=L0;window.toggleSection=M0;window.selectWorkflowStep=it;window.copyCode=N0;window.retryWithDifferentModel=j0;window.openApiKeysModal=Tl;window.closeApiKeysModal=jh;window.openComposerSettings=o0;window.closeComposerSettings=a0;window.walkthroughConnectAccount=s0;window.closeWalkthroughModal=c0;window.openWalkthroughModal=l0;window.advanceWalkthrough=$l;window.commitToFlutterFlow=F0;function Rw(){const t=document.getElementById("pipeline-input");t&&t.focus()}function Tw(){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=Rw;window.openModelSelector=Tw;window.handlePromptImageSelect=zy;window.removePromptImage=qy;window.saveApiKeys=f0;window.validateFlutterFlowConnection=Ll;window.clearAllApiKeys=h0;window.toggleKeyVisibility=y0;window.handleWelcomeVideoEnd=bw;window.dismissWelcomeVideo=On;window.initiateCommitToFlutterFlow=U0;window.updateFlutterFlowCredentialStatus=z0;window.openCommitConfirmModal=Jl;window.closeCommitConfirmModal=dp;window.closeCommitSuccessModal=xw;window.closeCommitTerminalModal=Iw;window.showCommitPartialModal=pp;window.showCommitUnconfirmedModal=gp;window.showCommitSuccessModal=fp;window.showCommitFailureModal=hp;window.toggleCodePreview=kw;window.confirmCommitToFlutterFlow=Fw;window.runRefinement=Xh;window.regenerateFromPastedErrors=Qh;window.clearErrorInput=D0;window.setFlutterFlowEndpoint=r0;window.getFlutterFlowEndpoint=yt;window.commitProgress=Be;window.openSignInModal=Ws;window.closeSignInModal=rp;window.handleMagicLinkRequest=Y0;window.handleSignOut=J0;window.handleSendNewLink=Q0;window.handleClearCache=ew;window.handleDeleteAccount=tw;window.closeDeleteUnavailableModal=nw;window.startCheckout=hw;window.openCustomerPortal=pw;window.openPricingModal=fi;window.closePricingModal=up;let jr=null,wp=null,Bn={1:"pending",2:"pending",3:"pending"},Ql=1,ec=null;const Vs={1:"Prompt Architect",2:"Code Generator",3:"Code Review"},$w={1:"Understanding your prompt",2:"Generating Dart code",3:"Running the code audit"},Mw={1:"Prompt understood",2:"Dart code generated",3:"Code audit complete"};function Gs(){return y.runId+=1,y.runId}function re(t){return t===void 0||t===y.runId}function Lw(){y.runId+=1}function tc(t){return document.getElementById(`pdot-${t}`)}function Ya(t){const e=document.getElementById("btn-run-pipeline")||document.getElementById("hero-send");e&&(e.disabled=t,e.classList.toggle("is-busy",t),t?e.setAttribute("aria-busy","true"):e.removeAttribute("aria-busy"))}function Ks(t){const e=document.getElementById("pipeline-progress");e&&(e.dataset.runState=t)}function Tn(t,e){Bn[t]=e;const n=tc(t);if(!n)return;n.dataset.state=e,n.disabled=e==="pending"||e==="skipped";const i=Vs[t],r={pending:"not started",active:"in progress",done:"complete",failed:"failed",skipped:"not run"};n.setAttribute("aria-label",`Step ${t} of 3, ${i}: ${r[e]||e}`),e==="active"?n.setAttribute("aria-current","step"):n.removeAttribute("aria-current")}function Nw(){return[1,2,3].filter(t=>Bn[t]==="done").length}function Ys(){const t=document.getElementById("pipeline-progress-fill");t&&(t.style.width=`${Nw()/3*100}%`);const e=document.getElementById("progress-stage-count");e&&(e.textContent=`Step ${Ql} of 3`)}function Js(t,{done:e=!1}={}){const n=document.getElementById("progress-title-text"),i=document.getElementById("progress-substep-text"),r=Bn[t],s=e||r==="done";if(n&&(n.textContent=s?Mw[t]:$w[t]),i){const o=s?" — complete":r==="failed"?" — stopped":"";i.textContent=`Step ${t} of 3 — ${Vs[t]}${o}`}}function Ow(t){Bn[t]==="pending"||Bn[t]==="skipped"||(ec=t,[1,2,3].forEach(e=>{const n=tc(e);n&&n.setAttribute("aria-pressed",String(e===t))}),Js(t))}function nc(){ec=null,[1,2,3].forEach(t=>{const e=tc(t);e&&e.removeAttribute("aria-pressed")})}function bp(t){const e=document.getElementById("pipeline-note");e&&(e.textContent=t||"",e.hidden=!t)}function Bw(t,e,n){re(n)&&bp(`${Gt(t)} did not answer. Continuing on ${Gt(e)}.`)}function ic(){const t=document.getElementById("pipeline-failure");if(!t)return;t.hidden=!0;const e=document.getElementById("pipeline-failure-actions");e&&e.replaceChildren()}const Dw=1120;function jw(){const t=getComputedStyle(document.documentElement).getPropertyValue("--t-morph").trim(),e=Number.parseFloat(t);return Number.isFinite(e)&&e>0?e:Dw}let ei=null,Ur=null;function Uw(){return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0}function dn(){if(Ur){try{Ur.cancel()}catch{}Ur=null}ei&&(ei.remove(),ei=null),window.removeEventListener("resize",dn)}function Ep(t,e){if(dn(),Uw()||!t||!e||!document.body||typeof Element.prototype.animate!="function")return;const n=t.getBoundingClientRect(),i=e.getBoundingClientRect();if(!n.width||!n.height||!i.width||!i.height)return;const r=document.createElement("div");r.className="composer-morph",r.setAttribute("aria-hidden","true"),r.style.cssText=`left:${i.left}px;top:${i.top}px;width:${i.width}px;height:${i.height}px;opacity:0;`,document.body.appendChild(r);const s=n.left+n.width/2-(i.left+i.width/2),o=n.top+n.height/2-(i.top+i.height/2),a=n.width/i.width,l=n.height/i.height,u=`translate(${s}px,${o}px) scale(${a},${l})`,c=r.animate([{transform:u,opacity:0,offset:0,easing:"cubic-bezier(.2,0,0,1)"},{transform:u,opacity:1,offset:.14,easing:"cubic-bezier(.4,0,.2,1)"},{transform:`translate(${s}px,${o}px) scale(${a*.93},${l*.93})`,opacity:1,offset:.28,easing:"cubic-bezier(.32,1.38,.5,1)"},{transform:"translate(0px,0px) scale(1,1)",opacity:1,offset:1}],{duration:jw(),fill:"both"});ei=r,Ur=c,window.addEventListener("resize",dn),c.onfinish=()=>{if(ei!==r)return;const d=r.animate([{opacity:1},{opacity:0}],{duration:260,fill:"forwards"});d.onfinish=()=>{ei===r&&dn()}}}function Hw(){const e=document.getElementById("composer")?.getBoundingClientRect();e&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{Ep({getBoundingClientRect:()=>e},document.getElementById("main-stage-container"))})})}function Ww(){Ep(document.getElementById("pipeline-progress"),document.getElementById("main-stage-container"))}window.addEventListener("hashchange",dn);window.addEventListener("popstate",dn);function Zs(t={}){const{prompt:e=null,runId:n}=t;if(!re(n))return;Qs(),nn(!0);const i=document.getElementById("pipeline-progress"),r=document.getElementById("results-view"),s=document.getElementById("ready-state");if(s&&s.classList.add("hidden"),r&&r.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),i&&i.classList.add("visible"),Ks("running"),e!==null){const a=document.getElementById("pipeline-submitted-prompt");a&&(a.textContent=e)}wp=Date.now();const o=document.getElementById("progress-elapsed");o&&(o.textContent="0s"),Bn={1:"pending",2:"pending",3:"pending"},nc(),ic(),bp(""),[1,2,3].forEach(a=>Tn(a,"pending")),Ft(1,n),zw()}function Ft(t,e){re(e)&&(Ql=t,nc(),[1,2,3].forEach(n=>{n===t?Tn(n,"active"):nt&&Tn(n,"pending")}),Js(t),Ys())}function tn(t,e){re(e)&&(Tn(t,"done"),ec===null&&Js(t,{done:!0}),Ys())}function Sp(t,{stage:e=1,runId:n,retry:i=xp}={}){if(!re(n))return;Xs(),Qs(),dn(),Ks("failed"),nn(!0);const r=document.getElementById("pipeline-progress");r&&r.classList.add("visible");const s=document.getElementById("results-view");s&&s.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),Tn(e,"failed"),[1,2,3].forEach(p=>{p>e&&Tn(p,"pending")}),Ql=e,nc(),Js(e),Ys();const o=kh(t),a=document.getElementById("pipeline-failure"),l=document.getElementById("pipeline-failure-title"),u=document.getElementById("pipeline-failure-message"),c=document.getElementById("pipeline-failure-hint"),d=document.getElementById("pipeline-failure-actions");if(!a||!l||!u||!d)return;if(a.dataset.kind=o.kind,l.textContent=`${Vs[e]}: ${o.title}`,u.textContent=o.message,c){const p=o.detail&&o.detail!==o.message?o.detail:"";c.textContent=p,c.hidden=!p}d.replaceChildren();const f=[o.canUpgrade&&{id:"upgrade",label:"View plans",variant:"primary",onClick:()=>fi()},o.canRetry&&{id:"retry",label:"Retry",variant:o.canUpgrade?"secondary":"primary",onClick:i},o.canEdit&&{id:"edit",label:"Edit prompt",variant:"secondary",onClick:Ja}].filter(Boolean);!o.canEdit&&!o.canRetry&&f.push({id:"edit",label:"Back to prompt",variant:"secondary",onClick:Ja}),f.forEach(p=>{const g=document.createElement("button");g.type="button",g.textContent=p.label,g.dataset.action=p.id,g.dataset.variant=p.variant,g.addEventListener("click",p.onClick),d.appendChild(g)}),a.hidden=!1;const h=d.querySelector("button");h&&h.focus({preventScroll:!0})}function Ja(){Lw(),gw(),y.isRunning=!1,Ya(!1),rn(),Ks("settled"),dn(),Xs(),Qs(),ic();const t=document.getElementById("pipeline-progress");t&&t.classList.remove("visible"),nn(!1);const e=document.getElementById("pipeline-input");e&&(y.submittedPrompt&&(e.value=y.submittedPrompt,e.dispatchEvent(new Event("input",{bubbles:!0}))),e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length))}function xp(){const t=document.getElementById("pipeline-input");t&&y.submittedPrompt&&(t.value=y.submittedPrompt,t.dispatchEvent(new Event("input",{bubbles:!0}))),Oe=y.submittedImages.slice(),cn(),ic(),or()}function zw(){Xs(),jr=setInterval(()=>{const t=(Date.now()-wp)/1e3,e=document.getElementById("progress-elapsed");e&&(e.textContent=`${Math.floor(t)}s`)},250)}function Xs(){jr&&(clearInterval(jr),jr=null)}let Gi=null;function Qs(){Gi&&(clearTimeout(Gi),Gi=null)}function cr(){Xs(),Qs(),Ks("settled"),Ys();const t=document.getElementById("pipeline-progress-fill");Gi=setTimeout(()=>{Gi=null;const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function $n(t,e=""){const n={pass:'',warning:'',fail:'',info:''};return``}function Ip(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function qw(){return __({bundle:y.artifactBundle,reviewResult:y.step3Result})}function Vw(t){return` +`;const o=lh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:s});Qs({runId:i}),Ft(2,i),it(2),Ae(2,!0);const a=await Ws(o,n,[],i);if(!re(i))return;y.step2Result=a,js(),tn(2,i);const l=document.getElementById("step2-output"),u=ci(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),it(3),Ft(3,i),Ae(3,!0);const c=await zs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,Us(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),dr();const h=Os(y.step3Result);fr(u,h)}catch(s){if(console.error("Regeneration failed:",s),!re(i))return;const o=Ns(s,{architect:2,generator:2,review:3});s.isUsageLimit&&un(),it(o),Ae(o,!1),xp(s,{stage:o,runId:i,retry:()=>tp(t,e)}),Ss(o,"error")}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function G0(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const n=await Te("flutterflow"),i=await Te("flutterflow_project_id");n&&i?(t.className="w-2 h-2 rounded-full bg-green-500",e.textContent="FlutterFlow credentials configured",e.className="text-green-600"):n||i?(t.className="w-2 h-2 rounded-full bg-yellow-500",e.textContent="FlutterFlow credentials incomplete",e.className="text-yellow-600"):(t.className="w-2 h-2 rounded-full bg-red-500",e.textContent="FlutterFlow credentials not configured",e.className="text-red-600")}async function np(t){try{const e=await fetch(`${_t}/auth/send-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:t})});if(!e.ok)throw new Error(`Failed to send magic link: HTTP ${e.status}`);return e.json()}catch(e){throw console.error("sendMagicLink failed:",{email:t,message:e.message,stack:e.stack}),e}}async function K0(t){try{const n=await(await fetch(`${_t}/auth/verify-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})})).json();if(n.error||!n.email||!n.sessionToken)throw new Error(n.error||"Invalid or expired link");return n}catch(e){throw console.error("verifyMagicLink failed:",{message:e.message,stack:e.stack}),e}}async function Y0(t){try{const e=await fetch(`${_t}/auth/refresh-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:t})});if(!e.ok)return console.error("refreshSession: non-OK response",{url:`${_t}/auth/refresh-session`,status:e.status}),null;const n=await e.json();return n.error||!n.email||!n.sessionToken?(console.warn("refreshSession: validation failed",{error:n.error,hasEmail:!!n.email,hasToken:!!n.sessionToken}),null):n}catch(e){return console.error("refreshSession: fetch failed",{url:`${_t}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function ad(t,e){const n=rp(),i=(q.email||n.email)!==t;q.email=t,q.sessionToken=e,q.isVerified=!0,ce=Ln({isLoading:!0}),localStorage.setItem(gs,JSON.stringify({email:t,sessionToken:e})),i&&up()}function ip(){q.email=null,q.sessionToken=null,q.isVerified=!1,ce=Ln({isResolved:!0}),localStorage.removeItem(gs),localStorage.removeItem(vs)}function rp(){try{const t=localStorage.getItem(gs);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(gs),{email:null,sessionToken:null}}}async function J0(){const e=new URLSearchParams(window.location.search).get("token");if(e){window.history.replaceState({},"",window.location.pathname+window.location.hash);try{const{email:n,sessionToken:i}=await K0(e);ad(n,i),sp();const r=ld();r&&!window.location.hash&&(window.location.hash=r)}catch(n){ld();const i=n.message||"Sign-in link invalid or expired.";Ee(i,"error"),qs(),Zn(i,"error")}}else{const{email:n,sessionToken:i}=rp();if(n&&i){const r=await Y0(i);r?ad(r.email,r.sessionToken):ip()}}Jl()}function Z0(){try{localStorage.setItem(Ba,JSON.stringify({hash:window.location.hash||"#home",ts:Date.now()}))}catch(t){console.warn("rememberSignInReturnSurface: failed to persist return surface:",t)}}function ld(){try{const t=localStorage.getItem(Ba);if(localStorage.removeItem(Ba),!t)return null;const{hash:e,ts:n}=JSON.parse(t);return!e||typeof n!="number"||Date.now()-n>Ry?null:e}catch(t){return console.warn("consumeSignInReturnSurface: failed to read return surface:",t),null}}function qs(){const t=document.getElementById("signin-modal");if(!t)return;Z0(),document.getElementById("signin-email-input")?.removeAttribute("aria-invalid"),Zn(""),We(t)}function sp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&ze(e)}function Zn(t,e){const n=document.getElementById("signin-message");n&&(n.textContent=t||"",n.classList.remove("signin-message-success","signin-message-error"),e&&n.classList.add(`signin-message-${e}`))}async function X0(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),n=Ts(t?.value);if(!n||!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(n)||n.length>254){t?.setAttribute("aria-invalid","true"),Zn("Please enter a valid email address.","error");return}t?.removeAttribute("aria-invalid"),e&&(e.disabled=!0,e.textContent="Sending…");const r=mh(n);r&&Zn(r,"error");try{const s=await np(n),o=s?.code===gh;t&&!o&&(t.value=""),t?.setAttribute("aria-invalid",String(o)),Zn(vh(s,n),o?"error":"success"),e&&(e.disabled=!1,e.textContent=o?"Send Sign-in Link":"Sent!",o||setTimeout(()=>{e.textContent==="Sent!"&&(e.textContent="Send Sign-in Link")},2500))}catch(s){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:n,err:s}),Zn("Something went wrong. Please try again.","error"),e&&(e.disabled=!1,e.textContent="Send Sign-in Link")}}function Q0(){q.email=null,q.sessionToken=null,q.isVerified=!1,ce=Ln({isResolved:!0}),j_({storage:window.localStorage,onIdentityChanged:Jl,onPlanChanged:Gs})}const ew=U_({sendLink:np,getEmail:()=>q.email||"",onState:tw});function tw(t){const e=document.getElementById("send-new-link-btn"),n=document.getElementById("send-new-link-msg");if(!e||!n)return;if(t.status==="pending"){e.disabled=!0,e.textContent="Sending…",n.className="acct-access-msg",n.textContent="Sending a fresh sign-in link…";return}if(t.status==="sent"){e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg",n.textContent=vh(t.data,q.email||"")||"Link sent — check your email.";return}e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg error";const i=t.error?.message?`Couldn't send a link right now. ${t.error.message}`:"Couldn't send a link right now. Please try again.";n.textContent=i}async function nw(){await ew()}function iw(){const t=B_(window.localStorage),e=t.length?`Cleared disposable UI caches: ${t.join(", ")}.`:"Nothing disposable to clear.";Ee(`${e} Your run count, identity and stored keys are kept.`,"info")}function rw(){const t=document.getElementById("delete-unavailable-modal");t&&We(t,{trigger:document.activeElement})}function sw(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("delete-unavailable-modal");e&&ze(e)}function Jl(){const t=q.isVerified&&!!q.email,e=document.getElementById("auth-signedout"),n=document.getElementById("auth-signedin"),i=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),n&&n.classList.toggle("hidden",!t),i&&i.classList.toggle("hidden",t);const r=document.getElementById("auth-user-email");r&&(r.textContent=q.email||"");const s=document.getElementById("access-signed-email");s&&(s.textContent=q.email||""),gw(),Gs()}async function op(){try{if(typeof FingerprintJS>"u"){console.warn("resolveIdentity: FingerprintJS not loaded, skipping");return}const e=await(await FingerprintJS.load()).get(),n=e.visitorId,i=await fetch(Ly,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fingerprint:e.visitorId,cookie_id:n})});if(!i.ok)throw new Error(`Identity check HTTP ${i.status}`);const r=await i.json();if(ht.userId=r.user_id,ht.token=r.identity_token||null,ht.status=r.status,ht.resolved=!0,sessionStorage.setItem($y,r.user_id),ht.token&&sessionStorage.setItem(My,ht.token),r.usage_count!==void 0){const s=gn(),a=(r.usage_month||s)===s?r.usage_count:0;localStorage.setItem(Fn,JSON.stringify({count:a,month:s})),un()}console.log(`Identity resolved: ${r.status} (${r.user_id.slice(0,8)}...) usage: ${r.usage_count??"n/a"}`)}catch(t){console.error("resolveIdentity failed:",t)}}let qo=null;function ow(t=5e3){return ht.resolved?Promise.resolve():(qo||(qo=op().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([qo,new Promise(e=>setTimeout(e,t))]))}function ap(){const t=gn();try{const e=localStorage.getItem(Fn);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Fn,month:t,err:e}),localStorage.removeItem(Fn),{count:0,month:t}}}function gn(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function ur(){const t=ap();return t.month!==gn()?{count:0,month:gn()}:t}function aw(){const e={count:ur().count+1,month:gn()};return localStorage.setItem(Fn,JSON.stringify(e)),e}function gi(){return!!ce.isLoading}function Tt(){return!!ce.isResolved}function lw(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(ms,e)?e:null}function cw(t){return t&&Object.entries(Fh).find(([,e])=>e===t)?.[0]||null}function Pr(...t){return t.find(e=>e!=null&&e!=="")}function uw(...t){return t.find(e=>e&&typeof e=="object")||{}}function dw(t){const e=t.data&&typeof t.data=="object"?t.data:t,n=uw(e.subscription,e.stripeSubscription,e.currentSubscription,e.customer?.subscriptions?.data?.[0],e.subscriptions?.data?.[0],e.subscriptions?.[0]),i=e.metadata||n.metadata||e.customer?.metadata||{},r=Pr(e.priceId,e.price_id,e.stripePriceId,e.stripe_price_id,n.priceId,n.price_id,n.plan?.id,n.price?.id,n.items?.data?.[0]?.price?.id,n.items?.[0]?.price?.id,n.lines?.data?.[0]?.price?.id),s=Pr(e.status,e.subscriptionStatus,e.subscription_status,n.status,"none"),o=lw(Pr(e.tier,e.plan,e.planId,e.plan_id,e.subscriptionTier,e.subscription_tier,e.product,e.productName,n.tier,n.plan,i.tier,i.plan)),a=Ny.has(String(s).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||cw(r)||(a||l?"professional":"free");return Ln({tier:u,status:s,periodEnd:Pr(e.periodEnd,e.currentPeriodEnd,e.current_period_end,n.current_period_end,n.periodEnd,null),isResolved:!0})}function Vs(){return ms[ce.tier]??ms.free}async function fw(){if(q.isVerified&&(!Tt()||gi())&&(await cp({force:!0}),Gs()),q.isVerified&&!Tt())return Ee("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=ur(),e=Vs();if(t>=e)return lp(t,e,{openModal:!0}),!1;const n=Math.floor(e*.8);if(t>=n){const i=e-t;Ee(`${i} run${i===1?"":"s"} remaining this month.`,"warning")}return!0}function cd(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function lp(t,e,n={}){nn(!0);const i=document.getElementById("walkthrough-modal");i&&ze(i,{restoreFocus:!1});const r=document.getElementById("ready-state");r&&r.classList.add("hidden");const s=document.getElementById("preview-frame-container");s&&(s.style.display="none");const o=document.getElementById("main-stage-container");o&&o.classList.add("visible");const a=document.getElementById("results-view");a&&a.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar");const l=document.getElementById("pipeline-progress");l&&l.classList.remove("visible");const u=document.getElementById("paywall-exhausted");if(!u){Ee(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),fi();return}const c=document.getElementById("paywall-exhausted-text");if(c){const h=ce.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"),n.openModal&&fi()}function Ka(t){return ce.tier==="free"&&Br.includes(t)?_s:t}function hw(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const n=ce.tier,r=!(q.isVerified&&!Tt())&&n==="free";Array.from(e.options).forEach(o=>{const a=Gt(o.value),l=Br.includes(o.value);o.textContent=l&&r?`${a} (PRO)`:a,o.disabled=!1}),r&&Br.includes(e.value)&&(e.value=_s),e.disabled=!1,Ju.has(e)||(e.addEventListener("change",()=>{Tt()&&ce.tier==="free"&&Br.includes(e.value)&&(e.value=_s,fi()),Ga(e.value),Pl()}),Ju.add(e));let s=document.getElementById("model-selector-free-notice");r?(s||(s=document.createElement("p"),s.id="model-selector-free-notice",s.className="text-xs text-gray-400 mt-1",t.appendChild(s)),s.innerHTML='Free plan — Gemini only. '):s&&s.remove(),Ga(e.value)}function Zl(){const t=q.isVerified&&!!q.email,e=t&&gi(),n=!t||Tt(),i=ur(),r=n?i.count:0,s=n?Vs():0,o=Math.max(0,s-r),a=`${r} / ${s} runs this month`,l=_l,u=n?ce.tier||"free":null,c=document.getElementById("topbar-credits-count");c&&(e?c.textContent="…":n?c.textContent=String(o):c.textContent="—");const d=document.getElementById("credits-balance");d&&(e?d.textContent="Checking plan…":n?d.textContent=a:d.textContent="Plan check failed");const h=document.getElementById("usage-dialog-tier");h&&(e?h.textContent="Checking…":n?h.textContent=l[u]||"Free":h.textContent="Unavailable");const f=document.getElementById("usage-dialog-status");f&&(e?f.textContent="Verifying your subscription…":n?f.textContent="Runs reset at the start of each month.":f.textContent="Could not verify your subscription. Try again or sign out.");const p=document.getElementById("usage-counter");if(p)if(e&&t)p.textContent="Checking plan…",p.className="text-xs text-gray-500";else if(!n&&t)p.textContent="Plan check failed",p.className="text-xs text-red-600 font-medium";else{p.textContent=a;const g=s>0?r/s:0;p.className=g>=1?"text-xs text-red-600 font-medium":g>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500"}if(!t){const g=document.getElementById("guest-usage-text");if(g){const m=ap(),v=m.month===gn()?m.count??0:0;g.textContent=`${v} / ${ms.free} generations used`}}pw()}function pw(){if(!(q.isVerified&&!!q.email))return;const e=gi(),n=Tt(),i=ur(),r=n?i.count:0,s=n?Vs():0,o=Math.max(0,s-r),a=n?ce.tier||"free":null,l={free:"Free",professional:"Pro",power:"Power"}[a]||"Free",u=q.email||"",c=u.split("@")[0]||u,d=document.getElementById("acct-avatar");d&&(d.textContent=(u[0]||"?").toUpperCase());const h=document.getElementById("acct-name");h&&(h.textContent=c||"—");const f=document.getElementById("acct-plan-tier"),p=document.getElementById("acct-plan-price"),g=document.getElementById("acct-plan-note"),m=document.getElementById("acct-renewal");if(f&&(f.textContent=e?"Checking…":n?l:"Plan unavailable"),p)if(e)p.textContent="—";else if(!n)p.textContent="—";else if(a==="free")p.textContent="$0 / month";else{const x=Bi(Oi[a]??0,Fl());p.textContent=`${x} / month`}if(g&&(e?g.textContent="Verifying your subscription…":n?a==="free"?g.textContent="No subscription. Upgrade for more generations.":g.textContent="billed monthly through Stripe":g.textContent="Could not verify your subscription. Check billing or sign out."),m){const x=Date.parse(ce.periodEnd||""),F=n&&a!=="free"&&!!ce.periodEnd&&!Number.isNaN(x);if(e)m.textContent="";else if(!n)m.textContent="";else if(a==="free")m.textContent="";else if(F){const $=new Date(x).toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"});m.textContent=`Renews ${$} · reset at the start of each month.`}else m.textContent="Renewal date is not available for this period."}const v=document.getElementById("acct-left-count"),E=document.getElementById("acct-left-limit"),S=document.getElementById("acct-reset-note");v&&(v.textContent=e?"…":n?String(o):"—"),E&&(E.textContent=e?"…":n?String(s):"—"),S&&(e?S.textContent="Checking plan…":n?S.textContent="Runs reset at the start of each month.":S.textContent="Plan check failed. Refresh or manage billing.");const _=document.getElementById("acct-used-count"),b=document.getElementById("acct-meter-fill"),k=document.getElementById("acct-meter-meta"),T=document.getElementById("acct-meter-track");if(_&&(_.textContent=e?"…":n?String(r):"—"),b){const x=n&&s>0?Math.min(100,Math.round(r/s*100)):0;b.style.width=`${x}%`}if(k)if(e)k.textContent="Checking…";else if(!n)k.textContent="Plan check failed";else if(s===0)k.textContent=`${r} of ${s}`;else{const x=Math.round(r/s*100);k.textContent=`${r} of ${s} · ${x}%`}T&&(e?T.setAttribute("aria-label","Checking usage…"):n?T.setAttribute("aria-label",`${r} of ${s} generations used`):T.setAttribute("aria-label","Usage unavailable")),vt()}function un(){if(Zl(),q.isVerified&&(gi()||!Tt())){cd();return}const{count:t}=ur(),e=Vs();t>=e&&!y.isRunning?lp(t,e):cd()}function gw(){Zl()}async function cp(t={}){const e=t.force===!0;if(!q.isVerified||!q.sessionToken){ce=Ln({isResolved:!0});return}ce={...ce,isLoading:!0,error:null};const n=localStorage.getItem(vs);if(!e&&n)try{const{data:i,email:r,ts:s,version:o}=JSON.parse(n);if(o===Zu&&r===q.email&&Date.now()-s<300*1e3){ce={...i,isLoading:!1,isResolved:i.isResolved!==!1};return}}catch(i){console.warn("Failed to parse subscription cache:",i,"| raw value:",n)}try{const r=await(await fetch(`${_t}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:q.sessionToken,user_id:ht.userId})})).json();if(r.error){if(["unauthorized","invalid session","expired session"].some(o=>String(r.error).toLowerCase().includes(o))){ip(),Jl();return}ce=Ln({isResolved:!1,error:r.error});return}ce=dw(r),localStorage.setItem(vs,JSON.stringify({version:Zu,data:ce,email:q.email,ts:Date.now()}))}catch(i){console.error("fetchSubscription failed:",i),ce={...ce,isLoading:!1,isResolved:!1,error:i.message}}}function up(){localStorage.removeItem(vs)}async function mw(t){if(!q.isVerified||!q.sessionToken){dp(),qs();return}if(!Fh[t]){Ee("Invalid plan selected.","error");return}const e=document.getElementById(`checkout-btn-${t}`);e&&(e.disabled=!0,e.textContent="Redirecting…");try{const i=await(await fetch(`${_t}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:q.sessionToken,currency:Fl()})})).json();if(i.error||!i.url)throw new Error(i.error||"Failed to create checkout session");const{url:r}=i;window.location.href=r}catch(n){console.error("startCheckout failed:",n),e&&(e.disabled=!1,e.textContent="Subscribe"),Ee("Could not start checkout. Please try again.","error")}}async function vw(t){if(!q.isVerified||!q.sessionToken){qs();return}const e=t||document.getElementById("manage-billing-btn"),n=e?e.textContent:"";e&&(e.disabled=!0,e.textContent="Loading…");try{const r=await(await fetch(`${_t}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:q.sessionToken})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to open billing portal");const{url:s}=r;window.location.href=s}catch(i){console.error("openCustomerPortal failed:",i),e&&(e.disabled=!1,e.textContent=n),Ee("Could not open billing portal. Please try again.","error")}}const xs=new Set;function _w(){xs.forEach(t=>t.abort()),xs.clear()}async function Is(t,e,n,i={},r=[]){const o=new AbortController;xs.add(o);let a=!1;const l=setTimeout(()=>{a=!0,o.abort()},12e4);try{const u=await fetch(Ty,{method:"POST",headers:{"Content-Type":"application/json",...ht.token?{Authorization:`Bearer ${ht.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:ht.userId,step:t,model:e,prompt:n,images:r,context:i})}),c=await u.text();let d={};try{d=c?JSON.parse(c):{}}catch{d={}}if(u.status===429){d.serverCount!==void 0&&(localStorage.setItem(Fn,JSON.stringify({count:d.serverCount,month:gn()})),un());const p=new Error(d.message||"Monthly usage limit reached. Upgrade to continue.");throw p.isUsageLimit=!0,p.pipelineStep=t,p}const h=Cv(d,t);if(h)throw h;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(d),"content type:",typeof d.content),!u.ok)throw new Error(`${d.message||d.error||"BuildShip pipeline error"} (HTTP ${u.status})`);if(t==="generator")if(d.usage_status==="success"&&Number.isFinite(d.usage_count)){const p=gn();(d.usage_month||p)===p&&(localStorage.setItem(Fn,JSON.stringify({count:d.usage_count,month:p})),un())}else aw(),un();let f=d.output||d.content;if(!f){const p=c?` (body: ${c.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${p}`)}return Array.isArray(f)&&(f=f.map(p=>typeof p=="string"?p:p.text||"").join("")),typeof f!="string"&&(f=JSON.stringify(f)),f}catch(u){if(u.name==="AbortError"){if(a)throw new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`);const c=new Error(`BuildShip ${t} request cancelled`);throw c.isPipelineCancel=!0,c}throw u instanceof TypeError?new Error(`BuildShip unreachable: ${u.message}`):u}finally{clearTimeout(l),xs.delete(o)}}let Ya=!1;function yw(){const e=new URLSearchParams(window.location.search).get("checkout");return e==="success"?(window.history.replaceState({},"",window.location.pathname+window.location.hash),up(),Ya=!0):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname+window.location.hash),Ee("Checkout cancelled.","info")),e}function ww(){if(!Ya)return;Ya=!1;const t=ce.tier!=="free";Ee(t?"Subscription active! Your plan is live.":"Checkout complete — confirming your subscription. Check Manage billing if it does not update.",t?"success":"info")}function Gs(){const t=q.isVerified&&!!q.email,e=ce.tier,n=t&&gi(),i=!t||Tt(),r=document.getElementById("subscription-tier-badge");if(r){const a=_l,l={free:"bg-gray-100 text-gray-600",professional:"bg-indigo-100 text-indigo-700",power:"bg-purple-100 text-purple-700",unresolved:"bg-red-50 text-red-600"};r.textContent=n?"Checking…":i?a[e]||"Free":"Plan unavailable",r.className=`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${i?l[e]||l.free:l.unresolved}`}const s=document.getElementById("upgrade-prompt");s&&s.classList.toggle("hidden",!t||n||!i||e!=="free");const o=document.getElementById("manage-billing-btn");o&&o.classList.toggle("hidden",!t||n||i&&e==="free"),bw(i?e:null),hw(),Pl(),un(),Pp()}function bw(t){const e=["bg-gray-100","text-gray-500","cursor-default"];Object.entries({professional:{btnId:"checkout-btn-professional",defaultText:"Subscribe"},power:{btnId:"checkout-btn-power",defaultText:"Subscribe"}}).forEach(([r,{btnId:s,defaultText:o}])=>{const a=document.getElementById(s);a&&(r===t?(a.disabled=!0,a.textContent="Current plan",a.classList.add(...e)):(a.disabled=!1,a.textContent=o,a.classList.remove(...e)))});const i=document.getElementById("free-tier-current");i&&i.classList.toggle("hidden",t!=="free")}function Ew(){document.querySelectorAll(".pm-card[data-tier]").forEach(t=>{const e=t.dataset.tier,n=pv[e];if(!n)return;const i=t.querySelector("ul.pm-features");if(i){i.innerHTML="";for(const r of n){const s=document.createElement("li");s.textContent=r,i.appendChild(s)}}})}function Ja(){const t=Fl(),e=document.getElementById("pro-price"),n=document.getElementById("power-price"),i=document.getElementById("plans-pro-price"),r=document.getElementById("plans-power-price"),s=document.getElementById("pro-price-note"),o=document.getElementById("power-price-note"),a=document.getElementById("plans-pro-price-note"),l=document.getElementById("plans-power-price-note");e&&(e.textContent=Bi(Oi.professional,t)),n&&(n.textContent=Bi(Oi.power,t)),i&&(i.textContent=Bi(Oi.professional,t)),r&&(r.textContent=Bi(Oi.power,t));const u="billed monthly";s&&(s.textContent=u),o&&(o.textContent=u),a&&(a.textContent=u),l&&(l.textContent=u)}function fi(){Ja();const t=document.getElementById("pricing-modal");t&&We(t),Gy().then(()=>Ja())}function dp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&ze(e)}function Ee(t,e="info"){const n={success:"bg-green-600 text-white",error:"bg-red-600 text-white",warning:"bg-amber-500 text-white",info:"bg-gray-800 text-white"},i=document.createElement("div");i.className=`fixed bottom-6 left-1/2 -translate-x-1/2 px-5 py-3 rounded-lg text-sm font-medium shadow-lg z-50 transition-opacity duration-300 ${n[e]||n.info}`,i.textContent=t,document.body.appendChild(i),setTimeout(()=>{i.style.opacity="0",setTimeout(()=>i.remove(),300)},3500)}document.addEventListener("DOMContentLoaded",async()=>{dv(),hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),Sw(),window.__heroField=ry(),window.__pipelineLogo=ly(),Th=Py({onSubmit:lr}),Da=(async()=>{try{await J0(),yw(),await cp()}catch(n){console.warn("Startup auth/subscription initialization failed:",n)}})(),await Da,ww(),Gs(),Ja(),Ew(),await S0(),_0();const t=document.getElementById("flutterflow-endpoint-select");if(t){const n=yt();t.value=n}zh(),op();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{en===2&&e.value.trim().length>0&&(Ll(),Bs())}),e.addEventListener("blur",()=>{const n=document.getElementById("walkthrough-modal");en===2&&n&&We(n)}),e.addEventListener("keydown",n=>{if(n.key==="Tab"){const i=document.getElementById("walkthrough-modal");en===2&&i&&setTimeout(()=>{We(i)},100)}})),window.addEventListener("commitStateChange",n=>{const{state:i}=n.detail;i===ee.PREPARING||i===ee.VALIDATING||i===ee.PUSHING?(Be.phaseId||vp(),dd(i)):(i===ee.SUCCESS||i===ee.ERROR)&&(dd(i),setTimeout(ec,1e3))}),ac()});function Sw(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function xw(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",On),document.addEventListener("keydown",On))}function On(){const t=document.getElementById("preview-frame-container"),e=document.getElementById("main-stage-container"),n=document.getElementById("ready-state");t&&(t.style.display="none"),e&&e.classList.add("visible"),n&&n.classList.remove("hidden");const i=document.getElementById("welcome-video-player");i&&i.removeEventListener("click",On),document.removeEventListener("keydown",On),zh()}let Vi=null;async function Iw(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++nd,n=()=>e===nd,i=await Te("flutterflow"),r=await Te("flutterflow_project_id");if(n()){if(!i){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const o=await new pi(i,"","main",yt()).listProjects();if(!n())return;if(!o||o.length===0){t.innerHTML='';return}t.innerHTML='',o.forEach(a=>{const l=document.createElement("option");l.value=a.id||a.projectId||"",l.textContent=a.name||a.projectName||`Project ${a.id}`,t.appendChild(l)}),r&&(t.value=r)}catch(s){if(!n())return;console.error("Failed to load projects for deploy:",s),t.innerHTML=''}}}function kw(){return document.getElementById("confirm-project-select")?.value?.trim()||null}function Xl(t,e,n,i=null){Vi={codeInfo:t,checks:e,deps:n,bundlePlan:i},document.getElementById("confirm-file-name").textContent=t.fileName,document.getElementById("confirm-artifact-type").textContent=t.artifactType,document.getElementById("confirm-file-size").textContent=`${(t.content.length/1024).toFixed(1)} KB`,document.getElementById("confirm-line-count").textContent=i?`${i.fileEntries.length} files`:t.content.split(` +`).length,Iw();const r=document.getElementById("confirm-deps-list"),s=document.getElementById("confirm-deps-section");n&&Object.keys(n).length>0?(r.innerHTML=Object.entries(n).map(([u,c])=>{const d=c?`at least ${Qt(c)}`:"version resolved from your project";return`
    • • ${Qt(u)}: ${d}
    • `}).join(""),s.classList.remove("hidden")):s.classList.add("hidden");const o=document.getElementById("confirm-warnings-list"),a=document.getElementById("confirm-warnings-section");e.warnings&&e.warnings.length>0?(o.innerHTML=e.warnings.map(u=>`
    • • ${Qt(u)}
    • `).join(""),a.classList.remove("hidden")):a.classList.add("hidden"),document.getElementById("confirm-code-preview").textContent=t.content,document.getElementById("code-preview-content").classList.add("hidden"),document.getElementById("code-preview-chevron").style.transform="rotate(0deg)";const l=document.getElementById("commit-confirm-modal");l&&We(l)}function fp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&ze(e),Vi=null}function Cw(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&ze(e);const n=["success-message","success-project-id","success-file-name","success-artifact-type","success-time","success-size"];for(const s of n){const o=document.getElementById(s);o&&(o.textContent="")}const i=document.getElementById("success-warnings-section");i&&i.classList.add("hidden");const r=document.getElementById("success-warnings-list");r&&(r.innerHTML="")}function hp(t){const e=(m,v)=>{const E=document.getElementById(m);E&&(E.textContent=v||"")},n=t.metadata?.fileName||"",i=t.metadata?.projectId||"",r=t.metadata?.artifactType||"",s=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",i),e("success-file-name",n),e("success-artifact-type",r),e("success-time",s),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&i&&(u.href=`https://app.flutterflow.io/project/${i}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),h=t.unverified||[],f=t.approximate||[],p=t.warnings||[];(p.length>0||h.length>0||f.length>0)&&c&&d&&(d.innerHTML=[...h.map(m=>`
    • Not verified before deploying: ${z(String(m))}
    • `),...f.map(m=>`
    • Verified approximately: ${z(String(m))}
    • `),...p.map(([m,v])=>`
    • ${z(m)}: ${z(String(v))}
    • `)].join(""),c.classList.remove("hidden"));const g=document.getElementById("commit-success-modal");g&&We(g)}function pp(t){ec(),V0(t);const e=t.remoteRefusal===!0;Ql(t,{heading:"Deploy failed",title:e?"FlutterFlow refused this deploy — nothing was confirmed written.":"The deploy failed before FlutterFlow confirmed anything.",guidance:e?"Review the error and any per-file outcomes above, fix them in your code or in FlutterFlow, then deploy again. A refusal is definitive: no part of this deploy was applied, so retrying is safe once the problem is fixed.":"Review the error above, fix it, then deploy again. The deploy stopped before a write was confirmed, so nothing was applied."})}function Ql(t,{heading:e,title:n,guidance:i}){const r=t.targetIdentity||{},s=document.getElementById("commit-terminal-modal");if(!s)return!1;const o=(f,p)=>{const g=document.getElementById(f);g&&(g.textContent=p||"")};o("terminal-heading",e),o("terminal-title",n),o("terminal-message",t.error||t.message||"");const a=document.getElementById("terminal-identity-list");if(a){const f=[["Project",r.projectId||t.metadata?.projectId],["Endpoint",r.endpoint],["File",r.fileName||t.metadata?.fileName],["Artifact",r.artifactType||t.metadata?.artifactType]];a.innerHTML=f.map(([p,g])=>`
      ${z(p)}:${z(String(g??"—"))}
      `).join("")}const l=document.getElementById("terminal-file-outcomes");let u=t.errorMap;u&&!(u instanceof Map)&&(u=new Map(Object.entries(u))),l&&u&&u.size>0?(l.innerHTML=[...u.entries()].map(([f,p])=>`
    • ${z(f)}: ${z(Il(p))}
    • `).join(""),l.classList.remove("hidden")):l&&l.classList.add("hidden");const c=document.getElementById("terminal-guidance");c&&(c.innerHTML=i);const d=document.getElementById("terminal-open-ff-link"),h=r.projectId||t.metadata?.projectId;return d&&(d.href=h?`https://app.flutterflow.io/project/${h}`:"https://app.flutterflow.io/"),We(s),!0}function gp(t){Ql(t,{heading:"Deploy partially applied",title:"Some custom classes reached FlutterFlow, but the deploy did not fully complete.",guidance:"The custom classes the runner confirmed are already in your project and are not lost. Review the per-file errors above, fix them in FlutterFlow or regenerate, then deploy again. Open the project to see exactly what landed."})}function mp(t){Ql(t,{heading:"Deploy outcome not yet known",title:"This browser stopped waiting before the FlutterFlow server reported a result.",guidance:"The deploy may still be finishing on the server — it was not cancelled. Open your FlutterFlow project and confirm whether the class landed before retrying, so you do not push a duplicate or build on top of an unknown state."})}function Aw(t){t&&t.target!==t.currentTarget||ze(document.getElementById("commit-terminal-modal"))}function Pw(){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 ud={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}},Fw=[{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&&(ku(e,!0,"Deploying to FlutterFlow"),We(e)),this.set("prepare")},set(t,e=null){if(!(!ud[t]||t===this.phaseId)){if(!this.sequence.includes(t)){const n=this.sequence.indexOf("package");this.sequence.splice(n===-1?this.sequence.length:n,0,t)}this.phaseId=t,this.phaseStartedAt=Date.now(),this.substatus=e,this.liveSubstatus=!1,this.render(),this.timer&&clearInterval(this.timer),t!=="done"&&(this.timer=setInterval(()=>this.render(),500))}},setSubstatus(t){t&&(this.liveSubstatus=!0,this.substatus=t,this.render())},render(){const t=ud[this.phaseId];if(!t)return;const e=(Date.now()-this.phaseStartedAt)/1e3,n=t.start+(t.end-t.start)*(1-Math.exp(-e/25));if(this.phaseId==="provision"&&!this.liveSubstatus){const o=Fw.filter(a=>e>=a.after).pop();o&&(this.substatus=o.text)}const i=this.sequence.indexOf(this.phaseId),s=[`Step ${i===-1?1:i+1} of ${this.sequence.length}`];e>=5&&s.push(Rw(e)),_p(this.phaseId==="done"?100:n,t.message,s.join(" · "),this.substatus)},stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.phaseId=null;const t=document.getElementById("commit-progress-overlay");t&&(ku(t,!1),ze(t,{force:!0,restoreFocus:!1}))}};function Rw(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 vp(t){Be.start(t)}function ec(){Be.stop()}function _p(t,e,n,i=null){const r=document.getElementById("commit-progress-bar"),s=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");r&&(r.style.width=`${Math.round(t*10)/10}%`),s&&(s.textContent=e),o&&(o.textContent=n),a&&(a.textContent=i||"",a.classList.toggle("hidden",!i))}function dd(t){const e={[ee.PREPARING]:"prepare",[ee.VALIDATING]:"validate",[ee.PUSHING]:"project",[ee.SUCCESS]:"done"};if(t===ee.ERROR){Be.timer&&clearInterval(Be.timer),Be.timer=null,_p(100,"Failed","Error occurred");return}const n=e[t];n&&Be.set(n)}function Tw(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===J.CODE_FILE):t.codeInfo?.codeType===J.CODE_FILE}let yp=!1;function wp(t){yp=t;const e=document.querySelector("#commit-confirm-modal button[data-deploy-confirm]");e&&(e.disabled=t),[...document.querySelectorAll("[data-deploy-start]"),...document.querySelectorAll("#btn-deploy-to-ff")].forEach(i=>{i.disabled=t})}function fd(t){ec(),wp(!1);const e=kh(t);e===Le.COMMITTED?hp(t):e===Le.PARTIAL?gp(t):e===Le.UNCONFIRMED?mp(t):pp(t)}async function $w(){if(!Vi){console.error("No pending commit data");return}if(yp){console.warn("Deploy already in flight; ignoring duplicate confirm.");return}const t=Vi;if(Vi=null,qi=kw(),fp(),wp(!0),vp({withProvisioning:Tw(t)}),t.bundlePlan){const o=await L0(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});qi=null,fd(o);return}const{codeInfo:e}=t,{artifactType:n,artifactName:i,fileName:r}=qh(),s=await M0(e.content,{artifactType:n,artifactName:i,fileName:r,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});qi=null,fd(s)}window.runThinkingPipeline=lr;window.toggleStep=B0;window.toggleSection=O0;window.selectWorkflowStep=it;window.copyCode=D0;window.retryWithDifferentModel=W0;window.openApiKeysModal=Ml;window.closeApiKeysModal=Hh;window.openComposerSettings=a0;window.closeComposerSettings=l0;window.walkthroughConnectAccount=o0;window.closeWalkthroughModal=u0;window.openWalkthroughModal=c0;window.advanceWalkthrough=Ll;window.commitToFlutterFlow=$0;function Mw(){const t=document.getElementById("pipeline-input");t&&t.focus()}function Lw(){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=Mw;window.openModelSelector=Lw;window.handlePromptImageSelect=qy;window.removePromptImage=Vy;window.saveApiKeys=h0;window.validateFlutterFlowConnection=Ol;window.clearAllApiKeys=p0;window.toggleKeyVisibility=w0;window.handleWelcomeVideoEnd=xw;window.dismissWelcomeVideo=On;window.initiateCommitToFlutterFlow=z0;window.updateFlutterFlowCredentialStatus=G0;window.openCommitConfirmModal=Xl;window.closeCommitConfirmModal=fp;window.closeCommitSuccessModal=Cw;window.closeCommitTerminalModal=Aw;window.showCommitPartialModal=gp;window.showCommitUnconfirmedModal=mp;window.showCommitSuccessModal=hp;window.showCommitFailureModal=pp;window.toggleCodePreview=Pw;window.confirmCommitToFlutterFlow=$w;window.runRefinement=Qh;window.regenerateFromPastedErrors=ep;window.clearErrorInput=H0;window.setFlutterFlowEndpoint=s0;window.getFlutterFlowEndpoint=yt;window.commitProgress=Be;window.openSignInModal=qs;window.closeSignInModal=sp;window.handleMagicLinkRequest=X0;window.handleSignOut=Q0;window.handleSendNewLink=nw;window.handleClearCache=iw;window.handleDeleteAccount=rw;window.closeDeleteUnavailableModal=sw;window.startCheckout=mw;window.openCustomerPortal=vw;window.openPricingModal=fi;window.closePricingModal=dp;let Hr=null,bp=null,Bn={1:"pending",2:"pending",3:"pending"},tc=1,nc=null;const Ks={1:"Prompt Architect",2:"Code Generator",3:"Code Review"},Nw={1:"Understanding your prompt",2:"Generating Dart code",3:"Running the code audit"},Ow={1:"Prompt understood",2:"Dart code generated",3:"Code audit complete"};function Ys(){return y.runId+=1,y.runId}function re(t){return t===void 0||t===y.runId}function Bw(){y.runId+=1}function ic(t){return document.getElementById(`pdot-${t}`)}function Za(t){const e=document.getElementById("btn-run-pipeline")||document.getElementById("hero-send");e&&(e.disabled=t,e.classList.toggle("is-busy",t),t?e.setAttribute("aria-busy","true"):e.removeAttribute("aria-busy"))}function Js(t){const e=document.getElementById("pipeline-progress");e&&(e.dataset.runState=t)}function Tn(t,e){Bn[t]=e;const n=ic(t);if(!n)return;n.dataset.state=e,n.disabled=e==="pending"||e==="skipped";const i=Ks[t],r={pending:"not started",active:"in progress",done:"complete",failed:"failed",skipped:"not run"};n.setAttribute("aria-label",`Step ${t} of 3, ${i}: ${r[e]||e}`),e==="active"?n.setAttribute("aria-current","step"):n.removeAttribute("aria-current")}function Dw(){return[1,2,3].filter(t=>Bn[t]==="done").length}function Zs(){const t=document.getElementById("pipeline-progress-fill");t&&(t.style.width=`${Dw()/3*100}%`);const e=document.getElementById("progress-stage-count");e&&(e.textContent=`Step ${tc} of 3`)}function Xs(t,{done:e=!1}={}){const n=document.getElementById("progress-title-text"),i=document.getElementById("progress-substep-text"),r=Bn[t],s=e||r==="done";if(n&&(n.textContent=s?Ow[t]:Nw[t]),i){const o=s?" — complete":r==="failed"?" — stopped":"";i.textContent=`Step ${t} of 3 — ${Ks[t]}${o}`}}function jw(t){Bn[t]==="pending"||Bn[t]==="skipped"||(nc=t,[1,2,3].forEach(e=>{const n=ic(e);n&&n.setAttribute("aria-pressed",String(e===t))}),Xs(t))}function rc(){nc=null,[1,2,3].forEach(t=>{const e=ic(t);e&&e.removeAttribute("aria-pressed")})}function Ep(t){const e=document.getElementById("pipeline-note");e&&(e.textContent=t||"",e.hidden=!t)}function Uw(t,e,n){re(n)&&Ep(`${Gt(t)} did not answer. Continuing on ${Gt(e)}.`)}function sc(){const t=document.getElementById("pipeline-failure");if(!t)return;t.hidden=!0;const e=document.getElementById("pipeline-failure-actions");e&&e.replaceChildren()}const Hw=1120;function Ww(){const t=getComputedStyle(document.documentElement).getPropertyValue("--t-morph").trim(),e=Number.parseFloat(t);return Number.isFinite(e)&&e>0?e:Hw}let ei=null,Wr=null;function zw(){return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0}function dn(){if(Wr){try{Wr.cancel()}catch{}Wr=null}ei&&(ei.remove(),ei=null),window.removeEventListener("resize",dn)}function Sp(t,e){if(dn(),zw()||!t||!e||!document.body||typeof Element.prototype.animate!="function")return;const n=t.getBoundingClientRect(),i=e.getBoundingClientRect();if(!n.width||!n.height||!i.width||!i.height)return;const r=document.createElement("div");r.className="composer-morph",r.setAttribute("aria-hidden","true"),r.style.cssText=`left:${i.left}px;top:${i.top}px;width:${i.width}px;height:${i.height}px;opacity:0;`,document.body.appendChild(r);const s=n.left+n.width/2-(i.left+i.width/2),o=n.top+n.height/2-(i.top+i.height/2),a=n.width/i.width,l=n.height/i.height,u=`translate(${s}px,${o}px) scale(${a},${l})`,c=r.animate([{transform:u,opacity:0,offset:0,easing:"cubic-bezier(.2,0,0,1)"},{transform:u,opacity:1,offset:.14,easing:"cubic-bezier(.4,0,.2,1)"},{transform:`translate(${s}px,${o}px) scale(${a*.93},${l*.93})`,opacity:1,offset:.28,easing:"cubic-bezier(.32,1.38,.5,1)"},{transform:"translate(0px,0px) scale(1,1)",opacity:1,offset:1}],{duration:Ww(),fill:"both"});ei=r,Wr=c,window.addEventListener("resize",dn),c.onfinish=()=>{if(ei!==r)return;const d=r.animate([{opacity:1},{opacity:0}],{duration:260,fill:"forwards"});d.onfinish=()=>{ei===r&&dn()}}}function qw(){const e=document.getElementById("composer")?.getBoundingClientRect();e&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{Sp({getBoundingClientRect:()=>e},document.getElementById("main-stage-container"))})})}function Vw(){Sp(document.getElementById("pipeline-progress"),document.getElementById("main-stage-container"))}window.addEventListener("hashchange",dn);window.addEventListener("popstate",dn);function Qs(t={}){const{prompt:e=null,runId:n}=t;if(!re(n))return;to(),nn(!0);const i=document.getElementById("pipeline-progress"),r=document.getElementById("results-view"),s=document.getElementById("ready-state");if(s&&s.classList.add("hidden"),r&&r.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),i&&i.classList.add("visible"),Js("running"),e!==null){const a=document.getElementById("pipeline-submitted-prompt");a&&(a.textContent=e)}bp=Date.now();const o=document.getElementById("progress-elapsed");o&&(o.textContent="0s"),Bn={1:"pending",2:"pending",3:"pending"},rc(),sc(),Ep(""),[1,2,3].forEach(a=>Tn(a,"pending")),Ft(1,n),Gw()}function Ft(t,e){re(e)&&(tc=t,rc(),[1,2,3].forEach(n=>{n===t?Tn(n,"active"):nt&&Tn(n,"pending")}),Xs(t),Zs())}function tn(t,e){re(e)&&(Tn(t,"done"),nc===null&&Xs(t,{done:!0}),Zs())}function xp(t,{stage:e=1,runId:n,retry:i=Ip}={}){if(!re(n))return;eo(),to(),dn(),Js("failed"),nn(!0);const r=document.getElementById("pipeline-progress");r&&r.classList.add("visible");const s=document.getElementById("results-view");s&&s.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),Tn(e,"failed"),[1,2,3].forEach(p=>{p>e&&Tn(p,"pending")}),tc=e,rc(),Xs(e),Zs();const o=Ah(t),a=document.getElementById("pipeline-failure"),l=document.getElementById("pipeline-failure-title"),u=document.getElementById("pipeline-failure-message"),c=document.getElementById("pipeline-failure-hint"),d=document.getElementById("pipeline-failure-actions");if(!a||!l||!u||!d)return;if(a.dataset.kind=o.kind,l.textContent=`${Ks[e]}: ${o.title}`,u.textContent=o.message,c){const p=o.detail&&o.detail!==o.message?o.detail:"";c.textContent=p,c.hidden=!p}d.replaceChildren();const h=[o.canUpgrade&&{id:"upgrade",label:"View plans",variant:"primary",onClick:()=>fi()},o.canRetry&&{id:"retry",label:"Retry",variant:o.canUpgrade?"secondary":"primary",onClick:i},o.canEdit&&{id:"edit",label:"Edit prompt",variant:"secondary",onClick:Xa}].filter(Boolean);!o.canEdit&&!o.canRetry&&h.push({id:"edit",label:"Back to prompt",variant:"secondary",onClick:Xa}),h.forEach(p=>{const g=document.createElement("button");g.type="button",g.textContent=p.label,g.dataset.action=p.id,g.dataset.variant=p.variant,g.addEventListener("click",p.onClick),d.appendChild(g)}),a.hidden=!1;const f=d.querySelector("button");f&&f.focus({preventScroll:!0})}function Xa(){Bw(),_w(),y.isRunning=!1,Za(!1),rn(),Js("settled"),dn(),eo(),to(),sc();const t=document.getElementById("pipeline-progress");t&&t.classList.remove("visible"),nn(!1);const e=document.getElementById("pipeline-input");e&&(y.submittedPrompt&&(e.value=y.submittedPrompt,e.dispatchEvent(new Event("input",{bubbles:!0}))),e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length))}function Ip(){const t=document.getElementById("pipeline-input");t&&y.submittedPrompt&&(t.value=y.submittedPrompt,t.dispatchEvent(new Event("input",{bubbles:!0}))),Oe=y.submittedImages.slice(),cn(),sc(),lr()}function Gw(){eo(),Hr=setInterval(()=>{const t=(Date.now()-bp)/1e3,e=document.getElementById("progress-elapsed");e&&(e.textContent=`${Math.floor(t)}s`)},250)}function eo(){Hr&&(clearInterval(Hr),Hr=null)}let Gi=null;function to(){Gi&&(clearTimeout(Gi),Gi=null)}function dr(){eo(),to(),Js("settled"),Zs();const t=document.getElementById("pipeline-progress-fill");Gi=setTimeout(()=>{Gi=null;const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function $n(t,e=""){const n={pass:'',warning:'',fail:'',info:''};return``}function kp(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function Kw(){return y_({bundle:y.artifactBundle,reviewResult:y.step3Result})}function Yw(t){return`
      ${$n(t.severity)}
      @@ -174,14 +174,14 @@ Error: ${g} ${z(t.source)}
      - `}function Gw(t){return` + `}function Jw(t){return`
    • ${z(t.title)} ${t.detail&&t.detail!==t.title?`

      ${z(t.detail)}

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

      ${z(l.reason)}

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

      ${z(l.description)}

      `:""}
    • `).join(""):'
    • No relationships for this file
    • ';return`
      - ${$n(e.status)} ${z(Ip(e.status))} + ${$n(e.status)} ${z(kp(e.status))}

      ${z(e.artifactName)}

      ${e.description?`

      ${z(e.description)}

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

      Manual FlutterFlow steps for this file

      -
        ${e.manualSteps.map(Gw).join("")}
      +
        ${e.manualSteps.map(Jw).join("")}
      `:""}
      @@ -297,7 +297,7 @@ Error: ${g}
        ${a}
      - `}function Jw(t){const e=document.getElementById("bundle-strip"),n=document.getElementById("results-summary-tab"),i=document.getElementById("artifact-tabs"),r=document.getElementById("results-file-count");if(n){const s=y.resultsViewMode==="summary";n.classList.toggle("active",s),n.setAttribute("role","tab"),n.setAttribute("aria-selected",String(s)),n.setAttribute("aria-controls","results-summary-detail"),n.tabIndex=s?0:-1}if(i&&(i.setAttribute("role","tablist"),i.setAttribute("aria-label","Artifacts in this bundle")),!t.artifacts.length){r&&(r.textContent="0 files"),e&&e.classList.remove("visible"),i&&(i.innerHTML=""),dd();return}if(r){const s=t.artifacts.length;r.textContent=`${s} ${s===1?"file":"files"}`}i&&(i.innerHTML=t.artifacts.map(s=>{const o=y.resultsViewMode==="file"&&s.id===y.selectedArtifactId;return` + `}function Qw(t){const e=document.getElementById("bundle-strip"),n=document.getElementById("results-summary-tab"),i=document.getElementById("artifact-tabs"),r=document.getElementById("results-file-count");if(n){const s=y.resultsViewMode==="summary";n.classList.toggle("active",s),n.setAttribute("role","tab"),n.setAttribute("aria-selected",String(s)),n.setAttribute("aria-controls","results-summary-detail"),n.tabIndex=s?0:-1}if(i&&(i.setAttribute("role","tablist"),i.setAttribute("aria-label","Artifacts in this bundle")),!t.artifacts.length){r&&(r.textContent="0 files"),e&&e.classList.remove("visible"),i&&(i.innerHTML=""),hd();return}if(r){const s=t.artifacts.length;r.textContent=`${s} ${s===1?"file":"files"}`}i&&(i.innerHTML=t.artifacts.map(s=>{const o=y.resultsViewMode==="file"&&s.id===y.selectedArtifactId;return` - `}).join(""),i.onclick=s=>{const o=s.target.closest(".artifact-tab");o?.dataset?.artifactId&&rc(o.dataset.artifactId)},dd()),e&&e.classList.add("visible")}function dd(){const t=document.getElementById("bundle-strip");!t||t.dataset.tabKeyboard==="bound"||(t.dataset.tabKeyboard="bound",t.addEventListener("keydown",e=>{if(e.defaultPrevented)return;const n=[document.getElementById("results-summary-tab"),...Array.from(document.querySelectorAll("#artifact-tabs .artifact-tab"))].filter(Boolean);if(!n.length||!n.includes(document.activeElement))return;let i=-1;const r=n.indexOf(document.activeElement);if(e.key==="ArrowRight")i=(r+1)%n.length;else if(e.key==="ArrowLeft")i=(r-1+n.length)%n.length;else if(e.key==="Home")i=0;else if(e.key==="End")i=n.length-1;else return;e.preventDefault();const s=n[i];if(!s)return;if(s.id==="results-summary-tab")kp();else{const a=s.dataset.artifactId;a&&rc(a)}const o=s.id==="results-summary-tab"?document.getElementById("results-summary-tab"):document.querySelector(`#artifact-tabs .artifact-tab[data-artifact-id="${s.dataset.artifactId}"]`);o&&o.focus()}))}function eo(){document.body.classList.add("results-fullscreen"),document.body.classList.add("results-with-sidebar");const t=document.getElementById("results-view"),e=document.getElementById("results-code-output"),n=document.getElementById("results-audit-output"),i=document.getElementById("results-summary-detail"),r=document.getElementById("artifact-results-split"),s=qw(),o=Bl();if(i&&(i.setAttribute("role","tabpanel"),i.setAttribute("aria-labelledby","results-summary-tab")),r){r.setAttribute("role","tabpanel");const a=s?.artifacts?.find(l=>l.id===y.selectedArtifactId);r.setAttribute("aria-labelledby",a?`artifact-tab-${a.id}`:"results-summary-tab")}if(Kw(s),Jw(s),e&&(e.textContent=""),e){const a=Ch(o);e.innerHTML=a}n&&(n.innerHTML=Yw(s)),i&&i.classList.toggle("hidden",y.resultsViewMode!=="summary"),r&&r.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function ur(t,e){nn(!0),y.selectedArtifactId||(y.selectedArtifactId=ai(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const n=document.getElementById("step3-output");n&&(n.textContent=""),eo(),rn(),Zw()}function Zw(){const t=document.getElementById("btn-feedback-up"),e=document.getElementById("btn-feedback-down"),n=document.getElementById("results-feedback-status");t&&(t.className="feedback-btn",t.setAttribute("aria-pressed","false"),t.disabled=!1,t.removeAttribute("aria-disabled")),e&&(e.className="feedback-btn",e.setAttribute("aria-pressed","false"),e.disabled=!1,e.removeAttribute("aria-disabled")),n&&(n.textContent=""),Za=!1}function rc(t){y.selectedArtifactId=t,y.resultsViewMode="file",eo()}function kp(){y.resultsViewMode="summary",eo()}function Xw(){const t=document.getElementById("btn-copy-results"),e=document.getElementById("results-copy-status"),n=Bl(),i=(r,s)=>{e&&(e.textContent=r,e.classList.toggle("ok",!!s),e.classList.toggle("fail",!s))};if(!navigator.clipboard?.writeText){i("Copying isn't supported in this browser.",!1);return}navigator.clipboard.writeText(n).then(()=>{if(i("Copied to clipboard",!0),t){t.classList.add("copied");const r=t.querySelector("span");if(r){const s=r.textContent;r.textContent="Copied!",setTimeout(()=>{t.classList.remove("copied"),r.textContent=s},2e3)}}}).catch(()=>{i("Clipboard permission was denied. Select the code to copy it manually.",!1)})}let Za=!1;async function Qw(t){const e=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down"),i=document.getElementById("results-feedback-status");if(!e||!n||Za)return;const r=l=>{i&&(i.textContent="",i.offsetWidth,i.textContent=l)},s=l=>{Za=l,[e,n].forEach(u=>{u.disabled=l,u.setAttribute("aria-disabled",String(l))})},o=t==="up"?"thumbsUp":"thumbsDown";s(!0),r("Submitting review feedback…");const a={type:o,code:y.step2Result,input:y.step1Result};try{const l=await Gl(a.type,a.code,a.input);if(!l||l.success!==!0){s(!1),r("Review feedback could not be sent. Tap again to retry.");return}e.classList.toggle("active-up",t==="up"),n.classList.toggle("active-down",t==="down"),e.setAttribute("aria-pressed",String(t==="up")),n.setAttribute("aria-pressed",String(t==="down")),s(!1),r("Review feedback saved.")}catch{s(!1),r("Review feedback could not be sent. Tap again to retry.")}}function eb(){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 Cp(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}function nn(t){const e=document.getElementById("generation-stage");e&&(t?(e.hidden=!1,e.inert=!1,requestAnimationFrame(()=>e.classList.add("is-active"))):(e.classList.remove("is-active"),e.inert=!0,setTimeout(()=>{e.classList.contains("is-active")||(e.hidden=!0)},260)))}function Ap(){const t=q.isVerified&&!!q.email,e=ce.tier||"free",n=t&&gi(),i=!t||Tt(),s=n?"Checking…":i?ml[e]||"Free":"—",o=document.getElementById("topbar-plan");o&&(o.textContent=s);const a=document.getElementById("topbar-avatar");a&&(a.textContent=(q.email||"?")[0].toUpperCase()),Yl();const l=document.getElementById("plans-free-current");l&&l.classList.toggle("hidden",e!=="free"||!i);const u=document.getElementById("plans-checkout-btn-professional");if(u){const d=e==="professional"&&i;u.disabled=d,u.textContent=d?"Current plan":"Subscribe"}const c=document.getElementById("plans-checkout-btn-power");if(c){const d=e==="power"&&i;c.disabled=d,c.textContent=d?"Current plan":"Subscribe"}}function tb(){Ap();const t=document.getElementById("credits-modal");t&&We(t)}function nb(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("credits-modal");e&&ze(e)}function Pp(t,e=!0,n=!0){if(t=["home","account","plans"].includes(t)?t:"home",document.querySelectorAll(".view[data-view]").forEach(r=>{r.dataset.view===t?(r.hidden=!1,r.removeAttribute("inert"),requestAnimationFrame(()=>{r.classList.add("is-active"),n&&r.focus({preventScroll:!0})})):(r.classList.remove("is-active"),r.setAttribute("inert","true"),setTimeout(()=>{r.classList.contains("is-active")||(r.hidden=!0)},260))}),t!=="home")nn(!1);else{const r=document.getElementById("main-stage-container");r&&r.classList.contains("visible")&&nn(!0)}if(document.querySelectorAll(".nav-link[data-view]").forEach(r=>{const s=r.dataset.view===t;r.setAttribute("aria-current",s?"page":null),s||r.removeAttribute("aria-current")}),e){const r=t==="home"?"":`#${t}`;window.location.hash!==r&&window.history.pushState({view:t},"",r||"#")}}let fd=!1;function sc(){const t=window.location.hash.replace(/^#/,"");Pp(t||"home",!1,fd),fd=!0}window.addEventListener("popstate",t=>{sc()});window.addEventListener("hashchange",()=>{sc()});window.copyResultsCode=Xw;window.selectArtifact=rc;window.selectResultsSummary=kp;window.submitResultsFeedback=Qw;window.showErrorInputPanel=eb;window.hideErrorInputPanel=Cp;window.setGenerationStageVisible=nn;window.switchView=Pp;window.selectPipelineStage=Ow;window.editPipelinePrompt=Ja;window.retryPipelineRun=xp;window.openCreditsModal=tb;window.closeCreditsModal=nb; + `}).join(""),i.onclick=s=>{const o=s.target.closest(".artifact-tab");o?.dataset?.artifactId&&oc(o.dataset.artifactId)},hd()),e&&e.classList.add("visible")}function hd(){const t=document.getElementById("bundle-strip");!t||t.dataset.tabKeyboard==="bound"||(t.dataset.tabKeyboard="bound",t.addEventListener("keydown",e=>{if(e.defaultPrevented)return;const n=[document.getElementById("results-summary-tab"),...Array.from(document.querySelectorAll("#artifact-tabs .artifact-tab"))].filter(Boolean);if(!n.length||!n.includes(document.activeElement))return;let i=-1;const r=n.indexOf(document.activeElement);if(e.key==="ArrowRight")i=(r+1)%n.length;else if(e.key==="ArrowLeft")i=(r-1+n.length)%n.length;else if(e.key==="Home")i=0;else if(e.key==="End")i=n.length-1;else return;e.preventDefault();const s=n[i];if(!s)return;if(s.id==="results-summary-tab")Cp();else{const a=s.dataset.artifactId;a&&oc(a)}const o=s.id==="results-summary-tab"?document.getElementById("results-summary-tab"):document.querySelector(`#artifact-tabs .artifact-tab[data-artifact-id="${s.dataset.artifactId}"]`);o&&o.focus()}))}function no(){document.body.classList.add("results-fullscreen"),document.body.classList.add("results-with-sidebar");const t=document.getElementById("results-view"),e=document.getElementById("results-code-output"),n=document.getElementById("results-audit-output"),i=document.getElementById("results-summary-detail"),r=document.getElementById("artifact-results-split"),s=Kw(),o=jl();if(i&&(i.setAttribute("role","tabpanel"),i.setAttribute("aria-labelledby","results-summary-tab")),r){r.setAttribute("role","tabpanel");const a=s?.artifacts?.find(l=>l.id===y.selectedArtifactId);r.setAttribute("aria-labelledby",a?`artifact-tab-${a.id}`:"results-summary-tab")}if(Zw(s),Qw(s),e&&(e.textContent=""),e){const a=Ph(o);e.innerHTML=a}n&&(n.innerHTML=Xw(s)),i&&i.classList.toggle("hidden",y.resultsViewMode!=="summary"),r&&r.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function fr(t,e){nn(!0),y.selectedArtifactId||(y.selectedArtifactId=ai(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const n=document.getElementById("step3-output");n&&(n.textContent=""),no(),rn(),eb()}function eb(){const t=document.getElementById("btn-feedback-up"),e=document.getElementById("btn-feedback-down"),n=document.getElementById("results-feedback-status");t&&(t.className="feedback-btn",t.setAttribute("aria-pressed","false"),t.disabled=!1,t.removeAttribute("aria-disabled")),e&&(e.className="feedback-btn",e.setAttribute("aria-pressed","false"),e.disabled=!1,e.removeAttribute("aria-disabled")),n&&(n.textContent=""),Qa=!1}function oc(t){y.selectedArtifactId=t,y.resultsViewMode="file",no()}function Cp(){y.resultsViewMode="summary",no()}function tb(){const t=document.getElementById("btn-copy-results"),e=document.getElementById("results-copy-status"),n=jl(),i=(r,s)=>{e&&(e.textContent=r,e.classList.toggle("ok",!!s),e.classList.toggle("fail",!s))};if(!navigator.clipboard?.writeText){i("Copying isn't supported in this browser.",!1);return}navigator.clipboard.writeText(n).then(()=>{if(i("Copied to clipboard",!0),t){t.classList.add("copied");const r=t.querySelector("span");if(r){const s=r.textContent;r.textContent="Copied!",setTimeout(()=>{t.classList.remove("copied"),r.textContent=s},2e3)}}}).catch(()=>{i("Clipboard permission was denied. Select the code to copy it manually.",!1)})}let Qa=!1;async function nb(t){const e=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down"),i=document.getElementById("results-feedback-status");if(!e||!n||Qa)return;const r=l=>{i&&(i.textContent="",i.offsetWidth,i.textContent=l)},s=l=>{Qa=l,[e,n].forEach(u=>{u.disabled=l,u.setAttribute("aria-disabled",String(l))})},o=t==="up"?"thumbsUp":"thumbsDown";s(!0),r("Submitting review feedback…");const a={type:o,code:y.step2Result,input:y.step1Result};try{const l=await Yl(a.type,a.code,a.input);if(!l||l.success!==!0){s(!1),r("Review feedback could not be sent. Tap again to retry.");return}e.classList.toggle("active-up",t==="up"),n.classList.toggle("active-down",t==="down"),e.setAttribute("aria-pressed",String(t==="up")),n.setAttribute("aria-pressed",String(t==="down")),s(!1),r("Review feedback saved.")}catch{s(!1),r("Review feedback could not be sent. Tap again to retry.")}}function ib(){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 Ap(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}function nn(t){const e=document.getElementById("generation-stage");e&&(t?(e.hidden=!1,e.inert=!1,requestAnimationFrame(()=>e.classList.add("is-active"))):(e.classList.remove("is-active"),e.inert=!0,setTimeout(()=>{e.classList.contains("is-active")||(e.hidden=!0)},260)))}function Pp(){const t=q.isVerified&&!!q.email,e=ce.tier||"free",n=t&&gi(),i=!t||Tt(),s=n?"Checking…":i?_l[e]||"Free":"—",o=document.getElementById("topbar-plan");o&&(o.textContent=s);const a=document.getElementById("topbar-avatar");a&&(a.textContent=(q.email||"?")[0].toUpperCase()),Zl();const l=document.getElementById("plans-free-current");l&&l.classList.toggle("hidden",e!=="free"||!i);const u=document.getElementById("plans-checkout-btn-professional");if(u){const d=e==="professional"&&i;u.disabled=d,u.textContent=d?"Current plan":"Subscribe"}const c=document.getElementById("plans-checkout-btn-power");if(c){const d=e==="power"&&i;c.disabled=d,c.textContent=d?"Current plan":"Subscribe"}}function rb(){Pp();const t=document.getElementById("credits-modal");t&&We(t)}function sb(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("credits-modal");e&&ze(e)}function Fp(t,e=!0,n=!0){if(t=["home","account","plans"].includes(t)?t:"home",document.querySelectorAll(".view[data-view]").forEach(r=>{r.dataset.view===t?(r.hidden=!1,r.removeAttribute("inert"),requestAnimationFrame(()=>{r.classList.add("is-active"),n&&r.focus({preventScroll:!0})})):(r.classList.remove("is-active"),r.setAttribute("inert","true"),setTimeout(()=>{r.classList.contains("is-active")||(r.hidden=!0)},260))}),t!=="home")nn(!1);else{const r=document.getElementById("main-stage-container");r&&r.classList.contains("visible")&&nn(!0)}if(document.querySelectorAll(".nav-link[data-view]").forEach(r=>{const s=r.dataset.view===t;r.setAttribute("aria-current",s?"page":null),s||r.removeAttribute("aria-current")}),e){const r=t==="home"?"":`#${t}`;window.location.hash!==r&&window.history.pushState({view:t},"",r||"#")}}let pd=!1;function ac(){const t=window.location.hash.replace(/^#/,"");Fp(t||"home",!1,pd),pd=!0}window.addEventListener("popstate",t=>{ac()});window.addEventListener("hashchange",()=>{ac()});window.copyResultsCode=tb;window.selectArtifact=oc;window.selectResultsSummary=Cp;window.submitResultsFeedback=nb;window.showErrorInputPanel=ib;window.hideErrorInputPanel=Ap;window.setGenerationStageVisible=nn;window.switchView=Fp;window.selectPipelineStage=jw;window.editPipelinePrompt=Xa;window.retryPipelineRun=Ip;window.openCreditsModal=rb;window.closeCreditsModal=sb; diff --git a/dist/index.html b/dist/index.html index 3ead2a9..63edc60 100644 --- a/dist/index.html +++ b/dist/index.html @@ -3313,7 +3313,7 @@ .send.is-busy .send-spin { animation: none; opacity: 0.6; } } - + diff --git a/e2e/stu380-deploy.spec.js b/e2e/stu380-deploy.spec.js index b3340ab..651f936 100644 --- a/e2e/stu380-deploy.spec.js +++ b/e2e/stu380-deploy.spec.js @@ -994,7 +994,7 @@ test.describe("STU-380 transport outcome regressions", () => { expect(exportCalls).toBe(2); }); - test("a late-settling provision invalidates a snapshot cached mid-write", async ({ page }) => { + test("a dropped provisioning stream keeps exports uncached until the file is seen", async ({ page }) => { await loadDeployHooks(page); const zip = new JSZip(); @@ -1003,19 +1003,26 @@ test.describe("STU-380 transport outcome regressions", () => { "name: my_app\n\ndependencies:\n flutter:\n sdk: flutter\n", ); const projectZip = await zip.generateAsync({ type: "base64" }); + zip.file( + "lib/custom_code/gauge_model.dart", + "class GaugeModel { final int value; GaugeModel(this.value); }", + ); + const projectZipWithClass = await zip.generateAsync({ type: "base64" }); + // The export only shows gauge_model.dart once the runner's write "lands" — + // before that, every export is a mid-write snapshot that must not cache. + let gaugeLanded = false; let exportCalls = 0; await page.route("**/exportCode", async (route) => { exportCalls += 1; await route.fulfill({ status: 200, contentType: "application/json", - body: JSON.stringify({ value: { project_zip: projectZip } }), + body: JSON.stringify({ + value: { project_zip: gaugeLanded ? projectZipWithClass : projectZip }, + }), }); }); - // The runner's stream opens but stays open past the UI bound — the - // underlying request keeps running (it may still write server-side). - // The test closes the stream afterwards to simulate late settlement. await page.evaluate(() => { const realFetch = window.fetch; window.fetch = (url, ...args) => { @@ -1036,9 +1043,7 @@ test.describe("STU-380 transport outcome regressions", () => { }; }); - const seeded = await page.evaluate(() => - window.__CCC_RESOLVE_PROJECT_PUBSPEC__({}), - ); + await page.evaluate(() => window.__CCC_RESOLVE_PROJECT_PUBSPEC__({})); expect(exportCalls).toBe(1); const outcome = await settleAsOutcome( @@ -1048,20 +1053,24 @@ test.describe("STU-380 transport outcome regressions", () => { ); expect(outcome.name).toBe("UnconfirmedDeployError"); - // A deploy that starts while the runner is still working re-exports and - // caches a snapshot that can predate the write. + // A follow-up deploy exports fresh but must not cache: the file may land + // later and leave this snapshot stale forever. await page.evaluate(() => window.__CCC_RESOLVE_PROJECT_PUBSPEC__({})); expect(exportCalls).toBe(2); - // When the provision request finally settles (runner finished, stream - // closed), that mid-write snapshot is dropped — the next deploy re-reads - // the project instead of provisioning the same class twice. + // Even the request settling proves nothing about the remote write — a + // dropped stream can precede it — so exports stay uncached. await page.evaluate(() => window.__CCC_PROVISION_STREAM__.close()); - await expect - .poll(async () => { - await page.evaluate(() => window.__CCC_RESOLVE_PROJECT_PUBSPEC__({})); - return exportCalls; - }) - .toBe(3); + await page.waitForTimeout(50); + await page.evaluate(() => window.__CCC_RESOLVE_PROJECT_PUBSPEC__({})); + expect(exportCalls).toBe(3); + + // The first export that actually shows the file proves the write landed; + // the path clears and caching resumes. + gaugeLanded = true; + await page.evaluate(() => window.__CCC_RESOLVE_PROJECT_PUBSPEC__({})); + expect(exportCalls).toBe(4); + await page.evaluate(() => window.__CCC_RESOLVE_PROJECT_PUBSPEC__({})); + expect(exportCalls).toBe(4); }); }); From 2c5039030570b658b33d29b7925b137dae22dcf0 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Sun, 27 Sep 2026 18:21:11 +0000 Subject: [PATCH 15/16] fix(deploy): key dirty writes by content so overlapping provisions stay honest MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A dirty path cleared on the next provision's success let a cached export be poisoned by an earlier writer still in flight: provision A times out (dirty), provision B writes different content and succeeds (cleared the path), an export caches B's snapshot, then A lands last. Dirty state is now per (path, content): a confirmed result removes only the contents it verified, and an export clears a write only when it contains that path with the exact content carried — a sighting of different content keeps the path uncached since the earlier writer may still overwrite it. Co-Authored-By: Stuart Gardoll --- app.js | 89 ++++++++------ .../{index-Bnh0pNOg.js => index-CRbziOBo.js} | 72 ++++++------ dist/index.html | 2 +- e2e/stu380-deploy.spec.js | 111 ++++++++++++++++++ 4 files changed, 199 insertions(+), 75 deletions(-) rename dist/assets/{index-Bnh0pNOg.js => index-CRbziOBo.js} (89%) diff --git a/app.js b/app.js index 4e5caf5..3898b18 100644 --- a/app.js +++ b/app.js @@ -2669,15 +2669,18 @@ function getFileNameFromPath(filePath) { // the session. Fetching them means one full project export. const projectSourceCache = new Map(); -// File paths whose provisioning outcome is unconfirmed, per cache key — the -// request ended without a verified answer, so the runner may still be writing -// them. While any dirty path is outstanding, fresh exports must not be -// cached: a snapshot taken mid-write would keep telling later deploys the -// file is missing and provision it again. A fresh export that contains a -// dirty path proves the write landed, and is the only signal that clears it — -// the request settling is not proof (a disconnected stream can precede the -// write). -const projectSourceDirtyPaths = new Map(); +// File writes whose provisioning outcome is unconfirmed, per cache key — +// each dirty path holds the contents its outstanding requests tried to write. +// The request ending (bound expiry, dropped stream) is not proof the runner +// stopped: a disconnect can precede the write. While any dirty write is +// outstanding, fresh exports must not be cached — a snapshot taken mid-write +// would keep telling later deploys the file is missing, or pin content a +// still-running writer later replaces. An export clears a dirty write only +// when it contains that path with exactly the carried content — the +// authoritative observation of that write; a confirmed provision removes the +// contents it verified. A later success for the same path cannot clear an +// earlier write whose content differs — it may still land afterwards. +const projectSourceDirtyWrites = new Map(); function projectSourceCacheKey(apiClient) { return `${apiClient.baseUrl}|${apiClient.projectId}|${apiClient.branchName}`; @@ -2687,18 +2690,28 @@ function invalidateProjectSourceCache(apiClient) { projectSourceCache.delete(projectSourceCacheKey(apiClient)); } -function markProjectSourceDirty(apiClient, paths) { +function markProjectSourceDirty(apiClient, entries) { const key = projectSourceCacheKey(apiClient); - const dirty = projectSourceDirtyPaths.get(key) ?? new Set(); - for (const path of paths) dirty.add(path); - projectSourceDirtyPaths.set(key, dirty); + const dirty = projectSourceDirtyWrites.get(key) ?? new Map(); + for (const { path, content } of entries) { + const writes = dirty.get(path) ?? new Set(); + writes.add(content); + dirty.set(path, writes); + } + projectSourceDirtyWrites.set(key, dirty); } -function clearProjectSourceDirty(apiClient, paths) { - const dirty = projectSourceDirtyPaths.get(projectSourceCacheKey(apiClient)); +function clearProjectSourceDirty(apiClient, entries) { + const key = projectSourceCacheKey(apiClient); + const dirty = projectSourceDirtyWrites.get(key); if (!dirty) return; - for (const path of paths) dirty.delete(path); - if (dirty.size === 0) projectSourceDirtyPaths.delete(projectSourceCacheKey(apiClient)); + for (const { path, content } of entries) { + const writes = dirty.get(path); + if (!writes) continue; + writes.delete(content); + if (writes.size === 0) dirty.delete(path); + } + if (dirty.size === 0) projectSourceDirtyWrites.delete(key); } /** @@ -2925,24 +2938,20 @@ async function provisionMissingCodeFiles( if (error instanceof UnconfirmedDeployError) { invalidateProjectSourceCache(apiClient); // Every file this request may have written stays dirty until a fresh - // export shows it — the runner can keep working after the request is - // lost or the bound expires, and its settlement is not proof the write - // finished (or started). While dirty, exports are never cached. - markProjectSourceDirty( - apiClient, - missingCodeFiles.map((entry) => entry.path), - ); + // export shows the same content — the runner can keep working after the + // request is lost or the bound expires, and its settlement is not proof + // the write finished (or started). While dirty, exports are never + // cached. + markProjectSourceDirty(apiClient, missingCodeFiles); } throw error; } invalidateProjectSourceCache(apiClient); - // A confirmed result proves these files were written — they are no longer - // dirty even if they were provisioned uncertainly in an earlier deploy. - clearProjectSourceDirty( - apiClient, - missingCodeFiles.map((entry) => entry.path), - ); + // A confirmed result proves this request's writes landed — only its own + // contents clear; an earlier unconfirmed write of different content to the + // same path may still be in flight and stays dirty. + clearProjectSourceDirty(apiClient, missingCodeFiles); if (result.verificationSkipped) { console.warn(`[custom class deploy] ${result.verificationSkipped}`); @@ -3010,16 +3019,20 @@ async function resolveProjectPubspec(apiClient, newDependencies = {}) { ); } - const dirtyPaths = projectSourceDirtyPaths.get(cacheKey); - if (dirtyPaths) { - // This fresh export is the authoritative read: every dirty path it - // shows is proven written and clears; the rest keep exports uncached. - for (const path of [...dirtyPaths]) { - if (projectSource.files.has(path)) dirtyPaths.delete(path); + const dirty = projectSourceDirtyWrites.get(cacheKey); + if (dirty) { + // This fresh export is the authoritative read: a dirty write clears + // only when the export contains its path with exactly the content that + // write carried — different content means another writer may still + // overwrite it, so the entry (and the cache) stays out of play. + for (const [path, writes] of [...dirty]) { + const observed = projectSource.files.get(path); + if (observed !== undefined) writes.delete(observed); + if (writes.size === 0) dirty.delete(path); } - if (dirtyPaths.size === 0) projectSourceDirtyPaths.delete(cacheKey); + if (dirty.size === 0) projectSourceDirtyWrites.delete(cacheKey); } - if (!projectSourceDirtyPaths.has(cacheKey)) { + if (!projectSourceDirtyWrites.has(cacheKey)) { projectSourceCache.set(cacheKey, projectSource); } } diff --git a/dist/assets/index-Bnh0pNOg.js b/dist/assets/index-CRbziOBo.js similarity index 89% rename from dist/assets/index-Bnh0pNOg.js rename to dist/assets/index-CRbziOBo.js index e1dbe66..e8039ea 100644 --- a/dist/assets/index-Bnh0pNOg.js +++ b/dist/assets/index-CRbziOBo.js @@ -1,7 +1,7 @@ -(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const s of r)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function n(r){const s={};return r.integrity&&(s.integrity=r.integrity),r.referrerPolicy&&(s.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?s.credentials="include":r.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function i(r){if(r.ep)return;r.ep=!0;const s=n(r);fetch(r.href,s)}})();var w=typeof window<"u"?window:void 0,Ne=typeof globalThis<"u"?globalThis:w,He=Ne?.navigator,P=Ne?.document,me=Ne?.location,el=Ne?.fetch,Vo=Ne!=null&&Ne.XMLHttpRequest&&"withCredentials"in new Ne.XMLHttpRequest?Ne.XMLHttpRequest:void 0,pc=Ne?.AbortController,Op=Ne?.CompressionStream,Ge=He?.userAgent;function gd(){return!(!w||w.navigator.onLine===!1)}var _i=typeof globalThis<"u"?globalThis:w;_i&&typeof self>"u"&&(_i.self=_i),_i&&typeof File>"u"&&(_i.File=function(){});var B=w??{},ne={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function gc(t,e,n,i,r,s,o){try{var a=t[s](o),l=a.value}catch(u){return void n(u)}a.done?e(l):Promise.resolve(l).then(i,r)}function se(t){return function(){var e=this,n=arguments;return new Promise((function(i,r){var s=t.apply(e,n);function o(l){gc(s,i,r,o,a,"next",l)}function a(l){gc(s,i,r,o,a,"throw",l)}o(void 0)}))}}function I(){return I=Object.assign?Object.assign.bind():function(t){for(var e=1;arguments.length>e;e++){var n=arguments[e];for(var i in n)({}).hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},I.apply(null,arguments)}function md(t,e){if(t==null)return{};var n={};for(var i in t)if({}.hasOwnProperty.call(t,i)){if(e.indexOf(i)!==-1)continue;n[i]=t[i]}return n}var mc=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function vc(t){return typeof t=="string"||t}function _c(t){return typeof t=="string"?t:void 0}var yi,Bp=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],Ut=(function(t){return t.AnonymousId="anonymous_id",t.DistinctId="distinct_id",t.Props="props",t.EnablePersonProcessing="enable_person_processing",t.PersonMode="person_mode",t.FeatureFlagDetails="feature_flag_details",t.FeatureFlags="feature_flags",t.FeatureFlagPayloads="feature_flag_payloads",t.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",t.BootstrapFeatureFlags="bootstrap_feature_flags",t.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",t.OverrideFeatureFlags="override_feature_flags",t.Queue="queue",t.AiQueue="ai_queue",t.LogsQueue="logs_queue",t.OptedOut="opted_out",t.SessionId="session_id",t.SessionStartTimestamp="session_start_timestamp",t.SessionLastTimestamp="session_timestamp",t.PersonProperties="person_properties",t.GroupProperties="group_properties",t.InstalledAppBuild="installed_app_build",t.InstalledAppVersion="installed_app_version",t.SessionReplay="session_replay",t.PushRegistered="push_registered",t.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",t.SurveyLastSeenDate="survey_last_seen_date",t.SurveysSeen="surveys_seen",t.Surveys="surveys",t.RemoteConfig="remote_config",t.FlagsEndpointWasHit="flags_endpoint_was_hit",t.DeviceId="device_id",t})({}),yc=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),Dp=["$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"],jp=["token"],vd="NativeGzipValidationError",Go=t=>t.length>=2&&t[0]===31&&t[1]===139,wc=(t,e)=>t===yc.GZipJS||e===yc.GZipJS||e==="gzip",bc=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",mr=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=vd,e},Up=(function(){var t=se((function*(e,n){18>e.size&&mr("too-short");var i=new Uint8Array(yield e.slice(0,10).arrayBuffer());Go(i)&&i[2]===8||mr("invalid-header");var r=new DataView(yield e.slice(e.size-8).arrayBuffer());r.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(yi)return yi;yi=[];for(var c=0;256>c;c++){for(var d=c,h=0;8>h;h++)d=1&d?3988292384^d>>>1:d>>>1;yi[c]=d>>>0}return yi})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(n)&&mr("invalid-crc");var s=n.length>>>0;r.getUint32(4,!0)!==s&&mr("invalid-size")}));return function(e,n){return t.apply(this,arguments)}})();function Ko(){return Ko=se((function*(t,e,n){e===void 0&&(e=!0);try{var i=new TextEncoder().encode(t),r=new globalThis.CompressionStream("gzip"),s=r.writable.getWriter(),o=s.write(i).then((()=>s.close())).catch((function(){var u=se((function*(c){try{yield s.abort(c)}catch{}throw c}));return function(c){return u.apply(this,arguments)}})()),a=new Response(r.readable).blob(),l=(yield Promise.all([a,o]))[0];return yield Up(l,i),l}catch(u){if(n!=null&&n.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),Ko.apply(this,arguments)}var Hp=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],Ec=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var n=t.toLowerCase();return Hp.concat(e).some((i=>{var r=i.toLowerCase();return n.indexOf(r)!==-1}))};function j(t,e){return t.indexOf(e)!==-1}var ks=function(t){return t.trim()},Yo=function(t){return t.replace(/^\$/,"")};function _d(t){var e,n=[];return(e=JSON.stringify(t,(function(i,r){if(typeof r=="bigint")return r.toString();if(typeof r!="function"&&typeof r!="symbol"){if(r instanceof Error)return{name:r.name,message:r.message,stack:r.stack};if(r&&typeof r=="object"){for(;n.length>0&&n[n.length-1]!==this;)n.pop();if(n.includes(r))return"[Circular]";n.push(r)}return r}})))!==null&&e!==void 0?e:"null"}var yd=Object.prototype,wd=yd.hasOwnProperty,Cs=yd.toString,U=Array.isArray||function(t){return Cs.call(t)==="[object Array]"},je=t=>typeof t=="function",he=t=>t===Object(t)&&!U(t),Kt=t=>{if(he(t)){for(var e in t)if(wd.call(t,e))return!1;return!0}return!1},C=t=>t===void 0,X=t=>Cs.call(t)=="[object String]",Jo=t=>X(t)&&t.trim().length===0,Ye=t=>t===null,H=t=>C(t)||Ye(t),ke=t=>Cs.call(t)=="[object Number]"&&t==t,Dt=t=>ke(t)&&t>0,mt=t=>Cs.call(t)==="[object Boolean]",Wp=t=>t instanceof FormData,zp=t=>j(Dp,t),qp=t=>j(jp,t);function bd(t){return t===null||typeof t!="object"}function zr(t,e){return{}.toString.call(t)==="[object "+e+"]"}function tl(t){return typeof Event<"u"&&Ed(t,Event)}function Ed(t,e){try{return t instanceof e}catch{return!1}}var Vp=[!0,"true",1,"1","yes"],ho=t=>j(Vp,t),Gp=[!1,"false",0,"0","no"];function At(t,e,n,i,r){return e>n&&(i.warn("min cannot be greater than max."),e=n),ke(t)?t>n?(i.warn(" cannot be greater than max: "+n+". Using max value instead."),n):e>t?(i.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(i.warn(" must be a number. using max or fallback. max: "+n+", fallback: "+r),At(r||n,e,n,i))}class Kp{constructor(e){this.tt={},this.et=e.et,this.it=At(e.bucketSize,0,100,e.rt),this.nt=At(e.refillRate,0,this.it,e.rt),this.st=At(e.refillInterval,0,864e5,e.rt)}ot(e,n){var i=Math.floor((n-e.lastAccess)/this.st);i>0&&(e.tokens=Math.min(e.tokens+i*this.nt,this.it),e.lastAccess=e.lastAccess+i*this.st)}consumeRateLimit(e){var n,i=Date.now(),r=String(e),s=this.tt[r];return s?this.ot(s,i):this.tt[r]=s={tokens:this.it,lastAccess:i},s.tokens===0||(s.tokens--,s.tokens===0&&((n=this.et)==null||n.call(this,e)),s.tokens===0)}stop(){this.tt={}}}var rt="Mobile",qr="iOS",Yt="Android",ti="Tablet",Sd=Yt+" "+ti,xd="iPad",Id="Apple",kd=Id+" Watch",Di="Safari",ni="BlackBerry",Cd="Samsung",Ad=Cd+"Browser",Pd=Cd+" Internet",Pn="Chrome",Yp=Pn+" OS",Fd=Pn+" "+qr,nl="Internet Explorer",Rd=nl+" "+rt,il="Opera",Jp=il+" Mini",rl="Edge",Td="Microsoft "+rl,Xn="Firefox",$d=Xn+" "+qr,Ki="Nintendo",Yi="PlayStation",Qn="Xbox",Md=Yt+" "+rt,Ld=rt+" "+Di,Fi="Windows",Zo=Fi+" Phone",Sc="Nokia",Xo="Ouya",Nd="Generic",Zp=Nd+" "+rt.toLowerCase(),Od=Nd+" "+ti.toLowerCase(),Qo="Konqueror",Bd="Oculus Browser",Vr="Vivaldi",Dd="Yandex",Gr="Whale",ea="DuckDuckGo",jd="Pale Moon",Kr="Waterfox",ji="Brave",Ud="Google Search App",we="(\\d+(\\.\\d+)?)",po=new RegExp("Version/"+we),Xp=new RegExp(Qn,"i"),Qp=new RegExp(Yi+" \\w+","i"),eg=new RegExp(Ki+" \\w+","i"),sl=new RegExp(ni+"|PlayBook|BB10","i"),tg={"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"},Hd=function(t,e,n,i){e=e||"";var r=(function(s){return s!=null&&s.brave?ji:null})(n);return r||(i!=null&&i.detectGoogleSearchApp&&j(t,"GSA/")?Ud:j(t," OPR/")&&j(t,"Mini")?Jp:j(t," OPR/")?il:sl.test(t)?ni:j(t,"IE"+rt)||j(t,"WPDesktop")?Rd:j(t,"OculusBrowser")?Bd:j(t,Ad)?Pd:j(t,rl)||j(t,"Edg/")?Td:j(t,Vr+"/")?Vr:j(t,"YaBrowser/")?Dd:j(t,Gr+"/")?Gr:j(t,ea+"/")||j(t,"Ddg/")?ea:j(t,"FBIOS")?"Facebook "+rt:j(t,"UCWEB")||j(t,"UCBrowser")?"UC Browser":j(t,"CriOS")?Fd:j(t,"CrMo")||j(t,Pn)?Pn:j(t,Yt)&&j(t,Di)?Md:j(t,"FxiOS")?$d:j(t.toLowerCase(),Qo.toLowerCase())?Qo:j(t,ji+"/")?ji:((s,o)=>o&&j(o,Id)||(function(a){return j(a,Di)&&!j(a,Pn)&&!j(a,Yt)})(s))(t,e)?j(t,rt)?Ld:Di:j(t,"PaleMoon/")?jd:j(t,Kr+"/")?Kr:j(t,Xn)?Xn:j(t,"MSIE")||j(t,"Trident/")?nl:j(t,"Gecko")?Xn:"")},ng={[Rd]:[new RegExp("rv:"+we)],[Td]:[new RegExp(rl+"?\\/"+we)],[Pn]:[new RegExp("("+Pn+"|CrMo)\\/"+we)],[Fd]:[new RegExp("CriOS\\/"+we)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+we)],[Di]:[po],[Ld]:[po],[il]:[new RegExp("(Opera|OPR)\\/"+we)],[Xn]:[new RegExp(Xn+"\\/"+we)],[$d]:[new RegExp("FxiOS\\/"+we)],[Qo]:[new RegExp("Konqueror[:/]?"+we,"i")],[ni]:[new RegExp(ni+" "+we),po],[Md]:[new RegExp("android\\s"+we,"i")],[Pd]:[new RegExp(Ad+"\\/"+we)],[Bd]:[new RegExp("OculusBrowser\\/"+we)],[Vr]:[new RegExp(Vr+"\\/"+we)],[Dd]:[new RegExp("YaBrowser\\/"+we)],[Gr]:[new RegExp(Gr+"\\/"+we)],[ji]:[new RegExp(ji+"\\/"+we)],[ea]:[new RegExp("(DuckDuckGo|Ddg)\\/"+we)],[jd]:[new RegExp("PaleMoon\\/"+we)],[Kr]:[new RegExp(Kr+"\\/"+we)],[Ud]:[new RegExp("GSA\\/"+we)],[nl]:[new RegExp("(rv:|MSIE )"+we)],Mozilla:[new RegExp("rv:"+we)]},ig=function(t,e,n,i){var r=Hd(t,e,n,i),s=ng[r];if(C(s))return null;for(var o=0;s.length>o;o++){var a=t.match(s[o]);if(a)return parseFloat(a[a.length-2])}return null},xc=[[new RegExp(Qn+"; "+Qn+" (.*?)[);]","i"),t=>[Qn,t&&t[1]||""]],[new RegExp(Ki,"i"),[Ki,""]],[new RegExp(Yi,"i"),[Yi,""]],[sl,[ni,""]],[new RegExp(Fi,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Zo,""];if(new RegExp(rt).test(e)&&!/IEMobile\b/.test(e))return[Fi+" "+rt,""];var n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){var i=tg[n[1]]||"";return/arm/i.test(e)&&(i="RT"),[Fi,i]}return[Fi,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>t&&t[3]?[qr,[t[3],t[4],t[5]||"0"].join(".")]:[qr,""]],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{var e="";return t&&t.length>=3&&(e=C(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+Yt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Yt+")","i"),t=>t&&t[2]?[Yt,[t[2],t[3],t[4]||"0"].join(".")]:[Yt,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{var e=["Mac OS X",""];return t&&t[1]&&(e[1]=[t[1],t[2],t[3]||"0"].join(".")),e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[Yp,""]],[/Linux|debian/i,["Linux",""]]],Ic=function(t){return eg.test(t)?Ki:Qp.test(t)?Yi:Xp.test(t)?Qn:new RegExp(Xo,"i").test(t)?Xo:new RegExp("("+Zo+"|WPDesktop)","i").test(t)?Zo:/iPad/.test(t)?xd:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?kd:sl.test(t)?ni:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(Sc,"i").test(t)?Sc:/(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(rt).test(t)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(t)||/pixel[\daxl ]{1,6}/i.test(t)&&!/pixel c/i.test(t)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(t)||/lmy47v/i.test(t)&&!/QTAQZ3/i.test(t)?Yt:Sd:new RegExp("(pda|"+rt+")","i").test(t)?Zp:new RegExp(ti,"i").test(t)&&!new RegExp(ti+" pc","i").test(t)?Od:""},rg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function kc(t,e){return typeof(n=t)=="string"&&rg.test(n)?t:e();var n}function fn(t){return t&&t.split("#")[0]}function ol(t,e){var n=setTimeout(t,e);return n?.unref&&n?.unref(),n}function Cc(t,e,n){return Wd.apply(this,arguments)}function Wd(){return(Wd=se((function*(t,e,n){var i;try{return yield Promise.race([t,new Promise(((r,s)=>{i=ol((()=>{try{n?.(),r()}catch(o){s(o)}}),e)}))])}finally{clearTimeout(i)}}))).apply(this,arguments)}var sg=t=>t instanceof Error,zd={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}},og=zd.info;function qd(t){if(mt(t))return{boolValue:t};if(typeof t=="number")return Number.isFinite(t)?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:{stringValue:String(t)};if(typeof t=="string")return{stringValue:t};if(U(t))return{arrayValue:{values:t.map((e=>qd(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function Yr(t){var e=[];for(var n in t){var i=t[n];Ye(i)||C(i)||e.push({key:n,value:qd(i)})}return e}function ag(t,e){var n=zd[t.level||"info"]||og,i=n.text,r=n.number,s=String(Date.now())+"000000",o={};e.distinctId&&(o.posthogDistinctId=e.distinctId),e.sessionId&&(o.sessionId=e.sessionId),e.windowId&&(o["window.id"]=e.windowId),H(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),H(e.lastActivityTimestamp)||(o.lastActivityTimestamp=String(e.lastActivityTimestamp)),e.currentUrl&&(o["url.full"]=e.currentUrl),e.screenName&&(o["screen.name"]=e.screenName),e.appState&&(o["app.state"]=e.appState),e.activeFeatureFlags&&e.activeFeatureFlags.length>0&&(o.feature_flags=e.activeFeatureFlags);var a=I({},o,t.attributes||{}),l={timeUnixNano:s,observedTimeUnixNano:s,severityNumber:r,severityText:i,body:{stringValue:t.body},attributes:Yr(a)};return t.trace_id&&(l.traceId=t.trace_id),t.span_id&&(l.spanId=t.span_id),C(t.trace_flags)||(l.flags=t.trace_flags),l}function Vd(t,e,n){return I({},t.resourceAttributes,{"service.name":t.serviceName||"unknown_service"},t.environment&&{"deployment.environment":t.environment},t.serviceVersion&&{"service.version":t.serviceVersion},{"telemetry.sdk.name":e,"telemetry.sdk.version":n})}function Gd(t,e,n,i){return{resourceLogs:[{resource:{attributes:Yr(e)},scopeLogs:[{scope:{name:n,version:i},logRecords:t}]}]}}let lg=class{constructor(t,e,n,i,r,s,o){var a;s===void 0&&(s=()=>Promise.resolve()),this._instance=t,this.Ne=e,this.rt=n,this.ut=i,this.ht=r,this.dt=s,this.vt=o,this.ct=null,this.ft=0,this.yt=0,this.bt=0,this._t=0,this.wt=!1,this.kt=e.maxBufferSize,this.xt=Math.max((a=e.maxQueueSize)!==null&&a!==void 0?a:e.maxBufferSize,e.maxBufferSize),this.St=e.flushIntervalMs,this.Ct=e.maxBatchRecordsPerPost,this.Mt=e.rateCapWindowMs,this.Tt=e.maxLogsPerInterval}reset(){this.Et(),this.ct=null,this.bt=0,this._t=0,this.wt=!1,this.ft=0,this.yt=0,this.Ct=this.Ne.maxBatchRecordsPerPost}onReconnect(){this.yt=0,this.It()}captureLog(t){if(!this._instance.isDisabled&&!this._instance.optedOut&&t!=null&&t.body){var e=this.Pt(t);if(e!==null)if(e.body){if(this.Rt()){var n={record:ag(e,this.ut())};this.ht((()=>this.At(n)))}}else this.rt.info("Log was rejected in beforeSend function")}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Log was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for log:",o),null}return i}Rt(){if(this.Tt===void 0)return!0;var t=Date.now(),e=t-this.bt;return this.Mt>e&&e>=0||(this.bt=t,this._t=0,this.wt=!1),this.Tt>this._t?(this._t++,!0):(this.wt||(this.rt.warn("captureLog dropping logs: exceeded "+this.Tt+" logs per "+this.Mt+"ms"),this.wt=!0),!1)}flush(){var t=this;return se((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return se((function*(){var e;t.Et();var n=(e=t._instance.getPersistedProperty(Ut.LogsQueue))!==null&&e!==void 0?e:[];if(n.length!==0)for(var i=n.length,r=0;n.length>0&&i>r;){var s,o;t.ft=0;var a=Math.min(n.length,t.Ct),l=n.slice(0,a),u=Gd(l.map((d=>d.record)),t.Lt(),(s=t.vt)!==null&&s!==void 0?s:t._instance.getLibraryId(),t._instance.getLibraryVersion()),c=yield t._instance.Ot(u);if(c.kind==="too-large"&&l.length>1)t.Ct=Math.max(1,Math.floor(l.length/2)),t.rt.warn("Received 413 when sending logs batch of size "+l.length+", reducing batch size to "+t.Ct);else if(c.kind==="retry-later"||(c.kind==="too-large"?t.rt.warn("Dropping a single log record after 413 with batch size 1 — the record is larger than the server cap and cannot be split further."):c.kind==="ok"&&t.Ne.maxBatchRecordsPerPost>t.Ct&&(t.Ct=Math.min(t.Ne.maxBatchRecordsPerPost,t.Ct+1)),yield t.Dt(l.length),n=(o=t._instance.getPersistedProperty(Ut.LogsQueue))!==null&&o!==void 0?o:[],r+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return se((function*(){var n,i=Math.max(0,t-e.ft),r=(n=e._instance.getPersistedProperty(Ut.LogsQueue))!==null&&n!==void 0?n:[];e._instance.setPersistedProperty(Ut.LogsQueue,r.slice(i)),yield e.dt()}))()}Lt(){return Vd(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var n=(e=this._instance.getPersistedProperty(Ut.LogsQueue))!==null&&e!==void 0?e:[];this.xt>n.length||(n.shift(),this.ft++,this.rt.info("Logs queue is full, dropping oldest record.")),n.push(t),this._instance.setPersistedProperty(Ut.LogsQueue,n),this.kt>n.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=ol((()=>{this.Nt=void 0,this.It()}),t))}qt(){var t=Math.min(Math.max(0,this.yt-1),6);return this.St*Math.pow(2,t)}jt(){var t=this._instance.getPersistedProperty(Ut.LogsQueue);return!!t&&t.length>0}shutdown(t){var e=this;return se((function*(){e.Et();var n=e.flush().catch((()=>{}));t!==void 0?yield Cc(n,t):yield n}))()}flushWithTimeout(t){var e=this;return se((function*(){var n=e.flush();yield Cc(n,t,(()=>{n.catch((()=>{}))}))}))()}It(){this.flush().then((()=>{this.yt=0}),(t=>{this.yt++,this.rt.error("PostHog logs flush failed:",t)})).finally((()=>{!this._instance.isDisabled&&this.jt()&&this.$t(this.qt())}))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}};var go=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function Ac(t){return String(t)+"000000"}function Pc(t,e,n,i){var r="";return i&&(r=Object.keys(i).sort().map((s=>JSON.stringify(s)+":"+JSON.stringify(i[s]))).join(",")),t+"\0"+e+"\0"+(n??"")+"\0"+r}let cg=class{constructor(t,e,n){this._instance=t,this.Ne=e,this.rt=n,this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Wt=0}count(t,e,n){e===void 0&&(e=1),this.Vt({name:t,type:"count",value:e,unit:n?.unit,attributes:n?.attributes})}gauge(t,e,n){this.Vt({name:t,type:"gauge",value:e,unit:n?.unit,attributes:n?.attributes})}histogram(t,e,n){this.Vt({name:t,type:"histogram",value:e,unit:n?.unit,attributes:n?.attributes})}flush(){var t=this,e=this.ct,n=(function(){var r=se((function*(){e&&(yield e.catch((()=>{}))),yield t.Zt()}));return function(){return r.apply(this,arguments)}})(),i=n().finally((()=>{this.ct===i&&(this.ct=null)}));return this.ct=i,i}drainWindow(){if(this.Bt.size===0)return null;var t=this.Bt;return this.Bt=new Map,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Gt(t)}reset(){this.Wt++,this.Et(),this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set}Vt(t){if(!this._instance.isDisabled&&!this._instance.optedOut){var e=this.Pt(t);if(e!==null)if(e.name&&typeof e.name=="string")if(typeof e.value=="number"&&Number.isFinite(e.value))if(e.type==="count"&&0>e.value)this.rt.warn("Dropping count '"+e.name+"': counters are monotonic, value must be >= 0");else{var n,i;try{n=e.attributes?I({},e.attributes):void 0,i=Pc(e.type,e.name,e.unit,n)}catch(o){return void this.rt.warn("Dropping metric '"+e.name+"': attributes could not be serialized",o)}var r=this.Bt.get(i);if(!r){if(!this.Qt())return;r={name:e.name,type:e.type,unit:e.unit,attributes:n,windowStartMs:Date.now()},this.Bt.set(i,r)}var s=this.Ut.get(e.name);s===void 0?this.Ut.set(e.name,e.type):s===e.type||this.zt.has(e.name)||(this.zt.add(e.name),this.rt.warn("Metric name '"+e.name+"' is already used as a "+s+"; recording it as a "+e.type+" too will blend both series in charts. Use a distinct name.")),this.Kt(r,e.value),this.$t()}else this.rt.warn("Dropping metric '"+e.name+"': value must be a finite number");else this.rt.warn("Dropping metric with empty name")}}Qt(){return this.Ne.maxSeriesPerFlush>this.Bt.size||(this.Ht||(this.Ht=!0,this.rt.warn("Metric series cap reached ("+this.Ne.maxSeriesPerFlush+" per flush window); dropping new series until the next flush. Reduce attribute cardinality.")),!1)}Kt(t,e){var n;switch(t.type){case"count":t.total=((n=t.total)!==null&&n!==void 0?n:0)+e;break;case"gauge":t.last=e;break;case"histogram":t.hist||(t.hist={count:0,sum:0,min:e,max:e,bucketCounts:new Array(go.length+1).fill(0)});var i=t.hist;i.count+=1,i.sum+=e,i.min=Math.min(i.min,e),i.max=Math.max(i.max,e),i.bucketCounts[(function(r,s){for(var o=0;s.length>o;o++)if(s[o]>=r)return o;return s.length})(e,go)]+=1}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Metric was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for metric:",o),null}return i}$t(){this.Nt||(this.Nt=ol((()=>{this.Nt=void 0,this.flush().catch((t=>{this.rt.error("Metrics flush failed:",t)}))}),this.Ne.flushIntervalMs))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}Zt(){var t=this;return se((function*(){if(t.Bt.size!==0){var e=t.Bt;t.Bt=new Map,t.Ht=!1,t.Ut=new Map,t.zt=new Set;var n=t.Wt,i=yield t._instance.Jt(t.Gt(e));if(n===t.Wt)switch(i.kind){case"ok":return;case"retry-later":return t.Yt(e),void t.$t();case"too-large":return void t.rt.warn("Metrics batch exceeded the server size limit and was dropped");case"fatal":return void t.rt.error("Failed to send metrics batch:",i.error)}}}))()}Gt(t){return e=this.Xt(t),n=(function(s,o,a){return I({},s.resourceAttributes,{"service.name":s.serviceName||"unknown_service"},s.environment&&{"deployment.environment":s.environment},s.serviceVersion&&{"service.version":s.serviceVersion},{"telemetry.sdk.name":o,"telemetry.sdk.version":a})})(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion()),i=this._instance.getLibraryId(),r=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:Yr(n)},scopeMetrics:[{scope:{name:i,version:r},metrics:e}]}]};var e,n,i,r}Xt(t){var e=Ac(Date.now()),n=new Map;for(var i of t.values()){var r,s=Pc(i.type,i.name,i.unit,void 0),o=n.get(s);o||(o=I({name:i.name},i.unit&&{unit:i.unit}),i.type==="count"?o.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:i.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:1,dataPoints:[]},n.set(s,o));var a=Yr((r=i.attributes)!==null&&r!==void 0?r:{}),l=Ac(i.windowStartMs);if(i.type==="count"){var u,c={attributes:a,startTimeUnixNano:l,timeUnixNano:e,asDouble:(u=i.total)!==null&&u!==void 0?u:0};o.sum.dataPoints.push(c)}else if(i.type==="gauge"){var d,h={attributes:a,timeUnixNano:e,asDouble:(d=i.last)!==null&&d!==void 0?d:0};o.gauge.dataPoints.push(h)}else i.hist&&o.histogram.dataPoints.push({attributes:a,startTimeUnixNano:l,timeUnixNano:e,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:go})}return Array.from(n.values())}Yt(t){var e,n;for(var i of t){var r=i[0],s=i[1],o=this.Bt.get(r);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,s.windowStartMs),o.type){case"count":o.total=((e=o.total)!==null&&e!==void 0?e:0)+((n=s.total)!==null&&n!==void 0?n:0);break;case"gauge":break;case"histogram":if(s.hist)if(o.hist){o.hist.count+=s.hist.count,o.hist.sum+=s.hist.sum,o.hist.min=Math.min(o.hist.min,s.hist.min),o.hist.max=Math.max(o.hist.max,s.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=s.hist.bucketCounts[a]}else o.hist=s.hist}else this.Qt()&&this.Bt.set(r,s)}}};var vr,Fc,mo;function ug(t){var e=globalThis._posthogChunkIds;if(e){var n=Object.keys(e);return mo&&n.length===Fc||(Fc=n.length,mo=n.reduce(((i,r)=>{vr||(vr={});var s=vr[r];if(s)i[s[0]]=s[1];else for(var o=t(r),a=o.length-1;a>=0;a--){var l=o[a],u=l?.filename,c=e[r];if(u&&c){i[u]=c,vr[r]=[u,c];break}}return i}),{})),mo}}class dg{constructor(e,n,i){i===void 0&&(i=[]),this.coercers=e,this.stackParser=n,this.modifiers=i}buildFromUnknown(e,n){n===void 0&&(n={});var i=n&&n.mechanism||{handled:!0,type:"generic"},r=this.buildCoercingContext(i,n,0).apply(e),s=this.buildParsingContext(n),o=this.parseStacktrace(r,s);return{$exception_list:this.convertToExceptionList(o,i),$exception_level:"error"}}modifyFrames(e){var n=this;return se((function*(){for(var i of e)i.stacktrace&&i.stacktrace.frames&&U(i.stacktrace.frames)&&(i.stacktrace.frames=yield n.applyModifiers(i.stacktrace.frames));return e}))()}coerceFallback(e){var n;return{type:"Error",value:"Unknown error",stack:(n=e.syntheticException)==null?void 0:n.stack,synthetic:!0}}parseStacktrace(e,n){var i,r;return e.cause!=null&&(i=this.parseStacktrace(e.cause,n)),e.stack!=""&&e.stack!=null&&(r=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?n.skipFirstLines:0),n.chunkIdMap)),I({},e,{cause:i,stack:r})}applyChunkIds(e,n){return e.map((i=>(i.filename&&n&&(i.chunk_id=n[i.filename]),i)))}applyCoercers(e,n){for(var i of this.coercers)if(i.match(e))return i.coerce(e,n);return this.coerceFallback(n)}applyModifiers(e){var n=this;return se((function*(){var i=e;for(var r of n.modifiers)i=yield r(i);return i}))()}convertToExceptionList(e,n){var i,r,s,o={type:e.type,value:e.value,mechanism:{type:(i=n.type)!==null&&i!==void 0?i:"generic",handled:(r=n.handled)===null||r===void 0||r,synthetic:(s=e.synthetic)!==null&&s!==void 0&&s}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,I({},n,{handled:!0}))),a}buildParsingContext(e){var n;return{chunkIdMap:ug(this.stackParser),skipFirstLines:(n=e.skipFirstLines)!==null&&n!==void 0?n:1}}buildCoercingContext(e,n,i){i===void 0&&(i=0);var r=(s,o)=>{if(4>=o){var a=this.buildCoercingContext(e,n,o);return this.applyCoercers(s,a)}};return I({},n,{syntheticException:i==0?n.syntheticException:void 0,mechanism:e,apply:s=>r(s,i),next:s=>r(s,i+1)})}}var ii="?";function ta(t,e,n,i,r){var s={platform:t,filename:e,function:n===""?ii:n,in_app:!0};return C(i)||(s.lineno=i),C(r)||(s.colno=r),s}var Kd=(t,e)=>{var n=t.indexOf("safari-extension")!==-1,i=t.indexOf("safari-web-extension")!==-1;return n||i?[t.indexOf("@")!==-1?t.split("@")[0]:ii,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},fg=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,hg=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,pg=/\((\S*)(?::(\d+))(?::(\d+))\)/,gg=(t,e)=>{var n=fg.exec(t);if(n)return ta(e,n[1],ii,+n[2],+n[3]);var i=hg.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var r=pg.exec(i[2]);r&&(i[2]=r[1],i[3]=r[2],i[4]=r[3])}var s=Kd(i[1]||ii,i[2]);return ta(e,s[1],s[0],i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},mg=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,vg=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,_g=(t,e)=>{var n=mg.exec(t);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){var i=vg.exec(n[3]);i&&(n[1]=n[1]||"eval",n[3]=i[1],n[4]=i[2],n[5]="")}var r=n[3],s=n[1]||ii,o=Kd(s,r);return ta(e,r=o[1],s=o[0],n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},Rc=/\(error: (.*)\)/;class yg{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,n){var i=X(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:i?e.stack:void 0,cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var n=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?n+": "+e.message:n}isDOMException(e){return zr(e,"DOMException")}isDOMError(e){return zr(e,"DOMError")}}class wg{match(e){return(function(n){switch({}.toString.call(n)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return Ed(n,Error)}})(e)}coerce(e,n){return{type:this.getType(e),value:this.getMessage(e,n),stack:this.getStack(e),cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,n){var i=e.message;return String(i.error&&typeof i.error.message=="string"?i.error.message:i)}getStack(e){return e.stacktrace||e.stack||void 0}}class bg{constructor(){}match(e){return!!zr(e,"ErrorEvent")&&(e.error!=null||this.fe(e))}coerce(e,n){var i;if(e.error!=null)return n.apply(e.error);var r=n.apply(e.message);return I({},r,{stack:(i=this.pe(e))!==null&&i!==void 0?i:r.stack,synthetic:!0})}fe(e){return X(e.message)&&e.message.length>0}pe(e){var n=e;if(X(n.filename)&&n.filename.length>0){var i,r,s=(i=n.lineno)!==null&&i!==void 0?i:0,o=(r=n.colno)!==null&&r!==void 0?r:0;return`Error - at `+n.filename+":"+s+":"+o}}}var Eg=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class Sg{match(e){return typeof e=="string"}coerce(e,n){var i,r=this.getInfos(e),s=r[0],o=r[1];return{type:s??"Error",value:o??e,stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}getInfos(e){var n="Error",i=e,r=e.match(Eg);return r&&(n=r[1],i=r[2]),[n,i]}}var xg=["fatal","error","warning","log","info","debug"];function Yd(t,e){e===void 0&&(e=40);var n=Object.keys(t);if(n.sort(),!n.length)return"[object has no keys]";for(var i=n.length;i>0;i--){var r=n.slice(0,i).join(", ");if(e>=r.length)return i===n.length?r:r.length>e?r.slice(0,e)+"...":r}return""}class Ig{match(e){return typeof e=="object"&&e!==null}coerce(e,n){var i,r,s=this.getErrorPropertyFromObject(e);return s?n.apply(s):{type:this.getType(e),value:this.getValue(e),stack:(i=this.getStack(e))!==null&&i!==void 0?i:(r=n.syntheticException)==null?void 0:r.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return tl(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var n="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(n+=" with message: '"+e.message+"'"),n}if("message"in e&&typeof e.message=="string")return e.message;var i=this.getObjectClassName(e);return(i&&i!=="Object"?"'"+i+"'":"Object")+" captured as exception with keys: "+Yd(e)}isSeverityLevel(e){return X(e)&&!Jo(e)&&xg.indexOf(e)>=0}getStack(e){try{return X(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:X(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(var n in e)if({}.hasOwnProperty.call(e,n)){var i=e[n];if(sg(i))return i}}getObjectClassName(e){try{var n=Object.getPrototypeOf(e);return n?n.constructor.name:void 0}catch{return}}}class kg{match(e){return tl(e)}coerce(e,n){var i,r=e.constructor.name;return{type:r,value:r+" captured as exception with keys: "+Yd(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class Cg{match(e){return bd(e)}coerce(e,n){var i;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class Ag{match(e){return zr(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!tl(e))return!1;try{var n=e.detail;return n!=null&&typeof n=="object"&&"reason"in n}catch{return!1}}coerce(e,n){var i,r=this.getUnhandledRejectionReason(e);return bd(r)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(r),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}:n.apply(r)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}}var Jr="$message",Zr="$timestamp",Pg=new Set([Jr,Zr]),vo={enabled:!0,max_bytes:32768};function Xr(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:vo.enabled,max_bytes:Rg(t.max_bytes,vo.max_bytes)}:I({},vo)}class Fg{constructor(e){this.Ke=[],this.Je=0,this.Ne=Xr(e)}setConfig(e){this.Ne=Xr(e),this.Xe()}add(e){var n=(function(r){var s;try{s=_d(r)}catch{return}try{var o=JSON.parse(s);if(!he(o))return;var a=o,l=a[Jr],u=a[Zr];return!X(l)||l.trim().length===0||!X(u)&&!ke(u)?void 0:{step:a,json:s}}catch{return}})(e);if(n){var i=(function(r){if(typeof TextEncoder<"u")return new TextEncoder().encode(r).length;for(var s=encodeURIComponent(r),o=0,a=0;s.length>a;a++)s[a]==="%"?(o+=1,a+=2):o+=1;return o})(n.json);i>this.Ne.max_bytes||(this.Ke.push({step:n.step,bytes:i}),this.Je+=i,this.Xe())}}getAttachable(){return this.Ke.map((e=>e.step))}clear(){this.Ke=[],this.Je=0}size(){return this.Ke.length}Xe(){for(;this.Je>this.Ne.max_bytes&&this.Ke.length>0;){var e=this.Ke.shift();e&&(this.Je-=e.bytes)}}}function Rg(t,e){if(!ke(t)||t===1/0||t===-1/0)return e;var n=Math.floor(t);return 0>n?e:n}var Jd=function(t,e){var n=(e===void 0?{}:e).debugEnabled,i={k(r){if(w&&(ne.DEBUG||w.POSTHOG_DEBUG||n)&&!C(w.console)&&w.console){for(var s=("__rrweb_original__"in w.console[r])?w.console[r].__rrweb_original__:w.console[r],o=arguments.length,a=new Array(o>1?o-1:0),l=1;o>l;l++)a[l-1]=arguments[l];s(t,...a)}},debug(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("debug",...s)},info(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("log",...s)},warn(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("warn",...s)},error(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("error",...s)},critical(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];console.error(t,...s)},uninitializedWarning(r){i.error("You must initialize PostHog before calling "+r)},createLogger:(r,s)=>Jd(t+" "+r,s)};return i},A=Jd("[PostHog.js]"),pe=A.createLogger,Tg=pe("[ExternalScriptsLoader]"),_o=(t,e,n)=>{if(t.config.disable_external_dependency_loading)return Tg.warn(e+" was requested but loading of external scripts is disabled."),n("Loading of external scripts is disabled");var i=P?.querySelectorAll("script");if(i){for(var r,s=function(){if(i[o].src===e){var l=i[o];return l.__posthog_loading_callback_fired?{v:n()}:(l.addEventListener("load",(u=>{l.__posthog_loading_callback_fired=!0,n(void 0,u)})),l.onerror=u=>n(u),{v:void 0})}},o=0;i.length>o;o++)if(r=s())return r.v}var a=()=>{if(!P)return n("document not found");var l=P.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=d=>{l.__posthog_loading_callback_fired=!0,n(void 0,d)},l.onerror=d=>n(d),t.config.prepare_external_dependency_script&&(l=t.config.prepare_external_dependency_script(l)),!l)return n("prepare_external_dependency_script returned null");if(t.config.external_scripts_inject_target==="head")P.head.appendChild(l);else{var u,c=P.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):P.body.appendChild(l)}};P!=null&&P.body?a():P?.addEventListener("DOMContentLoaded",a)};B.__PosthogExtensions__=B.__PosthogExtensions__||{},B.__PosthogExtensions__.loadExternalDependency=(t,e,n)=>{if(e!=="remote-config"){var i;if(t.config.strict_script_versioning)i=t.requestRouter.endpointFor("assets","/static/"+t.version+"/"+e+".js");else{var r="/static/"+e+".js?v="+t.version;if(e==="toolbar"){var s=3e5;r=r+"&t="+Math.floor(Date.now()/s)*s}i=t.requestRouter.endpointFor("assets",r)}_o(t,i,n)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");_o(t,o,n)}},B.__PosthogExtensions__.loadSiteApp=(t,e,n)=>{var i=t.requestRouter.endpointFor("api",e);_o(t,i,n)};ne.DEBUG=!1,ne.LIB_VERSION="1.415.7",ne.LIB_NAME="web";var Zd="$people_distinct_id",Ji="$device_id",yo="$device_model",Ri="__alias",Ti="__timers",na="$autocapture_disabled_server_side",ia="$heatmaps_enabled_server_side",ra="$exception_capture_enabled_server_side",sa="$error_tracking_suppression_rules",oa="$error_tracking_capture_extension_exceptions",aa="$web_vitals_enabled_server_side",al="$dead_clicks_enabled_server_side",ll="$product_tours_enabled_server_side",la="$web_vitals_allowed_metrics",An="$session_recording_remote_config",Xd="$replay_sample_rate",Qd="$replay_override_sampling",ef="$replay_override_linked_flag",tf="$replay_override_url_trigger",nf="$replay_override_event_trigger",Yn="$sesid",cl="$session_is_sampled",Sn="$enabled_feature_flags",$i="$active_feature_flags",Fr="$early_access_features",ca="$feature_flag_details",Mi="$feature_flag_payloads",Rr="$feature_flag_request_id",Qr="$minimal_flag_called_events",It="$override_feature_flags",xn="$override_feature_flag_payloads",jt="$stored_person_properties",In="$stored_group_properties",ua="$surveys",es="$surveys_loaded_at",da="$surveys_activated",Tr="$surveys_activated_session",$r="$surveys_activated_timestamps",Li="ph_product_tours",Cn="$flag_call_reported",Ni="$flag_call_reported_session_id",Mr="$feature_flag_errors",Ui="$feature_flag_evaluated_at",at="$user_state",fa="$client_session_props",ha="$capture_rate_limit",pa="$initial_campaign_params",ga="$initial_referrer_info",ts="$initial_person_info",ns="$epp",_r="$posthog_cookieless",rf="$cookieless_mode",sf="$sdk_debug_extensions_init_method",of="$sdk_debug_extensions_init_time_ms",af="$sdk_debug_recording_script_not_loaded",ul="PostHog loadExternalDependency extension not found.",kn="on_reject",Wt="always",Hn="anonymous",vn="identified",ma="identified_only",is="visibilitychange",rs="beforeunload",Gn="$pageview",wo="$pageleave",bo="$identify",Tc="$groupidentify";function yr(t,e){U(t)&&t.forEach(e)}function ie(t,e){if(!H(t))if(U(t))t.forEach(e);else if(Wp(t))t.forEach(((i,r)=>e(i,r)));else for(var n in t)wd.call(t,n)&&e(t[n],n)}var fe=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;e>i;i++)n[i-1]=arguments[i];for(var r of n)for(var s in r)r[s]!==void 0&&(t[s]=r[s]);return t};function Lr(t){for(var e=Object.keys(t),n=e.length,i=new Array(n);n--;)i[n]=[e[n],t[e[n]]];return i}var $c=function(t){try{return t()}catch{return}},$g=function(t){return function(){try{for(var e=arguments.length,n=new Array(e),i=0;e>i;i++)n[i]=arguments[i];return t.apply(this,n)}catch(r){A.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),A.critical(r)}}},dl=function(t){var e={};return ie(t,(function(n,i){(X(n)&&n.length>0||ke(n))&&(e[i]=n)})),e},Mg=["herokuapp.com","vercel.app","netlify.app"];function Lg(t){var e=t?.hostname;if(!X(e))return!1;var n=e.split(".").slice(-2).join(".");for(var i of Mg)if(n===i)return!1;return!0}function ve(t,e,n,i){var r=i??{},s=r.capture,o=r.passive;t?.addEventListener(e,n,{capture:s!==void 0&&s,passive:o===void 0||o})}function va(t){return t.name==="ph_toolbar_internal"}var lf=t=>{if(P){try{for(var e=t+"=",n=P.cookie.split(";").filter((s=>s.length)),i=0;n.length>i;i++){for(var r=n[i];r.charAt(0)==" ";)r=r.substring(1,r.length);if(r.indexOf(e)===0)return decodeURIComponent(r.substring(e.length,r.length))}}catch{}return null}};Math.trunc||(Math.trunc=function(t){return 0>t?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return ke(t)&&isFinite(t)&&Math.floor(t)===t});class ss{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,n,i,r){if(!Number.isInteger(e)||!Number.isInteger(n)||!Number.isInteger(i)||!Number.isInteger(r)||0>e||0>n||0>i||0>r||e>0xffffffffffff||n>4095||i>1073741823||r>4294967295)throw new RangeError("invalid field value");var s=new Uint8Array(16);return s[0]=e/Math.pow(2,40),s[1]=e/Math.pow(2,32),s[2]=e/Math.pow(2,24),s[3]=e/Math.pow(2,16),s[4]=e/256,s[5]=e,s[6]=112|n>>>8,s[7]=n,s[8]=128|i>>>24,s[9]=i>>>16,s[10]=i>>>8,s[11]=i,s[12]=r>>>24,s[13]=r>>>16,s[14]=r>>>8,s[15]=r,new ss(s)}toString(){for(var e="",n=0;this.bytes.length>n;n++)e=e+(this.bytes[n]>>>4).toString(16)+(15&this.bytes[n]).toString(16),n!==3&&n!==5&&n!==7&&n!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new ss(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var n=0;16>n;n++){var i=this.bytes[n]-e.bytes[n];if(i!==0)return Math.sign(i)}return 0}}class Ng{generate(){var e=this.generateOrAbort();if(!C(e))return e;this.S=0;var n=this.generateOrAbort();if(C(n))throw new Error("Could not generate UUID after timestamp reset");return n}generateOrAbort(){var e=Date.now();if(e>this.S)this.S=e,this.C();else{if(this.S>=e+1e4)return;this.I++,this.I>4398046511103&&(this.S++,this.C())}return ss.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 Og}}var Mc,cf=t=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;t.length>e;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};w&&!C(w.crypto)&&crypto.getRandomValues&&(cf=t=>crypto.getRandomValues(t));class Og{nextUint32(){return this.R.length>this.O||(cf(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var Ht=()=>Bg().toString(),Bg=()=>(Mc||(Mc=new Ng)).generate(),wi="",Dg=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,zt={N:()=>!!P,j(t){A.error("cookieStore error: "+t)},P:lf,H(t){var e;try{e=JSON.parse(zt.P(t))||{}}catch{}return e},F(t,e,n,i,r){if(!P)return!1;try{var s="",o="",a=(function(c,d){if(d){var h=(function(p,g){if(g===void 0&&(g=P),wi)return wi;if(!g||["localhost","127.0.0.1"].includes(p))return"";for(var m=p.split("."),v=Math.min(m.length,8),E="dmn_chk_"+Ht();!wi&&v--;){var S=m.slice(v).join("."),_=E+"=1;domain=."+S+";path=/";g.cookie=_+";max-age=3",g.cookie.includes(E)&&(g.cookie=_+";max-age=0",wi=S)}return wi})(c);if(!h){var f=(p=>{var g=p.match(Dg);return g?g[0]:""})(c);f!==h&&A.info("Warning: cookie subdomain discovery mismatch",f,h),h=f}return h?"; domain=."+h:""}return""})(P.location.hostname,i);if(n){var l=new Date;l.setTime(l.getTime()+864e5*n),s="; expires="+l.toUTCString()}r&&(o="; secure");var u=t+"="+encodeURIComponent(JSON.stringify(e))+s+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&A.warn("cookieStore warning: large cookie, len="+u.length),P.cookie=u,!0}catch{return!1}},q(t,e){if(P!=null&&P.cookie)try{zt.F(t,"",-1,e)}catch{return}}},Eo=null,le={N(){if(!Ye(Eo))return Eo;var t=!0;if(C(w))t=!1;else try{var e="__mplssupport__";le.F(e,"xyz"),le.P(e)!=='"xyz"'&&(t=!1),le.q(e)}catch{t=!1}return t||A.error("localStorage unsupported; falling back to cookie store"),Eo=t,t},j(t){A.error("localStorage error: "+t)},P(t){try{return w?.localStorage.getItem(t)}catch(e){le.j(e)}return null},H(t){try{return JSON.parse(le.P(t))||{}}catch{}return null},F(t,e){try{return w?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(n){le.j(n)}return!1},q(t){try{w?.localStorage.removeItem(t)}catch(e){le.j(e)}}},jg=[Ji,"distinct_id",Yn,cl,ns,ts,at],wr={},Ug={N:()=>!0,j(t){A.error("memoryStorage error: "+t)},P:t=>wr[t]||null,H:t=>wr[t]||null,F:(t,e)=>(wr[t]=e,!0),q(t){delete wr[t]}},_n=null,be={N(){if(!Ye(_n))return _n;if(_n=!0,C(w))_n=!1;else try{var t="__support__";be.F(t,"xyz"),be.P(t)!=='"xyz"'&&(_n=!1),be.q(t)}catch{_n=!1}return _n},j(t){A.error("sessionStorage error: ",t)},P(t){try{return w?.sessionStorage.getItem(t)}catch(e){be.j(e)}return null},H(t){try{return JSON.parse(be.P(t))||null}catch{}return null},F(t,e){try{return w?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(n){be.j(n)}return!1},q(t){try{w?.sessionStorage.removeItem(t)}catch(e){be.j(e)}}};class Hg{constructor(e){this._instance=e}get Ne(){return this._instance.config}get consent(){return this.ti()?0:this.ei}isOptedOut(){return this.Ne.cookieless_mode===Wt||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===kn}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===0}isRejected(){return this.consent===0||this.consent===-1&&this.Ne.opt_out_capturing_by_default}optInOut(e){this.ii.F(this.ri,e?1:0,this.Ne.cookie_expiration,this.Ne.cross_subdomain_cookie,this.Ne.secure_cookie)}reset(){this.ii.q(this.ri,this.Ne.cross_subdomain_cookie)}get ri(){var e=this._instance.config,n=e.token,i=e.opt_out_capturing_cookie_prefix;return e.consent_persistence_name||(i?i+n:"__ph_opt_in_out_"+n)}get ei(){var e=this.ii.P(this.ri);return ho(e)?1:j(Gp,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,n=e==="localStorage"?le:zt;if(!this.ni||this.ni!==n){this.ni=n;var i=e==="localStorage"?zt:le;i.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(ho(i.P(this.ri))),i.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[He?.doNotTrack,He?.msDoNotTrack,B.doNotTrack].some((e=>ho(e)))}}function uf(t,e){var n,i=t==null||(n=t.config)==null?void 0:n.get_current_url;if(!je(i))return e;try{var r=i(e);return X(r)&&r?r:e}catch(s){return A.error("Error in get_current_url, falling back to window.location.href",s),e}}var df="__POSTHOG_TOOLBAR__",Wg=1,zg=3,qg=11;function Lc(t){return t instanceof Element&&(t.id===df||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function hn(t){return!!t&&t.nodeType===Wg}function et(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function ff(t){return!!t&&t.nodeType===zg}function hf(t){return!!t&&t.nodeType===qg&&hn(t.host)}var pf=1e3;function fl(t){return t?ks(t).split(/\s+/):[]}function Nc(t,e){var n=(function(i){var r,s=w==null||(r=w.location)==null?void 0:r.href;return C(s)?void 0:uf(i,s)})(e);return!!(n&&t&&t.some((i=>n.match(i))))}function os(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 fl(e)}function gf(t){return H(t)?null:ks(t).split(/(\s+)/).filter((e=>Hi(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function Zi(t){var e="";return ya(t)&&!yf(t)&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;ff(n)&&n.textContent&&(e+=(i=gf(n.textContent))!==null&&i!==void 0?i:"")})),ks(e)}function So(t){var e;return C(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var hl=["a","button","form","input","select","textarea","label"];function _a(t,e){if(C(e))return!0;var n,i=function(s){if(e.some((o=>(function(a,l){var u=a.matches||a.matchesSelector||a.msMatchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.oMatchesSelector;try{return!!u&&u.call(a,l)}catch{return!1}})(s,o))))return{v:!0}};for(var r of t)if(n=i(r))return n.v;return!1}function mf(t){var e=t.parentNode;return!(!e||!hn(e))&&e}var Vg=[".ph-no-autocapture","[data-ph-no-autocapture]"],vf=["next","previous","prev",">","<"],Gg=[...vf,"+","-","−","–"],Oc=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,Bc=[".ph-no-rageclick",".ph-no-capture"],Kg=["","text","search","email","password","url","tel","number"];function Dc(t,e){if(!w||pl(t))return!1;var n,i,r,s,o;if(mt(e)?(n=!!e&&Bc,i=void 0,r=!1):(n=(s=e?.css_selector_ignorelist)!==null&&s!==void 0?s:Bc,i=e?.content_ignorelist,r=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),n===!1||r&&(function(l){return!(!l||!hn(l))&&(!!et(l,"textarea")||(et(l,"input")?j(Kg,(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=_f(t,!1).targetElementList;return!(function(l,u){if(l===!1||C(l))return!1;var c;if(l===!0)c=vf;else{if(!U(l))return!1;if(l.length>10)return A.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var h=d.safeText,f=d.ariaLabel;return c.some((p=>Oc(h,p)||Oc(f,p)))}))})(i,a.map((l=>{var u;return{safeText:Zi(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!_a(a,n)}var pl=t=>!t||et(t,"html")||!hn(t),_f=(t,e)=>{if(!w||pl(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,i=[t],r=t;r.parentNode&&!et(r,"body");)if(hf(r.parentNode))i.push(r.parentNode.host),r=r.parentNode.host;else{var s=mf(r);if(!s)break;if(e||hl.indexOf(s.tagName.toLowerCase())>-1)n=!0;else try{var o=w.getComputedStyle(s);o&&o.getPropertyValue("cursor")==="pointer"&&(n=!0)}catch{}i.push(s),r=s}return{parentIsUsefulElement:n,targetElementList:i}};function ya(t){for(var e=new Set,n=0,i=t;i.parentNode&&!et(i,"body");i=i.parentNode){if(n++>=pf||e.has(i))return!1;e.add(i);var r=os(i);if(j(r,"ph-sensitive")||j(r,"ph-no-capture"))return!1}if(j(os(t),"ph-include"))return!0;var s=t.type||"";if(X(s))switch(s.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!X(o)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(o.replace(/[^a-zA-Z0-9]/g,""))}function yf(t){return!!(et(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||et(t,"select")||et(t,"textarea")||t.getAttribute("contenteditable")==="true")}var jc=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}))$"),Uc=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,Yg=[16,15,14,13],Jg=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),Hc=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),Wc=/[0-9A-Za-z_]/;function Zg(t){for(var e=0,n=!1,i=t.length-1;i>=0;i--){var r=t.charCodeAt(i)-48;n&&(r*=2)>9&&(r-=9),e+=r,n=!n}return e%10==0}function Hi(t,e){if(e===void 0&&(e=!0),H(t))return!1;if(X(t)){t=ks(t);var n=e?jc.test((t||"").replace(/[- ]/g,"")):(function(r){var s;for(Uc.lastIndex=0;s=Uc.exec(r);){var o=s[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of Yg){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(jc.test(d)&&Zg(d))return!0}}}return!1})(t);if(n)return!1;var i=e?Jg.test(t):(function(r){var s;for(Hc.lastIndex=0;s=Hc.exec(r);){var o=s[1],a=s[3];if(!(o&&a&&Wc.test(o)&&Wc.test(a)))return!0}return!1})(t);if(i)return!1}return!0}function zc(t){var e=Zi(t);return Hi(e=(e+" "+wf(t)).trim())?e:""}function wf(t){var e="";return t&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;if(n&&((i=n.tagName)==null?void 0:i.toLowerCase())==="span")try{var r=Zi(n);e=(e+" "+r).trim(),n.childNodes&&n.childNodes.length&&(e=(e+" "+wf(n)).trim())}catch(s){A.error("[AutoCapture]",s)}})),e}function qc(t){return t.replace(/"|\\"/g,'\\"')}function Xg(t){var e=t.attr__class;if(e)return U(e)?e:fl(e)}var br=pe("[Dead Clicks]"),Qg=()=>!0,em=t=>{var e,n=!((e=t.instance.persistence)==null||!e.get_property(al)),i=t.instance.config.capture_dead_clicks;return mt(i)?i:!!he(i)||n};class Vc{get lazyLoadedDeadClicksAutocapture(){return this.si}constructor(e,n,i){this.instance=e,this.isEnabled=n,this.onCapture=i,this.startIfEnabledOrStop()}onRemoteConfig(e){if(e.ok){var n=e.config;"captureDeadClicks"in n&&(this.instance.persistence&&this.instance.persistence.register({[al]:n.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var n,i;(n=B.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture?e():(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"dead-clicks-autocapture",(r=>{r?br.error("failed to load script",r):e()}))}oi(){var e;if(P){if(!this.si&&(e=B.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var n=he(this.instance.config.capture_dead_clicks)?I({},this.instance.config.capture_dead_clicks):{};n.__onCapture=this.onCapture,this.onCapture&&(n.capture_dead_swipes=!1),this.si=B.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.si.start(P),br.info("starting...")}}else br.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,br.info("stopping..."))}}var xo=pe("[SegmentIntegration]"),bf="posthog-js";function Ef(t,e){var n=e===void 0?{}:e,i=n.organization,r=n.projectId,s=n.prefix,o=n.severityAllowList,a=o===void 0?["error"]:o,l=n.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,h,f,p,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var v,E=((d=c.exception)==null?void 0:d.values)||[],S=E.map((b=>I({},b,{stacktrace:b.stacktrace?I({},b.stacktrace,{type:"raw",frames:(b.stacktrace.frames||[]).map((k=>I({},k,{platform:"web:javascript"})))}):void 0}))),_={$exception_message:((h=E[0])==null?void 0:h.value)||c.message,$exception_type:(f=E[0])==null?void 0:f.type,$exception_level:c.level,$exception_list:S,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((p=E[0])==null?void 0:p.value)||c.message,$sentry_exception_type:(g=E[0])==null?void 0:g.type,$sentry_tags:c.tags};return i&&r&&(_.$sentry_url=(s||"https://sentry.io/organizations/")+i+"/issues/?project="+r+"&query="+c.event_id),u&&((v=t.exceptions)==null||v.sendExceptionEvent(_)),c}}class tm{constructor(e,n,i,r,s,o){this.name=bf,this.setupOnce=function(a){a(Ef(e,{organization:n,projectId:i,prefix:r,severityAllowList:s,sendExceptionsToPostHog:o==null||o}))}}}class Gc{constructor(e){this.li=(n,i,r)=>{r&&(r.noSessionId||r.activityTimeout||r.sessionPastMaximumLength||r.crossTabAdoption)&&(A.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:n,changeReason:r}),this.ui=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.hi()}hi(){var e;this.di=(e=this._instance.sessionManager)==null?void 0:e.onSessionId(this.li)}destroy(){var e;(e=this.di)==null||e.call(this),this.di=void 0}doPageView(e,n){var i,r=this.vi(e,n);return this.ui={pathname:(i=w?.location.pathname)!==null&&i!==void 0?i:"",pageViewId:n,timestamp:e},this._instance.scrollManager.resetContext(),r}doPageLeave(e){var n;return this.vi(e,(n=this.ui)==null?void 0:n.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.ui)==null?void 0:e.pageViewId}}vi(e,n){var i=this.ui;if(!i)return{$pageview_id:n};var r={$pageview_id:n,$prev_pageview_id:i.pageViewId},s=this._instance.scrollManager.getContext();if(s&&!this._instance.config.disable_scroll_properties){var o=s.maxScrollHeight,a=s.lastScrollY,l=s.maxScrollY,u=s.maxContentHeight,c=s.lastContentY,d=s.maxContentY;if(!(C(o)||C(a)||C(l)||C(u)||C(c)||C(d))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),d=Math.ceil(d);var h=o>1?At(a/o,0,1,A):1,f=o>1?At(l/o,0,1,A):1,p=u>1?At(c/u,0,1,A):1,g=u>1?At(d/u,0,1,A):1;r=fe(r,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:h,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:f,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:p,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return i.pathname&&(r.$prev_pageview_pathname=i.pathname),i.timestamp&&(r.$prev_pageview_duration=(e.getTime()-i.timestamp.getTime())/1e3),r}}var Io=["flags","surveys"],nm={[Zd]:{exposure:"hidden"},[Ri]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[Ti]:{exposure:"hidden"},[na]:{exposure:"event"},[ia]:{exposure:"hidden"},[ra]:{exposure:"event"},[sa]:{exposure:"hidden"},[oa]:{exposure:"event"},[aa]:{exposure:"event"},[al]:{exposure:"event"},[ll]:{exposure:"hidden"},[la]:{exposure:"event"},[An]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[Yn]:{exposure:"hidden"},[cl]:{exposure:"event"},[Xd]:{exposure:"event",shouldSkipFromEventProperties:t=>Ye(t)},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},$sess_rec_flush_size:{exposure:"hidden"},[Sn]:{exposure:"hidden",storageGroup:"flags"},[$i]:{exposure:"hidden",storageGroup:"flags"},[Fr]:{exposure:"hidden"},[ca]:{exposure:"hidden",storageGroup:"flags"},[Mi]:{exposure:"hidden",storageGroup:"flags"},[Rr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[Qr]:{exposure:"hidden",storageGroup:"flags"},[It]:{exposure:"hidden"},[xn]:{exposure:"hidden"},[jt]:{exposure:"hidden"},[In]:{exposure:"hidden"},[ua]:{exposure:"hidden",storageGroup:"surveys"},[es]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[da]:{exposure:"event"},[Tr]:{exposure:"hidden"},[$r]:{exposure:"hidden"},[Li]:{exposure:"hidden"},$product_tours_activated:{exposure:"hidden"},$product_tours_activated_session:{exposure:"hidden"},$conversations_widget_session_id:{exposure:"event"},$conversations_ticket_id:{exposure:"event"},$conversations_widget_state:{exposure:"event"},$conversations_user_traits:{exposure:"event"},[Cn]:{exposure:"hidden"},[Ni]:{exposure:"hidden"},[Mr]:{exposure:"hidden"},[Ui]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[at]:{exposure:"hidden"},[fa]:{exposure:"hidden"},[ha]:{exposure:"hidden"},[pa]:{exposure:"hidden"},[ga]:{exposure:"hidden"},[ts]:{exposure:"hidden"},[ns]:{exposure:"hidden"},[Qd]:{exposure:"event"},[ef]:{exposure:"event"},[tf]:{exposure:"event"},[nf]:{exposure:"event"},[sf]:{exposure:"event"},[of]:{exposure:"event"},[af]:{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"}},im=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],yn=t=>{var e=nm[t];if(e)return e;for(var n of im){var i=n[1];if(t.indexOf(n[0])===0)return i}},Jn=(t,e)=>{try{return JSON.stringify(t,((n,i)=>typeof i=="bigint"?i.toString():i),e)}catch{return _d(t)}},as=t=>{var e=P?.createElement("a");return C(e)?null:(e.href=t,e)},ri=function(t,e){for(var n,i=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),r=0;i.length>r;r++){var s=i[r].split("=");if(s[0]===e){n=s;break}}if(!U(n)||2>n.length)return"";var o=n[1];try{o=decodeURIComponent(o)}catch{A.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},Xi=function(t,e,n){if(!t||!e||!e.length)return t;for(var i=t.split("#"),r=i[1],s=(i[0]||"").split("?"),o=s[1],a=s[0],l=(o||"").split("&"),u=[],c=0;l.length>c;c++){var d=l[c].split("=");U(d)&&(e.includes(d[0])?u.push(d[0]+"="+n):u.push(l[c]))}var h=a;return o!=null&&(h+="?"+u.join("&")),r!=null&&(h+="#"+r),h},ls=function(t,e){var n=t.match(new RegExp(e+"=([^&]*)"));return n?n[1]:null},Sf=(t,e)=>t>=e&&gd(),xf=(t,e,n,i)=>{if(t===0){if(gd()){var r=e+1;return r===n&&i(),r}return e}return 0},Er="https?://(.*)",si=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],rm=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...si],Qi="",sm=["li_fat_id"];function If(t,e,n){if(!P)return{};var i,r=e?[...si,...n||[]]:[],s=kf(Xi(P.URL,r,Qi),t),o=(i={},ie(sm,(function(a){var l=lf(a);i[a]=l||null})),i);return fe(o,s)}function kf(t,e){var n=rm.concat(e||[]),i={};return ie(n,(function(r){var s=ri(t,r);i[r]=s||null})),i}function Cf(t){var e=(function(s){return s?s.search(Er+"google.([^/?]*)")===0?"google":s.search(Er+"bing.com")===0?"bing":s.search(Er+"yahoo.com")===0?"yahoo":s.search(Er+"duckduckgo.com")===0?"duckduckgo":null:null})(t),n=e!="yahoo"?"q":"p",i={};if(!Ye(e)){i.$search_engine=e;var r=P?ri(P.referrer,n):"";r.length&&(i.ph_keyword=r)}return i}function Kc(){return navigator.language||navigator.userLanguage}var cs="$direct";function Af(){return P?.referrer||cs}function Pf(t,e,n){n===void 0&&(n=!1);var i=t?[...si,...e||[]]:[],r=n?fn(me?.href):me?.href,s=r?.substring(0,1e3);return{r:Af().substring(0,1e3),u:s?Xi(s,i,Qi):void 0}}function Ff(t,e){var n;e===void 0&&(e=!1);var i=t.r,r=t.u,s=e?fn(r):r,o={$referrer:i,$referring_domain:i==null?void 0:i==cs?cs:(n=as(i))==null?void 0:n.host};if(s){o.$current_url=s;var a=as(s);o.$host=a?.host,o.$pathname=a?.pathname;var l=kf(s);fe(o,l)}if(i){var u=Cf(i);fe(o,u)}return o}function Rf(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function om(){try{return new Date().getTimezoneOffset()}catch{return}}var am={flags:Ui,surveys:es},lm=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],Wn="main";class ko{constructor(e,n,i){if(i===void 0&&(i=!0),this.ci={},this.fi=!1,this.pi=!1,this.Ne=e,this.gi=i,this.props={},this.mi=void 0,this.yi=(s=>{var o="";return s.token&&(o=s.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),s.persistence_name?"ph_"+s.persistence_name:"ph_"+o+"_posthog"})(e),this.ii=this.bi(e),this.pi=this.wi(e),this.load(),e.debug&&A.info("Persistence loaded",e.persistence,I({},this.props)),this.update_config(e,e,n),this.save(),w){var r=()=>this.flush();ve(w,"beforeunload",r,{capture:!1}),ve(w,"pagehide",r,{capture:!1})}}ki(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return ke(n)&&n>0?n:0}isDisabled(){return!!this.xi}bi(e){lm.indexOf(e.persistence.toLowerCase())===-1&&(A.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var n,i=(function(o,a){o===void 0&&(o=[]),a===void 0&&(a=!1);var l=[...jg,...o];return I({},le,{H(u){try{var c={};try{c=zt.H(u)||{}}catch{}var d,h=JSON.parse(le.P(u)||"{}");if(a){var f={};for(var p in c){var g=c[p];Ye(g)||g===""||(f[p]=g)}d=fe(h,f)}else d=fe(c,h);return le.F(u,d),d}catch{}return null},F(u,c,d,h,f,p){var g=le.F(u,c,void 0,void 0,p);try{var m={};l.forEach((v=>{c[v]&&(m[v]=c[v])})),Object.keys(m).length&&zt.F(u,m,d,h,f,p)}catch(v){le.j(v)}return g},q(u,c){try{w?.localStorage.removeItem(u),zt.q(u,c)}catch(d){le.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),r=!1,s=e.persistence.toLowerCase();return s==="localstorage"&&le.N()?(n=le,r=!0):s==="localstorage+cookie"&&i.N()?(n=i,r=!0):s==="sessionstorage"&&be.N()?n=be:s==="memory"?n=Ug:s==="cookie"?n=zt:i.N()?(n=i,r=!0):n=zt,this.fi=r,n}Si(e){return this.yi+"__"+e}wi(e){return this.fi&&!!e.split_storage}properties(){var e={};return ie(this.props,((n,i)=>{var r=yn(i);if(!r||r.exposure==="event"){if(r!=null&&r.shouldSkipFromEventProperties!=null&&r.shouldSkipFromEventProperties(n))return;e[i]=n}})),e}load(){if(!this.xi){var e=this.ii.H(this.yi);e&&(this.props=fe({},e)),this.pi&&this.Ci()}}Ci(){for(var e of Io){var n=le.H(this.Si(e));if(n&&!Kt(n)){var i=this.Mi(e);i.persisted=!0,this.Ti(e)||(i.fingerprint=this.Ei(n,e)),this.Ii(e,n)||fe(this.props,n)}}}Ti(e){return Object.keys(this.props).some((n=>{var i;return((i=yn(n))==null?void 0:i.storageGroup)===e}))}Ii(e,n){var i=am[e];if(!i)return!1;var r=n[i],s=this.props[i];return ke(r)&&ke(s)&&s>r}refreshKey(e){var n;if(!this.xi){var i=this.pi?(n=yn(e))==null?void 0:n.storageGroup:void 0,r=i?le.H(this.Si(i)):this.ii.H(this.yi);if(r&&e in r)this.Pi(e,r[e]);else{if(i){var s=this.ii.H(this.yi);if(s&&e in s)return void this.Pi(e,s[e])}this.Ri(e)}}}save(){if(!this.xi){var e=this.ki();e>0?C(this.Ai)&&(this.Ai=setTimeout((()=>{this.Ai=void 0,this.Fi()}),e)):this.Fi()}}flush(){C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0,this.Fi())}Fi(){this.xi||(this.pi?this.Li():this.Oi(this.ii,this.yi,this.props,Wn))}Li(){var e=this.Di(),n=e.main,i=e.groups;for(var r of(this.Oi(this.ii,this.yi,n,Wn),Io)){var s,o=i[r];(!Kt(o)||(s=this.ci[r])!=null&&s.persisted)&&this.Oi(le,this.Si(r),o,r)}}Di(){var e={},n={flags:{},surveys:{}};return ie(this.props,((i,r)=>{var s,o=(s=yn(r))==null?void 0:s.storageGroup;o?n[o][r]=i:e[r]=i})),{main:e,groups:n}}Ei(e,n){if(n===Wn)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var i={};return ie(e,((r,s)=>{var o;i[s]=(o=yn(s))!=null&&o.volatile?"__volatile__":r})),JSON.stringify(i)}Oi(e,n,i,r){var s=this.Mi(r);if(r===Wn||s.dirty||C(s.fingerprint)){var o;try{if((o=this.Ei(i,r))===s.fingerprint)return void(s.dirty=!1)}catch{o=void 0}e.F(n,i,this.$i,this.Ni,this.qi,this.Ne.debug)?(s.dirty=!1,r!==Wn&&(s.persisted=!0),C(o)||(s.fingerprint=o)):this.Ne.debug&&A.warn('failed to persist storage entry "'+n+'"; will retry on next save')}}remove(e){var n=(e===void 0?{}:e).keepGroupEntries,i=n!==void 0&&n;if(C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0),this.ii.q(this.yi,!1),this.ii.q(this.yi,!0),!i&&this.gi)for(var r of Io)le.q(this.Si(r));i?delete this.ci[Wn]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,n,i){if(he(e)){C(n)&&(n="None"),this.$i=C(i)?this.ji:i;var r=!1;if(ie(e,((s,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==n||(this.Pi(o,s),r=!0)})),r)return this.save(),!0}return!1}register(e,n){if(he(e)){this.$i=C(n)?this.ji:n;var i=!1;if(ie(e,((r,s)=>{e.hasOwnProperty(s)&&(this.props[s]!==r||he(r)||U(r))&&(this.Pi(s,r),i=!0)})),i)return this.save(),!0}return!1}unregister(e){var n=typeof e=="string"?[e]:e,i=!1;for(var r of n)r in this.props&&(this.Ri(r),i=!0);i&&this.save()}update_campaign_params(){var e=P?.URL;if(e!==this.mi){var n=If(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);Kt(dl(n))||this.register(n),this.mi=e}}update_search_keyword(){var e;this.register((e=P?.referrer)?Cf(e):{})}update_referrer_info(){var e;this.register_once({$referrer:Af(),$referring_domain:P!=null&&P.referrer&&((e=as(P.referrer))==null?void 0:e.host)||cs},void 0)}set_initial_person_info(){this.props[pa]||this.props[ga]||this.register_once({[ts]:Pf(this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties,this.Ne.disable_capture_url_hashes)},void 0)}get_initial_props(){var e={};ie([ga,pa],(r=>{var s=this.props[r];s&&ie(s,(function(o,a){e["$initial_"+Yo(a)]=o}))}));var n=this.props[ts];if(n){var i=(function(r,s){s===void 0&&(s=!1);var o=Ff(r,s),a={};return ie(o,(function(l,u){a["$initial_"+Yo(u)]=l})),a})(n,this.Ne.disable_capture_url_hashes);fe(e,i)}return e}safe_merge(e){return ie(this.props,(function(n,i){i in e||(e[i]=n)})),e}update_config(e,n,i){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!i),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var r=e.persistence!==n.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((h,f)=>h===d[f]))})(e.cookie_persisted_properties||[],n.cookie_persisted_properties||[]),s=r?this.bi(e):this.ii,o=this.wi(e);if(r||o!==this.pi){var a=this.props;this.clear(),this.ii=s,this.pi=o,this.props=a,this.save()}}set_disabled(e){this.xi=e,this.xi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ni&&(this.Ni=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this.qi&&(this.qi=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,n){var i=this.props[Ti]||{};i[e]=n,this.Pi(Ti,i),this.save()}remove_event_timer(e){var n=this.props[Ti]||{},i=n[e];return C(i)||(delete n[e],this.Pi(Ti,n),this.save()),i}get_property(e){return this.props[e]}set_property(e,n){this.Pi(e,n),this.save()}Pi(e,n){var i;this.props[e]=n,(i=yn(e))!=null&&i.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var n,i=(n=yn(e))==null?void 0:n.storageGroup;i&&(this.Mi(i).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function Sr(t){var e=!0;return{dispose(){if(e){e=!1;var n=t();n&&je(n.then)&&n.then(void 0,(()=>{}))}}}}var Ue={GZipJS:"gzip-js",Base64:"base64"},bi={Activation:"events",Cancellation:"cancelEvents"},Co={Popover:"popover",API:"api",Widget:"widget"},qt={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},Ao={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},wa={Popover:"popover",Inline:"inline"},cm={SHOWN:"product tour shown"},Yc={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},Jc=pe("[RateLimiter]");class um{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=n=>{var i=n.text;if(i&&i.length)try{(JSON.parse(i).quota_limited||[]).forEach((r=>{Jc.info((r||"events")+" is quota limited."),this.serverLimits[r]=new Date().getTime()+6e4}))}catch(r){return void Jc.warn('could not rate limit - continuing. Error: "'+r?.message+'"',{text:i})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var n,i,r;e===void 0&&(e=!1);var s=this.captureEventsBurstLimit,o=this.captureEventsPerSecond,a=new Date().getTime(),l=(n=(i=this.instance.persistence)==null?void 0:i.get_property(ha))!==null&&n!==void 0?n:{tokens:s,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>s&&(l.tokens=s);var u=1>l.tokens;if(u||e||(l.tokens=Math.max(0,l.tokens-1)),u&&!e){var c=(ke(l.dropped)?l.dropped:0)+1;l.dropped=c,!this.lastEventRateLimited&&this.Hi(c)&&(l.dropped=0)}return this.lastEventRateLimited=u,(r=this.instance.persistence)==null||r.set_property(ha,l),{isRateLimited:u,remainingTokens:l.tokens}}Ui(e){var n=this.instance.config.property_denylist;return!U(n)||!n.includes(e)}zi(){var e;if(this.Ui("$current_url")&&this.Ui("$pathname")&&me!=null&&me.pathname)return""+((e=me.origin)!==null&&e!==void 0?e:"")+me.pathname}Hi(e){var n,i,r=this.captureEventsBurstLimit,s=this.captureEventsPerSecond,o=this.zi(),a=this.Ui("$session_id")?(n=(i=this.instance).get_session_id)==null?void 0:n.call(i):void 0,l=[e+" event(s) dropped since the last warning",o?"triggered on "+o:void 0,a?"session "+a:void 0].filter(Boolean).join(", ");return!!this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited: "+l+". Config is set to "+s+" events per second and "+r+" events burst limit."},{skip_client_rate_limiting:!0})}isServerRateLimited(e){var n=this.serverLimits[e||"events"]||!1;return n!==!1&&new Date().getTime()e(this.remoteConfig))):e()}Vi(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:e})}load(){try{if(this.remoteConfig)return an.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void an.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return an.info("No config found after loading remote JS config. Falling back to JSON."),void this.Vi((n=>{this.Zi(n.json,n),this.Gi()}));this.Zi(e),this.Gi()}))}catch(e){an.error("Error loading remote config",e),this.Zi()}}stop(){this.Ki&&(clearInterval(this.Ki),this.Ki=void 0)}refresh(){!this._instance.Qi()&&P&&P.visibilityState!=="hidden"&&this._instance.reloadFeatureFlags()}Gi(){var e;if(!this.Ki){var n=(e=this._instance.config.remote_config_refresh_interval_ms)!==null&&e!==void 0?e:3e5;n!==0&&(this.Ki=setInterval((()=>{this.refresh()}),n))}}Zi(e,n){!e&&n&&(n.statusCode===0?n.error||an.warn("Failed to fetch remote config from PostHog."):an.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(r){an.error("Error applying remote config",r)}if(e?.hasFeatureFlags!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var i;(i=this._instance.featureFlags)==null||i.ensureFlagsLoaded()}catch(r){an.error("Error loading feature flags",r)}}}var ct=Uint8Array,Ke=Uint16Array,oi=Uint32Array,gl=new ct([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]),ml=new ct([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]),Zc=new ct([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),$f=function(t,e){for(var n=new Ke(31),i=0;31>i;++i)n[i]=e+=1<i;++i)for(var s=n[i];n[i+1]>s;++s)r[s]=s-n[i]<<5|i;return[n,r]},Mf=$f(gl,2),ba=Mf[1];Mf[0][28]=258,ba[258]=28;for(var Xc=$f(ml,0)[1],Lf=new Ke(32768),_e=0;32768>_e;++_e){var zn=(43690&_e)>>>1|(21845&_e)<<1;Lf[_e]=((65280&(zn=(61680&(zn=(52428&zn)>>>2|(13107&zn)<<2))>>>4|(3855&zn)<<4))>>>8|(255&zn)<<8)>>>1}var Wi=function(t,e,n){for(var i=t.length,r=0,s=new Ke(e);i>r;++r)++s[t[r]-1];var o,a=new Ke(e);for(r=0;e>r;++r)a[r]=a[r-1]+s[r-1]<<1;for(o=new Ke(i),r=0;i>r;++r)o[r]=Lf[a[t[r]-1]++]>>>15-t[r];return o},Mn=new ct(288);for(_e=0;144>_e;++_e)Mn[_e]=8;for(_e=144;256>_e;++_e)Mn[_e]=9;for(_e=256;280>_e;++_e)Mn[_e]=7;for(_e=280;288>_e;++_e)Mn[_e]=8;var us=new ct(32);for(_e=0;32>_e;++_e)us[_e]=5;var dm=Wi(Mn,9),fm=Wi(us,5),Nf=function(t){return(t/8>>0)+(7&t&&1)},Of=function(t,e,n){(n==null||n>t.length)&&(n=t.length);var i=new(t instanceof Ke?Ke:t instanceof oi?oi:ct)(n-e);return i.set(t.subarray(e,n)),i},Ot=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8},Ei=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8,t[i+2]|=n>>>16},Po=function(t,e){for(var n=[],i=0;t.length>i;++i)t[i]&&n.push({s:i,f:t[i]});var r=n.length,s=n.slice();if(!r)return[new ct(0),0];if(r==1){var o=new ct(n[0].s+1);return o[n[0].s]=1,[o,1]}n.sort((function(b,k){return b.f-k.f})),n.push({s:-1,f:25001});var a=n[0],l=n[1],u=0,c=1,d=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=r-1;)a=n[n[d].f>n[u].f?u++:d++],l=n[u!=c&&n[d].f>n[u].f?u++:d++],n[c++]={s:-1,f:a.f+l.f,l:a,r:l};var h=s[0].s;for(i=1;r>i;++i)s[i].s>h&&(h=s[i].s);var f=new Ke(h+1),p=Ea(n[c-1],f,0);if(p>e){i=0;var g=0,m=p-e,v=1<i;++i){var E=s[i].s;if(e>=f[E])break;g+=v-(1<>>=m;g>0;){var S=s[i].s;e>f[S]?g-=1<=0&&g;--i){var _=s[i].s;f[_]==e&&(--f[_],++g)}p=e}return[new ct(f),p]},Ea=function(t,e,n){return t.s==-1?Math.max(Ea(t.l,e,n+1),Ea(t.r,e,n+1)):e[t.s]=n},Qc=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new Ke(++e),i=0,r=t[0],s=1,o=function(l){n[i++]=l},a=1;e>=a;++a)if(t[a]==r&&a!=e)++s;else{if(!r&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(r),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(r);s=1,r=t[a]}return[n.subarray(0,i),e]},Si=function(t,e){for(var n=0,i=0;e.length>i;++i)n+=t[i]*e[i];return n},Sa=function(t,e,n){var i=n.length,r=Nf(e+2);t[r]=255&i,t[r+1]=i>>>8,t[r+2]=255^t[r],t[r+3]=255^t[r+1];for(var s=0;i>s;++s)t[r+s+4]=n[s];return 8*(r+4+i)},eu=function(t,e,n,i,r,s,o,a,l,u,c){Ot(e,c++,n),++r[256];for(var d=Po(r,15),h=d[0],f=d[1],p=Po(s,15),g=p[0],m=p[1],v=Qc(h),E=v[0],S=v[1],_=Qc(g),b=_[0],k=_[1],T=new Ke(19),x=0;E.length>x;++x)T[31&E[x]]++;for(x=0;b.length>x;++x)T[31&b[x]]++;for(var F=Po(T,7),$=F[0],O=F[1],L=19;L>4&&!$[Zc[L-1]];--L);var N,K,V,M,R=u+5<<3,Z=Si(r,Mn)+Si(s,us)+o,Ce=Si(r,h)+Si(s,g)+o+14+3*L+Si(T,$)+(2*T[16]+3*T[17]+7*T[18]);if(Z>=R&&Ce>=R)return Sa(e,c,t.subarray(l,l+u));if(Ot(e,c,1+(Z>Ce)),c+=2,Z>Ce){N=Wi(h,f),K=h,V=Wi(g,m),M=g;var oe=Wi($,O);for(Ot(e,c,S-257),Ot(e,c+5,k-1),Ot(e,c+10,L-4),c+=14,x=0;L>x;++x)Ot(e,c+3*x,$[Zc[x]]);c+=3*L;for(var ye=[E,b],$e=0;2>$e;++$e){var ae=ye[$e];for(x=0;ae.length>x;++x)Ot(e,c,oe[Ie=31&ae[x]]),c+=$[Ie],Ie>15&&(Ot(e,c,ae[x]>>>5&127),c+=ae[x]>>>12)}}else N=dm,K=Mn,V=fm,M=us;for(x=0;a>x;++x)if(i[x]>255){var Ie;Ei(e,c,N[257+(Ie=i[x]>>>18&31)]),c+=K[Ie+257],Ie>7&&(Ot(e,c,i[x]>>>23&31),c+=gl[Ie]);var Se=31&i[x];Ei(e,c,V[Se]),c+=M[Se],Se>3&&(Ei(e,c,i[x]>>>5&8191),c+=ml[Se])}else Ei(e,c,N[i[x]]),c+=K[i[x]];return Ei(e,c,N[256]),c+K[256]},hm=new oi([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),pm=(function(){for(var t=new oi(256),e=0;256>e;++e){for(var n=e,i=9;--i;)n=(1&n&&3988292384)^n>>>1;t[e]=n}return t})(),Fo=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8};function gm(t,e){e===void 0&&(e={});var n=(function(){var d=4294967295;return{p(h){for(var f=d,p=0;h.length>p;++p)f=pm[255&f^h[p]]^f>>>8;d=f},d(){return 4294967295^d}}})(),i=t.length;n.p(t);var r,s,o,a,l,u=(a=10+((r=e).filename&&r.filename.length+1||0),l=8,(function(d,h,f,p,g,m){var v=d.length,E=new ct(p+v+5*(1+Math.floor(v/7e3))+g),S=E.subarray(p,E.length-g),_=0;if(!h||8>v)for(var b=0;v>=b;b+=65535){var k=b+65535;v>k?_=Sa(S,_,d.subarray(b,k)):(S[b]=!0,_=Sa(S,_,d.subarray(b,v)))}else{for(var T=hm[h-1],x=T>>>13,F=8191&T,$=(1<b;++b){var Ie=V(b),Se=32767&b,De=L[Ie];if(O[Se]=De,L[Ie]=Se,b>=$e){var wt=v-b;if((Ce>7e3||ye>24576)&&wt>423){_=eu(d,S,0,M,R,Z,oe,ye,ae,b-ae,_),ye=Ce=oe=0,ae=b;for(var ge=0;286>ge;++ge)R[ge]=0;for(ge=0;30>ge;++ge)Z[ge]=0}var Je=2,bt=0,mn=F,Re=Se-De&32767;if(wt>2&&Ie==V(b-Re))for(var Pe=Math.min(x,wt)-1,$t=Math.min(32767,b),Dn=Math.min(258,wt);$t>=Re&&--mn&&Se!=De;){if(d[b+Je]==d[b+Je-Re]){for(var qe=0;Dn>qe&&d[b+qe]==d[b+qe-Re];++qe);if(qe>Je){if(Je=qe,bt=Re,qe>Pe)break;var jn=Math.min(Re,qe-2),Mt=0;for(ge=0;jn>ge;++ge){var Lt=b-Re+ge+32768&32767,ut=Lt-O[Lt]+32768&32767;ut>Mt&&(Mt=ut,De=Lt)}}}Re+=(Se=De)-(De=O[Se])+32768&32767}if(bt){M[ye++]=268435456|ba[Je]<<18|Xc[bt];var sn=31&ba[Je],mi=31&Xc[bt];oe+=gl[sn]+ml[mi],++R[257+sn],++Z[mi],$e=b+Je,++Ce}else M[ye++]=d[b],++R[d[b]]}}_=eu(d,S,!0,M,R,Z,oe,ye,ae,b-ae,_)}return Of(E,0,p+Nf(_)+g)})(s=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):12+o.mem,a,l)),c=u.length;return(function(d,h){var f=h.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>h.level?4:h.level==9?2:0,d[9]=3,h.mtime!=0&&Fo(d,4,Math.floor(new Date(h.mtime||Date.now())/1e3)),f){d[3]=8;for(var p=0;f.length>=p;++p)d[p+10]=f.charCodeAt(p)}})(u,e),Fo(u,c-8,n.d()),Fo(u,c-4,i),u}var mm=!!Vo||!!el,Bf="text/plain",Nr=!1,Df=(t,e)=>{var n=t.split("#"),i=n[1],r=n[0].split("?"),s=r[0],o=r[1];if(!o)return t;var a=o.split("&").filter((l=>l.split("=")[0]!==e)).join("&");return s+(a?"?"+a:"")+(i?"#"+i:"")},As=function(t,e,n){var i;n===void 0&&(n=!0);var r=t.split("?"),s=r[0],o=r[1],a=I({},e),l=(i=o?.split("&").map((c=>{var d,h=c.split("="),f=h[0],p=n&&(d=a[f])!==null&&d!==void 0?d:h[1];return delete a[f],f+"="+p})))!==null&&i!==void 0?i:[],u=(function(c,d){var h,f;d===void 0&&(d="&");var p=[];return ie(c,(function(g,m){C(g)||C(m)||m==="undefined"||(h=encodeURIComponent((v=>v instanceof File)(g)?g.name:g.toString()),f=encodeURIComponent(m),p[p.length]=f+"="+h)})),p.join(d)})(a);return u&&l.push(u),l.length>0?s+"?"+l.join("&"):s},Ro=t=>{if(t.Ji)return t.Ji;var e=t.data,n=t.compression;if(e){if(n===Ue.GZipJS){var i=gm((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new ct(a.length+(a.length>>>1)),d=0,h=function(m){c[d++]=m},f=0;u>f;++f){if(d+5>c.length){var p=new ct(d+8+(u-f<<1));p.set(c),c=p}var g=a.charCodeAt(f);128>g?h(g):2048>g?(h(192|g>>>6),h(128|63&g)):g>55295&&57344>g?(h(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++f))>>>18),h(128|g>>>12&63),h(128|g>>>6&63),h(128|63&g)):(h(224|g>>>12),h(128|g>>>6&63),h(128|63&g))}return Of(c,0,d)})(Jn(e)),{mtime:0});return{contentType:Bf,body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),estimatedSize:i.byteLength}}if(n===Ue.Base64){var r=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(Jn(e)),s=(a=>"data="+encodeURIComponent(typeof a=="string"?a:Jn(a)))(r);return{contentType:"application/x-www-form-urlencoded",body:s,estimatedSize:new Blob([s]).size}}var o=Jn(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},jf=t=>{var e,n,i=()=>t.transport==="sendBeacon"?{url:As(t.url,{compression:Ue.Base64}),encodedBody:Ro(I({},t,{compression:Ue.Base64,Ji:void 0}))}:{url:Df(t.url,"compression"),encodedBody:Ro(I({},t,{compression:void 0,Ji:void 0}))};try{e=Ro(t)}catch(r){if(wc(t.compression,ri(t.url,"compression")))return A.error("Failed to gzip request body, sending uncompressed payload",r),i();throw r}return e&&wc(t.compression,ri(t.url,"compression"))&&!((n=e.body)instanceof ArrayBuffer?Go(new Uint8Array(n)):ArrayBuffer.isView(n)&&Go(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)))?(Nr=!0,i()):{url:t.url,encodedBody:e}},Uf=t=>{try{return jf(t)}catch(e){return A.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},vm=(function(){var t=se((function*(e){var n=Jn(e.data),i=yield(function(s,o,a){return Ko.apply(this,arguments)})(n,ne.DEBUG,{rethrow:!0});if(!i)return e;var r=yield i.arrayBuffer();return I({},e,{Ji:{contentType:Bf,body:r,estimatedSize:r.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),_m=/Failed to fetch|NetworkError|Load failed/i,Hf=t=>t?.name==="TypeError"&&_m.test(t?.message||""),Wf=t=>{var e=Uf(t);if(e){var n=e.url,i=e.encodedBody,r=i??{},s=r.contentType,o=r.body,a=r.estimatedSize,l=new Headers;ie(t.headers,(function(p,g){l.append(g,p)})),s&&l.append("Content-Type",s);var u=null,c=!1;if(pc){var d=new pc;u={signal:d.signal,timeout:setTimeout((()=>{var p,g;c=!0,d.abort((p=t.timeout,(g=new Error("PostHog request timed out"+(p?" after "+p+"ms":""))).name="AbortError",g))}),t.timeout)}}var h=p=>{c&&p?.name==="AbortError"||Hf(p)?A.warn(p):A.error(p),t.callback==null||t.callback({statusCode:0,error:p})};try{var f;el(n,I({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(f=u)==null?void 0:f.signal},t.fetchOptions)).then((p=>p.text().then((g=>{var m={statusCode:p.status,text:g};if(p.status===200)try{m.json=JSON.parse(g)}catch(v){A.error(v)}t.callback==null||t.callback(m)})))).catch(h).finally((()=>u?clearTimeout(u.timeout):null))}catch(p){u&&clearTimeout(u.timeout),h(p)}}},xa=t=>{try{var e,n=jf(t),i=n.url,r=n.encodedBody,s=r??{},o=s.body,a=s.estimatedSize;if(!o)return;var l=o instanceof Blob?o:new Blob([o],{type:s.contentType});if(He.sendBeacon(i,l))return;var u=U(t.data)?t.data:(e=t.data)==null?void 0:e.batch;if(U(u)&&u.length>1&&(a??0)>16384){var c=Math.ceil(u.length/2),d=h=>U(t.data)?h:I({},t.data,{batch:h});return xa(I({},t,{data:d(u.slice(0,c))})),void xa(I({},t,{data:d(u.slice(c))}))}A.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),Wf(I({},t,{Yi:!0}))}catch(h){A.warn("Beacon send failed",h)}},tu=(t,e,n,i)=>{var r=i==="query"?e==="POST"?"sent_at":"_":void 0;return As(n===Ue.GZipJS?Df(t,"compression"):t,I({},r?{[r]:Date.now().toString()}:{},n===Ue.GZipJS?{}:{compression:n}))},Or=[];el&&Or.push({transport:"fetch",method:Wf}),Vo&&Or.push({transport:"XHR",method(t){var e=Uf(t);if(e){var n=new Vo,i=e.encodedBody;n.open(t.method||"GET",e.url,!0);var r=i??{},s=r.contentType,o=r.body;ie(t.headers,(function(a,l){n.setRequestHeader(l,a)})),s&&n.setRequestHeader("Content-Type",s),t.timeout&&(n.timeout=t.timeout),n.onreadystatechange=()=>{if(n.readyState===4){var a={statusCode:n.status,text:n.responseText};if(n.status===200)try{a.json=JSON.parse(n.responseText)}catch{}t.callback==null||t.callback(a)}},n.send(o)}}}),He!=null&&He.sendBeacon&&Or.push({transport:"sendBeacon",method:xa});var Ia=3e3;class ym{constructor(e,n){this.Xi=!0,this.tr=[],this.er=At(n?.flush_interval_ms||Ia,250,5e3,A.createLogger("flush interval"),Ia),this.ir=e}enqueue(e){this.tr.push(e),this.rr||this.nr()}unload(){this.sr();var e=this.tr.length>0?this.ar():{},n=Object.values(e);[...n.filter((i=>i.url.indexOf("/e")===0)),...n.filter((i=>i.url.indexOf("/e")!==0))].map((i=>{this.lr(I({},i,{transport:"sendBeacon"}))}))}enable(){this.Xi=!1,this.nr()}nr(){var e=this;this.Xi||(this.rr=setTimeout((()=>{if(this.sr(),this.tr.length>0){var n=this.ar(),i=function(){var s=n[r],o=new Date().getTime();s.data&&U(s.data)&&ie(s.data,(a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp})),e.lr(s)};for(var r in n)i()}}),this.er))}lr(e){try{this.ir(e)}catch(n){A.error(n)}}sr(){clearTimeout(this.rr),this.rr=void 0}ar(){var e={};return ie(this.tr,(n=>{var i,r=n,s=(r?r.batchKey:null)||r.url;C(e[s])&&(e[s]=I({},r,{data:[]})),(i=e[s].data)==null||i.push(r.data)})),this.tr=[],e}}var wm=["retriesPerformedSoFar"];class bm{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!C(w)&&"onLine"in w.navigator&&(this.dr=w.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},ve(w,"online",this.vr),ve(w,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var n=e.retriesPerformedSoFar,i=md(e,wm);Dt(n)&&(i.url=As(i.url,{retry_count:n})),this._instance._send_request(I({},i,{callback:r=>{if(r.statusCode!==200&&(400>r.statusCode||r.statusCode>=500)){if((r.statusCode===0?3:10)>(n??0))return void this.At(I({retriesPerformedSoFar:n},i));r.statusCode===0&&A.warn("Request failed before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped retrying after "+(n??0)+" retries.")}i.callback==null||i.callback(r)}}))}At(e){var n=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=n+1;var i=(function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),c=Math.random()-.5;return Math.ceil(u+c*(u-l))})(n),r=Date.now()+i;this.tr.push({retryAt:r,requestOptions:e});var s="Enqueued failed request for retry in "+i;navigator.onLine||(s+=" (Browser is offline)"),A.warn(s),this.ur||(this.ur=!0,this.gr())}gr(){if(this.mr&&clearTimeout(this.mr),this.tr.length===0)return this.ur=!1,void(this.mr=void 0);this.mr=setTimeout((()=>{this.dr&&this.tr.length>0&&this.cr(),this.gr()}),this.hr)}cr(){var e=Date.now(),n=[],i=this.tr.filter((s=>e>s.retryAt||(n.push(s),!1)));if(this.tr=n,i.length>0)for(var r of i)this.retriableRequest(r.requestOptions)}unload(){for(var e of(this.mr&&(clearTimeout(this.mr),this.mr=void 0),this.ur=!1,C(w)||(this.vr&&(w.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(w.removeEventListener("offline",this.pr),this.pr=void 0)),this.tr)){var n=e.requestOptions;try{this._instance._send_request(I({},n,{transport:"sendBeacon"}))}catch(i){A.error(i)}}this.tr=[]}}class Em{constructor(e){this.yr=()=>{var n,i,r,s;this.br||(this.br={});var o=this.scrollElement(),a=this.scrollY(),l=o?Math.max(0,o.scrollHeight-o.clientHeight):0,u=a+(o?.clientHeight||0),c=o?.scrollHeight||0;this.br.lastScrollY=Math.ceil(a),this.br.maxScrollY=Math.max(a,(n=this.br.maxScrollY)!==null&&n!==void 0?n:0),this.br.maxScrollHeight=Math.max(l,(i=this.br.maxScrollHeight)!==null&&i!==void 0?i:0),this.br.lastContentY=u,this.br.maxContentY=Math.max(u,(r=this.br.maxContentY)!==null&&r!==void 0?r:0),this.br.maxContentHeight=Math.max(c,(s=this.br.maxContentHeight)!==null&&s!==void 0?s:0)},this._instance=e}get _r(){return this._instance.config.scroll_root_selector}getContext(){return this.br}resetContext(){var e=this.br;return setTimeout(this.yr,0),e}startMeasuringScrollPosition(){ve(w,"scroll",this.yr,{capture:!0}),ve(w,"scrollend",this.yr,{capture:!0}),ve(w,"resize",this.yr)}scrollElement(){if(!this._r)return w?.document.documentElement;var e=U(this._r)?this._r:[this._r];for(var n of e){var i=w?.document.querySelector(n);if(i)return i}}wr(e){var n=e==="y"?"scrollTop":"scrollLeft";if(this._r){var i=this.scrollElement();return i&&i[n]||0}return w?e==="y"?w.scrollY||w.pageYOffset||w.document.documentElement.scrollTop||0:w.scrollX||w.pageXOffset||w.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var Sm=t=>Pf(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class nu{constructor(e,n,i,r){this.kr=s=>{var o=this.Sr();if(!o||o.sessionId!==s){var a={sessionId:s,props:this.Cr(this._instance)};this.Mr.register({[fa]:a})}},this._instance=e,this.Tr=n,this.Mr=i,this.Cr=r||Sm,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[fa]}getSetOnceProps(){var e,n=(e=this.Sr())==null?void 0:e.props;return n?"r"in n?Ff(n,this._instance.config.disable_capture_url_hashes):{$referring_domain:n.referringDomain,$pathname:n.initialPathName,utm_source:n.utm_source,utm_campaign:n.utm_campaign,utm_medium:n.utm_medium,utm_content:n.utm_content,utm_term:n.utm_term}:{}}getSessionProps(){var e={};return ie(dl(this.getSetOnceProps()),((n,i)=>{i==="$current_url"&&(i="url"),e["$session_entry_"+Yo(i)]=n})),e}}class vl{on(e,n){return this.Er[e]||(this.Er[e]=[]),this.Er[e].push(n),()=>{this.Er[e]=this.Er[e].filter((i=>i!==n))}}emit(e,n){for(var i of this.Er[e]||[])i(n);for(var r of this.Er["*"]||[])r(e,n)}constructor(){this.Er={}}}var xi=pe("[SessionId]");class iu{on(e,n){return this.Ir.on(e,n)}constructor(e,n,i){var r;if(this.Pr=null,this.Rr=[],this.Ar=void 0,this.Fr=!1,this.Ir=new vl,this.Lr=(u,c)=>!(!Dt(u)||!Dt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===Wt)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Ne=e.config,this.Mr=e.persistence,this.Or=void 0,this.Dr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.$r=n||Ht,this.Nr=i||Ht;var s=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*At(this.Ne.session_idle_timeout_seconds||1800,60,36e3,xi.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.qr(),this.jr="ph_"+s+"_window_id",this.Br="ph_"+s+"_primary_window_exists",this.Hr()){var o=be.H(this.jr),a=be.H(this.Br);o&&!a?this.Or=o:be.q(this.jr),be.F(this.Br,!0)}if((r=this.Ne.bootstrap)!=null&&r.sessionID)try{var l=(u=>{var c=this.Ne.bootstrap.sessionID.replace(/-/g,"");if(c.length!==32)throw new Error("Not a valid UUID");if(c[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(c.substring(0,12),16)})();this.Ur(this.Ne.bootstrap.sessionID,new Date().getTime(),l)}catch(u){xi.error("Invalid sessionID in bootstrap",u)}this.zr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return C(this.Rr)&&(this.Rr=[]),this.Rr.push(e),this.Dr&&e(this.Dr,this.Or),()=>{this.Rr=this.Rr.filter((n=>n!==e))}}Hr(){return this.Ne.persistence!=="memory"&&!this.Mr.xi&&be.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&be.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?be.H(this.jr):null}Zr(e){var n=this.Pr;return!Ye(n)&&!Ye(e)&&5e3>Math.abs(e-n)}Ur(e,n,i){var r=n!==this._sessionActivityTimestamp,s=!(e!==this.Dr||i!==this._sessionStartTimestamp);this._sessionStartTimestamp=i,this._sessionActivityTimestamp=n,this.Dr=e,s&&!r||s&&this.Zr(n)||(this.Pr=n,this.Mr.register({[Yn]:[n,e,i]}))}Gr(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return Dt(n)&&n>0}Qr(){this.Gr()?this.Mr.refreshKey(Yn):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!Ye(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this.Pr){this.Qr();var n=this.Jr();n[1]===this.Dr&&n[2]===this._sessionStartTimestamp&&(this.Pr=this._sessionActivityTimestamp,this.Mr.register({[Yn]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],n=Dt(e)?e:0,i=Dt(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(n,i)}Xr(e){return this.Qr(),this.Lr(e,this.Yr())}Jr(){var e=this.Mr.props[Yn];return U(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Pr=null,clearTimeout(this.tn),this.tn=void 0,this.Ur(null,null,null)}destroy(){this.Fr=!0,this.Kr(),clearTimeout(this.tn),this.tn=void 0,this.Ar&&w&&(w.removeEventListener(rs,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&be.q(this.Br)},ve(w,rs,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=null),this.Ne.cookieless_mode===Wt)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var i=n||new Date().getTime(),r=this.Jr(),s=r[1],o=r[2],a=this.Yr(),l=this.Vr(),u=Dt(o)&&Math.abs(i-o)>864e5,c=!1,d=!1,h=!s,f=s,p=!h&&!e&&this.Lr(i,a);if(p){(p=this.Xr(i))||xi.info("cross-tab refresh kept the session alive",{sessionId:s});var g=this.Jr();s=g[1],o=g[2]}h||p||u?(s=this.$r(),l=this.Nr(),xi.info("new session ID generated",{sessionId:s,windowId:l,changeReason:{noSessionId:h,activityTimeout:p,sessionPastMaximumLength:u}}),o=i,c=!0):(l||(l=this.Nr(),c=!0),(d=s!==f)&&(xi.info("adopted cross-tab session id",{sessionId:s,windowId:l}),c=!0));var m=Dt(a)&&e&&!u?a:i,v=Dt(o)?o:new Date().getTime();this.Wr(l),this.Ur(s,m,v),e||this.qr();var E={noSessionId:h,activityTimeout:p,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((S=>S(s,l,E))),{sessionId:s,windowId:l,sessionStartTimestamp:v,changeReason:c?E:void 0,lastActivityTimestamp:a}}qr(){this.Fr||(clearTimeout(this.tn),this.tn=setTimeout((()=>{if(!this.Fr)if(this.Xr(new Date().getTime())){var e=this.Dr;this.resetSessionId(),this.Ir.emit("forcedIdleReset",{idleSessionId:e})}else this.qr()}),1.1*this.sessionTimeoutMs))}}var zf=function(t,e){if(!t)return!1;var n=t.userAgent;if(n&&Ec(n,e))return!0;try{var i=t?.userAgentData;if(i!=null&&i.brands&&i.brands.some((r=>Ec(r?.brand,e))))return!0}catch{}return!!t.webdriver};function qf(){return(qf=se((function*(){var t=He?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),n=e?.model;return X(n)&&n.length>0?n:void 0}catch(i){return void A.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",i)}}))).apply(this,arguments)}var ds=function(t,e){if(!(function(n){try{new RegExp(n)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function To(t,e,n){return Jn({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}var Vf={exact:(t,e)=>e.some((n=>t.some((i=>n===i)))),is_not:(t,e)=>e.every((n=>t.every((i=>n!==i)))),regex:(t,e)=>e.some((n=>t.some((i=>ds(n,i))))),not_regex:(t,e)=>e.every((n=>t.every((i=>!ds(n,i))))),icontains:(t,e)=>e.map(xr).some((n=>t.map(xr).some((i=>n.includes(i))))),not_icontains:(t,e)=>e.map(xr).every((n=>t.map(xr).every((i=>!n.includes(i))))),gt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>i>parseFloat(r)))})),lt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>it.toLowerCase();function Gf(t,e){return!t||Object.entries(t).every((n=>{var i=n[1],r=e?.[n[0]];if(C(r)||Ye(r))return!1;var s=[String(r)],o=Vf[i.operator];return!!o&&o(i.values,s)}))}var ka="custom",ru="i.posthog.com",xm=/^\/static\//;class Im{constructor(e){this.en={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,n=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return n||(n=this.apiHost.replace("."+ru,".posthog.com")),n==="https://app.posthog.com"?"https://us.posthog.com":n}get region(){return this.en[this.apiHost]||(this.en[this.apiHost]=/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"us":/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"eu":ka),this.en[this.apiHost]}rn(e){if(xm.test(e)){var n=this.instance.config.asset_host;if(typeof n=="string")return n.trim().replace(/\/$/,"")||void 0}}endpointFor(e,n){if(n===void 0&&(n=""),n&&(n=n[0]==="/"?n:"/"+n),e==="ui")return this.uiHost+n;if(e==="flags")return this.flagsApiHost+n;if(e==="assets"){var i=this.rn(n);if(i)return""+i+n}if(this.region===ka)return this.apiHost+n;var r=ru+n;switch(e){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}}function Kf(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var Q=pe("[Surveys]"),Yf="seenSurvey_",Jf=t=>{try{var e=(n=>((i,r)=>""+Yf+(function(s){return s.current_iteration&&s.current_iteration>0?s.id+"_"+s.current_iteration:s.id})(r))(0,n))(t);if(localStorage.getItem(e))return;localStorage.setItem(e,"true")}catch(n){Q.error("Failed to persist survey seen state",n)}},km=[Co.Popover,Co.Widget,Co.API],Cm={ignoreConditions:!1,ignoreDelay:!1,displayType:wa.Popover},Am=pe("[PostHog ExternalIntegrations]"),Pm={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class Fm{constructor(e){this._instance=e}ai(e,n){var i;(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,e,(r=>{if(r)return Am.error("failed to load script",r);n()}))}startIfEnabledOrStop(){var e=this,n=function(){var s,o,a,l=i[0],u=i[1];!u||(s=B.__PosthogExtensions__)!=null&&(s=s.integrations)!=null&&s[l]||e.ai(Pm[l],(()=>{var c;(c=B.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=B.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=B.__PosthogExtensions__)==null||(a=a.integrations)==null||(a=a[l])==null||a.stop())};for(var i of Object.entries((r=this._instance.config.integrations)!==null&&r!==void 0?r:{})){var r;n()}}}class Rm{constructor(e,n){this.rt=e,this.nn=n,this.sn=new Map,this.an=!1}add(e){var n=this;return se((function*(){if(n.an)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(n.sn.has(e.name))throw new Error('Browser extension "'+e.name+'" is already registered');n.sn.set(e.name,e);try{var i=e.setup(n.nn);i&&(yield i)}catch(s){var r=n.sn.get(e.name)===e;r&&n.sn.delete(e.name),n.rt.error('Failed to set up browser extension "'+e.name+'"',s),r&&n.ln(e)}}))()}dispose(){if(!this.an){this.an=!0;var e=Array.from(this.sn.values()).reverse();for(var n of(this.sn.clear(),e))this.ln(n)}}ln(e){try{var n=e.dispose==null?void 0:e.dispose();n&&je(n.then)&&n.then(void 0,(i=>{this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}))}catch(i){this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}}}class Tm{constructor(e){this._instance=e}initialize(){}get(e){var n=this._instance.persistence;if(typeof e=="string")return n?.get_property(e);var i={};for(var r of e){var s=n?.get_property(r);C(s)||(i[r]=s)}return i}set(e,n){var i;(i=this._instance.persistence)==null||i.register(typeof e=="string"?{[e]:n}:e)}remove(e){var n;(n=this._instance.persistence)==null||n.unregister(e)}}var su="extensionsRemoteConfig";class $m{constructor(e){this.an=!1,this.instance=e,this.rt=A,this.un=e.hn,this.kv=new Tm(e),this.onEvent=n=>Sr(this.instance.on("eventCaptured",(i=>{try{n({event:i.event,properties:i.properties})}catch(r){this.rt.error("Browser extension event listener failed",r)}}))),this.onRemoteConfig=n=>{if(this.an)return Sr((()=>{}));var i=s=>{try{n(s)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},r=this.instance.dn.on(su,i);return this.un&&i(this.un),Sr(r)},this.vn=new Rm(A.createLogger("[BrowserExtensions]"),this)}get logger(){return this.rt}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return(e=this.instance.get_property(Ji))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(Ji);return typeof e=="string"?e:void 0}get library(){return{name:ne.LIB_NAME,version:ne.LIB_VERSION}}get initialPersonProperties(){var e,n;return(e=(n=this.instance.persistence)==null?void 0:n.get_initial_props())!==null&&e!==void 0?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,n,i,r,s=(e=this.instance.sessionManager)==null?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:(n=s?.sessionId)!==null&&n!==void 0?n:"",windowId:(i=s?.windowId)!==null&&i!==void 0?i:"",sessionStartTimestamp:(r=s?.sessionStartTimestamp)!==null&&r!==void 0?r:0}}catch{return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get projectToken(){return this.instance.config.token}add(e){return this.vn.add(e)}capture(e,n,i){var r=this;return se((function*(){i?r.instance.capture(e,n,{timestamp:i.timestamp,uuid:i.uuid,$set:i.set,$set_once:i.setOnce}):r.instance.capture(e,n)}))()}registerDynamicEventProperties(e){return Sr(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(su,e))}sendRequest(e,n){var i=this;return se((function*(){var r;n===void 0&&(n={});var s=i.instance.requestRouter.endpointFor((r=n.target)!==null&&r!==void 0?r:"api",e),o={method:n.method,url:n.query?As(s,n.query):s,data:n.body,headers:n.headers,timeout:n.timeoutMs,fireCallbackOnDrop:!0,transport:n.transport,compression:n.compression,timestampMode:n.sentAt};return n.transport==="sendBeacon"?(i.instance._send_request(o),{statusCode:202}):new Promise((a=>{o.callback=a,i.instance._send_request(o)}))}))()}dispose(){this.an||(this.an=!0,this.vn.dispose())}}var zi={},$o=0,fs=()=>{},ou='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',Ii="Surveys module not available",au="sanitize_properties is deprecated. Use before_send instead",Zf="Invalid value for property_denylist config: ",Mm=["token","distinct_id",rf],Kn="posthog",Xf=!mm&&Ge?.indexOf("MSIE")===-1&&Ge?.indexOf("Mozilla")===-1,Mo=t=>{var e;return I({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:Lg(P?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:fs,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:t??"unset",__preview_deferred_init_extensions:!1,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:me&&X(me?.search)&&me.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disableDeviceModel:!1,disable_external_dependency_loading:!1,strict_script_versioning:!1,enable_recording_console_log:void 0,secure_cookie:(w==null||(e=w.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(n){A.error("Bad HTTP status: "+n.statusCode+" "+n.text)},get_device_id:n=>n,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:ma,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:Ia},error_tracking:{},_onCapture:fs},(n=>({rageclick:n&&n>="2026-05-30"?{content_ignorelist:Gg,ignore_text_selection:!0}:!n||"2025-11-30">n||{content_ignorelist:!0},capture_pageview:!n||"2025-05-24">n||"history_change",session_recording:n&&n>="2026-06-25"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6},streamNetworkBody:!0}:n&&n>="2026-05-30"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6}}:n&&n>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:n&&n>="2026-01-30"?"head":"body",internal_or_test_user_hostname:n&&n>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:n&&n>="2026-05-30"?250:0,split_storage:!(!n||"2026-05-30">n),detect_google_search_app:!(!n||"2026-05-30">n),disable_capture_url_hashes:!(!n||"2026-06-25">n)}))(t))},Lm=[["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"]],lu=t=>{var e={};for(var n of Lm){var i=n[0],r=n[1];C(t[i])||(e[r]=t[i])}var s=fe({},e,t),o=t.__preview_external_dependency_versioned_paths;return C(o)||(C(t.strict_script_versioning)&&(s.strict_script_versioning=!!o),X(o)&&C(t.asset_host)&&(s.asset_host=o)),U(t.property_blacklist)&&(C(t.property_denylist)?s.property_denylist=t.property_blacklist:U(t.property_denylist)?s.property_denylist=[...t.property_blacklist,...t.property_denylist]:A.error(Zf+t.property_denylist)),s};class Nm{constructor(){this.__forceAllowLocalhost=!1}get fn(){return this.__forceAllowLocalhost}set fn(e){A.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class Ze{pn(e,n){if(e){var i=this.sn.indexOf(e);i!==-1&&this.sn.splice(i,1)}return this.sn.push(n),n.initialize==null||n.initialize(),n}gn(){return this.config.cookieless_mode===Wt||this.config.cookieless_mode===kn&&this.consent.isRejected()}get decideEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){var e;this.webPerformance=new Nm,this.mn=!1,this.version=ne.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new vl,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=Mo(),this.SentryIntegration=tm,this.sentryIntegration=i=>(function(r,s){var o=Ef(r,s);return{name:bf,processEvent:a=>o(a)}})(this,i),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.wn=!1,this.kn=null,this.xn=null,this.Sn=null,this.scrollManager=new Em(this),this.pageViewManager=new Gc(this),this.rateLimiter=new um(this),this.requestRouter=new Im(this),this.consent=new Hg(this),this.externalIntegrations=new Fm(this);var n=(e=Ze.__defaultExtensionClasses)!==null&&e!==void 0?e:{};this.featureFlags=n.featureFlags&&new n.featureFlags(this),this.toolbar=n.toolbar&&new n.toolbar(this),this.surveys=n.surveys&&new n.surveys(this),this.conversations=n.conversations&&new n.conversations(this),this.logs=n.logs&&new n.logs(this),this.metrics=n.metrics&&new n.metrics(this),this.experiments=n.experiments&&new n.experiments(this),this.exceptions=n.exceptions&&new n.exceptions(this),this.people={set:(i,r,s)=>{var o=X(i)?{[i]:r}:i;this.setPersonProperties(o),s?.({})},set_once:(i,r,s)=>{var o=X(i)?{[i]:r}:i;this.setPersonProperties(void 0,o),s?.({})}},this.on("eventCaptured",(i=>A.info('send "'+i?.event+'"',i)))}init(e,n,i){if(i&&i!==Kn){var r,s=(r=zi[i])!==null&&r!==void 0?r:new Ze;return s._init(e,n,i),zi[i]=s,zi[Kn][i]=s,s}return this._init(e,n,i)}_init(e,n,i){var r,s;n===void 0&&(n={});var o,a=X(e)?e.trim():"";if(!a)return A.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return a!==((o=this.config)==null?void 0:o.token)?console.warn("[PostHog.js]","You have already initialized PostHog with a different project token! Re-initializing is a no-op, so events will keep going to the project this instance was initialized with. To capture into a second project, load PostHog once, then initialize a named instance after the SDK has loaded, e.g. posthog.init('"+a+"', { ... }, 'project2')"):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=Mo(n.defaults),n.debug=this.Cn(n.debug),this.Mn=n,this.Tn=[],n.person_profiles?this.xn=n.person_profiles:n.process_person&&(this.xn=n.process_person);var l=Mo(n.defaults),u=lu(n),c=fe({},l,u,{name:i,token:a});he(l.rageclick)&&he(u.rageclick)&&(c.rageclick=fe({},l.rageclick,u.rageclick)),he(l.session_recording)&&he(u.session_recording)&&(c.session_recording=fe({},l.session_recording,u.session_recording)),this.set_config(c),this.config.on_xhr_error&&A.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=n.disable_compression?void 0:Ue.GZipJS;var d=this.En();if(this.persistence=new ko(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new ko(I({},this.config,{persistence:"sessionStorage"}),d,!1),this.bn="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&be.N()){var h=be.H(this.bn);U(h)&&h.forEach((k=>{X(k)&&this.yn.add(k)}))}else be.q(this.bn);var f=I({},this.persistence.props),p=I({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new ym((k=>this.Pn(k)),this.config.request_queue_config),this.Rn=new bm(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new iu(this),this.sessionPropsManager=new nu(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((k,T,x)=>{(x!=null&&x.activityTimeout||x!=null&&x.sessionPastMaximumLength||x!=null&&x.crossTabAdoption)&&this.An()}))),this.Fn(),this.config.__preview_deferred_init_extensions?(A.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Ln(g)}),0)):(A.info("Initializing extensions synchronously"),this.Ln(g)),ne.DEBUG=ne.DEBUG||this.config.debug,ne.DEBUG&&A.info("Starting in debug mode",{this:this,config:n,thisC:I({},this.config),p:f,s:p}),!this.config.identity_distinct_id||(r=n.bootstrap)!=null&&r.distinctID||(n.bootstrap=I({},n.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((s=n.bootstrap)==null?void 0:s.distinctID)!==void 0){var m=n.bootstrap.distinctID,v=this.get_distinct_id(),E=this.persistence.get_property(at);if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&E===Hn)this.identify(m);else if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&E===vn)A.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{var S=this.config.get_device_id(Ht()),_=n.bootstrap.isIdentifiedID?S:m;this.persistence.set_property(at,n.bootstrap.isIdentifiedID?vn:Hn),this.register({distinct_id:m,$device_id:_})}}if(g)this.register_once({distinct_id:_r,$device_id:null},"");else if(!this.get_distinct_id()){var b=this.config.get_device_id(Ht());this.register_once({distinct_id:b,$device_id:b},""),this.persistence.set_property(at,Hn)}return ve(w,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),n.segment?(function(k,T){var x=k.config.segment;if(!x)return T();(function(F,$){var O=F.config.segment;if(!O)return $();var L=K=>{var V=()=>K.anonymousId()||Ht();F.config.get_device_id=V,K.id()&&(F.register({distinct_id:K.id(),$device_id:V()}),F.persistence.set_property(at,vn)),$()},N=O.user();"then"in N&&je(N.then)?N.then(L):L(N)})(k,(()=>{x.register((F=>{typeof Promise<"u"&&Promise.resolve||xo.warn("This browser does not have Promise support, and can not use the segment integration");var $=(O,L)=>{if(!L)return O;O.event.userId||O.event.anonymousId===F.get_distinct_id()||(xo.info("No userId set, resetting PostHog"),F.reset()),O.event.userId&&O.event.userId!==F.get_distinct_id()&&(xo.info("UserId set, identifying with PostHog"),F.identify(O.event.userId));var N=F.calculateEventProperties(L,O.event.properties);return O.event.properties=Object.assign({},N,O.event.properties),O};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:O=>$(O,O.event.event),page:O=>$(O,Gn),identify:O=>$(O,bo),screen:O=>$(O,"$screen")}})(k)).then((()=>{T()}))}))})(this,(()=>this.On())):this.On(),je(this.config._onCapture)&&this.config._onCapture!==fs&&(A.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(k=>this.config._onCapture(k.event,k)))),this.config.ip&&A.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this.config.disableDeviceModel||(function(){return qf.apply(this,arguments)})().then((k=>{k&&this.register({[yo]:k})})).catch(fs),this}Fn(){var e,n,i,r,s,o,a=(e=(n=this.config.__extensionClasses)==null?void 0:n.featureFlags)!==null&&e!==void 0?e:(i=Ze.__defaultExtensionClasses)==null?void 0:i.featureFlags;a&&(this.featureFlags&&this.featureFlags instanceof a||((r=this.Dn)==null||r.call(this),this.Dn=void 0,this.featureFlags=new a(this)),je(this.featureFlags.onReloading)&&je(this.featureFlags.setup)?this.Dn||(this.Dn=this.featureFlags.onReloading((()=>{this.dn.emit("featureFlagsReloading",!0)})),this.$n().add(this.featureFlags)):(s=(o=this.featureFlags).initialize)==null||s.call(o))}Ln(e){var n,i,r,s,o,a,l,u=performance.now(),c=I({},Ze.__defaultExtensionClasses,this.config.__extensionClasses),d=[];c.exceptions&&this.sn.push(this.exceptions=(n=this.exceptions)!==null&&n!==void 0?n:new c.exceptions(this)),c.historyAutocapture&&this.sn.push(this.historyAutocapture=new c.historyAutocapture(this)),c.tracingHeaders&&this.sn.push(this.tracingHeaders=new c.tracingHeaders(this)),c.siteApps&&this.sn.push(this.siteApps=new c.siteApps(this)),c.sessionRecording&&!e&&this.sn.push(this.sessionRecording=new c.sessionRecording(this)),this.config.disable_scroll_properties||d.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),c.autocapture&&this.sn.push(this.autocapture=new c.autocapture(this)),c.surveys&&this.sn.push(this.surveys=(i=this.surveys)!==null&&i!==void 0?i:new c.surveys(this)),c.logs&&this.sn.push(this.logs=(r=this.logs)!==null&&r!==void 0?r:new c.logs(this)),c.metrics&&this.sn.push(this.metrics=(s=this.metrics)!==null&&s!==void 0?s:new c.metrics(this)),c.conversations&&this.sn.push(this.conversations=(o=this.conversations)!==null&&o!==void 0?o:new c.conversations(this)),c.productTours&&this.sn.push(this.productTours=new c.productTours(this)),c.heatmaps&&this.sn.push(this.heatmaps=new c.heatmaps(this)),c.webVitalsAutocapture&&this.sn.push(this.webVitalsAutocapture=new c.webVitalsAutocapture(this)),c.exceptionObserver&&this.sn.push(this.exceptionObserver=new c.exceptionObserver(this)),c.deadClicksAutocapture&&this.sn.push(this.deadClicksAutocapture=new c.deadClicksAutocapture(this,em)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((h=>{h.initialize&&d.push((()=>{h.initialize==null||h.initialize()}))})),d.push((()=>{if(this.Nn){var h=this.Nn;this.Nn=void 0,this.sn.forEach((f=>f.onRemoteConfig==null?void 0:f.onRemoteConfig(h)))}})),this.qn(d,u)}qn(e,n){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,n)}),0);var i=e.shift();if(i)try{i()}catch(s){A.error("Error initializing extension:",s)}}var r=Math.round(performance.now()-n);this.register_for_session({[sf]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[of]:r}),this.config.__preview_deferred_init_extensions&&A.info("PostHog extensions initialized ("+r+"ms)")}Zi(e){var n;if(!P||!P.body)return A.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.Zi(e)}),500);if(this.config.__preview_deferred_init_extensions&&(this.Nn=e),this.hn=e,this.compression=void 0,e.ok){var i,r=e.config;r.supportedCompression&&!this.config.disable_compression&&(this.compression=j(r.supportedCompression,Ue.GZipJS)?Ue.GZipJS:j(r.supportedCompression,Ue.Base64)?Ue.Base64:void 0),(i=r.analytics)!=null&&i.endpoint&&(this.analyticsDefaultEndpoint=r.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:ma}),(n=this.jn)==null||n.handleRemoteConfig(e),this.sn.forEach((s=>s.onRemoteConfig==null?void 0:s.onRemoteConfig(e)))}On(){try{this.config.loaded(this)}catch(i){A.critical("`loaded` function failed",i)}if(this.Bn(),this.config.internal_or_test_user_hostname&&me!=null&&me.hostname){var e=me.hostname,n=this.config.internal_or_test_user_hostname;(typeof n=="string"?e===n:n.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.gn())&&this.Hn()}),1),this.Un=new Tf(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()&&yr(this.__request_queue,(e=>this.Pn(e))),this.__request_queue=[],this.Bn()}_handle_unload(){var e,n,i,r,s;(e=this.surveys)==null||e.handlePageUnload==null||e.handlePageUnload(),(n=this.metrics)==null||n.flush("sendBeacon"),this.config.request_batching?(this.zn()&&this.capture(wo),(i=this.logs)==null||i.flushLogs("sendBeacon"),(r=this.In)==null||r.unload(),(s=this.Rn)==null||s.unload()):this.zn()&&this.capture(wo,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?Xf?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)?e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:429})):(e.transport=e.transport||this.config.api_transport,e.headers=I({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,(C(this.config.disable_beacon)?this.config.__preview_disable_beacon:this.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(n=>{var i,r,s,o=I({},n);o.timeout=o.timeout||6e4;var a,l,u,c,d,h=(i=o.transport)!==null&&i!==void 0?i:"fetch";h==="sendBeacon"&&C(o.compression)&&o.data&&(o.compression=Ue.Base64),o.method==="POST"&&o.data&&(o.timestampMode==="capture-body"?o.data={api_key:(l=(d=(c=U(a=o.data)?a:[a])[0])==null||(u=d.properties)==null?void 0:u.token)!==null&&l!==void 0?l:d?.token,batch:c,sent_at:new Date().toISOString()}:o.timestampMode==="body"&&(o.data=(function(m,v){return v===void 0&&(v=new Date().toISOString()),U(m)?m.map((E=>I({},E,{sent_at:v}))):I({},m,{sent_at:v})})(o.data))),o.url=tu(o.url,o.method,o.compression,o.timestampMode);var f=Or.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),p=(r=(s=(function(m,v){for(var E=0;m.length>E;E++)if(m[E].transport===h)return m[E]})(f))==null?void 0:s.method)!==null&&r!==void 0?r:f[0].method;if(!p)throw new Error("No available transport method");var g=m=>{try{p(m)}catch(v){Hf(v)?A.warn(v):A.error(v),o.callback==null||o.callback({statusCode:0,error:v})}};h!=="sendBeacon"&&o.data&&o.compression===Ue.GZipJS&&Op&&typeof Promise<"u"&&!Nr?vm(o).then((m=>{g(m)})).catch((m=>{if(bc(m))return Nr=!0,void g(I({},o,{compression:void 0,url:tu(n.url,n.method,void 0,n.timestampMode)}));(v=>{if(!v||typeof v!="object")return!1;var E="name"in v?String(v.name):"";return bc(v)||E===vd})(m)&&(Nr=!0),g(o)})):p(o)})(I({},e,{callback:n=>{var i,r;this.rateLimiter.checkForLimiting(n),400>n.statusCode||(i=(r=this.config).on_request_error)==null||i.call(r,n),e.callback==null||e.callback(n)}}))):e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:0}))}Pn(e){this.Rn?this.Rn.retriableRequest(e):this._send_request(e)}_execute_array(e){$o++;try{var n,i=[],r=[],s=[];yr(e,(a=>{if(a)if(U(n=a[0]))s.push(a);else if(je(a))try{a.call(this)}catch(l){A.error("Error executing queued PostHog call",a,l)}else U(a)&&n==="alias"?i.push(a):U(a)&&n.indexOf("capture")!==-1&&je(this[n])?s.push(a):r.push(a)}));var o=function(a,l){yr(a,(function(u){try{if(U(u[0])){var c=l;ie(u,(function(d){c=c[d[0]].apply(c,d.slice(1))}))}else l[u[0]].apply(l,u.slice(1))}catch(d){A.error("Error executing queued PostHog call",u,d)}}))};o(i,this),o(r,this),o(s,this)}finally{$o--}}push(e){if($o>0&&U(e)&&X(e[0])){var n=Ze.prototype[e[0]];je(n)&&n.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,n,i){var r,s,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.In){if(this.is_capturing())if(!C(e)&&X(e)){var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var c=i!=null&&i.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(c==null||!c.isRateLimited){n!=null&&n.$current_url&&!X(n?.$current_url)&&(A.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),n==null||delete n.$current_url),e!=="$exception"||i!=null&&i.Wn||A.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,h=i?.timestamp||d,f=kc(i?.uuid,Ht),p={uuid:f,event:e,properties:this.calculateEventProperties(e,n||{},h,f)};e===Gn&&this.config.__preview_capture_bot_pageviews&&u&&(p.event="$bot_pageview",p.properties.$browser_type="bot"),c&&(p.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&p.properties.$feature_flag_has_experiment===!1&&this.get_property(Qr)===!0;i?.$set&&!g&&(p.$set=i?.$set);var m=i?.$unset;m&&(p.$unset=m);var v,E,S,_=g?void 0:this.Vn(i?.$set_once,e!==Tc,e===bo);if(_&&(p.$set_once=_),i!=null&&i._noTruncate||(s=this.config.properties_string_max_length,o=p,a=L=>X(L)?L.slice(0,s):L,l=new Set,p=(function L(N,K){if(N!==Object(N))return a?a(N):N;if(!l.has(N)){var V;if(l.add(N),U(N))V=[],yr(N,(R=>{V.push(L(R))}));else{var M={};ie(N,((R,Z)=>{l.has(R)||(M[Z]=L(R))})),V=M}return V}})(o)),p.timestamp=h,C(i?.timestamp)||(p.properties.$event_time_override_provided=!0,p.properties.$event_time_override_system_time=d),g&&(p.properties=(function(L,N){N===void 0&&(N=[]);var K={},V=M=>{L[M]!==void 0&&(K[M]=L[M])};return Bp.forEach(V),N.forEach(V),K})(p.properties,Mm)),e===qt.DISMISSED||e===qt.SENT){var b=n?.[Ao.SURVEY_ID],k=n?.[Ao.SURVEY_ITERATION];Jf({id:b,current_iteration:k}),p.$set=I({},p.$set,{[(v={id:b,current_iteration:k},E=e===qt.SENT?"responded":"dismissed",S="$survey_"+E+"/"+v.id,v.current_iteration&&v.current_iteration>0&&(S="$survey_"+E+"/"+v.id+"/"+v.current_iteration),S)]:!0})}else e===qt.SHOWN&&(p.$set=I({},p.$set,{[Ao.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===cm.SHOWN){var T=n?.[Yc.TOUR_TYPE];T&&(p.$set=I({},p.$set,{[Yc.TOUR_LAST_SEEN_DATE+"/"+T]:new Date().toISOString()}))}var x=I({},p.properties.$set,p.$set);if(Kt(x)||this.setPersonPropertiesForFlags(x),!H(this.config.before_send)){var F=this.Pt(p);if(!F)return;(p=F).uuid=kc(p.uuid,Ht)}this.dn.emit("eventCaptured",p);var $=(r=i?._url)!==null&&r!==void 0?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),O={method:"POST",url:$,data:p,compression:"best-available",timestampMode:i?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test($)?"body":"capture-body",batchKey:i?._batchKey,transport:i?.transport};return!this.config.request_batching||i&&(i==null||!i._batchKey)||i!=null&&i.send_instantly?this.Pn(O):this.In.enqueue(O),p}A.critical("This capture call is ignored due to client rate limiting.")}}else A.error("No event name provided to posthog.capture")}else A.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(n=>e(n.event,n)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new $m(this)}cn(e){this._n.push(e);var n=!0;return()=>{if(n){n=!1;var i=this._n.indexOf(e);i!==-1&&this._n.splice(i,1)}}}calculateEventProperties(e,n,i,r,s){if(i=i||new Date,!this.persistence||!this.sessionPersistence)return n;var o=s?void 0:this.persistence.remove_event_timer(e),a=I({},n);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.gn()&&(a[rf]=!0),e==="$snapshot"){var l=I({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!X(a.distinct_id)&&!ke(a.distinct_id)||Jo(a.distinct_id))&&A.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=(function(b,k,T,x){var F,$,O,L;if(x===void 0&&(x=!1),!Ge)return{};var N,K=b?[...si,...k||[]]:[],V=(function(Dn){for(var qe=0;xc.length>qe;qe++){var jn=xc[qe],Mt=jn[1],Lt=jn[0].exec(Dn),ut=Lt&&(je(Mt)?Mt(Lt,Dn):Mt);if(ut)return ut}return["",""]})(Ge),M=V[0],R=V[1],Z=(N=typeof navigator<"u"?navigator:void 0)!=null&&N.brave?{brave:!0}:{},Ce={};C(T)||(Ce.detectGoogleSearchApp=T);var oe={},ye=(F=navigator)==null||(F=F.userAgentData)==null?void 0:F.platform,$e=($=navigator)==null?void 0:$.maxTouchPoints,ae=w==null||(O=w.screen)==null?void 0:O.width,Ie=w==null||(L=w.screen)==null?void 0:L.height,Se=w?.devicePixelRatio;C(ye)||(oe.userAgentDataPlatform=ye),C($e)||(oe.maxTouchPoints=$e),C(ae)||(oe.screenWidth=ae),C(Ie)||(oe.screenHeight=Ie),C(Se)||(oe.devicePixelRatio=Se);var De,wt,ge,Je,bt,mn,Re,Pe,$t=fe(dl({$os:M,$os_version:R,$browser:Hd(Ge,navigator.vendor,Z,Ce),$device:Ic(Ge),$device_type:(wt=Ge,ge=oe,Pe=Ic(wt),Pe===xd||Pe===Sd||Pe==="Kobo"||Pe==="Kindle Fire"||Pe===Od?ti:Pe===Ki||Pe===Qn||Pe===Yi||Pe===Xo?"Console":Pe===kd?"Wearable":Pe?rt:ge?.userAgentDataPlatform==="Android"&&((Je=ge?.maxTouchPoints)!==null&&Je!==void 0?Je:0)>0?600>Math.min((bt=ge?.screenWidth)!==null&&bt!==void 0?bt:0,(mn=ge?.screenHeight)!==null&&mn!==void 0?mn:0)/((Re=ge?.devicePixelRatio)!==null&&Re!==void 0?Re:1)?rt:ti:"Desktop"),$timezone:Rf(),$timezone_offset:om()}),{$current_url:Xi(x?fn(me?.href):me?.href,K,Qi),$host:me?.host,$pathname:me?.pathname,$raw_user_agent:Ge.length>1e3?Ge.substring(0,997)+"...":Ge,$browser_version:ig(Ge,navigator.vendor,Z,Ce),$browser_language:Kc(),$browser_language_prefix:(De=Kc(),typeof De=="string"?De.split("-")[0]:void 0),$screen_height:w?.screen.height,$screen_width:w?.screen.width,$viewport_height:w?.innerHeight,$viewport_width:w?.innerWidth,$lib:ne.LIB_NAME,$lib_version:ne.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return ne.SDK_DIST_CHANNEL&&($t.$sdk_dist_channel=ne.SDK_DIST_CHANNEL),$t})(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties,this.config.detect_google_search_app,this.config.disable_capture_url_hashes);if(this.sessionManager){var d=this.sessionManager.checkAndGetSessionAndWindowId(s,i.getTime()),h=d.windowId;a.$session_id=d.sessionId,a.$window_id=h}this.sessionPropsManager&&fe(a,this.sessionPropsManager.getSessionProps());try{var f;this.sessionRecording&&fe(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(f=this.Rn)==null?void 0:f.length}catch(b){a.$sdk_debug_error_capturing_properties=String(b)}if(this.requestRouter.region===ka&&(a.$lib_custom_api_host=this.config.api_host),u=e!==Gn||s?e!==wo||s?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(i):this.pageViewManager.doPageView(i,r),a=fe(a,u),e===Gn&&P&&(a.title=P.title),!C(o)){var p=i.getTime()-o;a.$duration=parseFloat((p/1e3).toFixed(3))}Ge&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();ie(["$referrer","$referring_domain"],(b=>{b in g&&delete m[b]}));var v={};if(this._n.length>0)for(var E of this._n.slice())try{fe(v,E())}catch(b){A.error("Failed to produce browser extension event properties",b)}(a=fe({},c,g,m,I({},v,a))).$is_identified=this._isIdentified(),U(this.config.property_denylist)?ie(this.config.property_denylist,(function(b){delete a[b]})):A.error(Zf+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var S=this.config.sanitize_properties;S&&(A.error(au),a=S(a,e));var _=this.Zn();return a.$process_person_profile=_,_&&!s&&this.Gn("_calculate_event_properties"),a}Vn(e,n,i){var r;if(n===void 0&&(n=!0),i===void 0&&(i=!1),!this.persistence||!this.Zn()||this.mn&&!i)return e;var s=this.persistence.get_initial_props(),o=(r=this.sessionPropsManager)==null?void 0:r.getSetOnceProps(),a=fe({},s,o||{},e||{}),l=this.config.sanitize_properties;return l&&(A.error(au),a=l(a,"$set_once")),n&&(this.mn=!0),Kt(a)?void 0:a}register(e,n){var i;(i=this.persistence)==null||i.register(e,n)}register_once(e,n,i){var r;(r=this.persistence)==null||r.register_once(e,n,i)}register_for_session(e){var n;(n=this.sessionPersistence)==null||n.register(e),Object.keys(e).forEach((i=>this.yn.add(i))),this.Qn()}unregister(e){var n;(n=this.persistence)==null||n.unregister(e)}unregister_for_session(e){var n;(n=this.sessionPersistence)==null||n.unregister(e),this.yn.delete(e),this.Qn()}Kn(e,n){this.register({[e]:n})}An(){this.yn.forEach((e=>{var n;(n=this.sessionPersistence)==null||n.unregister(e)})),this.yn.clear(),this.Qn()}Qn(){var e;if(this.bn)if(this.config.persistence==="memory"||(e=this.sessionPersistence)!=null&&e.xi||!be.N())be.q(this.bn);else{var n=[];this.yn.forEach((i=>n.push(i))),n.length>0?be.F(this.bn,n):be.q(this.bn)}}getFeatureFlag(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlag(e,n)}getFeatureFlagPayload(e){var n;return(n=this.featureFlags)==null?void 0:n.getFeatureFlagPayload(e)}getFeatureFlagResult(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlagResult(e,n)}getAllFeatureFlags(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.getAllFeatureFlags())!==null&&e!==void 0?e:[]}isFeatureEnabled(e,n){var i,r;return(i=(r=this.featureFlags)==null?void 0:r.isFeatureEnabled(e,n))!==null&&i!==void 0?i:n?.defaultValue}reloadFeatureFlags(){var e;(e=this.featureFlags)==null||e.reloadFeatureFlags()}updateFlags(e,n,i){var r;(r=this.featureFlags)==null||r.updateFlags(e,n,i)}updateEarlyAccessFeatureEnrollment(e,n,i){var r;(r=this.featureFlags)==null||r.updateEarlyAccessFeatureEnrollment(e,n,i)}getEarlyAccessFeatures(e,n,i){var r;return n===void 0&&(n=!1),(r=this.featureFlags)==null?void 0:r.getEarlyAccessFeatures(e,n,i)}on(e,n){return this.dn.on(e,n)}onFeatureFlags(e){return this.featureFlags?this.featureFlags.onFeatureFlags(e):(e([],{},{errorsLoading:!0}),()=>{})}onSurveysLoaded(e){return this.surveys?this.surveys.onSurveysLoaded(e):(e([],{isLoaded:!1,error:Ii}),()=>{})}onSessionId(e){var n,i;return(n=(i=this.sessionManager)==null?void 0:i.onSessionId(e))!==null&&n!==void 0?n:()=>{}}getSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getSurveys(e,n):e([],{isLoaded:!1,error:Ii})}getActiveMatchingSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,n):e([],{isLoaded:!1,error:Ii})}renderSurvey(e,n){var i;(i=this.surveys)==null||i.renderSurvey(e,n)}displaySurvey(e,n){var i;n===void 0&&(n=Cm),(i=this.surveys)==null||i.displaySurvey(e,n)}cancelPendingSurvey(e){var n;(n=this.surveys)==null||n.cancelPendingSurvey(e)}canRenderSurvey(e){var n,i;return(n=(i=this.surveys)==null?void 0:i.canRenderSurvey(e))!==null&&n!==void 0?n:{visible:!1,disabledReason:Ii}}canRenderSurveyAsync(e,n){var i,r;return n===void 0&&(n=!1),(i=(r=this.surveys)==null?void 0:r.canRenderSurveyAsync(e,n))!==null&&i!==void 0?i:Promise.resolve({visible:!1,disabledReason:Ii})}Jn(e){return!e||Jo(e)?(A.critical("Unique user id has not been set in posthog.identify"),!1):e===_r?(A.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.'),!1):!["distinct_id","distinctid"].includes(e.toLowerCase())&&!["undefined","null"].includes(e.toLowerCase())||(A.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.'),!1)}identify(e,n,i){if(!this.__loaded||!this.persistence)return A.uninitializedWarning("posthog.identify");if(ke(e)&&(e=e.toString(),A.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.Jn(e)&&this.Gn("posthog.identify")){var r=this.get_distinct_id();this.register({$user_id:e}),this.get_property(Ji)||this.register_once({$had_persisted_distinct_id:!0,$device_id:r},""),e!==r&&e!==this.get_property(Ri)&&(this.unregister(Ri),this.register({distinct_id:e}));var s,o=(this.persistence.get_property(at)||Hn)===Hn,a=e!==r,l=!a&&o;if(a&&o)this.persistence.set_property(at,vn),this.setPersonPropertiesForFlags({$set:n||{},$set_once:i||{}},!1),this.capture(bo,{distinct_id:e,$anon_distinct_id:r},{$set:n||{},$set_once:i||{}}),this.Sn=To(e,n,i),(s=this.featureFlags)==null||s.setAnonymousDistinctId(r);else if(l){this.persistence.set_property(at,vn);var u=n||{},c=i||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=To(e,n,i)}else(n||i)&&this.setPersonProperties(n,i);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Cn)):l&&(n||i)&&this.reloadFeatureFlags()}}setPersonProperties(e,n){if((e||n)&&this.Gn("posthog.setPersonProperties")){var i=To(this.get_distinct_id(),e,n);this.Sn!==i?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:n||{}},!0),this.capture("$set",{$set:e||{},$set_once:n||{}}),this.Sn=i):A.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}unsetPersonProperties(e){var n,i=(U(e)?e:[e]).filter((r=>X(r)&&r.length>0));i.length!==0&&this.Gn("posthog.unsetPersonProperties")&&((n=this.featureFlags)==null||n.unsetPersonPropertiesForFlags(i,!0),this.capture("$set",{$unset:i}),this.Sn=null)}group(e,n,i){if(e&&n){var r=this.getGroups(),s=r[e]!==n;if(s&&this.resetGroupPropertiesForFlags(e),this.register({$groups:I({},r,{[e]:n})}),s||i){var o={$group_type:e,$group_key:n};i&&(o.$group_set=i),this.capture(Tc,o)}i&&this.setGroupPropertiesForFlags({[e]:i}),s&&!i&&this.reloadFeatureFlags()}else A.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),(i=this.featureFlags)==null||i.setPersonPropertiesForFlags(e,n)}resetPersonPropertiesForFlags(e){var n;e===void 0&&(e=!0),(n=this.featureFlags)==null||n.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((i=this.featureFlags)==null||i.setGroupPropertiesForFlags(e,n))}resetGroupPropertiesForFlags(e){var n;(n=this.featureFlags)==null||n.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,n){var i,r,s,o,a,l,u,c,d,h;if(n===void 0&&(n=!1),A.info("reset"),!this.__loaded)return A.uninitializedWarning("posthog.reset");var f,p=this.get_property(Ji),g=this.get_property(yo),m=this.get_property(An),v=this.is_capturing();if(this.consent.reset(),n||!v||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after."),(i=this.persistence)==null||i.clear(),(r=this.sessionPersistence)==null||r.clear(),this.yn.clear(),this.Qn(),C(m)||(f=this.persistence)==null||f.register({[An]:m}),(s=this.surveys)==null||s.reset(),(o=this.Un)==null||o.stop(),(a=this.featureFlags)==null||a.reset(),(l=this.conversations)==null||l.reset(),(u=this.logs)==null||u.reset(),(c=this.metrics)==null||c.reset(),(d=this.persistence)==null||d.set_property(at,Hn),(h=this.sessionManager)==null||h.resetSessionId(),this.Sn=null,this.config.cookieless_mode===Wt)this.register_once({distinct_id:_r,$device_id:null},"");else{var E=this.config.get_device_id(Ht());this.register_once({distinct_id:E,$device_id:e?E:p},""),e||C(g)||this.register({[yo]:g})}this.register({$last_posthog_reset:new Date().toISOString()},1),delete this.config.identity_distinct_id,delete this.config.identity_hash,this.reloadFeatureFlags()}shutdown(e){var n=this;return se((function*(){var i,r,s,o,a,l,u;if(n.__loaded){(i=n.Un)==null||i.stop(),(r=n.jn)==null||r.dispose(),(s=n.sessionRecording)==null||s.dispose(),(o=n.logs)==null||o.flushLogs("sendBeacon"),(a=n.metrics)==null||a.flush("sendBeacon"),(l=n.In)==null||l.unload(),(u=n.Rn)==null||u.unload();try{var c;(c=n.featureFlags)==null||c.destroy()}catch(d){A.error("Error while destroying feature flags",d)}}else A.uninitializedWarning("posthog.shutdown")}))()}setIdentity(e,n){var i;this.config.identity_distinct_id=e,this.config.identity_hash=n,this.alias(e),(i=this.conversations)==null||i.Xn()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,(e=this.conversations)==null||e.ts()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,n;return(e=(n=this.sessionManager)==null?void 0:n.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var n=this.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.sessionStartTimestamp,r=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+n.sessionId);if(e!=null&&e.withTimestamp&&i){var s,o=(s=e.timestampLookBack)!==null&&s!==void 0?s:10;if(!i)return r;r+="?t="+Math.max(Math.floor((new Date().getTime()-i)/1e3)-o,0)}return r}alias(e,n){return e===this.get_property(Zd)?(A.critical("Attempting to create alias for existing People user - aborting."),-2):this.Gn("posthog.alias")?(C(n)&&(n=this.get_distinct_id()),e!==n?(this.Kn(Ri,e),this.capture("$create_alias",{alias:e,distinct_id:n})):(A.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var n=I({},this.config);if(he(e)){var i,r,s,o,a,l,u,c,d,h,f,p;fe(this.config,lu(e));var g=this.En();(i=this.persistence)==null||i.update_config(this.config,n,g),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new ko(I({},this.config,{persistence:"sessionStorage"}),g,!1);var m=this.Cn(this.config.debug);mt(m)&&(this.config.debug=m),mt(this.config.debug)&&(this.config.debug?(ne.DEBUG=!0,le.N()&&le.F("ph_debug",!0),A.info("set_config",{config:e,oldConfig:n,newConfig:I({},this.config)})):(ne.DEBUG=!1,le.N()&&le.q("ph_debug"))),(r=this.featureFlags)==null||r.updateConfig==null||r.updateConfig(this.config,this.Qi()),(s=this.exceptionObserver)==null||s.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(h=this.deadClicksAutocapture)==null||h.startIfEnabledOrStop(),(f=this.surveys)==null||f.loadIfEnabled(),this.es(),(p=this.externalIntegrations)==null||p.startIfEnabledOrStop()}}_overrideSDKInfo(e,n){ne.LIB_NAME=e,ne.LIB_VERSION=n}startSessionRecording(e){var n,i,r,s,o,a=e===!0,l={sampling:a||!(e==null||!e.sampling),linked_flag:a||!(e==null||!e.linked_flag),url_trigger:a||!(e==null||!e.url_trigger),event_trigger:a||!(e==null||!e.event_trigger)};Object.values(l).some(Boolean)&&((n=this.sessionManager)==null||n.checkAndGetSessionAndWindowId(),l.sampling&&((i=this.sessionRecording)==null||i.overrideSampling()),l.linked_flag&&((r=this.sessionRecording)==null||r.overrideLinkedFlag()),l.url_trigger&&((s=this.sessionRecording)==null||s.overrideTrigger("url")),l.event_trigger&&((o=this.sessionRecording)==null||o.overrideTrigger("event"))),this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,n){if(this.exceptions){var i=new Error("PostHog syntheticException"),r=this.exceptions.buildProperties(e,{handled:!0,syntheticException:i});return this.exceptions.sendExceptionEvent(I({},r,n))}}addExceptionStep(e,n){var i;(i=this.exceptions)==null||i.addExceptionStep(e,n)}captureLog(e){var n;(n=this.logs)==null||n.captureLog(e)}get logger(){var e,n;return(e=(n=this.logs)==null?void 0:n.logger)!==null&&e!==void 0?e:Ze.rs}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var n,i;return(n=(i=this.toolbar)==null?void 0:i.loadToolbar(e))!==null&&n!==void 0&&n}get_property(e){var n;return(n=this.persistence)==null?void 0:n.props[e]}getSessionProperty(e){var n;return(n=this.sessionPersistence)==null?void 0:n.props[e]}toString(){var e,n=(e=this.config.name)!==null&&e!==void 0?e:Kn;return n!==Kn&&(n=Kn+"."+n),n}_isIdentified(){var e,n;return((e=this.persistence)==null?void 0:e.get_property(at))===vn||((n=this.sessionPersistence)==null?void 0:n.get_property(at))===vn}Zn(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles===ma&&!this._isIdentified()&&Kt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[Ri])&&((n=this.persistence)==null||(n=n.props)==null||!n[ns]))}zn(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Zn()||this.Gn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.Gn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}Gn(e){return this.config.person_profiles==="never"?(A.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Kn(ns,!0),!0)}En(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut();return this.config.disable_persistence||e&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!==kn)}es(){var e,n,i,r,s=this.En();return((e=this.persistence)==null?void 0:e.xi)!==s&&((i=this.persistence)==null||i.set_disabled(s)),((n=this.sessionPersistence)==null?void 0:n.xi)!==s&&((r=this.sessionPersistence)==null||r.set_disabled(s)),s&&(this.yn.clear(),this.Qn()),s}opt_in_capturing(e){var n;if(this.config.cookieless_mode!==Wt){if(this.gn()){var i,r,s,o,a;this.Yn(!0,!0),(i=this.sessionManager)==null||i.destroy(),(r=this.pageViewManager)==null||r.destroy(),this.sessionManager=new iu(this),this.pageViewManager=new Gc(this),this.persistence&&(this.sessionPropsManager=new nu(this,this.sessionManager,this.persistence));var l,u=(s=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&s!==void 0?s:(a=Ze.__defaultExtensionClasses)==null?void 0:a.sessionRecording;u&&(this.sessionRecording=this.pn(this.sessionRecording,new u(this)),this.hn&&((l=this.sessionRecording)==null||l.onRemoteConfig==null||l.onRemoteConfig(this.hn)))}var c,d;this.consent.optInOut(!0),this.es(),this.Bn(),(n=this.sessionRecording)==null||n.startIfEnabledOrStop(),this.config.cookieless_mode==kn&&((c=this.surveys)==null||c.loadIfEnabled()),(C(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((d=e?.captureEventName)!==null&&d!==void 0?d:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hn()}else A.warn(ou)}opt_out_capturing(){var e,n,i;this.config.cookieless_mode!==Wt?(this.config.cookieless_mode===kn&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===kn&&(this.register({distinct_id:_r,$device_id:null}),(e=this.sessionRecording)==null||e.stopRecording(),this.sessionRecording=void 0,(n=this.sessionManager)==null||n.destroy(),(i=this.pageViewManager)==null||i.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.Hn(),this.Bn())):A.warn(ou)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===Wt||(this.config.cookieless_mode===kn?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return He?zf(He,this.config.custom_blocked_useragents):void 0}Hn(){P&&(P.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(Gn,{title:P.title},{send_instantly:!0}),this.kn&&(P.removeEventListener(is,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),ve(P,is,this.kn)))}debug(e){e===!1?(w?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(w?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}Qi(){var e=this.Mn||{};return"advanced_disable_flags"in e?!!e.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(A.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(function(n,i,r,s,o){var a=i in n&&!H(n[i]),l=r in n&&!H(n[r]);return a?n[i]:!!l&&(o&&o.warn("Config field '"+r+"' is deprecated. Please use '"+i+"' instead. The old field will be removed in a future major version."),n[r])})(e,"advanced_disable_flags","advanced_disable_decide",0,A)}Pt(e){var n;if(H(this.config.before_send))return e;var i=Object.keys((n=e.properties)!==null&&n!==void 0?n:{}).filter(qp),r=U(this.config.before_send)?this.config.before_send:[this.config.before_send],s=e;for(var o of r){if(s=o(s),H(s)){var a="Event '"+e.event+"' was rejected in beforeSend function";return zp(e.event)?A.warn(a+". This can cause unexpected behavior."):A.info(a),null}s.properties&&!Kt(s.properties)||A.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}for(var l of i)if(s.properties&&H(s.properties[l]))return A.warn("Event '"+e.event+"' had its '"+l+"' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped."),null;return s}getPageViewId(){var e;return(e=this.pageViewManager.ui)==null?void 0:e.pageViewId}captureTraceFeedback(e,n){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:n})}captureTraceMetric(e,n,i){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:n,$ai_metric_value:String(i)})}Cn(e){var n=mt(e)&&!e,i=le.N()&&le.P("ph_debug")==="true";return!n&&(!!i||e)}}Ze.__defaultExtensionClasses={},Ze.rs=(()=>{var t=()=>{};return{trace:t,debug:t,info:t,warn:t,error:t,fatal:t}})(),(function(t,e){for(var n=0;e.length>n;n++)t.prototype[e[n]]=$g(t.prototype[e[n]])})(Ze,["identify"]);class cu{constructor(e){this.disabled=e===!1;var n=he(e)?e:{};this.thresholdPx=n.threshold_px||30,this.timeoutMs=n.timeout_ms||1e3,this.clickCount=n.click_count||3,this.clicks=[]}isRageClick(e,n,i){if(this.disabled)return!1;var r=this.clicks[this.clicks.length-1];if(r&&Math.abs(e-r.x)+Math.abs(n-r.y)i-r.timestamp){if(this.clicks.push({x:e,y:n,timestamp:i}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:n,timestamp:i}];return!1}}var Lo="$copy_autocapture",No=pe("[AutoCapture]");function Oo(t,e){return e.length>t?e.slice(0,t)+"...":e}function Om(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!hn(e));return e}function Bm(t,e){var n,i,r=e.e,s=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!hn(t))return{props:{}};for(var c=[t],d=new Set([t]),h=t;h.parentNode&&!et(h,"body")&&pf>c.length;)if(hf(h.parentNode)){var f=h.parentNode.host;if(d.has(f))break;d.add(f),c.push(f),h=f}else{if(!hn(h.parentNode)||d.has(h.parentNode))break;d.add(h.parentNode),c.push(h.parentNode),h=h.parentNode}var p,g,m=[],v={},E=!1,S=!1;if(ie(c,(x=>{var F=ya(x);if(et(x,"a")){var $=x.getAttribute("href");E=!!(F&&$&&Hi($))&&(u?fn($):$)}j(os(x),"ph-no-capture")&&(S=!0),m.push((function(L,N,K,V,M){M===void 0&&(M=!1);var R=L.tagName.toLowerCase(),Z={tag_name:R};hl.indexOf(R)>-1&&!K&&(Z.$el_text=R.toLowerCase()==="a"||R.toLowerCase()==="button"?Oo(1024,zc(L)):Oo(1024,Zi(L)));var Ce=os(L);Ce.length>0&&(Z.classes=Ce.filter((function(ae){return ae!==""}))),ie(L.attributes,(function(ae){var Ie;if((!yf(L)||["name","id","class","aria-label"].indexOf(ae.name)!==-1)&&(V==null||!V.includes(ae.name))&&!N&&Hi(ae.value)&&(!X(Ie=ae.name)||Ie.substring(0,10)!=="_ngcontent"&&Ie.substring(0,7)!=="_nghost")){var Se=ae.value;ae.name==="class"&&(Se=fl(Se).join(" ")),Z["attr__"+ae.name]=Oo(1024,ae.name==="href"&&M?fn(Se):Se)}}));for(var oe=1,ye=1,$e=L;$e=Om($e);)oe++,$e.tagName===L.tagName&&ye++;return Z.nth_child=oe,Z.nth_of_type=ye,Z})(x,s,o,a,u));var O=(function(L){if(!ya(L))return{};var N={};return ie(L.attributes,(function(K){if(K.name&&K.name.indexOf("data-ph-capture-attribute")===0){var V=K.name.replace("data-ph-capture-attribute-",""),M=K.value;V&&M&&Hi(M)&&(N[V]=M)}})),N})(x);fe(v,O)})),S)return{props:{},explicitNoCapture:S};if(o||(m[0].$el_text=et(t,"a")||et(t,"button")?zc(t):Zi(t)),E){var _,b;m[0].attr__href=E;var k=(_=as(E))==null?void 0:_.host,T=w==null||(b=w.location)==null?void 0:b.host;k&&T&&k!==T&&(p=E)}return{props:fe({$event_type:r.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(x){return x.map((F=>{var $,O,L="";if(F.tag_name&&(L+=F.tag_name),F.attr_class)for(var N of(F.attr_class.sort(),F.attr_class))L+="."+N.replace(/"/g,"");var K=I({},F.text?{text:F.text}:{},{"nth-child":($=F.nth_child)!==null&&$!==void 0?$:0,"nth-of-type":(O=F.nth_of_type)!==null&&O!==void 0?O:0},F.href?{href:F.href}:{},F.attr_id?{attr_id:F.attr_id}:{},F.attributes),V={};return Lr(K).sort(((M,R)=>M[0].localeCompare(R[0]))).forEach((M=>{var R=M[1];return V[qc(M[0].toString())]=qc(R.toString())})),(L+=":")+Lr(V).map((M=>M[0]+'="'+M[1]+'"')).join("")})).join(";")})((function(x){return x.map((F=>{var $,O,L={text:($=F.$el_text)==null?void 0:$.slice(0,400),tag_name:F.tag_name,href:(O=F.attr__href)==null?void 0:O.slice(0,2048),attr_class:Xg(F),attr_id:F.attr__id,nth_child:F.nth_child,nth_of_type:F.nth_of_type,attributes:{}};return Lr(F).filter((N=>N[0].indexOf("attr__")===0)).forEach((N=>L.attributes[N[0]]=N[1])),L}))})(g)))},(n=m[0])!=null&&n.$el_text?{$el_text:(i=m[0])==null?void 0:i.$el_text}:{},p&&r.type==="click"?{$external_click_url:p}:{},v)}}var ki=pe("[ExceptionAutocapture]"),uu=()=>{},Dm=pe("[TracingHeaders]"),wn=pe("[Web Vitals]"),du=9e5,fu="disabled",hu="lazy_loading",Ci="awaiting_config",Ir="missing_config";pe("[SessionRecording]"),pe("[SessionRecording]");var Ca="[SessionRecording]",Bt=pe(Ca),jm=pe("[Heatmaps]");function Bo(t){return he(t)&&"clientX"in t&&"clientY"in t&&ke(t.clientX)&&ke(t.clientY)}var kr=pe("[Product Tours]"),Do=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(ll))},Um=["$set_once","$set"],Et=pe("[SiteApps]"),pu="Error while initializing PostHog app with config id ";function qn(t,e,n){if(H(t))return!1;switch(n){case"exact":return t===e;case"contains":var i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(i,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}class Hm{constructor(e){this.ns=new vl,this.ss=(n,i)=>this.os(n,i)&&this.ls(n,i)&&this.us(n,i)&&this.hs(n,i),this.os=(n,i)=>i==null||!i.event||n?.event===i?.event,this._instance=e,this.ds=new Set,this.vs=new Set}init(){var e,n;C((e=this._instance)==null?void 0:e._addCaptureHook)||(n=this._instance)==null||n._addCaptureHook(((i,r)=>{this.on(i,r)}))}register(e){var n,i;if(!C((n=this._instance)==null?void 0:n._addCaptureHook)&&(e.forEach((o=>{var a,l;(a=this.vs)==null||a.add(o),(l=o.steps)==null||l.forEach((u=>{var c;(c=this.ds)==null||c.add(u?.event||"")}))})),(i=this._instance)!=null&&i.autocapture)){var r,s=new Set;e.forEach((o=>{var a;(a=o.steps)==null||a.forEach((l=>{l!=null&&l.selector&&s.add(l?.selector)}))})),(r=this._instance)==null||r.autocapture.setElementSelectors(s)}}on(e,n){var i;n!=null&&e.length!=0&&(this.ds.has(e)||this.ds.has(n.event))&&this.vs&&((i=this.vs)==null?void 0:i.size)>0&&this.vs.forEach((r=>{this.cs(n,r)&&this.ns.emit("actionCaptured",r.name)}))}fs(e){this.onAction("actionCaptured",(n=>e(n)))}cs(e,n){if(n?.steps==null)return!1;for(var i of n.steps)if(this.ss(e,i))return!0;return!1}onAction(e,n){return this.ns.on(e,n)}ls(e,n){if(n!=null&&n.url){var i,r=e==null||(i=e.properties)==null?void 0:i.$current_url;if(!r||typeof r!="string"||!qn(r,n.url,n.url_matching||"contains"))return!1}return!0}us(e,n){return!!this.ps(e,n)&&!!this.gs(e,n)&&!!this.ys(e,n)}ps(e,n){var i;if(n==null||!n.href)return!0;var r=this.bs(e);if(r.length>0)return r.some((a=>qn(a.href,n.href,n.href_matching||"exact")));var s,o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!o&&qn((s=o.match(/(?::|")href="(.*?)"/))?s[1]:"",n.href,n.href_matching||"exact")}gs(e,n){var i;if(n==null||!n.text)return!0;var r=this.bs(e);if(r.length>0)return r.some((u=>qn(u.text,n.text,n.text_matching||"exact")||qn(u.$el_text,n.text,n.text_matching||"exact")));var s,o,a,l=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!l&&(s=(function(u){for(var c,d=[],h=/(?::|")text="(.*?)"/g;!H(c=h.exec(u));)d.includes(c[1])||d.push(c[1]);return d})(l),o=n.text,a=n.text_matching||"exact",s.some((u=>qn(u,o,a))))}ys(e,n){var i,r;if(n==null||!n.selector)return!0;var s=e==null||(i=e.properties)==null?void 0:i.$element_selectors;if(s!=null&&s.includes(n.selector))return!0;var o=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";if(n.selector_regex&&o)try{return new RegExp(n.selector_regex).test(o)}catch{return!1}return!1}bs(e){var n;return(e==null||(n=e.properties)==null?void 0:n.$elements)==null?[]:e?.properties.$elements}hs(e,n){return n==null||!n.properties||n.properties.length===0||Gf(n.properties.reduce(((i,r)=>{var s=U(r.value)?r.value.map(String):r.value!=null?[String(r.value)]:[];return i[r.key]={values:s,operator:r.operator||"exact"},i}),{}),e?.properties)}}class Wm{constructor(e){var n;this._s=[],this._instance=e,this.ws=new Map,this.ks=new Map,this.xs=new Map,(n=this._instance)==null||n.onSessionId==null||n.onSessionId((i=>this.Ss(i)))}Cs(e){return!1}Ms(){return null}Ts(e){}Es(){}Is(e,n){return!!e&&Gf(e.propertyFilters,n?.properties)}Ps(e,n){var i=new Map;return e.forEach((r=>{var s;(s=r.conditions)==null||(s=s[n])==null||(s=s.values)==null||s.forEach((o=>{if(o!=null&&o.name){var a=i.get(o.name)||[];a.push(r.id),i.set(o.name,a)}}))})),i}Rs(e,n,i){var r=(i===bi.Activation?this.ws:this.ks).get(e),s=[];return this.As((o=>{s=o.filter((a=>r?.includes(a.id)))})),s.filter((o=>{var a,l=(a=o.conditions)==null||(a=a[i])==null||(a=a.values)==null?void 0:a.find((u=>u.name===e));return this.Is(l,n)}))}register(e){var n;C((n=this._instance)==null?void 0:n._addCaptureHook)||(this.Fs(e),this.Ls(e))}Ls(e){var n=e.filter((i=>{var r,s;return((r=i.conditions)==null?void 0:r.actions)&&((s=i.conditions)==null||(s=s.actions)==null||(s=s.values)==null?void 0:s.length)>0}));n.length!==0&&(this.Os==null&&(this.Os=new Hm(this._instance),this.Os.init(),this.Os.fs((i=>{this.onAction(i)}))),n.forEach((i=>{var r,s,o,a,l;i.conditions&&(r=i.conditions)!=null&&r.actions&&(s=i.conditions)!=null&&(s=s.actions)!=null&&s.values&&((o=i.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.Os)==null||a.register(i.conditions.actions.values),(l=i.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var c=this.xs.get(u.name);c&&c.push(i.id),this.xs.set(u.name,c||[i.id])}})))})))}Fs(e){var n,i=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.events)&&((a=s.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0})),r=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.cancelEvents)&&((a=s.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0}));i.length===0&&r.length===0||((n=this._instance)==null||n._addCaptureHook(((s,o)=>{this.onEvent(s,o)})),this.ws=this.Ps(e,bi.Activation),this.ks=this.Ps(e,bi.Cancellation))}onEvent(e,n){var i,r,s=this.Ds(),o=(n==null||(i=n.properties)==null?void 0:i.$survey_id)||(n==null||(r=n.properties)==null?void 0:r.$product_tour_id);if(o&&this.getActivatedIds().includes(o)){var a=this.$s(e,o);if(a==="consume")return s.info("event consumed activated item, removing it",{event:e,itemId:o}),void this.Ns([o]);if(a==="persist")return s.info("shown item promoted to persisted activation",{event:e,itemId:o}),this.qs(o),void this.js([o])}if(this.ks.has(e)){var l=this.Rs(e,n,bi.Cancellation);l.length>0&&(s.info("cancel event matched, cancelling items",{event:e,itemsToCancel:l.map((c=>c.id))}),this.Ns(l.map((c=>c.id))),l.forEach((c=>this.Bs(c.id))))}if(this.ws.has(e)){s.info("event name matched",{event:e,eventPayload:n,items:this.ws.get(e)});var u=this.Rs(e,n,bi.Activation);this.Hs(u.map((c=>c.id)))}}onAction(e){this.xs.has(e)&&this.Hs(this.xs.get(e)||[])}Hs(e){var n;if(e.length!==0){var i=!((n=this._instance)==null||n.get_session_id==null||!n.get_session_id()),r=[];for(var s of e)i&&this.Cs(s)?this.qs(s)&&this.Us(s):r.push(s);r.length>0&&(this._s=[...new Set([...this._s,...r])]),this.Ds().info("updating activated items",{activatedItems:this.getActivatedIds()})}}qs(e){this._s=this._s.filter((i=>i!==e));var n=this.zs();return!n.includes(e)&&(this.Ws([...n,e]),this.Vs(),!0)}Ns(e){var n=new Set(e);this._s=this._s.filter((s=>!n.has(s)));var i=this.Zs(),r=i.filter((s=>!n.has(s)));r.length!==i.length&&(this.Ws(r),r.length===0&&this.Gs()),this.js(e)}Qs(){var e,n=this.Ms();if(!n)return{};var i=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n];return i&&typeof i=="object"?i:{}}Us(e){if(this.Ms()){var n=this.Qs();this.Ts(I({},n,{[e]:Date.now()}))}}js(e){if(this.Ms()){var n=this.Qs(),i={},r=!1;for(var s of Object.entries(n)){var o=s[0],a=s[1];e.includes(o)?r=!0:i[o]=a}r&&(Kt(i)?this.Es():this.Ts(i))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var n=this.Qs()[e];return ke(n)?n:void 0}}Zs(){var e,n=this.Js();return((e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n])||[]}zs(){var e,n,i=this.Zs();if(i.length===0)return[];var r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[this.Ys()],s=(n=this._instance)==null||n.get_session_id==null?void 0:n.get_session_id();return s&&r===s?i:[]}Vs(){var e,n=(e=this._instance)==null||e.get_session_id==null?void 0:e.get_session_id();n&&this.Xs(n)}Gs(){this.ta()}Ss(e){var n,i=(n=this._instance)==null||(n=n.persistence)==null?void 0:n.props[this.Ys()];if(i&&i!==e){var r=this.Zs(),s=this.Qs();r.length>0&&(this.Ws([]),r.filter((o=>ke(s[o]))).forEach((o=>this.Bs(o)))),this.Gs(),this.Ks()}}getActivatedIds(){return[...new Set([...this.zs(),...this._s])].filter((e=>!this.ea(e)))}reset(){this._s=[],this.Zs().length>0&&this.Ws([]),this.Gs(),this.Ks()}getEventToItemsMap(){return this.ws}ia(){return this.Os}}class zm extends Wm{constructor(e){super(e)}Js(){return da}Ys(){return Tr}Ms(){return $r}Ts(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[$r]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister($r)}Cs(e){var n,i;this.As((s=>{i=s.find((o=>o.id===e))}));var r=(n=i)==null||(n=n.appearance)==null?void 0:n.surveyPopupDelaySeconds;return ke(r)&&r>0}ra(){return qt.SHOWN}As(e){var n;(n=this._instance)==null||n.getSurveys(e)}Bs(e){var n;(n=this._instance)==null||n.cancelPendingSurvey(e)}Ds(){return Q}Ws(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[da]:e})}Xs(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Tr]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Tr)}ea(){return!1}$s(e,n){var i;this.As((s=>{i=s.find((o=>o.id===n))}));var r=!i||(function(s){var o;return Kf(s)&&!((o=s.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||s.schedule==="always"})(i);return r?e===qt.SHOWN?"consume":"ignore":e===qt.SHOWN?"persist":e===qt.DISMISSED||e===qt.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var Cr="SDK is not enabled or survey functionality is not yet loaded",gu="Disabled. Not loading surveys.",qm=w!=null&&w.location?ls(w.location.hash,"__posthog")||ls(location.hash,"state"):null,mu="_postHogToolbarParams",vu=pe("[Toolbar]"),_u=pe("[FeatureFlags]");class Vm{constructor(e,n){n===void 0&&(n=!1),this.na=!1,this.update(e,n)}update(e,n){this.sa=((i,r)=>{var s,o,a,l;return{bootstrap:{featureFlags:(s=i.bootstrap)==null?void 0:s.featureFlags,featureFlagPayloads:(o=i.bootstrap)==null?void 0:o.featureFlagPayloads},remoteRequestsDisabled:r,featureFlagsDisabled:!!i.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!i.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!i.advanced_feature_flags_dedup_per_session,cacheTtlMs:i.feature_flag_cache_ttl_ms,requestTimeoutMs:i.feature_flag_request_timeout_ms,compression:i.disable_compression?"none":"base64",evaluationContexts:(a=(l=i.evaluation_contexts)!==null&&l!==void 0?l:i.evaluation_environments)!==null&&a!==void 0?a:[],flagKeys:U(i.flag_keys)?i.flag_keys:void 0}})(e,n),!e.evaluation_environments||e.evaluation_contexts||this.na||(_u.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.na=!0),C(e.flag_keys)||U(e.flag_keys)||_u.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var yu=pe("[FeatureFlags]"),bn=pe("[FeatureFlags]",{debugEnabled:!0}),jo=`" failed. Feature flags didn't load in time.`,wu="connection_error",bu=t=>{for(var e={},n=0;t.length>n;n++)e[t[n]]=!0;return e},Eu=t=>{var e={};for(var n of Lr(t||{})){var i=n[1];i&&(e[n[0]]=i)}return e},St=pe("[Error tracking]"),Su="Refusing to render web experiment since the viewer is a likely bot",Gm={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>ds(e,t),not_regex:(t,e)=>!ds(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class Me{get Ne(){return this._instance.config}constructor(e){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(i){i===void 0&&(i=!1),n.getWebExperiments((r=>{Me.aa("retrieved web experiments from the server"),n.oa=new Map,r.forEach((s=>{if(s.feature_flag_key){var o;n.oa&&(Me.aa("setting flag key ",s.feature_flag_key," to web experiment ",s),(o=n.oa)==null||o.set(s.feature_flag_key,s));var a=n._instance.getFeatureFlag(s.feature_flag_key);X(a)&&s.variants[a]&&n.la(s.name,a,s.variants[a].transforms)}else if(s.variants)for(var l in s.variants){var u=s.variants[l];Me.ua(u,n._instance)&&n.la(s.name,l,u.transforms)}}))}),i)},this._instance=e,this._instance.onFeatureFlags((i=>{this.onFeatureFlags(i)}))}initialize(){}onFeatureFlags(e){if(this._is_bot())Me.aa(Su);else if(!this.Ne.disable_web_experiments){if(H(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();Me.aa("applying feature flags",e),e.forEach((n=>{var i;if(this.oa&&(i=this.oa)!=null&&i.has(n)){var r,s=this._instance.getFeatureFlag(n),o=(r=this.oa)==null?void 0:r.get(n);s&&o!=null&&o.variants[s]&&this.la(o.name,s,o.variants[s].transforms)}}))}}previewWebExperiment(){var e=Me.getWindowLocation();if(e!=null&&e.search){var n=ri(e?.search,"__experiment_id"),i=ri(e?.search,"__experiment_variant");n&&i&&(Me.aa("previewing web experiments "+n+" && "+i),this.getWebExperiments((r=>{this.ha(parseInt(n),i,r)}),!1,!0))}}loadIfEnabled(){this.Ne.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,n,i){if(this.Ne.disable_web_experiments&&!i)return e([]);var r=this._instance.get_property("$web_experiments");if(r&&!n)return e(r);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this.Ne.token),method:"GET",timestampMode:"query",callback:s=>e(s.statusCode===200&&s.json&&s.json.experiments||[])})}ha(e,n,i){var r=i.filter((s=>s.id===e));r&&r.length>0&&(Me.aa("Previewing web experiment ["+r[0].name+"] with variant ["+n+"]"),this.la(r[0].name,n,r[0].variants[n].transforms))}static ua(e,n){return!H(e.conditions)&&Me.da(e,n)&&Me.va(e)}static da(e,n){var i;if(H(e.conditions)||H((i=e.conditions)==null?void 0:i.url))return!0;var r=Me.getWindowLocation();if(r){var s,o,a,l=uf(n,r.href);return(s=e.conditions)==null||!s.url||Gm[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return w?.location}static va(e){var n;if(H(e.conditions)||H((n=e.conditions)==null?void 0:n.utm))return!0;var i=If();if(i.utm_source){var r,s,o,a,l,u,c,d,h=(r=e.conditions)==null||(r=r.utm)==null||!r.utm_campaign||((s=e.conditions)==null||(s=s.utm)==null?void 0:s.utm_campaign)==i.utm_campaign,f=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==i.utm_source,p=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==i.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==i.utm_term;return h&&p&&g&&f}return!1}static aa(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;n>r;r++)i[r-1]=arguments[r];A.info("[WebExperiments] "+e,i)}la(e,n,i){this._is_bot()?Me.aa(Su):n!=="control"?i.forEach((r=>{if(r.selector){var s;Me.aa("applying transform of variant "+n+" for experiment "+e+" ",r);var o=(s=document)==null?void 0:s.querySelectorAll(r.selector);o?.forEach((a=>{var l=a;r.html&&(l.innerHTML=r.html),r.css&&l.setAttribute("style",r.css)}))}})):Me.aa("Control variants leave the page unmodified.")}_is_bot(){return He&&this._instance?zf(He,this.Ne.custom_blocked_useragents):void 0}}var ot=pe("[Conversations]"),En="Conversations not available yet.",xu="console",Qf="__posthogHandledLogsRequestError",Uo=(t,e)=>{var n=t instanceof Error?t:new Error(e);return n[Qf]=!0,n},Iu=t=>!!t&&typeof t=="object"&&t[Qf]===!0,Ps={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=yu,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 Vm(t.config,t.Qi()),this.Ta=this.Ea)}updateConfig(t,e){var n;(n=this.Ea)==null||n.update(t,e)}setup(t){return this.Ia=t,this.rt=t.logger.createLogger("[FeatureFlags]"),n=()=>{this.Ia===t&&(this.Ia=void 0,this.nn=t,this.Pa(t))},(e=t.kv.initialize())!=null&&e.then?e.then(n):n();var e,n}Pa(t){if(this.nn===t)return w&&ve(w,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){w?.removeEventListener("online",this.Ca)}dispose(){var t;this.ba++,this.wa=!1,this.Ia=void 0,this.nn&&(this.La(),(t=this.Ra)==null||t.dispose(),this.Ra=void 0,this.ga=[],w?.removeEventListener("online",this.Ca),this.nn=void 0)}get Ne(){return this.Ta.get()}Oa(t){var e;return(e=this.nn)==null?void 0:e.kv.get(t)}F(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.set(t)}))}q(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.remove(t)}))}Da(t){try{t()}catch(e){this.rt.error("Failed to update feature flag persistence",e)}}Fa(){var t={};for(var e of[$i,Mi,Rr,It]){var n=this.Oa(e);C(n)||(t[e]=n)}this.fa=t;var i=I({},t),r=this.Oa(Sn);if(r)for(var s of Object.entries(r))i["$feature/"+s[0]]=s[1];this.pa=i}Aa(){var t=this.Ne.cacheTtlMs;if(!t||0>=t)return!1;var e=this.Oa(Ui);return typeof e!="number"||Date.now()-e>t}$a(){return!!this.Aa()&&(this.xa||this.ya||(this.xa=!0,this.rt.warn("Feature flag cache is stale, triggering refresh..."),this.reloadFeatureFlags()),!0)}Na(){var t=this.Ne.evaluationContexts;return t!=null&&t.length?t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid evaluation context found:",e,"Expected non-empty string"),n})):[]}qa(){var t=this.Ne.flagKeys;if(!C(t))return t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid flag key found:",e,"Expected non-empty string"),n}))}initialize(){var t,e,n=this.Ne,i=(t=(e=n.bootstrap)==null?void 0:e.featureFlags)!==null&&t!==void 0?t:{};if(Object.keys(i).length){var r,s,o=(r=(s=n.bootstrap)==null?void 0:s.featureFlagPayloads)!==null&&r!==void 0?r:{},a=Object.keys(i).filter((u=>!!i[u])).reduce(((u,c)=>(u[c]=i[c]||!1,u)),{}),l=Object.keys(o).filter((u=>a[u])).reduce(((u,c)=>(o[c]&&(u[c]=o[c]),u)),{});return this.ja({featureFlags:a,featureFlagPayloads:l})}}updateFlags(t,e,n){var i,r,s=n!=null&&n.merge&&(i=this.Oa(Sn))!==null&&i!==void 0?i:{},o=n!=null&&n.merge&&(r=this.Oa(Mi))!==null&&r!==void 0?r:{},a=I({},s,t),l=I({},o,e),u={};for(var c of Object.entries(a)){var d=c[0],h=c[1];u[d]={key:d,enabled:vc(h),variant:_c(h),reason:void 0,metadata:C(l?.[d])?void 0:{id:0,version:void 0,description:void 0,payload:l[d]}}}this.ja({flags:u})}get hasLoadedFlags(){return this.ma}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var t=this.Oa(ca),e=this.Oa(It),n=this.Oa(xn);if(!n&&!e)return t||{};var i=fe({},t||{}),r=[...new Set([...Object.keys(n||{}),...Object.keys(e||{})])];for(var s of r){var o,a,l=i[s],u=e?.[s],c=C(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=C(u)?l?.variant:typeof u=="string"?u:void 0,h=n?.[s],f=I({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(f.original_enabled=l?.enabled),d!==l?.variant&&(f.original_variant=l?.variant),h&&(f.metadata=I({},l?.metadata,{payload:h,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),i[s]=f}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:n,finalDetails:i}),this.ca=!0),i}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((n=>{var i=t[n];return{key:n,enabled:vc(i),variant:_c(i),payload:mc(e[n])}}))}getFlagVariants(){var t=this.Oa(Sn),e=this.Oa(It);if(!e)return t||{};for(var n=fe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:e,finalFlags:n}),this.ca=!0),n}getFlagPayloads(){var t=this.Oa(Mi),e=this.Oa(xn);if(!e)return t||{};for(var n=fe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flag payloads!",{flagPayloads:t,overriddenPayloads:e,finalPayloads:n}),this.ca=!0),n}reloadFeatureFlags(){this._a||this.Ne.featureFlagsDisabled||this.Ma()||this.Ba||(this.ga.slice().forEach((t=>{try{t()}catch(e){this.rt.error("Error while running feature flags reloading callback",e)}})),this.Ba=setTimeout((()=>{this.Ha()}),5))}La(){clearTimeout(this.Ba),this.Ba=void 0}onReloading(t){return this.ga.push(t),()=>{this.ga=this.ga.filter((e=>e!==t))}}ensureFlagsLoaded(){this.ma||this.ya||this.Ba||this.reloadFeatureFlags()}setAnonymousDistinctId(t){this.$anon_distinct_id=t}setReloadingPaused(t){this._a=t}resetFlagCallReported(){this.q(Cn)}Ha(t){this.La();var e=this.nn;if(e&&!this.Ne.remoteRequestsDisabled&&!this.Ma())if(this.ya)this.wa=!0;else{var n={token:e.projectToken,distinct_id:e.distinctId,groups:e.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:I({},e.initialPersonProperties,this.Oa(jt)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(In),timezone:Rf()};C(e.deviceId)||(n.$device_id=e.deviceId),(t!=null&&t.disableFlags||this.Ne.featureFlagsDisabled)&&(n.disable_flags=!0);var i=this.Na();i.length&&(n.evaluation_contexts=i);var r=this.qa();C(r)||(n.flag_keys=r);var s=this.Ne.onlyEvaluateSurveyFeatureFlags,o="/flags/?v=2"+(s?"&only_evaluate_survey_feature_flags=true":""),a=this.ba;this.ya=!0;var l=()=>{this.wa&&(this.wa=!1,this.Ha())},u=c=>{this.ya=!1,a===this.ba&&(this.F({[Mr]:[wu]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:n,compression:this.Ne.compression==="base64"?Ue.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,h,f=(d=c.json)!==null&&d!==void 0?d:{},p=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),p||this.wa||(this.$anon_distinct_id=void 0),!n.disable_flags||this.wa){this.ka=!p;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?wu:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),f.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((h=f.quotaLimited)==null||!h.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[Mr]:g}),m?this.rt.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more."):n.disable_flags||this.ja(f,p,{partialResponse:s}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return Sf(this.Sa,3)}Ua(t){this.Sa=xf(t,this.Sa,3,(()=>this.rt.warn("Feature flag requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped refreshing feature flags; will try again when connectivity changes.")))}getFeatureFlag(t,e){var n;if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var i=this.getFeatureFlagResult(t,e);return(n=i?.variant)!==null&&n!==void 0?n:i?.enabled}}else this.rt.warn('getFeatureFlag for key "'+t+jo)}getFeatureFlagDetails(t){return this.getFlagsWithDetails()[t]}getFeatureFlagPayload(t){var e=this.getFeatureFlagResult(t,{send_event:!1});return e?.payload}getFeatureFlagResult(t,e){if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var n,i=this.getFlagVariants(),r=t in i,s=i[t],o=this.getFlagPayloads()[t],a=String(s),l=this.Oa(Rr)||void 0,u=this.Oa(Ui)||void 0,c=this.Oa(Cn)||{};if(this.Ne.deduplicateCallsPerSession){var d,h=(d=this.nn)==null?void 0:d.session.sessionId,f=this.Oa(Ni);h&&h!==f&&(c={},n=h)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))n&&this.F({[Cn]:c,[Ni]:n});else{var p,g,m,v,E,S,_,b,k,T;U(c[t])?c[t].push(a):c[t]=[a],this.F(I({[Cn]:c},n?{[Ni]:n}:{}));var x=this.getFeatureFlagDetails(t),F=[...(p=this.Oa(Mr))!==null&&p!==void 0?p:[]];C(s)&&F.push("flag_missing");var $={$feature_flag:t,$feature_flag_response:s,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((g=this.Ne.bootstrap)==null||(g=g.featureFlags)==null?void 0:g[t])||null,$feature_flag_bootstrapped_payload:((m=this.Ne.bootstrap)==null||(m=m.featureFlagPayloads)==null?void 0:m[t])||null,$used_bootstrap_value:!this.ka};C(x==null||(v=x.metadata)==null?void 0:v.has_experiment)||($.$feature_flag_has_experiment=x.metadata.has_experiment),C(x==null||(E=x.metadata)==null?void 0:E.version)||($.$feature_flag_version=x.metadata.version);var O,L=(S=x==null||(_=x.reason)==null?void 0:_.description)!==null&&S!==void 0?S:x==null||(b=x.reason)==null?void 0:b.code;L&&($.$feature_flag_reason=L),x!=null&&(k=x.metadata)!=null&&k.id&&($.$feature_flag_id=x.metadata.id),C(x?.original_variant)&&C(x?.original_enabled)||($.$feature_flag_original_response=C(x.original_variant)?x.original_enabled:x.original_variant),x!=null&&(T=x.metadata)!=null&&T.original_payload&&($.$feature_flag_original_payload=x==null||(O=x.metadata)==null?void 0:O.original_payload),F.length&&($.$feature_flag_error=F.join(",")),this.za($)}else n&&this.F({[Cn]:c,[Ni]:n});if(r)return{key:t,enabled:!!s,variant:typeof s=="string"?s:void 0,payload:mc(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+jo)}za(t){try{var e;(e=this.nn)==null||e.capture("$feature_flag_called",t).catch((n=>{this.rt.error("Failed to capture feature flag call",n)}))}catch(n){this.rt.error("Failed to capture feature flag call",n)}}getRemoteConfigPayload(t,e){this.Wa(t,e)}Wa(t,e){var n=this;return se((function*(){var i=n.nn;if(i){var r={distinct_id:i.distinctId,token:i.projectToken,person_properties:{$lib:i.library.name,$lib_version:i.library.version}},s=n.Na();s.length&&(r.evaluation_contexts=s);var o,a=n.qa();C(a)||(r.flag_keys=a);try{var l,u=(l=(yield i.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:r,compression:n.Ne.compression==="base64"?Ue.Base64:void 0,sentAt:"body",timeoutMs:n.Ne.requestTimeoutMs})).json)==null?void 0:l.featureFlagPayloads;o=u?.[t]||void 0}catch(c){return void n.rt.error("Remote config feature flag request failed",c)}try{e(o)}catch(c){n.rt.error("Remote config feature flag callback failed",c)}}}))()}isFeatureEnabled(t,e){if(e===void 0&&(e={}),e.fresh&&!this.ka)return e.defaultValue;if(!(this.ma||this.getFlags()&&this.getFlags().length>0))return this.rt.warn('isFeatureEnabled for key "'+t+jo),e.defaultValue;var n=this.getFeatureFlag(t,e);return C(n)?e.defaultValue:!!n}addFeatureFlagsHandler(t){this.featureFlagEventHandlers.push(t)}removeFeatureFlagsHandler(t){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((e=>e!==t))}receivedFeatureFlags(t,e,n){this.ja(t,e,n)}ja(t,e,n){if(this.nn){this.ma=!0;var i=(function(r,s,o,a,l,u){s===void 0&&(s={}),o===void 0&&(o={}),a===void 0&&(a={}),u===void 0&&(u=yu);var c=((k,T)=>{var x=k.flags;return x?I({},k,{featureFlags:Object.fromEntries(Object.keys(x).map((F=>{var $;return[F,($=x[F].variant)!==null&&$!==void 0?$:x[F].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(x).filter((F=>x[F].enabled)).filter((F=>{var $;return($=x[F].metadata)==null?void 0:$.payload})).map((F=>{var $;return[F,($=x[F].metadata)==null?void 0:$.payload]})))}):(k.featureFlags&&T.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),k)})(r,u),d=c.flags,h=c.featureFlags,f=c.featureFlagPayloads;if(h){var p=r.requestId,g=r.evaluatedAt;if(U(h)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(h)for(var v=0;h.length>v;v++)m[h[v]]=!0;return{[$i]:h,[Sn]:m,[Qr]:!1}}var E=h,S=f,_=d;if(l!=null&&l.partialResponse)E=I({},s,E),S=I({},o,S),_=I({},a,_);else if(r.errorsWhileComputingFlags)if(d){var b=new Set(Object.keys(d).filter((k=>{var T;return!((T=d[k])!=null&&T.failed)})));E=I({},s,Object.fromEntries(Object.entries(E).filter((k=>b.has(k[0]))))),S=I({},o,Object.fromEntries(Object.entries(S||{}).filter((k=>b.has(k[0]))))),_=I({},a,Object.fromEntries(Object.entries(_||{}).filter((k=>b.has(k[0])))))}else E=I({},s,E),S=I({},o,S),_=I({},a,_);return I({[$i]:Object.keys(Eu(E)),[Sn]:E||{},[Mi]:S||{},[ca]:_||{},[Qr]:r.minimalFlagCalledEvents===!0},p?{[Rr]:p}:{},g?{[Ui]:g}:{})}})(t,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),n,this.rt);i&&this.F(i),e||(this.xa=!1),this.Va(e)}}override(t,e){e===void 0&&(e=!1),this.rt.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:t,suppressWarning:e})}overrideFeatureFlags(t){this.Za(t)}Za(t){if(this.nn){if(t===!1)return this.q([It,xn]),this.Va(),void bn.info("All overrides cleared");if(U(t))return this.F({[It]:bu(t)}),this.Va(),void bn.info("Flag overrides set",{flags:t});if(t&&typeof t=="object"&&("flags"in t||"payloads"in t)){var e,n=t;this.ca=!!((e=n.suppressWarning)!==null&&e!==void 0&&e);var i={},r=n.flags,s=n.payloads;return r&&(i[It]=U(r)?bu(r):r),s&&(i[xn]=s),Object.keys(i).length&&this.F(i),r===!1&&s===!1?this.q([It,xn]):r===!1?this.q(It):s===!1&&this.q(xn),this.Va(),r===!1?bn.info("Flag overrides cleared"):r&&bn.info("Flag overrides set",{flags:r}),void(s===!1?bn.info("Payload overrides cleared"):s&&bn.info("Payload overrides set",{payloads:s}))}if(t&&typeof t=="object")return this.F({[It]:t}),this.Va(),void bn.info("Flag overrides set",{flags:t});this.rt.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:t})}else this.rt.warn("posthog.featureFlags.overrideFeatureFlags called before feature flags were ready")}onFeatureFlags(t){if(this.addFeatureFlagsHandler(t),this.ma){var e=this.Ga(),n=e.flags,i=e.flagVariants;try{t(n,i)}catch(r){this.rt.error("Error while running feature flags callback",r)}}return()=>this.removeFeatureFlagsHandler(t)}updateEarlyAccessFeatureEnrollment(t,e,n){var i=(this.Oa(Fr)||[]).find((l=>l.flagKey===t)),r={["$feature_enrollment/"+t]:e},s={$feature_flag:t,$feature_enrollment:e,$set:r};i&&(s.$early_access_feature_name=i.name),n&&(s.$feature_enrollment_stage=n);var o=I({},this.getFlagVariants(),{[t]:e});this.F({[$i]:Object.keys(Eu(o)),[Sn]:o,[jt]:I({},this.Oa(jt)||{},r)}),this.Va();try{var a;(a=this.nn)==null||a.capture("$feature_enrollment_update",s).catch((l=>{this.rt.error("Failed to capture early access feature enrollment",l)}))}catch(l){this.rt.error("Failed to capture early access feature enrollment",l)}}getEarlyAccessFeatures(t,e,n){e===void 0&&(e=!1);var i=this.Oa(Fr);!i||e?this.Qa(t,n):t(i)}Qa(t,e){var n=this;return se((function*(){var i=n.nn;if(i){var r,s=e?"&"+e.map((a=>"stage="+a)).join("&"):"";try{var o=yield i.sendRequest("/api/early_access_features/?token="+i.projectToken+s,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;n.F({[Fr]:r=o.json.earlyAccessFeatures})}catch(a){return void n.rt.error("Early access feature request failed",a)}try{t(r)}catch(a){n.rt.error("Early access feature callback failed",a)}}}))()}Ga(){var t=this.getFlags(),e=this.getFlagVariants();return{flags:t.filter((n=>e[n])),flagVariants:Object.keys(e).filter((n=>e[n])).reduce(((n,i)=>(n[i]=e[i],n)),{})}}Va(t){this.Fa();var e=this.Ga(),n=e.flags,i=e.flagVariants;this.featureFlagEventHandlers.forEach((r=>{try{r(n,i,{errorsLoading:t})}catch(s){this.rt.error("Error while running feature flags callback",s)}}))}setPersonPropertiesForFlags(t,e){e===void 0&&(e=!0),this.Ka(t,e)}Ka(t,e){e===void 0&&(e=!0);var n=this.Oa(jt)||{},i=t?.$set||(t!=null&&t.$set_once?{}:t),r=t?.$set_once,s={};if(r)for(var o in r)({}).hasOwnProperty.call(r,o)&&(o in n||(s[o]=r[o]));this.F({[jt]:I({},n,s,i)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=I({},this.Oa(jt)||{});t.forEach((i=>{delete n[i]})),this.F({[jt]:n}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(jt),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=this.Oa(In)||{},i=I({},n);for(var r of Object.keys(t))i[r]=I({},n[r],t[r]);this.F({[In]:i}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(In)||{};this.F({[In]:I({},e,{[t]:{}})})}else this.q(In)}reset(){this.ba++,this.wa=!1,this.Fa(),this.ma=!1,this._a=!1,this.ka=!1,this.$anon_distinct_id=void 0,this.La(),this.ca=!1,this.Sa=0}}},Km={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===Ci||this.Ya===Ir?this.Ya:(t=(e=this.Ja)==null?void 0:e.status)!==null&&t!==void 0?t:this.Ya}constructor(t){if(this._forceAllowLocalhostNetworkCapture=!1,this.Ya=fu,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(P==null||!P.visibilityState||P.visibilityState==="visible")return!0;var n=w==null||(e=w.performance)==null||e.getEntriesByType==null?void 0:e.getEntriesByType("visibility-state");return!(n!=null&&n.length)||n.some((i=>i.name==="visible"))})(),this.Ie=()=>{var e;P?.visibilityState==="visible"&&(this.io=!0,(e=this.Ja)==null||e.setDocumentWasEverVisible==null||e.setDocumentWasEverVisible(!0))},this._instance=t,!this._instance.sessionManager)throw Bt.error("started without valid sessionManager"),new Error(Ca+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===Wt)throw new Error(Ca+' cannot be used with cookieless_mode="always"');P!=null&&P.addEventListener&&ve(P,"visibilitychange",this.Ie)}initialize(){this.startIfEnabledOrStop()}dispose(){this.eo=!0,P==null||P.removeEventListener==null||P.removeEventListener("visibilitychange",this.Ie),this.stopRecording()}get ro(){var t,e=!((t=this._instance.get_property(An))==null||!t.enabled),n=!this.Ne.disable_session_recording,i=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return w&&e&&n&&!i}startIfEnabledOrStop(t){var e;if(!(this.eo||this.ro&&(e=this.Ja)!=null&&e.isStarted)){var n=!C(Object.assign)&&!C(Array.from);this.ro&&n?(this.no(t),Bt.info("starting")):(this.Ya=fu,this.stopRecording())}}no(t){var e,n,i;this.ro&&(this.Ya!==Ci&&this.Ya!==Ir&&(this.Ya=hu),B!=null&&(e=B.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(n=B.__PosthogExtensions__)!=null&&n.initSessionRecording?this.so(t):(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,this.ao,(r=>{if(r)return Bt.error("could not load recorder",r);this.so(t)})))}stopRecording(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.stop()}oo(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.discard()}lo(){var t,e;(t=this.Mr)==null||t.unregister(cl),(e=this.Mr)==null||e.unregister(Xd)}uo(t,e){if(H(t))return null;var n,i=ke(t)?t:parseFloat(t);return typeof(n=i)!="number"||!Number.isFinite(n)||0>n||n>1?(Bt.warn(e+" must be between 0 and 1. Ignoring invalid value:",t),null):i}ho(t){if(this.Mr){var e,n,i=this.Mr,r=()=>{var s,o=t.sessionRecording===!1?void 0:t.sessionRecording,a=this.uo((s=this.Ne.session_recording)==null?void 0:s.sampleRate,"session_recording.sampleRate"),l=this.uo(o?.sampleRate,"remote config sampleRate"),u=a??l;H(u)&&this.lo();var c=o?.minimumDurationMilliseconds;i.register({[An]:I({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:I({capturePerformance:t.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:u,minimumDurationMilliseconds:C(c)?null:c,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers,version:o?.version,triggerGroups:o?.triggerGroups})})};r(),(e=this.Xa)==null||e.call(this),this.Xa=(n=this._instance.sessionManager)==null?void 0:n.onSessionId(r)}}onRemoteConfig(t){var e=t.ok?t.config:void 0;return e&&"sessionRecording"in e?e.sessionRecording===!1?(this.ho(e),void this.oo()):(this.ho(e),void this.startIfEnabledOrStop()):(this.Ya===Ci&&(this.Ya=Ir,Bt.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(t,e){var n;e===void 0&&(e="log"),(n=this.Ja)!=null&&n.log?this.Ja.log(t,e):Bt.warn("log called before recorder was ready")}get ao(){var t,e,n=(t=this._instance)==null||(t=t.persistence)==null?void 0:t.get_property(An);return(n==null||(e=n.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(An);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(n){return Bt.warn("persisted remote config for session recording is invalid and will be ignored",n),!1}return!H(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,n,i;if(!this.eo){if((e=B.__PosthogExtensions__)==null||!e.initSessionRecording)return Bt.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[af]:!0});var r;if(this.Ja||(this.Ja=(r=B.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===Ir||this.Ya===Ci?void 0:(this.Ya=Ci,Bt.info("persisted remote config is stale, requesting fresh config before starting"),void new Tf(this._instance).load());this.Ya=hu,(n=(i=this.Ja).setDocumentWasEverVisible)==null||n.call(i,this.io),this.Ja.start(t)}}onRRwebEmit(t){var e;(e=this.Ja)==null||e.onRRwebEmit==null||e.onRRwebEmit(t)}overrideLinkedFlag(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[ef]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Qd]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,n;this.Ja||(n=this.Mr)==null||n.register({[t==="url"?tf:nf]:!0}),(e=this.Ja)==null||e.overrideTrigger(t)}get sdkDebugProperties(){var t;return((t=this.Ja)==null?void 0:t.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(t,e){var n;return!((n=this.Ja)==null||!n.tryAddCustomEvent(t,e))}}},Ym={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new cu(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,n=he(this.instance.config.autocapture)?this.instance.config.autocapture:{};return n.url_allowlist=(t=n.url_allowlist)==null?void 0:t.map((i=>new RegExp(i))),n.url_ignorelist=(e=n.url_ignorelist)==null?void 0:e.map((i=>new RegExp(i))),n}yo(){if(this.isBrowserSupported()){if(w&&P){var t=n=>{n=n||w?.event;try{this.bo(n)}catch(i){No.error("Failed to capture event",i)}};if(ve(P,"submit",t,{capture:!0}),ve(P,"change",t,{capture:!0}),ve(P,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=n=>{n=n||w?.event;try{this.bo(n,Lo)}catch(i){No.error("Failed to capture copy/cut event",i)}};ve(P,"copy",e,{capture:!0}),ve(P,"cut",e,{capture:!0})}}}else No.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.vo&&(this.yo(),this.vo=!0)}onRemoteConfig(t){if(this.fo=!0,t.ok){var e=t.config;e.elementsChainAsString&&(this.po=e.elementsChainAsString);var n=e.autocapture_opt_out;mt(n)&&(this.instance.persistence&&this.instance.persistence.register({[na]:n}),this.co=n),this.startIfEnabled()}else this.startIfEnabled()}setElementSelectors(t){this.mo=t}getElementSelectors(t){var e,n=[];return(e=this.mo)==null||e.forEach((i=>{var r=P?.querySelectorAll(i);r?.forEach((s=>{t===s&&n.push(i)}))})),n}get isEnabled(){var t,e,n=(t=this.instance.persistence)==null?void 0:t.props[na],i=this.co,r=this.instance.Qi()&&!this.fo;if(Ye(i)&&!mt(n)&&!r)return!1;var s=(e=this.co)!==null&&e!==void 0?e:!!n;return!!this.instance.config.autocapture&&!s}bo(t,e){if(e===void 0&&(e="$autocapture"),this.isEnabled){var n,i=So(t);ff(i)&&(i=i.parentNode||null),e==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&this.instance.config.rageclick&&(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,t.timeStamp||new Date().getTime())&&Dc(i,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var r=e===Lo;if(i&&(function(d,h,f,p,g,m){var v;if(!w||pl(d)||f!=null&&f.url_allowlist&&!Nc(f.url_allowlist,m)||f!=null&&f.url_ignorelist&&Nc(f.url_ignorelist,m))return!1;if(f!=null&&f.dom_event_allowlist){var E=f.dom_event_allowlist;if(E&&!E.some((x=>h.type===x)))return!1}var S=_f(d,p),_=S.parentIsUsefulElement,b=S.targetElementList;if(!(function(x,F){var $=F?.element_allowlist;if(C($))return!0;var O,L=function(K){if($.some((V=>K.tagName.toLowerCase()===V)))return{v:!0}};for(var N of x)if(O=L(N))return O.v;return!1})(b,f)||!_a(b,f?.css_selector_allowlist)||_a(b,(v=f?.css_selector_ignorelist)!==null&&v!==void 0?v:Vg))return!1;try{var k=w.getComputedStyle(d);if(k&&k.getPropertyValue("cursor")==="pointer"&&h.type==="click")return!0}catch{}var T=d.tagName.toLowerCase();switch(T){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 _?(g||["click"]).indexOf(h.type)>=0:(g||["click"]).indexOf(h.type)>=0&&(hl.indexOf(T)>-1||d.getAttribute("contenteditable")==="true")}})(i,t,this.Ne,r,r?["copy","cut"]:void 0,this.instance)){var s=Bm(i,{e:t,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.Ne.element_attribute_ignorelist,elementsChainAsString:this.po,disableCaptureUrlHashes:this.instance.config.disable_capture_url_hashes}),o=s.props;if(s.explicitNoCapture)return!1;var a=this.getElementSelectors(i);if(a&&a.length>0&&(o.$element_selectors=a),e===Lo){var l,u=gf(w==null||(l=w.getSelection())==null?void 0:l.toString()),c=t.type||"clipboard";if(!u)return!1;o.$selected_content=u,o.$copy_type=c}return this.instance.capture(e,o),!0}}}isBrowserSupported(){return je(P?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(w==null||(e=w.location)==null?void 0:e.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(A.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.wo&&this.wo(),this.wo=void 0,A.info("History API monitoring stopped")}monitorHistoryChanges(){w&&w.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(w&&((e=w.history[t])==null||!e.__posthog_wrapped__)){var n=this;(function(i,r,s){try{if(!(r in i))return uu;var o={next:i[r]},a=s((function(){for(var l=arguments.length,u=new Array(l),c=0;l>c;c++)u[c]=arguments[c];return o.next.apply(this,u)}));return je(a)&&(a.prototype=a.prototype||{},Object.defineProperties(a,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:o}})),i[r]=a,()=>{if(i[r]!==a)for(var l=i[r];je(l)&&l.__posthog_layer__;){var u=l.__posthog_layer__;if(u.next===a)return void(u.next=o.next);l=u.next}else i[r]=o.next}}catch{return uu}})(w.history,t,(i=>function(r,s,o){i.call(this,r,s,o),n.So(t)}))}}So(t){try{var e,n=w==null||(e=w.location)==null?void 0:e.pathname;if(!n)return;n!==this._o&&this.isEnabled&&this._instance.capture(Gn,{navigation_type:t}),this._o=n}catch(i){A.error("Error capturing "+t+" pageview",i)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};ve(w,"popstate",t),this.wo=()=>{w&&w.removeEventListener("popstate",t)}}}},heatmaps:class{get Ne(){return this.instance.config}constructor(t){var e;this.Co=!1,this.vo=!1,this.Mo=null,this.instance=t,this.Co=!((e=this.instance.persistence)==null||!e.props[ia]),this.rageclicks=new cu(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return he(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return H(this.Ne.capture_heatmaps)?H(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;jm.info("starting..."),this.To(),this.Ie()}else{var t;clearInterval((t=this.Mo)!==null&&t!==void 0?t:void 0),this.Eo(),this.getAndClearBuffer()}}onRemoteConfig(t){if(t.ok){var e=t.config;if("heatmaps"in e){var n=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[ia]:n}),this.Co=n,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){Bo(t.originalEvent)&&this.ke(t.originalEvent,"deadclick")}Ie(){this.Mo&&clearInterval(this.Mo),this.Mo=P?.visibilityState==="visible"?setInterval(this.cr.bind(this),this.flushIntervalMilliseconds):null}To(){w&&P&&(this.Po=this.cr.bind(this),ve(w,rs,this.Po),this.Ro=t=>this.ke(t||w?.event),ve(P,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||w?.event),ve(P,"mousemove",this.Ao,{capture:!0}),this.Lo=new Vc(this.instance,Qg,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),ve(P,is,this.Oo),this.vo=!0)}Eo(){var t;w&&P&&(this.Po&&w.removeEventListener(rs,this.Po),this.Ro&&P.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&P.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&P.removeEventListener(is,this.Oo),clearTimeout(this.Do),(t=this.Lo)==null||t.stop(),this.vo=!1)}$o(t,e){var n=this.instance.scrollManager.scrollY(),i=this.instance.scrollManager.scrollX(),r=this.instance.scrollManager.scrollElement(),s=(function(o,a,l){for(var u=o;u&&hn(u)&&!et(u,"body");){if(u===l)return!1;var c=void 0;try{var d,h,f;c=(d=(h=(f=u.ownerDocument)==null?void 0:f.defaultView)!==null&&h!==void 0?h:w)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(j(a,c))return!0;u=mf(u)}return!1})(So(t),["fixed","sticky"],r);return{x:t.clientX+(s?0:i),y:t.clientY+(s?0:n),target_fixed:s,type:e}}ke(t,e){var n;if(e===void 0&&(e="click"),!Lc(t.target)&&Bo(t)){var i=this.$o(t,e);(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,new Date().getTime())&&Dc(So(t),this.instance.config.rageclick)&&this.Vt(I({},i,{type:"rageclick"})),this.Vt(i)}}Fo(t){!Lc(t.target)&&Bo(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(w){var e=this.Ne.disable_capture_url_hashes?fn(w.location.href):w.location.href,n=this.Ne.custom_personal_data_properties,i=this.Ne.mask_personal_data_properties?[...si,...n||[]]:[],r=Xi(e,i,Qi);this.R=this.R||{},this.R[r]||(this.R[r]=[]),this.R[r].push(t)}}cr(){this.R&&!Kt(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:Vc,webVitalsAutocapture:class{constructor(t){var e;this.Co=!1,this.vo=!1,this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this.No=()=>{clearTimeout(this.qo),this.qo=void 0,this.R.metrics.length!==0&&(this._instance.capture("$web_vitals",I({$current_url:this.R.url},this.R.metrics.reduce(((n,i)=>I({},n,{["$web_vitals_"+i.name+"_event"]:I({},i),["$web_vitals_"+i.name+"_value"]:i.value})),{}))),this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.jo=n=>{var i;if(this.R=this.R||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},H(n?.name)||H(n?.value))wn.error("Invalid metric received",n);else{var r=typeof n.navigationURL=="string"?n.navigationURL:void 0,s=this.Bo(r);if(!C(s)){var o=ke(n.navigationId)||typeof n.navigationId=="string"?"navigation:"+n.navigationId:"url:"+s;if(!this.Ho||this.Ho>n.value){this.R.navigationKey!==o&&(this.No(),this.qo=setTimeout(this.No,this.flushToCaptureTimeoutMs)),C(this.R.navigationKey)&&(this.R.navigationKey=o,this.R.url=s),this.R.firstMetricTimestamp=C(this.R.firstMetricTimestamp)?Date.now():this.R.firstMetricTimestamp,n.attribution&&n.attribution.interactionTargetElement&&(n.attribution.interactionTargetElement=void 0);var a=(i=this._instance.sessionManager)==null?void 0:i.checkAndGetSessionAndWindowId(!0),l=I({},n,r?{navigationURL:s}:{},{$current_url:s,timestamp:Date.now()});C(a)||(l.$session_id=a.sessionId,l.$window_id=a.windowId),this.R.metrics.push(l),this.R.metrics.length===this.allowedMetrics.length&&this.No()}else wn.error("Ignoring metric with value >= "+this.Ho,n)}}},this.Uo=()=>{if(!this.vo){var n,i,r,s,o=B.__PosthogExtensions__,a=o?.postHogWebVitalsCallbacksByFlavor,l=a?.[this.zo]||(this.zo==="web-vitals"&&C(a)?o?.postHogWebVitalsCallbacks:void 0);if(C(l)||(n=l.onLCP,i=l.onCLS,r=l.onFCP,s=l.onINP),n&&i&&r&&s){var u={reportSoftNavs:this.useSoftNavs};this.allowedMetrics.indexOf("LCP")>-1&&n(this.jo.bind(this),u),this.allowedMetrics.indexOf("CLS")>-1&&i(this.jo.bind(this),u),this.allowedMetrics.indexOf("FCP")>-1&&r(this.jo.bind(this),u),this.allowedMetrics.indexOf("INP")>-1&&s(this.jo.bind(this),u),this.vo=!0}else wn.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[aa]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,n=he(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return H(n)?((e=this._instance.persistence)==null?void 0:e.props[la])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(he(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=he(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=he(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=he(this.Wo)&&ke(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:du;return t>0&&6e4>=t?du:t}get isEnabled(){var t=me?.protocol;if(t!=="http:"&&t!=="https:")return wn.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=he(this.Wo)?this.Wo.web_vitals:mt(this.Wo)?this.Wo:void 0;return mt(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(wn.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var n=he(e.capturePerformance)&&!!e.capturePerformance.web_vitals,i=he(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[aa]:n}),this._instance.persistence.register({[la]:i})),this.Co=n,this.startIfEnabled()}}}get zo(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}ai(t){var e=B.__PosthogExtensions__,n=this.zo,i=e?.postHogWebVitalsCallbacksByFlavor;i!=null&&i[n]||n==="web-vitals"&&C(i)&&e!=null&&e.postHogWebVitalsCallbacks?t():e==null||e.loadExternalDependency==null||e.loadExternalDependency(this._instance,n,(r=>{r?wn.error("failed to load script",r):t()}))}Bo(t){var e=t||w?.location.href;if(e){var n=this._instance.config.disable_capture_url_hashes?fn(e):e,i=this._instance.config.custom_personal_data_properties,r=this._instance.config.mask_personal_data_properties?[...si,...i||[]]:[];return Xi(n,r,Qi)}wn.error("Could not determine current URL")}}},Jm={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var n;if(w&&this.isEnabled&&(n=B.__PosthogExtensions__)!=null&&n.errorWrappingFunctions){var i=B.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,r=B.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,s=B.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.Vo&&this.Ne.capture_unhandled_errors&&(this.Vo=i(this.captureException.bind(this))),!this.Zo&&this.Ne.capture_unhandled_rejections&&(this.Zo=r(this.captureException.bind(this))),!this.Go&&this.Ne.capture_console_errors&&(this.Go=s(this.captureException.bind(this)))}catch(o){ki.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[ra]),this.Jo=new Kp(I({},(function(n){var i,r,s,o;return n===void 0&&(n={}),{refillRate:(i=(r=n.exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:n.__exceptionRateLimiterRefillRate)!==null&&i!==void 0?i:1,bucketSize:(s=(o=n.exceptionRateLimiterBucketSize)!==null&&o!==void 0?o:n.__exceptionRateLimiterBucketSize)!==null&&s!==void 0?s:10}})(this._instance.config.error_tracking),{refillInterval:1e4,rt:ki})),this.Ne=this.Yo(),this.startIfEnabledOrStop()}Yo(){var t=this._instance.config.capture_exceptions,e={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return he(t)?e=I({},e,t):(C(t)?this.Ko:t)&&(e=I({},e,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),e}get isEnabled(){return this.Ne.capture_console_errors||this.Ne.capture_unhandled_errors||this.Ne.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(ki.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",(i=>{if(i)return ki.error("failed to load script",i);t()}))}Qo(){var t,e,n;(t=this.Vo)==null||t.call(this),this.Vo=void 0,(e=this.Zo)==null||e.call(this),this.Zo=void 0,(n=this.Go)==null||n.call(this),this.Go=void 0}onRemoteConfig(t){if(t.ok){var e=t.config;"autocaptureExceptions"in e&&(this.Ko=!!e.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[ra]:this.Ko}),this.Ne=this.Yo(),this.startIfEnabledOrStop())}}onConfigChange(){this.Ne=this.Yo()}captureException(t){var e,n,i,r=(e=t==null||(n=t.$exception_list)==null||(n=n[0])==null?void 0:n.type)!==null&&e!==void 0?e:"Exception";this.Jo.consumeRateLimit(r)?ki.info("Skipping exception capture because of client rate limiting.",{exception:r}):(i=this._instance.exceptions)==null||i.sendExceptionEvent(t)}},exceptions:class{constructor(t){var e,n;this.Xo=[],this.tl=new dg([new yg,new Ag,new bg,new wg,new kg,new Ig,new Sg,new Cg],(function(i){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;r>o;o++)s[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` -`),d=l;c.length>d;d++){var h=c[d];if(1024>=h.length){var f=Rc.test(h)?h.replace(Rc,"$1"):h;if(!f.match(/\S*Error: /)){for(var p of s){var g=p(f,i);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var v=Array.from(m);return v.reverse(),v.slice(0,50).map((E=>{return I({},E,{filename:E.filename||(S=v,S[S.length-1]||{}).filename,function:E.function||ii});var S}))})(u)}})("web:javascript",gg,_g)),this._instance=t,this.Xo=(e=(n=this._instance.persistence)==null?void 0:n.get_property(sa))!==null&&e!==void 0?e:[],this.el=Xr(this.il()),this.rl=new Fg(this.el)}onConfigChange(){this.el=Xr(this.il()),this.rl.setConfig(this.el)}onRemoteConfig(t){var e,n,i;if(t.ok){var r=t.config;if("errorTracking"in r){var s=(e=(n=r.errorTracking)==null?void 0:n.suppressionRules)!==null&&e!==void 0?e:[],o=(i=r.errorTracking)==null?void 0:i.captureExtensionExceptions;this.Xo=s,this._instance.persistence&&this._instance.persistence.register({[sa]:this.Xo,[oa]:o})}}}get nl(){var t,e=!!this._instance.get_property(oa),n=this._instance.config.error_tracking.captureExtensionExceptions;return(t=n??e)!==null&&t!==void 0&&t}buildProperties(t,e){return this.tl.buildFromUnknown(t,{syntheticException:e?.syntheticException,mechanism:{handled:e?.handled}})}addExceptionStep(t,e){if(this.el.enabled)try{if(!X(t)||t.trim().length===0)return void St.warn("Ignoring exception step because message must be a non-empty string");var n=(function(s){if(!s)return{sanitizedProperties:{},droppedKeys:[]};var o=[];return{sanitizedProperties:Object.keys(s).reduce(((a,l)=>Pg.has(l)?(o.push(l),a):(a[l]=s[l],a)),{}),droppedKeys:o}})(this.sl(e)),i=n.sanitizedProperties,r=n.droppedKeys;r.length>0&&St.warn("Ignoring reserved exception step fields",{droppedKeys:r}),this.rl.add(I({[Jr]:t,[Zr]:new Date().toISOString()},i))}catch(s){St.error("Failed to add exception step. Ignoring breadcrumb.",s)}}sendExceptionEvent(t){try{var e=t.$exception_list;if(this.al(e)){if(this.ol(e))return this.ll("Exception dropped: matched a suppression rule"),void St.info("Skipping exception capture because a suppression rule matched");if(!this.nl&&this.ul(e))return this.ll("Exception dropped: thrown by a browser extension"),void St.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.hl(e))return this.ll("Exception dropped: thrown by the PostHog SDK"),void St.info("Skipping exception capture because it was thrown by the PostHog SDK")}var n=this.el.enabled&&H(t.$exception_steps)?this.dl(t):t,i=typeof(s=globalThis._posthogReleaseId)=="string"&&s.length>0?s:void 0;i&&(n.$release_id=i);try{var r=this._instance.capture("$exception",n,{_noTruncate:!0,_batchKey:"exceptionEvent",Wn:!0});return r&&this.rl.clear(),r}catch(o){return St.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void St.error("Failed to process exception event. Ignoring this exception.",o)}var s}dl(t){try{var e=this.rl.getAttachable();return e.length===0?t:I({},t,{$exception_steps:e})}catch(n){return St.error("Failed to read buffered exception steps. Capturing exception without steps.",n),t}}ll(t){this.el.enabled&&this.rl.add({[Jr]:t,[Zr]:new Date().toISOString()})}sl(t){return he(t)?I({},t):{}}il(){var t,e;return(t=(e=this._instance.config.error_tracking)==null?void 0:e.exception_steps)!==null&&t!==void 0?t:{}}ol(t){if(t.length===0)return!1;try{var e=t.reduce(((n,i)=>{var r=i.type,s=i.value;return X(r)&&r.length>0&&n.$exception_types.push(r),X(s)&&s.length>0&&n.$exception_values.push(s),n}),{$exception_types:[],$exception_values:[]});return this.Xo.some((n=>{var i=n.values.map((r=>{var s=Vf[r.operator],o=e[r.key];if(!s||!o)return!1;var a=U(r.value)?r.value:[r.value];return a.length>0&&s(a,o)}));return n.type==="OR"?i.some(Boolean):i.every(Boolean)}))}catch(n){return St.warn("Failed to evaluate suppression rules. Capturing the exception.",n),!1}}ul(t){return t.flatMap((e=>{var n,i;return(n=(i=e.stacktrace)==null?void 0:i.frames)!==null&&n!==void 0?n:[]})).some((e=>e.filename&&e.filename.startsWith("chrome-extension://")))}hl(t){if(t.length>0){var e,n,i,r,s=(e=(n=t[0].stacktrace)==null?void 0:n.frames)!==null&&e!==void 0?e:[],o=s[s.length-1];return(i=o==null||(r=o.filename)==null?void 0:r.includes("posthog.com/static"))!==null&&i!==void 0&&i}return!1}al(t){return!H(t)&&U(t)}}},Zm=I({productTours:class{get Mr(){return this._instance.persistence}constructor(t){this.vl=null,this.cl=null,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(t.ok){var e=t.config;if("productTours"in e){var n,i;if(this.Mr&&this.Mr.register({[ll]:!!e.productTours}),!Do(this._instance))return!this.vl&&H((n=this.Mr)==null?void 0:n.props[Li])||kr.info("product tours disabled; stopping and clearing cached tours"),(i=this.vl)==null||i.stop(),this.vl=null,void this.clearCache();this.loadIfEnabled()}}}loadIfEnabled(){!this.vl&&Do(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.generateProductTours?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",(i=>{i?kr.error("Could not load product tours script",i):t()}))}fl(){var t;!this.vl&&(t=B.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=B.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(t,e){if(e===void 0&&(e=!1),!U(this.cl)||e){var n=this.Mr;if(n){var i=n.props[Li];if(U(i)&&!e)return this.cl=i,void t(i,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",timestampMode:"query",callback:r=>{if(Do(this._instance)){var s=r.statusCode;if(s!==200||!r.json){var o="Product Tours API could not be loaded, status: "+s;return s===0?r.error||kr.warn(o):kr.error(o),void t([],{isLoaded:!1,error:o})}var a=U(r.json.product_tours)?r.json.product_tours:[];this.cl=a,n&&n.register({[Li]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){H(this.vl)?t([],{isLoaded:!1,error:"Product tours not loaded"}):this.vl.getActiveProductTours(t)}showProductTour(t){var e;(e=this.vl)==null||e.showTourById(t)}previewTour(t){this.vl?this.vl.previewTour(t):this.ai((()=>{var e;this.fl(),(e=this.vl)==null||e.previewTour(t)}))}dismissProductTour(){var t;(t=this.vl)==null||t.dismissTour("user_clicked_skip")}nextStep(){var t;(t=this.vl)==null||t.nextStep()}previousStep(){var t;(t=this.vl)==null||t.previousStep()}clearCache(){var t;this.cl=null,(t=this.Mr)==null||t.unregister(Li)}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)}}},Ps),Xm={siteApps:class{constructor(t){this.pl=0,this._instance=t,this.gl=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}ml(t,e){if(e){var n=this.globalsForEvent(e);this.gl.push(n),this.gl.length>1e3&&(this.gl=this.gl.slice(10))}}get siteAppLoaders(){var t;return(t=B._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,n,i,r,s,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var h=d[0];l[h]={id:u[h],type:h,properties:d[1]}}var f=t.$set_once,p=t.$set;return{event:I({},md(t,Um),{properties:I({},t.properties,p?{$set:I({},(e=(n=t.properties)==null?void 0:n.$set)!==null&&e!==void 0?e:{},p)}:{},f?{$set_once:I({},(i=(r=t.properties)==null?void 0:r.$set_once)!==null&&i!==void 0?i:{},f)}:{}),elements_chain:(s=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&s!==void 0?s:"",distinct_id:(a=t.properties)==null?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}bl(t){var e,n=(e=t.tagName)==null?void 0:e.toLowerCase();return n==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(Et.error("prepare_external_dependency_stylesheet returned null"),null):n==="script"&&this._instance.config.prepare_external_dependency_script?this._instance.config.prepare_external_dependency_script(t)||(Et.error("prepare_external_dependency_script returned null"),null):t}_l(){var t,e,n,i,r,s,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=P?.defaultView,u=l==null||(t=l.Node)==null?void 0:t.prototype;if(!l||!u)return()=>{};if(this.pl++,this.wl)return this.kl();var c=[],d=this,h=new WeakSet,f=(m,v,E)=>{if(m!=null&&m[v]){var S=m[v];m[v]=E(S),c.push((()=>{m[v]=S}))}},p=m=>{if(h.has(m))return m;var v=d.bl(m);return v&&h.add(v),v},g=m=>m.map((v=>typeof v=="string"?v:p(v))).filter((v=>!Ye(v)));return f(u,"appendChild",(m=>function(v){var E=p(v);return E?m.call(this,E):v})),f(u,"insertBefore",(m=>function(v,E){var S=p(v);return S?m.call(this,S,E):v})),f(u,"replaceChild",(m=>function(v,E){var S=p(v);return S?m.call(this,S,E):E})),[(e=l.Element)==null?void 0:e.prototype,(n=l.Document)==null?void 0:n.prototype,(i=l.DocumentFragment)==null?void 0:i.prototype].forEach((m=>{f(m,"append",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),f(m,"prepend",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))}))})),[(r=l.Element)==null?void 0:r.prototype,(s=l.CharacterData)==null?void 0:s.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((m=>{f(m,"before",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),f(m,"after",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),f(m,"replaceWith",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];var b=g(S);return S.length&&!b.length?void 0:v.apply(this,b)}))})),f((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(v,E){var S=p(E);return S?m.call(this,v,S):null})),this.wl=()=>{c.forEach((m=>m())),this.wl=void 0},this.kl()}kl(){var t=!1;return()=>{var e;t||(t=!0,this.pl--,this.pl===0&&((e=this.wl)==null||e.call(this)))}}xl(t,e){e===void 0&&(e=!0);var n=this._l();try{var i=t(n);return e&&n(),i}catch(r){throw n(),r}}setupSiteApp(t){var e=this.apps[t.id],n=()=>{var o;!e.errored&&this.gl.length&&(Et.info("Processing "+this.gl.length+" events for site app with id "+t.id),this.gl.forEach((a=>this.xl((()=>e.processEvent==null?void 0:e.processEvent(a))))),e.processedBuffer=!0),Object.values(this.apps).every((a=>a.processedBuffer||a.errored))&&((o=this.yl)==null||o.call(this))},i=!1,r=o=>{e.errored=!o,e.loaded=!0,Et.info("Site app with id "+t.id+" "+(o?"loaded":"errored")),i&&n()};try{var s=this.xl((o=>t.init({posthog:this._instance,callback(a){o(),r(a)}})),!1).processEvent;s&&(e.processEvent=s),i=!0}catch(o){Et.error(pu+t.id,o),r(!1)}if(i&&e.loaded)try{n()}catch(o){Et.error("Error while processing buffered events PostHog app with config id "+t.id,o),e.errored=!0}}Sl(){var t=this.siteAppLoaders||[];for(var e of t)this.apps[e.id]={id:e.id,loaded:!1,errored:!1,processedBuffer:!1};for(var n of t)this.setupSiteApp(n)}Cl(t){var e=this;if(Object.keys(this.apps).length!==0){var n=this.globalsForEvent(t),i=function(s){try{e.xl((()=>s.processEvent==null?void 0:s.processEvent(n)))}catch(o){Et.error("Error while processing event "+t.event+" for site app "+s.id,o)}};for(var r of Object.values(this.apps))i(r)}}onRemoteConfig(t){var e,n,i,r=this;if((e=this.siteAppLoaders)!=null&&e.length)return this.isEnabled?(this.Sl(),void this._instance.on("eventCaptured",(l=>this.Cl(l)))):void Et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((n=this.yl)==null||n.call(this),t.ok){var s=t.config;if((i=s.siteApps)!=null&&i.length)if(this.isEnabled){var o=function(){var l,u=a.id,c=a.url;B["__$$ph_site_app_"+u]=r._instance,(l=B.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(r._instance,c,(d=>{if(d)return Et.error(pu+u,d)}))};for(var a of s.siteApps)o()}else Et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},Qm={tracingHeaders:class{constructor(t){this.Ml=void 0,this.Tl=void 0,this.El=void 0,this.Uo=()=>{var e,n,i=this.Il();i?(C(this.Ml)&&(this.Ml=(e=B.__PosthogExtensions__)==null||(e=e.tracingHeadersPatchFns)==null?void 0:e._patchXHR(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager)),C(this.Tl)&&(this.Tl=(n=B.__PosthogExtensions__)==null||(n=n.tracingHeadersPatchFns)==null?void 0:n._patchFetch(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager))):this.Qo()},this._instance=t}initialize(){this.startIfEnabledOrStop()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",(i=>{if(i)return Dm.error("failed to load script",i);t()}))}Pl(){var t,e;return(t=(e=this._instance.config.tracing_headers)!==null&&e!==void 0?e:this._instance.config.addTracingHeaders)!==null&&t!==void 0?t:this._instance.config.__add_tracing_headers}Il(){var t=this.Pl();return U(t)?(U(this.El)?this.El.splice(0,this.El.length,...t):this.El=[...t],t.length>0?this.El:void 0):(U(this.El)&&this.El.splice(0),this.El=t||void 0,this.El)}Qo(){var t,e;(t=this.Ml)==null||t.call(this),(e=this.Tl)==null||e.call(this),this.Ml=void 0,this.Tl=void 0}startIfEnabledOrStop(){this.Il()?this.ai(this.Uo):this.Qo()}}},ev=I({surveys:class{get Ne(){return this._instance.config}constructor(t){this.Rl=void 0,this._surveyManager=null,this.Al=!1,this.Fl=[],this.Ll=null,this.Ol=null,this._instance=t,this._surveyEventReceiver=null}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this.Ne.disable_surveys){if(!t.ok)return Q.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(H(e))return Q.warn("Flags not loaded yet. Not loading surveys.");var n=U(e);this.Rl=n?e.length>0:e,Q.info("flags response received, isSurveysEnabled: "+this.Rl),this.loadIfEnabled()}}reset(){try{var t;(t=this._surveyEventReceiver)==null||t.reset(),localStorage.removeItem("lastSeenSurveyDate");for(var e=[],n=0;nlocalStorage.removeItem(r)))}catch{}}loadIfEnabled(){if(!this._surveyManager)if(this.Al)Q.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)Q.info(gu);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())Q.info("Not loading surveys in cookieless mode without consent.");else{var t=B?.__PosthogExtensions__;if(t){if(!C(this.Rl)||this.Ne.advanced_enable_surveys){var e=this.Rl||this.Ne.advanced_enable_surveys;this.Al=!0;try{var n=t.generateSurveys;if(n)return void this.Dl(n,e);var i=t.loadExternalDependency;if(!i)return void this.$l(ul);i(this._instance,"surveys",(r=>{r||!t.generateSurveys?this.$l("Could not load surveys script",r):this.Dl(t.generateSurveys,e)}))}catch(r){throw this.$l("Error initializing surveys",r),r}finally{this.Al=!1}}}else Q.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new zm(this._instance),Q.info("Surveys loaded successfully"),this.Nl({isLoaded:!0})}$l(t,e){Q.error(t,e),this.Nl({isLoaded:!1,error:t})}onSurveysLoaded(t){return this.Fl.push(t),this._surveyManager&&this.Nl({isLoaded:!0}),()=>{this.Fl=this.Fl.filter((e=>e!==t))}}getSurveys(t,e){if(e===void 0&&(e=!1),this.Ne.disable_surveys)return Q.info(gu),t([]);var n,i=this._instance.get_property(ua);if(i&&!e)return t(i,{isLoaded:!0}),void(this.ql()&&this.getSurveys((()=>{}),!0));typeof Promise<"u"&&this.Ll?this.Ll.then((r=>t(r.surveys,r.context))):(typeof Promise<"u"&&(this.Ll=new Promise((r=>{n=r}))),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this.Ne.token),method:"GET",timestampMode:"query",timeout:this.Ne.surveys_request_timeout_ms,callback:r=>{var s;this.Ll=null;var o=r.statusCode;if(o!==200||!r.json){var a="Surveys API could not be loaded, status: "+o;o!==0?Q.error(a):r.error||Q.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(n==null||n({surveys:[],context:l}))}this.Ol=null;var u,c=r.json.surveys||[],d=c.filter((f=>(function(p){return!(!p.start_date||p.end_date)})(f)&&(Kf(f)||(function(p){var g;return!((g=p.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(f))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(s=this._instance.persistence)==null||s.register({[ua]:c,[es]:Date.now()});var h={isLoaded:!0};t(c,h),n?.({surveys:c,context:h})}}))}ql(){return this.jl()&&!this.Ll&&!this.Bl()}jl(){var t=this._instance.get_property(es);return ke(t)&&Date.now()-t>3e5}Bl(){return ke(this.Ol)&&3e5>Date.now()-this.Ol}markSurveyAsSeen(t,e){var n,i={id:t,current_iteration:(n=e?.iteration)!==null&&n!==void 0?n:null};Jf(i);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}}Nl(t){for(var e of this.Fl)try{if(!t.isLoaded)return e([],t);this.getSurveys(e)}catch(n){Q.error("Error in survey callback",n)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!H(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);Q.warn("init was not called")}Hl(t){var e=null;return this.getSurveys((n=>{var i;e=(i=n.find((r=>r.id===t)))!==null&&i!==void 0?i:null})),e}Ul(t){if(H(this._surveyManager))return{eligible:!1,reason:Cr};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyEligibility(e):{eligible:!1,reason:"Survey not found"}}zl(t){if(H(this._surveyManager))return{eligible:!1,reason:Cr};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyRenderability(e):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(t){if(H(this._surveyManager))return Q.warn("init was not called"),{visible:!1,disabledReason:Cr};var e=this.zl(t);return{visible:e.eligible,disabledReason:e.reason}}canRenderSurveyAsync(t,e){return H(this._surveyManager)?(Q.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Cr})):new Promise((n=>{this.getSurveys((i=>{var r,s=(r=i.find((a=>a.id===t)))!==null&&r!==void 0?r:null;if(s){var o=this.zl(s);n({visible:o.eligible,disabledReason:o.reason})}else n({visible:!1,disabledReason:"Survey not found"})}),e)}))}renderSurvey(t,e,n){var i;if(H(this._surveyManager))Q.warn("init was not called");else{var r=typeof t=="string"?this.Hl(t):t;if(r!=null&&r.id)if(km.includes(r.type)){var s=P?.querySelector(e);if(s)return(i=r.appearance)!=null&&i.surveyPopupDelaySeconds?(Q.info("Rendering survey "+r.id+" with delay of "+r.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;Q.info("Rendering survey "+r.id+" with delay of "+((o=r.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(a=this._surveyManager)==null||a.renderSurvey(r,s,n),Q.info("Survey "+r.id+" rendered")}),1e3*r.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(r,s,n);Q.warn("Survey element not found")}else Q.warn("Surveys of type "+r.type+" cannot be rendered in the app");else Q.warn("Survey not found")}}displaySurvey(t,e){var n;if(H(this._surveyManager))Q.warn("init was not called");else{var i=this.Hl(t);if(i){var r=i;if((n=i.appearance)!=null&&n.surveyPopupDelaySeconds&&e.ignoreDelay&&(r=I({},i,{appearance:I({},i.appearance,{surveyPopupDelaySeconds:0})})),e.displayType!==wa.Popover&&e.initialResponses&&Q.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),e.ignoreConditions===!1){var s=this.Ul(i);if(!s.eligible)return void Q.warn("Survey is not eligible to be displayed: ",s.reason)}e.displayType!==wa.Inline?this._surveyManager.handlePopoverSurvey(r,e):this.renderSurvey(r,e.selector,e.properties)}else Q.warn("Survey not found")}}cancelPendingSurvey(t){H(this._surveyManager)?Q.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},Ps),tv={toolbar:class{constructor(t){this.instance=t}Wl(t){B.ph_toolbar_state=t}Vl(){var t;return(t=B.ph_toolbar_state)!==null&&t!==void 0?t:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(t,e,n){if(t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),va(this.instance.config)||!w||!P)return!1;t=t??w.location,n=n??w.history;try{if(!e){try{w.localStorage.setItem("test","test"),w.localStorage.removeItem("test")}catch{return!1}e=w?.localStorage}var i,r=qm||ls(t.hash,"__posthog")||ls(t.hash,"state"),s=r?$c((()=>JSON.parse(atob(decodeURIComponent(r)))))||$c((()=>JSON.parse(decodeURIComponent(r)))):null;return s&&s.action==="ph_authorize"?((i=s).source="url",i&&Object.keys(i).length>0&&(s.desiredHash?t.hash=s.desiredHash:n?n.replaceState(n.state,"",t.pathname+t.search):t.hash="")):((i=JSON.parse(e.getItem(mu)||"{}")).source="localstorage",delete i.userIntent),!(!i.token||this.instance.config.token!==i.token||(this.loadToolbar(i),0))}catch{return!1}}Zl(t){var e=B.ph_load_toolbar||B.ph_load_editor;!H(e)&&je(e)?e(t,this.instance):vu.warn("No toolbar load function found")}loadToolbar(t){var e=!(P==null||!P.getElementById(df));if(!w||e)return!1;var n=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,i=I({token:this.instance.config.token},t,{apiURL:this.instance.requestRouter.endpointFor("ui")},n?{instrument:!1}:{});if(w.localStorage.setItem(mu,JSON.stringify(I({},i,{source:void 0}))),this.Vl()===2)this.Zl(i);else if(this.Vl()===0){var r;this.Wl(1),(r=B.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"toolbar",(s=>{if(s)return vu.error("[Toolbar] Failed to load",s),void this.Wl(0);this.Wl(2),this.Zl(i)})),ve(w,"turbolinks:load",(()=>{this.Wl(0),this.loadToolbar(i)}))}return!0}Gl(t){return this.loadToolbar(t)}maybeLoadEditor(t,e,n){return t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),this.maybeLoadToolbar(t,e,n)}}},nv=I({experiments:Me},Ps),iv={conversations:class{constructor(t){this.Ql=void 0,this._conversationsManager=null,this.Kl=!1,this.Jl=null,this.Yl=!1,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this._instance.config.disable_conversations&&(this.Xl=t.ok,t.ok)){var e=t.config.conversations;H(e)||(mt(e)?this.Ql=e:(this.Ql=e.enabled,this.Jl=e),this.loadIfEnabled())}}reset(){var t;(t=this._conversationsManager)==null||t.reset(),this._conversationsManager=null,this.Ql=void 0,this.Jl=null,this.Xl=void 0,this.Yl=!1}loadIfEnabled(){if(!(this._conversationsManager||this.Kl||this._instance.config.disable_conversations||va(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=B?.__PosthogExtensions__;if(t&&!C(this.Ql)&&this.Ql)if(this.Jl&&this.Jl.token){this.Kl=!0;try{var e=t.initConversations;if(e)return this.tu(e),void(this.Kl=!1);var n=t.loadExternalDependency;if(!n)return void this.eu(ul);n(this._instance,"conversations",(i=>{i||!t.initConversations?this.eu("Could not load conversations script",i):this.tu(t.initConversations),this.Kl=!1}))}catch(i){this.eu("Error initializing conversations",i),this.Kl=!1}}else ot.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,ot.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else ot.error("Cannot complete initialization: remote config is null")}eu(t,e){ot.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():ot.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!Ye(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":va(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.Xl===!1?"remote_config_failed":C(this.Ql)?this.Xl?"disabled_in_project":"remote_config_pending":this.Ql?H(this.Jl)||!this.Jl.token?"missing_token":B!=null&&B.__PosthogExtensions__?this.Kl?"initializing":this.Yl?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.isVisible())!==null&&t!==void 0&&t}sendMessage(t,e,n){var i=this;return se((function*(){return i._conversationsManager?i._conversationsManager.sendMessage(t,e,n):(ot.warn(En),null)}))()}getMessages(t,e){var n=this;return se((function*(){return n._conversationsManager?n._conversationsManager.getMessages(t,e):(ot.warn(En),null)}))()}markAsRead(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(ot.warn(En),null)}))()}getTickets(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(ot.warn(En),null)}))()}requestRestoreLink(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(ot.warn(En),null)}))()}restoreFromToken(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(ot.warn(En),null)}))()}restoreFromUrlToken(){var t=this;return se((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(ot.warn(En),null)}))()}getCurrentTicketId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getCurrentTicketId())!==null&&t!==void 0?t:null}getWidgetSessionId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getWidgetSessionId())!==null&&t!==void 0?t:null}Xn(){var t;(t=this._conversationsManager)==null||t.setIdentity()}ts(){var t;(t=this._conversationsManager)==null||t.clearIdentity()}}},rv={logs:class{constructor(t){var e,n=this;this.iu=!1,this.ru=!1,this.rt=pe("[logs]"),this.nu=I({},this.rt,{error(){for(var i=arguments.length,r=new Array(i),s=0;i>s;s++)r[s]=arguments[s];r.some(Iu)||n.rt.error(...r)}}),this.tr=[],this.su=[],this.Sa=0,this.au=()=>{var i,r;this.Sa=0,(i=this.ou)==null||i.onReconnect(),(r=this.lu)==null||r.onReconnect()},this._instance=t,this._instance&&(e=this._instance.config.logs)!=null&&e.captureConsoleLogs&&(this.iu=!0),w&&ve(w,"online",this.au)}uu(t,e,n,i){var r,s=(function(o,a){var l,u,c,d,h,f,p,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,v=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,E=C(v)?Math.max(m,2048):Math.max(m,v),S=o?.resourceAttributes;return{serviceName:(d=(h=S?.["service.name"])!==null&&h!==void 0?h:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(f=S?.["service.version"])!==null&&f!==void 0?f:o?.serviceVersion,environment:(p=S?.["deployment.environment"])!==null&&p!==void 0?p:o?.environment,resourceAttributes:S,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:E,maxBatchRecordsPerPost:100,rateCapWindowMs:g,maxLogsPerInterval:v,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}})((r=this._instance)==null||(r=r.config)==null?void 0:r.logs,n);return[new lg(this.hu(t,e),s,this.nu,(()=>this.du()),(o=>o()),void 0,i),s]}vu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.ou||this.cu!==e){var n;(n=this.ou)==null||n.reset(),this.cu=e;var i=this.uu((()=>this.tr),(r=>{this.tr=r}));this.ou=i[0],this.fu=i[1]}return this.ou}pu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.lu||this.gu!==e){var n;(n=this.lu)==null||n.reset(),this.gu=e;var i=this.uu((()=>this.su),(r=>{this.su=r}),{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},xu);this.lu=i[0],this.mu=i[1]}return this.lu}initialize(){this.loadIfEnabled()}onRemoteConfig(t){var e;if(t.ok){var n=(e=t.config.logs)==null?void 0:e.captureConsoleLogs;!H(n)&&n&&(this.iu=!0,this.loadIfEnabled())}}reset(){var t,e;this.tr=[],(t=this.ou)==null||t.reset(),this.su=[],(e=this.lu)==null||e.reset(),this.Sa=0}captureLog(t){this.vu().captureLog(t)}he(t){this.pu().captureLog(t)}get logger(){return this.yu||(this.yu={trace:(t,e)=>this.captureLog({body:t,level:"trace",attributes:e}),debug:(t,e)=>this.captureLog({body:t,level:"debug",attributes:e}),info:(t,e)=>this.captureLog({body:t,level:"info",attributes:e}),warn:(t,e)=>this.captureLog({body:t,level:"warn",attributes:e}),error:(t,e)=>this.captureLog({body:t,level:"error",attributes:e}),fatal:(t,e)=>this.captureLog({body:t,level:"fatal",attributes:e})}),this.yu}flushLogs(t){t?this.bu(t):(this.ou&&this.ou.flush().catch((e=>this._u(e))),this.lu&&this.lu.flush().catch((e=>this._u(e))))}_u(t){Iu(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=B?.__PosthogExtensions__;if(t){var e=t.loadExternalDependency;e?e(this._instance,"logs",(n=>{var i;n||(i=t.logs)==null||!i.initializeLogs?this.rt.error("Could not load logs script",n):(t.logs.initializeLogs(this._instance),this.ru=!0)})):this.rt.error(ul)}else this.rt.error("PostHog Extensions not found.")}}hu(t,e){var n=this._instance;return{get isDisabled(){return!1},get optedOut(){return!n.is_capturing()},getPersistedProperty:i=>i===Ut.LogsQueue?t():void 0,setPersistedProperty(i,r){var s;i===Ut.LogsQueue&&e((s=r)!==null&&s!==void 0?s:[])},Ot:i=>this.Ot(i),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Ot(t){return new Promise((e=>{if(Sf(this.Sa,3))e({kind:"fatal",error:Uo(void 0,"logs endpoint is unreachable, dropping batch")});else{var n=!1,i=s=>{n||(n=!0,clearTimeout(r),e(s))},r=setTimeout((()=>{this.rt.warn("Logs request timed out before receiving a response"),i({kind:"retry-later",error:Uo(void 0,"logs request timed out")})}),9e4);this._instance._send_request({method:"POST",url:this.wu(),data:t,compression:"best-available",batchKey:"logs",fireCallbackOnDrop:!0,callback:s=>{var o=s.statusCode;if(this.ku(o),o>=200&&300>o)i({kind:"ok"});else if(o===413)i({kind:"too-large"});else if(o!==0&&o!==429&&500>o)i({kind:"fatal",error:new Error("logs request failed with status "+o)});else{var a;o===0?(s.error||this.rt.warn("Logs request failed before receiving an HTTP response"),i({kind:"retry-later",error:Uo(s.error,"logs request failed before receiving an HTTP response")})):i({kind:"retry-later",error:(a=s.error)!==null&&a!==void 0?a:new Error("logs request failed with status "+o)})}}})}}))}ku(t){(t!==0||this._instance.__loaded)&&(this.Sa=xf(t,this.Sa,3,(()=>this.rt.warn("Log requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped sending logs; will try again when connectivity changes."))))}bu(t){this.tr.length>0&&this.xu(t,this.tr,this.fu,ne.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,xu,(e=>{this.su=e}))}xu(t,e,n,i,r){if(e.length!==0){var s=e.map((a=>a.record));r([]);var o=Gd(s,Vd(n,ne.LIB_NAME,ne.LIB_VERSION),i,ne.LIB_VERSION);this._instance._send_request({method:"POST",url:this.wu(),data:o,compression:"best-available",batchKey:"logs",transport:t})}}wu(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}du(){var t,e={};if(e.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var n=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.windowId,r=n.sessionStartTimestamp,s=n.lastActivityTimestamp;e.sessionId=n.sessionId,e.windowId=i,H(r)||(e.sessionStartTimestamp=r),H(s)||(e.lastActivityTimestamp=s)}if(B!=null&&(t=B.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?fn(B.location.href):B.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},sv={metrics:class{constructor(t){this.rt=pe("[metrics]"),this._instance=t}initialize(){}vu(){var t,e,n=(t=this._instance)==null||(t=t.config)==null?void 0:t.metrics;return this.ou&&this.cu===n||((e=this.ou)==null||e.reset(),this.cu=n,this.ou=new cg(this.hu(),(function(i){var r,s,o,a,l,u=i?.resourceAttributes;return{serviceName:(r=u?.["service.name"])!==null&&r!==void 0?r:i?.serviceName,serviceVersion:(s=u?.["service.version"])!==null&&s!==void 0?s:i?.serviceVersion,environment:(o=u?.["deployment.environment"])!==null&&o!==void 0?o:i?.environment,resourceAttributes:u,beforeSend:i?.beforeSend,flushIntervalMs:(a=i?.flushIntervalMs)!==null&&a!==void 0?a:1e4,maxSeriesPerFlush:(l=i?.maxSeriesPerFlush)!==null&&l!==void 0?l:1e3}})(n),this.rt)),this.ou}count(t,e,n){e===void 0&&(e=1),this.vu().count(t,e,n)}gauge(t,e,n){this.vu().gauge(t,e,n)}histogram(t,e,n){this.vu().histogram(t,e,n)}flush(t){if(!this.ou)return Promise.resolve();if(t){var e=this.ou.drainWindow();return e&&this.Jt(e,t),Promise.resolve()}return this.ou.flush().catch((n=>this.rt.error("PostHog metrics flush failed:",n)))}reset(){var t;(t=this.ou)==null||t.reset()}hu(){var t=this._instance,e=this;return{get isDisabled(){return!1},get optedOut(){return!t.is_capturing()},Jt:n=>e.Jt(n),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Jt(t,e){return new Promise((n=>{var i=!1,r=o=>{i||(i=!0,clearTimeout(s),n(o))},s=setTimeout((()=>r({kind:"retry-later",error:new Error("metrics request timed out")})),9e4);this._instance._send_request(I({method:"POST",url:this.Su(),data:t,compression:"best-available",batchKey:"metrics"},e&&{transport:e},{fireCallbackOnDrop:!0,callback(o){var a=o.statusCode;if(a>=200&&300>a)r({kind:"ok"});else if(a===413)r({kind:"too-large"});else if(a!==0&&a!==429&&500>a)r({kind:"fatal",error:new Error("metrics request failed with status "+a)});else{var l;r({kind:"retry-later",error:(l=o.error)!==null&&l!==void 0?l:new Error("metrics request failed with status "+a)})}}}))}))}Su(){return this._instance.requestRouter.endpointFor("api","/i/v1/metrics")+"?token="+encodeURIComponent(this._instance.config.token)}}},ov=I({},Ps,Km,Ym,Jm,Zm,Xm,ev,Qm,tv,nv,iv,rv,sv);Ze.__defaultExtensionClasses=I({},ov);(function(){ne.SDK_DIST_CHANNEL="npm";var t=zi[Kn]=new Ze;return(function(){function e(){e.done||(e.done=!0,Xf=!1,ie(zi,(function(n){n._dom_loaded()})))}P!=null&&P.addEventListener?P.readyState==="complete"?e():ve(P,"DOMContentLoaded",e,{capture:!1}):w&&A.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const av=["a[href]","button:not([disabled])","input:not([disabled]):not([type='hidden'])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(",");let pt=null,Aa=null,eh="";const Pa=new Map;function th(t){return[...t.querySelectorAll(av)].filter(e=>!e.hidden&&e.getAttribute("aria-hidden")!=="true"&&e.getClientRects().length>0)}function lv(t){for(const e of document.body.children)e===t||e.tagName==="SCRIPT"||(Pa.set(e,{inert:e.inert,ariaHidden:e.getAttribute("aria-hidden")}),e.inert=!0,e.setAttribute("aria-hidden","true"))}function cv(){for(const[t,e]of Pa)t.inert=e.inert,e.ariaHidden===null?t.removeAttribute("aria-hidden"):t.setAttribute("aria-hidden",e.ariaHidden);Pa.clear()}function nh(t){return t?.dataset.modalDismissible!=="false"&&t?.getAttribute("aria-busy")!=="true"}function We(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n)return!1;pt&&pt!==n&&ze(pt,{restoreFocus:!1,force:!0}),Aa=e.trigger||document.activeElement,pt=n,eh=document.body.style.overflow,lv(n),document.body.style.overflow="hidden",n.classList.add("open"),n.setAttribute("aria-hidden","false");const i=n.querySelector(".modal-content");i&&(i.style.transform="scale(1) translateY(0)");const r=()=>{if(pt!==n)return;((e.initialFocus?n.querySelector(e.initialFocus):n.querySelector("[data-modal-initial-focus]"))||th(n)[0]||n.querySelector(".modal-content")||n).focus({preventScroll:!0})};return requestAnimationFrame(r),setTimeout(r,260),!0}function ze(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n||!e.force&&!nh(n))return!1;n.classList.remove("open"),n.setAttribute("aria-hidden","true"),cv(),document.body.style.overflow=eh,pt=null;const i=Aa;return Aa=null,e.restoreFocus!==!1&&i?.isConnected&&i.focus({preventScroll:!0}),!0}function ku(t,e,n="Operation in progress"){const i=typeof t=="string"?document.getElementById(t):t;i&&(i.dataset.modalDismissible=e?"false":"true",i.setAttribute("aria-busy",String(!!e)),e?i.setAttribute("aria-label",n):i.removeAttribute("aria-label"))}function uv(t){if(!nh(t))return;const e=t.dataset.modalCloseHandler;e&&typeof window[e]=="function"?window[e]():ze(t)}document.addEventListener("keydown",t=>{if(!pt)return;if(t.key==="Escape"){t.preventDefault(),t.stopImmediatePropagation(),uv(pt);return}if(t.key!=="Tab"){t.stopPropagation();return}const e=th(pt);if(!e.length){t.preventDefault(),(pt.querySelector(".modal-content")||pt).focus();return}const n=e[0],i=e[e.length-1];t.shiftKey&&document.activeElement===n?(t.preventDefault(),i.focus()):!t.shiftKey&&document.activeElement===i&&(t.preventDefault(),n.focus())},!0);function dv(){document.querySelectorAll(".modal-overlay").forEach(t=>{t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-hidden",t.classList.contains("open")?"false":"true");const e=t.querySelector(".modal-content");e&&!e.hasAttribute("tabindex")&&(e.tabIndex=-1);const n=t.querySelector("h1, h2, h3");n&&(n.id||(n.id=`${t.id}-title`),t.setAttribute("aria-labelledby",n.id)),t.querySelectorAll(".modal-close").forEach(i=>{i.getAttribute("aria-label")||i.setAttribute("aria-label","Close dialog")})})}const _l=Object.freeze({free:"Free",professional:"Pro",power:"Power"}),fv=Object.freeze({free:2,professional:50,power:2e3}),hv="(contact us)",pv=Object.freeze({free:Object.freeze(["2 generations/month","Gemini model only","Code Review"]),professional:Object.freeze(["50 generations/month","All models","Code Regeneration","Code Review"]),power:Object.freeze(["2000 generations/month","All models","Code Regeneration","Bring your own key (BYOK)","Code Review","All models + early access",`API & MCP access ${hv}`])}),ih="CodeFile",rh="GeneratedCode",gv={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function ln(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Fa(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function mv(t={},e=0){const n=Fa(t.artifactType||t.type||ih),i=Fa(t.artifactName||t.name||t.fileName||`${rh}-${e+1}`);return`${n||"artifact"}-${i||e+1}`}function sh(t={},e=0){const n=ln(t),i=n.artifactType||n.type||ih,r=n.artifactName||n.name||rh;let s=n.fileName||r;return s.endsWith(".dart")||(s+=".dart"),{id:Fa(n.id)||mv({...n,artifactType:i,artifactName:r,fileName:s},e),artifactType:i,artifactName:r,fileName:s,deployPath:n.deployPath||"",description:n.description||"",code:n.code||n.content||"",dependencies:oh(n.dependencies),imports:Array.isArray(n.imports)?n.imports:[],publicApi:Array.isArray(n.publicApi)?n.publicApi:[],relationships:ah(n.relationships),deployStatus:n.deployStatus||"pending",review:n.review||null,metadata:ln(n.metadata),codeType:n.codeType||gv[i]||"O"}}function oh(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const n=ln(e),i=n.name||n.package;return i?{name:i,version:n.version||null,versionRequired:!!(n.versionRequired||n.required),inferred:!!n.inferred,...n.reason?{reason:n.reason}:{}}:null}).filter(Boolean):Object.entries(ln(t)).map(([e,n])=>({name:e,version:n||null,inferred:!1})):[]}function ah(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const n=ln(e);return!n.from&&!n.to?null:{from:n.from||null,to:n.to||null,type:n.type||"uses",description:n.description||""}}).filter(Boolean):[]}function Ra(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;try{return JSON.parse(e)}catch{const n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(!n)return null;try{return JSON.parse(n[1].trim())}catch{return null}}}function er(t,e={}){const n=[],i=typeof t=="string"?Ra(t):t,s=ln(i||{});!i&&typeof t=="string"&&n.push("Structured bundle parse failed; using legacy single-artifact fallback.");const o=Array.isArray(s.artifacts)?s.artifacts:[{artifactType:s.artifactType||e.artifactType,artifactName:s.artifactName||e.artifactName,fileName:s.fileName||e.fileName,description:s.description,code:s.code||e.code||(typeof t=="string"?t:""),dependencies:s.dependencies||e.dependencies,relationships:s.relationships||e.relationships}];o.forEach((d,h)=>{!d?.artifactType&&!d?.type&&n.push(`Artifact ${h+1} has no artifactType; it will deploy as a standalone code file under lib/custom_code/ root.`)});const a=o.map((d,h)=>sh(d,h)),l=new Map(o.map((d,h)=>[ln(d).id,a[h]?.id]).filter(([d,h])=>d&&h)),u=d=>l.get(d)||d,c=ah(s.relationships||e.relationships).map(d=>({...d,from:d.from?u(d.from):d.from,to:d.to?u(d.to):d.to}));return{schemaVersion:s.schemaVersion||e.schemaVersion||null,id:s.id||e.id||"bundle-current",title:s.title||s.name||e.title||"Generated artifact bundle",description:s.description||e.description||"",artifacts:a,dependencies:oh(s.dependencies||e.dependencies),relationships:c,deployOrder:Array.isArray(s.deployOrder)?s.deployOrder.map(u):a.map(d=>d.id),warnings:[...n,...Array.isArray(s.warnings)?s.warnings:[]],metadata:ln(s.metadata)}}function ai(t){return er(t).artifacts[0]||sh()}function Zt(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function li(t){return JSON.stringify(t,null,2)}function vv(t){return li({task:"architect",userRequest:String(t??"")})}function _v(t){const e=Zt(t);return e&&typeof e=="object"&&typeof e.task=="string"?li(e):li({task:"generate_bundle",bundleSpec:e})}function yv(t){return li({task:"review_bundle",generatedBundle:Zt(t),outputRequirements:{bundleReview:["status","score","summary","manualActions","findings"],scoreRange:[0,100],eachArtifact:["id","review.status","review.findings"],manualActions:{definition:"Setup the developer must perform by hand in the FlutterFlow editor that FlutterFlow will NOT do for them.",exclude:["creating the Custom Action, Widget or Code File itself - deploying the code creates it","declaring parameters or return values FlutterFlow derives from the function signature","anything that resolves as a side effect of using the action or widget in the editor","generic advice such as testing, reviewing or rebuilding the app"],preferEmpty:"Return an empty array when nothing qualifies - an empty list is the expected result for most bundles."}}})}function yl(t,e=null){const n={stage:t};return e!=null&&(n.bundle=Zt(e)),n}function wv({bundleSpec:t,artifactBundle:e,bundleReview:n,artifactId:i,userFeedback:r}){return li({task:"regenerate_artifact",artifactId:i,bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(r)})}function lh({bundleSpec:t,artifactBundle:e,bundleReview:n,userFeedback:i}){return li({task:"regenerate_bundle",bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(i??"")})}const Cu={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"},bv=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function tt(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Ev(t){return tt(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||tt(t.filterSummary)||tt(t.filterResults):!1}function ch(t,e=0){if(!tt(t)||e>3)return null;if(Ev(t))return t;for(const n of bv){const i=t[n];if(tt(i)){const r=ch(i,e+1);if(r)return r}}return null}function hs(t){return Array.isArray(t)?t.some(hs):tt(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(hs):!1}function Ta(t){return Array.isArray(t)?t.some(Ta):tt(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(Ta):!1}function uh(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function Sv(t,e){if(tt(t))for(const[n,i]of Object.entries(t)){if(!tt(i))continue;const r=tt(i.categories)?i.categories:{},s=Object.entries(r).filter(([,o])=>tt(o)&&o.matched===!0).map(([o])=>o);s.length>0?s.forEach(o=>e.add(o)):i.matched===!0&&e.add(uh(n))}}function xv(t,e){if(!t)return;const n=Array.isArray(t)?t.flatMap(i=>tt(i)?Object.entries(i):[]):Object.entries(t);for(const[i,r]of n){if(!hs(r))continue;const s=uh(i),o=r?.raiFilterResult?.raiFilterTypeResults||(s==="rai"?r?.raiFilterTypeResults:null),a=tt(o)?Object.entries(o).filter(([,l])=>hs(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(s)}}function Iv(t){return Cu[t]?Cu[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function Au(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 kv(t){const e=ch(t);if(!e)return null;const n=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);Sv(e.filterSummary,n),xv(e.filterResults,n);const i=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||n.size>0,r=e.invocationResult||null,s=Ta(e.filterSummary||e.filterResults);return!i&&!s&&!["PARTIAL","FAILURE"].includes(r)?null:{kind:i?"blocked":"unavailable",invocationResult:r,matchedFilters:[...n]}}function Cv(t,e){const n=kv(t);if(!n)return null;const i=[...new Set(n.matchedFilters.map(Iv))],r=n.kind==="blocked",s=new Error(r?`Safety screening blocked this pipeline step for ${Au(i)}.`:"Safety screening could not be completed. Please try again.");return s.name="ModelArmorError",s.code=r?"MODEL_ARMOR_BLOCKED":"MODEL_ARMOR_UNAVAILABLE",s.isModelArmor=!0,s.pipelineStep=e,s.userTitle=r?"Request blocked for safety":"Safety check unavailable",s.userMessage=r?`The safety check detected ${Au(i)}. Edit your request to remove or rephrase the flagged content, then run the pipeline again.`:"The safety service did not finish all of its checks. Please wait a moment and run the pipeline again.",s.retryExplanation=r?"Trying another model would not change this safety decision.":"A fallback model was not attempted because safety screening must complete first.",s.matchedFilters=n.matchedFilters,s}function Av(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function Pu(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,n=[];for(const i of Av(t).split(` -`)){if(!/^[A-Za-z_$]/.test(i)||e.test(i))continue;const r=i.match(/^[\w$<>,?\s[\]]+?\s([a-zA-Z_$][\w$]*)\s*\(/);r&&n.push(r[1])}return n}function wl(t,e){const n=t.replace(/\.dart$/,"");if(e==="W")return n.replace(/(^|_)(\w)/g,(i,r,s)=>s.toUpperCase());if(e==="A"){const i=n.replace(/(^|_)(\w)/g,(r,s,o)=>o.toUpperCase());return i.charAt(0).toLowerCase()+i.slice(1)}return e==="F"?"CustomFunctions":e==="C"?t.endsWith(".dart")?t:`${t}.dart`:n}async function Fu(t){const e=new TextEncoder().encode(String(t||"")),n=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n),i=>i.toString(16).padStart(2,"0")).join("")}async function Pv(t,e=new Map){const n={},i=new Set;for(const[o,a]of t.entries()){if(a.type==="D"||a.type==="O")continue;const l=wl(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await Fu(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await Fu(c)),n[o]=u,a.type==="F"){const d=Pu(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(f=>i.add(f))}}const r=new Set(Pu(e.get("lib/flutter_flow/custom_functions.dart")||"")),s={functions_to_rename:[],functions_to_delete:[],functions_to_add:Array.from(i).filter(o=>!r.has(o))};return{fileMapContents:JSON.stringify(n),functionsMapContents:JSON.stringify(s)}}const Fv=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),Ru={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},Rv=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),Tv=["Struct","Record"],$v=[{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=>Ho(t).some(e=>/\brequired\s+this\.\w+/.test(e)),pos:"class W extends StatefulWidget { const W({required this.value}); final double value; }",neg:`class _P { const _P({required this.t}); final double t; } +(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const s of r)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function n(r){const s={};return r.integrity&&(s.integrity=r.integrity),r.referrerPolicy&&(s.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?s.credentials="include":r.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function i(r){if(r.ep)return;r.ep=!0;const s=n(r);fetch(r.href,s)}})();var w=typeof window<"u"?window:void 0,Ne=typeof globalThis<"u"?globalThis:w,He=Ne?.navigator,P=Ne?.document,me=Ne?.location,el=Ne?.fetch,Vo=Ne!=null&&Ne.XMLHttpRequest&&"withCredentials"in new Ne.XMLHttpRequest?Ne.XMLHttpRequest:void 0,pc=Ne?.AbortController,Op=Ne?.CompressionStream,Ge=He?.userAgent;function gd(){return!(!w||w.navigator.onLine===!1)}var _i=typeof globalThis<"u"?globalThis:w;_i&&typeof self>"u"&&(_i.self=_i),_i&&typeof File>"u"&&(_i.File=function(){});var B=w??{},ne={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function gc(t,e,n,i,r,s,o){try{var a=t[s](o),l=a.value}catch(u){return void n(u)}a.done?e(l):Promise.resolve(l).then(i,r)}function se(t){return function(){var e=this,n=arguments;return new Promise((function(i,r){var s=t.apply(e,n);function o(l){gc(s,i,r,o,a,"next",l)}function a(l){gc(s,i,r,o,a,"throw",l)}o(void 0)}))}}function I(){return I=Object.assign?Object.assign.bind():function(t){for(var e=1;arguments.length>e;e++){var n=arguments[e];for(var i in n)({}).hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},I.apply(null,arguments)}function md(t,e){if(t==null)return{};var n={};for(var i in t)if({}.hasOwnProperty.call(t,i)){if(e.indexOf(i)!==-1)continue;n[i]=t[i]}return n}var mc=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function vc(t){return typeof t=="string"||t}function _c(t){return typeof t=="string"?t:void 0}var yi,Bp=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],Ut=(function(t){return t.AnonymousId="anonymous_id",t.DistinctId="distinct_id",t.Props="props",t.EnablePersonProcessing="enable_person_processing",t.PersonMode="person_mode",t.FeatureFlagDetails="feature_flag_details",t.FeatureFlags="feature_flags",t.FeatureFlagPayloads="feature_flag_payloads",t.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",t.BootstrapFeatureFlags="bootstrap_feature_flags",t.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",t.OverrideFeatureFlags="override_feature_flags",t.Queue="queue",t.AiQueue="ai_queue",t.LogsQueue="logs_queue",t.OptedOut="opted_out",t.SessionId="session_id",t.SessionStartTimestamp="session_start_timestamp",t.SessionLastTimestamp="session_timestamp",t.PersonProperties="person_properties",t.GroupProperties="group_properties",t.InstalledAppBuild="installed_app_build",t.InstalledAppVersion="installed_app_version",t.SessionReplay="session_replay",t.PushRegistered="push_registered",t.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",t.SurveyLastSeenDate="survey_last_seen_date",t.SurveysSeen="surveys_seen",t.Surveys="surveys",t.RemoteConfig="remote_config",t.FlagsEndpointWasHit="flags_endpoint_was_hit",t.DeviceId="device_id",t})({}),yc=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),Dp=["$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"],jp=["token"],vd="NativeGzipValidationError",Go=t=>t.length>=2&&t[0]===31&&t[1]===139,wc=(t,e)=>t===yc.GZipJS||e===yc.GZipJS||e==="gzip",bc=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=vd,e},Up=(function(){var t=se((function*(e,n){18>e.size&&gr("too-short");var i=new Uint8Array(yield e.slice(0,10).arrayBuffer());Go(i)&&i[2]===8||gr("invalid-header");var r=new DataView(yield e.slice(e.size-8).arrayBuffer());r.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(yi)return yi;yi=[];for(var c=0;256>c;c++){for(var d=c,f=0;8>f;f++)d=1&d?3988292384^d>>>1:d>>>1;yi[c]=d>>>0}return yi})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(n)&&gr("invalid-crc");var s=n.length>>>0;r.getUint32(4,!0)!==s&&gr("invalid-size")}));return function(e,n){return t.apply(this,arguments)}})();function Ko(){return Ko=se((function*(t,e,n){e===void 0&&(e=!0);try{var i=new TextEncoder().encode(t),r=new globalThis.CompressionStream("gzip"),s=r.writable.getWriter(),o=s.write(i).then((()=>s.close())).catch((function(){var u=se((function*(c){try{yield s.abort(c)}catch{}throw c}));return function(c){return u.apply(this,arguments)}})()),a=new Response(r.readable).blob(),l=(yield Promise.all([a,o]))[0];return yield Up(l,i),l}catch(u){if(n!=null&&n.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),Ko.apply(this,arguments)}var Hp=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],Ec=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var n=t.toLowerCase();return Hp.concat(e).some((i=>{var r=i.toLowerCase();return n.indexOf(r)!==-1}))};function j(t,e){return t.indexOf(e)!==-1}var Is=function(t){return t.trim()},Yo=function(t){return t.replace(/^\$/,"")};function _d(t){var e,n=[];return(e=JSON.stringify(t,(function(i,r){if(typeof r=="bigint")return r.toString();if(typeof r!="function"&&typeof r!="symbol"){if(r instanceof Error)return{name:r.name,message:r.message,stack:r.stack};if(r&&typeof r=="object"){for(;n.length>0&&n[n.length-1]!==this;)n.pop();if(n.includes(r))return"[Circular]";n.push(r)}return r}})))!==null&&e!==void 0?e:"null"}var yd=Object.prototype,wd=yd.hasOwnProperty,ks=yd.toString,U=Array.isArray||function(t){return ks.call(t)==="[object Array]"},je=t=>typeof t=="function",he=t=>t===Object(t)&&!U(t),Kt=t=>{if(he(t)){for(var e in t)if(wd.call(t,e))return!1;return!0}return!1},C=t=>t===void 0,X=t=>ks.call(t)=="[object String]",Jo=t=>X(t)&&t.trim().length===0,Ye=t=>t===null,H=t=>C(t)||Ye(t),ke=t=>ks.call(t)=="[object Number]"&&t==t,Dt=t=>ke(t)&&t>0,mt=t=>ks.call(t)==="[object Boolean]",Wp=t=>t instanceof FormData,zp=t=>j(Dp,t),qp=t=>j(jp,t);function bd(t){return t===null||typeof t!="object"}function Wr(t,e){return{}.toString.call(t)==="[object "+e+"]"}function tl(t){return typeof Event<"u"&&Ed(t,Event)}function Ed(t,e){try{return t instanceof e}catch{return!1}}var Vp=[!0,"true",1,"1","yes"],ho=t=>j(Vp,t),Gp=[!1,"false",0,"0","no"];function At(t,e,n,i,r){return e>n&&(i.warn("min cannot be greater than max."),e=n),ke(t)?t>n?(i.warn(" cannot be greater than max: "+n+". Using max value instead."),n):e>t?(i.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(i.warn(" must be a number. using max or fallback. max: "+n+", fallback: "+r),At(r||n,e,n,i))}class Kp{constructor(e){this.tt={},this.et=e.et,this.it=At(e.bucketSize,0,100,e.rt),this.nt=At(e.refillRate,0,this.it,e.rt),this.st=At(e.refillInterval,0,864e5,e.rt)}ot(e,n){var i=Math.floor((n-e.lastAccess)/this.st);i>0&&(e.tokens=Math.min(e.tokens+i*this.nt,this.it),e.lastAccess=e.lastAccess+i*this.st)}consumeRateLimit(e){var n,i=Date.now(),r=String(e),s=this.tt[r];return s?this.ot(s,i):this.tt[r]=s={tokens:this.it,lastAccess:i},s.tokens===0||(s.tokens--,s.tokens===0&&((n=this.et)==null||n.call(this,e)),s.tokens===0)}stop(){this.tt={}}}var rt="Mobile",zr="iOS",Yt="Android",ti="Tablet",Sd=Yt+" "+ti,xd="iPad",Id="Apple",kd=Id+" Watch",Di="Safari",ni="BlackBerry",Cd="Samsung",Ad=Cd+"Browser",Pd=Cd+" Internet",Pn="Chrome",Yp=Pn+" OS",Fd=Pn+" "+zr,nl="Internet Explorer",Rd=nl+" "+rt,il="Opera",Jp=il+" Mini",rl="Edge",Td="Microsoft "+rl,Xn="Firefox",$d=Xn+" "+zr,Ki="Nintendo",Yi="PlayStation",Qn="Xbox",Md=Yt+" "+rt,Ld=rt+" "+Di,Fi="Windows",Zo=Fi+" Phone",Sc="Nokia",Xo="Ouya",Nd="Generic",Zp=Nd+" "+rt.toLowerCase(),Od=Nd+" "+ti.toLowerCase(),Qo="Konqueror",Bd="Oculus Browser",qr="Vivaldi",Dd="Yandex",Vr="Whale",ea="DuckDuckGo",jd="Pale Moon",Gr="Waterfox",ji="Brave",Ud="Google Search App",we="(\\d+(\\.\\d+)?)",po=new RegExp("Version/"+we),Xp=new RegExp(Qn,"i"),Qp=new RegExp(Yi+" \\w+","i"),eg=new RegExp(Ki+" \\w+","i"),sl=new RegExp(ni+"|PlayBook|BB10","i"),tg={"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"},Hd=function(t,e,n,i){e=e||"";var r=(function(s){return s!=null&&s.brave?ji:null})(n);return r||(i!=null&&i.detectGoogleSearchApp&&j(t,"GSA/")?Ud:j(t," OPR/")&&j(t,"Mini")?Jp:j(t," OPR/")?il:sl.test(t)?ni:j(t,"IE"+rt)||j(t,"WPDesktop")?Rd:j(t,"OculusBrowser")?Bd:j(t,Ad)?Pd:j(t,rl)||j(t,"Edg/")?Td:j(t,qr+"/")?qr:j(t,"YaBrowser/")?Dd:j(t,Vr+"/")?Vr:j(t,ea+"/")||j(t,"Ddg/")?ea:j(t,"FBIOS")?"Facebook "+rt:j(t,"UCWEB")||j(t,"UCBrowser")?"UC Browser":j(t,"CriOS")?Fd:j(t,"CrMo")||j(t,Pn)?Pn:j(t,Yt)&&j(t,Di)?Md:j(t,"FxiOS")?$d:j(t.toLowerCase(),Qo.toLowerCase())?Qo:j(t,ji+"/")?ji:((s,o)=>o&&j(o,Id)||(function(a){return j(a,Di)&&!j(a,Pn)&&!j(a,Yt)})(s))(t,e)?j(t,rt)?Ld:Di:j(t,"PaleMoon/")?jd:j(t,Gr+"/")?Gr:j(t,Xn)?Xn:j(t,"MSIE")||j(t,"Trident/")?nl:j(t,"Gecko")?Xn:"")},ng={[Rd]:[new RegExp("rv:"+we)],[Td]:[new RegExp(rl+"?\\/"+we)],[Pn]:[new RegExp("("+Pn+"|CrMo)\\/"+we)],[Fd]:[new RegExp("CriOS\\/"+we)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+we)],[Di]:[po],[Ld]:[po],[il]:[new RegExp("(Opera|OPR)\\/"+we)],[Xn]:[new RegExp(Xn+"\\/"+we)],[$d]:[new RegExp("FxiOS\\/"+we)],[Qo]:[new RegExp("Konqueror[:/]?"+we,"i")],[ni]:[new RegExp(ni+" "+we),po],[Md]:[new RegExp("android\\s"+we,"i")],[Pd]:[new RegExp(Ad+"\\/"+we)],[Bd]:[new RegExp("OculusBrowser\\/"+we)],[qr]:[new RegExp(qr+"\\/"+we)],[Dd]:[new RegExp("YaBrowser\\/"+we)],[Vr]:[new RegExp(Vr+"\\/"+we)],[ji]:[new RegExp(ji+"\\/"+we)],[ea]:[new RegExp("(DuckDuckGo|Ddg)\\/"+we)],[jd]:[new RegExp("PaleMoon\\/"+we)],[Gr]:[new RegExp(Gr+"\\/"+we)],[Ud]:[new RegExp("GSA\\/"+we)],[nl]:[new RegExp("(rv:|MSIE )"+we)],Mozilla:[new RegExp("rv:"+we)]},ig=function(t,e,n,i){var r=Hd(t,e,n,i),s=ng[r];if(C(s))return null;for(var o=0;s.length>o;o++){var a=t.match(s[o]);if(a)return parseFloat(a[a.length-2])}return null},xc=[[new RegExp(Qn+"; "+Qn+" (.*?)[);]","i"),t=>[Qn,t&&t[1]||""]],[new RegExp(Ki,"i"),[Ki,""]],[new RegExp(Yi,"i"),[Yi,""]],[sl,[ni,""]],[new RegExp(Fi,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Zo,""];if(new RegExp(rt).test(e)&&!/IEMobile\b/.test(e))return[Fi+" "+rt,""];var n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){var i=tg[n[1]]||"";return/arm/i.test(e)&&(i="RT"),[Fi,i]}return[Fi,""]}],[/((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=C(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+Yt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Yt+")","i"),t=>t&&t[2]?[Yt,[t[2],t[3],t[4]||"0"].join(".")]:[Yt,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{var e=["Mac OS X",""];return t&&t[1]&&(e[1]=[t[1],t[2],t[3]||"0"].join(".")),e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[Yp,""]],[/Linux|debian/i,["Linux",""]]],Ic=function(t){return eg.test(t)?Ki:Qp.test(t)?Yi:Xp.test(t)?Qn:new RegExp(Xo,"i").test(t)?Xo:new RegExp("("+Zo+"|WPDesktop)","i").test(t)?Zo:/iPad/.test(t)?xd:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?kd:sl.test(t)?ni:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(Sc,"i").test(t)?Sc:/(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(rt).test(t)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(t)||/pixel[\daxl ]{1,6}/i.test(t)&&!/pixel c/i.test(t)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(t)||/lmy47v/i.test(t)&&!/QTAQZ3/i.test(t)?Yt:Sd:new RegExp("(pda|"+rt+")","i").test(t)?Zp:new RegExp(ti,"i").test(t)&&!new RegExp(ti+" pc","i").test(t)?Od:""},rg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function kc(t,e){return typeof(n=t)=="string"&&rg.test(n)?t:e();var n}function fn(t){return t&&t.split("#")[0]}function ol(t,e){var n=setTimeout(t,e);return n?.unref&&n?.unref(),n}function Cc(t,e,n){return Wd.apply(this,arguments)}function Wd(){return(Wd=se((function*(t,e,n){var i;try{return yield Promise.race([t,new Promise(((r,s)=>{i=ol((()=>{try{n?.(),r()}catch(o){s(o)}}),e)}))])}finally{clearTimeout(i)}}))).apply(this,arguments)}var sg=t=>t instanceof Error,zd={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}},og=zd.info;function qd(t){if(mt(t))return{boolValue:t};if(typeof t=="number")return Number.isFinite(t)?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:{stringValue:String(t)};if(typeof t=="string")return{stringValue:t};if(U(t))return{arrayValue:{values:t.map((e=>qd(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function Kr(t){var e=[];for(var n in t){var i=t[n];Ye(i)||C(i)||e.push({key:n,value:qd(i)})}return e}function ag(t,e){var n=zd[t.level||"info"]||og,i=n.text,r=n.number,s=String(Date.now())+"000000",o={};e.distinctId&&(o.posthogDistinctId=e.distinctId),e.sessionId&&(o.sessionId=e.sessionId),e.windowId&&(o["window.id"]=e.windowId),H(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),H(e.lastActivityTimestamp)||(o.lastActivityTimestamp=String(e.lastActivityTimestamp)),e.currentUrl&&(o["url.full"]=e.currentUrl),e.screenName&&(o["screen.name"]=e.screenName),e.appState&&(o["app.state"]=e.appState),e.activeFeatureFlags&&e.activeFeatureFlags.length>0&&(o.feature_flags=e.activeFeatureFlags);var a=I({},o,t.attributes||{}),l={timeUnixNano:s,observedTimeUnixNano:s,severityNumber:r,severityText:i,body:{stringValue:t.body},attributes:Kr(a)};return t.trace_id&&(l.traceId=t.trace_id),t.span_id&&(l.spanId=t.span_id),C(t.trace_flags)||(l.flags=t.trace_flags),l}function Vd(t,e,n){return I({},t.resourceAttributes,{"service.name":t.serviceName||"unknown_service"},t.environment&&{"deployment.environment":t.environment},t.serviceVersion&&{"service.version":t.serviceVersion},{"telemetry.sdk.name":e,"telemetry.sdk.version":n})}function Gd(t,e,n,i){return{resourceLogs:[{resource:{attributes:Kr(e)},scopeLogs:[{scope:{name:n,version:i},logRecords:t}]}]}}let lg=class{constructor(t,e,n,i,r,s,o){var a;s===void 0&&(s=()=>Promise.resolve()),this._instance=t,this.Ne=e,this.rt=n,this.ut=i,this.ht=r,this.dt=s,this.vt=o,this.ct=null,this.ft=0,this.yt=0,this.bt=0,this._t=0,this.wt=!1,this.kt=e.maxBufferSize,this.xt=Math.max((a=e.maxQueueSize)!==null&&a!==void 0?a:e.maxBufferSize,e.maxBufferSize),this.St=e.flushIntervalMs,this.Ct=e.maxBatchRecordsPerPost,this.Mt=e.rateCapWindowMs,this.Tt=e.maxLogsPerInterval}reset(){this.Et(),this.ct=null,this.bt=0,this._t=0,this.wt=!1,this.ft=0,this.yt=0,this.Ct=this.Ne.maxBatchRecordsPerPost}onReconnect(){this.yt=0,this.It()}captureLog(t){if(!this._instance.isDisabled&&!this._instance.optedOut&&t!=null&&t.body){var e=this.Pt(t);if(e!==null)if(e.body){if(this.Rt()){var n={record:ag(e,this.ut())};this.ht((()=>this.At(n)))}}else this.rt.info("Log was rejected in beforeSend function")}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Log was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for log:",o),null}return i}Rt(){if(this.Tt===void 0)return!0;var t=Date.now(),e=t-this.bt;return this.Mt>e&&e>=0||(this.bt=t,this._t=0,this.wt=!1),this.Tt>this._t?(this._t++,!0):(this.wt||(this.rt.warn("captureLog dropping logs: exceeded "+this.Tt+" logs per "+this.Mt+"ms"),this.wt=!0),!1)}flush(){var t=this;return se((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return se((function*(){var e;t.Et();var n=(e=t._instance.getPersistedProperty(Ut.LogsQueue))!==null&&e!==void 0?e:[];if(n.length!==0)for(var i=n.length,r=0;n.length>0&&i>r;){var s,o;t.ft=0;var a=Math.min(n.length,t.Ct),l=n.slice(0,a),u=Gd(l.map((d=>d.record)),t.Lt(),(s=t.vt)!==null&&s!==void 0?s:t._instance.getLibraryId(),t._instance.getLibraryVersion()),c=yield t._instance.Ot(u);if(c.kind==="too-large"&&l.length>1)t.Ct=Math.max(1,Math.floor(l.length/2)),t.rt.warn("Received 413 when sending logs batch of size "+l.length+", reducing batch size to "+t.Ct);else if(c.kind==="retry-later"||(c.kind==="too-large"?t.rt.warn("Dropping a single log record after 413 with batch size 1 — the record is larger than the server cap and cannot be split further."):c.kind==="ok"&&t.Ne.maxBatchRecordsPerPost>t.Ct&&(t.Ct=Math.min(t.Ne.maxBatchRecordsPerPost,t.Ct+1)),yield t.Dt(l.length),n=(o=t._instance.getPersistedProperty(Ut.LogsQueue))!==null&&o!==void 0?o:[],r+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return se((function*(){var n,i=Math.max(0,t-e.ft),r=(n=e._instance.getPersistedProperty(Ut.LogsQueue))!==null&&n!==void 0?n:[];e._instance.setPersistedProperty(Ut.LogsQueue,r.slice(i)),yield e.dt()}))()}Lt(){return Vd(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var n=(e=this._instance.getPersistedProperty(Ut.LogsQueue))!==null&&e!==void 0?e:[];this.xt>n.length||(n.shift(),this.ft++,this.rt.info("Logs queue is full, dropping oldest record.")),n.push(t),this._instance.setPersistedProperty(Ut.LogsQueue,n),this.kt>n.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=ol((()=>{this.Nt=void 0,this.It()}),t))}qt(){var t=Math.min(Math.max(0,this.yt-1),6);return this.St*Math.pow(2,t)}jt(){var t=this._instance.getPersistedProperty(Ut.LogsQueue);return!!t&&t.length>0}shutdown(t){var e=this;return se((function*(){e.Et();var n=e.flush().catch((()=>{}));t!==void 0?yield Cc(n,t):yield n}))()}flushWithTimeout(t){var e=this;return se((function*(){var n=e.flush();yield Cc(n,t,(()=>{n.catch((()=>{}))}))}))()}It(){this.flush().then((()=>{this.yt=0}),(t=>{this.yt++,this.rt.error("PostHog logs flush failed:",t)})).finally((()=>{!this._instance.isDisabled&&this.jt()&&this.$t(this.qt())}))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}};var go=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function Ac(t){return String(t)+"000000"}function Pc(t,e,n,i){var r="";return i&&(r=Object.keys(i).sort().map((s=>JSON.stringify(s)+":"+JSON.stringify(i[s]))).join(",")),t+"\0"+e+"\0"+(n??"")+"\0"+r}let cg=class{constructor(t,e,n){this._instance=t,this.Ne=e,this.rt=n,this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Wt=0}count(t,e,n){e===void 0&&(e=1),this.Vt({name:t,type:"count",value:e,unit:n?.unit,attributes:n?.attributes})}gauge(t,e,n){this.Vt({name:t,type:"gauge",value:e,unit:n?.unit,attributes:n?.attributes})}histogram(t,e,n){this.Vt({name:t,type:"histogram",value:e,unit:n?.unit,attributes:n?.attributes})}flush(){var t=this,e=this.ct,n=(function(){var r=se((function*(){e&&(yield e.catch((()=>{}))),yield t.Zt()}));return function(){return r.apply(this,arguments)}})(),i=n().finally((()=>{this.ct===i&&(this.ct=null)}));return this.ct=i,i}drainWindow(){if(this.Bt.size===0)return null;var t=this.Bt;return this.Bt=new Map,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Gt(t)}reset(){this.Wt++,this.Et(),this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set}Vt(t){if(!this._instance.isDisabled&&!this._instance.optedOut){var e=this.Pt(t);if(e!==null)if(e.name&&typeof e.name=="string")if(typeof e.value=="number"&&Number.isFinite(e.value))if(e.type==="count"&&0>e.value)this.rt.warn("Dropping count '"+e.name+"': counters are monotonic, value must be >= 0");else{var n,i;try{n=e.attributes?I({},e.attributes):void 0,i=Pc(e.type,e.name,e.unit,n)}catch(o){return void this.rt.warn("Dropping metric '"+e.name+"': attributes could not be serialized",o)}var r=this.Bt.get(i);if(!r){if(!this.Qt())return;r={name:e.name,type:e.type,unit:e.unit,attributes:n,windowStartMs:Date.now()},this.Bt.set(i,r)}var s=this.Ut.get(e.name);s===void 0?this.Ut.set(e.name,e.type):s===e.type||this.zt.has(e.name)||(this.zt.add(e.name),this.rt.warn("Metric name '"+e.name+"' is already used as a "+s+"; recording it as a "+e.type+" too will blend both series in charts. Use a distinct name.")),this.Kt(r,e.value),this.$t()}else this.rt.warn("Dropping metric '"+e.name+"': value must be a finite number");else this.rt.warn("Dropping metric with empty name")}}Qt(){return this.Ne.maxSeriesPerFlush>this.Bt.size||(this.Ht||(this.Ht=!0,this.rt.warn("Metric series cap reached ("+this.Ne.maxSeriesPerFlush+" per flush window); dropping new series until the next flush. Reduce attribute cardinality.")),!1)}Kt(t,e){var n;switch(t.type){case"count":t.total=((n=t.total)!==null&&n!==void 0?n:0)+e;break;case"gauge":t.last=e;break;case"histogram":t.hist||(t.hist={count:0,sum:0,min:e,max:e,bucketCounts:new Array(go.length+1).fill(0)});var i=t.hist;i.count+=1,i.sum+=e,i.min=Math.min(i.min,e),i.max=Math.max(i.max,e),i.bucketCounts[(function(r,s){for(var o=0;s.length>o;o++)if(s[o]>=r)return o;return s.length})(e,go)]+=1}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Metric was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for metric:",o),null}return i}$t(){this.Nt||(this.Nt=ol((()=>{this.Nt=void 0,this.flush().catch((t=>{this.rt.error("Metrics flush failed:",t)}))}),this.Ne.flushIntervalMs))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}Zt(){var t=this;return se((function*(){if(t.Bt.size!==0){var e=t.Bt;t.Bt=new Map,t.Ht=!1,t.Ut=new Map,t.zt=new Set;var n=t.Wt,i=yield t._instance.Jt(t.Gt(e));if(n===t.Wt)switch(i.kind){case"ok":return;case"retry-later":return t.Yt(e),void t.$t();case"too-large":return void t.rt.warn("Metrics batch exceeded the server size limit and was dropped");case"fatal":return void t.rt.error("Failed to send metrics batch:",i.error)}}}))()}Gt(t){return e=this.Xt(t),n=(function(s,o,a){return I({},s.resourceAttributes,{"service.name":s.serviceName||"unknown_service"},s.environment&&{"deployment.environment":s.environment},s.serviceVersion&&{"service.version":s.serviceVersion},{"telemetry.sdk.name":o,"telemetry.sdk.version":a})})(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion()),i=this._instance.getLibraryId(),r=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:Kr(n)},scopeMetrics:[{scope:{name:i,version:r},metrics:e}]}]};var e,n,i,r}Xt(t){var e=Ac(Date.now()),n=new Map;for(var i of t.values()){var r,s=Pc(i.type,i.name,i.unit,void 0),o=n.get(s);o||(o=I({name:i.name},i.unit&&{unit:i.unit}),i.type==="count"?o.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:i.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:1,dataPoints:[]},n.set(s,o));var a=Kr((r=i.attributes)!==null&&r!==void 0?r:{}),l=Ac(i.windowStartMs);if(i.type==="count"){var u,c={attributes:a,startTimeUnixNano:l,timeUnixNano:e,asDouble:(u=i.total)!==null&&u!==void 0?u:0};o.sum.dataPoints.push(c)}else if(i.type==="gauge"){var d,f={attributes:a,timeUnixNano:e,asDouble:(d=i.last)!==null&&d!==void 0?d:0};o.gauge.dataPoints.push(f)}else i.hist&&o.histogram.dataPoints.push({attributes:a,startTimeUnixNano:l,timeUnixNano:e,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:go})}return Array.from(n.values())}Yt(t){var e,n;for(var i of t){var r=i[0],s=i[1],o=this.Bt.get(r);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,s.windowStartMs),o.type){case"count":o.total=((e=o.total)!==null&&e!==void 0?e:0)+((n=s.total)!==null&&n!==void 0?n:0);break;case"gauge":break;case"histogram":if(s.hist)if(o.hist){o.hist.count+=s.hist.count,o.hist.sum+=s.hist.sum,o.hist.min=Math.min(o.hist.min,s.hist.min),o.hist.max=Math.max(o.hist.max,s.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=s.hist.bucketCounts[a]}else o.hist=s.hist}else this.Qt()&&this.Bt.set(r,s)}}};var mr,Fc,mo;function ug(t){var e=globalThis._posthogChunkIds;if(e){var n=Object.keys(e);return mo&&n.length===Fc||(Fc=n.length,mo=n.reduce(((i,r)=>{mr||(mr={});var s=mr[r];if(s)i[s[0]]=s[1];else for(var o=t(r),a=o.length-1;a>=0;a--){var l=o[a],u=l?.filename,c=e[r];if(u&&c){i[u]=c,mr[r]=[u,c];break}}return i}),{})),mo}}class dg{constructor(e,n,i){i===void 0&&(i=[]),this.coercers=e,this.stackParser=n,this.modifiers=i}buildFromUnknown(e,n){n===void 0&&(n={});var i=n&&n.mechanism||{handled:!0,type:"generic"},r=this.buildCoercingContext(i,n,0).apply(e),s=this.buildParsingContext(n),o=this.parseStacktrace(r,s);return{$exception_list:this.convertToExceptionList(o,i),$exception_level:"error"}}modifyFrames(e){var n=this;return se((function*(){for(var i of e)i.stacktrace&&i.stacktrace.frames&&U(i.stacktrace.frames)&&(i.stacktrace.frames=yield n.applyModifiers(i.stacktrace.frames));return e}))()}coerceFallback(e){var n;return{type:"Error",value:"Unknown error",stack:(n=e.syntheticException)==null?void 0:n.stack,synthetic:!0}}parseStacktrace(e,n){var i,r;return e.cause!=null&&(i=this.parseStacktrace(e.cause,n)),e.stack!=""&&e.stack!=null&&(r=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?n.skipFirstLines:0),n.chunkIdMap)),I({},e,{cause:i,stack:r})}applyChunkIds(e,n){return e.map((i=>(i.filename&&n&&(i.chunk_id=n[i.filename]),i)))}applyCoercers(e,n){for(var i of this.coercers)if(i.match(e))return i.coerce(e,n);return this.coerceFallback(n)}applyModifiers(e){var n=this;return se((function*(){var i=e;for(var r of n.modifiers)i=yield r(i);return i}))()}convertToExceptionList(e,n){var i,r,s,o={type:e.type,value:e.value,mechanism:{type:(i=n.type)!==null&&i!==void 0?i:"generic",handled:(r=n.handled)===null||r===void 0||r,synthetic:(s=e.synthetic)!==null&&s!==void 0&&s}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,I({},n,{handled:!0}))),a}buildParsingContext(e){var n;return{chunkIdMap:ug(this.stackParser),skipFirstLines:(n=e.skipFirstLines)!==null&&n!==void 0?n:1}}buildCoercingContext(e,n,i){i===void 0&&(i=0);var r=(s,o)=>{if(4>=o){var a=this.buildCoercingContext(e,n,o);return this.applyCoercers(s,a)}};return I({},n,{syntheticException:i==0?n.syntheticException:void 0,mechanism:e,apply:s=>r(s,i),next:s=>r(s,i+1)})}}var ii="?";function ta(t,e,n,i,r){var s={platform:t,filename:e,function:n===""?ii:n,in_app:!0};return C(i)||(s.lineno=i),C(r)||(s.colno=r),s}var Kd=(t,e)=>{var n=t.indexOf("safari-extension")!==-1,i=t.indexOf("safari-web-extension")!==-1;return n||i?[t.indexOf("@")!==-1?t.split("@")[0]:ii,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},fg=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,hg=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,pg=/\((\S*)(?::(\d+))(?::(\d+))\)/,gg=(t,e)=>{var n=fg.exec(t);if(n)return ta(e,n[1],ii,+n[2],+n[3]);var i=hg.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var r=pg.exec(i[2]);r&&(i[2]=r[1],i[3]=r[2],i[4]=r[3])}var s=Kd(i[1]||ii,i[2]);return ta(e,s[1],s[0],i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},mg=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,vg=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,_g=(t,e)=>{var n=mg.exec(t);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){var i=vg.exec(n[3]);i&&(n[1]=n[1]||"eval",n[3]=i[1],n[4]=i[2],n[5]="")}var r=n[3],s=n[1]||ii,o=Kd(s,r);return ta(e,r=o[1],s=o[0],n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},Rc=/\(error: (.*)\)/;class yg{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,n){var i=X(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:i?e.stack:void 0,cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var n=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?n+": "+e.message:n}isDOMException(e){return Wr(e,"DOMException")}isDOMError(e){return Wr(e,"DOMError")}}class wg{match(e){return(function(n){switch({}.toString.call(n)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return Ed(n,Error)}})(e)}coerce(e,n){return{type:this.getType(e),value:this.getMessage(e,n),stack:this.getStack(e),cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,n){var i=e.message;return String(i.error&&typeof i.error.message=="string"?i.error.message:i)}getStack(e){return e.stacktrace||e.stack||void 0}}class bg{constructor(){}match(e){return!!Wr(e,"ErrorEvent")&&(e.error!=null||this.fe(e))}coerce(e,n){var i;if(e.error!=null)return n.apply(e.error);var r=n.apply(e.message);return I({},r,{stack:(i=this.pe(e))!==null&&i!==void 0?i:r.stack,synthetic:!0})}fe(e){return X(e.message)&&e.message.length>0}pe(e){var n=e;if(X(n.filename)&&n.filename.length>0){var i,r,s=(i=n.lineno)!==null&&i!==void 0?i:0,o=(r=n.colno)!==null&&r!==void 0?r:0;return`Error + at `+n.filename+":"+s+":"+o}}}var Eg=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class Sg{match(e){return typeof e=="string"}coerce(e,n){var i,r=this.getInfos(e),s=r[0],o=r[1];return{type:s??"Error",value:o??e,stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}getInfos(e){var n="Error",i=e,r=e.match(Eg);return r&&(n=r[1],i=r[2]),[n,i]}}var xg=["fatal","error","warning","log","info","debug"];function Yd(t,e){e===void 0&&(e=40);var n=Object.keys(t);if(n.sort(),!n.length)return"[object has no keys]";for(var i=n.length;i>0;i--){var r=n.slice(0,i).join(", ");if(e>=r.length)return i===n.length?r:r.length>e?r.slice(0,e)+"...":r}return""}class Ig{match(e){return typeof e=="object"&&e!==null}coerce(e,n){var i,r,s=this.getErrorPropertyFromObject(e);return s?n.apply(s):{type:this.getType(e),value:this.getValue(e),stack:(i=this.getStack(e))!==null&&i!==void 0?i:(r=n.syntheticException)==null?void 0:r.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return tl(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var n="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(n+=" with message: '"+e.message+"'"),n}if("message"in e&&typeof e.message=="string")return e.message;var i=this.getObjectClassName(e);return(i&&i!=="Object"?"'"+i+"'":"Object")+" captured as exception with keys: "+Yd(e)}isSeverityLevel(e){return X(e)&&!Jo(e)&&xg.indexOf(e)>=0}getStack(e){try{return X(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:X(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(var n in e)if({}.hasOwnProperty.call(e,n)){var i=e[n];if(sg(i))return i}}getObjectClassName(e){try{var n=Object.getPrototypeOf(e);return n?n.constructor.name:void 0}catch{return}}}class kg{match(e){return tl(e)}coerce(e,n){var i,r=e.constructor.name;return{type:r,value:r+" captured as exception with keys: "+Yd(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class Cg{match(e){return bd(e)}coerce(e,n){var i;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class Ag{match(e){return Wr(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!tl(e))return!1;try{var n=e.detail;return n!=null&&typeof n=="object"&&"reason"in n}catch{return!1}}coerce(e,n){var i,r=this.getUnhandledRejectionReason(e);return bd(r)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(r),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}:n.apply(r)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}}var Yr="$message",Jr="$timestamp",Pg=new Set([Yr,Jr]),vo={enabled:!0,max_bytes:32768};function Zr(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:vo.enabled,max_bytes:Rg(t.max_bytes,vo.max_bytes)}:I({},vo)}class Fg{constructor(e){this.Ke=[],this.Je=0,this.Ne=Zr(e)}setConfig(e){this.Ne=Zr(e),this.Xe()}add(e){var n=(function(r){var s;try{s=_d(r)}catch{return}try{var o=JSON.parse(s);if(!he(o))return;var a=o,l=a[Yr],u=a[Jr];return!X(l)||l.trim().length===0||!X(u)&&!ke(u)?void 0:{step:a,json:s}}catch{return}})(e);if(n){var i=(function(r){if(typeof TextEncoder<"u")return new TextEncoder().encode(r).length;for(var s=encodeURIComponent(r),o=0,a=0;s.length>a;a++)s[a]==="%"?(o+=1,a+=2):o+=1;return o})(n.json);i>this.Ne.max_bytes||(this.Ke.push({step:n.step,bytes:i}),this.Je+=i,this.Xe())}}getAttachable(){return this.Ke.map((e=>e.step))}clear(){this.Ke=[],this.Je=0}size(){return this.Ke.length}Xe(){for(;this.Je>this.Ne.max_bytes&&this.Ke.length>0;){var e=this.Ke.shift();e&&(this.Je-=e.bytes)}}}function Rg(t,e){if(!ke(t)||t===1/0||t===-1/0)return e;var n=Math.floor(t);return 0>n?e:n}var Jd=function(t,e){var n=(e===void 0?{}:e).debugEnabled,i={k(r){if(w&&(ne.DEBUG||w.POSTHOG_DEBUG||n)&&!C(w.console)&&w.console){for(var s=("__rrweb_original__"in w.console[r])?w.console[r].__rrweb_original__:w.console[r],o=arguments.length,a=new Array(o>1?o-1:0),l=1;o>l;l++)a[l-1]=arguments[l];s(t,...a)}},debug(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("debug",...s)},info(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("log",...s)},warn(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("warn",...s)},error(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("error",...s)},critical(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];console.error(t,...s)},uninitializedWarning(r){i.error("You must initialize PostHog before calling "+r)},createLogger:(r,s)=>Jd(t+" "+r,s)};return i},A=Jd("[PostHog.js]"),pe=A.createLogger,Tg=pe("[ExternalScriptsLoader]"),_o=(t,e,n)=>{if(t.config.disable_external_dependency_loading)return Tg.warn(e+" was requested but loading of external scripts is disabled."),n("Loading of external scripts is disabled");var i=P?.querySelectorAll("script");if(i){for(var r,s=function(){if(i[o].src===e){var l=i[o];return l.__posthog_loading_callback_fired?{v:n()}:(l.addEventListener("load",(u=>{l.__posthog_loading_callback_fired=!0,n(void 0,u)})),l.onerror=u=>n(u),{v:void 0})}},o=0;i.length>o;o++)if(r=s())return r.v}var a=()=>{if(!P)return n("document not found");var l=P.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=d=>{l.__posthog_loading_callback_fired=!0,n(void 0,d)},l.onerror=d=>n(d),t.config.prepare_external_dependency_script&&(l=t.config.prepare_external_dependency_script(l)),!l)return n("prepare_external_dependency_script returned null");if(t.config.external_scripts_inject_target==="head")P.head.appendChild(l);else{var u,c=P.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):P.body.appendChild(l)}};P!=null&&P.body?a():P?.addEventListener("DOMContentLoaded",a)};B.__PosthogExtensions__=B.__PosthogExtensions__||{},B.__PosthogExtensions__.loadExternalDependency=(t,e,n)=>{if(e!=="remote-config"){var i;if(t.config.strict_script_versioning)i=t.requestRouter.endpointFor("assets","/static/"+t.version+"/"+e+".js");else{var r="/static/"+e+".js?v="+t.version;if(e==="toolbar"){var s=3e5;r=r+"&t="+Math.floor(Date.now()/s)*s}i=t.requestRouter.endpointFor("assets",r)}_o(t,i,n)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");_o(t,o,n)}},B.__PosthogExtensions__.loadSiteApp=(t,e,n)=>{var i=t.requestRouter.endpointFor("api",e);_o(t,i,n)};ne.DEBUG=!1,ne.LIB_VERSION="1.415.7",ne.LIB_NAME="web";var Zd="$people_distinct_id",Ji="$device_id",yo="$device_model",Ri="__alias",Ti="__timers",na="$autocapture_disabled_server_side",ia="$heatmaps_enabled_server_side",ra="$exception_capture_enabled_server_side",sa="$error_tracking_suppression_rules",oa="$error_tracking_capture_extension_exceptions",aa="$web_vitals_enabled_server_side",al="$dead_clicks_enabled_server_side",ll="$product_tours_enabled_server_side",la="$web_vitals_allowed_metrics",An="$session_recording_remote_config",Xd="$replay_sample_rate",Qd="$replay_override_sampling",ef="$replay_override_linked_flag",tf="$replay_override_url_trigger",nf="$replay_override_event_trigger",Yn="$sesid",cl="$session_is_sampled",Sn="$enabled_feature_flags",$i="$active_feature_flags",Pr="$early_access_features",ca="$feature_flag_details",Mi="$feature_flag_payloads",Fr="$feature_flag_request_id",Xr="$minimal_flag_called_events",It="$override_feature_flags",xn="$override_feature_flag_payloads",jt="$stored_person_properties",In="$stored_group_properties",ua="$surveys",Qr="$surveys_loaded_at",da="$surveys_activated",Rr="$surveys_activated_session",Tr="$surveys_activated_timestamps",Li="ph_product_tours",Cn="$flag_call_reported",Ni="$flag_call_reported_session_id",$r="$feature_flag_errors",Ui="$feature_flag_evaluated_at",at="$user_state",fa="$client_session_props",ha="$capture_rate_limit",pa="$initial_campaign_params",ga="$initial_referrer_info",es="$initial_person_info",ts="$epp",vr="$posthog_cookieless",rf="$cookieless_mode",sf="$sdk_debug_extensions_init_method",of="$sdk_debug_extensions_init_time_ms",af="$sdk_debug_recording_script_not_loaded",ul="PostHog loadExternalDependency extension not found.",kn="on_reject",Wt="always",Hn="anonymous",vn="identified",ma="identified_only",ns="visibilitychange",is="beforeunload",Gn="$pageview",wo="$pageleave",bo="$identify",Tc="$groupidentify";function _r(t,e){U(t)&&t.forEach(e)}function ie(t,e){if(!H(t))if(U(t))t.forEach(e);else if(Wp(t))t.forEach(((i,r)=>e(i,r)));else for(var n in t)wd.call(t,n)&&e(t[n],n)}var fe=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;e>i;i++)n[i-1]=arguments[i];for(var r of n)for(var s in r)r[s]!==void 0&&(t[s]=r[s]);return t};function Mr(t){for(var e=Object.keys(t),n=e.length,i=new Array(n);n--;)i[n]=[e[n],t[e[n]]];return i}var $c=function(t){try{return t()}catch{return}},$g=function(t){return function(){try{for(var e=arguments.length,n=new Array(e),i=0;e>i;i++)n[i]=arguments[i];return t.apply(this,n)}catch(r){A.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),A.critical(r)}}},dl=function(t){var e={};return ie(t,(function(n,i){(X(n)&&n.length>0||ke(n))&&(e[i]=n)})),e},Mg=["herokuapp.com","vercel.app","netlify.app"];function Lg(t){var e=t?.hostname;if(!X(e))return!1;var n=e.split(".").slice(-2).join(".");for(var i of Mg)if(n===i)return!1;return!0}function ve(t,e,n,i){var r=i??{},s=r.capture,o=r.passive;t?.addEventListener(e,n,{capture:s!==void 0&&s,passive:o===void 0||o})}function va(t){return t.name==="ph_toolbar_internal"}var lf=t=>{if(P){try{for(var e=t+"=",n=P.cookie.split(";").filter((s=>s.length)),i=0;n.length>i;i++){for(var r=n[i];r.charAt(0)==" ";)r=r.substring(1,r.length);if(r.indexOf(e)===0)return decodeURIComponent(r.substring(e.length,r.length))}}catch{}return null}};Math.trunc||(Math.trunc=function(t){return 0>t?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return ke(t)&&isFinite(t)&&Math.floor(t)===t});class rs{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,n,i,r){if(!Number.isInteger(e)||!Number.isInteger(n)||!Number.isInteger(i)||!Number.isInteger(r)||0>e||0>n||0>i||0>r||e>0xffffffffffff||n>4095||i>1073741823||r>4294967295)throw new RangeError("invalid field value");var s=new Uint8Array(16);return s[0]=e/Math.pow(2,40),s[1]=e/Math.pow(2,32),s[2]=e/Math.pow(2,24),s[3]=e/Math.pow(2,16),s[4]=e/256,s[5]=e,s[6]=112|n>>>8,s[7]=n,s[8]=128|i>>>24,s[9]=i>>>16,s[10]=i>>>8,s[11]=i,s[12]=r>>>24,s[13]=r>>>16,s[14]=r>>>8,s[15]=r,new rs(s)}toString(){for(var e="",n=0;this.bytes.length>n;n++)e=e+(this.bytes[n]>>>4).toString(16)+(15&this.bytes[n]).toString(16),n!==3&&n!==5&&n!==7&&n!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new rs(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var n=0;16>n;n++){var i=this.bytes[n]-e.bytes[n];if(i!==0)return Math.sign(i)}return 0}}class Ng{generate(){var e=this.generateOrAbort();if(!C(e))return e;this.S=0;var n=this.generateOrAbort();if(C(n))throw new Error("Could not generate UUID after timestamp reset");return n}generateOrAbort(){var e=Date.now();if(e>this.S)this.S=e,this.C();else{if(this.S>=e+1e4)return;this.I++,this.I>4398046511103&&(this.S++,this.C())}return rs.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 Og}}var Mc,cf=t=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;t.length>e;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};w&&!C(w.crypto)&&crypto.getRandomValues&&(cf=t=>crypto.getRandomValues(t));class Og{nextUint32(){return this.R.length>this.O||(cf(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var Ht=()=>Bg().toString(),Bg=()=>(Mc||(Mc=new Ng)).generate(),wi="",Dg=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,zt={N:()=>!!P,j(t){A.error("cookieStore error: "+t)},P:lf,H(t){var e;try{e=JSON.parse(zt.P(t))||{}}catch{}return e},F(t,e,n,i,r){if(!P)return!1;try{var s="",o="",a=(function(c,d){if(d){var f=(function(p,g){if(g===void 0&&(g=P),wi)return wi;if(!g||["localhost","127.0.0.1"].includes(p))return"";for(var m=p.split("."),v=Math.min(m.length,8),E="dmn_chk_"+Ht();!wi&&v--;){var S=m.slice(v).join("."),_=E+"=1;domain=."+S+";path=/";g.cookie=_+";max-age=3",g.cookie.includes(E)&&(g.cookie=_+";max-age=0",wi=S)}return wi})(c);if(!f){var h=(p=>{var g=p.match(Dg);return g?g[0]:""})(c);h!==f&&A.info("Warning: cookie subdomain discovery mismatch",h,f),f=h}return f?"; domain=."+f:""}return""})(P.location.hostname,i);if(n){var l=new Date;l.setTime(l.getTime()+864e5*n),s="; expires="+l.toUTCString()}r&&(o="; secure");var u=t+"="+encodeURIComponent(JSON.stringify(e))+s+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&A.warn("cookieStore warning: large cookie, len="+u.length),P.cookie=u,!0}catch{return!1}},q(t,e){if(P!=null&&P.cookie)try{zt.F(t,"",-1,e)}catch{return}}},Eo=null,le={N(){if(!Ye(Eo))return Eo;var t=!0;if(C(w))t=!1;else try{var e="__mplssupport__";le.F(e,"xyz"),le.P(e)!=='"xyz"'&&(t=!1),le.q(e)}catch{t=!1}return t||A.error("localStorage unsupported; falling back to cookie store"),Eo=t,t},j(t){A.error("localStorage error: "+t)},P(t){try{return w?.localStorage.getItem(t)}catch(e){le.j(e)}return null},H(t){try{return JSON.parse(le.P(t))||{}}catch{}return null},F(t,e){try{return w?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(n){le.j(n)}return!1},q(t){try{w?.localStorage.removeItem(t)}catch(e){le.j(e)}}},jg=[Ji,"distinct_id",Yn,cl,ts,es,at],yr={},Ug={N:()=>!0,j(t){A.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]}},_n=null,be={N(){if(!Ye(_n))return _n;if(_n=!0,C(w))_n=!1;else try{var t="__support__";be.F(t,"xyz"),be.P(t)!=='"xyz"'&&(_n=!1),be.q(t)}catch{_n=!1}return _n},j(t){A.error("sessionStorage error: ",t)},P(t){try{return w?.sessionStorage.getItem(t)}catch(e){be.j(e)}return null},H(t){try{return JSON.parse(be.P(t))||null}catch{}return null},F(t,e){try{return w?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(n){be.j(n)}return!1},q(t){try{w?.sessionStorage.removeItem(t)}catch(e){be.j(e)}}};class Hg{constructor(e){this._instance=e}get Ne(){return this._instance.config}get consent(){return this.ti()?0:this.ei}isOptedOut(){return this.Ne.cookieless_mode===Wt||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===kn}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===0}isRejected(){return this.consent===0||this.consent===-1&&this.Ne.opt_out_capturing_by_default}optInOut(e){this.ii.F(this.ri,e?1:0,this.Ne.cookie_expiration,this.Ne.cross_subdomain_cookie,this.Ne.secure_cookie)}reset(){this.ii.q(this.ri,this.Ne.cross_subdomain_cookie)}get ri(){var e=this._instance.config,n=e.token,i=e.opt_out_capturing_cookie_prefix;return e.consent_persistence_name||(i?i+n:"__ph_opt_in_out_"+n)}get ei(){var e=this.ii.P(this.ri);return ho(e)?1:j(Gp,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,n=e==="localStorage"?le:zt;if(!this.ni||this.ni!==n){this.ni=n;var i=e==="localStorage"?zt:le;i.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(ho(i.P(this.ri))),i.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[He?.doNotTrack,He?.msDoNotTrack,B.doNotTrack].some((e=>ho(e)))}}function uf(t,e){var n,i=t==null||(n=t.config)==null?void 0:n.get_current_url;if(!je(i))return e;try{var r=i(e);return X(r)&&r?r:e}catch(s){return A.error("Error in get_current_url, falling back to window.location.href",s),e}}var df="__POSTHOG_TOOLBAR__",Wg=1,zg=3,qg=11;function Lc(t){return t instanceof Element&&(t.id===df||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function hn(t){return!!t&&t.nodeType===Wg}function et(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function ff(t){return!!t&&t.nodeType===zg}function hf(t){return!!t&&t.nodeType===qg&&hn(t.host)}var pf=1e3;function fl(t){return t?Is(t).split(/\s+/):[]}function Nc(t,e){var n=(function(i){var r,s=w==null||(r=w.location)==null?void 0:r.href;return C(s)?void 0:uf(i,s)})(e);return!!(n&&t&&t.some((i=>n.match(i))))}function ss(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 fl(e)}function gf(t){return H(t)?null:Is(t).split(/(\s+)/).filter((e=>Hi(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function Zi(t){var e="";return ya(t)&&!yf(t)&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;ff(n)&&n.textContent&&(e+=(i=gf(n.textContent))!==null&&i!==void 0?i:"")})),Is(e)}function So(t){var e;return C(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var hl=["a","button","form","input","select","textarea","label"];function _a(t,e){if(C(e))return!0;var n,i=function(s){if(e.some((o=>(function(a,l){var u=a.matches||a.matchesSelector||a.msMatchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.oMatchesSelector;try{return!!u&&u.call(a,l)}catch{return!1}})(s,o))))return{v:!0}};for(var r of t)if(n=i(r))return n.v;return!1}function mf(t){var e=t.parentNode;return!(!e||!hn(e))&&e}var Vg=[".ph-no-autocapture","[data-ph-no-autocapture]"],vf=["next","previous","prev",">","<"],Gg=[...vf,"+","-","−","–"],Oc=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,Bc=[".ph-no-rageclick",".ph-no-capture"],Kg=["","text","search","email","password","url","tel","number"];function Dc(t,e){if(!w||pl(t))return!1;var n,i,r,s,o;if(mt(e)?(n=!!e&&Bc,i=void 0,r=!1):(n=(s=e?.css_selector_ignorelist)!==null&&s!==void 0?s:Bc,i=e?.content_ignorelist,r=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),n===!1||r&&(function(l){return!(!l||!hn(l))&&(!!et(l,"textarea")||(et(l,"input")?j(Kg,(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=_f(t,!1).targetElementList;return!(function(l,u){if(l===!1||C(l))return!1;var c;if(l===!0)c=vf;else{if(!U(l))return!1;if(l.length>10)return A.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var f=d.safeText,h=d.ariaLabel;return c.some((p=>Oc(f,p)||Oc(h,p)))}))})(i,a.map((l=>{var u;return{safeText:Zi(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!_a(a,n)}var pl=t=>!t||et(t,"html")||!hn(t),_f=(t,e)=>{if(!w||pl(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,i=[t],r=t;r.parentNode&&!et(r,"body");)if(hf(r.parentNode))i.push(r.parentNode.host),r=r.parentNode.host;else{var s=mf(r);if(!s)break;if(e||hl.indexOf(s.tagName.toLowerCase())>-1)n=!0;else try{var o=w.getComputedStyle(s);o&&o.getPropertyValue("cursor")==="pointer"&&(n=!0)}catch{}i.push(s),r=s}return{parentIsUsefulElement:n,targetElementList:i}};function ya(t){for(var e=new Set,n=0,i=t;i.parentNode&&!et(i,"body");i=i.parentNode){if(n++>=pf||e.has(i))return!1;e.add(i);var r=ss(i);if(j(r,"ph-sensitive")||j(r,"ph-no-capture"))return!1}if(j(ss(t),"ph-include"))return!0;var s=t.type||"";if(X(s))switch(s.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!X(o)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(o.replace(/[^a-zA-Z0-9]/g,""))}function yf(t){return!!(et(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||et(t,"select")||et(t,"textarea")||t.getAttribute("contenteditable")==="true")}var jc=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}))$"),Uc=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,Yg=[16,15,14,13],Jg=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),Hc=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),Wc=/[0-9A-Za-z_]/;function Zg(t){for(var e=0,n=!1,i=t.length-1;i>=0;i--){var r=t.charCodeAt(i)-48;n&&(r*=2)>9&&(r-=9),e+=r,n=!n}return e%10==0}function Hi(t,e){if(e===void 0&&(e=!0),H(t))return!1;if(X(t)){t=Is(t);var n=e?jc.test((t||"").replace(/[- ]/g,"")):(function(r){var s;for(Uc.lastIndex=0;s=Uc.exec(r);){var o=s[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of Yg){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(jc.test(d)&&Zg(d))return!0}}}return!1})(t);if(n)return!1;var i=e?Jg.test(t):(function(r){var s;for(Hc.lastIndex=0;s=Hc.exec(r);){var o=s[1],a=s[3];if(!(o&&a&&Wc.test(o)&&Wc.test(a)))return!0}return!1})(t);if(i)return!1}return!0}function zc(t){var e=Zi(t);return Hi(e=(e+" "+wf(t)).trim())?e:""}function wf(t){var e="";return t&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;if(n&&((i=n.tagName)==null?void 0:i.toLowerCase())==="span")try{var r=Zi(n);e=(e+" "+r).trim(),n.childNodes&&n.childNodes.length&&(e=(e+" "+wf(n)).trim())}catch(s){A.error("[AutoCapture]",s)}})),e}function qc(t){return t.replace(/"|\\"/g,'\\"')}function Xg(t){var e=t.attr__class;if(e)return U(e)?e:fl(e)}var wr=pe("[Dead Clicks]"),Qg=()=>!0,em=t=>{var e,n=!((e=t.instance.persistence)==null||!e.get_property(al)),i=t.instance.config.capture_dead_clicks;return mt(i)?i:!!he(i)||n};class Vc{get lazyLoadedDeadClicksAutocapture(){return this.si}constructor(e,n,i){this.instance=e,this.isEnabled=n,this.onCapture=i,this.startIfEnabledOrStop()}onRemoteConfig(e){if(e.ok){var n=e.config;"captureDeadClicks"in n&&(this.instance.persistence&&this.instance.persistence.register({[al]:n.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var n,i;(n=B.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture?e():(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"dead-clicks-autocapture",(r=>{r?wr.error("failed to load script",r):e()}))}oi(){var e;if(P){if(!this.si&&(e=B.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var n=he(this.instance.config.capture_dead_clicks)?I({},this.instance.config.capture_dead_clicks):{};n.__onCapture=this.onCapture,this.onCapture&&(n.capture_dead_swipes=!1),this.si=B.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.si.start(P),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 xo=pe("[SegmentIntegration]"),bf="posthog-js";function Ef(t,e){var n=e===void 0?{}:e,i=n.organization,r=n.projectId,s=n.prefix,o=n.severityAllowList,a=o===void 0?["error"]:o,l=n.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,f,h,p,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var v,E=((d=c.exception)==null?void 0:d.values)||[],S=E.map((b=>I({},b,{stacktrace:b.stacktrace?I({},b.stacktrace,{type:"raw",frames:(b.stacktrace.frames||[]).map((k=>I({},k,{platform:"web:javascript"})))}):void 0}))),_={$exception_message:((f=E[0])==null?void 0:f.value)||c.message,$exception_type:(h=E[0])==null?void 0:h.type,$exception_level:c.level,$exception_list:S,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((p=E[0])==null?void 0:p.value)||c.message,$sentry_exception_type:(g=E[0])==null?void 0:g.type,$sentry_tags:c.tags};return i&&r&&(_.$sentry_url=(s||"https://sentry.io/organizations/")+i+"/issues/?project="+r+"&query="+c.event_id),u&&((v=t.exceptions)==null||v.sendExceptionEvent(_)),c}}class tm{constructor(e,n,i,r,s,o){this.name=bf,this.setupOnce=function(a){a(Ef(e,{organization:n,projectId:i,prefix:r,severityAllowList:s,sendExceptionsToPostHog:o==null||o}))}}}class Gc{constructor(e){this.li=(n,i,r)=>{r&&(r.noSessionId||r.activityTimeout||r.sessionPastMaximumLength||r.crossTabAdoption)&&(A.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:n,changeReason:r}),this.ui=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.hi()}hi(){var e;this.di=(e=this._instance.sessionManager)==null?void 0:e.onSessionId(this.li)}destroy(){var e;(e=this.di)==null||e.call(this),this.di=void 0}doPageView(e,n){var i,r=this.vi(e,n);return this.ui={pathname:(i=w?.location.pathname)!==null&&i!==void 0?i:"",pageViewId:n,timestamp:e},this._instance.scrollManager.resetContext(),r}doPageLeave(e){var n;return this.vi(e,(n=this.ui)==null?void 0:n.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.ui)==null?void 0:e.pageViewId}}vi(e,n){var i=this.ui;if(!i)return{$pageview_id:n};var r={$pageview_id:n,$prev_pageview_id:i.pageViewId},s=this._instance.scrollManager.getContext();if(s&&!this._instance.config.disable_scroll_properties){var o=s.maxScrollHeight,a=s.lastScrollY,l=s.maxScrollY,u=s.maxContentHeight,c=s.lastContentY,d=s.maxContentY;if(!(C(o)||C(a)||C(l)||C(u)||C(c)||C(d))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),d=Math.ceil(d);var f=o>1?At(a/o,0,1,A):1,h=o>1?At(l/o,0,1,A):1,p=u>1?At(c/u,0,1,A):1,g=u>1?At(d/u,0,1,A):1;r=fe(r,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:f,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:h,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:p,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return i.pathname&&(r.$prev_pageview_pathname=i.pathname),i.timestamp&&(r.$prev_pageview_duration=(e.getTime()-i.timestamp.getTime())/1e3),r}}var Io=["flags","surveys"],nm={[Zd]:{exposure:"hidden"},[Ri]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[Ti]:{exposure:"hidden"},[na]:{exposure:"event"},[ia]:{exposure:"hidden"},[ra]:{exposure:"event"},[sa]:{exposure:"hidden"},[oa]:{exposure:"event"},[aa]:{exposure:"event"},[al]:{exposure:"event"},[ll]:{exposure:"hidden"},[la]:{exposure:"event"},[An]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[Yn]:{exposure:"hidden"},[cl]:{exposure:"event"},[Xd]:{exposure:"event",shouldSkipFromEventProperties:t=>Ye(t)},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},$sess_rec_flush_size:{exposure:"hidden"},[Sn]:{exposure:"hidden",storageGroup:"flags"},[$i]:{exposure:"hidden",storageGroup:"flags"},[Pr]:{exposure:"hidden"},[ca]:{exposure:"hidden",storageGroup:"flags"},[Mi]:{exposure:"hidden",storageGroup:"flags"},[Fr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[Xr]:{exposure:"hidden",storageGroup:"flags"},[It]:{exposure:"hidden"},[xn]:{exposure:"hidden"},[jt]:{exposure:"hidden"},[In]:{exposure:"hidden"},[ua]:{exposure:"hidden",storageGroup:"surveys"},[Qr]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[da]:{exposure:"event"},[Rr]:{exposure:"hidden"},[Tr]:{exposure:"hidden"},[Li]:{exposure:"hidden"},$product_tours_activated:{exposure:"hidden"},$product_tours_activated_session:{exposure:"hidden"},$conversations_widget_session_id:{exposure:"event"},$conversations_ticket_id:{exposure:"event"},$conversations_widget_state:{exposure:"event"},$conversations_user_traits:{exposure:"event"},[Cn]:{exposure:"hidden"},[Ni]:{exposure:"hidden"},[$r]:{exposure:"hidden"},[Ui]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[at]:{exposure:"hidden"},[fa]:{exposure:"hidden"},[ha]:{exposure:"hidden"},[pa]:{exposure:"hidden"},[ga]:{exposure:"hidden"},[es]:{exposure:"hidden"},[ts]:{exposure:"hidden"},[Qd]:{exposure:"event"},[ef]:{exposure:"event"},[tf]:{exposure:"event"},[nf]:{exposure:"event"},[sf]:{exposure:"event"},[of]:{exposure:"event"},[af]:{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"}},im=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],yn=t=>{var e=nm[t];if(e)return e;for(var n of im){var i=n[1];if(t.indexOf(n[0])===0)return i}},Jn=(t,e)=>{try{return JSON.stringify(t,((n,i)=>typeof i=="bigint"?i.toString():i),e)}catch{return _d(t)}},os=t=>{var e=P?.createElement("a");return C(e)?null:(e.href=t,e)},ri=function(t,e){for(var n,i=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),r=0;i.length>r;r++){var s=i[r].split("=");if(s[0]===e){n=s;break}}if(!U(n)||2>n.length)return"";var o=n[1];try{o=decodeURIComponent(o)}catch{A.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},Xi=function(t,e,n){if(!t||!e||!e.length)return t;for(var i=t.split("#"),r=i[1],s=(i[0]||"").split("?"),o=s[1],a=s[0],l=(o||"").split("&"),u=[],c=0;l.length>c;c++){var d=l[c].split("=");U(d)&&(e.includes(d[0])?u.push(d[0]+"="+n):u.push(l[c]))}var f=a;return o!=null&&(f+="?"+u.join("&")),r!=null&&(f+="#"+r),f},as=function(t,e){var n=t.match(new RegExp(e+"=([^&]*)"));return n?n[1]:null},Sf=(t,e)=>t>=e&&gd(),xf=(t,e,n,i)=>{if(t===0){if(gd()){var r=e+1;return r===n&&i(),r}return e}return 0},br="https?://(.*)",si=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],rm=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...si],Qi="",sm=["li_fat_id"];function If(t,e,n){if(!P)return{};var i,r=e?[...si,...n||[]]:[],s=kf(Xi(P.URL,r,Qi),t),o=(i={},ie(sm,(function(a){var l=lf(a);i[a]=l||null})),i);return fe(o,s)}function kf(t,e){var n=rm.concat(e||[]),i={};return ie(n,(function(r){var s=ri(t,r);i[r]=s||null})),i}function Cf(t){var e=(function(s){return s?s.search(br+"google.([^/?]*)")===0?"google":s.search(br+"bing.com")===0?"bing":s.search(br+"yahoo.com")===0?"yahoo":s.search(br+"duckduckgo.com")===0?"duckduckgo":null:null})(t),n=e!="yahoo"?"q":"p",i={};if(!Ye(e)){i.$search_engine=e;var r=P?ri(P.referrer,n):"";r.length&&(i.ph_keyword=r)}return i}function Kc(){return navigator.language||navigator.userLanguage}var ls="$direct";function Af(){return P?.referrer||ls}function Pf(t,e,n){n===void 0&&(n=!1);var i=t?[...si,...e||[]]:[],r=n?fn(me?.href):me?.href,s=r?.substring(0,1e3);return{r:Af().substring(0,1e3),u:s?Xi(s,i,Qi):void 0}}function Ff(t,e){var n;e===void 0&&(e=!1);var i=t.r,r=t.u,s=e?fn(r):r,o={$referrer:i,$referring_domain:i==null?void 0:i==ls?ls:(n=os(i))==null?void 0:n.host};if(s){o.$current_url=s;var a=os(s);o.$host=a?.host,o.$pathname=a?.pathname;var l=kf(s);fe(o,l)}if(i){var u=Cf(i);fe(o,u)}return o}function Rf(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function om(){try{return new Date().getTimezoneOffset()}catch{return}}var am={flags:Ui,surveys:Qr},lm=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],Wn="main";class ko{constructor(e,n,i){if(i===void 0&&(i=!0),this.ci={},this.fi=!1,this.pi=!1,this.Ne=e,this.gi=i,this.props={},this.mi=void 0,this.yi=(s=>{var o="";return s.token&&(o=s.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),s.persistence_name?"ph_"+s.persistence_name:"ph_"+o+"_posthog"})(e),this.ii=this.bi(e),this.pi=this.wi(e),this.load(),e.debug&&A.info("Persistence loaded",e.persistence,I({},this.props)),this.update_config(e,e,n),this.save(),w){var r=()=>this.flush();ve(w,"beforeunload",r,{capture:!1}),ve(w,"pagehide",r,{capture:!1})}}ki(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return ke(n)&&n>0?n:0}isDisabled(){return!!this.xi}bi(e){lm.indexOf(e.persistence.toLowerCase())===-1&&(A.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var n,i=(function(o,a){o===void 0&&(o=[]),a===void 0&&(a=!1);var l=[...jg,...o];return I({},le,{H(u){try{var c={};try{c=zt.H(u)||{}}catch{}var d,f=JSON.parse(le.P(u)||"{}");if(a){var h={};for(var p in c){var g=c[p];Ye(g)||g===""||(h[p]=g)}d=fe(f,h)}else d=fe(c,f);return le.F(u,d),d}catch{}return null},F(u,c,d,f,h,p){var g=le.F(u,c,void 0,void 0,p);try{var m={};l.forEach((v=>{c[v]&&(m[v]=c[v])})),Object.keys(m).length&&zt.F(u,m,d,f,h,p)}catch(v){le.j(v)}return g},q(u,c){try{w?.localStorage.removeItem(u),zt.q(u,c)}catch(d){le.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),r=!1,s=e.persistence.toLowerCase();return s==="localstorage"&&le.N()?(n=le,r=!0):s==="localstorage+cookie"&&i.N()?(n=i,r=!0):s==="sessionstorage"&&be.N()?n=be:s==="memory"?n=Ug:s==="cookie"?n=zt:i.N()?(n=i,r=!0):n=zt,this.fi=r,n}Si(e){return this.yi+"__"+e}wi(e){return this.fi&&!!e.split_storage}properties(){var e={};return ie(this.props,((n,i)=>{var r=yn(i);if(!r||r.exposure==="event"){if(r!=null&&r.shouldSkipFromEventProperties!=null&&r.shouldSkipFromEventProperties(n))return;e[i]=n}})),e}load(){if(!this.xi){var e=this.ii.H(this.yi);e&&(this.props=fe({},e)),this.pi&&this.Ci()}}Ci(){for(var e of Io){var n=le.H(this.Si(e));if(n&&!Kt(n)){var i=this.Mi(e);i.persisted=!0,this.Ti(e)||(i.fingerprint=this.Ei(n,e)),this.Ii(e,n)||fe(this.props,n)}}}Ti(e){return Object.keys(this.props).some((n=>{var i;return((i=yn(n))==null?void 0:i.storageGroup)===e}))}Ii(e,n){var i=am[e];if(!i)return!1;var r=n[i],s=this.props[i];return ke(r)&&ke(s)&&s>r}refreshKey(e){var n;if(!this.xi){var i=this.pi?(n=yn(e))==null?void 0:n.storageGroup:void 0,r=i?le.H(this.Si(i)):this.ii.H(this.yi);if(r&&e in r)this.Pi(e,r[e]);else{if(i){var s=this.ii.H(this.yi);if(s&&e in s)return void this.Pi(e,s[e])}this.Ri(e)}}}save(){if(!this.xi){var e=this.ki();e>0?C(this.Ai)&&(this.Ai=setTimeout((()=>{this.Ai=void 0,this.Fi()}),e)):this.Fi()}}flush(){C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0,this.Fi())}Fi(){this.xi||(this.pi?this.Li():this.Oi(this.ii,this.yi,this.props,Wn))}Li(){var e=this.Di(),n=e.main,i=e.groups;for(var r of(this.Oi(this.ii,this.yi,n,Wn),Io)){var s,o=i[r];(!Kt(o)||(s=this.ci[r])!=null&&s.persisted)&&this.Oi(le,this.Si(r),o,r)}}Di(){var e={},n={flags:{},surveys:{}};return ie(this.props,((i,r)=>{var s,o=(s=yn(r))==null?void 0:s.storageGroup;o?n[o][r]=i:e[r]=i})),{main:e,groups:n}}Ei(e,n){if(n===Wn)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var i={};return ie(e,((r,s)=>{var o;i[s]=(o=yn(s))!=null&&o.volatile?"__volatile__":r})),JSON.stringify(i)}Oi(e,n,i,r){var s=this.Mi(r);if(r===Wn||s.dirty||C(s.fingerprint)){var o;try{if((o=this.Ei(i,r))===s.fingerprint)return void(s.dirty=!1)}catch{o=void 0}e.F(n,i,this.$i,this.Ni,this.qi,this.Ne.debug)?(s.dirty=!1,r!==Wn&&(s.persisted=!0),C(o)||(s.fingerprint=o)):this.Ne.debug&&A.warn('failed to persist storage entry "'+n+'"; will retry on next save')}}remove(e){var n=(e===void 0?{}:e).keepGroupEntries,i=n!==void 0&&n;if(C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0),this.ii.q(this.yi,!1),this.ii.q(this.yi,!0),!i&&this.gi)for(var r of Io)le.q(this.Si(r));i?delete this.ci[Wn]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,n,i){if(he(e)){C(n)&&(n="None"),this.$i=C(i)?this.ji:i;var r=!1;if(ie(e,((s,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==n||(this.Pi(o,s),r=!0)})),r)return this.save(),!0}return!1}register(e,n){if(he(e)){this.$i=C(n)?this.ji:n;var i=!1;if(ie(e,((r,s)=>{e.hasOwnProperty(s)&&(this.props[s]!==r||he(r)||U(r))&&(this.Pi(s,r),i=!0)})),i)return this.save(),!0}return!1}unregister(e){var n=typeof e=="string"?[e]:e,i=!1;for(var r of n)r in this.props&&(this.Ri(r),i=!0);i&&this.save()}update_campaign_params(){var e=P?.URL;if(e!==this.mi){var n=If(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);Kt(dl(n))||this.register(n),this.mi=e}}update_search_keyword(){var e;this.register((e=P?.referrer)?Cf(e):{})}update_referrer_info(){var e;this.register_once({$referrer:Af(),$referring_domain:P!=null&&P.referrer&&((e=os(P.referrer))==null?void 0:e.host)||ls},void 0)}set_initial_person_info(){this.props[pa]||this.props[ga]||this.register_once({[es]:Pf(this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties,this.Ne.disable_capture_url_hashes)},void 0)}get_initial_props(){var e={};ie([ga,pa],(r=>{var s=this.props[r];s&&ie(s,(function(o,a){e["$initial_"+Yo(a)]=o}))}));var n=this.props[es];if(n){var i=(function(r,s){s===void 0&&(s=!1);var o=Ff(r,s),a={};return ie(o,(function(l,u){a["$initial_"+Yo(u)]=l})),a})(n,this.Ne.disable_capture_url_hashes);fe(e,i)}return e}safe_merge(e){return ie(this.props,(function(n,i){i in e||(e[i]=n)})),e}update_config(e,n,i){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!i),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var r=e.persistence!==n.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((f,h)=>f===d[h]))})(e.cookie_persisted_properties||[],n.cookie_persisted_properties||[]),s=r?this.bi(e):this.ii,o=this.wi(e);if(r||o!==this.pi){var a=this.props;this.clear(),this.ii=s,this.pi=o,this.props=a,this.save()}}set_disabled(e){this.xi=e,this.xi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ni&&(this.Ni=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this.qi&&(this.qi=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,n){var i=this.props[Ti]||{};i[e]=n,this.Pi(Ti,i),this.save()}remove_event_timer(e){var n=this.props[Ti]||{},i=n[e];return C(i)||(delete n[e],this.Pi(Ti,n),this.save()),i}get_property(e){return this.props[e]}set_property(e,n){this.Pi(e,n),this.save()}Pi(e,n){var i;this.props[e]=n,(i=yn(e))!=null&&i.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var n,i=(n=yn(e))==null?void 0:n.storageGroup;i&&(this.Mi(i).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function Er(t){var e=!0;return{dispose(){if(e){e=!1;var n=t();n&&je(n.then)&&n.then(void 0,(()=>{}))}}}}var Ue={GZipJS:"gzip-js",Base64:"base64"},bi={Activation:"events",Cancellation:"cancelEvents"},Co={Popover:"popover",API:"api",Widget:"widget"},qt={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},Ao={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},wa={Popover:"popover",Inline:"inline"},cm={SHOWN:"product tour shown"},Yc={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},Jc=pe("[RateLimiter]");class um{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=n=>{var i=n.text;if(i&&i.length)try{(JSON.parse(i).quota_limited||[]).forEach((r=>{Jc.info((r||"events")+" is quota limited."),this.serverLimits[r]=new Date().getTime()+6e4}))}catch(r){return void Jc.warn('could not rate limit - continuing. Error: "'+r?.message+'"',{text:i})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var n,i,r;e===void 0&&(e=!1);var s=this.captureEventsBurstLimit,o=this.captureEventsPerSecond,a=new Date().getTime(),l=(n=(i=this.instance.persistence)==null?void 0:i.get_property(ha))!==null&&n!==void 0?n:{tokens:s,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>s&&(l.tokens=s);var u=1>l.tokens;if(u||e||(l.tokens=Math.max(0,l.tokens-1)),u&&!e){var c=(ke(l.dropped)?l.dropped:0)+1;l.dropped=c,!this.lastEventRateLimited&&this.Hi(c)&&(l.dropped=0)}return this.lastEventRateLimited=u,(r=this.instance.persistence)==null||r.set_property(ha,l),{isRateLimited:u,remainingTokens:l.tokens}}Ui(e){var n=this.instance.config.property_denylist;return!U(n)||!n.includes(e)}zi(){var e;if(this.Ui("$current_url")&&this.Ui("$pathname")&&me!=null&&me.pathname)return""+((e=me.origin)!==null&&e!==void 0?e:"")+me.pathname}Hi(e){var n,i,r=this.captureEventsBurstLimit,s=this.captureEventsPerSecond,o=this.zi(),a=this.Ui("$session_id")?(n=(i=this.instance).get_session_id)==null?void 0:n.call(i):void 0,l=[e+" event(s) dropped since the last warning",o?"triggered on "+o:void 0,a?"session "+a:void 0].filter(Boolean).join(", ");return!!this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited: "+l+". Config is set to "+s+" events per second and "+r+" events burst limit."},{skip_client_rate_limiting:!0})}isServerRateLimited(e){var n=this.serverLimits[e||"events"]||!1;return n!==!1&&new Date().getTime()e(this.remoteConfig))):e()}Vi(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:e})}load(){try{if(this.remoteConfig)return an.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void an.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return an.info("No config found after loading remote JS config. Falling back to JSON."),void this.Vi((n=>{this.Zi(n.json,n),this.Gi()}));this.Zi(e),this.Gi()}))}catch(e){an.error("Error loading remote config",e),this.Zi()}}stop(){this.Ki&&(clearInterval(this.Ki),this.Ki=void 0)}refresh(){!this._instance.Qi()&&P&&P.visibilityState!=="hidden"&&this._instance.reloadFeatureFlags()}Gi(){var e;if(!this.Ki){var n=(e=this._instance.config.remote_config_refresh_interval_ms)!==null&&e!==void 0?e:3e5;n!==0&&(this.Ki=setInterval((()=>{this.refresh()}),n))}}Zi(e,n){!e&&n&&(n.statusCode===0?n.error||an.warn("Failed to fetch remote config from PostHog."):an.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(r){an.error("Error applying remote config",r)}if(e?.hasFeatureFlags!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var i;(i=this._instance.featureFlags)==null||i.ensureFlagsLoaded()}catch(r){an.error("Error loading feature flags",r)}}}var ct=Uint8Array,Ke=Uint16Array,oi=Uint32Array,gl=new ct([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]),ml=new ct([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]),Zc=new ct([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),$f=function(t,e){for(var n=new Ke(31),i=0;31>i;++i)n[i]=e+=1<i;++i)for(var s=n[i];n[i+1]>s;++s)r[s]=s-n[i]<<5|i;return[n,r]},Mf=$f(gl,2),ba=Mf[1];Mf[0][28]=258,ba[258]=28;for(var Xc=$f(ml,0)[1],Lf=new Ke(32768),_e=0;32768>_e;++_e){var zn=(43690&_e)>>>1|(21845&_e)<<1;Lf[_e]=((65280&(zn=(61680&(zn=(52428&zn)>>>2|(13107&zn)<<2))>>>4|(3855&zn)<<4))>>>8|(255&zn)<<8)>>>1}var Wi=function(t,e,n){for(var i=t.length,r=0,s=new Ke(e);i>r;++r)++s[t[r]-1];var o,a=new Ke(e);for(r=0;e>r;++r)a[r]=a[r-1]+s[r-1]<<1;for(o=new Ke(i),r=0;i>r;++r)o[r]=Lf[a[t[r]-1]++]>>>15-t[r];return o},Mn=new ct(288);for(_e=0;144>_e;++_e)Mn[_e]=8;for(_e=144;256>_e;++_e)Mn[_e]=9;for(_e=256;280>_e;++_e)Mn[_e]=7;for(_e=280;288>_e;++_e)Mn[_e]=8;var cs=new ct(32);for(_e=0;32>_e;++_e)cs[_e]=5;var dm=Wi(Mn,9),fm=Wi(cs,5),Nf=function(t){return(t/8>>0)+(7&t&&1)},Of=function(t,e,n){(n==null||n>t.length)&&(n=t.length);var i=new(t instanceof Ke?Ke:t instanceof oi?oi:ct)(n-e);return i.set(t.subarray(e,n)),i},Ot=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8},Ei=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8,t[i+2]|=n>>>16},Po=function(t,e){for(var n=[],i=0;t.length>i;++i)t[i]&&n.push({s:i,f:t[i]});var r=n.length,s=n.slice();if(!r)return[new ct(0),0];if(r==1){var o=new ct(n[0].s+1);return o[n[0].s]=1,[o,1]}n.sort((function(b,k){return b.f-k.f})),n.push({s:-1,f:25001});var a=n[0],l=n[1],u=0,c=1,d=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=r-1;)a=n[n[d].f>n[u].f?u++:d++],l=n[u!=c&&n[d].f>n[u].f?u++:d++],n[c++]={s:-1,f:a.f+l.f,l:a,r:l};var f=s[0].s;for(i=1;r>i;++i)s[i].s>f&&(f=s[i].s);var h=new Ke(f+1),p=Ea(n[c-1],h,0);if(p>e){i=0;var g=0,m=p-e,v=1<i;++i){var E=s[i].s;if(e>=h[E])break;g+=v-(1<>>=m;g>0;){var S=s[i].s;e>h[S]?g-=1<=0&&g;--i){var _=s[i].s;h[_]==e&&(--h[_],++g)}p=e}return[new ct(h),p]},Ea=function(t,e,n){return t.s==-1?Math.max(Ea(t.l,e,n+1),Ea(t.r,e,n+1)):e[t.s]=n},Qc=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new Ke(++e),i=0,r=t[0],s=1,o=function(l){n[i++]=l},a=1;e>=a;++a)if(t[a]==r&&a!=e)++s;else{if(!r&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(r),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(r);s=1,r=t[a]}return[n.subarray(0,i),e]},Si=function(t,e){for(var n=0,i=0;e.length>i;++i)n+=t[i]*e[i];return n},Sa=function(t,e,n){var i=n.length,r=Nf(e+2);t[r]=255&i,t[r+1]=i>>>8,t[r+2]=255^t[r],t[r+3]=255^t[r+1];for(var s=0;i>s;++s)t[r+s+4]=n[s];return 8*(r+4+i)},eu=function(t,e,n,i,r,s,o,a,l,u,c){Ot(e,c++,n),++r[256];for(var d=Po(r,15),f=d[0],h=d[1],p=Po(s,15),g=p[0],m=p[1],v=Qc(f),E=v[0],S=v[1],_=Qc(g),b=_[0],k=_[1],T=new Ke(19),x=0;E.length>x;++x)T[31&E[x]]++;for(x=0;b.length>x;++x)T[31&b[x]]++;for(var F=Po(T,7),$=F[0],O=F[1],L=19;L>4&&!$[Zc[L-1]];--L);var N,K,V,M,R=u+5<<3,Z=Si(r,Mn)+Si(s,cs)+o,Ce=Si(r,f)+Si(s,g)+o+14+3*L+Si(T,$)+(2*T[16]+3*T[17]+7*T[18]);if(Z>=R&&Ce>=R)return Sa(e,c,t.subarray(l,l+u));if(Ot(e,c,1+(Z>Ce)),c+=2,Z>Ce){N=Wi(f,h),K=f,V=Wi(g,m),M=g;var oe=Wi($,O);for(Ot(e,c,S-257),Ot(e,c+5,k-1),Ot(e,c+10,L-4),c+=14,x=0;L>x;++x)Ot(e,c+3*x,$[Zc[x]]);c+=3*L;for(var ye=[E,b],$e=0;2>$e;++$e){var ae=ye[$e];for(x=0;ae.length>x;++x)Ot(e,c,oe[Ie=31&ae[x]]),c+=$[Ie],Ie>15&&(Ot(e,c,ae[x]>>>5&127),c+=ae[x]>>>12)}}else N=dm,K=Mn,V=fm,M=cs;for(x=0;a>x;++x)if(i[x]>255){var Ie;Ei(e,c,N[257+(Ie=i[x]>>>18&31)]),c+=K[Ie+257],Ie>7&&(Ot(e,c,i[x]>>>23&31),c+=gl[Ie]);var Se=31&i[x];Ei(e,c,V[Se]),c+=M[Se],Se>3&&(Ei(e,c,i[x]>>>5&8191),c+=ml[Se])}else Ei(e,c,N[i[x]]),c+=K[i[x]];return Ei(e,c,N[256]),c+K[256]},hm=new oi([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),pm=(function(){for(var t=new oi(256),e=0;256>e;++e){for(var n=e,i=9;--i;)n=(1&n&&3988292384)^n>>>1;t[e]=n}return t})(),Fo=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8};function gm(t,e){e===void 0&&(e={});var n=(function(){var d=4294967295;return{p(f){for(var h=d,p=0;f.length>p;++p)h=pm[255&h^f[p]]^h>>>8;d=h},d(){return 4294967295^d}}})(),i=t.length;n.p(t);var r,s,o,a,l,u=(a=10+((r=e).filename&&r.filename.length+1||0),l=8,(function(d,f,h,p,g,m){var v=d.length,E=new ct(p+v+5*(1+Math.floor(v/7e3))+g),S=E.subarray(p,E.length-g),_=0;if(!f||8>v)for(var b=0;v>=b;b+=65535){var k=b+65535;v>k?_=Sa(S,_,d.subarray(b,k)):(S[b]=!0,_=Sa(S,_,d.subarray(b,v)))}else{for(var T=hm[f-1],x=T>>>13,F=8191&T,$=(1<b;++b){var Ie=V(b),Se=32767&b,De=L[Ie];if(O[Se]=De,L[Ie]=Se,b>=$e){var wt=v-b;if((Ce>7e3||ye>24576)&&wt>423){_=eu(d,S,0,M,R,Z,oe,ye,ae,b-ae,_),ye=Ce=oe=0,ae=b;for(var ge=0;286>ge;++ge)R[ge]=0;for(ge=0;30>ge;++ge)Z[ge]=0}var Je=2,bt=0,mn=F,Re=Se-De&32767;if(wt>2&&Ie==V(b-Re))for(var Pe=Math.min(x,wt)-1,$t=Math.min(32767,b),Dn=Math.min(258,wt);$t>=Re&&--mn&&Se!=De;){if(d[b+Je]==d[b+Je-Re]){for(var qe=0;Dn>qe&&d[b+qe]==d[b+qe-Re];++qe);if(qe>Je){if(Je=qe,bt=Re,qe>Pe)break;var jn=Math.min(Re,qe-2),Mt=0;for(ge=0;jn>ge;++ge){var Lt=b-Re+ge+32768&32767,ut=Lt-O[Lt]+32768&32767;ut>Mt&&(Mt=ut,De=Lt)}}}Re+=(Se=De)-(De=O[Se])+32768&32767}if(bt){M[ye++]=268435456|ba[Je]<<18|Xc[bt];var sn=31&ba[Je],mi=31&Xc[bt];oe+=gl[sn]+ml[mi],++R[257+sn],++Z[mi],$e=b+Je,++Ce}else M[ye++]=d[b],++R[d[b]]}}_=eu(d,S,!0,M,R,Z,oe,ye,ae,b-ae,_)}return Of(E,0,p+Nf(_)+g)})(s=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):12+o.mem,a,l)),c=u.length;return(function(d,f){var h=f.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>f.level?4:f.level==9?2:0,d[9]=3,f.mtime!=0&&Fo(d,4,Math.floor(new Date(f.mtime||Date.now())/1e3)),h){d[3]=8;for(var p=0;h.length>=p;++p)d[p+10]=h.charCodeAt(p)}})(u,e),Fo(u,c-8,n.d()),Fo(u,c-4,i),u}var mm=!!Vo||!!el,Bf="text/plain",Lr=!1,Df=(t,e)=>{var n=t.split("#"),i=n[1],r=n[0].split("?"),s=r[0],o=r[1];if(!o)return t;var a=o.split("&").filter((l=>l.split("=")[0]!==e)).join("&");return s+(a?"?"+a:"")+(i?"#"+i:"")},Cs=function(t,e,n){var i;n===void 0&&(n=!0);var r=t.split("?"),s=r[0],o=r[1],a=I({},e),l=(i=o?.split("&").map((c=>{var d,f=c.split("="),h=f[0],p=n&&(d=a[h])!==null&&d!==void 0?d:f[1];return delete a[h],h+"="+p})))!==null&&i!==void 0?i:[],u=(function(c,d){var f,h;d===void 0&&(d="&");var p=[];return ie(c,(function(g,m){C(g)||C(m)||m==="undefined"||(f=encodeURIComponent((v=>v instanceof File)(g)?g.name:g.toString()),h=encodeURIComponent(m),p[p.length]=h+"="+f)})),p.join(d)})(a);return u&&l.push(u),l.length>0?s+"?"+l.join("&"):s},Ro=t=>{if(t.Ji)return t.Ji;var e=t.data,n=t.compression;if(e){if(n===Ue.GZipJS){var i=gm((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new ct(a.length+(a.length>>>1)),d=0,f=function(m){c[d++]=m},h=0;u>h;++h){if(d+5>c.length){var p=new ct(d+8+(u-h<<1));p.set(c),c=p}var g=a.charCodeAt(h);128>g?f(g):2048>g?(f(192|g>>>6),f(128|63&g)):g>55295&&57344>g?(f(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++h))>>>18),f(128|g>>>12&63),f(128|g>>>6&63),f(128|63&g)):(f(224|g>>>12),f(128|g>>>6&63),f(128|63&g))}return Of(c,0,d)})(Jn(e)),{mtime:0});return{contentType:Bf,body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),estimatedSize:i.byteLength}}if(n===Ue.Base64){var r=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(Jn(e)),s=(a=>"data="+encodeURIComponent(typeof a=="string"?a:Jn(a)))(r);return{contentType:"application/x-www-form-urlencoded",body:s,estimatedSize:new Blob([s]).size}}var o=Jn(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},jf=t=>{var e,n,i=()=>t.transport==="sendBeacon"?{url:Cs(t.url,{compression:Ue.Base64}),encodedBody:Ro(I({},t,{compression:Ue.Base64,Ji:void 0}))}:{url:Df(t.url,"compression"),encodedBody:Ro(I({},t,{compression:void 0,Ji:void 0}))};try{e=Ro(t)}catch(r){if(wc(t.compression,ri(t.url,"compression")))return A.error("Failed to gzip request body, sending uncompressed payload",r),i();throw r}return e&&wc(t.compression,ri(t.url,"compression"))&&!((n=e.body)instanceof ArrayBuffer?Go(new Uint8Array(n)):ArrayBuffer.isView(n)&&Go(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)))?(Lr=!0,i()):{url:t.url,encodedBody:e}},Uf=t=>{try{return jf(t)}catch(e){return A.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},vm=(function(){var t=se((function*(e){var n=Jn(e.data),i=yield(function(s,o,a){return Ko.apply(this,arguments)})(n,ne.DEBUG,{rethrow:!0});if(!i)return e;var r=yield i.arrayBuffer();return I({},e,{Ji:{contentType:Bf,body:r,estimatedSize:r.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),_m=/Failed to fetch|NetworkError|Load failed/i,Hf=t=>t?.name==="TypeError"&&_m.test(t?.message||""),Wf=t=>{var e=Uf(t);if(e){var n=e.url,i=e.encodedBody,r=i??{},s=r.contentType,o=r.body,a=r.estimatedSize,l=new Headers;ie(t.headers,(function(p,g){l.append(g,p)})),s&&l.append("Content-Type",s);var u=null,c=!1;if(pc){var d=new pc;u={signal:d.signal,timeout:setTimeout((()=>{var p,g;c=!0,d.abort((p=t.timeout,(g=new Error("PostHog request timed out"+(p?" after "+p+"ms":""))).name="AbortError",g))}),t.timeout)}}var f=p=>{c&&p?.name==="AbortError"||Hf(p)?A.warn(p):A.error(p),t.callback==null||t.callback({statusCode:0,error:p})};try{var h;el(n,I({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(h=u)==null?void 0:h.signal},t.fetchOptions)).then((p=>p.text().then((g=>{var m={statusCode:p.status,text:g};if(p.status===200)try{m.json=JSON.parse(g)}catch(v){A.error(v)}t.callback==null||t.callback(m)})))).catch(f).finally((()=>u?clearTimeout(u.timeout):null))}catch(p){u&&clearTimeout(u.timeout),f(p)}}},xa=t=>{try{var e,n=jf(t),i=n.url,r=n.encodedBody,s=r??{},o=s.body,a=s.estimatedSize;if(!o)return;var l=o instanceof Blob?o:new Blob([o],{type:s.contentType});if(He.sendBeacon(i,l))return;var u=U(t.data)?t.data:(e=t.data)==null?void 0:e.batch;if(U(u)&&u.length>1&&(a??0)>16384){var c=Math.ceil(u.length/2),d=f=>U(t.data)?f:I({},t.data,{batch:f});return xa(I({},t,{data:d(u.slice(0,c))})),void xa(I({},t,{data:d(u.slice(c))}))}A.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),Wf(I({},t,{Yi:!0}))}catch(f){A.warn("Beacon send failed",f)}},tu=(t,e,n,i)=>{var r=i==="query"?e==="POST"?"sent_at":"_":void 0;return Cs(n===Ue.GZipJS?Df(t,"compression"):t,I({},r?{[r]:Date.now().toString()}:{},n===Ue.GZipJS?{}:{compression:n}))},Nr=[];el&&Nr.push({transport:"fetch",method:Wf}),Vo&&Nr.push({transport:"XHR",method(t){var e=Uf(t);if(e){var n=new Vo,i=e.encodedBody;n.open(t.method||"GET",e.url,!0);var r=i??{},s=r.contentType,o=r.body;ie(t.headers,(function(a,l){n.setRequestHeader(l,a)})),s&&n.setRequestHeader("Content-Type",s),t.timeout&&(n.timeout=t.timeout),n.onreadystatechange=()=>{if(n.readyState===4){var a={statusCode:n.status,text:n.responseText};if(n.status===200)try{a.json=JSON.parse(n.responseText)}catch{}t.callback==null||t.callback(a)}},n.send(o)}}}),He!=null&&He.sendBeacon&&Nr.push({transport:"sendBeacon",method:xa});var Ia=3e3;class ym{constructor(e,n){this.Xi=!0,this.tr=[],this.er=At(n?.flush_interval_ms||Ia,250,5e3,A.createLogger("flush interval"),Ia),this.ir=e}enqueue(e){this.tr.push(e),this.rr||this.nr()}unload(){this.sr();var e=this.tr.length>0?this.ar():{},n=Object.values(e);[...n.filter((i=>i.url.indexOf("/e")===0)),...n.filter((i=>i.url.indexOf("/e")!==0))].map((i=>{this.lr(I({},i,{transport:"sendBeacon"}))}))}enable(){this.Xi=!1,this.nr()}nr(){var e=this;this.Xi||(this.rr=setTimeout((()=>{if(this.sr(),this.tr.length>0){var n=this.ar(),i=function(){var s=n[r],o=new Date().getTime();s.data&&U(s.data)&&ie(s.data,(a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp})),e.lr(s)};for(var r in n)i()}}),this.er))}lr(e){try{this.ir(e)}catch(n){A.error(n)}}sr(){clearTimeout(this.rr),this.rr=void 0}ar(){var e={};return ie(this.tr,(n=>{var i,r=n,s=(r?r.batchKey:null)||r.url;C(e[s])&&(e[s]=I({},r,{data:[]})),(i=e[s].data)==null||i.push(r.data)})),this.tr=[],e}}var wm=["retriesPerformedSoFar"];class bm{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!C(w)&&"onLine"in w.navigator&&(this.dr=w.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},ve(w,"online",this.vr),ve(w,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var n=e.retriesPerformedSoFar,i=md(e,wm);Dt(n)&&(i.url=Cs(i.url,{retry_count:n})),this._instance._send_request(I({},i,{callback:r=>{if(r.statusCode!==200&&(400>r.statusCode||r.statusCode>=500)){if((r.statusCode===0?3:10)>(n??0))return void this.At(I({retriesPerformedSoFar:n},i));r.statusCode===0&&A.warn("Request failed before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped retrying after "+(n??0)+" retries.")}i.callback==null||i.callback(r)}}))}At(e){var n=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=n+1;var i=(function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),c=Math.random()-.5;return Math.ceil(u+c*(u-l))})(n),r=Date.now()+i;this.tr.push({retryAt:r,requestOptions:e});var s="Enqueued failed request for retry in "+i;navigator.onLine||(s+=" (Browser is offline)"),A.warn(s),this.ur||(this.ur=!0,this.gr())}gr(){if(this.mr&&clearTimeout(this.mr),this.tr.length===0)return this.ur=!1,void(this.mr=void 0);this.mr=setTimeout((()=>{this.dr&&this.tr.length>0&&this.cr(),this.gr()}),this.hr)}cr(){var e=Date.now(),n=[],i=this.tr.filter((s=>e>s.retryAt||(n.push(s),!1)));if(this.tr=n,i.length>0)for(var r of i)this.retriableRequest(r.requestOptions)}unload(){for(var e of(this.mr&&(clearTimeout(this.mr),this.mr=void 0),this.ur=!1,C(w)||(this.vr&&(w.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(w.removeEventListener("offline",this.pr),this.pr=void 0)),this.tr)){var n=e.requestOptions;try{this._instance._send_request(I({},n,{transport:"sendBeacon"}))}catch(i){A.error(i)}}this.tr=[]}}class Em{constructor(e){this.yr=()=>{var n,i,r,s;this.br||(this.br={});var o=this.scrollElement(),a=this.scrollY(),l=o?Math.max(0,o.scrollHeight-o.clientHeight):0,u=a+(o?.clientHeight||0),c=o?.scrollHeight||0;this.br.lastScrollY=Math.ceil(a),this.br.maxScrollY=Math.max(a,(n=this.br.maxScrollY)!==null&&n!==void 0?n:0),this.br.maxScrollHeight=Math.max(l,(i=this.br.maxScrollHeight)!==null&&i!==void 0?i:0),this.br.lastContentY=u,this.br.maxContentY=Math.max(u,(r=this.br.maxContentY)!==null&&r!==void 0?r:0),this.br.maxContentHeight=Math.max(c,(s=this.br.maxContentHeight)!==null&&s!==void 0?s:0)},this._instance=e}get _r(){return this._instance.config.scroll_root_selector}getContext(){return this.br}resetContext(){var e=this.br;return setTimeout(this.yr,0),e}startMeasuringScrollPosition(){ve(w,"scroll",this.yr,{capture:!0}),ve(w,"scrollend",this.yr,{capture:!0}),ve(w,"resize",this.yr)}scrollElement(){if(!this._r)return w?.document.documentElement;var e=U(this._r)?this._r:[this._r];for(var n of e){var i=w?.document.querySelector(n);if(i)return i}}wr(e){var n=e==="y"?"scrollTop":"scrollLeft";if(this._r){var i=this.scrollElement();return i&&i[n]||0}return w?e==="y"?w.scrollY||w.pageYOffset||w.document.documentElement.scrollTop||0:w.scrollX||w.pageXOffset||w.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var Sm=t=>Pf(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class nu{constructor(e,n,i,r){this.kr=s=>{var o=this.Sr();if(!o||o.sessionId!==s){var a={sessionId:s,props:this.Cr(this._instance)};this.Mr.register({[fa]:a})}},this._instance=e,this.Tr=n,this.Mr=i,this.Cr=r||Sm,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[fa]}getSetOnceProps(){var e,n=(e=this.Sr())==null?void 0:e.props;return n?"r"in n?Ff(n,this._instance.config.disable_capture_url_hashes):{$referring_domain:n.referringDomain,$pathname:n.initialPathName,utm_source:n.utm_source,utm_campaign:n.utm_campaign,utm_medium:n.utm_medium,utm_content:n.utm_content,utm_term:n.utm_term}:{}}getSessionProps(){var e={};return ie(dl(this.getSetOnceProps()),((n,i)=>{i==="$current_url"&&(i="url"),e["$session_entry_"+Yo(i)]=n})),e}}class vl{on(e,n){return this.Er[e]||(this.Er[e]=[]),this.Er[e].push(n),()=>{this.Er[e]=this.Er[e].filter((i=>i!==n))}}emit(e,n){for(var i of this.Er[e]||[])i(n);for(var r of this.Er["*"]||[])r(e,n)}constructor(){this.Er={}}}var xi=pe("[SessionId]");class iu{on(e,n){return this.Ir.on(e,n)}constructor(e,n,i){var r;if(this.Pr=null,this.Rr=[],this.Ar=void 0,this.Fr=!1,this.Ir=new vl,this.Lr=(u,c)=>!(!Dt(u)||!Dt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===Wt)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Ne=e.config,this.Mr=e.persistence,this.Or=void 0,this.Dr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.$r=n||Ht,this.Nr=i||Ht;var s=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*At(this.Ne.session_idle_timeout_seconds||1800,60,36e3,xi.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.qr(),this.jr="ph_"+s+"_window_id",this.Br="ph_"+s+"_primary_window_exists",this.Hr()){var o=be.H(this.jr),a=be.H(this.Br);o&&!a?this.Or=o:be.q(this.jr),be.F(this.Br,!0)}if((r=this.Ne.bootstrap)!=null&&r.sessionID)try{var l=(u=>{var c=this.Ne.bootstrap.sessionID.replace(/-/g,"");if(c.length!==32)throw new Error("Not a valid UUID");if(c[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(c.substring(0,12),16)})();this.Ur(this.Ne.bootstrap.sessionID,new Date().getTime(),l)}catch(u){xi.error("Invalid sessionID in bootstrap",u)}this.zr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return C(this.Rr)&&(this.Rr=[]),this.Rr.push(e),this.Dr&&e(this.Dr,this.Or),()=>{this.Rr=this.Rr.filter((n=>n!==e))}}Hr(){return this.Ne.persistence!=="memory"&&!this.Mr.xi&&be.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&be.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?be.H(this.jr):null}Zr(e){var n=this.Pr;return!Ye(n)&&!Ye(e)&&5e3>Math.abs(e-n)}Ur(e,n,i){var r=n!==this._sessionActivityTimestamp,s=!(e!==this.Dr||i!==this._sessionStartTimestamp);this._sessionStartTimestamp=i,this._sessionActivityTimestamp=n,this.Dr=e,s&&!r||s&&this.Zr(n)||(this.Pr=n,this.Mr.register({[Yn]:[n,e,i]}))}Gr(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return Dt(n)&&n>0}Qr(){this.Gr()?this.Mr.refreshKey(Yn):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!Ye(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this.Pr){this.Qr();var n=this.Jr();n[1]===this.Dr&&n[2]===this._sessionStartTimestamp&&(this.Pr=this._sessionActivityTimestamp,this.Mr.register({[Yn]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],n=Dt(e)?e:0,i=Dt(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(n,i)}Xr(e){return this.Qr(),this.Lr(e,this.Yr())}Jr(){var e=this.Mr.props[Yn];return U(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Pr=null,clearTimeout(this.tn),this.tn=void 0,this.Ur(null,null,null)}destroy(){this.Fr=!0,this.Kr(),clearTimeout(this.tn),this.tn=void 0,this.Ar&&w&&(w.removeEventListener(is,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&be.q(this.Br)},ve(w,is,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=null),this.Ne.cookieless_mode===Wt)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var i=n||new Date().getTime(),r=this.Jr(),s=r[1],o=r[2],a=this.Yr(),l=this.Vr(),u=Dt(o)&&Math.abs(i-o)>864e5,c=!1,d=!1,f=!s,h=s,p=!f&&!e&&this.Lr(i,a);if(p){(p=this.Xr(i))||xi.info("cross-tab refresh kept the session alive",{sessionId:s});var g=this.Jr();s=g[1],o=g[2]}f||p||u?(s=this.$r(),l=this.Nr(),xi.info("new session ID generated",{sessionId:s,windowId:l,changeReason:{noSessionId:f,activityTimeout:p,sessionPastMaximumLength:u}}),o=i,c=!0):(l||(l=this.Nr(),c=!0),(d=s!==h)&&(xi.info("adopted cross-tab session id",{sessionId:s,windowId:l}),c=!0));var m=Dt(a)&&e&&!u?a:i,v=Dt(o)?o:new Date().getTime();this.Wr(l),this.Ur(s,m,v),e||this.qr();var E={noSessionId:f,activityTimeout:p,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((S=>S(s,l,E))),{sessionId:s,windowId:l,sessionStartTimestamp:v,changeReason:c?E:void 0,lastActivityTimestamp:a}}qr(){this.Fr||(clearTimeout(this.tn),this.tn=setTimeout((()=>{if(!this.Fr)if(this.Xr(new Date().getTime())){var e=this.Dr;this.resetSessionId(),this.Ir.emit("forcedIdleReset",{idleSessionId:e})}else this.qr()}),1.1*this.sessionTimeoutMs))}}var zf=function(t,e){if(!t)return!1;var n=t.userAgent;if(n&&Ec(n,e))return!0;try{var i=t?.userAgentData;if(i!=null&&i.brands&&i.brands.some((r=>Ec(r?.brand,e))))return!0}catch{}return!!t.webdriver};function qf(){return(qf=se((function*(){var t=He?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),n=e?.model;return X(n)&&n.length>0?n:void 0}catch(i){return void A.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",i)}}))).apply(this,arguments)}var us=function(t,e){if(!(function(n){try{new RegExp(n)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function To(t,e,n){return Jn({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}var Vf={exact:(t,e)=>e.some((n=>t.some((i=>n===i)))),is_not:(t,e)=>e.every((n=>t.every((i=>n!==i)))),regex:(t,e)=>e.some((n=>t.some((i=>us(n,i))))),not_regex:(t,e)=>e.every((n=>t.every((i=>!us(n,i))))),icontains:(t,e)=>e.map(Sr).some((n=>t.map(Sr).some((i=>n.includes(i))))),not_icontains:(t,e)=>e.map(Sr).every((n=>t.map(Sr).every((i=>!n.includes(i))))),gt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>i>parseFloat(r)))})),lt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>it.toLowerCase();function Gf(t,e){return!t||Object.entries(t).every((n=>{var i=n[1],r=e?.[n[0]];if(C(r)||Ye(r))return!1;var s=[String(r)],o=Vf[i.operator];return!!o&&o(i.values,s)}))}var ka="custom",ru="i.posthog.com",xm=/^\/static\//;class Im{constructor(e){this.en={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,n=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return n||(n=this.apiHost.replace("."+ru,".posthog.com")),n==="https://app.posthog.com"?"https://us.posthog.com":n}get region(){return this.en[this.apiHost]||(this.en[this.apiHost]=/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"us":/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"eu":ka),this.en[this.apiHost]}rn(e){if(xm.test(e)){var n=this.instance.config.asset_host;if(typeof n=="string")return n.trim().replace(/\/$/,"")||void 0}}endpointFor(e,n){if(n===void 0&&(n=""),n&&(n=n[0]==="/"?n:"/"+n),e==="ui")return this.uiHost+n;if(e==="flags")return this.flagsApiHost+n;if(e==="assets"){var i=this.rn(n);if(i)return""+i+n}if(this.region===ka)return this.apiHost+n;var r=ru+n;switch(e){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}}function Kf(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var Q=pe("[Surveys]"),Yf="seenSurvey_",Jf=t=>{try{var e=(n=>((i,r)=>""+Yf+(function(s){return s.current_iteration&&s.current_iteration>0?s.id+"_"+s.current_iteration:s.id})(r))(0,n))(t);if(localStorage.getItem(e))return;localStorage.setItem(e,"true")}catch(n){Q.error("Failed to persist survey seen state",n)}},km=[Co.Popover,Co.Widget,Co.API],Cm={ignoreConditions:!1,ignoreDelay:!1,displayType:wa.Popover},Am=pe("[PostHog ExternalIntegrations]"),Pm={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class Fm{constructor(e){this._instance=e}ai(e,n){var i;(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,e,(r=>{if(r)return Am.error("failed to load script",r);n()}))}startIfEnabledOrStop(){var e=this,n=function(){var s,o,a,l=i[0],u=i[1];!u||(s=B.__PosthogExtensions__)!=null&&(s=s.integrations)!=null&&s[l]||e.ai(Pm[l],(()=>{var c;(c=B.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=B.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=B.__PosthogExtensions__)==null||(a=a.integrations)==null||(a=a[l])==null||a.stop())};for(var i of Object.entries((r=this._instance.config.integrations)!==null&&r!==void 0?r:{})){var r;n()}}}class Rm{constructor(e,n){this.rt=e,this.nn=n,this.sn=new Map,this.an=!1}add(e){var n=this;return se((function*(){if(n.an)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(n.sn.has(e.name))throw new Error('Browser extension "'+e.name+'" is already registered');n.sn.set(e.name,e);try{var i=e.setup(n.nn);i&&(yield i)}catch(s){var r=n.sn.get(e.name)===e;r&&n.sn.delete(e.name),n.rt.error('Failed to set up browser extension "'+e.name+'"',s),r&&n.ln(e)}}))()}dispose(){if(!this.an){this.an=!0;var e=Array.from(this.sn.values()).reverse();for(var n of(this.sn.clear(),e))this.ln(n)}}ln(e){try{var n=e.dispose==null?void 0:e.dispose();n&&je(n.then)&&n.then(void 0,(i=>{this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}))}catch(i){this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}}}class Tm{constructor(e){this._instance=e}initialize(){}get(e){var n=this._instance.persistence;if(typeof e=="string")return n?.get_property(e);var i={};for(var r of e){var s=n?.get_property(r);C(s)||(i[r]=s)}return i}set(e,n){var i;(i=this._instance.persistence)==null||i.register(typeof e=="string"?{[e]:n}:e)}remove(e){var n;(n=this._instance.persistence)==null||n.unregister(e)}}var su="extensionsRemoteConfig";class $m{constructor(e){this.an=!1,this.instance=e,this.rt=A,this.un=e.hn,this.kv=new Tm(e),this.onEvent=n=>Er(this.instance.on("eventCaptured",(i=>{try{n({event:i.event,properties:i.properties})}catch(r){this.rt.error("Browser extension event listener failed",r)}}))),this.onRemoteConfig=n=>{if(this.an)return Er((()=>{}));var i=s=>{try{n(s)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},r=this.instance.dn.on(su,i);return this.un&&i(this.un),Er(r)},this.vn=new Rm(A.createLogger("[BrowserExtensions]"),this)}get logger(){return this.rt}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return(e=this.instance.get_property(Ji))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(Ji);return typeof e=="string"?e:void 0}get library(){return{name:ne.LIB_NAME,version:ne.LIB_VERSION}}get initialPersonProperties(){var e,n;return(e=(n=this.instance.persistence)==null?void 0:n.get_initial_props())!==null&&e!==void 0?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,n,i,r,s=(e=this.instance.sessionManager)==null?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:(n=s?.sessionId)!==null&&n!==void 0?n:"",windowId:(i=s?.windowId)!==null&&i!==void 0?i:"",sessionStartTimestamp:(r=s?.sessionStartTimestamp)!==null&&r!==void 0?r:0}}catch{return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get projectToken(){return this.instance.config.token}add(e){return this.vn.add(e)}capture(e,n,i){var r=this;return se((function*(){i?r.instance.capture(e,n,{timestamp:i.timestamp,uuid:i.uuid,$set:i.set,$set_once:i.setOnce}):r.instance.capture(e,n)}))()}registerDynamicEventProperties(e){return Er(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(su,e))}sendRequest(e,n){var i=this;return se((function*(){var r;n===void 0&&(n={});var s=i.instance.requestRouter.endpointFor((r=n.target)!==null&&r!==void 0?r:"api",e),o={method:n.method,url:n.query?Cs(s,n.query):s,data:n.body,headers:n.headers,timeout:n.timeoutMs,fireCallbackOnDrop:!0,transport:n.transport,compression:n.compression,timestampMode:n.sentAt};return n.transport==="sendBeacon"?(i.instance._send_request(o),{statusCode:202}):new Promise((a=>{o.callback=a,i.instance._send_request(o)}))}))()}dispose(){this.an||(this.an=!0,this.vn.dispose())}}var zi={},$o=0,ds=()=>{},ou='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',Ii="Surveys module not available",au="sanitize_properties is deprecated. Use before_send instead",Zf="Invalid value for property_denylist config: ",Mm=["token","distinct_id",rf],Kn="posthog",Xf=!mm&&Ge?.indexOf("MSIE")===-1&&Ge?.indexOf("Mozilla")===-1,Mo=t=>{var e;return I({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:Lg(P?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:ds,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:t??"unset",__preview_deferred_init_extensions:!1,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:me&&X(me?.search)&&me.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disableDeviceModel:!1,disable_external_dependency_loading:!1,strict_script_versioning:!1,enable_recording_console_log:void 0,secure_cookie:(w==null||(e=w.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(n){A.error("Bad HTTP status: "+n.statusCode+" "+n.text)},get_device_id:n=>n,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:ma,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:Ia},error_tracking:{},_onCapture:ds},(n=>({rageclick:n&&n>="2026-05-30"?{content_ignorelist:Gg,ignore_text_selection:!0}:!n||"2025-11-30">n||{content_ignorelist:!0},capture_pageview:!n||"2025-05-24">n||"history_change",session_recording:n&&n>="2026-06-25"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6},streamNetworkBody:!0}:n&&n>="2026-05-30"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6}}:n&&n>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:n&&n>="2026-01-30"?"head":"body",internal_or_test_user_hostname:n&&n>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:n&&n>="2026-05-30"?250:0,split_storage:!(!n||"2026-05-30">n),detect_google_search_app:!(!n||"2026-05-30">n),disable_capture_url_hashes:!(!n||"2026-06-25">n)}))(t))},Lm=[["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"]],lu=t=>{var e={};for(var n of Lm){var i=n[0],r=n[1];C(t[i])||(e[r]=t[i])}var s=fe({},e,t),o=t.__preview_external_dependency_versioned_paths;return C(o)||(C(t.strict_script_versioning)&&(s.strict_script_versioning=!!o),X(o)&&C(t.asset_host)&&(s.asset_host=o)),U(t.property_blacklist)&&(C(t.property_denylist)?s.property_denylist=t.property_blacklist:U(t.property_denylist)?s.property_denylist=[...t.property_blacklist,...t.property_denylist]:A.error(Zf+t.property_denylist)),s};class Nm{constructor(){this.__forceAllowLocalhost=!1}get fn(){return this.__forceAllowLocalhost}set fn(e){A.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class Ze{pn(e,n){if(e){var i=this.sn.indexOf(e);i!==-1&&this.sn.splice(i,1)}return this.sn.push(n),n.initialize==null||n.initialize(),n}gn(){return this.config.cookieless_mode===Wt||this.config.cookieless_mode===kn&&this.consent.isRejected()}get decideEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){var e;this.webPerformance=new Nm,this.mn=!1,this.version=ne.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new vl,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=Mo(),this.SentryIntegration=tm,this.sentryIntegration=i=>(function(r,s){var o=Ef(r,s);return{name:bf,processEvent:a=>o(a)}})(this,i),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.wn=!1,this.kn=null,this.xn=null,this.Sn=null,this.scrollManager=new Em(this),this.pageViewManager=new Gc(this),this.rateLimiter=new um(this),this.requestRouter=new Im(this),this.consent=new Hg(this),this.externalIntegrations=new Fm(this);var n=(e=Ze.__defaultExtensionClasses)!==null&&e!==void 0?e:{};this.featureFlags=n.featureFlags&&new n.featureFlags(this),this.toolbar=n.toolbar&&new n.toolbar(this),this.surveys=n.surveys&&new n.surveys(this),this.conversations=n.conversations&&new n.conversations(this),this.logs=n.logs&&new n.logs(this),this.metrics=n.metrics&&new n.metrics(this),this.experiments=n.experiments&&new n.experiments(this),this.exceptions=n.exceptions&&new n.exceptions(this),this.people={set:(i,r,s)=>{var o=X(i)?{[i]:r}:i;this.setPersonProperties(o),s?.({})},set_once:(i,r,s)=>{var o=X(i)?{[i]:r}:i;this.setPersonProperties(void 0,o),s?.({})}},this.on("eventCaptured",(i=>A.info('send "'+i?.event+'"',i)))}init(e,n,i){if(i&&i!==Kn){var r,s=(r=zi[i])!==null&&r!==void 0?r:new Ze;return s._init(e,n,i),zi[i]=s,zi[Kn][i]=s,s}return this._init(e,n,i)}_init(e,n,i){var r,s;n===void 0&&(n={});var o,a=X(e)?e.trim():"";if(!a)return A.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return a!==((o=this.config)==null?void 0:o.token)?console.warn("[PostHog.js]","You have already initialized PostHog with a different project token! Re-initializing is a no-op, so events will keep going to the project this instance was initialized with. To capture into a second project, load PostHog once, then initialize a named instance after the SDK has loaded, e.g. posthog.init('"+a+"', { ... }, 'project2')"):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=Mo(n.defaults),n.debug=this.Cn(n.debug),this.Mn=n,this.Tn=[],n.person_profiles?this.xn=n.person_profiles:n.process_person&&(this.xn=n.process_person);var l=Mo(n.defaults),u=lu(n),c=fe({},l,u,{name:i,token:a});he(l.rageclick)&&he(u.rageclick)&&(c.rageclick=fe({},l.rageclick,u.rageclick)),he(l.session_recording)&&he(u.session_recording)&&(c.session_recording=fe({},l.session_recording,u.session_recording)),this.set_config(c),this.config.on_xhr_error&&A.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=n.disable_compression?void 0:Ue.GZipJS;var d=this.En();if(this.persistence=new ko(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new ko(I({},this.config,{persistence:"sessionStorage"}),d,!1),this.bn="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&be.N()){var f=be.H(this.bn);U(f)&&f.forEach((k=>{X(k)&&this.yn.add(k)}))}else be.q(this.bn);var h=I({},this.persistence.props),p=I({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new ym((k=>this.Pn(k)),this.config.request_queue_config),this.Rn=new bm(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new iu(this),this.sessionPropsManager=new nu(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((k,T,x)=>{(x!=null&&x.activityTimeout||x!=null&&x.sessionPastMaximumLength||x!=null&&x.crossTabAdoption)&&this.An()}))),this.Fn(),this.config.__preview_deferred_init_extensions?(A.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Ln(g)}),0)):(A.info("Initializing extensions synchronously"),this.Ln(g)),ne.DEBUG=ne.DEBUG||this.config.debug,ne.DEBUG&&A.info("Starting in debug mode",{this:this,config:n,thisC:I({},this.config),p:h,s:p}),!this.config.identity_distinct_id||(r=n.bootstrap)!=null&&r.distinctID||(n.bootstrap=I({},n.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((s=n.bootstrap)==null?void 0:s.distinctID)!==void 0){var m=n.bootstrap.distinctID,v=this.get_distinct_id(),E=this.persistence.get_property(at);if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&E===Hn)this.identify(m);else if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&E===vn)A.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{var S=this.config.get_device_id(Ht()),_=n.bootstrap.isIdentifiedID?S:m;this.persistence.set_property(at,n.bootstrap.isIdentifiedID?vn:Hn),this.register({distinct_id:m,$device_id:_})}}if(g)this.register_once({distinct_id:vr,$device_id:null},"");else if(!this.get_distinct_id()){var b=this.config.get_device_id(Ht());this.register_once({distinct_id:b,$device_id:b},""),this.persistence.set_property(at,Hn)}return ve(w,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),n.segment?(function(k,T){var x=k.config.segment;if(!x)return T();(function(F,$){var O=F.config.segment;if(!O)return $();var L=K=>{var V=()=>K.anonymousId()||Ht();F.config.get_device_id=V,K.id()&&(F.register({distinct_id:K.id(),$device_id:V()}),F.persistence.set_property(at,vn)),$()},N=O.user();"then"in N&&je(N.then)?N.then(L):L(N)})(k,(()=>{x.register((F=>{typeof Promise<"u"&&Promise.resolve||xo.warn("This browser does not have Promise support, and can not use the segment integration");var $=(O,L)=>{if(!L)return O;O.event.userId||O.event.anonymousId===F.get_distinct_id()||(xo.info("No userId set, resetting PostHog"),F.reset()),O.event.userId&&O.event.userId!==F.get_distinct_id()&&(xo.info("UserId set, identifying with PostHog"),F.identify(O.event.userId));var N=F.calculateEventProperties(L,O.event.properties);return O.event.properties=Object.assign({},N,O.event.properties),O};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:O=>$(O,O.event.event),page:O=>$(O,Gn),identify:O=>$(O,bo),screen:O=>$(O,"$screen")}})(k)).then((()=>{T()}))}))})(this,(()=>this.On())):this.On(),je(this.config._onCapture)&&this.config._onCapture!==ds&&(A.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(k=>this.config._onCapture(k.event,k)))),this.config.ip&&A.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this.config.disableDeviceModel||(function(){return qf.apply(this,arguments)})().then((k=>{k&&this.register({[yo]:k})})).catch(ds),this}Fn(){var e,n,i,r,s,o,a=(e=(n=this.config.__extensionClasses)==null?void 0:n.featureFlags)!==null&&e!==void 0?e:(i=Ze.__defaultExtensionClasses)==null?void 0:i.featureFlags;a&&(this.featureFlags&&this.featureFlags instanceof a||((r=this.Dn)==null||r.call(this),this.Dn=void 0,this.featureFlags=new a(this)),je(this.featureFlags.onReloading)&&je(this.featureFlags.setup)?this.Dn||(this.Dn=this.featureFlags.onReloading((()=>{this.dn.emit("featureFlagsReloading",!0)})),this.$n().add(this.featureFlags)):(s=(o=this.featureFlags).initialize)==null||s.call(o))}Ln(e){var n,i,r,s,o,a,l,u=performance.now(),c=I({},Ze.__defaultExtensionClasses,this.config.__extensionClasses),d=[];c.exceptions&&this.sn.push(this.exceptions=(n=this.exceptions)!==null&&n!==void 0?n:new c.exceptions(this)),c.historyAutocapture&&this.sn.push(this.historyAutocapture=new c.historyAutocapture(this)),c.tracingHeaders&&this.sn.push(this.tracingHeaders=new c.tracingHeaders(this)),c.siteApps&&this.sn.push(this.siteApps=new c.siteApps(this)),c.sessionRecording&&!e&&this.sn.push(this.sessionRecording=new c.sessionRecording(this)),this.config.disable_scroll_properties||d.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),c.autocapture&&this.sn.push(this.autocapture=new c.autocapture(this)),c.surveys&&this.sn.push(this.surveys=(i=this.surveys)!==null&&i!==void 0?i:new c.surveys(this)),c.logs&&this.sn.push(this.logs=(r=this.logs)!==null&&r!==void 0?r:new c.logs(this)),c.metrics&&this.sn.push(this.metrics=(s=this.metrics)!==null&&s!==void 0?s:new c.metrics(this)),c.conversations&&this.sn.push(this.conversations=(o=this.conversations)!==null&&o!==void 0?o:new c.conversations(this)),c.productTours&&this.sn.push(this.productTours=new c.productTours(this)),c.heatmaps&&this.sn.push(this.heatmaps=new c.heatmaps(this)),c.webVitalsAutocapture&&this.sn.push(this.webVitalsAutocapture=new c.webVitalsAutocapture(this)),c.exceptionObserver&&this.sn.push(this.exceptionObserver=new c.exceptionObserver(this)),c.deadClicksAutocapture&&this.sn.push(this.deadClicksAutocapture=new c.deadClicksAutocapture(this,em)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((f=>{f.initialize&&d.push((()=>{f.initialize==null||f.initialize()}))})),d.push((()=>{if(this.Nn){var f=this.Nn;this.Nn=void 0,this.sn.forEach((h=>h.onRemoteConfig==null?void 0:h.onRemoteConfig(f)))}})),this.qn(d,u)}qn(e,n){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,n)}),0);var i=e.shift();if(i)try{i()}catch(s){A.error("Error initializing extension:",s)}}var r=Math.round(performance.now()-n);this.register_for_session({[sf]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[of]:r}),this.config.__preview_deferred_init_extensions&&A.info("PostHog extensions initialized ("+r+"ms)")}Zi(e){var n;if(!P||!P.body)return A.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.Zi(e)}),500);if(this.config.__preview_deferred_init_extensions&&(this.Nn=e),this.hn=e,this.compression=void 0,e.ok){var i,r=e.config;r.supportedCompression&&!this.config.disable_compression&&(this.compression=j(r.supportedCompression,Ue.GZipJS)?Ue.GZipJS:j(r.supportedCompression,Ue.Base64)?Ue.Base64:void 0),(i=r.analytics)!=null&&i.endpoint&&(this.analyticsDefaultEndpoint=r.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:ma}),(n=this.jn)==null||n.handleRemoteConfig(e),this.sn.forEach((s=>s.onRemoteConfig==null?void 0:s.onRemoteConfig(e)))}On(){try{this.config.loaded(this)}catch(i){A.critical("`loaded` function failed",i)}if(this.Bn(),this.config.internal_or_test_user_hostname&&me!=null&&me.hostname){var e=me.hostname,n=this.config.internal_or_test_user_hostname;(typeof n=="string"?e===n:n.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.gn())&&this.Hn()}),1),this.Un=new Tf(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,n,i,r,s;(e=this.surveys)==null||e.handlePageUnload==null||e.handlePageUnload(),(n=this.metrics)==null||n.flush("sendBeacon"),this.config.request_batching?(this.zn()&&this.capture(wo),(i=this.logs)==null||i.flushLogs("sendBeacon"),(r=this.In)==null||r.unload(),(s=this.Rn)==null||s.unload()):this.zn()&&this.capture(wo,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?Xf?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)?e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:429})):(e.transport=e.transport||this.config.api_transport,e.headers=I({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,(C(this.config.disable_beacon)?this.config.__preview_disable_beacon:this.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(n=>{var i,r,s,o=I({},n);o.timeout=o.timeout||6e4;var a,l,u,c,d,f=(i=o.transport)!==null&&i!==void 0?i:"fetch";f==="sendBeacon"&&C(o.compression)&&o.data&&(o.compression=Ue.Base64),o.method==="POST"&&o.data&&(o.timestampMode==="capture-body"?o.data={api_key:(l=(d=(c=U(a=o.data)?a:[a])[0])==null||(u=d.properties)==null?void 0:u.token)!==null&&l!==void 0?l:d?.token,batch:c,sent_at:new Date().toISOString()}:o.timestampMode==="body"&&(o.data=(function(m,v){return v===void 0&&(v=new Date().toISOString()),U(m)?m.map((E=>I({},E,{sent_at:v}))):I({},m,{sent_at:v})})(o.data))),o.url=tu(o.url,o.method,o.compression,o.timestampMode);var h=Nr.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),p=(r=(s=(function(m,v){for(var E=0;m.length>E;E++)if(m[E].transport===f)return m[E]})(h))==null?void 0:s.method)!==null&&r!==void 0?r:h[0].method;if(!p)throw new Error("No available transport method");var g=m=>{try{p(m)}catch(v){Hf(v)?A.warn(v):A.error(v),o.callback==null||o.callback({statusCode:0,error:v})}};f!=="sendBeacon"&&o.data&&o.compression===Ue.GZipJS&&Op&&typeof Promise<"u"&&!Lr?vm(o).then((m=>{g(m)})).catch((m=>{if(bc(m))return Lr=!0,void g(I({},o,{compression:void 0,url:tu(n.url,n.method,void 0,n.timestampMode)}));(v=>{if(!v||typeof v!="object")return!1;var E="name"in v?String(v.name):"";return bc(v)||E===vd})(m)&&(Lr=!0),g(o)})):p(o)})(I({},e,{callback:n=>{var i,r;this.rateLimiter.checkForLimiting(n),400>n.statusCode||(i=(r=this.config).on_request_error)==null||i.call(r,n),e.callback==null||e.callback(n)}}))):e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:0}))}Pn(e){this.Rn?this.Rn.retriableRequest(e):this._send_request(e)}_execute_array(e){$o++;try{var n,i=[],r=[],s=[];_r(e,(a=>{if(a)if(U(n=a[0]))s.push(a);else if(je(a))try{a.call(this)}catch(l){A.error("Error executing queued PostHog call",a,l)}else U(a)&&n==="alias"?i.push(a):U(a)&&n.indexOf("capture")!==-1&&je(this[n])?s.push(a):r.push(a)}));var o=function(a,l){_r(a,(function(u){try{if(U(u[0])){var c=l;ie(u,(function(d){c=c[d[0]].apply(c,d.slice(1))}))}else l[u[0]].apply(l,u.slice(1))}catch(d){A.error("Error executing queued PostHog call",u,d)}}))};o(i,this),o(r,this),o(s,this)}finally{$o--}}push(e){if($o>0&&U(e)&&X(e[0])){var n=Ze.prototype[e[0]];je(n)&&n.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,n,i){var r,s,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.In){if(this.is_capturing())if(!C(e)&&X(e)){var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var c=i!=null&&i.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(c==null||!c.isRateLimited){n!=null&&n.$current_url&&!X(n?.$current_url)&&(A.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),n==null||delete n.$current_url),e!=="$exception"||i!=null&&i.Wn||A.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,f=i?.timestamp||d,h=kc(i?.uuid,Ht),p={uuid:h,event:e,properties:this.calculateEventProperties(e,n||{},f,h)};e===Gn&&this.config.__preview_capture_bot_pageviews&&u&&(p.event="$bot_pageview",p.properties.$browser_type="bot"),c&&(p.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&p.properties.$feature_flag_has_experiment===!1&&this.get_property(Xr)===!0;i?.$set&&!g&&(p.$set=i?.$set);var m=i?.$unset;m&&(p.$unset=m);var v,E,S,_=g?void 0:this.Vn(i?.$set_once,e!==Tc,e===bo);if(_&&(p.$set_once=_),i!=null&&i._noTruncate||(s=this.config.properties_string_max_length,o=p,a=L=>X(L)?L.slice(0,s):L,l=new Set,p=(function L(N,K){if(N!==Object(N))return a?a(N):N;if(!l.has(N)){var V;if(l.add(N),U(N))V=[],_r(N,(R=>{V.push(L(R))}));else{var M={};ie(N,((R,Z)=>{l.has(R)||(M[Z]=L(R))})),V=M}return V}})(o)),p.timestamp=f,C(i?.timestamp)||(p.properties.$event_time_override_provided=!0,p.properties.$event_time_override_system_time=d),g&&(p.properties=(function(L,N){N===void 0&&(N=[]);var K={},V=M=>{L[M]!==void 0&&(K[M]=L[M])};return Bp.forEach(V),N.forEach(V),K})(p.properties,Mm)),e===qt.DISMISSED||e===qt.SENT){var b=n?.[Ao.SURVEY_ID],k=n?.[Ao.SURVEY_ITERATION];Jf({id:b,current_iteration:k}),p.$set=I({},p.$set,{[(v={id:b,current_iteration:k},E=e===qt.SENT?"responded":"dismissed",S="$survey_"+E+"/"+v.id,v.current_iteration&&v.current_iteration>0&&(S="$survey_"+E+"/"+v.id+"/"+v.current_iteration),S)]:!0})}else e===qt.SHOWN&&(p.$set=I({},p.$set,{[Ao.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===cm.SHOWN){var T=n?.[Yc.TOUR_TYPE];T&&(p.$set=I({},p.$set,{[Yc.TOUR_LAST_SEEN_DATE+"/"+T]:new Date().toISOString()}))}var x=I({},p.properties.$set,p.$set);if(Kt(x)||this.setPersonPropertiesForFlags(x),!H(this.config.before_send)){var F=this.Pt(p);if(!F)return;(p=F).uuid=kc(p.uuid,Ht)}this.dn.emit("eventCaptured",p);var $=(r=i?._url)!==null&&r!==void 0?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),O={method:"POST",url:$,data:p,compression:"best-available",timestampMode:i?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test($)?"body":"capture-body",batchKey:i?._batchKey,transport:i?.transport};return!this.config.request_batching||i&&(i==null||!i._batchKey)||i!=null&&i.send_instantly?this.Pn(O):this.In.enqueue(O),p}A.critical("This capture call is ignored due to client rate limiting.")}}else A.error("No event name provided to posthog.capture")}else A.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(n=>e(n.event,n)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new $m(this)}cn(e){this._n.push(e);var n=!0;return()=>{if(n){n=!1;var i=this._n.indexOf(e);i!==-1&&this._n.splice(i,1)}}}calculateEventProperties(e,n,i,r,s){if(i=i||new Date,!this.persistence||!this.sessionPersistence)return n;var o=s?void 0:this.persistence.remove_event_timer(e),a=I({},n);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.gn()&&(a[rf]=!0),e==="$snapshot"){var l=I({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!X(a.distinct_id)&&!ke(a.distinct_id)||Jo(a.distinct_id))&&A.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=(function(b,k,T,x){var F,$,O,L;if(x===void 0&&(x=!1),!Ge)return{};var N,K=b?[...si,...k||[]]:[],V=(function(Dn){for(var qe=0;xc.length>qe;qe++){var jn=xc[qe],Mt=jn[1],Lt=jn[0].exec(Dn),ut=Lt&&(je(Mt)?Mt(Lt,Dn):Mt);if(ut)return ut}return["",""]})(Ge),M=V[0],R=V[1],Z=(N=typeof navigator<"u"?navigator:void 0)!=null&&N.brave?{brave:!0}:{},Ce={};C(T)||(Ce.detectGoogleSearchApp=T);var oe={},ye=(F=navigator)==null||(F=F.userAgentData)==null?void 0:F.platform,$e=($=navigator)==null?void 0:$.maxTouchPoints,ae=w==null||(O=w.screen)==null?void 0:O.width,Ie=w==null||(L=w.screen)==null?void 0:L.height,Se=w?.devicePixelRatio;C(ye)||(oe.userAgentDataPlatform=ye),C($e)||(oe.maxTouchPoints=$e),C(ae)||(oe.screenWidth=ae),C(Ie)||(oe.screenHeight=Ie),C(Se)||(oe.devicePixelRatio=Se);var De,wt,ge,Je,bt,mn,Re,Pe,$t=fe(dl({$os:M,$os_version:R,$browser:Hd(Ge,navigator.vendor,Z,Ce),$device:Ic(Ge),$device_type:(wt=Ge,ge=oe,Pe=Ic(wt),Pe===xd||Pe===Sd||Pe==="Kobo"||Pe==="Kindle Fire"||Pe===Od?ti:Pe===Ki||Pe===Qn||Pe===Yi||Pe===Xo?"Console":Pe===kd?"Wearable":Pe?rt:ge?.userAgentDataPlatform==="Android"&&((Je=ge?.maxTouchPoints)!==null&&Je!==void 0?Je:0)>0?600>Math.min((bt=ge?.screenWidth)!==null&&bt!==void 0?bt:0,(mn=ge?.screenHeight)!==null&&mn!==void 0?mn:0)/((Re=ge?.devicePixelRatio)!==null&&Re!==void 0?Re:1)?rt:ti:"Desktop"),$timezone:Rf(),$timezone_offset:om()}),{$current_url:Xi(x?fn(me?.href):me?.href,K,Qi),$host:me?.host,$pathname:me?.pathname,$raw_user_agent:Ge.length>1e3?Ge.substring(0,997)+"...":Ge,$browser_version:ig(Ge,navigator.vendor,Z,Ce),$browser_language:Kc(),$browser_language_prefix:(De=Kc(),typeof De=="string"?De.split("-")[0]:void 0),$screen_height:w?.screen.height,$screen_width:w?.screen.width,$viewport_height:w?.innerHeight,$viewport_width:w?.innerWidth,$lib:ne.LIB_NAME,$lib_version:ne.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return ne.SDK_DIST_CHANNEL&&($t.$sdk_dist_channel=ne.SDK_DIST_CHANNEL),$t})(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties,this.config.detect_google_search_app,this.config.disable_capture_url_hashes);if(this.sessionManager){var d=this.sessionManager.checkAndGetSessionAndWindowId(s,i.getTime()),f=d.windowId;a.$session_id=d.sessionId,a.$window_id=f}this.sessionPropsManager&&fe(a,this.sessionPropsManager.getSessionProps());try{var h;this.sessionRecording&&fe(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(h=this.Rn)==null?void 0:h.length}catch(b){a.$sdk_debug_error_capturing_properties=String(b)}if(this.requestRouter.region===ka&&(a.$lib_custom_api_host=this.config.api_host),u=e!==Gn||s?e!==wo||s?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(i):this.pageViewManager.doPageView(i,r),a=fe(a,u),e===Gn&&P&&(a.title=P.title),!C(o)){var p=i.getTime()-o;a.$duration=parseFloat((p/1e3).toFixed(3))}Ge&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();ie(["$referrer","$referring_domain"],(b=>{b in g&&delete m[b]}));var v={};if(this._n.length>0)for(var E of this._n.slice())try{fe(v,E())}catch(b){A.error("Failed to produce browser extension event properties",b)}(a=fe({},c,g,m,I({},v,a))).$is_identified=this._isIdentified(),U(this.config.property_denylist)?ie(this.config.property_denylist,(function(b){delete a[b]})):A.error(Zf+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var S=this.config.sanitize_properties;S&&(A.error(au),a=S(a,e));var _=this.Zn();return a.$process_person_profile=_,_&&!s&&this.Gn("_calculate_event_properties"),a}Vn(e,n,i){var r;if(n===void 0&&(n=!0),i===void 0&&(i=!1),!this.persistence||!this.Zn()||this.mn&&!i)return e;var s=this.persistence.get_initial_props(),o=(r=this.sessionPropsManager)==null?void 0:r.getSetOnceProps(),a=fe({},s,o||{},e||{}),l=this.config.sanitize_properties;return l&&(A.error(au),a=l(a,"$set_once")),n&&(this.mn=!0),Kt(a)?void 0:a}register(e,n){var i;(i=this.persistence)==null||i.register(e,n)}register_once(e,n,i){var r;(r=this.persistence)==null||r.register_once(e,n,i)}register_for_session(e){var n;(n=this.sessionPersistence)==null||n.register(e),Object.keys(e).forEach((i=>this.yn.add(i))),this.Qn()}unregister(e){var n;(n=this.persistence)==null||n.unregister(e)}unregister_for_session(e){var n;(n=this.sessionPersistence)==null||n.unregister(e),this.yn.delete(e),this.Qn()}Kn(e,n){this.register({[e]:n})}An(){this.yn.forEach((e=>{var n;(n=this.sessionPersistence)==null||n.unregister(e)})),this.yn.clear(),this.Qn()}Qn(){var e;if(this.bn)if(this.config.persistence==="memory"||(e=this.sessionPersistence)!=null&&e.xi||!be.N())be.q(this.bn);else{var n=[];this.yn.forEach((i=>n.push(i))),n.length>0?be.F(this.bn,n):be.q(this.bn)}}getFeatureFlag(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlag(e,n)}getFeatureFlagPayload(e){var n;return(n=this.featureFlags)==null?void 0:n.getFeatureFlagPayload(e)}getFeatureFlagResult(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlagResult(e,n)}getAllFeatureFlags(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.getAllFeatureFlags())!==null&&e!==void 0?e:[]}isFeatureEnabled(e,n){var i,r;return(i=(r=this.featureFlags)==null?void 0:r.isFeatureEnabled(e,n))!==null&&i!==void 0?i:n?.defaultValue}reloadFeatureFlags(){var e;(e=this.featureFlags)==null||e.reloadFeatureFlags()}updateFlags(e,n,i){var r;(r=this.featureFlags)==null||r.updateFlags(e,n,i)}updateEarlyAccessFeatureEnrollment(e,n,i){var r;(r=this.featureFlags)==null||r.updateEarlyAccessFeatureEnrollment(e,n,i)}getEarlyAccessFeatures(e,n,i){var r;return n===void 0&&(n=!1),(r=this.featureFlags)==null?void 0:r.getEarlyAccessFeatures(e,n,i)}on(e,n){return this.dn.on(e,n)}onFeatureFlags(e){return this.featureFlags?this.featureFlags.onFeatureFlags(e):(e([],{},{errorsLoading:!0}),()=>{})}onSurveysLoaded(e){return this.surveys?this.surveys.onSurveysLoaded(e):(e([],{isLoaded:!1,error:Ii}),()=>{})}onSessionId(e){var n,i;return(n=(i=this.sessionManager)==null?void 0:i.onSessionId(e))!==null&&n!==void 0?n:()=>{}}getSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getSurveys(e,n):e([],{isLoaded:!1,error:Ii})}getActiveMatchingSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,n):e([],{isLoaded:!1,error:Ii})}renderSurvey(e,n){var i;(i=this.surveys)==null||i.renderSurvey(e,n)}displaySurvey(e,n){var i;n===void 0&&(n=Cm),(i=this.surveys)==null||i.displaySurvey(e,n)}cancelPendingSurvey(e){var n;(n=this.surveys)==null||n.cancelPendingSurvey(e)}canRenderSurvey(e){var n,i;return(n=(i=this.surveys)==null?void 0:i.canRenderSurvey(e))!==null&&n!==void 0?n:{visible:!1,disabledReason:Ii}}canRenderSurveyAsync(e,n){var i,r;return n===void 0&&(n=!1),(i=(r=this.surveys)==null?void 0:r.canRenderSurveyAsync(e,n))!==null&&i!==void 0?i:Promise.resolve({visible:!1,disabledReason:Ii})}Jn(e){return!e||Jo(e)?(A.critical("Unique user id has not been set in posthog.identify"),!1):e===vr?(A.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.'),!1):!["distinct_id","distinctid"].includes(e.toLowerCase())&&!["undefined","null"].includes(e.toLowerCase())||(A.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.'),!1)}identify(e,n,i){if(!this.__loaded||!this.persistence)return A.uninitializedWarning("posthog.identify");if(ke(e)&&(e=e.toString(),A.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.Jn(e)&&this.Gn("posthog.identify")){var r=this.get_distinct_id();this.register({$user_id:e}),this.get_property(Ji)||this.register_once({$had_persisted_distinct_id:!0,$device_id:r},""),e!==r&&e!==this.get_property(Ri)&&(this.unregister(Ri),this.register({distinct_id:e}));var s,o=(this.persistence.get_property(at)||Hn)===Hn,a=e!==r,l=!a&&o;if(a&&o)this.persistence.set_property(at,vn),this.setPersonPropertiesForFlags({$set:n||{},$set_once:i||{}},!1),this.capture(bo,{distinct_id:e,$anon_distinct_id:r},{$set:n||{},$set_once:i||{}}),this.Sn=To(e,n,i),(s=this.featureFlags)==null||s.setAnonymousDistinctId(r);else if(l){this.persistence.set_property(at,vn);var u=n||{},c=i||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=To(e,n,i)}else(n||i)&&this.setPersonProperties(n,i);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Cn)):l&&(n||i)&&this.reloadFeatureFlags()}}setPersonProperties(e,n){if((e||n)&&this.Gn("posthog.setPersonProperties")){var i=To(this.get_distinct_id(),e,n);this.Sn!==i?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:n||{}},!0),this.capture("$set",{$set:e||{},$set_once:n||{}}),this.Sn=i):A.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}unsetPersonProperties(e){var n,i=(U(e)?e:[e]).filter((r=>X(r)&&r.length>0));i.length!==0&&this.Gn("posthog.unsetPersonProperties")&&((n=this.featureFlags)==null||n.unsetPersonPropertiesForFlags(i,!0),this.capture("$set",{$unset:i}),this.Sn=null)}group(e,n,i){if(e&&n){var r=this.getGroups(),s=r[e]!==n;if(s&&this.resetGroupPropertiesForFlags(e),this.register({$groups:I({},r,{[e]:n})}),s||i){var o={$group_type:e,$group_key:n};i&&(o.$group_set=i),this.capture(Tc,o)}i&&this.setGroupPropertiesForFlags({[e]:i}),s&&!i&&this.reloadFeatureFlags()}else A.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),(i=this.featureFlags)==null||i.setPersonPropertiesForFlags(e,n)}resetPersonPropertiesForFlags(e){var n;e===void 0&&(e=!0),(n=this.featureFlags)==null||n.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((i=this.featureFlags)==null||i.setGroupPropertiesForFlags(e,n))}resetGroupPropertiesForFlags(e){var n;(n=this.featureFlags)==null||n.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,n){var i,r,s,o,a,l,u,c,d,f;if(n===void 0&&(n=!1),A.info("reset"),!this.__loaded)return A.uninitializedWarning("posthog.reset");var h,p=this.get_property(Ji),g=this.get_property(yo),m=this.get_property(An),v=this.is_capturing();if(this.consent.reset(),n||!v||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after."),(i=this.persistence)==null||i.clear(),(r=this.sessionPersistence)==null||r.clear(),this.yn.clear(),this.Qn(),C(m)||(h=this.persistence)==null||h.register({[An]:m}),(s=this.surveys)==null||s.reset(),(o=this.Un)==null||o.stop(),(a=this.featureFlags)==null||a.reset(),(l=this.conversations)==null||l.reset(),(u=this.logs)==null||u.reset(),(c=this.metrics)==null||c.reset(),(d=this.persistence)==null||d.set_property(at,Hn),(f=this.sessionManager)==null||f.resetSessionId(),this.Sn=null,this.config.cookieless_mode===Wt)this.register_once({distinct_id:vr,$device_id:null},"");else{var E=this.config.get_device_id(Ht());this.register_once({distinct_id:E,$device_id:e?E:p},""),e||C(g)||this.register({[yo]:g})}this.register({$last_posthog_reset:new Date().toISOString()},1),delete this.config.identity_distinct_id,delete this.config.identity_hash,this.reloadFeatureFlags()}shutdown(e){var n=this;return se((function*(){var i,r,s,o,a,l,u;if(n.__loaded){(i=n.Un)==null||i.stop(),(r=n.jn)==null||r.dispose(),(s=n.sessionRecording)==null||s.dispose(),(o=n.logs)==null||o.flushLogs("sendBeacon"),(a=n.metrics)==null||a.flush("sendBeacon"),(l=n.In)==null||l.unload(),(u=n.Rn)==null||u.unload();try{var c;(c=n.featureFlags)==null||c.destroy()}catch(d){A.error("Error while destroying feature flags",d)}}else A.uninitializedWarning("posthog.shutdown")}))()}setIdentity(e,n){var i;this.config.identity_distinct_id=e,this.config.identity_hash=n,this.alias(e),(i=this.conversations)==null||i.Xn()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,(e=this.conversations)==null||e.ts()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,n;return(e=(n=this.sessionManager)==null?void 0:n.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var n=this.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.sessionStartTimestamp,r=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+n.sessionId);if(e!=null&&e.withTimestamp&&i){var s,o=(s=e.timestampLookBack)!==null&&s!==void 0?s:10;if(!i)return r;r+="?t="+Math.max(Math.floor((new Date().getTime()-i)/1e3)-o,0)}return r}alias(e,n){return e===this.get_property(Zd)?(A.critical("Attempting to create alias for existing People user - aborting."),-2):this.Gn("posthog.alias")?(C(n)&&(n=this.get_distinct_id()),e!==n?(this.Kn(Ri,e),this.capture("$create_alias",{alias:e,distinct_id:n})):(A.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var n=I({},this.config);if(he(e)){var i,r,s,o,a,l,u,c,d,f,h,p;fe(this.config,lu(e));var g=this.En();(i=this.persistence)==null||i.update_config(this.config,n,g),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new ko(I({},this.config,{persistence:"sessionStorage"}),g,!1);var m=this.Cn(this.config.debug);mt(m)&&(this.config.debug=m),mt(this.config.debug)&&(this.config.debug?(ne.DEBUG=!0,le.N()&&le.F("ph_debug",!0),A.info("set_config",{config:e,oldConfig:n,newConfig:I({},this.config)})):(ne.DEBUG=!1,le.N()&&le.q("ph_debug"))),(r=this.featureFlags)==null||r.updateConfig==null||r.updateConfig(this.config,this.Qi()),(s=this.exceptionObserver)==null||s.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(f=this.deadClicksAutocapture)==null||f.startIfEnabledOrStop(),(h=this.surveys)==null||h.loadIfEnabled(),this.es(),(p=this.externalIntegrations)==null||p.startIfEnabledOrStop()}}_overrideSDKInfo(e,n){ne.LIB_NAME=e,ne.LIB_VERSION=n}startSessionRecording(e){var n,i,r,s,o,a=e===!0,l={sampling:a||!(e==null||!e.sampling),linked_flag:a||!(e==null||!e.linked_flag),url_trigger:a||!(e==null||!e.url_trigger),event_trigger:a||!(e==null||!e.event_trigger)};Object.values(l).some(Boolean)&&((n=this.sessionManager)==null||n.checkAndGetSessionAndWindowId(),l.sampling&&((i=this.sessionRecording)==null||i.overrideSampling()),l.linked_flag&&((r=this.sessionRecording)==null||r.overrideLinkedFlag()),l.url_trigger&&((s=this.sessionRecording)==null||s.overrideTrigger("url")),l.event_trigger&&((o=this.sessionRecording)==null||o.overrideTrigger("event"))),this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,n){if(this.exceptions){var i=new Error("PostHog syntheticException"),r=this.exceptions.buildProperties(e,{handled:!0,syntheticException:i});return this.exceptions.sendExceptionEvent(I({},r,n))}}addExceptionStep(e,n){var i;(i=this.exceptions)==null||i.addExceptionStep(e,n)}captureLog(e){var n;(n=this.logs)==null||n.captureLog(e)}get logger(){var e,n;return(e=(n=this.logs)==null?void 0:n.logger)!==null&&e!==void 0?e:Ze.rs}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var n,i;return(n=(i=this.toolbar)==null?void 0:i.loadToolbar(e))!==null&&n!==void 0&&n}get_property(e){var n;return(n=this.persistence)==null?void 0:n.props[e]}getSessionProperty(e){var n;return(n=this.sessionPersistence)==null?void 0:n.props[e]}toString(){var e,n=(e=this.config.name)!==null&&e!==void 0?e:Kn;return n!==Kn&&(n=Kn+"."+n),n}_isIdentified(){var e,n;return((e=this.persistence)==null?void 0:e.get_property(at))===vn||((n=this.sessionPersistence)==null?void 0:n.get_property(at))===vn}Zn(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles===ma&&!this._isIdentified()&&Kt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[Ri])&&((n=this.persistence)==null||(n=n.props)==null||!n[ts]))}zn(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Zn()||this.Gn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.Gn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}Gn(e){return this.config.person_profiles==="never"?(A.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Kn(ts,!0),!0)}En(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut();return this.config.disable_persistence||e&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!==kn)}es(){var e,n,i,r,s=this.En();return((e=this.persistence)==null?void 0:e.xi)!==s&&((i=this.persistence)==null||i.set_disabled(s)),((n=this.sessionPersistence)==null?void 0:n.xi)!==s&&((r=this.sessionPersistence)==null||r.set_disabled(s)),s&&(this.yn.clear(),this.Qn()),s}opt_in_capturing(e){var n;if(this.config.cookieless_mode!==Wt){if(this.gn()){var i,r,s,o,a;this.Yn(!0,!0),(i=this.sessionManager)==null||i.destroy(),(r=this.pageViewManager)==null||r.destroy(),this.sessionManager=new iu(this),this.pageViewManager=new Gc(this),this.persistence&&(this.sessionPropsManager=new nu(this,this.sessionManager,this.persistence));var l,u=(s=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&s!==void 0?s:(a=Ze.__defaultExtensionClasses)==null?void 0:a.sessionRecording;u&&(this.sessionRecording=this.pn(this.sessionRecording,new u(this)),this.hn&&((l=this.sessionRecording)==null||l.onRemoteConfig==null||l.onRemoteConfig(this.hn)))}var c,d;this.consent.optInOut(!0),this.es(),this.Bn(),(n=this.sessionRecording)==null||n.startIfEnabledOrStop(),this.config.cookieless_mode==kn&&((c=this.surveys)==null||c.loadIfEnabled()),(C(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((d=e?.captureEventName)!==null&&d!==void 0?d:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hn()}else A.warn(ou)}opt_out_capturing(){var e,n,i;this.config.cookieless_mode!==Wt?(this.config.cookieless_mode===kn&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===kn&&(this.register({distinct_id:vr,$device_id:null}),(e=this.sessionRecording)==null||e.stopRecording(),this.sessionRecording=void 0,(n=this.sessionManager)==null||n.destroy(),(i=this.pageViewManager)==null||i.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.Hn(),this.Bn())):A.warn(ou)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===Wt||(this.config.cookieless_mode===kn?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return He?zf(He,this.config.custom_blocked_useragents):void 0}Hn(){P&&(P.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(Gn,{title:P.title},{send_instantly:!0}),this.kn&&(P.removeEventListener(ns,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),ve(P,ns,this.kn)))}debug(e){e===!1?(w?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(w?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}Qi(){var e=this.Mn||{};return"advanced_disable_flags"in e?!!e.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(A.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(function(n,i,r,s,o){var a=i in n&&!H(n[i]),l=r in n&&!H(n[r]);return a?n[i]:!!l&&(o&&o.warn("Config field '"+r+"' is deprecated. Please use '"+i+"' instead. The old field will be removed in a future major version."),n[r])})(e,"advanced_disable_flags","advanced_disable_decide",0,A)}Pt(e){var n;if(H(this.config.before_send))return e;var i=Object.keys((n=e.properties)!==null&&n!==void 0?n:{}).filter(qp),r=U(this.config.before_send)?this.config.before_send:[this.config.before_send],s=e;for(var o of r){if(s=o(s),H(s)){var a="Event '"+e.event+"' was rejected in beforeSend function";return zp(e.event)?A.warn(a+". This can cause unexpected behavior."):A.info(a),null}s.properties&&!Kt(s.properties)||A.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}for(var l of i)if(s.properties&&H(s.properties[l]))return A.warn("Event '"+e.event+"' had its '"+l+"' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped."),null;return s}getPageViewId(){var e;return(e=this.pageViewManager.ui)==null?void 0:e.pageViewId}captureTraceFeedback(e,n){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:n})}captureTraceMetric(e,n,i){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:n,$ai_metric_value:String(i)})}Cn(e){var n=mt(e)&&!e,i=le.N()&&le.P("ph_debug")==="true";return!n&&(!!i||e)}}Ze.__defaultExtensionClasses={},Ze.rs=(()=>{var t=()=>{};return{trace:t,debug:t,info:t,warn:t,error:t,fatal:t}})(),(function(t,e){for(var n=0;e.length>n;n++)t.prototype[e[n]]=$g(t.prototype[e[n]])})(Ze,["identify"]);class cu{constructor(e){this.disabled=e===!1;var n=he(e)?e:{};this.thresholdPx=n.threshold_px||30,this.timeoutMs=n.timeout_ms||1e3,this.clickCount=n.click_count||3,this.clicks=[]}isRageClick(e,n,i){if(this.disabled)return!1;var r=this.clicks[this.clicks.length-1];if(r&&Math.abs(e-r.x)+Math.abs(n-r.y)i-r.timestamp){if(this.clicks.push({x:e,y:n,timestamp:i}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:n,timestamp:i}];return!1}}var Lo="$copy_autocapture",No=pe("[AutoCapture]");function Oo(t,e){return e.length>t?e.slice(0,t)+"...":e}function Om(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!hn(e));return e}function Bm(t,e){var n,i,r=e.e,s=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!hn(t))return{props:{}};for(var c=[t],d=new Set([t]),f=t;f.parentNode&&!et(f,"body")&&pf>c.length;)if(hf(f.parentNode)){var h=f.parentNode.host;if(d.has(h))break;d.add(h),c.push(h),f=h}else{if(!hn(f.parentNode)||d.has(f.parentNode))break;d.add(f.parentNode),c.push(f.parentNode),f=f.parentNode}var p,g,m=[],v={},E=!1,S=!1;if(ie(c,(x=>{var F=ya(x);if(et(x,"a")){var $=x.getAttribute("href");E=!!(F&&$&&Hi($))&&(u?fn($):$)}j(ss(x),"ph-no-capture")&&(S=!0),m.push((function(L,N,K,V,M){M===void 0&&(M=!1);var R=L.tagName.toLowerCase(),Z={tag_name:R};hl.indexOf(R)>-1&&!K&&(Z.$el_text=R.toLowerCase()==="a"||R.toLowerCase()==="button"?Oo(1024,zc(L)):Oo(1024,Zi(L)));var Ce=ss(L);Ce.length>0&&(Z.classes=Ce.filter((function(ae){return ae!==""}))),ie(L.attributes,(function(ae){var Ie;if((!yf(L)||["name","id","class","aria-label"].indexOf(ae.name)!==-1)&&(V==null||!V.includes(ae.name))&&!N&&Hi(ae.value)&&(!X(Ie=ae.name)||Ie.substring(0,10)!=="_ngcontent"&&Ie.substring(0,7)!=="_nghost")){var Se=ae.value;ae.name==="class"&&(Se=fl(Se).join(" ")),Z["attr__"+ae.name]=Oo(1024,ae.name==="href"&&M?fn(Se):Se)}}));for(var oe=1,ye=1,$e=L;$e=Om($e);)oe++,$e.tagName===L.tagName&&ye++;return Z.nth_child=oe,Z.nth_of_type=ye,Z})(x,s,o,a,u));var O=(function(L){if(!ya(L))return{};var N={};return ie(L.attributes,(function(K){if(K.name&&K.name.indexOf("data-ph-capture-attribute")===0){var V=K.name.replace("data-ph-capture-attribute-",""),M=K.value;V&&M&&Hi(M)&&(N[V]=M)}})),N})(x);fe(v,O)})),S)return{props:{},explicitNoCapture:S};if(o||(m[0].$el_text=et(t,"a")||et(t,"button")?zc(t):Zi(t)),E){var _,b;m[0].attr__href=E;var k=(_=os(E))==null?void 0:_.host,T=w==null||(b=w.location)==null?void 0:b.host;k&&T&&k!==T&&(p=E)}return{props:fe({$event_type:r.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(x){return x.map((F=>{var $,O,L="";if(F.tag_name&&(L+=F.tag_name),F.attr_class)for(var N of(F.attr_class.sort(),F.attr_class))L+="."+N.replace(/"/g,"");var K=I({},F.text?{text:F.text}:{},{"nth-child":($=F.nth_child)!==null&&$!==void 0?$:0,"nth-of-type":(O=F.nth_of_type)!==null&&O!==void 0?O:0},F.href?{href:F.href}:{},F.attr_id?{attr_id:F.attr_id}:{},F.attributes),V={};return Mr(K).sort(((M,R)=>M[0].localeCompare(R[0]))).forEach((M=>{var R=M[1];return V[qc(M[0].toString())]=qc(R.toString())})),(L+=":")+Mr(V).map((M=>M[0]+'="'+M[1]+'"')).join("")})).join(";")})((function(x){return x.map((F=>{var $,O,L={text:($=F.$el_text)==null?void 0:$.slice(0,400),tag_name:F.tag_name,href:(O=F.attr__href)==null?void 0:O.slice(0,2048),attr_class:Xg(F),attr_id:F.attr__id,nth_child:F.nth_child,nth_of_type:F.nth_of_type,attributes:{}};return Mr(F).filter((N=>N[0].indexOf("attr__")===0)).forEach((N=>L.attributes[N[0]]=N[1])),L}))})(g)))},(n=m[0])!=null&&n.$el_text?{$el_text:(i=m[0])==null?void 0:i.$el_text}:{},p&&r.type==="click"?{$external_click_url:p}:{},v)}}var ki=pe("[ExceptionAutocapture]"),uu=()=>{},Dm=pe("[TracingHeaders]"),wn=pe("[Web Vitals]"),du=9e5,fu="disabled",hu="lazy_loading",Ci="awaiting_config",xr="missing_config";pe("[SessionRecording]"),pe("[SessionRecording]");var Ca="[SessionRecording]",Bt=pe(Ca),jm=pe("[Heatmaps]");function Bo(t){return he(t)&&"clientX"in t&&"clientY"in t&&ke(t.clientX)&&ke(t.clientY)}var Ir=pe("[Product Tours]"),Do=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(ll))},Um=["$set_once","$set"],Et=pe("[SiteApps]"),pu="Error while initializing PostHog app with config id ";function qn(t,e,n){if(H(t))return!1;switch(n){case"exact":return t===e;case"contains":var i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(i,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}class Hm{constructor(e){this.ns=new vl,this.ss=(n,i)=>this.os(n,i)&&this.ls(n,i)&&this.us(n,i)&&this.hs(n,i),this.os=(n,i)=>i==null||!i.event||n?.event===i?.event,this._instance=e,this.ds=new Set,this.vs=new Set}init(){var e,n;C((e=this._instance)==null?void 0:e._addCaptureHook)||(n=this._instance)==null||n._addCaptureHook(((i,r)=>{this.on(i,r)}))}register(e){var n,i;if(!C((n=this._instance)==null?void 0:n._addCaptureHook)&&(e.forEach((o=>{var a,l;(a=this.vs)==null||a.add(o),(l=o.steps)==null||l.forEach((u=>{var c;(c=this.ds)==null||c.add(u?.event||"")}))})),(i=this._instance)!=null&&i.autocapture)){var r,s=new Set;e.forEach((o=>{var a;(a=o.steps)==null||a.forEach((l=>{l!=null&&l.selector&&s.add(l?.selector)}))})),(r=this._instance)==null||r.autocapture.setElementSelectors(s)}}on(e,n){var i;n!=null&&e.length!=0&&(this.ds.has(e)||this.ds.has(n.event))&&this.vs&&((i=this.vs)==null?void 0:i.size)>0&&this.vs.forEach((r=>{this.cs(n,r)&&this.ns.emit("actionCaptured",r.name)}))}fs(e){this.onAction("actionCaptured",(n=>e(n)))}cs(e,n){if(n?.steps==null)return!1;for(var i of n.steps)if(this.ss(e,i))return!0;return!1}onAction(e,n){return this.ns.on(e,n)}ls(e,n){if(n!=null&&n.url){var i,r=e==null||(i=e.properties)==null?void 0:i.$current_url;if(!r||typeof r!="string"||!qn(r,n.url,n.url_matching||"contains"))return!1}return!0}us(e,n){return!!this.ps(e,n)&&!!this.gs(e,n)&&!!this.ys(e,n)}ps(e,n){var i;if(n==null||!n.href)return!0;var r=this.bs(e);if(r.length>0)return r.some((a=>qn(a.href,n.href,n.href_matching||"exact")));var s,o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!o&&qn((s=o.match(/(?::|")href="(.*?)"/))?s[1]:"",n.href,n.href_matching||"exact")}gs(e,n){var i;if(n==null||!n.text)return!0;var r=this.bs(e);if(r.length>0)return r.some((u=>qn(u.text,n.text,n.text_matching||"exact")||qn(u.$el_text,n.text,n.text_matching||"exact")));var s,o,a,l=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!l&&(s=(function(u){for(var c,d=[],f=/(?::|")text="(.*?)"/g;!H(c=f.exec(u));)d.includes(c[1])||d.push(c[1]);return d})(l),o=n.text,a=n.text_matching||"exact",s.some((u=>qn(u,o,a))))}ys(e,n){var i,r;if(n==null||!n.selector)return!0;var s=e==null||(i=e.properties)==null?void 0:i.$element_selectors;if(s!=null&&s.includes(n.selector))return!0;var o=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";if(n.selector_regex&&o)try{return new RegExp(n.selector_regex).test(o)}catch{return!1}return!1}bs(e){var n;return(e==null||(n=e.properties)==null?void 0:n.$elements)==null?[]:e?.properties.$elements}hs(e,n){return n==null||!n.properties||n.properties.length===0||Gf(n.properties.reduce(((i,r)=>{var s=U(r.value)?r.value.map(String):r.value!=null?[String(r.value)]:[];return i[r.key]={values:s,operator:r.operator||"exact"},i}),{}),e?.properties)}}class Wm{constructor(e){var n;this._s=[],this._instance=e,this.ws=new Map,this.ks=new Map,this.xs=new Map,(n=this._instance)==null||n.onSessionId==null||n.onSessionId((i=>this.Ss(i)))}Cs(e){return!1}Ms(){return null}Ts(e){}Es(){}Is(e,n){return!!e&&Gf(e.propertyFilters,n?.properties)}Ps(e,n){var i=new Map;return e.forEach((r=>{var s;(s=r.conditions)==null||(s=s[n])==null||(s=s.values)==null||s.forEach((o=>{if(o!=null&&o.name){var a=i.get(o.name)||[];a.push(r.id),i.set(o.name,a)}}))})),i}Rs(e,n,i){var r=(i===bi.Activation?this.ws:this.ks).get(e),s=[];return this.As((o=>{s=o.filter((a=>r?.includes(a.id)))})),s.filter((o=>{var a,l=(a=o.conditions)==null||(a=a[i])==null||(a=a.values)==null?void 0:a.find((u=>u.name===e));return this.Is(l,n)}))}register(e){var n;C((n=this._instance)==null?void 0:n._addCaptureHook)||(this.Fs(e),this.Ls(e))}Ls(e){var n=e.filter((i=>{var r,s;return((r=i.conditions)==null?void 0:r.actions)&&((s=i.conditions)==null||(s=s.actions)==null||(s=s.values)==null?void 0:s.length)>0}));n.length!==0&&(this.Os==null&&(this.Os=new Hm(this._instance),this.Os.init(),this.Os.fs((i=>{this.onAction(i)}))),n.forEach((i=>{var r,s,o,a,l;i.conditions&&(r=i.conditions)!=null&&r.actions&&(s=i.conditions)!=null&&(s=s.actions)!=null&&s.values&&((o=i.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.Os)==null||a.register(i.conditions.actions.values),(l=i.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var c=this.xs.get(u.name);c&&c.push(i.id),this.xs.set(u.name,c||[i.id])}})))})))}Fs(e){var n,i=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.events)&&((a=s.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0})),r=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.cancelEvents)&&((a=s.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0}));i.length===0&&r.length===0||((n=this._instance)==null||n._addCaptureHook(((s,o)=>{this.onEvent(s,o)})),this.ws=this.Ps(e,bi.Activation),this.ks=this.Ps(e,bi.Cancellation))}onEvent(e,n){var i,r,s=this.Ds(),o=(n==null||(i=n.properties)==null?void 0:i.$survey_id)||(n==null||(r=n.properties)==null?void 0:r.$product_tour_id);if(o&&this.getActivatedIds().includes(o)){var a=this.$s(e,o);if(a==="consume")return s.info("event consumed activated item, removing it",{event:e,itemId:o}),void this.Ns([o]);if(a==="persist")return s.info("shown item promoted to persisted activation",{event:e,itemId:o}),this.qs(o),void this.js([o])}if(this.ks.has(e)){var l=this.Rs(e,n,bi.Cancellation);l.length>0&&(s.info("cancel event matched, cancelling items",{event:e,itemsToCancel:l.map((c=>c.id))}),this.Ns(l.map((c=>c.id))),l.forEach((c=>this.Bs(c.id))))}if(this.ws.has(e)){s.info("event name matched",{event:e,eventPayload:n,items:this.ws.get(e)});var u=this.Rs(e,n,bi.Activation);this.Hs(u.map((c=>c.id)))}}onAction(e){this.xs.has(e)&&this.Hs(this.xs.get(e)||[])}Hs(e){var n;if(e.length!==0){var i=!((n=this._instance)==null||n.get_session_id==null||!n.get_session_id()),r=[];for(var s of e)i&&this.Cs(s)?this.qs(s)&&this.Us(s):r.push(s);r.length>0&&(this._s=[...new Set([...this._s,...r])]),this.Ds().info("updating activated items",{activatedItems:this.getActivatedIds()})}}qs(e){this._s=this._s.filter((i=>i!==e));var n=this.zs();return!n.includes(e)&&(this.Ws([...n,e]),this.Vs(),!0)}Ns(e){var n=new Set(e);this._s=this._s.filter((s=>!n.has(s)));var i=this.Zs(),r=i.filter((s=>!n.has(s)));r.length!==i.length&&(this.Ws(r),r.length===0&&this.Gs()),this.js(e)}Qs(){var e,n=this.Ms();if(!n)return{};var i=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n];return i&&typeof i=="object"?i:{}}Us(e){if(this.Ms()){var n=this.Qs();this.Ts(I({},n,{[e]:Date.now()}))}}js(e){if(this.Ms()){var n=this.Qs(),i={},r=!1;for(var s of Object.entries(n)){var o=s[0],a=s[1];e.includes(o)?r=!0:i[o]=a}r&&(Kt(i)?this.Es():this.Ts(i))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var n=this.Qs()[e];return ke(n)?n:void 0}}Zs(){var e,n=this.Js();return((e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n])||[]}zs(){var e,n,i=this.Zs();if(i.length===0)return[];var r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[this.Ys()],s=(n=this._instance)==null||n.get_session_id==null?void 0:n.get_session_id();return s&&r===s?i:[]}Vs(){var e,n=(e=this._instance)==null||e.get_session_id==null?void 0:e.get_session_id();n&&this.Xs(n)}Gs(){this.ta()}Ss(e){var n,i=(n=this._instance)==null||(n=n.persistence)==null?void 0:n.props[this.Ys()];if(i&&i!==e){var r=this.Zs(),s=this.Qs();r.length>0&&(this.Ws([]),r.filter((o=>ke(s[o]))).forEach((o=>this.Bs(o)))),this.Gs(),this.Ks()}}getActivatedIds(){return[...new Set([...this.zs(),...this._s])].filter((e=>!this.ea(e)))}reset(){this._s=[],this.Zs().length>0&&this.Ws([]),this.Gs(),this.Ks()}getEventToItemsMap(){return this.ws}ia(){return this.Os}}class zm extends Wm{constructor(e){super(e)}Js(){return da}Ys(){return Rr}Ms(){return Tr}Ts(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Tr]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Tr)}Cs(e){var n,i;this.As((s=>{i=s.find((o=>o.id===e))}));var r=(n=i)==null||(n=n.appearance)==null?void 0:n.surveyPopupDelaySeconds;return ke(r)&&r>0}ra(){return qt.SHOWN}As(e){var n;(n=this._instance)==null||n.getSurveys(e)}Bs(e){var n;(n=this._instance)==null||n.cancelPendingSurvey(e)}Ds(){return Q}Ws(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[da]:e})}Xs(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Rr]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Rr)}ea(){return!1}$s(e,n){var i;this.As((s=>{i=s.find((o=>o.id===n))}));var r=!i||(function(s){var o;return Kf(s)&&!((o=s.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||s.schedule==="always"})(i);return r?e===qt.SHOWN?"consume":"ignore":e===qt.SHOWN?"persist":e===qt.DISMISSED||e===qt.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var kr="SDK is not enabled or survey functionality is not yet loaded",gu="Disabled. Not loading surveys.",qm=w!=null&&w.location?as(w.location.hash,"__posthog")||as(location.hash,"state"):null,mu="_postHogToolbarParams",vu=pe("[Toolbar]"),_u=pe("[FeatureFlags]");class Vm{constructor(e,n){n===void 0&&(n=!1),this.na=!1,this.update(e,n)}update(e,n){this.sa=((i,r)=>{var s,o,a,l;return{bootstrap:{featureFlags:(s=i.bootstrap)==null?void 0:s.featureFlags,featureFlagPayloads:(o=i.bootstrap)==null?void 0:o.featureFlagPayloads},remoteRequestsDisabled:r,featureFlagsDisabled:!!i.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!i.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!i.advanced_feature_flags_dedup_per_session,cacheTtlMs:i.feature_flag_cache_ttl_ms,requestTimeoutMs:i.feature_flag_request_timeout_ms,compression:i.disable_compression?"none":"base64",evaluationContexts:(a=(l=i.evaluation_contexts)!==null&&l!==void 0?l:i.evaluation_environments)!==null&&a!==void 0?a:[],flagKeys:U(i.flag_keys)?i.flag_keys:void 0}})(e,n),!e.evaluation_environments||e.evaluation_contexts||this.na||(_u.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.na=!0),C(e.flag_keys)||U(e.flag_keys)||_u.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var yu=pe("[FeatureFlags]"),bn=pe("[FeatureFlags]",{debugEnabled:!0}),jo=`" failed. Feature flags didn't load in time.`,wu="connection_error",bu=t=>{for(var e={},n=0;t.length>n;n++)e[t[n]]=!0;return e},Eu=t=>{var e={};for(var n of Mr(t||{})){var i=n[1];i&&(e[n[0]]=i)}return e},St=pe("[Error tracking]"),Su="Refusing to render web experiment since the viewer is a likely bot",Gm={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>us(e,t),not_regex:(t,e)=>!us(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class Me{get Ne(){return this._instance.config}constructor(e){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(i){i===void 0&&(i=!1),n.getWebExperiments((r=>{Me.aa("retrieved web experiments from the server"),n.oa=new Map,r.forEach((s=>{if(s.feature_flag_key){var o;n.oa&&(Me.aa("setting flag key ",s.feature_flag_key," to web experiment ",s),(o=n.oa)==null||o.set(s.feature_flag_key,s));var a=n._instance.getFeatureFlag(s.feature_flag_key);X(a)&&s.variants[a]&&n.la(s.name,a,s.variants[a].transforms)}else if(s.variants)for(var l in s.variants){var u=s.variants[l];Me.ua(u,n._instance)&&n.la(s.name,l,u.transforms)}}))}),i)},this._instance=e,this._instance.onFeatureFlags((i=>{this.onFeatureFlags(i)}))}initialize(){}onFeatureFlags(e){if(this._is_bot())Me.aa(Su);else if(!this.Ne.disable_web_experiments){if(H(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();Me.aa("applying feature flags",e),e.forEach((n=>{var i;if(this.oa&&(i=this.oa)!=null&&i.has(n)){var r,s=this._instance.getFeatureFlag(n),o=(r=this.oa)==null?void 0:r.get(n);s&&o!=null&&o.variants[s]&&this.la(o.name,s,o.variants[s].transforms)}}))}}previewWebExperiment(){var e=Me.getWindowLocation();if(e!=null&&e.search){var n=ri(e?.search,"__experiment_id"),i=ri(e?.search,"__experiment_variant");n&&i&&(Me.aa("previewing web experiments "+n+" && "+i),this.getWebExperiments((r=>{this.ha(parseInt(n),i,r)}),!1,!0))}}loadIfEnabled(){this.Ne.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,n,i){if(this.Ne.disable_web_experiments&&!i)return e([]);var r=this._instance.get_property("$web_experiments");if(r&&!n)return e(r);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this.Ne.token),method:"GET",timestampMode:"query",callback:s=>e(s.statusCode===200&&s.json&&s.json.experiments||[])})}ha(e,n,i){var r=i.filter((s=>s.id===e));r&&r.length>0&&(Me.aa("Previewing web experiment ["+r[0].name+"] with variant ["+n+"]"),this.la(r[0].name,n,r[0].variants[n].transforms))}static ua(e,n){return!H(e.conditions)&&Me.da(e,n)&&Me.va(e)}static da(e,n){var i;if(H(e.conditions)||H((i=e.conditions)==null?void 0:i.url))return!0;var r=Me.getWindowLocation();if(r){var s,o,a,l=uf(n,r.href);return(s=e.conditions)==null||!s.url||Gm[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return w?.location}static va(e){var n;if(H(e.conditions)||H((n=e.conditions)==null?void 0:n.utm))return!0;var i=If();if(i.utm_source){var r,s,o,a,l,u,c,d,f=(r=e.conditions)==null||(r=r.utm)==null||!r.utm_campaign||((s=e.conditions)==null||(s=s.utm)==null?void 0:s.utm_campaign)==i.utm_campaign,h=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==i.utm_source,p=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==i.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==i.utm_term;return f&&p&&g&&h}return!1}static aa(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;n>r;r++)i[r-1]=arguments[r];A.info("[WebExperiments] "+e,i)}la(e,n,i){this._is_bot()?Me.aa(Su):n!=="control"?i.forEach((r=>{if(r.selector){var s;Me.aa("applying transform of variant "+n+" for experiment "+e+" ",r);var o=(s=document)==null?void 0:s.querySelectorAll(r.selector);o?.forEach((a=>{var l=a;r.html&&(l.innerHTML=r.html),r.css&&l.setAttribute("style",r.css)}))}})):Me.aa("Control variants leave the page unmodified.")}_is_bot(){return He&&this._instance?zf(He,this.Ne.custom_blocked_useragents):void 0}}var ot=pe("[Conversations]"),En="Conversations not available yet.",xu="console",Qf="__posthogHandledLogsRequestError",Uo=(t,e)=>{var n=t instanceof Error?t:new Error(e);return n[Qf]=!0,n},Iu=t=>!!t&&typeof t=="object"&&t[Qf]===!0,As={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=yu,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 Vm(t.config,t.Qi()),this.Ta=this.Ea)}updateConfig(t,e){var n;(n=this.Ea)==null||n.update(t,e)}setup(t){return this.Ia=t,this.rt=t.logger.createLogger("[FeatureFlags]"),n=()=>{this.Ia===t&&(this.Ia=void 0,this.nn=t,this.Pa(t))},(e=t.kv.initialize())!=null&&e.then?e.then(n):n();var e,n}Pa(t){if(this.nn===t)return w&&ve(w,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){w?.removeEventListener("online",this.Ca)}dispose(){var t;this.ba++,this.wa=!1,this.Ia=void 0,this.nn&&(this.La(),(t=this.Ra)==null||t.dispose(),this.Ra=void 0,this.ga=[],w?.removeEventListener("online",this.Ca),this.nn=void 0)}get Ne(){return this.Ta.get()}Oa(t){var e;return(e=this.nn)==null?void 0:e.kv.get(t)}F(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.set(t)}))}q(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.remove(t)}))}Da(t){try{t()}catch(e){this.rt.error("Failed to update feature flag persistence",e)}}Fa(){var t={};for(var e of[$i,Mi,Fr,It]){var n=this.Oa(e);C(n)||(t[e]=n)}this.fa=t;var i=I({},t),r=this.Oa(Sn);if(r)for(var s of Object.entries(r))i["$feature/"+s[0]]=s[1];this.pa=i}Aa(){var t=this.Ne.cacheTtlMs;if(!t||0>=t)return!1;var e=this.Oa(Ui);return typeof e!="number"||Date.now()-e>t}$a(){return!!this.Aa()&&(this.xa||this.ya||(this.xa=!0,this.rt.warn("Feature flag cache is stale, triggering refresh..."),this.reloadFeatureFlags()),!0)}Na(){var t=this.Ne.evaluationContexts;return t!=null&&t.length?t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid evaluation context found:",e,"Expected non-empty string"),n})):[]}qa(){var t=this.Ne.flagKeys;if(!C(t))return t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid flag key found:",e,"Expected non-empty string"),n}))}initialize(){var t,e,n=this.Ne,i=(t=(e=n.bootstrap)==null?void 0:e.featureFlags)!==null&&t!==void 0?t:{};if(Object.keys(i).length){var r,s,o=(r=(s=n.bootstrap)==null?void 0:s.featureFlagPayloads)!==null&&r!==void 0?r:{},a=Object.keys(i).filter((u=>!!i[u])).reduce(((u,c)=>(u[c]=i[c]||!1,u)),{}),l=Object.keys(o).filter((u=>a[u])).reduce(((u,c)=>(o[c]&&(u[c]=o[c]),u)),{});return this.ja({featureFlags:a,featureFlagPayloads:l})}}updateFlags(t,e,n){var i,r,s=n!=null&&n.merge&&(i=this.Oa(Sn))!==null&&i!==void 0?i:{},o=n!=null&&n.merge&&(r=this.Oa(Mi))!==null&&r!==void 0?r:{},a=I({},s,t),l=I({},o,e),u={};for(var c of Object.entries(a)){var d=c[0],f=c[1];u[d]={key:d,enabled:vc(f),variant:_c(f),reason:void 0,metadata:C(l?.[d])?void 0:{id:0,version:void 0,description:void 0,payload:l[d]}}}this.ja({flags:u})}get hasLoadedFlags(){return this.ma}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var t=this.Oa(ca),e=this.Oa(It),n=this.Oa(xn);if(!n&&!e)return t||{};var i=fe({},t||{}),r=[...new Set([...Object.keys(n||{}),...Object.keys(e||{})])];for(var s of r){var o,a,l=i[s],u=e?.[s],c=C(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=C(u)?l?.variant:typeof u=="string"?u:void 0,f=n?.[s],h=I({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(h.original_enabled=l?.enabled),d!==l?.variant&&(h.original_variant=l?.variant),f&&(h.metadata=I({},l?.metadata,{payload:f,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),i[s]=h}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:n,finalDetails:i}),this.ca=!0),i}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((n=>{var i=t[n];return{key:n,enabled:vc(i),variant:_c(i),payload:mc(e[n])}}))}getFlagVariants(){var t=this.Oa(Sn),e=this.Oa(It);if(!e)return t||{};for(var n=fe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:e,finalFlags:n}),this.ca=!0),n}getFlagPayloads(){var t=this.Oa(Mi),e=this.Oa(xn);if(!e)return t||{};for(var n=fe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flag payloads!",{flagPayloads:t,overriddenPayloads:e,finalPayloads:n}),this.ca=!0),n}reloadFeatureFlags(){this._a||this.Ne.featureFlagsDisabled||this.Ma()||this.Ba||(this.ga.slice().forEach((t=>{try{t()}catch(e){this.rt.error("Error while running feature flags reloading callback",e)}})),this.Ba=setTimeout((()=>{this.Ha()}),5))}La(){clearTimeout(this.Ba),this.Ba=void 0}onReloading(t){return this.ga.push(t),()=>{this.ga=this.ga.filter((e=>e!==t))}}ensureFlagsLoaded(){this.ma||this.ya||this.Ba||this.reloadFeatureFlags()}setAnonymousDistinctId(t){this.$anon_distinct_id=t}setReloadingPaused(t){this._a=t}resetFlagCallReported(){this.q(Cn)}Ha(t){this.La();var e=this.nn;if(e&&!this.Ne.remoteRequestsDisabled&&!this.Ma())if(this.ya)this.wa=!0;else{var n={token:e.projectToken,distinct_id:e.distinctId,groups:e.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:I({},e.initialPersonProperties,this.Oa(jt)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(In),timezone:Rf()};C(e.deviceId)||(n.$device_id=e.deviceId),(t!=null&&t.disableFlags||this.Ne.featureFlagsDisabled)&&(n.disable_flags=!0);var i=this.Na();i.length&&(n.evaluation_contexts=i);var r=this.qa();C(r)||(n.flag_keys=r);var s=this.Ne.onlyEvaluateSurveyFeatureFlags,o="/flags/?v=2"+(s?"&only_evaluate_survey_feature_flags=true":""),a=this.ba;this.ya=!0;var l=()=>{this.wa&&(this.wa=!1,this.Ha())},u=c=>{this.ya=!1,a===this.ba&&(this.F({[$r]:[wu]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:n,compression:this.Ne.compression==="base64"?Ue.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,f,h=(d=c.json)!==null&&d!==void 0?d:{},p=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),p||this.wa||(this.$anon_distinct_id=void 0),!n.disable_flags||this.wa){this.ka=!p;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?wu:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),h.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((f=h.quotaLimited)==null||!f.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[$r]:g}),m?this.rt.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more."):n.disable_flags||this.ja(h,p,{partialResponse:s}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return Sf(this.Sa,3)}Ua(t){this.Sa=xf(t,this.Sa,3,(()=>this.rt.warn("Feature flag requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped refreshing feature flags; will try again when connectivity changes.")))}getFeatureFlag(t,e){var n;if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var i=this.getFeatureFlagResult(t,e);return(n=i?.variant)!==null&&n!==void 0?n:i?.enabled}}else this.rt.warn('getFeatureFlag for key "'+t+jo)}getFeatureFlagDetails(t){return this.getFlagsWithDetails()[t]}getFeatureFlagPayload(t){var e=this.getFeatureFlagResult(t,{send_event:!1});return e?.payload}getFeatureFlagResult(t,e){if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var n,i=this.getFlagVariants(),r=t in i,s=i[t],o=this.getFlagPayloads()[t],a=String(s),l=this.Oa(Fr)||void 0,u=this.Oa(Ui)||void 0,c=this.Oa(Cn)||{};if(this.Ne.deduplicateCallsPerSession){var d,f=(d=this.nn)==null?void 0:d.session.sessionId,h=this.Oa(Ni);f&&f!==h&&(c={},n=f)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))n&&this.F({[Cn]:c,[Ni]:n});else{var p,g,m,v,E,S,_,b,k,T;U(c[t])?c[t].push(a):c[t]=[a],this.F(I({[Cn]:c},n?{[Ni]:n}:{}));var x=this.getFeatureFlagDetails(t),F=[...(p=this.Oa($r))!==null&&p!==void 0?p:[]];C(s)&&F.push("flag_missing");var $={$feature_flag:t,$feature_flag_response:s,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((g=this.Ne.bootstrap)==null||(g=g.featureFlags)==null?void 0:g[t])||null,$feature_flag_bootstrapped_payload:((m=this.Ne.bootstrap)==null||(m=m.featureFlagPayloads)==null?void 0:m[t])||null,$used_bootstrap_value:!this.ka};C(x==null||(v=x.metadata)==null?void 0:v.has_experiment)||($.$feature_flag_has_experiment=x.metadata.has_experiment),C(x==null||(E=x.metadata)==null?void 0:E.version)||($.$feature_flag_version=x.metadata.version);var O,L=(S=x==null||(_=x.reason)==null?void 0:_.description)!==null&&S!==void 0?S:x==null||(b=x.reason)==null?void 0:b.code;L&&($.$feature_flag_reason=L),x!=null&&(k=x.metadata)!=null&&k.id&&($.$feature_flag_id=x.metadata.id),C(x?.original_variant)&&C(x?.original_enabled)||($.$feature_flag_original_response=C(x.original_variant)?x.original_enabled:x.original_variant),x!=null&&(T=x.metadata)!=null&&T.original_payload&&($.$feature_flag_original_payload=x==null||(O=x.metadata)==null?void 0:O.original_payload),F.length&&($.$feature_flag_error=F.join(",")),this.za($)}else n&&this.F({[Cn]:c,[Ni]:n});if(r)return{key:t,enabled:!!s,variant:typeof s=="string"?s:void 0,payload:mc(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+jo)}za(t){try{var e;(e=this.nn)==null||e.capture("$feature_flag_called",t).catch((n=>{this.rt.error("Failed to capture feature flag call",n)}))}catch(n){this.rt.error("Failed to capture feature flag call",n)}}getRemoteConfigPayload(t,e){this.Wa(t,e)}Wa(t,e){var n=this;return se((function*(){var i=n.nn;if(i){var r={distinct_id:i.distinctId,token:i.projectToken,person_properties:{$lib:i.library.name,$lib_version:i.library.version}},s=n.Na();s.length&&(r.evaluation_contexts=s);var o,a=n.qa();C(a)||(r.flag_keys=a);try{var l,u=(l=(yield i.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:r,compression:n.Ne.compression==="base64"?Ue.Base64:void 0,sentAt:"body",timeoutMs:n.Ne.requestTimeoutMs})).json)==null?void 0:l.featureFlagPayloads;o=u?.[t]||void 0}catch(c){return void n.rt.error("Remote config feature flag request failed",c)}try{e(o)}catch(c){n.rt.error("Remote config feature flag callback failed",c)}}}))()}isFeatureEnabled(t,e){if(e===void 0&&(e={}),e.fresh&&!this.ka)return e.defaultValue;if(!(this.ma||this.getFlags()&&this.getFlags().length>0))return this.rt.warn('isFeatureEnabled for key "'+t+jo),e.defaultValue;var n=this.getFeatureFlag(t,e);return C(n)?e.defaultValue:!!n}addFeatureFlagsHandler(t){this.featureFlagEventHandlers.push(t)}removeFeatureFlagsHandler(t){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((e=>e!==t))}receivedFeatureFlags(t,e,n){this.ja(t,e,n)}ja(t,e,n){if(this.nn){this.ma=!0;var i=(function(r,s,o,a,l,u){s===void 0&&(s={}),o===void 0&&(o={}),a===void 0&&(a={}),u===void 0&&(u=yu);var c=((k,T)=>{var x=k.flags;return x?I({},k,{featureFlags:Object.fromEntries(Object.keys(x).map((F=>{var $;return[F,($=x[F].variant)!==null&&$!==void 0?$:x[F].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(x).filter((F=>x[F].enabled)).filter((F=>{var $;return($=x[F].metadata)==null?void 0:$.payload})).map((F=>{var $;return[F,($=x[F].metadata)==null?void 0:$.payload]})))}):(k.featureFlags&&T.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),k)})(r,u),d=c.flags,f=c.featureFlags,h=c.featureFlagPayloads;if(f){var p=r.requestId,g=r.evaluatedAt;if(U(f)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(f)for(var v=0;f.length>v;v++)m[f[v]]=!0;return{[$i]:f,[Sn]:m,[Xr]:!1}}var E=f,S=h,_=d;if(l!=null&&l.partialResponse)E=I({},s,E),S=I({},o,S),_=I({},a,_);else if(r.errorsWhileComputingFlags)if(d){var b=new Set(Object.keys(d).filter((k=>{var T;return!((T=d[k])!=null&&T.failed)})));E=I({},s,Object.fromEntries(Object.entries(E).filter((k=>b.has(k[0]))))),S=I({},o,Object.fromEntries(Object.entries(S||{}).filter((k=>b.has(k[0]))))),_=I({},a,Object.fromEntries(Object.entries(_||{}).filter((k=>b.has(k[0])))))}else E=I({},s,E),S=I({},o,S),_=I({},a,_);return I({[$i]:Object.keys(Eu(E)),[Sn]:E||{},[Mi]:S||{},[ca]:_||{},[Xr]:r.minimalFlagCalledEvents===!0},p?{[Fr]:p}:{},g?{[Ui]:g}:{})}})(t,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),n,this.rt);i&&this.F(i),e||(this.xa=!1),this.Va(e)}}override(t,e){e===void 0&&(e=!1),this.rt.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:t,suppressWarning:e})}overrideFeatureFlags(t){this.Za(t)}Za(t){if(this.nn){if(t===!1)return this.q([It,xn]),this.Va(),void bn.info("All overrides cleared");if(U(t))return this.F({[It]:bu(t)}),this.Va(),void bn.info("Flag overrides set",{flags:t});if(t&&typeof t=="object"&&("flags"in t||"payloads"in t)){var e,n=t;this.ca=!!((e=n.suppressWarning)!==null&&e!==void 0&&e);var i={},r=n.flags,s=n.payloads;return r&&(i[It]=U(r)?bu(r):r),s&&(i[xn]=s),Object.keys(i).length&&this.F(i),r===!1&&s===!1?this.q([It,xn]):r===!1?this.q(It):s===!1&&this.q(xn),this.Va(),r===!1?bn.info("Flag overrides cleared"):r&&bn.info("Flag overrides set",{flags:r}),void(s===!1?bn.info("Payload overrides cleared"):s&&bn.info("Payload overrides set",{payloads:s}))}if(t&&typeof t=="object")return this.F({[It]:t}),this.Va(),void bn.info("Flag overrides set",{flags:t});this.rt.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:t})}else this.rt.warn("posthog.featureFlags.overrideFeatureFlags called before feature flags were ready")}onFeatureFlags(t){if(this.addFeatureFlagsHandler(t),this.ma){var e=this.Ga(),n=e.flags,i=e.flagVariants;try{t(n,i)}catch(r){this.rt.error("Error while running feature flags callback",r)}}return()=>this.removeFeatureFlagsHandler(t)}updateEarlyAccessFeatureEnrollment(t,e,n){var i=(this.Oa(Pr)||[]).find((l=>l.flagKey===t)),r={["$feature_enrollment/"+t]:e},s={$feature_flag:t,$feature_enrollment:e,$set:r};i&&(s.$early_access_feature_name=i.name),n&&(s.$feature_enrollment_stage=n);var o=I({},this.getFlagVariants(),{[t]:e});this.F({[$i]:Object.keys(Eu(o)),[Sn]:o,[jt]:I({},this.Oa(jt)||{},r)}),this.Va();try{var a;(a=this.nn)==null||a.capture("$feature_enrollment_update",s).catch((l=>{this.rt.error("Failed to capture early access feature enrollment",l)}))}catch(l){this.rt.error("Failed to capture early access feature enrollment",l)}}getEarlyAccessFeatures(t,e,n){e===void 0&&(e=!1);var i=this.Oa(Pr);!i||e?this.Qa(t,n):t(i)}Qa(t,e){var n=this;return se((function*(){var i=n.nn;if(i){var r,s=e?"&"+e.map((a=>"stage="+a)).join("&"):"";try{var o=yield i.sendRequest("/api/early_access_features/?token="+i.projectToken+s,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;n.F({[Pr]:r=o.json.earlyAccessFeatures})}catch(a){return void n.rt.error("Early access feature request failed",a)}try{t(r)}catch(a){n.rt.error("Early access feature callback failed",a)}}}))()}Ga(){var t=this.getFlags(),e=this.getFlagVariants();return{flags:t.filter((n=>e[n])),flagVariants:Object.keys(e).filter((n=>e[n])).reduce(((n,i)=>(n[i]=e[i],n)),{})}}Va(t){this.Fa();var e=this.Ga(),n=e.flags,i=e.flagVariants;this.featureFlagEventHandlers.forEach((r=>{try{r(n,i,{errorsLoading:t})}catch(s){this.rt.error("Error while running feature flags callback",s)}}))}setPersonPropertiesForFlags(t,e){e===void 0&&(e=!0),this.Ka(t,e)}Ka(t,e){e===void 0&&(e=!0);var n=this.Oa(jt)||{},i=t?.$set||(t!=null&&t.$set_once?{}:t),r=t?.$set_once,s={};if(r)for(var o in r)({}).hasOwnProperty.call(r,o)&&(o in n||(s[o]=r[o]));this.F({[jt]:I({},n,s,i)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=I({},this.Oa(jt)||{});t.forEach((i=>{delete n[i]})),this.F({[jt]:n}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(jt),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=this.Oa(In)||{},i=I({},n);for(var r of Object.keys(t))i[r]=I({},n[r],t[r]);this.F({[In]:i}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(In)||{};this.F({[In]:I({},e,{[t]:{}})})}else this.q(In)}reset(){this.ba++,this.wa=!1,this.Fa(),this.ma=!1,this._a=!1,this.ka=!1,this.$anon_distinct_id=void 0,this.La(),this.ca=!1,this.Sa=0}}},Km={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===Ci||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=fu,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(P==null||!P.visibilityState||P.visibilityState==="visible")return!0;var n=w==null||(e=w.performance)==null||e.getEntriesByType==null?void 0:e.getEntriesByType("visibility-state");return!(n!=null&&n.length)||n.some((i=>i.name==="visible"))})(),this.Ie=()=>{var e;P?.visibilityState==="visible"&&(this.io=!0,(e=this.Ja)==null||e.setDocumentWasEverVisible==null||e.setDocumentWasEverVisible(!0))},this._instance=t,!this._instance.sessionManager)throw Bt.error("started without valid sessionManager"),new Error(Ca+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===Wt)throw new Error(Ca+' cannot be used with cookieless_mode="always"');P!=null&&P.addEventListener&&ve(P,"visibilitychange",this.Ie)}initialize(){this.startIfEnabledOrStop()}dispose(){this.eo=!0,P==null||P.removeEventListener==null||P.removeEventListener("visibilitychange",this.Ie),this.stopRecording()}get ro(){var t,e=!((t=this._instance.get_property(An))==null||!t.enabled),n=!this.Ne.disable_session_recording,i=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return w&&e&&n&&!i}startIfEnabledOrStop(t){var e;if(!(this.eo||this.ro&&(e=this.Ja)!=null&&e.isStarted)){var n=!C(Object.assign)&&!C(Array.from);this.ro&&n?(this.no(t),Bt.info("starting")):(this.Ya=fu,this.stopRecording())}}no(t){var e,n,i;this.ro&&(this.Ya!==Ci&&this.Ya!==xr&&(this.Ya=hu),B!=null&&(e=B.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(n=B.__PosthogExtensions__)!=null&&n.initSessionRecording?this.so(t):(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,this.ao,(r=>{if(r)return Bt.error("could not load recorder",r);this.so(t)})))}stopRecording(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.stop()}oo(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.discard()}lo(){var t,e;(t=this.Mr)==null||t.unregister(cl),(e=this.Mr)==null||e.unregister(Xd)}uo(t,e){if(H(t))return null;var n,i=ke(t)?t:parseFloat(t);return typeof(n=i)!="number"||!Number.isFinite(n)||0>n||n>1?(Bt.warn(e+" must be between 0 and 1. Ignoring invalid value:",t),null):i}ho(t){if(this.Mr){var e,n,i=this.Mr,r=()=>{var s,o=t.sessionRecording===!1?void 0:t.sessionRecording,a=this.uo((s=this.Ne.session_recording)==null?void 0:s.sampleRate,"session_recording.sampleRate"),l=this.uo(o?.sampleRate,"remote config sampleRate"),u=a??l;H(u)&&this.lo();var c=o?.minimumDurationMilliseconds;i.register({[An]:I({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:I({capturePerformance:t.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:u,minimumDurationMilliseconds:C(c)?null:c,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers,version:o?.version,triggerGroups:o?.triggerGroups})})};r(),(e=this.Xa)==null||e.call(this),this.Xa=(n=this._instance.sessionManager)==null?void 0:n.onSessionId(r)}}onRemoteConfig(t){var e=t.ok?t.config:void 0;return e&&"sessionRecording"in e?e.sessionRecording===!1?(this.ho(e),void this.oo()):(this.ho(e),void this.startIfEnabledOrStop()):(this.Ya===Ci&&(this.Ya=xr,Bt.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(t,e){var n;e===void 0&&(e="log"),(n=this.Ja)!=null&&n.log?this.Ja.log(t,e):Bt.warn("log called before recorder was ready")}get ao(){var t,e,n=(t=this._instance)==null||(t=t.persistence)==null?void 0:t.get_property(An);return(n==null||(e=n.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(An);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(n){return Bt.warn("persisted remote config for session recording is invalid and will be ignored",n),!1}return!H(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,n,i;if(!this.eo){if((e=B.__PosthogExtensions__)==null||!e.initSessionRecording)return Bt.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[af]:!0});var r;if(this.Ja||(this.Ja=(r=B.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===xr||this.Ya===Ci?void 0:(this.Ya=Ci,Bt.info("persisted remote config is stale, requesting fresh config before starting"),void new Tf(this._instance).load());this.Ya=hu,(n=(i=this.Ja).setDocumentWasEverVisible)==null||n.call(i,this.io),this.Ja.start(t)}}onRRwebEmit(t){var e;(e=this.Ja)==null||e.onRRwebEmit==null||e.onRRwebEmit(t)}overrideLinkedFlag(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[ef]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Qd]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,n;this.Ja||(n=this.Mr)==null||n.register({[t==="url"?tf:nf]:!0}),(e=this.Ja)==null||e.overrideTrigger(t)}get sdkDebugProperties(){var t;return((t=this.Ja)==null?void 0:t.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(t,e){var n;return!((n=this.Ja)==null||!n.tryAddCustomEvent(t,e))}}},Ym={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new cu(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,n=he(this.instance.config.autocapture)?this.instance.config.autocapture:{};return n.url_allowlist=(t=n.url_allowlist)==null?void 0:t.map((i=>new RegExp(i))),n.url_ignorelist=(e=n.url_ignorelist)==null?void 0:e.map((i=>new RegExp(i))),n}yo(){if(this.isBrowserSupported()){if(w&&P){var t=n=>{n=n||w?.event;try{this.bo(n)}catch(i){No.error("Failed to capture event",i)}};if(ve(P,"submit",t,{capture:!0}),ve(P,"change",t,{capture:!0}),ve(P,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=n=>{n=n||w?.event;try{this.bo(n,Lo)}catch(i){No.error("Failed to capture copy/cut event",i)}};ve(P,"copy",e,{capture:!0}),ve(P,"cut",e,{capture:!0})}}}else No.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.vo&&(this.yo(),this.vo=!0)}onRemoteConfig(t){if(this.fo=!0,t.ok){var e=t.config;e.elementsChainAsString&&(this.po=e.elementsChainAsString);var n=e.autocapture_opt_out;mt(n)&&(this.instance.persistence&&this.instance.persistence.register({[na]:n}),this.co=n),this.startIfEnabled()}else this.startIfEnabled()}setElementSelectors(t){this.mo=t}getElementSelectors(t){var e,n=[];return(e=this.mo)==null||e.forEach((i=>{var r=P?.querySelectorAll(i);r?.forEach((s=>{t===s&&n.push(i)}))})),n}get isEnabled(){var t,e,n=(t=this.instance.persistence)==null?void 0:t.props[na],i=this.co,r=this.instance.Qi()&&!this.fo;if(Ye(i)&&!mt(n)&&!r)return!1;var s=(e=this.co)!==null&&e!==void 0?e:!!n;return!!this.instance.config.autocapture&&!s}bo(t,e){if(e===void 0&&(e="$autocapture"),this.isEnabled){var n,i=So(t);ff(i)&&(i=i.parentNode||null),e==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&this.instance.config.rageclick&&(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,t.timeStamp||new Date().getTime())&&Dc(i,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var r=e===Lo;if(i&&(function(d,f,h,p,g,m){var v;if(!w||pl(d)||h!=null&&h.url_allowlist&&!Nc(h.url_allowlist,m)||h!=null&&h.url_ignorelist&&Nc(h.url_ignorelist,m))return!1;if(h!=null&&h.dom_event_allowlist){var E=h.dom_event_allowlist;if(E&&!E.some((x=>f.type===x)))return!1}var S=_f(d,p),_=S.parentIsUsefulElement,b=S.targetElementList;if(!(function(x,F){var $=F?.element_allowlist;if(C($))return!0;var O,L=function(K){if($.some((V=>K.tagName.toLowerCase()===V)))return{v:!0}};for(var N of x)if(O=L(N))return O.v;return!1})(b,h)||!_a(b,h?.css_selector_allowlist)||_a(b,(v=h?.css_selector_ignorelist)!==null&&v!==void 0?v:Vg))return!1;try{var k=w.getComputedStyle(d);if(k&&k.getPropertyValue("cursor")==="pointer"&&f.type==="click")return!0}catch{}var T=d.tagName.toLowerCase();switch(T){case"html":return!1;case"form":return(g||["submit"]).indexOf(f.type)>=0;case"input":case"select":case"textarea":return(g||["change","click"]).indexOf(f.type)>=0;default:return _?(g||["click"]).indexOf(f.type)>=0:(g||["click"]).indexOf(f.type)>=0&&(hl.indexOf(T)>-1||d.getAttribute("contenteditable")==="true")}})(i,t,this.Ne,r,r?["copy","cut"]:void 0,this.instance)){var s=Bm(i,{e:t,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.Ne.element_attribute_ignorelist,elementsChainAsString:this.po,disableCaptureUrlHashes:this.instance.config.disable_capture_url_hashes}),o=s.props;if(s.explicitNoCapture)return!1;var a=this.getElementSelectors(i);if(a&&a.length>0&&(o.$element_selectors=a),e===Lo){var l,u=gf(w==null||(l=w.getSelection())==null?void 0:l.toString()),c=t.type||"clipboard";if(!u)return!1;o.$selected_content=u,o.$copy_type=c}return this.instance.capture(e,o),!0}}}isBrowserSupported(){return je(P?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(w==null||(e=w.location)==null?void 0:e.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(A.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.wo&&this.wo(),this.wo=void 0,A.info("History API monitoring stopped")}monitorHistoryChanges(){w&&w.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(w&&((e=w.history[t])==null||!e.__posthog_wrapped__)){var n=this;(function(i,r,s){try{if(!(r in i))return uu;var o={next:i[r]},a=s((function(){for(var l=arguments.length,u=new Array(l),c=0;l>c;c++)u[c]=arguments[c];return o.next.apply(this,u)}));return je(a)&&(a.prototype=a.prototype||{},Object.defineProperties(a,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:o}})),i[r]=a,()=>{if(i[r]!==a)for(var l=i[r];je(l)&&l.__posthog_layer__;){var u=l.__posthog_layer__;if(u.next===a)return void(u.next=o.next);l=u.next}else i[r]=o.next}}catch{return uu}})(w.history,t,(i=>function(r,s,o){i.call(this,r,s,o),n.So(t)}))}}So(t){try{var e,n=w==null||(e=w.location)==null?void 0:e.pathname;if(!n)return;n!==this._o&&this.isEnabled&&this._instance.capture(Gn,{navigation_type:t}),this._o=n}catch(i){A.error("Error capturing "+t+" pageview",i)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};ve(w,"popstate",t),this.wo=()=>{w&&w.removeEventListener("popstate",t)}}}},heatmaps:class{get Ne(){return this.instance.config}constructor(t){var e;this.Co=!1,this.vo=!1,this.Mo=null,this.instance=t,this.Co=!((e=this.instance.persistence)==null||!e.props[ia]),this.rageclicks=new cu(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return he(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return H(this.Ne.capture_heatmaps)?H(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;jm.info("starting..."),this.To(),this.Ie()}else{var t;clearInterval((t=this.Mo)!==null&&t!==void 0?t:void 0),this.Eo(),this.getAndClearBuffer()}}onRemoteConfig(t){if(t.ok){var e=t.config;if("heatmaps"in e){var n=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[ia]:n}),this.Co=n,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){Bo(t.originalEvent)&&this.ke(t.originalEvent,"deadclick")}Ie(){this.Mo&&clearInterval(this.Mo),this.Mo=P?.visibilityState==="visible"?setInterval(this.cr.bind(this),this.flushIntervalMilliseconds):null}To(){w&&P&&(this.Po=this.cr.bind(this),ve(w,is,this.Po),this.Ro=t=>this.ke(t||w?.event),ve(P,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||w?.event),ve(P,"mousemove",this.Ao,{capture:!0}),this.Lo=new Vc(this.instance,Qg,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),ve(P,ns,this.Oo),this.vo=!0)}Eo(){var t;w&&P&&(this.Po&&w.removeEventListener(is,this.Po),this.Ro&&P.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&P.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&P.removeEventListener(ns,this.Oo),clearTimeout(this.Do),(t=this.Lo)==null||t.stop(),this.vo=!1)}$o(t,e){var n=this.instance.scrollManager.scrollY(),i=this.instance.scrollManager.scrollX(),r=this.instance.scrollManager.scrollElement(),s=(function(o,a,l){for(var u=o;u&&hn(u)&&!et(u,"body");){if(u===l)return!1;var c=void 0;try{var d,f,h;c=(d=(f=(h=u.ownerDocument)==null?void 0:h.defaultView)!==null&&f!==void 0?f:w)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(j(a,c))return!0;u=mf(u)}return!1})(So(t),["fixed","sticky"],r);return{x:t.clientX+(s?0:i),y:t.clientY+(s?0:n),target_fixed:s,type:e}}ke(t,e){var n;if(e===void 0&&(e="click"),!Lc(t.target)&&Bo(t)){var i=this.$o(t,e);(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,new Date().getTime())&&Dc(So(t),this.instance.config.rageclick)&&this.Vt(I({},i,{type:"rageclick"})),this.Vt(i)}}Fo(t){!Lc(t.target)&&Bo(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(w){var e=this.Ne.disable_capture_url_hashes?fn(w.location.href):w.location.href,n=this.Ne.custom_personal_data_properties,i=this.Ne.mask_personal_data_properties?[...si,...n||[]]:[],r=Xi(e,i,Qi);this.R=this.R||{},this.R[r]||(this.R[r]=[]),this.R[r].push(t)}}cr(){this.R&&!Kt(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:Vc,webVitalsAutocapture:class{constructor(t){var e;this.Co=!1,this.vo=!1,this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this.No=()=>{clearTimeout(this.qo),this.qo=void 0,this.R.metrics.length!==0&&(this._instance.capture("$web_vitals",I({$current_url:this.R.url},this.R.metrics.reduce(((n,i)=>I({},n,{["$web_vitals_"+i.name+"_event"]:I({},i),["$web_vitals_"+i.name+"_value"]:i.value})),{}))),this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.jo=n=>{var i;if(this.R=this.R||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},H(n?.name)||H(n?.value))wn.error("Invalid metric received",n);else{var r=typeof n.navigationURL=="string"?n.navigationURL:void 0,s=this.Bo(r);if(!C(s)){var o=ke(n.navigationId)||typeof n.navigationId=="string"?"navigation:"+n.navigationId:"url:"+s;if(!this.Ho||this.Ho>n.value){this.R.navigationKey!==o&&(this.No(),this.qo=setTimeout(this.No,this.flushToCaptureTimeoutMs)),C(this.R.navigationKey)&&(this.R.navigationKey=o,this.R.url=s),this.R.firstMetricTimestamp=C(this.R.firstMetricTimestamp)?Date.now():this.R.firstMetricTimestamp,n.attribution&&n.attribution.interactionTargetElement&&(n.attribution.interactionTargetElement=void 0);var a=(i=this._instance.sessionManager)==null?void 0:i.checkAndGetSessionAndWindowId(!0),l=I({},n,r?{navigationURL:s}:{},{$current_url:s,timestamp:Date.now()});C(a)||(l.$session_id=a.sessionId,l.$window_id=a.windowId),this.R.metrics.push(l),this.R.metrics.length===this.allowedMetrics.length&&this.No()}else wn.error("Ignoring metric with value >= "+this.Ho,n)}}},this.Uo=()=>{if(!this.vo){var n,i,r,s,o=B.__PosthogExtensions__,a=o?.postHogWebVitalsCallbacksByFlavor,l=a?.[this.zo]||(this.zo==="web-vitals"&&C(a)?o?.postHogWebVitalsCallbacks:void 0);if(C(l)||(n=l.onLCP,i=l.onCLS,r=l.onFCP,s=l.onINP),n&&i&&r&&s){var u={reportSoftNavs:this.useSoftNavs};this.allowedMetrics.indexOf("LCP")>-1&&n(this.jo.bind(this),u),this.allowedMetrics.indexOf("CLS")>-1&&i(this.jo.bind(this),u),this.allowedMetrics.indexOf("FCP")>-1&&r(this.jo.bind(this),u),this.allowedMetrics.indexOf("INP")>-1&&s(this.jo.bind(this),u),this.vo=!0}else wn.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[aa]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,n=he(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return H(n)?((e=this._instance.persistence)==null?void 0:e.props[la])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(he(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=he(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=he(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=he(this.Wo)&&ke(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:du;return t>0&&6e4>=t?du:t}get isEnabled(){var t=me?.protocol;if(t!=="http:"&&t!=="https:")return wn.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=he(this.Wo)?this.Wo.web_vitals:mt(this.Wo)?this.Wo:void 0;return mt(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(wn.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var n=he(e.capturePerformance)&&!!e.capturePerformance.web_vitals,i=he(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[aa]:n}),this._instance.persistence.register({[la]:i})),this.Co=n,this.startIfEnabled()}}}get zo(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}ai(t){var e=B.__PosthogExtensions__,n=this.zo,i=e?.postHogWebVitalsCallbacksByFlavor;i!=null&&i[n]||n==="web-vitals"&&C(i)&&e!=null&&e.postHogWebVitalsCallbacks?t():e==null||e.loadExternalDependency==null||e.loadExternalDependency(this._instance,n,(r=>{r?wn.error("failed to load script",r):t()}))}Bo(t){var e=t||w?.location.href;if(e){var n=this._instance.config.disable_capture_url_hashes?fn(e):e,i=this._instance.config.custom_personal_data_properties,r=this._instance.config.mask_personal_data_properties?[...si,...i||[]]:[];return Xi(n,r,Qi)}wn.error("Could not determine current URL")}}},Jm={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var n;if(w&&this.isEnabled&&(n=B.__PosthogExtensions__)!=null&&n.errorWrappingFunctions){var i=B.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,r=B.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,s=B.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.Vo&&this.Ne.capture_unhandled_errors&&(this.Vo=i(this.captureException.bind(this))),!this.Zo&&this.Ne.capture_unhandled_rejections&&(this.Zo=r(this.captureException.bind(this))),!this.Go&&this.Ne.capture_console_errors&&(this.Go=s(this.captureException.bind(this)))}catch(o){ki.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[ra]),this.Jo=new Kp(I({},(function(n){var i,r,s,o;return n===void 0&&(n={}),{refillRate:(i=(r=n.exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:n.__exceptionRateLimiterRefillRate)!==null&&i!==void 0?i:1,bucketSize:(s=(o=n.exceptionRateLimiterBucketSize)!==null&&o!==void 0?o:n.__exceptionRateLimiterBucketSize)!==null&&s!==void 0?s:10}})(this._instance.config.error_tracking),{refillInterval:1e4,rt:ki})),this.Ne=this.Yo(),this.startIfEnabledOrStop()}Yo(){var t=this._instance.config.capture_exceptions,e={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return he(t)?e=I({},e,t):(C(t)?this.Ko:t)&&(e=I({},e,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),e}get isEnabled(){return this.Ne.capture_console_errors||this.Ne.capture_unhandled_errors||this.Ne.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(ki.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",(i=>{if(i)return ki.error("failed to load script",i);t()}))}Qo(){var t,e,n;(t=this.Vo)==null||t.call(this),this.Vo=void 0,(e=this.Zo)==null||e.call(this),this.Zo=void 0,(n=this.Go)==null||n.call(this),this.Go=void 0}onRemoteConfig(t){if(t.ok){var e=t.config;"autocaptureExceptions"in e&&(this.Ko=!!e.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[ra]:this.Ko}),this.Ne=this.Yo(),this.startIfEnabledOrStop())}}onConfigChange(){this.Ne=this.Yo()}captureException(t){var e,n,i,r=(e=t==null||(n=t.$exception_list)==null||(n=n[0])==null?void 0:n.type)!==null&&e!==void 0?e:"Exception";this.Jo.consumeRateLimit(r)?ki.info("Skipping exception capture because of client rate limiting.",{exception:r}):(i=this._instance.exceptions)==null||i.sendExceptionEvent(t)}},exceptions:class{constructor(t){var e,n;this.Xo=[],this.tl=new dg([new yg,new Ag,new bg,new wg,new kg,new Ig,new Sg,new Cg],(function(i){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;r>o;o++)s[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` +`),d=l;c.length>d;d++){var f=c[d];if(1024>=f.length){var h=Rc.test(f)?f.replace(Rc,"$1"):f;if(!h.match(/\S*Error: /)){for(var p of s){var g=p(h,i);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var v=Array.from(m);return v.reverse(),v.slice(0,50).map((E=>{return I({},E,{filename:E.filename||(S=v,S[S.length-1]||{}).filename,function:E.function||ii});var S}))})(u)}})("web:javascript",gg,_g)),this._instance=t,this.Xo=(e=(n=this._instance.persistence)==null?void 0:n.get_property(sa))!==null&&e!==void 0?e:[],this.el=Zr(this.il()),this.rl=new Fg(this.el)}onConfigChange(){this.el=Zr(this.il()),this.rl.setConfig(this.el)}onRemoteConfig(t){var e,n,i;if(t.ok){var r=t.config;if("errorTracking"in r){var s=(e=(n=r.errorTracking)==null?void 0:n.suppressionRules)!==null&&e!==void 0?e:[],o=(i=r.errorTracking)==null?void 0:i.captureExtensionExceptions;this.Xo=s,this._instance.persistence&&this._instance.persistence.register({[sa]:this.Xo,[oa]:o})}}}get nl(){var t,e=!!this._instance.get_property(oa),n=this._instance.config.error_tracking.captureExtensionExceptions;return(t=n??e)!==null&&t!==void 0&&t}buildProperties(t,e){return this.tl.buildFromUnknown(t,{syntheticException:e?.syntheticException,mechanism:{handled:e?.handled}})}addExceptionStep(t,e){if(this.el.enabled)try{if(!X(t)||t.trim().length===0)return void St.warn("Ignoring exception step because message must be a non-empty string");var n=(function(s){if(!s)return{sanitizedProperties:{},droppedKeys:[]};var o=[];return{sanitizedProperties:Object.keys(s).reduce(((a,l)=>Pg.has(l)?(o.push(l),a):(a[l]=s[l],a)),{}),droppedKeys:o}})(this.sl(e)),i=n.sanitizedProperties,r=n.droppedKeys;r.length>0&&St.warn("Ignoring reserved exception step fields",{droppedKeys:r}),this.rl.add(I({[Yr]:t,[Jr]:new Date().toISOString()},i))}catch(s){St.error("Failed to add exception step. Ignoring breadcrumb.",s)}}sendExceptionEvent(t){try{var e=t.$exception_list;if(this.al(e)){if(this.ol(e))return this.ll("Exception dropped: matched a suppression rule"),void St.info("Skipping exception capture because a suppression rule matched");if(!this.nl&&this.ul(e))return this.ll("Exception dropped: thrown by a browser extension"),void St.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.hl(e))return this.ll("Exception dropped: thrown by the PostHog SDK"),void St.info("Skipping exception capture because it was thrown by the PostHog SDK")}var n=this.el.enabled&&H(t.$exception_steps)?this.dl(t):t,i=typeof(s=globalThis._posthogReleaseId)=="string"&&s.length>0?s:void 0;i&&(n.$release_id=i);try{var r=this._instance.capture("$exception",n,{_noTruncate:!0,_batchKey:"exceptionEvent",Wn:!0});return r&&this.rl.clear(),r}catch(o){return St.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void St.error("Failed to process exception event. Ignoring this exception.",o)}var s}dl(t){try{var e=this.rl.getAttachable();return e.length===0?t:I({},t,{$exception_steps:e})}catch(n){return St.error("Failed to read buffered exception steps. Capturing exception without steps.",n),t}}ll(t){this.el.enabled&&this.rl.add({[Yr]:t,[Jr]:new Date().toISOString()})}sl(t){return he(t)?I({},t):{}}il(){var t,e;return(t=(e=this._instance.config.error_tracking)==null?void 0:e.exception_steps)!==null&&t!==void 0?t:{}}ol(t){if(t.length===0)return!1;try{var e=t.reduce(((n,i)=>{var r=i.type,s=i.value;return X(r)&&r.length>0&&n.$exception_types.push(r),X(s)&&s.length>0&&n.$exception_values.push(s),n}),{$exception_types:[],$exception_values:[]});return this.Xo.some((n=>{var i=n.values.map((r=>{var s=Vf[r.operator],o=e[r.key];if(!s||!o)return!1;var a=U(r.value)?r.value:[r.value];return a.length>0&&s(a,o)}));return n.type==="OR"?i.some(Boolean):i.every(Boolean)}))}catch(n){return St.warn("Failed to evaluate suppression rules. Capturing the exception.",n),!1}}ul(t){return t.flatMap((e=>{var n,i;return(n=(i=e.stacktrace)==null?void 0:i.frames)!==null&&n!==void 0?n:[]})).some((e=>e.filename&&e.filename.startsWith("chrome-extension://")))}hl(t){if(t.length>0){var e,n,i,r,s=(e=(n=t[0].stacktrace)==null?void 0:n.frames)!==null&&e!==void 0?e:[],o=s[s.length-1];return(i=o==null||(r=o.filename)==null?void 0:r.includes("posthog.com/static"))!==null&&i!==void 0&&i}return!1}al(t){return!H(t)&&U(t)}}},Zm=I({productTours:class{get Mr(){return this._instance.persistence}constructor(t){this.vl=null,this.cl=null,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(t.ok){var e=t.config;if("productTours"in e){var n,i;if(this.Mr&&this.Mr.register({[ll]:!!e.productTours}),!Do(this._instance))return!this.vl&&H((n=this.Mr)==null?void 0:n.props[Li])||Ir.info("product tours disabled; stopping and clearing cached tours"),(i=this.vl)==null||i.stop(),this.vl=null,void this.clearCache();this.loadIfEnabled()}}}loadIfEnabled(){!this.vl&&Do(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.generateProductTours?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",(i=>{i?Ir.error("Could not load product tours script",i):t()}))}fl(){var t;!this.vl&&(t=B.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=B.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(t,e){if(e===void 0&&(e=!1),!U(this.cl)||e){var n=this.Mr;if(n){var i=n.props[Li];if(U(i)&&!e)return this.cl=i,void t(i,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",timestampMode:"query",callback:r=>{if(Do(this._instance)){var s=r.statusCode;if(s!==200||!r.json){var o="Product Tours API could not be loaded, status: "+s;return s===0?r.error||Ir.warn(o):Ir.error(o),void t([],{isLoaded:!1,error:o})}var a=U(r.json.product_tours)?r.json.product_tours:[];this.cl=a,n&&n.register({[Li]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){H(this.vl)?t([],{isLoaded:!1,error:"Product tours not loaded"}):this.vl.getActiveProductTours(t)}showProductTour(t){var e;(e=this.vl)==null||e.showTourById(t)}previewTour(t){this.vl?this.vl.previewTour(t):this.ai((()=>{var e;this.fl(),(e=this.vl)==null||e.previewTour(t)}))}dismissProductTour(){var t;(t=this.vl)==null||t.dismissTour("user_clicked_skip")}nextStep(){var t;(t=this.vl)==null||t.nextStep()}previousStep(){var t;(t=this.vl)==null||t.previousStep()}clearCache(){var t;this.cl=null,(t=this.Mr)==null||t.unregister(Li)}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)}}},As),Xm={siteApps:class{constructor(t){this.pl=0,this._instance=t,this.gl=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}ml(t,e){if(e){var n=this.globalsForEvent(e);this.gl.push(n),this.gl.length>1e3&&(this.gl=this.gl.slice(10))}}get siteAppLoaders(){var t;return(t=B._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,n,i,r,s,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var f=d[0];l[f]={id:u[f],type:f,properties:d[1]}}var h=t.$set_once,p=t.$set;return{event:I({},md(t,Um),{properties:I({},t.properties,p?{$set:I({},(e=(n=t.properties)==null?void 0:n.$set)!==null&&e!==void 0?e:{},p)}:{},h?{$set_once:I({},(i=(r=t.properties)==null?void 0:r.$set_once)!==null&&i!==void 0?i:{},h)}:{}),elements_chain:(s=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&s!==void 0?s:"",distinct_id:(a=t.properties)==null?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}bl(t){var e,n=(e=t.tagName)==null?void 0:e.toLowerCase();return n==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(Et.error("prepare_external_dependency_stylesheet returned null"),null):n==="script"&&this._instance.config.prepare_external_dependency_script?this._instance.config.prepare_external_dependency_script(t)||(Et.error("prepare_external_dependency_script returned null"),null):t}_l(){var t,e,n,i,r,s,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=P?.defaultView,u=l==null||(t=l.Node)==null?void 0:t.prototype;if(!l||!u)return()=>{};if(this.pl++,this.wl)return this.kl();var c=[],d=this,f=new WeakSet,h=(m,v,E)=>{if(m!=null&&m[v]){var S=m[v];m[v]=E(S),c.push((()=>{m[v]=S}))}},p=m=>{if(f.has(m))return m;var v=d.bl(m);return v&&f.add(v),v},g=m=>m.map((v=>typeof v=="string"?v:p(v))).filter((v=>!Ye(v)));return h(u,"appendChild",(m=>function(v){var E=p(v);return E?m.call(this,E):v})),h(u,"insertBefore",(m=>function(v,E){var S=p(v);return S?m.call(this,S,E):v})),h(u,"replaceChild",(m=>function(v,E){var S=p(v);return S?m.call(this,S,E):E})),[(e=l.Element)==null?void 0:e.prototype,(n=l.Document)==null?void 0:n.prototype,(i=l.DocumentFragment)==null?void 0:i.prototype].forEach((m=>{h(m,"append",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),h(m,"prepend",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))}))})),[(r=l.Element)==null?void 0:r.prototype,(s=l.CharacterData)==null?void 0:s.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((m=>{h(m,"before",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),h(m,"after",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),h(m,"replaceWith",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];var b=g(S);return S.length&&!b.length?void 0:v.apply(this,b)}))})),h((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(v,E){var S=p(E);return S?m.call(this,v,S):null})),this.wl=()=>{c.forEach((m=>m())),this.wl=void 0},this.kl()}kl(){var t=!1;return()=>{var e;t||(t=!0,this.pl--,this.pl===0&&((e=this.wl)==null||e.call(this)))}}xl(t,e){e===void 0&&(e=!0);var n=this._l();try{var i=t(n);return e&&n(),i}catch(r){throw n(),r}}setupSiteApp(t){var e=this.apps[t.id],n=()=>{var o;!e.errored&&this.gl.length&&(Et.info("Processing "+this.gl.length+" events for site app with id "+t.id),this.gl.forEach((a=>this.xl((()=>e.processEvent==null?void 0:e.processEvent(a))))),e.processedBuffer=!0),Object.values(this.apps).every((a=>a.processedBuffer||a.errored))&&((o=this.yl)==null||o.call(this))},i=!1,r=o=>{e.errored=!o,e.loaded=!0,Et.info("Site app with id "+t.id+" "+(o?"loaded":"errored")),i&&n()};try{var s=this.xl((o=>t.init({posthog:this._instance,callback(a){o(),r(a)}})),!1).processEvent;s&&(e.processEvent=s),i=!0}catch(o){Et.error(pu+t.id,o),r(!1)}if(i&&e.loaded)try{n()}catch(o){Et.error("Error while processing buffered events PostHog app with config id "+t.id,o),e.errored=!0}}Sl(){var t=this.siteAppLoaders||[];for(var e of t)this.apps[e.id]={id:e.id,loaded:!1,errored:!1,processedBuffer:!1};for(var n of t)this.setupSiteApp(n)}Cl(t){var e=this;if(Object.keys(this.apps).length!==0){var n=this.globalsForEvent(t),i=function(s){try{e.xl((()=>s.processEvent==null?void 0:s.processEvent(n)))}catch(o){Et.error("Error while processing event "+t.event+" for site app "+s.id,o)}};for(var r of Object.values(this.apps))i(r)}}onRemoteConfig(t){var e,n,i,r=this;if((e=this.siteAppLoaders)!=null&&e.length)return this.isEnabled?(this.Sl(),void this._instance.on("eventCaptured",(l=>this.Cl(l)))):void Et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((n=this.yl)==null||n.call(this),t.ok){var s=t.config;if((i=s.siteApps)!=null&&i.length)if(this.isEnabled){var o=function(){var l,u=a.id,c=a.url;B["__$$ph_site_app_"+u]=r._instance,(l=B.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(r._instance,c,(d=>{if(d)return Et.error(pu+u,d)}))};for(var a of s.siteApps)o()}else Et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},Qm={tracingHeaders:class{constructor(t){this.Ml=void 0,this.Tl=void 0,this.El=void 0,this.Uo=()=>{var e,n,i=this.Il();i?(C(this.Ml)&&(this.Ml=(e=B.__PosthogExtensions__)==null||(e=e.tracingHeadersPatchFns)==null?void 0:e._patchXHR(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager)),C(this.Tl)&&(this.Tl=(n=B.__PosthogExtensions__)==null||(n=n.tracingHeadersPatchFns)==null?void 0:n._patchFetch(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager))):this.Qo()},this._instance=t}initialize(){this.startIfEnabledOrStop()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",(i=>{if(i)return Dm.error("failed to load script",i);t()}))}Pl(){var t,e;return(t=(e=this._instance.config.tracing_headers)!==null&&e!==void 0?e:this._instance.config.addTracingHeaders)!==null&&t!==void 0?t:this._instance.config.__add_tracing_headers}Il(){var t=this.Pl();return U(t)?(U(this.El)?this.El.splice(0,this.El.length,...t):this.El=[...t],t.length>0?this.El:void 0):(U(this.El)&&this.El.splice(0),this.El=t||void 0,this.El)}Qo(){var t,e;(t=this.Ml)==null||t.call(this),(e=this.Tl)==null||e.call(this),this.Ml=void 0,this.Tl=void 0}startIfEnabledOrStop(){this.Il()?this.ai(this.Uo):this.Qo()}}},ev=I({surveys:class{get Ne(){return this._instance.config}constructor(t){this.Rl=void 0,this._surveyManager=null,this.Al=!1,this.Fl=[],this.Ll=null,this.Ol=null,this._instance=t,this._surveyEventReceiver=null}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this.Ne.disable_surveys){if(!t.ok)return Q.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(H(e))return Q.warn("Flags not loaded yet. Not loading surveys.");var n=U(e);this.Rl=n?e.length>0:e,Q.info("flags response received, isSurveysEnabled: "+this.Rl),this.loadIfEnabled()}}reset(){try{var t;(t=this._surveyEventReceiver)==null||t.reset(),localStorage.removeItem("lastSeenSurveyDate");for(var e=[],n=0;nlocalStorage.removeItem(r)))}catch{}}loadIfEnabled(){if(!this._surveyManager)if(this.Al)Q.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)Q.info(gu);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())Q.info("Not loading surveys in cookieless mode without consent.");else{var t=B?.__PosthogExtensions__;if(t){if(!C(this.Rl)||this.Ne.advanced_enable_surveys){var e=this.Rl||this.Ne.advanced_enable_surveys;this.Al=!0;try{var n=t.generateSurveys;if(n)return void this.Dl(n,e);var i=t.loadExternalDependency;if(!i)return void this.$l(ul);i(this._instance,"surveys",(r=>{r||!t.generateSurveys?this.$l("Could not load surveys script",r):this.Dl(t.generateSurveys,e)}))}catch(r){throw this.$l("Error initializing surveys",r),r}finally{this.Al=!1}}}else Q.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new zm(this._instance),Q.info("Surveys loaded successfully"),this.Nl({isLoaded:!0})}$l(t,e){Q.error(t,e),this.Nl({isLoaded:!1,error:t})}onSurveysLoaded(t){return this.Fl.push(t),this._surveyManager&&this.Nl({isLoaded:!0}),()=>{this.Fl=this.Fl.filter((e=>e!==t))}}getSurveys(t,e){if(e===void 0&&(e=!1),this.Ne.disable_surveys)return Q.info(gu),t([]);var n,i=this._instance.get_property(ua);if(i&&!e)return t(i,{isLoaded:!0}),void(this.ql()&&this.getSurveys((()=>{}),!0));typeof Promise<"u"&&this.Ll?this.Ll.then((r=>t(r.surveys,r.context))):(typeof Promise<"u"&&(this.Ll=new Promise((r=>{n=r}))),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this.Ne.token),method:"GET",timestampMode:"query",timeout:this.Ne.surveys_request_timeout_ms,callback:r=>{var s;this.Ll=null;var o=r.statusCode;if(o!==200||!r.json){var a="Surveys API could not be loaded, status: "+o;o!==0?Q.error(a):r.error||Q.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(n==null||n({surveys:[],context:l}))}this.Ol=null;var u,c=r.json.surveys||[],d=c.filter((h=>(function(p){return!(!p.start_date||p.end_date)})(h)&&(Kf(h)||(function(p){var g;return!((g=p.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(h))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(s=this._instance.persistence)==null||s.register({[ua]:c,[Qr]:Date.now()});var f={isLoaded:!0};t(c,f),n?.({surveys:c,context:f})}}))}ql(){return this.jl()&&!this.Ll&&!this.Bl()}jl(){var t=this._instance.get_property(Qr);return ke(t)&&Date.now()-t>3e5}Bl(){return ke(this.Ol)&&3e5>Date.now()-this.Ol}markSurveyAsSeen(t,e){var n,i={id:t,current_iteration:(n=e?.iteration)!==null&&n!==void 0?n:null};Jf(i);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}}Nl(t){for(var e of this.Fl)try{if(!t.isLoaded)return e([],t);this.getSurveys(e)}catch(n){Q.error("Error in survey callback",n)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!H(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);Q.warn("init was not called")}Hl(t){var e=null;return this.getSurveys((n=>{var i;e=(i=n.find((r=>r.id===t)))!==null&&i!==void 0?i:null})),e}Ul(t){if(H(this._surveyManager))return{eligible:!1,reason:kr};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyEligibility(e):{eligible:!1,reason:"Survey not found"}}zl(t){if(H(this._surveyManager))return{eligible:!1,reason:kr};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyRenderability(e):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(t){if(H(this._surveyManager))return Q.warn("init was not called"),{visible:!1,disabledReason:kr};var e=this.zl(t);return{visible:e.eligible,disabledReason:e.reason}}canRenderSurveyAsync(t,e){return H(this._surveyManager)?(Q.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:kr})):new Promise((n=>{this.getSurveys((i=>{var r,s=(r=i.find((a=>a.id===t)))!==null&&r!==void 0?r:null;if(s){var o=this.zl(s);n({visible:o.eligible,disabledReason:o.reason})}else n({visible:!1,disabledReason:"Survey not found"})}),e)}))}renderSurvey(t,e,n){var i;if(H(this._surveyManager))Q.warn("init was not called");else{var r=typeof t=="string"?this.Hl(t):t;if(r!=null&&r.id)if(km.includes(r.type)){var s=P?.querySelector(e);if(s)return(i=r.appearance)!=null&&i.surveyPopupDelaySeconds?(Q.info("Rendering survey "+r.id+" with delay of "+r.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;Q.info("Rendering survey "+r.id+" with delay of "+((o=r.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(a=this._surveyManager)==null||a.renderSurvey(r,s,n),Q.info("Survey "+r.id+" rendered")}),1e3*r.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(r,s,n);Q.warn("Survey element not found")}else Q.warn("Surveys of type "+r.type+" cannot be rendered in the app");else Q.warn("Survey not found")}}displaySurvey(t,e){var n;if(H(this._surveyManager))Q.warn("init was not called");else{var i=this.Hl(t);if(i){var r=i;if((n=i.appearance)!=null&&n.surveyPopupDelaySeconds&&e.ignoreDelay&&(r=I({},i,{appearance:I({},i.appearance,{surveyPopupDelaySeconds:0})})),e.displayType!==wa.Popover&&e.initialResponses&&Q.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),e.ignoreConditions===!1){var s=this.Ul(i);if(!s.eligible)return void Q.warn("Survey is not eligible to be displayed: ",s.reason)}e.displayType!==wa.Inline?this._surveyManager.handlePopoverSurvey(r,e):this.renderSurvey(r,e.selector,e.properties)}else Q.warn("Survey not found")}}cancelPendingSurvey(t){H(this._surveyManager)?Q.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},As),tv={toolbar:class{constructor(t){this.instance=t}Wl(t){B.ph_toolbar_state=t}Vl(){var t;return(t=B.ph_toolbar_state)!==null&&t!==void 0?t:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(t,e,n){if(t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),va(this.instance.config)||!w||!P)return!1;t=t??w.location,n=n??w.history;try{if(!e){try{w.localStorage.setItem("test","test"),w.localStorage.removeItem("test")}catch{return!1}e=w?.localStorage}var i,r=qm||as(t.hash,"__posthog")||as(t.hash,"state"),s=r?$c((()=>JSON.parse(atob(decodeURIComponent(r)))))||$c((()=>JSON.parse(decodeURIComponent(r)))):null;return s&&s.action==="ph_authorize"?((i=s).source="url",i&&Object.keys(i).length>0&&(s.desiredHash?t.hash=s.desiredHash:n?n.replaceState(n.state,"",t.pathname+t.search):t.hash="")):((i=JSON.parse(e.getItem(mu)||"{}")).source="localstorage",delete i.userIntent),!(!i.token||this.instance.config.token!==i.token||(this.loadToolbar(i),0))}catch{return!1}}Zl(t){var e=B.ph_load_toolbar||B.ph_load_editor;!H(e)&&je(e)?e(t,this.instance):vu.warn("No toolbar load function found")}loadToolbar(t){var e=!(P==null||!P.getElementById(df));if(!w||e)return!1;var n=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,i=I({token:this.instance.config.token},t,{apiURL:this.instance.requestRouter.endpointFor("ui")},n?{instrument:!1}:{});if(w.localStorage.setItem(mu,JSON.stringify(I({},i,{source:void 0}))),this.Vl()===2)this.Zl(i);else if(this.Vl()===0){var r;this.Wl(1),(r=B.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"toolbar",(s=>{if(s)return vu.error("[Toolbar] Failed to load",s),void this.Wl(0);this.Wl(2),this.Zl(i)})),ve(w,"turbolinks:load",(()=>{this.Wl(0),this.loadToolbar(i)}))}return!0}Gl(t){return this.loadToolbar(t)}maybeLoadEditor(t,e,n){return t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),this.maybeLoadToolbar(t,e,n)}}},nv=I({experiments:Me},As),iv={conversations:class{constructor(t){this.Ql=void 0,this._conversationsManager=null,this.Kl=!1,this.Jl=null,this.Yl=!1,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this._instance.config.disable_conversations&&(this.Xl=t.ok,t.ok)){var e=t.config.conversations;H(e)||(mt(e)?this.Ql=e:(this.Ql=e.enabled,this.Jl=e),this.loadIfEnabled())}}reset(){var t;(t=this._conversationsManager)==null||t.reset(),this._conversationsManager=null,this.Ql=void 0,this.Jl=null,this.Xl=void 0,this.Yl=!1}loadIfEnabled(){if(!(this._conversationsManager||this.Kl||this._instance.config.disable_conversations||va(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=B?.__PosthogExtensions__;if(t&&!C(this.Ql)&&this.Ql)if(this.Jl&&this.Jl.token){this.Kl=!0;try{var e=t.initConversations;if(e)return this.tu(e),void(this.Kl=!1);var n=t.loadExternalDependency;if(!n)return void this.eu(ul);n(this._instance,"conversations",(i=>{i||!t.initConversations?this.eu("Could not load conversations script",i):this.tu(t.initConversations),this.Kl=!1}))}catch(i){this.eu("Error initializing conversations",i),this.Kl=!1}}else ot.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,ot.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else ot.error("Cannot complete initialization: remote config is null")}eu(t,e){ot.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():ot.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!Ye(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":va(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.Xl===!1?"remote_config_failed":C(this.Ql)?this.Xl?"disabled_in_project":"remote_config_pending":this.Ql?H(this.Jl)||!this.Jl.token?"missing_token":B!=null&&B.__PosthogExtensions__?this.Kl?"initializing":this.Yl?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.isVisible())!==null&&t!==void 0&&t}sendMessage(t,e,n){var i=this;return se((function*(){return i._conversationsManager?i._conversationsManager.sendMessage(t,e,n):(ot.warn(En),null)}))()}getMessages(t,e){var n=this;return se((function*(){return n._conversationsManager?n._conversationsManager.getMessages(t,e):(ot.warn(En),null)}))()}markAsRead(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(ot.warn(En),null)}))()}getTickets(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(ot.warn(En),null)}))()}requestRestoreLink(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(ot.warn(En),null)}))()}restoreFromToken(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(ot.warn(En),null)}))()}restoreFromUrlToken(){var t=this;return se((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(ot.warn(En),null)}))()}getCurrentTicketId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getCurrentTicketId())!==null&&t!==void 0?t:null}getWidgetSessionId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getWidgetSessionId())!==null&&t!==void 0?t:null}Xn(){var t;(t=this._conversationsManager)==null||t.setIdentity()}ts(){var t;(t=this._conversationsManager)==null||t.clearIdentity()}}},rv={logs:class{constructor(t){var e,n=this;this.iu=!1,this.ru=!1,this.rt=pe("[logs]"),this.nu=I({},this.rt,{error(){for(var i=arguments.length,r=new Array(i),s=0;i>s;s++)r[s]=arguments[s];r.some(Iu)||n.rt.error(...r)}}),this.tr=[],this.su=[],this.Sa=0,this.au=()=>{var i,r;this.Sa=0,(i=this.ou)==null||i.onReconnect(),(r=this.lu)==null||r.onReconnect()},this._instance=t,this._instance&&(e=this._instance.config.logs)!=null&&e.captureConsoleLogs&&(this.iu=!0),w&&ve(w,"online",this.au)}uu(t,e,n,i){var r,s=(function(o,a){var l,u,c,d,f,h,p,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,v=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,E=C(v)?Math.max(m,2048):Math.max(m,v),S=o?.resourceAttributes;return{serviceName:(d=(f=S?.["service.name"])!==null&&f!==void 0?f:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(h=S?.["service.version"])!==null&&h!==void 0?h:o?.serviceVersion,environment:(p=S?.["deployment.environment"])!==null&&p!==void 0?p:o?.environment,resourceAttributes:S,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:E,maxBatchRecordsPerPost:100,rateCapWindowMs:g,maxLogsPerInterval:v,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}})((r=this._instance)==null||(r=r.config)==null?void 0:r.logs,n);return[new lg(this.hu(t,e),s,this.nu,(()=>this.du()),(o=>o()),void 0,i),s]}vu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.ou||this.cu!==e){var n;(n=this.ou)==null||n.reset(),this.cu=e;var i=this.uu((()=>this.tr),(r=>{this.tr=r}));this.ou=i[0],this.fu=i[1]}return this.ou}pu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.lu||this.gu!==e){var n;(n=this.lu)==null||n.reset(),this.gu=e;var i=this.uu((()=>this.su),(r=>{this.su=r}),{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},xu);this.lu=i[0],this.mu=i[1]}return this.lu}initialize(){this.loadIfEnabled()}onRemoteConfig(t){var e;if(t.ok){var n=(e=t.config.logs)==null?void 0:e.captureConsoleLogs;!H(n)&&n&&(this.iu=!0,this.loadIfEnabled())}}reset(){var t,e;this.tr=[],(t=this.ou)==null||t.reset(),this.su=[],(e=this.lu)==null||e.reset(),this.Sa=0}captureLog(t){this.vu().captureLog(t)}he(t){this.pu().captureLog(t)}get logger(){return this.yu||(this.yu={trace:(t,e)=>this.captureLog({body:t,level:"trace",attributes:e}),debug:(t,e)=>this.captureLog({body:t,level:"debug",attributes:e}),info:(t,e)=>this.captureLog({body:t,level:"info",attributes:e}),warn:(t,e)=>this.captureLog({body:t,level:"warn",attributes:e}),error:(t,e)=>this.captureLog({body:t,level:"error",attributes:e}),fatal:(t,e)=>this.captureLog({body:t,level:"fatal",attributes:e})}),this.yu}flushLogs(t){t?this.bu(t):(this.ou&&this.ou.flush().catch((e=>this._u(e))),this.lu&&this.lu.flush().catch((e=>this._u(e))))}_u(t){Iu(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=B?.__PosthogExtensions__;if(t){var e=t.loadExternalDependency;e?e(this._instance,"logs",(n=>{var i;n||(i=t.logs)==null||!i.initializeLogs?this.rt.error("Could not load logs script",n):(t.logs.initializeLogs(this._instance),this.ru=!0)})):this.rt.error(ul)}else this.rt.error("PostHog Extensions not found.")}}hu(t,e){var n=this._instance;return{get isDisabled(){return!1},get optedOut(){return!n.is_capturing()},getPersistedProperty:i=>i===Ut.LogsQueue?t():void 0,setPersistedProperty(i,r){var s;i===Ut.LogsQueue&&e((s=r)!==null&&s!==void 0?s:[])},Ot:i=>this.Ot(i),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Ot(t){return new Promise((e=>{if(Sf(this.Sa,3))e({kind:"fatal",error:Uo(void 0,"logs endpoint is unreachable, dropping batch")});else{var n=!1,i=s=>{n||(n=!0,clearTimeout(r),e(s))},r=setTimeout((()=>{this.rt.warn("Logs request timed out before receiving a response"),i({kind:"retry-later",error:Uo(void 0,"logs request timed out")})}),9e4);this._instance._send_request({method:"POST",url:this.wu(),data:t,compression:"best-available",batchKey:"logs",fireCallbackOnDrop:!0,callback:s=>{var o=s.statusCode;if(this.ku(o),o>=200&&300>o)i({kind:"ok"});else if(o===413)i({kind:"too-large"});else if(o!==0&&o!==429&&500>o)i({kind:"fatal",error:new Error("logs request failed with status "+o)});else{var a;o===0?(s.error||this.rt.warn("Logs request failed before receiving an HTTP response"),i({kind:"retry-later",error:Uo(s.error,"logs request failed before receiving an HTTP response")})):i({kind:"retry-later",error:(a=s.error)!==null&&a!==void 0?a:new Error("logs request failed with status "+o)})}}})}}))}ku(t){(t!==0||this._instance.__loaded)&&(this.Sa=xf(t,this.Sa,3,(()=>this.rt.warn("Log requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped sending logs; will try again when connectivity changes."))))}bu(t){this.tr.length>0&&this.xu(t,this.tr,this.fu,ne.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,xu,(e=>{this.su=e}))}xu(t,e,n,i,r){if(e.length!==0){var s=e.map((a=>a.record));r([]);var o=Gd(s,Vd(n,ne.LIB_NAME,ne.LIB_VERSION),i,ne.LIB_VERSION);this._instance._send_request({method:"POST",url:this.wu(),data:o,compression:"best-available",batchKey:"logs",transport:t})}}wu(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}du(){var t,e={};if(e.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var n=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.windowId,r=n.sessionStartTimestamp,s=n.lastActivityTimestamp;e.sessionId=n.sessionId,e.windowId=i,H(r)||(e.sessionStartTimestamp=r),H(s)||(e.lastActivityTimestamp=s)}if(B!=null&&(t=B.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?fn(B.location.href):B.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},sv={metrics:class{constructor(t){this.rt=pe("[metrics]"),this._instance=t}initialize(){}vu(){var t,e,n=(t=this._instance)==null||(t=t.config)==null?void 0:t.metrics;return this.ou&&this.cu===n||((e=this.ou)==null||e.reset(),this.cu=n,this.ou=new cg(this.hu(),(function(i){var r,s,o,a,l,u=i?.resourceAttributes;return{serviceName:(r=u?.["service.name"])!==null&&r!==void 0?r:i?.serviceName,serviceVersion:(s=u?.["service.version"])!==null&&s!==void 0?s:i?.serviceVersion,environment:(o=u?.["deployment.environment"])!==null&&o!==void 0?o:i?.environment,resourceAttributes:u,beforeSend:i?.beforeSend,flushIntervalMs:(a=i?.flushIntervalMs)!==null&&a!==void 0?a:1e4,maxSeriesPerFlush:(l=i?.maxSeriesPerFlush)!==null&&l!==void 0?l:1e3}})(n),this.rt)),this.ou}count(t,e,n){e===void 0&&(e=1),this.vu().count(t,e,n)}gauge(t,e,n){this.vu().gauge(t,e,n)}histogram(t,e,n){this.vu().histogram(t,e,n)}flush(t){if(!this.ou)return Promise.resolve();if(t){var e=this.ou.drainWindow();return e&&this.Jt(e,t),Promise.resolve()}return this.ou.flush().catch((n=>this.rt.error("PostHog metrics flush failed:",n)))}reset(){var t;(t=this.ou)==null||t.reset()}hu(){var t=this._instance,e=this;return{get isDisabled(){return!1},get optedOut(){return!t.is_capturing()},Jt:n=>e.Jt(n),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Jt(t,e){return new Promise((n=>{var i=!1,r=o=>{i||(i=!0,clearTimeout(s),n(o))},s=setTimeout((()=>r({kind:"retry-later",error:new Error("metrics request timed out")})),9e4);this._instance._send_request(I({method:"POST",url:this.Su(),data:t,compression:"best-available",batchKey:"metrics"},e&&{transport:e},{fireCallbackOnDrop:!0,callback(o){var a=o.statusCode;if(a>=200&&300>a)r({kind:"ok"});else if(a===413)r({kind:"too-large"});else if(a!==0&&a!==429&&500>a)r({kind:"fatal",error:new Error("metrics request failed with status "+a)});else{var l;r({kind:"retry-later",error:(l=o.error)!==null&&l!==void 0?l:new Error("metrics request failed with status "+a)})}}}))}))}Su(){return this._instance.requestRouter.endpointFor("api","/i/v1/metrics")+"?token="+encodeURIComponent(this._instance.config.token)}}},ov=I({},As,Km,Ym,Jm,Zm,Xm,ev,Qm,tv,nv,iv,rv,sv);Ze.__defaultExtensionClasses=I({},ov);(function(){ne.SDK_DIST_CHANNEL="npm";var t=zi[Kn]=new Ze;return(function(){function e(){e.done||(e.done=!0,Xf=!1,ie(zi,(function(n){n._dom_loaded()})))}P!=null&&P.addEventListener?P.readyState==="complete"?e():ve(P,"DOMContentLoaded",e,{capture:!1}):w&&A.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const av=["a[href]","button:not([disabled])","input:not([disabled]):not([type='hidden'])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(",");let pt=null,Aa=null,eh="";const Pa=new Map;function th(t){return[...t.querySelectorAll(av)].filter(e=>!e.hidden&&e.getAttribute("aria-hidden")!=="true"&&e.getClientRects().length>0)}function lv(t){for(const e of document.body.children)e===t||e.tagName==="SCRIPT"||(Pa.set(e,{inert:e.inert,ariaHidden:e.getAttribute("aria-hidden")}),e.inert=!0,e.setAttribute("aria-hidden","true"))}function cv(){for(const[t,e]of Pa)t.inert=e.inert,e.ariaHidden===null?t.removeAttribute("aria-hidden"):t.setAttribute("aria-hidden",e.ariaHidden);Pa.clear()}function nh(t){return t?.dataset.modalDismissible!=="false"&&t?.getAttribute("aria-busy")!=="true"}function We(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n)return!1;pt&&pt!==n&&ze(pt,{restoreFocus:!1,force:!0}),Aa=e.trigger||document.activeElement,pt=n,eh=document.body.style.overflow,lv(n),document.body.style.overflow="hidden",n.classList.add("open"),n.setAttribute("aria-hidden","false");const i=n.querySelector(".modal-content");i&&(i.style.transform="scale(1) translateY(0)");const r=()=>{if(pt!==n)return;((e.initialFocus?n.querySelector(e.initialFocus):n.querySelector("[data-modal-initial-focus]"))||th(n)[0]||n.querySelector(".modal-content")||n).focus({preventScroll:!0})};return requestAnimationFrame(r),setTimeout(r,260),!0}function ze(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n||!e.force&&!nh(n))return!1;n.classList.remove("open"),n.setAttribute("aria-hidden","true"),cv(),document.body.style.overflow=eh,pt=null;const i=Aa;return Aa=null,e.restoreFocus!==!1&&i?.isConnected&&i.focus({preventScroll:!0}),!0}function ku(t,e,n="Operation in progress"){const i=typeof t=="string"?document.getElementById(t):t;i&&(i.dataset.modalDismissible=e?"false":"true",i.setAttribute("aria-busy",String(!!e)),e?i.setAttribute("aria-label",n):i.removeAttribute("aria-label"))}function uv(t){if(!nh(t))return;const e=t.dataset.modalCloseHandler;e&&typeof window[e]=="function"?window[e]():ze(t)}document.addEventListener("keydown",t=>{if(!pt)return;if(t.key==="Escape"){t.preventDefault(),t.stopImmediatePropagation(),uv(pt);return}if(t.key!=="Tab"){t.stopPropagation();return}const e=th(pt);if(!e.length){t.preventDefault(),(pt.querySelector(".modal-content")||pt).focus();return}const n=e[0],i=e[e.length-1];t.shiftKey&&document.activeElement===n?(t.preventDefault(),i.focus()):!t.shiftKey&&document.activeElement===i&&(t.preventDefault(),n.focus())},!0);function dv(){document.querySelectorAll(".modal-overlay").forEach(t=>{t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-hidden",t.classList.contains("open")?"false":"true");const e=t.querySelector(".modal-content");e&&!e.hasAttribute("tabindex")&&(e.tabIndex=-1);const n=t.querySelector("h1, h2, h3");n&&(n.id||(n.id=`${t.id}-title`),t.setAttribute("aria-labelledby",n.id)),t.querySelectorAll(".modal-close").forEach(i=>{i.getAttribute("aria-label")||i.setAttribute("aria-label","Close dialog")})})}const _l=Object.freeze({free:"Free",professional:"Pro",power:"Power"}),fv=Object.freeze({free:2,professional:50,power:2e3}),hv="(contact us)",pv=Object.freeze({free:Object.freeze(["2 generations/month","Gemini model only","Code Review"]),professional:Object.freeze(["50 generations/month","All models","Code Regeneration","Code Review"]),power:Object.freeze(["2000 generations/month","All models","Code Regeneration","Bring your own key (BYOK)","Code Review","All models + early access",`API & MCP access ${hv}`])}),ih="CodeFile",rh="GeneratedCode",gv={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function ln(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Fa(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function mv(t={},e=0){const n=Fa(t.artifactType||t.type||ih),i=Fa(t.artifactName||t.name||t.fileName||`${rh}-${e+1}`);return`${n||"artifact"}-${i||e+1}`}function sh(t={},e=0){const n=ln(t),i=n.artifactType||n.type||ih,r=n.artifactName||n.name||rh;let s=n.fileName||r;return s.endsWith(".dart")||(s+=".dart"),{id:Fa(n.id)||mv({...n,artifactType:i,artifactName:r,fileName:s},e),artifactType:i,artifactName:r,fileName:s,deployPath:n.deployPath||"",description:n.description||"",code:n.code||n.content||"",dependencies:oh(n.dependencies),imports:Array.isArray(n.imports)?n.imports:[],publicApi:Array.isArray(n.publicApi)?n.publicApi:[],relationships:ah(n.relationships),deployStatus:n.deployStatus||"pending",review:n.review||null,metadata:ln(n.metadata),codeType:n.codeType||gv[i]||"O"}}function oh(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const n=ln(e),i=n.name||n.package;return i?{name:i,version:n.version||null,versionRequired:!!(n.versionRequired||n.required),inferred:!!n.inferred,...n.reason?{reason:n.reason}:{}}:null}).filter(Boolean):Object.entries(ln(t)).map(([e,n])=>({name:e,version:n||null,inferred:!1})):[]}function ah(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const n=ln(e);return!n.from&&!n.to?null:{from:n.from||null,to:n.to||null,type:n.type||"uses",description:n.description||""}}).filter(Boolean):[]}function Ra(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;try{return JSON.parse(e)}catch{const n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(!n)return null;try{return JSON.parse(n[1].trim())}catch{return null}}}function er(t,e={}){const n=[],i=typeof t=="string"?Ra(t):t,s=ln(i||{});!i&&typeof t=="string"&&n.push("Structured bundle parse failed; using legacy single-artifact fallback.");const o=Array.isArray(s.artifacts)?s.artifacts:[{artifactType:s.artifactType||e.artifactType,artifactName:s.artifactName||e.artifactName,fileName:s.fileName||e.fileName,description:s.description,code:s.code||e.code||(typeof t=="string"?t:""),dependencies:s.dependencies||e.dependencies,relationships:s.relationships||e.relationships}];o.forEach((d,f)=>{!d?.artifactType&&!d?.type&&n.push(`Artifact ${f+1} has no artifactType; it will deploy as a standalone code file under lib/custom_code/ root.`)});const a=o.map((d,f)=>sh(d,f)),l=new Map(o.map((d,f)=>[ln(d).id,a[f]?.id]).filter(([d,f])=>d&&f)),u=d=>l.get(d)||d,c=ah(s.relationships||e.relationships).map(d=>({...d,from:d.from?u(d.from):d.from,to:d.to?u(d.to):d.to}));return{schemaVersion:s.schemaVersion||e.schemaVersion||null,id:s.id||e.id||"bundle-current",title:s.title||s.name||e.title||"Generated artifact bundle",description:s.description||e.description||"",artifacts:a,dependencies:oh(s.dependencies||e.dependencies),relationships:c,deployOrder:Array.isArray(s.deployOrder)?s.deployOrder.map(u):a.map(d=>d.id),warnings:[...n,...Array.isArray(s.warnings)?s.warnings:[]],metadata:ln(s.metadata)}}function ai(t){return er(t).artifacts[0]||sh()}function Zt(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function li(t){return JSON.stringify(t,null,2)}function vv(t){return li({task:"architect",userRequest:String(t??"")})}function _v(t){const e=Zt(t);return e&&typeof e=="object"&&typeof e.task=="string"?li(e):li({task:"generate_bundle",bundleSpec:e})}function yv(t){return li({task:"review_bundle",generatedBundle:Zt(t),outputRequirements:{bundleReview:["status","score","summary","manualActions","findings"],scoreRange:[0,100],eachArtifact:["id","review.status","review.findings"],manualActions:{definition:"Setup the developer must perform by hand in the FlutterFlow editor that FlutterFlow will NOT do for them.",exclude:["creating the Custom Action, Widget or Code File itself - deploying the code creates it","declaring parameters or return values FlutterFlow derives from the function signature","anything that resolves as a side effect of using the action or widget in the editor","generic advice such as testing, reviewing or rebuilding the app"],preferEmpty:"Return an empty array when nothing qualifies - an empty list is the expected result for most bundles."}}})}function yl(t,e=null){const n={stage:t};return e!=null&&(n.bundle=Zt(e)),n}function wv({bundleSpec:t,artifactBundle:e,bundleReview:n,artifactId:i,userFeedback:r}){return li({task:"regenerate_artifact",artifactId:i,bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(r)})}function lh({bundleSpec:t,artifactBundle:e,bundleReview:n,userFeedback:i}){return li({task:"regenerate_bundle",bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(i??"")})}const Cu={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"},bv=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function tt(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Ev(t){return tt(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||tt(t.filterSummary)||tt(t.filterResults):!1}function ch(t,e=0){if(!tt(t)||e>3)return null;if(Ev(t))return t;for(const n of bv){const i=t[n];if(tt(i)){const r=ch(i,e+1);if(r)return r}}return null}function fs(t){return Array.isArray(t)?t.some(fs):tt(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(fs):!1}function Ta(t){return Array.isArray(t)?t.some(Ta):tt(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(Ta):!1}function uh(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function Sv(t,e){if(tt(t))for(const[n,i]of Object.entries(t)){if(!tt(i))continue;const r=tt(i.categories)?i.categories:{},s=Object.entries(r).filter(([,o])=>tt(o)&&o.matched===!0).map(([o])=>o);s.length>0?s.forEach(o=>e.add(o)):i.matched===!0&&e.add(uh(n))}}function xv(t,e){if(!t)return;const n=Array.isArray(t)?t.flatMap(i=>tt(i)?Object.entries(i):[]):Object.entries(t);for(const[i,r]of n){if(!fs(r))continue;const s=uh(i),o=r?.raiFilterResult?.raiFilterTypeResults||(s==="rai"?r?.raiFilterTypeResults:null),a=tt(o)?Object.entries(o).filter(([,l])=>fs(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(s)}}function Iv(t){return Cu[t]?Cu[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function Au(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 kv(t){const e=ch(t);if(!e)return null;const n=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);Sv(e.filterSummary,n),xv(e.filterResults,n);const i=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||n.size>0,r=e.invocationResult||null,s=Ta(e.filterSummary||e.filterResults);return!i&&!s&&!["PARTIAL","FAILURE"].includes(r)?null:{kind:i?"blocked":"unavailable",invocationResult:r,matchedFilters:[...n]}}function Cv(t,e){const n=kv(t);if(!n)return null;const i=[...new Set(n.matchedFilters.map(Iv))],r=n.kind==="blocked",s=new Error(r?`Safety screening blocked this pipeline step for ${Au(i)}.`:"Safety screening could not be completed. Please try again.");return s.name="ModelArmorError",s.code=r?"MODEL_ARMOR_BLOCKED":"MODEL_ARMOR_UNAVAILABLE",s.isModelArmor=!0,s.pipelineStep=e,s.userTitle=r?"Request blocked for safety":"Safety check unavailable",s.userMessage=r?`The safety check detected ${Au(i)}. Edit your request to remove or rephrase the flagged content, then run the pipeline again.`:"The safety service did not finish all of its checks. Please wait a moment and run the pipeline again.",s.retryExplanation=r?"Trying another model would not change this safety decision.":"A fallback model was not attempted because safety screening must complete first.",s.matchedFilters=n.matchedFilters,s}function Av(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function Pu(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,n=[];for(const i of Av(t).split(` +`)){if(!/^[A-Za-z_$]/.test(i)||e.test(i))continue;const r=i.match(/^[\w$<>,?\s[\]]+?\s([a-zA-Z_$][\w$]*)\s*\(/);r&&n.push(r[1])}return n}function wl(t,e){const n=t.replace(/\.dart$/,"");if(e==="W")return n.replace(/(^|_)(\w)/g,(i,r,s)=>s.toUpperCase());if(e==="A"){const i=n.replace(/(^|_)(\w)/g,(r,s,o)=>o.toUpperCase());return i.charAt(0).toLowerCase()+i.slice(1)}return e==="F"?"CustomFunctions":e==="C"?t.endsWith(".dart")?t:`${t}.dart`:n}async function Fu(t){const e=new TextEncoder().encode(String(t||"")),n=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n),i=>i.toString(16).padStart(2,"0")).join("")}async function Pv(t,e=new Map){const n={},i=new Set;for(const[o,a]of t.entries()){if(a.type==="D"||a.type==="O")continue;const l=wl(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await Fu(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await Fu(c)),n[o]=u,a.type==="F"){const d=Pu(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(h=>i.add(h))}}const r=new Set(Pu(e.get("lib/flutter_flow/custom_functions.dart")||"")),s={functions_to_rename:[],functions_to_delete:[],functions_to_add:Array.from(i).filter(o=>!r.has(o))};return{fileMapContents:JSON.stringify(n),functionsMapContents:JSON.stringify(s)}}const Fv=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),Ru={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},Rv=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),Tv=["Struct","Record"],$v=[{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=>Ho(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=>Ho(t).some(e=>{const n=/^\s*final\s+(?:double|int|String|bool|Color|num)\s+(\w+)\s*;/gm;let i;for(;(i=n.exec(e))!==null;){const r=i[1];if(!(new RegExp(`this\\.${r}\\s*=(?!=)`).test(e)||new RegExp(`[:,]\\s*${r}\\s*=(?!=)`).test(e)))return!0}return!1}),pos:`class W extends StatefulWidget { const W({required this.value}); final double value; @@ -25,35 +25,35 @@ class _S extends State { @override Widget build(BuildContext c) => const Size @override _S createState() => _S(); } class _S extends State { @override Widget build(BuildContext c) => Padding(padding: const EdgeInsets.all(8), child: const SizedBox()); }`}];function xt(t,e,n){return{artifactId:t.id,artifactName:t.artifactName,artifactType:t.artifactType,severity:e,message:n}}function tr(t){let e="",n=0;for(;n"&&(n--,n===0))return{inner:t.slice(e+1,i),end:i+1};return null}function Lv(t,e){const n=new RegExp(`class\\s+${e}\\b[^{]*\\{`).exec(t);if(!n)return null;let i=0;for(let r=n.index+n[0].length-1;rNv(t).usable);function Bv(t=""){const e=tr(t);return Ov.filter(n=>n.detect(e)).map(({id:n,severity:i,message:r})=>({id:n,severity:i,message:r}))}function Dv(t){const e=[],n=t.matchAll(/\bFuture\b/g);for(const i of n){let r=i.index+6,s=null;const o=r;for(;ro;if(t[r]==="<"){const u=Mv(t,r);if(!u||(s=u.inner.replace(/\s+/g," ").trim(),r=u.end,!/\s/.test(t[r]||"")))continue;for(;rTu(o.functionName)===i);if(r)return r;const s=o=>!o.functionName.startsWith("_");return n.find(s)||n[0]}function Fs(t=""){return Array.from(tr(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function jv(t="",e=""){return bl(t,e)?.returnType||null}function $u(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 Uv(t,e){const n=Fs(e);if(n.length===0)return null;const r=String(t||"").split("/").pop().replace(/\.dart$/,"");if(n.some(l=>$u(l)===r)||n.length>1)return null;const[o]=n,a=`${$u(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 El(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function Hv(t,e,n=""){const i=bl(e,n)?.functionName;if(!i)return null;const r=String(t||"").split("/").pop(),s=wl(r,"A");if(s===i)return null;const o=`${El(i)}.dart`;return`File name "${r}" does not match Action "${i}". FlutterFlow derives the action from the file name, so it looks for "${s}" and reports Action "${s}" declaration not found. Rename the file to "${o}" - FlutterFlow puts an underscore before every capital - or rename the function to "${s}".`}function Wv(t="",e=""){return bl(t,e)!==null}function zv(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(i=>Rv.has(i)?!1:!Tv.some(s=>i.endsWith(s))||e.has(i))}function qv(t,{functionName:e="",declaredTypes:n=new Set}={}){const i=jv(t,e),r=zv(i,n);if(r.length===0)return null;const[s]=r;let o;return n.has(s)?o=`uses Code File type "${s}", which FlutterFlow cannot process as an Action Return Value`:i===s?o="is not a FlutterFlow Action Return Value":o=`uses type "${s}", which is not a FlutterFlow Action Return Value`,`CustomAction return type "${i}" ${o}. Return JSON (Future) or an existing FlutterFlow Data Type (*Struct) instead.`}function Vv(t,e={}){const n=[],i=t.fileName||"",r=t.code||"";if(Fv.has(t.artifactType)||n.push(xt(t,"error",`Unsupported artifact type "${t.artifactType}".`)),i.endsWith(".dart")||n.push(xt(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!r.trim())return n.push(xt(t,"warning","Generated artifact has no Dart code yet.")),n;if(t.artifactType==="CustomWidget"){/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)||n.push(xt(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const s of Bv(r))n.push(xt(t,s.severity,s.message))}if(t.artifactType==="CustomAction"&&!Wv(r,t.artifactName)&&n.push(xt(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const s=e.declaredTypes||new Set(Fs(r)),o=qv(r,{functionName:t.artifactName,declaredTypes:s});o&&n.push(xt(t,"error",o));const a=Hv(i,r,t.artifactName);a&&n.push(xt(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)&&n.push(xt(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const s=Uv(i,r);s&&n.push(xt(t,"info",s))}return n}function Gv(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],n=new Set(e.flatMap(s=>Fs(s.code||""))),i=e.flatMap(s=>Vv(s,{declaredTypes:n})),r=e.map(s=>({artifactId:s.id,fileName:s.fileName,pathHint:Ru[s.artifactType]||Ru.CodeFile}));return{valid:i.every(s=>s.severity!=="error"),findings:i,deployHints:r}}const Mu="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function Lu(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function Kv(t=""){const e=t.indexOf(Mu);return e===-1?t:t.slice(e+Mu.length).replace(/^\s*\n/,"")}const Yv=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function Jv(t="",e=""){const n=Kv(t),i=new Set((e.match(/^\s*import .*$/gm)||[]).map(Lu).filter(Boolean)),r=n.split(` +`;)n++;e+=" "}else if(i==="/*"){for(n+=2;n"&&(n--,n===0))return{inner:t.slice(e+1,i),end:i+1};return null}function Lv(t,e){const n=new RegExp(`class\\s+${e}\\b[^{]*\\{`).exec(t);if(!n)return null;let i=0;for(let r=n.index+n[0].length-1;rNv(t).usable);function Bv(t=""){const e=tr(t);return Ov.filter(n=>n.detect(e)).map(({id:n,severity:i,message:r})=>({id:n,severity:i,message:r}))}function Dv(t){const e=[],n=t.matchAll(/\bFuture\b/g);for(const i of n){let r=i.index+6,s=null;const o=r;for(;ro;if(t[r]==="<"){const u=Mv(t,r);if(!u||(s=u.inner.replace(/\s+/g," ").trim(),r=u.end,!/\s/.test(t[r]||"")))continue;for(;rTu(o.functionName)===i);if(r)return r;const s=o=>!o.functionName.startsWith("_");return n.find(s)||n[0]}function Ps(t=""){return Array.from(tr(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function jv(t="",e=""){return bl(t,e)?.returnType||null}function $u(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 Uv(t,e){const n=Ps(e);if(n.length===0)return null;const r=String(t||"").split("/").pop().replace(/\.dart$/,"");if(n.some(l=>$u(l)===r)||n.length>1)return null;const[o]=n,a=`${$u(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 El(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function Hv(t,e,n=""){const i=bl(e,n)?.functionName;if(!i)return null;const r=String(t||"").split("/").pop(),s=wl(r,"A");if(s===i)return null;const o=`${El(i)}.dart`;return`File name "${r}" does not match Action "${i}". FlutterFlow derives the action from the file name, so it looks for "${s}" and reports Action "${s}" declaration not found. Rename the file to "${o}" - FlutterFlow puts an underscore before every capital - or rename the function to "${s}".`}function Wv(t="",e=""){return bl(t,e)!==null}function zv(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(i=>Rv.has(i)?!1:!Tv.some(s=>i.endsWith(s))||e.has(i))}function qv(t,{functionName:e="",declaredTypes:n=new Set}={}){const i=jv(t,e),r=zv(i,n);if(r.length===0)return null;const[s]=r;let o;return n.has(s)?o=`uses Code File type "${s}", which FlutterFlow cannot process as an Action Return Value`:i===s?o="is not a FlutterFlow Action Return Value":o=`uses type "${s}", which is not a FlutterFlow Action Return Value`,`CustomAction return type "${i}" ${o}. Return JSON (Future) or an existing FlutterFlow Data Type (*Struct) instead.`}function Vv(t,e={}){const n=[],i=t.fileName||"",r=t.code||"";if(Fv.has(t.artifactType)||n.push(xt(t,"error",`Unsupported artifact type "${t.artifactType}".`)),i.endsWith(".dart")||n.push(xt(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!r.trim())return n.push(xt(t,"warning","Generated artifact has no Dart code yet.")),n;if(t.artifactType==="CustomWidget"){/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)||n.push(xt(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const s of Bv(r))n.push(xt(t,s.severity,s.message))}if(t.artifactType==="CustomAction"&&!Wv(r,t.artifactName)&&n.push(xt(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const s=e.declaredTypes||new Set(Ps(r)),o=qv(r,{functionName:t.artifactName,declaredTypes:s});o&&n.push(xt(t,"error",o));const a=Hv(i,r,t.artifactName);a&&n.push(xt(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)&&n.push(xt(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const s=Uv(i,r);s&&n.push(xt(t,"info",s))}return n}function Gv(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],n=new Set(e.flatMap(s=>Ps(s.code||""))),i=e.flatMap(s=>Vv(s,{declaredTypes:n})),r=e.map(s=>({artifactId:s.id,fileName:s.fileName,pathHint:Ru[s.artifactType]||Ru.CodeFile}));return{valid:i.every(s=>s.severity!=="error"),findings:i,deployHints:r}}const Mu="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function Lu(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function Kv(t=""){const e=t.indexOf(Mu);return e===-1?t:t.slice(e+Mu.length).replace(/^\s*\n/,"")}const Yv=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function Jv(t="",e=""){const n=Kv(t),i=new Set((e.match(/^\s*import .*$/gm)||[]).map(Lu).filter(Boolean)),r=n.split(` `).filter(s=>{const o=Lu(s);return o===null||!i.has(o)?!0:!Yv.test(s)}).join(` `).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+r}const Zv=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations"]);function dh(t){let e="",n=0;for(;n{const i=n.name||n.package;if(!i||i==="flutter")return e;const r=n.versionRequired||n.required;return e[i]=r&&n.version||"",e},{})}function n_(t){const e=new Map,n=new Map,i=[];for(const r of t)e.has(r.fileName)?i.push(`Duplicate deploy file name "${r.fileName}" for artifacts "${e.get(r.fileName)}" and "${r.artifactId}".`):e.set(r.fileName,r.artifactId),n.has(r.path)?i.push(`Duplicate deploy path "${r.path}" for artifacts "${n.get(r.path)}" and "${r.artifactId}".`):n.set(r.path,r.artifactId);return i}function i_(t,e={}){const n=Array.isArray(t?.artifacts)?t.artifacts:[],r=(e.selectedArtifactIds||t?.deployOrder||n.map(f=>f.id)).map(f=>n.find(p=>p.id===f)).filter(Boolean),s=[...t?.warnings||[]];let o=[];r.forEach(f=>{const p=t_(f),g=f.fixedCode||f.code||"",m=f.codeType||Qv[f.artifactType]||Xe.OTHER;g.trim()||s.push(`${f.artifactName||f.id} has no generated code.`),o.push({artifactId:f.id,artifactName:f.artifactName,artifactType:f.artifactType,fileName:p,content:g,type:m,path:f.deployPath||e_(p,m),deployPath:f.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((f,p)=>({entry:f,index:p})).filter(({entry:f})=>f.type===Xe.FUNCTION&&f.path===a);if(l.length>1){const f=l[0],p={...f.entry,artifactId:l.map(({entry:m})=>m.artifactId).join("+"),artifactName:f.entry.artifactName,content:l.map(({entry:m})=>`// ${m.artifactId} +`;)n++;e+=" "}else if(i==="/*"){for(n+=2;n{const i=n.name||n.package;if(!i||i==="flutter")return e;const r=n.versionRequired||n.required;return e[i]=r&&n.version||"",e},{})}function n_(t){const e=new Map,n=new Map,i=[];for(const r of t)e.has(r.fileName)?i.push(`Duplicate deploy file name "${r.fileName}" for artifacts "${e.get(r.fileName)}" and "${r.artifactId}".`):e.set(r.fileName,r.artifactId),n.has(r.path)?i.push(`Duplicate deploy path "${r.path}" for artifacts "${n.get(r.path)}" and "${r.artifactId}".`):n.set(r.path,r.artifactId);return i}function i_(t,e={}){const n=Array.isArray(t?.artifacts)?t.artifacts:[],r=(e.selectedArtifactIds||t?.deployOrder||n.map(h=>h.id)).map(h=>n.find(p=>p.id===h)).filter(Boolean),s=[...t?.warnings||[]];let o=[];r.forEach(h=>{const p=t_(h),g=h.fixedCode||h.code||"",m=h.codeType||Qv[h.artifactType]||Xe.OTHER;g.trim()||s.push(`${h.artifactName||h.id} has no generated code.`),o.push({artifactId:h.id,artifactName:h.artifactName,artifactType:h.artifactType,fileName:p,content:g,type:m,path:h.deployPath||e_(p,m),deployPath:h.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((h,p)=>({entry:h,index:p})).filter(({entry:h})=>h.type===Xe.FUNCTION&&h.path===a);if(l.length>1){const h=l[0],p={...h.entry,artifactId:l.map(({entry:m})=>m.artifactId).join("+"),artifactName:h.entry.artifactName,content:l.map(({entry:m})=>`// ${m.artifactId} ${m.content}`).join(` -`)},g=new Set(l.slice(1).map(({index:m})=>m));o=o.filter((m,v)=>!g.has(v)),o[f.index]=p}const u={...Nu(t?.dependencies),...r.reduce((f,p)=>({...f,...Nu(p.dependencies)}),{})},c={};r.forEach(f=>{Sl(f.code||"").forEach(p=>{p in u||(c[p]="")})});const d={...c,...u},h=n_(o);return{bundleId:t?.id||"bundle-current",title:t?.title||"Generated artifact bundle",fileEntries:o,dependencies:d,relationships:t?.relationships||[],warnings:s,errors:h}}function r_(t){return String(t||"").match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/)?.[1]}function s_(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 o_(t,e){const i=[s_(t),r_(e.content),e.artifactName].find(r=>/^[A-Z][A-Za-z0-9_]*$/.test(String(r||"")));if(!i)throw new Error(`Cannot derive a FlutterFlow custom class name for ${t}.`);return i}function a_(t,e=new Map){const n=[];for(const[i,r]of t.entries())r.type!=="C"||e.has(r.path)||n.push({artifactId:r.artifactId||i,className:o_(i,r),content:r.content,fileName:i,path:r.path});return n}function l_(t,e){const n=new Set(e.map(i=>i.path));return new Map(Array.from(t.entries()).filter(([,i])=>!n.has(i.path)))}const Ou={pass:0,warning:1,fail:2},c_=["manualActions"];function st(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Vt(...t){for(const e of t){if(typeof e=="string"&&e.trim())return e.trim();if(Array.isArray(e)&&e.length>0){const n=e.filter(i=>typeof i=="string").join(` -`);if(n)return n}}return""}function kt(t){return t==null?[]:Array.isArray(t)?t:[t]}function u_(t){const e=st(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const n=Number(e);if(Number.isFinite(n))return Bu(n);const i=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return i?Bu(Number(i[1])):null}function Bu(t){return t>=0&&t<=100?t:null}function lt(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function xl(t){const e=String(t||"").toLowerCase();return/(fail|error|critical|block|reject|invalid)/.test(e)?"fail":/(warn|attention|manual|partial|incomplete|concern)/.test(e)?"warning":/(pass|success|ready|approve|valid|clean|info|notice)/.test(e)?"pass":null}function $a(...t){return t.filter(Boolean).reduce((e,n)=>Ou[n]>Ou[e]?n:e,"pass")}function fh(t,e="warning",n="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:n};const i=st(t),r=Vt(i.message,i.title,i.issue,i.description,i.summary);return r?{severity:xl(i.severity||i.status||i.level)||e,message:r,suggestion:Vt(i.suggestion,i.fix,i.recommendation,i.action),source:i.source||n}:null}function Ma(t,e="review"){const n=st(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([r,s])=>kt(n[r]).map(o=>fh(o,s,e)).filter(Boolean))}function d_(t,e,n=null){if(typeof t=="string")return{id:`${n||"bundle"}-manual-${e+1}`,title:t,detail:"",location:"",timing:"unspecified",artifactId:n,source:"Code Review"};const i=st(t),r=Vt(i.title,i.action,i.step,i.message,i.name,i.description);return r?{id:i.id||`${n||"bundle"}-manual-${e+1}`,title:r,detail:Vt(i.detail,i.instructions,i.description),location:Vt(i.location,i.flutterFlowPath,i.path),timing:Vt(i.timing,i.phase)||"unspecified",artifactId:n,source:Vt(i.source)||"Code Review"}:null}function La(t,e=null){const n=st(t);return c_.flatMap(i=>kt(n[i])).map((i,r)=>d_(i,r,e)).filter(Boolean)}function f_(t){let e=typeof t=="string"?Ra(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const n=st(e);typeof n.content=="string"&&(e=Ra(n.content)||e);const i=st(e),r=st(i.reviewResult||i.codeReview||i.result);return{rawText:"",root:Object.keys(r).length?r:i}}function h_(t,e){const n=[e.id,e.fileName,e.artifactName].map(lt);return t.find(i=>{const r=st(i);return[r.id,r.fileName,r.artifactName,r.name].map(lt).some(s=>s&&n.includes(s))})||null}function p_(t,e){return kt(t?.metadata?.compatibility?.deployHints).find(r=>lt(r?.artifactId)===lt(e.id)||lt(r?.fileName)===lt(e.fileName))?.pathHint||""}function g_(t,e){return kt(t?.relationships).filter(n=>lt(n?.from)===lt(e.id)||lt(n?.to)===lt(e.id))}function m_(t,e){return kt(t?.metadata?.compatibility?.findings).filter(n=>!n?.artifactId||lt(n.artifactId)===lt(e.id)).map(n=>fh(n,"warning","Compatibility check")).filter(Boolean)}function v_(t,e,n,i){const r=h_(e,n),s=st(r?.review||r||n.review),o=Object.keys(s).length>0,a=[...Ma(s),...m_(t,n)],l=La(s,n.id),u=xl(s.status||s.verdict||s.outcome||s.result),c=a.length?$a(...a.map(h=>h.severity)):null,d=$a(u,c,o?null:"warning");return{...n,index:i,status:d,statusReason:o?Vt(s.summary,s.overview,s.assessment,s.conclusion)||(a.length?`${a.length} review finding${a.length===1?"":"s"}`:"No file-level findings"):"No file-level verdict was returned",reviewComplete:o,findings:a,manualSteps:l,fixedSource:typeof s.fixedSource=="string"&&s.fixedSource.trim()?s.fixedSource.trim():null,pathHint:p_(t,n),relationships:g_(t,n)}}function __({status:t,score:e,artifactPresentations:n,manualSteps:i}){const r=n.length;if(r===0&&i.length===0)return e==null?"Code review returned no overall summary and no score.":`Reviewed bundle with score ${e}/100.`;const s=n.reduce((a,l)=>(a[l.status]+=1,a),{pass:0,warning:0,fail:0}),o=[];return t&&o.push(`Overall verdict: ${t}.`),r&&o.push(`${r} artifact${r===1?"":"s"}: ${s.pass} pass, ${s.warning} warn, ${s.fail} fail.`),i.length&&o.push(`Do before deploy: ${i.map(a=>a.title).join("; ")}.`),e==null&&o.push("No numeric score (0-100) was returned."),o.join(" ")}function y_({bundle:t,reviewResult:e}){const n=st(t),i=kt(n.artifacts),{root:r,rawText:s}=f_(e),o=[r.bundleReview,r.overallReview,r.overall,r.bundleSummary,r.summaryReview,r.review].map(st).find(S=>Object.keys(S).length)||{},a=kt(r.artifacts||r.files||r.reviews),l=i.map((S,_)=>v_(n,a,S,_)),u=Ma(r),d=[...Ma(o),...u],h=[...La(o),...La(r),...l.flatMap(S=>S.manualSteps)].filter((S,_,b)=>b.findIndex(k=>k.title===S.title&&k.artifactId===S.artifactId)===_),f=xl(o.status||o.verdict||o.overallStatus||r.status||r.verdict||r.overallStatus||r.outcome),p=$a(f,...d.map(S=>S.severity),...l.map(S=>S.status)),g=o.score??r.score??r.overallScore??s,m=u_(g),v=Vt(o.headline,o.summary,o.executiveSummary,o.overview,o.assessment,o.conclusion,r.overallSummary,r.headline,r.summary,r.executiveSummary,r.overview,r.assessment,r.conclusion,s)||__({status:p,score:m,artifactPresentations:l,manualSteps:h}),E=l.reduce((S,_)=>(S[_.status]+=1,S),{pass:0,warning:0,fail:0});return{title:n.title||"Generated artifact bundle",description:n.description||"",status:p,score:m,summary:v,findings:d,manualSteps:h,artifacts:l,counts:E,reviewCoverage:{reviewed:l.filter(S=>S.reviewComplete).length,total:l.length},deployOrder:kt(n.deployOrder),relationships:kt(n.relationships),warnings:kt(n.warnings),compatibility:st(n.metadata?.compatibility)}}const w_=/^\uFEFF/;function Ai(t){let e=0,n=t.length;for(;ee&&!t[n-1].trim();)n--;return t.slice(e,n).join(` +`)},g=new Set(l.slice(1).map(({index:m})=>m));o=o.filter((m,v)=>!g.has(v)),o[h.index]=p}const u={...Nu(t?.dependencies),...r.reduce((h,p)=>({...h,...Nu(p.dependencies)}),{})},c={};r.forEach(h=>{Sl(h.code||"").forEach(p=>{p in u||(c[p]="")})});const d={...c,...u},f=n_(o);return{bundleId:t?.id||"bundle-current",title:t?.title||"Generated artifact bundle",fileEntries:o,dependencies:d,relationships:t?.relationships||[],warnings:s,errors:f}}function r_(t){return String(t||"").match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/)?.[1]}function s_(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 o_(t,e){const i=[s_(t),r_(e.content),e.artifactName].find(r=>/^[A-Z][A-Za-z0-9_]*$/.test(String(r||"")));if(!i)throw new Error(`Cannot derive a FlutterFlow custom class name for ${t}.`);return i}function a_(t,e=new Map){const n=[];for(const[i,r]of t.entries())r.type!=="C"||e.has(r.path)||n.push({artifactId:r.artifactId||i,className:o_(i,r),content:r.content,fileName:i,path:r.path});return n}function l_(t,e){const n=new Set(e.map(i=>i.path));return new Map(Array.from(t.entries()).filter(([,i])=>!n.has(i.path)))}const Ou={pass:0,warning:1,fail:2},c_=["manualActions"];function st(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Vt(...t){for(const e of t){if(typeof e=="string"&&e.trim())return e.trim();if(Array.isArray(e)&&e.length>0){const n=e.filter(i=>typeof i=="string").join(` +`);if(n)return n}}return""}function kt(t){return t==null?[]:Array.isArray(t)?t:[t]}function u_(t){const e=st(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const n=Number(e);if(Number.isFinite(n))return Bu(n);const i=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return i?Bu(Number(i[1])):null}function Bu(t){return t>=0&&t<=100?t:null}function lt(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function xl(t){const e=String(t||"").toLowerCase();return/(fail|error|critical|block|reject|invalid)/.test(e)?"fail":/(warn|attention|manual|partial|incomplete|concern)/.test(e)?"warning":/(pass|success|ready|approve|valid|clean|info|notice)/.test(e)?"pass":null}function $a(...t){return t.filter(Boolean).reduce((e,n)=>Ou[n]>Ou[e]?n:e,"pass")}function fh(t,e="warning",n="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:n};const i=st(t),r=Vt(i.message,i.title,i.issue,i.description,i.summary);return r?{severity:xl(i.severity||i.status||i.level)||e,message:r,suggestion:Vt(i.suggestion,i.fix,i.recommendation,i.action),source:i.source||n}:null}function Ma(t,e="review"){const n=st(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([r,s])=>kt(n[r]).map(o=>fh(o,s,e)).filter(Boolean))}function d_(t,e,n=null){if(typeof t=="string")return{id:`${n||"bundle"}-manual-${e+1}`,title:t,detail:"",location:"",timing:"unspecified",artifactId:n,source:"Code Review"};const i=st(t),r=Vt(i.title,i.action,i.step,i.message,i.name,i.description);return r?{id:i.id||`${n||"bundle"}-manual-${e+1}`,title:r,detail:Vt(i.detail,i.instructions,i.description),location:Vt(i.location,i.flutterFlowPath,i.path),timing:Vt(i.timing,i.phase)||"unspecified",artifactId:n,source:Vt(i.source)||"Code Review"}:null}function La(t,e=null){const n=st(t);return c_.flatMap(i=>kt(n[i])).map((i,r)=>d_(i,r,e)).filter(Boolean)}function f_(t){let e=typeof t=="string"?Ra(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const n=st(e);typeof n.content=="string"&&(e=Ra(n.content)||e);const i=st(e),r=st(i.reviewResult||i.codeReview||i.result);return{rawText:"",root:Object.keys(r).length?r:i}}function h_(t,e){const n=[e.id,e.fileName,e.artifactName].map(lt);return t.find(i=>{const r=st(i);return[r.id,r.fileName,r.artifactName,r.name].map(lt).some(s=>s&&n.includes(s))})||null}function p_(t,e){return kt(t?.metadata?.compatibility?.deployHints).find(r=>lt(r?.artifactId)===lt(e.id)||lt(r?.fileName)===lt(e.fileName))?.pathHint||""}function g_(t,e){return kt(t?.relationships).filter(n=>lt(n?.from)===lt(e.id)||lt(n?.to)===lt(e.id))}function m_(t,e){return kt(t?.metadata?.compatibility?.findings).filter(n=>!n?.artifactId||lt(n.artifactId)===lt(e.id)).map(n=>fh(n,"warning","Compatibility check")).filter(Boolean)}function v_(t,e,n,i){const r=h_(e,n),s=st(r?.review||r||n.review),o=Object.keys(s).length>0,a=[...Ma(s),...m_(t,n)],l=La(s,n.id),u=xl(s.status||s.verdict||s.outcome||s.result),c=a.length?$a(...a.map(f=>f.severity)):null,d=$a(u,c,o?null:"warning");return{...n,index:i,status:d,statusReason:o?Vt(s.summary,s.overview,s.assessment,s.conclusion)||(a.length?`${a.length} review finding${a.length===1?"":"s"}`:"No file-level findings"):"No file-level verdict was returned",reviewComplete:o,findings:a,manualSteps:l,fixedSource:typeof s.fixedSource=="string"&&s.fixedSource.trim()?s.fixedSource.trim():null,pathHint:p_(t,n),relationships:g_(t,n)}}function __({status:t,score:e,artifactPresentations:n,manualSteps:i}){const r=n.length;if(r===0&&i.length===0)return e==null?"Code review returned no overall summary and no score.":`Reviewed bundle with score ${e}/100.`;const s=n.reduce((a,l)=>(a[l.status]+=1,a),{pass:0,warning:0,fail:0}),o=[];return t&&o.push(`Overall verdict: ${t}.`),r&&o.push(`${r} artifact${r===1?"":"s"}: ${s.pass} pass, ${s.warning} warn, ${s.fail} fail.`),i.length&&o.push(`Do before deploy: ${i.map(a=>a.title).join("; ")}.`),e==null&&o.push("No numeric score (0-100) was returned."),o.join(" ")}function y_({bundle:t,reviewResult:e}){const n=st(t),i=kt(n.artifacts),{root:r,rawText:s}=f_(e),o=[r.bundleReview,r.overallReview,r.overall,r.bundleSummary,r.summaryReview,r.review].map(st).find(S=>Object.keys(S).length)||{},a=kt(r.artifacts||r.files||r.reviews),l=i.map((S,_)=>v_(n,a,S,_)),u=Ma(r),d=[...Ma(o),...u],f=[...La(o),...La(r),...l.flatMap(S=>S.manualSteps)].filter((S,_,b)=>b.findIndex(k=>k.title===S.title&&k.artifactId===S.artifactId)===_),h=xl(o.status||o.verdict||o.overallStatus||r.status||r.verdict||r.overallStatus||r.outcome),p=$a(h,...d.map(S=>S.severity),...l.map(S=>S.status)),g=o.score??r.score??r.overallScore??s,m=u_(g),v=Vt(o.headline,o.summary,o.executiveSummary,o.overview,o.assessment,o.conclusion,r.overallSummary,r.headline,r.summary,r.executiveSummary,r.overview,r.assessment,r.conclusion,s)||__({status:p,score:m,artifactPresentations:l,manualSteps:f}),E=l.reduce((S,_)=>(S[_.status]+=1,S),{pass:0,warning:0,fail:0});return{title:n.title||"Generated artifact bundle",description:n.description||"",status:p,score:m,summary:v,findings:d,manualSteps:f,artifacts:l,counts:E,reviewCoverage:{reviewed:l.filter(S=>S.reviewComplete).length,total:l.length},deployOrder:kt(n.deployOrder),relationships:kt(n.relationships),warnings:kt(n.warnings),compatibility:st(n.metadata?.compatibility)}}const w_=/^\uFEFF/;function Ai(t){let e=0,n=t.length;for(;ee&&!t[n-1].trim();)n--;return t.slice(e,n).join(` `)}function b_(t){const e=String(t??"").replace(w_,"");if(!e.trim())return"";const n=e.split(` -`),i=c=>{const d=c.trim();return/^`{3,}[A-Za-z0-9+#_.-]*$/.test(d)?c.length-c.trimStart().length:-1};let r=0,s=-1;const o=[];{let c=0;for(let d=0;d=0&&(r++,s<0&&(s=d),o.push(c+h)),c+=n[d].length+1}}if(r===0)return Ai(n);{const c=Na(e);if(!c.error&&o.every(h=>ju(h,c.commentAndStringRanges)))return Ai(n)}if(r===1){const c=Ai(n.slice(0,s)),d=Ai(n.slice(s+1));return d.length>=c.length?d:c}const a=[];let l=null;for(let c=0;cc.length>0);return u.length===0?"":u.join(` +`),i=c=>{const d=c.trim();return/^`{3,}[A-Za-z0-9+#_.-]*$/.test(d)?c.length-c.trimStart().length:-1};let r=0,s=-1;const o=[];{let c=0;for(let d=0;d=0&&(r++,s<0&&(s=d),o.push(c+f)),c+=n[d].length+1}}if(r===0)return Ai(n);{const c=Na(e);if(!c.error&&o.every(f=>ju(f,c.commentAndStringRanges)))return Ai(n)}if(r===1){const c=Ai(n.slice(0,s)),d=Ai(n.slice(s+1));return d.length>=c.length?d:c}const a=[];let l=null;for(let c=0;cc.length>0);return u.length===0?"":u.join(` `)}function E_(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 hh(t){const e=E_(t);return Array.from(e.matchAll(/class\s+([A-Z]\w*)\s+extends\s+[A-Za-z_]\w*Widget\b/g),n=>n[1])}function ph(t){return`${El(t)}.dart`}function S_(t){return wl(t,"W")}const Du={"(":")","[":"]","{":"}"},x_={")":"(","]":"[","}":"{"},I_=/[A-Za-z0-9_]/;function Na(t){const e=[{kind:"code",opener:null,openedLine:0}],n=[];let i=1,r=0;const s=(c,d)=>{(c===` `||c==="\r"&&d!==` `)&&i++};let o=null;const a=()=>{for(const c of e)(c.kind==="string"||c.kind==="block-comment"||c.kind==="line-comment")&&n.push({start:c.startIndex,end:t.length})};for(;r0?t[r-1]:"",p=r>1?t[r-2]:"",g=(f==="r"||f==="R")&&!I_.test(p);e.push({kind:"string",quote:c,triple:h,raw:g,startIndex:r,openedLine:i}),r+=h?3:1;continue}if(Du[c]){e.push({kind:"code",opener:c,openedLine:i}),r++;continue}if(x_[c]){if(d.interpolation&&c==="}"){e.pop(),r++;continue}if(d.opener&&Du[d.opener]===c){e.pop(),r++;continue}return d.opener?(a(),{error:o??`line ${i}: "${c}" closes nothing - "${d.opener}" opened on line ${d.openedLine} is still open`,commentAndStringRanges:n}):(a(),{error:o??`line ${i}: unexpected "${c}" with no matching opener`,commentAndStringRanges:n})}s(c,t[r+1]),r++}a();let l=e.length-1;for(;l>0&&e[l].kind==="line-comment";)l--;let u=o;if(!u){const c=e[l];if(!(c.kind==="code"&&!c.opener&&!c.interpolation))if(c.kind==="string")u=`unclosed ${c.triple?"triple-quoted ":""}string starting on line ${c.openedLine} was never closed`;else if(c.kind==="block-comment")u=`unterminated /* comment starting on line ${c.openedLine}`;else if(c.interpolation){const d=e.findLast(f=>f.opener);u=`unclosed "\${" expression${d?` opened on line ${d.openedLine}`:""} was never closed`}else u=`"${c.opener}" opened on line ${c.openedLine} is never closed`}return{error:u,commentAndStringRanges:n}}function k_(t){return Na(String(t??"")).error}function ju(t,e){return e.some(({start:n,end:i})=>t>=n&&ttypeof n=="string"?n:n?.errorMessage).filter(Boolean);return e.length>0?e.join("; "):JSON.stringify(t)}return t&&typeof t=="object"?t.errorMessage||JSON.stringify(t):String(t??"")}const C_=["gmail.com","googlemail.com","outlook.com","hotmail.com","live.com","msn.com"],A_="MAGIC_LINK_SENT",P_="PLUS_ALIAS_REJECTED",F_="Please enter your primary email address. Plus aliases (such as {email}) are not allowed for {domain} accounts.",Rs={allowlistedDomains:C_,successCode:A_,validationCode:P_,messageTemplate:F_},R_=new Set(Rs.allowlistedDomains),T_=Rs.successCode,gh=Rs.validationCode;function Ts(t){return typeof t=="string"?t.trim():""}function $_(t){const e=Ts(t),n=e.lastIndexOf("@");if(n<=0||n===e.length-1)return!1;const i=e.slice(0,n),r=e.slice(n+1).toLowerCase();return R_.has(r)?i.includes("+"):!1}function M_(t,e){return Rs.messageTemplate.replaceAll("{email}",t).replaceAll("{domain}",e)}function mh(t){if(!$_(t))return null;const e=Ts(t),n=e.lastIndexOf("@"),i=e.slice(n+1).toLowerCase();return M_(e,i)}function vh(t,e){return t?.code===gh?t.message||mh(e)||"Please enter your primary email address.":t?.code===T_||!t?.code?`Check your email — we sent a link to ${Ts(e)}`:t.message||"Something went wrong. Please try again."}const L_="ccc_auth_session",N_="ccc_subscription",O_=Object.freeze(["hasSeenWalkthrough"]);function B_(t){const e=[];for(const n of O_)t.getItem(n)!==null&&(t.removeItem(n),e.push(n));return e}function D_(){return[L_,N_]}function j_({storage:t,onIdentityChanged:e,onPlanChanged:n}){for(const i of D_())t.removeItem(i);typeof e=="function"&&e(),typeof n=="function"&&n()}function U_({sendLink:t,getEmail:e,onState:n}){let i=!1;return async function(){if(i)return{status:"busy"};i=!0;let s;try{n({status:"pending",error:null});const o=await t(e());return s={status:"sent",data:o},n({status:"sent",data:o}),s}catch(o){return s={status:"error",error:o},n({status:"error",error:o}),s}finally{i=!1}}}const H_=/^dependencies\s*:\s*(?:#.*)?$/,W_=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function $s(t){const e=t.match(W_);return e?e[1]??e[2]??e[3]:null}function cr(t){const e=t.trim();return e===""||e.startsWith("#")}function hi(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function kl(t,e){const n=t.findIndex(s=>e.test(s));if(n===-1)return null;let i=n,r=null;for(let s=n+1;s=0.0.0"}`}function G_(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([u])=>u&&u!=="flutter");if(i.length===0)return{yaml:n,added:[],alreadyPresent:[]};const r=n.split(` +`){n.push({start:d.startIndex,end:r}),o??=`line ${i}: string starting on line ${d.openedLine} is never closed`,e.pop();continue}if(!d.raw&&c==="\\"){s(t[r+1]??"",t[r+2]??""),r+=2;continue}if(!d.raw&&c==="$"&&t[r+1]==="{"){e.push({kind:"code",opener:null,interpolation:!0}),r+=2;continue}const f=d.triple?3:1;if(c===d.quote&&t.slice(r,r+f)===d.quote.repeat(f)){n.push({start:d.startIndex,end:r+f}),e.pop(),r+=f;continue}s(c,t[r+1]),r++;continue}if(c==="/"&&t[r+1]==="/"){e.push({kind:"line-comment",startIndex:r}),r+=2;continue}if(c==="/"&&t[r+1]==="*"){e.push({kind:"block-comment",startIndex:r,openedLine:i,depth:1}),r+=2;continue}if(c==="'"||c==='"'){const f=t.slice(r,r+3)===c.repeat(3),h=r>0?t[r-1]:"",p=r>1?t[r-2]:"",g=(h==="r"||h==="R")&&!I_.test(p);e.push({kind:"string",quote:c,triple:f,raw:g,startIndex:r,openedLine:i}),r+=f?3:1;continue}if(Du[c]){e.push({kind:"code",opener:c,openedLine:i}),r++;continue}if(x_[c]){if(d.interpolation&&c==="}"){e.pop(),r++;continue}if(d.opener&&Du[d.opener]===c){e.pop(),r++;continue}return d.opener?(a(),{error:o??`line ${i}: "${c}" closes nothing - "${d.opener}" opened on line ${d.openedLine} is still open`,commentAndStringRanges:n}):(a(),{error:o??`line ${i}: unexpected "${c}" with no matching opener`,commentAndStringRanges:n})}s(c,t[r+1]),r++}a();let l=e.length-1;for(;l>0&&e[l].kind==="line-comment";)l--;let u=o;if(!u){const c=e[l];if(!(c.kind==="code"&&!c.opener&&!c.interpolation))if(c.kind==="string")u=`unclosed ${c.triple?"triple-quoted ":""}string starting on line ${c.openedLine} was never closed`;else if(c.kind==="block-comment")u=`unterminated /* comment starting on line ${c.openedLine}`;else if(c.interpolation){const d=e.findLast(h=>h.opener);u=`unclosed "\${" expression${d?` opened on line ${d.openedLine}`:""} was never closed`}else u=`"${c.opener}" opened on line ${c.openedLine} is never closed`}return{error:u,commentAndStringRanges:n}}function k_(t){return Na(String(t??"")).error}function ju(t,e){return e.some(({start:n,end:i})=>t>=n&&ttypeof n=="string"?n:n?.errorMessage).filter(Boolean);return e.length>0?e.join("; "):JSON.stringify(t)}return t&&typeof t=="object"?t.errorMessage||JSON.stringify(t):String(t??"")}const C_=["gmail.com","googlemail.com","outlook.com","hotmail.com","live.com","msn.com"],A_="MAGIC_LINK_SENT",P_="PLUS_ALIAS_REJECTED",F_="Please enter your primary email address. Plus aliases (such as {email}) are not allowed for {domain} accounts.",Fs={allowlistedDomains:C_,successCode:A_,validationCode:P_,messageTemplate:F_},R_=new Set(Fs.allowlistedDomains),T_=Fs.successCode,gh=Fs.validationCode;function Rs(t){return typeof t=="string"?t.trim():""}function $_(t){const e=Rs(t),n=e.lastIndexOf("@");if(n<=0||n===e.length-1)return!1;const i=e.slice(0,n),r=e.slice(n+1).toLowerCase();return R_.has(r)?i.includes("+"):!1}function M_(t,e){return Fs.messageTemplate.replaceAll("{email}",t).replaceAll("{domain}",e)}function mh(t){if(!$_(t))return null;const e=Rs(t),n=e.lastIndexOf("@"),i=e.slice(n+1).toLowerCase();return M_(e,i)}function vh(t,e){return t?.code===gh?t.message||mh(e)||"Please enter your primary email address.":t?.code===T_||!t?.code?`Check your email — we sent a link to ${Rs(e)}`:t.message||"Something went wrong. Please try again."}const L_="ccc_auth_session",N_="ccc_subscription",O_=Object.freeze(["hasSeenWalkthrough"]);function B_(t){const e=[];for(const n of O_)t.getItem(n)!==null&&(t.removeItem(n),e.push(n));return e}function D_(){return[L_,N_]}function j_({storage:t,onIdentityChanged:e,onPlanChanged:n}){for(const i of D_())t.removeItem(i);typeof e=="function"&&e(),typeof n=="function"&&n()}function U_({sendLink:t,getEmail:e,onState:n}){let i=!1;return async function(){if(i)return{status:"busy"};i=!0;let s;try{n({status:"pending",error:null});const o=await t(e());return s={status:"sent",data:o},n({status:"sent",data:o}),s}catch(o){return s={status:"error",error:o},n({status:"error",error:o}),s}finally{i=!1}}}const H_=/^dependencies\s*:\s*(?:#.*)?$/,W_=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function Ts(t){const e=t.match(W_);return e?e[1]??e[2]??e[3]:null}function lr(t){const e=t.trim();return e===""||e.startsWith("#")}function hi(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function kl(t,e){const n=t.findIndex(s=>e.test(s));if(n===-1)return null;let i=n,r=null;for(let s=n+1;s=0.0.0"}`}function G_(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([u])=>u&&u!=="flutter");if(i.length===0)return{yaml:n,added:[],alreadyPresent:[]};const r=n.split(` `),s=new Set(yh(n)),o=[],a=[];for(const[u,c]of i)s.has(u)?a.push(u):(o.push([u,c]),s.add(u));if(o.length===0)return{yaml:n,added:[],alreadyPresent:a};const l=Cl(r);if(l){const u=o.map(([c,d])=>Uu(l.childIndent,c,d));r.splice(l.endIndex,0,...u)}else r.length>0&&r[r.length-1].trim()!==""&&r.push(""),r.push("dependencies:"),o.forEach(([u,c])=>{r.push(Uu(" ",u,c))});return{yaml:r.join(` `),added:o.map(([u])=>u),alreadyPresent:a}}function K_(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([l])=>l&&l!=="flutter");if(i.length===0)return{yaml:n,overridden:[],skipped:[]};const r=n.split(` -`),s=Ls(n),o=[],a=[];for(const[l,u]of i){const c=s.get(l);if(!c||!c.isScalar||!String(u||"").trim()){a.push(l);continue}const d=" ".repeat(hi(r[c.lineIndex]));r[c.lineIndex]=`${d}${l}: ${bh(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:r.join(` +`),s=Ms(n),o=[],a=[];for(const[l,u]of i){const c=s.get(l);if(!c||!c.isScalar||!String(u||"").trim()){a.push(l);continue}const d=" ".repeat(hi(r[c.lineIndex]));r[c.lineIndex]=`${d}${l}: ${bh(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:r.join(` `),overridden:o,skipped:a}}function Eh(t){const e=String(t||""),n=[];return e.trim()?(/^name:\s*\S+/m.test(e)||n.push("pubspec.yaml missing name field"),Cl(e.split(` -`))||n.push("pubspec.yaml missing dependencies section"),yh(e).includes("flutter")||n.push("pubspec.yaml missing Flutter SDK dependency"),{valid:n.length===0,errors:n}):(n.push("pubspec.yaml is empty"),{valid:!1,errors:n})}const Y_=">=3.0.0 <4.0.0";function Oa(t){const e=String(t||"").trim(),n=e[0];return n!=="'"&&n!=='"'||e[e.length-1]!==n?e:e.slice(1,-1).replaceAll(`${n}${n}`,n)}function J_(t=""){const e=Xv(t).filter(n=>!n.startsWith("dart:")&&!n.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function Hu(t,e,n){const i=[];for(const[r,s]of t){if(s.isScalar){e[r]=Oa(s.constraint);continue}if(s.sourceKey==="sdk"){n.add(r);continue}if(s.sourceKey===null&&s.version){e[r]=Oa(s.version);continue}i.push(r)}return i}function Z_(t){const e=new Set,n={},i={},r=Hu(Ls(t),n,e);r.push(...Hu(q_(t,"dependency_overrides"),i,e));const s=new Set([...Object.keys(n),...e]),{sdk:o}=wh(t);return{sdkConstraint:Oa(o)||Y_,dependencies:n,overrides:i,sdkPackages:[...e].sort(),availablePackages:s,unrepresentable:r}}function X_(t,e,n){return e.length>0?`${t} imports ${e.join(", ")}, which FlutterFlow only generates once the app is built, so it could not be compiled before the deploy.`:`${t} imports ${n.join(", ")}, which your project's pubspec.yaml does not declare with a version constraint, so it could not be compiled before the deploy.`}function Q_(t,e){const{sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s,availablePackages:o,unrepresentable:a}=Z_(e),l={sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s},u=[],c=[],d=a.map(h=>`Your project declares ${h} from a source that cannot be reproduced outside it, so the pre-deploy compile check runs against a scratch package graph that omits ${h}. Classes that do not import ${h} directly are still checked, but against that reduced graph, so their transitive package resolution may differ from your project's and the check is approximate for them.`);for(const h of t){const{className:f,content:p}=h,g=Sl(p),m=g.filter(S=>a.includes(S));if(m.length>0){c.push({className:f,reason:`${f} was not compiled before deploying: it imports ${m.join(", ")}, which your project declares from a source that cannot be reproduced outside it, so package resolution could not be matched exactly.`});continue}const{unresolvableImports:v}=J_(p),E=g.filter(S=>!o.has(S));if(v.length>0||E.length>0){c.push({className:f,reason:X_(f,v,E)});continue}u.push({fileName:`${El(f)}.dart`,content:p})}return{manifest:l,sources:u,skipped:c,approximate:d}}function Wu(t,e){const n=`${t}${e}`.split(` -`),i=n.pop()??"",r=[];for(const s of n){const o=Sh(s);o&&r.push(o)}return{events:r,buffer:i}}function ey(t){const e=Sh(t);return e?[e]:[]}function Sh(t){const e=t.trim();if(!e)return null;try{const n=JSON.parse(e);return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}const Le=Object.freeze({COMMITTED:"committed",PARTIAL:"partial",FAILED:"failed",UNCONFIRMED:"unconfirmed"}),xh=12e4,Ih=1e4;function kh(t){return t?.unconfirmed===!0||t?.outcome===Le.UNCONFIRMED?Le.UNCONFIRMED:t?.partial===!0||t?.outcome===Le.PARTIAL?Le.PARTIAL:t?.success===!0?Le.COMMITTED:Le.FAILED}class Qe extends Error{constructor(e){super(e),this.name="UnconfirmedDeployError",this.outcome=Le.UNCONFIRMED}}function zu({httpStatus:t}={}){return new Qe(`Every FlutterFlow sync endpoint lost its response or ended in a server error${t?` (last: HTTP ${t})`:""} — neither can prove the push was refused, so it may already have been applied. Open the FlutterFlow project to reconcile before retrying.`)}async function ty(t,e={}){const{onPhase:n,onLog:i}=e;let r=null,s=null,o="";const a=u=>{if(u.event==="phase"){u.phase&&(s=u.phase),u.message&&n&&n(u.message);return}if(u.event==="log"){u.message&&i&&i(u.message);return}r=u};let l=null;try{if(t.body?.getReader){const u=t.body.getReader(),c=new TextDecoder;for(;;){const{done:d,value:h}=await u.read();if(d)break;const f=Wu(o,c.decode(h,{stream:!0}));o=f.buffer,f.events.forEach(a)}}else{const u=Wu("",await t.text());o=u.buffer,u.events.forEach(a)}}catch(u){l=u}return ey(o).forEach(a),r?{...r,success:r.success===!0||r.success===void 0&&t.ok,finalResultReceived:!0,runnerPhase:s,httpStatus:t.status}:{success:!1,finalResultReceived:!1,httpRejected:!t.ok,httpStatus:t.status,runnerPhase:s,error:t.ok?l?"The connection to the FlutterFlow deploy runner dropped before it reported a result.":"The FlutterFlow deploy runner closed the connection before it finished.":`FlutterFlow custom class provisioning failed (HTTP ${t.status}).`}}const ny=new Set(["connected","workspace_init","workspace_ready","verifying"]);function iy(t){return t?.preWrite===!0||Array.isArray(t?.analyzerErrors)&&t.analyzerErrors.length>0?!0:typeof t?.runnerPhase=="string"?ny.has(t.runnerPhase):typeof t?.httpStatus=="number"?t.httpStatus>=400&&t.httpStatus<500:!1}function qu(t){if(t?.finalResultReceived){const e=kh(t);return e===Le.FAILED&&!iy(t)?Le.UNCONFIRMED:e}return t?.httpRejected?Le.FAILED:Le.UNCONFIRMED}function ry(){let t=document.getElementById("fx-grid");if(!t)return null;const e=window.matchMedia("(prefers-reduced-motion: reduce)"),n=window.matchMedia("(pointer: none)");let i=t.getContext("webgl2",{alpha:!0,antialias:!1,depth:!1,stencil:!1,premultipliedAlpha:!0,powerPreference:"low-power"}),r=i?null:t.getContext("2d");if(!i&&!r)return null;const s='',o=`#version 300 es +`))||n.push("pubspec.yaml missing dependencies section"),yh(e).includes("flutter")||n.push("pubspec.yaml missing Flutter SDK dependency"),{valid:n.length===0,errors:n}):(n.push("pubspec.yaml is empty"),{valid:!1,errors:n})}const Y_=">=3.0.0 <4.0.0";function Oa(t){const e=String(t||"").trim(),n=e[0];return n!=="'"&&n!=='"'||e[e.length-1]!==n?e:e.slice(1,-1).replaceAll(`${n}${n}`,n)}function J_(t=""){const e=Xv(t).filter(n=>!n.startsWith("dart:")&&!n.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function Hu(t,e,n){const i=[];for(const[r,s]of t){if(s.isScalar){e[r]=Oa(s.constraint);continue}if(s.sourceKey==="sdk"){n.add(r);continue}if(s.sourceKey===null&&s.version){e[r]=Oa(s.version);continue}i.push(r)}return i}function Z_(t){const e=new Set,n={},i={},r=Hu(Ms(t),n,e);r.push(...Hu(q_(t,"dependency_overrides"),i,e));const s=new Set([...Object.keys(n),...e]),{sdk:o}=wh(t);return{sdkConstraint:Oa(o)||Y_,dependencies:n,overrides:i,sdkPackages:[...e].sort(),availablePackages:s,unrepresentable:r}}function X_(t,e,n){return e.length>0?`${t} imports ${e.join(", ")}, which FlutterFlow only generates once the app is built, so it could not be compiled before the deploy.`:`${t} imports ${n.join(", ")}, which your project's pubspec.yaml does not declare with a version constraint, so it could not be compiled before the deploy.`}function Q_(t,e){const{sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s,availablePackages:o,unrepresentable:a}=Z_(e),l={sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s},u=[],c=[],d=a.map(f=>`Your project declares ${f} from a source that cannot be reproduced outside it, so the pre-deploy compile check runs against a scratch package graph that omits ${f}. Classes that do not import ${f} directly are still checked, but against that reduced graph, so their transitive package resolution may differ from your project's and the check is approximate for them.`);for(const f of t){const{className:h,content:p}=f,g=Sl(p),m=g.filter(S=>a.includes(S));if(m.length>0){c.push({className:h,reason:`${h} was not compiled before deploying: it imports ${m.join(", ")}, which your project declares from a source that cannot be reproduced outside it, so package resolution could not be matched exactly.`});continue}const{unresolvableImports:v}=J_(p),E=g.filter(S=>!o.has(S));if(v.length>0||E.length>0){c.push({className:h,reason:X_(h,v,E)});continue}u.push({fileName:`${El(h)}.dart`,content:p})}return{manifest:l,sources:u,skipped:c,approximate:d}}function Wu(t,e){const n=`${t}${e}`.split(` +`),i=n.pop()??"",r=[];for(const s of n){const o=Sh(s);o&&r.push(o)}return{events:r,buffer:i}}function ey(t){const e=Sh(t);return e?[e]:[]}function Sh(t){const e=t.trim();if(!e)return null;try{const n=JSON.parse(e);return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}const Le=Object.freeze({COMMITTED:"committed",PARTIAL:"partial",FAILED:"failed",UNCONFIRMED:"unconfirmed"}),xh=12e4,Ih=1e4;function kh(t){return t?.unconfirmed===!0||t?.outcome===Le.UNCONFIRMED?Le.UNCONFIRMED:t?.partial===!0||t?.outcome===Le.PARTIAL?Le.PARTIAL:t?.success===!0?Le.COMMITTED:Le.FAILED}class Qe extends Error{constructor(e){super(e),this.name="UnconfirmedDeployError",this.outcome=Le.UNCONFIRMED}}function zu({httpStatus:t}={}){return new Qe(`Every FlutterFlow sync endpoint lost its response or ended in a server error${t?` (last: HTTP ${t})`:""} — neither can prove the push was refused, so it may already have been applied. Open the FlutterFlow project to reconcile before retrying.`)}async function ty(t,e={}){const{onPhase:n,onLog:i}=e;let r=null,s=null,o="";const a=u=>{if(u.event==="phase"){u.phase&&(s=u.phase),u.message&&n&&n(u.message);return}if(u.event==="log"){u.message&&i&&i(u.message);return}r=u};let l=null;try{if(t.body?.getReader){const u=t.body.getReader(),c=new TextDecoder;for(;;){const{done:d,value:f}=await u.read();if(d)break;const h=Wu(o,c.decode(f,{stream:!0}));o=h.buffer,h.events.forEach(a)}}else{const u=Wu("",await t.text());o=u.buffer,u.events.forEach(a)}}catch(u){l=u}return ey(o).forEach(a),r?{...r,success:r.success===!0||r.success===void 0&&t.ok,finalResultReceived:!0,runnerPhase:s,httpStatus:t.status}:{success:!1,finalResultReceived:!1,httpRejected:!t.ok,httpStatus:t.status,runnerPhase:s,error:t.ok?l?"The connection to the FlutterFlow deploy runner dropped before it reported a result.":"The FlutterFlow deploy runner closed the connection before it finished.":`FlutterFlow custom class provisioning failed (HTTP ${t.status}).`}}const ny=new Set(["connected","workspace_init","workspace_ready","verifying"]);function iy(t){return t?.preWrite===!0||Array.isArray(t?.analyzerErrors)&&t.analyzerErrors.length>0?!0:typeof t?.runnerPhase=="string"?ny.has(t.runnerPhase):typeof t?.httpStatus=="number"?t.httpStatus>=400&&t.httpStatus<500:!1}function qu(t){if(t?.finalResultReceived){const e=kh(t);return e===Le.FAILED&&!iy(t)?Le.UNCONFIRMED:e}return t?.httpRejected?Le.FAILED:Le.UNCONFIRMED}function ry(){let t=document.getElementById("fx-grid");if(!t)return null;const e=window.matchMedia("(prefers-reduced-motion: reduce)"),n=window.matchMedia("(pointer: none)");let i=t.getContext("webgl2",{alpha:!0,antialias:!1,depth:!1,stencil:!1,premultipliedAlpha:!0,powerPreference:"low-power"}),r=i?null:t.getContext("2d");if(!i&&!r)return null;const s='',o=`#version 300 es in vec2 p; void main(){ gl_Position = vec4(p, 0.0, 1.0); }`;function a(){return["#version 300 es","precision highp float;","out vec4 o;","uniform vec2 res;","uniform vec2 design;","uniform vec2 mouse;","uniform float energy;","uniform float parallax;","uniform float t;","uniform vec3 ink;","uniform sampler2D mark;","uniform vec2 rot;","const float WARP_A = 0.0032;","void main(){"," vec2 px = gl_FragCoord.xy * (design / res);"," vec2 p = vec2(px.x, design.y - px.y);"," vec2 off = vec2(0.0, -parallax) + vec2(sin(t * 0.11), cos(t * 0.09)) * 7.0;"," vec2 g = p + off;"," vec2 gm = mouse + off;"," float base = min(design.x, design.y);"," float spacing = clamp(base / 10.0, 64.0, 118.0);"," vec2 rel = g - gm;"," float rho = length(rel) + 1e-5;"," vec2 dir = rel / rho;"," vec2 pw = gm + dir * (rho + WARP_A * rho * rho);"," vec2 cell = floor(pw / spacing);"," vec2 cw = (cell + 0.5) * spacing - gm;"," float Rc = length(cw) + 1e-5;"," float rhoC = (-1.0 + sqrt(1.0 + 4.0 * WARP_A * Rc)) / (2.0 * WARP_A);"," vec2 c = gm + (cw / Rc) * rhoC;"," float cellSize = spacing / (1.0 + 2.0 * WARP_A * rhoC);"," float sigma = spacing * 2.9;"," float f = exp(-(rhoC * rhoC) / (2.0 * sigma * sigma));"," float scale = mix(0.32, 1.42, f);"," float weight = smoothstep(0.06, 0.80, f);"," float hs = cellSize * 0.26 * scale;"," vec2 uv = (g - c) / hs;"," vec2 ruv = mat2(rot.x, rot.y, -rot.y, rot.x) * uv;"," float cov = 0.0;"," if (abs(ruv.x) <= 1.0 && abs(ruv.y) <= 1.0) cov = texture(mark, ruv * 0.5 + 0.5).a;"," float s = cov * weight * energy * 0.26;"," o = vec4(ink * s, s);","}"].join(` -`)}let l=null,u,c,d,h,f,p,g,m,v;function E(Y,W){if(!i)return null;const D=i.createShader(Y);return i.shaderSource(D,W),i.compileShader(D),i.getShaderParameter(D,i.COMPILE_STATUS)?D:(window.console&&console.warn("fx-grid shader: "+i.getShaderInfoLog(D)),null)}if(i){const Y=E(i.VERTEX_SHADER,o),W=E(i.FRAGMENT_SHADER,a());if(Y&&W&&(l=i.createProgram(),i.attachShader(l,Y),i.attachShader(l,W),i.linkProgram(l),i.getProgramParameter(l,i.LINK_STATUS)||(window.console&&console.warn("fx-grid link: "+i.getProgramInfoLog(l)),l=null)),l){i.useProgram(l),i.bindBuffer(i.ARRAY_BUFFER,i.createBuffer()),i.bufferData(i.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),i.STATIC_DRAW);const D=i.getAttribLocation(l,"p");i.enableVertexAttribArray(D),i.vertexAttribPointer(D,2,i.FLOAT,!1,0,0),u=i.getUniformLocation(l,"res"),c=i.getUniformLocation(l,"design"),d=i.getUniformLocation(l,"mouse"),h=i.getUniformLocation(l,"energy"),f=i.getUniformLocation(l,"parallax"),p=i.getUniformLocation(l,"t"),g=i.getUniformLocation(l,"ink"),m=i.getUniformLocation(l,"mark"),v=i.getUniformLocation(l,"rot"),i.enable(i.BLEND),i.blendFunc(i.ONE,i.ONE_MINUS_SRC_ALPHA),i.clearColor(0,0,0,0)}else{i=null;const D=t.cloneNode(!1);if(t.parentNode.replaceChild(D,t),t=D,r=t.getContext("2d"),!r)return null}}function S(Y){if(!Y)return null;const W=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(Y);if(W){let D=W[1];return D.length===3&&(D=D[0]+D[0]+D[1]+D[1]+D[2]+D[2]),[parseInt(D.slice(0,2),16)/255,parseInt(D.slice(2,4),16)/255,parseInt(D.slice(4,6),16)/255]}try{const D=document.createElement("canvas");D.width=1,D.height=1;const ue=D.getContext("2d");ue.fillStyle="rgb(9, 8, 7)";const xe=String(ue.fillStyle);ue.fillStyle=Y;const Fe=String(ue.fillStyle);if(Fe===xe)return null;const dt=/^#([0-9a-f]{6})$/i.exec(Fe);if(dt){const ft=dt[1];return[parseInt(ft.slice(0,2),16)/255,parseInt(ft.slice(2,4),16)/255,parseInt(ft.slice(4,6),16)/255]}const Nt=/rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i.exec(Fe);if(Nt)return[Number(Nt[1])/255,Number(Nt[2])/255,Number(Nt[3])/255]}catch{}return null}function _(){let Y="";try{const W=getComputedStyle(document.documentElement);Y=(W.getPropertyValue("--fx-ink")||"").trim()||(W.getPropertyValue("--fg")||"").trim()}catch{}return S(Y)||[.56,.68,.88]}const b=_();let k=1920,T=1080,x=960,F=540,$=960,O=540,L=.66,N=0,K=-1e9,V=!1,M=0,R=0,Z=null,Ce=!1,oe=!1,ye=!1;const $e=64,ae=15.2;let Ie=0,Se=0;const De=.0032,wt=0,ge=.56,Je=.26,bt=.32,mn=.16,Re=.349;let Pe=wt;function $t(){const Y=t.getBoundingClientRect(),W=t.clientWidth,D=t.clientHeight;if(!Y.width||!W||!D)return;const ue=Math.min(window.devicePixelRatio||1,2),xe=Math.max(.2,Math.min(2,Y.width/W*ue)),Fe=Math.max(2,Math.round(W*xe)),dt=Math.max(2,Math.round(D*xe));(Fe!==t.width||dt!==t.height)&&(t.width=Fe,t.height=dt,i&&i.viewport(0,0,Fe,dt)),k=W,T=D,V||(x=$=k/2,F=O=T/2,V=!0)}function Dn(Y){!l||!Ce||!i||(i.uniform2f(u,t.width,t.height),i.uniform2f(c,k,T),i.uniform2f(d,x,F),i.uniform1f(h,L),i.uniform1f(f,N),i.uniform2f(v,Math.cos(Pe),Math.sin(Pe)),i.uniform1f(p,Y),i.uniform3f(g,b[0],b[1],b[2]),i.clear(i.COLOR_BUFFER_BIT),i.drawArrays(i.TRIANGLES,0,3))}function qe(Y,W,D){const ue=Math.max(0,Math.min(1,(D-Y)/(W-Y)));return ue*ue*(3-2*ue)}function jn(Y){if(!Z||!r)return;const W=r;W.setTransform(1,0,0,1,0,0),W.clearRect(0,0,t.width,t.height);const D=t.width/k;W.setTransform(D,0,0,D,0,0),W.globalAlpha=1;const ue=Math.min(k,T),xe=Math.max(64,Math.min(118,ue/10)),Fe=xe*2.9,dt=2*Fe*Fe,Nt=Math.sin(Y*.11)*7,ft=Math.cos(Y*.09)*7-N,hr=x+Nt,pr=F+ft,ro=Fe*Math.sqrt(2*Math.log(1/.06)),vi=ro+De*ro*ro+xe,Tp=Math.floor((hr-vi)/xe)-1,$p=Math.ceil((hr+vi)/xe)+1,Mp=Math.floor((pr-vi)/xe)-1,Lp=Math.ceil((pr+vi)/xe)+1;for(let so=Mp;so<=Lp;so++){const Np=(so+.5)*xe;for(let oo=Tp;oo<=$p;oo++){const ao=(oo+.5)*xe-hr,lo=Np-pr,co=Math.sqrt(ao*ao+lo*lo)+1e-5;if(co>vi)continue;const gr=(-1+Math.sqrt(1+4*De*co))/(2*De),dc=Math.exp(-(gr*gr)/dt),fc=qe(.06,.8,dc)*L*.26;if(fc<.004)continue;const on=xe/(1+2*De*gr)*.26*(.32+1.1*dc),hc=gr/co,uo=hr+ao*hc,fo=pr+lo*hc;uo<-on*1.6||uo>k+on*1.6||fo<-on*1.6||fo>T+on*1.6||(W.globalAlpha=fc,W.save(),W.translate(uo,fo),W.rotate(Pe),W.drawImage(Z,-on,-on,on*2,on*2),W.restore())}}W.globalAlpha=1}function Mt(Y){if(!oe)return;const W=R?Math.min(.05,(Y-R)/1e3):.016;R=Y;const ue=Y-K>2400?.6:1;L+=(ue-L)*Math.min(1,W*3.2);const xe=Math.min(.05,W);Ie+=(($-x)*$e-Ie*ae)*xe,Se+=((O-F)*$e-Se*ae)*xe,x+=Ie*xe,F+=Se*xe,N=(window.scrollY||window.pageYOffset||0)*.55;const Fe=Y/1e3,dt=x/(k||1)-.5,Nt=F/(T||1)-.5;let ft=dt*(dt>=0?ge:Je)+Nt*(Nt>=0?bt:mn);ft>Re?ft=Re:ft<-Re&&(ft=-Re),Pe=wt+ft-N*6e-4,$t(),i?Dn(Fe):jn(Fe),M=requestAnimationFrame(Mt)}function Lt(Y){if(!oe)return;const W=t.getBoundingClientRect();!W.width||!k||!T||($=(Y.clientX-W.left)/W.width*k,O=(Y.clientY-W.top)/W.height*T,K=performance.now())}function ut(){oe||io||e.matches||n.matches||!ye||document.hidden||(oe=!0,R=0,M=requestAnimationFrame(Mt))}function sn(){oe=!1,M&&(cancelAnimationFrame(M),M=0),R=0}function mi(){e.matches?(sn(),t.classList.remove("is-ready")):ye&&ut()}function Un(){n.matches?sn():ye&&ut()}function lc(){document.hidden?sn():ye&&ut()}const cc=new IntersectionObserver(Y=>{ye=Y[0]?.isIntersecting||!1,ye?ut():sn()},{threshold:0});cc.observe(t),window.addEventListener("pointermove",Lt,{passive:!0,capture:!0}),window.addEventListener("resize",$t),e.addEventListener("change",mi),n.addEventListener("change",Un),document.addEventListener("visibilitychange",lc);function Rp(){const Y=(s.match(/\sd="([^"]+)"/)||[])[1],W=document.createElement("canvas");W.width=256,W.height=256;const D=W.getContext("2d");if(Y&&window.Path2D){const ue=Math.min(8.533333333333333,8.421052631578947);D.setTransform(ue,0,0,ue,ue+(256-30*ue)/2,-6.4*ue),D.fillStyle="rgb(255,255,255)",D.fill(new Path2D(Y),"evenodd"),D.setTransform(1,0,0,1,0,0)}try{const ue=D.getImageData(0,0,256,256),xe=ue.data;for(let Fe=3;Feoe}}const sy=120;function oy(t,e,n){return tn?n:t}function de(t,e,n){return oy((t-e)/(n-e),0,1)}function ay(t){return t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2}function Wo(t){return 1-Math.pow(1-t,3)}function Ve(t,e){return e=e===void 0?1.7:e,1+(e+1)*Math.pow(t-1,3)+e*Math.pow(t-1,2)}function Vu(t){return 1-Math.pow(2,-9*t)*Math.cos(t*15)}function te(t,e){if(t<=e[0].t)return e[0].v;for(let n=1;n8.2&&_<9.4&&(s*=1-.07*Math.sin(de(_,8.2,9.4)*Math.PI))}else if(t<53){const _=t-42;g=te(_,[{t:0,v:1},{t:2,v:0},{t:4.2,v:0},{t:4.6,v:1},{t:6.8,v:1},{t:7.4,v:0},{t:9.4,v:0},{t:10.6,v:1}]),p=te(_,[{t:0,v:1},{t:2,v:.3},{t:4.6,v:1,e:Ve}]),d=te(_,[{t:0,v:0},{t:2,v:.3},{t:4.6,v:.16,e:Ve},{t:10.6,v:0}]),f=te(_,[{t:0,v:0},{t:2,v:-40},{t:4.6,v:0,e:Ve}]),o=te(_,[{t:0,v:0},{t:4.6,v:-.12},{t:10.6,v:0}])}else if(t<60){const _=t-53;c=te(_,[{t:0,v:1},{t:.35,v:0},{t:.45,v:0},{t:.7,v:1}]);const b=de(_,.45,2.2);a=b>0?-2.6*(1-Vu(b)):0,g=te(_,[{t:0,v:1},{t:.57,v:0},{t:.67,v:0},{t:.92,v:1}]);const k=de(_,.67,2.42);h=k>0?-2.6*(1-Vu(k)):0,s=1-.05*(Math.sin(de(_,1.9,2.5)*Math.PI)+Math.sin(de(_,2.5,3.1)*Math.PI))}else if(t<74){let b=function(F){return[te(F,[{t:0,v:0},{t:.25,v:1},{t:.5,v:1},{t:.72,v:.14},{t:.82,v:.14},{t:1,v:0}]),te(F,[{t:0,v:0},{t:.08,v:-.62},{t:.25,v:-.62},{t:.33,v:.62},{t:.7,v:.62},{t:.82,v:-.62},{t:1,v:-.62}])]};var S=b;const _=t-60,k=1-de(_,12,14),T=b(de(_,0,12)),x=b(de(_-.5,0,12));n=T[0]*k,i=(T[1]+.05*Math.sin(_*7))*k,o=(x[0]-T[0])*.6*k,a=(x[1]-T[1])*.6*k,f=(x[0]-T[0])*30*k,E=de(_,0,.4)*k}else if(t<85.4){const _=t-74,b=te(_,[{t:0,v:0},{t:4,v:1},{t:8,v:.24},{t:9.6,v:1,e:Ve},{t:11.4,v:0}]);o=b*.5,d=-b*.5,l=te(_,[{t:0,v:0},{t:4,v:6},{t:8,v:20},{t:9.6,v:38,e:Ve},{t:11.4,v:0}]),f=-l*.7,a=te(_,[{t:0,v:0},{t:8,v:0},{t:9.6,v:.4},{t:11.4,v:0}])}else if(t<96.4){const _=t-85.4,b=de(_,0,5.6),k=de(_,5.6,7.6),T=.72*Math.min(1,_/.6)*(1-k);d=Math.cos(b*Math.PI*2)*T,h=Math.sin(b*Math.PI*2)*T*.55,f=b*360*(1-k);const x=te(_,[{t:0,v:0},{t:7.6,v:0},{t:8.2,v:1,e:Wo},{t:8.6,v:.55},{t:9.4,v:0}]);o=-.16*x,d+=.16*x,l=-6*x,f+=6*x,s=1+.05*x,m=1+.9*x}else if(t<108.6){const _=t-96.4,b=de(_,9.6,12.2);n=te(_,[{t:0,v:0},{t:2.1,v:1},{t:4.8,v:.08},{t:7.5,v:1},{t:9.6,v:0}])*(1-b),i=-.35*Math.abs(Math.sin(de(_,0,9.6)*Math.PI*3))*(1-b);const k=Math.sin(_*6.2)*(1-b);u=1+.12*k,p=1-.12*k,l=k*8,f=-k*8,o=.06*k,d=-.06*k,E=de(_,0,.4)*(1-b)}else{const _=t-108.6,b=Math.sin(de(_,0,8)*Math.PI),k=1-de(_,8,11.4);s=1+.04*b*k,i=-.1*b*k,r=2*b*k,m=1+.5*Math.sin(de(_,0,6)*Math.PI),v=1+.1*Math.sin(de(_,0,6)*Math.PI)}return e.x=n,e.y=i,e.rot=r,e.scale=s,e.ax=o,e.ay=a,e.ar=l,e.asc=u,e.afade=c,e.bx=d,e.by=h,e.br=f,e.bsc=p,e.bfade=g,e.hfade=m,e.hsc=v,e.shd=E,e}function ly(t={}){const e=t.arena||document.querySelector(".pipeline-glyph.logo-loop");if(!e)return null;const n=e.querySelector(".loop-mark"),i=e.querySelector(".loop-piece-a"),r=e.querySelector(".loop-piece-b"),s=e.querySelector(".loop-halo"),o=e.querySelector(".loop-shadow");if(!n||!i||!r||!s||!o)return null;const a=t.reducedMotion||window.matchMedia("(prefers-reduced-motion: reduce)"),l=sy;let u=34,c=0,d=0;function h(){u=n.offsetWidth||34,c=Math.max(0,e.offsetWidth-u-4),d=Math.max(0,(e.offsetHeight-u)/2-2),e.style.setProperty("--mark-c",u/2+"px")}function f(M){const R=Math.min(1,Math.max(0,M.x))*c,Z=M.y*d;n.style.transform="translate3d("+R.toFixed(2)+"px,"+Z.toFixed(2)+"px,0) rotate("+M.rot.toFixed(2)+"deg) scale("+M.scale.toFixed(3)+")",i.style.transform="translate3d("+(M.ax*u).toFixed(2)+"px,"+(M.ay*u).toFixed(2)+"px,0) rotate("+M.ar.toFixed(2)+"deg) scale("+M.asc.toFixed(3)+")",i.style.opacity=M.afade.toFixed(3),r.style.transform="translate3d("+(M.bx*u).toFixed(2)+"px,"+(M.by*u).toFixed(2)+"px,0) rotate("+M.br.toFixed(2)+"deg) scale("+M.bsc.toFixed(3)+")",r.style.opacity=M.bfade.toFixed(3),s.style.transform="scale("+M.hsc.toFixed(3)+")",s.style.opacity=(.09*M.hfade).toFixed(3),o.style.transform="translateX("+R.toFixed(2)+"px) scaleX("+(.75+.4*Math.abs(M.x)).toFixed(3)+")",o.style.opacity=(M.shd*.5).toFixed(3)}let p=0,g=0,m=0,v=!1,E=!1,S=!1,_=0;function b(){return S||a.matches||document.hidden||!e.offsetParent?!1:E}function k(M){if(!v)return;if(m=requestAnimationFrame(k),!b()){x();return}const R=g?(M-g)/1e3:0;g=M,p=(p+Math.min(R,.1))%l,_+=1,f(Pi(p))}function T(){v||S||b()&&(v=!0,g=0,m=requestAnimationFrame(k))}function x(){v=!1,m&&(cancelAnimationFrame(m),m=0),g=0}function F(){b()?T():x()}function $(){a.matches?(x(),f(Pi(0))):F()}function O(){h(),v&&f(Pi(p))}function L(){g=0,F()}const N=new IntersectionObserver(M=>{E=M[0]?M[0].isIntersecting:!1,F()},{threshold:0});N.observe(e),window.addEventListener("resize",O),a.addEventListener("change",$),document.addEventListener("visibilitychange",L);function K(){S||(S=!0,x(),N.disconnect(),window.removeEventListener("resize",O),a.removeEventListener("change",$),document.removeEventListener("visibilitychange",L))}window.addEventListener("pagehide",K);function V(M){p=(M%l+l)%l,f(Pi(p))}return h(),f(Pi(0)),F(),{isRunning:()=>v,currentTime:()=>p,frameCount:()=>_,seek:V,dispose:K}}const cy=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function Xt(t){const e=String(t||"").trim().match(cy);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function uy(t,e){if(t.length===0&&e.length===0)return 0;if(t.length===0)return 1;if(e.length===0)return-1;for(let n=0;n0)}function fy(t){const e=Xt(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function Al(t){let e=String(t??"").trim();if((e.startsWith("'")||e.startsWith('"'))&&(e=e.slice(1,-1).trim()),e===""||e==="any"||e==="*")return{min:null,minInclusive:!1,max:null,maxInclusive:!1};if(e.startsWith("^")){const o=e.slice(1).trim();return Xt(o)?{min:o,minInclusive:!0,max:fy(o),maxInclusive:!1}:null}if(Xt(e))return{min:e,minInclusive:!0,max:e,maxInclusive:!0};const n={min:null,minInclusive:!1,max:null,maxInclusive:!1},i=/(>=|<=|>|<)\s*([0-9][0-9A-Za-z.+-]*)/g;let r=!1,s;for(;(s=i.exec(e))!==null;){const[,o,a]=s;if(!Xt(a))return null;r=!0,o===">="||o===">"?(n.min=a,n.minInclusive=o===">="):(n.max=a,n.maxInclusive=o==="<=")}return r?n:null}function Gu(t,e){const n=Al(t);if(!n||!Xt(e))return!1;if(n.min!==null){const i=ps(e,n.min);if(i<0||i===0&&!n.minInclusive)return!1}if(n.max!==null){const i=ps(e,n.max);if(i>0||i===0&&!n.maxInclusive)return!1}return!0}function hy(t,e){const n=Al(t);if(!n||!Xt(e))return!1;if(n.max===null)return!0;const i=ps(n.max,e);return i>0?!0:i===0&&n.maxInclusive}function Vn(t){const e=Al(t);return e?e.min:null}const py="https://pub.dev/api/packages/",gy=8e3;function my(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null}=e,r=Array.isArray(t?.versions)?t.versions:[];let s=null;for(const o of r){const a=o?.version;if(!a||o.retracted||dy(a))continue;const l=o.pubspec?.environment||{};n&&l.sdk&&!Gu(l.sdk,n)||i&&l.flutter&&!Gu(l.flutter,i)||(!s||ps(a,s)>0)&&(s=a)}return s?{version:s,constraint:`^${s}`}:null}async function vy(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null,fetchImpl:r=fetch}=e;let s;try{const a=await r(`${py}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(gy)});if(!a.ok)return{name:t,constraint:null,version:null,error:a.status===404?`"${t}" was not found on pub.dev`:`pub.dev returned ${a.status} for "${t}"`};s=await a.json()}catch(a){return{name:t,constraint:null,version:null,error:`could not reach pub.dev for "${t}" (${a.message})`}}const o=my(s,{dartSdkFloor:n,flutterSdkFloor:i});return o?{name:t,...o,error:null}:{name:t,constraint:null,version:null,error:n?`no published "${t}" release supports Dart ${n}`:`no published "${t}" release could be read`}}async function _y(t,e={}){const n=await Promise.all(t.map(i=>vy(i,e)));return new Map(n.map(({name:i,...r})=>[i,r]))}async function yy(t,e={},n={}){const{resolveVersions:i=_y}=n,r=Object.entries(e).filter(([c])=>c&&c!=="flutter"),s=wh(t),o={dartSdkFloor:Vn(s.sdk),flutterSdkFloor:Vn(s.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(r.length===0)return a;const l=Ls(t),u=[];for(const[c,d]of r){const h=l.get(c);if(!h){u.push(c);continue}const f=Vn(d);if(!f){a.kept.push({name:c,constraint:h.constraint});continue}if(!h.isScalar){a.warnings.push(`"${c}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${f}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:c,constraint:h.constraint});continue}if(hy(h.constraint,f)){a.kept.push({name:c,constraint:h.constraint});continue}a.overrides[c]=`^${f}`,a.warnings.push(`"${c}" was pinned to ${h.constraint} in your project, which cannot resolve the ${f} the generated code needs. Raising it to ^${f} — this changes a dependency the rest of your app also uses.`)}if(u.length>0){const c=await i(u,o);for(const d of u){const h=c.get(d);if(h?.constraint){a.additions[d]=h.constraint;continue}const f=e[d]||"";if(Vn(f)){a.additions[d]=`^${Vn(f)}`,a.warnings.push(`Could not confirm "${d}" version on pub.dev (${h?.error||"lookup failed"}). Using ^${Vn(f)} from the AI's recommendation — verify this is current.`);continue}a.additions[d]=">=0.0.0",a.warnings.push(`Could not determine a version for "${d}" (${h?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const wy={"&":"&","<":"<",">":">",'"':""","'":"'"};function Qt(t){return String(t??"").replace(/[&<>"']/g,e=>wy[e])}function z(t){return t?Qt(t).replace(/\n/g,"
      "):""}function Jt(t){return Qt(t).replace(/\r?\n/g," ")}function Ns(t,e={}){const n=t?.pipelineStep;if(n!=null&&e[n]!=null)return e[n];const i=t?.message||"";return i.includes("Code Generator")?2:i.includes("Code Review")?3:1}function Ah(t){if(!t)return{kind:"generic",title:"Generation failed",message:"An unknown error occurred. Please try again.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1};if(t.isModelArmor){const n=t.code==="MODEL_ARMOR_BLOCKED";return{kind:"safety",title:t.userTitle||"Request blocked for safety",message:t.userMessage||t.message,detail:t.retryExplanation||"",canRetry:!n,canEdit:!0,canUpgrade:!1}}if(t.isUsageLimit)return{kind:"quota",title:"Monthly limit reached",message:t.message||"You've used all your generations for this period.",detail:"",canRetry:!1,canEdit:!1,canUpgrade:!0};const e=t.message||"";return/timed out after/i.test(e)?{kind:"timeout",title:"Request timed out",message:"The generation service took too long to respond.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:/unreachable|failed to fetch|load failed|cors/i.test(e)?{kind:"network",title:"Connection problem",message:"We couldn't reach the generation service. Check your connection and try again.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:{kind:"generic",title:"Generation failed",message:e||"An unexpected error occurred.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1}}function by(t){const e={"Integration Audit Report":"📋","Critical Issues":"❌",Warnings:"⚠️",Recommendations:"✅","Overall Score":"📊"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📄"}function Ey(t){const e={critical:"❌",warning:"⚠️",recommendation:"✅",score:"📊",issue:"🔍",fix:"🔧"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📝"}function Sy(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 ci(t){if(!t)return"";if(typeof t!="string")return String(t);const e=/```(?:\w+)?\n?([\s\S]*?)```/,n=t.match(e);return n?n[1].trim():t.trim()}function Ku(t){return t=Qt(t),t=t.replace(/\*\*(.*?)\*\*/g,'$1'),t=t.replace(/\*(.*?)\*/g,'$1'),t=t.replace(/`(.*?)`/g,'$1'),t=t.replace(/\b(FAIL|ERROR|CRITICAL)\b/g,'$1'),t=t.replace(/\b(WARN|WARNING)\b/g,'$1'),t=t.replace(/\b(PASS|SUCCESS|OK)\b/g,'$1'),t}function Ph(t,e="dart",n=globalThis.hljs){if(!t)return"";const i=ci(t);try{return n.highlight(i,{language:e}).value}catch(r){console.warn("Syntax highlighting failed:",r);try{return n.highlight(i,{language:"json"}).value}catch{return Qt(i)}}}function Os(t,e={}){const{highlighter:n=globalThis.hljs}=e;let i='
      ';const r=String(t??"").split(` +`)}let l=null,u,c,d,f,h,p,g,m,v;function E(Y,W){if(!i)return null;const D=i.createShader(Y);return i.shaderSource(D,W),i.compileShader(D),i.getShaderParameter(D,i.COMPILE_STATUS)?D:(window.console&&console.warn("fx-grid shader: "+i.getShaderInfoLog(D)),null)}if(i){const Y=E(i.VERTEX_SHADER,o),W=E(i.FRAGMENT_SHADER,a());if(Y&&W&&(l=i.createProgram(),i.attachShader(l,Y),i.attachShader(l,W),i.linkProgram(l),i.getProgramParameter(l,i.LINK_STATUS)||(window.console&&console.warn("fx-grid link: "+i.getProgramInfoLog(l)),l=null)),l){i.useProgram(l),i.bindBuffer(i.ARRAY_BUFFER,i.createBuffer()),i.bufferData(i.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),i.STATIC_DRAW);const D=i.getAttribLocation(l,"p");i.enableVertexAttribArray(D),i.vertexAttribPointer(D,2,i.FLOAT,!1,0,0),u=i.getUniformLocation(l,"res"),c=i.getUniformLocation(l,"design"),d=i.getUniformLocation(l,"mouse"),f=i.getUniformLocation(l,"energy"),h=i.getUniformLocation(l,"parallax"),p=i.getUniformLocation(l,"t"),g=i.getUniformLocation(l,"ink"),m=i.getUniformLocation(l,"mark"),v=i.getUniformLocation(l,"rot"),i.enable(i.BLEND),i.blendFunc(i.ONE,i.ONE_MINUS_SRC_ALPHA),i.clearColor(0,0,0,0)}else{i=null;const D=t.cloneNode(!1);if(t.parentNode.replaceChild(D,t),t=D,r=t.getContext("2d"),!r)return null}}function S(Y){if(!Y)return null;const W=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(Y);if(W){let D=W[1];return D.length===3&&(D=D[0]+D[0]+D[1]+D[1]+D[2]+D[2]),[parseInt(D.slice(0,2),16)/255,parseInt(D.slice(2,4),16)/255,parseInt(D.slice(4,6),16)/255]}try{const D=document.createElement("canvas");D.width=1,D.height=1;const ue=D.getContext("2d");ue.fillStyle="rgb(9, 8, 7)";const xe=String(ue.fillStyle);ue.fillStyle=Y;const Fe=String(ue.fillStyle);if(Fe===xe)return null;const dt=/^#([0-9a-f]{6})$/i.exec(Fe);if(dt){const ft=dt[1];return[parseInt(ft.slice(0,2),16)/255,parseInt(ft.slice(2,4),16)/255,parseInt(ft.slice(4,6),16)/255]}const Nt=/rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i.exec(Fe);if(Nt)return[Number(Nt[1])/255,Number(Nt[2])/255,Number(Nt[3])/255]}catch{}return null}function _(){let Y="";try{const W=getComputedStyle(document.documentElement);Y=(W.getPropertyValue("--fx-ink")||"").trim()||(W.getPropertyValue("--fg")||"").trim()}catch{}return S(Y)||[.56,.68,.88]}const b=_();let k=1920,T=1080,x=960,F=540,$=960,O=540,L=.66,N=0,K=-1e9,V=!1,M=0,R=0,Z=null,Ce=!1,oe=!1,ye=!1;const $e=64,ae=15.2;let Ie=0,Se=0;const De=.0032,wt=0,ge=.56,Je=.26,bt=.32,mn=.16,Re=.349;let Pe=wt;function $t(){const Y=t.getBoundingClientRect(),W=t.clientWidth,D=t.clientHeight;if(!Y.width||!W||!D)return;const ue=Math.min(window.devicePixelRatio||1,2),xe=Math.max(.2,Math.min(2,Y.width/W*ue)),Fe=Math.max(2,Math.round(W*xe)),dt=Math.max(2,Math.round(D*xe));(Fe!==t.width||dt!==t.height)&&(t.width=Fe,t.height=dt,i&&i.viewport(0,0,Fe,dt)),k=W,T=D,V||(x=$=k/2,F=O=T/2,V=!0)}function Dn(Y){!l||!Ce||!i||(i.uniform2f(u,t.width,t.height),i.uniform2f(c,k,T),i.uniform2f(d,x,F),i.uniform1f(f,L),i.uniform1f(h,N),i.uniform2f(v,Math.cos(Pe),Math.sin(Pe)),i.uniform1f(p,Y),i.uniform3f(g,b[0],b[1],b[2]),i.clear(i.COLOR_BUFFER_BIT),i.drawArrays(i.TRIANGLES,0,3))}function qe(Y,W,D){const ue=Math.max(0,Math.min(1,(D-Y)/(W-Y)));return ue*ue*(3-2*ue)}function jn(Y){if(!Z||!r)return;const W=r;W.setTransform(1,0,0,1,0,0),W.clearRect(0,0,t.width,t.height);const D=t.width/k;W.setTransform(D,0,0,D,0,0),W.globalAlpha=1;const ue=Math.min(k,T),xe=Math.max(64,Math.min(118,ue/10)),Fe=xe*2.9,dt=2*Fe*Fe,Nt=Math.sin(Y*.11)*7,ft=Math.cos(Y*.09)*7-N,fr=x+Nt,hr=F+ft,ro=Fe*Math.sqrt(2*Math.log(1/.06)),vi=ro+De*ro*ro+xe,Tp=Math.floor((fr-vi)/xe)-1,$p=Math.ceil((fr+vi)/xe)+1,Mp=Math.floor((hr-vi)/xe)-1,Lp=Math.ceil((hr+vi)/xe)+1;for(let so=Mp;so<=Lp;so++){const Np=(so+.5)*xe;for(let oo=Tp;oo<=$p;oo++){const ao=(oo+.5)*xe-fr,lo=Np-hr,co=Math.sqrt(ao*ao+lo*lo)+1e-5;if(co>vi)continue;const pr=(-1+Math.sqrt(1+4*De*co))/(2*De),dc=Math.exp(-(pr*pr)/dt),fc=qe(.06,.8,dc)*L*.26;if(fc<.004)continue;const on=xe/(1+2*De*pr)*.26*(.32+1.1*dc),hc=pr/co,uo=fr+ao*hc,fo=hr+lo*hc;uo<-on*1.6||uo>k+on*1.6||fo<-on*1.6||fo>T+on*1.6||(W.globalAlpha=fc,W.save(),W.translate(uo,fo),W.rotate(Pe),W.drawImage(Z,-on,-on,on*2,on*2),W.restore())}}W.globalAlpha=1}function Mt(Y){if(!oe)return;const W=R?Math.min(.05,(Y-R)/1e3):.016;R=Y;const ue=Y-K>2400?.6:1;L+=(ue-L)*Math.min(1,W*3.2);const xe=Math.min(.05,W);Ie+=(($-x)*$e-Ie*ae)*xe,Se+=((O-F)*$e-Se*ae)*xe,x+=Ie*xe,F+=Se*xe,N=(window.scrollY||window.pageYOffset||0)*.55;const Fe=Y/1e3,dt=x/(k||1)-.5,Nt=F/(T||1)-.5;let ft=dt*(dt>=0?ge:Je)+Nt*(Nt>=0?bt:mn);ft>Re?ft=Re:ft<-Re&&(ft=-Re),Pe=wt+ft-N*6e-4,$t(),i?Dn(Fe):jn(Fe),M=requestAnimationFrame(Mt)}function Lt(Y){if(!oe)return;const W=t.getBoundingClientRect();!W.width||!k||!T||($=(Y.clientX-W.left)/W.width*k,O=(Y.clientY-W.top)/W.height*T,K=performance.now())}function ut(){oe||io||e.matches||n.matches||!ye||document.hidden||(oe=!0,R=0,M=requestAnimationFrame(Mt))}function sn(){oe=!1,M&&(cancelAnimationFrame(M),M=0),R=0}function mi(){e.matches?(sn(),t.classList.remove("is-ready")):ye&&ut()}function Un(){n.matches?sn():ye&&ut()}function lc(){document.hidden?sn():ye&&ut()}const cc=new IntersectionObserver(Y=>{ye=Y[0]?.isIntersecting||!1,ye?ut():sn()},{threshold:0});cc.observe(t),window.addEventListener("pointermove",Lt,{passive:!0,capture:!0}),window.addEventListener("resize",$t),e.addEventListener("change",mi),n.addEventListener("change",Un),document.addEventListener("visibilitychange",lc);function Rp(){const Y=(s.match(/\sd="([^"]+)"/)||[])[1],W=document.createElement("canvas");W.width=256,W.height=256;const D=W.getContext("2d");if(Y&&window.Path2D){const ue=Math.min(8.533333333333333,8.421052631578947);D.setTransform(ue,0,0,ue,ue+(256-30*ue)/2,-6.4*ue),D.fillStyle="rgb(255,255,255)",D.fill(new Path2D(Y),"evenodd"),D.setTransform(1,0,0,1,0,0)}try{const ue=D.getImageData(0,0,256,256),xe=ue.data;for(let Fe=3;Feoe}}const sy=120;function oy(t,e,n){return tn?n:t}function de(t,e,n){return oy((t-e)/(n-e),0,1)}function ay(t){return t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2}function Wo(t){return 1-Math.pow(1-t,3)}function Ve(t,e){return e=e===void 0?1.7:e,1+(e+1)*Math.pow(t-1,3)+e*Math.pow(t-1,2)}function Vu(t){return 1-Math.pow(2,-9*t)*Math.cos(t*15)}function te(t,e){if(t<=e[0].t)return e[0].v;for(let n=1;n8.2&&_<9.4&&(s*=1-.07*Math.sin(de(_,8.2,9.4)*Math.PI))}else if(t<53){const _=t-42;g=te(_,[{t:0,v:1},{t:2,v:0},{t:4.2,v:0},{t:4.6,v:1},{t:6.8,v:1},{t:7.4,v:0},{t:9.4,v:0},{t:10.6,v:1}]),p=te(_,[{t:0,v:1},{t:2,v:.3},{t:4.6,v:1,e:Ve}]),d=te(_,[{t:0,v:0},{t:2,v:.3},{t:4.6,v:.16,e:Ve},{t:10.6,v:0}]),h=te(_,[{t:0,v:0},{t:2,v:-40},{t:4.6,v:0,e:Ve}]),o=te(_,[{t:0,v:0},{t:4.6,v:-.12},{t:10.6,v:0}])}else if(t<60){const _=t-53;c=te(_,[{t:0,v:1},{t:.35,v:0},{t:.45,v:0},{t:.7,v:1}]);const b=de(_,.45,2.2);a=b>0?-2.6*(1-Vu(b)):0,g=te(_,[{t:0,v:1},{t:.57,v:0},{t:.67,v:0},{t:.92,v:1}]);const k=de(_,.67,2.42);f=k>0?-2.6*(1-Vu(k)):0,s=1-.05*(Math.sin(de(_,1.9,2.5)*Math.PI)+Math.sin(de(_,2.5,3.1)*Math.PI))}else if(t<74){let b=function(F){return[te(F,[{t:0,v:0},{t:.25,v:1},{t:.5,v:1},{t:.72,v:.14},{t:.82,v:.14},{t:1,v:0}]),te(F,[{t:0,v:0},{t:.08,v:-.62},{t:.25,v:-.62},{t:.33,v:.62},{t:.7,v:.62},{t:.82,v:-.62},{t:1,v:-.62}])]};var S=b;const _=t-60,k=1-de(_,12,14),T=b(de(_,0,12)),x=b(de(_-.5,0,12));n=T[0]*k,i=(T[1]+.05*Math.sin(_*7))*k,o=(x[0]-T[0])*.6*k,a=(x[1]-T[1])*.6*k,h=(x[0]-T[0])*30*k,E=de(_,0,.4)*k}else if(t<85.4){const _=t-74,b=te(_,[{t:0,v:0},{t:4,v:1},{t:8,v:.24},{t:9.6,v:1,e:Ve},{t:11.4,v:0}]);o=b*.5,d=-b*.5,l=te(_,[{t:0,v:0},{t:4,v:6},{t:8,v:20},{t:9.6,v:38,e:Ve},{t:11.4,v:0}]),h=-l*.7,a=te(_,[{t:0,v:0},{t:8,v:0},{t:9.6,v:.4},{t:11.4,v:0}])}else if(t<96.4){const _=t-85.4,b=de(_,0,5.6),k=de(_,5.6,7.6),T=.72*Math.min(1,_/.6)*(1-k);d=Math.cos(b*Math.PI*2)*T,f=Math.sin(b*Math.PI*2)*T*.55,h=b*360*(1-k);const x=te(_,[{t:0,v:0},{t:7.6,v:0},{t:8.2,v:1,e:Wo},{t:8.6,v:.55},{t:9.4,v:0}]);o=-.16*x,d+=.16*x,l=-6*x,h+=6*x,s=1+.05*x,m=1+.9*x}else if(t<108.6){const _=t-96.4,b=de(_,9.6,12.2);n=te(_,[{t:0,v:0},{t:2.1,v:1},{t:4.8,v:.08},{t:7.5,v:1},{t:9.6,v:0}])*(1-b),i=-.35*Math.abs(Math.sin(de(_,0,9.6)*Math.PI*3))*(1-b);const k=Math.sin(_*6.2)*(1-b);u=1+.12*k,p=1-.12*k,l=k*8,h=-k*8,o=.06*k,d=-.06*k,E=de(_,0,.4)*(1-b)}else{const _=t-108.6,b=Math.sin(de(_,0,8)*Math.PI),k=1-de(_,8,11.4);s=1+.04*b*k,i=-.1*b*k,r=2*b*k,m=1+.5*Math.sin(de(_,0,6)*Math.PI),v=1+.1*Math.sin(de(_,0,6)*Math.PI)}return e.x=n,e.y=i,e.rot=r,e.scale=s,e.ax=o,e.ay=a,e.ar=l,e.asc=u,e.afade=c,e.bx=d,e.by=f,e.br=h,e.bsc=p,e.bfade=g,e.hfade=m,e.hsc=v,e.shd=E,e}function ly(t={}){const e=t.arena||document.querySelector(".pipeline-glyph.logo-loop");if(!e)return null;const n=e.querySelector(".loop-mark"),i=e.querySelector(".loop-piece-a"),r=e.querySelector(".loop-piece-b"),s=e.querySelector(".loop-halo"),o=e.querySelector(".loop-shadow");if(!n||!i||!r||!s||!o)return null;const a=t.reducedMotion||window.matchMedia("(prefers-reduced-motion: reduce)"),l=sy;let u=34,c=0,d=0;function f(){u=n.offsetWidth||34,c=Math.max(0,e.offsetWidth-u-4),d=Math.max(0,(e.offsetHeight-u)/2-2),e.style.setProperty("--mark-c",u/2+"px")}function h(M){const R=Math.min(1,Math.max(0,M.x))*c,Z=M.y*d;n.style.transform="translate3d("+R.toFixed(2)+"px,"+Z.toFixed(2)+"px,0) rotate("+M.rot.toFixed(2)+"deg) scale("+M.scale.toFixed(3)+")",i.style.transform="translate3d("+(M.ax*u).toFixed(2)+"px,"+(M.ay*u).toFixed(2)+"px,0) rotate("+M.ar.toFixed(2)+"deg) scale("+M.asc.toFixed(3)+")",i.style.opacity=M.afade.toFixed(3),r.style.transform="translate3d("+(M.bx*u).toFixed(2)+"px,"+(M.by*u).toFixed(2)+"px,0) rotate("+M.br.toFixed(2)+"deg) scale("+M.bsc.toFixed(3)+")",r.style.opacity=M.bfade.toFixed(3),s.style.transform="scale("+M.hsc.toFixed(3)+")",s.style.opacity=(.09*M.hfade).toFixed(3),o.style.transform="translateX("+R.toFixed(2)+"px) scaleX("+(.75+.4*Math.abs(M.x)).toFixed(3)+")",o.style.opacity=(M.shd*.5).toFixed(3)}let p=0,g=0,m=0,v=!1,E=!1,S=!1,_=0;function b(){return S||a.matches||document.hidden||!e.offsetParent?!1:E}function k(M){if(!v)return;if(m=requestAnimationFrame(k),!b()){x();return}const R=g?(M-g)/1e3:0;g=M,p=(p+Math.min(R,.1))%l,_+=1,h(Pi(p))}function T(){v||S||b()&&(v=!0,g=0,m=requestAnimationFrame(k))}function x(){v=!1,m&&(cancelAnimationFrame(m),m=0),g=0}function F(){b()?T():x()}function $(){a.matches?(x(),h(Pi(0))):F()}function O(){f(),v&&h(Pi(p))}function L(){g=0,F()}const N=new IntersectionObserver(M=>{E=M[0]?M[0].isIntersecting:!1,F()},{threshold:0});N.observe(e),window.addEventListener("resize",O),a.addEventListener("change",$),document.addEventListener("visibilitychange",L);function K(){S||(S=!0,x(),N.disconnect(),window.removeEventListener("resize",O),a.removeEventListener("change",$),document.removeEventListener("visibilitychange",L))}window.addEventListener("pagehide",K);function V(M){p=(M%l+l)%l,h(Pi(p))}return f(),h(Pi(0)),F(),{isRunning:()=>v,currentTime:()=>p,frameCount:()=>_,seek:V,dispose:K}}const cy=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function Xt(t){const e=String(t||"").trim().match(cy);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function uy(t,e){if(t.length===0&&e.length===0)return 0;if(t.length===0)return 1;if(e.length===0)return-1;for(let n=0;n0)}function fy(t){const e=Xt(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function Al(t){let e=String(t??"").trim();if((e.startsWith("'")||e.startsWith('"'))&&(e=e.slice(1,-1).trim()),e===""||e==="any"||e==="*")return{min:null,minInclusive:!1,max:null,maxInclusive:!1};if(e.startsWith("^")){const o=e.slice(1).trim();return Xt(o)?{min:o,minInclusive:!0,max:fy(o),maxInclusive:!1}:null}if(Xt(e))return{min:e,minInclusive:!0,max:e,maxInclusive:!0};const n={min:null,minInclusive:!1,max:null,maxInclusive:!1},i=/(>=|<=|>|<)\s*([0-9][0-9A-Za-z.+-]*)/g;let r=!1,s;for(;(s=i.exec(e))!==null;){const[,o,a]=s;if(!Xt(a))return null;r=!0,o===">="||o===">"?(n.min=a,n.minInclusive=o===">="):(n.max=a,n.maxInclusive=o==="<=")}return r?n:null}function Gu(t,e){const n=Al(t);if(!n||!Xt(e))return!1;if(n.min!==null){const i=hs(e,n.min);if(i<0||i===0&&!n.minInclusive)return!1}if(n.max!==null){const i=hs(e,n.max);if(i>0||i===0&&!n.maxInclusive)return!1}return!0}function hy(t,e){const n=Al(t);if(!n||!Xt(e))return!1;if(n.max===null)return!0;const i=hs(n.max,e);return i>0?!0:i===0&&n.maxInclusive}function Vn(t){const e=Al(t);return e?e.min:null}const py="https://pub.dev/api/packages/",gy=8e3;function my(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null}=e,r=Array.isArray(t?.versions)?t.versions:[];let s=null;for(const o of r){const a=o?.version;if(!a||o.retracted||dy(a))continue;const l=o.pubspec?.environment||{};n&&l.sdk&&!Gu(l.sdk,n)||i&&l.flutter&&!Gu(l.flutter,i)||(!s||hs(a,s)>0)&&(s=a)}return s?{version:s,constraint:`^${s}`}:null}async function vy(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null,fetchImpl:r=fetch}=e;let s;try{const a=await r(`${py}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(gy)});if(!a.ok)return{name:t,constraint:null,version:null,error:a.status===404?`"${t}" was not found on pub.dev`:`pub.dev returned ${a.status} for "${t}"`};s=await a.json()}catch(a){return{name:t,constraint:null,version:null,error:`could not reach pub.dev for "${t}" (${a.message})`}}const o=my(s,{dartSdkFloor:n,flutterSdkFloor:i});return o?{name:t,...o,error:null}:{name:t,constraint:null,version:null,error:n?`no published "${t}" release supports Dart ${n}`:`no published "${t}" release could be read`}}async function _y(t,e={}){const n=await Promise.all(t.map(i=>vy(i,e)));return new Map(n.map(({name:i,...r})=>[i,r]))}async function yy(t,e={},n={}){const{resolveVersions:i=_y}=n,r=Object.entries(e).filter(([c])=>c&&c!=="flutter"),s=wh(t),o={dartSdkFloor:Vn(s.sdk),flutterSdkFloor:Vn(s.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(r.length===0)return a;const l=Ms(t),u=[];for(const[c,d]of r){const f=l.get(c);if(!f){u.push(c);continue}const h=Vn(d);if(!h){a.kept.push({name:c,constraint:f.constraint});continue}if(!f.isScalar){a.warnings.push(`"${c}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${h}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:c,constraint:f.constraint});continue}if(hy(f.constraint,h)){a.kept.push({name:c,constraint:f.constraint});continue}a.overrides[c]=`^${h}`,a.warnings.push(`"${c}" was pinned to ${f.constraint} in your project, which cannot resolve the ${h} the generated code needs. Raising it to ^${h} — this changes a dependency the rest of your app also uses.`)}if(u.length>0){const c=await i(u,o);for(const d of u){const f=c.get(d);if(f?.constraint){a.additions[d]=f.constraint;continue}const h=e[d]||"";if(Vn(h)){a.additions[d]=`^${Vn(h)}`,a.warnings.push(`Could not confirm "${d}" version on pub.dev (${f?.error||"lookup failed"}). Using ^${Vn(h)} from the AI's recommendation — verify this is current.`);continue}a.additions[d]=">=0.0.0",a.warnings.push(`Could not determine a version for "${d}" (${f?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const wy={"&":"&","<":"<",">":">",'"':""","'":"'"};function Qt(t){return String(t??"").replace(/[&<>"']/g,e=>wy[e])}function z(t){return t?Qt(t).replace(/\n/g,"
      "):""}function Jt(t){return Qt(t).replace(/\r?\n/g," ")}function Ls(t,e={}){const n=t?.pipelineStep;if(n!=null&&e[n]!=null)return e[n];const i=t?.message||"";return i.includes("Code Generator")?2:i.includes("Code Review")?3:1}function Ah(t){if(!t)return{kind:"generic",title:"Generation failed",message:"An unknown error occurred. Please try again.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1};if(t.isModelArmor){const n=t.code==="MODEL_ARMOR_BLOCKED";return{kind:"safety",title:t.userTitle||"Request blocked for safety",message:t.userMessage||t.message,detail:t.retryExplanation||"",canRetry:!n,canEdit:!0,canUpgrade:!1}}if(t.isUsageLimit)return{kind:"quota",title:"Monthly limit reached",message:t.message||"You've used all your generations for this period.",detail:"",canRetry:!1,canEdit:!1,canUpgrade:!0};const e=t.message||"";return/timed out after/i.test(e)?{kind:"timeout",title:"Request timed out",message:"The generation service took too long to respond.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:/unreachable|failed to fetch|load failed|cors/i.test(e)?{kind:"network",title:"Connection problem",message:"We couldn't reach the generation service. Check your connection and try again.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:{kind:"generic",title:"Generation failed",message:e||"An unexpected error occurred.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1}}function by(t){const e={"Integration Audit Report":"📋","Critical Issues":"❌",Warnings:"⚠️",Recommendations:"✅","Overall Score":"📊"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📄"}function Ey(t){const e={critical:"❌",warning:"⚠️",recommendation:"✅",score:"📊",issue:"🔍",fix:"🔧"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📝"}function Sy(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 ci(t){if(!t)return"";if(typeof t!="string")return String(t);const e=/```(?:\w+)?\n?([\s\S]*?)```/,n=t.match(e);return n?n[1].trim():t.trim()}function Ku(t){return t=Qt(t),t=t.replace(/\*\*(.*?)\*\*/g,'$1'),t=t.replace(/\*(.*?)\*/g,'$1'),t=t.replace(/`(.*?)`/g,'$1'),t=t.replace(/\b(FAIL|ERROR|CRITICAL)\b/g,'$1'),t=t.replace(/\b(WARN|WARNING)\b/g,'$1'),t=t.replace(/\b(PASS|SUCCESS|OK)\b/g,'$1'),t}function Ph(t,e="dart",n=globalThis.hljs){if(!t)return"";const i=ci(t);try{return n.highlight(i,{language:e}).value}catch(r){console.warn("Syntax highlighting failed:",r);try{return n.highlight(i,{language:"json"}).value}catch{return Qt(i)}}}function Ns(t,e={}){const{highlighter:n=globalThis.hljs}=e;let i='
      ';const r=String(t??"").split(` `);let s=!1,o="";for(const a of r){if(a.startsWith("```")){if(s){const l=Sy(o),u=Ph(o.trim(),l,n);i+=`
      ${u}
      `,o="",s=!1}else s=!0;continue}if(s){o+=a+` @@ -78,13 +78,13 @@ in vec2 p; void main(){ gl_Position = vec4(p, 0.0, 1.0); }`;function a(){return[
      ${i}
      - `}const xy=[[/gradient stroke\s*$/i," and an animated percentage label"],[/gauge\s*$/i," with a gradient stroke and animated fill"],[/rating\s*(bar|widget)?\s*$/i," with half-star support and haptic feedback"],[/list\s*$/i," with swipe-to-delete and an undo snackbar"],[/pad\s*$/i," that exports a transparent PNG"],[/carousel\s*$/i," with parallax cards and page indicators"],[/(button|cta)\s*$/i," with a loading spinner and success state"],[/(chart|graph)\s*$/i," that animates from a Firestore stream"],[/action\s*(that|to)?\s*$/i," uploads an image to Firebase Storage and returns the URL"],[/timer\s*$/i," with pause, resume and a completion callback"],[/map\s*$/i," with clustered markers and a custom info window"],[/^a\s+\w*$/i," widget that"],[/(picker|selector)\s*$/i," with search and multi-select"]],Iy=220,ky=6;function Yu(t,e){return!!(t&&t.trim())&&!e}function Cy(t,e=""){if(typeof t!="string"||!t||t===e||t.trim().lengthi.test(t));return n?n[1]:null}function Ay(){let t="",e="";return{get active(){return t},resolve(n){return t=Cy(n,e)??"",t},dismiss(){t=""},accept(n){if(!t)return null;const i=n+t;return e=i,t="",i}}}function Py({onSubmit:t}){const e=document.getElementById("composer"),n=document.getElementById("pipeline-input"),i=document.getElementById("hero-send");if(!e||!n||!i||typeof t!="function")return;const r=e.querySelector(".ghost .typed"),s=e.querySelector(".ghost .suggest"),o=document.getElementById("tab-hint"),a=document.getElementById("suggest-status"),l=Array.from(document.querySelectorAll("#example-chips .chip")),u=document.getElementById("btn-add-images"),c=document.getElementById("prompt-image-input"),d=window.matchMedia("(prefers-reduced-motion: reduce)"),h=Ay();let f=!1,p=!1,g=!1,m=!1,v=null,E=null;function S(){i.disabled=!Yu(n.value,p||g||m)}function _(){r&&(r.textContent=n.value)}function b(){s&&(s.textContent=""),_(),e.classList.remove("has-suggest"),o&&(o.hidden=!0,o.tabIndex=-1),a&&(a.textContent="")}function k(R){s&&(s.textContent=R),_(),e.classList.add("has-suggest"),o&&(o.hidden=!1,o.tabIndex=0,o.setAttribute("aria-label","Accept suggestion: "+R.trim())),a&&(a.textContent="Suggestion: "+R+". Press Tab to accept.")}function T(){h.dismiss(),b()}function x(){if(f||p)return;const R=h.resolve(n.value);R&&k(R)}function F(){clearTimeout(v),!f&&(v=setTimeout(x,Iy))}function $(){const R=h.accept(n.value);return R===null?!1:(n.value=R,b(),S(),!0)}function O(R){p=R,e.classList.toggle("is-busy",R),i.classList.toggle("is-busy",R),i.setAttribute("aria-label",R?"Generating":"Generate"),n.readOnly=R,l.forEach(Z=>{Z.disabled=R}),u&&(u.disabled=R),c&&(c.disabled=R),S()}async function L(){if(Yu(n.value,p||g||m)){T(),O(!0);try{await t()}finally{O(!1)}}}function N(){g=!1,E&&(clearInterval(E),E=null),e.classList.remove("is-demo-typing"),S()}function K(){l.forEach(R=>{R.classList.remove("is-active"),R.setAttribute("aria-pressed","false")})}function V(){try{n.focus({preventScroll:!0}),n.setSelectionRange(n.value.length,n.value.length)}catch{}}function M(R){const Z=R.dataset.prompt||"";if(N(),clearTimeout(v),v=null,T(),l.forEach(oe=>{const ye=oe===R;oe.classList.toggle("is-active",ye),oe.setAttribute("aria-pressed",String(ye))}),d.matches||!Z){n.value=Z,_(),S(),V();return}n.value="",_(),g=!0,S(),e.classList.add("is-demo-typing");let Ce=0;E=setInterval(()=>{Ce+=1,n.value=Z.slice(0,Ce),_(),Ce>=Z.length?(N(),V()):S()},22)}return l.forEach(R=>{R.setAttribute("aria-pressed","false"),R.addEventListener("click",()=>M(R))}),n.addEventListener("keydown",R=>{if(g&&R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!f){R.preventDefault();return}N(),R.key==="Tab"&&!R.shiftKey&&h.active?(R.preventDefault(),$()):R.key==="Escape"?(clearTimeout(v),v=null,T()):R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!f&&(R.preventDefault(),L())}),n.addEventListener("input",()=>{N(),K(),T(),S(),F()}),n.addEventListener("compositionstart",()=>{f=!0}),n.addEventListener("compositionend",()=>{f=!1,T(),S(),F()}),n.addEventListener("scroll",()=>{r&&r.parentNode&&(r.parentNode.scrollTop=n.scrollTop)}),o&&o.addEventListener("click",()=>{$(),n.focus({preventScroll:!0})}),i.addEventListener("click",L),n.addEventListener("pointerdown",()=>{N(),K()}),_(),S(),{setAttachmentsPending(R){m=!!R,S()}}}const Fy="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses";const _t="https://4tgke4.buildship.run",Fh={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},gs="ccc_auth_session",Ba="ccc_signin_return",Ry=1800*1e3,Ju=new WeakSet;let q={email:null,sessionToken:null,isVerified:!1};function Ln(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let ce=Ln({isResolved:!0}),Da=Promise.resolve();const Ty=`${_t}/service/runpipeline`,$y="bs_user_id",My="bs_identity_token",Ly=`${_t}/authUserCheck`;let ht={userId:null,token:null,status:null,resolved:!1};const ms=fv,vs="ccc_subscription",Zu=3,Ny=new Set(["active","trialing","paid"]),_s="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"],Oy={"google/gemini-3.7-flash":"Gemini 3.7 Flash","anthropic/claude-opus-5":"Claude Opus 5","openai/gpt-5.6-sol":"GPT-5.6 Sol","z-ai/glm-5.2":"GLM 5.2","moonshotai/kimi-k3":"Kimi K3","openrouter/auto-beta":"OpenRouter: Auto Router","openrouter/free":"OpenRouter: Free Models","openrouter/deepseek/deepseek-v4-pro":"DeepSeek v4 Pro"};function Gt(t){return Oy[t]||t}const By=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 Rh(t){return By.has(t)}const ja=4,zo=8*1024*1024,Dy="https://4tgke4.buildship.run/service/runpipeline-image";let Oe=[];const pn=[],jy=3e4;let Th=null;function Uy(t){return new Promise(e=>{const n=new FileReader;n.onload=()=>e(n.result),n.onerror=()=>e(null),n.readAsDataURL(t)})}async function Hy(t,e){const n=new FormData;return n.append("file",t),(await fetch(Dy,{method:"POST",body:n,signal:e})).json()}function Wy(t){if(Array.isArray(t)){const e=t[0];if(e&&typeof e=="object")for(const n of Object.keys(e)){if(n==="item"||n==="index")continue;const i=e[n];if(i&&typeof i=="object"){if(typeof i.file=="string")return i.file;if(typeof i.url=="string")return i.url}if(typeof i=="string")return i}return""}return typeof t=="string"?t:t&&typeof t=="object"&&(t.url||t.fileUrl||t.file_url||t.downloadUrl||t.imageUrl||t.image_url||t.file)||""}async function zy(t,e,n){const i=await Uy(t);i&&Oe.includes(e)&&(e.dataUrl=i,cn());let r="";if(i)try{r=Wy(await Hy(t,n))}catch{r=""}return Oe.includes(e)?!i||!r?(Oe.splice(Oe.indexOf(e),1),cn(),"failed"):(e.url=r,cn(),"added"):"dropped"}function $h(t){const e=pn.indexOf(t);e>=0&&pn.splice(e,1),Lh()}function Mh(t){t.controller.abort(),$h(t);const e=Oe.indexOf(t.slot);e>=0&&(Oe.splice(e,1),cn())}function Lh(){Th?.setAttachmentsPending(pn.length>0)}async function qy(t){const e=Array.from(t.target.files||[]);if(!e.length)return;if(t.target.value="",y.isRunning){Ee("Wait for the current generation to finish before attaching images.","info");return}const n=e.filter(u=>u.size>zo);n.length&&Ee(`Skipped ${n.length} image(s) over the ${(zo/1024/1024).toFixed(0)} MB limit.`,"warning");const i=e.filter(u=>u.size<=zo);if(!i.length)return;const r=ja-Oe.length,s=i.slice(0,r);if(i.length>r&&Ee(`You can attach up to ${ja} images.`,"info"),!s.length)return;const o=s.map(u=>{const c={dataUrl:null,name:u.name,url:null};Oe.push(c);const d={slot:c,controller:new AbortController},h=setTimeout(()=>d.controller.abort(),jy);return d.job=zy(u,c,d.controller.signal),pn.push(d),d.job.finally(()=>{clearTimeout(h),$h(d)}),d.job});cn(),Lh();const l=(await Promise.all(o)).filter(u=>u==="failed").length;l&&Ee(`${l} image(s) could not be uploaded and were not attached.`,"error")}function Vy(t){const e=Oe[t],n=pn.find(i=>i.slot===e);if(n){Mh(n);return}Oe.splice(t,1),cn()}function cn(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",Oe.forEach((n,i)=>{const r=document.createElement("div");r.className="prompt-img-thumb"+(n.url?"":" is-pending"),r.innerHTML=(n.dataUrl?`Prompt image`:"")+``,t.appendChild(r)}),e&&(e.textContent=Oe.length>=ja?"Image limit reached":"Add images"))}function Pl(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),n=Rh(e?.value);t.classList.toggle("hidden",!n),!n&&Oe.length&&(pn.slice().forEach(Mh),Oe=[],cn())}const Fn="ccc_usage",Nh="google/gemini-3.7-flash",Oh="google/gemini-3.7-flash",Ar="google/gemini-3.7-flash",Oi={professional:11,power:49},Ua={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 Gy(){const t=new AbortController,e=setTimeout(()=>t.abort(),5e3);try{const n=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:t.signal});if(!n.ok)return;const i=await n.json();if(i.result!=="success"||!i.rates)return;const r=i.rates,s={AUD:1},o=new Set([...Object.keys(Dr),...Object.values(Ha),...Object.values(Ua)]);for(const a of o)a!=="AUD"&&(typeof r[a]=="number"&&r[a]>0?s[a]=r[a]:Dr[a]&&(s[a]=Dr[a]));jr=s}catch{}finally{clearTimeout(e)}}const Ha={"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 Fl(){try{const s=Intl.DateTimeFormat().resolvedOptions().timeZone;if(s&&Ha[s])return Ha[s]}catch{}const e=(navigator.language||"en-US").replace("-","_"),n=Ua[e];if(n)return n;const i=e.split("_")[0],r=Ua[i];return r||"USD"}function Bi(t,e){const n=jr[e]??jr.USD,i=t*n,r=Math.round(i*100)/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:r>=100||r%1===0?0:2}).format(r)}catch{return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(t*jr.USD)}}const gt="ccc_api_key_",Pt="ccc_session_api_key_",Rt="ccc_encryption_key",nr="ccc_encryption_key_scope",Ky="ccc_keystore",ys="keys",ir="ccc_encryption_key_version";let Wa=null,ws=null,rr=!1,bs=!1,Xu=!1;class Es extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function Qu(){if(Xu)return;Xu=!0;const t="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(t),document.body&&Ee(t,"warning")}function Bh(){return localStorage.getItem(ir)||""}function za(){return crypto.randomUUID?.()||jh(crypto.getRandomValues(new Uint8Array(16)))}function Yy(){const t=Bh();if(t)return t;const e=za();return localStorage.setItem(ir,e),e}function ui(){Wa=null,ws=null,rr=!1,bs=!1}window.addEventListener("storage",t=>{t.key===ir&&ui()});function Jy(){return new Promise((t,e)=>{const n=indexedDB.open(Ky,1);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(ys)||i.createObjectStore(ys)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function Rl(t,e){const n=await Jy();return new Promise((i,r)=>{const s=n.transaction(ys,t);let o;try{o=e(s.objectStore(ys))}catch(l){n.close(),r(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>r(o.error),s.oncomplete=()=>{n.close(),i(a)},s.onerror=()=>{n.close(),r(s.error||new Error("Encryption key transaction failed."))},s.onabort=()=>{n.close(),r(s.error||new Error("Encryption key transaction aborted."))}})}function Zy(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function Xy(){const t=await Rl("readonly",e=>e.get(Rt));return Zy(t)?t:null}async function Dh(t){await Rl("readwrite",e=>e.put(t,Rt))}async function Qy(){ui();try{await Rl("readwrite",t=>t.delete(Rt))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function e0(){const t=sessionStorage.getItem(Rt);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Dh(e),sessionStorage.removeItem(Rt),sessionStorage.removeItem(nr),localStorage.removeItem(gt+"salt"),e}async function ed(t){const e=sessionStorage.getItem(Rt);if(e)return bs=sessionStorage.getItem(nr)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new Es;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),i=await crypto.subtle.exportKey("jwk",n);return sessionStorage.setItem(Rt,JSON.stringify(i)),sessionStorage.setItem(nr,"session"),bs=!1,crypto.subtle.importKey("jwk",i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function t0(t){if(sessionStorage.getItem(nr)==="session"&&sessionStorage.getItem(Rt))return Qu(),rr=!0,ed(t);try{const e=await Xy();if(e)return e;const n=await e0();if(n)return n;const i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Dh(i),i}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),Qu(),rr=!0,ed(t)}}async function Tl(t={}){const{allowSessionFallbackCreation:e=!0}=t,n=Yy();ws!==n&&ui();const i=Wa||t0(e);Wa=i,ws=n;try{return await i}catch(r){throw ui(),r}}async function n0(t){const e=await Tl(),n=ws,i=new TextEncoder,r=crypto.getRandomValues(new Uint8Array(12)),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},e,i.encode(t)),o=new Uint8Array(r.length+s.byteLength);return o.set(r),o.set(new Uint8Array(s),r.length),{ciphertext:jh(o),keyVersion:n,sessionFallback:rr}}async function i0(t,e={}){const{isSessionCredential:n=!1}=e;try{const i=await Tl({allowSessionFallbackCreation:!1});if(rr&&!n&&!bs)throw new Es;const r=r0(t),s=r.slice(0,12),o=r.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},i,o);return new TextDecoder().decode(a)}catch(i){if(i instanceof Es)throw i;return console.error("Decryption failed:",i),null}}function jh(t){const e=new Uint8Array(t);let n="";for(let i=0;i0}let Nn="",di="",qi=null,nd=0,nt="not-configured";async function $l(){sessionStorage.getItem(Rt)&&await Tl(),Nn=await Te("flutterflow"),di=await Te("flutterflow_project_id"),f0(),rn(),Nn?Ol():(nt="not-configured",vt())}let sr=!1;function Uh(){const t=document.getElementById("api-keys-modal");We(t),Nl(),Nn&&Bl(Nn)}function Ml(){sr=!1,Uh()}function o0(){sr=!0;const t=document.getElementById("walkthrough-modal");t&&ze(t),Uh()}let id=!1;function rd(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-settings-model");if(!t||!e)return;e.value=t.value;const n=Array.from(t.options);Array.from(e.options).forEach((r,s)=>{const o=n[s];o&&(r.textContent=o.textContent)});const i=document.getElementById("composer-settings-free-notice");i&&(document.getElementById("model-selector-free-notice")?(i.hidden=!1,i.innerHTML='Free plan — Gemini only. '):i.hidden=!0)}function sd(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-image-capability"),n=document.getElementById("composer-image-capability-note");if(!t)return;const i=Gt(t.value),r=Rh(t.value);e&&(e.textContent=r?"Supported":"Not supported"),n&&(n.textContent=r?`${i} accepts reference images you attach to the prompt.`:`Images can't be attached with ${i}. Attached images are removed when you switch to it.`),Pl()}function a0(){if(sr=!1,rd(),sd(),!id){const e=document.getElementById("composer-settings-model");e&&e.addEventListener("change",()=>{const n=document.getElementById("code-generator-model");n.value=e.value,n.dispatchEvent(new Event("change")),rd(),sd()}),id=!0}const t=document.querySelector('.composer [aria-label="Generation settings"]');We("composer-settings-modal",{trigger:t})}function l0(t){t&&t.target!==t.currentTarget||ze("composer-settings-modal")}function Hh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&ze(e);const n=sr;if(sr=!1,n){const i=document.getElementById("walkthrough-modal");i&&(nt==="connected"&&Ll(),We(i))}}let en=1;function Wh(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function Bs(){const t=Wh();t.length&&t.forEach((e,n)=>{const i=n+1;e.classList.remove("wt-current","wt-done","wt-pending");const r=e.querySelector(".wt-step-num");i===en?(e.classList.add("wt-current"),r&&(r.textContent=i)):i0&&en<=t&&(en++,Bs())}function c0(){const t=document.getElementById("walkthrough-modal");t&&(en=1,Bs(),We(t))}function u0(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&ze(e);const n=document.getElementById("walkthrough-dont-show");n&&n.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function zh(){if(q.isVerified&&Tt()&&ce.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(en=1,Bs(),We(e))}}async function Nl(){const t=document.getElementById("flutterflow-api-key-input");Nn?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",d0()}function d0(){od("flutterflow","flutterflow-key-status"),od("flutterflow_project_id","flutterflow-project-status")}function od(t,e){const n=document.getElementById(e);if(!n)return;const i=n.querySelector(".key-status-dot"),r=n.querySelector("span");Ct(t)?(i.className="key-status-dot configured",r.className="text-green-600",r.textContent="User key configured"):(i.className="key-status-dot missing",r.className="text-gray-500",r.textContent="Not configured")}function rn(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff");e&&e.classList.toggle("hidden",!t)}function f0(){const t=document.getElementById("api-keys-status");if(!t)return;const e=t.querySelectorAll(".key-status-dot"),n=["flutterflow"];e.forEach((i,r)=>{const s=n[r];s==="flutterflow"?Ct("flutterflow")&&Ct("flutterflow_project_id")?(i.className="key-status-dot configured",i.title="FlutterFlow (Fully configured)"):Ct("flutterflow")||Ct("flutterflow_project_id")?(i.className="key-status-dot env",i.title="FlutterFlow (Partially configured)"):(i.className="key-status-dot missing",i.title="FlutterFlow (Not configured)"):Ct(s)?(i.className="key-status-dot configured",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (User key)"):(i.className="key-status-dot missing",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (Not configured)")}),rn()}async function h0(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select"),n=t.value.trim();n&&await td("flutterflow",n);const i=e?.value.trim()||"";if(i){if(!Ds(i)){Ee("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await td("flutterflow_project_id",i)}await $l(),n&&await Ol(),Nl();const r=document.querySelector("#api-keys-modal .bg-blue-500"),s=r.textContent;r.textContent="Saved!",r.classList.remove("bg-blue-500","hover:bg-blue-600"),r.classList.add("bg-green-500"),setTimeout(()=>{r.textContent=s,r.classList.remove("bg-green-500"),r.classList.add("bg-blue-500","hover:bg-blue-600"),Hh()},1e3)}async function p0(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(ir,za()),ui(),localStorage.removeItem(gt+"flutterflow"),localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow"),sessionStorage.removeItem(Pt+"flutterflow_project_id"),sessionStorage.removeItem(Rt),sessionStorage.removeItem(nr),localStorage.removeItem(gt+"salt"),await Qy(),localStorage.setItem(ir,za()),localStorage.removeItem(gt+"flutterflow"),localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow"),sessionStorage.removeItem(Pt+"flutterflow_project_id"),await $l();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),Nl()}function Ds(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function vt(){const t=document.getElementById("acct-ff-dot"),e=document.getElementById("acct-ff-status"),n=document.getElementById("acct-ff-endpoint"),i=document.getElementById("acct-ff-project");if(n){const o=yt();n.textContent=o.includes("staging")?"Staging":"Production"}if(i&&(i.textContent=di||"—"),!e)return;let r,s;if(!Ct("flutterflow"))r="Not connected — add your FlutterFlow API key",s="";else switch(nt){case"connected":r="Connected to FlutterFlow",s="ok";break;case"no-projects":r="Key accepted — no projects found",s="warn";break;case"unauthorized":r="API key rejected (401/403) — re-enter your key",s="bad";break;case"network-error":r="Could not reach FlutterFlow — check your network",s="bad";break;default:r="Checking connection…",s="warn";break}e.textContent=r,t&&(t.className=`acct-dot${s?" "+s:""}`)}async function Ol(){const t=await Te("flutterflow");if(!t||!Ct("flutterflow"))return nt="not-configured",vt(),null;nt="validating",vt();try{const n=await new pi(t,"","main",yt()).listProjects();return nt=n&&n.length>0?"connected":"no-projects",vt(),n}catch(e){const n=String(e&&e.message||"");return nt=/(401|403)|denied|unauthorized|scoped|list permission/i.test(n)?"unauthorized":"network-error",vt(),null}}function g0(){di="",localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow_project_id")}function m0(){g0();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML='',t.value=""),Ct("flutterflow")?(nt="validating",Bl(Nn)):nt="not-configured",vt()}function v0(t,e){const n=document.getElementById(t);n&&(n.value?e?n.style.borderColor="#22c55e":n.style.borderColor="#ef4444":n.style.borderColor="")}function _0(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const n=e.target.value.trim().length>0;v0("flutterflow-api-key-input",n)}),t.addEventListener("blur",y0(async e=>{const n=e.target.value.trim();n&&await Bl(n)},500)))}function y0(t,e){let n;return function(...r){const s=()=>{clearTimeout(n),t(...r)};clearTimeout(n),n=setTimeout(s,e)}}async function Bl(t){const e=document.getElementById("flutterflow-projects-select"),n=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',n&&n.classList.add("hidden"),(Ct("flutterflow")||t)&&(nt="validating"),vt();try{const r=await new pi(t,"","main",yt()).listProjects();if(!r||r.length===0){nt="no-projects",vt(),e.innerHTML='';return}nt="connected",vt(),e.innerHTML='',r.forEach(s=>{const o=document.createElement("option");o.value=s.id||s.projectId||"",o.textContent=s.name||s.projectName||`Project ${s.id}`,e.appendChild(o)}),di&&(e.value=di)}catch(i){console.error("Failed to fetch projects:",i);const r=String(i&&i.message||"");nt=/(401|403)|denied|unauthorized|scoped|list permission/i.test(r)?"unauthorized":"network-error",vt(),e.innerHTML='',n&&(n.textContent=`Failed to load projects: ${i.message}`,n.classList.remove("hidden"))}}function w0(t){const e=document.getElementById(t),i=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",i.innerHTML=` + `}const xy=[[/gradient stroke\s*$/i," and an animated percentage label"],[/gauge\s*$/i," with a gradient stroke and animated fill"],[/rating\s*(bar|widget)?\s*$/i," with half-star support and haptic feedback"],[/list\s*$/i," with swipe-to-delete and an undo snackbar"],[/pad\s*$/i," that exports a transparent PNG"],[/carousel\s*$/i," with parallax cards and page indicators"],[/(button|cta)\s*$/i," with a loading spinner and success state"],[/(chart|graph)\s*$/i," that animates from a Firestore stream"],[/action\s*(that|to)?\s*$/i," uploads an image to Firebase Storage and returns the URL"],[/timer\s*$/i," with pause, resume and a completion callback"],[/map\s*$/i," with clustered markers and a custom info window"],[/^a\s+\w*$/i," widget that"],[/(picker|selector)\s*$/i," with search and multi-select"]],Iy=220,ky=6;function Yu(t,e){return!!(t&&t.trim())&&!e}function Cy(t,e=""){if(typeof t!="string"||!t||t===e||t.trim().lengthi.test(t));return n?n[1]:null}function Ay(){let t="",e="";return{get active(){return t},resolve(n){return t=Cy(n,e)??"",t},dismiss(){t=""},accept(n){if(!t)return null;const i=n+t;return e=i,t="",i}}}function Py({onSubmit:t}){const e=document.getElementById("composer"),n=document.getElementById("pipeline-input"),i=document.getElementById("hero-send");if(!e||!n||!i||typeof t!="function")return;const r=e.querySelector(".ghost .typed"),s=e.querySelector(".ghost .suggest"),o=document.getElementById("tab-hint"),a=document.getElementById("suggest-status"),l=Array.from(document.querySelectorAll("#example-chips .chip")),u=document.getElementById("btn-add-images"),c=document.getElementById("prompt-image-input"),d=window.matchMedia("(prefers-reduced-motion: reduce)"),f=Ay();let h=!1,p=!1,g=!1,m=!1,v=null,E=null;function S(){i.disabled=!Yu(n.value,p||g||m)}function _(){r&&(r.textContent=n.value)}function b(){s&&(s.textContent=""),_(),e.classList.remove("has-suggest"),o&&(o.hidden=!0,o.tabIndex=-1),a&&(a.textContent="")}function k(R){s&&(s.textContent=R),_(),e.classList.add("has-suggest"),o&&(o.hidden=!1,o.tabIndex=0,o.setAttribute("aria-label","Accept suggestion: "+R.trim())),a&&(a.textContent="Suggestion: "+R+". Press Tab to accept.")}function T(){f.dismiss(),b()}function x(){if(h||p)return;const R=f.resolve(n.value);R&&k(R)}function F(){clearTimeout(v),!h&&(v=setTimeout(x,Iy))}function $(){const R=f.accept(n.value);return R===null?!1:(n.value=R,b(),S(),!0)}function O(R){p=R,e.classList.toggle("is-busy",R),i.classList.toggle("is-busy",R),i.setAttribute("aria-label",R?"Generating":"Generate"),n.readOnly=R,l.forEach(Z=>{Z.disabled=R}),u&&(u.disabled=R),c&&(c.disabled=R),S()}async function L(){if(Yu(n.value,p||g||m)){T(),O(!0);try{await t()}finally{O(!1)}}}function N(){g=!1,E&&(clearInterval(E),E=null),e.classList.remove("is-demo-typing"),S()}function K(){l.forEach(R=>{R.classList.remove("is-active"),R.setAttribute("aria-pressed","false")})}function V(){try{n.focus({preventScroll:!0}),n.setSelectionRange(n.value.length,n.value.length)}catch{}}function M(R){const Z=R.dataset.prompt||"";if(N(),clearTimeout(v),v=null,T(),l.forEach(oe=>{const ye=oe===R;oe.classList.toggle("is-active",ye),oe.setAttribute("aria-pressed",String(ye))}),d.matches||!Z){n.value=Z,_(),S(),V();return}n.value="",_(),g=!0,S(),e.classList.add("is-demo-typing");let Ce=0;E=setInterval(()=>{Ce+=1,n.value=Z.slice(0,Ce),_(),Ce>=Z.length?(N(),V()):S()},22)}return l.forEach(R=>{R.setAttribute("aria-pressed","false"),R.addEventListener("click",()=>M(R))}),n.addEventListener("keydown",R=>{if(g&&R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!h){R.preventDefault();return}N(),R.key==="Tab"&&!R.shiftKey&&f.active?(R.preventDefault(),$()):R.key==="Escape"?(clearTimeout(v),v=null,T()):R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!h&&(R.preventDefault(),L())}),n.addEventListener("input",()=>{N(),K(),T(),S(),F()}),n.addEventListener("compositionstart",()=>{h=!0}),n.addEventListener("compositionend",()=>{h=!1,T(),S(),F()}),n.addEventListener("scroll",()=>{r&&r.parentNode&&(r.parentNode.scrollTop=n.scrollTop)}),o&&o.addEventListener("click",()=>{$(),n.focus({preventScroll:!0})}),i.addEventListener("click",L),n.addEventListener("pointerdown",()=>{N(),K()}),_(),S(),{setAttachmentsPending(R){m=!!R,S()}}}const Fy="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses";const _t="https://4tgke4.buildship.run",Fh={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},ps="ccc_auth_session",Ba="ccc_signin_return",Ry=1800*1e3,Ju=new WeakSet;let q={email:null,sessionToken:null,isVerified:!1};function Ln(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let ce=Ln({isResolved:!0}),Da=Promise.resolve();const Ty=`${_t}/service/runpipeline`,$y="bs_user_id",My="bs_identity_token",Ly=`${_t}/authUserCheck`;let ht={userId:null,token:null,status:null,resolved:!1};const gs=fv,ms="ccc_subscription",Zu=3,Ny=new Set(["active","trialing","paid"]),vs="google/gemini-3.7-flash",Or=["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"],Oy={"google/gemini-3.7-flash":"Gemini 3.7 Flash","anthropic/claude-opus-5":"Claude Opus 5","openai/gpt-5.6-sol":"GPT-5.6 Sol","z-ai/glm-5.2":"GLM 5.2","moonshotai/kimi-k3":"Kimi K3","openrouter/auto-beta":"OpenRouter: Auto Router","openrouter/free":"OpenRouter: Free Models","openrouter/deepseek/deepseek-v4-pro":"DeepSeek v4 Pro"};function Gt(t){return Oy[t]||t}const By=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 Rh(t){return By.has(t)}const ja=4,zo=8*1024*1024,Dy="https://4tgke4.buildship.run/service/runpipeline-image";let Oe=[];const pn=[],jy=3e4;let Th=null;function Uy(t){return new Promise(e=>{const n=new FileReader;n.onload=()=>e(n.result),n.onerror=()=>e(null),n.readAsDataURL(t)})}async function Hy(t,e){const n=new FormData;return n.append("file",t),(await fetch(Dy,{method:"POST",body:n,signal:e})).json()}function Wy(t){if(Array.isArray(t)){const e=t[0];if(e&&typeof e=="object")for(const n of Object.keys(e)){if(n==="item"||n==="index")continue;const i=e[n];if(i&&typeof i=="object"){if(typeof i.file=="string")return i.file;if(typeof i.url=="string")return i.url}if(typeof i=="string")return i}return""}return typeof t=="string"?t:t&&typeof t=="object"&&(t.url||t.fileUrl||t.file_url||t.downloadUrl||t.imageUrl||t.image_url||t.file)||""}async function zy(t,e,n){const i=await Uy(t);i&&Oe.includes(e)&&(e.dataUrl=i,cn());let r="";if(i)try{r=Wy(await Hy(t,n))}catch{r=""}return Oe.includes(e)?!i||!r?(Oe.splice(Oe.indexOf(e),1),cn(),"failed"):(e.url=r,cn(),"added"):"dropped"}function $h(t){const e=pn.indexOf(t);e>=0&&pn.splice(e,1),Lh()}function Mh(t){t.controller.abort(),$h(t);const e=Oe.indexOf(t.slot);e>=0&&(Oe.splice(e,1),cn())}function Lh(){Th?.setAttachmentsPending(pn.length>0)}async function qy(t){const e=Array.from(t.target.files||[]);if(!e.length)return;if(t.target.value="",y.isRunning){Ee("Wait for the current generation to finish before attaching images.","info");return}const n=e.filter(u=>u.size>zo);n.length&&Ee(`Skipped ${n.length} image(s) over the ${(zo/1024/1024).toFixed(0)} MB limit.`,"warning");const i=e.filter(u=>u.size<=zo);if(!i.length)return;const r=ja-Oe.length,s=i.slice(0,r);if(i.length>r&&Ee(`You can attach up to ${ja} images.`,"info"),!s.length)return;const o=s.map(u=>{const c={dataUrl:null,name:u.name,url:null};Oe.push(c);const d={slot:c,controller:new AbortController},f=setTimeout(()=>d.controller.abort(),jy);return d.job=zy(u,c,d.controller.signal),pn.push(d),d.job.finally(()=>{clearTimeout(f),$h(d)}),d.job});cn(),Lh();const l=(await Promise.all(o)).filter(u=>u==="failed").length;l&&Ee(`${l} image(s) could not be uploaded and were not attached.`,"error")}function Vy(t){const e=Oe[t],n=pn.find(i=>i.slot===e);if(n){Mh(n);return}Oe.splice(t,1),cn()}function cn(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",Oe.forEach((n,i)=>{const r=document.createElement("div");r.className="prompt-img-thumb"+(n.url?"":" is-pending"),r.innerHTML=(n.dataUrl?`Prompt image`:"")+``,t.appendChild(r)}),e&&(e.textContent=Oe.length>=ja?"Image limit reached":"Add images"))}function Pl(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),n=Rh(e?.value);t.classList.toggle("hidden",!n),!n&&Oe.length&&(pn.slice().forEach(Mh),Oe=[],cn())}const Fn="ccc_usage",Nh="google/gemini-3.7-flash",Oh="google/gemini-3.7-flash",Cr="google/gemini-3.7-flash",Oi={professional:11,power:49},Ua={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 Gy(){const t=new AbortController,e=setTimeout(()=>t.abort(),5e3);try{const n=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:t.signal});if(!n.ok)return;const i=await n.json();if(i.result!=="success"||!i.rates)return;const r=i.rates,s={AUD:1},o=new Set([...Object.keys(Br),...Object.values(Ha),...Object.values(Ua)]);for(const a of o)a!=="AUD"&&(typeof r[a]=="number"&&r[a]>0?s[a]=r[a]:Br[a]&&(s[a]=Br[a]));Dr=s}catch{}finally{clearTimeout(e)}}const Ha={"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 Fl(){try{const s=Intl.DateTimeFormat().resolvedOptions().timeZone;if(s&&Ha[s])return Ha[s]}catch{}const e=(navigator.language||"en-US").replace("-","_"),n=Ua[e];if(n)return n;const i=e.split("_")[0],r=Ua[i];return r||"USD"}function Bi(t,e){const n=Dr[e]??Dr.USD,i=t*n,r=Math.round(i*100)/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:r>=100||r%1===0?0:2}).format(r)}catch{return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(t*Dr.USD)}}const gt="ccc_api_key_",Pt="ccc_session_api_key_",Rt="ccc_encryption_key",nr="ccc_encryption_key_scope",Ky="ccc_keystore",_s="keys",ir="ccc_encryption_key_version";let Wa=null,ys=null,rr=!1,ws=!1,Xu=!1;class bs extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function Qu(){if(Xu)return;Xu=!0;const t="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(t),document.body&&Ee(t,"warning")}function Bh(){return localStorage.getItem(ir)||""}function za(){return crypto.randomUUID?.()||jh(crypto.getRandomValues(new Uint8Array(16)))}function Yy(){const t=Bh();if(t)return t;const e=za();return localStorage.setItem(ir,e),e}function ui(){Wa=null,ys=null,rr=!1,ws=!1}window.addEventListener("storage",t=>{t.key===ir&&ui()});function Jy(){return new Promise((t,e)=>{const n=indexedDB.open(Ky,1);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(_s)||i.createObjectStore(_s)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function Rl(t,e){const n=await Jy();return new Promise((i,r)=>{const s=n.transaction(_s,t);let o;try{o=e(s.objectStore(_s))}catch(l){n.close(),r(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>r(o.error),s.oncomplete=()=>{n.close(),i(a)},s.onerror=()=>{n.close(),r(s.error||new Error("Encryption key transaction failed."))},s.onabort=()=>{n.close(),r(s.error||new Error("Encryption key transaction aborted."))}})}function Zy(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function Xy(){const t=await Rl("readonly",e=>e.get(Rt));return Zy(t)?t:null}async function Dh(t){await Rl("readwrite",e=>e.put(t,Rt))}async function Qy(){ui();try{await Rl("readwrite",t=>t.delete(Rt))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function e0(){const t=sessionStorage.getItem(Rt);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Dh(e),sessionStorage.removeItem(Rt),sessionStorage.removeItem(nr),localStorage.removeItem(gt+"salt"),e}async function ed(t){const e=sessionStorage.getItem(Rt);if(e)return ws=sessionStorage.getItem(nr)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new bs;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),i=await crypto.subtle.exportKey("jwk",n);return sessionStorage.setItem(Rt,JSON.stringify(i)),sessionStorage.setItem(nr,"session"),ws=!1,crypto.subtle.importKey("jwk",i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function t0(t){if(sessionStorage.getItem(nr)==="session"&&sessionStorage.getItem(Rt))return Qu(),rr=!0,ed(t);try{const e=await Xy();if(e)return e;const n=await e0();if(n)return n;const i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Dh(i),i}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),Qu(),rr=!0,ed(t)}}async function Tl(t={}){const{allowSessionFallbackCreation:e=!0}=t,n=Yy();ys!==n&&ui();const i=Wa||t0(e);Wa=i,ys=n;try{return await i}catch(r){throw ui(),r}}async function n0(t){const e=await Tl(),n=ys,i=new TextEncoder,r=crypto.getRandomValues(new Uint8Array(12)),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},e,i.encode(t)),o=new Uint8Array(r.length+s.byteLength);return o.set(r),o.set(new Uint8Array(s),r.length),{ciphertext:jh(o),keyVersion:n,sessionFallback:rr}}async function i0(t,e={}){const{isSessionCredential:n=!1}=e;try{const i=await Tl({allowSessionFallbackCreation:!1});if(rr&&!n&&!ws)throw new bs;const r=r0(t),s=r.slice(0,12),o=r.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},i,o);return new TextDecoder().decode(a)}catch(i){if(i instanceof bs)throw i;return console.error("Decryption failed:",i),null}}function jh(t){const e=new Uint8Array(t);let n="";for(let i=0;i0}let Nn="",di="",qi=null,nd=0,nt="not-configured";async function $l(){sessionStorage.getItem(Rt)&&await Tl(),Nn=await Te("flutterflow"),di=await Te("flutterflow_project_id"),f0(),rn(),Nn?Ol():(nt="not-configured",vt())}let sr=!1;function Uh(){const t=document.getElementById("api-keys-modal");We(t),Nl(),Nn&&Bl(Nn)}function Ml(){sr=!1,Uh()}function o0(){sr=!0;const t=document.getElementById("walkthrough-modal");t&&ze(t),Uh()}let id=!1;function rd(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-settings-model");if(!t||!e)return;e.value=t.value;const n=Array.from(t.options);Array.from(e.options).forEach((r,s)=>{const o=n[s];o&&(r.textContent=o.textContent)});const i=document.getElementById("composer-settings-free-notice");i&&(document.getElementById("model-selector-free-notice")?(i.hidden=!1,i.innerHTML='Free plan — Gemini only. '):i.hidden=!0)}function sd(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-image-capability"),n=document.getElementById("composer-image-capability-note");if(!t)return;const i=Gt(t.value),r=Rh(t.value);e&&(e.textContent=r?"Supported":"Not supported"),n&&(n.textContent=r?`${i} accepts reference images you attach to the prompt.`:`Images can't be attached with ${i}. Attached images are removed when you switch to it.`),Pl()}function a0(){if(sr=!1,rd(),sd(),!id){const e=document.getElementById("composer-settings-model");e&&e.addEventListener("change",()=>{const n=document.getElementById("code-generator-model");n.value=e.value,n.dispatchEvent(new Event("change")),rd(),sd()}),id=!0}const t=document.querySelector('.composer [aria-label="Generation settings"]');We("composer-settings-modal",{trigger:t})}function l0(t){t&&t.target!==t.currentTarget||ze("composer-settings-modal")}function Hh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&ze(e);const n=sr;if(sr=!1,n){const i=document.getElementById("walkthrough-modal");i&&(nt==="connected"&&Ll(),We(i))}}let en=1;function Wh(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function Os(){const t=Wh();t.length&&t.forEach((e,n)=>{const i=n+1;e.classList.remove("wt-current","wt-done","wt-pending");const r=e.querySelector(".wt-step-num");i===en?(e.classList.add("wt-current"),r&&(r.textContent=i)):i0&&en<=t&&(en++,Os())}function c0(){const t=document.getElementById("walkthrough-modal");t&&(en=1,Os(),We(t))}function u0(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&ze(e);const n=document.getElementById("walkthrough-dont-show");n&&n.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function zh(){if(q.isVerified&&Tt()&&ce.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(en=1,Os(),We(e))}}async function Nl(){const t=document.getElementById("flutterflow-api-key-input");Nn?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",d0()}function d0(){od("flutterflow","flutterflow-key-status"),od("flutterflow_project_id","flutterflow-project-status")}function od(t,e){const n=document.getElementById(e);if(!n)return;const i=n.querySelector(".key-status-dot"),r=n.querySelector("span");Ct(t)?(i.className="key-status-dot configured",r.className="text-green-600",r.textContent="User key configured"):(i.className="key-status-dot missing",r.className="text-gray-500",r.textContent="Not configured")}function rn(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff");e&&e.classList.toggle("hidden",!t)}function f0(){const t=document.getElementById("api-keys-status");if(!t)return;const e=t.querySelectorAll(".key-status-dot"),n=["flutterflow"];e.forEach((i,r)=>{const s=n[r];s==="flutterflow"?Ct("flutterflow")&&Ct("flutterflow_project_id")?(i.className="key-status-dot configured",i.title="FlutterFlow (Fully configured)"):Ct("flutterflow")||Ct("flutterflow_project_id")?(i.className="key-status-dot env",i.title="FlutterFlow (Partially configured)"):(i.className="key-status-dot missing",i.title="FlutterFlow (Not configured)"):Ct(s)?(i.className="key-status-dot configured",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (User key)"):(i.className="key-status-dot missing",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (Not configured)")}),rn()}async function h0(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select"),n=t.value.trim();n&&await td("flutterflow",n);const i=e?.value.trim()||"";if(i){if(!Bs(i)){Ee("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await td("flutterflow_project_id",i)}await $l(),n&&await Ol(),Nl();const r=document.querySelector("#api-keys-modal .bg-blue-500"),s=r.textContent;r.textContent="Saved!",r.classList.remove("bg-blue-500","hover:bg-blue-600"),r.classList.add("bg-green-500"),setTimeout(()=>{r.textContent=s,r.classList.remove("bg-green-500"),r.classList.add("bg-blue-500","hover:bg-blue-600"),Hh()},1e3)}async function p0(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(ir,za()),ui(),localStorage.removeItem(gt+"flutterflow"),localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow"),sessionStorage.removeItem(Pt+"flutterflow_project_id"),sessionStorage.removeItem(Rt),sessionStorage.removeItem(nr),localStorage.removeItem(gt+"salt"),await Qy(),localStorage.setItem(ir,za()),localStorage.removeItem(gt+"flutterflow"),localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow"),sessionStorage.removeItem(Pt+"flutterflow_project_id"),await $l();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),Nl()}function Bs(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function vt(){const t=document.getElementById("acct-ff-dot"),e=document.getElementById("acct-ff-status"),n=document.getElementById("acct-ff-endpoint"),i=document.getElementById("acct-ff-project");if(n){const o=yt();n.textContent=o.includes("staging")?"Staging":"Production"}if(i&&(i.textContent=di||"—"),!e)return;let r,s;if(!Ct("flutterflow"))r="Not connected — add your FlutterFlow API key",s="";else switch(nt){case"connected":r="Connected to FlutterFlow",s="ok";break;case"no-projects":r="Key accepted — no projects found",s="warn";break;case"unauthorized":r="API key rejected (401/403) — re-enter your key",s="bad";break;case"network-error":r="Could not reach FlutterFlow — check your network",s="bad";break;default:r="Checking connection…",s="warn";break}e.textContent=r,t&&(t.className=`acct-dot${s?" "+s:""}`)}async function Ol(){const t=await Te("flutterflow");if(!t||!Ct("flutterflow"))return nt="not-configured",vt(),null;nt="validating",vt();try{const n=await new pi(t,"","main",yt()).listProjects();return nt=n&&n.length>0?"connected":"no-projects",vt(),n}catch(e){const n=String(e&&e.message||"");return nt=/(401|403)|denied|unauthorized|scoped|list permission/i.test(n)?"unauthorized":"network-error",vt(),null}}function g0(){di="",localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow_project_id")}function m0(){g0();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML='',t.value=""),Ct("flutterflow")?(nt="validating",Bl(Nn)):nt="not-configured",vt()}function v0(t,e){const n=document.getElementById(t);n&&(n.value?e?n.style.borderColor="#22c55e":n.style.borderColor="#ef4444":n.style.borderColor="")}function _0(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const n=e.target.value.trim().length>0;v0("flutterflow-api-key-input",n)}),t.addEventListener("blur",y0(async e=>{const n=e.target.value.trim();n&&await Bl(n)},500)))}function y0(t,e){let n;return function(...r){const s=()=>{clearTimeout(n),t(...r)};clearTimeout(n),n=setTimeout(s,e)}}async function Bl(t){const e=document.getElementById("flutterflow-projects-select"),n=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',n&&n.classList.add("hidden"),(Ct("flutterflow")||t)&&(nt="validating"),vt();try{const r=await new pi(t,"","main",yt()).listProjects();if(!r||r.length===0){nt="no-projects",vt(),e.innerHTML='';return}nt="connected",vt(),e.innerHTML='',r.forEach(s=>{const o=document.createElement("option");o.value=s.id||s.projectId||"",o.textContent=s.name||s.projectName||`Project ${s.id}`,e.appendChild(o)}),di&&(e.value=di)}catch(i){console.error("Failed to fetch projects:",i);const r=String(i&&i.message||"");nt=/(401|403)|denied|unauthorized|scoped|list permission/i.test(r)?"unauthorized":"network-error",vt(),e.innerHTML='',n&&(n.textContent=`Failed to load projects: ${i.message}`,n.classList.remove("hidden"))}}function w0(t){const e=document.getElementById(t),i=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",i.innerHTML=` `):(e.type="password",i.innerHTML=` - `)}let y={step1Result:null,step2Result:null,step3Result:null,bundleSpec:null,artifactBundle:null,bundleReview:null,selectedArtifactId:null,resultsViewMode:"summary",currentStep:0,isRunning:!1,runId:0,submittedPrompt:"",submittedImages:[]};function b0(){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 E0(){y.bundleSpec=er(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function js(){const t=ai(y.bundleSpec);y.artifactBundle=er(y.step2Result,{id:y.bundleSpec?.id,title:y.bundleSpec?.title,description:y.bundleSpec?.description,artifactType:t.artifactType,artifactName:t.artifactName,fileName:t.fileName,dependencies:t.dependencies,relationships:y.bundleSpec?.relationships,code:y.step2Result||""});const e=Gv(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(n=>n.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=ai(y.artifactBundle).id}function Us(){const t=er(y.step3Result,{id:y.artifactBundle?.id,title:y.artifactBundle?.title}),e=new Map(t.artifacts.map(i=>[i.id,i.review])),n=new Map(t.artifacts.filter(i=>{const r=i.review;return r&&typeof r.fixedSource=="string"&&r.fixedSource.trim()}).map(i=>[i.id,i.review.fixedSource.trim()]));y.bundleReview=er({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(i=>{const r=n.get(i.id)||null;return{...i,review:e.get(i.id)||i.review||y.step3Result||null,...r?{fixedCode:r}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function qh(){const t=Dl();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function Dl(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(n=>n.id===y.selectedArtifactId)||ai(t)}function jl(){return Dl().code||y.step2Result||""}async function S0(){try{await $l()}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/"};function x0(t,e){const n=e?.trim()?` (${e.trim().slice(0,200)})`:"";return t===401?`Your FlutterFlow API key was rejected (401 Unauthorized)${n}. Re-enter a current key under API Keys settings, then try again.`:`Listing FlutterFlow projects was denied (403)${n}. The key may be scoped to sync a single project without list permission - verify the key's access in FlutterFlow, re-enter it under API Keys settings, then retry.`}class pi{constructor(e,n,i="main",r=Ur.production){this.apiKey=e,this.baseUrl=r,this._projectId=n,this._branchName=i,this._endpoint=r}get projectId(){return this._projectId}get branchName(){return this._branchName==="main"?"":this._branchName}async exportProjectZip(){console.log(`Exporting code from FlutterFlow project: ${this.projectId}, branch: ${this.branchName||"main"}`);const e=[{project:{path:`projects/${this.projectId}`},...this.branchName?{branch_name:this.branchName}:{},export_as_module:!1,include_assets_map:!1,format:!1,export_as_debug:!1},{project_id:this.projectId,branch_name:this.branchName,include_assets:!1,export_as_module:!1}];let n=null;for(const i of e)try{const r=await fetch(`${this.baseUrl}exportCode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(i)});if(!r.ok){const a=await r.text();n=new Error(`Export failed: ${r.status} - ${a}`);continue}const s=await r.json(),o=s?.value?.project_zip||s?.project_zip;if(!o){n=new Error("Export response did not include project source.");continue}return o}catch(r){n=r}throw n||new Error("Export failed for an unknown reason.")}async fetchProjectSource(){const e=await this.exportProjectZip(),n=await JSZip.loadAsync(e,{base64:!0}),i=Object.keys(n.files).filter(a=>!n.files[a].dir&&(a==="pubspec.yaml"||a.endsWith("/pubspec.yaml"))).sort((a,l)=>a.split("/").length-l.split("/").length)[0];if(!i)throw new Error("Export did not contain a pubspec.yaml.");const r=i.slice(0,i.length-12),s=new Map,o=Object.keys(n.files).filter(a=>{if(n.files[a].dir||!a.startsWith(r))return!1;const l=a.slice(r.length);return l==="lib/flutter_flow/custom_functions.dart"||l.startsWith("lib/custom_code/")&&l.endsWith(".dart")});return await Promise.all(o.map(async a=>{s.set(a.slice(r.length),await n.files[a].async("string"))})),{pubspecYaml:await n.files[i].async("string"),files:s}}async pushCodeWithRetry(e,n=3,i=null){const r=[Ur.production,Ur.staging],s=Math.max(0,r.indexOf(this._endpoint));let o=!1,a=null;for(let l=0;lsetTimeout(p,1e3*(l+1)));continue}if(d.ok)return console.log(`Push to ${c} succeeded!`),d;a=d.status;const h=d.status<500&&!o;if(qa(h?d.clone():d,Ih).then(f=>console.log(`Push to ${c} returned ${d.status}: ${f}`),()=>console.log(`Push to ${c} returned ${d.status} (unreadable response body)`)),d.status>=500&&(o=!0),d.status===500){console.warn(`Endpoint ${c} returned 500, trying next...`),await new Promise(f=>setTimeout(f,1e3*(l+1)));continue}if(d.status>=500)throw new Qe(`FlutterFlow reported a server error (HTTP ${d.status}), which cannot prove the push was refused — the write may have been applied before the failure. Open your FlutterFlow project to reconcile before retrying.`);if(o)throw new Qe(`The push was refused (HTTP ${d.status}), but an earlier sync attempt may already have applied it — server errors and dropped responses cannot prove a refusal. Open your FlutterFlow project to reconcile before retrying.`);return d}throw zu({httpStatus:a})}async pushCode(e,n=null){return this.pushCodeWithRetry(e,3,n)}parseProjectsResponse(e){if(e?.success&&typeof e.value=="string")try{const i=JSON.parse(e.value);if(i&&Array.isArray(i.entries))return i.entries.map(r=>({id:r.id,name:r.project?.name||r.id}))}catch(i){console.error("Failed to parse stringified project value:",i)}const n=e?.projects||e?.items||e?.entries||(Array.isArray(e)?e:[]);return Array.isArray(n)?n:[]}async listProjects(){console.log("Listing projects for API key");const e=[`${this.baseUrl}listProjects`,"https://api.flutterflow.io/v2/l/listProjects"];let n=0,i="";for(const r of e){const s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({project_type:"ALL",deserialize_response:!0})});if(s.ok)return r!==e[0]&&console.log(`listProjects answered on legacy path ${r}`),this.parseProjectsResponse(await s.json());if(n=s.status,i=await s.text(),console.warn(`listProjects via ${r} returned ${n}: ${i}`),s.status===401||s.status===403)throw new Error(x0(s.status,i));if(s.status!==404)throw new Error(`List projects failed: ${s.status} - ${i}`)}throw new Error(`List projects failed: ${n} - ${i}`)}}function qa(t,e){const n=t.body?.getReader?.(),i=n?(async()=>{const r=new TextDecoder;let s="";for(;;){const{done:o,value:a}=await n.read();if(o)break;s+=r.decode(a,{stream:!0})}return s+r.decode()})():Promise.resolve("");return Wl(i,e,(r,s)=>{try{n?.cancel()?.catch?.(()=>{})}catch{}s(new Error("The response body stalled before it finished."))})}async function I0(t,e=Ih){const n=t.clone();let i;try{i=JSON.parse(await qa(t,e))}catch{let o="";try{o=await qa(n,e)}catch{}if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:o||`HTTP ${t.status}`,errorMap:new Map};throw new Qe(`FlutterFlow accepted the sync but returned an unreadable response${o?`: ${o.slice(0,200)}`:"."}`)}if(!t.ok){let s=i.message||`HTTP ${t.status}`,o=new Map;if(i.errors)o=new Map(Object.entries(i.errors));else if(!i.message&&typeof i=="object"){const a=Object.keys(i).filter(l=>l.endsWith(".dart")&&Array.isArray(i[l]));a.length>0&&(o=new Map(Object.entries(i)),s=a.flatMap(u=>i[u].map(c=>`${u}: ${c.errorMessage}`)).join(` -`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:s,errorMap:o}}let r={};if(i.value)try{r=typeof i.value=="string"?JSON.parse(i.value):i.value}catch(s){console.warn("Ignoring malformed push response value:",s)}return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(r))}}function Ul(t,e){return{401:"Authentication failed. Please check your FlutterFlow API key.",403:"Access denied. You may not have permission to modify this project.",404:"Project not found. Please check your Project ID.",409:"Conflict detected. The project may have been modified elsewhere.",422:"Validation failed: Invalid request format",429:"Rate limit exceeded. Please try again in a few minutes.",500:"FlutterFlow server error. Please try again later.",503:"FlutterFlow service temporarily unavailable."}[t]||`FlutterFlow API error: ${`HTTP ${t}`}`}const J={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},Vh=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,Gh=/extends\s+State<\w+>/;function k0(t,e=""){if(t==="pubspec.yaml")return J.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return J.OTHER;if(t==="custom_functions.dart")return J.FUNCTION;if(e){const n=Vh.test(e),i=Gh.test(e);if(n||i)return J.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return J.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return J.FUNCTION}return J.CODE_FILE}function Kh(t,e){switch(e){case J.ACTION:return`lib/custom_code/actions/${t}`;case J.WIDGET:return`lib/custom_code/widgets/${t}`;case J.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case J.CODE_FILE:return`lib/custom_code/${t}`;case J.DEPENDENCIES:return"pubspec.yaml";case J.OTHER:return`lib/custom_code/${t}`;default:return t}}async function Hl(t,e=new Map){return Pv(t,e)}const Va=new Map,Rn=new Map;function or(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function ar(t){Va.delete(or(t))}function C0(t,e){const n=or(t),i=Rn.get(n)??new Set;for(const r of e)i.add(r);Rn.set(n,i)}function A0(t,e){const n=Rn.get(or(t));if(n){for(const i of e)n.delete(i);n.size===0&&Rn.delete(or(t))}}function Wl(t,e,n){return new Promise((i,r)=>{let s=!1;const o=(l,u,c)=>{s||(s=!0,c==="resolve"?i(u):r(u))},a=setTimeout(()=>{s||(s=!0,n(i,r))},e);t.then(l=>{clearTimeout(a),o(i,l,"resolve")},l=>{clearTimeout(a),o(r,l,"reject")})})}async function zl(t,e,n=xh){const i={stop:!1};return Wl((async()=>{const r=await t.pushCode(e,i);return I0(r)})(),n,(r,s)=>{i.stop=!0,s(new Qe("FlutterFlow did not answer the sync in time — the push may still have been applied. The outcome is not yet known: open your FlutterFlow project to reconcile before retrying the deploy."))})}async function ql(t,e,n,i,r="",s=xh){const o=a_(e,n);if(o.length===0)return{remoteFiles:n,syncFileMap:e,unverified:[],approximate:[]};const a=Q_(o,r),l={...a.manifest,sources:a.sources},u=a.skipped.map(f=>f.reason);u.forEach(f=>console.warn(`[custom class deploy] ${f}`));const c=a.approximate;c.forEach(f=>console.warn(`[custom class deploy] ${f}`)),console.log(`Provisioning ${o.length} new FlutterFlow custom code file(s) before sync.`),Be.set("provision");let d=!0,h;try{const f=(async()=>{let p;try{p=await fetch(Fy,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:i,customClasses:o,verification:l,stream:!0})})}catch{throw new Qe("The provisioning request did not return a response. The deploy may have reached the FlutterFlow server — open your FlutterFlow project to reconcile before retrying.")}return ty(p,{onPhase:g=>{d&&Be.setSubstatus(g)},onLog:g=>{d&&console.log(`[custom class deploy] ${g}`)}})})();if(h=await Wl(f,s,(p,g)=>{d=!1,g(new Qe("The deploy is still working on the FlutterFlow server, but this browser tab has stopped waiting. Your custom classes may or may not have been written — the outcome is not yet known. Open your FlutterFlow project to reconcile before retrying the deploy."))}),!h.finalResultReceived)throw qu(h)===Le.FAILED?new Error(h.error||`FlutterFlow custom class provisioning failed (HTTP ${h.httpStatus}).`):new Qe("The connection to the FlutterFlow deploy runner dropped before it reported a result. The deploy may still be finishing on the server; open your FlutterFlow project to reconcile before retrying.");if(!h.success){const p=h.details?` ${h.details}`:"",g=`${h.error||"FlutterFlow custom class provisioning failed."}${p}`;throw qu(h)===Le.UNCONFIRMED?new Qe(`${g} The failure arrived after the deploy began — custom classes may already be written. Open your FlutterFlow project to reconcile before retrying.`):new Error(g)}}catch(f){throw f instanceof Qe&&(ar(t),C0(t,o.map(p=>p.path))),f}return ar(t),A0(t,o.map(f=>f.path)),h.verificationSkipped&&(console.warn(`[custom class deploy] ${h.verificationSkipped}`),u.push(h.verificationSkipped)),{remoteFiles:n,syncFileMap:l_(e,o),unverified:u,approximate:c,provisionSucceeded:!0}}async function Vl(t,e={}){const n=or(t);let i=Va.get(n);if(i===void 0){try{i=await t.fetchProjectSource()}catch(u){throw new Error(`Could not read your project's pubspec.yaml (${u.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=Eh(i.pubspecYaml);if(!a.valid)throw new Error(`Your project's pubspec.yaml could not be read reliably (${a.errors.join("; ")}). Deploy was stopped so your existing package dependencies aren't overwritten.`);const l=Rn.get(n);if(l){for(const u of[...l])i.files.has(u)&&l.delete(u);l.size===0&&Rn.delete(n)}Rn.has(n)||Va.set(n,i)}const r=await yy(i.pubspecYaml,e),s=K_(i.pubspecYaml,r.overrides),o=G_(s.yaml,r.additions);return r.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>`${a}: ${r.additions[a]||"any"}`).join(", "),r.sdk.dartSdkFloor?`(resolved for Dart ${r.sdk.dartSdkFloor})`:""),r.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:s.overridden,warnings:r.warnings,remoteFiles:i.files}}function P0(t){const e=[],n=[];t.content.length>5e4&&n.push("Code file is large (>50KB). This may take longer to commit."),t.content.length>1e5&&e.push("Code file is too large (>100KB). Consider splitting into smaller components.");const i=t.content.split(` + `)}let y={step1Result:null,step2Result:null,step3Result:null,bundleSpec:null,artifactBundle:null,bundleReview:null,selectedArtifactId:null,resultsViewMode:"summary",currentStep:0,isRunning:!1,runId:0,submittedPrompt:"",submittedImages:[]};function b0(){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 E0(){y.bundleSpec=er(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function Ds(){const t=ai(y.bundleSpec);y.artifactBundle=er(y.step2Result,{id:y.bundleSpec?.id,title:y.bundleSpec?.title,description:y.bundleSpec?.description,artifactType:t.artifactType,artifactName:t.artifactName,fileName:t.fileName,dependencies:t.dependencies,relationships:y.bundleSpec?.relationships,code:y.step2Result||""});const e=Gv(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(n=>n.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=ai(y.artifactBundle).id}function js(){const t=er(y.step3Result,{id:y.artifactBundle?.id,title:y.artifactBundle?.title}),e=new Map(t.artifacts.map(i=>[i.id,i.review])),n=new Map(t.artifacts.filter(i=>{const r=i.review;return r&&typeof r.fixedSource=="string"&&r.fixedSource.trim()}).map(i=>[i.id,i.review.fixedSource.trim()]));y.bundleReview=er({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(i=>{const r=n.get(i.id)||null;return{...i,review:e.get(i.id)||i.review||y.step3Result||null,...r?{fixedCode:r}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function qh(){const t=Dl();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function Dl(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(n=>n.id===y.selectedArtifactId)||ai(t)}function jl(){return Dl().code||y.step2Result||""}async function S0(){try{await $l()}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/"};function x0(t,e){const n=e?.trim()?` (${e.trim().slice(0,200)})`:"";return t===401?`Your FlutterFlow API key was rejected (401 Unauthorized)${n}. Re-enter a current key under API Keys settings, then try again.`:`Listing FlutterFlow projects was denied (403)${n}. The key may be scoped to sync a single project without list permission - verify the key's access in FlutterFlow, re-enter it under API Keys settings, then retry.`}class pi{constructor(e,n,i="main",r=jr.production){this.apiKey=e,this.baseUrl=r,this._projectId=n,this._branchName=i,this._endpoint=r}get projectId(){return this._projectId}get branchName(){return this._branchName==="main"?"":this._branchName}async exportProjectZip(){console.log(`Exporting code from FlutterFlow project: ${this.projectId}, branch: ${this.branchName||"main"}`);const e=[{project:{path:`projects/${this.projectId}`},...this.branchName?{branch_name:this.branchName}:{},export_as_module:!1,include_assets_map:!1,format:!1,export_as_debug:!1},{project_id:this.projectId,branch_name:this.branchName,include_assets:!1,export_as_module:!1}];let n=null;for(const i of e)try{const r=await fetch(`${this.baseUrl}exportCode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(i)});if(!r.ok){const a=await r.text();n=new Error(`Export failed: ${r.status} - ${a}`);continue}const s=await r.json(),o=s?.value?.project_zip||s?.project_zip;if(!o){n=new Error("Export response did not include project source.");continue}return o}catch(r){n=r}throw n||new Error("Export failed for an unknown reason.")}async fetchProjectSource(){const e=await this.exportProjectZip(),n=await JSZip.loadAsync(e,{base64:!0}),i=Object.keys(n.files).filter(a=>!n.files[a].dir&&(a==="pubspec.yaml"||a.endsWith("/pubspec.yaml"))).sort((a,l)=>a.split("/").length-l.split("/").length)[0];if(!i)throw new Error("Export did not contain a pubspec.yaml.");const r=i.slice(0,i.length-12),s=new Map,o=Object.keys(n.files).filter(a=>{if(n.files[a].dir||!a.startsWith(r))return!1;const l=a.slice(r.length);return l==="lib/flutter_flow/custom_functions.dart"||l.startsWith("lib/custom_code/")&&l.endsWith(".dart")});return await Promise.all(o.map(async a=>{s.set(a.slice(r.length),await n.files[a].async("string"))})),{pubspecYaml:await n.files[i].async("string"),files:s}}async pushCodeWithRetry(e,n=3,i=null){const r=[jr.production,jr.staging],s=Math.max(0,r.indexOf(this._endpoint));let o=!1,a=null;for(let l=0;lsetTimeout(p,1e3*(l+1)));continue}if(d.ok)return console.log(`Push to ${c} succeeded!`),d;a=d.status;const f=d.status<500&&!o;if(qa(f?d.clone():d,Ih).then(h=>console.log(`Push to ${c} returned ${d.status}: ${h}`),()=>console.log(`Push to ${c} returned ${d.status} (unreadable response body)`)),d.status>=500&&(o=!0),d.status===500){console.warn(`Endpoint ${c} returned 500, trying next...`),await new Promise(h=>setTimeout(h,1e3*(l+1)));continue}if(d.status>=500)throw new Qe(`FlutterFlow reported a server error (HTTP ${d.status}), which cannot prove the push was refused — the write may have been applied before the failure. Open your FlutterFlow project to reconcile before retrying.`);if(o)throw new Qe(`The push was refused (HTTP ${d.status}), but an earlier sync attempt may already have applied it — server errors and dropped responses cannot prove a refusal. Open your FlutterFlow project to reconcile before retrying.`);return d}throw zu({httpStatus:a})}async pushCode(e,n=null){return this.pushCodeWithRetry(e,3,n)}parseProjectsResponse(e){if(e?.success&&typeof e.value=="string")try{const i=JSON.parse(e.value);if(i&&Array.isArray(i.entries))return i.entries.map(r=>({id:r.id,name:r.project?.name||r.id}))}catch(i){console.error("Failed to parse stringified project value:",i)}const n=e?.projects||e?.items||e?.entries||(Array.isArray(e)?e:[]);return Array.isArray(n)?n:[]}async listProjects(){console.log("Listing projects for API key");const e=[`${this.baseUrl}listProjects`,"https://api.flutterflow.io/v2/l/listProjects"];let n=0,i="";for(const r of e){const s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({project_type:"ALL",deserialize_response:!0})});if(s.ok)return r!==e[0]&&console.log(`listProjects answered on legacy path ${r}`),this.parseProjectsResponse(await s.json());if(n=s.status,i=await s.text(),console.warn(`listProjects via ${r} returned ${n}: ${i}`),s.status===401||s.status===403)throw new Error(x0(s.status,i));if(s.status!==404)throw new Error(`List projects failed: ${s.status} - ${i}`)}throw new Error(`List projects failed: ${n} - ${i}`)}}function qa(t,e){const n=t.body?.getReader?.(),i=n?(async()=>{const r=new TextDecoder;let s="";for(;;){const{done:o,value:a}=await n.read();if(o)break;s+=r.decode(a,{stream:!0})}return s+r.decode()})():Promise.resolve("");return Wl(i,e,(r,s)=>{try{n?.cancel()?.catch?.(()=>{})}catch{}s(new Error("The response body stalled before it finished."))})}async function I0(t,e=Ih){const n=t.clone();let i;try{i=JSON.parse(await qa(t,e))}catch{let o="";try{o=await qa(n,e)}catch{}if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:o||`HTTP ${t.status}`,errorMap:new Map};throw new Qe(`FlutterFlow accepted the sync but returned an unreadable response${o?`: ${o.slice(0,200)}`:"."}`)}if(!t.ok){let s=i.message||`HTTP ${t.status}`,o=new Map;if(i.errors)o=new Map(Object.entries(i.errors));else if(!i.message&&typeof i=="object"){const a=Object.keys(i).filter(l=>l.endsWith(".dart")&&Array.isArray(i[l]));a.length>0&&(o=new Map(Object.entries(i)),s=a.flatMap(u=>i[u].map(c=>`${u}: ${c.errorMessage}`)).join(` +`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:s,errorMap:o}}let r={};if(i.value)try{r=typeof i.value=="string"?JSON.parse(i.value):i.value}catch(s){console.warn("Ignoring malformed push response value:",s)}return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(r))}}function Ul(t,e){return{401:"Authentication failed. Please check your FlutterFlow API key.",403:"Access denied. You may not have permission to modify this project.",404:"Project not found. Please check your Project ID.",409:"Conflict detected. The project may have been modified elsewhere.",422:"Validation failed: Invalid request format",429:"Rate limit exceeded. Please try again in a few minutes.",500:"FlutterFlow server error. Please try again later.",503:"FlutterFlow service temporarily unavailable."}[t]||`FlutterFlow API error: ${`HTTP ${t}`}`}const J={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},Vh=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,Gh=/extends\s+State<\w+>/;function k0(t,e=""){if(t==="pubspec.yaml")return J.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return J.OTHER;if(t==="custom_functions.dart")return J.FUNCTION;if(e){const n=Vh.test(e),i=Gh.test(e);if(n||i)return J.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return J.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return J.FUNCTION}return J.CODE_FILE}function Kh(t,e){switch(e){case J.ACTION:return`lib/custom_code/actions/${t}`;case J.WIDGET:return`lib/custom_code/widgets/${t}`;case J.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case J.CODE_FILE:return`lib/custom_code/${t}`;case J.DEPENDENCIES:return"pubspec.yaml";case J.OTHER:return`lib/custom_code/${t}`;default:return t}}async function Hl(t,e=new Map){return Pv(t,e)}const Va=new Map,Rn=new Map;function Us(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function or(t){Va.delete(Us(t))}function C0(t,e){const n=Us(t),i=Rn.get(n)??new Map;for(const{path:r,content:s}of e){const o=i.get(r)??new Set;o.add(s),i.set(r,o)}Rn.set(n,i)}function A0(t,e){const n=Us(t),i=Rn.get(n);if(i){for(const{path:r,content:s}of e){const o=i.get(r);o&&(o.delete(s),o.size===0&&i.delete(r))}i.size===0&&Rn.delete(n)}}function Wl(t,e,n){return new Promise((i,r)=>{let s=!1;const o=(l,u,c)=>{s||(s=!0,c==="resolve"?i(u):r(u))},a=setTimeout(()=>{s||(s=!0,n(i,r))},e);t.then(l=>{clearTimeout(a),o(i,l,"resolve")},l=>{clearTimeout(a),o(r,l,"reject")})})}async function zl(t,e,n=xh){const i={stop:!1};return Wl((async()=>{const r=await t.pushCode(e,i);return I0(r)})(),n,(r,s)=>{i.stop=!0,s(new Qe("FlutterFlow did not answer the sync in time — the push may still have been applied. The outcome is not yet known: open your FlutterFlow project to reconcile before retrying the deploy."))})}async function ql(t,e,n,i,r="",s=xh){const o=a_(e,n);if(o.length===0)return{remoteFiles:n,syncFileMap:e,unverified:[],approximate:[]};const a=Q_(o,r),l={...a.manifest,sources:a.sources},u=a.skipped.map(h=>h.reason);u.forEach(h=>console.warn(`[custom class deploy] ${h}`));const c=a.approximate;c.forEach(h=>console.warn(`[custom class deploy] ${h}`)),console.log(`Provisioning ${o.length} new FlutterFlow custom code file(s) before sync.`),Be.set("provision");let d=!0,f;try{const h=(async()=>{let p;try{p=await fetch(Fy,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:i,customClasses:o,verification:l,stream:!0})})}catch{throw new Qe("The provisioning request did not return a response. The deploy may have reached the FlutterFlow server — open your FlutterFlow project to reconcile before retrying.")}return ty(p,{onPhase:g=>{d&&Be.setSubstatus(g)},onLog:g=>{d&&console.log(`[custom class deploy] ${g}`)}})})();if(f=await Wl(h,s,(p,g)=>{d=!1,g(new Qe("The deploy is still working on the FlutterFlow server, but this browser tab has stopped waiting. Your custom classes may or may not have been written — the outcome is not yet known. Open your FlutterFlow project to reconcile before retrying the deploy."))}),!f.finalResultReceived)throw qu(f)===Le.FAILED?new Error(f.error||`FlutterFlow custom class provisioning failed (HTTP ${f.httpStatus}).`):new Qe("The connection to the FlutterFlow deploy runner dropped before it reported a result. The deploy may still be finishing on the server; open your FlutterFlow project to reconcile before retrying.");if(!f.success){const p=f.details?` ${f.details}`:"",g=`${f.error||"FlutterFlow custom class provisioning failed."}${p}`;throw qu(f)===Le.UNCONFIRMED?new Qe(`${g} The failure arrived after the deploy began — custom classes may already be written. Open your FlutterFlow project to reconcile before retrying.`):new Error(g)}}catch(h){throw h instanceof Qe&&(or(t),C0(t,o)),h}return or(t),A0(t,o),f.verificationSkipped&&(console.warn(`[custom class deploy] ${f.verificationSkipped}`),u.push(f.verificationSkipped)),{remoteFiles:n,syncFileMap:l_(e,o),unverified:u,approximate:c,provisionSucceeded:!0}}async function Vl(t,e={}){const n=Us(t);let i=Va.get(n);if(i===void 0){try{i=await t.fetchProjectSource()}catch(u){throw new Error(`Could not read your project's pubspec.yaml (${u.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=Eh(i.pubspecYaml);if(!a.valid)throw new Error(`Your project's pubspec.yaml could not be read reliably (${a.errors.join("; ")}). Deploy was stopped so your existing package dependencies aren't overwritten.`);const l=Rn.get(n);if(l){for(const[u,c]of[...l]){const d=i.files.get(u);d!==void 0&&c.delete(d),c.size===0&&l.delete(u)}l.size===0&&Rn.delete(n)}Rn.has(n)||Va.set(n,i)}const r=await yy(i.pubspecYaml,e),s=K_(i.pubspecYaml,r.overrides),o=G_(s.yaml,r.additions);return r.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>`${a}: ${r.additions[a]||"any"}`).join(", "),r.sdk.dartSdkFloor?`(resolved for Dart ${r.sdk.dartSdkFloor})`:""),r.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:s.overridden,warnings:r.warnings,remoteFiles:i.files}}function P0(t){const e=[],n=[];t.content.length>5e4&&n.push("Code file is large (>50KB). This may take longer to commit."),t.content.length>1e5&&e.push("Code file is too large (>100KB). Consider splitting into smaller components.");const i=t.content.split(` `).length;i>500&&n.push(`Code has ${i} lines. Consider breaking it into smaller widgets.`),t.content.includes("setState")&&t.codeType===J.ACTION&&n.push("Using setState in a Custom Action may not work as expected. Consider using a Custom Widget."),t.content.includes("dynamic")&&!t.content.includes("?")&&n.push('Code uses "dynamic" types. Consider adding explicit types for better null safety.'),t.content.match(/Color\(0xFF[0-9A-Fa-f]{6}\)/)&&n.push("Code contains hardcoded colors. Consider using FlutterFlowTheme.of(context) for theme consistency.");const r=t.content.match(/print\s*\(/g);r&&r.length>3&&n.push(`Code contains ${r.length} print statements. Consider removing debug prints before committing.`);const s=k_(t.content);if(s&&e.push(`FlutterFlow cannot format this code - ${s}. Fix or regenerate before committing.`),t.codeType===J.WIDGET){const o=hh(t.content),a=S_(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=`${ph(o[0])}`;e.push(`Widget class name "${o[0]}" does not match the file name "${t.fileName}". FlutterFlow derives the widget from the file name, so it will report "No widget ${a} found". Rename the file to "${l}" or the class to match before committing.`)}}return{canProceed:e.length===0,issues:e,warnings:n}}function Yh(t,e={}){const{artifactType:n="CustomWidget",artifactName:i="GeneratedCode",fileName:r}=e,s=b_(t);let o=r||i;if(n==="CustomFunction")o="custom_functions.dart";else if(n==="CustomWidget"){const u=hh(s)[0],c=u?ph(u):null;c&&o!==c?(console.warn(`Commit file name "${o}" does not match declared widget class "${u}"; renaming to "${c}" so FlutterFlow can find the widget.`),o=c):o.endsWith(".dart")||(o+=".dart")}else o.endsWith(".dart")||(o+=".dart");let a=J.CODE_FILE;switch(n){case"CustomAction":a=J.ACTION;break;case"CustomWidget":a=J.WIDGET;break;case"CustomFunction":a=J.FUNCTION;break;case"CustomClass":case"CodeFile":a=J.CODE_FILE;break}let l="";return a===J.WIDGET?l=`// Automatic FlutterFlow imports import '/flutter_flow/flutter_flow_theme.dart'; import '/flutter_flow/flutter_flow_util.dart'; @@ -111,15 +111,15 @@ import '/flutter_flow/lat_lng.dart'; import '/flutter_flow/place.dart'; import '/flutter_flow/uploaded_file.dart'; -`),{content:Jv(s,l),fileName:o,codeType:a,artifactType:n,artifactName:i}}function F0(t){const e={};for(const n of Sl(t))e[n]="";return e}function R0(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 T0(t,e,n,i=new Set,r=""){const s=[],o=Vh.test(e),a=Gh.test(e);return n===J.WIDGET&&!o&&!a&&s.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:s.length===0,errors:s}}function Hs(t){const e=[],n=[];if(!t||t.size===0)return e.push("No files to commit"),{valid:!1,errors:e,warnings:n};const i=new Set(Array.from(t.values()).flatMap(r=>Fs(r.content||"")));for(const[r,s]of t.entries()){if((!s.content||s.content.trim().length===0)&&e.push(`File ${r} is empty`),s.content&&s.content.length>1e5&&n.push(`File ${r} is very large (>100KB)`),r.endsWith(".dart")){const o=T0(r,s.content,s.type,i,s.artifactName);o.valid||e.push(...o.errors.map(a=>`${r}: ${a}`))}if(r==="pubspec.yaml"){const o=Eh(s.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:n}}const ee={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},G={currentState:ee.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=ee.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(ee).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===ee.PREPARING&&(this.startTime=Date.now()),(t===ee.SUCCESS||t===ee.ERROR)&&(this.endTime=Date.now()),typeof window<"u"&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("commitStateChange",{detail:{state:t,commitState:this}})),console.log(`Commit state changed to: ${t}`)},setError(t){this.error=t,this.setState(ee.ERROR)},setSuccess(t){this.result=t,this.setState(ee.SUCCESS)},setProgress(t,e){this.filesProcessed=t,this.totalFiles=e},getElapsedTime(){return this.startTime?(this.endTime||Date.now())-this.startTime:null},isInProgress(){return this.currentState===ee.PREPARING||this.currentState===ee.VALIDATING||this.currentState===ee.PUSHING}};async function $0(t,e,n={}){let{codeType:i="W"}=n;const{pubspecDeps:r={},artifactName:s=e}=n;i==="CustomWidget"&&(i=J.WIDGET),i==="CustomAction"&&(i=J.ACTION),i==="CustomFunction"&&(i=J.FUNCTION),i==="CustomClass"&&(i=J.CODE_FILE),i==="CodeFile"&&(i=J.CODE_FILE),G.reset(),G.setState(ee.PREPARING);try{const o=await Te("flutterflow"),a=await Te("flutterflow_project_id");if(!o||!a)throw new Error("FlutterFlow credentials not configured. Please set your API key and Project ID in the API Keys settings.");if(!Ds(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=yt(),u=new pi(o,a,"main",l);G.setState(ee.VALIDATING);const c=new Map,d=i||k0(e,t),h=Kh(e,d);c.set(e,{artifactName:s,content:t,type:d,path:h}),G.setProgress(0,c.size);const f=Hs(c);if(!f.valid)throw new Error(`Validation failed: -${f.errors.join(` -`)}`);const p=await Vl(u,r),g=p.yaml,m=await ql(u,c,p.remoteFiles,`Provision ${s} custom class`,g),v=await Hl(m.syncFileMap,m.remoteFiles),E=new Map(m.syncFileMap);E.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),Be.set("package");const S=await Gl(E),_={project_id:a,zipped_custom_code:S,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};G.setState(ee.PUSHING),G.setProgress(1,c.size),ar(u),Be.set("push");const b=await zl(u,_);if(b.success)G.setSuccess({fileCount:c.size,projectId:a,warnings:b.errorMap&&b.errorMap.size>0?Array.from(b.errorMap.entries()):[]});else{const k=b.errorMessage||Ul(b.responseCode),T=new Error(k);throw T.remoteRefusal=!0,T}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:p.added,unverified:m.unverified,approximate:m.approximate,warnings:b.errorMap?Array.from(b.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),G.setError(o),o instanceof Qe?{success:!1,unconfirmed:!0,error:o.message,state:G.currentState}:{success:!1,error:o.message,remoteRefusal:o.remoteRefusal===!0,state:G.currentState}}}async function Gl(t){const e=new JSZip;for(const[n,i]of t.entries())e.file(n,i.content);return e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}async function M0(t,e={}){const{artifactType:n,artifactName:i,fileName:r,pipelineResult:s}=e;console.log(`Starting commit for ${i} (${n})`);let o=!1;const a={projectId:null,endpoint:yt(),artifactType:n,artifactName:i,fileName:r};try{G.setState(ee.PREPARING);const l=Yh(t,{artifactType:n,artifactName:i,fileName:r}),u=F0(l.content);console.log("Detected dependencies:",u),G.setState(ee.VALIDATING);const c=await Te("flutterflow"),d=qi||await Te("flutterflow_project_id");if(!c)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!d)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Ds(d))throw new Error("Invalid FlutterFlow Project ID format.");a.projectId=d;const h=new Map;h.set(l.fileName,{artifactName:i,content:l.content,type:l.codeType,path:Kh(l.fileName,l.codeType),functionName:l.codeType===J.FUNCTION?i:void 0}),G.setProgress(0,h.size);const f=Hs(h);if(!f.valid)throw new Error(`File validation failed: -${f.errors.join(` -`)}`);f.warnings.length>0&&console.warn("Validation warnings:",f.warnings),G.setState(ee.PUSHING);const p=yt(),g=new pi(c,d,"main",p),m=await Vl(g,u),v=m.yaml,E=await ql(g,h,m.remoteFiles,`Provision ${i} custom class`,v);o=E.provisionSucceeded===!0;const S=await Hl(E.syncFileMap,E.remoteFiles),_=new Map(E.syncFileMap);_.set("pubspec.yaml",{content:v,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Be.set("package");const b=await Gl(_),k={project_id:d,zipped_custom_code:b,uid:`web_${Date.now()}`,branch_name:g.branchName,serialized_yaml:v,file_map:S.fileMapContents,functions_map:S.functionsMapContents};G.setProgress(1,h.size),ar(g),Be.set("push");const T=await zl(g,k);if(T.success){const x={...R0(l,s),projectId:d};return G.setSuccess({...x,fileCount:h.size,warnings:T.errorMap?Array.from(T.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${l.fileName} to FlutterFlow`,metadata:x,targetIdentity:a,addedDependencies:m.added,unverified:E.unverified,approximate:E.approximate,warnings:T.errorMap?Array.from(T.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}else{const x=T.errorMessage||Ul(T.responseCode),F=new Error(x);throw F.errorMap=T.errorMap,F.remoteRefusal=!0,F}}catch(l){console.error("Commit execution failed:",l),G.setError(l);let u=new Map;if(l.errorMap)u=l.errorMap;else if(l.message&&l.message.includes("{"))try{const c=l.message.match(/\{[\s\S]*\}/);if(c){const d=JSON.parse(c[0]);u=new Map(Object.entries(d))}}catch(c){console.warn("Failed to parse error map from commit response:",c)}return l instanceof Qe?{success:!1,unconfirmed:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:o?{success:!1,partial:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:l.message,errorMap:u,remoteRefusal:l.remoteRefusal===!0,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function L0(t,e={}){const{pipelineResult:n}=e;let i=!1;const r={projectId:null,endpoint:yt(),artifactType:"Bundle",artifactName:t?.title,fileName:t?.fileEntries?`${t.fileEntries.length} artifacts`:"bundle"};try{if(G.setState(ee.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: +`),{content:Jv(s,l),fileName:o,codeType:a,artifactType:n,artifactName:i}}function F0(t){const e={};for(const n of Sl(t))e[n]="";return e}function R0(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 T0(t,e,n,i=new Set,r=""){const s=[],o=Vh.test(e),a=Gh.test(e);return n===J.WIDGET&&!o&&!a&&s.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:s.length===0,errors:s}}function Hs(t){const e=[],n=[];if(!t||t.size===0)return e.push("No files to commit"),{valid:!1,errors:e,warnings:n};const i=new Set(Array.from(t.values()).flatMap(r=>Ps(r.content||"")));for(const[r,s]of t.entries()){if((!s.content||s.content.trim().length===0)&&e.push(`File ${r} is empty`),s.content&&s.content.length>1e5&&n.push(`File ${r} is very large (>100KB)`),r.endsWith(".dart")){const o=T0(r,s.content,s.type,i,s.artifactName);o.valid||e.push(...o.errors.map(a=>`${r}: ${a}`))}if(r==="pubspec.yaml"){const o=Eh(s.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:n}}const ee={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},G={currentState:ee.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=ee.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(ee).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===ee.PREPARING&&(this.startTime=Date.now()),(t===ee.SUCCESS||t===ee.ERROR)&&(this.endTime=Date.now()),typeof window<"u"&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("commitStateChange",{detail:{state:t,commitState:this}})),console.log(`Commit state changed to: ${t}`)},setError(t){this.error=t,this.setState(ee.ERROR)},setSuccess(t){this.result=t,this.setState(ee.SUCCESS)},setProgress(t,e){this.filesProcessed=t,this.totalFiles=e},getElapsedTime(){return this.startTime?(this.endTime||Date.now())-this.startTime:null},isInProgress(){return this.currentState===ee.PREPARING||this.currentState===ee.VALIDATING||this.currentState===ee.PUSHING}};async function $0(t,e,n={}){let{codeType:i="W"}=n;const{pubspecDeps:r={},artifactName:s=e}=n;i==="CustomWidget"&&(i=J.WIDGET),i==="CustomAction"&&(i=J.ACTION),i==="CustomFunction"&&(i=J.FUNCTION),i==="CustomClass"&&(i=J.CODE_FILE),i==="CodeFile"&&(i=J.CODE_FILE),G.reset(),G.setState(ee.PREPARING);try{const o=await Te("flutterflow"),a=await Te("flutterflow_project_id");if(!o||!a)throw new Error("FlutterFlow credentials not configured. Please set your API key and Project ID in the API Keys settings.");if(!Bs(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=yt(),u=new pi(o,a,"main",l);G.setState(ee.VALIDATING);const c=new Map,d=i||k0(e,t),f=Kh(e,d);c.set(e,{artifactName:s,content:t,type:d,path:f}),G.setProgress(0,c.size);const h=Hs(c);if(!h.valid)throw new Error(`Validation failed: +${h.errors.join(` +`)}`);const p=await Vl(u,r),g=p.yaml,m=await ql(u,c,p.remoteFiles,`Provision ${s} custom class`,g),v=await Hl(m.syncFileMap,m.remoteFiles),E=new Map(m.syncFileMap);E.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),Be.set("package");const S=await Gl(E),_={project_id:a,zipped_custom_code:S,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};G.setState(ee.PUSHING),G.setProgress(1,c.size),or(u),Be.set("push");const b=await zl(u,_);if(b.success)G.setSuccess({fileCount:c.size,projectId:a,warnings:b.errorMap&&b.errorMap.size>0?Array.from(b.errorMap.entries()):[]});else{const k=b.errorMessage||Ul(b.responseCode),T=new Error(k);throw T.remoteRefusal=!0,T}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:p.added,unverified:m.unverified,approximate:m.approximate,warnings:b.errorMap?Array.from(b.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),G.setError(o),o instanceof Qe?{success:!1,unconfirmed:!0,error:o.message,state:G.currentState}:{success:!1,error:o.message,remoteRefusal:o.remoteRefusal===!0,state:G.currentState}}}async function Gl(t){const e=new JSZip;for(const[n,i]of t.entries())e.file(n,i.content);return e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}async function M0(t,e={}){const{artifactType:n,artifactName:i,fileName:r,pipelineResult:s}=e;console.log(`Starting commit for ${i} (${n})`);let o=!1;const a={projectId:null,endpoint:yt(),artifactType:n,artifactName:i,fileName:r};try{G.setState(ee.PREPARING);const l=Yh(t,{artifactType:n,artifactName:i,fileName:r}),u=F0(l.content);console.log("Detected dependencies:",u),G.setState(ee.VALIDATING);const c=await Te("flutterflow"),d=qi||await Te("flutterflow_project_id");if(!c)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!d)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Bs(d))throw new Error("Invalid FlutterFlow Project ID format.");a.projectId=d;const f=new Map;f.set(l.fileName,{artifactName:i,content:l.content,type:l.codeType,path:Kh(l.fileName,l.codeType),functionName:l.codeType===J.FUNCTION?i:void 0}),G.setProgress(0,f.size);const h=Hs(f);if(!h.valid)throw new Error(`File validation failed: +${h.errors.join(` +`)}`);h.warnings.length>0&&console.warn("Validation warnings:",h.warnings),G.setState(ee.PUSHING);const p=yt(),g=new pi(c,d,"main",p),m=await Vl(g,u),v=m.yaml,E=await ql(g,f,m.remoteFiles,`Provision ${i} custom class`,v);o=E.provisionSucceeded===!0;const S=await Hl(E.syncFileMap,E.remoteFiles),_=new Map(E.syncFileMap);_.set("pubspec.yaml",{content:v,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Be.set("package");const b=await Gl(_),k={project_id:d,zipped_custom_code:b,uid:`web_${Date.now()}`,branch_name:g.branchName,serialized_yaml:v,file_map:S.fileMapContents,functions_map:S.functionsMapContents};G.setProgress(1,f.size),or(g),Be.set("push");const T=await zl(g,k);if(T.success){const x={...R0(l,s),projectId:d};return G.setSuccess({...x,fileCount:f.size,warnings:T.errorMap?Array.from(T.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${l.fileName} to FlutterFlow`,metadata:x,targetIdentity:a,addedDependencies:m.added,unverified:E.unverified,approximate:E.approximate,warnings:T.errorMap?Array.from(T.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}else{const x=T.errorMessage||Ul(T.responseCode),F=new Error(x);throw F.errorMap=T.errorMap,F.remoteRefusal=!0,F}}catch(l){console.error("Commit execution failed:",l),G.setError(l);let u=new Map;if(l.errorMap)u=l.errorMap;else if(l.message&&l.message.includes("{"))try{const c=l.message.match(/\{[\s\S]*\}/);if(c){const d=JSON.parse(c[0]);u=new Map(Object.entries(d))}}catch(c){console.warn("Failed to parse error map from commit response:",c)}return l instanceof Qe?{success:!1,unconfirmed:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:o?{success:!1,partial:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:l.message,errorMap:u,remoteRefusal:l.remoteRefusal===!0,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function L0(t,e={}){const{pipelineResult:n}=e;let i=!1;const r={projectId:null,endpoint:yt(),artifactType:"Bundle",artifactName:t?.title,fileName:t?.fileEntries?`${t.fileEntries.length} artifacts`:"bundle"};try{if(G.setState(ee.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: ${t.errors.join(` `)}`);const s=new Map(t.fileEntries.map(b=>[b.fileName,{artifactId:b.artifactId,artifactName:b.artifactName,content:b.content,type:b.type,path:b.path,functionName:b.type===J.FUNCTION?b.artifactName:void 0}]));G.setProgress(0,s.size);const o=Hs(s);if(!o.valid)throw new Error(`File validation failed: ${o.errors.join(` -`)}`);G.setState(ee.VALIDATING);const a=await Te("flutterflow"),l=qi||await Te("flutterflow_project_id");if(!a)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!l)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Ds(l))throw new Error("Invalid FlutterFlow Project ID format.");r.projectId=l,G.setState(ee.PUSHING);const u=yt(),c=new pi(a,l,"main",u),d=await Vl(c,t.dependencies),h=d.yaml,f=await ql(c,s,d.remoteFiles,`Provision ${t.title} custom classes`,h);i=f.provisionSucceeded===!0;const p=await Hl(f.syncFileMap,f.remoteFiles),g=new Map(f.syncFileMap);g.set("pubspec.yaml",{content:h,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Be.set("package");const m=await Gl(g),v={project_id:l,zipped_custom_code:m,uid:`web_${Date.now()}`,branch_name:c.branchName,serialized_yaml:h,file_map:p.fileMapContents,functions_map:p.functionsMapContents};G.setProgress(1,s.size),ar(c),Be.set("push");const E=await zl(c,v);if(E.success){const b={...n,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((k,T)=>k+T.content.length,0),projectId:l};return G.setSuccess({...b,fileCount:s.size,warnings:E.errorMap?Array.from(E.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:b,targetIdentity:r,addedDependencies:d.added,unverified:f.unverified,approximate:f.approximate,warnings:E.errorMap?Array.from(E.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}const S=E.errorMessage||Ul(E.responseCode),_=new Error(S);throw _.errorMap=E.errorMap,_.remoteRefusal=!0,_}catch(s){console.error("Bundle commit execution failed:",s),G.setError(s);const o=s.errorMap||new Map;return s instanceof Qe?{success:!1,unconfirmed:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:i?{success:!1,partial:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function N0(t,e=[]){const n=yl("architect");try{return await Is("architect",Nh,vv(t),n,e)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Prompt Architect failed: ${i.message}`)}}async function Ws(t,e,n=[],i){const r=_v(t),s=yl("generator",y.bundleSpec);try{return await Is("generator",e,r,s,n)}catch(o){if(o.isModelArmor||o.isUsageLimit||o.isPipelineCancel)throw o;if(e!==Ar){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,o.message),Uw(e,Ar,i);try{return await Is("generator",Ar,r,s,n)}catch(a){throw a.isModelArmor||a.isUsageLimit||a.isPipelineCancel?a:new Error(`Code Generator failed: primary (${e}): ${o.message} | fallback (${Ar}): ${a.message}`)}}throw new Error(`Code Generator failed: ${o.message}`)}}async function zs(t,e=null){const n={...yl("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await Is("review",Oh,yv(t),n)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Code Review failed: ${i.message}`)}}function Ss(t,e){const n=document.getElementById(`step${t}-item`),i=document.getElementById(`step${t}-status`);!n||!i||(n.classList.remove("active","completed","error"),i.classList.remove("running","completed","error"),e==="active"?(n.classList.add("active"),i.classList.add("running"),i.innerHTML=` +`)}`);G.setState(ee.VALIDATING);const a=await Te("flutterflow"),l=qi||await Te("flutterflow_project_id");if(!a)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!l)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Bs(l))throw new Error("Invalid FlutterFlow Project ID format.");r.projectId=l,G.setState(ee.PUSHING);const u=yt(),c=new pi(a,l,"main",u),d=await Vl(c,t.dependencies),f=d.yaml,h=await ql(c,s,d.remoteFiles,`Provision ${t.title} custom classes`,f);i=h.provisionSucceeded===!0;const p=await Hl(h.syncFileMap,h.remoteFiles),g=new Map(h.syncFileMap);g.set("pubspec.yaml",{content:f,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Be.set("package");const m=await Gl(g),v={project_id:l,zipped_custom_code:m,uid:`web_${Date.now()}`,branch_name:c.branchName,serialized_yaml:f,file_map:p.fileMapContents,functions_map:p.functionsMapContents};G.setProgress(1,s.size),or(c),Be.set("push");const E=await zl(c,v);if(E.success){const b={...n,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((k,T)=>k+T.content.length,0),projectId:l};return G.setSuccess({...b,fileCount:s.size,warnings:E.errorMap?Array.from(E.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:b,targetIdentity:r,addedDependencies:d.added,unverified:h.unverified,approximate:h.approximate,warnings:E.errorMap?Array.from(E.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}const S=E.errorMessage||Ul(E.responseCode),_=new Error(S);throw _.errorMap=E.errorMap,_.remoteRefusal=!0,_}catch(s){console.error("Bundle commit execution failed:",s),G.setError(s);const o=s.errorMap||new Map;return s instanceof Qe?{success:!1,unconfirmed:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:i?{success:!1,partial:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function N0(t,e=[]){const n=yl("architect");try{return await xs("architect",Nh,vv(t),n,e)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Prompt Architect failed: ${i.message}`)}}async function Ws(t,e,n=[],i){const r=_v(t),s=yl("generator",y.bundleSpec);try{return await xs("generator",e,r,s,n)}catch(o){if(o.isModelArmor||o.isUsageLimit||o.isPipelineCancel)throw o;if(e!==Cr){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,o.message),Uw(e,Cr,i);try{return await xs("generator",Cr,r,s,n)}catch(a){throw a.isModelArmor||a.isUsageLimit||a.isPipelineCancel?a:new Error(`Code Generator failed: primary (${e}): ${o.message} | fallback (${Cr}): ${a.message}`)}}throw new Error(`Code Generator failed: ${o.message}`)}}async function zs(t,e=null){const n={...yl("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await xs("review",Oh,yv(t),n)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Code Review failed: ${i.message}`)}}function Es(t,e){const n=document.getElementById(`step${t}-item`),i=document.getElementById(`step${t}-status`);!n||!i||(n.classList.remove("active","completed","error"),i.classList.remove("running","completed","error"),e==="active"?(n.classList.add("active"),i.classList.add("running"),i.innerHTML=` `):e==="completed"?(n.classList.add("completed"),i.classList.add("completed"),i.innerHTML=` @@ -127,12 +127,12 @@ ${o.errors.join(` `):i.innerHTML=` - `)}function Ae(t,e){const n=document.getElementById(`step${t}-loading`),i=document.getElementById(`step${t}-result`);e?(n.classList.remove("hidden"),i.classList.add("hidden"),Ss(t,"active")):(n.classList.add("hidden"),i.classList.remove("hidden"),Ss(t,"completed"))}function O0(t){const e=document.getElementById(`${t}-content`),n=document.getElementById(`${t}-chevron`);e.classList.contains("open")?(e.classList.remove("open"),n&&(n.style.transform="rotate(0deg)")):(e.classList.add("open"),n&&(n.style.transform="rotate(180deg)"))}function B0(t){it(parseInt(t.replace("step","")))}function it(t){for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-item`);a&&a.classList.remove("active")}const e=document.getElementById(`step${t}-item`);e&&e.classList.add("active"),On();const n=document.getElementById("ready-state");n&&n.classList.add("hidden");for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-content`);a&&a.classList.add("hidden")}const i=document.getElementById(`step${t}-content`);i&&i.classList.remove("hidden");const r=document.getElementById("stage-title"),s={1:"Prompt Architect",2:"Code Generator",3:"Code Review"};r&&(r.textContent=s[t]||"Active Workflow Stage")}function D0(t){const e=document.getElementById(t);if(!e)return;const n=e.dataset.raw||e.textContent;navigator.clipboard.writeText(n).then(()=>{const r=e.closest(".code-container")?.querySelector(".copy-btn");r&&(r.classList.add("copied"),r.innerHTML=' Copied!',setTimeout(()=>{r.classList.remove("copied"),r.innerHTML=' Copy'},2e3))}).catch(i=>{console.warn("Failed to copy to clipboard:",i)})}function Ga(t){const e=Ka(t);console.log(`Step 1 (Prompt Architect): ${Gt(Nh)}`),console.log(e!==t?`Step 2 (Code Generator): ${Gt(t)} → ${Gt(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${Gt(t)}`),console.log(`Step 3 (Code Review): ${Gt(Oh)}`)}function Jh(){return{step1Result:y.step1Result,step2Result:y.step2Result,step3Result:y.step3Result,artifactBundle:y.artifactBundle,bundleReview:y.bundleReview,selectedArtifactId:y.selectedArtifactId}}function j0(t){if(!t)return;Object.assign(y,t),new Set((y.artifactBundle?.artifacts||[]).map(n=>n.id)).has(y.selectedArtifactId)||(y.selectedArtifactId=ai(y.artifactBundle)?.id||null)}const Zh="results-replacement-error";function U0(t,{stage:e=2,runId:n,retry:i}){if(!re(n))return;const r=document.getElementById(Zh);if(!r)return;const s=Ah(t),o=document.getElementById("results-replacement-error-title"),a=document.getElementById("results-replacement-error-message"),l=document.getElementById("results-replacement-error-retry"),u=document.getElementById("results-replacement-error-upgrade");o&&(o.textContent=`${Ks[e]||"Regeneration"}: ${s.title}`),a&&(a.textContent=s.message),r.hidden=!1;let c=null;u&&(u.hidden=!s.canUpgrade,s.canUpgrade&&(u.textContent="View plans",u.onclick=()=>fi(),c=u)),l&&(l.hidden=s.canUpgrade,s.canUpgrade||(l.onclick=()=>{Kl(),typeof i=="function"&&i()},l.textContent="Retry",c=l)),(c||r).focus({preventScroll:!0})}function Kl(){const t=document.getElementById(Zh);t&&(t.hidden=!0)}function Xh(t,{previous:e,stage:n,runId:i,retry:r}){re(i)&&(t.isUsageLimit&&un(),j0(e),dr(),nn(!0),fr(),no(),U0(t,{stage:n,runId:i,retry:r}),rn())}async function Qh(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0;const e=Ys();Yl("standardRegenerate",y.step2Result,y.step1Result);const n=document.querySelectorAll(".btn-refine-action"),i=Jh();n.forEach(r=>{r.disabled=!0,r.innerHTML=` + `)}function Ae(t,e){const n=document.getElementById(`step${t}-loading`),i=document.getElementById(`step${t}-result`);e?(n.classList.remove("hidden"),i.classList.add("hidden"),Es(t,"active")):(n.classList.add("hidden"),i.classList.remove("hidden"),Es(t,"completed"))}function O0(t){const e=document.getElementById(`${t}-content`),n=document.getElementById(`${t}-chevron`);e.classList.contains("open")?(e.classList.remove("open"),n&&(n.style.transform="rotate(0deg)")):(e.classList.add("open"),n&&(n.style.transform="rotate(180deg)"))}function B0(t){it(parseInt(t.replace("step","")))}function it(t){for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-item`);a&&a.classList.remove("active")}const e=document.getElementById(`step${t}-item`);e&&e.classList.add("active"),On();const n=document.getElementById("ready-state");n&&n.classList.add("hidden");for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-content`);a&&a.classList.add("hidden")}const i=document.getElementById(`step${t}-content`);i&&i.classList.remove("hidden");const r=document.getElementById("stage-title"),s={1:"Prompt Architect",2:"Code Generator",3:"Code Review"};r&&(r.textContent=s[t]||"Active Workflow Stage")}function D0(t){const e=document.getElementById(t);if(!e)return;const n=e.dataset.raw||e.textContent;navigator.clipboard.writeText(n).then(()=>{const r=e.closest(".code-container")?.querySelector(".copy-btn");r&&(r.classList.add("copied"),r.innerHTML=' Copied!',setTimeout(()=>{r.classList.remove("copied"),r.innerHTML=' Copy'},2e3))}).catch(i=>{console.warn("Failed to copy to clipboard:",i)})}function Ga(t){const e=Ka(t);console.log(`Step 1 (Prompt Architect): ${Gt(Nh)}`),console.log(e!==t?`Step 2 (Code Generator): ${Gt(t)} → ${Gt(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${Gt(t)}`),console.log(`Step 3 (Code Review): ${Gt(Oh)}`)}function Jh(){return{step1Result:y.step1Result,step2Result:y.step2Result,step3Result:y.step3Result,artifactBundle:y.artifactBundle,bundleReview:y.bundleReview,selectedArtifactId:y.selectedArtifactId}}function j0(t){if(!t)return;Object.assign(y,t),new Set((y.artifactBundle?.artifacts||[]).map(n=>n.id)).has(y.selectedArtifactId)||(y.selectedArtifactId=ai(y.artifactBundle)?.id||null)}const Zh="results-replacement-error";function U0(t,{stage:e=2,runId:n,retry:i}){if(!re(n))return;const r=document.getElementById(Zh);if(!r)return;const s=Ah(t),o=document.getElementById("results-replacement-error-title"),a=document.getElementById("results-replacement-error-message"),l=document.getElementById("results-replacement-error-retry"),u=document.getElementById("results-replacement-error-upgrade");o&&(o.textContent=`${Ks[e]||"Regeneration"}: ${s.title}`),a&&(a.textContent=s.message),r.hidden=!1;let c=null;u&&(u.hidden=!s.canUpgrade,s.canUpgrade&&(u.textContent="View plans",u.onclick=()=>fi(),c=u)),l&&(l.hidden=s.canUpgrade,s.canUpgrade||(l.onclick=()=>{Kl(),typeof i=="function"&&i()},l.textContent="Retry",c=l)),(c||r).focus({preventScroll:!0})}function Kl(){const t=document.getElementById(Zh);t&&(t.hidden=!0)}function Xh(t,{previous:e,stage:n,runId:i,retry:r}){re(i)&&(t.isUsageLimit&&un(),j0(e),ur(),nn(!0),dr(),no(),U0(t,{stage:n,runId:i,retry:r}),rn())}async function Qh(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0;const e=Ys();Yl("standardRegenerate",y.step2Result,y.step1Result);const n=document.querySelectorAll(".btn-refine-action"),i=Jh();n.forEach(r=>{r.disabled=!0,r.innerHTML=` - Refining...`});try{Kl();const r=Dl(),s=r.id,o=wv({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,artifactId:r.id,userFeedback:"Fix the issues listed in the audit report."});Qs({runId:e}),Ft(2,e),it(2),Ae(2,!0);const a=await Ws(o,t,[],e);if(!re(e))return;y.step2Result=a,js(),tn(2,e);const l=document.getElementById("step2-output"),u=ci(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),it(3),Ft(3,e),Ae(3,!0);const c=await zs(y.step2Result,y.step1Result);if(!re(e))return;y.step3Result=c,Us(),tn(3,e),y.artifactBundle?.artifacts?.some(f=>f.id===s)?y.selectedArtifactId=s:y.selectedArtifactId=ai(y.artifactBundle)?.id||null;const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),dr();const h=Os(y.step3Result);fr(u,h)}catch(r){if(console.error("Refinement failed:",r),!re(e))return;const s=Ns(r,{architect:2,generator:2,review:3});Xh(r,{previous:i,stage:s,runId:e,retry:Qh})}finally{n.forEach(r=>{r.disabled=!1,r.textContent="Refine & Regenerate"}),re(e)&&(y.isRunning=!1,rn())}}async function Yl(t,e,n){const i=`${_t}/connectFeedback`,r={type:t,code:e,input:n};try{const s=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok){const a=await s.text();return console.error(`callEndpoint failed: ${s.status} ${s.statusText}`,a),{success:!1,status:s.status,error:a}}const o=await s.json();return console.log("Telemetry success:",o),o}catch(s){return console.error("callEndpoint failed:",s),{success:!1,error:s.message}}}function H0(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function ep(){const t=document.getElementById("ff-error-paste-input"),e=t?.value?.trim();if(!e){t?.focus(),t?.classList.add("ring-2","ring-red-400","border-red-300"),setTimeout(()=>t?.classList.remove("ring-2","ring-red-400","border-red-300"),2e3);return}if(!y.step2Result){Ee("No generated code found. Please run the full pipeline first.","warning");return}if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=Ys();Yl("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` + Refining...`});try{Kl();const r=Dl(),s=r.id,o=wv({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,artifactId:r.id,userFeedback:"Fix the issues listed in the audit report."});Qs({runId:e}),Ft(2,e),it(2),Ae(2,!0);const a=await Ws(o,t,[],e);if(!re(e))return;y.step2Result=a,Ds(),tn(2,e);const l=document.getElementById("step2-output"),u=ci(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),it(3),Ft(3,e),Ae(3,!0);const c=await zs(y.step2Result,y.step1Result);if(!re(e))return;y.step3Result=c,js(),tn(3,e),y.artifactBundle?.artifacts?.some(h=>h.id===s)?y.selectedArtifactId=s:y.selectedArtifactId=ai(y.artifactBundle)?.id||null;const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),ur();const f=Ns(y.step3Result);dr(u,f)}catch(r){if(console.error("Refinement failed:",r),!re(e))return;const s=Ls(r,{architect:2,generator:2,review:3});Xh(r,{previous:i,stage:s,runId:e,retry:Qh})}finally{n.forEach(r=>{r.disabled=!1,r.textContent="Refine & Regenerate"}),re(e)&&(y.isRunning=!1,rn())}}async function Yl(t,e,n){const i=`${_t}/connectFeedback`,r={type:t,code:e,input:n};try{const s=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok){const a=await s.text();return console.error(`callEndpoint failed: ${s.status} ${s.statusText}`,a),{success:!1,status:s.status,error:a}}const o=await s.json();return console.log("Telemetry success:",o),o}catch(s){return console.error("callEndpoint failed:",s),{success:!1,error:s.message}}}function H0(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function ep(){const t=document.getElementById("ff-error-paste-input"),e=t?.value?.trim();if(!e){t?.focus(),t?.classList.add("ring-2","ring-red-400","border-red-300"),setTimeout(()=>t?.classList.remove("ring-2","ring-red-400","border-red-300"),2e3);return}if(!y.step2Result){Ee("No generated code found. Please run the full pipeline first.","warning");return}if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=Ys();Yl("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` - Fixing…`);const s=Jh();try{Kl();const o=lh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});Ap(),Qs({runId:i}),Ft(2,i),it(2),Ae(2,!0);const a=await Ws(o,n,[],i);if(!re(i))return;y.step2Result=a,js(),tn(2,i);const l=document.getElementById("step2-output"),u=ci(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),it(3),Ft(3,i),Ae(3,!0);const c=await zs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,Us(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),dr();const h=Os(y.step3Result);fr(u,h),t&&(t.value="")}catch(o){if(console.error("Fix from errors failed:",o),!re(i))return;const a=Ns(o,{architect:2,generator:2,review:3});Xh(o,{previous:s,stage:a,runId:i,retry:ep})}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function lr(){if(console.log("runThinkingPipeline called"),y.isRunning)return;localStorage.setItem("hasSeenWalkthrough","true");const t=document.getElementById("pipeline-input").value,e=document.getElementById("code-generator-model").value,n=Oe.slice();if(!t.trim()){Ee("Please describe your FlutterFlow widget first.","warning");return}y.isRunning=!0;const i=Ys();try{if(await Da,!re(i)||(pn.length&&await Promise.allSettled(pn.map(v=>v.job)),!re(i))||!await fw()||!re(i)||(await ow(),!re(i)))return;const r=Ka(e);t.length,b0(),y.submittedPrompt=t,y.submittedImages=n.filter(v=>v.url),Za(!0),Ga(r),On();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const o=document.getElementById("paywall-exhausted");o&&o.classList.add("hidden"),Qs({prompt:t,runId:i}),qw(),it(1),Ft(1,i),Ae(1,!0);const a=y.submittedImages.map(v=>({url:v.url})),l=await N0(t,a);if(!re(i))return;y.step1Result=l,E0(),tn(1,i);const u=document.getElementById("step1-output"),c=ci(y.step1Result);u.textContent=c,u.dataset.raw=c,Ae(1,!1),it(2),Ft(2,i),Ae(2,!0);const d=await Ws(y.step1Result,r,a,i);if(!re(i))return;y.step2Result=d,js(),tn(2,i);const h=document.getElementById("step2-output"),f=ci(y.step2Result);h.textContent=f,h.dataset.raw=f,Ae(2,!1),it(3),Ft(3,i),Ae(3,!0);const p=await zs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=p,Us(),tn(3,i);const g=document.getElementById("step3-output");g.textContent=y.step3Result,Ae(3,!1),dr();const m=Os(y.step3Result);Vw(),fr(f,m)}catch(r){if(r.isPipelineCancel||console.error("Pipeline failed:",r),!re(i))return;const s=Ns(r,{architect:1,generator:2,review:3});r.isUsageLimit?un():(r.message,Ka(document.getElementById("code-generator-model").value),void 0),it(s),Ae(s,!1),xp(r,{stage:s,runId:i}),Ss(s,"error")}finally{re(i)&&(y.isRunning=!1,Za(!1),rn())}}function W0(){const t=document.getElementById("code-generator-model").value,e=[_s,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(i=>i!==t),n=prompt(`Retry with different model? + Fixing…`);const s=Jh();try{Kl();const o=lh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});Ap(),Qs({runId:i}),Ft(2,i),it(2),Ae(2,!0);const a=await Ws(o,n,[],i);if(!re(i))return;y.step2Result=a,Ds(),tn(2,i);const l=document.getElementById("step2-output"),u=ci(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),it(3),Ft(3,i),Ae(3,!0);const c=await zs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,js(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),ur();const f=Ns(y.step3Result);dr(u,f),t&&(t.value="")}catch(o){if(console.error("Fix from errors failed:",o),!re(i))return;const a=Ls(o,{architect:2,generator:2,review:3});Xh(o,{previous:s,stage:a,runId:i,retry:ep})}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function ar(){if(console.log("runThinkingPipeline called"),y.isRunning)return;localStorage.setItem("hasSeenWalkthrough","true");const t=document.getElementById("pipeline-input").value,e=document.getElementById("code-generator-model").value,n=Oe.slice();if(!t.trim()){Ee("Please describe your FlutterFlow widget first.","warning");return}y.isRunning=!0;const i=Ys();try{if(await Da,!re(i)||(pn.length&&await Promise.allSettled(pn.map(v=>v.job)),!re(i))||!await fw()||!re(i)||(await ow(),!re(i)))return;const r=Ka(e);t.length,b0(),y.submittedPrompt=t,y.submittedImages=n.filter(v=>v.url),Za(!0),Ga(r),On();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const o=document.getElementById("paywall-exhausted");o&&o.classList.add("hidden"),Qs({prompt:t,runId:i}),qw(),it(1),Ft(1,i),Ae(1,!0);const a=y.submittedImages.map(v=>({url:v.url})),l=await N0(t,a);if(!re(i))return;y.step1Result=l,E0(),tn(1,i);const u=document.getElementById("step1-output"),c=ci(y.step1Result);u.textContent=c,u.dataset.raw=c,Ae(1,!1),it(2),Ft(2,i),Ae(2,!0);const d=await Ws(y.step1Result,r,a,i);if(!re(i))return;y.step2Result=d,Ds(),tn(2,i);const f=document.getElementById("step2-output"),h=ci(y.step2Result);f.textContent=h,f.dataset.raw=h,Ae(2,!1),it(3),Ft(3,i),Ae(3,!0);const p=await zs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=p,js(),tn(3,i);const g=document.getElementById("step3-output");g.textContent=y.step3Result,Ae(3,!1),ur();const m=Ns(y.step3Result);Vw(),dr(h,m)}catch(r){if(r.isPipelineCancel||console.error("Pipeline failed:",r),!re(i))return;const s=Ls(r,{architect:1,generator:2,review:3});r.isUsageLimit?un():(r.message,Ka(document.getElementById("code-generator-model").value),void 0),it(s),Ae(s,!1),xp(r,{stage:s,runId:i}),Es(s,"error")}finally{re(i)&&(y.isRunning=!1,Za(!1),rn())}}function W0(){const t=document.getElementById("code-generator-model").value,e=[vs,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(i=>i!==t),n=prompt(`Retry with different model? Current: ${t} @@ -140,7 +140,7 @@ Options: 1. ${e[0]} 2. ${e[1]} -Enter 1 or 2:`);n==="1"?(document.getElementById("code-generator-model").value=e[0],lr()):n==="2"&&(document.getElementById("code-generator-model").value=e[1],lr())}async function z0(){const t=jl();if(!t){Ee("No code to commit. Please run the pipeline first.","warning");return}const e=await Te("flutterflow"),n=await Te("flutterflow_project_id");if(!e||!n){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),Ml();return}if(y.artifactBundle?.artifacts?.length>1){await q0();return}const{artifactType:i,artifactName:r,fileName:s}=qh(),o=Yh(t,{artifactType:i,artifactName:r,fileName:s}),a=P0(o);if(!a.canProceed){Ee(`Pre-commit checks failed: ${a.issues.join("; ")}`,"error");return}Xl(o,a,null,null)}async function q0(){const t=await Te("flutterflow"),e=await Te("flutterflow_project_id");if(!t||!e){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),Ml();return}const n=i_(y.artifactBundle);if(n.errors.length>0){Ee(`Bundle validation failed: ${n.errors.join("; ")}`,"error");return}const i=new Map(n.fileEntries.map(a=>[a.fileName,{content:a.content,type:a.type,path:a.path}])),r=Hs(i),s={canProceed:r.valid&&n.errors.length===0,issues:[...n.errors,...r.errors],warnings:[...n.warnings,...r.warnings]};if(!s.canProceed){Ee(`Bundle validation failed: ${s.issues.join("; ")}`,"error");return}const o={content:n.fileEntries.map(a=>`// ${a.fileName} +Enter 1 or 2:`);n==="1"?(document.getElementById("code-generator-model").value=e[0],ar()):n==="2"&&(document.getElementById("code-generator-model").value=e[1],ar())}async function z0(){const t=jl();if(!t){Ee("No code to commit. Please run the pipeline first.","warning");return}const e=await Te("flutterflow"),n=await Te("flutterflow_project_id");if(!e||!n){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),Ml();return}if(y.artifactBundle?.artifacts?.length>1){await q0();return}const{artifactType:i,artifactName:r,fileName:s}=qh(),o=Yh(t,{artifactType:i,artifactName:r,fileName:s}),a=P0(o);if(!a.canProceed){Ee(`Pre-commit checks failed: ${a.issues.join("; ")}`,"error");return}Xl(o,a,null,null)}async function q0(){const t=await Te("flutterflow"),e=await Te("flutterflow_project_id");if(!t||!e){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),Ml();return}const n=i_(y.artifactBundle);if(n.errors.length>0){Ee(`Bundle validation failed: ${n.errors.join("; ")}`,"error");return}const i=new Map(n.fileEntries.map(a=>[a.fileName,{content:a.content,type:a.type,path:a.path}])),r=Hs(i),s={canProceed:r.valid&&n.errors.length===0,issues:[...n.errors,...r.errors],warnings:[...n.warnings,...r.warnings]};if(!s.canProceed){Ee(`Bundle validation failed: ${s.issues.join("; ")}`,"error");return}const o={content:n.fileEntries.map(a=>`// ${a.fileName} ${a.content}`).join(` `),fileName:`${n.fileEntries.length} files`,codeType:"bundle",artifactType:"Bundle",artifactName:n.title};Xl(o,s,n.dependencies,n)}function V0(t){let e=t.errorMap||new Map;!(e instanceof Map)&&typeof e=="object"&&(e=new Map(Object.entries(e)));let n=`
      @@ -160,12 +160,12 @@ ${a.content}`).join(` Fixing...`);try{let s=`The previous code had the following errors when committing to FlutterFlow: -`;if(e&&e.size>0)for(const[f,p]of e.entries()){const g=Il(p);s+=`File: ${f} +`;if(e&&e.size>0)for(const[h,p]of e.entries()){const g=Il(p);s+=`File: ${h} Error: ${g} `}else s+=`${t} -`;const o=lh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:s});Qs({runId:i}),Ft(2,i),it(2),Ae(2,!0);const a=await Ws(o,n,[],i);if(!re(i))return;y.step2Result=a,js(),tn(2,i);const l=document.getElementById("step2-output"),u=ci(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),it(3),Ft(3,i),Ae(3,!0);const c=await zs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,Us(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),dr();const h=Os(y.step3Result);fr(u,h)}catch(s){if(console.error("Regeneration failed:",s),!re(i))return;const o=Ns(s,{architect:2,generator:2,review:3});s.isUsageLimit&&un(),it(o),Ae(o,!1),xp(s,{stage:o,runId:i,retry:()=>tp(t,e)}),Ss(o,"error")}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function G0(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const n=await Te("flutterflow"),i=await Te("flutterflow_project_id");n&&i?(t.className="w-2 h-2 rounded-full bg-green-500",e.textContent="FlutterFlow credentials configured",e.className="text-green-600"):n||i?(t.className="w-2 h-2 rounded-full bg-yellow-500",e.textContent="FlutterFlow credentials incomplete",e.className="text-yellow-600"):(t.className="w-2 h-2 rounded-full bg-red-500",e.textContent="FlutterFlow credentials not configured",e.className="text-red-600")}async function np(t){try{const e=await fetch(`${_t}/auth/send-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:t})});if(!e.ok)throw new Error(`Failed to send magic link: HTTP ${e.status}`);return e.json()}catch(e){throw console.error("sendMagicLink failed:",{email:t,message:e.message,stack:e.stack}),e}}async function K0(t){try{const n=await(await fetch(`${_t}/auth/verify-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})})).json();if(n.error||!n.email||!n.sessionToken)throw new Error(n.error||"Invalid or expired link");return n}catch(e){throw console.error("verifyMagicLink failed:",{message:e.message,stack:e.stack}),e}}async function Y0(t){try{const e=await fetch(`${_t}/auth/refresh-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:t})});if(!e.ok)return console.error("refreshSession: non-OK response",{url:`${_t}/auth/refresh-session`,status:e.status}),null;const n=await e.json();return n.error||!n.email||!n.sessionToken?(console.warn("refreshSession: validation failed",{error:n.error,hasEmail:!!n.email,hasToken:!!n.sessionToken}),null):n}catch(e){return console.error("refreshSession: fetch failed",{url:`${_t}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function ad(t,e){const n=rp(),i=(q.email||n.email)!==t;q.email=t,q.sessionToken=e,q.isVerified=!0,ce=Ln({isLoading:!0}),localStorage.setItem(gs,JSON.stringify({email:t,sessionToken:e})),i&&up()}function ip(){q.email=null,q.sessionToken=null,q.isVerified=!1,ce=Ln({isResolved:!0}),localStorage.removeItem(gs),localStorage.removeItem(vs)}function rp(){try{const t=localStorage.getItem(gs);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(gs),{email:null,sessionToken:null}}}async function J0(){const e=new URLSearchParams(window.location.search).get("token");if(e){window.history.replaceState({},"",window.location.pathname+window.location.hash);try{const{email:n,sessionToken:i}=await K0(e);ad(n,i),sp();const r=ld();r&&!window.location.hash&&(window.location.hash=r)}catch(n){ld();const i=n.message||"Sign-in link invalid or expired.";Ee(i,"error"),qs(),Zn(i,"error")}}else{const{email:n,sessionToken:i}=rp();if(n&&i){const r=await Y0(i);r?ad(r.email,r.sessionToken):ip()}}Jl()}function Z0(){try{localStorage.setItem(Ba,JSON.stringify({hash:window.location.hash||"#home",ts:Date.now()}))}catch(t){console.warn("rememberSignInReturnSurface: failed to persist return surface:",t)}}function ld(){try{const t=localStorage.getItem(Ba);if(localStorage.removeItem(Ba),!t)return null;const{hash:e,ts:n}=JSON.parse(t);return!e||typeof n!="number"||Date.now()-n>Ry?null:e}catch(t){return console.warn("consumeSignInReturnSurface: failed to read return surface:",t),null}}function qs(){const t=document.getElementById("signin-modal");if(!t)return;Z0(),document.getElementById("signin-email-input")?.removeAttribute("aria-invalid"),Zn(""),We(t)}function sp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&ze(e)}function Zn(t,e){const n=document.getElementById("signin-message");n&&(n.textContent=t||"",n.classList.remove("signin-message-success","signin-message-error"),e&&n.classList.add(`signin-message-${e}`))}async function X0(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),n=Ts(t?.value);if(!n||!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(n)||n.length>254){t?.setAttribute("aria-invalid","true"),Zn("Please enter a valid email address.","error");return}t?.removeAttribute("aria-invalid"),e&&(e.disabled=!0,e.textContent="Sending…");const r=mh(n);r&&Zn(r,"error");try{const s=await np(n),o=s?.code===gh;t&&!o&&(t.value=""),t?.setAttribute("aria-invalid",String(o)),Zn(vh(s,n),o?"error":"success"),e&&(e.disabled=!1,e.textContent=o?"Send Sign-in Link":"Sent!",o||setTimeout(()=>{e.textContent==="Sent!"&&(e.textContent="Send Sign-in Link")},2500))}catch(s){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:n,err:s}),Zn("Something went wrong. Please try again.","error"),e&&(e.disabled=!1,e.textContent="Send Sign-in Link")}}function Q0(){q.email=null,q.sessionToken=null,q.isVerified=!1,ce=Ln({isResolved:!0}),j_({storage:window.localStorage,onIdentityChanged:Jl,onPlanChanged:Gs})}const ew=U_({sendLink:np,getEmail:()=>q.email||"",onState:tw});function tw(t){const e=document.getElementById("send-new-link-btn"),n=document.getElementById("send-new-link-msg");if(!e||!n)return;if(t.status==="pending"){e.disabled=!0,e.textContent="Sending…",n.className="acct-access-msg",n.textContent="Sending a fresh sign-in link…";return}if(t.status==="sent"){e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg",n.textContent=vh(t.data,q.email||"")||"Link sent — check your email.";return}e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg error";const i=t.error?.message?`Couldn't send a link right now. ${t.error.message}`:"Couldn't send a link right now. Please try again.";n.textContent=i}async function nw(){await ew()}function iw(){const t=B_(window.localStorage),e=t.length?`Cleared disposable UI caches: ${t.join(", ")}.`:"Nothing disposable to clear.";Ee(`${e} Your run count, identity and stored keys are kept.`,"info")}function rw(){const t=document.getElementById("delete-unavailable-modal");t&&We(t,{trigger:document.activeElement})}function sw(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("delete-unavailable-modal");e&&ze(e)}function Jl(){const t=q.isVerified&&!!q.email,e=document.getElementById("auth-signedout"),n=document.getElementById("auth-signedin"),i=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),n&&n.classList.toggle("hidden",!t),i&&i.classList.toggle("hidden",t);const r=document.getElementById("auth-user-email");r&&(r.textContent=q.email||"");const s=document.getElementById("access-signed-email");s&&(s.textContent=q.email||""),gw(),Gs()}async function op(){try{if(typeof FingerprintJS>"u"){console.warn("resolveIdentity: FingerprintJS not loaded, skipping");return}const e=await(await FingerprintJS.load()).get(),n=e.visitorId,i=await fetch(Ly,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fingerprint:e.visitorId,cookie_id:n})});if(!i.ok)throw new Error(`Identity check HTTP ${i.status}`);const r=await i.json();if(ht.userId=r.user_id,ht.token=r.identity_token||null,ht.status=r.status,ht.resolved=!0,sessionStorage.setItem($y,r.user_id),ht.token&&sessionStorage.setItem(My,ht.token),r.usage_count!==void 0){const s=gn(),a=(r.usage_month||s)===s?r.usage_count:0;localStorage.setItem(Fn,JSON.stringify({count:a,month:s})),un()}console.log(`Identity resolved: ${r.status} (${r.user_id.slice(0,8)}...) usage: ${r.usage_count??"n/a"}`)}catch(t){console.error("resolveIdentity failed:",t)}}let qo=null;function ow(t=5e3){return ht.resolved?Promise.resolve():(qo||(qo=op().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([qo,new Promise(e=>setTimeout(e,t))]))}function ap(){const t=gn();try{const e=localStorage.getItem(Fn);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Fn,month:t,err:e}),localStorage.removeItem(Fn),{count:0,month:t}}}function gn(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function ur(){const t=ap();return t.month!==gn()?{count:0,month:gn()}:t}function aw(){const e={count:ur().count+1,month:gn()};return localStorage.setItem(Fn,JSON.stringify(e)),e}function gi(){return!!ce.isLoading}function Tt(){return!!ce.isResolved}function lw(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(ms,e)?e:null}function cw(t){return t&&Object.entries(Fh).find(([,e])=>e===t)?.[0]||null}function Pr(...t){return t.find(e=>e!=null&&e!=="")}function uw(...t){return t.find(e=>e&&typeof e=="object")||{}}function dw(t){const e=t.data&&typeof t.data=="object"?t.data:t,n=uw(e.subscription,e.stripeSubscription,e.currentSubscription,e.customer?.subscriptions?.data?.[0],e.subscriptions?.data?.[0],e.subscriptions?.[0]),i=e.metadata||n.metadata||e.customer?.metadata||{},r=Pr(e.priceId,e.price_id,e.stripePriceId,e.stripe_price_id,n.priceId,n.price_id,n.plan?.id,n.price?.id,n.items?.data?.[0]?.price?.id,n.items?.[0]?.price?.id,n.lines?.data?.[0]?.price?.id),s=Pr(e.status,e.subscriptionStatus,e.subscription_status,n.status,"none"),o=lw(Pr(e.tier,e.plan,e.planId,e.plan_id,e.subscriptionTier,e.subscription_tier,e.product,e.productName,n.tier,n.plan,i.tier,i.plan)),a=Ny.has(String(s).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||cw(r)||(a||l?"professional":"free");return Ln({tier:u,status:s,periodEnd:Pr(e.periodEnd,e.currentPeriodEnd,e.current_period_end,n.current_period_end,n.periodEnd,null),isResolved:!0})}function Vs(){return ms[ce.tier]??ms.free}async function fw(){if(q.isVerified&&(!Tt()||gi())&&(await cp({force:!0}),Gs()),q.isVerified&&!Tt())return Ee("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=ur(),e=Vs();if(t>=e)return lp(t,e,{openModal:!0}),!1;const n=Math.floor(e*.8);if(t>=n){const i=e-t;Ee(`${i} run${i===1?"":"s"} remaining this month.`,"warning")}return!0}function cd(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function lp(t,e,n={}){nn(!0);const i=document.getElementById("walkthrough-modal");i&&ze(i,{restoreFocus:!1});const r=document.getElementById("ready-state");r&&r.classList.add("hidden");const s=document.getElementById("preview-frame-container");s&&(s.style.display="none");const o=document.getElementById("main-stage-container");o&&o.classList.add("visible");const a=document.getElementById("results-view");a&&a.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar");const l=document.getElementById("pipeline-progress");l&&l.classList.remove("visible");const u=document.getElementById("paywall-exhausted");if(!u){Ee(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),fi();return}const c=document.getElementById("paywall-exhausted-text");if(c){const h=ce.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"),n.openModal&&fi()}function Ka(t){return ce.tier==="free"&&Br.includes(t)?_s:t}function hw(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const n=ce.tier,r=!(q.isVerified&&!Tt())&&n==="free";Array.from(e.options).forEach(o=>{const a=Gt(o.value),l=Br.includes(o.value);o.textContent=l&&r?`${a} (PRO)`:a,o.disabled=!1}),r&&Br.includes(e.value)&&(e.value=_s),e.disabled=!1,Ju.has(e)||(e.addEventListener("change",()=>{Tt()&&ce.tier==="free"&&Br.includes(e.value)&&(e.value=_s,fi()),Ga(e.value),Pl()}),Ju.add(e));let s=document.getElementById("model-selector-free-notice");r?(s||(s=document.createElement("p"),s.id="model-selector-free-notice",s.className="text-xs text-gray-400 mt-1",t.appendChild(s)),s.innerHTML='Free plan — Gemini only. '):s&&s.remove(),Ga(e.value)}function Zl(){const t=q.isVerified&&!!q.email,e=t&&gi(),n=!t||Tt(),i=ur(),r=n?i.count:0,s=n?Vs():0,o=Math.max(0,s-r),a=`${r} / ${s} runs this month`,l=_l,u=n?ce.tier||"free":null,c=document.getElementById("topbar-credits-count");c&&(e?c.textContent="…":n?c.textContent=String(o):c.textContent="—");const d=document.getElementById("credits-balance");d&&(e?d.textContent="Checking plan…":n?d.textContent=a:d.textContent="Plan check failed");const h=document.getElementById("usage-dialog-tier");h&&(e?h.textContent="Checking…":n?h.textContent=l[u]||"Free":h.textContent="Unavailable");const f=document.getElementById("usage-dialog-status");f&&(e?f.textContent="Verifying your subscription…":n?f.textContent="Runs reset at the start of each month.":f.textContent="Could not verify your subscription. Try again or sign out.");const p=document.getElementById("usage-counter");if(p)if(e&&t)p.textContent="Checking plan…",p.className="text-xs text-gray-500";else if(!n&&t)p.textContent="Plan check failed",p.className="text-xs text-red-600 font-medium";else{p.textContent=a;const g=s>0?r/s:0;p.className=g>=1?"text-xs text-red-600 font-medium":g>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500"}if(!t){const g=document.getElementById("guest-usage-text");if(g){const m=ap(),v=m.month===gn()?m.count??0:0;g.textContent=`${v} / ${ms.free} generations used`}}pw()}function pw(){if(!(q.isVerified&&!!q.email))return;const e=gi(),n=Tt(),i=ur(),r=n?i.count:0,s=n?Vs():0,o=Math.max(0,s-r),a=n?ce.tier||"free":null,l={free:"Free",professional:"Pro",power:"Power"}[a]||"Free",u=q.email||"",c=u.split("@")[0]||u,d=document.getElementById("acct-avatar");d&&(d.textContent=(u[0]||"?").toUpperCase());const h=document.getElementById("acct-name");h&&(h.textContent=c||"—");const f=document.getElementById("acct-plan-tier"),p=document.getElementById("acct-plan-price"),g=document.getElementById("acct-plan-note"),m=document.getElementById("acct-renewal");if(f&&(f.textContent=e?"Checking…":n?l:"Plan unavailable"),p)if(e)p.textContent="—";else if(!n)p.textContent="—";else if(a==="free")p.textContent="$0 / month";else{const x=Bi(Oi[a]??0,Fl());p.textContent=`${x} / month`}if(g&&(e?g.textContent="Verifying your subscription…":n?a==="free"?g.textContent="No subscription. Upgrade for more generations.":g.textContent="billed monthly through Stripe":g.textContent="Could not verify your subscription. Check billing or sign out."),m){const x=Date.parse(ce.periodEnd||""),F=n&&a!=="free"&&!!ce.periodEnd&&!Number.isNaN(x);if(e)m.textContent="";else if(!n)m.textContent="";else if(a==="free")m.textContent="";else if(F){const $=new Date(x).toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"});m.textContent=`Renews ${$} · reset at the start of each month.`}else m.textContent="Renewal date is not available for this period."}const v=document.getElementById("acct-left-count"),E=document.getElementById("acct-left-limit"),S=document.getElementById("acct-reset-note");v&&(v.textContent=e?"…":n?String(o):"—"),E&&(E.textContent=e?"…":n?String(s):"—"),S&&(e?S.textContent="Checking plan…":n?S.textContent="Runs reset at the start of each month.":S.textContent="Plan check failed. Refresh or manage billing.");const _=document.getElementById("acct-used-count"),b=document.getElementById("acct-meter-fill"),k=document.getElementById("acct-meter-meta"),T=document.getElementById("acct-meter-track");if(_&&(_.textContent=e?"…":n?String(r):"—"),b){const x=n&&s>0?Math.min(100,Math.round(r/s*100)):0;b.style.width=`${x}%`}if(k)if(e)k.textContent="Checking…";else if(!n)k.textContent="Plan check failed";else if(s===0)k.textContent=`${r} of ${s}`;else{const x=Math.round(r/s*100);k.textContent=`${r} of ${s} · ${x}%`}T&&(e?T.setAttribute("aria-label","Checking usage…"):n?T.setAttribute("aria-label",`${r} of ${s} generations used`):T.setAttribute("aria-label","Usage unavailable")),vt()}function un(){if(Zl(),q.isVerified&&(gi()||!Tt())){cd();return}const{count:t}=ur(),e=Vs();t>=e&&!y.isRunning?lp(t,e):cd()}function gw(){Zl()}async function cp(t={}){const e=t.force===!0;if(!q.isVerified||!q.sessionToken){ce=Ln({isResolved:!0});return}ce={...ce,isLoading:!0,error:null};const n=localStorage.getItem(vs);if(!e&&n)try{const{data:i,email:r,ts:s,version:o}=JSON.parse(n);if(o===Zu&&r===q.email&&Date.now()-s<300*1e3){ce={...i,isLoading:!1,isResolved:i.isResolved!==!1};return}}catch(i){console.warn("Failed to parse subscription cache:",i,"| raw value:",n)}try{const r=await(await fetch(`${_t}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:q.sessionToken,user_id:ht.userId})})).json();if(r.error){if(["unauthorized","invalid session","expired session"].some(o=>String(r.error).toLowerCase().includes(o))){ip(),Jl();return}ce=Ln({isResolved:!1,error:r.error});return}ce=dw(r),localStorage.setItem(vs,JSON.stringify({version:Zu,data:ce,email:q.email,ts:Date.now()}))}catch(i){console.error("fetchSubscription failed:",i),ce={...ce,isLoading:!1,isResolved:!1,error:i.message}}}function up(){localStorage.removeItem(vs)}async function mw(t){if(!q.isVerified||!q.sessionToken){dp(),qs();return}if(!Fh[t]){Ee("Invalid plan selected.","error");return}const e=document.getElementById(`checkout-btn-${t}`);e&&(e.disabled=!0,e.textContent="Redirecting…");try{const i=await(await fetch(`${_t}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:q.sessionToken,currency:Fl()})})).json();if(i.error||!i.url)throw new Error(i.error||"Failed to create checkout session");const{url:r}=i;window.location.href=r}catch(n){console.error("startCheckout failed:",n),e&&(e.disabled=!1,e.textContent="Subscribe"),Ee("Could not start checkout. Please try again.","error")}}async function vw(t){if(!q.isVerified||!q.sessionToken){qs();return}const e=t||document.getElementById("manage-billing-btn"),n=e?e.textContent:"";e&&(e.disabled=!0,e.textContent="Loading…");try{const r=await(await fetch(`${_t}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:q.sessionToken})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to open billing portal");const{url:s}=r;window.location.href=s}catch(i){console.error("openCustomerPortal failed:",i),e&&(e.disabled=!1,e.textContent=n),Ee("Could not open billing portal. Please try again.","error")}}const xs=new Set;function _w(){xs.forEach(t=>t.abort()),xs.clear()}async function Is(t,e,n,i={},r=[]){const o=new AbortController;xs.add(o);let a=!1;const l=setTimeout(()=>{a=!0,o.abort()},12e4);try{const u=await fetch(Ty,{method:"POST",headers:{"Content-Type":"application/json",...ht.token?{Authorization:`Bearer ${ht.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:ht.userId,step:t,model:e,prompt:n,images:r,context:i})}),c=await u.text();let d={};try{d=c?JSON.parse(c):{}}catch{d={}}if(u.status===429){d.serverCount!==void 0&&(localStorage.setItem(Fn,JSON.stringify({count:d.serverCount,month:gn()})),un());const p=new Error(d.message||"Monthly usage limit reached. Upgrade to continue.");throw p.isUsageLimit=!0,p.pipelineStep=t,p}const h=Cv(d,t);if(h)throw h;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(d),"content type:",typeof d.content),!u.ok)throw new Error(`${d.message||d.error||"BuildShip pipeline error"} (HTTP ${u.status})`);if(t==="generator")if(d.usage_status==="success"&&Number.isFinite(d.usage_count)){const p=gn();(d.usage_month||p)===p&&(localStorage.setItem(Fn,JSON.stringify({count:d.usage_count,month:p})),un())}else aw(),un();let f=d.output||d.content;if(!f){const p=c?` (body: ${c.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${p}`)}return Array.isArray(f)&&(f=f.map(p=>typeof p=="string"?p:p.text||"").join("")),typeof f!="string"&&(f=JSON.stringify(f)),f}catch(u){if(u.name==="AbortError"){if(a)throw new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`);const c=new Error(`BuildShip ${t} request cancelled`);throw c.isPipelineCancel=!0,c}throw u instanceof TypeError?new Error(`BuildShip unreachable: ${u.message}`):u}finally{clearTimeout(l),xs.delete(o)}}let Ya=!1;function yw(){const e=new URLSearchParams(window.location.search).get("checkout");return e==="success"?(window.history.replaceState({},"",window.location.pathname+window.location.hash),up(),Ya=!0):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname+window.location.hash),Ee("Checkout cancelled.","info")),e}function ww(){if(!Ya)return;Ya=!1;const t=ce.tier!=="free";Ee(t?"Subscription active! Your plan is live.":"Checkout complete — confirming your subscription. Check Manage billing if it does not update.",t?"success":"info")}function Gs(){const t=q.isVerified&&!!q.email,e=ce.tier,n=t&&gi(),i=!t||Tt(),r=document.getElementById("subscription-tier-badge");if(r){const a=_l,l={free:"bg-gray-100 text-gray-600",professional:"bg-indigo-100 text-indigo-700",power:"bg-purple-100 text-purple-700",unresolved:"bg-red-50 text-red-600"};r.textContent=n?"Checking…":i?a[e]||"Free":"Plan unavailable",r.className=`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${i?l[e]||l.free:l.unresolved}`}const s=document.getElementById("upgrade-prompt");s&&s.classList.toggle("hidden",!t||n||!i||e!=="free");const o=document.getElementById("manage-billing-btn");o&&o.classList.toggle("hidden",!t||n||i&&e==="free"),bw(i?e:null),hw(),Pl(),un(),Pp()}function bw(t){const e=["bg-gray-100","text-gray-500","cursor-default"];Object.entries({professional:{btnId:"checkout-btn-professional",defaultText:"Subscribe"},power:{btnId:"checkout-btn-power",defaultText:"Subscribe"}}).forEach(([r,{btnId:s,defaultText:o}])=>{const a=document.getElementById(s);a&&(r===t?(a.disabled=!0,a.textContent="Current plan",a.classList.add(...e)):(a.disabled=!1,a.textContent=o,a.classList.remove(...e)))});const i=document.getElementById("free-tier-current");i&&i.classList.toggle("hidden",t!=="free")}function Ew(){document.querySelectorAll(".pm-card[data-tier]").forEach(t=>{const e=t.dataset.tier,n=pv[e];if(!n)return;const i=t.querySelector("ul.pm-features");if(i){i.innerHTML="";for(const r of n){const s=document.createElement("li");s.textContent=r,i.appendChild(s)}}})}function Ja(){const t=Fl(),e=document.getElementById("pro-price"),n=document.getElementById("power-price"),i=document.getElementById("plans-pro-price"),r=document.getElementById("plans-power-price"),s=document.getElementById("pro-price-note"),o=document.getElementById("power-price-note"),a=document.getElementById("plans-pro-price-note"),l=document.getElementById("plans-power-price-note");e&&(e.textContent=Bi(Oi.professional,t)),n&&(n.textContent=Bi(Oi.power,t)),i&&(i.textContent=Bi(Oi.professional,t)),r&&(r.textContent=Bi(Oi.power,t));const u="billed monthly";s&&(s.textContent=u),o&&(o.textContent=u),a&&(a.textContent=u),l&&(l.textContent=u)}function fi(){Ja();const t=document.getElementById("pricing-modal");t&&We(t),Gy().then(()=>Ja())}function dp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&ze(e)}function Ee(t,e="info"){const n={success:"bg-green-600 text-white",error:"bg-red-600 text-white",warning:"bg-amber-500 text-white",info:"bg-gray-800 text-white"},i=document.createElement("div");i.className=`fixed bottom-6 left-1/2 -translate-x-1/2 px-5 py-3 rounded-lg text-sm font-medium shadow-lg z-50 transition-opacity duration-300 ${n[e]||n.info}`,i.textContent=t,document.body.appendChild(i),setTimeout(()=>{i.style.opacity="0",setTimeout(()=>i.remove(),300)},3500)}document.addEventListener("DOMContentLoaded",async()=>{dv(),hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),Sw(),window.__heroField=ry(),window.__pipelineLogo=ly(),Th=Py({onSubmit:lr}),Da=(async()=>{try{await J0(),yw(),await cp()}catch(n){console.warn("Startup auth/subscription initialization failed:",n)}})(),await Da,ww(),Gs(),Ja(),Ew(),await S0(),_0();const t=document.getElementById("flutterflow-endpoint-select");if(t){const n=yt();t.value=n}zh(),op();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{en===2&&e.value.trim().length>0&&(Ll(),Bs())}),e.addEventListener("blur",()=>{const n=document.getElementById("walkthrough-modal");en===2&&n&&We(n)}),e.addEventListener("keydown",n=>{if(n.key==="Tab"){const i=document.getElementById("walkthrough-modal");en===2&&i&&setTimeout(()=>{We(i)},100)}})),window.addEventListener("commitStateChange",n=>{const{state:i}=n.detail;i===ee.PREPARING||i===ee.VALIDATING||i===ee.PUSHING?(Be.phaseId||vp(),dd(i)):(i===ee.SUCCESS||i===ee.ERROR)&&(dd(i),setTimeout(ec,1e3))}),ac()});function Sw(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function xw(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",On),document.addEventListener("keydown",On))}function On(){const t=document.getElementById("preview-frame-container"),e=document.getElementById("main-stage-container"),n=document.getElementById("ready-state");t&&(t.style.display="none"),e&&e.classList.add("visible"),n&&n.classList.remove("hidden");const i=document.getElementById("welcome-video-player");i&&i.removeEventListener("click",On),document.removeEventListener("keydown",On),zh()}let Vi=null;async function Iw(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++nd,n=()=>e===nd,i=await Te("flutterflow"),r=await Te("flutterflow_project_id");if(n()){if(!i){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const o=await new pi(i,"","main",yt()).listProjects();if(!n())return;if(!o||o.length===0){t.innerHTML='';return}t.innerHTML='',o.forEach(a=>{const l=document.createElement("option");l.value=a.id||a.projectId||"",l.textContent=a.name||a.projectName||`Project ${a.id}`,t.appendChild(l)}),r&&(t.value=r)}catch(s){if(!n())return;console.error("Failed to load projects for deploy:",s),t.innerHTML=''}}}function kw(){return document.getElementById("confirm-project-select")?.value?.trim()||null}function Xl(t,e,n,i=null){Vi={codeInfo:t,checks:e,deps:n,bundlePlan:i},document.getElementById("confirm-file-name").textContent=t.fileName,document.getElementById("confirm-artifact-type").textContent=t.artifactType,document.getElementById("confirm-file-size").textContent=`${(t.content.length/1024).toFixed(1)} KB`,document.getElementById("confirm-line-count").textContent=i?`${i.fileEntries.length} files`:t.content.split(` -`).length,Iw();const r=document.getElementById("confirm-deps-list"),s=document.getElementById("confirm-deps-section");n&&Object.keys(n).length>0?(r.innerHTML=Object.entries(n).map(([u,c])=>{const d=c?`at least ${Qt(c)}`:"version resolved from your project";return`
    • • ${Qt(u)}: ${d}
    • `}).join(""),s.classList.remove("hidden")):s.classList.add("hidden");const o=document.getElementById("confirm-warnings-list"),a=document.getElementById("confirm-warnings-section");e.warnings&&e.warnings.length>0?(o.innerHTML=e.warnings.map(u=>`
    • • ${Qt(u)}
    • `).join(""),a.classList.remove("hidden")):a.classList.add("hidden"),document.getElementById("confirm-code-preview").textContent=t.content,document.getElementById("code-preview-content").classList.add("hidden"),document.getElementById("code-preview-chevron").style.transform="rotate(0deg)";const l=document.getElementById("commit-confirm-modal");l&&We(l)}function fp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&ze(e),Vi=null}function Cw(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&ze(e);const n=["success-message","success-project-id","success-file-name","success-artifact-type","success-time","success-size"];for(const s of n){const o=document.getElementById(s);o&&(o.textContent="")}const i=document.getElementById("success-warnings-section");i&&i.classList.add("hidden");const r=document.getElementById("success-warnings-list");r&&(r.innerHTML="")}function hp(t){const e=(m,v)=>{const E=document.getElementById(m);E&&(E.textContent=v||"")},n=t.metadata?.fileName||"",i=t.metadata?.projectId||"",r=t.metadata?.artifactType||"",s=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",i),e("success-file-name",n),e("success-artifact-type",r),e("success-time",s),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&i&&(u.href=`https://app.flutterflow.io/project/${i}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),h=t.unverified||[],f=t.approximate||[],p=t.warnings||[];(p.length>0||h.length>0||f.length>0)&&c&&d&&(d.innerHTML=[...h.map(m=>`
    • Not verified before deploying: ${z(String(m))}
    • `),...f.map(m=>`
    • Verified approximately: ${z(String(m))}
    • `),...p.map(([m,v])=>`
    • ${z(m)}: ${z(String(v))}
    • `)].join(""),c.classList.remove("hidden"));const g=document.getElementById("commit-success-modal");g&&We(g)}function pp(t){ec(),V0(t);const e=t.remoteRefusal===!0;Ql(t,{heading:"Deploy failed",title:e?"FlutterFlow refused this deploy — nothing was confirmed written.":"The deploy failed before FlutterFlow confirmed anything.",guidance:e?"Review the error and any per-file outcomes above, fix them in your code or in FlutterFlow, then deploy again. A refusal is definitive: no part of this deploy was applied, so retrying is safe once the problem is fixed.":"Review the error above, fix it, then deploy again. The deploy stopped before a write was confirmed, so nothing was applied."})}function Ql(t,{heading:e,title:n,guidance:i}){const r=t.targetIdentity||{},s=document.getElementById("commit-terminal-modal");if(!s)return!1;const o=(f,p)=>{const g=document.getElementById(f);g&&(g.textContent=p||"")};o("terminal-heading",e),o("terminal-title",n),o("terminal-message",t.error||t.message||"");const a=document.getElementById("terminal-identity-list");if(a){const f=[["Project",r.projectId||t.metadata?.projectId],["Endpoint",r.endpoint],["File",r.fileName||t.metadata?.fileName],["Artifact",r.artifactType||t.metadata?.artifactType]];a.innerHTML=f.map(([p,g])=>`
      ${z(p)}:${z(String(g??"—"))}
      `).join("")}const l=document.getElementById("terminal-file-outcomes");let u=t.errorMap;u&&!(u instanceof Map)&&(u=new Map(Object.entries(u))),l&&u&&u.size>0?(l.innerHTML=[...u.entries()].map(([f,p])=>`
    • ${z(f)}: ${z(Il(p))}
    • `).join(""),l.classList.remove("hidden")):l&&l.classList.add("hidden");const c=document.getElementById("terminal-guidance");c&&(c.innerHTML=i);const d=document.getElementById("terminal-open-ff-link"),h=r.projectId||t.metadata?.projectId;return d&&(d.href=h?`https://app.flutterflow.io/project/${h}`:"https://app.flutterflow.io/"),We(s),!0}function gp(t){Ql(t,{heading:"Deploy partially applied",title:"Some custom classes reached FlutterFlow, but the deploy did not fully complete.",guidance:"The custom classes the runner confirmed are already in your project and are not lost. Review the per-file errors above, fix them in FlutterFlow or regenerate, then deploy again. Open the project to see exactly what landed."})}function mp(t){Ql(t,{heading:"Deploy outcome not yet known",title:"This browser stopped waiting before the FlutterFlow server reported a result.",guidance:"The deploy may still be finishing on the server — it was not cancelled. Open your FlutterFlow project and confirm whether the class landed before retrying, so you do not push a duplicate or build on top of an unknown state."})}function Aw(t){t&&t.target!==t.currentTarget||ze(document.getElementById("commit-terminal-modal"))}function Pw(){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 ud={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}},Fw=[{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&&(ku(e,!0,"Deploying to FlutterFlow"),We(e)),this.set("prepare")},set(t,e=null){if(!(!ud[t]||t===this.phaseId)){if(!this.sequence.includes(t)){const n=this.sequence.indexOf("package");this.sequence.splice(n===-1?this.sequence.length:n,0,t)}this.phaseId=t,this.phaseStartedAt=Date.now(),this.substatus=e,this.liveSubstatus=!1,this.render(),this.timer&&clearInterval(this.timer),t!=="done"&&(this.timer=setInterval(()=>this.render(),500))}},setSubstatus(t){t&&(this.liveSubstatus=!0,this.substatus=t,this.render())},render(){const t=ud[this.phaseId];if(!t)return;const e=(Date.now()-this.phaseStartedAt)/1e3,n=t.start+(t.end-t.start)*(1-Math.exp(-e/25));if(this.phaseId==="provision"&&!this.liveSubstatus){const o=Fw.filter(a=>e>=a.after).pop();o&&(this.substatus=o.text)}const i=this.sequence.indexOf(this.phaseId),s=[`Step ${i===-1?1:i+1} of ${this.sequence.length}`];e>=5&&s.push(Rw(e)),_p(this.phaseId==="done"?100:n,t.message,s.join(" · "),this.substatus)},stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.phaseId=null;const t=document.getElementById("commit-progress-overlay");t&&(ku(t,!1),ze(t,{force:!0,restoreFocus:!1}))}};function Rw(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 vp(t){Be.start(t)}function ec(){Be.stop()}function _p(t,e,n,i=null){const r=document.getElementById("commit-progress-bar"),s=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");r&&(r.style.width=`${Math.round(t*10)/10}%`),s&&(s.textContent=e),o&&(o.textContent=n),a&&(a.textContent=i||"",a.classList.toggle("hidden",!i))}function dd(t){const e={[ee.PREPARING]:"prepare",[ee.VALIDATING]:"validate",[ee.PUSHING]:"project",[ee.SUCCESS]:"done"};if(t===ee.ERROR){Be.timer&&clearInterval(Be.timer),Be.timer=null,_p(100,"Failed","Error occurred");return}const n=e[t];n&&Be.set(n)}function Tw(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===J.CODE_FILE):t.codeInfo?.codeType===J.CODE_FILE}let yp=!1;function wp(t){yp=t;const e=document.querySelector("#commit-confirm-modal button[data-deploy-confirm]");e&&(e.disabled=t),[...document.querySelectorAll("[data-deploy-start]"),...document.querySelectorAll("#btn-deploy-to-ff")].forEach(i=>{i.disabled=t})}function fd(t){ec(),wp(!1);const e=kh(t);e===Le.COMMITTED?hp(t):e===Le.PARTIAL?gp(t):e===Le.UNCONFIRMED?mp(t):pp(t)}async function $w(){if(!Vi){console.error("No pending commit data");return}if(yp){console.warn("Deploy already in flight; ignoring duplicate confirm.");return}const t=Vi;if(Vi=null,qi=kw(),fp(),wp(!0),vp({withProvisioning:Tw(t)}),t.bundlePlan){const o=await L0(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});qi=null,fd(o);return}const{codeInfo:e}=t,{artifactType:n,artifactName:i,fileName:r}=qh(),s=await M0(e.content,{artifactType:n,artifactName:i,fileName:r,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});qi=null,fd(s)}window.runThinkingPipeline=lr;window.toggleStep=B0;window.toggleSection=O0;window.selectWorkflowStep=it;window.copyCode=D0;window.retryWithDifferentModel=W0;window.openApiKeysModal=Ml;window.closeApiKeysModal=Hh;window.openComposerSettings=a0;window.closeComposerSettings=l0;window.walkthroughConnectAccount=o0;window.closeWalkthroughModal=u0;window.openWalkthroughModal=c0;window.advanceWalkthrough=Ll;window.commitToFlutterFlow=$0;function Mw(){const t=document.getElementById("pipeline-input");t&&t.focus()}function Lw(){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=Mw;window.openModelSelector=Lw;window.handlePromptImageSelect=qy;window.removePromptImage=Vy;window.saveApiKeys=h0;window.validateFlutterFlowConnection=Ol;window.clearAllApiKeys=p0;window.toggleKeyVisibility=w0;window.handleWelcomeVideoEnd=xw;window.dismissWelcomeVideo=On;window.initiateCommitToFlutterFlow=z0;window.updateFlutterFlowCredentialStatus=G0;window.openCommitConfirmModal=Xl;window.closeCommitConfirmModal=fp;window.closeCommitSuccessModal=Cw;window.closeCommitTerminalModal=Aw;window.showCommitPartialModal=gp;window.showCommitUnconfirmedModal=mp;window.showCommitSuccessModal=hp;window.showCommitFailureModal=pp;window.toggleCodePreview=Pw;window.confirmCommitToFlutterFlow=$w;window.runRefinement=Qh;window.regenerateFromPastedErrors=ep;window.clearErrorInput=H0;window.setFlutterFlowEndpoint=s0;window.getFlutterFlowEndpoint=yt;window.commitProgress=Be;window.openSignInModal=qs;window.closeSignInModal=sp;window.handleMagicLinkRequest=X0;window.handleSignOut=Q0;window.handleSendNewLink=nw;window.handleClearCache=iw;window.handleDeleteAccount=rw;window.closeDeleteUnavailableModal=sw;window.startCheckout=mw;window.openCustomerPortal=vw;window.openPricingModal=fi;window.closePricingModal=dp;let Hr=null,bp=null,Bn={1:"pending",2:"pending",3:"pending"},tc=1,nc=null;const Ks={1:"Prompt Architect",2:"Code Generator",3:"Code Review"},Nw={1:"Understanding your prompt",2:"Generating Dart code",3:"Running the code audit"},Ow={1:"Prompt understood",2:"Dart code generated",3:"Code audit complete"};function Ys(){return y.runId+=1,y.runId}function re(t){return t===void 0||t===y.runId}function Bw(){y.runId+=1}function ic(t){return document.getElementById(`pdot-${t}`)}function Za(t){const e=document.getElementById("btn-run-pipeline")||document.getElementById("hero-send");e&&(e.disabled=t,e.classList.toggle("is-busy",t),t?e.setAttribute("aria-busy","true"):e.removeAttribute("aria-busy"))}function Js(t){const e=document.getElementById("pipeline-progress");e&&(e.dataset.runState=t)}function Tn(t,e){Bn[t]=e;const n=ic(t);if(!n)return;n.dataset.state=e,n.disabled=e==="pending"||e==="skipped";const i=Ks[t],r={pending:"not started",active:"in progress",done:"complete",failed:"failed",skipped:"not run"};n.setAttribute("aria-label",`Step ${t} of 3, ${i}: ${r[e]||e}`),e==="active"?n.setAttribute("aria-current","step"):n.removeAttribute("aria-current")}function Dw(){return[1,2,3].filter(t=>Bn[t]==="done").length}function Zs(){const t=document.getElementById("pipeline-progress-fill");t&&(t.style.width=`${Dw()/3*100}%`);const e=document.getElementById("progress-stage-count");e&&(e.textContent=`Step ${tc} of 3`)}function Xs(t,{done:e=!1}={}){const n=document.getElementById("progress-title-text"),i=document.getElementById("progress-substep-text"),r=Bn[t],s=e||r==="done";if(n&&(n.textContent=s?Ow[t]:Nw[t]),i){const o=s?" — complete":r==="failed"?" — stopped":"";i.textContent=`Step ${t} of 3 — ${Ks[t]}${o}`}}function jw(t){Bn[t]==="pending"||Bn[t]==="skipped"||(nc=t,[1,2,3].forEach(e=>{const n=ic(e);n&&n.setAttribute("aria-pressed",String(e===t))}),Xs(t))}function rc(){nc=null,[1,2,3].forEach(t=>{const e=ic(t);e&&e.removeAttribute("aria-pressed")})}function Ep(t){const e=document.getElementById("pipeline-note");e&&(e.textContent=t||"",e.hidden=!t)}function Uw(t,e,n){re(n)&&Ep(`${Gt(t)} did not answer. Continuing on ${Gt(e)}.`)}function sc(){const t=document.getElementById("pipeline-failure");if(!t)return;t.hidden=!0;const e=document.getElementById("pipeline-failure-actions");e&&e.replaceChildren()}const Hw=1120;function Ww(){const t=getComputedStyle(document.documentElement).getPropertyValue("--t-morph").trim(),e=Number.parseFloat(t);return Number.isFinite(e)&&e>0?e:Hw}let ei=null,Wr=null;function zw(){return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0}function dn(){if(Wr){try{Wr.cancel()}catch{}Wr=null}ei&&(ei.remove(),ei=null),window.removeEventListener("resize",dn)}function Sp(t,e){if(dn(),zw()||!t||!e||!document.body||typeof Element.prototype.animate!="function")return;const n=t.getBoundingClientRect(),i=e.getBoundingClientRect();if(!n.width||!n.height||!i.width||!i.height)return;const r=document.createElement("div");r.className="composer-morph",r.setAttribute("aria-hidden","true"),r.style.cssText=`left:${i.left}px;top:${i.top}px;width:${i.width}px;height:${i.height}px;opacity:0;`,document.body.appendChild(r);const s=n.left+n.width/2-(i.left+i.width/2),o=n.top+n.height/2-(i.top+i.height/2),a=n.width/i.width,l=n.height/i.height,u=`translate(${s}px,${o}px) scale(${a},${l})`,c=r.animate([{transform:u,opacity:0,offset:0,easing:"cubic-bezier(.2,0,0,1)"},{transform:u,opacity:1,offset:.14,easing:"cubic-bezier(.4,0,.2,1)"},{transform:`translate(${s}px,${o}px) scale(${a*.93},${l*.93})`,opacity:1,offset:.28,easing:"cubic-bezier(.32,1.38,.5,1)"},{transform:"translate(0px,0px) scale(1,1)",opacity:1,offset:1}],{duration:Ww(),fill:"both"});ei=r,Wr=c,window.addEventListener("resize",dn),c.onfinish=()=>{if(ei!==r)return;const d=r.animate([{opacity:1},{opacity:0}],{duration:260,fill:"forwards"});d.onfinish=()=>{ei===r&&dn()}}}function qw(){const e=document.getElementById("composer")?.getBoundingClientRect();e&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{Sp({getBoundingClientRect:()=>e},document.getElementById("main-stage-container"))})})}function Vw(){Sp(document.getElementById("pipeline-progress"),document.getElementById("main-stage-container"))}window.addEventListener("hashchange",dn);window.addEventListener("popstate",dn);function Qs(t={}){const{prompt:e=null,runId:n}=t;if(!re(n))return;to(),nn(!0);const i=document.getElementById("pipeline-progress"),r=document.getElementById("results-view"),s=document.getElementById("ready-state");if(s&&s.classList.add("hidden"),r&&r.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),i&&i.classList.add("visible"),Js("running"),e!==null){const a=document.getElementById("pipeline-submitted-prompt");a&&(a.textContent=e)}bp=Date.now();const o=document.getElementById("progress-elapsed");o&&(o.textContent="0s"),Bn={1:"pending",2:"pending",3:"pending"},rc(),sc(),Ep(""),[1,2,3].forEach(a=>Tn(a,"pending")),Ft(1,n),Gw()}function Ft(t,e){re(e)&&(tc=t,rc(),[1,2,3].forEach(n=>{n===t?Tn(n,"active"):nt&&Tn(n,"pending")}),Xs(t),Zs())}function tn(t,e){re(e)&&(Tn(t,"done"),nc===null&&Xs(t,{done:!0}),Zs())}function xp(t,{stage:e=1,runId:n,retry:i=Ip}={}){if(!re(n))return;eo(),to(),dn(),Js("failed"),nn(!0);const r=document.getElementById("pipeline-progress");r&&r.classList.add("visible");const s=document.getElementById("results-view");s&&s.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),Tn(e,"failed"),[1,2,3].forEach(p=>{p>e&&Tn(p,"pending")}),tc=e,rc(),Xs(e),Zs();const o=Ah(t),a=document.getElementById("pipeline-failure"),l=document.getElementById("pipeline-failure-title"),u=document.getElementById("pipeline-failure-message"),c=document.getElementById("pipeline-failure-hint"),d=document.getElementById("pipeline-failure-actions");if(!a||!l||!u||!d)return;if(a.dataset.kind=o.kind,l.textContent=`${Ks[e]}: ${o.title}`,u.textContent=o.message,c){const p=o.detail&&o.detail!==o.message?o.detail:"";c.textContent=p,c.hidden=!p}d.replaceChildren();const h=[o.canUpgrade&&{id:"upgrade",label:"View plans",variant:"primary",onClick:()=>fi()},o.canRetry&&{id:"retry",label:"Retry",variant:o.canUpgrade?"secondary":"primary",onClick:i},o.canEdit&&{id:"edit",label:"Edit prompt",variant:"secondary",onClick:Xa}].filter(Boolean);!o.canEdit&&!o.canRetry&&h.push({id:"edit",label:"Back to prompt",variant:"secondary",onClick:Xa}),h.forEach(p=>{const g=document.createElement("button");g.type="button",g.textContent=p.label,g.dataset.action=p.id,g.dataset.variant=p.variant,g.addEventListener("click",p.onClick),d.appendChild(g)}),a.hidden=!1;const f=d.querySelector("button");f&&f.focus({preventScroll:!0})}function Xa(){Bw(),_w(),y.isRunning=!1,Za(!1),rn(),Js("settled"),dn(),eo(),to(),sc();const t=document.getElementById("pipeline-progress");t&&t.classList.remove("visible"),nn(!1);const e=document.getElementById("pipeline-input");e&&(y.submittedPrompt&&(e.value=y.submittedPrompt,e.dispatchEvent(new Event("input",{bubbles:!0}))),e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length))}function Ip(){const t=document.getElementById("pipeline-input");t&&y.submittedPrompt&&(t.value=y.submittedPrompt,t.dispatchEvent(new Event("input",{bubbles:!0}))),Oe=y.submittedImages.slice(),cn(),sc(),lr()}function Gw(){eo(),Hr=setInterval(()=>{const t=(Date.now()-bp)/1e3,e=document.getElementById("progress-elapsed");e&&(e.textContent=`${Math.floor(t)}s`)},250)}function eo(){Hr&&(clearInterval(Hr),Hr=null)}let Gi=null;function to(){Gi&&(clearTimeout(Gi),Gi=null)}function dr(){eo(),to(),Js("settled"),Zs();const t=document.getElementById("pipeline-progress-fill");Gi=setTimeout(()=>{Gi=null;const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function $n(t,e=""){const n={pass:'',warning:'',fail:'',info:''};return``}function kp(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function Kw(){return y_({bundle:y.artifactBundle,reviewResult:y.step3Result})}function Yw(t){return` +`;const o=lh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:s});Qs({runId:i}),Ft(2,i),it(2),Ae(2,!0);const a=await Ws(o,n,[],i);if(!re(i))return;y.step2Result=a,Ds(),tn(2,i);const l=document.getElementById("step2-output"),u=ci(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),it(3),Ft(3,i),Ae(3,!0);const c=await zs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,js(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),ur();const f=Ns(y.step3Result);dr(u,f)}catch(s){if(console.error("Regeneration failed:",s),!re(i))return;const o=Ls(s,{architect:2,generator:2,review:3});s.isUsageLimit&&un(),it(o),Ae(o,!1),xp(s,{stage:o,runId:i,retry:()=>tp(t,e)}),Es(o,"error")}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function G0(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const n=await Te("flutterflow"),i=await Te("flutterflow_project_id");n&&i?(t.className="w-2 h-2 rounded-full bg-green-500",e.textContent="FlutterFlow credentials configured",e.className="text-green-600"):n||i?(t.className="w-2 h-2 rounded-full bg-yellow-500",e.textContent="FlutterFlow credentials incomplete",e.className="text-yellow-600"):(t.className="w-2 h-2 rounded-full bg-red-500",e.textContent="FlutterFlow credentials not configured",e.className="text-red-600")}async function np(t){try{const e=await fetch(`${_t}/auth/send-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:t})});if(!e.ok)throw new Error(`Failed to send magic link: HTTP ${e.status}`);return e.json()}catch(e){throw console.error("sendMagicLink failed:",{email:t,message:e.message,stack:e.stack}),e}}async function K0(t){try{const n=await(await fetch(`${_t}/auth/verify-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})})).json();if(n.error||!n.email||!n.sessionToken)throw new Error(n.error||"Invalid or expired link");return n}catch(e){throw console.error("verifyMagicLink failed:",{message:e.message,stack:e.stack}),e}}async function Y0(t){try{const e=await fetch(`${_t}/auth/refresh-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:t})});if(!e.ok)return console.error("refreshSession: non-OK response",{url:`${_t}/auth/refresh-session`,status:e.status}),null;const n=await e.json();return n.error||!n.email||!n.sessionToken?(console.warn("refreshSession: validation failed",{error:n.error,hasEmail:!!n.email,hasToken:!!n.sessionToken}),null):n}catch(e){return console.error("refreshSession: fetch failed",{url:`${_t}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function ad(t,e){const n=rp(),i=(q.email||n.email)!==t;q.email=t,q.sessionToken=e,q.isVerified=!0,ce=Ln({isLoading:!0}),localStorage.setItem(ps,JSON.stringify({email:t,sessionToken:e})),i&&up()}function ip(){q.email=null,q.sessionToken=null,q.isVerified=!1,ce=Ln({isResolved:!0}),localStorage.removeItem(ps),localStorage.removeItem(ms)}function rp(){try{const t=localStorage.getItem(ps);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(ps),{email:null,sessionToken:null}}}async function J0(){const e=new URLSearchParams(window.location.search).get("token");if(e){window.history.replaceState({},"",window.location.pathname+window.location.hash);try{const{email:n,sessionToken:i}=await K0(e);ad(n,i),sp();const r=ld();r&&!window.location.hash&&(window.location.hash=r)}catch(n){ld();const i=n.message||"Sign-in link invalid or expired.";Ee(i,"error"),qs(),Zn(i,"error")}}else{const{email:n,sessionToken:i}=rp();if(n&&i){const r=await Y0(i);r?ad(r.email,r.sessionToken):ip()}}Jl()}function Z0(){try{localStorage.setItem(Ba,JSON.stringify({hash:window.location.hash||"#home",ts:Date.now()}))}catch(t){console.warn("rememberSignInReturnSurface: failed to persist return surface:",t)}}function ld(){try{const t=localStorage.getItem(Ba);if(localStorage.removeItem(Ba),!t)return null;const{hash:e,ts:n}=JSON.parse(t);return!e||typeof n!="number"||Date.now()-n>Ry?null:e}catch(t){return console.warn("consumeSignInReturnSurface: failed to read return surface:",t),null}}function qs(){const t=document.getElementById("signin-modal");if(!t)return;Z0(),document.getElementById("signin-email-input")?.removeAttribute("aria-invalid"),Zn(""),We(t)}function sp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&ze(e)}function Zn(t,e){const n=document.getElementById("signin-message");n&&(n.textContent=t||"",n.classList.remove("signin-message-success","signin-message-error"),e&&n.classList.add(`signin-message-${e}`))}async function X0(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),n=Rs(t?.value);if(!n||!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(n)||n.length>254){t?.setAttribute("aria-invalid","true"),Zn("Please enter a valid email address.","error");return}t?.removeAttribute("aria-invalid"),e&&(e.disabled=!0,e.textContent="Sending…");const r=mh(n);r&&Zn(r,"error");try{const s=await np(n),o=s?.code===gh;t&&!o&&(t.value=""),t?.setAttribute("aria-invalid",String(o)),Zn(vh(s,n),o?"error":"success"),e&&(e.disabled=!1,e.textContent=o?"Send Sign-in Link":"Sent!",o||setTimeout(()=>{e.textContent==="Sent!"&&(e.textContent="Send Sign-in Link")},2500))}catch(s){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:n,err:s}),Zn("Something went wrong. Please try again.","error"),e&&(e.disabled=!1,e.textContent="Send Sign-in Link")}}function Q0(){q.email=null,q.sessionToken=null,q.isVerified=!1,ce=Ln({isResolved:!0}),j_({storage:window.localStorage,onIdentityChanged:Jl,onPlanChanged:Gs})}const ew=U_({sendLink:np,getEmail:()=>q.email||"",onState:tw});function tw(t){const e=document.getElementById("send-new-link-btn"),n=document.getElementById("send-new-link-msg");if(!e||!n)return;if(t.status==="pending"){e.disabled=!0,e.textContent="Sending…",n.className="acct-access-msg",n.textContent="Sending a fresh sign-in link…";return}if(t.status==="sent"){e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg",n.textContent=vh(t.data,q.email||"")||"Link sent — check your email.";return}e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg error";const i=t.error?.message?`Couldn't send a link right now. ${t.error.message}`:"Couldn't send a link right now. Please try again.";n.textContent=i}async function nw(){await ew()}function iw(){const t=B_(window.localStorage),e=t.length?`Cleared disposable UI caches: ${t.join(", ")}.`:"Nothing disposable to clear.";Ee(`${e} Your run count, identity and stored keys are kept.`,"info")}function rw(){const t=document.getElementById("delete-unavailable-modal");t&&We(t,{trigger:document.activeElement})}function sw(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("delete-unavailable-modal");e&&ze(e)}function Jl(){const t=q.isVerified&&!!q.email,e=document.getElementById("auth-signedout"),n=document.getElementById("auth-signedin"),i=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),n&&n.classList.toggle("hidden",!t),i&&i.classList.toggle("hidden",t);const r=document.getElementById("auth-user-email");r&&(r.textContent=q.email||"");const s=document.getElementById("access-signed-email");s&&(s.textContent=q.email||""),gw(),Gs()}async function op(){try{if(typeof FingerprintJS>"u"){console.warn("resolveIdentity: FingerprintJS not loaded, skipping");return}const e=await(await FingerprintJS.load()).get(),n=e.visitorId,i=await fetch(Ly,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fingerprint:e.visitorId,cookie_id:n})});if(!i.ok)throw new Error(`Identity check HTTP ${i.status}`);const r=await i.json();if(ht.userId=r.user_id,ht.token=r.identity_token||null,ht.status=r.status,ht.resolved=!0,sessionStorage.setItem($y,r.user_id),ht.token&&sessionStorage.setItem(My,ht.token),r.usage_count!==void 0){const s=gn(),a=(r.usage_month||s)===s?r.usage_count:0;localStorage.setItem(Fn,JSON.stringify({count:a,month:s})),un()}console.log(`Identity resolved: ${r.status} (${r.user_id.slice(0,8)}...) usage: ${r.usage_count??"n/a"}`)}catch(t){console.error("resolveIdentity failed:",t)}}let qo=null;function ow(t=5e3){return ht.resolved?Promise.resolve():(qo||(qo=op().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([qo,new Promise(e=>setTimeout(e,t))]))}function ap(){const t=gn();try{const e=localStorage.getItem(Fn);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Fn,month:t,err:e}),localStorage.removeItem(Fn),{count:0,month:t}}}function gn(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function cr(){const t=ap();return t.month!==gn()?{count:0,month:gn()}:t}function aw(){const e={count:cr().count+1,month:gn()};return localStorage.setItem(Fn,JSON.stringify(e)),e}function gi(){return!!ce.isLoading}function Tt(){return!!ce.isResolved}function lw(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(gs,e)?e:null}function cw(t){return t&&Object.entries(Fh).find(([,e])=>e===t)?.[0]||null}function Ar(...t){return t.find(e=>e!=null&&e!=="")}function uw(...t){return t.find(e=>e&&typeof e=="object")||{}}function dw(t){const e=t.data&&typeof t.data=="object"?t.data:t,n=uw(e.subscription,e.stripeSubscription,e.currentSubscription,e.customer?.subscriptions?.data?.[0],e.subscriptions?.data?.[0],e.subscriptions?.[0]),i=e.metadata||n.metadata||e.customer?.metadata||{},r=Ar(e.priceId,e.price_id,e.stripePriceId,e.stripe_price_id,n.priceId,n.price_id,n.plan?.id,n.price?.id,n.items?.data?.[0]?.price?.id,n.items?.[0]?.price?.id,n.lines?.data?.[0]?.price?.id),s=Ar(e.status,e.subscriptionStatus,e.subscription_status,n.status,"none"),o=lw(Ar(e.tier,e.plan,e.planId,e.plan_id,e.subscriptionTier,e.subscription_tier,e.product,e.productName,n.tier,n.plan,i.tier,i.plan)),a=Ny.has(String(s).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||cw(r)||(a||l?"professional":"free");return Ln({tier:u,status:s,periodEnd:Ar(e.periodEnd,e.currentPeriodEnd,e.current_period_end,n.current_period_end,n.periodEnd,null),isResolved:!0})}function Vs(){return gs[ce.tier]??gs.free}async function fw(){if(q.isVerified&&(!Tt()||gi())&&(await cp({force:!0}),Gs()),q.isVerified&&!Tt())return Ee("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=cr(),e=Vs();if(t>=e)return lp(t,e,{openModal:!0}),!1;const n=Math.floor(e*.8);if(t>=n){const i=e-t;Ee(`${i} run${i===1?"":"s"} remaining this month.`,"warning")}return!0}function cd(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function lp(t,e,n={}){nn(!0);const i=document.getElementById("walkthrough-modal");i&&ze(i,{restoreFocus:!1});const r=document.getElementById("ready-state");r&&r.classList.add("hidden");const s=document.getElementById("preview-frame-container");s&&(s.style.display="none");const o=document.getElementById("main-stage-container");o&&o.classList.add("visible");const a=document.getElementById("results-view");a&&a.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar");const l=document.getElementById("pipeline-progress");l&&l.classList.remove("visible");const u=document.getElementById("paywall-exhausted");if(!u){Ee(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),fi();return}const c=document.getElementById("paywall-exhausted-text");if(c){const f=ce.tier;f==="free"?c.textContent=`You've used all ${e} free generations this month. Upgrade to Pro for 50 generations/month and access to all AI models.`:c.textContent=`You've used all ${e} generations this month on your ${f} plan. Your limit resets next month.`}const d=document.getElementById("paywall-signin-btn");d&&d.classList.toggle("hidden",q.isVerified),u.classList.remove("hidden"),n.openModal&&fi()}function Ka(t){return ce.tier==="free"&&Or.includes(t)?vs:t}function hw(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const n=ce.tier,r=!(q.isVerified&&!Tt())&&n==="free";Array.from(e.options).forEach(o=>{const a=Gt(o.value),l=Or.includes(o.value);o.textContent=l&&r?`${a} (PRO)`:a,o.disabled=!1}),r&&Or.includes(e.value)&&(e.value=vs),e.disabled=!1,Ju.has(e)||(e.addEventListener("change",()=>{Tt()&&ce.tier==="free"&&Or.includes(e.value)&&(e.value=vs,fi()),Ga(e.value),Pl()}),Ju.add(e));let s=document.getElementById("model-selector-free-notice");r?(s||(s=document.createElement("p"),s.id="model-selector-free-notice",s.className="text-xs text-gray-400 mt-1",t.appendChild(s)),s.innerHTML='Free plan — Gemini only. '):s&&s.remove(),Ga(e.value)}function Zl(){const t=q.isVerified&&!!q.email,e=t&&gi(),n=!t||Tt(),i=cr(),r=n?i.count:0,s=n?Vs():0,o=Math.max(0,s-r),a=`${r} / ${s} runs this month`,l=_l,u=n?ce.tier||"free":null,c=document.getElementById("topbar-credits-count");c&&(e?c.textContent="…":n?c.textContent=String(o):c.textContent="—");const d=document.getElementById("credits-balance");d&&(e?d.textContent="Checking plan…":n?d.textContent=a:d.textContent="Plan check failed");const f=document.getElementById("usage-dialog-tier");f&&(e?f.textContent="Checking…":n?f.textContent=l[u]||"Free":f.textContent="Unavailable");const h=document.getElementById("usage-dialog-status");h&&(e?h.textContent="Verifying your subscription…":n?h.textContent="Runs reset at the start of each month.":h.textContent="Could not verify your subscription. Try again or sign out.");const p=document.getElementById("usage-counter");if(p)if(e&&t)p.textContent="Checking plan…",p.className="text-xs text-gray-500";else if(!n&&t)p.textContent="Plan check failed",p.className="text-xs text-red-600 font-medium";else{p.textContent=a;const g=s>0?r/s:0;p.className=g>=1?"text-xs text-red-600 font-medium":g>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500"}if(!t){const g=document.getElementById("guest-usage-text");if(g){const m=ap(),v=m.month===gn()?m.count??0:0;g.textContent=`${v} / ${gs.free} generations used`}}pw()}function pw(){if(!(q.isVerified&&!!q.email))return;const e=gi(),n=Tt(),i=cr(),r=n?i.count:0,s=n?Vs():0,o=Math.max(0,s-r),a=n?ce.tier||"free":null,l={free:"Free",professional:"Pro",power:"Power"}[a]||"Free",u=q.email||"",c=u.split("@")[0]||u,d=document.getElementById("acct-avatar");d&&(d.textContent=(u[0]||"?").toUpperCase());const f=document.getElementById("acct-name");f&&(f.textContent=c||"—");const h=document.getElementById("acct-plan-tier"),p=document.getElementById("acct-plan-price"),g=document.getElementById("acct-plan-note"),m=document.getElementById("acct-renewal");if(h&&(h.textContent=e?"Checking…":n?l:"Plan unavailable"),p)if(e)p.textContent="—";else if(!n)p.textContent="—";else if(a==="free")p.textContent="$0 / month";else{const x=Bi(Oi[a]??0,Fl());p.textContent=`${x} / month`}if(g&&(e?g.textContent="Verifying your subscription…":n?a==="free"?g.textContent="No subscription. Upgrade for more generations.":g.textContent="billed monthly through Stripe":g.textContent="Could not verify your subscription. Check billing or sign out."),m){const x=Date.parse(ce.periodEnd||""),F=n&&a!=="free"&&!!ce.periodEnd&&!Number.isNaN(x);if(e)m.textContent="";else if(!n)m.textContent="";else if(a==="free")m.textContent="";else if(F){const $=new Date(x).toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"});m.textContent=`Renews ${$} · reset at the start of each month.`}else m.textContent="Renewal date is not available for this period."}const v=document.getElementById("acct-left-count"),E=document.getElementById("acct-left-limit"),S=document.getElementById("acct-reset-note");v&&(v.textContent=e?"…":n?String(o):"—"),E&&(E.textContent=e?"…":n?String(s):"—"),S&&(e?S.textContent="Checking plan…":n?S.textContent="Runs reset at the start of each month.":S.textContent="Plan check failed. Refresh or manage billing.");const _=document.getElementById("acct-used-count"),b=document.getElementById("acct-meter-fill"),k=document.getElementById("acct-meter-meta"),T=document.getElementById("acct-meter-track");if(_&&(_.textContent=e?"…":n?String(r):"—"),b){const x=n&&s>0?Math.min(100,Math.round(r/s*100)):0;b.style.width=`${x}%`}if(k)if(e)k.textContent="Checking…";else if(!n)k.textContent="Plan check failed";else if(s===0)k.textContent=`${r} of ${s}`;else{const x=Math.round(r/s*100);k.textContent=`${r} of ${s} · ${x}%`}T&&(e?T.setAttribute("aria-label","Checking usage…"):n?T.setAttribute("aria-label",`${r} of ${s} generations used`):T.setAttribute("aria-label","Usage unavailable")),vt()}function un(){if(Zl(),q.isVerified&&(gi()||!Tt())){cd();return}const{count:t}=cr(),e=Vs();t>=e&&!y.isRunning?lp(t,e):cd()}function gw(){Zl()}async function cp(t={}){const e=t.force===!0;if(!q.isVerified||!q.sessionToken){ce=Ln({isResolved:!0});return}ce={...ce,isLoading:!0,error:null};const n=localStorage.getItem(ms);if(!e&&n)try{const{data:i,email:r,ts:s,version:o}=JSON.parse(n);if(o===Zu&&r===q.email&&Date.now()-s<300*1e3){ce={...i,isLoading:!1,isResolved:i.isResolved!==!1};return}}catch(i){console.warn("Failed to parse subscription cache:",i,"| raw value:",n)}try{const r=await(await fetch(`${_t}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:q.sessionToken,user_id:ht.userId})})).json();if(r.error){if(["unauthorized","invalid session","expired session"].some(o=>String(r.error).toLowerCase().includes(o))){ip(),Jl();return}ce=Ln({isResolved:!1,error:r.error});return}ce=dw(r),localStorage.setItem(ms,JSON.stringify({version:Zu,data:ce,email:q.email,ts:Date.now()}))}catch(i){console.error("fetchSubscription failed:",i),ce={...ce,isLoading:!1,isResolved:!1,error:i.message}}}function up(){localStorage.removeItem(ms)}async function mw(t){if(!q.isVerified||!q.sessionToken){dp(),qs();return}if(!Fh[t]){Ee("Invalid plan selected.","error");return}const e=document.getElementById(`checkout-btn-${t}`);e&&(e.disabled=!0,e.textContent="Redirecting…");try{const i=await(await fetch(`${_t}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:q.sessionToken,currency:Fl()})})).json();if(i.error||!i.url)throw new Error(i.error||"Failed to create checkout session");const{url:r}=i;window.location.href=r}catch(n){console.error("startCheckout failed:",n),e&&(e.disabled=!1,e.textContent="Subscribe"),Ee("Could not start checkout. Please try again.","error")}}async function vw(t){if(!q.isVerified||!q.sessionToken){qs();return}const e=t||document.getElementById("manage-billing-btn"),n=e?e.textContent:"";e&&(e.disabled=!0,e.textContent="Loading…");try{const r=await(await fetch(`${_t}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:q.sessionToken})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to open billing portal");const{url:s}=r;window.location.href=s}catch(i){console.error("openCustomerPortal failed:",i),e&&(e.disabled=!1,e.textContent=n),Ee("Could not open billing portal. Please try again.","error")}}const Ss=new Set;function _w(){Ss.forEach(t=>t.abort()),Ss.clear()}async function xs(t,e,n,i={},r=[]){const o=new AbortController;Ss.add(o);let a=!1;const l=setTimeout(()=>{a=!0,o.abort()},12e4);try{const u=await fetch(Ty,{method:"POST",headers:{"Content-Type":"application/json",...ht.token?{Authorization:`Bearer ${ht.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:ht.userId,step:t,model:e,prompt:n,images:r,context:i})}),c=await u.text();let d={};try{d=c?JSON.parse(c):{}}catch{d={}}if(u.status===429){d.serverCount!==void 0&&(localStorage.setItem(Fn,JSON.stringify({count:d.serverCount,month:gn()})),un());const p=new Error(d.message||"Monthly usage limit reached. Upgrade to continue.");throw p.isUsageLimit=!0,p.pipelineStep=t,p}const f=Cv(d,t);if(f)throw f;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(d),"content type:",typeof d.content),!u.ok)throw new Error(`${d.message||d.error||"BuildShip pipeline error"} (HTTP ${u.status})`);if(t==="generator")if(d.usage_status==="success"&&Number.isFinite(d.usage_count)){const p=gn();(d.usage_month||p)===p&&(localStorage.setItem(Fn,JSON.stringify({count:d.usage_count,month:p})),un())}else aw(),un();let h=d.output||d.content;if(!h){const p=c?` (body: ${c.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${p}`)}return Array.isArray(h)&&(h=h.map(p=>typeof p=="string"?p:p.text||"").join("")),typeof h!="string"&&(h=JSON.stringify(h)),h}catch(u){if(u.name==="AbortError"){if(a)throw new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`);const c=new Error(`BuildShip ${t} request cancelled`);throw c.isPipelineCancel=!0,c}throw u instanceof TypeError?new Error(`BuildShip unreachable: ${u.message}`):u}finally{clearTimeout(l),Ss.delete(o)}}let Ya=!1;function yw(){const e=new URLSearchParams(window.location.search).get("checkout");return e==="success"?(window.history.replaceState({},"",window.location.pathname+window.location.hash),up(),Ya=!0):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname+window.location.hash),Ee("Checkout cancelled.","info")),e}function ww(){if(!Ya)return;Ya=!1;const t=ce.tier!=="free";Ee(t?"Subscription active! Your plan is live.":"Checkout complete — confirming your subscription. Check Manage billing if it does not update.",t?"success":"info")}function Gs(){const t=q.isVerified&&!!q.email,e=ce.tier,n=t&&gi(),i=!t||Tt(),r=document.getElementById("subscription-tier-badge");if(r){const a=_l,l={free:"bg-gray-100 text-gray-600",professional:"bg-indigo-100 text-indigo-700",power:"bg-purple-100 text-purple-700",unresolved:"bg-red-50 text-red-600"};r.textContent=n?"Checking…":i?a[e]||"Free":"Plan unavailable",r.className=`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${i?l[e]||l.free:l.unresolved}`}const s=document.getElementById("upgrade-prompt");s&&s.classList.toggle("hidden",!t||n||!i||e!=="free");const o=document.getElementById("manage-billing-btn");o&&o.classList.toggle("hidden",!t||n||i&&e==="free"),bw(i?e:null),hw(),Pl(),un(),Pp()}function bw(t){const e=["bg-gray-100","text-gray-500","cursor-default"];Object.entries({professional:{btnId:"checkout-btn-professional",defaultText:"Subscribe"},power:{btnId:"checkout-btn-power",defaultText:"Subscribe"}}).forEach(([r,{btnId:s,defaultText:o}])=>{const a=document.getElementById(s);a&&(r===t?(a.disabled=!0,a.textContent="Current plan",a.classList.add(...e)):(a.disabled=!1,a.textContent=o,a.classList.remove(...e)))});const i=document.getElementById("free-tier-current");i&&i.classList.toggle("hidden",t!=="free")}function Ew(){document.querySelectorAll(".pm-card[data-tier]").forEach(t=>{const e=t.dataset.tier,n=pv[e];if(!n)return;const i=t.querySelector("ul.pm-features");if(i){i.innerHTML="";for(const r of n){const s=document.createElement("li");s.textContent=r,i.appendChild(s)}}})}function Ja(){const t=Fl(),e=document.getElementById("pro-price"),n=document.getElementById("power-price"),i=document.getElementById("plans-pro-price"),r=document.getElementById("plans-power-price"),s=document.getElementById("pro-price-note"),o=document.getElementById("power-price-note"),a=document.getElementById("plans-pro-price-note"),l=document.getElementById("plans-power-price-note");e&&(e.textContent=Bi(Oi.professional,t)),n&&(n.textContent=Bi(Oi.power,t)),i&&(i.textContent=Bi(Oi.professional,t)),r&&(r.textContent=Bi(Oi.power,t));const u="billed monthly";s&&(s.textContent=u),o&&(o.textContent=u),a&&(a.textContent=u),l&&(l.textContent=u)}function fi(){Ja();const t=document.getElementById("pricing-modal");t&&We(t),Gy().then(()=>Ja())}function dp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&ze(e)}function Ee(t,e="info"){const n={success:"bg-green-600 text-white",error:"bg-red-600 text-white",warning:"bg-amber-500 text-white",info:"bg-gray-800 text-white"},i=document.createElement("div");i.className=`fixed bottom-6 left-1/2 -translate-x-1/2 px-5 py-3 rounded-lg text-sm font-medium shadow-lg z-50 transition-opacity duration-300 ${n[e]||n.info}`,i.textContent=t,document.body.appendChild(i),setTimeout(()=>{i.style.opacity="0",setTimeout(()=>i.remove(),300)},3500)}document.addEventListener("DOMContentLoaded",async()=>{dv(),hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),Sw(),window.__heroField=ry(),window.__pipelineLogo=ly(),Th=Py({onSubmit:ar}),Da=(async()=>{try{await J0(),yw(),await cp()}catch(n){console.warn("Startup auth/subscription initialization failed:",n)}})(),await Da,ww(),Gs(),Ja(),Ew(),await S0(),_0();const t=document.getElementById("flutterflow-endpoint-select");if(t){const n=yt();t.value=n}zh(),op();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{en===2&&e.value.trim().length>0&&(Ll(),Os())}),e.addEventListener("blur",()=>{const n=document.getElementById("walkthrough-modal");en===2&&n&&We(n)}),e.addEventListener("keydown",n=>{if(n.key==="Tab"){const i=document.getElementById("walkthrough-modal");en===2&&i&&setTimeout(()=>{We(i)},100)}})),window.addEventListener("commitStateChange",n=>{const{state:i}=n.detail;i===ee.PREPARING||i===ee.VALIDATING||i===ee.PUSHING?(Be.phaseId||vp(),dd(i)):(i===ee.SUCCESS||i===ee.ERROR)&&(dd(i),setTimeout(ec,1e3))}),ac()});function Sw(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function xw(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",On),document.addEventListener("keydown",On))}function On(){const t=document.getElementById("preview-frame-container"),e=document.getElementById("main-stage-container"),n=document.getElementById("ready-state");t&&(t.style.display="none"),e&&e.classList.add("visible"),n&&n.classList.remove("hidden");const i=document.getElementById("welcome-video-player");i&&i.removeEventListener("click",On),document.removeEventListener("keydown",On),zh()}let Vi=null;async function Iw(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++nd,n=()=>e===nd,i=await Te("flutterflow"),r=await Te("flutterflow_project_id");if(n()){if(!i){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const o=await new pi(i,"","main",yt()).listProjects();if(!n())return;if(!o||o.length===0){t.innerHTML='';return}t.innerHTML='',o.forEach(a=>{const l=document.createElement("option");l.value=a.id||a.projectId||"",l.textContent=a.name||a.projectName||`Project ${a.id}`,t.appendChild(l)}),r&&(t.value=r)}catch(s){if(!n())return;console.error("Failed to load projects for deploy:",s),t.innerHTML=''}}}function kw(){return document.getElementById("confirm-project-select")?.value?.trim()||null}function Xl(t,e,n,i=null){Vi={codeInfo:t,checks:e,deps:n,bundlePlan:i},document.getElementById("confirm-file-name").textContent=t.fileName,document.getElementById("confirm-artifact-type").textContent=t.artifactType,document.getElementById("confirm-file-size").textContent=`${(t.content.length/1024).toFixed(1)} KB`,document.getElementById("confirm-line-count").textContent=i?`${i.fileEntries.length} files`:t.content.split(` +`).length,Iw();const r=document.getElementById("confirm-deps-list"),s=document.getElementById("confirm-deps-section");n&&Object.keys(n).length>0?(r.innerHTML=Object.entries(n).map(([u,c])=>{const d=c?`at least ${Qt(c)}`:"version resolved from your project";return`
    • • ${Qt(u)}: ${d}
    • `}).join(""),s.classList.remove("hidden")):s.classList.add("hidden");const o=document.getElementById("confirm-warnings-list"),a=document.getElementById("confirm-warnings-section");e.warnings&&e.warnings.length>0?(o.innerHTML=e.warnings.map(u=>`
    • • ${Qt(u)}
    • `).join(""),a.classList.remove("hidden")):a.classList.add("hidden"),document.getElementById("confirm-code-preview").textContent=t.content,document.getElementById("code-preview-content").classList.add("hidden"),document.getElementById("code-preview-chevron").style.transform="rotate(0deg)";const l=document.getElementById("commit-confirm-modal");l&&We(l)}function fp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&ze(e),Vi=null}function Cw(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&ze(e);const n=["success-message","success-project-id","success-file-name","success-artifact-type","success-time","success-size"];for(const s of n){const o=document.getElementById(s);o&&(o.textContent="")}const i=document.getElementById("success-warnings-section");i&&i.classList.add("hidden");const r=document.getElementById("success-warnings-list");r&&(r.innerHTML="")}function hp(t){const e=(m,v)=>{const E=document.getElementById(m);E&&(E.textContent=v||"")},n=t.metadata?.fileName||"",i=t.metadata?.projectId||"",r=t.metadata?.artifactType||"",s=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",i),e("success-file-name",n),e("success-artifact-type",r),e("success-time",s),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&i&&(u.href=`https://app.flutterflow.io/project/${i}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),f=t.unverified||[],h=t.approximate||[],p=t.warnings||[];(p.length>0||f.length>0||h.length>0)&&c&&d&&(d.innerHTML=[...f.map(m=>`
    • Not verified before deploying: ${z(String(m))}
    • `),...h.map(m=>`
    • Verified approximately: ${z(String(m))}
    • `),...p.map(([m,v])=>`
    • ${z(m)}: ${z(String(v))}
    • `)].join(""),c.classList.remove("hidden"));const g=document.getElementById("commit-success-modal");g&&We(g)}function pp(t){ec(),V0(t);const e=t.remoteRefusal===!0;Ql(t,{heading:"Deploy failed",title:e?"FlutterFlow refused this deploy — nothing was confirmed written.":"The deploy failed before FlutterFlow confirmed anything.",guidance:e?"Review the error and any per-file outcomes above, fix them in your code or in FlutterFlow, then deploy again. A refusal is definitive: no part of this deploy was applied, so retrying is safe once the problem is fixed.":"Review the error above, fix it, then deploy again. The deploy stopped before a write was confirmed, so nothing was applied."})}function Ql(t,{heading:e,title:n,guidance:i}){const r=t.targetIdentity||{},s=document.getElementById("commit-terminal-modal");if(!s)return!1;const o=(h,p)=>{const g=document.getElementById(h);g&&(g.textContent=p||"")};o("terminal-heading",e),o("terminal-title",n),o("terminal-message",t.error||t.message||"");const a=document.getElementById("terminal-identity-list");if(a){const h=[["Project",r.projectId||t.metadata?.projectId],["Endpoint",r.endpoint],["File",r.fileName||t.metadata?.fileName],["Artifact",r.artifactType||t.metadata?.artifactType]];a.innerHTML=h.map(([p,g])=>`
      ${z(p)}:${z(String(g??"—"))}
      `).join("")}const l=document.getElementById("terminal-file-outcomes");let u=t.errorMap;u&&!(u instanceof Map)&&(u=new Map(Object.entries(u))),l&&u&&u.size>0?(l.innerHTML=[...u.entries()].map(([h,p])=>`
    • ${z(h)}: ${z(Il(p))}
    • `).join(""),l.classList.remove("hidden")):l&&l.classList.add("hidden");const c=document.getElementById("terminal-guidance");c&&(c.innerHTML=i);const d=document.getElementById("terminal-open-ff-link"),f=r.projectId||t.metadata?.projectId;return d&&(d.href=f?`https://app.flutterflow.io/project/${f}`:"https://app.flutterflow.io/"),We(s),!0}function gp(t){Ql(t,{heading:"Deploy partially applied",title:"Some custom classes reached FlutterFlow, but the deploy did not fully complete.",guidance:"The custom classes the runner confirmed are already in your project and are not lost. Review the per-file errors above, fix them in FlutterFlow or regenerate, then deploy again. Open the project to see exactly what landed."})}function mp(t){Ql(t,{heading:"Deploy outcome not yet known",title:"This browser stopped waiting before the FlutterFlow server reported a result.",guidance:"The deploy may still be finishing on the server — it was not cancelled. Open your FlutterFlow project and confirm whether the class landed before retrying, so you do not push a duplicate or build on top of an unknown state."})}function Aw(t){t&&t.target!==t.currentTarget||ze(document.getElementById("commit-terminal-modal"))}function Pw(){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 ud={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}},Fw=[{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&&(ku(e,!0,"Deploying to FlutterFlow"),We(e)),this.set("prepare")},set(t,e=null){if(!(!ud[t]||t===this.phaseId)){if(!this.sequence.includes(t)){const n=this.sequence.indexOf("package");this.sequence.splice(n===-1?this.sequence.length:n,0,t)}this.phaseId=t,this.phaseStartedAt=Date.now(),this.substatus=e,this.liveSubstatus=!1,this.render(),this.timer&&clearInterval(this.timer),t!=="done"&&(this.timer=setInterval(()=>this.render(),500))}},setSubstatus(t){t&&(this.liveSubstatus=!0,this.substatus=t,this.render())},render(){const t=ud[this.phaseId];if(!t)return;const e=(Date.now()-this.phaseStartedAt)/1e3,n=t.start+(t.end-t.start)*(1-Math.exp(-e/25));if(this.phaseId==="provision"&&!this.liveSubstatus){const o=Fw.filter(a=>e>=a.after).pop();o&&(this.substatus=o.text)}const i=this.sequence.indexOf(this.phaseId),s=[`Step ${i===-1?1:i+1} of ${this.sequence.length}`];e>=5&&s.push(Rw(e)),_p(this.phaseId==="done"?100:n,t.message,s.join(" · "),this.substatus)},stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.phaseId=null;const t=document.getElementById("commit-progress-overlay");t&&(ku(t,!1),ze(t,{force:!0,restoreFocus:!1}))}};function Rw(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 vp(t){Be.start(t)}function ec(){Be.stop()}function _p(t,e,n,i=null){const r=document.getElementById("commit-progress-bar"),s=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");r&&(r.style.width=`${Math.round(t*10)/10}%`),s&&(s.textContent=e),o&&(o.textContent=n),a&&(a.textContent=i||"",a.classList.toggle("hidden",!i))}function dd(t){const e={[ee.PREPARING]:"prepare",[ee.VALIDATING]:"validate",[ee.PUSHING]:"project",[ee.SUCCESS]:"done"};if(t===ee.ERROR){Be.timer&&clearInterval(Be.timer),Be.timer=null,_p(100,"Failed","Error occurred");return}const n=e[t];n&&Be.set(n)}function Tw(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===J.CODE_FILE):t.codeInfo?.codeType===J.CODE_FILE}let yp=!1;function wp(t){yp=t;const e=document.querySelector("#commit-confirm-modal button[data-deploy-confirm]");e&&(e.disabled=t),[...document.querySelectorAll("[data-deploy-start]"),...document.querySelectorAll("#btn-deploy-to-ff")].forEach(i=>{i.disabled=t})}function fd(t){ec(),wp(!1);const e=kh(t);e===Le.COMMITTED?hp(t):e===Le.PARTIAL?gp(t):e===Le.UNCONFIRMED?mp(t):pp(t)}async function $w(){if(!Vi){console.error("No pending commit data");return}if(yp){console.warn("Deploy already in flight; ignoring duplicate confirm.");return}const t=Vi;if(Vi=null,qi=kw(),fp(),wp(!0),vp({withProvisioning:Tw(t)}),t.bundlePlan){const o=await L0(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});qi=null,fd(o);return}const{codeInfo:e}=t,{artifactType:n,artifactName:i,fileName:r}=qh(),s=await M0(e.content,{artifactType:n,artifactName:i,fileName:r,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});qi=null,fd(s)}window.runThinkingPipeline=ar;window.toggleStep=B0;window.toggleSection=O0;window.selectWorkflowStep=it;window.copyCode=D0;window.retryWithDifferentModel=W0;window.openApiKeysModal=Ml;window.closeApiKeysModal=Hh;window.openComposerSettings=a0;window.closeComposerSettings=l0;window.walkthroughConnectAccount=o0;window.closeWalkthroughModal=u0;window.openWalkthroughModal=c0;window.advanceWalkthrough=Ll;window.commitToFlutterFlow=$0;function Mw(){const t=document.getElementById("pipeline-input");t&&t.focus()}function Lw(){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=Mw;window.openModelSelector=Lw;window.handlePromptImageSelect=qy;window.removePromptImage=Vy;window.saveApiKeys=h0;window.validateFlutterFlowConnection=Ol;window.clearAllApiKeys=p0;window.toggleKeyVisibility=w0;window.handleWelcomeVideoEnd=xw;window.dismissWelcomeVideo=On;window.initiateCommitToFlutterFlow=z0;window.updateFlutterFlowCredentialStatus=G0;window.openCommitConfirmModal=Xl;window.closeCommitConfirmModal=fp;window.closeCommitSuccessModal=Cw;window.closeCommitTerminalModal=Aw;window.showCommitPartialModal=gp;window.showCommitUnconfirmedModal=mp;window.showCommitSuccessModal=hp;window.showCommitFailureModal=pp;window.toggleCodePreview=Pw;window.confirmCommitToFlutterFlow=$w;window.runRefinement=Qh;window.regenerateFromPastedErrors=ep;window.clearErrorInput=H0;window.setFlutterFlowEndpoint=s0;window.getFlutterFlowEndpoint=yt;window.commitProgress=Be;window.openSignInModal=qs;window.closeSignInModal=sp;window.handleMagicLinkRequest=X0;window.handleSignOut=Q0;window.handleSendNewLink=nw;window.handleClearCache=iw;window.handleDeleteAccount=rw;window.closeDeleteUnavailableModal=sw;window.startCheckout=mw;window.openCustomerPortal=vw;window.openPricingModal=fi;window.closePricingModal=dp;let Ur=null,bp=null,Bn={1:"pending",2:"pending",3:"pending"},tc=1,nc=null;const Ks={1:"Prompt Architect",2:"Code Generator",3:"Code Review"},Nw={1:"Understanding your prompt",2:"Generating Dart code",3:"Running the code audit"},Ow={1:"Prompt understood",2:"Dart code generated",3:"Code audit complete"};function Ys(){return y.runId+=1,y.runId}function re(t){return t===void 0||t===y.runId}function Bw(){y.runId+=1}function ic(t){return document.getElementById(`pdot-${t}`)}function Za(t){const e=document.getElementById("btn-run-pipeline")||document.getElementById("hero-send");e&&(e.disabled=t,e.classList.toggle("is-busy",t),t?e.setAttribute("aria-busy","true"):e.removeAttribute("aria-busy"))}function Js(t){const e=document.getElementById("pipeline-progress");e&&(e.dataset.runState=t)}function Tn(t,e){Bn[t]=e;const n=ic(t);if(!n)return;n.dataset.state=e,n.disabled=e==="pending"||e==="skipped";const i=Ks[t],r={pending:"not started",active:"in progress",done:"complete",failed:"failed",skipped:"not run"};n.setAttribute("aria-label",`Step ${t} of 3, ${i}: ${r[e]||e}`),e==="active"?n.setAttribute("aria-current","step"):n.removeAttribute("aria-current")}function Dw(){return[1,2,3].filter(t=>Bn[t]==="done").length}function Zs(){const t=document.getElementById("pipeline-progress-fill");t&&(t.style.width=`${Dw()/3*100}%`);const e=document.getElementById("progress-stage-count");e&&(e.textContent=`Step ${tc} of 3`)}function Xs(t,{done:e=!1}={}){const n=document.getElementById("progress-title-text"),i=document.getElementById("progress-substep-text"),r=Bn[t],s=e||r==="done";if(n&&(n.textContent=s?Ow[t]:Nw[t]),i){const o=s?" — complete":r==="failed"?" — stopped":"";i.textContent=`Step ${t} of 3 — ${Ks[t]}${o}`}}function jw(t){Bn[t]==="pending"||Bn[t]==="skipped"||(nc=t,[1,2,3].forEach(e=>{const n=ic(e);n&&n.setAttribute("aria-pressed",String(e===t))}),Xs(t))}function rc(){nc=null,[1,2,3].forEach(t=>{const e=ic(t);e&&e.removeAttribute("aria-pressed")})}function Ep(t){const e=document.getElementById("pipeline-note");e&&(e.textContent=t||"",e.hidden=!t)}function Uw(t,e,n){re(n)&&Ep(`${Gt(t)} did not answer. Continuing on ${Gt(e)}.`)}function sc(){const t=document.getElementById("pipeline-failure");if(!t)return;t.hidden=!0;const e=document.getElementById("pipeline-failure-actions");e&&e.replaceChildren()}const Hw=1120;function Ww(){const t=getComputedStyle(document.documentElement).getPropertyValue("--t-morph").trim(),e=Number.parseFloat(t);return Number.isFinite(e)&&e>0?e:Hw}let ei=null,Hr=null;function zw(){return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0}function dn(){if(Hr){try{Hr.cancel()}catch{}Hr=null}ei&&(ei.remove(),ei=null),window.removeEventListener("resize",dn)}function Sp(t,e){if(dn(),zw()||!t||!e||!document.body||typeof Element.prototype.animate!="function")return;const n=t.getBoundingClientRect(),i=e.getBoundingClientRect();if(!n.width||!n.height||!i.width||!i.height)return;const r=document.createElement("div");r.className="composer-morph",r.setAttribute("aria-hidden","true"),r.style.cssText=`left:${i.left}px;top:${i.top}px;width:${i.width}px;height:${i.height}px;opacity:0;`,document.body.appendChild(r);const s=n.left+n.width/2-(i.left+i.width/2),o=n.top+n.height/2-(i.top+i.height/2),a=n.width/i.width,l=n.height/i.height,u=`translate(${s}px,${o}px) scale(${a},${l})`,c=r.animate([{transform:u,opacity:0,offset:0,easing:"cubic-bezier(.2,0,0,1)"},{transform:u,opacity:1,offset:.14,easing:"cubic-bezier(.4,0,.2,1)"},{transform:`translate(${s}px,${o}px) scale(${a*.93},${l*.93})`,opacity:1,offset:.28,easing:"cubic-bezier(.32,1.38,.5,1)"},{transform:"translate(0px,0px) scale(1,1)",opacity:1,offset:1}],{duration:Ww(),fill:"both"});ei=r,Hr=c,window.addEventListener("resize",dn),c.onfinish=()=>{if(ei!==r)return;const d=r.animate([{opacity:1},{opacity:0}],{duration:260,fill:"forwards"});d.onfinish=()=>{ei===r&&dn()}}}function qw(){const e=document.getElementById("composer")?.getBoundingClientRect();e&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{Sp({getBoundingClientRect:()=>e},document.getElementById("main-stage-container"))})})}function Vw(){Sp(document.getElementById("pipeline-progress"),document.getElementById("main-stage-container"))}window.addEventListener("hashchange",dn);window.addEventListener("popstate",dn);function Qs(t={}){const{prompt:e=null,runId:n}=t;if(!re(n))return;to(),nn(!0);const i=document.getElementById("pipeline-progress"),r=document.getElementById("results-view"),s=document.getElementById("ready-state");if(s&&s.classList.add("hidden"),r&&r.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),i&&i.classList.add("visible"),Js("running"),e!==null){const a=document.getElementById("pipeline-submitted-prompt");a&&(a.textContent=e)}bp=Date.now();const o=document.getElementById("progress-elapsed");o&&(o.textContent="0s"),Bn={1:"pending",2:"pending",3:"pending"},rc(),sc(),Ep(""),[1,2,3].forEach(a=>Tn(a,"pending")),Ft(1,n),Gw()}function Ft(t,e){re(e)&&(tc=t,rc(),[1,2,3].forEach(n=>{n===t?Tn(n,"active"):nt&&Tn(n,"pending")}),Xs(t),Zs())}function tn(t,e){re(e)&&(Tn(t,"done"),nc===null&&Xs(t,{done:!0}),Zs())}function xp(t,{stage:e=1,runId:n,retry:i=Ip}={}){if(!re(n))return;eo(),to(),dn(),Js("failed"),nn(!0);const r=document.getElementById("pipeline-progress");r&&r.classList.add("visible");const s=document.getElementById("results-view");s&&s.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),Tn(e,"failed"),[1,2,3].forEach(p=>{p>e&&Tn(p,"pending")}),tc=e,rc(),Xs(e),Zs();const o=Ah(t),a=document.getElementById("pipeline-failure"),l=document.getElementById("pipeline-failure-title"),u=document.getElementById("pipeline-failure-message"),c=document.getElementById("pipeline-failure-hint"),d=document.getElementById("pipeline-failure-actions");if(!a||!l||!u||!d)return;if(a.dataset.kind=o.kind,l.textContent=`${Ks[e]}: ${o.title}`,u.textContent=o.message,c){const p=o.detail&&o.detail!==o.message?o.detail:"";c.textContent=p,c.hidden=!p}d.replaceChildren();const f=[o.canUpgrade&&{id:"upgrade",label:"View plans",variant:"primary",onClick:()=>fi()},o.canRetry&&{id:"retry",label:"Retry",variant:o.canUpgrade?"secondary":"primary",onClick:i},o.canEdit&&{id:"edit",label:"Edit prompt",variant:"secondary",onClick:Xa}].filter(Boolean);!o.canEdit&&!o.canRetry&&f.push({id:"edit",label:"Back to prompt",variant:"secondary",onClick:Xa}),f.forEach(p=>{const g=document.createElement("button");g.type="button",g.textContent=p.label,g.dataset.action=p.id,g.dataset.variant=p.variant,g.addEventListener("click",p.onClick),d.appendChild(g)}),a.hidden=!1;const h=d.querySelector("button");h&&h.focus({preventScroll:!0})}function Xa(){Bw(),_w(),y.isRunning=!1,Za(!1),rn(),Js("settled"),dn(),eo(),to(),sc();const t=document.getElementById("pipeline-progress");t&&t.classList.remove("visible"),nn(!1);const e=document.getElementById("pipeline-input");e&&(y.submittedPrompt&&(e.value=y.submittedPrompt,e.dispatchEvent(new Event("input",{bubbles:!0}))),e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length))}function Ip(){const t=document.getElementById("pipeline-input");t&&y.submittedPrompt&&(t.value=y.submittedPrompt,t.dispatchEvent(new Event("input",{bubbles:!0}))),Oe=y.submittedImages.slice(),cn(),sc(),ar()}function Gw(){eo(),Ur=setInterval(()=>{const t=(Date.now()-bp)/1e3,e=document.getElementById("progress-elapsed");e&&(e.textContent=`${Math.floor(t)}s`)},250)}function eo(){Ur&&(clearInterval(Ur),Ur=null)}let Gi=null;function to(){Gi&&(clearTimeout(Gi),Gi=null)}function ur(){eo(),to(),Js("settled"),Zs();const t=document.getElementById("pipeline-progress-fill");Gi=setTimeout(()=>{Gi=null;const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function $n(t,e=""){const n={pass:'',warning:'',fail:'',info:''};return``}function kp(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function Kw(){return y_({bundle:y.artifactBundle,reviewResult:y.step3Result})}function Yw(t){return`
      ${$n(t.severity)}
      @@ -315,4 +315,4 @@ Error: ${g} ${z(s.artifactType)} - `}).join(""),i.onclick=s=>{const o=s.target.closest(".artifact-tab");o?.dataset?.artifactId&&oc(o.dataset.artifactId)},hd()),e&&e.classList.add("visible")}function hd(){const t=document.getElementById("bundle-strip");!t||t.dataset.tabKeyboard==="bound"||(t.dataset.tabKeyboard="bound",t.addEventListener("keydown",e=>{if(e.defaultPrevented)return;const n=[document.getElementById("results-summary-tab"),...Array.from(document.querySelectorAll("#artifact-tabs .artifact-tab"))].filter(Boolean);if(!n.length||!n.includes(document.activeElement))return;let i=-1;const r=n.indexOf(document.activeElement);if(e.key==="ArrowRight")i=(r+1)%n.length;else if(e.key==="ArrowLeft")i=(r-1+n.length)%n.length;else if(e.key==="Home")i=0;else if(e.key==="End")i=n.length-1;else return;e.preventDefault();const s=n[i];if(!s)return;if(s.id==="results-summary-tab")Cp();else{const a=s.dataset.artifactId;a&&oc(a)}const o=s.id==="results-summary-tab"?document.getElementById("results-summary-tab"):document.querySelector(`#artifact-tabs .artifact-tab[data-artifact-id="${s.dataset.artifactId}"]`);o&&o.focus()}))}function no(){document.body.classList.add("results-fullscreen"),document.body.classList.add("results-with-sidebar");const t=document.getElementById("results-view"),e=document.getElementById("results-code-output"),n=document.getElementById("results-audit-output"),i=document.getElementById("results-summary-detail"),r=document.getElementById("artifact-results-split"),s=Kw(),o=jl();if(i&&(i.setAttribute("role","tabpanel"),i.setAttribute("aria-labelledby","results-summary-tab")),r){r.setAttribute("role","tabpanel");const a=s?.artifacts?.find(l=>l.id===y.selectedArtifactId);r.setAttribute("aria-labelledby",a?`artifact-tab-${a.id}`:"results-summary-tab")}if(Zw(s),Qw(s),e&&(e.textContent=""),e){const a=Ph(o);e.innerHTML=a}n&&(n.innerHTML=Xw(s)),i&&i.classList.toggle("hidden",y.resultsViewMode!=="summary"),r&&r.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function fr(t,e){nn(!0),y.selectedArtifactId||(y.selectedArtifactId=ai(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const n=document.getElementById("step3-output");n&&(n.textContent=""),no(),rn(),eb()}function eb(){const t=document.getElementById("btn-feedback-up"),e=document.getElementById("btn-feedback-down"),n=document.getElementById("results-feedback-status");t&&(t.className="feedback-btn",t.setAttribute("aria-pressed","false"),t.disabled=!1,t.removeAttribute("aria-disabled")),e&&(e.className="feedback-btn",e.setAttribute("aria-pressed","false"),e.disabled=!1,e.removeAttribute("aria-disabled")),n&&(n.textContent=""),Qa=!1}function oc(t){y.selectedArtifactId=t,y.resultsViewMode="file",no()}function Cp(){y.resultsViewMode="summary",no()}function tb(){const t=document.getElementById("btn-copy-results"),e=document.getElementById("results-copy-status"),n=jl(),i=(r,s)=>{e&&(e.textContent=r,e.classList.toggle("ok",!!s),e.classList.toggle("fail",!s))};if(!navigator.clipboard?.writeText){i("Copying isn't supported in this browser.",!1);return}navigator.clipboard.writeText(n).then(()=>{if(i("Copied to clipboard",!0),t){t.classList.add("copied");const r=t.querySelector("span");if(r){const s=r.textContent;r.textContent="Copied!",setTimeout(()=>{t.classList.remove("copied"),r.textContent=s},2e3)}}}).catch(()=>{i("Clipboard permission was denied. Select the code to copy it manually.",!1)})}let Qa=!1;async function nb(t){const e=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down"),i=document.getElementById("results-feedback-status");if(!e||!n||Qa)return;const r=l=>{i&&(i.textContent="",i.offsetWidth,i.textContent=l)},s=l=>{Qa=l,[e,n].forEach(u=>{u.disabled=l,u.setAttribute("aria-disabled",String(l))})},o=t==="up"?"thumbsUp":"thumbsDown";s(!0),r("Submitting review feedback…");const a={type:o,code:y.step2Result,input:y.step1Result};try{const l=await Yl(a.type,a.code,a.input);if(!l||l.success!==!0){s(!1),r("Review feedback could not be sent. Tap again to retry.");return}e.classList.toggle("active-up",t==="up"),n.classList.toggle("active-down",t==="down"),e.setAttribute("aria-pressed",String(t==="up")),n.setAttribute("aria-pressed",String(t==="down")),s(!1),r("Review feedback saved.")}catch{s(!1),r("Review feedback could not be sent. Tap again to retry.")}}function ib(){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 Ap(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}function nn(t){const e=document.getElementById("generation-stage");e&&(t?(e.hidden=!1,e.inert=!1,requestAnimationFrame(()=>e.classList.add("is-active"))):(e.classList.remove("is-active"),e.inert=!0,setTimeout(()=>{e.classList.contains("is-active")||(e.hidden=!0)},260)))}function Pp(){const t=q.isVerified&&!!q.email,e=ce.tier||"free",n=t&&gi(),i=!t||Tt(),s=n?"Checking…":i?_l[e]||"Free":"—",o=document.getElementById("topbar-plan");o&&(o.textContent=s);const a=document.getElementById("topbar-avatar");a&&(a.textContent=(q.email||"?")[0].toUpperCase()),Zl();const l=document.getElementById("plans-free-current");l&&l.classList.toggle("hidden",e!=="free"||!i);const u=document.getElementById("plans-checkout-btn-professional");if(u){const d=e==="professional"&&i;u.disabled=d,u.textContent=d?"Current plan":"Subscribe"}const c=document.getElementById("plans-checkout-btn-power");if(c){const d=e==="power"&&i;c.disabled=d,c.textContent=d?"Current plan":"Subscribe"}}function rb(){Pp();const t=document.getElementById("credits-modal");t&&We(t)}function sb(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("credits-modal");e&&ze(e)}function Fp(t,e=!0,n=!0){if(t=["home","account","plans"].includes(t)?t:"home",document.querySelectorAll(".view[data-view]").forEach(r=>{r.dataset.view===t?(r.hidden=!1,r.removeAttribute("inert"),requestAnimationFrame(()=>{r.classList.add("is-active"),n&&r.focus({preventScroll:!0})})):(r.classList.remove("is-active"),r.setAttribute("inert","true"),setTimeout(()=>{r.classList.contains("is-active")||(r.hidden=!0)},260))}),t!=="home")nn(!1);else{const r=document.getElementById("main-stage-container");r&&r.classList.contains("visible")&&nn(!0)}if(document.querySelectorAll(".nav-link[data-view]").forEach(r=>{const s=r.dataset.view===t;r.setAttribute("aria-current",s?"page":null),s||r.removeAttribute("aria-current")}),e){const r=t==="home"?"":`#${t}`;window.location.hash!==r&&window.history.pushState({view:t},"",r||"#")}}let pd=!1;function ac(){const t=window.location.hash.replace(/^#/,"");Fp(t||"home",!1,pd),pd=!0}window.addEventListener("popstate",t=>{ac()});window.addEventListener("hashchange",()=>{ac()});window.copyResultsCode=tb;window.selectArtifact=oc;window.selectResultsSummary=Cp;window.submitResultsFeedback=nb;window.showErrorInputPanel=ib;window.hideErrorInputPanel=Ap;window.setGenerationStageVisible=nn;window.switchView=Fp;window.selectPipelineStage=jw;window.editPipelinePrompt=Xa;window.retryPipelineRun=Ip;window.openCreditsModal=rb;window.closeCreditsModal=sb; + `}).join(""),i.onclick=s=>{const o=s.target.closest(".artifact-tab");o?.dataset?.artifactId&&oc(o.dataset.artifactId)},hd()),e&&e.classList.add("visible")}function hd(){const t=document.getElementById("bundle-strip");!t||t.dataset.tabKeyboard==="bound"||(t.dataset.tabKeyboard="bound",t.addEventListener("keydown",e=>{if(e.defaultPrevented)return;const n=[document.getElementById("results-summary-tab"),...Array.from(document.querySelectorAll("#artifact-tabs .artifact-tab"))].filter(Boolean);if(!n.length||!n.includes(document.activeElement))return;let i=-1;const r=n.indexOf(document.activeElement);if(e.key==="ArrowRight")i=(r+1)%n.length;else if(e.key==="ArrowLeft")i=(r-1+n.length)%n.length;else if(e.key==="Home")i=0;else if(e.key==="End")i=n.length-1;else return;e.preventDefault();const s=n[i];if(!s)return;if(s.id==="results-summary-tab")Cp();else{const a=s.dataset.artifactId;a&&oc(a)}const o=s.id==="results-summary-tab"?document.getElementById("results-summary-tab"):document.querySelector(`#artifact-tabs .artifact-tab[data-artifact-id="${s.dataset.artifactId}"]`);o&&o.focus()}))}function no(){document.body.classList.add("results-fullscreen"),document.body.classList.add("results-with-sidebar");const t=document.getElementById("results-view"),e=document.getElementById("results-code-output"),n=document.getElementById("results-audit-output"),i=document.getElementById("results-summary-detail"),r=document.getElementById("artifact-results-split"),s=Kw(),o=jl();if(i&&(i.setAttribute("role","tabpanel"),i.setAttribute("aria-labelledby","results-summary-tab")),r){r.setAttribute("role","tabpanel");const a=s?.artifacts?.find(l=>l.id===y.selectedArtifactId);r.setAttribute("aria-labelledby",a?`artifact-tab-${a.id}`:"results-summary-tab")}if(Zw(s),Qw(s),e&&(e.textContent=""),e){const a=Ph(o);e.innerHTML=a}n&&(n.innerHTML=Xw(s)),i&&i.classList.toggle("hidden",y.resultsViewMode!=="summary"),r&&r.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function dr(t,e){nn(!0),y.selectedArtifactId||(y.selectedArtifactId=ai(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const n=document.getElementById("step3-output");n&&(n.textContent=""),no(),rn(),eb()}function eb(){const t=document.getElementById("btn-feedback-up"),e=document.getElementById("btn-feedback-down"),n=document.getElementById("results-feedback-status");t&&(t.className="feedback-btn",t.setAttribute("aria-pressed","false"),t.disabled=!1,t.removeAttribute("aria-disabled")),e&&(e.className="feedback-btn",e.setAttribute("aria-pressed","false"),e.disabled=!1,e.removeAttribute("aria-disabled")),n&&(n.textContent=""),Qa=!1}function oc(t){y.selectedArtifactId=t,y.resultsViewMode="file",no()}function Cp(){y.resultsViewMode="summary",no()}function tb(){const t=document.getElementById("btn-copy-results"),e=document.getElementById("results-copy-status"),n=jl(),i=(r,s)=>{e&&(e.textContent=r,e.classList.toggle("ok",!!s),e.classList.toggle("fail",!s))};if(!navigator.clipboard?.writeText){i("Copying isn't supported in this browser.",!1);return}navigator.clipboard.writeText(n).then(()=>{if(i("Copied to clipboard",!0),t){t.classList.add("copied");const r=t.querySelector("span");if(r){const s=r.textContent;r.textContent="Copied!",setTimeout(()=>{t.classList.remove("copied"),r.textContent=s},2e3)}}}).catch(()=>{i("Clipboard permission was denied. Select the code to copy it manually.",!1)})}let Qa=!1;async function nb(t){const e=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down"),i=document.getElementById("results-feedback-status");if(!e||!n||Qa)return;const r=l=>{i&&(i.textContent="",i.offsetWidth,i.textContent=l)},s=l=>{Qa=l,[e,n].forEach(u=>{u.disabled=l,u.setAttribute("aria-disabled",String(l))})},o=t==="up"?"thumbsUp":"thumbsDown";s(!0),r("Submitting review feedback…");const a={type:o,code:y.step2Result,input:y.step1Result};try{const l=await Yl(a.type,a.code,a.input);if(!l||l.success!==!0){s(!1),r("Review feedback could not be sent. Tap again to retry.");return}e.classList.toggle("active-up",t==="up"),n.classList.toggle("active-down",t==="down"),e.setAttribute("aria-pressed",String(t==="up")),n.setAttribute("aria-pressed",String(t==="down")),s(!1),r("Review feedback saved.")}catch{s(!1),r("Review feedback could not be sent. Tap again to retry.")}}function ib(){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 Ap(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}function nn(t){const e=document.getElementById("generation-stage");e&&(t?(e.hidden=!1,e.inert=!1,requestAnimationFrame(()=>e.classList.add("is-active"))):(e.classList.remove("is-active"),e.inert=!0,setTimeout(()=>{e.classList.contains("is-active")||(e.hidden=!0)},260)))}function Pp(){const t=q.isVerified&&!!q.email,e=ce.tier||"free",n=t&&gi(),i=!t||Tt(),s=n?"Checking…":i?_l[e]||"Free":"—",o=document.getElementById("topbar-plan");o&&(o.textContent=s);const a=document.getElementById("topbar-avatar");a&&(a.textContent=(q.email||"?")[0].toUpperCase()),Zl();const l=document.getElementById("plans-free-current");l&&l.classList.toggle("hidden",e!=="free"||!i);const u=document.getElementById("plans-checkout-btn-professional");if(u){const d=e==="professional"&&i;u.disabled=d,u.textContent=d?"Current plan":"Subscribe"}const c=document.getElementById("plans-checkout-btn-power");if(c){const d=e==="power"&&i;c.disabled=d,c.textContent=d?"Current plan":"Subscribe"}}function rb(){Pp();const t=document.getElementById("credits-modal");t&&We(t)}function sb(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("credits-modal");e&&ze(e)}function Fp(t,e=!0,n=!0){if(t=["home","account","plans"].includes(t)?t:"home",document.querySelectorAll(".view[data-view]").forEach(r=>{r.dataset.view===t?(r.hidden=!1,r.removeAttribute("inert"),requestAnimationFrame(()=>{r.classList.add("is-active"),n&&r.focus({preventScroll:!0})})):(r.classList.remove("is-active"),r.setAttribute("inert","true"),setTimeout(()=>{r.classList.contains("is-active")||(r.hidden=!0)},260))}),t!=="home")nn(!1);else{const r=document.getElementById("main-stage-container");r&&r.classList.contains("visible")&&nn(!0)}if(document.querySelectorAll(".nav-link[data-view]").forEach(r=>{const s=r.dataset.view===t;r.setAttribute("aria-current",s?"page":null),s||r.removeAttribute("aria-current")}),e){const r=t==="home"?"":`#${t}`;window.location.hash!==r&&window.history.pushState({view:t},"",r||"#")}}let pd=!1;function ac(){const t=window.location.hash.replace(/^#/,"");Fp(t||"home",!1,pd),pd=!0}window.addEventListener("popstate",t=>{ac()});window.addEventListener("hashchange",()=>{ac()});window.copyResultsCode=tb;window.selectArtifact=oc;window.selectResultsSummary=Cp;window.submitResultsFeedback=nb;window.showErrorInputPanel=ib;window.hideErrorInputPanel=Ap;window.setGenerationStageVisible=nn;window.switchView=Fp;window.selectPipelineStage=jw;window.editPipelinePrompt=Xa;window.retryPipelineRun=Ip;window.openCreditsModal=rb;window.closeCreditsModal=sb; diff --git a/dist/index.html b/dist/index.html index 63edc60..db71103 100644 --- a/dist/index.html +++ b/dist/index.html @@ -3313,7 +3313,7 @@ .send.is-busy .send-spin { animation: none; opacity: 0.6; } } - + diff --git a/e2e/stu380-deploy.spec.js b/e2e/stu380-deploy.spec.js index 651f936..eabcef3 100644 --- a/e2e/stu380-deploy.spec.js +++ b/e2e/stu380-deploy.spec.js @@ -1073,4 +1073,115 @@ test.describe("STU-380 transport outcome regressions", () => { await page.evaluate(() => window.__CCC_RESOLVE_PROJECT_PUBSPEC__({})); expect(exportCalls).toBe(4); }); + + test("a retry's success cannot clear an earlier write that may still land", async ({ page }) => { + await loadDeployHooks(page); + + const gaugeA = "class GaugeModel { final int value; GaugeModel(this.value); }"; + const gaugeB = "class GaugeModel { final String value; GaugeModel(this.value); }"; + const makeZip = async (content) => { + const zip = new JSZip(); + zip.file( + "pubspec.yaml", + "name: my_app\n\ndependencies:\n flutter:\n sdk: flutter\n", + ); + if (content) zip.file("lib/custom_code/gauge_model.dart", content); + return zip.generateAsync({ type: "base64" }); + }; + const zipEmpty = await makeZip(null); + const zipA = await makeZip(gaugeA); + const zipB = await makeZip(gaugeB); + + // landed controls what the export shows: none → A's content → B's content. + let landed = "none"; + let exportCalls = 0; + await page.route("**/exportCode", async (route) => { + exportCalls += 1; + const project_zip = + landed === "a" ? zipA : landed === "b" ? zipB : zipEmpty; + await route.fulfill({ + status: 200, + contentType: "application/json", + body: JSON.stringify({ value: { project_zip } }), + }); + }); + // First provision hangs past the bound; the second answers success. + await page.evaluate(() => { + const realFetch = window.fetch; + let provisionCalls = 0; + window.fetch = (url, ...args) => { + if (String(url).includes("deployCustomClasses")) { + provisionCalls += 1; + if (provisionCalls === 1) { + return Promise.resolve( + new Response(new ReadableStream({ start() {} }), { + status: 200, + headers: { "Content-Type": "application/x-ndjson" }, + }), + ); + } + return Promise.resolve( + new Response( + '{"event":"result","success":true}\n', + { status: 200, headers: { "Content-Type": "application/x-ndjson" } }, + ), + ); + } + return realFetch(url, ...args); + }; + }); + + const fileMapA = { + "gauge_model.dart": { + artifactName: "GaugeModel", + content: gaugeA, + type: "C", + path: "lib/custom_code/gauge_model.dart", + }, + }; + const fileMapB = { + "gauge_model.dart": { + artifactName: "GaugeModel", + content: gaugeB, + type: "C", + path: "lib/custom_code/gauge_model.dart", + }, + }; + + await page.evaluate(() => window.__CCC_RESOLVE_PROJECT_PUBSPEC__({})); + expect(exportCalls).toBe(1); + + // Provision A times out — its write may still land later. + const outcomeA = await settleAsOutcome( + page, + "__CCC_PROVISION_CUSTOM_CLASSES__", + [{ fileMap: fileMapA, uiTimeoutMs: 60 }], + ); + expect(outcomeA.name).toBe("UnconfirmedDeployError"); + + // Provision B (edited content, same path) succeeds — it proves only its + // own write; A's outstanding write stays dirty. + const outcomeB = await settleAsOutcome( + page, + "__CCC_PROVISION_CUSTOM_CLASSES__", + [{ fileMap: fileMapB, remoteFiles: {} }], + ); + expect(outcomeB.settled).toBe("resolved"); + + // An export showing B's content cannot clear A's write — it can still + // land afterwards and replace it, so nothing may be cached yet. + landed = "b"; + await page.evaluate(() => window.__CCC_RESOLVE_PROJECT_PUBSPEC__({})); + expect(exportCalls).toBe(2); + await page.evaluate(() => window.__CCC_RESOLVE_PROJECT_PUBSPEC__({})); + expect(exportCalls).toBe(3); // still uncached — A remains outstanding + + // Only an export carrying A's exact content proves that write landed; + // then the dirty set empties and caching resumes. + landed = "a"; + await page.evaluate(() => window.__CCC_RESOLVE_PROJECT_PUBSPEC__({})); + expect(exportCalls).toBe(4); + await page.evaluate(() => window.__CCC_RESOLVE_PROJECT_PUBSPEC__({})); + expect(exportCalls).toBe(4); + }); }); From 635cbe1c3d3617a28997bf96ad2f4fd0b0b2d23b Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Sun, 27 Sep 2026 18:33:40 +0000 Subject: [PATCH 16/16] fix(deploy): account writes per attempt; hold exports while a push is in flight MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two related stale-snapshot holes: - Dirty tracking now counts per (path, content) with separate uncertain / verified tallies. A confirmed provision credits a verified write instead of clearing shared state, and an export sighting consumes a verified credit before it can retire an uncertain write — so an identical retry's success can never retire an earlier timed-out attempt whose write may still land over newer edits. A late-arriving verified result (success → verified credit; provable pre-write failure → retired) also resolves its own attempt's entries. - An unconfirmed push whose request is still in flight now marks the project pending: syncCustomCodeChanges writes inside its own request handling, so once that request settles no write can arrive later — until then, exports must not be cached or a mid-push snapshot (missing the push's dependency/file changes) could poison later deploys. Co-Authored-By: Stuart Gardoll --- app.js | 160 +++++++++++++----- .../{index-CRbziOBo.js => index-Dd8Pj96z.js} | 130 +++++++------- dist/index.html | 2 +- e2e/stu380-deploy.spec.js | 150 ++++++++++++++++ 4 files changed, 330 insertions(+), 112 deletions(-) rename dist/assets/{index-CRbziOBo.js => index-Dd8Pj96z.js} (70%) diff --git a/app.js b/app.js index 3898b18..75ddcf0 100644 --- a/app.js +++ b/app.js @@ -59,6 +59,7 @@ import { import { planCustomCodeVerification } from "./src/customCodeVerification.js"; import { deployOutcomeOfStreamResult, + isPreWriteRunnerFailure, readProvisionResponse, } from "./src/provisionStream.js"; import { @@ -2670,18 +2671,23 @@ function getFileNameFromPath(filePath) { const projectSourceCache = new Map(); // File writes whose provisioning outcome is unconfirmed, per cache key — -// each dirty path holds the contents its outstanding requests tried to write. -// The request ending (bound expiry, dropped stream) is not proof the runner -// stopped: a disconnect can precede the write. While any dirty write is -// outstanding, fresh exports must not be cached — a snapshot taken mid-write -// would keep telling later deploys the file is missing, or pin content a -// still-running writer later replaces. An export clears a dirty write only -// when it contains that path with exactly the carried content — the -// authoritative observation of that write; a confirmed provision removes the -// contents it verified. A later success for the same path cannot clear an -// earlier write whose content differs — it may still land afterwards. +// each dirty path maps content -> { uncertain, verified }: `uncertain` counts +// provision attempts that may still write that content (a lost/dropped +// request is not proof the runner stopped), and `verified` credits confirmed +// writes an export sighting must consume first. An export showing content X +// can retire an uncertain X-write only when no verified X-write explains the +// observation — so a confirmed retry can never clear an earlier attempt whose +// identical write may still land over a newer edit. While any entry is +// outstanding, fresh exports are never cached. const projectSourceDirtyWrites = new Map(); +// Unconfirmed sync pushes whose underlying request is still in flight, per +// cache key. Unlike provisioning, a push writes inside its own request +// handling — once the request settles (response or dropped connection) no +// write can land afterwards, so an export taken after settlement is +// authoritative again. +const projectSourcePendingPushes = new Map(); + function projectSourceCacheKey(apiClient) { return `${apiClient.baseUrl}|${apiClient.projectId}|${apiClient.branchName}`; } @@ -2690,28 +2696,40 @@ function invalidateProjectSourceCache(apiClient) { projectSourceCache.delete(projectSourceCacheKey(apiClient)); } -function markProjectSourceDirty(apiClient, entries) { +function adjustProjectSourceDirty(apiClient, entries, delta) { const key = projectSourceCacheKey(apiClient); const dirty = projectSourceDirtyWrites.get(key) ?? new Map(); for (const { path, content } of entries) { - const writes = dirty.get(path) ?? new Set(); - writes.add(content); - dirty.set(path, writes); + const contents = dirty.get(path) ?? new Map(); + const record = contents.get(content) ?? { uncertain: 0, verified: 0 }; + if (delta.uncertain) record.uncertain += delta.uncertain; + if (delta.verified) record.verified += delta.verified; + if (record.uncertain <= 0 && record.verified <= 0) { + contents.delete(content); + } else { + contents.set(content, record); + } + if (contents.size === 0) dirty.delete(path); + else dirty.set(path, contents); } - projectSourceDirtyWrites.set(key, dirty); + if (dirty.size === 0) projectSourceDirtyWrites.delete(key); + else projectSourceDirtyWrites.set(key, dirty); } -function clearProjectSourceDirty(apiClient, entries) { +function markProjectSourceDirty(apiClient, entries) { + adjustProjectSourceDirty(apiClient, entries, { uncertain: 1 }); +} + +function markProjectSourcePushPending(apiClient) { const key = projectSourceCacheKey(apiClient); - const dirty = projectSourceDirtyWrites.get(key); - if (!dirty) return; - for (const { path, content } of entries) { - const writes = dirty.get(path); - if (!writes) continue; - writes.delete(content); - if (writes.size === 0) dirty.delete(path); - } - if (dirty.size === 0) projectSourceDirtyWrites.delete(key); + projectSourcePendingPushes.set(key, (projectSourcePendingPushes.get(key) ?? 0) + 1); +} + +function clearProjectSourcePushPending(apiClient) { + const key = projectSourceCacheKey(apiClient); + const pending = (projectSourcePendingPushes.get(key) ?? 0) - 1; + if (pending <= 0) projectSourcePendingPushes.delete(key); + else projectSourcePendingPushes.set(key, pending); } /** @@ -2767,14 +2785,25 @@ async function pushCodeWithUiTimeout( // ignored), but no further attempts may start — they could overlap a deploy // the user just retried. const stopToken = { stop: false }; + const pushWork = (async () => { + const response = await apiClient.pushCode(pushRequest, stopToken); + return parsePushCodeResponse(response); + })(); return withUiTimeout( - (async () => { - const response = await apiClient.pushCode(pushRequest, stopToken); - return parsePushCodeResponse(response); - })(), + pushWork, uiTimeoutMs, (resolve, reject) => { stopToken.stop = true; + // The in-flight request is left running; its writes can still land + // until it settles (a push writes inside its own request handling — + // settlement is the boundary after which nothing can arrive). While + // pending, the project's exports must not be cached. + invalidateProjectSourceCache(apiClient); + markProjectSourcePushPending(apiClient); + pushWork.then( + () => clearProjectSourcePushPending(apiClient), + () => clearProjectSourcePushPending(apiClient), + ); reject( new UnconfirmedDeployError( "FlutterFlow did not answer the sync in time — the push may still " + @@ -2841,8 +2870,12 @@ async function provisionMissingCodeFiles( // any response is still an unknown outcome — the POST may have reached the // server — so it maps to unconfirmed, not failed. let result; + // Kept outside the try: a verified result that arrives after the bound + // resolves this attempt's dirty entries (success → verified credit, + // provable pre-write failure → retired). + let provisionWork; try { - const provisionWork = (async () => { + provisionWork = (async () => { let response; try { response = await fetch(FLUTTERFLOW_CLASS_PROVISION_ENDPOINT, { @@ -2938,20 +2971,41 @@ async function provisionMissingCodeFiles( if (error instanceof UnconfirmedDeployError) { invalidateProjectSourceCache(apiClient); // Every file this request may have written stays dirty until a fresh - // export shows the same content — the runner can keep working after the - // request is lost or the bound expires, and its settlement is not proof - // the write finished (or started). While dirty, exports are never - // cached. + // export observes that exact content with no verified write to explain + // it — the runner can keep working after the request is lost or the + // bound expires. While dirty, exports are never cached. markProjectSourceDirty(apiClient, missingCodeFiles); + // A result event that arrives after the bound still proves this + // attempt's outcome: success converts its writes to verified (the sighting + // they produce is then attributable), a provable pre-write failure + // retires them outright. + provisionWork?.then( + (late) => { + if (late?.finalResultReceived && late.success) { + adjustProjectSourceDirty(apiClient, missingCodeFiles, { + uncertain: -1, + verified: 1, + }); + } else if ( + late?.finalResultReceived && + isPreWriteRunnerFailure(late) + ) { + adjustProjectSourceDirty(apiClient, missingCodeFiles, { + uncertain: -1, + }); + } + }, + () => {}, + ); } throw error; } invalidateProjectSourceCache(apiClient); - // A confirmed result proves this request's writes landed — only its own - // contents clear; an earlier unconfirmed write of different content to the - // same path may still be in flight and stays dirty. - clearProjectSourceDirty(apiClient, missingCodeFiles); + // A confirmed result credits this request's writes as verified: export + // sightings of that content are attributable to it, so earlier uncertain + // writes of the same path stay dirty until their own landing is observed. + adjustProjectSourceDirty(apiClient, missingCodeFiles, { verified: 1 }); if (result.verificationSkipped) { console.warn(`[custom class deploy] ${result.verificationSkipped}`); @@ -3021,18 +3075,32 @@ async function resolveProjectPubspec(apiClient, newDependencies = {}) { const dirty = projectSourceDirtyWrites.get(cacheKey); if (dirty) { - // This fresh export is the authoritative read: a dirty write clears - // only when the export contains its path with exactly the content that - // write carried — different content means another writer may still - // overwrite it, so the entry (and the cache) stays out of play. - for (const [path, writes] of [...dirty]) { + // This fresh export is the authoritative read: an observed content + // first consumes a verified write credit (the sighting is explained by + // a confirmed provision), and only retires an uncertain write when no + // verified write could have produced it. + for (const [path, contents] of [...dirty]) { const observed = projectSource.files.get(path); - if (observed !== undefined) writes.delete(observed); - if (writes.size === 0) dirty.delete(path); + if (observed !== undefined) { + const record = contents.get(observed); + if (record) { + if (record.verified > 0) record.verified -= 1; + else record.uncertain -= 1; + if (record.uncertain <= 0 && record.verified <= 0) { + contents.delete(observed); + } + } + } + if (contents.size === 0) dirty.delete(path); } if (dirty.size === 0) projectSourceDirtyWrites.delete(cacheKey); } - if (!projectSourceDirtyWrites.has(cacheKey)) { + // Pending pushes keep exports uncached too: a request still in flight can + // still land its writes. + if ( + !projectSourceDirtyWrites.has(cacheKey) && + !projectSourcePendingPushes.has(cacheKey) + ) { projectSourceCache.set(cacheKey, projectSource); } } diff --git a/dist/assets/index-CRbziOBo.js b/dist/assets/index-Dd8Pj96z.js similarity index 70% rename from dist/assets/index-CRbziOBo.js rename to dist/assets/index-Dd8Pj96z.js index e8039ea..a26a016 100644 --- a/dist/assets/index-CRbziOBo.js +++ b/dist/assets/index-Dd8Pj96z.js @@ -1,8 +1,8 @@ -(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const s of r)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function n(r){const s={};return r.integrity&&(s.integrity=r.integrity),r.referrerPolicy&&(s.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?s.credentials="include":r.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function i(r){if(r.ep)return;r.ep=!0;const s=n(r);fetch(r.href,s)}})();var w=typeof window<"u"?window:void 0,Ne=typeof globalThis<"u"?globalThis:w,He=Ne?.navigator,P=Ne?.document,me=Ne?.location,el=Ne?.fetch,Vo=Ne!=null&&Ne.XMLHttpRequest&&"withCredentials"in new Ne.XMLHttpRequest?Ne.XMLHttpRequest:void 0,pc=Ne?.AbortController,Op=Ne?.CompressionStream,Ge=He?.userAgent;function gd(){return!(!w||w.navigator.onLine===!1)}var _i=typeof globalThis<"u"?globalThis:w;_i&&typeof self>"u"&&(_i.self=_i),_i&&typeof File>"u"&&(_i.File=function(){});var B=w??{},ne={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function gc(t,e,n,i,r,s,o){try{var a=t[s](o),l=a.value}catch(u){return void n(u)}a.done?e(l):Promise.resolve(l).then(i,r)}function se(t){return function(){var e=this,n=arguments;return new Promise((function(i,r){var s=t.apply(e,n);function o(l){gc(s,i,r,o,a,"next",l)}function a(l){gc(s,i,r,o,a,"throw",l)}o(void 0)}))}}function I(){return I=Object.assign?Object.assign.bind():function(t){for(var e=1;arguments.length>e;e++){var n=arguments[e];for(var i in n)({}).hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},I.apply(null,arguments)}function md(t,e){if(t==null)return{};var n={};for(var i in t)if({}.hasOwnProperty.call(t,i)){if(e.indexOf(i)!==-1)continue;n[i]=t[i]}return n}var mc=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function vc(t){return typeof t=="string"||t}function _c(t){return typeof t=="string"?t:void 0}var yi,Bp=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],Ut=(function(t){return t.AnonymousId="anonymous_id",t.DistinctId="distinct_id",t.Props="props",t.EnablePersonProcessing="enable_person_processing",t.PersonMode="person_mode",t.FeatureFlagDetails="feature_flag_details",t.FeatureFlags="feature_flags",t.FeatureFlagPayloads="feature_flag_payloads",t.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",t.BootstrapFeatureFlags="bootstrap_feature_flags",t.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",t.OverrideFeatureFlags="override_feature_flags",t.Queue="queue",t.AiQueue="ai_queue",t.LogsQueue="logs_queue",t.OptedOut="opted_out",t.SessionId="session_id",t.SessionStartTimestamp="session_start_timestamp",t.SessionLastTimestamp="session_timestamp",t.PersonProperties="person_properties",t.GroupProperties="group_properties",t.InstalledAppBuild="installed_app_build",t.InstalledAppVersion="installed_app_version",t.SessionReplay="session_replay",t.PushRegistered="push_registered",t.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",t.SurveyLastSeenDate="survey_last_seen_date",t.SurveysSeen="surveys_seen",t.Surveys="surveys",t.RemoteConfig="remote_config",t.FlagsEndpointWasHit="flags_endpoint_was_hit",t.DeviceId="device_id",t})({}),yc=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),Dp=["$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"],jp=["token"],vd="NativeGzipValidationError",Go=t=>t.length>=2&&t[0]===31&&t[1]===139,wc=(t,e)=>t===yc.GZipJS||e===yc.GZipJS||e==="gzip",bc=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=vd,e},Up=(function(){var t=se((function*(e,n){18>e.size&&gr("too-short");var i=new Uint8Array(yield e.slice(0,10).arrayBuffer());Go(i)&&i[2]===8||gr("invalid-header");var r=new DataView(yield e.slice(e.size-8).arrayBuffer());r.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(yi)return yi;yi=[];for(var c=0;256>c;c++){for(var d=c,f=0;8>f;f++)d=1&d?3988292384^d>>>1:d>>>1;yi[c]=d>>>0}return yi})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(n)&&gr("invalid-crc");var s=n.length>>>0;r.getUint32(4,!0)!==s&&gr("invalid-size")}));return function(e,n){return t.apply(this,arguments)}})();function Ko(){return Ko=se((function*(t,e,n){e===void 0&&(e=!0);try{var i=new TextEncoder().encode(t),r=new globalThis.CompressionStream("gzip"),s=r.writable.getWriter(),o=s.write(i).then((()=>s.close())).catch((function(){var u=se((function*(c){try{yield s.abort(c)}catch{}throw c}));return function(c){return u.apply(this,arguments)}})()),a=new Response(r.readable).blob(),l=(yield Promise.all([a,o]))[0];return yield Up(l,i),l}catch(u){if(n!=null&&n.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),Ko.apply(this,arguments)}var Hp=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],Ec=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var n=t.toLowerCase();return Hp.concat(e).some((i=>{var r=i.toLowerCase();return n.indexOf(r)!==-1}))};function j(t,e){return t.indexOf(e)!==-1}var Is=function(t){return t.trim()},Yo=function(t){return t.replace(/^\$/,"")};function _d(t){var e,n=[];return(e=JSON.stringify(t,(function(i,r){if(typeof r=="bigint")return r.toString();if(typeof r!="function"&&typeof r!="symbol"){if(r instanceof Error)return{name:r.name,message:r.message,stack:r.stack};if(r&&typeof r=="object"){for(;n.length>0&&n[n.length-1]!==this;)n.pop();if(n.includes(r))return"[Circular]";n.push(r)}return r}})))!==null&&e!==void 0?e:"null"}var yd=Object.prototype,wd=yd.hasOwnProperty,ks=yd.toString,U=Array.isArray||function(t){return ks.call(t)==="[object Array]"},je=t=>typeof t=="function",he=t=>t===Object(t)&&!U(t),Kt=t=>{if(he(t)){for(var e in t)if(wd.call(t,e))return!1;return!0}return!1},C=t=>t===void 0,X=t=>ks.call(t)=="[object String]",Jo=t=>X(t)&&t.trim().length===0,Ye=t=>t===null,H=t=>C(t)||Ye(t),ke=t=>ks.call(t)=="[object Number]"&&t==t,Dt=t=>ke(t)&&t>0,mt=t=>ks.call(t)==="[object Boolean]",Wp=t=>t instanceof FormData,zp=t=>j(Dp,t),qp=t=>j(jp,t);function bd(t){return t===null||typeof t!="object"}function Wr(t,e){return{}.toString.call(t)==="[object "+e+"]"}function tl(t){return typeof Event<"u"&&Ed(t,Event)}function Ed(t,e){try{return t instanceof e}catch{return!1}}var Vp=[!0,"true",1,"1","yes"],ho=t=>j(Vp,t),Gp=[!1,"false",0,"0","no"];function At(t,e,n,i,r){return e>n&&(i.warn("min cannot be greater than max."),e=n),ke(t)?t>n?(i.warn(" cannot be greater than max: "+n+". Using max value instead."),n):e>t?(i.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(i.warn(" must be a number. using max or fallback. max: "+n+", fallback: "+r),At(r||n,e,n,i))}class Kp{constructor(e){this.tt={},this.et=e.et,this.it=At(e.bucketSize,0,100,e.rt),this.nt=At(e.refillRate,0,this.it,e.rt),this.st=At(e.refillInterval,0,864e5,e.rt)}ot(e,n){var i=Math.floor((n-e.lastAccess)/this.st);i>0&&(e.tokens=Math.min(e.tokens+i*this.nt,this.it),e.lastAccess=e.lastAccess+i*this.st)}consumeRateLimit(e){var n,i=Date.now(),r=String(e),s=this.tt[r];return s?this.ot(s,i):this.tt[r]=s={tokens:this.it,lastAccess:i},s.tokens===0||(s.tokens--,s.tokens===0&&((n=this.et)==null||n.call(this,e)),s.tokens===0)}stop(){this.tt={}}}var rt="Mobile",zr="iOS",Yt="Android",ti="Tablet",Sd=Yt+" "+ti,xd="iPad",Id="Apple",kd=Id+" Watch",Di="Safari",ni="BlackBerry",Cd="Samsung",Ad=Cd+"Browser",Pd=Cd+" Internet",Pn="Chrome",Yp=Pn+" OS",Fd=Pn+" "+zr,nl="Internet Explorer",Rd=nl+" "+rt,il="Opera",Jp=il+" Mini",rl="Edge",Td="Microsoft "+rl,Xn="Firefox",$d=Xn+" "+zr,Ki="Nintendo",Yi="PlayStation",Qn="Xbox",Md=Yt+" "+rt,Ld=rt+" "+Di,Fi="Windows",Zo=Fi+" Phone",Sc="Nokia",Xo="Ouya",Nd="Generic",Zp=Nd+" "+rt.toLowerCase(),Od=Nd+" "+ti.toLowerCase(),Qo="Konqueror",Bd="Oculus Browser",qr="Vivaldi",Dd="Yandex",Vr="Whale",ea="DuckDuckGo",jd="Pale Moon",Gr="Waterfox",ji="Brave",Ud="Google Search App",we="(\\d+(\\.\\d+)?)",po=new RegExp("Version/"+we),Xp=new RegExp(Qn,"i"),Qp=new RegExp(Yi+" \\w+","i"),eg=new RegExp(Ki+" \\w+","i"),sl=new RegExp(ni+"|PlayBook|BB10","i"),tg={"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"},Hd=function(t,e,n,i){e=e||"";var r=(function(s){return s!=null&&s.brave?ji:null})(n);return r||(i!=null&&i.detectGoogleSearchApp&&j(t,"GSA/")?Ud:j(t," OPR/")&&j(t,"Mini")?Jp:j(t," OPR/")?il:sl.test(t)?ni:j(t,"IE"+rt)||j(t,"WPDesktop")?Rd:j(t,"OculusBrowser")?Bd:j(t,Ad)?Pd:j(t,rl)||j(t,"Edg/")?Td:j(t,qr+"/")?qr:j(t,"YaBrowser/")?Dd:j(t,Vr+"/")?Vr:j(t,ea+"/")||j(t,"Ddg/")?ea:j(t,"FBIOS")?"Facebook "+rt:j(t,"UCWEB")||j(t,"UCBrowser")?"UC Browser":j(t,"CriOS")?Fd:j(t,"CrMo")||j(t,Pn)?Pn:j(t,Yt)&&j(t,Di)?Md:j(t,"FxiOS")?$d:j(t.toLowerCase(),Qo.toLowerCase())?Qo:j(t,ji+"/")?ji:((s,o)=>o&&j(o,Id)||(function(a){return j(a,Di)&&!j(a,Pn)&&!j(a,Yt)})(s))(t,e)?j(t,rt)?Ld:Di:j(t,"PaleMoon/")?jd:j(t,Gr+"/")?Gr:j(t,Xn)?Xn:j(t,"MSIE")||j(t,"Trident/")?nl:j(t,"Gecko")?Xn:"")},ng={[Rd]:[new RegExp("rv:"+we)],[Td]:[new RegExp(rl+"?\\/"+we)],[Pn]:[new RegExp("("+Pn+"|CrMo)\\/"+we)],[Fd]:[new RegExp("CriOS\\/"+we)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+we)],[Di]:[po],[Ld]:[po],[il]:[new RegExp("(Opera|OPR)\\/"+we)],[Xn]:[new RegExp(Xn+"\\/"+we)],[$d]:[new RegExp("FxiOS\\/"+we)],[Qo]:[new RegExp("Konqueror[:/]?"+we,"i")],[ni]:[new RegExp(ni+" "+we),po],[Md]:[new RegExp("android\\s"+we,"i")],[Pd]:[new RegExp(Ad+"\\/"+we)],[Bd]:[new RegExp("OculusBrowser\\/"+we)],[qr]:[new RegExp(qr+"\\/"+we)],[Dd]:[new RegExp("YaBrowser\\/"+we)],[Vr]:[new RegExp(Vr+"\\/"+we)],[ji]:[new RegExp(ji+"\\/"+we)],[ea]:[new RegExp("(DuckDuckGo|Ddg)\\/"+we)],[jd]:[new RegExp("PaleMoon\\/"+we)],[Gr]:[new RegExp(Gr+"\\/"+we)],[Ud]:[new RegExp("GSA\\/"+we)],[nl]:[new RegExp("(rv:|MSIE )"+we)],Mozilla:[new RegExp("rv:"+we)]},ig=function(t,e,n,i){var r=Hd(t,e,n,i),s=ng[r];if(C(s))return null;for(var o=0;s.length>o;o++){var a=t.match(s[o]);if(a)return parseFloat(a[a.length-2])}return null},xc=[[new RegExp(Qn+"; "+Qn+" (.*?)[);]","i"),t=>[Qn,t&&t[1]||""]],[new RegExp(Ki,"i"),[Ki,""]],[new RegExp(Yi,"i"),[Yi,""]],[sl,[ni,""]],[new RegExp(Fi,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Zo,""];if(new RegExp(rt).test(e)&&!/IEMobile\b/.test(e))return[Fi+" "+rt,""];var n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){var i=tg[n[1]]||"";return/arm/i.test(e)&&(i="RT"),[Fi,i]}return[Fi,""]}],[/((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=C(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+Yt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Yt+")","i"),t=>t&&t[2]?[Yt,[t[2],t[3],t[4]||"0"].join(".")]:[Yt,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{var e=["Mac OS X",""];return t&&t[1]&&(e[1]=[t[1],t[2],t[3]||"0"].join(".")),e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[Yp,""]],[/Linux|debian/i,["Linux",""]]],Ic=function(t){return eg.test(t)?Ki:Qp.test(t)?Yi:Xp.test(t)?Qn:new RegExp(Xo,"i").test(t)?Xo:new RegExp("("+Zo+"|WPDesktop)","i").test(t)?Zo:/iPad/.test(t)?xd:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?kd:sl.test(t)?ni:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(Sc,"i").test(t)?Sc:/(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(rt).test(t)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(t)||/pixel[\daxl ]{1,6}/i.test(t)&&!/pixel c/i.test(t)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(t)||/lmy47v/i.test(t)&&!/QTAQZ3/i.test(t)?Yt:Sd:new RegExp("(pda|"+rt+")","i").test(t)?Zp:new RegExp(ti,"i").test(t)&&!new RegExp(ti+" pc","i").test(t)?Od:""},rg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function kc(t,e){return typeof(n=t)=="string"&&rg.test(n)?t:e();var n}function fn(t){return t&&t.split("#")[0]}function ol(t,e){var n=setTimeout(t,e);return n?.unref&&n?.unref(),n}function Cc(t,e,n){return Wd.apply(this,arguments)}function Wd(){return(Wd=se((function*(t,e,n){var i;try{return yield Promise.race([t,new Promise(((r,s)=>{i=ol((()=>{try{n?.(),r()}catch(o){s(o)}}),e)}))])}finally{clearTimeout(i)}}))).apply(this,arguments)}var sg=t=>t instanceof Error,zd={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}},og=zd.info;function qd(t){if(mt(t))return{boolValue:t};if(typeof t=="number")return Number.isFinite(t)?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:{stringValue:String(t)};if(typeof t=="string")return{stringValue:t};if(U(t))return{arrayValue:{values:t.map((e=>qd(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function Kr(t){var e=[];for(var n in t){var i=t[n];Ye(i)||C(i)||e.push({key:n,value:qd(i)})}return e}function ag(t,e){var n=zd[t.level||"info"]||og,i=n.text,r=n.number,s=String(Date.now())+"000000",o={};e.distinctId&&(o.posthogDistinctId=e.distinctId),e.sessionId&&(o.sessionId=e.sessionId),e.windowId&&(o["window.id"]=e.windowId),H(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),H(e.lastActivityTimestamp)||(o.lastActivityTimestamp=String(e.lastActivityTimestamp)),e.currentUrl&&(o["url.full"]=e.currentUrl),e.screenName&&(o["screen.name"]=e.screenName),e.appState&&(o["app.state"]=e.appState),e.activeFeatureFlags&&e.activeFeatureFlags.length>0&&(o.feature_flags=e.activeFeatureFlags);var a=I({},o,t.attributes||{}),l={timeUnixNano:s,observedTimeUnixNano:s,severityNumber:r,severityText:i,body:{stringValue:t.body},attributes:Kr(a)};return t.trace_id&&(l.traceId=t.trace_id),t.span_id&&(l.spanId=t.span_id),C(t.trace_flags)||(l.flags=t.trace_flags),l}function Vd(t,e,n){return I({},t.resourceAttributes,{"service.name":t.serviceName||"unknown_service"},t.environment&&{"deployment.environment":t.environment},t.serviceVersion&&{"service.version":t.serviceVersion},{"telemetry.sdk.name":e,"telemetry.sdk.version":n})}function Gd(t,e,n,i){return{resourceLogs:[{resource:{attributes:Kr(e)},scopeLogs:[{scope:{name:n,version:i},logRecords:t}]}]}}let lg=class{constructor(t,e,n,i,r,s,o){var a;s===void 0&&(s=()=>Promise.resolve()),this._instance=t,this.Ne=e,this.rt=n,this.ut=i,this.ht=r,this.dt=s,this.vt=o,this.ct=null,this.ft=0,this.yt=0,this.bt=0,this._t=0,this.wt=!1,this.kt=e.maxBufferSize,this.xt=Math.max((a=e.maxQueueSize)!==null&&a!==void 0?a:e.maxBufferSize,e.maxBufferSize),this.St=e.flushIntervalMs,this.Ct=e.maxBatchRecordsPerPost,this.Mt=e.rateCapWindowMs,this.Tt=e.maxLogsPerInterval}reset(){this.Et(),this.ct=null,this.bt=0,this._t=0,this.wt=!1,this.ft=0,this.yt=0,this.Ct=this.Ne.maxBatchRecordsPerPost}onReconnect(){this.yt=0,this.It()}captureLog(t){if(!this._instance.isDisabled&&!this._instance.optedOut&&t!=null&&t.body){var e=this.Pt(t);if(e!==null)if(e.body){if(this.Rt()){var n={record:ag(e,this.ut())};this.ht((()=>this.At(n)))}}else this.rt.info("Log was rejected in beforeSend function")}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Log was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for log:",o),null}return i}Rt(){if(this.Tt===void 0)return!0;var t=Date.now(),e=t-this.bt;return this.Mt>e&&e>=0||(this.bt=t,this._t=0,this.wt=!1),this.Tt>this._t?(this._t++,!0):(this.wt||(this.rt.warn("captureLog dropping logs: exceeded "+this.Tt+" logs per "+this.Mt+"ms"),this.wt=!0),!1)}flush(){var t=this;return se((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return se((function*(){var e;t.Et();var n=(e=t._instance.getPersistedProperty(Ut.LogsQueue))!==null&&e!==void 0?e:[];if(n.length!==0)for(var i=n.length,r=0;n.length>0&&i>r;){var s,o;t.ft=0;var a=Math.min(n.length,t.Ct),l=n.slice(0,a),u=Gd(l.map((d=>d.record)),t.Lt(),(s=t.vt)!==null&&s!==void 0?s:t._instance.getLibraryId(),t._instance.getLibraryVersion()),c=yield t._instance.Ot(u);if(c.kind==="too-large"&&l.length>1)t.Ct=Math.max(1,Math.floor(l.length/2)),t.rt.warn("Received 413 when sending logs batch of size "+l.length+", reducing batch size to "+t.Ct);else if(c.kind==="retry-later"||(c.kind==="too-large"?t.rt.warn("Dropping a single log record after 413 with batch size 1 — the record is larger than the server cap and cannot be split further."):c.kind==="ok"&&t.Ne.maxBatchRecordsPerPost>t.Ct&&(t.Ct=Math.min(t.Ne.maxBatchRecordsPerPost,t.Ct+1)),yield t.Dt(l.length),n=(o=t._instance.getPersistedProperty(Ut.LogsQueue))!==null&&o!==void 0?o:[],r+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return se((function*(){var n,i=Math.max(0,t-e.ft),r=(n=e._instance.getPersistedProperty(Ut.LogsQueue))!==null&&n!==void 0?n:[];e._instance.setPersistedProperty(Ut.LogsQueue,r.slice(i)),yield e.dt()}))()}Lt(){return Vd(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var n=(e=this._instance.getPersistedProperty(Ut.LogsQueue))!==null&&e!==void 0?e:[];this.xt>n.length||(n.shift(),this.ft++,this.rt.info("Logs queue is full, dropping oldest record.")),n.push(t),this._instance.setPersistedProperty(Ut.LogsQueue,n),this.kt>n.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=ol((()=>{this.Nt=void 0,this.It()}),t))}qt(){var t=Math.min(Math.max(0,this.yt-1),6);return this.St*Math.pow(2,t)}jt(){var t=this._instance.getPersistedProperty(Ut.LogsQueue);return!!t&&t.length>0}shutdown(t){var e=this;return se((function*(){e.Et();var n=e.flush().catch((()=>{}));t!==void 0?yield Cc(n,t):yield n}))()}flushWithTimeout(t){var e=this;return se((function*(){var n=e.flush();yield Cc(n,t,(()=>{n.catch((()=>{}))}))}))()}It(){this.flush().then((()=>{this.yt=0}),(t=>{this.yt++,this.rt.error("PostHog logs flush failed:",t)})).finally((()=>{!this._instance.isDisabled&&this.jt()&&this.$t(this.qt())}))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}};var go=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function Ac(t){return String(t)+"000000"}function Pc(t,e,n,i){var r="";return i&&(r=Object.keys(i).sort().map((s=>JSON.stringify(s)+":"+JSON.stringify(i[s]))).join(",")),t+"\0"+e+"\0"+(n??"")+"\0"+r}let cg=class{constructor(t,e,n){this._instance=t,this.Ne=e,this.rt=n,this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Wt=0}count(t,e,n){e===void 0&&(e=1),this.Vt({name:t,type:"count",value:e,unit:n?.unit,attributes:n?.attributes})}gauge(t,e,n){this.Vt({name:t,type:"gauge",value:e,unit:n?.unit,attributes:n?.attributes})}histogram(t,e,n){this.Vt({name:t,type:"histogram",value:e,unit:n?.unit,attributes:n?.attributes})}flush(){var t=this,e=this.ct,n=(function(){var r=se((function*(){e&&(yield e.catch((()=>{}))),yield t.Zt()}));return function(){return r.apply(this,arguments)}})(),i=n().finally((()=>{this.ct===i&&(this.ct=null)}));return this.ct=i,i}drainWindow(){if(this.Bt.size===0)return null;var t=this.Bt;return this.Bt=new Map,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Gt(t)}reset(){this.Wt++,this.Et(),this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set}Vt(t){if(!this._instance.isDisabled&&!this._instance.optedOut){var e=this.Pt(t);if(e!==null)if(e.name&&typeof e.name=="string")if(typeof e.value=="number"&&Number.isFinite(e.value))if(e.type==="count"&&0>e.value)this.rt.warn("Dropping count '"+e.name+"': counters are monotonic, value must be >= 0");else{var n,i;try{n=e.attributes?I({},e.attributes):void 0,i=Pc(e.type,e.name,e.unit,n)}catch(o){return void this.rt.warn("Dropping metric '"+e.name+"': attributes could not be serialized",o)}var r=this.Bt.get(i);if(!r){if(!this.Qt())return;r={name:e.name,type:e.type,unit:e.unit,attributes:n,windowStartMs:Date.now()},this.Bt.set(i,r)}var s=this.Ut.get(e.name);s===void 0?this.Ut.set(e.name,e.type):s===e.type||this.zt.has(e.name)||(this.zt.add(e.name),this.rt.warn("Metric name '"+e.name+"' is already used as a "+s+"; recording it as a "+e.type+" too will blend both series in charts. Use a distinct name.")),this.Kt(r,e.value),this.$t()}else this.rt.warn("Dropping metric '"+e.name+"': value must be a finite number");else this.rt.warn("Dropping metric with empty name")}}Qt(){return this.Ne.maxSeriesPerFlush>this.Bt.size||(this.Ht||(this.Ht=!0,this.rt.warn("Metric series cap reached ("+this.Ne.maxSeriesPerFlush+" per flush window); dropping new series until the next flush. Reduce attribute cardinality.")),!1)}Kt(t,e){var n;switch(t.type){case"count":t.total=((n=t.total)!==null&&n!==void 0?n:0)+e;break;case"gauge":t.last=e;break;case"histogram":t.hist||(t.hist={count:0,sum:0,min:e,max:e,bucketCounts:new Array(go.length+1).fill(0)});var i=t.hist;i.count+=1,i.sum+=e,i.min=Math.min(i.min,e),i.max=Math.max(i.max,e),i.bucketCounts[(function(r,s){for(var o=0;s.length>o;o++)if(s[o]>=r)return o;return s.length})(e,go)]+=1}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Metric was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for metric:",o),null}return i}$t(){this.Nt||(this.Nt=ol((()=>{this.Nt=void 0,this.flush().catch((t=>{this.rt.error("Metrics flush failed:",t)}))}),this.Ne.flushIntervalMs))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}Zt(){var t=this;return se((function*(){if(t.Bt.size!==0){var e=t.Bt;t.Bt=new Map,t.Ht=!1,t.Ut=new Map,t.zt=new Set;var n=t.Wt,i=yield t._instance.Jt(t.Gt(e));if(n===t.Wt)switch(i.kind){case"ok":return;case"retry-later":return t.Yt(e),void t.$t();case"too-large":return void t.rt.warn("Metrics batch exceeded the server size limit and was dropped");case"fatal":return void t.rt.error("Failed to send metrics batch:",i.error)}}}))()}Gt(t){return e=this.Xt(t),n=(function(s,o,a){return I({},s.resourceAttributes,{"service.name":s.serviceName||"unknown_service"},s.environment&&{"deployment.environment":s.environment},s.serviceVersion&&{"service.version":s.serviceVersion},{"telemetry.sdk.name":o,"telemetry.sdk.version":a})})(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion()),i=this._instance.getLibraryId(),r=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:Kr(n)},scopeMetrics:[{scope:{name:i,version:r},metrics:e}]}]};var e,n,i,r}Xt(t){var e=Ac(Date.now()),n=new Map;for(var i of t.values()){var r,s=Pc(i.type,i.name,i.unit,void 0),o=n.get(s);o||(o=I({name:i.name},i.unit&&{unit:i.unit}),i.type==="count"?o.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:i.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:1,dataPoints:[]},n.set(s,o));var a=Kr((r=i.attributes)!==null&&r!==void 0?r:{}),l=Ac(i.windowStartMs);if(i.type==="count"){var u,c={attributes:a,startTimeUnixNano:l,timeUnixNano:e,asDouble:(u=i.total)!==null&&u!==void 0?u:0};o.sum.dataPoints.push(c)}else if(i.type==="gauge"){var d,f={attributes:a,timeUnixNano:e,asDouble:(d=i.last)!==null&&d!==void 0?d:0};o.gauge.dataPoints.push(f)}else i.hist&&o.histogram.dataPoints.push({attributes:a,startTimeUnixNano:l,timeUnixNano:e,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:go})}return Array.from(n.values())}Yt(t){var e,n;for(var i of t){var r=i[0],s=i[1],o=this.Bt.get(r);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,s.windowStartMs),o.type){case"count":o.total=((e=o.total)!==null&&e!==void 0?e:0)+((n=s.total)!==null&&n!==void 0?n:0);break;case"gauge":break;case"histogram":if(s.hist)if(o.hist){o.hist.count+=s.hist.count,o.hist.sum+=s.hist.sum,o.hist.min=Math.min(o.hist.min,s.hist.min),o.hist.max=Math.max(o.hist.max,s.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=s.hist.bucketCounts[a]}else o.hist=s.hist}else this.Qt()&&this.Bt.set(r,s)}}};var mr,Fc,mo;function ug(t){var e=globalThis._posthogChunkIds;if(e){var n=Object.keys(e);return mo&&n.length===Fc||(Fc=n.length,mo=n.reduce(((i,r)=>{mr||(mr={});var s=mr[r];if(s)i[s[0]]=s[1];else for(var o=t(r),a=o.length-1;a>=0;a--){var l=o[a],u=l?.filename,c=e[r];if(u&&c){i[u]=c,mr[r]=[u,c];break}}return i}),{})),mo}}class dg{constructor(e,n,i){i===void 0&&(i=[]),this.coercers=e,this.stackParser=n,this.modifiers=i}buildFromUnknown(e,n){n===void 0&&(n={});var i=n&&n.mechanism||{handled:!0,type:"generic"},r=this.buildCoercingContext(i,n,0).apply(e),s=this.buildParsingContext(n),o=this.parseStacktrace(r,s);return{$exception_list:this.convertToExceptionList(o,i),$exception_level:"error"}}modifyFrames(e){var n=this;return se((function*(){for(var i of e)i.stacktrace&&i.stacktrace.frames&&U(i.stacktrace.frames)&&(i.stacktrace.frames=yield n.applyModifiers(i.stacktrace.frames));return e}))()}coerceFallback(e){var n;return{type:"Error",value:"Unknown error",stack:(n=e.syntheticException)==null?void 0:n.stack,synthetic:!0}}parseStacktrace(e,n){var i,r;return e.cause!=null&&(i=this.parseStacktrace(e.cause,n)),e.stack!=""&&e.stack!=null&&(r=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?n.skipFirstLines:0),n.chunkIdMap)),I({},e,{cause:i,stack:r})}applyChunkIds(e,n){return e.map((i=>(i.filename&&n&&(i.chunk_id=n[i.filename]),i)))}applyCoercers(e,n){for(var i of this.coercers)if(i.match(e))return i.coerce(e,n);return this.coerceFallback(n)}applyModifiers(e){var n=this;return se((function*(){var i=e;for(var r of n.modifiers)i=yield r(i);return i}))()}convertToExceptionList(e,n){var i,r,s,o={type:e.type,value:e.value,mechanism:{type:(i=n.type)!==null&&i!==void 0?i:"generic",handled:(r=n.handled)===null||r===void 0||r,synthetic:(s=e.synthetic)!==null&&s!==void 0&&s}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,I({},n,{handled:!0}))),a}buildParsingContext(e){var n;return{chunkIdMap:ug(this.stackParser),skipFirstLines:(n=e.skipFirstLines)!==null&&n!==void 0?n:1}}buildCoercingContext(e,n,i){i===void 0&&(i=0);var r=(s,o)=>{if(4>=o){var a=this.buildCoercingContext(e,n,o);return this.applyCoercers(s,a)}};return I({},n,{syntheticException:i==0?n.syntheticException:void 0,mechanism:e,apply:s=>r(s,i),next:s=>r(s,i+1)})}}var ii="?";function ta(t,e,n,i,r){var s={platform:t,filename:e,function:n===""?ii:n,in_app:!0};return C(i)||(s.lineno=i),C(r)||(s.colno=r),s}var Kd=(t,e)=>{var n=t.indexOf("safari-extension")!==-1,i=t.indexOf("safari-web-extension")!==-1;return n||i?[t.indexOf("@")!==-1?t.split("@")[0]:ii,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},fg=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,hg=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,pg=/\((\S*)(?::(\d+))(?::(\d+))\)/,gg=(t,e)=>{var n=fg.exec(t);if(n)return ta(e,n[1],ii,+n[2],+n[3]);var i=hg.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var r=pg.exec(i[2]);r&&(i[2]=r[1],i[3]=r[2],i[4]=r[3])}var s=Kd(i[1]||ii,i[2]);return ta(e,s[1],s[0],i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},mg=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,vg=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,_g=(t,e)=>{var n=mg.exec(t);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){var i=vg.exec(n[3]);i&&(n[1]=n[1]||"eval",n[3]=i[1],n[4]=i[2],n[5]="")}var r=n[3],s=n[1]||ii,o=Kd(s,r);return ta(e,r=o[1],s=o[0],n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},Rc=/\(error: (.*)\)/;class yg{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,n){var i=X(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:i?e.stack:void 0,cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var n=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?n+": "+e.message:n}isDOMException(e){return Wr(e,"DOMException")}isDOMError(e){return Wr(e,"DOMError")}}class wg{match(e){return(function(n){switch({}.toString.call(n)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return Ed(n,Error)}})(e)}coerce(e,n){return{type:this.getType(e),value:this.getMessage(e,n),stack:this.getStack(e),cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,n){var i=e.message;return String(i.error&&typeof i.error.message=="string"?i.error.message:i)}getStack(e){return e.stacktrace||e.stack||void 0}}class bg{constructor(){}match(e){return!!Wr(e,"ErrorEvent")&&(e.error!=null||this.fe(e))}coerce(e,n){var i;if(e.error!=null)return n.apply(e.error);var r=n.apply(e.message);return I({},r,{stack:(i=this.pe(e))!==null&&i!==void 0?i:r.stack,synthetic:!0})}fe(e){return X(e.message)&&e.message.length>0}pe(e){var n=e;if(X(n.filename)&&n.filename.length>0){var i,r,s=(i=n.lineno)!==null&&i!==void 0?i:0,o=(r=n.colno)!==null&&r!==void 0?r:0;return`Error - at `+n.filename+":"+s+":"+o}}}var Eg=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class Sg{match(e){return typeof e=="string"}coerce(e,n){var i,r=this.getInfos(e),s=r[0],o=r[1];return{type:s??"Error",value:o??e,stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}getInfos(e){var n="Error",i=e,r=e.match(Eg);return r&&(n=r[1],i=r[2]),[n,i]}}var xg=["fatal","error","warning","log","info","debug"];function Yd(t,e){e===void 0&&(e=40);var n=Object.keys(t);if(n.sort(),!n.length)return"[object has no keys]";for(var i=n.length;i>0;i--){var r=n.slice(0,i).join(", ");if(e>=r.length)return i===n.length?r:r.length>e?r.slice(0,e)+"...":r}return""}class Ig{match(e){return typeof e=="object"&&e!==null}coerce(e,n){var i,r,s=this.getErrorPropertyFromObject(e);return s?n.apply(s):{type:this.getType(e),value:this.getValue(e),stack:(i=this.getStack(e))!==null&&i!==void 0?i:(r=n.syntheticException)==null?void 0:r.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return tl(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var n="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(n+=" with message: '"+e.message+"'"),n}if("message"in e&&typeof e.message=="string")return e.message;var i=this.getObjectClassName(e);return(i&&i!=="Object"?"'"+i+"'":"Object")+" captured as exception with keys: "+Yd(e)}isSeverityLevel(e){return X(e)&&!Jo(e)&&xg.indexOf(e)>=0}getStack(e){try{return X(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:X(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(var n in e)if({}.hasOwnProperty.call(e,n)){var i=e[n];if(sg(i))return i}}getObjectClassName(e){try{var n=Object.getPrototypeOf(e);return n?n.constructor.name:void 0}catch{return}}}class kg{match(e){return tl(e)}coerce(e,n){var i,r=e.constructor.name;return{type:r,value:r+" captured as exception with keys: "+Yd(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class Cg{match(e){return bd(e)}coerce(e,n){var i;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class Ag{match(e){return Wr(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!tl(e))return!1;try{var n=e.detail;return n!=null&&typeof n=="object"&&"reason"in n}catch{return!1}}coerce(e,n){var i,r=this.getUnhandledRejectionReason(e);return bd(r)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(r),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}:n.apply(r)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}}var Yr="$message",Jr="$timestamp",Pg=new Set([Yr,Jr]),vo={enabled:!0,max_bytes:32768};function Zr(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:vo.enabled,max_bytes:Rg(t.max_bytes,vo.max_bytes)}:I({},vo)}class Fg{constructor(e){this.Ke=[],this.Je=0,this.Ne=Zr(e)}setConfig(e){this.Ne=Zr(e),this.Xe()}add(e){var n=(function(r){var s;try{s=_d(r)}catch{return}try{var o=JSON.parse(s);if(!he(o))return;var a=o,l=a[Yr],u=a[Jr];return!X(l)||l.trim().length===0||!X(u)&&!ke(u)?void 0:{step:a,json:s}}catch{return}})(e);if(n){var i=(function(r){if(typeof TextEncoder<"u")return new TextEncoder().encode(r).length;for(var s=encodeURIComponent(r),o=0,a=0;s.length>a;a++)s[a]==="%"?(o+=1,a+=2):o+=1;return o})(n.json);i>this.Ne.max_bytes||(this.Ke.push({step:n.step,bytes:i}),this.Je+=i,this.Xe())}}getAttachable(){return this.Ke.map((e=>e.step))}clear(){this.Ke=[],this.Je=0}size(){return this.Ke.length}Xe(){for(;this.Je>this.Ne.max_bytes&&this.Ke.length>0;){var e=this.Ke.shift();e&&(this.Je-=e.bytes)}}}function Rg(t,e){if(!ke(t)||t===1/0||t===-1/0)return e;var n=Math.floor(t);return 0>n?e:n}var Jd=function(t,e){var n=(e===void 0?{}:e).debugEnabled,i={k(r){if(w&&(ne.DEBUG||w.POSTHOG_DEBUG||n)&&!C(w.console)&&w.console){for(var s=("__rrweb_original__"in w.console[r])?w.console[r].__rrweb_original__:w.console[r],o=arguments.length,a=new Array(o>1?o-1:0),l=1;o>l;l++)a[l-1]=arguments[l];s(t,...a)}},debug(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("debug",...s)},info(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("log",...s)},warn(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("warn",...s)},error(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("error",...s)},critical(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];console.error(t,...s)},uninitializedWarning(r){i.error("You must initialize PostHog before calling "+r)},createLogger:(r,s)=>Jd(t+" "+r,s)};return i},A=Jd("[PostHog.js]"),pe=A.createLogger,Tg=pe("[ExternalScriptsLoader]"),_o=(t,e,n)=>{if(t.config.disable_external_dependency_loading)return Tg.warn(e+" was requested but loading of external scripts is disabled."),n("Loading of external scripts is disabled");var i=P?.querySelectorAll("script");if(i){for(var r,s=function(){if(i[o].src===e){var l=i[o];return l.__posthog_loading_callback_fired?{v:n()}:(l.addEventListener("load",(u=>{l.__posthog_loading_callback_fired=!0,n(void 0,u)})),l.onerror=u=>n(u),{v:void 0})}},o=0;i.length>o;o++)if(r=s())return r.v}var a=()=>{if(!P)return n("document not found");var l=P.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=d=>{l.__posthog_loading_callback_fired=!0,n(void 0,d)},l.onerror=d=>n(d),t.config.prepare_external_dependency_script&&(l=t.config.prepare_external_dependency_script(l)),!l)return n("prepare_external_dependency_script returned null");if(t.config.external_scripts_inject_target==="head")P.head.appendChild(l);else{var u,c=P.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):P.body.appendChild(l)}};P!=null&&P.body?a():P?.addEventListener("DOMContentLoaded",a)};B.__PosthogExtensions__=B.__PosthogExtensions__||{},B.__PosthogExtensions__.loadExternalDependency=(t,e,n)=>{if(e!=="remote-config"){var i;if(t.config.strict_script_versioning)i=t.requestRouter.endpointFor("assets","/static/"+t.version+"/"+e+".js");else{var r="/static/"+e+".js?v="+t.version;if(e==="toolbar"){var s=3e5;r=r+"&t="+Math.floor(Date.now()/s)*s}i=t.requestRouter.endpointFor("assets",r)}_o(t,i,n)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");_o(t,o,n)}},B.__PosthogExtensions__.loadSiteApp=(t,e,n)=>{var i=t.requestRouter.endpointFor("api",e);_o(t,i,n)};ne.DEBUG=!1,ne.LIB_VERSION="1.415.7",ne.LIB_NAME="web";var Zd="$people_distinct_id",Ji="$device_id",yo="$device_model",Ri="__alias",Ti="__timers",na="$autocapture_disabled_server_side",ia="$heatmaps_enabled_server_side",ra="$exception_capture_enabled_server_side",sa="$error_tracking_suppression_rules",oa="$error_tracking_capture_extension_exceptions",aa="$web_vitals_enabled_server_side",al="$dead_clicks_enabled_server_side",ll="$product_tours_enabled_server_side",la="$web_vitals_allowed_metrics",An="$session_recording_remote_config",Xd="$replay_sample_rate",Qd="$replay_override_sampling",ef="$replay_override_linked_flag",tf="$replay_override_url_trigger",nf="$replay_override_event_trigger",Yn="$sesid",cl="$session_is_sampled",Sn="$enabled_feature_flags",$i="$active_feature_flags",Pr="$early_access_features",ca="$feature_flag_details",Mi="$feature_flag_payloads",Fr="$feature_flag_request_id",Xr="$minimal_flag_called_events",It="$override_feature_flags",xn="$override_feature_flag_payloads",jt="$stored_person_properties",In="$stored_group_properties",ua="$surveys",Qr="$surveys_loaded_at",da="$surveys_activated",Rr="$surveys_activated_session",Tr="$surveys_activated_timestamps",Li="ph_product_tours",Cn="$flag_call_reported",Ni="$flag_call_reported_session_id",$r="$feature_flag_errors",Ui="$feature_flag_evaluated_at",at="$user_state",fa="$client_session_props",ha="$capture_rate_limit",pa="$initial_campaign_params",ga="$initial_referrer_info",es="$initial_person_info",ts="$epp",vr="$posthog_cookieless",rf="$cookieless_mode",sf="$sdk_debug_extensions_init_method",of="$sdk_debug_extensions_init_time_ms",af="$sdk_debug_recording_script_not_loaded",ul="PostHog loadExternalDependency extension not found.",kn="on_reject",Wt="always",Hn="anonymous",vn="identified",ma="identified_only",ns="visibilitychange",is="beforeunload",Gn="$pageview",wo="$pageleave",bo="$identify",Tc="$groupidentify";function _r(t,e){U(t)&&t.forEach(e)}function ie(t,e){if(!H(t))if(U(t))t.forEach(e);else if(Wp(t))t.forEach(((i,r)=>e(i,r)));else for(var n in t)wd.call(t,n)&&e(t[n],n)}var fe=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;e>i;i++)n[i-1]=arguments[i];for(var r of n)for(var s in r)r[s]!==void 0&&(t[s]=r[s]);return t};function Mr(t){for(var e=Object.keys(t),n=e.length,i=new Array(n);n--;)i[n]=[e[n],t[e[n]]];return i}var $c=function(t){try{return t()}catch{return}},$g=function(t){return function(){try{for(var e=arguments.length,n=new Array(e),i=0;e>i;i++)n[i]=arguments[i];return t.apply(this,n)}catch(r){A.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),A.critical(r)}}},dl=function(t){var e={};return ie(t,(function(n,i){(X(n)&&n.length>0||ke(n))&&(e[i]=n)})),e},Mg=["herokuapp.com","vercel.app","netlify.app"];function Lg(t){var e=t?.hostname;if(!X(e))return!1;var n=e.split(".").slice(-2).join(".");for(var i of Mg)if(n===i)return!1;return!0}function ve(t,e,n,i){var r=i??{},s=r.capture,o=r.passive;t?.addEventListener(e,n,{capture:s!==void 0&&s,passive:o===void 0||o})}function va(t){return t.name==="ph_toolbar_internal"}var lf=t=>{if(P){try{for(var e=t+"=",n=P.cookie.split(";").filter((s=>s.length)),i=0;n.length>i;i++){for(var r=n[i];r.charAt(0)==" ";)r=r.substring(1,r.length);if(r.indexOf(e)===0)return decodeURIComponent(r.substring(e.length,r.length))}}catch{}return null}};Math.trunc||(Math.trunc=function(t){return 0>t?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return ke(t)&&isFinite(t)&&Math.floor(t)===t});class rs{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,n,i,r){if(!Number.isInteger(e)||!Number.isInteger(n)||!Number.isInteger(i)||!Number.isInteger(r)||0>e||0>n||0>i||0>r||e>0xffffffffffff||n>4095||i>1073741823||r>4294967295)throw new RangeError("invalid field value");var s=new Uint8Array(16);return s[0]=e/Math.pow(2,40),s[1]=e/Math.pow(2,32),s[2]=e/Math.pow(2,24),s[3]=e/Math.pow(2,16),s[4]=e/256,s[5]=e,s[6]=112|n>>>8,s[7]=n,s[8]=128|i>>>24,s[9]=i>>>16,s[10]=i>>>8,s[11]=i,s[12]=r>>>24,s[13]=r>>>16,s[14]=r>>>8,s[15]=r,new rs(s)}toString(){for(var e="",n=0;this.bytes.length>n;n++)e=e+(this.bytes[n]>>>4).toString(16)+(15&this.bytes[n]).toString(16),n!==3&&n!==5&&n!==7&&n!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new rs(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var n=0;16>n;n++){var i=this.bytes[n]-e.bytes[n];if(i!==0)return Math.sign(i)}return 0}}class Ng{generate(){var e=this.generateOrAbort();if(!C(e))return e;this.S=0;var n=this.generateOrAbort();if(C(n))throw new Error("Could not generate UUID after timestamp reset");return n}generateOrAbort(){var e=Date.now();if(e>this.S)this.S=e,this.C();else{if(this.S>=e+1e4)return;this.I++,this.I>4398046511103&&(this.S++,this.C())}return rs.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 Og}}var Mc,cf=t=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;t.length>e;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};w&&!C(w.crypto)&&crypto.getRandomValues&&(cf=t=>crypto.getRandomValues(t));class Og{nextUint32(){return this.R.length>this.O||(cf(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var Ht=()=>Bg().toString(),Bg=()=>(Mc||(Mc=new Ng)).generate(),wi="",Dg=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,zt={N:()=>!!P,j(t){A.error("cookieStore error: "+t)},P:lf,H(t){var e;try{e=JSON.parse(zt.P(t))||{}}catch{}return e},F(t,e,n,i,r){if(!P)return!1;try{var s="",o="",a=(function(c,d){if(d){var f=(function(p,g){if(g===void 0&&(g=P),wi)return wi;if(!g||["localhost","127.0.0.1"].includes(p))return"";for(var m=p.split("."),v=Math.min(m.length,8),E="dmn_chk_"+Ht();!wi&&v--;){var S=m.slice(v).join("."),_=E+"=1;domain=."+S+";path=/";g.cookie=_+";max-age=3",g.cookie.includes(E)&&(g.cookie=_+";max-age=0",wi=S)}return wi})(c);if(!f){var h=(p=>{var g=p.match(Dg);return g?g[0]:""})(c);h!==f&&A.info("Warning: cookie subdomain discovery mismatch",h,f),f=h}return f?"; domain=."+f:""}return""})(P.location.hostname,i);if(n){var l=new Date;l.setTime(l.getTime()+864e5*n),s="; expires="+l.toUTCString()}r&&(o="; secure");var u=t+"="+encodeURIComponent(JSON.stringify(e))+s+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&A.warn("cookieStore warning: large cookie, len="+u.length),P.cookie=u,!0}catch{return!1}},q(t,e){if(P!=null&&P.cookie)try{zt.F(t,"",-1,e)}catch{return}}},Eo=null,le={N(){if(!Ye(Eo))return Eo;var t=!0;if(C(w))t=!1;else try{var e="__mplssupport__";le.F(e,"xyz"),le.P(e)!=='"xyz"'&&(t=!1),le.q(e)}catch{t=!1}return t||A.error("localStorage unsupported; falling back to cookie store"),Eo=t,t},j(t){A.error("localStorage error: "+t)},P(t){try{return w?.localStorage.getItem(t)}catch(e){le.j(e)}return null},H(t){try{return JSON.parse(le.P(t))||{}}catch{}return null},F(t,e){try{return w?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(n){le.j(n)}return!1},q(t){try{w?.localStorage.removeItem(t)}catch(e){le.j(e)}}},jg=[Ji,"distinct_id",Yn,cl,ts,es,at],yr={},Ug={N:()=>!0,j(t){A.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]}},_n=null,be={N(){if(!Ye(_n))return _n;if(_n=!0,C(w))_n=!1;else try{var t="__support__";be.F(t,"xyz"),be.P(t)!=='"xyz"'&&(_n=!1),be.q(t)}catch{_n=!1}return _n},j(t){A.error("sessionStorage error: ",t)},P(t){try{return w?.sessionStorage.getItem(t)}catch(e){be.j(e)}return null},H(t){try{return JSON.parse(be.P(t))||null}catch{}return null},F(t,e){try{return w?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(n){be.j(n)}return!1},q(t){try{w?.sessionStorage.removeItem(t)}catch(e){be.j(e)}}};class Hg{constructor(e){this._instance=e}get Ne(){return this._instance.config}get consent(){return this.ti()?0:this.ei}isOptedOut(){return this.Ne.cookieless_mode===Wt||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===kn}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===0}isRejected(){return this.consent===0||this.consent===-1&&this.Ne.opt_out_capturing_by_default}optInOut(e){this.ii.F(this.ri,e?1:0,this.Ne.cookie_expiration,this.Ne.cross_subdomain_cookie,this.Ne.secure_cookie)}reset(){this.ii.q(this.ri,this.Ne.cross_subdomain_cookie)}get ri(){var e=this._instance.config,n=e.token,i=e.opt_out_capturing_cookie_prefix;return e.consent_persistence_name||(i?i+n:"__ph_opt_in_out_"+n)}get ei(){var e=this.ii.P(this.ri);return ho(e)?1:j(Gp,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,n=e==="localStorage"?le:zt;if(!this.ni||this.ni!==n){this.ni=n;var i=e==="localStorage"?zt:le;i.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(ho(i.P(this.ri))),i.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[He?.doNotTrack,He?.msDoNotTrack,B.doNotTrack].some((e=>ho(e)))}}function uf(t,e){var n,i=t==null||(n=t.config)==null?void 0:n.get_current_url;if(!je(i))return e;try{var r=i(e);return X(r)&&r?r:e}catch(s){return A.error("Error in get_current_url, falling back to window.location.href",s),e}}var df="__POSTHOG_TOOLBAR__",Wg=1,zg=3,qg=11;function Lc(t){return t instanceof Element&&(t.id===df||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function hn(t){return!!t&&t.nodeType===Wg}function et(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function ff(t){return!!t&&t.nodeType===zg}function hf(t){return!!t&&t.nodeType===qg&&hn(t.host)}var pf=1e3;function fl(t){return t?Is(t).split(/\s+/):[]}function Nc(t,e){var n=(function(i){var r,s=w==null||(r=w.location)==null?void 0:r.href;return C(s)?void 0:uf(i,s)})(e);return!!(n&&t&&t.some((i=>n.match(i))))}function ss(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 fl(e)}function gf(t){return H(t)?null:Is(t).split(/(\s+)/).filter((e=>Hi(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function Zi(t){var e="";return ya(t)&&!yf(t)&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;ff(n)&&n.textContent&&(e+=(i=gf(n.textContent))!==null&&i!==void 0?i:"")})),Is(e)}function So(t){var e;return C(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var hl=["a","button","form","input","select","textarea","label"];function _a(t,e){if(C(e))return!0;var n,i=function(s){if(e.some((o=>(function(a,l){var u=a.matches||a.matchesSelector||a.msMatchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.oMatchesSelector;try{return!!u&&u.call(a,l)}catch{return!1}})(s,o))))return{v:!0}};for(var r of t)if(n=i(r))return n.v;return!1}function mf(t){var e=t.parentNode;return!(!e||!hn(e))&&e}var Vg=[".ph-no-autocapture","[data-ph-no-autocapture]"],vf=["next","previous","prev",">","<"],Gg=[...vf,"+","-","−","–"],Oc=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,Bc=[".ph-no-rageclick",".ph-no-capture"],Kg=["","text","search","email","password","url","tel","number"];function Dc(t,e){if(!w||pl(t))return!1;var n,i,r,s,o;if(mt(e)?(n=!!e&&Bc,i=void 0,r=!1):(n=(s=e?.css_selector_ignorelist)!==null&&s!==void 0?s:Bc,i=e?.content_ignorelist,r=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),n===!1||r&&(function(l){return!(!l||!hn(l))&&(!!et(l,"textarea")||(et(l,"input")?j(Kg,(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=_f(t,!1).targetElementList;return!(function(l,u){if(l===!1||C(l))return!1;var c;if(l===!0)c=vf;else{if(!U(l))return!1;if(l.length>10)return A.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var f=d.safeText,h=d.ariaLabel;return c.some((p=>Oc(f,p)||Oc(h,p)))}))})(i,a.map((l=>{var u;return{safeText:Zi(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!_a(a,n)}var pl=t=>!t||et(t,"html")||!hn(t),_f=(t,e)=>{if(!w||pl(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,i=[t],r=t;r.parentNode&&!et(r,"body");)if(hf(r.parentNode))i.push(r.parentNode.host),r=r.parentNode.host;else{var s=mf(r);if(!s)break;if(e||hl.indexOf(s.tagName.toLowerCase())>-1)n=!0;else try{var o=w.getComputedStyle(s);o&&o.getPropertyValue("cursor")==="pointer"&&(n=!0)}catch{}i.push(s),r=s}return{parentIsUsefulElement:n,targetElementList:i}};function ya(t){for(var e=new Set,n=0,i=t;i.parentNode&&!et(i,"body");i=i.parentNode){if(n++>=pf||e.has(i))return!1;e.add(i);var r=ss(i);if(j(r,"ph-sensitive")||j(r,"ph-no-capture"))return!1}if(j(ss(t),"ph-include"))return!0;var s=t.type||"";if(X(s))switch(s.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!X(o)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(o.replace(/[^a-zA-Z0-9]/g,""))}function yf(t){return!!(et(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||et(t,"select")||et(t,"textarea")||t.getAttribute("contenteditable")==="true")}var jc=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}))$"),Uc=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,Yg=[16,15,14,13],Jg=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),Hc=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),Wc=/[0-9A-Za-z_]/;function Zg(t){for(var e=0,n=!1,i=t.length-1;i>=0;i--){var r=t.charCodeAt(i)-48;n&&(r*=2)>9&&(r-=9),e+=r,n=!n}return e%10==0}function Hi(t,e){if(e===void 0&&(e=!0),H(t))return!1;if(X(t)){t=Is(t);var n=e?jc.test((t||"").replace(/[- ]/g,"")):(function(r){var s;for(Uc.lastIndex=0;s=Uc.exec(r);){var o=s[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of Yg){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(jc.test(d)&&Zg(d))return!0}}}return!1})(t);if(n)return!1;var i=e?Jg.test(t):(function(r){var s;for(Hc.lastIndex=0;s=Hc.exec(r);){var o=s[1],a=s[3];if(!(o&&a&&Wc.test(o)&&Wc.test(a)))return!0}return!1})(t);if(i)return!1}return!0}function zc(t){var e=Zi(t);return Hi(e=(e+" "+wf(t)).trim())?e:""}function wf(t){var e="";return t&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;if(n&&((i=n.tagName)==null?void 0:i.toLowerCase())==="span")try{var r=Zi(n);e=(e+" "+r).trim(),n.childNodes&&n.childNodes.length&&(e=(e+" "+wf(n)).trim())}catch(s){A.error("[AutoCapture]",s)}})),e}function qc(t){return t.replace(/"|\\"/g,'\\"')}function Xg(t){var e=t.attr__class;if(e)return U(e)?e:fl(e)}var wr=pe("[Dead Clicks]"),Qg=()=>!0,em=t=>{var e,n=!((e=t.instance.persistence)==null||!e.get_property(al)),i=t.instance.config.capture_dead_clicks;return mt(i)?i:!!he(i)||n};class Vc{get lazyLoadedDeadClicksAutocapture(){return this.si}constructor(e,n,i){this.instance=e,this.isEnabled=n,this.onCapture=i,this.startIfEnabledOrStop()}onRemoteConfig(e){if(e.ok){var n=e.config;"captureDeadClicks"in n&&(this.instance.persistence&&this.instance.persistence.register({[al]:n.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var n,i;(n=B.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture?e():(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"dead-clicks-autocapture",(r=>{r?wr.error("failed to load script",r):e()}))}oi(){var e;if(P){if(!this.si&&(e=B.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var n=he(this.instance.config.capture_dead_clicks)?I({},this.instance.config.capture_dead_clicks):{};n.__onCapture=this.onCapture,this.onCapture&&(n.capture_dead_swipes=!1),this.si=B.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.si.start(P),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 xo=pe("[SegmentIntegration]"),bf="posthog-js";function Ef(t,e){var n=e===void 0?{}:e,i=n.organization,r=n.projectId,s=n.prefix,o=n.severityAllowList,a=o===void 0?["error"]:o,l=n.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,f,h,p,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var v,E=((d=c.exception)==null?void 0:d.values)||[],S=E.map((b=>I({},b,{stacktrace:b.stacktrace?I({},b.stacktrace,{type:"raw",frames:(b.stacktrace.frames||[]).map((k=>I({},k,{platform:"web:javascript"})))}):void 0}))),_={$exception_message:((f=E[0])==null?void 0:f.value)||c.message,$exception_type:(h=E[0])==null?void 0:h.type,$exception_level:c.level,$exception_list:S,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((p=E[0])==null?void 0:p.value)||c.message,$sentry_exception_type:(g=E[0])==null?void 0:g.type,$sentry_tags:c.tags};return i&&r&&(_.$sentry_url=(s||"https://sentry.io/organizations/")+i+"/issues/?project="+r+"&query="+c.event_id),u&&((v=t.exceptions)==null||v.sendExceptionEvent(_)),c}}class tm{constructor(e,n,i,r,s,o){this.name=bf,this.setupOnce=function(a){a(Ef(e,{organization:n,projectId:i,prefix:r,severityAllowList:s,sendExceptionsToPostHog:o==null||o}))}}}class Gc{constructor(e){this.li=(n,i,r)=>{r&&(r.noSessionId||r.activityTimeout||r.sessionPastMaximumLength||r.crossTabAdoption)&&(A.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:n,changeReason:r}),this.ui=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.hi()}hi(){var e;this.di=(e=this._instance.sessionManager)==null?void 0:e.onSessionId(this.li)}destroy(){var e;(e=this.di)==null||e.call(this),this.di=void 0}doPageView(e,n){var i,r=this.vi(e,n);return this.ui={pathname:(i=w?.location.pathname)!==null&&i!==void 0?i:"",pageViewId:n,timestamp:e},this._instance.scrollManager.resetContext(),r}doPageLeave(e){var n;return this.vi(e,(n=this.ui)==null?void 0:n.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.ui)==null?void 0:e.pageViewId}}vi(e,n){var i=this.ui;if(!i)return{$pageview_id:n};var r={$pageview_id:n,$prev_pageview_id:i.pageViewId},s=this._instance.scrollManager.getContext();if(s&&!this._instance.config.disable_scroll_properties){var o=s.maxScrollHeight,a=s.lastScrollY,l=s.maxScrollY,u=s.maxContentHeight,c=s.lastContentY,d=s.maxContentY;if(!(C(o)||C(a)||C(l)||C(u)||C(c)||C(d))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),d=Math.ceil(d);var f=o>1?At(a/o,0,1,A):1,h=o>1?At(l/o,0,1,A):1,p=u>1?At(c/u,0,1,A):1,g=u>1?At(d/u,0,1,A):1;r=fe(r,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:f,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:h,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:p,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return i.pathname&&(r.$prev_pageview_pathname=i.pathname),i.timestamp&&(r.$prev_pageview_duration=(e.getTime()-i.timestamp.getTime())/1e3),r}}var Io=["flags","surveys"],nm={[Zd]:{exposure:"hidden"},[Ri]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[Ti]:{exposure:"hidden"},[na]:{exposure:"event"},[ia]:{exposure:"hidden"},[ra]:{exposure:"event"},[sa]:{exposure:"hidden"},[oa]:{exposure:"event"},[aa]:{exposure:"event"},[al]:{exposure:"event"},[ll]:{exposure:"hidden"},[la]:{exposure:"event"},[An]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[Yn]:{exposure:"hidden"},[cl]:{exposure:"event"},[Xd]:{exposure:"event",shouldSkipFromEventProperties:t=>Ye(t)},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},$sess_rec_flush_size:{exposure:"hidden"},[Sn]:{exposure:"hidden",storageGroup:"flags"},[$i]:{exposure:"hidden",storageGroup:"flags"},[Pr]:{exposure:"hidden"},[ca]:{exposure:"hidden",storageGroup:"flags"},[Mi]:{exposure:"hidden",storageGroup:"flags"},[Fr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[Xr]:{exposure:"hidden",storageGroup:"flags"},[It]:{exposure:"hidden"},[xn]:{exposure:"hidden"},[jt]:{exposure:"hidden"},[In]:{exposure:"hidden"},[ua]:{exposure:"hidden",storageGroup:"surveys"},[Qr]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[da]:{exposure:"event"},[Rr]:{exposure:"hidden"},[Tr]:{exposure:"hidden"},[Li]:{exposure:"hidden"},$product_tours_activated:{exposure:"hidden"},$product_tours_activated_session:{exposure:"hidden"},$conversations_widget_session_id:{exposure:"event"},$conversations_ticket_id:{exposure:"event"},$conversations_widget_state:{exposure:"event"},$conversations_user_traits:{exposure:"event"},[Cn]:{exposure:"hidden"},[Ni]:{exposure:"hidden"},[$r]:{exposure:"hidden"},[Ui]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[at]:{exposure:"hidden"},[fa]:{exposure:"hidden"},[ha]:{exposure:"hidden"},[pa]:{exposure:"hidden"},[ga]:{exposure:"hidden"},[es]:{exposure:"hidden"},[ts]:{exposure:"hidden"},[Qd]:{exposure:"event"},[ef]:{exposure:"event"},[tf]:{exposure:"event"},[nf]:{exposure:"event"},[sf]:{exposure:"event"},[of]:{exposure:"event"},[af]:{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"}},im=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],yn=t=>{var e=nm[t];if(e)return e;for(var n of im){var i=n[1];if(t.indexOf(n[0])===0)return i}},Jn=(t,e)=>{try{return JSON.stringify(t,((n,i)=>typeof i=="bigint"?i.toString():i),e)}catch{return _d(t)}},os=t=>{var e=P?.createElement("a");return C(e)?null:(e.href=t,e)},ri=function(t,e){for(var n,i=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),r=0;i.length>r;r++){var s=i[r].split("=");if(s[0]===e){n=s;break}}if(!U(n)||2>n.length)return"";var o=n[1];try{o=decodeURIComponent(o)}catch{A.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},Xi=function(t,e,n){if(!t||!e||!e.length)return t;for(var i=t.split("#"),r=i[1],s=(i[0]||"").split("?"),o=s[1],a=s[0],l=(o||"").split("&"),u=[],c=0;l.length>c;c++){var d=l[c].split("=");U(d)&&(e.includes(d[0])?u.push(d[0]+"="+n):u.push(l[c]))}var f=a;return o!=null&&(f+="?"+u.join("&")),r!=null&&(f+="#"+r),f},as=function(t,e){var n=t.match(new RegExp(e+"=([^&]*)"));return n?n[1]:null},Sf=(t,e)=>t>=e&&gd(),xf=(t,e,n,i)=>{if(t===0){if(gd()){var r=e+1;return r===n&&i(),r}return e}return 0},br="https?://(.*)",si=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],rm=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...si],Qi="",sm=["li_fat_id"];function If(t,e,n){if(!P)return{};var i,r=e?[...si,...n||[]]:[],s=kf(Xi(P.URL,r,Qi),t),o=(i={},ie(sm,(function(a){var l=lf(a);i[a]=l||null})),i);return fe(o,s)}function kf(t,e){var n=rm.concat(e||[]),i={};return ie(n,(function(r){var s=ri(t,r);i[r]=s||null})),i}function Cf(t){var e=(function(s){return s?s.search(br+"google.([^/?]*)")===0?"google":s.search(br+"bing.com")===0?"bing":s.search(br+"yahoo.com")===0?"yahoo":s.search(br+"duckduckgo.com")===0?"duckduckgo":null:null})(t),n=e!="yahoo"?"q":"p",i={};if(!Ye(e)){i.$search_engine=e;var r=P?ri(P.referrer,n):"";r.length&&(i.ph_keyword=r)}return i}function Kc(){return navigator.language||navigator.userLanguage}var ls="$direct";function Af(){return P?.referrer||ls}function Pf(t,e,n){n===void 0&&(n=!1);var i=t?[...si,...e||[]]:[],r=n?fn(me?.href):me?.href,s=r?.substring(0,1e3);return{r:Af().substring(0,1e3),u:s?Xi(s,i,Qi):void 0}}function Ff(t,e){var n;e===void 0&&(e=!1);var i=t.r,r=t.u,s=e?fn(r):r,o={$referrer:i,$referring_domain:i==null?void 0:i==ls?ls:(n=os(i))==null?void 0:n.host};if(s){o.$current_url=s;var a=os(s);o.$host=a?.host,o.$pathname=a?.pathname;var l=kf(s);fe(o,l)}if(i){var u=Cf(i);fe(o,u)}return o}function Rf(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function om(){try{return new Date().getTimezoneOffset()}catch{return}}var am={flags:Ui,surveys:Qr},lm=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],Wn="main";class ko{constructor(e,n,i){if(i===void 0&&(i=!0),this.ci={},this.fi=!1,this.pi=!1,this.Ne=e,this.gi=i,this.props={},this.mi=void 0,this.yi=(s=>{var o="";return s.token&&(o=s.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),s.persistence_name?"ph_"+s.persistence_name:"ph_"+o+"_posthog"})(e),this.ii=this.bi(e),this.pi=this.wi(e),this.load(),e.debug&&A.info("Persistence loaded",e.persistence,I({},this.props)),this.update_config(e,e,n),this.save(),w){var r=()=>this.flush();ve(w,"beforeunload",r,{capture:!1}),ve(w,"pagehide",r,{capture:!1})}}ki(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return ke(n)&&n>0?n:0}isDisabled(){return!!this.xi}bi(e){lm.indexOf(e.persistence.toLowerCase())===-1&&(A.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var n,i=(function(o,a){o===void 0&&(o=[]),a===void 0&&(a=!1);var l=[...jg,...o];return I({},le,{H(u){try{var c={};try{c=zt.H(u)||{}}catch{}var d,f=JSON.parse(le.P(u)||"{}");if(a){var h={};for(var p in c){var g=c[p];Ye(g)||g===""||(h[p]=g)}d=fe(f,h)}else d=fe(c,f);return le.F(u,d),d}catch{}return null},F(u,c,d,f,h,p){var g=le.F(u,c,void 0,void 0,p);try{var m={};l.forEach((v=>{c[v]&&(m[v]=c[v])})),Object.keys(m).length&&zt.F(u,m,d,f,h,p)}catch(v){le.j(v)}return g},q(u,c){try{w?.localStorage.removeItem(u),zt.q(u,c)}catch(d){le.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),r=!1,s=e.persistence.toLowerCase();return s==="localstorage"&&le.N()?(n=le,r=!0):s==="localstorage+cookie"&&i.N()?(n=i,r=!0):s==="sessionstorage"&&be.N()?n=be:s==="memory"?n=Ug:s==="cookie"?n=zt:i.N()?(n=i,r=!0):n=zt,this.fi=r,n}Si(e){return this.yi+"__"+e}wi(e){return this.fi&&!!e.split_storage}properties(){var e={};return ie(this.props,((n,i)=>{var r=yn(i);if(!r||r.exposure==="event"){if(r!=null&&r.shouldSkipFromEventProperties!=null&&r.shouldSkipFromEventProperties(n))return;e[i]=n}})),e}load(){if(!this.xi){var e=this.ii.H(this.yi);e&&(this.props=fe({},e)),this.pi&&this.Ci()}}Ci(){for(var e of Io){var n=le.H(this.Si(e));if(n&&!Kt(n)){var i=this.Mi(e);i.persisted=!0,this.Ti(e)||(i.fingerprint=this.Ei(n,e)),this.Ii(e,n)||fe(this.props,n)}}}Ti(e){return Object.keys(this.props).some((n=>{var i;return((i=yn(n))==null?void 0:i.storageGroup)===e}))}Ii(e,n){var i=am[e];if(!i)return!1;var r=n[i],s=this.props[i];return ke(r)&&ke(s)&&s>r}refreshKey(e){var n;if(!this.xi){var i=this.pi?(n=yn(e))==null?void 0:n.storageGroup:void 0,r=i?le.H(this.Si(i)):this.ii.H(this.yi);if(r&&e in r)this.Pi(e,r[e]);else{if(i){var s=this.ii.H(this.yi);if(s&&e in s)return void this.Pi(e,s[e])}this.Ri(e)}}}save(){if(!this.xi){var e=this.ki();e>0?C(this.Ai)&&(this.Ai=setTimeout((()=>{this.Ai=void 0,this.Fi()}),e)):this.Fi()}}flush(){C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0,this.Fi())}Fi(){this.xi||(this.pi?this.Li():this.Oi(this.ii,this.yi,this.props,Wn))}Li(){var e=this.Di(),n=e.main,i=e.groups;for(var r of(this.Oi(this.ii,this.yi,n,Wn),Io)){var s,o=i[r];(!Kt(o)||(s=this.ci[r])!=null&&s.persisted)&&this.Oi(le,this.Si(r),o,r)}}Di(){var e={},n={flags:{},surveys:{}};return ie(this.props,((i,r)=>{var s,o=(s=yn(r))==null?void 0:s.storageGroup;o?n[o][r]=i:e[r]=i})),{main:e,groups:n}}Ei(e,n){if(n===Wn)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var i={};return ie(e,((r,s)=>{var o;i[s]=(o=yn(s))!=null&&o.volatile?"__volatile__":r})),JSON.stringify(i)}Oi(e,n,i,r){var s=this.Mi(r);if(r===Wn||s.dirty||C(s.fingerprint)){var o;try{if((o=this.Ei(i,r))===s.fingerprint)return void(s.dirty=!1)}catch{o=void 0}e.F(n,i,this.$i,this.Ni,this.qi,this.Ne.debug)?(s.dirty=!1,r!==Wn&&(s.persisted=!0),C(o)||(s.fingerprint=o)):this.Ne.debug&&A.warn('failed to persist storage entry "'+n+'"; will retry on next save')}}remove(e){var n=(e===void 0?{}:e).keepGroupEntries,i=n!==void 0&&n;if(C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0),this.ii.q(this.yi,!1),this.ii.q(this.yi,!0),!i&&this.gi)for(var r of Io)le.q(this.Si(r));i?delete this.ci[Wn]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,n,i){if(he(e)){C(n)&&(n="None"),this.$i=C(i)?this.ji:i;var r=!1;if(ie(e,((s,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==n||(this.Pi(o,s),r=!0)})),r)return this.save(),!0}return!1}register(e,n){if(he(e)){this.$i=C(n)?this.ji:n;var i=!1;if(ie(e,((r,s)=>{e.hasOwnProperty(s)&&(this.props[s]!==r||he(r)||U(r))&&(this.Pi(s,r),i=!0)})),i)return this.save(),!0}return!1}unregister(e){var n=typeof e=="string"?[e]:e,i=!1;for(var r of n)r in this.props&&(this.Ri(r),i=!0);i&&this.save()}update_campaign_params(){var e=P?.URL;if(e!==this.mi){var n=If(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);Kt(dl(n))||this.register(n),this.mi=e}}update_search_keyword(){var e;this.register((e=P?.referrer)?Cf(e):{})}update_referrer_info(){var e;this.register_once({$referrer:Af(),$referring_domain:P!=null&&P.referrer&&((e=os(P.referrer))==null?void 0:e.host)||ls},void 0)}set_initial_person_info(){this.props[pa]||this.props[ga]||this.register_once({[es]:Pf(this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties,this.Ne.disable_capture_url_hashes)},void 0)}get_initial_props(){var e={};ie([ga,pa],(r=>{var s=this.props[r];s&&ie(s,(function(o,a){e["$initial_"+Yo(a)]=o}))}));var n=this.props[es];if(n){var i=(function(r,s){s===void 0&&(s=!1);var o=Ff(r,s),a={};return ie(o,(function(l,u){a["$initial_"+Yo(u)]=l})),a})(n,this.Ne.disable_capture_url_hashes);fe(e,i)}return e}safe_merge(e){return ie(this.props,(function(n,i){i in e||(e[i]=n)})),e}update_config(e,n,i){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!i),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var r=e.persistence!==n.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((f,h)=>f===d[h]))})(e.cookie_persisted_properties||[],n.cookie_persisted_properties||[]),s=r?this.bi(e):this.ii,o=this.wi(e);if(r||o!==this.pi){var a=this.props;this.clear(),this.ii=s,this.pi=o,this.props=a,this.save()}}set_disabled(e){this.xi=e,this.xi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ni&&(this.Ni=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this.qi&&(this.qi=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,n){var i=this.props[Ti]||{};i[e]=n,this.Pi(Ti,i),this.save()}remove_event_timer(e){var n=this.props[Ti]||{},i=n[e];return C(i)||(delete n[e],this.Pi(Ti,n),this.save()),i}get_property(e){return this.props[e]}set_property(e,n){this.Pi(e,n),this.save()}Pi(e,n){var i;this.props[e]=n,(i=yn(e))!=null&&i.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var n,i=(n=yn(e))==null?void 0:n.storageGroup;i&&(this.Mi(i).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function Er(t){var e=!0;return{dispose(){if(e){e=!1;var n=t();n&&je(n.then)&&n.then(void 0,(()=>{}))}}}}var Ue={GZipJS:"gzip-js",Base64:"base64"},bi={Activation:"events",Cancellation:"cancelEvents"},Co={Popover:"popover",API:"api",Widget:"widget"},qt={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},Ao={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},wa={Popover:"popover",Inline:"inline"},cm={SHOWN:"product tour shown"},Yc={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},Jc=pe("[RateLimiter]");class um{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=n=>{var i=n.text;if(i&&i.length)try{(JSON.parse(i).quota_limited||[]).forEach((r=>{Jc.info((r||"events")+" is quota limited."),this.serverLimits[r]=new Date().getTime()+6e4}))}catch(r){return void Jc.warn('could not rate limit - continuing. Error: "'+r?.message+'"',{text:i})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var n,i,r;e===void 0&&(e=!1);var s=this.captureEventsBurstLimit,o=this.captureEventsPerSecond,a=new Date().getTime(),l=(n=(i=this.instance.persistence)==null?void 0:i.get_property(ha))!==null&&n!==void 0?n:{tokens:s,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>s&&(l.tokens=s);var u=1>l.tokens;if(u||e||(l.tokens=Math.max(0,l.tokens-1)),u&&!e){var c=(ke(l.dropped)?l.dropped:0)+1;l.dropped=c,!this.lastEventRateLimited&&this.Hi(c)&&(l.dropped=0)}return this.lastEventRateLimited=u,(r=this.instance.persistence)==null||r.set_property(ha,l),{isRateLimited:u,remainingTokens:l.tokens}}Ui(e){var n=this.instance.config.property_denylist;return!U(n)||!n.includes(e)}zi(){var e;if(this.Ui("$current_url")&&this.Ui("$pathname")&&me!=null&&me.pathname)return""+((e=me.origin)!==null&&e!==void 0?e:"")+me.pathname}Hi(e){var n,i,r=this.captureEventsBurstLimit,s=this.captureEventsPerSecond,o=this.zi(),a=this.Ui("$session_id")?(n=(i=this.instance).get_session_id)==null?void 0:n.call(i):void 0,l=[e+" event(s) dropped since the last warning",o?"triggered on "+o:void 0,a?"session "+a:void 0].filter(Boolean).join(", ");return!!this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited: "+l+". Config is set to "+s+" events per second and "+r+" events burst limit."},{skip_client_rate_limiting:!0})}isServerRateLimited(e){var n=this.serverLimits[e||"events"]||!1;return n!==!1&&new Date().getTime()e(this.remoteConfig))):e()}Vi(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:e})}load(){try{if(this.remoteConfig)return an.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void an.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return an.info("No config found after loading remote JS config. Falling back to JSON."),void this.Vi((n=>{this.Zi(n.json,n),this.Gi()}));this.Zi(e),this.Gi()}))}catch(e){an.error("Error loading remote config",e),this.Zi()}}stop(){this.Ki&&(clearInterval(this.Ki),this.Ki=void 0)}refresh(){!this._instance.Qi()&&P&&P.visibilityState!=="hidden"&&this._instance.reloadFeatureFlags()}Gi(){var e;if(!this.Ki){var n=(e=this._instance.config.remote_config_refresh_interval_ms)!==null&&e!==void 0?e:3e5;n!==0&&(this.Ki=setInterval((()=>{this.refresh()}),n))}}Zi(e,n){!e&&n&&(n.statusCode===0?n.error||an.warn("Failed to fetch remote config from PostHog."):an.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(r){an.error("Error applying remote config",r)}if(e?.hasFeatureFlags!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var i;(i=this._instance.featureFlags)==null||i.ensureFlagsLoaded()}catch(r){an.error("Error loading feature flags",r)}}}var ct=Uint8Array,Ke=Uint16Array,oi=Uint32Array,gl=new ct([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]),ml=new ct([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]),Zc=new ct([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),$f=function(t,e){for(var n=new Ke(31),i=0;31>i;++i)n[i]=e+=1<i;++i)for(var s=n[i];n[i+1]>s;++s)r[s]=s-n[i]<<5|i;return[n,r]},Mf=$f(gl,2),ba=Mf[1];Mf[0][28]=258,ba[258]=28;for(var Xc=$f(ml,0)[1],Lf=new Ke(32768),_e=0;32768>_e;++_e){var zn=(43690&_e)>>>1|(21845&_e)<<1;Lf[_e]=((65280&(zn=(61680&(zn=(52428&zn)>>>2|(13107&zn)<<2))>>>4|(3855&zn)<<4))>>>8|(255&zn)<<8)>>>1}var Wi=function(t,e,n){for(var i=t.length,r=0,s=new Ke(e);i>r;++r)++s[t[r]-1];var o,a=new Ke(e);for(r=0;e>r;++r)a[r]=a[r-1]+s[r-1]<<1;for(o=new Ke(i),r=0;i>r;++r)o[r]=Lf[a[t[r]-1]++]>>>15-t[r];return o},Mn=new ct(288);for(_e=0;144>_e;++_e)Mn[_e]=8;for(_e=144;256>_e;++_e)Mn[_e]=9;for(_e=256;280>_e;++_e)Mn[_e]=7;for(_e=280;288>_e;++_e)Mn[_e]=8;var cs=new ct(32);for(_e=0;32>_e;++_e)cs[_e]=5;var dm=Wi(Mn,9),fm=Wi(cs,5),Nf=function(t){return(t/8>>0)+(7&t&&1)},Of=function(t,e,n){(n==null||n>t.length)&&(n=t.length);var i=new(t instanceof Ke?Ke:t instanceof oi?oi:ct)(n-e);return i.set(t.subarray(e,n)),i},Ot=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8},Ei=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8,t[i+2]|=n>>>16},Po=function(t,e){for(var n=[],i=0;t.length>i;++i)t[i]&&n.push({s:i,f:t[i]});var r=n.length,s=n.slice();if(!r)return[new ct(0),0];if(r==1){var o=new ct(n[0].s+1);return o[n[0].s]=1,[o,1]}n.sort((function(b,k){return b.f-k.f})),n.push({s:-1,f:25001});var a=n[0],l=n[1],u=0,c=1,d=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=r-1;)a=n[n[d].f>n[u].f?u++:d++],l=n[u!=c&&n[d].f>n[u].f?u++:d++],n[c++]={s:-1,f:a.f+l.f,l:a,r:l};var f=s[0].s;for(i=1;r>i;++i)s[i].s>f&&(f=s[i].s);var h=new Ke(f+1),p=Ea(n[c-1],h,0);if(p>e){i=0;var g=0,m=p-e,v=1<i;++i){var E=s[i].s;if(e>=h[E])break;g+=v-(1<>>=m;g>0;){var S=s[i].s;e>h[S]?g-=1<=0&&g;--i){var _=s[i].s;h[_]==e&&(--h[_],++g)}p=e}return[new ct(h),p]},Ea=function(t,e,n){return t.s==-1?Math.max(Ea(t.l,e,n+1),Ea(t.r,e,n+1)):e[t.s]=n},Qc=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new Ke(++e),i=0,r=t[0],s=1,o=function(l){n[i++]=l},a=1;e>=a;++a)if(t[a]==r&&a!=e)++s;else{if(!r&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(r),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(r);s=1,r=t[a]}return[n.subarray(0,i),e]},Si=function(t,e){for(var n=0,i=0;e.length>i;++i)n+=t[i]*e[i];return n},Sa=function(t,e,n){var i=n.length,r=Nf(e+2);t[r]=255&i,t[r+1]=i>>>8,t[r+2]=255^t[r],t[r+3]=255^t[r+1];for(var s=0;i>s;++s)t[r+s+4]=n[s];return 8*(r+4+i)},eu=function(t,e,n,i,r,s,o,a,l,u,c){Ot(e,c++,n),++r[256];for(var d=Po(r,15),f=d[0],h=d[1],p=Po(s,15),g=p[0],m=p[1],v=Qc(f),E=v[0],S=v[1],_=Qc(g),b=_[0],k=_[1],T=new Ke(19),x=0;E.length>x;++x)T[31&E[x]]++;for(x=0;b.length>x;++x)T[31&b[x]]++;for(var F=Po(T,7),$=F[0],O=F[1],L=19;L>4&&!$[Zc[L-1]];--L);var N,K,V,M,R=u+5<<3,Z=Si(r,Mn)+Si(s,cs)+o,Ce=Si(r,f)+Si(s,g)+o+14+3*L+Si(T,$)+(2*T[16]+3*T[17]+7*T[18]);if(Z>=R&&Ce>=R)return Sa(e,c,t.subarray(l,l+u));if(Ot(e,c,1+(Z>Ce)),c+=2,Z>Ce){N=Wi(f,h),K=f,V=Wi(g,m),M=g;var oe=Wi($,O);for(Ot(e,c,S-257),Ot(e,c+5,k-1),Ot(e,c+10,L-4),c+=14,x=0;L>x;++x)Ot(e,c+3*x,$[Zc[x]]);c+=3*L;for(var ye=[E,b],$e=0;2>$e;++$e){var ae=ye[$e];for(x=0;ae.length>x;++x)Ot(e,c,oe[Ie=31&ae[x]]),c+=$[Ie],Ie>15&&(Ot(e,c,ae[x]>>>5&127),c+=ae[x]>>>12)}}else N=dm,K=Mn,V=fm,M=cs;for(x=0;a>x;++x)if(i[x]>255){var Ie;Ei(e,c,N[257+(Ie=i[x]>>>18&31)]),c+=K[Ie+257],Ie>7&&(Ot(e,c,i[x]>>>23&31),c+=gl[Ie]);var Se=31&i[x];Ei(e,c,V[Se]),c+=M[Se],Se>3&&(Ei(e,c,i[x]>>>5&8191),c+=ml[Se])}else Ei(e,c,N[i[x]]),c+=K[i[x]];return Ei(e,c,N[256]),c+K[256]},hm=new oi([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),pm=(function(){for(var t=new oi(256),e=0;256>e;++e){for(var n=e,i=9;--i;)n=(1&n&&3988292384)^n>>>1;t[e]=n}return t})(),Fo=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8};function gm(t,e){e===void 0&&(e={});var n=(function(){var d=4294967295;return{p(f){for(var h=d,p=0;f.length>p;++p)h=pm[255&h^f[p]]^h>>>8;d=h},d(){return 4294967295^d}}})(),i=t.length;n.p(t);var r,s,o,a,l,u=(a=10+((r=e).filename&&r.filename.length+1||0),l=8,(function(d,f,h,p,g,m){var v=d.length,E=new ct(p+v+5*(1+Math.floor(v/7e3))+g),S=E.subarray(p,E.length-g),_=0;if(!f||8>v)for(var b=0;v>=b;b+=65535){var k=b+65535;v>k?_=Sa(S,_,d.subarray(b,k)):(S[b]=!0,_=Sa(S,_,d.subarray(b,v)))}else{for(var T=hm[f-1],x=T>>>13,F=8191&T,$=(1<b;++b){var Ie=V(b),Se=32767&b,De=L[Ie];if(O[Se]=De,L[Ie]=Se,b>=$e){var wt=v-b;if((Ce>7e3||ye>24576)&&wt>423){_=eu(d,S,0,M,R,Z,oe,ye,ae,b-ae,_),ye=Ce=oe=0,ae=b;for(var ge=0;286>ge;++ge)R[ge]=0;for(ge=0;30>ge;++ge)Z[ge]=0}var Je=2,bt=0,mn=F,Re=Se-De&32767;if(wt>2&&Ie==V(b-Re))for(var Pe=Math.min(x,wt)-1,$t=Math.min(32767,b),Dn=Math.min(258,wt);$t>=Re&&--mn&&Se!=De;){if(d[b+Je]==d[b+Je-Re]){for(var qe=0;Dn>qe&&d[b+qe]==d[b+qe-Re];++qe);if(qe>Je){if(Je=qe,bt=Re,qe>Pe)break;var jn=Math.min(Re,qe-2),Mt=0;for(ge=0;jn>ge;++ge){var Lt=b-Re+ge+32768&32767,ut=Lt-O[Lt]+32768&32767;ut>Mt&&(Mt=ut,De=Lt)}}}Re+=(Se=De)-(De=O[Se])+32768&32767}if(bt){M[ye++]=268435456|ba[Je]<<18|Xc[bt];var sn=31&ba[Je],mi=31&Xc[bt];oe+=gl[sn]+ml[mi],++R[257+sn],++Z[mi],$e=b+Je,++Ce}else M[ye++]=d[b],++R[d[b]]}}_=eu(d,S,!0,M,R,Z,oe,ye,ae,b-ae,_)}return Of(E,0,p+Nf(_)+g)})(s=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):12+o.mem,a,l)),c=u.length;return(function(d,f){var h=f.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>f.level?4:f.level==9?2:0,d[9]=3,f.mtime!=0&&Fo(d,4,Math.floor(new Date(f.mtime||Date.now())/1e3)),h){d[3]=8;for(var p=0;h.length>=p;++p)d[p+10]=h.charCodeAt(p)}})(u,e),Fo(u,c-8,n.d()),Fo(u,c-4,i),u}var mm=!!Vo||!!el,Bf="text/plain",Lr=!1,Df=(t,e)=>{var n=t.split("#"),i=n[1],r=n[0].split("?"),s=r[0],o=r[1];if(!o)return t;var a=o.split("&").filter((l=>l.split("=")[0]!==e)).join("&");return s+(a?"?"+a:"")+(i?"#"+i:"")},Cs=function(t,e,n){var i;n===void 0&&(n=!0);var r=t.split("?"),s=r[0],o=r[1],a=I({},e),l=(i=o?.split("&").map((c=>{var d,f=c.split("="),h=f[0],p=n&&(d=a[h])!==null&&d!==void 0?d:f[1];return delete a[h],h+"="+p})))!==null&&i!==void 0?i:[],u=(function(c,d){var f,h;d===void 0&&(d="&");var p=[];return ie(c,(function(g,m){C(g)||C(m)||m==="undefined"||(f=encodeURIComponent((v=>v instanceof File)(g)?g.name:g.toString()),h=encodeURIComponent(m),p[p.length]=h+"="+f)})),p.join(d)})(a);return u&&l.push(u),l.length>0?s+"?"+l.join("&"):s},Ro=t=>{if(t.Ji)return t.Ji;var e=t.data,n=t.compression;if(e){if(n===Ue.GZipJS){var i=gm((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new ct(a.length+(a.length>>>1)),d=0,f=function(m){c[d++]=m},h=0;u>h;++h){if(d+5>c.length){var p=new ct(d+8+(u-h<<1));p.set(c),c=p}var g=a.charCodeAt(h);128>g?f(g):2048>g?(f(192|g>>>6),f(128|63&g)):g>55295&&57344>g?(f(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++h))>>>18),f(128|g>>>12&63),f(128|g>>>6&63),f(128|63&g)):(f(224|g>>>12),f(128|g>>>6&63),f(128|63&g))}return Of(c,0,d)})(Jn(e)),{mtime:0});return{contentType:Bf,body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),estimatedSize:i.byteLength}}if(n===Ue.Base64){var r=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(Jn(e)),s=(a=>"data="+encodeURIComponent(typeof a=="string"?a:Jn(a)))(r);return{contentType:"application/x-www-form-urlencoded",body:s,estimatedSize:new Blob([s]).size}}var o=Jn(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},jf=t=>{var e,n,i=()=>t.transport==="sendBeacon"?{url:Cs(t.url,{compression:Ue.Base64}),encodedBody:Ro(I({},t,{compression:Ue.Base64,Ji:void 0}))}:{url:Df(t.url,"compression"),encodedBody:Ro(I({},t,{compression:void 0,Ji:void 0}))};try{e=Ro(t)}catch(r){if(wc(t.compression,ri(t.url,"compression")))return A.error("Failed to gzip request body, sending uncompressed payload",r),i();throw r}return e&&wc(t.compression,ri(t.url,"compression"))&&!((n=e.body)instanceof ArrayBuffer?Go(new Uint8Array(n)):ArrayBuffer.isView(n)&&Go(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)))?(Lr=!0,i()):{url:t.url,encodedBody:e}},Uf=t=>{try{return jf(t)}catch(e){return A.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},vm=(function(){var t=se((function*(e){var n=Jn(e.data),i=yield(function(s,o,a){return Ko.apply(this,arguments)})(n,ne.DEBUG,{rethrow:!0});if(!i)return e;var r=yield i.arrayBuffer();return I({},e,{Ji:{contentType:Bf,body:r,estimatedSize:r.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),_m=/Failed to fetch|NetworkError|Load failed/i,Hf=t=>t?.name==="TypeError"&&_m.test(t?.message||""),Wf=t=>{var e=Uf(t);if(e){var n=e.url,i=e.encodedBody,r=i??{},s=r.contentType,o=r.body,a=r.estimatedSize,l=new Headers;ie(t.headers,(function(p,g){l.append(g,p)})),s&&l.append("Content-Type",s);var u=null,c=!1;if(pc){var d=new pc;u={signal:d.signal,timeout:setTimeout((()=>{var p,g;c=!0,d.abort((p=t.timeout,(g=new Error("PostHog request timed out"+(p?" after "+p+"ms":""))).name="AbortError",g))}),t.timeout)}}var f=p=>{c&&p?.name==="AbortError"||Hf(p)?A.warn(p):A.error(p),t.callback==null||t.callback({statusCode:0,error:p})};try{var h;el(n,I({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(h=u)==null?void 0:h.signal},t.fetchOptions)).then((p=>p.text().then((g=>{var m={statusCode:p.status,text:g};if(p.status===200)try{m.json=JSON.parse(g)}catch(v){A.error(v)}t.callback==null||t.callback(m)})))).catch(f).finally((()=>u?clearTimeout(u.timeout):null))}catch(p){u&&clearTimeout(u.timeout),f(p)}}},xa=t=>{try{var e,n=jf(t),i=n.url,r=n.encodedBody,s=r??{},o=s.body,a=s.estimatedSize;if(!o)return;var l=o instanceof Blob?o:new Blob([o],{type:s.contentType});if(He.sendBeacon(i,l))return;var u=U(t.data)?t.data:(e=t.data)==null?void 0:e.batch;if(U(u)&&u.length>1&&(a??0)>16384){var c=Math.ceil(u.length/2),d=f=>U(t.data)?f:I({},t.data,{batch:f});return xa(I({},t,{data:d(u.slice(0,c))})),void xa(I({},t,{data:d(u.slice(c))}))}A.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),Wf(I({},t,{Yi:!0}))}catch(f){A.warn("Beacon send failed",f)}},tu=(t,e,n,i)=>{var r=i==="query"?e==="POST"?"sent_at":"_":void 0;return Cs(n===Ue.GZipJS?Df(t,"compression"):t,I({},r?{[r]:Date.now().toString()}:{},n===Ue.GZipJS?{}:{compression:n}))},Nr=[];el&&Nr.push({transport:"fetch",method:Wf}),Vo&&Nr.push({transport:"XHR",method(t){var e=Uf(t);if(e){var n=new Vo,i=e.encodedBody;n.open(t.method||"GET",e.url,!0);var r=i??{},s=r.contentType,o=r.body;ie(t.headers,(function(a,l){n.setRequestHeader(l,a)})),s&&n.setRequestHeader("Content-Type",s),t.timeout&&(n.timeout=t.timeout),n.onreadystatechange=()=>{if(n.readyState===4){var a={statusCode:n.status,text:n.responseText};if(n.status===200)try{a.json=JSON.parse(n.responseText)}catch{}t.callback==null||t.callback(a)}},n.send(o)}}}),He!=null&&He.sendBeacon&&Nr.push({transport:"sendBeacon",method:xa});var Ia=3e3;class ym{constructor(e,n){this.Xi=!0,this.tr=[],this.er=At(n?.flush_interval_ms||Ia,250,5e3,A.createLogger("flush interval"),Ia),this.ir=e}enqueue(e){this.tr.push(e),this.rr||this.nr()}unload(){this.sr();var e=this.tr.length>0?this.ar():{},n=Object.values(e);[...n.filter((i=>i.url.indexOf("/e")===0)),...n.filter((i=>i.url.indexOf("/e")!==0))].map((i=>{this.lr(I({},i,{transport:"sendBeacon"}))}))}enable(){this.Xi=!1,this.nr()}nr(){var e=this;this.Xi||(this.rr=setTimeout((()=>{if(this.sr(),this.tr.length>0){var n=this.ar(),i=function(){var s=n[r],o=new Date().getTime();s.data&&U(s.data)&&ie(s.data,(a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp})),e.lr(s)};for(var r in n)i()}}),this.er))}lr(e){try{this.ir(e)}catch(n){A.error(n)}}sr(){clearTimeout(this.rr),this.rr=void 0}ar(){var e={};return ie(this.tr,(n=>{var i,r=n,s=(r?r.batchKey:null)||r.url;C(e[s])&&(e[s]=I({},r,{data:[]})),(i=e[s].data)==null||i.push(r.data)})),this.tr=[],e}}var wm=["retriesPerformedSoFar"];class bm{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!C(w)&&"onLine"in w.navigator&&(this.dr=w.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},ve(w,"online",this.vr),ve(w,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var n=e.retriesPerformedSoFar,i=md(e,wm);Dt(n)&&(i.url=Cs(i.url,{retry_count:n})),this._instance._send_request(I({},i,{callback:r=>{if(r.statusCode!==200&&(400>r.statusCode||r.statusCode>=500)){if((r.statusCode===0?3:10)>(n??0))return void this.At(I({retriesPerformedSoFar:n},i));r.statusCode===0&&A.warn("Request failed before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped retrying after "+(n??0)+" retries.")}i.callback==null||i.callback(r)}}))}At(e){var n=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=n+1;var i=(function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),c=Math.random()-.5;return Math.ceil(u+c*(u-l))})(n),r=Date.now()+i;this.tr.push({retryAt:r,requestOptions:e});var s="Enqueued failed request for retry in "+i;navigator.onLine||(s+=" (Browser is offline)"),A.warn(s),this.ur||(this.ur=!0,this.gr())}gr(){if(this.mr&&clearTimeout(this.mr),this.tr.length===0)return this.ur=!1,void(this.mr=void 0);this.mr=setTimeout((()=>{this.dr&&this.tr.length>0&&this.cr(),this.gr()}),this.hr)}cr(){var e=Date.now(),n=[],i=this.tr.filter((s=>e>s.retryAt||(n.push(s),!1)));if(this.tr=n,i.length>0)for(var r of i)this.retriableRequest(r.requestOptions)}unload(){for(var e of(this.mr&&(clearTimeout(this.mr),this.mr=void 0),this.ur=!1,C(w)||(this.vr&&(w.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(w.removeEventListener("offline",this.pr),this.pr=void 0)),this.tr)){var n=e.requestOptions;try{this._instance._send_request(I({},n,{transport:"sendBeacon"}))}catch(i){A.error(i)}}this.tr=[]}}class Em{constructor(e){this.yr=()=>{var n,i,r,s;this.br||(this.br={});var o=this.scrollElement(),a=this.scrollY(),l=o?Math.max(0,o.scrollHeight-o.clientHeight):0,u=a+(o?.clientHeight||0),c=o?.scrollHeight||0;this.br.lastScrollY=Math.ceil(a),this.br.maxScrollY=Math.max(a,(n=this.br.maxScrollY)!==null&&n!==void 0?n:0),this.br.maxScrollHeight=Math.max(l,(i=this.br.maxScrollHeight)!==null&&i!==void 0?i:0),this.br.lastContentY=u,this.br.maxContentY=Math.max(u,(r=this.br.maxContentY)!==null&&r!==void 0?r:0),this.br.maxContentHeight=Math.max(c,(s=this.br.maxContentHeight)!==null&&s!==void 0?s:0)},this._instance=e}get _r(){return this._instance.config.scroll_root_selector}getContext(){return this.br}resetContext(){var e=this.br;return setTimeout(this.yr,0),e}startMeasuringScrollPosition(){ve(w,"scroll",this.yr,{capture:!0}),ve(w,"scrollend",this.yr,{capture:!0}),ve(w,"resize",this.yr)}scrollElement(){if(!this._r)return w?.document.documentElement;var e=U(this._r)?this._r:[this._r];for(var n of e){var i=w?.document.querySelector(n);if(i)return i}}wr(e){var n=e==="y"?"scrollTop":"scrollLeft";if(this._r){var i=this.scrollElement();return i&&i[n]||0}return w?e==="y"?w.scrollY||w.pageYOffset||w.document.documentElement.scrollTop||0:w.scrollX||w.pageXOffset||w.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var Sm=t=>Pf(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class nu{constructor(e,n,i,r){this.kr=s=>{var o=this.Sr();if(!o||o.sessionId!==s){var a={sessionId:s,props:this.Cr(this._instance)};this.Mr.register({[fa]:a})}},this._instance=e,this.Tr=n,this.Mr=i,this.Cr=r||Sm,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[fa]}getSetOnceProps(){var e,n=(e=this.Sr())==null?void 0:e.props;return n?"r"in n?Ff(n,this._instance.config.disable_capture_url_hashes):{$referring_domain:n.referringDomain,$pathname:n.initialPathName,utm_source:n.utm_source,utm_campaign:n.utm_campaign,utm_medium:n.utm_medium,utm_content:n.utm_content,utm_term:n.utm_term}:{}}getSessionProps(){var e={};return ie(dl(this.getSetOnceProps()),((n,i)=>{i==="$current_url"&&(i="url"),e["$session_entry_"+Yo(i)]=n})),e}}class vl{on(e,n){return this.Er[e]||(this.Er[e]=[]),this.Er[e].push(n),()=>{this.Er[e]=this.Er[e].filter((i=>i!==n))}}emit(e,n){for(var i of this.Er[e]||[])i(n);for(var r of this.Er["*"]||[])r(e,n)}constructor(){this.Er={}}}var xi=pe("[SessionId]");class iu{on(e,n){return this.Ir.on(e,n)}constructor(e,n,i){var r;if(this.Pr=null,this.Rr=[],this.Ar=void 0,this.Fr=!1,this.Ir=new vl,this.Lr=(u,c)=>!(!Dt(u)||!Dt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===Wt)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Ne=e.config,this.Mr=e.persistence,this.Or=void 0,this.Dr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.$r=n||Ht,this.Nr=i||Ht;var s=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*At(this.Ne.session_idle_timeout_seconds||1800,60,36e3,xi.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.qr(),this.jr="ph_"+s+"_window_id",this.Br="ph_"+s+"_primary_window_exists",this.Hr()){var o=be.H(this.jr),a=be.H(this.Br);o&&!a?this.Or=o:be.q(this.jr),be.F(this.Br,!0)}if((r=this.Ne.bootstrap)!=null&&r.sessionID)try{var l=(u=>{var c=this.Ne.bootstrap.sessionID.replace(/-/g,"");if(c.length!==32)throw new Error("Not a valid UUID");if(c[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(c.substring(0,12),16)})();this.Ur(this.Ne.bootstrap.sessionID,new Date().getTime(),l)}catch(u){xi.error("Invalid sessionID in bootstrap",u)}this.zr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return C(this.Rr)&&(this.Rr=[]),this.Rr.push(e),this.Dr&&e(this.Dr,this.Or),()=>{this.Rr=this.Rr.filter((n=>n!==e))}}Hr(){return this.Ne.persistence!=="memory"&&!this.Mr.xi&&be.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&be.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?be.H(this.jr):null}Zr(e){var n=this.Pr;return!Ye(n)&&!Ye(e)&&5e3>Math.abs(e-n)}Ur(e,n,i){var r=n!==this._sessionActivityTimestamp,s=!(e!==this.Dr||i!==this._sessionStartTimestamp);this._sessionStartTimestamp=i,this._sessionActivityTimestamp=n,this.Dr=e,s&&!r||s&&this.Zr(n)||(this.Pr=n,this.Mr.register({[Yn]:[n,e,i]}))}Gr(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return Dt(n)&&n>0}Qr(){this.Gr()?this.Mr.refreshKey(Yn):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!Ye(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this.Pr){this.Qr();var n=this.Jr();n[1]===this.Dr&&n[2]===this._sessionStartTimestamp&&(this.Pr=this._sessionActivityTimestamp,this.Mr.register({[Yn]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],n=Dt(e)?e:0,i=Dt(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(n,i)}Xr(e){return this.Qr(),this.Lr(e,this.Yr())}Jr(){var e=this.Mr.props[Yn];return U(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Pr=null,clearTimeout(this.tn),this.tn=void 0,this.Ur(null,null,null)}destroy(){this.Fr=!0,this.Kr(),clearTimeout(this.tn),this.tn=void 0,this.Ar&&w&&(w.removeEventListener(is,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&be.q(this.Br)},ve(w,is,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=null),this.Ne.cookieless_mode===Wt)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var i=n||new Date().getTime(),r=this.Jr(),s=r[1],o=r[2],a=this.Yr(),l=this.Vr(),u=Dt(o)&&Math.abs(i-o)>864e5,c=!1,d=!1,f=!s,h=s,p=!f&&!e&&this.Lr(i,a);if(p){(p=this.Xr(i))||xi.info("cross-tab refresh kept the session alive",{sessionId:s});var g=this.Jr();s=g[1],o=g[2]}f||p||u?(s=this.$r(),l=this.Nr(),xi.info("new session ID generated",{sessionId:s,windowId:l,changeReason:{noSessionId:f,activityTimeout:p,sessionPastMaximumLength:u}}),o=i,c=!0):(l||(l=this.Nr(),c=!0),(d=s!==h)&&(xi.info("adopted cross-tab session id",{sessionId:s,windowId:l}),c=!0));var m=Dt(a)&&e&&!u?a:i,v=Dt(o)?o:new Date().getTime();this.Wr(l),this.Ur(s,m,v),e||this.qr();var E={noSessionId:f,activityTimeout:p,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((S=>S(s,l,E))),{sessionId:s,windowId:l,sessionStartTimestamp:v,changeReason:c?E:void 0,lastActivityTimestamp:a}}qr(){this.Fr||(clearTimeout(this.tn),this.tn=setTimeout((()=>{if(!this.Fr)if(this.Xr(new Date().getTime())){var e=this.Dr;this.resetSessionId(),this.Ir.emit("forcedIdleReset",{idleSessionId:e})}else this.qr()}),1.1*this.sessionTimeoutMs))}}var zf=function(t,e){if(!t)return!1;var n=t.userAgent;if(n&&Ec(n,e))return!0;try{var i=t?.userAgentData;if(i!=null&&i.brands&&i.brands.some((r=>Ec(r?.brand,e))))return!0}catch{}return!!t.webdriver};function qf(){return(qf=se((function*(){var t=He?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),n=e?.model;return X(n)&&n.length>0?n:void 0}catch(i){return void A.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",i)}}))).apply(this,arguments)}var us=function(t,e){if(!(function(n){try{new RegExp(n)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function To(t,e,n){return Jn({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}var Vf={exact:(t,e)=>e.some((n=>t.some((i=>n===i)))),is_not:(t,e)=>e.every((n=>t.every((i=>n!==i)))),regex:(t,e)=>e.some((n=>t.some((i=>us(n,i))))),not_regex:(t,e)=>e.every((n=>t.every((i=>!us(n,i))))),icontains:(t,e)=>e.map(Sr).some((n=>t.map(Sr).some((i=>n.includes(i))))),not_icontains:(t,e)=>e.map(Sr).every((n=>t.map(Sr).every((i=>!n.includes(i))))),gt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>i>parseFloat(r)))})),lt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>it.toLowerCase();function Gf(t,e){return!t||Object.entries(t).every((n=>{var i=n[1],r=e?.[n[0]];if(C(r)||Ye(r))return!1;var s=[String(r)],o=Vf[i.operator];return!!o&&o(i.values,s)}))}var ka="custom",ru="i.posthog.com",xm=/^\/static\//;class Im{constructor(e){this.en={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,n=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return n||(n=this.apiHost.replace("."+ru,".posthog.com")),n==="https://app.posthog.com"?"https://us.posthog.com":n}get region(){return this.en[this.apiHost]||(this.en[this.apiHost]=/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"us":/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"eu":ka),this.en[this.apiHost]}rn(e){if(xm.test(e)){var n=this.instance.config.asset_host;if(typeof n=="string")return n.trim().replace(/\/$/,"")||void 0}}endpointFor(e,n){if(n===void 0&&(n=""),n&&(n=n[0]==="/"?n:"/"+n),e==="ui")return this.uiHost+n;if(e==="flags")return this.flagsApiHost+n;if(e==="assets"){var i=this.rn(n);if(i)return""+i+n}if(this.region===ka)return this.apiHost+n;var r=ru+n;switch(e){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}}function Kf(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var Q=pe("[Surveys]"),Yf="seenSurvey_",Jf=t=>{try{var e=(n=>((i,r)=>""+Yf+(function(s){return s.current_iteration&&s.current_iteration>0?s.id+"_"+s.current_iteration:s.id})(r))(0,n))(t);if(localStorage.getItem(e))return;localStorage.setItem(e,"true")}catch(n){Q.error("Failed to persist survey seen state",n)}},km=[Co.Popover,Co.Widget,Co.API],Cm={ignoreConditions:!1,ignoreDelay:!1,displayType:wa.Popover},Am=pe("[PostHog ExternalIntegrations]"),Pm={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class Fm{constructor(e){this._instance=e}ai(e,n){var i;(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,e,(r=>{if(r)return Am.error("failed to load script",r);n()}))}startIfEnabledOrStop(){var e=this,n=function(){var s,o,a,l=i[0],u=i[1];!u||(s=B.__PosthogExtensions__)!=null&&(s=s.integrations)!=null&&s[l]||e.ai(Pm[l],(()=>{var c;(c=B.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=B.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=B.__PosthogExtensions__)==null||(a=a.integrations)==null||(a=a[l])==null||a.stop())};for(var i of Object.entries((r=this._instance.config.integrations)!==null&&r!==void 0?r:{})){var r;n()}}}class Rm{constructor(e,n){this.rt=e,this.nn=n,this.sn=new Map,this.an=!1}add(e){var n=this;return se((function*(){if(n.an)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(n.sn.has(e.name))throw new Error('Browser extension "'+e.name+'" is already registered');n.sn.set(e.name,e);try{var i=e.setup(n.nn);i&&(yield i)}catch(s){var r=n.sn.get(e.name)===e;r&&n.sn.delete(e.name),n.rt.error('Failed to set up browser extension "'+e.name+'"',s),r&&n.ln(e)}}))()}dispose(){if(!this.an){this.an=!0;var e=Array.from(this.sn.values()).reverse();for(var n of(this.sn.clear(),e))this.ln(n)}}ln(e){try{var n=e.dispose==null?void 0:e.dispose();n&&je(n.then)&&n.then(void 0,(i=>{this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}))}catch(i){this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}}}class Tm{constructor(e){this._instance=e}initialize(){}get(e){var n=this._instance.persistence;if(typeof e=="string")return n?.get_property(e);var i={};for(var r of e){var s=n?.get_property(r);C(s)||(i[r]=s)}return i}set(e,n){var i;(i=this._instance.persistence)==null||i.register(typeof e=="string"?{[e]:n}:e)}remove(e){var n;(n=this._instance.persistence)==null||n.unregister(e)}}var su="extensionsRemoteConfig";class $m{constructor(e){this.an=!1,this.instance=e,this.rt=A,this.un=e.hn,this.kv=new Tm(e),this.onEvent=n=>Er(this.instance.on("eventCaptured",(i=>{try{n({event:i.event,properties:i.properties})}catch(r){this.rt.error("Browser extension event listener failed",r)}}))),this.onRemoteConfig=n=>{if(this.an)return Er((()=>{}));var i=s=>{try{n(s)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},r=this.instance.dn.on(su,i);return this.un&&i(this.un),Er(r)},this.vn=new Rm(A.createLogger("[BrowserExtensions]"),this)}get logger(){return this.rt}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return(e=this.instance.get_property(Ji))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(Ji);return typeof e=="string"?e:void 0}get library(){return{name:ne.LIB_NAME,version:ne.LIB_VERSION}}get initialPersonProperties(){var e,n;return(e=(n=this.instance.persistence)==null?void 0:n.get_initial_props())!==null&&e!==void 0?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,n,i,r,s=(e=this.instance.sessionManager)==null?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:(n=s?.sessionId)!==null&&n!==void 0?n:"",windowId:(i=s?.windowId)!==null&&i!==void 0?i:"",sessionStartTimestamp:(r=s?.sessionStartTimestamp)!==null&&r!==void 0?r:0}}catch{return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get projectToken(){return this.instance.config.token}add(e){return this.vn.add(e)}capture(e,n,i){var r=this;return se((function*(){i?r.instance.capture(e,n,{timestamp:i.timestamp,uuid:i.uuid,$set:i.set,$set_once:i.setOnce}):r.instance.capture(e,n)}))()}registerDynamicEventProperties(e){return Er(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(su,e))}sendRequest(e,n){var i=this;return se((function*(){var r;n===void 0&&(n={});var s=i.instance.requestRouter.endpointFor((r=n.target)!==null&&r!==void 0?r:"api",e),o={method:n.method,url:n.query?Cs(s,n.query):s,data:n.body,headers:n.headers,timeout:n.timeoutMs,fireCallbackOnDrop:!0,transport:n.transport,compression:n.compression,timestampMode:n.sentAt};return n.transport==="sendBeacon"?(i.instance._send_request(o),{statusCode:202}):new Promise((a=>{o.callback=a,i.instance._send_request(o)}))}))()}dispose(){this.an||(this.an=!0,this.vn.dispose())}}var zi={},$o=0,ds=()=>{},ou='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',Ii="Surveys module not available",au="sanitize_properties is deprecated. Use before_send instead",Zf="Invalid value for property_denylist config: ",Mm=["token","distinct_id",rf],Kn="posthog",Xf=!mm&&Ge?.indexOf("MSIE")===-1&&Ge?.indexOf("Mozilla")===-1,Mo=t=>{var e;return I({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:Lg(P?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:ds,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:t??"unset",__preview_deferred_init_extensions:!1,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:me&&X(me?.search)&&me.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disableDeviceModel:!1,disable_external_dependency_loading:!1,strict_script_versioning:!1,enable_recording_console_log:void 0,secure_cookie:(w==null||(e=w.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(n){A.error("Bad HTTP status: "+n.statusCode+" "+n.text)},get_device_id:n=>n,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:ma,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:Ia},error_tracking:{},_onCapture:ds},(n=>({rageclick:n&&n>="2026-05-30"?{content_ignorelist:Gg,ignore_text_selection:!0}:!n||"2025-11-30">n||{content_ignorelist:!0},capture_pageview:!n||"2025-05-24">n||"history_change",session_recording:n&&n>="2026-06-25"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6},streamNetworkBody:!0}:n&&n>="2026-05-30"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6}}:n&&n>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:n&&n>="2026-01-30"?"head":"body",internal_or_test_user_hostname:n&&n>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:n&&n>="2026-05-30"?250:0,split_storage:!(!n||"2026-05-30">n),detect_google_search_app:!(!n||"2026-05-30">n),disable_capture_url_hashes:!(!n||"2026-06-25">n)}))(t))},Lm=[["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"]],lu=t=>{var e={};for(var n of Lm){var i=n[0],r=n[1];C(t[i])||(e[r]=t[i])}var s=fe({},e,t),o=t.__preview_external_dependency_versioned_paths;return C(o)||(C(t.strict_script_versioning)&&(s.strict_script_versioning=!!o),X(o)&&C(t.asset_host)&&(s.asset_host=o)),U(t.property_blacklist)&&(C(t.property_denylist)?s.property_denylist=t.property_blacklist:U(t.property_denylist)?s.property_denylist=[...t.property_blacklist,...t.property_denylist]:A.error(Zf+t.property_denylist)),s};class Nm{constructor(){this.__forceAllowLocalhost=!1}get fn(){return this.__forceAllowLocalhost}set fn(e){A.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class Ze{pn(e,n){if(e){var i=this.sn.indexOf(e);i!==-1&&this.sn.splice(i,1)}return this.sn.push(n),n.initialize==null||n.initialize(),n}gn(){return this.config.cookieless_mode===Wt||this.config.cookieless_mode===kn&&this.consent.isRejected()}get decideEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){var e;this.webPerformance=new Nm,this.mn=!1,this.version=ne.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new vl,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=Mo(),this.SentryIntegration=tm,this.sentryIntegration=i=>(function(r,s){var o=Ef(r,s);return{name:bf,processEvent:a=>o(a)}})(this,i),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.wn=!1,this.kn=null,this.xn=null,this.Sn=null,this.scrollManager=new Em(this),this.pageViewManager=new Gc(this),this.rateLimiter=new um(this),this.requestRouter=new Im(this),this.consent=new Hg(this),this.externalIntegrations=new Fm(this);var n=(e=Ze.__defaultExtensionClasses)!==null&&e!==void 0?e:{};this.featureFlags=n.featureFlags&&new n.featureFlags(this),this.toolbar=n.toolbar&&new n.toolbar(this),this.surveys=n.surveys&&new n.surveys(this),this.conversations=n.conversations&&new n.conversations(this),this.logs=n.logs&&new n.logs(this),this.metrics=n.metrics&&new n.metrics(this),this.experiments=n.experiments&&new n.experiments(this),this.exceptions=n.exceptions&&new n.exceptions(this),this.people={set:(i,r,s)=>{var o=X(i)?{[i]:r}:i;this.setPersonProperties(o),s?.({})},set_once:(i,r,s)=>{var o=X(i)?{[i]:r}:i;this.setPersonProperties(void 0,o),s?.({})}},this.on("eventCaptured",(i=>A.info('send "'+i?.event+'"',i)))}init(e,n,i){if(i&&i!==Kn){var r,s=(r=zi[i])!==null&&r!==void 0?r:new Ze;return s._init(e,n,i),zi[i]=s,zi[Kn][i]=s,s}return this._init(e,n,i)}_init(e,n,i){var r,s;n===void 0&&(n={});var o,a=X(e)?e.trim():"";if(!a)return A.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return a!==((o=this.config)==null?void 0:o.token)?console.warn("[PostHog.js]","You have already initialized PostHog with a different project token! Re-initializing is a no-op, so events will keep going to the project this instance was initialized with. To capture into a second project, load PostHog once, then initialize a named instance after the SDK has loaded, e.g. posthog.init('"+a+"', { ... }, 'project2')"):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=Mo(n.defaults),n.debug=this.Cn(n.debug),this.Mn=n,this.Tn=[],n.person_profiles?this.xn=n.person_profiles:n.process_person&&(this.xn=n.process_person);var l=Mo(n.defaults),u=lu(n),c=fe({},l,u,{name:i,token:a});he(l.rageclick)&&he(u.rageclick)&&(c.rageclick=fe({},l.rageclick,u.rageclick)),he(l.session_recording)&&he(u.session_recording)&&(c.session_recording=fe({},l.session_recording,u.session_recording)),this.set_config(c),this.config.on_xhr_error&&A.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=n.disable_compression?void 0:Ue.GZipJS;var d=this.En();if(this.persistence=new ko(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new ko(I({},this.config,{persistence:"sessionStorage"}),d,!1),this.bn="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&be.N()){var f=be.H(this.bn);U(f)&&f.forEach((k=>{X(k)&&this.yn.add(k)}))}else be.q(this.bn);var h=I({},this.persistence.props),p=I({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new ym((k=>this.Pn(k)),this.config.request_queue_config),this.Rn=new bm(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new iu(this),this.sessionPropsManager=new nu(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((k,T,x)=>{(x!=null&&x.activityTimeout||x!=null&&x.sessionPastMaximumLength||x!=null&&x.crossTabAdoption)&&this.An()}))),this.Fn(),this.config.__preview_deferred_init_extensions?(A.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Ln(g)}),0)):(A.info("Initializing extensions synchronously"),this.Ln(g)),ne.DEBUG=ne.DEBUG||this.config.debug,ne.DEBUG&&A.info("Starting in debug mode",{this:this,config:n,thisC:I({},this.config),p:h,s:p}),!this.config.identity_distinct_id||(r=n.bootstrap)!=null&&r.distinctID||(n.bootstrap=I({},n.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((s=n.bootstrap)==null?void 0:s.distinctID)!==void 0){var m=n.bootstrap.distinctID,v=this.get_distinct_id(),E=this.persistence.get_property(at);if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&E===Hn)this.identify(m);else if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&E===vn)A.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{var S=this.config.get_device_id(Ht()),_=n.bootstrap.isIdentifiedID?S:m;this.persistence.set_property(at,n.bootstrap.isIdentifiedID?vn:Hn),this.register({distinct_id:m,$device_id:_})}}if(g)this.register_once({distinct_id:vr,$device_id:null},"");else if(!this.get_distinct_id()){var b=this.config.get_device_id(Ht());this.register_once({distinct_id:b,$device_id:b},""),this.persistence.set_property(at,Hn)}return ve(w,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),n.segment?(function(k,T){var x=k.config.segment;if(!x)return T();(function(F,$){var O=F.config.segment;if(!O)return $();var L=K=>{var V=()=>K.anonymousId()||Ht();F.config.get_device_id=V,K.id()&&(F.register({distinct_id:K.id(),$device_id:V()}),F.persistence.set_property(at,vn)),$()},N=O.user();"then"in N&&je(N.then)?N.then(L):L(N)})(k,(()=>{x.register((F=>{typeof Promise<"u"&&Promise.resolve||xo.warn("This browser does not have Promise support, and can not use the segment integration");var $=(O,L)=>{if(!L)return O;O.event.userId||O.event.anonymousId===F.get_distinct_id()||(xo.info("No userId set, resetting PostHog"),F.reset()),O.event.userId&&O.event.userId!==F.get_distinct_id()&&(xo.info("UserId set, identifying with PostHog"),F.identify(O.event.userId));var N=F.calculateEventProperties(L,O.event.properties);return O.event.properties=Object.assign({},N,O.event.properties),O};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:O=>$(O,O.event.event),page:O=>$(O,Gn),identify:O=>$(O,bo),screen:O=>$(O,"$screen")}})(k)).then((()=>{T()}))}))})(this,(()=>this.On())):this.On(),je(this.config._onCapture)&&this.config._onCapture!==ds&&(A.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(k=>this.config._onCapture(k.event,k)))),this.config.ip&&A.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this.config.disableDeviceModel||(function(){return qf.apply(this,arguments)})().then((k=>{k&&this.register({[yo]:k})})).catch(ds),this}Fn(){var e,n,i,r,s,o,a=(e=(n=this.config.__extensionClasses)==null?void 0:n.featureFlags)!==null&&e!==void 0?e:(i=Ze.__defaultExtensionClasses)==null?void 0:i.featureFlags;a&&(this.featureFlags&&this.featureFlags instanceof a||((r=this.Dn)==null||r.call(this),this.Dn=void 0,this.featureFlags=new a(this)),je(this.featureFlags.onReloading)&&je(this.featureFlags.setup)?this.Dn||(this.Dn=this.featureFlags.onReloading((()=>{this.dn.emit("featureFlagsReloading",!0)})),this.$n().add(this.featureFlags)):(s=(o=this.featureFlags).initialize)==null||s.call(o))}Ln(e){var n,i,r,s,o,a,l,u=performance.now(),c=I({},Ze.__defaultExtensionClasses,this.config.__extensionClasses),d=[];c.exceptions&&this.sn.push(this.exceptions=(n=this.exceptions)!==null&&n!==void 0?n:new c.exceptions(this)),c.historyAutocapture&&this.sn.push(this.historyAutocapture=new c.historyAutocapture(this)),c.tracingHeaders&&this.sn.push(this.tracingHeaders=new c.tracingHeaders(this)),c.siteApps&&this.sn.push(this.siteApps=new c.siteApps(this)),c.sessionRecording&&!e&&this.sn.push(this.sessionRecording=new c.sessionRecording(this)),this.config.disable_scroll_properties||d.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),c.autocapture&&this.sn.push(this.autocapture=new c.autocapture(this)),c.surveys&&this.sn.push(this.surveys=(i=this.surveys)!==null&&i!==void 0?i:new c.surveys(this)),c.logs&&this.sn.push(this.logs=(r=this.logs)!==null&&r!==void 0?r:new c.logs(this)),c.metrics&&this.sn.push(this.metrics=(s=this.metrics)!==null&&s!==void 0?s:new c.metrics(this)),c.conversations&&this.sn.push(this.conversations=(o=this.conversations)!==null&&o!==void 0?o:new c.conversations(this)),c.productTours&&this.sn.push(this.productTours=new c.productTours(this)),c.heatmaps&&this.sn.push(this.heatmaps=new c.heatmaps(this)),c.webVitalsAutocapture&&this.sn.push(this.webVitalsAutocapture=new c.webVitalsAutocapture(this)),c.exceptionObserver&&this.sn.push(this.exceptionObserver=new c.exceptionObserver(this)),c.deadClicksAutocapture&&this.sn.push(this.deadClicksAutocapture=new c.deadClicksAutocapture(this,em)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((f=>{f.initialize&&d.push((()=>{f.initialize==null||f.initialize()}))})),d.push((()=>{if(this.Nn){var f=this.Nn;this.Nn=void 0,this.sn.forEach((h=>h.onRemoteConfig==null?void 0:h.onRemoteConfig(f)))}})),this.qn(d,u)}qn(e,n){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,n)}),0);var i=e.shift();if(i)try{i()}catch(s){A.error("Error initializing extension:",s)}}var r=Math.round(performance.now()-n);this.register_for_session({[sf]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[of]:r}),this.config.__preview_deferred_init_extensions&&A.info("PostHog extensions initialized ("+r+"ms)")}Zi(e){var n;if(!P||!P.body)return A.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.Zi(e)}),500);if(this.config.__preview_deferred_init_extensions&&(this.Nn=e),this.hn=e,this.compression=void 0,e.ok){var i,r=e.config;r.supportedCompression&&!this.config.disable_compression&&(this.compression=j(r.supportedCompression,Ue.GZipJS)?Ue.GZipJS:j(r.supportedCompression,Ue.Base64)?Ue.Base64:void 0),(i=r.analytics)!=null&&i.endpoint&&(this.analyticsDefaultEndpoint=r.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:ma}),(n=this.jn)==null||n.handleRemoteConfig(e),this.sn.forEach((s=>s.onRemoteConfig==null?void 0:s.onRemoteConfig(e)))}On(){try{this.config.loaded(this)}catch(i){A.critical("`loaded` function failed",i)}if(this.Bn(),this.config.internal_or_test_user_hostname&&me!=null&&me.hostname){var e=me.hostname,n=this.config.internal_or_test_user_hostname;(typeof n=="string"?e===n:n.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.gn())&&this.Hn()}),1),this.Un=new Tf(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,n,i,r,s;(e=this.surveys)==null||e.handlePageUnload==null||e.handlePageUnload(),(n=this.metrics)==null||n.flush("sendBeacon"),this.config.request_batching?(this.zn()&&this.capture(wo),(i=this.logs)==null||i.flushLogs("sendBeacon"),(r=this.In)==null||r.unload(),(s=this.Rn)==null||s.unload()):this.zn()&&this.capture(wo,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?Xf?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)?e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:429})):(e.transport=e.transport||this.config.api_transport,e.headers=I({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,(C(this.config.disable_beacon)?this.config.__preview_disable_beacon:this.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(n=>{var i,r,s,o=I({},n);o.timeout=o.timeout||6e4;var a,l,u,c,d,f=(i=o.transport)!==null&&i!==void 0?i:"fetch";f==="sendBeacon"&&C(o.compression)&&o.data&&(o.compression=Ue.Base64),o.method==="POST"&&o.data&&(o.timestampMode==="capture-body"?o.data={api_key:(l=(d=(c=U(a=o.data)?a:[a])[0])==null||(u=d.properties)==null?void 0:u.token)!==null&&l!==void 0?l:d?.token,batch:c,sent_at:new Date().toISOString()}:o.timestampMode==="body"&&(o.data=(function(m,v){return v===void 0&&(v=new Date().toISOString()),U(m)?m.map((E=>I({},E,{sent_at:v}))):I({},m,{sent_at:v})})(o.data))),o.url=tu(o.url,o.method,o.compression,o.timestampMode);var h=Nr.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),p=(r=(s=(function(m,v){for(var E=0;m.length>E;E++)if(m[E].transport===f)return m[E]})(h))==null?void 0:s.method)!==null&&r!==void 0?r:h[0].method;if(!p)throw new Error("No available transport method");var g=m=>{try{p(m)}catch(v){Hf(v)?A.warn(v):A.error(v),o.callback==null||o.callback({statusCode:0,error:v})}};f!=="sendBeacon"&&o.data&&o.compression===Ue.GZipJS&&Op&&typeof Promise<"u"&&!Lr?vm(o).then((m=>{g(m)})).catch((m=>{if(bc(m))return Lr=!0,void g(I({},o,{compression:void 0,url:tu(n.url,n.method,void 0,n.timestampMode)}));(v=>{if(!v||typeof v!="object")return!1;var E="name"in v?String(v.name):"";return bc(v)||E===vd})(m)&&(Lr=!0),g(o)})):p(o)})(I({},e,{callback:n=>{var i,r;this.rateLimiter.checkForLimiting(n),400>n.statusCode||(i=(r=this.config).on_request_error)==null||i.call(r,n),e.callback==null||e.callback(n)}}))):e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:0}))}Pn(e){this.Rn?this.Rn.retriableRequest(e):this._send_request(e)}_execute_array(e){$o++;try{var n,i=[],r=[],s=[];_r(e,(a=>{if(a)if(U(n=a[0]))s.push(a);else if(je(a))try{a.call(this)}catch(l){A.error("Error executing queued PostHog call",a,l)}else U(a)&&n==="alias"?i.push(a):U(a)&&n.indexOf("capture")!==-1&&je(this[n])?s.push(a):r.push(a)}));var o=function(a,l){_r(a,(function(u){try{if(U(u[0])){var c=l;ie(u,(function(d){c=c[d[0]].apply(c,d.slice(1))}))}else l[u[0]].apply(l,u.slice(1))}catch(d){A.error("Error executing queued PostHog call",u,d)}}))};o(i,this),o(r,this),o(s,this)}finally{$o--}}push(e){if($o>0&&U(e)&&X(e[0])){var n=Ze.prototype[e[0]];je(n)&&n.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,n,i){var r,s,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.In){if(this.is_capturing())if(!C(e)&&X(e)){var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var c=i!=null&&i.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(c==null||!c.isRateLimited){n!=null&&n.$current_url&&!X(n?.$current_url)&&(A.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),n==null||delete n.$current_url),e!=="$exception"||i!=null&&i.Wn||A.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,f=i?.timestamp||d,h=kc(i?.uuid,Ht),p={uuid:h,event:e,properties:this.calculateEventProperties(e,n||{},f,h)};e===Gn&&this.config.__preview_capture_bot_pageviews&&u&&(p.event="$bot_pageview",p.properties.$browser_type="bot"),c&&(p.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&p.properties.$feature_flag_has_experiment===!1&&this.get_property(Xr)===!0;i?.$set&&!g&&(p.$set=i?.$set);var m=i?.$unset;m&&(p.$unset=m);var v,E,S,_=g?void 0:this.Vn(i?.$set_once,e!==Tc,e===bo);if(_&&(p.$set_once=_),i!=null&&i._noTruncate||(s=this.config.properties_string_max_length,o=p,a=L=>X(L)?L.slice(0,s):L,l=new Set,p=(function L(N,K){if(N!==Object(N))return a?a(N):N;if(!l.has(N)){var V;if(l.add(N),U(N))V=[],_r(N,(R=>{V.push(L(R))}));else{var M={};ie(N,((R,Z)=>{l.has(R)||(M[Z]=L(R))})),V=M}return V}})(o)),p.timestamp=f,C(i?.timestamp)||(p.properties.$event_time_override_provided=!0,p.properties.$event_time_override_system_time=d),g&&(p.properties=(function(L,N){N===void 0&&(N=[]);var K={},V=M=>{L[M]!==void 0&&(K[M]=L[M])};return Bp.forEach(V),N.forEach(V),K})(p.properties,Mm)),e===qt.DISMISSED||e===qt.SENT){var b=n?.[Ao.SURVEY_ID],k=n?.[Ao.SURVEY_ITERATION];Jf({id:b,current_iteration:k}),p.$set=I({},p.$set,{[(v={id:b,current_iteration:k},E=e===qt.SENT?"responded":"dismissed",S="$survey_"+E+"/"+v.id,v.current_iteration&&v.current_iteration>0&&(S="$survey_"+E+"/"+v.id+"/"+v.current_iteration),S)]:!0})}else e===qt.SHOWN&&(p.$set=I({},p.$set,{[Ao.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===cm.SHOWN){var T=n?.[Yc.TOUR_TYPE];T&&(p.$set=I({},p.$set,{[Yc.TOUR_LAST_SEEN_DATE+"/"+T]:new Date().toISOString()}))}var x=I({},p.properties.$set,p.$set);if(Kt(x)||this.setPersonPropertiesForFlags(x),!H(this.config.before_send)){var F=this.Pt(p);if(!F)return;(p=F).uuid=kc(p.uuid,Ht)}this.dn.emit("eventCaptured",p);var $=(r=i?._url)!==null&&r!==void 0?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),O={method:"POST",url:$,data:p,compression:"best-available",timestampMode:i?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test($)?"body":"capture-body",batchKey:i?._batchKey,transport:i?.transport};return!this.config.request_batching||i&&(i==null||!i._batchKey)||i!=null&&i.send_instantly?this.Pn(O):this.In.enqueue(O),p}A.critical("This capture call is ignored due to client rate limiting.")}}else A.error("No event name provided to posthog.capture")}else A.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(n=>e(n.event,n)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new $m(this)}cn(e){this._n.push(e);var n=!0;return()=>{if(n){n=!1;var i=this._n.indexOf(e);i!==-1&&this._n.splice(i,1)}}}calculateEventProperties(e,n,i,r,s){if(i=i||new Date,!this.persistence||!this.sessionPersistence)return n;var o=s?void 0:this.persistence.remove_event_timer(e),a=I({},n);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.gn()&&(a[rf]=!0),e==="$snapshot"){var l=I({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!X(a.distinct_id)&&!ke(a.distinct_id)||Jo(a.distinct_id))&&A.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=(function(b,k,T,x){var F,$,O,L;if(x===void 0&&(x=!1),!Ge)return{};var N,K=b?[...si,...k||[]]:[],V=(function(Dn){for(var qe=0;xc.length>qe;qe++){var jn=xc[qe],Mt=jn[1],Lt=jn[0].exec(Dn),ut=Lt&&(je(Mt)?Mt(Lt,Dn):Mt);if(ut)return ut}return["",""]})(Ge),M=V[0],R=V[1],Z=(N=typeof navigator<"u"?navigator:void 0)!=null&&N.brave?{brave:!0}:{},Ce={};C(T)||(Ce.detectGoogleSearchApp=T);var oe={},ye=(F=navigator)==null||(F=F.userAgentData)==null?void 0:F.platform,$e=($=navigator)==null?void 0:$.maxTouchPoints,ae=w==null||(O=w.screen)==null?void 0:O.width,Ie=w==null||(L=w.screen)==null?void 0:L.height,Se=w?.devicePixelRatio;C(ye)||(oe.userAgentDataPlatform=ye),C($e)||(oe.maxTouchPoints=$e),C(ae)||(oe.screenWidth=ae),C(Ie)||(oe.screenHeight=Ie),C(Se)||(oe.devicePixelRatio=Se);var De,wt,ge,Je,bt,mn,Re,Pe,$t=fe(dl({$os:M,$os_version:R,$browser:Hd(Ge,navigator.vendor,Z,Ce),$device:Ic(Ge),$device_type:(wt=Ge,ge=oe,Pe=Ic(wt),Pe===xd||Pe===Sd||Pe==="Kobo"||Pe==="Kindle Fire"||Pe===Od?ti:Pe===Ki||Pe===Qn||Pe===Yi||Pe===Xo?"Console":Pe===kd?"Wearable":Pe?rt:ge?.userAgentDataPlatform==="Android"&&((Je=ge?.maxTouchPoints)!==null&&Je!==void 0?Je:0)>0?600>Math.min((bt=ge?.screenWidth)!==null&&bt!==void 0?bt:0,(mn=ge?.screenHeight)!==null&&mn!==void 0?mn:0)/((Re=ge?.devicePixelRatio)!==null&&Re!==void 0?Re:1)?rt:ti:"Desktop"),$timezone:Rf(),$timezone_offset:om()}),{$current_url:Xi(x?fn(me?.href):me?.href,K,Qi),$host:me?.host,$pathname:me?.pathname,$raw_user_agent:Ge.length>1e3?Ge.substring(0,997)+"...":Ge,$browser_version:ig(Ge,navigator.vendor,Z,Ce),$browser_language:Kc(),$browser_language_prefix:(De=Kc(),typeof De=="string"?De.split("-")[0]:void 0),$screen_height:w?.screen.height,$screen_width:w?.screen.width,$viewport_height:w?.innerHeight,$viewport_width:w?.innerWidth,$lib:ne.LIB_NAME,$lib_version:ne.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return ne.SDK_DIST_CHANNEL&&($t.$sdk_dist_channel=ne.SDK_DIST_CHANNEL),$t})(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties,this.config.detect_google_search_app,this.config.disable_capture_url_hashes);if(this.sessionManager){var d=this.sessionManager.checkAndGetSessionAndWindowId(s,i.getTime()),f=d.windowId;a.$session_id=d.sessionId,a.$window_id=f}this.sessionPropsManager&&fe(a,this.sessionPropsManager.getSessionProps());try{var h;this.sessionRecording&&fe(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(h=this.Rn)==null?void 0:h.length}catch(b){a.$sdk_debug_error_capturing_properties=String(b)}if(this.requestRouter.region===ka&&(a.$lib_custom_api_host=this.config.api_host),u=e!==Gn||s?e!==wo||s?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(i):this.pageViewManager.doPageView(i,r),a=fe(a,u),e===Gn&&P&&(a.title=P.title),!C(o)){var p=i.getTime()-o;a.$duration=parseFloat((p/1e3).toFixed(3))}Ge&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();ie(["$referrer","$referring_domain"],(b=>{b in g&&delete m[b]}));var v={};if(this._n.length>0)for(var E of this._n.slice())try{fe(v,E())}catch(b){A.error("Failed to produce browser extension event properties",b)}(a=fe({},c,g,m,I({},v,a))).$is_identified=this._isIdentified(),U(this.config.property_denylist)?ie(this.config.property_denylist,(function(b){delete a[b]})):A.error(Zf+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var S=this.config.sanitize_properties;S&&(A.error(au),a=S(a,e));var _=this.Zn();return a.$process_person_profile=_,_&&!s&&this.Gn("_calculate_event_properties"),a}Vn(e,n,i){var r;if(n===void 0&&(n=!0),i===void 0&&(i=!1),!this.persistence||!this.Zn()||this.mn&&!i)return e;var s=this.persistence.get_initial_props(),o=(r=this.sessionPropsManager)==null?void 0:r.getSetOnceProps(),a=fe({},s,o||{},e||{}),l=this.config.sanitize_properties;return l&&(A.error(au),a=l(a,"$set_once")),n&&(this.mn=!0),Kt(a)?void 0:a}register(e,n){var i;(i=this.persistence)==null||i.register(e,n)}register_once(e,n,i){var r;(r=this.persistence)==null||r.register_once(e,n,i)}register_for_session(e){var n;(n=this.sessionPersistence)==null||n.register(e),Object.keys(e).forEach((i=>this.yn.add(i))),this.Qn()}unregister(e){var n;(n=this.persistence)==null||n.unregister(e)}unregister_for_session(e){var n;(n=this.sessionPersistence)==null||n.unregister(e),this.yn.delete(e),this.Qn()}Kn(e,n){this.register({[e]:n})}An(){this.yn.forEach((e=>{var n;(n=this.sessionPersistence)==null||n.unregister(e)})),this.yn.clear(),this.Qn()}Qn(){var e;if(this.bn)if(this.config.persistence==="memory"||(e=this.sessionPersistence)!=null&&e.xi||!be.N())be.q(this.bn);else{var n=[];this.yn.forEach((i=>n.push(i))),n.length>0?be.F(this.bn,n):be.q(this.bn)}}getFeatureFlag(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlag(e,n)}getFeatureFlagPayload(e){var n;return(n=this.featureFlags)==null?void 0:n.getFeatureFlagPayload(e)}getFeatureFlagResult(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlagResult(e,n)}getAllFeatureFlags(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.getAllFeatureFlags())!==null&&e!==void 0?e:[]}isFeatureEnabled(e,n){var i,r;return(i=(r=this.featureFlags)==null?void 0:r.isFeatureEnabled(e,n))!==null&&i!==void 0?i:n?.defaultValue}reloadFeatureFlags(){var e;(e=this.featureFlags)==null||e.reloadFeatureFlags()}updateFlags(e,n,i){var r;(r=this.featureFlags)==null||r.updateFlags(e,n,i)}updateEarlyAccessFeatureEnrollment(e,n,i){var r;(r=this.featureFlags)==null||r.updateEarlyAccessFeatureEnrollment(e,n,i)}getEarlyAccessFeatures(e,n,i){var r;return n===void 0&&(n=!1),(r=this.featureFlags)==null?void 0:r.getEarlyAccessFeatures(e,n,i)}on(e,n){return this.dn.on(e,n)}onFeatureFlags(e){return this.featureFlags?this.featureFlags.onFeatureFlags(e):(e([],{},{errorsLoading:!0}),()=>{})}onSurveysLoaded(e){return this.surveys?this.surveys.onSurveysLoaded(e):(e([],{isLoaded:!1,error:Ii}),()=>{})}onSessionId(e){var n,i;return(n=(i=this.sessionManager)==null?void 0:i.onSessionId(e))!==null&&n!==void 0?n:()=>{}}getSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getSurveys(e,n):e([],{isLoaded:!1,error:Ii})}getActiveMatchingSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,n):e([],{isLoaded:!1,error:Ii})}renderSurvey(e,n){var i;(i=this.surveys)==null||i.renderSurvey(e,n)}displaySurvey(e,n){var i;n===void 0&&(n=Cm),(i=this.surveys)==null||i.displaySurvey(e,n)}cancelPendingSurvey(e){var n;(n=this.surveys)==null||n.cancelPendingSurvey(e)}canRenderSurvey(e){var n,i;return(n=(i=this.surveys)==null?void 0:i.canRenderSurvey(e))!==null&&n!==void 0?n:{visible:!1,disabledReason:Ii}}canRenderSurveyAsync(e,n){var i,r;return n===void 0&&(n=!1),(i=(r=this.surveys)==null?void 0:r.canRenderSurveyAsync(e,n))!==null&&i!==void 0?i:Promise.resolve({visible:!1,disabledReason:Ii})}Jn(e){return!e||Jo(e)?(A.critical("Unique user id has not been set in posthog.identify"),!1):e===vr?(A.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.'),!1):!["distinct_id","distinctid"].includes(e.toLowerCase())&&!["undefined","null"].includes(e.toLowerCase())||(A.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.'),!1)}identify(e,n,i){if(!this.__loaded||!this.persistence)return A.uninitializedWarning("posthog.identify");if(ke(e)&&(e=e.toString(),A.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.Jn(e)&&this.Gn("posthog.identify")){var r=this.get_distinct_id();this.register({$user_id:e}),this.get_property(Ji)||this.register_once({$had_persisted_distinct_id:!0,$device_id:r},""),e!==r&&e!==this.get_property(Ri)&&(this.unregister(Ri),this.register({distinct_id:e}));var s,o=(this.persistence.get_property(at)||Hn)===Hn,a=e!==r,l=!a&&o;if(a&&o)this.persistence.set_property(at,vn),this.setPersonPropertiesForFlags({$set:n||{},$set_once:i||{}},!1),this.capture(bo,{distinct_id:e,$anon_distinct_id:r},{$set:n||{},$set_once:i||{}}),this.Sn=To(e,n,i),(s=this.featureFlags)==null||s.setAnonymousDistinctId(r);else if(l){this.persistence.set_property(at,vn);var u=n||{},c=i||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=To(e,n,i)}else(n||i)&&this.setPersonProperties(n,i);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Cn)):l&&(n||i)&&this.reloadFeatureFlags()}}setPersonProperties(e,n){if((e||n)&&this.Gn("posthog.setPersonProperties")){var i=To(this.get_distinct_id(),e,n);this.Sn!==i?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:n||{}},!0),this.capture("$set",{$set:e||{},$set_once:n||{}}),this.Sn=i):A.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}unsetPersonProperties(e){var n,i=(U(e)?e:[e]).filter((r=>X(r)&&r.length>0));i.length!==0&&this.Gn("posthog.unsetPersonProperties")&&((n=this.featureFlags)==null||n.unsetPersonPropertiesForFlags(i,!0),this.capture("$set",{$unset:i}),this.Sn=null)}group(e,n,i){if(e&&n){var r=this.getGroups(),s=r[e]!==n;if(s&&this.resetGroupPropertiesForFlags(e),this.register({$groups:I({},r,{[e]:n})}),s||i){var o={$group_type:e,$group_key:n};i&&(o.$group_set=i),this.capture(Tc,o)}i&&this.setGroupPropertiesForFlags({[e]:i}),s&&!i&&this.reloadFeatureFlags()}else A.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),(i=this.featureFlags)==null||i.setPersonPropertiesForFlags(e,n)}resetPersonPropertiesForFlags(e){var n;e===void 0&&(e=!0),(n=this.featureFlags)==null||n.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((i=this.featureFlags)==null||i.setGroupPropertiesForFlags(e,n))}resetGroupPropertiesForFlags(e){var n;(n=this.featureFlags)==null||n.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,n){var i,r,s,o,a,l,u,c,d,f;if(n===void 0&&(n=!1),A.info("reset"),!this.__loaded)return A.uninitializedWarning("posthog.reset");var h,p=this.get_property(Ji),g=this.get_property(yo),m=this.get_property(An),v=this.is_capturing();if(this.consent.reset(),n||!v||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after."),(i=this.persistence)==null||i.clear(),(r=this.sessionPersistence)==null||r.clear(),this.yn.clear(),this.Qn(),C(m)||(h=this.persistence)==null||h.register({[An]:m}),(s=this.surveys)==null||s.reset(),(o=this.Un)==null||o.stop(),(a=this.featureFlags)==null||a.reset(),(l=this.conversations)==null||l.reset(),(u=this.logs)==null||u.reset(),(c=this.metrics)==null||c.reset(),(d=this.persistence)==null||d.set_property(at,Hn),(f=this.sessionManager)==null||f.resetSessionId(),this.Sn=null,this.config.cookieless_mode===Wt)this.register_once({distinct_id:vr,$device_id:null},"");else{var E=this.config.get_device_id(Ht());this.register_once({distinct_id:E,$device_id:e?E:p},""),e||C(g)||this.register({[yo]:g})}this.register({$last_posthog_reset:new Date().toISOString()},1),delete this.config.identity_distinct_id,delete this.config.identity_hash,this.reloadFeatureFlags()}shutdown(e){var n=this;return se((function*(){var i,r,s,o,a,l,u;if(n.__loaded){(i=n.Un)==null||i.stop(),(r=n.jn)==null||r.dispose(),(s=n.sessionRecording)==null||s.dispose(),(o=n.logs)==null||o.flushLogs("sendBeacon"),(a=n.metrics)==null||a.flush("sendBeacon"),(l=n.In)==null||l.unload(),(u=n.Rn)==null||u.unload();try{var c;(c=n.featureFlags)==null||c.destroy()}catch(d){A.error("Error while destroying feature flags",d)}}else A.uninitializedWarning("posthog.shutdown")}))()}setIdentity(e,n){var i;this.config.identity_distinct_id=e,this.config.identity_hash=n,this.alias(e),(i=this.conversations)==null||i.Xn()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,(e=this.conversations)==null||e.ts()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,n;return(e=(n=this.sessionManager)==null?void 0:n.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var n=this.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.sessionStartTimestamp,r=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+n.sessionId);if(e!=null&&e.withTimestamp&&i){var s,o=(s=e.timestampLookBack)!==null&&s!==void 0?s:10;if(!i)return r;r+="?t="+Math.max(Math.floor((new Date().getTime()-i)/1e3)-o,0)}return r}alias(e,n){return e===this.get_property(Zd)?(A.critical("Attempting to create alias for existing People user - aborting."),-2):this.Gn("posthog.alias")?(C(n)&&(n=this.get_distinct_id()),e!==n?(this.Kn(Ri,e),this.capture("$create_alias",{alias:e,distinct_id:n})):(A.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var n=I({},this.config);if(he(e)){var i,r,s,o,a,l,u,c,d,f,h,p;fe(this.config,lu(e));var g=this.En();(i=this.persistence)==null||i.update_config(this.config,n,g),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new ko(I({},this.config,{persistence:"sessionStorage"}),g,!1);var m=this.Cn(this.config.debug);mt(m)&&(this.config.debug=m),mt(this.config.debug)&&(this.config.debug?(ne.DEBUG=!0,le.N()&&le.F("ph_debug",!0),A.info("set_config",{config:e,oldConfig:n,newConfig:I({},this.config)})):(ne.DEBUG=!1,le.N()&&le.q("ph_debug"))),(r=this.featureFlags)==null||r.updateConfig==null||r.updateConfig(this.config,this.Qi()),(s=this.exceptionObserver)==null||s.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(f=this.deadClicksAutocapture)==null||f.startIfEnabledOrStop(),(h=this.surveys)==null||h.loadIfEnabled(),this.es(),(p=this.externalIntegrations)==null||p.startIfEnabledOrStop()}}_overrideSDKInfo(e,n){ne.LIB_NAME=e,ne.LIB_VERSION=n}startSessionRecording(e){var n,i,r,s,o,a=e===!0,l={sampling:a||!(e==null||!e.sampling),linked_flag:a||!(e==null||!e.linked_flag),url_trigger:a||!(e==null||!e.url_trigger),event_trigger:a||!(e==null||!e.event_trigger)};Object.values(l).some(Boolean)&&((n=this.sessionManager)==null||n.checkAndGetSessionAndWindowId(),l.sampling&&((i=this.sessionRecording)==null||i.overrideSampling()),l.linked_flag&&((r=this.sessionRecording)==null||r.overrideLinkedFlag()),l.url_trigger&&((s=this.sessionRecording)==null||s.overrideTrigger("url")),l.event_trigger&&((o=this.sessionRecording)==null||o.overrideTrigger("event"))),this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,n){if(this.exceptions){var i=new Error("PostHog syntheticException"),r=this.exceptions.buildProperties(e,{handled:!0,syntheticException:i});return this.exceptions.sendExceptionEvent(I({},r,n))}}addExceptionStep(e,n){var i;(i=this.exceptions)==null||i.addExceptionStep(e,n)}captureLog(e){var n;(n=this.logs)==null||n.captureLog(e)}get logger(){var e,n;return(e=(n=this.logs)==null?void 0:n.logger)!==null&&e!==void 0?e:Ze.rs}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var n,i;return(n=(i=this.toolbar)==null?void 0:i.loadToolbar(e))!==null&&n!==void 0&&n}get_property(e){var n;return(n=this.persistence)==null?void 0:n.props[e]}getSessionProperty(e){var n;return(n=this.sessionPersistence)==null?void 0:n.props[e]}toString(){var e,n=(e=this.config.name)!==null&&e!==void 0?e:Kn;return n!==Kn&&(n=Kn+"."+n),n}_isIdentified(){var e,n;return((e=this.persistence)==null?void 0:e.get_property(at))===vn||((n=this.sessionPersistence)==null?void 0:n.get_property(at))===vn}Zn(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles===ma&&!this._isIdentified()&&Kt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[Ri])&&((n=this.persistence)==null||(n=n.props)==null||!n[ts]))}zn(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Zn()||this.Gn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.Gn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}Gn(e){return this.config.person_profiles==="never"?(A.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Kn(ts,!0),!0)}En(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut();return this.config.disable_persistence||e&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!==kn)}es(){var e,n,i,r,s=this.En();return((e=this.persistence)==null?void 0:e.xi)!==s&&((i=this.persistence)==null||i.set_disabled(s)),((n=this.sessionPersistence)==null?void 0:n.xi)!==s&&((r=this.sessionPersistence)==null||r.set_disabled(s)),s&&(this.yn.clear(),this.Qn()),s}opt_in_capturing(e){var n;if(this.config.cookieless_mode!==Wt){if(this.gn()){var i,r,s,o,a;this.Yn(!0,!0),(i=this.sessionManager)==null||i.destroy(),(r=this.pageViewManager)==null||r.destroy(),this.sessionManager=new iu(this),this.pageViewManager=new Gc(this),this.persistence&&(this.sessionPropsManager=new nu(this,this.sessionManager,this.persistence));var l,u=(s=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&s!==void 0?s:(a=Ze.__defaultExtensionClasses)==null?void 0:a.sessionRecording;u&&(this.sessionRecording=this.pn(this.sessionRecording,new u(this)),this.hn&&((l=this.sessionRecording)==null||l.onRemoteConfig==null||l.onRemoteConfig(this.hn)))}var c,d;this.consent.optInOut(!0),this.es(),this.Bn(),(n=this.sessionRecording)==null||n.startIfEnabledOrStop(),this.config.cookieless_mode==kn&&((c=this.surveys)==null||c.loadIfEnabled()),(C(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((d=e?.captureEventName)!==null&&d!==void 0?d:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hn()}else A.warn(ou)}opt_out_capturing(){var e,n,i;this.config.cookieless_mode!==Wt?(this.config.cookieless_mode===kn&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===kn&&(this.register({distinct_id:vr,$device_id:null}),(e=this.sessionRecording)==null||e.stopRecording(),this.sessionRecording=void 0,(n=this.sessionManager)==null||n.destroy(),(i=this.pageViewManager)==null||i.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.Hn(),this.Bn())):A.warn(ou)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===Wt||(this.config.cookieless_mode===kn?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return He?zf(He,this.config.custom_blocked_useragents):void 0}Hn(){P&&(P.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(Gn,{title:P.title},{send_instantly:!0}),this.kn&&(P.removeEventListener(ns,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),ve(P,ns,this.kn)))}debug(e){e===!1?(w?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(w?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}Qi(){var e=this.Mn||{};return"advanced_disable_flags"in e?!!e.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(A.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(function(n,i,r,s,o){var a=i in n&&!H(n[i]),l=r in n&&!H(n[r]);return a?n[i]:!!l&&(o&&o.warn("Config field '"+r+"' is deprecated. Please use '"+i+"' instead. The old field will be removed in a future major version."),n[r])})(e,"advanced_disable_flags","advanced_disable_decide",0,A)}Pt(e){var n;if(H(this.config.before_send))return e;var i=Object.keys((n=e.properties)!==null&&n!==void 0?n:{}).filter(qp),r=U(this.config.before_send)?this.config.before_send:[this.config.before_send],s=e;for(var o of r){if(s=o(s),H(s)){var a="Event '"+e.event+"' was rejected in beforeSend function";return zp(e.event)?A.warn(a+". This can cause unexpected behavior."):A.info(a),null}s.properties&&!Kt(s.properties)||A.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}for(var l of i)if(s.properties&&H(s.properties[l]))return A.warn("Event '"+e.event+"' had its '"+l+"' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped."),null;return s}getPageViewId(){var e;return(e=this.pageViewManager.ui)==null?void 0:e.pageViewId}captureTraceFeedback(e,n){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:n})}captureTraceMetric(e,n,i){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:n,$ai_metric_value:String(i)})}Cn(e){var n=mt(e)&&!e,i=le.N()&&le.P("ph_debug")==="true";return!n&&(!!i||e)}}Ze.__defaultExtensionClasses={},Ze.rs=(()=>{var t=()=>{};return{trace:t,debug:t,info:t,warn:t,error:t,fatal:t}})(),(function(t,e){for(var n=0;e.length>n;n++)t.prototype[e[n]]=$g(t.prototype[e[n]])})(Ze,["identify"]);class cu{constructor(e){this.disabled=e===!1;var n=he(e)?e:{};this.thresholdPx=n.threshold_px||30,this.timeoutMs=n.timeout_ms||1e3,this.clickCount=n.click_count||3,this.clicks=[]}isRageClick(e,n,i){if(this.disabled)return!1;var r=this.clicks[this.clicks.length-1];if(r&&Math.abs(e-r.x)+Math.abs(n-r.y)i-r.timestamp){if(this.clicks.push({x:e,y:n,timestamp:i}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:n,timestamp:i}];return!1}}var Lo="$copy_autocapture",No=pe("[AutoCapture]");function Oo(t,e){return e.length>t?e.slice(0,t)+"...":e}function Om(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!hn(e));return e}function Bm(t,e){var n,i,r=e.e,s=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!hn(t))return{props:{}};for(var c=[t],d=new Set([t]),f=t;f.parentNode&&!et(f,"body")&&pf>c.length;)if(hf(f.parentNode)){var h=f.parentNode.host;if(d.has(h))break;d.add(h),c.push(h),f=h}else{if(!hn(f.parentNode)||d.has(f.parentNode))break;d.add(f.parentNode),c.push(f.parentNode),f=f.parentNode}var p,g,m=[],v={},E=!1,S=!1;if(ie(c,(x=>{var F=ya(x);if(et(x,"a")){var $=x.getAttribute("href");E=!!(F&&$&&Hi($))&&(u?fn($):$)}j(ss(x),"ph-no-capture")&&(S=!0),m.push((function(L,N,K,V,M){M===void 0&&(M=!1);var R=L.tagName.toLowerCase(),Z={tag_name:R};hl.indexOf(R)>-1&&!K&&(Z.$el_text=R.toLowerCase()==="a"||R.toLowerCase()==="button"?Oo(1024,zc(L)):Oo(1024,Zi(L)));var Ce=ss(L);Ce.length>0&&(Z.classes=Ce.filter((function(ae){return ae!==""}))),ie(L.attributes,(function(ae){var Ie;if((!yf(L)||["name","id","class","aria-label"].indexOf(ae.name)!==-1)&&(V==null||!V.includes(ae.name))&&!N&&Hi(ae.value)&&(!X(Ie=ae.name)||Ie.substring(0,10)!=="_ngcontent"&&Ie.substring(0,7)!=="_nghost")){var Se=ae.value;ae.name==="class"&&(Se=fl(Se).join(" ")),Z["attr__"+ae.name]=Oo(1024,ae.name==="href"&&M?fn(Se):Se)}}));for(var oe=1,ye=1,$e=L;$e=Om($e);)oe++,$e.tagName===L.tagName&&ye++;return Z.nth_child=oe,Z.nth_of_type=ye,Z})(x,s,o,a,u));var O=(function(L){if(!ya(L))return{};var N={};return ie(L.attributes,(function(K){if(K.name&&K.name.indexOf("data-ph-capture-attribute")===0){var V=K.name.replace("data-ph-capture-attribute-",""),M=K.value;V&&M&&Hi(M)&&(N[V]=M)}})),N})(x);fe(v,O)})),S)return{props:{},explicitNoCapture:S};if(o||(m[0].$el_text=et(t,"a")||et(t,"button")?zc(t):Zi(t)),E){var _,b;m[0].attr__href=E;var k=(_=os(E))==null?void 0:_.host,T=w==null||(b=w.location)==null?void 0:b.host;k&&T&&k!==T&&(p=E)}return{props:fe({$event_type:r.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(x){return x.map((F=>{var $,O,L="";if(F.tag_name&&(L+=F.tag_name),F.attr_class)for(var N of(F.attr_class.sort(),F.attr_class))L+="."+N.replace(/"/g,"");var K=I({},F.text?{text:F.text}:{},{"nth-child":($=F.nth_child)!==null&&$!==void 0?$:0,"nth-of-type":(O=F.nth_of_type)!==null&&O!==void 0?O:0},F.href?{href:F.href}:{},F.attr_id?{attr_id:F.attr_id}:{},F.attributes),V={};return Mr(K).sort(((M,R)=>M[0].localeCompare(R[0]))).forEach((M=>{var R=M[1];return V[qc(M[0].toString())]=qc(R.toString())})),(L+=":")+Mr(V).map((M=>M[0]+'="'+M[1]+'"')).join("")})).join(";")})((function(x){return x.map((F=>{var $,O,L={text:($=F.$el_text)==null?void 0:$.slice(0,400),tag_name:F.tag_name,href:(O=F.attr__href)==null?void 0:O.slice(0,2048),attr_class:Xg(F),attr_id:F.attr__id,nth_child:F.nth_child,nth_of_type:F.nth_of_type,attributes:{}};return Mr(F).filter((N=>N[0].indexOf("attr__")===0)).forEach((N=>L.attributes[N[0]]=N[1])),L}))})(g)))},(n=m[0])!=null&&n.$el_text?{$el_text:(i=m[0])==null?void 0:i.$el_text}:{},p&&r.type==="click"?{$external_click_url:p}:{},v)}}var ki=pe("[ExceptionAutocapture]"),uu=()=>{},Dm=pe("[TracingHeaders]"),wn=pe("[Web Vitals]"),du=9e5,fu="disabled",hu="lazy_loading",Ci="awaiting_config",xr="missing_config";pe("[SessionRecording]"),pe("[SessionRecording]");var Ca="[SessionRecording]",Bt=pe(Ca),jm=pe("[Heatmaps]");function Bo(t){return he(t)&&"clientX"in t&&"clientY"in t&&ke(t.clientX)&&ke(t.clientY)}var Ir=pe("[Product Tours]"),Do=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(ll))},Um=["$set_once","$set"],Et=pe("[SiteApps]"),pu="Error while initializing PostHog app with config id ";function qn(t,e,n){if(H(t))return!1;switch(n){case"exact":return t===e;case"contains":var i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(i,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}class Hm{constructor(e){this.ns=new vl,this.ss=(n,i)=>this.os(n,i)&&this.ls(n,i)&&this.us(n,i)&&this.hs(n,i),this.os=(n,i)=>i==null||!i.event||n?.event===i?.event,this._instance=e,this.ds=new Set,this.vs=new Set}init(){var e,n;C((e=this._instance)==null?void 0:e._addCaptureHook)||(n=this._instance)==null||n._addCaptureHook(((i,r)=>{this.on(i,r)}))}register(e){var n,i;if(!C((n=this._instance)==null?void 0:n._addCaptureHook)&&(e.forEach((o=>{var a,l;(a=this.vs)==null||a.add(o),(l=o.steps)==null||l.forEach((u=>{var c;(c=this.ds)==null||c.add(u?.event||"")}))})),(i=this._instance)!=null&&i.autocapture)){var r,s=new Set;e.forEach((o=>{var a;(a=o.steps)==null||a.forEach((l=>{l!=null&&l.selector&&s.add(l?.selector)}))})),(r=this._instance)==null||r.autocapture.setElementSelectors(s)}}on(e,n){var i;n!=null&&e.length!=0&&(this.ds.has(e)||this.ds.has(n.event))&&this.vs&&((i=this.vs)==null?void 0:i.size)>0&&this.vs.forEach((r=>{this.cs(n,r)&&this.ns.emit("actionCaptured",r.name)}))}fs(e){this.onAction("actionCaptured",(n=>e(n)))}cs(e,n){if(n?.steps==null)return!1;for(var i of n.steps)if(this.ss(e,i))return!0;return!1}onAction(e,n){return this.ns.on(e,n)}ls(e,n){if(n!=null&&n.url){var i,r=e==null||(i=e.properties)==null?void 0:i.$current_url;if(!r||typeof r!="string"||!qn(r,n.url,n.url_matching||"contains"))return!1}return!0}us(e,n){return!!this.ps(e,n)&&!!this.gs(e,n)&&!!this.ys(e,n)}ps(e,n){var i;if(n==null||!n.href)return!0;var r=this.bs(e);if(r.length>0)return r.some((a=>qn(a.href,n.href,n.href_matching||"exact")));var s,o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!o&&qn((s=o.match(/(?::|")href="(.*?)"/))?s[1]:"",n.href,n.href_matching||"exact")}gs(e,n){var i;if(n==null||!n.text)return!0;var r=this.bs(e);if(r.length>0)return r.some((u=>qn(u.text,n.text,n.text_matching||"exact")||qn(u.$el_text,n.text,n.text_matching||"exact")));var s,o,a,l=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!l&&(s=(function(u){for(var c,d=[],f=/(?::|")text="(.*?)"/g;!H(c=f.exec(u));)d.includes(c[1])||d.push(c[1]);return d})(l),o=n.text,a=n.text_matching||"exact",s.some((u=>qn(u,o,a))))}ys(e,n){var i,r;if(n==null||!n.selector)return!0;var s=e==null||(i=e.properties)==null?void 0:i.$element_selectors;if(s!=null&&s.includes(n.selector))return!0;var o=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";if(n.selector_regex&&o)try{return new RegExp(n.selector_regex).test(o)}catch{return!1}return!1}bs(e){var n;return(e==null||(n=e.properties)==null?void 0:n.$elements)==null?[]:e?.properties.$elements}hs(e,n){return n==null||!n.properties||n.properties.length===0||Gf(n.properties.reduce(((i,r)=>{var s=U(r.value)?r.value.map(String):r.value!=null?[String(r.value)]:[];return i[r.key]={values:s,operator:r.operator||"exact"},i}),{}),e?.properties)}}class Wm{constructor(e){var n;this._s=[],this._instance=e,this.ws=new Map,this.ks=new Map,this.xs=new Map,(n=this._instance)==null||n.onSessionId==null||n.onSessionId((i=>this.Ss(i)))}Cs(e){return!1}Ms(){return null}Ts(e){}Es(){}Is(e,n){return!!e&&Gf(e.propertyFilters,n?.properties)}Ps(e,n){var i=new Map;return e.forEach((r=>{var s;(s=r.conditions)==null||(s=s[n])==null||(s=s.values)==null||s.forEach((o=>{if(o!=null&&o.name){var a=i.get(o.name)||[];a.push(r.id),i.set(o.name,a)}}))})),i}Rs(e,n,i){var r=(i===bi.Activation?this.ws:this.ks).get(e),s=[];return this.As((o=>{s=o.filter((a=>r?.includes(a.id)))})),s.filter((o=>{var a,l=(a=o.conditions)==null||(a=a[i])==null||(a=a.values)==null?void 0:a.find((u=>u.name===e));return this.Is(l,n)}))}register(e){var n;C((n=this._instance)==null?void 0:n._addCaptureHook)||(this.Fs(e),this.Ls(e))}Ls(e){var n=e.filter((i=>{var r,s;return((r=i.conditions)==null?void 0:r.actions)&&((s=i.conditions)==null||(s=s.actions)==null||(s=s.values)==null?void 0:s.length)>0}));n.length!==0&&(this.Os==null&&(this.Os=new Hm(this._instance),this.Os.init(),this.Os.fs((i=>{this.onAction(i)}))),n.forEach((i=>{var r,s,o,a,l;i.conditions&&(r=i.conditions)!=null&&r.actions&&(s=i.conditions)!=null&&(s=s.actions)!=null&&s.values&&((o=i.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.Os)==null||a.register(i.conditions.actions.values),(l=i.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var c=this.xs.get(u.name);c&&c.push(i.id),this.xs.set(u.name,c||[i.id])}})))})))}Fs(e){var n,i=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.events)&&((a=s.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0})),r=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.cancelEvents)&&((a=s.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0}));i.length===0&&r.length===0||((n=this._instance)==null||n._addCaptureHook(((s,o)=>{this.onEvent(s,o)})),this.ws=this.Ps(e,bi.Activation),this.ks=this.Ps(e,bi.Cancellation))}onEvent(e,n){var i,r,s=this.Ds(),o=(n==null||(i=n.properties)==null?void 0:i.$survey_id)||(n==null||(r=n.properties)==null?void 0:r.$product_tour_id);if(o&&this.getActivatedIds().includes(o)){var a=this.$s(e,o);if(a==="consume")return s.info("event consumed activated item, removing it",{event:e,itemId:o}),void this.Ns([o]);if(a==="persist")return s.info("shown item promoted to persisted activation",{event:e,itemId:o}),this.qs(o),void this.js([o])}if(this.ks.has(e)){var l=this.Rs(e,n,bi.Cancellation);l.length>0&&(s.info("cancel event matched, cancelling items",{event:e,itemsToCancel:l.map((c=>c.id))}),this.Ns(l.map((c=>c.id))),l.forEach((c=>this.Bs(c.id))))}if(this.ws.has(e)){s.info("event name matched",{event:e,eventPayload:n,items:this.ws.get(e)});var u=this.Rs(e,n,bi.Activation);this.Hs(u.map((c=>c.id)))}}onAction(e){this.xs.has(e)&&this.Hs(this.xs.get(e)||[])}Hs(e){var n;if(e.length!==0){var i=!((n=this._instance)==null||n.get_session_id==null||!n.get_session_id()),r=[];for(var s of e)i&&this.Cs(s)?this.qs(s)&&this.Us(s):r.push(s);r.length>0&&(this._s=[...new Set([...this._s,...r])]),this.Ds().info("updating activated items",{activatedItems:this.getActivatedIds()})}}qs(e){this._s=this._s.filter((i=>i!==e));var n=this.zs();return!n.includes(e)&&(this.Ws([...n,e]),this.Vs(),!0)}Ns(e){var n=new Set(e);this._s=this._s.filter((s=>!n.has(s)));var i=this.Zs(),r=i.filter((s=>!n.has(s)));r.length!==i.length&&(this.Ws(r),r.length===0&&this.Gs()),this.js(e)}Qs(){var e,n=this.Ms();if(!n)return{};var i=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n];return i&&typeof i=="object"?i:{}}Us(e){if(this.Ms()){var n=this.Qs();this.Ts(I({},n,{[e]:Date.now()}))}}js(e){if(this.Ms()){var n=this.Qs(),i={},r=!1;for(var s of Object.entries(n)){var o=s[0],a=s[1];e.includes(o)?r=!0:i[o]=a}r&&(Kt(i)?this.Es():this.Ts(i))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var n=this.Qs()[e];return ke(n)?n:void 0}}Zs(){var e,n=this.Js();return((e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n])||[]}zs(){var e,n,i=this.Zs();if(i.length===0)return[];var r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[this.Ys()],s=(n=this._instance)==null||n.get_session_id==null?void 0:n.get_session_id();return s&&r===s?i:[]}Vs(){var e,n=(e=this._instance)==null||e.get_session_id==null?void 0:e.get_session_id();n&&this.Xs(n)}Gs(){this.ta()}Ss(e){var n,i=(n=this._instance)==null||(n=n.persistence)==null?void 0:n.props[this.Ys()];if(i&&i!==e){var r=this.Zs(),s=this.Qs();r.length>0&&(this.Ws([]),r.filter((o=>ke(s[o]))).forEach((o=>this.Bs(o)))),this.Gs(),this.Ks()}}getActivatedIds(){return[...new Set([...this.zs(),...this._s])].filter((e=>!this.ea(e)))}reset(){this._s=[],this.Zs().length>0&&this.Ws([]),this.Gs(),this.Ks()}getEventToItemsMap(){return this.ws}ia(){return this.Os}}class zm extends Wm{constructor(e){super(e)}Js(){return da}Ys(){return Rr}Ms(){return Tr}Ts(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Tr]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Tr)}Cs(e){var n,i;this.As((s=>{i=s.find((o=>o.id===e))}));var r=(n=i)==null||(n=n.appearance)==null?void 0:n.surveyPopupDelaySeconds;return ke(r)&&r>0}ra(){return qt.SHOWN}As(e){var n;(n=this._instance)==null||n.getSurveys(e)}Bs(e){var n;(n=this._instance)==null||n.cancelPendingSurvey(e)}Ds(){return Q}Ws(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[da]:e})}Xs(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Rr]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Rr)}ea(){return!1}$s(e,n){var i;this.As((s=>{i=s.find((o=>o.id===n))}));var r=!i||(function(s){var o;return Kf(s)&&!((o=s.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||s.schedule==="always"})(i);return r?e===qt.SHOWN?"consume":"ignore":e===qt.SHOWN?"persist":e===qt.DISMISSED||e===qt.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var kr="SDK is not enabled or survey functionality is not yet loaded",gu="Disabled. Not loading surveys.",qm=w!=null&&w.location?as(w.location.hash,"__posthog")||as(location.hash,"state"):null,mu="_postHogToolbarParams",vu=pe("[Toolbar]"),_u=pe("[FeatureFlags]");class Vm{constructor(e,n){n===void 0&&(n=!1),this.na=!1,this.update(e,n)}update(e,n){this.sa=((i,r)=>{var s,o,a,l;return{bootstrap:{featureFlags:(s=i.bootstrap)==null?void 0:s.featureFlags,featureFlagPayloads:(o=i.bootstrap)==null?void 0:o.featureFlagPayloads},remoteRequestsDisabled:r,featureFlagsDisabled:!!i.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!i.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!i.advanced_feature_flags_dedup_per_session,cacheTtlMs:i.feature_flag_cache_ttl_ms,requestTimeoutMs:i.feature_flag_request_timeout_ms,compression:i.disable_compression?"none":"base64",evaluationContexts:(a=(l=i.evaluation_contexts)!==null&&l!==void 0?l:i.evaluation_environments)!==null&&a!==void 0?a:[],flagKeys:U(i.flag_keys)?i.flag_keys:void 0}})(e,n),!e.evaluation_environments||e.evaluation_contexts||this.na||(_u.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.na=!0),C(e.flag_keys)||U(e.flag_keys)||_u.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var yu=pe("[FeatureFlags]"),bn=pe("[FeatureFlags]",{debugEnabled:!0}),jo=`" failed. Feature flags didn't load in time.`,wu="connection_error",bu=t=>{for(var e={},n=0;t.length>n;n++)e[t[n]]=!0;return e},Eu=t=>{var e={};for(var n of Mr(t||{})){var i=n[1];i&&(e[n[0]]=i)}return e},St=pe("[Error tracking]"),Su="Refusing to render web experiment since the viewer is a likely bot",Gm={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>us(e,t),not_regex:(t,e)=>!us(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class Me{get Ne(){return this._instance.config}constructor(e){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(i){i===void 0&&(i=!1),n.getWebExperiments((r=>{Me.aa("retrieved web experiments from the server"),n.oa=new Map,r.forEach((s=>{if(s.feature_flag_key){var o;n.oa&&(Me.aa("setting flag key ",s.feature_flag_key," to web experiment ",s),(o=n.oa)==null||o.set(s.feature_flag_key,s));var a=n._instance.getFeatureFlag(s.feature_flag_key);X(a)&&s.variants[a]&&n.la(s.name,a,s.variants[a].transforms)}else if(s.variants)for(var l in s.variants){var u=s.variants[l];Me.ua(u,n._instance)&&n.la(s.name,l,u.transforms)}}))}),i)},this._instance=e,this._instance.onFeatureFlags((i=>{this.onFeatureFlags(i)}))}initialize(){}onFeatureFlags(e){if(this._is_bot())Me.aa(Su);else if(!this.Ne.disable_web_experiments){if(H(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();Me.aa("applying feature flags",e),e.forEach((n=>{var i;if(this.oa&&(i=this.oa)!=null&&i.has(n)){var r,s=this._instance.getFeatureFlag(n),o=(r=this.oa)==null?void 0:r.get(n);s&&o!=null&&o.variants[s]&&this.la(o.name,s,o.variants[s].transforms)}}))}}previewWebExperiment(){var e=Me.getWindowLocation();if(e!=null&&e.search){var n=ri(e?.search,"__experiment_id"),i=ri(e?.search,"__experiment_variant");n&&i&&(Me.aa("previewing web experiments "+n+" && "+i),this.getWebExperiments((r=>{this.ha(parseInt(n),i,r)}),!1,!0))}}loadIfEnabled(){this.Ne.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,n,i){if(this.Ne.disable_web_experiments&&!i)return e([]);var r=this._instance.get_property("$web_experiments");if(r&&!n)return e(r);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this.Ne.token),method:"GET",timestampMode:"query",callback:s=>e(s.statusCode===200&&s.json&&s.json.experiments||[])})}ha(e,n,i){var r=i.filter((s=>s.id===e));r&&r.length>0&&(Me.aa("Previewing web experiment ["+r[0].name+"] with variant ["+n+"]"),this.la(r[0].name,n,r[0].variants[n].transforms))}static ua(e,n){return!H(e.conditions)&&Me.da(e,n)&&Me.va(e)}static da(e,n){var i;if(H(e.conditions)||H((i=e.conditions)==null?void 0:i.url))return!0;var r=Me.getWindowLocation();if(r){var s,o,a,l=uf(n,r.href);return(s=e.conditions)==null||!s.url||Gm[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return w?.location}static va(e){var n;if(H(e.conditions)||H((n=e.conditions)==null?void 0:n.utm))return!0;var i=If();if(i.utm_source){var r,s,o,a,l,u,c,d,f=(r=e.conditions)==null||(r=r.utm)==null||!r.utm_campaign||((s=e.conditions)==null||(s=s.utm)==null?void 0:s.utm_campaign)==i.utm_campaign,h=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==i.utm_source,p=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==i.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==i.utm_term;return f&&p&&g&&h}return!1}static aa(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;n>r;r++)i[r-1]=arguments[r];A.info("[WebExperiments] "+e,i)}la(e,n,i){this._is_bot()?Me.aa(Su):n!=="control"?i.forEach((r=>{if(r.selector){var s;Me.aa("applying transform of variant "+n+" for experiment "+e+" ",r);var o=(s=document)==null?void 0:s.querySelectorAll(r.selector);o?.forEach((a=>{var l=a;r.html&&(l.innerHTML=r.html),r.css&&l.setAttribute("style",r.css)}))}})):Me.aa("Control variants leave the page unmodified.")}_is_bot(){return He&&this._instance?zf(He,this.Ne.custom_blocked_useragents):void 0}}var ot=pe("[Conversations]"),En="Conversations not available yet.",xu="console",Qf="__posthogHandledLogsRequestError",Uo=(t,e)=>{var n=t instanceof Error?t:new Error(e);return n[Qf]=!0,n},Iu=t=>!!t&&typeof t=="object"&&t[Qf]===!0,As={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=yu,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 Vm(t.config,t.Qi()),this.Ta=this.Ea)}updateConfig(t,e){var n;(n=this.Ea)==null||n.update(t,e)}setup(t){return this.Ia=t,this.rt=t.logger.createLogger("[FeatureFlags]"),n=()=>{this.Ia===t&&(this.Ia=void 0,this.nn=t,this.Pa(t))},(e=t.kv.initialize())!=null&&e.then?e.then(n):n();var e,n}Pa(t){if(this.nn===t)return w&&ve(w,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){w?.removeEventListener("online",this.Ca)}dispose(){var t;this.ba++,this.wa=!1,this.Ia=void 0,this.nn&&(this.La(),(t=this.Ra)==null||t.dispose(),this.Ra=void 0,this.ga=[],w?.removeEventListener("online",this.Ca),this.nn=void 0)}get Ne(){return this.Ta.get()}Oa(t){var e;return(e=this.nn)==null?void 0:e.kv.get(t)}F(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.set(t)}))}q(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.remove(t)}))}Da(t){try{t()}catch(e){this.rt.error("Failed to update feature flag persistence",e)}}Fa(){var t={};for(var e of[$i,Mi,Fr,It]){var n=this.Oa(e);C(n)||(t[e]=n)}this.fa=t;var i=I({},t),r=this.Oa(Sn);if(r)for(var s of Object.entries(r))i["$feature/"+s[0]]=s[1];this.pa=i}Aa(){var t=this.Ne.cacheTtlMs;if(!t||0>=t)return!1;var e=this.Oa(Ui);return typeof e!="number"||Date.now()-e>t}$a(){return!!this.Aa()&&(this.xa||this.ya||(this.xa=!0,this.rt.warn("Feature flag cache is stale, triggering refresh..."),this.reloadFeatureFlags()),!0)}Na(){var t=this.Ne.evaluationContexts;return t!=null&&t.length?t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid evaluation context found:",e,"Expected non-empty string"),n})):[]}qa(){var t=this.Ne.flagKeys;if(!C(t))return t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid flag key found:",e,"Expected non-empty string"),n}))}initialize(){var t,e,n=this.Ne,i=(t=(e=n.bootstrap)==null?void 0:e.featureFlags)!==null&&t!==void 0?t:{};if(Object.keys(i).length){var r,s,o=(r=(s=n.bootstrap)==null?void 0:s.featureFlagPayloads)!==null&&r!==void 0?r:{},a=Object.keys(i).filter((u=>!!i[u])).reduce(((u,c)=>(u[c]=i[c]||!1,u)),{}),l=Object.keys(o).filter((u=>a[u])).reduce(((u,c)=>(o[c]&&(u[c]=o[c]),u)),{});return this.ja({featureFlags:a,featureFlagPayloads:l})}}updateFlags(t,e,n){var i,r,s=n!=null&&n.merge&&(i=this.Oa(Sn))!==null&&i!==void 0?i:{},o=n!=null&&n.merge&&(r=this.Oa(Mi))!==null&&r!==void 0?r:{},a=I({},s,t),l=I({},o,e),u={};for(var c of Object.entries(a)){var d=c[0],f=c[1];u[d]={key:d,enabled:vc(f),variant:_c(f),reason:void 0,metadata:C(l?.[d])?void 0:{id:0,version:void 0,description:void 0,payload:l[d]}}}this.ja({flags:u})}get hasLoadedFlags(){return this.ma}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var t=this.Oa(ca),e=this.Oa(It),n=this.Oa(xn);if(!n&&!e)return t||{};var i=fe({},t||{}),r=[...new Set([...Object.keys(n||{}),...Object.keys(e||{})])];for(var s of r){var o,a,l=i[s],u=e?.[s],c=C(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=C(u)?l?.variant:typeof u=="string"?u:void 0,f=n?.[s],h=I({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(h.original_enabled=l?.enabled),d!==l?.variant&&(h.original_variant=l?.variant),f&&(h.metadata=I({},l?.metadata,{payload:f,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),i[s]=h}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:n,finalDetails:i}),this.ca=!0),i}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((n=>{var i=t[n];return{key:n,enabled:vc(i),variant:_c(i),payload:mc(e[n])}}))}getFlagVariants(){var t=this.Oa(Sn),e=this.Oa(It);if(!e)return t||{};for(var n=fe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:e,finalFlags:n}),this.ca=!0),n}getFlagPayloads(){var t=this.Oa(Mi),e=this.Oa(xn);if(!e)return t||{};for(var n=fe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flag payloads!",{flagPayloads:t,overriddenPayloads:e,finalPayloads:n}),this.ca=!0),n}reloadFeatureFlags(){this._a||this.Ne.featureFlagsDisabled||this.Ma()||this.Ba||(this.ga.slice().forEach((t=>{try{t()}catch(e){this.rt.error("Error while running feature flags reloading callback",e)}})),this.Ba=setTimeout((()=>{this.Ha()}),5))}La(){clearTimeout(this.Ba),this.Ba=void 0}onReloading(t){return this.ga.push(t),()=>{this.ga=this.ga.filter((e=>e!==t))}}ensureFlagsLoaded(){this.ma||this.ya||this.Ba||this.reloadFeatureFlags()}setAnonymousDistinctId(t){this.$anon_distinct_id=t}setReloadingPaused(t){this._a=t}resetFlagCallReported(){this.q(Cn)}Ha(t){this.La();var e=this.nn;if(e&&!this.Ne.remoteRequestsDisabled&&!this.Ma())if(this.ya)this.wa=!0;else{var n={token:e.projectToken,distinct_id:e.distinctId,groups:e.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:I({},e.initialPersonProperties,this.Oa(jt)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(In),timezone:Rf()};C(e.deviceId)||(n.$device_id=e.deviceId),(t!=null&&t.disableFlags||this.Ne.featureFlagsDisabled)&&(n.disable_flags=!0);var i=this.Na();i.length&&(n.evaluation_contexts=i);var r=this.qa();C(r)||(n.flag_keys=r);var s=this.Ne.onlyEvaluateSurveyFeatureFlags,o="/flags/?v=2"+(s?"&only_evaluate_survey_feature_flags=true":""),a=this.ba;this.ya=!0;var l=()=>{this.wa&&(this.wa=!1,this.Ha())},u=c=>{this.ya=!1,a===this.ba&&(this.F({[$r]:[wu]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:n,compression:this.Ne.compression==="base64"?Ue.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,f,h=(d=c.json)!==null&&d!==void 0?d:{},p=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),p||this.wa||(this.$anon_distinct_id=void 0),!n.disable_flags||this.wa){this.ka=!p;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?wu:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),h.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((f=h.quotaLimited)==null||!f.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[$r]:g}),m?this.rt.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more."):n.disable_flags||this.ja(h,p,{partialResponse:s}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return Sf(this.Sa,3)}Ua(t){this.Sa=xf(t,this.Sa,3,(()=>this.rt.warn("Feature flag requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped refreshing feature flags; will try again when connectivity changes.")))}getFeatureFlag(t,e){var n;if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var i=this.getFeatureFlagResult(t,e);return(n=i?.variant)!==null&&n!==void 0?n:i?.enabled}}else this.rt.warn('getFeatureFlag for key "'+t+jo)}getFeatureFlagDetails(t){return this.getFlagsWithDetails()[t]}getFeatureFlagPayload(t){var e=this.getFeatureFlagResult(t,{send_event:!1});return e?.payload}getFeatureFlagResult(t,e){if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var n,i=this.getFlagVariants(),r=t in i,s=i[t],o=this.getFlagPayloads()[t],a=String(s),l=this.Oa(Fr)||void 0,u=this.Oa(Ui)||void 0,c=this.Oa(Cn)||{};if(this.Ne.deduplicateCallsPerSession){var d,f=(d=this.nn)==null?void 0:d.session.sessionId,h=this.Oa(Ni);f&&f!==h&&(c={},n=f)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))n&&this.F({[Cn]:c,[Ni]:n});else{var p,g,m,v,E,S,_,b,k,T;U(c[t])?c[t].push(a):c[t]=[a],this.F(I({[Cn]:c},n?{[Ni]:n}:{}));var x=this.getFeatureFlagDetails(t),F=[...(p=this.Oa($r))!==null&&p!==void 0?p:[]];C(s)&&F.push("flag_missing");var $={$feature_flag:t,$feature_flag_response:s,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((g=this.Ne.bootstrap)==null||(g=g.featureFlags)==null?void 0:g[t])||null,$feature_flag_bootstrapped_payload:((m=this.Ne.bootstrap)==null||(m=m.featureFlagPayloads)==null?void 0:m[t])||null,$used_bootstrap_value:!this.ka};C(x==null||(v=x.metadata)==null?void 0:v.has_experiment)||($.$feature_flag_has_experiment=x.metadata.has_experiment),C(x==null||(E=x.metadata)==null?void 0:E.version)||($.$feature_flag_version=x.metadata.version);var O,L=(S=x==null||(_=x.reason)==null?void 0:_.description)!==null&&S!==void 0?S:x==null||(b=x.reason)==null?void 0:b.code;L&&($.$feature_flag_reason=L),x!=null&&(k=x.metadata)!=null&&k.id&&($.$feature_flag_id=x.metadata.id),C(x?.original_variant)&&C(x?.original_enabled)||($.$feature_flag_original_response=C(x.original_variant)?x.original_enabled:x.original_variant),x!=null&&(T=x.metadata)!=null&&T.original_payload&&($.$feature_flag_original_payload=x==null||(O=x.metadata)==null?void 0:O.original_payload),F.length&&($.$feature_flag_error=F.join(",")),this.za($)}else n&&this.F({[Cn]:c,[Ni]:n});if(r)return{key:t,enabled:!!s,variant:typeof s=="string"?s:void 0,payload:mc(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+jo)}za(t){try{var e;(e=this.nn)==null||e.capture("$feature_flag_called",t).catch((n=>{this.rt.error("Failed to capture feature flag call",n)}))}catch(n){this.rt.error("Failed to capture feature flag call",n)}}getRemoteConfigPayload(t,e){this.Wa(t,e)}Wa(t,e){var n=this;return se((function*(){var i=n.nn;if(i){var r={distinct_id:i.distinctId,token:i.projectToken,person_properties:{$lib:i.library.name,$lib_version:i.library.version}},s=n.Na();s.length&&(r.evaluation_contexts=s);var o,a=n.qa();C(a)||(r.flag_keys=a);try{var l,u=(l=(yield i.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:r,compression:n.Ne.compression==="base64"?Ue.Base64:void 0,sentAt:"body",timeoutMs:n.Ne.requestTimeoutMs})).json)==null?void 0:l.featureFlagPayloads;o=u?.[t]||void 0}catch(c){return void n.rt.error("Remote config feature flag request failed",c)}try{e(o)}catch(c){n.rt.error("Remote config feature flag callback failed",c)}}}))()}isFeatureEnabled(t,e){if(e===void 0&&(e={}),e.fresh&&!this.ka)return e.defaultValue;if(!(this.ma||this.getFlags()&&this.getFlags().length>0))return this.rt.warn('isFeatureEnabled for key "'+t+jo),e.defaultValue;var n=this.getFeatureFlag(t,e);return C(n)?e.defaultValue:!!n}addFeatureFlagsHandler(t){this.featureFlagEventHandlers.push(t)}removeFeatureFlagsHandler(t){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((e=>e!==t))}receivedFeatureFlags(t,e,n){this.ja(t,e,n)}ja(t,e,n){if(this.nn){this.ma=!0;var i=(function(r,s,o,a,l,u){s===void 0&&(s={}),o===void 0&&(o={}),a===void 0&&(a={}),u===void 0&&(u=yu);var c=((k,T)=>{var x=k.flags;return x?I({},k,{featureFlags:Object.fromEntries(Object.keys(x).map((F=>{var $;return[F,($=x[F].variant)!==null&&$!==void 0?$:x[F].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(x).filter((F=>x[F].enabled)).filter((F=>{var $;return($=x[F].metadata)==null?void 0:$.payload})).map((F=>{var $;return[F,($=x[F].metadata)==null?void 0:$.payload]})))}):(k.featureFlags&&T.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),k)})(r,u),d=c.flags,f=c.featureFlags,h=c.featureFlagPayloads;if(f){var p=r.requestId,g=r.evaluatedAt;if(U(f)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(f)for(var v=0;f.length>v;v++)m[f[v]]=!0;return{[$i]:f,[Sn]:m,[Xr]:!1}}var E=f,S=h,_=d;if(l!=null&&l.partialResponse)E=I({},s,E),S=I({},o,S),_=I({},a,_);else if(r.errorsWhileComputingFlags)if(d){var b=new Set(Object.keys(d).filter((k=>{var T;return!((T=d[k])!=null&&T.failed)})));E=I({},s,Object.fromEntries(Object.entries(E).filter((k=>b.has(k[0]))))),S=I({},o,Object.fromEntries(Object.entries(S||{}).filter((k=>b.has(k[0]))))),_=I({},a,Object.fromEntries(Object.entries(_||{}).filter((k=>b.has(k[0])))))}else E=I({},s,E),S=I({},o,S),_=I({},a,_);return I({[$i]:Object.keys(Eu(E)),[Sn]:E||{},[Mi]:S||{},[ca]:_||{},[Xr]:r.minimalFlagCalledEvents===!0},p?{[Fr]:p}:{},g?{[Ui]:g}:{})}})(t,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),n,this.rt);i&&this.F(i),e||(this.xa=!1),this.Va(e)}}override(t,e){e===void 0&&(e=!1),this.rt.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:t,suppressWarning:e})}overrideFeatureFlags(t){this.Za(t)}Za(t){if(this.nn){if(t===!1)return this.q([It,xn]),this.Va(),void bn.info("All overrides cleared");if(U(t))return this.F({[It]:bu(t)}),this.Va(),void bn.info("Flag overrides set",{flags:t});if(t&&typeof t=="object"&&("flags"in t||"payloads"in t)){var e,n=t;this.ca=!!((e=n.suppressWarning)!==null&&e!==void 0&&e);var i={},r=n.flags,s=n.payloads;return r&&(i[It]=U(r)?bu(r):r),s&&(i[xn]=s),Object.keys(i).length&&this.F(i),r===!1&&s===!1?this.q([It,xn]):r===!1?this.q(It):s===!1&&this.q(xn),this.Va(),r===!1?bn.info("Flag overrides cleared"):r&&bn.info("Flag overrides set",{flags:r}),void(s===!1?bn.info("Payload overrides cleared"):s&&bn.info("Payload overrides set",{payloads:s}))}if(t&&typeof t=="object")return this.F({[It]:t}),this.Va(),void bn.info("Flag overrides set",{flags:t});this.rt.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:t})}else this.rt.warn("posthog.featureFlags.overrideFeatureFlags called before feature flags were ready")}onFeatureFlags(t){if(this.addFeatureFlagsHandler(t),this.ma){var e=this.Ga(),n=e.flags,i=e.flagVariants;try{t(n,i)}catch(r){this.rt.error("Error while running feature flags callback",r)}}return()=>this.removeFeatureFlagsHandler(t)}updateEarlyAccessFeatureEnrollment(t,e,n){var i=(this.Oa(Pr)||[]).find((l=>l.flagKey===t)),r={["$feature_enrollment/"+t]:e},s={$feature_flag:t,$feature_enrollment:e,$set:r};i&&(s.$early_access_feature_name=i.name),n&&(s.$feature_enrollment_stage=n);var o=I({},this.getFlagVariants(),{[t]:e});this.F({[$i]:Object.keys(Eu(o)),[Sn]:o,[jt]:I({},this.Oa(jt)||{},r)}),this.Va();try{var a;(a=this.nn)==null||a.capture("$feature_enrollment_update",s).catch((l=>{this.rt.error("Failed to capture early access feature enrollment",l)}))}catch(l){this.rt.error("Failed to capture early access feature enrollment",l)}}getEarlyAccessFeatures(t,e,n){e===void 0&&(e=!1);var i=this.Oa(Pr);!i||e?this.Qa(t,n):t(i)}Qa(t,e){var n=this;return se((function*(){var i=n.nn;if(i){var r,s=e?"&"+e.map((a=>"stage="+a)).join("&"):"";try{var o=yield i.sendRequest("/api/early_access_features/?token="+i.projectToken+s,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;n.F({[Pr]:r=o.json.earlyAccessFeatures})}catch(a){return void n.rt.error("Early access feature request failed",a)}try{t(r)}catch(a){n.rt.error("Early access feature callback failed",a)}}}))()}Ga(){var t=this.getFlags(),e=this.getFlagVariants();return{flags:t.filter((n=>e[n])),flagVariants:Object.keys(e).filter((n=>e[n])).reduce(((n,i)=>(n[i]=e[i],n)),{})}}Va(t){this.Fa();var e=this.Ga(),n=e.flags,i=e.flagVariants;this.featureFlagEventHandlers.forEach((r=>{try{r(n,i,{errorsLoading:t})}catch(s){this.rt.error("Error while running feature flags callback",s)}}))}setPersonPropertiesForFlags(t,e){e===void 0&&(e=!0),this.Ka(t,e)}Ka(t,e){e===void 0&&(e=!0);var n=this.Oa(jt)||{},i=t?.$set||(t!=null&&t.$set_once?{}:t),r=t?.$set_once,s={};if(r)for(var o in r)({}).hasOwnProperty.call(r,o)&&(o in n||(s[o]=r[o]));this.F({[jt]:I({},n,s,i)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=I({},this.Oa(jt)||{});t.forEach((i=>{delete n[i]})),this.F({[jt]:n}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(jt),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=this.Oa(In)||{},i=I({},n);for(var r of Object.keys(t))i[r]=I({},n[r],t[r]);this.F({[In]:i}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(In)||{};this.F({[In]:I({},e,{[t]:{}})})}else this.q(In)}reset(){this.ba++,this.wa=!1,this.Fa(),this.ma=!1,this._a=!1,this.ka=!1,this.$anon_distinct_id=void 0,this.La(),this.ca=!1,this.Sa=0}}},Km={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===Ci||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=fu,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(P==null||!P.visibilityState||P.visibilityState==="visible")return!0;var n=w==null||(e=w.performance)==null||e.getEntriesByType==null?void 0:e.getEntriesByType("visibility-state");return!(n!=null&&n.length)||n.some((i=>i.name==="visible"))})(),this.Ie=()=>{var e;P?.visibilityState==="visible"&&(this.io=!0,(e=this.Ja)==null||e.setDocumentWasEverVisible==null||e.setDocumentWasEverVisible(!0))},this._instance=t,!this._instance.sessionManager)throw Bt.error("started without valid sessionManager"),new Error(Ca+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===Wt)throw new Error(Ca+' cannot be used with cookieless_mode="always"');P!=null&&P.addEventListener&&ve(P,"visibilitychange",this.Ie)}initialize(){this.startIfEnabledOrStop()}dispose(){this.eo=!0,P==null||P.removeEventListener==null||P.removeEventListener("visibilitychange",this.Ie),this.stopRecording()}get ro(){var t,e=!((t=this._instance.get_property(An))==null||!t.enabled),n=!this.Ne.disable_session_recording,i=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return w&&e&&n&&!i}startIfEnabledOrStop(t){var e;if(!(this.eo||this.ro&&(e=this.Ja)!=null&&e.isStarted)){var n=!C(Object.assign)&&!C(Array.from);this.ro&&n?(this.no(t),Bt.info("starting")):(this.Ya=fu,this.stopRecording())}}no(t){var e,n,i;this.ro&&(this.Ya!==Ci&&this.Ya!==xr&&(this.Ya=hu),B!=null&&(e=B.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(n=B.__PosthogExtensions__)!=null&&n.initSessionRecording?this.so(t):(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,this.ao,(r=>{if(r)return Bt.error("could not load recorder",r);this.so(t)})))}stopRecording(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.stop()}oo(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.discard()}lo(){var t,e;(t=this.Mr)==null||t.unregister(cl),(e=this.Mr)==null||e.unregister(Xd)}uo(t,e){if(H(t))return null;var n,i=ke(t)?t:parseFloat(t);return typeof(n=i)!="number"||!Number.isFinite(n)||0>n||n>1?(Bt.warn(e+" must be between 0 and 1. Ignoring invalid value:",t),null):i}ho(t){if(this.Mr){var e,n,i=this.Mr,r=()=>{var s,o=t.sessionRecording===!1?void 0:t.sessionRecording,a=this.uo((s=this.Ne.session_recording)==null?void 0:s.sampleRate,"session_recording.sampleRate"),l=this.uo(o?.sampleRate,"remote config sampleRate"),u=a??l;H(u)&&this.lo();var c=o?.minimumDurationMilliseconds;i.register({[An]:I({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:I({capturePerformance:t.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:u,minimumDurationMilliseconds:C(c)?null:c,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers,version:o?.version,triggerGroups:o?.triggerGroups})})};r(),(e=this.Xa)==null||e.call(this),this.Xa=(n=this._instance.sessionManager)==null?void 0:n.onSessionId(r)}}onRemoteConfig(t){var e=t.ok?t.config:void 0;return e&&"sessionRecording"in e?e.sessionRecording===!1?(this.ho(e),void this.oo()):(this.ho(e),void this.startIfEnabledOrStop()):(this.Ya===Ci&&(this.Ya=xr,Bt.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(t,e){var n;e===void 0&&(e="log"),(n=this.Ja)!=null&&n.log?this.Ja.log(t,e):Bt.warn("log called before recorder was ready")}get ao(){var t,e,n=(t=this._instance)==null||(t=t.persistence)==null?void 0:t.get_property(An);return(n==null||(e=n.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(An);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(n){return Bt.warn("persisted remote config for session recording is invalid and will be ignored",n),!1}return!H(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,n,i;if(!this.eo){if((e=B.__PosthogExtensions__)==null||!e.initSessionRecording)return Bt.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[af]:!0});var r;if(this.Ja||(this.Ja=(r=B.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===xr||this.Ya===Ci?void 0:(this.Ya=Ci,Bt.info("persisted remote config is stale, requesting fresh config before starting"),void new Tf(this._instance).load());this.Ya=hu,(n=(i=this.Ja).setDocumentWasEverVisible)==null||n.call(i,this.io),this.Ja.start(t)}}onRRwebEmit(t){var e;(e=this.Ja)==null||e.onRRwebEmit==null||e.onRRwebEmit(t)}overrideLinkedFlag(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[ef]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Qd]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,n;this.Ja||(n=this.Mr)==null||n.register({[t==="url"?tf:nf]:!0}),(e=this.Ja)==null||e.overrideTrigger(t)}get sdkDebugProperties(){var t;return((t=this.Ja)==null?void 0:t.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(t,e){var n;return!((n=this.Ja)==null||!n.tryAddCustomEvent(t,e))}}},Ym={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new cu(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,n=he(this.instance.config.autocapture)?this.instance.config.autocapture:{};return n.url_allowlist=(t=n.url_allowlist)==null?void 0:t.map((i=>new RegExp(i))),n.url_ignorelist=(e=n.url_ignorelist)==null?void 0:e.map((i=>new RegExp(i))),n}yo(){if(this.isBrowserSupported()){if(w&&P){var t=n=>{n=n||w?.event;try{this.bo(n)}catch(i){No.error("Failed to capture event",i)}};if(ve(P,"submit",t,{capture:!0}),ve(P,"change",t,{capture:!0}),ve(P,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=n=>{n=n||w?.event;try{this.bo(n,Lo)}catch(i){No.error("Failed to capture copy/cut event",i)}};ve(P,"copy",e,{capture:!0}),ve(P,"cut",e,{capture:!0})}}}else No.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.vo&&(this.yo(),this.vo=!0)}onRemoteConfig(t){if(this.fo=!0,t.ok){var e=t.config;e.elementsChainAsString&&(this.po=e.elementsChainAsString);var n=e.autocapture_opt_out;mt(n)&&(this.instance.persistence&&this.instance.persistence.register({[na]:n}),this.co=n),this.startIfEnabled()}else this.startIfEnabled()}setElementSelectors(t){this.mo=t}getElementSelectors(t){var e,n=[];return(e=this.mo)==null||e.forEach((i=>{var r=P?.querySelectorAll(i);r?.forEach((s=>{t===s&&n.push(i)}))})),n}get isEnabled(){var t,e,n=(t=this.instance.persistence)==null?void 0:t.props[na],i=this.co,r=this.instance.Qi()&&!this.fo;if(Ye(i)&&!mt(n)&&!r)return!1;var s=(e=this.co)!==null&&e!==void 0?e:!!n;return!!this.instance.config.autocapture&&!s}bo(t,e){if(e===void 0&&(e="$autocapture"),this.isEnabled){var n,i=So(t);ff(i)&&(i=i.parentNode||null),e==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&this.instance.config.rageclick&&(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,t.timeStamp||new Date().getTime())&&Dc(i,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var r=e===Lo;if(i&&(function(d,f,h,p,g,m){var v;if(!w||pl(d)||h!=null&&h.url_allowlist&&!Nc(h.url_allowlist,m)||h!=null&&h.url_ignorelist&&Nc(h.url_ignorelist,m))return!1;if(h!=null&&h.dom_event_allowlist){var E=h.dom_event_allowlist;if(E&&!E.some((x=>f.type===x)))return!1}var S=_f(d,p),_=S.parentIsUsefulElement,b=S.targetElementList;if(!(function(x,F){var $=F?.element_allowlist;if(C($))return!0;var O,L=function(K){if($.some((V=>K.tagName.toLowerCase()===V)))return{v:!0}};for(var N of x)if(O=L(N))return O.v;return!1})(b,h)||!_a(b,h?.css_selector_allowlist)||_a(b,(v=h?.css_selector_ignorelist)!==null&&v!==void 0?v:Vg))return!1;try{var k=w.getComputedStyle(d);if(k&&k.getPropertyValue("cursor")==="pointer"&&f.type==="click")return!0}catch{}var T=d.tagName.toLowerCase();switch(T){case"html":return!1;case"form":return(g||["submit"]).indexOf(f.type)>=0;case"input":case"select":case"textarea":return(g||["change","click"]).indexOf(f.type)>=0;default:return _?(g||["click"]).indexOf(f.type)>=0:(g||["click"]).indexOf(f.type)>=0&&(hl.indexOf(T)>-1||d.getAttribute("contenteditable")==="true")}})(i,t,this.Ne,r,r?["copy","cut"]:void 0,this.instance)){var s=Bm(i,{e:t,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.Ne.element_attribute_ignorelist,elementsChainAsString:this.po,disableCaptureUrlHashes:this.instance.config.disable_capture_url_hashes}),o=s.props;if(s.explicitNoCapture)return!1;var a=this.getElementSelectors(i);if(a&&a.length>0&&(o.$element_selectors=a),e===Lo){var l,u=gf(w==null||(l=w.getSelection())==null?void 0:l.toString()),c=t.type||"clipboard";if(!u)return!1;o.$selected_content=u,o.$copy_type=c}return this.instance.capture(e,o),!0}}}isBrowserSupported(){return je(P?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(w==null||(e=w.location)==null?void 0:e.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(A.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.wo&&this.wo(),this.wo=void 0,A.info("History API monitoring stopped")}monitorHistoryChanges(){w&&w.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(w&&((e=w.history[t])==null||!e.__posthog_wrapped__)){var n=this;(function(i,r,s){try{if(!(r in i))return uu;var o={next:i[r]},a=s((function(){for(var l=arguments.length,u=new Array(l),c=0;l>c;c++)u[c]=arguments[c];return o.next.apply(this,u)}));return je(a)&&(a.prototype=a.prototype||{},Object.defineProperties(a,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:o}})),i[r]=a,()=>{if(i[r]!==a)for(var l=i[r];je(l)&&l.__posthog_layer__;){var u=l.__posthog_layer__;if(u.next===a)return void(u.next=o.next);l=u.next}else i[r]=o.next}}catch{return uu}})(w.history,t,(i=>function(r,s,o){i.call(this,r,s,o),n.So(t)}))}}So(t){try{var e,n=w==null||(e=w.location)==null?void 0:e.pathname;if(!n)return;n!==this._o&&this.isEnabled&&this._instance.capture(Gn,{navigation_type:t}),this._o=n}catch(i){A.error("Error capturing "+t+" pageview",i)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};ve(w,"popstate",t),this.wo=()=>{w&&w.removeEventListener("popstate",t)}}}},heatmaps:class{get Ne(){return this.instance.config}constructor(t){var e;this.Co=!1,this.vo=!1,this.Mo=null,this.instance=t,this.Co=!((e=this.instance.persistence)==null||!e.props[ia]),this.rageclicks=new cu(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return he(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return H(this.Ne.capture_heatmaps)?H(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;jm.info("starting..."),this.To(),this.Ie()}else{var t;clearInterval((t=this.Mo)!==null&&t!==void 0?t:void 0),this.Eo(),this.getAndClearBuffer()}}onRemoteConfig(t){if(t.ok){var e=t.config;if("heatmaps"in e){var n=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[ia]:n}),this.Co=n,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){Bo(t.originalEvent)&&this.ke(t.originalEvent,"deadclick")}Ie(){this.Mo&&clearInterval(this.Mo),this.Mo=P?.visibilityState==="visible"?setInterval(this.cr.bind(this),this.flushIntervalMilliseconds):null}To(){w&&P&&(this.Po=this.cr.bind(this),ve(w,is,this.Po),this.Ro=t=>this.ke(t||w?.event),ve(P,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||w?.event),ve(P,"mousemove",this.Ao,{capture:!0}),this.Lo=new Vc(this.instance,Qg,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),ve(P,ns,this.Oo),this.vo=!0)}Eo(){var t;w&&P&&(this.Po&&w.removeEventListener(is,this.Po),this.Ro&&P.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&P.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&P.removeEventListener(ns,this.Oo),clearTimeout(this.Do),(t=this.Lo)==null||t.stop(),this.vo=!1)}$o(t,e){var n=this.instance.scrollManager.scrollY(),i=this.instance.scrollManager.scrollX(),r=this.instance.scrollManager.scrollElement(),s=(function(o,a,l){for(var u=o;u&&hn(u)&&!et(u,"body");){if(u===l)return!1;var c=void 0;try{var d,f,h;c=(d=(f=(h=u.ownerDocument)==null?void 0:h.defaultView)!==null&&f!==void 0?f:w)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(j(a,c))return!0;u=mf(u)}return!1})(So(t),["fixed","sticky"],r);return{x:t.clientX+(s?0:i),y:t.clientY+(s?0:n),target_fixed:s,type:e}}ke(t,e){var n;if(e===void 0&&(e="click"),!Lc(t.target)&&Bo(t)){var i=this.$o(t,e);(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,new Date().getTime())&&Dc(So(t),this.instance.config.rageclick)&&this.Vt(I({},i,{type:"rageclick"})),this.Vt(i)}}Fo(t){!Lc(t.target)&&Bo(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(w){var e=this.Ne.disable_capture_url_hashes?fn(w.location.href):w.location.href,n=this.Ne.custom_personal_data_properties,i=this.Ne.mask_personal_data_properties?[...si,...n||[]]:[],r=Xi(e,i,Qi);this.R=this.R||{},this.R[r]||(this.R[r]=[]),this.R[r].push(t)}}cr(){this.R&&!Kt(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:Vc,webVitalsAutocapture:class{constructor(t){var e;this.Co=!1,this.vo=!1,this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this.No=()=>{clearTimeout(this.qo),this.qo=void 0,this.R.metrics.length!==0&&(this._instance.capture("$web_vitals",I({$current_url:this.R.url},this.R.metrics.reduce(((n,i)=>I({},n,{["$web_vitals_"+i.name+"_event"]:I({},i),["$web_vitals_"+i.name+"_value"]:i.value})),{}))),this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.jo=n=>{var i;if(this.R=this.R||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},H(n?.name)||H(n?.value))wn.error("Invalid metric received",n);else{var r=typeof n.navigationURL=="string"?n.navigationURL:void 0,s=this.Bo(r);if(!C(s)){var o=ke(n.navigationId)||typeof n.navigationId=="string"?"navigation:"+n.navigationId:"url:"+s;if(!this.Ho||this.Ho>n.value){this.R.navigationKey!==o&&(this.No(),this.qo=setTimeout(this.No,this.flushToCaptureTimeoutMs)),C(this.R.navigationKey)&&(this.R.navigationKey=o,this.R.url=s),this.R.firstMetricTimestamp=C(this.R.firstMetricTimestamp)?Date.now():this.R.firstMetricTimestamp,n.attribution&&n.attribution.interactionTargetElement&&(n.attribution.interactionTargetElement=void 0);var a=(i=this._instance.sessionManager)==null?void 0:i.checkAndGetSessionAndWindowId(!0),l=I({},n,r?{navigationURL:s}:{},{$current_url:s,timestamp:Date.now()});C(a)||(l.$session_id=a.sessionId,l.$window_id=a.windowId),this.R.metrics.push(l),this.R.metrics.length===this.allowedMetrics.length&&this.No()}else wn.error("Ignoring metric with value >= "+this.Ho,n)}}},this.Uo=()=>{if(!this.vo){var n,i,r,s,o=B.__PosthogExtensions__,a=o?.postHogWebVitalsCallbacksByFlavor,l=a?.[this.zo]||(this.zo==="web-vitals"&&C(a)?o?.postHogWebVitalsCallbacks:void 0);if(C(l)||(n=l.onLCP,i=l.onCLS,r=l.onFCP,s=l.onINP),n&&i&&r&&s){var u={reportSoftNavs:this.useSoftNavs};this.allowedMetrics.indexOf("LCP")>-1&&n(this.jo.bind(this),u),this.allowedMetrics.indexOf("CLS")>-1&&i(this.jo.bind(this),u),this.allowedMetrics.indexOf("FCP")>-1&&r(this.jo.bind(this),u),this.allowedMetrics.indexOf("INP")>-1&&s(this.jo.bind(this),u),this.vo=!0}else wn.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[aa]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,n=he(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return H(n)?((e=this._instance.persistence)==null?void 0:e.props[la])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(he(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=he(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=he(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=he(this.Wo)&&ke(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:du;return t>0&&6e4>=t?du:t}get isEnabled(){var t=me?.protocol;if(t!=="http:"&&t!=="https:")return wn.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=he(this.Wo)?this.Wo.web_vitals:mt(this.Wo)?this.Wo:void 0;return mt(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(wn.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var n=he(e.capturePerformance)&&!!e.capturePerformance.web_vitals,i=he(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[aa]:n}),this._instance.persistence.register({[la]:i})),this.Co=n,this.startIfEnabled()}}}get zo(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}ai(t){var e=B.__PosthogExtensions__,n=this.zo,i=e?.postHogWebVitalsCallbacksByFlavor;i!=null&&i[n]||n==="web-vitals"&&C(i)&&e!=null&&e.postHogWebVitalsCallbacks?t():e==null||e.loadExternalDependency==null||e.loadExternalDependency(this._instance,n,(r=>{r?wn.error("failed to load script",r):t()}))}Bo(t){var e=t||w?.location.href;if(e){var n=this._instance.config.disable_capture_url_hashes?fn(e):e,i=this._instance.config.custom_personal_data_properties,r=this._instance.config.mask_personal_data_properties?[...si,...i||[]]:[];return Xi(n,r,Qi)}wn.error("Could not determine current URL")}}},Jm={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var n;if(w&&this.isEnabled&&(n=B.__PosthogExtensions__)!=null&&n.errorWrappingFunctions){var i=B.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,r=B.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,s=B.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.Vo&&this.Ne.capture_unhandled_errors&&(this.Vo=i(this.captureException.bind(this))),!this.Zo&&this.Ne.capture_unhandled_rejections&&(this.Zo=r(this.captureException.bind(this))),!this.Go&&this.Ne.capture_console_errors&&(this.Go=s(this.captureException.bind(this)))}catch(o){ki.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[ra]),this.Jo=new Kp(I({},(function(n){var i,r,s,o;return n===void 0&&(n={}),{refillRate:(i=(r=n.exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:n.__exceptionRateLimiterRefillRate)!==null&&i!==void 0?i:1,bucketSize:(s=(o=n.exceptionRateLimiterBucketSize)!==null&&o!==void 0?o:n.__exceptionRateLimiterBucketSize)!==null&&s!==void 0?s:10}})(this._instance.config.error_tracking),{refillInterval:1e4,rt:ki})),this.Ne=this.Yo(),this.startIfEnabledOrStop()}Yo(){var t=this._instance.config.capture_exceptions,e={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return he(t)?e=I({},e,t):(C(t)?this.Ko:t)&&(e=I({},e,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),e}get isEnabled(){return this.Ne.capture_console_errors||this.Ne.capture_unhandled_errors||this.Ne.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(ki.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",(i=>{if(i)return ki.error("failed to load script",i);t()}))}Qo(){var t,e,n;(t=this.Vo)==null||t.call(this),this.Vo=void 0,(e=this.Zo)==null||e.call(this),this.Zo=void 0,(n=this.Go)==null||n.call(this),this.Go=void 0}onRemoteConfig(t){if(t.ok){var e=t.config;"autocaptureExceptions"in e&&(this.Ko=!!e.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[ra]:this.Ko}),this.Ne=this.Yo(),this.startIfEnabledOrStop())}}onConfigChange(){this.Ne=this.Yo()}captureException(t){var e,n,i,r=(e=t==null||(n=t.$exception_list)==null||(n=n[0])==null?void 0:n.type)!==null&&e!==void 0?e:"Exception";this.Jo.consumeRateLimit(r)?ki.info("Skipping exception capture because of client rate limiting.",{exception:r}):(i=this._instance.exceptions)==null||i.sendExceptionEvent(t)}},exceptions:class{constructor(t){var e,n;this.Xo=[],this.tl=new dg([new yg,new Ag,new bg,new wg,new kg,new Ig,new Sg,new Cg],(function(i){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;r>o;o++)s[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` -`),d=l;c.length>d;d++){var f=c[d];if(1024>=f.length){var h=Rc.test(f)?f.replace(Rc,"$1"):f;if(!h.match(/\S*Error: /)){for(var p of s){var g=p(h,i);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var v=Array.from(m);return v.reverse(),v.slice(0,50).map((E=>{return I({},E,{filename:E.filename||(S=v,S[S.length-1]||{}).filename,function:E.function||ii});var S}))})(u)}})("web:javascript",gg,_g)),this._instance=t,this.Xo=(e=(n=this._instance.persistence)==null?void 0:n.get_property(sa))!==null&&e!==void 0?e:[],this.el=Zr(this.il()),this.rl=new Fg(this.el)}onConfigChange(){this.el=Zr(this.il()),this.rl.setConfig(this.el)}onRemoteConfig(t){var e,n,i;if(t.ok){var r=t.config;if("errorTracking"in r){var s=(e=(n=r.errorTracking)==null?void 0:n.suppressionRules)!==null&&e!==void 0?e:[],o=(i=r.errorTracking)==null?void 0:i.captureExtensionExceptions;this.Xo=s,this._instance.persistence&&this._instance.persistence.register({[sa]:this.Xo,[oa]:o})}}}get nl(){var t,e=!!this._instance.get_property(oa),n=this._instance.config.error_tracking.captureExtensionExceptions;return(t=n??e)!==null&&t!==void 0&&t}buildProperties(t,e){return this.tl.buildFromUnknown(t,{syntheticException:e?.syntheticException,mechanism:{handled:e?.handled}})}addExceptionStep(t,e){if(this.el.enabled)try{if(!X(t)||t.trim().length===0)return void St.warn("Ignoring exception step because message must be a non-empty string");var n=(function(s){if(!s)return{sanitizedProperties:{},droppedKeys:[]};var o=[];return{sanitizedProperties:Object.keys(s).reduce(((a,l)=>Pg.has(l)?(o.push(l),a):(a[l]=s[l],a)),{}),droppedKeys:o}})(this.sl(e)),i=n.sanitizedProperties,r=n.droppedKeys;r.length>0&&St.warn("Ignoring reserved exception step fields",{droppedKeys:r}),this.rl.add(I({[Yr]:t,[Jr]:new Date().toISOString()},i))}catch(s){St.error("Failed to add exception step. Ignoring breadcrumb.",s)}}sendExceptionEvent(t){try{var e=t.$exception_list;if(this.al(e)){if(this.ol(e))return this.ll("Exception dropped: matched a suppression rule"),void St.info("Skipping exception capture because a suppression rule matched");if(!this.nl&&this.ul(e))return this.ll("Exception dropped: thrown by a browser extension"),void St.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.hl(e))return this.ll("Exception dropped: thrown by the PostHog SDK"),void St.info("Skipping exception capture because it was thrown by the PostHog SDK")}var n=this.el.enabled&&H(t.$exception_steps)?this.dl(t):t,i=typeof(s=globalThis._posthogReleaseId)=="string"&&s.length>0?s:void 0;i&&(n.$release_id=i);try{var r=this._instance.capture("$exception",n,{_noTruncate:!0,_batchKey:"exceptionEvent",Wn:!0});return r&&this.rl.clear(),r}catch(o){return St.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void St.error("Failed to process exception event. Ignoring this exception.",o)}var s}dl(t){try{var e=this.rl.getAttachable();return e.length===0?t:I({},t,{$exception_steps:e})}catch(n){return St.error("Failed to read buffered exception steps. Capturing exception without steps.",n),t}}ll(t){this.el.enabled&&this.rl.add({[Yr]:t,[Jr]:new Date().toISOString()})}sl(t){return he(t)?I({},t):{}}il(){var t,e;return(t=(e=this._instance.config.error_tracking)==null?void 0:e.exception_steps)!==null&&t!==void 0?t:{}}ol(t){if(t.length===0)return!1;try{var e=t.reduce(((n,i)=>{var r=i.type,s=i.value;return X(r)&&r.length>0&&n.$exception_types.push(r),X(s)&&s.length>0&&n.$exception_values.push(s),n}),{$exception_types:[],$exception_values:[]});return this.Xo.some((n=>{var i=n.values.map((r=>{var s=Vf[r.operator],o=e[r.key];if(!s||!o)return!1;var a=U(r.value)?r.value:[r.value];return a.length>0&&s(a,o)}));return n.type==="OR"?i.some(Boolean):i.every(Boolean)}))}catch(n){return St.warn("Failed to evaluate suppression rules. Capturing the exception.",n),!1}}ul(t){return t.flatMap((e=>{var n,i;return(n=(i=e.stacktrace)==null?void 0:i.frames)!==null&&n!==void 0?n:[]})).some((e=>e.filename&&e.filename.startsWith("chrome-extension://")))}hl(t){if(t.length>0){var e,n,i,r,s=(e=(n=t[0].stacktrace)==null?void 0:n.frames)!==null&&e!==void 0?e:[],o=s[s.length-1];return(i=o==null||(r=o.filename)==null?void 0:r.includes("posthog.com/static"))!==null&&i!==void 0&&i}return!1}al(t){return!H(t)&&U(t)}}},Zm=I({productTours:class{get Mr(){return this._instance.persistence}constructor(t){this.vl=null,this.cl=null,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(t.ok){var e=t.config;if("productTours"in e){var n,i;if(this.Mr&&this.Mr.register({[ll]:!!e.productTours}),!Do(this._instance))return!this.vl&&H((n=this.Mr)==null?void 0:n.props[Li])||Ir.info("product tours disabled; stopping and clearing cached tours"),(i=this.vl)==null||i.stop(),this.vl=null,void this.clearCache();this.loadIfEnabled()}}}loadIfEnabled(){!this.vl&&Do(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.generateProductTours?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",(i=>{i?Ir.error("Could not load product tours script",i):t()}))}fl(){var t;!this.vl&&(t=B.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=B.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(t,e){if(e===void 0&&(e=!1),!U(this.cl)||e){var n=this.Mr;if(n){var i=n.props[Li];if(U(i)&&!e)return this.cl=i,void t(i,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",timestampMode:"query",callback:r=>{if(Do(this._instance)){var s=r.statusCode;if(s!==200||!r.json){var o="Product Tours API could not be loaded, status: "+s;return s===0?r.error||Ir.warn(o):Ir.error(o),void t([],{isLoaded:!1,error:o})}var a=U(r.json.product_tours)?r.json.product_tours:[];this.cl=a,n&&n.register({[Li]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){H(this.vl)?t([],{isLoaded:!1,error:"Product tours not loaded"}):this.vl.getActiveProductTours(t)}showProductTour(t){var e;(e=this.vl)==null||e.showTourById(t)}previewTour(t){this.vl?this.vl.previewTour(t):this.ai((()=>{var e;this.fl(),(e=this.vl)==null||e.previewTour(t)}))}dismissProductTour(){var t;(t=this.vl)==null||t.dismissTour("user_clicked_skip")}nextStep(){var t;(t=this.vl)==null||t.nextStep()}previousStep(){var t;(t=this.vl)==null||t.previousStep()}clearCache(){var t;this.cl=null,(t=this.Mr)==null||t.unregister(Li)}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)}}},As),Xm={siteApps:class{constructor(t){this.pl=0,this._instance=t,this.gl=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}ml(t,e){if(e){var n=this.globalsForEvent(e);this.gl.push(n),this.gl.length>1e3&&(this.gl=this.gl.slice(10))}}get siteAppLoaders(){var t;return(t=B._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,n,i,r,s,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var f=d[0];l[f]={id:u[f],type:f,properties:d[1]}}var h=t.$set_once,p=t.$set;return{event:I({},md(t,Um),{properties:I({},t.properties,p?{$set:I({},(e=(n=t.properties)==null?void 0:n.$set)!==null&&e!==void 0?e:{},p)}:{},h?{$set_once:I({},(i=(r=t.properties)==null?void 0:r.$set_once)!==null&&i!==void 0?i:{},h)}:{}),elements_chain:(s=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&s!==void 0?s:"",distinct_id:(a=t.properties)==null?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}bl(t){var e,n=(e=t.tagName)==null?void 0:e.toLowerCase();return n==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(Et.error("prepare_external_dependency_stylesheet returned null"),null):n==="script"&&this._instance.config.prepare_external_dependency_script?this._instance.config.prepare_external_dependency_script(t)||(Et.error("prepare_external_dependency_script returned null"),null):t}_l(){var t,e,n,i,r,s,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=P?.defaultView,u=l==null||(t=l.Node)==null?void 0:t.prototype;if(!l||!u)return()=>{};if(this.pl++,this.wl)return this.kl();var c=[],d=this,f=new WeakSet,h=(m,v,E)=>{if(m!=null&&m[v]){var S=m[v];m[v]=E(S),c.push((()=>{m[v]=S}))}},p=m=>{if(f.has(m))return m;var v=d.bl(m);return v&&f.add(v),v},g=m=>m.map((v=>typeof v=="string"?v:p(v))).filter((v=>!Ye(v)));return h(u,"appendChild",(m=>function(v){var E=p(v);return E?m.call(this,E):v})),h(u,"insertBefore",(m=>function(v,E){var S=p(v);return S?m.call(this,S,E):v})),h(u,"replaceChild",(m=>function(v,E){var S=p(v);return S?m.call(this,S,E):E})),[(e=l.Element)==null?void 0:e.prototype,(n=l.Document)==null?void 0:n.prototype,(i=l.DocumentFragment)==null?void 0:i.prototype].forEach((m=>{h(m,"append",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),h(m,"prepend",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))}))})),[(r=l.Element)==null?void 0:r.prototype,(s=l.CharacterData)==null?void 0:s.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((m=>{h(m,"before",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),h(m,"after",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),h(m,"replaceWith",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];var b=g(S);return S.length&&!b.length?void 0:v.apply(this,b)}))})),h((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(v,E){var S=p(E);return S?m.call(this,v,S):null})),this.wl=()=>{c.forEach((m=>m())),this.wl=void 0},this.kl()}kl(){var t=!1;return()=>{var e;t||(t=!0,this.pl--,this.pl===0&&((e=this.wl)==null||e.call(this)))}}xl(t,e){e===void 0&&(e=!0);var n=this._l();try{var i=t(n);return e&&n(),i}catch(r){throw n(),r}}setupSiteApp(t){var e=this.apps[t.id],n=()=>{var o;!e.errored&&this.gl.length&&(Et.info("Processing "+this.gl.length+" events for site app with id "+t.id),this.gl.forEach((a=>this.xl((()=>e.processEvent==null?void 0:e.processEvent(a))))),e.processedBuffer=!0),Object.values(this.apps).every((a=>a.processedBuffer||a.errored))&&((o=this.yl)==null||o.call(this))},i=!1,r=o=>{e.errored=!o,e.loaded=!0,Et.info("Site app with id "+t.id+" "+(o?"loaded":"errored")),i&&n()};try{var s=this.xl((o=>t.init({posthog:this._instance,callback(a){o(),r(a)}})),!1).processEvent;s&&(e.processEvent=s),i=!0}catch(o){Et.error(pu+t.id,o),r(!1)}if(i&&e.loaded)try{n()}catch(o){Et.error("Error while processing buffered events PostHog app with config id "+t.id,o),e.errored=!0}}Sl(){var t=this.siteAppLoaders||[];for(var e of t)this.apps[e.id]={id:e.id,loaded:!1,errored:!1,processedBuffer:!1};for(var n of t)this.setupSiteApp(n)}Cl(t){var e=this;if(Object.keys(this.apps).length!==0){var n=this.globalsForEvent(t),i=function(s){try{e.xl((()=>s.processEvent==null?void 0:s.processEvent(n)))}catch(o){Et.error("Error while processing event "+t.event+" for site app "+s.id,o)}};for(var r of Object.values(this.apps))i(r)}}onRemoteConfig(t){var e,n,i,r=this;if((e=this.siteAppLoaders)!=null&&e.length)return this.isEnabled?(this.Sl(),void this._instance.on("eventCaptured",(l=>this.Cl(l)))):void Et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((n=this.yl)==null||n.call(this),t.ok){var s=t.config;if((i=s.siteApps)!=null&&i.length)if(this.isEnabled){var o=function(){var l,u=a.id,c=a.url;B["__$$ph_site_app_"+u]=r._instance,(l=B.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(r._instance,c,(d=>{if(d)return Et.error(pu+u,d)}))};for(var a of s.siteApps)o()}else Et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},Qm={tracingHeaders:class{constructor(t){this.Ml=void 0,this.Tl=void 0,this.El=void 0,this.Uo=()=>{var e,n,i=this.Il();i?(C(this.Ml)&&(this.Ml=(e=B.__PosthogExtensions__)==null||(e=e.tracingHeadersPatchFns)==null?void 0:e._patchXHR(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager)),C(this.Tl)&&(this.Tl=(n=B.__PosthogExtensions__)==null||(n=n.tracingHeadersPatchFns)==null?void 0:n._patchFetch(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager))):this.Qo()},this._instance=t}initialize(){this.startIfEnabledOrStop()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",(i=>{if(i)return Dm.error("failed to load script",i);t()}))}Pl(){var t,e;return(t=(e=this._instance.config.tracing_headers)!==null&&e!==void 0?e:this._instance.config.addTracingHeaders)!==null&&t!==void 0?t:this._instance.config.__add_tracing_headers}Il(){var t=this.Pl();return U(t)?(U(this.El)?this.El.splice(0,this.El.length,...t):this.El=[...t],t.length>0?this.El:void 0):(U(this.El)&&this.El.splice(0),this.El=t||void 0,this.El)}Qo(){var t,e;(t=this.Ml)==null||t.call(this),(e=this.Tl)==null||e.call(this),this.Ml=void 0,this.Tl=void 0}startIfEnabledOrStop(){this.Il()?this.ai(this.Uo):this.Qo()}}},ev=I({surveys:class{get Ne(){return this._instance.config}constructor(t){this.Rl=void 0,this._surveyManager=null,this.Al=!1,this.Fl=[],this.Ll=null,this.Ol=null,this._instance=t,this._surveyEventReceiver=null}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this.Ne.disable_surveys){if(!t.ok)return Q.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(H(e))return Q.warn("Flags not loaded yet. Not loading surveys.");var n=U(e);this.Rl=n?e.length>0:e,Q.info("flags response received, isSurveysEnabled: "+this.Rl),this.loadIfEnabled()}}reset(){try{var t;(t=this._surveyEventReceiver)==null||t.reset(),localStorage.removeItem("lastSeenSurveyDate");for(var e=[],n=0;nlocalStorage.removeItem(r)))}catch{}}loadIfEnabled(){if(!this._surveyManager)if(this.Al)Q.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)Q.info(gu);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())Q.info("Not loading surveys in cookieless mode without consent.");else{var t=B?.__PosthogExtensions__;if(t){if(!C(this.Rl)||this.Ne.advanced_enable_surveys){var e=this.Rl||this.Ne.advanced_enable_surveys;this.Al=!0;try{var n=t.generateSurveys;if(n)return void this.Dl(n,e);var i=t.loadExternalDependency;if(!i)return void this.$l(ul);i(this._instance,"surveys",(r=>{r||!t.generateSurveys?this.$l("Could not load surveys script",r):this.Dl(t.generateSurveys,e)}))}catch(r){throw this.$l("Error initializing surveys",r),r}finally{this.Al=!1}}}else Q.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new zm(this._instance),Q.info("Surveys loaded successfully"),this.Nl({isLoaded:!0})}$l(t,e){Q.error(t,e),this.Nl({isLoaded:!1,error:t})}onSurveysLoaded(t){return this.Fl.push(t),this._surveyManager&&this.Nl({isLoaded:!0}),()=>{this.Fl=this.Fl.filter((e=>e!==t))}}getSurveys(t,e){if(e===void 0&&(e=!1),this.Ne.disable_surveys)return Q.info(gu),t([]);var n,i=this._instance.get_property(ua);if(i&&!e)return t(i,{isLoaded:!0}),void(this.ql()&&this.getSurveys((()=>{}),!0));typeof Promise<"u"&&this.Ll?this.Ll.then((r=>t(r.surveys,r.context))):(typeof Promise<"u"&&(this.Ll=new Promise((r=>{n=r}))),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this.Ne.token),method:"GET",timestampMode:"query",timeout:this.Ne.surveys_request_timeout_ms,callback:r=>{var s;this.Ll=null;var o=r.statusCode;if(o!==200||!r.json){var a="Surveys API could not be loaded, status: "+o;o!==0?Q.error(a):r.error||Q.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(n==null||n({surveys:[],context:l}))}this.Ol=null;var u,c=r.json.surveys||[],d=c.filter((h=>(function(p){return!(!p.start_date||p.end_date)})(h)&&(Kf(h)||(function(p){var g;return!((g=p.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(h))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(s=this._instance.persistence)==null||s.register({[ua]:c,[Qr]:Date.now()});var f={isLoaded:!0};t(c,f),n?.({surveys:c,context:f})}}))}ql(){return this.jl()&&!this.Ll&&!this.Bl()}jl(){var t=this._instance.get_property(Qr);return ke(t)&&Date.now()-t>3e5}Bl(){return ke(this.Ol)&&3e5>Date.now()-this.Ol}markSurveyAsSeen(t,e){var n,i={id:t,current_iteration:(n=e?.iteration)!==null&&n!==void 0?n:null};Jf(i);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}}Nl(t){for(var e of this.Fl)try{if(!t.isLoaded)return e([],t);this.getSurveys(e)}catch(n){Q.error("Error in survey callback",n)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!H(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);Q.warn("init was not called")}Hl(t){var e=null;return this.getSurveys((n=>{var i;e=(i=n.find((r=>r.id===t)))!==null&&i!==void 0?i:null})),e}Ul(t){if(H(this._surveyManager))return{eligible:!1,reason:kr};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyEligibility(e):{eligible:!1,reason:"Survey not found"}}zl(t){if(H(this._surveyManager))return{eligible:!1,reason:kr};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyRenderability(e):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(t){if(H(this._surveyManager))return Q.warn("init was not called"),{visible:!1,disabledReason:kr};var e=this.zl(t);return{visible:e.eligible,disabledReason:e.reason}}canRenderSurveyAsync(t,e){return H(this._surveyManager)?(Q.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:kr})):new Promise((n=>{this.getSurveys((i=>{var r,s=(r=i.find((a=>a.id===t)))!==null&&r!==void 0?r:null;if(s){var o=this.zl(s);n({visible:o.eligible,disabledReason:o.reason})}else n({visible:!1,disabledReason:"Survey not found"})}),e)}))}renderSurvey(t,e,n){var i;if(H(this._surveyManager))Q.warn("init was not called");else{var r=typeof t=="string"?this.Hl(t):t;if(r!=null&&r.id)if(km.includes(r.type)){var s=P?.querySelector(e);if(s)return(i=r.appearance)!=null&&i.surveyPopupDelaySeconds?(Q.info("Rendering survey "+r.id+" with delay of "+r.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;Q.info("Rendering survey "+r.id+" with delay of "+((o=r.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(a=this._surveyManager)==null||a.renderSurvey(r,s,n),Q.info("Survey "+r.id+" rendered")}),1e3*r.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(r,s,n);Q.warn("Survey element not found")}else Q.warn("Surveys of type "+r.type+" cannot be rendered in the app");else Q.warn("Survey not found")}}displaySurvey(t,e){var n;if(H(this._surveyManager))Q.warn("init was not called");else{var i=this.Hl(t);if(i){var r=i;if((n=i.appearance)!=null&&n.surveyPopupDelaySeconds&&e.ignoreDelay&&(r=I({},i,{appearance:I({},i.appearance,{surveyPopupDelaySeconds:0})})),e.displayType!==wa.Popover&&e.initialResponses&&Q.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),e.ignoreConditions===!1){var s=this.Ul(i);if(!s.eligible)return void Q.warn("Survey is not eligible to be displayed: ",s.reason)}e.displayType!==wa.Inline?this._surveyManager.handlePopoverSurvey(r,e):this.renderSurvey(r,e.selector,e.properties)}else Q.warn("Survey not found")}}cancelPendingSurvey(t){H(this._surveyManager)?Q.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},As),tv={toolbar:class{constructor(t){this.instance=t}Wl(t){B.ph_toolbar_state=t}Vl(){var t;return(t=B.ph_toolbar_state)!==null&&t!==void 0?t:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(t,e,n){if(t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),va(this.instance.config)||!w||!P)return!1;t=t??w.location,n=n??w.history;try{if(!e){try{w.localStorage.setItem("test","test"),w.localStorage.removeItem("test")}catch{return!1}e=w?.localStorage}var i,r=qm||as(t.hash,"__posthog")||as(t.hash,"state"),s=r?$c((()=>JSON.parse(atob(decodeURIComponent(r)))))||$c((()=>JSON.parse(decodeURIComponent(r)))):null;return s&&s.action==="ph_authorize"?((i=s).source="url",i&&Object.keys(i).length>0&&(s.desiredHash?t.hash=s.desiredHash:n?n.replaceState(n.state,"",t.pathname+t.search):t.hash="")):((i=JSON.parse(e.getItem(mu)||"{}")).source="localstorage",delete i.userIntent),!(!i.token||this.instance.config.token!==i.token||(this.loadToolbar(i),0))}catch{return!1}}Zl(t){var e=B.ph_load_toolbar||B.ph_load_editor;!H(e)&&je(e)?e(t,this.instance):vu.warn("No toolbar load function found")}loadToolbar(t){var e=!(P==null||!P.getElementById(df));if(!w||e)return!1;var n=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,i=I({token:this.instance.config.token},t,{apiURL:this.instance.requestRouter.endpointFor("ui")},n?{instrument:!1}:{});if(w.localStorage.setItem(mu,JSON.stringify(I({},i,{source:void 0}))),this.Vl()===2)this.Zl(i);else if(this.Vl()===0){var r;this.Wl(1),(r=B.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"toolbar",(s=>{if(s)return vu.error("[Toolbar] Failed to load",s),void this.Wl(0);this.Wl(2),this.Zl(i)})),ve(w,"turbolinks:load",(()=>{this.Wl(0),this.loadToolbar(i)}))}return!0}Gl(t){return this.loadToolbar(t)}maybeLoadEditor(t,e,n){return t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),this.maybeLoadToolbar(t,e,n)}}},nv=I({experiments:Me},As),iv={conversations:class{constructor(t){this.Ql=void 0,this._conversationsManager=null,this.Kl=!1,this.Jl=null,this.Yl=!1,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this._instance.config.disable_conversations&&(this.Xl=t.ok,t.ok)){var e=t.config.conversations;H(e)||(mt(e)?this.Ql=e:(this.Ql=e.enabled,this.Jl=e),this.loadIfEnabled())}}reset(){var t;(t=this._conversationsManager)==null||t.reset(),this._conversationsManager=null,this.Ql=void 0,this.Jl=null,this.Xl=void 0,this.Yl=!1}loadIfEnabled(){if(!(this._conversationsManager||this.Kl||this._instance.config.disable_conversations||va(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=B?.__PosthogExtensions__;if(t&&!C(this.Ql)&&this.Ql)if(this.Jl&&this.Jl.token){this.Kl=!0;try{var e=t.initConversations;if(e)return this.tu(e),void(this.Kl=!1);var n=t.loadExternalDependency;if(!n)return void this.eu(ul);n(this._instance,"conversations",(i=>{i||!t.initConversations?this.eu("Could not load conversations script",i):this.tu(t.initConversations),this.Kl=!1}))}catch(i){this.eu("Error initializing conversations",i),this.Kl=!1}}else ot.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,ot.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else ot.error("Cannot complete initialization: remote config is null")}eu(t,e){ot.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():ot.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!Ye(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":va(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.Xl===!1?"remote_config_failed":C(this.Ql)?this.Xl?"disabled_in_project":"remote_config_pending":this.Ql?H(this.Jl)||!this.Jl.token?"missing_token":B!=null&&B.__PosthogExtensions__?this.Kl?"initializing":this.Yl?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.isVisible())!==null&&t!==void 0&&t}sendMessage(t,e,n){var i=this;return se((function*(){return i._conversationsManager?i._conversationsManager.sendMessage(t,e,n):(ot.warn(En),null)}))()}getMessages(t,e){var n=this;return se((function*(){return n._conversationsManager?n._conversationsManager.getMessages(t,e):(ot.warn(En),null)}))()}markAsRead(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(ot.warn(En),null)}))()}getTickets(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(ot.warn(En),null)}))()}requestRestoreLink(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(ot.warn(En),null)}))()}restoreFromToken(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(ot.warn(En),null)}))()}restoreFromUrlToken(){var t=this;return se((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(ot.warn(En),null)}))()}getCurrentTicketId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getCurrentTicketId())!==null&&t!==void 0?t:null}getWidgetSessionId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getWidgetSessionId())!==null&&t!==void 0?t:null}Xn(){var t;(t=this._conversationsManager)==null||t.setIdentity()}ts(){var t;(t=this._conversationsManager)==null||t.clearIdentity()}}},rv={logs:class{constructor(t){var e,n=this;this.iu=!1,this.ru=!1,this.rt=pe("[logs]"),this.nu=I({},this.rt,{error(){for(var i=arguments.length,r=new Array(i),s=0;i>s;s++)r[s]=arguments[s];r.some(Iu)||n.rt.error(...r)}}),this.tr=[],this.su=[],this.Sa=0,this.au=()=>{var i,r;this.Sa=0,(i=this.ou)==null||i.onReconnect(),(r=this.lu)==null||r.onReconnect()},this._instance=t,this._instance&&(e=this._instance.config.logs)!=null&&e.captureConsoleLogs&&(this.iu=!0),w&&ve(w,"online",this.au)}uu(t,e,n,i){var r,s=(function(o,a){var l,u,c,d,f,h,p,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,v=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,E=C(v)?Math.max(m,2048):Math.max(m,v),S=o?.resourceAttributes;return{serviceName:(d=(f=S?.["service.name"])!==null&&f!==void 0?f:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(h=S?.["service.version"])!==null&&h!==void 0?h:o?.serviceVersion,environment:(p=S?.["deployment.environment"])!==null&&p!==void 0?p:o?.environment,resourceAttributes:S,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:E,maxBatchRecordsPerPost:100,rateCapWindowMs:g,maxLogsPerInterval:v,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}})((r=this._instance)==null||(r=r.config)==null?void 0:r.logs,n);return[new lg(this.hu(t,e),s,this.nu,(()=>this.du()),(o=>o()),void 0,i),s]}vu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.ou||this.cu!==e){var n;(n=this.ou)==null||n.reset(),this.cu=e;var i=this.uu((()=>this.tr),(r=>{this.tr=r}));this.ou=i[0],this.fu=i[1]}return this.ou}pu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.lu||this.gu!==e){var n;(n=this.lu)==null||n.reset(),this.gu=e;var i=this.uu((()=>this.su),(r=>{this.su=r}),{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},xu);this.lu=i[0],this.mu=i[1]}return this.lu}initialize(){this.loadIfEnabled()}onRemoteConfig(t){var e;if(t.ok){var n=(e=t.config.logs)==null?void 0:e.captureConsoleLogs;!H(n)&&n&&(this.iu=!0,this.loadIfEnabled())}}reset(){var t,e;this.tr=[],(t=this.ou)==null||t.reset(),this.su=[],(e=this.lu)==null||e.reset(),this.Sa=0}captureLog(t){this.vu().captureLog(t)}he(t){this.pu().captureLog(t)}get logger(){return this.yu||(this.yu={trace:(t,e)=>this.captureLog({body:t,level:"trace",attributes:e}),debug:(t,e)=>this.captureLog({body:t,level:"debug",attributes:e}),info:(t,e)=>this.captureLog({body:t,level:"info",attributes:e}),warn:(t,e)=>this.captureLog({body:t,level:"warn",attributes:e}),error:(t,e)=>this.captureLog({body:t,level:"error",attributes:e}),fatal:(t,e)=>this.captureLog({body:t,level:"fatal",attributes:e})}),this.yu}flushLogs(t){t?this.bu(t):(this.ou&&this.ou.flush().catch((e=>this._u(e))),this.lu&&this.lu.flush().catch((e=>this._u(e))))}_u(t){Iu(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=B?.__PosthogExtensions__;if(t){var e=t.loadExternalDependency;e?e(this._instance,"logs",(n=>{var i;n||(i=t.logs)==null||!i.initializeLogs?this.rt.error("Could not load logs script",n):(t.logs.initializeLogs(this._instance),this.ru=!0)})):this.rt.error(ul)}else this.rt.error("PostHog Extensions not found.")}}hu(t,e){var n=this._instance;return{get isDisabled(){return!1},get optedOut(){return!n.is_capturing()},getPersistedProperty:i=>i===Ut.LogsQueue?t():void 0,setPersistedProperty(i,r){var s;i===Ut.LogsQueue&&e((s=r)!==null&&s!==void 0?s:[])},Ot:i=>this.Ot(i),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Ot(t){return new Promise((e=>{if(Sf(this.Sa,3))e({kind:"fatal",error:Uo(void 0,"logs endpoint is unreachable, dropping batch")});else{var n=!1,i=s=>{n||(n=!0,clearTimeout(r),e(s))},r=setTimeout((()=>{this.rt.warn("Logs request timed out before receiving a response"),i({kind:"retry-later",error:Uo(void 0,"logs request timed out")})}),9e4);this._instance._send_request({method:"POST",url:this.wu(),data:t,compression:"best-available",batchKey:"logs",fireCallbackOnDrop:!0,callback:s=>{var o=s.statusCode;if(this.ku(o),o>=200&&300>o)i({kind:"ok"});else if(o===413)i({kind:"too-large"});else if(o!==0&&o!==429&&500>o)i({kind:"fatal",error:new Error("logs request failed with status "+o)});else{var a;o===0?(s.error||this.rt.warn("Logs request failed before receiving an HTTP response"),i({kind:"retry-later",error:Uo(s.error,"logs request failed before receiving an HTTP response")})):i({kind:"retry-later",error:(a=s.error)!==null&&a!==void 0?a:new Error("logs request failed with status "+o)})}}})}}))}ku(t){(t!==0||this._instance.__loaded)&&(this.Sa=xf(t,this.Sa,3,(()=>this.rt.warn("Log requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped sending logs; will try again when connectivity changes."))))}bu(t){this.tr.length>0&&this.xu(t,this.tr,this.fu,ne.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,xu,(e=>{this.su=e}))}xu(t,e,n,i,r){if(e.length!==0){var s=e.map((a=>a.record));r([]);var o=Gd(s,Vd(n,ne.LIB_NAME,ne.LIB_VERSION),i,ne.LIB_VERSION);this._instance._send_request({method:"POST",url:this.wu(),data:o,compression:"best-available",batchKey:"logs",transport:t})}}wu(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}du(){var t,e={};if(e.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var n=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.windowId,r=n.sessionStartTimestamp,s=n.lastActivityTimestamp;e.sessionId=n.sessionId,e.windowId=i,H(r)||(e.sessionStartTimestamp=r),H(s)||(e.lastActivityTimestamp=s)}if(B!=null&&(t=B.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?fn(B.location.href):B.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},sv={metrics:class{constructor(t){this.rt=pe("[metrics]"),this._instance=t}initialize(){}vu(){var t,e,n=(t=this._instance)==null||(t=t.config)==null?void 0:t.metrics;return this.ou&&this.cu===n||((e=this.ou)==null||e.reset(),this.cu=n,this.ou=new cg(this.hu(),(function(i){var r,s,o,a,l,u=i?.resourceAttributes;return{serviceName:(r=u?.["service.name"])!==null&&r!==void 0?r:i?.serviceName,serviceVersion:(s=u?.["service.version"])!==null&&s!==void 0?s:i?.serviceVersion,environment:(o=u?.["deployment.environment"])!==null&&o!==void 0?o:i?.environment,resourceAttributes:u,beforeSend:i?.beforeSend,flushIntervalMs:(a=i?.flushIntervalMs)!==null&&a!==void 0?a:1e4,maxSeriesPerFlush:(l=i?.maxSeriesPerFlush)!==null&&l!==void 0?l:1e3}})(n),this.rt)),this.ou}count(t,e,n){e===void 0&&(e=1),this.vu().count(t,e,n)}gauge(t,e,n){this.vu().gauge(t,e,n)}histogram(t,e,n){this.vu().histogram(t,e,n)}flush(t){if(!this.ou)return Promise.resolve();if(t){var e=this.ou.drainWindow();return e&&this.Jt(e,t),Promise.resolve()}return this.ou.flush().catch((n=>this.rt.error("PostHog metrics flush failed:",n)))}reset(){var t;(t=this.ou)==null||t.reset()}hu(){var t=this._instance,e=this;return{get isDisabled(){return!1},get optedOut(){return!t.is_capturing()},Jt:n=>e.Jt(n),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Jt(t,e){return new Promise((n=>{var i=!1,r=o=>{i||(i=!0,clearTimeout(s),n(o))},s=setTimeout((()=>r({kind:"retry-later",error:new Error("metrics request timed out")})),9e4);this._instance._send_request(I({method:"POST",url:this.Su(),data:t,compression:"best-available",batchKey:"metrics"},e&&{transport:e},{fireCallbackOnDrop:!0,callback(o){var a=o.statusCode;if(a>=200&&300>a)r({kind:"ok"});else if(a===413)r({kind:"too-large"});else if(a!==0&&a!==429&&500>a)r({kind:"fatal",error:new Error("metrics request failed with status "+a)});else{var l;r({kind:"retry-later",error:(l=o.error)!==null&&l!==void 0?l:new Error("metrics request failed with status "+a)})}}}))}))}Su(){return this._instance.requestRouter.endpointFor("api","/i/v1/metrics")+"?token="+encodeURIComponent(this._instance.config.token)}}},ov=I({},As,Km,Ym,Jm,Zm,Xm,ev,Qm,tv,nv,iv,rv,sv);Ze.__defaultExtensionClasses=I({},ov);(function(){ne.SDK_DIST_CHANNEL="npm";var t=zi[Kn]=new Ze;return(function(){function e(){e.done||(e.done=!0,Xf=!1,ie(zi,(function(n){n._dom_loaded()})))}P!=null&&P.addEventListener?P.readyState==="complete"?e():ve(P,"DOMContentLoaded",e,{capture:!1}):w&&A.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const av=["a[href]","button:not([disabled])","input:not([disabled]):not([type='hidden'])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(",");let pt=null,Aa=null,eh="";const Pa=new Map;function th(t){return[...t.querySelectorAll(av)].filter(e=>!e.hidden&&e.getAttribute("aria-hidden")!=="true"&&e.getClientRects().length>0)}function lv(t){for(const e of document.body.children)e===t||e.tagName==="SCRIPT"||(Pa.set(e,{inert:e.inert,ariaHidden:e.getAttribute("aria-hidden")}),e.inert=!0,e.setAttribute("aria-hidden","true"))}function cv(){for(const[t,e]of Pa)t.inert=e.inert,e.ariaHidden===null?t.removeAttribute("aria-hidden"):t.setAttribute("aria-hidden",e.ariaHidden);Pa.clear()}function nh(t){return t?.dataset.modalDismissible!=="false"&&t?.getAttribute("aria-busy")!=="true"}function We(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n)return!1;pt&&pt!==n&&ze(pt,{restoreFocus:!1,force:!0}),Aa=e.trigger||document.activeElement,pt=n,eh=document.body.style.overflow,lv(n),document.body.style.overflow="hidden",n.classList.add("open"),n.setAttribute("aria-hidden","false");const i=n.querySelector(".modal-content");i&&(i.style.transform="scale(1) translateY(0)");const r=()=>{if(pt!==n)return;((e.initialFocus?n.querySelector(e.initialFocus):n.querySelector("[data-modal-initial-focus]"))||th(n)[0]||n.querySelector(".modal-content")||n).focus({preventScroll:!0})};return requestAnimationFrame(r),setTimeout(r,260),!0}function ze(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n||!e.force&&!nh(n))return!1;n.classList.remove("open"),n.setAttribute("aria-hidden","true"),cv(),document.body.style.overflow=eh,pt=null;const i=Aa;return Aa=null,e.restoreFocus!==!1&&i?.isConnected&&i.focus({preventScroll:!0}),!0}function ku(t,e,n="Operation in progress"){const i=typeof t=="string"?document.getElementById(t):t;i&&(i.dataset.modalDismissible=e?"false":"true",i.setAttribute("aria-busy",String(!!e)),e?i.setAttribute("aria-label",n):i.removeAttribute("aria-label"))}function uv(t){if(!nh(t))return;const e=t.dataset.modalCloseHandler;e&&typeof window[e]=="function"?window[e]():ze(t)}document.addEventListener("keydown",t=>{if(!pt)return;if(t.key==="Escape"){t.preventDefault(),t.stopImmediatePropagation(),uv(pt);return}if(t.key!=="Tab"){t.stopPropagation();return}const e=th(pt);if(!e.length){t.preventDefault(),(pt.querySelector(".modal-content")||pt).focus();return}const n=e[0],i=e[e.length-1];t.shiftKey&&document.activeElement===n?(t.preventDefault(),i.focus()):!t.shiftKey&&document.activeElement===i&&(t.preventDefault(),n.focus())},!0);function dv(){document.querySelectorAll(".modal-overlay").forEach(t=>{t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-hidden",t.classList.contains("open")?"false":"true");const e=t.querySelector(".modal-content");e&&!e.hasAttribute("tabindex")&&(e.tabIndex=-1);const n=t.querySelector("h1, h2, h3");n&&(n.id||(n.id=`${t.id}-title`),t.setAttribute("aria-labelledby",n.id)),t.querySelectorAll(".modal-close").forEach(i=>{i.getAttribute("aria-label")||i.setAttribute("aria-label","Close dialog")})})}const _l=Object.freeze({free:"Free",professional:"Pro",power:"Power"}),fv=Object.freeze({free:2,professional:50,power:2e3}),hv="(contact us)",pv=Object.freeze({free:Object.freeze(["2 generations/month","Gemini model only","Code Review"]),professional:Object.freeze(["50 generations/month","All models","Code Regeneration","Code Review"]),power:Object.freeze(["2000 generations/month","All models","Code Regeneration","Bring your own key (BYOK)","Code Review","All models + early access",`API & MCP access ${hv}`])}),ih="CodeFile",rh="GeneratedCode",gv={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function ln(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Fa(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function mv(t={},e=0){const n=Fa(t.artifactType||t.type||ih),i=Fa(t.artifactName||t.name||t.fileName||`${rh}-${e+1}`);return`${n||"artifact"}-${i||e+1}`}function sh(t={},e=0){const n=ln(t),i=n.artifactType||n.type||ih,r=n.artifactName||n.name||rh;let s=n.fileName||r;return s.endsWith(".dart")||(s+=".dart"),{id:Fa(n.id)||mv({...n,artifactType:i,artifactName:r,fileName:s},e),artifactType:i,artifactName:r,fileName:s,deployPath:n.deployPath||"",description:n.description||"",code:n.code||n.content||"",dependencies:oh(n.dependencies),imports:Array.isArray(n.imports)?n.imports:[],publicApi:Array.isArray(n.publicApi)?n.publicApi:[],relationships:ah(n.relationships),deployStatus:n.deployStatus||"pending",review:n.review||null,metadata:ln(n.metadata),codeType:n.codeType||gv[i]||"O"}}function oh(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const n=ln(e),i=n.name||n.package;return i?{name:i,version:n.version||null,versionRequired:!!(n.versionRequired||n.required),inferred:!!n.inferred,...n.reason?{reason:n.reason}:{}}:null}).filter(Boolean):Object.entries(ln(t)).map(([e,n])=>({name:e,version:n||null,inferred:!1})):[]}function ah(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const n=ln(e);return!n.from&&!n.to?null:{from:n.from||null,to:n.to||null,type:n.type||"uses",description:n.description||""}}).filter(Boolean):[]}function Ra(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;try{return JSON.parse(e)}catch{const n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(!n)return null;try{return JSON.parse(n[1].trim())}catch{return null}}}function er(t,e={}){const n=[],i=typeof t=="string"?Ra(t):t,s=ln(i||{});!i&&typeof t=="string"&&n.push("Structured bundle parse failed; using legacy single-artifact fallback.");const o=Array.isArray(s.artifacts)?s.artifacts:[{artifactType:s.artifactType||e.artifactType,artifactName:s.artifactName||e.artifactName,fileName:s.fileName||e.fileName,description:s.description,code:s.code||e.code||(typeof t=="string"?t:""),dependencies:s.dependencies||e.dependencies,relationships:s.relationships||e.relationships}];o.forEach((d,f)=>{!d?.artifactType&&!d?.type&&n.push(`Artifact ${f+1} has no artifactType; it will deploy as a standalone code file under lib/custom_code/ root.`)});const a=o.map((d,f)=>sh(d,f)),l=new Map(o.map((d,f)=>[ln(d).id,a[f]?.id]).filter(([d,f])=>d&&f)),u=d=>l.get(d)||d,c=ah(s.relationships||e.relationships).map(d=>({...d,from:d.from?u(d.from):d.from,to:d.to?u(d.to):d.to}));return{schemaVersion:s.schemaVersion||e.schemaVersion||null,id:s.id||e.id||"bundle-current",title:s.title||s.name||e.title||"Generated artifact bundle",description:s.description||e.description||"",artifacts:a,dependencies:oh(s.dependencies||e.dependencies),relationships:c,deployOrder:Array.isArray(s.deployOrder)?s.deployOrder.map(u):a.map(d=>d.id),warnings:[...n,...Array.isArray(s.warnings)?s.warnings:[]],metadata:ln(s.metadata)}}function ai(t){return er(t).artifacts[0]||sh()}function Zt(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function li(t){return JSON.stringify(t,null,2)}function vv(t){return li({task:"architect",userRequest:String(t??"")})}function _v(t){const e=Zt(t);return e&&typeof e=="object"&&typeof e.task=="string"?li(e):li({task:"generate_bundle",bundleSpec:e})}function yv(t){return li({task:"review_bundle",generatedBundle:Zt(t),outputRequirements:{bundleReview:["status","score","summary","manualActions","findings"],scoreRange:[0,100],eachArtifact:["id","review.status","review.findings"],manualActions:{definition:"Setup the developer must perform by hand in the FlutterFlow editor that FlutterFlow will NOT do for them.",exclude:["creating the Custom Action, Widget or Code File itself - deploying the code creates it","declaring parameters or return values FlutterFlow derives from the function signature","anything that resolves as a side effect of using the action or widget in the editor","generic advice such as testing, reviewing or rebuilding the app"],preferEmpty:"Return an empty array when nothing qualifies - an empty list is the expected result for most bundles."}}})}function yl(t,e=null){const n={stage:t};return e!=null&&(n.bundle=Zt(e)),n}function wv({bundleSpec:t,artifactBundle:e,bundleReview:n,artifactId:i,userFeedback:r}){return li({task:"regenerate_artifact",artifactId:i,bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(r)})}function lh({bundleSpec:t,artifactBundle:e,bundleReview:n,userFeedback:i}){return li({task:"regenerate_bundle",bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(i??"")})}const Cu={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"},bv=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function tt(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Ev(t){return tt(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||tt(t.filterSummary)||tt(t.filterResults):!1}function ch(t,e=0){if(!tt(t)||e>3)return null;if(Ev(t))return t;for(const n of bv){const i=t[n];if(tt(i)){const r=ch(i,e+1);if(r)return r}}return null}function fs(t){return Array.isArray(t)?t.some(fs):tt(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(fs):!1}function Ta(t){return Array.isArray(t)?t.some(Ta):tt(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(Ta):!1}function uh(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function Sv(t,e){if(tt(t))for(const[n,i]of Object.entries(t)){if(!tt(i))continue;const r=tt(i.categories)?i.categories:{},s=Object.entries(r).filter(([,o])=>tt(o)&&o.matched===!0).map(([o])=>o);s.length>0?s.forEach(o=>e.add(o)):i.matched===!0&&e.add(uh(n))}}function xv(t,e){if(!t)return;const n=Array.isArray(t)?t.flatMap(i=>tt(i)?Object.entries(i):[]):Object.entries(t);for(const[i,r]of n){if(!fs(r))continue;const s=uh(i),o=r?.raiFilterResult?.raiFilterTypeResults||(s==="rai"?r?.raiFilterTypeResults:null),a=tt(o)?Object.entries(o).filter(([,l])=>fs(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(s)}}function Iv(t){return Cu[t]?Cu[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function Au(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 kv(t){const e=ch(t);if(!e)return null;const n=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);Sv(e.filterSummary,n),xv(e.filterResults,n);const i=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||n.size>0,r=e.invocationResult||null,s=Ta(e.filterSummary||e.filterResults);return!i&&!s&&!["PARTIAL","FAILURE"].includes(r)?null:{kind:i?"blocked":"unavailable",invocationResult:r,matchedFilters:[...n]}}function Cv(t,e){const n=kv(t);if(!n)return null;const i=[...new Set(n.matchedFilters.map(Iv))],r=n.kind==="blocked",s=new Error(r?`Safety screening blocked this pipeline step for ${Au(i)}.`:"Safety screening could not be completed. Please try again.");return s.name="ModelArmorError",s.code=r?"MODEL_ARMOR_BLOCKED":"MODEL_ARMOR_UNAVAILABLE",s.isModelArmor=!0,s.pipelineStep=e,s.userTitle=r?"Request blocked for safety":"Safety check unavailable",s.userMessage=r?`The safety check detected ${Au(i)}. Edit your request to remove or rephrase the flagged content, then run the pipeline again.`:"The safety service did not finish all of its checks. Please wait a moment and run the pipeline again.",s.retryExplanation=r?"Trying another model would not change this safety decision.":"A fallback model was not attempted because safety screening must complete first.",s.matchedFilters=n.matchedFilters,s}function Av(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function Pu(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,n=[];for(const i of Av(t).split(` -`)){if(!/^[A-Za-z_$]/.test(i)||e.test(i))continue;const r=i.match(/^[\w$<>,?\s[\]]+?\s([a-zA-Z_$][\w$]*)\s*\(/);r&&n.push(r[1])}return n}function wl(t,e){const n=t.replace(/\.dart$/,"");if(e==="W")return n.replace(/(^|_)(\w)/g,(i,r,s)=>s.toUpperCase());if(e==="A"){const i=n.replace(/(^|_)(\w)/g,(r,s,o)=>o.toUpperCase());return i.charAt(0).toLowerCase()+i.slice(1)}return e==="F"?"CustomFunctions":e==="C"?t.endsWith(".dart")?t:`${t}.dart`:n}async function Fu(t){const e=new TextEncoder().encode(String(t||"")),n=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n),i=>i.toString(16).padStart(2,"0")).join("")}async function Pv(t,e=new Map){const n={},i=new Set;for(const[o,a]of t.entries()){if(a.type==="D"||a.type==="O")continue;const l=wl(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await Fu(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await Fu(c)),n[o]=u,a.type==="F"){const d=Pu(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(h=>i.add(h))}}const r=new Set(Pu(e.get("lib/flutter_flow/custom_functions.dart")||"")),s={functions_to_rename:[],functions_to_delete:[],functions_to_add:Array.from(i).filter(o=>!r.has(o))};return{fileMapContents:JSON.stringify(n),functionsMapContents:JSON.stringify(s)}}const Fv=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),Ru={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},Rv=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),Tv=["Struct","Record"],$v=[{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=>Ho(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=>Ho(t).some(e=>{const n=/^\s*final\s+(?:double|int|String|bool|Color|num)\s+(\w+)\s*;/gm;let i;for(;(i=n.exec(e))!==null;){const r=i[1];if(!(new RegExp(`this\\.${r}\\s*=(?!=)`).test(e)||new RegExp(`[:,]\\s*${r}\\s*=(?!=)`).test(e)))return!0}return!1}),pos:`class W extends StatefulWidget { +(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const s of r)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function n(r){const s={};return r.integrity&&(s.integrity=r.integrity),r.referrerPolicy&&(s.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?s.credentials="include":r.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function i(r){if(r.ep)return;r.ep=!0;const s=n(r);fetch(r.href,s)}})();var w=typeof window<"u"?window:void 0,Ne=typeof globalThis<"u"?globalThis:w,He=Ne?.navigator,P=Ne?.document,me=Ne?.location,nl=Ne?.fetch,Ko=Ne!=null&&Ne.XMLHttpRequest&&"withCredentials"in new Ne.XMLHttpRequest?Ne.XMLHttpRequest:void 0,mc=Ne?.AbortController,Up=Ne?.CompressionStream,Ge=He?.userAgent;function _d(){return!(!w||w.navigator.onLine===!1)}var wi=typeof globalThis<"u"?globalThis:w;wi&&typeof self>"u"&&(wi.self=wi),wi&&typeof File>"u"&&(wi.File=function(){});var B=w??{},ne={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function vc(t,e,n,i,r,s,o){try{var a=t[s](o),l=a.value}catch(u){return void n(u)}a.done?e(l):Promise.resolve(l).then(i,r)}function se(t){return function(){var e=this,n=arguments;return new Promise((function(i,r){var s=t.apply(e,n);function o(l){vc(s,i,r,o,a,"next",l)}function a(l){vc(s,i,r,o,a,"throw",l)}o(void 0)}))}}function I(){return I=Object.assign?Object.assign.bind():function(t){for(var e=1;arguments.length>e;e++){var n=arguments[e];for(var i in n)({}).hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},I.apply(null,arguments)}function yd(t,e){if(t==null)return{};var n={};for(var i in t)if({}.hasOwnProperty.call(t,i)){if(e.indexOf(i)!==-1)continue;n[i]=t[i]}return n}var _c=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function yc(t){return typeof t=="string"||t}function wc(t){return typeof t=="string"?t:void 0}var bi,Hp=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],Ut=(function(t){return t.AnonymousId="anonymous_id",t.DistinctId="distinct_id",t.Props="props",t.EnablePersonProcessing="enable_person_processing",t.PersonMode="person_mode",t.FeatureFlagDetails="feature_flag_details",t.FeatureFlags="feature_flags",t.FeatureFlagPayloads="feature_flag_payloads",t.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",t.BootstrapFeatureFlags="bootstrap_feature_flags",t.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",t.OverrideFeatureFlags="override_feature_flags",t.Queue="queue",t.AiQueue="ai_queue",t.LogsQueue="logs_queue",t.OptedOut="opted_out",t.SessionId="session_id",t.SessionStartTimestamp="session_start_timestamp",t.SessionLastTimestamp="session_timestamp",t.PersonProperties="person_properties",t.GroupProperties="group_properties",t.InstalledAppBuild="installed_app_build",t.InstalledAppVersion="installed_app_version",t.SessionReplay="session_replay",t.PushRegistered="push_registered",t.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",t.SurveyLastSeenDate="survey_last_seen_date",t.SurveysSeen="surveys_seen",t.Surveys="surveys",t.RemoteConfig="remote_config",t.FlagsEndpointWasHit="flags_endpoint_was_hit",t.DeviceId="device_id",t})({}),bc=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),Wp=["$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"],zp=["token"],wd="NativeGzipValidationError",Yo=t=>t.length>=2&&t[0]===31&&t[1]===139,Ec=(t,e)=>t===bc.GZipJS||e===bc.GZipJS||e==="gzip",Sc=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",vr=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=wd,e},qp=(function(){var t=se((function*(e,n){18>e.size&&vr("too-short");var i=new Uint8Array(yield e.slice(0,10).arrayBuffer());Yo(i)&&i[2]===8||vr("invalid-header");var r=new DataView(yield e.slice(e.size-8).arrayBuffer());r.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(bi)return bi;bi=[];for(var c=0;256>c;c++){for(var d=c,f=0;8>f;f++)d=1&d?3988292384^d>>>1:d>>>1;bi[c]=d>>>0}return bi})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(n)&&vr("invalid-crc");var s=n.length>>>0;r.getUint32(4,!0)!==s&&vr("invalid-size")}));return function(e,n){return t.apply(this,arguments)}})();function Jo(){return Jo=se((function*(t,e,n){e===void 0&&(e=!0);try{var i=new TextEncoder().encode(t),r=new globalThis.CompressionStream("gzip"),s=r.writable.getWriter(),o=s.write(i).then((()=>s.close())).catch((function(){var u=se((function*(c){try{yield s.abort(c)}catch{}throw c}));return function(c){return u.apply(this,arguments)}})()),a=new Response(r.readable).blob(),l=(yield Promise.all([a,o]))[0];return yield qp(l,i),l}catch(u){if(n!=null&&n.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),Jo.apply(this,arguments)}var Vp=["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"],xc=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var n=t.toLowerCase();return Vp.concat(e).some((i=>{var r=i.toLowerCase();return n.indexOf(r)!==-1}))};function j(t,e){return t.indexOf(e)!==-1}var As=function(t){return t.trim()},Zo=function(t){return t.replace(/^\$/,"")};function bd(t){var e,n=[];return(e=JSON.stringify(t,(function(i,r){if(typeof r=="bigint")return r.toString();if(typeof r!="function"&&typeof r!="symbol"){if(r instanceof Error)return{name:r.name,message:r.message,stack:r.stack};if(r&&typeof r=="object"){for(;n.length>0&&n[n.length-1]!==this;)n.pop();if(n.includes(r))return"[Circular]";n.push(r)}return r}})))!==null&&e!==void 0?e:"null"}var Ed=Object.prototype,Sd=Ed.hasOwnProperty,Ps=Ed.toString,U=Array.isArray||function(t){return Ps.call(t)==="[object Array]"},je=t=>typeof t=="function",he=t=>t===Object(t)&&!U(t),Kt=t=>{if(he(t)){for(var e in t)if(Sd.call(t,e))return!1;return!0}return!1},C=t=>t===void 0,X=t=>Ps.call(t)=="[object String]",Xo=t=>X(t)&&t.trim().length===0,Ye=t=>t===null,H=t=>C(t)||Ye(t),ke=t=>Ps.call(t)=="[object Number]"&&t==t,Dt=t=>ke(t)&&t>0,mt=t=>Ps.call(t)==="[object Boolean]",Gp=t=>t instanceof FormData,Kp=t=>j(Wp,t),Yp=t=>j(zp,t);function xd(t){return t===null||typeof t!="object"}function Vr(t,e){return{}.toString.call(t)==="[object "+e+"]"}function il(t){return typeof Event<"u"&&Id(t,Event)}function Id(t,e){try{return t instanceof e}catch{return!1}}var Jp=[!0,"true",1,"1","yes"],go=t=>j(Jp,t),Zp=[!1,"false",0,"0","no"];function At(t,e,n,i,r){return e>n&&(i.warn("min cannot be greater than max."),e=n),ke(t)?t>n?(i.warn(" cannot be greater than max: "+n+". Using max value instead."),n):e>t?(i.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(i.warn(" must be a number. using max or fallback. max: "+n+", fallback: "+r),At(r||n,e,n,i))}class Xp{constructor(e){this.tt={},this.et=e.et,this.it=At(e.bucketSize,0,100,e.rt),this.nt=At(e.refillRate,0,this.it,e.rt),this.st=At(e.refillInterval,0,864e5,e.rt)}ot(e,n){var i=Math.floor((n-e.lastAccess)/this.st);i>0&&(e.tokens=Math.min(e.tokens+i*this.nt,this.it),e.lastAccess=e.lastAccess+i*this.st)}consumeRateLimit(e){var n,i=Date.now(),r=String(e),s=this.tt[r];return s?this.ot(s,i):this.tt[r]=s={tokens:this.it,lastAccess:i},s.tokens===0||(s.tokens--,s.tokens===0&&((n=this.et)==null||n.call(this,e)),s.tokens===0)}stop(){this.tt={}}}var rt="Mobile",Gr="iOS",Yt="Android",ni="Tablet",kd=Yt+" "+ni,Cd="iPad",Ad="Apple",Pd=Ad+" Watch",Ui="Safari",ii="BlackBerry",Fd="Samsung",Rd=Fd+"Browser",Td=Fd+" Internet",Pn="Chrome",Qp=Pn+" OS",$d=Pn+" "+Gr,rl="Internet Explorer",Md=rl+" "+rt,sl="Opera",eg=sl+" Mini",ol="Edge",Ld="Microsoft "+ol,Zn="Firefox",Nd=Zn+" "+Gr,Ji="Nintendo",Zi="PlayStation",Xn="Xbox",Od=Yt+" "+rt,Bd=rt+" "+Ui,Ti="Windows",Qo=Ti+" Phone",Ic="Nokia",ea="Ouya",Dd="Generic",tg=Dd+" "+rt.toLowerCase(),jd=Dd+" "+ni.toLowerCase(),ta="Konqueror",Ud="Oculus Browser",Kr="Vivaldi",Hd="Yandex",Yr="Whale",na="DuckDuckGo",Wd="Pale Moon",Jr="Waterfox",Hi="Brave",zd="Google Search App",we="(\\d+(\\.\\d+)?)",mo=new RegExp("Version/"+we),ng=new RegExp(Xn,"i"),ig=new RegExp(Zi+" \\w+","i"),rg=new RegExp(Ji+" \\w+","i"),al=new RegExp(ii+"|PlayBook|BB10","i"),sg={"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"},qd=function(t,e,n,i){e=e||"";var r=(function(s){return s!=null&&s.brave?Hi:null})(n);return r||(i!=null&&i.detectGoogleSearchApp&&j(t,"GSA/")?zd:j(t," OPR/")&&j(t,"Mini")?eg:j(t," OPR/")?sl:al.test(t)?ii:j(t,"IE"+rt)||j(t,"WPDesktop")?Md:j(t,"OculusBrowser")?Ud:j(t,Rd)?Td:j(t,ol)||j(t,"Edg/")?Ld:j(t,Kr+"/")?Kr:j(t,"YaBrowser/")?Hd:j(t,Yr+"/")?Yr:j(t,na+"/")||j(t,"Ddg/")?na:j(t,"FBIOS")?"Facebook "+rt:j(t,"UCWEB")||j(t,"UCBrowser")?"UC Browser":j(t,"CriOS")?$d:j(t,"CrMo")||j(t,Pn)?Pn:j(t,Yt)&&j(t,Ui)?Od:j(t,"FxiOS")?Nd:j(t.toLowerCase(),ta.toLowerCase())?ta:j(t,Hi+"/")?Hi:((s,o)=>o&&j(o,Ad)||(function(a){return j(a,Ui)&&!j(a,Pn)&&!j(a,Yt)})(s))(t,e)?j(t,rt)?Bd:Ui:j(t,"PaleMoon/")?Wd:j(t,Jr+"/")?Jr:j(t,Zn)?Zn:j(t,"MSIE")||j(t,"Trident/")?rl:j(t,"Gecko")?Zn:"")},og={[Md]:[new RegExp("rv:"+we)],[Ld]:[new RegExp(ol+"?\\/"+we)],[Pn]:[new RegExp("("+Pn+"|CrMo)\\/"+we)],[$d]:[new RegExp("CriOS\\/"+we)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+we)],[Ui]:[mo],[Bd]:[mo],[sl]:[new RegExp("(Opera|OPR)\\/"+we)],[Zn]:[new RegExp(Zn+"\\/"+we)],[Nd]:[new RegExp("FxiOS\\/"+we)],[ta]:[new RegExp("Konqueror[:/]?"+we,"i")],[ii]:[new RegExp(ii+" "+we),mo],[Od]:[new RegExp("android\\s"+we,"i")],[Td]:[new RegExp(Rd+"\\/"+we)],[Ud]:[new RegExp("OculusBrowser\\/"+we)],[Kr]:[new RegExp(Kr+"\\/"+we)],[Hd]:[new RegExp("YaBrowser\\/"+we)],[Yr]:[new RegExp(Yr+"\\/"+we)],[Hi]:[new RegExp(Hi+"\\/"+we)],[na]:[new RegExp("(DuckDuckGo|Ddg)\\/"+we)],[Wd]:[new RegExp("PaleMoon\\/"+we)],[Jr]:[new RegExp(Jr+"\\/"+we)],[zd]:[new RegExp("GSA\\/"+we)],[rl]:[new RegExp("(rv:|MSIE )"+we)],Mozilla:[new RegExp("rv:"+we)]},ag=function(t,e,n,i){var r=qd(t,e,n,i),s=og[r];if(C(s))return null;for(var o=0;s.length>o;o++){var a=t.match(s[o]);if(a)return parseFloat(a[a.length-2])}return null},kc=[[new RegExp(Xn+"; "+Xn+" (.*?)[);]","i"),t=>[Xn,t&&t[1]||""]],[new RegExp(Ji,"i"),[Ji,""]],[new RegExp(Zi,"i"),[Zi,""]],[al,[ii,""]],[new RegExp(Ti,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Qo,""];if(new RegExp(rt).test(e)&&!/IEMobile\b/.test(e))return[Ti+" "+rt,""];var n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){var i=sg[n[1]]||"";return/arm/i.test(e)&&(i="RT"),[Ti,i]}return[Ti,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>t&&t[3]?[Gr,[t[3],t[4],t[5]||"0"].join(".")]:[Gr,""]],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{var e="";return t&&t.length>=3&&(e=C(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+Yt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Yt+")","i"),t=>t&&t[2]?[Yt,[t[2],t[3],t[4]||"0"].join(".")]:[Yt,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{var e=["Mac OS X",""];return t&&t[1]&&(e[1]=[t[1],t[2],t[3]||"0"].join(".")),e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[Qp,""]],[/Linux|debian/i,["Linux",""]]],Cc=function(t){return rg.test(t)?Ji:ig.test(t)?Zi:ng.test(t)?Xn:new RegExp(ea,"i").test(t)?ea:new RegExp("("+Qo+"|WPDesktop)","i").test(t)?Qo:/iPad/.test(t)?Cd:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?Pd:al.test(t)?ii:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(Ic,"i").test(t)?Ic:/(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(rt).test(t)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(t)||/pixel[\daxl ]{1,6}/i.test(t)&&!/pixel c/i.test(t)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(t)||/lmy47v/i.test(t)&&!/QTAQZ3/i.test(t)?Yt:kd:new RegExp("(pda|"+rt+")","i").test(t)?tg:new RegExp(ni,"i").test(t)&&!new RegExp(ni+" pc","i").test(t)?jd:""},lg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ac(t,e){return typeof(n=t)=="string"&&lg.test(n)?t:e();var n}function fn(t){return t&&t.split("#")[0]}function ll(t,e){var n=setTimeout(t,e);return n?.unref&&n?.unref(),n}function Pc(t,e,n){return Vd.apply(this,arguments)}function Vd(){return(Vd=se((function*(t,e,n){var i;try{return yield Promise.race([t,new Promise(((r,s)=>{i=ll((()=>{try{n?.(),r()}catch(o){s(o)}}),e)}))])}finally{clearTimeout(i)}}))).apply(this,arguments)}var cg=t=>t instanceof Error,Gd={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}},ug=Gd.info;function Kd(t){if(mt(t))return{boolValue:t};if(typeof t=="number")return Number.isFinite(t)?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:{stringValue:String(t)};if(typeof t=="string")return{stringValue:t};if(U(t))return{arrayValue:{values:t.map((e=>Kd(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function Zr(t){var e=[];for(var n in t){var i=t[n];Ye(i)||C(i)||e.push({key:n,value:Kd(i)})}return e}function dg(t,e){var n=Gd[t.level||"info"]||ug,i=n.text,r=n.number,s=String(Date.now())+"000000",o={};e.distinctId&&(o.posthogDistinctId=e.distinctId),e.sessionId&&(o.sessionId=e.sessionId),e.windowId&&(o["window.id"]=e.windowId),H(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),H(e.lastActivityTimestamp)||(o.lastActivityTimestamp=String(e.lastActivityTimestamp)),e.currentUrl&&(o["url.full"]=e.currentUrl),e.screenName&&(o["screen.name"]=e.screenName),e.appState&&(o["app.state"]=e.appState),e.activeFeatureFlags&&e.activeFeatureFlags.length>0&&(o.feature_flags=e.activeFeatureFlags);var a=I({},o,t.attributes||{}),l={timeUnixNano:s,observedTimeUnixNano:s,severityNumber:r,severityText:i,body:{stringValue:t.body},attributes:Zr(a)};return t.trace_id&&(l.traceId=t.trace_id),t.span_id&&(l.spanId=t.span_id),C(t.trace_flags)||(l.flags=t.trace_flags),l}function Yd(t,e,n){return I({},t.resourceAttributes,{"service.name":t.serviceName||"unknown_service"},t.environment&&{"deployment.environment":t.environment},t.serviceVersion&&{"service.version":t.serviceVersion},{"telemetry.sdk.name":e,"telemetry.sdk.version":n})}function Jd(t,e,n,i){return{resourceLogs:[{resource:{attributes:Zr(e)},scopeLogs:[{scope:{name:n,version:i},logRecords:t}]}]}}let fg=class{constructor(t,e,n,i,r,s,o){var a;s===void 0&&(s=()=>Promise.resolve()),this._instance=t,this.Ne=e,this.rt=n,this.ut=i,this.ht=r,this.dt=s,this.vt=o,this.ct=null,this.ft=0,this.yt=0,this.bt=0,this._t=0,this.wt=!1,this.kt=e.maxBufferSize,this.xt=Math.max((a=e.maxQueueSize)!==null&&a!==void 0?a:e.maxBufferSize,e.maxBufferSize),this.St=e.flushIntervalMs,this.Ct=e.maxBatchRecordsPerPost,this.Mt=e.rateCapWindowMs,this.Tt=e.maxLogsPerInterval}reset(){this.Et(),this.ct=null,this.bt=0,this._t=0,this.wt=!1,this.ft=0,this.yt=0,this.Ct=this.Ne.maxBatchRecordsPerPost}onReconnect(){this.yt=0,this.It()}captureLog(t){if(!this._instance.isDisabled&&!this._instance.optedOut&&t!=null&&t.body){var e=this.Pt(t);if(e!==null)if(e.body){if(this.Rt()){var n={record:dg(e,this.ut())};this.ht((()=>this.At(n)))}}else this.rt.info("Log was rejected in beforeSend function")}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Log was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for log:",o),null}return i}Rt(){if(this.Tt===void 0)return!0;var t=Date.now(),e=t-this.bt;return this.Mt>e&&e>=0||(this.bt=t,this._t=0,this.wt=!1),this.Tt>this._t?(this._t++,!0):(this.wt||(this.rt.warn("captureLog dropping logs: exceeded "+this.Tt+" logs per "+this.Mt+"ms"),this.wt=!0),!1)}flush(){var t=this;return se((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return se((function*(){var e;t.Et();var n=(e=t._instance.getPersistedProperty(Ut.LogsQueue))!==null&&e!==void 0?e:[];if(n.length!==0)for(var i=n.length,r=0;n.length>0&&i>r;){var s,o;t.ft=0;var a=Math.min(n.length,t.Ct),l=n.slice(0,a),u=Jd(l.map((d=>d.record)),t.Lt(),(s=t.vt)!==null&&s!==void 0?s:t._instance.getLibraryId(),t._instance.getLibraryVersion()),c=yield t._instance.Ot(u);if(c.kind==="too-large"&&l.length>1)t.Ct=Math.max(1,Math.floor(l.length/2)),t.rt.warn("Received 413 when sending logs batch of size "+l.length+", reducing batch size to "+t.Ct);else if(c.kind==="retry-later"||(c.kind==="too-large"?t.rt.warn("Dropping a single log record after 413 with batch size 1 — the record is larger than the server cap and cannot be split further."):c.kind==="ok"&&t.Ne.maxBatchRecordsPerPost>t.Ct&&(t.Ct=Math.min(t.Ne.maxBatchRecordsPerPost,t.Ct+1)),yield t.Dt(l.length),n=(o=t._instance.getPersistedProperty(Ut.LogsQueue))!==null&&o!==void 0?o:[],r+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return se((function*(){var n,i=Math.max(0,t-e.ft),r=(n=e._instance.getPersistedProperty(Ut.LogsQueue))!==null&&n!==void 0?n:[];e._instance.setPersistedProperty(Ut.LogsQueue,r.slice(i)),yield e.dt()}))()}Lt(){return Yd(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var n=(e=this._instance.getPersistedProperty(Ut.LogsQueue))!==null&&e!==void 0?e:[];this.xt>n.length||(n.shift(),this.ft++,this.rt.info("Logs queue is full, dropping oldest record.")),n.push(t),this._instance.setPersistedProperty(Ut.LogsQueue,n),this.kt>n.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=ll((()=>{this.Nt=void 0,this.It()}),t))}qt(){var t=Math.min(Math.max(0,this.yt-1),6);return this.St*Math.pow(2,t)}jt(){var t=this._instance.getPersistedProperty(Ut.LogsQueue);return!!t&&t.length>0}shutdown(t){var e=this;return se((function*(){e.Et();var n=e.flush().catch((()=>{}));t!==void 0?yield Pc(n,t):yield n}))()}flushWithTimeout(t){var e=this;return se((function*(){var n=e.flush();yield Pc(n,t,(()=>{n.catch((()=>{}))}))}))()}It(){this.flush().then((()=>{this.yt=0}),(t=>{this.yt++,this.rt.error("PostHog logs flush failed:",t)})).finally((()=>{!this._instance.isDisabled&&this.jt()&&this.$t(this.qt())}))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}};var vo=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function Fc(t){return String(t)+"000000"}function Rc(t,e,n,i){var r="";return i&&(r=Object.keys(i).sort().map((s=>JSON.stringify(s)+":"+JSON.stringify(i[s]))).join(",")),t+"\0"+e+"\0"+(n??"")+"\0"+r}let hg=class{constructor(t,e,n){this._instance=t,this.Ne=e,this.rt=n,this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Wt=0}count(t,e,n){e===void 0&&(e=1),this.Vt({name:t,type:"count",value:e,unit:n?.unit,attributes:n?.attributes})}gauge(t,e,n){this.Vt({name:t,type:"gauge",value:e,unit:n?.unit,attributes:n?.attributes})}histogram(t,e,n){this.Vt({name:t,type:"histogram",value:e,unit:n?.unit,attributes:n?.attributes})}flush(){var t=this,e=this.ct,n=(function(){var r=se((function*(){e&&(yield e.catch((()=>{}))),yield t.Zt()}));return function(){return r.apply(this,arguments)}})(),i=n().finally((()=>{this.ct===i&&(this.ct=null)}));return this.ct=i,i}drainWindow(){if(this.Bt.size===0)return null;var t=this.Bt;return this.Bt=new Map,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Gt(t)}reset(){this.Wt++,this.Et(),this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set}Vt(t){if(!this._instance.isDisabled&&!this._instance.optedOut){var e=this.Pt(t);if(e!==null)if(e.name&&typeof e.name=="string")if(typeof e.value=="number"&&Number.isFinite(e.value))if(e.type==="count"&&0>e.value)this.rt.warn("Dropping count '"+e.name+"': counters are monotonic, value must be >= 0");else{var n,i;try{n=e.attributes?I({},e.attributes):void 0,i=Rc(e.type,e.name,e.unit,n)}catch(o){return void this.rt.warn("Dropping metric '"+e.name+"': attributes could not be serialized",o)}var r=this.Bt.get(i);if(!r){if(!this.Qt())return;r={name:e.name,type:e.type,unit:e.unit,attributes:n,windowStartMs:Date.now()},this.Bt.set(i,r)}var s=this.Ut.get(e.name);s===void 0?this.Ut.set(e.name,e.type):s===e.type||this.zt.has(e.name)||(this.zt.add(e.name),this.rt.warn("Metric name '"+e.name+"' is already used as a "+s+"; recording it as a "+e.type+" too will blend both series in charts. Use a distinct name.")),this.Kt(r,e.value),this.$t()}else this.rt.warn("Dropping metric '"+e.name+"': value must be a finite number");else this.rt.warn("Dropping metric with empty name")}}Qt(){return this.Ne.maxSeriesPerFlush>this.Bt.size||(this.Ht||(this.Ht=!0,this.rt.warn("Metric series cap reached ("+this.Ne.maxSeriesPerFlush+" per flush window); dropping new series until the next flush. Reduce attribute cardinality.")),!1)}Kt(t,e){var n;switch(t.type){case"count":t.total=((n=t.total)!==null&&n!==void 0?n:0)+e;break;case"gauge":t.last=e;break;case"histogram":t.hist||(t.hist={count:0,sum:0,min:e,max:e,bucketCounts:new Array(vo.length+1).fill(0)});var i=t.hist;i.count+=1,i.sum+=e,i.min=Math.min(i.min,e),i.max=Math.max(i.max,e),i.bucketCounts[(function(r,s){for(var o=0;s.length>o;o++)if(s[o]>=r)return o;return s.length})(e,vo)]+=1}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var n=U(e)?e:[e],i=t;for(var r of n)try{var s=r(i);if(!s)return this.rt.info("Metric was rejected in beforeSend function"),null;i=s}catch(o){return this.rt.error("Error in beforeSend function for metric:",o),null}return i}$t(){this.Nt||(this.Nt=ll((()=>{this.Nt=void 0,this.flush().catch((t=>{this.rt.error("Metrics flush failed:",t)}))}),this.Ne.flushIntervalMs))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}Zt(){var t=this;return se((function*(){if(t.Bt.size!==0){var e=t.Bt;t.Bt=new Map,t.Ht=!1,t.Ut=new Map,t.zt=new Set;var n=t.Wt,i=yield t._instance.Jt(t.Gt(e));if(n===t.Wt)switch(i.kind){case"ok":return;case"retry-later":return t.Yt(e),void t.$t();case"too-large":return void t.rt.warn("Metrics batch exceeded the server size limit and was dropped");case"fatal":return void t.rt.error("Failed to send metrics batch:",i.error)}}}))()}Gt(t){return e=this.Xt(t),n=(function(s,o,a){return I({},s.resourceAttributes,{"service.name":s.serviceName||"unknown_service"},s.environment&&{"deployment.environment":s.environment},s.serviceVersion&&{"service.version":s.serviceVersion},{"telemetry.sdk.name":o,"telemetry.sdk.version":a})})(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion()),i=this._instance.getLibraryId(),r=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:Zr(n)},scopeMetrics:[{scope:{name:i,version:r},metrics:e}]}]};var e,n,i,r}Xt(t){var e=Fc(Date.now()),n=new Map;for(var i of t.values()){var r,s=Rc(i.type,i.name,i.unit,void 0),o=n.get(s);o||(o=I({name:i.name},i.unit&&{unit:i.unit}),i.type==="count"?o.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:i.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:1,dataPoints:[]},n.set(s,o));var a=Zr((r=i.attributes)!==null&&r!==void 0?r:{}),l=Fc(i.windowStartMs);if(i.type==="count"){var u,c={attributes:a,startTimeUnixNano:l,timeUnixNano:e,asDouble:(u=i.total)!==null&&u!==void 0?u:0};o.sum.dataPoints.push(c)}else if(i.type==="gauge"){var d,f={attributes:a,timeUnixNano:e,asDouble:(d=i.last)!==null&&d!==void 0?d:0};o.gauge.dataPoints.push(f)}else i.hist&&o.histogram.dataPoints.push({attributes:a,startTimeUnixNano:l,timeUnixNano:e,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:vo})}return Array.from(n.values())}Yt(t){var e,n;for(var i of t){var r=i[0],s=i[1],o=this.Bt.get(r);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,s.windowStartMs),o.type){case"count":o.total=((e=o.total)!==null&&e!==void 0?e:0)+((n=s.total)!==null&&n!==void 0?n:0);break;case"gauge":break;case"histogram":if(s.hist)if(o.hist){o.hist.count+=s.hist.count,o.hist.sum+=s.hist.sum,o.hist.min=Math.min(o.hist.min,s.hist.min),o.hist.max=Math.max(o.hist.max,s.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=s.hist.bucketCounts[a]}else o.hist=s.hist}else this.Qt()&&this.Bt.set(r,s)}}};var _r,Tc,_o;function pg(t){var e=globalThis._posthogChunkIds;if(e){var n=Object.keys(e);return _o&&n.length===Tc||(Tc=n.length,_o=n.reduce(((i,r)=>{_r||(_r={});var s=_r[r];if(s)i[s[0]]=s[1];else for(var o=t(r),a=o.length-1;a>=0;a--){var l=o[a],u=l?.filename,c=e[r];if(u&&c){i[u]=c,_r[r]=[u,c];break}}return i}),{})),_o}}class gg{constructor(e,n,i){i===void 0&&(i=[]),this.coercers=e,this.stackParser=n,this.modifiers=i}buildFromUnknown(e,n){n===void 0&&(n={});var i=n&&n.mechanism||{handled:!0,type:"generic"},r=this.buildCoercingContext(i,n,0).apply(e),s=this.buildParsingContext(n),o=this.parseStacktrace(r,s);return{$exception_list:this.convertToExceptionList(o,i),$exception_level:"error"}}modifyFrames(e){var n=this;return se((function*(){for(var i of e)i.stacktrace&&i.stacktrace.frames&&U(i.stacktrace.frames)&&(i.stacktrace.frames=yield n.applyModifiers(i.stacktrace.frames));return e}))()}coerceFallback(e){var n;return{type:"Error",value:"Unknown error",stack:(n=e.syntheticException)==null?void 0:n.stack,synthetic:!0}}parseStacktrace(e,n){var i,r;return e.cause!=null&&(i=this.parseStacktrace(e.cause,n)),e.stack!=""&&e.stack!=null&&(r=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?n.skipFirstLines:0),n.chunkIdMap)),I({},e,{cause:i,stack:r})}applyChunkIds(e,n){return e.map((i=>(i.filename&&n&&(i.chunk_id=n[i.filename]),i)))}applyCoercers(e,n){for(var i of this.coercers)if(i.match(e))return i.coerce(e,n);return this.coerceFallback(n)}applyModifiers(e){var n=this;return se((function*(){var i=e;for(var r of n.modifiers)i=yield r(i);return i}))()}convertToExceptionList(e,n){var i,r,s,o={type:e.type,value:e.value,mechanism:{type:(i=n.type)!==null&&i!==void 0?i:"generic",handled:(r=n.handled)===null||r===void 0||r,synthetic:(s=e.synthetic)!==null&&s!==void 0&&s}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,I({},n,{handled:!0}))),a}buildParsingContext(e){var n;return{chunkIdMap:pg(this.stackParser),skipFirstLines:(n=e.skipFirstLines)!==null&&n!==void 0?n:1}}buildCoercingContext(e,n,i){i===void 0&&(i=0);var r=(s,o)=>{if(4>=o){var a=this.buildCoercingContext(e,n,o);return this.applyCoercers(s,a)}};return I({},n,{syntheticException:i==0?n.syntheticException:void 0,mechanism:e,apply:s=>r(s,i),next:s=>r(s,i+1)})}}var ri="?";function ia(t,e,n,i,r){var s={platform:t,filename:e,function:n===""?ri:n,in_app:!0};return C(i)||(s.lineno=i),C(r)||(s.colno=r),s}var Zd=(t,e)=>{var n=t.indexOf("safari-extension")!==-1,i=t.indexOf("safari-web-extension")!==-1;return n||i?[t.indexOf("@")!==-1?t.split("@")[0]:ri,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},mg=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,vg=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,_g=/\((\S*)(?::(\d+))(?::(\d+))\)/,yg=(t,e)=>{var n=mg.exec(t);if(n)return ia(e,n[1],ri,+n[2],+n[3]);var i=vg.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var r=_g.exec(i[2]);r&&(i[2]=r[1],i[3]=r[2],i[4]=r[3])}var s=Zd(i[1]||ri,i[2]);return ia(e,s[1],s[0],i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},wg=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,bg=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Eg=(t,e)=>{var n=wg.exec(t);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){var i=bg.exec(n[3]);i&&(n[1]=n[1]||"eval",n[3]=i[1],n[4]=i[2],n[5]="")}var r=n[3],s=n[1]||ri,o=Zd(s,r);return ia(e,r=o[1],s=o[0],n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},$c=/\(error: (.*)\)/;class Sg{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,n){var i=X(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:i?e.stack:void 0,cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var n=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?n+": "+e.message:n}isDOMException(e){return Vr(e,"DOMException")}isDOMError(e){return Vr(e,"DOMError")}}class xg{match(e){return(function(n){switch({}.toString.call(n)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return Id(n,Error)}})(e)}coerce(e,n){return{type:this.getType(e),value:this.getMessage(e,n),stack:this.getStack(e),cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,n){var i=e.message;return String(i.error&&typeof i.error.message=="string"?i.error.message:i)}getStack(e){return e.stacktrace||e.stack||void 0}}class Ig{constructor(){}match(e){return!!Vr(e,"ErrorEvent")&&(e.error!=null||this.fe(e))}coerce(e,n){var i;if(e.error!=null)return n.apply(e.error);var r=n.apply(e.message);return I({},r,{stack:(i=this.pe(e))!==null&&i!==void 0?i:r.stack,synthetic:!0})}fe(e){return X(e.message)&&e.message.length>0}pe(e){var n=e;if(X(n.filename)&&n.filename.length>0){var i,r,s=(i=n.lineno)!==null&&i!==void 0?i:0,o=(r=n.colno)!==null&&r!==void 0?r:0;return`Error + at `+n.filename+":"+s+":"+o}}}var kg=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class Cg{match(e){return typeof e=="string"}coerce(e,n){var i,r=this.getInfos(e),s=r[0],o=r[1];return{type:s??"Error",value:o??e,stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}getInfos(e){var n="Error",i=e,r=e.match(kg);return r&&(n=r[1],i=r[2]),[n,i]}}var Ag=["fatal","error","warning","log","info","debug"];function Xd(t,e){e===void 0&&(e=40);var n=Object.keys(t);if(n.sort(),!n.length)return"[object has no keys]";for(var i=n.length;i>0;i--){var r=n.slice(0,i).join(", ");if(e>=r.length)return i===n.length?r:r.length>e?r.slice(0,e)+"...":r}return""}class Pg{match(e){return typeof e=="object"&&e!==null}coerce(e,n){var i,r,s=this.getErrorPropertyFromObject(e);return s?n.apply(s):{type:this.getType(e),value:this.getValue(e),stack:(i=this.getStack(e))!==null&&i!==void 0?i:(r=n.syntheticException)==null?void 0:r.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return il(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var n="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(n+=" with message: '"+e.message+"'"),n}if("message"in e&&typeof e.message=="string")return e.message;var i=this.getObjectClassName(e);return(i&&i!=="Object"?"'"+i+"'":"Object")+" captured as exception with keys: "+Xd(e)}isSeverityLevel(e){return X(e)&&!Xo(e)&&Ag.indexOf(e)>=0}getStack(e){try{return X(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:X(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(var n in e)if({}.hasOwnProperty.call(e,n)){var i=e[n];if(cg(i))return i}}getObjectClassName(e){try{var n=Object.getPrototypeOf(e);return n?n.constructor.name:void 0}catch{return}}}class Fg{match(e){return il(e)}coerce(e,n){var i,r=e.constructor.name;return{type:r,value:r+" captured as exception with keys: "+Xd(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class Rg{match(e){return xd(e)}coerce(e,n){var i;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class Tg{match(e){return Vr(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!il(e))return!1;try{var n=e.detail;return n!=null&&typeof n=="object"&&"reason"in n}catch{return!1}}coerce(e,n){var i,r=this.getUnhandledRejectionReason(e);return xd(r)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(r),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}:n.apply(r)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}}var Xr="$message",Qr="$timestamp",$g=new Set([Xr,Qr]),yo={enabled:!0,max_bytes:32768};function es(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:yo.enabled,max_bytes:Lg(t.max_bytes,yo.max_bytes)}:I({},yo)}class Mg{constructor(e){this.Ke=[],this.Je=0,this.Ne=es(e)}setConfig(e){this.Ne=es(e),this.Xe()}add(e){var n=(function(r){var s;try{s=bd(r)}catch{return}try{var o=JSON.parse(s);if(!he(o))return;var a=o,l=a[Xr],u=a[Qr];return!X(l)||l.trim().length===0||!X(u)&&!ke(u)?void 0:{step:a,json:s}}catch{return}})(e);if(n){var i=(function(r){if(typeof TextEncoder<"u")return new TextEncoder().encode(r).length;for(var s=encodeURIComponent(r),o=0,a=0;s.length>a;a++)s[a]==="%"?(o+=1,a+=2):o+=1;return o})(n.json);i>this.Ne.max_bytes||(this.Ke.push({step:n.step,bytes:i}),this.Je+=i,this.Xe())}}getAttachable(){return this.Ke.map((e=>e.step))}clear(){this.Ke=[],this.Je=0}size(){return this.Ke.length}Xe(){for(;this.Je>this.Ne.max_bytes&&this.Ke.length>0;){var e=this.Ke.shift();e&&(this.Je-=e.bytes)}}}function Lg(t,e){if(!ke(t)||t===1/0||t===-1/0)return e;var n=Math.floor(t);return 0>n?e:n}var Qd=function(t,e){var n=(e===void 0?{}:e).debugEnabled,i={k(r){if(w&&(ne.DEBUG||w.POSTHOG_DEBUG||n)&&!C(w.console)&&w.console){for(var s=("__rrweb_original__"in w.console[r])?w.console[r].__rrweb_original__:w.console[r],o=arguments.length,a=new Array(o>1?o-1:0),l=1;o>l;l++)a[l-1]=arguments[l];s(t,...a)}},debug(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("debug",...s)},info(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("log",...s)},warn(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("warn",...s)},error(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];i.k("error",...s)},critical(){for(var r=arguments.length,s=new Array(r),o=0;r>o;o++)s[o]=arguments[o];console.error(t,...s)},uninitializedWarning(r){i.error("You must initialize PostHog before calling "+r)},createLogger:(r,s)=>Qd(t+" "+r,s)};return i},A=Qd("[PostHog.js]"),pe=A.createLogger,Ng=pe("[ExternalScriptsLoader]"),wo=(t,e,n)=>{if(t.config.disable_external_dependency_loading)return Ng.warn(e+" was requested but loading of external scripts is disabled."),n("Loading of external scripts is disabled");var i=P?.querySelectorAll("script");if(i){for(var r,s=function(){if(i[o].src===e){var l=i[o];return l.__posthog_loading_callback_fired?{v:n()}:(l.addEventListener("load",(u=>{l.__posthog_loading_callback_fired=!0,n(void 0,u)})),l.onerror=u=>n(u),{v:void 0})}},o=0;i.length>o;o++)if(r=s())return r.v}var a=()=>{if(!P)return n("document not found");var l=P.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=d=>{l.__posthog_loading_callback_fired=!0,n(void 0,d)},l.onerror=d=>n(d),t.config.prepare_external_dependency_script&&(l=t.config.prepare_external_dependency_script(l)),!l)return n("prepare_external_dependency_script returned null");if(t.config.external_scripts_inject_target==="head")P.head.appendChild(l);else{var u,c=P.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):P.body.appendChild(l)}};P!=null&&P.body?a():P?.addEventListener("DOMContentLoaded",a)};B.__PosthogExtensions__=B.__PosthogExtensions__||{},B.__PosthogExtensions__.loadExternalDependency=(t,e,n)=>{if(e!=="remote-config"){var i;if(t.config.strict_script_versioning)i=t.requestRouter.endpointFor("assets","/static/"+t.version+"/"+e+".js");else{var r="/static/"+e+".js?v="+t.version;if(e==="toolbar"){var s=3e5;r=r+"&t="+Math.floor(Date.now()/s)*s}i=t.requestRouter.endpointFor("assets",r)}wo(t,i,n)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");wo(t,o,n)}},B.__PosthogExtensions__.loadSiteApp=(t,e,n)=>{var i=t.requestRouter.endpointFor("api",e);wo(t,i,n)};ne.DEBUG=!1,ne.LIB_VERSION="1.415.7",ne.LIB_NAME="web";var ef="$people_distinct_id",Xi="$device_id",bo="$device_model",$i="__alias",Mi="__timers",ra="$autocapture_disabled_server_side",sa="$heatmaps_enabled_server_side",oa="$exception_capture_enabled_server_side",aa="$error_tracking_suppression_rules",la="$error_tracking_capture_extension_exceptions",ca="$web_vitals_enabled_server_side",cl="$dead_clicks_enabled_server_side",ul="$product_tours_enabled_server_side",ua="$web_vitals_allowed_metrics",An="$session_recording_remote_config",tf="$replay_sample_rate",nf="$replay_override_sampling",rf="$replay_override_linked_flag",sf="$replay_override_url_trigger",of="$replay_override_event_trigger",Kn="$sesid",dl="$session_is_sampled",Sn="$enabled_feature_flags",Li="$active_feature_flags",Rr="$early_access_features",da="$feature_flag_details",Ni="$feature_flag_payloads",Tr="$feature_flag_request_id",ts="$minimal_flag_called_events",It="$override_feature_flags",xn="$override_feature_flag_payloads",jt="$stored_person_properties",In="$stored_group_properties",fa="$surveys",ns="$surveys_loaded_at",ha="$surveys_activated",$r="$surveys_activated_session",Mr="$surveys_activated_timestamps",Oi="ph_product_tours",Cn="$flag_call_reported",Bi="$flag_call_reported_session_id",Lr="$feature_flag_errors",Wi="$feature_flag_evaluated_at",at="$user_state",pa="$client_session_props",ga="$capture_rate_limit",ma="$initial_campaign_params",va="$initial_referrer_info",is="$initial_person_info",rs="$epp",yr="$posthog_cookieless",af="$cookieless_mode",lf="$sdk_debug_extensions_init_method",cf="$sdk_debug_extensions_init_time_ms",uf="$sdk_debug_recording_script_not_loaded",fl="PostHog loadExternalDependency extension not found.",kn="on_reject",Wt="always",Un="anonymous",vn="identified",_a="identified_only",ss="visibilitychange",os="beforeunload",Vn="$pageview",Eo="$pageleave",So="$identify",Mc="$groupidentify";function wr(t,e){U(t)&&t.forEach(e)}function ie(t,e){if(!H(t))if(U(t))t.forEach(e);else if(Gp(t))t.forEach(((i,r)=>e(i,r)));else for(var n in t)Sd.call(t,n)&&e(t[n],n)}var fe=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;e>i;i++)n[i-1]=arguments[i];for(var r of n)for(var s in r)r[s]!==void 0&&(t[s]=r[s]);return t};function Nr(t){for(var e=Object.keys(t),n=e.length,i=new Array(n);n--;)i[n]=[e[n],t[e[n]]];return i}var Lc=function(t){try{return t()}catch{return}},Og=function(t){return function(){try{for(var e=arguments.length,n=new Array(e),i=0;e>i;i++)n[i]=arguments[i];return t.apply(this,n)}catch(r){A.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),A.critical(r)}}},hl=function(t){var e={};return ie(t,(function(n,i){(X(n)&&n.length>0||ke(n))&&(e[i]=n)})),e},Bg=["herokuapp.com","vercel.app","netlify.app"];function Dg(t){var e=t?.hostname;if(!X(e))return!1;var n=e.split(".").slice(-2).join(".");for(var i of Bg)if(n===i)return!1;return!0}function ve(t,e,n,i){var r=i??{},s=r.capture,o=r.passive;t?.addEventListener(e,n,{capture:s!==void 0&&s,passive:o===void 0||o})}function ya(t){return t.name==="ph_toolbar_internal"}var df=t=>{if(P){try{for(var e=t+"=",n=P.cookie.split(";").filter((s=>s.length)),i=0;n.length>i;i++){for(var r=n[i];r.charAt(0)==" ";)r=r.substring(1,r.length);if(r.indexOf(e)===0)return decodeURIComponent(r.substring(e.length,r.length))}}catch{}return null}};Math.trunc||(Math.trunc=function(t){return 0>t?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return ke(t)&&isFinite(t)&&Math.floor(t)===t});class as{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,n,i,r){if(!Number.isInteger(e)||!Number.isInteger(n)||!Number.isInteger(i)||!Number.isInteger(r)||0>e||0>n||0>i||0>r||e>0xffffffffffff||n>4095||i>1073741823||r>4294967295)throw new RangeError("invalid field value");var s=new Uint8Array(16);return s[0]=e/Math.pow(2,40),s[1]=e/Math.pow(2,32),s[2]=e/Math.pow(2,24),s[3]=e/Math.pow(2,16),s[4]=e/256,s[5]=e,s[6]=112|n>>>8,s[7]=n,s[8]=128|i>>>24,s[9]=i>>>16,s[10]=i>>>8,s[11]=i,s[12]=r>>>24,s[13]=r>>>16,s[14]=r>>>8,s[15]=r,new as(s)}toString(){for(var e="",n=0;this.bytes.length>n;n++)e=e+(this.bytes[n]>>>4).toString(16)+(15&this.bytes[n]).toString(16),n!==3&&n!==5&&n!==7&&n!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new as(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var n=0;16>n;n++){var i=this.bytes[n]-e.bytes[n];if(i!==0)return Math.sign(i)}return 0}}class jg{generate(){var e=this.generateOrAbort();if(!C(e))return e;this.S=0;var n=this.generateOrAbort();if(C(n))throw new Error("Could not generate UUID after timestamp reset");return n}generateOrAbort(){var e=Date.now();if(e>this.S)this.S=e,this.C();else{if(this.S>=e+1e4)return;this.I++,this.I>4398046511103&&(this.S++,this.C())}return as.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 Ug}}var Nc,ff=t=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;t.length>e;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};w&&!C(w.crypto)&&crypto.getRandomValues&&(ff=t=>crypto.getRandomValues(t));class Ug{nextUint32(){return this.R.length>this.O||(ff(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var Ht=()=>Hg().toString(),Hg=()=>(Nc||(Nc=new jg)).generate(),Ei="",Wg=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,zt={N:()=>!!P,j(t){A.error("cookieStore error: "+t)},P:df,H(t){var e;try{e=JSON.parse(zt.P(t))||{}}catch{}return e},F(t,e,n,i,r){if(!P)return!1;try{var s="",o="",a=(function(c,d){if(d){var f=(function(p,g){if(g===void 0&&(g=P),Ei)return Ei;if(!g||["localhost","127.0.0.1"].includes(p))return"";for(var m=p.split("."),v=Math.min(m.length,8),E="dmn_chk_"+Ht();!Ei&&v--;){var S=m.slice(v).join("."),_=E+"=1;domain=."+S+";path=/";g.cookie=_+";max-age=3",g.cookie.includes(E)&&(g.cookie=_+";max-age=0",Ei=S)}return Ei})(c);if(!f){var h=(p=>{var g=p.match(Wg);return g?g[0]:""})(c);h!==f&&A.info("Warning: cookie subdomain discovery mismatch",h,f),f=h}return f?"; domain=."+f:""}return""})(P.location.hostname,i);if(n){var l=new Date;l.setTime(l.getTime()+864e5*n),s="; expires="+l.toUTCString()}r&&(o="; secure");var u=t+"="+encodeURIComponent(JSON.stringify(e))+s+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&A.warn("cookieStore warning: large cookie, len="+u.length),P.cookie=u,!0}catch{return!1}},q(t,e){if(P!=null&&P.cookie)try{zt.F(t,"",-1,e)}catch{return}}},xo=null,le={N(){if(!Ye(xo))return xo;var t=!0;if(C(w))t=!1;else try{var e="__mplssupport__";le.F(e,"xyz"),le.P(e)!=='"xyz"'&&(t=!1),le.q(e)}catch{t=!1}return t||A.error("localStorage unsupported; falling back to cookie store"),xo=t,t},j(t){A.error("localStorage error: "+t)},P(t){try{return w?.localStorage.getItem(t)}catch(e){le.j(e)}return null},H(t){try{return JSON.parse(le.P(t))||{}}catch{}return null},F(t,e){try{return w?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(n){le.j(n)}return!1},q(t){try{w?.localStorage.removeItem(t)}catch(e){le.j(e)}}},zg=[Xi,"distinct_id",Kn,dl,rs,is,at],br={},qg={N:()=>!0,j(t){A.error("memoryStorage error: "+t)},P:t=>br[t]||null,H:t=>br[t]||null,F:(t,e)=>(br[t]=e,!0),q(t){delete br[t]}},_n=null,be={N(){if(!Ye(_n))return _n;if(_n=!0,C(w))_n=!1;else try{var t="__support__";be.F(t,"xyz"),be.P(t)!=='"xyz"'&&(_n=!1),be.q(t)}catch{_n=!1}return _n},j(t){A.error("sessionStorage error: ",t)},P(t){try{return w?.sessionStorage.getItem(t)}catch(e){be.j(e)}return null},H(t){try{return JSON.parse(be.P(t))||null}catch{}return null},F(t,e){try{return w?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(n){be.j(n)}return!1},q(t){try{w?.sessionStorage.removeItem(t)}catch(e){be.j(e)}}};class Vg{constructor(e){this._instance=e}get Ne(){return this._instance.config}get consent(){return this.ti()?0:this.ei}isOptedOut(){return this.Ne.cookieless_mode===Wt||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===kn}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===0}isRejected(){return this.consent===0||this.consent===-1&&this.Ne.opt_out_capturing_by_default}optInOut(e){this.ii.F(this.ri,e?1:0,this.Ne.cookie_expiration,this.Ne.cross_subdomain_cookie,this.Ne.secure_cookie)}reset(){this.ii.q(this.ri,this.Ne.cross_subdomain_cookie)}get ri(){var e=this._instance.config,n=e.token,i=e.opt_out_capturing_cookie_prefix;return e.consent_persistence_name||(i?i+n:"__ph_opt_in_out_"+n)}get ei(){var e=this.ii.P(this.ri);return go(e)?1:j(Zp,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,n=e==="localStorage"?le:zt;if(!this.ni||this.ni!==n){this.ni=n;var i=e==="localStorage"?zt:le;i.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(go(i.P(this.ri))),i.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[He?.doNotTrack,He?.msDoNotTrack,B.doNotTrack].some((e=>go(e)))}}function hf(t,e){var n,i=t==null||(n=t.config)==null?void 0:n.get_current_url;if(!je(i))return e;try{var r=i(e);return X(r)&&r?r:e}catch(s){return A.error("Error in get_current_url, falling back to window.location.href",s),e}}var pf="__POSTHOG_TOOLBAR__",Gg=1,Kg=3,Yg=11;function Oc(t){return t instanceof Element&&(t.id===pf||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function hn(t){return!!t&&t.nodeType===Gg}function et(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function gf(t){return!!t&&t.nodeType===Kg}function mf(t){return!!t&&t.nodeType===Yg&&hn(t.host)}var vf=1e3;function pl(t){return t?As(t).split(/\s+/):[]}function Bc(t,e){var n=(function(i){var r,s=w==null||(r=w.location)==null?void 0:r.href;return C(s)?void 0:hf(i,s)})(e);return!!(n&&t&&t.some((i=>n.match(i))))}function ls(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 pl(e)}function _f(t){return H(t)?null:As(t).split(/(\s+)/).filter((e=>zi(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function Qi(t){var e="";return ba(t)&&!Ef(t)&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;gf(n)&&n.textContent&&(e+=(i=_f(n.textContent))!==null&&i!==void 0?i:"")})),As(e)}function Io(t){var e;return C(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var gl=["a","button","form","input","select","textarea","label"];function wa(t,e){if(C(e))return!0;var n,i=function(s){if(e.some((o=>(function(a,l){var u=a.matches||a.matchesSelector||a.msMatchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.oMatchesSelector;try{return!!u&&u.call(a,l)}catch{return!1}})(s,o))))return{v:!0}};for(var r of t)if(n=i(r))return n.v;return!1}function yf(t){var e=t.parentNode;return!(!e||!hn(e))&&e}var Jg=[".ph-no-autocapture","[data-ph-no-autocapture]"],wf=["next","previous","prev",">","<"],Zg=[...wf,"+","-","−","–"],Dc=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,jc=[".ph-no-rageclick",".ph-no-capture"],Xg=["","text","search","email","password","url","tel","number"];function Uc(t,e){if(!w||ml(t))return!1;var n,i,r,s,o;if(mt(e)?(n=!!e&&jc,i=void 0,r=!1):(n=(s=e?.css_selector_ignorelist)!==null&&s!==void 0?s:jc,i=e?.content_ignorelist,r=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),n===!1||r&&(function(l){return!(!l||!hn(l))&&(!!et(l,"textarea")||(et(l,"input")?j(Xg,(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=bf(t,!1).targetElementList;return!(function(l,u){if(l===!1||C(l))return!1;var c;if(l===!0)c=wf;else{if(!U(l))return!1;if(l.length>10)return A.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var f=d.safeText,h=d.ariaLabel;return c.some((p=>Dc(f,p)||Dc(h,p)))}))})(i,a.map((l=>{var u;return{safeText:Qi(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!wa(a,n)}var ml=t=>!t||et(t,"html")||!hn(t),bf=(t,e)=>{if(!w||ml(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,i=[t],r=t;r.parentNode&&!et(r,"body");)if(mf(r.parentNode))i.push(r.parentNode.host),r=r.parentNode.host;else{var s=yf(r);if(!s)break;if(e||gl.indexOf(s.tagName.toLowerCase())>-1)n=!0;else try{var o=w.getComputedStyle(s);o&&o.getPropertyValue("cursor")==="pointer"&&(n=!0)}catch{}i.push(s),r=s}return{parentIsUsefulElement:n,targetElementList:i}};function ba(t){for(var e=new Set,n=0,i=t;i.parentNode&&!et(i,"body");i=i.parentNode){if(n++>=vf||e.has(i))return!1;e.add(i);var r=ls(i);if(j(r,"ph-sensitive")||j(r,"ph-no-capture"))return!1}if(j(ls(t),"ph-include"))return!0;var s=t.type||"";if(X(s))switch(s.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!X(o)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(o.replace(/[^a-zA-Z0-9]/g,""))}function Ef(t){return!!(et(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||et(t,"select")||et(t,"textarea")||t.getAttribute("contenteditable")==="true")}var Hc=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}))$"),Wc=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,Qg=[16,15,14,13],em=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),zc=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),qc=/[0-9A-Za-z_]/;function tm(t){for(var e=0,n=!1,i=t.length-1;i>=0;i--){var r=t.charCodeAt(i)-48;n&&(r*=2)>9&&(r-=9),e+=r,n=!n}return e%10==0}function zi(t,e){if(e===void 0&&(e=!0),H(t))return!1;if(X(t)){t=As(t);var n=e?Hc.test((t||"").replace(/[- ]/g,"")):(function(r){var s;for(Wc.lastIndex=0;s=Wc.exec(r);){var o=s[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of Qg){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(Hc.test(d)&&tm(d))return!0}}}return!1})(t);if(n)return!1;var i=e?em.test(t):(function(r){var s;for(zc.lastIndex=0;s=zc.exec(r);){var o=s[1],a=s[3];if(!(o&&a&&qc.test(o)&&qc.test(a)))return!0}return!1})(t);if(i)return!1}return!0}function Vc(t){var e=Qi(t);return zi(e=(e+" "+Sf(t)).trim())?e:""}function Sf(t){var e="";return t&&t.childNodes&&t.childNodes.length&&ie(t.childNodes,(function(n){var i;if(n&&((i=n.tagName)==null?void 0:i.toLowerCase())==="span")try{var r=Qi(n);e=(e+" "+r).trim(),n.childNodes&&n.childNodes.length&&(e=(e+" "+Sf(n)).trim())}catch(s){A.error("[AutoCapture]",s)}})),e}function Gc(t){return t.replace(/"|\\"/g,'\\"')}function nm(t){var e=t.attr__class;if(e)return U(e)?e:pl(e)}var Er=pe("[Dead Clicks]"),im=()=>!0,rm=t=>{var e,n=!((e=t.instance.persistence)==null||!e.get_property(cl)),i=t.instance.config.capture_dead_clicks;return mt(i)?i:!!he(i)||n};class Kc{get lazyLoadedDeadClicksAutocapture(){return this.si}constructor(e,n,i){this.instance=e,this.isEnabled=n,this.onCapture=i,this.startIfEnabledOrStop()}onRemoteConfig(e){if(e.ok){var n=e.config;"captureDeadClicks"in n&&(this.instance.persistence&&this.instance.persistence.register({[cl]:n.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var n,i;(n=B.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture?e():(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"dead-clicks-autocapture",(r=>{r?Er.error("failed to load script",r):e()}))}oi(){var e;if(P){if(!this.si&&(e=B.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var n=he(this.instance.config.capture_dead_clicks)?I({},this.instance.config.capture_dead_clicks):{};n.__onCapture=this.onCapture,this.onCapture&&(n.capture_dead_swipes=!1),this.si=B.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.si.start(P),Er.info("starting...")}}else Er.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,Er.info("stopping..."))}}var ko=pe("[SegmentIntegration]"),xf="posthog-js";function If(t,e){var n=e===void 0?{}:e,i=n.organization,r=n.projectId,s=n.prefix,o=n.severityAllowList,a=o===void 0?["error"]:o,l=n.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,f,h,p,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var v,E=((d=c.exception)==null?void 0:d.values)||[],S=E.map((b=>I({},b,{stacktrace:b.stacktrace?I({},b.stacktrace,{type:"raw",frames:(b.stacktrace.frames||[]).map((k=>I({},k,{platform:"web:javascript"})))}):void 0}))),_={$exception_message:((f=E[0])==null?void 0:f.value)||c.message,$exception_type:(h=E[0])==null?void 0:h.type,$exception_level:c.level,$exception_list:S,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((p=E[0])==null?void 0:p.value)||c.message,$sentry_exception_type:(g=E[0])==null?void 0:g.type,$sentry_tags:c.tags};return i&&r&&(_.$sentry_url=(s||"https://sentry.io/organizations/")+i+"/issues/?project="+r+"&query="+c.event_id),u&&((v=t.exceptions)==null||v.sendExceptionEvent(_)),c}}class sm{constructor(e,n,i,r,s,o){this.name=xf,this.setupOnce=function(a){a(If(e,{organization:n,projectId:i,prefix:r,severityAllowList:s,sendExceptionsToPostHog:o==null||o}))}}}class Yc{constructor(e){this.li=(n,i,r)=>{r&&(r.noSessionId||r.activityTimeout||r.sessionPastMaximumLength||r.crossTabAdoption)&&(A.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:n,changeReason:r}),this.ui=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.hi()}hi(){var e;this.di=(e=this._instance.sessionManager)==null?void 0:e.onSessionId(this.li)}destroy(){var e;(e=this.di)==null||e.call(this),this.di=void 0}doPageView(e,n){var i,r=this.vi(e,n);return this.ui={pathname:(i=w?.location.pathname)!==null&&i!==void 0?i:"",pageViewId:n,timestamp:e},this._instance.scrollManager.resetContext(),r}doPageLeave(e){var n;return this.vi(e,(n=this.ui)==null?void 0:n.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.ui)==null?void 0:e.pageViewId}}vi(e,n){var i=this.ui;if(!i)return{$pageview_id:n};var r={$pageview_id:n,$prev_pageview_id:i.pageViewId},s=this._instance.scrollManager.getContext();if(s&&!this._instance.config.disable_scroll_properties){var o=s.maxScrollHeight,a=s.lastScrollY,l=s.maxScrollY,u=s.maxContentHeight,c=s.lastContentY,d=s.maxContentY;if(!(C(o)||C(a)||C(l)||C(u)||C(c)||C(d))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),d=Math.ceil(d);var f=o>1?At(a/o,0,1,A):1,h=o>1?At(l/o,0,1,A):1,p=u>1?At(c/u,0,1,A):1,g=u>1?At(d/u,0,1,A):1;r=fe(r,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:f,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:h,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:p,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return i.pathname&&(r.$prev_pageview_pathname=i.pathname),i.timestamp&&(r.$prev_pageview_duration=(e.getTime()-i.timestamp.getTime())/1e3),r}}var Co=["flags","surveys"],om={[ef]:{exposure:"hidden"},[$i]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[Mi]:{exposure:"hidden"},[ra]:{exposure:"event"},[sa]:{exposure:"hidden"},[oa]:{exposure:"event"},[aa]:{exposure:"hidden"},[la]:{exposure:"event"},[ca]:{exposure:"event"},[cl]:{exposure:"event"},[ul]:{exposure:"hidden"},[ua]:{exposure:"event"},[An]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[Kn]:{exposure:"hidden"},[dl]:{exposure:"event"},[tf]:{exposure:"event",shouldSkipFromEventProperties:t=>Ye(t)},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},$sess_rec_flush_size:{exposure:"hidden"},[Sn]:{exposure:"hidden",storageGroup:"flags"},[Li]:{exposure:"hidden",storageGroup:"flags"},[Rr]:{exposure:"hidden"},[da]:{exposure:"hidden",storageGroup:"flags"},[Ni]:{exposure:"hidden",storageGroup:"flags"},[Tr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[ts]:{exposure:"hidden",storageGroup:"flags"},[It]:{exposure:"hidden"},[xn]:{exposure:"hidden"},[jt]:{exposure:"hidden"},[In]:{exposure:"hidden"},[fa]:{exposure:"hidden",storageGroup:"surveys"},[ns]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[ha]:{exposure:"event"},[$r]:{exposure:"hidden"},[Mr]:{exposure:"hidden"},[Oi]:{exposure:"hidden"},$product_tours_activated:{exposure:"hidden"},$product_tours_activated_session:{exposure:"hidden"},$conversations_widget_session_id:{exposure:"event"},$conversations_ticket_id:{exposure:"event"},$conversations_widget_state:{exposure:"event"},$conversations_user_traits:{exposure:"event"},[Cn]:{exposure:"hidden"},[Bi]:{exposure:"hidden"},[Lr]:{exposure:"hidden"},[Wi]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[at]:{exposure:"hidden"},[pa]:{exposure:"hidden"},[ga]:{exposure:"hidden"},[ma]:{exposure:"hidden"},[va]:{exposure:"hidden"},[is]:{exposure:"hidden"},[rs]:{exposure:"hidden"},[nf]:{exposure:"event"},[rf]:{exposure:"event"},[sf]:{exposure:"event"},[of]:{exposure:"event"},[lf]:{exposure:"event"},[cf]:{exposure:"event"},[uf]:{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"}},am=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],yn=t=>{var e=om[t];if(e)return e;for(var n of am){var i=n[1];if(t.indexOf(n[0])===0)return i}},Yn=(t,e)=>{try{return JSON.stringify(t,((n,i)=>typeof i=="bigint"?i.toString():i),e)}catch{return bd(t)}},cs=t=>{var e=P?.createElement("a");return C(e)?null:(e.href=t,e)},si=function(t,e){for(var n,i=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),r=0;i.length>r;r++){var s=i[r].split("=");if(s[0]===e){n=s;break}}if(!U(n)||2>n.length)return"";var o=n[1];try{o=decodeURIComponent(o)}catch{A.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},er=function(t,e,n){if(!t||!e||!e.length)return t;for(var i=t.split("#"),r=i[1],s=(i[0]||"").split("?"),o=s[1],a=s[0],l=(o||"").split("&"),u=[],c=0;l.length>c;c++){var d=l[c].split("=");U(d)&&(e.includes(d[0])?u.push(d[0]+"="+n):u.push(l[c]))}var f=a;return o!=null&&(f+="?"+u.join("&")),r!=null&&(f+="#"+r),f},us=function(t,e){var n=t.match(new RegExp(e+"=([^&]*)"));return n?n[1]:null},kf=(t,e)=>t>=e&&_d(),Cf=(t,e,n,i)=>{if(t===0){if(_d()){var r=e+1;return r===n&&i(),r}return e}return 0},Sr="https?://(.*)",oi=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],lm=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...oi],tr="",cm=["li_fat_id"];function Af(t,e,n){if(!P)return{};var i,r=e?[...oi,...n||[]]:[],s=Pf(er(P.URL,r,tr),t),o=(i={},ie(cm,(function(a){var l=df(a);i[a]=l||null})),i);return fe(o,s)}function Pf(t,e){var n=lm.concat(e||[]),i={};return ie(n,(function(r){var s=si(t,r);i[r]=s||null})),i}function Ff(t){var e=(function(s){return s?s.search(Sr+"google.([^/?]*)")===0?"google":s.search(Sr+"bing.com")===0?"bing":s.search(Sr+"yahoo.com")===0?"yahoo":s.search(Sr+"duckduckgo.com")===0?"duckduckgo":null:null})(t),n=e!="yahoo"?"q":"p",i={};if(!Ye(e)){i.$search_engine=e;var r=P?si(P.referrer,n):"";r.length&&(i.ph_keyword=r)}return i}function Jc(){return navigator.language||navigator.userLanguage}var ds="$direct";function Rf(){return P?.referrer||ds}function Tf(t,e,n){n===void 0&&(n=!1);var i=t?[...oi,...e||[]]:[],r=n?fn(me?.href):me?.href,s=r?.substring(0,1e3);return{r:Rf().substring(0,1e3),u:s?er(s,i,tr):void 0}}function $f(t,e){var n;e===void 0&&(e=!1);var i=t.r,r=t.u,s=e?fn(r):r,o={$referrer:i,$referring_domain:i==null?void 0:i==ds?ds:(n=cs(i))==null?void 0:n.host};if(s){o.$current_url=s;var a=cs(s);o.$host=a?.host,o.$pathname=a?.pathname;var l=Pf(s);fe(o,l)}if(i){var u=Ff(i);fe(o,u)}return o}function Mf(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function um(){try{return new Date().getTimezoneOffset()}catch{return}}var dm={flags:Wi,surveys:ns},fm=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],Hn="main";class Ao{constructor(e,n,i){if(i===void 0&&(i=!0),this.ci={},this.fi=!1,this.pi=!1,this.Ne=e,this.gi=i,this.props={},this.mi=void 0,this.yi=(s=>{var o="";return s.token&&(o=s.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),s.persistence_name?"ph_"+s.persistence_name:"ph_"+o+"_posthog"})(e),this.ii=this.bi(e),this.pi=this.wi(e),this.load(),e.debug&&A.info("Persistence loaded",e.persistence,I({},this.props)),this.update_config(e,e,n),this.save(),w){var r=()=>this.flush();ve(w,"beforeunload",r,{capture:!1}),ve(w,"pagehide",r,{capture:!1})}}ki(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return ke(n)&&n>0?n:0}isDisabled(){return!!this.xi}bi(e){fm.indexOf(e.persistence.toLowerCase())===-1&&(A.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var n,i=(function(o,a){o===void 0&&(o=[]),a===void 0&&(a=!1);var l=[...zg,...o];return I({},le,{H(u){try{var c={};try{c=zt.H(u)||{}}catch{}var d,f=JSON.parse(le.P(u)||"{}");if(a){var h={};for(var p in c){var g=c[p];Ye(g)||g===""||(h[p]=g)}d=fe(f,h)}else d=fe(c,f);return le.F(u,d),d}catch{}return null},F(u,c,d,f,h,p){var g=le.F(u,c,void 0,void 0,p);try{var m={};l.forEach((v=>{c[v]&&(m[v]=c[v])})),Object.keys(m).length&&zt.F(u,m,d,f,h,p)}catch(v){le.j(v)}return g},q(u,c){try{w?.localStorage.removeItem(u),zt.q(u,c)}catch(d){le.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),r=!1,s=e.persistence.toLowerCase();return s==="localstorage"&&le.N()?(n=le,r=!0):s==="localstorage+cookie"&&i.N()?(n=i,r=!0):s==="sessionstorage"&&be.N()?n=be:s==="memory"?n=qg:s==="cookie"?n=zt:i.N()?(n=i,r=!0):n=zt,this.fi=r,n}Si(e){return this.yi+"__"+e}wi(e){return this.fi&&!!e.split_storage}properties(){var e={};return ie(this.props,((n,i)=>{var r=yn(i);if(!r||r.exposure==="event"){if(r!=null&&r.shouldSkipFromEventProperties!=null&&r.shouldSkipFromEventProperties(n))return;e[i]=n}})),e}load(){if(!this.xi){var e=this.ii.H(this.yi);e&&(this.props=fe({},e)),this.pi&&this.Ci()}}Ci(){for(var e of Co){var n=le.H(this.Si(e));if(n&&!Kt(n)){var i=this.Mi(e);i.persisted=!0,this.Ti(e)||(i.fingerprint=this.Ei(n,e)),this.Ii(e,n)||fe(this.props,n)}}}Ti(e){return Object.keys(this.props).some((n=>{var i;return((i=yn(n))==null?void 0:i.storageGroup)===e}))}Ii(e,n){var i=dm[e];if(!i)return!1;var r=n[i],s=this.props[i];return ke(r)&&ke(s)&&s>r}refreshKey(e){var n;if(!this.xi){var i=this.pi?(n=yn(e))==null?void 0:n.storageGroup:void 0,r=i?le.H(this.Si(i)):this.ii.H(this.yi);if(r&&e in r)this.Pi(e,r[e]);else{if(i){var s=this.ii.H(this.yi);if(s&&e in s)return void this.Pi(e,s[e])}this.Ri(e)}}}save(){if(!this.xi){var e=this.ki();e>0?C(this.Ai)&&(this.Ai=setTimeout((()=>{this.Ai=void 0,this.Fi()}),e)):this.Fi()}}flush(){C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0,this.Fi())}Fi(){this.xi||(this.pi?this.Li():this.Oi(this.ii,this.yi,this.props,Hn))}Li(){var e=this.Di(),n=e.main,i=e.groups;for(var r of(this.Oi(this.ii,this.yi,n,Hn),Co)){var s,o=i[r];(!Kt(o)||(s=this.ci[r])!=null&&s.persisted)&&this.Oi(le,this.Si(r),o,r)}}Di(){var e={},n={flags:{},surveys:{}};return ie(this.props,((i,r)=>{var s,o=(s=yn(r))==null?void 0:s.storageGroup;o?n[o][r]=i:e[r]=i})),{main:e,groups:n}}Ei(e,n){if(n===Hn)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var i={};return ie(e,((r,s)=>{var o;i[s]=(o=yn(s))!=null&&o.volatile?"__volatile__":r})),JSON.stringify(i)}Oi(e,n,i,r){var s=this.Mi(r);if(r===Hn||s.dirty||C(s.fingerprint)){var o;try{if((o=this.Ei(i,r))===s.fingerprint)return void(s.dirty=!1)}catch{o=void 0}e.F(n,i,this.$i,this.Ni,this.qi,this.Ne.debug)?(s.dirty=!1,r!==Hn&&(s.persisted=!0),C(o)||(s.fingerprint=o)):this.Ne.debug&&A.warn('failed to persist storage entry "'+n+'"; will retry on next save')}}remove(e){var n=(e===void 0?{}:e).keepGroupEntries,i=n!==void 0&&n;if(C(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0),this.ii.q(this.yi,!1),this.ii.q(this.yi,!0),!i&&this.gi)for(var r of Co)le.q(this.Si(r));i?delete this.ci[Hn]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,n,i){if(he(e)){C(n)&&(n="None"),this.$i=C(i)?this.ji:i;var r=!1;if(ie(e,((s,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==n||(this.Pi(o,s),r=!0)})),r)return this.save(),!0}return!1}register(e,n){if(he(e)){this.$i=C(n)?this.ji:n;var i=!1;if(ie(e,((r,s)=>{e.hasOwnProperty(s)&&(this.props[s]!==r||he(r)||U(r))&&(this.Pi(s,r),i=!0)})),i)return this.save(),!0}return!1}unregister(e){var n=typeof e=="string"?[e]:e,i=!1;for(var r of n)r in this.props&&(this.Ri(r),i=!0);i&&this.save()}update_campaign_params(){var e=P?.URL;if(e!==this.mi){var n=Af(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);Kt(hl(n))||this.register(n),this.mi=e}}update_search_keyword(){var e;this.register((e=P?.referrer)?Ff(e):{})}update_referrer_info(){var e;this.register_once({$referrer:Rf(),$referring_domain:P!=null&&P.referrer&&((e=cs(P.referrer))==null?void 0:e.host)||ds},void 0)}set_initial_person_info(){this.props[ma]||this.props[va]||this.register_once({[is]:Tf(this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties,this.Ne.disable_capture_url_hashes)},void 0)}get_initial_props(){var e={};ie([va,ma],(r=>{var s=this.props[r];s&&ie(s,(function(o,a){e["$initial_"+Zo(a)]=o}))}));var n=this.props[is];if(n){var i=(function(r,s){s===void 0&&(s=!1);var o=$f(r,s),a={};return ie(o,(function(l,u){a["$initial_"+Zo(u)]=l})),a})(n,this.Ne.disable_capture_url_hashes);fe(e,i)}return e}safe_merge(e){return ie(this.props,(function(n,i){i in e||(e[i]=n)})),e}update_config(e,n,i){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!i),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var r=e.persistence!==n.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((f,h)=>f===d[h]))})(e.cookie_persisted_properties||[],n.cookie_persisted_properties||[]),s=r?this.bi(e):this.ii,o=this.wi(e);if(r||o!==this.pi){var a=this.props;this.clear(),this.ii=s,this.pi=o,this.props=a,this.save()}}set_disabled(e){this.xi=e,this.xi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ni&&(this.Ni=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this.qi&&(this.qi=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,n){var i=this.props[Mi]||{};i[e]=n,this.Pi(Mi,i),this.save()}remove_event_timer(e){var n=this.props[Mi]||{},i=n[e];return C(i)||(delete n[e],this.Pi(Mi,n),this.save()),i}get_property(e){return this.props[e]}set_property(e,n){this.Pi(e,n),this.save()}Pi(e,n){var i;this.props[e]=n,(i=yn(e))!=null&&i.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var n,i=(n=yn(e))==null?void 0:n.storageGroup;i&&(this.Mi(i).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function xr(t){var e=!0;return{dispose(){if(e){e=!1;var n=t();n&&je(n.then)&&n.then(void 0,(()=>{}))}}}}var Ue={GZipJS:"gzip-js",Base64:"base64"},Si={Activation:"events",Cancellation:"cancelEvents"},Po={Popover:"popover",API:"api",Widget:"widget"},qt={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},Fo={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},Ea={Popover:"popover",Inline:"inline"},hm={SHOWN:"product tour shown"},Zc={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},Xc=pe("[RateLimiter]");class pm{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=n=>{var i=n.text;if(i&&i.length)try{(JSON.parse(i).quota_limited||[]).forEach((r=>{Xc.info((r||"events")+" is quota limited."),this.serverLimits[r]=new Date().getTime()+6e4}))}catch(r){return void Xc.warn('could not rate limit - continuing. Error: "'+r?.message+'"',{text:i})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var n,i,r;e===void 0&&(e=!1);var s=this.captureEventsBurstLimit,o=this.captureEventsPerSecond,a=new Date().getTime(),l=(n=(i=this.instance.persistence)==null?void 0:i.get_property(ga))!==null&&n!==void 0?n:{tokens:s,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>s&&(l.tokens=s);var u=1>l.tokens;if(u||e||(l.tokens=Math.max(0,l.tokens-1)),u&&!e){var c=(ke(l.dropped)?l.dropped:0)+1;l.dropped=c,!this.lastEventRateLimited&&this.Hi(c)&&(l.dropped=0)}return this.lastEventRateLimited=u,(r=this.instance.persistence)==null||r.set_property(ga,l),{isRateLimited:u,remainingTokens:l.tokens}}Ui(e){var n=this.instance.config.property_denylist;return!U(n)||!n.includes(e)}zi(){var e;if(this.Ui("$current_url")&&this.Ui("$pathname")&&me!=null&&me.pathname)return""+((e=me.origin)!==null&&e!==void 0?e:"")+me.pathname}Hi(e){var n,i,r=this.captureEventsBurstLimit,s=this.captureEventsPerSecond,o=this.zi(),a=this.Ui("$session_id")?(n=(i=this.instance).get_session_id)==null?void 0:n.call(i):void 0,l=[e+" event(s) dropped since the last warning",o?"triggered on "+o:void 0,a?"session "+a:void 0].filter(Boolean).join(", ");return!!this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited: "+l+". Config is set to "+s+" events per second and "+r+" events burst limit."},{skip_client_rate_limiting:!0})}isServerRateLimited(e){var n=this.serverLimits[e||"events"]||!1;return n!==!1&&new Date().getTime()e(this.remoteConfig))):e()}Vi(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:e})}load(){try{if(this.remoteConfig)return an.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void an.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return an.info("No config found after loading remote JS config. Falling back to JSON."),void this.Vi((n=>{this.Zi(n.json,n),this.Gi()}));this.Zi(e),this.Gi()}))}catch(e){an.error("Error loading remote config",e),this.Zi()}}stop(){this.Ki&&(clearInterval(this.Ki),this.Ki=void 0)}refresh(){!this._instance.Qi()&&P&&P.visibilityState!=="hidden"&&this._instance.reloadFeatureFlags()}Gi(){var e;if(!this.Ki){var n=(e=this._instance.config.remote_config_refresh_interval_ms)!==null&&e!==void 0?e:3e5;n!==0&&(this.Ki=setInterval((()=>{this.refresh()}),n))}}Zi(e,n){!e&&n&&(n.statusCode===0?n.error||an.warn("Failed to fetch remote config from PostHog."):an.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(r){an.error("Error applying remote config",r)}if(e?.hasFeatureFlags!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var i;(i=this._instance.featureFlags)==null||i.ensureFlagsLoaded()}catch(r){an.error("Error loading feature flags",r)}}}var ct=Uint8Array,Ke=Uint16Array,ai=Uint32Array,vl=new ct([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]),_l=new ct([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]),Qc=new ct([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Nf=function(t,e){for(var n=new Ke(31),i=0;31>i;++i)n[i]=e+=1<i;++i)for(var s=n[i];n[i+1]>s;++s)r[s]=s-n[i]<<5|i;return[n,r]},Of=Nf(vl,2),Sa=Of[1];Of[0][28]=258,Sa[258]=28;for(var eu=Nf(_l,0)[1],Bf=new Ke(32768),_e=0;32768>_e;++_e){var Wn=(43690&_e)>>>1|(21845&_e)<<1;Bf[_e]=((65280&(Wn=(61680&(Wn=(52428&Wn)>>>2|(13107&Wn)<<2))>>>4|(3855&Wn)<<4))>>>8|(255&Wn)<<8)>>>1}var qi=function(t,e,n){for(var i=t.length,r=0,s=new Ke(e);i>r;++r)++s[t[r]-1];var o,a=new Ke(e);for(r=0;e>r;++r)a[r]=a[r-1]+s[r-1]<<1;for(o=new Ke(i),r=0;i>r;++r)o[r]=Bf[a[t[r]-1]++]>>>15-t[r];return o},$n=new ct(288);for(_e=0;144>_e;++_e)$n[_e]=8;for(_e=144;256>_e;++_e)$n[_e]=9;for(_e=256;280>_e;++_e)$n[_e]=7;for(_e=280;288>_e;++_e)$n[_e]=8;var fs=new ct(32);for(_e=0;32>_e;++_e)fs[_e]=5;var gm=qi($n,9),mm=qi(fs,5),Df=function(t){return(t/8>>0)+(7&t&&1)},jf=function(t,e,n){(n==null||n>t.length)&&(n=t.length);var i=new(t instanceof Ke?Ke:t instanceof ai?ai:ct)(n-e);return i.set(t.subarray(e,n)),i},Ot=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8},xi=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8,t[i+2]|=n>>>16},Ro=function(t,e){for(var n=[],i=0;t.length>i;++i)t[i]&&n.push({s:i,f:t[i]});var r=n.length,s=n.slice();if(!r)return[new ct(0),0];if(r==1){var o=new ct(n[0].s+1);return o[n[0].s]=1,[o,1]}n.sort((function(b,k){return b.f-k.f})),n.push({s:-1,f:25001});var a=n[0],l=n[1],u=0,c=1,d=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=r-1;)a=n[n[d].f>n[u].f?u++:d++],l=n[u!=c&&n[d].f>n[u].f?u++:d++],n[c++]={s:-1,f:a.f+l.f,l:a,r:l};var f=s[0].s;for(i=1;r>i;++i)s[i].s>f&&(f=s[i].s);var h=new Ke(f+1),p=xa(n[c-1],h,0);if(p>e){i=0;var g=0,m=p-e,v=1<i;++i){var E=s[i].s;if(e>=h[E])break;g+=v-(1<>>=m;g>0;){var S=s[i].s;e>h[S]?g-=1<=0&&g;--i){var _=s[i].s;h[_]==e&&(--h[_],++g)}p=e}return[new ct(h),p]},xa=function(t,e,n){return t.s==-1?Math.max(xa(t.l,e,n+1),xa(t.r,e,n+1)):e[t.s]=n},tu=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new Ke(++e),i=0,r=t[0],s=1,o=function(l){n[i++]=l},a=1;e>=a;++a)if(t[a]==r&&a!=e)++s;else{if(!r&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(r),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(r);s=1,r=t[a]}return[n.subarray(0,i),e]},Ii=function(t,e){for(var n=0,i=0;e.length>i;++i)n+=t[i]*e[i];return n},Ia=function(t,e,n){var i=n.length,r=Df(e+2);t[r]=255&i,t[r+1]=i>>>8,t[r+2]=255^t[r],t[r+3]=255^t[r+1];for(var s=0;i>s;++s)t[r+s+4]=n[s];return 8*(r+4+i)},nu=function(t,e,n,i,r,s,o,a,l,u,c){Ot(e,c++,n),++r[256];for(var d=Ro(r,15),f=d[0],h=d[1],p=Ro(s,15),g=p[0],m=p[1],v=tu(f),E=v[0],S=v[1],_=tu(g),b=_[0],k=_[1],T=new Ke(19),x=0;E.length>x;++x)T[31&E[x]]++;for(x=0;b.length>x;++x)T[31&b[x]]++;for(var F=Ro(T,7),$=F[0],O=F[1],L=19;L>4&&!$[Qc[L-1]];--L);var N,K,V,M,R=u+5<<3,Z=Ii(r,$n)+Ii(s,fs)+o,Ce=Ii(r,f)+Ii(s,g)+o+14+3*L+Ii(T,$)+(2*T[16]+3*T[17]+7*T[18]);if(Z>=R&&Ce>=R)return Ia(e,c,t.subarray(l,l+u));if(Ot(e,c,1+(Z>Ce)),c+=2,Z>Ce){N=qi(f,h),K=f,V=qi(g,m),M=g;var oe=qi($,O);for(Ot(e,c,S-257),Ot(e,c+5,k-1),Ot(e,c+10,L-4),c+=14,x=0;L>x;++x)Ot(e,c+3*x,$[Qc[x]]);c+=3*L;for(var ye=[E,b],$e=0;2>$e;++$e){var ae=ye[$e];for(x=0;ae.length>x;++x)Ot(e,c,oe[Ie=31&ae[x]]),c+=$[Ie],Ie>15&&(Ot(e,c,ae[x]>>>5&127),c+=ae[x]>>>12)}}else N=gm,K=$n,V=mm,M=fs;for(x=0;a>x;++x)if(i[x]>255){var Ie;xi(e,c,N[257+(Ie=i[x]>>>18&31)]),c+=K[Ie+257],Ie>7&&(Ot(e,c,i[x]>>>23&31),c+=vl[Ie]);var Se=31&i[x];xi(e,c,V[Se]),c+=M[Se],Se>3&&(xi(e,c,i[x]>>>5&8191),c+=_l[Se])}else xi(e,c,N[i[x]]),c+=K[i[x]];return xi(e,c,N[256]),c+K[256]},vm=new ai([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),_m=(function(){for(var t=new ai(256),e=0;256>e;++e){for(var n=e,i=9;--i;)n=(1&n&&3988292384)^n>>>1;t[e]=n}return t})(),To=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8};function ym(t,e){e===void 0&&(e={});var n=(function(){var d=4294967295;return{p(f){for(var h=d,p=0;f.length>p;++p)h=_m[255&h^f[p]]^h>>>8;d=h},d(){return 4294967295^d}}})(),i=t.length;n.p(t);var r,s,o,a,l,u=(a=10+((r=e).filename&&r.filename.length+1||0),l=8,(function(d,f,h,p,g,m){var v=d.length,E=new ct(p+v+5*(1+Math.floor(v/7e3))+g),S=E.subarray(p,E.length-g),_=0;if(!f||8>v)for(var b=0;v>=b;b+=65535){var k=b+65535;v>k?_=Ia(S,_,d.subarray(b,k)):(S[b]=!0,_=Ia(S,_,d.subarray(b,v)))}else{for(var T=vm[f-1],x=T>>>13,F=8191&T,$=(1<b;++b){var Ie=V(b),Se=32767&b,De=L[Ie];if(O[Se]=De,L[Ie]=Se,b>=$e){var wt=v-b;if((Ce>7e3||ye>24576)&&wt>423){_=nu(d,S,0,M,R,Z,oe,ye,ae,b-ae,_),ye=Ce=oe=0,ae=b;for(var ge=0;286>ge;++ge)R[ge]=0;for(ge=0;30>ge;++ge)Z[ge]=0}var Je=2,bt=0,mn=F,Re=Se-De&32767;if(wt>2&&Ie==V(b-Re))for(var Pe=Math.min(x,wt)-1,$t=Math.min(32767,b),Bn=Math.min(258,wt);$t>=Re&&--mn&&Se!=De;){if(d[b+Je]==d[b+Je-Re]){for(var qe=0;Bn>qe&&d[b+qe]==d[b+qe-Re];++qe);if(qe>Je){if(Je=qe,bt=Re,qe>Pe)break;var Dn=Math.min(Re,qe-2),Mt=0;for(ge=0;Dn>ge;++ge){var Lt=b-Re+ge+32768&32767,ut=Lt-O[Lt]+32768&32767;ut>Mt&&(Mt=ut,De=Lt)}}}Re+=(Se=De)-(De=O[Se])+32768&32767}if(bt){M[ye++]=268435456|Sa[Je]<<18|eu[bt];var sn=31&Sa[Je],_i=31&eu[bt];oe+=vl[sn]+_l[_i],++R[257+sn],++Z[_i],$e=b+Je,++Ce}else M[ye++]=d[b],++R[d[b]]}}_=nu(d,S,!0,M,R,Z,oe,ye,ae,b-ae,_)}return jf(E,0,p+Df(_)+g)})(s=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):12+o.mem,a,l)),c=u.length;return(function(d,f){var h=f.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>f.level?4:f.level==9?2:0,d[9]=3,f.mtime!=0&&To(d,4,Math.floor(new Date(f.mtime||Date.now())/1e3)),h){d[3]=8;for(var p=0;h.length>=p;++p)d[p+10]=h.charCodeAt(p)}})(u,e),To(u,c-8,n.d()),To(u,c-4,i),u}var wm=!!Ko||!!nl,Uf="text/plain",Or=!1,Hf=(t,e)=>{var n=t.split("#"),i=n[1],r=n[0].split("?"),s=r[0],o=r[1];if(!o)return t;var a=o.split("&").filter((l=>l.split("=")[0]!==e)).join("&");return s+(a?"?"+a:"")+(i?"#"+i:"")},Fs=function(t,e,n){var i;n===void 0&&(n=!0);var r=t.split("?"),s=r[0],o=r[1],a=I({},e),l=(i=o?.split("&").map((c=>{var d,f=c.split("="),h=f[0],p=n&&(d=a[h])!==null&&d!==void 0?d:f[1];return delete a[h],h+"="+p})))!==null&&i!==void 0?i:[],u=(function(c,d){var f,h;d===void 0&&(d="&");var p=[];return ie(c,(function(g,m){C(g)||C(m)||m==="undefined"||(f=encodeURIComponent((v=>v instanceof File)(g)?g.name:g.toString()),h=encodeURIComponent(m),p[p.length]=h+"="+f)})),p.join(d)})(a);return u&&l.push(u),l.length>0?s+"?"+l.join("&"):s},$o=t=>{if(t.Ji)return t.Ji;var e=t.data,n=t.compression;if(e){if(n===Ue.GZipJS){var i=ym((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new ct(a.length+(a.length>>>1)),d=0,f=function(m){c[d++]=m},h=0;u>h;++h){if(d+5>c.length){var p=new ct(d+8+(u-h<<1));p.set(c),c=p}var g=a.charCodeAt(h);128>g?f(g):2048>g?(f(192|g>>>6),f(128|63&g)):g>55295&&57344>g?(f(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++h))>>>18),f(128|g>>>12&63),f(128|g>>>6&63),f(128|63&g)):(f(224|g>>>12),f(128|g>>>6&63),f(128|63&g))}return jf(c,0,d)})(Yn(e)),{mtime:0});return{contentType:Uf,body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),estimatedSize:i.byteLength}}if(n===Ue.Base64){var r=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(Yn(e)),s=(a=>"data="+encodeURIComponent(typeof a=="string"?a:Yn(a)))(r);return{contentType:"application/x-www-form-urlencoded",body:s,estimatedSize:new Blob([s]).size}}var o=Yn(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},Wf=t=>{var e,n,i=()=>t.transport==="sendBeacon"?{url:Fs(t.url,{compression:Ue.Base64}),encodedBody:$o(I({},t,{compression:Ue.Base64,Ji:void 0}))}:{url:Hf(t.url,"compression"),encodedBody:$o(I({},t,{compression:void 0,Ji:void 0}))};try{e=$o(t)}catch(r){if(Ec(t.compression,si(t.url,"compression")))return A.error("Failed to gzip request body, sending uncompressed payload",r),i();throw r}return e&&Ec(t.compression,si(t.url,"compression"))&&!((n=e.body)instanceof ArrayBuffer?Yo(new Uint8Array(n)):ArrayBuffer.isView(n)&&Yo(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)))?(Or=!0,i()):{url:t.url,encodedBody:e}},zf=t=>{try{return Wf(t)}catch(e){return A.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},bm=(function(){var t=se((function*(e){var n=Yn(e.data),i=yield(function(s,o,a){return Jo.apply(this,arguments)})(n,ne.DEBUG,{rethrow:!0});if(!i)return e;var r=yield i.arrayBuffer();return I({},e,{Ji:{contentType:Uf,body:r,estimatedSize:r.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),Em=/Failed to fetch|NetworkError|Load failed/i,qf=t=>t?.name==="TypeError"&&Em.test(t?.message||""),Vf=t=>{var e=zf(t);if(e){var n=e.url,i=e.encodedBody,r=i??{},s=r.contentType,o=r.body,a=r.estimatedSize,l=new Headers;ie(t.headers,(function(p,g){l.append(g,p)})),s&&l.append("Content-Type",s);var u=null,c=!1;if(mc){var d=new mc;u={signal:d.signal,timeout:setTimeout((()=>{var p,g;c=!0,d.abort((p=t.timeout,(g=new Error("PostHog request timed out"+(p?" after "+p+"ms":""))).name="AbortError",g))}),t.timeout)}}var f=p=>{c&&p?.name==="AbortError"||qf(p)?A.warn(p):A.error(p),t.callback==null||t.callback({statusCode:0,error:p})};try{var h;nl(n,I({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(h=u)==null?void 0:h.signal},t.fetchOptions)).then((p=>p.text().then((g=>{var m={statusCode:p.status,text:g};if(p.status===200)try{m.json=JSON.parse(g)}catch(v){A.error(v)}t.callback==null||t.callback(m)})))).catch(f).finally((()=>u?clearTimeout(u.timeout):null))}catch(p){u&&clearTimeout(u.timeout),f(p)}}},ka=t=>{try{var e,n=Wf(t),i=n.url,r=n.encodedBody,s=r??{},o=s.body,a=s.estimatedSize;if(!o)return;var l=o instanceof Blob?o:new Blob([o],{type:s.contentType});if(He.sendBeacon(i,l))return;var u=U(t.data)?t.data:(e=t.data)==null?void 0:e.batch;if(U(u)&&u.length>1&&(a??0)>16384){var c=Math.ceil(u.length/2),d=f=>U(t.data)?f:I({},t.data,{batch:f});return ka(I({},t,{data:d(u.slice(0,c))})),void ka(I({},t,{data:d(u.slice(c))}))}A.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),Vf(I({},t,{Yi:!0}))}catch(f){A.warn("Beacon send failed",f)}},iu=(t,e,n,i)=>{var r=i==="query"?e==="POST"?"sent_at":"_":void 0;return Fs(n===Ue.GZipJS?Hf(t,"compression"):t,I({},r?{[r]:Date.now().toString()}:{},n===Ue.GZipJS?{}:{compression:n}))},Br=[];nl&&Br.push({transport:"fetch",method:Vf}),Ko&&Br.push({transport:"XHR",method(t){var e=zf(t);if(e){var n=new Ko,i=e.encodedBody;n.open(t.method||"GET",e.url,!0);var r=i??{},s=r.contentType,o=r.body;ie(t.headers,(function(a,l){n.setRequestHeader(l,a)})),s&&n.setRequestHeader("Content-Type",s),t.timeout&&(n.timeout=t.timeout),n.onreadystatechange=()=>{if(n.readyState===4){var a={statusCode:n.status,text:n.responseText};if(n.status===200)try{a.json=JSON.parse(n.responseText)}catch{}t.callback==null||t.callback(a)}},n.send(o)}}}),He!=null&&He.sendBeacon&&Br.push({transport:"sendBeacon",method:ka});var Ca=3e3;class Sm{constructor(e,n){this.Xi=!0,this.tr=[],this.er=At(n?.flush_interval_ms||Ca,250,5e3,A.createLogger("flush interval"),Ca),this.ir=e}enqueue(e){this.tr.push(e),this.rr||this.nr()}unload(){this.sr();var e=this.tr.length>0?this.ar():{},n=Object.values(e);[...n.filter((i=>i.url.indexOf("/e")===0)),...n.filter((i=>i.url.indexOf("/e")!==0))].map((i=>{this.lr(I({},i,{transport:"sendBeacon"}))}))}enable(){this.Xi=!1,this.nr()}nr(){var e=this;this.Xi||(this.rr=setTimeout((()=>{if(this.sr(),this.tr.length>0){var n=this.ar(),i=function(){var s=n[r],o=new Date().getTime();s.data&&U(s.data)&&ie(s.data,(a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp})),e.lr(s)};for(var r in n)i()}}),this.er))}lr(e){try{this.ir(e)}catch(n){A.error(n)}}sr(){clearTimeout(this.rr),this.rr=void 0}ar(){var e={};return ie(this.tr,(n=>{var i,r=n,s=(r?r.batchKey:null)||r.url;C(e[s])&&(e[s]=I({},r,{data:[]})),(i=e[s].data)==null||i.push(r.data)})),this.tr=[],e}}var xm=["retriesPerformedSoFar"];class Im{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!C(w)&&"onLine"in w.navigator&&(this.dr=w.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},ve(w,"online",this.vr),ve(w,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var n=e.retriesPerformedSoFar,i=yd(e,xm);Dt(n)&&(i.url=Fs(i.url,{retry_count:n})),this._instance._send_request(I({},i,{callback:r=>{if(r.statusCode!==200&&(400>r.statusCode||r.statusCode>=500)){if((r.statusCode===0?3:10)>(n??0))return void this.At(I({retriesPerformedSoFar:n},i));r.statusCode===0&&A.warn("Request failed before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped retrying after "+(n??0)+" retries.")}i.callback==null||i.callback(r)}}))}At(e){var n=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=n+1;var i=(function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),c=Math.random()-.5;return Math.ceil(u+c*(u-l))})(n),r=Date.now()+i;this.tr.push({retryAt:r,requestOptions:e});var s="Enqueued failed request for retry in "+i;navigator.onLine||(s+=" (Browser is offline)"),A.warn(s),this.ur||(this.ur=!0,this.gr())}gr(){if(this.mr&&clearTimeout(this.mr),this.tr.length===0)return this.ur=!1,void(this.mr=void 0);this.mr=setTimeout((()=>{this.dr&&this.tr.length>0&&this.cr(),this.gr()}),this.hr)}cr(){var e=Date.now(),n=[],i=this.tr.filter((s=>e>s.retryAt||(n.push(s),!1)));if(this.tr=n,i.length>0)for(var r of i)this.retriableRequest(r.requestOptions)}unload(){for(var e of(this.mr&&(clearTimeout(this.mr),this.mr=void 0),this.ur=!1,C(w)||(this.vr&&(w.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(w.removeEventListener("offline",this.pr),this.pr=void 0)),this.tr)){var n=e.requestOptions;try{this._instance._send_request(I({},n,{transport:"sendBeacon"}))}catch(i){A.error(i)}}this.tr=[]}}class km{constructor(e){this.yr=()=>{var n,i,r,s;this.br||(this.br={});var o=this.scrollElement(),a=this.scrollY(),l=o?Math.max(0,o.scrollHeight-o.clientHeight):0,u=a+(o?.clientHeight||0),c=o?.scrollHeight||0;this.br.lastScrollY=Math.ceil(a),this.br.maxScrollY=Math.max(a,(n=this.br.maxScrollY)!==null&&n!==void 0?n:0),this.br.maxScrollHeight=Math.max(l,(i=this.br.maxScrollHeight)!==null&&i!==void 0?i:0),this.br.lastContentY=u,this.br.maxContentY=Math.max(u,(r=this.br.maxContentY)!==null&&r!==void 0?r:0),this.br.maxContentHeight=Math.max(c,(s=this.br.maxContentHeight)!==null&&s!==void 0?s:0)},this._instance=e}get _r(){return this._instance.config.scroll_root_selector}getContext(){return this.br}resetContext(){var e=this.br;return setTimeout(this.yr,0),e}startMeasuringScrollPosition(){ve(w,"scroll",this.yr,{capture:!0}),ve(w,"scrollend",this.yr,{capture:!0}),ve(w,"resize",this.yr)}scrollElement(){if(!this._r)return w?.document.documentElement;var e=U(this._r)?this._r:[this._r];for(var n of e){var i=w?.document.querySelector(n);if(i)return i}}wr(e){var n=e==="y"?"scrollTop":"scrollLeft";if(this._r){var i=this.scrollElement();return i&&i[n]||0}return w?e==="y"?w.scrollY||w.pageYOffset||w.document.documentElement.scrollTop||0:w.scrollX||w.pageXOffset||w.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var Cm=t=>Tf(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class ru{constructor(e,n,i,r){this.kr=s=>{var o=this.Sr();if(!o||o.sessionId!==s){var a={sessionId:s,props:this.Cr(this._instance)};this.Mr.register({[pa]:a})}},this._instance=e,this.Tr=n,this.Mr=i,this.Cr=r||Cm,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[pa]}getSetOnceProps(){var e,n=(e=this.Sr())==null?void 0:e.props;return n?"r"in n?$f(n,this._instance.config.disable_capture_url_hashes):{$referring_domain:n.referringDomain,$pathname:n.initialPathName,utm_source:n.utm_source,utm_campaign:n.utm_campaign,utm_medium:n.utm_medium,utm_content:n.utm_content,utm_term:n.utm_term}:{}}getSessionProps(){var e={};return ie(hl(this.getSetOnceProps()),((n,i)=>{i==="$current_url"&&(i="url"),e["$session_entry_"+Zo(i)]=n})),e}}class yl{on(e,n){return this.Er[e]||(this.Er[e]=[]),this.Er[e].push(n),()=>{this.Er[e]=this.Er[e].filter((i=>i!==n))}}emit(e,n){for(var i of this.Er[e]||[])i(n);for(var r of this.Er["*"]||[])r(e,n)}constructor(){this.Er={}}}var ki=pe("[SessionId]");class su{on(e,n){return this.Ir.on(e,n)}constructor(e,n,i){var r;if(this.Pr=null,this.Rr=[],this.Ar=void 0,this.Fr=!1,this.Ir=new yl,this.Lr=(u,c)=>!(!Dt(u)||!Dt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===Wt)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Ne=e.config,this.Mr=e.persistence,this.Or=void 0,this.Dr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.$r=n||Ht,this.Nr=i||Ht;var s=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*At(this.Ne.session_idle_timeout_seconds||1800,60,36e3,ki.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.qr(),this.jr="ph_"+s+"_window_id",this.Br="ph_"+s+"_primary_window_exists",this.Hr()){var o=be.H(this.jr),a=be.H(this.Br);o&&!a?this.Or=o:be.q(this.jr),be.F(this.Br,!0)}if((r=this.Ne.bootstrap)!=null&&r.sessionID)try{var l=(u=>{var c=this.Ne.bootstrap.sessionID.replace(/-/g,"");if(c.length!==32)throw new Error("Not a valid UUID");if(c[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(c.substring(0,12),16)})();this.Ur(this.Ne.bootstrap.sessionID,new Date().getTime(),l)}catch(u){ki.error("Invalid sessionID in bootstrap",u)}this.zr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return C(this.Rr)&&(this.Rr=[]),this.Rr.push(e),this.Dr&&e(this.Dr,this.Or),()=>{this.Rr=this.Rr.filter((n=>n!==e))}}Hr(){return this.Ne.persistence!=="memory"&&!this.Mr.xi&&be.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&be.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?be.H(this.jr):null}Zr(e){var n=this.Pr;return!Ye(n)&&!Ye(e)&&5e3>Math.abs(e-n)}Ur(e,n,i){var r=n!==this._sessionActivityTimestamp,s=!(e!==this.Dr||i!==this._sessionStartTimestamp);this._sessionStartTimestamp=i,this._sessionActivityTimestamp=n,this.Dr=e,s&&!r||s&&this.Zr(n)||(this.Pr=n,this.Mr.register({[Kn]:[n,e,i]}))}Gr(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return Dt(n)&&n>0}Qr(){this.Gr()?this.Mr.refreshKey(Kn):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!Ye(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this.Pr){this.Qr();var n=this.Jr();n[1]===this.Dr&&n[2]===this._sessionStartTimestamp&&(this.Pr=this._sessionActivityTimestamp,this.Mr.register({[Kn]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],n=Dt(e)?e:0,i=Dt(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(n,i)}Xr(e){return this.Qr(),this.Lr(e,this.Yr())}Jr(){var e=this.Mr.props[Kn];return U(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Pr=null,clearTimeout(this.tn),this.tn=void 0,this.Ur(null,null,null)}destroy(){this.Fr=!0,this.Kr(),clearTimeout(this.tn),this.tn=void 0,this.Ar&&w&&(w.removeEventListener(os,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&be.q(this.Br)},ve(w,os,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=null),this.Ne.cookieless_mode===Wt)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var i=n||new Date().getTime(),r=this.Jr(),s=r[1],o=r[2],a=this.Yr(),l=this.Vr(),u=Dt(o)&&Math.abs(i-o)>864e5,c=!1,d=!1,f=!s,h=s,p=!f&&!e&&this.Lr(i,a);if(p){(p=this.Xr(i))||ki.info("cross-tab refresh kept the session alive",{sessionId:s});var g=this.Jr();s=g[1],o=g[2]}f||p||u?(s=this.$r(),l=this.Nr(),ki.info("new session ID generated",{sessionId:s,windowId:l,changeReason:{noSessionId:f,activityTimeout:p,sessionPastMaximumLength:u}}),o=i,c=!0):(l||(l=this.Nr(),c=!0),(d=s!==h)&&(ki.info("adopted cross-tab session id",{sessionId:s,windowId:l}),c=!0));var m=Dt(a)&&e&&!u?a:i,v=Dt(o)?o:new Date().getTime();this.Wr(l),this.Ur(s,m,v),e||this.qr();var E={noSessionId:f,activityTimeout:p,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((S=>S(s,l,E))),{sessionId:s,windowId:l,sessionStartTimestamp:v,changeReason:c?E:void 0,lastActivityTimestamp:a}}qr(){this.Fr||(clearTimeout(this.tn),this.tn=setTimeout((()=>{if(!this.Fr)if(this.Xr(new Date().getTime())){var e=this.Dr;this.resetSessionId(),this.Ir.emit("forcedIdleReset",{idleSessionId:e})}else this.qr()}),1.1*this.sessionTimeoutMs))}}var Gf=function(t,e){if(!t)return!1;var n=t.userAgent;if(n&&xc(n,e))return!0;try{var i=t?.userAgentData;if(i!=null&&i.brands&&i.brands.some((r=>xc(r?.brand,e))))return!0}catch{}return!!t.webdriver};function Kf(){return(Kf=se((function*(){var t=He?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),n=e?.model;return X(n)&&n.length>0?n:void 0}catch(i){return void A.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",i)}}))).apply(this,arguments)}var hs=function(t,e){if(!(function(n){try{new RegExp(n)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function Mo(t,e,n){return Yn({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}var Yf={exact:(t,e)=>e.some((n=>t.some((i=>n===i)))),is_not:(t,e)=>e.every((n=>t.every((i=>n!==i)))),regex:(t,e)=>e.some((n=>t.some((i=>hs(n,i))))),not_regex:(t,e)=>e.every((n=>t.every((i=>!hs(n,i))))),icontains:(t,e)=>e.map(Ir).some((n=>t.map(Ir).some((i=>n.includes(i))))),not_icontains:(t,e)=>e.map(Ir).every((n=>t.map(Ir).every((i=>!n.includes(i))))),gt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>i>parseFloat(r)))})),lt:(t,e)=>e.some((n=>{var i=parseFloat(n);return!isNaN(i)&&t.some((r=>it.toLowerCase();function Jf(t,e){return!t||Object.entries(t).every((n=>{var i=n[1],r=e?.[n[0]];if(C(r)||Ye(r))return!1;var s=[String(r)],o=Yf[i.operator];return!!o&&o(i.values,s)}))}var Aa="custom",ou="i.posthog.com",Am=/^\/static\//;class Pm{constructor(e){this.en={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,n=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return n||(n=this.apiHost.replace("."+ou,".posthog.com")),n==="https://app.posthog.com"?"https://us.posthog.com":n}get region(){return this.en[this.apiHost]||(this.en[this.apiHost]=/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"us":/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"eu":Aa),this.en[this.apiHost]}rn(e){if(Am.test(e)){var n=this.instance.config.asset_host;if(typeof n=="string")return n.trim().replace(/\/$/,"")||void 0}}endpointFor(e,n){if(n===void 0&&(n=""),n&&(n=n[0]==="/"?n:"/"+n),e==="ui")return this.uiHost+n;if(e==="flags")return this.flagsApiHost+n;if(e==="assets"){var i=this.rn(n);if(i)return""+i+n}if(this.region===Aa)return this.apiHost+n;var r=ou+n;switch(e){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}}function Zf(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var Q=pe("[Surveys]"),Xf="seenSurvey_",Qf=t=>{try{var e=(n=>((i,r)=>""+Xf+(function(s){return s.current_iteration&&s.current_iteration>0?s.id+"_"+s.current_iteration:s.id})(r))(0,n))(t);if(localStorage.getItem(e))return;localStorage.setItem(e,"true")}catch(n){Q.error("Failed to persist survey seen state",n)}},Fm=[Po.Popover,Po.Widget,Po.API],Rm={ignoreConditions:!1,ignoreDelay:!1,displayType:Ea.Popover},Tm=pe("[PostHog ExternalIntegrations]"),$m={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class Mm{constructor(e){this._instance=e}ai(e,n){var i;(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,e,(r=>{if(r)return Tm.error("failed to load script",r);n()}))}startIfEnabledOrStop(){var e=this,n=function(){var s,o,a,l=i[0],u=i[1];!u||(s=B.__PosthogExtensions__)!=null&&(s=s.integrations)!=null&&s[l]||e.ai($m[l],(()=>{var c;(c=B.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=B.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=B.__PosthogExtensions__)==null||(a=a.integrations)==null||(a=a[l])==null||a.stop())};for(var i of Object.entries((r=this._instance.config.integrations)!==null&&r!==void 0?r:{})){var r;n()}}}class Lm{constructor(e,n){this.rt=e,this.nn=n,this.sn=new Map,this.an=!1}add(e){var n=this;return se((function*(){if(n.an)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(n.sn.has(e.name))throw new Error('Browser extension "'+e.name+'" is already registered');n.sn.set(e.name,e);try{var i=e.setup(n.nn);i&&(yield i)}catch(s){var r=n.sn.get(e.name)===e;r&&n.sn.delete(e.name),n.rt.error('Failed to set up browser extension "'+e.name+'"',s),r&&n.ln(e)}}))()}dispose(){if(!this.an){this.an=!0;var e=Array.from(this.sn.values()).reverse();for(var n of(this.sn.clear(),e))this.ln(n)}}ln(e){try{var n=e.dispose==null?void 0:e.dispose();n&&je(n.then)&&n.then(void 0,(i=>{this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}))}catch(i){this.rt.error('Failed to dispose browser extension "'+e.name+'"',i)}}}class Nm{constructor(e){this._instance=e}initialize(){}get(e){var n=this._instance.persistence;if(typeof e=="string")return n?.get_property(e);var i={};for(var r of e){var s=n?.get_property(r);C(s)||(i[r]=s)}return i}set(e,n){var i;(i=this._instance.persistence)==null||i.register(typeof e=="string"?{[e]:n}:e)}remove(e){var n;(n=this._instance.persistence)==null||n.unregister(e)}}var au="extensionsRemoteConfig";class Om{constructor(e){this.an=!1,this.instance=e,this.rt=A,this.un=e.hn,this.kv=new Nm(e),this.onEvent=n=>xr(this.instance.on("eventCaptured",(i=>{try{n({event:i.event,properties:i.properties})}catch(r){this.rt.error("Browser extension event listener failed",r)}}))),this.onRemoteConfig=n=>{if(this.an)return xr((()=>{}));var i=s=>{try{n(s)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},r=this.instance.dn.on(au,i);return this.un&&i(this.un),xr(r)},this.vn=new Lm(A.createLogger("[BrowserExtensions]"),this)}get logger(){return this.rt}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return(e=this.instance.get_property(Xi))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(Xi);return typeof e=="string"?e:void 0}get library(){return{name:ne.LIB_NAME,version:ne.LIB_VERSION}}get initialPersonProperties(){var e,n;return(e=(n=this.instance.persistence)==null?void 0:n.get_initial_props())!==null&&e!==void 0?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,n,i,r,s=(e=this.instance.sessionManager)==null?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:(n=s?.sessionId)!==null&&n!==void 0?n:"",windowId:(i=s?.windowId)!==null&&i!==void 0?i:"",sessionStartTimestamp:(r=s?.sessionStartTimestamp)!==null&&r!==void 0?r:0}}catch{return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get projectToken(){return this.instance.config.token}add(e){return this.vn.add(e)}capture(e,n,i){var r=this;return se((function*(){i?r.instance.capture(e,n,{timestamp:i.timestamp,uuid:i.uuid,$set:i.set,$set_once:i.setOnce}):r.instance.capture(e,n)}))()}registerDynamicEventProperties(e){return xr(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(au,e))}sendRequest(e,n){var i=this;return se((function*(){var r;n===void 0&&(n={});var s=i.instance.requestRouter.endpointFor((r=n.target)!==null&&r!==void 0?r:"api",e),o={method:n.method,url:n.query?Fs(s,n.query):s,data:n.body,headers:n.headers,timeout:n.timeoutMs,fireCallbackOnDrop:!0,transport:n.transport,compression:n.compression,timestampMode:n.sentAt};return n.transport==="sendBeacon"?(i.instance._send_request(o),{statusCode:202}):new Promise((a=>{o.callback=a,i.instance._send_request(o)}))}))()}dispose(){this.an||(this.an=!0,this.vn.dispose())}}var Vi={},Lo=0,ps=()=>{},lu='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',Ci="Surveys module not available",cu="sanitize_properties is deprecated. Use before_send instead",eh="Invalid value for property_denylist config: ",Bm=["token","distinct_id",af],Gn="posthog",th=!wm&&Ge?.indexOf("MSIE")===-1&&Ge?.indexOf("Mozilla")===-1,No=t=>{var e;return I({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:Dg(P?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:ps,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:t??"unset",__preview_deferred_init_extensions:!1,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:me&&X(me?.search)&&me.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disableDeviceModel:!1,disable_external_dependency_loading:!1,strict_script_versioning:!1,enable_recording_console_log:void 0,secure_cookie:(w==null||(e=w.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(n){A.error("Bad HTTP status: "+n.statusCode+" "+n.text)},get_device_id:n=>n,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:_a,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:Ca},error_tracking:{},_onCapture:ps},(n=>({rageclick:n&&n>="2026-05-30"?{content_ignorelist:Zg,ignore_text_selection:!0}:!n||"2025-11-30">n||{content_ignorelist:!0},capture_pageview:!n||"2025-05-24">n||"history_change",session_recording:n&&n>="2026-06-25"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6},streamNetworkBody:!0}:n&&n>="2026-05-30"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6}}:n&&n>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:n&&n>="2026-01-30"?"head":"body",internal_or_test_user_hostname:n&&n>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:n&&n>="2026-05-30"?250:0,split_storage:!(!n||"2026-05-30">n),detect_google_search_app:!(!n||"2026-05-30">n),disable_capture_url_hashes:!(!n||"2026-06-25">n)}))(t))},Dm=[["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"]],uu=t=>{var e={};for(var n of Dm){var i=n[0],r=n[1];C(t[i])||(e[r]=t[i])}var s=fe({},e,t),o=t.__preview_external_dependency_versioned_paths;return C(o)||(C(t.strict_script_versioning)&&(s.strict_script_versioning=!!o),X(o)&&C(t.asset_host)&&(s.asset_host=o)),U(t.property_blacklist)&&(C(t.property_denylist)?s.property_denylist=t.property_blacklist:U(t.property_denylist)?s.property_denylist=[...t.property_blacklist,...t.property_denylist]:A.error(eh+t.property_denylist)),s};class jm{constructor(){this.__forceAllowLocalhost=!1}get fn(){return this.__forceAllowLocalhost}set fn(e){A.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class Ze{pn(e,n){if(e){var i=this.sn.indexOf(e);i!==-1&&this.sn.splice(i,1)}return this.sn.push(n),n.initialize==null||n.initialize(),n}gn(){return this.config.cookieless_mode===Wt||this.config.cookieless_mode===kn&&this.consent.isRejected()}get decideEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){var e;this.webPerformance=new jm,this.mn=!1,this.version=ne.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new yl,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=No(),this.SentryIntegration=sm,this.sentryIntegration=i=>(function(r,s){var o=If(r,s);return{name:xf,processEvent:a=>o(a)}})(this,i),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.wn=!1,this.kn=null,this.xn=null,this.Sn=null,this.scrollManager=new km(this),this.pageViewManager=new Yc(this),this.rateLimiter=new pm(this),this.requestRouter=new Pm(this),this.consent=new Vg(this),this.externalIntegrations=new Mm(this);var n=(e=Ze.__defaultExtensionClasses)!==null&&e!==void 0?e:{};this.featureFlags=n.featureFlags&&new n.featureFlags(this),this.toolbar=n.toolbar&&new n.toolbar(this),this.surveys=n.surveys&&new n.surveys(this),this.conversations=n.conversations&&new n.conversations(this),this.logs=n.logs&&new n.logs(this),this.metrics=n.metrics&&new n.metrics(this),this.experiments=n.experiments&&new n.experiments(this),this.exceptions=n.exceptions&&new n.exceptions(this),this.people={set:(i,r,s)=>{var o=X(i)?{[i]:r}:i;this.setPersonProperties(o),s?.({})},set_once:(i,r,s)=>{var o=X(i)?{[i]:r}:i;this.setPersonProperties(void 0,o),s?.({})}},this.on("eventCaptured",(i=>A.info('send "'+i?.event+'"',i)))}init(e,n,i){if(i&&i!==Gn){var r,s=(r=Vi[i])!==null&&r!==void 0?r:new Ze;return s._init(e,n,i),Vi[i]=s,Vi[Gn][i]=s,s}return this._init(e,n,i)}_init(e,n,i){var r,s;n===void 0&&(n={});var o,a=X(e)?e.trim():"";if(!a)return A.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return a!==((o=this.config)==null?void 0:o.token)?console.warn("[PostHog.js]","You have already initialized PostHog with a different project token! Re-initializing is a no-op, so events will keep going to the project this instance was initialized with. To capture into a second project, load PostHog once, then initialize a named instance after the SDK has loaded, e.g. posthog.init('"+a+"', { ... }, 'project2')"):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=No(n.defaults),n.debug=this.Cn(n.debug),this.Mn=n,this.Tn=[],n.person_profiles?this.xn=n.person_profiles:n.process_person&&(this.xn=n.process_person);var l=No(n.defaults),u=uu(n),c=fe({},l,u,{name:i,token:a});he(l.rageclick)&&he(u.rageclick)&&(c.rageclick=fe({},l.rageclick,u.rageclick)),he(l.session_recording)&&he(u.session_recording)&&(c.session_recording=fe({},l.session_recording,u.session_recording)),this.set_config(c),this.config.on_xhr_error&&A.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=n.disable_compression?void 0:Ue.GZipJS;var d=this.En();if(this.persistence=new Ao(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Ao(I({},this.config,{persistence:"sessionStorage"}),d,!1),this.bn="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&be.N()){var f=be.H(this.bn);U(f)&&f.forEach((k=>{X(k)&&this.yn.add(k)}))}else be.q(this.bn);var h=I({},this.persistence.props),p=I({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new Sm((k=>this.Pn(k)),this.config.request_queue_config),this.Rn=new Im(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new su(this),this.sessionPropsManager=new ru(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((k,T,x)=>{(x!=null&&x.activityTimeout||x!=null&&x.sessionPastMaximumLength||x!=null&&x.crossTabAdoption)&&this.An()}))),this.Fn(),this.config.__preview_deferred_init_extensions?(A.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Ln(g)}),0)):(A.info("Initializing extensions synchronously"),this.Ln(g)),ne.DEBUG=ne.DEBUG||this.config.debug,ne.DEBUG&&A.info("Starting in debug mode",{this:this,config:n,thisC:I({},this.config),p:h,s:p}),!this.config.identity_distinct_id||(r=n.bootstrap)!=null&&r.distinctID||(n.bootstrap=I({},n.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((s=n.bootstrap)==null?void 0:s.distinctID)!==void 0){var m=n.bootstrap.distinctID,v=this.get_distinct_id(),E=this.persistence.get_property(at);if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&E===Un)this.identify(m);else if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&E===vn)A.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{var S=this.config.get_device_id(Ht()),_=n.bootstrap.isIdentifiedID?S:m;this.persistence.set_property(at,n.bootstrap.isIdentifiedID?vn:Un),this.register({distinct_id:m,$device_id:_})}}if(g)this.register_once({distinct_id:yr,$device_id:null},"");else if(!this.get_distinct_id()){var b=this.config.get_device_id(Ht());this.register_once({distinct_id:b,$device_id:b},""),this.persistence.set_property(at,Un)}return ve(w,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),n.segment?(function(k,T){var x=k.config.segment;if(!x)return T();(function(F,$){var O=F.config.segment;if(!O)return $();var L=K=>{var V=()=>K.anonymousId()||Ht();F.config.get_device_id=V,K.id()&&(F.register({distinct_id:K.id(),$device_id:V()}),F.persistence.set_property(at,vn)),$()},N=O.user();"then"in N&&je(N.then)?N.then(L):L(N)})(k,(()=>{x.register((F=>{typeof Promise<"u"&&Promise.resolve||ko.warn("This browser does not have Promise support, and can not use the segment integration");var $=(O,L)=>{if(!L)return O;O.event.userId||O.event.anonymousId===F.get_distinct_id()||(ko.info("No userId set, resetting PostHog"),F.reset()),O.event.userId&&O.event.userId!==F.get_distinct_id()&&(ko.info("UserId set, identifying with PostHog"),F.identify(O.event.userId));var N=F.calculateEventProperties(L,O.event.properties);return O.event.properties=Object.assign({},N,O.event.properties),O};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:O=>$(O,O.event.event),page:O=>$(O,Vn),identify:O=>$(O,So),screen:O=>$(O,"$screen")}})(k)).then((()=>{T()}))}))})(this,(()=>this.On())):this.On(),je(this.config._onCapture)&&this.config._onCapture!==ps&&(A.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(k=>this.config._onCapture(k.event,k)))),this.config.ip&&A.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this.config.disableDeviceModel||(function(){return Kf.apply(this,arguments)})().then((k=>{k&&this.register({[bo]:k})})).catch(ps),this}Fn(){var e,n,i,r,s,o,a=(e=(n=this.config.__extensionClasses)==null?void 0:n.featureFlags)!==null&&e!==void 0?e:(i=Ze.__defaultExtensionClasses)==null?void 0:i.featureFlags;a&&(this.featureFlags&&this.featureFlags instanceof a||((r=this.Dn)==null||r.call(this),this.Dn=void 0,this.featureFlags=new a(this)),je(this.featureFlags.onReloading)&&je(this.featureFlags.setup)?this.Dn||(this.Dn=this.featureFlags.onReloading((()=>{this.dn.emit("featureFlagsReloading",!0)})),this.$n().add(this.featureFlags)):(s=(o=this.featureFlags).initialize)==null||s.call(o))}Ln(e){var n,i,r,s,o,a,l,u=performance.now(),c=I({},Ze.__defaultExtensionClasses,this.config.__extensionClasses),d=[];c.exceptions&&this.sn.push(this.exceptions=(n=this.exceptions)!==null&&n!==void 0?n:new c.exceptions(this)),c.historyAutocapture&&this.sn.push(this.historyAutocapture=new c.historyAutocapture(this)),c.tracingHeaders&&this.sn.push(this.tracingHeaders=new c.tracingHeaders(this)),c.siteApps&&this.sn.push(this.siteApps=new c.siteApps(this)),c.sessionRecording&&!e&&this.sn.push(this.sessionRecording=new c.sessionRecording(this)),this.config.disable_scroll_properties||d.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),c.autocapture&&this.sn.push(this.autocapture=new c.autocapture(this)),c.surveys&&this.sn.push(this.surveys=(i=this.surveys)!==null&&i!==void 0?i:new c.surveys(this)),c.logs&&this.sn.push(this.logs=(r=this.logs)!==null&&r!==void 0?r:new c.logs(this)),c.metrics&&this.sn.push(this.metrics=(s=this.metrics)!==null&&s!==void 0?s:new c.metrics(this)),c.conversations&&this.sn.push(this.conversations=(o=this.conversations)!==null&&o!==void 0?o:new c.conversations(this)),c.productTours&&this.sn.push(this.productTours=new c.productTours(this)),c.heatmaps&&this.sn.push(this.heatmaps=new c.heatmaps(this)),c.webVitalsAutocapture&&this.sn.push(this.webVitalsAutocapture=new c.webVitalsAutocapture(this)),c.exceptionObserver&&this.sn.push(this.exceptionObserver=new c.exceptionObserver(this)),c.deadClicksAutocapture&&this.sn.push(this.deadClicksAutocapture=new c.deadClicksAutocapture(this,rm)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((f=>{f.initialize&&d.push((()=>{f.initialize==null||f.initialize()}))})),d.push((()=>{if(this.Nn){var f=this.Nn;this.Nn=void 0,this.sn.forEach((h=>h.onRemoteConfig==null?void 0:h.onRemoteConfig(f)))}})),this.qn(d,u)}qn(e,n){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,n)}),0);var i=e.shift();if(i)try{i()}catch(s){A.error("Error initializing extension:",s)}}var r=Math.round(performance.now()-n);this.register_for_session({[lf]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[cf]:r}),this.config.__preview_deferred_init_extensions&&A.info("PostHog extensions initialized ("+r+"ms)")}Zi(e){var n;if(!P||!P.body)return A.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.Zi(e)}),500);if(this.config.__preview_deferred_init_extensions&&(this.Nn=e),this.hn=e,this.compression=void 0,e.ok){var i,r=e.config;r.supportedCompression&&!this.config.disable_compression&&(this.compression=j(r.supportedCompression,Ue.GZipJS)?Ue.GZipJS:j(r.supportedCompression,Ue.Base64)?Ue.Base64:void 0),(i=r.analytics)!=null&&i.endpoint&&(this.analyticsDefaultEndpoint=r.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:_a}),(n=this.jn)==null||n.handleRemoteConfig(e),this.sn.forEach((s=>s.onRemoteConfig==null?void 0:s.onRemoteConfig(e)))}On(){try{this.config.loaded(this)}catch(i){A.critical("`loaded` function failed",i)}if(this.Bn(),this.config.internal_or_test_user_hostname&&me!=null&&me.hostname){var e=me.hostname,n=this.config.internal_or_test_user_hostname;(typeof n=="string"?e===n:n.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.gn())&&this.Hn()}),1),this.Un=new Lf(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()&&wr(this.__request_queue,(e=>this.Pn(e))),this.__request_queue=[],this.Bn()}_handle_unload(){var e,n,i,r,s;(e=this.surveys)==null||e.handlePageUnload==null||e.handlePageUnload(),(n=this.metrics)==null||n.flush("sendBeacon"),this.config.request_batching?(this.zn()&&this.capture(Eo),(i=this.logs)==null||i.flushLogs("sendBeacon"),(r=this.In)==null||r.unload(),(s=this.Rn)==null||s.unload()):this.zn()&&this.capture(Eo,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?th?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)?e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:429})):(e.transport=e.transport||this.config.api_transport,e.headers=I({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,(C(this.config.disable_beacon)?this.config.__preview_disable_beacon:this.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(n=>{var i,r,s,o=I({},n);o.timeout=o.timeout||6e4;var a,l,u,c,d,f=(i=o.transport)!==null&&i!==void 0?i:"fetch";f==="sendBeacon"&&C(o.compression)&&o.data&&(o.compression=Ue.Base64),o.method==="POST"&&o.data&&(o.timestampMode==="capture-body"?o.data={api_key:(l=(d=(c=U(a=o.data)?a:[a])[0])==null||(u=d.properties)==null?void 0:u.token)!==null&&l!==void 0?l:d?.token,batch:c,sent_at:new Date().toISOString()}:o.timestampMode==="body"&&(o.data=(function(m,v){return v===void 0&&(v=new Date().toISOString()),U(m)?m.map((E=>I({},E,{sent_at:v}))):I({},m,{sent_at:v})})(o.data))),o.url=iu(o.url,o.method,o.compression,o.timestampMode);var h=Br.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),p=(r=(s=(function(m,v){for(var E=0;m.length>E;E++)if(m[E].transport===f)return m[E]})(h))==null?void 0:s.method)!==null&&r!==void 0?r:h[0].method;if(!p)throw new Error("No available transport method");var g=m=>{try{p(m)}catch(v){qf(v)?A.warn(v):A.error(v),o.callback==null||o.callback({statusCode:0,error:v})}};f!=="sendBeacon"&&o.data&&o.compression===Ue.GZipJS&&Up&&typeof Promise<"u"&&!Or?bm(o).then((m=>{g(m)})).catch((m=>{if(Sc(m))return Or=!0,void g(I({},o,{compression:void 0,url:iu(n.url,n.method,void 0,n.timestampMode)}));(v=>{if(!v||typeof v!="object")return!1;var E="name"in v?String(v.name):"";return Sc(v)||E===wd})(m)&&(Or=!0),g(o)})):p(o)})(I({},e,{callback:n=>{var i,r;this.rateLimiter.checkForLimiting(n),400>n.statusCode||(i=(r=this.config).on_request_error)==null||i.call(r,n),e.callback==null||e.callback(n)}}))):e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:0}))}Pn(e){this.Rn?this.Rn.retriableRequest(e):this._send_request(e)}_execute_array(e){Lo++;try{var n,i=[],r=[],s=[];wr(e,(a=>{if(a)if(U(n=a[0]))s.push(a);else if(je(a))try{a.call(this)}catch(l){A.error("Error executing queued PostHog call",a,l)}else U(a)&&n==="alias"?i.push(a):U(a)&&n.indexOf("capture")!==-1&&je(this[n])?s.push(a):r.push(a)}));var o=function(a,l){wr(a,(function(u){try{if(U(u[0])){var c=l;ie(u,(function(d){c=c[d[0]].apply(c,d.slice(1))}))}else l[u[0]].apply(l,u.slice(1))}catch(d){A.error("Error executing queued PostHog call",u,d)}}))};o(i,this),o(r,this),o(s,this)}finally{Lo--}}push(e){if(Lo>0&&U(e)&&X(e[0])){var n=Ze.prototype[e[0]];je(n)&&n.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,n,i){var r,s,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.In){if(this.is_capturing())if(!C(e)&&X(e)){var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var c=i!=null&&i.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(c==null||!c.isRateLimited){n!=null&&n.$current_url&&!X(n?.$current_url)&&(A.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),n==null||delete n.$current_url),e!=="$exception"||i!=null&&i.Wn||A.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,f=i?.timestamp||d,h=Ac(i?.uuid,Ht),p={uuid:h,event:e,properties:this.calculateEventProperties(e,n||{},f,h)};e===Vn&&this.config.__preview_capture_bot_pageviews&&u&&(p.event="$bot_pageview",p.properties.$browser_type="bot"),c&&(p.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&p.properties.$feature_flag_has_experiment===!1&&this.get_property(ts)===!0;i?.$set&&!g&&(p.$set=i?.$set);var m=i?.$unset;m&&(p.$unset=m);var v,E,S,_=g?void 0:this.Vn(i?.$set_once,e!==Mc,e===So);if(_&&(p.$set_once=_),i!=null&&i._noTruncate||(s=this.config.properties_string_max_length,o=p,a=L=>X(L)?L.slice(0,s):L,l=new Set,p=(function L(N,K){if(N!==Object(N))return a?a(N):N;if(!l.has(N)){var V;if(l.add(N),U(N))V=[],wr(N,(R=>{V.push(L(R))}));else{var M={};ie(N,((R,Z)=>{l.has(R)||(M[Z]=L(R))})),V=M}return V}})(o)),p.timestamp=f,C(i?.timestamp)||(p.properties.$event_time_override_provided=!0,p.properties.$event_time_override_system_time=d),g&&(p.properties=(function(L,N){N===void 0&&(N=[]);var K={},V=M=>{L[M]!==void 0&&(K[M]=L[M])};return Hp.forEach(V),N.forEach(V),K})(p.properties,Bm)),e===qt.DISMISSED||e===qt.SENT){var b=n?.[Fo.SURVEY_ID],k=n?.[Fo.SURVEY_ITERATION];Qf({id:b,current_iteration:k}),p.$set=I({},p.$set,{[(v={id:b,current_iteration:k},E=e===qt.SENT?"responded":"dismissed",S="$survey_"+E+"/"+v.id,v.current_iteration&&v.current_iteration>0&&(S="$survey_"+E+"/"+v.id+"/"+v.current_iteration),S)]:!0})}else e===qt.SHOWN&&(p.$set=I({},p.$set,{[Fo.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===hm.SHOWN){var T=n?.[Zc.TOUR_TYPE];T&&(p.$set=I({},p.$set,{[Zc.TOUR_LAST_SEEN_DATE+"/"+T]:new Date().toISOString()}))}var x=I({},p.properties.$set,p.$set);if(Kt(x)||this.setPersonPropertiesForFlags(x),!H(this.config.before_send)){var F=this.Pt(p);if(!F)return;(p=F).uuid=Ac(p.uuid,Ht)}this.dn.emit("eventCaptured",p);var $=(r=i?._url)!==null&&r!==void 0?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),O={method:"POST",url:$,data:p,compression:"best-available",timestampMode:i?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test($)?"body":"capture-body",batchKey:i?._batchKey,transport:i?.transport};return!this.config.request_batching||i&&(i==null||!i._batchKey)||i!=null&&i.send_instantly?this.Pn(O):this.In.enqueue(O),p}A.critical("This capture call is ignored due to client rate limiting.")}}else A.error("No event name provided to posthog.capture")}else A.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(n=>e(n.event,n)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new Om(this)}cn(e){this._n.push(e);var n=!0;return()=>{if(n){n=!1;var i=this._n.indexOf(e);i!==-1&&this._n.splice(i,1)}}}calculateEventProperties(e,n,i,r,s){if(i=i||new Date,!this.persistence||!this.sessionPersistence)return n;var o=s?void 0:this.persistence.remove_event_timer(e),a=I({},n);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.gn()&&(a[af]=!0),e==="$snapshot"){var l=I({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!X(a.distinct_id)&&!ke(a.distinct_id)||Xo(a.distinct_id))&&A.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=(function(b,k,T,x){var F,$,O,L;if(x===void 0&&(x=!1),!Ge)return{};var N,K=b?[...oi,...k||[]]:[],V=(function(Bn){for(var qe=0;kc.length>qe;qe++){var Dn=kc[qe],Mt=Dn[1],Lt=Dn[0].exec(Bn),ut=Lt&&(je(Mt)?Mt(Lt,Bn):Mt);if(ut)return ut}return["",""]})(Ge),M=V[0],R=V[1],Z=(N=typeof navigator<"u"?navigator:void 0)!=null&&N.brave?{brave:!0}:{},Ce={};C(T)||(Ce.detectGoogleSearchApp=T);var oe={},ye=(F=navigator)==null||(F=F.userAgentData)==null?void 0:F.platform,$e=($=navigator)==null?void 0:$.maxTouchPoints,ae=w==null||(O=w.screen)==null?void 0:O.width,Ie=w==null||(L=w.screen)==null?void 0:L.height,Se=w?.devicePixelRatio;C(ye)||(oe.userAgentDataPlatform=ye),C($e)||(oe.maxTouchPoints=$e),C(ae)||(oe.screenWidth=ae),C(Ie)||(oe.screenHeight=Ie),C(Se)||(oe.devicePixelRatio=Se);var De,wt,ge,Je,bt,mn,Re,Pe,$t=fe(hl({$os:M,$os_version:R,$browser:qd(Ge,navigator.vendor,Z,Ce),$device:Cc(Ge),$device_type:(wt=Ge,ge=oe,Pe=Cc(wt),Pe===Cd||Pe===kd||Pe==="Kobo"||Pe==="Kindle Fire"||Pe===jd?ni:Pe===Ji||Pe===Xn||Pe===Zi||Pe===ea?"Console":Pe===Pd?"Wearable":Pe?rt:ge?.userAgentDataPlatform==="Android"&&((Je=ge?.maxTouchPoints)!==null&&Je!==void 0?Je:0)>0?600>Math.min((bt=ge?.screenWidth)!==null&&bt!==void 0?bt:0,(mn=ge?.screenHeight)!==null&&mn!==void 0?mn:0)/((Re=ge?.devicePixelRatio)!==null&&Re!==void 0?Re:1)?rt:ni:"Desktop"),$timezone:Mf(),$timezone_offset:um()}),{$current_url:er(x?fn(me?.href):me?.href,K,tr),$host:me?.host,$pathname:me?.pathname,$raw_user_agent:Ge.length>1e3?Ge.substring(0,997)+"...":Ge,$browser_version:ag(Ge,navigator.vendor,Z,Ce),$browser_language:Jc(),$browser_language_prefix:(De=Jc(),typeof De=="string"?De.split("-")[0]:void 0),$screen_height:w?.screen.height,$screen_width:w?.screen.width,$viewport_height:w?.innerHeight,$viewport_width:w?.innerWidth,$lib:ne.LIB_NAME,$lib_version:ne.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return ne.SDK_DIST_CHANNEL&&($t.$sdk_dist_channel=ne.SDK_DIST_CHANNEL),$t})(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties,this.config.detect_google_search_app,this.config.disable_capture_url_hashes);if(this.sessionManager){var d=this.sessionManager.checkAndGetSessionAndWindowId(s,i.getTime()),f=d.windowId;a.$session_id=d.sessionId,a.$window_id=f}this.sessionPropsManager&&fe(a,this.sessionPropsManager.getSessionProps());try{var h;this.sessionRecording&&fe(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(h=this.Rn)==null?void 0:h.length}catch(b){a.$sdk_debug_error_capturing_properties=String(b)}if(this.requestRouter.region===Aa&&(a.$lib_custom_api_host=this.config.api_host),u=e!==Vn||s?e!==Eo||s?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(i):this.pageViewManager.doPageView(i,r),a=fe(a,u),e===Vn&&P&&(a.title=P.title),!C(o)){var p=i.getTime()-o;a.$duration=parseFloat((p/1e3).toFixed(3))}Ge&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();ie(["$referrer","$referring_domain"],(b=>{b in g&&delete m[b]}));var v={};if(this._n.length>0)for(var E of this._n.slice())try{fe(v,E())}catch(b){A.error("Failed to produce browser extension event properties",b)}(a=fe({},c,g,m,I({},v,a))).$is_identified=this._isIdentified(),U(this.config.property_denylist)?ie(this.config.property_denylist,(function(b){delete a[b]})):A.error(eh+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var S=this.config.sanitize_properties;S&&(A.error(cu),a=S(a,e));var _=this.Zn();return a.$process_person_profile=_,_&&!s&&this.Gn("_calculate_event_properties"),a}Vn(e,n,i){var r;if(n===void 0&&(n=!0),i===void 0&&(i=!1),!this.persistence||!this.Zn()||this.mn&&!i)return e;var s=this.persistence.get_initial_props(),o=(r=this.sessionPropsManager)==null?void 0:r.getSetOnceProps(),a=fe({},s,o||{},e||{}),l=this.config.sanitize_properties;return l&&(A.error(cu),a=l(a,"$set_once")),n&&(this.mn=!0),Kt(a)?void 0:a}register(e,n){var i;(i=this.persistence)==null||i.register(e,n)}register_once(e,n,i){var r;(r=this.persistence)==null||r.register_once(e,n,i)}register_for_session(e){var n;(n=this.sessionPersistence)==null||n.register(e),Object.keys(e).forEach((i=>this.yn.add(i))),this.Qn()}unregister(e){var n;(n=this.persistence)==null||n.unregister(e)}unregister_for_session(e){var n;(n=this.sessionPersistence)==null||n.unregister(e),this.yn.delete(e),this.Qn()}Kn(e,n){this.register({[e]:n})}An(){this.yn.forEach((e=>{var n;(n=this.sessionPersistence)==null||n.unregister(e)})),this.yn.clear(),this.Qn()}Qn(){var e;if(this.bn)if(this.config.persistence==="memory"||(e=this.sessionPersistence)!=null&&e.xi||!be.N())be.q(this.bn);else{var n=[];this.yn.forEach((i=>n.push(i))),n.length>0?be.F(this.bn,n):be.q(this.bn)}}getFeatureFlag(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlag(e,n)}getFeatureFlagPayload(e){var n;return(n=this.featureFlags)==null?void 0:n.getFeatureFlagPayload(e)}getFeatureFlagResult(e,n){var i;return(i=this.featureFlags)==null?void 0:i.getFeatureFlagResult(e,n)}getAllFeatureFlags(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.getAllFeatureFlags())!==null&&e!==void 0?e:[]}isFeatureEnabled(e,n){var i,r;return(i=(r=this.featureFlags)==null?void 0:r.isFeatureEnabled(e,n))!==null&&i!==void 0?i:n?.defaultValue}reloadFeatureFlags(){var e;(e=this.featureFlags)==null||e.reloadFeatureFlags()}updateFlags(e,n,i){var r;(r=this.featureFlags)==null||r.updateFlags(e,n,i)}updateEarlyAccessFeatureEnrollment(e,n,i){var r;(r=this.featureFlags)==null||r.updateEarlyAccessFeatureEnrollment(e,n,i)}getEarlyAccessFeatures(e,n,i){var r;return n===void 0&&(n=!1),(r=this.featureFlags)==null?void 0:r.getEarlyAccessFeatures(e,n,i)}on(e,n){return this.dn.on(e,n)}onFeatureFlags(e){return this.featureFlags?this.featureFlags.onFeatureFlags(e):(e([],{},{errorsLoading:!0}),()=>{})}onSurveysLoaded(e){return this.surveys?this.surveys.onSurveysLoaded(e):(e([],{isLoaded:!1,error:Ci}),()=>{})}onSessionId(e){var n,i;return(n=(i=this.sessionManager)==null?void 0:i.onSessionId(e))!==null&&n!==void 0?n:()=>{}}getSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getSurveys(e,n):e([],{isLoaded:!1,error:Ci})}getActiveMatchingSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,n):e([],{isLoaded:!1,error:Ci})}renderSurvey(e,n){var i;(i=this.surveys)==null||i.renderSurvey(e,n)}displaySurvey(e,n){var i;n===void 0&&(n=Rm),(i=this.surveys)==null||i.displaySurvey(e,n)}cancelPendingSurvey(e){var n;(n=this.surveys)==null||n.cancelPendingSurvey(e)}canRenderSurvey(e){var n,i;return(n=(i=this.surveys)==null?void 0:i.canRenderSurvey(e))!==null&&n!==void 0?n:{visible:!1,disabledReason:Ci}}canRenderSurveyAsync(e,n){var i,r;return n===void 0&&(n=!1),(i=(r=this.surveys)==null?void 0:r.canRenderSurveyAsync(e,n))!==null&&i!==void 0?i:Promise.resolve({visible:!1,disabledReason:Ci})}Jn(e){return!e||Xo(e)?(A.critical("Unique user id has not been set in posthog.identify"),!1):e===yr?(A.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.'),!1):!["distinct_id","distinctid"].includes(e.toLowerCase())&&!["undefined","null"].includes(e.toLowerCase())||(A.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.'),!1)}identify(e,n,i){if(!this.__loaded||!this.persistence)return A.uninitializedWarning("posthog.identify");if(ke(e)&&(e=e.toString(),A.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.Jn(e)&&this.Gn("posthog.identify")){var r=this.get_distinct_id();this.register({$user_id:e}),this.get_property(Xi)||this.register_once({$had_persisted_distinct_id:!0,$device_id:r},""),e!==r&&e!==this.get_property($i)&&(this.unregister($i),this.register({distinct_id:e}));var s,o=(this.persistence.get_property(at)||Un)===Un,a=e!==r,l=!a&&o;if(a&&o)this.persistence.set_property(at,vn),this.setPersonPropertiesForFlags({$set:n||{},$set_once:i||{}},!1),this.capture(So,{distinct_id:e,$anon_distinct_id:r},{$set:n||{},$set_once:i||{}}),this.Sn=Mo(e,n,i),(s=this.featureFlags)==null||s.setAnonymousDistinctId(r);else if(l){this.persistence.set_property(at,vn);var u=n||{},c=i||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=Mo(e,n,i)}else(n||i)&&this.setPersonProperties(n,i);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Cn)):l&&(n||i)&&this.reloadFeatureFlags()}}setPersonProperties(e,n){if((e||n)&&this.Gn("posthog.setPersonProperties")){var i=Mo(this.get_distinct_id(),e,n);this.Sn!==i?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:n||{}},!0),this.capture("$set",{$set:e||{},$set_once:n||{}}),this.Sn=i):A.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}unsetPersonProperties(e){var n,i=(U(e)?e:[e]).filter((r=>X(r)&&r.length>0));i.length!==0&&this.Gn("posthog.unsetPersonProperties")&&((n=this.featureFlags)==null||n.unsetPersonPropertiesForFlags(i,!0),this.capture("$set",{$unset:i}),this.Sn=null)}group(e,n,i){if(e&&n){var r=this.getGroups(),s=r[e]!==n;if(s&&this.resetGroupPropertiesForFlags(e),this.register({$groups:I({},r,{[e]:n})}),s||i){var o={$group_type:e,$group_key:n};i&&(o.$group_set=i),this.capture(Mc,o)}i&&this.setGroupPropertiesForFlags({[e]:i}),s&&!i&&this.reloadFeatureFlags()}else A.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),(i=this.featureFlags)==null||i.setPersonPropertiesForFlags(e,n)}resetPersonPropertiesForFlags(e){var n;e===void 0&&(e=!0),(n=this.featureFlags)==null||n.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((i=this.featureFlags)==null||i.setGroupPropertiesForFlags(e,n))}resetGroupPropertiesForFlags(e){var n;(n=this.featureFlags)==null||n.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,n){var i,r,s,o,a,l,u,c,d,f;if(n===void 0&&(n=!1),A.info("reset"),!this.__loaded)return A.uninitializedWarning("posthog.reset");var h,p=this.get_property(Xi),g=this.get_property(bo),m=this.get_property(An),v=this.is_capturing();if(this.consent.reset(),n||!v||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after."),(i=this.persistence)==null||i.clear(),(r=this.sessionPersistence)==null||r.clear(),this.yn.clear(),this.Qn(),C(m)||(h=this.persistence)==null||h.register({[An]:m}),(s=this.surveys)==null||s.reset(),(o=this.Un)==null||o.stop(),(a=this.featureFlags)==null||a.reset(),(l=this.conversations)==null||l.reset(),(u=this.logs)==null||u.reset(),(c=this.metrics)==null||c.reset(),(d=this.persistence)==null||d.set_property(at,Un),(f=this.sessionManager)==null||f.resetSessionId(),this.Sn=null,this.config.cookieless_mode===Wt)this.register_once({distinct_id:yr,$device_id:null},"");else{var E=this.config.get_device_id(Ht());this.register_once({distinct_id:E,$device_id:e?E:p},""),e||C(g)||this.register({[bo]:g})}this.register({$last_posthog_reset:new Date().toISOString()},1),delete this.config.identity_distinct_id,delete this.config.identity_hash,this.reloadFeatureFlags()}shutdown(e){var n=this;return se((function*(){var i,r,s,o,a,l,u;if(n.__loaded){(i=n.Un)==null||i.stop(),(r=n.jn)==null||r.dispose(),(s=n.sessionRecording)==null||s.dispose(),(o=n.logs)==null||o.flushLogs("sendBeacon"),(a=n.metrics)==null||a.flush("sendBeacon"),(l=n.In)==null||l.unload(),(u=n.Rn)==null||u.unload();try{var c;(c=n.featureFlags)==null||c.destroy()}catch(d){A.error("Error while destroying feature flags",d)}}else A.uninitializedWarning("posthog.shutdown")}))()}setIdentity(e,n){var i;this.config.identity_distinct_id=e,this.config.identity_hash=n,this.alias(e),(i=this.conversations)==null||i.Xn()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,(e=this.conversations)==null||e.ts()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,n;return(e=(n=this.sessionManager)==null?void 0:n.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var n=this.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.sessionStartTimestamp,r=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+n.sessionId);if(e!=null&&e.withTimestamp&&i){var s,o=(s=e.timestampLookBack)!==null&&s!==void 0?s:10;if(!i)return r;r+="?t="+Math.max(Math.floor((new Date().getTime()-i)/1e3)-o,0)}return r}alias(e,n){return e===this.get_property(ef)?(A.critical("Attempting to create alias for existing People user - aborting."),-2):this.Gn("posthog.alias")?(C(n)&&(n=this.get_distinct_id()),e!==n?(this.Kn($i,e),this.capture("$create_alias",{alias:e,distinct_id:n})):(A.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var n=I({},this.config);if(he(e)){var i,r,s,o,a,l,u,c,d,f,h,p;fe(this.config,uu(e));var g=this.En();(i=this.persistence)==null||i.update_config(this.config,n,g),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Ao(I({},this.config,{persistence:"sessionStorage"}),g,!1);var m=this.Cn(this.config.debug);mt(m)&&(this.config.debug=m),mt(this.config.debug)&&(this.config.debug?(ne.DEBUG=!0,le.N()&&le.F("ph_debug",!0),A.info("set_config",{config:e,oldConfig:n,newConfig:I({},this.config)})):(ne.DEBUG=!1,le.N()&&le.q("ph_debug"))),(r=this.featureFlags)==null||r.updateConfig==null||r.updateConfig(this.config,this.Qi()),(s=this.exceptionObserver)==null||s.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(f=this.deadClicksAutocapture)==null||f.startIfEnabledOrStop(),(h=this.surveys)==null||h.loadIfEnabled(),this.es(),(p=this.externalIntegrations)==null||p.startIfEnabledOrStop()}}_overrideSDKInfo(e,n){ne.LIB_NAME=e,ne.LIB_VERSION=n}startSessionRecording(e){var n,i,r,s,o,a=e===!0,l={sampling:a||!(e==null||!e.sampling),linked_flag:a||!(e==null||!e.linked_flag),url_trigger:a||!(e==null||!e.url_trigger),event_trigger:a||!(e==null||!e.event_trigger)};Object.values(l).some(Boolean)&&((n=this.sessionManager)==null||n.checkAndGetSessionAndWindowId(),l.sampling&&((i=this.sessionRecording)==null||i.overrideSampling()),l.linked_flag&&((r=this.sessionRecording)==null||r.overrideLinkedFlag()),l.url_trigger&&((s=this.sessionRecording)==null||s.overrideTrigger("url")),l.event_trigger&&((o=this.sessionRecording)==null||o.overrideTrigger("event"))),this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,n){if(this.exceptions){var i=new Error("PostHog syntheticException"),r=this.exceptions.buildProperties(e,{handled:!0,syntheticException:i});return this.exceptions.sendExceptionEvent(I({},r,n))}}addExceptionStep(e,n){var i;(i=this.exceptions)==null||i.addExceptionStep(e,n)}captureLog(e){var n;(n=this.logs)==null||n.captureLog(e)}get logger(){var e,n;return(e=(n=this.logs)==null?void 0:n.logger)!==null&&e!==void 0?e:Ze.rs}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var n,i;return(n=(i=this.toolbar)==null?void 0:i.loadToolbar(e))!==null&&n!==void 0&&n}get_property(e){var n;return(n=this.persistence)==null?void 0:n.props[e]}getSessionProperty(e){var n;return(n=this.sessionPersistence)==null?void 0:n.props[e]}toString(){var e,n=(e=this.config.name)!==null&&e!==void 0?e:Gn;return n!==Gn&&(n=Gn+"."+n),n}_isIdentified(){var e,n;return((e=this.persistence)==null?void 0:e.get_property(at))===vn||((n=this.sessionPersistence)==null?void 0:n.get_property(at))===vn}Zn(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles===_a&&!this._isIdentified()&&Kt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[$i])&&((n=this.persistence)==null||(n=n.props)==null||!n[rs]))}zn(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Zn()||this.Gn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.Gn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}Gn(e){return this.config.person_profiles==="never"?(A.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Kn(rs,!0),!0)}En(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut();return this.config.disable_persistence||e&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!==kn)}es(){var e,n,i,r,s=this.En();return((e=this.persistence)==null?void 0:e.xi)!==s&&((i=this.persistence)==null||i.set_disabled(s)),((n=this.sessionPersistence)==null?void 0:n.xi)!==s&&((r=this.sessionPersistence)==null||r.set_disabled(s)),s&&(this.yn.clear(),this.Qn()),s}opt_in_capturing(e){var n;if(this.config.cookieless_mode!==Wt){if(this.gn()){var i,r,s,o,a;this.Yn(!0,!0),(i=this.sessionManager)==null||i.destroy(),(r=this.pageViewManager)==null||r.destroy(),this.sessionManager=new su(this),this.pageViewManager=new Yc(this),this.persistence&&(this.sessionPropsManager=new ru(this,this.sessionManager,this.persistence));var l,u=(s=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&s!==void 0?s:(a=Ze.__defaultExtensionClasses)==null?void 0:a.sessionRecording;u&&(this.sessionRecording=this.pn(this.sessionRecording,new u(this)),this.hn&&((l=this.sessionRecording)==null||l.onRemoteConfig==null||l.onRemoteConfig(this.hn)))}var c,d;this.consent.optInOut(!0),this.es(),this.Bn(),(n=this.sessionRecording)==null||n.startIfEnabledOrStop(),this.config.cookieless_mode==kn&&((c=this.surveys)==null||c.loadIfEnabled()),(C(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((d=e?.captureEventName)!==null&&d!==void 0?d:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hn()}else A.warn(lu)}opt_out_capturing(){var e,n,i;this.config.cookieless_mode!==Wt?(this.config.cookieless_mode===kn&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===kn&&(this.register({distinct_id:yr,$device_id:null}),(e=this.sessionRecording)==null||e.stopRecording(),this.sessionRecording=void 0,(n=this.sessionManager)==null||n.destroy(),(i=this.pageViewManager)==null||i.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.Hn(),this.Bn())):A.warn(lu)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===Wt||(this.config.cookieless_mode===kn?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return He?Gf(He,this.config.custom_blocked_useragents):void 0}Hn(){P&&(P.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(Vn,{title:P.title},{send_instantly:!0}),this.kn&&(P.removeEventListener(ss,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),ve(P,ss,this.kn)))}debug(e){e===!1?(w?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(w?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}Qi(){var e=this.Mn||{};return"advanced_disable_flags"in e?!!e.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(A.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(function(n,i,r,s,o){var a=i in n&&!H(n[i]),l=r in n&&!H(n[r]);return a?n[i]:!!l&&(o&&o.warn("Config field '"+r+"' is deprecated. Please use '"+i+"' instead. The old field will be removed in a future major version."),n[r])})(e,"advanced_disable_flags","advanced_disable_decide",0,A)}Pt(e){var n;if(H(this.config.before_send))return e;var i=Object.keys((n=e.properties)!==null&&n!==void 0?n:{}).filter(Yp),r=U(this.config.before_send)?this.config.before_send:[this.config.before_send],s=e;for(var o of r){if(s=o(s),H(s)){var a="Event '"+e.event+"' was rejected in beforeSend function";return Kp(e.event)?A.warn(a+". This can cause unexpected behavior."):A.info(a),null}s.properties&&!Kt(s.properties)||A.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}for(var l of i)if(s.properties&&H(s.properties[l]))return A.warn("Event '"+e.event+"' had its '"+l+"' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped."),null;return s}getPageViewId(){var e;return(e=this.pageViewManager.ui)==null?void 0:e.pageViewId}captureTraceFeedback(e,n){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:n})}captureTraceMetric(e,n,i){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:n,$ai_metric_value:String(i)})}Cn(e){var n=mt(e)&&!e,i=le.N()&&le.P("ph_debug")==="true";return!n&&(!!i||e)}}Ze.__defaultExtensionClasses={},Ze.rs=(()=>{var t=()=>{};return{trace:t,debug:t,info:t,warn:t,error:t,fatal:t}})(),(function(t,e){for(var n=0;e.length>n;n++)t.prototype[e[n]]=Og(t.prototype[e[n]])})(Ze,["identify"]);class du{constructor(e){this.disabled=e===!1;var n=he(e)?e:{};this.thresholdPx=n.threshold_px||30,this.timeoutMs=n.timeout_ms||1e3,this.clickCount=n.click_count||3,this.clicks=[]}isRageClick(e,n,i){if(this.disabled)return!1;var r=this.clicks[this.clicks.length-1];if(r&&Math.abs(e-r.x)+Math.abs(n-r.y)i-r.timestamp){if(this.clicks.push({x:e,y:n,timestamp:i}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:n,timestamp:i}];return!1}}var Oo="$copy_autocapture",Bo=pe("[AutoCapture]");function Do(t,e){return e.length>t?e.slice(0,t)+"...":e}function Um(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!hn(e));return e}function Hm(t,e){var n,i,r=e.e,s=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!hn(t))return{props:{}};for(var c=[t],d=new Set([t]),f=t;f.parentNode&&!et(f,"body")&&vf>c.length;)if(mf(f.parentNode)){var h=f.parentNode.host;if(d.has(h))break;d.add(h),c.push(h),f=h}else{if(!hn(f.parentNode)||d.has(f.parentNode))break;d.add(f.parentNode),c.push(f.parentNode),f=f.parentNode}var p,g,m=[],v={},E=!1,S=!1;if(ie(c,(x=>{var F=ba(x);if(et(x,"a")){var $=x.getAttribute("href");E=!!(F&&$&&zi($))&&(u?fn($):$)}j(ls(x),"ph-no-capture")&&(S=!0),m.push((function(L,N,K,V,M){M===void 0&&(M=!1);var R=L.tagName.toLowerCase(),Z={tag_name:R};gl.indexOf(R)>-1&&!K&&(Z.$el_text=R.toLowerCase()==="a"||R.toLowerCase()==="button"?Do(1024,Vc(L)):Do(1024,Qi(L)));var Ce=ls(L);Ce.length>0&&(Z.classes=Ce.filter((function(ae){return ae!==""}))),ie(L.attributes,(function(ae){var Ie;if((!Ef(L)||["name","id","class","aria-label"].indexOf(ae.name)!==-1)&&(V==null||!V.includes(ae.name))&&!N&&zi(ae.value)&&(!X(Ie=ae.name)||Ie.substring(0,10)!=="_ngcontent"&&Ie.substring(0,7)!=="_nghost")){var Se=ae.value;ae.name==="class"&&(Se=pl(Se).join(" ")),Z["attr__"+ae.name]=Do(1024,ae.name==="href"&&M?fn(Se):Se)}}));for(var oe=1,ye=1,$e=L;$e=Um($e);)oe++,$e.tagName===L.tagName&&ye++;return Z.nth_child=oe,Z.nth_of_type=ye,Z})(x,s,o,a,u));var O=(function(L){if(!ba(L))return{};var N={};return ie(L.attributes,(function(K){if(K.name&&K.name.indexOf("data-ph-capture-attribute")===0){var V=K.name.replace("data-ph-capture-attribute-",""),M=K.value;V&&M&&zi(M)&&(N[V]=M)}})),N})(x);fe(v,O)})),S)return{props:{},explicitNoCapture:S};if(o||(m[0].$el_text=et(t,"a")||et(t,"button")?Vc(t):Qi(t)),E){var _,b;m[0].attr__href=E;var k=(_=cs(E))==null?void 0:_.host,T=w==null||(b=w.location)==null?void 0:b.host;k&&T&&k!==T&&(p=E)}return{props:fe({$event_type:r.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(x){return x.map((F=>{var $,O,L="";if(F.tag_name&&(L+=F.tag_name),F.attr_class)for(var N of(F.attr_class.sort(),F.attr_class))L+="."+N.replace(/"/g,"");var K=I({},F.text?{text:F.text}:{},{"nth-child":($=F.nth_child)!==null&&$!==void 0?$:0,"nth-of-type":(O=F.nth_of_type)!==null&&O!==void 0?O:0},F.href?{href:F.href}:{},F.attr_id?{attr_id:F.attr_id}:{},F.attributes),V={};return Nr(K).sort(((M,R)=>M[0].localeCompare(R[0]))).forEach((M=>{var R=M[1];return V[Gc(M[0].toString())]=Gc(R.toString())})),(L+=":")+Nr(V).map((M=>M[0]+'="'+M[1]+'"')).join("")})).join(";")})((function(x){return x.map((F=>{var $,O,L={text:($=F.$el_text)==null?void 0:$.slice(0,400),tag_name:F.tag_name,href:(O=F.attr__href)==null?void 0:O.slice(0,2048),attr_class:nm(F),attr_id:F.attr__id,nth_child:F.nth_child,nth_of_type:F.nth_of_type,attributes:{}};return Nr(F).filter((N=>N[0].indexOf("attr__")===0)).forEach((N=>L.attributes[N[0]]=N[1])),L}))})(g)))},(n=m[0])!=null&&n.$el_text?{$el_text:(i=m[0])==null?void 0:i.$el_text}:{},p&&r.type==="click"?{$external_click_url:p}:{},v)}}var Ai=pe("[ExceptionAutocapture]"),fu=()=>{},Wm=pe("[TracingHeaders]"),wn=pe("[Web Vitals]"),hu=9e5,pu="disabled",gu="lazy_loading",Pi="awaiting_config",kr="missing_config";pe("[SessionRecording]"),pe("[SessionRecording]");var Pa="[SessionRecording]",Bt=pe(Pa),zm=pe("[Heatmaps]");function jo(t){return he(t)&&"clientX"in t&&"clientY"in t&&ke(t.clientX)&&ke(t.clientY)}var Cr=pe("[Product Tours]"),Uo=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(ul))},qm=["$set_once","$set"],Et=pe("[SiteApps]"),mu="Error while initializing PostHog app with config id ";function zn(t,e,n){if(H(t))return!1;switch(n){case"exact":return t===e;case"contains":var i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(i,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}class Vm{constructor(e){this.ns=new yl,this.ss=(n,i)=>this.os(n,i)&&this.ls(n,i)&&this.us(n,i)&&this.hs(n,i),this.os=(n,i)=>i==null||!i.event||n?.event===i?.event,this._instance=e,this.ds=new Set,this.vs=new Set}init(){var e,n;C((e=this._instance)==null?void 0:e._addCaptureHook)||(n=this._instance)==null||n._addCaptureHook(((i,r)=>{this.on(i,r)}))}register(e){var n,i;if(!C((n=this._instance)==null?void 0:n._addCaptureHook)&&(e.forEach((o=>{var a,l;(a=this.vs)==null||a.add(o),(l=o.steps)==null||l.forEach((u=>{var c;(c=this.ds)==null||c.add(u?.event||"")}))})),(i=this._instance)!=null&&i.autocapture)){var r,s=new Set;e.forEach((o=>{var a;(a=o.steps)==null||a.forEach((l=>{l!=null&&l.selector&&s.add(l?.selector)}))})),(r=this._instance)==null||r.autocapture.setElementSelectors(s)}}on(e,n){var i;n!=null&&e.length!=0&&(this.ds.has(e)||this.ds.has(n.event))&&this.vs&&((i=this.vs)==null?void 0:i.size)>0&&this.vs.forEach((r=>{this.cs(n,r)&&this.ns.emit("actionCaptured",r.name)}))}fs(e){this.onAction("actionCaptured",(n=>e(n)))}cs(e,n){if(n?.steps==null)return!1;for(var i of n.steps)if(this.ss(e,i))return!0;return!1}onAction(e,n){return this.ns.on(e,n)}ls(e,n){if(n!=null&&n.url){var i,r=e==null||(i=e.properties)==null?void 0:i.$current_url;if(!r||typeof r!="string"||!zn(r,n.url,n.url_matching||"contains"))return!1}return!0}us(e,n){return!!this.ps(e,n)&&!!this.gs(e,n)&&!!this.ys(e,n)}ps(e,n){var i;if(n==null||!n.href)return!0;var r=this.bs(e);if(r.length>0)return r.some((a=>zn(a.href,n.href,n.href_matching||"exact")));var s,o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!o&&zn((s=o.match(/(?::|")href="(.*?)"/))?s[1]:"",n.href,n.href_matching||"exact")}gs(e,n){var i;if(n==null||!n.text)return!0;var r=this.bs(e);if(r.length>0)return r.some((u=>zn(u.text,n.text,n.text_matching||"exact")||zn(u.$el_text,n.text,n.text_matching||"exact")));var s,o,a,l=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!l&&(s=(function(u){for(var c,d=[],f=/(?::|")text="(.*?)"/g;!H(c=f.exec(u));)d.includes(c[1])||d.push(c[1]);return d})(l),o=n.text,a=n.text_matching||"exact",s.some((u=>zn(u,o,a))))}ys(e,n){var i,r;if(n==null||!n.selector)return!0;var s=e==null||(i=e.properties)==null?void 0:i.$element_selectors;if(s!=null&&s.includes(n.selector))return!0;var o=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";if(n.selector_regex&&o)try{return new RegExp(n.selector_regex).test(o)}catch{return!1}return!1}bs(e){var n;return(e==null||(n=e.properties)==null?void 0:n.$elements)==null?[]:e?.properties.$elements}hs(e,n){return n==null||!n.properties||n.properties.length===0||Jf(n.properties.reduce(((i,r)=>{var s=U(r.value)?r.value.map(String):r.value!=null?[String(r.value)]:[];return i[r.key]={values:s,operator:r.operator||"exact"},i}),{}),e?.properties)}}class Gm{constructor(e){var n;this._s=[],this._instance=e,this.ws=new Map,this.ks=new Map,this.xs=new Map,(n=this._instance)==null||n.onSessionId==null||n.onSessionId((i=>this.Ss(i)))}Cs(e){return!1}Ms(){return null}Ts(e){}Es(){}Is(e,n){return!!e&&Jf(e.propertyFilters,n?.properties)}Ps(e,n){var i=new Map;return e.forEach((r=>{var s;(s=r.conditions)==null||(s=s[n])==null||(s=s.values)==null||s.forEach((o=>{if(o!=null&&o.name){var a=i.get(o.name)||[];a.push(r.id),i.set(o.name,a)}}))})),i}Rs(e,n,i){var r=(i===Si.Activation?this.ws:this.ks).get(e),s=[];return this.As((o=>{s=o.filter((a=>r?.includes(a.id)))})),s.filter((o=>{var a,l=(a=o.conditions)==null||(a=a[i])==null||(a=a.values)==null?void 0:a.find((u=>u.name===e));return this.Is(l,n)}))}register(e){var n;C((n=this._instance)==null?void 0:n._addCaptureHook)||(this.Fs(e),this.Ls(e))}Ls(e){var n=e.filter((i=>{var r,s;return((r=i.conditions)==null?void 0:r.actions)&&((s=i.conditions)==null||(s=s.actions)==null||(s=s.values)==null?void 0:s.length)>0}));n.length!==0&&(this.Os==null&&(this.Os=new Vm(this._instance),this.Os.init(),this.Os.fs((i=>{this.onAction(i)}))),n.forEach((i=>{var r,s,o,a,l;i.conditions&&(r=i.conditions)!=null&&r.actions&&(s=i.conditions)!=null&&(s=s.actions)!=null&&s.values&&((o=i.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.Os)==null||a.register(i.conditions.actions.values),(l=i.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var c=this.xs.get(u.name);c&&c.push(i.id),this.xs.set(u.name,c||[i.id])}})))})))}Fs(e){var n,i=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.events)&&((a=s.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0})),r=e.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.cancelEvents)&&((a=s.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0}));i.length===0&&r.length===0||((n=this._instance)==null||n._addCaptureHook(((s,o)=>{this.onEvent(s,o)})),this.ws=this.Ps(e,Si.Activation),this.ks=this.Ps(e,Si.Cancellation))}onEvent(e,n){var i,r,s=this.Ds(),o=(n==null||(i=n.properties)==null?void 0:i.$survey_id)||(n==null||(r=n.properties)==null?void 0:r.$product_tour_id);if(o&&this.getActivatedIds().includes(o)){var a=this.$s(e,o);if(a==="consume")return s.info("event consumed activated item, removing it",{event:e,itemId:o}),void this.Ns([o]);if(a==="persist")return s.info("shown item promoted to persisted activation",{event:e,itemId:o}),this.qs(o),void this.js([o])}if(this.ks.has(e)){var l=this.Rs(e,n,Si.Cancellation);l.length>0&&(s.info("cancel event matched, cancelling items",{event:e,itemsToCancel:l.map((c=>c.id))}),this.Ns(l.map((c=>c.id))),l.forEach((c=>this.Bs(c.id))))}if(this.ws.has(e)){s.info("event name matched",{event:e,eventPayload:n,items:this.ws.get(e)});var u=this.Rs(e,n,Si.Activation);this.Hs(u.map((c=>c.id)))}}onAction(e){this.xs.has(e)&&this.Hs(this.xs.get(e)||[])}Hs(e){var n;if(e.length!==0){var i=!((n=this._instance)==null||n.get_session_id==null||!n.get_session_id()),r=[];for(var s of e)i&&this.Cs(s)?this.qs(s)&&this.Us(s):r.push(s);r.length>0&&(this._s=[...new Set([...this._s,...r])]),this.Ds().info("updating activated items",{activatedItems:this.getActivatedIds()})}}qs(e){this._s=this._s.filter((i=>i!==e));var n=this.zs();return!n.includes(e)&&(this.Ws([...n,e]),this.Vs(),!0)}Ns(e){var n=new Set(e);this._s=this._s.filter((s=>!n.has(s)));var i=this.Zs(),r=i.filter((s=>!n.has(s)));r.length!==i.length&&(this.Ws(r),r.length===0&&this.Gs()),this.js(e)}Qs(){var e,n=this.Ms();if(!n)return{};var i=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n];return i&&typeof i=="object"?i:{}}Us(e){if(this.Ms()){var n=this.Qs();this.Ts(I({},n,{[e]:Date.now()}))}}js(e){if(this.Ms()){var n=this.Qs(),i={},r=!1;for(var s of Object.entries(n)){var o=s[0],a=s[1];e.includes(o)?r=!0:i[o]=a}r&&(Kt(i)?this.Es():this.Ts(i))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var n=this.Qs()[e];return ke(n)?n:void 0}}Zs(){var e,n=this.Js();return((e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n])||[]}zs(){var e,n,i=this.Zs();if(i.length===0)return[];var r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[this.Ys()],s=(n=this._instance)==null||n.get_session_id==null?void 0:n.get_session_id();return s&&r===s?i:[]}Vs(){var e,n=(e=this._instance)==null||e.get_session_id==null?void 0:e.get_session_id();n&&this.Xs(n)}Gs(){this.ta()}Ss(e){var n,i=(n=this._instance)==null||(n=n.persistence)==null?void 0:n.props[this.Ys()];if(i&&i!==e){var r=this.Zs(),s=this.Qs();r.length>0&&(this.Ws([]),r.filter((o=>ke(s[o]))).forEach((o=>this.Bs(o)))),this.Gs(),this.Ks()}}getActivatedIds(){return[...new Set([...this.zs(),...this._s])].filter((e=>!this.ea(e)))}reset(){this._s=[],this.Zs().length>0&&this.Ws([]),this.Gs(),this.Ks()}getEventToItemsMap(){return this.ws}ia(){return this.Os}}class Km extends Gm{constructor(e){super(e)}Js(){return ha}Ys(){return $r}Ms(){return Mr}Ts(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Mr]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Mr)}Cs(e){var n,i;this.As((s=>{i=s.find((o=>o.id===e))}));var r=(n=i)==null||(n=n.appearance)==null?void 0:n.surveyPopupDelaySeconds;return ke(r)&&r>0}ra(){return qt.SHOWN}As(e){var n;(n=this._instance)==null||n.getSurveys(e)}Bs(e){var n;(n=this._instance)==null||n.cancelPendingSurvey(e)}Ds(){return Q}Ws(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[ha]:e})}Xs(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[$r]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister($r)}ea(){return!1}$s(e,n){var i;this.As((s=>{i=s.find((o=>o.id===n))}));var r=!i||(function(s){var o;return Zf(s)&&!((o=s.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||s.schedule==="always"})(i);return r?e===qt.SHOWN?"consume":"ignore":e===qt.SHOWN?"persist":e===qt.DISMISSED||e===qt.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var Ar="SDK is not enabled or survey functionality is not yet loaded",vu="Disabled. Not loading surveys.",Ym=w!=null&&w.location?us(w.location.hash,"__posthog")||us(location.hash,"state"):null,_u="_postHogToolbarParams",yu=pe("[Toolbar]"),wu=pe("[FeatureFlags]");class Jm{constructor(e,n){n===void 0&&(n=!1),this.na=!1,this.update(e,n)}update(e,n){this.sa=((i,r)=>{var s,o,a,l;return{bootstrap:{featureFlags:(s=i.bootstrap)==null?void 0:s.featureFlags,featureFlagPayloads:(o=i.bootstrap)==null?void 0:o.featureFlagPayloads},remoteRequestsDisabled:r,featureFlagsDisabled:!!i.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!i.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!i.advanced_feature_flags_dedup_per_session,cacheTtlMs:i.feature_flag_cache_ttl_ms,requestTimeoutMs:i.feature_flag_request_timeout_ms,compression:i.disable_compression?"none":"base64",evaluationContexts:(a=(l=i.evaluation_contexts)!==null&&l!==void 0?l:i.evaluation_environments)!==null&&a!==void 0?a:[],flagKeys:U(i.flag_keys)?i.flag_keys:void 0}})(e,n),!e.evaluation_environments||e.evaluation_contexts||this.na||(wu.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.na=!0),C(e.flag_keys)||U(e.flag_keys)||wu.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var bu=pe("[FeatureFlags]"),bn=pe("[FeatureFlags]",{debugEnabled:!0}),Ho=`" failed. Feature flags didn't load in time.`,Eu="connection_error",Su=t=>{for(var e={},n=0;t.length>n;n++)e[t[n]]=!0;return e},xu=t=>{var e={};for(var n of Nr(t||{})){var i=n[1];i&&(e[n[0]]=i)}return e},St=pe("[Error tracking]"),Iu="Refusing to render web experiment since the viewer is a likely bot",Zm={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>hs(e,t),not_regex:(t,e)=>!hs(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class Me{get Ne(){return this._instance.config}constructor(e){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(i){i===void 0&&(i=!1),n.getWebExperiments((r=>{Me.aa("retrieved web experiments from the server"),n.oa=new Map,r.forEach((s=>{if(s.feature_flag_key){var o;n.oa&&(Me.aa("setting flag key ",s.feature_flag_key," to web experiment ",s),(o=n.oa)==null||o.set(s.feature_flag_key,s));var a=n._instance.getFeatureFlag(s.feature_flag_key);X(a)&&s.variants[a]&&n.la(s.name,a,s.variants[a].transforms)}else if(s.variants)for(var l in s.variants){var u=s.variants[l];Me.ua(u,n._instance)&&n.la(s.name,l,u.transforms)}}))}),i)},this._instance=e,this._instance.onFeatureFlags((i=>{this.onFeatureFlags(i)}))}initialize(){}onFeatureFlags(e){if(this._is_bot())Me.aa(Iu);else if(!this.Ne.disable_web_experiments){if(H(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();Me.aa("applying feature flags",e),e.forEach((n=>{var i;if(this.oa&&(i=this.oa)!=null&&i.has(n)){var r,s=this._instance.getFeatureFlag(n),o=(r=this.oa)==null?void 0:r.get(n);s&&o!=null&&o.variants[s]&&this.la(o.name,s,o.variants[s].transforms)}}))}}previewWebExperiment(){var e=Me.getWindowLocation();if(e!=null&&e.search){var n=si(e?.search,"__experiment_id"),i=si(e?.search,"__experiment_variant");n&&i&&(Me.aa("previewing web experiments "+n+" && "+i),this.getWebExperiments((r=>{this.ha(parseInt(n),i,r)}),!1,!0))}}loadIfEnabled(){this.Ne.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,n,i){if(this.Ne.disable_web_experiments&&!i)return e([]);var r=this._instance.get_property("$web_experiments");if(r&&!n)return e(r);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this.Ne.token),method:"GET",timestampMode:"query",callback:s=>e(s.statusCode===200&&s.json&&s.json.experiments||[])})}ha(e,n,i){var r=i.filter((s=>s.id===e));r&&r.length>0&&(Me.aa("Previewing web experiment ["+r[0].name+"] with variant ["+n+"]"),this.la(r[0].name,n,r[0].variants[n].transforms))}static ua(e,n){return!H(e.conditions)&&Me.da(e,n)&&Me.va(e)}static da(e,n){var i;if(H(e.conditions)||H((i=e.conditions)==null?void 0:i.url))return!0;var r=Me.getWindowLocation();if(r){var s,o,a,l=hf(n,r.href);return(s=e.conditions)==null||!s.url||Zm[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return w?.location}static va(e){var n;if(H(e.conditions)||H((n=e.conditions)==null?void 0:n.utm))return!0;var i=Af();if(i.utm_source){var r,s,o,a,l,u,c,d,f=(r=e.conditions)==null||(r=r.utm)==null||!r.utm_campaign||((s=e.conditions)==null||(s=s.utm)==null?void 0:s.utm_campaign)==i.utm_campaign,h=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==i.utm_source,p=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==i.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==i.utm_term;return f&&p&&g&&h}return!1}static aa(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;n>r;r++)i[r-1]=arguments[r];A.info("[WebExperiments] "+e,i)}la(e,n,i){this._is_bot()?Me.aa(Iu):n!=="control"?i.forEach((r=>{if(r.selector){var s;Me.aa("applying transform of variant "+n+" for experiment "+e+" ",r);var o=(s=document)==null?void 0:s.querySelectorAll(r.selector);o?.forEach((a=>{var l=a;r.html&&(l.innerHTML=r.html),r.css&&l.setAttribute("style",r.css)}))}})):Me.aa("Control variants leave the page unmodified.")}_is_bot(){return He&&this._instance?Gf(He,this.Ne.custom_blocked_useragents):void 0}}var ot=pe("[Conversations]"),En="Conversations not available yet.",ku="console",nh="__posthogHandledLogsRequestError",Wo=(t,e)=>{var n=t instanceof Error?t:new Error(e);return n[nh]=!0,n},Cu=t=>!!t&&typeof t=="object"&&t[nh]===!0,Rs={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=bu,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 Jm(t.config,t.Qi()),this.Ta=this.Ea)}updateConfig(t,e){var n;(n=this.Ea)==null||n.update(t,e)}setup(t){return this.Ia=t,this.rt=t.logger.createLogger("[FeatureFlags]"),n=()=>{this.Ia===t&&(this.Ia=void 0,this.nn=t,this.Pa(t))},(e=t.kv.initialize())!=null&&e.then?e.then(n):n();var e,n}Pa(t){if(this.nn===t)return w&&ve(w,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){w?.removeEventListener("online",this.Ca)}dispose(){var t;this.ba++,this.wa=!1,this.Ia=void 0,this.nn&&(this.La(),(t=this.Ra)==null||t.dispose(),this.Ra=void 0,this.ga=[],w?.removeEventListener("online",this.Ca),this.nn=void 0)}get Ne(){return this.Ta.get()}Oa(t){var e;return(e=this.nn)==null?void 0:e.kv.get(t)}F(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.set(t)}))}q(t){this.Da((()=>{var e;return(e=this.nn)==null?void 0:e.kv.remove(t)}))}Da(t){try{t()}catch(e){this.rt.error("Failed to update feature flag persistence",e)}}Fa(){var t={};for(var e of[Li,Ni,Tr,It]){var n=this.Oa(e);C(n)||(t[e]=n)}this.fa=t;var i=I({},t),r=this.Oa(Sn);if(r)for(var s of Object.entries(r))i["$feature/"+s[0]]=s[1];this.pa=i}Aa(){var t=this.Ne.cacheTtlMs;if(!t||0>=t)return!1;var e=this.Oa(Wi);return typeof e!="number"||Date.now()-e>t}$a(){return!!this.Aa()&&(this.xa||this.ya||(this.xa=!0,this.rt.warn("Feature flag cache is stale, triggering refresh..."),this.reloadFeatureFlags()),!0)}Na(){var t=this.Ne.evaluationContexts;return t!=null&&t.length?t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid evaluation context found:",e,"Expected non-empty string"),n})):[]}qa(){var t=this.Ne.flagKeys;if(!C(t))return t.filter((e=>{var n=e&&typeof e=="string"&&e.trim().length>0;return n||this.rt.error("Invalid flag key found:",e,"Expected non-empty string"),n}))}initialize(){var t,e,n=this.Ne,i=(t=(e=n.bootstrap)==null?void 0:e.featureFlags)!==null&&t!==void 0?t:{};if(Object.keys(i).length){var r,s,o=(r=(s=n.bootstrap)==null?void 0:s.featureFlagPayloads)!==null&&r!==void 0?r:{},a=Object.keys(i).filter((u=>!!i[u])).reduce(((u,c)=>(u[c]=i[c]||!1,u)),{}),l=Object.keys(o).filter((u=>a[u])).reduce(((u,c)=>(o[c]&&(u[c]=o[c]),u)),{});return this.ja({featureFlags:a,featureFlagPayloads:l})}}updateFlags(t,e,n){var i,r,s=n!=null&&n.merge&&(i=this.Oa(Sn))!==null&&i!==void 0?i:{},o=n!=null&&n.merge&&(r=this.Oa(Ni))!==null&&r!==void 0?r:{},a=I({},s,t),l=I({},o,e),u={};for(var c of Object.entries(a)){var d=c[0],f=c[1];u[d]={key:d,enabled:yc(f),variant:wc(f),reason:void 0,metadata:C(l?.[d])?void 0:{id:0,version:void 0,description:void 0,payload:l[d]}}}this.ja({flags:u})}get hasLoadedFlags(){return this.ma}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var t=this.Oa(da),e=this.Oa(It),n=this.Oa(xn);if(!n&&!e)return t||{};var i=fe({},t||{}),r=[...new Set([...Object.keys(n||{}),...Object.keys(e||{})])];for(var s of r){var o,a,l=i[s],u=e?.[s],c=C(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=C(u)?l?.variant:typeof u=="string"?u:void 0,f=n?.[s],h=I({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(h.original_enabled=l?.enabled),d!==l?.variant&&(h.original_variant=l?.variant),f&&(h.metadata=I({},l?.metadata,{payload:f,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),i[s]=h}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:n,finalDetails:i}),this.ca=!0),i}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((n=>{var i=t[n];return{key:n,enabled:yc(i),variant:wc(i),payload:_c(e[n])}}))}getFlagVariants(){var t=this.Oa(Sn),e=this.Oa(It);if(!e)return t||{};for(var n=fe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:e,finalFlags:n}),this.ca=!0),n}getFlagPayloads(){var t=this.Oa(Ni),e=this.Oa(xn);if(!e)return t||{};for(var n=fe({},t||{}),i=Object.keys(e),r=0;i.length>r;r++)n[i[r]]=e[i[r]];return this.ca||(this.rt.warn(" Overriding feature flag payloads!",{flagPayloads:t,overriddenPayloads:e,finalPayloads:n}),this.ca=!0),n}reloadFeatureFlags(){this._a||this.Ne.featureFlagsDisabled||this.Ma()||this.Ba||(this.ga.slice().forEach((t=>{try{t()}catch(e){this.rt.error("Error while running feature flags reloading callback",e)}})),this.Ba=setTimeout((()=>{this.Ha()}),5))}La(){clearTimeout(this.Ba),this.Ba=void 0}onReloading(t){return this.ga.push(t),()=>{this.ga=this.ga.filter((e=>e!==t))}}ensureFlagsLoaded(){this.ma||this.ya||this.Ba||this.reloadFeatureFlags()}setAnonymousDistinctId(t){this.$anon_distinct_id=t}setReloadingPaused(t){this._a=t}resetFlagCallReported(){this.q(Cn)}Ha(t){this.La();var e=this.nn;if(e&&!this.Ne.remoteRequestsDisabled&&!this.Ma())if(this.ya)this.wa=!0;else{var n={token:e.projectToken,distinct_id:e.distinctId,groups:e.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:I({},e.initialPersonProperties,this.Oa(jt)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(In),timezone:Mf()};C(e.deviceId)||(n.$device_id=e.deviceId),(t!=null&&t.disableFlags||this.Ne.featureFlagsDisabled)&&(n.disable_flags=!0);var i=this.Na();i.length&&(n.evaluation_contexts=i);var r=this.qa();C(r)||(n.flag_keys=r);var s=this.Ne.onlyEvaluateSurveyFeatureFlags,o="/flags/?v=2"+(s?"&only_evaluate_survey_feature_flags=true":""),a=this.ba;this.ya=!0;var l=()=>{this.wa&&(this.wa=!1,this.Ha())},u=c=>{this.ya=!1,a===this.ba&&(this.F({[Lr]:[Eu]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:n,compression:this.Ne.compression==="base64"?Ue.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,f,h=(d=c.json)!==null&&d!==void 0?d:{},p=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),p||this.wa||(this.$anon_distinct_id=void 0),!n.disable_flags||this.wa){this.ka=!p;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?Eu:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),h.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((f=h.quotaLimited)==null||!f.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[Lr]:g}),m?this.rt.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more."):n.disable_flags||this.ja(h,p,{partialResponse:s}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return kf(this.Sa,3)}Ua(t){this.Sa=Cf(t,this.Sa,3,(()=>this.rt.warn("Feature flag requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped refreshing feature flags; will try again when connectivity changes.")))}getFeatureFlag(t,e){var n;if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var i=this.getFeatureFlagResult(t,e);return(n=i?.variant)!==null&&n!==void 0?n:i?.enabled}}else this.rt.warn('getFeatureFlag for key "'+t+Ho)}getFeatureFlagDetails(t){return this.getFlagsWithDetails()[t]}getFeatureFlagPayload(t){var e=this.getFeatureFlagResult(t,{send_event:!1});return e?.payload}getFeatureFlagResult(t,e){if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var n,i=this.getFlagVariants(),r=t in i,s=i[t],o=this.getFlagPayloads()[t],a=String(s),l=this.Oa(Tr)||void 0,u=this.Oa(Wi)||void 0,c=this.Oa(Cn)||{};if(this.Ne.deduplicateCallsPerSession){var d,f=(d=this.nn)==null?void 0:d.session.sessionId,h=this.Oa(Bi);f&&f!==h&&(c={},n=f)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))n&&this.F({[Cn]:c,[Bi]:n});else{var p,g,m,v,E,S,_,b,k,T;U(c[t])?c[t].push(a):c[t]=[a],this.F(I({[Cn]:c},n?{[Bi]:n}:{}));var x=this.getFeatureFlagDetails(t),F=[...(p=this.Oa(Lr))!==null&&p!==void 0?p:[]];C(s)&&F.push("flag_missing");var $={$feature_flag:t,$feature_flag_response:s,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((g=this.Ne.bootstrap)==null||(g=g.featureFlags)==null?void 0:g[t])||null,$feature_flag_bootstrapped_payload:((m=this.Ne.bootstrap)==null||(m=m.featureFlagPayloads)==null?void 0:m[t])||null,$used_bootstrap_value:!this.ka};C(x==null||(v=x.metadata)==null?void 0:v.has_experiment)||($.$feature_flag_has_experiment=x.metadata.has_experiment),C(x==null||(E=x.metadata)==null?void 0:E.version)||($.$feature_flag_version=x.metadata.version);var O,L=(S=x==null||(_=x.reason)==null?void 0:_.description)!==null&&S!==void 0?S:x==null||(b=x.reason)==null?void 0:b.code;L&&($.$feature_flag_reason=L),x!=null&&(k=x.metadata)!=null&&k.id&&($.$feature_flag_id=x.metadata.id),C(x?.original_variant)&&C(x?.original_enabled)||($.$feature_flag_original_response=C(x.original_variant)?x.original_enabled:x.original_variant),x!=null&&(T=x.metadata)!=null&&T.original_payload&&($.$feature_flag_original_payload=x==null||(O=x.metadata)==null?void 0:O.original_payload),F.length&&($.$feature_flag_error=F.join(",")),this.za($)}else n&&this.F({[Cn]:c,[Bi]:n});if(r)return{key:t,enabled:!!s,variant:typeof s=="string"?s:void 0,payload:_c(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+Ho)}za(t){try{var e;(e=this.nn)==null||e.capture("$feature_flag_called",t).catch((n=>{this.rt.error("Failed to capture feature flag call",n)}))}catch(n){this.rt.error("Failed to capture feature flag call",n)}}getRemoteConfigPayload(t,e){this.Wa(t,e)}Wa(t,e){var n=this;return se((function*(){var i=n.nn;if(i){var r={distinct_id:i.distinctId,token:i.projectToken,person_properties:{$lib:i.library.name,$lib_version:i.library.version}},s=n.Na();s.length&&(r.evaluation_contexts=s);var o,a=n.qa();C(a)||(r.flag_keys=a);try{var l,u=(l=(yield i.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:r,compression:n.Ne.compression==="base64"?Ue.Base64:void 0,sentAt:"body",timeoutMs:n.Ne.requestTimeoutMs})).json)==null?void 0:l.featureFlagPayloads;o=u?.[t]||void 0}catch(c){return void n.rt.error("Remote config feature flag request failed",c)}try{e(o)}catch(c){n.rt.error("Remote config feature flag callback failed",c)}}}))()}isFeatureEnabled(t,e){if(e===void 0&&(e={}),e.fresh&&!this.ka)return e.defaultValue;if(!(this.ma||this.getFlags()&&this.getFlags().length>0))return this.rt.warn('isFeatureEnabled for key "'+t+Ho),e.defaultValue;var n=this.getFeatureFlag(t,e);return C(n)?e.defaultValue:!!n}addFeatureFlagsHandler(t){this.featureFlagEventHandlers.push(t)}removeFeatureFlagsHandler(t){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((e=>e!==t))}receivedFeatureFlags(t,e,n){this.ja(t,e,n)}ja(t,e,n){if(this.nn){this.ma=!0;var i=(function(r,s,o,a,l,u){s===void 0&&(s={}),o===void 0&&(o={}),a===void 0&&(a={}),u===void 0&&(u=bu);var c=((k,T)=>{var x=k.flags;return x?I({},k,{featureFlags:Object.fromEntries(Object.keys(x).map((F=>{var $;return[F,($=x[F].variant)!==null&&$!==void 0?$:x[F].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(x).filter((F=>x[F].enabled)).filter((F=>{var $;return($=x[F].metadata)==null?void 0:$.payload})).map((F=>{var $;return[F,($=x[F].metadata)==null?void 0:$.payload]})))}):(k.featureFlags&&T.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),k)})(r,u),d=c.flags,f=c.featureFlags,h=c.featureFlagPayloads;if(f){var p=r.requestId,g=r.evaluatedAt;if(U(f)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(f)for(var v=0;f.length>v;v++)m[f[v]]=!0;return{[Li]:f,[Sn]:m,[ts]:!1}}var E=f,S=h,_=d;if(l!=null&&l.partialResponse)E=I({},s,E),S=I({},o,S),_=I({},a,_);else if(r.errorsWhileComputingFlags)if(d){var b=new Set(Object.keys(d).filter((k=>{var T;return!((T=d[k])!=null&&T.failed)})));E=I({},s,Object.fromEntries(Object.entries(E).filter((k=>b.has(k[0]))))),S=I({},o,Object.fromEntries(Object.entries(S||{}).filter((k=>b.has(k[0]))))),_=I({},a,Object.fromEntries(Object.entries(_||{}).filter((k=>b.has(k[0])))))}else E=I({},s,E),S=I({},o,S),_=I({},a,_);return I({[Li]:Object.keys(xu(E)),[Sn]:E||{},[Ni]:S||{},[da]:_||{},[ts]:r.minimalFlagCalledEvents===!0},p?{[Tr]:p}:{},g?{[Wi]:g}:{})}})(t,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),n,this.rt);i&&this.F(i),e||(this.xa=!1),this.Va(e)}}override(t,e){e===void 0&&(e=!1),this.rt.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:t,suppressWarning:e})}overrideFeatureFlags(t){this.Za(t)}Za(t){if(this.nn){if(t===!1)return this.q([It,xn]),this.Va(),void bn.info("All overrides cleared");if(U(t))return this.F({[It]:Su(t)}),this.Va(),void bn.info("Flag overrides set",{flags:t});if(t&&typeof t=="object"&&("flags"in t||"payloads"in t)){var e,n=t;this.ca=!!((e=n.suppressWarning)!==null&&e!==void 0&&e);var i={},r=n.flags,s=n.payloads;return r&&(i[It]=U(r)?Su(r):r),s&&(i[xn]=s),Object.keys(i).length&&this.F(i),r===!1&&s===!1?this.q([It,xn]):r===!1?this.q(It):s===!1&&this.q(xn),this.Va(),r===!1?bn.info("Flag overrides cleared"):r&&bn.info("Flag overrides set",{flags:r}),void(s===!1?bn.info("Payload overrides cleared"):s&&bn.info("Payload overrides set",{payloads:s}))}if(t&&typeof t=="object")return this.F({[It]:t}),this.Va(),void bn.info("Flag overrides set",{flags:t});this.rt.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:t})}else this.rt.warn("posthog.featureFlags.overrideFeatureFlags called before feature flags were ready")}onFeatureFlags(t){if(this.addFeatureFlagsHandler(t),this.ma){var e=this.Ga(),n=e.flags,i=e.flagVariants;try{t(n,i)}catch(r){this.rt.error("Error while running feature flags callback",r)}}return()=>this.removeFeatureFlagsHandler(t)}updateEarlyAccessFeatureEnrollment(t,e,n){var i=(this.Oa(Rr)||[]).find((l=>l.flagKey===t)),r={["$feature_enrollment/"+t]:e},s={$feature_flag:t,$feature_enrollment:e,$set:r};i&&(s.$early_access_feature_name=i.name),n&&(s.$feature_enrollment_stage=n);var o=I({},this.getFlagVariants(),{[t]:e});this.F({[Li]:Object.keys(xu(o)),[Sn]:o,[jt]:I({},this.Oa(jt)||{},r)}),this.Va();try{var a;(a=this.nn)==null||a.capture("$feature_enrollment_update",s).catch((l=>{this.rt.error("Failed to capture early access feature enrollment",l)}))}catch(l){this.rt.error("Failed to capture early access feature enrollment",l)}}getEarlyAccessFeatures(t,e,n){e===void 0&&(e=!1);var i=this.Oa(Rr);!i||e?this.Qa(t,n):t(i)}Qa(t,e){var n=this;return se((function*(){var i=n.nn;if(i){var r,s=e?"&"+e.map((a=>"stage="+a)).join("&"):"";try{var o=yield i.sendRequest("/api/early_access_features/?token="+i.projectToken+s,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;n.F({[Rr]:r=o.json.earlyAccessFeatures})}catch(a){return void n.rt.error("Early access feature request failed",a)}try{t(r)}catch(a){n.rt.error("Early access feature callback failed",a)}}}))()}Ga(){var t=this.getFlags(),e=this.getFlagVariants();return{flags:t.filter((n=>e[n])),flagVariants:Object.keys(e).filter((n=>e[n])).reduce(((n,i)=>(n[i]=e[i],n)),{})}}Va(t){this.Fa();var e=this.Ga(),n=e.flags,i=e.flagVariants;this.featureFlagEventHandlers.forEach((r=>{try{r(n,i,{errorsLoading:t})}catch(s){this.rt.error("Error while running feature flags callback",s)}}))}setPersonPropertiesForFlags(t,e){e===void 0&&(e=!0),this.Ka(t,e)}Ka(t,e){e===void 0&&(e=!0);var n=this.Oa(jt)||{},i=t?.$set||(t!=null&&t.$set_once?{}:t),r=t?.$set_once,s={};if(r)for(var o in r)({}).hasOwnProperty.call(r,o)&&(o in n||(s[o]=r[o]));this.F({[jt]:I({},n,s,i)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=I({},this.Oa(jt)||{});t.forEach((i=>{delete n[i]})),this.F({[jt]:n}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(jt),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=this.Oa(In)||{},i=I({},n);for(var r of Object.keys(t))i[r]=I({},n[r],t[r]);this.F({[In]:i}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(In)||{};this.F({[In]:I({},e,{[t]:{}})})}else this.q(In)}reset(){this.ba++,this.wa=!1,this.Fa(),this.ma=!1,this._a=!1,this.ka=!1,this.$anon_distinct_id=void 0,this.La(),this.ca=!1,this.Sa=0}}},Xm={sessionRecording:class{get Ne(){return this._instance.config}get Mr(){return this._instance.persistence}get started(){var t;return!((t=this.Ja)==null||!t.isStarted)}get status(){var t,e;return this.Ya===Pi||this.Ya===kr?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=pu,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(P==null||!P.visibilityState||P.visibilityState==="visible")return!0;var n=w==null||(e=w.performance)==null||e.getEntriesByType==null?void 0:e.getEntriesByType("visibility-state");return!(n!=null&&n.length)||n.some((i=>i.name==="visible"))})(),this.Ie=()=>{var e;P?.visibilityState==="visible"&&(this.io=!0,(e=this.Ja)==null||e.setDocumentWasEverVisible==null||e.setDocumentWasEverVisible(!0))},this._instance=t,!this._instance.sessionManager)throw Bt.error("started without valid sessionManager"),new Error(Pa+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===Wt)throw new Error(Pa+' cannot be used with cookieless_mode="always"');P!=null&&P.addEventListener&&ve(P,"visibilitychange",this.Ie)}initialize(){this.startIfEnabledOrStop()}dispose(){this.eo=!0,P==null||P.removeEventListener==null||P.removeEventListener("visibilitychange",this.Ie),this.stopRecording()}get ro(){var t,e=!((t=this._instance.get_property(An))==null||!t.enabled),n=!this.Ne.disable_session_recording,i=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return w&&e&&n&&!i}startIfEnabledOrStop(t){var e;if(!(this.eo||this.ro&&(e=this.Ja)!=null&&e.isStarted)){var n=!C(Object.assign)&&!C(Array.from);this.ro&&n?(this.no(t),Bt.info("starting")):(this.Ya=pu,this.stopRecording())}}no(t){var e,n,i;this.ro&&(this.Ya!==Pi&&this.Ya!==kr&&(this.Ya=gu),B!=null&&(e=B.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(n=B.__PosthogExtensions__)!=null&&n.initSessionRecording?this.so(t):(i=B.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,this.ao,(r=>{if(r)return Bt.error("could not load recorder",r);this.so(t)})))}stopRecording(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.stop()}oo(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.discard()}lo(){var t,e;(t=this.Mr)==null||t.unregister(dl),(e=this.Mr)==null||e.unregister(tf)}uo(t,e){if(H(t))return null;var n,i=ke(t)?t:parseFloat(t);return typeof(n=i)!="number"||!Number.isFinite(n)||0>n||n>1?(Bt.warn(e+" must be between 0 and 1. Ignoring invalid value:",t),null):i}ho(t){if(this.Mr){var e,n,i=this.Mr,r=()=>{var s,o=t.sessionRecording===!1?void 0:t.sessionRecording,a=this.uo((s=this.Ne.session_recording)==null?void 0:s.sampleRate,"session_recording.sampleRate"),l=this.uo(o?.sampleRate,"remote config sampleRate"),u=a??l;H(u)&&this.lo();var c=o?.minimumDurationMilliseconds;i.register({[An]:I({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:I({capturePerformance:t.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:u,minimumDurationMilliseconds:C(c)?null:c,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers,version:o?.version,triggerGroups:o?.triggerGroups})})};r(),(e=this.Xa)==null||e.call(this),this.Xa=(n=this._instance.sessionManager)==null?void 0:n.onSessionId(r)}}onRemoteConfig(t){var e=t.ok?t.config:void 0;return e&&"sessionRecording"in e?e.sessionRecording===!1?(this.ho(e),void this.oo()):(this.ho(e),void this.startIfEnabledOrStop()):(this.Ya===Pi&&(this.Ya=kr,Bt.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(t,e){var n;e===void 0&&(e="log"),(n=this.Ja)!=null&&n.log?this.Ja.log(t,e):Bt.warn("log called before recorder was ready")}get ao(){var t,e,n=(t=this._instance)==null||(t=t.persistence)==null?void 0:t.get_property(An);return(n==null||(e=n.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(An);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(n){return Bt.warn("persisted remote config for session recording is invalid and will be ignored",n),!1}return!H(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,n,i;if(!this.eo){if((e=B.__PosthogExtensions__)==null||!e.initSessionRecording)return Bt.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[uf]:!0});var r;if(this.Ja||(this.Ja=(r=B.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===kr||this.Ya===Pi?void 0:(this.Ya=Pi,Bt.info("persisted remote config is stale, requesting fresh config before starting"),void new Lf(this._instance).load());this.Ya=gu,(n=(i=this.Ja).setDocumentWasEverVisible)==null||n.call(i,this.io),this.Ja.start(t)}}onRRwebEmit(t){var e;(e=this.Ja)==null||e.onRRwebEmit==null||e.onRRwebEmit(t)}overrideLinkedFlag(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[rf]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[nf]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,n;this.Ja||(n=this.Mr)==null||n.register({[t==="url"?sf:of]:!0}),(e=this.Ja)==null||e.overrideTrigger(t)}get sdkDebugProperties(){var t;return((t=this.Ja)==null?void 0:t.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(t,e){var n;return!((n=this.Ja)==null||!n.tryAddCustomEvent(t,e))}}},Qm={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new du(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,n=he(this.instance.config.autocapture)?this.instance.config.autocapture:{};return n.url_allowlist=(t=n.url_allowlist)==null?void 0:t.map((i=>new RegExp(i))),n.url_ignorelist=(e=n.url_ignorelist)==null?void 0:e.map((i=>new RegExp(i))),n}yo(){if(this.isBrowserSupported()){if(w&&P){var t=n=>{n=n||w?.event;try{this.bo(n)}catch(i){Bo.error("Failed to capture event",i)}};if(ve(P,"submit",t,{capture:!0}),ve(P,"change",t,{capture:!0}),ve(P,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=n=>{n=n||w?.event;try{this.bo(n,Oo)}catch(i){Bo.error("Failed to capture copy/cut event",i)}};ve(P,"copy",e,{capture:!0}),ve(P,"cut",e,{capture:!0})}}}else Bo.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.vo&&(this.yo(),this.vo=!0)}onRemoteConfig(t){if(this.fo=!0,t.ok){var e=t.config;e.elementsChainAsString&&(this.po=e.elementsChainAsString);var n=e.autocapture_opt_out;mt(n)&&(this.instance.persistence&&this.instance.persistence.register({[ra]:n}),this.co=n),this.startIfEnabled()}else this.startIfEnabled()}setElementSelectors(t){this.mo=t}getElementSelectors(t){var e,n=[];return(e=this.mo)==null||e.forEach((i=>{var r=P?.querySelectorAll(i);r?.forEach((s=>{t===s&&n.push(i)}))})),n}get isEnabled(){var t,e,n=(t=this.instance.persistence)==null?void 0:t.props[ra],i=this.co,r=this.instance.Qi()&&!this.fo;if(Ye(i)&&!mt(n)&&!r)return!1;var s=(e=this.co)!==null&&e!==void 0?e:!!n;return!!this.instance.config.autocapture&&!s}bo(t,e){if(e===void 0&&(e="$autocapture"),this.isEnabled){var n,i=Io(t);gf(i)&&(i=i.parentNode||null),e==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&this.instance.config.rageclick&&(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,t.timeStamp||new Date().getTime())&&Uc(i,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var r=e===Oo;if(i&&(function(d,f,h,p,g,m){var v;if(!w||ml(d)||h!=null&&h.url_allowlist&&!Bc(h.url_allowlist,m)||h!=null&&h.url_ignorelist&&Bc(h.url_ignorelist,m))return!1;if(h!=null&&h.dom_event_allowlist){var E=h.dom_event_allowlist;if(E&&!E.some((x=>f.type===x)))return!1}var S=bf(d,p),_=S.parentIsUsefulElement,b=S.targetElementList;if(!(function(x,F){var $=F?.element_allowlist;if(C($))return!0;var O,L=function(K){if($.some((V=>K.tagName.toLowerCase()===V)))return{v:!0}};for(var N of x)if(O=L(N))return O.v;return!1})(b,h)||!wa(b,h?.css_selector_allowlist)||wa(b,(v=h?.css_selector_ignorelist)!==null&&v!==void 0?v:Jg))return!1;try{var k=w.getComputedStyle(d);if(k&&k.getPropertyValue("cursor")==="pointer"&&f.type==="click")return!0}catch{}var T=d.tagName.toLowerCase();switch(T){case"html":return!1;case"form":return(g||["submit"]).indexOf(f.type)>=0;case"input":case"select":case"textarea":return(g||["change","click"]).indexOf(f.type)>=0;default:return _?(g||["click"]).indexOf(f.type)>=0:(g||["click"]).indexOf(f.type)>=0&&(gl.indexOf(T)>-1||d.getAttribute("contenteditable")==="true")}})(i,t,this.Ne,r,r?["copy","cut"]:void 0,this.instance)){var s=Hm(i,{e:t,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.Ne.element_attribute_ignorelist,elementsChainAsString:this.po,disableCaptureUrlHashes:this.instance.config.disable_capture_url_hashes}),o=s.props;if(s.explicitNoCapture)return!1;var a=this.getElementSelectors(i);if(a&&a.length>0&&(o.$element_selectors=a),e===Oo){var l,u=_f(w==null||(l=w.getSelection())==null?void 0:l.toString()),c=t.type||"clipboard";if(!u)return!1;o.$selected_content=u,o.$copy_type=c}return this.instance.capture(e,o),!0}}}isBrowserSupported(){return je(P?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(w==null||(e=w.location)==null?void 0:e.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(A.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.wo&&this.wo(),this.wo=void 0,A.info("History API monitoring stopped")}monitorHistoryChanges(){w&&w.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(w&&((e=w.history[t])==null||!e.__posthog_wrapped__)){var n=this;(function(i,r,s){try{if(!(r in i))return fu;var o={next:i[r]},a=s((function(){for(var l=arguments.length,u=new Array(l),c=0;l>c;c++)u[c]=arguments[c];return o.next.apply(this,u)}));return je(a)&&(a.prototype=a.prototype||{},Object.defineProperties(a,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:o}})),i[r]=a,()=>{if(i[r]!==a)for(var l=i[r];je(l)&&l.__posthog_layer__;){var u=l.__posthog_layer__;if(u.next===a)return void(u.next=o.next);l=u.next}else i[r]=o.next}}catch{return fu}})(w.history,t,(i=>function(r,s,o){i.call(this,r,s,o),n.So(t)}))}}So(t){try{var e,n=w==null||(e=w.location)==null?void 0:e.pathname;if(!n)return;n!==this._o&&this.isEnabled&&this._instance.capture(Vn,{navigation_type:t}),this._o=n}catch(i){A.error("Error capturing "+t+" pageview",i)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};ve(w,"popstate",t),this.wo=()=>{w&&w.removeEventListener("popstate",t)}}}},heatmaps:class{get Ne(){return this.instance.config}constructor(t){var e;this.Co=!1,this.vo=!1,this.Mo=null,this.instance=t,this.Co=!((e=this.instance.persistence)==null||!e.props[sa]),this.rageclicks=new du(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return he(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return H(this.Ne.capture_heatmaps)?H(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;zm.info("starting..."),this.To(),this.Ie()}else{var t;clearInterval((t=this.Mo)!==null&&t!==void 0?t:void 0),this.Eo(),this.getAndClearBuffer()}}onRemoteConfig(t){if(t.ok){var e=t.config;if("heatmaps"in e){var n=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[sa]:n}),this.Co=n,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){jo(t.originalEvent)&&this.ke(t.originalEvent,"deadclick")}Ie(){this.Mo&&clearInterval(this.Mo),this.Mo=P?.visibilityState==="visible"?setInterval(this.cr.bind(this),this.flushIntervalMilliseconds):null}To(){w&&P&&(this.Po=this.cr.bind(this),ve(w,os,this.Po),this.Ro=t=>this.ke(t||w?.event),ve(P,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||w?.event),ve(P,"mousemove",this.Ao,{capture:!0}),this.Lo=new Kc(this.instance,im,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),ve(P,ss,this.Oo),this.vo=!0)}Eo(){var t;w&&P&&(this.Po&&w.removeEventListener(os,this.Po),this.Ro&&P.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&P.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&P.removeEventListener(ss,this.Oo),clearTimeout(this.Do),(t=this.Lo)==null||t.stop(),this.vo=!1)}$o(t,e){var n=this.instance.scrollManager.scrollY(),i=this.instance.scrollManager.scrollX(),r=this.instance.scrollManager.scrollElement(),s=(function(o,a,l){for(var u=o;u&&hn(u)&&!et(u,"body");){if(u===l)return!1;var c=void 0;try{var d,f,h;c=(d=(f=(h=u.ownerDocument)==null?void 0:h.defaultView)!==null&&f!==void 0?f:w)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(j(a,c))return!0;u=yf(u)}return!1})(Io(t),["fixed","sticky"],r);return{x:t.clientX+(s?0:i),y:t.clientY+(s?0:n),target_fixed:s,type:e}}ke(t,e){var n;if(e===void 0&&(e="click"),!Oc(t.target)&&jo(t)){var i=this.$o(t,e);(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,new Date().getTime())&&Uc(Io(t),this.instance.config.rageclick)&&this.Vt(I({},i,{type:"rageclick"})),this.Vt(i)}}Fo(t){!Oc(t.target)&&jo(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(w){var e=this.Ne.disable_capture_url_hashes?fn(w.location.href):w.location.href,n=this.Ne.custom_personal_data_properties,i=this.Ne.mask_personal_data_properties?[...oi,...n||[]]:[],r=er(e,i,tr);this.R=this.R||{},this.R[r]||(this.R[r]=[]),this.R[r].push(t)}}cr(){this.R&&!Kt(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:Kc,webVitalsAutocapture:class{constructor(t){var e;this.Co=!1,this.vo=!1,this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this.No=()=>{clearTimeout(this.qo),this.qo=void 0,this.R.metrics.length!==0&&(this._instance.capture("$web_vitals",I({$current_url:this.R.url},this.R.metrics.reduce(((n,i)=>I({},n,{["$web_vitals_"+i.name+"_event"]:I({},i),["$web_vitals_"+i.name+"_value"]:i.value})),{}))),this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.jo=n=>{var i;if(this.R=this.R||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},H(n?.name)||H(n?.value))wn.error("Invalid metric received",n);else{var r=typeof n.navigationURL=="string"?n.navigationURL:void 0,s=this.Bo(r);if(!C(s)){var o=ke(n.navigationId)||typeof n.navigationId=="string"?"navigation:"+n.navigationId:"url:"+s;if(!this.Ho||this.Ho>n.value){this.R.navigationKey!==o&&(this.No(),this.qo=setTimeout(this.No,this.flushToCaptureTimeoutMs)),C(this.R.navigationKey)&&(this.R.navigationKey=o,this.R.url=s),this.R.firstMetricTimestamp=C(this.R.firstMetricTimestamp)?Date.now():this.R.firstMetricTimestamp,n.attribution&&n.attribution.interactionTargetElement&&(n.attribution.interactionTargetElement=void 0);var a=(i=this._instance.sessionManager)==null?void 0:i.checkAndGetSessionAndWindowId(!0),l=I({},n,r?{navigationURL:s}:{},{$current_url:s,timestamp:Date.now()});C(a)||(l.$session_id=a.sessionId,l.$window_id=a.windowId),this.R.metrics.push(l),this.R.metrics.length===this.allowedMetrics.length&&this.No()}else wn.error("Ignoring metric with value >= "+this.Ho,n)}}},this.Uo=()=>{if(!this.vo){var n,i,r,s,o=B.__PosthogExtensions__,a=o?.postHogWebVitalsCallbacksByFlavor,l=a?.[this.zo]||(this.zo==="web-vitals"&&C(a)?o?.postHogWebVitalsCallbacks:void 0);if(C(l)||(n=l.onLCP,i=l.onCLS,r=l.onFCP,s=l.onINP),n&&i&&r&&s){var u={reportSoftNavs:this.useSoftNavs};this.allowedMetrics.indexOf("LCP")>-1&&n(this.jo.bind(this),u),this.allowedMetrics.indexOf("CLS")>-1&&i(this.jo.bind(this),u),this.allowedMetrics.indexOf("FCP")>-1&&r(this.jo.bind(this),u),this.allowedMetrics.indexOf("INP")>-1&&s(this.jo.bind(this),u),this.vo=!0}else wn.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[ca]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,n=he(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return H(n)?((e=this._instance.persistence)==null?void 0:e.props[ua])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(he(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=he(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=he(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=he(this.Wo)&&ke(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:hu;return t>0&&6e4>=t?hu:t}get isEnabled(){var t=me?.protocol;if(t!=="http:"&&t!=="https:")return wn.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=he(this.Wo)?this.Wo.web_vitals:mt(this.Wo)?this.Wo:void 0;return mt(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(wn.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var n=he(e.capturePerformance)&&!!e.capturePerformance.web_vitals,i=he(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[ca]:n}),this._instance.persistence.register({[ua]:i})),this.Co=n,this.startIfEnabled()}}}get zo(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}ai(t){var e=B.__PosthogExtensions__,n=this.zo,i=e?.postHogWebVitalsCallbacksByFlavor;i!=null&&i[n]||n==="web-vitals"&&C(i)&&e!=null&&e.postHogWebVitalsCallbacks?t():e==null||e.loadExternalDependency==null||e.loadExternalDependency(this._instance,n,(r=>{r?wn.error("failed to load script",r):t()}))}Bo(t){var e=t||w?.location.href;if(e){var n=this._instance.config.disable_capture_url_hashes?fn(e):e,i=this._instance.config.custom_personal_data_properties,r=this._instance.config.mask_personal_data_properties?[...oi,...i||[]]:[];return er(n,r,tr)}wn.error("Could not determine current URL")}}},ev={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var n;if(w&&this.isEnabled&&(n=B.__PosthogExtensions__)!=null&&n.errorWrappingFunctions){var i=B.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,r=B.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,s=B.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.Vo&&this.Ne.capture_unhandled_errors&&(this.Vo=i(this.captureException.bind(this))),!this.Zo&&this.Ne.capture_unhandled_rejections&&(this.Zo=r(this.captureException.bind(this))),!this.Go&&this.Ne.capture_console_errors&&(this.Go=s(this.captureException.bind(this)))}catch(o){Ai.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[oa]),this.Jo=new Xp(I({},(function(n){var i,r,s,o;return n===void 0&&(n={}),{refillRate:(i=(r=n.exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:n.__exceptionRateLimiterRefillRate)!==null&&i!==void 0?i:1,bucketSize:(s=(o=n.exceptionRateLimiterBucketSize)!==null&&o!==void 0?o:n.__exceptionRateLimiterBucketSize)!==null&&s!==void 0?s:10}})(this._instance.config.error_tracking),{refillInterval:1e4,rt:Ai})),this.Ne=this.Yo(),this.startIfEnabledOrStop()}Yo(){var t=this._instance.config.capture_exceptions,e={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return he(t)?e=I({},e,t):(C(t)?this.Ko:t)&&(e=I({},e,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),e}get isEnabled(){return this.Ne.capture_console_errors||this.Ne.capture_unhandled_errors||this.Ne.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(Ai.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",(i=>{if(i)return Ai.error("failed to load script",i);t()}))}Qo(){var t,e,n;(t=this.Vo)==null||t.call(this),this.Vo=void 0,(e=this.Zo)==null||e.call(this),this.Zo=void 0,(n=this.Go)==null||n.call(this),this.Go=void 0}onRemoteConfig(t){if(t.ok){var e=t.config;"autocaptureExceptions"in e&&(this.Ko=!!e.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[oa]:this.Ko}),this.Ne=this.Yo(),this.startIfEnabledOrStop())}}onConfigChange(){this.Ne=this.Yo()}captureException(t){var e,n,i,r=(e=t==null||(n=t.$exception_list)==null||(n=n[0])==null?void 0:n.type)!==null&&e!==void 0?e:"Exception";this.Jo.consumeRateLimit(r)?Ai.info("Skipping exception capture because of client rate limiting.",{exception:r}):(i=this._instance.exceptions)==null||i.sendExceptionEvent(t)}},exceptions:class{constructor(t){var e,n;this.Xo=[],this.tl=new gg([new Sg,new Tg,new Ig,new xg,new Fg,new Pg,new Cg,new Rg],(function(i){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;r>o;o++)s[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` +`),d=l;c.length>d;d++){var f=c[d];if(1024>=f.length){var h=$c.test(f)?f.replace($c,"$1"):f;if(!h.match(/\S*Error: /)){for(var p of s){var g=p(h,i);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var v=Array.from(m);return v.reverse(),v.slice(0,50).map((E=>{return I({},E,{filename:E.filename||(S=v,S[S.length-1]||{}).filename,function:E.function||ri});var S}))})(u)}})("web:javascript",yg,Eg)),this._instance=t,this.Xo=(e=(n=this._instance.persistence)==null?void 0:n.get_property(aa))!==null&&e!==void 0?e:[],this.el=es(this.il()),this.rl=new Mg(this.el)}onConfigChange(){this.el=es(this.il()),this.rl.setConfig(this.el)}onRemoteConfig(t){var e,n,i;if(t.ok){var r=t.config;if("errorTracking"in r){var s=(e=(n=r.errorTracking)==null?void 0:n.suppressionRules)!==null&&e!==void 0?e:[],o=(i=r.errorTracking)==null?void 0:i.captureExtensionExceptions;this.Xo=s,this._instance.persistence&&this._instance.persistence.register({[aa]:this.Xo,[la]:o})}}}get nl(){var t,e=!!this._instance.get_property(la),n=this._instance.config.error_tracking.captureExtensionExceptions;return(t=n??e)!==null&&t!==void 0&&t}buildProperties(t,e){return this.tl.buildFromUnknown(t,{syntheticException:e?.syntheticException,mechanism:{handled:e?.handled}})}addExceptionStep(t,e){if(this.el.enabled)try{if(!X(t)||t.trim().length===0)return void St.warn("Ignoring exception step because message must be a non-empty string");var n=(function(s){if(!s)return{sanitizedProperties:{},droppedKeys:[]};var o=[];return{sanitizedProperties:Object.keys(s).reduce(((a,l)=>$g.has(l)?(o.push(l),a):(a[l]=s[l],a)),{}),droppedKeys:o}})(this.sl(e)),i=n.sanitizedProperties,r=n.droppedKeys;r.length>0&&St.warn("Ignoring reserved exception step fields",{droppedKeys:r}),this.rl.add(I({[Xr]:t,[Qr]:new Date().toISOString()},i))}catch(s){St.error("Failed to add exception step. Ignoring breadcrumb.",s)}}sendExceptionEvent(t){try{var e=t.$exception_list;if(this.al(e)){if(this.ol(e))return this.ll("Exception dropped: matched a suppression rule"),void St.info("Skipping exception capture because a suppression rule matched");if(!this.nl&&this.ul(e))return this.ll("Exception dropped: thrown by a browser extension"),void St.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.hl(e))return this.ll("Exception dropped: thrown by the PostHog SDK"),void St.info("Skipping exception capture because it was thrown by the PostHog SDK")}var n=this.el.enabled&&H(t.$exception_steps)?this.dl(t):t,i=typeof(s=globalThis._posthogReleaseId)=="string"&&s.length>0?s:void 0;i&&(n.$release_id=i);try{var r=this._instance.capture("$exception",n,{_noTruncate:!0,_batchKey:"exceptionEvent",Wn:!0});return r&&this.rl.clear(),r}catch(o){return St.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void St.error("Failed to process exception event. Ignoring this exception.",o)}var s}dl(t){try{var e=this.rl.getAttachable();return e.length===0?t:I({},t,{$exception_steps:e})}catch(n){return St.error("Failed to read buffered exception steps. Capturing exception without steps.",n),t}}ll(t){this.el.enabled&&this.rl.add({[Xr]:t,[Qr]:new Date().toISOString()})}sl(t){return he(t)?I({},t):{}}il(){var t,e;return(t=(e=this._instance.config.error_tracking)==null?void 0:e.exception_steps)!==null&&t!==void 0?t:{}}ol(t){if(t.length===0)return!1;try{var e=t.reduce(((n,i)=>{var r=i.type,s=i.value;return X(r)&&r.length>0&&n.$exception_types.push(r),X(s)&&s.length>0&&n.$exception_values.push(s),n}),{$exception_types:[],$exception_values:[]});return this.Xo.some((n=>{var i=n.values.map((r=>{var s=Yf[r.operator],o=e[r.key];if(!s||!o)return!1;var a=U(r.value)?r.value:[r.value];return a.length>0&&s(a,o)}));return n.type==="OR"?i.some(Boolean):i.every(Boolean)}))}catch(n){return St.warn("Failed to evaluate suppression rules. Capturing the exception.",n),!1}}ul(t){return t.flatMap((e=>{var n,i;return(n=(i=e.stacktrace)==null?void 0:i.frames)!==null&&n!==void 0?n:[]})).some((e=>e.filename&&e.filename.startsWith("chrome-extension://")))}hl(t){if(t.length>0){var e,n,i,r,s=(e=(n=t[0].stacktrace)==null?void 0:n.frames)!==null&&e!==void 0?e:[],o=s[s.length-1];return(i=o==null||(r=o.filename)==null?void 0:r.includes("posthog.com/static"))!==null&&i!==void 0&&i}return!1}al(t){return!H(t)&&U(t)}}},tv=I({productTours:class{get Mr(){return this._instance.persistence}constructor(t){this.vl=null,this.cl=null,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(t.ok){var e=t.config;if("productTours"in e){var n,i;if(this.Mr&&this.Mr.register({[ul]:!!e.productTours}),!Uo(this._instance))return!this.vl&&H((n=this.Mr)==null?void 0:n.props[Oi])||Cr.info("product tours disabled; stopping and clearing cached tours"),(i=this.vl)==null||i.stop(),this.vl=null,void this.clearCache();this.loadIfEnabled()}}}loadIfEnabled(){!this.vl&&Uo(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.generateProductTours?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",(i=>{i?Cr.error("Could not load product tours script",i):t()}))}fl(){var t;!this.vl&&(t=B.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=B.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(t,e){if(e===void 0&&(e=!1),!U(this.cl)||e){var n=this.Mr;if(n){var i=n.props[Oi];if(U(i)&&!e)return this.cl=i,void t(i,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",timestampMode:"query",callback:r=>{if(Uo(this._instance)){var s=r.statusCode;if(s!==200||!r.json){var o="Product Tours API could not be loaded, status: "+s;return s===0?r.error||Cr.warn(o):Cr.error(o),void t([],{isLoaded:!1,error:o})}var a=U(r.json.product_tours)?r.json.product_tours:[];this.cl=a,n&&n.register({[Oi]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){H(this.vl)?t([],{isLoaded:!1,error:"Product tours not loaded"}):this.vl.getActiveProductTours(t)}showProductTour(t){var e;(e=this.vl)==null||e.showTourById(t)}previewTour(t){this.vl?this.vl.previewTour(t):this.ai((()=>{var e;this.fl(),(e=this.vl)==null||e.previewTour(t)}))}dismissProductTour(){var t;(t=this.vl)==null||t.dismissTour("user_clicked_skip")}nextStep(){var t;(t=this.vl)==null||t.nextStep()}previousStep(){var t;(t=this.vl)==null||t.previousStep()}clearCache(){var t;this.cl=null,(t=this.Mr)==null||t.unregister(Oi)}resetTour(t){var e;(e=this.vl)==null||e.resetTour(t)}resetAllTours(){var t;(t=this.vl)==null||t.resetAllTours()}cancelPendingTour(t){var e;(e=this.vl)==null||e.cancelPendingTour(t)}}},Rs),nv={siteApps:class{constructor(t){this.pl=0,this._instance=t,this.gl=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}ml(t,e){if(e){var n=this.globalsForEvent(e);this.gl.push(n),this.gl.length>1e3&&(this.gl=this.gl.slice(10))}}get siteAppLoaders(){var t;return(t=B._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,n,i,r,s,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var f=d[0];l[f]={id:u[f],type:f,properties:d[1]}}var h=t.$set_once,p=t.$set;return{event:I({},yd(t,qm),{properties:I({},t.properties,p?{$set:I({},(e=(n=t.properties)==null?void 0:n.$set)!==null&&e!==void 0?e:{},p)}:{},h?{$set_once:I({},(i=(r=t.properties)==null?void 0:r.$set_once)!==null&&i!==void 0?i:{},h)}:{}),elements_chain:(s=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&s!==void 0?s:"",distinct_id:(a=t.properties)==null?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}bl(t){var e,n=(e=t.tagName)==null?void 0:e.toLowerCase();return n==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(Et.error("prepare_external_dependency_stylesheet returned null"),null):n==="script"&&this._instance.config.prepare_external_dependency_script?this._instance.config.prepare_external_dependency_script(t)||(Et.error("prepare_external_dependency_script returned null"),null):t}_l(){var t,e,n,i,r,s,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=P?.defaultView,u=l==null||(t=l.Node)==null?void 0:t.prototype;if(!l||!u)return()=>{};if(this.pl++,this.wl)return this.kl();var c=[],d=this,f=new WeakSet,h=(m,v,E)=>{if(m!=null&&m[v]){var S=m[v];m[v]=E(S),c.push((()=>{m[v]=S}))}},p=m=>{if(f.has(m))return m;var v=d.bl(m);return v&&f.add(v),v},g=m=>m.map((v=>typeof v=="string"?v:p(v))).filter((v=>!Ye(v)));return h(u,"appendChild",(m=>function(v){var E=p(v);return E?m.call(this,E):v})),h(u,"insertBefore",(m=>function(v,E){var S=p(v);return S?m.call(this,S,E):v})),h(u,"replaceChild",(m=>function(v,E){var S=p(v);return S?m.call(this,S,E):E})),[(e=l.Element)==null?void 0:e.prototype,(n=l.Document)==null?void 0:n.prototype,(i=l.DocumentFragment)==null?void 0:i.prototype].forEach((m=>{h(m,"append",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),h(m,"prepend",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))}))})),[(r=l.Element)==null?void 0:r.prototype,(s=l.CharacterData)==null?void 0:s.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((m=>{h(m,"before",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),h(m,"after",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];return v.apply(this,g(S))})),h(m,"replaceWith",(v=>function(){for(var E=arguments.length,S=new Array(E),_=0;E>_;_++)S[_]=arguments[_];var b=g(S);return S.length&&!b.length?void 0:v.apply(this,b)}))})),h((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(v,E){var S=p(E);return S?m.call(this,v,S):null})),this.wl=()=>{c.forEach((m=>m())),this.wl=void 0},this.kl()}kl(){var t=!1;return()=>{var e;t||(t=!0,this.pl--,this.pl===0&&((e=this.wl)==null||e.call(this)))}}xl(t,e){e===void 0&&(e=!0);var n=this._l();try{var i=t(n);return e&&n(),i}catch(r){throw n(),r}}setupSiteApp(t){var e=this.apps[t.id],n=()=>{var o;!e.errored&&this.gl.length&&(Et.info("Processing "+this.gl.length+" events for site app with id "+t.id),this.gl.forEach((a=>this.xl((()=>e.processEvent==null?void 0:e.processEvent(a))))),e.processedBuffer=!0),Object.values(this.apps).every((a=>a.processedBuffer||a.errored))&&((o=this.yl)==null||o.call(this))},i=!1,r=o=>{e.errored=!o,e.loaded=!0,Et.info("Site app with id "+t.id+" "+(o?"loaded":"errored")),i&&n()};try{var s=this.xl((o=>t.init({posthog:this._instance,callback(a){o(),r(a)}})),!1).processEvent;s&&(e.processEvent=s),i=!0}catch(o){Et.error(mu+t.id,o),r(!1)}if(i&&e.loaded)try{n()}catch(o){Et.error("Error while processing buffered events PostHog app with config id "+t.id,o),e.errored=!0}}Sl(){var t=this.siteAppLoaders||[];for(var e of t)this.apps[e.id]={id:e.id,loaded:!1,errored:!1,processedBuffer:!1};for(var n of t)this.setupSiteApp(n)}Cl(t){var e=this;if(Object.keys(this.apps).length!==0){var n=this.globalsForEvent(t),i=function(s){try{e.xl((()=>s.processEvent==null?void 0:s.processEvent(n)))}catch(o){Et.error("Error while processing event "+t.event+" for site app "+s.id,o)}};for(var r of Object.values(this.apps))i(r)}}onRemoteConfig(t){var e,n,i,r=this;if((e=this.siteAppLoaders)!=null&&e.length)return this.isEnabled?(this.Sl(),void this._instance.on("eventCaptured",(l=>this.Cl(l)))):void Et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((n=this.yl)==null||n.call(this),t.ok){var s=t.config;if((i=s.siteApps)!=null&&i.length)if(this.isEnabled){var o=function(){var l,u=a.id,c=a.url;B["__$$ph_site_app_"+u]=r._instance,(l=B.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(r._instance,c,(d=>{if(d)return Et.error(mu+u,d)}))};for(var a of s.siteApps)o()}else Et.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},iv={tracingHeaders:class{constructor(t){this.Ml=void 0,this.Tl=void 0,this.El=void 0,this.Uo=()=>{var e,n,i=this.Il();i?(C(this.Ml)&&(this.Ml=(e=B.__PosthogExtensions__)==null||(e=e.tracingHeadersPatchFns)==null?void 0:e._patchXHR(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager)),C(this.Tl)&&(this.Tl=(n=B.__PosthogExtensions__)==null||(n=n.tracingHeadersPatchFns)==null?void 0:n._patchFetch(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager))):this.Qo()},this._instance=t}initialize(){this.startIfEnabledOrStop()}ai(t){var e,n;(e=B.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(n=B.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",(i=>{if(i)return Wm.error("failed to load script",i);t()}))}Pl(){var t,e;return(t=(e=this._instance.config.tracing_headers)!==null&&e!==void 0?e:this._instance.config.addTracingHeaders)!==null&&t!==void 0?t:this._instance.config.__add_tracing_headers}Il(){var t=this.Pl();return U(t)?(U(this.El)?this.El.splice(0,this.El.length,...t):this.El=[...t],t.length>0?this.El:void 0):(U(this.El)&&this.El.splice(0),this.El=t||void 0,this.El)}Qo(){var t,e;(t=this.Ml)==null||t.call(this),(e=this.Tl)==null||e.call(this),this.Ml=void 0,this.Tl=void 0}startIfEnabledOrStop(){this.Il()?this.ai(this.Uo):this.Qo()}}},rv=I({surveys:class{get Ne(){return this._instance.config}constructor(t){this.Rl=void 0,this._surveyManager=null,this.Al=!1,this.Fl=[],this.Ll=null,this.Ol=null,this._instance=t,this._surveyEventReceiver=null}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this.Ne.disable_surveys){if(!t.ok)return Q.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(H(e))return Q.warn("Flags not loaded yet. Not loading surveys.");var n=U(e);this.Rl=n?e.length>0:e,Q.info("flags response received, isSurveysEnabled: "+this.Rl),this.loadIfEnabled()}}reset(){try{var t;(t=this._surveyEventReceiver)==null||t.reset(),localStorage.removeItem("lastSeenSurveyDate");for(var e=[],n=0;nlocalStorage.removeItem(r)))}catch{}}loadIfEnabled(){if(!this._surveyManager)if(this.Al)Q.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)Q.info(vu);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())Q.info("Not loading surveys in cookieless mode without consent.");else{var t=B?.__PosthogExtensions__;if(t){if(!C(this.Rl)||this.Ne.advanced_enable_surveys){var e=this.Rl||this.Ne.advanced_enable_surveys;this.Al=!0;try{var n=t.generateSurveys;if(n)return void this.Dl(n,e);var i=t.loadExternalDependency;if(!i)return void this.$l(fl);i(this._instance,"surveys",(r=>{r||!t.generateSurveys?this.$l("Could not load surveys script",r):this.Dl(t.generateSurveys,e)}))}catch(r){throw this.$l("Error initializing surveys",r),r}finally{this.Al=!1}}}else Q.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new Km(this._instance),Q.info("Surveys loaded successfully"),this.Nl({isLoaded:!0})}$l(t,e){Q.error(t,e),this.Nl({isLoaded:!1,error:t})}onSurveysLoaded(t){return this.Fl.push(t),this._surveyManager&&this.Nl({isLoaded:!0}),()=>{this.Fl=this.Fl.filter((e=>e!==t))}}getSurveys(t,e){if(e===void 0&&(e=!1),this.Ne.disable_surveys)return Q.info(vu),t([]);var n,i=this._instance.get_property(fa);if(i&&!e)return t(i,{isLoaded:!0}),void(this.ql()&&this.getSurveys((()=>{}),!0));typeof Promise<"u"&&this.Ll?this.Ll.then((r=>t(r.surveys,r.context))):(typeof Promise<"u"&&(this.Ll=new Promise((r=>{n=r}))),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this.Ne.token),method:"GET",timestampMode:"query",timeout:this.Ne.surveys_request_timeout_ms,callback:r=>{var s;this.Ll=null;var o=r.statusCode;if(o!==200||!r.json){var a="Surveys API could not be loaded, status: "+o;o!==0?Q.error(a):r.error||Q.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(n==null||n({surveys:[],context:l}))}this.Ol=null;var u,c=r.json.surveys||[],d=c.filter((h=>(function(p){return!(!p.start_date||p.end_date)})(h)&&(Zf(h)||(function(p){var g;return!((g=p.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(h))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(s=this._instance.persistence)==null||s.register({[fa]:c,[ns]:Date.now()});var f={isLoaded:!0};t(c,f),n?.({surveys:c,context:f})}}))}ql(){return this.jl()&&!this.Ll&&!this.Bl()}jl(){var t=this._instance.get_property(ns);return ke(t)&&Date.now()-t>3e5}Bl(){return ke(this.Ol)&&3e5>Date.now()-this.Ol}markSurveyAsSeen(t,e){var n,i={id:t,current_iteration:(n=e?.iteration)!==null&&n!==void 0?n:null};Qf(i);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}}Nl(t){for(var e of this.Fl)try{if(!t.isLoaded)return e([],t);this.getSurveys(e)}catch(n){Q.error("Error in survey callback",n)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!H(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);Q.warn("init was not called")}Hl(t){var e=null;return this.getSurveys((n=>{var i;e=(i=n.find((r=>r.id===t)))!==null&&i!==void 0?i:null})),e}Ul(t){if(H(this._surveyManager))return{eligible:!1,reason:Ar};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyEligibility(e):{eligible:!1,reason:"Survey not found"}}zl(t){if(H(this._surveyManager))return{eligible:!1,reason:Ar};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyRenderability(e):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(t){if(H(this._surveyManager))return Q.warn("init was not called"),{visible:!1,disabledReason:Ar};var e=this.zl(t);return{visible:e.eligible,disabledReason:e.reason}}canRenderSurveyAsync(t,e){return H(this._surveyManager)?(Q.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Ar})):new Promise((n=>{this.getSurveys((i=>{var r,s=(r=i.find((a=>a.id===t)))!==null&&r!==void 0?r:null;if(s){var o=this.zl(s);n({visible:o.eligible,disabledReason:o.reason})}else n({visible:!1,disabledReason:"Survey not found"})}),e)}))}renderSurvey(t,e,n){var i;if(H(this._surveyManager))Q.warn("init was not called");else{var r=typeof t=="string"?this.Hl(t):t;if(r!=null&&r.id)if(Fm.includes(r.type)){var s=P?.querySelector(e);if(s)return(i=r.appearance)!=null&&i.surveyPopupDelaySeconds?(Q.info("Rendering survey "+r.id+" with delay of "+r.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;Q.info("Rendering survey "+r.id+" with delay of "+((o=r.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(a=this._surveyManager)==null||a.renderSurvey(r,s,n),Q.info("Survey "+r.id+" rendered")}),1e3*r.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(r,s,n);Q.warn("Survey element not found")}else Q.warn("Surveys of type "+r.type+" cannot be rendered in the app");else Q.warn("Survey not found")}}displaySurvey(t,e){var n;if(H(this._surveyManager))Q.warn("init was not called");else{var i=this.Hl(t);if(i){var r=i;if((n=i.appearance)!=null&&n.surveyPopupDelaySeconds&&e.ignoreDelay&&(r=I({},i,{appearance:I({},i.appearance,{surveyPopupDelaySeconds:0})})),e.displayType!==Ea.Popover&&e.initialResponses&&Q.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),e.ignoreConditions===!1){var s=this.Ul(i);if(!s.eligible)return void Q.warn("Survey is not eligible to be displayed: ",s.reason)}e.displayType!==Ea.Inline?this._surveyManager.handlePopoverSurvey(r,e):this.renderSurvey(r,e.selector,e.properties)}else Q.warn("Survey not found")}}cancelPendingSurvey(t){H(this._surveyManager)?Q.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},Rs),sv={toolbar:class{constructor(t){this.instance=t}Wl(t){B.ph_toolbar_state=t}Vl(){var t;return(t=B.ph_toolbar_state)!==null&&t!==void 0?t:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(t,e,n){if(t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),ya(this.instance.config)||!w||!P)return!1;t=t??w.location,n=n??w.history;try{if(!e){try{w.localStorage.setItem("test","test"),w.localStorage.removeItem("test")}catch{return!1}e=w?.localStorage}var i,r=Ym||us(t.hash,"__posthog")||us(t.hash,"state"),s=r?Lc((()=>JSON.parse(atob(decodeURIComponent(r)))))||Lc((()=>JSON.parse(decodeURIComponent(r)))):null;return s&&s.action==="ph_authorize"?((i=s).source="url",i&&Object.keys(i).length>0&&(s.desiredHash?t.hash=s.desiredHash:n?n.replaceState(n.state,"",t.pathname+t.search):t.hash="")):((i=JSON.parse(e.getItem(_u)||"{}")).source="localstorage",delete i.userIntent),!(!i.token||this.instance.config.token!==i.token||(this.loadToolbar(i),0))}catch{return!1}}Zl(t){var e=B.ph_load_toolbar||B.ph_load_editor;!H(e)&&je(e)?e(t,this.instance):yu.warn("No toolbar load function found")}loadToolbar(t){var e=!(P==null||!P.getElementById(pf));if(!w||e)return!1;var n=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,i=I({token:this.instance.config.token},t,{apiURL:this.instance.requestRouter.endpointFor("ui")},n?{instrument:!1}:{});if(w.localStorage.setItem(_u,JSON.stringify(I({},i,{source:void 0}))),this.Vl()===2)this.Zl(i);else if(this.Vl()===0){var r;this.Wl(1),(r=B.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"toolbar",(s=>{if(s)return yu.error("[Toolbar] Failed to load",s),void this.Wl(0);this.Wl(2),this.Zl(i)})),ve(w,"turbolinks:load",(()=>{this.Wl(0),this.loadToolbar(i)}))}return!0}Gl(t){return this.loadToolbar(t)}maybeLoadEditor(t,e,n){return t===void 0&&(t=void 0),e===void 0&&(e=void 0),n===void 0&&(n=void 0),this.maybeLoadToolbar(t,e,n)}}},ov=I({experiments:Me},Rs),av={conversations:class{constructor(t){this.Ql=void 0,this._conversationsManager=null,this.Kl=!1,this.Jl=null,this.Yl=!1,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this._instance.config.disable_conversations&&(this.Xl=t.ok,t.ok)){var e=t.config.conversations;H(e)||(mt(e)?this.Ql=e:(this.Ql=e.enabled,this.Jl=e),this.loadIfEnabled())}}reset(){var t;(t=this._conversationsManager)==null||t.reset(),this._conversationsManager=null,this.Ql=void 0,this.Jl=null,this.Xl=void 0,this.Yl=!1}loadIfEnabled(){if(!(this._conversationsManager||this.Kl||this._instance.config.disable_conversations||ya(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=B?.__PosthogExtensions__;if(t&&!C(this.Ql)&&this.Ql)if(this.Jl&&this.Jl.token){this.Kl=!0;try{var e=t.initConversations;if(e)return this.tu(e),void(this.Kl=!1);var n=t.loadExternalDependency;if(!n)return void this.eu(fl);n(this._instance,"conversations",(i=>{i||!t.initConversations?this.eu("Could not load conversations script",i):this.tu(t.initConversations),this.Kl=!1}))}catch(i){this.eu("Error initializing conversations",i),this.Kl=!1}}else ot.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,ot.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else ot.error("Cannot complete initialization: remote config is null")}eu(t,e){ot.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():ot.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!Ye(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":ya(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.Xl===!1?"remote_config_failed":C(this.Ql)?this.Xl?"disabled_in_project":"remote_config_pending":this.Ql?H(this.Jl)||!this.Jl.token?"missing_token":B!=null&&B.__PosthogExtensions__?this.Kl?"initializing":this.Yl?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.isVisible())!==null&&t!==void 0&&t}sendMessage(t,e,n){var i=this;return se((function*(){return i._conversationsManager?i._conversationsManager.sendMessage(t,e,n):(ot.warn(En),null)}))()}getMessages(t,e){var n=this;return se((function*(){return n._conversationsManager?n._conversationsManager.getMessages(t,e):(ot.warn(En),null)}))()}markAsRead(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(ot.warn(En),null)}))()}getTickets(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(ot.warn(En),null)}))()}requestRestoreLink(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(ot.warn(En),null)}))()}restoreFromToken(t){var e=this;return se((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(ot.warn(En),null)}))()}restoreFromUrlToken(){var t=this;return se((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(ot.warn(En),null)}))()}getCurrentTicketId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getCurrentTicketId())!==null&&t!==void 0?t:null}getWidgetSessionId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getWidgetSessionId())!==null&&t!==void 0?t:null}Xn(){var t;(t=this._conversationsManager)==null||t.setIdentity()}ts(){var t;(t=this._conversationsManager)==null||t.clearIdentity()}}},lv={logs:class{constructor(t){var e,n=this;this.iu=!1,this.ru=!1,this.rt=pe("[logs]"),this.nu=I({},this.rt,{error(){for(var i=arguments.length,r=new Array(i),s=0;i>s;s++)r[s]=arguments[s];r.some(Cu)||n.rt.error(...r)}}),this.tr=[],this.su=[],this.Sa=0,this.au=()=>{var i,r;this.Sa=0,(i=this.ou)==null||i.onReconnect(),(r=this.lu)==null||r.onReconnect()},this._instance=t,this._instance&&(e=this._instance.config.logs)!=null&&e.captureConsoleLogs&&(this.iu=!0),w&&ve(w,"online",this.au)}uu(t,e,n,i){var r,s=(function(o,a){var l,u,c,d,f,h,p,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,v=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,E=C(v)?Math.max(m,2048):Math.max(m,v),S=o?.resourceAttributes;return{serviceName:(d=(f=S?.["service.name"])!==null&&f!==void 0?f:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(h=S?.["service.version"])!==null&&h!==void 0?h:o?.serviceVersion,environment:(p=S?.["deployment.environment"])!==null&&p!==void 0?p:o?.environment,resourceAttributes:S,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:E,maxBatchRecordsPerPost:100,rateCapWindowMs:g,maxLogsPerInterval:v,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}})((r=this._instance)==null||(r=r.config)==null?void 0:r.logs,n);return[new fg(this.hu(t,e),s,this.nu,(()=>this.du()),(o=>o()),void 0,i),s]}vu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.ou||this.cu!==e){var n;(n=this.ou)==null||n.reset(),this.cu=e;var i=this.uu((()=>this.tr),(r=>{this.tr=r}));this.ou=i[0],this.fu=i[1]}return this.ou}pu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.lu||this.gu!==e){var n;(n=this.lu)==null||n.reset(),this.gu=e;var i=this.uu((()=>this.su),(r=>{this.su=r}),{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},ku);this.lu=i[0],this.mu=i[1]}return this.lu}initialize(){this.loadIfEnabled()}onRemoteConfig(t){var e;if(t.ok){var n=(e=t.config.logs)==null?void 0:e.captureConsoleLogs;!H(n)&&n&&(this.iu=!0,this.loadIfEnabled())}}reset(){var t,e;this.tr=[],(t=this.ou)==null||t.reset(),this.su=[],(e=this.lu)==null||e.reset(),this.Sa=0}captureLog(t){this.vu().captureLog(t)}he(t){this.pu().captureLog(t)}get logger(){return this.yu||(this.yu={trace:(t,e)=>this.captureLog({body:t,level:"trace",attributes:e}),debug:(t,e)=>this.captureLog({body:t,level:"debug",attributes:e}),info:(t,e)=>this.captureLog({body:t,level:"info",attributes:e}),warn:(t,e)=>this.captureLog({body:t,level:"warn",attributes:e}),error:(t,e)=>this.captureLog({body:t,level:"error",attributes:e}),fatal:(t,e)=>this.captureLog({body:t,level:"fatal",attributes:e})}),this.yu}flushLogs(t){t?this.bu(t):(this.ou&&this.ou.flush().catch((e=>this._u(e))),this.lu&&this.lu.flush().catch((e=>this._u(e))))}_u(t){Cu(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=B?.__PosthogExtensions__;if(t){var e=t.loadExternalDependency;e?e(this._instance,"logs",(n=>{var i;n||(i=t.logs)==null||!i.initializeLogs?this.rt.error("Could not load logs script",n):(t.logs.initializeLogs(this._instance),this.ru=!0)})):this.rt.error(fl)}else this.rt.error("PostHog Extensions not found.")}}hu(t,e){var n=this._instance;return{get isDisabled(){return!1},get optedOut(){return!n.is_capturing()},getPersistedProperty:i=>i===Ut.LogsQueue?t():void 0,setPersistedProperty(i,r){var s;i===Ut.LogsQueue&&e((s=r)!==null&&s!==void 0?s:[])},Ot:i=>this.Ot(i),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Ot(t){return new Promise((e=>{if(kf(this.Sa,3))e({kind:"fatal",error:Wo(void 0,"logs endpoint is unreachable, dropping batch")});else{var n=!1,i=s=>{n||(n=!0,clearTimeout(r),e(s))},r=setTimeout((()=>{this.rt.warn("Logs request timed out before receiving a response"),i({kind:"retry-later",error:Wo(void 0,"logs request timed out")})}),9e4);this._instance._send_request({method:"POST",url:this.wu(),data:t,compression:"best-available",batchKey:"logs",fireCallbackOnDrop:!0,callback:s=>{var o=s.statusCode;if(this.ku(o),o>=200&&300>o)i({kind:"ok"});else if(o===413)i({kind:"too-large"});else if(o!==0&&o!==429&&500>o)i({kind:"fatal",error:new Error("logs request failed with status "+o)});else{var a;o===0?(s.error||this.rt.warn("Logs request failed before receiving an HTTP response"),i({kind:"retry-later",error:Wo(s.error,"logs request failed before receiving an HTTP response")})):i({kind:"retry-later",error:(a=s.error)!==null&&a!==void 0?a:new Error("logs request failed with status "+o)})}}})}}))}ku(t){(t!==0||this._instance.__loaded)&&(this.Sa=Cf(t,this.Sa,3,(()=>this.rt.warn("Log requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped sending logs; will try again when connectivity changes."))))}bu(t){this.tr.length>0&&this.xu(t,this.tr,this.fu,ne.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,ku,(e=>{this.su=e}))}xu(t,e,n,i,r){if(e.length!==0){var s=e.map((a=>a.record));r([]);var o=Jd(s,Yd(n,ne.LIB_NAME,ne.LIB_VERSION),i,ne.LIB_VERSION);this._instance._send_request({method:"POST",url:this.wu(),data:o,compression:"best-available",batchKey:"logs",transport:t})}}wu(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}du(){var t,e={};if(e.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var n=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.windowId,r=n.sessionStartTimestamp,s=n.lastActivityTimestamp;e.sessionId=n.sessionId,e.windowId=i,H(r)||(e.sessionStartTimestamp=r),H(s)||(e.lastActivityTimestamp=s)}if(B!=null&&(t=B.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?fn(B.location.href):B.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},cv={metrics:class{constructor(t){this.rt=pe("[metrics]"),this._instance=t}initialize(){}vu(){var t,e,n=(t=this._instance)==null||(t=t.config)==null?void 0:t.metrics;return this.ou&&this.cu===n||((e=this.ou)==null||e.reset(),this.cu=n,this.ou=new hg(this.hu(),(function(i){var r,s,o,a,l,u=i?.resourceAttributes;return{serviceName:(r=u?.["service.name"])!==null&&r!==void 0?r:i?.serviceName,serviceVersion:(s=u?.["service.version"])!==null&&s!==void 0?s:i?.serviceVersion,environment:(o=u?.["deployment.environment"])!==null&&o!==void 0?o:i?.environment,resourceAttributes:u,beforeSend:i?.beforeSend,flushIntervalMs:(a=i?.flushIntervalMs)!==null&&a!==void 0?a:1e4,maxSeriesPerFlush:(l=i?.maxSeriesPerFlush)!==null&&l!==void 0?l:1e3}})(n),this.rt)),this.ou}count(t,e,n){e===void 0&&(e=1),this.vu().count(t,e,n)}gauge(t,e,n){this.vu().gauge(t,e,n)}histogram(t,e,n){this.vu().histogram(t,e,n)}flush(t){if(!this.ou)return Promise.resolve();if(t){var e=this.ou.drainWindow();return e&&this.Jt(e,t),Promise.resolve()}return this.ou.flush().catch((n=>this.rt.error("PostHog metrics flush failed:",n)))}reset(){var t;(t=this.ou)==null||t.reset()}hu(){var t=this._instance,e=this;return{get isDisabled(){return!1},get optedOut(){return!t.is_capturing()},Jt:n=>e.Jt(n),getLibraryId:()=>ne.LIB_NAME,getLibraryVersion:()=>ne.LIB_VERSION}}Jt(t,e){return new Promise((n=>{var i=!1,r=o=>{i||(i=!0,clearTimeout(s),n(o))},s=setTimeout((()=>r({kind:"retry-later",error:new Error("metrics request timed out")})),9e4);this._instance._send_request(I({method:"POST",url:this.Su(),data:t,compression:"best-available",batchKey:"metrics"},e&&{transport:e},{fireCallbackOnDrop:!0,callback(o){var a=o.statusCode;if(a>=200&&300>a)r({kind:"ok"});else if(a===413)r({kind:"too-large"});else if(a!==0&&a!==429&&500>a)r({kind:"fatal",error:new Error("metrics request failed with status "+a)});else{var l;r({kind:"retry-later",error:(l=o.error)!==null&&l!==void 0?l:new Error("metrics request failed with status "+a)})}}}))}))}Su(){return this._instance.requestRouter.endpointFor("api","/i/v1/metrics")+"?token="+encodeURIComponent(this._instance.config.token)}}},uv=I({},Rs,Xm,Qm,ev,tv,nv,rv,iv,sv,ov,av,lv,cv);Ze.__defaultExtensionClasses=I({},uv);(function(){ne.SDK_DIST_CHANNEL="npm";var t=Vi[Gn]=new Ze;return(function(){function e(){e.done||(e.done=!0,th=!1,ie(Vi,(function(n){n._dom_loaded()})))}P!=null&&P.addEventListener?P.readyState==="complete"?e():ve(P,"DOMContentLoaded",e,{capture:!1}):w&&A.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const dv=["a[href]","button:not([disabled])","input:not([disabled]):not([type='hidden'])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(",");let pt=null,Fa=null,ih="";const Ra=new Map;function rh(t){return[...t.querySelectorAll(dv)].filter(e=>!e.hidden&&e.getAttribute("aria-hidden")!=="true"&&e.getClientRects().length>0)}function fv(t){for(const e of document.body.children)e===t||e.tagName==="SCRIPT"||(Ra.set(e,{inert:e.inert,ariaHidden:e.getAttribute("aria-hidden")}),e.inert=!0,e.setAttribute("aria-hidden","true"))}function hv(){for(const[t,e]of Ra)t.inert=e.inert,e.ariaHidden===null?t.removeAttribute("aria-hidden"):t.setAttribute("aria-hidden",e.ariaHidden);Ra.clear()}function sh(t){return t?.dataset.modalDismissible!=="false"&&t?.getAttribute("aria-busy")!=="true"}function We(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n)return!1;pt&&pt!==n&&ze(pt,{restoreFocus:!1,force:!0}),Fa=e.trigger||document.activeElement,pt=n,ih=document.body.style.overflow,fv(n),document.body.style.overflow="hidden",n.classList.add("open"),n.setAttribute("aria-hidden","false");const i=n.querySelector(".modal-content");i&&(i.style.transform="scale(1) translateY(0)");const r=()=>{if(pt!==n)return;((e.initialFocus?n.querySelector(e.initialFocus):n.querySelector("[data-modal-initial-focus]"))||rh(n)[0]||n.querySelector(".modal-content")||n).focus({preventScroll:!0})};return requestAnimationFrame(r),setTimeout(r,260),!0}function ze(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n||!e.force&&!sh(n))return!1;n.classList.remove("open"),n.setAttribute("aria-hidden","true"),hv(),document.body.style.overflow=ih,pt=null;const i=Fa;return Fa=null,e.restoreFocus!==!1&&i?.isConnected&&i.focus({preventScroll:!0}),!0}function Au(t,e,n="Operation in progress"){const i=typeof t=="string"?document.getElementById(t):t;i&&(i.dataset.modalDismissible=e?"false":"true",i.setAttribute("aria-busy",String(!!e)),e?i.setAttribute("aria-label",n):i.removeAttribute("aria-label"))}function pv(t){if(!sh(t))return;const e=t.dataset.modalCloseHandler;e&&typeof window[e]=="function"?window[e]():ze(t)}document.addEventListener("keydown",t=>{if(!pt)return;if(t.key==="Escape"){t.preventDefault(),t.stopImmediatePropagation(),pv(pt);return}if(t.key!=="Tab"){t.stopPropagation();return}const e=rh(pt);if(!e.length){t.preventDefault(),(pt.querySelector(".modal-content")||pt).focus();return}const n=e[0],i=e[e.length-1];t.shiftKey&&document.activeElement===n?(t.preventDefault(),i.focus()):!t.shiftKey&&document.activeElement===i&&(t.preventDefault(),n.focus())},!0);function gv(){document.querySelectorAll(".modal-overlay").forEach(t=>{t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-hidden",t.classList.contains("open")?"false":"true");const e=t.querySelector(".modal-content");e&&!e.hasAttribute("tabindex")&&(e.tabIndex=-1);const n=t.querySelector("h1, h2, h3");n&&(n.id||(n.id=`${t.id}-title`),t.setAttribute("aria-labelledby",n.id)),t.querySelectorAll(".modal-close").forEach(i=>{i.getAttribute("aria-label")||i.setAttribute("aria-label","Close dialog")})})}const wl=Object.freeze({free:"Free",professional:"Pro",power:"Power"}),mv=Object.freeze({free:2,professional:50,power:2e3}),vv="(contact us)",_v=Object.freeze({free:Object.freeze(["2 generations/month","Gemini model only","Code Review"]),professional:Object.freeze(["50 generations/month","All models","Code Regeneration","Code Review"]),power:Object.freeze(["2000 generations/month","All models","Code Regeneration","Bring your own key (BYOK)","Code Review","All models + early access",`API & MCP access ${vv}`])}),oh="CodeFile",ah="GeneratedCode",yv={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function ln(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Ta(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function wv(t={},e=0){const n=Ta(t.artifactType||t.type||oh),i=Ta(t.artifactName||t.name||t.fileName||`${ah}-${e+1}`);return`${n||"artifact"}-${i||e+1}`}function lh(t={},e=0){const n=ln(t),i=n.artifactType||n.type||oh,r=n.artifactName||n.name||ah;let s=n.fileName||r;return s.endsWith(".dart")||(s+=".dart"),{id:Ta(n.id)||wv({...n,artifactType:i,artifactName:r,fileName:s},e),artifactType:i,artifactName:r,fileName:s,deployPath:n.deployPath||"",description:n.description||"",code:n.code||n.content||"",dependencies:ch(n.dependencies),imports:Array.isArray(n.imports)?n.imports:[],publicApi:Array.isArray(n.publicApi)?n.publicApi:[],relationships:uh(n.relationships),deployStatus:n.deployStatus||"pending",review:n.review||null,metadata:ln(n.metadata),codeType:n.codeType||yv[i]||"O"}}function ch(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const n=ln(e),i=n.name||n.package;return i?{name:i,version:n.version||null,versionRequired:!!(n.versionRequired||n.required),inferred:!!n.inferred,...n.reason?{reason:n.reason}:{}}:null}).filter(Boolean):Object.entries(ln(t)).map(([e,n])=>({name:e,version:n||null,inferred:!1})):[]}function uh(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const n=ln(e);return!n.from&&!n.to?null:{from:n.from||null,to:n.to||null,type:n.type||"uses",description:n.description||""}}).filter(Boolean):[]}function $a(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;try{return JSON.parse(e)}catch{const n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(!n)return null;try{return JSON.parse(n[1].trim())}catch{return null}}}function nr(t,e={}){const n=[],i=typeof t=="string"?$a(t):t,s=ln(i||{});!i&&typeof t=="string"&&n.push("Structured bundle parse failed; using legacy single-artifact fallback.");const o=Array.isArray(s.artifacts)?s.artifacts:[{artifactType:s.artifactType||e.artifactType,artifactName:s.artifactName||e.artifactName,fileName:s.fileName||e.fileName,description:s.description,code:s.code||e.code||(typeof t=="string"?t:""),dependencies:s.dependencies||e.dependencies,relationships:s.relationships||e.relationships}];o.forEach((d,f)=>{!d?.artifactType&&!d?.type&&n.push(`Artifact ${f+1} has no artifactType; it will deploy as a standalone code file under lib/custom_code/ root.`)});const a=o.map((d,f)=>lh(d,f)),l=new Map(o.map((d,f)=>[ln(d).id,a[f]?.id]).filter(([d,f])=>d&&f)),u=d=>l.get(d)||d,c=uh(s.relationships||e.relationships).map(d=>({...d,from:d.from?u(d.from):d.from,to:d.to?u(d.to):d.to}));return{schemaVersion:s.schemaVersion||e.schemaVersion||null,id:s.id||e.id||"bundle-current",title:s.title||s.name||e.title||"Generated artifact bundle",description:s.description||e.description||"",artifacts:a,dependencies:ch(s.dependencies||e.dependencies),relationships:c,deployOrder:Array.isArray(s.deployOrder)?s.deployOrder.map(u):a.map(d=>d.id),warnings:[...n,...Array.isArray(s.warnings)?s.warnings:[]],metadata:ln(s.metadata)}}function li(t){return nr(t).artifacts[0]||lh()}function Zt(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function ci(t){return JSON.stringify(t,null,2)}function bv(t){return ci({task:"architect",userRequest:String(t??"")})}function Ev(t){const e=Zt(t);return e&&typeof e=="object"&&typeof e.task=="string"?ci(e):ci({task:"generate_bundle",bundleSpec:e})}function Sv(t){return ci({task:"review_bundle",generatedBundle:Zt(t),outputRequirements:{bundleReview:["status","score","summary","manualActions","findings"],scoreRange:[0,100],eachArtifact:["id","review.status","review.findings"],manualActions:{definition:"Setup the developer must perform by hand in the FlutterFlow editor that FlutterFlow will NOT do for them.",exclude:["creating the Custom Action, Widget or Code File itself - deploying the code creates it","declaring parameters or return values FlutterFlow derives from the function signature","anything that resolves as a side effect of using the action or widget in the editor","generic advice such as testing, reviewing or rebuilding the app"],preferEmpty:"Return an empty array when nothing qualifies - an empty list is the expected result for most bundles."}}})}function bl(t,e=null){const n={stage:t};return e!=null&&(n.bundle=Zt(e)),n}function xv({bundleSpec:t,artifactBundle:e,bundleReview:n,artifactId:i,userFeedback:r}){return ci({task:"regenerate_artifact",artifactId:i,bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(r)})}function dh({bundleSpec:t,artifactBundle:e,bundleReview:n,userFeedback:i}){return ci({task:"regenerate_bundle",bundleSpec:Zt(t),artifactBundle:Zt(e),bundleReview:Zt(n),userFeedback:String(i??"")})}const Pu={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"},Iv=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function tt(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function kv(t){return tt(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||tt(t.filterSummary)||tt(t.filterResults):!1}function fh(t,e=0){if(!tt(t)||e>3)return null;if(kv(t))return t;for(const n of Iv){const i=t[n];if(tt(i)){const r=fh(i,e+1);if(r)return r}}return null}function gs(t){return Array.isArray(t)?t.some(gs):tt(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(gs):!1}function Ma(t){return Array.isArray(t)?t.some(Ma):tt(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(Ma):!1}function hh(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function Cv(t,e){if(tt(t))for(const[n,i]of Object.entries(t)){if(!tt(i))continue;const r=tt(i.categories)?i.categories:{},s=Object.entries(r).filter(([,o])=>tt(o)&&o.matched===!0).map(([o])=>o);s.length>0?s.forEach(o=>e.add(o)):i.matched===!0&&e.add(hh(n))}}function Av(t,e){if(!t)return;const n=Array.isArray(t)?t.flatMap(i=>tt(i)?Object.entries(i):[]):Object.entries(t);for(const[i,r]of n){if(!gs(r))continue;const s=hh(i),o=r?.raiFilterResult?.raiFilterTypeResults||(s==="rai"?r?.raiFilterTypeResults:null),a=tt(o)?Object.entries(o).filter(([,l])=>gs(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(s)}}function Pv(t){return Pu[t]?Pu[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function Fu(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 Fv(t){const e=fh(t);if(!e)return null;const n=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);Cv(e.filterSummary,n),Av(e.filterResults,n);const i=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||n.size>0,r=e.invocationResult||null,s=Ma(e.filterSummary||e.filterResults);return!i&&!s&&!["PARTIAL","FAILURE"].includes(r)?null:{kind:i?"blocked":"unavailable",invocationResult:r,matchedFilters:[...n]}}function Rv(t,e){const n=Fv(t);if(!n)return null;const i=[...new Set(n.matchedFilters.map(Pv))],r=n.kind==="blocked",s=new Error(r?`Safety screening blocked this pipeline step for ${Fu(i)}.`:"Safety screening could not be completed. Please try again.");return s.name="ModelArmorError",s.code=r?"MODEL_ARMOR_BLOCKED":"MODEL_ARMOR_UNAVAILABLE",s.isModelArmor=!0,s.pipelineStep=e,s.userTitle=r?"Request blocked for safety":"Safety check unavailable",s.userMessage=r?`The safety check detected ${Fu(i)}. Edit your request to remove or rephrase the flagged content, then run the pipeline again.`:"The safety service did not finish all of its checks. Please wait a moment and run the pipeline again.",s.retryExplanation=r?"Trying another model would not change this safety decision.":"A fallback model was not attempted because safety screening must complete first.",s.matchedFilters=n.matchedFilters,s}function Tv(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function Ru(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,n=[];for(const i of Tv(t).split(` +`)){if(!/^[A-Za-z_$]/.test(i)||e.test(i))continue;const r=i.match(/^[\w$<>,?\s[\]]+?\s([a-zA-Z_$][\w$]*)\s*\(/);r&&n.push(r[1])}return n}function El(t,e){const n=t.replace(/\.dart$/,"");if(e==="W")return n.replace(/(^|_)(\w)/g,(i,r,s)=>s.toUpperCase());if(e==="A"){const i=n.replace(/(^|_)(\w)/g,(r,s,o)=>o.toUpperCase());return i.charAt(0).toLowerCase()+i.slice(1)}return e==="F"?"CustomFunctions":e==="C"?t.endsWith(".dart")?t:`${t}.dart`:n}async function Tu(t){const e=new TextEncoder().encode(String(t||"")),n=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n),i=>i.toString(16).padStart(2,"0")).join("")}async function $v(t,e=new Map){const n={},i=new Set;for(const[o,a]of t.entries()){if(a.type==="D"||a.type==="O")continue;const l=El(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await Tu(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await Tu(c)),n[o]=u,a.type==="F"){const d=Ru(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(h=>i.add(h))}}const r=new Set(Ru(e.get("lib/flutter_flow/custom_functions.dart")||"")),s={functions_to_rename:[],functions_to_delete:[],functions_to_add:Array.from(i).filter(o=>!r.has(o))};return{fileMapContents:JSON.stringify(n),functionsMapContents:JSON.stringify(s)}}const Mv=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),$u={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},Lv=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),Nv=["Struct","Record"],Ov=[{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=>zo(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=>zo(t).some(e=>{const n=/^\s*final\s+(?:double|int|String|bool|Color|num)\s+(\w+)\s*;/gm;let i;for(;(i=n.exec(e))!==null;){const r=i[1];if(!(new RegExp(`this\\.${r}\\s*=(?!=)`).test(e)||new RegExp(`[:,]\\s*${r}\\s*=(?!=)`).test(e)))return!0}return!1}),pos:`class W extends StatefulWidget { const W({required this.value}); final double value; }`,neg:`class _P { @@ -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=>Ho(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=>zo(t).some(e=>/final\s+(TextStyle|BoxShadow|FontWeight|FontStyle|TextDirection|TextAlign|EdgeInsets|Offset|Alignment(?:Geometry)?|Border(?:Radius|Side)?|BoxDecoration|BoxConstraints|Gradient|LinearGradient|RadialGradient|ThemeData)\??\s+\w+\s*;/.test(e)),pos:`class W extends StatefulWidget { const W({this.textStyle}); final TextStyle? textStyle; @override _S createState() => _S(); @@ -24,53 +24,53 @@ class _S extends State { @override Widget build(BuildContext c) => const Size final double? width; @override _S createState() => _S(); } -class _S extends State { @override Widget build(BuildContext c) => Padding(padding: const EdgeInsets.all(8), child: const SizedBox()); }`}];function xt(t,e,n){return{artifactId:t.id,artifactName:t.artifactName,artifactType:t.artifactType,severity:e,message:n}}function tr(t){let e="",n=0;for(;n"&&(n--,n===0))return{inner:t.slice(e+1,i),end:i+1};return null}function Lv(t,e){const n=new RegExp(`class\\s+${e}\\b[^{]*\\{`).exec(t);if(!n)return null;let i=0;for(let r=n.index+n[0].length-1;rNv(t).usable);function Bv(t=""){const e=tr(t);return Ov.filter(n=>n.detect(e)).map(({id:n,severity:i,message:r})=>({id:n,severity:i,message:r}))}function Dv(t){const e=[],n=t.matchAll(/\bFuture\b/g);for(const i of n){let r=i.index+6,s=null;const o=r;for(;ro;if(t[r]==="<"){const u=Mv(t,r);if(!u||(s=u.inner.replace(/\s+/g," ").trim(),r=u.end,!/\s/.test(t[r]||"")))continue;for(;rTu(o.functionName)===i);if(r)return r;const s=o=>!o.functionName.startsWith("_");return n.find(s)||n[0]}function Ps(t=""){return Array.from(tr(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function jv(t="",e=""){return bl(t,e)?.returnType||null}function $u(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 Uv(t,e){const n=Ps(e);if(n.length===0)return null;const r=String(t||"").split("/").pop().replace(/\.dart$/,"");if(n.some(l=>$u(l)===r)||n.length>1)return null;const[o]=n,a=`${$u(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 El(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function Hv(t,e,n=""){const i=bl(e,n)?.functionName;if(!i)return null;const r=String(t||"").split("/").pop(),s=wl(r,"A");if(s===i)return null;const o=`${El(i)}.dart`;return`File name "${r}" does not match Action "${i}". FlutterFlow derives the action from the file name, so it looks for "${s}" and reports Action "${s}" declaration not found. Rename the file to "${o}" - FlutterFlow puts an underscore before every capital - or rename the function to "${s}".`}function Wv(t="",e=""){return bl(t,e)!==null}function zv(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(i=>Rv.has(i)?!1:!Tv.some(s=>i.endsWith(s))||e.has(i))}function qv(t,{functionName:e="",declaredTypes:n=new Set}={}){const i=jv(t,e),r=zv(i,n);if(r.length===0)return null;const[s]=r;let o;return n.has(s)?o=`uses Code File type "${s}", which FlutterFlow cannot process as an Action Return Value`:i===s?o="is not a FlutterFlow Action Return Value":o=`uses type "${s}", which is not a FlutterFlow Action Return Value`,`CustomAction return type "${i}" ${o}. Return JSON (Future) or an existing FlutterFlow Data Type (*Struct) instead.`}function Vv(t,e={}){const n=[],i=t.fileName||"",r=t.code||"";if(Fv.has(t.artifactType)||n.push(xt(t,"error",`Unsupported artifact type "${t.artifactType}".`)),i.endsWith(".dart")||n.push(xt(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!r.trim())return n.push(xt(t,"warning","Generated artifact has no Dart code yet.")),n;if(t.artifactType==="CustomWidget"){/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)||n.push(xt(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const s of Bv(r))n.push(xt(t,s.severity,s.message))}if(t.artifactType==="CustomAction"&&!Wv(r,t.artifactName)&&n.push(xt(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const s=e.declaredTypes||new Set(Ps(r)),o=qv(r,{functionName:t.artifactName,declaredTypes:s});o&&n.push(xt(t,"error",o));const a=Hv(i,r,t.artifactName);a&&n.push(xt(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)&&n.push(xt(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const s=Uv(i,r);s&&n.push(xt(t,"info",s))}return n}function Gv(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],n=new Set(e.flatMap(s=>Ps(s.code||""))),i=e.flatMap(s=>Vv(s,{declaredTypes:n})),r=e.map(s=>({artifactId:s.id,fileName:s.fileName,pathHint:Ru[s.artifactType]||Ru.CodeFile}));return{valid:i.every(s=>s.severity!=="error"),findings:i,deployHints:r}}const Mu="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function Lu(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function Kv(t=""){const e=t.indexOf(Mu);return e===-1?t:t.slice(e+Mu.length).replace(/^\s*\n/,"")}const Yv=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function Jv(t="",e=""){const n=Kv(t),i=new Set((e.match(/^\s*import .*$/gm)||[]).map(Lu).filter(Boolean)),r=n.split(` -`).filter(s=>{const o=Lu(s);return o===null||!i.has(o)?!0:!Yv.test(s)}).join(` -`).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+r}const Zv=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations"]);function dh(t){let e="",n=0;for(;n{const i=n.name||n.package;if(!i||i==="flutter")return e;const r=n.versionRequired||n.required;return e[i]=r&&n.version||"",e},{})}function n_(t){const e=new Map,n=new Map,i=[];for(const r of t)e.has(r.fileName)?i.push(`Duplicate deploy file name "${r.fileName}" for artifacts "${e.get(r.fileName)}" and "${r.artifactId}".`):e.set(r.fileName,r.artifactId),n.has(r.path)?i.push(`Duplicate deploy path "${r.path}" for artifacts "${n.get(r.path)}" and "${r.artifactId}".`):n.set(r.path,r.artifactId);return i}function i_(t,e={}){const n=Array.isArray(t?.artifacts)?t.artifacts:[],r=(e.selectedArtifactIds||t?.deployOrder||n.map(h=>h.id)).map(h=>n.find(p=>p.id===h)).filter(Boolean),s=[...t?.warnings||[]];let o=[];r.forEach(h=>{const p=t_(h),g=h.fixedCode||h.code||"",m=h.codeType||Qv[h.artifactType]||Xe.OTHER;g.trim()||s.push(`${h.artifactName||h.id} has no generated code.`),o.push({artifactId:h.id,artifactName:h.artifactName,artifactType:h.artifactType,fileName:p,content:g,type:m,path:h.deployPath||e_(p,m),deployPath:h.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((h,p)=>({entry:h,index:p})).filter(({entry:h})=>h.type===Xe.FUNCTION&&h.path===a);if(l.length>1){const h=l[0],p={...h.entry,artifactId:l.map(({entry:m})=>m.artifactId).join("+"),artifactName:h.entry.artifactName,content:l.map(({entry:m})=>`// ${m.artifactId} +class _S extends State { @override Widget build(BuildContext c) => Padding(padding: const EdgeInsets.all(8), child: const SizedBox()); }`}];function xt(t,e,n){return{artifactId:t.id,artifactName:t.artifactName,artifactType:t.artifactType,severity:e,message:n}}function ir(t){let e="",n=0;for(;n"&&(n--,n===0))return{inner:t.slice(e+1,i),end:i+1};return null}function Dv(t,e){const n=new RegExp(`class\\s+${e}\\b[^{]*\\{`).exec(t);if(!n)return null;let i=0;for(let r=n.index+n[0].length-1;rjv(t).usable);function Hv(t=""){const e=ir(t);return Uv.filter(n=>n.detect(e)).map(({id:n,severity:i,message:r})=>({id:n,severity:i,message:r}))}function Wv(t){const e=[],n=t.matchAll(/\bFuture\b/g);for(const i of n){let r=i.index+6,s=null;const o=r;for(;ro;if(t[r]==="<"){const u=Bv(t,r);if(!u||(s=u.inner.replace(/\s+/g," ").trim(),r=u.end,!/\s/.test(t[r]||"")))continue;for(;rMu(o.functionName)===i);if(r)return r;const s=o=>!o.functionName.startsWith("_");return n.find(s)||n[0]}function Ts(t=""){return Array.from(ir(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function zv(t="",e=""){return Sl(t,e)?.returnType||null}function Lu(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 qv(t,e){const n=Ts(e);if(n.length===0)return null;const r=String(t||"").split("/").pop().replace(/\.dart$/,"");if(n.some(l=>Lu(l)===r)||n.length>1)return null;const[o]=n,a=`${Lu(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 xl(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function Vv(t,e,n=""){const i=Sl(e,n)?.functionName;if(!i)return null;const r=String(t||"").split("/").pop(),s=El(r,"A");if(s===i)return null;const o=`${xl(i)}.dart`;return`File name "${r}" does not match Action "${i}". FlutterFlow derives the action from the file name, so it looks for "${s}" and reports Action "${s}" declaration not found. Rename the file to "${o}" - FlutterFlow puts an underscore before every capital - or rename the function to "${s}".`}function Gv(t="",e=""){return Sl(t,e)!==null}function Kv(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(i=>Lv.has(i)?!1:!Nv.some(s=>i.endsWith(s))||e.has(i))}function Yv(t,{functionName:e="",declaredTypes:n=new Set}={}){const i=zv(t,e),r=Kv(i,n);if(r.length===0)return null;const[s]=r;let o;return n.has(s)?o=`uses Code File type "${s}", which FlutterFlow cannot process as an Action Return Value`:i===s?o="is not a FlutterFlow Action Return Value":o=`uses type "${s}", which is not a FlutterFlow Action Return Value`,`CustomAction return type "${i}" ${o}. Return JSON (Future) or an existing FlutterFlow Data Type (*Struct) instead.`}function Jv(t,e={}){const n=[],i=t.fileName||"",r=t.code||"";if(Mv.has(t.artifactType)||n.push(xt(t,"error",`Unsupported artifact type "${t.artifactType}".`)),i.endsWith(".dart")||n.push(xt(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!r.trim())return n.push(xt(t,"warning","Generated artifact has no Dart code yet.")),n;if(t.artifactType==="CustomWidget"){/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)||n.push(xt(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const s of Hv(r))n.push(xt(t,s.severity,s.message))}if(t.artifactType==="CustomAction"&&!Gv(r,t.artifactName)&&n.push(xt(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const s=e.declaredTypes||new Set(Ts(r)),o=Yv(r,{functionName:t.artifactName,declaredTypes:s});o&&n.push(xt(t,"error",o));const a=Vv(i,r,t.artifactName);a&&n.push(xt(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)&&n.push(xt(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const s=qv(i,r);s&&n.push(xt(t,"info",s))}return n}function Zv(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],n=new Set(e.flatMap(s=>Ts(s.code||""))),i=e.flatMap(s=>Jv(s,{declaredTypes:n})),r=e.map(s=>({artifactId:s.id,fileName:s.fileName,pathHint:$u[s.artifactType]||$u.CodeFile}));return{valid:i.every(s=>s.severity!=="error"),findings:i,deployHints:r}}const Nu="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function Ou(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function Xv(t=""){const e=t.indexOf(Nu);return e===-1?t:t.slice(e+Nu.length).replace(/^\s*\n/,"")}const Qv=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function e_(t="",e=""){const n=Xv(t),i=new Set((e.match(/^\s*import .*$/gm)||[]).map(Ou).filter(Boolean)),r=n.split(` +`).filter(s=>{const o=Ou(s);return o===null||!i.has(o)?!0:!Qv.test(s)}).join(` +`).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+r}const t_=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations"]);function ph(t){let e="",n=0;for(;n{const i=n.name||n.package;if(!i||i==="flutter")return e;const r=n.versionRequired||n.required;return e[i]=r&&n.version||"",e},{})}function o_(t){const e=new Map,n=new Map,i=[];for(const r of t)e.has(r.fileName)?i.push(`Duplicate deploy file name "${r.fileName}" for artifacts "${e.get(r.fileName)}" and "${r.artifactId}".`):e.set(r.fileName,r.artifactId),n.has(r.path)?i.push(`Duplicate deploy path "${r.path}" for artifacts "${n.get(r.path)}" and "${r.artifactId}".`):n.set(r.path,r.artifactId);return i}function a_(t,e={}){const n=Array.isArray(t?.artifacts)?t.artifacts:[],r=(e.selectedArtifactIds||t?.deployOrder||n.map(h=>h.id)).map(h=>n.find(p=>p.id===h)).filter(Boolean),s=[...t?.warnings||[]];let o=[];r.forEach(h=>{const p=s_(h),g=h.fixedCode||h.code||"",m=h.codeType||i_[h.artifactType]||Xe.OTHER;g.trim()||s.push(`${h.artifactName||h.id} has no generated code.`),o.push({artifactId:h.id,artifactName:h.artifactName,artifactType:h.artifactType,fileName:p,content:g,type:m,path:h.deployPath||r_(p,m),deployPath:h.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((h,p)=>({entry:h,index:p})).filter(({entry:h})=>h.type===Xe.FUNCTION&&h.path===a);if(l.length>1){const h=l[0],p={...h.entry,artifactId:l.map(({entry:m})=>m.artifactId).join("+"),artifactName:h.entry.artifactName,content:l.map(({entry:m})=>`// ${m.artifactId} ${m.content}`).join(` -`)},g=new Set(l.slice(1).map(({index:m})=>m));o=o.filter((m,v)=>!g.has(v)),o[h.index]=p}const u={...Nu(t?.dependencies),...r.reduce((h,p)=>({...h,...Nu(p.dependencies)}),{})},c={};r.forEach(h=>{Sl(h.code||"").forEach(p=>{p in u||(c[p]="")})});const d={...c,...u},f=n_(o);return{bundleId:t?.id||"bundle-current",title:t?.title||"Generated artifact bundle",fileEntries:o,dependencies:d,relationships:t?.relationships||[],warnings:s,errors:f}}function r_(t){return String(t||"").match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/)?.[1]}function s_(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 o_(t,e){const i=[s_(t),r_(e.content),e.artifactName].find(r=>/^[A-Z][A-Za-z0-9_]*$/.test(String(r||"")));if(!i)throw new Error(`Cannot derive a FlutterFlow custom class name for ${t}.`);return i}function a_(t,e=new Map){const n=[];for(const[i,r]of t.entries())r.type!=="C"||e.has(r.path)||n.push({artifactId:r.artifactId||i,className:o_(i,r),content:r.content,fileName:i,path:r.path});return n}function l_(t,e){const n=new Set(e.map(i=>i.path));return new Map(Array.from(t.entries()).filter(([,i])=>!n.has(i.path)))}const Ou={pass:0,warning:1,fail:2},c_=["manualActions"];function st(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Vt(...t){for(const e of t){if(typeof e=="string"&&e.trim())return e.trim();if(Array.isArray(e)&&e.length>0){const n=e.filter(i=>typeof i=="string").join(` -`);if(n)return n}}return""}function kt(t){return t==null?[]:Array.isArray(t)?t:[t]}function u_(t){const e=st(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const n=Number(e);if(Number.isFinite(n))return Bu(n);const i=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return i?Bu(Number(i[1])):null}function Bu(t){return t>=0&&t<=100?t:null}function lt(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function xl(t){const e=String(t||"").toLowerCase();return/(fail|error|critical|block|reject|invalid)/.test(e)?"fail":/(warn|attention|manual|partial|incomplete|concern)/.test(e)?"warning":/(pass|success|ready|approve|valid|clean|info|notice)/.test(e)?"pass":null}function $a(...t){return t.filter(Boolean).reduce((e,n)=>Ou[n]>Ou[e]?n:e,"pass")}function fh(t,e="warning",n="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:n};const i=st(t),r=Vt(i.message,i.title,i.issue,i.description,i.summary);return r?{severity:xl(i.severity||i.status||i.level)||e,message:r,suggestion:Vt(i.suggestion,i.fix,i.recommendation,i.action),source:i.source||n}:null}function Ma(t,e="review"){const n=st(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([r,s])=>kt(n[r]).map(o=>fh(o,s,e)).filter(Boolean))}function d_(t,e,n=null){if(typeof t=="string")return{id:`${n||"bundle"}-manual-${e+1}`,title:t,detail:"",location:"",timing:"unspecified",artifactId:n,source:"Code Review"};const i=st(t),r=Vt(i.title,i.action,i.step,i.message,i.name,i.description);return r?{id:i.id||`${n||"bundle"}-manual-${e+1}`,title:r,detail:Vt(i.detail,i.instructions,i.description),location:Vt(i.location,i.flutterFlowPath,i.path),timing:Vt(i.timing,i.phase)||"unspecified",artifactId:n,source:Vt(i.source)||"Code Review"}:null}function La(t,e=null){const n=st(t);return c_.flatMap(i=>kt(n[i])).map((i,r)=>d_(i,r,e)).filter(Boolean)}function f_(t){let e=typeof t=="string"?Ra(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const n=st(e);typeof n.content=="string"&&(e=Ra(n.content)||e);const i=st(e),r=st(i.reviewResult||i.codeReview||i.result);return{rawText:"",root:Object.keys(r).length?r:i}}function h_(t,e){const n=[e.id,e.fileName,e.artifactName].map(lt);return t.find(i=>{const r=st(i);return[r.id,r.fileName,r.artifactName,r.name].map(lt).some(s=>s&&n.includes(s))})||null}function p_(t,e){return kt(t?.metadata?.compatibility?.deployHints).find(r=>lt(r?.artifactId)===lt(e.id)||lt(r?.fileName)===lt(e.fileName))?.pathHint||""}function g_(t,e){return kt(t?.relationships).filter(n=>lt(n?.from)===lt(e.id)||lt(n?.to)===lt(e.id))}function m_(t,e){return kt(t?.metadata?.compatibility?.findings).filter(n=>!n?.artifactId||lt(n.artifactId)===lt(e.id)).map(n=>fh(n,"warning","Compatibility check")).filter(Boolean)}function v_(t,e,n,i){const r=h_(e,n),s=st(r?.review||r||n.review),o=Object.keys(s).length>0,a=[...Ma(s),...m_(t,n)],l=La(s,n.id),u=xl(s.status||s.verdict||s.outcome||s.result),c=a.length?$a(...a.map(f=>f.severity)):null,d=$a(u,c,o?null:"warning");return{...n,index:i,status:d,statusReason:o?Vt(s.summary,s.overview,s.assessment,s.conclusion)||(a.length?`${a.length} review finding${a.length===1?"":"s"}`:"No file-level findings"):"No file-level verdict was returned",reviewComplete:o,findings:a,manualSteps:l,fixedSource:typeof s.fixedSource=="string"&&s.fixedSource.trim()?s.fixedSource.trim():null,pathHint:p_(t,n),relationships:g_(t,n)}}function __({status:t,score:e,artifactPresentations:n,manualSteps:i}){const r=n.length;if(r===0&&i.length===0)return e==null?"Code review returned no overall summary and no score.":`Reviewed bundle with score ${e}/100.`;const s=n.reduce((a,l)=>(a[l.status]+=1,a),{pass:0,warning:0,fail:0}),o=[];return t&&o.push(`Overall verdict: ${t}.`),r&&o.push(`${r} artifact${r===1?"":"s"}: ${s.pass} pass, ${s.warning} warn, ${s.fail} fail.`),i.length&&o.push(`Do before deploy: ${i.map(a=>a.title).join("; ")}.`),e==null&&o.push("No numeric score (0-100) was returned."),o.join(" ")}function y_({bundle:t,reviewResult:e}){const n=st(t),i=kt(n.artifacts),{root:r,rawText:s}=f_(e),o=[r.bundleReview,r.overallReview,r.overall,r.bundleSummary,r.summaryReview,r.review].map(st).find(S=>Object.keys(S).length)||{},a=kt(r.artifacts||r.files||r.reviews),l=i.map((S,_)=>v_(n,a,S,_)),u=Ma(r),d=[...Ma(o),...u],f=[...La(o),...La(r),...l.flatMap(S=>S.manualSteps)].filter((S,_,b)=>b.findIndex(k=>k.title===S.title&&k.artifactId===S.artifactId)===_),h=xl(o.status||o.verdict||o.overallStatus||r.status||r.verdict||r.overallStatus||r.outcome),p=$a(h,...d.map(S=>S.severity),...l.map(S=>S.status)),g=o.score??r.score??r.overallScore??s,m=u_(g),v=Vt(o.headline,o.summary,o.executiveSummary,o.overview,o.assessment,o.conclusion,r.overallSummary,r.headline,r.summary,r.executiveSummary,r.overview,r.assessment,r.conclusion,s)||__({status:p,score:m,artifactPresentations:l,manualSteps:f}),E=l.reduce((S,_)=>(S[_.status]+=1,S),{pass:0,warning:0,fail:0});return{title:n.title||"Generated artifact bundle",description:n.description||"",status:p,score:m,summary:v,findings:d,manualSteps:f,artifacts:l,counts:E,reviewCoverage:{reviewed:l.filter(S=>S.reviewComplete).length,total:l.length},deployOrder:kt(n.deployOrder),relationships:kt(n.relationships),warnings:kt(n.warnings),compatibility:st(n.metadata?.compatibility)}}const w_=/^\uFEFF/;function Ai(t){let e=0,n=t.length;for(;ee&&!t[n-1].trim();)n--;return t.slice(e,n).join(` -`)}function b_(t){const e=String(t??"").replace(w_,"");if(!e.trim())return"";const n=e.split(` -`),i=c=>{const d=c.trim();return/^`{3,}[A-Za-z0-9+#_.-]*$/.test(d)?c.length-c.trimStart().length:-1};let r=0,s=-1;const o=[];{let c=0;for(let d=0;d=0&&(r++,s<0&&(s=d),o.push(c+f)),c+=n[d].length+1}}if(r===0)return Ai(n);{const c=Na(e);if(!c.error&&o.every(f=>ju(f,c.commentAndStringRanges)))return Ai(n)}if(r===1){const c=Ai(n.slice(0,s)),d=Ai(n.slice(s+1));return d.length>=c.length?d:c}const a=[];let l=null;for(let c=0;cm));o=o.filter((m,v)=>!g.has(v)),o[h.index]=p}const u={...Bu(t?.dependencies),...r.reduce((h,p)=>({...h,...Bu(p.dependencies)}),{})},c={};r.forEach(h=>{Il(h.code||"").forEach(p=>{p in u||(c[p]="")})});const d={...c,...u},f=o_(o);return{bundleId:t?.id||"bundle-current",title:t?.title||"Generated artifact bundle",fileEntries:o,dependencies:d,relationships:t?.relationships||[],warnings:s,errors:f}}function l_(t){return String(t||"").match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/)?.[1]}function c_(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 u_(t,e){const i=[c_(t),l_(e.content),e.artifactName].find(r=>/^[A-Z][A-Za-z0-9_]*$/.test(String(r||"")));if(!i)throw new Error(`Cannot derive a FlutterFlow custom class name for ${t}.`);return i}function d_(t,e=new Map){const n=[];for(const[i,r]of t.entries())r.type!=="C"||e.has(r.path)||n.push({artifactId:r.artifactId||i,className:u_(i,r),content:r.content,fileName:i,path:r.path});return n}function f_(t,e){const n=new Set(e.map(i=>i.path));return new Map(Array.from(t.entries()).filter(([,i])=>!n.has(i.path)))}const Du={pass:0,warning:1,fail:2},h_=["manualActions"];function st(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Vt(...t){for(const e of t){if(typeof e=="string"&&e.trim())return e.trim();if(Array.isArray(e)&&e.length>0){const n=e.filter(i=>typeof i=="string").join(` +`);if(n)return n}}return""}function kt(t){return t==null?[]:Array.isArray(t)?t:[t]}function p_(t){const e=st(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const n=Number(e);if(Number.isFinite(n))return ju(n);const i=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return i?ju(Number(i[1])):null}function ju(t){return t>=0&&t<=100?t:null}function lt(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function kl(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 La(...t){return t.filter(Boolean).reduce((e,n)=>Du[n]>Du[e]?n:e,"pass")}function gh(t,e="warning",n="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:n};const i=st(t),r=Vt(i.message,i.title,i.issue,i.description,i.summary);return r?{severity:kl(i.severity||i.status||i.level)||e,message:r,suggestion:Vt(i.suggestion,i.fix,i.recommendation,i.action),source:i.source||n}:null}function Na(t,e="review"){const n=st(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([r,s])=>kt(n[r]).map(o=>gh(o,s,e)).filter(Boolean))}function g_(t,e,n=null){if(typeof t=="string")return{id:`${n||"bundle"}-manual-${e+1}`,title:t,detail:"",location:"",timing:"unspecified",artifactId:n,source:"Code Review"};const i=st(t),r=Vt(i.title,i.action,i.step,i.message,i.name,i.description);return r?{id:i.id||`${n||"bundle"}-manual-${e+1}`,title:r,detail:Vt(i.detail,i.instructions,i.description),location:Vt(i.location,i.flutterFlowPath,i.path),timing:Vt(i.timing,i.phase)||"unspecified",artifactId:n,source:Vt(i.source)||"Code Review"}:null}function Oa(t,e=null){const n=st(t);return h_.flatMap(i=>kt(n[i])).map((i,r)=>g_(i,r,e)).filter(Boolean)}function m_(t){let e=typeof t=="string"?$a(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const n=st(e);typeof n.content=="string"&&(e=$a(n.content)||e);const i=st(e),r=st(i.reviewResult||i.codeReview||i.result);return{rawText:"",root:Object.keys(r).length?r:i}}function v_(t,e){const n=[e.id,e.fileName,e.artifactName].map(lt);return t.find(i=>{const r=st(i);return[r.id,r.fileName,r.artifactName,r.name].map(lt).some(s=>s&&n.includes(s))})||null}function __(t,e){return kt(t?.metadata?.compatibility?.deployHints).find(r=>lt(r?.artifactId)===lt(e.id)||lt(r?.fileName)===lt(e.fileName))?.pathHint||""}function y_(t,e){return kt(t?.relationships).filter(n=>lt(n?.from)===lt(e.id)||lt(n?.to)===lt(e.id))}function w_(t,e){return kt(t?.metadata?.compatibility?.findings).filter(n=>!n?.artifactId||lt(n.artifactId)===lt(e.id)).map(n=>gh(n,"warning","Compatibility check")).filter(Boolean)}function b_(t,e,n,i){const r=v_(e,n),s=st(r?.review||r||n.review),o=Object.keys(s).length>0,a=[...Na(s),...w_(t,n)],l=Oa(s,n.id),u=kl(s.status||s.verdict||s.outcome||s.result),c=a.length?La(...a.map(f=>f.severity)):null,d=La(u,c,o?null:"warning");return{...n,index:i,status:d,statusReason:o?Vt(s.summary,s.overview,s.assessment,s.conclusion)||(a.length?`${a.length} review finding${a.length===1?"":"s"}`:"No file-level findings"):"No file-level verdict was returned",reviewComplete:o,findings:a,manualSteps:l,fixedSource:typeof s.fixedSource=="string"&&s.fixedSource.trim()?s.fixedSource.trim():null,pathHint:__(t,n),relationships:y_(t,n)}}function E_({status:t,score:e,artifactPresentations:n,manualSteps:i}){const r=n.length;if(r===0&&i.length===0)return e==null?"Code review returned no overall summary and no score.":`Reviewed bundle with score ${e}/100.`;const s=n.reduce((a,l)=>(a[l.status]+=1,a),{pass:0,warning:0,fail:0}),o=[];return t&&o.push(`Overall verdict: ${t}.`),r&&o.push(`${r} artifact${r===1?"":"s"}: ${s.pass} pass, ${s.warning} warn, ${s.fail} fail.`),i.length&&o.push(`Do before deploy: ${i.map(a=>a.title).join("; ")}.`),e==null&&o.push("No numeric score (0-100) was returned."),o.join(" ")}function S_({bundle:t,reviewResult:e}){const n=st(t),i=kt(n.artifacts),{root:r,rawText:s}=m_(e),o=[r.bundleReview,r.overallReview,r.overall,r.bundleSummary,r.summaryReview,r.review].map(st).find(S=>Object.keys(S).length)||{},a=kt(r.artifacts||r.files||r.reviews),l=i.map((S,_)=>b_(n,a,S,_)),u=Na(r),d=[...Na(o),...u],f=[...Oa(o),...Oa(r),...l.flatMap(S=>S.manualSteps)].filter((S,_,b)=>b.findIndex(k=>k.title===S.title&&k.artifactId===S.artifactId)===_),h=kl(o.status||o.verdict||o.overallStatus||r.status||r.verdict||r.overallStatus||r.outcome),p=La(h,...d.map(S=>S.severity),...l.map(S=>S.status)),g=o.score??r.score??r.overallScore??s,m=p_(g),v=Vt(o.headline,o.summary,o.executiveSummary,o.overview,o.assessment,o.conclusion,r.overallSummary,r.headline,r.summary,r.executiveSummary,r.overview,r.assessment,r.conclusion,s)||E_({status:p,score:m,artifactPresentations:l,manualSteps:f}),E=l.reduce((S,_)=>(S[_.status]+=1,S),{pass:0,warning:0,fail:0});return{title:n.title||"Generated artifact bundle",description:n.description||"",status:p,score:m,summary:v,findings:d,manualSteps:f,artifacts:l,counts:E,reviewCoverage:{reviewed:l.filter(S=>S.reviewComplete).length,total:l.length},deployOrder:kt(n.deployOrder),relationships:kt(n.relationships),warnings:kt(n.warnings),compatibility:st(n.metadata?.compatibility)}}const x_=/^\uFEFF/;function Fi(t){let e=0,n=t.length;for(;ee&&!t[n-1].trim();)n--;return t.slice(e,n).join(` +`)}function I_(t){const e=String(t??"").replace(x_,"");if(!e.trim())return"";const n=e.split(` +`),i=c=>{const d=c.trim();return/^`{3,}[A-Za-z0-9+#_.-]*$/.test(d)?c.length-c.trimStart().length:-1};let r=0,s=-1;const o=[];{let c=0;for(let d=0;d=0&&(r++,s<0&&(s=d),o.push(c+f)),c+=n[d].length+1}}if(r===0)return Fi(n);{const c=Ba(e);if(!c.error&&o.every(f=>Hu(f,c.commentAndStringRanges)))return Fi(n)}if(r===1){const c=Fi(n.slice(0,s)),d=Fi(n.slice(s+1));return d.length>=c.length?d:c}const a=[];let l=null;for(let c=0;cc.length>0);return u.length===0?"":u.join(` +${d}`,{commentAndStringRanges:g}=Ba(p),m=h.length+1+f;if(Hu(m,g)){l.push(d);continue}a.push(Fi(l)),l=null}const u=a.filter(c=>c.length>0);return u.length===0?"":u.join(` -`)}function E_(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 hh(t){const e=E_(t);return Array.from(e.matchAll(/class\s+([A-Z]\w*)\s+extends\s+[A-Za-z_]\w*Widget\b/g),n=>n[1])}function ph(t){return`${El(t)}.dart`}function S_(t){return wl(t,"W")}const Du={"(":")","[":"]","{":"}"},x_={")":"(","]":"[","}":"{"},I_=/[A-Za-z0-9_]/;function Na(t){const e=[{kind:"code",opener:null,openedLine:0}],n=[];let i=1,r=0;const s=(c,d)=>{(c===` +`)}function k_(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 mh(t){const e=k_(t);return Array.from(e.matchAll(/class\s+([A-Z]\w*)\s+extends\s+[A-Za-z_]\w*Widget\b/g),n=>n[1])}function vh(t){return`${xl(t)}.dart`}function C_(t){return El(t,"W")}const Uu={"(":")","[":"]","{":"}"},A_={")":"(","]":"[","}":"{"},P_=/[A-Za-z0-9_]/;function Ba(t){const e=[{kind:"code",opener:null,openedLine:0}],n=[];let i=1,r=0;const s=(c,d)=>{(c===` `||c==="\r"&&d!==` `)&&i++};let o=null;const a=()=>{for(const c of e)(c.kind==="string"||c.kind==="block-comment"||c.kind==="line-comment")&&n.push({start:c.startIndex,end:t.length})};for(;r0?t[r-1]:"",p=r>1?t[r-2]:"",g=(h==="r"||h==="R")&&!I_.test(p);e.push({kind:"string",quote:c,triple:f,raw:g,startIndex:r,openedLine:i}),r+=f?3:1;continue}if(Du[c]){e.push({kind:"code",opener:c,openedLine:i}),r++;continue}if(x_[c]){if(d.interpolation&&c==="}"){e.pop(),r++;continue}if(d.opener&&Du[d.opener]===c){e.pop(),r++;continue}return d.opener?(a(),{error:o??`line ${i}: "${c}" closes nothing - "${d.opener}" opened on line ${d.openedLine} is still open`,commentAndStringRanges:n}):(a(),{error:o??`line ${i}: unexpected "${c}" with no matching opener`,commentAndStringRanges:n})}s(c,t[r+1]),r++}a();let l=e.length-1;for(;l>0&&e[l].kind==="line-comment";)l--;let u=o;if(!u){const c=e[l];if(!(c.kind==="code"&&!c.opener&&!c.interpolation))if(c.kind==="string")u=`unclosed ${c.triple?"triple-quoted ":""}string starting on line ${c.openedLine} was never closed`;else if(c.kind==="block-comment")u=`unterminated /* comment starting on line ${c.openedLine}`;else if(c.interpolation){const d=e.findLast(h=>h.opener);u=`unclosed "\${" expression${d?` opened on line ${d.openedLine}`:""} was never closed`}else u=`"${c.opener}" opened on line ${c.openedLine} is never closed`}return{error:u,commentAndStringRanges:n}}function k_(t){return Na(String(t??"")).error}function ju(t,e){return e.some(({start:n,end:i})=>t>=n&&ttypeof n=="string"?n:n?.errorMessage).filter(Boolean);return e.length>0?e.join("; "):JSON.stringify(t)}return t&&typeof t=="object"?t.errorMessage||JSON.stringify(t):String(t??"")}const C_=["gmail.com","googlemail.com","outlook.com","hotmail.com","live.com","msn.com"],A_="MAGIC_LINK_SENT",P_="PLUS_ALIAS_REJECTED",F_="Please enter your primary email address. Plus aliases (such as {email}) are not allowed for {domain} accounts.",Fs={allowlistedDomains:C_,successCode:A_,validationCode:P_,messageTemplate:F_},R_=new Set(Fs.allowlistedDomains),T_=Fs.successCode,gh=Fs.validationCode;function Rs(t){return typeof t=="string"?t.trim():""}function $_(t){const e=Rs(t),n=e.lastIndexOf("@");if(n<=0||n===e.length-1)return!1;const i=e.slice(0,n),r=e.slice(n+1).toLowerCase();return R_.has(r)?i.includes("+"):!1}function M_(t,e){return Fs.messageTemplate.replaceAll("{email}",t).replaceAll("{domain}",e)}function mh(t){if(!$_(t))return null;const e=Rs(t),n=e.lastIndexOf("@"),i=e.slice(n+1).toLowerCase();return M_(e,i)}function vh(t,e){return t?.code===gh?t.message||mh(e)||"Please enter your primary email address.":t?.code===T_||!t?.code?`Check your email — we sent a link to ${Rs(e)}`:t.message||"Something went wrong. Please try again."}const L_="ccc_auth_session",N_="ccc_subscription",O_=Object.freeze(["hasSeenWalkthrough"]);function B_(t){const e=[];for(const n of O_)t.getItem(n)!==null&&(t.removeItem(n),e.push(n));return e}function D_(){return[L_,N_]}function j_({storage:t,onIdentityChanged:e,onPlanChanged:n}){for(const i of D_())t.removeItem(i);typeof e=="function"&&e(),typeof n=="function"&&n()}function U_({sendLink:t,getEmail:e,onState:n}){let i=!1;return async function(){if(i)return{status:"busy"};i=!0;let s;try{n({status:"pending",error:null});const o=await t(e());return s={status:"sent",data:o},n({status:"sent",data:o}),s}catch(o){return s={status:"error",error:o},n({status:"error",error:o}),s}finally{i=!1}}}const H_=/^dependencies\s*:\s*(?:#.*)?$/,W_=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function Ts(t){const e=t.match(W_);return e?e[1]??e[2]??e[3]:null}function lr(t){const e=t.trim();return e===""||e.startsWith("#")}function hi(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function kl(t,e){const n=t.findIndex(s=>e.test(s));if(n===-1)return null;let i=n,r=null;for(let s=n+1;s=0.0.0"}`}function G_(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([u])=>u&&u!=="flutter");if(i.length===0)return{yaml:n,added:[],alreadyPresent:[]};const r=n.split(` -`),s=new Set(yh(n)),o=[],a=[];for(const[u,c]of i)s.has(u)?a.push(u):(o.push([u,c]),s.add(u));if(o.length===0)return{yaml:n,added:[],alreadyPresent:a};const l=Cl(r);if(l){const u=o.map(([c,d])=>Uu(l.childIndent,c,d));r.splice(l.endIndex,0,...u)}else r.length>0&&r[r.length-1].trim()!==""&&r.push(""),r.push("dependencies:"),o.forEach(([u,c])=>{r.push(Uu(" ",u,c))});return{yaml:r.join(` -`),added:o.map(([u])=>u),alreadyPresent:a}}function K_(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([l])=>l&&l!=="flutter");if(i.length===0)return{yaml:n,overridden:[],skipped:[]};const r=n.split(` -`),s=Ms(n),o=[],a=[];for(const[l,u]of i){const c=s.get(l);if(!c||!c.isScalar||!String(u||"").trim()){a.push(l);continue}const d=" ".repeat(hi(r[c.lineIndex]));r[c.lineIndex]=`${d}${l}: ${bh(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:r.join(` -`),overridden:o,skipped:a}}function Eh(t){const e=String(t||""),n=[];return e.trim()?(/^name:\s*\S+/m.test(e)||n.push("pubspec.yaml missing name field"),Cl(e.split(` -`))||n.push("pubspec.yaml missing dependencies section"),yh(e).includes("flutter")||n.push("pubspec.yaml missing Flutter SDK dependency"),{valid:n.length===0,errors:n}):(n.push("pubspec.yaml is empty"),{valid:!1,errors:n})}const Y_=">=3.0.0 <4.0.0";function Oa(t){const e=String(t||"").trim(),n=e[0];return n!=="'"&&n!=='"'||e[e.length-1]!==n?e:e.slice(1,-1).replaceAll(`${n}${n}`,n)}function J_(t=""){const e=Xv(t).filter(n=>!n.startsWith("dart:")&&!n.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function Hu(t,e,n){const i=[];for(const[r,s]of t){if(s.isScalar){e[r]=Oa(s.constraint);continue}if(s.sourceKey==="sdk"){n.add(r);continue}if(s.sourceKey===null&&s.version){e[r]=Oa(s.version);continue}i.push(r)}return i}function Z_(t){const e=new Set,n={},i={},r=Hu(Ms(t),n,e);r.push(...Hu(q_(t,"dependency_overrides"),i,e));const s=new Set([...Object.keys(n),...e]),{sdk:o}=wh(t);return{sdkConstraint:Oa(o)||Y_,dependencies:n,overrides:i,sdkPackages:[...e].sort(),availablePackages:s,unrepresentable:r}}function X_(t,e,n){return e.length>0?`${t} imports ${e.join(", ")}, which FlutterFlow only generates once the app is built, so it could not be compiled before the deploy.`:`${t} imports ${n.join(", ")}, which your project's pubspec.yaml does not declare with a version constraint, so it could not be compiled before the deploy.`}function Q_(t,e){const{sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s,availablePackages:o,unrepresentable:a}=Z_(e),l={sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s},u=[],c=[],d=a.map(f=>`Your project declares ${f} from a source that cannot be reproduced outside it, so the pre-deploy compile check runs against a scratch package graph that omits ${f}. Classes that do not import ${f} directly are still checked, but against that reduced graph, so their transitive package resolution may differ from your project's and the check is approximate for them.`);for(const f of t){const{className:h,content:p}=f,g=Sl(p),m=g.filter(S=>a.includes(S));if(m.length>0){c.push({className:h,reason:`${h} was not compiled before deploying: it imports ${m.join(", ")}, which your project declares from a source that cannot be reproduced outside it, so package resolution could not be matched exactly.`});continue}const{unresolvableImports:v}=J_(p),E=g.filter(S=>!o.has(S));if(v.length>0||E.length>0){c.push({className:h,reason:X_(h,v,E)});continue}u.push({fileName:`${El(h)}.dart`,content:p})}return{manifest:l,sources:u,skipped:c,approximate:d}}function Wu(t,e){const n=`${t}${e}`.split(` -`),i=n.pop()??"",r=[];for(const s of n){const o=Sh(s);o&&r.push(o)}return{events:r,buffer:i}}function ey(t){const e=Sh(t);return e?[e]:[]}function Sh(t){const e=t.trim();if(!e)return null;try{const n=JSON.parse(e);return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}const Le=Object.freeze({COMMITTED:"committed",PARTIAL:"partial",FAILED:"failed",UNCONFIRMED:"unconfirmed"}),xh=12e4,Ih=1e4;function kh(t){return t?.unconfirmed===!0||t?.outcome===Le.UNCONFIRMED?Le.UNCONFIRMED:t?.partial===!0||t?.outcome===Le.PARTIAL?Le.PARTIAL:t?.success===!0?Le.COMMITTED:Le.FAILED}class Qe extends Error{constructor(e){super(e),this.name="UnconfirmedDeployError",this.outcome=Le.UNCONFIRMED}}function zu({httpStatus:t}={}){return new Qe(`Every FlutterFlow sync endpoint lost its response or ended in a server error${t?` (last: HTTP ${t})`:""} — neither can prove the push was refused, so it may already have been applied. Open the FlutterFlow project to reconcile before retrying.`)}async function ty(t,e={}){const{onPhase:n,onLog:i}=e;let r=null,s=null,o="";const a=u=>{if(u.event==="phase"){u.phase&&(s=u.phase),u.message&&n&&n(u.message);return}if(u.event==="log"){u.message&&i&&i(u.message);return}r=u};let l=null;try{if(t.body?.getReader){const u=t.body.getReader(),c=new TextDecoder;for(;;){const{done:d,value:f}=await u.read();if(d)break;const h=Wu(o,c.decode(f,{stream:!0}));o=h.buffer,h.events.forEach(a)}}else{const u=Wu("",await t.text());o=u.buffer,u.events.forEach(a)}}catch(u){l=u}return ey(o).forEach(a),r?{...r,success:r.success===!0||r.success===void 0&&t.ok,finalResultReceived:!0,runnerPhase:s,httpStatus:t.status}:{success:!1,finalResultReceived:!1,httpRejected:!t.ok,httpStatus:t.status,runnerPhase:s,error:t.ok?l?"The connection to the FlutterFlow deploy runner dropped before it reported a result.":"The FlutterFlow deploy runner closed the connection before it finished.":`FlutterFlow custom class provisioning failed (HTTP ${t.status}).`}}const ny=new Set(["connected","workspace_init","workspace_ready","verifying"]);function iy(t){return t?.preWrite===!0||Array.isArray(t?.analyzerErrors)&&t.analyzerErrors.length>0?!0:typeof t?.runnerPhase=="string"?ny.has(t.runnerPhase):typeof t?.httpStatus=="number"?t.httpStatus>=400&&t.httpStatus<500:!1}function qu(t){if(t?.finalResultReceived){const e=kh(t);return e===Le.FAILED&&!iy(t)?Le.UNCONFIRMED:e}return t?.httpRejected?Le.FAILED:Le.UNCONFIRMED}function ry(){let t=document.getElementById("fx-grid");if(!t)return null;const e=window.matchMedia("(prefers-reduced-motion: reduce)"),n=window.matchMedia("(pointer: none)");let i=t.getContext("webgl2",{alpha:!0,antialias:!1,depth:!1,stencil:!1,premultipliedAlpha:!0,powerPreference:"low-power"}),r=i?null:t.getContext("2d");if(!i&&!r)return null;const s='',o=`#version 300 es +`){n.push({start:d.startIndex,end:r}),o??=`line ${i}: string starting on line ${d.openedLine} is never closed`,e.pop();continue}if(!d.raw&&c==="\\"){s(t[r+1]??"",t[r+2]??""),r+=2;continue}if(!d.raw&&c==="$"&&t[r+1]==="{"){e.push({kind:"code",opener:null,interpolation:!0}),r+=2;continue}const f=d.triple?3:1;if(c===d.quote&&t.slice(r,r+f)===d.quote.repeat(f)){n.push({start:d.startIndex,end:r+f}),e.pop(),r+=f;continue}s(c,t[r+1]),r++;continue}if(c==="/"&&t[r+1]==="/"){e.push({kind:"line-comment",startIndex:r}),r+=2;continue}if(c==="/"&&t[r+1]==="*"){e.push({kind:"block-comment",startIndex:r,openedLine:i,depth:1}),r+=2;continue}if(c==="'"||c==='"'){const f=t.slice(r,r+3)===c.repeat(3),h=r>0?t[r-1]:"",p=r>1?t[r-2]:"",g=(h==="r"||h==="R")&&!P_.test(p);e.push({kind:"string",quote:c,triple:f,raw:g,startIndex:r,openedLine:i}),r+=f?3:1;continue}if(Uu[c]){e.push({kind:"code",opener:c,openedLine:i}),r++;continue}if(A_[c]){if(d.interpolation&&c==="}"){e.pop(),r++;continue}if(d.opener&&Uu[d.opener]===c){e.pop(),r++;continue}return d.opener?(a(),{error:o??`line ${i}: "${c}" closes nothing - "${d.opener}" opened on line ${d.openedLine} is still open`,commentAndStringRanges:n}):(a(),{error:o??`line ${i}: unexpected "${c}" with no matching opener`,commentAndStringRanges:n})}s(c,t[r+1]),r++}a();let l=e.length-1;for(;l>0&&e[l].kind==="line-comment";)l--;let u=o;if(!u){const c=e[l];if(!(c.kind==="code"&&!c.opener&&!c.interpolation))if(c.kind==="string")u=`unclosed ${c.triple?"triple-quoted ":""}string starting on line ${c.openedLine} was never closed`;else if(c.kind==="block-comment")u=`unterminated /* comment starting on line ${c.openedLine}`;else if(c.interpolation){const d=e.findLast(h=>h.opener);u=`unclosed "\${" expression${d?` opened on line ${d.openedLine}`:""} was never closed`}else u=`"${c.opener}" opened on line ${c.openedLine} is never closed`}return{error:u,commentAndStringRanges:n}}function F_(t){return Ba(String(t??"")).error}function Hu(t,e){return e.some(({start:n,end:i})=>t>=n&&ttypeof n=="string"?n:n?.errorMessage).filter(Boolean);return e.length>0?e.join("; "):JSON.stringify(t)}return t&&typeof t=="object"?t.errorMessage||JSON.stringify(t):String(t??"")}const R_=["gmail.com","googlemail.com","outlook.com","hotmail.com","live.com","msn.com"],T_="MAGIC_LINK_SENT",$_="PLUS_ALIAS_REJECTED",M_="Please enter your primary email address. Plus aliases (such as {email}) are not allowed for {domain} accounts.",$s={allowlistedDomains:R_,successCode:T_,validationCode:$_,messageTemplate:M_},L_=new Set($s.allowlistedDomains),N_=$s.successCode,_h=$s.validationCode;function Ms(t){return typeof t=="string"?t.trim():""}function O_(t){const e=Ms(t),n=e.lastIndexOf("@");if(n<=0||n===e.length-1)return!1;const i=e.slice(0,n),r=e.slice(n+1).toLowerCase();return L_.has(r)?i.includes("+"):!1}function B_(t,e){return $s.messageTemplate.replaceAll("{email}",t).replaceAll("{domain}",e)}function yh(t){if(!O_(t))return null;const e=Ms(t),n=e.lastIndexOf("@"),i=e.slice(n+1).toLowerCase();return B_(e,i)}function wh(t,e){return t?.code===_h?t.message||yh(e)||"Please enter your primary email address.":t?.code===N_||!t?.code?`Check your email — we sent a link to ${Ms(e)}`:t.message||"Something went wrong. Please try again."}const D_="ccc_auth_session",j_="ccc_subscription",U_=Object.freeze(["hasSeenWalkthrough"]);function H_(t){const e=[];for(const n of U_)t.getItem(n)!==null&&(t.removeItem(n),e.push(n));return e}function W_(){return[D_,j_]}function z_({storage:t,onIdentityChanged:e,onPlanChanged:n}){for(const i of W_())t.removeItem(i);typeof e=="function"&&e(),typeof n=="function"&&n()}function q_({sendLink:t,getEmail:e,onState:n}){let i=!1;return async function(){if(i)return{status:"busy"};i=!0;let s;try{n({status:"pending",error:null});const o=await t(e());return s={status:"sent",data:o},n({status:"sent",data:o}),s}catch(o){return s={status:"error",error:o},n({status:"error",error:o}),s}finally{i=!1}}}const V_=/^dependencies\s*:\s*(?:#.*)?$/,G_=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function Ls(t){const e=t.match(G_);return e?e[1]??e[2]??e[3]:null}function cr(t){const e=t.trim();return e===""||e.startsWith("#")}function gi(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function Al(t,e){const n=t.findIndex(s=>e.test(s));if(n===-1)return null;let i=n,r=null;for(let s=n+1;s=0.0.0"}`}function Z_(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([u])=>u&&u!=="flutter");if(i.length===0)return{yaml:n,added:[],alreadyPresent:[]};const r=n.split(` +`),s=new Set(Eh(n)),o=[],a=[];for(const[u,c]of i)s.has(u)?a.push(u):(o.push([u,c]),s.add(u));if(o.length===0)return{yaml:n,added:[],alreadyPresent:a};const l=Pl(r);if(l){const u=o.map(([c,d])=>Wu(l.childIndent,c,d));r.splice(l.endIndex,0,...u)}else r.length>0&&r[r.length-1].trim()!==""&&r.push(""),r.push("dependencies:"),o.forEach(([u,c])=>{r.push(Wu(" ",u,c))});return{yaml:r.join(` +`),added:o.map(([u])=>u),alreadyPresent:a}}function X_(t,e={}){const n=String(t||""),i=Object.entries(e).filter(([l])=>l&&l!=="flutter");if(i.length===0)return{yaml:n,overridden:[],skipped:[]};const r=n.split(` +`),s=Os(n),o=[],a=[];for(const[l,u]of i){const c=s.get(l);if(!c||!c.isScalar||!String(u||"").trim()){a.push(l);continue}const d=" ".repeat(gi(r[c.lineIndex]));r[c.lineIndex]=`${d}${l}: ${xh(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:r.join(` +`),overridden:o,skipped:a}}function Ih(t){const e=String(t||""),n=[];return e.trim()?(/^name:\s*\S+/m.test(e)||n.push("pubspec.yaml missing name field"),Pl(e.split(` +`))||n.push("pubspec.yaml missing dependencies section"),Eh(e).includes("flutter")||n.push("pubspec.yaml missing Flutter SDK dependency"),{valid:n.length===0,errors:n}):(n.push("pubspec.yaml is empty"),{valid:!1,errors:n})}const Q_=">=3.0.0 <4.0.0";function Da(t){const e=String(t||"").trim(),n=e[0];return n!=="'"&&n!=='"'||e[e.length-1]!==n?e:e.slice(1,-1).replaceAll(`${n}${n}`,n)}function ey(t=""){const e=n_(t).filter(n=>!n.startsWith("dart:")&&!n.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function zu(t,e,n){const i=[];for(const[r,s]of t){if(s.isScalar){e[r]=Da(s.constraint);continue}if(s.sourceKey==="sdk"){n.add(r);continue}if(s.sourceKey===null&&s.version){e[r]=Da(s.version);continue}i.push(r)}return i}function ty(t){const e=new Set,n={},i={},r=zu(Os(t),n,e);r.push(...zu(Y_(t,"dependency_overrides"),i,e));const s=new Set([...Object.keys(n),...e]),{sdk:o}=Sh(t);return{sdkConstraint:Da(o)||Q_,dependencies:n,overrides:i,sdkPackages:[...e].sort(),availablePackages:s,unrepresentable:r}}function ny(t,e,n){return e.length>0?`${t} imports ${e.join(", ")}, which FlutterFlow only generates once the app is built, so it could not be compiled before the deploy.`:`${t} imports ${n.join(", ")}, which your project's pubspec.yaml does not declare with a version constraint, so it could not be compiled before the deploy.`}function iy(t,e){const{sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s,availablePackages:o,unrepresentable:a}=ty(e),l={sdkConstraint:n,dependencies:i,overrides:r,sdkPackages:s},u=[],c=[],d=a.map(f=>`Your project declares ${f} from a source that cannot be reproduced outside it, so the pre-deploy compile check runs against a scratch package graph that omits ${f}. Classes that do not import ${f} directly are still checked, but against that reduced graph, so their transitive package resolution may differ from your project's and the check is approximate for them.`);for(const f of t){const{className:h,content:p}=f,g=Il(p),m=g.filter(S=>a.includes(S));if(m.length>0){c.push({className:h,reason:`${h} was not compiled before deploying: it imports ${m.join(", ")}, which your project declares from a source that cannot be reproduced outside it, so package resolution could not be matched exactly.`});continue}const{unresolvableImports:v}=ey(p),E=g.filter(S=>!o.has(S));if(v.length>0||E.length>0){c.push({className:h,reason:ny(h,v,E)});continue}u.push({fileName:`${xl(h)}.dart`,content:p})}return{manifest:l,sources:u,skipped:c,approximate:d}}function qu(t,e){const n=`${t}${e}`.split(` +`),i=n.pop()??"",r=[];for(const s of n){const o=kh(s);o&&r.push(o)}return{events:r,buffer:i}}function ry(t){const e=kh(t);return e?[e]:[]}function kh(t){const e=t.trim();if(!e)return null;try{const n=JSON.parse(e);return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}const Le=Object.freeze({COMMITTED:"committed",PARTIAL:"partial",FAILED:"failed",UNCONFIRMED:"unconfirmed"}),Ch=12e4,Ah=1e4;function Ph(t){return t?.unconfirmed===!0||t?.outcome===Le.UNCONFIRMED?Le.UNCONFIRMED:t?.partial===!0||t?.outcome===Le.PARTIAL?Le.PARTIAL:t?.success===!0?Le.COMMITTED:Le.FAILED}class Qe extends Error{constructor(e){super(e),this.name="UnconfirmedDeployError",this.outcome=Le.UNCONFIRMED}}function Vu({httpStatus:t}={}){return new Qe(`Every FlutterFlow sync endpoint lost its response or ended in a server error${t?` (last: HTTP ${t})`:""} — neither can prove the push was refused, so it may already have been applied. Open the FlutterFlow project to reconcile before retrying.`)}async function sy(t,e={}){const{onPhase:n,onLog:i}=e;let r=null,s=null,o="";const a=u=>{if(u.event==="phase"){u.phase&&(s=u.phase),u.message&&n&&n(u.message);return}if(u.event==="log"){u.message&&i&&i(u.message);return}r=u};let l=null;try{if(t.body?.getReader){const u=t.body.getReader(),c=new TextDecoder;for(;;){const{done:d,value:f}=await u.read();if(d)break;const h=qu(o,c.decode(f,{stream:!0}));o=h.buffer,h.events.forEach(a)}}else{const u=qu("",await t.text());o=u.buffer,u.events.forEach(a)}}catch(u){l=u}return ry(o).forEach(a),r?{...r,success:r.success===!0||r.success===void 0&&t.ok,finalResultReceived:!0,runnerPhase:s,httpStatus:t.status}:{success:!1,finalResultReceived:!1,httpRejected:!t.ok,httpStatus:t.status,runnerPhase:s,error:t.ok?l?"The connection to the FlutterFlow deploy runner dropped before it reported a result.":"The FlutterFlow deploy runner closed the connection before it finished.":`FlutterFlow custom class provisioning failed (HTTP ${t.status}).`}}const oy=new Set(["connected","workspace_init","workspace_ready","verifying"]);function Fh(t){return t?.preWrite===!0||Array.isArray(t?.analyzerErrors)&&t.analyzerErrors.length>0?!0:typeof t?.runnerPhase=="string"?oy.has(t.runnerPhase):typeof t?.httpStatus=="number"?t.httpStatus>=400&&t.httpStatus<500:!1}function Gu(t){if(t?.finalResultReceived){const e=Ph(t);return e===Le.FAILED&&!Fh(t)?Le.UNCONFIRMED:e}return t?.httpRejected?Le.FAILED:Le.UNCONFIRMED}function ay(){let t=document.getElementById("fx-grid");if(!t)return null;const e=window.matchMedia("(prefers-reduced-motion: reduce)"),n=window.matchMedia("(pointer: none)");let i=t.getContext("webgl2",{alpha:!0,antialias:!1,depth:!1,stencil:!1,premultipliedAlpha:!0,powerPreference:"low-power"}),r=i?null:t.getContext("2d");if(!i&&!r)return null;const s='',o=`#version 300 es in vec2 p; void main(){ gl_Position = vec4(p, 0.0, 1.0); }`;function a(){return["#version 300 es","precision highp float;","out vec4 o;","uniform vec2 res;","uniform vec2 design;","uniform vec2 mouse;","uniform float energy;","uniform float parallax;","uniform float t;","uniform vec3 ink;","uniform sampler2D mark;","uniform vec2 rot;","const float WARP_A = 0.0032;","void main(){"," vec2 px = gl_FragCoord.xy * (design / res);"," vec2 p = vec2(px.x, design.y - px.y);"," vec2 off = vec2(0.0, -parallax) + vec2(sin(t * 0.11), cos(t * 0.09)) * 7.0;"," vec2 g = p + off;"," vec2 gm = mouse + off;"," float base = min(design.x, design.y);"," float spacing = clamp(base / 10.0, 64.0, 118.0);"," vec2 rel = g - gm;"," float rho = length(rel) + 1e-5;"," vec2 dir = rel / rho;"," vec2 pw = gm + dir * (rho + WARP_A * rho * rho);"," vec2 cell = floor(pw / spacing);"," vec2 cw = (cell + 0.5) * spacing - gm;"," float Rc = length(cw) + 1e-5;"," float rhoC = (-1.0 + sqrt(1.0 + 4.0 * WARP_A * Rc)) / (2.0 * WARP_A);"," vec2 c = gm + (cw / Rc) * rhoC;"," float cellSize = spacing / (1.0 + 2.0 * WARP_A * rhoC);"," float sigma = spacing * 2.9;"," float f = exp(-(rhoC * rhoC) / (2.0 * sigma * sigma));"," float scale = mix(0.32, 1.42, f);"," float weight = smoothstep(0.06, 0.80, f);"," float hs = cellSize * 0.26 * scale;"," vec2 uv = (g - c) / hs;"," vec2 ruv = mat2(rot.x, rot.y, -rot.y, rot.x) * uv;"," float cov = 0.0;"," if (abs(ruv.x) <= 1.0 && abs(ruv.y) <= 1.0) cov = texture(mark, ruv * 0.5 + 0.5).a;"," float s = cov * weight * energy * 0.26;"," o = vec4(ink * s, s);","}"].join(` -`)}let l=null,u,c,d,f,h,p,g,m,v;function E(Y,W){if(!i)return null;const D=i.createShader(Y);return i.shaderSource(D,W),i.compileShader(D),i.getShaderParameter(D,i.COMPILE_STATUS)?D:(window.console&&console.warn("fx-grid shader: "+i.getShaderInfoLog(D)),null)}if(i){const Y=E(i.VERTEX_SHADER,o),W=E(i.FRAGMENT_SHADER,a());if(Y&&W&&(l=i.createProgram(),i.attachShader(l,Y),i.attachShader(l,W),i.linkProgram(l),i.getProgramParameter(l,i.LINK_STATUS)||(window.console&&console.warn("fx-grid link: "+i.getProgramInfoLog(l)),l=null)),l){i.useProgram(l),i.bindBuffer(i.ARRAY_BUFFER,i.createBuffer()),i.bufferData(i.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),i.STATIC_DRAW);const D=i.getAttribLocation(l,"p");i.enableVertexAttribArray(D),i.vertexAttribPointer(D,2,i.FLOAT,!1,0,0),u=i.getUniformLocation(l,"res"),c=i.getUniformLocation(l,"design"),d=i.getUniformLocation(l,"mouse"),f=i.getUniformLocation(l,"energy"),h=i.getUniformLocation(l,"parallax"),p=i.getUniformLocation(l,"t"),g=i.getUniformLocation(l,"ink"),m=i.getUniformLocation(l,"mark"),v=i.getUniformLocation(l,"rot"),i.enable(i.BLEND),i.blendFunc(i.ONE,i.ONE_MINUS_SRC_ALPHA),i.clearColor(0,0,0,0)}else{i=null;const D=t.cloneNode(!1);if(t.parentNode.replaceChild(D,t),t=D,r=t.getContext("2d"),!r)return null}}function S(Y){if(!Y)return null;const W=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(Y);if(W){let D=W[1];return D.length===3&&(D=D[0]+D[0]+D[1]+D[1]+D[2]+D[2]),[parseInt(D.slice(0,2),16)/255,parseInt(D.slice(2,4),16)/255,parseInt(D.slice(4,6),16)/255]}try{const D=document.createElement("canvas");D.width=1,D.height=1;const ue=D.getContext("2d");ue.fillStyle="rgb(9, 8, 7)";const xe=String(ue.fillStyle);ue.fillStyle=Y;const Fe=String(ue.fillStyle);if(Fe===xe)return null;const dt=/^#([0-9a-f]{6})$/i.exec(Fe);if(dt){const ft=dt[1];return[parseInt(ft.slice(0,2),16)/255,parseInt(ft.slice(2,4),16)/255,parseInt(ft.slice(4,6),16)/255]}const Nt=/rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i.exec(Fe);if(Nt)return[Number(Nt[1])/255,Number(Nt[2])/255,Number(Nt[3])/255]}catch{}return null}function _(){let Y="";try{const W=getComputedStyle(document.documentElement);Y=(W.getPropertyValue("--fx-ink")||"").trim()||(W.getPropertyValue("--fg")||"").trim()}catch{}return S(Y)||[.56,.68,.88]}const b=_();let k=1920,T=1080,x=960,F=540,$=960,O=540,L=.66,N=0,K=-1e9,V=!1,M=0,R=0,Z=null,Ce=!1,oe=!1,ye=!1;const $e=64,ae=15.2;let Ie=0,Se=0;const De=.0032,wt=0,ge=.56,Je=.26,bt=.32,mn=.16,Re=.349;let Pe=wt;function $t(){const Y=t.getBoundingClientRect(),W=t.clientWidth,D=t.clientHeight;if(!Y.width||!W||!D)return;const ue=Math.min(window.devicePixelRatio||1,2),xe=Math.max(.2,Math.min(2,Y.width/W*ue)),Fe=Math.max(2,Math.round(W*xe)),dt=Math.max(2,Math.round(D*xe));(Fe!==t.width||dt!==t.height)&&(t.width=Fe,t.height=dt,i&&i.viewport(0,0,Fe,dt)),k=W,T=D,V||(x=$=k/2,F=O=T/2,V=!0)}function Dn(Y){!l||!Ce||!i||(i.uniform2f(u,t.width,t.height),i.uniform2f(c,k,T),i.uniform2f(d,x,F),i.uniform1f(f,L),i.uniform1f(h,N),i.uniform2f(v,Math.cos(Pe),Math.sin(Pe)),i.uniform1f(p,Y),i.uniform3f(g,b[0],b[1],b[2]),i.clear(i.COLOR_BUFFER_BIT),i.drawArrays(i.TRIANGLES,0,3))}function qe(Y,W,D){const ue=Math.max(0,Math.min(1,(D-Y)/(W-Y)));return ue*ue*(3-2*ue)}function jn(Y){if(!Z||!r)return;const W=r;W.setTransform(1,0,0,1,0,0),W.clearRect(0,0,t.width,t.height);const D=t.width/k;W.setTransform(D,0,0,D,0,0),W.globalAlpha=1;const ue=Math.min(k,T),xe=Math.max(64,Math.min(118,ue/10)),Fe=xe*2.9,dt=2*Fe*Fe,Nt=Math.sin(Y*.11)*7,ft=Math.cos(Y*.09)*7-N,fr=x+Nt,hr=F+ft,ro=Fe*Math.sqrt(2*Math.log(1/.06)),vi=ro+De*ro*ro+xe,Tp=Math.floor((fr-vi)/xe)-1,$p=Math.ceil((fr+vi)/xe)+1,Mp=Math.floor((hr-vi)/xe)-1,Lp=Math.ceil((hr+vi)/xe)+1;for(let so=Mp;so<=Lp;so++){const Np=(so+.5)*xe;for(let oo=Tp;oo<=$p;oo++){const ao=(oo+.5)*xe-fr,lo=Np-hr,co=Math.sqrt(ao*ao+lo*lo)+1e-5;if(co>vi)continue;const pr=(-1+Math.sqrt(1+4*De*co))/(2*De),dc=Math.exp(-(pr*pr)/dt),fc=qe(.06,.8,dc)*L*.26;if(fc<.004)continue;const on=xe/(1+2*De*pr)*.26*(.32+1.1*dc),hc=pr/co,uo=fr+ao*hc,fo=hr+lo*hc;uo<-on*1.6||uo>k+on*1.6||fo<-on*1.6||fo>T+on*1.6||(W.globalAlpha=fc,W.save(),W.translate(uo,fo),W.rotate(Pe),W.drawImage(Z,-on,-on,on*2,on*2),W.restore())}}W.globalAlpha=1}function Mt(Y){if(!oe)return;const W=R?Math.min(.05,(Y-R)/1e3):.016;R=Y;const ue=Y-K>2400?.6:1;L+=(ue-L)*Math.min(1,W*3.2);const xe=Math.min(.05,W);Ie+=(($-x)*$e-Ie*ae)*xe,Se+=((O-F)*$e-Se*ae)*xe,x+=Ie*xe,F+=Se*xe,N=(window.scrollY||window.pageYOffset||0)*.55;const Fe=Y/1e3,dt=x/(k||1)-.5,Nt=F/(T||1)-.5;let ft=dt*(dt>=0?ge:Je)+Nt*(Nt>=0?bt:mn);ft>Re?ft=Re:ft<-Re&&(ft=-Re),Pe=wt+ft-N*6e-4,$t(),i?Dn(Fe):jn(Fe),M=requestAnimationFrame(Mt)}function Lt(Y){if(!oe)return;const W=t.getBoundingClientRect();!W.width||!k||!T||($=(Y.clientX-W.left)/W.width*k,O=(Y.clientY-W.top)/W.height*T,K=performance.now())}function ut(){oe||io||e.matches||n.matches||!ye||document.hidden||(oe=!0,R=0,M=requestAnimationFrame(Mt))}function sn(){oe=!1,M&&(cancelAnimationFrame(M),M=0),R=0}function mi(){e.matches?(sn(),t.classList.remove("is-ready")):ye&&ut()}function Un(){n.matches?sn():ye&&ut()}function lc(){document.hidden?sn():ye&&ut()}const cc=new IntersectionObserver(Y=>{ye=Y[0]?.isIntersecting||!1,ye?ut():sn()},{threshold:0});cc.observe(t),window.addEventListener("pointermove",Lt,{passive:!0,capture:!0}),window.addEventListener("resize",$t),e.addEventListener("change",mi),n.addEventListener("change",Un),document.addEventListener("visibilitychange",lc);function Rp(){const Y=(s.match(/\sd="([^"]+)"/)||[])[1],W=document.createElement("canvas");W.width=256,W.height=256;const D=W.getContext("2d");if(Y&&window.Path2D){const ue=Math.min(8.533333333333333,8.421052631578947);D.setTransform(ue,0,0,ue,ue+(256-30*ue)/2,-6.4*ue),D.fillStyle="rgb(255,255,255)",D.fill(new Path2D(Y),"evenodd"),D.setTransform(1,0,0,1,0,0)}try{const ue=D.getImageData(0,0,256,256),xe=ue.data;for(let Fe=3;Feoe}}const sy=120;function oy(t,e,n){return tn?n:t}function de(t,e,n){return oy((t-e)/(n-e),0,1)}function ay(t){return t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2}function Wo(t){return 1-Math.pow(1-t,3)}function Ve(t,e){return e=e===void 0?1.7:e,1+(e+1)*Math.pow(t-1,3)+e*Math.pow(t-1,2)}function Vu(t){return 1-Math.pow(2,-9*t)*Math.cos(t*15)}function te(t,e){if(t<=e[0].t)return e[0].v;for(let n=1;n8.2&&_<9.4&&(s*=1-.07*Math.sin(de(_,8.2,9.4)*Math.PI))}else if(t<53){const _=t-42;g=te(_,[{t:0,v:1},{t:2,v:0},{t:4.2,v:0},{t:4.6,v:1},{t:6.8,v:1},{t:7.4,v:0},{t:9.4,v:0},{t:10.6,v:1}]),p=te(_,[{t:0,v:1},{t:2,v:.3},{t:4.6,v:1,e:Ve}]),d=te(_,[{t:0,v:0},{t:2,v:.3},{t:4.6,v:.16,e:Ve},{t:10.6,v:0}]),h=te(_,[{t:0,v:0},{t:2,v:-40},{t:4.6,v:0,e:Ve}]),o=te(_,[{t:0,v:0},{t:4.6,v:-.12},{t:10.6,v:0}])}else if(t<60){const _=t-53;c=te(_,[{t:0,v:1},{t:.35,v:0},{t:.45,v:0},{t:.7,v:1}]);const b=de(_,.45,2.2);a=b>0?-2.6*(1-Vu(b)):0,g=te(_,[{t:0,v:1},{t:.57,v:0},{t:.67,v:0},{t:.92,v:1}]);const k=de(_,.67,2.42);f=k>0?-2.6*(1-Vu(k)):0,s=1-.05*(Math.sin(de(_,1.9,2.5)*Math.PI)+Math.sin(de(_,2.5,3.1)*Math.PI))}else if(t<74){let b=function(F){return[te(F,[{t:0,v:0},{t:.25,v:1},{t:.5,v:1},{t:.72,v:.14},{t:.82,v:.14},{t:1,v:0}]),te(F,[{t:0,v:0},{t:.08,v:-.62},{t:.25,v:-.62},{t:.33,v:.62},{t:.7,v:.62},{t:.82,v:-.62},{t:1,v:-.62}])]};var S=b;const _=t-60,k=1-de(_,12,14),T=b(de(_,0,12)),x=b(de(_-.5,0,12));n=T[0]*k,i=(T[1]+.05*Math.sin(_*7))*k,o=(x[0]-T[0])*.6*k,a=(x[1]-T[1])*.6*k,h=(x[0]-T[0])*30*k,E=de(_,0,.4)*k}else if(t<85.4){const _=t-74,b=te(_,[{t:0,v:0},{t:4,v:1},{t:8,v:.24},{t:9.6,v:1,e:Ve},{t:11.4,v:0}]);o=b*.5,d=-b*.5,l=te(_,[{t:0,v:0},{t:4,v:6},{t:8,v:20},{t:9.6,v:38,e:Ve},{t:11.4,v:0}]),h=-l*.7,a=te(_,[{t:0,v:0},{t:8,v:0},{t:9.6,v:.4},{t:11.4,v:0}])}else if(t<96.4){const _=t-85.4,b=de(_,0,5.6),k=de(_,5.6,7.6),T=.72*Math.min(1,_/.6)*(1-k);d=Math.cos(b*Math.PI*2)*T,f=Math.sin(b*Math.PI*2)*T*.55,h=b*360*(1-k);const x=te(_,[{t:0,v:0},{t:7.6,v:0},{t:8.2,v:1,e:Wo},{t:8.6,v:.55},{t:9.4,v:0}]);o=-.16*x,d+=.16*x,l=-6*x,h+=6*x,s=1+.05*x,m=1+.9*x}else if(t<108.6){const _=t-96.4,b=de(_,9.6,12.2);n=te(_,[{t:0,v:0},{t:2.1,v:1},{t:4.8,v:.08},{t:7.5,v:1},{t:9.6,v:0}])*(1-b),i=-.35*Math.abs(Math.sin(de(_,0,9.6)*Math.PI*3))*(1-b);const k=Math.sin(_*6.2)*(1-b);u=1+.12*k,p=1-.12*k,l=k*8,h=-k*8,o=.06*k,d=-.06*k,E=de(_,0,.4)*(1-b)}else{const _=t-108.6,b=Math.sin(de(_,0,8)*Math.PI),k=1-de(_,8,11.4);s=1+.04*b*k,i=-.1*b*k,r=2*b*k,m=1+.5*Math.sin(de(_,0,6)*Math.PI),v=1+.1*Math.sin(de(_,0,6)*Math.PI)}return e.x=n,e.y=i,e.rot=r,e.scale=s,e.ax=o,e.ay=a,e.ar=l,e.asc=u,e.afade=c,e.bx=d,e.by=f,e.br=h,e.bsc=p,e.bfade=g,e.hfade=m,e.hsc=v,e.shd=E,e}function ly(t={}){const e=t.arena||document.querySelector(".pipeline-glyph.logo-loop");if(!e)return null;const n=e.querySelector(".loop-mark"),i=e.querySelector(".loop-piece-a"),r=e.querySelector(".loop-piece-b"),s=e.querySelector(".loop-halo"),o=e.querySelector(".loop-shadow");if(!n||!i||!r||!s||!o)return null;const a=t.reducedMotion||window.matchMedia("(prefers-reduced-motion: reduce)"),l=sy;let u=34,c=0,d=0;function f(){u=n.offsetWidth||34,c=Math.max(0,e.offsetWidth-u-4),d=Math.max(0,(e.offsetHeight-u)/2-2),e.style.setProperty("--mark-c",u/2+"px")}function h(M){const R=Math.min(1,Math.max(0,M.x))*c,Z=M.y*d;n.style.transform="translate3d("+R.toFixed(2)+"px,"+Z.toFixed(2)+"px,0) rotate("+M.rot.toFixed(2)+"deg) scale("+M.scale.toFixed(3)+")",i.style.transform="translate3d("+(M.ax*u).toFixed(2)+"px,"+(M.ay*u).toFixed(2)+"px,0) rotate("+M.ar.toFixed(2)+"deg) scale("+M.asc.toFixed(3)+")",i.style.opacity=M.afade.toFixed(3),r.style.transform="translate3d("+(M.bx*u).toFixed(2)+"px,"+(M.by*u).toFixed(2)+"px,0) rotate("+M.br.toFixed(2)+"deg) scale("+M.bsc.toFixed(3)+")",r.style.opacity=M.bfade.toFixed(3),s.style.transform="scale("+M.hsc.toFixed(3)+")",s.style.opacity=(.09*M.hfade).toFixed(3),o.style.transform="translateX("+R.toFixed(2)+"px) scaleX("+(.75+.4*Math.abs(M.x)).toFixed(3)+")",o.style.opacity=(M.shd*.5).toFixed(3)}let p=0,g=0,m=0,v=!1,E=!1,S=!1,_=0;function b(){return S||a.matches||document.hidden||!e.offsetParent?!1:E}function k(M){if(!v)return;if(m=requestAnimationFrame(k),!b()){x();return}const R=g?(M-g)/1e3:0;g=M,p=(p+Math.min(R,.1))%l,_+=1,h(Pi(p))}function T(){v||S||b()&&(v=!0,g=0,m=requestAnimationFrame(k))}function x(){v=!1,m&&(cancelAnimationFrame(m),m=0),g=0}function F(){b()?T():x()}function $(){a.matches?(x(),h(Pi(0))):F()}function O(){f(),v&&h(Pi(p))}function L(){g=0,F()}const N=new IntersectionObserver(M=>{E=M[0]?M[0].isIntersecting:!1,F()},{threshold:0});N.observe(e),window.addEventListener("resize",O),a.addEventListener("change",$),document.addEventListener("visibilitychange",L);function K(){S||(S=!0,x(),N.disconnect(),window.removeEventListener("resize",O),a.removeEventListener("change",$),document.removeEventListener("visibilitychange",L))}window.addEventListener("pagehide",K);function V(M){p=(M%l+l)%l,h(Pi(p))}return f(),h(Pi(0)),F(),{isRunning:()=>v,currentTime:()=>p,frameCount:()=>_,seek:V,dispose:K}}const cy=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function Xt(t){const e=String(t||"").trim().match(cy);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function uy(t,e){if(t.length===0&&e.length===0)return 0;if(t.length===0)return 1;if(e.length===0)return-1;for(let n=0;n0)}function fy(t){const e=Xt(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function Al(t){let e=String(t??"").trim();if((e.startsWith("'")||e.startsWith('"'))&&(e=e.slice(1,-1).trim()),e===""||e==="any"||e==="*")return{min:null,minInclusive:!1,max:null,maxInclusive:!1};if(e.startsWith("^")){const o=e.slice(1).trim();return Xt(o)?{min:o,minInclusive:!0,max:fy(o),maxInclusive:!1}:null}if(Xt(e))return{min:e,minInclusive:!0,max:e,maxInclusive:!0};const n={min:null,minInclusive:!1,max:null,maxInclusive:!1},i=/(>=|<=|>|<)\s*([0-9][0-9A-Za-z.+-]*)/g;let r=!1,s;for(;(s=i.exec(e))!==null;){const[,o,a]=s;if(!Xt(a))return null;r=!0,o===">="||o===">"?(n.min=a,n.minInclusive=o===">="):(n.max=a,n.maxInclusive=o==="<=")}return r?n:null}function Gu(t,e){const n=Al(t);if(!n||!Xt(e))return!1;if(n.min!==null){const i=hs(e,n.min);if(i<0||i===0&&!n.minInclusive)return!1}if(n.max!==null){const i=hs(e,n.max);if(i>0||i===0&&!n.maxInclusive)return!1}return!0}function hy(t,e){const n=Al(t);if(!n||!Xt(e))return!1;if(n.max===null)return!0;const i=hs(n.max,e);return i>0?!0:i===0&&n.maxInclusive}function Vn(t){const e=Al(t);return e?e.min:null}const py="https://pub.dev/api/packages/",gy=8e3;function my(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null}=e,r=Array.isArray(t?.versions)?t.versions:[];let s=null;for(const o of r){const a=o?.version;if(!a||o.retracted||dy(a))continue;const l=o.pubspec?.environment||{};n&&l.sdk&&!Gu(l.sdk,n)||i&&l.flutter&&!Gu(l.flutter,i)||(!s||hs(a,s)>0)&&(s=a)}return s?{version:s,constraint:`^${s}`}:null}async function vy(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null,fetchImpl:r=fetch}=e;let s;try{const a=await r(`${py}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(gy)});if(!a.ok)return{name:t,constraint:null,version:null,error:a.status===404?`"${t}" was not found on pub.dev`:`pub.dev returned ${a.status} for "${t}"`};s=await a.json()}catch(a){return{name:t,constraint:null,version:null,error:`could not reach pub.dev for "${t}" (${a.message})`}}const o=my(s,{dartSdkFloor:n,flutterSdkFloor:i});return o?{name:t,...o,error:null}:{name:t,constraint:null,version:null,error:n?`no published "${t}" release supports Dart ${n}`:`no published "${t}" release could be read`}}async function _y(t,e={}){const n=await Promise.all(t.map(i=>vy(i,e)));return new Map(n.map(({name:i,...r})=>[i,r]))}async function yy(t,e={},n={}){const{resolveVersions:i=_y}=n,r=Object.entries(e).filter(([c])=>c&&c!=="flutter"),s=wh(t),o={dartSdkFloor:Vn(s.sdk),flutterSdkFloor:Vn(s.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(r.length===0)return a;const l=Ms(t),u=[];for(const[c,d]of r){const f=l.get(c);if(!f){u.push(c);continue}const h=Vn(d);if(!h){a.kept.push({name:c,constraint:f.constraint});continue}if(!f.isScalar){a.warnings.push(`"${c}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${h}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:c,constraint:f.constraint});continue}if(hy(f.constraint,h)){a.kept.push({name:c,constraint:f.constraint});continue}a.overrides[c]=`^${h}`,a.warnings.push(`"${c}" was pinned to ${f.constraint} in your project, which cannot resolve the ${h} the generated code needs. Raising it to ^${h} — this changes a dependency the rest of your app also uses.`)}if(u.length>0){const c=await i(u,o);for(const d of u){const f=c.get(d);if(f?.constraint){a.additions[d]=f.constraint;continue}const h=e[d]||"";if(Vn(h)){a.additions[d]=`^${Vn(h)}`,a.warnings.push(`Could not confirm "${d}" version on pub.dev (${f?.error||"lookup failed"}). Using ^${Vn(h)} from the AI's recommendation — verify this is current.`);continue}a.additions[d]=">=0.0.0",a.warnings.push(`Could not determine a version for "${d}" (${f?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const wy={"&":"&","<":"<",">":">",'"':""","'":"'"};function Qt(t){return String(t??"").replace(/[&<>"']/g,e=>wy[e])}function z(t){return t?Qt(t).replace(/\n/g,"
      "):""}function Jt(t){return Qt(t).replace(/\r?\n/g," ")}function Ls(t,e={}){const n=t?.pipelineStep;if(n!=null&&e[n]!=null)return e[n];const i=t?.message||"";return i.includes("Code Generator")?2:i.includes("Code Review")?3:1}function Ah(t){if(!t)return{kind:"generic",title:"Generation failed",message:"An unknown error occurred. Please try again.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1};if(t.isModelArmor){const n=t.code==="MODEL_ARMOR_BLOCKED";return{kind:"safety",title:t.userTitle||"Request blocked for safety",message:t.userMessage||t.message,detail:t.retryExplanation||"",canRetry:!n,canEdit:!0,canUpgrade:!1}}if(t.isUsageLimit)return{kind:"quota",title:"Monthly limit reached",message:t.message||"You've used all your generations for this period.",detail:"",canRetry:!1,canEdit:!1,canUpgrade:!0};const e=t.message||"";return/timed out after/i.test(e)?{kind:"timeout",title:"Request timed out",message:"The generation service took too long to respond.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:/unreachable|failed to fetch|load failed|cors/i.test(e)?{kind:"network",title:"Connection problem",message:"We couldn't reach the generation service. Check your connection and try again.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:{kind:"generic",title:"Generation failed",message:e||"An unexpected error occurred.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1}}function by(t){const e={"Integration Audit Report":"📋","Critical Issues":"❌",Warnings:"⚠️",Recommendations:"✅","Overall Score":"📊"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📄"}function Ey(t){const e={critical:"❌",warning:"⚠️",recommendation:"✅",score:"📊",issue:"🔍",fix:"🔧"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📝"}function Sy(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 ci(t){if(!t)return"";if(typeof t!="string")return String(t);const e=/```(?:\w+)?\n?([\s\S]*?)```/,n=t.match(e);return n?n[1].trim():t.trim()}function Ku(t){return t=Qt(t),t=t.replace(/\*\*(.*?)\*\*/g,'$1'),t=t.replace(/\*(.*?)\*/g,'$1'),t=t.replace(/`(.*?)`/g,'$1'),t=t.replace(/\b(FAIL|ERROR|CRITICAL)\b/g,'$1'),t=t.replace(/\b(WARN|WARNING)\b/g,'$1'),t=t.replace(/\b(PASS|SUCCESS|OK)\b/g,'$1'),t}function Ph(t,e="dart",n=globalThis.hljs){if(!t)return"";const i=ci(t);try{return n.highlight(i,{language:e}).value}catch(r){console.warn("Syntax highlighting failed:",r);try{return n.highlight(i,{language:"json"}).value}catch{return Qt(i)}}}function Ns(t,e={}){const{highlighter:n=globalThis.hljs}=e;let i='
      ';const r=String(t??"").split(` -`);let s=!1,o="";for(const a of r){if(a.startsWith("```")){if(s){const l=Sy(o),u=Ph(o.trim(),l,n);i+=`
      +`)}let l=null,u,c,d,f,h,p,g,m,v;function E(Y,W){if(!i)return null;const D=i.createShader(Y);return i.shaderSource(D,W),i.compileShader(D),i.getShaderParameter(D,i.COMPILE_STATUS)?D:(window.console&&console.warn("fx-grid shader: "+i.getShaderInfoLog(D)),null)}if(i){const Y=E(i.VERTEX_SHADER,o),W=E(i.FRAGMENT_SHADER,a());if(Y&&W&&(l=i.createProgram(),i.attachShader(l,Y),i.attachShader(l,W),i.linkProgram(l),i.getProgramParameter(l,i.LINK_STATUS)||(window.console&&console.warn("fx-grid link: "+i.getProgramInfoLog(l)),l=null)),l){i.useProgram(l),i.bindBuffer(i.ARRAY_BUFFER,i.createBuffer()),i.bufferData(i.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),i.STATIC_DRAW);const D=i.getAttribLocation(l,"p");i.enableVertexAttribArray(D),i.vertexAttribPointer(D,2,i.FLOAT,!1,0,0),u=i.getUniformLocation(l,"res"),c=i.getUniformLocation(l,"design"),d=i.getUniformLocation(l,"mouse"),f=i.getUniformLocation(l,"energy"),h=i.getUniformLocation(l,"parallax"),p=i.getUniformLocation(l,"t"),g=i.getUniformLocation(l,"ink"),m=i.getUniformLocation(l,"mark"),v=i.getUniformLocation(l,"rot"),i.enable(i.BLEND),i.blendFunc(i.ONE,i.ONE_MINUS_SRC_ALPHA),i.clearColor(0,0,0,0)}else{i=null;const D=t.cloneNode(!1);if(t.parentNode.replaceChild(D,t),t=D,r=t.getContext("2d"),!r)return null}}function S(Y){if(!Y)return null;const W=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(Y);if(W){let D=W[1];return D.length===3&&(D=D[0]+D[0]+D[1]+D[1]+D[2]+D[2]),[parseInt(D.slice(0,2),16)/255,parseInt(D.slice(2,4),16)/255,parseInt(D.slice(4,6),16)/255]}try{const D=document.createElement("canvas");D.width=1,D.height=1;const ue=D.getContext("2d");ue.fillStyle="rgb(9, 8, 7)";const xe=String(ue.fillStyle);ue.fillStyle=Y;const Fe=String(ue.fillStyle);if(Fe===xe)return null;const dt=/^#([0-9a-f]{6})$/i.exec(Fe);if(dt){const ft=dt[1];return[parseInt(ft.slice(0,2),16)/255,parseInt(ft.slice(2,4),16)/255,parseInt(ft.slice(4,6),16)/255]}const Nt=/rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i.exec(Fe);if(Nt)return[Number(Nt[1])/255,Number(Nt[2])/255,Number(Nt[3])/255]}catch{}return null}function _(){let Y="";try{const W=getComputedStyle(document.documentElement);Y=(W.getPropertyValue("--fx-ink")||"").trim()||(W.getPropertyValue("--fg")||"").trim()}catch{}return S(Y)||[.56,.68,.88]}const b=_();let k=1920,T=1080,x=960,F=540,$=960,O=540,L=.66,N=0,K=-1e9,V=!1,M=0,R=0,Z=null,Ce=!1,oe=!1,ye=!1;const $e=64,ae=15.2;let Ie=0,Se=0;const De=.0032,wt=0,ge=.56,Je=.26,bt=.32,mn=.16,Re=.349;let Pe=wt;function $t(){const Y=t.getBoundingClientRect(),W=t.clientWidth,D=t.clientHeight;if(!Y.width||!W||!D)return;const ue=Math.min(window.devicePixelRatio||1,2),xe=Math.max(.2,Math.min(2,Y.width/W*ue)),Fe=Math.max(2,Math.round(W*xe)),dt=Math.max(2,Math.round(D*xe));(Fe!==t.width||dt!==t.height)&&(t.width=Fe,t.height=dt,i&&i.viewport(0,0,Fe,dt)),k=W,T=D,V||(x=$=k/2,F=O=T/2,V=!0)}function Bn(Y){!l||!Ce||!i||(i.uniform2f(u,t.width,t.height),i.uniform2f(c,k,T),i.uniform2f(d,x,F),i.uniform1f(f,L),i.uniform1f(h,N),i.uniform2f(v,Math.cos(Pe),Math.sin(Pe)),i.uniform1f(p,Y),i.uniform3f(g,b[0],b[1],b[2]),i.clear(i.COLOR_BUFFER_BIT),i.drawArrays(i.TRIANGLES,0,3))}function qe(Y,W,D){const ue=Math.max(0,Math.min(1,(D-Y)/(W-Y)));return ue*ue*(3-2*ue)}function Dn(Y){if(!Z||!r)return;const W=r;W.setTransform(1,0,0,1,0,0),W.clearRect(0,0,t.width,t.height);const D=t.width/k;W.setTransform(D,0,0,D,0,0),W.globalAlpha=1;const ue=Math.min(k,T),xe=Math.max(64,Math.min(118,ue/10)),Fe=xe*2.9,dt=2*Fe*Fe,Nt=Math.sin(Y*.11)*7,ft=Math.cos(Y*.09)*7-N,pr=x+Nt,gr=F+ft,oo=Fe*Math.sqrt(2*Math.log(1/.06)),yi=oo+De*oo*oo+xe,Np=Math.floor((pr-yi)/xe)-1,Op=Math.ceil((pr+yi)/xe)+1,Bp=Math.floor((gr-yi)/xe)-1,Dp=Math.ceil((gr+yi)/xe)+1;for(let ao=Bp;ao<=Dp;ao++){const jp=(ao+.5)*xe;for(let lo=Np;lo<=Op;lo++){const co=(lo+.5)*xe-pr,uo=jp-gr,fo=Math.sqrt(co*co+uo*uo)+1e-5;if(fo>yi)continue;const mr=(-1+Math.sqrt(1+4*De*fo))/(2*De),hc=Math.exp(-(mr*mr)/dt),pc=qe(.06,.8,hc)*L*.26;if(pc<.004)continue;const on=xe/(1+2*De*mr)*.26*(.32+1.1*hc),gc=mr/fo,ho=pr+co*gc,po=gr+uo*gc;ho<-on*1.6||ho>k+on*1.6||po<-on*1.6||po>T+on*1.6||(W.globalAlpha=pc,W.save(),W.translate(ho,po),W.rotate(Pe),W.drawImage(Z,-on,-on,on*2,on*2),W.restore())}}W.globalAlpha=1}function Mt(Y){if(!oe)return;const W=R?Math.min(.05,(Y-R)/1e3):.016;R=Y;const ue=Y-K>2400?.6:1;L+=(ue-L)*Math.min(1,W*3.2);const xe=Math.min(.05,W);Ie+=(($-x)*$e-Ie*ae)*xe,Se+=((O-F)*$e-Se*ae)*xe,x+=Ie*xe,F+=Se*xe,N=(window.scrollY||window.pageYOffset||0)*.55;const Fe=Y/1e3,dt=x/(k||1)-.5,Nt=F/(T||1)-.5;let ft=dt*(dt>=0?ge:Je)+Nt*(Nt>=0?bt:mn);ft>Re?ft=Re:ft<-Re&&(ft=-Re),Pe=wt+ft-N*6e-4,$t(),i?Bn(Fe):Dn(Fe),M=requestAnimationFrame(Mt)}function Lt(Y){if(!oe)return;const W=t.getBoundingClientRect();!W.width||!k||!T||($=(Y.clientX-W.left)/W.width*k,O=(Y.clientY-W.top)/W.height*T,K=performance.now())}function ut(){oe||so||e.matches||n.matches||!ye||document.hidden||(oe=!0,R=0,M=requestAnimationFrame(Mt))}function sn(){oe=!1,M&&(cancelAnimationFrame(M),M=0),R=0}function _i(){e.matches?(sn(),t.classList.remove("is-ready")):ye&&ut()}function jn(){n.matches?sn():ye&&ut()}function uc(){document.hidden?sn():ye&&ut()}const dc=new IntersectionObserver(Y=>{ye=Y[0]?.isIntersecting||!1,ye?ut():sn()},{threshold:0});dc.observe(t),window.addEventListener("pointermove",Lt,{passive:!0,capture:!0}),window.addEventListener("resize",$t),e.addEventListener("change",_i),n.addEventListener("change",jn),document.addEventListener("visibilitychange",uc);function Lp(){const Y=(s.match(/\sd="([^"]+)"/)||[])[1],W=document.createElement("canvas");W.width=256,W.height=256;const D=W.getContext("2d");if(Y&&window.Path2D){const ue=Math.min(8.533333333333333,8.421052631578947);D.setTransform(ue,0,0,ue,ue+(256-30*ue)/2,-6.4*ue),D.fillStyle="rgb(255,255,255)",D.fill(new Path2D(Y),"evenodd"),D.setTransform(1,0,0,1,0,0)}try{const ue=D.getImageData(0,0,256,256),xe=ue.data;for(let Fe=3;Feoe}}const ly=120;function cy(t,e,n){return tn?n:t}function de(t,e,n){return cy((t-e)/(n-e),0,1)}function uy(t){return t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2}function qo(t){return 1-Math.pow(1-t,3)}function Ve(t,e){return e=e===void 0?1.7:e,1+(e+1)*Math.pow(t-1,3)+e*Math.pow(t-1,2)}function Ku(t){return 1-Math.pow(2,-9*t)*Math.cos(t*15)}function te(t,e){if(t<=e[0].t)return e[0].v;for(let n=1;n8.2&&_<9.4&&(s*=1-.07*Math.sin(de(_,8.2,9.4)*Math.PI))}else if(t<53){const _=t-42;g=te(_,[{t:0,v:1},{t:2,v:0},{t:4.2,v:0},{t:4.6,v:1},{t:6.8,v:1},{t:7.4,v:0},{t:9.4,v:0},{t:10.6,v:1}]),p=te(_,[{t:0,v:1},{t:2,v:.3},{t:4.6,v:1,e:Ve}]),d=te(_,[{t:0,v:0},{t:2,v:.3},{t:4.6,v:.16,e:Ve},{t:10.6,v:0}]),h=te(_,[{t:0,v:0},{t:2,v:-40},{t:4.6,v:0,e:Ve}]),o=te(_,[{t:0,v:0},{t:4.6,v:-.12},{t:10.6,v:0}])}else if(t<60){const _=t-53;c=te(_,[{t:0,v:1},{t:.35,v:0},{t:.45,v:0},{t:.7,v:1}]);const b=de(_,.45,2.2);a=b>0?-2.6*(1-Ku(b)):0,g=te(_,[{t:0,v:1},{t:.57,v:0},{t:.67,v:0},{t:.92,v:1}]);const k=de(_,.67,2.42);f=k>0?-2.6*(1-Ku(k)):0,s=1-.05*(Math.sin(de(_,1.9,2.5)*Math.PI)+Math.sin(de(_,2.5,3.1)*Math.PI))}else if(t<74){let b=function(F){return[te(F,[{t:0,v:0},{t:.25,v:1},{t:.5,v:1},{t:.72,v:.14},{t:.82,v:.14},{t:1,v:0}]),te(F,[{t:0,v:0},{t:.08,v:-.62},{t:.25,v:-.62},{t:.33,v:.62},{t:.7,v:.62},{t:.82,v:-.62},{t:1,v:-.62}])]};var S=b;const _=t-60,k=1-de(_,12,14),T=b(de(_,0,12)),x=b(de(_-.5,0,12));n=T[0]*k,i=(T[1]+.05*Math.sin(_*7))*k,o=(x[0]-T[0])*.6*k,a=(x[1]-T[1])*.6*k,h=(x[0]-T[0])*30*k,E=de(_,0,.4)*k}else if(t<85.4){const _=t-74,b=te(_,[{t:0,v:0},{t:4,v:1},{t:8,v:.24},{t:9.6,v:1,e:Ve},{t:11.4,v:0}]);o=b*.5,d=-b*.5,l=te(_,[{t:0,v:0},{t:4,v:6},{t:8,v:20},{t:9.6,v:38,e:Ve},{t:11.4,v:0}]),h=-l*.7,a=te(_,[{t:0,v:0},{t:8,v:0},{t:9.6,v:.4},{t:11.4,v:0}])}else if(t<96.4){const _=t-85.4,b=de(_,0,5.6),k=de(_,5.6,7.6),T=.72*Math.min(1,_/.6)*(1-k);d=Math.cos(b*Math.PI*2)*T,f=Math.sin(b*Math.PI*2)*T*.55,h=b*360*(1-k);const x=te(_,[{t:0,v:0},{t:7.6,v:0},{t:8.2,v:1,e:qo},{t:8.6,v:.55},{t:9.4,v:0}]);o=-.16*x,d+=.16*x,l=-6*x,h+=6*x,s=1+.05*x,m=1+.9*x}else if(t<108.6){const _=t-96.4,b=de(_,9.6,12.2);n=te(_,[{t:0,v:0},{t:2.1,v:1},{t:4.8,v:.08},{t:7.5,v:1},{t:9.6,v:0}])*(1-b),i=-.35*Math.abs(Math.sin(de(_,0,9.6)*Math.PI*3))*(1-b);const k=Math.sin(_*6.2)*(1-b);u=1+.12*k,p=1-.12*k,l=k*8,h=-k*8,o=.06*k,d=-.06*k,E=de(_,0,.4)*(1-b)}else{const _=t-108.6,b=Math.sin(de(_,0,8)*Math.PI),k=1-de(_,8,11.4);s=1+.04*b*k,i=-.1*b*k,r=2*b*k,m=1+.5*Math.sin(de(_,0,6)*Math.PI),v=1+.1*Math.sin(de(_,0,6)*Math.PI)}return e.x=n,e.y=i,e.rot=r,e.scale=s,e.ax=o,e.ay=a,e.ar=l,e.asc=u,e.afade=c,e.bx=d,e.by=f,e.br=h,e.bsc=p,e.bfade=g,e.hfade=m,e.hsc=v,e.shd=E,e}function dy(t={}){const e=t.arena||document.querySelector(".pipeline-glyph.logo-loop");if(!e)return null;const n=e.querySelector(".loop-mark"),i=e.querySelector(".loop-piece-a"),r=e.querySelector(".loop-piece-b"),s=e.querySelector(".loop-halo"),o=e.querySelector(".loop-shadow");if(!n||!i||!r||!s||!o)return null;const a=t.reducedMotion||window.matchMedia("(prefers-reduced-motion: reduce)"),l=ly;let u=34,c=0,d=0;function f(){u=n.offsetWidth||34,c=Math.max(0,e.offsetWidth-u-4),d=Math.max(0,(e.offsetHeight-u)/2-2),e.style.setProperty("--mark-c",u/2+"px")}function h(M){const R=Math.min(1,Math.max(0,M.x))*c,Z=M.y*d;n.style.transform="translate3d("+R.toFixed(2)+"px,"+Z.toFixed(2)+"px,0) rotate("+M.rot.toFixed(2)+"deg) scale("+M.scale.toFixed(3)+")",i.style.transform="translate3d("+(M.ax*u).toFixed(2)+"px,"+(M.ay*u).toFixed(2)+"px,0) rotate("+M.ar.toFixed(2)+"deg) scale("+M.asc.toFixed(3)+")",i.style.opacity=M.afade.toFixed(3),r.style.transform="translate3d("+(M.bx*u).toFixed(2)+"px,"+(M.by*u).toFixed(2)+"px,0) rotate("+M.br.toFixed(2)+"deg) scale("+M.bsc.toFixed(3)+")",r.style.opacity=M.bfade.toFixed(3),s.style.transform="scale("+M.hsc.toFixed(3)+")",s.style.opacity=(.09*M.hfade).toFixed(3),o.style.transform="translateX("+R.toFixed(2)+"px) scaleX("+(.75+.4*Math.abs(M.x)).toFixed(3)+")",o.style.opacity=(M.shd*.5).toFixed(3)}let p=0,g=0,m=0,v=!1,E=!1,S=!1,_=0;function b(){return S||a.matches||document.hidden||!e.offsetParent?!1:E}function k(M){if(!v)return;if(m=requestAnimationFrame(k),!b()){x();return}const R=g?(M-g)/1e3:0;g=M,p=(p+Math.min(R,.1))%l,_+=1,h(Ri(p))}function T(){v||S||b()&&(v=!0,g=0,m=requestAnimationFrame(k))}function x(){v=!1,m&&(cancelAnimationFrame(m),m=0),g=0}function F(){b()?T():x()}function $(){a.matches?(x(),h(Ri(0))):F()}function O(){f(),v&&h(Ri(p))}function L(){g=0,F()}const N=new IntersectionObserver(M=>{E=M[0]?M[0].isIntersecting:!1,F()},{threshold:0});N.observe(e),window.addEventListener("resize",O),a.addEventListener("change",$),document.addEventListener("visibilitychange",L);function K(){S||(S=!0,x(),N.disconnect(),window.removeEventListener("resize",O),a.removeEventListener("change",$),document.removeEventListener("visibilitychange",L))}window.addEventListener("pagehide",K);function V(M){p=(M%l+l)%l,h(Ri(p))}return f(),h(Ri(0)),F(),{isRunning:()=>v,currentTime:()=>p,frameCount:()=>_,seek:V,dispose:K}}const fy=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function Xt(t){const e=String(t||"").trim().match(fy);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function hy(t,e){if(t.length===0&&e.length===0)return 0;if(t.length===0)return 1;if(e.length===0)return-1;for(let n=0;n0)}function gy(t){const e=Xt(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function Fl(t){let e=String(t??"").trim();if((e.startsWith("'")||e.startsWith('"'))&&(e=e.slice(1,-1).trim()),e===""||e==="any"||e==="*")return{min:null,minInclusive:!1,max:null,maxInclusive:!1};if(e.startsWith("^")){const o=e.slice(1).trim();return Xt(o)?{min:o,minInclusive:!0,max:gy(o),maxInclusive:!1}:null}if(Xt(e))return{min:e,minInclusive:!0,max:e,maxInclusive:!0};const n={min:null,minInclusive:!1,max:null,maxInclusive:!1},i=/(>=|<=|>|<)\s*([0-9][0-9A-Za-z.+-]*)/g;let r=!1,s;for(;(s=i.exec(e))!==null;){const[,o,a]=s;if(!Xt(a))return null;r=!0,o===">="||o===">"?(n.min=a,n.minInclusive=o===">="):(n.max=a,n.maxInclusive=o==="<=")}return r?n:null}function Yu(t,e){const n=Fl(t);if(!n||!Xt(e))return!1;if(n.min!==null){const i=ms(e,n.min);if(i<0||i===0&&!n.minInclusive)return!1}if(n.max!==null){const i=ms(e,n.max);if(i>0||i===0&&!n.maxInclusive)return!1}return!0}function my(t,e){const n=Fl(t);if(!n||!Xt(e))return!1;if(n.max===null)return!0;const i=ms(n.max,e);return i>0?!0:i===0&&n.maxInclusive}function qn(t){const e=Fl(t);return e?e.min:null}const vy="https://pub.dev/api/packages/",_y=8e3;function yy(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null}=e,r=Array.isArray(t?.versions)?t.versions:[];let s=null;for(const o of r){const a=o?.version;if(!a||o.retracted||py(a))continue;const l=o.pubspec?.environment||{};n&&l.sdk&&!Yu(l.sdk,n)||i&&l.flutter&&!Yu(l.flutter,i)||(!s||ms(a,s)>0)&&(s=a)}return s?{version:s,constraint:`^${s}`}:null}async function wy(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null,fetchImpl:r=fetch}=e;let s;try{const a=await r(`${vy}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(_y)});if(!a.ok)return{name:t,constraint:null,version:null,error:a.status===404?`"${t}" was not found on pub.dev`:`pub.dev returned ${a.status} for "${t}"`};s=await a.json()}catch(a){return{name:t,constraint:null,version:null,error:`could not reach pub.dev for "${t}" (${a.message})`}}const o=yy(s,{dartSdkFloor:n,flutterSdkFloor:i});return o?{name:t,...o,error:null}:{name:t,constraint:null,version:null,error:n?`no published "${t}" release supports Dart ${n}`:`no published "${t}" release could be read`}}async function by(t,e={}){const n=await Promise.all(t.map(i=>wy(i,e)));return new Map(n.map(({name:i,...r})=>[i,r]))}async function Ey(t,e={},n={}){const{resolveVersions:i=by}=n,r=Object.entries(e).filter(([c])=>c&&c!=="flutter"),s=Sh(t),o={dartSdkFloor:qn(s.sdk),flutterSdkFloor:qn(s.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(r.length===0)return a;const l=Os(t),u=[];for(const[c,d]of r){const f=l.get(c);if(!f){u.push(c);continue}const h=qn(d);if(!h){a.kept.push({name:c,constraint:f.constraint});continue}if(!f.isScalar){a.warnings.push(`"${c}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${h}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:c,constraint:f.constraint});continue}if(my(f.constraint,h)){a.kept.push({name:c,constraint:f.constraint});continue}a.overrides[c]=`^${h}`,a.warnings.push(`"${c}" was pinned to ${f.constraint} in your project, which cannot resolve the ${h} the generated code needs. Raising it to ^${h} — this changes a dependency the rest of your app also uses.`)}if(u.length>0){const c=await i(u,o);for(const d of u){const f=c.get(d);if(f?.constraint){a.additions[d]=f.constraint;continue}const h=e[d]||"";if(qn(h)){a.additions[d]=`^${qn(h)}`,a.warnings.push(`Could not confirm "${d}" version on pub.dev (${f?.error||"lookup failed"}). Using ^${qn(h)} from the AI's recommendation — verify this is current.`);continue}a.additions[d]=">=0.0.0",a.warnings.push(`Could not determine a version for "${d}" (${f?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const Sy={"&":"&","<":"<",">":">",'"':""","'":"'"};function Qt(t){return String(t??"").replace(/[&<>"']/g,e=>Sy[e])}function z(t){return t?Qt(t).replace(/\n/g,"
      "):""}function Jt(t){return Qt(t).replace(/\r?\n/g," ")}function Bs(t,e={}){const n=t?.pipelineStep;if(n!=null&&e[n]!=null)return e[n];const i=t?.message||"";return i.includes("Code Generator")?2:i.includes("Code Review")?3:1}function Th(t){if(!t)return{kind:"generic",title:"Generation failed",message:"An unknown error occurred. Please try again.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1};if(t.isModelArmor){const n=t.code==="MODEL_ARMOR_BLOCKED";return{kind:"safety",title:t.userTitle||"Request blocked for safety",message:t.userMessage||t.message,detail:t.retryExplanation||"",canRetry:!n,canEdit:!0,canUpgrade:!1}}if(t.isUsageLimit)return{kind:"quota",title:"Monthly limit reached",message:t.message||"You've used all your generations for this period.",detail:"",canRetry:!1,canEdit:!1,canUpgrade:!0};const e=t.message||"";return/timed out after/i.test(e)?{kind:"timeout",title:"Request timed out",message:"The generation service took too long to respond.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:/unreachable|failed to fetch|load failed|cors/i.test(e)?{kind:"network",title:"Connection problem",message:"We couldn't reach the generation service. Check your connection and try again.",detail:e,canRetry:!0,canEdit:!0,canUpgrade:!1}:{kind:"generic",title:"Generation failed",message:e||"An unexpected error occurred.",detail:"",canRetry:!0,canEdit:!0,canUpgrade:!1}}function xy(t){const e={"Integration Audit Report":"📋","Critical Issues":"❌",Warnings:"⚠️",Recommendations:"✅","Overall Score":"📊"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📄"}function Iy(t){const e={critical:"❌",warning:"⚠️",recommendation:"✅",score:"📊",issue:"🔍",fix:"🔧"};for(const[n,i]of Object.entries(e))if(t.toLowerCase().includes(n.toLowerCase()))return i;return"📝"}function ky(t){return t.includes("class ")&&t.includes("extends ")||t.includes("StatelessWidget")||t.includes("StatefulWidget")||t.includes("import 'package:flutter/")?"dart":t.includes("def ")||t.includes("import ")||t.includes("print(")?"python":t.includes("function ")||t.includes("const ")||t.includes("console.")?"javascript":"dart"}function ui(t){if(!t)return"";if(typeof t!="string")return String(t);const e=/```(?:\w+)?\n?([\s\S]*?)```/,n=t.match(e);return n?n[1].trim():t.trim()}function Ju(t){return t=Qt(t),t=t.replace(/\*\*(.*?)\*\*/g,'$1'),t=t.replace(/\*(.*?)\*/g,'$1'),t=t.replace(/`(.*?)`/g,'$1'),t=t.replace(/\b(FAIL|ERROR|CRITICAL)\b/g,'$1'),t=t.replace(/\b(WARN|WARNING)\b/g,'$1'),t=t.replace(/\b(PASS|SUCCESS|OK)\b/g,'$1'),t}function $h(t,e="dart",n=globalThis.hljs){if(!t)return"";const i=ui(t);try{return n.highlight(i,{language:e}).value}catch(r){console.warn("Syntax highlighting failed:",r);try{return n.highlight(i,{language:"json"}).value}catch{return Qt(i)}}}function Ds(t,e={}){const{highlighter:n=globalThis.hljs}=e;let i='
      ';const r=String(t??"").split(` +`);let s=!1,o="";for(const a of r){if(a.startsWith("```")){if(s){const l=ky(o),u=$h(o.trim(),l,n);i+=`
      ${u}
      `,o="",s=!1}else s=!0;continue}if(s){o+=a+` `;continue}if(a.startsWith("# ")){const l=a.substring(2).trim();i+=`

      - ${by(l)} + ${xy(l)} ${Qt(l)}

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

      - ${Ey(l)} + ${Iy(l)} ${Qt(l)}

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

      ${Ku(a)}

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

      ${Ju(a)}

      `)}return i+="
      ",`
      @@ -78,14 +78,14 @@ in vec2 p; void main(){ gl_Position = vec4(p, 0.0, 1.0); }`;function a(){return[
      ${i}
      - `}const xy=[[/gradient stroke\s*$/i," and an animated percentage label"],[/gauge\s*$/i," with a gradient stroke and animated fill"],[/rating\s*(bar|widget)?\s*$/i," with half-star support and haptic feedback"],[/list\s*$/i," with swipe-to-delete and an undo snackbar"],[/pad\s*$/i," that exports a transparent PNG"],[/carousel\s*$/i," with parallax cards and page indicators"],[/(button|cta)\s*$/i," with a loading spinner and success state"],[/(chart|graph)\s*$/i," that animates from a Firestore stream"],[/action\s*(that|to)?\s*$/i," uploads an image to Firebase Storage and returns the URL"],[/timer\s*$/i," with pause, resume and a completion callback"],[/map\s*$/i," with clustered markers and a custom info window"],[/^a\s+\w*$/i," widget that"],[/(picker|selector)\s*$/i," with search and multi-select"]],Iy=220,ky=6;function Yu(t,e){return!!(t&&t.trim())&&!e}function Cy(t,e=""){if(typeof t!="string"||!t||t===e||t.trim().lengthi.test(t));return n?n[1]:null}function Ay(){let t="",e="";return{get active(){return t},resolve(n){return t=Cy(n,e)??"",t},dismiss(){t=""},accept(n){if(!t)return null;const i=n+t;return e=i,t="",i}}}function Py({onSubmit:t}){const e=document.getElementById("composer"),n=document.getElementById("pipeline-input"),i=document.getElementById("hero-send");if(!e||!n||!i||typeof t!="function")return;const r=e.querySelector(".ghost .typed"),s=e.querySelector(".ghost .suggest"),o=document.getElementById("tab-hint"),a=document.getElementById("suggest-status"),l=Array.from(document.querySelectorAll("#example-chips .chip")),u=document.getElementById("btn-add-images"),c=document.getElementById("prompt-image-input"),d=window.matchMedia("(prefers-reduced-motion: reduce)"),f=Ay();let h=!1,p=!1,g=!1,m=!1,v=null,E=null;function S(){i.disabled=!Yu(n.value,p||g||m)}function _(){r&&(r.textContent=n.value)}function b(){s&&(s.textContent=""),_(),e.classList.remove("has-suggest"),o&&(o.hidden=!0,o.tabIndex=-1),a&&(a.textContent="")}function k(R){s&&(s.textContent=R),_(),e.classList.add("has-suggest"),o&&(o.hidden=!1,o.tabIndex=0,o.setAttribute("aria-label","Accept suggestion: "+R.trim())),a&&(a.textContent="Suggestion: "+R+". Press Tab to accept.")}function T(){f.dismiss(),b()}function x(){if(h||p)return;const R=f.resolve(n.value);R&&k(R)}function F(){clearTimeout(v),!h&&(v=setTimeout(x,Iy))}function $(){const R=f.accept(n.value);return R===null?!1:(n.value=R,b(),S(),!0)}function O(R){p=R,e.classList.toggle("is-busy",R),i.classList.toggle("is-busy",R),i.setAttribute("aria-label",R?"Generating":"Generate"),n.readOnly=R,l.forEach(Z=>{Z.disabled=R}),u&&(u.disabled=R),c&&(c.disabled=R),S()}async function L(){if(Yu(n.value,p||g||m)){T(),O(!0);try{await t()}finally{O(!1)}}}function N(){g=!1,E&&(clearInterval(E),E=null),e.classList.remove("is-demo-typing"),S()}function K(){l.forEach(R=>{R.classList.remove("is-active"),R.setAttribute("aria-pressed","false")})}function V(){try{n.focus({preventScroll:!0}),n.setSelectionRange(n.value.length,n.value.length)}catch{}}function M(R){const Z=R.dataset.prompt||"";if(N(),clearTimeout(v),v=null,T(),l.forEach(oe=>{const ye=oe===R;oe.classList.toggle("is-active",ye),oe.setAttribute("aria-pressed",String(ye))}),d.matches||!Z){n.value=Z,_(),S(),V();return}n.value="",_(),g=!0,S(),e.classList.add("is-demo-typing");let Ce=0;E=setInterval(()=>{Ce+=1,n.value=Z.slice(0,Ce),_(),Ce>=Z.length?(N(),V()):S()},22)}return l.forEach(R=>{R.setAttribute("aria-pressed","false"),R.addEventListener("click",()=>M(R))}),n.addEventListener("keydown",R=>{if(g&&R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!h){R.preventDefault();return}N(),R.key==="Tab"&&!R.shiftKey&&f.active?(R.preventDefault(),$()):R.key==="Escape"?(clearTimeout(v),v=null,T()):R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!h&&(R.preventDefault(),L())}),n.addEventListener("input",()=>{N(),K(),T(),S(),F()}),n.addEventListener("compositionstart",()=>{h=!0}),n.addEventListener("compositionend",()=>{h=!1,T(),S(),F()}),n.addEventListener("scroll",()=>{r&&r.parentNode&&(r.parentNode.scrollTop=n.scrollTop)}),o&&o.addEventListener("click",()=>{$(),n.focus({preventScroll:!0})}),i.addEventListener("click",L),n.addEventListener("pointerdown",()=>{N(),K()}),_(),S(),{setAttachmentsPending(R){m=!!R,S()}}}const Fy="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses";const _t="https://4tgke4.buildship.run",Fh={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},ps="ccc_auth_session",Ba="ccc_signin_return",Ry=1800*1e3,Ju=new WeakSet;let q={email:null,sessionToken:null,isVerified:!1};function Ln(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let ce=Ln({isResolved:!0}),Da=Promise.resolve();const Ty=`${_t}/service/runpipeline`,$y="bs_user_id",My="bs_identity_token",Ly=`${_t}/authUserCheck`;let ht={userId:null,token:null,status:null,resolved:!1};const gs=fv,ms="ccc_subscription",Zu=3,Ny=new Set(["active","trialing","paid"]),vs="google/gemini-3.7-flash",Or=["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"],Oy={"google/gemini-3.7-flash":"Gemini 3.7 Flash","anthropic/claude-opus-5":"Claude Opus 5","openai/gpt-5.6-sol":"GPT-5.6 Sol","z-ai/glm-5.2":"GLM 5.2","moonshotai/kimi-k3":"Kimi K3","openrouter/auto-beta":"OpenRouter: Auto Router","openrouter/free":"OpenRouter: Free Models","openrouter/deepseek/deepseek-v4-pro":"DeepSeek v4 Pro"};function Gt(t){return Oy[t]||t}const By=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 Rh(t){return By.has(t)}const ja=4,zo=8*1024*1024,Dy="https://4tgke4.buildship.run/service/runpipeline-image";let Oe=[];const pn=[],jy=3e4;let Th=null;function Uy(t){return new Promise(e=>{const n=new FileReader;n.onload=()=>e(n.result),n.onerror=()=>e(null),n.readAsDataURL(t)})}async function Hy(t,e){const n=new FormData;return n.append("file",t),(await fetch(Dy,{method:"POST",body:n,signal:e})).json()}function Wy(t){if(Array.isArray(t)){const e=t[0];if(e&&typeof e=="object")for(const n of Object.keys(e)){if(n==="item"||n==="index")continue;const i=e[n];if(i&&typeof i=="object"){if(typeof i.file=="string")return i.file;if(typeof i.url=="string")return i.url}if(typeof i=="string")return i}return""}return typeof t=="string"?t:t&&typeof t=="object"&&(t.url||t.fileUrl||t.file_url||t.downloadUrl||t.imageUrl||t.image_url||t.file)||""}async function zy(t,e,n){const i=await Uy(t);i&&Oe.includes(e)&&(e.dataUrl=i,cn());let r="";if(i)try{r=Wy(await Hy(t,n))}catch{r=""}return Oe.includes(e)?!i||!r?(Oe.splice(Oe.indexOf(e),1),cn(),"failed"):(e.url=r,cn(),"added"):"dropped"}function $h(t){const e=pn.indexOf(t);e>=0&&pn.splice(e,1),Lh()}function Mh(t){t.controller.abort(),$h(t);const e=Oe.indexOf(t.slot);e>=0&&(Oe.splice(e,1),cn())}function Lh(){Th?.setAttachmentsPending(pn.length>0)}async function qy(t){const e=Array.from(t.target.files||[]);if(!e.length)return;if(t.target.value="",y.isRunning){Ee("Wait for the current generation to finish before attaching images.","info");return}const n=e.filter(u=>u.size>zo);n.length&&Ee(`Skipped ${n.length} image(s) over the ${(zo/1024/1024).toFixed(0)} MB limit.`,"warning");const i=e.filter(u=>u.size<=zo);if(!i.length)return;const r=ja-Oe.length,s=i.slice(0,r);if(i.length>r&&Ee(`You can attach up to ${ja} images.`,"info"),!s.length)return;const o=s.map(u=>{const c={dataUrl:null,name:u.name,url:null};Oe.push(c);const d={slot:c,controller:new AbortController},f=setTimeout(()=>d.controller.abort(),jy);return d.job=zy(u,c,d.controller.signal),pn.push(d),d.job.finally(()=>{clearTimeout(f),$h(d)}),d.job});cn(),Lh();const l=(await Promise.all(o)).filter(u=>u==="failed").length;l&&Ee(`${l} image(s) could not be uploaded and were not attached.`,"error")}function Vy(t){const e=Oe[t],n=pn.find(i=>i.slot===e);if(n){Mh(n);return}Oe.splice(t,1),cn()}function cn(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",Oe.forEach((n,i)=>{const r=document.createElement("div");r.className="prompt-img-thumb"+(n.url?"":" is-pending"),r.innerHTML=(n.dataUrl?`Prompt image`:"")+``,t.appendChild(r)}),e&&(e.textContent=Oe.length>=ja?"Image limit reached":"Add images"))}function Pl(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),n=Rh(e?.value);t.classList.toggle("hidden",!n),!n&&Oe.length&&(pn.slice().forEach(Mh),Oe=[],cn())}const Fn="ccc_usage",Nh="google/gemini-3.7-flash",Oh="google/gemini-3.7-flash",Cr="google/gemini-3.7-flash",Oi={professional:11,power:49},Ua={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 Gy(){const t=new AbortController,e=setTimeout(()=>t.abort(),5e3);try{const n=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:t.signal});if(!n.ok)return;const i=await n.json();if(i.result!=="success"||!i.rates)return;const r=i.rates,s={AUD:1},o=new Set([...Object.keys(Br),...Object.values(Ha),...Object.values(Ua)]);for(const a of o)a!=="AUD"&&(typeof r[a]=="number"&&r[a]>0?s[a]=r[a]:Br[a]&&(s[a]=Br[a]));Dr=s}catch{}finally{clearTimeout(e)}}const Ha={"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 Fl(){try{const s=Intl.DateTimeFormat().resolvedOptions().timeZone;if(s&&Ha[s])return Ha[s]}catch{}const e=(navigator.language||"en-US").replace("-","_"),n=Ua[e];if(n)return n;const i=e.split("_")[0],r=Ua[i];return r||"USD"}function Bi(t,e){const n=Dr[e]??Dr.USD,i=t*n,r=Math.round(i*100)/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:r>=100||r%1===0?0:2}).format(r)}catch{return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(t*Dr.USD)}}const gt="ccc_api_key_",Pt="ccc_session_api_key_",Rt="ccc_encryption_key",nr="ccc_encryption_key_scope",Ky="ccc_keystore",_s="keys",ir="ccc_encryption_key_version";let Wa=null,ys=null,rr=!1,ws=!1,Xu=!1;class bs extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function Qu(){if(Xu)return;Xu=!0;const t="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(t),document.body&&Ee(t,"warning")}function Bh(){return localStorage.getItem(ir)||""}function za(){return crypto.randomUUID?.()||jh(crypto.getRandomValues(new Uint8Array(16)))}function Yy(){const t=Bh();if(t)return t;const e=za();return localStorage.setItem(ir,e),e}function ui(){Wa=null,ys=null,rr=!1,ws=!1}window.addEventListener("storage",t=>{t.key===ir&&ui()});function Jy(){return new Promise((t,e)=>{const n=indexedDB.open(Ky,1);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(_s)||i.createObjectStore(_s)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function Rl(t,e){const n=await Jy();return new Promise((i,r)=>{const s=n.transaction(_s,t);let o;try{o=e(s.objectStore(_s))}catch(l){n.close(),r(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>r(o.error),s.oncomplete=()=>{n.close(),i(a)},s.onerror=()=>{n.close(),r(s.error||new Error("Encryption key transaction failed."))},s.onabort=()=>{n.close(),r(s.error||new Error("Encryption key transaction aborted."))}})}function Zy(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function Xy(){const t=await Rl("readonly",e=>e.get(Rt));return Zy(t)?t:null}async function Dh(t){await Rl("readwrite",e=>e.put(t,Rt))}async function Qy(){ui();try{await Rl("readwrite",t=>t.delete(Rt))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function e0(){const t=sessionStorage.getItem(Rt);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Dh(e),sessionStorage.removeItem(Rt),sessionStorage.removeItem(nr),localStorage.removeItem(gt+"salt"),e}async function ed(t){const e=sessionStorage.getItem(Rt);if(e)return ws=sessionStorage.getItem(nr)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new bs;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),i=await crypto.subtle.exportKey("jwk",n);return sessionStorage.setItem(Rt,JSON.stringify(i)),sessionStorage.setItem(nr,"session"),ws=!1,crypto.subtle.importKey("jwk",i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function t0(t){if(sessionStorage.getItem(nr)==="session"&&sessionStorage.getItem(Rt))return Qu(),rr=!0,ed(t);try{const e=await Xy();if(e)return e;const n=await e0();if(n)return n;const i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Dh(i),i}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),Qu(),rr=!0,ed(t)}}async function Tl(t={}){const{allowSessionFallbackCreation:e=!0}=t,n=Yy();ys!==n&&ui();const i=Wa||t0(e);Wa=i,ys=n;try{return await i}catch(r){throw ui(),r}}async function n0(t){const e=await Tl(),n=ys,i=new TextEncoder,r=crypto.getRandomValues(new Uint8Array(12)),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},e,i.encode(t)),o=new Uint8Array(r.length+s.byteLength);return o.set(r),o.set(new Uint8Array(s),r.length),{ciphertext:jh(o),keyVersion:n,sessionFallback:rr}}async function i0(t,e={}){const{isSessionCredential:n=!1}=e;try{const i=await Tl({allowSessionFallbackCreation:!1});if(rr&&!n&&!ws)throw new bs;const r=r0(t),s=r.slice(0,12),o=r.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},i,o);return new TextDecoder().decode(a)}catch(i){if(i instanceof bs)throw i;return console.error("Decryption failed:",i),null}}function jh(t){const e=new Uint8Array(t);let n="";for(let i=0;i0}let Nn="",di="",qi=null,nd=0,nt="not-configured";async function $l(){sessionStorage.getItem(Rt)&&await Tl(),Nn=await Te("flutterflow"),di=await Te("flutterflow_project_id"),f0(),rn(),Nn?Ol():(nt="not-configured",vt())}let sr=!1;function Uh(){const t=document.getElementById("api-keys-modal");We(t),Nl(),Nn&&Bl(Nn)}function Ml(){sr=!1,Uh()}function o0(){sr=!0;const t=document.getElementById("walkthrough-modal");t&&ze(t),Uh()}let id=!1;function rd(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-settings-model");if(!t||!e)return;e.value=t.value;const n=Array.from(t.options);Array.from(e.options).forEach((r,s)=>{const o=n[s];o&&(r.textContent=o.textContent)});const i=document.getElementById("composer-settings-free-notice");i&&(document.getElementById("model-selector-free-notice")?(i.hidden=!1,i.innerHTML='Free plan — Gemini only. '):i.hidden=!0)}function sd(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-image-capability"),n=document.getElementById("composer-image-capability-note");if(!t)return;const i=Gt(t.value),r=Rh(t.value);e&&(e.textContent=r?"Supported":"Not supported"),n&&(n.textContent=r?`${i} accepts reference images you attach to the prompt.`:`Images can't be attached with ${i}. Attached images are removed when you switch to it.`),Pl()}function a0(){if(sr=!1,rd(),sd(),!id){const e=document.getElementById("composer-settings-model");e&&e.addEventListener("change",()=>{const n=document.getElementById("code-generator-model");n.value=e.value,n.dispatchEvent(new Event("change")),rd(),sd()}),id=!0}const t=document.querySelector('.composer [aria-label="Generation settings"]');We("composer-settings-modal",{trigger:t})}function l0(t){t&&t.target!==t.currentTarget||ze("composer-settings-modal")}function Hh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&ze(e);const n=sr;if(sr=!1,n){const i=document.getElementById("walkthrough-modal");i&&(nt==="connected"&&Ll(),We(i))}}let en=1;function Wh(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function Os(){const t=Wh();t.length&&t.forEach((e,n)=>{const i=n+1;e.classList.remove("wt-current","wt-done","wt-pending");const r=e.querySelector(".wt-step-num");i===en?(e.classList.add("wt-current"),r&&(r.textContent=i)):i0&&en<=t&&(en++,Os())}function c0(){const t=document.getElementById("walkthrough-modal");t&&(en=1,Os(),We(t))}function u0(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&ze(e);const n=document.getElementById("walkthrough-dont-show");n&&n.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function zh(){if(q.isVerified&&Tt()&&ce.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(en=1,Os(),We(e))}}async function Nl(){const t=document.getElementById("flutterflow-api-key-input");Nn?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",d0()}function d0(){od("flutterflow","flutterflow-key-status"),od("flutterflow_project_id","flutterflow-project-status")}function od(t,e){const n=document.getElementById(e);if(!n)return;const i=n.querySelector(".key-status-dot"),r=n.querySelector("span");Ct(t)?(i.className="key-status-dot configured",r.className="text-green-600",r.textContent="User key configured"):(i.className="key-status-dot missing",r.className="text-gray-500",r.textContent="Not configured")}function rn(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff");e&&e.classList.toggle("hidden",!t)}function f0(){const t=document.getElementById("api-keys-status");if(!t)return;const e=t.querySelectorAll(".key-status-dot"),n=["flutterflow"];e.forEach((i,r)=>{const s=n[r];s==="flutterflow"?Ct("flutterflow")&&Ct("flutterflow_project_id")?(i.className="key-status-dot configured",i.title="FlutterFlow (Fully configured)"):Ct("flutterflow")||Ct("flutterflow_project_id")?(i.className="key-status-dot env",i.title="FlutterFlow (Partially configured)"):(i.className="key-status-dot missing",i.title="FlutterFlow (Not configured)"):Ct(s)?(i.className="key-status-dot configured",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (User key)"):(i.className="key-status-dot missing",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (Not configured)")}),rn()}async function h0(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select"),n=t.value.trim();n&&await td("flutterflow",n);const i=e?.value.trim()||"";if(i){if(!Bs(i)){Ee("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await td("flutterflow_project_id",i)}await $l(),n&&await Ol(),Nl();const r=document.querySelector("#api-keys-modal .bg-blue-500"),s=r.textContent;r.textContent="Saved!",r.classList.remove("bg-blue-500","hover:bg-blue-600"),r.classList.add("bg-green-500"),setTimeout(()=>{r.textContent=s,r.classList.remove("bg-green-500"),r.classList.add("bg-blue-500","hover:bg-blue-600"),Hh()},1e3)}async function p0(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(ir,za()),ui(),localStorage.removeItem(gt+"flutterflow"),localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow"),sessionStorage.removeItem(Pt+"flutterflow_project_id"),sessionStorage.removeItem(Rt),sessionStorage.removeItem(nr),localStorage.removeItem(gt+"salt"),await Qy(),localStorage.setItem(ir,za()),localStorage.removeItem(gt+"flutterflow"),localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow"),sessionStorage.removeItem(Pt+"flutterflow_project_id"),await $l();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),Nl()}function Bs(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function vt(){const t=document.getElementById("acct-ff-dot"),e=document.getElementById("acct-ff-status"),n=document.getElementById("acct-ff-endpoint"),i=document.getElementById("acct-ff-project");if(n){const o=yt();n.textContent=o.includes("staging")?"Staging":"Production"}if(i&&(i.textContent=di||"—"),!e)return;let r,s;if(!Ct("flutterflow"))r="Not connected — add your FlutterFlow API key",s="";else switch(nt){case"connected":r="Connected to FlutterFlow",s="ok";break;case"no-projects":r="Key accepted — no projects found",s="warn";break;case"unauthorized":r="API key rejected (401/403) — re-enter your key",s="bad";break;case"network-error":r="Could not reach FlutterFlow — check your network",s="bad";break;default:r="Checking connection…",s="warn";break}e.textContent=r,t&&(t.className=`acct-dot${s?" "+s:""}`)}async function Ol(){const t=await Te("flutterflow");if(!t||!Ct("flutterflow"))return nt="not-configured",vt(),null;nt="validating",vt();try{const n=await new pi(t,"","main",yt()).listProjects();return nt=n&&n.length>0?"connected":"no-projects",vt(),n}catch(e){const n=String(e&&e.message||"");return nt=/(401|403)|denied|unauthorized|scoped|list permission/i.test(n)?"unauthorized":"network-error",vt(),null}}function g0(){di="",localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow_project_id")}function m0(){g0();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML='',t.value=""),Ct("flutterflow")?(nt="validating",Bl(Nn)):nt="not-configured",vt()}function v0(t,e){const n=document.getElementById(t);n&&(n.value?e?n.style.borderColor="#22c55e":n.style.borderColor="#ef4444":n.style.borderColor="")}function _0(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const n=e.target.value.trim().length>0;v0("flutterflow-api-key-input",n)}),t.addEventListener("blur",y0(async e=>{const n=e.target.value.trim();n&&await Bl(n)},500)))}function y0(t,e){let n;return function(...r){const s=()=>{clearTimeout(n),t(...r)};clearTimeout(n),n=setTimeout(s,e)}}async function Bl(t){const e=document.getElementById("flutterflow-projects-select"),n=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',n&&n.classList.add("hidden"),(Ct("flutterflow")||t)&&(nt="validating"),vt();try{const r=await new pi(t,"","main",yt()).listProjects();if(!r||r.length===0){nt="no-projects",vt(),e.innerHTML='';return}nt="connected",vt(),e.innerHTML='',r.forEach(s=>{const o=document.createElement("option");o.value=s.id||s.projectId||"",o.textContent=s.name||s.projectName||`Project ${s.id}`,e.appendChild(o)}),di&&(e.value=di)}catch(i){console.error("Failed to fetch projects:",i);const r=String(i&&i.message||"");nt=/(401|403)|denied|unauthorized|scoped|list permission/i.test(r)?"unauthorized":"network-error",vt(),e.innerHTML='',n&&(n.textContent=`Failed to load projects: ${i.message}`,n.classList.remove("hidden"))}}function w0(t){const e=document.getElementById(t),i=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",i.innerHTML=` + `}const Cy=[[/gradient stroke\s*$/i," and an animated percentage label"],[/gauge\s*$/i," with a gradient stroke and animated fill"],[/rating\s*(bar|widget)?\s*$/i," with half-star support and haptic feedback"],[/list\s*$/i," with swipe-to-delete and an undo snackbar"],[/pad\s*$/i," that exports a transparent PNG"],[/carousel\s*$/i," with parallax cards and page indicators"],[/(button|cta)\s*$/i," with a loading spinner and success state"],[/(chart|graph)\s*$/i," that animates from a Firestore stream"],[/action\s*(that|to)?\s*$/i," uploads an image to Firebase Storage and returns the URL"],[/timer\s*$/i," with pause, resume and a completion callback"],[/map\s*$/i," with clustered markers and a custom info window"],[/^a\s+\w*$/i," widget that"],[/(picker|selector)\s*$/i," with search and multi-select"]],Ay=220,Py=6;function Zu(t,e){return!!(t&&t.trim())&&!e}function Fy(t,e=""){if(typeof t!="string"||!t||t===e||t.trim().lengthi.test(t));return n?n[1]:null}function Ry(){let t="",e="";return{get active(){return t},resolve(n){return t=Fy(n,e)??"",t},dismiss(){t=""},accept(n){if(!t)return null;const i=n+t;return e=i,t="",i}}}function Ty({onSubmit:t}){const e=document.getElementById("composer"),n=document.getElementById("pipeline-input"),i=document.getElementById("hero-send");if(!e||!n||!i||typeof t!="function")return;const r=e.querySelector(".ghost .typed"),s=e.querySelector(".ghost .suggest"),o=document.getElementById("tab-hint"),a=document.getElementById("suggest-status"),l=Array.from(document.querySelectorAll("#example-chips .chip")),u=document.getElementById("btn-add-images"),c=document.getElementById("prompt-image-input"),d=window.matchMedia("(prefers-reduced-motion: reduce)"),f=Ry();let h=!1,p=!1,g=!1,m=!1,v=null,E=null;function S(){i.disabled=!Zu(n.value,p||g||m)}function _(){r&&(r.textContent=n.value)}function b(){s&&(s.textContent=""),_(),e.classList.remove("has-suggest"),o&&(o.hidden=!0,o.tabIndex=-1),a&&(a.textContent="")}function k(R){s&&(s.textContent=R),_(),e.classList.add("has-suggest"),o&&(o.hidden=!1,o.tabIndex=0,o.setAttribute("aria-label","Accept suggestion: "+R.trim())),a&&(a.textContent="Suggestion: "+R+". Press Tab to accept.")}function T(){f.dismiss(),b()}function x(){if(h||p)return;const R=f.resolve(n.value);R&&k(R)}function F(){clearTimeout(v),!h&&(v=setTimeout(x,Ay))}function $(){const R=f.accept(n.value);return R===null?!1:(n.value=R,b(),S(),!0)}function O(R){p=R,e.classList.toggle("is-busy",R),i.classList.toggle("is-busy",R),i.setAttribute("aria-label",R?"Generating":"Generate"),n.readOnly=R,l.forEach(Z=>{Z.disabled=R}),u&&(u.disabled=R),c&&(c.disabled=R),S()}async function L(){if(Zu(n.value,p||g||m)){T(),O(!0);try{await t()}finally{O(!1)}}}function N(){g=!1,E&&(clearInterval(E),E=null),e.classList.remove("is-demo-typing"),S()}function K(){l.forEach(R=>{R.classList.remove("is-active"),R.setAttribute("aria-pressed","false")})}function V(){try{n.focus({preventScroll:!0}),n.setSelectionRange(n.value.length,n.value.length)}catch{}}function M(R){const Z=R.dataset.prompt||"";if(N(),clearTimeout(v),v=null,T(),l.forEach(oe=>{const ye=oe===R;oe.classList.toggle("is-active",ye),oe.setAttribute("aria-pressed",String(ye))}),d.matches||!Z){n.value=Z,_(),S(),V();return}n.value="",_(),g=!0,S(),e.classList.add("is-demo-typing");let Ce=0;E=setInterval(()=>{Ce+=1,n.value=Z.slice(0,Ce),_(),Ce>=Z.length?(N(),V()):S()},22)}return l.forEach(R=>{R.setAttribute("aria-pressed","false"),R.addEventListener("click",()=>M(R))}),n.addEventListener("keydown",R=>{if(g&&R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!h){R.preventDefault();return}N(),R.key==="Tab"&&!R.shiftKey&&f.active?(R.preventDefault(),$()):R.key==="Escape"?(clearTimeout(v),v=null,T()):R.key==="Enter"&&!R.shiftKey&&!R.isComposing&&!h&&(R.preventDefault(),L())}),n.addEventListener("input",()=>{N(),K(),T(),S(),F()}),n.addEventListener("compositionstart",()=>{h=!0}),n.addEventListener("compositionend",()=>{h=!1,T(),S(),F()}),n.addEventListener("scroll",()=>{r&&r.parentNode&&(r.parentNode.scrollTop=n.scrollTop)}),o&&o.addEventListener("click",()=>{$(),n.focus({preventScroll:!0})}),i.addEventListener("click",L),n.addEventListener("pointerdown",()=>{N(),K()}),_(),S(),{setAttachmentsPending(R){m=!!R,S()}}}const $y="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses";const _t="https://4tgke4.buildship.run",Mh={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},vs="ccc_auth_session",ja="ccc_signin_return",My=1800*1e3,Xu=new WeakSet;let q={email:null,sessionToken:null,isVerified:!1};function Mn(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let ce=Mn({isResolved:!0}),Ua=Promise.resolve();const Ly=`${_t}/service/runpipeline`,Ny="bs_user_id",Oy="bs_identity_token",By=`${_t}/authUserCheck`;let ht={userId:null,token:null,status:null,resolved:!1};const _s=mv,ys="ccc_subscription",Qu=3,Dy=new Set(["active","trialing","paid"]),ws="google/gemini-3.7-flash",Dr=["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"],jy={"google/gemini-3.7-flash":"Gemini 3.7 Flash","anthropic/claude-opus-5":"Claude Opus 5","openai/gpt-5.6-sol":"GPT-5.6 Sol","z-ai/glm-5.2":"GLM 5.2","moonshotai/kimi-k3":"Kimi K3","openrouter/auto-beta":"OpenRouter: Auto Router","openrouter/free":"OpenRouter: Free Models","openrouter/deepseek/deepseek-v4-pro":"DeepSeek v4 Pro"};function Gt(t){return jy[t]||t}const Uy=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 Lh(t){return Uy.has(t)}const Ha=4,Vo=8*1024*1024,Hy="https://4tgke4.buildship.run/service/runpipeline-image";let Oe=[];const pn=[],Wy=3e4;let Nh=null;function zy(t){return new Promise(e=>{const n=new FileReader;n.onload=()=>e(n.result),n.onerror=()=>e(null),n.readAsDataURL(t)})}async function qy(t,e){const n=new FormData;return n.append("file",t),(await fetch(Hy,{method:"POST",body:n,signal:e})).json()}function Vy(t){if(Array.isArray(t)){const e=t[0];if(e&&typeof e=="object")for(const n of Object.keys(e)){if(n==="item"||n==="index")continue;const i=e[n];if(i&&typeof i=="object"){if(typeof i.file=="string")return i.file;if(typeof i.url=="string")return i.url}if(typeof i=="string")return i}return""}return typeof t=="string"?t:t&&typeof t=="object"&&(t.url||t.fileUrl||t.file_url||t.downloadUrl||t.imageUrl||t.image_url||t.file)||""}async function Gy(t,e,n){const i=await zy(t);i&&Oe.includes(e)&&(e.dataUrl=i,cn());let r="";if(i)try{r=Vy(await qy(t,n))}catch{r=""}return Oe.includes(e)?!i||!r?(Oe.splice(Oe.indexOf(e),1),cn(),"failed"):(e.url=r,cn(),"added"):"dropped"}function Oh(t){const e=pn.indexOf(t);e>=0&&pn.splice(e,1),Dh()}function Bh(t){t.controller.abort(),Oh(t);const e=Oe.indexOf(t.slot);e>=0&&(Oe.splice(e,1),cn())}function Dh(){Nh?.setAttachmentsPending(pn.length>0)}async function Ky(t){const e=Array.from(t.target.files||[]);if(!e.length)return;if(t.target.value="",y.isRunning){Ee("Wait for the current generation to finish before attaching images.","info");return}const n=e.filter(u=>u.size>Vo);n.length&&Ee(`Skipped ${n.length} image(s) over the ${(Vo/1024/1024).toFixed(0)} MB limit.`,"warning");const i=e.filter(u=>u.size<=Vo);if(!i.length)return;const r=Ha-Oe.length,s=i.slice(0,r);if(i.length>r&&Ee(`You can attach up to ${Ha} images.`,"info"),!s.length)return;const o=s.map(u=>{const c={dataUrl:null,name:u.name,url:null};Oe.push(c);const d={slot:c,controller:new AbortController},f=setTimeout(()=>d.controller.abort(),Wy);return d.job=Gy(u,c,d.controller.signal),pn.push(d),d.job.finally(()=>{clearTimeout(f),Oh(d)}),d.job});cn(),Dh();const l=(await Promise.all(o)).filter(u=>u==="failed").length;l&&Ee(`${l} image(s) could not be uploaded and were not attached.`,"error")}function Yy(t){const e=Oe[t],n=pn.find(i=>i.slot===e);if(n){Bh(n);return}Oe.splice(t,1),cn()}function cn(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",Oe.forEach((n,i)=>{const r=document.createElement("div");r.className="prompt-img-thumb"+(n.url?"":" is-pending"),r.innerHTML=(n.dataUrl?`Prompt image`:"")+``,t.appendChild(r)}),e&&(e.textContent=Oe.length>=Ha?"Image limit reached":"Add images"))}function Rl(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),n=Lh(e?.value);t.classList.toggle("hidden",!n),!n&&Oe.length&&(pn.slice().forEach(Bh),Oe=[],cn())}const Fn="ccc_usage",jh="google/gemini-3.7-flash",Uh="google/gemini-3.7-flash",Pr="google/gemini-3.7-flash",Di={professional:11,power:49},Wa={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"},jr={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 Ur={...jr};async function Jy(){const t=new AbortController,e=setTimeout(()=>t.abort(),5e3);try{const n=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:t.signal});if(!n.ok)return;const i=await n.json();if(i.result!=="success"||!i.rates)return;const r=i.rates,s={AUD:1},o=new Set([...Object.keys(jr),...Object.values(za),...Object.values(Wa)]);for(const a of o)a!=="AUD"&&(typeof r[a]=="number"&&r[a]>0?s[a]=r[a]:jr[a]&&(s[a]=jr[a]));Ur=s}catch{}finally{clearTimeout(e)}}const za={"America/Sao_Paulo":"BRL","America/Fortaleza":"BRL","America/Recife":"BRL","America/Bahia":"BRL","America/Belem":"BRL","America/Manaus":"BRL","America/Cuiaba":"BRL","America/Campo_Grande":"BRL","America/Araguaina":"BRL","America/Noronha":"BRL","America/Rio_Branco":"BRL","America/Porto_Velho":"BRL","America/Boa_Vista":"BRL","America/Maceio":"BRL","America/Santarem":"BRL","America/Eirunepe":"BRL","Europe/London":"GBP","Europe/Paris":"EUR","Europe/Berlin":"EUR","Europe/Madrid":"EUR","Europe/Rome":"EUR","Europe/Amsterdam":"EUR","Europe/Brussels":"EUR","Europe/Vienna":"EUR","Europe/Lisbon":"EUR","Europe/Dublin":"EUR","Europe/Helsinki":"EUR","Europe/Athens":"EUR","Europe/Bucharest":"RON","Europe/Budapest":"HUF","Europe/Warsaw":"PLN","Europe/Prague":"CZK","Europe/Copenhagen":"DKK","Europe/Stockholm":"SEK","Europe/Oslo":"NOK","Europe/Zurich":"CHF","Europe/Istanbul":"TRY","Europe/Moscow":"RUB","Europe/Kiev":"UAH","Europe/Kyiv":"UAH","Asia/Tokyo":"JPY","Asia/Seoul":"KRW","Asia/Shanghai":"CNY","Asia/Taipei":"TWD","Asia/Hong_Kong":"HKD","Asia/Singapore":"SGD","Asia/Kolkata":"INR","Asia/Calcutta":"INR","Asia/Bangkok":"THB","Asia/Ho_Chi_Minh":"VND","Asia/Jakarta":"IDR","Asia/Kuala_Lumpur":"MYR","Asia/Dubai":"AED","Asia/Jerusalem":"ILS","Asia/Tel_Aviv":"ILS","Asia/Manila":"PHP","Pacific/Auckland":"NZD","Australia/Sydney":"AUD","Australia/Melbourne":"AUD","Australia/Brisbane":"AUD","Australia/Perth":"AUD","Australia/Adelaide":"AUD","Australia/Hobart":"AUD","Australia/Darwin":"AUD","Australia/Lord_Howe":"AUD","America/Toronto":"CAD","America/Vancouver":"CAD","America/Edmonton":"CAD","America/Winnipeg":"CAD","America/Halifax":"CAD","America/St_Johns":"CAD","America/Regina":"CAD","America/New_York":"USD","America/Chicago":"USD","America/Denver":"USD","America/Los_Angeles":"USD","America/Phoenix":"USD","America/Anchorage":"USD","Pacific/Honolulu":"USD","America/Mexico_City":"MXN","America/Cancun":"MXN","America/Tijuana":"MXN","America/Argentina/Buenos_Aires":"ARS","America/Santiago":"CLP","America/Bogota":"COP","America/Lima":"PEN","Africa/Johannesburg":"ZAR"};function Tl(){try{const s=Intl.DateTimeFormat().resolvedOptions().timeZone;if(s&&za[s])return za[s]}catch{}const e=(navigator.language||"en-US").replace("-","_"),n=Wa[e];if(n)return n;const i=e.split("_")[0],r=Wa[i];return r||"USD"}function ji(t,e){const n=Ur[e]??Ur.USD,i=t*n,r=Math.round(i*100)/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:r>=100||r%1===0?0:2}).format(r)}catch{return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(t*Ur.USD)}}const gt="ccc_api_key_",Pt="ccc_session_api_key_",Rt="ccc_encryption_key",rr="ccc_encryption_key_scope",Zy="ccc_keystore",bs="keys",sr="ccc_encryption_key_version";let qa=null,Es=null,or=!1,Ss=!1,ed=!1;class xs extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function td(){if(ed)return;ed=!0;const t="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(t),document.body&&Ee(t,"warning")}function Hh(){return localStorage.getItem(sr)||""}function Va(){return crypto.randomUUID?.()||zh(crypto.getRandomValues(new Uint8Array(16)))}function Xy(){const t=Hh();if(t)return t;const e=Va();return localStorage.setItem(sr,e),e}function di(){qa=null,Es=null,or=!1,Ss=!1}window.addEventListener("storage",t=>{t.key===sr&&di()});function Qy(){return new Promise((t,e)=>{const n=indexedDB.open(Zy,1);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(bs)||i.createObjectStore(bs)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function $l(t,e){const n=await Qy();return new Promise((i,r)=>{const s=n.transaction(bs,t);let o;try{o=e(s.objectStore(bs))}catch(l){n.close(),r(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>r(o.error),s.oncomplete=()=>{n.close(),i(a)},s.onerror=()=>{n.close(),r(s.error||new Error("Encryption key transaction failed."))},s.onabort=()=>{n.close(),r(s.error||new Error("Encryption key transaction aborted."))}})}function e0(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function t0(){const t=await $l("readonly",e=>e.get(Rt));return e0(t)?t:null}async function Wh(t){await $l("readwrite",e=>e.put(t,Rt))}async function n0(){di();try{await $l("readwrite",t=>t.delete(Rt))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function i0(){const t=sessionStorage.getItem(Rt);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Wh(e),sessionStorage.removeItem(Rt),sessionStorage.removeItem(rr),localStorage.removeItem(gt+"salt"),e}async function nd(t){const e=sessionStorage.getItem(Rt);if(e)return Ss=sessionStorage.getItem(rr)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new xs;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),i=await crypto.subtle.exportKey("jwk",n);return sessionStorage.setItem(Rt,JSON.stringify(i)),sessionStorage.setItem(rr,"session"),Ss=!1,crypto.subtle.importKey("jwk",i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function r0(t){if(sessionStorage.getItem(rr)==="session"&&sessionStorage.getItem(Rt))return td(),or=!0,nd(t);try{const e=await t0();if(e)return e;const n=await i0();if(n)return n;const i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Wh(i),i}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),td(),or=!0,nd(t)}}async function Ml(t={}){const{allowSessionFallbackCreation:e=!0}=t,n=Xy();Es!==n&&di();const i=qa||r0(e);qa=i,Es=n;try{return await i}catch(r){throw di(),r}}async function s0(t){const e=await Ml(),n=Es,i=new TextEncoder,r=crypto.getRandomValues(new Uint8Array(12)),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},e,i.encode(t)),o=new Uint8Array(r.length+s.byteLength);return o.set(r),o.set(new Uint8Array(s),r.length),{ciphertext:zh(o),keyVersion:n,sessionFallback:or}}async function o0(t,e={}){const{isSessionCredential:n=!1}=e;try{const i=await Ml({allowSessionFallbackCreation:!1});if(or&&!n&&!Ss)throw new xs;const r=a0(t),s=r.slice(0,12),o=r.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},i,o);return new TextDecoder().decode(a)}catch(i){if(i instanceof xs)throw i;return console.error("Decryption failed:",i),null}}function zh(t){const e=new Uint8Array(t);let n="";for(let i=0;i0}let Ln="",fi="",Gi=null,rd=0,nt="not-configured";async function Ll(){sessionStorage.getItem(Rt)&&await Ml(),Ln=await Te("flutterflow"),fi=await Te("flutterflow_project_id"),g0(),rn(),Ln?Dl():(nt="not-configured",vt())}let ar=!1;function qh(){const t=document.getElementById("api-keys-modal");We(t),Bl(),Ln&&jl(Ln)}function Nl(){ar=!1,qh()}function c0(){ar=!0;const t=document.getElementById("walkthrough-modal");t&&ze(t),qh()}let sd=!1;function od(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-settings-model");if(!t||!e)return;e.value=t.value;const n=Array.from(t.options);Array.from(e.options).forEach((r,s)=>{const o=n[s];o&&(r.textContent=o.textContent)});const i=document.getElementById("composer-settings-free-notice");i&&(document.getElementById("model-selector-free-notice")?(i.hidden=!1,i.innerHTML='Free plan — Gemini only. '):i.hidden=!0)}function ad(){const t=document.getElementById("code-generator-model"),e=document.getElementById("composer-image-capability"),n=document.getElementById("composer-image-capability-note");if(!t)return;const i=Gt(t.value),r=Lh(t.value);e&&(e.textContent=r?"Supported":"Not supported"),n&&(n.textContent=r?`${i} accepts reference images you attach to the prompt.`:`Images can't be attached with ${i}. Attached images are removed when you switch to it.`),Rl()}function u0(){if(ar=!1,od(),ad(),!sd){const e=document.getElementById("composer-settings-model");e&&e.addEventListener("change",()=>{const n=document.getElementById("code-generator-model");n.value=e.value,n.dispatchEvent(new Event("change")),od(),ad()}),sd=!0}const t=document.querySelector('.composer [aria-label="Generation settings"]');We("composer-settings-modal",{trigger:t})}function d0(t){t&&t.target!==t.currentTarget||ze("composer-settings-modal")}function Vh(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&ze(e);const n=ar;if(ar=!1,n){const i=document.getElementById("walkthrough-modal");i&&(nt==="connected"&&Ol(),We(i))}}let en=1;function Gh(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function js(){const t=Gh();t.length&&t.forEach((e,n)=>{const i=n+1;e.classList.remove("wt-current","wt-done","wt-pending");const r=e.querySelector(".wt-step-num");i===en?(e.classList.add("wt-current"),r&&(r.textContent=i)):i0&&en<=t&&(en++,js())}function f0(){const t=document.getElementById("walkthrough-modal");t&&(en=1,js(),We(t))}function h0(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&ze(e);const n=document.getElementById("walkthrough-dont-show");n&&n.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function Kh(){if(q.isVerified&&Tt()&&ce.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(en=1,js(),We(e))}}async function Bl(){const t=document.getElementById("flutterflow-api-key-input");Ln?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",p0()}function p0(){ld("flutterflow","flutterflow-key-status"),ld("flutterflow_project_id","flutterflow-project-status")}function ld(t,e){const n=document.getElementById(e);if(!n)return;const i=n.querySelector(".key-status-dot"),r=n.querySelector("span");Ct(t)?(i.className="key-status-dot configured",r.className="text-green-600",r.textContent="User key configured"):(i.className="key-status-dot missing",r.className="text-gray-500",r.textContent="Not configured")}function rn(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff");e&&e.classList.toggle("hidden",!t)}function g0(){const t=document.getElementById("api-keys-status");if(!t)return;const e=t.querySelectorAll(".key-status-dot"),n=["flutterflow"];e.forEach((i,r)=>{const s=n[r];s==="flutterflow"?Ct("flutterflow")&&Ct("flutterflow_project_id")?(i.className="key-status-dot configured",i.title="FlutterFlow (Fully configured)"):Ct("flutterflow")||Ct("flutterflow_project_id")?(i.className="key-status-dot env",i.title="FlutterFlow (Partially configured)"):(i.className="key-status-dot missing",i.title="FlutterFlow (Not configured)"):Ct(s)?(i.className="key-status-dot configured",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (User key)"):(i.className="key-status-dot missing",i.title=s.charAt(0).toUpperCase()+s.slice(1)+" (Not configured)")}),rn()}async function m0(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select"),n=t.value.trim();n&&await id("flutterflow",n);const i=e?.value.trim()||"";if(i){if(!Us(i)){Ee("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await id("flutterflow_project_id",i)}await Ll(),n&&await Dl(),Bl();const r=document.querySelector("#api-keys-modal .bg-blue-500"),s=r.textContent;r.textContent="Saved!",r.classList.remove("bg-blue-500","hover:bg-blue-600"),r.classList.add("bg-green-500"),setTimeout(()=>{r.textContent=s,r.classList.remove("bg-green-500"),r.classList.add("bg-blue-500","hover:bg-blue-600"),Vh()},1e3)}async function v0(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(sr,Va()),di(),localStorage.removeItem(gt+"flutterflow"),localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow"),sessionStorage.removeItem(Pt+"flutterflow_project_id"),sessionStorage.removeItem(Rt),sessionStorage.removeItem(rr),localStorage.removeItem(gt+"salt"),await n0(),localStorage.setItem(sr,Va()),localStorage.removeItem(gt+"flutterflow"),localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow"),sessionStorage.removeItem(Pt+"flutterflow_project_id"),await Ll();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),Bl()}function Us(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function vt(){const t=document.getElementById("acct-ff-dot"),e=document.getElementById("acct-ff-status"),n=document.getElementById("acct-ff-endpoint"),i=document.getElementById("acct-ff-project");if(n){const o=yt();n.textContent=o.includes("staging")?"Staging":"Production"}if(i&&(i.textContent=fi||"—"),!e)return;let r,s;if(!Ct("flutterflow"))r="Not connected — add your FlutterFlow API key",s="";else switch(nt){case"connected":r="Connected to FlutterFlow",s="ok";break;case"no-projects":r="Key accepted — no projects found",s="warn";break;case"unauthorized":r="API key rejected (401/403) — re-enter your key",s="bad";break;case"network-error":r="Could not reach FlutterFlow — check your network",s="bad";break;default:r="Checking connection…",s="warn";break}e.textContent=r,t&&(t.className=`acct-dot${s?" "+s:""}`)}async function Dl(){const t=await Te("flutterflow");if(!t||!Ct("flutterflow"))return nt="not-configured",vt(),null;nt="validating",vt();try{const n=await new mi(t,"","main",yt()).listProjects();return nt=n&&n.length>0?"connected":"no-projects",vt(),n}catch(e){const n=String(e&&e.message||"");return nt=/(401|403)|denied|unauthorized|scoped|list permission/i.test(n)?"unauthorized":"network-error",vt(),null}}function _0(){fi="",localStorage.removeItem(gt+"flutterflow_project_id"),sessionStorage.removeItem(Pt+"flutterflow_project_id")}function y0(){_0();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML='',t.value=""),Ct("flutterflow")?(nt="validating",jl(Ln)):nt="not-configured",vt()}function w0(t,e){const n=document.getElementById(t);n&&(n.value?e?n.style.borderColor="#22c55e":n.style.borderColor="#ef4444":n.style.borderColor="")}function b0(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const n=e.target.value.trim().length>0;w0("flutterflow-api-key-input",n)}),t.addEventListener("blur",E0(async e=>{const n=e.target.value.trim();n&&await jl(n)},500)))}function E0(t,e){let n;return function(...r){const s=()=>{clearTimeout(n),t(...r)};clearTimeout(n),n=setTimeout(s,e)}}async function jl(t){const e=document.getElementById("flutterflow-projects-select"),n=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',n&&n.classList.add("hidden"),(Ct("flutterflow")||t)&&(nt="validating"),vt();try{const r=await new mi(t,"","main",yt()).listProjects();if(!r||r.length===0){nt="no-projects",vt(),e.innerHTML='';return}nt="connected",vt(),e.innerHTML='',r.forEach(s=>{const o=document.createElement("option");o.value=s.id||s.projectId||"",o.textContent=s.name||s.projectName||`Project ${s.id}`,e.appendChild(o)}),fi&&(e.value=fi)}catch(i){console.error("Failed to fetch projects:",i);const r=String(i&&i.message||"");nt=/(401|403)|denied|unauthorized|scoped|list permission/i.test(r)?"unauthorized":"network-error",vt(),e.innerHTML='',n&&(n.textContent=`Failed to load projects: ${i.message}`,n.classList.remove("hidden"))}}function S0(t){const e=document.getElementById(t),i=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",i.innerHTML=` `):(e.type="password",i.innerHTML=` - `)}let y={step1Result:null,step2Result:null,step3Result:null,bundleSpec:null,artifactBundle:null,bundleReview:null,selectedArtifactId:null,resultsViewMode:"summary",currentStep:0,isRunning:!1,runId:0,submittedPrompt:"",submittedImages:[]};function b0(){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 E0(){y.bundleSpec=er(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function Ds(){const t=ai(y.bundleSpec);y.artifactBundle=er(y.step2Result,{id:y.bundleSpec?.id,title:y.bundleSpec?.title,description:y.bundleSpec?.description,artifactType:t.artifactType,artifactName:t.artifactName,fileName:t.fileName,dependencies:t.dependencies,relationships:y.bundleSpec?.relationships,code:y.step2Result||""});const e=Gv(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(n=>n.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=ai(y.artifactBundle).id}function js(){const t=er(y.step3Result,{id:y.artifactBundle?.id,title:y.artifactBundle?.title}),e=new Map(t.artifacts.map(i=>[i.id,i.review])),n=new Map(t.artifacts.filter(i=>{const r=i.review;return r&&typeof r.fixedSource=="string"&&r.fixedSource.trim()}).map(i=>[i.id,i.review.fixedSource.trim()]));y.bundleReview=er({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(i=>{const r=n.get(i.id)||null;return{...i,review:e.get(i.id)||i.review||y.step3Result||null,...r?{fixedCode:r}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function qh(){const t=Dl();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function Dl(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(n=>n.id===y.selectedArtifactId)||ai(t)}function jl(){return Dl().code||y.step2Result||""}async function S0(){try{await $l()}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/"};function x0(t,e){const n=e?.trim()?` (${e.trim().slice(0,200)})`:"";return t===401?`Your FlutterFlow API key was rejected (401 Unauthorized)${n}. Re-enter a current key under API Keys settings, then try again.`:`Listing FlutterFlow projects was denied (403)${n}. The key may be scoped to sync a single project without list permission - verify the key's access in FlutterFlow, re-enter it under API Keys settings, then retry.`}class pi{constructor(e,n,i="main",r=jr.production){this.apiKey=e,this.baseUrl=r,this._projectId=n,this._branchName=i,this._endpoint=r}get projectId(){return this._projectId}get branchName(){return this._branchName==="main"?"":this._branchName}async exportProjectZip(){console.log(`Exporting code from FlutterFlow project: ${this.projectId}, branch: ${this.branchName||"main"}`);const e=[{project:{path:`projects/${this.projectId}`},...this.branchName?{branch_name:this.branchName}:{},export_as_module:!1,include_assets_map:!1,format:!1,export_as_debug:!1},{project_id:this.projectId,branch_name:this.branchName,include_assets:!1,export_as_module:!1}];let n=null;for(const i of e)try{const r=await fetch(`${this.baseUrl}exportCode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(i)});if(!r.ok){const a=await r.text();n=new Error(`Export failed: ${r.status} - ${a}`);continue}const s=await r.json(),o=s?.value?.project_zip||s?.project_zip;if(!o){n=new Error("Export response did not include project source.");continue}return o}catch(r){n=r}throw n||new Error("Export failed for an unknown reason.")}async fetchProjectSource(){const e=await this.exportProjectZip(),n=await JSZip.loadAsync(e,{base64:!0}),i=Object.keys(n.files).filter(a=>!n.files[a].dir&&(a==="pubspec.yaml"||a.endsWith("/pubspec.yaml"))).sort((a,l)=>a.split("/").length-l.split("/").length)[0];if(!i)throw new Error("Export did not contain a pubspec.yaml.");const r=i.slice(0,i.length-12),s=new Map,o=Object.keys(n.files).filter(a=>{if(n.files[a].dir||!a.startsWith(r))return!1;const l=a.slice(r.length);return l==="lib/flutter_flow/custom_functions.dart"||l.startsWith("lib/custom_code/")&&l.endsWith(".dart")});return await Promise.all(o.map(async a=>{s.set(a.slice(r.length),await n.files[a].async("string"))})),{pubspecYaml:await n.files[i].async("string"),files:s}}async pushCodeWithRetry(e,n=3,i=null){const r=[jr.production,jr.staging],s=Math.max(0,r.indexOf(this._endpoint));let o=!1,a=null;for(let l=0;lsetTimeout(p,1e3*(l+1)));continue}if(d.ok)return console.log(`Push to ${c} succeeded!`),d;a=d.status;const f=d.status<500&&!o;if(qa(f?d.clone():d,Ih).then(h=>console.log(`Push to ${c} returned ${d.status}: ${h}`),()=>console.log(`Push to ${c} returned ${d.status} (unreadable response body)`)),d.status>=500&&(o=!0),d.status===500){console.warn(`Endpoint ${c} returned 500, trying next...`),await new Promise(h=>setTimeout(h,1e3*(l+1)));continue}if(d.status>=500)throw new Qe(`FlutterFlow reported a server error (HTTP ${d.status}), which cannot prove the push was refused — the write may have been applied before the failure. Open your FlutterFlow project to reconcile before retrying.`);if(o)throw new Qe(`The push was refused (HTTP ${d.status}), but an earlier sync attempt may already have applied it — server errors and dropped responses cannot prove a refusal. Open your FlutterFlow project to reconcile before retrying.`);return d}throw zu({httpStatus:a})}async pushCode(e,n=null){return this.pushCodeWithRetry(e,3,n)}parseProjectsResponse(e){if(e?.success&&typeof e.value=="string")try{const i=JSON.parse(e.value);if(i&&Array.isArray(i.entries))return i.entries.map(r=>({id:r.id,name:r.project?.name||r.id}))}catch(i){console.error("Failed to parse stringified project value:",i)}const n=e?.projects||e?.items||e?.entries||(Array.isArray(e)?e:[]);return Array.isArray(n)?n:[]}async listProjects(){console.log("Listing projects for API key");const e=[`${this.baseUrl}listProjects`,"https://api.flutterflow.io/v2/l/listProjects"];let n=0,i="";for(const r of e){const s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({project_type:"ALL",deserialize_response:!0})});if(s.ok)return r!==e[0]&&console.log(`listProjects answered on legacy path ${r}`),this.parseProjectsResponse(await s.json());if(n=s.status,i=await s.text(),console.warn(`listProjects via ${r} returned ${n}: ${i}`),s.status===401||s.status===403)throw new Error(x0(s.status,i));if(s.status!==404)throw new Error(`List projects failed: ${s.status} - ${i}`)}throw new Error(`List projects failed: ${n} - ${i}`)}}function qa(t,e){const n=t.body?.getReader?.(),i=n?(async()=>{const r=new TextDecoder;let s="";for(;;){const{done:o,value:a}=await n.read();if(o)break;s+=r.decode(a,{stream:!0})}return s+r.decode()})():Promise.resolve("");return Wl(i,e,(r,s)=>{try{n?.cancel()?.catch?.(()=>{})}catch{}s(new Error("The response body stalled before it finished."))})}async function I0(t,e=Ih){const n=t.clone();let i;try{i=JSON.parse(await qa(t,e))}catch{let o="";try{o=await qa(n,e)}catch{}if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:o||`HTTP ${t.status}`,errorMap:new Map};throw new Qe(`FlutterFlow accepted the sync but returned an unreadable response${o?`: ${o.slice(0,200)}`:"."}`)}if(!t.ok){let s=i.message||`HTTP ${t.status}`,o=new Map;if(i.errors)o=new Map(Object.entries(i.errors));else if(!i.message&&typeof i=="object"){const a=Object.keys(i).filter(l=>l.endsWith(".dart")&&Array.isArray(i[l]));a.length>0&&(o=new Map(Object.entries(i)),s=a.flatMap(u=>i[u].map(c=>`${u}: ${c.errorMessage}`)).join(` -`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:s,errorMap:o}}let r={};if(i.value)try{r=typeof i.value=="string"?JSON.parse(i.value):i.value}catch(s){console.warn("Ignoring malformed push response value:",s)}return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(r))}}function Ul(t,e){return{401:"Authentication failed. Please check your FlutterFlow API key.",403:"Access denied. You may not have permission to modify this project.",404:"Project not found. Please check your Project ID.",409:"Conflict detected. The project may have been modified elsewhere.",422:"Validation failed: Invalid request format",429:"Rate limit exceeded. Please try again in a few minutes.",500:"FlutterFlow server error. Please try again later.",503:"FlutterFlow service temporarily unavailable."}[t]||`FlutterFlow API error: ${`HTTP ${t}`}`}const J={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},Vh=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,Gh=/extends\s+State<\w+>/;function k0(t,e=""){if(t==="pubspec.yaml")return J.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return J.OTHER;if(t==="custom_functions.dart")return J.FUNCTION;if(e){const n=Vh.test(e),i=Gh.test(e);if(n||i)return J.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return J.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return J.FUNCTION}return J.CODE_FILE}function Kh(t,e){switch(e){case J.ACTION:return`lib/custom_code/actions/${t}`;case J.WIDGET:return`lib/custom_code/widgets/${t}`;case J.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case J.CODE_FILE:return`lib/custom_code/${t}`;case J.DEPENDENCIES:return"pubspec.yaml";case J.OTHER:return`lib/custom_code/${t}`;default:return t}}async function Hl(t,e=new Map){return Pv(t,e)}const Va=new Map,Rn=new Map;function Us(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function or(t){Va.delete(Us(t))}function C0(t,e){const n=Us(t),i=Rn.get(n)??new Map;for(const{path:r,content:s}of e){const o=i.get(r)??new Set;o.add(s),i.set(r,o)}Rn.set(n,i)}function A0(t,e){const n=Us(t),i=Rn.get(n);if(i){for(const{path:r,content:s}of e){const o=i.get(r);o&&(o.delete(s),o.size===0&&i.delete(r))}i.size===0&&Rn.delete(n)}}function Wl(t,e,n){return new Promise((i,r)=>{let s=!1;const o=(l,u,c)=>{s||(s=!0,c==="resolve"?i(u):r(u))},a=setTimeout(()=>{s||(s=!0,n(i,r))},e);t.then(l=>{clearTimeout(a),o(i,l,"resolve")},l=>{clearTimeout(a),o(r,l,"reject")})})}async function zl(t,e,n=xh){const i={stop:!1};return Wl((async()=>{const r=await t.pushCode(e,i);return I0(r)})(),n,(r,s)=>{i.stop=!0,s(new Qe("FlutterFlow did not answer the sync in time — the push may still have been applied. The outcome is not yet known: open your FlutterFlow project to reconcile before retrying the deploy."))})}async function ql(t,e,n,i,r="",s=xh){const o=a_(e,n);if(o.length===0)return{remoteFiles:n,syncFileMap:e,unverified:[],approximate:[]};const a=Q_(o,r),l={...a.manifest,sources:a.sources},u=a.skipped.map(h=>h.reason);u.forEach(h=>console.warn(`[custom class deploy] ${h}`));const c=a.approximate;c.forEach(h=>console.warn(`[custom class deploy] ${h}`)),console.log(`Provisioning ${o.length} new FlutterFlow custom code file(s) before sync.`),Be.set("provision");let d=!0,f;try{const h=(async()=>{let p;try{p=await fetch(Fy,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:i,customClasses:o,verification:l,stream:!0})})}catch{throw new Qe("The provisioning request did not return a response. The deploy may have reached the FlutterFlow server — open your FlutterFlow project to reconcile before retrying.")}return ty(p,{onPhase:g=>{d&&Be.setSubstatus(g)},onLog:g=>{d&&console.log(`[custom class deploy] ${g}`)}})})();if(f=await Wl(h,s,(p,g)=>{d=!1,g(new Qe("The deploy is still working on the FlutterFlow server, but this browser tab has stopped waiting. Your custom classes may or may not have been written — the outcome is not yet known. Open your FlutterFlow project to reconcile before retrying the deploy."))}),!f.finalResultReceived)throw qu(f)===Le.FAILED?new Error(f.error||`FlutterFlow custom class provisioning failed (HTTP ${f.httpStatus}).`):new Qe("The connection to the FlutterFlow deploy runner dropped before it reported a result. The deploy may still be finishing on the server; open your FlutterFlow project to reconcile before retrying.");if(!f.success){const p=f.details?` ${f.details}`:"",g=`${f.error||"FlutterFlow custom class provisioning failed."}${p}`;throw qu(f)===Le.UNCONFIRMED?new Qe(`${g} The failure arrived after the deploy began — custom classes may already be written. Open your FlutterFlow project to reconcile before retrying.`):new Error(g)}}catch(h){throw h instanceof Qe&&(or(t),C0(t,o)),h}return or(t),A0(t,o),f.verificationSkipped&&(console.warn(`[custom class deploy] ${f.verificationSkipped}`),u.push(f.verificationSkipped)),{remoteFiles:n,syncFileMap:l_(e,o),unverified:u,approximate:c,provisionSucceeded:!0}}async function Vl(t,e={}){const n=Us(t);let i=Va.get(n);if(i===void 0){try{i=await t.fetchProjectSource()}catch(u){throw new Error(`Could not read your project's pubspec.yaml (${u.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=Eh(i.pubspecYaml);if(!a.valid)throw new Error(`Your project's pubspec.yaml could not be read reliably (${a.errors.join("; ")}). Deploy was stopped so your existing package dependencies aren't overwritten.`);const l=Rn.get(n);if(l){for(const[u,c]of[...l]){const d=i.files.get(u);d!==void 0&&c.delete(d),c.size===0&&l.delete(u)}l.size===0&&Rn.delete(n)}Rn.has(n)||Va.set(n,i)}const r=await yy(i.pubspecYaml,e),s=K_(i.pubspecYaml,r.overrides),o=G_(s.yaml,r.additions);return r.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>`${a}: ${r.additions[a]||"any"}`).join(", "),r.sdk.dartSdkFloor?`(resolved for Dart ${r.sdk.dartSdkFloor})`:""),r.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:s.overridden,warnings:r.warnings,remoteFiles:i.files}}function P0(t){const e=[],n=[];t.content.length>5e4&&n.push("Code file is large (>50KB). This may take longer to commit."),t.content.length>1e5&&e.push("Code file is too large (>100KB). Consider splitting into smaller components.");const i=t.content.split(` -`).length;i>500&&n.push(`Code has ${i} lines. Consider breaking it into smaller widgets.`),t.content.includes("setState")&&t.codeType===J.ACTION&&n.push("Using setState in a Custom Action may not work as expected. Consider using a Custom Widget."),t.content.includes("dynamic")&&!t.content.includes("?")&&n.push('Code uses "dynamic" types. Consider adding explicit types for better null safety.'),t.content.match(/Color\(0xFF[0-9A-Fa-f]{6}\)/)&&n.push("Code contains hardcoded colors. Consider using FlutterFlowTheme.of(context) for theme consistency.");const r=t.content.match(/print\s*\(/g);r&&r.length>3&&n.push(`Code contains ${r.length} print statements. Consider removing debug prints before committing.`);const s=k_(t.content);if(s&&e.push(`FlutterFlow cannot format this code - ${s}. Fix or regenerate before committing.`),t.codeType===J.WIDGET){const o=hh(t.content),a=S_(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=`${ph(o[0])}`;e.push(`Widget class name "${o[0]}" does not match the file name "${t.fileName}". FlutterFlow derives the widget from the file name, so it will report "No widget ${a} found". Rename the file to "${l}" or the class to match before committing.`)}}return{canProceed:e.length===0,issues:e,warnings:n}}function Yh(t,e={}){const{artifactType:n="CustomWidget",artifactName:i="GeneratedCode",fileName:r}=e,s=b_(t);let o=r||i;if(n==="CustomFunction")o="custom_functions.dart";else if(n==="CustomWidget"){const u=hh(s)[0],c=u?ph(u):null;c&&o!==c?(console.warn(`Commit file name "${o}" does not match declared widget class "${u}"; renaming to "${c}" so FlutterFlow can find the widget.`),o=c):o.endsWith(".dart")||(o+=".dart")}else o.endsWith(".dart")||(o+=".dart");let a=J.CODE_FILE;switch(n){case"CustomAction":a=J.ACTION;break;case"CustomWidget":a=J.WIDGET;break;case"CustomFunction":a=J.FUNCTION;break;case"CustomClass":case"CodeFile":a=J.CODE_FILE;break}let l="";return a===J.WIDGET?l=`// Automatic FlutterFlow imports + `)}let y={step1Result:null,step2Result:null,step3Result:null,bundleSpec:null,artifactBundle:null,bundleReview:null,selectedArtifactId:null,resultsViewMode:"summary",currentStep:0,isRunning:!1,runId:0,submittedPrompt:"",submittedImages:[]};function x0(){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 I0(){y.bundleSpec=nr(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function Hs(){const t=li(y.bundleSpec);y.artifactBundle=nr(y.step2Result,{id:y.bundleSpec?.id,title:y.bundleSpec?.title,description:y.bundleSpec?.description,artifactType:t.artifactType,artifactName:t.artifactName,fileName:t.fileName,dependencies:t.dependencies,relationships:y.bundleSpec?.relationships,code:y.step2Result||""});const e=Zv(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(n=>n.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=li(y.artifactBundle).id}function Ws(){const t=nr(y.step3Result,{id:y.artifactBundle?.id,title:y.artifactBundle?.title}),e=new Map(t.artifacts.map(i=>[i.id,i.review])),n=new Map(t.artifacts.filter(i=>{const r=i.review;return r&&typeof r.fixedSource=="string"&&r.fixedSource.trim()}).map(i=>[i.id,i.review.fixedSource.trim()]));y.bundleReview=nr({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(i=>{const r=n.get(i.id)||null;return{...i,review:e.get(i.id)||i.review||y.step3Result||null,...r?{fixedCode:r}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function Yh(){const t=Ul();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function Ul(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(n=>n.id===y.selectedArtifactId)||li(t)}function Hl(){return Ul().code||y.step2Result||""}async function k0(){try{await Ll()}catch(t){return console.error("checkConnection: initializeApiKeys failed:",t),!1}return!0}const Hr={production:"https://api.flutterflow.io/v2/",staging:"https://api.flutterflow.io/v2-staging/"};function C0(t,e){const n=e?.trim()?` (${e.trim().slice(0,200)})`:"";return t===401?`Your FlutterFlow API key was rejected (401 Unauthorized)${n}. Re-enter a current key under API Keys settings, then try again.`:`Listing FlutterFlow projects was denied (403)${n}. The key may be scoped to sync a single project without list permission - verify the key's access in FlutterFlow, re-enter it under API Keys settings, then retry.`}class mi{constructor(e,n,i="main",r=Hr.production){this.apiKey=e,this.baseUrl=r,this._projectId=n,this._branchName=i,this._endpoint=r}get projectId(){return this._projectId}get branchName(){return this._branchName==="main"?"":this._branchName}async exportProjectZip(){console.log(`Exporting code from FlutterFlow project: ${this.projectId}, branch: ${this.branchName||"main"}`);const e=[{project:{path:`projects/${this.projectId}`},...this.branchName?{branch_name:this.branchName}:{},export_as_module:!1,include_assets_map:!1,format:!1,export_as_debug:!1},{project_id:this.projectId,branch_name:this.branchName,include_assets:!1,export_as_module:!1}];let n=null;for(const i of e)try{const r=await fetch(`${this.baseUrl}exportCode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(i)});if(!r.ok){const a=await r.text();n=new Error(`Export failed: ${r.status} - ${a}`);continue}const s=await r.json(),o=s?.value?.project_zip||s?.project_zip;if(!o){n=new Error("Export response did not include project source.");continue}return o}catch(r){n=r}throw n||new Error("Export failed for an unknown reason.")}async fetchProjectSource(){const e=await this.exportProjectZip(),n=await JSZip.loadAsync(e,{base64:!0}),i=Object.keys(n.files).filter(a=>!n.files[a].dir&&(a==="pubspec.yaml"||a.endsWith("/pubspec.yaml"))).sort((a,l)=>a.split("/").length-l.split("/").length)[0];if(!i)throw new Error("Export did not contain a pubspec.yaml.");const r=i.slice(0,i.length-12),s=new Map,o=Object.keys(n.files).filter(a=>{if(n.files[a].dir||!a.startsWith(r))return!1;const l=a.slice(r.length);return l==="lib/flutter_flow/custom_functions.dart"||l.startsWith("lib/custom_code/")&&l.endsWith(".dart")});return await Promise.all(o.map(async a=>{s.set(a.slice(r.length),await n.files[a].async("string"))})),{pubspecYaml:await n.files[i].async("string"),files:s}}async pushCodeWithRetry(e,n=3,i=null){const r=[Hr.production,Hr.staging],s=Math.max(0,r.indexOf(this._endpoint));let o=!1,a=null;for(let l=0;lsetTimeout(p,1e3*(l+1)));continue}if(d.ok)return console.log(`Push to ${c} succeeded!`),d;a=d.status;const f=d.status<500&&!o;if(Ga(f?d.clone():d,Ah).then(h=>console.log(`Push to ${c} returned ${d.status}: ${h}`),()=>console.log(`Push to ${c} returned ${d.status} (unreadable response body)`)),d.status>=500&&(o=!0),d.status===500){console.warn(`Endpoint ${c} returned 500, trying next...`),await new Promise(h=>setTimeout(h,1e3*(l+1)));continue}if(d.status>=500)throw new Qe(`FlutterFlow reported a server error (HTTP ${d.status}), which cannot prove the push was refused — the write may have been applied before the failure. Open your FlutterFlow project to reconcile before retrying.`);if(o)throw new Qe(`The push was refused (HTTP ${d.status}), but an earlier sync attempt may already have applied it — server errors and dropped responses cannot prove a refusal. Open your FlutterFlow project to reconcile before retrying.`);return d}throw Vu({httpStatus:a})}async pushCode(e,n=null){return this.pushCodeWithRetry(e,3,n)}parseProjectsResponse(e){if(e?.success&&typeof e.value=="string")try{const i=JSON.parse(e.value);if(i&&Array.isArray(i.entries))return i.entries.map(r=>({id:r.id,name:r.project?.name||r.id}))}catch(i){console.error("Failed to parse stringified project value:",i)}const n=e?.projects||e?.items||e?.entries||(Array.isArray(e)?e:[]);return Array.isArray(n)?n:[]}async listProjects(){console.log("Listing projects for API key");const e=[`${this.baseUrl}listProjects`,"https://api.flutterflow.io/v2/l/listProjects"];let n=0,i="";for(const r of e){const s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({project_type:"ALL",deserialize_response:!0})});if(s.ok)return r!==e[0]&&console.log(`listProjects answered on legacy path ${r}`),this.parseProjectsResponse(await s.json());if(n=s.status,i=await s.text(),console.warn(`listProjects via ${r} returned ${n}: ${i}`),s.status===401||s.status===403)throw new Error(C0(s.status,i));if(s.status!==404)throw new Error(`List projects failed: ${s.status} - ${i}`)}throw new Error(`List projects failed: ${n} - ${i}`)}}function Ga(t,e){const n=t.body?.getReader?.(),i=n?(async()=>{const r=new TextDecoder;let s="";for(;;){const{done:o,value:a}=await n.read();if(o)break;s+=r.decode(a,{stream:!0})}return s+r.decode()})():Promise.resolve("");return ql(i,e,(r,s)=>{try{n?.cancel()?.catch?.(()=>{})}catch{}s(new Error("The response body stalled before it finished."))})}async function A0(t,e=Ah){const n=t.clone();let i;try{i=JSON.parse(await Ga(t,e))}catch{let o="";try{o=await Ga(n,e)}catch{}if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:o||`HTTP ${t.status}`,errorMap:new Map};throw new Qe(`FlutterFlow accepted the sync but returned an unreadable response${o?`: ${o.slice(0,200)}`:"."}`)}if(!t.ok){let s=i.message||`HTTP ${t.status}`,o=new Map;if(i.errors)o=new Map(Object.entries(i.errors));else if(!i.message&&typeof i=="object"){const a=Object.keys(i).filter(l=>l.endsWith(".dart")&&Array.isArray(i[l]));a.length>0&&(o=new Map(Object.entries(i)),s=a.flatMap(u=>i[u].map(c=>`${u}: ${c.errorMessage}`)).join(` +`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:s,errorMap:o}}let r={};if(i.value)try{r=typeof i.value=="string"?JSON.parse(i.value):i.value}catch(s){console.warn("Ignoring malformed push response value:",s)}return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(r))}}function Wl(t,e){return{401:"Authentication failed. Please check your FlutterFlow API key.",403:"Access denied. You may not have permission to modify this project.",404:"Project not found. Please check your Project ID.",409:"Conflict detected. The project may have been modified elsewhere.",422:"Validation failed: Invalid request format",429:"Rate limit exceeded. Please try again in a few minutes.",500:"FlutterFlow server error. Please try again later.",503:"FlutterFlow service temporarily unavailable."}[t]||`FlutterFlow API error: ${`HTTP ${t}`}`}const J={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},Jh=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,Zh=/extends\s+State<\w+>/;function P0(t,e=""){if(t==="pubspec.yaml")return J.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return J.OTHER;if(t==="custom_functions.dart")return J.FUNCTION;if(e){const n=Jh.test(e),i=Zh.test(e);if(n||i)return J.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return J.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return J.FUNCTION}return J.CODE_FILE}function Xh(t,e){switch(e){case J.ACTION:return`lib/custom_code/actions/${t}`;case J.WIDGET:return`lib/custom_code/widgets/${t}`;case J.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case J.CODE_FILE:return`lib/custom_code/${t}`;case J.DEPENDENCIES:return"pubspec.yaml";case J.OTHER:return`lib/custom_code/${t}`;default:return t}}async function zl(t,e=new Map){return $v(t,e)}const Ka=new Map,Qn=new Map,ei=new Map;function ur(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function hi(t){Ka.delete(ur(t))}function Wr(t,e,n){const i=ur(t),r=Qn.get(i)??new Map;for(const{path:s,content:o}of e){const a=r.get(s)??new Map,l=a.get(o)??{uncertain:0,verified:0};n.uncertain&&(l.uncertain+=n.uncertain),n.verified&&(l.verified+=n.verified),l.uncertain<=0&&l.verified<=0?a.delete(o):a.set(o,l),a.size===0?r.delete(s):r.set(s,a)}r.size===0?Qn.delete(i):Qn.set(i,r)}function F0(t,e){Wr(t,e,{uncertain:1})}function R0(t){const e=ur(t);ei.set(e,(ei.get(e)??0)+1)}function cd(t){const e=ur(t),n=(ei.get(e)??0)-1;n<=0?ei.delete(e):ei.set(e,n)}function ql(t,e,n){return new Promise((i,r)=>{let s=!1;const o=(l,u,c)=>{s||(s=!0,c==="resolve"?i(u):r(u))},a=setTimeout(()=>{s||(s=!0,n(i,r))},e);t.then(l=>{clearTimeout(a),o(i,l,"resolve")},l=>{clearTimeout(a),o(r,l,"reject")})})}async function Vl(t,e,n=Ch){const i={stop:!1},r=(async()=>{const s=await t.pushCode(e,i);return A0(s)})();return ql(r,n,(s,o)=>{i.stop=!0,hi(t),R0(t),r.then(()=>cd(t),()=>cd(t)),o(new Qe("FlutterFlow did not answer the sync in time — the push may still have been applied. The outcome is not yet known: open your FlutterFlow project to reconcile before retrying the deploy."))})}async function Gl(t,e,n,i,r="",s=Ch){const o=d_(e,n);if(o.length===0)return{remoteFiles:n,syncFileMap:e,unverified:[],approximate:[]};const a=iy(o,r),l={...a.manifest,sources:a.sources},u=a.skipped.map(p=>p.reason);u.forEach(p=>console.warn(`[custom class deploy] ${p}`));const c=a.approximate;c.forEach(p=>console.warn(`[custom class deploy] ${p}`)),console.log(`Provisioning ${o.length} new FlutterFlow custom code file(s) before sync.`),Be.set("provision");let d=!0,f,h;try{if(h=(async()=>{let p;try{p=await fetch($y,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:i,customClasses:o,verification:l,stream:!0})})}catch{throw new Qe("The provisioning request did not return a response. The deploy may have reached the FlutterFlow server — open your FlutterFlow project to reconcile before retrying.")}return sy(p,{onPhase:g=>{d&&Be.setSubstatus(g)},onLog:g=>{d&&console.log(`[custom class deploy] ${g}`)}})})(),f=await ql(h,s,(p,g)=>{d=!1,g(new Qe("The deploy is still working on the FlutterFlow server, but this browser tab has stopped waiting. Your custom classes may or may not have been written — the outcome is not yet known. Open your FlutterFlow project to reconcile before retrying the deploy."))}),!f.finalResultReceived)throw Gu(f)===Le.FAILED?new Error(f.error||`FlutterFlow custom class provisioning failed (HTTP ${f.httpStatus}).`):new Qe("The connection to the FlutterFlow deploy runner dropped before it reported a result. The deploy may still be finishing on the server; open your FlutterFlow project to reconcile before retrying.");if(!f.success){const p=f.details?` ${f.details}`:"",g=`${f.error||"FlutterFlow custom class provisioning failed."}${p}`;throw Gu(f)===Le.UNCONFIRMED?new Qe(`${g} The failure arrived after the deploy began — custom classes may already be written. Open your FlutterFlow project to reconcile before retrying.`):new Error(g)}}catch(p){throw p instanceof Qe&&(hi(t),F0(t,o),h?.then(g=>{g?.finalResultReceived&&g.success?Wr(t,o,{uncertain:-1,verified:1}):g?.finalResultReceived&&Fh(g)&&Wr(t,o,{uncertain:-1})},()=>{})),p}return hi(t),Wr(t,o,{verified:1}),f.verificationSkipped&&(console.warn(`[custom class deploy] ${f.verificationSkipped}`),u.push(f.verificationSkipped)),{remoteFiles:n,syncFileMap:f_(e,o),unverified:u,approximate:c,provisionSucceeded:!0}}async function Kl(t,e={}){const n=ur(t);let i=Ka.get(n);if(i===void 0){try{i=await t.fetchProjectSource()}catch(u){throw new Error(`Could not read your project's pubspec.yaml (${u.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=Ih(i.pubspecYaml);if(!a.valid)throw new Error(`Your project's pubspec.yaml could not be read reliably (${a.errors.join("; ")}). Deploy was stopped so your existing package dependencies aren't overwritten.`);const l=Qn.get(n);if(l){for(const[u,c]of[...l]){const d=i.files.get(u);if(d!==void 0){const f=c.get(d);f&&(f.verified>0?f.verified-=1:f.uncertain-=1,f.uncertain<=0&&f.verified<=0&&c.delete(d))}c.size===0&&l.delete(u)}l.size===0&&Qn.delete(n)}!Qn.has(n)&&!ei.has(n)&&Ka.set(n,i)}const r=await Ey(i.pubspecYaml,e),s=X_(i.pubspecYaml,r.overrides),o=Z_(s.yaml,r.additions);return r.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>`${a}: ${r.additions[a]||"any"}`).join(", "),r.sdk.dartSdkFloor?`(resolved for Dart ${r.sdk.dartSdkFloor})`:""),r.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:s.overridden,warnings:r.warnings,remoteFiles:i.files}}function T0(t){const e=[],n=[];t.content.length>5e4&&n.push("Code file is large (>50KB). This may take longer to commit."),t.content.length>1e5&&e.push("Code file is too large (>100KB). Consider splitting into smaller components.");const i=t.content.split(` +`).length;i>500&&n.push(`Code has ${i} lines. Consider breaking it into smaller widgets.`),t.content.includes("setState")&&t.codeType===J.ACTION&&n.push("Using setState in a Custom Action may not work as expected. Consider using a Custom Widget."),t.content.includes("dynamic")&&!t.content.includes("?")&&n.push('Code uses "dynamic" types. Consider adding explicit types for better null safety.'),t.content.match(/Color\(0xFF[0-9A-Fa-f]{6}\)/)&&n.push("Code contains hardcoded colors. Consider using FlutterFlowTheme.of(context) for theme consistency.");const r=t.content.match(/print\s*\(/g);r&&r.length>3&&n.push(`Code contains ${r.length} print statements. Consider removing debug prints before committing.`);const s=F_(t.content);if(s&&e.push(`FlutterFlow cannot format this code - ${s}. Fix or regenerate before committing.`),t.codeType===J.WIDGET){const o=mh(t.content),a=C_(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=`${vh(o[0])}`;e.push(`Widget class name "${o[0]}" does not match the file name "${t.fileName}". FlutterFlow derives the widget from the file name, so it will report "No widget ${a} found". Rename the file to "${l}" or the class to match before committing.`)}}return{canProceed:e.length===0,issues:e,warnings:n}}function Qh(t,e={}){const{artifactType:n="CustomWidget",artifactName:i="GeneratedCode",fileName:r}=e,s=I_(t);let o=r||i;if(n==="CustomFunction")o="custom_functions.dart";else if(n==="CustomWidget"){const u=mh(s)[0],c=u?vh(u):null;c&&o!==c?(console.warn(`Commit file name "${o}" does not match declared widget class "${u}"; renaming to "${c}" so FlutterFlow can find the widget.`),o=c):o.endsWith(".dart")||(o+=".dart")}else o.endsWith(".dart")||(o+=".dart");let a=J.CODE_FILE;switch(n){case"CustomAction":a=J.ACTION;break;case"CustomWidget":a=J.WIDGET;break;case"CustomFunction":a=J.FUNCTION;break;case"CustomClass":case"CodeFile":a=J.CODE_FILE;break}let l="";return a===J.WIDGET?l=`// Automatic FlutterFlow imports import '/flutter_flow/flutter_flow_theme.dart'; import '/flutter_flow/flutter_flow_util.dart'; import 'package:flutter/material.dart'; @@ -111,15 +111,15 @@ import '/flutter_flow/lat_lng.dart'; import '/flutter_flow/place.dart'; import '/flutter_flow/uploaded_file.dart'; -`),{content:Jv(s,l),fileName:o,codeType:a,artifactType:n,artifactName:i}}function F0(t){const e={};for(const n of Sl(t))e[n]="";return e}function R0(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 T0(t,e,n,i=new Set,r=""){const s=[],o=Vh.test(e),a=Gh.test(e);return n===J.WIDGET&&!o&&!a&&s.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:s.length===0,errors:s}}function Hs(t){const e=[],n=[];if(!t||t.size===0)return e.push("No files to commit"),{valid:!1,errors:e,warnings:n};const i=new Set(Array.from(t.values()).flatMap(r=>Ps(r.content||"")));for(const[r,s]of t.entries()){if((!s.content||s.content.trim().length===0)&&e.push(`File ${r} is empty`),s.content&&s.content.length>1e5&&n.push(`File ${r} is very large (>100KB)`),r.endsWith(".dart")){const o=T0(r,s.content,s.type,i,s.artifactName);o.valid||e.push(...o.errors.map(a=>`${r}: ${a}`))}if(r==="pubspec.yaml"){const o=Eh(s.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:n}}const ee={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},G={currentState:ee.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=ee.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(ee).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===ee.PREPARING&&(this.startTime=Date.now()),(t===ee.SUCCESS||t===ee.ERROR)&&(this.endTime=Date.now()),typeof window<"u"&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("commitStateChange",{detail:{state:t,commitState:this}})),console.log(`Commit state changed to: ${t}`)},setError(t){this.error=t,this.setState(ee.ERROR)},setSuccess(t){this.result=t,this.setState(ee.SUCCESS)},setProgress(t,e){this.filesProcessed=t,this.totalFiles=e},getElapsedTime(){return this.startTime?(this.endTime||Date.now())-this.startTime:null},isInProgress(){return this.currentState===ee.PREPARING||this.currentState===ee.VALIDATING||this.currentState===ee.PUSHING}};async function $0(t,e,n={}){let{codeType:i="W"}=n;const{pubspecDeps:r={},artifactName:s=e}=n;i==="CustomWidget"&&(i=J.WIDGET),i==="CustomAction"&&(i=J.ACTION),i==="CustomFunction"&&(i=J.FUNCTION),i==="CustomClass"&&(i=J.CODE_FILE),i==="CodeFile"&&(i=J.CODE_FILE),G.reset(),G.setState(ee.PREPARING);try{const o=await Te("flutterflow"),a=await Te("flutterflow_project_id");if(!o||!a)throw new Error("FlutterFlow credentials not configured. Please set your API key and Project ID in the API Keys settings.");if(!Bs(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=yt(),u=new pi(o,a,"main",l);G.setState(ee.VALIDATING);const c=new Map,d=i||k0(e,t),f=Kh(e,d);c.set(e,{artifactName:s,content:t,type:d,path:f}),G.setProgress(0,c.size);const h=Hs(c);if(!h.valid)throw new Error(`Validation failed: +`),{content:e_(s,l),fileName:o,codeType:a,artifactType:n,artifactName:i}}function $0(t){const e={};for(const n of Il(t))e[n]="";return e}function M0(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 L0(t,e,n,i=new Set,r=""){const s=[],o=Jh.test(e),a=Zh.test(e);return n===J.WIDGET&&!o&&!a&&s.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:s.length===0,errors:s}}function zs(t){const e=[],n=[];if(!t||t.size===0)return e.push("No files to commit"),{valid:!1,errors:e,warnings:n};const i=new Set(Array.from(t.values()).flatMap(r=>Ts(r.content||"")));for(const[r,s]of t.entries()){if((!s.content||s.content.trim().length===0)&&e.push(`File ${r} is empty`),s.content&&s.content.length>1e5&&n.push(`File ${r} is very large (>100KB)`),r.endsWith(".dart")){const o=L0(r,s.content,s.type,i,s.artifactName);o.valid||e.push(...o.errors.map(a=>`${r}: ${a}`))}if(r==="pubspec.yaml"){const o=Ih(s.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:n}}const ee={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},G={currentState:ee.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=ee.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(ee).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===ee.PREPARING&&(this.startTime=Date.now()),(t===ee.SUCCESS||t===ee.ERROR)&&(this.endTime=Date.now()),typeof window<"u"&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("commitStateChange",{detail:{state:t,commitState:this}})),console.log(`Commit state changed to: ${t}`)},setError(t){this.error=t,this.setState(ee.ERROR)},setSuccess(t){this.result=t,this.setState(ee.SUCCESS)},setProgress(t,e){this.filesProcessed=t,this.totalFiles=e},getElapsedTime(){return this.startTime?(this.endTime||Date.now())-this.startTime:null},isInProgress(){return this.currentState===ee.PREPARING||this.currentState===ee.VALIDATING||this.currentState===ee.PUSHING}};async function N0(t,e,n={}){let{codeType:i="W"}=n;const{pubspecDeps:r={},artifactName:s=e}=n;i==="CustomWidget"&&(i=J.WIDGET),i==="CustomAction"&&(i=J.ACTION),i==="CustomFunction"&&(i=J.FUNCTION),i==="CustomClass"&&(i=J.CODE_FILE),i==="CodeFile"&&(i=J.CODE_FILE),G.reset(),G.setState(ee.PREPARING);try{const o=await Te("flutterflow"),a=await Te("flutterflow_project_id");if(!o||!a)throw new Error("FlutterFlow credentials not configured. Please set your API key and Project ID in the API Keys settings.");if(!Us(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=yt(),u=new mi(o,a,"main",l);G.setState(ee.VALIDATING);const c=new Map,d=i||P0(e,t),f=Xh(e,d);c.set(e,{artifactName:s,content:t,type:d,path:f}),G.setProgress(0,c.size);const h=zs(c);if(!h.valid)throw new Error(`Validation failed: ${h.errors.join(` -`)}`);const p=await Vl(u,r),g=p.yaml,m=await ql(u,c,p.remoteFiles,`Provision ${s} custom class`,g),v=await Hl(m.syncFileMap,m.remoteFiles),E=new Map(m.syncFileMap);E.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),Be.set("package");const S=await Gl(E),_={project_id:a,zipped_custom_code:S,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};G.setState(ee.PUSHING),G.setProgress(1,c.size),or(u),Be.set("push");const b=await zl(u,_);if(b.success)G.setSuccess({fileCount:c.size,projectId:a,warnings:b.errorMap&&b.errorMap.size>0?Array.from(b.errorMap.entries()):[]});else{const k=b.errorMessage||Ul(b.responseCode),T=new Error(k);throw T.remoteRefusal=!0,T}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:p.added,unverified:m.unverified,approximate:m.approximate,warnings:b.errorMap?Array.from(b.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),G.setError(o),o instanceof Qe?{success:!1,unconfirmed:!0,error:o.message,state:G.currentState}:{success:!1,error:o.message,remoteRefusal:o.remoteRefusal===!0,state:G.currentState}}}async function Gl(t){const e=new JSZip;for(const[n,i]of t.entries())e.file(n,i.content);return e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}async function M0(t,e={}){const{artifactType:n,artifactName:i,fileName:r,pipelineResult:s}=e;console.log(`Starting commit for ${i} (${n})`);let o=!1;const a={projectId:null,endpoint:yt(),artifactType:n,artifactName:i,fileName:r};try{G.setState(ee.PREPARING);const l=Yh(t,{artifactType:n,artifactName:i,fileName:r}),u=F0(l.content);console.log("Detected dependencies:",u),G.setState(ee.VALIDATING);const c=await Te("flutterflow"),d=qi||await Te("flutterflow_project_id");if(!c)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!d)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Bs(d))throw new Error("Invalid FlutterFlow Project ID format.");a.projectId=d;const f=new Map;f.set(l.fileName,{artifactName:i,content:l.content,type:l.codeType,path:Kh(l.fileName,l.codeType),functionName:l.codeType===J.FUNCTION?i:void 0}),G.setProgress(0,f.size);const h=Hs(f);if(!h.valid)throw new Error(`File validation failed: +`)}`);const p=await Kl(u,r),g=p.yaml,m=await Gl(u,c,p.remoteFiles,`Provision ${s} custom class`,g),v=await zl(m.syncFileMap,m.remoteFiles),E=new Map(m.syncFileMap);E.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),Be.set("package");const S=await Yl(E),_={project_id:a,zipped_custom_code:S,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};G.setState(ee.PUSHING),G.setProgress(1,c.size),hi(u),Be.set("push");const b=await Vl(u,_);if(b.success)G.setSuccess({fileCount:c.size,projectId:a,warnings:b.errorMap&&b.errorMap.size>0?Array.from(b.errorMap.entries()):[]});else{const k=b.errorMessage||Wl(b.responseCode),T=new Error(k);throw T.remoteRefusal=!0,T}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:p.added,unverified:m.unverified,approximate:m.approximate,warnings:b.errorMap?Array.from(b.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),G.setError(o),o instanceof Qe?{success:!1,unconfirmed:!0,error:o.message,state:G.currentState}:{success:!1,error:o.message,remoteRefusal:o.remoteRefusal===!0,state:G.currentState}}}async function Yl(t){const e=new JSZip;for(const[n,i]of t.entries())e.file(n,i.content);return e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}async function O0(t,e={}){const{artifactType:n,artifactName:i,fileName:r,pipelineResult:s}=e;console.log(`Starting commit for ${i} (${n})`);let o=!1;const a={projectId:null,endpoint:yt(),artifactType:n,artifactName:i,fileName:r};try{G.setState(ee.PREPARING);const l=Qh(t,{artifactType:n,artifactName:i,fileName:r}),u=$0(l.content);console.log("Detected dependencies:",u),G.setState(ee.VALIDATING);const c=await Te("flutterflow"),d=Gi||await Te("flutterflow_project_id");if(!c)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!d)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Us(d))throw new Error("Invalid FlutterFlow Project ID format.");a.projectId=d;const f=new Map;f.set(l.fileName,{artifactName:i,content:l.content,type:l.codeType,path:Xh(l.fileName,l.codeType),functionName:l.codeType===J.FUNCTION?i:void 0}),G.setProgress(0,f.size);const h=zs(f);if(!h.valid)throw new Error(`File validation failed: ${h.errors.join(` -`)}`);h.warnings.length>0&&console.warn("Validation warnings:",h.warnings),G.setState(ee.PUSHING);const p=yt(),g=new pi(c,d,"main",p),m=await Vl(g,u),v=m.yaml,E=await ql(g,f,m.remoteFiles,`Provision ${i} custom class`,v);o=E.provisionSucceeded===!0;const S=await Hl(E.syncFileMap,E.remoteFiles),_=new Map(E.syncFileMap);_.set("pubspec.yaml",{content:v,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Be.set("package");const b=await Gl(_),k={project_id:d,zipped_custom_code:b,uid:`web_${Date.now()}`,branch_name:g.branchName,serialized_yaml:v,file_map:S.fileMapContents,functions_map:S.functionsMapContents};G.setProgress(1,f.size),or(g),Be.set("push");const T=await zl(g,k);if(T.success){const x={...R0(l,s),projectId:d};return G.setSuccess({...x,fileCount:f.size,warnings:T.errorMap?Array.from(T.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${l.fileName} to FlutterFlow`,metadata:x,targetIdentity:a,addedDependencies:m.added,unverified:E.unverified,approximate:E.approximate,warnings:T.errorMap?Array.from(T.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}else{const x=T.errorMessage||Ul(T.responseCode),F=new Error(x);throw F.errorMap=T.errorMap,F.remoteRefusal=!0,F}}catch(l){console.error("Commit execution failed:",l),G.setError(l);let u=new Map;if(l.errorMap)u=l.errorMap;else if(l.message&&l.message.includes("{"))try{const c=l.message.match(/\{[\s\S]*\}/);if(c){const d=JSON.parse(c[0]);u=new Map(Object.entries(d))}}catch(c){console.warn("Failed to parse error map from commit response:",c)}return l instanceof Qe?{success:!1,unconfirmed:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:o?{success:!1,partial:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:l.message,errorMap:u,remoteRefusal:l.remoteRefusal===!0,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function L0(t,e={}){const{pipelineResult:n}=e;let i=!1;const r={projectId:null,endpoint:yt(),artifactType:"Bundle",artifactName:t?.title,fileName:t?.fileEntries?`${t.fileEntries.length} artifacts`:"bundle"};try{if(G.setState(ee.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: +`)}`);h.warnings.length>0&&console.warn("Validation warnings:",h.warnings),G.setState(ee.PUSHING);const p=yt(),g=new mi(c,d,"main",p),m=await Kl(g,u),v=m.yaml,E=await Gl(g,f,m.remoteFiles,`Provision ${i} custom class`,v);o=E.provisionSucceeded===!0;const S=await zl(E.syncFileMap,E.remoteFiles),_=new Map(E.syncFileMap);_.set("pubspec.yaml",{content:v,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Be.set("package");const b=await Yl(_),k={project_id:d,zipped_custom_code:b,uid:`web_${Date.now()}`,branch_name:g.branchName,serialized_yaml:v,file_map:S.fileMapContents,functions_map:S.functionsMapContents};G.setProgress(1,f.size),hi(g),Be.set("push");const T=await Vl(g,k);if(T.success){const x={...M0(l,s),projectId:d};return G.setSuccess({...x,fileCount:f.size,warnings:T.errorMap?Array.from(T.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${l.fileName} to FlutterFlow`,metadata:x,targetIdentity:a,addedDependencies:m.added,unverified:E.unverified,approximate:E.approximate,warnings:T.errorMap?Array.from(T.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}else{const x=T.errorMessage||Wl(T.responseCode),F=new Error(x);throw F.errorMap=T.errorMap,F.remoteRefusal=!0,F}}catch(l){console.error("Commit execution failed:",l),G.setError(l);let u=new Map;if(l.errorMap)u=l.errorMap;else if(l.message&&l.message.includes("{"))try{const c=l.message.match(/\{[\s\S]*\}/);if(c){const d=JSON.parse(c[0]);u=new Map(Object.entries(d))}}catch(c){console.warn("Failed to parse error map from commit response:",c)}return l instanceof Qe?{success:!1,unconfirmed:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:o?{success:!1,partial:!0,error:l.message,errorMap:u,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:l.message,errorMap:u,remoteRefusal:l.remoteRefusal===!0,targetIdentity:a,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function B0(t,e={}){const{pipelineResult:n}=e;let i=!1;const r={projectId:null,endpoint:yt(),artifactType:"Bundle",artifactName:t?.title,fileName:t?.fileEntries?`${t.fileEntries.length} artifacts`:"bundle"};try{if(G.setState(ee.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: ${t.errors.join(` -`)}`);const s=new Map(t.fileEntries.map(b=>[b.fileName,{artifactId:b.artifactId,artifactName:b.artifactName,content:b.content,type:b.type,path:b.path,functionName:b.type===J.FUNCTION?b.artifactName:void 0}]));G.setProgress(0,s.size);const o=Hs(s);if(!o.valid)throw new Error(`File validation failed: +`)}`);const s=new Map(t.fileEntries.map(b=>[b.fileName,{artifactId:b.artifactId,artifactName:b.artifactName,content:b.content,type:b.type,path:b.path,functionName:b.type===J.FUNCTION?b.artifactName:void 0}]));G.setProgress(0,s.size);const o=zs(s);if(!o.valid)throw new Error(`File validation failed: ${o.errors.join(` -`)}`);G.setState(ee.VALIDATING);const a=await Te("flutterflow"),l=qi||await Te("flutterflow_project_id");if(!a)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!l)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Bs(l))throw new Error("Invalid FlutterFlow Project ID format.");r.projectId=l,G.setState(ee.PUSHING);const u=yt(),c=new pi(a,l,"main",u),d=await Vl(c,t.dependencies),f=d.yaml,h=await ql(c,s,d.remoteFiles,`Provision ${t.title} custom classes`,f);i=h.provisionSucceeded===!0;const p=await Hl(h.syncFileMap,h.remoteFiles),g=new Map(h.syncFileMap);g.set("pubspec.yaml",{content:f,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Be.set("package");const m=await Gl(g),v={project_id:l,zipped_custom_code:m,uid:`web_${Date.now()}`,branch_name:c.branchName,serialized_yaml:f,file_map:p.fileMapContents,functions_map:p.functionsMapContents};G.setProgress(1,s.size),or(c),Be.set("push");const E=await zl(c,v);if(E.success){const b={...n,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((k,T)=>k+T.content.length,0),projectId:l};return G.setSuccess({...b,fileCount:s.size,warnings:E.errorMap?Array.from(E.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:b,targetIdentity:r,addedDependencies:d.added,unverified:h.unverified,approximate:h.approximate,warnings:E.errorMap?Array.from(E.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}const S=E.errorMessage||Ul(E.responseCode),_=new Error(S);throw _.errorMap=E.errorMap,_.remoteRefusal=!0,_}catch(s){console.error("Bundle commit execution failed:",s),G.setError(s);const o=s.errorMap||new Map;return s instanceof Qe?{success:!1,unconfirmed:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:i?{success:!1,partial:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function N0(t,e=[]){const n=yl("architect");try{return await xs("architect",Nh,vv(t),n,e)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Prompt Architect failed: ${i.message}`)}}async function Ws(t,e,n=[],i){const r=_v(t),s=yl("generator",y.bundleSpec);try{return await xs("generator",e,r,s,n)}catch(o){if(o.isModelArmor||o.isUsageLimit||o.isPipelineCancel)throw o;if(e!==Cr){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,o.message),Uw(e,Cr,i);try{return await xs("generator",Cr,r,s,n)}catch(a){throw a.isModelArmor||a.isUsageLimit||a.isPipelineCancel?a:new Error(`Code Generator failed: primary (${e}): ${o.message} | fallback (${Cr}): ${a.message}`)}}throw new Error(`Code Generator failed: ${o.message}`)}}async function zs(t,e=null){const n={...yl("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await xs("review",Oh,yv(t),n)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Code Review failed: ${i.message}`)}}function Es(t,e){const n=document.getElementById(`step${t}-item`),i=document.getElementById(`step${t}-status`);!n||!i||(n.classList.remove("active","completed","error"),i.classList.remove("running","completed","error"),e==="active"?(n.classList.add("active"),i.classList.add("running"),i.innerHTML=` +`)}`);G.setState(ee.VALIDATING);const a=await Te("flutterflow"),l=Gi||await Te("flutterflow_project_id");if(!a)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!l)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Us(l))throw new Error("Invalid FlutterFlow Project ID format.");r.projectId=l,G.setState(ee.PUSHING);const u=yt(),c=new mi(a,l,"main",u),d=await Kl(c,t.dependencies),f=d.yaml,h=await Gl(c,s,d.remoteFiles,`Provision ${t.title} custom classes`,f);i=h.provisionSucceeded===!0;const p=await zl(h.syncFileMap,h.remoteFiles),g=new Map(h.syncFileMap);g.set("pubspec.yaml",{content:f,type:J.DEPENDENCIES,path:"pubspec.yaml"}),Be.set("package");const m=await Yl(g),v={project_id:l,zipped_custom_code:m,uid:`web_${Date.now()}`,branch_name:c.branchName,serialized_yaml:f,file_map:p.fileMapContents,functions_map:p.functionsMapContents};G.setProgress(1,s.size),hi(c),Be.set("push");const E=await Vl(c,v);if(E.success){const b={...n,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((k,T)=>k+T.content.length,0),projectId:l};return G.setSuccess({...b,fileCount:s.size,warnings:E.errorMap?Array.from(E.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:b,targetIdentity:r,addedDependencies:d.added,unverified:h.unverified,approximate:h.approximate,warnings:E.errorMap?Array.from(E.errorMap.entries()):[],elapsedTime:G.getElapsedTime()}}const S=E.errorMessage||Wl(E.responseCode),_=new Error(S);throw _.errorMap=E.errorMap,_.remoteRefusal=!0,_}catch(s){console.error("Bundle commit execution failed:",s),G.setError(s);const o=s.errorMap||new Map;return s instanceof Qe?{success:!1,unconfirmed:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:i?{success:!1,partial:!0,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}:{success:!1,error:s.message,errorMap:o,targetIdentity:r,state:G.currentState,elapsedTime:G.getElapsedTime()}}}async function D0(t,e=[]){const n=bl("architect");try{return await Cs("architect",jh,bv(t),n,e)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Prompt Architect failed: ${i.message}`)}}async function qs(t,e,n=[],i){const r=Ev(t),s=bl("generator",y.bundleSpec);try{return await Cs("generator",e,r,s,n)}catch(o){if(o.isModelArmor||o.isUsageLimit||o.isPipelineCancel)throw o;if(e!==Pr){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,o.message),zw(e,Pr,i);try{return await Cs("generator",Pr,r,s,n)}catch(a){throw a.isModelArmor||a.isUsageLimit||a.isPipelineCancel?a:new Error(`Code Generator failed: primary (${e}): ${o.message} | fallback (${Pr}): ${a.message}`)}}throw new Error(`Code Generator failed: ${o.message}`)}}async function Vs(t,e=null){const n={...bl("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await Cs("review",Uh,Sv(t),n)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Code Review failed: ${i.message}`)}}function Is(t,e){const n=document.getElementById(`step${t}-item`),i=document.getElementById(`step${t}-status`);!n||!i||(n.classList.remove("active","completed","error"),i.classList.remove("running","completed","error"),e==="active"?(n.classList.add("active"),i.classList.add("running"),i.innerHTML=` `):e==="completed"?(n.classList.add("completed"),i.classList.add("completed"),i.innerHTML=` @@ -127,12 +127,12 @@ ${o.errors.join(` `):i.innerHTML=` - `)}function Ae(t,e){const n=document.getElementById(`step${t}-loading`),i=document.getElementById(`step${t}-result`);e?(n.classList.remove("hidden"),i.classList.add("hidden"),Es(t,"active")):(n.classList.add("hidden"),i.classList.remove("hidden"),Es(t,"completed"))}function O0(t){const e=document.getElementById(`${t}-content`),n=document.getElementById(`${t}-chevron`);e.classList.contains("open")?(e.classList.remove("open"),n&&(n.style.transform="rotate(0deg)")):(e.classList.add("open"),n&&(n.style.transform="rotate(180deg)"))}function B0(t){it(parseInt(t.replace("step","")))}function it(t){for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-item`);a&&a.classList.remove("active")}const e=document.getElementById(`step${t}-item`);e&&e.classList.add("active"),On();const n=document.getElementById("ready-state");n&&n.classList.add("hidden");for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-content`);a&&a.classList.add("hidden")}const i=document.getElementById(`step${t}-content`);i&&i.classList.remove("hidden");const r=document.getElementById("stage-title"),s={1:"Prompt Architect",2:"Code Generator",3:"Code Review"};r&&(r.textContent=s[t]||"Active Workflow Stage")}function D0(t){const e=document.getElementById(t);if(!e)return;const n=e.dataset.raw||e.textContent;navigator.clipboard.writeText(n).then(()=>{const r=e.closest(".code-container")?.querySelector(".copy-btn");r&&(r.classList.add("copied"),r.innerHTML=' Copied!',setTimeout(()=>{r.classList.remove("copied"),r.innerHTML=' Copy'},2e3))}).catch(i=>{console.warn("Failed to copy to clipboard:",i)})}function Ga(t){const e=Ka(t);console.log(`Step 1 (Prompt Architect): ${Gt(Nh)}`),console.log(e!==t?`Step 2 (Code Generator): ${Gt(t)} → ${Gt(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${Gt(t)}`),console.log(`Step 3 (Code Review): ${Gt(Oh)}`)}function Jh(){return{step1Result:y.step1Result,step2Result:y.step2Result,step3Result:y.step3Result,artifactBundle:y.artifactBundle,bundleReview:y.bundleReview,selectedArtifactId:y.selectedArtifactId}}function j0(t){if(!t)return;Object.assign(y,t),new Set((y.artifactBundle?.artifacts||[]).map(n=>n.id)).has(y.selectedArtifactId)||(y.selectedArtifactId=ai(y.artifactBundle)?.id||null)}const Zh="results-replacement-error";function U0(t,{stage:e=2,runId:n,retry:i}){if(!re(n))return;const r=document.getElementById(Zh);if(!r)return;const s=Ah(t),o=document.getElementById("results-replacement-error-title"),a=document.getElementById("results-replacement-error-message"),l=document.getElementById("results-replacement-error-retry"),u=document.getElementById("results-replacement-error-upgrade");o&&(o.textContent=`${Ks[e]||"Regeneration"}: ${s.title}`),a&&(a.textContent=s.message),r.hidden=!1;let c=null;u&&(u.hidden=!s.canUpgrade,s.canUpgrade&&(u.textContent="View plans",u.onclick=()=>fi(),c=u)),l&&(l.hidden=s.canUpgrade,s.canUpgrade||(l.onclick=()=>{Kl(),typeof i=="function"&&i()},l.textContent="Retry",c=l)),(c||r).focus({preventScroll:!0})}function Kl(){const t=document.getElementById(Zh);t&&(t.hidden=!0)}function Xh(t,{previous:e,stage:n,runId:i,retry:r}){re(i)&&(t.isUsageLimit&&un(),j0(e),ur(),nn(!0),dr(),no(),U0(t,{stage:n,runId:i,retry:r}),rn())}async function Qh(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0;const e=Ys();Yl("standardRegenerate",y.step2Result,y.step1Result);const n=document.querySelectorAll(".btn-refine-action"),i=Jh();n.forEach(r=>{r.disabled=!0,r.innerHTML=` + `)}function Ae(t,e){const n=document.getElementById(`step${t}-loading`),i=document.getElementById(`step${t}-result`);e?(n.classList.remove("hidden"),i.classList.add("hidden"),Is(t,"active")):(n.classList.add("hidden"),i.classList.remove("hidden"),Is(t,"completed"))}function j0(t){const e=document.getElementById(`${t}-content`),n=document.getElementById(`${t}-chevron`);e.classList.contains("open")?(e.classList.remove("open"),n&&(n.style.transform="rotate(0deg)")):(e.classList.add("open"),n&&(n.style.transform="rotate(180deg)"))}function U0(t){it(parseInt(t.replace("step","")))}function it(t){for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-item`);a&&a.classList.remove("active")}const e=document.getElementById(`step${t}-item`);e&&e.classList.add("active"),Nn();const n=document.getElementById("ready-state");n&&n.classList.add("hidden");for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-content`);a&&a.classList.add("hidden")}const i=document.getElementById(`step${t}-content`);i&&i.classList.remove("hidden");const r=document.getElementById("stage-title"),s={1:"Prompt Architect",2:"Code Generator",3:"Code Review"};r&&(r.textContent=s[t]||"Active Workflow Stage")}function H0(t){const e=document.getElementById(t);if(!e)return;const n=e.dataset.raw||e.textContent;navigator.clipboard.writeText(n).then(()=>{const r=e.closest(".code-container")?.querySelector(".copy-btn");r&&(r.classList.add("copied"),r.innerHTML=' Copied!',setTimeout(()=>{r.classList.remove("copied"),r.innerHTML=' Copy'},2e3))}).catch(i=>{console.warn("Failed to copy to clipboard:",i)})}function Ya(t){const e=Ja(t);console.log(`Step 1 (Prompt Architect): ${Gt(jh)}`),console.log(e!==t?`Step 2 (Code Generator): ${Gt(t)} → ${Gt(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${Gt(t)}`),console.log(`Step 3 (Code Review): ${Gt(Uh)}`)}function ep(){return{step1Result:y.step1Result,step2Result:y.step2Result,step3Result:y.step3Result,artifactBundle:y.artifactBundle,bundleReview:y.bundleReview,selectedArtifactId:y.selectedArtifactId}}function W0(t){if(!t)return;Object.assign(y,t),new Set((y.artifactBundle?.artifacts||[]).map(n=>n.id)).has(y.selectedArtifactId)||(y.selectedArtifactId=li(y.artifactBundle)?.id||null)}const tp="results-replacement-error";function z0(t,{stage:e=2,runId:n,retry:i}){if(!re(n))return;const r=document.getElementById(tp);if(!r)return;const s=Th(t),o=document.getElementById("results-replacement-error-title"),a=document.getElementById("results-replacement-error-message"),l=document.getElementById("results-replacement-error-retry"),u=document.getElementById("results-replacement-error-upgrade");o&&(o.textContent=`${Js[e]||"Regeneration"}: ${s.title}`),a&&(a.textContent=s.message),r.hidden=!1;let c=null;u&&(u.hidden=!s.canUpgrade,s.canUpgrade&&(u.textContent="View plans",u.onclick=()=>pi(),c=u)),l&&(l.hidden=s.canUpgrade,s.canUpgrade||(l.onclick=()=>{Jl(),typeof i=="function"&&i()},l.textContent="Retry",c=l)),(c||r).focus({preventScroll:!0})}function Jl(){const t=document.getElementById(tp);t&&(t.hidden=!0)}function np(t,{previous:e,stage:n,runId:i,retry:r}){re(i)&&(t.isUsageLimit&&un(),W0(e),fr(),nn(!0),hr(),ro(),z0(t,{stage:n,runId:i,retry:r}),rn())}async function ip(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0;const e=Zs();Zl("standardRegenerate",y.step2Result,y.step1Result);const n=document.querySelectorAll(".btn-refine-action"),i=ep();n.forEach(r=>{r.disabled=!0,r.innerHTML=` - Refining...`});try{Kl();const r=Dl(),s=r.id,o=wv({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,artifactId:r.id,userFeedback:"Fix the issues listed in the audit report."});Qs({runId:e}),Ft(2,e),it(2),Ae(2,!0);const a=await Ws(o,t,[],e);if(!re(e))return;y.step2Result=a,Ds(),tn(2,e);const l=document.getElementById("step2-output"),u=ci(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),it(3),Ft(3,e),Ae(3,!0);const c=await zs(y.step2Result,y.step1Result);if(!re(e))return;y.step3Result=c,js(),tn(3,e),y.artifactBundle?.artifacts?.some(h=>h.id===s)?y.selectedArtifactId=s:y.selectedArtifactId=ai(y.artifactBundle)?.id||null;const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),ur();const f=Ns(y.step3Result);dr(u,f)}catch(r){if(console.error("Refinement failed:",r),!re(e))return;const s=Ls(r,{architect:2,generator:2,review:3});Xh(r,{previous:i,stage:s,runId:e,retry:Qh})}finally{n.forEach(r=>{r.disabled=!1,r.textContent="Refine & Regenerate"}),re(e)&&(y.isRunning=!1,rn())}}async function Yl(t,e,n){const i=`${_t}/connectFeedback`,r={type:t,code:e,input:n};try{const s=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok){const a=await s.text();return console.error(`callEndpoint failed: ${s.status} ${s.statusText}`,a),{success:!1,status:s.status,error:a}}const o=await s.json();return console.log("Telemetry success:",o),o}catch(s){return console.error("callEndpoint failed:",s),{success:!1,error:s.message}}}function H0(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function ep(){const t=document.getElementById("ff-error-paste-input"),e=t?.value?.trim();if(!e){t?.focus(),t?.classList.add("ring-2","ring-red-400","border-red-300"),setTimeout(()=>t?.classList.remove("ring-2","ring-red-400","border-red-300"),2e3);return}if(!y.step2Result){Ee("No generated code found. Please run the full pipeline first.","warning");return}if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=Ys();Yl("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` + Refining...`});try{Jl();const r=Ul(),s=r.id,o=xv({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,artifactId:r.id,userFeedback:"Fix the issues listed in the audit report."});to({runId:e}),Ft(2,e),it(2),Ae(2,!0);const a=await qs(o,t,[],e);if(!re(e))return;y.step2Result=a,Hs(),tn(2,e);const l=document.getElementById("step2-output"),u=ui(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),it(3),Ft(3,e),Ae(3,!0);const c=await Vs(y.step2Result,y.step1Result);if(!re(e))return;y.step3Result=c,Ws(),tn(3,e),y.artifactBundle?.artifacts?.some(h=>h.id===s)?y.selectedArtifactId=s:y.selectedArtifactId=li(y.artifactBundle)?.id||null;const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),fr();const f=Ds(y.step3Result);hr(u,f)}catch(r){if(console.error("Refinement failed:",r),!re(e))return;const s=Bs(r,{architect:2,generator:2,review:3});np(r,{previous:i,stage:s,runId:e,retry:ip})}finally{n.forEach(r=>{r.disabled=!1,r.textContent="Refine & Regenerate"}),re(e)&&(y.isRunning=!1,rn())}}async function Zl(t,e,n){const i=`${_t}/connectFeedback`,r={type:t,code:e,input:n};try{const s=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok){const a=await s.text();return console.error(`callEndpoint failed: ${s.status} ${s.statusText}`,a),{success:!1,status:s.status,error:a}}const o=await s.json();return console.log("Telemetry success:",o),o}catch(s){return console.error("callEndpoint failed:",s),{success:!1,error:s.message}}}function q0(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function rp(){const t=document.getElementById("ff-error-paste-input"),e=t?.value?.trim();if(!e){t?.focus(),t?.classList.add("ring-2","ring-red-400","border-red-300"),setTimeout(()=>t?.classList.remove("ring-2","ring-red-400","border-red-300"),2e3);return}if(!y.step2Result){Ee("No generated code found. Please run the full pipeline first.","warning");return}if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=Zs();Zl("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` - Fixing…`);const s=Jh();try{Kl();const o=lh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});Ap(),Qs({runId:i}),Ft(2,i),it(2),Ae(2,!0);const a=await Ws(o,n,[],i);if(!re(i))return;y.step2Result=a,Ds(),tn(2,i);const l=document.getElementById("step2-output"),u=ci(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),it(3),Ft(3,i),Ae(3,!0);const c=await zs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,js(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),ur();const f=Ns(y.step3Result);dr(u,f),t&&(t.value="")}catch(o){if(console.error("Fix from errors failed:",o),!re(i))return;const a=Ls(o,{architect:2,generator:2,review:3});Xh(o,{previous:s,stage:a,runId:i,retry:ep})}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function ar(){if(console.log("runThinkingPipeline called"),y.isRunning)return;localStorage.setItem("hasSeenWalkthrough","true");const t=document.getElementById("pipeline-input").value,e=document.getElementById("code-generator-model").value,n=Oe.slice();if(!t.trim()){Ee("Please describe your FlutterFlow widget first.","warning");return}y.isRunning=!0;const i=Ys();try{if(await Da,!re(i)||(pn.length&&await Promise.allSettled(pn.map(v=>v.job)),!re(i))||!await fw()||!re(i)||(await ow(),!re(i)))return;const r=Ka(e);t.length,b0(),y.submittedPrompt=t,y.submittedImages=n.filter(v=>v.url),Za(!0),Ga(r),On();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const o=document.getElementById("paywall-exhausted");o&&o.classList.add("hidden"),Qs({prompt:t,runId:i}),qw(),it(1),Ft(1,i),Ae(1,!0);const a=y.submittedImages.map(v=>({url:v.url})),l=await N0(t,a);if(!re(i))return;y.step1Result=l,E0(),tn(1,i);const u=document.getElementById("step1-output"),c=ci(y.step1Result);u.textContent=c,u.dataset.raw=c,Ae(1,!1),it(2),Ft(2,i),Ae(2,!0);const d=await Ws(y.step1Result,r,a,i);if(!re(i))return;y.step2Result=d,Ds(),tn(2,i);const f=document.getElementById("step2-output"),h=ci(y.step2Result);f.textContent=h,f.dataset.raw=h,Ae(2,!1),it(3),Ft(3,i),Ae(3,!0);const p=await zs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=p,js(),tn(3,i);const g=document.getElementById("step3-output");g.textContent=y.step3Result,Ae(3,!1),ur();const m=Ns(y.step3Result);Vw(),dr(h,m)}catch(r){if(r.isPipelineCancel||console.error("Pipeline failed:",r),!re(i))return;const s=Ls(r,{architect:1,generator:2,review:3});r.isUsageLimit?un():(r.message,Ka(document.getElementById("code-generator-model").value),void 0),it(s),Ae(s,!1),xp(r,{stage:s,runId:i}),Es(s,"error")}finally{re(i)&&(y.isRunning=!1,Za(!1),rn())}}function W0(){const t=document.getElementById("code-generator-model").value,e=[vs,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(i=>i!==t),n=prompt(`Retry with different model? + Fixing…`);const s=ep();try{Jl();const o=dh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});Tp(),to({runId:i}),Ft(2,i),it(2),Ae(2,!0);const a=await qs(o,n,[],i);if(!re(i))return;y.step2Result=a,Hs(),tn(2,i);const l=document.getElementById("step2-output"),u=ui(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),it(3),Ft(3,i),Ae(3,!0);const c=await Vs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,Ws(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),fr();const f=Ds(y.step3Result);hr(u,f),t&&(t.value="")}catch(o){if(console.error("Fix from errors failed:",o),!re(i))return;const a=Bs(o,{architect:2,generator:2,review:3});np(o,{previous:s,stage:a,runId:i,retry:rp})}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function lr(){if(console.log("runThinkingPipeline called"),y.isRunning)return;localStorage.setItem("hasSeenWalkthrough","true");const t=document.getElementById("pipeline-input").value,e=document.getElementById("code-generator-model").value,n=Oe.slice();if(!t.trim()){Ee("Please describe your FlutterFlow widget first.","warning");return}y.isRunning=!0;const i=Zs();try{if(await Ua,!re(i)||(pn.length&&await Promise.allSettled(pn.map(v=>v.job)),!re(i))||!await gw()||!re(i)||(await cw(),!re(i)))return;const r=Ja(e);t.length,x0(),y.submittedPrompt=t,y.submittedImages=n.filter(v=>v.url),Qa(!0),Ya(r),Nn();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const o=document.getElementById("paywall-exhausted");o&&o.classList.add("hidden"),to({prompt:t,runId:i}),Kw(),it(1),Ft(1,i),Ae(1,!0);const a=y.submittedImages.map(v=>({url:v.url})),l=await D0(t,a);if(!re(i))return;y.step1Result=l,I0(),tn(1,i);const u=document.getElementById("step1-output"),c=ui(y.step1Result);u.textContent=c,u.dataset.raw=c,Ae(1,!1),it(2),Ft(2,i),Ae(2,!0);const d=await qs(y.step1Result,r,a,i);if(!re(i))return;y.step2Result=d,Hs(),tn(2,i);const f=document.getElementById("step2-output"),h=ui(y.step2Result);f.textContent=h,f.dataset.raw=h,Ae(2,!1),it(3),Ft(3,i),Ae(3,!0);const p=await Vs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=p,Ws(),tn(3,i);const g=document.getElementById("step3-output");g.textContent=y.step3Result,Ae(3,!1),fr();const m=Ds(y.step3Result);Yw(),hr(h,m)}catch(r){if(r.isPipelineCancel||console.error("Pipeline failed:",r),!re(i))return;const s=Bs(r,{architect:1,generator:2,review:3});r.isUsageLimit?un():(r.message,Ja(document.getElementById("code-generator-model").value),void 0),it(s),Ae(s,!1),Ap(r,{stage:s,runId:i}),Is(s,"error")}finally{re(i)&&(y.isRunning=!1,Qa(!1),rn())}}function V0(){const t=document.getElementById("code-generator-model").value,e=[ws,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(i=>i!==t),n=prompt(`Retry with different model? Current: ${t} @@ -140,14 +140,14 @@ Options: 1. ${e[0]} 2. ${e[1]} -Enter 1 or 2:`);n==="1"?(document.getElementById("code-generator-model").value=e[0],ar()):n==="2"&&(document.getElementById("code-generator-model").value=e[1],ar())}async function z0(){const t=jl();if(!t){Ee("No code to commit. Please run the pipeline first.","warning");return}const e=await Te("flutterflow"),n=await Te("flutterflow_project_id");if(!e||!n){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),Ml();return}if(y.artifactBundle?.artifacts?.length>1){await q0();return}const{artifactType:i,artifactName:r,fileName:s}=qh(),o=Yh(t,{artifactType:i,artifactName:r,fileName:s}),a=P0(o);if(!a.canProceed){Ee(`Pre-commit checks failed: ${a.issues.join("; ")}`,"error");return}Xl(o,a,null,null)}async function q0(){const t=await Te("flutterflow"),e=await Te("flutterflow_project_id");if(!t||!e){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),Ml();return}const n=i_(y.artifactBundle);if(n.errors.length>0){Ee(`Bundle validation failed: ${n.errors.join("; ")}`,"error");return}const i=new Map(n.fileEntries.map(a=>[a.fileName,{content:a.content,type:a.type,path:a.path}])),r=Hs(i),s={canProceed:r.valid&&n.errors.length===0,issues:[...n.errors,...r.errors],warnings:[...n.warnings,...r.warnings]};if(!s.canProceed){Ee(`Bundle validation failed: ${s.issues.join("; ")}`,"error");return}const o={content:n.fileEntries.map(a=>`// ${a.fileName} +Enter 1 or 2:`);n==="1"?(document.getElementById("code-generator-model").value=e[0],lr()):n==="2"&&(document.getElementById("code-generator-model").value=e[1],lr())}async function G0(){const t=Hl();if(!t){Ee("No code to commit. Please run the pipeline first.","warning");return}const e=await Te("flutterflow"),n=await Te("flutterflow_project_id");if(!e||!n){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),Nl();return}if(y.artifactBundle?.artifacts?.length>1){await K0();return}const{artifactType:i,artifactName:r,fileName:s}=Yh(),o=Qh(t,{artifactType:i,artifactName:r,fileName:s}),a=T0(o);if(!a.canProceed){Ee(`Pre-commit checks failed: ${a.issues.join("; ")}`,"error");return}ec(o,a,null,null)}async function K0(){const t=await Te("flutterflow"),e=await Te("flutterflow_project_id");if(!t||!e){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),Nl();return}const n=a_(y.artifactBundle);if(n.errors.length>0){Ee(`Bundle validation failed: ${n.errors.join("; ")}`,"error");return}const i=new Map(n.fileEntries.map(a=>[a.fileName,{content:a.content,type:a.type,path:a.path}])),r=zs(i),s={canProceed:r.valid&&n.errors.length===0,issues:[...n.errors,...r.errors],warnings:[...n.warnings,...r.warnings]};if(!s.canProceed){Ee(`Bundle validation failed: ${s.issues.join("; ")}`,"error");return}const o={content:n.fileEntries.map(a=>`// ${a.fileName} ${a.content}`).join(` -`),fileName:`${n.fileEntries.length} files`,codeType:"bundle",artifactType:"Bundle",artifactName:n.title};Xl(o,s,n.dependencies,n)}function V0(t){let e=t.errorMap||new Map;!(e instanceof Map)&&typeof e=="object"&&(e=new Map(Object.entries(e)));let n=`
      +`),fileName:`${n.fileEntries.length} files`,codeType:"bundle",artifactType:"Bundle",artifactName:n.title};ec(o,s,n.dependencies,n)}function Y0(t){let e=t.errorMap||new Map;!(e instanceof Map)&&typeof e=="object"&&(e=new Map(Object.entries(e)));let n=`

      FlutterFlow Commit Failed

      ${z(t.error)}

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

      Errors:

      -
        `;for(const[r,s]of e.entries()){const o=Il(s);n+=`
      • +
          `;for(const[r,s]of e.entries()){const o=Cl(s);n+=`
        • ${z(r)}: ${z(o)}
        • `}n+="
      "}n+="
      ",n+=`
      -
      `;const i=document.getElementById("step3-output");i&&(i.innerHTML=n,document.getElementById("btn-regenerate-from-error")?.addEventListener("click",()=>{tp(t.error,e)}))}async function tp(t,e){if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=Ys(),r=document.getElementById("btn-regenerate-from-error");r&&(r.disabled=!0,r.innerHTML=` +
      `;const i=document.getElementById("step3-output");i&&(i.innerHTML=n,document.getElementById("btn-regenerate-from-error")?.addEventListener("click",()=>{sp(t.error,e)}))}async function sp(t,e){if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=Zs(),r=document.getElementById("btn-regenerate-from-error");r&&(r.disabled=!0,r.innerHTML=` Fixing...`);try{let s=`The previous code had the following errors when committing to FlutterFlow: -`;if(e&&e.size>0)for(const[h,p]of e.entries()){const g=Il(p);s+=`File: ${h} +`;if(e&&e.size>0)for(const[h,p]of e.entries()){const g=Cl(p);s+=`File: ${h} Error: ${g} `}else s+=`${t} -`;const o=lh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:s});Qs({runId:i}),Ft(2,i),it(2),Ae(2,!0);const a=await Ws(o,n,[],i);if(!re(i))return;y.step2Result=a,Ds(),tn(2,i);const l=document.getElementById("step2-output"),u=ci(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),it(3),Ft(3,i),Ae(3,!0);const c=await zs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,js(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),ur();const f=Ns(y.step3Result);dr(u,f)}catch(s){if(console.error("Regeneration failed:",s),!re(i))return;const o=Ls(s,{architect:2,generator:2,review:3});s.isUsageLimit&&un(),it(o),Ae(o,!1),xp(s,{stage:o,runId:i,retry:()=>tp(t,e)}),Es(o,"error")}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function G0(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const n=await Te("flutterflow"),i=await Te("flutterflow_project_id");n&&i?(t.className="w-2 h-2 rounded-full bg-green-500",e.textContent="FlutterFlow credentials configured",e.className="text-green-600"):n||i?(t.className="w-2 h-2 rounded-full bg-yellow-500",e.textContent="FlutterFlow credentials incomplete",e.className="text-yellow-600"):(t.className="w-2 h-2 rounded-full bg-red-500",e.textContent="FlutterFlow credentials not configured",e.className="text-red-600")}async function np(t){try{const e=await fetch(`${_t}/auth/send-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:t})});if(!e.ok)throw new Error(`Failed to send magic link: HTTP ${e.status}`);return e.json()}catch(e){throw console.error("sendMagicLink failed:",{email:t,message:e.message,stack:e.stack}),e}}async function K0(t){try{const n=await(await fetch(`${_t}/auth/verify-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})})).json();if(n.error||!n.email||!n.sessionToken)throw new Error(n.error||"Invalid or expired link");return n}catch(e){throw console.error("verifyMagicLink failed:",{message:e.message,stack:e.stack}),e}}async function Y0(t){try{const e=await fetch(`${_t}/auth/refresh-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:t})});if(!e.ok)return console.error("refreshSession: non-OK response",{url:`${_t}/auth/refresh-session`,status:e.status}),null;const n=await e.json();return n.error||!n.email||!n.sessionToken?(console.warn("refreshSession: validation failed",{error:n.error,hasEmail:!!n.email,hasToken:!!n.sessionToken}),null):n}catch(e){return console.error("refreshSession: fetch failed",{url:`${_t}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function ad(t,e){const n=rp(),i=(q.email||n.email)!==t;q.email=t,q.sessionToken=e,q.isVerified=!0,ce=Ln({isLoading:!0}),localStorage.setItem(ps,JSON.stringify({email:t,sessionToken:e})),i&&up()}function ip(){q.email=null,q.sessionToken=null,q.isVerified=!1,ce=Ln({isResolved:!0}),localStorage.removeItem(ps),localStorage.removeItem(ms)}function rp(){try{const t=localStorage.getItem(ps);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(ps),{email:null,sessionToken:null}}}async function J0(){const e=new URLSearchParams(window.location.search).get("token");if(e){window.history.replaceState({},"",window.location.pathname+window.location.hash);try{const{email:n,sessionToken:i}=await K0(e);ad(n,i),sp();const r=ld();r&&!window.location.hash&&(window.location.hash=r)}catch(n){ld();const i=n.message||"Sign-in link invalid or expired.";Ee(i,"error"),qs(),Zn(i,"error")}}else{const{email:n,sessionToken:i}=rp();if(n&&i){const r=await Y0(i);r?ad(r.email,r.sessionToken):ip()}}Jl()}function Z0(){try{localStorage.setItem(Ba,JSON.stringify({hash:window.location.hash||"#home",ts:Date.now()}))}catch(t){console.warn("rememberSignInReturnSurface: failed to persist return surface:",t)}}function ld(){try{const t=localStorage.getItem(Ba);if(localStorage.removeItem(Ba),!t)return null;const{hash:e,ts:n}=JSON.parse(t);return!e||typeof n!="number"||Date.now()-n>Ry?null:e}catch(t){return console.warn("consumeSignInReturnSurface: failed to read return surface:",t),null}}function qs(){const t=document.getElementById("signin-modal");if(!t)return;Z0(),document.getElementById("signin-email-input")?.removeAttribute("aria-invalid"),Zn(""),We(t)}function sp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&ze(e)}function Zn(t,e){const n=document.getElementById("signin-message");n&&(n.textContent=t||"",n.classList.remove("signin-message-success","signin-message-error"),e&&n.classList.add(`signin-message-${e}`))}async function X0(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),n=Rs(t?.value);if(!n||!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(n)||n.length>254){t?.setAttribute("aria-invalid","true"),Zn("Please enter a valid email address.","error");return}t?.removeAttribute("aria-invalid"),e&&(e.disabled=!0,e.textContent="Sending…");const r=mh(n);r&&Zn(r,"error");try{const s=await np(n),o=s?.code===gh;t&&!o&&(t.value=""),t?.setAttribute("aria-invalid",String(o)),Zn(vh(s,n),o?"error":"success"),e&&(e.disabled=!1,e.textContent=o?"Send Sign-in Link":"Sent!",o||setTimeout(()=>{e.textContent==="Sent!"&&(e.textContent="Send Sign-in Link")},2500))}catch(s){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:n,err:s}),Zn("Something went wrong. Please try again.","error"),e&&(e.disabled=!1,e.textContent="Send Sign-in Link")}}function Q0(){q.email=null,q.sessionToken=null,q.isVerified=!1,ce=Ln({isResolved:!0}),j_({storage:window.localStorage,onIdentityChanged:Jl,onPlanChanged:Gs})}const ew=U_({sendLink:np,getEmail:()=>q.email||"",onState:tw});function tw(t){const e=document.getElementById("send-new-link-btn"),n=document.getElementById("send-new-link-msg");if(!e||!n)return;if(t.status==="pending"){e.disabled=!0,e.textContent="Sending…",n.className="acct-access-msg",n.textContent="Sending a fresh sign-in link…";return}if(t.status==="sent"){e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg",n.textContent=vh(t.data,q.email||"")||"Link sent — check your email.";return}e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg error";const i=t.error?.message?`Couldn't send a link right now. ${t.error.message}`:"Couldn't send a link right now. Please try again.";n.textContent=i}async function nw(){await ew()}function iw(){const t=B_(window.localStorage),e=t.length?`Cleared disposable UI caches: ${t.join(", ")}.`:"Nothing disposable to clear.";Ee(`${e} Your run count, identity and stored keys are kept.`,"info")}function rw(){const t=document.getElementById("delete-unavailable-modal");t&&We(t,{trigger:document.activeElement})}function sw(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("delete-unavailable-modal");e&&ze(e)}function Jl(){const t=q.isVerified&&!!q.email,e=document.getElementById("auth-signedout"),n=document.getElementById("auth-signedin"),i=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),n&&n.classList.toggle("hidden",!t),i&&i.classList.toggle("hidden",t);const r=document.getElementById("auth-user-email");r&&(r.textContent=q.email||"");const s=document.getElementById("access-signed-email");s&&(s.textContent=q.email||""),gw(),Gs()}async function op(){try{if(typeof FingerprintJS>"u"){console.warn("resolveIdentity: FingerprintJS not loaded, skipping");return}const e=await(await FingerprintJS.load()).get(),n=e.visitorId,i=await fetch(Ly,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fingerprint:e.visitorId,cookie_id:n})});if(!i.ok)throw new Error(`Identity check HTTP ${i.status}`);const r=await i.json();if(ht.userId=r.user_id,ht.token=r.identity_token||null,ht.status=r.status,ht.resolved=!0,sessionStorage.setItem($y,r.user_id),ht.token&&sessionStorage.setItem(My,ht.token),r.usage_count!==void 0){const s=gn(),a=(r.usage_month||s)===s?r.usage_count:0;localStorage.setItem(Fn,JSON.stringify({count:a,month:s})),un()}console.log(`Identity resolved: ${r.status} (${r.user_id.slice(0,8)}...) usage: ${r.usage_count??"n/a"}`)}catch(t){console.error("resolveIdentity failed:",t)}}let qo=null;function ow(t=5e3){return ht.resolved?Promise.resolve():(qo||(qo=op().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([qo,new Promise(e=>setTimeout(e,t))]))}function ap(){const t=gn();try{const e=localStorage.getItem(Fn);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Fn,month:t,err:e}),localStorage.removeItem(Fn),{count:0,month:t}}}function gn(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function cr(){const t=ap();return t.month!==gn()?{count:0,month:gn()}:t}function aw(){const e={count:cr().count+1,month:gn()};return localStorage.setItem(Fn,JSON.stringify(e)),e}function gi(){return!!ce.isLoading}function Tt(){return!!ce.isResolved}function lw(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(gs,e)?e:null}function cw(t){return t&&Object.entries(Fh).find(([,e])=>e===t)?.[0]||null}function Ar(...t){return t.find(e=>e!=null&&e!=="")}function uw(...t){return t.find(e=>e&&typeof e=="object")||{}}function dw(t){const e=t.data&&typeof t.data=="object"?t.data:t,n=uw(e.subscription,e.stripeSubscription,e.currentSubscription,e.customer?.subscriptions?.data?.[0],e.subscriptions?.data?.[0],e.subscriptions?.[0]),i=e.metadata||n.metadata||e.customer?.metadata||{},r=Ar(e.priceId,e.price_id,e.stripePriceId,e.stripe_price_id,n.priceId,n.price_id,n.plan?.id,n.price?.id,n.items?.data?.[0]?.price?.id,n.items?.[0]?.price?.id,n.lines?.data?.[0]?.price?.id),s=Ar(e.status,e.subscriptionStatus,e.subscription_status,n.status,"none"),o=lw(Ar(e.tier,e.plan,e.planId,e.plan_id,e.subscriptionTier,e.subscription_tier,e.product,e.productName,n.tier,n.plan,i.tier,i.plan)),a=Ny.has(String(s).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||cw(r)||(a||l?"professional":"free");return Ln({tier:u,status:s,periodEnd:Ar(e.periodEnd,e.currentPeriodEnd,e.current_period_end,n.current_period_end,n.periodEnd,null),isResolved:!0})}function Vs(){return gs[ce.tier]??gs.free}async function fw(){if(q.isVerified&&(!Tt()||gi())&&(await cp({force:!0}),Gs()),q.isVerified&&!Tt())return Ee("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=cr(),e=Vs();if(t>=e)return lp(t,e,{openModal:!0}),!1;const n=Math.floor(e*.8);if(t>=n){const i=e-t;Ee(`${i} run${i===1?"":"s"} remaining this month.`,"warning")}return!0}function cd(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function lp(t,e,n={}){nn(!0);const i=document.getElementById("walkthrough-modal");i&&ze(i,{restoreFocus:!1});const r=document.getElementById("ready-state");r&&r.classList.add("hidden");const s=document.getElementById("preview-frame-container");s&&(s.style.display="none");const o=document.getElementById("main-stage-container");o&&o.classList.add("visible");const a=document.getElementById("results-view");a&&a.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar");const l=document.getElementById("pipeline-progress");l&&l.classList.remove("visible");const u=document.getElementById("paywall-exhausted");if(!u){Ee(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),fi();return}const c=document.getElementById("paywall-exhausted-text");if(c){const f=ce.tier;f==="free"?c.textContent=`You've used all ${e} free generations this month. Upgrade to Pro for 50 generations/month and access to all AI models.`:c.textContent=`You've used all ${e} generations this month on your ${f} plan. Your limit resets next month.`}const d=document.getElementById("paywall-signin-btn");d&&d.classList.toggle("hidden",q.isVerified),u.classList.remove("hidden"),n.openModal&&fi()}function Ka(t){return ce.tier==="free"&&Or.includes(t)?vs:t}function hw(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const n=ce.tier,r=!(q.isVerified&&!Tt())&&n==="free";Array.from(e.options).forEach(o=>{const a=Gt(o.value),l=Or.includes(o.value);o.textContent=l&&r?`${a} (PRO)`:a,o.disabled=!1}),r&&Or.includes(e.value)&&(e.value=vs),e.disabled=!1,Ju.has(e)||(e.addEventListener("change",()=>{Tt()&&ce.tier==="free"&&Or.includes(e.value)&&(e.value=vs,fi()),Ga(e.value),Pl()}),Ju.add(e));let s=document.getElementById("model-selector-free-notice");r?(s||(s=document.createElement("p"),s.id="model-selector-free-notice",s.className="text-xs text-gray-400 mt-1",t.appendChild(s)),s.innerHTML='Free plan — Gemini only. '):s&&s.remove(),Ga(e.value)}function Zl(){const t=q.isVerified&&!!q.email,e=t&&gi(),n=!t||Tt(),i=cr(),r=n?i.count:0,s=n?Vs():0,o=Math.max(0,s-r),a=`${r} / ${s} runs this month`,l=_l,u=n?ce.tier||"free":null,c=document.getElementById("topbar-credits-count");c&&(e?c.textContent="…":n?c.textContent=String(o):c.textContent="—");const d=document.getElementById("credits-balance");d&&(e?d.textContent="Checking plan…":n?d.textContent=a:d.textContent="Plan check failed");const f=document.getElementById("usage-dialog-tier");f&&(e?f.textContent="Checking…":n?f.textContent=l[u]||"Free":f.textContent="Unavailable");const h=document.getElementById("usage-dialog-status");h&&(e?h.textContent="Verifying your subscription…":n?h.textContent="Runs reset at the start of each month.":h.textContent="Could not verify your subscription. Try again or sign out.");const p=document.getElementById("usage-counter");if(p)if(e&&t)p.textContent="Checking plan…",p.className="text-xs text-gray-500";else if(!n&&t)p.textContent="Plan check failed",p.className="text-xs text-red-600 font-medium";else{p.textContent=a;const g=s>0?r/s:0;p.className=g>=1?"text-xs text-red-600 font-medium":g>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500"}if(!t){const g=document.getElementById("guest-usage-text");if(g){const m=ap(),v=m.month===gn()?m.count??0:0;g.textContent=`${v} / ${gs.free} generations used`}}pw()}function pw(){if(!(q.isVerified&&!!q.email))return;const e=gi(),n=Tt(),i=cr(),r=n?i.count:0,s=n?Vs():0,o=Math.max(0,s-r),a=n?ce.tier||"free":null,l={free:"Free",professional:"Pro",power:"Power"}[a]||"Free",u=q.email||"",c=u.split("@")[0]||u,d=document.getElementById("acct-avatar");d&&(d.textContent=(u[0]||"?").toUpperCase());const f=document.getElementById("acct-name");f&&(f.textContent=c||"—");const h=document.getElementById("acct-plan-tier"),p=document.getElementById("acct-plan-price"),g=document.getElementById("acct-plan-note"),m=document.getElementById("acct-renewal");if(h&&(h.textContent=e?"Checking…":n?l:"Plan unavailable"),p)if(e)p.textContent="—";else if(!n)p.textContent="—";else if(a==="free")p.textContent="$0 / month";else{const x=Bi(Oi[a]??0,Fl());p.textContent=`${x} / month`}if(g&&(e?g.textContent="Verifying your subscription…":n?a==="free"?g.textContent="No subscription. Upgrade for more generations.":g.textContent="billed monthly through Stripe":g.textContent="Could not verify your subscription. Check billing or sign out."),m){const x=Date.parse(ce.periodEnd||""),F=n&&a!=="free"&&!!ce.periodEnd&&!Number.isNaN(x);if(e)m.textContent="";else if(!n)m.textContent="";else if(a==="free")m.textContent="";else if(F){const $=new Date(x).toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"});m.textContent=`Renews ${$} · reset at the start of each month.`}else m.textContent="Renewal date is not available for this period."}const v=document.getElementById("acct-left-count"),E=document.getElementById("acct-left-limit"),S=document.getElementById("acct-reset-note");v&&(v.textContent=e?"…":n?String(o):"—"),E&&(E.textContent=e?"…":n?String(s):"—"),S&&(e?S.textContent="Checking plan…":n?S.textContent="Runs reset at the start of each month.":S.textContent="Plan check failed. Refresh or manage billing.");const _=document.getElementById("acct-used-count"),b=document.getElementById("acct-meter-fill"),k=document.getElementById("acct-meter-meta"),T=document.getElementById("acct-meter-track");if(_&&(_.textContent=e?"…":n?String(r):"—"),b){const x=n&&s>0?Math.min(100,Math.round(r/s*100)):0;b.style.width=`${x}%`}if(k)if(e)k.textContent="Checking…";else if(!n)k.textContent="Plan check failed";else if(s===0)k.textContent=`${r} of ${s}`;else{const x=Math.round(r/s*100);k.textContent=`${r} of ${s} · ${x}%`}T&&(e?T.setAttribute("aria-label","Checking usage…"):n?T.setAttribute("aria-label",`${r} of ${s} generations used`):T.setAttribute("aria-label","Usage unavailable")),vt()}function un(){if(Zl(),q.isVerified&&(gi()||!Tt())){cd();return}const{count:t}=cr(),e=Vs();t>=e&&!y.isRunning?lp(t,e):cd()}function gw(){Zl()}async function cp(t={}){const e=t.force===!0;if(!q.isVerified||!q.sessionToken){ce=Ln({isResolved:!0});return}ce={...ce,isLoading:!0,error:null};const n=localStorage.getItem(ms);if(!e&&n)try{const{data:i,email:r,ts:s,version:o}=JSON.parse(n);if(o===Zu&&r===q.email&&Date.now()-s<300*1e3){ce={...i,isLoading:!1,isResolved:i.isResolved!==!1};return}}catch(i){console.warn("Failed to parse subscription cache:",i,"| raw value:",n)}try{const r=await(await fetch(`${_t}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:q.sessionToken,user_id:ht.userId})})).json();if(r.error){if(["unauthorized","invalid session","expired session"].some(o=>String(r.error).toLowerCase().includes(o))){ip(),Jl();return}ce=Ln({isResolved:!1,error:r.error});return}ce=dw(r),localStorage.setItem(ms,JSON.stringify({version:Zu,data:ce,email:q.email,ts:Date.now()}))}catch(i){console.error("fetchSubscription failed:",i),ce={...ce,isLoading:!1,isResolved:!1,error:i.message}}}function up(){localStorage.removeItem(ms)}async function mw(t){if(!q.isVerified||!q.sessionToken){dp(),qs();return}if(!Fh[t]){Ee("Invalid plan selected.","error");return}const e=document.getElementById(`checkout-btn-${t}`);e&&(e.disabled=!0,e.textContent="Redirecting…");try{const i=await(await fetch(`${_t}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:q.sessionToken,currency:Fl()})})).json();if(i.error||!i.url)throw new Error(i.error||"Failed to create checkout session");const{url:r}=i;window.location.href=r}catch(n){console.error("startCheckout failed:",n),e&&(e.disabled=!1,e.textContent="Subscribe"),Ee("Could not start checkout. Please try again.","error")}}async function vw(t){if(!q.isVerified||!q.sessionToken){qs();return}const e=t||document.getElementById("manage-billing-btn"),n=e?e.textContent:"";e&&(e.disabled=!0,e.textContent="Loading…");try{const r=await(await fetch(`${_t}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:q.sessionToken})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to open billing portal");const{url:s}=r;window.location.href=s}catch(i){console.error("openCustomerPortal failed:",i),e&&(e.disabled=!1,e.textContent=n),Ee("Could not open billing portal. Please try again.","error")}}const Ss=new Set;function _w(){Ss.forEach(t=>t.abort()),Ss.clear()}async function xs(t,e,n,i={},r=[]){const o=new AbortController;Ss.add(o);let a=!1;const l=setTimeout(()=>{a=!0,o.abort()},12e4);try{const u=await fetch(Ty,{method:"POST",headers:{"Content-Type":"application/json",...ht.token?{Authorization:`Bearer ${ht.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:ht.userId,step:t,model:e,prompt:n,images:r,context:i})}),c=await u.text();let d={};try{d=c?JSON.parse(c):{}}catch{d={}}if(u.status===429){d.serverCount!==void 0&&(localStorage.setItem(Fn,JSON.stringify({count:d.serverCount,month:gn()})),un());const p=new Error(d.message||"Monthly usage limit reached. Upgrade to continue.");throw p.isUsageLimit=!0,p.pipelineStep=t,p}const f=Cv(d,t);if(f)throw f;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(d),"content type:",typeof d.content),!u.ok)throw new Error(`${d.message||d.error||"BuildShip pipeline error"} (HTTP ${u.status})`);if(t==="generator")if(d.usage_status==="success"&&Number.isFinite(d.usage_count)){const p=gn();(d.usage_month||p)===p&&(localStorage.setItem(Fn,JSON.stringify({count:d.usage_count,month:p})),un())}else aw(),un();let h=d.output||d.content;if(!h){const p=c?` (body: ${c.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${p}`)}return Array.isArray(h)&&(h=h.map(p=>typeof p=="string"?p:p.text||"").join("")),typeof h!="string"&&(h=JSON.stringify(h)),h}catch(u){if(u.name==="AbortError"){if(a)throw new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`);const c=new Error(`BuildShip ${t} request cancelled`);throw c.isPipelineCancel=!0,c}throw u instanceof TypeError?new Error(`BuildShip unreachable: ${u.message}`):u}finally{clearTimeout(l),Ss.delete(o)}}let Ya=!1;function yw(){const e=new URLSearchParams(window.location.search).get("checkout");return e==="success"?(window.history.replaceState({},"",window.location.pathname+window.location.hash),up(),Ya=!0):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname+window.location.hash),Ee("Checkout cancelled.","info")),e}function ww(){if(!Ya)return;Ya=!1;const t=ce.tier!=="free";Ee(t?"Subscription active! Your plan is live.":"Checkout complete — confirming your subscription. Check Manage billing if it does not update.",t?"success":"info")}function Gs(){const t=q.isVerified&&!!q.email,e=ce.tier,n=t&&gi(),i=!t||Tt(),r=document.getElementById("subscription-tier-badge");if(r){const a=_l,l={free:"bg-gray-100 text-gray-600",professional:"bg-indigo-100 text-indigo-700",power:"bg-purple-100 text-purple-700",unresolved:"bg-red-50 text-red-600"};r.textContent=n?"Checking…":i?a[e]||"Free":"Plan unavailable",r.className=`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${i?l[e]||l.free:l.unresolved}`}const s=document.getElementById("upgrade-prompt");s&&s.classList.toggle("hidden",!t||n||!i||e!=="free");const o=document.getElementById("manage-billing-btn");o&&o.classList.toggle("hidden",!t||n||i&&e==="free"),bw(i?e:null),hw(),Pl(),un(),Pp()}function bw(t){const e=["bg-gray-100","text-gray-500","cursor-default"];Object.entries({professional:{btnId:"checkout-btn-professional",defaultText:"Subscribe"},power:{btnId:"checkout-btn-power",defaultText:"Subscribe"}}).forEach(([r,{btnId:s,defaultText:o}])=>{const a=document.getElementById(s);a&&(r===t?(a.disabled=!0,a.textContent="Current plan",a.classList.add(...e)):(a.disabled=!1,a.textContent=o,a.classList.remove(...e)))});const i=document.getElementById("free-tier-current");i&&i.classList.toggle("hidden",t!=="free")}function Ew(){document.querySelectorAll(".pm-card[data-tier]").forEach(t=>{const e=t.dataset.tier,n=pv[e];if(!n)return;const i=t.querySelector("ul.pm-features");if(i){i.innerHTML="";for(const r of n){const s=document.createElement("li");s.textContent=r,i.appendChild(s)}}})}function Ja(){const t=Fl(),e=document.getElementById("pro-price"),n=document.getElementById("power-price"),i=document.getElementById("plans-pro-price"),r=document.getElementById("plans-power-price"),s=document.getElementById("pro-price-note"),o=document.getElementById("power-price-note"),a=document.getElementById("plans-pro-price-note"),l=document.getElementById("plans-power-price-note");e&&(e.textContent=Bi(Oi.professional,t)),n&&(n.textContent=Bi(Oi.power,t)),i&&(i.textContent=Bi(Oi.professional,t)),r&&(r.textContent=Bi(Oi.power,t));const u="billed monthly";s&&(s.textContent=u),o&&(o.textContent=u),a&&(a.textContent=u),l&&(l.textContent=u)}function fi(){Ja();const t=document.getElementById("pricing-modal");t&&We(t),Gy().then(()=>Ja())}function dp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&ze(e)}function Ee(t,e="info"){const n={success:"bg-green-600 text-white",error:"bg-red-600 text-white",warning:"bg-amber-500 text-white",info:"bg-gray-800 text-white"},i=document.createElement("div");i.className=`fixed bottom-6 left-1/2 -translate-x-1/2 px-5 py-3 rounded-lg text-sm font-medium shadow-lg z-50 transition-opacity duration-300 ${n[e]||n.info}`,i.textContent=t,document.body.appendChild(i),setTimeout(()=>{i.style.opacity="0",setTimeout(()=>i.remove(),300)},3500)}document.addEventListener("DOMContentLoaded",async()=>{dv(),hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),Sw(),window.__heroField=ry(),window.__pipelineLogo=ly(),Th=Py({onSubmit:ar}),Da=(async()=>{try{await J0(),yw(),await cp()}catch(n){console.warn("Startup auth/subscription initialization failed:",n)}})(),await Da,ww(),Gs(),Ja(),Ew(),await S0(),_0();const t=document.getElementById("flutterflow-endpoint-select");if(t){const n=yt();t.value=n}zh(),op();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{en===2&&e.value.trim().length>0&&(Ll(),Os())}),e.addEventListener("blur",()=>{const n=document.getElementById("walkthrough-modal");en===2&&n&&We(n)}),e.addEventListener("keydown",n=>{if(n.key==="Tab"){const i=document.getElementById("walkthrough-modal");en===2&&i&&setTimeout(()=>{We(i)},100)}})),window.addEventListener("commitStateChange",n=>{const{state:i}=n.detail;i===ee.PREPARING||i===ee.VALIDATING||i===ee.PUSHING?(Be.phaseId||vp(),dd(i)):(i===ee.SUCCESS||i===ee.ERROR)&&(dd(i),setTimeout(ec,1e3))}),ac()});function Sw(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function xw(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",On),document.addEventListener("keydown",On))}function On(){const t=document.getElementById("preview-frame-container"),e=document.getElementById("main-stage-container"),n=document.getElementById("ready-state");t&&(t.style.display="none"),e&&e.classList.add("visible"),n&&n.classList.remove("hidden");const i=document.getElementById("welcome-video-player");i&&i.removeEventListener("click",On),document.removeEventListener("keydown",On),zh()}let Vi=null;async function Iw(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++nd,n=()=>e===nd,i=await Te("flutterflow"),r=await Te("flutterflow_project_id");if(n()){if(!i){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const o=await new pi(i,"","main",yt()).listProjects();if(!n())return;if(!o||o.length===0){t.innerHTML='';return}t.innerHTML='',o.forEach(a=>{const l=document.createElement("option");l.value=a.id||a.projectId||"",l.textContent=a.name||a.projectName||`Project ${a.id}`,t.appendChild(l)}),r&&(t.value=r)}catch(s){if(!n())return;console.error("Failed to load projects for deploy:",s),t.innerHTML=''}}}function kw(){return document.getElementById("confirm-project-select")?.value?.trim()||null}function Xl(t,e,n,i=null){Vi={codeInfo:t,checks:e,deps:n,bundlePlan:i},document.getElementById("confirm-file-name").textContent=t.fileName,document.getElementById("confirm-artifact-type").textContent=t.artifactType,document.getElementById("confirm-file-size").textContent=`${(t.content.length/1024).toFixed(1)} KB`,document.getElementById("confirm-line-count").textContent=i?`${i.fileEntries.length} files`:t.content.split(` -`).length,Iw();const r=document.getElementById("confirm-deps-list"),s=document.getElementById("confirm-deps-section");n&&Object.keys(n).length>0?(r.innerHTML=Object.entries(n).map(([u,c])=>{const d=c?`at least ${Qt(c)}`:"version resolved from your project";return`
    • • ${Qt(u)}: ${d}
    • `}).join(""),s.classList.remove("hidden")):s.classList.add("hidden");const o=document.getElementById("confirm-warnings-list"),a=document.getElementById("confirm-warnings-section");e.warnings&&e.warnings.length>0?(o.innerHTML=e.warnings.map(u=>`
    • • ${Qt(u)}
    • `).join(""),a.classList.remove("hidden")):a.classList.add("hidden"),document.getElementById("confirm-code-preview").textContent=t.content,document.getElementById("code-preview-content").classList.add("hidden"),document.getElementById("code-preview-chevron").style.transform="rotate(0deg)";const l=document.getElementById("commit-confirm-modal");l&&We(l)}function fp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&ze(e),Vi=null}function Cw(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&ze(e);const n=["success-message","success-project-id","success-file-name","success-artifact-type","success-time","success-size"];for(const s of n){const o=document.getElementById(s);o&&(o.textContent="")}const i=document.getElementById("success-warnings-section");i&&i.classList.add("hidden");const r=document.getElementById("success-warnings-list");r&&(r.innerHTML="")}function hp(t){const e=(m,v)=>{const E=document.getElementById(m);E&&(E.textContent=v||"")},n=t.metadata?.fileName||"",i=t.metadata?.projectId||"",r=t.metadata?.artifactType||"",s=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",i),e("success-file-name",n),e("success-artifact-type",r),e("success-time",s),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&i&&(u.href=`https://app.flutterflow.io/project/${i}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),f=t.unverified||[],h=t.approximate||[],p=t.warnings||[];(p.length>0||f.length>0||h.length>0)&&c&&d&&(d.innerHTML=[...f.map(m=>`
    • Not verified before deploying: ${z(String(m))}
    • `),...h.map(m=>`
    • Verified approximately: ${z(String(m))}
    • `),...p.map(([m,v])=>`
    • ${z(m)}: ${z(String(v))}
    • `)].join(""),c.classList.remove("hidden"));const g=document.getElementById("commit-success-modal");g&&We(g)}function pp(t){ec(),V0(t);const e=t.remoteRefusal===!0;Ql(t,{heading:"Deploy failed",title:e?"FlutterFlow refused this deploy — nothing was confirmed written.":"The deploy failed before FlutterFlow confirmed anything.",guidance:e?"Review the error and any per-file outcomes above, fix them in your code or in FlutterFlow, then deploy again. A refusal is definitive: no part of this deploy was applied, so retrying is safe once the problem is fixed.":"Review the error above, fix it, then deploy again. The deploy stopped before a write was confirmed, so nothing was applied."})}function Ql(t,{heading:e,title:n,guidance:i}){const r=t.targetIdentity||{},s=document.getElementById("commit-terminal-modal");if(!s)return!1;const o=(h,p)=>{const g=document.getElementById(h);g&&(g.textContent=p||"")};o("terminal-heading",e),o("terminal-title",n),o("terminal-message",t.error||t.message||"");const a=document.getElementById("terminal-identity-list");if(a){const h=[["Project",r.projectId||t.metadata?.projectId],["Endpoint",r.endpoint],["File",r.fileName||t.metadata?.fileName],["Artifact",r.artifactType||t.metadata?.artifactType]];a.innerHTML=h.map(([p,g])=>`
      ${z(p)}:${z(String(g??"—"))}
      `).join("")}const l=document.getElementById("terminal-file-outcomes");let u=t.errorMap;u&&!(u instanceof Map)&&(u=new Map(Object.entries(u))),l&&u&&u.size>0?(l.innerHTML=[...u.entries()].map(([h,p])=>`
    • ${z(h)}: ${z(Il(p))}
    • `).join(""),l.classList.remove("hidden")):l&&l.classList.add("hidden");const c=document.getElementById("terminal-guidance");c&&(c.innerHTML=i);const d=document.getElementById("terminal-open-ff-link"),f=r.projectId||t.metadata?.projectId;return d&&(d.href=f?`https://app.flutterflow.io/project/${f}`:"https://app.flutterflow.io/"),We(s),!0}function gp(t){Ql(t,{heading:"Deploy partially applied",title:"Some custom classes reached FlutterFlow, but the deploy did not fully complete.",guidance:"The custom classes the runner confirmed are already in your project and are not lost. Review the per-file errors above, fix them in FlutterFlow or regenerate, then deploy again. Open the project to see exactly what landed."})}function mp(t){Ql(t,{heading:"Deploy outcome not yet known",title:"This browser stopped waiting before the FlutterFlow server reported a result.",guidance:"The deploy may still be finishing on the server — it was not cancelled. Open your FlutterFlow project and confirm whether the class landed before retrying, so you do not push a duplicate or build on top of an unknown state."})}function Aw(t){t&&t.target!==t.currentTarget||ze(document.getElementById("commit-terminal-modal"))}function Pw(){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 ud={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}},Fw=[{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&&(ku(e,!0,"Deploying to FlutterFlow"),We(e)),this.set("prepare")},set(t,e=null){if(!(!ud[t]||t===this.phaseId)){if(!this.sequence.includes(t)){const n=this.sequence.indexOf("package");this.sequence.splice(n===-1?this.sequence.length:n,0,t)}this.phaseId=t,this.phaseStartedAt=Date.now(),this.substatus=e,this.liveSubstatus=!1,this.render(),this.timer&&clearInterval(this.timer),t!=="done"&&(this.timer=setInterval(()=>this.render(),500))}},setSubstatus(t){t&&(this.liveSubstatus=!0,this.substatus=t,this.render())},render(){const t=ud[this.phaseId];if(!t)return;const e=(Date.now()-this.phaseStartedAt)/1e3,n=t.start+(t.end-t.start)*(1-Math.exp(-e/25));if(this.phaseId==="provision"&&!this.liveSubstatus){const o=Fw.filter(a=>e>=a.after).pop();o&&(this.substatus=o.text)}const i=this.sequence.indexOf(this.phaseId),s=[`Step ${i===-1?1:i+1} of ${this.sequence.length}`];e>=5&&s.push(Rw(e)),_p(this.phaseId==="done"?100:n,t.message,s.join(" · "),this.substatus)},stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.phaseId=null;const t=document.getElementById("commit-progress-overlay");t&&(ku(t,!1),ze(t,{force:!0,restoreFocus:!1}))}};function Rw(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 vp(t){Be.start(t)}function ec(){Be.stop()}function _p(t,e,n,i=null){const r=document.getElementById("commit-progress-bar"),s=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");r&&(r.style.width=`${Math.round(t*10)/10}%`),s&&(s.textContent=e),o&&(o.textContent=n),a&&(a.textContent=i||"",a.classList.toggle("hidden",!i))}function dd(t){const e={[ee.PREPARING]:"prepare",[ee.VALIDATING]:"validate",[ee.PUSHING]:"project",[ee.SUCCESS]:"done"};if(t===ee.ERROR){Be.timer&&clearInterval(Be.timer),Be.timer=null,_p(100,"Failed","Error occurred");return}const n=e[t];n&&Be.set(n)}function Tw(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===J.CODE_FILE):t.codeInfo?.codeType===J.CODE_FILE}let yp=!1;function wp(t){yp=t;const e=document.querySelector("#commit-confirm-modal button[data-deploy-confirm]");e&&(e.disabled=t),[...document.querySelectorAll("[data-deploy-start]"),...document.querySelectorAll("#btn-deploy-to-ff")].forEach(i=>{i.disabled=t})}function fd(t){ec(),wp(!1);const e=kh(t);e===Le.COMMITTED?hp(t):e===Le.PARTIAL?gp(t):e===Le.UNCONFIRMED?mp(t):pp(t)}async function $w(){if(!Vi){console.error("No pending commit data");return}if(yp){console.warn("Deploy already in flight; ignoring duplicate confirm.");return}const t=Vi;if(Vi=null,qi=kw(),fp(),wp(!0),vp({withProvisioning:Tw(t)}),t.bundlePlan){const o=await L0(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});qi=null,fd(o);return}const{codeInfo:e}=t,{artifactType:n,artifactName:i,fileName:r}=qh(),s=await M0(e.content,{artifactType:n,artifactName:i,fileName:r,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});qi=null,fd(s)}window.runThinkingPipeline=ar;window.toggleStep=B0;window.toggleSection=O0;window.selectWorkflowStep=it;window.copyCode=D0;window.retryWithDifferentModel=W0;window.openApiKeysModal=Ml;window.closeApiKeysModal=Hh;window.openComposerSettings=a0;window.closeComposerSettings=l0;window.walkthroughConnectAccount=o0;window.closeWalkthroughModal=u0;window.openWalkthroughModal=c0;window.advanceWalkthrough=Ll;window.commitToFlutterFlow=$0;function Mw(){const t=document.getElementById("pipeline-input");t&&t.focus()}function Lw(){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=Mw;window.openModelSelector=Lw;window.handlePromptImageSelect=qy;window.removePromptImage=Vy;window.saveApiKeys=h0;window.validateFlutterFlowConnection=Ol;window.clearAllApiKeys=p0;window.toggleKeyVisibility=w0;window.handleWelcomeVideoEnd=xw;window.dismissWelcomeVideo=On;window.initiateCommitToFlutterFlow=z0;window.updateFlutterFlowCredentialStatus=G0;window.openCommitConfirmModal=Xl;window.closeCommitConfirmModal=fp;window.closeCommitSuccessModal=Cw;window.closeCommitTerminalModal=Aw;window.showCommitPartialModal=gp;window.showCommitUnconfirmedModal=mp;window.showCommitSuccessModal=hp;window.showCommitFailureModal=pp;window.toggleCodePreview=Pw;window.confirmCommitToFlutterFlow=$w;window.runRefinement=Qh;window.regenerateFromPastedErrors=ep;window.clearErrorInput=H0;window.setFlutterFlowEndpoint=s0;window.getFlutterFlowEndpoint=yt;window.commitProgress=Be;window.openSignInModal=qs;window.closeSignInModal=sp;window.handleMagicLinkRequest=X0;window.handleSignOut=Q0;window.handleSendNewLink=nw;window.handleClearCache=iw;window.handleDeleteAccount=rw;window.closeDeleteUnavailableModal=sw;window.startCheckout=mw;window.openCustomerPortal=vw;window.openPricingModal=fi;window.closePricingModal=dp;let Ur=null,bp=null,Bn={1:"pending",2:"pending",3:"pending"},tc=1,nc=null;const Ks={1:"Prompt Architect",2:"Code Generator",3:"Code Review"},Nw={1:"Understanding your prompt",2:"Generating Dart code",3:"Running the code audit"},Ow={1:"Prompt understood",2:"Dart code generated",3:"Code audit complete"};function Ys(){return y.runId+=1,y.runId}function re(t){return t===void 0||t===y.runId}function Bw(){y.runId+=1}function ic(t){return document.getElementById(`pdot-${t}`)}function Za(t){const e=document.getElementById("btn-run-pipeline")||document.getElementById("hero-send");e&&(e.disabled=t,e.classList.toggle("is-busy",t),t?e.setAttribute("aria-busy","true"):e.removeAttribute("aria-busy"))}function Js(t){const e=document.getElementById("pipeline-progress");e&&(e.dataset.runState=t)}function Tn(t,e){Bn[t]=e;const n=ic(t);if(!n)return;n.dataset.state=e,n.disabled=e==="pending"||e==="skipped";const i=Ks[t],r={pending:"not started",active:"in progress",done:"complete",failed:"failed",skipped:"not run"};n.setAttribute("aria-label",`Step ${t} of 3, ${i}: ${r[e]||e}`),e==="active"?n.setAttribute("aria-current","step"):n.removeAttribute("aria-current")}function Dw(){return[1,2,3].filter(t=>Bn[t]==="done").length}function Zs(){const t=document.getElementById("pipeline-progress-fill");t&&(t.style.width=`${Dw()/3*100}%`);const e=document.getElementById("progress-stage-count");e&&(e.textContent=`Step ${tc} of 3`)}function Xs(t,{done:e=!1}={}){const n=document.getElementById("progress-title-text"),i=document.getElementById("progress-substep-text"),r=Bn[t],s=e||r==="done";if(n&&(n.textContent=s?Ow[t]:Nw[t]),i){const o=s?" — complete":r==="failed"?" — stopped":"";i.textContent=`Step ${t} of 3 — ${Ks[t]}${o}`}}function jw(t){Bn[t]==="pending"||Bn[t]==="skipped"||(nc=t,[1,2,3].forEach(e=>{const n=ic(e);n&&n.setAttribute("aria-pressed",String(e===t))}),Xs(t))}function rc(){nc=null,[1,2,3].forEach(t=>{const e=ic(t);e&&e.removeAttribute("aria-pressed")})}function Ep(t){const e=document.getElementById("pipeline-note");e&&(e.textContent=t||"",e.hidden=!t)}function Uw(t,e,n){re(n)&&Ep(`${Gt(t)} did not answer. Continuing on ${Gt(e)}.`)}function sc(){const t=document.getElementById("pipeline-failure");if(!t)return;t.hidden=!0;const e=document.getElementById("pipeline-failure-actions");e&&e.replaceChildren()}const Hw=1120;function Ww(){const t=getComputedStyle(document.documentElement).getPropertyValue("--t-morph").trim(),e=Number.parseFloat(t);return Number.isFinite(e)&&e>0?e:Hw}let ei=null,Hr=null;function zw(){return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0}function dn(){if(Hr){try{Hr.cancel()}catch{}Hr=null}ei&&(ei.remove(),ei=null),window.removeEventListener("resize",dn)}function Sp(t,e){if(dn(),zw()||!t||!e||!document.body||typeof Element.prototype.animate!="function")return;const n=t.getBoundingClientRect(),i=e.getBoundingClientRect();if(!n.width||!n.height||!i.width||!i.height)return;const r=document.createElement("div");r.className="composer-morph",r.setAttribute("aria-hidden","true"),r.style.cssText=`left:${i.left}px;top:${i.top}px;width:${i.width}px;height:${i.height}px;opacity:0;`,document.body.appendChild(r);const s=n.left+n.width/2-(i.left+i.width/2),o=n.top+n.height/2-(i.top+i.height/2),a=n.width/i.width,l=n.height/i.height,u=`translate(${s}px,${o}px) scale(${a},${l})`,c=r.animate([{transform:u,opacity:0,offset:0,easing:"cubic-bezier(.2,0,0,1)"},{transform:u,opacity:1,offset:.14,easing:"cubic-bezier(.4,0,.2,1)"},{transform:`translate(${s}px,${o}px) scale(${a*.93},${l*.93})`,opacity:1,offset:.28,easing:"cubic-bezier(.32,1.38,.5,1)"},{transform:"translate(0px,0px) scale(1,1)",opacity:1,offset:1}],{duration:Ww(),fill:"both"});ei=r,Hr=c,window.addEventListener("resize",dn),c.onfinish=()=>{if(ei!==r)return;const d=r.animate([{opacity:1},{opacity:0}],{duration:260,fill:"forwards"});d.onfinish=()=>{ei===r&&dn()}}}function qw(){const e=document.getElementById("composer")?.getBoundingClientRect();e&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{Sp({getBoundingClientRect:()=>e},document.getElementById("main-stage-container"))})})}function Vw(){Sp(document.getElementById("pipeline-progress"),document.getElementById("main-stage-container"))}window.addEventListener("hashchange",dn);window.addEventListener("popstate",dn);function Qs(t={}){const{prompt:e=null,runId:n}=t;if(!re(n))return;to(),nn(!0);const i=document.getElementById("pipeline-progress"),r=document.getElementById("results-view"),s=document.getElementById("ready-state");if(s&&s.classList.add("hidden"),r&&r.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),i&&i.classList.add("visible"),Js("running"),e!==null){const a=document.getElementById("pipeline-submitted-prompt");a&&(a.textContent=e)}bp=Date.now();const o=document.getElementById("progress-elapsed");o&&(o.textContent="0s"),Bn={1:"pending",2:"pending",3:"pending"},rc(),sc(),Ep(""),[1,2,3].forEach(a=>Tn(a,"pending")),Ft(1,n),Gw()}function Ft(t,e){re(e)&&(tc=t,rc(),[1,2,3].forEach(n=>{n===t?Tn(n,"active"):nt&&Tn(n,"pending")}),Xs(t),Zs())}function tn(t,e){re(e)&&(Tn(t,"done"),nc===null&&Xs(t,{done:!0}),Zs())}function xp(t,{stage:e=1,runId:n,retry:i=Ip}={}){if(!re(n))return;eo(),to(),dn(),Js("failed"),nn(!0);const r=document.getElementById("pipeline-progress");r&&r.classList.add("visible");const s=document.getElementById("results-view");s&&s.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),Tn(e,"failed"),[1,2,3].forEach(p=>{p>e&&Tn(p,"pending")}),tc=e,rc(),Xs(e),Zs();const o=Ah(t),a=document.getElementById("pipeline-failure"),l=document.getElementById("pipeline-failure-title"),u=document.getElementById("pipeline-failure-message"),c=document.getElementById("pipeline-failure-hint"),d=document.getElementById("pipeline-failure-actions");if(!a||!l||!u||!d)return;if(a.dataset.kind=o.kind,l.textContent=`${Ks[e]}: ${o.title}`,u.textContent=o.message,c){const p=o.detail&&o.detail!==o.message?o.detail:"";c.textContent=p,c.hidden=!p}d.replaceChildren();const f=[o.canUpgrade&&{id:"upgrade",label:"View plans",variant:"primary",onClick:()=>fi()},o.canRetry&&{id:"retry",label:"Retry",variant:o.canUpgrade?"secondary":"primary",onClick:i},o.canEdit&&{id:"edit",label:"Edit prompt",variant:"secondary",onClick:Xa}].filter(Boolean);!o.canEdit&&!o.canRetry&&f.push({id:"edit",label:"Back to prompt",variant:"secondary",onClick:Xa}),f.forEach(p=>{const g=document.createElement("button");g.type="button",g.textContent=p.label,g.dataset.action=p.id,g.dataset.variant=p.variant,g.addEventListener("click",p.onClick),d.appendChild(g)}),a.hidden=!1;const h=d.querySelector("button");h&&h.focus({preventScroll:!0})}function Xa(){Bw(),_w(),y.isRunning=!1,Za(!1),rn(),Js("settled"),dn(),eo(),to(),sc();const t=document.getElementById("pipeline-progress");t&&t.classList.remove("visible"),nn(!1);const e=document.getElementById("pipeline-input");e&&(y.submittedPrompt&&(e.value=y.submittedPrompt,e.dispatchEvent(new Event("input",{bubbles:!0}))),e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length))}function Ip(){const t=document.getElementById("pipeline-input");t&&y.submittedPrompt&&(t.value=y.submittedPrompt,t.dispatchEvent(new Event("input",{bubbles:!0}))),Oe=y.submittedImages.slice(),cn(),sc(),ar()}function Gw(){eo(),Ur=setInterval(()=>{const t=(Date.now()-bp)/1e3,e=document.getElementById("progress-elapsed");e&&(e.textContent=`${Math.floor(t)}s`)},250)}function eo(){Ur&&(clearInterval(Ur),Ur=null)}let Gi=null;function to(){Gi&&(clearTimeout(Gi),Gi=null)}function ur(){eo(),to(),Js("settled"),Zs();const t=document.getElementById("pipeline-progress-fill");Gi=setTimeout(()=>{Gi=null;const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function $n(t,e=""){const n={pass:'',warning:'',fail:'',info:''};return``}function kp(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function Kw(){return y_({bundle:y.artifactBundle,reviewResult:y.step3Result})}function Yw(t){return` +`;const o=dh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:s});to({runId:i}),Ft(2,i),it(2),Ae(2,!0);const a=await qs(o,n,[],i);if(!re(i))return;y.step2Result=a,Hs(),tn(2,i);const l=document.getElementById("step2-output"),u=ui(y.step2Result);l.textContent=u,l.dataset.raw=u,Ae(2,!1),it(3),Ft(3,i),Ae(3,!0);const c=await Vs(y.step2Result,y.step1Result);if(!re(i))return;y.step3Result=c,Ws(),tn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Ae(3,!1),fr();const f=Ds(y.step3Result);hr(u,f)}catch(s){if(console.error("Regeneration failed:",s),!re(i))return;const o=Bs(s,{architect:2,generator:2,review:3});s.isUsageLimit&&un(),it(o),Ae(o,!1),Ap(s,{stage:o,runId:i,retry:()=>sp(t,e)}),Is(o,"error")}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),re(i)&&(y.isRunning=!1,rn())}}async function J0(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const n=await Te("flutterflow"),i=await Te("flutterflow_project_id");n&&i?(t.className="w-2 h-2 rounded-full bg-green-500",e.textContent="FlutterFlow credentials configured",e.className="text-green-600"):n||i?(t.className="w-2 h-2 rounded-full bg-yellow-500",e.textContent="FlutterFlow credentials incomplete",e.className="text-yellow-600"):(t.className="w-2 h-2 rounded-full bg-red-500",e.textContent="FlutterFlow credentials not configured",e.className="text-red-600")}async function op(t){try{const e=await fetch(`${_t}/auth/send-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:t})});if(!e.ok)throw new Error(`Failed to send magic link: HTTP ${e.status}`);return e.json()}catch(e){throw console.error("sendMagicLink failed:",{email:t,message:e.message,stack:e.stack}),e}}async function Z0(t){try{const n=await(await fetch(`${_t}/auth/verify-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})})).json();if(n.error||!n.email||!n.sessionToken)throw new Error(n.error||"Invalid or expired link");return n}catch(e){throw console.error("verifyMagicLink failed:",{message:e.message,stack:e.stack}),e}}async function X0(t){try{const e=await fetch(`${_t}/auth/refresh-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:t})});if(!e.ok)return console.error("refreshSession: non-OK response",{url:`${_t}/auth/refresh-session`,status:e.status}),null;const n=await e.json();return n.error||!n.email||!n.sessionToken?(console.warn("refreshSession: validation failed",{error:n.error,hasEmail:!!n.email,hasToken:!!n.sessionToken}),null):n}catch(e){return console.error("refreshSession: fetch failed",{url:`${_t}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function ud(t,e){const n=lp(),i=(q.email||n.email)!==t;q.email=t,q.sessionToken=e,q.isVerified=!0,ce=Mn({isLoading:!0}),localStorage.setItem(vs,JSON.stringify({email:t,sessionToken:e})),i&&pp()}function ap(){q.email=null,q.sessionToken=null,q.isVerified=!1,ce=Mn({isResolved:!0}),localStorage.removeItem(vs),localStorage.removeItem(ys)}function lp(){try{const t=localStorage.getItem(vs);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(vs),{email:null,sessionToken:null}}}async function Q0(){const e=new URLSearchParams(window.location.search).get("token");if(e){window.history.replaceState({},"",window.location.pathname+window.location.hash);try{const{email:n,sessionToken:i}=await Z0(e);ud(n,i),cp();const r=dd();r&&!window.location.hash&&(window.location.hash=r)}catch(n){dd();const i=n.message||"Sign-in link invalid or expired.";Ee(i,"error"),Gs(),Jn(i,"error")}}else{const{email:n,sessionToken:i}=lp();if(n&&i){const r=await X0(i);r?ud(r.email,r.sessionToken):ap()}}Xl()}function ew(){try{localStorage.setItem(ja,JSON.stringify({hash:window.location.hash||"#home",ts:Date.now()}))}catch(t){console.warn("rememberSignInReturnSurface: failed to persist return surface:",t)}}function dd(){try{const t=localStorage.getItem(ja);if(localStorage.removeItem(ja),!t)return null;const{hash:e,ts:n}=JSON.parse(t);return!e||typeof n!="number"||Date.now()-n>My?null:e}catch(t){return console.warn("consumeSignInReturnSurface: failed to read return surface:",t),null}}function Gs(){const t=document.getElementById("signin-modal");if(!t)return;ew(),document.getElementById("signin-email-input")?.removeAttribute("aria-invalid"),Jn(""),We(t)}function cp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&ze(e)}function Jn(t,e){const n=document.getElementById("signin-message");n&&(n.textContent=t||"",n.classList.remove("signin-message-success","signin-message-error"),e&&n.classList.add(`signin-message-${e}`))}async function tw(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),n=Ms(t?.value);if(!n||!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(n)||n.length>254){t?.setAttribute("aria-invalid","true"),Jn("Please enter a valid email address.","error");return}t?.removeAttribute("aria-invalid"),e&&(e.disabled=!0,e.textContent="Sending…");const r=yh(n);r&&Jn(r,"error");try{const s=await op(n),o=s?.code===_h;t&&!o&&(t.value=""),t?.setAttribute("aria-invalid",String(o)),Jn(wh(s,n),o?"error":"success"),e&&(e.disabled=!1,e.textContent=o?"Send Sign-in Link":"Sent!",o||setTimeout(()=>{e.textContent==="Sent!"&&(e.textContent="Send Sign-in Link")},2500))}catch(s){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:n,err:s}),Jn("Something went wrong. Please try again.","error"),e&&(e.disabled=!1,e.textContent="Send Sign-in Link")}}function nw(){q.email=null,q.sessionToken=null,q.isVerified=!1,ce=Mn({isResolved:!0}),z_({storage:window.localStorage,onIdentityChanged:Xl,onPlanChanged:Ys})}const iw=q_({sendLink:op,getEmail:()=>q.email||"",onState:rw});function rw(t){const e=document.getElementById("send-new-link-btn"),n=document.getElementById("send-new-link-msg");if(!e||!n)return;if(t.status==="pending"){e.disabled=!0,e.textContent="Sending…",n.className="acct-access-msg",n.textContent="Sending a fresh sign-in link…";return}if(t.status==="sent"){e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg",n.textContent=wh(t.data,q.email||"")||"Link sent — check your email.";return}e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg error";const i=t.error?.message?`Couldn't send a link right now. ${t.error.message}`:"Couldn't send a link right now. Please try again.";n.textContent=i}async function sw(){await iw()}function ow(){const t=H_(window.localStorage),e=t.length?`Cleared disposable UI caches: ${t.join(", ")}.`:"Nothing disposable to clear.";Ee(`${e} Your run count, identity and stored keys are kept.`,"info")}function aw(){const t=document.getElementById("delete-unavailable-modal");t&&We(t,{trigger:document.activeElement})}function lw(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("delete-unavailable-modal");e&&ze(e)}function Xl(){const t=q.isVerified&&!!q.email,e=document.getElementById("auth-signedout"),n=document.getElementById("auth-signedin"),i=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),n&&n.classList.toggle("hidden",!t),i&&i.classList.toggle("hidden",t);const r=document.getElementById("auth-user-email");r&&(r.textContent=q.email||"");const s=document.getElementById("access-signed-email");s&&(s.textContent=q.email||""),_w(),Ys()}async function up(){try{if(typeof FingerprintJS>"u"){console.warn("resolveIdentity: FingerprintJS not loaded, skipping");return}const e=await(await FingerprintJS.load()).get(),n=e.visitorId,i=await fetch(By,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fingerprint:e.visitorId,cookie_id:n})});if(!i.ok)throw new Error(`Identity check HTTP ${i.status}`);const r=await i.json();if(ht.userId=r.user_id,ht.token=r.identity_token||null,ht.status=r.status,ht.resolved=!0,sessionStorage.setItem(Ny,r.user_id),ht.token&&sessionStorage.setItem(Oy,ht.token),r.usage_count!==void 0){const s=gn(),a=(r.usage_month||s)===s?r.usage_count:0;localStorage.setItem(Fn,JSON.stringify({count:a,month:s})),un()}console.log(`Identity resolved: ${r.status} (${r.user_id.slice(0,8)}...) usage: ${r.usage_count??"n/a"}`)}catch(t){console.error("resolveIdentity failed:",t)}}let Go=null;function cw(t=5e3){return ht.resolved?Promise.resolve():(Go||(Go=up().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([Go,new Promise(e=>setTimeout(e,t))]))}function dp(){const t=gn();try{const e=localStorage.getItem(Fn);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Fn,month:t,err:e}),localStorage.removeItem(Fn),{count:0,month:t}}}function gn(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function dr(){const t=dp();return t.month!==gn()?{count:0,month:gn()}:t}function uw(){const e={count:dr().count+1,month:gn()};return localStorage.setItem(Fn,JSON.stringify(e)),e}function vi(){return!!ce.isLoading}function Tt(){return!!ce.isResolved}function dw(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(_s,e)?e:null}function fw(t){return t&&Object.entries(Mh).find(([,e])=>e===t)?.[0]||null}function Fr(...t){return t.find(e=>e!=null&&e!=="")}function hw(...t){return t.find(e=>e&&typeof e=="object")||{}}function pw(t){const e=t.data&&typeof t.data=="object"?t.data:t,n=hw(e.subscription,e.stripeSubscription,e.currentSubscription,e.customer?.subscriptions?.data?.[0],e.subscriptions?.data?.[0],e.subscriptions?.[0]),i=e.metadata||n.metadata||e.customer?.metadata||{},r=Fr(e.priceId,e.price_id,e.stripePriceId,e.stripe_price_id,n.priceId,n.price_id,n.plan?.id,n.price?.id,n.items?.data?.[0]?.price?.id,n.items?.[0]?.price?.id,n.lines?.data?.[0]?.price?.id),s=Fr(e.status,e.subscriptionStatus,e.subscription_status,n.status,"none"),o=dw(Fr(e.tier,e.plan,e.planId,e.plan_id,e.subscriptionTier,e.subscription_tier,e.product,e.productName,n.tier,n.plan,i.tier,i.plan)),a=Dy.has(String(s).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||fw(r)||(a||l?"professional":"free");return Mn({tier:u,status:s,periodEnd:Fr(e.periodEnd,e.currentPeriodEnd,e.current_period_end,n.current_period_end,n.periodEnd,null),isResolved:!0})}function Ks(){return _s[ce.tier]??_s.free}async function gw(){if(q.isVerified&&(!Tt()||vi())&&(await hp({force:!0}),Ys()),q.isVerified&&!Tt())return Ee("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=dr(),e=Ks();if(t>=e)return fp(t,e,{openModal:!0}),!1;const n=Math.floor(e*.8);if(t>=n){const i=e-t;Ee(`${i} run${i===1?"":"s"} remaining this month.`,"warning")}return!0}function fd(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function fp(t,e,n={}){nn(!0);const i=document.getElementById("walkthrough-modal");i&&ze(i,{restoreFocus:!1});const r=document.getElementById("ready-state");r&&r.classList.add("hidden");const s=document.getElementById("preview-frame-container");s&&(s.style.display="none");const o=document.getElementById("main-stage-container");o&&o.classList.add("visible");const a=document.getElementById("results-view");a&&a.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar");const l=document.getElementById("pipeline-progress");l&&l.classList.remove("visible");const u=document.getElementById("paywall-exhausted");if(!u){Ee(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),pi();return}const c=document.getElementById("paywall-exhausted-text");if(c){const f=ce.tier;f==="free"?c.textContent=`You've used all ${e} free generations this month. Upgrade to Pro for 50 generations/month and access to all AI models.`:c.textContent=`You've used all ${e} generations this month on your ${f} plan. Your limit resets next month.`}const d=document.getElementById("paywall-signin-btn");d&&d.classList.toggle("hidden",q.isVerified),u.classList.remove("hidden"),n.openModal&&pi()}function Ja(t){return ce.tier==="free"&&Dr.includes(t)?ws:t}function mw(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const n=ce.tier,r=!(q.isVerified&&!Tt())&&n==="free";Array.from(e.options).forEach(o=>{const a=Gt(o.value),l=Dr.includes(o.value);o.textContent=l&&r?`${a} (PRO)`:a,o.disabled=!1}),r&&Dr.includes(e.value)&&(e.value=ws),e.disabled=!1,Xu.has(e)||(e.addEventListener("change",()=>{Tt()&&ce.tier==="free"&&Dr.includes(e.value)&&(e.value=ws,pi()),Ya(e.value),Rl()}),Xu.add(e));let s=document.getElementById("model-selector-free-notice");r?(s||(s=document.createElement("p"),s.id="model-selector-free-notice",s.className="text-xs text-gray-400 mt-1",t.appendChild(s)),s.innerHTML='Free plan — Gemini only. '):s&&s.remove(),Ya(e.value)}function Ql(){const t=q.isVerified&&!!q.email,e=t&&vi(),n=!t||Tt(),i=dr(),r=n?i.count:0,s=n?Ks():0,o=Math.max(0,s-r),a=`${r} / ${s} runs this month`,l=wl,u=n?ce.tier||"free":null,c=document.getElementById("topbar-credits-count");c&&(e?c.textContent="…":n?c.textContent=String(o):c.textContent="—");const d=document.getElementById("credits-balance");d&&(e?d.textContent="Checking plan…":n?d.textContent=a:d.textContent="Plan check failed");const f=document.getElementById("usage-dialog-tier");f&&(e?f.textContent="Checking…":n?f.textContent=l[u]||"Free":f.textContent="Unavailable");const h=document.getElementById("usage-dialog-status");h&&(e?h.textContent="Verifying your subscription…":n?h.textContent="Runs reset at the start of each month.":h.textContent="Could not verify your subscription. Try again or sign out.");const p=document.getElementById("usage-counter");if(p)if(e&&t)p.textContent="Checking plan…",p.className="text-xs text-gray-500";else if(!n&&t)p.textContent="Plan check failed",p.className="text-xs text-red-600 font-medium";else{p.textContent=a;const g=s>0?r/s:0;p.className=g>=1?"text-xs text-red-600 font-medium":g>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500"}if(!t){const g=document.getElementById("guest-usage-text");if(g){const m=dp(),v=m.month===gn()?m.count??0:0;g.textContent=`${v} / ${_s.free} generations used`}}vw()}function vw(){if(!(q.isVerified&&!!q.email))return;const e=vi(),n=Tt(),i=dr(),r=n?i.count:0,s=n?Ks():0,o=Math.max(0,s-r),a=n?ce.tier||"free":null,l={free:"Free",professional:"Pro",power:"Power"}[a]||"Free",u=q.email||"",c=u.split("@")[0]||u,d=document.getElementById("acct-avatar");d&&(d.textContent=(u[0]||"?").toUpperCase());const f=document.getElementById("acct-name");f&&(f.textContent=c||"—");const h=document.getElementById("acct-plan-tier"),p=document.getElementById("acct-plan-price"),g=document.getElementById("acct-plan-note"),m=document.getElementById("acct-renewal");if(h&&(h.textContent=e?"Checking…":n?l:"Plan unavailable"),p)if(e)p.textContent="—";else if(!n)p.textContent="—";else if(a==="free")p.textContent="$0 / month";else{const x=ji(Di[a]??0,Tl());p.textContent=`${x} / month`}if(g&&(e?g.textContent="Verifying your subscription…":n?a==="free"?g.textContent="No subscription. Upgrade for more generations.":g.textContent="billed monthly through Stripe":g.textContent="Could not verify your subscription. Check billing or sign out."),m){const x=Date.parse(ce.periodEnd||""),F=n&&a!=="free"&&!!ce.periodEnd&&!Number.isNaN(x);if(e)m.textContent="";else if(!n)m.textContent="";else if(a==="free")m.textContent="";else if(F){const $=new Date(x).toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"});m.textContent=`Renews ${$} · reset at the start of each month.`}else m.textContent="Renewal date is not available for this period."}const v=document.getElementById("acct-left-count"),E=document.getElementById("acct-left-limit"),S=document.getElementById("acct-reset-note");v&&(v.textContent=e?"…":n?String(o):"—"),E&&(E.textContent=e?"…":n?String(s):"—"),S&&(e?S.textContent="Checking plan…":n?S.textContent="Runs reset at the start of each month.":S.textContent="Plan check failed. Refresh or manage billing.");const _=document.getElementById("acct-used-count"),b=document.getElementById("acct-meter-fill"),k=document.getElementById("acct-meter-meta"),T=document.getElementById("acct-meter-track");if(_&&(_.textContent=e?"…":n?String(r):"—"),b){const x=n&&s>0?Math.min(100,Math.round(r/s*100)):0;b.style.width=`${x}%`}if(k)if(e)k.textContent="Checking…";else if(!n)k.textContent="Plan check failed";else if(s===0)k.textContent=`${r} of ${s}`;else{const x=Math.round(r/s*100);k.textContent=`${r} of ${s} · ${x}%`}T&&(e?T.setAttribute("aria-label","Checking usage…"):n?T.setAttribute("aria-label",`${r} of ${s} generations used`):T.setAttribute("aria-label","Usage unavailable")),vt()}function un(){if(Ql(),q.isVerified&&(vi()||!Tt())){fd();return}const{count:t}=dr(),e=Ks();t>=e&&!y.isRunning?fp(t,e):fd()}function _w(){Ql()}async function hp(t={}){const e=t.force===!0;if(!q.isVerified||!q.sessionToken){ce=Mn({isResolved:!0});return}ce={...ce,isLoading:!0,error:null};const n=localStorage.getItem(ys);if(!e&&n)try{const{data:i,email:r,ts:s,version:o}=JSON.parse(n);if(o===Qu&&r===q.email&&Date.now()-s<300*1e3){ce={...i,isLoading:!1,isResolved:i.isResolved!==!1};return}}catch(i){console.warn("Failed to parse subscription cache:",i,"| raw value:",n)}try{const r=await(await fetch(`${_t}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:q.sessionToken,user_id:ht.userId})})).json();if(r.error){if(["unauthorized","invalid session","expired session"].some(o=>String(r.error).toLowerCase().includes(o))){ap(),Xl();return}ce=Mn({isResolved:!1,error:r.error});return}ce=pw(r),localStorage.setItem(ys,JSON.stringify({version:Qu,data:ce,email:q.email,ts:Date.now()}))}catch(i){console.error("fetchSubscription failed:",i),ce={...ce,isLoading:!1,isResolved:!1,error:i.message}}}function pp(){localStorage.removeItem(ys)}async function yw(t){if(!q.isVerified||!q.sessionToken){gp(),Gs();return}if(!Mh[t]){Ee("Invalid plan selected.","error");return}const e=document.getElementById(`checkout-btn-${t}`);e&&(e.disabled=!0,e.textContent="Redirecting…");try{const i=await(await fetch(`${_t}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:q.sessionToken,currency:Tl()})})).json();if(i.error||!i.url)throw new Error(i.error||"Failed to create checkout session");const{url:r}=i;window.location.href=r}catch(n){console.error("startCheckout failed:",n),e&&(e.disabled=!1,e.textContent="Subscribe"),Ee("Could not start checkout. Please try again.","error")}}async function ww(t){if(!q.isVerified||!q.sessionToken){Gs();return}const e=t||document.getElementById("manage-billing-btn"),n=e?e.textContent:"";e&&(e.disabled=!0,e.textContent="Loading…");try{const r=await(await fetch(`${_t}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:q.sessionToken})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to open billing portal");const{url:s}=r;window.location.href=s}catch(i){console.error("openCustomerPortal failed:",i),e&&(e.disabled=!1,e.textContent=n),Ee("Could not open billing portal. Please try again.","error")}}const ks=new Set;function bw(){ks.forEach(t=>t.abort()),ks.clear()}async function Cs(t,e,n,i={},r=[]){const o=new AbortController;ks.add(o);let a=!1;const l=setTimeout(()=>{a=!0,o.abort()},12e4);try{const u=await fetch(Ly,{method:"POST",headers:{"Content-Type":"application/json",...ht.token?{Authorization:`Bearer ${ht.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:ht.userId,step:t,model:e,prompt:n,images:r,context:i})}),c=await u.text();let d={};try{d=c?JSON.parse(c):{}}catch{d={}}if(u.status===429){d.serverCount!==void 0&&(localStorage.setItem(Fn,JSON.stringify({count:d.serverCount,month:gn()})),un());const p=new Error(d.message||"Monthly usage limit reached. Upgrade to continue.");throw p.isUsageLimit=!0,p.pipelineStep=t,p}const f=Rv(d,t);if(f)throw f;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(d),"content type:",typeof d.content),!u.ok)throw new Error(`${d.message||d.error||"BuildShip pipeline error"} (HTTP ${u.status})`);if(t==="generator")if(d.usage_status==="success"&&Number.isFinite(d.usage_count)){const p=gn();(d.usage_month||p)===p&&(localStorage.setItem(Fn,JSON.stringify({count:d.usage_count,month:p})),un())}else uw(),un();let h=d.output||d.content;if(!h){const p=c?` (body: ${c.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${p}`)}return Array.isArray(h)&&(h=h.map(p=>typeof p=="string"?p:p.text||"").join("")),typeof h!="string"&&(h=JSON.stringify(h)),h}catch(u){if(u.name==="AbortError"){if(a)throw new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`);const c=new Error(`BuildShip ${t} request cancelled`);throw c.isPipelineCancel=!0,c}throw u instanceof TypeError?new Error(`BuildShip unreachable: ${u.message}`):u}finally{clearTimeout(l),ks.delete(o)}}let Za=!1;function Ew(){const e=new URLSearchParams(window.location.search).get("checkout");return e==="success"?(window.history.replaceState({},"",window.location.pathname+window.location.hash),pp(),Za=!0):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname+window.location.hash),Ee("Checkout cancelled.","info")),e}function Sw(){if(!Za)return;Za=!1;const t=ce.tier!=="free";Ee(t?"Subscription active! Your plan is live.":"Checkout complete — confirming your subscription. Check Manage billing if it does not update.",t?"success":"info")}function Ys(){const t=q.isVerified&&!!q.email,e=ce.tier,n=t&&vi(),i=!t||Tt(),r=document.getElementById("subscription-tier-badge");if(r){const a=wl,l={free:"bg-gray-100 text-gray-600",professional:"bg-indigo-100 text-indigo-700",power:"bg-purple-100 text-purple-700",unresolved:"bg-red-50 text-red-600"};r.textContent=n?"Checking…":i?a[e]||"Free":"Plan unavailable",r.className=`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${i?l[e]||l.free:l.unresolved}`}const s=document.getElementById("upgrade-prompt");s&&s.classList.toggle("hidden",!t||n||!i||e!=="free");const o=document.getElementById("manage-billing-btn");o&&o.classList.toggle("hidden",!t||n||i&&e==="free"),xw(i?e:null),mw(),Rl(),un(),$p()}function xw(t){const e=["bg-gray-100","text-gray-500","cursor-default"];Object.entries({professional:{btnId:"checkout-btn-professional",defaultText:"Subscribe"},power:{btnId:"checkout-btn-power",defaultText:"Subscribe"}}).forEach(([r,{btnId:s,defaultText:o}])=>{const a=document.getElementById(s);a&&(r===t?(a.disabled=!0,a.textContent="Current plan",a.classList.add(...e)):(a.disabled=!1,a.textContent=o,a.classList.remove(...e)))});const i=document.getElementById("free-tier-current");i&&i.classList.toggle("hidden",t!=="free")}function Iw(){document.querySelectorAll(".pm-card[data-tier]").forEach(t=>{const e=t.dataset.tier,n=_v[e];if(!n)return;const i=t.querySelector("ul.pm-features");if(i){i.innerHTML="";for(const r of n){const s=document.createElement("li");s.textContent=r,i.appendChild(s)}}})}function Xa(){const t=Tl(),e=document.getElementById("pro-price"),n=document.getElementById("power-price"),i=document.getElementById("plans-pro-price"),r=document.getElementById("plans-power-price"),s=document.getElementById("pro-price-note"),o=document.getElementById("power-price-note"),a=document.getElementById("plans-pro-price-note"),l=document.getElementById("plans-power-price-note");e&&(e.textContent=ji(Di.professional,t)),n&&(n.textContent=ji(Di.power,t)),i&&(i.textContent=ji(Di.professional,t)),r&&(r.textContent=ji(Di.power,t));const u="billed monthly";s&&(s.textContent=u),o&&(o.textContent=u),a&&(a.textContent=u),l&&(l.textContent=u)}function pi(){Xa();const t=document.getElementById("pricing-modal");t&&We(t),Jy().then(()=>Xa())}function gp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&ze(e)}function Ee(t,e="info"){const n={success:"bg-green-600 text-white",error:"bg-red-600 text-white",warning:"bg-amber-500 text-white",info:"bg-gray-800 text-white"},i=document.createElement("div");i.className=`fixed bottom-6 left-1/2 -translate-x-1/2 px-5 py-3 rounded-lg text-sm font-medium shadow-lg z-50 transition-opacity duration-300 ${n[e]||n.info}`,i.textContent=t,document.body.appendChild(i),setTimeout(()=>{i.style.opacity="0",setTimeout(()=>i.remove(),300)},3500)}document.addEventListener("DOMContentLoaded",async()=>{gv(),hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),kw(),window.__heroField=ay(),window.__pipelineLogo=dy(),Nh=Ty({onSubmit:lr}),Ua=(async()=>{try{await Q0(),Ew(),await hp()}catch(n){console.warn("Startup auth/subscription initialization failed:",n)}})(),await Ua,Sw(),Ys(),Xa(),Iw(),await k0(),b0();const t=document.getElementById("flutterflow-endpoint-select");if(t){const n=yt();t.value=n}Kh(),up();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{en===2&&e.value.trim().length>0&&(Ol(),js())}),e.addEventListener("blur",()=>{const n=document.getElementById("walkthrough-modal");en===2&&n&&We(n)}),e.addEventListener("keydown",n=>{if(n.key==="Tab"){const i=document.getElementById("walkthrough-modal");en===2&&i&&setTimeout(()=>{We(i)},100)}})),window.addEventListener("commitStateChange",n=>{const{state:i}=n.detail;i===ee.PREPARING||i===ee.VALIDATING||i===ee.PUSHING?(Be.phaseId||bp(),pd(i)):(i===ee.SUCCESS||i===ee.ERROR)&&(pd(i),setTimeout(nc,1e3))}),cc()});function kw(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function Cw(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Nn),document.addEventListener("keydown",Nn))}function Nn(){const t=document.getElementById("preview-frame-container"),e=document.getElementById("main-stage-container"),n=document.getElementById("ready-state");t&&(t.style.display="none"),e&&e.classList.add("visible"),n&&n.classList.remove("hidden");const i=document.getElementById("welcome-video-player");i&&i.removeEventListener("click",Nn),document.removeEventListener("keydown",Nn),Kh()}let Ki=null;async function Aw(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++rd,n=()=>e===rd,i=await Te("flutterflow"),r=await Te("flutterflow_project_id");if(n()){if(!i){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const o=await new mi(i,"","main",yt()).listProjects();if(!n())return;if(!o||o.length===0){t.innerHTML='';return}t.innerHTML='',o.forEach(a=>{const l=document.createElement("option");l.value=a.id||a.projectId||"",l.textContent=a.name||a.projectName||`Project ${a.id}`,t.appendChild(l)}),r&&(t.value=r)}catch(s){if(!n())return;console.error("Failed to load projects for deploy:",s),t.innerHTML=''}}}function Pw(){return document.getElementById("confirm-project-select")?.value?.trim()||null}function ec(t,e,n,i=null){Ki={codeInfo:t,checks:e,deps:n,bundlePlan:i},document.getElementById("confirm-file-name").textContent=t.fileName,document.getElementById("confirm-artifact-type").textContent=t.artifactType,document.getElementById("confirm-file-size").textContent=`${(t.content.length/1024).toFixed(1)} KB`,document.getElementById("confirm-line-count").textContent=i?`${i.fileEntries.length} files`:t.content.split(` +`).length,Aw();const r=document.getElementById("confirm-deps-list"),s=document.getElementById("confirm-deps-section");n&&Object.keys(n).length>0?(r.innerHTML=Object.entries(n).map(([u,c])=>{const d=c?`at least ${Qt(c)}`:"version resolved from your project";return`
    • • ${Qt(u)}: ${d}
    • `}).join(""),s.classList.remove("hidden")):s.classList.add("hidden");const o=document.getElementById("confirm-warnings-list"),a=document.getElementById("confirm-warnings-section");e.warnings&&e.warnings.length>0?(o.innerHTML=e.warnings.map(u=>`
    • • ${Qt(u)}
    • `).join(""),a.classList.remove("hidden")):a.classList.add("hidden"),document.getElementById("confirm-code-preview").textContent=t.content,document.getElementById("code-preview-content").classList.add("hidden"),document.getElementById("code-preview-chevron").style.transform="rotate(0deg)";const l=document.getElementById("commit-confirm-modal");l&&We(l)}function mp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&ze(e),Ki=null}function Fw(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&ze(e);const n=["success-message","success-project-id","success-file-name","success-artifact-type","success-time","success-size"];for(const s of n){const o=document.getElementById(s);o&&(o.textContent="")}const i=document.getElementById("success-warnings-section");i&&i.classList.add("hidden");const r=document.getElementById("success-warnings-list");r&&(r.innerHTML="")}function vp(t){const e=(m,v)=>{const E=document.getElementById(m);E&&(E.textContent=v||"")},n=t.metadata?.fileName||"",i=t.metadata?.projectId||"",r=t.metadata?.artifactType||"",s=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",i),e("success-file-name",n),e("success-artifact-type",r),e("success-time",s),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&i&&(u.href=`https://app.flutterflow.io/project/${i}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),f=t.unverified||[],h=t.approximate||[],p=t.warnings||[];(p.length>0||f.length>0||h.length>0)&&c&&d&&(d.innerHTML=[...f.map(m=>`
    • Not verified before deploying: ${z(String(m))}
    • `),...h.map(m=>`
    • Verified approximately: ${z(String(m))}
    • `),...p.map(([m,v])=>`
    • ${z(m)}: ${z(String(v))}
    • `)].join(""),c.classList.remove("hidden"));const g=document.getElementById("commit-success-modal");g&&We(g)}function _p(t){nc(),Y0(t);const e=t.remoteRefusal===!0;tc(t,{heading:"Deploy failed",title:e?"FlutterFlow refused this deploy — nothing was confirmed written.":"The deploy failed before FlutterFlow confirmed anything.",guidance:e?"Review the error and any per-file outcomes above, fix them in your code or in FlutterFlow, then deploy again. A refusal is definitive: no part of this deploy was applied, so retrying is safe once the problem is fixed.":"Review the error above, fix it, then deploy again. The deploy stopped before a write was confirmed, so nothing was applied."})}function tc(t,{heading:e,title:n,guidance:i}){const r=t.targetIdentity||{},s=document.getElementById("commit-terminal-modal");if(!s)return!1;const o=(h,p)=>{const g=document.getElementById(h);g&&(g.textContent=p||"")};o("terminal-heading",e),o("terminal-title",n),o("terminal-message",t.error||t.message||"");const a=document.getElementById("terminal-identity-list");if(a){const h=[["Project",r.projectId||t.metadata?.projectId],["Endpoint",r.endpoint],["File",r.fileName||t.metadata?.fileName],["Artifact",r.artifactType||t.metadata?.artifactType]];a.innerHTML=h.map(([p,g])=>`
      ${z(p)}:${z(String(g??"—"))}
      `).join("")}const l=document.getElementById("terminal-file-outcomes");let u=t.errorMap;u&&!(u instanceof Map)&&(u=new Map(Object.entries(u))),l&&u&&u.size>0?(l.innerHTML=[...u.entries()].map(([h,p])=>`
    • ${z(h)}: ${z(Cl(p))}
    • `).join(""),l.classList.remove("hidden")):l&&l.classList.add("hidden");const c=document.getElementById("terminal-guidance");c&&(c.innerHTML=i);const d=document.getElementById("terminal-open-ff-link"),f=r.projectId||t.metadata?.projectId;return d&&(d.href=f?`https://app.flutterflow.io/project/${f}`:"https://app.flutterflow.io/"),We(s),!0}function yp(t){tc(t,{heading:"Deploy partially applied",title:"Some custom classes reached FlutterFlow, but the deploy did not fully complete.",guidance:"The custom classes the runner confirmed are already in your project and are not lost. Review the per-file errors above, fix them in FlutterFlow or regenerate, then deploy again. Open the project to see exactly what landed."})}function wp(t){tc(t,{heading:"Deploy outcome not yet known",title:"This browser stopped waiting before the FlutterFlow server reported a result.",guidance:"The deploy may still be finishing on the server — it was not cancelled. Open your FlutterFlow project and confirm whether the class landed before retrying, so you do not push a duplicate or build on top of an unknown state."})}function Rw(t){t&&t.target!==t.currentTarget||ze(document.getElementById("commit-terminal-modal"))}function Tw(){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 hd={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}},$w=[{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&&(Au(e,!0,"Deploying to FlutterFlow"),We(e)),this.set("prepare")},set(t,e=null){if(!(!hd[t]||t===this.phaseId)){if(!this.sequence.includes(t)){const n=this.sequence.indexOf("package");this.sequence.splice(n===-1?this.sequence.length:n,0,t)}this.phaseId=t,this.phaseStartedAt=Date.now(),this.substatus=e,this.liveSubstatus=!1,this.render(),this.timer&&clearInterval(this.timer),t!=="done"&&(this.timer=setInterval(()=>this.render(),500))}},setSubstatus(t){t&&(this.liveSubstatus=!0,this.substatus=t,this.render())},render(){const t=hd[this.phaseId];if(!t)return;const e=(Date.now()-this.phaseStartedAt)/1e3,n=t.start+(t.end-t.start)*(1-Math.exp(-e/25));if(this.phaseId==="provision"&&!this.liveSubstatus){const o=$w.filter(a=>e>=a.after).pop();o&&(this.substatus=o.text)}const i=this.sequence.indexOf(this.phaseId),s=[`Step ${i===-1?1:i+1} of ${this.sequence.length}`];e>=5&&s.push(Mw(e)),Ep(this.phaseId==="done"?100:n,t.message,s.join(" · "),this.substatus)},stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.phaseId=null;const t=document.getElementById("commit-progress-overlay");t&&(Au(t,!1),ze(t,{force:!0,restoreFocus:!1}))}};function Mw(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 bp(t){Be.start(t)}function nc(){Be.stop()}function Ep(t,e,n,i=null){const r=document.getElementById("commit-progress-bar"),s=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");r&&(r.style.width=`${Math.round(t*10)/10}%`),s&&(s.textContent=e),o&&(o.textContent=n),a&&(a.textContent=i||"",a.classList.toggle("hidden",!i))}function pd(t){const e={[ee.PREPARING]:"prepare",[ee.VALIDATING]:"validate",[ee.PUSHING]:"project",[ee.SUCCESS]:"done"};if(t===ee.ERROR){Be.timer&&clearInterval(Be.timer),Be.timer=null,Ep(100,"Failed","Error occurred");return}const n=e[t];n&&Be.set(n)}function Lw(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===J.CODE_FILE):t.codeInfo?.codeType===J.CODE_FILE}let Sp=!1;function xp(t){Sp=t;const e=document.querySelector("#commit-confirm-modal button[data-deploy-confirm]");e&&(e.disabled=t),[...document.querySelectorAll("[data-deploy-start]"),...document.querySelectorAll("#btn-deploy-to-ff")].forEach(i=>{i.disabled=t})}function gd(t){nc(),xp(!1);const e=Ph(t);e===Le.COMMITTED?vp(t):e===Le.PARTIAL?yp(t):e===Le.UNCONFIRMED?wp(t):_p(t)}async function Nw(){if(!Ki){console.error("No pending commit data");return}if(Sp){console.warn("Deploy already in flight; ignoring duplicate confirm.");return}const t=Ki;if(Ki=null,Gi=Pw(),mp(),xp(!0),bp({withProvisioning:Lw(t)}),t.bundlePlan){const o=await B0(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});Gi=null,gd(o);return}const{codeInfo:e}=t,{artifactType:n,artifactName:i,fileName:r}=Yh(),s=await O0(e.content,{artifactType:n,artifactName:i,fileName:r,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});Gi=null,gd(s)}window.runThinkingPipeline=lr;window.toggleStep=U0;window.toggleSection=j0;window.selectWorkflowStep=it;window.copyCode=H0;window.retryWithDifferentModel=V0;window.openApiKeysModal=Nl;window.closeApiKeysModal=Vh;window.openComposerSettings=u0;window.closeComposerSettings=d0;window.walkthroughConnectAccount=c0;window.closeWalkthroughModal=h0;window.openWalkthroughModal=f0;window.advanceWalkthrough=Ol;window.commitToFlutterFlow=N0;function Ow(){const t=document.getElementById("pipeline-input");t&&t.focus()}function Bw(){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=Ow;window.openModelSelector=Bw;window.handlePromptImageSelect=Ky;window.removePromptImage=Yy;window.saveApiKeys=m0;window.validateFlutterFlowConnection=Dl;window.clearAllApiKeys=v0;window.toggleKeyVisibility=S0;window.handleWelcomeVideoEnd=Cw;window.dismissWelcomeVideo=Nn;window.initiateCommitToFlutterFlow=G0;window.updateFlutterFlowCredentialStatus=J0;window.openCommitConfirmModal=ec;window.closeCommitConfirmModal=mp;window.closeCommitSuccessModal=Fw;window.closeCommitTerminalModal=Rw;window.showCommitPartialModal=yp;window.showCommitUnconfirmedModal=wp;window.showCommitSuccessModal=vp;window.showCommitFailureModal=_p;window.toggleCodePreview=Tw;window.confirmCommitToFlutterFlow=Nw;window.runRefinement=ip;window.regenerateFromPastedErrors=rp;window.clearErrorInput=q0;window.setFlutterFlowEndpoint=l0;window.getFlutterFlowEndpoint=yt;window.commitProgress=Be;window.openSignInModal=Gs;window.closeSignInModal=cp;window.handleMagicLinkRequest=tw;window.handleSignOut=nw;window.handleSendNewLink=sw;window.handleClearCache=ow;window.handleDeleteAccount=aw;window.closeDeleteUnavailableModal=lw;window.startCheckout=yw;window.openCustomerPortal=ww;window.openPricingModal=pi;window.closePricingModal=gp;let zr=null,Ip=null,On={1:"pending",2:"pending",3:"pending"},ic=1,rc=null;const Js={1:"Prompt Architect",2:"Code Generator",3:"Code Review"},Dw={1:"Understanding your prompt",2:"Generating Dart code",3:"Running the code audit"},jw={1:"Prompt understood",2:"Dart code generated",3:"Code audit complete"};function Zs(){return y.runId+=1,y.runId}function re(t){return t===void 0||t===y.runId}function Uw(){y.runId+=1}function sc(t){return document.getElementById(`pdot-${t}`)}function Qa(t){const e=document.getElementById("btn-run-pipeline")||document.getElementById("hero-send");e&&(e.disabled=t,e.classList.toggle("is-busy",t),t?e.setAttribute("aria-busy","true"):e.removeAttribute("aria-busy"))}function Xs(t){const e=document.getElementById("pipeline-progress");e&&(e.dataset.runState=t)}function Rn(t,e){On[t]=e;const n=sc(t);if(!n)return;n.dataset.state=e,n.disabled=e==="pending"||e==="skipped";const i=Js[t],r={pending:"not started",active:"in progress",done:"complete",failed:"failed",skipped:"not run"};n.setAttribute("aria-label",`Step ${t} of 3, ${i}: ${r[e]||e}`),e==="active"?n.setAttribute("aria-current","step"):n.removeAttribute("aria-current")}function Hw(){return[1,2,3].filter(t=>On[t]==="done").length}function Qs(){const t=document.getElementById("pipeline-progress-fill");t&&(t.style.width=`${Hw()/3*100}%`);const e=document.getElementById("progress-stage-count");e&&(e.textContent=`Step ${ic} of 3`)}function eo(t,{done:e=!1}={}){const n=document.getElementById("progress-title-text"),i=document.getElementById("progress-substep-text"),r=On[t],s=e||r==="done";if(n&&(n.textContent=s?jw[t]:Dw[t]),i){const o=s?" — complete":r==="failed"?" — stopped":"";i.textContent=`Step ${t} of 3 — ${Js[t]}${o}`}}function Ww(t){On[t]==="pending"||On[t]==="skipped"||(rc=t,[1,2,3].forEach(e=>{const n=sc(e);n&&n.setAttribute("aria-pressed",String(e===t))}),eo(t))}function oc(){rc=null,[1,2,3].forEach(t=>{const e=sc(t);e&&e.removeAttribute("aria-pressed")})}function kp(t){const e=document.getElementById("pipeline-note");e&&(e.textContent=t||"",e.hidden=!t)}function zw(t,e,n){re(n)&&kp(`${Gt(t)} did not answer. Continuing on ${Gt(e)}.`)}function ac(){const t=document.getElementById("pipeline-failure");if(!t)return;t.hidden=!0;const e=document.getElementById("pipeline-failure-actions");e&&e.replaceChildren()}const qw=1120;function Vw(){const t=getComputedStyle(document.documentElement).getPropertyValue("--t-morph").trim(),e=Number.parseFloat(t);return Number.isFinite(e)&&e>0?e:qw}let ti=null,qr=null;function Gw(){return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0}function dn(){if(qr){try{qr.cancel()}catch{}qr=null}ti&&(ti.remove(),ti=null),window.removeEventListener("resize",dn)}function Cp(t,e){if(dn(),Gw()||!t||!e||!document.body||typeof Element.prototype.animate!="function")return;const n=t.getBoundingClientRect(),i=e.getBoundingClientRect();if(!n.width||!n.height||!i.width||!i.height)return;const r=document.createElement("div");r.className="composer-morph",r.setAttribute("aria-hidden","true"),r.style.cssText=`left:${i.left}px;top:${i.top}px;width:${i.width}px;height:${i.height}px;opacity:0;`,document.body.appendChild(r);const s=n.left+n.width/2-(i.left+i.width/2),o=n.top+n.height/2-(i.top+i.height/2),a=n.width/i.width,l=n.height/i.height,u=`translate(${s}px,${o}px) scale(${a},${l})`,c=r.animate([{transform:u,opacity:0,offset:0,easing:"cubic-bezier(.2,0,0,1)"},{transform:u,opacity:1,offset:.14,easing:"cubic-bezier(.4,0,.2,1)"},{transform:`translate(${s}px,${o}px) scale(${a*.93},${l*.93})`,opacity:1,offset:.28,easing:"cubic-bezier(.32,1.38,.5,1)"},{transform:"translate(0px,0px) scale(1,1)",opacity:1,offset:1}],{duration:Vw(),fill:"both"});ti=r,qr=c,window.addEventListener("resize",dn),c.onfinish=()=>{if(ti!==r)return;const d=r.animate([{opacity:1},{opacity:0}],{duration:260,fill:"forwards"});d.onfinish=()=>{ti===r&&dn()}}}function Kw(){const e=document.getElementById("composer")?.getBoundingClientRect();e&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{Cp({getBoundingClientRect:()=>e},document.getElementById("main-stage-container"))})})}function Yw(){Cp(document.getElementById("pipeline-progress"),document.getElementById("main-stage-container"))}window.addEventListener("hashchange",dn);window.addEventListener("popstate",dn);function to(t={}){const{prompt:e=null,runId:n}=t;if(!re(n))return;io(),nn(!0);const i=document.getElementById("pipeline-progress"),r=document.getElementById("results-view"),s=document.getElementById("ready-state");if(s&&s.classList.add("hidden"),r&&r.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),i&&i.classList.add("visible"),Xs("running"),e!==null){const a=document.getElementById("pipeline-submitted-prompt");a&&(a.textContent=e)}Ip=Date.now();const o=document.getElementById("progress-elapsed");o&&(o.textContent="0s"),On={1:"pending",2:"pending",3:"pending"},oc(),ac(),kp(""),[1,2,3].forEach(a=>Rn(a,"pending")),Ft(1,n),Jw()}function Ft(t,e){re(e)&&(ic=t,oc(),[1,2,3].forEach(n=>{n===t?Rn(n,"active"):nt&&Rn(n,"pending")}),eo(t),Qs())}function tn(t,e){re(e)&&(Rn(t,"done"),rc===null&&eo(t,{done:!0}),Qs())}function Ap(t,{stage:e=1,runId:n,retry:i=Pp}={}){if(!re(n))return;no(),io(),dn(),Xs("failed"),nn(!0);const r=document.getElementById("pipeline-progress");r&&r.classList.add("visible");const s=document.getElementById("results-view");s&&s.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),Rn(e,"failed"),[1,2,3].forEach(p=>{p>e&&Rn(p,"pending")}),ic=e,oc(),eo(e),Qs();const o=Th(t),a=document.getElementById("pipeline-failure"),l=document.getElementById("pipeline-failure-title"),u=document.getElementById("pipeline-failure-message"),c=document.getElementById("pipeline-failure-hint"),d=document.getElementById("pipeline-failure-actions");if(!a||!l||!u||!d)return;if(a.dataset.kind=o.kind,l.textContent=`${Js[e]}: ${o.title}`,u.textContent=o.message,c){const p=o.detail&&o.detail!==o.message?o.detail:"";c.textContent=p,c.hidden=!p}d.replaceChildren();const f=[o.canUpgrade&&{id:"upgrade",label:"View plans",variant:"primary",onClick:()=>pi()},o.canRetry&&{id:"retry",label:"Retry",variant:o.canUpgrade?"secondary":"primary",onClick:i},o.canEdit&&{id:"edit",label:"Edit prompt",variant:"secondary",onClick:el}].filter(Boolean);!o.canEdit&&!o.canRetry&&f.push({id:"edit",label:"Back to prompt",variant:"secondary",onClick:el}),f.forEach(p=>{const g=document.createElement("button");g.type="button",g.textContent=p.label,g.dataset.action=p.id,g.dataset.variant=p.variant,g.addEventListener("click",p.onClick),d.appendChild(g)}),a.hidden=!1;const h=d.querySelector("button");h&&h.focus({preventScroll:!0})}function el(){Uw(),bw(),y.isRunning=!1,Qa(!1),rn(),Xs("settled"),dn(),no(),io(),ac();const t=document.getElementById("pipeline-progress");t&&t.classList.remove("visible"),nn(!1);const e=document.getElementById("pipeline-input");e&&(y.submittedPrompt&&(e.value=y.submittedPrompt,e.dispatchEvent(new Event("input",{bubbles:!0}))),e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length))}function Pp(){const t=document.getElementById("pipeline-input");t&&y.submittedPrompt&&(t.value=y.submittedPrompt,t.dispatchEvent(new Event("input",{bubbles:!0}))),Oe=y.submittedImages.slice(),cn(),ac(),lr()}function Jw(){no(),zr=setInterval(()=>{const t=(Date.now()-Ip)/1e3,e=document.getElementById("progress-elapsed");e&&(e.textContent=`${Math.floor(t)}s`)},250)}function no(){zr&&(clearInterval(zr),zr=null)}let Yi=null;function io(){Yi&&(clearTimeout(Yi),Yi=null)}function fr(){no(),io(),Xs("settled"),Qs();const t=document.getElementById("pipeline-progress-fill");Yi=setTimeout(()=>{Yi=null;const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function Tn(t,e=""){const n={pass:'',warning:'',fail:'',info:''};return``}function Fp(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function Zw(){return S_({bundle:y.artifactBundle,reviewResult:y.step3Result})}function Xw(t){return`
      - ${$n(t.severity)} + ${Tn(t.severity)}
      ${z(t.message)}
      ${t.suggestion?`
      ${z(t.suggestion)}
      `:""} ${z(t.source)}
      - `}function Jw(t){return` + `}function Qw(t){return`
    • ${z(t.title)} ${t.detail&&t.detail!==t.title?`

      ${z(t.detail)}

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

      ${$n("warning")} Bundle

      +

      ${Tn("warning")} Bundle

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

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

      +

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

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

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

      ${z(l.reason)}

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

      ${z(l.description)}

      `:""}
    • `).join(""):'
    • No relationships for this file
    • ';return`
      - ${$n(e.status)} ${z(kp(e.status))} + ${Tn(e.status)} ${z(Fp(e.status))}

      ${z(e.artifactName)}

      ${e.description?`

      ${z(e.description)}

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

      Manual FlutterFlow steps for this file

      -
        ${e.manualSteps.map(Jw).join("")}
      +
        ${e.manualSteps.map(Qw).join("")}
      `:""}
      @@ -297,7 +297,7 @@ Error: ${g}
        ${a}
      - `}function Qw(t){const e=document.getElementById("bundle-strip"),n=document.getElementById("results-summary-tab"),i=document.getElementById("artifact-tabs"),r=document.getElementById("results-file-count");if(n){const s=y.resultsViewMode==="summary";n.classList.toggle("active",s),n.setAttribute("role","tab"),n.setAttribute("aria-selected",String(s)),n.setAttribute("aria-controls","results-summary-detail"),n.tabIndex=s?0:-1}if(i&&(i.setAttribute("role","tablist"),i.setAttribute("aria-label","Artifacts in this bundle")),!t.artifacts.length){r&&(r.textContent="0 files"),e&&e.classList.remove("visible"),i&&(i.innerHTML=""),hd();return}if(r){const s=t.artifacts.length;r.textContent=`${s} ${s===1?"file":"files"}`}i&&(i.innerHTML=t.artifacts.map(s=>{const o=y.resultsViewMode==="file"&&s.id===y.selectedArtifactId;return` + `}function nb(t){const e=document.getElementById("bundle-strip"),n=document.getElementById("results-summary-tab"),i=document.getElementById("artifact-tabs"),r=document.getElementById("results-file-count");if(n){const s=y.resultsViewMode==="summary";n.classList.toggle("active",s),n.setAttribute("role","tab"),n.setAttribute("aria-selected",String(s)),n.setAttribute("aria-controls","results-summary-detail"),n.tabIndex=s?0:-1}if(i&&(i.setAttribute("role","tablist"),i.setAttribute("aria-label","Artifacts in this bundle")),!t.artifacts.length){r&&(r.textContent="0 files"),e&&e.classList.remove("visible"),i&&(i.innerHTML=""),md();return}if(r){const s=t.artifacts.length;r.textContent=`${s} ${s===1?"file":"files"}`}i&&(i.innerHTML=t.artifacts.map(s=>{const o=y.resultsViewMode==="file"&&s.id===y.selectedArtifactId;return` - `}).join(""),i.onclick=s=>{const o=s.target.closest(".artifact-tab");o?.dataset?.artifactId&&oc(o.dataset.artifactId)},hd()),e&&e.classList.add("visible")}function hd(){const t=document.getElementById("bundle-strip");!t||t.dataset.tabKeyboard==="bound"||(t.dataset.tabKeyboard="bound",t.addEventListener("keydown",e=>{if(e.defaultPrevented)return;const n=[document.getElementById("results-summary-tab"),...Array.from(document.querySelectorAll("#artifact-tabs .artifact-tab"))].filter(Boolean);if(!n.length||!n.includes(document.activeElement))return;let i=-1;const r=n.indexOf(document.activeElement);if(e.key==="ArrowRight")i=(r+1)%n.length;else if(e.key==="ArrowLeft")i=(r-1+n.length)%n.length;else if(e.key==="Home")i=0;else if(e.key==="End")i=n.length-1;else return;e.preventDefault();const s=n[i];if(!s)return;if(s.id==="results-summary-tab")Cp();else{const a=s.dataset.artifactId;a&&oc(a)}const o=s.id==="results-summary-tab"?document.getElementById("results-summary-tab"):document.querySelector(`#artifact-tabs .artifact-tab[data-artifact-id="${s.dataset.artifactId}"]`);o&&o.focus()}))}function no(){document.body.classList.add("results-fullscreen"),document.body.classList.add("results-with-sidebar");const t=document.getElementById("results-view"),e=document.getElementById("results-code-output"),n=document.getElementById("results-audit-output"),i=document.getElementById("results-summary-detail"),r=document.getElementById("artifact-results-split"),s=Kw(),o=jl();if(i&&(i.setAttribute("role","tabpanel"),i.setAttribute("aria-labelledby","results-summary-tab")),r){r.setAttribute("role","tabpanel");const a=s?.artifacts?.find(l=>l.id===y.selectedArtifactId);r.setAttribute("aria-labelledby",a?`artifact-tab-${a.id}`:"results-summary-tab")}if(Zw(s),Qw(s),e&&(e.textContent=""),e){const a=Ph(o);e.innerHTML=a}n&&(n.innerHTML=Xw(s)),i&&i.classList.toggle("hidden",y.resultsViewMode!=="summary"),r&&r.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function dr(t,e){nn(!0),y.selectedArtifactId||(y.selectedArtifactId=ai(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const n=document.getElementById("step3-output");n&&(n.textContent=""),no(),rn(),eb()}function eb(){const t=document.getElementById("btn-feedback-up"),e=document.getElementById("btn-feedback-down"),n=document.getElementById("results-feedback-status");t&&(t.className="feedback-btn",t.setAttribute("aria-pressed","false"),t.disabled=!1,t.removeAttribute("aria-disabled")),e&&(e.className="feedback-btn",e.setAttribute("aria-pressed","false"),e.disabled=!1,e.removeAttribute("aria-disabled")),n&&(n.textContent=""),Qa=!1}function oc(t){y.selectedArtifactId=t,y.resultsViewMode="file",no()}function Cp(){y.resultsViewMode="summary",no()}function tb(){const t=document.getElementById("btn-copy-results"),e=document.getElementById("results-copy-status"),n=jl(),i=(r,s)=>{e&&(e.textContent=r,e.classList.toggle("ok",!!s),e.classList.toggle("fail",!s))};if(!navigator.clipboard?.writeText){i("Copying isn't supported in this browser.",!1);return}navigator.clipboard.writeText(n).then(()=>{if(i("Copied to clipboard",!0),t){t.classList.add("copied");const r=t.querySelector("span");if(r){const s=r.textContent;r.textContent="Copied!",setTimeout(()=>{t.classList.remove("copied"),r.textContent=s},2e3)}}}).catch(()=>{i("Clipboard permission was denied. Select the code to copy it manually.",!1)})}let Qa=!1;async function nb(t){const e=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down"),i=document.getElementById("results-feedback-status");if(!e||!n||Qa)return;const r=l=>{i&&(i.textContent="",i.offsetWidth,i.textContent=l)},s=l=>{Qa=l,[e,n].forEach(u=>{u.disabled=l,u.setAttribute("aria-disabled",String(l))})},o=t==="up"?"thumbsUp":"thumbsDown";s(!0),r("Submitting review feedback…");const a={type:o,code:y.step2Result,input:y.step1Result};try{const l=await Yl(a.type,a.code,a.input);if(!l||l.success!==!0){s(!1),r("Review feedback could not be sent. Tap again to retry.");return}e.classList.toggle("active-up",t==="up"),n.classList.toggle("active-down",t==="down"),e.setAttribute("aria-pressed",String(t==="up")),n.setAttribute("aria-pressed",String(t==="down")),s(!1),r("Review feedback saved.")}catch{s(!1),r("Review feedback could not be sent. Tap again to retry.")}}function ib(){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 Ap(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}function nn(t){const e=document.getElementById("generation-stage");e&&(t?(e.hidden=!1,e.inert=!1,requestAnimationFrame(()=>e.classList.add("is-active"))):(e.classList.remove("is-active"),e.inert=!0,setTimeout(()=>{e.classList.contains("is-active")||(e.hidden=!0)},260)))}function Pp(){const t=q.isVerified&&!!q.email,e=ce.tier||"free",n=t&&gi(),i=!t||Tt(),s=n?"Checking…":i?_l[e]||"Free":"—",o=document.getElementById("topbar-plan");o&&(o.textContent=s);const a=document.getElementById("topbar-avatar");a&&(a.textContent=(q.email||"?")[0].toUpperCase()),Zl();const l=document.getElementById("plans-free-current");l&&l.classList.toggle("hidden",e!=="free"||!i);const u=document.getElementById("plans-checkout-btn-professional");if(u){const d=e==="professional"&&i;u.disabled=d,u.textContent=d?"Current plan":"Subscribe"}const c=document.getElementById("plans-checkout-btn-power");if(c){const d=e==="power"&&i;c.disabled=d,c.textContent=d?"Current plan":"Subscribe"}}function rb(){Pp();const t=document.getElementById("credits-modal");t&&We(t)}function sb(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("credits-modal");e&&ze(e)}function Fp(t,e=!0,n=!0){if(t=["home","account","plans"].includes(t)?t:"home",document.querySelectorAll(".view[data-view]").forEach(r=>{r.dataset.view===t?(r.hidden=!1,r.removeAttribute("inert"),requestAnimationFrame(()=>{r.classList.add("is-active"),n&&r.focus({preventScroll:!0})})):(r.classList.remove("is-active"),r.setAttribute("inert","true"),setTimeout(()=>{r.classList.contains("is-active")||(r.hidden=!0)},260))}),t!=="home")nn(!1);else{const r=document.getElementById("main-stage-container");r&&r.classList.contains("visible")&&nn(!0)}if(document.querySelectorAll(".nav-link[data-view]").forEach(r=>{const s=r.dataset.view===t;r.setAttribute("aria-current",s?"page":null),s||r.removeAttribute("aria-current")}),e){const r=t==="home"?"":`#${t}`;window.location.hash!==r&&window.history.pushState({view:t},"",r||"#")}}let pd=!1;function ac(){const t=window.location.hash.replace(/^#/,"");Fp(t||"home",!1,pd),pd=!0}window.addEventListener("popstate",t=>{ac()});window.addEventListener("hashchange",()=>{ac()});window.copyResultsCode=tb;window.selectArtifact=oc;window.selectResultsSummary=Cp;window.submitResultsFeedback=nb;window.showErrorInputPanel=ib;window.hideErrorInputPanel=Ap;window.setGenerationStageVisible=nn;window.switchView=Fp;window.selectPipelineStage=jw;window.editPipelinePrompt=Xa;window.retryPipelineRun=Ip;window.openCreditsModal=rb;window.closeCreditsModal=sb; + `}).join(""),i.onclick=s=>{const o=s.target.closest(".artifact-tab");o?.dataset?.artifactId&&lc(o.dataset.artifactId)},md()),e&&e.classList.add("visible")}function md(){const t=document.getElementById("bundle-strip");!t||t.dataset.tabKeyboard==="bound"||(t.dataset.tabKeyboard="bound",t.addEventListener("keydown",e=>{if(e.defaultPrevented)return;const n=[document.getElementById("results-summary-tab"),...Array.from(document.querySelectorAll("#artifact-tabs .artifact-tab"))].filter(Boolean);if(!n.length||!n.includes(document.activeElement))return;let i=-1;const r=n.indexOf(document.activeElement);if(e.key==="ArrowRight")i=(r+1)%n.length;else if(e.key==="ArrowLeft")i=(r-1+n.length)%n.length;else if(e.key==="Home")i=0;else if(e.key==="End")i=n.length-1;else return;e.preventDefault();const s=n[i];if(!s)return;if(s.id==="results-summary-tab")Rp();else{const a=s.dataset.artifactId;a&&lc(a)}const o=s.id==="results-summary-tab"?document.getElementById("results-summary-tab"):document.querySelector(`#artifact-tabs .artifact-tab[data-artifact-id="${s.dataset.artifactId}"]`);o&&o.focus()}))}function ro(){document.body.classList.add("results-fullscreen"),document.body.classList.add("results-with-sidebar");const t=document.getElementById("results-view"),e=document.getElementById("results-code-output"),n=document.getElementById("results-audit-output"),i=document.getElementById("results-summary-detail"),r=document.getElementById("artifact-results-split"),s=Zw(),o=Hl();if(i&&(i.setAttribute("role","tabpanel"),i.setAttribute("aria-labelledby","results-summary-tab")),r){r.setAttribute("role","tabpanel");const a=s?.artifacts?.find(l=>l.id===y.selectedArtifactId);r.setAttribute("aria-labelledby",a?`artifact-tab-${a.id}`:"results-summary-tab")}if(eb(s),nb(s),e&&(e.textContent=""),e){const a=$h(o);e.innerHTML=a}n&&(n.innerHTML=tb(s)),i&&i.classList.toggle("hidden",y.resultsViewMode!=="summary"),r&&r.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function hr(t,e){nn(!0),y.selectedArtifactId||(y.selectedArtifactId=li(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const n=document.getElementById("step3-output");n&&(n.textContent=""),ro(),rn(),ib()}function ib(){const t=document.getElementById("btn-feedback-up"),e=document.getElementById("btn-feedback-down"),n=document.getElementById("results-feedback-status");t&&(t.className="feedback-btn",t.setAttribute("aria-pressed","false"),t.disabled=!1,t.removeAttribute("aria-disabled")),e&&(e.className="feedback-btn",e.setAttribute("aria-pressed","false"),e.disabled=!1,e.removeAttribute("aria-disabled")),n&&(n.textContent=""),tl=!1}function lc(t){y.selectedArtifactId=t,y.resultsViewMode="file",ro()}function Rp(){y.resultsViewMode="summary",ro()}function rb(){const t=document.getElementById("btn-copy-results"),e=document.getElementById("results-copy-status"),n=Hl(),i=(r,s)=>{e&&(e.textContent=r,e.classList.toggle("ok",!!s),e.classList.toggle("fail",!s))};if(!navigator.clipboard?.writeText){i("Copying isn't supported in this browser.",!1);return}navigator.clipboard.writeText(n).then(()=>{if(i("Copied to clipboard",!0),t){t.classList.add("copied");const r=t.querySelector("span");if(r){const s=r.textContent;r.textContent="Copied!",setTimeout(()=>{t.classList.remove("copied"),r.textContent=s},2e3)}}}).catch(()=>{i("Clipboard permission was denied. Select the code to copy it manually.",!1)})}let tl=!1;async function sb(t){const e=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down"),i=document.getElementById("results-feedback-status");if(!e||!n||tl)return;const r=l=>{i&&(i.textContent="",i.offsetWidth,i.textContent=l)},s=l=>{tl=l,[e,n].forEach(u=>{u.disabled=l,u.setAttribute("aria-disabled",String(l))})},o=t==="up"?"thumbsUp":"thumbsDown";s(!0),r("Submitting review feedback…");const a={type:o,code:y.step2Result,input:y.step1Result};try{const l=await Zl(a.type,a.code,a.input);if(!l||l.success!==!0){s(!1),r("Review feedback could not be sent. Tap again to retry.");return}e.classList.toggle("active-up",t==="up"),n.classList.toggle("active-down",t==="down"),e.setAttribute("aria-pressed",String(t==="up")),n.setAttribute("aria-pressed",String(t==="down")),s(!1),r("Review feedback saved.")}catch{s(!1),r("Review feedback could not be sent. Tap again to retry.")}}function ob(){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 Tp(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}function nn(t){const e=document.getElementById("generation-stage");e&&(t?(e.hidden=!1,e.inert=!1,requestAnimationFrame(()=>e.classList.add("is-active"))):(e.classList.remove("is-active"),e.inert=!0,setTimeout(()=>{e.classList.contains("is-active")||(e.hidden=!0)},260)))}function $p(){const t=q.isVerified&&!!q.email,e=ce.tier||"free",n=t&&vi(),i=!t||Tt(),s=n?"Checking…":i?wl[e]||"Free":"—",o=document.getElementById("topbar-plan");o&&(o.textContent=s);const a=document.getElementById("topbar-avatar");a&&(a.textContent=(q.email||"?")[0].toUpperCase()),Ql();const l=document.getElementById("plans-free-current");l&&l.classList.toggle("hidden",e!=="free"||!i);const u=document.getElementById("plans-checkout-btn-professional");if(u){const d=e==="professional"&&i;u.disabled=d,u.textContent=d?"Current plan":"Subscribe"}const c=document.getElementById("plans-checkout-btn-power");if(c){const d=e==="power"&&i;c.disabled=d,c.textContent=d?"Current plan":"Subscribe"}}function ab(){$p();const t=document.getElementById("credits-modal");t&&We(t)}function lb(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("credits-modal");e&&ze(e)}function Mp(t,e=!0,n=!0){if(t=["home","account","plans"].includes(t)?t:"home",document.querySelectorAll(".view[data-view]").forEach(r=>{r.dataset.view===t?(r.hidden=!1,r.removeAttribute("inert"),requestAnimationFrame(()=>{r.classList.add("is-active"),n&&r.focus({preventScroll:!0})})):(r.classList.remove("is-active"),r.setAttribute("inert","true"),setTimeout(()=>{r.classList.contains("is-active")||(r.hidden=!0)},260))}),t!=="home")nn(!1);else{const r=document.getElementById("main-stage-container");r&&r.classList.contains("visible")&&nn(!0)}if(document.querySelectorAll(".nav-link[data-view]").forEach(r=>{const s=r.dataset.view===t;r.setAttribute("aria-current",s?"page":null),s||r.removeAttribute("aria-current")}),e){const r=t==="home"?"":`#${t}`;window.location.hash!==r&&window.history.pushState({view:t},"",r||"#")}}let vd=!1;function cc(){const t=window.location.hash.replace(/^#/,"");Mp(t||"home",!1,vd),vd=!0}window.addEventListener("popstate",t=>{cc()});window.addEventListener("hashchange",()=>{cc()});window.copyResultsCode=rb;window.selectArtifact=lc;window.selectResultsSummary=Rp;window.submitResultsFeedback=sb;window.showErrorInputPanel=ob;window.hideErrorInputPanel=Tp;window.setGenerationStageVisible=nn;window.switchView=Mp;window.selectPipelineStage=Ww;window.editPipelinePrompt=el;window.retryPipelineRun=Pp;window.openCreditsModal=ab;window.closeCreditsModal=lb; diff --git a/dist/index.html b/dist/index.html index db71103..99a225c 100644 --- a/dist/index.html +++ b/dist/index.html @@ -3313,7 +3313,7 @@ .send.is-busy .send-spin { animation: none; opacity: 0.6; } } - + diff --git a/e2e/stu380-deploy.spec.js b/e2e/stu380-deploy.spec.js index eabcef3..403dd54 100644 --- a/e2e/stu380-deploy.spec.js +++ b/e2e/stu380-deploy.spec.js @@ -1184,4 +1184,154 @@ test.describe("STU-380 transport outcome regressions", () => { await page.evaluate(() => window.__CCC_RESOLVE_PROJECT_PUBSPEC__({})); expect(exportCalls).toBe(4); }); + + test("an identical retry's success cannot retire the earlier uncertain write", async ({ page }) => { + await loadDeployHooks(page); + + const gaugeX = "class GaugeModel { final int value; GaugeModel(this.value); }"; + const zip = new JSZip(); + zip.file( + "pubspec.yaml", + "name: my_app\n\ndependencies:\n flutter:\n sdk: flutter\n", + ); + const zipEmpty = await zip.generateAsync({ type: "base64" }); + zip.file("lib/custom_code/gauge_model.dart", gaugeX); + const zipX = await zip.generateAsync({ type: "base64" }); + + let landed = false; + let exportCalls = 0; + await page.route("**/exportCode", async (route) => { + exportCalls += 1; + await route.fulfill({ + status: 200, + contentType: "application/json", + body: JSON.stringify({ + value: { project_zip: landed ? zipX : zipEmpty }, + }), + }); + }); + // First provision hangs past the bound; the retry answers success. + await page.evaluate(() => { + const realFetch = window.fetch; + let provisionCalls = 0; + window.fetch = (url, ...args) => { + if (String(url).includes("deployCustomClasses")) { + provisionCalls += 1; + if (provisionCalls === 1) { + return Promise.resolve( + new Response(new ReadableStream({ start() {} }), { + status: 200, + headers: { "Content-Type": "application/x-ndjson" }, + }), + ); + } + return Promise.resolve( + new Response('{"event":"result","success":true}\n', { + status: 200, + headers: { "Content-Type": "application/x-ndjson" }, + }), + ); + } + return realFetch(url, ...args); + }; + }); + + await page.evaluate(() => window.__CCC_RESOLVE_PROJECT_PUBSPEC__({})); + expect(exportCalls).toBe(1); + + const outcomeA = await settleAsOutcome( + page, + "__CCC_PROVISION_CUSTOM_CLASSES__", + [{ fileMap: newClassFileMap, uiTimeoutMs: 60 }], + ); + expect(outcomeA.name).toBe("UnconfirmedDeployError"); + + // Identical retry succeeds — it credits one verified write of X, but A's + // uncertain write is a separate attempt and must stay outstanding. + const outcomeB = await settleAsOutcome( + page, + "__CCC_PROVISION_CUSTOM_CLASSES__", + [{ fileMap: newClassFileMap, remoteFiles: {} }], + ); + expect(outcomeB.settled).toBe("resolved"); + + // First X-sighting is attributable to the verified retry — A's write can + // still be in flight, so the snapshot must not cache. + landed = true; + await page.evaluate(() => window.__CCC_RESOLVE_PROJECT_PUBSPEC__({})); + expect(exportCalls).toBe(2); + await page.evaluate(() => window.__CCC_RESOLVE_PROJECT_PUBSPEC__({})); + // Second sighting has no verified credit left — it retires A's write and + // this export becomes the cached snapshot. + expect(exportCalls).toBe(3); + await page.evaluate(() => window.__CCC_RESOLVE_PROJECT_PUBSPEC__({})); + expect(exportCalls).toBe(3); + }); + + test("a push still in flight keeps exports uncached until it settles", async ({ page }) => { + await loadDeployHooks(page); + + const zip = new JSZip(); + zip.file( + "pubspec.yaml", + "name: my_app\n\ndependencies:\n flutter:\n sdk: flutter\n", + ); + const projectZip = await zip.generateAsync({ type: "base64" }); + + let exportCalls = 0; + await page.route("**/exportCode", async (route) => { + exportCalls += 1; + await route.fulfill({ + status: 200, + contentType: "application/json", + body: JSON.stringify({ value: { project_zip: projectZip } }), + }); + }); + // The push hangs past the UI bound; the test releases it afterwards. + await page.evaluate(() => { + const realFetch = window.fetch; + window.__CCC_PUSH_RELEASE__ = null; + window.fetch = (url, ...args) => { + if (String(url).includes("syncCustomCodeChanges")) { + return new Promise((resolve) => { + window.__CCC_PUSH_RELEASE__ = () => + resolve(new Response('{"success":true}', { status: 200 })); + }); + } + return realFetch(url, ...args); + }; + }); + + await page.evaluate(() => window.__CCC_RESOLVE_PROJECT_PUBSPEC__({})); + expect(exportCalls).toBe(1); + + const outcome = await page.evaluate(async () => { + try { + await window.__CCC_PUSH_CODE_WITH_TIMEOUT__( + { project_id: "ff-proj-0007", zipped_custom_code: "eA==" }, + 60, + ); + return { settled: "resolved" }; + } catch (error) { + return { settled: "rejected", name: error.name }; + } + }); + expect(outcome.name).toBe("UnconfirmedDeployError"); + + // While the push is still in flight its writes can land at any moment — + // exports must not be cached. + await page.evaluate(() => window.__CCC_RESOLVE_PROJECT_PUBSPEC__({})); + expect(exportCalls).toBe(2); + await page.evaluate(() => window.__CCC_RESOLVE_PROJECT_PUBSPEC__({})); + expect(exportCalls).toBe(3); + + // Once the request settles, no write can arrive later — the next export + // is authoritative and caches again. + await page.evaluate(() => window.__CCC_PUSH_RELEASE__()); + await page.waitForTimeout(50); + await page.evaluate(() => window.__CCC_RESOLVE_PROJECT_PUBSPEC__({})); + expect(exportCalls).toBe(4); + await page.evaluate(() => window.__CCC_RESOLVE_PROJECT_PUBSPEC__({})); + expect(exportCalls).toBe(4); + }); });